@metamask-previews/perps-controller 25.0.0-preview-d8b2a69a9 → 25.0.0-preview-a7bdec3

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.
Files changed (86) hide show
  1. package/CHANGELOG.md +40 -2
  2. package/dist/constants/eventNames.d.ts +32 -0
  3. package/dist/constants/eventNames.d.ts.map +1 -1
  4. package/dist/constants/eventNames.js +38 -0
  5. package/dist/constants/eventNames.js.map +1 -1
  6. package/dist/constants/hyperLiquidConfig.d.ts +4 -0
  7. package/dist/constants/hyperLiquidConfig.d.ts.map +1 -1
  8. package/dist/constants/hyperLiquidConfig.js +2 -0
  9. package/dist/constants/hyperLiquidConfig.js.map +1 -1
  10. package/dist/constants/perpsConfig.d.ts +25 -0
  11. package/dist/constants/perpsConfig.d.ts.map +1 -1
  12. package/dist/constants/perpsConfig.js +26 -0
  13. package/dist/constants/perpsConfig.js.map +1 -1
  14. package/dist/index.d.ts +13 -9
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +9 -6
  17. package/dist/index.js.map +1 -1
  18. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
  19. package/dist/providers/HyperLiquidProvider.js +39 -70
  20. package/dist/providers/HyperLiquidProvider.js.map +1 -1
  21. package/dist/providers/LighterProvider.d.ts.map +1 -1
  22. package/dist/providers/LighterProvider.js +10 -0
  23. package/dist/providers/LighterProvider.js.map +1 -1
  24. package/dist/services/HyperLiquidClientService.d.ts.map +1 -1
  25. package/dist/services/HyperLiquidClientService.js +4 -5
  26. package/dist/services/HyperLiquidClientService.js.map +1 -1
  27. package/dist/services/HyperLiquidSubscriptionService.d.ts +1 -13
  28. package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -1
  29. package/dist/services/HyperLiquidSubscriptionService.js +50 -296
  30. package/dist/services/HyperLiquidSubscriptionService.js.map +1 -1
  31. package/dist/types/index.d.ts +18 -10
  32. package/dist/types/index.d.ts.map +1 -1
  33. package/dist/types/index.js.map +1 -1
  34. package/dist/utils/accountUtils.d.ts +10 -0
  35. package/dist/utils/accountUtils.d.ts.map +1 -1
  36. package/dist/utils/accountUtils.js +17 -0
  37. package/dist/utils/accountUtils.js.map +1 -1
  38. package/dist/utils/closeCalculations.d.ts +41 -0
  39. package/dist/utils/closeCalculations.d.ts.map +1 -1
  40. package/dist/utils/closeCalculations.js +44 -0
  41. package/dist/utils/closeCalculations.js.map +1 -1
  42. package/dist/utils/feeAmounts.d.ts +55 -0
  43. package/dist/utils/feeAmounts.d.ts.map +1 -0
  44. package/dist/utils/feeAmounts.js +92 -0
  45. package/dist/utils/feeAmounts.js.map +1 -0
  46. package/dist/utils/hyperLiquidScaleOrders.d.ts +73 -0
  47. package/dist/utils/hyperLiquidScaleOrders.d.ts.map +1 -0
  48. package/dist/utils/hyperLiquidScaleOrders.js +195 -0
  49. package/dist/utils/hyperLiquidScaleOrders.js.map +1 -0
  50. package/dist/utils/index.d.ts +13 -4
  51. package/dist/utils/index.d.ts.map +1 -1
  52. package/dist/utils/index.js +9 -2
  53. package/dist/utils/index.js.map +1 -1
  54. package/dist/utils/orderBookGrouping.d.ts +62 -1
  55. package/dist/utils/orderBookGrouping.d.ts.map +1 -1
  56. package/dist/utils/orderBookGrouping.js +96 -1
  57. package/dist/utils/orderBookGrouping.js.map +1 -1
  58. package/dist/utils/orderBookSlippage.d.ts +39 -0
  59. package/dist/utils/orderBookSlippage.d.ts.map +1 -0
  60. package/dist/utils/orderBookSlippage.js +72 -0
  61. package/dist/utils/orderBookSlippage.js.map +1 -0
  62. package/dist/utils/orderFills.d.ts +24 -0
  63. package/dist/utils/orderFills.d.ts.map +1 -0
  64. package/dist/utils/orderFills.js +71 -0
  65. package/dist/utils/orderFills.js.map +1 -0
  66. package/dist/utils/positionCalculations.d.ts +22 -0
  67. package/dist/utils/positionCalculations.d.ts.map +1 -0
  68. package/dist/utils/positionCalculations.js +54 -0
  69. package/dist/utils/positionCalculations.js.map +1 -0
  70. package/dist/utils/priceDeviation.d.ts +27 -0
  71. package/dist/utils/priceDeviation.d.ts.map +1 -0
  72. package/dist/utils/priceDeviation.js +58 -0
  73. package/dist/utils/priceDeviation.js.map +1 -0
  74. package/dist/utils/pricePrecision.d.ts +20 -0
  75. package/dist/utils/pricePrecision.d.ts.map +1 -0
  76. package/dist/utils/pricePrecision.js +52 -0
  77. package/dist/utils/pricePrecision.js.map +1 -0
  78. package/dist/utils/tpslCalculations.d.ts +22 -0
  79. package/dist/utils/tpslCalculations.d.ts.map +1 -1
  80. package/dist/utils/tpslCalculations.js +29 -0
  81. package/dist/utils/tpslCalculations.js.map +1 -1
  82. package/docs/client-contract.md +31 -8
  83. package/docs/contracts/events.md +33 -31
  84. package/docs/venues/hyperliquid/init-flow.md +8 -25
  85. package/docs/venues/lighter/capabilities.md +1 -0
  86. package/package.json +1 -1
