@trufnetwork/sdk-js 0.5.10 → 0.6.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 +45 -0
  2. package/dist/cjs/client/client.cjs +30 -0
  3. package/dist/cjs/client/client.cjs.map +2 -2
  4. package/dist/cjs/contracts-api/action.cjs +22 -0
  5. package/dist/cjs/contracts-api/action.cjs.map +2 -2
  6. package/dist/cjs/contracts-api/action.test.cjs +63 -0
  7. package/dist/cjs/contracts-api/action.test.cjs.map +7 -0
  8. package/dist/cjs/contracts-api/orderbookAction.cjs +880 -0
  9. package/dist/cjs/contracts-api/orderbookAction.cjs.map +7 -0
  10. package/dist/cjs/internal.cjs +9 -0
  11. package/dist/cjs/internal.cjs.map +2 -2
  12. package/dist/cjs/types/bridge.cjs.map +1 -1
  13. package/dist/cjs/types/orderbook.cjs +19 -0
  14. package/dist/cjs/types/orderbook.cjs.map +7 -0
  15. package/dist/cjs/util/AttestationEncoding.cjs +3 -2
  16. package/dist/cjs/util/AttestationEncoding.cjs.map +2 -2
  17. package/dist/cjs/util/orderbookHelpers.cjs +194 -0
  18. package/dist/cjs/util/orderbookHelpers.cjs.map +7 -0
  19. package/dist/cjs/util/orderbookHelpers.test.cjs +217 -0
  20. package/dist/cjs/util/orderbookHelpers.test.cjs.map +7 -0
  21. package/dist/esm/client/client.mjs +30 -0
  22. package/dist/esm/client/client.mjs.map +2 -2
  23. package/dist/esm/contracts-api/action.mjs +22 -0
  24. package/dist/esm/contracts-api/action.mjs.map +2 -2
  25. package/dist/esm/contracts-api/action.test.mjs +61 -0
  26. package/dist/esm/contracts-api/action.test.mjs.map +7 -0
  27. package/dist/esm/contracts-api/orderbookAction.mjs +875 -0
  28. package/dist/esm/contracts-api/orderbookAction.mjs.map +7 -0
  29. package/dist/esm/internal.mjs +16 -0
  30. package/dist/esm/internal.mjs.map +2 -2
  31. package/dist/esm/types/orderbook.mjs +1 -0
  32. package/dist/esm/types/orderbook.mjs.map +7 -0
  33. package/dist/esm/util/AttestationEncoding.mjs +3 -2
  34. package/dist/esm/util/AttestationEncoding.mjs.map +2 -2
  35. package/dist/esm/util/orderbookHelpers.mjs +173 -0
  36. package/dist/esm/util/orderbookHelpers.mjs.map +7 -0
  37. package/dist/esm/util/orderbookHelpers.test.mjs +229 -0
  38. package/dist/esm/util/orderbookHelpers.test.mjs.map +7 -0
  39. package/dist/tsconfig.build.tsbuildinfo +1 -1
  40. package/dist/types/client/client.d.ts +23 -1
  41. package/dist/types/client/client.d.ts.map +1 -1
  42. package/dist/types/contracts-api/action.d.ts +11 -1
  43. package/dist/types/contracts-api/action.d.ts.map +1 -1
  44. package/dist/types/contracts-api/action.test.d.ts +2 -0
  45. package/dist/types/contracts-api/action.test.d.ts.map +1 -0
  46. package/dist/types/contracts-api/orderbookAction.d.ts +303 -0
  47. package/dist/types/contracts-api/orderbookAction.d.ts.map +1 -0
  48. package/dist/types/internal.d.ts +3 -0
  49. package/dist/types/internal.d.ts.map +1 -1
  50. package/dist/types/types/bridge.d.ts +45 -0
  51. package/dist/types/types/bridge.d.ts.map +1 -1
  52. package/dist/types/types/orderbook.d.ts +376 -0
  53. package/dist/types/types/orderbook.d.ts.map +1 -0
  54. package/dist/types/util/AttestationEncoding.d.ts +9 -1
  55. package/dist/types/util/AttestationEncoding.d.ts.map +1 -1
  56. package/dist/types/util/orderbookHelpers.d.ts +161 -0
  57. package/dist/types/util/orderbookHelpers.d.ts.map +1 -0
  58. package/dist/types/util/orderbookHelpers.test.d.ts +2 -0
  59. package/dist/types/util/orderbookHelpers.test.d.ts.map +1 -0
  60. package/package.json +1 -1
