@metamask-previews/perps-controller 22.2.0-preview-4dd847ca3 → 22.2.0-preview-2ad7fb9

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.
@@ -1,96 +0,0 @@
1
- import type { PerpsProviderType, Position } from '../types/index.js';
2
- /**
3
- * Inputs to {@link estimateCloseReceive}.
4
- */
5
- export type CloseReceiveEstimateParams = {
6
- /** The position being closed; a `Position` can be passed as-is. */
7
- position: Pick<Position, 'size' | 'entryPrice' | 'marginUsed' | 'unrealizedPnl'> & {
8
- leverage: Pick<Position['leverage'], 'type'>;
9
- };
10
- /**
11
- * Provider holding the position. It decides whether isolated `marginUsed`
12
- * is the position's collateral; for Lighter or an unknown provider,
13
- * isolated margin returned is undefined. `Position.providerId` is only set
14
- * under aggregation, so pass the provider explicitly.
15
- */
16
- providerId: PerpsProviderType;
17
- /**
18
- * Size to close in base units, unsigned: the whole position or part of it.
19
- * A size above the position size closes the whole position.
20
- */
21
- closeSize: number | string;
22
- /**
23
- * Price the close executes at: the limit price of a limit close, else the
24
- * live price. Undefined until known.
25
- */
26
- price: number | string | undefined;
27
- /**
28
- * Total fee rate for the close as a decimal (0.00145 = 0.145%), such as
29
- * `FeeCalculationResult.feeRate` from `calculateFees` for this close, which
30
- * already applies the maker or taker rate and any fee discount. Undefined
31
- * until quoted.
32
- */
33
- feeRate: number | undefined;
34
- };
35
- /**
36
- * The cash a close returns, in USD. Each figure is undefined while an input it
37
- * needs is missing or unusable; none falls back to 0.
38
- */
39
- export type CloseReceiveEstimate = {
40
- /** The closed share of the margin backing the position, unrealized PnL excluded. */
41
- marginReturned: number | undefined;
42
- /** PnL realized on the closed size at the close price. */
43
- realizedPnl: number | undefined;
44
- /** Fee on the closed notional at the supplied fee rate. */
45
- fee: number | undefined;
46
- /**
47
- * `marginReturned + realizedPnl`, less `fee`, each of the two rounded first
48
- * to `CLOSE_POSITION_CONFIG.UsdDecimalPlaces` decimals, half away from zero.
49
- * A margin row that includes the PnL and a fee row, shown at that rounding,
50
- * add up to it. Undefined unless all three are known.
51
- */
52
- receive: number | undefined;
53
- };
54
- /**
55
- * Inputs to {@link calculateNetClosedPnl}. An `OrderFill` can be passed as-is.
56
- */
57
- export type NetClosedPnlParams = {
58
- /** Realized PnL the venue reported for the fill (`OrderFill.pnl`). */
59
- pnl?: number | string;
60
- /** Fee paid on the fill (`OrderFill.fee`). */
61
- fee?: number | string;
62
- };
63
- /**
64
- * Estimate the cash a close returns: the closed share of the position's
65
- * backing margin, plus the PnL realized at the close price, minus the fee.
66
- *
67
- * Backing margin is `marginUsed`, less the unrealized PnL for Hyperliquid
68
- * isolated margin, which holds it. Cross margin is taken as reported. Lighter
69
- * isolated `marginUsed` is required margin, not the allocated collateral, so
70
- * its margin returned and receive are undefined. The realized PnL replaces the
71
- * mark-price PnL, so a limit close is quoted at its limit price. A close is
72
- * reduce-only, so a `closeSize` above the position size closes the whole
73
- * position.
74
- *
75
- * @param params - The close inputs.
76
- * @param params.position - The position being closed.
77
- * @param params.providerId - Provider holding the position.
78
- * @param params.closeSize - Unsigned size to close, in base units.
79
- * @param params.price - Price the close executes at.
80
- * @param params.feeRate - Total fee rate for the close, as a decimal.
81
- * @returns The estimate; a figure is undefined while an input it needs is
82
- * missing or unusable.
83
- */
84
- export declare function estimateCloseReceive({ position, providerId, closeSize, price, feeRate, }: CloseReceiveEstimateParams): CloseReceiveEstimate;
85
- /**
86
- * A fill's closed PnL net of its fee: the venue's realized PnL less the fee
87
- * paid on the fill.
88
- *
89
- * @param params - The fill figures.
90
- * @param params.pnl - Realized PnL the venue reported.
91
- * @param params.fee - Fee paid on the fill.
92
- * @returns The net PnL in USD, or undefined when either figure is missing,
93
- * empty or not a finite number.
94
- */
95
- export declare function calculateNetClosedPnl({ pnl, fee, }: NetClosedPnlParams): number | undefined;
96
- //# sourceMappingURL=closeCalculations.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"closeCalculations.d.ts","sourceRoot":"","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CAiDnD;AAED;;;;;;;;;GASG;AACH,wBAAgB,qBAAqB,CAAC,EACpC,GAAG,EACH,GAAG,GACJ,EAAE,kBAAkB,GAAG,MAAM,GAAG,SAAS,CAMzC"}
@@ -1,130 +0,0 @@
1
- /**
2
- * Close-position figures shared by Mobile, Extension and Terminal: the cash a
3
- * close returns ("You'll receive") and a fill's closed PnL net of its fee.
4
- */
5
- import { BigNumber } from 'bignumber.js';
6
- import { CLOSE_POSITION_CONFIG } from '../constants/perpsConfig.js';
7
- /**
8
- * Whether a provider's isolated `Position.marginUsed` is the collateral
9
- * backing the position. Hyperliquid's is, with the unrealized PnL at mark
10
- * included. Lighter's is the initial margin the position requires at its
11
- * current value; its allocated collateral is not on `Position`, so the margin
12
- * a Lighter isolated close returns is unknown. Cross `marginUsed` is taken as
13
- * reported and never holds the unrealized PnL.
14
- */
15
- const ISOLATED_MARGIN_USED_IS_COLLATERAL = {
16
- hyperliquid: true,
17
- lighter: false,
18
- };
19
- function toDecimal(value) {
20
- if (value === undefined) {
21
- return undefined;
22
- }
23
- const decimal = new BigNumber(value);
24
- return decimal.isFinite() ? decimal : undefined;
25
- }
26
- function toPositiveDecimal(value) {
27
- const decimal = toDecimal(value);
28
- return decimal?.isGreaterThan(0) ? decimal : undefined;
29
- }
30
- /**
31
- * The unrealized PnL the position's margin holds: all of it for isolated
32
- * margin that is the position's collateral, none for cross margin.
33
- *
34
- * @param position - The position being closed.
35
- * @param providerId - Provider holding the position.
36
- * @returns The held PnL, or undefined when it or the collateral is unknown.
37
- */
38
- function heldUnrealizedPnl(position, providerId) {
39
- if (position.leverage.type !== 'isolated') {
40
- return new BigNumber(0);
41
- }
42
- if (!Object.hasOwn(ISOLATED_MARGIN_USED_IS_COLLATERAL, providerId) ||
43
- !ISOLATED_MARGIN_USED_IS_COLLATERAL[providerId]) {
44
- return undefined;
45
- }
46
- return toDecimal(position.unrealizedPnl);
47
- }
48
- function roundUsd(value) {
49
- return value.decimalPlaces(CLOSE_POSITION_CONFIG.UsdDecimalPlaces, BigNumber.ROUND_HALF_UP);
50
- }
51
- /**
52
- * Estimate the cash a close returns: the closed share of the position's
53
- * backing margin, plus the PnL realized at the close price, minus the fee.
54
- *
55
- * Backing margin is `marginUsed`, less the unrealized PnL for Hyperliquid
56
- * isolated margin, which holds it. Cross margin is taken as reported. Lighter
57
- * isolated `marginUsed` is required margin, not the allocated collateral, so
58
- * its margin returned and receive are undefined. The realized PnL replaces the
59
- * mark-price PnL, so a limit close is quoted at its limit price. A close is
60
- * reduce-only, so a `closeSize` above the position size closes the whole
61
- * position.
62
- *
63
- * @param params - The close inputs.
64
- * @param params.position - The position being closed.
65
- * @param params.providerId - Provider holding the position.
66
- * @param params.closeSize - Unsigned size to close, in base units.
67
- * @param params.price - Price the close executes at.
68
- * @param params.feeRate - Total fee rate for the close, as a decimal.
69
- * @returns The estimate; a figure is undefined while an input it needs is
70
- * missing or unusable.
71
- */
72
- export function estimateCloseReceive({ position, providerId, closeSize, price, feeRate, }) {
73
- const size = toDecimal(position.size);
74
- const positionSize = size?.isZero() ? undefined : size;
75
- const requested = toPositiveDecimal(closeSize);
76
- const closing = requested !== undefined && positionSize !== undefined
77
- ? BigNumber.min(requested, positionSize.abs())
78
- : requested;
79
- const closePrice = toPositiveDecimal(price);
80
- const entryPrice = toPositiveDecimal(position.entryPrice);
81
- const rate = toDecimal(feeRate);
82
- const marginUsed = toDecimal(position.marginUsed);
83
- const heldPnl = heldUnrealizedPnl(position, providerId);
84
- const marginReturned = marginUsed !== undefined &&
85
- heldPnl !== undefined &&
86
- positionSize !== undefined &&
87
- closing !== undefined
88
- ? marginUsed.minus(heldPnl).times(closing).div(positionSize.abs())
89
- : undefined;
90
- const realizedPnl = positionSize !== undefined &&
91
- closing !== undefined &&
92
- closePrice !== undefined &&
93
- entryPrice !== undefined
94
- ? (positionSize.isNegative()
95
- ? entryPrice.minus(closePrice)
96
- : closePrice.minus(entryPrice)).times(closing)
97
- : undefined;
98
- const fee = closing !== undefined && closePrice !== undefined && rate !== undefined
99
- ? closing.times(closePrice).times(rate)
100
- : undefined;
101
- const receive = marginReturned !== undefined &&
102
- realizedPnl !== undefined &&
103
- fee !== undefined
104
- ? roundUsd(marginReturned.plus(realizedPnl)).minus(roundUsd(fee))
105
- : undefined;
106
- return {
107
- marginReturned: marginReturned?.toNumber(),
108
- realizedPnl: realizedPnl?.toNumber(),
109
- fee: fee?.toNumber(),
110
- receive: receive?.toNumber(),
111
- };
112
- }
113
- /**
114
- * A fill's closed PnL net of its fee: the venue's realized PnL less the fee
115
- * paid on the fill.
116
- *
117
- * @param params - The fill figures.
118
- * @param params.pnl - Realized PnL the venue reported.
119
- * @param params.fee - Fee paid on the fill.
120
- * @returns The net PnL in USD, or undefined when either figure is missing,
121
- * empty or not a finite number.
122
- */
123
- export function calculateNetClosedPnl({ pnl, fee, }) {
124
- const gross = toDecimal(pnl);
125
- const cost = toDecimal(fee);
126
- return gross === undefined || cost === undefined
127
- ? undefined
128
- : gross.minus(cost).toNumber();
129
- }
130
- //# sourceMappingURL=closeCalculations.js.map
@@ -1 +0,0 @@
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,CA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OAAO,GACX,cAAc,KAAK,SAAS;QAC5B,WAAW,KAAK,SAAS;QACzB,GAAG,KAAK,SAAS;QACf,CAAC,CAAC,QAAQ,CAAC,cAAc,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;QACjE,CAAC,CAAC,SAAS,CAAC;IAEhB,OAAO;QACL,cAAc,EAAE,cAAc,EAAE,QAAQ,EAAE;QAC1C,WAAW,EAAE,WAAW,EAAE,QAAQ,EAAE;QACpC,GAAG,EAAE,GAAG,EAAE,QAAQ,EAAE;QACpB,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE;KAC7B,CAAC;AACJ,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,qBAAqB,CAAC,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"]}