@liberfi.io/react-predict 0.1.20 → 0.1.22

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
@@ -108,13 +108,19 @@ var PredictClient = class {
108
108
  // Positions
109
109
  // -------------------------------------------------------------------------
110
110
  /**
111
- * Maps to `GET /api/v1/positions?source=...&user=...`.
111
+ * Maps to `GET /api/v1/positions`.
112
112
  *
113
- * @param user - Wallet address.
114
- * @param source - Provider source. Omit to aggregate all providers.
113
+ * Single-source: `getPositions("addr", "kalshi")`.
114
+ * Multi-wallet: `getPositions({ kalshi_user: "SOLaddr", polymarket_user: "EVMaddr" })`.
115
+ * Legacy agg: `getPositions("addr")` (same address for all providers).
115
116
  */
116
- async getPositions(user, source) {
117
- const query = buildQuery({ source, user });
117
+ async getPositions(userOrWallets, source) {
118
+ let query;
119
+ if (typeof userOrWallets === "string") {
120
+ query = buildQuery({ source, user: userOrWallets });
121
+ } else {
122
+ query = buildQuery(userOrWallets);
123
+ }
118
124
  const url = `${this.endpoint}/api/v1/positions${query}`;
119
125
  return await utils.httpGet(url);
120
126
  }
@@ -137,23 +143,46 @@ var PredictClient = class {
137
143
  // -------------------------------------------------------------------------
138
144
  // Orders
139
145
  // -------------------------------------------------------------------------
140
- /** Maps to `GET /api/v1/orders?source=...&wallet_address=...`. */
141
- async listOrders(params) {
146
+ /**
147
+ * Maps to `GET /api/v1/orders?source=...&wallet_address=...`.
148
+ *
149
+ * @param params - Query parameters (source, wallet_address, etc.).
150
+ * @param headers - Optional extra headers (e.g. Polymarket POLY_* HMAC headers).
151
+ */
152
+ async listOrders(params, headers) {
142
153
  const query = buildQuery(params);
143
154
  const url = `${this.endpoint}/api/v1/orders${query}`;
144
- return await utils.httpGet(url);
155
+ return await utils.httpGet(
156
+ url,
157
+ headers ? { headers } : void 0
158
+ );
145
159
  }
146
- /** Maps to `GET /api/v1/orders/:id?source=...`. */
147
- async getOrder(id, source) {
160
+ /**
161
+ * Maps to `GET /api/v1/orders/:id?source=...`.
162
+ *
163
+ * @param id - Order ID.
164
+ * @param source - Provider source.
165
+ * @param headers - Optional extra headers (e.g. Polymarket POLY_* HMAC headers).
166
+ */
167
+ async getOrder(id, source, headers) {
148
168
  const query = buildQuery({ source });
149
169
  const url = `${this.endpoint}/api/v1/orders/${encodeURIComponent(id)}${query}`;
150
- return await utils.httpGet(url);
170
+ return await utils.httpGet(url, headers ? { headers } : void 0);
151
171
  }
152
- /** Maps to `DELETE /api/v1/orders/:id?source=...`. */
153
- async cancelOrder(id, source) {
172
+ /**
173
+ * Maps to `DELETE /api/v1/orders/:id?source=...`.
174
+ *
175
+ * @param id - Order ID.
176
+ * @param source - Provider source.
177
+ * @param headers - Optional extra headers (e.g. Polymarket POLY_* HMAC headers).
178
+ */
179
+ async cancelOrder(id, source, headers) {
154
180
  const query = buildQuery({ source });
155
181
  const url = `${this.endpoint}/api/v1/orders/${encodeURIComponent(id)}${query}`;
156
- return await utils.httpDelete(url);
182
+ return await utils.httpDelete(
183
+ url,
184
+ headers ? { headers } : void 0
185
+ );
157
186
  }
158
187
  // -------------------------------------------------------------------------
159
188
  // Polymarket trading
@@ -203,6 +232,30 @@ var PredictClient = class {
203
232
  return await utils.httpGet(url);
204
233
  }
205
234
  // -------------------------------------------------------------------------
235
+ // Polymarket wallet setup
236
+ // -------------------------------------------------------------------------
237
+ /**
238
+ * Check Polymarket wallet setup status (Safe deployed + USDC.e approved).
239
+ *
240
+ * Maps to `GET /api/v1/setup/polymarket?wallet_address=...`.
241
+ */
242
+ async checkPolymarketSetup(walletAddress) {
243
+ const query = buildQuery({ wallet_address: walletAddress });
244
+ const url = `${this.endpoint}/api/v1/setup/polymarket${query}`;
245
+ return await utils.httpGet(url);
246
+ }
247
+ /**
248
+ * Run Polymarket wallet setup (deploy Safe + approve USDC.e).
249
+ *
250
+ * Maps to `POST /api/v1/setup/polymarket`.
251
+ */
252
+ async runPolymarketSetup(walletAddress) {
253
+ const url = `${this.endpoint}/api/v1/setup/polymarket`;
254
+ return await utils.httpPost(url, {
255
+ wallet_address: walletAddress
256
+ });
257
+ }
258
+ // -------------------------------------------------------------------------
206
259
  // Cross-platform matches
207
260
  // -------------------------------------------------------------------------
208
261
  /**
@@ -224,6 +277,16 @@ var PredictClient = class {
224
277
  const url = `${this.endpoint}/api/v1/matches/${id}`;
225
278
  return await utils.httpGet(url);
226
279
  }
280
+ /**
281
+ * List flattened market pairs across match groups (market-level granularity).
282
+ *
283
+ * Maps to `GET /api/v1/matches/markets`.
284
+ */
285
+ async listMatchMarkets(params) {
286
+ const query = buildQuery(params ?? {});
287
+ const url = `${this.endpoint}/api/v1/matches/markets${query}`;
288
+ return await utils.httpGet(url);
289
+ }
227
290
  // -------------------------------------------------------------------------
228
291
  // Trades by wallet
229
292
  // -------------------------------------------------------------------------
@@ -233,6 +296,73 @@ var PredictClient = class {
233
296
  const url = `${this.endpoint}/api/v1/trades${query}`;
234
297
  return await utils.httpGet(url);
235
298
  }
299
+ // -------------------------------------------------------------------------
300
+ // Withdraw
301
+ // -------------------------------------------------------------------------
302
+ /** Maps to `POST /api/v1/withdraw/build`. */
303
+ async withdrawBuild(body) {
304
+ const url = `${this.endpoint}/api/v1/withdraw/build`;
305
+ return await utils.httpPost(url, body);
306
+ }
307
+ /** Maps to `POST /api/v1/withdraw/submit`. */
308
+ async withdrawSubmit(body) {
309
+ const url = `${this.endpoint}/api/v1/withdraw/submit`;
310
+ return await utils.httpPost(url, body);
311
+ }
312
+ /** Maps to `GET /api/v1/withdraw/status?tx_hash=...&source=...`. */
313
+ async withdrawStatus(txHash, source) {
314
+ const query = buildQuery({ tx_hash: txHash, source });
315
+ const url = `${this.endpoint}/api/v1/withdraw/status${query}`;
316
+ return await utils.httpGet(url);
317
+ }
318
+ // -------------------------------------------------------------------------
319
+ // Deposit (native USDC → USDC.e for Polymarket)
320
+ // -------------------------------------------------------------------------
321
+ /**
322
+ * Build unsigned deposit transactions (approve + Uniswap V3 swap).
323
+ *
324
+ * The server checks the Safe's USDC.e balance and returns only
325
+ * the transactions needed to cover the shortfall.
326
+ *
327
+ * Maps to `POST /api/v1/deposit/polymarket/build`.
328
+ */
329
+ async depositBuild(body) {
330
+ const url = `${this.endpoint}/api/v1/deposit/polymarket/build`;
331
+ return await utils.httpPost(url, body);
332
+ }
333
+ /** Maps to `POST /api/v1/deposit/polymarket/submit`. */
334
+ async depositSubmit(body) {
335
+ const url = `${this.endpoint}/api/v1/deposit/polymarket/submit`;
336
+ return await utils.httpPost(url, body);
337
+ }
338
+ /** Maps to `GET /api/v1/deposit/polymarket/status?tx_hash=...&source=...`. */
339
+ async depositStatus(txHash, source) {
340
+ const query = buildQuery({ tx_hash: txHash, source });
341
+ const url = `${this.endpoint}/api/v1/deposit/polymarket/status${query}`;
342
+ return await utils.httpGet(url);
343
+ }
344
+ /**
345
+ * Get multi-chain deposit addresses for a Polymarket Safe wallet via Bridge API.
346
+ *
347
+ * Maps to `GET /api/v1/deposit/polymarket/addresses?safe_address=...`.
348
+ */
349
+ async getPolymarketDepositAddresses(safeAddress) {
350
+ const query = buildQuery({ safe_address: safeAddress });
351
+ const url = `${this.endpoint}/api/v1/deposit/polymarket/addresses${query}`;
352
+ return await utils.httpGet(url);
353
+ }
354
+ // -------------------------------------------------------------------------
355
+ // Polymarket Relayer Withdraw
356
+ // -------------------------------------------------------------------------
357
+ /**
358
+ * Execute a gasless USDC.e withdrawal from a Polymarket Safe wallet via Relayer.
359
+ *
360
+ * Maps to `POST /api/v1/withdraw/polymarket/execute`.
361
+ */
362
+ async executePolymarketWithdraw(body) {
363
+ const url = `${this.endpoint}/api/v1/withdraw/polymarket/execute`;
364
+ return await utils.httpPost(url, body);
365
+ }
236
366
  };
237
367
  function createPredictClient(endpoint) {
238
368
  return new PredictClient(endpoint);
@@ -587,7 +717,9 @@ function encode(str) {
587
717
  return new TextEncoder().encode(str);
588
718
  }
589
719
  function base64ToBytes(b64) {
590
- const binary = atob(b64);
720
+ let std = b64.replace(/-/g, "+").replace(/_/g, "/");
721
+ while (std.length % 4 !== 0) std += "=";
722
+ const binary = atob(std);
591
723
  const bytes = new Uint8Array(binary.length);
592
724
  for (let i = 0; i < binary.length; i++) {
593
725
  bytes[i] = binary.charCodeAt(i);
@@ -616,7 +748,8 @@ async function hmacSha256Base64(secretBase64, message) {
616
748
  cryptoKey,
617
749
  msgBytes.buffer
618
750
  );
619
- return bytesToBase64(new Uint8Array(signature));
751
+ const b64 = bytesToBase64(new Uint8Array(signature));
752
+ return b64.replace(/\+/g, "-").replace(/\//g, "_");
620
753
  }
621
754
  async function buildPolymarketL2Headers(address, input) {
622
755
  const timestamp = Math.floor(Date.now() / 1e3).toString();
@@ -652,27 +785,34 @@ function buildClobAuthMessage(input) {
652
785
  message: "This message attests that I control the given wallet"
653
786
  };
654
787
  }
788
+ function buildL1Headers(address, signature, timestamp, nonce) {
789
+ return {
790
+ POLY_ADDRESS: address,
791
+ POLY_SIGNATURE: signature,
792
+ POLY_TIMESTAMP: timestamp,
793
+ POLY_NONCE: String(nonce)
794
+ };
795
+ }
655
796
  async function derivePolymarketApiKey(address, signature, timestamp, nonce) {
656
- const res = await fetch(
797
+ const headers = buildL1Headers(address, signature, timestamp, nonce);
798
+ const deriveRes = await fetch(
657
799
  `https://clob.polymarket.com/auth/derive-api-key?nonce=${nonce}`,
658
- {
659
- method: "GET",
660
- headers: {
661
- "Content-Type": "application/json",
662
- POLY_ADDRESS: address,
663
- POLY_SIGNATURE: signature,
664
- POLY_TIMESTAMP: timestamp,
665
- POLY_NONCE: String(nonce)
666
- }
667
- }
800
+ { method: "GET", headers }
668
801
  );
669
- if (!res.ok) {
670
- const text = await res.text().catch(() => res.statusText);
671
- throw new Error(
672
- `Polymarket credential exchange failed (${res.status}): ${text}`
673
- );
802
+ if (deriveRes.ok) {
803
+ return deriveRes.json();
674
804
  }
675
- return res.json();
805
+ const createRes = await fetch("https://clob.polymarket.com/auth/api-key", {
806
+ method: "POST",
807
+ headers
808
+ });
809
+ if (createRes.ok) {
810
+ return createRes.json();
811
+ }
812
+ const text = await createRes.text().catch(() => createRes.statusText);
813
+ throw new Error(
814
+ `Polymarket credential exchange failed (${createRes.status}): ${text}`
815
+ );
676
816
  }
677
817
  var PolymarketContext = react.createContext(
678
818
  null
@@ -687,7 +827,7 @@ function PolymarketProvider({ children }) {
687
827
  const authenticate = react.useCallback(
688
828
  async (signer) => {
689
829
  if (lastAuthAddressRef.current === signer.address && credentials !== null) {
690
- return;
830
+ return credentials;
691
831
  }
692
832
  setIsAuthenticating(true);
693
833
  setAuthError(null);
@@ -702,6 +842,7 @@ function PolymarketProvider({ children }) {
702
842
  const signature = await signer.signTypedData(
703
843
  CLOB_AUTH_DOMAIN,
704
844
  CLOB_AUTH_TYPES,
845
+ "ClobAuth",
705
846
  message
706
847
  );
707
848
  const { apiKey, secret, passphrase } = await derivePolymarketApiKey(
@@ -710,13 +851,21 @@ function PolymarketProvider({ children }) {
710
851
  timestamp,
711
852
  nonce
712
853
  );
854
+ const newCreds = {
855
+ apiKey,
856
+ secret,
857
+ passphrase,
858
+ address: signer.address
859
+ };
713
860
  lastAuthAddressRef.current = signer.address;
714
- setCredentials({ apiKey, secret, passphrase, address: signer.address });
861
+ setCredentials(newCreds);
862
+ return newCreds;
715
863
  } catch (err) {
716
864
  setAuthError(
717
865
  err instanceof Error ? err : new Error("Polymarket authentication failed")
718
866
  );
719
867
  lastAuthAddressRef.current = null;
868
+ throw err;
720
869
  } finally {
721
870
  setIsAuthenticating(false);
722
871
  }
@@ -1028,6 +1177,15 @@ function useCandlesticks(params, queryOptions = {}) {
1028
1177
  function positionsQueryKey(user, source) {
1029
1178
  return ["predict", "positions", source ?? "all", user];
1030
1179
  }
1180
+ function positionsMultiQueryKey(wallets) {
1181
+ return [
1182
+ "predict",
1183
+ "positions",
1184
+ "multi",
1185
+ wallets.kalshi_user ?? "",
1186
+ wallets.polymarket_user ?? ""
1187
+ ];
1188
+ }
1031
1189
  function usePositions(params, queryOptions = {}) {
1032
1190
  const client = usePredictClient();
1033
1191
  return reactQuery.useQuery({
@@ -1038,6 +1196,17 @@ function usePositions(params, queryOptions = {}) {
1038
1196
  ...queryOptions
1039
1197
  });
1040
1198
  }
1199
+ function usePositionsMulti(params, queryOptions = {}) {
1200
+ const client = usePredictClient();
1201
+ const hasAnyWallet = Boolean(params.kalshi_user || params.polymarket_user);
1202
+ return reactQuery.useQuery({
1203
+ queryKey: positionsMultiQueryKey(params),
1204
+ queryFn: () => client.getPositions(params),
1205
+ enabled: hasAnyWallet,
1206
+ staleTime: 1e4,
1207
+ ...queryOptions
1208
+ });
1209
+ }
1041
1210
  function balanceQueryKey(source, user) {
1042
1211
  return ["predict", "balance", source, user];
1043
1212
  }
@@ -1054,11 +1223,14 @@ function useBalance(params, queryOptions = {}) {
1054
1223
  function ordersQueryKey(params) {
1055
1224
  return ["predict", "orders", params];
1056
1225
  }
1057
- function useOrders(params, queryOptions = {}) {
1226
+ function useOrders(params, options, queryOptions = {}) {
1058
1227
  const client = usePredictClient();
1059
1228
  return reactQuery.useQuery({
1060
1229
  queryKey: ordersQueryKey(params),
1061
- queryFn: () => client.listOrders(params),
1230
+ queryFn: async () => {
1231
+ const headers = await options?.getHeaders?.();
1232
+ return client.listOrders(params, headers);
1233
+ },
1062
1234
  enabled: Boolean(params.wallet_address),
1063
1235
  ...queryOptions
1064
1236
  });
@@ -1066,11 +1238,14 @@ function useOrders(params, queryOptions = {}) {
1066
1238
  function infiniteOrdersQueryKey(params) {
1067
1239
  return ["predict", "orders", "infinite", params];
1068
1240
  }
1069
- function useInfiniteOrders(params) {
1241
+ function useInfiniteOrders(params, options) {
1070
1242
  const client = usePredictClient();
1071
1243
  return reactQuery.useInfiniteQuery({
1072
1244
  queryKey: infiniteOrdersQueryKey(params),
1073
- queryFn: ({ pageParam }) => client.listOrders({ ...params, next_cursor: pageParam }),
1245
+ queryFn: async ({ pageParam }) => {
1246
+ const headers = await options?.getHeaders?.();
1247
+ return client.listOrders({ ...params, next_cursor: pageParam }, headers);
1248
+ },
1074
1249
  initialPageParam: void 0,
1075
1250
  getNextPageParam: (lastPage) => lastPage.has_more ? lastPage.next_cursor : void 0,
1076
1251
  enabled: Boolean(params.wallet_address)
@@ -1136,6 +1311,34 @@ function useMatch(id, queryOptions = {}) {
1136
1311
  ...queryOptions
1137
1312
  });
1138
1313
  }
1314
+
1315
+ // src/hooks/predict/matchMarkets.params.ts
1316
+ function matchMarketsQueryKey(params) {
1317
+ return ["predict", "matchMarkets", params];
1318
+ }
1319
+ async function fetchMatchMarketsPage(client, params) {
1320
+ return client.listMatchMarkets(params);
1321
+ }
1322
+
1323
+ // src/hooks/predict/useMatchMarkets.ts
1324
+ function useInfiniteMatchMarkets(params, queryOptions = {}) {
1325
+ const client = usePredictClient();
1326
+ const limit = params.limit ?? 20;
1327
+ return reactQuery.useInfiniteQuery({
1328
+ queryKey: matchMarketsQueryKey(params),
1329
+ queryFn: ({ pageParam }) => fetchMatchMarketsPage(client, {
1330
+ ...params,
1331
+ limit,
1332
+ offset: pageParam
1333
+ }),
1334
+ initialPageParam: 0,
1335
+ getNextPageParam: (lastPage) => {
1336
+ const nextOffset = lastPage.offset + lastPage.items.length;
1337
+ return nextOffset < lastPage.total ? nextOffset : void 0;
1338
+ },
1339
+ ...queryOptions
1340
+ });
1341
+ }
1139
1342
  function tradesQueryKey(params) {
1140
1343
  return ["predict", "trades-by-wallet", params];
1141
1344
  }
@@ -1200,6 +1403,149 @@ function useDFlowKYC(walletAddress, queryOptions = {}) {
1200
1403
  ...queryOptions
1201
1404
  });
1202
1405
  }
1406
+ function polymarketSetupQueryKey(walletAddress) {
1407
+ return ["predict", "setup", "polymarket", walletAddress];
1408
+ }
1409
+ function usePolymarketSetup(walletAddress, queryOptions = {}) {
1410
+ const client = usePredictClient();
1411
+ return reactQuery.useQuery({
1412
+ queryKey: polymarketSetupQueryKey(walletAddress ?? ""),
1413
+ queryFn: () => client.checkPolymarketSetup(walletAddress),
1414
+ enabled: !!walletAddress,
1415
+ staleTime: 6e4,
1416
+ ...queryOptions
1417
+ });
1418
+ }
1419
+ function useRunPolymarketSetup(walletAddress) {
1420
+ const client = usePredictClient();
1421
+ const queryClient = reactQuery.useQueryClient();
1422
+ return reactQuery.useMutation({
1423
+ mutationFn: (address) => client.runPolymarketSetup(address),
1424
+ onSuccess: () => {
1425
+ if (walletAddress) {
1426
+ queryClient.invalidateQueries({
1427
+ queryKey: polymarketSetupQueryKey(walletAddress)
1428
+ });
1429
+ }
1430
+ }
1431
+ });
1432
+ }
1433
+ function useWithdrawBuildMutation(mutationOptions = {}) {
1434
+ const client = usePredictClient();
1435
+ return reactQuery.useMutation({
1436
+ mutationFn: (body) => client.withdrawBuild(body),
1437
+ ...mutationOptions
1438
+ });
1439
+ }
1440
+ function useWithdrawSubmitMutation(mutationOptions = {}) {
1441
+ const client = usePredictClient();
1442
+ const queryClient = reactQuery.useQueryClient();
1443
+ return reactQuery.useMutation({
1444
+ mutationFn: (body) => client.withdrawSubmit(body),
1445
+ onSuccess: () => {
1446
+ queryClient.invalidateQueries({ queryKey: ["predict", "balance"] });
1447
+ queryClient.invalidateQueries({ queryKey: ["predict", "positions"] });
1448
+ },
1449
+ ...mutationOptions
1450
+ });
1451
+ }
1452
+ function withdrawStatusQueryKey(txHash, source) {
1453
+ return ["predict", "withdraw", "status", txHash, source];
1454
+ }
1455
+ function useWithdrawStatusQuery(params, queryOptions = {}) {
1456
+ const client = usePredictClient();
1457
+ const { txHash, source } = params;
1458
+ return reactQuery.useQuery({
1459
+ queryKey: withdrawStatusQueryKey(txHash ?? "", source),
1460
+ queryFn: () => client.withdrawStatus(txHash, source),
1461
+ enabled: Boolean(txHash && source),
1462
+ refetchInterval: (query) => {
1463
+ const status = query.state.data?.status;
1464
+ if (status === "confirmed" || status === "failed") return false;
1465
+ return 3e3;
1466
+ },
1467
+ ...queryOptions
1468
+ });
1469
+ }
1470
+ var TX_POLL_INTERVAL = 3e3;
1471
+ var TX_POLL_MAX_ATTEMPTS = 60;
1472
+ function usePolymarketDeposit(mutationOptions = {}) {
1473
+ const client = usePredictClient();
1474
+ const queryClient = reactQuery.useQueryClient();
1475
+ return reactQuery.useMutation({
1476
+ mutationFn: async ({
1477
+ from,
1478
+ safeAddress,
1479
+ amount,
1480
+ signTransaction
1481
+ }) => {
1482
+ const buildResult = await client.depositBuild({
1483
+ source: "polymarket",
1484
+ from,
1485
+ safe_address: safeAddress,
1486
+ amount
1487
+ });
1488
+ if (buildResult.transactions.length === 0) {
1489
+ return {
1490
+ deposited: false,
1491
+ txCount: 0,
1492
+ shortfall: buildResult.shortfall,
1493
+ safeBalance: buildResult.safe_balance
1494
+ };
1495
+ }
1496
+ for (const unsignedTx of buildResult.transactions) {
1497
+ const signedHex = await signTransaction(unsignedTx.params);
1498
+ const submitResult = await client.depositSubmit({
1499
+ source: "polymarket",
1500
+ signed_tx: signedHex
1501
+ });
1502
+ await pollTxUntilConfirmed(client, submitResult.tx_hash);
1503
+ }
1504
+ return {
1505
+ deposited: true,
1506
+ txCount: buildResult.transactions.length,
1507
+ shortfall: buildResult.shortfall,
1508
+ safeBalance: buildResult.safe_balance
1509
+ };
1510
+ },
1511
+ onSuccess: () => {
1512
+ queryClient.invalidateQueries({ queryKey: ["predict", "balance"] });
1513
+ },
1514
+ ...mutationOptions
1515
+ });
1516
+ }
1517
+ async function pollTxUntilConfirmed(client, txHash) {
1518
+ for (let i = 0; i < TX_POLL_MAX_ATTEMPTS; i++) {
1519
+ await sleep(TX_POLL_INTERVAL);
1520
+ const result = await client.depositStatus(txHash, "polymarket");
1521
+ if (result.status === "confirmed") return;
1522
+ if (result.status === "failed") {
1523
+ throw new Error(`Deposit transaction failed: ${txHash}`);
1524
+ }
1525
+ }
1526
+ throw new Error(
1527
+ `Deposit transaction timed out after ${TX_POLL_MAX_ATTEMPTS * TX_POLL_INTERVAL / 1e3}s: ${txHash}`
1528
+ );
1529
+ }
1530
+ function sleep(ms) {
1531
+ return new Promise((resolve) => setTimeout(resolve, ms));
1532
+ }
1533
+ var polymarketDepositAddressesQueryKey = (safeAddress) => ["polymarket", "deposit-addresses", safeAddress];
1534
+ function usePolymarketDepositAddresses(safeAddress) {
1535
+ const client = usePredictClient();
1536
+ return reactQuery.useQuery({
1537
+ queryKey: polymarketDepositAddressesQueryKey(safeAddress ?? ""),
1538
+ queryFn: () => client.getPolymarketDepositAddresses(safeAddress),
1539
+ enabled: !!safeAddress,
1540
+ staleTime: 5 * 60 * 1e3
1541
+ });
1542
+ }
1543
+ function usePolymarketWithdraw() {
1544
+ const client = usePredictClient();
1545
+ return reactQuery.useMutation({
1546
+ mutationFn: (req) => client.executePolymarketWithdraw(req)
1547
+ });
1548
+ }
1203
1549
  function usePredictWsClient() {
1204
1550
  const context = react.useContext(PredictContext);
1205
1551
  if (!context) {
@@ -1448,7 +1794,7 @@ var USDC_ADDRESS = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174";
1448
1794
  var POLYGON_CHAIN_ID = 137;
1449
1795
  function buildCtfExchangeDomain(negRisk = false) {
1450
1796
  return {
1451
- name: "CTFExchange",
1797
+ name: "Polymarket CTF Exchange",
1452
1798
  version: "1",
1453
1799
  chainId: POLYGON_CHAIN_ID,
1454
1800
  verifyingContract: negRisk ? NEG_RISK_CTF_EXCHANGE_ADDRESS : CTF_EXCHANGE_ADDRESS
@@ -1494,6 +1840,12 @@ function roundToTick(price, tickSize) {
1494
1840
  function toMicroUsdc(amount) {
1495
1841
  return BigInt(Math.round(amount * 1e6));
1496
1842
  }
1843
+ function normalizeTokenId(tokenId) {
1844
+ if (tokenId.startsWith("0x") || tokenId.startsWith("0X")) {
1845
+ return BigInt(tokenId).toString(10);
1846
+ }
1847
+ return tokenId;
1848
+ }
1497
1849
  function buildOrderMessage(input) {
1498
1850
  const side = input.side === "BUY" ? SIDE.BUY : SIDE.SELL;
1499
1851
  const priceStr = roundToTick(input.price, input.tickSize);
@@ -1508,7 +1860,7 @@ function buildOrderMessage(input) {
1508
1860
  maker,
1509
1861
  signer: input.signerAddress,
1510
1862
  taker: "0x0000000000000000000000000000000000000000",
1511
- tokenId: input.tokenId,
1863
+ tokenId: normalizeTokenId(input.tokenId),
1512
1864
  makerAmount,
1513
1865
  takerAmount,
1514
1866
  expiration: String(input.expiration ?? 0),
@@ -1518,16 +1870,30 @@ function buildOrderMessage(input) {
1518
1870
  signatureType: input.signatureType
1519
1871
  };
1520
1872
  }
1521
- function buildSignedOrder(input) {
1522
- const message = buildOrderMessage(input);
1873
+ function buildSignedOrder(orderMessage, signature, orderType) {
1523
1874
  return {
1524
- ...message,
1525
- signature: input.signature,
1526
- orderType: input.orderType ?? "GTC"
1875
+ ...orderMessage,
1876
+ signature,
1877
+ orderType: orderType ?? "GTC"
1878
+ };
1879
+ }
1880
+ function buildClobPayload(signedOrder, owner) {
1881
+ const { orderType: ot, ...order } = signedOrder;
1882
+ return {
1883
+ order: {
1884
+ ...order,
1885
+ salt: parseInt(order.salt, 10),
1886
+ side: order.side === SIDE.BUY ? "BUY" : "SELL"
1887
+ },
1888
+ owner,
1889
+ orderType: ot ?? "GTC",
1890
+ deferExec: false
1527
1891
  };
1528
1892
  }
1529
1893
 
1530
1894
  // src/hooks/polymarket/useCreatePolymarketOrder.ts
1895
+ var TX_POLL_INTERVAL2 = 3e3;
1896
+ var TX_POLL_MAX_ATTEMPTS2 = 60;
1531
1897
  function useCreatePolymarketOrder(mutationOptions = {}) {
1532
1898
  const client = usePredictClient();
1533
1899
  const { credentials, authenticate } = usePolymarket();
@@ -1537,13 +1903,27 @@ function useCreatePolymarketOrder(mutationOptions = {}) {
1537
1903
  input,
1538
1904
  signer
1539
1905
  }) => {
1540
- const creds = credentials;
1541
- if (!creds) {
1542
- await authenticate(signer);
1543
- if (!creds) {
1544
- throw new Error(
1545
- "Polymarket authentication failed. Cannot create order without credentials."
1546
- );
1906
+ const creds = credentials ?? await authenticate(signer);
1907
+ if (signer.signTransaction && input.funderAddress) {
1908
+ const orderCost = computeOrderCost(input);
1909
+ const buildResult = await client.depositBuild({
1910
+ source: "polymarket",
1911
+ from: signer.address,
1912
+ safe_address: input.funderAddress,
1913
+ amount: orderCost
1914
+ });
1915
+ if (buildResult.transactions.length > 0) {
1916
+ for (const unsignedTx of buildResult.transactions) {
1917
+ const signedHex = await signer.signTransaction(unsignedTx.params);
1918
+ const submitResult = await client.depositSubmit({
1919
+ source: "polymarket",
1920
+ signed_tx: signedHex
1921
+ });
1922
+ await pollTxConfirmed(
1923
+ (txHash) => client.depositStatus(txHash, "polymarket"),
1924
+ submitResult.tx_hash
1925
+ );
1926
+ }
1547
1927
  }
1548
1928
  }
1549
1929
  const domain = buildCtfExchangeDomain(input.negRisk ?? false);
@@ -1555,35 +1935,54 @@ function useCreatePolymarketOrder(mutationOptions = {}) {
1555
1935
  const signature = await signer.signTypedData(
1556
1936
  domain,
1557
1937
  CTF_ORDER_TYPES,
1938
+ "Order",
1558
1939
  orderMessage
1559
1940
  );
1560
- const signedOrder = buildSignedOrder({
1561
- ...input,
1562
- signerAddress: signer.address,
1563
- signatureType: signer.signatureType,
1564
- signature
1565
- });
1566
- const body = JSON.stringify(signedOrder);
1941
+ const signedOrder = buildSignedOrder(
1942
+ orderMessage,
1943
+ signature,
1944
+ input.orderType
1945
+ );
1946
+ const clobPayload = buildClobPayload(signedOrder, creds.apiKey);
1947
+ const body = JSON.stringify(clobPayload);
1567
1948
  const headers = await buildPolymarketL2Headers(creds.address, {
1568
1949
  apiKey: creds.apiKey,
1569
1950
  secret: creds.secret,
1570
1951
  passphrase: creds.passphrase,
1571
1952
  method: "POST",
1572
- requestPath: "/api/v1/orders/polymarket",
1953
+ requestPath: "/order",
1573
1954
  body
1574
1955
  });
1575
1956
  return client.createPolymarketOrder(
1576
- signedOrder,
1957
+ clobPayload,
1577
1958
  headers
1578
1959
  );
1579
1960
  },
1580
1961
  onSuccess: () => {
1581
1962
  queryClient.invalidateQueries({ queryKey: ["predict", "orders"] });
1582
1963
  queryClient.invalidateQueries({ queryKey: ["predict", "positions"] });
1964
+ queryClient.invalidateQueries({ queryKey: ["predict", "balance"] });
1583
1965
  },
1584
1966
  ...mutationOptions
1585
1967
  });
1586
1968
  }
1969
+ function computeOrderCost(input) {
1970
+ if (input.side === "SELL") return "0";
1971
+ return (input.price * input.size).toFixed(6);
1972
+ }
1973
+ async function pollTxConfirmed(fetchStatus, txHash) {
1974
+ for (let i = 0; i < TX_POLL_MAX_ATTEMPTS2; i++) {
1975
+ await new Promise((r) => setTimeout(r, TX_POLL_INTERVAL2));
1976
+ const result = await fetchStatus(txHash);
1977
+ if (result.status === "confirmed") return;
1978
+ if (result.status === "failed") {
1979
+ throw new Error(`Deposit transaction failed: ${txHash}`);
1980
+ }
1981
+ }
1982
+ throw new Error(
1983
+ `Deposit transaction timed out after ${TX_POLL_MAX_ATTEMPTS2 * TX_POLL_INTERVAL2 / 1e3}s: ${txHash}`
1984
+ );
1985
+ }
1587
1986
 
1588
1987
  exports.CLOB_AUTH_DOMAIN = CLOB_AUTH_DOMAIN;
1589
1988
  exports.CLOB_AUTH_TYPES = CLOB_AUTH_TYPES;
@@ -1603,6 +2002,7 @@ exports.SIDE = SIDE;
1603
2002
  exports.USDC_ADDRESS = USDC_ADDRESS;
1604
2003
  exports.balanceQueryKey = balanceQueryKey;
1605
2004
  exports.buildClobAuthMessage = buildClobAuthMessage;
2005
+ exports.buildClobPayload = buildClobPayload;
1606
2006
  exports.buildCtfExchangeDomain = buildCtfExchangeDomain;
1607
2007
  exports.buildOrderMessage = buildOrderMessage;
1608
2008
  exports.buildPolymarketL2Headers = buildPolymarketL2Headers;
@@ -1619,6 +2019,7 @@ exports.fetchEvent = fetchEvent;
1619
2019
  exports.fetchEvents = fetchEvents;
1620
2020
  exports.fetchEventsPage = fetchEventsPage;
1621
2021
  exports.fetchMarket = fetchMarket;
2022
+ exports.fetchMatchMarketsPage = fetchMatchMarketsPage;
1622
2023
  exports.fetchMatchesPage = fetchMatchesPage;
1623
2024
  exports.hmacSha256Base64 = hmacSha256Base64;
1624
2025
  exports.infiniteEventsQueryKey = infiniteEventsQueryKey;
@@ -1626,11 +2027,15 @@ exports.infiniteOrdersQueryKey = infiniteOrdersQueryKey;
1626
2027
  exports.infiniteTradesQueryKey = infiniteTradesQueryKey;
1627
2028
  exports.marketQueryKey = marketQueryKey;
1628
2029
  exports.marketTradesQueryKey = marketTradesQueryKey;
2030
+ exports.matchMarketsQueryKey = matchMarketsQueryKey;
1629
2031
  exports.matchQueryKey = matchQueryKey;
1630
2032
  exports.matchesQueryKey = matchesQueryKey;
1631
2033
  exports.orderQueryKey = orderQueryKey;
1632
2034
  exports.orderbookQueryKey = orderbookQueryKey;
1633
2035
  exports.ordersQueryKey = ordersQueryKey;
2036
+ exports.polymarketDepositAddressesQueryKey = polymarketDepositAddressesQueryKey;
2037
+ exports.polymarketSetupQueryKey = polymarketSetupQueryKey;
2038
+ exports.positionsMultiQueryKey = positionsMultiQueryKey;
1634
2039
  exports.positionsQueryKey = positionsQueryKey;
1635
2040
  exports.priceHistoryQueryKey = priceHistoryQueryKey;
1636
2041
  exports.resolveEventsParams = resolveEventsParams;
@@ -1647,6 +2052,7 @@ exports.useDFlowSubmit = useDFlowSubmit;
1647
2052
  exports.useEvent = useEvent;
1648
2053
  exports.useEvents = useEvents;
1649
2054
  exports.useInfiniteEvents = useInfiniteEvents;
2055
+ exports.useInfiniteMatchMarkets = useInfiniteMatchMarkets;
1650
2056
  exports.useInfiniteMatches = useInfiniteMatches;
1651
2057
  exports.useInfiniteOrders = useInfiniteOrders;
1652
2058
  exports.useInfiniteTrades = useInfiniteTrades;
@@ -1659,7 +2065,12 @@ exports.useOrderbook = useOrderbook;
1659
2065
  exports.useOrderbookSubscription = useOrderbookSubscription;
1660
2066
  exports.useOrders = useOrders;
1661
2067
  exports.usePolymarket = usePolymarket;
2068
+ exports.usePolymarketDeposit = usePolymarketDeposit;
2069
+ exports.usePolymarketDepositAddresses = usePolymarketDepositAddresses;
2070
+ exports.usePolymarketSetup = usePolymarketSetup;
2071
+ exports.usePolymarketWithdraw = usePolymarketWithdraw;
1662
2072
  exports.usePositions = usePositions;
2073
+ exports.usePositionsMulti = usePositionsMulti;
1663
2074
  exports.usePredictClient = usePredictClient;
1664
2075
  exports.usePredictWsClient = usePredictWsClient;
1665
2076
  exports.usePriceHistory = usePriceHistory;
@@ -1667,9 +2078,14 @@ exports.usePricesSubscription = usePricesSubscription;
1667
2078
  exports.useRealtimeOrderbook = useRealtimeOrderbook;
1668
2079
  exports.useRealtimePrices = useRealtimePrices;
1669
2080
  exports.useRealtimeTrades = useRealtimeTrades;
2081
+ exports.useRunPolymarketSetup = useRunPolymarketSetup;
1670
2082
  exports.useSearchEvents = useSearchEvents;
1671
2083
  exports.useSimilarEvents = useSimilarEvents;
1672
2084
  exports.useTrades = useTrades;
1673
2085
  exports.useTradesSubscription = useTradesSubscription;
2086
+ exports.useWithdrawBuildMutation = useWithdrawBuildMutation;
2087
+ exports.useWithdrawStatusQuery = useWithdrawStatusQuery;
2088
+ exports.useWithdrawSubmitMutation = useWithdrawSubmitMutation;
2089
+ exports.withdrawStatusQueryKey = withdrawStatusQueryKey;
1674
2090
  //# sourceMappingURL=index.js.map
1675
2091
  //# sourceMappingURL=index.js.map