riskmarket-sdk 1.1.1

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.
Files changed (60) hide show
  1. package/README.md +440 -0
  2. package/dist/Graphs/fetchGraphChartsData.d.ts +1 -0
  3. package/dist/Graphs/fetchGraphChartsData.js +20 -0
  4. package/dist/Graphs/fetchOwnerBetHistory.d.ts +2 -0
  5. package/dist/Graphs/fetchOwnerBetHistory.js +121 -0
  6. package/dist/Graphs/fetchPlayerBetHistory.d.ts +1 -0
  7. package/dist/Graphs/fetchPlayerBetHistory.js +26 -0
  8. package/dist/Graphs/fetchPlayerBetHistoryInEpochs.d.ts +1 -0
  9. package/dist/Graphs/fetchPlayerBetHistoryInEpochs.js +29 -0
  10. package/dist/Graphs/fetchPlayerHistory.d.ts +1 -0
  11. package/dist/Graphs/fetchPlayerHistory.js +29 -0
  12. package/dist/Graphs.d.ts +14 -0
  13. package/dist/Graphs.js +30 -0
  14. package/dist/Helpers/calculatePnl.d.ts +2 -0
  15. package/dist/Helpers/calculatePnl.js +63 -0
  16. package/dist/Helpers.d.ts +11 -0
  17. package/dist/Helpers.js +19 -0
  18. package/dist/Market/read/getMarketIndexTermination.d.ts +1 -0
  19. package/dist/Market/read/getMarketIndexTermination.js +14 -0
  20. package/dist/Market/read/getMarketRoundByIndex.d.ts +1 -0
  21. package/dist/Market/read/getMarketRoundByIndex.js +17 -0
  22. package/dist/Market/read/getMinOpen.d.ts +1 -0
  23. package/dist/Market/read/getMinOpen.js +16 -0
  24. package/dist/Market/read/getPositionData.d.ts +1 -0
  25. package/dist/Market/read/getPositionData.js +23 -0
  26. package/dist/Market/read/getPositionProgress.d.ts +1 -0
  27. package/dist/Market/read/getPositionProgress.js +25 -0
  28. package/dist/Market/read/isUserPositionOpen.d.ts +4 -0
  29. package/dist/Market/read/isUserPositionOpen.js +31 -0
  30. package/dist/Market/write/cashout.d.ts +3 -0
  31. package/dist/Market/write/cashout.js +34 -0
  32. package/dist/Market/write/openMarket.d.ts +7 -0
  33. package/dist/Market/write/openMarket.js +41 -0
  34. package/dist/Market.d.ts +63 -0
  35. package/dist/Market.js +56 -0
  36. package/dist/Sockets.d.ts +42 -0
  37. package/dist/Sockets.js +132 -0
  38. package/dist/abi/BalanceOfAbi.d.ts +594 -0
  39. package/dist/abi/BalanceOfAbi.js +772 -0
  40. package/dist/abi/riskMarketAbi.d.ts +1704 -0
  41. package/dist/abi/riskMarketAbi.js +2193 -0
  42. package/dist/constants/index.d.ts +150 -0
  43. package/dist/constants/index.js +110 -0
  44. package/dist/index.d.ts +5 -0
  45. package/dist/index.js +5 -0
  46. package/dist/types.d.ts +37 -0
  47. package/dist/types.js +1 -0
  48. package/dist/utils/AxiosGraphInstance.d.ts +2 -0
  49. package/dist/utils/AxiosGraphInstance.js +24 -0
  50. package/dist/utils/external_services.d.ts +1 -0
  51. package/dist/utils/external_services.js +19 -0
  52. package/dist/utils/formatToWeb3Response.d.ts +1 -0
  53. package/dist/utils/formatToWeb3Response.js +32 -0
  54. package/dist/utils/helpers.d.ts +9 -0
  55. package/dist/utils/helpers.js +125 -0
  56. package/dist/web3/contractHelpers.d.ts +3 -0
  57. package/dist/web3/contractHelpers.js +17 -0
  58. package/dist/web3/web3.d.ts +4652 -0
  59. package/dist/web3/web3.js +11 -0
  60. package/package.json +41 -0
