@inversealtruism/cairnx-core 0.1.37 → 0.1.40

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
@@ -28,7 +28,7 @@ declare const CLAIM_FILL_GRACE_BLOCKS = 5;
28
28
  declare const MAX_ACTIVE_CLAIMS = 3;
29
29
  declare const CLAIM_COOLDOWN_BLOCKS = 15;
30
30
  declare const FCLAIM_MAX_EPOCH_AHEAD = 2;
31
- declare const FILL_TIP_MARGIN = 2;
31
+ declare const FILL_TIP_MARGIN = 4;
32
32
  declare const CONF_TOKEN_FILL = 1000000;
33
33
  declare const TREASURY_ADDR = "0x6b09ce74e6070ebc982ab0fb793a211c4d24f016";
34
34
  declare const FEE_BPS = 100;
@@ -73,9 +73,11 @@ declare const FINALIZE_TIP_MARGIN = 2;
73
73
  declare const V26_HEIGHT = 46480;
74
74
  declare const V27_HEIGHT = 46520;
75
75
  declare const V28_HEIGHT = 60000;
76
+ declare const V29_HEIGHT = 88000;
76
77
  declare const epochOf: (height: number) => number;
77
78
  declare const claimWindowAt: (height: number) => number;
78
- declare const claimWindowOf: (claimUntilHeight: number) => number;
79
+ declare const FCLAIM_WINDOW_MIN: number;
80
+ declare const claimWindowOf: (claimUntilHeight: number, claimTxid?: string) => number;
79
81
  declare const claimGraceOf: (claimUntilHeight: number, claimTxid?: string) => number;
80
82
  declare const fclaimEpochFor: (tipHeight: number, offerExpiresEpoch: number) => number;
81
83
  declare const fclaimHoldEnd: (expiresEpoch: number) => number;
