@crypticdot/defituna-api 1.10.16 → 3.0.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/index.js CHANGED
@@ -1,1545 +1,1565 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
- // If the importer is in node compatibility mode or this is not an ESM
21
- // file that has been converted to a CommonJS file using a Babel-
22
- // compatible transform (i.e. "__esModule" has not been set), then set
23
- // "default" to the CommonJS "module.exports" for node compatibility.
24
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
- mod
26
- ));
27
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
-
29
- // src/index.ts
30
- var index_exports = {};
31
- __export(index_exports, {
32
- NotificationAction: () => NotificationAction,
33
- NotificationEntity: () => NotificationEntity,
34
- PoolProvider: () => PoolProvider,
35
- PoolSubscriptionTopic: () => PoolSubscriptionTopic,
36
- ProviderFilter: () => ProviderFilter,
37
- TunaApiClient: () => TunaApiClient,
38
- TunaPositionState: () => TunaPositionState,
39
- WalletSubscriptionTopic: () => WalletSubscriptionTopic,
40
- schemas: () => schemas_exports
41
- });
42
- module.exports = __toCommonJS(index_exports);
43
-
44
- // src/client/client.ts
45
- var import_camelcase_keys = __toESM(require("camelcase-keys"));
46
- var import_snakecase_keys = __toESM(require("snakecase-keys"));
47
-
48
- // src/client/schemas.ts
49
- var schemas_exports = {};
50
- __export(schemas_exports, {
51
- AmountWithUsdSchema: () => AmountWithUsdSchema,
52
- AmountWithoutUsdSchema: () => AmountWithoutUsdSchema,
53
- CloseSpotPositionQuote: () => CloseSpotPositionQuote,
54
- DecreaseSpotPositionQuote: () => DecreaseSpotPositionQuote,
55
- FeesStatsGroup: () => FeesStatsGroup,
56
- IncreaseSpotPositionQuote: () => IncreaseSpotPositionQuote,
57
- LendingPosition: () => LendingPosition,
58
- LendingPositionNotification: () => LendingPositionNotification,
59
- LimitOrder: () => LimitOrder,
60
- LimitOrderQuoteByInput: () => LimitOrderQuoteByInput,
61
- LimitOrderQuoteByOutput: () => LimitOrderQuoteByOutput,
62
- LimitOrderState: () => LimitOrderState,
63
- LimitOrderStateSchema: () => LimitOrderStateSchema,
64
- LpPositionAutoCompound: () => LpPositionAutoCompound,
65
- LpPositionAutoCompoundSchema: () => LpPositionAutoCompoundSchema,
66
- LpPositionLimitOrderSwap: () => LpPositionLimitOrderSwap,
67
- LpPositionLimitOrderSwapSchema: () => LpPositionLimitOrderSwapSchema,
68
- LpPositionRebalance: () => LpPositionRebalance,
69
- LpPositionRebalanceSchema: () => LpPositionRebalanceSchema,
70
- LpPositionsActionType: () => LpPositionsActionType,
71
- LpPositionsActionTypeSchema: () => LpPositionsActionTypeSchema,
72
- Market: () => Market,
73
- Mint: () => Mint,
74
- NotificationAction: () => NotificationAction,
75
- NotificationActionSchema: () => NotificationActionSchema,
76
- NotificationEntity: () => NotificationEntity,
77
- NotificationEntitySchema: () => NotificationEntitySchema,
78
- OrderBook: () => OrderBook,
79
- OrderBookEntry: () => OrderBookEntry,
80
- OrderHistoryEntry: () => OrderHistoryEntry,
81
- OrderHistoryEntryNotification: () => OrderHistoryEntryNotification,
82
- OrderHistoryOrderType: () => OrderHistoryOrderType,
83
- OrderHistoryOrderTypeSchema: () => OrderHistoryOrderTypeSchema,
84
- OrderHistoryStatus: () => OrderHistoryStatus,
85
- OrderHistoryStatusSchema: () => OrderHistoryStatusSchema,
86
- OrderHistoryUIDirection: () => OrderHistoryUIDirection,
87
- OrderHistoryUIDirectionSchema: () => OrderHistoryUIDirectionSchema,
88
- PaginationMeta: () => PaginationMeta,
89
- Pool: () => Pool,
90
- PoolPriceCandle: () => PoolPriceCandle,
91
- PoolProvider: () => PoolProvider,
92
- PoolProviderSchema: () => PoolProviderSchema,
93
- PoolSubscriptionTopic: () => PoolSubscriptionTopic,
94
- PoolSubscriptionTopicSchema: () => PoolSubscriptionTopicSchema,
95
- PoolSwap: () => PoolSwap,
96
- PoolSwapNotification: () => PoolSwapNotification,
97
- PoolTicks: () => PoolTicks,
98
- StakingLeaderboardPage: () => StakingLeaderboardPage,
99
- StakingLeaderboardPosition: () => StakingLeaderboardPosition,
100
- StakingPosition: () => StakingPosition,
101
- StakingPositionHistoryAction: () => StakingPositionHistoryAction,
102
- StakingPositionHistoryActionType: () => StakingPositionHistoryActionType,
103
- StakingPositionHistoryActionTypeSchema: () => StakingPositionHistoryActionTypeSchema,
104
- StakingPositionNotification: () => StakingPositionNotification,
105
- StakingRevenueStatsGroup: () => StakingRevenueStatsGroup,
106
- StakingTreasury: () => StakingTreasury,
107
- StateSnapshot: () => StateSnapshot,
108
- StateSnapshotNotification: () => StateSnapshotNotification,
109
- SwapQuoteByInput: () => SwapQuoteByInput,
110
- SwapQuoteByOutput: () => SwapQuoteByOutput,
111
- Tick: () => Tick,
112
- TokenOraclePrice: () => TokenOraclePrice,
113
- TokensPnlSchema: () => TokensPnlSchema,
114
- TradableAmount: () => TradableAmount,
115
- TradeHistoryAction: () => TradeHistoryAction,
116
- TradeHistoryActionSchema: () => TradeHistoryActionSchema,
117
- TradeHistoryEntry: () => TradeHistoryEntry,
118
- TradeHistoryEntryNotification: () => TradeHistoryEntryNotification,
119
- TradeHistoryUIDirection: () => TradeHistoryUIDirection,
120
- TradeHistoryUIDirectionSchema: () => TradeHistoryUIDirectionSchema,
121
- TunaLpPositionAction: () => TunaLpPositionAction,
122
- TunaLpPositionActionClose: () => TunaLpPositionActionClose,
123
- TunaLpPositionActionCollectAndCompoundFees: () => TunaLpPositionActionCollectAndCompoundFees,
124
- TunaLpPositionActionCollectFees: () => TunaLpPositionActionCollectFees,
125
- TunaLpPositionActionDecreaseLiquidity: () => TunaLpPositionActionDecreaseLiquidity,
126
- TunaLpPositionActionIncreaseLiquidity: () => TunaLpPositionActionIncreaseLiquidity,
127
- TunaLpPositionActionLiquidate: () => TunaLpPositionActionLiquidate,
128
- TunaLpPositionActionOpen: () => TunaLpPositionActionOpen,
129
- TunaLpPositionActionParametersUpdate: () => TunaLpPositionActionParametersUpdate,
130
- TunaLpPositionActionRepayDebt: () => TunaLpPositionActionRepayDebt,
131
- TunaLpPositionAutoCompounding: () => TunaLpPositionAutoCompounding,
132
- TunaLpPositionAutoCompoundingSchema: () => TunaLpPositionAutoCompoundingSchema,
133
- TunaLpPositionDtoSchema: () => TunaLpPositionDtoSchema,
134
- TunaLpPositionFlagsSchema: () => TunaLpPositionFlagsSchema,
135
- TunaLpPositionHistorical: () => TunaLpPositionHistorical,
136
- TunaLpPositionParameters: () => TunaLpPositionParameters,
137
- TunaLpPositionTokenPrices: () => TunaLpPositionTokenPrices,
138
- TunaLpPositionTransfer: () => TunaLpPositionTransfer,
139
- TunaLpPositionValue: () => TunaLpPositionValue,
140
- TunaPositionLegacy: () => TunaPositionLegacy,
141
- TunaPositionPoolToken: () => TunaPositionPoolToken,
142
- TunaPositionPoolTokenSchema: () => TunaPositionPoolTokenSchema,
143
- TunaPositionState: () => TunaPositionState,
144
- TunaPositionStateSchema: () => TunaPositionStateSchema,
145
- TunaPositionTokenPnlSchema: () => TunaPositionTokenPnlSchema,
146
- TunaSpotPosition: () => TunaSpotPosition,
147
- TunaSpotPositionState: () => TunaSpotPositionState,
148
- TunaSpotPositionStateSchema: () => TunaSpotPositionStateSchema,
149
- UpdateStreamSubscriptionResult: () => UpdateStreamSubscriptionResult,
150
- UsdPnlSchema: () => UsdPnlSchema,
151
- Vault: () => Vault,
152
- VaultHistoricalStats: () => VaultHistoricalStats,
153
- WalletSubscriptionTopic: () => WalletSubscriptionTopic,
154
- WalletSubscriptionTopicSchema: () => WalletSubscriptionTopicSchema
155
- });
156
- var import_zod11 = require("zod");
157
-
158
- // src/client/schemas/basic.ts
159
- var import_zod = require("zod");
160
- var AmountWithUsdSchema = import_zod.z.object({
161
- amount: import_zod.z.coerce.bigint(),
162
- usd: import_zod.z.number()
163
- });
164
- var AmountWithoutUsdSchema = import_zod.z.object({
165
- amount: import_zod.z.coerce.bigint()
166
- });
167
- var TokensPnlSchema = import_zod.z.object({
168
- amount: import_zod.z.coerce.bigint(),
169
- rate: import_zod.z.number()
170
- });
171
- var UsdPnlSchema = import_zod.z.object({
172
- amount: import_zod.z.number(),
173
- rate: import_zod.z.number()
174
- });
175
-
176
- // src/client/schemas/pool.ts
177
- var import_zod3 = __toESM(require("zod"));
178
-
179
- // src/client/schemas/mint.ts
180
- var import_zod2 = require("zod");
181
- var Mint = import_zod2.z.object({
182
- address: import_zod2.z.string(),
183
- symbol: import_zod2.z.string(),
184
- name: import_zod2.z.string(),
185
- logo: import_zod2.z.string(),
186
- decimals: import_zod2.z.number()
187
- });
188
-
189
- // src/client/schemas/pool.ts
190
- var PoolProvider = {
191
- ORCA: "orca",
192
- FUSION: "fusion"
193
- };
194
- var PoolProviderSchema = import_zod3.default.enum([PoolProvider.ORCA, ...Object.values(PoolProvider)]);
195
- var Pool = import_zod3.default.object({
196
- address: import_zod3.default.string(),
197
- provider: PoolProviderSchema,
198
- mintA: Mint,
199
- mintB: Mint,
200
- tokenAVault: import_zod3.default.string(),
201
- tokenBVault: import_zod3.default.string(),
202
- tickSpacing: import_zod3.default.number(),
203
- feeRate: import_zod3.default.number(),
204
- protocolFeeRate: import_zod3.default.number(),
205
- olpFeeRate: import_zod3.default.nullable(import_zod3.default.number()),
206
- liquidity: import_zod3.default.coerce.bigint(),
207
- sqrtPrice: import_zod3.default.coerce.bigint(),
208
- price: import_zod3.default.number(),
209
- tickCurrentIndex: import_zod3.default.number(),
210
- stats: import_zod3.default.optional(
211
- import_zod3.default.nullable(
212
- import_zod3.default.object({
213
- tvlUsd: import_zod3.default.coerce.number(),
214
- groups: import_zod3.default.object({
215
- "24h": import_zod3.default.object({
216
- volumeUsd: import_zod3.default.number(),
217
- feesUsd: import_zod3.default.number(),
218
- priceChange: import_zod3.default.number()
219
- })
220
- })
221
- })
222
- )
223
- )
224
- });
225
-
226
- // src/client/schemas/state_snapshot.ts
227
- var import_zod10 = __toESM(require("zod"));
228
-
229
- // src/client/schemas/limit_orders.ts
230
- var import_zod4 = require("zod");
231
- var LimitOrderState = {
232
- OPEN: "open",
233
- PARTIALLY_FILLED: "partially_filled",
234
- FILLED: "filled",
235
- COMPLETE: "complete",
236
- CANCELLED: "cancelled"
237
- };
238
- var LimitOrderStateSchema = import_zod4.z.enum([LimitOrderState.OPEN, ...Object.values(LimitOrderState)]);
239
- var LimitOrder = import_zod4.z.object({
240
- address: import_zod4.z.string(),
241
- orderMint: import_zod4.z.string(),
242
- authority: import_zod4.z.string(),
243
- pool: Pool,
244
- state: LimitOrderStateSchema,
245
- aToB: import_zod4.z.boolean(),
246
- tickIndex: import_zod4.z.number(),
247
- fillRatio: import_zod4.z.number(),
248
- openTxSignature: import_zod4.z.string(),
249
- closeTxSignature: import_zod4.z.nullable(import_zod4.z.string()),
250
- amountIn: AmountWithUsdSchema,
251
- amountOut: AmountWithUsdSchema,
252
- openedAt: import_zod4.z.coerce.date(),
253
- closedAt: import_zod4.z.nullable(import_zod4.z.coerce.date())
254
- });
1
+ // src/baseUrl.ts
2
+ var baseUrl = "https://api.defituna.com/api";
3
+ function setTunaBaseUrl(url) {
4
+ baseUrl = url.replace(/\/$/, "");
5
+ }
6
+ function resolveTunaUrl(url, init) {
7
+ const resolvedBaseUrl = init?.baseUrl?.replace(/\/$/, "") ?? baseUrl;
8
+ const fullUrl = resolvedBaseUrl && !url.startsWith("http") ? `${resolvedBaseUrl}${url.startsWith("/") ? "" : "/"}${url}` : url;
9
+ return fullUrl;
10
+ }
255
11
 
256
- // src/client/schemas/lp_positions.ts
257
- var import_zod6 = __toESM(require("zod"));
12
+ // src/customFetch.ts
13
+ var snakeToCamel = (s) => s.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());
14
+ var camelToSnake = (s) => s.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
15
+ var isPlainObject = (v) => !!v && typeof v === "object" && Object.getPrototypeOf(v) === Object.prototype;
16
+ function mapKeysDeep(value, keyMap, onValue) {
17
+ const patched = onValue ? onValue(value) : value;
18
+ if (Array.isArray(patched)) {
19
+ return patched.map((x, _i) => mapKeysDeep(x, keyMap, onValue));
20
+ }
21
+ if (isPlainObject(patched)) {
22
+ const out = {};
23
+ for (const [k, v] of Object.entries(patched)) {
24
+ const nk = keyMap(k);
25
+ out[nk] = mapKeysDeep(v, keyMap, onValue);
26
+ }
27
+ return out;
28
+ }
29
+ return patched;
30
+ }
31
+ var ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;
32
+ var INT_STRING_RE = /^-?\d+$/;
33
+ function reviveScalars(v) {
34
+ if (typeof v !== "string") return v;
35
+ if (ISO_DATE_RE.test(v)) {
36
+ const d = new Date(v);
37
+ if (!Number.isNaN(d.getTime())) return d;
38
+ }
39
+ if (INT_STRING_RE.test(v)) {
40
+ try {
41
+ return BigInt(v);
42
+ } catch {
43
+ }
44
+ }
45
+ return v;
46
+ }
47
+ function normalizeResponseJson(raw) {
48
+ const revived = mapKeysDeep(raw, (k) => k, reviveScalars);
49
+ return mapKeysDeep(revived, snakeToCamel);
50
+ }
51
+ function normalizeRequestBody(body) {
52
+ return mapKeysDeep(body, camelToSnake);
53
+ }
54
+ function modifyQuery(url) {
55
+ const u = new URL(url);
56
+ const params = u.searchParams;
57
+ const grouped = /* @__PURE__ */ new Map();
58
+ for (const [key, value] of params.entries()) {
59
+ if (!grouped.has(key)) {
60
+ grouped.set(key, []);
61
+ }
62
+ grouped.get(key).push(value);
63
+ }
64
+ const newParams = new URLSearchParams();
65
+ for (const [key, values] of grouped.entries()) {
66
+ const snakeKey = camelToSnake(key);
67
+ newParams.set(snakeKey, values.join(","));
68
+ }
69
+ u.search = newParams.toString();
70
+ return u.toString();
71
+ }
72
+ async function customFetch(url, init) {
73
+ const fullUrl = resolveTunaUrl(url, init);
74
+ const finalInit = { ...init };
75
+ if (finalInit.body && typeof finalInit.body === "object" && !(finalInit.body instanceof FormData)) {
76
+ const snaked = normalizeRequestBody(finalInit.body);
77
+ finalInit.body = JSON.stringify(snaked);
78
+ finalInit.headers = {
79
+ "content-type": "application/json",
80
+ ...finalInit.headers || {}
81
+ };
82
+ }
83
+ const fullUrlWithQuery = modifyQuery(fullUrl);
84
+ const res = await fetch(fullUrlWithQuery, finalInit);
85
+ const text = await res.text();
86
+ let data = void 0;
87
+ try {
88
+ const raw = JSON.parse(text);
89
+ data = normalizeResponseJson(raw);
90
+ } catch {
91
+ }
92
+ return { status: res.status, data };
93
+ }
258
94
 
