@inversealtruism/cairnx-core 0.1.33 → 0.1.34

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
@@ -110,8 +110,12 @@ __export(index_exports, {
110
110
  deploy: () => deploy,
111
111
  epochOf: () => epochOf,
112
112
  expiredClaimFee: () => expiredClaimFee,
113
+ fillIsSafe: () => fillIsSafe,
114
+ finalizeWinnerCheck: () => finalizeWinnerCheck,
115
+ hasLiveClaim: () => hasLiveClaim,
113
116
  isName: () => isName,
114
117
  isNameGive: () => isNameGive,
118
+ isOpenClaimLane: () => isOpenClaimLane,
115
119
  isTokenWant: () => isTokenWant,
116
120
  makerRebate: () => makerRebate,
117
121
  mint: () => mint,
@@ -131,6 +135,7 @@ __export(index_exports, {
131
135
  parseAmount: () => parseAmount,
132
136
  parseRecord: () => parseRecord,
133
137
  payloadHash: () => import_csd_codec4.payloadHash,
138
+ previewFill: () => previewFill,
134
139
  requiredClaimDepth: () => requiredClaimDepth,
135
140
  resolve: () => resolve,
136
141
  tokenMeta: () => tokenMeta,
@@ -1403,6 +1408,70 @@ function requiredClaimDepth(valueSats, height) {
1403
1408
  return { depth: max, reversalPct: Math.pow(r, max) * 100, capped: true };
1404
1409
  }
1405
1410
 
1411
+ // src/preflight.ts
1412
+ function previewFill(offer2, payRaw) {
1413
+ const pay = BigInt(payRaw);
1414
+ const zero = { deliverable: false, got: 0n, pay: 0n, fee: 0n, rebate: 0n };
1415
+ if (offer2.status !== "open") return { ...zero, reason: "not-open" };
1416
+ if (isTokenWant(offer2.want)) return { ...zero, reason: "not-csd-priced" };
1417
+ const want = BigInt(offer2.want.value);
1418
+ const feeBps = offer2.feeBps;
1419
+ if (offer2.min !== void 0 && !isNameGive(offer2.give)) {
1420
+ const paidSoFar = BigInt(offer2.paid ?? "0");
1421
+ const remaining = want - paidSoFar;
1422
+ const minV = BigInt(offer2.min);
1423
+ const effMin = remaining < minV ? remaining : minV;
1424
+ if (pay < effMin) return { ...zero, reason: "below-min" };
1425
+ const x = pay < remaining ? pay : remaining;
1426
+ const fee2 = feeBps ? tradeFee(x, feeBps) : 0n;
1427
+ const giveTotal = BigInt(offer2.give.amount);
1428
+ const newPaid = paidSoFar + x;
1429
+ const deliveredSoFar = BigInt(offer2.delivered ?? "0");
1430
+ const out = giveTotal * newPaid / want - deliveredSoFar;
1431
+ if (out === 0n) return { deliverable: false, reason: "zero-delivery", got: 0n, pay: x, fee: fee2, rebate: 0n };
1432
+ return { deliverable: true, reason: "ok", got: out, pay: x, fee: fee2, rebate: 0n };
1433
+ }
1434
+ if (pay < want) return { deliverable: false, reason: "below-min", got: 0n, pay, fee: 0n, rebate: 0n };
1435
+ const fee = feeBps ? tradeFee(want, feeBps) : 0n;
1436
+ const restingLiquidity = offer2.taker !== void 0 && offer2.bid !== void 0 || offer2.height >= V17_HEIGHT && offer2.taker === void 0;
1437
+ const rebate = offer2.height >= V16_HEIGHT && restingLiquidity ? makerRebate(want) : 0n;
1438
+ const got = isNameGive(offer2.give) ? 1n : BigInt(offer2.give.amount);
1439
+ return { deliverable: true, reason: "ok", got, pay: want, fee, rebate };
1440
+ }
1441
+ function isOpenClaimLane(offer2, tip) {
1442
+ return tip >= V13_HEIGHT && offer2.taker === void 0 && !isTokenWant(offer2.want);
1443
+ }
1444
+ function hasLiveClaim(offer2, me, tip) {
1445
+ if (tip < V17_HEIGHT) return false;
1446
+ if (offer2.claimedBy === void 0 || offer2.claimUntilHeight === void 0) return false;
1447
+ if (offer2.claimedBy.toLowerCase() !== me.toLowerCase()) return false;
1448
+ const grace = claimGraceOf(offer2.claimUntilHeight);
1449
+ return tip < offer2.claimUntilHeight + grace;
1450
+ }
1451
+ function fillIsSafe(offer2, me, pay, tip) {
1452
+ const preview = previewFill(offer2, pay);
1453
+ if (offer2.status !== "open") return { safe: false, reason: `offer is ${offer2.status}`, preview };
1454
+ if (offer2.taker !== void 0 && offer2.taker.toLowerCase() !== me.toLowerCase())
1455
+ return { safe: false, reason: "taker-bound offer \u2014 not bound to you", preview };
1456
+ if (isOpenClaimLane(offer2, tip) && !hasLiveClaim(offer2, me, tip))
1457
+ return { safe: false, reason: "open CSD offer \u2014 claim it first and fill while your claim is live", preview };
1458
+ if (isTokenWant(offer2.want)) return { safe: true, reason: "token-priced \u2014 deliverability is the buyer's balance", preview };
1459
+ if (!preview.deliverable) {
1460
+ if (preview.reason === "below-min") return { safe: false, reason: "payment is below the offer minimum", preview };
1461
+ return { safe: false, reason: "this payment would deliver 0 tokens \u2014 refusing (the CSD would be lost)", preview };
1462
+ }
1463
+ return { safe: true, reason: "ok", preview };
1464
+ }
1465
+ function finalizeWinnerCheck(nameState, me, commitHeight) {
1466
+ const m = me.toLowerCase();
1467
+ if (!nameState) return { safe: false, reason: "no reservation on-chain (displaced, swept, or never accepted) \u2014 a finalize now would burn the fee" };
1468
+ if (nameState.owner?.toLowerCase() !== m) return { safe: false, reason: "an earlier committer won this name \u2014 you were outbid" };
1469
+ if (nameState.pending !== true) return { safe: false, reason: "already registered to you \u2014 no second finalize fee is needed" };
1470
+ if (Number(nameState.effectiveHeight) !== Number(commitHeight))
1471
+ return { safe: false, reason: "your reservation was displaced (effective height changed) \u2014 a finalize now would burn the fee" };
1472
+ return { safe: true, reason: "ok" };
1473
+ }
1474
+
1406
1475
  // src/paidto.ts
1407
1476
  function paidToFromOutputs(outputs) {
1408
1477
  const m = /* @__PURE__ */ Object.create(null);
@@ -1507,8 +1576,12 @@ var import_csd_codec4 = require("@inversealtruism/csd-codec");
1507
1576
  deploy,
1508
1577
  epochOf,
1509
1578
  expiredClaimFee,
1579
+ fillIsSafe,
1580
+ finalizeWinnerCheck,
1581
+ hasLiveClaim,
1510
1582
  isName,
1511
1583
  isNameGive,
1584
+ isOpenClaimLane,
1512
1585
  isTokenWant,
1513
1586
  makerRebate,
1514
1587
  mint,
@@ -1528,6 +1601,7 @@ var import_csd_codec4 = require("@inversealtruism/csd-codec");
1528
1601
  parseAmount,
1529
1602
  parseRecord,
1530
1603
  payloadHash,
1604
+ previewFill,
1531
1605
  requiredClaimDepth,
1532
1606
  resolve,
1533
1607
  tokenMeta,
package/dist/index.d.cts CHANGED
@@ -430,9 +430,56 @@ declare function requiredClaimDepth(valueSats: number | bigint, height: number):
430
430
  capped: boolean;
431
431
  };
432
432
 
433
+ /** What a payment of `pay` (base units of CSD, the seller-paid amount to `want.payto`) would DELIVER
434
+ * against a CSD-priced offer, computed with the resolver's exact expressions. Returns the delivered
435
+ * token `got`, the treasury `fee`, and the maker `rebate` — plus a `deliverable` flag that is false
436
+ * exactly when the resolver would reject the fill AFTER the CSD moved (the C3 zero-delivery trap).
437
+ *
438
+ * Only meaningful for CSD-priced token offers (a `want.value`). For a name give, `got` is 1 (a name is
439
+ * indivisible) when `pay >= want.value`. Token-for-token offers (`want.ticker`) return deliverable:false
440
+ * with reason "not-csd-priced" — their deliverability depends on the buyer's balance, out of scope here. */
441
+ interface FillPreview {
442
+ deliverable: boolean;
443
+ reason?: "not-open" | "not-csd-priced" | "below-min" | "zero-delivery" | "ok";
444
+ got: bigint;
445
+ pay: bigint;
446
+ fee: bigint;
447
+ rebate: bigint;
448
+ }
449
+ /** Preview a fill of `offer` paying `payRaw` CSD base units to the seller. Pure; no I/O. */
450
+ declare function previewFill(offer: OfferState, payRaw: bigint | string | number): FillPreview;
451
+ /** Is the offer an OPEN (untaken) CSD-priced offer subject to the v1.7 claim-to-fill gate at `tip`?
452
+ * Such an offer may be filled ONLY by the holder of a LIVE claim (resolve.ts openFillReject:166-171). */
453
+ declare function isOpenClaimLane(offer: OfferState, tip: number): boolean;
454
+ /** Does `me` currently hold a LIVE claim on `offer` at `tip`? Mirrors resolve.ts claimHeld + the
455
+ * who===claimedBy check (:160-169). For a pre-V17 open offer, open fills are banned entirely. */
456
+ declare function hasLiveClaim(offer: OfferState, me: string, tip: number): boolean;
457
+ /** The union verdict a client must clear BEFORE signing a fill of `offer` paying `pay`, as `me`, at `tip`.
458
+ * Closes C2/C3/C4: status open, deliverability >= 1 token, live-claim holdership for the open-CSD lane,
459
+ * and taker match. `safe:true` ⇒ the fill is guaranteed to be accepted by the deterministic gates a
460
+ * payer can verify at signing time (the irreducible timing residual — CLAIM_FILL_GRACE_BLOCKS late mine
461
+ * — is documented, not closable by a preflight). Returns the preview so the caller can size outputs. */
462
+ interface FillSafety {
463
+ safe: boolean;
464
+ reason: string;
465
+ preview: FillPreview;
466
+ }
467
+ declare function fillIsSafe(offer: OfferState, me: string, pay: bigint | string | number, tip: number): FillSafety;
468
+ /** C1: may `me` safely sign the fee-bearing registration `nfinalize` for `nameState` committed at
469
+ * `commitHeight`? The reg fee rides nfinalize; a finalize on a reservation that was displaced or has
470
+ * expired is REJECTED after the fee moved (a burn). Sound by the freeze arithmetic: once a client waits
471
+ * for `tip > effectiveHeight + REG_COMMIT_MAX_BLOCKS` (which the UI's finalizeReady already enforces) no
472
+ * new displacer can appear, so a re-fetch showing "still my live pending reservation at my commit height"
473
+ * guarantees the finalize lands. Pass the AUTHORITATIVE (freshly re-fetched) name record — never a cached
474
+ * one — as `nameState` (undefined = the resolver returns 404 / unregistered, which is a definitive loss). */
475
+ declare function finalizeWinnerCheck(nameState: NameState | null | undefined, me: string, commitHeight: number): {
476
+ safe: boolean;
477
+ reason: string;
478
+ };
479
+
433
480
  declare function paidToFromOutputs(outputs: readonly {
434
481
  addr: string;
435
482
  value: number;
436
483
  }[]): Record<string, string>;
437
484
 
438
- 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, FEE_BPS, FEE_BPS_V16, FINALIZE_TIP_MARGIN, type FillEntry, type Give, HASH_RE, MAX_ACTIVE_CLAIMS, MAX_AMOUNT, MAX_OFFER_EPOCHS, MAX_PENDING_REG, MAX_RECORD_BYTES, 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, REBATE_BPS, REBATE_FLAT, REG_COMMIT_MAX_BLOCKS, REG_FINALIZE_GRACE_BLOCKS, RESERVED_NAMES, SALT_RE, 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, type Want, ZERO_ADDR, bid, buildRecord, canonicalState, claimGraceOf, claimWindowAt, claimWindowOf, deploy, epochOf, expiredClaimFee, isName, isNameGive, isTokenWant, makerRebate, mint, nameClaim, nameCommit, nameCommitRecord, nameFinalize, nameProfile, nameRegFee, nameRenew, nameSet, nameXfer, offer, offerCancelAll, offerExpiryHeightOf, paidToFromOutputs, parseAmount, parseRecord, requiredClaimDepth, resolve, tokenMeta, tradeFee, transfer };
485
+ 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, FEE_BPS, FEE_BPS_V16, FINALIZE_TIP_MARGIN, type FillEntry, type FillPreview, type FillSafety, type Give, HASH_RE, MAX_ACTIVE_CLAIMS, MAX_AMOUNT, MAX_OFFER_EPOCHS, MAX_PENDING_REG, MAX_RECORD_BYTES, 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, REBATE_BPS, REBATE_FLAT, REG_COMMIT_MAX_BLOCKS, REG_FINALIZE_GRACE_BLOCKS, RESERVED_NAMES, SALT_RE, 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, type Want, ZERO_ADDR, bid, buildRecord, canonicalState, claimGraceOf, claimWindowAt, claimWindowOf, deploy, epochOf, expiredClaimFee, fillIsSafe, finalizeWinnerCheck, hasLiveClaim, isName, isNameGive, isOpenClaimLane, isTokenWant, makerRebate, mint, nameClaim, nameCommit, nameCommitRecord, nameFinalize, nameProfile, nameRegFee, nameRenew, nameSet, nameXfer, offer, offerCancelAll, offerExpiryHeightOf, paidToFromOutputs, parseAmount, parseRecord, previewFill, requiredClaimDepth, resolve, tokenMeta, tradeFee, transfer };
package/dist/index.d.ts CHANGED
@@ -430,9 +430,56 @@ declare function requiredClaimDepth(valueSats: number | bigint, height: number):
430
430
  capped: boolean;
431
431
  };
432
432
 
433
+ /** What a payment of `pay` (base units of CSD, the seller-paid amount to `want.payto`) would DELIVER
434
+ * against a CSD-priced offer, computed with the resolver's exact expressions. Returns the delivered
435
+ * token `got`, the treasury `fee`, and the maker `rebate` — plus a `deliverable` flag that is false
436
+ * exactly when the resolver would reject the fill AFTER the CSD moved (the C3 zero-delivery trap).
437
+ *
438
+ * Only meaningful for CSD-priced token offers (a `want.value`). For a name give, `got` is 1 (a name is
439
+ * indivisible) when `pay >= want.value`. Token-for-token offers (`want.ticker`) return deliverable:false
440
+ * with reason "not-csd-priced" — their deliverability depends on the buyer's balance, out of scope here. */
441
+ interface FillPreview {
442
+ deliverable: boolean;
443
+ reason?: "not-open" | "not-csd-priced" | "below-min" | "zero-delivery" | "ok";
444
+ got: bigint;
445
+ pay: bigint;
446
+ fee: bigint;
447
+ rebate: bigint;
448
+ }
449
+ /** Preview a fill of `offer` paying `payRaw` CSD base units to the seller. Pure; no I/O. */
450
+ declare function previewFill(offer: OfferState, payRaw: bigint | string | number): FillPreview;
451
+ /** Is the offer an OPEN (untaken) CSD-priced offer subject to the v1.7 claim-to-fill gate at `tip`?
452
+ * Such an offer may be filled ONLY by the holder of a LIVE claim (resolve.ts openFillReject:166-171). */
453
+ declare function isOpenClaimLane(offer: OfferState, tip: number): boolean;
454
+ /** Does `me` currently hold a LIVE claim on `offer` at `tip`? Mirrors resolve.ts claimHeld + the
455
+ * who===claimedBy check (:160-169). For a pre-V17 open offer, open fills are banned entirely. */
456
+ declare function hasLiveClaim(offer: OfferState, me: string, tip: number): boolean;
457
+ /** The union verdict a client must clear BEFORE signing a fill of `offer` paying `pay`, as `me`, at `tip`.
458
+ * Closes C2/C3/C4: status open, deliverability >= 1 token, live-claim holdership for the open-CSD lane,
459
+ * and taker match. `safe:true` ⇒ the fill is guaranteed to be accepted by the deterministic gates a
460
+ * payer can verify at signing time (the irreducible timing residual — CLAIM_FILL_GRACE_BLOCKS late mine
461
+ * — is documented, not closable by a preflight). Returns the preview so the caller can size outputs. */
462
+ interface FillSafety {
463
+ safe: boolean;
464
+ reason: string;
465
+ preview: FillPreview;
466
+ }
467
+ declare function fillIsSafe(offer: OfferState, me: string, pay: bigint | string | number, tip: number): FillSafety;
468
+ /** C1: may `me` safely sign the fee-bearing registration `nfinalize` for `nameState` committed at
469
+ * `commitHeight`? The reg fee rides nfinalize; a finalize on a reservation that was displaced or has
470
+ * expired is REJECTED after the fee moved (a burn). Sound by the freeze arithmetic: once a client waits
471
+ * for `tip > effectiveHeight + REG_COMMIT_MAX_BLOCKS` (which the UI's finalizeReady already enforces) no
472
+ * new displacer can appear, so a re-fetch showing "still my live pending reservation at my commit height"
473
+ * guarantees the finalize lands. Pass the AUTHORITATIVE (freshly re-fetched) name record — never a cached
474
+ * one — as `nameState` (undefined = the resolver returns 404 / unregistered, which is a definitive loss). */
475
+ declare function finalizeWinnerCheck(nameState: NameState | null | undefined, me: string, commitHeight: number): {
476
+ safe: boolean;
477
+ reason: string;
478
+ };
479
+
433
480
  declare function paidToFromOutputs(outputs: readonly {
434
481
  addr: string;
435
482
  value: number;
436
483
  }[]): Record<string, string>;
437
484
 
438
- 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, FEE_BPS, FEE_BPS_V16, FINALIZE_TIP_MARGIN, type FillEntry, type Give, HASH_RE, MAX_ACTIVE_CLAIMS, MAX_AMOUNT, MAX_OFFER_EPOCHS, MAX_PENDING_REG, MAX_RECORD_BYTES, 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, REBATE_BPS, REBATE_FLAT, REG_COMMIT_MAX_BLOCKS, REG_FINALIZE_GRACE_BLOCKS, RESERVED_NAMES, SALT_RE, 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, type Want, ZERO_ADDR, bid, buildRecord, canonicalState, claimGraceOf, claimWindowAt, claimWindowOf, deploy, epochOf, expiredClaimFee, isName, isNameGive, isTokenWant, makerRebate, mint, nameClaim, nameCommit, nameCommitRecord, nameFinalize, nameProfile, nameRegFee, nameRenew, nameSet, nameXfer, offer, offerCancelAll, offerExpiryHeightOf, paidToFromOutputs, parseAmount, parseRecord, requiredClaimDepth, resolve, tokenMeta, tradeFee, transfer };
485
+ 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, FEE_BPS, FEE_BPS_V16, FINALIZE_TIP_MARGIN, type FillEntry, type FillPreview, type FillSafety, type Give, HASH_RE, MAX_ACTIVE_CLAIMS, MAX_AMOUNT, MAX_OFFER_EPOCHS, MAX_PENDING_REG, MAX_RECORD_BYTES, 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, REBATE_BPS, REBATE_FLAT, REG_COMMIT_MAX_BLOCKS, REG_FINALIZE_GRACE_BLOCKS, RESERVED_NAMES, SALT_RE, 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, type Want, ZERO_ADDR, bid, buildRecord, canonicalState, claimGraceOf, claimWindowAt, claimWindowOf, deploy, epochOf, expiredClaimFee, fillIsSafe, finalizeWinnerCheck, hasLiveClaim, isName, isNameGive, isOpenClaimLane, isTokenWant, makerRebate, mint, nameClaim, nameCommit, nameCommitRecord, nameFinalize, nameProfile, nameRegFee, nameRenew, nameSet, nameXfer, offer, offerCancelAll, offerExpiryHeightOf, paidToFromOutputs, parseAmount, parseRecord, previewFill, requiredClaimDepth, resolve, tokenMeta, tradeFee, transfer };
package/dist/index.js CHANGED
@@ -1262,6 +1262,70 @@ function requiredClaimDepth(valueSats, height) {
1262
1262
  return { depth: max, reversalPct: Math.pow(r, max) * 100, capped: true };
1263
1263
  }