@@ -486,11 +488,53 @@ declare function previewFill(offer: OfferState, payRaw: bigint | string | number
486
488
  * claims/takers. Until 2026-07-06 this map was hand-mirrored in the wallet's fillOffer, the cairnx
487
489
  * service txbuild, and TWICE in the cairn trade UI — four copies of fund-loss-class math with no
488
490
  * cross-repo lock. This is now the only place it lives; test/preflight.test.ts pins it against the
489
- * real resolver (outputs accepted; any single-unit per-address underpayment refused). */
491
+ * real resolver (outputs accepted; any single-unit per-address underpayment refused).
492
+ *
493
+ * DOC CORRECTION (B6b / REBIND M1) - the `[]` vs `null` asymmetry is a live hazard, not a convenience:
494
+ * `[]` (token want) means "no CSD outputs are required", it does NOT mean "this fill is checked". Every
495
+ * caller whose safety loop is `for (const o of outs) ...` iterates ZERO times on a token fill and passes
496
+ * silently, while the undeliverable-CSD case (`null`) is explicitly refused. That asymmetry is the
497
+ * mechanical reason the token-fill hole (W1) propagated to every consumer. The token side of a fill is
498
+ * settled from the ATTESTER's token balance and carries the CONF_TOKEN_FILL confidence marker; nothing
499
+ * in this return value verifies any of that.
500
+ * @deprecated Use `fillOutputPlan` - it returns the same math behind a DISCRIMINATED result, so the
501
+ * token-want case cannot be silently conflated with "nothing to check". This function's behavior is
502
+ * FROZEN (published npm API; `[]` is load-bearing in downstream builders and tests) and it will keep
503
+ * working; new callers should not add to the need-map-loop hazard. */
490
504
  declare function requiredFillOutputs(offer: OfferState, payRaw: bigint | string | number): {
491
505
  to: string;
492
506
  value: bigint;
493
507
  }[] | null;
508
+ /** B6b (REBIND M1): the DISCRIMINATED successor to requiredFillOutputs. Same math (it calls
509
+ * requiredFillOutputs - the addr->sum map still lives in exactly one place); the difference is that the
510
+ * three outcomes a caller must treat differently are now three distinct kinds instead of `[] | null`:
511
+ * "csd-outputs" - build EXACTLY these CSD outputs (payto + treasury fee + maker rebate, merged per
512
+ * address). The normal CSD-priced case.
513
+ * "token-settled" - a token-priced offer: there are NO CSD outputs to build, and that is NOT the same
514
+ * as "checked". The fill debits the ATTESTER's want-token balance and the attest MUST
515
+ * carry `confidence` (= CONF_TOKEN_FILL, resolve.ts requires the explicit marker).
516
+ * Verify your token balance and terms yourself before signing.
517
+ * "undeliverable" - the resolver would reject this payment AFTER the CSD moved; do not sign.
518
+ * ADDITIVE and default-safe: requiredFillOutputs is unchanged in behavior (its `[]` is load-bearing in
519
+ * published consumers); this wrapper only makes the pivot impossible to fall through silently. */
520
+ type FillOutputPlan = {
521
+ kind: "csd-outputs";
522
+ outputs: {
523
+ to: string;
524
+ value: bigint;
525
+ }[];
526
+ preview: FillPreview;
527
+ } | {
528
+ kind: "token-settled";
529
+ outputs: [];
530
+ confidence: number;
531
+ preview: FillPreview;
532
+ } | {
533
+ kind: "undeliverable";
534
+ reason: "not-open" | "not-csd-priced" | "below-min" | "zero-delivery";
535
+ preview: FillPreview;
536
+ };
537
+ declare function fillOutputPlan(offer: OfferState, payRaw: bigint | string | number): FillOutputPlan;
494
538
  /** Name-fee build heuristic (app-side, NOT a resolver rule): a name-fee OUTPUT built just below a fee
495
539
  * gate but mined at/after it underpays the new tier → resolver rejects → the treasury-fee UTXO is
496
540
  * forfeit. Within FEE_GATE_MARGIN_BLOCKS below ANY upcoming fee gate, price the BUILD at that gate:
@@ -514,15 +558,59 @@ declare function hasLiveClaim(offer: OfferState, me: string, tip: number): boole
514
558
  declare function fillTargetId(offer: OfferState, tip: number): string;
515
559
  /** The union verdict a client must clear BEFORE signing a fill of `offer` paying `pay`, as `me`, at `tip`.
516
560
  * Closes C2/C3/C4: status open, deliverability >= 1 token, live-claim holdership for the open-CSD lane,
517
- * and taker match. `safe:true` ⇒ the fill is guaranteed to be accepted by the deterministic gates a
518
- * payer can verify at signing time (the irreducible timing residual — CLAIM_FILL_GRACE_BLOCKS late mine
519
- * — is documented, not closable by a preflight). Returns the preview so the caller can size outputs. */
561
+ * and taker match. Returns the preview so the caller can size outputs.
562
+ *
563
+ * DOC CORRECTION (B6b / REBIND W10) - the historical claim that `safe:true` means "the fill is guaranteed
564
+ * to be accepted by the deterministic gates a payer can verify at signing time" OVER-STATES this predicate
565
+ * on two counts, both live:
566
+ * 1. For a TOKEN-priced want it returns `safe:true` unconditionally ("deliverability is the buyer's
567
+ * balance"). That is an honest statement of what it cannot see, but as a boolean it reads as an
568
+ * ENDORSEMENT of the un-verifiable path - the never-over-claim rule this codebase holds elsewhere.
569
+ * 2. It never receives the FILL TARGET id, so it cannot implement the v2.8 Correction-1 clause: during
570
+ * a live fclaim hold the chain rejects an attest on the OFFER txid (the payment must attest the
571
+ * FCLAIM txid), and this predicate says `safe:true` for exactly that doomed fill.
572
+ * @deprecated Use `fillEndorsement` - a discriminated verdict ("endorsed" / "refused" / "not-endorsable")
573
+ * plus the `fillTargetId` parameter that closes both gaps. This function's verdicts are FROZEN (published
574
+ * npm API; flipping them could hard-refuse honest fills in unknowable third-party dApps) and it keeps
575
+ * working; it must not be "hardened" in place. */
520
576
  interface FillSafety {
521
577
  safe: boolean;
522
578
  reason: string;
523
579
  preview: FillPreview;
524
580
  }
525
581
  declare function fillIsSafe(offer: OfferState, me: string, pay: bigint | string | number, tip: number): FillSafety;
582
+ /** B6b (REBIND W10): the DISCRIMINATED successor to fillIsSafe. Three verdicts, and consuming them
583
+ * correctly is part of the contract:
584
+ * "endorsed" - every deterministic gate a payer can verify at signing time passes (status, taker,
585
+ * open-lane holdership, deliverability, and - NEW - the v2.8 fill-target routing).
586
+ * "refused" - the chain WILL reject this fill after the payment moved. Do not sign.
587
+ * "not-endorsable" - a TOKEN-priced want: deliverability is the attester's token balance, which this
588
+ * pure predicate cannot see. This is HONEST NON-ENDORSEMENT, not refusal: proceed
589
+ * with your own token-balance and proven-terms checks (a consumer that treats this
590
+ * as "refuse" hard-blocks every honest token fill - the named B7f trap).
591
+ *
592
+ * `opts.fillTargetId` is the proposal txid your attest will actually target. Pass it whenever you have
593
+ * it (= `fillTargetId(offer, tip)` for an honest builder). The v2.8 Correction-1 clause (resolve.ts
594
+ * openFillReject): during a live fclaim hold an attest on the OFFER txid is rejected while the payment
595
+ * still moves - the exact doomed fill the deprecated fillIsSafe endorses. If the offer carries a live
596
+ * fclaim-hold routing and no target is supplied, the endorsement fails CLOSED with instructions rather
597
+ * than guessing what your builder will attest. */
598
+ type FillEndorsement = {
599
+ verdict: "endorsed";
600
+ reason: "ok";
601
+ preview: FillPreview;
602
+ } | {
603
+ verdict: "refused";
604
+ reason: string;
605
+ preview: FillPreview;
606
+ } | {
607
+ verdict: "not-endorsable";
608
+ reason: string;
609
+ preview: FillPreview;
610
+ };
611
+ declare function fillEndorsement(offer: OfferState, me: string, pay: bigint | string | number, tip: number, opts?: {
612
+ fillTargetId?: string;
613
+ }): FillEndorsement;
526
614
  /** C1: may `me` safely sign the fee-bearing registration `nfinalize` for `nameState` committed at
527
615
  * `commitHeight`? The reg fee rides nfinalize; a finalize on a reservation that was displaced, has
528
616
  * expired, OR is raised before the displacement contest froze is REJECTED after the fee moved (a burn).
@@ -599,15 +687,85 @@ interface FillVerdict {
599
687
  * replay cannot see the buyer's other-offer holds, and MAX_ACTIVE_CLAIMS is the one grant clause counted
600
688
  * across offers, so without this the surface would false-accept a cap-denied fclaim. `opts.pay` overrides the
601
689
  * payment (base units to want.payto) for a PARTIAL tail-fill; defaults to the offer's full want.value.
690
+ *
691
+ * `opts.sums` (OPT-IN, B6a / REBIND W3; default OFF = byte-identical verdicts for existing callers) binds the
692
+ * caller's PLANNED per-address CSD payment sums to the PROVEN offer state: requiredFillOutputs is re-run over
693
+ * the merkle-proven, replayed offer (so `paid`/`delivered` are the chain's, not a served lie) and the caller's
694
+ * map must match it EXACTLY, address for address. This closes the W3 overpay: a resolver serving `paid:"0"`
695
+ * for a 90%-filled partial made callers size the FULL want while the chain credits only the remainder - the
696
+ * difference was permanently overpaid. Pass the SAME per-address sums you will build (the wallet's need-map
697
+ * shape: payto + treasury fee + maker rebate, MERGED per address - `payto === seller` merges the rebate leg).
698
+ * DELIBERATELY NOT the scalar `dp.pay !== pay` form: that refuses honest fills on both live callers (the
699
+ * wallet's per-address sum includes the maker rebate when payto === seller; the site passes no pay at all).
602
700
  */
603
701
  declare function verifyFillSpv(offerId: string, fclaimTxid: string, me: string, io: FillSpvIo, opts: {
604
702
  myLiveHoldsAtGrant: number;
605
703
  pay?: bigint | string | number;
704
+ sums?: Record<string, bigint | string | number>;
606
705
  }): Promise<FillVerdict>;
706
+ interface ProvenOfferTerms {
707
+ height: number;
708
+ feeBps: number;
709
+ value?: string;
710
+ taker?: string;
711
+ bid?: string;
712
+ min?: string;
713
+ giveTicker?: string;
714
+ giveAmount?: string;
715
+ giveName?: string;
716
+ wantType?: "csd" | "token";
717
+ }
718
+ declare const PROVEN_TERMS_MINT: unique symbol;
719
+ type MintedProvenOfferTerms = ProvenOfferTerms & {
720
+ readonly [PROVEN_TERMS_MINT]: "cairnx-core/provenOfferTerms";
721
+ };
722
+ /** UNSAFE escape hatch, TESTS ONLY: brand a hand-built terms object. Production code must never call this -
723
+ * hand-built terms are exactly the W2 defect class the brand exists to make unrepresentable. */
724
+ declare const unsafeMintProvenOfferTerms: (t: ProvenOfferTerms) => MintedProvenOfferTerms;
725
+ declare const feeBpsAt: (height: number) => number;
726
+ declare function provenOfferTerms(offerRec: OfferRecord, provenHeight: number): MintedProvenOfferTerms;
727
+ /**
728
+ * The fill-boundary TERM-MISMATCH verdict: `true` iff any fee/rebate/partial-sizing field of the resolver-
729
+ * SERVED offer diverges from the merkle-proven terms `t`. FAIL-CLOSED semantics (any divergence => true =>
730
+ * the caller refuses). Byte-identical in behaviour to the wallet's old provenTermsMismatch and the site's
731
+ * old inline amount-leg bind (they were reconciled to be one predicate here):
732
+ * - height (offer.height vs t.height)
733
+ * - feeBps (offer.feeBps vs t.feeBps = feeBpsAt(creation height))
734
+ * - value (offer.want.value vs t.value, only when the proven offer is CSD-priced)
735
+ * - taker (offer.taker vs t.taker, case-insensitive, undefined/null == "")
736
+ * - bid (offer.bid vs t.bid, same normalization)
737
+ * - min presence AND value: an ADDED spurious min (whole->partial rebate-drop burn) OR a deflated min
738
+ * both mismatch. EXPLICIT presence (a served min="" must not slip past a proven-absent min).
739
+ * `value` is bound only when `t.value` is defined so a token<->token offer (no CSD value) is not spuriously
740
+ * refused; a caller that binds want.value separately (the site does) may still pass it here (redundant-safe).
741
+ *
742
+ * B6a (REBIND W2 legs + W7) OPT-IN legs, via the third argument (default OFF: a 2-arg call is byte-identical
743
+ * to the pre-B6 predicate on every input). The 3-arg overload requires MINTED terms (the brand), so a caller
744
+ * adopting the new legs cannot feed them a hand-built terms object that leaves the new fields undefined -
745
+ * that shape would false-refuse every honest fill (the W2 trap this file documents).
746
+ * opts.give - bind give.ticker / give.amount / give.name: EXPLICIT PRESENCE (a served give growing or
747
+ * losing a field mismatches) AND verbatim string equality. Closes the W7 shortchange (a
748
+ * genuine offer served with give.amount inflated a millionfold passes every legacy leg).
749
+ * opts.wantType - the SYMMETRIC want-type refusal: the served offer's want type (token iff want.ticker is
750
+ * a string, the isTokenWant pivot) must equal the proven type. The legacy value leg already
751
+ * catches proven-CSD-served-as-token (String(undefined) mismatches t.value); this closes
752
+ * the reverse, proven-token-served-as-CSD, which today only wallet.ts catches one-sidedly.
753
+ */
754
+ interface BindTermsOpts {
755
+ give?: boolean;
756
+ wantType?: boolean;
757
+ }
758
+ declare function bindOfferTerms(servedOffer: unknown, t: ProvenOfferTerms): boolean;
759
+ declare function bindOfferTerms(servedOffer: unknown, t: MintedProvenOfferTerms, opts: BindTermsOpts): boolean;
760
+ declare function bindProvenOffer(offerEv: ProvenPropose): {
761
+ payto: string;
762
+ seller: string;
763
+ terms: MintedProvenOfferTerms;
764
+ } | null;
607
765
 
608
766
  declare function paidToFromOutputs(outputs: readonly {
609
767
  addr: string;
610
768
  value: number;
611
769
  }[]): Record<string, string>;
612
770
 
613
- export { ACTIVATION_HEIGHT, ADDR_RE, AMOUNT_RE, type AppliedEvent, type AttestEvent, BID_KEYS, type BalanceState, type BidRecord, type BidState, type BidStatus, type BuiltRecord, 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, FCLAIM_KEYS, FCLAIM_MAX_EPOCH_AHEAD, FEE_BPS, FEE_BPS_V16, FEE_GATE_MARGIN_BLOCKS, FILL_TIP_MARGIN, FINALIZE_TIP_MARGIN, type FclaimRecord, type FillEntry, type FillPreview, type FillSafety, type FillSpvIo, type FillVerdict, GAP_NEEDED, type Give, HASH_RE, type HoldReplay, MAX_ACTIVE_CLAIMS, MAX_AMOUNT, MAX_OFFER_EPOCHS, MAX_PENDING_REG, MAX_RECORD_BYTES, MAX_SCAN, MINT_KEYS, type MintRecord, 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 ProvenPropose, REBATE_BPS, REBATE_FLAT, REG_COMMIT_MAX_BLOCKS, REG_FINALIZE_GRACE_BLOCKS, RESERVED_NAMES, 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, type Want, ZERO_ADDR, bid, buildFeeHeight, buildRecord, canonicalState, claimGraceOf, claimWindowAt, claimWindowOf, deploy, epochOf, expiredClaimFee, fclaim, fclaimEpochFor, fclaimHoldEnd, fillIsSafe, fillTargetId, finalizeWinnerCheck, hasLiveClaim, isName, isNameGive, isOpenClaimLane, isTokenWant, makerRebate, mint, nameClaim, nameCommit, nameCommitRecord, nameFinalize, nameProfile, nameRegFee, nameRenew, nameSet, nameXfer, offer, offerCancelAll, offerExpiryHeightOf, paidToFromOutputs, parseAmount, parseRecord, pickPrimaryName, previewFill, primaryRankBefore, replayLiveHold, requiredClaimDepth, requiredFillOutputs, resolve, tokenMeta, tradeFee, transfer, verifyFillSpv };
771
+ export { ACTIVATION_HEIGHT, ADDR_RE, AMOUNT_RE, type AppliedEvent, type AttestEvent, BID_KEYS, type BalanceState, type BidRecord, type BidState, type BidStatus, type BindTermsOpts, type BuiltRecord, 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, FCLAIM_KEYS, FCLAIM_MAX_EPOCH_AHEAD, FCLAIM_WINDOW_MIN, FEE_BPS, FEE_BPS_V16, FEE_GATE_MARGIN_BLOCKS, FILL_TIP_MARGIN, FINALIZE_TIP_MARGIN, type FclaimRecord, type FillEndorsement, type FillEntry, type FillOutputPlan, type FillPreview, type FillSafety, type FillSpvIo, type FillVerdict, GAP_NEEDED, type Give, HASH_RE, type HoldReplay, MAX_ACTIVE_CLAIMS, MAX_AMOUNT, MAX_OFFER_EPOCHS, MAX_PENDING_REG, MAX_RECORD_BYTES, MAX_SCAN, 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 ProvenPropose, REBATE_BPS, REBATE_FLAT, REG_COMMIT_MAX_BLOCKS, REG_FINALIZE_GRACE_BLOCKS, RESERVED_NAMES, 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, bid, bindOfferTerms, bindProvenOffer, buildFeeHeight, buildRecord, canonicalState, claimGraceOf, claimWindowAt, claimWindowOf, deploy, epochOf, expiredClaimFee, fclaim, fclaimEpochFor, fclaimHoldEnd, feeBpsAt, fillEndorsement, fillIsSafe, fillOutputPlan, fillTargetId, finalizeWinnerCheck, hasLiveClaim, isName, isNameGive, isOpenClaimLane, isTokenWant, makerRebate, mint, nameClaim, nameCommit, nameCommitRecord, nameFinalize, nameProfile, nameRegFee, nameRenew, nameSet, nameXfer, offer, offerCancelAll, offerExpiryHeightOf, paidToFromOutputs, parseAmount, parseRecord, pickPrimaryName, previewFill, primaryRankBefore, provenOfferTerms, replayLiveHold, requiredClaimDepth, requiredFillOutputs, resolve, tokenMeta, tradeFee, transfer, unsafeMintProvenOfferTerms, verifyFillSpv };
package/dist/index.js CHANGED
@@ -31,7 +31,7 @@ var CLAIM_FILL_GRACE_BLOCKS = 5;
31
31
  var MAX_ACTIVE_CLAIMS = 3;
32
32
  var CLAIM_COOLDOWN_BLOCKS = 15;
33
33
  var FCLAIM_MAX_EPOCH_AHEAD = 2;
34
- var FILL_TIP_MARGIN = 2;
34
+ var FILL_TIP_MARGIN = 4;
35
35
  var CONF_TOKEN_FILL = 1e6;
36
36
  var TREASURY_ADDR = "0x6b09ce74e6070ebc982ab0fb793a211c4d24f016";
37
37
  var FEE_BPS = 100;
@@ -91,9 +91,14 @@ var FINALIZE_TIP_MARGIN = 2;
91
91
  var V26_HEIGHT = 46480;
92
92
  var V27_HEIGHT = 46520;
93
93
  var V28_HEIGHT = 6e4;
94
+ var V29_HEIGHT = 88e3;
94
95
  var epochOf = (height) => Math.floor(height / EPOCH_LEN);
95
96
  var claimWindowAt = (height) => height >= V20_HEIGHT ? CLAIM_WINDOW_BLOCKS_V20 : CLAIM_WINDOW_BLOCKS;
96
- var claimWindowOf = (claimUntilHeight) => claimUntilHeight - CLAIM_WINDOW_BLOCKS_V20 >= V20_HEIGHT ? CLAIM_WINDOW_BLOCKS_V20 : CLAIM_WINDOW_BLOCKS;
97
+ var FCLAIM_WINDOW_MIN = CLAIM_WINDOW_BLOCKS_V20 + CLAIM_FILL_GRACE_BLOCKS + 1;
98
+ var claimWindowOf = (claimUntilHeight, claimTxid) => {
99
+ if (claimTxid !== void 0) return FCLAIM_WINDOW_MIN;
100
+ return claimUntilHeight - CLAIM_WINDOW_BLOCKS_V20 >= V20_HEIGHT ? CLAIM_WINDOW_BLOCKS_V20 : CLAIM_WINDOW_BLOCKS;
101
+ };
97
102
  var claimGraceOf = (claimUntilHeight, claimTxid) => claimTxid !== void 0 ? 0 : claimUntilHeight - CLAIM_WINDOW_BLOCKS_V20 >= V20_HEIGHT ? CLAIM_FILL_GRACE_BLOCKS : 0;
98
103
  var fclaimEpochFor = (tipHeight, offerExpiresEpoch) => Math.min(epochOf(tipHeight + CLAIM_WINDOW_BLOCKS_V20 + CLAIM_FILL_GRACE_BLOCKS), offerExpiresEpoch);
99
104
  var fclaimHoldEnd = (expiresEpoch) => (expiresEpoch + 1) * EPOCH_LEN - 1;
@@ -355,6 +360,17 @@ function resolve(events, tipHeight) {
355
360
  b.kind === "propose" ? b.id : b.txid
356
361
  )
357
362
  );