@@ -0,0 +1,880 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/contracts-api/orderbookAction.ts
21
+ var orderbookAction_exports = {};
22
+ __export(orderbookAction_exports, {
23
+ OrderbookAction: () => OrderbookAction
24
+ });
25
+ module.exports = __toCommonJS(orderbookAction_exports);
26
+ var import_orderbookHelpers = require("../util/orderbookHelpers.cjs");
27
+ var OrderbookAction = class {
28
+ kwilClient;
29
+ kwilSigner;
30
+ constructor(kwilClient, kwilSigner) {
31
+ this.kwilClient = kwilClient;
32
+ this.kwilSigner = kwilSigner;
33
+ }
34
+ // ==========================================
35
+ // Market Operations
36
+ // ==========================================
37
+ /**
38
+ * Creates a new binary prediction market.
39
+ *
40
+ * @param input - Market creation parameters
41
+ * @returns Transaction receipt with tx_hash
42
+ *
43
+ * @example
44
+ * ```typescript
45
+ * const args = OrderbookAction.encodeActionArgs(
46
+ * dataProvider, streamId, timestamp, threshold, frozenAt
47
+ * );
48
+ * const queryComponents = OrderbookAction.encodeQueryComponents(
49
+ * dataProvider, streamId, "price_above_threshold", args
50
+ * );
51
+ *
52
+ * const result = await orderbook.createMarket({
53
+ * bridge: "hoodi_tt2",
54
+ * queryComponents,
55
+ * settleTime: Math.floor(Date.now() / 1000) + 3600,
56
+ * maxSpread: 10,
57
+ * minOrderSize: 1,
58
+ * });
59
+ * ```
60
+ */
61
+ async createMarket(input) {
62
+ (0, import_orderbookHelpers.validateBridge)(input.bridge);
63
+ (0, import_orderbookHelpers.validateMaxSpread)(input.maxSpread);
64
+ (0, import_orderbookHelpers.validateSettleTime)(input.settleTime);
65
+ return this.kwilClient.execute(
66
+ {
67
+ namespace: "main",
68
+ name: "create_market",
69
+ inputs: [
70
+ {
71
+ $bridge: input.bridge,
72
+ $query_components: input.queryComponents,
73
+ $settle_time: input.settleTime,
74
+ $max_spread: input.maxSpread,
75
+ $min_order_size: input.minOrderSize
76
+ }
77
+ ],
78
+ description: "TN SDK - Create market"
79
+ },
80
+ this.kwilSigner
81
+ );
82
+ }
83
+ /**
84
+ * Gets detailed information about a market.
85
+ *
86
+ * @param queryId - Market identifier
87
+ * @returns Full market information
88
+ */
89
+ async getMarketInfo(queryId) {
90
+ const result = await this.kwilClient.call(
91
+ {
92
+ namespace: "main",
93
+ name: "get_market_info",
94
+ inputs: { $query_id: queryId }
95
+ },
96
+ this.kwilSigner
97
+ );
98
+ if (result.status !== 200) {
99
+ throw new Error(`Failed to get market info: ${result.status}`);
100
+ }
101
+ const rows = result.data?.result;
102
+ if (!rows || rows.length === 0) {
103
+ throw new Error(`Market not found: ${queryId}`);
104
+ }
105
+ return this.parseMarketInfo(rows[0], queryId);
106
+ }
107
+ /**
108
+ * Gets market information by query hash.
109
+ *
110
+ * @param queryHash - SHA256 hash of query components (32 bytes)
111
+ * @returns Full market information
112
+ */
113
+ async getMarketByHash(queryHash) {
114
+ if (queryHash.length !== 32) {
115
+ throw new Error("Query hash must be exactly 32 bytes");
116
+ }
117
+ const result = await this.kwilClient.call(
118
+ {
119
+ namespace: "main",
120
+ name: "get_market_by_hash",
121
+ inputs: { $query_hash: queryHash }
122
+ },
123
+ this.kwilSigner
124
+ );
125
+ if (result.status !== 200) {
126
+ throw new Error(`Failed to get market by hash: ${result.status}`);
127
+ }
128
+ const rows = result.data?.result;
129
+ if (!rows || rows.length === 0) {
130
+ throw new Error("Market not found for given hash");
131
+ }
132
+ return this.parseMarketInfo(rows[0]);
133
+ }
134
+ /**
135
+ * Lists markets with optional filtering.
136
+ *
137
+ * @param input - Filter and pagination options
138
+ * @returns Array of market summaries
139
+ */
140
+ async listMarkets(input) {
141
+ const settledFilter = (0, import_orderbookHelpers.settledFilterToBoolean)(input?.settledFilter);
142
+ const result = await this.kwilClient.call(
143
+ {
144
+ namespace: "main",
145
+ name: "list_markets",
146
+ inputs: {
147
+ $settled_filter: settledFilter,
148
+ $limit_val: input?.limit ?? 100,
149
+ $offset_val: input?.offset ?? 0
150
+ }
151
+ },
152
+ this.kwilSigner
153
+ );
154
+ if (result.status !== 200) {
155
+ throw new Error(`Failed to list markets: ${result.status}`);
156
+ }
157
+ const rows = result.data?.result || [];
158
+ return rows.map((row) => this.parseMarketSummary(row));
159
+ }
160
+ /**
161
+ * Checks if a market exists for the given query hash.
162
+ *
163
+ * @param queryHash - SHA256 hash of query components (32 bytes)
164
+ * @returns true if market exists
165
+ */
166
+ async marketExists(queryHash) {
167
+ if (queryHash.length !== 32) {
168
+ throw new Error("Query hash must be exactly 32 bytes");
169
+ }
170
+ const result = await this.kwilClient.call(
171
+ {
172
+ namespace: "main",
173
+ name: "market_exists",
174
+ inputs: { $query_hash: queryHash }
175
+ },
176
+ this.kwilSigner
177
+ );
178
+ if (result.status !== 200) {
179
+ throw new Error(`Failed to check market exists: ${result.status}`);
180
+ }
181
+ const rows = result.data?.result;
182
+ return rows && rows.length > 0 && rows[0].exists;
183
+ }
184
+ /**
185
+ * Validates market collateral integrity.
186
+ *
187
+ * Checks that:
188
+ * - YES and NO token counts match (binary pairs)
189
+ * - Vault balance matches expected collateral
190
+ *
191
+ * @param queryId - Market identifier
192
+ * @returns Validation result with detailed breakdown
193
+ */
194
+ async validateMarketCollateral(queryId) {
195
+ const result = await this.kwilClient.call(
196
+ {
197
+ namespace: "main",
198
+ name: "validate_market_collateral",
199
+ inputs: { $query_id: queryId }
200
+ },
201
+ this.kwilSigner
202
+ );
203
+ if (result.status !== 200) {
204
+ throw new Error(`Failed to validate market collateral: ${result.status}`);
205
+ }
206
+ const rows = result.data?.result;
207
+ if (!rows || rows.length === 0) {
208
+ throw new Error(`Market not found: ${queryId}`);
209
+ }
210
+ const row = rows[0];
211
+ return {
212
+ validTokenBinaries: row.valid_token_binaries,
213
+ validCollateral: row.valid_collateral,
214
+ totalTrue: row.total_true,
215
+ totalFalse: row.total_false,
216
+ vaultBalance: row.vault_balance,
217
+ expectedCollateral: row.expected_collateral,
218
+ openBuysValue: row.open_buys_value
219
+ };
220
+ }
221
+ // ==========================================
222
+ // Order Placement Operations
223
+ // ==========================================
224
+ /**
225
+ * Places a buy order for shares.
226
+ *
227
+ * Locks collateral: amount × price × 10^16 wei
228
+ *
229
+ * @param input - Order parameters
230
+ * @returns Transaction receipt
231
+ */
232
+ async placeBuyOrder(input) {
233
+ (0, import_orderbookHelpers.validatePrice)(input.price, "placeBuyOrder");
234
+ (0, import_orderbookHelpers.validateAmount)(input.amount, "placeBuyOrder");
235
+ return this.kwilClient.execute(
236
+ {
237
+ namespace: "main",
238
+ name: "place_buy_order",
239
+ inputs: [
240
+ {
241
+ $query_id: input.queryId,
242
+ $outcome: input.outcome,
243
+ $price: input.price,
244
+ $amount: input.amount
245
+ }
246
+ ],
247
+ description: "TN SDK - Place buy order"
248
+ },
249
+ this.kwilSigner
250
+ );
251
+ }
252
+ /**
253
+ * Places a sell order for owned shares.
254
+ *
255
+ * @param input - Order parameters
256
+ * @returns Transaction receipt
257
+ */
258
+ async placeSellOrder(input) {
259
+ (0, import_orderbookHelpers.validatePrice)(input.price, "placeSellOrder");
260
+ (0, import_orderbookHelpers.validateAmount)(input.amount, "placeSellOrder");
261
+ return this.kwilClient.execute(
262
+ {
263
+ namespace: "main",
264
+ name: "place_sell_order",
265
+ inputs: [
266
+ {
267
+ $query_id: input.queryId,
268
+ $outcome: input.outcome,
269
+ $price: input.price,
270
+ $amount: input.amount
271
+ }
272
+ ],
273
+ description: "TN SDK - Place sell order"
274
+ },
275
+ this.kwilSigner
276
+ );
277
+ }
278
+ /**
279
+ * Places a split limit order for market making.
280
+ *
281
+ * Atomically:
282
+ * 1. Locks collateral (amount × $1.00)
283
+ * 2. Mints a YES/NO share pair
284
+ * 3. Keeps YES shares as holdings
285
+ * 4. Places NO shares as a sell order at (100 - truePrice) cents
286
+ *
287
+ * @param input - Order parameters
288
+ * @returns Transaction receipt
289
+ *
290
+ * @example
291
+ * ```typescript
292
+ * // Create 100 pairs at YES=55¢, NO=45¢
293
+ * await orderbook.placeSplitLimitOrder({
294
+ * queryId: market.id,
295
+ * truePrice: 55,
296
+ * amount: 100,
297
+ * });
298
+ * // Result: 100 YES holdings + 100 NO sell orders at 45¢
299
+ * ```
300
+ */
301
+ async placeSplitLimitOrder(input) {
302
+ (0, import_orderbookHelpers.validatePrice)(input.truePrice, "placeSplitLimitOrder");
303
+ (0, import_orderbookHelpers.validateAmount)(input.amount, "placeSplitLimitOrder");
304
+ return this.kwilClient.execute(
305
+ {
306
+ namespace: "main",
307
+ name: "place_split_limit_order",
308
+ inputs: [
309
+ {
310
+ $query_id: input.queryId,
311
+ $true_price: input.truePrice,
312
+ $amount: input.amount
313
+ }
314
+ ],
315
+ description: "TN SDK - Place split limit order"
316
+ },
317
+ this.kwilSigner
318
+ );
319
+ }
320
+ /**
321
+ * Cancels an open order.
322
+ *
323
+ * Cannot cancel holdings (price = 0).
324
+ *
325
+ * @param input - Order to cancel
326
+ * @returns Transaction receipt
327
+ */
328
+ async cancelOrder(input) {
329
+ if (input.price === 0) {
330
+ throw new Error("Cannot cancel holdings (price = 0)");
331
+ }
332
+ return this.kwilClient.execute(
333
+ {
334
+ namespace: "main",
335
+ name: "cancel_order",
336
+ inputs: [
337
+ {
338
+ $query_id: input.queryId,
339
+ $outcome: input.outcome,
340
+ $price: input.price
341
+ }
342
+ ],
343
+ description: "TN SDK - Cancel order"
344
+ },
345
+ this.kwilSigner
346
+ );
347
+ }
348
+ /**
349
+ * Modifies a buy order atomically.
350
+ *
351
+ * Preserves FIFO queue position via timestamp inheritance.
352
+ *
353
+ * @param input - Bid modification parameters
354
+ * @returns Transaction receipt
355
+ */
356
+ async changeBid(input) {
357
+ if (input.oldPrice >= 0 || input.newPrice >= 0) {
358
+ throw new Error("changeBid: Prices must be negative (buy orders)");
359
+ }
360
+ (0, import_orderbookHelpers.validateAmount)(input.newAmount, "changeBid");
361
+ return this.kwilClient.execute(
362
+ {
363
+ namespace: "main",
364
+ name: "change_bid",
365
+ inputs: [
366
+ {
367
+ $query_id: input.queryId,
368
+ $outcome: input.outcome,
369
+ $old_price: input.oldPrice,
370
+ $new_price: input.newPrice,
371
+ $new_amount: input.newAmount
372
+ }
373
+ ],
374
+ description: "TN SDK - Change bid"
375
+ },
376
+ this.kwilSigner
377
+ );
378
+ }
379
+ /**
380
+ * Modifies a sell order atomically.
381
+ *
382
+ * Preserves FIFO queue position via timestamp inheritance.
383
+ *
384
+ * @param input - Ask modification parameters
385
+ * @returns Transaction receipt
386
+ */
387
+ async changeAsk(input) {
388
+ if (input.oldPrice <= 0 || input.newPrice <= 0) {
389
+ throw new Error(
390
+ "changeAsk: Prices must be strictly positive (sell orders, price 0 is holdings)"
391
+ );
392
+ }
393
+ (0, import_orderbookHelpers.validateAmount)(input.newAmount, "changeAsk");
394
+ return this.kwilClient.execute(
395
+ {
396
+ namespace: "main",
397
+ name: "change_ask",
398
+ inputs: [
399
+ {
400
+ $query_id: input.queryId,
401
+ $outcome: input.outcome,
402
+ $old_price: input.oldPrice,
403
+ $new_price: input.newPrice,
404
+ $new_amount: input.newAmount
405
+ }
406
+ ],
407
+ description: "TN SDK - Change ask"
408
+ },
409
+ this.kwilSigner
410
+ );
411
+ }
412
+ // ==========================================
413
+ // Query Operations (Read-only)
414
+ // ==========================================
415
+ /**
416
+ * Gets the order book for a market outcome.
417
+ *
418
+ * Returns all buy and sell orders (excludes holdings).
419
+ *
420
+ * @param queryId - Market identifier
421
+ * @param outcome - true=YES, false=NO
422
+ * @returns Array of order book entries
423
+ */
424
+ async getOrderBook(queryId, outcome) {
425
+ const result = await this.kwilClient.call(
426
+ {
427
+ namespace: "main",
428
+ name: "get_order_book",
429
+ inputs: {
430
+ $query_id: queryId,
431
+ $outcome: outcome
432
+ }
433
+ },
434
+ this.kwilSigner
435
+ );
436
+ if (result.status !== 200) {
437
+ throw new Error(`Failed to get order book: ${result.status}`);
438
+ }
439
+ const rows = result.data?.result || [];
440
+ return rows.map((row) => ({
441
+ walletAddress: (0, import_orderbookHelpers.dbBytesToUint8Array)(row.wallet_address),
442
+ price: row.price,
443
+ amount: row.amount,
444
+ lastUpdated: row.last_updated
445
+ }));
446
+ }
447
+ /**
448
+ * Gets the caller's positions across all markets.
449
+ *
450
+ * @returns Array of user positions (holdings and orders)
451
+ */
452
+ async getUserPositions() {
453
+ const result = await this.kwilClient.call(
454
+ {
455
+ namespace: "main",
456
+ name: "get_user_positions",
457
+ inputs: {}
458
+ },
459
+ this.kwilSigner
460
+ );
461
+ if (result.status !== 200) {
462
+ throw new Error(`Failed to get user positions: ${result.status}`);
463
+ }
464
+ const rows = result.data?.result || [];
465
+ return rows.map((row) => ({
466
+ queryId: row.query_id,
467
+ outcome: row.outcome,
468
+ price: row.price,
469
+ amount: row.amount,
470
+ lastUpdated: row.last_updated
471
+ }));
472
+ }
473
+ /**
474
+ * Gets aggregated market depth for an outcome.
475
+ *
476
+ * @param queryId - Market identifier
477
+ * @param outcome - true=YES, false=NO
478
+ * @returns Array of depth levels (price + total volume)
479
+ */
480
+ async getMarketDepth(queryId, outcome) {
481
+ const result = await this.kwilClient.call(
482
+ {
483
+ namespace: "main",
484
+ name: "get_market_depth",
485
+ inputs: {
486
+ $query_id: queryId,
487
+ $outcome: outcome
488
+ }
489
+ },
490
+ this.kwilSigner
491
+ );
492
+ if (result.status !== 200) {
493
+ throw new Error(`Failed to get market depth: ${result.status}`);
494
+ }
495
+ const rows = result.data?.result || [];
496
+ return rows.map((row) => ({
497
+ price: Number(row.price),
498
+ buyVolume: Number(row.buy_volume),
499
+ sellVolume: Number(row.sell_volume)
500
+ }));
501
+ }
502
+ /**
503
+ * Gets the best bid and ask prices for an outcome.
504
+ *
505
+ * @param queryId - Market identifier
506
+ * @param outcome - true=YES, false=NO
507
+ * @returns Best prices and spread
508
+ */
509
+ async getBestPrices(queryId, outcome) {
510
+ const result = await this.kwilClient.call(
511
+ {
512
+ namespace: "main",
513
+ name: "get_best_prices",
514
+ inputs: {
515
+ $query_id: queryId,
516
+ $outcome: outcome
517
+ }
518
+ },
519
+ this.kwilSigner
520
+ );
521
+ if (result.status !== 200) {
522
+ throw new Error(`Failed to get best prices: ${result.status}`);
523
+ }
524
+ const rows = result.data?.result;
525
+ if (!rows || rows.length === 0) {
526
+ return { bestBid: null, bestAsk: null, spread: null };
527
+ }
528
+ const row = rows[0];
529
+ return {
530
+ bestBid: row.best_bid,
531
+ bestAsk: row.best_ask,
532
+ spread: row.spread
533
+ };
534
+ }
535
+ /**
536
+ * Gets the caller's total locked collateral.
537
+ *
538
+ * @returns Collateral breakdown
539
+ */
540
+ async getUserCollateral() {
541
+ const result = await this.kwilClient.call(
542
+ {
543
+ namespace: "main",
544
+ name: "get_user_collateral",
545
+ inputs: {}
546
+ },
547
+ this.kwilSigner
548
+ );
549
+ if (result.status !== 200) {
550
+ throw new Error(`Failed to get user collateral: ${result.status}`);
551
+ }
552
+ const rows = result.data?.result;
553
+ if (!rows || rows.length === 0) {
554
+ return {
555
+ totalLocked: "0",
556
+ buyOrdersLocked: "0",
557
+ sharesValue: "0"
558
+ };
559
+ }
560
+ const row = rows[0];
561
+ return {
562
+ totalLocked: row.total_locked,
563
+ buyOrdersLocked: row.buy_orders_locked,
564
+ sharesValue: row.shares_value
565
+ };
566
+ }
567
+ // ==========================================
568
+ // Settlement & Rewards
569
+ // ==========================================
570
+ /**
571
+ * Settles a market using attestation results.
572
+ *
573
+ * Can only be called after settle_time has passed.
574
+ * Automatically distributes payouts and LP rewards.
575
+ *
576
+ * @param queryId - Market identifier
577
+ * @returns Transaction receipt
578
+ */
579
+ async settleMarket(queryId) {
580
+ return this.kwilClient.execute(
581
+ {
582
+ namespace: "main",
583
+ name: "settle_market",
584
+ inputs: [{ $query_id: queryId }],
585
+ description: "TN SDK - Settle market"
586
+ },
587
+ this.kwilSigner
588
+ );
589
+ }
590
+ /**
591
+ * Samples LP rewards for a specific block.
592
+ *
593
+ * Should be called periodically to track LP eligibility.
594
+ *
595
+ * @param queryId - Market identifier
596
+ * @param block - Block height to sample
597
+ * @returns Transaction receipt
598
+ */
599
+ async sampleLPRewards(queryId, block) {
600
+ return this.kwilClient.execute(
601
+ {
602
+ namespace: "main",
603
+ name: "sample_lp_rewards",
604
+ inputs: [
605
+ {
606
+ $query_id: queryId,
607
+ $block: block
608
+ }
609
+ ],
610
+ description: "TN SDK - Sample LP rewards"
611
+ },
612
+ this.kwilSigner
613
+ );
614
+ }
615
+ /**
616
+ * Gets the fee distribution summary for a market.
617
+ *
618
+ * @param queryId - Market identifier
619
+ * @returns Distribution summary
620
+ */
621
+ async getDistributionSummary(queryId) {
622
+ const result = await this.kwilClient.call(
623
+ {
624
+ namespace: "main",
625
+ name: "get_distribution_summary",
626
+ inputs: { $query_id: queryId }
627
+ },
628
+ this.kwilSigner
629
+ );
630
+ if (result.status !== 200) {
631
+ throw new Error(`Failed to get distribution summary: ${result.status}`);
632
+ }
633
+ const rows = result.data?.result;
634
+ if (!rows || rows.length === 0) {
635
+ throw new Error(`No distribution found for market: ${queryId}`);
636
+ }
637
+ const row = rows[0];
638
+ return {
639
+ distributionId: row.distribution_id,
640
+ queryId: row.query_id,
641
+ totalFees: row.total_fees,
642
+ distributedAt: row.distributed_at
643
+ };
644
+ }
645
+ /**
646
+ * Gets detailed reward breakdown for a distribution.
647
+ *
648
+ * @param distributionId - Distribution identifier
649
+ * @returns Array of per-LP reward details
650
+ */
651
+ async getDistributionDetails(distributionId) {
652
+ const result = await this.kwilClient.call(
653
+ {
654
+ namespace: "main",
655
+ name: "get_distribution_details",
656
+ inputs: { $distribution_id: distributionId }
657
+ },
658
+ this.kwilSigner
659
+ );
660
+ if (result.status !== 200) {
661
+ throw new Error(`Failed to get distribution details: ${result.status}`);
662
+ }
663
+ const rows = result.data?.result || [];
664
+ return rows.map((row) => ({
665
+ walletAddress: (0, import_orderbookHelpers.dbBytesToUint8Array)(row.wallet_address),
666
+ rewardAmount: row.reward_amount,
667
+ sharePercentage: row.share_percentage
668
+ }));
669
+ }
670
+ /**
671
+ * Gets reward history for a participant.
672
+ *
673
+ * @param walletHex - Wallet address (0x-prefixed hex)
674
+ * @returns Array of reward history entries
675
+ */
676
+ async getParticipantRewardHistory(walletHex) {
677
+ const result = await this.kwilClient.call(
678
+ {
679
+ namespace: "main",
680
+ name: "get_participant_reward_history",
681
+ inputs: { $wallet_hex: walletHex }
682
+ },
683
+ this.kwilSigner
684
+ );
685
+ if (result.status !== 200) {
686
+ throw new Error(
687
+ `Failed to get participant reward history: ${result.status}`
688
+ );
689
+ }
690
+ const rows = result.data?.result || [];
691
+ return rows.map((row) => ({
692
+ distributionId: row.distribution_id,
693
+ queryId: row.query_id,
694
+ rewardAmount: row.reward_amount,
695
+ totalRewardPercent: row.total_reward_percent,
696
+ distributedAt: row.distributed_at
697
+ }));
698
+ }
699
+ // ==========================================
700
+ // Binary Market Convenience Creators
701
+ // ==========================================
702
+ /**
703
+ * Creates a "price above threshold" market.
704
+ *
705
+ * YES wins if price > threshold at settlement time.
706
+ *
707
+ * @param input - Market parameters
708
+ * @returns Transaction receipt
709
+ */
710
+ async createPriceAboveThresholdMarket(input) {
711
+ const args = (0, import_orderbookHelpers.encodeActionArgs)(
712
+ input.dataProvider,
713
+ input.streamId,
714
+ input.timestamp,
715
+ input.threshold,
716
+ input.frozenAt
717
+ );
718
+ const queryComponents = (0, import_orderbookHelpers.encodeQueryComponents)(
719
+ input.dataProvider,
720
+ input.streamId,
721
+ "price_above_threshold",
722
+ args
723
+ );
724
+ return this.createMarket({
725
+ bridge: input.bridge,
726
+ queryComponents,
727
+ settleTime: input.settleTime,
728
+ maxSpread: input.maxSpread,
729
+ minOrderSize: input.minOrderSize
730
+ });
731
+ }
732
+ /**
733
+ * Creates a "price below threshold" market.
734
+ *
735
+ * YES wins if price < threshold at settlement time.
736
+ *
737
+ * @param input - Market parameters
738
+ * @returns Transaction receipt
739
+ */
740
+ async createPriceBelowThresholdMarket(input) {
741
+ const args = (0, import_orderbookHelpers.encodeActionArgs)(
742
+ input.dataProvider,
743
+ input.streamId,
744
+ input.timestamp,
745
+ input.threshold,
746
+ input.frozenAt
747
+ );
748
+ const queryComponents = (0, import_orderbookHelpers.encodeQueryComponents)(
749
+ input.dataProvider,
750
+ input.streamId,
751
+ "price_below_threshold",
752
+ args
753
+ );
754
+ return this.createMarket({
755
+ bridge: input.bridge,
756
+ queryComponents,
757
+ settleTime: input.settleTime,
758
+ maxSpread: input.maxSpread,
759
+ minOrderSize: input.minOrderSize
760
+ });
761
+ }
762
+ /**
763
+ * Creates a "value in range" market.
764
+ *
765
+ * YES wins if minValue <= value <= maxValue at settlement time.
766
+ *
767
+ * @param input - Market parameters
768
+ * @returns Transaction receipt
769
+ */
770
+ async createValueInRangeMarket(input) {
771
+ const args = (0, import_orderbookHelpers.encodeRangeActionArgs)(
772
+ input.dataProvider,
773
+ input.streamId,
774
+ input.timestamp,
775
+ input.minValue,
776
+ input.maxValue,
777
+ input.frozenAt
778
+ );
779
+ const queryComponents = (0, import_orderbookHelpers.encodeQueryComponents)(
780
+ input.dataProvider,
781
+ input.streamId,
782
+ "value_in_range",
783
+ args
784
+ );
785
+ return this.createMarket({
786
+ bridge: input.bridge,
787
+ queryComponents,
788
+ settleTime: input.settleTime,
789
+ maxSpread: input.maxSpread,
790
+ minOrderSize: input.minOrderSize
791
+ });
792
+ }
793
+ /**
794
+ * Creates a "value equals" market.
795
+ *
796
+ * YES wins if |value - targetValue| <= tolerance at settlement time.
797
+ *
798
+ * @param input - Market parameters
799
+ * @returns Transaction receipt
800
+ */
801
+ async createValueEqualsMarket(input) {
802
+ const args = (0, import_orderbookHelpers.encodeEqualsActionArgs)(
803
+ input.dataProvider,
804
+ input.streamId,
805
+ input.timestamp,
806
+ input.targetValue,
807
+ input.tolerance,
808
+ input.frozenAt
809
+ );
810
+ const queryComponents = (0, import_orderbookHelpers.encodeQueryComponents)(
811
+ input.dataProvider,
812
+ input.streamId,
813
+ "value_equals",
814
+ args
815
+ );
816
+ return this.createMarket({
817
+ bridge: input.bridge,
818
+ queryComponents,
819
+ settleTime: input.settleTime,
820
+ maxSpread: input.maxSpread,
821
+ minOrderSize: input.minOrderSize
822
+ });
823
+ }
824
+ // ==========================================
825
+ // Static Helper Methods
826
+ // ==========================================
827
+ /**
828
+ * Encodes action arguments for query components.
829
+ * @see encodeActionArgs
830
+ */
831
+ static encodeActionArgs = import_orderbookHelpers.encodeActionArgs;
832
+ /**
833
+ * Encodes query components for market creation.
834
+ * @see encodeQueryComponents
835
+ */
836
+ static encodeQueryComponents = import_orderbookHelpers.encodeQueryComponents;
837
+ /**
838
+ * Encodes action arguments for range markets.
839
+ * @see encodeRangeActionArgs
840
+ */
841
+ static encodeRangeActionArgs = import_orderbookHelpers.encodeRangeActionArgs;
842
+ /**
843
+ * Encodes action arguments for equals markets.
844
+ * @see encodeEqualsActionArgs
845
+ */
846
+ static encodeEqualsActionArgs = import_orderbookHelpers.encodeEqualsActionArgs;
847
+ // ==========================================
848
+ // Private Helper Methods
849
+ // ==========================================
850
+ parseMarketInfo(row, queryId) {
851
+ return {
852
+ // get_market_info doesn't return id, so use the passed queryId if available
853
+ id: queryId ?? Number(row.id),
854
+ hash: (0, import_orderbookHelpers.dbBytesToUint8Array)(row.hash),
855
+ queryComponents: (0, import_orderbookHelpers.dbBytesToUint8Array)(row.query_components),
856
+ bridge: row.bridge,
857
+ settleTime: Number(row.settle_time),
858
+ settled: row.settled,
859
+ winningOutcome: row.winning_outcome,
860
+ settledAt: row.settled_at !== null ? Number(row.settled_at) : null,
861
+ maxSpread: Number(row.max_spread),
862
+ minOrderSize: String(row.min_order_size),
863
+ createdAt: Number(row.created_at),
864
+ creator: (0, import_orderbookHelpers.dbBytesToUint8Array)(row.creator)
865
+ };
866
+ }
867
+ parseMarketSummary(row) {
868
+ return {
869
+ id: Number(row.id),
870
+ hash: (0, import_orderbookHelpers.dbBytesToUint8Array)(row.hash),
871
+ settleTime: Number(row.settle_time),
872
+ settled: row.settled,
873
+ winningOutcome: row.winning_outcome,
874
+ maxSpread: Number(row.max_spread),
875
+ minOrderSize: String(row.min_order_size),
876
+ createdAt: Number(row.created_at)
877
+ };
878
+ }
879
+ };
880
+ //# sourceMappingURL=orderbookAction.cjs.map