@arca-network/sdk 1.24.0 → 1.26.0

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/streams.js CHANGED
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.FundingWatchStream = exports.RealmExchangeWatchStream = exports.RealmFillWatchStream = exports.FillWatchStream = exports.TwapWatchStream = exports.ExchangeWatchStream = exports.CandleChartStream = exports.CoverageTracker = exports.TradeWatchStream = exports.OIWatchStream = exports.CandleWatchStream = exports.PriceWatchStream = exports.MaxOrderSizeWatchStream = exports.PnlChartStream = exports.EquityChartStream = exports.ProjectionWatchStream = exports.AggregationWatchStream = exports.ObjectsWatchStream = exports.ObjectWatchStream = exports.BalanceWatchStream = exports.OperationWatchStream = exports.WatchStreamReadyTimeoutError = void 0;
4
4
  exports.getMarketAvailability = getMarketAvailability;
5
+ exports.availabilityDivergenceUsd = availabilityDivergenceUsd;
5
6
  exports.deriveActiveAssetDataFromState = deriveActiveAssetDataFromState;
6
7
  const types_1 = require("./types");
7
8
  const revalue_1 = require("./revalue");
@@ -1457,9 +1458,32 @@ function availabilityFor(exchangeState, market, equity, initialMarginUsed) {
1457
1458
  const rate = parsePositiveNumber(model?.crossDexReservationRate);
1458
1459
  const total = parsePositiveNumber(model?.totalCollateralUsd);
1459
1460
  const targetDex = perpDexIndexOf(market);
1460
- // No declared rule (a single-pool venue), or a term the venue did not send:
1461
- // there is one budget and it is the ordinary one. Never guess a reservation.
1462
- if (!model?.crossDexReservationEnforced || rate <= 0 || total <= 0) {
1461
+ const onNativeDex = targetDex === 0;
1462
+ // No declared rule (a single-pool venue): one budget, and it is the ordinary
1463
+ // one. Never guess a reservation.
1464
+ if (!model?.crossDexReservationEnforced) {
1465
+ return { available: native, crossDex: native, native, enforced: false, rate };
1466
+ }
1467
+ // The rule is enforced but a term needed to evaluate it is missing. Falling
1468
+ // through to `native` here would hand a HIP-3 market the LARGER number — the
1469
+ // one it may not spend — so prefer the venue's own evaluation when it sent
1470
+ // one. Read with an explicit undefined check, not truthiness: a published
1471
+ // "0" is a real answer ("this market can open nothing"), and treating it as
1472
+ // absent is how a $0 market gets advertised as fundable.
1473
+ if (rate <= 0 || total <= 0) {
1474
+ const publishedCrossDex = model.crossDexAvailableUsd;
1475
+ if (publishedCrossDex !== undefined) {
1476
+ const crossDex = Math.max(0, Number.parseFloat(publishedCrossDex) || 0);
1477
+ const publishedNative = model.nativeAvailableUsd;
1478
+ const nativeUsd = publishedNative !== undefined ? Math.max(0, Number.parseFloat(publishedNative) || 0) : native;
1479
+ return {
1480
+ available: onNativeDex ? nativeUsd : crossDex,
1481
+ crossDex,
1482
+ native: nativeUsd,
1483
+ enforced: !onNativeDex,
1484
+ rate,
1485
+ };
1486
+ }
1463
1487
  return { available: native, crossDex: native, native, enforced: false, rate };
1464
1488
  }
1465
1489
  let marginNative = 0;
@@ -1483,7 +1507,6 @@ function availabilityFor(exchangeState, market, equity, initialMarginUsed) {
1483
1507
  // The native dex keeps the ordinary budget; every other dex draws on the
1484
1508
  // shared pool — including one this account already holds a position on,
1485
1509
  // because adding there still has to move collateral into it.
1486
- const onNativeDex = targetDex === 0;
1487
1510
  return {
1488
1511
  available: onNativeDex ? native : crossDex,
1489
1512
  crossDex,
@@ -1492,6 +1515,35 @@ function availabilityFor(exchangeState, market, equity, initialMarginUsed) {
1492
1515
  rate,
1493
1516
  };
1494
1517
  }
1518
+ /**
1519
+ * Signed gap, in USD, between what this SDK derives for `market` and what the
1520
+ * venue published for the same account at the same marks. Positive means the
1521
+ * client is claiming more buying power than the venue does.
1522
+ *
1523
+ * `null` when the venue published nothing to compare against (an older server,
1524
+ * or a venue that declares no cross-dex rule), which is not a divergence.
1525
+ *
1526
+ * Only meaningful on a state that has NOT been re-marked locally: once the
1527
+ * client revalues against newer mids the two are answering at different prices
1528
+ * and are supposed to differ.
1529
+ */
1530
+ function availabilityDivergenceUsd(exchangeState, market) {
1531
+ const model = exchangeState.collateralModel;
1532
+ if (!model?.crossDexReservationEnforced)
1533
+ return null;
1534
+ const onNativeDex = perpDexIndexOf(market) === 0;
1535
+ const published = onNativeDex ? model.nativeAvailableUsd : model.crossDexAvailableUsd;
1536
+ if (published === undefined)
1537
+ return null;
1538
+ const theirs = Number.parseFloat(published);
1539
+ if (!Number.isFinite(theirs))
1540
+ return null;
1541
+ const a = getMarketAvailability(exchangeState, market);
1542
+ const ours = Number.parseFloat(onNativeDex ? a.nativeAvailableUsd : a.crossDexAvailableUsd);
1543
+ if (!Number.isFinite(ours))
1544
+ return null;
1545
+ return ours - theirs;
1546
+ }
1495
1547
  function deriveActiveAssetDataFromState(exchangeState, market, markPx, leverage, side, builderFeeBps = 0, szDecimals = 5, feeScale = 1,
1496
1548
  // Per-asset base MMR resolved by the caller (e.g. from the initial
1497
1549
  // `getActiveAssetData` fetch). Server derives this from the asset's margin
@@ -1659,6 +1711,8 @@ class MaxOrderSizeWatchStream extends WatchStream {
1659
1711
  askRatio = 1;
1660
1712
  bidRatio = 1;
1661
1713
  priceStream;
1714
+ _pendingReason = 'awaiting_exchange_state';
1715
+ _availabilityDivergenceUsd = null;
1662
1716
  constructor(priceStream, options, initialExchangeState, initialPrices = {}) {
1663
1717
  super();
1664
1718
  this.priceStream = priceStream;
@@ -1693,8 +1747,36 @@ class MaxOrderSizeWatchStream extends WatchStream {
1693
1747
  }));
1694
1748
  this.recompute('init');
1695
1749
  }
1750
+ /**
1751
+ * Why no {@link activeAssetData} is available yet, or `null` when it is.
1752
+ *
1753
+ * Read this before treating an absent figure as zero. `awaiting_mark_price`
1754
+ * in particular means the account is fine and the market is simply unpriced
1755
+ * so far — a ticket should hold its sizing controls in a loading state rather
1756
+ * than render a $0 rail, which reads to the user as "you have no money".
1757
+ */
1758
+ get pendingReason() {
1759
+ return this.activeAssetData ? null : this._pendingReason;
1760
+ }
1761
+ /**
1762
+ * How far the local derivation sat from the venue's own published figure at
1763
+ * the last structural push, in USD, or `null` if the venue published none.
1764
+ *
1765
+ * The two are computed from the same inputs at the same marks, so anything
1766
+ * but ~0 means one of the implementations is wrong. This is deliberately
1767
+ * exposed rather than silently reconciled: the cross-dex rule has been
1768
+ * re-derived independently in four SDKs and has been wrong before, and a
1769
+ * divergence that is quietly papered over is one nobody fixes.
1770
+ */
1771
+ get availabilityDivergenceUsd() {
1772
+ return this._availabilityDivergenceUsd;
1773
+ }
1696
1774
  updateExchangeState(state) {
1697
1775
  this.exchangeState = state;
1776
+ // Compare BEFORE recompute so the divergence reflects this push. Both
1777
+ // sides are evaluated at the server's marks here — the state has not been
1778
+ // re-marked yet — which is the only instant at which they are comparable.
1779
+ this._availabilityDivergenceUsd = availabilityDivergenceUsd(state, this.opts.market);
1698
1780
  this.recompute('exchange');
1699
1781
  }
1700
1782
  /** Update the per-asset maintenance margin rate used to populate
@@ -1731,12 +1813,42 @@ class MaxOrderSizeWatchStream extends WatchStream {
1731
1813
  this.unsubs.push(fn);
1732
1814
  }
1733
1815
  recompute(event) {
1816
+ if (!this.exchangeState) {
1817
+ this._pendingReason = 'awaiting_exchange_state';
1818
+ return;
1819
+ }
1734
1820
  const markPx = parsePositiveNumber(this.prices[this.opts.market]);
1735
- if (!this.exchangeState || markPx <= 0)
1821
+ if (markPx <= 0) {
1822
+ // No mid for this market yet. Emitting nothing at all is indistinguishable
1823
+ // from "$0 available" to a caller reading `activeAssetData`, and a ticket
1824
+ // that renders an empty slider on the strength of it tells the user they
1825
+ // have no money when the truth is that we have not priced the market.
1826
+ this._pendingReason = 'awaiting_mark_price';
1736
1827
  return;
1737
- const next = deriveActiveAssetDataFromState(this.exchangeState, this.opts.market, markPx, this.opts.leverage, this.opts.side, this.opts.builderFeeBps, this.opts.szDecimals, this.opts.feeScale, this.maintenanceMarginRate, this.marginTiers, this.askRatio, this.bidRatio);
1738
- if (!next)
1828
+ }
1829
+ // Re-mark the book against current mids before deriving.
1830
+ //
1831
+ // This is load-bearing for HIP-3 markets and not merely a freshness nicety:
1832
+ // the cross-dex reservation is `max(margin, rate x NOTIONAL)` of the
1833
+ // venue-native position, and notional is read off `positionValue`. A book
1834
+ // left at the marks of the last structural push therefore holds the shared
1835
+ // pool still while the price it depends on moves — so NVIDIA's buying power
1836
+ // would sit at a stale number until the next fill or funding event, which
1837
+ // on a quiet account can be hours. `ExchangeWatchStream` has always
1838
+ // revalued on every mid tick; this stream did not, which is the defect.
1839
+ //
1840
+ // `totalCollateralUsd` is spot cash and price-invariant by construction
1841
+ // (see CollateralModel), so re-marking positions is the whole of what has
1842
+ // to move.
1843
+ const state = Object.keys(this.prices).length > 0
1844
+ ? (0, revalue_1.revalueExchangeState)(this.exchangeState, this.prices)
1845
+ : this.exchangeState;
1846
+ const next = deriveActiveAssetDataFromState(state, this.opts.market, markPx, this.opts.leverage, this.opts.side, this.opts.builderFeeBps, this.opts.szDecimals, this.opts.feeScale, this.maintenanceMarginRate, this.marginTiers, this.askRatio, this.bidRatio);
1847
+ if (!next) {
1848
+ this._pendingReason = 'awaiting_exchange_state';
1739
1849
  return;
1850
+ }
1851
+ this._pendingReason = null;
1740
1852
  this.activeAssetData = next;
1741
1853
  this.setState('connected');
1742
1854
  this.emit({ activeAssetData: next, event });