@symmio/trading-core 4.1.0 → 4.2.0
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.ts +17 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +108 -87
- package/dist/pools/add-market/to-created-pool.d.ts.map +1 -1
- package/dist/pools/add-market/to-created-pool.js +4 -0
- package/dist/pools/add-market/to-created-pool.js.map +1 -1
- package/dist/pools/add-market/types.d.ts +8 -0
- package/dist/pools/add-market/types.d.ts.map +1 -1
- package/dist/pools/auth/authenticate-listing.d.ts +3 -1
- package/dist/pools/auth/authenticate-listing.d.ts.map +1 -1
- package/dist/pools/auth/authenticate-listing.js +28 -23
- package/dist/pools/auth/authenticate-listing.js.map +1 -1
- package/dist/pools/auth/can-reuse-listing-challenge.d.ts +5 -0
- package/dist/pools/auth/can-reuse-listing-challenge.d.ts.map +1 -0
- package/dist/pools/auth/can-reuse-listing-challenge.js +9 -0
- package/dist/pools/auth/can-reuse-listing-challenge.js.map +1 -0
- package/dist/pools/auth/query.d.ts +15 -0
- package/dist/pools/auth/query.d.ts.map +1 -1
- package/dist/pools/auth/query.js +28 -4
- package/dist/pools/auth/query.js.map +1 -1
- package/dist/pools/auth/to-siwe.d.ts +5 -1
- package/dist/pools/auth/to-siwe.d.ts.map +1 -1
- package/dist/pools/auth/to-siwe.js +4 -2
- package/dist/pools/auth/to-siwe.js.map +1 -1
- package/dist/pools/auth/types.d.ts +2 -0
- package/dist/pools/auth/types.d.ts.map +1 -1
- package/dist/pools/cancel-withdraw/cancel-withdraw.js +1 -1
- package/dist/pools/cancel-withdraw/cancel-withdraw.js.map +1 -1
- package/dist/pools/claim-history/get-pool-claim.d.ts +11 -0
- package/dist/pools/claim-history/get-pool-claim.d.ts.map +1 -0
- package/dist/pools/claim-history/get-pool-claim.js +25 -0
- package/dist/pools/claim-history/get-pool-claim.js.map +1 -0
- package/dist/pools/claim-history/index.d.ts +1 -0
- package/dist/pools/claim-history/index.d.ts.map +1 -1
- package/dist/pools/claim-history/to-pool-claim.d.ts.map +1 -1
- package/dist/pools/claim-history/to-pool-claim.js +2 -0
- package/dist/pools/claim-history/to-pool-claim.js.map +1 -1
- package/dist/pools/composition.d.ts +16 -0
- package/dist/pools/composition.d.ts.map +1 -0
- package/dist/pools/composition.js +39 -0
- package/dist/pools/composition.js.map +1 -0
- package/dist/pools/empty-pool-profit.d.ts +4 -0
- package/dist/pools/empty-pool-profit.d.ts.map +1 -0
- package/dist/pools/empty-pool-profit.js +17 -0
- package/dist/pools/empty-pool-profit.js.map +1 -0
- package/dist/pools/index.d.ts +8 -0
- package/dist/pools/index.d.ts.map +1 -1
- package/dist/pools/listing-config/to-listing-config.d.ts +5 -1
- package/dist/pools/listing-config/to-listing-config.d.ts.map +1 -1
- package/dist/pools/listing-config/to-listing-config.js +19 -8
- package/dist/pools/listing-config/to-listing-config.js.map +1 -1
- package/dist/pools/maintenance-fees/get-pool-maintenance-fees.d.ts +37 -0
- package/dist/pools/maintenance-fees/get-pool-maintenance-fees.d.ts.map +1 -0
- package/dist/pools/maintenance-fees/get-pool-maintenance-fees.js +35 -0
- package/dist/pools/maintenance-fees/get-pool-maintenance-fees.js.map +1 -0
- package/dist/pools/maintenance-fees/index.d.ts +3 -0
- package/dist/pools/maintenance-fees/index.d.ts.map +1 -0
- package/dist/pools/maintenance-fees/query.d.ts +11 -0
- package/dist/pools/maintenance-fees/query.d.ts.map +1 -0
- package/dist/pools/maintenance-fees/query.js +21 -0
- package/dist/pools/maintenance-fees/query.js.map +1 -0
- package/dist/pools/market-config/to-listing-market-config.d.ts +6 -1
- package/dist/pools/market-config/to-listing-market-config.d.ts.map +1 -1
- package/dist/pools/market-config/to-listing-market-config.js +1 -0
- package/dist/pools/market-config/to-listing-market-config.js.map +1 -1
- package/dist/pools/market-config/types.d.ts +5 -0
- package/dist/pools/market-config/types.d.ts.map +1 -1
- package/dist/pools/market-config/types.js.map +1 -1
- package/dist/pools/market-data/get-pool-market-data.d.ts +14 -0
- package/dist/pools/market-data/get-pool-market-data.d.ts.map +1 -0
- package/dist/pools/market-data/get-pool-market-data.js +25 -0
- package/dist/pools/market-data/get-pool-market-data.js.map +1 -0
- package/dist/pools/market-data/index.d.ts +2 -0
- package/dist/pools/market-data/index.d.ts.map +1 -0
- package/dist/pools/market-detail/to-listing-market-detail.d.ts +5 -1
- package/dist/pools/market-detail/to-listing-market-detail.d.ts.map +1 -1
- package/dist/pools/market-detail/to-listing-market-detail.js +45 -33
- package/dist/pools/market-detail/to-listing-market-detail.js.map +1 -1
- package/dist/pools/markets/to-listing-market.d.ts +13 -1
- package/dist/pools/markets/to-listing-market.d.ts.map +1 -1
- package/dist/pools/markets/to-listing-market.js +24 -12
- package/dist/pools/markets/to-listing-market.js.map +1 -1
- package/dist/pools/open-positions/calculate-pool-open-positions.d.ts +39 -0
- package/dist/pools/open-positions/calculate-pool-open-positions.d.ts.map +1 -0
- package/dist/pools/open-positions/calculate-pool-open-positions.js +83 -0
- package/dist/pools/open-positions/calculate-pool-open-positions.js.map +1 -0
- package/dist/pools/open-positions/get-pool-open-positions.d.ts +17 -0
- package/dist/pools/open-positions/get-pool-open-positions.d.ts.map +1 -0
- package/dist/pools/open-positions/get-pool-open-positions.js +39 -0
- package/dist/pools/open-positions/get-pool-open-positions.js.map +1 -0
- package/dist/pools/open-positions/index.d.ts +4 -0
- package/dist/pools/open-positions/index.d.ts.map +1 -0
- package/dist/pools/open-positions/query.d.ts +17 -0
- package/dist/pools/open-positions/query.d.ts.map +1 -0
- package/dist/pools/open-positions/query.js +21 -0
- package/dist/pools/open-positions/query.js.map +1 -0
- package/dist/pools/portfolio/calculate-pool-portfolio.d.ts +66 -0
- package/dist/pools/portfolio/calculate-pool-portfolio.d.ts.map +1 -0
- package/dist/pools/portfolio/calculate-pool-portfolio.js +96 -0
- package/dist/pools/portfolio/calculate-pool-portfolio.js.map +1 -0
- package/dist/pools/portfolio/get-pool-portfolio.d.ts +19 -0
- package/dist/pools/portfolio/get-pool-portfolio.d.ts.map +1 -0
- package/dist/pools/portfolio/get-pool-portfolio.js +88 -0
- package/dist/pools/portfolio/get-pool-portfolio.js.map +1 -0
- package/dist/pools/portfolio/index.d.ts +4 -0
- package/dist/pools/portfolio/index.d.ts.map +1 -0
- package/dist/pools/portfolio/query.d.ts +17 -0
- package/dist/pools/portfolio/query.d.ts.map +1 -0
- package/dist/pools/portfolio/query.js +21 -0
- package/dist/pools/portfolio/query.js.map +1 -0
- package/dist/pools/portfolio/read-positions.d.ts +4 -0
- package/dist/pools/portfolio/read-positions.d.ts.map +1 -0
- package/dist/pools/portfolio/read-positions.js +31 -0
- package/dist/pools/portfolio/read-positions.js.map +1 -0
- package/dist/pools/position/calculate-pool-position.d.ts +85 -0
- package/dist/pools/position/calculate-pool-position.d.ts.map +1 -0
- package/dist/pools/position/calculate-pool-position.js +59 -0
- package/dist/pools/position/calculate-pool-position.js.map +1 -0
- package/dist/pools/position/get-pool-position.d.ts +22 -0
- package/dist/pools/position/get-pool-position.d.ts.map +1 -0
- package/dist/pools/position/get-pool-position.js +47 -0
- package/dist/pools/position/get-pool-position.js.map +1 -0
- package/dist/pools/position/index.d.ts +4 -0
- package/dist/pools/position/index.d.ts.map +1 -0
- package/dist/pools/position/query.d.ts +17 -0
- package/dist/pools/position/query.d.ts.map +1 -0
- package/dist/pools/position/query.js +21 -0
- package/dist/pools/position/query.js.map +1 -0
- package/dist/pools/position/sum-deposits.d.ts +10 -0
- package/dist/pools/position/sum-deposits.d.ts.map +1 -0
- package/dist/pools/position/sum-deposits.js +35 -0
- package/dist/pools/position/sum-deposits.js.map +1 -0
- package/dist/pools/profit/get-user-profit.d.ts +4 -0
- package/dist/pools/profit/get-user-profit.d.ts.map +1 -1
- package/dist/pools/profit/get-user-profit.js +18 -12
- package/dist/pools/profit/get-user-profit.js.map +1 -1
- package/dist/pools/profit/to-user-pool-profit.d.ts +22 -4
- package/dist/pools/profit/to-user-pool-profit.d.ts.map +1 -1
- package/dist/pools/profit/to-user-pool-profit.js +28 -12
- package/dist/pools/profit/to-user-pool-profit.js.map +1 -1
- package/dist/pools/quotes/get-pool-quotes.d.ts +8 -1
- package/dist/pools/quotes/get-pool-quotes.d.ts.map +1 -1
- package/dist/pools/quotes/get-pool-quotes.js +8 -1
- package/dist/pools/quotes/get-pool-quotes.js.map +1 -1
- package/dist/pools/quotes/query-document.d.ts.map +1 -1
- package/dist/pools/quotes/query-document.js +1 -1
- package/dist/pools/quotes/query-document.js.map +1 -1
- package/dist/pools/quotes/to-pool-quote.d.ts.map +1 -1
- package/dist/pools/quotes/to-pool-quote.js +13 -0
- package/dist/pools/quotes/to-pool-quote.js.map +1 -1
- package/dist/pools/rewards/query.js +25 -25
- package/dist/pools/statistics/calculate-pool-statistics.d.ts +69 -0
- package/dist/pools/statistics/calculate-pool-statistics.d.ts.map +1 -0
- package/dist/pools/statistics/calculate-pool-statistics.js +42 -0
- package/dist/pools/statistics/calculate-pool-statistics.js.map +1 -0
- package/dist/pools/statistics/get-pool-statistics.d.ts +29 -0
- package/dist/pools/statistics/get-pool-statistics.d.ts.map +1 -0
- package/dist/pools/statistics/get-pool-statistics.js +61 -0
- package/dist/pools/statistics/get-pool-statistics.js.map +1 -0
- package/dist/pools/statistics/index.d.ts +4 -0
- package/dist/pools/statistics/index.d.ts.map +1 -0
- package/dist/pools/statistics/query.d.ts +17 -0
- package/dist/pools/statistics/query.d.ts.map +1 -0
- package/dist/pools/statistics/query.js +21 -0
- package/dist/pools/statistics/query.js.map +1 -0
- package/dist/pools/token-metadata/get-listing-token-metadata.d.ts +32 -0
- package/dist/pools/token-metadata/get-listing-token-metadata.d.ts.map +1 -0
- package/dist/pools/token-metadata/get-listing-token-metadata.js +43 -0
- package/dist/pools/token-metadata/get-listing-token-metadata.js.map +1 -0
- package/dist/pools/token-metadata/index.d.ts +3 -0
- package/dist/pools/token-metadata/index.d.ts.map +1 -0
- package/dist/pools/token-metadata/query.d.ts +11 -0
- package/dist/pools/token-metadata/query.d.ts.map +1 -0
- package/dist/pools/token-metadata/query.js +21 -0
- package/dist/pools/token-metadata/query.js.map +1 -0
- package/dist/pools/token-support/check-listing-token-support.d.ts +23 -0
- package/dist/pools/token-support/check-listing-token-support.d.ts.map +1 -0
- package/dist/pools/token-support/check-listing-token-support.js +36 -0
- package/dist/pools/token-support/check-listing-token-support.js.map +1 -0
- package/dist/pools/token-support/index.d.ts +3 -0
- package/dist/pools/token-support/index.d.ts.map +1 -0
- package/dist/pools/token-support/query.d.ts +11 -0
- package/dist/pools/token-support/query.d.ts.map +1 -0
- package/dist/pools/token-support/query.js +21 -0
- package/dist/pools/token-support/query.js.map +1 -0
- package/dist/pools/trade-history/calculate-history-metrics.d.ts +12 -0
- package/dist/pools/trade-history/calculate-history-metrics.d.ts.map +1 -0
- package/dist/pools/trade-history/calculate-history-metrics.js +36 -0
- package/dist/pools/trade-history/calculate-history-metrics.js.map +1 -0
- package/dist/pools/trade-history/get-pool-trade-history.d.ts +21 -1
- package/dist/pools/trade-history/get-pool-trade-history.d.ts.map +1 -1
- package/dist/pools/trade-history/get-pool-trade-history.js +57 -18
- package/dist/pools/trade-history/get-pool-trade-history.js.map +1 -1
- package/dist/pools/trade-history/query-document.d.ts.map +1 -1
- package/dist/pools/trade-history/query-document.js +1 -1
- package/dist/pools/trade-history/query-document.js.map +1 -1
- package/dist/pools/transactions/get-pool-transaction-range.d.ts +6 -0
- package/dist/pools/transactions/get-pool-transaction-range.d.ts.map +1 -0
- package/dist/pools/transactions/get-pool-transaction-range.js +26 -0
- package/dist/pools/transactions/get-pool-transaction-range.js.map +1 -0
- package/dist/pools/transactions/index.d.ts +1 -0
- package/dist/pools/transactions/index.d.ts.map +1 -1
- package/dist/pools/types/generated/listing-backend.js +34 -10
- package/dist/pools/types/generated/listing-backend.js.map +1 -1
- package/dist/pools/types.d.ts +129 -6
- package/dist/pools/types.d.ts.map +1 -1
- package/dist/pools/types.js.map +1 -1
- package/dist/pools/user-markets/get-user-listing-markets.d.ts +2 -0
- package/dist/pools/user-markets/get-user-listing-markets.d.ts.map +1 -1
- package/dist/pools/user-markets/get-user-listing-markets.js.map +1 -1
- package/dist/pools/user-markets/to-user-listing-market.js +1 -1
- package/dist/pools/user-markets/to-user-listing-market.js.map +1 -1
- package/dist/pools/user-transactions/get-user-transactions.d.ts +2 -0
- package/dist/pools/user-transactions/get-user-transactions.d.ts.map +1 -1
- package/dist/pools/user-transactions/get-user-transactions.js.map +1 -1
- package/dist/pools/user-transactions/to-user-transaction.d.ts +5 -1
- package/dist/pools/user-transactions/to-user-transaction.d.ts.map +1 -1
- package/dist/pools/user-transactions/to-user-transaction.js +3 -0
- package/dist/pools/user-transactions/to-user-transaction.js.map +1 -1
- package/dist/quotes/liquidation/calculate-liquidation-price.d.ts +5 -1
- package/dist/quotes/liquidation/calculate-liquidation-price.d.ts.map +1 -1
- package/dist/quotes/liquidation/calculate-liquidation-price.js +1 -1
- package/dist/quotes/liquidation/calculate-liquidation-price.js.map +1 -1
- package/dist/quotes/upnl/calculate-quote-pnl.d.ts.map +1 -1
- package/dist/quotes/upnl/calculate-quote-pnl.js +8 -8
- package/dist/quotes/upnl/calculate-quote-pnl.js.map +1 -1
- package/dist/quotes/upnl/calculate-quote-upnl.d.ts +2 -2
- package/dist/quotes/upnl/calculate-quote-upnl.d.ts.map +1 -1
- package/dist/quotes/upnl/calculate-quote-upnl.js +16 -15
- package/dist/quotes/upnl/calculate-quote-upnl.js.map +1 -1
- package/dist/symmio-subgraph/types/generated/analytics/gql.d.ts +2 -2
- package/dist/symmio-subgraph/types/generated/analytics/gql.d.ts.map +1 -1
- package/dist/symmio-subgraph/types/generated/analytics/gql.js +2 -2
- package/dist/symmio-subgraph/types/generated/analytics/gql.js.map +1 -1
- package/dist/symmio-subgraph/types/generated/analytics/graphql.d.ts +21 -0
- package/dist/symmio-subgraph/types/generated/analytics/graphql.d.ts.map +1 -1
- package/dist/symmio-subgraph/types/generated/analytics/graphql.js +1 -1
- package/dist/symmio-subgraph/types/generated/analytics/graphql.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { PositionType as e } from "../../symmio-contracts/symmio/types.js";
|
|
2
|
+
import { calculateLiquidationPrice as t } from "../../quotes/liquidation/calculate-liquidation-price.js";
|
|
3
|
+
import { calculateQuoteLeverage as n } from "../../quotes/upnl/calculate-quote-leverage.js";
|
|
4
|
+
import { calculateQuoteUpnl as r } from "../../quotes/upnl/calculate-quote-upnl.js";
|
|
5
|
+
import { units as i } from "../composition.js";
|
|
6
|
+
import { parseUnits as a } from "viem";
|
|
7
|
+
import { toDecimal as o } from "@symmio/utils";
|
|
8
|
+
//#region src/pools/open-positions/calculate-pool-open-positions.ts
|
|
9
|
+
function s(n) {
|
|
10
|
+
let a = n.priceUsd != null && Number.isFinite(n.priceUsd) && n.priceUsd >= 0 ? n.priceUsd : null;
|
|
11
|
+
return {
|
|
12
|
+
entries: n.quotes.map((o) => {
|
|
13
|
+
let s = [
|
|
14
|
+
o.openedPrice,
|
|
15
|
+
o.initialOpenedPrice,
|
|
16
|
+
o.requestedOpenPrice
|
|
17
|
+
].find((e) => e != null && e > 0n) ?? null, u = o.quantity == null || o.closedAmount == null ? null : o.quantity > o.closedAmount ? o.quantity - o.closedAmount : 0n, d = c(o, s), f = o.positionType === e.SHORT || o.positionType === e.LONG ? o.positionType : null, p = a == null || s == null || u == null || f == null ? null : r({
|
|
18
|
+
markPrice: String(a),
|
|
19
|
+
positionType: f,
|
|
20
|
+
quantity: u,
|
|
21
|
+
closedAmount: 0n,
|
|
22
|
+
openedPrice: s,
|
|
23
|
+
leverage: "1"
|
|
24
|
+
}), m = o.partyA?.toLowerCase(), h = m == null ? null : n.balances[m], g = m == null ? [] : n.quotes.filter((e) => e.partyA?.toLowerCase() === m), _ = g.flatMap((e) => e.quantity == null || e.closedAmount == null || e.openedPrice == null ? [] : [{
|
|
25
|
+
quantity: e.quantity,
|
|
26
|
+
closedAmount: e.closedAmount,
|
|
27
|
+
openedPrice: e.openedPrice
|
|
28
|
+
}]), v = g.every((e) => e.symbolId === o.symbolId && Number(e.positionType) === Number(o.positionType)), y = h && f != null && n.complete !== !1 && v && g.length > 0 && _.length === g.length ? t({
|
|
29
|
+
...h,
|
|
30
|
+
positions: _,
|
|
31
|
+
positionType: f
|
|
32
|
+
}) : null, b = n.allowQuoteLockEstimate && f != null && s != null && u != null && u > 0n ? l(o, s, d, f) : null, x = y ?? b;
|
|
33
|
+
return {
|
|
34
|
+
...o,
|
|
35
|
+
remainingQuantity: u,
|
|
36
|
+
entryPrice: s,
|
|
37
|
+
positionValueUsd: u == null || a == null ? null : i(u) * a,
|
|
38
|
+
entryValueUsd: u == null || s == null ? null : i(u * s / 10n ** 18n),
|
|
39
|
+
leverageMultiplier: d,
|
|
40
|
+
upnlUsd: p ? Number(p.upnl) : null,
|
|
41
|
+
priceChangePercent: p && u != null && u > 0n && s != null ? Number(p.upnl) / (i(u) * i(s)) * 100 : null,
|
|
42
|
+
liquidationPrice: x,
|
|
43
|
+
liquidationSource: y == null ? b == null ? null : "quote-lock" : "account",
|
|
44
|
+
openedAt: [
|
|
45
|
+
o.timestampOpenPosition,
|
|
46
|
+
o.timestampSendQuote,
|
|
47
|
+
o.timestamp
|
|
48
|
+
].find((e) => e != null && e > 0) ?? null
|
|
49
|
+
};
|
|
50
|
+
}),
|
|
51
|
+
gaps: [...n.gaps ?? []]
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
function c(e, t) {
|
|
55
|
+
if (e.leverage != null && e.leverage > 0n) return i(e.leverage);
|
|
56
|
+
if (e.initialCva == null || e.initialLf == null || e.initialPartyAmm == null) return null;
|
|
57
|
+
let r = e.initialCva + e.initialLf + e.initialPartyAmm;
|
|
58
|
+
if (r <= 0n) return null;
|
|
59
|
+
if (e.initialLf > 0n) return Math.max(1, Math.round(Number(e.initialLf * 100n * 10n ** 18n / r) / 0xde0b6b3a7640000));
|
|
60
|
+
if (e.quantity == null || e.quantity <= 0n || t == null) return null;
|
|
61
|
+
let a = (t) => Number(n({
|
|
62
|
+
quantity: e.quantity,
|
|
63
|
+
openedPrice: t,
|
|
64
|
+
requestedOpenPrice: t,
|
|
65
|
+
lockedValues: {
|
|
66
|
+
cva: e.initialCva,
|
|
67
|
+
lf: e.initialLf,
|
|
68
|
+
partyAmm: e.initialPartyAmm,
|
|
69
|
+
partyBmm: 0n
|
|
70
|
+
}
|
|
71
|
+
})), o = a(t), s = e.requestedOpenPrice != null && e.requestedOpenPrice > 0n ? a(e.requestedOpenPrice) : o;
|
|
72
|
+
return Math.max(1, Math.round(Math.abs(s - Math.round(s)) < Math.abs(o - Math.round(o)) ? s : o));
|
|
73
|
+
}
|
|
74
|
+
function l(t, n, r, i) {
|
|
75
|
+
let s = t.quantity != null && t.quantity > 0n && t.initialPartyAmm != null && t.initialPartyAmm > 0n ? t.initialPartyAmm * 10n ** 18n / t.quantity : r != null && Number.isFinite(r) && r > 0 ? n * 10n ** 18n / a(o(r).toFixed(), 18) : null;
|
|
76
|
+
if (s == null) return null;
|
|
77
|
+
let c = i === e.SHORT ? n + s : n - s;
|
|
78
|
+
return c > 0n ? c : 0n;
|
|
79
|
+
}
|
|
80
|
+
//#endregion
|
|
81
|
+
export { s as calculatePoolOpenPositions };
|
|
82
|
+
|
|
83
|
+
//# sourceMappingURL=calculate-pool-open-positions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"calculate-pool-open-positions.js","names":[],"sources":["../../../src/pools/open-positions/calculate-pool-open-positions.ts"],"sourcesContent":["import { toDecimal } from \"@symmio/utils\";\nimport { parseUnits } from \"viem\";\nimport { calculateLiquidationPrice } from \"../../quotes/liquidation/calculate-liquidation-price\";\nimport { calculateQuoteLeverage } from \"../../quotes/upnl/calculate-quote-leverage\";\nimport { calculateQuoteUpnl } from \"../../quotes/upnl/calculate-quote-upnl\";\nimport type { AccountBalanceInfo } from \"../../symmio-contracts/account-layer/types\";\nimport { PositionType } from \"../../symmio-contracts/symmio/types\";\nimport { units, type PoolReadGap } from \"../composition\";\nimport type { PoolQuote } from \"../types\";\n\n/** Normalized quote and account reads for the pool's open positions. */\nexport interface CalculatePoolOpenPositionsParameters {\n quotes: readonly Partial<PoolQuote>[];\n balances: Readonly<\n Record<\n string,\n Pick<\n AccountBalanceInfo,\n \"allocatedBalance\" | \"lockedCVA\" | \"lockedLF\" | \"pendingLockedCVA\" | \"pendingLockedLF\"\n > | null\n >\n >;\n /** External/current mark price in USD. Omit when unknown. */\n priceUsd?: number;\n /** Set false when quotes are only a page; incomplete accounts cannot yield liquidation estimates. */\n complete?: boolean;\n /** Opt in to a quote-lock estimate when account liquidation is unavailable. */\n allowQuoteLockEstimate?: boolean;\n gaps?: readonly PoolReadGap[];\n}\n\n/** Calculate table metrics using the shared SDK quote primitives.\n * @param input - SDK quotes, account balances and optional mark price.\n * @returns Quote fields plus metrics; priceChangePercent is deliberately unleveraged.\n */\nexport function calculatePoolOpenPositions<TQuote extends Partial<PoolQuote>>(\n input: Omit<CalculatePoolOpenPositionsParameters, \"quotes\"> & { quotes: readonly TQuote[] },\n) {\n const price =\n input.priceUsd != null && Number.isFinite(input.priceUsd) && input.priceUsd >= 0 ? input.priceUsd : null;\n const entries = input.quotes.map((quote) => {\n const openedPrice =\n [quote.openedPrice, quote.initialOpenedPrice, quote.requestedOpenPrice].find(\n (value) => value != null && value > 0n,\n ) ?? null;\n const quantity =\n quote.quantity == null || quote.closedAmount == null\n ? null\n : quote.quantity > quote.closedAmount\n ? quote.quantity - quote.closedAmount\n : 0n;\n const leverage = poolLeverage(quote, openedPrice);\n const positionType =\n quote.positionType === PositionType.SHORT || quote.positionType === PositionType.LONG ? quote.positionType : null;\n const pnl =\n price == null || openedPrice == null || quantity == null || positionType == null\n ? null\n : calculateQuoteUpnl({\n markPrice: String(price),\n positionType,\n quantity,\n closedAmount: 0n,\n openedPrice,\n leverage: \"1\",\n });\n const account = quote.partyA?.toLowerCase();\n const balance = account == null ? null : input.balances[account];\n const accountQuotes = account == null ? [] : input.quotes.filter((row) => row.partyA?.toLowerCase() === account);\n const positions = accountQuotes.flatMap((row) =>\n row.quantity == null || row.closedAmount == null || row.openedPrice == null\n ? []\n : [{ quantity: row.quantity, closedAmount: row.closedAmount, openedPrice: row.openedPrice }],\n );\n const compatible = accountQuotes.every(\n (row) => row.symbolId === quote.symbolId && Number(row.positionType) === Number(quote.positionType),\n );\n const accountLiquidation =\n balance &&\n positionType != null &&\n input.complete !== false &&\n compatible &&\n accountQuotes.length > 0 &&\n positions.length === accountQuotes.length\n ? calculateLiquidationPrice({ ...balance, positions, positionType })\n : null;\n const lockEstimate =\n input.allowQuoteLockEstimate && positionType != null && openedPrice != null && quantity != null && quantity > 0n\n ? quoteLockLiquidation(quote, openedPrice, leverage, positionType)\n : null;\n const liquidationPrice = accountLiquidation ?? lockEstimate;\n return {\n ...quote,\n remainingQuantity: quantity,\n entryPrice: openedPrice,\n positionValueUsd: quantity == null || price == null ? null : units(quantity)! * price,\n entryValueUsd: quantity == null || openedPrice == null ? null : units((quantity * openedPrice) / 10n ** 18n),\n leverageMultiplier: leverage,\n upnlUsd: pnl ? Number(pnl.upnl) : null,\n // The shared helper's percent is display-rounded. This read exposes the unrounded notional return.\n priceChangePercent:\n pnl && quantity != null && quantity > 0n && openedPrice != null\n ? (Number(pnl.upnl) / (units(quantity)! * units(openedPrice)!)) * 100\n : null,\n liquidationPrice,\n liquidationSource:\n accountLiquidation != null ? (\"account\" as const) : lockEstimate != null ? (\"quote-lock\" as const) : null,\n openedAt:\n [quote.timestampOpenPosition, quote.timestampSendQuote, quote.timestamp].find(\n (value) => value != null && value > 0,\n ) ?? null,\n };\n });\n return { entries, gaps: [...(input.gaps ?? [])] };\n}\n/** Pool open-position table projection. */\nexport type PoolOpenPositions = ReturnType<typeof calculatePoolOpenPositions<PoolQuote>>;\n\n/** Preserve the pool table's legacy integer leverage inference when the backend omits leverage. */\nfunction poolLeverage(quote: Partial<PoolQuote>, openedPrice: bigint | null): number | null {\n if (quote.leverage != null && quote.leverage > 0n) return units(quote.leverage);\n if (quote.initialCva == null || quote.initialLf == null || quote.initialPartyAmm == null) return null;\n const margin = quote.initialCva + quote.initialLf + quote.initialPartyAmm;\n if (margin <= 0n) return null;\n if (quote.initialLf > 0n)\n return Math.max(1, Math.round(Number((quote.initialLf * 100n * 10n ** 18n) / margin) / 1e18));\n if (quote.quantity == null || quote.quantity <= 0n || openedPrice == null) return null;\n const candidate = (price: bigint) =>\n Number(\n calculateQuoteLeverage({\n quantity: quote.quantity!,\n openedPrice: price,\n requestedOpenPrice: price,\n lockedValues: { cva: quote.initialCva!, lf: quote.initialLf!, partyAmm: quote.initialPartyAmm!, partyBmm: 0n },\n }),\n );\n const opened = candidate(openedPrice);\n const requested =\n quote.requestedOpenPrice != null && quote.requestedOpenPrice > 0n ? candidate(quote.requestedOpenPrice) : opened;\n return Math.max(\n 1,\n Math.round(\n Math.abs(requested - Math.round(requested)) < Math.abs(opened - Math.round(opened)) ? requested : opened,\n ),\n );\n}\n\n/** Historical quote-lock estimate, explicitly separate from live account collateral. */\nfunction quoteLockLiquidation(\n quote: Partial<PoolQuote>,\n price: bigint,\n leverage: number | null,\n side: PositionType,\n): bigint | null {\n const marginPerToken =\n quote.quantity != null && quote.quantity > 0n && quote.initialPartyAmm != null && quote.initialPartyAmm > 0n\n ? (quote.initialPartyAmm * 10n ** 18n) / quote.quantity\n : leverage != null && Number.isFinite(leverage) && leverage > 0\n ? (price * 10n ** 18n) / parseUnits(toDecimal(leverage).toFixed(), 18)\n : null;\n if (marginPerToken == null) return null;\n const result = side === PositionType.SHORT ? price + marginPerToken : price - marginPerToken;\n return result > 0n ? result : 0n;\n}\n"],"mappings":";;;;;;;;AAmCA,SAAgB,EACd,GACA;CACA,IAAM,IACJ,EAAM,YAAY,QAAQ,OAAO,SAAS,EAAM,QAAQ,KAAK,EAAM,YAAY,IAAI,EAAM,WAAW;CAyEtG,OAAO;EAAE,SAxEO,EAAM,OAAO,KAAK,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CACH,GACI,IAAS,EAAU,CAAW,GAC9B,IACJ,EAAM,sBAAsB,QAAQ,EAAM,qBAAqB,KAAK,EAAU,EAAM,kBAAkB,IAAI;CAC5G,OAAO,KAAK,IACV,GACA,KAAK,MACH,KAAK,IAAI,IAAY,KAAK,MAAM,CAAS,CAAC,IAAI,KAAK,IAAI,IAAS,KAAK,MAAM,CAAM,CAAC,IAAI,IAAY,CACpG,CACF;AACF;AAGA,SAAS,EACP,GACA,GACA,GACA,GACe;CACf,IAAM,IACJ,EAAM,YAAY,QAAQ,EAAM,WAAW,MAAM,EAAM,mBAAmB,QAAQ,EAAM,kBAAkB,KACrG,EAAM,kBAAkB,OAAO,MAAO,EAAM,WAC7C,KAAY,QAAQ,OAAO,SAAS,CAAQ,KAAK,IAAW,IACzD,IAAQ,OAAO,MAAO,EAAW,EAAU,CAAQ,EAAE,QAAQ,GAAG,EAAE,IACnE;CACR,IAAI,KAAkB,MAAM,OAAO;CACnC,IAAM,IAAS,MAAS,EAAa,QAAQ,IAAQ,IAAiB,IAAQ;CAC9E,OAAO,IAAS,KAAK,IAAS;AAChC"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Config } from '../../core/config/index.js';
|
|
2
|
+
import { GetPoolQuotesParameters } from '../quotes/get-pool-quotes.js';
|
|
3
|
+
import { PoolOpenPositions } from './calculate-pool-open-positions.js';
|
|
4
|
+
/** Read a bounded complete open book; caller filtering/paging follows calculation. */
|
|
5
|
+
export type GetPoolOpenPositionsParameters = Pick<GetPoolQuotesParameters, "chainId" | "symbolId" | "orderDirection"> & {
|
|
6
|
+
priceUsd?: number;
|
|
7
|
+
allowQuoteLockEstimate?: boolean;
|
|
8
|
+
};
|
|
9
|
+
/** Result of getPoolOpenPositions. */
|
|
10
|
+
export type GetPoolOpenPositionsReturnType = PoolOpenPositions;
|
|
11
|
+
/** Read open quotes and deduplicated account balances before deriving table metrics.
|
|
12
|
+
* @param config - SDK configuration.
|
|
13
|
+
* @param parameters - Market identity and optional external mark price.
|
|
14
|
+
* @returns Open positions and source gaps; incomplete books have no liquidation estimate.
|
|
15
|
+
*/
|
|
16
|
+
export declare function getPoolOpenPositions(config: Config, parameters: GetPoolOpenPositionsParameters): Promise<PoolOpenPositions>;
|
|
17
|
+
//# sourceMappingURL=get-pool-open-positions.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"get-pool-open-positions.d.ts","sourceRoot":"","sources":["../../../src/pools/open-positions/get-pool-open-positions.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAGhD,OAAO,EAA2C,KAAK,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAClH,OAAO,EAA8B,KAAK,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AAErG,sFAAsF;AACtF,MAAM,MAAM,8BAA8B,GAAG,IAAI,CAC/C,uBAAuB,EACvB,SAAS,GAAG,UAAU,GAAG,gBAAgB,CAC1C,GAAG;IAAE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAAC,sBAAsB,CAAC,EAAE,OAAO,CAAA;CAAE,CAAC;AAC5D,sCAAsC;AACtC,MAAM,MAAM,8BAA8B,GAAG,iBAAiB,CAAC;AAE/D;;;;GAIG;AACH,wBAAsB,oBAAoB,CACxC,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,8BAA8B,GACzC,OAAO,CAAC,iBAAiB,CAAC,CA0C5B"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { getAccountBalanceInfo as e } from "../../symmio-contracts/account-layer/actions/get-account-balance-info.js";
|
|
2
|
+
import { readOptional as t, readPages as n } from "../composition.js";
|
|
3
|
+
import { calculatePoolOpenPositions as r } from "./calculate-pool-open-positions.js";
|
|
4
|
+
import { POOL_OPEN_QUOTE_STATUSES as i, getPoolQuotes as a } from "../quotes/get-pool-quotes.js";
|
|
5
|
+
//#region src/pools/open-positions/get-pool-open-positions.ts
|
|
6
|
+
async function o(o, s) {
|
|
7
|
+
let c = [], l = await n(async (e) => {
|
|
8
|
+
let t = await a(o, {
|
|
9
|
+
chainId: s.chainId,
|
|
10
|
+
symbolId: s.symbolId,
|
|
11
|
+
orderDirection: s.orderDirection,
|
|
12
|
+
quoteStatuses: i,
|
|
13
|
+
first: 100,
|
|
14
|
+
skip: e
|
|
15
|
+
});
|
|
16
|
+
return {
|
|
17
|
+
items: t.quotes,
|
|
18
|
+
total: t.quotes.length < 100 ? e + t.quotes.length : 2 ** 53 - 1
|
|
19
|
+
};
|
|
20
|
+
}, (e) => e.id, c, "quotes"), u = {}, d = [...new Set(l.map((e) => e.partyA.toLowerCase()))];
|
|
21
|
+
for (let n = 0; n < d.length; n += 8) await Promise.all(d.slice(n, n + 8).map(async (n) => {
|
|
22
|
+
u[n] = await t(() => e(o, {
|
|
23
|
+
chainId: s.chainId,
|
|
24
|
+
account: n
|
|
25
|
+
}), c, "accountBalance", n);
|
|
26
|
+
}));
|
|
27
|
+
return r({
|
|
28
|
+
quotes: l,
|
|
29
|
+
balances: u,
|
|
30
|
+
priceUsd: s.priceUsd,
|
|
31
|
+
allowQuoteLockEstimate: s.allowQuoteLockEstimate,
|
|
32
|
+
complete: !c.some((e) => e.source === "quotes"),
|
|
33
|
+
gaps: c
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
//#endregion
|
|
37
|
+
export { o as getPoolOpenPositions };
|
|
38
|
+
|
|
39
|
+
//# sourceMappingURL=get-pool-open-positions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"get-pool-open-positions.js","names":[],"sources":["../../../src/pools/open-positions/get-pool-open-positions.ts"],"sourcesContent":["import type { Address } from \"viem\";\nimport type { Config } from \"../../core/config\";\nimport { getAccountBalanceInfo } from \"../../symmio-contracts/account-layer/actions/get-account-balance-info\";\nimport { readOptional, readPages, type PoolReadGap } from \"../composition\";\nimport { getPoolQuotes, POOL_OPEN_QUOTE_STATUSES, type GetPoolQuotesParameters } from \"../quotes/get-pool-quotes\";\nimport { calculatePoolOpenPositions, type PoolOpenPositions } from \"./calculate-pool-open-positions\";\n\n/** Read a bounded complete open book; caller filtering/paging follows calculation. */\nexport type GetPoolOpenPositionsParameters = Pick<\n GetPoolQuotesParameters,\n \"chainId\" | \"symbolId\" | \"orderDirection\"\n> & { priceUsd?: number; allowQuoteLockEstimate?: boolean };\n/** Result of getPoolOpenPositions. */\nexport type GetPoolOpenPositionsReturnType = PoolOpenPositions;\n\n/** Read open quotes and deduplicated account balances before deriving table metrics.\n * @param config - SDK configuration.\n * @param parameters - Market identity and optional external mark price.\n * @returns Open positions and source gaps; incomplete books have no liquidation estimate.\n */\nexport async function getPoolOpenPositions(\n config: Config,\n parameters: GetPoolOpenPositionsParameters,\n): Promise<PoolOpenPositions> {\n const gaps: PoolReadGap[] = [];\n const quotes = await readPages(\n async (skip) => {\n const page = await getPoolQuotes(config, {\n chainId: parameters.chainId,\n symbolId: parameters.symbolId,\n orderDirection: parameters.orderDirection,\n quoteStatuses: POOL_OPEN_QUOTE_STATUSES,\n first: 100,\n skip,\n });\n return {\n items: page.quotes,\n total: page.quotes.length < 100 ? skip + page.quotes.length : Number.MAX_SAFE_INTEGER,\n };\n },\n (row) => row.id,\n gaps,\n \"quotes\",\n );\n const balances: Record<string, Awaited<ReturnType<typeof getAccountBalanceInfo>> | null> = {};\n const accounts = [...new Set(quotes.map((row) => row.partyA.toLowerCase()))];\n for (let offset = 0; offset < accounts.length; offset += 8)\n await Promise.all(\n accounts.slice(offset, offset + 8).map(async (account) => {\n balances[account] = await readOptional(\n () => getAccountBalanceInfo(config, { chainId: parameters.chainId, account: account as Address }),\n gaps,\n \"accountBalance\",\n account,\n );\n }),\n );\n return calculatePoolOpenPositions({\n quotes,\n balances,\n priceUsd: parameters.priceUsd,\n allowQuoteLockEstimate: parameters.allowQuoteLockEstimate,\n complete: !gaps.some((gap) => gap.source === \"quotes\"),\n gaps,\n });\n}\n"],"mappings":";;;;;AAoBA,eAAsB,EACpB,GACA,GAC4B;CAC5B,IAAM,IAAsB,CAAC,GACvB,IAAS,MAAM,EACnB,OAAO,MAAS;EACd,IAAM,IAAO,MAAM,EAAc,GAAQ;GACvC,SAAS,EAAW;GACpB,UAAU,EAAW;GACrB,gBAAgB,EAAW;GAC3B,eAAe;GACf,OAAO;GACP;EACF,CAAC;EACD,OAAO;GACL,OAAO,EAAK;GACZ,OAAO,EAAK,OAAO,SAAS,MAAM,IAAO,EAAK,OAAO;EACvD;CACF,IACC,MAAQ,EAAI,IACb,GACA,QACF,GACM,IAAqF,CAAC,GACtF,IAAW,CAAC,GAAG,IAAI,IAAI,EAAO,KAAK,MAAQ,EAAI,OAAO,YAAY,CAAC,CAAC,CAAC;CAC3E,KAAK,IAAI,IAAS,GAAG,IAAS,EAAS,QAAQ,KAAU,GACvD,MAAM,QAAQ,IACZ,EAAS,MAAM,GAAQ,IAAS,CAAC,EAAE,IAAI,OAAO,MAAY;EACxD,EAAS,KAAW,MAAM,QAClB,EAAsB,GAAQ;GAAE,SAAS,EAAW;GAAkB;EAAmB,CAAC,GAChG,GACA,kBACA,CACF;CACF,CAAC,CACH;CACF,OAAO,EAA2B;EAChC;EACA;EACA,UAAU,EAAW;EACrB,wBAAwB,EAAW;EACnC,UAAU,CAAC,EAAK,MAAM,MAAQ,EAAI,WAAW,QAAQ;EACrD;CACF,CAAC;AACH"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/pools/open-positions/index.ts"],"names":[],"mappings":"AAAA,cAAc,iCAAiC,CAAC;AAChD,cAAc,2BAA2B,CAAC;AAC1C,cAAc,SAAS,CAAC"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Config } from '../../core/config/index.js';
|
|
2
|
+
import { Compute, ConfigKeyParameter } from '../../shared/types/properties.js';
|
|
3
|
+
import { QueryParameter, SymmioQueryOptions } from '../../shared/types/query.js';
|
|
4
|
+
import { GetPoolOpenPositionsParameters, GetPoolOpenPositionsReturnType } from './get-pool-open-positions.js';
|
|
5
|
+
/** Stable key for the composed core read. Credentials are excluded. */
|
|
6
|
+
export declare function getPoolOpenPositionsQueryKey(options: Compute<GetPoolOpenPositionsParameters & ConfigKeyParameter>): readonly ["getPoolOpenPositions", Record<string, unknown>];
|
|
7
|
+
/** Composed query key type. */
|
|
8
|
+
export type GetPoolOpenPositionsQueryKey = ReturnType<typeof getPoolOpenPositionsQueryKey>;
|
|
9
|
+
/** Query controls plus all required read inputs. */
|
|
10
|
+
export type GetPoolOpenPositionsOptions = GetPoolOpenPositionsParameters & QueryParameter<GetPoolOpenPositionsReturnType, Error, GetPoolOpenPositionsReturnType, GetPoolOpenPositionsQueryKey>;
|
|
11
|
+
/** Build options for non-React consumers; React composition uses the underlying primitive queries instead.
|
|
12
|
+
* @param config - SDK configuration.
|
|
13
|
+
* @param options - Required read inputs and optional query controls.
|
|
14
|
+
* @returns Typed query options with a credential-free key.
|
|
15
|
+
*/
|
|
16
|
+
export declare function getPoolOpenPositionsQueryOptions(config: Config, options: GetPoolOpenPositionsOptions): SymmioQueryOptions<GetPoolOpenPositionsReturnType, Error, GetPoolOpenPositionsReturnType, GetPoolOpenPositionsQueryKey>;
|
|
17
|
+
//# sourceMappingURL=query.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"query.d.ts","sourceRoot":"","sources":["../../../src/pools/open-positions/query.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,KAAK,EAAE,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AACjF,OAAO,KAAK,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAEnF,OAAO,EAEL,KAAK,8BAA8B,EACnC,KAAK,8BAA8B,EACpC,MAAM,2BAA2B,CAAC;AACnC,uEAAuE;AACvE,wBAAgB,4BAA4B,CAAC,OAAO,EAAE,OAAO,CAAC,8BAA8B,GAAG,kBAAkB,CAAC,8DAEjH;AACD,+BAA+B;AAC/B,MAAM,MAAM,4BAA4B,GAAG,UAAU,CAAC,OAAO,4BAA4B,CAAC,CAAC;AAC3F,oDAAoD;AACpD,MAAM,MAAM,2BAA2B,GAAG,8BAA8B,GACtE,cAAc,CAAC,8BAA8B,EAAE,KAAK,EAAE,8BAA8B,EAAE,4BAA4B,CAAC,CAAC;AACtH;;;;GAIG;AACH,wBAAgB,gCAAgC,CAC9C,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,2BAA2B,GACnC,kBAAkB,CACnB,8BAA8B,EAC9B,KAAK,EACL,8BAA8B,EAC9B,4BAA4B,CAC7B,CAOA"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { filterQueryOptions as e } from "../../shared/utils/query.js";
|
|
2
|
+
import { getPoolOpenPositions as t } from "./get-pool-open-positions.js";
|
|
3
|
+
//#region src/pools/open-positions/query.ts
|
|
4
|
+
function n(t) {
|
|
5
|
+
return ["getPoolOpenPositions", e(t)];
|
|
6
|
+
}
|
|
7
|
+
function r(e, r) {
|
|
8
|
+
return {
|
|
9
|
+
...r.query,
|
|
10
|
+
queryKey: n({
|
|
11
|
+
...r,
|
|
12
|
+
configKey: e.getChainConfigKey(r.chainId)
|
|
13
|
+
}),
|
|
14
|
+
enabled: r.query?.enabled ?? !0,
|
|
15
|
+
queryFn: () => t(e, r)
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
//#endregion
|
|
19
|
+
export { n as getPoolOpenPositionsQueryKey, r as getPoolOpenPositionsQueryOptions };
|
|
20
|
+
|
|
21
|
+
//# sourceMappingURL=query.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"query.js","names":[],"sources":["../../../src/pools/open-positions/query.ts"],"sourcesContent":["import type { Config } from \"../../core/config\";\nimport type { Compute, ConfigKeyParameter } from \"../../shared/types/properties\";\nimport type { QueryParameter, SymmioQueryOptions } from \"../../shared/types/query\";\nimport { filterQueryOptions } from \"../../shared/utils/query\";\nimport {\n getPoolOpenPositions,\n type GetPoolOpenPositionsParameters,\n type GetPoolOpenPositionsReturnType,\n} from \"./get-pool-open-positions\";\n/** Stable key for the composed core read. Credentials are excluded. */\nexport function getPoolOpenPositionsQueryKey(options: Compute<GetPoolOpenPositionsParameters & ConfigKeyParameter>) {\n return [\"getPoolOpenPositions\", filterQueryOptions(options)] as const;\n}\n/** Composed query key type. */\nexport type GetPoolOpenPositionsQueryKey = ReturnType<typeof getPoolOpenPositionsQueryKey>;\n/** Query controls plus all required read inputs. */\nexport type GetPoolOpenPositionsOptions = GetPoolOpenPositionsParameters &\n QueryParameter<GetPoolOpenPositionsReturnType, Error, GetPoolOpenPositionsReturnType, GetPoolOpenPositionsQueryKey>;\n/** Build options for non-React consumers; React composition uses the underlying primitive queries instead.\n * @param config - SDK configuration.\n * @param options - Required read inputs and optional query controls.\n * @returns Typed query options with a credential-free key.\n */\nexport function getPoolOpenPositionsQueryOptions(\n config: Config,\n options: GetPoolOpenPositionsOptions,\n): SymmioQueryOptions<\n GetPoolOpenPositionsReturnType,\n Error,\n GetPoolOpenPositionsReturnType,\n GetPoolOpenPositionsQueryKey\n> {\n return {\n ...options.query,\n queryKey: getPoolOpenPositionsQueryKey({ ...options, configKey: config.getChainConfigKey(options.chainId) }),\n enabled: options.query?.enabled ?? true,\n queryFn: () => getPoolOpenPositions(config, options),\n };\n}\n"],"mappings":";;;AAUA,SAAgB,EAA6B,GAAuE;CAClH,OAAO,CAAC,wBAAwB,EAAmB,CAAO,CAAC;AAC7D;AAWA,SAAgB,EACd,GACA,GAMA;CACA,OAAO;EACL,GAAG,EAAQ;EACX,UAAU,EAA6B;GAAE,GAAG;GAAS,WAAW,EAAO,kBAAkB,EAAQ,OAAO;EAAE,CAAC;EAC3G,SAAS,EAAQ,OAAO,WAAW;EACnC,eAAe,EAAqB,GAAQ,CAAO;CACrD;AACF"}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { PoolReadGap } from '../composition.js';
|
|
2
|
+
import { PoolPositionData } from '../position/calculate-pool-position.js';
|
|
3
|
+
import { ListingMarketDetail, UserListingMarket, UserPoolProfit, UserTransaction } from '../types.js';
|
|
4
|
+
/** Pool identity and an optional third-party price, supplied by the consumer. */
|
|
5
|
+
export interface PoolPortfolioPrice {
|
|
6
|
+
tokenContractAddress: string;
|
|
7
|
+
depositChain: number;
|
|
8
|
+
priceUsd: number;
|
|
9
|
+
}
|
|
10
|
+
/** Flat portfolio row. Stake fields have exactly the position read's semantics. */
|
|
11
|
+
export interface PoolPortfolioPosition extends PoolPositionData {
|
|
12
|
+
tokenContractAddress: string;
|
|
13
|
+
depositChain: number;
|
|
14
|
+
/** Original normalized catalog snapshot, including rates, flags and ownership metadata. */
|
|
15
|
+
market: UserListingMarket | null;
|
|
16
|
+
/** Positive deposit observed in history or catalog; null when incomplete history cannot establish absence. */
|
|
17
|
+
hasDeposit: boolean | null;
|
|
18
|
+
tokenName: string | null;
|
|
19
|
+
tokenTicker: string | null;
|
|
20
|
+
apr: number | null;
|
|
21
|
+
}
|
|
22
|
+
/** Portfolio values before any consumer filtering or pagination. */
|
|
23
|
+
export interface PoolPortfolio {
|
|
24
|
+
entries: PoolPortfolioPosition[];
|
|
25
|
+
totalBalanceUsd: number | null;
|
|
26
|
+
totalDepositedUsd: number | null;
|
|
27
|
+
claimableRewardUsd: number | null;
|
|
28
|
+
claimedRewardUsd: number | null;
|
|
29
|
+
rewardWindowUsd: number | null;
|
|
30
|
+
averageApr: number | null;
|
|
31
|
+
/** ROI over the same fully priced positions on both sides. Null when no comparable deposits exist. */
|
|
32
|
+
roiPercent: number | null;
|
|
33
|
+
/** Partial known-value totals; consult totalBalanceUsd/totalDepositedUsd for source completeness. */
|
|
34
|
+
knownBalanceUsd: number;
|
|
35
|
+
knownDepositedUsd: number;
|
|
36
|
+
knownValueRoiPercent: number | null;
|
|
37
|
+
/** Historical claimed plus claimable rewards, including positions no longer held. */
|
|
38
|
+
lifetimeRewardsUsd: number | null;
|
|
39
|
+
gaps: PoolReadGap[];
|
|
40
|
+
}
|
|
41
|
+
/** Normalized reads for portfolio assembly; no wire strings or generated vendor types. */
|
|
42
|
+
export interface CalculatePoolPortfolioParameters {
|
|
43
|
+
listed: readonly UserListingMarket[];
|
|
44
|
+
nonListed: readonly UserListingMarket[];
|
|
45
|
+
deposits: readonly UserTransaction[] | null;
|
|
46
|
+
positions: readonly {
|
|
47
|
+
tokenContractAddress: string;
|
|
48
|
+
depositChain: number;
|
|
49
|
+
profit: Partial<UserPoolProfit> | null;
|
|
50
|
+
detail: ListingMarketDetail | null;
|
|
51
|
+
}[];
|
|
52
|
+
prices?: readonly PoolPortfolioPrice[];
|
|
53
|
+
reward: bigint | null;
|
|
54
|
+
/** Optional complete historical reward ledger. Values include any consumer optimistic projection. */
|
|
55
|
+
rewardPositions?: readonly {
|
|
56
|
+
claimed: bigint | null;
|
|
57
|
+
claimable: bigint | null;
|
|
58
|
+
}[];
|
|
59
|
+
gaps?: readonly PoolReadGap[];
|
|
60
|
+
}
|
|
61
|
+
/** Assemble holdings and totals from SDK reads; filtering and top-earner selection remain consumer-owned.
|
|
62
|
+
* @param input - Normalized source snapshots and explicit read gaps.
|
|
63
|
+
* @returns Rows with exact stake amounts, USD totals and completeness information.
|
|
64
|
+
*/
|
|
65
|
+
export declare function calculatePoolPortfolio(input: CalculatePoolPortfolioParameters): PoolPortfolio;
|
|
66
|
+
//# sourceMappingURL=calculate-pool-portfolio.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"calculate-pool-portfolio.d.ts","sourceRoot":"","sources":["../../../src/pools/portfolio/calculate-pool-portfolio.ts"],"names":[],"mappings":"AAAA,OAAO,EAAS,KAAK,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAEzD,OAAO,EAAyB,KAAK,gBAAgB,EAAE,MAAM,qCAAqC,CAAC;AACnG,OAAO,EAEL,KA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D,0FAA0F;AAC1F,MAAM,WAAW,gCAAgC;IAC/C,MAAM,EAAE,SAAS,iBAAiB,EAAE,CAAC;IACrC,SAAS,EAAE,SAAS,iBAAiB,EAAE,CAAC;IACxC,QAAQ,EAAE,SAAS,eAAe,EAAE,GAAG,IAAI,CAAC;IAC5C,SAAS,EAAE,SAAS;QAClB,oBAAoB,EAAE,MAAM,CAAC;QAC7B,YAAY,EAAE,MAAM,CAAC;QACrB,MAAM,EAAE,OAAO,CAAC,cAAc,CAAC,GAAG,IAAI,CAAC;QACvC,MAAM,EAAE,mBAAmB,GAAG,IAAI,CAAC;KACpC,EAAE,CAAC;IACJ,MAAM,CAAC,EAAE,SAAS,kBAAkB,EAAE,CAAC;IACvC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,qGAAqG;IACrG,eAAe,CAAC,EAAE,SAAS;QAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;QAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,EAAE,CAAC;IAClF,IAAI,CAAC,EAAE,SAAS,WAAW,EAAE,CAAC;CAC/B;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,gCAAgC,GAAG,aAAa,CAkJ7F"}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { ListingMarketStatus as e } from "../types.js";
|
|
2
|
+
import { units as t } from "../composition.js";
|
|
3
|
+
import { emptyPoolProfit as n } from "../empty-pool-profit.js";
|
|
4
|
+
import { calculatePoolPosition as r } from "../position/calculate-pool-position.js";
|
|
5
|
+
//#region src/pools/portfolio/calculate-pool-portfolio.ts
|
|
6
|
+
function i(i) {
|
|
7
|
+
let a = [...i.gaps ?? []], o = [...i.listed, ...i.nonListed], s = /* @__PURE__ */ new Map();
|
|
8
|
+
for (let e of o) {
|
|
9
|
+
let t = `${e.chainId}:${e.contractAddress.toLowerCase()}`, n = s.get(t) ?? /* @__PURE__ */ new Set();
|
|
10
|
+
n.add(e.contractAddress), s.set(t, n);
|
|
11
|
+
}
|
|
12
|
+
function c(e, t) {
|
|
13
|
+
let n = `${t}:${e.toLowerCase()}`;
|
|
14
|
+
return t === 0 && (s.get(n)?.size ?? 0) > 1 ? `${t}:${e}` : n;
|
|
15
|
+
}
|
|
16
|
+
let l = new Map(o.map((e) => [c(e.contractAddress, e.chainId), e])), u = /* @__PURE__ */ new Map();
|
|
17
|
+
for (let e of i.deposits ?? []) {
|
|
18
|
+
if (e.type !== "deposit") continue;
|
|
19
|
+
let t = c(e.tokenAddress, e.chainId);
|
|
20
|
+
e.chainId === 0 && (s.get(`${e.chainId}:${e.tokenAddress.toLowerCase()}`)?.size ?? 0) > 1 && !l.has(t) && a.push({
|
|
21
|
+
source: "deposits",
|
|
22
|
+
tokenContractAddress: e.tokenAddress,
|
|
23
|
+
reason: "ambiguous-address"
|
|
24
|
+
}), u.set(t, [...u.get(t) ?? [], e]);
|
|
25
|
+
}
|
|
26
|
+
let d = new Map([...i.listed, ...i.nonListed.filter((e) => (e.userDeposit ?? 0n) > 0n)].map((e) => [c(e.contractAddress, e.chainId), {
|
|
27
|
+
address: e.contractAddress,
|
|
28
|
+
chain: e.chainId
|
|
29
|
+
}]));
|
|
30
|
+
for (let [e, t] of u) if (!d.has(e)) {
|
|
31
|
+
let n = l.get(e);
|
|
32
|
+
d.set(e, {
|
|
33
|
+
address: n?.contractAddress ?? t[0].tokenAddress,
|
|
34
|
+
chain: t[0].chainId
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
let f = [...d].map(([o, s]) => {
|
|
38
|
+
let d = l.get(o), f = i.positions.find((e) => c(e.tokenContractAddress, e.depositChain) === o), p = i.prices?.find((e) => c(e.tokenContractAddress, e.depositChain) === o), m = i.deposits != null && !a.some((e) => e.source === "deposits"), h = (d?.userDeposit ?? 0n) > 0n || (u.get(o) ?? []).some((e) => e.amount > 0n), g = d != null && d.marketStatus !== e.LISTED || m && !h, _ = a.filter((e) => e.tokenContractAddress != null && c(e.tokenContractAddress, s.chain) === o), v = _.some((e) => e.source === "profit" && e.reason === "failed"), y = v ? null : f?.profit ?? (g ? n() : null), b = (v ? void 0 : f?.profit?.userDepositedTokenAmount) ?? d?.userDeposit, x = r({
|
|
39
|
+
tokenContractAddress: s.address,
|
|
40
|
+
depositChain: s.chain,
|
|
41
|
+
detail: f?.detail ?? null,
|
|
42
|
+
profit: y,
|
|
43
|
+
userSharePercentage: d?.userSharePercentage,
|
|
44
|
+
deposits: i.deposits == null ? null : u.get(o) ?? [],
|
|
45
|
+
depositsComplete: !a.some((e) => e.source === "deposits"),
|
|
46
|
+
depositHistory: m && !u.has(o) && b != null ? {
|
|
47
|
+
pending: 0n,
|
|
48
|
+
transferred: 0n,
|
|
49
|
+
success: b,
|
|
50
|
+
rejected: 0n,
|
|
51
|
+
refund: 0n
|
|
52
|
+
} : void 0,
|
|
53
|
+
priceUsd: p?.priceUsd,
|
|
54
|
+
gaps: _
|
|
55
|
+
});
|
|
56
|
+
return u.has(o) || (x.depositedToken = b ?? x.depositedToken), {
|
|
57
|
+
...x,
|
|
58
|
+
tokenContractAddress: s.address,
|
|
59
|
+
depositChain: s.chain,
|
|
60
|
+
market: d ?? null,
|
|
61
|
+
hasDeposit: h ? !0 : m ? !1 : null,
|
|
62
|
+
marketStatus: d?.marketStatus ?? x.marketStatus,
|
|
63
|
+
symbolId: d?.symbolId ?? x.symbolId,
|
|
64
|
+
tokenName: d?.tokenName ?? u.get(o)?.[0]?.tokenName ?? null,
|
|
65
|
+
tokenTicker: d?.tokenTicker ?? u.get(o)?.[0]?.tokenTicker ?? null,
|
|
66
|
+
apr: t(d?.apr)
|
|
67
|
+
};
|
|
68
|
+
}), p = 0, m = 0, h = 0, g = 0;
|
|
69
|
+
for (let e of f) e.valuationComplete && e.balanceUsd != null && e.depositedToken != null && e.priceUsd != null && (p += e.balanceUsd, m += t(e.depositedToken) * e.priceUsd), e.apr != null && e.apr > 0 && e.totalUsdc != null && e.totalUsdc > 0n && (h += t(e.totalUsdc), g += t(e.totalUsdc) * e.apr);
|
|
70
|
+
let _ = !a.some((e) => e.source === "deposits" || [
|
|
71
|
+
"listed",
|
|
72
|
+
"under_review",
|
|
73
|
+
"rejected",
|
|
74
|
+
"delisted",
|
|
75
|
+
"waiting_for_deposit"
|
|
76
|
+
].includes(e.source)), v = _ && f.every((e) => e.balanceUsd != null), y = (e) => _ && f.every((t) => t[e] != null) ? t(f.reduce((t, n) => t + n[e], 0n)) : null, b = f.reduce((e, t) => e + (t.balanceUsd ?? 0), 0), x = f.reduce((e, n) => e + (t(n.depositedToken) ?? 0) * (n.priceUsd ?? 0), 0), S = i.rewardPositions, C = S == null ? y("claimedReward") : S.every((e) => e.claimed != null) ? t(S.reduce((e, t) => e + t.claimed, 0n)) : null, w = S == null ? y("claimableReward") : S.every((e) => e.claimable != null) ? t(S.reduce((e, t) => e + t.claimable, 0n)) : null;
|
|
77
|
+
return {
|
|
78
|
+
entries: f,
|
|
79
|
+
totalBalanceUsd: v ? f.reduce((e, t) => e + t.balanceUsd, 0) : null,
|
|
80
|
+
totalDepositedUsd: _ && f.every((e) => e.depositedToken != null && (e.depositedToken === 0n || e.priceUsd != null)) ? f.reduce((e, n) => e + t(n.depositedToken) * (n.priceUsd ?? 0), 0) : null,
|
|
81
|
+
claimableRewardUsd: y("claimableReward"),
|
|
82
|
+
claimedRewardUsd: y("claimedReward"),
|
|
83
|
+
lifetimeRewardsUsd: C == null || w == null ? null : C + w,
|
|
84
|
+
knownBalanceUsd: b,
|
|
85
|
+
knownDepositedUsd: x,
|
|
86
|
+
knownValueRoiPercent: x > 0 ? (b - x) / x * 100 : null,
|
|
87
|
+
rewardWindowUsd: t(i.reward),
|
|
88
|
+
averageApr: h > 0 ? g / h : null,
|
|
89
|
+
roiPercent: m > 0 ? (p - m) / m * 100 : null,
|
|
90
|
+
gaps: a
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
//#endregion
|
|
94
|
+
export { i as calculatePoolPortfolio };
|
|
95
|
+
|
|
96
|
+
//# sourceMappingURL=calculate-pool-portfolio.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"calculate-pool-portfolio.js","names":[],"sources":["../../../src/pools/portfolio/calculate-pool-portfolio.ts"],"sourcesContent":["import { units, type PoolReadGap } from \"../composition\";\nimport { emptyPoolProfit } from \"../empty-pool-profit\";\nimport { calculatePoolPosition, type PoolPositionData } from \"../position/calculate-pool-position\";\nimport {\n ListingMarketStatus,\n type ListingMarketDetail,\n type UserListingMarket,\n type UserPoolProfit,\n type UserTransaction,\n} from \"../types\";\n\n/** Pool identity and an optional third-party price, supplied by the consumer. */\nexport interface PoolPortfolioPrice {\n tokenContractAddress: string;\n depositChain: number;\n priceUsd: number;\n}\n/** Flat portfolio row. Stake fields have exactly the position read's semantics. */\nexport interface PoolPortfolioPosition extends PoolPositionData {\n tokenContractAddress: string;\n depositChain: number;\n /** Original normalized catalog snapshot, including rates, flags and ownership metadata. */\n market: UserListingMarket | null;\n /** Positive deposit observed in history or catalog; null when incomplete history cannot establish absence. */\n hasDeposit: boolean | null;\n tokenName: string | null;\n tokenTicker: string | null;\n apr: number | null;\n}\n/** Portfolio values before any consumer filtering or pagination. */\nexport interface PoolPortfolio {\n entries: PoolPortfolioPosition[];\n totalBalanceUsd: number | null;\n totalDepositedUsd: number | null;\n claimableRewardUsd: number | null;\n claimedRewardUsd: number | null;\n rewardWindowUsd: number | null;\n averageApr: number | null;\n /** ROI over the same fully priced positions on both sides. Null when no comparable deposits exist. */\n roiPercent: number | null;\n /** Partial known-value totals; consult totalBalanceUsd/totalDepositedUsd for source completeness. */\n knownBalanceUsd: number;\n knownDepositedUsd: number;\n knownValueRoiPercent: number | null;\n /** Historical claimed plus claimable rewards, including positions no longer held. */\n lifetimeRewardsUsd: number | null;\n gaps: PoolReadGap[];\n}\n/** Normalized reads for portfolio assembly; no wire strings or generated vendor types. */\nexport interface CalculatePoolPortfolioParameters {\n listed: readonly UserListingMarket[];\n nonListed: readonly UserListingMarket[];\n deposits: readonly UserTransaction[] | null;\n positions: readonly {\n tokenContractAddress: string;\n depositChain: number;\n profit: Partial<UserPoolProfit> | null;\n detail: ListingMarketDetail | null;\n }[];\n prices?: readonly PoolPortfolioPrice[];\n reward: bigint | null;\n /** Optional complete historical reward ledger. Values include any consumer optimistic projection. */\n rewardPositions?: readonly { claimed: bigint | null; claimable: bigint | null }[];\n gaps?: readonly PoolReadGap[];\n}\n\n/** Assemble holdings and totals from SDK reads; filtering and top-earner selection remain consumer-owned.\n * @param input - Normalized source snapshots and explicit read gaps.\n * @returns Rows with exact stake amounts, USD totals and completeness information.\n */\nexport function calculatePoolPortfolio(input: CalculatePoolPortfolioParameters): PoolPortfolio {\n const gaps = [...(input.gaps ?? [])];\n const catalog = [...input.listed, ...input.nonListed];\n const aliases = new Map<string, Set<string>>();\n for (const row of catalog) {\n const id = `${row.chainId}:${row.contractAddress.toLowerCase()}`;\n const values = aliases.get(id) ?? new Set<string>();\n values.add(row.contractAddress);\n aliases.set(id, values);\n }\n function key(address: string, chain: number): string {\n const folded = `${chain}:${address.toLowerCase()}`;\n return chain === 0 && (aliases.get(folded)?.size ?? 0) > 1 ? `${chain}:${address}` : folded;\n }\n const markets = new Map(catalog.map((row) => [key(row.contractAddress, row.chainId), row]));\n const groups = new Map<string, UserTransaction[]>();\n for (const row of input.deposits ?? []) {\n if (row.type !== \"deposit\") continue;\n const id = key(row.tokenAddress, row.chainId);\n if (\n row.chainId === 0 &&\n (aliases.get(`${row.chainId}:${row.tokenAddress.toLowerCase()}`)?.size ?? 0) > 1 &&\n !markets.has(id)\n ) {\n gaps.push({ source: \"deposits\", tokenContractAddress: row.tokenAddress, reason: \"ambiguous-address\" });\n }\n groups.set(id, [...(groups.get(id) ?? []), row]);\n }\n const identities = new Map(\n [...input.listed, ...input.nonListed.filter((row) => (row.userDeposit ?? 0n) > 0n)].map((row) => [\n key(row.contractAddress, row.chainId),\n { address: row.contractAddress, chain: row.chainId },\n ]),\n );\n for (const [id, rows] of groups)\n if (!identities.has(id)) {\n const market = markets.get(id);\n identities.set(id, { address: market?.contractAddress ?? rows[0]!.tokenAddress, chain: rows[0]!.chainId });\n }\n const entries = [...identities].map(([id, identity]) => {\n const market = markets.get(id);\n const source = input.positions.find((row) => key(row.tokenContractAddress, row.depositChain) === id);\n const price = input.prices?.find((row) => key(row.tokenContractAddress, row.depositChain) === id);\n const depositsComplete = input.deposits != null && !gaps.some((gap) => gap.source === \"deposits\");\n const hasDeposit = (market?.userDeposit ?? 0n) > 0n || (groups.get(id) ?? []).some((row) => row.amount > 0n);\n const noPosition =\n (market != null && market.marketStatus !== ListingMarketStatus.LISTED) || (depositsComplete && !hasDeposit);\n const positionGaps = gaps.filter(\n (gap) => gap.tokenContractAddress != null && key(gap.tokenContractAddress, identity.chain) === id,\n );\n // React retains cached data after a failed refetch. A failed snapshot cannot establish a known stake.\n const profitFailed = positionGaps.some((gap) => gap.source === \"profit\" && gap.reason === \"failed\");\n const profit = profitFailed ? null : (source?.profit ?? (noPosition ? emptyPoolProfit() : null));\n const deposited = (profitFailed ? undefined : source?.profit?.userDepositedTokenAmount) ?? market?.userDeposit;\n const position = calculatePoolPosition({\n tokenContractAddress: identity.address,\n depositChain: identity.chain,\n detail: source?.detail ?? null,\n profit,\n userSharePercentage: market?.userSharePercentage,\n deposits: input.deposits == null ? null : (groups.get(id) ?? []),\n depositsComplete: !gaps.some((gap) => gap.source === \"deposits\"),\n // Seed the projection, so every derived amount uses the same authoritative fallback.\n depositHistory:\n depositsComplete && !groups.has(id) && deposited != null\n ? { pending: 0n, transferred: 0n, success: deposited, rejected: 0n, refund: 0n }\n : undefined,\n priceUsd: price?.priceUsd,\n gaps: positionGaps,\n });\n if (!groups.has(id)) position.depositedToken = deposited ?? position.depositedToken;\n return {\n ...position,\n tokenContractAddress: identity.address,\n depositChain: identity.chain,\n market: market ?? null,\n hasDeposit: hasDeposit ? true : depositsComplete ? false : null,\n marketStatus: market?.marketStatus ?? position.marketStatus,\n symbolId: market?.symbolId ?? position.symbolId,\n tokenName: market?.tokenName ?? groups.get(id)?.[0]?.tokenName ?? null,\n tokenTicker: market?.tokenTicker ?? groups.get(id)?.[0]?.tokenTicker ?? null,\n apr: units(market?.apr),\n };\n });\n let balance = 0,\n deposits = 0,\n weight = 0,\n weightedApr = 0;\n for (const row of entries) {\n if (row.valuationComplete && row.balanceUsd != null && row.depositedToken != null && row.priceUsd != null) {\n balance += row.balanceUsd;\n deposits += units(row.depositedToken)! * row.priceUsd;\n }\n if (row.apr != null && row.apr > 0 && row.totalUsdc != null && row.totalUsdc > 0n) {\n weight += units(row.totalUsdc)!;\n weightedApr += units(row.totalUsdc)! * row.apr;\n }\n }\n const holdingsComplete = !gaps.some(\n (gap) =>\n gap.source === \"deposits\" ||\n [\"listed\", \"under_review\", \"rejected\", \"delisted\", \"waiting_for_deposit\"].includes(gap.source),\n );\n const allKnown = holdingsComplete && entries.every((row) => row.balanceUsd != null);\n const sumReward = (field: \"claimableReward\" | \"claimedReward\") =>\n holdingsComplete && entries.every((row) => row[field] != null)\n ? units(entries.reduce((sum, row) => sum + row[field]!, 0n))\n : null;\n const knownBalanceUsd = entries.reduce((sum, row) => sum + (row.balanceUsd ?? 0), 0);\n const knownDepositedUsd = entries.reduce(\n (sum, row) => sum + (units(row.depositedToken) ?? 0) * (row.priceUsd ?? 0),\n 0,\n );\n const rewardPositions = input.rewardPositions;\n const claimed =\n rewardPositions == null\n ? sumReward(\"claimedReward\")\n : rewardPositions.every((row) => row.claimed != null)\n ? units(rewardPositions.reduce((sum, row) => sum + row.claimed!, 0n))\n : null;\n const claimable =\n rewardPositions == null\n ? sumReward(\"claimableReward\")\n : rewardPositions.every((row) => row.claimable != null)\n ? units(rewardPositions.reduce((sum, row) => sum + row.claimable!, 0n))\n : null;\n return {\n entries,\n totalBalanceUsd: allKnown ? entries.reduce((sum, row) => sum + row.balanceUsd!, 0) : null,\n totalDepositedUsd:\n holdingsComplete &&\n entries.every((row) => row.depositedToken != null && (row.depositedToken === 0n || row.priceUsd != null))\n ? entries.reduce((sum, row) => sum + units(row.depositedToken)! * (row.priceUsd ?? 0), 0)\n : null,\n claimableRewardUsd: sumReward(\"claimableReward\"),\n claimedRewardUsd: sumReward(\"claimedReward\"),\n lifetimeRewardsUsd: claimed == null || claimable == null ? null : claimed + claimable,\n knownBalanceUsd,\n knownDepositedUsd,\n knownValueRoiPercent:\n knownDepositedUsd > 0 ? ((knownBalanceUsd - knownDepositedUsd) / knownDepositedUsd) * 100 : null,\n rewardWindowUsd: units(input.reward),\n averageApr: weight > 0 ? weightedApr / weight : null,\n roiPercent: deposits > 0 ? ((balance - deposits) / deposits) * 100 : null,\n gaps,\n };\n}\n"],"mappings":";;;;;AAsEA,SAAgB,EAAuB,GAAwD;CAC7F,IAAM,IAAO,CAAC,GAAI,EAAM,QAAQ,CAAC,CAAE,GAC7B,IAAU,CAAC,GAAG,EAAM,QAAQ,GAAG,EAAM,SAAS,GAC9C,oBAAU,IAAI,IAAyB;CAC7C,KAAK,IAAM,KAAO,GAAS;EACzB,IAAM,IAAK,GAAG,EAAI,QAAQ,GAAG,EAAI,gBAAgB,YAAY,KACvD,IAAS,EAAQ,IAAI,CAAE,qBAAK,IAAI,IAAY;EAElD,AADA,EAAO,IAAI,EAAI,eAAe,GAC9B,EAAQ,IAAI,GAAI,CAAM;CACxB;CACA,SAAS,EAAI,GAAiB,GAAuB;EACnD,IAAM,IAAS,GAAG,EAAM,GAAG,EAAQ,YAAY;EAC/C,OAAO,MAAU,MAAM,EAAQ,IAAI,CAAM,GAAG,QAAQ,KAAK,IAAI,GAAG,EAAM,GAAG,MAAY;CACvF;CACA,IAAM,IAAU,IAAI,IAAI,EAAQ,KAAK,MAAQ,CAAC,EAAI,EAAI,iBAAiB,EAAI,OAAO,GAAG,CAAG,CAAC,CAAC,GACpF,oBAAS,IAAI,IAA+B;CAClD,KAAK,IAAM,KAAO,EAAM,YAAY,CAAC,GAAG;EACtC,IAAI,EAAI,SAAS,WA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AAW,EAAQ,QAAQ,GAAK,MAAQ,IAAM,EAAI,YAAa,CAAC,IAAI;EACrF,mBACE,KACA,EAAQ,OAAO,MAAQ,EAAI,kBAAkB,SAAS,EAAI,mBAAmB,MAAM,EAAI,YAAY,KAAK,IACpG,EAAQ,QAAQ,GAAK,MAAQ,IAAM,EAAM,EAAI,cAAc,KAAM,EAAI,YAAY,IAAI,CAAC,IACtF;EACN,oBAAoB,EAAU,iBAAiB;EAC/C,kBAAkB,EAAU,eAAe;EAC3C,oBAAoB,KAAW,QAAQ,KAAa,OAAO,OAAO,IAAU;EAC5E;EACA;EACA,sBACE,IAAoB,KAAM,IAAkB,KAAqB,IAAqB,MAAM;EAC9F,iBAAiB,EAAM,EAAM,MAAM;EACnC,YAAY,IAAS,IAAI,IAAc,IAAS;EAChD,YAAY,IAAW,KAAM,IAAU,KAAY,IAAY,MAAM;EACrE;CACF;AACF"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { Config } from '../../core/config/index.js';
|
|
2
|
+
import { GetUserListingMarketsParameters } from '../user-markets/get-user-listing-markets.js';
|
|
3
|
+
import { PoolPortfolio, PoolPortfolioPrice } from './calculate-pool-portfolio.js';
|
|
4
|
+
/** Full portfolio inputs. Filter after assembly; userAddress scopes private query caches. */
|
|
5
|
+
export type GetPoolPortfolioParameters = Pick<GetUserListingMarketsParameters, "chainId" | "accessToken" | "sortBy" | "orderBy"> & {
|
|
6
|
+
userAddress: string;
|
|
7
|
+
/** Reward window, 1–30 days. Defaults to 30. */
|
|
8
|
+
rewardDays?: number;
|
|
9
|
+
prices?: readonly PoolPortfolioPrice[];
|
|
10
|
+
};
|
|
11
|
+
/** Portfolio entries, totals and explicit gaps. */
|
|
12
|
+
export type GetPoolPortfolioReturnType = PoolPortfolio;
|
|
13
|
+
/** Read a bounded portfolio before client filters. Each source is capped at ten pages.
|
|
14
|
+
* @param config - SDK configuration.
|
|
15
|
+
* @param parameters - Authenticated user, optional ordering and external prices.
|
|
16
|
+
* @returns Positions and totals with failed, repeated or truncated source information.
|
|
17
|
+
*/
|
|
18
|
+
export declare function getPoolPortfolio(config: Config, parameters: GetPoolPortfolioParameters): Promise<PoolPortfolio>;
|
|
19
|
+
//# sourceMappingURL=get-pool-portfolio.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"get-pool-portfolio.d.ts","sourceRoot":"","sources":["../../../src/pools/portfolio/get-pool-portfolio.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAMhD,OAAO,EAAyB,KAAK,+BAA+B,EAAE,MAAM,0CAA0C,CAAC;AAEvH,OAAO,EAA0B,KAAK,aAAa,EAAE,KAAK,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAGjH,6FAA6F;AAC7F,MAAM,MAAM,0BAA0B,GAAG,IAAI,CAC3C,+BAA+B,EAC/B,SAAS,GAAG,aAAa,GAAG,QAAQ,GAAG,SAAS,CACjD,GAAG;IACF,WAAW,EAAE,MAAM,CAAC;IACpB,gDAAgD;IAChD,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,MAAM,CAAC,EAAE,SAAS,kBAAkB,EAAE,CAAC;CACxC,CAAC;AACF,mDAAmD;AACnD,MAAM,MAAM,0BAA0B,GAAG,aAAa,CAAC;AAEvD;;;;GAIG;AACH,wBAAsB,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,0BAA0B,GAAG,OAAO,CAAC,aAAa,CAAC,CAoGrH"}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { ListingMarketStatus as e, PoolTransactionType as t } from "../types.js";
|
|
2
|
+
import { getListingMarketDetail as n } from "../market-detail/get-listing-market-detail.js";
|
|
3
|
+
import { readOptional as r, readPages as i } from "../composition.js";
|
|
4
|
+
import { calculatePoolPortfolio as a } from "./calculate-pool-portfolio.js";
|
|
5
|
+
import { getUserProfit as o } from "../profit/get-user-profit.js";
|
|
6
|
+
import { getUserTotalReward as s } from "../rewards/get-user-total-reward.js";
|
|
7
|
+
import { getUserListingMarkets as c } from "../user-markets/get-user-listing-markets.js";
|
|
8
|
+
import { getUserTransactions as l } from "../user-transactions/get-user-transactions.js";
|
|
9
|
+
import { createPositionReader as u } from "./read-positions.js";
|
|
10
|
+
//#region src/pools/portfolio/get-pool-portfolio.ts
|
|
11
|
+
async function d(d, f) {
|
|
12
|
+
let p = [], { chainId: m, accessToken: h, sortBy: g, orderBy: _ } = f, v = [
|
|
13
|
+
e.LISTED,
|
|
14
|
+
e.UNDER_REVIEW,
|
|
15
|
+
e.REJECTED,
|
|
16
|
+
e.DELISTED,
|
|
17
|
+
e.WAITING_FOR_DEPOSIT
|
|
18
|
+
], [y, b, x] = await Promise.all([
|
|
19
|
+
Promise.all(v.map((e) => r(() => i(async (t) => {
|
|
20
|
+
let n = await c(d, {
|
|
21
|
+
chainId: m,
|
|
22
|
+
accessToken: h,
|
|
23
|
+
sortBy: g,
|
|
24
|
+
orderBy: _,
|
|
25
|
+
marketStatus: e,
|
|
26
|
+
offset: t,
|
|
27
|
+
limit: 100
|
|
28
|
+
});
|
|
29
|
+
return {
|
|
30
|
+
items: n.items,
|
|
31
|
+
total: n.total
|
|
32
|
+
};
|
|
33
|
+
}, (e) => `${e.chainId}:${e.contractAddress}`, p, e), p, e))),
|
|
34
|
+
r(() => i(async (e) => {
|
|
35
|
+
let n = await l(d, {
|
|
36
|
+
chainId: m,
|
|
37
|
+
accessToken: h,
|
|
38
|
+
transactionType: t.DEPOSIT,
|
|
39
|
+
start: e,
|
|
40
|
+
size: 100
|
|
41
|
+
});
|
|
42
|
+
return {
|
|
43
|
+
items: n.items,
|
|
44
|
+
total: n.count
|
|
45
|
+
};
|
|
46
|
+
}, (e) => e.transactionId, p, "deposits"), p, "deposits"),
|
|
47
|
+
r(() => s(d, {
|
|
48
|
+
chainId: m,
|
|
49
|
+
accessToken: h,
|
|
50
|
+
userAddress: f.userAddress,
|
|
51
|
+
days: f.rewardDays ?? 30
|
|
52
|
+
}), p, "rewards")
|
|
53
|
+
]), S = {
|
|
54
|
+
listed: y[0] ?? [],
|
|
55
|
+
nonListed: y.slice(1).flatMap((e) => e ?? []),
|
|
56
|
+
deposits: b,
|
|
57
|
+
reward: x,
|
|
58
|
+
gaps: p,
|
|
59
|
+
prices: f.prices
|
|
60
|
+
}, C = a({
|
|
61
|
+
...S,
|
|
62
|
+
positions: []
|
|
63
|
+
}).entries.filter((e) => e.hasDeposit === !0 && e.totalLp !== 0n), w = u(p), T = await Promise.all(C.map(async (e) => {
|
|
64
|
+
let t = e.tokenContractAddress, [r, i] = await Promise.all([w(() => o(d, {
|
|
65
|
+
chainId: m,
|
|
66
|
+
accessToken: h,
|
|
67
|
+
tokenContractAddress: t
|
|
68
|
+
}), "profit", t), w(() => n(d, {
|
|
69
|
+
chainId: m,
|
|
70
|
+
tokenContractAddress: t,
|
|
71
|
+
depositChain: e.depositChain
|
|
72
|
+
}), "detail", t)]);
|
|
73
|
+
return {
|
|
74
|
+
tokenContractAddress: t,
|
|
75
|
+
depositChain: e.depositChain,
|
|
76
|
+
profit: r,
|
|
77
|
+
detail: i
|
|
78
|
+
};
|
|
79
|
+
}));
|
|
80
|
+
return a({
|
|
81
|
+
...S,
|
|
82
|
+
positions: T
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
//#endregion
|
|
86
|
+
export { d as getPoolPortfolio };
|
|
87
|
+
|
|
88
|
+
//# sourceMappingURL=get-pool-portfolio.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"get-pool-portfolio.js","names":[],"sources":["../../../src/pools/portfolio/get-pool-portfolio.ts"],"sourcesContent":["import type { Config } from \"../../core/config\";\nimport { readOptional, readPages, type PoolReadGap } from \"../composition\";\nimport { getListingMarketDetail } from \"../market-detail/get-listing-market-detail\";\nimport { getUserProfit } from \"../profit/get-user-profit\";\nimport { getUserTotalReward } from \"../rewards/get-user-total-reward\";\nimport { ListingMarketStatus, PoolTransactionType } from \"../types\";\nimport { getUserListingMarkets, type GetUserListingMarketsParameters } from \"../user-markets/get-user-listing-markets\";\nimport { getUserTransactions } from \"../user-transactions/get-user-transactions\";\nimport { calculatePoolPortfolio, type PoolPortfolio, type PoolPortfolioPrice } from \"./calculate-pool-portfolio\";\nimport { createPositionReader } from \"./read-positions\";\n\n/** Full portfolio inputs. Filter after assembly; userAddress scopes private query caches. */\nexport type GetPoolPortfolioParameters = Pick<\n GetUserListingMarketsParameters,\n \"chainId\" | \"accessToken\" | \"sortBy\" | \"orderBy\"\n> & {\n userAddress: string;\n /** Reward window, 1–30 days. Defaults to 30. */\n rewardDays?: number;\n prices?: readonly PoolPortfolioPrice[];\n};\n/** Portfolio entries, totals and explicit gaps. */\nexport type GetPoolPortfolioReturnType = PoolPortfolio;\n\n/** Read a bounded portfolio before client filters. Each source is capped at ten pages.\n * @param config - SDK configuration.\n * @param parameters - Authenticated user, optional ordering and external prices.\n * @returns Positions and totals with failed, repeated or truncated source information.\n */\nexport async function getPoolPortfolio(config: Config, parameters: GetPoolPortfolioParameters): Promise<PoolPortfolio> {\n const gaps: PoolReadGap[] = [];\n const { chainId, accessToken, sortBy, orderBy } = parameters;\n const statuses = [\n ListingMarketStatus.LISTED,\n ListingMarketStatus.UNDER_REVIEW,\n ListingMarketStatus.REJECTED,\n ListingMarketStatus.DELISTED,\n ListingMarketStatus.WAITING_FOR_DEPOSIT,\n ];\n const [catalog, deposits, reward] = await Promise.all([\n Promise.all(\n statuses.map((marketStatus) =>\n readOptional(\n () =>\n readPages(\n async (offset) => {\n const page = await getUserListingMarkets(config, {\n chainId,\n accessToken,\n sortBy,\n orderBy,\n marketStatus,\n offset,\n limit: 100,\n });\n return { items: page.items, total: page.total };\n },\n (row) => `${row.chainId}:${row.contractAddress}`,\n gaps,\n marketStatus,\n ),\n gaps,\n marketStatus,\n ),\n ),\n ),\n readOptional(\n () =>\n readPages(\n async (start) => {\n const page = await getUserTransactions(config, {\n chainId,\n accessToken,\n transactionType: PoolTransactionType.DEPOSIT,\n start,\n size: 100,\n });\n return { items: page.items, total: page.count };\n },\n (row) => row.transactionId,\n gaps,\n \"deposits\",\n ),\n gaps,\n \"deposits\",\n ),\n readOptional(\n () =>\n getUserTotalReward(config, {\n chainId,\n accessToken,\n userAddress: parameters.userAddress,\n days: parameters.rewardDays ?? 30,\n }),\n gaps,\n \"rewards\",\n ),\n ]);\n const sources = {\n listed: catalog[0] ?? [],\n nonListed: catalog.slice(1).flatMap((rows) => rows ?? []),\n deposits,\n reward,\n gaps,\n prices: parameters.prices,\n };\n const holdings = calculatePoolPortfolio({ ...sources, positions: [] }).entries.filter(\n (row) => row.hasDeposit === true && row.totalLp !== 0n,\n );\n const readPosition = createPositionReader(gaps);\n const positions = await Promise.all(\n holdings.map(async (row) => {\n const tokenContractAddress = row.tokenContractAddress;\n const [profit, detail] = await Promise.all([\n readPosition(\n () => getUserProfit(config, { chainId, accessToken, tokenContractAddress }),\n \"profit\",\n tokenContractAddress,\n ),\n readPosition(\n () => getListingMarketDetail(config, { chainId, tokenContractAddress, depositChain: row.depositChain }),\n \"detail\",\n tokenContractAddress,\n ),\n ]);\n return { tokenContractAddress, depositChain: row.depositChain, profit, detail };\n }),\n );\n return calculatePoolPortfolio({ ...sources, positions });\n}\n"],"mappings":";;;;;;;;;;AA6BA,eAAsB,EAAiB,GAAgB,GAAgE;CACrH,IAAM,IAAsB,CAAC,GACvB,EAAE,YAAS,gBAAa,WAAQ,eAAY,GAC5C,IAAW;EACf,EAAoB;EACpB,EAAoB;EACpB,EAAoB;EACpB,EAAoB;EACpB,EAAoB;CACtB,GACM,CAAC,GAAS,GAAU,KAAU,MAAM,QAAQ,IAAI;EACpD,QAAQ,IACN,EAAS,KAAK,MACZ,QAEI,EACE,OAAO,MAAW;GAChB,IAAM,IAAO,MAAM,EAAsB,GAAQ;IAC/C;IACA;IACA;IACA;IACA;IACA;IACA,OAAO;GACT,CAAC;GACD,OAAO;IAAE,OAAO,EAA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3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/pools/portfolio/index.ts"],"names":[],"mappings":"AAAA,cAAc,4BAA4B,CAAC;AAC3C,cAAc,sBAAsB,CAAC;AACrC,cAAc,SAAS,CAAC"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Config } from '../../core/config/index.js';
|
|
2
|
+
import { Compute, ConfigKeyParameter } from '../../shared/types/properties.js';
|
|
3
|
+
import { QueryParameter, SymmioQueryOptions } from '../../shared/types/query.js';
|
|
4
|
+
import { GetPoolPortfolioParameters, GetPoolPortfolioReturnType } from './get-pool-portfolio.js';
|
|
5
|
+
/** Stable key for the composed core read. Credentials are excluded. */
|
|
6
|
+
export declare function getPoolPortfolioQueryKey(options: Compute<GetPoolPortfolioParameters & ConfigKeyParameter>): readonly ["getPoolPortfolio", Record<string, unknown>];
|
|
7
|
+
/** Composed query key type. */
|
|
8
|
+
export type GetPoolPortfolioQueryKey = ReturnType<typeof getPoolPortfolioQueryKey>;
|
|
9
|
+
/** Query controls plus all required read inputs. */
|
|
10
|
+
export type GetPoolPortfolioOptions = GetPoolPortfolioParameters & QueryParameter<GetPoolPortfolioReturnType, Error, GetPoolPortfolioReturnType, GetPoolPortfolioQueryKey>;
|
|
11
|
+
/** Build options for non-React consumers; React composition uses the underlying primitive queries instead.
|
|
12
|
+
* @param config - SDK configuration.
|
|
13
|
+
* @param options - Required read inputs and optional query controls.
|
|
14
|
+
* @returns Typed query options with a credential-free key.
|
|
15
|
+
*/
|
|
16
|
+
export declare function getPoolPortfolioQueryOptions(config: Config, options: GetPoolPortfolioOptions): SymmioQueryOptions<GetPoolPortfolioReturnType, Error, GetPoolPortfolioReturnType, GetPoolPortfolioQueryKey>;
|
|
17
|
+
//# sourceMappingURL=query.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"query.d.ts","sourceRoot":"","sources":["../../../src/pools/portfolio/query.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,KAAK,EAAE,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AACjF,OAAO,KAAK,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAEnF,OAAO,EAEL,KAAK,0BAA0B,EAC/B,KAAK,0BAA0B,EAChC,MAAM,sBAAsB,CAAC;AAC9B,uEAAuE;AACvE,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,OAAO,CAAC,0BAA0B,GAAG,kBAAkB,CAAC,0DAEzG;AACD,+BAA+B;AAC/B,MAAM,MAAM,wBAAwB,GAAG,UAAU,CAAC,OAAO,wBAAwB,CAAC,CAAC;AACnF,oDAAoD;AACpD,MAAM,MAAM,uBAAuB,GAAG,0BAA0B,GAC9D,cAAc,CAAC,0BAA0B,EAAE,KAAK,EAAE,0BAA0B,EAAE,wBAAwB,CAAC,CAAC;AAC1G;;;;GAIG;AACH,wBAAgB,4BAA4B,CAC1C,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,uBAAuB,GAC/B,kBAAkB,CAAC,0BAA0B,EAAE,KAAK,EAAE,0BAA0B,EAAE,wBAAwB,CAAC,CAO7G"}
|