259
- // src/client/schemas/positions_shared.ts
260
- var import_zod5 = __toESM(require("zod"));
261
- var TunaPositionPoolToken = {
262
- A: "a",
263
- B: "b"
95
+ // src/gen/defiTunaAPI.ts
96
+ var LeaderboardPeriod = {
97
+ week: "week"
264
98
  };
265
- var TunaPositionPoolTokenSchema = import_zod5.default.enum(Object.values(TunaPositionPoolToken));
266
-
267
- // src/client/schemas/lp_positions.ts
268
- var LpPositionLimitOrderSwap = {
269
- NO_SWAP: "no_swap",
270
- SWAP_TO_TOKEN_A: "swap_to_token_a",
271
- SWAP_TO_TOKEN_B: "swap_to_token_b"
272
- };
273
- var LpPositionAutoCompound = {
274
- NO_AUTO_COMPOUND: "no_auto_compound",
275
- AUTO_COMPOUND: "auto_compound",
276
- AUTO_COMPOUND_WITH_LEVERAGE: "auto_compound_with_leverage"
277
- };
278
- var LpPositionRebalance = {
279
- NO_REBALANCE: "no_rebalance",
280
- AUTO_REBALANCE: "auto_rebalance"
281
- };
282
- var LpPositionsActionType = {
283
- OPEN_POSITION: "open_position",
284
- CLOSE_POSITION: "close_position",
285
- INCREASE_LIQUIDITY: "increase_liquidity",
286
- DECREASE_LIQUIDITY: "decrease_liquidity",
287
- REPAY_DEBT: "repay_debt",
288
- LIQUIDATE: "liquidate",
289
- EXECUTE_LIMIT_ORDER: "execute_limit_order",
290
- COLLECT_FEES: "collect_fees",
291
- COLLECT_REWARDS: "collect_rewards",
292
- COLLECT_AND_COMPOUND_FEES: "collect_and_compound_fees",
293
- REBALANCE_POSITION: "rebalance_position",
294
- SET_LIMIT_ORDERS: "set_limit_orders",
295
- SET_FLAGS: "set_flags",
296
- SET_REBALANCE_THRESHOLD: "set_rebalance_threshold"
297
- };
298
- var LpPositionLimitOrderSwapSchema = import_zod6.default.enum(Object.values(LpPositionLimitOrderSwap));
299
- var LpPositionAutoCompoundSchema = import_zod6.default.enum(Object.values(LpPositionAutoCompound));
300
- var LpPositionRebalanceSchema = import_zod6.default.enum(Object.values(LpPositionRebalance));
301
- var LpPositionsActionTypeSchema = import_zod6.default.enum(Object.values(LpPositionsActionType));
302
- var TunaPositionState = {
303
- OPEN: "open",
304
- LIQUIDATED: "liquidated",
305
- CLOSED_BY_LIMIT_ORDER: "closed_by_limit_order",
306
- CLOSED: "closed"
307
- };
308
- var TunaPositionStateSchema = import_zod6.default.enum([TunaPositionState.OPEN, ...Object.values(TunaPositionState)]);
309
- var TunaLpPositionAutoCompounding = {
310
- WITH_LEVERAGE: "with_leverage",
311
- WITHOUT_LEVERAGE: "without_leverage"
312
- };
313
- var TunaLpPositionAutoCompoundingSchema = import_zod6.default.enum(
314
- Object.values(TunaLpPositionAutoCompounding)
315
- );
316
- var TunaPositionTokenPnlSchema = import_zod6.default.object({
317
- amount: import_zod6.default.coerce.bigint(),
318
- bps: import_zod6.default.number()
319
- });
320
- var TunaLpPositionFlagsSchema = import_zod6.default.object({
321
- lowerLimitOrderSwapToToken: import_zod6.default.nullable(TunaPositionPoolTokenSchema),
322
- upperLimitOrderSwapToToken: import_zod6.default.nullable(TunaPositionPoolTokenSchema),
323
- autoCompounding: import_zod6.default.nullable(TunaLpPositionAutoCompoundingSchema),
324
- autoRebalancing: import_zod6.default.boolean()
325
- });
326
- var TunaLpPositionDtoSchema = import_zod6.default.object({
327
- address: import_zod6.default.string(),
328
- authority: import_zod6.default.string(),
329
- version: import_zod6.default.number(),
330
- state: TunaPositionStateSchema,
331
- positionMint: import_zod6.default.string(),
332
- liquidity: import_zod6.default.coerce.bigint(),
333
- tickLowerIndex: import_zod6.default.number(),
334
- tickUpperIndex: import_zod6.default.number(),
335
- lowerLimitOrderPrice: import_zod6.default.number(),
336
- upperLimitOrderPrice: import_zod6.default.number(),
337
- entryPrice: import_zod6.default.number(),
338
- flags: TunaLpPositionFlagsSchema,
339
- pool: Pool,
340
- marketMaker: PoolProviderSchema,
341
- depositedCollateralA: AmountWithUsdSchema,
342
- depositedCollateralB: AmountWithUsdSchema,
343
- leverage: import_zod6.default.number(),
344
- maxLeverage: import_zod6.default.number(),
345
- liquidationPriceLower: import_zod6.default.number(),
346
- liquidationPriceUpper: import_zod6.default.number(),
347
- initialDebtA: AmountWithUsdSchema,
348
- initialDebtB: AmountWithUsdSchema,
349
- currentDebtA: AmountWithUsdSchema,
350
- currentDebtB: AmountWithUsdSchema,
351
- leftoversA: AmountWithUsdSchema,
352
- leftoversB: AmountWithUsdSchema,
353
- yieldA: AmountWithUsdSchema,
354
- yieldB: AmountWithUsdSchema,
355
- compoundedYieldA: AmountWithUsdSchema,
356
- compoundedYieldB: AmountWithUsdSchema,
357
- totalA: AmountWithUsdSchema,
358
- totalB: AmountWithUsdSchema,
359
- pnlA: TokensPnlSchema,
360
- pnlB: TokensPnlSchema,
361
- pnlUsd: UsdPnlSchema,
362
- openedAt: import_zod6.default.coerce.date(),
363
- closedAt: import_zod6.default.nullable(import_zod6.default.coerce.date())
364
- });
365
- var TunaLpPositionHistorical = import_zod6.default.object({
366
- positionAddress: import_zod6.default.string(),
367
- authority: import_zod6.default.string(),
368
- pool: import_zod6.default.string(),
369
- state: TunaPositionStateSchema,
370
- lowerPrice: import_zod6.default.number(),
371
- upperPrice: import_zod6.default.number(),
372
- lowerLimitOrder: import_zod6.default.number().nullable(),
373
- upperLimitOrder: import_zod6.default.number().nullable(),
374
- marketMaker: PoolProviderSchema,
375
- openedAt: import_zod6.default.coerce.date(),
376
- closedAt: import_zod6.default.coerce.date().nullable(),
377
- totalValueUsd: import_zod6.default.number(),
378
- leverage: import_zod6.default.number(),
379
- initialLeverage: import_zod6.default.number(),
380
- totalDepositUsd: import_zod6.default.number(),
381
- totalWithdrawnUsd: import_zod6.default.number(),
382
- feesSumUsd: import_zod6.default.number(),
383
- closedPnlSumUsd: import_zod6.default.number(),
384
- entryPrice: import_zod6.default.number(),
385
- exitPrice: import_zod6.default.number().nullable()
386
- });
387
- var TunaPositionLegacy = import_zod6.default.object({
388
- address: import_zod6.default.string(),
389
- authority: import_zod6.default.string(),
390
- version: import_zod6.default.number(),
391
- state: TunaPositionStateSchema,
392
- positionMint: import_zod6.default.string(),
393
- liquidity: import_zod6.default.coerce.bigint(),
394
- tickLowerIndex: import_zod6.default.number(),
395
- tickUpperIndex: import_zod6.default.number(),
396
- entrySqrtPrice: import_zod6.default.coerce.bigint(),
397
- lowerLimitOrderSqrtPrice: import_zod6.default.coerce.bigint(),
398
- upperLimitOrderSqrtPrice: import_zod6.default.coerce.bigint(),
399
- flags: import_zod6.default.number(),
400
- pool: import_zod6.default.string(),
401
- poolSqrtPrice: import_zod6.default.coerce.bigint(),
402
- depositedCollateralA: AmountWithoutUsdSchema,
403
- depositedCollateralB: AmountWithoutUsdSchema,
404
- depositedCollateralUsd: import_zod6.default.object({
405
- amount: import_zod6.default.number()
406
- }),
407
- loanFundsA: AmountWithUsdSchema,
408
- loanFundsB: AmountWithUsdSchema,
409
- currentLoanA: AmountWithUsdSchema,
410
- currentLoanB: AmountWithUsdSchema,
411
- leftoversA: AmountWithUsdSchema,
412
- leftoversB: AmountWithUsdSchema,
413
- yieldA: AmountWithUsdSchema,
414
- yieldB: AmountWithUsdSchema,
415
- compoundedYieldA: AmountWithUsdSchema,
416
- compoundedYieldB: AmountWithUsdSchema,
417
- totalA: AmountWithUsdSchema,
418
- totalB: AmountWithUsdSchema,
419
- pnlA: TokensPnlSchema,
420
- pnlB: TokensPnlSchema,
421
- pnlUsd: UsdPnlSchema,
422
- openedAt: import_zod6.default.coerce.date(),
423
- updatedAtSlot: import_zod6.default.coerce.bigint(),
424
- closedAt: import_zod6.default.nullable(import_zod6.default.coerce.date())
425
- });
426
- var TunaLpPositionParameters = import_zod6.default.object({
427
- lowerPrice: import_zod6.default.number(),
428
- upperPrice: import_zod6.default.number(),
429
- lowerLimitOrder: import_zod6.default.number().nullable(),
430
- upperLimitOrder: import_zod6.default.number().nullable(),
431
- lowerLimitOrderSwap: LpPositionLimitOrderSwapSchema,
432
- upperLimitOrderSwap: LpPositionLimitOrderSwapSchema,
433
- autoCompound: LpPositionAutoCompoundSchema,
434
- rebalance: LpPositionRebalanceSchema,
435
- rebalanceThresholdTicks: import_zod6.default.number()
436
- });
437
- var TunaLpPositionValue = import_zod6.default.object({
438
- totalValueA: import_zod6.default.number(),
439
- totalValueB: import_zod6.default.number(),
440
- totalValueUsd: import_zod6.default.number(),
441
- loanFundsA: import_zod6.default.number(),
442
- loanFundsB: import_zod6.default.number(),
443
- loanFundsUsd: import_zod6.default.number(),
444
- leverage: import_zod6.default.number()
445
- });
446
- var TunaLpPositionTransfer = import_zod6.default.object({
447
- amountA: import_zod6.default.number(),
448
- amountB: import_zod6.default.number(),
449
- amountUsd: import_zod6.default.number()
450
- });
451
- var TunaLpPositionTokenPrices = import_zod6.default.object({
452
- tokenPriceA: import_zod6.default.number(),
453
- tokenPriceB: import_zod6.default.number()
454
- });
455
- var TunaLpPositionActionOpen = import_zod6.default.object({
456
- parameters: TunaLpPositionParameters
457
- });
458
- var TunaLpPositionActionClose = import_zod6.default.object({
459
- toOwner: TunaLpPositionTransfer.nullable(),
460
- prices: TunaLpPositionTokenPrices.nullable()
461
- });
462
- var TunaLpPositionActionIncreaseLiquidity = import_zod6.default.object({
463
- fromPosition: TunaLpPositionValue.nullable(),
464
- toPosition: TunaLpPositionValue,
465
- fromOwner: TunaLpPositionTransfer,
466
- fromLending: TunaLpPositionTransfer,
467
- protocolFees: TunaLpPositionTransfer,
468
- prices: TunaLpPositionTokenPrices
469
- });
470
- var TunaLpPositionActionDecreaseLiquidity = import_zod6.default.object({
471
- withdrawPercent: import_zod6.default.number(),
472
- closedPnlUsd: import_zod6.default.number(),
473
- fromPosition: TunaLpPositionValue,
474
- toPosition: TunaLpPositionValue.nullable(),
475
- toOwner: TunaLpPositionTransfer,
476
- toLending: TunaLpPositionTransfer,
477
- collectedFees: TunaLpPositionTransfer,
478
- prices: TunaLpPositionTokenPrices
479
- });
480
- var TunaLpPositionActionLiquidate = import_zod6.default.object({
481
- withdrawPercent: import_zod6.default.number(),
482
- fromPosition: TunaLpPositionValue,
483
- toLending: TunaLpPositionTransfer,
484
- protocolFees: TunaLpPositionTransfer,
485
- prices: TunaLpPositionTokenPrices
486
- });
487
- var TunaLpPositionActionRepayDebt = import_zod6.default.object({
488
- fromPosition: TunaLpPositionValue,
489
- toPosition: TunaLpPositionValue,
490
- fromOwner: TunaLpPositionTransfer,
491
- toLending: TunaLpPositionTransfer,
492
- prices: TunaLpPositionTokenPrices
493
- });
494
- var TunaLpPositionActionCollectFees = import_zod6.default.object({
495
- closedPnlUsd: import_zod6.default.number(),
496
- position: TunaLpPositionValue,
497
- collectedFees: TunaLpPositionTransfer,
498
- toOwner: TunaLpPositionTransfer,
499
- prices: TunaLpPositionTokenPrices
500
- });
501
- var TunaLpPositionActionCollectAndCompoundFees = import_zod6.default.object({
502
- fromPosition: TunaLpPositionValue,
503
- toPosition: TunaLpPositionValue,
504
- collectedFees: TunaLpPositionTransfer,
505
- fromLending: TunaLpPositionTransfer,
506
- protocolFees: TunaLpPositionTransfer,
507
- prices: TunaLpPositionTokenPrices
508
- });
509
- var TunaLpPositionActionParametersUpdate = import_zod6.default.object({
510
- fromParameters: TunaLpPositionParameters,
511
- toParameters: TunaLpPositionParameters
512
- });
513
- var TunaLpPositionAction = import_zod6.default.object({
514
- action: LpPositionsActionTypeSchema,
515
- txSignature: import_zod6.default.string(),
516
- txTimestamp: import_zod6.default.coerce.date(),
517
- data: import_zod6.default.object({
518
- /** defined for: IncreaseLiquidity, DecreaseLiquidity, Liquidate, ExecuteLimitOrder, RepayDebt, CollectAndCompoundFees */
519
- fromPosition: TunaLpPositionValue.optional().nullable(),
520
- /** defined for: IncreaseLiquidity, DecreaseLiquidity, Liquidate, ExecuteLimitOrder, RepayDebt, CollectAndCompoundFees */
521
- toPosition: TunaLpPositionValue.optional().nullable(),
522
- /** defined for: CollectFees */
523
- position: TunaLpPositionValue.optional().nullable(),
524
- /** defined for: IncreaseLiquidity, RepayDebt */
525
- fromOwner: TunaLpPositionTransfer.optional(),
526
- /** defined for: DecreaseLiquidity, CollectFees, ClosePosition; nullable for: ClosePosition */
527
- toOwner: TunaLpPositionTransfer.optional().nullable(),
528
- /** defined for: IncreaseLiquidity, CollectAndCompoundFees */
529
- fromLending: TunaLpPositionTransfer.optional(),
530
- /** defined for: DecreaseLiquidity, Liquidate, ExecuteLimitOrder, RepayDebt */
531
- toLending: TunaLpPositionTransfer.optional(),
532
- /** defined for: CollectFees, CollectAndCompoundFees */
533
- collectedFees: TunaLpPositionTransfer.optional(),
534
- /** defined for: IncreaseLiquidity, Liquidate, ExecuteLimitOrder, CollectAndCompoundFees */
535
- protocolFees: TunaLpPositionTransfer.optional(),
536
- /** defined for: IncreaseLiquidity, DecreaseLiquidity, Liquidate, ExecuteLimitOrder, RepayDebt, CollectFees, CollectAndCompoundFees, ClosePosition; nullable for: ClosePosition */
537
- prices: TunaLpPositionTokenPrices.optional().nullable(),
538
- /** defined for: OpenPosition */
539
- parameters: TunaLpPositionParameters.optional(),
540
- /** defined for: ParametersUpdate */
541
- fromParameters: TunaLpPositionParameters.optional(),
542
- /** defined for: ParametersUpdate */
543
- toParameters: TunaLpPositionParameters.optional(),
544
- /** defined for: DecreaseLiquidity */
545
- withdrawPercent: import_zod6.default.number().optional(),
546
- /** defined for: DecreaseLiquidity, CollectFees */
547
- closedPnlUsd: import_zod6.default.number().optional()
548
- })
549
- });
550
-
551
- // src/client/schemas/market.ts
552
- var import_zod7 = require("zod");
553
- var Market = import_zod7.z.object({
554
- address: import_zod7.z.string(),
555
- addressLookupTable: import_zod7.z.string(),
556
- maxLeverage: import_zod7.z.number(),
557
- maxSwapSlippage: import_zod7.z.number(),
558
- protocolFee: import_zod7.z.number(),
559
- protocolFeeOnCollateral: import_zod7.z.number(),
560
- liquidationFee: import_zod7.z.number(),
561
- liquidationThreshold: import_zod7.z.number(),
562
- oraclePriceDeviationThreshold: import_zod7.z.number(),
563
- rebalanceProtocolFee: import_zod7.z.number(),
564
- borrowedFundsA: AmountWithUsdSchema,
565
- borrowedFundsB: AmountWithUsdSchema,
566
- borrowLimitA: AmountWithUsdSchema,
567
- borrowLimitB: AmountWithUsdSchema,
568
- maxSpotPositionSizeA: AmountWithUsdSchema,
569
- maxSpotPositionSizeB: AmountWithUsdSchema,
570
- pool: Pool,
571
- disabled: import_zod7.z.boolean(),
572
- createdAt: import_zod7.z.coerce.date()
573
- });
574
-
575
- // src/client/schemas/order_book.ts
576
- var import_zod8 = __toESM(require("zod"));
577
- var OrderBookEntry = import_zod8.default.object({
578
- concentratedAmount: import_zod8.default.coerce.bigint(),
579
- concentratedAmountQuote: import_zod8.default.coerce.bigint(),
580
- concentratedTotal: import_zod8.default.coerce.bigint(),
581
- concentratedTotalQuote: import_zod8.default.coerce.bigint(),
582
- limitAmount: import_zod8.default.coerce.bigint(),
583
- limitAmountQuote: import_zod8.default.coerce.bigint(),
584
- limitTotal: import_zod8.default.coerce.bigint(),
585
- limitTotalQuote: import_zod8.default.coerce.bigint(),
586
- price: import_zod8.default.number(),
587
- askSide: import_zod8.default.boolean()
588
- });
589
- var OrderBook = import_zod8.default.object({
590
- entries: OrderBookEntry.array(),
591
- poolPrice: import_zod8.default.number(),
592
- poolAddress: import_zod8.default.string()
593
- });
594
-
595
- // src/client/schemas/spot_positions.ts
596
- var import_zod9 = require("zod");
597
- var TunaSpotPositionState = {
598
- OPEN: "open",
599
- CLOSED: "closed"
600
- };
601
- var TunaSpotPositionStateSchema = import_zod9.z.enum([
602
- TunaSpotPositionState.OPEN,
603
- ...Object.values(TunaSpotPositionState)
604
- ]);
605
- var TunaSpotPosition = import_zod9.z.object({
606
- address: import_zod9.z.string(),
607
- authority: import_zod9.z.string(),
608
- version: import_zod9.z.number(),
609
- state: TunaSpotPositionStateSchema,
610
- lowerLimitOrderPrice: import_zod9.z.number(),
611
- upperLimitOrderPrice: import_zod9.z.number(),
612
- entryPrice: import_zod9.z.number(),
613
- pool: Pool,
614
- positionToken: TunaPositionPoolTokenSchema,
615
- collateralToken: TunaPositionPoolTokenSchema,
616
- marketMaker: PoolProviderSchema,
617
- depositedCollateral: AmountWithUsdSchema,
618
- initialDebt: AmountWithUsdSchema,
619
- currentDebt: AmountWithUsdSchema,
620
- total: AmountWithUsdSchema,
621
- leverage: import_zod9.z.number(),
622
- maxLeverage: import_zod9.z.number(),
623
- liquidationPrice: import_zod9.z.number(),
624
- pnlUsd: UsdPnlSchema,
625
- openedAt: import_zod9.z.coerce.date(),
626
- closedAt: import_zod9.z.nullable(import_zod9.z.coerce.date())
627
- });
628
- var IncreaseSpotPositionQuote = import_zod9.z.object({
629
- /** Required collateral amount */
630
- collateralAmount: import_zod9.z.coerce.bigint(),
631
- /** Required amount to borrow */
632
- borrowAmount: import_zod9.z.coerce.bigint(),
633
- /** Estimated position size in the position token. */
634
- estimatedAmount: import_zod9.z.coerce.bigint(),
635
- /** Swap input amount. */
636
- swapInputAmount: import_zod9.z.coerce.bigint(),
637
- /** Minimum swap output amount according to the provided slippage. */
638
- minSwapOutputAmount: import_zod9.z.coerce.bigint(),
639
- /** Protocol fee in token A */
640
- protocolFeeA: import_zod9.z.coerce.bigint(),
641
- /** Protocol fee in token B */
642
- protocolFeeB: import_zod9.z.coerce.bigint(),
643
- /** Price impact in percents */
644
- priceImpact: import_zod9.z.number(),
645
- /** Liquidation price */
646
- liquidationPrice: import_zod9.z.number()
647
- });
648
- var DecreaseSpotPositionQuote = import_zod9.z.object({
649
- /** Confirmed position decrease percentage (100% = 1.0) */
650
- decreasePercent: import_zod9.z.number(),
651
- /** The maximum acceptable swap input amount for position decrease according to the provided slippage
652
- * (if collateral_token == position_token) OR the minimum swap output amount (if collateral_token != position_token).
653
- */
654
- requiredSwapAmount: import_zod9.z.coerce.bigint(),
655
- /** Estimated total amount of the adjusted position */
656
- estimatedAmount: import_zod9.z.coerce.bigint(),
657
- /** Estimated amount of the withdrawn collateral */
658
- estimatedWithdrawnCollateral: import_zod9.z.coerce.bigint(),
659
- /** Price impact in percents */
660
- priceImpact: import_zod9.z.number(),
661
- /** Liquidation price */
662
- liquidationPrice: import_zod9.z.number()
663
- });
664
- var CloseSpotPositionQuote = import_zod9.z.object({
665
- /** Position decrease percentage */
666
- decreasePercent: import_zod9.z.number(),
667
- /** The maximum acceptable swap input amount for position decrease according to the provided slippage
668
- * (if collateral_token == position_token) OR the minimum swap output amount (if collateral_token != position_token).
669
- */
670
- requiredSwapAmount: import_zod9.z.coerce.bigint(),
671
- /** Estimated amount of the withdrawn collateral */
672
- estimatedWithdrawnCollateral: import_zod9.z.coerce.bigint(),
673
- /** Price impact in percents */
674
- priceImpact: import_zod9.z.number()
675
- });
676
-
677
- // src/client/schemas/state_snapshot.ts
678
- var StateSnapshot = import_zod10.default.object({
679
- slot: import_zod10.default.coerce.bigint(),
680
- blockTime: import_zod10.default.coerce.date(),
681
- markets: import_zod10.default.optional(import_zod10.default.array(Market)),
682
- tunaSpotPositions: import_zod10.default.optional(import_zod10.default.array(TunaSpotPosition)),
683
- tunaLpPositions: import_zod10.default.optional(import_zod10.default.array(TunaLpPositionDtoSchema)),
684
- fusionLimitOrders: import_zod10.default.optional(import_zod10.default.array(LimitOrder)),
685
- orderBooks: import_zod10.default.optional(import_zod10.default.array(OrderBook))
686
- });
687
-
688
- // src/client/schemas.ts
689
- var NotificationEntity = {
690
- POOL_SWAP: "pool_swap",
691
- LENDING_POSITION: "lending_position",
692
- STAKING_POSITION: "staking_position",
693
- MARKET: "market",
694
- TRADE_HISTORY_ENTRY: "trade_history_entry",
695
- ORDER_HISTORY_ENTRY: "order_history_entry",
696
- STATE_SNAPSHOT: "state_snapshot"
99
+ var LeaderboardSortBy = {
100
+ profit: "profit",
101
+ percent: "percent"
697
102
  };
698
- var NotificationAction = {
699
- CREATE: "create",
700
- UPDATE: "update"
103
+ var LimitOrderStatus = {
104
+ open: "open",
105
+ partiallyFilled: "partially_filled",
106
+ filled: "filled",
107
+ complete: "complete",
108
+ cancelled: "cancelled"
701
109
  };
702
- var TradeHistoryAction = {
703
- SWAP: "swap",
704
- LIMIT_ORDER_FILL: "limit_order_fill",
705
- POSITION_INCREASE: "position_increase",
706
- POSITION_DECREASE: "position_decrease",
707
- TAKE_PROFIT: "take_profit",
708
- STOP_LOSS: "stop_loss",
709
- LIQUIDATION: "liquidation"
110
+ var LpPositionsHistoryQueryFilter = {
111
+ opened: "opened",
112
+ closed: "closed",
113
+ all: "all"
710
114
  };
711
- var TradeHistoryUIDirection = {
712
- BUY: "buy",
713
- SELL: "sell",
714
- OPEN_LONG: "open_long",
715
- CLOSE_LONG: "close_long",
716
- OPEN_SHORT: "open_short",
717
- CLOSE_SHORT: "close_short"
718
- };
719
- var OrderHistoryOrderType = {
720
- MARKET: "market",
721
- LIMIT: "limit",
722
- TAKE_PROFIT_MARKET: "take_profit_market",
723
- STOP_LOSS_MARKET: "stop_loss_market",
724
- LIQUIDATION_MARKET: "liquidation_market"
115
+ var NotificationAction = {
116
+ create: "create",
117
+ update: "update"
118
+ };
119
+ var NotificationEntity = {
120
+ initialMessage: "initial_message",
121
+ poolSwap: "pool_swap",
122
+ orderBook: "order_book",
123
+ oraclePrice: "oracle_price",
124
+ market: "market",
125
+ tunaPosition: "tuna_position",
126
+ tunaSpotPosition: "tuna_spot_position",
127
+ stakingPosition: "staking_position",
128
+ lendingPosition: "lending_position",
129
+ fusionLimitOrder: "fusion_limit_order",
130
+ tradeHistoryEntry: "trade_history_entry",
131
+ orderHistoryEntry: "order_history_entry",
132
+ stateSnapshot: "state_snapshot"
725
133
  };
726
134
  var OrderHistoryStatus = {
727
- OPEN: "open",
728
- PARTIALLY_FILLED: "partially_filled",
729
- FILLED: "filled",
730
- CANCELLED: "cancelled",
731
- CLAIMED: "claimed",
732
- REJECTED: "rejected"
135
+ open: "open",
136
+ partiallyFilled: "partially_filled",
137
+ filled: "filled",
138
+ cancelled: "cancelled",
139
+ claimed: "claimed",
140
+ rejected: "rejected"
141
+ };
142
+ var OrderHistoryType = {
143
+ market: "market",
144
+ limit: "limit",
145
+ takeProfitMarket: "take_profit_market",
146
+ stopLossMarket: "stop_loss_market",
147
+ liquidationMarket: "liquidation_market"
733
148
  };
734
149
  var OrderHistoryUIDirection = {
735
- BUY: "buy",
736
- SELL: "sell",
737
- LONG: "long",
738
- SHORT: "short"
739
- };
740
- var StakingPositionHistoryActionType = {
741
- STAKE: "stake",
742
- UNSTAKE: "unstake",
743
- WITHDRAW: "withdraw",
744
- CLAIM_REWARDS: "claim_rewards",
745
- COMPOUND_REWARDS: "compound_rewards"
150
+ buy: "buy",
151
+ sell: "sell",
152
+ long: "long",
153
+ short: "short"
154
+ };
155
+ var PoolProvider = {
156
+ orca: "orca",
157
+ fusion: "fusion"
746
158
  };
747
159
  var PoolSubscriptionTopic = {
748
- ORDER_BOOK: "order_book",
749
- POOL_SWAPS: "pool_swaps"
160
+ poolSwaps: "pool_swaps",
161
+ orderBook: "order_book",
162
+ poolPrices: "pool_prices"
163
+ };
164
+ var StakingPositionActionType = {
165
+ stake: "stake",
166
+ unstake: "unstake",
167
+ withdraw: "withdraw",
168
+ claimRewards: "claim_rewards",
169
+ compoundRewards: "compound_rewards"
170
+ };
171
+ var TradeHistoryAction = {
172
+ swap: "swap",
173
+ limitOrderFill: "limit_order_fill",
174
+ positionIncrease: "position_increase",
175
+ positionDecrease: "position_decrease",
176
+ takeProfit: "take_profit",
177
+ stopLoss: "stop_loss",
178
+ liquidation: "liquidation"
179
+ };
180
+ var TradeHistoryUIDirection = {
181
+ buy: "buy",
182
+ sell: "sell",
183
+ openLong: "open_long",
184
+ closeLong: "close_long",
185
+ openShort: "open_short",
186
+ closeShort: "close_short"
187
+ };
188
+ var TunaLpPositionAutoCompound = {
189
+ noAutoCompound: "no_auto_compound",
190
+ autoCompound: "auto_compound",
191
+ autoCompoundWithLeverage: "auto_compound_with_leverage"
192
+ };
193
+ var TunaLpPositionAutoCompounding = {
194
+ withLeverage: "with_leverage",
195
+ withoutLeverage: "without_leverage"
196
+ };
197
+ var TunaLpPositionLimitOrderSwap = {
198
+ noSwap: "no_swap",
199
+ swapToTokenA: "swap_to_token_a",
200
+ swapToTokenB: "swap_to_token_b"
201
+ };
202
+ var TunaLpPositionRebalance = {
203
+ noRebalance: "no_rebalance",
204
+ autoRebalance: "auto_rebalance"
205
+ };
206
+ var TunaLpPositionsActionType = {
207
+ openPosition: "open_position",
208
+ closePosition: "close_position",
209
+ increaseLiquidity: "increase_liquidity",
210
+ decreaseLiquidity: "decrease_liquidity",
211
+ repayDebt: "repay_debt",
212
+ liquidate: "liquidate",
213
+ executeLimitOrder: "execute_limit_order",
214
+ collectFees: "collect_fees",
215
+ collectRewards: "collect_rewards",
216
+ collectAndCompoundFees: "collect_and_compound_fees",
217
+ rebalancePosition: "rebalance_position",
218
+ setLimitOrders: "set_limit_orders",
219
+ setFlags: "set_flags",
220
+ setRebalanceThreshold: "set_rebalance_threshold"
221
+ };
222
+ var TunaPositionDtoState = {
223
+ open: "open",
224
+ liquidated: "liquidated",
225
+ closedByLimitOrder: "closed_by_limit_order",
226
+ closed: "closed"
227
+ };
228
+ var TunaPositionMarketMaker = {
229
+ fusion: "fusion",
230
+ orca: "orca"
231
+ };
232
+ var TunaPositionPoolToken = {
233
+ a: "a",
234
+ b: "b"
235
+ };
236
+ var TunaSpotPositionDtoState = {
237
+ open: "open",
238
+ closed: "closed"
750
239
  };
751
240
  var WalletSubscriptionTopic = {
752
- TUNA_POSITIONS: "tuna_positions",
753
- TUNA_SPOT_POSITIONS: "tuna_spot_positions",
754
- LENDING_POSITIONS: "lending_positions",
755
- FUSION_LIMIT_ORDERS: "fusion_limit_orders",
756
- STAKING_POSITION: "staking_position",
757
- TRADE_HISTORY: "trade_history",
758
- ORDER_HISTORY: "order_history"
759
- };
760
- var NotificationEntitySchema = import_zod11.z.enum([NotificationEntity.POOL_SWAP, ...Object.values(NotificationEntity)]);
761
- var NotificationActionSchema = import_zod11.z.enum([NotificationAction.CREATE, ...Object.values(NotificationAction)]);
762
- var TradeHistoryActionSchema = import_zod11.z.enum([TradeHistoryAction.SWAP, ...Object.values(TradeHistoryAction)]);
763
- var TradeHistoryUIDirectionSchema = import_zod11.z.enum([
764
- TradeHistoryUIDirection.BUY,
765
- ...Object.values(TradeHistoryUIDirection)
766
- ]);
767
- var OrderHistoryOrderTypeSchema = import_zod11.z.enum([
768
- OrderHistoryOrderType.MARKET,
769
- ...Object.values(OrderHistoryOrderType)
770
- ]);
771
- var OrderHistoryStatusSchema = import_zod11.z.enum([OrderHistoryStatus.OPEN, ...Object.values(OrderHistoryStatus)]);
772
- var OrderHistoryUIDirectionSchema = import_zod11.z.enum([
773
- OrderHistoryUIDirection.BUY,
774
- ...Object.values(OrderHistoryUIDirection)
775
- ]);
776
- var StakingPositionHistoryActionTypeSchema = import_zod11.z.enum([
777
- StakingPositionHistoryActionType.STAKE,
778
- ...Object.values(StakingPositionHistoryActionType)
779
- ]);
780
- var PoolSubscriptionTopicSchema = import_zod11.z.enum([
781
- PoolSubscriptionTopic.ORDER_BOOK,
782
- ...Object.values(PoolSubscriptionTopic)
783
- ]);
784
- var WalletSubscriptionTopicSchema = import_zod11.z.enum([
785
- WalletSubscriptionTopic.TUNA_POSITIONS,
786
- ...Object.values(WalletSubscriptionTopic)
787
- ]);
788
- var PaginationMeta = import_zod11.z.object({
789
- total: import_zod11.z.number()
790
- });
791
- var TokenOraclePrice = import_zod11.z.object({
792
- mint: import_zod11.z.string(),
793
- price: import_zod11.z.coerce.bigint(),
794
- decimals: import_zod11.z.number(),
795
- time: import_zod11.z.coerce.date()
796
- });
797
- var Vault = import_zod11.z.object({
798
- address: import_zod11.z.string(),
799
- mint: import_zod11.z.string(),
800
- depositedFunds: AmountWithUsdSchema,
801
- borrowedFunds: AmountWithUsdSchema,
802
- supplyLimit: AmountWithUsdSchema,
803
- borrowedShares: import_zod11.z.coerce.bigint(),
804
- depositedShares: import_zod11.z.coerce.bigint(),
805
- supplyApy: import_zod11.z.number(),
806
- borrowApy: import_zod11.z.number(),
807
- interestRate: import_zod11.z.coerce.bigint(),
808
- utilization: import_zod11.z.number(),
809
- pythOracleFeedId: import_zod11.z.string(),
810
- pythOraclePriceUpdate: import_zod11.z.string()
811
- });
812
- var VaultHistoricalStats = import_zod11.z.object({
813
- date: import_zod11.z.preprocess((val, ctx) => {
814
- if (typeof val === "string") {
815
- const [year, month, day] = val.split("-").map(Number);
816
- return new Date(year, month - 1, day);
817
- }
818
- ctx.addIssue({
819
- code: "custom",
820
- message: "Not a valid date string"
821
- });
822
- return import_zod11.z.NEVER;
823
- }, import_zod11.z.date()),
824
- supply: AmountWithUsdSchema,
825
- borrow: AmountWithUsdSchema,
826
- supplyApy: import_zod11.z.number(),
827
- borrowApr: import_zod11.z.number()
828
- });
829
- var Tick = import_zod11.z.object({
830
- index: import_zod11.z.number(),
831
- liquidity: import_zod11.z.coerce.bigint()
832
- });
833
- var PoolTicks = import_zod11.z.object({
834
- tickSpacing: import_zod11.z.number(),
835
- ticks: Tick.array()
836
- });
837
- var LendingPosition = import_zod11.z.object({
838
- address: import_zod11.z.string(),
839
- authority: import_zod11.z.string(),
840
- mint: import_zod11.z.string(),
841
- vault: import_zod11.z.string(),
842
- shares: import_zod11.z.coerce.bigint(),
843
- funds: AmountWithUsdSchema,
844
- earned: AmountWithUsdSchema
845
- });
846
- var PoolSwap = import_zod11.z.object({
847
- id: import_zod11.z.string(),
848
- amountIn: import_zod11.z.coerce.bigint(),
849
- amountOut: import_zod11.z.coerce.bigint(),
850
- amountUsd: import_zod11.z.number(),
851
- aToB: import_zod11.z.boolean(),
852
- pool: import_zod11.z.string(),
853
- time: import_zod11.z.coerce.date()
854
- });
855
- var TradeHistoryEntry = import_zod11.z.object({
856
- // Internal entry ID
857
- id: import_zod11.z.string(),
858
- pool: Pool,
859
- authority: import_zod11.z.string(),
860
- aToB: import_zod11.z.boolean(),
861
- // Trade action which created entry
862
- action: TradeHistoryActionSchema,
863
- // Trade direction formatted for ui display
864
- uiDirection: TradeHistoryUIDirectionSchema,
865
- // Trade price formatted for ui display
866
- uiPrice: import_zod11.z.number(),
867
- baseToken: AmountWithUsdSchema,
868
- quoteToken: AmountWithUsdSchema,
869
- fee: AmountWithUsdSchema,
870
- pnl: import_zod11.z.nullable(
871
- import_zod11.z.object({
872
- usd: import_zod11.z.number(),
873
- bps: import_zod11.z.number()
874
- })
875
- ),
876
- txSignature: import_zod11.z.nullable(import_zod11.z.string()),
877
- positionAddress: import_zod11.z.nullable(import_zod11.z.string()),
878
- slot: import_zod11.z.coerce.bigint(),
879
- ts: import_zod11.z.coerce.date()
880
- });
881
- var OrderHistoryEntry = import_zod11.z.object({
882
- // Internal entry ID
883
- id: import_zod11.z.string(),
884
- pool: Pool,
885
- authority: import_zod11.z.string(),
886
- orderType: OrderHistoryOrderTypeSchema,
887
- isReduceOnly: import_zod11.z.nullable(import_zod11.z.boolean()),
888
- aToB: import_zod11.z.boolean(),
889
- uiDirection: OrderHistoryUIDirectionSchema,
890
- uiPrice: import_zod11.z.nullable(import_zod11.z.number()),
891
- uiExecutionPrice: import_zod11.z.nullable(import_zod11.z.number()),
892
- status: OrderHistoryStatusSchema,
893
- baseToken: AmountWithUsdSchema,
894
- quoteToken: AmountWithUsdSchema,
895
- baseTokenConsumedAmount: import_zod11.z.nullable(AmountWithUsdSchema),
896
- quoteTokenFilledAmount: import_zod11.z.nullable(AmountWithUsdSchema),
897
- txSignature: import_zod11.z.nullable(import_zod11.z.string()),
898
- positionAddress: import_zod11.z.nullable(import_zod11.z.string()),
899
- slot: import_zod11.z.coerce.bigint(),
900
- ts: import_zod11.z.coerce.date()
901
- });
902
- var StakingTreasury = import_zod11.z.object({
903
- address: import_zod11.z.string(),
904
- stakedTokenMint: import_zod11.z.string(),
905
- rewardTokenMint: import_zod11.z.string(),
906
- apy: import_zod11.z.number(),
907
- uniqueStakers: import_zod11.z.number(),
908
- totalStaked: AmountWithUsdSchema,
909
- totalReward: AmountWithUsdSchema,
910
- unstakeCooldownSeconds: import_zod11.z.number(),
911
- isStakingEnabled: import_zod11.z.boolean(),
912
- isUnstakingEnabled: import_zod11.z.boolean(),
913
- isWithdrawEnabled: import_zod11.z.boolean()
914
- });
915
- var StakingPosition = import_zod11.z.object({
916
- address: import_zod11.z.string(),
917
- owner: import_zod11.z.string(),
918
- staked: AmountWithUsdSchema,
919
- unstaked: AmountWithUsdSchema,
920
- claimedReward: AmountWithUsdSchema,
921
- unclaimedReward: AmountWithUsdSchema,
922
- rank: import_zod11.z.nullable(import_zod11.z.number()),
923
- vesting: import_zod11.z.object({
924
- locked: AmountWithUsdSchema,
925
- unlocked: AmountWithUsdSchema,
926
- unlockRate: import_zod11.z.coerce.bigint(),
927
- unlockEverySeconds: import_zod11.z.number(),
928
- unlockCliffSeconds: import_zod11.z.number(),
929
- lockedAt: import_zod11.z.nullable(import_zod11.z.coerce.date())
930
- }),
931
- lastUnstakedAt: import_zod11.z.nullable(import_zod11.z.coerce.date()),
932
- withdrawAvailableAt: import_zod11.z.nullable(import_zod11.z.coerce.date())
933
- });
934
- var StakingLeaderboardPosition = import_zod11.z.object({
935
- rank: import_zod11.z.number(),
936
- address: import_zod11.z.string(),
937
- owner: import_zod11.z.string(),
938
- staked: AmountWithUsdSchema
939
- });
940
- var StakingLeaderboardPage = import_zod11.z.object({
941
- data: StakingLeaderboardPosition.array(),
942
- meta: PaginationMeta
943
- });
944
- var StakingPositionHistoryAction = import_zod11.z.object({
945
- position: import_zod11.z.string(),
946
- action: StakingPositionHistoryActionTypeSchema,
947
- txSignature: import_zod11.z.string(),
948
- amount: import_zod11.z.coerce.bigint(),
949
- time: import_zod11.z.coerce.date()
950
- });
951
- var PoolPriceCandle = import_zod11.z.object({
952
- time: import_zod11.z.number(),
953
- open: import_zod11.z.number(),
954
- close: import_zod11.z.number(),
955
- high: import_zod11.z.number(),
956
- low: import_zod11.z.number(),
957
- volume: import_zod11.z.number()
958
- });
959
- var FeesStatsGroup = import_zod11.z.object({
960
- time: import_zod11.z.coerce.date(),
961
- addLiquidityFees: import_zod11.z.number(),
962
- limitOrderFees: import_zod11.z.number(),
963
- yieldCompoundingFees: import_zod11.z.number(),
964
- liquidationFees: import_zod11.z.number(),
965
- totalLiquidationsNetworkFees: import_zod11.z.number(),
966
- totalLimitOrdersNetworkFees: import_zod11.z.number(),
967
- totalYieldCompoundingNetworkFees: import_zod11.z.number(),
968
- failedNetworkFees: import_zod11.z.number(),
969
- processedNetworkFees: import_zod11.z.number(),
970
- totalCollectedFees: import_zod11.z.number(),
971
- totalNetworkFees: import_zod11.z.number(),
972
- jitoLiquidationFees: import_zod11.z.number(),
973
- jitoLimitOrderFees: import_zod11.z.number(),
974
- jitoYieldCompoundingFees: import_zod11.z.number(),
975
- runningAddLiquidityFees: import_zod11.z.number(),
976
- runningLimitOrderFees: import_zod11.z.number(),
977
- runningYieldCompoundingFees: import_zod11.z.number(),
978
- runningLiquidationFees: import_zod11.z.number(),
979
- runningTotalLiquidationsNetworkFees: import_zod11.z.number(),
980
- runningTotalLimitOrdersNetworkFees: import_zod11.z.number(),
981
- runningTotalYieldCompoundingNetworkFees: import_zod11.z.number(),
982
- runningFailedNetworkFees: import_zod11.z.number(),
983
- runningProcessedNetworkFees: import_zod11.z.number(),
984
- runningJitoLiquidationFees: import_zod11.z.number(),
985
- runningJitoLimitOrderFees: import_zod11.z.number(),
986
- runningJitoYieldCompoundingFees: import_zod11.z.number(),
987
- runningTotalCollectedFees: import_zod11.z.number(),
988
- runningTotalNetworkFees: import_zod11.z.number()
989
- });
990
- var StakingRevenueStatsGroup = import_zod11.z.object({
991
- time: import_zod11.z.coerce.date(),
992
- totalDepositsUsd: import_zod11.z.number(),
993
- totalDepositsSol: import_zod11.z.coerce.bigint(),
994
- runningTotalDepositsUsd: import_zod11.z.number(),
995
- runningTotalDepositsSol: import_zod11.z.coerce.bigint()
996
- });
997
- var SwapQuoteByInput = import_zod11.z.object({
998
- estimatedAmountOut: import_zod11.z.coerce.bigint(),
999
- minAmountOut: import_zod11.z.coerce.bigint(),
1000
- feeAmount: import_zod11.z.coerce.bigint(),
1001
- feeUsd: import_zod11.z.number(),
1002
- /** Price impact in percents */
1003
- priceImpact: import_zod11.z.number()
1004
- });
1005
- var SwapQuoteByOutput = import_zod11.z.object({
1006
- estimatedAmountIn: import_zod11.z.coerce.bigint(),
1007
- maxAmountIn: import_zod11.z.coerce.bigint(),
1008
- feeAmount: import_zod11.z.coerce.bigint(),
1009
- feeUsd: import_zod11.z.number(),
1010
- /** Price impact in percents */
1011
- priceImpact: import_zod11.z.number()
1012
- });
1013
- var LimitOrderQuoteByInput = import_zod11.z.object({
1014
- amountOut: import_zod11.z.coerce.bigint()
1015
- });
1016
- var LimitOrderQuoteByOutput = import_zod11.z.object({
1017
- amountIn: import_zod11.z.coerce.bigint()
1018
- });
1019
- var TradableAmount = AmountWithUsdSchema;
1020
- var UpdateStreamSubscriptionResult = import_zod11.z.object({
1021
- status: import_zod11.z.string()
1022
- });
1023
- var createNotificationSchema = (dataSchema, metaSchema) => import_zod11.z.object({
1024
- entity: NotificationEntitySchema,
1025
- action: NotificationActionSchema,
1026
- data: dataSchema,
1027
- id: import_zod11.z.string(),
1028
- authority: import_zod11.z.nullish(import_zod11.z.string()),
1029
- ...metaSchema ? { meta: metaSchema } : { meta: import_zod11.z.undefined().nullable() }
1030
- });
1031
- var PoolSwapNotification = createNotificationSchema(PoolSwap);
1032
- var LendingPositionNotification = createNotificationSchema(LendingPosition);
1033
- var TradeHistoryEntryNotification = createNotificationSchema(TradeHistoryEntry);
1034
- var OrderHistoryEntryNotification = createNotificationSchema(OrderHistoryEntry);
1035
- var StakingPositionNotification = createNotificationSchema(StakingPosition);
1036
- var StateSnapshotNotification = createNotificationSchema(StateSnapshot);
1037
-
1038
- // src/client/client.ts
1039
- var DEFAULT_TIMEOUT = 5e3;
1040
- var DEFAULT_HTTP_RETRIES = 3;
1041
- var ProviderFilter = /* @__PURE__ */ ((ProviderFilter2) => {
1042
- ProviderFilter2["ORCA"] = "orca";
1043
- ProviderFilter2["FUSION"] = "fusion";
1044
- ProviderFilter2["ALL"] = "all";
1045
- return ProviderFilter2;
1046
- })(ProviderFilter || {});
1047
- var TunaApiClient = class {
1048
- get baseURL() {
1049
- return this._baseURL;
1050
- }
1051
- get timeout() {
1052
- return this._timeout;
1053
- }
1054
- get httpRetries() {
1055
- return this._httpRetries;
1056
- }
1057
- get headers() {
1058
- return this._headers;
1059
- }
1060
- constructor(baseURL, config) {
1061
- this._baseURL = baseURL;
1062
- this._timeout = config?.timeout ?? DEFAULT_TIMEOUT;
1063
- this._httpRetries = config?.httpRetries ?? DEFAULT_HTTP_RETRIES;
1064
- this._headers = config?.headers ?? {};
1065
- }
1066
- setConfig(config) {
1067
- if (config.baseURL) {
1068
- this._baseURL = config.baseURL;
241
+ tunaPositions: "tuna_positions",
242
+ tunaSpotPositions: "tuna_spot_positions",
243
+ lendingPositions: "lending_positions",
244
+ fusionLimitOrders: "fusion_limit_orders",
245
+ stakingPosition: "staking_position",
246
+ tradeHistory: "trade_history",
247
+ orderHistory: "order_history"
248
+ };
249
+ var getGetLpSpotLeaderboardUrl = (params) => {
250
+ const normalizedParams = new URLSearchParams();
251
+ Object.entries(params || {}).forEach(([key, value]) => {
252
+ if (value !== void 0) {
253
+ normalizedParams.append(key, value === null ? "null" : value.toString());
1069
254
  }
1070
- this._timeout = config?.timeout ?? DEFAULT_TIMEOUT;
1071
- this._httpRetries = config?.httpRetries ?? DEFAULT_HTTP_RETRIES;
1072
- this._headers = config?.headers ?? {};
1073
- }
1074
- async httpRequest(url, schema, options, retries = this.httpRetries, backoff = 100 + Math.floor(Math.random() * 100)) {
1075
- try {
1076
- const controller = new AbortController();
1077
- const abort = setTimeout(() => {
1078
- controller.abort();
1079
- }, this.timeout);
1080
- const signal = options?.signal || controller.signal;
1081
- const response = await fetch(url, {
1082
- ...options,
1083
- signal,
1084
- headers: { "Content-Type": "application/json", ...this.headers, ...options?.headers }
255
+ });
256
+ const stringifiedParams = normalizedParams.toString();
257
+ return stringifiedParams.length > 0 ? `/v1/lp-spot-leaderboard?${stringifiedParams}` : `/v1/lp-spot-leaderboard`;
258
+ };
259
+ var getLpSpotLeaderboard = async (params, options) => {
260
+ return customFetch(
261
+ getGetLpSpotLeaderboardUrl(params),
262
+ {
263
+ ...options,
264
+ method: "GET"
265
+ }
266
+ );
267
+ };
268
+ var getGetMarketsUrl = () => {
269
+ return `/v1/markets`;
270
+ };
271
+ var getMarkets = async (options) => {
272
+ return customFetch(
273
+ getGetMarketsUrl(),
274
+ {
275
+ ...options,
276
+ method: "GET"
277
+ }
278
+ );
279
+ };
280
+ var getGetMarketUrl = (marketAddress) => {
281
+ return `/v1/markets/${marketAddress}`;
282
+ };
283
+ var getMarket = async (marketAddress, options) => {
284
+ return customFetch(
285
+ getGetMarketUrl(marketAddress),
286
+ {
287
+ ...options,
288
+ method: "GET"
289
+ }
290
+ );
291
+ };
292
+ var getGetMintsUrl = () => {
293
+ return `/v1/mints`;
294
+ };
295
+ var getMints = async (options) => {
296
+ return customFetch(
297
+ getGetMintsUrl(),
298
+ {
299
+ ...options,
300
+ method: "GET"
301
+ }
302
+ );
303
+ };
304
+ var getGetMintUrl = (mintAddress) => {
305
+ return `/v1/mints/${mintAddress}`;
306
+ };
307
+ var getMint = async (mintAddress, options) => {
308
+ return customFetch(
309
+ getGetMintUrl(mintAddress),
310
+ {
311
+ ...options,
312
+ method: "GET"
313
+ }
314
+ );
315
+ };
316
+ var getGetOraclePricesUrl = () => {
317
+ return `/v1/oracle-prices`;
318
+ };
319
+ var getOraclePrices = async (options) => {
320
+ return customFetch(
321
+ getGetOraclePricesUrl(),
322
+ {
323
+ ...options,
324
+ method: "GET"
325
+ }
326
+ );
327
+ };
328
+ var getGetOraclePriceUrl = (mintAddress) => {
329
+ return `/v1/oracle-prices/${mintAddress}`;
330
+ };
331
+ var getOraclePrice = async (mintAddress, options) => {
332
+ return customFetch(
333
+ getGetOraclePriceUrl(mintAddress),
334
+ {
335
+ ...options,
336
+ method: "GET"
337
+ }
338
+ );
339
+ };
340
+ var getGetPoolsUrl = (params) => {
341
+ const normalizedParams = new URLSearchParams();
342
+ Object.entries(params || {}).forEach(([key, value]) => {
343
+ if (value !== void 0) {
344
+ normalizedParams.append(key, value === null ? "null" : value.toString());
345
+ }
346
+ });
347
+ const stringifiedParams = normalizedParams.toString();
348
+ return stringifiedParams.length > 0 ? `/v1/pools?${stringifiedParams}` : `/v1/pools`;
349
+ };
350
+ var getPools = async (params, options) => {
351
+ return customFetch(
352
+ getGetPoolsUrl(params),
353
+ {
354
+ ...options,
355
+ method: "GET"
356
+ }
357
+ );
358
+ };
359
+ var getGetPoolUrl = (poolAddress) => {
360
+ return `/v1/pools/${poolAddress}`;
361
+ };
362
+ var getPool = async (poolAddress, options) => {
363
+ return customFetch(
364
+ getGetPoolUrl(poolAddress),
365
+ {
366
+ ...options,
367
+ method: "GET"
368
+ }
369
+ );
370
+ };
371
+ var getGetPoolCandlesUrl = (poolAddress, params) => {
372
+ const normalizedParams = new URLSearchParams();
373
+ Object.entries(params || {}).forEach(([key, value]) => {
374
+ if (value !== void 0) {
375
+ normalizedParams.append(key, value === null ? "null" : value instanceof Date ? value.toISOString() : value.toString());
376
+ }
377
+ });
378
+ const stringifiedParams = normalizedParams.toString();
379
+ return stringifiedParams.length > 0 ? `/v1/pools/${poolAddress}/candles?${stringifiedParams}` : `/v1/pools/${poolAddress}/candles`;
380
+ };
381
+ var getPoolCandles = async (poolAddress, params, options) => {
382
+ return customFetch(
383
+ getGetPoolCandlesUrl(poolAddress, params),
384
+ {
385
+ ...options,
386
+ method: "GET"
387
+ }
388
+ );
389
+ };
390
+ var getGetPoolOrderBookUrl = (poolAddress, params) => {
391
+ const normalizedParams = new URLSearchParams();
392
+ Object.entries(params || {}).forEach(([key, value]) => {
393
+ if (value !== void 0) {
394
+ normalizedParams.append(key, value === null ? "null" : value.toString());
395
+ }
396
+ });
397
+ const stringifiedParams = normalizedParams.toString();
398
+ return stringifiedParams.length > 0 ? `/v1/pools/${poolAddress}/order-book?${stringifiedParams}` : `/v1/pools/${poolAddress}/order-book`;
399
+ };
400
+ var getPoolOrderBook = async (poolAddress, params, options) => {
401
+ return customFetch(
402
+ getGetPoolOrderBookUrl(poolAddress, params),
403
+ {
404
+ ...options,
405
+ method: "GET"
406
+ }
407
+ );
408
+ };
409
+ var getGetPoolSwapsUrl = (poolAddress) => {
410
+ return `/v1/pools/${poolAddress}/swaps`;
411
+ };
412
+ var getPoolSwaps = async (poolAddress, options) => {
413
+ return customFetch(
414
+ getGetPoolSwapsUrl(poolAddress),
415
+ {
416
+ ...options,
417
+ method: "GET"
418
+ }
419
+ );
420
+ };
421
+ var getGetPoolTicksUrl = (poolAddress) => {
422
+ return `/v1/pools/${poolAddress}/ticks`;
423
+ };
424
+ var getPoolTicks = async (poolAddress, options) => {
425
+ return customFetch(
426
+ getGetPoolTicksUrl(poolAddress),
427
+ {
428
+ ...options,
429
+ method: "GET"
430
+ }
431
+ );
432
+ };
433
+ var getGetCloseSpotPositionQuoteUrl = (params) => {
434
+ const normalizedParams = new URLSearchParams();
435
+ Object.entries(params || {}).forEach(([key, value]) => {
436
+ if (value !== void 0) {
437
+ normalizedParams.append(key, value === null ? "null" : value.toString());
438
+ }
439
+ });
440
+ const stringifiedParams = normalizedParams.toString();
441
+ return stringifiedParams.length > 0 ? `/v1/quotes/close-spot-position?${stringifiedParams}` : `/v1/quotes/close-spot-position`;
442
+ };
443
+ var getCloseSpotPositionQuote = async (params, options) => {
444
+ return customFetch(
445
+ getGetCloseSpotPositionQuoteUrl(params),
446
+ {
447
+ ...options,
448
+ method: "GET"
449
+ }
450
+ );
451
+ };
452
+ var getGetDecreaseSpotPositionQuoteUrl = (params) => {
453
+ const normalizedParams = new URLSearchParams();
454
+ Object.entries(params || {}).forEach(([key, value]) => {
455
+ if (value !== void 0) {
456
+ normalizedParams.append(key, value === null ? "null" : value.toString());
457
+ }
458
+ });
459
+ const stringifiedParams = normalizedParams.toString();
460
+ return stringifiedParams.length > 0 ? `/v1/quotes/decrease-spot-position?${stringifiedParams}` : `/v1/quotes/decrease-spot-position`;
461
+ };
462
+ var getDecreaseSpotPositionQuote = async (params, options) => {
463
+ return customFetch(
464
+ getGetDecreaseSpotPositionQuoteUrl(params),
465
+ {
466
+ ...options,
467
+ method: "GET"
468
+ }
469
+ );
470
+ };
471
+ var getGetIncreaseSpotPositionQuoteUrl = (params) => {
472
+ const normalizedParams = new URLSearchParams();
473
+ Object.entries(params || {}).forEach(([key, value]) => {
474
+ if (value !== void 0) {
475
+ normalizedParams.append(key, value === null ? "null" : value.toString());
476
+ }
477
+ });
478
+ const stringifiedParams = normalizedParams.toString();
479
+ return stringifiedParams.length > 0 ? `/v1/quotes/increase-spot-position?${stringifiedParams}` : `/v1/quotes/increase-spot-position`;
480
+ };
481
+ var getIncreaseSpotPositionQuote = async (params, options) => {
482
+ return customFetch(
483
+ getGetIncreaseSpotPositionQuoteUrl(params),
484
+ {
485
+ ...options,
486
+ method: "GET"
487
+ }
488
+ );
489
+ };
490
+ var getGetLimitOrderQuoteByInputUrl = (params) => {
491
+ const normalizedParams = new URLSearchParams();
492
+ Object.entries(params || {}).forEach(([key, value]) => {
493
+ if (value !== void 0) {
494
+ normalizedParams.append(key, value === null ? "null" : value.toString());
495
+ }
496
+ });
497
+ const stringifiedParams = normalizedParams.toString();
498
+ return stringifiedParams.length > 0 ? `/v1/quotes/limit-order-by-input?${stringifiedParams}` : `/v1/quotes/limit-order-by-input`;
499
+ };
500
+ var getLimitOrderQuoteByInput = async (params, options) => {
501
+ return customFetch(
502
+ getGetLimitOrderQuoteByInputUrl(params),
503
+ {
504
+ ...options,
505
+ method: "GET"
506
+ }
507
+ );
508
+ };
509
+ var getGetLimitOrderQuoteByOutputUrl = (params) => {
510
+ const normalizedParams = new URLSearchParams();
511
+ Object.entries(params || {}).forEach(([key, value]) => {
512
+ if (value !== void 0) {
513
+ normalizedParams.append(key, value === null ? "null" : value.toString());
514
+ }
515
+ });
516
+ const stringifiedParams = normalizedParams.toString();
517
+ return stringifiedParams.length > 0 ? `/v1/quotes/limit-order-by-output?${stringifiedParams}` : `/v1/quotes/limit-order-by-output`;
518
+ };
519
+ var getLimitOrderQuoteByOutput = async (params, options) => {
520
+ return customFetch(
521
+ getGetLimitOrderQuoteByOutputUrl(params),
522
+ {
523
+ ...options,
524
+ method: "GET"
525
+ }
526
+ );
527
+ };
528
+ var getGetSwapQuoteByInputUrl = (params) => {
529
+ const normalizedParams = new URLSearchParams();
530
+ Object.entries(params || {}).forEach(([key, value]) => {
531
+ if (value !== void 0) {
532
+ normalizedParams.append(key, value === null ? "null" : value.toString());
533
+ }
534
+ });
535
+ const stringifiedParams = normalizedParams.toString();
536
+ return stringifiedParams.length > 0 ? `/v1/quotes/swap-by-input?${stringifiedParams}` : `/v1/quotes/swap-by-input`;
537
+ };
538
+ var getSwapQuoteByInput = async (params, options) => {
539
+ return customFetch(
540
+ getGetSwapQuoteByInputUrl(params),
541
+ {
542
+ ...options,
543
+ method: "GET"
544
+ }
545
+ );
546
+ };
547
+ var getGetSwapQuoteByOutputUrl = (params) => {
548
+ const normalizedParams = new URLSearchParams();
549
+ Object.entries(params || {}).forEach(([key, value]) => {
550
+ if (value !== void 0) {
551
+ normalizedParams.append(key, value === null ? "null" : value.toString());
552
+ }
553
+ });
554
+ const stringifiedParams = normalizedParams.toString();
555
+ return stringifiedParams.length > 0 ? `/v1/quotes/swap-by-output?${stringifiedParams}` : `/v1/quotes/swap-by-output`;
556
+ };
557
+ var getSwapQuoteByOutput = async (params, options) => {
558
+ return customFetch(
559
+ getGetSwapQuoteByOutputUrl(params),
560
+ {
561
+ ...options,
562
+ method: "GET"
563
+ }
564
+ );
565
+ };
566
+ var getGetTradableAmountUrl = (params) => {
567
+ const normalizedParams = new URLSearchParams();
568
+ Object.entries(params || {}).forEach(([key, value]) => {
569
+ if (value !== void 0) {
570
+ normalizedParams.append(key, value === null ? "null" : value.toString());
571
+ }
572
+ });
573
+ const stringifiedParams = normalizedParams.toString();
574
+ return stringifiedParams.length > 0 ? `/v1/quotes/tradable-amount?${stringifiedParams}` : `/v1/quotes/tradable-amount`;
575
+ };
576
+ var getTradableAmount = async (params, options) => {
577
+ return customFetch(
578
+ getGetTradableAmountUrl(params),
579
+ {
580
+ ...options,
581
+ method: "GET"
582
+ }
583
+ );
584
+ };
585
+ var getGetStakingLeaderboardUrl = (params) => {
586
+ const normalizedParams = new URLSearchParams();
587
+ Object.entries(params || {}).forEach(([key, value]) => {
588
+ if (value !== void 0) {
589
+ normalizedParams.append(key, value === null ? "null" : value.toString());
590
+ }
591
+ });
592
+ const stringifiedParams = normalizedParams.toString();
593
+ return stringifiedParams.length > 0 ? `/v1/staking/leaderboard?${stringifiedParams}` : `/v1/staking/leaderboard`;
594
+ };
595
+ var getStakingLeaderboard = async (params, options) => {
596
+ return customFetch(
597
+ getGetStakingLeaderboardUrl(params),
598
+ {
599
+ ...options,
600
+ method: "GET"
601
+ }
602
+ );
603
+ };
604
+ var getGetStakingTreasuryUrl = () => {
605
+ return `/v1/staking/treasury`;
606
+ };
607
+ var getStakingTreasury = async (options) => {
608
+ return customFetch(
609
+ getGetStakingTreasuryUrl(),
610
+ {
611
+ ...options,
612
+ method: "GET"
613
+ }
614
+ );
615
+ };
616
+ var getGetFeesStatsUrl = (params) => {
617
+ const normalizedParams = new URLSearchParams();
618
+ Object.entries(params || {}).forEach(([key, value]) => {
619
+ if (value !== void 0) {
620
+ normalizedParams.append(key, value === null ? "null" : value instanceof Date ? value.toISOString() : value.toString());
621
+ }
622
+ });
623
+ const stringifiedParams = normalizedParams.toString();
624
+ return stringifiedParams.length > 0 ? `/v1/stats/fees?${stringifiedParams}` : `/v1/stats/fees`;
625
+ };
626
+ var getFeesStats = async (params, options) => {
627
+ return customFetch(
628
+ getGetFeesStatsUrl(params),
629
+ {
630
+ ...options,
631
+ method: "GET"
632
+ }
633
+ );
634
+ };
635
+ var getGetFusionFeesStatsUrl = (params) => {
636
+ const normalizedParams = new URLSearchParams();
637
+ Object.entries(params || {}).forEach(([key, value]) => {
638
+ if (value !== void 0) {
639
+ normalizedParams.append(key, value === null ? "null" : value instanceof Date ? value.toISOString() : value.toString());
640
+ }
641
+ });
642
+ const stringifiedParams = normalizedParams.toString();
643
+ return stringifiedParams.length > 0 ? `/v1/stats/fusion-fees?${stringifiedParams}` : `/v1/stats/fusion-fees`;
644
+ };
645
+ var getFusionFeesStats = async (params, options) => {
646
+ return customFetch(
647
+ getGetFusionFeesStatsUrl(params),
648
+ {
649
+ ...options,
650
+ method: "GET"
651
+ }
652
+ );
653
+ };
654
+ var getGetPositionsStatsUrl = (params) => {
655
+ const normalizedParams = new URLSearchParams();
656
+ Object.entries(params || {}).forEach(([key, value]) => {
657
+ if (value !== void 0) {
658
+ normalizedParams.append(key, value === null ? "null" : value instanceof Date ? value.toISOString() : value.toString());
659
+ }
660
+ });
661
+ const stringifiedParams = normalizedParams.toString();
662
+ return stringifiedParams.length > 0 ? `/v1/stats/positions?${stringifiedParams}` : `/v1/stats/positions`;
663
+ };
664
+ var getPositionsStats = async (params, options) => {
665
+ return customFetch(
666
+ getGetPositionsStatsUrl(params),
667
+ {
668
+ ...options,
669
+ method: "GET"
670
+ }
671
+ );
672
+ };
673
+ var getGetPositionsTotalUrl = () => {
674
+ return `/v1/stats/positions/total`;
675
+ };
676
+ var getPositionsTotal = async (options) => {
677
+ return customFetch(
678
+ getGetPositionsTotalUrl(),
679
+ {
680
+ ...options,
681
+ method: "GET"
682
+ }
683
+ );
684
+ };
685
+ var getGetStakingRevenueStatsUrl = (params) => {
686
+ const normalizedParams = new URLSearchParams();
687
+ Object.entries(params || {}).forEach(([key, value]) => {
688
+ if (value !== void 0) {
689
+ normalizedParams.append(key, value === null ? "null" : value.toString());
690
+ }
691
+ });
692
+ const stringifiedParams = normalizedParams.toString();
693
+ return stringifiedParams.length > 0 ? `/v1/stats/staking/revenue?${stringifiedParams}` : `/v1/stats/staking/revenue`;
694
+ };
695
+ var getStakingRevenueStats = async (params, options) => {
696
+ return customFetch(
697
+ getGetStakingRevenueStatsUrl(params),
698
+ {
699
+ ...options,
700
+ method: "GET"
701
+ }
702
+ );
703
+ };
704
+ var getSseUrl = () => {
705
+ return `/v1/streams/sse`;
706
+ };
707
+ var sse = async (options) => {
708
+ return customFetch(
709
+ getSseUrl(),
710
+ {
711
+ ...options,
712
+ method: "GET"
713
+ }
714
+ );
715
+ };
716
+ var getUpdateStreamSubscriptionUrl = (streamId) => {
717
+ return `/v1/streams/${streamId}/subscription`;
718
+ };
719
+ var updateStreamSubscription = async (streamId, subscriptionOptions, options) => {
720
+ return customFetch(
721
+ getUpdateStreamSubscriptionUrl(streamId),
722
+ {
723
+ ...options,
724
+ method: "PUT",
725
+ headers: { "Content-Type": "application/json", ...options?.headers },
726
+ body: JSON.stringify(
727
+ subscriptionOptions
728
+ )
729
+ }
730
+ );
731
+ };
732
+ var getGetLendingPositionsUrl = (userAddress) => {
733
+ return `/v1/users/${userAddress}/lending-positions`;
734
+ };
735
+ var getLendingPositions = async (userAddress, options) => {
736
+ return customFetch(
737
+ getGetLendingPositionsUrl(userAddress),
738
+ {
739
+ ...options,
740
+ method: "GET"
741
+ }
742
+ );
743
+ };
744
+ var getGetLendingPositionUrl = (userAddress, lendingPositionAddress) => {
745
+ return `/v1/users/${userAddress}/lending-positions/${lendingPositionAddress}`;
746
+ };
747
+ var getLendingPosition = async (userAddress, lendingPositionAddress, options) => {
748
+ return customFetch(
749
+ getGetLendingPositionUrl(userAddress, lendingPositionAddress),
750
+ {
751
+ ...options,
752
+ method: "GET"
753
+ }
754
+ );
755
+ };
756
+ var getGetLimitOrdersUrl = (userAddress, params) => {
757
+ const normalizedParams = new URLSearchParams();
758
+ Object.entries(params || {}).forEach(([key, value]) => {
759
+ const explodeParameters = ["pool", "status"];
760
+ if (Array.isArray(value) && explodeParameters.includes(key)) {
761
+ value.forEach((v) => {
762
+ normalizedParams.append(key, v === null ? "null" : v.toString());
1085
763
  });
1086
- clearTimeout(abort);
1087
- if (!response.ok) {
1088
- const errorBody = await response.json();
1089
- throw errorBody;
1090
- }
1091
- const data = await response.json();
1092
- const transformed = (0, import_camelcase_keys.default)(data, { deep: true, exclude: ["24h", "7d", "30d"] });
1093
- if (options?.parseRoot) {
1094
- return schema.parse(transformed);
1095
- }
1096
- return schema.parse(transformed.data);
1097
- } catch (error) {
1098
- if (retries > 0 && !(error instanceof Error && error.name === "AbortError")) {
1099
- await new Promise((resolve) => setTimeout(resolve, backoff));
1100
- return this.httpRequest(url, schema, options, retries - 1, backoff * 2);
1101
- }
1102
- throw error;
764
+ return;
765
+ }
766
+ if (value !== void 0) {
767
+ normalizedParams.append(key, value === null ? "null" : value.toString());
768
+ }
769
+ });
770
+ const stringifiedParams = normalizedParams.toString();
771
+ return stringifiedParams.length > 0 ? `/v1/users/${userAddress}/limit-orders?${stringifiedParams}` : `/v1/users/${userAddress}/limit-orders`;
772
+ };
773
+ var getLimitOrders = async (userAddress, params, options) => {
774
+ return customFetch(
775
+ getGetLimitOrdersUrl(userAddress, params),
776
+ {
777
+ ...options,
778
+ method: "GET"
779
+ }
780
+ );
781
+ };
782
+ var getGetLimitOrderUrl = (userAddress, limitOrderAddress) => {
783
+ return `/v1/users/${userAddress}/limit-orders/${limitOrderAddress}`;
784
+ };
785
+ var getLimitOrder = async (userAddress, limitOrderAddress, options) => {
786
+ return customFetch(
787
+ getGetLimitOrderUrl(userAddress, limitOrderAddress),
788
+ {
789
+ ...options,
790
+ method: "GET"
791
+ }
792
+ );
793
+ };
794
+ var getGetLpPositionsUrl = (userAddress, params) => {
795
+ const normalizedParams = new URLSearchParams();
796
+ Object.entries(params || {}).forEach(([key, value]) => {
797
+ if (value !== void 0) {
798
+ normalizedParams.append(key, value === null ? "null" : value instanceof Date ? value.toISOString() : value.toString());
799
+ }
800
+ });
801
+ const stringifiedParams = normalizedParams.toString();
802
+ return stringifiedParams.length > 0 ? `/v1/users/${userAddress}/lp-positions?${stringifiedParams}` : `/v1/users/${userAddress}/lp-positions`;
803
+ };
804
+ var getLpPositions = async (userAddress, params, options) => {
805
+ return customFetch(
806
+ getGetLpPositionsUrl(userAddress, params),
807
+ {
808
+ ...options,
809
+ method: "GET"
810
+ }
811
+ );
812
+ };
813
+ var getGetLpPositionActionsUrl = (userAddress, positionAddress) => {
814
+ return `/v1/users/${userAddress}/lp-positions/${positionAddress}/actions`;
815
+ };
816
+ var getLpPositionActions = async (userAddress, positionAddress, options) => {
817
+ return customFetch(
818
+ getGetLpPositionActionsUrl(userAddress, positionAddress),
819
+ {
820
+ ...options,
821
+ method: "GET"
822
+ }
823
+ );
824
+ };
825
+ var getGetOrderHistoryUrl = (userAddress, params) => {
826
+ const normalizedParams = new URLSearchParams();
827
+ Object.entries(params || {}).forEach(([key, value]) => {
828
+ const explodeParameters = ["pool", "orderType", "uiDirection"];
829
+ if (Array.isArray(value) && explodeParameters.includes(key)) {
830
+ value.forEach((v) => {
831
+ normalizedParams.append(key, v === null ? "null" : v.toString());
832
+ });
833
+ return;
834
+ }
835
+ if (value !== void 0) {
836
+ normalizedParams.append(key, value === null ? "null" : value.toString());
837
+ }
838
+ });
839
+ const stringifiedParams = normalizedParams.toString();
840
+ return stringifiedParams.length > 0 ? `/v1/users/${userAddress}/order-history?${stringifiedParams}` : `/v1/users/${userAddress}/order-history`;
841
+ };
842
+ var getOrderHistory = async (userAddress, params, options) => {
843
+ return customFetch(
844
+ getGetOrderHistoryUrl(userAddress, params),
845
+ {
846
+ ...options,
847
+ method: "GET"
848
+ }
849
+ );
850
+ };
851
+ var getGetSpotPositionsUrl = (userAddress) => {
852
+ return `/v1/users/${userAddress}/spot-positions`;
853
+ };
854
+ var getSpotPositions = async (userAddress, options) => {
855
+ return customFetch(
856
+ getGetSpotPositionsUrl(userAddress),
857
+ {
858
+ ...options,
859
+ method: "GET"
860
+ }
861
+ );
862
+ };
863
+ var getGetSpotPositionUrl = (userAddress, spotPositionAddress) => {
864
+ return `/v1/users/${userAddress}/spot-positions/${spotPositionAddress}`;
865
+ };
866
+ var getSpotPosition = async (userAddress, spotPositionAddress, options) => {
867
+ return customFetch(
868
+ getGetSpotPositionUrl(userAddress, spotPositionAddress),
869
+ {
870
+ ...options,
871
+ method: "GET"
872
+ }
873
+ );
874
+ };
875
+ var getGetUserStakingPositionUrl = (userAddress) => {
876
+ return `/v1/users/${userAddress}/staking-position`;
877
+ };
878
+ var getUserStakingPosition = async (userAddress, options) => {
879
+ return customFetch(
880
+ getGetUserStakingPositionUrl(userAddress),
881
+ {
882
+ ...options,
883
+ method: "GET"
884
+ }
885
+ );
886
+ };
887
+ var getGetUserStakingPositionHistoryUrl = (userAddress) => {
888
+ return `/v1/users/${userAddress}/staking-position/history`;
889
+ };
890
+ var getUserStakingPositionHistory = async (userAddress, options) => {
891
+ return customFetch(
892
+ getGetUserStakingPositionHistoryUrl(userAddress),
893
+ {
894
+ ...options,
895
+ method: "GET"
896
+ }
897
+ );
898
+ };
899
+ var getGetTradeHistoryUrl = (userAddress, params) => {
900
+ const normalizedParams = new URLSearchParams();
901
+ Object.entries(params || {}).forEach(([key, value]) => {
902
+ const explodeParameters = ["pool", "action", "uiDirection"];
903
+ if (Array.isArray(value) && explodeParameters.includes(key)) {
904
+ value.forEach((v) => {
905
+ normalizedParams.append(key, v === null ? "null" : v.toString());
906
+ });
907
+ return;
908
+ }
909
+ if (value !== void 0) {
910
+ normalizedParams.append(key, value === null ? "null" : value.toString());
911
+ }
912
+ });
913
+ const stringifiedParams = normalizedParams.toString();
914
+ return stringifiedParams.length > 0 ? `/v1/users/${userAddress}/trade-history?${stringifiedParams}` : `/v1/users/${userAddress}/trade-history`;
915
+ };
916
+ var getTradeHistory = async (userAddress, params, options) => {
917
+ return customFetch(
918
+ getGetTradeHistoryUrl(userAddress, params),
919
+ {
920
+ ...options,
921
+ method: "GET"
922
+ }
923
+ );
924
+ };
925
+ var getGetTunaPositionsUrl = (userAddress) => {
926
+ return `/v1/users/${userAddress}/tuna-positions`;
927
+ };
928
+ var getTunaPositions = async (userAddress, options) => {
929
+ return customFetch(
930
+ getGetTunaPositionsUrl(userAddress),
931
+ {
932
+ ...options,
933
+ method: "GET"
934
+ }
935
+ );
936
+ };
937
+ var getGetTunaPositionUrl = (userAddress, positionAddress) => {
938
+ return `/v1/users/${userAddress}/tuna-positions/${positionAddress}`;
939
+ };
940
+ var getTunaPosition = async (userAddress, positionAddress, options) => {
941
+ return customFetch(
942
+ getGetTunaPositionUrl(userAddress, positionAddress),
943
+ {
944
+ ...options,
945
+ method: "GET"
946
+ }
947
+ );
948
+ };
949
+ var getGetVaultsUrl = () => {
950
+ return `/v1/vaults`;
951
+ };
952
+ var getVaults = async (options) => {
953
+ return customFetch(
954
+ getGetVaultsUrl(),
955
+ {
956
+ ...options,
957
+ method: "GET"
958
+ }
959
+ );
960
+ };
961
+ var getGetVaultUrl = (vaultAddress) => {
962
+ return `/v1/vaults/${vaultAddress}`;
963
+ };
964
+ var getVault = async (vaultAddress, options) => {
965
+ return customFetch(
966
+ getGetVaultUrl(vaultAddress),
967
+ {
968
+ ...options,
969
+ method: "GET"
970
+ }
971
+ );
972
+ };
973
+ var getGetVaultHistoryUrl = (vaultAddress, params) => {
974
+ const normalizedParams = new URLSearchParams();
975
+ Object.entries(params || {}).forEach(([key, value]) => {
976
+ if (value !== void 0) {
977
+ normalizedParams.append(key, value === null ? "null" : value.toString());
1103
978
  }
979
+ });
980
+ const stringifiedParams = normalizedParams.toString();
981
+ return stringifiedParams.length > 0 ? `/v1/vaults/${vaultAddress}/history?${stringifiedParams}` : `/v1/vaults/${vaultAddress}/history`;
982
+ };
983
+ var getVaultHistory = async (vaultAddress, params, options) => {
984
+ return customFetch(
985
+ getGetVaultHistoryUrl(vaultAddress, params),
986
+ {
987
+ ...options,
988
+ method: "GET"
989
+ }
990
+ );
991
+ };
992
+
993
+ // src/unwrap.ts
994
+ function unwrapData(data) {
995
+ if (data && typeof data === "object" && "data" in data && Object.keys(data).length === 1) {
996
+ return data.data;
1104
997
  }
1105
- /* Endpoints */
1106
- async getMints() {
1107
- const url = this.buildURL("mints");
1108
- return await this.httpRequest(url, Mint.array());
998
+ return data;
999
+ }
1000
+ async function unwrap(promise) {
1001
+ const res = await promise;
1002
+ if (res.status != 200) {
1003
+ throw {
1004
+ status: res.status
1005
+ };
1109
1006
  }
1110
- async getMint(mintAddress) {
1111
- const url = this.buildURL(`mints/${mintAddress}`);
1112
- return await this.httpRequest(url, Mint);
1007
+ return unwrapData(res.data);
1008
+ }
1009
+
1010
+ // ../../node_modules/.pnpm/eventsource-parser@3.0.2/node_modules/eventsource-parser/dist/index.js
1011
+ var ParseError = class extends Error {
1012
+ constructor(message, options) {
1013
+ super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
1113
1014
  }
1114
- async getMarkets() {
1115
- const url = this.buildURL("markets");
1116
- return await this.httpRequest(url, Market.array());
1015
+ };
1016
+ function noop(_arg) {
1017
+ }
1018
+ function createParser(callbacks) {
1019
+ if (typeof callbacks == "function")
1020
+ throw new TypeError(
1021
+ "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
1022
+ );
1023
+ const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
1024
+ let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
1025
+ function feed(newChunk) {
1026
+ const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
1027
+ for (const line of complete)
1028
+ parseLine(line);
1029
+ incompleteLine = incomplete, isFirstChunk = false;
1117
1030
  }
1118
- async getMarket(marketAddress) {
1119
- const url = this.buildURL(`markets/${marketAddress}`);
1120
- return await this.httpRequest(url, Market);
1031
+ function parseLine(line) {
1032
+ if (line === "") {
1033
+ dispatchEvent();
1034
+ return;
1035
+ }
1036
+ if (line.startsWith(":")) {
1037
+ onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
1038
+ return;
1039
+ }
1040
+ const fieldSeparatorIndex = line.indexOf(":");
1041
+ if (fieldSeparatorIndex !== -1) {
1042
+ const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
1043
+ processField(field, value, line);
1044
+ return;
1045
+ }
1046
+ processField(line, "", line);
1121
1047
  }
1122
- async getOraclePrices() {
1123
- const url = this.buildURL("oracle-prices");
1124
- return await this.httpRequest(url, TokenOraclePrice.array());
1048
+ function processField(field, value, line) {
1049
+ switch (field) {
1050
+ case "event":
1051
+ eventType = value;
1052
+ break;
1053
+ case "data":
1054
+ data = `${data}${value}
1055
+ `;
1056
+ break;
1057
+ case "id":
1058
+ id = value.includes("\0") ? void 0 : value;
1059
+ break;
1060
+ case "retry":
1061
+ /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
1062
+ new ParseError(`Invalid \`retry\` value: "${value}"`, {
1063
+ type: "invalid-retry",
1064
+ value,
1065
+ line
1066
+ })
1067
+ );
1068
+ break;
1069
+ default:
1070
+ onError(
1071
+ new ParseError(
1072
+ `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
1073
+ { type: "unknown-field", field, value, line }
1074
+ )
1075
+ );
1076
+ break;
1077
+ }
1125
1078
  }
1126
- async getOraclePrice(mintAddress) {
1127
- const url = this.buildURL(`oracle-prices/${mintAddress}`);
1128
- return await this.httpRequest(url, TokenOraclePrice);
1079
+ function dispatchEvent() {
1080
+ data.length > 0 && onEvent({
1081
+ id,
1082
+ event: eventType || void 0,
1083
+ // If the data buffer's last character is a U+000A LINE FEED (LF) character,
1084
+ // then remove the last character from the data buffer.
1085
+ data: data.endsWith(`
1086
+ `) ? data.slice(0, -1) : data
1087
+ }), id = void 0, data = "", eventType = "";
1129
1088
  }
1130
- async getVaults() {
1131
- const url = this.buildURL("vaults");
1132
- return await this.httpRequest(url, Vault.array());
1089
+ function reset(options = {}) {
1090
+ incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = "";
1133
1091
  }
1134
- async getVault(vaultAddress) {
1135
- const url = this.buildURL(`vaults/${vaultAddress}`);
1136
- return await this.httpRequest(url, Vault);
1092
+ return { feed, reset };
1093
+ }
1094
+ function splitLines(chunk) {
1095
+ const lines = [];
1096
+ let incompleteLine = "", searchIndex = 0;
1097
+ for (; searchIndex < chunk.length; ) {
1098
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
1099
+ `, searchIndex);
1100
+ let lineEnd = -1;
1101
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
1102
+ incompleteLine = chunk.slice(searchIndex);
1103
+ break;
1104
+ } else {
1105
+ const line = chunk.slice(searchIndex, lineEnd);
1106
+ lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
1107
+ ` && searchIndex++;
1108
+ }
1137
1109
  }
1110
+ return [lines, incompleteLine];
1111
+ }
1112
+
1113
+ // ../../node_modules/.pnpm/eventsource@3.0.7/node_modules/eventsource/dist/index.js
1114
+ var ErrorEvent = class extends Event {
1138
1115
  /**
1139
- * Returns vault historical data for selected time interval.
1116
+ * Constructs a new `ErrorEvent` instance. This is typically not called directly,
1117
+ * but rather emitted by the `EventSource` object when an error occurs.
1140
1118
  *
1141
- * Example usage: getVaultHistory('H3ifgix98vzi3yCPbmZDLTheeTRf2jykXx8FpY5L7Sfd', '2025-03-10', '2025-04-10')
1119
+ * @param type - The type of the event (should be "error")
1120
+ * @param errorEventInitDict - Optional properties to include in the error event
1142
1121
  */
1143
- async getVaultHistory(vaultAddress, from, to) {
1144
- const url = this.appendUrlSearchParams(this.buildURL(`vaults/${vaultAddress}/history`), {
1145
- from: from.toISOString().slice(0, 10),
1146
- to: to.toISOString().slice(0, 10)
1147
- });
1148
- return await this.httpRequest(url, VaultHistoricalStats.array());
1149
- }
1150
- async getPools(providerFilter) {
1151
- const url = this.appendUrlSearchParams(this.buildURL("pools"), {
1152
- provider: providerFilter && providerFilter !== "all" /* ALL */ ? providerFilter : void 0
1153
- });
1154
- return await this.httpRequest(url, Pool.array());
1155
- }
1156
- async getPool(address) {
1157
- const url = this.buildURL(`pools/${address}`);
1158
- return await this.httpRequest(url, Pool);
1159
- }
1160
- async getPoolTicks(poolAddress) {
1161
- const url = this.buildURL(`pools/${poolAddress}/ticks`);
1162
- return await this.httpRequest(url, PoolTicks);
1163
- }
1164
- async getPoolSwaps(poolAddress) {
1165
- const url = this.buildURL(`pools/${poolAddress}/swaps`);
1166
- return await this.httpRequest(url, PoolSwap.array());
1167
- }
1168
- async getPoolOrderBook(poolAddress, priceStep, inverted) {
1169
- const url = this.appendUrlSearchParams(this.buildURL(`pools/${poolAddress}/order-book`), {
1170
- price_step: priceStep,
1171
- inverted: inverted || void 0
1172
- });
1173
- return await this.httpRequest(url, OrderBook);
1122
+ constructor(type, errorEventInitDict) {
1123
+ var _a, _b;
1124
+ super(type), this.code = (_a = errorEventInitDict == null ? void 0 : errorEventInitDict.code) != null ? _a : void 0, this.message = (_b = errorEventInitDict == null ? void 0 : errorEventInitDict.message) != null ? _b : void 0;
1174
1125
  }
1175
- async getPoolPriceCandles(poolAddress, options) {
1176
- const { from, to, interval, candles } = options;
1177
- const url = this.appendUrlSearchParams(this.buildURL(`pools/${poolAddress}/candles`), {
1178
- from: from.toISOString(),
1179
- to: to.toISOString(),
1180
- candles,
1181
- interval
1182
- });
1183
- return await this.httpRequest(url, PoolPriceCandle.array());
1184
- }
1185
- async getStakingTreasury() {
1186
- const url = this.buildURL(`staking/treasury`);
1187
- return await this.httpRequest(url, StakingTreasury);
1188
- }
1189
- async getStakingLeaderboard(page, pageSize, search) {
1190
- const url = this.appendUrlSearchParams(this.buildURL(`staking/leaderboard`), {
1191
- page,
1192
- page_size: pageSize,
1193
- search: search || void 0
1194
- });
1195
- return await this.httpRequest(url, StakingLeaderboardPage, { parseRoot: true });
1196
- }
1197
- async getUserLendingPositions(userAddress) {
1198
- const url = this.buildURL(`users/${userAddress}/lending-positions`);
1199
- return await this.httpRequest(url, LendingPosition.array());
1200
- }
1201
- async getUserLendingPositionByAddress(userAddress, lendingPositionAddress) {
1202
- const url = this.buildURL(`users/${userAddress}/lending-positions/${lendingPositionAddress}`);
1203
- return await this.httpRequest(url, LendingPosition);
1204
- }
1205
- async getUserTunaPositions(userAddress) {
1206
- const url = this.buildURL(`users/${userAddress}/tuna-positions`);
1207
- return await this.httpRequest(url, TunaLpPositionDtoSchema.array());
1208
- }
1209
- async getUserTunaPositionByAddress(userAddress, tunaPositionAddress) {
1210
- const url = this.buildURL(`users/${userAddress}/tuna-positions/${tunaPositionAddress}`);
1211
- return await this.httpRequest(url, TunaLpPositionDtoSchema);
1212
- }
1213
- async getUserLpPositions(userAddress, options) {
1214
- const query = {};
1215
- if (options) {
1216
- if (options.filter) {
1217
- query.filter = options.filter;
1218
- }
1219
- if (options.afterPosition) {
1220
- query.after_position = options.afterPosition;
1221
- }
1222
- if (options.openedAt) {
1223
- if (options.openedAt.from) {
1224
- query.opened_at_min = options.openedAt.from.toISOString();
1225
- }
1226
- if (options.openedAt.to) {
1227
- query.opened_at_max = options.openedAt.to.toISOString();
1228
- }
1229
- }
1230
- if (options.closedAt) {
1231
- if (options.closedAt.from) {
1232
- query.closed_at_min = options.closedAt.from.toISOString();
1233
- }
1234
- if (options.closedAt.to) {
1235
- query.closed_at_max = options.closedAt.to.toISOString();
1236
- }
1237
- }
1238
- }
1239
- const url = this.appendUrlSearchParams(this.buildURL(`users/${userAddress}/lp-positions`), query);
1240
- return await this.httpRequest(url, TunaLpPositionHistorical.array());
1241
- }
1242
- async getUserLpPositionActions(userAddress, positionAddress) {
1243
- const url = this.buildURL(`users/${userAddress}/lp-positions/${positionAddress}/actions`);
1244
- return await this.httpRequest(url, TunaLpPositionAction.array());
1245
- }
1246
- async getUserTunaSpotPositions(userAddress) {
1247
- const url = this.buildURL(`users/${userAddress}/spot-positions`);
1248
- return await this.httpRequest(url, TunaSpotPosition.array());
1249
- }
1250
- async getUserTunaSpotPositionByAddress(userAddress, tunaSpotPositionAddress) {
1251
- const url = this.buildURL(`users/${userAddress}/spot-positions/${tunaSpotPositionAddress}`);
1252
- return await this.httpRequest(url, TunaSpotPosition);
1253
- }
1254
- async getUserLimitOrders(userAddress, options) {
1255
- const query = {};
1256
- if (options) {
1257
- if (options.pool?.length) {
1258
- query.pool = options.pool.join(",");
1259
- }
1260
- if (options.status?.length) {
1261
- query.status = options.status.join(",");
1262
- }
1263
- if (options.openedAt?.from) {
1264
- query.opened_at_from = options.openedAt.from.toISOString();
1265
- }
1266
- if (options.openedAt?.to) {
1267
- query.opened_at_from = options.openedAt.to.toISOString();
1268
- }
1269
- if (options.limit) {
1270
- query.limit = options.limit;
1271
- }
1272
- if (options.cursor) {
1273
- query.cursor = options.cursor;
1274
- }
1275
- if (options.desc !== void 0) {
1276
- query.desc = options.desc;
1277
- }
1278
- }
1279
- const url = this.appendUrlSearchParams(this.buildURL(`users/${userAddress}/limit-orders`), query);
1280
- return await this.httpRequest(url, LimitOrder.array());
1281
- }
1282
- async getUserLimitOrderByAddress(userAddress, limitOrderAddress) {
1283
- const url = this.buildURL(`users/${userAddress}/limit-orders/${limitOrderAddress}`);
1284
- return await this.httpRequest(url, LimitOrder);
1126
+ /**
1127
+ * Node.js "hides" the `message` and `code` properties of the `ErrorEvent` instance,
1128
+ * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
1129
+ * we explicitly include the properties in the `inspect` method.
1130
+ *
1131
+ * This is automatically called by Node.js when you `console.log` an instance of this class.
1132
+ *
1133
+ * @param _depth - The current depth
1134
+ * @param options - The options passed to `util.inspect`
1135
+ * @param inspect - The inspect function to use (prevents having to import it from `util`)
1136
+ * @returns A string representation of the error
1137
+ */
1138
+ [Symbol.for("nodejs.util.inspect.custom")](_depth, options, inspect) {
1139
+ return inspect(inspectableError(this), options);
1285
1140
  }
1286
- async getUserTradeHistory(userAddress, options) {
1287
- const query = {};
1288
- if (options) {
1289
- if (options.pool?.length) {
1290
- query.pool = options.pool.join(",");
1291
- }
1292
- if (options.action?.length) {
1293
- query.action = options.action.join(",");
1294
- }
1295
- if (options.uiDirection?.length) {
1296
- query.ui_direction = options.uiDirection.join(",");
1297
- }
1298
- if (options.limit) {
1299
- query.limit = options.limit;
1300
- }
1301
- if (options.cursor) {
1302
- query.cursor = options.cursor;
1303
- }
1304
- if (options.desc !== void 0) {
1305
- query.desc = options.desc;
1306
- }
1307
- }
1308
- const url = this.appendUrlSearchParams(this.buildURL(`users/${userAddress}/trade-history`), query);
1309
- return await this.httpRequest(url, TradeHistoryEntry.array());
1141
+ /**
1142
+ * Deno "hides" the `message` and `code` properties of the `ErrorEvent` instance,
1143
+ * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
1144
+ * we explicitly include the properties in the `inspect` method.
1145
+ *
1146
+ * This is automatically called by Deno when you `console.log` an instance of this class.
1147
+ *
1148
+ * @param inspect - The inspect function to use (prevents having to import it from `util`)
1149
+ * @param options - The options passed to `Deno.inspect`
1150
+ * @returns A string representation of the error
1151
+ */
1152
+ [Symbol.for("Deno.customInspect")](inspect, options) {
1153
+ return inspect(inspectableError(this), options);
1310
1154
  }
1311
- async getUserOrderHistory(userAddress, options) {
1312
- const query = {};
1313
- if (options) {
1314
- if (options.pool?.length) {
1315
- query.pool = options.pool.join(",");
1316
- }
1317
- if (options.orderType?.length) {
1318
- query.order_type = options.orderType.join(",");
1319
- }
1320
- if (options.uiDiretion?.length) {
1321
- query.ui_direction = options.uiDiretion.join(",");
1155
+ };
1156
+ function syntaxError(message) {
1157
+ const DomException = globalThis.DOMException;
1158
+ return typeof DomException == "function" ? new DomException(message, "SyntaxError") : new SyntaxError(message);
1159
+ }
1160
+ function flattenError(err) {
1161
+ return err instanceof Error ? "errors" in err && Array.isArray(err.errors) ? err.errors.map(flattenError).join(", ") : "cause" in err && err.cause instanceof Error ? `${err}: ${flattenError(err.cause)}` : err.message : `${err}`;
1162
+ }
1163
+ function inspectableError(err) {
1164
+ return {
1165
+ type: err.type,
1166
+ message: err.message,
1167
+ code: err.code,
1168
+ defaultPrevented: err.defaultPrevented,
1169
+ cancelable: err.cancelable,
1170
+ timeStamp: err.timeStamp
1171
+ };
1172
+ }
1173
+ var __typeError = (msg) => {
1174
+ throw TypeError(msg);
1175
+ };
1176
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
1177
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
1178
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
1179
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
1180
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
1181
+ var _readyState;
1182
+ var _url;
1183
+ var _redirectUrl;
1184
+ var _withCredentials;
1185
+ var _fetch;
1186
+ var _reconnectInterval;
1187
+ var _reconnectTimer;
1188
+ var _lastEventId;
1189
+ var _controller;
1190
+ var _parser;
1191
+ var _onError;
1192
+ var _onMessage;
1193
+ var _onOpen;
1194
+ var _EventSource_instances;
1195
+ var connect_fn;
1196
+ var _onFetchResponse;
1197
+ var _onFetchError;
1198
+ var getRequestOptions_fn;
1199
+ var _onEvent;
1200
+ var _onRetryChange;
1201
+ var failConnection_fn;
1202
+ var scheduleReconnect_fn;
1203
+ var _reconnect;
1204
+ var EventSource = class extends EventTarget {
1205
+ constructor(url, eventSourceInitDict) {
1206
+ var _a, _b;
1207
+ super(), __privateAdd(this, _EventSource_instances), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, __privateAdd(this, _readyState), __privateAdd(this, _url), __privateAdd(this, _redirectUrl), __privateAdd(this, _withCredentials), __privateAdd(this, _fetch), __privateAdd(this, _reconnectInterval), __privateAdd(this, _reconnectTimer), __privateAdd(this, _lastEventId, null), __privateAdd(this, _controller), __privateAdd(this, _parser), __privateAdd(this, _onError, null), __privateAdd(this, _onMessage, null), __privateAdd(this, _onOpen, null), __privateAdd(this, _onFetchResponse, async (response) => {
1208
+ var _a2;
1209
+ __privateGet(this, _parser).reset();
1210
+ const { body, redirected, status, headers } = response;
1211
+ if (status === 204) {
1212
+ __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Server sent HTTP 204, not reconnecting", 204), this.close();
1213
+ return;
1322
1214
  }
1323
- if (options.limit) {
1324
- query.limit = options.limit;
1215
+ if (redirected ? __privateSet(this, _redirectUrl, new URL(response.url)) : __privateSet(this, _redirectUrl, void 0), status !== 200) {
1216
+ __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, `Non-200 status code (${status})`, status);
1217
+ return;
1325
1218
  }
1326
- if (options.cursor) {
1327
- query.cursor = options.cursor;
1219
+ if (!(headers.get("content-type") || "").startsWith("text/event-stream")) {
1220
+ __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, 'Invalid content type, expected "text/event-stream"', status);
1221
+ return;
1328
1222
  }
1329
- if (options.desc !== void 0) {
1330
- query.desc = options.desc;
1223
+ if (__privateGet(this, _readyState) === this.CLOSED)
1224
+ return;
1225
+ __privateSet(this, _readyState, this.OPEN);
1226
+ const openEvent = new Event("open");
1227
+ if ((_a2 = __privateGet(this, _onOpen)) == null || _a2.call(this, openEvent), this.dispatchEvent(openEvent), typeof body != "object" || !body || !("getReader" in body)) {
1228
+ __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Invalid response body, expected a web ReadableStream", status), this.close();
1229
+ return;
1331
1230
  }
1332
- }
1333
- const url = this.appendUrlSearchParams(this.buildURL(`users/${userAddress}/order-history`), query);
1334
- return await this.httpRequest(url, OrderHistoryEntry.array());
1335
- }
1336
- async getUserStakingPosition(userAddress) {
1337
- const url = this.buildURL(`users/${userAddress}/staking-position`);
1338
- return await this.httpRequest(url, StakingPosition);
1339
- }
1340
- async getUserStakingPositionHistory(userAddress) {
1341
- const url = this.buildURL(`users/${userAddress}/staking-position/history`);
1342
- return await this.httpRequest(url, StakingPositionHistoryAction.array());
1343
- }
1344
- async getFeesStats(from, to, interval) {
1345
- const url = this.appendUrlSearchParams(this.buildURL(`stats/fees`), {
1346
- from: from.toISOString(),
1347
- to: to.toISOString(),
1348
- interval
1349
- });
1350
- return await this.httpRequest(url, FeesStatsGroup.array());
1351
- }
1352
- async getStakingRevenueStats(from, to) {
1353
- const url = this.appendUrlSearchParams(this.buildURL(`stats/staking/revenue`), {
1354
- from: from.toISOString().split("T")[0],
1355
- to: to.toISOString().split("T")[0]
1231
+ const decoder = new TextDecoder(), reader = body.getReader();
1232
+ let open = true;
1233
+ do {
1234
+ const { done, value } = await reader.read();
1235
+ value && __privateGet(this, _parser).feed(decoder.decode(value, { stream: !done })), done && (open = false, __privateGet(this, _parser).reset(), __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this));
1236
+ } while (open);
1237
+ }), __privateAdd(this, _onFetchError, (err) => {
1238
+ __privateSet(this, _controller, void 0), !(err.name === "AbortError" || err.type === "aborted") && __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this, flattenError(err));
1239
+ }), __privateAdd(this, _onEvent, (event) => {
1240
+ typeof event.id == "string" && __privateSet(this, _lastEventId, event.id);
1241
+ const messageEvent = new MessageEvent(event.event || "message", {
1242
+ data: event.data,
1243
+ origin: __privateGet(this, _redirectUrl) ? __privateGet(this, _redirectUrl).origin : __privateGet(this, _url).origin,
1244
+ lastEventId: event.id || ""
1245
+ });
1246
+ __privateGet(this, _onMessage) && (!event.event || event.event === "message") && __privateGet(this, _onMessage).call(this, messageEvent), this.dispatchEvent(messageEvent);
1247
+ }), __privateAdd(this, _onRetryChange, (value) => {
1248
+ __privateSet(this, _reconnectInterval, value);
1249
+ }), __privateAdd(this, _reconnect, () => {
1250
+ __privateSet(this, _reconnectTimer, void 0), __privateGet(this, _readyState) === this.CONNECTING && __privateMethod(this, _EventSource_instances, connect_fn).call(this);
1356
1251
  });
1357
- return await this.httpRequest(url, StakingRevenueStatsGroup.array());
1252
+ try {
1253
+ if (url instanceof URL)
1254
+ __privateSet(this, _url, url);
1255
+ else if (typeof url == "string")
1256
+ __privateSet(this, _url, new URL(url, getBaseURL()));
1257
+ else
1258
+ throw new Error("Invalid URL");
1259
+ } catch {
1260
+ throw syntaxError("An invalid or illegal string was specified");
1261
+ }
1262
+ __privateSet(this, _parser, createParser({
1263
+ onEvent: __privateGet(this, _onEvent),
1264
+ onRetry: __privateGet(this, _onRetryChange)
1265
+ })), __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _reconnectInterval, 3e3), __privateSet(this, _fetch, (_a = eventSourceInitDict == null ? void 0 : eventSourceInitDict.fetch) != null ? _a : globalThis.fetch), __privateSet(this, _withCredentials, (_b = eventSourceInitDict == null ? void 0 : eventSourceInitDict.withCredentials) != null ? _b : false), __privateMethod(this, _EventSource_instances, connect_fn).call(this);
1358
1266
  }
1359
- async getLimitOrderQuoteByInput(args, config) {
1360
- const { pool, amountIn, aToB, tickIndex } = args;
1361
- const query = {
1362
- pool,
1363
- amount_in: amountIn.toString(),
1364
- a_to_b: aToB,
1365
- tick_index: tickIndex
1366
- };
1367
- const url = this.appendUrlSearchParams(this.buildURL(`quotes/limit-order-by-input`), query);
1368
- return await this.httpRequest(url, LimitOrderQuoteByInput, {
1369
- signal: config?.abortSignal
1370
- });
1267
+ /**
1268
+ * Returns the state of this EventSource object's connection. It can have the values described below.
1269
+ *
1270
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)
1271
+ *
1272
+ * Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface,
1273
+ * defined in the TypeScript `dom` library.
1274
+ *
1275
+ * @public
1276
+ */
1277
+ get readyState() {
1278
+ return __privateGet(this, _readyState);
1371
1279
  }
1372
- async getLimitOrderQuoteByOutput(args, config) {
1373
- const { pool, amountOut, aToB, tickIndex } = args;
1374
- const query = {
1375
- pool,
1376
- amount_out: amountOut.toString(),
1377
- a_to_b: aToB,
1378
- tick_index: tickIndex
1379
- };
1380
- const url = this.appendUrlSearchParams(this.buildURL(`quotes/limit-order-by-output`), query);
1381
- return await this.httpRequest(url, LimitOrderQuoteByOutput, {
1382
- signal: config?.abortSignal
1383
- });
1280
+ /**
1281
+ * Returns the URL providing the event stream.
1282
+ *
1283
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)
1284
+ *
1285
+ * @public
1286
+ */
1287
+ get url() {
1288
+ return __privateGet(this, _url).href;
1384
1289
  }
1385
- async getSwapQuoteByInput(args, config) {
1386
- const { pool, amountIn, aToB, slippageToleranceBps } = args;
1387
- const query = {
1388
- pool,
1389
- amount_in: amountIn.toString(),
1390
- a_to_b: aToB
1391
- };
1392
- if (slippageToleranceBps) {
1393
- query.slippage_tolerance = slippageToleranceBps;
1394
- }
1395
- const url = this.appendUrlSearchParams(this.buildURL(`quotes/swap-by-input`), query);
1396
- return await this.httpRequest(url, SwapQuoteByInput, {
1397
- signal: config?.abortSignal
1398
- });
1290
+ /**
1291
+ * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise.
1292
+ *
1293
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)
1294
+ */
1295
+ get withCredentials() {
1296
+ return __privateGet(this, _withCredentials);
1399
1297
  }
1400
- async getSwapQuoteByOutput(args, config) {
1401
- const { pool, amountOut, aToB, slippageToleranceBps } = args;
1402
- const query = {
1403
- pool,
1404
- amount_out: amountOut.toString(),
1405
- a_to_b: aToB
1406
- };
1407
- if (slippageToleranceBps) {
1408
- query.slippage_tolerance = slippageToleranceBps;
1409
- }
1410
- const url = this.appendUrlSearchParams(this.buildURL(`quotes/swap-by-output`), query);
1411
- return await this.httpRequest(url, SwapQuoteByOutput, {
1412
- signal: config?.abortSignal
1413
- });
1298
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */
1299
+ get onerror() {
1300
+ return __privateGet(this, _onError);
1414
1301
  }
1415
- async getIncreaseSpotPositionQuote(args, config) {
1416
- const {
1417
- market,
1418
- increaseAmount,
1419
- collateralToken,
1420
- positionToken,
1421
- leverage,
1422
- positionAmount,
1423
- positionDebt,
1424
- slippageTolerance
1425
- } = args;
1426
- const query = {
1427
- market,
1428
- increase_amount: increaseAmount.toString(),
1429
- collateral_token: collateralToken,
1430
- position_token: positionToken,
1431
- leverage
1432
- };
1433
- if (slippageTolerance) {
1434
- query.slippage_tolerance = slippageTolerance;
1435
- }
1436
- if (positionAmount) {
1437
- query.position_amount = positionAmount.toString();
1438
- }
1439
- if (positionDebt) {
1440
- query.position_debt = positionDebt.toString();
1441
- }
1442
- const url = this.appendUrlSearchParams(this.buildURL(`quotes/increase-spot-position`), query);
1443
- return await this.httpRequest(url, IncreaseSpotPositionQuote, {
1444
- signal: config?.abortSignal
1445
- });
1302
+ set onerror(value) {
1303
+ __privateSet(this, _onError, value);
1446
1304
  }
1447
- async getDecreaseSpotPositionQuote(args, config) {
1448
- const {
1449
- market,
1450
- decreaseAmount,
1451
- collateralToken,
1452
- positionToken,
1453
- leverage,
1454
- positionAmount,
1455
- positionDebt,
1456
- slippageTolerance
1457
- } = args;
1458
- const query = {
1459
- market,
1460
- decrease_amount: decreaseAmount.toString(),
1461
- collateral_token: collateralToken,
1462
- position_token: positionToken,
1463
- leverage,
1464
- position_amount: positionAmount.toString(),
1465
- position_debt: positionDebt.toString()
1466
- };
1467
- if (slippageTolerance) {
1468
- query.slippage_tolerance = slippageTolerance;
1469
- }
1470
- const url = this.appendUrlSearchParams(this.buildURL(`quotes/decrease-spot-position`), query);
1471
- return await this.httpRequest(url, DecreaseSpotPositionQuote, {
1472
- signal: config?.abortSignal
1473
- });
1305
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */
1306
+ get onmessage() {
1307
+ return __privateGet(this, _onMessage);
1474
1308
  }
1475
- async getCloseSpotPositionQuote(args, config) {
1476
- const { market, decreasePercent, collateralToken, positionToken, positionAmount, positionDebt, slippageTolerance } = args;
1477
- const query = {
1478
- market,
1479
- decrease_percent: decreasePercent,
1480
- collateral_token: collateralToken,
1481
- position_token: positionToken,
1482
- position_amount: positionAmount.toString(),
1483
- position_debt: positionDebt.toString()
1484
- };
1485
- if (slippageTolerance) {
1486
- query.slippage_tolerance = slippageTolerance;
1487
- }
1488
- const url = this.appendUrlSearchParams(this.buildURL(`quotes/close-spot-position`), query);
1489
- return await this.httpRequest(url, CloseSpotPositionQuote, {
1490
- signal: config?.abortSignal
1491
- });
1309
+ set onmessage(value) {
1310
+ __privateSet(this, _onMessage, value);
1492
1311
  }
1493
- async getTradableAmount(args, config) {
1494
- const { market, collateralToken, positionToken, availableBalance, leverage, positionAmount, increase } = args;
1495
- const url = this.appendUrlSearchParams(this.buildURL(`quotes/tradable-amount`), {
1496
- market,
1497
- collateral_token: collateralToken,
1498
- position_token: positionToken,
1499
- available_balance: availableBalance.toString(),
1500
- leverage,
1501
- position_amount: positionAmount.toString(),
1502
- increase
1503
- });
1504
- return await this.httpRequest(url, TradableAmount, {
1505
- signal: config?.abortSignal
1506
- });
1312
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */
1313
+ get onopen() {
1314
+ return __privateGet(this, _onOpen);
1507
1315
  }
1508
- async getUpdatesStream() {
1509
- const url = this.buildURL(`streams/sse`);
1510
- return new EventSource(url);
1316
+ set onopen(value) {
1317
+ __privateSet(this, _onOpen, value);
1511
1318
  }
1512
- async updateStreamSubscription(streamId, subscription) {
1513
- const url = this.buildURL(`streams/${streamId}/subscription`);
1514
- const body = JSON.stringify((0, import_snakecase_keys.default)(subscription, { deep: true }));
1515
- return await this.httpRequest(url, UpdateStreamSubscriptionResult, { method: "PUT", body });
1319
+ addEventListener(type, listener, options) {
1320
+ const listen = listener;
1321
+ super.addEventListener(type, listen, options);
1516
1322
  }
1517
- /* Utility functions */
1518
- buildURL(endpoint) {
1519
- return `${this.baseURL}${this.baseURL.endsWith("/") ? "" : "/"}v1/${endpoint}`;
1323
+ removeEventListener(type, listener, options) {
1324
+ const listen = listener;
1325
+ super.removeEventListener(type, listen, options);
1520
1326
  }
1521
- appendUrlSearchParams(url, params) {
1522
- const urlSearchParams = new URLSearchParams();
1523
- Object.entries(params).forEach(([key, value]) => {
1524
- if (value !== void 0) {
1525
- urlSearchParams.append(key, String(value));
1526
- }
1527
- });
1528
- if (urlSearchParams.size > 0) {
1529
- return `${url}?${urlSearchParams.toString()}`;
1530
- }
1531
- return url;
1327
+ /**
1328
+ * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.
1329
+ *
1330
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)
1331
+ *
1332
+ * @public
1333
+ */
1334
+ close() {
1335
+ __privateGet(this, _reconnectTimer) && clearTimeout(__privateGet(this, _reconnectTimer)), __privateGet(this, _readyState) !== this.CLOSED && (__privateGet(this, _controller) && __privateGet(this, _controller).abort(), __privateSet(this, _readyState, this.CLOSED), __privateSet(this, _controller, void 0));
1532
1336
  }
1533
1337
  };
1534
- // Annotate the CommonJS export names for ESM import in node:
1535
- 0 && (module.exports = {
1338
+ _readyState = /* @__PURE__ */ new WeakMap(), _url = /* @__PURE__ */ new WeakMap(), _redirectUrl = /* @__PURE__ */ new WeakMap(), _withCredentials = /* @__PURE__ */ new WeakMap(), _fetch = /* @__PURE__ */ new WeakMap(), _reconnectInterval = /* @__PURE__ */ new WeakMap(), _reconnectTimer = /* @__PURE__ */ new WeakMap(), _lastEventId = /* @__PURE__ */ new WeakMap(), _controller = /* @__PURE__ */ new WeakMap(), _parser = /* @__PURE__ */ new WeakMap(), _onError = /* @__PURE__ */ new WeakMap(), _onMessage = /* @__PURE__ */ new WeakMap(), _onOpen = /* @__PURE__ */ new WeakMap(), _EventSource_instances = /* @__PURE__ */ new WeakSet(), /**
1339
+ * Connect to the given URL and start receiving events
1340
+ *
1341
+ * @internal
1342
+ */
1343
+ connect_fn = function() {
1344
+ __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _controller, new AbortController()), __privateGet(this, _fetch)(__privateGet(this, _url), __privateMethod(this, _EventSource_instances, getRequestOptions_fn).call(this)).then(__privateGet(this, _onFetchResponse)).catch(__privateGet(this, _onFetchError));
1345
+ }, _onFetchResponse = /* @__PURE__ */ new WeakMap(), _onFetchError = /* @__PURE__ */ new WeakMap(), /**
1346
+ * Get request options for the `fetch()` request
1347
+ *
1348
+ * @returns The request options
1349
+ * @internal
1350
+ */
1351
+ getRequestOptions_fn = function() {
1352
+ var _a;
1353
+ const init = {
1354
+ // [spec] Let `corsAttributeState` be `Anonymous`…
1355
+ // [spec] …will have their mode set to "cors"…
1356
+ mode: "cors",
1357
+ redirect: "follow",
1358
+ headers: { Accept: "text/event-stream", ...__privateGet(this, _lastEventId) ? { "Last-Event-ID": __privateGet(this, _lastEventId) } : void 0 },
1359
+ cache: "no-store",
1360
+ signal: (_a = __privateGet(this, _controller)) == null ? void 0 : _a.signal
1361
+ };
1362
+ return "window" in globalThis && (init.credentials = this.withCredentials ? "include" : "same-origin"), init;
1363
+ }, _onEvent = /* @__PURE__ */ new WeakMap(), _onRetryChange = /* @__PURE__ */ new WeakMap(), /**
1364
+ * Handles the process referred to in the EventSource specification as "failing a connection".
1365
+ *
1366
+ * @param error - The error causing the connection to fail
1367
+ * @param code - The HTTP status code, if available
1368
+ * @internal
1369
+ */
1370
+ failConnection_fn = function(message, code) {
1371
+ var _a;
1372
+ __privateGet(this, _readyState) !== this.CLOSED && __privateSet(this, _readyState, this.CLOSED);
1373
+ const errorEvent = new ErrorEvent("error", { code, message });
1374
+ (_a = __privateGet(this, _onError)) == null || _a.call(this, errorEvent), this.dispatchEvent(errorEvent);
1375
+ }, /**
1376
+ * Schedules a reconnection attempt against the EventSource endpoint.
1377
+ *
1378
+ * @param message - The error causing the connection to fail
1379
+ * @param code - The HTTP status code, if available
1380
+ * @internal
1381
+ */
1382
+ scheduleReconnect_fn = function(message, code) {
1383
+ var _a;
1384
+ if (__privateGet(this, _readyState) === this.CLOSED)
1385
+ return;
1386
+ __privateSet(this, _readyState, this.CONNECTING);
1387
+ const errorEvent = new ErrorEvent("error", { code, message });
1388
+ (_a = __privateGet(this, _onError)) == null || _a.call(this, errorEvent), this.dispatchEvent(errorEvent), __privateSet(this, _reconnectTimer, setTimeout(__privateGet(this, _reconnect), __privateGet(this, _reconnectInterval)));
1389
+ }, _reconnect = /* @__PURE__ */ new WeakMap(), /**
1390
+ * ReadyState representing an EventSource currently trying to connect
1391
+ *
1392
+ * @public
1393
+ */
1394
+ EventSource.CONNECTING = 0, /**
1395
+ * ReadyState representing an EventSource connection that is open (eg connected)
1396
+ *
1397
+ * @public
1398
+ */
1399
+ EventSource.OPEN = 1, /**
1400
+ * ReadyState representing an EventSource connection that is closed (eg disconnected)
1401
+ *
1402
+ * @public
1403
+ */
1404
+ EventSource.CLOSED = 2;
1405
+ function getBaseURL() {
1406
+ const doc = "document" in globalThis ? globalThis.document : void 0;
1407
+ return doc && typeof doc == "object" && "baseURI" in doc && typeof doc.baseURI == "string" ? doc.baseURI : void 0;
1408
+ }
1409
+
1410
+ // src/sse.ts
1411
+ var getSseUpdatesStream = async () => {
1412
+ const url = resolveTunaUrl(getSseUrl());
1413
+ return new EventSource(url);
1414
+ };
1415
+ function eventIsInitialMessage(event) {
1416
+ return !("entity" in event) || "entity" in event && event.entity === NotificationEntity.initialMessage;
1417
+ }
1418
+ function eventIsPoolSwap(event) {
1419
+ return "entity" in event && event.entity === NotificationEntity.poolSwap;
1420
+ }
1421
+ function eventIsStakingPosition(event) {
1422
+ return "entity" in event && event.entity === NotificationEntity.stakingPosition;
1423
+ }
1424
+ function eventIsLendingPosition(event) {
1425
+ return "entity" in event && event.entity === NotificationEntity.lendingPosition;
1426
+ }
1427
+ function eventIsTradeHistory(event) {
1428
+ return "entity" in event && event.entity === NotificationEntity.tradeHistoryEntry;
1429
+ }
1430
+ function eventIsOrderHistory(event) {
1431
+ return "entity" in event && event.entity === NotificationEntity.orderHistoryEntry;
1432
+ }
1433
+ function eventIsStateSnapshot(event) {
1434
+ return "entity" in event && event.entity === NotificationEntity.stateSnapshot;
1435
+ }
1436
+ export {
1437
+ LeaderboardPeriod,
1438
+ LeaderboardSortBy,
1439
+ LimitOrderStatus,
1440
+ LpPositionsHistoryQueryFilter,
1536
1441
  NotificationAction,
1537
1442
  NotificationEntity,
1443
+ OrderHistoryStatus,
1444
+ OrderHistoryType,
1445
+ OrderHistoryUIDirection,
1538
1446
  PoolProvider,
1539
1447
  PoolSubscriptionTopic,
1540
- ProviderFilter,
1541
- TunaApiClient,
1542
- TunaPositionState,
1448
+ StakingPositionActionType,
1449
+ TradeHistoryAction,
1450
+ TradeHistoryUIDirection,
1451
+ TunaLpPositionAutoCompound,
1452
+ TunaLpPositionAutoCompounding,
1453
+ TunaLpPositionLimitOrderSwap,
1454
+ TunaLpPositionRebalance,
1455
+ TunaLpPositionsActionType,
1456
+ TunaPositionDtoState,
1457
+ TunaPositionMarketMaker,
1458
+ TunaPositionPoolToken,
1459
+ TunaSpotPositionDtoState,
1543
1460
  WalletSubscriptionTopic,
1544
- schemas
1545
- });
1461
+ eventIsInitialMessage,
1462
+ eventIsLendingPosition,
1463
+ eventIsOrderHistory,
1464
+ eventIsPoolSwap,
1465
+ eventIsStakingPosition,
1466
+ eventIsStateSnapshot,
1467
+ eventIsTradeHistory,
1468
+ getCloseSpotPositionQuote,
1469
+ getDecreaseSpotPositionQuote,
1470
+ getFeesStats,
1471
+ getFusionFeesStats,
1472
+ getGetCloseSpotPositionQuoteUrl,
1473
+ getGetDecreaseSpotPositionQuoteUrl,
1474
+ getGetFeesStatsUrl,
1475
+ getGetFusionFeesStatsUrl,
1476
+ getGetIncreaseSpotPositionQuoteUrl,
1477
+ getGetLendingPositionUrl,
1478
+ getGetLendingPositionsUrl,
1479
+ getGetLimitOrderQuoteByInputUrl,
1480
+ getGetLimitOrderQuoteByOutputUrl,
1481
+ getGetLimitOrderUrl,
1482
+ getGetLimitOrdersUrl,
1483
+ getGetLpPositionActionsUrl,
1484
+ getGetLpPositionsUrl,
1485
+ getGetLpSpotLeaderboardUrl,
1486
+ getGetMarketUrl,
1487
+ getGetMarketsUrl,
1488
+ getGetMintUrl,
1489
+ getGetMintsUrl,
1490
+ getGetOraclePriceUrl,
1491
+ getGetOraclePricesUrl,
1492
+ getGetOrderHistoryUrl,
1493
+ getGetPoolCandlesUrl,
1494
+ getGetPoolOrderBookUrl,
1495
+ getGetPoolSwapsUrl,
1496
+ getGetPoolTicksUrl,
1497
+ getGetPoolUrl,
1498
+ getGetPoolsUrl,
1499
+ getGetPositionsStatsUrl,
1500
+ getGetPositionsTotalUrl,
1501
+ getGetSpotPositionUrl,
1502
+ getGetSpotPositionsUrl,
1503
+ getGetStakingLeaderboardUrl,
1504
+ getGetStakingRevenueStatsUrl,
1505
+ getGetStakingTreasuryUrl,
1506
+ getGetSwapQuoteByInputUrl,
1507
+ getGetSwapQuoteByOutputUrl,
1508
+ getGetTradableAmountUrl,
1509
+ getGetTradeHistoryUrl,
1510
+ getGetTunaPositionUrl,
1511
+ getGetTunaPositionsUrl,
1512
+ getGetUserStakingPositionHistoryUrl,
1513
+ getGetUserStakingPositionUrl,
1514
+ getGetVaultHistoryUrl,
1515
+ getGetVaultUrl,
1516
+ getGetVaultsUrl,
1517
+ getIncreaseSpotPositionQuote,
1518
+ getLendingPosition,
1519
+ getLendingPositions,
1520
+ getLimitOrder,
1521
+ getLimitOrderQuoteByInput,
1522
+ getLimitOrderQuoteByOutput,
1523
+ getLimitOrders,
1524
+ getLpPositionActions,
1525
+ getLpPositions,
1526
+ getLpSpotLeaderboard,
1527
+ getMarket,
1528
+ getMarkets,
1529
+ getMint,
1530
+ getMints,
1531
+ getOraclePrice,
1532
+ getOraclePrices,
1533
+ getOrderHistory,
1534
+ getPool,
1535
+ getPoolCandles,
1536
+ getPoolOrderBook,
1537
+ getPoolSwaps,
1538
+ getPoolTicks,
1539
+ getPools,
1540
+ getPositionsStats,
1541
+ getPositionsTotal,
1542
+ getSpotPosition,
1543
+ getSpotPositions,
1544
+ getSseUpdatesStream,
1545
+ getSseUrl,
1546
+ getStakingLeaderboard,
1547
+ getStakingRevenueStats,
1548
+ getStakingTreasury,
1549
+ getSwapQuoteByInput,
1550
+ getSwapQuoteByOutput,
1551
+ getTradableAmount,
1552
+ getTradeHistory,
1553
+ getTunaPosition,
1554
+ getTunaPositions,
1555
+ getUpdateStreamSubscriptionUrl,
1556
+ getUserStakingPosition,
1557
+ getUserStakingPositionHistory,
1558
+ getVault,
1559
+ getVaultHistory,
1560
+ getVaults,
1561
+ setTunaBaseUrl,
1562
+ sse,
1563
+ unwrap,
1564
+ updateStreamSubscription
1565
+ };