@inversealtruism/cairnx-core 0.2.7 → 0.2.9

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.d.ts CHANGED
@@ -473,6 +473,15 @@ interface BidState {
473
473
  /** offers anchored in response (tagged with this bid's id), in apply order */
474
474
  offers: string[];
475
475
  }
476
+ /** One token movement of an applied record (CONVENTION §41): `amount` base units of `ticker` from `from` (null for a mint)
477
+ * to `to`, written by the line that applies it. `amount` is a positive decimal string, the form of the state's balances. */
478
+ interface TokenMove {
479
+ leg: "xfer" | "mint" | "fill" | "sale" | "fee";
480
+ ticker: string;
481
+ from: string | null;
482
+ to: string;
483
+ amount: string;
484
+ }
476
485
  interface AppliedEvent {
477
486
  height: number;
478
487
  pos: number;
@@ -483,6 +492,9 @@ interface AppliedEvent {
483
492
  * a log built by hand or by a core before 0.2.6 has none. */
484
493
  code?: ReasonCode;
485
494
  note?: string;
495
+ /** The token moves of an applied record that moved tokens, in the order applied (CONVENTION §41); absent on every other
496
+ * entry and in a log from a core before 0.2.8. Outside canonical state, like the rest of the log. */
497
+ moves?: TokenMove[];
486
498
  }
487
499
  interface CairnXState {
488
500
  tipHeight: number;
@@ -592,9 +604,9 @@ declare function eventId(e: ChainEvent): string;
592
604
  * Outside that domain the result is unspecified: a NaN key compares as equal. */
593
605
  declare function applyOrder(a: ChainEvent, b: ChainEvent): number;
594
606
  declare function resolve(events: ChainEvent[], tipHeight: number): CairnXState;
595
- /** Canonical serialization of state (FORMAT 2) — byte-identical across honest resolvers.
607
+ /** Canonical serialization of state (FORMAT 2): byte-identical across honest resolvers.
596
608
  * The canonical surface is the DATA ONLY: {tipHeight, tokens, balances, names, offers, bids,
597
- * feesPaid}. The applied-event log is deliberately EXCLUDED — its free-text reason strings are
609
+ * feesPaid}. The applied-event log is deliberately EXCLUDED: its free-text reason strings are
598
610
  * implementation diagnostics, and making them normative would force every third-party resolver
599
611
  * to reproduce English prose byte-for-byte. (Format 1, pre-2026-06-12, included the log and
600
612
  * sorted with localeCompare; pinned format-1 hashes live in test/vectors/replay-hashes.json
@@ -818,6 +830,68 @@ declare const primaryRankBefore: (a: NameState, b: NameState) => boolean;
818
830
  /** The primary .csd name for address `a`, or null. Pure; no I/O. `a` may be any case. */
819
831
  declare function pickPrimaryName(names: Iterable<NameState>, a: string): string | null;
820
832
 
833
+ /** Where a payment to `name` goes: its `nset` address, else its owner. `lapsed` is the name's `expired` (§17): the
834
+ * address is the record's, and a sender refuses it. */
835
+ interface ResolvedName {
836
+ name: string;
837
+ addr: string;
838
+ via: "nset" | "owner";
839
+ lapsed: boolean;
840
+ owner: string;
841
+ }
842
+ /** The address `name` receives at in `names`, or null when `names` holds no such own key or holds a pending reservation
843
+ * (§28), which confers no address. The key is looked up as given: a caller normalizes its input first. */
844
+ declare function resolveNameIn(names: Record<string, NameState>, name: string): ResolvedName | null;
845
+ /** The classes of `nameView`: `free` is a name absent from `names`; `reserved` one in RESERVED_NAMES, whose record does
846
+ * not parse (§9), so it is never in `names`. */
847
+ type NameViewState = "held" | "pending" | "lapsed" | "free" | "reserved";
848
+ /** A name as a reader shows it. `addr` and `profile` are a held name's only: a pending or lapsed name gives no address,
849
+ * and its profile is not the word of a current owner (§35.3). `owner` is the reserver of a pending name and the last
850
+ * owner of a lapsed one. `paidThroughEpoch` is null where the state carries none (a pending name, a tip below V15). */
851
+ interface NameView {
852
+ name: string;
853
+ state: NameViewState;
854
+ owner: string | null;
855
+ addr: string | null;
856
+ profile: Record<string, string>;
857
+ paidThroughEpoch: number | null;
858
+ }
859
+ /** The view of `name` in `names`, or null when `name` does not match NAME_RE. Built on resolveNameIn: a held name's
860
+ * `addr` is its address. */
861
+ declare function nameView(names: Record<string, NameState>, name: string): NameView | null;
862
+
863
+ /** This package's version, for a host that names the core it loaded (cairnx-api's `rev`, a replica's report). Equal to
864
+ * package.json's version (test/version.test.ts). */
865
+ declare const CAIRNX_CORE_VERSION = "0.2.9";
866
+
867
+ /** Gate name to height: `ACTIVATION_HEIGHT` and each `V<n>_HEIGHT`, frozen. test/gates.test.ts keeps it equal to the
868
+ * individual exports and complete. It leaves out the one other exported height, `LEGACY_HOLD_SUNSET_HEIGHT`, which is
869
+ * derived from `V28_HEIGHT` and the claim window and grace, and which no replay rule reads. Two equal tables show
870
+ * equal gate heights, not equal rules: no fee, window or reserved-name constant is in the table. */
871
+ declare const GATE_HEIGHTS: Readonly<{
872
+ ACTIVATION_HEIGHT: 29860;
873
+ V11_HEIGHT: 29960;
874
+ V12_HEIGHT: 30300;
875
+ V13_HEIGHT: 31100;
876
+ V14_HEIGHT: 31400;
877
+ V15_HEIGHT: 32000;
878
+ V16_HEIGHT: 33600;
879
+ V17_HEIGHT: 34000;
880
+ V18_HEIGHT: 40000;
881
+ V19_HEIGHT: 36700;
882
+ V20_HEIGHT: 38400;
883
+ V21_HEIGHT: 40100;
884
+ V22_HEIGHT: 41300;
885
+ V23_HEIGHT: 52000;
886
+ V24_HEIGHT: 46400;
887
+ V25_HEIGHT: 46440;
888
+ V26_HEIGHT: 46480;
889
+ V27_HEIGHT: 46520;
890
+ V28_HEIGHT: 60000;
891
+ V29_HEIGHT: 88000;
892
+ }>;
893
+ type GateName = keyof typeof GATE_HEIGHTS;
894
+
821
895
  declare const FCLAIM_MAX_HOLD_SPAN: number;
822
896
  declare const GAP_NEEDED: number;
823
897
  declare const SCAN_MARGIN = 30;
@@ -1118,4 +1192,4 @@ interface ProvenOfferTx {
1118
1192
  * rules; the resolver writes no note below activation), or null when it passes. */
1119
1193
  declare function provenOfferRefusal(rec: OfferRecord, tx: ProvenOfferTx): string | null;
1120
1194
 
1121
- export { ACTIVATION_HEIGHT, ADDR_RE, AMOUNT_RE, type AppliedCode, type AppliedEvent, type AttestEvent, BID_KEYS, type BalanceState, type BidRecord, type BidState, type BidStatus, type BindTermsOpts, type BuiltRecord, CAIRNX_EVENT_RULE, CAP_CODES, CLAIM_ATTACKER_Q, CLAIM_COOLDOWN_BLOCKS, CLAIM_FILL_GRACE_BLOCKS, CLAIM_MIN_DEPTH, CLAIM_WINDOW_BLOCKS, CLAIM_WINDOW_BLOCKS_V20, COMMIT_MAX_BLOCKS, COMMIT_REVEAL_MIN_DEPTH, CONF_TOKEN_FILL, type CairnXRecord, type CairnXState, type ChainEvent, DEPLOY_FEE, DEPLOY_KEYS, DOMAIN, type DeployRecord, EVENTS_HASH_START, type EventMember, type EventRule, type EventRuleTx, type EventsSoFar, FCLAIM_KEYS, FCLAIM_MAX_EPOCH_AHEAD, FCLAIM_MAX_HOLD_SPAN, FCLAIM_WINDOW_MIN, FEE_BPS, FEE_BPS_V16, FEE_GATE_MARGIN_BLOCKS, FILL_TIP_MARGIN, FINALIZE_TIP_MARGIN, FINAL_DEPTH, type FclaimRecord, type FillEndorsement, type FillEntry, type FillOutputPlan, type FillPreview, type FillSafety, type FillSpvIo, type FillVerdict, GAP_NEEDED, type Give, HASH_RE, type HashedEvent, type HoldCandidate, type HoldCount, type HoldReplay, type HoldTarget, LEGACY_HOLD_SUNSET_HEIGHT, type LegacyBindOpts, MAX_ACTIVE_CLAIMS, MAX_AMOUNT, MAX_OFFER_EPOCHS, MAX_PENDING_REG, MAX_RECORD_BYTES, MAX_SCAN, MAX_TOKEN_DECIMALS, MINT_KEYS, type MintRecord, type MintedProvenOfferTerms, NAME_FEE_LEN3_V24, NAME_FEE_LEN4_V24, NAME_FEE_LONG_V24, NAME_FEE_MID_V24, NAME_FEE_SHORT_V18, NAME_FEE_V18, NAME_GRACE_EPOCHS, NAME_KEYS, NAME_PREMIUM_DECAY_EPOCHS, NAME_PREMIUM_START, NAME_RE, NAME_TERM_EPOCHS, NFINALIZE_KEYS, NPROFILE_KEYS, type NameCommitRecord, type NameFinalizeRecord, type NameProfileRecord, type NameRecord, type NameRenewRecord, type NameSetRecord, type NameState, type NameXferRecord, OFFER_KEYS, type OfferCancelAllRecord, type OfferRecord, type OfferState, type OfferStatus, PKEY, PROFILE_MAX_KEYS, PROFILE_MAX_VALUE_BYTES, type ProposeEvent, type ProvenAttest, type ProvenEvent, type ProvenOfferTerms, type ProvenOfferTx, type ProvenPropose, REASON_CODES, REASON_CODE_OUTCOME, REBATE_BPS, REBATE_FLAT, REG_COMMIT_MAX_BLOCKS, REG_FINALIZE_GRACE_BLOCKS, RESERVED_NAMES, type ReasonCode, type RecordCode, RecordError, type RefusalCode, SALT_RE, SCAN_MARGIN, SCORE_CANCEL, SCORE_CLAIM, SCORE_FILL, TICKER_RE, TRANSFER_KEYS, TREASURY_ADDR, type TokenMetaRecord, type TokenState, type TransferRecord, V11_HEIGHT, V12_HEIGHT, V13_HEIGHT, V14_HEIGHT, V15_HEIGHT, V16_HEIGHT, V17_HEIGHT, V18_HEIGHT, V19_HEIGHT, V20_HEIGHT, V21_HEIGHT, V22_HEIGHT, V23_HEIGHT, V24_HEIGHT, V25_HEIGHT, V26_HEIGHT, V27_HEIGHT, V28_HEIGHT, V29_HEIGHT, type Want, ZERO_ADDR, applyOrder, beforeActivation, bid, bindOfferTerms, bindProvenOffer, blockEvents, blockMembers, buildFeeHeight, buildRecord, burnedPayment, canonicalState, claimGraceOf, claimWindowAt, claimWindowOf, countOtherHoldsAtGrant, deploy, eventId, eventOfTx, eventsHash, eventsHashStep, expiredClaimFee, explainRecord, fclaim, fclaimEpochFor, fclaimHoldEnd, feeBpsAt, fillEndorsement, fillIsSafe, fillOutputPlan, fillTargetId, finalizeWinnerCheck, hasLiveClaim, isName, isNameGive, isOpenClaimLane, isTokenWant, makerRebate, mint, myProvenFillClosedOffer, nameClaim, nameCommit, nameCommitRecord, nameFinalize, nameProfile, nameRegFee, nameRenew, nameSet, nameXfer, offer, offerCancelAll, offerExpiryHeightOf, offerFillTooLate, paidToFromOutputs, parseAmount, parseRecord, pickPrimaryName, previewFill, primaryRankBefore, provenOfferRefusal, provenOfferTerms, ptAmt, replayLiveHold, requiredClaimDepth, requiredFillOutputs, resolve, stateHash, tokenMeta, tradeFee, transfer, unsafeMintProvenOfferTerms, verifyFillSpv };
1195
+ export { ACTIVATION_HEIGHT, ADDR_RE, AMOUNT_RE, type AppliedCode, type AppliedEvent, type AttestEvent, BID_KEYS, type BalanceState, type BidRecord, type BidState, type BidStatus, type BindTermsOpts, type BuiltRecord, CAIRNX_CORE_VERSION, CAIRNX_EVENT_RULE, CAP_CODES, CLAIM_ATTACKER_Q, CLAIM_COOLDOWN_BLOCKS, CLAIM_FILL_GRACE_BLOCKS, CLAIM_MIN_DEPTH, CLAIM_WINDOW_BLOCKS, CLAIM_WINDOW_BLOCKS_V20, COMMIT_MAX_BLOCKS, COMMIT_REVEAL_MIN_DEPTH, CONF_TOKEN_FILL, type CairnXRecord, type CairnXState, type ChainEvent, DEPLOY_FEE, DEPLOY_KEYS, DOMAIN, type DeployRecord, EVENTS_HASH_START, type EventMember, type EventRule, type EventRuleTx, type EventsSoFar, FCLAIM_KEYS, FCLAIM_MAX_EPOCH_AHEAD, FCLAIM_MAX_HOLD_SPAN, FCLAIM_WINDOW_MIN, FEE_BPS, FEE_BPS_V16, FEE_GATE_MARGIN_BLOCKS, FILL_TIP_MARGIN, FINALIZE_TIP_MARGIN, FINAL_DEPTH, type FclaimRecord, type FillEndorsement, type FillEntry, type FillOutputPlan, type FillPreview, type FillSafety, type FillSpvIo, type FillVerdict, GAP_NEEDED, GATE_HEIGHTS, type GateName, type Give, HASH_RE, type HashedEvent, type HoldCandidate, type HoldCount, type HoldReplay, type HoldTarget, LEGACY_HOLD_SUNSET_HEIGHT, type LegacyBindOpts, MAX_ACTIVE_CLAIMS, MAX_AMOUNT, MAX_OFFER_EPOCHS, MAX_PENDING_REG, MAX_RECORD_BYTES, MAX_SCAN, MAX_TOKEN_DECIMALS, MINT_KEYS, type MintRecord, type MintedProvenOfferTerms, NAME_FEE_LEN3_V24, NAME_FEE_LEN4_V24, NAME_FEE_LONG_V24, NAME_FEE_MID_V24, NAME_FEE_SHORT_V18, NAME_FEE_V18, NAME_GRACE_EPOCHS, NAME_KEYS, NAME_PREMIUM_DECAY_EPOCHS, NAME_PREMIUM_START, NAME_RE, NAME_TERM_EPOCHS, NFINALIZE_KEYS, NPROFILE_KEYS, type NameCommitRecord, type NameFinalizeRecord, type NameProfileRecord, type NameRecord, type NameRenewRecord, type NameSetRecord, type NameState, type NameView, type NameViewState, type NameXferRecord, OFFER_KEYS, type OfferCancelAllRecord, type OfferRecord, type OfferState, type OfferStatus, PKEY, PROFILE_MAX_KEYS, PROFILE_MAX_VALUE_BYTES, type ProposeEvent, type ProvenAttest, type ProvenEvent, type ProvenOfferTerms, type ProvenOfferTx, type ProvenPropose, REASON_CODES, REASON_CODE_OUTCOME, REBATE_BPS, REBATE_FLAT, REG_COMMIT_MAX_BLOCKS, REG_FINALIZE_GRACE_BLOCKS, RESERVED_NAMES, type ReasonCode, type RecordCode, RecordError, type RefusalCode, type ResolvedName, SALT_RE, SCAN_MARGIN, SCORE_CANCEL, SCORE_CLAIM, SCORE_FILL, TICKER_RE, TRANSFER_KEYS, TREASURY_ADDR, type TokenMetaRecord, type TokenMove, type TokenState, type TransferRecord, V11_HEIGHT, V12_HEIGHT, V13_HEIGHT, V14_HEIGHT, V15_HEIGHT, V16_HEIGHT, V17_HEIGHT, V18_HEIGHT, V19_HEIGHT, V20_HEIGHT, V21_HEIGHT, V22_HEIGHT, V23_HEIGHT, V24_HEIGHT, V25_HEIGHT, V26_HEIGHT, V27_HEIGHT, V28_HEIGHT, V29_HEIGHT, type Want, ZERO_ADDR, applyOrder, beforeActivation, bid, bindOfferTerms, bindProvenOffer, blockEvents, blockMembers, buildFeeHeight, buildRecord, burnedPayment, canonicalState, claimGraceOf, claimWindowAt, claimWindowOf, countOtherHoldsAtGrant, deploy, eventId, eventOfTx, eventsHash, eventsHashStep, expiredClaimFee, explainRecord, fclaim, fclaimEpochFor, fclaimHoldEnd, feeBpsAt, fillEndorsement, fillIsSafe, fillOutputPlan, fillTargetId, finalizeWinnerCheck, hasLiveClaim, isName, isNameGive, isOpenClaimLane, isTokenWant, makerRebate, mint, myProvenFillClosedOffer, nameClaim, nameCommit, nameCommitRecord, nameFinalize, nameProfile, nameRegFee, nameRenew, nameSet, nameView, nameXfer, offer, offerCancelAll, offerExpiryHeightOf, offerFillTooLate, paidToFromOutputs, parseAmount, parseRecord, pickPrimaryName, previewFill, primaryRankBefore, provenOfferRefusal, provenOfferTerms, ptAmt, replayLiveHold, requiredClaimDepth, requiredFillOutputs, resolve, resolveNameIn, stateHash, tokenMeta, tradeFee, transfer, unsafeMintProvenOfferTerms, verifyFillSpv };
package/dist/index.js CHANGED
@@ -377,6 +377,7 @@ var fclaim = (r) => buildRecord({ v: 1, t: "fclaim", ...r });
377
377
  function ptAmt(v) {
378
378
  return typeof v === "string" && AMOUNT_RE.test(v) ? BigInt(v) : 0n;
379
379
  }
380
+ var tokenMove = (leg, ticker, from, to, amount) => ({ leg, ticker, from, to, amount: amount.toString() });
380
381
  var effExpiry = (e, height) => e.height >= V22_HEIGHT ? e.expiresEpoch : height >= V21_HEIGHT ? Math.min(e.expiresEpoch, epochOf(e.height) + MAX_OFFER_EPOCHS) : e.expiresEpoch;
381
382
  var claimGrace = (o) => o.claimUntilHeight !== void 0 ? claimGraceOf(o.claimUntilHeight, o.claimTxid) : 0;
382
383
  var claimHeld = (o, height) => o.claimedBy !== void 0 && o.claimUntilHeight !== void 0 && height < o.claimUntilHeight + claimGrace(o);
@@ -429,9 +430,13 @@ function createContext(store) {
429
430
  bal(t, o.seller).locked -= amt;
430
431
  bal(t, who).available += amt;
431
432
  offerLock.delete(o.id);
433
+ return tokenMove("fill", t, o.seller, who, amt);
432
434
  };
433
- const entry = (e, id, kind, ok, code, why) => log.push({ height: e.height, pos: e.pos, id, kind, ok, code, ...why ? { note: why } : {} });
434
- const applied = (e, id, kind, code, why) => entry(e, id, kind, true, code, why);
435
+ const entry = (e, id, kind, ok, code, why, moves) => {
436
+ const written = moves?.filter((m) => m.amount !== "0") ?? [];
437
+ log.push({ height: e.height, pos: e.pos, id, kind, ok, code, ...why ? { note: why } : {}, ...written.length ? { moves: written } : {} });
438
+ };
439
+ const applied = (e, id, kind, code, why, moves) => entry(e, id, kind, true, code, why, moves);
435
440
  const refused = (e, id, kind, code, why) => entry(e, id, kind, false, code, why);
436
441
  return {
437
442
  tokens,
@@ -594,13 +599,17 @@ function applyTokenFill(c, ev, o, who) {
594
599
  }
595
600
  buyer.available -= amt + fee;
596
601
  bal(o.want.ticker, o.want.payto).available += amt;
597
- if (fee > 0n) bal(o.want.ticker, TREASURY_ADDR).available += fee;
602
+ const moves = [tokenMove("sale", o.want.ticker, who, o.want.payto, amt)];
603
+ if (fee > 0n) {
604
+ bal(o.want.ticker, TREASURY_ADDR).available += fee;
605
+ moves.push(tokenMove("fee", o.want.ticker, who, TREASURY_ADDR, fee));
606
+ }
598
607
  if (isNameGive(o.give)) deliverNameToBuyer(c, o.give.name, giveName, who, ev);
599
- else releaseGiveLock(o, who, giveLock);
608
+ else moves.push(releaseGiveLock(o, who, giveLock));
600
609
  setOfferStatus(o, "filled");
601
610
  o.fill = { buyer: who, txid: ev.txid, height: ev.height, paid: amt.toString(), fee: fee.toString() };
602
611
  markBidDone(o, who);
603
- applied(ev, ev.txid, "fill", "FILL_APPLIED");
612
+ applied(ev, ev.txid, "fill", "FILL_APPLIED", void 0, moves);
604
613
  }
605
614
  function applyPartialFill(c, ev, o, who) {
606
615
  const { offerLock, bal, applied, refused, setOfferStatus, markBidDone } = c;
@@ -650,6 +659,7 @@ function applyPartialFill(c, ev, o, who) {
650
659
  }
651
660
  bal(o.give.ticker, o.seller).locked -= out;
652
661
  bal(o.give.ticker, who).available += out;
662
+ const moves = [tokenMove("fill", o.give.ticker, o.seller, who, out)];
653
663
  offerLock.set(o.id, lock - out);
654
664
  o.paid = newPaid.toString();
655
665
  o.delivered = newDelivered.toString();
@@ -662,7 +672,7 @@ function applyPartialFill(c, ev, o, who) {
662
672
  offerLock.delete(o.id);
663
673
  markBidDone(o, who);
664
674
  }
665
- applied(ev, ev.txid, "fill", "FILL_PARTIAL", `partial ${x}/${want}`);
675
+ applied(ev, ev.txid, "fill", "FILL_PARTIAL", `partial ${x}/${want}`, moves);
666
676
  }
667
677
  function applyFill(c, ev, o, who) {
668
678
  const { names, offerLock, applied, refused, setOfferStatus, markBidDone, releaseGiveLock } = c;
@@ -699,6 +709,7 @@ function applyFill(c, ev, o, who) {
699
709
  return;
700
710
  }
701
711
  const paid = ptAmt(pt[o.want.payto]);
712
+ const moves = [];
702
713
  if (isNameGive(o.give)) {
703
714
  const n = names.get(o.give.name);
704
715
  if (!n) {
@@ -712,13 +723,13 @@ function applyFill(c, ev, o, who) {
712
723
  refused(ev, ev.txid, "fill", "INVARIANT_BROKEN", "offer lock missing");
713
724
  return;
714
725
  }
715
- releaseGiveLock(o, who, amt);
726
+ moves.push(releaseGiveLock(o, who, amt));
716
727
  }
717
728
  c.feesPaid += fee;
718
729
  setOfferStatus(o, "filled");
719
730
  o.fill = { buyer: who, txid: ev.txid, height: ev.height, paid: paid.toString(), fee: fee.toString() };
720
731
  markBidDone(o, who);
721
- applied(ev, ev.txid, "fill", "FILL_APPLIED");
732
+ applied(ev, ev.txid, "fill", "FILL_APPLIED", void 0, moves);
722
733
  }
723
734
  function applyLegacyClaim(c, ev, o, who) {
724
735
  const { applied, refused, store } = c;
@@ -763,6 +774,10 @@ var MinQueue = class {
763
774
  get size() {
764
775
  return this.ids.length;
765
776
  }
777
+ /** The smallest stored key, or undefined when the queue is empty. */
778
+ peekKey() {
779
+ return this.keys[0];
780
+ }
766
781
  /** Adds an entry. A NaN key is not stored: no comparison with NaN is true, so such an item is never due. */
767
782
  push(key, id) {
768
783
  if (key !== key) return;
@@ -848,6 +863,7 @@ function createStore(opts = {}) {
848
863
  s.add(v);
849
864
  };
850
865
  const regimeHeight = () => maxSweep >= V21_HEIGHT ? V21_HEIGHT : V21_HEIGHT - 1;
866
+ let splitSweep = true;
851
867
  const addOffer = (o) => {
852
868
  if (!offers.has(o.id)) offerAt.set(o.id, ++stamp);
853
869
  offers.set(o.id, o);
@@ -988,11 +1004,27 @@ function createStore(opts = {}) {
988
1004
  stats.visits += popped.length;
989
1005
  return [...new Set(popped)].filter(isDue).sort((a, b) => at.get(a) - at.get(b));
990
1006
  };
1007
+ const nextDue = () => {
1008
+ let d = maxSweep >= V21_HEIGHT ? Infinity : V21_HEIGHT;
1009
+ const ko = offerQ.peekKey(), kb = bidQ.peekKey(), kn = nameQ.peekKey(), kr = recaptureQ.peekKey();
1010
+ if (ko !== void 0) d = Math.min(d, (ko + 1) * EPOCH_LEN);
1011
+ if (kb !== void 0) d = Math.min(d, (kb + 1) * EPOCH_LEN);
1012
+ if (kn !== void 0) d = Math.min(d, kn + 1);
1013
+ if (kr !== void 0) d = Math.min(d, kr + 1);
1014
+ return d;
1015
+ };
991
1016
  const sweep = (height, expireOffer) => {
992
1017
  if (!(height >= maxSweep)) {
993
1018
  walkSweep(height, expireOffer);
994
1019
  return;
995
1020
  }
1021
+ if (splitSweep) for (let d = nextDue(); d < height; d = nextDue()) {
1022
+ if (!(d > maxSweep)) break;
1023
+ sweepAt(d, expireOffer);
1024
+ }
1025
+ sweepAt(height, expireOffer);
1026
+ };
1027
+ const sweepAt = (height, expireOffer) => {
996
1028
  if (!(maxSweep >= V21_HEIGHT) && height >= V21_HEIGHT) {
997
1029
  stats.visits += openOffers.size + openBids.size;
998
1030
  for (const id of openOffers) {
@@ -1019,6 +1051,13 @@ function createStore(opts = {}) {
1019
1051
  same(`expired bids at ${height}`, dueBids, want.bids);
1020
1052
  same(`expired reservations at ${height}`, dueNames, want.names);
1021
1053
  same(`expired recaptures at ${height}`, dueRecaptures, want.recaptures);
1054
+ const early = !splitSweep ? [] : [
1055
+ ...dueOffers.filter((id) => offerDue(offers.get(id), height - 1)),
1056
+ ...dueBids.filter((id) => bidDue(bids.get(id), height - 1)),
1057
+ ...dueNames.filter((nm) => nameDue(names.get(nm), height - 1)),
1058
+ ...dueRecaptures.filter((nm) => height - 1 > recaptures.get(nm).finalizeBy)
1059
+ ];
1060
+ if (early.length) throw new Error(`replay index check: expired at ${height}, due before it: ${early.join(", ")}`);
1022
1061
  }
1023
1062
  for (const id of dueOffers) {
1024
1063
  const o = offers.get(id);
@@ -1168,6 +1207,9 @@ function createStore(opts = {}) {
1168
1207
  putRecapture,
1169
1208
  deleteRecapture,
1170
1209
  sweep,
1210
+ endSplit: () => {
1211
+ splitSweep = false;
1212
+ },
1171
1213
  pendingCount,
1172
1214
  recaptureCount,
1173
1215
  liveHoldCount,
@@ -1728,7 +1770,7 @@ function applyMint(c, ev, rec, who) {
1728
1770
  }
1729
1771
  tok.minted += credit;
1730
1772
  bal(rec.ticker, who).available += credit;
1731
- applied(ev, ev.id, "mint", "TOKEN_MINTED", credit.toString());
1773
+ applied(ev, ev.id, "mint", "TOKEN_MINTED", credit.toString(), [tokenMove("mint", rec.ticker, null, who, credit)]);
1732
1774
  }
1733
1775
  function applyTransfer(c, ev, rec, who) {
1734
1776
  const { tokens, bal, applied, refused } = c;
@@ -1742,9 +1784,10 @@ function applyTransfer(c, ev, rec, who) {
1742
1784
  refused(ev, ev.id, "transfer", "TOKEN_BALANCE_LOW", "insufficient available balance");
1743
1785
  return;
1744
1786
  }
1787
+ const to = rec.to.toLowerCase();
1745
1788
  from.available -= amt;
1746
- bal(rec.ticker, rec.to.toLowerCase()).available += amt;
1747
- applied(ev, ev.id, "transfer", "TOKEN_TRANSFERRED");
1789
+ bal(rec.ticker, to).available += amt;
1790
+ applied(ev, ev.id, "transfer", "TOKEN_TRANSFERRED", void 0, [tokenMove("xfer", rec.ticker, who, to, amt)]);
1748
1791
  }
1749
1792
  function applyTmeta(c, ev, rec, who) {
1750
1793
  const { tokens, applied, refused } = c;
@@ -1778,27 +1821,31 @@ function resolve(events, tipHeight) {
1778
1821
  return replay(events, tipHeight);
1779
1822
  }
1780
1823
  function replay(events, tipHeight, opts = {}) {
1781
- const ordered = [...events].sort(applyOrder);
1824
+ const fold = createFold(opts);
1825
+ for (const e of [...events].sort(applyOrder)) fold.apply(e);
1826
+ return fold.finish(tipHeight);
1827
+ }
1828
+ function createFold(opts) {
1782
1829
  const seenIds = /* @__PURE__ */ new Set();
1783
- const applied = [];
1784
- for (const e of ordered) {
1785
- if (e.height >= V29_HEIGHT) {
1786
- const k = eventId(e);
1787
- if (seenIds.has(k)) continue;
1788
- seenIds.add(k);
1789
- }
1790
- applied.push(e);
1791
- }
1792
1830
  const store = createStore(opts);
1793
1831
  const c = createContext(store);
1794
- const { tokens, balances, names, recaptures, offers, bids, fclaims, log, refused, sweepExpired } = c;
1832
+ const { refused, sweepExpired } = c;
1795
1833
  let pendingBlock = -1;
1796
1834
  const applyPendingCancels = () => {
1797
1835
  for (const f of c.pendingCancels) f();
1798
1836
  c.pendingCancels = [];
1799
1837
  };
1800
- for (const ev of applied) {
1801
- if (beforeActivation(ev.height)) continue;
1838
+ const inDomain = (height) => {
1839
+ if (!Number.isSafeInteger(height)) store.endSplit();
1840
+ };
1841
+ const apply = (ev) => {
1842
+ inDomain(ev.height);
1843
+ if (ev.height >= V29_HEIGHT) {
1844
+ const k = eventId(ev);
1845
+ if (seenIds.has(k)) return;
1846
+ seenIds.add(k);
1847
+ }
1848
+ if (beforeActivation(ev.height)) return;
1802
1849
  if (ev.height !== pendingBlock) {
1803
1850
  applyPendingCancels();
1804
1851
  pendingBlock = ev.height;
@@ -1810,7 +1857,7 @@ function replay(events, tipHeight, opts = {}) {
1810
1857
  const parsed = explainRecord(ev.uri, ev.payloadHash);
1811
1858
  if (!parsed.ok) {
1812
1859
  refused(ev, ev.id, "invalid", parsed.code, "unparseable/non-canonical record");
1813
- continue;
1860
+ return;
1814
1861
  }
1815
1862
  const rec = parsed.record;
1816
1863
  const who = ev.proposer.toLowerCase();
@@ -1864,10 +1911,18 @@ function replay(events, tipHeight, opts = {}) {
1864
1911
  } else {
1865
1912
  applyAttest(c, ev);
1866
1913
  }
1867
- }
1868
- applyPendingCancels();
1869
- sweepExpired(tipHeight + 1);
1870
- store.verify(tipHeight + 1, true);
1914
+ };
1915
+ const finish = (tipHeight) => {
1916
+ applyPendingCancels();
1917
+ inDomain(tipHeight);
1918
+ sweepExpired(tipHeight + 1);
1919
+ store.verify(tipHeight + 1, true);
1920
+ return materialize(c, tipHeight);
1921
+ };
1922
+ return { apply, finish };
1923
+ }
1924
+ function materialize(c, tipHeight) {
1925
+ const { tokens, balances, names, recaptures, offers, bids, fclaims, log } = c;
1871
1926
  const tokensOut = {};
1872
1927
  for (const [t, tok] of [...tokens.entries()].sort(([a], [b]) => ord(a, b))) tokensOut[t] = { ...tok.meta, minted: tok.minted.toString() };
1873
1928
  const balancesOut = {};
@@ -2093,6 +2148,54 @@ function pickPrimaryName(names, a) {
2093
2148
  return best ? best.name : null;
2094
2149
  }
2095
2150
 
2151
+ // src/forward.ts
2152
+ function resolveNameIn(names, name) {
2153
+ if (!Object.hasOwn(names, name)) return null;
2154
+ const n = names[name];
2155
+ if (!n) return null;
2156
+ if (n.pending) return null;
2157
+ return { name, addr: n.addr ?? n.owner, via: n.addr ? "nset" : "owner", lapsed: n.expired === true, owner: n.owner };
2158
+ }
2159
+ function nameView(names, name) {
2160
+ if (typeof name !== "string" || !NAME_RE.test(name)) return null;
2161
+ const none = { owner: null, addr: null, profile: {}, paidThroughEpoch: null };
2162
+ if (RESERVED_NAMES.has(name)) return { name, state: "reserved", ...none };
2163
+ const n = Object.hasOwn(names, name) ? names[name] : void 0;
2164
+ if (!n) return { name, state: "free", ...none };
2165
+ const r = resolveNameIn(names, name);
2166
+ if (r === null) return { name, state: "pending", ...none, owner: n.owner };
2167
+ const paidThroughEpoch = n.paidThroughEpoch ?? null;
2168
+ if (r.lapsed) return { name, state: "lapsed", ...none, owner: n.owner, paidThroughEpoch };
2169
+ return { name, state: "held", owner: n.owner, addr: r.addr, profile: { ...n.profile }, paidThroughEpoch };
2170
+ }
2171
+
2172
+ // src/version.ts
2173
+ var CAIRNX_CORE_VERSION = "0.2.9";
2174
+
2175
+ // src/gates.ts
2176
+ var GATE_HEIGHTS = Object.freeze({
2177
+ ACTIVATION_HEIGHT,
2178
+ V11_HEIGHT,
2179
+ V12_HEIGHT,
2180
+ V13_HEIGHT,
2181
+ V14_HEIGHT,
2182
+ V15_HEIGHT,
2183
+ V16_HEIGHT,
2184
+ V17_HEIGHT,
2185
+ V18_HEIGHT,
2186
+ V19_HEIGHT,
2187
+ V20_HEIGHT,
2188
+ V21_HEIGHT,
2189
+ V22_HEIGHT,
2190
+ V23_HEIGHT,
2191
+ V24_HEIGHT,
2192
+ V25_HEIGHT,
2193
+ V26_HEIGHT,
2194
+ V27_HEIGHT,
2195
+ V28_HEIGHT,
2196
+ V29_HEIGHT
2197
+ });
2198
+
2096
2199
  // src/verifyfill.ts
2097
2200
  import { payloadHash as payloadHash2 } from "@inversealtruism/csd-codec";
2098
2201
  var FCLAIM_MAX_HOLD_SPAN = EPOCH_LEN * (FCLAIM_MAX_EPOCH_AHEAD + 1) - 1;
@@ -2647,6 +2750,7 @@ export {
2647
2750
  ADDR_RE,
2648
2751
  AMOUNT_RE,
2649
2752
  BID_KEYS,
2753
+ CAIRNX_CORE_VERSION,
2650
2754
  CAIRNX_EVENT_RULE,
2651
2755
  CAP_CODES,
2652
2756
  CLAIM_ATTACKER_Q,
@@ -2674,6 +2778,7 @@ export {
2674
2778
  FINALIZE_TIP_MARGIN,
2675
2779
  FINAL_DEPTH,
2676
2780
  GAP_NEEDED,
2781
+ GATE_HEIGHTS,
2677
2782
  HALVING_INTERVAL,
2678
2783
  HASH_RE,
2679
2784
  INITIAL_REWARD2 as INITIAL_REWARD,
@@ -2792,6 +2897,7 @@ export {
2792
2897
  nameRegFee,
2793
2898
  nameRenew,
2794
2899
  nameSet,
2900
+ nameView,
2795
2901
  nameXfer,
2796
2902
  offer,
2797
2903
  offerCancelAll,
@@ -2811,6 +2917,7 @@ export {
2811
2917
  requiredClaimDepth,
2812
2918
  requiredFillOutputs,
2813
2919
  resolve,
2920
+ resolveNameIn,
2814
2921
  stateHash,
2815
2922
  tokenMeta,
2816
2923
  tradeFee,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inversealtruism/cairnx-core",
3
- "version": "0.2.7",
3
+ "version": "0.2.9",
4
4
  "engines": {
5
5
  "node": ">=18"
6
6
  },