363
+ const eid = (e) => e.kind === "propose" ? e.id : e.txid;
364
+ const seenIds = /* @__PURE__ */ new Set();
365
+ const applied = [];
366
+ for (const e of ordered) {
367
+ if (e.height >= V29_HEIGHT) {
368
+ const k = eid(e);
369
+ if (seenIds.has(k)) continue;
370
+ seenIds.add(k);
371
+ }
372
+ applied.push(e);
373
+ }
358
374
  const tokens = /* @__PURE__ */ new Map();
359
375
  const balances = /* @__PURE__ */ new Map();
360
376
  const names = /* @__PURE__ */ new Map();
@@ -463,7 +479,7 @@ function resolve(events, tipHeight) {
463
479
  bal(t, who).available += amt;
464
480
  offerLock.delete(o.id);
465
481
  };
466
- for (const ev of ordered) {
482
+ for (const ev of applied) {
467
483
  if (ev.height < ACTIVATION_HEIGHT) continue;
468
484
  if (ev.height !== pendingBlock) {
469
485
  applyPendingCancels();
@@ -1022,7 +1038,7 @@ function resolve(events, tipHeight) {
1022
1038
  continue;
1023
1039
  }
1024
1040
  let liveN = 0;
1025
- for (const x of offers.values()) if (x.claimedBy === who && claimHeld(x, ev.height)) liveN++;
1041
+ for (const x of offers.values()) if (x.claimedBy === who && claimHeld(x, ev.height) && (ev.height < V29_HEIGHT || x.status === "open")) liveN++;
1026
1042
  if (liveN >= MAX_ACTIVE_CLAIMS) {
1027
1043
  deny(`max ${MAX_ACTIVE_CLAIMS} live claims per address`);
1028
1044
  continue;
@@ -1276,7 +1292,7 @@ function resolve(events, tipHeight) {
1276
1292
  continue;
1277
1293
  }
1278
1294
  let liveN = 0;
1279
- for (const x of offers.values()) if (x.claimedBy === who && claimHeld(x, ev.height)) liveN++;
1295
+ for (const x of offers.values()) if (x.claimedBy === who && claimHeld(x, ev.height) && (ev.height < V29_HEIGHT || x.status === "open")) liveN++;
1280
1296
  if (liveN >= MAX_ACTIVE_CLAIMS) {
1281
1297
  note(ev, ev.txid, "claim", false, `max ${MAX_ACTIVE_CLAIMS} live claims per address`);
1282
1298
  continue;
@@ -1410,6 +1426,17 @@ function requiredFillOutputs(offer2, payRaw) {
1410
1426
  add(offer2.seller, p.rebate);
1411
1427
  return [...need].map(([to, value]) => ({ to, value }));
1412
1428
  }
1429
+ function fillOutputPlan(offer2, payRaw) {
1430
+ const preview = previewFill(offer2, payRaw);
1431
+ if (isTokenWant(offer2.want)) {
1432
+ if (offer2.status !== "open") return { kind: "undeliverable", reason: "not-open", preview };
1433
+ return { kind: "token-settled", outputs: [], confidence: CONF_TOKEN_FILL, preview };
1434
+ }
1435
+ if (!preview.deliverable) return { kind: "undeliverable", reason: preview.reason === "not-open" || preview.reason === "below-min" ? preview.reason : "zero-delivery", preview };
1436
+ const outputs = requiredFillOutputs(offer2, payRaw);
1437
+ if (outputs === null) return { kind: "undeliverable", reason: "zero-delivery", preview };
1438
+ return { kind: "csd-outputs", outputs, preview };
1439
+ }
1413
1440
  var FEE_GATE_MARGIN_BLOCKS = 5;
1414
1441
  var NAME_FEE_GATES = [V18_HEIGHT, V24_HEIGHT];
1415
1442
  var buildFeeHeight = (tip) => {
@@ -1445,6 +1472,29 @@ function fillIsSafe(offer2, me, pay, tip) {
1445
1472
  }
1446
1473
  return { safe: true, reason: "ok", preview };
1447
1474
  }
1475
+ function fillEndorsement(offer2, me, pay, tip, opts) {
1476
+ const preview = previewFill(offer2, pay);
1477
+ const refuse = (reason) => ({ verdict: "refused", reason, preview });
1478
+ if (offer2.status !== "open") return refuse(`offer is ${offer2.status}`);
1479
+ if (offer2.taker !== void 0 && offer2.taker.toLowerCase() !== me.toLowerCase())
1480
+ return refuse("taker-bound offer - not bound to you");
1481
+ if (isOpenClaimLane(offer2, tip) && !hasLiveClaim(offer2, me, tip))
1482
+ return refuse("open CSD offer - claim it first and fill while your claim is live");
1483
+ const expected = fillTargetId(offer2, tip);
1484
+ const holdRouted = expected.toLowerCase() !== offer2.id.toLowerCase();
1485
+ if (opts?.fillTargetId !== void 0) {
1486
+ if (String(opts.fillTargetId).toLowerCase() !== expected.toLowerCase()) return refuse(holdRouted ? "v2.8: a live fclaim hold routes this fill - the attest must target the fclaim txid, not the offer id (an offer-txid fill is chain-rejected after the payment moved)" : "the attested fill target does not match this offer's routing (attest the offer id)");
1487
+ } else if (holdRouted) {
1488
+ return refuse("v2.8: a live fclaim hold routes this fill - pass opts.fillTargetId (use fillTargetId(offer, tip)) so the endorsement can verify what your attest targets");
1489
+ }
1490
+ if (isTokenWant(offer2.want))
1491
+ return { verdict: "not-endorsable", reason: "token-priced want - deliverability is the attester's token balance, which a pure record predicate cannot see; NOT an endorsement and NOT a refusal (verify your token balance + proven terms, then proceed)", preview };
1492
+ if (!preview.deliverable) {
1493
+ if (preview.reason === "below-min") return refuse("payment is below the offer minimum");
1494
+ return refuse("this payment would deliver 0 tokens - refusing (the CSD would be lost)");
1495
+ }
1496
+ return { verdict: "endorsed", reason: "ok", preview };
1497
+ }
1448
1498
  function finalizeWinnerCheck(nameState, me, commitHeight, tip) {
1449
1499
  const m = me.toLowerCase();
1450
1500
  if (!nameState) return { safe: false, reason: "no reservation on-chain (displaced, swept, or never accepted) \u2014 a finalize now would burn the fee" };
@@ -1567,10 +1617,74 @@ async function verifyFillSpv(offerId, fclaimTxid, me, io, opts) {
1567
1617
  }
1568
1618
  const dp = previewFill({ ...r.offer, status: "open" }, pay);
1569
1619
  if (!dp.deliverable || dp.got < 1n) return no("this fill would deliver 0 units - refusing (the CSD would be lost)");
1620
+ if (opts.sums !== void 0) {
1621
+ const req = requiredFillOutputs({ ...r.offer, status: "open" }, pay);
1622
+ if (req === null) return no("the proven offer state cannot size this payment - refusing");
1623
+ const proven2 = new Map(req.map((o) => [o.to, o.value]));
1624
+ const planned = /* @__PURE__ */ new Map();
1625
+ try {
1626
+ for (const [a, v] of Object.entries(opts.sums)) {
1627
+ const k = String(a).toLowerCase();
1628
+ planned.set(k, (planned.get(k) ?? 0n) + BigInt(v));
1629
+ }
1630
+ } catch {
1631
+ return no("invalid sums (amounts must be base-unit integers)");
1632
+ }
1633
+ const sumsKeys = /* @__PURE__ */ new Set([...proven2.keys(), ...planned.keys()]);
1634
+ for (const k of sumsKeys) if ((proven2.get(k) ?? 0n) !== (planned.get(k) ?? 0n)) return no(`payment does not match the proven fill progress (${k}: planned ${(planned.get(k) ?? 0n).toString()}, proven state requires ${(proven2.get(k) ?? 0n).toString()}) - refusing (an overpay past the real remainder is unrecoverable)`);
1635
+ }
1570
1636
  const holdEnd = fclaimHoldEnd(E);
1571
1637
  if (holdEnd < tip + FILL_TIP_MARGIN) return no(`too close to the hold deadline (holdEnd ${holdEnd}, tip ${tip}) - would strand`);
1572
1638
  return { safe: true, reason: "ok" };
1573
1639
  }
1640
+ var unsafeMintProvenOfferTerms = (t) => t;
1641
+ var feeBpsAt = (height) => height >= V11_HEIGHT ? height >= V16_HEIGHT ? FEE_BPS_V16 : FEE_BPS : 0;
1642
+ function provenOfferTerms(offerRec, provenHeight) {
1643
+ const w = offerRec.want;
1644
+ const g = offerRec.give;
1645
+ return {
1646
+ height: Number(provenHeight),
1647
+ feeBps: feeBpsAt(Number(provenHeight)),
1648
+ value: w.value !== void 0 ? String(w.value) : void 0,
1649
+ taker: offerRec.taker !== void 0 ? String(offerRec.taker).toLowerCase() : void 0,
1650
+ bid: offerRec.bid !== void 0 ? String(offerRec.bid).toLowerCase() : void 0,
1651
+ min: offerRec.min !== void 0 ? String(offerRec.min) : void 0,
1652
+ giveTicker: g.ticker !== void 0 ? String(g.ticker) : void 0,
1653
+ giveAmount: g.amount !== void 0 ? String(g.amount) : void 0,
1654
+ giveName: g.name !== void 0 ? String(g.name) : void 0,
1655
+ wantType: isTokenWant(offerRec.want) ? "token" : "csd"
1656
+ };
1657
+ }
1658
+ function bindOfferTerms(servedOffer, t, opts) {
1659
+ const o = servedOffer;
1660
+ const s = (v) => v === void 0 || v === null ? "" : String(v).toLowerCase();
1661
+ if (Number(o?.height) !== t.height) return true;
1662
+ if (Number(o?.feeBps) !== t.feeBps) return true;
1663
+ if (t.value !== void 0 && String(o?.want?.value) !== t.value) return true;
1664
+ if (s(o?.taker) !== s(t.taker)) return true;
1665
+ if (s(o?.bid) !== s(t.bid)) return true;
1666
+ const om = o?.min;
1667
+ if ((om !== void 0 && om !== null) !== (t.min !== void 0)) return true;
1668
+ if (t.min !== void 0 && String(om) !== t.min) return true;
1669
+ if (opts?.wantType) {
1670
+ if (t.wantType === void 0 || typeof o?.want?.ticker === "string" !== (t.wantType === "token")) return true;
1671
+ }
1672
+ if (opts?.give) {
1673
+ const g = o?.give;
1674
+ if ((g?.ticker !== void 0 && g?.ticker !== null) !== (t.giveTicker !== void 0) || t.giveTicker !== void 0 && String(g?.ticker) !== t.giveTicker) return true;
1675
+ if ((g?.amount !== void 0 && g?.amount !== null) !== (t.giveAmount !== void 0) || t.giveAmount !== void 0 && String(g?.amount) !== t.giveAmount) return true;
1676
+ if ((g?.name !== void 0 && g?.name !== null) !== (t.giveName !== void 0) || t.giveName !== void 0 && String(g?.name) !== t.giveName) return true;
1677
+ }
1678
+ return false;
1679
+ }
1680
+ function bindProvenOffer(offerEv) {
1681
+ const rec = bindRecord(offerEv);
1682
+ if (!rec || rec.t !== "offer") return null;
1683
+ const seller = String(offerEv.proposer).toLowerCase();
1684
+ const w = rec.want;
1685
+ const payto = w.payto && ADDR_RE.test(String(w.payto).toLowerCase()) ? String(w.payto).toLowerCase() : seller;
1686
+ return { payto, seller, terms: provenOfferTerms(rec, offerEv.height) };
1687
+ }
1574
1688
 
1575
1689
  // src/paidto.ts
1576
1690
  function paidToFromOutputs(outputs) {
@@ -1613,6 +1727,7 @@ export {
1613
1727
  EPOCH_LEN2 as EPOCH_LEN,
1614
1728
  FCLAIM_KEYS,
1615
1729
  FCLAIM_MAX_EPOCH_AHEAD,
1730
+ FCLAIM_WINDOW_MIN,
1616
1731
  FEE_BPS,
1617
1732
  FEE_BPS_V16,
1618
1733
  FEE_GATE_MARGIN_BLOCKS,
@@ -1680,8 +1795,11 @@ export {
1680
1795
  V26_HEIGHT,
1681
1796
  V27_HEIGHT,
1682
1797
  V28_HEIGHT,
1798
+ V29_HEIGHT,
1683
1799
  ZERO_ADDR,
1684
1800
  bid,
1801
+ bindOfferTerms,
1802
+ bindProvenOffer,
1685
1803
  blockReward2 as blockReward,
1686
1804
  buildFeeHeight,
1687
1805
  buildRecord,
@@ -1696,7 +1814,10 @@ export {
1696
1814
  fclaim,
1697
1815
  fclaimEpochFor,
1698
1816
  fclaimHoldEnd,
1817
+ feeBpsAt,
1818
+ fillEndorsement,
1699
1819
  fillIsSafe,
1820
+ fillOutputPlan,
1700
1821
  fillTargetId,
1701
1822
  finalizeWinnerCheck,
1702
1823
  hasLiveClaim,
@@ -1725,6 +1846,7 @@ export {
1725
1846
  pickPrimaryName,
1726
1847
  previewFill,
1727
1848
  primaryRankBefore,
1849
+ provenOfferTerms,
1728
1850
  replayLiveHold,
1729
1851
  requiredClaimDepth,
1730
1852
  requiredFillOutputs,
@@ -1732,5 +1854,6 @@ export {
1732
1854
  tokenMeta,
1733
1855
  tradeFee,
1734
1856
  transfer,
1857
+ unsafeMintProvenOfferTerms,
1735
1858
  verifyFillSpv
1736
1859
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inversealtruism/cairnx-core",
3
- "version": "0.1.37",
3
+ "version": "0.1.40",
4
4
  "engines": {
5
5
  "node": ">=18"
6
6
  },
@@ -45,6 +45,6 @@
45
45
  "homepage": "https://cairn-substrate.com/trade",
46
46
  "scripts": {
47
47
  "build": "tsup src/index.ts --format esm,cjs --dts --clean",
48
- "test": "tsx test/vectors.test.ts && tsx test/name-decoy.test.ts && tsx test/client-helpers.test.ts && tsx test/paidto.test.ts && tsx test/preflight.test.ts && tsx test/primary.test.ts && tsx test/fclaim.test.ts && tsx test/fclaim-v28.test.ts && tsx test/verifyfill.test.ts"
48
+ "test": "node test/run.mjs"
49
49
  }
50
50
  }