1264
1264
 
1265
+ // src/preflight.ts
1266
+ function previewFill(offer2, payRaw) {
1267
+ const pay = BigInt(payRaw);
1268
+ const zero = { deliverable: false, got: 0n, pay: 0n, fee: 0n, rebate: 0n };
1269
+ if (offer2.status !== "open") return { ...zero, reason: "not-open" };
1270
+ if (isTokenWant(offer2.want)) return { ...zero, reason: "not-csd-priced" };
1271
+ const want = BigInt(offer2.want.value);
1272
+ const feeBps = offer2.feeBps;
1273
+ if (offer2.min !== void 0 && !isNameGive(offer2.give)) {
1274
+ const paidSoFar = BigInt(offer2.paid ?? "0");
1275
+ const remaining = want - paidSoFar;
1276
+ const minV = BigInt(offer2.min);
1277
+ const effMin = remaining < minV ? remaining : minV;
1278
+ if (pay < effMin) return { ...zero, reason: "below-min" };
1279
+ const x = pay < remaining ? pay : remaining;
1280
+ const fee2 = feeBps ? tradeFee(x, feeBps) : 0n;
1281
+ const giveTotal = BigInt(offer2.give.amount);
1282
+ const newPaid = paidSoFar + x;
1283
+ const deliveredSoFar = BigInt(offer2.delivered ?? "0");
1284
+ const out = giveTotal * newPaid / want - deliveredSoFar;
1285
+ if (out === 0n) return { deliverable: false, reason: "zero-delivery", got: 0n, pay: x, fee: fee2, rebate: 0n };
1286
+ return { deliverable: true, reason: "ok", got: out, pay: x, fee: fee2, rebate: 0n };
1287
+ }
1288
+ if (pay < want) return { deliverable: false, reason: "below-min", got: 0n, pay, fee: 0n, rebate: 0n };
1289
+ const fee = feeBps ? tradeFee(want, feeBps) : 0n;
1290
+ const restingLiquidity = offer2.taker !== void 0 && offer2.bid !== void 0 || offer2.height >= V17_HEIGHT && offer2.taker === void 0;
1291
+ const rebate = offer2.height >= V16_HEIGHT && restingLiquidity ? makerRebate(want) : 0n;
1292
+ const got = isNameGive(offer2.give) ? 1n : BigInt(offer2.give.amount);
1293
+ return { deliverable: true, reason: "ok", got, pay: want, fee, rebate };
1294
+ }
1295
+ function isOpenClaimLane(offer2, tip) {
1296
+ return tip >= V13_HEIGHT && offer2.taker === void 0 && !isTokenWant(offer2.want);
1297
+ }
1298
+ function hasLiveClaim(offer2, me, tip) {
1299
+ if (tip < V17_HEIGHT) return false;
1300
+ if (offer2.claimedBy === void 0 || offer2.claimUntilHeight === void 0) return false;
1301
+ if (offer2.claimedBy.toLowerCase() !== me.toLowerCase()) return false;
1302
+ const grace = claimGraceOf(offer2.claimUntilHeight);
1303
+ return tip < offer2.claimUntilHeight + grace;
1304
+ }
1305
+ function fillIsSafe(offer2, me, pay, tip) {
1306
+ const preview = previewFill(offer2, pay);
1307
+ if (offer2.status !== "open") return { safe: false, reason: `offer is ${offer2.status}`, preview };
1308
+ if (offer2.taker !== void 0 && offer2.taker.toLowerCase() !== me.toLowerCase())
1309
+ return { safe: false, reason: "taker-bound offer \u2014 not bound to you", preview };
1310
+ if (isOpenClaimLane(offer2, tip) && !hasLiveClaim(offer2, me, tip))
1311
+ return { safe: false, reason: "open CSD offer \u2014 claim it first and fill while your claim is live", preview };
1312
+ if (isTokenWant(offer2.want)) return { safe: true, reason: "token-priced \u2014 deliverability is the buyer's balance", preview };
1313
+ if (!preview.deliverable) {
1314
+ if (preview.reason === "below-min") return { safe: false, reason: "payment is below the offer minimum", preview };
1315
+ return { safe: false, reason: "this payment would deliver 0 tokens \u2014 refusing (the CSD would be lost)", preview };
1316
+ }
1317
+ return { safe: true, reason: "ok", preview };
1318
+ }
1319
+ function finalizeWinnerCheck(nameState, me, commitHeight) {
1320
+ const m = me.toLowerCase();
1321
+ if (!nameState) return { safe: false, reason: "no reservation on-chain (displaced, swept, or never accepted) \u2014 a finalize now would burn the fee" };
1322
+ if (nameState.owner?.toLowerCase() !== m) return { safe: false, reason: "an earlier committer won this name \u2014 you were outbid" };
1323
+ if (nameState.pending !== true) return { safe: false, reason: "already registered to you \u2014 no second finalize fee is needed" };
1324
+ if (Number(nameState.effectiveHeight) !== Number(commitHeight))
1325
+ return { safe: false, reason: "your reservation was displaced (effective height changed) \u2014 a finalize now would burn the fee" };
1326
+ return { safe: true, reason: "ok" };
1327
+ }
1328
+
1265
1329
  // src/paidto.ts
1266
1330
  function paidToFromOutputs(outputs) {
1267
1331
  const m = /* @__PURE__ */ Object.create(null);
@@ -1374,8 +1438,12 @@ export {
1374
1438
  deploy,
1375
1439
  epochOf,
1376
1440
  expiredClaimFee,
1441
+ fillIsSafe,
1442
+ finalizeWinnerCheck,
1443
+ hasLiveClaim,
1377
1444
  isName,
1378
1445
  isNameGive,
1446
+ isOpenClaimLane,
1379
1447
  isTokenWant,
1380
1448
  makerRebate,
1381
1449
  mint,
@@ -1395,6 +1463,7 @@ export {
1395
1463
  parseAmount,
1396
1464
  parseRecord,
1397
1465
  payloadHash2 as payloadHash,
1466
+ previewFill,
1398
1467
  requiredClaimDepth,
1399
1468
  resolve,
1400
1469
  tokenMeta,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inversealtruism/cairnx-core",
3
- "version": "0.1.33",
3
+ "version": "0.1.34",
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"
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"
49
49
  }
50
50
  }