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