@liberfi.io/react-predict 0.3.52 → 0.3.54
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.d.mts +26 -2
- package/dist/index.d.ts +26 -2
- package/dist/index.js +477 -20
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +478 -22
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { httpGet, httpPost, httpDelete } from '@liberfi.io/utils';
|
|
2
2
|
import { createContext, useMemo, useState, useRef, useCallback, useContext, useEffect } from 'react';
|
|
3
3
|
import { jsx } from 'react/jsx-runtime';
|
|
4
|
-
import { useQuery, useInfiniteQuery, useQueries,
|
|
4
|
+
import { useQuery, useInfiniteQuery, useQueries, useMutation, useQueryClient } from '@tanstack/react-query';
|
|
5
5
|
import { OrderBuilder, SignatureTypeV2, Side, OrderType, orderToJsonV2, ClobClient } from '@polymarket/clob-client-v2';
|
|
6
6
|
|
|
7
7
|
// src/client/client.ts
|
|
@@ -1565,7 +1565,6 @@ function useOrder(params, queryOptions = {}) {
|
|
|
1565
1565
|
}
|
|
1566
1566
|
function useCancelOrder(options, mutationOptions = {}) {
|
|
1567
1567
|
const client = usePredictClient();
|
|
1568
|
-
const queryClient = useQueryClient();
|
|
1569
1568
|
const { onSuccess, onError, ...restMutationOptions } = mutationOptions;
|
|
1570
1569
|
return useMutation({
|
|
1571
1570
|
mutationFn: async (vars) => {
|
|
@@ -1573,7 +1572,6 @@ function useCancelOrder(options, mutationOptions = {}) {
|
|
|
1573
1572
|
return client.cancelOrder(vars.id, vars.source, headers);
|
|
1574
1573
|
},
|
|
1575
1574
|
onSuccess: (...args) => {
|
|
1576
|
-
queryClient.invalidateQueries({ queryKey: ["predict", "orders"] });
|
|
1577
1575
|
onSuccess?.(...args);
|
|
1578
1576
|
},
|
|
1579
1577
|
onError: (...args) => {
|
|
@@ -1582,6 +1580,480 @@ function useCancelOrder(options, mutationOptions = {}) {
|
|
|
1582
1580
|
...restMutationOptions
|
|
1583
1581
|
});
|
|
1584
1582
|
}
|
|
1583
|
+
var DEFAULT_MAX_DURATION_MS = 3e4;
|
|
1584
|
+
var FAST_INTERVAL_MS = 2e3;
|
|
1585
|
+
var SLOW_INTERVAL_MS = 3e3;
|
|
1586
|
+
var SLOW_AFTER_MS = 12e3;
|
|
1587
|
+
var QUERY_PREFIXES = [
|
|
1588
|
+
["predict", "trades"],
|
|
1589
|
+
["predict", "trades-by-wallet"],
|
|
1590
|
+
["predict", "available-shares"]
|
|
1591
|
+
];
|
|
1592
|
+
var OPEN_ORDER_STATUSES = /* @__PURE__ */ new Set(["live", "open", "submitted", "pending"]);
|
|
1593
|
+
function getPositionsWallets(input) {
|
|
1594
|
+
const wallets = {
|
|
1595
|
+
kalshi_user: input.kalshiUser ?? (input.source === "kalshi" ? input.user : void 0),
|
|
1596
|
+
polymarket_user: input.polymarketUser ?? (input.source === "polymarket" ? input.user : void 0)
|
|
1597
|
+
};
|
|
1598
|
+
return wallets.kalshi_user || wallets.polymarket_user ? wallets : void 0;
|
|
1599
|
+
}
|
|
1600
|
+
function getOrdersWalletSets(input) {
|
|
1601
|
+
const wallets = getPositionsWallets(input);
|
|
1602
|
+
const sourceWallet = input.source === "kalshi" ? { kalshi_user: input.user } : { polymarket_user: input.user };
|
|
1603
|
+
const result = [];
|
|
1604
|
+
if (input.user) {
|
|
1605
|
+
result.push(sourceWallet);
|
|
1606
|
+
}
|
|
1607
|
+
if (wallets) {
|
|
1608
|
+
const duplicate = result.some(
|
|
1609
|
+
(item) => item.kalshi_user === wallets.kalshi_user && item.polymarket_user === wallets.polymarket_user
|
|
1610
|
+
);
|
|
1611
|
+
if (!duplicate) {
|
|
1612
|
+
result.push(wallets);
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
return result;
|
|
1616
|
+
}
|
|
1617
|
+
function getSourceOnlyWallets(input) {
|
|
1618
|
+
if (!input.user) return void 0;
|
|
1619
|
+
return input.source === "kalshi" ? { kalshi_user: input.user } : { polymarket_user: input.user };
|
|
1620
|
+
}
|
|
1621
|
+
function dataForSourcePositions(data, source) {
|
|
1622
|
+
if (!data || typeof data !== "object") return data;
|
|
1623
|
+
const response = data;
|
|
1624
|
+
if (!Array.isArray(response.positions)) return data;
|
|
1625
|
+
return {
|
|
1626
|
+
...response,
|
|
1627
|
+
positions: response.positions.filter(
|
|
1628
|
+
(position) => !position.source || position.source === source
|
|
1629
|
+
)
|
|
1630
|
+
};
|
|
1631
|
+
}
|
|
1632
|
+
function normalizeBalanceData(data) {
|
|
1633
|
+
if (!data || typeof data !== "object") return data;
|
|
1634
|
+
const balance = data;
|
|
1635
|
+
return {
|
|
1636
|
+
source: balance.source,
|
|
1637
|
+
user: balance.user,
|
|
1638
|
+
balance: balance.balance,
|
|
1639
|
+
raw_balance: balance.raw_balance
|
|
1640
|
+
};
|
|
1641
|
+
}
|
|
1642
|
+
function normalizePositionsData(data, input) {
|
|
1643
|
+
if (!data || typeof data !== "object") return data;
|
|
1644
|
+
const response = data;
|
|
1645
|
+
return (response.positions ?? []).filter((position) => {
|
|
1646
|
+
const eventSlug = typeof position.event === "object" && position.event ? position.event.slug : void 0;
|
|
1647
|
+
const marketSlug = typeof position.market === "object" && position.market ? position.market.slug : void 0;
|
|
1648
|
+
if (input.marketSlug && marketSlug && marketSlug !== input.marketSlug) {
|
|
1649
|
+
return false;
|
|
1650
|
+
}
|
|
1651
|
+
if (input.eventSlug && eventSlug && eventSlug !== input.eventSlug) {
|
|
1652
|
+
return false;
|
|
1653
|
+
}
|
|
1654
|
+
if (position.source && position.source !== input.source) return false;
|
|
1655
|
+
return true;
|
|
1656
|
+
}).map((position) => ({
|
|
1657
|
+
source: position.source,
|
|
1658
|
+
side: position.side,
|
|
1659
|
+
size: position.size,
|
|
1660
|
+
redeemable: position.redeemable,
|
|
1661
|
+
eventSlug: typeof position.event === "object" && position.event ? position.event.slug : void 0,
|
|
1662
|
+
marketSlug: typeof position.market === "object" && position.market ? position.market.slug : void 0
|
|
1663
|
+
})).sort(
|
|
1664
|
+
(a, b) => `${a.source}:${a.marketSlug}:${a.side}`.localeCompare(
|
|
1665
|
+
`${b.source}:${b.marketSlug}:${b.side}`
|
|
1666
|
+
)
|
|
1667
|
+
);
|
|
1668
|
+
}
|
|
1669
|
+
function normalizeOrdersData(data, input) {
|
|
1670
|
+
if (!data || typeof data !== "object") return data;
|
|
1671
|
+
const response = data;
|
|
1672
|
+
return (response.orders ?? response.items ?? []).filter((order) => {
|
|
1673
|
+
const eventSlug = typeof order.event === "object" && order.event ? order.event.slug : void 0;
|
|
1674
|
+
const marketSlug = typeof order.market === "object" && order.market ? order.market.slug : void 0;
|
|
1675
|
+
const status = typeof order.status === "string" ? order.status : "";
|
|
1676
|
+
if (!OPEN_ORDER_STATUSES.has(status)) return false;
|
|
1677
|
+
if (input.marketSlug && marketSlug && marketSlug !== input.marketSlug) {
|
|
1678
|
+
return false;
|
|
1679
|
+
}
|
|
1680
|
+
if (input.eventSlug && eventSlug && eventSlug !== input.eventSlug) {
|
|
1681
|
+
return false;
|
|
1682
|
+
}
|
|
1683
|
+
if (order.source && order.source !== input.source) return false;
|
|
1684
|
+
return true;
|
|
1685
|
+
}).map((order) => ({
|
|
1686
|
+
id: order.id,
|
|
1687
|
+
source: order.source,
|
|
1688
|
+
status: order.status,
|
|
1689
|
+
side: order.side,
|
|
1690
|
+
outcome: order.outcome,
|
|
1691
|
+
price: order.price,
|
|
1692
|
+
originalSize: order.original_size,
|
|
1693
|
+
marketSlug: typeof order.market === "object" && order.market ? order.market.slug : void 0,
|
|
1694
|
+
eventSlug: typeof order.event === "object" && order.event ? order.event.slug : void 0
|
|
1695
|
+
})).sort((a, b) => String(a.id).localeCompare(String(b.id)));
|
|
1696
|
+
}
|
|
1697
|
+
function getCachedAccountSnapshot(client, input) {
|
|
1698
|
+
const snapshot = {};
|
|
1699
|
+
if (input.user) {
|
|
1700
|
+
const balance = client.getQueryData(
|
|
1701
|
+
balanceQueryKey(input.source, input.user)
|
|
1702
|
+
);
|
|
1703
|
+
if (balance !== void 0) {
|
|
1704
|
+
snapshot.balance = normalizeBalanceData(balance);
|
|
1705
|
+
}
|
|
1706
|
+
}
|
|
1707
|
+
const wallets = getPositionsWallets(input);
|
|
1708
|
+
const multiPositions = wallets ? client.getQueryData(positionsMultiQueryKey(wallets)) : void 0;
|
|
1709
|
+
const singlePositions = input.user ? client.getQueryData(positionsQueryKey(input.user, input.source)) : void 0;
|
|
1710
|
+
const positions = multiPositions ?? singlePositions;
|
|
1711
|
+
if (positions !== void 0) {
|
|
1712
|
+
snapshot.positions = normalizePositionsData(positions, input);
|
|
1713
|
+
}
|
|
1714
|
+
const orders = input.user ? client.getQueryData(
|
|
1715
|
+
ordersQueryKey({ source: input.source, wallet_address: input.user })
|
|
1716
|
+
) : void 0;
|
|
1717
|
+
if (orders !== void 0) {
|
|
1718
|
+
snapshot.orders = normalizeOrdersData(orders, input);
|
|
1719
|
+
}
|
|
1720
|
+
return snapshot;
|
|
1721
|
+
}
|
|
1722
|
+
function serializeSnapshotField(value) {
|
|
1723
|
+
return JSON.stringify(value);
|
|
1724
|
+
}
|
|
1725
|
+
function didFieldChange(field, baseline, current) {
|
|
1726
|
+
if (baseline[field] === void 0 || current[field] === void 0) {
|
|
1727
|
+
return false;
|
|
1728
|
+
}
|
|
1729
|
+
return serializeSnapshotField(current[field]) !== serializeSnapshotField(baseline[field]);
|
|
1730
|
+
}
|
|
1731
|
+
function parseNumeric(value) {
|
|
1732
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
1733
|
+
if (typeof value === "string") {
|
|
1734
|
+
const parsed = Number(value);
|
|
1735
|
+
return Number.isFinite(parsed) ? parsed : void 0;
|
|
1736
|
+
}
|
|
1737
|
+
return void 0;
|
|
1738
|
+
}
|
|
1739
|
+
function getBalanceAmount(snapshot) {
|
|
1740
|
+
if (!snapshot.balance || typeof snapshot.balance !== "object")
|
|
1741
|
+
return void 0;
|
|
1742
|
+
const balance = snapshot.balance;
|
|
1743
|
+
return parseNumeric(balance.raw_balance) ?? parseNumeric(balance.balance);
|
|
1744
|
+
}
|
|
1745
|
+
function getPositionSizeTotal(snapshot) {
|
|
1746
|
+
if (!Array.isArray(snapshot.positions)) return void 0;
|
|
1747
|
+
return snapshot.positions.reduce((total, position) => {
|
|
1748
|
+
if (!position || typeof position !== "object") return total;
|
|
1749
|
+
const size = parseNumeric(position.size);
|
|
1750
|
+
return total + (size ?? 0);
|
|
1751
|
+
}, 0);
|
|
1752
|
+
}
|
|
1753
|
+
function getOpenOrderCount(snapshot) {
|
|
1754
|
+
if (!Array.isArray(snapshot.orders)) return void 0;
|
|
1755
|
+
return snapshot.orders.length;
|
|
1756
|
+
}
|
|
1757
|
+
function hasBothAccountFields(snapshot) {
|
|
1758
|
+
return snapshot.balance !== void 0 && snapshot.positions !== void 0;
|
|
1759
|
+
}
|
|
1760
|
+
function isTradeResultConfirmed(expectation, baseline, current) {
|
|
1761
|
+
const ordersChanged = didFieldChange("orders", baseline, current);
|
|
1762
|
+
const baselineOpenOrders = getOpenOrderCount(baseline);
|
|
1763
|
+
const currentOpenOrders = getOpenOrderCount(current);
|
|
1764
|
+
const openOrdersIncreased = baselineOpenOrders !== void 0 && currentOpenOrders !== void 0 && currentOpenOrders > baselineOpenOrders;
|
|
1765
|
+
if (expectation === "buy-limit" || expectation === "sell-limit") {
|
|
1766
|
+
if (baselineOpenOrders === void 0) {
|
|
1767
|
+
return currentOpenOrders !== void 0 && currentOpenOrders > 0;
|
|
1768
|
+
}
|
|
1769
|
+
return openOrdersIncreased || ordersChanged;
|
|
1770
|
+
}
|
|
1771
|
+
if (!hasBothAccountFields(baseline) || !hasBothAccountFields(current)) {
|
|
1772
|
+
return false;
|
|
1773
|
+
}
|
|
1774
|
+
const balanceChanged = didFieldChange("balance", baseline, current);
|
|
1775
|
+
const positionsChanged = didFieldChange("positions", baseline, current);
|
|
1776
|
+
const baselineBalance = getBalanceAmount(baseline);
|
|
1777
|
+
const currentBalance = getBalanceAmount(current);
|
|
1778
|
+
const baselinePositionSize = getPositionSizeTotal(baseline);
|
|
1779
|
+
const currentPositionSize = getPositionSizeTotal(current);
|
|
1780
|
+
const balanceDecreased = baselineBalance !== void 0 && currentBalance !== void 0 && currentBalance < baselineBalance;
|
|
1781
|
+
const balanceIncreased = baselineBalance !== void 0 && currentBalance !== void 0 && currentBalance > baselineBalance;
|
|
1782
|
+
const positionsIncreased = baselinePositionSize !== void 0 && currentPositionSize !== void 0 && currentPositionSize > baselinePositionSize;
|
|
1783
|
+
const positionsDecreased = baselinePositionSize !== void 0 && currentPositionSize !== void 0 && currentPositionSize < baselinePositionSize;
|
|
1784
|
+
switch (expectation) {
|
|
1785
|
+
case "buy-market":
|
|
1786
|
+
return balanceDecreased && positionsIncreased;
|
|
1787
|
+
case "sell-market":
|
|
1788
|
+
return balanceIncreased && positionsDecreased;
|
|
1789
|
+
case "redeem":
|
|
1790
|
+
return balanceChanged && positionsChanged;
|
|
1791
|
+
case "cancel-order":
|
|
1792
|
+
return false;
|
|
1793
|
+
default:
|
|
1794
|
+
return false;
|
|
1795
|
+
}
|
|
1796
|
+
}
|
|
1797
|
+
function hasOpenTargetOrder(client, orderId) {
|
|
1798
|
+
const orderQueries = client.getQueriesData({
|
|
1799
|
+
queryKey: ["predict", "orders"]
|
|
1800
|
+
});
|
|
1801
|
+
return orderQueries.some(([, data]) => dataContainsOpenOrder(data, orderId));
|
|
1802
|
+
}
|
|
1803
|
+
function dataContainsOpenOrder(data, orderId) {
|
|
1804
|
+
if (!data || typeof data !== "object") return false;
|
|
1805
|
+
if (Array.isArray(data)) {
|
|
1806
|
+
return data.some((item) => dataContainsOpenOrder(item, orderId));
|
|
1807
|
+
}
|
|
1808
|
+
const record = data;
|
|
1809
|
+
if (record.id === orderId) {
|
|
1810
|
+
const status = typeof record.status === "string" ? record.status : "";
|
|
1811
|
+
return !status || OPEN_ORDER_STATUSES.has(status);
|
|
1812
|
+
}
|
|
1813
|
+
for (const value of Object.values(record)) {
|
|
1814
|
+
if (dataContainsOpenOrder(value, orderId)) return true;
|
|
1815
|
+
}
|
|
1816
|
+
return false;
|
|
1817
|
+
}
|
|
1818
|
+
function refetchActiveTradeResultQueries(queryClient) {
|
|
1819
|
+
for (const queryKey of QUERY_PREFIXES) {
|
|
1820
|
+
void queryClient.refetchQueries({ queryKey, type: "active" });
|
|
1821
|
+
}
|
|
1822
|
+
}
|
|
1823
|
+
function requestBalanceSnapshot(queryClient, predictClient, input) {
|
|
1824
|
+
if (!input.user) return Promise.resolve(void 0);
|
|
1825
|
+
const queryKey = balanceQueryKey(input.source, input.user);
|
|
1826
|
+
return queryClient.cancelQueries({ queryKey }).then(() => predictClient.getBalance(input.source, input.user)).then((data) => {
|
|
1827
|
+
queryClient.setQueryData(queryKey, data);
|
|
1828
|
+
return normalizeBalanceData(data);
|
|
1829
|
+
});
|
|
1830
|
+
}
|
|
1831
|
+
function requestPositionsSnapshot(queryClient, predictClient, input) {
|
|
1832
|
+
const wallets = getPositionsWallets(input);
|
|
1833
|
+
if (!wallets) return Promise.resolve(void 0);
|
|
1834
|
+
const sourceOnlyWallets = getSourceOnlyWallets(input);
|
|
1835
|
+
const cancelTasks = [
|
|
1836
|
+
queryClient.cancelQueries({ queryKey: positionsMultiQueryKey(wallets) })
|
|
1837
|
+
];
|
|
1838
|
+
if (sourceOnlyWallets) {
|
|
1839
|
+
cancelTasks.push(
|
|
1840
|
+
queryClient.cancelQueries({
|
|
1841
|
+
queryKey: positionsMultiQueryKey(sourceOnlyWallets)
|
|
1842
|
+
})
|
|
1843
|
+
);
|
|
1844
|
+
}
|
|
1845
|
+
if (input.user) {
|
|
1846
|
+
cancelTasks.push(
|
|
1847
|
+
queryClient.cancelQueries({
|
|
1848
|
+
queryKey: positionsQueryKey(input.user, input.source)
|
|
1849
|
+
})
|
|
1850
|
+
);
|
|
1851
|
+
}
|
|
1852
|
+
return Promise.all(cancelTasks).then(() => predictClient.getPositions(wallets)).then((data) => {
|
|
1853
|
+
queryClient.setQueryData(positionsMultiQueryKey(wallets), data);
|
|
1854
|
+
if (sourceOnlyWallets) {
|
|
1855
|
+
queryClient.setQueryData(
|
|
1856
|
+
positionsMultiQueryKey(sourceOnlyWallets),
|
|
1857
|
+
dataForSourcePositions(data, input.source)
|
|
1858
|
+
);
|
|
1859
|
+
}
|
|
1860
|
+
if (input.user) {
|
|
1861
|
+
queryClient.setQueryData(
|
|
1862
|
+
positionsQueryKey(input.user, input.source),
|
|
1863
|
+
dataForSourcePositions(data, input.source)
|
|
1864
|
+
);
|
|
1865
|
+
}
|
|
1866
|
+
return normalizePositionsData(data, input);
|
|
1867
|
+
});
|
|
1868
|
+
}
|
|
1869
|
+
function requestOrdersSnapshot(queryClient, predictClient, input) {
|
|
1870
|
+
if (!input.user) return Promise.resolve(void 0);
|
|
1871
|
+
const params = { source: input.source, wallet_address: input.user };
|
|
1872
|
+
return Promise.resolve(input.getOrdersHeaders?.()).then((headers) => predictClient.listOrders(params, headers)).then((data) => {
|
|
1873
|
+
queryClient.setQueryData(ordersQueryKey(params), data);
|
|
1874
|
+
return normalizeOrdersData(data, input);
|
|
1875
|
+
});
|
|
1876
|
+
}
|
|
1877
|
+
function refreshEnrichedOrdersSnapshot(queryClient, predictClient, input) {
|
|
1878
|
+
const walletSets = getOrdersWalletSets(input);
|
|
1879
|
+
if (walletSets.length === 0) return Promise.resolve();
|
|
1880
|
+
return Promise.resolve(input.getOrdersHeaders?.()).then(
|
|
1881
|
+
(headers) => Promise.all(
|
|
1882
|
+
walletSets.map(
|
|
1883
|
+
(wallets) => predictClient.listOrdersMulti(wallets, headers).then((data) => {
|
|
1884
|
+
queryClient.setQueryData(ordersMultiQueryKey(wallets), data);
|
|
1885
|
+
})
|
|
1886
|
+
)
|
|
1887
|
+
)
|
|
1888
|
+
).then(() => void 0).catch(() => void 0);
|
|
1889
|
+
}
|
|
1890
|
+
function isLimitExpectation(expectation) {
|
|
1891
|
+
return expectation === "buy-limit" || expectation === "sell-limit";
|
|
1892
|
+
}
|
|
1893
|
+
function nextPollInterval(startedAt) {
|
|
1894
|
+
const elapsed = Date.now() - startedAt;
|
|
1895
|
+
return elapsed < SLOW_AFTER_MS ? FAST_INTERVAL_MS : SLOW_INTERVAL_MS;
|
|
1896
|
+
}
|
|
1897
|
+
function createDeferredConfirmation() {
|
|
1898
|
+
let resolveResult = () => void 0;
|
|
1899
|
+
const promise = new Promise((resolve) => {
|
|
1900
|
+
resolveResult = resolve;
|
|
1901
|
+
});
|
|
1902
|
+
return { promise, resolve: resolveResult };
|
|
1903
|
+
}
|
|
1904
|
+
function sleep(ms) {
|
|
1905
|
+
return new Promise((resolve) => {
|
|
1906
|
+
setTimeout(resolve, ms);
|
|
1907
|
+
});
|
|
1908
|
+
}
|
|
1909
|
+
async function runFixedIntervalConfirmation({
|
|
1910
|
+
queryClient,
|
|
1911
|
+
predictClient,
|
|
1912
|
+
input,
|
|
1913
|
+
startedAt,
|
|
1914
|
+
deadlineAt,
|
|
1915
|
+
initialBaseline,
|
|
1916
|
+
hadTargetOrder,
|
|
1917
|
+
confirm,
|
|
1918
|
+
delay
|
|
1919
|
+
}) {
|
|
1920
|
+
const baseline = { ...initialBaseline };
|
|
1921
|
+
const current = { ...initialBaseline };
|
|
1922
|
+
const inFlight = {
|
|
1923
|
+
balance: false,
|
|
1924
|
+
positions: false,
|
|
1925
|
+
orders: false
|
|
1926
|
+
};
|
|
1927
|
+
let settled = false;
|
|
1928
|
+
const finishConfirmed = () => {
|
|
1929
|
+
settled = true;
|
|
1930
|
+
if (!isLimitExpectation(input.expectation)) {
|
|
1931
|
+
confirm();
|
|
1932
|
+
return;
|
|
1933
|
+
}
|
|
1934
|
+
void refreshEnrichedOrdersSnapshot(
|
|
1935
|
+
queryClient,
|
|
1936
|
+
predictClient,
|
|
1937
|
+
input
|
|
1938
|
+
).finally(confirm);
|
|
1939
|
+
};
|
|
1940
|
+
const handleSnapshot = (field, value) => {
|
|
1941
|
+
if (value === void 0 || settled) return;
|
|
1942
|
+
if (baseline[field] === void 0) {
|
|
1943
|
+
current[field] = value;
|
|
1944
|
+
if (field === "orders" && isLimitExpectation(input.expectation) && isTradeResultConfirmed(input.expectation, baseline, current)) {
|
|
1945
|
+
finishConfirmed();
|
|
1946
|
+
return;
|
|
1947
|
+
}
|
|
1948
|
+
baseline[field] = value;
|
|
1949
|
+
return;
|
|
1950
|
+
}
|
|
1951
|
+
current[field] = value;
|
|
1952
|
+
if (isTradeResultConfirmed(input.expectation, baseline, current)) {
|
|
1953
|
+
finishConfirmed();
|
|
1954
|
+
}
|
|
1955
|
+
};
|
|
1956
|
+
const pollField = (field, request) => {
|
|
1957
|
+
if (inFlight[field] || settled) return;
|
|
1958
|
+
inFlight[field] = true;
|
|
1959
|
+
void request().then((value) => handleSnapshot(field, value)).catch(() => void 0).finally(() => {
|
|
1960
|
+
inFlight[field] = false;
|
|
1961
|
+
});
|
|
1962
|
+
};
|
|
1963
|
+
while (!settled && Date.now() <= deadlineAt) {
|
|
1964
|
+
refetchActiveTradeResultQueries(queryClient);
|
|
1965
|
+
if (input.expectation === "cancel-order" && input.orderId && hadTargetOrder) {
|
|
1966
|
+
if (!hasOpenTargetOrder(queryClient, input.orderId)) {
|
|
1967
|
+
settled = true;
|
|
1968
|
+
confirm();
|
|
1969
|
+
return;
|
|
1970
|
+
}
|
|
1971
|
+
} else if (isLimitExpectation(input.expectation)) {
|
|
1972
|
+
pollField(
|
|
1973
|
+
"orders",
|
|
1974
|
+
() => requestOrdersSnapshot(queryClient, predictClient, input)
|
|
1975
|
+
);
|
|
1976
|
+
} else {
|
|
1977
|
+
pollField(
|
|
1978
|
+
"balance",
|
|
1979
|
+
() => requestBalanceSnapshot(queryClient, predictClient, input)
|
|
1980
|
+
);
|
|
1981
|
+
pollField(
|
|
1982
|
+
"positions",
|
|
1983
|
+
() => requestPositionsSnapshot(queryClient, predictClient, input)
|
|
1984
|
+
);
|
|
1985
|
+
}
|
|
1986
|
+
await sleep(
|
|
1987
|
+
Math.min(
|
|
1988
|
+
nextPollInterval(startedAt),
|
|
1989
|
+
Math.max(0, deadlineAt - Date.now())
|
|
1990
|
+
)
|
|
1991
|
+
);
|
|
1992
|
+
}
|
|
1993
|
+
if (!settled) delay();
|
|
1994
|
+
}
|
|
1995
|
+
function useTradeResultConfirmation() {
|
|
1996
|
+
const queryClient = useQueryClient();
|
|
1997
|
+
const predictClient = usePredictClient();
|
|
1998
|
+
const mountedRef = useRef(true);
|
|
1999
|
+
const [state, setState] = useState({
|
|
2000
|
+
status: "idle"
|
|
2001
|
+
});
|
|
2002
|
+
useEffect(() => {
|
|
2003
|
+
return () => {
|
|
2004
|
+
mountedRef.current = false;
|
|
2005
|
+
};
|
|
2006
|
+
}, []);
|
|
2007
|
+
const start = useCallback(
|
|
2008
|
+
async (input) => {
|
|
2009
|
+
const {
|
|
2010
|
+
expectation,
|
|
2011
|
+
orderId,
|
|
2012
|
+
maxDurationMs = DEFAULT_MAX_DURATION_MS
|
|
2013
|
+
} = input;
|
|
2014
|
+
const startedAt = Date.now();
|
|
2015
|
+
const deadlineAt = startedAt + maxDurationMs;
|
|
2016
|
+
const preflightBaseline = getCachedAccountSnapshot(queryClient, input);
|
|
2017
|
+
const hadTargetOrder = expectation === "cancel-order" && orderId ? hasOpenTargetOrder(queryClient, orderId) : false;
|
|
2018
|
+
if (mountedRef.current) {
|
|
2019
|
+
setState({ status: "confirming", startedAt, deadlineAt });
|
|
2020
|
+
}
|
|
2021
|
+
const result = createDeferredConfirmation();
|
|
2022
|
+
let resolved = false;
|
|
2023
|
+
const resolveOnce = (confirmationResult) => {
|
|
2024
|
+
if (resolved) return;
|
|
2025
|
+
resolved = true;
|
|
2026
|
+
result.resolve(confirmationResult);
|
|
2027
|
+
};
|
|
2028
|
+
const confirm = () => {
|
|
2029
|
+
if (mountedRef.current) {
|
|
2030
|
+
setState({ status: "confirmed", startedAt, deadlineAt });
|
|
2031
|
+
}
|
|
2032
|
+
resolveOnce("confirmed");
|
|
2033
|
+
};
|
|
2034
|
+
const delay = () => {
|
|
2035
|
+
if (mountedRef.current) {
|
|
2036
|
+
setState({ status: "delayed", startedAt, deadlineAt });
|
|
2037
|
+
}
|
|
2038
|
+
resolveOnce("delayed");
|
|
2039
|
+
};
|
|
2040
|
+
void runFixedIntervalConfirmation({
|
|
2041
|
+
queryClient,
|
|
2042
|
+
predictClient,
|
|
2043
|
+
input,
|
|
2044
|
+
startedAt,
|
|
2045
|
+
deadlineAt,
|
|
2046
|
+
initialBaseline: preflightBaseline,
|
|
2047
|
+
hadTargetOrder,
|
|
2048
|
+
confirm,
|
|
2049
|
+
delay
|
|
2050
|
+
});
|
|
2051
|
+
return await result.promise;
|
|
2052
|
+
},
|
|
2053
|
+
[predictClient, queryClient]
|
|
2054
|
+
);
|
|
2055
|
+
return { start, state };
|
|
2056
|
+
}
|
|
1585
2057
|
|
|
1586
2058
|
// src/hooks/predict/matches.params.ts
|
|
1587
2059
|
function matchesQueryKey(params) {
|
|
@@ -1701,13 +2173,8 @@ function useDFlowQuote(params, queryOptions = {}) {
|
|
|
1701
2173
|
}
|
|
1702
2174
|
function useDFlowSubmit(mutationOptions = {}) {
|
|
1703
2175
|
const client = usePredictClient();
|
|
1704
|
-
const queryClient = useQueryClient();
|
|
1705
2176
|
return useMutation({
|
|
1706
2177
|
mutationFn: (body) => client.submitDFlowTransaction(body),
|
|
1707
|
-
onSuccess: () => {
|
|
1708
|
-
queryClient.invalidateQueries({ queryKey: ["predict", "orders"] });
|
|
1709
|
-
queryClient.invalidateQueries({ queryKey: ["predict", "positions"] });
|
|
1710
|
-
},
|
|
1711
2178
|
...mutationOptions
|
|
1712
2179
|
});
|
|
1713
2180
|
}
|
|
@@ -1851,7 +2318,7 @@ function usePolymarketDeposit(mutationOptions = {}) {
|
|
|
1851
2318
|
}
|
|
1852
2319
|
async function pollTxUntilConfirmed(client, txHash) {
|
|
1853
2320
|
for (let i = 0; i < TX_POLL_MAX_ATTEMPTS; i++) {
|
|
1854
|
-
await
|
|
2321
|
+
await sleep2(TX_POLL_INTERVAL);
|
|
1855
2322
|
const result = await client.depositStatus(txHash, "polymarket");
|
|
1856
2323
|
if (result.status === "confirmed") return;
|
|
1857
2324
|
if (result.status === "failed") {
|
|
@@ -1862,7 +2329,7 @@ async function pollTxUntilConfirmed(client, txHash) {
|
|
|
1862
2329
|
`Deposit transaction timed out after ${TX_POLL_MAX_ATTEMPTS * TX_POLL_INTERVAL / 1e3}s: ${txHash}`
|
|
1863
2330
|
);
|
|
1864
2331
|
}
|
|
1865
|
-
function
|
|
2332
|
+
function sleep2(ms) {
|
|
1866
2333
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1867
2334
|
}
|
|
1868
2335
|
var polymarketDepositAddressesQueryKey = (safeAddress) => ["polymarket", "deposit-addresses", safeAddress];
|
|
@@ -1936,7 +2403,6 @@ function usePolymarketWithdrawStatusQuery(params) {
|
|
|
1936
2403
|
}
|
|
1937
2404
|
function useRedeemPosition() {
|
|
1938
2405
|
const client = usePredictClient();
|
|
1939
|
-
const queryClient = useQueryClient();
|
|
1940
2406
|
return useMutation({
|
|
1941
2407
|
mutationFn: async ({
|
|
1942
2408
|
wallet_address,
|
|
@@ -1987,10 +2453,6 @@ function useRedeemPosition() {
|
|
|
1987
2453
|
);
|
|
1988
2454
|
}
|
|
1989
2455
|
return result;
|
|
1990
|
-
},
|
|
1991
|
-
onSuccess: () => {
|
|
1992
|
-
queryClient.invalidateQueries({ queryKey: ["predict", "positions"] });
|
|
1993
|
-
queryClient.invalidateQueries({ queryKey: ["predict", "balance"] });
|
|
1994
2456
|
}
|
|
1995
2457
|
});
|
|
1996
2458
|
}
|
|
@@ -2519,7 +2981,6 @@ var TX_POLL_MAX_ATTEMPTS2 = 60;
|
|
|
2519
2981
|
function useCreatePolymarketOrder(mutationOptions = {}) {
|
|
2520
2982
|
const client = usePredictClient();
|
|
2521
2983
|
const { credentials, authenticate } = usePolymarket();
|
|
2522
|
-
const queryClient = useQueryClient();
|
|
2523
2984
|
return useMutation({
|
|
2524
2985
|
mutationFn: async ({
|
|
2525
2986
|
input,
|
|
@@ -2594,11 +3055,6 @@ function useCreatePolymarketOrder(mutationOptions = {}) {
|
|
|
2594
3055
|
});
|
|
2595
3056
|
return result.raw;
|
|
2596
3057
|
},
|
|
2597
|
-
onSuccess: () => {
|
|
2598
|
-
queryClient.invalidateQueries({ queryKey: ["predict", "orders"] });
|
|
2599
|
-
queryClient.invalidateQueries({ queryKey: ["predict", "positions"] });
|
|
2600
|
-
queryClient.invalidateQueries({ queryKey: ["predict", "balance"] });
|
|
2601
|
-
},
|
|
2602
3058
|
...mutationOptions
|
|
2603
3059
|
});
|
|
2604
3060
|
}
|
|
@@ -2720,6 +3176,6 @@ function walkOrderbook({
|
|
|
2720
3176
|
};
|
|
2721
3177
|
}
|
|
2722
3178
|
|
|
2723
|
-
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, availableSharesQueryKey, balanceQueryKey, buildClobAuthMessage, buildClobPayload, buildCtfExchangeDomain, buildOrderMessage, buildPolymarketL2Headers, buildSignedOrder, buildSignedV2OrderPayload, candlesticksQueryKey, createPredictClient, createPredictWsClient, derivePolymarketApiKey, dflowKYCQueryKey, dflowQuoteQueryKey, eventQueryKey, eventStatsQueryKey, eventsQueryKey, feeRateQueryKey, fetchEvent, fetchEvents, fetchEventsPage, fetchMarket, fetchMatchMarketsPage, fetchMatchesPage, getPolymarketSharesPrecision, hmacSha256Base64, infiniteCommentsQueryKey, infiniteEventsQueryKey, infiniteOrdersQueryKey, infiniteTradesMultiQueryKey, infiniteTradesQueryKey, marketQueryKey, marketTradesQueryKey, matchMarketsQueryKey, matchQueryKey, matchesQueryKey, orderQueryKey, orderbookQueryKey, ordersMultiQueryKey, ordersQueryKey, pickBestAsk, pickBestBid, polymarketDepositAddressesQueryKey, polymarketSetupQueryKey, polymarketSupportedAssetsQueryKey, polymarketWithdrawStatusQueryKey, positionsMultiQueryKey, positionsQueryKey, priceHistoryQueryKey, rebateConfigQueryKey, resolveEventsParams, resolveTagSlug, similarEventsQueryKey, tickSizeQueryKey, tradesQueryKey, updatePolymarketBalanceAllowance, useAvailableShares, useBalance, useCancelOrder, useCandlesticks, useCreatePolymarketOrder, useDFlowKYC, useDFlowQuote, useDFlowSubmit, useDeployPolymarketDepositWallet, useEvent, useEventStats, useEvents, useFeeRate, useInfiniteComments, useInfiniteEvents, useInfiniteMatchMarkets, useInfiniteMatches, useInfiniteOrders, useInfiniteTrades, useInfiniteTradesMulti, useMarket, useMarketHistory, useMarketTrades, useMatch, useOrder, useOrderbook, useOrderbookSubscription, useOrders, useOrdersMulti, usePolymarket, usePolymarketDeposit, usePolymarketDepositAddresses, usePolymarketSetup, usePolymarketSupportedAssets, usePolymarketWithdraw, usePolymarketWithdrawPrepareMutation, usePolymarketWithdrawQuoteMutation, usePolymarketWithdrawRelayBuildMutation, usePolymarketWithdrawRelaySubmitMutation, usePolymarketWithdrawStatusQuery, usePositions, usePositionsMulti, usePredictClient, usePredictWsClient, usePriceHistory, usePricesSubscription, useRealtimeOrderbook, useRealtimePrices, useRealtimeTrades, useRebateConfig, useRedeemPosition, useRunPolymarketSetup, useSearchEvents, useSimilarEvents, useTickSize, useTrades, useTradesSubscription, useWithdrawBuildMutation, useWithdrawStatusQuery, useWithdrawSubmitMutation, walkOrderbook, withdrawStatusQueryKey };
|
|
3179
|
+
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, availableSharesQueryKey, balanceQueryKey, buildClobAuthMessage, buildClobPayload, buildCtfExchangeDomain, buildOrderMessage, buildPolymarketL2Headers, buildSignedOrder, buildSignedV2OrderPayload, candlesticksQueryKey, createPredictClient, createPredictWsClient, derivePolymarketApiKey, dflowKYCQueryKey, dflowQuoteQueryKey, eventQueryKey, eventStatsQueryKey, eventsQueryKey, feeRateQueryKey, fetchEvent, fetchEvents, fetchEventsPage, fetchMarket, fetchMatchMarketsPage, fetchMatchesPage, getPolymarketSharesPrecision, hmacSha256Base64, infiniteCommentsQueryKey, infiniteEventsQueryKey, infiniteOrdersQueryKey, infiniteTradesMultiQueryKey, infiniteTradesQueryKey, marketQueryKey, marketTradesQueryKey, matchMarketsQueryKey, matchQueryKey, matchesQueryKey, orderQueryKey, orderbookQueryKey, ordersMultiQueryKey, ordersQueryKey, pickBestAsk, pickBestBid, polymarketDepositAddressesQueryKey, polymarketSetupQueryKey, polymarketSupportedAssetsQueryKey, polymarketWithdrawStatusQueryKey, positionsMultiQueryKey, positionsQueryKey, priceHistoryQueryKey, rebateConfigQueryKey, resolveEventsParams, resolveTagSlug, similarEventsQueryKey, tickSizeQueryKey, tradesQueryKey, updatePolymarketBalanceAllowance, useAvailableShares, useBalance, useCancelOrder, useCandlesticks, useCreatePolymarketOrder, useDFlowKYC, useDFlowQuote, useDFlowSubmit, useDeployPolymarketDepositWallet, useEvent, useEventStats, useEvents, useFeeRate, useInfiniteComments, useInfiniteEvents, useInfiniteMatchMarkets, useInfiniteMatches, useInfiniteOrders, useInfiniteTrades, useInfiniteTradesMulti, useMarket, useMarketHistory, useMarketTrades, useMatch, useOrder, useOrderbook, useOrderbookSubscription, useOrders, useOrdersMulti, usePolymarket, usePolymarketDeposit, usePolymarketDepositAddresses, usePolymarketSetup, usePolymarketSupportedAssets, usePolymarketWithdraw, usePolymarketWithdrawPrepareMutation, usePolymarketWithdrawQuoteMutation, usePolymarketWithdrawRelayBuildMutation, usePolymarketWithdrawRelaySubmitMutation, usePolymarketWithdrawStatusQuery, usePositions, usePositionsMulti, usePredictClient, usePredictWsClient, usePriceHistory, usePricesSubscription, useRealtimeOrderbook, useRealtimePrices, useRealtimeTrades, useRebateConfig, useRedeemPosition, useRunPolymarketSetup, useSearchEvents, useSimilarEvents, useTickSize, useTradeResultConfirmation, useTrades, useTradesSubscription, useWithdrawBuildMutation, useWithdrawStatusQuery, useWithdrawSubmitMutation, walkOrderbook, withdrawStatusQueryKey };
|
|
2724
3180
|
//# sourceMappingURL=index.mjs.map
|
|
2725
3181
|
//# sourceMappingURL=index.mjs.map
|