@dimes-dot-fi/sdk 1.4.3 → 1.5.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/{aliases-C2l_JZX_.d.cts → aliases-ByZ2DcA5.d.cts} +235 -1
- package/dist/{aliases-C2l_JZX_.d.ts → aliases-ByZ2DcA5.d.ts} +235 -1
- package/dist/{chunk-SGA6OZEU.mjs → chunk-3OPRSKCY.mjs} +18 -2
- package/dist/chunk-3OPRSKCY.mjs.map +1 -0
- package/dist/{chunk-DYPABUKC.cjs → chunk-72LTVPD2.cjs} +16 -1
- package/dist/chunk-72LTVPD2.cjs.map +1 -0
- package/dist/{chunk-BVILILIV.mjs → chunk-PZCBUVPD.mjs} +16 -1
- package/dist/chunk-PZCBUVPD.mjs.map +1 -0
- package/dist/{chunk-COSLZ5TM.cjs → chunk-Y5WQ3UWF.cjs} +21 -5
- package/dist/chunk-Y5WQ3UWF.cjs.map +1 -0
- package/dist/contract/index.cjs +13 -13
- package/dist/contract/index.d.cts +3 -3
- package/dist/contract/index.d.ts +3 -3
- package/dist/contract/index.mjs +1 -1
- package/dist/{dimes-client-u5wLYVfp.d.ts → dimes-client-B-thu7VQ.d.cts} +18 -3
- package/dist/{dimes-client-ty6xwk0b.d.cts → dimes-client-CerC9mTr.d.ts} +18 -3
- package/dist/{dimes-error-5ldDx2_G.d.cts → dimes-error-BY5qVGZC.d.cts} +1 -1
- package/dist/{dimes-error-D2RVknPr.d.ts → dimes-error-CrvPuFzB.d.ts} +1 -1
- package/dist/index.cjs +88 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +138 -8
- package/dist/index.d.ts +138 -8
- package/dist/index.mjs +85 -3
- package/dist/index.mjs.map +1 -1
- package/dist/{quote-GCNVcEoo.d.ts → quote-Czq3Selh.d.ts} +2 -2
- package/dist/{quote-DoRJUXld.d.cts → quote-quIOosIv.d.cts} +2 -2
- package/dist/react/index.cjs +4 -4
- package/dist/react/index.d.cts +3 -3
- package/dist/react/index.d.ts +3 -3
- package/dist/react/index.mjs +2 -2
- package/dist/{types-CM14Dx5b.d.cts → types-2bGyrtqd.d.cts} +1 -1
- package/dist/{types-CVcrVq0A.d.ts → types-CAuPxEwO.d.ts} +1 -1
- package/dist/ws/index.d.cts +3 -3
- package/dist/ws/index.d.ts +3 -3
- package/package.json +1 -1
- package/dist/chunk-BVILILIV.mjs.map +0 -1
- package/dist/chunk-COSLZ5TM.cjs.map +0 -1
- package/dist/chunk-DYPABUKC.cjs.map +0 -1
- package/dist/chunk-SGA6OZEU.mjs.map +0 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
export { A as ApiKeyAuth, a as ApiKeyAuthOptions, b as AuthProvider, C as CorrectedField, D as DimesClient, c as DimesClientOptions, G as
|
|
2
|
-
export { D as DimesApiError, a as DimesContractError, b as DimesError } from './dimes-error-
|
|
3
|
-
import { C as CreateOfferParams, O as Offer, M as Market, P as Position } from './aliases-
|
|
4
|
-
export { a as CamelizeKeys, b as CloseAttempt, c as ClosedPosition, d as ContractInfo, e as CreateTokenResult, f as CustomerLimit, g as
|
|
5
|
-
import { Q as QuoteParams, a as QuoteOptions, b as QuoteResult } from './quote-
|
|
6
|
-
export { M as MarketMovedEvent, S as Side } from './quote-
|
|
7
|
-
export { P as PositionEvent, a as PositionEventType, p as positionEventTypes } from './types-
|
|
1
|
+
export { A as ApiKeyAuth, a as ApiKeyAuthOptions, b as AuthProvider, C as CorrectedField, D as DimesClient, c as DimesClientOptions, G as GetFeeRatesParams, d as GetMarketsParams, e as GetPositionsParams, H as HintAdjustment, J as JwtAuth, f as JwtAuthOptions, M as MarketSort, P as Paginated, Q as QuoteHint, h as hintAdjustment, m as marketMovedCodes, q as quoteErrorHint } from './dimes-client-CerC9mTr.js';
|
|
2
|
+
export { D as DimesApiError, a as DimesContractError, b as DimesError } from './dimes-error-CrvPuFzB.js';
|
|
3
|
+
import { C as CreateOfferParams, O as Offer, M as Market, P as Position } from './aliases-ByZ2DcA5.js';
|
|
4
|
+
export { a as CamelizeKeys, b as CloseAttempt, c as ClosedPosition, d as ContractInfo, e as CreateTokenResult, f as CustomerLimit, F as FeeRates, g as FeeRatesMarket, h as FeeRatesOriginationTier, i as FeeReport, j as FeeReportParams, k as MarketFees, l as MarketLeverage, m as MarketMaxLeveragePerNotional, n as MarketPrices, o as MarketSidedEligibility, p as MarketSidedMaxLeveragePerNotional, q as OpenPosition, r as OriginationTier, s as PositionClosedFees, t as PositionCurrent, u as PositionEntry, v as PositionFailure, w as PositionOpenFees, x as PositionResult, y as PositionRisk, z as PositionTiming, A as PositionUnwind, B as PositionUnwindList, D as isClosedPosition, E as isOpenPosition, G as leverageMaxBps } from './aliases-ByZ2DcA5.js';
|
|
5
|
+
import { Q as QuoteParams, a as QuoteOptions, b as QuoteResult } from './quote-Czq3Selh.js';
|
|
6
|
+
export { M as MarketMovedEvent, S as Side } from './quote-Czq3Selh.js';
|
|
7
|
+
export { P as PositionEvent, a as PositionEventType, p as positionEventTypes } from './types-CAuPxEwO.js';
|
|
8
8
|
|
|
9
9
|
type Params = Record<string, unknown> | null;
|
|
10
10
|
|
|
@@ -52,6 +52,39 @@ declare function maxLeverageBpsAtNotional(market: Market, side: Side, notionalUs
|
|
|
52
52
|
*/
|
|
53
53
|
declare function maxViableLeverageBpsForCollateral(market: Market, side: Side, collateralUsd: number): number;
|
|
54
54
|
|
|
55
|
+
/**
|
|
56
|
+
* One leverage-tiered origination-fee rate. `maxLeverageBps` is the inclusive
|
|
57
|
+
* upper bound (in basis points) of leverage covered by this tier; `feeBps` is
|
|
58
|
+
* the protocol origination fee charged for any leverage at or below that bound.
|
|
59
|
+
* Tiers must be supplied in ascending `maxLeverageBps` order; the final tier
|
|
60
|
+
* acts as the catch-all for the highest leverages.
|
|
61
|
+
*/
|
|
62
|
+
interface OriginationFeeTier {
|
|
63
|
+
maxLeverageBps: number;
|
|
64
|
+
feeBps: number;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Resolve the protocol origination fee rate (bps) for a given leverage from an
|
|
68
|
+
* ordered list of leverage tiers. Returns the `feeBps` of the first tier whose
|
|
69
|
+
* `maxLeverageBps >= leverageBps`. If no tier matches (leverage exceeds every
|
|
70
|
+
* bound) the last tier is used as the catch-all. The caller fetches the tiers
|
|
71
|
+
* from the `fee-rates` API; the math is pure.
|
|
72
|
+
*
|
|
73
|
+
* Note: this returns the PROTOCOL rate only — add `partnerOriginationFeeBps`
|
|
74
|
+
* separately (see {@link resolveOriginationFeeBps}).
|
|
75
|
+
*/
|
|
76
|
+
declare function resolveProtocolOriginationFeeBps(tiers: readonly OriginationFeeTier[], leverageBps: number): number;
|
|
77
|
+
/**
|
|
78
|
+
* Combined origination fee rate (bps) = protocol tier rate + partner add-on.
|
|
79
|
+
* Mirrors the server: the protocol rate is leverage-tiered, the partner rate is
|
|
80
|
+
* a flat add-on supplied by the partner's `fee-rates` config.
|
|
81
|
+
*/
|
|
82
|
+
declare function resolveOriginationFeeBps(tiers: readonly OriginationFeeTier[], leverageBps: number, partnerOriginationFeeBps: number): number;
|
|
83
|
+
/**
|
|
84
|
+
* Origination fee in USDC units (1_000_000 = $1), floored, matching the server:
|
|
85
|
+
* `floor(notionalUsdcUnits * combinedOriginationFeeBps / 10_000)`.
|
|
86
|
+
*/
|
|
87
|
+
declare function computeOriginationFeeUsdcUnits(notionalUsdcUnits: number, combinedOriginationFeeBps: number): number;
|
|
55
88
|
interface OriginationFeeBreakdown {
|
|
56
89
|
totalBps: number;
|
|
57
90
|
totalUsd: number;
|
|
@@ -62,4 +95,101 @@ interface OriginationFeeBreakdown {
|
|
|
62
95
|
}
|
|
63
96
|
declare function getOriginationFeeBreakdown(position: Position): OriginationFeeBreakdown;
|
|
64
97
|
|
|
65
|
-
|
|
98
|
+
/**
|
|
99
|
+
* Inputs to the Polymarket trading-fee curve. All rates are basis points; the
|
|
100
|
+
* caller fetches `feeRateBps`, `feeExponent`, and `builderTakerFeeRateBps` from
|
|
101
|
+
* the `fee-rates` API (snapshotted server-side as `Offer.polymarketFeeRateBps`
|
|
102
|
+
* / `polymarketFeeExponent` / `polymarketBuilderFeeRateBps`).
|
|
103
|
+
*/
|
|
104
|
+
interface PolymarketTradingFeeInput {
|
|
105
|
+
notionalUsdcUnits: number;
|
|
106
|
+
priceUsd: number;
|
|
107
|
+
feeRateBps: number;
|
|
108
|
+
feeExponent?: number;
|
|
109
|
+
builderTakerFeeRateBps?: number;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Polymarket open/close trading fee in USDC units (1_000_000 = $1).
|
|
113
|
+
*
|
|
114
|
+
* Matches the canonical formula (docs: position-math/09-exchange-trading-fees):
|
|
115
|
+
*
|
|
116
|
+
* ```
|
|
117
|
+
* protocol = feeRateBps / 10_000 * C * (p * (1 - p)) ^ feeExponent * 1e6
|
|
118
|
+
* builder = builderTakerFeeRateBps / 10_000 * notionalUsdc
|
|
119
|
+
* fee = ceil(protocol + builder)
|
|
120
|
+
* ```
|
|
121
|
+
*
|
|
122
|
+
* where `C` = contracts = notionalUsd / p, `p` = price in dollars (0..1). The
|
|
123
|
+
* curvature term peaks at p = 0.5 and is symmetric; the flat builder term does
|
|
124
|
+
* not shrink at price extremes. `feeExponent` defaults to 1 (standard quadratic
|
|
125
|
+
* curvature); some markets use 0 (flat `feeRate * C`). `builderTakerFeeRateBps`
|
|
126
|
+
* defaults to 0 (Bloom's own operator builder code is always 0-fee).
|
|
127
|
+
*/
|
|
128
|
+
declare function computePolymarketTradingFee(input: PolymarketTradingFeeInput): number;
|
|
129
|
+
/**
|
|
130
|
+
* Expected position size in token units (1_000_000 = 1 whole token) for a given
|
|
131
|
+
* notional and entry price, optionally discounted by slippage. A token redeems
|
|
132
|
+
* at $1 on a win, so token units are numerically equal to USDC units.
|
|
133
|
+
*
|
|
134
|
+
* `tokens = notionalUsd / entryPrice`, then scaled down by `slippageBps`.
|
|
135
|
+
* Floored to whole token units. This is an at-quote estimate of the offer's
|
|
136
|
+
* `minExpectedPositionTokenUnits`; the server is authoritative.
|
|
137
|
+
*/
|
|
138
|
+
declare function expectedPositionTokenUnits(notionalUsdcUnits: number, entryPriceUsd: number, slippageBps?: number): number;
|
|
139
|
+
/**
|
|
140
|
+
* Estimated base liquidation price (deterministic, at-entry closed form).
|
|
141
|
+
*
|
|
142
|
+
* **This is an estimate, not the server's TWAP solver result.** It computes the
|
|
143
|
+
* at-entry base liquidation price (F = 0, no safety margin) per the docs
|
|
144
|
+
* (position-math/04-liquidation):
|
|
145
|
+
*
|
|
146
|
+
* ```
|
|
147
|
+
* P_liq_base = entryPrice * (L - 1) / L * (1 + liquidationFeeBps / 10_000)
|
|
148
|
+
* ```
|
|
149
|
+
*
|
|
150
|
+
* where `L = leverageBps / 10_000`. At 1x leverage the borrowed capital is zero
|
|
151
|
+
* so the liquidation price is zero. `entryPriceUsd` is in dollars; the result is
|
|
152
|
+
* in the same units. The live server liquidation price drifts above this as the
|
|
153
|
+
* lifetime fee `F` accrues and includes a safety margin.
|
|
154
|
+
*/
|
|
155
|
+
declare function estimateLiquidationPrice(entryPriceUsd: number, leverageBps: number, liquidationFeeBps: number): number;
|
|
156
|
+
/**
|
|
157
|
+
* Inputs for {@link computeMaxGain}. All amounts are in USDC units
|
|
158
|
+
* (1_000_000 = $1) except `positionTokenUnits` (token units, 1_000_000 = 1
|
|
159
|
+
* token) which is numerically equal to its settlement USDC value.
|
|
160
|
+
*/
|
|
161
|
+
interface MaxGainInput {
|
|
162
|
+
positionTokenUnits: number;
|
|
163
|
+
notionalUsdcUnits: number;
|
|
164
|
+
expectedOpenTradingFeeUsdcUnits: number;
|
|
165
|
+
originationFeeUsdcUnits: number;
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Result of {@link computeMaxGain}. All amounts in USDC units (1_000_000 = $1).
|
|
169
|
+
* Gains are profit OVER principal (notional = loan + collateral) and may be
|
|
170
|
+
* negative — they are signed and never clamped.
|
|
171
|
+
*/
|
|
172
|
+
interface MaxGainResult {
|
|
173
|
+
fullValueOnWinUsdcUnits: number;
|
|
174
|
+
grossMaxGainUsdcUnits: number;
|
|
175
|
+
netMaxGainUsdcUnits: number;
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Maximum gain (gross and net) for a winning settlement exit — profit over
|
|
179
|
+
* principal. On a win each position token redeems at $1 (CTF settlement), so
|
|
180
|
+
* the full value equals `positionTokenUnits` and there is NO exit trading fee.
|
|
181
|
+
*
|
|
182
|
+
* ```
|
|
183
|
+
* fullValueOnWin = positionTokenUnits
|
|
184
|
+
* grossMaxGain = fullValueOnWin - notionalUsdcUnits
|
|
185
|
+
* netMaxGain = grossMaxGain - expectedOpenTradingFee - originationFee
|
|
186
|
+
* ```
|
|
187
|
+
*
|
|
188
|
+
* Lifetime fees are excluded, so net max gain is an upper bound (a position held
|
|
189
|
+
* to settlement accrues lifetime fees that reduce realized profit). Gains are
|
|
190
|
+
* signed — a position whose principal exceeds its winning redemption value
|
|
191
|
+
* yields a negative max gain.
|
|
192
|
+
*/
|
|
193
|
+
declare function computeMaxGain(input: MaxGainInput): MaxGainResult;
|
|
194
|
+
|
|
195
|
+
export { CreateOfferParams, Market, type MaxGainInput, type MaxGainResult, Offer, type OriginationFeeBreakdown, type OriginationFeeTier, type PolymarketTradingFeeInput, Position, QuoteOptions, QuoteParams, QuoteResult, type SideEligibility, type SidedEligibility, buildQuoteParams, computeMaxGain, computeOriginationFeeUsdcUnits, computePolymarketTradingFee, defaultSide, estimateLiquidationPrice, executeQuote, expectedPositionTokenUnits, formatErrorMessage, getOriginationFeeBreakdown, getSidedEligibility, isFullyClosed, isFullyOpen, maxLeverageBpsAtNotional, maxViableLeverageBpsForCollateral, rejectionReasonShort, rejectionReasonText, resolveFriendlyMessage, resolveOriginationFeeBps, resolveProtocolOriginationFeeBps };
|
package/dist/index.mjs
CHANGED
|
@@ -4,14 +4,14 @@ import {
|
|
|
4
4
|
hintAdjustment,
|
|
5
5
|
marketMovedCodes,
|
|
6
6
|
quoteErrorHint
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-3OPRSKCY.mjs";
|
|
8
8
|
import {
|
|
9
9
|
DimesApiError,
|
|
10
10
|
DimesContractError,
|
|
11
11
|
DimesError,
|
|
12
12
|
formatErrorMessage,
|
|
13
13
|
resolveFriendlyMessage
|
|
14
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-PZCBUVPD.mjs";
|
|
15
15
|
import {
|
|
16
16
|
positionEventTypes
|
|
17
17
|
} from "./chunk-4MO3HKMS.mjs";
|
|
@@ -186,6 +186,16 @@ var DimesClient = class {
|
|
|
186
186
|
async getLimits() {
|
|
187
187
|
return this.http.request("/v1/prediction-markets/limits");
|
|
188
188
|
}
|
|
189
|
+
async getFeeRates(params) {
|
|
190
|
+
const query = params ? buildQueryFromEntries(Object.entries(params)) : "";
|
|
191
|
+
return this.http.request(`/v1/prediction-markets/fee-rates${query}`);
|
|
192
|
+
}
|
|
193
|
+
async getFeeReport(params) {
|
|
194
|
+
return this.http.request("/v1/prediction-markets/fee-reports", {
|
|
195
|
+
method: "POST",
|
|
196
|
+
body: JSON.stringify(decamelizeKeys(params))
|
|
197
|
+
});
|
|
198
|
+
}
|
|
189
199
|
};
|
|
190
200
|
|
|
191
201
|
// src/client/auth.ts
|
|
@@ -421,6 +431,25 @@ function maxViableLeverageBpsForCollateral(market, side, collateralUsd) {
|
|
|
421
431
|
}
|
|
422
432
|
|
|
423
433
|
// src/utils/fees.ts
|
|
434
|
+
var BPS_DIVISOR = 1e4;
|
|
435
|
+
function resolveProtocolOriginationFeeBps(tiers, leverageBps) {
|
|
436
|
+
const lastTier = tiers[tiers.length - 1];
|
|
437
|
+
if (!lastTier) {
|
|
438
|
+
return 0;
|
|
439
|
+
}
|
|
440
|
+
for (const tier of tiers) {
|
|
441
|
+
if (leverageBps <= tier.maxLeverageBps) {
|
|
442
|
+
return tier.feeBps;
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
return lastTier.feeBps;
|
|
446
|
+
}
|
|
447
|
+
function resolveOriginationFeeBps(tiers, leverageBps, partnerOriginationFeeBps) {
|
|
448
|
+
return resolveProtocolOriginationFeeBps(tiers, leverageBps) + partnerOriginationFeeBps;
|
|
449
|
+
}
|
|
450
|
+
function computeOriginationFeeUsdcUnits(notionalUsdcUnits, combinedOriginationFeeBps) {
|
|
451
|
+
return Math.floor(notionalUsdcUnits * combinedOriginationFeeBps / BPS_DIVISOR);
|
|
452
|
+
}
|
|
424
453
|
function getEntry(position) {
|
|
425
454
|
return position.entry;
|
|
426
455
|
}
|
|
@@ -442,6 +471,52 @@ function getOriginationFeeBreakdown(position) {
|
|
|
442
471
|
partnerUsd
|
|
443
472
|
};
|
|
444
473
|
}
|
|
474
|
+
|
|
475
|
+
// src/utils/max-gain.ts
|
|
476
|
+
var BPS_DIVISOR2 = 1e4;
|
|
477
|
+
var USDC_UNITS_PER_USD = 1e6;
|
|
478
|
+
var TOKEN_UNITS_PER_TOKEN = 1e6;
|
|
479
|
+
function computePolymarketTradingFee(input) {
|
|
480
|
+
const { notionalUsdcUnits, priceUsd, feeRateBps } = input;
|
|
481
|
+
const feeExponent = input.feeExponent ?? 1;
|
|
482
|
+
const builderTakerFeeRateBps = input.builderTakerFeeRateBps ?? 0;
|
|
483
|
+
if (priceUsd <= 0) {
|
|
484
|
+
return 0;
|
|
485
|
+
}
|
|
486
|
+
const notionalUsd = notionalUsdcUnits / USDC_UNITS_PER_USD;
|
|
487
|
+
const contracts = notionalUsd / priceUsd;
|
|
488
|
+
const curvature = (priceUsd * (1 - priceUsd)) ** feeExponent;
|
|
489
|
+
const protocolFeeUsdcUnits = feeRateBps / BPS_DIVISOR2 * contracts * curvature * USDC_UNITS_PER_USD;
|
|
490
|
+
const builderFeeUsdcUnits = builderTakerFeeRateBps / BPS_DIVISOR2 * notionalUsdcUnits;
|
|
491
|
+
return Math.ceil(protocolFeeUsdcUnits + builderFeeUsdcUnits);
|
|
492
|
+
}
|
|
493
|
+
function expectedPositionTokenUnits(notionalUsdcUnits, entryPriceUsd, slippageBps = 0) {
|
|
494
|
+
if (entryPriceUsd <= 0) {
|
|
495
|
+
return 0;
|
|
496
|
+
}
|
|
497
|
+
const notionalUsd = notionalUsdcUnits / USDC_UNITS_PER_USD;
|
|
498
|
+
const tokens = notionalUsd / entryPriceUsd;
|
|
499
|
+
const slippageFactor = (BPS_DIVISOR2 - slippageBps) / BPS_DIVISOR2;
|
|
500
|
+
return Math.floor(tokens * slippageFactor * TOKEN_UNITS_PER_TOKEN);
|
|
501
|
+
}
|
|
502
|
+
function estimateLiquidationPrice(entryPriceUsd, leverageBps, liquidationFeeBps) {
|
|
503
|
+
const leverage = leverageBps / BPS_DIVISOR2;
|
|
504
|
+
if (leverage <= 1) {
|
|
505
|
+
return 0;
|
|
506
|
+
}
|
|
507
|
+
const loanPerToken = entryPriceUsd * ((leverage - 1) / leverage);
|
|
508
|
+
return loanPerToken * (1 + liquidationFeeBps / BPS_DIVISOR2);
|
|
509
|
+
}
|
|
510
|
+
function computeMaxGain(input) {
|
|
511
|
+
const fullValueOnWinUsdcUnits = input.positionTokenUnits;
|
|
512
|
+
const grossMaxGainUsdcUnits = fullValueOnWinUsdcUnits - input.notionalUsdcUnits;
|
|
513
|
+
const netMaxGainUsdcUnits = grossMaxGainUsdcUnits - input.expectedOpenTradingFeeUsdcUnits - input.originationFeeUsdcUnits;
|
|
514
|
+
return {
|
|
515
|
+
fullValueOnWinUsdcUnits,
|
|
516
|
+
grossMaxGainUsdcUnits,
|
|
517
|
+
netMaxGainUsdcUnits
|
|
518
|
+
};
|
|
519
|
+
}
|
|
445
520
|
export {
|
|
446
521
|
ApiKeyAuth,
|
|
447
522
|
DimesApiError,
|
|
@@ -450,8 +525,13 @@ export {
|
|
|
450
525
|
DimesError,
|
|
451
526
|
JwtAuth,
|
|
452
527
|
buildQuoteParams,
|
|
528
|
+
computeMaxGain,
|
|
529
|
+
computeOriginationFeeUsdcUnits,
|
|
530
|
+
computePolymarketTradingFee,
|
|
453
531
|
defaultSide,
|
|
532
|
+
estimateLiquidationPrice,
|
|
454
533
|
executeQuote,
|
|
534
|
+
expectedPositionTokenUnits,
|
|
455
535
|
formatErrorMessage,
|
|
456
536
|
getOriginationFeeBreakdown,
|
|
457
537
|
getSidedEligibility,
|
|
@@ -468,6 +548,8 @@ export {
|
|
|
468
548
|
quoteErrorHint,
|
|
469
549
|
rejectionReasonShort,
|
|
470
550
|
rejectionReasonText,
|
|
471
|
-
resolveFriendlyMessage
|
|
551
|
+
resolveFriendlyMessage,
|
|
552
|
+
resolveOriginationFeeBps,
|
|
553
|
+
resolveProtocolOriginationFeeBps
|
|
472
554
|
};
|
|
473
555
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client/dimes-client.ts","../src/client/http.ts","../src/client/auth.ts","../src/types/aliases.ts","../src/utils/eligibility.ts","../src/utils/leverage.ts","../src/utils/fees.ts"],"sourcesContent":["import { decamelizeKeys } from \"humps\";\nimport type {\n ContractInfo,\n CreateOfferParams,\n CustomerLimit,\n Market,\n Offer,\n Paginated,\n Position,\n PositionTransactions,\n} from \"../types\";\nimport type { AuthProvider } from \"./auth\";\nimport { HttpClient } from \"./http\";\n\nexport interface DimesClientOptions {\n baseUrl?: string;\n auth: AuthProvider;\n fetch?: typeof globalThis.fetch;\n maxRetries?: number;\n maxRetryDelayMs?: number;\n}\n\nexport type MarketSort = \"ticker_asc\" | \"depth_desc\" | \"discovered_at_desc\";\n\nexport interface GetMarketsParams {\n cursor?: string;\n limit?: number;\n category?: string;\n status?: string;\n provider?: \"polymarket\" | \"kalshi\";\n sort?: MarketSort;\n}\n\nexport interface GetPositionsParams {\n cursor?: string;\n limit?: number;\n status?: \"open\" | \"closed\";\n}\n\nfunction buildQueryFromEntries(entries: [string, unknown][]): string {\n const filtered = entries.filter(([, v]) => v !== undefined && v !== null);\n if (filtered.length === 0) {\n return \"\";\n }\n\n const search = new URLSearchParams();\n for (const [key, value] of filtered) {\n search.set(\n key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`),\n String(value),\n );\n }\n\n return `?${search.toString()}`;\n}\n\nexport class DimesClient {\n private readonly http: HttpClient;\n\n constructor(options: DimesClientOptions) {\n this.http = new HttpClient({\n baseUrl: options.baseUrl ?? \"https://api.dimes.fi\",\n auth: options.auth,\n fetch: options.fetch,\n maxRetries: options.maxRetries,\n maxRetryDelayMs: options.maxRetryDelayMs,\n });\n }\n\n public async getMarkets(params?: GetMarketsParams): Promise<Paginated<Market>> {\n const query = params ? buildQueryFromEntries(Object.entries(params)) : \"\";\n return this.http.request<Paginated<Market>>(`/v1/prediction-markets/markets${query}`);\n }\n\n public async getMarket(ticker: string): Promise<Market> {\n return this.http.request<Market>(`/v1/prediction-markets/markets/${encodeURIComponent(ticker)}`);\n }\n\n public async createDraftQuote(params: CreateOfferParams): Promise<Offer> {\n return this.http.request<Offer>(\"/v1/prediction-markets/draft-quotes\", {\n method: \"POST\",\n body: JSON.stringify(decamelizeKeys(params)),\n });\n }\n\n public async promoteDraftQuote(draftId: string): Promise<Offer> {\n return this.http.request<Offer>(`/v1/prediction-markets/promoted-quotes/${encodeURIComponent(draftId)}`, {\n method: \"POST\",\n });\n }\n\n public async createQuote(params: CreateOfferParams): Promise<Offer> {\n return this.http.request<Offer>(\"/v1/prediction-markets/quotes\", {\n method: \"POST\",\n body: JSON.stringify(decamelizeKeys(params)),\n });\n }\n\n public async getPositions(params?: GetPositionsParams): Promise<Position[]> {\n const query = params ? buildQueryFromEntries(Object.entries(params)) : \"\";\n return this.http.requestList<Position>(`/v1/prediction-markets/positions${query}`);\n }\n\n public async getPositionTransactions(positionId: string): Promise<PositionTransactions> {\n return this.http.request<PositionTransactions>(\n `/v1/prediction-markets/positions/${encodeURIComponent(positionId)}/transactions`,\n );\n }\n\n public async cancelPosition(positionId: string): Promise<void> {\n await this.http.request<unknown>(`/v1/prediction-markets/positions/${encodeURIComponent(positionId)}/cancel`, {\n method: \"POST\",\n });\n }\n\n public async getContractInfo(): Promise<ContractInfo> {\n return this.http.request<ContractInfo>(\"/v1/prediction-markets/contract-info\");\n }\n\n public async getLimits(): Promise<CustomerLimit> {\n return this.http.request<CustomerLimit>(\"/v1/prediction-markets/limits\");\n }\n}\n","import { camelizeKeys, type Camelized } from \"humps\";\nimport { DimesApiError } from \"../errors/dimes-error\";\nimport type { AuthProvider } from \"./auth\";\n\nexport type { Camelized };\n\ninterface ApiErrorBody {\n error?: {\n type?: string;\n code?: string;\n message: string;\n params?: Record<string, unknown>;\n };\n}\n\nconst HTTP_UNAUTHORIZED = 401;\nconst HTTP_TOO_MANY_REQUESTS = 429;\nconst DEFAULT_MAX_RETRIES = 3;\nconst DEFAULT_MAX_RETRY_DELAY_MS = 60_000;\nconst DEFAULT_RETRY_DELAY_MS = 1000;\nconst BACKOFF_FACTOR = 2;\nconst MS_PER_SECOND = 1000;\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction parseRetryAfterMs(header: string | null, attempt: number): number {\n const fallbackMs = DEFAULT_RETRY_DELAY_MS * BACKOFF_FACTOR ** attempt;\n if (!header) {\n return fallbackMs;\n }\n\n const seconds = Number(header);\n if (!Number.isNaN(seconds) && seconds >= 0) {\n return seconds * MS_PER_SECOND;\n }\n\n const dateMs = Date.parse(header);\n if (!Number.isNaN(dateMs)) {\n return Math.max(0, dateMs - Date.now());\n }\n\n return fallbackMs;\n}\n\n// eslint-disable-next-line complexity\nasync function throwFromResponse(response: Response): Promise<never> {\n const rawBody = await response.text();\n let parsed: ApiErrorBody | null;\n try {\n parsed = rawBody ? (JSON.parse(rawBody) as ApiErrorBody) : null;\n } catch {\n parsed = null;\n }\n\n const code = parsed?.error?.code ?? \"unknown_error\";\n const type = parsed?.error?.type ?? null;\n const message = parsed?.error?.message ?? `API error ${response.status}`;\n const rawParams = parsed?.error?.params;\n const params = rawParams ? (camelizeKeys(rawParams) as Record<string, unknown>) : null;\n\n throw new DimesApiError({ status: response.status, code, type, message, params });\n}\n\nexport interface HttpClientOptions {\n baseUrl: string;\n auth: AuthProvider;\n fetch?: typeof globalThis.fetch;\n maxRetries?: number;\n maxRetryDelayMs?: number;\n}\n\nexport class HttpClient {\n private readonly baseUrl: string;\n\n private readonly auth: AuthProvider;\n\n private readonly fetchFn: typeof globalThis.fetch;\n\n private readonly maxRetries: number;\n\n private readonly maxRetryDelayMs: number;\n\n constructor(options: HttpClientOptions) {\n this.baseUrl = options.baseUrl;\n this.auth = options.auth;\n this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;\n this.maxRetryDelayMs = options.maxRetryDelayMs ?? DEFAULT_MAX_RETRY_DELAY_MS;\n }\n\n public async request<T>(path: string, options?: RequestInit): Promise<T> {\n const authHeaders = await this.auth.getHeaders();\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n ...authHeaders,\n ...(options?.headers as Record<string, string> | undefined),\n };\n\n let response = await this.fetchFn(`${this.baseUrl}${path}`, {\n ...options,\n headers,\n });\n\n if (response.status === HTTP_UNAUTHORIZED && this.auth.refresh) {\n await this.auth.refresh();\n const retryHeaders = await this.auth.getHeaders();\n response = await this.fetchFn(`${this.baseUrl}${path}`, {\n ...options,\n headers: { ...headers, ...retryHeaders },\n });\n }\n\n for (let attempt = 0; response.status === HTTP_TOO_MANY_REQUESTS && attempt < this.maxRetries; attempt++) {\n const delayMs = parseRetryAfterMs(response.headers.get(\"retry-after\"), attempt);\n if (delayMs > this.maxRetryDelayMs) {\n break;\n }\n await sleep(delayMs);\n const freshAuth = await this.auth.getHeaders();\n response = await this.fetchFn(`${this.baseUrl}${path}`, {\n ...options,\n headers: { ...headers, ...freshAuth },\n });\n }\n\n if (!response.ok) {\n await throwFromResponse(response);\n }\n\n return camelizeKeys(await response.json()) as T;\n }\n\n public async requestList<T>(path: string, options?: RequestInit): Promise<T[]> {\n const result = await this.request<{ data: T[] }>(path, options);\n return result.data;\n }\n}\n","import { DimesError } from \"../errors/dimes-error\";\n\nexport interface AuthProvider {\n getHeaders(): Promise<Record<string, string>>;\n refresh?(): Promise<void>;\n}\n\ninterface TokenResponse {\n token: string;\n expires_at: string;\n}\n\nexport interface ApiKeyAuthOptions {\n apiKey: string;\n walletAddress: string;\n baseUrl?: string;\n fetch?: typeof globalThis.fetch;\n}\n\nexport class ApiKeyAuth implements AuthProvider {\n private jwt: string | null = null;\n\n private expiresAt = 0;\n\n private refreshPromise: Promise<void> | null = null;\n\n private readonly apiKey: string;\n\n private readonly walletAddress: string;\n\n private readonly baseUrl: string;\n\n private readonly fetchFn: typeof globalThis.fetch;\n\n constructor(options: ApiKeyAuthOptions) {\n this.apiKey = options.apiKey;\n this.walletAddress = options.walletAddress;\n this.baseUrl = options.baseUrl ?? \"https://api.dimes.fi\";\n this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n }\n\n public async getHeaders(): Promise<Record<string, string>> {\n const TOKEN_EXPIRY_BUFFER_MS = 30_000;\n if (!this.jwt || Date.now() >= this.expiresAt - TOKEN_EXPIRY_BUFFER_MS) {\n await this.refresh();\n }\n return { Authorization: `Bearer ${this.jwt}` };\n }\n\n public async refresh(): Promise<void> {\n if (this.refreshPromise) {\n await this.refreshPromise;\n return;\n }\n\n this.refreshPromise = this.fetchToken();\n try {\n await this.refreshPromise;\n } finally {\n this.refreshPromise = null;\n }\n }\n\n private async fetchToken(): Promise<void> {\n const response = await this.fetchFn(`${this.baseUrl}/v1/prediction-markets/tokens`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${this.apiKey}`,\n },\n body: JSON.stringify({ wallet_address: this.walletAddress }),\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new DimesError(\"auth_token_failed\", `Failed to obtain auth token (${response.status}): ${text}`);\n }\n\n const data = (await response.json()) as TokenResponse;\n this.jwt = data.token;\n this.expiresAt = new Date(data.expires_at).getTime();\n }\n}\n\nexport interface JwtAuthOptions {\n tokenUrl: string;\n fetch?: typeof globalThis.fetch;\n}\n\nexport class JwtAuth implements AuthProvider {\n private readonly fetchFn: typeof globalThis.fetch;\n\n private readonly tokenUrl: string;\n\n private jwt: string | null = null;\n\n private expiresAt = 0;\n\n private refreshPromise: Promise<void> | null = null;\n\n constructor(options: JwtAuthOptions) {\n this.tokenUrl = options.tokenUrl;\n this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n }\n\n public async getHeaders(): Promise<Record<string, string>> {\n const TOKEN_EXPIRY_BUFFER_MS = 30_000;\n if (!this.jwt || Date.now() >= this.expiresAt - TOKEN_EXPIRY_BUFFER_MS) {\n await this.refresh();\n }\n return { Authorization: `Bearer ${this.jwt}` };\n }\n\n public async refresh(): Promise<void> {\n if (this.refreshPromise) {\n await this.refreshPromise;\n return;\n }\n\n this.refreshPromise = this.fetchToken();\n try {\n await this.refreshPromise;\n } finally {\n this.refreshPromise = null;\n }\n }\n\n private async fetchToken(): Promise<void> {\n const response = await this.fetchFn(this.tokenUrl);\n\n if (!response.ok) {\n const text = await response.text();\n throw new DimesError(\n \"auth_token_failed\",\n `Failed to fetch token from ${this.tokenUrl} (${response.status}): ${text}`,\n );\n }\n\n const data = (await response.json()) as TokenResponse;\n this.jwt = data.token;\n this.expiresAt = new Date(data.expires_at).getTime();\n }\n}\n","import type { CamelizeKeys } from \"./camelize\";\nimport type { components } from \"./generated\";\n\ntype Raw = components[\"schemas\"];\n\nexport type Market = CamelizeKeys<Raw[\"CustomerMarket\"]>;\n\nexport type MarketLeverage = CamelizeKeys<Raw[\"CustomerLeverage\"]>;\n\nexport type MarketMaxLeveragePerNotional = CamelizeKeys<Raw[\"CustomerMaxMarketLeveragePerNotional\"]>;\n\nexport type MarketSidedMaxLeveragePerNotional = CamelizeKeys<Raw[\"CustomerSidedMaxMarketLeveragePerNotional\"]>;\n\nexport type MarketSidedEligibility = CamelizeKeys<Raw[\"CustomerSidedEligibility\"]>;\n\nexport type MarketFees = CamelizeKeys<Raw[\"CustomerFees\"]>;\n\nexport type MarketPrices = CamelizeKeys<Raw[\"CustomerMarketPrices\"]>;\n\nexport interface MarketPolymarket {\n conditionId: string | null;\n noTokenId: string;\n slug: string;\n yesTokenId: string;\n}\n\nexport type OriginationTier = CamelizeKeys<Raw[\"CustomerOriginationTier\"]>;\n\nexport type Offer = CamelizeKeys<Raw[\"CustomerOffer\"]>;\n\nexport type OpenPosition = CamelizeKeys<Raw[\"CustomerOpenPosition\"]>;\n\nexport type ClosedPosition = CamelizeKeys<Raw[\"CustomerClosedPosition\"]>;\n\nexport type Position = OpenPosition | ClosedPosition;\n\nexport type PositionEntry = CamelizeKeys<Raw[\"CustomerPositionEntry\"]>;\n\nexport type PositionCurrent = CamelizeKeys<Raw[\"CustomerPositionCurrent\"]>;\n\nexport type PositionRisk = CamelizeKeys<Raw[\"CustomerPositionRisk\"]>;\n\nexport type PositionOpenFees = CamelizeKeys<Raw[\"CustomerPositionOpenFees\"]>;\n\nexport type PositionClosedFees = CamelizeKeys<Raw[\"CustomerPositionClosedFees\"]>;\n\nexport type PositionResult = CamelizeKeys<Raw[\"CustomerPositionResult\"]>;\n\nexport type PositionTiming = CamelizeKeys<Raw[\"CustomerPositionTiming\"]>;\n\nexport type PositionFailure = CamelizeKeys<Raw[\"CustomerPositionFailure\"]>;\n\nexport type CloseAttempt = CamelizeKeys<Raw[\"CustomerCloseAttempt\"]>;\n\nexport type PositionUnwind = CamelizeKeys<Raw[\"CustomerPositionUnwind\"]>;\n\nexport type PositionUnwindList = CamelizeKeys<Raw[\"CustomerPositionUnwindList\"]>;\n\nexport type PositionTransactionEntry = CamelizeKeys<Raw[\"PositionTransactionEntry\"]>;\n\nexport type PositionTransactionGroup = CamelizeKeys<Raw[\"PositionTransactionGroup\"]>;\n\nexport type PositionTransactions = CamelizeKeys<Raw[\"PositionTransactions\"]>;\n\nexport type ContractInfo = CamelizeKeys<Raw[\"CustomerContractInfo\"]>;\n\nexport type CustomerLimit = CamelizeKeys<Raw[\"CustomerLimit\"]>;\n\nexport type CreateTokenResult = CamelizeKeys<Raw[\"CreateTokenResult\"]>;\n\nexport interface CreateOfferParams {\n marketTicker: string;\n effectiveSide: \"yes\" | \"no\";\n leverageBps: number;\n notionalAmountUsdPips: string;\n slippageBps: number;\n pmProvider?: \"polymarket\" | \"kalshi\";\n}\n\nexport function isOpenPosition(p: Position): p is OpenPosition {\n return \"current\" in p;\n}\n\nexport function isClosedPosition(p: Position): p is ClosedPosition {\n return \"result\" in p;\n}\n\nexport function leverageMaxBps(lev: MarketLeverage, side: \"yes\" | \"no\"): number {\n const perSide = side === \"yes\" ? lev.maxYesBps : lev.maxNoBps;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n return perSide ?? lev.maxBps ?? lev.minBps;\n}\n","import type { Market } from \"../types/aliases\";\n\nexport type Side = \"yes\" | \"no\";\n\nexport interface SideEligibility {\n open: boolean;\n reasonCode: string | null;\n}\n\nexport interface SidedEligibility {\n yes: SideEligibility;\n no: SideEligibility;\n}\n\nexport function getSidedEligibility(market: Market): SidedEligibility {\n const sided = market.sidedEligibility;\n return {\n yes: {\n open: sided.yes.acceptingNewPositions,\n reasonCode: sided.yes.rejectionReasonCode ?? null,\n },\n no: {\n open: sided.no.acceptingNewPositions,\n reasonCode: sided.no.rejectionReasonCode ?? null,\n },\n };\n}\n\nexport function defaultSide(eligibility: SidedEligibility): Side | null {\n if (eligibility.yes.open && eligibility.no.open) {\n return \"yes\";\n }\n if (eligibility.yes.open) {\n return \"yes\";\n }\n if (eligibility.no.open) {\n return \"no\";\n }\n return null;\n}\n\nexport function isFullyOpen(eligibility: SidedEligibility): boolean {\n return eligibility.yes.open && eligibility.no.open;\n}\n\nexport function isFullyClosed(eligibility: SidedEligibility): boolean {\n return !eligibility.yes.open && !eligibility.no.open;\n}\n\nexport function rejectionReasonText(code: string | null | undefined): string {\n if (!code) {\n return \"Not eligible for new positions\";\n }\n const stripped = code\n .replace(/^quote_/i, \"\")\n .replaceAll(\"_\", \" \")\n .toLowerCase();\n return stripped.charAt(0).toUpperCase() + stripped.slice(1);\n}\n\nexport function rejectionReasonShort(code: string | null | undefined): string {\n if (!code) {\n return \"unavailable\";\n }\n const stripped = code\n .replace(/^quote_/i, \"\")\n .replace(/_exceeded$/i, \"\")\n .replace(/_too_(low|high)$/i, \"\")\n .replaceAll(\"_\", \" \")\n .toLowerCase();\n return stripped;\n}\n","import { type Market, type MarketMaxLeveragePerNotional, leverageMaxBps } from \"../types/aliases\";\nimport type { Side } from \"./eligibility\";\n\nconst USD_100 = 100;\nconst USD_500 = 500;\nconst USD_1K = 1_000;\nconst USD_10K = 10_000;\nconst BPS_PER_UNIT = 10_000;\n\nconst ANCHORS_USD = [USD_100, USD_500, USD_1K, USD_10K] as const;\n\ntype Anchor = readonly [usd: number, bps: number];\n\nfunction anchorsForSide(market: Market, side: Side): readonly Anchor[] {\n const sided = market.leverage.maxMarketLeveragePerNotional;\n const per: MarketMaxLeveragePerNotional = side === \"yes\" ? sided.yes : sided.no;\n return [\n [ANCHORS_USD[0], per.at100UsdBps],\n [ANCHORS_USD[1], per.at500UsdBps],\n [ANCHORS_USD[2], per.at1000UsdBps],\n [ANCHORS_USD[3], per.at10000UsdBps],\n ];\n}\n\nfunction snapDownToStep(bps: number, stepBps: number, minBps: number): number {\n if (stepBps <= 0) {\n return Math.max(minBps, bps);\n }\n const k = Math.floor((bps - minBps) / stepBps);\n return Math.max(minBps, minBps + Math.max(0, k) * stepBps);\n}\n\nfunction interpolateRawBps(anchors: readonly Anchor[], notionalUsd: number): number {\n const first = anchors[0];\n const last = anchors[anchors.length - 1];\n if (!first || !last) {\n return 0;\n }\n if (notionalUsd <= first[0]) {\n return first[1];\n }\n if (notionalUsd >= last[0]) {\n return last[1];\n }\n for (let i = 1; i < anchors.length; i++) {\n const hi = anchors[i];\n const lo = anchors[i - 1];\n if (!hi || !lo) {\n continue;\n }\n if (notionalUsd <= hi[0]) {\n const t = (notionalUsd - lo[0]) / (hi[0] - lo[0]);\n return lo[1] + (hi[1] - lo[1]) * t;\n }\n }\n return last[1];\n}\n\n/**\n * Maximum leverage in basis points the API will allow at a given notional, per side.\n * Piecewise-linear interpolation across the four anchor points ($100/$500/$1k/$10k).\n * Below $100 uses the $100 cap; above $10k uses the $10k cap. Result is clamped to\n * the absolute side max and rounded down to `stepBps`.\n */\nexport function maxLeverageBpsAtNotional(market: Market, side: Side, notionalUsd: number): number {\n const sideAbsMax = leverageMaxBps(market.leverage, side);\n if (!Number.isFinite(notionalUsd) || notionalUsd <= 0) {\n return sideAbsMax;\n }\n const anchors = anchorsForSide(market, side);\n const raw = interpolateRawBps(anchors, notionalUsd);\n const clamped = Math.min(sideAbsMax, raw);\n return snapDownToStep(clamped, market.leverage.stepBps, market.leverage.minBps);\n}\n\n/**\n * Largest leverage (bps) the user can pick for a given collateral such that the\n * resulting notional still satisfies the per-notional cap.\n *\n * Walks down from the absolute side max in `stepBps` increments and returns the\n * first leverage `lev` where `lev <= maxLeverageBpsAtNotional(collateral * lev / 1)`.\n */\nexport function maxViableLeverageBpsForCollateral(market: Market, side: Side, collateralUsd: number): number {\n const sideAbsMax = leverageMaxBps(market.leverage, side);\n if (!Number.isFinite(collateralUsd) || collateralUsd <= 0) {\n return sideAbsMax;\n }\n\n const step = Math.max(market.leverage.stepBps, 1);\n const minBps = market.leverage.minBps;\n const maxSteps = Math.max(0, Math.floor((sideAbsMax - minBps) / step));\n\n for (let i = maxSteps; i >= 0; i--) {\n const lev = minBps + i * step;\n const notionalUsd = collateralUsd * (lev / BPS_PER_UNIT);\n if (lev <= maxLeverageBpsAtNotional(market, side, notionalUsd)) {\n return lev;\n }\n }\n return minBps;\n}\n","import type { Position, PositionEntry } from \"../types/aliases\";\n\nexport interface OriginationFeeBreakdown {\n totalBps: number;\n totalUsd: number;\n protocolBps: number;\n protocolUsd: number;\n partnerBps: number;\n partnerUsd: number;\n}\n\nfunction getEntry(position: Position): PositionEntry {\n return position.entry;\n}\n\nexport function getOriginationFeeBreakdown(position: Position): OriginationFeeBreakdown {\n const entry = getEntry(position);\n const totalBps = entry.originationFeeBps;\n const totalUsd = Number(entry.originationFeeUsd) || 0;\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const protocolBps = entry.protocolOriginationFeeBps ?? totalBps;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const partnerBps = entry.partnerOriginationFeeBps ?? 0;\n\n const share = totalBps > 0 ? protocolBps / totalBps : 1;\n const protocolUsd = totalUsd * share;\n const partnerUsd = totalUsd - protocolUsd;\n\n return {\n totalBps,\n totalUsd,\n protocolBps,\n protocolUsd,\n partnerBps,\n partnerUsd,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA,SAAS,sBAAsB;;;ACA/B,SAAS,oBAAoC;AAe7C,IAAM,oBAAoB;AAC1B,IAAM,yBAAyB;AAC/B,IAAM,sBAAsB;AAC5B,IAAM,6BAA6B;AACnC,IAAM,yBAAyB;AAC/B,IAAM,iBAAiB;AACvB,IAAM,gBAAgB;AAEtB,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;AAEA,SAAS,kBAAkB,QAAuB,SAAyB;AACzE,QAAM,aAAa,yBAAyB,kBAAkB;AAC9D,MAAI,CAAC,QAAQ;AACX,WAAO;AAAA,EACT;AAEA,QAAM,UAAU,OAAO,MAAM;AAC7B,MAAI,CAAC,OAAO,MAAM,OAAO,KAAK,WAAW,GAAG;AAC1C,WAAO,UAAU;AAAA,EACnB;AAEA,QAAM,SAAS,KAAK,MAAM,MAAM;AAChC,MAAI,CAAC,OAAO,MAAM,MAAM,GAAG;AACzB,WAAO,KAAK,IAAI,GAAG,SAAS,KAAK,IAAI,CAAC;AAAA,EACxC;AAEA,SAAO;AACT;AAGA,eAAe,kBAAkB,U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;AAC3C,QAAI,OAAO,yBAAyB,QAAQ,MAAM,WAAW,GAAG;AAC9D,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;;;ACzFA,SAAS,SAAS,UAAmC;AACnD,SAAO,SAAS;AAClB;AAEO,SAAS,2BAA2B,UAA6C;AACtF,QAAM,QAAQ,SAAS,QAAQ;AAC/B,QAAM,WAAW,MAAM;AACvB,QAAM,WAAW,OAAO,MAAM,iBAAiB,KAAK;AAGpD,QAAM,cAAc,MAAM,6BAA6B;AAEvD,QAAM,aAAa,MAAM,4BAA4B;AAErD,QAAM,QAAQ,WAAW,IAAI,cAAc,WAAW;AACtD,QAAM,cAAc,WAAW;AAC/B,QAAM,aAAa,WAAW;AAE9B,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/client/dimes-client.ts","../src/client/http.ts","../src/client/auth.ts","../src/types/aliases.ts","../src/utils/eligibility.ts","../src/utils/leverage.ts","../src/utils/fees.ts","../src/utils/max-gain.ts"],"sourcesContent":["import { decamelizeKeys } from \"humps\";\nimport type {\n ContractInfo,\n CreateOfferParams,\n CustomerLimit,\n FeeRates,\n FeeReport,\n FeeReportParams,\n Market,\n Offer,\n Paginated,\n Position,\n PositionTransactions,\n} from \"../types\";\nimport type { AuthProvider } from \"./auth\";\nimport { HttpClient } from \"./http\";\n\nexport interface DimesClientOptions {\n baseUrl?: string;\n auth: AuthProvider;\n fetch?: typeof globalThis.fetch;\n maxRetries?: number;\n maxRetryDelayMs?: number;\n}\n\nexport type MarketSort = \"ticker_asc\" | \"depth_desc\" | \"discovered_at_desc\";\n\nexport interface GetMarketsParams {\n cursor?: string;\n limit?: number;\n category?: string;\n status?: string;\n provider?: \"polymarket\" | \"kalshi\";\n sort?: MarketSort;\n}\n\nexport interface GetPositionsParams {\n cursor?: string;\n limit?: number;\n status?: \"open\" | \"closed\";\n}\n\nexport interface GetFeeRatesParams {\n ticker?: string;\n}\n\nfunction buildQueryFromEntries(entries: [string, unknown][]): string {\n const filtered = entries.filter(([, v]) => v !== undefined && v !== null);\n if (filtered.length === 0) {\n return \"\";\n }\n\n const search = new URLSearchParams();\n for (const [key, value] of filtered) {\n search.set(\n key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`),\n String(value),\n );\n }\n\n return `?${search.toString()}`;\n}\n\nexport class DimesClient {\n private readonly http: HttpClient;\n\n constructor(options: DimesClientOptions) {\n this.http = new HttpClient({\n baseUrl: options.baseUrl ?? \"https://api.dimes.fi\",\n auth: options.auth,\n fetch: options.fetch,\n maxRetries: options.maxRetries,\n maxRetryDelayMs: options.maxRetryDelayMs,\n });\n }\n\n public async getMarkets(params?: GetMarketsParams): Promise<Paginated<Market>> {\n const query = params ? buildQueryFromEntries(Object.entries(params)) : \"\";\n return this.http.request<Paginated<Market>>(`/v1/prediction-markets/markets${query}`);\n }\n\n public async getMarket(ticker: string): Promise<Market> {\n return this.http.request<Market>(`/v1/prediction-markets/markets/${encodeURIComponent(ticker)}`);\n }\n\n public async createDraftQuote(params: CreateOfferParams): Promise<Offer> {\n return this.http.request<Offer>(\"/v1/prediction-markets/draft-quotes\", {\n method: \"POST\",\n body: JSON.stringify(decamelizeKeys(params)),\n });\n }\n\n public async promoteDraftQuote(draftId: string): Promise<Offer> {\n return this.http.request<Offer>(`/v1/prediction-markets/promoted-quotes/${encodeURIComponent(draftId)}`, {\n method: \"POST\",\n });\n }\n\n public async createQuote(params: CreateOfferParams): Promise<Offer> {\n return this.http.request<Offer>(\"/v1/prediction-markets/quotes\", {\n method: \"POST\",\n body: JSON.stringify(decamelizeKeys(params)),\n });\n }\n\n public async getPositions(params?: GetPositionsParams): Promise<Position[]> {\n const query = params ? buildQueryFromEntries(Object.entries(params)) : \"\";\n return this.http.requestList<Position>(`/v1/prediction-markets/positions${query}`);\n }\n\n public async getPositionTransactions(positionId: string): Promise<PositionTransactions> {\n return this.http.request<PositionTransactions>(\n `/v1/prediction-markets/positions/${encodeURIComponent(positionId)}/transactions`,\n );\n }\n\n public async cancelPosition(positionId: string): Promise<void> {\n await this.http.request<unknown>(`/v1/prediction-markets/positions/${encodeURIComponent(positionId)}/cancel`, {\n method: \"POST\",\n });\n }\n\n public async getContractInfo(): Promise<ContractInfo> {\n return this.http.request<ContractInfo>(\"/v1/prediction-markets/contract-info\");\n }\n\n public async getLimits(): Promise<CustomerLimit> {\n return this.http.request<CustomerLimit>(\"/v1/prediction-markets/limits\");\n }\n\n public async getFeeRates(params?: GetFeeRatesParams): Promise<FeeRates> {\n const query = params ? buildQueryFromEntries(Object.entries(params)) : \"\";\n return this.http.request<FeeRates>(`/v1/prediction-markets/fee-rates${query}`);\n }\n\n public async getFeeReport(params: FeeReportParams): Promise<FeeReport> {\n return this.http.request<FeeReport>(\"/v1/prediction-markets/fee-reports\", {\n method: \"POST\",\n body: JSON.stringify(decamelizeKeys(params)),\n });\n }\n}\n","import { camelizeKeys, type Camelized } from \"humps\";\nimport { DimesApiError } from \"../errors/dimes-error\";\nimport type { AuthProvider } from \"./auth\";\n\nexport type { Camelized };\n\ninterface ApiErrorBody {\n error?: {\n type?: string;\n code?: string;\n message: string;\n params?: Record<string, unknown>;\n };\n}\n\nconst HTTP_UNAUTHORIZED = 401;\nconst HTTP_TOO_MANY_REQUESTS = 429;\nconst DEFAULT_MAX_RETRIES = 3;\nconst DEFAULT_MAX_RETRY_DELAY_MS = 60_000;\nconst DEFAULT_RETRY_DELAY_MS = 1000;\nconst BACKOFF_FACTOR = 2;\nconst MS_PER_SECOND = 1000;\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction parseRetryAfterMs(header: string | null, attempt: number): number {\n const fallbackMs = DEFAULT_RETRY_DELAY_MS * BACKOFF_FACTOR ** attempt;\n if (!header) {\n return fallbackMs;\n }\n\n const seconds = Number(header);\n if (!Number.isNaN(seconds) && seconds >= 0) {\n return seconds * MS_PER_SECOND;\n }\n\n const dateMs = Date.parse(header);\n if (!Number.isNaN(dateMs)) {\n return Math.max(0, dateMs - Date.now());\n }\n\n return fallbackMs;\n}\n\n// eslint-disable-next-line complexity\nasync function throwFromResponse(response: Response): Promise<never> {\n const rawBody = await response.text();\n let parsed: ApiErrorBody | null;\n try {\n parsed = rawBody ? (JSON.parse(rawBody) as ApiErrorBody) : null;\n } catch {\n parsed = null;\n }\n\n const code = parsed?.error?.code ?? \"unknown_error\";\n const type = parsed?.error?.type ?? null;\n const message = parsed?.error?.message ?? `API error ${response.status}`;\n const rawParams = parsed?.error?.params;\n const params = rawParams ? (camelizeKeys(rawParams) as Record<string, unknown>) : null;\n\n throw new DimesApiError({ status: response.status, code, type, message, params });\n}\n\nexport interface HttpClientOptions {\n baseUrl: string;\n auth: AuthProvider;\n fetch?: typeof globalThis.fetch;\n maxRetries?: number;\n maxRetryDelayMs?: number;\n}\n\nexport class HttpClient {\n private readonly baseUrl: string;\n\n private readonly auth: AuthProvider;\n\n private readonly fetchFn: typeof globalThis.fetch;\n\n private readonly maxRetries: number;\n\n private readonly maxRetryDelayMs: number;\n\n constructor(options: HttpClientOptions) {\n this.baseUrl = options.baseUrl;\n this.auth = options.auth;\n this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;\n this.maxRetryDelayMs = options.maxRetryDelayMs ?? DEFAULT_MAX_RETRY_DELAY_MS;\n }\n\n public async request<T>(path: string, options?: RequestInit): Promise<T> {\n const authHeaders = await this.auth.getHeaders();\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n ...authHeaders,\n ...(options?.headers as Record<string, string> | undefined),\n };\n\n let response = await this.fetchFn(`${this.baseUrl}${path}`, {\n ...options,\n headers,\n });\n\n if (response.status === HTTP_UNAUTHORIZED && this.auth.refresh) {\n await this.auth.refresh();\n const retryHeaders = await this.auth.getHeaders();\n response = await this.fetchFn(`${this.baseUrl}${path}`, {\n ...options,\n headers: { ...headers, ...retryHeaders },\n });\n }\n\n for (let attempt = 0; response.status === HTTP_TOO_MANY_REQUESTS && attempt < this.maxRetries; attempt++) {\n const delayMs = parseRetryAfterMs(response.headers.get(\"retry-after\"), attempt);\n if (delayMs > this.maxRetryDelayMs) {\n break;\n }\n await sleep(delayMs);\n const freshAuth = await this.auth.getHeaders();\n response = await this.fetchFn(`${this.baseUrl}${path}`, {\n ...options,\n headers: { ...headers, ...freshAuth },\n });\n }\n\n if (!response.ok) {\n await throwFromResponse(response);\n }\n\n return camelizeKeys(await response.json()) as T;\n }\n\n public async requestList<T>(path: string, options?: RequestInit): Promise<T[]> {\n const result = await this.request<{ data: T[] }>(path, options);\n return result.data;\n }\n}\n","import { DimesError } from \"../errors/dimes-error\";\n\nexport interface AuthProvider {\n getHeaders(): Promise<Record<string, string>>;\n refresh?(): Promise<void>;\n}\n\ninterface TokenResponse {\n token: string;\n expires_at: string;\n}\n\nexport interface ApiKeyAuthOptions {\n apiKey: string;\n walletAddress: string;\n baseUrl?: string;\n fetch?: typeof globalThis.fetch;\n}\n\nexport class ApiKeyAuth implements AuthProvider {\n private jwt: string | null = null;\n\n private expiresAt = 0;\n\n private refreshPromise: Promise<void> | null = null;\n\n private readonly apiKey: string;\n\n private readonly walletAddress: string;\n\n private readonly baseUrl: string;\n\n private readonly fetchFn: typeof globalThis.fetch;\n\n constructor(options: ApiKeyAuthOptions) {\n this.apiKey = options.apiKey;\n this.walletAddress = options.walletAddress;\n this.baseUrl = options.baseUrl ?? \"https://api.dimes.fi\";\n this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n }\n\n public async getHeaders(): Promise<Record<string, string>> {\n const TOKEN_EXPIRY_BUFFER_MS = 30_000;\n if (!this.jwt || Date.now() >= this.expiresAt - TOKEN_EXPIRY_BUFFER_MS) {\n await this.refresh();\n }\n return { Authorization: `Bearer ${this.jwt}` };\n }\n\n public async refresh(): Promise<void> {\n if (this.refreshPromise) {\n await this.refreshPromise;\n return;\n }\n\n this.refreshPromise = this.fetchToken();\n try {\n await this.refreshPromise;\n } finally {\n this.refreshPromise = null;\n }\n }\n\n private async fetchToken(): Promise<void> {\n const response = await this.fetchFn(`${this.baseUrl}/v1/prediction-markets/tokens`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${this.apiKey}`,\n },\n body: JSON.stringify({ wallet_address: this.walletAddress }),\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new DimesError(\"auth_token_failed\", `Failed to obtain auth token (${response.status}): ${text}`);\n }\n\n const data = (await response.json()) as TokenResponse;\n this.jwt = data.token;\n this.expiresAt = new Date(data.expires_at).getTime();\n }\n}\n\nexport interface JwtAuthOptions {\n tokenUrl: string;\n fetch?: typeof globalThis.fetch;\n}\n\nexport class JwtAuth implements AuthProvider {\n private readonly fetchFn: typeof globalThis.fetch;\n\n private readonly tokenUrl: string;\n\n private jwt: string | null = null;\n\n private expiresAt = 0;\n\n private refreshPromise: Promise<void> | null = null;\n\n constructor(options: JwtAuthOptions) {\n this.tokenUrl = options.tokenUrl;\n this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);\n }\n\n public async getHeaders(): Promise<Record<string, string>> {\n const TOKEN_EXPIRY_BUFFER_MS = 30_000;\n if (!this.jwt || Date.now() >= this.expiresAt - TOKEN_EXPIRY_BUFFER_MS) {\n await this.refresh();\n }\n return { Authorization: `Bearer ${this.jwt}` };\n }\n\n public async refresh(): Promise<void> {\n if (this.refreshPromise) {\n await this.refreshPromise;\n return;\n }\n\n this.refreshPromise = this.fetchToken();\n try {\n await this.refreshPromise;\n } finally {\n this.refreshPromise = null;\n }\n }\n\n private async fetchToken(): Promise<void> {\n const response = await this.fetchFn(this.tokenUrl);\n\n if (!response.ok) {\n const text = await response.text();\n throw new DimesError(\n \"auth_token_failed\",\n `Failed to fetch token from ${this.tokenUrl} (${response.status}): ${text}`,\n );\n }\n\n const data = (await response.json()) as TokenResponse;\n this.jwt = data.token;\n this.expiresAt = new Date(data.expires_at).getTime();\n }\n}\n","import type { CamelizeKeys } from \"./camelize\";\nimport type { components } from \"./generated\";\n\ntype Raw = components[\"schemas\"];\n\nexport type Market = CamelizeKeys<Raw[\"CustomerMarket\"]>;\n\nexport type MarketLeverage = CamelizeKeys<Raw[\"CustomerLeverage\"]>;\n\nexport type MarketMaxLeveragePerNotional = CamelizeKeys<Raw[\"CustomerMaxMarketLeveragePerNotional\"]>;\n\nexport type MarketSidedMaxLeveragePerNotional = CamelizeKeys<Raw[\"CustomerSidedMaxMarketLeveragePerNotional\"]>;\n\nexport type MarketSidedEligibility = CamelizeKeys<Raw[\"CustomerSidedEligibility\"]>;\n\nexport type MarketFees = CamelizeKeys<Raw[\"CustomerFees\"]>;\n\nexport type MarketPrices = CamelizeKeys<Raw[\"CustomerMarketPrices\"]>;\n\nexport interface MarketPolymarket {\n conditionId: string | null;\n noTokenId: string;\n slug: string;\n yesTokenId: string;\n}\n\nexport type OriginationTier = CamelizeKeys<Raw[\"CustomerOriginationTier\"]>;\n\nexport type Offer = CamelizeKeys<Raw[\"CustomerOffer\"]>;\n\nexport type OpenPosition = CamelizeKeys<Raw[\"CustomerOpenPosition\"]>;\n\nexport type ClosedPosition = CamelizeKeys<Raw[\"CustomerClosedPosition\"]>;\n\nexport type Position = OpenPosition | ClosedPosition;\n\nexport type PositionEntry = CamelizeKeys<Raw[\"CustomerPositionEntry\"]>;\n\nexport type PositionCurrent = CamelizeKeys<Raw[\"CustomerPositionCurrent\"]>;\n\nexport type PositionRisk = CamelizeKeys<Raw[\"CustomerPositionRisk\"]>;\n\nexport type PositionOpenFees = CamelizeKeys<Raw[\"CustomerPositionOpenFees\"]>;\n\nexport type PositionClosedFees = CamelizeKeys<Raw[\"CustomerPositionClosedFees\"]>;\n\nexport type PositionResult = CamelizeKeys<Raw[\"CustomerPositionResult\"]>;\n\nexport type PositionTiming = CamelizeKeys<Raw[\"CustomerPositionTiming\"]>;\n\nexport type PositionFailure = CamelizeKeys<Raw[\"CustomerPositionFailure\"]>;\n\nexport type CloseAttempt = CamelizeKeys<Raw[\"CustomerCloseAttempt\"]>;\n\nexport type PositionUnwind = CamelizeKeys<Raw[\"CustomerPositionUnwind\"]>;\n\nexport type PositionUnwindList = CamelizeKeys<Raw[\"CustomerPositionUnwindList\"]>;\n\nexport type PositionTransactionEntry = CamelizeKeys<Raw[\"PositionTransactionEntry\"]>;\n\nexport type PositionTransactionGroup = CamelizeKeys<Raw[\"PositionTransactionGroup\"]>;\n\nexport type PositionTransactions = CamelizeKeys<Raw[\"PositionTransactions\"]>;\n\nexport type ContractInfo = CamelizeKeys<Raw[\"CustomerContractInfo\"]>;\n\nexport type CustomerLimit = CamelizeKeys<Raw[\"CustomerLimit\"]>;\n\nexport type CreateTokenResult = CamelizeKeys<Raw[\"CreateTokenResult\"]>;\n\nexport type FeeRatesOriginationTier = CamelizeKeys<Raw[\"CustomerOriginationFeeTier\"]>;\n\nexport type FeeRatesMarket = CamelizeKeys<Raw[\"CustomerFeeRatesMarket\"]>;\n\nexport type FeeRates = CamelizeKeys<Raw[\"CustomerFeeRates\"]>;\n\nexport type FeeReport = CamelizeKeys<Raw[\"CustomerFeeReport\"]>;\n\nexport interface CreateOfferParams {\n marketTicker: string;\n effectiveSide: \"yes\" | \"no\";\n leverageBps: number;\n notionalAmountUsdPips: string;\n slippageBps: number;\n pmProvider?: \"polymarket\" | \"kalshi\";\n}\n\nexport interface FeeReportParams {\n marketTicker: string;\n effectiveSide: \"yes\" | \"no\";\n leverageBps: number;\n notionalAmountUsdPips: string;\n entryPriceUsdPips?: string;\n}\n\nexport function isOpenPosition(p: Position): p is OpenPosition {\n return \"current\" in p;\n}\n\nexport function isClosedPosition(p: Position): p is ClosedPosition {\n return \"result\" in p;\n}\n\nexport function leverageMaxBps(lev: MarketLeverage, side: \"yes\" | \"no\"): number {\n const perSide = side === \"yes\" ? lev.maxYesBps : lev.maxNoBps;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n return perSide ?? lev.maxBps ?? lev.minBps;\n}\n","import type { Market } from \"../types/aliases\";\n\nexport type Side = \"yes\" | \"no\";\n\nexport interface SideEligibility {\n open: boolean;\n reasonCode: string | null;\n}\n\nexport interface SidedEligibility {\n yes: SideEligibility;\n no: SideEligibility;\n}\n\nexport function getSidedEligibility(market: Market): SidedEligibility {\n const sided = market.sidedEligibility;\n return {\n yes: {\n open: sided.yes.acceptingNewPositions,\n reasonCode: sided.yes.rejectionReasonCode ?? null,\n },\n no: {\n open: sided.no.acceptingNewPositions,\n reasonCode: sided.no.rejectionReasonCode ?? null,\n },\n };\n}\n\nexport function defaultSide(eligibility: SidedEligibility): Side | null {\n if (eligibility.yes.open && eligibility.no.open) {\n return \"yes\";\n }\n if (eligibility.yes.open) {\n return \"yes\";\n }\n if (eligibility.no.open) {\n return \"no\";\n }\n return null;\n}\n\nexport function isFullyOpen(eligibility: SidedEligibility): boolean {\n return eligibility.yes.open && eligibility.no.open;\n}\n\nexport function isFullyClosed(eligibility: SidedEligibility): boolean {\n return !eligibility.yes.open && !eligibility.no.open;\n}\n\nexport function rejectionReasonText(code: string | null | undefined): string {\n if (!code) {\n return \"Not eligible for new positions\";\n }\n const stripped = code\n .replace(/^quote_/i, \"\")\n .replaceAll(\"_\", \" \")\n .toLowerCase();\n return stripped.charAt(0).toUpperCase() + stripped.slice(1);\n}\n\nexport function rejectionReasonShort(code: string | null | undefined): string {\n if (!code) {\n return \"unavailable\";\n }\n const stripped = code\n .replace(/^quote_/i, \"\")\n .replace(/_exceeded$/i, \"\")\n .replace(/_too_(low|high)$/i, \"\")\n .replaceAll(\"_\", \" \")\n .toLowerCase();\n return stripped;\n}\n","import { type Market, type MarketMaxLeveragePerNotional, leverageMaxBps } from \"../types/aliases\";\nimport type { Side } from \"./eligibility\";\n\nconst USD_100 = 100;\nconst USD_500 = 500;\nconst USD_1K = 1_000;\nconst USD_10K = 10_000;\nconst BPS_PER_UNIT = 10_000;\n\nconst ANCHORS_USD = [USD_100, USD_500, USD_1K, USD_10K] as const;\n\ntype Anchor = readonly [usd: number, bps: number];\n\nfunction anchorsForSide(market: Market, side: Side): readonly Anchor[] {\n const sided = market.leverage.maxMarketLeveragePerNotional;\n const per: MarketMaxLeveragePerNotional = side === \"yes\" ? sided.yes : sided.no;\n return [\n [ANCHORS_USD[0], per.at100UsdBps],\n [ANCHORS_USD[1], per.at500UsdBps],\n [ANCHORS_USD[2], per.at1000UsdBps],\n [ANCHORS_USD[3], per.at10000UsdBps],\n ];\n}\n\nfunction snapDownToStep(bps: number, stepBps: number, minBps: number): number {\n if (stepBps <= 0) {\n return Math.max(minBps, bps);\n }\n const k = Math.floor((bps - minBps) / stepBps);\n return Math.max(minBps, minBps + Math.max(0, k) * stepBps);\n}\n\nfunction interpolateRawBps(anchors: readonly Anchor[], notionalUsd: number): number {\n const first = anchors[0];\n const last = anchors[anchors.length - 1];\n if (!first || !last) {\n return 0;\n }\n if (notionalUsd <= first[0]) {\n return first[1];\n }\n if (notionalUsd >= last[0]) {\n return last[1];\n }\n for (let i = 1; i < anchors.length; i++) {\n const hi = anchors[i];\n const lo = anchors[i - 1];\n if (!hi || !lo) {\n continue;\n }\n if (notionalUsd <= hi[0]) {\n const t = (notionalUsd - lo[0]) / (hi[0] - lo[0]);\n return lo[1] + (hi[1] - lo[1]) * t;\n }\n }\n return last[1];\n}\n\n/**\n * Maximum leverage in basis points the API will allow at a given notional, per side.\n * Piecewise-linear interpolation across the four anchor points ($100/$500/$1k/$10k).\n * Below $100 uses the $100 cap; above $10k uses the $10k cap. Result is clamped to\n * the absolute side max and rounded down to `stepBps`.\n */\nexport function maxLeverageBpsAtNotional(market: Market, side: Side, notionalUsd: number): number {\n const sideAbsMax = leverageMaxBps(market.leverage, side);\n if (!Number.isFinite(notionalUsd) || notionalUsd <= 0) {\n return sideAbsMax;\n }\n const anchors = anchorsForSide(market, side);\n const raw = interpolateRawBps(anchors, notionalUsd);\n const clamped = Math.min(sideAbsMax, raw);\n return snapDownToStep(clamped, market.leverage.stepBps, market.leverage.minBps);\n}\n\n/**\n * Largest leverage (bps) the user can pick for a given collateral such that the\n * resulting notional still satisfies the per-notional cap.\n *\n * Walks down from the absolute side max in `stepBps` increments and returns the\n * first leverage `lev` where `lev <= maxLeverageBpsAtNotional(collateral * lev / 1)`.\n */\nexport function maxViableLeverageBpsForCollateral(market: Market, side: Side, collateralUsd: number): number {\n const sideAbsMax = leverageMaxBps(market.leverage, side);\n if (!Number.isFinite(collateralUsd) || collateralUsd <= 0) {\n return sideAbsMax;\n }\n\n const step = Math.max(market.leverage.stepBps, 1);\n const minBps = market.leverage.minBps;\n const maxSteps = Math.max(0, Math.floor((sideAbsMax - minBps) / step));\n\n for (let i = maxSteps; i >= 0; i--) {\n const lev = minBps + i * step;\n const notionalUsd = collateralUsd * (lev / BPS_PER_UNIT);\n if (lev <= maxLeverageBpsAtNotional(market, side, notionalUsd)) {\n return lev;\n }\n }\n return minBps;\n}\n","import type { Position, PositionEntry } from \"../types/aliases\";\n\nconst BPS_DIVISOR = 10_000;\n\n/**\n * One leverage-tiered origination-fee rate. `maxLeverageBps` is the inclusive\n * upper bound (in basis points) of leverage covered by this tier; `feeBps` is\n * the protocol origination fee charged for any leverage at or below that bound.\n * Tiers must be supplied in ascending `maxLeverageBps` order; the final tier\n * acts as the catch-all for the highest leverages.\n */\nexport interface OriginationFeeTier {\n maxLeverageBps: number;\n feeBps: number;\n}\n\n/**\n * Resolve the protocol origination fee rate (bps) for a given leverage from an\n * ordered list of leverage tiers. Returns the `feeBps` of the first tier whose\n * `maxLeverageBps >= leverageBps`. If no tier matches (leverage exceeds every\n * bound) the last tier is used as the catch-all. The caller fetches the tiers\n * from the `fee-rates` API; the math is pure.\n *\n * Note: this returns the PROTOCOL rate only — add `partnerOriginationFeeBps`\n * separately (see {@link resolveOriginationFeeBps}).\n */\nexport function resolveProtocolOriginationFeeBps(tiers: readonly OriginationFeeTier[], leverageBps: number): number {\n const lastTier = tiers[tiers.length - 1];\n if (!lastTier) {\n return 0;\n }\n for (const tier of tiers) {\n if (leverageBps <= tier.maxLeverageBps) {\n return tier.feeBps;\n }\n }\n return lastTier.feeBps;\n}\n\n/**\n * Combined origination fee rate (bps) = protocol tier rate + partner add-on.\n * Mirrors the server: the protocol rate is leverage-tiered, the partner rate is\n * a flat add-on supplied by the partner's `fee-rates` config.\n */\nexport function resolveOriginationFeeBps(\n tiers: readonly OriginationFeeTier[],\n leverageBps: number,\n partnerOriginationFeeBps: number,\n): number {\n return resolveProtocolOriginationFeeBps(tiers, leverageBps) + partnerOriginationFeeBps;\n}\n\n/**\n * Origination fee in USDC units (1_000_000 = $1), floored, matching the server:\n * `floor(notionalUsdcUnits * combinedOriginationFeeBps / 10_000)`.\n */\nexport function computeOriginationFeeUsdcUnits(notionalUsdcUnits: number, combinedOriginationFeeBps: number): number {\n return Math.floor((notionalUsdcUnits * combinedOriginationFeeBps) / BPS_DIVISOR);\n}\n\nexport interface OriginationFeeBreakdown {\n totalBps: number;\n totalUsd: number;\n protocolBps: number;\n protocolUsd: number;\n partnerBps: number;\n partnerUsd: number;\n}\n\nfunction getEntry(position: Position): PositionEntry {\n return position.entry;\n}\n\nexport function getOriginationFeeBreakdown(position: Position): OriginationFeeBreakdown {\n const entry = getEntry(position);\n const totalBps = entry.originationFeeBps;\n const totalUsd = Number(entry.originationFeeUsd) || 0;\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const protocolBps = entry.protocolOriginationFeeBps ?? totalBps;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const partnerBps = entry.partnerOriginationFeeBps ?? 0;\n\n const share = totalBps > 0 ? protocolBps / totalBps : 1;\n const protocolUsd = totalUsd * share;\n const partnerUsd = totalUsd - protocolUsd;\n\n return {\n totalBps,\n totalUsd,\n protocolBps,\n protocolUsd,\n partnerBps,\n partnerUsd,\n };\n}\n","const BPS_DIVISOR = 10_000;\nconst USDC_UNITS_PER_USD = 1_000_000;\nconst TOKEN_UNITS_PER_TOKEN = 1_000_000;\n\n/**\n * Inputs to the Polymarket trading-fee curve. All rates are basis points; the\n * caller fetches `feeRateBps`, `feeExponent`, and `builderTakerFeeRateBps` from\n * the `fee-rates` API (snapshotted server-side as `Offer.polymarketFeeRateBps`\n * / `polymarketFeeExponent` / `polymarketBuilderFeeRateBps`).\n */\nexport interface PolymarketTradingFeeInput {\n notionalUsdcUnits: number;\n priceUsd: number;\n feeRateBps: number;\n feeExponent?: number;\n builderTakerFeeRateBps?: number;\n}\n\n/**\n * Polymarket open/close trading fee in USDC units (1_000_000 = $1).\n *\n * Matches the canonical formula (docs: position-math/09-exchange-trading-fees):\n *\n * ```\n * protocol = feeRateBps / 10_000 * C * (p * (1 - p)) ^ feeExponent * 1e6\n * builder = builderTakerFeeRateBps / 10_000 * notionalUsdc\n * fee = ceil(protocol + builder)\n * ```\n *\n * where `C` = contracts = notionalUsd / p, `p` = price in dollars (0..1). The\n * curvature term peaks at p = 0.5 and is symmetric; the flat builder term does\n * not shrink at price extremes. `feeExponent` defaults to 1 (standard quadratic\n * curvature); some markets use 0 (flat `feeRate * C`). `builderTakerFeeRateBps`\n * defaults to 0 (Bloom's own operator builder code is always 0-fee).\n */\nexport function computePolymarketTradingFee(input: PolymarketTradingFeeInput): number {\n const { notionalUsdcUnits, priceUsd, feeRateBps } = input;\n const feeExponent = input.feeExponent ?? 1;\n const builderTakerFeeRateBps = input.builderTakerFeeRateBps ?? 0;\n\n if (priceUsd <= 0) {\n return 0;\n }\n\n const notionalUsd = notionalUsdcUnits / USDC_UNITS_PER_USD;\n const contracts = notionalUsd / priceUsd;\n const curvature = (priceUsd * (1 - priceUsd)) ** feeExponent;\n\n const protocolFeeUsdcUnits = (feeRateBps / BPS_DIVISOR) * contracts * curvature * USDC_UNITS_PER_USD;\n const builderFeeUsdcUnits = (builderTakerFeeRateBps / BPS_DIVISOR) * notionalUsdcUnits;\n\n return Math.ceil(protocolFeeUsdcUnits + builderFeeUsdcUnits);\n}\n\n/**\n * Expected position size in token units (1_000_000 = 1 whole token) for a given\n * notional and entry price, optionally discounted by slippage. A token redeems\n * at $1 on a win, so token units are numerically equal to USDC units.\n *\n * `tokens = notionalUsd / entryPrice`, then scaled down by `slippageBps`.\n * Floored to whole token units. This is an at-quote estimate of the offer's\n * `minExpectedPositionTokenUnits`; the server is authoritative.\n */\nexport function expectedPositionTokenUnits(notionalUsdcUnits: number, entryPriceUsd: number, slippageBps = 0): number {\n if (entryPriceUsd <= 0) {\n return 0;\n }\n const notionalUsd = notionalUsdcUnits / USDC_UNITS_PER_USD;\n const tokens = notionalUsd / entryPriceUsd;\n const slippageFactor = (BPS_DIVISOR - slippageBps) / BPS_DIVISOR;\n return Math.floor(tokens * slippageFactor * TOKEN_UNITS_PER_TOKEN);\n}\n\n/**\n * Estimated base liquidation price (deterministic, at-entry closed form).\n *\n * **This is an estimate, not the server's TWAP solver result.** It computes the\n * at-entry base liquidation price (F = 0, no safety margin) per the docs\n * (position-math/04-liquidation):\n *\n * ```\n * P_liq_base = entryPrice * (L - 1) / L * (1 + liquidationFeeBps / 10_000)\n * ```\n *\n * where `L = leverageBps / 10_000`. At 1x leverage the borrowed capital is zero\n * so the liquidation price is zero. `entryPriceUsd` is in dollars; the result is\n * in the same units. The live server liquidation price drifts above this as the\n * lifetime fee `F` accrues and includes a safety margin.\n */\nexport function estimateLiquidationPrice(\n entryPriceUsd: number,\n leverageBps: number,\n liquidationFeeBps: number,\n): number {\n const leverage = leverageBps / BPS_DIVISOR;\n if (leverage <= 1) {\n return 0;\n }\n const loanPerToken = entryPriceUsd * ((leverage - 1) / leverage);\n return loanPerToken * (1 + liquidationFeeBps / BPS_DIVISOR);\n}\n\n/**\n * Inputs for {@link computeMaxGain}. All amounts are in USDC units\n * (1_000_000 = $1) except `positionTokenUnits` (token units, 1_000_000 = 1\n * token) which is numerically equal to its settlement USDC value.\n */\nexport interface MaxGainInput {\n positionTokenUnits: number;\n notionalUsdcUnits: number;\n expectedOpenTradingFeeUsdcUnits: number;\n originationFeeUsdcUnits: number;\n}\n\n/**\n * Result of {@link computeMaxGain}. All amounts in USDC units (1_000_000 = $1).\n * Gains are profit OVER principal (notional = loan + collateral) and may be\n * negative — they are signed and never clamped.\n */\nexport interface MaxGainResult {\n fullValueOnWinUsdcUnits: number;\n grossMaxGainUsdcUnits: number;\n netMaxGainUsdcUnits: number;\n}\n\n/**\n * Maximum gain (gross and net) for a winning settlement exit — profit over\n * principal. On a win each position token redeems at $1 (CTF settlement), so\n * the full value equals `positionTokenUnits` and there is NO exit trading fee.\n *\n * ```\n * fullValueOnWin = positionTokenUnits\n * grossMaxGain = fullValueOnWin - notionalUsdcUnits\n * netMaxGain = grossMaxGain - expectedOpenTradingFee - originationFee\n * ```\n *\n * Lifetime fees are excluded, so net max gain is an upper bound (a position held\n * to settlement accrues lifetime fees that reduce realized profit). Gains are\n * signed — a position whose principal exceeds its winning redemption value\n * yields a negative max gain.\n */\nexport function computeMaxGain(input: MaxGainInput): MaxGainResult {\n const fullValueOnWinUsdcUnits = input.positionTokenUnits;\n const grossMaxGainUsdcUnits = fullValueOnWinUsdcUnits - input.notionalUsdcUnits;\n const netMaxGainUsdcUnits =\n grossMaxGainUsdcUnits - input.expectedOpenTradingFeeUsdcUnits - input.originationFeeUsdcUnits;\n\n return {\n fullValueOnWinUsdcUnits,\n grossMaxGainUsdcUnits,\n netMaxGainUsdcUnits,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA,SAAS,sBAAsB;;;ACA/B,SAAS,oBAAoC;AAe7C,IAAM,oBAAoB;AAC1B,IAAM,yBAAyB;AAC/B,IAAM,sBAAsB;AAC5B,IAAM,6BAA6B;AACnC,IAAM,yBAAyB;AAC/B,IAAM,iBAAiB;AACvB,IAAM,gBAAgB;AAEtB,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;AAEA,SAAS,kBAAkB,QAAuB,SAAyB;AACz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AAG;AACjB,WAAO;AAAA,EACT;AACA,QAAM,eAAe,kBAAkB,WAAW,KAAK;AACvD,SAAO,gBAAgB,IAAI,oBAAoBA;AACjD;AAyCO,SAAS,eAAe,OAAoC;AACjE,QAAM,0BAA0B,MAAM;AACtC,QAAM,wBAAwB,0BAA0B,MAAM;AAC9D,QAAM,sBACJ,wBAAwB,MAAM,kCAAkC,MAAM;AAExE,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["BPS_DIVISOR"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { H as HintAdjustment } from './dimes-client-
|
|
2
|
-
import { O as Offer } from './aliases-
|
|
1
|
+
import { H as HintAdjustment } from './dimes-client-CerC9mTr.js';
|
|
2
|
+
import { O as Offer } from './aliases-ByZ2DcA5.js';
|
|
3
3
|
|
|
4
4
|
type Side = "yes" | "no";
|
|
5
5
|
interface QuoteParams {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { H as HintAdjustment } from './dimes-client-
|
|
2
|
-
import { O as Offer } from './aliases-
|
|
1
|
+
import { H as HintAdjustment } from './dimes-client-B-thu7VQ.cjs';
|
|
2
|
+
import { O as Offer } from './aliases-ByZ2DcA5.cjs';
|
|
3
3
|
|
|
4
4
|
type Side = "yes" | "no";
|
|
5
5
|
interface QuoteParams {
|
package/dist/react/index.cjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunkY5WQ3UWFcjs = require('../chunk-Y5WQ3UWF.cjs');
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
var
|
|
6
|
+
var _chunk72LTVPD2cjs = require('../chunk-72LTVPD2.cjs');
|
|
7
7
|
|
|
8
8
|
// src/react/provider.tsx
|
|
9
9
|
var _react = require('react');
|
|
@@ -15,7 +15,7 @@ function DimesProvider({ client, children }) {
|
|
|
15
15
|
function useDimesClient() {
|
|
16
16
|
const client = _react.useContext.call(void 0, DimesContext);
|
|
17
17
|
if (!client) {
|
|
18
|
-
throw new (0,
|
|
18
|
+
throw new (0, _chunk72LTVPD2cjs.DimesError)("missing_provider", "useDimesClient must be used within a <DimesProvider>");
|
|
19
19
|
}
|
|
20
20
|
return client;
|
|
21
21
|
}
|
|
@@ -59,7 +59,7 @@ function useQuote() {
|
|
|
59
59
|
async (params, options) => {
|
|
60
60
|
dispatch({ type: "loading" });
|
|
61
61
|
try {
|
|
62
|
-
const result = await
|
|
62
|
+
const result = await _chunkY5WQ3UWFcjs.executeQuote.call(void 0, client, params, {
|
|
63
63
|
...options,
|
|
64
64
|
onDraftReady: (draft) => {
|
|
65
65
|
dispatch({ type: "draftReady", draft });
|
package/dist/react/index.d.cts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
2
|
import { ReactNode } from 'react';
|
|
3
|
-
import { D as DimesClient, H as HintAdjustment,
|
|
4
|
-
import { O as Offer, M as Market, P as Position, d as ContractInfo, f as CustomerLimit } from '../aliases-
|
|
5
|
-
import { Q as QuoteParams, a as QuoteOptions, b as QuoteResult } from '../quote-
|
|
3
|
+
import { D as DimesClient, H as HintAdjustment, d as GetMarketsParams, P as Paginated, e as GetPositionsParams } from '../dimes-client-B-thu7VQ.cjs';
|
|
4
|
+
import { O as Offer, M as Market, P as Position, d as ContractInfo, f as CustomerLimit } from '../aliases-ByZ2DcA5.cjs';
|
|
5
|
+
import { Q as QuoteParams, a as QuoteOptions, b as QuoteResult } from '../quote-quIOosIv.cjs';
|
|
6
6
|
import { UseQueryOptions, UseQueryResult, UseMutationOptions, UseMutationResult } from '@tanstack/react-query';
|
|
7
7
|
|
|
8
8
|
interface DimesProviderProps {
|
package/dist/react/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
2
|
import { ReactNode } from 'react';
|
|
3
|
-
import { D as DimesClient, H as HintAdjustment,
|
|
4
|
-
import { O as Offer, M as Market, P as Position, d as ContractInfo, f as CustomerLimit } from '../aliases-
|
|
5
|
-
import { Q as QuoteParams, a as QuoteOptions, b as QuoteResult } from '../quote-
|
|
3
|
+
import { D as DimesClient, H as HintAdjustment, d as GetMarketsParams, P as Paginated, e as GetPositionsParams } from '../dimes-client-CerC9mTr.js';
|
|
4
|
+
import { O as Offer, M as Market, P as Position, d as ContractInfo, f as CustomerLimit } from '../aliases-ByZ2DcA5.js';
|
|
5
|
+
import { Q as QuoteParams, a as QuoteOptions, b as QuoteResult } from '../quote-Czq3Selh.js';
|
|
6
6
|
import { UseQueryOptions, UseQueryResult, UseMutationOptions, UseMutationResult } from '@tanstack/react-query';
|
|
7
7
|
|
|
8
8
|
interface DimesProviderProps {
|
package/dist/react/index.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
executeQuote
|
|
3
|
-
} from "../chunk-
|
|
3
|
+
} from "../chunk-3OPRSKCY.mjs";
|
|
4
4
|
import {
|
|
5
5
|
DimesError
|
|
6
|
-
} from "../chunk-
|
|
6
|
+
} from "../chunk-PZCBUVPD.mjs";
|
|
7
7
|
|
|
8
8
|
// src/react/provider.tsx
|
|
9
9
|
import { createContext, useContext } from "react";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as Position, M as Market,
|
|
1
|
+
import { P as Position, M as Market, I as MarketPolymarket, l as MarketLeverage } from './aliases-ByZ2DcA5.cjs';
|
|
2
2
|
|
|
3
3
|
declare const positionEventTypes: readonly ["position.cancelled", "position.close_requested", "position.closed", "position.created", "position.force_unwound", "position.liquidated", "position.opened", "position.opening", "position.reverted", "position.settled"];
|
|
4
4
|
type PositionEventType = (typeof positionEventTypes)[number];
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as Position, M as Market,
|
|
1
|
+
import { P as Position, M as Market, I as MarketPolymarket, l as MarketLeverage } from './aliases-ByZ2DcA5.js';
|
|
2
2
|
|
|
3
3
|
declare const positionEventTypes: readonly ["position.cancelled", "position.close_requested", "position.closed", "position.created", "position.force_unwound", "position.liquidated", "position.opened", "position.opening", "position.reverted", "position.settled"];
|
|
4
4
|
type PositionEventType = (typeof positionEventTypes)[number];
|
package/dist/ws/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { a as PositionEventType, P as PositionEvent, N as NotificationEvent, M as MarketEventType, b as MarketEvent } from '../types-
|
|
2
|
-
export { c as MarketDelta, d as MarketEventEnvelope, e as NotificationCode, f as NotificationEventEnvelope, g as PositionEventEnvelope, m as marketEventTypes, n as notificationCodes, p as positionEventTypes } from '../types-
|
|
3
|
-
import '../aliases-
|
|
1
|
+
import { a as PositionEventType, P as PositionEvent, N as NotificationEvent, M as MarketEventType, b as MarketEvent } from '../types-2bGyrtqd.cjs';
|
|
2
|
+
export { c as MarketDelta, d as MarketEventEnvelope, e as NotificationCode, f as NotificationEventEnvelope, g as PositionEventEnvelope, m as marketEventTypes, n as notificationCodes, p as positionEventTypes } from '../types-2bGyrtqd.cjs';
|
|
3
|
+
import '../aliases-ByZ2DcA5.cjs';
|
|
4
4
|
|
|
5
5
|
interface PositionSocketOptions {
|
|
6
6
|
baseUrl?: string;
|
package/dist/ws/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { a as PositionEventType, P as PositionEvent, N as NotificationEvent, M as MarketEventType, b as MarketEvent } from '../types-
|
|
2
|
-
export { c as MarketDelta, d as MarketEventEnvelope, e as NotificationCode, f as NotificationEventEnvelope, g as PositionEventEnvelope, m as marketEventTypes, n as notificationCodes, p as positionEventTypes } from '../types-
|
|
3
|
-
import '../aliases-
|
|
1
|
+
import { a as PositionEventType, P as PositionEvent, N as NotificationEvent, M as MarketEventType, b as MarketEvent } from '../types-CAuPxEwO.js';
|
|
2
|
+
export { c as MarketDelta, d as MarketEventEnvelope, e as NotificationCode, f as NotificationEventEnvelope, g as PositionEventEnvelope, m as marketEventTypes, n as notificationCodes, p as positionEventTypes } from '../types-CAuPxEwO.js';
|
|
3
|
+
import '../aliases-ByZ2DcA5.js';
|
|
4
4
|
|
|
5
5
|
interface PositionSocketOptions {
|
|
6
6
|
baseUrl?: string;
|