package/README.md ADDED
@@ -0,0 +1,440 @@
1
+ # RiskMarket SDK Documentation
2
+
3
+ ## Overview
4
+
5
+ RiskMarket SDK is designed as a **clean, modular, and extensible TypeScript SDK** for interacting with the RiskMarket protocol on **Arbitrum** and preparing on-chain transactions.
6
+
7
+ The SDK provides a single entry point through the `Market` class, which offers:
8
+
9
+ - **Read Methods** → Fetching on-chain data (market state, round info, position data, min open amount)
10
+ - **Write Methods** → Building encoded transaction calldata (open position, cash out)
11
+
12
+ ---
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ npm install riskmarket-sdk
18
+ ```
19
+
20
+ or
21
+
22
+ ```bash
23
+ yarn add riskmarket-sdk
24
+ ```
25
+
26
+ ## Initialization
27
+
28
+ ```ts
29
+ import { Market } from "riskmarket-sdk";
30
+
31
+ const market = new Market();
32
+ ```
33
+
34
+ The constructor accepts an optional `MarketOptions` object to configure the environment:
35
+
36
+ ```ts
37
+ import { Market } from "riskmarket-sdk";
38
+
39
+ const market = new Market({ environment: "production" });
40
+ ```
41
+
42
+ ### MarketOptions
43
+
44
+ | Option | Type | Default | Description |
45
+ | ------------- | ------------- | --------------- | ------------------------------------------------ |
46
+ | `environment` | `Environment` | `"development"` | Target environment: `"development"`, `"staging"`, or `"production"` |
47
+
48
+ > The constructor initializes an internal viem `PublicClient` connected to Arbitrum mainnet using the configuration for the selected environment.
49
+
50
+ ---
51
+
52
+ ## Read Methods
53
+
54
+ ### getMarketIndexTermination
55
+
56
+ Fetches the current market round index.
57
+
58
+ #### Method Signature
59
+
60
+ ```ts
61
+ getMarketIndexTermination(): Promise<bigint>
62
+ ```
63
+
64
+ #### Returns
65
+
66
+ `bigint` — The current market round index.
67
+
68
+ #### Example
69
+
70
+ ```ts
71
+ const currentIndex = await market.getMarketIndexTermination();
72
+ console.log(currentIndex); // 1363n
73
+ ```
74
+
75
+ ---
76
+
77
+ ### getMarketRoundByIndex
78
+
79
+ Fetches market round data for a specific index.
80
+
81
+ #### Method Signature
82
+
83
+ ```ts
84
+ getMarketRoundByIndex(index: number): Promise<MarketRound>
85
+ ```
86
+
87
+ #### Parameters
88
+
89
+ | Parameter | Type | Required | Description |
90
+ | --------- | -------- | -------- | --------------------- |
91
+ | `index` | `number` | ✅ | The market round index |
92
+
93
+ #### Returns
94
+
95
+ `MarketRound` — Market round data with all values as strings.
96
+
97
+ | Field | Type | Description |
98
+ | ------------------------- | -------- | ------------------------------ |
99
+ | `marketState` | `string` | Current state of the market |
100
+ | `index` | `string` | Market round index |
101
+ | `startTime` | `string` | Unix timestamp of round start |
102
+ | `totalAssets` | `string` | Total assets in the round |
103
+ | `requestId` | `string` | VRF request ID |
104
+ | `encryptedMarketDuration` | `string` | Encrypted market duration hash |
105
+ | `extraData` | `string` | Additional encoded data |
106
+
107
+ #### Example
108
+
109
+ ```ts
110
+ const round = await market.getMarketRoundByIndex(3);
111
+ console.log(round.index); // "3"
112
+ console.log(round.marketState); // "3"
113
+ console.log(round.startTime); // "1767267308"
114
+ console.log(round.totalAssets); // "9500000"
115
+ ```
116
+
117
+ ---
118
+
119
+ ### getMinOpen
120
+
121
+ Fetches the minimum position amount allowed to open a market position.
122
+
123
+ #### Method Signature
124
+
125
+ ```ts
126
+ getMinOpen(): Promise<string>
127
+ ```
128
+
129
+ #### Returns
130
+
131
+ `string` — The minimum position amount converted from Wei (mwei / 6 decimals).
132
+
133
+ #### Example
134
+
135
+ ```ts
136
+ const minOpen = await market.getMinOpen();
137
+ console.log(minOpen); // "1.000000"
138
+ ```
139
+
140
+ ---
141
+
142
+ ### getPositionData
143
+
144
+ Fetches the full position data for a user at a specific market round index.
145
+
146
+ #### Method Signature
147
+
148
+ ```ts
149
+ getPositionData(
150
+ userAddress: `0x${string}`,
151
+ index: number
152
+ ): Promise<PositionData>
153
+ ```
154
+
155
+ #### Parameters
156
+
157
+ | Parameter | Type | Required | Description |
158
+ | ------------- | ------------------- | -------- | ----------------------- |
159
+ | `userAddress` | `` `0x${string}` `` | ✅ | User's Ethereum address |
160
+ | `index` | `number` | ✅ | Market round index |
161
+
162
+ #### Returns
163
+
164
+ An object with the following fields (all numeric values are strings):
165
+
166
+ | Field | Type | Description |
167
+ | ----------------------- | ---------- | ----------------------------------------- |
168
+ | `marketType` | `string` | Market type identifier |
169
+ | `id` | `string` | Position ID (bytes32) |
170
+ | `user` | `string` | User's address |
171
+ | `amount` | `string` | Position amount placed |
172
+ | `line` | `string` | Cashout line target |
173
+ | `iterations` | `string` | Number of RNG iterations required |
174
+ | `startBlock` | `string` | Block number when position was opened |
175
+ | `startTime` | `string` | Unix timestamp when position was opened |
176
+ | `expiryTime` | `string` | Unix timestamp when position expires |
177
+ | `requiredConfirmations` | `string` | Number of confirmations required |
178
+ | `requestIds` | `string[]` | Array of VRF request IDs |
179
+ | `extraData` | `string` | Additional encoded position data |
180
+
181
+ #### Example
182
+
183
+ ```ts
184
+ const positionData = await market.getPositionData(
185
+ "0xa682C9022871881b3257A72E103B50fC75013245",
186
+ 1363
187
+ );
188
+ console.log(positionData.amount); // "9500000"
189
+ console.log(positionData.startTime); // "1767267308"
190
+ console.log(positionData.line); // "150"
191
+ ```
192
+
193
+ ---
194
+
195
+ ### getPositionProgress
196
+
197
+ Fetches the current settlement progress for a user's position at a specific market round index.
198
+
199
+ #### Method Signature
200
+
201
+ ```ts
202
+ getPositionProgress(
203
+ userAddress: `0x${string}`,
204
+ index: number
205
+ ): Promise<PositionProgress>
206
+ ```
207
+
208
+ #### Parameters
209
+
210
+ | Parameter | Type | Required | Description |
211
+ | ------------- | ------------------- | -------- | ----------------------- |
212
+ | `userAddress` | `` `0x${string}` `` | ✅ | User's Ethereum address |
213
+ | `index` | `number` | ✅ | Market round index |
214
+
215
+ #### Returns
216
+
217
+ An object with the following fields:
218
+
219
+ | Field | Type | Description |
220
+ | ----------------------- | -------- | -------------------------------------------------- |
221
+ | `marketType` | `string` | Market type identifier |
222
+ | `id` | `string` | Position ID (bytes32) |
223
+ | `user` | `string` | User's address |
224
+ | `settlement` | `string` | Settled payout amount |
225
+ | `receivedConfirmations` | `string` | Number of RNG confirmations received so far |
226
+ | `extraData` | `string` | Additional encoded progress data |
227
+
228
+ #### Example
229
+
230
+ ```ts
231
+ const progress = await market.getPositionProgress(
232
+ "0xa682C9022871881b3257A72E103B50fC75013245",
233
+ 1363
234
+ );
235
+ console.log(progress.receivedConfirmations); // "2"
236
+ console.log(progress.settlement); // "0"
237
+ ```
238
+
239
+ ---
240
+
241
+ ### isUserPositionOpen
242
+
243
+ Checks whether a user has an open position in a specific market round, and returns its amount and confirmation status.
244
+
245
+ #### Method Signature
246
+
247
+ ```ts
248
+ isUserPositionOpen(
249
+ user_address: `0x${string}`,
250
+ index: number
251
+ ): Promise<UserPositionInfo>
252
+ ```
253
+
254
+ #### Parameters
255
+
256
+ | Parameter | Type | Required | Description |
257
+ | -------------- | ------------------- | -------- | ----------------------- |
258
+ | `user_address` | `` `0x${string}` `` | ✅ | User's Ethereum address |
259
+ | `index` | `number` | ✅ | Market round index |
260
+
261
+ #### Returns
262
+
263
+ `UserPositionInfo`:
264
+
265
+ | Field | Type | Description |
266
+ | -------- | -------- | ------------------------------------------------ |
267
+ | `amount` | `string` | Position amount placed by the user |
268
+ | `status` | `string` | Number of RNG confirmations received (`receivedConfirmations`) |
269
+
270
+ #### Example
271
+
272
+ ```ts
273
+ const position = await market.isUserPositionOpen(
274
+ "0xa682C9022871881b3257A72E103B50fC75013245",
275
+ 1363
276
+ );
277
+ console.log(position.amount); // "9500000"
278
+ console.log(position.status); // "1"
279
+ ```
280
+
281
+ ---
282
+
283
+ ## Write Methods
284
+
285
+ Write methods return **encoded transaction calldata** as an array of `EncodedCall` objects. They **do not execute transactions** — you must send them through your own provider or smart account client.
286
+
287
+ ### Return Type (All Write Methods)
288
+
289
+ ```ts
290
+ interface EncodedCall {
291
+ to: `0x${string}`;
292
+ data: `0x${string}`;
293
+ }
294
+ ```
295
+
296
+ All write methods return `Promise<EncodedCall[]>`.
297
+
298
+ ---
299
+
300
+ ### openMarketMethod
301
+
302
+ Builds encoded calldata for opening a position in the current market round. Internally fetches the current round index and retrieves RNG data from the API before encoding the transaction.
303
+
304
+ #### Method Signature
305
+
306
+ ```ts
307
+ openMarketMethod(params: {
308
+ amount: string;
309
+ smartAccount: string;
310
+ }): Promise<EncodedCall[]>
311
+ ```
312
+
313
+ #### Parameters
314
+
315
+ | Parameter | Type | Required | Description |
316
+ | -------------- | -------- | -------- | ---------------------------------------- |
317
+ | `amount` | `string` | ✅ | Amount (in USDT) to place as a position |
318
+ | `smartAccount` | `string` | ✅ | Smart account address |
319
+
320
+ #### Example
321
+
322
+ ```ts
323
+ const calls = await market.openMarketMethod({
324
+ amount: "10",
325
+ smartAccount: "0xa682C9022871881b3257A72E103B50fC75013245",
326
+ });
327
+
328
+ // Execute via your smart account client
329
+ await smartAccountClient.sendTransaction({ calls });
330
+ ```
331
+
332
+ ---
333
+
334
+ ### cashOutMethod
335
+
336
+ Builds encoded calldata for cashing out (closing) an open position. Internally calls the API to retrieve a signed key before encoding the transaction.
337
+
338
+ #### Method Signature
339
+
340
+ ```ts
341
+ cashOutMethod(params: {
342
+ smartAccount: string;
343
+ }): Promise<EncodedCall[]>
344
+ ```
345
+
346
+ #### Parameters
347
+
348
+ | Parameter | Type | Required | Description |
349
+ | -------------- | -------- | -------- | --------------------- |
350
+ | `smartAccount` | `string` | ✅ | Smart account address |
351
+
352
+ #### Example
353
+
354
+ ```ts
355
+ const calls = await market.cashOutMethod({
356
+ smartAccount: "0xa682C9022871881b3257A72E103B50fC75013245",
357
+ });
358
+
359
+ // Execute via your smart account client
360
+ await smartAccountClient.sendTransaction({ calls });
361
+ ```
362
+
363
+ ---
364
+
365
+ ## Recommended Usage Pattern
366
+
367
+ ```ts
368
+ import { Market } from "riskmarket-sdk";
369
+
370
+ const market = new Market({ environment: "production" });
371
+
372
+ // 1. Read current round info
373
+ const currentIndex = await market.getMarketIndexTermination();
374
+ const round = await market.getMarketRoundByIndex(Number(currentIndex));
375
+ console.log("Current round state:", round.marketState);
376
+
377
+ // 2. Check if user already has a position
378
+ const position = await market.isUserPositionOpen(
379
+ "0xYourSmartAccount...",
380
+ Number(currentIndex)
381
+ );
382
+
383
+ // 3. Open a position (if none exists)
384
+ if (position.amount === "0") {
385
+ const openCalls = await market.openMarketMethod({
386
+ amount: "10",
387
+ smartAccount: "0xYourSmartAccount...",
388
+ });
389
+ await smartAccountClient.sendTransaction({ calls: openCalls });
390
+ }
391
+
392
+ // 4. Cash out when ready
393
+ const cashOutCalls = await market.cashOutMethod({
394
+ smartAccount: "0xYourSmartAccount...",
395
+ });
396
+ await smartAccountClient.sendTransaction({ calls: cashOutCalls });
397
+ ```
398
+
399
+ ---
400
+
401
+ ## Local Development Setup
402
+
403
+ To use this SDK locally during development:
404
+
405
+ 1. Navigate to the SDK directory and link it:
406
+
407
+ ```bash
408
+ cd riskmarket-sdk
409
+ yarn build
410
+ yarn link
411
+ ```
412
+
413
+ 2. In your consumer application directory, link to the local SDK:
414
+
415
+ ```bash
416
+ cd /path/to/your/consumer/app
417
+ yarn link "riskmarket-sdk"
418
+ ```
419
+
420
+ 3. After making changes to the SDK, rebuild it:
421
+
422
+ ```bash
423
+ yarn build
424
+ ```
425
+
426
+ 4. Restart your consumer application to pick up the changes.
427
+
428
+ ---
429
+
430
+ ## Versioning Policy
431
+
432
+ RiskMarket SDK follows **Semantic Versioning**:
433
+
434
+ - **Patch** (`1.0.x`) → Bug fixes
435
+ - **Minor** (`1.x.0`) → New features, backward compatible
436
+ - **Major** (`x.0.0`) → Breaking API changes
437
+
438
+ ---
439
+
440
+ **RiskMarket SDK** is built to scale with both products and protocols.
@@ -0,0 +1 @@
1
+ export declare const fetchGraphChartsData: () => Promise<any>;
@@ -0,0 +1,20 @@
1
+ import AxiosGraphInstance from "../utils/AxiosGraphInstance.js";
2
+ export const fetchGraphChartsData = async () => {
3
+ const query = `
4
+ query finalizeMarketTerminations {
5
+ finalizeMarketTerminations(first: 1000, orderBy: blockNumber, orderDirection: desc) {
6
+ transactionHash
7
+ marketIndexTermination
8
+ random
9
+ }
10
+ }
11
+ `;
12
+ try {
13
+ const data = await AxiosGraphInstance(query);
14
+ return data?.finalizeMarketTerminations ?? [];
15
+ }
16
+ catch (error) {
17
+ console.error("Failed to fetch graph charts data:", error);
18
+ throw error;
19
+ }
20
+ };
@@ -0,0 +1,2 @@
1
+ import { TimePeriod } from "../types.js";
2
+ export declare const fetchOwnerBetHistory: (userAddress: `0x${string}`, timePeriod?: TimePeriod) => Promise<any>;
@@ -0,0 +1,121 @@
1
+ import AxiosGraphInstance from "../utils/AxiosGraphInstance.js";
2
+ import { UtilitiyFunctions } from "../utils/helpers.js";
3
+ export const fetchOwnerBetHistory = async (userAddress, timePeriod = "all") => {
4
+ const closePositionQuery = `
5
+ query closePositionTerminations {
6
+ closePositionTerminations(where: { user: "${userAddress}" }) {
7
+ marketIndexTermination
8
+ positionId
9
+ settlement
10
+ closePositionTimeMs
11
+ blockTimestamp
12
+ blockNumber
13
+ id
14
+ timeElapsed
15
+ transactionHash
16
+ user
17
+ }
18
+ }
19
+ `;
20
+ const openPositionQuery = `
21
+ query openPositionTerminations {
22
+ openPositionTerminations(where: { user: "${userAddress}" }) {
23
+ marketIndexTermination
24
+ amount
25
+ blockTimestamp
26
+ transactionHash
27
+ blockNumber
28
+ user
29
+ positionId
30
+ }
31
+ }
32
+ `;
33
+ try {
34
+ const [closePositionData, openPositionData] = await Promise.all([
35
+ AxiosGraphInstance(closePositionQuery),
36
+ AxiosGraphInstance(openPositionQuery),
37
+ ]);
38
+ let closePositions = closePositionData?.closePositionTerminations ?? [];
39
+ let openPositions = openPositionData?.openPositionTerminations ?? [];
40
+ const now = Math.floor(Date.now() / 1000);
41
+ let timeThreshold = 0;
42
+ switch (timePeriod) {
43
+ case "day":
44
+ timeThreshold = now - 24 * 60 * 60;
45
+ break;
46
+ case "week":
47
+ timeThreshold = now - 7 * 24 * 60 * 60;
48
+ break;
49
+ case "month":
50
+ timeThreshold = now - 30 * 24 * 60 * 60;
51
+ break;
52
+ case "all":
53
+ default:
54
+ timeThreshold = 0;
55
+ break;
56
+ }
57
+ if (timePeriod !== "all") {
58
+ closePositions = closePositions.filter((pos) => Number(pos.blockTimestamp) >= timeThreshold);
59
+ openPositions = openPositions.filter((pos) => Number(pos.blockTimestamp) >= timeThreshold);
60
+ }
61
+ const totalAmountFromPlaced = openPositions.reduce((sum, bet) => {
62
+ return (sum +
63
+ parseFloat(UtilitiyFunctions.convertFromWei(bet?.amount || "0", "mwei")));
64
+ }, 0);
65
+ const totalAmountFromResolved = closePositions.reduce((sum, bet) => {
66
+ return (sum +
67
+ parseFloat(UtilitiyFunctions.convertFromWei(bet?.settlement || "0", "mwei")));
68
+ }, 0);
69
+ const netProfit = totalAmountFromResolved - totalAmountFromPlaced;
70
+ const graphData = closePositions.map((closePos) => {
71
+ const openPos = openPositions.find((op) => op.positionId === closePos.positionId);
72
+ const amountPlaced = openPos
73
+ ? parseFloat(UtilitiyFunctions.convertFromWei(openPos.amount || "0", "mwei"))
74
+ : 0;
75
+ const settlement = parseFloat(UtilitiyFunctions.convertFromWei(closePos.settlement || "0", "mwei"));
76
+ const pnl = settlement - amountPlaced;
77
+ const timestamp = new Date(Number(closePos.blockTimestamp) * 1000).toISOString();
78
+ const date = new Date(Number(closePos.blockTimestamp) * 1000);
79
+ let label = "";
80
+ switch (timePeriod) {
81
+ case "day": {
82
+ const hours = date.getHours().toString().padStart(2, "0");
83
+ const minutes = date.getMinutes().toString().padStart(2, "0");
84
+ label = `${hours}:${minutes}`;
85
+ break;
86
+ }
87
+ case "week":
88
+ case "month":
89
+ case "all":
90
+ default: {
91
+ const day = date.getDate().toString().padStart(2, "0");
92
+ const month = (date.getMonth() + 1).toString().padStart(2, "0");
93
+ label = `${day}/${month}`;
94
+ break;
95
+ }
96
+ }
97
+ return {
98
+ label,
99
+ pnl,
100
+ timestamp,
101
+ blockTimestamp: Number(closePos.blockTimestamp),
102
+ };
103
+ });
104
+ const sortedGraphData = graphData.sort((a, b) => a.blockTimestamp - b.blockTimestamp);
105
+ let cumulativePnl = 0;
106
+ const graphDataWithOverallPnl = sortedGraphData.map((item) => {
107
+ cumulativePnl += item.pnl;
108
+ return {
109
+ label: item.label,
110
+ pnl: item.pnl,
111
+ overallPnl: cumulativePnl,
112
+ timestamp: item.timestamp,
113
+ };
114
+ });
115
+ return { netProfit, graphData: graphDataWithOverallPnl };
116
+ }
117
+ catch (error) {
118
+ console.error("Failed to fetch owner bet history:", error);
119
+ throw error;
120
+ }
121
+ };
@@ -0,0 +1 @@
1
+ export declare const fetchPlayerBetHistory: (userAddress: `0x${string}`) => Promise<any>;
@@ -0,0 +1,26 @@
1
+ import AxiosGraphInstance from "../utils/AxiosGraphInstance.js";
2
+ export const fetchPlayerBetHistory = async (userAddress) => {
3
+ const query = `
4
+ query openPositionTerminations {
5
+ openPositionTerminations(where: { user: "${userAddress}" }) {
6
+ marketIndexTermination
7
+ amount
8
+ blockTimestamp
9
+ transactionHash
10
+ blockNumber
11
+ user
12
+ positionId
13
+ }
14
+ }
15
+ `;
16
+ try {
17
+ const data = await AxiosGraphInstance(query);
18
+ const allPositions = data?.openPositionTerminations ?? [];
19
+ const sortedHistory = allPositions.sort((a, b) => Number(b.blockTimestamp) - Number(a.blockTimestamp));
20
+ return sortedHistory;
21
+ }
22
+ catch (error) {
23
+ console.error("Failed to fetch player bet history:", error);
24
+ throw error;
25
+ }
26
+ };
@@ -0,0 +1 @@
1
+ export declare const fetchPlayerBetHistoryInEpochs: (userAddress: `0x${string}`) => Promise<any>;
@@ -0,0 +1,29 @@
1
+ import AxiosGraphInstance from "../utils/AxiosGraphInstance.js";
2
+ export const fetchPlayerBetHistoryInEpochs = async (userAddress) => {
3
+ const currentEpoch = Date.now() / 1000;
4
+ const currentDate = new Date(currentEpoch * 1000);
5
+ const startOfDay = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate());
6
+ const startOfDayEpoch = Math.floor(startOfDay.getTime() / 1000);
7
+ const endOfDayEpoch = startOfDayEpoch + 86399;
8
+ const query = `
9
+ query openPositionTerminations {
10
+ openPositionTerminations(where: {
11
+ user: "${userAddress}",
12
+ blockTimestamp_gte: "${startOfDayEpoch}",
13
+ blockTimestamp_lte: "${endOfDayEpoch}"
14
+ }) {
15
+ amount
16
+ }
17
+ }
18
+ `;
19
+ try {
20
+ const data = await AxiosGraphInstance(query);
21
+ const allPositions = data?.openPositionTerminations ?? [];
22
+ const sortedHistory = allPositions.sort((a, b) => Number(b.blockTimestamp) - Number(a.blockTimestamp));
23
+ return sortedHistory;
24
+ }
25
+ catch (error) {
26
+ console.error("Failed to fetch player bet history:", error);
27
+ throw error;
28
+ }
29
+ };
@@ -0,0 +1 @@
1
+ export declare const fetchPlayerHistory: (userAddress: `0x${string}`) => Promise<any>;
@@ -0,0 +1,29 @@
1
+ import AxiosGraphInstance from "../utils/AxiosGraphInstance.js";
2
+ export const fetchPlayerHistory = async (userAddress) => {
3
+ const query = `
4
+ query closePositionTerminations {
5
+ closePositionTerminations(where: { user: "${userAddress}" }) {
6
+ marketIndexTermination
7
+ positionId
8
+ settlement
9
+ closePositionTimeMs
10
+ blockTimestamp
11
+ blockNumber
12
+ id
13
+ timeElapsed
14
+ transactionHash
15
+ user
16
+ }
17
+ }
18
+ `;
19
+ try {
20
+ const data = await AxiosGraphInstance(query);
21
+ const allPositions = data?.closePositionTerminations ?? [];
22
+ const sortedHistory = allPositions.sort((a, b) => Number(b.blockTimestamp) - Number(a.blockTimestamp));
23
+ return sortedHistory;
24
+ }
25
+ catch (error) {
26
+ console.error("Failed to fetch player history:", error);
27
+ throw error;
28
+ }
29
+ };
@@ -0,0 +1,14 @@
1
+ import { type Environment } from "./constants/index.js";
2
+ import { TimePeriod } from "./types.js";
3
+ export interface GraphOptions {
4
+ environment?: Environment;
5
+ }
6
+ export declare class Graphs {
7
+ private config;
8
+ constructor(options?: GraphOptions);
9
+ fetchGraphChartsData(): Promise<any>;
10
+ fetchOwnerBetHistory(userAddress: `0x${string}`, timePeriod?: TimePeriod): Promise<any>;
11
+ fetchPlayerBetHistory(userAddress: `0x${string}`): Promise<any>;
12
+ fetchPlayerBetHistoryInEpochs(userAddress: `0x${string}`): Promise<any>;
13
+ fetchPlayerHistory(userAddress: `0x${string}`): Promise<any>;
14
+ }