@metamask-previews/perps-controller 25.0.0-preview-4046c2f69 → 26.0.0-preview-203750488
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/CHANGELOG.md +105 -9
- package/dist/PerpsController-method-action-types.d.ts +149 -3
- package/dist/PerpsController-method-action-types.d.ts.map +1 -1
- package/dist/PerpsController-method-action-types.js.map +1 -1
- package/dist/PerpsController.d.ts +125 -3
- package/dist/PerpsController.d.ts.map +1 -1
- package/dist/PerpsController.js +787 -31
- package/dist/PerpsController.js.map +1 -1
- package/dist/constants/eventNames.d.ts +69 -9
- package/dist/constants/eventNames.d.ts.map +1 -1
- package/dist/constants/eventNames.js +82 -11
- package/dist/constants/eventNames.js.map +1 -1
- package/dist/constants/hyperLiquidConfig.d.ts +15 -0
- package/dist/constants/hyperLiquidConfig.d.ts.map +1 -1
- package/dist/constants/hyperLiquidConfig.js +14 -0
- package/dist/constants/hyperLiquidConfig.js.map +1 -1
- package/dist/constants/perpsConfig.d.ts +10 -2
- package/dist/constants/perpsConfig.d.ts.map +1 -1
- package/dist/constants/perpsConfig.js +11 -3
- package/dist/constants/perpsConfig.js.map +1 -1
- package/dist/index.d.ts +10 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/internal/accountReturnOnEquity.d.ts +12 -0
- package/dist/internal/accountReturnOnEquity.d.ts.map +1 -0
- package/dist/internal/accountReturnOnEquity.js +18 -0
- package/dist/internal/accountReturnOnEquity.js.map +1 -0
- package/dist/internal/hyperLiquidHip3Rebalance.d.ts +14 -0
- package/dist/internal/hyperLiquidHip3Rebalance.d.ts.map +1 -0
- package/dist/internal/hyperLiquidHip3Rebalance.js +18 -0
- package/dist/internal/hyperLiquidHip3Rebalance.js.map +1 -0
- package/dist/internal/marketNumericValues.d.ts +10 -0
- package/dist/internal/marketNumericValues.d.ts.map +1 -0
- package/dist/internal/marketNumericValues.js +9 -0
- package/dist/internal/marketNumericValues.js.map +1 -0
- package/dist/internal/perpsDisplaySymbol.d.ts +12 -0
- package/dist/internal/perpsDisplaySymbol.d.ts.map +1 -0
- package/dist/internal/perpsDisplaySymbol.js +21 -0
- package/dist/internal/perpsDisplaySymbol.js.map +1 -0
- package/dist/perpsErrorCodes.d.ts +1 -0
- package/dist/perpsErrorCodes.d.ts.map +1 -1
- package/dist/perpsErrorCodes.js +1 -0
- package/dist/perpsErrorCodes.js.map +1 -1
- package/dist/providers/AggregatedPerpsProvider.d.ts +47 -1
- package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
- package/dist/providers/AggregatedPerpsProvider.js +140 -0
- package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
- package/dist/providers/HyperLiquidProvider.d.ts +72 -4
- package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
- package/dist/providers/HyperLiquidProvider.js +751 -159
- package/dist/providers/HyperLiquidProvider.js.map +1 -1
- package/dist/providers/LighterProvider.d.ts +2 -1
- package/dist/providers/LighterProvider.d.ts.map +1 -1
- package/dist/providers/LighterProvider.js +11 -6
- package/dist/providers/LighterProvider.js.map +1 -1
- package/dist/selectors.d.ts +15 -5
- package/dist/selectors.d.ts.map +1 -1
- package/dist/selectors.js +23 -5
- package/dist/selectors.js.map +1 -1
- package/dist/services/AggregatedOrderBookConnection.d.ts.map +1 -1
- package/dist/services/AggregatedOrderBookConnection.js +8 -10
- package/dist/services/AggregatedOrderBookConnection.js.map +1 -1
- package/dist/services/HyperLiquidClientService.d.ts +8 -0
- package/dist/services/HyperLiquidClientService.d.ts.map +1 -1
- package/dist/services/HyperLiquidClientService.js +65 -0
- package/dist/services/HyperLiquidClientService.js.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.d.ts +30 -1
- package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.js +117 -30
- package/dist/services/HyperLiquidSubscriptionService.js.map +1 -1
- package/dist/services/MarketDataService.d.ts +20 -3
- package/dist/services/MarketDataService.d.ts.map +1 -1
- package/dist/services/MarketDataService.js +55 -3
- package/dist/services/MarketDataService.js.map +1 -1
- package/dist/services/StreamChannelManager.d.ts +139 -0
- package/dist/services/StreamChannelManager.d.ts.map +1 -0
- package/dist/services/StreamChannelManager.js +475 -0
- package/dist/services/StreamChannelManager.js.map +1 -0
- package/dist/services/TerminalMarketService.d.ts.map +1 -1
- package/dist/services/TerminalMarketService.js +7 -0
- package/dist/services/TerminalMarketService.js.map +1 -1
- package/dist/services/agentSigner.d.ts +8 -0
- package/dist/services/agentSigner.d.ts.map +1 -1
- package/dist/services/agentSigner.js +13 -0
- package/dist/services/agentSigner.js.map +1 -1
- package/dist/types/hyperliquid-types.d.ts +9 -1
- package/dist/types/hyperliquid-types.d.ts.map +1 -1
- package/dist/types/hyperliquid-types.js +10 -0
- package/dist/types/hyperliquid-types.js.map +1 -1
- package/dist/types/index.d.ts +434 -17
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/utils/accountAggregation.d.ts +17 -0
- package/dist/utils/accountAggregation.d.ts.map +1 -1
- package/dist/utils/accountAggregation.js +21 -5
- package/dist/utils/accountAggregation.js.map +1 -1
- package/dist/utils/accountUtils.d.ts +31 -10
- package/dist/utils/accountUtils.d.ts.map +1 -1
- package/dist/utils/accountUtils.js +68 -28
- package/dist/utils/accountUtils.js.map +1 -1
- package/dist/utils/closeCalculations.d.ts +17 -4
- package/dist/utils/closeCalculations.d.ts.map +1 -1
- package/dist/utils/closeCalculations.js +23 -7
- package/dist/utils/closeCalculations.js.map +1 -1
- package/dist/utils/hyperLiquidAdapter.d.ts +10 -1
- package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -1
- package/dist/utils/hyperLiquidAdapter.js +17 -1
- package/dist/utils/hyperLiquidAdapter.js.map +1 -1
- package/dist/utils/hyperLiquidPositionPreview.d.ts +133 -9
- package/dist/utils/hyperLiquidPositionPreview.d.ts.map +1 -1
- package/dist/utils/hyperLiquidPositionPreview.js +264 -29
- package/dist/utils/hyperLiquidPositionPreview.js.map +1 -1
- package/dist/utils/index.d.ts +4 -2
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +1 -0
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/lighterAdapter.d.ts.map +1 -1
- package/dist/utils/lighterAdapter.js +46 -9
- package/dist/utils/lighterAdapter.js.map +1 -1
- package/dist/utils/marketDataTransform.d.ts.map +1 -1
- package/dist/utils/marketDataTransform.js +13 -8
- package/dist/utils/marketDataTransform.js.map +1 -1
- package/dist/utils/marketUtils.d.ts +1 -2
- package/dist/utils/marketUtils.d.ts.map +1 -1
- package/dist/utils/marketUtils.js +7 -17
- package/dist/utils/marketUtils.js.map +1 -1
- package/dist/utils/orderBookGrouping.d.ts +35 -5
- package/dist/utils/orderBookGrouping.d.ts.map +1 -1
- package/dist/utils/orderBookGrouping.js +62 -6
- package/dist/utils/orderBookGrouping.js.map +1 -1
- package/dist/utils/perpsClientCopy.d.ts.map +1 -1
- package/dist/utils/perpsClientCopy.js +4 -0
- package/dist/utils/perpsClientCopy.js.map +1 -1
- package/dist/utils/perpsDiskPersistence.d.ts.map +1 -1
- package/dist/utils/perpsDiskPersistence.js +10 -0
- package/dist/utils/perpsDiskPersistence.js.map +1 -1
- package/dist/utils/perpsFormatters.d.ts +31 -0
- package/dist/utils/perpsFormatters.d.ts.map +1 -1
- package/dist/utils/perpsFormatters.js +26 -0
- package/dist/utils/perpsFormatters.js.map +1 -1
- package/dist/utils/priceDeviation.d.ts +9 -6
- package/dist/utils/priceDeviation.d.ts.map +1 -1
- package/dist/utils/priceDeviation.js +17 -26
- package/dist/utils/priceDeviation.js.map +1 -1
- package/dist/utils/sortMarkets.d.ts +13 -5
- package/dist/utils/sortMarkets.d.ts.map +1 -1
- package/dist/utils/sortMarkets.js +60 -38
- package/dist/utils/sortMarkets.js.map +1 -1
- package/docs/architecture.md +54 -24
- package/docs/client-contract.md +52 -27
- package/docs/contracts/events.md +38 -32
- package/docs/contracts/feature-flags.md +4 -4
- package/docs/formatting.md +2 -0
- package/docs/venues/lighter/capabilities.md +18 -15
- package/package.json +1 -1
|
@@ -29,6 +29,23 @@ export type AggregatedAccountTotals = {
|
|
|
29
29
|
* @returns The venue-neutral combined totals.
|
|
30
30
|
*/
|
|
31
31
|
export declare function aggregateAccountTotals(states: AccountState[]): AggregatedAccountTotals;
|
|
32
|
+
/** Inputs to {@link calculateAccountReturnOnEquity}: account totals. */
|
|
33
|
+
export type AccountReturnOnEquityParams = {
|
|
34
|
+
/** Total unrealized PnL of the account's positions, in USD. */
|
|
35
|
+
unrealizedPnl: number | string;
|
|
36
|
+
/** Total margin the account's positions use, in USD. */
|
|
37
|
+
marginUsed: number | string;
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Account return on equity from its totals: `100 x unrealizedPnl /
|
|
41
|
+
* marginUsed`, the margin-weighted RoE of its positions
|
|
42
|
+
* (`calculateWeightedReturnOnEquity`) for an account that only reports totals.
|
|
43
|
+
*
|
|
44
|
+
* @param params - See {@link AccountReturnOnEquityParams}.
|
|
45
|
+
* @returns The return in percent (12 / 120 gives 10), or undefined when
|
|
46
|
+
* `marginUsed` is not positive or an input is not a finite number.
|
|
47
|
+
*/
|
|
48
|
+
export declare function calculateAccountReturnOnEquity(params: AccountReturnOnEquityParams): number | undefined;
|
|
32
49
|
/**
|
|
33
50
|
* Classify the enabled venues, rejecting an entire snapshot if any required
|
|
34
51
|
* balance is missing or non-finite. Also usable when no combined state exists.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"accountAggregation.d.ts","sourceRoot":"","sources":["../../src/utils/accountAggregation.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"accountAggregation.d.ts","sourceRoot":"","sources":["../../src/utils/accountAggregation.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,wBAAwB,EACxB,YAAY,EACZ,8BAA8B,EAE/B,MAAM,mBAAmB,CAAC;AAE3B;;;;;;;GAOG;AACH,MAAM,MAAM,uBAAuB,GAAG;IACpC,YAAY,EAAE,MAAM,CAAC;IACrB,gBAAgB,EAAE,MAAM,CAAC;IACzB,mBAAmB,EAAE,MAAM,CAAC;IAC5B,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,cAAc,EAAE,MAAM,CAAC;CACxB,CAAC;AAgCF;;;;;;;;;;;;GAYG;AACH,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,YAAY,EAAE,GACrB,uBAAuB,CAezB;AAED,wEAAwE;AACxE,MAAM,MAAM,2BAA2B,GAAG;IACxC,+DAA+D;IAC/D,aAAa,EAAE,MAAM,GAAG,MAAM,CAAC;IAC/B,wDAAwD;IACxD,UAAU,EAAE,MAAM,GAAG,MAAM,CAAC;CAC7B,CAAC;AAEF;;;;;;;;GAQG;AACH,wBAAgB,8BAA8B,CAC5C,MAAM,EAAE,2BAA2B,GAClC,MAAM,GAAG,SAAS,CAOpB;AAED;;;;;;GAMG;AACH,wBAAgB,2BAA2B,CACzC,OAAO,EAAE,8BAA8B,EAAE,GACxC,wBAAwB,CA+B1B;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,2BAA2B,CAAC,MAAM,EAAE;IAClD,OAAO,EAAE,8BAA8B,EAAE,CAAC;CAC3C,GAAG,YAAY,GAAG,IAAI,CAyBtB"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { BigNumber } from 'bignumber.js';
|
|
2
|
+
import { accountReturnOnEquity } from '../internal/accountReturnOnEquity.js';
|
|
2
3
|
/** USD balance fields that add up across venues. */
|
|
3
4
|
const ADDITIVE_FIELDS = [
|
|
4
5
|
'totalBalance',
|
|
@@ -42,13 +43,28 @@ export function aggregateAccountTotals(states) {
|
|
|
42
43
|
marginUsed: sumField(states, 'marginUsed'),
|
|
43
44
|
unrealizedPnl: sumField(states, 'unrealizedPnl'),
|
|
44
45
|
};
|
|
45
|
-
|
|
46
|
-
const
|
|
47
|
-
|
|
48
|
-
? totalPnl.multipliedBy(100).dividedBy(totalMarginUsed).toFixed()
|
|
49
|
-
: '0';
|
|
46
|
+
// '0' only when no margin is used; a non-finite input stays visible.
|
|
47
|
+
const returnOnEquity = accountReturnOnEquity(totals.unrealizedPnl, totals.marginUsed)?.toFixed() ??
|
|
48
|
+
'0';
|
|
50
49
|
return { ...totals, returnOnEquity };
|
|
51
50
|
}
|
|
51
|
+
/**
|
|
52
|
+
* Account return on equity from its totals: `100 x unrealizedPnl /
|
|
53
|
+
* marginUsed`, the margin-weighted RoE of its positions
|
|
54
|
+
* (`calculateWeightedReturnOnEquity`) for an account that only reports totals.
|
|
55
|
+
*
|
|
56
|
+
* @param params - See {@link AccountReturnOnEquityParams}.
|
|
57
|
+
* @returns The return in percent (12 / 120 gives 10), or undefined when
|
|
58
|
+
* `marginUsed` is not positive or an input is not a finite number.
|
|
59
|
+
*/
|
|
60
|
+
export function calculateAccountReturnOnEquity(params) {
|
|
61
|
+
const unrealizedPnl = new BigNumber(params.unrealizedPnl);
|
|
62
|
+
const marginUsed = new BigNumber(params.marginUsed);
|
|
63
|
+
if (!unrealizedPnl.isFinite() || !marginUsed.isFinite()) {
|
|
64
|
+
return undefined;
|
|
65
|
+
}
|
|
66
|
+
return accountReturnOnEquity(unrealizedPnl, marginUsed)?.toNumber();
|
|
67
|
+
}
|
|
52
68
|
/**
|
|
53
69
|
* Classify the enabled venues, rejecting an entire snapshot if any required
|
|
54
70
|
* balance is missing or non-finite. Also usable when no combined state exists.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"accountAggregation.js","sourceRoot":"","sources":["../../src/utils/accountAggregation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AA0BzC,oDAAoD;AACpD,MAAM,eAAe,GAAG;IACtB,cAAc;IACd,kBAAkB;IAClB,qBAAqB;IACrB,YAAY;IACZ,eAAe;CACP,C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AQ,CAAC,oBAAoB,CAAC,QAAQ,CAAC,KAAK,CAAC,UAAU,CAAC;QACtD,CAAC,CAAC,EAAE,MAAM,EAAE,aAAa,EAAE,UAAU,EAAE,KAAK,CAAC,UAAU,EAAE;QACzD,CAAC,CAAC,KAAK,CACZ,CAAC;IACF,MAAM,eAAe,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE,CACzD,KAAK,CAAC,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAClD,CAAC;IAEF,IAAI,eAAe,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACjC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,GAAG,sBAAsB,CAAC,eAAe,CAAC;QAC1C,cAAc,EAAE,MAAM,CAAC,WAAW,CAChC,gBAAgB,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC,CAC3D;QACD,SAAS,EAAE,QAAQ;KACpB,CAAC;AACJ,CAAC","sourcesContent":["import { BigNumber } from 'bignumber.js';\n\nimport type {\n AccountAggregateMetadata,\n AccountState,\n PerpsProviderAccountStateEntry,\n PerpsProviderType,\n} from '../types/index.js';\n\n/**\n * Venue-neutral combined account data.\n *\n * Venue-local detail (`crossMarginSummary`, `subAccountBreakdown`) is\n * intentionally absent: cross-venue collateral is not mutually usable, so an\n * aggregate of it would imply a combined margin position that no venue\n * actually settles.\n */\nexport type AggregatedAccountTotals = {\n totalBalance: string;\n spendableBalance: string;\n withdrawableBalance: string;\n marginUsed: string;\n unrealizedPnl: string;\n returnOnEquity: string;\n};\n\n/** USD balance fields that add up across venues. */\nconst ADDITIVE_FIELDS = [\n 'totalBalance',\n 'spendableBalance',\n 'withdrawableBalance',\n 'marginUsed',\n 'unrealizedPnl',\n] as const;\n\n/**\n * Sum one decimal string field across states.\n *\n * Uses `bignumber.js`, never binary floating point. Callers supply states\n * whose required additive fields are finite decimal strings.\n *\n * @param states - The available venue states to sum over.\n * @param field - The USD field to sum.\n * @returns The decimal sum as a canonical string.\n */\nfunction sumField(\n states: AccountState[],\n field: (typeof ADDITIVE_FIELDS)[number],\n): string {\n const total = states.reduce(\n (acc, state) => acc.plus(state[field]),\n new BigNumber(0),\n );\n return total.toFixed();\n}\n\n/**\n * Build the combined totals for a set of available venue states.\n *\n * Additive USD fields are decimal-summed. `returnOnEquity` is a rate, not a\n * balance: both venues report account-level RoE in percentage points\n * (unrealized PnL relative to margin used), so the combined rate is\n * `100 x sum(unrealizedPnl) / sum(marginUsed)` — margin-weighted, never summed\n * or averaged. When no margin is used anywhere the combined RoE is '0': with\n * no collateral at work there is no meaningful rate.\n *\n * @param states - Available, valid per-venue account states.\n * @returns The venue-neutral combined totals.\n */\nexport function aggregateAccountTotals(\n states: AccountState[],\n): AggregatedAccountTotals {\n const totals: Record<(typeof ADDITIVE_FIELDS)[number], string> = {\n totalBalance: sumField(states, 'totalBalance'),\n spendableBalance: sumField(states, 'spendableBalance'),\n withdrawableBalance: sumField(states, 'withdrawableBalance'),\n marginUsed: sumField(states, 'marginUsed'),\n unrealizedPnl: sumField(states, 'unrealizedPnl'),\n };\n\n const totalPnl = new BigNumber(totals.unrealizedPnl);\n const totalMarginUsed = new BigNumber(totals.marginUsed);\n const returnOnEquity = totalMarginUsed.isGreaterThan(0)\n ? totalPnl.multipliedBy(100).dividedBy(totalMarginUsed).toFixed()\n : '0';\n\n return { ...totals, returnOnEquity };\n}\n\n/**\n * Classify the enabled venues, rejecting an entire snapshot if any required\n * balance is missing or non-finite. Also usable when no combined state exists.\n *\n * @param entries - One entry per enabled venue.\n * @returns Completeness metadata over the venues with valid balances.\n */\nexport function getAccountAggregateMetadata(\n entries: PerpsProviderAccountStateEntry[],\n): AccountAggregateMetadata {\n const availableProviders: PerpsProviderType[] = [];\n const unavailableProviders: PerpsProviderType[] = [];\n const pendingProviders: PerpsProviderType[] = [];\n\n for (const entry of entries) {\n if (entry.status === 'pending') {\n pendingProviders.push(entry.providerId);\n } else if (\n entry.status === 'available' &&\n ADDITIVE_FIELDS.every(\n (field) =>\n typeof entry.state[field] === 'string' &&\n new BigNumber(entry.state[field]).isFinite(),\n )\n ) {\n availableProviders.push(entry.providerId);\n } else {\n unavailableProviders.push(entry.providerId);\n }\n }\n\n return {\n status:\n unavailableProviders.length + pendingProviders.length > 0\n ? 'partial'\n : 'complete',\n availableProviders,\n unavailableProviders,\n ...(pendingProviders.length > 0 && { pendingProviders }),\n };\n}\n\n/**\n * Combine per-venue account entries into one {@link AccountState}.\n *\n * The top-level numeric fields are combined totals over available venues\n * only; each entry reports its own venue identity and state, and\n * `aggregate` says whether the totals cover every enabled venue. The\n * combined result carries no venue identity and no venue-local margin or\n * sub-account detail.\n *\n * @param params - Combined result inputs.\n * @param params.entries - One entry per enabled venue, available or not.\n * @returns The combined state, or null when no venue has usable data: a\n * failed or not-yet-reported venue must never be presented as an all-zero\n * successful total.\n */\nexport function buildAggregatedAccountState(params: {\n entries: PerpsProviderAccountStateEntry[];\n}): AccountState | null {\n const { entries } = params;\n const metadata = getAccountAggregateMetadata(entries);\n const validatedEntries = entries.map(\n (entry): PerpsProviderAccountStateEntry =>\n entry.status === 'available' &&\n metadata.unavailableProviders.includes(entry.providerId)\n ? { status: 'unavailable', providerId: entry.providerId }\n : entry,\n );\n const availableStates = validatedEntries.flatMap((entry) =>\n entry.status === 'available' ? [entry.state] : [],\n );\n\n if (availableStates.length === 0) {\n return null;\n }\n\n return {\n ...aggregateAccountTotals(availableStates),\n providerStates: Object.fromEntries(\n validatedEntries.map((entry) => [entry.providerId, entry]),\n ),\n aggregate: metadata,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"accountAggregation.js","sourceRoot":"","sources":["../../src/utils/accountAggregation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAE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,gBAAgB,CAAC,MAAM,GAAG,CAAC,IAAI,EAAE,gBAAgB,EAAE,CAAC;KACzD,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,2BAA2B,CAAC,MAE3C;IACC,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC;IAC3B,MAAM,QAAQ,GAAG,2BAA2B,CAAC,OAAO,CAAC,CAAC;IACtD,MAAM,gBAAgB,GAAG,OAAO,CAAC,GAAG,CAClC,CAAC,KAAK,EAAkC,EAAE,CACxC,KAAK,CAAC,MAAM,KAAK,WAAW;QAC5B,QAAQ,CAAC,oBAAoB,CAAC,QAAQ,CAAC,KAAK,CAAC,UAAU,CAAC;QACtD,CAAC,CAAC,EAAE,MAAM,EAAE,aAAa,EAAE,UAAU,EAAE,KAAK,CAAC,UAAU,EAAE;QACzD,CAAC,CAAC,KAAK,CACZ,CAAC;IACF,MAAM,eAAe,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE,CACzD,KAAK,CAAC,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAClD,CAAC;IAEF,IAAI,eAAe,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACjC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,GAAG,sBAAsB,CAAC,eAAe,CAAC;QAC1C,cAAc,EAAE,MAAM,CAAC,WAAW,CAChC,gBAAgB,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC,CAC3D;QACD,SAAS,EAAE,QAAQ;KACpB,CAAC;AACJ,CAAC","sourcesContent":["import { BigNumber } from 'bignumber.js';\n\nimport { accountReturnOnEquity } from '../internal/accountReturnOnEquity.js';\nimport type {\n AccountAggregateMetadata,\n AccountState,\n PerpsProviderAccountStateEntry,\n PerpsProviderType,\n} from '../types/index.js';\n\n/**\n * Venue-neutral combined account data.\n *\n * Venue-local detail (`crossMarginSummary`, `subAccountBreakdown`) is\n * intentionally absent: cross-venue collateral is not mutually usable, so an\n * aggregate of it would imply a combined margin position that no venue\n * actually settles.\n */\nexport type AggregatedAccountTotals = {\n totalBalance: string;\n spendableBalance: string;\n withdrawableBalance: string;\n marginUsed: string;\n unrealizedPnl: string;\n returnOnEquity: string;\n};\n\n/** USD balance fields that add up across venues. */\nconst ADDITIVE_FIELDS = [\n 'totalBalance',\n 'spendableBalance',\n 'withdrawableBalance',\n 'marginUsed',\n 'unrealizedPnl',\n] as const;\n\n/**\n * Sum one decimal string field across states.\n *\n * Uses `bignumber.js`, never binary floating point. Callers supply states\n * whose required additive fields are finite decimal strings.\n *\n * @param states - The available venue states to sum over.\n * @param field - The USD field to sum.\n * @returns The decimal sum as a canonical string.\n */\nfunction sumField(\n states: AccountState[],\n field: (typeof ADDITIVE_FIELDS)[number],\n): string {\n const total = states.reduce(\n (acc, state) => acc.plus(state[field]),\n new BigNumber(0),\n );\n return total.toFixed();\n}\n\n/**\n * Build the combined totals for a set of available venue states.\n *\n * Additive USD fields are decimal-summed. `returnOnEquity` is a rate, not a\n * balance: both venues report account-level RoE in percentage points\n * (unrealized PnL relative to margin used), so the combined rate is\n * `100 x sum(unrealizedPnl) / sum(marginUsed)` — margin-weighted, never summed\n * or averaged. When no margin is used anywhere the combined RoE is '0': with\n * no collateral at work there is no meaningful rate.\n *\n * @param states - Available, valid per-venue account states.\n * @returns The venue-neutral combined totals.\n */\nexport function aggregateAccountTotals(\n states: AccountState[],\n): AggregatedAccountTotals {\n const totals: Record<(typeof ADDITIVE_FIELDS)[number], string> = {\n totalBalance: sumField(states, 'totalBalance'),\n spendableBalance: sumField(states, 'spendableBalance'),\n withdrawableBalance: sumField(states, 'withdrawableBalance'),\n marginUsed: sumField(states, 'marginUsed'),\n unrealizedPnl: sumField(states, 'unrealizedPnl'),\n };\n\n // '0' only when no margin is used; a non-finite input stays visible.\n const returnOnEquity =\n accountReturnOnEquity(totals.unrealizedPnl, totals.marginUsed)?.toFixed() ??\n '0';\n\n return { ...totals, returnOnEquity };\n}\n\n/** Inputs to {@link calculateAccountReturnOnEquity}: account totals. */\nexport type AccountReturnOnEquityParams = {\n /** Total unrealized PnL of the account's positions, in USD. */\n unrealizedPnl: number | string;\n /** Total margin the account's positions use, in USD. */\n marginUsed: number | string;\n};\n\n/**\n * Account return on equity from its totals: `100 x unrealizedPnl /\n * marginUsed`, the margin-weighted RoE of its positions\n * (`calculateWeightedReturnOnEquity`) for an account that only reports totals.\n *\n * @param params - See {@link AccountReturnOnEquityParams}.\n * @returns The return in percent (12 / 120 gives 10), or undefined when\n * `marginUsed` is not positive or an input is not a finite number.\n */\nexport function calculateAccountReturnOnEquity(\n params: AccountReturnOnEquityParams,\n): number | undefined {\n const unrealizedPnl = new BigNumber(params.unrealizedPnl);\n const marginUsed = new BigNumber(params.marginUsed);\n if (!unrealizedPnl.isFinite() || !marginUsed.isFinite()) {\n return undefined;\n }\n return accountReturnOnEquity(unrealizedPnl, marginUsed)?.toNumber();\n}\n\n/**\n * Classify the enabled venues, rejecting an entire snapshot if any required\n * balance is missing or non-finite. Also usable when no combined state exists.\n *\n * @param entries - One entry per enabled venue.\n * @returns Completeness metadata over the venues with valid balances.\n */\nexport function getAccountAggregateMetadata(\n entries: PerpsProviderAccountStateEntry[],\n): AccountAggregateMetadata {\n const availableProviders: PerpsProviderType[] = [];\n const unavailableProviders: PerpsProviderType[] = [];\n const pendingProviders: PerpsProviderType[] = [];\n\n for (const entry of entries) {\n if (entry.status === 'pending') {\n pendingProviders.push(entry.providerId);\n } else if (\n entry.status === 'available' &&\n ADDITIVE_FIELDS.every(\n (field) =>\n typeof entry.state[field] === 'string' &&\n new BigNumber(entry.state[field]).isFinite(),\n )\n ) {\n availableProviders.push(entry.providerId);\n } else {\n unavailableProviders.push(entry.providerId);\n }\n }\n\n return {\n status:\n unavailableProviders.length + pendingProviders.length > 0\n ? 'partial'\n : 'complete',\n availableProviders,\n unavailableProviders,\n ...(pendingProviders.length > 0 && { pendingProviders }),\n };\n}\n\n/**\n * Combine per-venue account entries into one {@link AccountState}.\n *\n * The top-level numeric fields are combined totals over available venues\n * only; each entry reports its own venue identity and state, and\n * `aggregate` says whether the totals cover every enabled venue. The\n * combined result carries no venue identity and no venue-local margin or\n * sub-account detail.\n *\n * @param params - Combined result inputs.\n * @param params.entries - One entry per enabled venue, available or not.\n * @returns The combined state, or null when no venue has usable data: a\n * failed or not-yet-reported venue must never be presented as an all-zero\n * successful total.\n */\nexport function buildAggregatedAccountState(params: {\n entries: PerpsProviderAccountStateEntry[];\n}): AccountState | null {\n const { entries } = params;\n const metadata = getAccountAggregateMetadata(entries);\n const validatedEntries = entries.map(\n (entry): PerpsProviderAccountStateEntry =>\n entry.status === 'available' &&\n metadata.unavailableProviders.includes(entry.providerId)\n ? { status: 'unavailable', providerId: entry.providerId }\n : entry,\n );\n const availableStates = validatedEntries.flatMap((entry) =>\n entry.status === 'available' ? [entry.state] : [],\n );\n\n if (availableStates.length === 0) {\n return null;\n }\n\n return {\n ...aggregateAccountTotals(availableStates),\n providerStates: Object.fromEntries(\n validatedEntries.map((entry) => [entry.providerId, entry]),\n ),\n aggregate: metadata,\n };\n}\n"]}
|
|
@@ -70,11 +70,12 @@ export declare function getCrossMarginSpotCollateral(spotState: SpotClearinghous
|
|
|
70
70
|
*/
|
|
71
71
|
export type AddSpotBalanceOptions = {
|
|
72
72
|
/**
|
|
73
|
-
* When `true`,
|
|
74
|
-
*
|
|
75
|
-
*
|
|
76
|
-
*
|
|
77
|
-
*
|
|
73
|
+
* When `true`, spot is the account's single USDC ledger (HyperLiquid
|
|
74
|
+
* Unified/Portfolio mode, where `withdraw3` draws from it): its USDC
|
|
75
|
+
* `total` already includes every perps DEX's account value, so it becomes
|
|
76
|
+
* `totalBalance`, and free spot USDC (`total − hold`) becomes
|
|
77
|
+
* `spendableBalance` and `withdrawableBalance`. A spot read with no USDC
|
|
78
|
+
* entry keeps the perps figures.
|
|
78
79
|
*
|
|
79
80
|
* When `false`, free spot contributes to `totalBalance` only; spendable
|
|
80
81
|
* and withdrawable stay perps-only — appropriate for venues where spot
|
|
@@ -96,6 +97,13 @@ export type AddSpotBalanceOptions = {
|
|
|
96
97
|
* unknown: folding stays off, and `spotCollateral` stays unset.
|
|
97
98
|
*/
|
|
98
99
|
abstractionMode?: HyperLiquidAbstractionMode | null;
|
|
100
|
+
/**
|
|
101
|
+
* When folding, throw `ACCOUNT_STATE_FAILED` for a USDC entry whose
|
|
102
|
+
* `total` or `hold` is missing or invalid, instead of keeping the perps
|
|
103
|
+
* figures. On a Unified account the perps figures are not the balance, so
|
|
104
|
+
* a strict read reports the account as unavailable.
|
|
105
|
+
*/
|
|
106
|
+
rejectMalformedLedger?: boolean;
|
|
99
107
|
};
|
|
100
108
|
/**
|
|
101
109
|
* Add spot USDC to the AccountState contract. Caller decides whether the
|
|
@@ -105,7 +113,7 @@ export type AddSpotBalanceOptions = {
|
|
|
105
113
|
* @param accountState - Base AccountState produced by a provider adapter.
|
|
106
114
|
* @param spotState - Raw spot clearinghouse response (HL-shaped); null or missing means no spot balance and the balances are returned unchanged.
|
|
107
115
|
* @param options - See {@link AddSpotBalanceOptions}.
|
|
108
|
-
* @returns AccountState with spot
|
|
116
|
+
* @returns AccountState with spot added to `totalBalance` (Standard), or with all three balances taken from the spot ledger when `foldIntoCollateral` is true. When `abstractionMode` is passed, `spotCollateral` is the spot USDC that counts as cross collateral.
|
|
109
117
|
*/
|
|
110
118
|
export declare function addSpotBalanceToAccountState(accountState: AccountState, spotState?: SpotClearinghouseStateResponse | null, options?: AddSpotBalanceOptions): AccountState;
|
|
111
119
|
/**
|
|
@@ -132,7 +140,10 @@ export type PerpsAccountSummary = {
|
|
|
132
140
|
* positions are liquidated when it reaches 1.
|
|
133
141
|
*/
|
|
134
142
|
accountRatio: number | undefined;
|
|
135
|
-
/**
|
|
143
|
+
/**
|
|
144
|
+
* Cross notional as a multiple of total account equity, or of the cross
|
|
145
|
+
* account value on a Standard account.
|
|
146
|
+
*/
|
|
136
147
|
accountLeverage: number | undefined;
|
|
137
148
|
/** Cross margin used over cross collateral (0.25 = 25%). */
|
|
138
149
|
crossMarginUsage: number | undefined;
|
|
@@ -153,6 +164,13 @@ export type CalculateAccountSummaryParams = {
|
|
|
153
164
|
* undefined until read.
|
|
154
165
|
*/
|
|
155
166
|
spotCollateral: number | string | undefined;
|
|
167
|
+
/**
|
|
168
|
+
* The venue account mode (`AccountState.accountMode`). Standard
|
|
169
|
+
* (`disabled`, `default`) divides account leverage by the cross account
|
|
170
|
+
* value, as Hyperliquid's Cross Account Leverage does; any other or an
|
|
171
|
+
* unknown mode divides by total equity.
|
|
172
|
+
*/
|
|
173
|
+
accountMode?: AccountState['accountMode'];
|
|
156
174
|
};
|
|
157
175
|
/**
|
|
158
176
|
* The collateral the cross positions draw on: the cross account value plus
|
|
@@ -166,17 +184,20 @@ export declare function getCrossCollateral(crossMarginSummary: CrossMarginSummar
|
|
|
166
184
|
/**
|
|
167
185
|
* Derive the account summary from the venue's cross margin figures, matching
|
|
168
186
|
* Hyperliquid: account leverage divides cross notional by total account
|
|
169
|
-
* equity, isolated margin included
|
|
170
|
-
*
|
|
187
|
+
* equity, isolated margin included (Unified, Portfolio Margin), or by the
|
|
188
|
+
* cross account value on a Standard account; account ratio and cross margin
|
|
189
|
+
* usage divide the cross maintenance margin and margin used by cross
|
|
190
|
+
* collateral.
|
|
171
191
|
*
|
|
172
192
|
* @param params - The account inputs.
|
|
173
193
|
* @param params.totalEquity - Total account equity in USD.
|
|
174
194
|
* @param params.crossMarginSummary - The venue's cross margin figures.
|
|
175
195
|
* @param params.spotCollateral - Spot USDC counted as cross collateral.
|
|
196
|
+
* @param params.accountMode - The venue account mode, when known.
|
|
176
197
|
* @returns The summary; a ratio is undefined while its inputs are unknown or
|
|
177
198
|
* its denominator is not positive.
|
|
178
199
|
*/
|
|
179
|
-
export declare function calculateAccountSummary({ totalEquity, crossMarginSummary, spotCollateral, }: CalculateAccountSummaryParams): PerpsAccountSummary;
|
|
200
|
+
export declare function calculateAccountSummary({ totalEquity, crossMarginSummary, spotCollateral, accountMode, }: CalculateAccountSummaryParams): PerpsAccountSummary;
|
|
180
201
|
/**
|
|
181
202
|
* Aggregate multiple per-DEX AccountState objects into one by summing numeric
|
|
182
203
|
* fields exactly. Collateral subtotals retain their full precision so spot
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"accountUtils.d.ts","sourceRoot":"","sources":["../../src/utils/accountUtils.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;
|
|
1
|
+
{"version":3,"file":"accountUtils.d.ts","sourceRoot":"","sources":["../../src/utils/accountUtils.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AAWtE,OAAO,KAAK,EACV,0BAA0B,EAC1B,8BAA8B,EAC/B,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EACV,YAAY,EACZ,kBAAkB,EAClB,oBAAoB,EACrB,MAAM,mBAAmB,CAAC;AAM3B;;;;;;;;;GASG;AACH,wBAAgB,qBAAqB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAK3E;AAMD,wBAAgB,cAAc,CAC5B,QAAQ,EAAE,CAAC,eAAe,GAAG,oBAAoB,CAAC,EAAE,GACnD,eAAe,GAAG,oBAAoB,GAAG,IAAI,CAM/C;AAED,wBAAgB,6BAA6B,CAC3C,QAAQ,EAAE,CAAC,eAAe,GAAG,oBAAoB,CAAC,EAAE,GACnD;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAGjC;AAED,wBAAgB,qBAAqB,CACnC,QAAQ,EAAE,CAAC,eAAe,GAAG,oBAAoB,CAAC,EAAE,GACn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,EACX,kBAAkB,EAClB,cAAc,EACd,WAAW,GACZ,EAAE,6BAA6B,GAAG,mBAAmB,CAoBrD;AAED;;;;;;;;;GASG;AACH,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,YAAY,EAAE,GAAG,YAAY,CAkB3E;AAED,wCAAwC;AACxC,MAAM,MAAM,oBAAoB,GAAG,MAAM,GAAG,SAAS,GAAG,QAAQ,CAAC;AAEjE;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CACrC,KAAK,EAAE,MAAM,GAAG,SAAS,GACxB,oBAAoB,GAAG,SAAS,CAQlC"}
|
|
@@ -3,7 +3,7 @@ import { BigNumber } from 'bignumber.js';
|
|
|
3
3
|
import { USDC_DECIMALS } from '../constants/hyperLiquidConfig.js';
|
|
4
4
|
import { CROSS_MARGIN_RATIO_THRESHOLDS } from '../constants/perpsConfig.js';
|
|
5
5
|
import { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';
|
|
6
|
-
import { hyperLiquidModeFoldsSpot } from '../types/hyperliquid-types.js';
|
|
6
|
+
import { hyperLiquidModeFoldsSpot, isHyperLiquidStandardMode, } from '../types/hyperliquid-types.js';
|
|
7
7
|
import { aggregateAccountTotals } from './accountAggregation.js';
|
|
8
8
|
import { parseFiniteDecimal } from './stringParseUtils.js';
|
|
9
9
|
const EVM_ACCOUNT_TYPES = new Set(['eip155:eoa', 'eip155:erc4337']);
|
|
@@ -217,7 +217,7 @@ export function getCrossMarginSpotCollateral(spotState, abstractionMode) {
|
|
|
217
217
|
* @param accountState - Base AccountState produced by a provider adapter.
|
|
218
218
|
* @param spotState - Raw spot clearinghouse response (HL-shaped); null or missing means no spot balance and the balances are returned unchanged.
|
|
219
219
|
* @param options - See {@link AddSpotBalanceOptions}.
|
|
220
|
-
* @returns AccountState with spot
|
|
220
|
+
* @returns AccountState with spot added to `totalBalance` (Standard), or with all three balances taken from the spot ledger when `foldIntoCollateral` is true. When `abstractionMode` is passed, `spotCollateral` is the spot USDC that counts as cross collateral.
|
|
221
221
|
*/
|
|
222
222
|
export function addSpotBalanceToAccountState(accountState, spotState, options) {
|
|
223
223
|
// Fail-closed default: align with `hyperLiquidModeFoldsSpot(null) → false`.
|
|
@@ -242,31 +242,55 @@ export function addSpotBalanceToAccountState(accountState, spotState, options) {
|
|
|
242
242
|
}
|
|
243
243
|
return { ...state, spotCollateral };
|
|
244
244
|
};
|
|
245
|
-
const spotBalance = getSpotCollateralAmount(spotState, 'total');
|
|
246
|
-
const spotHold = getSpotCollateralAmount(spotState, 'hold');
|
|
247
|
-
const freeSpot = getFreeSpotUsdc(spotState);
|
|
248
245
|
const currentTotal = new BigNumber(accountState.totalBalance);
|
|
249
|
-
const currentSpendable = new BigNumber(accountState.spendableBalance);
|
|
250
|
-
const currentWithdrawable = new BigNumber(accountState.withdrawableBalance);
|
|
251
246
|
// Preserve sentinel totals (e.g. PERPS_CONSTANTS.FallbackDataDisplay '--')
|
|
252
247
|
// rather than coercing them to NaN.
|
|
253
248
|
if (!currentTotal.isFinite()) {
|
|
254
249
|
return withSpotCollateral(accountState);
|
|
255
250
|
}
|
|
256
|
-
//
|
|
257
|
-
//
|
|
258
|
-
//
|
|
259
|
-
//
|
|
260
|
-
//
|
|
261
|
-
//
|
|
262
|
-
//
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
//
|
|
266
|
-
//
|
|
267
|
-
//
|
|
268
|
-
//
|
|
269
|
-
|
|
251
|
+
// Unified / portfolio margin keep one USDC ledger. Its spot `total` already
|
|
252
|
+
// contains the account value of every perps DEX, cross and isolated, and
|
|
253
|
+
// `hold` is every DEX's margin: on testnet the spot total equals both
|
|
254
|
+
// `raw spot + Σ accountValue` and the account value hyperliquid.xyz shows.
|
|
255
|
+
// So the ledger replaces the perps figures; adding them would count
|
|
256
|
+
// unrealized PnL twice. Folding is gated strictly on the resolved
|
|
257
|
+
// abstraction mode (callers' `foldIntoCollateral`). A read that lists no
|
|
258
|
+
// USDC, or a missing or invalid USDC `total` or `hold`, keeps the perps
|
|
259
|
+
// figures rather than reporting 0 or an unheld total; those figures are
|
|
260
|
+
// perps-only, so a strict caller (`rejectMalformedLedger`) gets a throw
|
|
261
|
+
// for a malformed entry instead.
|
|
262
|
+
//
|
|
263
|
+
// Standard / DEX-abstraction keep perps and spot apart: withdraw3 draws
|
|
264
|
+
// only from the perps ledger, so spot adds to the total alone, net of the
|
|
265
|
+
// USDC its open spot orders hold.
|
|
266
|
+
let nextTotalValue = currentTotal;
|
|
267
|
+
let freeSpot;
|
|
268
|
+
if (foldIntoCollateral) {
|
|
269
|
+
const ledgerTotal = getSpotCollateralAmount(spotState, 'total', {
|
|
270
|
+
strict: true,
|
|
271
|
+
});
|
|
272
|
+
freeSpot = getFreeSpotUsdc(spotState, { strict: true });
|
|
273
|
+
if (hasSpotCollateralBalance(spotState) &&
|
|
274
|
+
ledgerTotal !== undefined &&
|
|
275
|
+
freeSpot !== undefined) {
|
|
276
|
+
nextTotalValue = ledgerTotal;
|
|
277
|
+
}
|
|
278
|
+
else if (options?.rejectMalformedLedger === true &&
|
|
279
|
+
hasSpotCollateralBalance(spotState)) {
|
|
280
|
+
throw new Error(PERPS_ERROR_CODES.ACCOUNT_STATE_FAILED);
|
|
281
|
+
}
|
|
282
|
+
else {
|
|
283
|
+
freeSpot = undefined;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
else {
|
|
287
|
+
nextTotalValue = currentTotal
|
|
288
|
+
.plus(getSpotCollateralAmount(spotState, 'total'))
|
|
289
|
+
.minus(getSpotCollateralAmount(spotState, 'hold'));
|
|
290
|
+
}
|
|
291
|
+
const nextSpendable = resolveFoldedBalance(accountState.spendableBalance, freeSpot);
|
|
292
|
+
const nextWithdrawable = resolveFoldedBalance(accountState.withdrawableBalance, freeSpot);
|
|
293
|
+
const nextTotal = canonicalizeUsdc(nextTotalValue);
|
|
270
294
|
if (nextTotal === accountState.totalBalance &&
|
|
271
295
|
nextSpendable === accountState.spendableBalance &&
|
|
272
296
|
nextWithdrawable === accountState.withdrawableBalance) {
|
|
@@ -279,7 +303,18 @@ export function addSpotBalanceToAccountState(accountState, spotState, options) {
|
|
|
279
303
|
withdrawableBalance: nextWithdrawable,
|
|
280
304
|
});
|
|
281
305
|
}
|
|
282
|
-
|
|
306
|
+
/**
|
|
307
|
+
* Whether a spot read lists a USDC balance.
|
|
308
|
+
*
|
|
309
|
+
* @param spotState - Spot clearinghouse state.
|
|
310
|
+
* @returns True when `balances` holds a collateral coin entry.
|
|
311
|
+
*/
|
|
312
|
+
function hasSpotCollateralBalance(spotState) {
|
|
313
|
+
return (Array.isArray(spotState?.balances) &&
|
|
314
|
+
spotState.balances.some((balance) => SPOT_COLLATERAL_COINS.has(balance?.coin)));
|
|
315
|
+
}
|
|
316
|
+
function resolveFoldedBalance(currentRaw, freeSpot) {
|
|
317
|
+
const currentNumeric = new BigNumber(currentRaw);
|
|
283
318
|
if (!currentNumeric.isFinite()) {
|
|
284
319
|
// Non-finite currentNumeric means the adapter passed a sentinel like
|
|
285
320
|
// `PERPS_CONSTANTS.FallbackDataDisplay` ("--") during loading. Preserve
|
|
@@ -288,8 +323,7 @@ function resolveFoldedBalance(currentNumeric, currentRaw, freeSpot, foldIntoColl
|
|
|
288
323
|
// spot-only figure while the per-DEX perps fetch is still in flight.
|
|
289
324
|
return currentRaw;
|
|
290
325
|
}
|
|
291
|
-
|
|
292
|
-
return canonicalizeUsdc(currentNumeric.plus(spotAmount));
|
|
326
|
+
return canonicalizeUsdc(freeSpot ?? currentNumeric);
|
|
293
327
|
}
|
|
294
328
|
function canonicalizeUsdc(value) {
|
|
295
329
|
return value.decimalPlaces(USDC_DECIMALS, BigNumber.ROUND_DOWN).toFixed();
|
|
@@ -348,23 +382,29 @@ export function getCrossCollateral(crossMarginSummary, spotCollateral) {
|
|
|
348
382
|
/**
|
|
349
383
|
* Derive the account summary from the venue's cross margin figures, matching
|
|
350
384
|
* Hyperliquid: account leverage divides cross notional by total account
|
|
351
|
-
* equity, isolated margin included
|
|
352
|
-
*
|
|
385
|
+
* equity, isolated margin included (Unified, Portfolio Margin), or by the
|
|
386
|
+
* cross account value on a Standard account; account ratio and cross margin
|
|
387
|
+
* usage divide the cross maintenance margin and margin used by cross
|
|
388
|
+
* collateral.
|
|
353
389
|
*
|
|
354
390
|
* @param params - The account inputs.
|
|
355
391
|
* @param params.totalEquity - Total account equity in USD.
|
|
356
392
|
* @param params.crossMarginSummary - The venue's cross margin figures.
|
|
357
393
|
* @param params.spotCollateral - Spot USDC counted as cross collateral.
|
|
394
|
+
* @param params.accountMode - The venue account mode, when known.
|
|
358
395
|
* @returns The summary; a ratio is undefined while its inputs are unknown or
|
|
359
396
|
* its denominator is not positive.
|
|
360
397
|
*/
|
|
361
|
-
export function calculateAccountSummary({ totalEquity, crossMarginSummary, spotCollateral, }) {
|
|
398
|
+
export function calculateAccountSummary({ totalEquity, crossMarginSummary, spotCollateral, accountMode, }) {
|
|
399
|
+
const isStandard = isHyperLiquidStandardMode(accountMode);
|
|
362
400
|
const collateral = getCrossCollateral(crossMarginSummary, spotCollateral);
|
|
363
401
|
const maintenanceMargin = toFiniteNumber(crossMarginSummary?.maintenanceMargin);
|
|
364
402
|
return {
|
|
365
403
|
maintenanceMargin,
|
|
366
404
|
accountRatio: share(maintenanceMargin, collateral),
|
|
367
|
-
accountLeverage: share(toFiniteNumber(crossMarginSummary?.notional),
|
|
405
|
+
accountLeverage: share(toFiniteNumber(crossMarginSummary?.notional), isStandard
|
|
406
|
+
? toFiniteNumber(crossMarginSummary?.accountValue)
|
|
407
|
+
: toFiniteNumber(totalEquity)),
|
|
368
408
|
crossMarginUsage: share(toFiniteNumber(crossMarginSummary?.marginUsed), collateral),
|
|
369
409
|
};
|
|
370
410
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"accountUtils.js","sourceRoot":"","sources":["../../src/utils/accountUtils.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACtE,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O,KAAK,IAAI,6BAA6B,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,QAAQ,CAAC;AAC9E,CAAC","sourcesContent":["/**\n * Account utilities for Perps components\n * Handles account selection and EVM account filtering\n */\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { isCaipAccountId, parseCaipAccountId } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport { USDC_DECIMALS } from '../constants/hyperLiquidConfig.js';\nimport { CROSS_MARGIN_RATIO_THRESHOLDS } from '../constants/perpsConfig.js';\nimport { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';\nimport { hyperLiquidModeFoldsSpot } from '../types/hyperliquid-types.js';\nimport type {\n HyperLiquidAbstractionMode,\n SpotClearinghouseStateResponse,\n} from '../types/hyperliquid-types.js';\nimport type {\n AccountState,\n CrossMarginSummary,\n PerpsInternalAccount,\n} from '../types/index.js';\nimport { aggregateAccountTotals } from './accountAggregation.js';\nimport { parseFiniteDecimal } from './stringParseUtils.js';\n\nconst EVM_ACCOUNT_TYPES = new Set(['eip155:eoa', 'eip155:erc4337']);\n\n/**\n * Read the account address from a CAIP-10 account id.\n *\n * The value is validated, not split: a bare address or an id with extra\n * segments names no account, so it can never be mistaken for the selected\n * wallet because its last segment happens to match.\n *\n * @param accountId - Account id from a caller; may be malformed at runtime.\n * @returns The lowercased address, or undefined when the id is not CAIP-10.\n */\nexport function getCaipAccountAddress(accountId: string): string | undefined {\n if (!isCaipAccountId(accountId)) {\n return undefined;\n }\n return parseCaipAccountId(accountId).address.toLowerCase();\n}\n\nfunction isEvmAccountType(type: string): boolean {\n return EVM_ACCOUNT_TYPES.has(type);\n}\n\nexport function findEvmAccount(\n accounts: (InternalAccount | PerpsInternalAccount)[],\n): InternalAccount | PerpsInternalAccount | null {\n const evmAccount = accounts.find(\n (account) =>\n account && isEvmAccountType(account.type as InternalAccount['type']),\n );\n return evmAccount ?? null;\n}\n\nexport function getEvmAccountFromAccountGroup(\n accounts: (InternalAccount | PerpsInternalAccount)[],\n): { address: string } | undefined {\n const evmAccount = findEvmAccount(accounts);\n return evmAccount ? { address: evmAccount.address } : undefined;\n}\n\nexport function getSelectedEvmAccount(\n accounts: (InternalAccount | PerpsInternalAccount)[],\n): { address: string } | undefined {\n return getEvmAccountFromAccountGroup(accounts);\n}\n\ntype SelectedEvmAccountMessenger = {\n call(\n actionType:\n | 'AccountsController:getSelectedAccount'\n | 'AccountTreeController:getAccountsFromSelectedAccountGroup',\n ): unknown;\n};\n\nfunction isAccountLike(\n value: unknown,\n): value is InternalAccount | PerpsInternalAccount {\n const account = value as { address?: unknown; type?: unknown } | null;\n\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof account?.address === 'string' &&\n account.address.length > 0 &&\n typeof account.type === 'string'\n );\n}\n\nexport function getSelectedEvmAccountDetailsFromMessenger(\n messenger: SelectedEvmAccountMessenger,\n): InternalAccount | PerpsInternalAccount | undefined {\n let legacyEvmAccount: InternalAccount | PerpsInternalAccount | undefined;\n try {\n const selectedAccount = messenger.call(\n 'AccountsController:getSelectedAccount',\n );\n if (isAccountLike(selectedAccount)) {\n legacyEvmAccount = findEvmAccount([selectedAccount]) ?? undefined;\n }\n } catch {\n // Some clients expose only the account tree action.\n }\n\n try {\n const selectedAccountGroup = messenger.call(\n 'AccountTreeController:getAccountsFromSelectedAccountGroup',\n );\n if (Array.isArray(selectedAccountGroup)) {\n const groupAccounts = selectedAccountGroup.filter(isAccountLike);\n if (groupAccounts.length > 0) {\n // The legacy action can return the last EVM wallet when a different\n // account group is selected. Keep it only if it belongs to this group.\n const legacyAddress = legacyEvmAccount?.address.toLowerCase();\n if (\n legacyAddress &&\n groupAccounts.some(\n ({ address }) => address.toLowerCase() === legacyAddress,\n )\n ) {\n return legacyEvmAccount;\n }\n return findEvmAccount(groupAccounts) ?? undefined;\n }\n }\n } catch {\n // Older clients and startup can use the legacy selection.\n }\n return legacyEvmAccount;\n}\n\nexport function getSelectedEvmAccountFromMessenger(\n messenger: SelectedEvmAccountMessenger,\n): { address: string } | undefined {\n const evmAccount = getSelectedEvmAccountDetailsFromMessenger(messenger);\n\n return evmAccount ? { address: evmAccount.address } : undefined;\n}\n\nexport type ReturnOnEquityInput = {\n unrealizedPnl: string | number;\n returnOnEquity: string | number;\n /**\n * Margin the account uses. When given, it is the account's weight, so an\n * account with an RoE of 0 still counts. Without it the weight is derived\n * from PnL / RoE, which an RoE of 0 cannot give.\n */\n marginUsed?: string | number;\n};\n\nexport function calculateWeightedReturnOnEquity(\n accounts: ReturnOnEquityInput[],\n): string {\n if (accounts.length === 0) {\n return '0';\n }\n\n let totalWeightedROE = new BigNumber(0);\n let totalMarginUsed = new BigNumber(0);\n\n for (const account of accounts) {\n const unrealizedPnl =\n typeof account.unrealizedPnl === 'string'\n ? Number.parseFloat(account.unrealizedPnl)\n : account.unrealizedPnl;\n const returnOnEquity =\n typeof account.returnOnEquity === 'string'\n ? Number.parseFloat(account.returnOnEquity)\n : account.returnOnEquity;\n\n if (!Number.isFinite(unrealizedPnl) || !Number.isFinite(returnOnEquity)) {\n continue;\n }\n\n let marginUsed: number | null;\n if (account.marginUsed === undefined) {\n if (returnOnEquity === 0) {\n continue;\n }\n marginUsed = (unrealizedPnl / returnOnEquity) * 100;\n } else {\n marginUsed =\n typeof account.marginUsed === 'string'\n ? parseFiniteDecimal(account.marginUsed)\n : account.marginUsed;\n }\n\n if (\n marginUsed === null ||\n !Number.isFinite(marginUsed) ||\n marginUsed <= 0\n ) {\n continue;\n }\n\n totalWeightedROE = totalWeightedROE.plus(\n new BigNumber(returnOnEquity).times(marginUsed),\n );\n totalMarginUsed = totalMarginUsed.plus(marginUsed);\n }\n\n if (totalMarginUsed.isZero()) {\n return '0';\n }\n\n return totalWeightedROE.dividedBy(totalMarginUsed).toString();\n}\n\n// The release-branch balance bridge is USDC-only. Non-USDC spot assets must\n// not inflate the balances shown or validated by withdraw/payment flows.\nconst SPOT_COLLATERAL_COINS = new Set<string>(['USDC']);\n\n/**\n * Sums one field of the USDC spot balances.\n *\n * The default fails soft: a missing response or a non-finite amount counts as\n * zero so displayed balances still render. `{ strict: true }` returns\n * `undefined` instead. Collateral is the denominator of the account ratio, so\n * a guess would show a ratio the venue never reported. A response that lists\n * no USDC balance is a genuine `0` in both modes.\n *\n * @param spotState - Spot clearinghouse state.\n * @param field - The USDC amount to sum.\n * @param options.strict - Fail the sum when `balances` is not a list or a\n * USDC amount is missing or not finite.\n * @returns The USDC sum, or `undefined` in strict mode when the response\n * cannot be trusted.\n */\nfunction getSpotCollateralAmount(\n spotState: SpotClearinghouseStateResponse | null | undefined,\n field: 'hold' | 'total',\n options: { strict: true },\n): BigNumber | undefined;\nfunction getSpotCollateralAmount(\n spotState: SpotClearinghouseStateResponse | null | undefined,\n field: 'hold' | 'total',\n options?: { strict?: false },\n): BigNumber;\nfunction getSpotCollateralAmount(\n spotState: SpotClearinghouseStateResponse | null | undefined,\n field: 'hold' | 'total',\n options?: { strict?: boolean },\n): BigNumber | undefined {\n const strict = options?.strict === true;\n if (!spotState?.balances || !Array.isArray(spotState.balances)) {\n return strict ? undefined : new BigNumber(0);\n }\n\n let sum = new BigNumber(0);\n for (const balance of spotState.balances) {\n if (!balance?.coin || !SPOT_COLLATERAL_COINS.has(balance.coin)) {\n continue;\n }\n const raw: unknown = balance[field];\n if (strict) {\n if (raw === undefined || raw === null || raw === '') {\n return undefined;\n }\n const value = new BigNumber(raw as BigNumber.Value);\n if (!value.isFinite()) {\n return undefined;\n }\n sum = sum.plus(value);\n continue;\n }\n const value = new BigNumber((raw ?? '0') as BigNumber.Value);\n if (value.isFinite()) {\n sum = sum.plus(value);\n }\n }\n return sum;\n}\n\n/**\n * Free spot USDC, `max(0, total − hold)`, counting USDC only.\n *\n * @param spotState - Spot clearinghouse state.\n * @param options.strict - See {@link getSpotCollateralAmount}.\n * @returns Free spot USDC, or `undefined` in strict mode when either amount\n * cannot be trusted.\n */\nfunction getFreeSpotUsdc(\n spotState: SpotClearinghouseStateResponse | null | undefined,\n options: { strict: true },\n): BigNumber | undefined;\nfunction getFreeSpotUsdc(\n spotState: SpotClearinghouseStateResponse | null | undefined,\n options?: { strict?: false },\n): BigNumber;\nfunction getFreeSpotUsdc(\n spotState: SpotClearinghouseStateResponse | null | undefined,\n options?: { strict?: boolean },\n): BigNumber | undefined {\n const total =\n options?.strict === true\n ? getSpotCollateralAmount(spotState, 'total', { strict: true })\n : getSpotCollateralAmount(spotState, 'total');\n const hold =\n options?.strict === true\n ? getSpotCollateralAmount(spotState, 'hold', { strict: true })\n : getSpotCollateralAmount(spotState, 'hold');\n if (total === undefined || hold === undefined) {\n return undefined;\n }\n return BigNumber.max(0, total.minus(hold));\n}\n\nexport function getSpotBalance(\n spotState?: SpotClearinghouseStateResponse | null,\n): number {\n return getSpotCollateralAmount(spotState, 'total').toNumber();\n}\n\nexport function getSpotHold(\n spotState?: SpotClearinghouseStateResponse | null,\n): number {\n return getSpotCollateralAmount(spotState, 'hold').toNumber();\n}\n\n/**\n * Spot USDC the venue counts as cross collateral.\n *\n * Unknown spot state or an unresolved abstraction mode stays `undefined`,\n * not `0`. A ratio computed from `0` treats a Unified account as Standard\n * and overstates how close it is to liquidation. This is deliberately\n * different from {@link hyperLiquidModeFoldsSpot}, which fail-closes an\n * unknown mode to \"do not fold\" so withdrawable funds are not over-reported.\n *\n * @param spotState - Spot clearinghouse state. `null` or omitted means it\n * has not been read yet.\n * @param abstractionMode - Resolved abstraction mode. `null` or omitted\n * means it has not been read yet.\n * @returns Canonical USDC decimal string: `'0'` when spot is not collateral\n * (Standard / `default`), or free spot USDC (`max(0, total − hold)`, USDC\n * only) for Unified and portfolio margin. `undefined` until both inputs\n * are known, and for Unified or portfolio margin when a USDC `total` or\n * `hold` is missing or not a finite number. A response that lists no USDC\n * balance is a genuine `'0'`.\n */\nexport function getCrossMarginSpotCollateral(\n spotState: SpotClearinghouseStateResponse | null | undefined,\n abstractionMode: HyperLiquidAbstractionMode | null | undefined,\n): string | undefined {\n if (\n spotState === null ||\n spotState === undefined ||\n abstractionMode === null ||\n abstractionMode === undefined\n ) {\n return undefined;\n }\n if (!hyperLiquidModeFoldsSpot(abstractionMode)) {\n return '0';\n }\n const freeSpot = getFreeSpotUsdc(spotState, { strict: true });\n if (freeSpot === undefined) {\n return undefined;\n }\n return canonicalizeUsdc(freeSpot);\n}\n\n/**\n * Options controlling how `addSpotBalanceToAccountState` folds spot balance\n * into the three-field AccountState contract.\n */\nexport type AddSpotBalanceOptions = {\n /**\n * When `true`, free spot USDC contributes to both `spendableBalance` and\n * `withdrawableBalance` in addition to `totalBalance` — appropriate for\n * venues where spot is automatically used as perps collateral (e.g.\n * HyperLiquid Unified/Portfolio mode, where `withdraw3` draws from the\n * unified ledger).\n *\n * When `false`, free spot contributes to `totalBalance` only; spendable\n * and withdrawable stay perps-only — appropriate for venues where spot\n * is a separate ledger the backend cannot auto-draw from (e.g. HL\n * Standard mode). The caller is responsible for translating\n * provider-specific state into this flag.\n *\n * Defaults to `false`. Omitting the flag does not mean the mode is\n * Standard: pass `abstractionMode` to publish `spotCollateral`.\n */\n foldIntoCollateral?: boolean;\n /**\n * Resolved abstraction mode used to publish `AccountState.spotCollateral`.\n * Pass `null` while the mode is unknown. Omit the property to leave any\n * existing `spotCollateral` untouched.\n *\n * Derive `foldIntoCollateral` from the same mode via\n * `hyperLiquidModeFoldsSpot`. The two answers differ when the mode is\n * unknown: folding stays off, and `spotCollateral` stays unset.\n */\n abstractionMode?: HyperLiquidAbstractionMode | null;\n};\n\n/**\n * Add spot USDC to the AccountState contract. Caller decides whether the\n * spot balance counts as perps collateral via `options.foldIntoCollateral`\n * — the util stays provider-agnostic.\n *\n * @param accountState - Base AccountState produced by a provider adapter.\n * @param spotState - Raw spot clearinghouse response (HL-shaped); null or missing means no spot balance and the balances are returned unchanged.\n * @param options - See {@link AddSpotBalanceOptions}.\n * @returns AccountState with spot folded into `totalBalance` always, and into spendable/withdrawable when `foldIntoCollateral` is true. When `abstractionMode` is passed, `spotCollateral` is the spot USDC that counts as cross collateral.\n */\nexport function addSpotBalanceToAccountState(\n accountState: AccountState,\n spotState?: SpotClearinghouseStateResponse | null,\n options?: AddSpotBalanceOptions,\n): AccountState {\n // Fail-closed default: align with `hyperLiquidModeFoldsSpot(null) → false`.\n // A caller that omits `options` should NOT silently fold spot — that would\n // over-report withdrawable funds for Standard / default users.\n const foldIntoCollateral = options?.foldIntoCollateral ?? false;\n const publishesSpotCollateral =\n options !== undefined &&\n Object.prototype.hasOwnProperty.call(options, 'abstractionMode');\n const spotCollateral = publishesSpotCollateral\n ? getCrossMarginSpotCollateral(spotState, options?.abstractionMode)\n : undefined;\n const withSpotCollateral = (state: AccountState): AccountState => {\n if (!publishesSpotCollateral) {\n return state;\n }\n if (state.spotCollateral === spotCollateral) {\n return state;\n }\n if (spotCollateral === undefined) {\n const { spotCollateral: _removed, ...rest } = state;\n return rest;\n }\n return { ...state, spotCollateral };\n };\n\n const spotBalance = getSpotCollateralAmount(spotState, 'total');\n const spotHold = getSpotCollateralAmount(spotState, 'hold');\n const freeSpot = getFreeSpotUsdc(spotState);\n\n const currentTotal = new BigNumber(accountState.totalBalance);\n const currentSpendable = new BigNumber(accountState.spendableBalance);\n const currentWithdrawable = new BigNumber(accountState.withdrawableBalance);\n\n // Preserve sentinel totals (e.g. PERPS_CONSTANTS.FallbackDataDisplay '--')\n // rather than coercing them to NaN.\n if (!currentTotal.isFinite()) {\n return withSpotCollateral(accountState);\n }\n\n // Folding is gated strictly on the resolved abstraction mode (see callers'\n // `foldIntoCollateral` argument). Standard / DEX-abstraction users keep\n // perps and spot independent, so spot must NOT surface as a perps-\n // withdrawable balance for them — withdraw3 only draws from the perps\n // ledger in those modes. Unified / portfolio-margin users get the fold;\n // live callers fail-CLOSED via `hyperLiquidModeFoldsSpot` when mode is\n // unresolved.\n const nextSpendable = resolveFoldedBalance(\n currentSpendable,\n accountState.spendableBalance,\n freeSpot,\n foldIntoCollateral,\n );\n const nextWithdrawable = resolveFoldedBalance(\n currentWithdrawable,\n accountState.withdrawableBalance,\n freeSpot,\n foldIntoCollateral,\n );\n\n // Total always reflects combined wealth: subtract spotHold to avoid\n // double-counting on Unified/PM accounts where marginSummary.accountValue\n // already includes the margin that HL surfaces via spot.hold. Standard\n // mode has spotHold = 0 by construction, so the subtraction is a no-op.\n const nextTotal = canonicalizeUsdc(\n currentTotal.plus(spotBalance).minus(spotHold),\n );\n\n if (\n nextTotal === accountState.totalBalance &&\n nextSpendable === accountState.spendableBalance &&\n nextWithdrawable === accountState.withdrawableBalance\n ) {\n return withSpotCollateral(accountState);\n }\n\n return withSpotCollateral({\n ...accountState,\n totalBalance: nextTotal,\n spendableBalance: nextSpendable,\n withdrawableBalance: nextWithdrawable,\n });\n}\n\nfunction resolveFoldedBalance(\n currentNumeric: BigNumber,\n currentRaw: string,\n freeSpot: BigNumber,\n foldIntoCollateral: boolean,\n): string {\n if (!currentNumeric.isFinite()) {\n // Non-finite currentNumeric means the adapter passed a sentinel like\n // `PERPS_CONSTANTS.FallbackDataDisplay` (\"--\") during loading. Preserve\n // the sentinel rather than synthesising a numeric fold; the caller's\n // UI treats \"--\" as \"loading\" and would otherwise show a misleading\n // spot-only figure while the per-DEX perps fetch is still in flight.\n return currentRaw;\n }\n\n const spotAmount = foldIntoCollateral ? freeSpot : new BigNumber(0);\n return canonicalizeUsdc(currentNumeric.plus(spotAmount));\n}\n\nfunction canonicalizeUsdc(value: BigNumber): string {\n return value.decimalPlaces(USDC_DECIMALS, BigNumber.ROUND_DOWN).toFixed();\n}\n\n/**\n * Sum per-DEX cross-margin summaries. Undefined unless every state carries\n * one, so a partial sum never reads as the whole account.\n *\n * @param states - The per-DEX account states.\n * @returns The summed summary, or undefined.\n */\nexport function sumCrossMarginSummaries(\n states: AccountState[],\n): CrossMarginSummary | undefined {\n const summaries = states\n .map((state) => state.crossMarginSummary)\n .filter((summary): summary is CrossMarginSummary => summary !== undefined);\n if (summaries.length === 0 || summaries.length !== states.length) {\n return undefined;\n }\n const sum = (field: keyof CrossMarginSummary): string =>\n summaries\n .reduce((total, summary) => total.plus(summary[field]), new BigNumber(0))\n .toFixed();\n return {\n accountValue: sum('accountValue'),\n maintenanceMargin: sum('maintenanceMargin'),\n marginUsed: sum('marginUsed'),\n notional: sum('notional'),\n };\n}\n\n/**\n * A {@link CrossMarginSummary} whose figures may already be numbers.\n */\nexport type CrossMarginSummaryInput = Record<\n keyof CrossMarginSummary,\n number | string\n>;\n\n/**\n * Account figures derived from the venue's cross margin. Each is undefined\n * while its inputs are unknown.\n */\nexport type PerpsAccountSummary = {\n /** Maintenance margin the cross positions require, in USD. */\n maintenanceMargin: number | undefined;\n /**\n * Cross maintenance margin over cross collateral (0.5 = 50%). Cross\n * positions are liquidated when it reaches 1.\n */\n accountRatio: number | undefined;\n /** Cross notional as a multiple of total account equity. */\n accountLeverage: number | undefined;\n /** Cross margin used over cross collateral (0.25 = 25%). */\n crossMarginUsage: number | undefined;\n};\n\n/**\n * Inputs to {@link calculateAccountSummary}.\n */\nexport type CalculateAccountSummaryParams = {\n /**\n * Total account equity in USD, isolated margin included\n * (`AccountState.totalBalance`).\n */\n totalEquity: number | string;\n /** The venue's cross margin figures; undefined until read. */\n crossMarginSummary: CrossMarginSummaryInput | undefined;\n /**\n * Spot USDC the venue counts as cross collateral (0 when it counts none);\n * undefined until read.\n */\n spotCollateral: number | string | undefined;\n};\n\nfunction toFiniteNumber(\n value: number | string | undefined,\n): number | undefined {\n if (value === undefined) {\n return undefined;\n }\n const parsed = typeof value === 'number' ? value : Number.parseFloat(value);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n\nfunction share(\n part: number | undefined,\n whole: number | undefined,\n): number | undefined {\n return part === undefined || whole === undefined || whole <= 0\n ? undefined\n : part / whole;\n}\n\n/**\n * The collateral the cross positions draw on: the cross account value plus\n * the spot USDC the venue counts as collateral.\n *\n * @param crossMarginSummary - The venue's cross margin figures.\n * @param spotCollateral - Spot USDC counted as cross collateral.\n * @returns The cross collateral in USD, or undefined until both are known.\n */\nexport function getCrossCollateral(\n crossMarginSummary: CrossMarginSummaryInput | undefined,\n spotCollateral: number | string | undefined,\n): number | undefined {\n const accountValue = toFiniteNumber(crossMarginSummary?.accountValue);\n const spot = toFiniteNumber(spotCollateral);\n return accountValue === undefined || spot === undefined\n ? undefined\n : accountValue + spot;\n}\n\n/**\n * Derive the account summary from the venue's cross margin figures, matching\n * Hyperliquid: account leverage divides cross notional by total account\n * equity, isolated margin included; account ratio and cross margin usage\n * divide the cross maintenance margin and margin used by cross collateral.\n *\n * @param params - The account inputs.\n * @param params.totalEquity - Total account equity in USD.\n * @param params.crossMarginSummary - The venue's cross margin figures.\n * @param params.spotCollateral - Spot USDC counted as cross collateral.\n * @returns The summary; a ratio is undefined while its inputs are unknown or\n * its denominator is not positive.\n */\nexport function calculateAccountSummary({\n totalEquity,\n crossMarginSummary,\n spotCollateral,\n}: CalculateAccountSummaryParams): PerpsAccountSummary {\n const collateral = getCrossCollateral(crossMarginSummary, spotCollateral);\n const maintenanceMargin = toFiniteNumber(\n crossMarginSummary?.maintenanceMargin,\n );\n return {\n maintenanceMargin,\n accountRatio: share(maintenanceMargin, collateral),\n accountLeverage: share(\n toFiniteNumber(crossMarginSummary?.notional),\n toFiniteNumber(totalEquity),\n ),\n crossMarginUsage: share(\n toFiniteNumber(crossMarginSummary?.marginUsed),\n collateral,\n ),\n };\n}\n\n/**\n * Aggregate multiple per-DEX AccountState objects into one by summing numeric\n * fields exactly. Collateral subtotals retain their full precision so spot\n * collateral can be added before the final USDC canonicalization.\n * ROE is recalculated as (totalUnrealizedPnl / totalMarginUsed) * 100.\n *\n * @param states - The array of per-DEX account states to aggregate.\n * @returns The combined account state with summed balances and recalculated ROE.\n * @throws `ACCOUNT_STATE_FAILED` when `states` is empty.\n */\nexport function aggregateAccountStates(states: AccountState[]): AccountState {\n if (states.length === 0) {\n // No account answered: the state is unknown. A '--' placeholder in\n // numeric fields parses as NaN downstream.\n throw new Error(PERPS_ERROR_CODES.ACCOUNT_STATE_FAILED);\n }\n\n const aggregated: AccountState = {\n ...(states.length === 1 ? states[0] : {}),\n ...aggregateAccountTotals(states),\n };\n\n const crossMarginSummary = sumCrossMarginSummaries(states);\n if (crossMarginSummary) {\n aggregated.crossMarginSummary = crossMarginSummary;\n }\n\n return aggregated;\n}\n\n/** Severity of a cross-margin ratio. */\nexport type CrossMarginRatioTone = 'safe' | 'warning' | 'danger';\n\n/**\n * Severity of a cross-margin ratio against `CROSS_MARGIN_RATIO_THRESHOLDS`.\n *\n * @param ratio - `PerpsAccountSummary.accountRatio` (0.5 = 50%).\n * @returns `safe` below the warning level, `warning` up to and including the\n * danger level, `danger` above it, or undefined for a missing ratio.\n */\nexport function getCrossMarginRatioTone(\n ratio: number | undefined,\n): CrossMarginRatioTone | undefined {\n if (ratio === undefined || !Number.isFinite(ratio)) {\n return undefined;\n }\n if (ratio < CROSS_MARGIN_RATIO_THRESHOLDS.Warning) {\n return 'safe';\n }\n return ratio <= CROSS_MARGIN_RATIO_THRESHOLDS.Danger ? 'warning' : 'danger';\n}\n"]}
|
|
1
|
+
{"version":3,"file":"accountUtils.js","sourceRoot":"","sources":["../../src/utils/accountUtils.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACtE,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AAClE,OAAO,EAAE,6BAA6B,EAAE,MAAM,6BAA6B,CAAC;AAC5E,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAC1D,OAAO,EACL,wBAAwB,EACxB,yBAAyB,GAC1B,MAAM,+BAA+B,CAAC;AAUvC,OAAO,EAAE,sBAAsB,EAAE,MAAM,yBAAyB,CAAC;AACjE,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAE3D,MAAM,iBAAiB,GAAG,IAAI,GAA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kB,CAAC;IACrD,CAAC;IAED,OAAO,UAAU,CAAC;AACpB,CAAC;AAKD;;;;;;GAMG;AACH,MAAM,UAAU,uBAAuB,CACrC,KAAyB;IAEzB,IAAI,KAAK,KAAK,SAAS,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QACnD,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,IAAI,KAAK,GAAG,6BAA6B,CAAC,OAAO,EAAE,CAAC;QAClD,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,OAAO,KAAK,IAAI,6BAA6B,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,QAAQ,CAAC;AAC9E,CAAC","sourcesContent":["/**\n * Account utilities for Perps components\n * Handles account selection and EVM account filtering\n */\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport { isCaipAccountId, parseCaipAccountId } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport { USDC_DECIMALS } from '../constants/hyperLiquidConfig.js';\nimport { CROSS_MARGIN_RATIO_THRESHOLDS } from '../constants/perpsConfig.js';\nimport { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';\nimport {\n hyperLiquidModeFoldsSpot,\n isHyperLiquidStandardMode,\n} from '../types/hyperliquid-types.js';\nimport type {\n HyperLiquidAbstractionMode,\n SpotClearinghouseStateResponse,\n} from '../types/hyperliquid-types.js';\nimport type {\n AccountState,\n CrossMarginSummary,\n PerpsInternalAccount,\n} from '../types/index.js';\nimport { aggregateAccountTotals } from './accountAggregation.js';\nimport { parseFiniteDecimal } from './stringParseUtils.js';\n\nconst EVM_ACCOUNT_TYPES = new Set(['eip155:eoa', 'eip155:erc4337']);\n\n/**\n * Read the account address from a CAIP-10 account id.\n *\n * The value is validated, not split: a bare address or an id with extra\n * segments names no account, so it can never be mistaken for the selected\n * wallet because its last segment happens to match.\n *\n * @param accountId - Account id from a caller; may be malformed at runtime.\n * @returns The lowercased address, or undefined when the id is not CAIP-10.\n */\nexport function getCaipAccountAddress(accountId: string): string | undefined {\n if (!isCaipAccountId(accountId)) {\n return undefined;\n }\n return parseCaipAccountId(accountId).address.toLowerCase();\n}\n\nfunction isEvmAccountType(type: string): boolean {\n return EVM_ACCOUNT_TYPES.has(type);\n}\n\nexport function findEvmAccount(\n accounts: (InternalAccount | PerpsInternalAccount)[],\n): InternalAccount | PerpsInternalAccount | null {\n const evmAccount = accounts.find(\n (account) =>\n account && isEvmAccountType(account.type as InternalAccount['type']),\n );\n return evmAccount ?? null;\n}\n\nexport function getEvmAccountFromAccountGroup(\n accounts: (InternalAccount | PerpsInternalAccount)[],\n): { address: string } | undefined {\n const evmAccount = findEvmAccount(accounts);\n return evmAccount ? { address: evmAccount.address } : undefined;\n}\n\nexport function getSelectedEvmAccount(\n accounts: (InternalAccount | PerpsInternalAccount)[],\n): { address: string } | undefined {\n return getEvmAccountFromAccountGroup(accounts);\n}\n\ntype SelectedEvmAccountMessenger = {\n call(\n actionType:\n | 'AccountsController:getSelectedAccount'\n | 'AccountTreeController:getAccountsFromSelectedAccountGroup',\n ): unknown;\n};\n\nfunction isAccountLike(\n value: unknown,\n): value is InternalAccount | PerpsInternalAccount {\n const account = value as { address?: unknown; type?: unknown } | null;\n\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof account?.address === 'string' &&\n account.address.length > 0 &&\n typeof account.type === 'string'\n );\n}\n\nexport function getSelectedEvmAccountDetailsFromMessenger(\n messenger: SelectedEvmAccountMessenger,\n): InternalAccount | PerpsInternalAccount | undefined {\n let legacyEvmAccount: InternalAccount | PerpsInternalAccount | undefined;\n try {\n const selectedAccount = messenger.call(\n 'AccountsController:getSelectedAccount',\n );\n if (isAccountLike(selectedAccount)) {\n legacyEvmAccount = findEvmAccount([selectedAccount]) ?? undefined;\n }\n } catch {\n // Some clients expose only the account tree action.\n }\n\n try {\n const selectedAccountGroup = messenger.call(\n 'AccountTreeController:getAccountsFromSelectedAccountGroup',\n );\n if (Array.isArray(selectedAccountGroup)) {\n const groupAccounts = selectedAccountGroup.filter(isAccountLike);\n if (groupAccounts.length > 0) {\n // The legacy action can return the last EVM wallet when a different\n // account group is selected. Keep it only if it belongs to this group.\n const legacyAddress = legacyEvmAccount?.address.toLowerCase();\n if (\n legacyAddress &&\n groupAccounts.some(\n ({ address }) => address.toLowerCase() === legacyAddress,\n )\n ) {\n return legacyEvmAccount;\n }\n return findEvmAccount(groupAccounts) ?? undefined;\n }\n }\n } catch {\n // Older clients and startup can use the legacy selection.\n }\n return legacyEvmAccount;\n}\n\nexport function getSelectedEvmAccountFromMessenger(\n messenger: SelectedEvmAccountMessenger,\n): { address: string } | undefined {\n const evmAccount = getSelectedEvmAccountDetailsFromMessenger(messenger);\n\n return evmAccount ? { address: evmAccount.address } : undefined;\n}\n\nexport type ReturnOnEquityInput = {\n unrealizedPnl: string | number;\n returnOnEquity: string | number;\n /**\n * Margin the account uses. When given, it is the account's weight, so an\n * account with an RoE of 0 still counts. Without it the weight is derived\n * from PnL / RoE, which an RoE of 0 cannot give.\n */\n marginUsed?: string | number;\n};\n\nexport function calculateWeightedReturnOnEquity(\n accounts: ReturnOnEquityInput[],\n): string {\n if (accounts.length === 0) {\n return '0';\n }\n\n let totalWeightedROE = new BigNumber(0);\n let totalMarginUsed = new BigNumber(0);\n\n for (const account of accounts) {\n const unrealizedPnl =\n typeof account.unrealizedPnl === 'string'\n ? Number.parseFloat(account.unrealizedPnl)\n : account.unrealizedPnl;\n const returnOnEquity =\n typeof account.returnOnEquity === 'string'\n ? Number.parseFloat(account.returnOnEquity)\n : account.returnOnEquity;\n\n if (!Number.isFinite(unrealizedPnl) || !Number.isFinite(returnOnEquity)) {\n continue;\n }\n\n let marginUsed: number | null;\n if (account.marginUsed === undefined) {\n if (returnOnEquity === 0) {\n continue;\n }\n marginUsed = (unrealizedPnl / returnOnEquity) * 100;\n } else {\n marginUsed =\n typeof account.marginUsed === 'string'\n ? parseFiniteDecimal(account.marginUsed)\n : account.marginUsed;\n }\n\n if (\n marginUsed === null ||\n !Number.isFinite(marginUsed) ||\n marginUsed <= 0\n ) {\n continue;\n }\n\n totalWeightedROE = totalWeightedROE.plus(\n new BigNumber(returnOnEquity).times(marginUsed),\n );\n totalMarginUsed = totalMarginUsed.plus(marginUsed);\n }\n\n if (totalMarginUsed.isZero()) {\n return '0';\n }\n\n return totalWeightedROE.dividedBy(totalMarginUsed).toString();\n}\n\n// The release-branch balance bridge is USDC-only. Non-USDC spot assets must\n// not inflate the balances shown or validated by withdraw/payment flows.\nconst SPOT_COLLATERAL_COINS = new Set<string>(['USDC']);\n\n/**\n * Sums one field of the USDC spot balances.\n *\n * The default fails soft: a missing response or a non-finite amount counts as\n * zero so displayed balances still render. `{ strict: true }` returns\n * `undefined` instead. Collateral is the denominator of the account ratio, so\n * a guess would show a ratio the venue never reported. A response that lists\n * no USDC balance is a genuine `0` in both modes.\n *\n * @param spotState - Spot clearinghouse state.\n * @param field - The USDC amount to sum.\n * @param options.strict - Fail the sum when `balances` is not a list or a\n * USDC amount is missing or not finite.\n * @returns The USDC sum, or `undefined` in strict mode when the response\n * cannot be trusted.\n */\nfunction getSpotCollateralAmount(\n spotState: SpotClearinghouseStateResponse | null | undefined,\n field: 'hold' | 'total',\n options: { strict: true },\n): BigNumber | undefined;\nfunction getSpotCollateralAmount(\n spotState: SpotClearinghouseStateResponse | null | undefined,\n field: 'hold' | 'total',\n options?: { strict?: false },\n): BigNumber;\nfunction getSpotCollateralAmount(\n spotState: SpotClearinghouseStateResponse | null | undefined,\n field: 'hold' | 'total',\n options?: { strict?: boolean },\n): BigNumber | undefined {\n const strict = options?.strict === true;\n if (!spotState?.balances || !Array.isArray(spotState.balances)) {\n return strict ? undefined : new BigNumber(0);\n }\n\n let sum = new BigNumber(0);\n for (const balance of spotState.balances) {\n if (!balance?.coin || !SPOT_COLLATERAL_COINS.has(balance.coin)) {\n continue;\n }\n const raw: unknown = balance[field];\n if (strict) {\n if (raw === undefined || raw === null || raw === '') {\n return undefined;\n }\n const value = new BigNumber(raw as BigNumber.Value);\n if (!value.isFinite()) {\n return undefined;\n }\n sum = sum.plus(value);\n continue;\n }\n const value = new BigNumber((raw ?? '0') as BigNumber.Value);\n if (value.isFinite()) {\n sum = sum.plus(value);\n }\n }\n return sum;\n}\n\n/**\n * Free spot USDC, `max(0, total − hold)`, counting USDC only.\n *\n * @param spotState - Spot clearinghouse state.\n * @param options.strict - See {@link getSpotCollateralAmount}.\n * @returns Free spot USDC, or `undefined` in strict mode when either amount\n * cannot be trusted.\n */\nfunction getFreeSpotUsdc(\n spotState: SpotClearinghouseStateResponse | null | undefined,\n options: { strict: true },\n): BigNumber | undefined;\nfunction getFreeSpotUsdc(\n spotState: SpotClearinghouseStateResponse | null | undefined,\n options?: { strict?: false },\n): BigNumber;\nfunction getFreeSpotUsdc(\n spotState: SpotClearinghouseStateResponse | null | undefined,\n options?: { strict?: boolean },\n): BigNumber | undefined {\n const total =\n options?.strict === true\n ? getSpotCollateralAmount(spotState, 'total', { strict: true })\n : getSpotCollateralAmount(spotState, 'total');\n const hold =\n options?.strict === true\n ? getSpotCollateralAmount(spotState, 'hold', { strict: true })\n : getSpotCollateralAmount(spotState, 'hold');\n if (total === undefined || hold === undefined) {\n return undefined;\n }\n return BigNumber.max(0, total.minus(hold));\n}\n\nexport function getSpotBalance(\n spotState?: SpotClearinghouseStateResponse | null,\n): number {\n return getSpotCollateralAmount(spotState, 'total').toNumber();\n}\n\nexport function getSpotHold(\n spotState?: SpotClearinghouseStateResponse | null,\n): number {\n return getSpotCollateralAmount(spotState, 'hold').toNumber();\n}\n\n/**\n * Spot USDC the venue counts as cross collateral.\n *\n * Unknown spot state or an unresolved abstraction mode stays `undefined`,\n * not `0`. A ratio computed from `0` treats a Unified account as Standard\n * and overstates how close it is to liquidation. This is deliberately\n * different from {@link hyperLiquidModeFoldsSpot}, which fail-closes an\n * unknown mode to \"do not fold\" so withdrawable funds are not over-reported.\n *\n * @param spotState - Spot clearinghouse state. `null` or omitted means it\n * has not been read yet.\n * @param abstractionMode - Resolved abstraction mode. `null` or omitted\n * means it has not been read yet.\n * @returns Canonical USDC decimal string: `'0'` when spot is not collateral\n * (Standard / `default`), or free spot USDC (`max(0, total − hold)`, USDC\n * only) for Unified and portfolio margin. `undefined` until both inputs\n * are known, and for Unified or portfolio margin when a USDC `total` or\n * `hold` is missing or not a finite number. A response that lists no USDC\n * balance is a genuine `'0'`.\n */\nexport function getCrossMarginSpotCollateral(\n spotState: SpotClearinghouseStateResponse | null | undefined,\n abstractionMode: HyperLiquidAbstractionMode | null | undefined,\n): string | undefined {\n if (\n spotState === null ||\n spotState === undefined ||\n abstractionMode === null ||\n abstractionMode === undefined\n ) {\n return undefined;\n }\n if (!hyperLiquidModeFoldsSpot(abstractionMode)) {\n return '0';\n }\n const freeSpot = getFreeSpotUsdc(spotState, { strict: true });\n if (freeSpot === undefined) {\n return undefined;\n }\n return canonicalizeUsdc(freeSpot);\n}\n\n/**\n * Options controlling how `addSpotBalanceToAccountState` folds spot balance\n * into the three-field AccountState contract.\n */\nexport type AddSpotBalanceOptions = {\n /**\n * When `true`, spot is the account's single USDC ledger (HyperLiquid\n * Unified/Portfolio mode, where `withdraw3` draws from it): its USDC\n * `total` already includes every perps DEX's account value, so it becomes\n * `totalBalance`, and free spot USDC (`total − hold`) becomes\n * `spendableBalance` and `withdrawableBalance`. A spot read with no USDC\n * entry keeps the perps figures.\n *\n * When `false`, free spot contributes to `totalBalance` only; spendable\n * and withdrawable stay perps-only — appropriate for venues where spot\n * is a separate ledger the backend cannot auto-draw from (e.g. HL\n * Standard mode). The caller is responsible for translating\n * provider-specific state into this flag.\n *\n * Defaults to `false`. Omitting the flag does not mean the mode is\n * Standard: pass `abstractionMode` to publish `spotCollateral`.\n */\n foldIntoCollateral?: boolean;\n /**\n * Resolved abstraction mode used to publish `AccountState.spotCollateral`.\n * Pass `null` while the mode is unknown. Omit the property to leave any\n * existing `spotCollateral` untouched.\n *\n * Derive `foldIntoCollateral` from the same mode via\n * `hyperLiquidModeFoldsSpot`. The two answers differ when the mode is\n * unknown: folding stays off, and `spotCollateral` stays unset.\n */\n abstractionMode?: HyperLiquidAbstractionMode | null;\n /**\n * When folding, throw `ACCOUNT_STATE_FAILED` for a USDC entry whose\n * `total` or `hold` is missing or invalid, instead of keeping the perps\n * figures. On a Unified account the perps figures are not the balance, so\n * a strict read reports the account as unavailable.\n */\n rejectMalformedLedger?: boolean;\n};\n\n/**\n * Add spot USDC to the AccountState contract. Caller decides whether the\n * spot balance counts as perps collateral via `options.foldIntoCollateral`\n * — the util stays provider-agnostic.\n *\n * @param accountState - Base AccountState produced by a provider adapter.\n * @param spotState - Raw spot clearinghouse response (HL-shaped); null or missing means no spot balance and the balances are returned unchanged.\n * @param options - See {@link AddSpotBalanceOptions}.\n * @returns AccountState with spot added to `totalBalance` (Standard), or with all three balances taken from the spot ledger when `foldIntoCollateral` is true. When `abstractionMode` is passed, `spotCollateral` is the spot USDC that counts as cross collateral.\n */\nexport function addSpotBalanceToAccountState(\n accountState: AccountState,\n spotState?: SpotClearinghouseStateResponse | null,\n options?: AddSpotBalanceOptions,\n): AccountState {\n // Fail-closed default: align with `hyperLiquidModeFoldsSpot(null) → false`.\n // A caller that omits `options` should NOT silently fold spot — that would\n // over-report withdrawable funds for Standard / default users.\n const foldIntoCollateral = options?.foldIntoCollateral ?? false;\n const publishesSpotCollateral =\n options !== undefined &&\n Object.prototype.hasOwnProperty.call(options, 'abstractionMode');\n const spotCollateral = publishesSpotCollateral\n ? getCrossMarginSpotCollateral(spotState, options?.abstractionMode)\n : undefined;\n const withSpotCollateral = (state: AccountState): AccountState => {\n if (!publishesSpotCollateral) {\n return state;\n }\n if (state.spotCollateral === spotCollateral) {\n return state;\n }\n if (spotCollateral === undefined) {\n const { spotCollateral: _removed, ...rest } = state;\n return rest;\n }\n return { ...state, spotCollateral };\n };\n\n const currentTotal = new BigNumber(accountState.totalBalance);\n\n // Preserve sentinel totals (e.g. PERPS_CONSTANTS.FallbackDataDisplay '--')\n // rather than coercing them to NaN.\n if (!currentTotal.isFinite()) {\n return withSpotCollateral(accountState);\n }\n\n // Unified / portfolio margin keep one USDC ledger. Its spot `total` already\n // contains the account value of every perps DEX, cross and isolated, and\n // `hold` is every DEX's margin: on testnet the spot total equals both\n // `raw spot + Σ accountValue` and the account value hyperliquid.xyz shows.\n // So the ledger replaces the perps figures; adding them would count\n // unrealized PnL twice. Folding is gated strictly on the resolved\n // abstraction mode (callers' `foldIntoCollateral`). A read that lists no\n // USDC, or a missing or invalid USDC `total` or `hold`, keeps the perps\n // figures rather than reporting 0 or an unheld total; those figures are\n // perps-only, so a strict caller (`rejectMalformedLedger`) gets a throw\n // for a malformed entry instead.\n //\n // Standard / DEX-abstraction keep perps and spot apart: withdraw3 draws\n // only from the perps ledger, so spot adds to the total alone, net of the\n // USDC its open spot orders hold.\n let nextTotalValue = currentTotal;\n let freeSpot: BigNumber | undefined;\n if (foldIntoCollateral) {\n const ledgerTotal = getSpotCollateralAmount(spotState, 'total', {\n strict: true,\n });\n freeSpot = getFreeSpotUsdc(spotState, { strict: true });\n if (\n hasSpotCollateralBalance(spotState) &&\n ledgerTotal !== undefined &&\n freeSpot !== undefined\n ) {\n nextTotalValue = ledgerTotal;\n } else if (\n options?.rejectMalformedLedger === true &&\n hasSpotCollateralBalance(spotState)\n ) {\n throw new Error(PERPS_ERROR_CODES.ACCOUNT_STATE_FAILED);\n } else {\n freeSpot = undefined;\n }\n } else {\n nextTotalValue = currentTotal\n .plus(getSpotCollateralAmount(spotState, 'total'))\n .minus(getSpotCollateralAmount(spotState, 'hold'));\n }\n const nextSpendable = resolveFoldedBalance(\n accountState.spendableBalance,\n freeSpot,\n );\n const nextWithdrawable = resolveFoldedBalance(\n accountState.withdrawableBalance,\n freeSpot,\n );\n const nextTotal = canonicalizeUsdc(nextTotalValue);\n\n if (\n nextTotal === accountState.totalBalance &&\n nextSpendable === accountState.spendableBalance &&\n nextWithdrawable === accountState.withdrawableBalance\n ) {\n return withSpotCollateral(accountState);\n }\n\n return withSpotCollateral({\n ...accountState,\n totalBalance: nextTotal,\n spendableBalance: nextSpendable,\n withdrawableBalance: nextWithdrawable,\n });\n}\n\n/**\n * Whether a spot read lists a USDC balance.\n *\n * @param spotState - Spot clearinghouse state.\n * @returns True when `balances` holds a collateral coin entry.\n */\nfunction hasSpotCollateralBalance(\n spotState: SpotClearinghouseStateResponse | null | undefined,\n): boolean {\n return (\n Array.isArray(spotState?.balances) &&\n spotState.balances.some((balance) =>\n SPOT_COLLATERAL_COINS.has(balance?.coin),\n )\n );\n}\n\nfunction resolveFoldedBalance(\n currentRaw: string,\n freeSpot: BigNumber | undefined,\n): string {\n const currentNumeric = new BigNumber(currentRaw);\n if (!currentNumeric.isFinite()) {\n // Non-finite currentNumeric means the adapter passed a sentinel like\n // `PERPS_CONSTANTS.FallbackDataDisplay` (\"--\") during loading. Preserve\n // the sentinel rather than synthesising a numeric fold; the caller's\n // UI treats \"--\" as \"loading\" and would otherwise show a misleading\n // spot-only figure while the per-DEX perps fetch is still in flight.\n return currentRaw;\n }\n\n return canonicalizeUsdc(freeSpot ?? currentNumeric);\n}\n\nfunction canonicalizeUsdc(value: BigNumber): string {\n return value.decimalPlaces(USDC_DECIMALS, BigNumber.ROUND_DOWN).toFixed();\n}\n\n/**\n * Sum per-DEX cross-margin summaries. Undefined unless every state carries\n * one, so a partial sum never reads as the whole account.\n *\n * @param states - The per-DEX account states.\n * @returns The summed summary, or undefined.\n */\nexport function sumCrossMarginSummaries(\n states: AccountState[],\n): CrossMarginSummary | undefined {\n const summaries = states\n .map((state) => state.crossMarginSummary)\n .filter((summary): summary is CrossMarginSummary => summary !== undefined);\n if (summaries.length === 0 || summaries.length !== states.length) {\n return undefined;\n }\n const sum = (field: keyof CrossMarginSummary): string =>\n summaries\n .reduce((total, summary) => total.plus(summary[field]), new BigNumber(0))\n .toFixed();\n return {\n accountValue: sum('accountValue'),\n maintenanceMargin: sum('maintenanceMargin'),\n marginUsed: sum('marginUsed'),\n notional: sum('notional'),\n };\n}\n\n/**\n * A {@link CrossMarginSummary} whose figures may already be numbers.\n */\nexport type CrossMarginSummaryInput = Record<\n keyof CrossMarginSummary,\n number | string\n>;\n\n/**\n * Account figures derived from the venue's cross margin. Each is undefined\n * while its inputs are unknown.\n */\nexport type PerpsAccountSummary = {\n /** Maintenance margin the cross positions require, in USD. */\n maintenanceMargin: number | undefined;\n /**\n * Cross maintenance margin over cross collateral (0.5 = 50%). Cross\n * positions are liquidated when it reaches 1.\n */\n accountRatio: number | undefined;\n /**\n * Cross notional as a multiple of total account equity, or of the cross\n * account value on a Standard account.\n */\n accountLeverage: number | undefined;\n /** Cross margin used over cross collateral (0.25 = 25%). */\n crossMarginUsage: number | undefined;\n};\n\n/**\n * Inputs to {@link calculateAccountSummary}.\n */\nexport type CalculateAccountSummaryParams = {\n /**\n * Total account equity in USD, isolated margin included\n * (`AccountState.totalBalance`).\n */\n totalEquity: number | string;\n /** The venue's cross margin figures; undefined until read. */\n crossMarginSummary: CrossMarginSummaryInput | undefined;\n /**\n * Spot USDC the venue counts as cross collateral (0 when it counts none);\n * undefined until read.\n */\n spotCollateral: number | string | undefined;\n /**\n * The venue account mode (`AccountState.accountMode`). Standard\n * (`disabled`, `default`) divides account leverage by the cross account\n * value, as Hyperliquid's Cross Account Leverage does; any other or an\n * unknown mode divides by total equity.\n */\n accountMode?: AccountState['accountMode'];\n};\n\nfunction toFiniteNumber(\n value: number | string | undefined,\n): number | undefined {\n if (value === undefined) {\n return undefined;\n }\n const parsed = typeof value === 'number' ? value : Number.parseFloat(value);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n\nfunction share(\n part: number | undefined,\n whole: number | undefined,\n): number | undefined {\n return part === undefined || whole === undefined || whole <= 0\n ? undefined\n : part / whole;\n}\n\n/**\n * The collateral the cross positions draw on: the cross account value plus\n * the spot USDC the venue counts as collateral.\n *\n * @param crossMarginSummary - The venue's cross margin figures.\n * @param spotCollateral - Spot USDC counted as cross collateral.\n * @returns The cross collateral in USD, or undefined until both are known.\n */\nexport function getCrossCollateral(\n crossMarginSummary: CrossMarginSummaryInput | undefined,\n spotCollateral: number | string | undefined,\n): number | undefined {\n const accountValue = toFiniteNumber(crossMarginSummary?.accountValue);\n const spot = toFiniteNumber(spotCollateral);\n return accountValue === undefined || spot === undefined\n ? undefined\n : accountValue + spot;\n}\n\n/**\n * Derive the account summary from the venue's cross margin figures, matching\n * Hyperliquid: account leverage divides cross notional by total account\n * equity, isolated margin included (Unified, Portfolio Margin), or by the\n * cross account value on a Standard account; account ratio and cross margin\n * usage divide the cross maintenance margin and margin used by cross\n * collateral.\n *\n * @param params - The account inputs.\n * @param params.totalEquity - Total account equity in USD.\n * @param params.crossMarginSummary - The venue's cross margin figures.\n * @param params.spotCollateral - Spot USDC counted as cross collateral.\n * @param params.accountMode - The venue account mode, when known.\n * @returns The summary; a ratio is undefined while its inputs are unknown or\n * its denominator is not positive.\n */\nexport function calculateAccountSummary({\n totalEquity,\n crossMarginSummary,\n spotCollateral,\n accountMode,\n}: CalculateAccountSummaryParams): PerpsAccountSummary {\n const isStandard = isHyperLiquidStandardMode(accountMode);\n const collateral = getCrossCollateral(crossMarginSummary, spotCollateral);\n const maintenanceMargin = toFiniteNumber(\n crossMarginSummary?.maintenanceMargin,\n );\n return {\n maintenanceMargin,\n accountRatio: share(maintenanceMargin, collateral),\n accountLeverage: share(\n toFiniteNumber(crossMarginSummary?.notional),\n isStandard\n ? toFiniteNumber(crossMarginSummary?.accountValue)\n : toFiniteNumber(totalEquity),\n ),\n crossMarginUsage: share(\n toFiniteNumber(crossMarginSummary?.marginUsed),\n collateral,\n ),\n };\n}\n\n/**\n * Aggregate multiple per-DEX AccountState objects into one by summing numeric\n * fields exactly. Collateral subtotals retain their full precision so spot\n * collateral can be added before the final USDC canonicalization.\n * ROE is recalculated as (totalUnrealizedPnl / totalMarginUsed) * 100.\n *\n * @param states - The array of per-DEX account states to aggregate.\n * @returns The combined account state with summed balances and recalculated ROE.\n * @throws `ACCOUNT_STATE_FAILED` when `states` is empty.\n */\nexport function aggregateAccountStates(states: AccountState[]): AccountState {\n if (states.length === 0) {\n // No account answered: the state is unknown. A '--' placeholder in\n // numeric fields parses as NaN downstream.\n throw new Error(PERPS_ERROR_CODES.ACCOUNT_STATE_FAILED);\n }\n\n const aggregated: AccountState = {\n ...(states.length === 1 ? states[0] : {}),\n ...aggregateAccountTotals(states),\n };\n\n const crossMarginSummary = sumCrossMarginSummaries(states);\n if (crossMarginSummary) {\n aggregated.crossMarginSummary = crossMarginSummary;\n }\n\n return aggregated;\n}\n\n/** Severity of a cross-margin ratio. */\nexport type CrossMarginRatioTone = 'safe' | 'warning' | 'danger';\n\n/**\n * Severity of a cross-margin ratio against `CROSS_MARGIN_RATIO_THRESHOLDS`.\n *\n * @param ratio - `PerpsAccountSummary.accountRatio` (0.5 = 50%).\n * @returns `safe` below the warning level, `warning` up to and including the\n * danger level, `danger` above it, or undefined for a missing ratio.\n */\nexport function getCrossMarginRatioTone(\n ratio: number | undefined,\n): CrossMarginRatioTone | undefined {\n if (ratio === undefined || !Number.isFinite(ratio)) {\n return undefined;\n }\n if (ratio < CROSS_MARGIN_RATIO_THRESHOLDS.Warning) {\n return 'safe';\n }\n return ratio <= CROSS_MARGIN_RATIO_THRESHOLDS.Danger ? 'warning' : 'danger';\n}\n"]}
|