@@ -188,5 +188,15 @@ export declare function calculateAccountSummary({ totalEquity, crossMarginSummar
188
188
  * @throws `ACCOUNT_STATE_FAILED` when `states` is empty.
189
189
  */
190
190
  export declare function aggregateAccountStates(states: AccountState[]): AccountState;
191
+ /** Severity of a cross-margin ratio. */
192
+ export type CrossMarginRatioTone = 'safe' | 'warning' | 'danger';
193
+ /**
194
+ * Severity of a cross-margin ratio against `CROSS_MARGIN_RATIO_THRESHOLDS`.
195
+ *
196
+ * @param ratio - `PerpsAccountSummary.accountRatio` (0.5 = 50%).
197
+ * @returns `safe` below the warning level, `warning` up to and including the
198
+ * danger level, `danger` above it, or undefined for a missing ratio.
199
+ */
200
+ export declare function getCrossMarginRatioTone(ratio: number | undefined): CrossMarginRatioTone | undefined;
191
201
  export {};
192
202
  //# sourceMappingURL=accountUtils.d.ts.map
@@ -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;AAOtE,OAAO,KAAK,EACV,0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AC,EACtC,WAAW,EACX,kBAAkB,EAClB,cAAc,GACf,EAAE,6BAA6B,GAAG,mBAAmB,CAiBrD;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"}
@@ -1,6 +1,7 @@
1
1
  import { isCaipAccountId, parseCaipAccountId } from '@metamask/utils';
2
2
  import { BigNumber } from 'bignumber.js';
3
3
  import { USDC_DECIMALS } from '../constants/hyperLiquidConfig.js';
4
+ import { CROSS_MARGIN_RATIO_THRESHOLDS } from '../constants/perpsConfig.js';
4
5
  import { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';
5
6
  import { hyperLiquidModeFoldsSpot } from '../types/hyperliquid-types.js';
6
7
  import { aggregateAccountTotals } from './accountAggregation.js';
@@ -393,4 +394,20 @@ export function aggregateAccountStates(states) {
393
394
  }
394
395
  return aggregated;
395
396
  }
397
+ /**
398
+ * Severity of a cross-margin ratio against `CROSS_MARGIN_RATIO_THRESHOLDS`.
399
+ *
400
+ * @param ratio - `PerpsAccountSummary.accountRatio` (0.5 = 50%).
401
+ * @returns `safe` below the warning level, `warning` up to and including the
402
+ * danger level, `danger` above it, or undefined for a missing ratio.
403
+ */
404
+ export function getCrossMarginRatioTone(ratio) {
405
+ if (ratio === undefined || !Number.isFinite(ratio)) {
406
+ return undefined;
407
+ }
408
+ if (ratio < CROSS_MARGIN_RATIO_THRESHOLDS.Warning) {
409
+ return 'safe';
410
+ }
411
+ return ratio <= CROSS_MARGIN_RATIO_THRESHOLDS.Danger ? 'warning' : 'danger';
412
+ }
396
413
  //# sourceMappingURL=accountUtils.js.map
@@ -1 +1 @@
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,UAAU,GAAG,kBAAkB,CAAC,kBAAkB,EAAE,cAAc,CAAC,CAAC;IAC1E,MAAM,iBAAiB,GAAG,cAAc,CACtC,kBAAkB,EAAE,iBAAiB,CACtC,CAAC;IACF,OAAO;QACL,iBAAiB;QACjB,YAAY,EAAE,KAAK,CAAC,iBAAiB,EAAE,UAAU,CAAC;QAClD,eAAe,EAAE,KAAK,CACpB,cAAc,CAAC,kBAAkB,EAAE,QAAQ,CAAC,EAC5C,cAAc,CAAC,WAAW,CAAC,CAC5B;QACD,gBAAgB,EAAE,KAAK,CACrB,cAAc,CAAC,kBAAkB,EAAE,UAAU,CAAC,EAC9C,UAAU,CACX;KACF,CAAC;AACJ,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,sBAAsB,CAAC,MAAsB;IAC3D,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACxB,mEAAmE;QACnE,2CAA2C;QAC3C,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,oBAAoB,CAAC,CAAC;IAC1D,CAAC;IAED,MAAM,UAAU,GAAiB;QAC/B,GAAG,CAAC,MAAM,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QACzC,GAAG,sBAAsB,CAAC,MAAM,CAAC;KAClC,CAAC;IAEF,MAAM,kBAAkB,GAAG,uBAAuB,CAAC,MAAM,CAAC,CAAC;IAC3D,IAAI,kBAAkB,EAAE,CAAC;QACvB,UAAU,CAAC,kBAAkB,GAAG,kBAAkB,CAAC;IACrD,CAAC;IAED,OAAO,UAAU,CAAC;AACpB,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 { 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"]}
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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AK,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"]}
@@ -93,4 +93,45 @@ export declare function estimateCloseReceive({ position, providerId, closeSize,
93
93
  * empty or not a finite number.
94
94
  */
95
95
  export declare function calculateNetClosedPnl({ pnl, fee, }: NetClosedPnlParams): number | undefined;
96
+ /**
97
+ * Inputs to {@link calculateCloseSize}: the share of the position to close as
98
+ * a percent, or as a USD amount at `price`.
99
+ */
100
+ export type CloseSizeParams = {
101
+ /** Position size in base units; the sign is ignored. */
102
+ positionSize: number | string;
103
+ /** Price the close is valued at. */
104
+ price: number | string;
105
+ /** Decimals the venue accepts for a size (`PerpsOrderLimits.sizeDecimals`). */
106
+ sizeDecimals: number;
107
+ } & ({
108
+ /** Percent of the position to close, 0 to 100. */
109
+ percent: number;
110
+ usdAmount?: never;
111
+ } | {
112
+ /** USD value to close; above the position's value closes all of it. */
113
+ usdAmount: number | string;
114
+ percent?: never;
115
+ });
116
+ /** Result of {@link calculateCloseSize}. */
117
+ export type CloseSize = {
118
+ /**
119
+ * Size to close, on the venue's size grid, or the exact position size when
120
+ * the close covers the whole position.
121
+ */
122
+ size: number;
123
+ /** Value of the requested share before size rounding, in USD to the cent. */
124
+ usdValue: number;
125
+ };
126
+ /**
127
+ * Size to close for a percent or USD amount of a position, in exact decimal
128
+ * arithmetic. The size rounds half up to `sizeDecimals`; when that leaves it
129
+ * below the requested size, one size step is added so the close covers the
130
+ * requested value. The result never exceeds the position.
131
+ *
132
+ * @param params - See {@link CloseSizeParams}.
133
+ * @returns The close size and value, or undefined when an input is missing,
134
+ * out of range or not a number, or the position is empty.
135
+ */
136
+ export declare function calculateCloseSize(params: CloseSizeParams): CloseSize | undefined;
96
137
  //# sourceMappingURL=closeCalculations.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"closeCalculations.d.ts","sourceRoot":"","sources":["../../src/utils/closeCalculations.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,iBAAiB,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAerE;;GAEG;AACH,MAAM,MAAM,0BAA0B,GAAG;IACvC,mEAAmE;IACnE,QAAQ,EAAE,IAAI,CACZ,QAAQ,EACR,MAAM,GAAG,YAAY,GAAG,YAAY,GAAG,eAAe,CACvD,GAAG;QACF,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC,CAAC;KAC9C,CAAC;IACF;;;;;OAKG;IACH,UAAU,EAAE,iBAAiB,CAAC;IAC9B;;;OAGG;IACH,SAAS,EAAE,MAAM,GAAG,MAAM,CAAC;IAC3B;;;OAGG;IACH,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;IACnC;;;;;OAKG;IACH,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;CAC7B,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,oBAAoB,GAAG;IACjC,oFAAoF;IACpF,cAAc,EAAE,MAAM,GAAG,SAAS,CAAC;IACnC,0D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ACJ,CAAC;AAEF,4CAA4C;AAC5C,MAAM,MAAM,SAAS,GAAG;IACtB;;;OAGG;IACH,IAAI,EAAE,MAAM,CAAC;IACb,6EAA6E;IAC7E,QAAQ,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,eAAe,GACtB,SAAS,GAAG,SAAS,CAqCvB"}
@@ -127,4 +127,48 @@ export function calculateNetClosedPnl({ pnl, fee, }) {
127
127
  ? undefined
128
128
  : gross.minus(cost).toNumber();
129
129
  }
130
+ /**
131
+ * Size to close for a percent or USD amount of a position, in exact decimal
132
+ * arithmetic. The size rounds half up to `sizeDecimals`; when that leaves it
133
+ * below the requested size, one size step is added so the close covers the
134
+ * requested value. The result never exceeds the position.
135
+ *
136
+ * @param params - See {@link CloseSizeParams}.
137
+ * @returns The close size and value, or undefined when an input is missing,
138
+ * out of range or not a number, or the position is empty.
139
+ */
140
+ export function calculateCloseSize(params) {
141
+ const { sizeDecimals } = params;
142
+ const positionSize = toDecimal(params.positionSize)?.abs();
143
+ const price = toPositiveDecimal(params.price);
144
+ if (!Number.isInteger(sizeDecimals) ||
145
+ sizeDecimals < 0 ||
146
+ !positionSize?.isGreaterThan(0) ||
147
+ price === undefined) {
148
+ return undefined;
149
+ }
150
+ let requestedSize;
151
+ if (params.usdAmount === undefined) {
152
+ const percent = toDecimal(params.percent);
153
+ if (percent === undefined || percent.lt(0) || percent.gt(100)) {
154
+ return undefined;
155
+ }
156
+ requestedSize = percent.dividedBy(100).multipliedBy(positionSize);
157
+ }
158
+ else {
159
+ const usdAmount = toDecimal(params.usdAmount);
160
+ if (usdAmount === undefined || usdAmount.lt(0)) {
161
+ return undefined;
162
+ }
163
+ requestedSize = BigNumber.min(usdAmount.dividedBy(price), positionSize);
164
+ }
165
+ let size = requestedSize.decimalPlaces(sizeDecimals, BigNumber.ROUND_HALF_UP);
166
+ if (size.lt(requestedSize)) {
167
+ size = size.plus(new BigNumber(1).shiftedBy(-sizeDecimals));
168
+ }
169
+ return {
170
+ size: BigNumber.min(size, positionSize).toNumber(),
171
+ usdValue: roundUsd(requestedSize.multipliedBy(price)).toNumber(),
172
+ };
173
+ }
130
174
  //# sourceMappingURL=closeCalculations.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"closeCalculations.js","sourceRoot":"","sources":["../../src/utils/closeCalculations.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AAGpE;;;;;;;GAOG;AACH,MAAM,kCAAkC,GAAuC;IAC7E,WAAW,EAAE,IAAI;IACjB,OAAO,EAAE,KAAK;CACf,CAAC;AAqEF,SAAS,SAAS,CAAC,KAAkC;IACnD,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACxB,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,MAAM,OAAO,GAAG,IAAI,SAAS,CAAC,KAAK,CAAC,CAAC;IACrC,OAAO,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;AAClD,CAAC;AAED,SAAS,iBAAiB,CACxB,KAAkC;IAElC,MAAM,OAAO,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC;IACjC,OAAO,OAAO,EAAE,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;AACzD,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,iBAAiB,CACxB,QAAgD,EAChD,UAA6B;IAE7B,IAAI,QAAQ,CAAC,QAAQ,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;QAC1C,OAAO,IAAI,SAAS,CAAC,CAAC,CAAC,CAAC;IAC1B,CAAC;IACD,IACE,CAAC,MAAM,CAAC,MAAM,CAAC,kCAAkC,EAAE,UAAU,CAAC;QAC9D,CAAC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,EACpC,GAAG,EACH,GAAG,GACgB;IACnB,MAAM,KAAK,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC;IAC7B,MAAM,IAAI,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC;IAC5B,OAAO,KAAK,KAAK,SAAS,IAAI,IAAI,KAAK,SAAS;QAC9C,CAAC,CAAC,SAAS;QACX,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,CAAC;AACnC,CAAC","sourcesContent":["/**\n * Close-position figures shared by Mobile, Extension and Terminal: the cash a\n * close returns (\"You'll receive\") and a fill's closed PnL net of its fee.\n */\nimport { BigNumber } from 'bignumber.js';\n\nimport { CLOSE_POSITION_CONFIG } from '../constants/perpsConfig.js';\nimport type { PerpsProviderType, Position } from '../types/index.js';\n\n/**\n * Whether a provider's isolated `Position.marginUsed` is the collateral\n * backing the position. Hyperliquid's is, with the unrealized PnL at mark\n * included. Lighter's is the initial margin the position requires at its\n * current value; its allocated collateral is not on `Position`, so the margin\n * a Lighter isolated close returns is unknown. Cross `marginUsed` is taken as\n * reported and never holds the unrealized PnL.\n */\nconst ISOLATED_MARGIN_USED_IS_COLLATERAL: Record<PerpsProviderType, boolean> = {\n hyperliquid: true,\n lighter: false,\n};\n\n/**\n * Inputs to {@link estimateCloseReceive}.\n */\nexport type CloseReceiveEstimateParams = {\n /** The position being closed; a `Position` can be passed as-is. */\n position: Pick<\n Position,\n 'size' | 'entryPrice' | 'marginUsed' | 'unrealizedPnl'\n > & {\n leverage: Pick<Position['leverage'], 'type'>;\n };\n /**\n * Provider holding the position. It decides whether isolated `marginUsed`\n * is the position's collateral; for Lighter or an unknown provider,\n * isolated margin returned is undefined. `Position.providerId` is only set\n * under aggregation, so pass the provider explicitly.\n */\n providerId: PerpsProviderType;\n /**\n * Size to close in base units, unsigned: the whole position or part of it.\n * A size above the position size closes the whole position.\n */\n closeSize: number | string;\n /**\n * Price the close executes at: the limit price of a limit close, else the\n * live price. Undefined until known.\n */\n price: number | string | undefined;\n /**\n * Total fee rate for the close as a decimal (0.00145 = 0.145%), such as\n * `FeeCalculationResult.feeRate` from `calculateFees` for this close, which\n * already applies the maker or taker rate and any fee discount. Undefined\n * until quoted.\n */\n feeRate: number | undefined;\n};\n\n/**\n * The cash a close returns, in USD. Each figure is undefined while an input it\n * needs is missing or unusable; none falls back to 0.\n */\nexport type CloseReceiveEstimate = {\n /** The closed share of the margin backing the position, unrealized PnL excluded. */\n marginReturned: number | undefined;\n /** PnL realized on the closed size at the close price. */\n realizedPnl: number | undefined;\n /** Fee on the closed notional at the supplied fee rate. */\n fee: number | undefined;\n /**\n * `marginReturned + realizedPnl`, less `fee`, each of the two rounded first\n * to `CLOSE_POSITION_CONFIG.UsdDecimalPlaces` decimals, half away from zero.\n * A margin row that includes the PnL and a fee row, shown at that rounding,\n * add up to it. Undefined unless all three are known.\n */\n receive: number | undefined;\n};\n\n/**\n * Inputs to {@link calculateNetClosedPnl}. An `OrderFill` can be passed as-is.\n */\nexport type NetClosedPnlParams = {\n /** Realized PnL the venue reported for the fill (`OrderFill.pnl`). */\n pnl?: number | string;\n /** Fee paid on the fill (`OrderFill.fee`). */\n fee?: number | string;\n};\n\nfunction toDecimal(value: number | string | undefined): BigNumber | undefined {\n if (value === undefined) {\n return undefined;\n }\n const decimal = new BigNumber(value);\n return decimal.isFinite() ? decimal : undefined;\n}\n\nfunction toPositiveDecimal(\n value: number | string | undefined,\n): BigNumber | undefined {\n const decimal = toDecimal(value);\n return decimal?.isGreaterThan(0) ? decimal : undefined;\n}\n\n/**\n * The unrealized PnL the position's margin holds: all of it for isolated\n * margin that is the position's collateral, none for cross margin.\n *\n * @param position - The position being closed.\n * @param providerId - Provider holding the position.\n * @returns The held PnL, or undefined when it or the collateral is unknown.\n */\nfunction heldUnrealizedPnl(\n position: CloseReceiveEstimateParams['position'],\n providerId: PerpsProviderType,\n): BigNumber | undefined {\n if (position.leverage.type !== 'isolated') {\n return new BigNumber(0);\n }\n if (\n !Object.hasOwn(ISOLATED_MARGIN_USED_IS_COLLATERAL, providerId) ||\n !ISOLATED_MARGIN_USED_IS_COLLATERAL[providerId]\n ) {\n return undefined;\n }\n return toDecimal(position.unrealizedPnl);\n}\n\nfunction roundUsd(value: BigNumber): BigNumber {\n return value.decimalPlaces(\n CLOSE_POSITION_CONFIG.UsdDecimalPlaces,\n BigNumber.ROUND_HALF_UP,\n );\n}\n\n/**\n * Estimate the cash a close returns: the closed share of the position's\n * backing margin, plus the PnL realized at the close price, minus the fee.\n *\n * Backing margin is `marginUsed`, less the unrealized PnL for Hyperliquid\n * isolated margin, which holds it. Cross margin is taken as reported. Lighter\n * isolated `marginUsed` is required margin, not the allocated collateral, so\n * its margin returned and receive are undefined. The realized PnL replaces the\n * mark-price PnL, so a limit close is quoted at its limit price. A close is\n * reduce-only, so a `closeSize` above the position size closes the whole\n * position.\n *\n * @param params - The close inputs.\n * @param params.position - The position being closed.\n * @param params.providerId - Provider holding the position.\n * @param params.closeSize - Unsigned size to close, in base units.\n * @param params.price - Price the close executes at.\n * @param params.feeRate - Total fee rate for the close, as a decimal.\n * @returns The estimate; a figure is undefined while an input it needs is\n * missing or unusable.\n */\nexport function estimateCloseReceive({\n position,\n providerId,\n closeSize,\n price,\n feeRate,\n}: CloseReceiveEstimateParams): CloseReceiveEstimate {\n const size = toDecimal(position.size);\n const positionSize = size?.isZero() ? undefined : size;\n const requested = toPositiveDecimal(closeSize);\n const closing =\n requested !== undefined && positionSize !== undefined\n ? BigNumber.min(requested, positionSize.abs())\n : requested;\n const closePrice = toPositiveDecimal(price);\n const entryPrice = toPositiveDecimal(position.entryPrice);\n const rate = toDecimal(feeRate);\n\n const marginUsed = toDecimal(position.marginUsed);\n const heldPnl = heldUnrealizedPnl(position, providerId);\n\n const marginReturned =\n marginUsed !== undefined &&\n heldPnl !== undefined &&\n positionSize !== undefined &&\n closing !== undefined\n ? marginUsed.minus(heldPnl).times(closing).div(positionSize.abs())\n : undefined;\n const realizedPnl =\n positionSize !== undefined &&\n closing !== undefined &&\n closePrice !== undefined &&\n entryPrice !== undefined\n ? (positionSize.isNegative()\n ? entryPrice.minus(closePrice)\n : closePrice.minus(entryPrice)\n ).times(closing)\n : undefined;\n const fee =\n closing !== undefined && closePrice !== undefined && rate !== undefined\n ? closing.times(closePrice).times(rate)\n : undefined;\n const receive =\n marginReturned !== undefined &&\n realizedPnl !== undefined &&\n fee !== undefined\n ? roundUsd(marginReturned.plus(realizedPnl)).minus(roundUsd(fee))\n : undefined;\n\n return {\n marginReturned: marginReturned?.toNumber(),\n realizedPnl: realizedPnl?.toNumber(),\n fee: fee?.toNumber(),\n receive: receive?.toNumber(),\n };\n}\n\n/**\n * A fill's closed PnL net of its fee: the venue's realized PnL less the fee\n * paid on the fill.\n *\n * @param params - The fill figures.\n * @param params.pnl - Realized PnL the venue reported.\n * @param params.fee - Fee paid on the fill.\n * @returns The net PnL in USD, or undefined when either figure is missing,\n * empty or not a finite number.\n */\nexport function calculateNetClosedPnl({\n pnl,\n fee,\n}: NetClosedPnlParams): number | undefined {\n const gross = toDecimal(pnl);\n const cost = toDecimal(fee);\n return gross === undefined || cost === undefined\n ? undefined\n : gross.minus(cost).toNumber();\n}\n"]}
1
+ {"version":3,"file":"closeCalculations.js","sourceRoot":"","sources":["../../src/utils/closeCalculations.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AAGpE;;;;;;;GAOG;AACH,MAAM,kCAAkC,GAAuC;IAC7E,WAAW,EAAE,IAAI;IACjB,OAAO,EAAE,KAAK;CACf,CAAC;AAqEF,SAAS,SAAS,CAAC,KAAkC;IACnD,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACxB,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,MAAM,OAAO,GAAG,IAAI,SAAS,CAAC,KAAK,CAAC,CAAC;IACrC,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,EAAE,QAAQ,CAAC,aAAa,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC,QAAQ,EAAE;KACjE,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Close-position figures shared by Mobile, Extension and Terminal: the cash a\n * close returns (\"You'll receive\") and a fill's closed PnL net of its fee.\n */\nimport { BigNumber } from 'bignumber.js';\n\nimport { CLOSE_POSITION_CONFIG } from '../constants/perpsConfig.js';\nimport type { PerpsProviderType, Position } from '../types/index.js';\n\n/**\n * Whether a provider's isolated `Position.marginUsed` is the collateral\n * backing the position. Hyperliquid's is, with the unrealized PnL at mark\n * included. Lighter's is the initial margin the position requires at its\n * current value; its allocated collateral is not on `Position`, so the margin\n * a Lighter isolated close returns is unknown. Cross `marginUsed` is taken as\n * reported and never holds the unrealized PnL.\n */\nconst ISOLATED_MARGIN_USED_IS_COLLATERAL: Record<PerpsProviderType, boolean> = {\n hyperliquid: true,\n lighter: false,\n};\n\n/**\n * Inputs to {@link estimateCloseReceive}.\n */\nexport type CloseReceiveEstimateParams = {\n /** The position being closed; a `Position` can be passed as-is. */\n position: Pick<\n Position,\n 'size' | 'entryPrice' | 'marginUsed' | 'unrealizedPnl'\n > & {\n leverage: Pick<Position['leverage'], 'type'>;\n };\n /**\n * Provider holding the position. It decides whether isolated `marginUsed`\n * is the position's collateral; for Lighter or an unknown provider,\n * isolated margin returned is undefined. `Position.providerId` is only set\n * under aggregation, so pass the provider explicitly.\n */\n providerId: PerpsProviderType;\n /**\n * Size to close in base units, unsigned: the whole position or part of it.\n * A size above the position size closes the whole position.\n */\n closeSize: number | string;\n /**\n * Price the close executes at: the limit price of a limit close, else the\n * live price. Undefined until known.\n */\n price: number | string | undefined;\n /**\n * Total fee rate for the close as a decimal (0.00145 = 0.145%), such as\n * `FeeCalculationResult.feeRate` from `calculateFees` for this close, which\n * already applies the maker or taker rate and any fee discount. Undefined\n * until quoted.\n */\n feeRate: number | undefined;\n};\n\n/**\n * The cash a close returns, in USD. Each figure is undefined while an input it\n * needs is missing or unusable; none falls back to 0.\n */\nexport type CloseReceiveEstimate = {\n /** The closed share of the margin backing the position, unrealized PnL excluded. */\n marginReturned: number | undefined;\n /** PnL realized on the closed size at the close price. */\n realizedPnl: number | undefined;\n /** Fee on the closed notional at the supplied fee rate. */\n fee: number | undefined;\n /**\n * `marginReturned + realizedPnl`, less `fee`, each of the two rounded first\n * to `CLOSE_POSITION_CONFIG.UsdDecimalPlaces` decimals, half away from zero.\n * A margin row that includes the PnL and a fee row, shown at that rounding,\n * add up to it. Undefined unless all three are known.\n */\n receive: number | undefined;\n};\n\n/**\n * Inputs to {@link calculateNetClosedPnl}. An `OrderFill` can be passed as-is.\n */\nexport type NetClosedPnlParams = {\n /** Realized PnL the venue reported for the fill (`OrderFill.pnl`). */\n pnl?: number | string;\n /** Fee paid on the fill (`OrderFill.fee`). */\n fee?: number | string;\n};\n\nfunction toDecimal(value: number | string | undefined): BigNumber | undefined {\n if (value === undefined) {\n return undefined;\n }\n const decimal = new BigNumber(value);\n return decimal.isFinite() ? decimal : undefined;\n}\n\nfunction toPositiveDecimal(\n value: number | string | undefined,\n): BigNumber | undefined {\n const decimal = toDecimal(value);\n return decimal?.isGreaterThan(0) ? decimal : undefined;\n}\n\n/**\n * The unrealized PnL the position's margin holds: all of it for isolated\n * margin that is the position's collateral, none for cross margin.\n *\n * @param position - The position being closed.\n * @param providerId - Provider holding the position.\n * @returns The held PnL, or undefined when it or the collateral is unknown.\n */\nfunction heldUnrealizedPnl(\n position: CloseReceiveEstimateParams['position'],\n providerId: PerpsProviderType,\n): BigNumber | undefined {\n if (position.leverage.type !== 'isolated') {\n return new BigNumber(0);\n }\n if (\n !Object.hasOwn(ISOLATED_MARGIN_USED_IS_COLLATERAL, providerId) ||\n !ISOLATED_MARGIN_USED_IS_COLLATERAL[providerId]\n ) {\n return undefined;\n }\n return toDecimal(position.unrealizedPnl);\n}\n\nfunction roundUsd(value: BigNumber): BigNumber {\n return value.decimalPlaces(\n CLOSE_POSITION_CONFIG.UsdDecimalPlaces,\n BigNumber.ROUND_HALF_UP,\n );\n}\n\n/**\n * Estimate the cash a close returns: the closed share of the position's\n * backing margin, plus the PnL realized at the close price, minus the fee.\n *\n * Backing margin is `marginUsed`, less the unrealized PnL for Hyperliquid\n * isolated margin, which holds it. Cross margin is taken as reported. Lighter\n * isolated `marginUsed` is required margin, not the allocated collateral, so\n * its margin returned and receive are undefined. The realized PnL replaces the\n * mark-price PnL, so a limit close is quoted at its limit price. A close is\n * reduce-only, so a `closeSize` above the position size closes the whole\n * position.\n *\n * @param params - The close inputs.\n * @param params.position - The position being closed.\n * @param params.providerId - Provider holding the position.\n * @param params.closeSize - Unsigned size to close, in base units.\n * @param params.price - Price the close executes at.\n * @param params.feeRate - Total fee rate for the close, as a decimal.\n * @returns The estimate; a figure is undefined while an input it needs is\n * missing or unusable.\n */\nexport function estimateCloseReceive({\n position,\n providerId,\n closeSize,\n price,\n feeRate,\n}: CloseReceiveEstimateParams): CloseReceiveEstimate {\n const size = toDecimal(position.size);\n const positionSize = size?.isZero() ? undefined : size;\n const requested = toPositiveDecimal(closeSize);\n const closing =\n requested !== undefined && positionSize !== undefined\n ? BigNumber.min(requested, positionSize.abs())\n : requested;\n const closePrice = toPositiveDecimal(price);\n const entryPrice = toPositiveDecimal(position.entryPrice);\n const rate = toDecimal(feeRate);\n\n const marginUsed = toDecimal(position.marginUsed);\n const heldPnl = heldUnrealizedPnl(position, providerId);\n\n const marginReturned =\n marginUsed !== undefined &&\n heldPnl !== undefined &&\n positionSize !== undefined &&\n closing !== undefined\n ? marginUsed.minus(heldPnl).times(closing).div(positionSize.abs())\n : undefined;\n const realizedPnl =\n positionSize !== undefined &&\n closing !== undefined &&\n closePrice !== undefined &&\n entryPrice !== undefined\n ? (positionSize.isNegative()\n ? entryPrice.minus(closePrice)\n : closePrice.minus(entryPrice)\n ).times(closing)\n : undefined;\n const fee =\n closing !== undefined && closePrice !== undefined && rate !== undefined\n ? closing.times(closePrice).times(rate)\n : undefined;\n const receive =\n marginReturned !== undefined &&\n realizedPnl !== undefined &&\n fee !== undefined\n ? roundUsd(marginReturned.plus(realizedPnl)).minus(roundUsd(fee))\n : undefined;\n\n return {\n marginReturned: marginReturned?.toNumber(),\n realizedPnl: realizedPnl?.toNumber(),\n fee: fee?.toNumber(),\n receive: receive?.toNumber(),\n };\n}\n\n/**\n * A fill's closed PnL net of its fee: the venue's realized PnL less the fee\n * paid on the fill.\n *\n * @param params - The fill figures.\n * @param params.pnl - Realized PnL the venue reported.\n * @param params.fee - Fee paid on the fill.\n * @returns The net PnL in USD, or undefined when either figure is missing,\n * empty or not a finite number.\n */\nexport function calculateNetClosedPnl({\n pnl,\n fee,\n}: NetClosedPnlParams): number | undefined {\n const gross = toDecimal(pnl);\n const cost = toDecimal(fee);\n return gross === undefined || cost === undefined\n ? undefined\n : gross.minus(cost).toNumber();\n}\n\n/**\n * Inputs to {@link calculateCloseSize}: the share of the position to close as\n * a percent, or as a USD amount at `price`.\n */\nexport type CloseSizeParams = {\n /** Position size in base units; the sign is ignored. */\n positionSize: number | string;\n /** Price the close is valued at. */\n price: number | string;\n /** Decimals the venue accepts for a size (`PerpsOrderLimits.sizeDecimals`). */\n sizeDecimals: number;\n} & (\n | {\n /** Percent of the position to close, 0 to 100. */\n percent: number;\n usdAmount?: never;\n }\n | {\n /** USD value to close; above the position's value closes all of it. */\n usdAmount: number | string;\n percent?: never;\n }\n);\n\n/** Result of {@link calculateCloseSize}. */\nexport type CloseSize = {\n /**\n * Size to close, on the venue's size grid, or the exact position size when\n * the close covers the whole position.\n */\n size: number;\n /** Value of the requested share before size rounding, in USD to the cent. */\n usdValue: number;\n};\n\n/**\n * Size to close for a percent or USD amount of a position, in exact decimal\n * arithmetic. The size rounds half up to `sizeDecimals`; when that leaves it\n * below the requested size, one size step is added so the close covers the\n * requested value. The result never exceeds the position.\n *\n * @param params - See {@link CloseSizeParams}.\n * @returns The close size and value, or undefined when an input is missing,\n * out of range or not a number, or the position is empty.\n */\nexport function calculateCloseSize(\n params: CloseSizeParams,\n): CloseSize | undefined {\n const { sizeDecimals } = params;\n const positionSize = toDecimal(params.positionSize)?.abs();\n const price = toPositiveDecimal(params.price);\n if (\n !Number.isInteger(sizeDecimals) ||\n sizeDecimals < 0 ||\n !positionSize?.isGreaterThan(0) ||\n price === undefined\n ) {\n return undefined;\n }\n\n let requestedSize: BigNumber;\n if (params.usdAmount === undefined) {\n const percent = toDecimal(params.percent);\n if (percent === undefined || percent.lt(0) || percent.gt(100)) {\n return undefined;\n }\n requestedSize = percent.dividedBy(100).multipliedBy(positionSize);\n } else {\n const usdAmount = toDecimal(params.usdAmount);\n if (usdAmount === undefined || usdAmount.lt(0)) {\n return undefined;\n }\n requestedSize = BigNumber.min(usdAmount.dividedBy(price), positionSize);\n }\n\n let size = requestedSize.decimalPlaces(sizeDecimals, BigNumber.ROUND_HALF_UP);\n if (size.lt(requestedSize)) {\n size = size.plus(new BigNumber(1).shiftedBy(-sizeDecimals));\n }\n\n return {\n size: BigNumber.min(size, positionSize).toNumber(),\n usdValue: roundUsd(requestedSize.multipliedBy(price)).toNumber(),\n };\n}\n"]}
@@ -0,0 +1,55 @@
1
+ import type { FeeCalculationResult } from '../types/index.js';
2
+ /** Inputs to {@link calculateFeeNotionalUsd}. */
3
+ export type FeeNotionalParams = ({
4
+ /** Order value in USD. */
5
+ usdAmount: number | string;
6
+ } | {
7
+ /** Size in base units; the sign is ignored. */
8
+ size: number | string;
9
+ /**
10
+ * Price the size is valued at. For a take-profit and stop-loss pair,
11
+ * pass both trigger prices: the higher one sets the notional, and a
12
+ * blank (`''`) or lone `.` leg counts as unset.
13
+ */
14
+ price: number | string | readonly [number | string, number | string];
15
+ }) & {
16
+ /** Percent of the notional the order covers, such as a partial close. Defaults to 100. */
17
+ closePercent?: number;
18
+ /** Multiplier on the notional, such as 2 for a flip that closes and reopens. Defaults to 1. */
19
+ multiplier?: number;
20
+ };
21
+ /**
22
+ * USD notional a fee is charged on: the absolute order value, or size times
23
+ * price (the higher trigger price of a TP/SL pair), scaled by `closePercent`
24
+ * and `multiplier`.
25
+ *
26
+ * @param params - See {@link FeeNotionalParams}. Strings may carry `$` or `,`.
27
+ * @returns The notional, or undefined when an input is empty, malformed or
28
+ * not finite.
29
+ */
30
+ export declare function calculateFeeNotionalUsd(params: FeeNotionalParams): number | undefined;
31
+ /**
32
+ * Total fee rate before a MetaMask fee discount: the protocol rate plus
33
+ * `undiscountedMetamaskFeeRate`. Equal to `feeRate` when no discount applied
34
+ * or the quote does not report the undiscounted rate.
35
+ *
36
+ * @param feeResult - A fee quote from `calculateFees`.
37
+ * @returns The undiscounted rate as a decimal, or undefined when `feeRate` is
38
+ * unknown and no discount is reported.
39
+ */
40
+ export declare function getUndiscountedFeeRate(feeResult: Pick<FeeCalculationResult, 'feeRate' | 'protocolFeeRate' | 'metamaskFeeRate' | 'undiscountedMetamaskFeeRate'>): number | undefined;
41
+ /**
42
+ * Fee amount before a MetaMask fee discount, to show beside the discounted
43
+ * fee.
44
+ *
45
+ * @param params - Fee inputs.
46
+ * @param params.notionalUsd - Notional from {@link calculateFeeNotionalUsd}.
47
+ * @param params.feeResult - A fee quote from `calculateFees`.
48
+ * @returns The undiscounted fee in USD, or undefined when the notional or
49
+ * rate is unknown.
50
+ */
51
+ export declare function calculateUndiscountedFeeAmount(params: {
52
+ notionalUsd: number | undefined;
53
+ feeResult: Parameters<typeof getUndiscountedFeeRate>[0];
54
+ }): number | undefined;
55
+ //# sourceMappingURL=feeAmounts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"feeAmounts.d.ts","sourceRoot":"","sources":["../../src/utils/feeAmounts.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAE9D,iDAAiD;AACjD,MAAM,MAAM,iBAAiB,GAAG,CAC5B;IACE,0BAA0B;IAC1B,SAAS,EAAE,MAAM,GAAG,MAAM,CAAC;CAC5B,GACD;IACE,+CAA+C;IAC/C,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC;IACtB;;;;OAIG;IACH,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC,MAAM,GAAG,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,CAAC;CACtE,CACJ,GAAG;IACF,0FAA0F;IAC1F,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,+FAA+F;IAC/F,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB,CAAC;AA6CF;;;;;;;;GAQG;AACH,wBAAgB,uBAAuB,CACrC,MAAM,EAAE,iBAAiB,GACxB,MAAM,GAAG,SAAS,CAWpB;AAED;;;;;;;;GAQG;AACH,wBAAgB,sBAAsB,CACpC,SAAS,EAAE,IAAI,CACb,oBAAoB,EAClB,SAAS,GACT,iBAAiB,GACjB,iBAAiB,GACjB,6BAA6B,CAChC,GACA,MAAM,GAAG,SAAS,CAQpB;AAED;;;;;;;;;GASG;AACH,wBAAgB,8BAA8B,CAAC,MAAM,EAAE;IACrD,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IAChC,SAAS,EAAE,UAAU,CAAC,OAAO,sBAAsB,CAAC,CAAC,CAAC,CAAC,CAAC;CACzD,GAAG,MAAM,GAAG,SAAS,CAOrB"}
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Read an amount, allowing `$`, `,` and surrounding spaces. A string that is
3
+ * not wholly a number, such as `12oops`, reads as NaN.
4
+ *
5
+ * @param value - The amount.
6
+ * @returns The number, or NaN when it is empty or malformed.
7
+ */
8
+ function toNumber(value) {
9
+ if (typeof value === 'number') {
10
+ return value;
11
+ }
12
+ const normalized = value.replace(/[$,]/gu, '').trim();
13
+ return normalized === '' ? Number.NaN : Number(normalized);
14
+ }
15
+ /**
16
+ * Whether an edited price field is still unset: empty, or a lone decimal
17
+ * point while the user types, as Extension's edit dialog sends them.
18
+ *
19
+ * @param price - The field value.
20
+ * @returns True for an unset field.
21
+ */
22
+ function isUnsetDraft(price) {
23
+ const normalized = price.replace(/[$,]/gu, '').trim();
24
+ return normalized === '' || normalized === '.';
25
+ }
26
+ /**
27
+ * Higher price of a TP/SL pair. An unset leg (`''` or a lone `.`) is skipped,
28
+ * as Extension's edit dialog sends it; a malformed leg is not.
29
+ *
30
+ * @param prices - Take-profit and stop-loss trigger prices.
31
+ * @returns The higher set price, or NaN when no leg is set or one is malformed.
32
+ */
33
+ function higherTriggerPrice(prices) {
34
+ const set = prices.filter((price) => typeof price === 'number' || !isUnsetDraft(price));
35
+ return set.length === 0 ? Number.NaN : Math.max(...set.map(toNumber));
36
+ }
37
+ /**
38
+ * USD notional a fee is charged on: the absolute order value, or size times
39
+ * price (the higher trigger price of a TP/SL pair), scaled by `closePercent`
40
+ * and `multiplier`.
41
+ *
42
+ * @param params - See {@link FeeNotionalParams}. Strings may carry `$` or `,`.
43
+ * @returns The notional, or undefined when an input is empty, malformed or
44
+ * not finite.
45
+ */
46
+ export function calculateFeeNotionalUsd(params) {
47
+ const { closePercent = 100, multiplier = 1 } = params;
48
+ const notional = 'usdAmount' in params
49
+ ? Math.abs(toNumber(params.usdAmount))
50
+ : Math.abs(toNumber(params.size)) *
51
+ (typeof params.price === 'object'
52
+ ? higherTriggerPrice(params.price)
53
+ : toNumber(params.price));
54
+ const scaled = notional * (closePercent / 100) * multiplier;
55
+ return Number.isFinite(scaled) ? scaled : undefined;
56
+ }
57
+ /**
58
+ * Total fee rate before a MetaMask fee discount: the protocol rate plus
59
+ * `undiscountedMetamaskFeeRate`. Equal to `feeRate` when no discount applied
60
+ * or the quote does not report the undiscounted rate.
61
+ *
62
+ * @param feeResult - A fee quote from `calculateFees`.
63
+ * @returns The undiscounted rate as a decimal, or undefined when `feeRate` is
64
+ * unknown and no discount is reported.
65
+ */
66
+ export function getUndiscountedFeeRate(feeResult) {
67
+ const { protocolFeeRate, metamaskFeeRate, undiscountedMetamaskFeeRate } = feeResult;
68
+ return protocolFeeRate !== undefined &&
69
+ undiscountedMetamaskFeeRate !== undefined &&
70
+ undiscountedMetamaskFeeRate !== metamaskFeeRate
71
+ ? protocolFeeRate + undiscountedMetamaskFeeRate
72
+ : feeResult.feeRate;
73
+ }
74
+ /**
75
+ * Fee amount before a MetaMask fee discount, to show beside the discounted
76
+ * fee.
77
+ *
78
+ * @param params - Fee inputs.
79
+ * @param params.notionalUsd - Notional from {@link calculateFeeNotionalUsd}.
80
+ * @param params.feeResult - A fee quote from `calculateFees`.
81
+ * @returns The undiscounted fee in USD, or undefined when the notional or
82
+ * rate is unknown.
83
+ */
84
+ export function calculateUndiscountedFeeAmount(params) {
85
+ const rate = getUndiscountedFeeRate(params.feeResult);
86
+ if (params.notionalUsd === undefined || rate === undefined) {
87
+ return undefined;
88
+ }
89
+ const amount = params.notionalUsd * rate;
90
+ return Number.isFinite(amount) ? amount : undefined;
91
+ }
92
+ //# sourceMappingURL=feeAmounts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"feeAmounts.js","sourceRoot":"","sources":["../../src/utils/feeAmounts.ts"],"names":[],"mappings":"AAyBA;;;;;;GAMG;AACH,SAAS,QAAQ,CAAC,KAAsB;IACtC,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9B,OAAO,KAAK,CAAC;IACf,CAAC;IACD,MAAM,UAAU,GAAG,KAAK,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IACtD,OAAO,UAAU,KAAK,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;AAC7D,CAAC;AAED;;;;;;GAMG;AACH,SAAS,YAAY,CAAC,KAAa;IACjC,MAAM,UAAU,GAAG,KAAK,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IACtD,OAAO,UAAU,KAAK,EAAE,IAAI,UAAU,KAAK,GAAG,CAAC;AACjD,CAAC;AAED;;;;;;GAMG;AACH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AAC;IACZ,OAAO,eAAe,KAAK,SAAS;QAClC,2BAA2B,KAAK,SAAS;QACzC,2BAA2B,KAAK,eAAe;QAC/C,CAAC,CAAC,eAAe,GAAG,2BAA2B;QAC/C,CAAC,CAAC,SAAS,CAAC,OAAO,CAAC;AACxB,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,8BAA8B,CAAC,MAG9C;IACC,MAAM,IAAI,GAAG,sBAAsB,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IACtD,IAAI,MAAM,CAAC,WAAW,KAAK,SAAS,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;QAC3D,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,MAAM,MAAM,GAAG,MAAM,CAAC,WAAW,GAAG,IAAI,CAAC;IACzC,OAAO,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC;AACtD,CAAC","sourcesContent":["import type { FeeCalculationResult } from '../types/index.js';\n\n/** Inputs to {@link calculateFeeNotionalUsd}. */\nexport type FeeNotionalParams = (\n | {\n /** Order value in USD. */\n usdAmount: number | string;\n }\n | {\n /** Size in base units; the sign is ignored. */\n size: number | string;\n /**\n * Price the size is valued at. For a take-profit and stop-loss pair,\n * pass both trigger prices: the higher one sets the notional, and a\n * blank (`''`) or lone `.` leg counts as unset.\n */\n price: number | string | readonly [number | string, number | string];\n }\n) & {\n /** Percent of the notional the order covers, such as a partial close. Defaults to 100. */\n closePercent?: number;\n /** Multiplier on the notional, such as 2 for a flip that closes and reopens. Defaults to 1. */\n multiplier?: number;\n};\n\n/**\n * Read an amount, allowing `$`, `,` and surrounding spaces. A string that is\n * not wholly a number, such as `12oops`, reads as NaN.\n *\n * @param value - The amount.\n * @returns The number, or NaN when it is empty or malformed.\n */\nfunction toNumber(value: number | string): number {\n if (typeof value === 'number') {\n return value;\n }\n const normalized = value.replace(/[$,]/gu, '').trim();\n return normalized === '' ? Number.NaN : Number(normalized);\n}\n\n/**\n * Whether an edited price field is still unset: empty, or a lone decimal\n * point while the user types, as Extension's edit dialog sends them.\n *\n * @param price - The field value.\n * @returns True for an unset field.\n */\nfunction isUnsetDraft(price: string): boolean {\n const normalized = price.replace(/[$,]/gu, '').trim();\n return normalized === '' || normalized === '.';\n}\n\n/**\n * Higher price of a TP/SL pair. An unset leg (`''` or a lone `.`) is skipped,\n * as Extension's edit dialog sends it; a malformed leg is not.\n *\n * @param prices - Take-profit and stop-loss trigger prices.\n * @returns The higher set price, or NaN when no leg is set or one is malformed.\n */\nfunction higherTriggerPrice(\n prices: readonly [number | string, number | string],\n): number {\n const set = prices.filter(\n (price) => typeof price === 'number' || !isUnsetDraft(price),\n );\n return set.length === 0 ? Number.NaN : Math.max(...set.map(toNumber));\n}\n\n/**\n * USD notional a fee is charged on: the absolute order value, or size times\n * price (the higher trigger price of a TP/SL pair), scaled by `closePercent`\n * and `multiplier`.\n *\n * @param params - See {@link FeeNotionalParams}. Strings may carry `$` or `,`.\n * @returns The notional, or undefined when an input is empty, malformed or\n * not finite.\n */\nexport function calculateFeeNotionalUsd(\n params: FeeNotionalParams,\n): number | undefined {\n const { closePercent = 100, multiplier = 1 } = params;\n const notional =\n 'usdAmount' in params\n ? Math.abs(toNumber(params.usdAmount))\n : Math.abs(toNumber(params.size)) *\n (typeof params.price === 'object'\n ? higherTriggerPrice(params.price)\n : toNumber(params.price));\n const scaled = notional * (closePercent / 100) * multiplier;\n return Number.isFinite(scaled) ? scaled : undefined;\n}\n\n/**\n * Total fee rate before a MetaMask fee discount: the protocol rate plus\n * `undiscountedMetamaskFeeRate`. Equal to `feeRate` when no discount applied\n * or the quote does not report the undiscounted rate.\n *\n * @param feeResult - A fee quote from `calculateFees`.\n * @returns The undiscounted rate as a decimal, or undefined when `feeRate` is\n * unknown and no discount is reported.\n */\nexport function getUndiscountedFeeRate(\n feeResult: Pick<\n FeeCalculationResult,\n | 'feeRate'\n | 'protocolFeeRate'\n | 'metamaskFeeRate'\n | 'undiscountedMetamaskFeeRate'\n >,\n): number | undefined {\n const { protocolFeeRate, metamaskFeeRate, undiscountedMetamaskFeeRate } =\n feeResult;\n return protocolFeeRate !== undefined &&\n undiscountedMetamaskFeeRate !== undefined &&\n undiscountedMetamaskFeeRate !== metamaskFeeRate\n ? protocolFeeRate + undiscountedMetamaskFeeRate\n : feeResult.feeRate;\n}\n\n/**\n * Fee amount before a MetaMask fee discount, to show beside the discounted\n * fee.\n *\n * @param params - Fee inputs.\n * @param params.notionalUsd - Notional from {@link calculateFeeNotionalUsd}.\n * @param params.feeResult - A fee quote from `calculateFees`.\n * @returns The undiscounted fee in USD, or undefined when the notional or\n * rate is unknown.\n */\nexport function calculateUndiscountedFeeAmount(params: {\n notionalUsd: number | undefined;\n feeResult: Parameters<typeof getUndiscountedFeeRate>[0];\n}): number | undefined {\n const rate = getUndiscountedFeeRate(params.feeResult);\n if (params.notionalUsd === undefined || rate === undefined) {\n return undefined;\n }\n const amount = params.notionalUsd * rate;\n return Number.isFinite(amount) ? amount : undefined;\n}\n"]}