@drift-labs/common 1.0.24 → 1.0.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/common-ui-utils/commonUiUtils.d.ts +2 -1
- package/lib/common-ui-utils/order.js +13 -31
- package/lib/common-ui-utils/order.js.map +1 -1
- package/lib/common-ui-utils/trading.d.ts +2 -1
- package/lib/common-ui-utils/trading.js +2 -2
- package/lib/common-ui-utils/trading.js.map +1 -1
- package/lib/constants/orders.js +2 -2
- package/lib/constants/orders.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.d.ts +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.js +3 -2
- package/lib/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.js.map +1 -1
- package/lib/types/UIMarket.js +1 -1
- package/lib/types/UIMarket.js.map +1 -1
- package/lib/utils/markets/precisions.d.ts +1 -1
- package/lib/utils/markets/precisions.js.map +1 -1
- package/package.json +1 -1
|
@@ -68,7 +68,7 @@ export declare const COMMON_UI_UTILS: {
|
|
|
68
68
|
notionalSizeAtEntry: BigNum;
|
|
69
69
|
notionalSizeAtExit: BigNum;
|
|
70
70
|
};
|
|
71
|
-
calculateLiquidationPriceAfterPerpTrade: ({ estEntryPrice, orderType, perpMarketIndex, tradeBaseSize, isLong, userClient, oraclePrice, limitPrice, offsetCollateral, precision, isEnteringHighLeverageMode, capLiqPrice, }: {
|
|
71
|
+
calculateLiquidationPriceAfterPerpTrade: ({ estEntryPrice, orderType, perpMarketIndex, tradeBaseSize, isLong, userClient, oraclePrice, limitPrice, offsetCollateral, precision, isEnteringHighLeverageMode, capLiqPrice, marginType, }: {
|
|
72
72
|
estEntryPrice: BN;
|
|
73
73
|
orderType: import("src/types").UIOrderType;
|
|
74
74
|
perpMarketIndex: number;
|
|
@@ -81,6 +81,7 @@ export declare const COMMON_UI_UTILS: {
|
|
|
81
81
|
precision?: number;
|
|
82
82
|
isEnteringHighLeverageMode?: boolean;
|
|
83
83
|
capLiqPrice?: boolean;
|
|
84
|
+
marginType?: "Cross" | "Isolated";
|
|
84
85
|
}) => number;
|
|
85
86
|
checkIsMarketOrderType: (orderType: import("src/types").UIOrderType) => boolean;
|
|
86
87
|
convertLeverageToMarginRatio: (leverage: number) => number;
|
|
@@ -24,53 +24,35 @@ const getOrderLabelFromOrderDetails = (orderDetails) => {
|
|
|
24
24
|
return 'Market (Triggered)';
|
|
25
25
|
}
|
|
26
26
|
const isTriggerAbove = (0, utils_1.matchEnum)(orderDetails.triggerCondition, sdk_1.OrderTriggerCondition.ABOVE);
|
|
27
|
-
const isExistingPositionShort = (0, utils_1.matchEnum)(orderDetails.existingPositionDirection, sdk_1.PositionDirection.SHORT);
|
|
28
27
|
const isOrderDirectionShort = (0, utils_1.matchEnum)(orderDetails.direction, sdk_1.PositionDirection.SHORT);
|
|
29
28
|
if (isTriggerAbove) {
|
|
30
|
-
return
|
|
31
|
-
?
|
|
32
|
-
|
|
33
|
-
: orders_1.UI_ORDER_TYPES.stopMarket.label // trigger above, existing position short, order direction long
|
|
34
|
-
: isOrderDirectionShort
|
|
35
|
-
? orders_1.UI_ORDER_TYPES.takeProfitMarket.label // trigger above, existing position long, order direction short
|
|
36
|
-
: 'Trigger Market'; // trigger above, existing position long, order direction long
|
|
29
|
+
return isOrderDirectionShort
|
|
30
|
+
? orders_1.UI_ORDER_TYPES.takeProfitMarket.label
|
|
31
|
+
: orders_1.UI_ORDER_TYPES.stopMarket.label;
|
|
37
32
|
}
|
|
38
33
|
else {
|
|
39
|
-
return
|
|
40
|
-
?
|
|
41
|
-
|
|
42
|
-
: orders_1.UI_ORDER_TYPES.takeProfitMarket.label // trigger below, existing position short, order direction long
|
|
43
|
-
: isOrderDirectionShort
|
|
44
|
-
? orders_1.UI_ORDER_TYPES.stopMarket.label // trigger below, existing position long, order direction short
|
|
45
|
-
: 'Trigger Market'; // trigger below, existing position long, order direction long
|
|
34
|
+
return isOrderDirectionShort
|
|
35
|
+
? orders_1.UI_ORDER_TYPES.stopMarket.label
|
|
36
|
+
: orders_1.UI_ORDER_TYPES.takeProfitMarket.label;
|
|
46
37
|
}
|
|
47
38
|
}
|
|
48
39
|
if ((0, utils_1.matchEnum)(orderDetails.orderType, sdk_1.OrderType.TRIGGER_LIMIT)) {
|
|
49
40
|
const isTriggered = (0, utils_1.matchEnum)(orderDetails.triggerCondition, sdk_1.OrderTriggerCondition.TRIGGERED_ABOVE) ||
|
|
50
41
|
(0, utils_1.matchEnum)(orderDetails.triggerCondition, sdk_1.OrderTriggerCondition.TRIGGERED_BELOW);
|
|
51
42
|
const isTriggerAbove = (0, utils_1.matchEnum)(orderDetails.triggerCondition, sdk_1.OrderTriggerCondition.ABOVE);
|
|
52
|
-
const
|
|
53
|
-
const isOrderDirectionLong = (0, utils_1.matchEnum)(orderDetails.direction, sdk_1.PositionDirection.LONG);
|
|
43
|
+
const isOrderDirectionShort = (0, utils_1.matchEnum)(orderDetails.direction, sdk_1.PositionDirection.SHORT);
|
|
54
44
|
if (isTriggered) {
|
|
55
45
|
return 'Limit (Triggered)';
|
|
56
46
|
}
|
|
57
47
|
if (isTriggerAbove) {
|
|
58
|
-
return
|
|
59
|
-
?
|
|
60
|
-
|
|
61
|
-
: orders_1.UI_ORDER_TYPES.takeProfitLimit.label // trigger above, existing position long, order direction short
|
|
62
|
-
: isExistingPositionLong
|
|
63
|
-
? orders_1.UI_ORDER_TYPES.stopLimit.label // trigger above, existing position short, order direction long
|
|
64
|
-
: 'Trigger Limit'; // trigger above, existing position short, order direction short
|
|
48
|
+
return isOrderDirectionShort
|
|
49
|
+
? orders_1.UI_ORDER_TYPES.takeProfitLimit.label
|
|
50
|
+
: orders_1.UI_ORDER_TYPES.stopLimit.label;
|
|
65
51
|
}
|
|
66
52
|
else {
|
|
67
|
-
return
|
|
68
|
-
?
|
|
69
|
-
|
|
70
|
-
: orders_1.UI_ORDER_TYPES.stopLimit.label // trigger below, existing position long, order direction short
|
|
71
|
-
: isExistingPositionLong
|
|
72
|
-
? orders_1.UI_ORDER_TYPES.takeProfitLimit.label // trigger below, existing position short, order direction long
|
|
73
|
-
: 'Trigger Limit'; // trigger below, existing position short, order direction short
|
|
53
|
+
return isOrderDirectionShort
|
|
54
|
+
? orders_1.UI_ORDER_TYPES.stopLimit.label
|
|
55
|
+
: orders_1.UI_ORDER_TYPES.takeProfitLimit.label;
|
|
74
56
|
}
|
|
75
57
|
}
|
|
76
58
|
return '-';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"order.js","sourceRoot":"","sources":["../../src/common-ui-utils/order.ts"],"names":[],"mappings":";;;AAAA,yCAcyB;AACzB,gDAU6B;AAE7B,oCAAiD;AAEjD,8CAA0D;AAC1D,qCAAwC;AAExC,MAAM,6BAA6B,GAAG,CACrC,YAOC,EACA,EAAE;;IACH,IAAI,IAAA,iBAAS,EAAC,YAAY,CAAC,SAAS,EAAE,eAAS,CAAC,MAAM,CAAC;QACtD,OAAO,uBAAc,CAAC,MAAM,CAAC,KAAK,CAAC;IAEpC,IAAI,IAAA,iBAAS,EAAC,YAAY,CAAC,SAAS,EAAE,eAAS,CAAC,KAAK,CAAC;QACrD,OAAO,GACN,YAAY,CAAC,iBAAiB;YAC9B,CAAC,CAAA,MAAA,YAAY,CAAC,iBAAiB,0CAAE,MAAM,EAAE,CAAA;YACxC,CAAC,CAAC,SAAS;YACX,CAAC,CAAC,EACJ,GAAG,uBAAc,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;IAEjC,IAAI,IAAA,iBAAS,EAAC,YAAY,CAAC,SAAS,EAAE,eAAS,CAAC,MAAM,CAAC;QACtD,OAAO,uBAAc,CAAC,MAAM,CAAC,KAAK,CAAC;IAEpC,IAAI,IAAA,iBAAS,EAAC,YAAY,CAAC,SAAS,EAAE,eAAS,CAAC,cAAc,CAAC,EAAE,CAAC;QACjE,MAAM,WAAW,GAChB,IAAA,iBAAS,EACR,YAAY,CAAC,gBAAg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E,GAC7D,mBAAmB,IAAI,EAAE,CAAC;IAE3B,IAAI,0BAA0B,IAAI,CAAC,EAAE,CAAC;QACrC,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,MAAM,EACL,eAAe,EAAE,2BAA2B,EAC5C,WAAW,EAAE,kBAAkB,GAC/B,GAAG,qBAAY,CAAC,uBAAuB,CACvC,gBAAU,CAAC,IAAI,EACf,WAAW,EACX,WAAW,CACX,CAAC;IAEF,IAAI,CAAC,2BAA2B,EAAE,CAAC;QAClC,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,iDAAiD;IACjD,IAAI,WAAW,CAAC,kBAAkB,CAAC,SAAS,CAAC,EAAE,CAAC;QAC/C,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,IAAI,iBAAiB,GAAG,kBAAkB,EAAE,CAAC;QAC5C,OAAO,wBAAkB,CAAC,sBAAsB,CAAC;IAClD,CAAC;IAED,OAAO,SAAS,CAAC;AAClB,CAAC;AAEY,QAAA,kBAAkB,GAAG;IACjC,6BAA6B;IAC7B,6BAA6B;IAC7B,cAAc;IACd,8BAA8B;IAC9B,sBAAsB;IACtB,0BAA0B;CAC1B,CAAC","sourcesContent":["import {\n\tOrderType,\n\tOrderTriggerCondition,\n\tPositionDirection,\n\tBigNum,\n\tZERO,\n\tContractTier,\n\tBN,\n\tPERCENTAGE_PRECISION,\n\tisOneOfVariant,\n\tMarketType,\n\tDriftClient,\n\tUser,\n\tOrderParamsBitFlag,\n} from '@drift-labs/sdk';\nimport {\n\tLIMIT_ORDER_TYPE_CONFIG,\n\tMARKET_ORDER_TYPE_CONFIG,\n\tORACLE_LIMIT_ORDER_TYPE_CONFIG,\n\tORACLE_MARKET_ORDER_TYPE_CONFIG,\n\tSTOP_LIMIT_ORDER_TYPE_CONFIG,\n\tSTOP_MARKET_ORDER_TYPE_CONFIG,\n\tTAKE_PROFIT_LIMIT_ORDER_TYPE_CONFIG,\n\tTAKE_PROFIT_MARKET_ORDER_TYPE_CONFIG,\n\tUI_ORDER_TYPES,\n} from '../constants/orders';\nimport { UISerializableOrder } from '../serializableTypes';\nimport { ENUM_UTILS, matchEnum } from '../utils';\nimport { AuctionParams } from '../types';\nimport { EMPTY_AUCTION_PARAMS } from '../constants/trade';\nimport { MARKET_UTILS } from './market';\n\nconst getOrderLabelFromOrderDetails = (\n\torderDetails: Pick<\n\t\tUISerializableOrder,\n\t\t| 'orderType'\n\t\t| 'oraclePriceOffset'\n\t\t| 'direction'\n\t\t| 'triggerCondition'\n\t\t| 'existingPositionDirection'\n\t>\n) => {\n\tif (matchEnum(orderDetails.orderType, OrderType.MARKET))\n\t\treturn UI_ORDER_TYPES.market.label;\n\n\tif (matchEnum(orderDetails.orderType, OrderType.LIMIT))\n\t\treturn `${\n\t\t\torderDetails.oraclePriceOffset &&\n\t\t\t!orderDetails.oraclePriceOffset?.eqZero()\n\t\t\t\t? 'Oracle '\n\t\t\t\t: ''\n\t\t}${UI_ORDER_TYPES.limit.label}`;\n\n\tif (matchEnum(orderDetails.orderType, OrderType.ORACLE))\n\t\treturn UI_ORDER_TYPES.oracle.label;\n\n\tif (matchEnum(orderDetails.orderType, OrderType.TRIGGER_MARKET)) {\n\t\tconst isTriggered =\n\t\t\tmatchEnum(\n\t\t\t\torderDetails.triggerCondition,\n\t\t\t\tOrderTriggerCondition.TRIGGERED_ABOVE\n\t\t\t) ||\n\t\t\tmatchEnum(\n\t\t\t\torderDetails.triggerCondition,\n\t\t\t\tOrderTriggerCondition.TRIGGERED_BELOW\n\t\t\t);\n\t\tif (isTriggered) {\n\t\t\treturn 'Market (Triggered)';\n\t\t}\n\n\t\tconst isTriggerAbove = matchEnum(\n\t\t\torderDetails.triggerCondition,\n\t\t\tOrderTriggerCondition.ABOVE\n\t\t);\n\t\tconst isExistingPositionShort = matchEnum(\n\t\t\torderDetails.existingPositionDirection,\n\t\t\tPositionDirection.SHORT\n\t\t);\n\t\tconst isOrderDirectionShort = matchEnum(\n\t\t\torderDetails.direction,\n\t\t\tPositionDirection.SHORT\n\t\t);\n\n\t\tif (isTriggerAbove) {\n\t\t\treturn isExistingPositionShort\n\t\t\t\t? isOrderDirectionShort\n\t\t\t\t\t? 'Trigger Market' // trigger above, existing position short, order direction short\n\t\t\t\t\t: UI_ORDER_TYPES.stopMarket.label // trigger above, existing position short, order direction long\n\t\t\t\t: isOrderDirectionShort\n\t\t\t\t? UI_ORDER_TYPES.takeProfitMarket.label // trigger above, existing position long, order direction short\n\t\t\t\t: 'Trigger Market'; // trigger above, existing position long, order direction long\n\t\t} else {\n\t\t\treturn isExistingPositionShort\n\t\t\t\t? isOrderDirectionShort\n\t\t\t\t\t? 'Trigger Market' // trigger below, existing position short, order direction short\n\t\t\t\t\t: UI_ORDER_TYPES.takeProfitMarket.label // trigger below, existing position short, order direction long\n\t\t\t\t: isOrderDirectionShort\n\t\t\t\t? UI_ORDER_TYPES.stopMarket.label // trigger below, existing position long, order direction short\n\t\t\t\t: 'Trigger Market'; // trigger below, existing position long, order direction long\n\t\t}\n\t}\n\n\tif (matchEnum(orderDetails.orderType, OrderType.TRIGGER_LIMIT)) {\n\t\tconst isTriggered =\n\t\t\tmatchEnum(\n\t\t\t\torderDetails.triggerCondition,\n\t\t\t\tOrderTriggerCondition.TRIGGERED_ABOVE\n\t\t\t) ||\n\t\t\tmatchEnum(\n\t\t\t\torderDetails.triggerCondition,\n\t\t\t\tOrderTriggerCondition.TRIGGERED_BELOW\n\t\t\t);\n\n\t\tconst isTriggerAbove = matchEnum(\n\t\t\torderDetails.triggerCondition,\n\t\t\tOrderTriggerCondition.ABOVE\n\t\t);\n\t\tconst isExistingPositionLong = matchEnum(\n\t\t\torderDetails.existingPositionDirection,\n\t\t\tPositionDirection.LONG\n\t\t);\n\t\tconst isOrderDirectionLong = matchEnum(\n\t\t\torderDetails.direction,\n\t\t\tPositionDirection.LONG\n\t\t);\n\n\t\tif (isTriggered) {\n\t\t\treturn 'Limit (Triggered)';\n\t\t}\n\n\t\tif (isTriggerAbove) {\n\t\t\treturn isExistingPositionLong\n\t\t\t\t? isOrderDirectionLong\n\t\t\t\t\t? 'Trigger Limit' // trigger above, existing position long, order direction long\n\t\t\t\t\t: UI_ORDER_TYPES.takeProfitLimit.label // trigger above, existing position long, order direction short\n\t\t\t\t: isExistingPositionLong\n\t\t\t\t? UI_ORDER_TYPES.stopLimit.label // trigger above, existing position short, order direction long\n\t\t\t\t: 'Trigger Limit'; // trigger above, existing position short, order direction short\n\t\t} else {\n\t\t\treturn isExistingPositionLong\n\t\t\t\t? isOrderDirectionLong\n\t\t\t\t\t? 'Trigger Limit' // trigger below, existing position long, order direction long\n\t\t\t\t\t: UI_ORDER_TYPES.stopLimit.label // trigger below, existing position long, order direction short\n\t\t\t\t: isExistingPositionLong\n\t\t\t\t? UI_ORDER_TYPES.takeProfitLimit.label // trigger below, existing position short, order direction long\n\t\t\t\t: 'Trigger Limit'; // trigger below, existing position short, order direction short\n\t\t}\n\t}\n\n\treturn '-';\n};\n\nconst getLimitPriceFromOracleOffset = (\n\torder: UISerializableOrder,\n\toraclePrice: BigNum\n): BigNum => {\n\tif (\n\t\t(order.price && !order.price.eqZero()) ||\n\t\t!order.oraclePriceOffset ||\n\t\torder.oraclePriceOffset.eqZero() ||\n\t\t!oraclePrice ||\n\t\toraclePrice?.eqZero()\n\t) {\n\t\treturn order.price;\n\t}\n\treturn oraclePrice.add(order.oraclePriceOffset);\n};\n\nfunction isAuctionEmpty(auctionParams: AuctionParams) {\n\treturn (\n\t\tauctionParams.auctionStartPrice ===\n\t\t\tEMPTY_AUCTION_PARAMS.auctionStartPrice &&\n\t\tauctionParams.auctionEndPrice === EMPTY_AUCTION_PARAMS.auctionEndPrice &&\n\t\tauctionParams.auctionDuration === EMPTY_AUCTION_PARAMS.auctionDuration\n\t);\n}\n\nconst getUIOrderTypeFromSdkOrderType = (\n\torderType: OrderType,\n\ttriggerCondition: OrderTriggerCondition,\n\tdirection: PositionDirection,\n\toracleOffset: BigNum | undefined\n) => {\n\tconst isLong = ENUM_UTILS.match(direction, PositionDirection.LONG);\n\tconst triggerAbove =\n\t\tmatchEnum(triggerCondition, OrderTriggerCondition.ABOVE) ||\n\t\tmatchEnum(triggerCondition, OrderTriggerCondition.TRIGGERED_ABOVE);\n\n\tconst triggerBelow =\n\t\tmatchEnum(triggerCondition, OrderTriggerCondition.BELOW) ||\n\t\tmatchEnum(triggerCondition, OrderTriggerCondition.TRIGGERED_BELOW);\n\n\t// Buy side + trigger below: take profit for a short position\n\t// Buy side + trigger above: stop loss for a short position\n\t// Sell side + trigger above: take profit for a long position\n\t// Sell side + trigger below: stop loss for a long position\n\n\tif (matchEnum(orderType, OrderType.MARKET)) {\n\t\treturn MARKET_ORDER_TYPE_CONFIG;\n\t} else if (matchEnum(orderType, OrderType.LIMIT)) {\n\t\tif (oracleOffset && !oracleOffset.eq(ZERO)) {\n\t\t\treturn ORACLE_LIMIT_ORDER_TYPE_CONFIG;\n\t\t} else {\n\t\t\treturn LIMIT_ORDER_TYPE_CONFIG;\n\t\t}\n\t} else if (matchEnum(orderType, OrderType.TRIGGER_MARKET)) {\n\t\tif (isLong) {\n\t\t\tif (triggerAbove) {\n\t\t\t\treturn STOP_MARKET_ORDER_TYPE_CONFIG;\n\t\t\t} else if (triggerBelow) {\n\t\t\t\treturn TAKE_PROFIT_MARKET_ORDER_TYPE_CONFIG;\n\t\t\t}\n\t\t} else {\n\t\t\tif (triggerAbove) {\n\t\t\t\treturn TAKE_PROFIT_MARKET_ORDER_TYPE_CONFIG;\n\t\t\t} else if (triggerBelow) {\n\t\t\t\treturn STOP_MARKET_ORDER_TYPE_CONFIG;\n\t\t\t}\n\t\t}\n\t} else if (matchEnum(orderType, OrderType.TRIGGER_LIMIT)) {\n\t\tif (isLong) {\n\t\t\tif (triggerAbove) {\n\t\t\t\treturn STOP_LIMIT_ORDER_TYPE_CONFIG;\n\t\t\t} else if (triggerBelow) {\n\t\t\t\treturn TAKE_PROFIT_LIMIT_ORDER_TYPE_CONFIG;\n\t\t\t}\n\t\t} else {\n\t\t\tif (triggerAbove) {\n\t\t\t\treturn TAKE_PROFIT_LIMIT_ORDER_TYPE_CONFIG;\n\t\t\t} else if (triggerBelow) {\n\t\t\t\treturn STOP_LIMIT_ORDER_TYPE_CONFIG;\n\t\t\t}\n\t\t}\n\t} else if (matchEnum(orderType, OrderType.ORACLE)) {\n\t\treturn ORACLE_MARKET_ORDER_TYPE_CONFIG;\n\t}\n\tthrow new Error('Invalid order type');\n};\n\nfunction getPerpAuctionDuration(\n\tpriceDiff: BN,\n\tprice: BN,\n\tcontractTier: ContractTier\n): number {\n\tconst percentDiff = priceDiff.mul(PERCENTAGE_PRECISION).div(price);\n\n\tconst slotsPerBp = isOneOfVariant(contractTier, ['a', 'b'])\n\t\t? new BN(100)\n\t\t: new BN(60);\n\n\tconst rawSlots = percentDiff\n\t\t.mul(slotsPerBp)\n\t\t.div(PERCENTAGE_PRECISION.divn(100));\n\n\tconst clamped = BN.min(BN.max(rawSlots, new BN(5)), new BN(180));\n\n\treturn clamped.toNumber();\n}\n\nexport type HighLeverageOptions = {\n\tnumOfOpenHighLeverageSpots?: number; // if not provided, the method will assume that there is spots open\n\tenterHighLeverageModeBufferPct?: number;\n};\n\n/**\n * Mainly checks if the user will be entering high leverage mode through this order.\n */\nfunction getPerpOrderParamsBitFlags(\n\tmarketIndex: number,\n\tdriftClient: DriftClient,\n\tuserAccount: User,\n\tattemptedLeverage: number,\n\thighLeverageOptions?: {\n\t\tnumOfOpenHighLeverageSpots?: number; // if not provided, the method will assume that there is spots open\n\t}\n): number | undefined {\n\tif (attemptedLeverage < 5) {\n\t\t// there is no high leverage mode leverage that is higher than 4\n\t\treturn undefined;\n\t}\n\n\tconst { numOfOpenHighLeverageSpots = Number.MAX_SAFE_INTEGER } =\n\t\thighLeverageOptions || {};\n\n\tif (numOfOpenHighLeverageSpots <= 0) {\n\t\treturn undefined;\n\t}\n\n\tconst {\n\t\thasHighLeverage: isMarketAHighLeverageMarket,\n\t\tmaxLeverage: regularMaxLeverage,\n\t} = MARKET_UTILS.getMaxLeverageForMarket(\n\t\tMarketType.PERP,\n\t\tmarketIndex,\n\t\tdriftClient\n\t);\n\n\tif (!isMarketAHighLeverageMarket) {\n\t\treturn undefined;\n\t}\n\n\t// Check if user is already in high leverage mode\n\tif (userAccount.isHighLeverageMode('Initial')) {\n\t\treturn undefined;\n\t}\n\n\tif (attemptedLeverage > regularMaxLeverage) {\n\t\treturn OrderParamsBitFlag.UpdateHighLeverageMode;\n\t}\n\n\treturn undefined;\n}\n\nexport const ORDER_COMMON_UTILS = {\n\tgetOrderLabelFromOrderDetails,\n\tgetLimitPriceFromOracleOffset,\n\tisAuctionEmpty,\n\tgetUIOrderTypeFromSdkOrderType,\n\tgetPerpAuctionDuration,\n\tgetPerpOrderParamsBitFlags,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"order.js","sourceRoot":"","sources":["../../src/common-ui-utils/order.ts"],"names":[],"mappings":";;;AAAA,yCAcyB;AACzB,gDAU6B;AAE7B,oCAAiD;AAEjD,8CAA0D;AAC1D,qCAAwC;AAExC,MAAM,6BAA6B,GAAG,CACrC,YAOC,EACA,EAAE;;IACH,IAAI,IAAA,iBAAS,EAAC,YAAY,CAAC,SAAS,EAAE,eAAS,CAAC,MAAM,CAAC;QACtD,OAAO,uBAAc,CAAC,MAAM,CAAC,KAAK,CAAC;IAEpC,IAAI,IAAA,iBAAS,EAAC,YAAY,CAAC,SAAS,EAAE,eAAS,CAAC,KAAK,CAAC;QACrD,OAAO,GACN,YAAY,CAAC,iBAAiB;YAC9B,CAAC,CAAA,MAAA,YAAY,CAAC,iBAAiB,0CAAE,MAAM,EAAE,CAAA;YACxC,CAAC,CAAC,SAAS;YACX,CAAC,CAAC,EACJ,GAAG,uBAAc,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;IAEjC,IAAI,IAAA,iBAAS,EAAC,YAAY,CAAC,SAAS,EAAE,eAAS,CAAC,MAAM,CAAC;QACtD,OAAO,uBAAc,CAAC,MAAM,CAAC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AA0B;CAC1B,CAAC","sourcesContent":["import {\n\tOrderType,\n\tOrderTriggerCondition,\n\tPositionDirection,\n\tBigNum,\n\tZERO,\n\tContractTier,\n\tBN,\n\tPERCENTAGE_PRECISION,\n\tisOneOfVariant,\n\tMarketType,\n\tDriftClient,\n\tUser,\n\tOrderParamsBitFlag,\n} from '@drift-labs/sdk';\nimport {\n\tLIMIT_ORDER_TYPE_CONFIG,\n\tMARKET_ORDER_TYPE_CONFIG,\n\tORACLE_LIMIT_ORDER_TYPE_CONFIG,\n\tORACLE_MARKET_ORDER_TYPE_CONFIG,\n\tSTOP_LIMIT_ORDER_TYPE_CONFIG,\n\tSTOP_MARKET_ORDER_TYPE_CONFIG,\n\tTAKE_PROFIT_LIMIT_ORDER_TYPE_CONFIG,\n\tTAKE_PROFIT_MARKET_ORDER_TYPE_CONFIG,\n\tUI_ORDER_TYPES,\n} from '../constants/orders';\nimport { UISerializableOrder } from '../serializableTypes';\nimport { ENUM_UTILS, matchEnum } from '../utils';\nimport { AuctionParams } from '../types';\nimport { EMPTY_AUCTION_PARAMS } from '../constants/trade';\nimport { MARKET_UTILS } from './market';\n\nconst getOrderLabelFromOrderDetails = (\n\torderDetails: Pick<\n\t\tUISerializableOrder,\n\t\t| 'orderType'\n\t\t| 'oraclePriceOffset'\n\t\t| 'direction'\n\t\t| 'triggerCondition'\n\t\t| 'existingPositionDirection'\n\t>\n) => {\n\tif (matchEnum(orderDetails.orderType, OrderType.MARKET))\n\t\treturn UI_ORDER_TYPES.market.label;\n\n\tif (matchEnum(orderDetails.orderType, OrderType.LIMIT))\n\t\treturn `${\n\t\t\torderDetails.oraclePriceOffset &&\n\t\t\t!orderDetails.oraclePriceOffset?.eqZero()\n\t\t\t\t? 'Oracle '\n\t\t\t\t: ''\n\t\t}${UI_ORDER_TYPES.limit.label}`;\n\n\tif (matchEnum(orderDetails.orderType, OrderType.ORACLE))\n\t\treturn UI_ORDER_TYPES.oracle.label;\n\n\tif (matchEnum(orderDetails.orderType, OrderType.TRIGGER_MARKET)) {\n\t\tconst isTriggered =\n\t\t\tmatchEnum(\n\t\t\t\torderDetails.triggerCondition,\n\t\t\t\tOrderTriggerCondition.TRIGGERED_ABOVE\n\t\t\t) ||\n\t\t\tmatchEnum(\n\t\t\t\torderDetails.triggerCondition,\n\t\t\t\tOrderTriggerCondition.TRIGGERED_BELOW\n\t\t\t);\n\t\tif (isTriggered) {\n\t\t\treturn 'Market (Triggered)';\n\t\t}\n\n\t\tconst isTriggerAbove = matchEnum(\n\t\t\torderDetails.triggerCondition,\n\t\t\tOrderTriggerCondition.ABOVE\n\t\t);\n\t\tconst isOrderDirectionShort = matchEnum(\n\t\t\torderDetails.direction,\n\t\t\tPositionDirection.SHORT\n\t\t);\n\n\t\tif (isTriggerAbove) {\n\t\t\treturn isOrderDirectionShort\n\t\t\t\t? UI_ORDER_TYPES.takeProfitMarket.label\n\t\t\t\t: UI_ORDER_TYPES.stopMarket.label;\n\t\t} else {\n\t\t\treturn isOrderDirectionShort\n\t\t\t\t? UI_ORDER_TYPES.stopMarket.label\n\t\t\t\t: UI_ORDER_TYPES.takeProfitMarket.label;\n\t\t}\n\t}\n\n\tif (matchEnum(orderDetails.orderType, OrderType.TRIGGER_LIMIT)) {\n\t\tconst isTriggered =\n\t\t\tmatchEnum(\n\t\t\t\torderDetails.triggerCondition,\n\t\t\t\tOrderTriggerCondition.TRIGGERED_ABOVE\n\t\t\t) ||\n\t\t\tmatchEnum(\n\t\t\t\torderDetails.triggerCondition,\n\t\t\t\tOrderTriggerCondition.TRIGGERED_BELOW\n\t\t\t);\n\n\t\tconst isTriggerAbove = matchEnum(\n\t\t\torderDetails.triggerCondition,\n\t\t\tOrderTriggerCondition.ABOVE\n\t\t);\n\t\tconst isOrderDirectionShort = matchEnum(\n\t\t\torderDetails.direction,\n\t\t\tPositionDirection.SHORT\n\t\t);\n\n\t\tif (isTriggered) {\n\t\t\treturn 'Limit (Triggered)';\n\t\t}\n\n\t\tif (isTriggerAbove) {\n\t\t\treturn isOrderDirectionShort\n\t\t\t\t? UI_ORDER_TYPES.takeProfitLimit.label\n\t\t\t\t: UI_ORDER_TYPES.stopLimit.label;\n\t\t} else {\n\t\t\treturn isOrderDirectionShort\n\t\t\t\t? UI_ORDER_TYPES.stopLimit.label\n\t\t\t\t: UI_ORDER_TYPES.takeProfitLimit.label;\n\t\t}\n\t}\n\n\treturn '-';\n};\n\nconst getLimitPriceFromOracleOffset = (\n\torder: UISerializableOrder,\n\toraclePrice: BigNum\n): BigNum => {\n\tif (\n\t\t(order.price && !order.price.eqZero()) ||\n\t\t!order.oraclePriceOffset ||\n\t\torder.oraclePriceOffset.eqZero() ||\n\t\t!oraclePrice ||\n\t\toraclePrice?.eqZero()\n\t) {\n\t\treturn order.price;\n\t}\n\treturn oraclePrice.add(order.oraclePriceOffset);\n};\n\nfunction isAuctionEmpty(auctionParams: AuctionParams) {\n\treturn (\n\t\tauctionParams.auctionStartPrice ===\n\t\t\tEMPTY_AUCTION_PARAMS.auctionStartPrice &&\n\t\tauctionParams.auctionEndPrice === EMPTY_AUCTION_PARAMS.auctionEndPrice &&\n\t\tauctionParams.auctionDuration === EMPTY_AUCTION_PARAMS.auctionDuration\n\t);\n}\n\nconst getUIOrderTypeFromSdkOrderType = (\n\torderType: OrderType,\n\ttriggerCondition: OrderTriggerCondition,\n\tdirection: PositionDirection,\n\toracleOffset: BigNum | undefined\n) => {\n\tconst isLong = ENUM_UTILS.match(direction, PositionDirection.LONG);\n\tconst triggerAbove =\n\t\tmatchEnum(triggerCondition, OrderTriggerCondition.ABOVE) ||\n\t\tmatchEnum(triggerCondition, OrderTriggerCondition.TRIGGERED_ABOVE);\n\n\tconst triggerBelow =\n\t\tmatchEnum(triggerCondition, OrderTriggerCondition.BELOW) ||\n\t\tmatchEnum(triggerCondition, OrderTriggerCondition.TRIGGERED_BELOW);\n\n\t// Buy side + trigger below: take profit for a short position\n\t// Buy side + trigger above: stop loss for a short position\n\t// Sell side + trigger above: take profit for a long position\n\t// Sell side + trigger below: stop loss for a long position\n\n\tif (matchEnum(orderType, OrderType.MARKET)) {\n\t\treturn MARKET_ORDER_TYPE_CONFIG;\n\t} else if (matchEnum(orderType, OrderType.LIMIT)) {\n\t\tif (oracleOffset && !oracleOffset.eq(ZERO)) {\n\t\t\treturn ORACLE_LIMIT_ORDER_TYPE_CONFIG;\n\t\t} else {\n\t\t\treturn LIMIT_ORDER_TYPE_CONFIG;\n\t\t}\n\t} else if (matchEnum(orderType, OrderType.TRIGGER_MARKET)) {\n\t\tif (isLong) {\n\t\t\tif (triggerAbove) {\n\t\t\t\treturn STOP_MARKET_ORDER_TYPE_CONFIG;\n\t\t\t} else if (triggerBelow) {\n\t\t\t\treturn TAKE_PROFIT_MARKET_ORDER_TYPE_CONFIG;\n\t\t\t}\n\t\t} else {\n\t\t\tif (triggerAbove) {\n\t\t\t\treturn TAKE_PROFIT_MARKET_ORDER_TYPE_CONFIG;\n\t\t\t} else if (triggerBelow) {\n\t\t\t\treturn STOP_MARKET_ORDER_TYPE_CONFIG;\n\t\t\t}\n\t\t}\n\t} else if (matchEnum(orderType, OrderType.TRIGGER_LIMIT)) {\n\t\tif (isLong) {\n\t\t\tif (triggerAbove) {\n\t\t\t\treturn STOP_LIMIT_ORDER_TYPE_CONFIG;\n\t\t\t} else if (triggerBelow) {\n\t\t\t\treturn TAKE_PROFIT_LIMIT_ORDER_TYPE_CONFIG;\n\t\t\t}\n\t\t} else {\n\t\t\tif (triggerAbove) {\n\t\t\t\treturn TAKE_PROFIT_LIMIT_ORDER_TYPE_CONFIG;\n\t\t\t} else if (triggerBelow) {\n\t\t\t\treturn STOP_LIMIT_ORDER_TYPE_CONFIG;\n\t\t\t}\n\t\t}\n\t} else if (matchEnum(orderType, OrderType.ORACLE)) {\n\t\treturn ORACLE_MARKET_ORDER_TYPE_CONFIG;\n\t}\n\tthrow new Error('Invalid order type');\n};\n\nfunction getPerpAuctionDuration(\n\tpriceDiff: BN,\n\tprice: BN,\n\tcontractTier: ContractTier\n): number {\n\tconst percentDiff = priceDiff.mul(PERCENTAGE_PRECISION).div(price);\n\n\tconst slotsPerBp = isOneOfVariant(contractTier, ['a', 'b'])\n\t\t? new BN(100)\n\t\t: new BN(60);\n\n\tconst rawSlots = percentDiff\n\t\t.mul(slotsPerBp)\n\t\t.div(PERCENTAGE_PRECISION.divn(100));\n\n\tconst clamped = BN.min(BN.max(rawSlots, new BN(5)), new BN(180));\n\n\treturn clamped.toNumber();\n}\n\nexport type HighLeverageOptions = {\n\tnumOfOpenHighLeverageSpots?: number; // if not provided, the method will assume that there is spots open\n\tenterHighLeverageModeBufferPct?: number;\n};\n\n/**\n * Mainly checks if the user will be entering high leverage mode through this order.\n */\nfunction getPerpOrderParamsBitFlags(\n\tmarketIndex: number,\n\tdriftClient: DriftClient,\n\tuserAccount: User,\n\tattemptedLeverage: number,\n\thighLeverageOptions?: {\n\t\tnumOfOpenHighLeverageSpots?: number; // if not provided, the method will assume that there is spots open\n\t}\n): number | undefined {\n\tif (attemptedLeverage < 5) {\n\t\t// there is no high leverage mode leverage that is higher than 4\n\t\treturn undefined;\n\t}\n\n\tconst { numOfOpenHighLeverageSpots = Number.MAX_SAFE_INTEGER } =\n\t\thighLeverageOptions || {};\n\n\tif (numOfOpenHighLeverageSpots <= 0) {\n\t\treturn undefined;\n\t}\n\n\tconst {\n\t\thasHighLeverage: isMarketAHighLeverageMarket,\n\t\tmaxLeverage: regularMaxLeverage,\n\t} = MARKET_UTILS.getMaxLeverageForMarket(\n\t\tMarketType.PERP,\n\t\tmarketIndex,\n\t\tdriftClient\n\t);\n\n\tif (!isMarketAHighLeverageMarket) {\n\t\treturn undefined;\n\t}\n\n\t// Check if user is already in high leverage mode\n\tif (userAccount.isHighLeverageMode('Initial')) {\n\t\treturn undefined;\n\t}\n\n\tif (attemptedLeverage > regularMaxLeverage) {\n\t\treturn OrderParamsBitFlag.UpdateHighLeverageMode;\n\t}\n\n\treturn undefined;\n}\n\nexport const ORDER_COMMON_UTILS = {\n\tgetOrderLabelFromOrderDetails,\n\tgetLimitPriceFromOracleOffset,\n\tisAuctionEmpty,\n\tgetUIOrderTypeFromSdkOrderType,\n\tgetPerpAuctionDuration,\n\tgetPerpOrderParamsBitFlags,\n};\n"]}
|
|
@@ -32,7 +32,7 @@ export declare const TRADING_UTILS: {
|
|
|
32
32
|
notionalSizeAtEntry: BigNum;
|
|
33
33
|
notionalSizeAtExit: BigNum;
|
|
34
34
|
};
|
|
35
|
-
calculateLiquidationPriceAfterPerpTrade: ({ estEntryPrice, orderType, perpMarketIndex, tradeBaseSize, isLong, userClient, oraclePrice, limitPrice, offsetCollateral, precision, isEnteringHighLeverageMode, capLiqPrice, }: {
|
|
35
|
+
calculateLiquidationPriceAfterPerpTrade: ({ estEntryPrice, orderType, perpMarketIndex, tradeBaseSize, isLong, userClient, oraclePrice, limitPrice, offsetCollateral, precision, isEnteringHighLeverageMode, capLiqPrice, marginType, }: {
|
|
36
36
|
estEntryPrice: BN;
|
|
37
37
|
orderType: UIOrderType;
|
|
38
38
|
perpMarketIndex: number;
|
|
@@ -45,6 +45,7 @@ export declare const TRADING_UTILS: {
|
|
|
45
45
|
precision?: number;
|
|
46
46
|
isEnteringHighLeverageMode?: boolean;
|
|
47
47
|
capLiqPrice?: boolean;
|
|
48
|
+
marginType?: 'Cross' | 'Isolated';
|
|
48
49
|
}) => number;
|
|
49
50
|
checkIsMarketOrderType: (orderType: UIOrderType) => boolean;
|
|
50
51
|
convertLeverageToMarginRatio: (leverage: number) => number | undefined;
|
|
@@ -92,7 +92,7 @@ const checkIsMarketOrderType = (orderType) => {
|
|
|
92
92
|
* Calculate the liquidation price of a position after a trade. Requires DriftClient to be subscribed.
|
|
93
93
|
* If the order type is limit order, a limit price must be provided.
|
|
94
94
|
*/
|
|
95
|
-
const calculateLiquidationPriceAfterPerpTrade = ({ estEntryPrice, orderType, perpMarketIndex, tradeBaseSize, isLong, userClient, oraclePrice, limitPrice, offsetCollateral, precision = 2, isEnteringHighLeverageMode, capLiqPrice, }) => {
|
|
95
|
+
const calculateLiquidationPriceAfterPerpTrade = ({ estEntryPrice, orderType, perpMarketIndex, tradeBaseSize, isLong, userClient, oraclePrice, limitPrice, offsetCollateral, precision = 2, isEnteringHighLeverageMode, capLiqPrice, marginType, }) => {
|
|
96
96
|
var _a, _b;
|
|
97
97
|
const ALLOWED_ORDER_TYPES = [
|
|
98
98
|
'limit',
|
|
@@ -120,7 +120,7 @@ const calculateLiquidationPriceAfterPerpTrade = ({ estEntryPrice, orderType, per
|
|
|
120
120
|
? limitPrice
|
|
121
121
|
: estEntryPrice;
|
|
122
122
|
const liqPriceBn = userClient.liquidationPrice(perpMarketIndex, signedBaseSize, priceToUse, undefined, undefined, // we can exclude open orders since open orders will be cancelled first (which results in reducing account leverage) before actual liquidation
|
|
123
|
-
offsetCollateral, isEnteringHighLeverageMode);
|
|
123
|
+
offsetCollateral, isEnteringHighLeverageMode, marginType === 'Isolated' ? 'Isolated' : undefined);
|
|
124
124
|
if (liqPriceBn.isNeg()) {
|
|
125
125
|
// means no liquidation price
|
|
126
126
|
return 0;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trading.js","sourceRoot":"","sources":["../../src/common-ui-utils/trading.ts"],"names":[],"mappings":";;;AAAA,yCAiByB;AAGzB,MAAM,2BAA2B,GAAG,CACnC,GAAO,EACP,QAAsB,EACtB,UAAe,EACN,EAAE;;IACX,IAAI,CAAC,CAAA,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,gBAAgB,CAAA,KAAI,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,gBAAgB,CAAC,EAAE,CAAC,UAAI,CAAC,CAAA;QACrE,OAAO,CAAC,CAAC;IAEV,IAAI,aAAqB,CAAC;IAE1B,IAAI,UAAU,EAAE,CAAC;QAChB,aAAa,GAAG,YAAM,CAAC,IAAI,CAAC,UAAU,EAAE,yBAAmB,CAAC,CAAC,KAAK,EAAE,CAAC;IACtE,CAAC;SAAM,C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;QAEF,MAAM,cAAc,GAAG,IAAI,CAAC,iBAAiB,EAAE,CAAC;QAEhD,wDAAwD;QACxD,OAAO,8BAA8B,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;IAC3D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,OAAO,CAAC,IAAI,CAAC,mCAAmC,EAAE,KAAK,CAAC,CAAC;QACzD,OAAO,IAAI,CAAC,CAAC,mCAAmC;IACjD,CAAC;AACF,CAAC,CAAC;AAEW,QAAA,aAAa,GAAG;IAC5B,2BAA2B;IAC3B,wBAAwB;IACxB,uCAAuC;IACvC,sBAAsB;IACtB,4BAA4B;IAC5B,4BAA4B;IAC5B,iBAAiB;IACjB,yBAAyB;IACzB,iBAAiB;IACjB,yBAAyB;IACzB,qBAAqB,EAArB,6BAAqB;IACrB,wBAAwB;IACxB,sBAAsB;CACtB,CAAC","sourcesContent":["import {\n\tAMM_RESERVE_PRECISION,\n\tBN,\n\tBigNum,\n\tDriftClient,\n\tMARGIN_PRECISION,\n\tMAX_LEVERAGE_ORDER_SIZE,\n\tONE,\n\tPRICE_PRECISION,\n\tPRICE_PRECISION_EXP,\n\tPerpMarketAccount,\n\tPositionDirection,\n\tQUOTE_PRECISION_EXP,\n\tSpotMarketAccount,\n\tUser,\n\tZERO,\n\tisVariant,\n} from '@drift-labs/sdk';\nimport { MarketId, OpenPosition, UIOrderType } from 'src/types';\n\nconst calculatePnlPctFromPosition = (\n\tpnl: BN,\n\tposition: OpenPosition,\n\tmarginUsed?: BN\n): number => {\n\tif (!position?.quoteEntryAmount || position?.quoteEntryAmount.eq(ZERO))\n\t\treturn 0;\n\n\tlet marginUsedNum: number;\n\n\tif (marginUsed) {\n\t\tmarginUsedNum = BigNum.from(marginUsed, QUOTE_PRECISION_EXP).toNum();\n\t} else {\n\t\tconst leverage = convertMarginRatioToLeverage(position.maxMarginRatio) ?? 1;\n\t\tconst quoteEntryAmountNum = BigNum.from(\n\t\t\tposition.quoteEntryAmount.abs(),\n\t\t\tQUOTE_PRECISION_EXP\n\t\t).toNum();\n\n\t\tif (leverage <= 0 || quoteEntryAmountNum <= 0) {\n\t\t\tmarginUsedNum = 0;\n\t\t} else {\n\t\t\tmarginUsedNum = quoteEntryAmountNum / leverage;\n\t\t}\n\t}\n\n\tif (marginUsedNum <= 0) {\n\t\treturn 0;\n\t}\n\n\treturn (\n\t\tBigNum.from(pnl, QUOTE_PRECISION_EXP)\n\t\t\t.shift(5)\n\t\t\t.div(BigNum.fromPrint(`${marginUsedNum}`, QUOTE_PRECISION_EXP))\n\t\t\t.toNum() * 100\n\t);\n};\n\nconst POTENTIAL_PROFIT_DEFAULT_STATE = {\n\testimatedProfit: BigNum.zero(PRICE_PRECISION_EXP),\n\testimatedProfitBeforeFees: BigNum.zero(PRICE_PRECISION_EXP),\n\testimatedTakerFee: BigNum.zero(PRICE_PRECISION_EXP),\n\tnotionalSizeAtEntry: BigNum.zero(PRICE_PRECISION_EXP),\n\tnotionalSizeAtExit: BigNum.zero(PRICE_PRECISION_EXP),\n};\n\nconst calculatePotentialProfit = (props: {\n\tcurrentPositionSize: BigNum;\n\tcurrentPositionDirection: PositionDirection;\n\tcurrentPositionEntryPrice: BigNum;\n\ttradeDirection: PositionDirection;\n\t/**\n\t * Amount of position being closed in base asset size\n\t */\n\texitBaseSize: BigNum;\n\t/**\n\t * Either the user's limit price (for limit orders) or the estimated exit price (for market orders)\n\t */\n\texitPrice: BigNum;\n\ttakerFeeBps: number;\n\tslippageTolerance?: number;\n\tisMarketOrder?: boolean;\n}): {\n\testimatedProfit: BigNum;\n\testimatedProfitBeforeFees: BigNum;\n\testimatedTakerFee: BigNum;\n\tnotionalSizeAtEntry: BigNum;\n\tnotionalSizeAtExit: BigNum;\n} => {\n\tlet estimatedProfit = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet estimatedProfitBeforeFees = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet estimatedTakerFee = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet notionalSizeAtEntry = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet notionalSizeAtExit = BigNum.zero(PRICE_PRECISION_EXP);\n\n\tconst isClosingLong =\n\t\tisVariant(props.currentPositionDirection, 'long') &&\n\t\tisVariant(props.tradeDirection, 'short');\n\tconst isClosingShort =\n\t\tisVariant(props.currentPositionDirection, 'short') &&\n\t\tisVariant(props.tradeDirection, 'long');\n\n\tif (!isClosingLong && !isClosingShort) return POTENTIAL_PROFIT_DEFAULT_STATE;\n\tif (!props.exitBaseSize) return POTENTIAL_PROFIT_DEFAULT_STATE;\n\n\tif (\n\t\tprops.exitBaseSize.eqZero() ||\n\t\tprops.currentPositionSize.lt(props.exitBaseSize)\n\t) {\n\t\treturn POTENTIAL_PROFIT_DEFAULT_STATE;\n\t}\n\n\tconst baseSizeBeingClosed = props.exitBaseSize.lte(props.currentPositionSize)\n\t\t? props.exitBaseSize\n\t\t: props.currentPositionSize;\n\n\t// Notional size of amount being closed at entry and exit\n\tnotionalSizeAtEntry = baseSizeBeingClosed.mul(\n\t\tprops.currentPositionEntryPrice.shiftTo(baseSizeBeingClosed.precision)\n\t);\n\tnotionalSizeAtExit = baseSizeBeingClosed.mul(\n\t\tprops.exitPrice.shiftTo(baseSizeBeingClosed.precision)\n\t);\n\n\tif (isClosingLong) {\n\t\testimatedProfitBeforeFees = notionalSizeAtExit.sub(notionalSizeAtEntry);\n\t} else if (isClosingShort) {\n\t\testimatedProfitBeforeFees = notionalSizeAtEntry.sub(notionalSizeAtExit);\n\t}\n\n\t// subtract takerFee if applicable\n\tif (props.takerFeeBps > 0) {\n\t\tconst takerFeeDenominator = Math.floor(100 / (props.takerFeeBps * 0.01));\n\t\testimatedTakerFee = notionalSizeAtExit.scale(1, takerFeeDenominator);\n\t\testimatedProfit = estimatedProfitBeforeFees.sub(\n\t\t\testimatedTakerFee.shiftTo(estimatedProfitBeforeFees.precision)\n\t\t);\n\t} else {\n\t\testimatedProfit = estimatedProfitBeforeFees;\n\t}\n\n\treturn {\n\t\testimatedProfit,\n\t\testimatedProfitBeforeFees,\n\t\testimatedTakerFee,\n\t\tnotionalSizeAtEntry,\n\t\tnotionalSizeAtExit,\n\t};\n};\n\n/**\n * Check if the order type is a market order or oracle market order\n */\nconst checkIsMarketOrderType = (orderType: UIOrderType) => {\n\treturn orderType === 'market' || orderType === 'oracle';\n};\n\n/**\n * Calculate the liquidation price of a position after a trade. Requires DriftClient to be subscribed.\n * If the order type is limit order, a limit price must be provided.\n */\nconst calculateLiquidationPriceAfterPerpTrade = ({\n\testEntryPrice,\n\torderType,\n\tperpMarketIndex,\n\ttradeBaseSize,\n\tisLong,\n\tuserClient,\n\toraclePrice,\n\tlimitPrice,\n\toffsetCollateral,\n\tprecision = 2,\n\tisEnteringHighLeverageMode,\n\tcapLiqPrice,\n}: {\n\testEntryPrice: BN;\n\torderType: UIOrderType;\n\tperpMarketIndex: number;\n\ttradeBaseSize: BN;\n\tisLong: boolean;\n\tuserClient: User;\n\toraclePrice: BN;\n\tlimitPrice?: BN;\n\toffsetCollateral?: BN;\n\tprecision?: number;\n\tisEnteringHighLeverageMode?: boolean;\n\tcapLiqPrice?: boolean;\n}) => {\n\tconst ALLOWED_ORDER_TYPES: UIOrderType[] = [\n\t\t'limit',\n\t\t'market',\n\t\t'oracle',\n\t\t'stopMarket',\n\t\t'stopLimit',\n\t\t'oracleLimit',\n\t];\n\n\tif (!ALLOWED_ORDER_TYPES.includes(orderType)) {\n\t\tconsole.error(\n\t\t\t'Invalid order type for perp trade liquidation price calculation',\n\t\t\torderType\n\t\t);\n\t\treturn 0;\n\t}\n\n\tif (orderType === 'limit' && !limitPrice) {\n\t\tconsole.error(\n\t\t\t'Limit order must have a limit price for perp trade liquidation price calculation'\n\t\t);\n\t\treturn 0;\n\t}\n\n\tconst signedBaseSize = isLong ? tradeBaseSize : tradeBaseSize.neg();\n\tconst priceToUse = [\n\t\t'limit',\n\t\t'stopMarket',\n\t\t'stopLimit',\n\t\t'oracleLimit',\n\t].includes(orderType)\n\t\t? limitPrice\n\t\t: estEntryPrice;\n\n\tconst liqPriceBn = userClient.liquidationPrice(\n\t\tperpMarketIndex,\n\t\tsignedBaseSize,\n\t\tpriceToUse,\n\t\tundefined,\n\t\tundefined, // we can exclude open orders since open orders will be cancelled first (which results in reducing account leverage) before actual liquidation\n\t\toffsetCollateral,\n\t\tisEnteringHighLeverageMode\n\t);\n\n\tif (liqPriceBn.isNeg()) {\n\t\t// means no liquidation price\n\t\treturn 0;\n\t}\n\n\t// Check if user has a spot position using the same oracle as the perp market\n\t// If so, force capLiqPrice to be false to avoid incorrect price capping\n\t// Technically in this case, liq price could be lower for a short or higher for a long\n\tconst perpMarketOracle =\n\t\tuserClient.driftClient.getPerpMarketAccount(perpMarketIndex)?.amm?.oracle;\n\n\tconst spotMarketWithSameOracle = userClient.driftClient\n\t\t.getSpotMarketAccounts()\n\t\t.find((market) => market.oracle.equals(perpMarketOracle));\n\n\tlet hasSpotPositionWithSameOracle = false;\n\tif (spotMarketWithSameOracle) {\n\t\tconst spotPosition = userClient.getSpotPosition(\n\t\t\tspotMarketWithSameOracle.marketIndex\n\t\t);\n\t\thasSpotPositionWithSameOracle = !!spotPosition;\n\t}\n\n\tconst effectiveCapLiqPrice = hasSpotPositionWithSameOracle\n\t\t? false\n\t\t: capLiqPrice;\n\n\tconst cappedLiqPriceBn = effectiveCapLiqPrice\n\t\t? isLong\n\t\t\t? BN.min(liqPriceBn, oraclePrice)\n\t\t\t: BN.max(liqPriceBn, oraclePrice)\n\t\t: liqPriceBn;\n\n\tconst liqPriceBigNum = BigNum.from(cappedLiqPriceBn, PRICE_PRECISION_EXP);\n\n\tconst liqPriceNum =\n\t\tMath.round(liqPriceBigNum.toNum() * 10 ** precision) / 10 ** precision;\n\n\treturn liqPriceNum;\n};\n\nconst convertLeverageToMarginRatio = (leverage: number): number | undefined => {\n\tif (!leverage) return undefined;\n\treturn Math.round((1 / leverage) * MARGIN_PRECISION.toNumber());\n};\n\nconst convertMarginRatioToLeverage = (\n\tmarginRatio: number,\n\tdecimals?: number\n): number | undefined => {\n\tif (!marginRatio) return undefined;\n\n\tconst leverage = 1 / (marginRatio / MARGIN_PRECISION.toNumber());\n\n\treturn decimals\n\t\t? parseFloat(leverage.toFixed(decimals))\n\t\t: Math.round(leverage);\n};\n\nconst getMarketTickSize = (\n\tdriftClient: DriftClient,\n\tmarketId: MarketId\n): BN => {\n\tconst marketAccount = marketId.isPerp\n\t\t? driftClient.getPerpMarketAccount(marketId.marketIndex)\n\t\t: driftClient.getSpotMarketAccount(marketId.marketIndex);\n\tif (!marketAccount) return ZERO;\n\n\tif (marketId.isPerp) {\n\t\treturn (marketAccount as PerpMarketAccount).amm.orderTickSize;\n\t} else {\n\t\treturn (marketAccount as SpotMarketAccount).orderTickSize;\n\t}\n};\n\nconst getMarketTickSizeDecimals = (\n\tdriftClient: DriftClient,\n\tmarketId: MarketId\n) => {\n\tconst tickSize = getMarketTickSize(driftClient, marketId);\n\n\tconst decimalPlaces = Math.max(\n\t\t0,\n\t\tMath.floor(\n\t\t\tMath.log10(\n\t\t\t\tPRICE_PRECISION.div(tickSize.eq(ZERO) ? ONE : tickSize).toNumber()\n\t\t\t)\n\t\t)\n\t);\n\n\treturn decimalPlaces;\n};\n\nconst getMarketStepSize = (driftClient: DriftClient, marketId: MarketId) => {\n\tconst marketAccount = marketId.isPerp\n\t\t? driftClient.getPerpMarketAccount(marketId.marketIndex)\n\t\t: driftClient.getSpotMarketAccount(marketId.marketIndex);\n\tif (!marketAccount) return ZERO;\n\n\tif (marketId.isPerp) {\n\t\treturn (marketAccount as PerpMarketAccount).amm.orderStepSize;\n\t} else {\n\t\treturn (marketAccount as SpotMarketAccount).orderStepSize;\n\t}\n};\n\nconst getMarketStepSizeDecimals = (\n\tdriftClient: DriftClient,\n\tmarketId: MarketId\n) => {\n\tconst stepSize = getMarketStepSize(driftClient, marketId);\n\n\tconst decimalPlaces = Math.max(\n\t\t0,\n\t\tMath.floor(\n\t\t\tMath.log10(\n\t\t\t\tAMM_RESERVE_PRECISION.div(stepSize.eq(ZERO) ? ONE : stepSize).toNumber()\n\t\t\t)\n\t\t)\n\t);\n\n\treturn decimalPlaces;\n};\n\n/**\n * Checks if a given order amount represents an entire position order\n * by comparing it with MAX_LEVERAGE_ORDER_SIZE\n * @param orderAmount - The BigNum order amount to check\n * @returns true if the order is for the entire position, false otherwise\n */\nexport const isEntirePositionOrder = (orderAmount: BigNum): boolean => {\n\tconst maxLeverageSize = new BigNum(\n\t\tMAX_LEVERAGE_ORDER_SIZE,\n\t\torderAmount.precision\n\t);\n\treturn Math.abs(maxLeverageSize.sub(orderAmount).toNum()) < 1;\n};\n\n/**\n * Calculate the margin used for a specific perp position\n * Returns the minimum of user's total collateral or the position's weighted value\n */\nconst getMarginUsedForPosition = (\n\tuser: User,\n\tmarketIndex: number,\n\tincludeOpenOrders = true\n): BN | undefined => {\n\tconst perpPosition = user.getPerpPosition(marketIndex);\n\tif (!perpPosition) return undefined;\n\n\tconst hc = user.getPerpPositionHealth({\n\t\tmarginCategory: 'Initial',\n\t\tperpPosition,\n\t\tincludeOpenOrders,\n\t});\n\tconst userCollateral = user.getTotalCollateral();\n\treturn userCollateral.lt(hc.weightedValue)\n\t\t? userCollateral\n\t\t: hc.weightedValue;\n};\n\n/**\n * Validate if a leverage change would exceed the user's free collateral\n * Returns true if the change is valid (doesn't exceed free collateral), false otherwise\n */\nconst validateLeverageChange = ({\n\tuser,\n\tmarketIndex,\n\tnewLeverage,\n}: {\n\tuser: User;\n\tmarketIndex: number;\n\tnewLeverage: number;\n}): boolean => {\n\ttry {\n\t\t// Convert leverage to margin ratio\n\t\tconst newMarginRatio = convertLeverageToMarginRatio(newLeverage);\n\t\tif (!newMarginRatio) return true;\n\n\t\t// Get the perp position from the user\n\t\tconst perpPosition = user.getPerpPosition(marketIndex);\n\t\tif (!perpPosition) return true;\n\n\t\t// Get current position weighted value\n\t\tconst currentPositionWeightedValue = user.getPerpPositionHealth({\n\t\t\tmarginCategory: 'Initial',\n\t\t\tperpPosition,\n\t\t}).weightedValue;\n\n\t\t// Create a modified version of the position with new maxMarginRatio\n\t\tconst modifiedPosition = {\n\t\t\t...perpPosition,\n\t\t\tmaxMarginRatio: newMarginRatio,\n\t\t};\n\n\t\t// Calculate new weighted value with the modified position\n\t\tconst newPositionWeightedValue = user.getPerpPositionHealth({\n\t\t\tmarginCategory: 'Initial',\n\t\t\tperpPosition: modifiedPosition,\n\t\t}).weightedValue;\n\n\t\tconst perpPositionWeightedValueDelta = newPositionWeightedValue.sub(\n\t\t\tcurrentPositionWeightedValue\n\t\t);\n\n\t\tconst freeCollateral = user.getFreeCollateral();\n\n\t\t// Check if weighted value delta exceeds free collateral\n\t\treturn perpPositionWeightedValueDelta.lte(freeCollateral);\n\t} catch (error) {\n\t\tconsole.warn('Error validating leverage change:', error);\n\t\treturn true; // Allow change if validation fails\n\t}\n};\n\nexport const TRADING_UTILS = {\n\tcalculatePnlPctFromPosition,\n\tcalculatePotentialProfit,\n\tcalculateLiquidationPriceAfterPerpTrade,\n\tcheckIsMarketOrderType,\n\tconvertLeverageToMarginRatio,\n\tconvertMarginRatioToLeverage,\n\tgetMarketTickSize,\n\tgetMarketTickSizeDecimals,\n\tgetMarketStepSize,\n\tgetMarketStepSizeDecimals,\n\tisEntirePositionOrder,\n\tgetMarginUsedForPosition,\n\tvalidateLeverageChange,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"trading.js","sourceRoot":"","sources":["../../src/common-ui-utils/trading.ts"],"names":[],"mappings":";;;AAAA,yCAiByB;AAGzB,MAAM,2BAA2B,GAAG,CACnC,GAAO,EACP,QAAsB,EACtB,UAAe,EACN,EAAE;;IACX,IAAI,CAAC,CAAA,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,gBAAgB,CAAA,KAAI,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,gBAAgB,CAAC,EAAE,CAAC,UAAI,CAAC,CAAA;QACrE,OAAO,CAAC,CAAC;IAE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E,cAAc;SAC9B,CAAC;QAEF,0DAA0D;QAC1D,MAAM,wBAAwB,GAAG,IAAI,CAAC,qBAAqB,CAAC;YAC3D,cAAc,EAAE,SAAS;YACzB,YAAY,EAAE,gBAAgB;SAC9B,CAAC,CAAC,aAAa,CAAC;QAEjB,MAAM,8BAA8B,GAAG,wBAAwB,CAAC,GAAG,CAClE,4BAA4B,CAC5B,CAAC;QAEF,MAAM,cAAc,GAAG,IAAI,CAAC,iBAAiB,EAAE,CAAC;QAEhD,wDAAwD;QACxD,OAAO,8BAA8B,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;IAC3D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,OAAO,CAAC,IAAI,CAAC,mCAAmC,EAAE,KAAK,CAAC,CAAC;QACzD,OAAO,IAAI,CAAC,CAAC,mCAAmC;IACjD,CAAC;AACF,CAAC,CAAC;AAEW,QAAA,aAAa,GAAG;IAC5B,2BAA2B;IAC3B,wBAAwB;IACxB,uCAAuC;IACvC,sBAAsB;IACtB,4BAA4B;IAC5B,4BAA4B;IAC5B,iBAAiB;IACjB,yBAAyB;IACzB,iBAAiB;IACjB,yBAAyB;IACzB,qBAAqB,EAArB,6BAAqB;IACrB,wBAAwB;IACxB,sBAAsB;CACtB,CAAC","sourcesContent":["import {\n\tAMM_RESERVE_PRECISION,\n\tBN,\n\tBigNum,\n\tDriftClient,\n\tMARGIN_PRECISION,\n\tMAX_LEVERAGE_ORDER_SIZE,\n\tONE,\n\tPRICE_PRECISION,\n\tPRICE_PRECISION_EXP,\n\tPerpMarketAccount,\n\tPositionDirection,\n\tQUOTE_PRECISION_EXP,\n\tSpotMarketAccount,\n\tUser,\n\tZERO,\n\tisVariant,\n} from '@drift-labs/sdk';\nimport { MarketId, OpenPosition, UIOrderType } from 'src/types';\n\nconst calculatePnlPctFromPosition = (\n\tpnl: BN,\n\tposition: OpenPosition,\n\tmarginUsed?: BN\n): number => {\n\tif (!position?.quoteEntryAmount || position?.quoteEntryAmount.eq(ZERO))\n\t\treturn 0;\n\n\tlet marginUsedNum: number;\n\n\tif (marginUsed) {\n\t\tmarginUsedNum = BigNum.from(marginUsed, QUOTE_PRECISION_EXP).toNum();\n\t} else {\n\t\tconst leverage = convertMarginRatioToLeverage(position.maxMarginRatio) ?? 1;\n\t\tconst quoteEntryAmountNum = BigNum.from(\n\t\t\tposition.quoteEntryAmount.abs(),\n\t\t\tQUOTE_PRECISION_EXP\n\t\t).toNum();\n\n\t\tif (leverage <= 0 || quoteEntryAmountNum <= 0) {\n\t\t\tmarginUsedNum = 0;\n\t\t} else {\n\t\t\tmarginUsedNum = quoteEntryAmountNum / leverage;\n\t\t}\n\t}\n\n\tif (marginUsedNum <= 0) {\n\t\treturn 0;\n\t}\n\n\treturn (\n\t\tBigNum.from(pnl, QUOTE_PRECISION_EXP)\n\t\t\t.shift(5)\n\t\t\t.div(BigNum.fromPrint(`${marginUsedNum}`, QUOTE_PRECISION_EXP))\n\t\t\t.toNum() * 100\n\t);\n};\n\nconst POTENTIAL_PROFIT_DEFAULT_STATE = {\n\testimatedProfit: BigNum.zero(PRICE_PRECISION_EXP),\n\testimatedProfitBeforeFees: BigNum.zero(PRICE_PRECISION_EXP),\n\testimatedTakerFee: BigNum.zero(PRICE_PRECISION_EXP),\n\tnotionalSizeAtEntry: BigNum.zero(PRICE_PRECISION_EXP),\n\tnotionalSizeAtExit: BigNum.zero(PRICE_PRECISION_EXP),\n};\n\nconst calculatePotentialProfit = (props: {\n\tcurrentPositionSize: BigNum;\n\tcurrentPositionDirection: PositionDirection;\n\tcurrentPositionEntryPrice: BigNum;\n\ttradeDirection: PositionDirection;\n\t/**\n\t * Amount of position being closed in base asset size\n\t */\n\texitBaseSize: BigNum;\n\t/**\n\t * Either the user's limit price (for limit orders) or the estimated exit price (for market orders)\n\t */\n\texitPrice: BigNum;\n\ttakerFeeBps: number;\n\tslippageTolerance?: number;\n\tisMarketOrder?: boolean;\n}): {\n\testimatedProfit: BigNum;\n\testimatedProfitBeforeFees: BigNum;\n\testimatedTakerFee: BigNum;\n\tnotionalSizeAtEntry: BigNum;\n\tnotionalSizeAtExit: BigNum;\n} => {\n\tlet estimatedProfit = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet estimatedProfitBeforeFees = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet estimatedTakerFee = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet notionalSizeAtEntry = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet notionalSizeAtExit = BigNum.zero(PRICE_PRECISION_EXP);\n\n\tconst isClosingLong =\n\t\tisVariant(props.currentPositionDirection, 'long') &&\n\t\tisVariant(props.tradeDirection, 'short');\n\tconst isClosingShort =\n\t\tisVariant(props.currentPositionDirection, 'short') &&\n\t\tisVariant(props.tradeDirection, 'long');\n\n\tif (!isClosingLong && !isClosingShort) return POTENTIAL_PROFIT_DEFAULT_STATE;\n\tif (!props.exitBaseSize) return POTENTIAL_PROFIT_DEFAULT_STATE;\n\n\tif (\n\t\tprops.exitBaseSize.eqZero() ||\n\t\tprops.currentPositionSize.lt(props.exitBaseSize)\n\t) {\n\t\treturn POTENTIAL_PROFIT_DEFAULT_STATE;\n\t}\n\n\tconst baseSizeBeingClosed = props.exitBaseSize.lte(props.currentPositionSize)\n\t\t? props.exitBaseSize\n\t\t: props.currentPositionSize;\n\n\t// Notional size of amount being closed at entry and exit\n\tnotionalSizeAtEntry = baseSizeBeingClosed.mul(\n\t\tprops.currentPositionEntryPrice.shiftTo(baseSizeBeingClosed.precision)\n\t);\n\tnotionalSizeAtExit = baseSizeBeingClosed.mul(\n\t\tprops.exitPrice.shiftTo(baseSizeBeingClosed.precision)\n\t);\n\n\tif (isClosingLong) {\n\t\testimatedProfitBeforeFees = notionalSizeAtExit.sub(notionalSizeAtEntry);\n\t} else if (isClosingShort) {\n\t\testimatedProfitBeforeFees = notionalSizeAtEntry.sub(notionalSizeAtExit);\n\t}\n\n\t// subtract takerFee if applicable\n\tif (props.takerFeeBps > 0) {\n\t\tconst takerFeeDenominator = Math.floor(100 / (props.takerFeeBps * 0.01));\n\t\testimatedTakerFee = notionalSizeAtExit.scale(1, takerFeeDenominator);\n\t\testimatedProfit = estimatedProfitBeforeFees.sub(\n\t\t\testimatedTakerFee.shiftTo(estimatedProfitBeforeFees.precision)\n\t\t);\n\t} else {\n\t\testimatedProfit = estimatedProfitBeforeFees;\n\t}\n\n\treturn {\n\t\testimatedProfit,\n\t\testimatedProfitBeforeFees,\n\t\testimatedTakerFee,\n\t\tnotionalSizeAtEntry,\n\t\tnotionalSizeAtExit,\n\t};\n};\n\n/**\n * Check if the order type is a market order or oracle market order\n */\nconst checkIsMarketOrderType = (orderType: UIOrderType) => {\n\treturn orderType === 'market' || orderType === 'oracle';\n};\n\n/**\n * Calculate the liquidation price of a position after a trade. Requires DriftClient to be subscribed.\n * If the order type is limit order, a limit price must be provided.\n */\nconst calculateLiquidationPriceAfterPerpTrade = ({\n\testEntryPrice,\n\torderType,\n\tperpMarketIndex,\n\ttradeBaseSize,\n\tisLong,\n\tuserClient,\n\toraclePrice,\n\tlimitPrice,\n\toffsetCollateral,\n\tprecision = 2,\n\tisEnteringHighLeverageMode,\n\tcapLiqPrice,\n\tmarginType,\n}: {\n\testEntryPrice: BN;\n\torderType: UIOrderType;\n\tperpMarketIndex: number;\n\ttradeBaseSize: BN;\n\tisLong: boolean;\n\tuserClient: User;\n\toraclePrice: BN;\n\tlimitPrice?: BN;\n\toffsetCollateral?: BN;\n\tprecision?: number;\n\tisEnteringHighLeverageMode?: boolean;\n\tcapLiqPrice?: boolean;\n\tmarginType?: 'Cross' | 'Isolated';\n}) => {\n\tconst ALLOWED_ORDER_TYPES: UIOrderType[] = [\n\t\t'limit',\n\t\t'market',\n\t\t'oracle',\n\t\t'stopMarket',\n\t\t'stopLimit',\n\t\t'oracleLimit',\n\t];\n\n\tif (!ALLOWED_ORDER_TYPES.includes(orderType)) {\n\t\tconsole.error(\n\t\t\t'Invalid order type for perp trade liquidation price calculation',\n\t\t\torderType\n\t\t);\n\t\treturn 0;\n\t}\n\n\tif (orderType === 'limit' && !limitPrice) {\n\t\tconsole.error(\n\t\t\t'Limit order must have a limit price for perp trade liquidation price calculation'\n\t\t);\n\t\treturn 0;\n\t}\n\n\tconst signedBaseSize = isLong ? tradeBaseSize : tradeBaseSize.neg();\n\tconst priceToUse = [\n\t\t'limit',\n\t\t'stopMarket',\n\t\t'stopLimit',\n\t\t'oracleLimit',\n\t].includes(orderType)\n\t\t? limitPrice\n\t\t: estEntryPrice;\n\n\tconst liqPriceBn = userClient.liquidationPrice(\n\t\tperpMarketIndex,\n\t\tsignedBaseSize,\n\t\tpriceToUse,\n\t\tundefined,\n\t\tundefined, // we can exclude open orders since open orders will be cancelled first (which results in reducing account leverage) before actual liquidation\n\t\toffsetCollateral,\n\t\tisEnteringHighLeverageMode,\n\t\tmarginType === 'Isolated' ? 'Isolated' : undefined\n\t);\n\n\tif (liqPriceBn.isNeg()) {\n\t\t// means no liquidation price\n\t\treturn 0;\n\t}\n\n\t// Check if user has a spot position using the same oracle as the perp market\n\t// If so, force capLiqPrice to be false to avoid incorrect price capping\n\t// Technically in this case, liq price could be lower for a short or higher for a long\n\tconst perpMarketOracle =\n\t\tuserClient.driftClient.getPerpMarketAccount(perpMarketIndex)?.amm?.oracle;\n\n\tconst spotMarketWithSameOracle = userClient.driftClient\n\t\t.getSpotMarketAccounts()\n\t\t.find((market) => market.oracle.equals(perpMarketOracle));\n\n\tlet hasSpotPositionWithSameOracle = false;\n\tif (spotMarketWithSameOracle) {\n\t\tconst spotPosition = userClient.getSpotPosition(\n\t\t\tspotMarketWithSameOracle.marketIndex\n\t\t);\n\t\thasSpotPositionWithSameOracle = !!spotPosition;\n\t}\n\n\tconst effectiveCapLiqPrice = hasSpotPositionWithSameOracle\n\t\t? false\n\t\t: capLiqPrice;\n\n\tconst cappedLiqPriceBn = effectiveCapLiqPrice\n\t\t? isLong\n\t\t\t? BN.min(liqPriceBn, oraclePrice)\n\t\t\t: BN.max(liqPriceBn, oraclePrice)\n\t\t: liqPriceBn;\n\n\tconst liqPriceBigNum = BigNum.from(cappedLiqPriceBn, PRICE_PRECISION_EXP);\n\n\tconst liqPriceNum =\n\t\tMath.round(liqPriceBigNum.toNum() * 10 ** precision) / 10 ** precision;\n\n\treturn liqPriceNum;\n};\n\nconst convertLeverageToMarginRatio = (leverage: number): number | undefined => {\n\tif (!leverage) return undefined;\n\treturn Math.round((1 / leverage) * MARGIN_PRECISION.toNumber());\n};\n\nconst convertMarginRatioToLeverage = (\n\tmarginRatio: number,\n\tdecimals?: number\n): number | undefined => {\n\tif (!marginRatio) return undefined;\n\n\tconst leverage = 1 / (marginRatio / MARGIN_PRECISION.toNumber());\n\n\treturn decimals\n\t\t? parseFloat(leverage.toFixed(decimals))\n\t\t: Math.round(leverage);\n};\n\nconst getMarketTickSize = (\n\tdriftClient: DriftClient,\n\tmarketId: MarketId\n): BN => {\n\tconst marketAccount = marketId.isPerp\n\t\t? driftClient.getPerpMarketAccount(marketId.marketIndex)\n\t\t: driftClient.getSpotMarketAccount(marketId.marketIndex);\n\tif (!marketAccount) return ZERO;\n\n\tif (marketId.isPerp) {\n\t\treturn (marketAccount as PerpMarketAccount).amm.orderTickSize;\n\t} else {\n\t\treturn (marketAccount as SpotMarketAccount).orderTickSize;\n\t}\n};\n\nconst getMarketTickSizeDecimals = (\n\tdriftClient: DriftClient,\n\tmarketId: MarketId\n) => {\n\tconst tickSize = getMarketTickSize(driftClient, marketId);\n\n\tconst decimalPlaces = Math.max(\n\t\t0,\n\t\tMath.floor(\n\t\t\tMath.log10(\n\t\t\t\tPRICE_PRECISION.div(tickSize.eq(ZERO) ? ONE : tickSize).toNumber()\n\t\t\t)\n\t\t)\n\t);\n\n\treturn decimalPlaces;\n};\n\nconst getMarketStepSize = (driftClient: DriftClient, marketId: MarketId) => {\n\tconst marketAccount = marketId.isPerp\n\t\t? driftClient.getPerpMarketAccount(marketId.marketIndex)\n\t\t: driftClient.getSpotMarketAccount(marketId.marketIndex);\n\tif (!marketAccount) return ZERO;\n\n\tif (marketId.isPerp) {\n\t\treturn (marketAccount as PerpMarketAccount).amm.orderStepSize;\n\t} else {\n\t\treturn (marketAccount as SpotMarketAccount).orderStepSize;\n\t}\n};\n\nconst getMarketStepSizeDecimals = (\n\tdriftClient: DriftClient,\n\tmarketId: MarketId\n) => {\n\tconst stepSize = getMarketStepSize(driftClient, marketId);\n\n\tconst decimalPlaces = Math.max(\n\t\t0,\n\t\tMath.floor(\n\t\t\tMath.log10(\n\t\t\t\tAMM_RESERVE_PRECISION.div(stepSize.eq(ZERO) ? ONE : stepSize).toNumber()\n\t\t\t)\n\t\t)\n\t);\n\n\treturn decimalPlaces;\n};\n\n/**\n * Checks if a given order amount represents an entire position order\n * by comparing it with MAX_LEVERAGE_ORDER_SIZE\n * @param orderAmount - The BigNum order amount to check\n * @returns true if the order is for the entire position, false otherwise\n */\nexport const isEntirePositionOrder = (orderAmount: BigNum): boolean => {\n\tconst maxLeverageSize = new BigNum(\n\t\tMAX_LEVERAGE_ORDER_SIZE,\n\t\torderAmount.precision\n\t);\n\treturn Math.abs(maxLeverageSize.sub(orderAmount).toNum()) < 1;\n};\n\n/**\n * Calculate the margin used for a specific perp position\n * Returns the minimum of user's total collateral or the position's weighted value\n */\nconst getMarginUsedForPosition = (\n\tuser: User,\n\tmarketIndex: number,\n\tincludeOpenOrders = true\n): BN | undefined => {\n\tconst perpPosition = user.getPerpPosition(marketIndex);\n\tif (!perpPosition) return undefined;\n\n\tconst hc = user.getPerpPositionHealth({\n\t\tmarginCategory: 'Initial',\n\t\tperpPosition,\n\t\tincludeOpenOrders,\n\t});\n\tconst userCollateral = user.getTotalCollateral();\n\treturn userCollateral.lt(hc.weightedValue)\n\t\t? userCollateral\n\t\t: hc.weightedValue;\n};\n\n/**\n * Validate if a leverage change would exceed the user's free collateral\n * Returns true if the change is valid (doesn't exceed free collateral), false otherwise\n */\nconst validateLeverageChange = ({\n\tuser,\n\tmarketIndex,\n\tnewLeverage,\n}: {\n\tuser: User;\n\tmarketIndex: number;\n\tnewLeverage: number;\n}): boolean => {\n\ttry {\n\t\t// Convert leverage to margin ratio\n\t\tconst newMarginRatio = convertLeverageToMarginRatio(newLeverage);\n\t\tif (!newMarginRatio) return true;\n\n\t\t// Get the perp position from the user\n\t\tconst perpPosition = user.getPerpPosition(marketIndex);\n\t\tif (!perpPosition) return true;\n\n\t\t// Get current position weighted value\n\t\tconst currentPositionWeightedValue = user.getPerpPositionHealth({\n\t\t\tmarginCategory: 'Initial',\n\t\t\tperpPosition,\n\t\t}).weightedValue;\n\n\t\t// Create a modified version of the position with new maxMarginRatio\n\t\tconst modifiedPosition = {\n\t\t\t...perpPosition,\n\t\t\tmaxMarginRatio: newMarginRatio,\n\t\t};\n\n\t\t// Calculate new weighted value with the modified position\n\t\tconst newPositionWeightedValue = user.getPerpPositionHealth({\n\t\t\tmarginCategory: 'Initial',\n\t\t\tperpPosition: modifiedPosition,\n\t\t}).weightedValue;\n\n\t\tconst perpPositionWeightedValueDelta = newPositionWeightedValue.sub(\n\t\t\tcurrentPositionWeightedValue\n\t\t);\n\n\t\tconst freeCollateral = user.getFreeCollateral();\n\n\t\t// Check if weighted value delta exceeds free collateral\n\t\treturn perpPositionWeightedValueDelta.lte(freeCollateral);\n\t} catch (error) {\n\t\tconsole.warn('Error validating leverage change:', error);\n\t\treturn true; // Allow change if validation fails\n\t}\n};\n\nexport const TRADING_UTILS = {\n\tcalculatePnlPctFromPosition,\n\tcalculatePotentialProfit,\n\tcalculateLiquidationPriceAfterPerpTrade,\n\tcheckIsMarketOrderType,\n\tconvertLeverageToMarginRatio,\n\tconvertMarginRatioToLeverage,\n\tgetMarketTickSize,\n\tgetMarketTickSizeDecimals,\n\tgetMarketStepSize,\n\tgetMarketStepSizeDecimals,\n\tisEntirePositionOrder,\n\tgetMarginUsedForPosition,\n\tvalidateLeverageChange,\n};\n"]}
|
package/lib/constants/orders.js
CHANGED
|
@@ -32,14 +32,14 @@ exports.STOP_LIMIT_ORDER_TYPE_CONFIG = {
|
|
|
32
32
|
};
|
|
33
33
|
// Take Profit Market order type
|
|
34
34
|
exports.TAKE_PROFIT_MARKET_ORDER_TYPE_CONFIG = {
|
|
35
|
-
label: '
|
|
35
|
+
label: 'TP Market',
|
|
36
36
|
value: 'takeProfitMarket',
|
|
37
37
|
orderType: sdk_1.OrderType.TRIGGER_MARKET,
|
|
38
38
|
description: 'A Take Profit Order is an order to close the position of a given asset if its Oracle Price reaches the specified Trigger Price. If this happens, the position is closed at Market Price.',
|
|
39
39
|
};
|
|
40
40
|
// Take Profit Limit order type
|
|
41
41
|
exports.TAKE_PROFIT_LIMIT_ORDER_TYPE_CONFIG = {
|
|
42
|
-
label: '
|
|
42
|
+
label: 'TP Limit',
|
|
43
43
|
value: 'takeProfitLimit',
|
|
44
44
|
orderType: sdk_1.OrderType.TRIGGER_LIMIT,
|
|
45
45
|
description: 'A Take Profit Limit Order will only execute where the Oracle Price of a given asset reaches the Trigger Price. If this happens, a Limit Order at the specified Limit Price will be placed.',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"orders.js","sourceRoot":"","sources":["../../src/constants/orders.ts"],"names":[],"mappings":";;;AAAA,yCAA4C;AAG5C,oBAAoB;AACP,QAAA,wBAAwB,GAAqB;IACzD,KAAK,EAAE,QAAQ;IACf,KAAK,EAAE,QAAQ;IACf,SAAS,EAAE,eAAS,CAAC,MAAM;IAC3B,WAAW,EACV,yIAAyI;CAC1I,CAAC;AAEF,mBAAmB;AACN,QAAA,uBAAuB,GAAqB;IACxD,KAAK,EAAE,OAAO;IACd,KAAK,EAAE,OAAO;IACd,SAAS,EAAE,eAAS,CAAC,KAAK;IAC1B,WAAW,EACV,wJAAwJ;CACzJ,CAAC;AAEF,yBAAyB;AACZ,QAAA,6BAA6B,GAAqB;IAC9D,KAAK,EAAE,aAAa;IACpB,KAAK,EAAE,YAAY;IACnB,SAAS,EAAE,eAAS,CAAC,cAAc;IACnC,W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AE,UAAU;IACjB,KAAK,EAAE,iBAAiB;IACxB,SAAS,EAAE,eAAS,CAAC,aAAa;IAClC,WAAW,EACV,4LAA4L;CAC7L,CAAC;AAEF,2BAA2B;AACd,QAAA,+BAA+B,GAAqB;IAChE,KAAK,EAAE,eAAe;IACtB,KAAK,EAAE,QAAQ;IACf,SAAS,EAAE,eAAS,CAAC,MAAM;CAC3B,CAAC;AAEF,0BAA0B;AACb,QAAA,8BAA8B,GAAqB;IAC/D,KAAK,EAAE,cAAc;IACrB,KAAK,EAAE,aAAa;IACpB,SAAS,EAAE,eAAS,CAAC,KAAK;IAC1B,WAAW,EACV,iNAAiN;CAClN,CAAC;AAEF,2BAA2B;AACd,QAAA,+BAA+B,GAAqB;IAChE,KAAK,EAAE,OAAO;IACd,KAAK,EAAE,cAAc;IACrB,SAAS,EAAE,eAAS,CAAC,KAAK;IAC1B,WAAW,EACV,uNAAuN;CACxN,CAAC;AAEW,QAAA,cAAc,GAAsB;IAChD,MAAM,EAAE,gCAAwB;IAChC,KAAK,EAAE,+BAAuB;IAC9B,UAAU,EAAE,qCAA6B;IACzC,SAAS,EAAE,oCAA4B;IACvC,gBAAgB,EAAE,4CAAoC;IACtD,eAAe,EAAE,2CAAmC;IACpD,MAAM,EAAE,uCAA+B;IACvC,WAAW,EAAE,sCAA8B;IAC3C,YAAY,EAAE,uCAA+B;CAC7C,CAAC;AAEW,QAAA,mBAAmB,GAAG,MAAM,CAAC,MAAM,CAAC,sBAAc,CAAC,CAAC","sourcesContent":["import { OrderType } from '@drift-labs/sdk';\nimport { UIOrderTypeLookup, UIOrderTypeValue } from '../types';\n\n// Market order type\nexport const MARKET_ORDER_TYPE_CONFIG: UIOrderTypeValue = {\n\tlabel: 'Market',\n\tvalue: 'market',\n\torderType: OrderType.MARKET,\n\tdescription:\n\t\t'A Market Order is an order to buy or sell an asset immediately at the current Market Price. Users can set a maximum slippage tolerance.',\n};\n\n// Limit order type\nexport const LIMIT_ORDER_TYPE_CONFIG: UIOrderTypeValue = {\n\tlabel: 'Limit',\n\tvalue: 'limit',\n\torderType: OrderType.LIMIT,\n\tdescription:\n\t\t'A Limit Order is an order to buy or sell a given asset at a specified price. Limit Orders are triggered once Oracle Price reaches the specified price.',\n};\n\n// Stop Market order type\nexport const STOP_MARKET_ORDER_TYPE_CONFIG: UIOrderTypeValue = {\n\tlabel: 'Stop Market',\n\tvalue: 'stopMarket',\n\torderType: OrderType.TRIGGER_MARKET,\n\tdescription:\n\t\t'A Stop Market Order is an order to close the position of a given asset if its specified Trigger Price is reached. If this happens, the position is closed at Market Price.',\n};\n\n// Stop Limit order type\nexport const STOP_LIMIT_ORDER_TYPE_CONFIG: UIOrderTypeValue = {\n\tlabel: 'Stop Limit',\n\tvalue: 'stopLimit',\n\torderType: OrderType.TRIGGER_LIMIT,\n\tdescription:\n\t\t'A Stop Limit Order will only execute where the specified Trigger Price of a given asset is reached. If this happens, a Limit Order at the specified Limit Price will be placed.',\n};\n\n// Take Profit Market order type\nexport const TAKE_PROFIT_MARKET_ORDER_TYPE_CONFIG: UIOrderTypeValue = {\n\tlabel: 'TP Market',\n\tvalue: 'takeProfitMarket',\n\torderType: OrderType.TRIGGER_MARKET,\n\tdescription:\n\t\t'A Take Profit Order is an order to close the position of a given asset if its Oracle Price reaches the specified Trigger Price. If this happens, the position is closed at Market Price.',\n};\n\n// Take Profit Limit order type\nexport const TAKE_PROFIT_LIMIT_ORDER_TYPE_CONFIG: UIOrderTypeValue = {\n\tlabel: 'TP Limit',\n\tvalue: 'takeProfitLimit',\n\torderType: OrderType.TRIGGER_LIMIT,\n\tdescription:\n\t\t'A Take Profit Limit Order will only execute where the Oracle Price of a given asset reaches the Trigger Price. If this happens, a Limit Order at the specified Limit Price will be placed.',\n};\n\n// Oracle Market order type\nexport const ORACLE_MARKET_ORDER_TYPE_CONFIG: UIOrderTypeValue = {\n\tlabel: 'Oracle Market',\n\tvalue: 'oracle',\n\torderType: OrderType.ORACLE,\n};\n\n// Oracle Limit order type\nexport const ORACLE_LIMIT_ORDER_TYPE_CONFIG: UIOrderTypeValue = {\n\tlabel: 'Oracle Limit',\n\tvalue: 'oracleLimit',\n\torderType: OrderType.LIMIT,\n\tdescription:\n\t\t'An Oracle Limit Order allows you to specify an offset rather than limit price to execute your order. The offset represents the price above/below the current Oracle Price you want to be filled at. Learn more.',\n};\n\n// Scaled Orders order type\nexport const SCALED_ORDERS_ORDER_TYPE_CONFIG: UIOrderTypeValue = {\n\tlabel: 'Scale',\n\tvalue: 'scaledOrders',\n\torderType: OrderType.LIMIT,\n\tdescription:\n\t\t'A scaled order automatically generates multiple limit orders within a specified price range. It splits the order amount into several suborders and places them separately without significantly impacting the market.',\n};\n\nexport const UI_ORDER_TYPES: UIOrderTypeLookup = {\n\tmarket: MARKET_ORDER_TYPE_CONFIG,\n\tlimit: LIMIT_ORDER_TYPE_CONFIG,\n\tstopMarket: STOP_MARKET_ORDER_TYPE_CONFIG,\n\tstopLimit: STOP_LIMIT_ORDER_TYPE_CONFIG,\n\ttakeProfitMarket: TAKE_PROFIT_MARKET_ORDER_TYPE_CONFIG,\n\ttakeProfitLimit: TAKE_PROFIT_LIMIT_ORDER_TYPE_CONFIG,\n\toracle: ORACLE_MARKET_ORDER_TYPE_CONFIG,\n\toracleLimit: ORACLE_LIMIT_ORDER_TYPE_CONFIG,\n\tscaledOrders: SCALED_ORDERS_ORDER_TYPE_CONFIG,\n};\n\nexport const UI_ORDER_TYPES_LIST = Object.values(UI_ORDER_TYPES);\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { BN, DriftClient, User, PositionDirection } from '@drift-labs/sdk';
|
|
2
2
|
import { PublicKey, TransactionInstruction } from '@solana/web3.js';
|
|
3
|
-
export declare const ISOLATED_POSITION_DEPOSIT_BUFFER_BPS =
|
|
3
|
+
export declare const ISOLATED_POSITION_DEPOSIT_BUFFER_BPS = 15;
|
|
4
4
|
export interface IsolatedMarginShortfall {
|
|
5
5
|
marketIndex: number;
|
|
6
6
|
shortfall: BN;
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.getIsolatedPositionDepositIxIfNeeded = exports.computeIsolatedPositionDepositForTrade = exports.getTotalIsolatedMarginShortfall = exports.getOtherIsolatedMarginShortfalls = exports.getIsolatedMarginShortfall = exports.getIsolatedMarginShortfalls = exports.ISOLATED_POSITION_DEPOSIT_BUFFER_BPS = void 0;
|
|
4
4
|
const sdk_1 = require("@drift-labs/sdk");
|
|
5
|
-
exports.ISOLATED_POSITION_DEPOSIT_BUFFER_BPS =
|
|
5
|
+
exports.ISOLATED_POSITION_DEPOSIT_BUFFER_BPS = 15;
|
|
6
6
|
/**
|
|
7
7
|
* Computes the initial margin shortfall for all isolated perp positions.
|
|
8
8
|
* Returns a map of marketIndex -> shortfall (in QUOTE_PRECISION).
|
|
@@ -41,7 +41,8 @@ function getOtherIsolatedMarginShortfalls(user, excludeMarketIndex) {
|
|
|
41
41
|
const shortfalls = getIsolatedMarginShortfalls(user);
|
|
42
42
|
const result = [];
|
|
43
43
|
for (const [marketIndex, shortfall] of shortfalls) {
|
|
44
|
-
if (excludeMarketIndex !== undefined &&
|
|
44
|
+
if (excludeMarketIndex !== undefined &&
|
|
45
|
+
marketIndex === excludeMarketIndex) {
|
|
45
46
|
continue;
|
|
46
47
|
}
|
|
47
48
|
result.push({ marketIndex, shortfall });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"isolatedPositionDeposit.js","sourceRoot":"","sources":["../../../../../../src/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.ts"],"names":[],"mappings":";;;AAAA,yCAUyB;AAGZ,QAAA,oCAAoC,GAAG,EAAE,CAAC;AAOvD;;;;GAIG;AACH,SAAgB,2BAA2B,CAAC,IAAU;IACrD,MAAM,UAAU,GAAG,IAAI,GAAG,EAAc,CAAC;IAEzC,MAAM,UAAU,GAAG,IAAI,CAAC,oBAAoB,CAAC,SAAS,CAAC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AG,CACjB,IAAI,QAAE,CAAC,iBAAiB,aAAjB,iBAAiB,cAAjB,iBAAiB,GAAI,4CAAoC,CAAC,CACjE,CACD,CAAC,CAAC,yBAAyB;IAE5B,sDAAsD;IACtD,IAAI,wBAAwB,EAAE,CAAC;QAC9B,MAAM,iBAAiB,GAAG,0BAA0B,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;QACxE,IAAI,iBAAiB,CAAC,EAAE,CAAC,UAAI,CAAC,EAAE,CAAC;YAChC,6DAA6D;YAC7D,MAAM,mBAAmB,GAAG,iBAAiB,CAAC,GAAG,CAChD,iBAAiB,CAAC,GAAG,CACpB,IAAI,QAAE,CAAC,iBAAiB,aAAjB,iBAAiB,cAAjB,iBAAiB,GAAI,4CAAoC,CAAC,CACjE,CACD,CAAC;YACF,aAAa,GAAG,aAAa,CAAC,GAAG,CAAC,mBAAmB,CAAC,CAAC;QACxD,CAAC;IACF,CAAC;IAED,OAAO,aAAa,CAAC;AACtB,CAAC;AAnED,wFAmEC;AAEM,KAAK,UAAU,oCAAoC,CACzD,WAAwB,EACxB,IAAU,EACV,WAAmB,EACnB,uBAA4B,EAC5B,gBAA4B;IAE5B,IAAI,CAAC,uBAAuB,EAAE,CAAC;QAC9B,OAAO,SAAS,CAAC;IAClB,CAAC;IACD,IAAI,uBAAuB,CAAC,MAAM,EAAE,EAAE,CAAC;QACtC,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,OAAO,WAAW,CAAC,wCAAwC,CAC1D,uBAAuB,EACvB,WAAW,EACX,IAAI,CAAC,cAAc,EAAE,CAAC,YAAY,EAClC,SAAS,EAAE,iBAAiB;IAC5B,gBAAgB,CAChB,CAAC;AACH,CAAC;AArBD,oFAqBC","sourcesContent":["import {\n\tBN,\n\tDriftClient,\n\tUser,\n\tcalculateMarginUSDCRequiredForTrade,\n\tOptionalOrderParams,\n\tPositionDirection,\n\tMarketType,\n\tOrderType,\n\tZERO,\n} from '@drift-labs/sdk';\nimport { PublicKey, TransactionInstruction } from '@solana/web3.js';\n\nexport const ISOLATED_POSITION_DEPOSIT_BUFFER_BPS = 20;\n\nexport interface IsolatedMarginShortfall {\n\tmarketIndex: number;\n\tshortfall: BN;\n}\n\n/**\n * Computes the initial margin shortfall for all isolated perp positions.\n * Returns a map of marketIndex -> shortfall (in QUOTE_PRECISION).\n * Only includes positions that are under initial margin (shortfall > 0).\n */\nexport function getIsolatedMarginShortfalls(user: User): Map<number, BN> {\n\tconst shortfalls = new Map<number, BN>();\n\n\tconst marginCalc = user.getMarginCalculation('Initial');\n\n\tfor (const [\n\t\tmarketIndex,\n\t\tisolatedCalc,\n\t] of marginCalc.isolatedMarginCalculations) {\n\t\tconst shortfall = isolatedCalc.marginShortage();\n\t\tif (shortfall.gt(ZERO)) {\n\t\t\tshortfalls.set(marketIndex, shortfall);\n\t\t}\n\t}\n\n\treturn shortfalls;\n}\n\n/**\n * Computes the initial margin shortfall for a single isolated perp position.\n * Returns the shortfall in QUOTE_PRECISION, or ZERO if no shortfall.\n */\nexport function getIsolatedMarginShortfall(\n\tuser: User,\n\tmarketIndex: number\n): BN {\n\tconst marginCalc = user.getMarginCalculation('Initial');\n\tconst isolatedCalc = marginCalc.isolatedMarginCalculations.get(marketIndex);\n\n\tif (!isolatedCalc) {\n\t\treturn ZERO;\n\t}\n\n\treturn isolatedCalc.marginShortage();\n}\n\n/**\n * Returns all isolated margin shortfalls as an array, excluding a specific market index.\n * Useful for getting shortfalls for \"other\" isolated positions.\n */\nexport function getOtherIsolatedMarginShortfalls(\n\tuser: User,\n\texcludeMarketIndex?: number\n): IsolatedMarginShortfall[] {\n\tconst shortfalls = getIsolatedMarginShortfalls(user);\n\tconst result: IsolatedMarginShortfall[] = [];\n\n\tfor (const [marketIndex, shortfall] of shortfalls) {\n\t\tif (excludeMarketIndex !== undefined && marketIndex === excludeMarketIndex) {\n\t\t\tcontinue;\n\t\t}\n\t\tresult.push({ marketIndex, shortfall });\n\t}\n\n\treturn result;\n}\n\n/**\n * Computes the total of all isolated margin shortfalls.\n */\nexport function getTotalIsolatedMarginShortfall(\n\tuser: User,\n\texcludeMarketIndex?: number\n): BN {\n\tconst shortfalls = getOtherIsolatedMarginShortfalls(user, excludeMarketIndex);\n\treturn shortfalls.reduce((acc, s) => acc.add(s.shortfall), ZERO);\n}\n\nexport interface ComputeIsolatedPositionDepositParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tmarketIndex: number;\n\tbaseAssetAmount: BN;\n\t/**\n\t * Optional direction of the order.\n\t * If provided, we will check if the order will increase the position.\n\t * If the order will not increase the position, we will return 0.\n\t */\n\tdirection?: PositionDirection;\n\t/**\n\t * Margin ratio to use for the position (e.g. 2000 for 5x leverage).\n\t */\n\tmarginRatio: number;\n\t/**\n\t * Optional estimated entry price to use for the margin calculation.\n\t */\n\tentryPrice?: BN;\n\t/**\n\t * Number of open high leverage spots available to the user (if any).\n\t * If greater than 0, we will consider the trade as entering high leverage mode.\n\t */\n\tnumOfOpenHighLeverageSpots?: number;\n\t/**\n\t * Optional buffer denominator for the isolated position deposit.\n\t * \n\t * Smaller numbers mean a bigger buffer.\n\t * \n\t * bufferDenominator -> Buffer %\n\t * \n\t * 15 -> 6.67%\n\t * \n\t * 20 (default) -> 5.00%\n\t * \n\t * 50 -> 2.00%\n\t * \n\t * 100 -> 1.00%\n\t * \n\t * 180 -> 0.56%\n\t * \n\t * 200 -> 0.50%\n\t */\n\tbufferDenominator?: number;\n\t/**\n\t * If true, the current market's initial margin shortfall (if any)\n\t * will be added to the deposit amount.\n\t */\n\tincludeExistingShortfall?: boolean;\n}\n\n/**\n * Computes the isolated position deposit required for opening an isolated perp position.\n * Returns a BN in QUOTE_PRECISION (USDC).\n */\nexport function computeIsolatedPositionDepositForTrade({\n\tdriftClient,\n\tuser,\n\tmarketIndex,\n\tbaseAssetAmount,\n\tdirection,\n\tmarginRatio,\n\tentryPrice,\n\tnumOfOpenHighLeverageSpots,\n\tbufferDenominator,\n\tincludeExistingShortfall,\n}: ComputeIsolatedPositionDepositParams): BN | null {\n\t// Only require isolated deposit if the order will increase the position (when direction is provided)\n\tif (direction !== undefined) {\n\t\tconst maybeOrderParams: OptionalOrderParams = {\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\torderType: OrderType.MARKET,\n\t\t\tdirection,\n\t\t\tbaseAssetAmount,\n\t\t};\n\t\tconst subAccountId = user.getUserAccount().subAccountId;\n\t\tconst isIncreasing = driftClient.isOrderIncreasingPosition(\n\t\t\tmaybeOrderParams,\n\t\t\tsubAccountId\n\t\t);\n\t\tif (!isIncreasing) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tconst userIsInHighLeverageMode = user.isHighLeverageMode('Initial') ?? false;\n\tconst hasOpenHighLeverageSpots =\n\t\tnumOfOpenHighLeverageSpots !== undefined && numOfOpenHighLeverageSpots > 0;\n\tconst enteringHighLeverageMode =\n\t\tuserIsInHighLeverageMode || hasOpenHighLeverageSpots;\n\n\tconst marginRequired = calculateMarginUSDCRequiredForTrade(\n\t\tdriftClient,\n\t\tmarketIndex,\n\t\tbaseAssetAmount,\n\t\tmarginRatio,\n\t\tenteringHighLeverageMode,\n\t\tentryPrice\n\t);\n\n\tlet depositAmount = marginRequired.add(\n\t\tmarginRequired.div(\n\t\t\tnew BN(bufferDenominator ?? ISOLATED_POSITION_DEPOSIT_BUFFER_BPS)\n\t\t)\n\t); // buffer in basis points\n\n\t// Add existing shortfall for this market if requested\n\tif (includeExistingShortfall) {\n\t\tconst existingShortfall = getIsolatedMarginShortfall(user, marketIndex);\n\t\tif (existingShortfall.gt(ZERO)) {\n\t\t\t// Add shortfall with a 5% buffer on top (same as new margin)\n\t\t\tconst shortfallWithBuffer = existingShortfall.add(\n\t\t\t\texistingShortfall.div(\n\t\t\t\t\tnew BN(bufferDenominator ?? ISOLATED_POSITION_DEPOSIT_BUFFER_BPS)\n\t\t\t\t)\n\t\t\t);\n\t\t\tdepositAmount = depositAmount.add(shortfallWithBuffer);\n\t\t}\n\t}\n\n\treturn depositAmount;\n}\n\nexport async function getIsolatedPositionDepositIxIfNeeded(\n\tdriftClient: DriftClient,\n\tuser: User,\n\tmarketIndex: number,\n\tisolatedPositionDeposit?: BN,\n\tsigningAuthority?: PublicKey\n): Promise<TransactionInstruction | undefined> {\n\tif (!isolatedPositionDeposit) {\n\t\treturn undefined;\n\t}\n\tif (isolatedPositionDeposit.isZero()) {\n\t\treturn undefined;\n\t}\n\n\treturn driftClient.getTransferIsolatedPerpPositionDepositIx(\n\t\tisolatedPositionDeposit,\n\t\tmarketIndex,\n\t\tuser.getUserAccount().subAccountId,\n\t\tundefined, // noAmountBuffer\n\t\tsigningAuthority\n\t);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"isolatedPositionDeposit.js","sourceRoot":"","sources":["../../../../../../src/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.ts"],"names":[],"mappings":";;;AAAA,yCAUyB;AAGZ,QAAA,oCAAoC,GAAG,EAAE,CAAC;AAOvD;;;;GAIG;AACH,SAAgB,2BAA2B,CAAC,IAAU;IACrD,MAAM,UAAU,GAAG,IAAI,GAAG,EAAc,CAAC;IAEzC,MAAM,UAAU,GAAG,IAAI,CAAC,oBAAoB,CAAC,SAAS,CAAC,CAAC;IAExD,KAAK,MAAM,CACV,WAAW,EACX,YAAY,EACZ,IAAI,UAAU,CAAC,0BAA0B,EAAE,CAAC;QAC5C,MAAM,SAAS,GAAG,YAAY,CAAC,cAAc,EAAE,CAAC;QAChD,IAAI,SAAS,CAAC,EAAE,CAAC,UAAI,CAAC,EAAE,CAAC;YACxB,UAAU,CAAC,GAAG,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;QACxC,CAAC;IACF,CAAC;IAED,OAAO,UAAU,CAAC;AACnB,CAAC;AAhBD,kEAgBC;AAED;;;GAGG;AACH,SAAgB,0BAA0B,CACzC,IAAU,EACV,WAAmB;IAEnB,MAAM,UAAU,GAAG,IAAI,CAAC,oBAAoB,CAAC,SAAS,CAAC,CAAC;IACx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C,CACjE,CACD,CAAC;YACF,aAAa,GAAG,aAAa,CAAC,GAAG,CAAC,mBAAmB,CAAC,CAAC;QACxD,CAAC;IACF,CAAC;IAED,OAAO,aAAa,CAAC;AACtB,CAAC;AAnED,wFAmEC;AAEM,KAAK,UAAU,oCAAoC,CACzD,WAAwB,EACxB,IAAU,EACV,WAAmB,EACnB,uBAA4B,EAC5B,gBAA4B;IAE5B,IAAI,CAAC,uBAAuB,EAAE,CAAC;QAC9B,OAAO,SAAS,CAAC;IAClB,CAAC;IACD,IAAI,uBAAuB,CAAC,MAAM,EAAE,EAAE,CAAC;QACtC,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,OAAO,WAAW,CAAC,wCAAwC,CAC1D,uBAAuB,EACvB,WAAW,EACX,IAAI,CAAC,cAAc,EAAE,CAAC,YAAY,EAClC,SAAS,EAAE,iBAAiB;IAC5B,gBAAgB,CAChB,CAAC;AACH,CAAC;AArBD,oFAqBC","sourcesContent":["import {\n\tBN,\n\tDriftClient,\n\tUser,\n\tcalculateMarginUSDCRequiredForTrade,\n\tOptionalOrderParams,\n\tPositionDirection,\n\tMarketType,\n\tOrderType,\n\tZERO,\n} from '@drift-labs/sdk';\nimport { PublicKey, TransactionInstruction } from '@solana/web3.js';\n\nexport const ISOLATED_POSITION_DEPOSIT_BUFFER_BPS = 15;\n\nexport interface IsolatedMarginShortfall {\n\tmarketIndex: number;\n\tshortfall: BN;\n}\n\n/**\n * Computes the initial margin shortfall for all isolated perp positions.\n * Returns a map of marketIndex -> shortfall (in QUOTE_PRECISION).\n * Only includes positions that are under initial margin (shortfall > 0).\n */\nexport function getIsolatedMarginShortfalls(user: User): Map<number, BN> {\n\tconst shortfalls = new Map<number, BN>();\n\n\tconst marginCalc = user.getMarginCalculation('Initial');\n\n\tfor (const [\n\t\tmarketIndex,\n\t\tisolatedCalc,\n\t] of marginCalc.isolatedMarginCalculations) {\n\t\tconst shortfall = isolatedCalc.marginShortage();\n\t\tif (shortfall.gt(ZERO)) {\n\t\t\tshortfalls.set(marketIndex, shortfall);\n\t\t}\n\t}\n\n\treturn shortfalls;\n}\n\n/**\n * Computes the initial margin shortfall for a single isolated perp position.\n * Returns the shortfall in QUOTE_PRECISION, or ZERO if no shortfall.\n */\nexport function getIsolatedMarginShortfall(\n\tuser: User,\n\tmarketIndex: number\n): BN {\n\tconst marginCalc = user.getMarginCalculation('Initial');\n\tconst isolatedCalc = marginCalc.isolatedMarginCalculations.get(marketIndex);\n\n\tif (!isolatedCalc) {\n\t\treturn ZERO;\n\t}\n\n\treturn isolatedCalc.marginShortage();\n}\n\n/**\n * Returns all isolated margin shortfalls as an array, excluding a specific market index.\n * Useful for getting shortfalls for \"other\" isolated positions.\n */\nexport function getOtherIsolatedMarginShortfalls(\n\tuser: User,\n\texcludeMarketIndex?: number\n): IsolatedMarginShortfall[] {\n\tconst shortfalls = getIsolatedMarginShortfalls(user);\n\tconst result: IsolatedMarginShortfall[] = [];\n\n\tfor (const [marketIndex, shortfall] of shortfalls) {\n\t\tif (\n\t\t\texcludeMarketIndex !== undefined &&\n\t\t\tmarketIndex === excludeMarketIndex\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tresult.push({ marketIndex, shortfall });\n\t}\n\n\treturn result;\n}\n\n/**\n * Computes the total of all isolated margin shortfalls.\n */\nexport function getTotalIsolatedMarginShortfall(\n\tuser: User,\n\texcludeMarketIndex?: number\n): BN {\n\tconst shortfalls = getOtherIsolatedMarginShortfalls(user, excludeMarketIndex);\n\treturn shortfalls.reduce((acc, s) => acc.add(s.shortfall), ZERO);\n}\n\nexport interface ComputeIsolatedPositionDepositParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tmarketIndex: number;\n\tbaseAssetAmount: BN;\n\t/**\n\t * Optional direction of the order.\n\t * If provided, we will check if the order will increase the position.\n\t * If the order will not increase the position, we will return 0.\n\t */\n\tdirection?: PositionDirection;\n\t/**\n\t * Margin ratio to use for the position (e.g. 2000 for 5x leverage).\n\t */\n\tmarginRatio: number;\n\t/**\n\t * Optional estimated entry price to use for the margin calculation.\n\t */\n\tentryPrice?: BN;\n\t/**\n\t * Number of open high leverage spots available to the user (if any).\n\t * If greater than 0, we will consider the trade as entering high leverage mode.\n\t */\n\tnumOfOpenHighLeverageSpots?: number;\n\t/**\n\t * Optional buffer denominator for the isolated position deposit.\n\t *\n\t * Smaller numbers mean a bigger buffer.\n\t *\n\t * bufferDenominator -> Buffer %\n\t *\n\t * 15 -> 6.67%\n\t *\n\t * 20 (default) -> 5.00%\n\t *\n\t * 50 -> 2.00%\n\t *\n\t * 100 -> 1.00%\n\t *\n\t * 180 -> 0.56%\n\t *\n\t * 200 -> 0.50%\n\t */\n\tbufferDenominator?: number;\n\t/**\n\t * If true, the current market's initial margin shortfall (if any)\n\t * will be added to the deposit amount.\n\t */\n\tincludeExistingShortfall?: boolean;\n}\n\n/**\n * Computes the isolated position deposit required for opening an isolated perp position.\n * Returns a BN in QUOTE_PRECISION (USDC).\n */\nexport function computeIsolatedPositionDepositForTrade({\n\tdriftClient,\n\tuser,\n\tmarketIndex,\n\tbaseAssetAmount,\n\tdirection,\n\tmarginRatio,\n\tentryPrice,\n\tnumOfOpenHighLeverageSpots,\n\tbufferDenominator,\n\tincludeExistingShortfall,\n}: ComputeIsolatedPositionDepositParams): BN | null {\n\t// Only require isolated deposit if the order will increase the position (when direction is provided)\n\tif (direction !== undefined) {\n\t\tconst maybeOrderParams: OptionalOrderParams = {\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\torderType: OrderType.MARKET,\n\t\t\tdirection,\n\t\t\tbaseAssetAmount,\n\t\t};\n\t\tconst subAccountId = user.getUserAccount().subAccountId;\n\t\tconst isIncreasing = driftClient.isOrderIncreasingPosition(\n\t\t\tmaybeOrderParams,\n\t\t\tsubAccountId\n\t\t);\n\t\tif (!isIncreasing) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tconst userIsInHighLeverageMode = user.isHighLeverageMode('Initial') ?? false;\n\tconst hasOpenHighLeverageSpots =\n\t\tnumOfOpenHighLeverageSpots !== undefined && numOfOpenHighLeverageSpots > 0;\n\tconst enteringHighLeverageMode =\n\t\tuserIsInHighLeverageMode || hasOpenHighLeverageSpots;\n\n\tconst marginRequired = calculateMarginUSDCRequiredForTrade(\n\t\tdriftClient,\n\t\tmarketIndex,\n\t\tbaseAssetAmount,\n\t\tmarginRatio,\n\t\tenteringHighLeverageMode,\n\t\tentryPrice\n\t);\n\n\tlet depositAmount = marginRequired.add(\n\t\tmarginRequired.div(\n\t\t\tnew BN(bufferDenominator ?? ISOLATED_POSITION_DEPOSIT_BUFFER_BPS)\n\t\t)\n\t); // buffer in basis points\n\n\t// Add existing shortfall for this market if requested\n\tif (includeExistingShortfall) {\n\t\tconst existingShortfall = getIsolatedMarginShortfall(user, marketIndex);\n\t\tif (existingShortfall.gt(ZERO)) {\n\t\t\t// Add shortfall with a 5% buffer on top (same as new margin)\n\t\t\tconst shortfallWithBuffer = existingShortfall.add(\n\t\t\t\texistingShortfall.div(\n\t\t\t\t\tnew BN(bufferDenominator ?? ISOLATED_POSITION_DEPOSIT_BUFFER_BPS)\n\t\t\t\t)\n\t\t\t);\n\t\t\tdepositAmount = depositAmount.add(shortfallWithBuffer);\n\t\t}\n\t}\n\n\treturn depositAmount;\n}\n\nexport async function getIsolatedPositionDepositIxIfNeeded(\n\tdriftClient: DriftClient,\n\tuser: User,\n\tmarketIndex: number,\n\tisolatedPositionDeposit?: BN,\n\tsigningAuthority?: PublicKey\n): Promise<TransactionInstruction | undefined> {\n\tif (!isolatedPositionDeposit) {\n\t\treturn undefined;\n\t}\n\tif (isolatedPositionDeposit.isZero()) {\n\t\treturn undefined;\n\t}\n\n\treturn driftClient.getTransferIsolatedPerpPositionDepositIx(\n\t\tisolatedPositionDeposit,\n\t\tmarketIndex,\n\t\tuser.getUserAccount().subAccountId,\n\t\tundefined, // noAmountBuffer\n\t\tsigningAuthority\n\t);\n}\n"]}
|
package/lib/types/UIMarket.js
CHANGED
|
@@ -67,7 +67,7 @@ class UIMarket {
|
|
|
67
67
|
if (!marketConfig.category) {
|
|
68
68
|
return false;
|
|
69
69
|
}
|
|
70
|
-
return (_b = (_a = marketConfig.category) === null || _a === void 0 ? void 0 : _a.includes('Prediction')) !== null && _b !== void 0 ? _b : false;
|
|
70
|
+
return ((_b = (_a = marketConfig.category) === null || _a === void 0 ? void 0 : _a.includes('Prediction')) !== null && _b !== void 0 ? _b : false);
|
|
71
71
|
}
|
|
72
72
|
get isSpot() {
|
|
73
73
|
return this.marketId.isSpot;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UIMarket.js","sourceRoot":"","sources":["../../src/types/UIMarket.ts"],"names":[],"mappings":";;;;;;AAAA,yCASyB;AACzB,yCAAsC;AACtC,oEAAuC;AACvC,8CAM4B;AAC5B,kDAA8D;AAC9D,oCAAsC;AACtC,sCAAmC;AAGnC,MAAM,qBAAqB,GAC1B,OAAO,CAAC,GAAG,CAAC,oCAAoC,KAAK,MAAM,CAAC;AAyD7D,MAAa,QAAQ;IAUpB,IAAI,SAAS;QACZ,OAAO,IAAI,CAAC,UAAU,CAAC;IACxB,CAAC;IAED,IAAY,SAAS,CAAC,SAAoB;QACzC,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;IAC7B,CAAC;IAED,YAAqB,WAAmB,EAAW,UAAsB;QAApD,gBAAW,GAAX,WAAW,CAAQ;QAAW,eAAU,GAAV,UAAU,CAAY;QACxE,MAAM,QAAQ,GAAG,IAAI,mBAAQ,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC;QACvD,MAAM,WAAW,GAAG,qBAAqB;YACxC,CAAC,CAAC,QAAQ,CAAC,WAAW;YACtB,CAAC,CAAC,eAAM,CAAC,iBAAiB,CAAC;QAC5B,MAAM,WAAW,GAAG,qBAAqB;YACxC,CAAC,CAAC,QAAQ,CAAC,WAAW;YACtB,CAAC,CAAC,eAAM,CAAC,iBAAiB,CAAC;QAC5B,MAAM,OAAO,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,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CACV,CAAC;gBAC7B,CAAC;gBACD;oBACC,OAAO,YAAY,CAAC,MAAgC,CAAC;YACvD,CAAC;QACF,CAAC;IACF,CAAC;;AA9PF,4BA+PC;AA9PO,oBAAW,GAAG,iBAAW,CAAC,cAAc,CAAC,CAAC;AAC1C,oBAAW,GAAG,iBAAW,CAAC,cAAc,CAAC,CAAC;AAClC,cAAK,GAAG,IAAI,GAAG,EAAoB,CAAC","sourcesContent":["import {\n\tMarketType,\n\tOracleSource,\n\tPerpMarketConfig,\n\tPerpMarkets,\n\tSpotMarkets,\n\tSpotMarketConfig,\n\tBASE_PRECISION,\n\tBASE_PRECISION_EXP,\n} from '@drift-labs/sdk';\nimport { MarketId } from './MarketId';\nimport invariant from 'tiny-invariant';\nimport {\n\tEXPONENT_POOL_ID,\n\tJLP_POOL_ID,\n\tLST_POOL_ID,\n\tMAIN_POOL_ID,\n\tSACRED_POOL_ID,\n} from '../constants/pools';\nimport { USDC_SPOT_MARKET_INDEX } from '../constants/markets';\nimport { ENUM_UTILS } from '../utils';\nimport { Config } from '../Config';\nimport { Opaque } from './utility';\n\nconst useAsyncMarketConfigs =\n\tprocess.env.NEXT_PUBLIC_USE_ASYNC_MARKET_CONFIGS === 'true';\n\n/**\n * MarketSymbol will uniquely identify a market\n */\nexport type MarketSymbol = Opaque<string, 'MarketSymbol'>;\n/**\n * MarketDisplaySymbol is the label for a market that we display to a user\n */\nexport type MarketDisplaySymbol = Opaque<string, 'MarketDisplaySymbol'>;\n/**\n * BaseAssetSymbol is the symbol for the underlying asset for a market\n */\nexport type BaseAssetSymbol = Opaque<string, 'BaseAssetSymbol'>;\n/**\n * BaseAssetDisplaySymbol is the label for the underlying asset for a market that we display to a user\n */\nexport type BaseAssetDisplaySymbol = Opaque<string, 'BaseAssetDisplaySymbol'>;\n\n/**\n * # Examples and explanations of the symbol types:\n *\n * ## MarketSymbol:\n * These are basically just the raw symbols in the market configs.\n * - 1KWEN-PERP\n * - JitoSOL-3\n * - PT-fragSOL-15JUN25-3\n *\n * ## MarketDisplaySymbol:\n * This is the symbol we use to display the market to the user. For SPOT markets it should be the exact same as the BaseAssetDisplaySymbol, but for PERP markets they might be different which is why we have this separate type.\n *\n * - 1KWEN-PERP => 1KWEN-PERP\n * - JitoSOL-3 => JitoSOL\n * - PT-fragSOL-15JUN25-3 => PT-fragSOL-15JUN25\n *\n * ## BaseAssetDisplaySymbol:\n * This is the symbol we use to communicate \"what asset they are holding\". For SPOT markets it should be the same as the MarketDisplaySymbol, but for PERP markets it may be different, for example we show open interest denominated in \"1KWEN\", while the market is \"1KWEN-PERP\".\n *\n * - 1KWEN-PERP => 1KWEN\n * - JitoSOL-3 => JitoSOL\n * - PT-fragSOL-15JUN25-3 => fragSOL\n *\n * ## BaseAssetSymbol:\n * This is the symbol for the underlying asset for a market. I don't believe we will display this anywhere but we use these for example when looking up the market icon to use.\n *\n * - 1KWEN-PERP => WEN\n * - JitoSOL-3 => JitoSOL\n * - PT-fragSOL-15JUN25-3 => PT-fragSOL-15JUN25 (note: PT-fragSOL has an icon different to regular fragSOL, otherwise we would use 'fragSOL' for the base asset symbol)\n */\n\ntype UISymbols = {\n\tmarketSymbol: MarketSymbol;\n\tmarketDisplaySymbol: MarketDisplaySymbol;\n\tbaseAssetSymbol: BaseAssetSymbol;\n\tbaseAssetDisplaySymbol: BaseAssetDisplaySymbol;\n};\n\nexport class UIMarket {\n\tstatic perpMarkets = PerpMarkets['mainnet-beta'];\n\tstatic spotMarkets = SpotMarkets['mainnet-beta'];\n\tprivate static cache = new Map<string, UIMarket>();\n\n\treadonly market: SpotMarketConfig | PerpMarketConfig;\n\treadonly marketId: MarketId;\n\n\tprivate _uiSymbols: UISymbols;\n\n\tget uiSymbols() {\n\t\treturn this._uiSymbols;\n\t}\n\n\tprivate set uiSymbols(uiSymbols: UISymbols) {\n\t\tthis._uiSymbols = uiSymbols;\n\t}\n\n\tconstructor(readonly marketIndex: number, readonly marketType: MarketType) {\n\t\tconst marketId = new MarketId(marketIndex, marketType);\n\t\tconst perpMarkets = useAsyncMarketConfigs\n\t\t\t? UIMarket.perpMarkets\n\t\t\t: Config.perpMarketsLookup;\n\t\tconst spotMarkets = useAsyncMarketConfigs\n\t\t\t? UIMarket.spotMarkets\n\t\t\t: Config.spotMarketsLookup;\n\t\tconst markets = marketId.isPerp ? perpMarkets : spotMarkets;\n\n\t\t//@ts-ignore\n\t\tconst market = markets.find((m) => m.marketIndex === marketIndex);\n\n\t\t// TODO: should we purposely throw an error here? Or construct a default market?\n\t\tinvariant(\n\t\t\tmarket,\n\t\t\t`Market not found for type: ${marketId.marketTypeStr}, market index: ${marketIndex}`\n\t\t);\n\n\t\tthis.marketId = marketId;\n\t\tthis.market = market;\n\n\t\tthis.setUiSymbols();\n\t}\n\n\tstatic setPerpMarkets(perpMarkets: PerpMarketConfig[]) {\n\t\tthis.perpMarkets = perpMarkets;\n\t}\n\n\tstatic setSpotMarkets(spotMarkets: SpotMarketConfig[]) {\n\t\tthis.spotMarkets = spotMarkets;\n\t}\n\n\tprivate static getOrCreate(marketIndex: number, marketType: MarketType) {\n\t\tconst key = MarketId.key(marketIndex, marketType);\n\t\tif (UIMarket.cache.has(key)) {\n\t\t\treturn UIMarket.cache.get(key)!;\n\t\t}\n\t\tconst market = new UIMarket(marketIndex, marketType);\n\t\tUIMarket.cache.set(key, market);\n\t\treturn market;\n\t}\n\n\tstatic createSpotMarket(marketIndex: number) {\n\t\treturn UIMarket.getOrCreate(marketIndex, MarketType.SPOT);\n\t}\n\n\tstatic createPerpMarket(marketIndex: number) {\n\t\treturn UIMarket.getOrCreate(marketIndex, MarketType.PERP);\n\t}\n\n\tstatic fromMarketId(marketId: MarketId) {\n\t\treturn UIMarket.getOrCreate(marketId.marketIndex, marketId.marketType);\n\t}\n\n\tstatic checkIsPredictionMarket(marketConfig: PerpMarketConfig) {\n\t\tif (!(marketConfig as PerpMarketConfig).category) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn (marketConfig as PerpMarketConfig).category?.includes('Prediction') ?? false;\n\t}\n\n\tget isSpot() {\n\t\treturn this.marketId.isSpot;\n\t}\n\n\tget isPerp() {\n\t\treturn this.marketId.isPerp;\n\t}\n\n\tget marketTypeStr() {\n\t\treturn this.marketId.marketTypeStr;\n\t}\n\n\tget key() {\n\t\treturn this.marketId.key;\n\t}\n\n\t// @deprecated : Use uiSymbols.marketDisplaySymbol instead\n\tget marketName() {\n\t\treturn `${this.market.symbol}${this.isSpot ? '/USDC' : ''}`;\n\t}\n\n\t// @deprecated : Use uiSymbols.marketSymbol instead\n\tget symbol() {\n\t\treturn this.market.symbol;\n\t}\n\n\tget isUsdcMarket() {\n\t\treturn this.isSpot && this.marketIndex === USDC_SPOT_MARKET_INDEX;\n\t}\n\n\tget isStableCoinMarket() {\n\t\treturn (\n\t\t\tthis.isSpot &&\n\t\t\tENUM_UTILS.match(this.market.oracleSource, OracleSource.PYTH_STABLE_COIN)\n\t\t);\n\t}\n\n\tget isPredictionMarket() {\n\t\treturn (\n\t\t\tthis.isPerp &&\n\t\t\tUIMarket.checkIsPredictionMarket(this.market as PerpMarketConfig)\n\t\t);\n\t}\n\n\tget precision() {\n\t\tif (this.marketId.isPerp) {\n\t\t\treturn BASE_PRECISION;\n\t\t} else {\n\t\t\treturn (this.market as SpotMarketConfig).precision;\n\t\t}\n\t}\n\n\tget precisionExp() {\n\t\tif (this.marketId.isPerp) {\n\t\t\treturn BASE_PRECISION_EXP;\n\t\t} else {\n\t\t\treturn (this.market as SpotMarketConfig).precisionExp;\n\t\t}\n\t}\n\n\tequals(other: UIMarket) {\n\t\treturn this.marketId.equals(other.marketId);\n\t}\n\n\t// @deprecated : Use uiSymbols.baseAssetSymbol instead\n\tbaseAssetSymbol(removePrefix = false) {\n\t\tlet baseAssetSymbol = this.isPerp\n\t\t\t? (this.market as PerpMarketConfig).baseAssetSymbol\n\t\t\t: this.market.symbol;\n\n\t\tif (removePrefix) {\n\t\t\tbaseAssetSymbol = baseAssetSymbol.replace('1K', '').replace('1M', '');\n\t\t}\n\n\t\treturn baseAssetSymbol;\n\t}\n\n\tprotected setUiSymbols() {\n\t\tinvariant(this.marketId, 'MarketId not set');\n\n\t\tconst marketSymbol = this.getMarketSymbol();\n\t\tconst marketDisplaySymbol = this.getMarketDisplaySymbol();\n\t\tconst baseAssetSymbol = this.getBaseAssetSymbol();\n\t\tconst baseAssetDisplaySymbol = this.getBaseAssetDisplaySymbol();\n\n\t\tthis.uiSymbols = {\n\t\t\tmarketSymbol,\n\t\t\tmarketDisplaySymbol,\n\t\t\tbaseAssetSymbol,\n\t\t\tbaseAssetDisplaySymbol,\n\t\t};\n\t}\n\n\tprivate getMarketSymbol(): MarketSymbol {\n\t\tif (this.marketId.isPerp) {\n\t\t\treturn this.market.symbol as MarketSymbol;\n\t\t} else {\n\t\t\treturn this.market.symbol as MarketSymbol;\n\t\t}\n\t}\n\n\tprivate getMarketDisplaySymbol(): MarketDisplaySymbol {\n\t\tif (this.marketId.isPerp) {\n\t\t\treturn this.market.symbol as MarketDisplaySymbol;\n\t\t} else {\n\t\t\tconst marketConfig = this.market as SpotMarketConfig;\n\t\t\tswitch (marketConfig.poolId) {\n\t\t\t\tcase MAIN_POOL_ID:\n\t\t\t\t\treturn marketConfig.symbol as MarketDisplaySymbol;\n\t\t\t\tcase JLP_POOL_ID:\n\t\t\t\t\treturn `${marketConfig.symbol.split('-')[0]}` as MarketDisplaySymbol;\n\t\t\t\tcase LST_POOL_ID:\n\t\t\t\t\treturn `${marketConfig.symbol.split('-')[0]}` as MarketDisplaySymbol;\n\t\t\t\tcase EXPONENT_POOL_ID: {\n\t\t\t\t\t/*\n\t\t\t\t\tExample market symbol conversions:\n\t\t\t\t\tPT-fragSOL-15JUN25-3 => PT-fragSOL-15JUN25\n\t\t\t\t\tPT-kySOL-10JUL25-3 => PT-kySOL-10JUL25\n\t\t\t\t\tJitoSOL-3 => JitoSOL\n\t\t\t\t\tJTO-3 => JTO\n\t\t\t\t*/\n\t\t\t\t\treturn (\n\t\t\t\t\t\tmarketConfig.symbol.startsWith('PT-')\n\t\t\t\t\t\t\t? marketConfig.symbol.slice(\n\t\t\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\t\t\tmarketConfig.symbol.lastIndexOf('-')\n\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t: marketConfig.symbol.split('-')[0]\n\t\t\t\t\t) as MarketDisplaySymbol;\n\t\t\t\t}\n\t\t\t\tcase SACRED_POOL_ID:\n\t\t\t\t\treturn `${marketConfig.symbol.split('-')[0]}` as MarketDisplaySymbol;\n\t\t\t\tdefault:\n\t\t\t\t\treturn marketConfig.symbol as MarketDisplaySymbol;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate getBaseAssetSymbol(): BaseAssetSymbol {\n\t\tif (this.marketId.isPerp) {\n\t\t\treturn (this.market as PerpMarketConfig).baseAssetSymbol\n\t\t\t\t.replace('1K', '')\n\t\t\t\t.replace('1M', '') as BaseAssetSymbol;\n\t\t} else {\n\t\t\treturn this.getMarketDisplaySymbol() as unknown as BaseAssetSymbol; // Currently no cases where SPOT baseAssetSymbol is different from marketDisplaySymbol\n\t\t}\n\t}\n\n\tprivate getBaseAssetDisplaySymbol(): BaseAssetDisplaySymbol {\n\t\tif (this.marketId.isPerp) {\n\t\t\treturn (this.market as PerpMarketConfig)\n\t\t\t\t.baseAssetSymbol as BaseAssetDisplaySymbol;\n\t\t} else {\n\t\t\tconst marketConfig = this.market as SpotMarketConfig;\n\t\t\tswitch (marketConfig.poolId) {\n\t\t\t\tcase EXPONENT_POOL_ID: {\n\t\t\t\t\t/*\n\t\t\t\t\tExample market symbol conversions:\n\t\t\t\t\tPT-fragSOL-15JUN25-3 => fragSOL\n\t\t\t\t\tPT-kySOL-10JUL25-3 => kySOL\n\t\t\t\t\tJitoSOL-3 => JitoSOL\n\t\t\t\t\tJTO-3 => JTO\n\t\t\t\t*/\n\t\t\t\t\treturn (\n\t\t\t\t\t\tmarketConfig.symbol.startsWith('PT-')\n\t\t\t\t\t\t\t? marketConfig.symbol.split('-')[1]\n\t\t\t\t\t\t\t: marketConfig.symbol.split('-')[0]\n\t\t\t\t\t) as BaseAssetDisplaySymbol;\n\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\treturn marketConfig.symbol as BaseAssetDisplaySymbol;\n\t\t\t}\n\t\t}\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"UIMarket.js","sourceRoot":"","sources":["../../src/types/UIMarket.ts"],"names":[],"mappings":";;;;;;AAAA,yCASyB;AACzB,yCAAsC;AACtC,oEAAuC;AACvC,8CAM4B;AAC5B,kDAA8D;AAC9D,oCAAsC;AACtC,sCAAmC;AAGnC,MAAM,qBAAqB,GAC1B,OAAO,CAAC,GAAG,CAAC,oCAAoC,KAAK,MAAM,CAAC;AAyD7D,MAAa,QAAQ;IAUpB,IAAI,SAAS;QACZ,OAAO,IAAI,CAAC,UAAU,CAAC;IACxB,CAAC;IAED,IAAY,SAAS,CAAC,SAAoB;QACzC,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;IAC7B,CAAC;IAED,YAAqB,WAAmB,EAAW,UAAsB;QAApD,gBAAW,GAAX,WAAW,CAAQ;QAAW,eAAU,GAAV,UAAU,CAAY;QACxE,MAAM,QAAQ,GAAG,IAAI,mBAAQ,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC;QACvD,MAAM,WAAW,GAAG,qBAAqB;YACxC,CAAC,CAAC,QAAQ,CAAC,WAAW;YACtB,CAAC,CAAC,eAAM,CAAC,iBAAiB,CAAC;QAC5B,MAAM,WAAW,GAAG,qBAAqB;YACxC,CAAC,CAAC,QAAQ,CAAC,WAAW;YACtB,CAAC,CAAC,eAAM,CAAC,iBAAiB,CAAC;QAC5B,MAAM,OAAO,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,WAAW,CAAC;QAE5D,YAAY;QACZ,MAAM,MAAM,GAAG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AAC;YACvD,CAAC;QACF,CAAC;IACF,CAAC;;AAjQF,4BAkQC;AAjQO,oBAAW,GAAG,iBAAW,CAAC,cAAc,CAAC,CAAC;AAC1C,oBAAW,GAAG,iBAAW,CAAC,cAAc,CAAC,CAAC;AAClC,cAAK,GAAG,IAAI,GAAG,EAAoB,CAAC","sourcesContent":["import {\n\tMarketType,\n\tOracleSource,\n\tPerpMarketConfig,\n\tPerpMarkets,\n\tSpotMarkets,\n\tSpotMarketConfig,\n\tBASE_PRECISION,\n\tBASE_PRECISION_EXP,\n} from '@drift-labs/sdk';\nimport { MarketId } from './MarketId';\nimport invariant from 'tiny-invariant';\nimport {\n\tEXPONENT_POOL_ID,\n\tJLP_POOL_ID,\n\tLST_POOL_ID,\n\tMAIN_POOL_ID,\n\tSACRED_POOL_ID,\n} from '../constants/pools';\nimport { USDC_SPOT_MARKET_INDEX } from '../constants/markets';\nimport { ENUM_UTILS } from '../utils';\nimport { Config } from '../Config';\nimport { Opaque } from './utility';\n\nconst useAsyncMarketConfigs =\n\tprocess.env.NEXT_PUBLIC_USE_ASYNC_MARKET_CONFIGS === 'true';\n\n/**\n * MarketSymbol will uniquely identify a market\n */\nexport type MarketSymbol = Opaque<string, 'MarketSymbol'>;\n/**\n * MarketDisplaySymbol is the label for a market that we display to a user\n */\nexport type MarketDisplaySymbol = Opaque<string, 'MarketDisplaySymbol'>;\n/**\n * BaseAssetSymbol is the symbol for the underlying asset for a market\n */\nexport type BaseAssetSymbol = Opaque<string, 'BaseAssetSymbol'>;\n/**\n * BaseAssetDisplaySymbol is the label for the underlying asset for a market that we display to a user\n */\nexport type BaseAssetDisplaySymbol = Opaque<string, 'BaseAssetDisplaySymbol'>;\n\n/**\n * # Examples and explanations of the symbol types:\n *\n * ## MarketSymbol:\n * These are basically just the raw symbols in the market configs.\n * - 1KWEN-PERP\n * - JitoSOL-3\n * - PT-fragSOL-15JUN25-3\n *\n * ## MarketDisplaySymbol:\n * This is the symbol we use to display the market to the user. For SPOT markets it should be the exact same as the BaseAssetDisplaySymbol, but for PERP markets they might be different which is why we have this separate type.\n *\n * - 1KWEN-PERP => 1KWEN-PERP\n * - JitoSOL-3 => JitoSOL\n * - PT-fragSOL-15JUN25-3 => PT-fragSOL-15JUN25\n *\n * ## BaseAssetDisplaySymbol:\n * This is the symbol we use to communicate \"what asset they are holding\". For SPOT markets it should be the same as the MarketDisplaySymbol, but for PERP markets it may be different, for example we show open interest denominated in \"1KWEN\", while the market is \"1KWEN-PERP\".\n *\n * - 1KWEN-PERP => 1KWEN\n * - JitoSOL-3 => JitoSOL\n * - PT-fragSOL-15JUN25-3 => fragSOL\n *\n * ## BaseAssetSymbol:\n * This is the symbol for the underlying asset for a market. I don't believe we will display this anywhere but we use these for example when looking up the market icon to use.\n *\n * - 1KWEN-PERP => WEN\n * - JitoSOL-3 => JitoSOL\n * - PT-fragSOL-15JUN25-3 => PT-fragSOL-15JUN25 (note: PT-fragSOL has an icon different to regular fragSOL, otherwise we would use 'fragSOL' for the base asset symbol)\n */\n\ntype UISymbols = {\n\tmarketSymbol: MarketSymbol;\n\tmarketDisplaySymbol: MarketDisplaySymbol;\n\tbaseAssetSymbol: BaseAssetSymbol;\n\tbaseAssetDisplaySymbol: BaseAssetDisplaySymbol;\n};\n\nexport class UIMarket {\n\tstatic perpMarkets = PerpMarkets['mainnet-beta'];\n\tstatic spotMarkets = SpotMarkets['mainnet-beta'];\n\tprivate static cache = new Map<string, UIMarket>();\n\n\treadonly market: SpotMarketConfig | PerpMarketConfig;\n\treadonly marketId: MarketId;\n\n\tprivate _uiSymbols: UISymbols;\n\n\tget uiSymbols() {\n\t\treturn this._uiSymbols;\n\t}\n\n\tprivate set uiSymbols(uiSymbols: UISymbols) {\n\t\tthis._uiSymbols = uiSymbols;\n\t}\n\n\tconstructor(readonly marketIndex: number, readonly marketType: MarketType) {\n\t\tconst marketId = new MarketId(marketIndex, marketType);\n\t\tconst perpMarkets = useAsyncMarketConfigs\n\t\t\t? UIMarket.perpMarkets\n\t\t\t: Config.perpMarketsLookup;\n\t\tconst spotMarkets = useAsyncMarketConfigs\n\t\t\t? UIMarket.spotMarkets\n\t\t\t: Config.spotMarketsLookup;\n\t\tconst markets = marketId.isPerp ? perpMarkets : spotMarkets;\n\n\t\t//@ts-ignore\n\t\tconst market = markets.find((m) => m.marketIndex === marketIndex);\n\n\t\t// TODO: should we purposely throw an error here? Or construct a default market?\n\t\tinvariant(\n\t\t\tmarket,\n\t\t\t`Market not found for type: ${marketId.marketTypeStr}, market index: ${marketIndex}`\n\t\t);\n\n\t\tthis.marketId = marketId;\n\t\tthis.market = market;\n\n\t\tthis.setUiSymbols();\n\t}\n\n\tstatic setPerpMarkets(perpMarkets: PerpMarketConfig[]) {\n\t\tthis.perpMarkets = perpMarkets;\n\t}\n\n\tstatic setSpotMarkets(spotMarkets: SpotMarketConfig[]) {\n\t\tthis.spotMarkets = spotMarkets;\n\t}\n\n\tprivate static getOrCreate(marketIndex: number, marketType: MarketType) {\n\t\tconst key = MarketId.key(marketIndex, marketType);\n\t\tif (UIMarket.cache.has(key)) {\n\t\t\treturn UIMarket.cache.get(key)!;\n\t\t}\n\t\tconst market = new UIMarket(marketIndex, marketType);\n\t\tUIMarket.cache.set(key, market);\n\t\treturn market;\n\t}\n\n\tstatic createSpotMarket(marketIndex: number) {\n\t\treturn UIMarket.getOrCreate(marketIndex, MarketType.SPOT);\n\t}\n\n\tstatic createPerpMarket(marketIndex: number) {\n\t\treturn UIMarket.getOrCreate(marketIndex, MarketType.PERP);\n\t}\n\n\tstatic fromMarketId(marketId: MarketId) {\n\t\treturn UIMarket.getOrCreate(marketId.marketIndex, marketId.marketType);\n\t}\n\n\tstatic checkIsPredictionMarket(marketConfig: PerpMarketConfig) {\n\t\tif (!(marketConfig as PerpMarketConfig).category) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn (\n\t\t\t(marketConfig as PerpMarketConfig).category?.includes('Prediction') ??\n\t\t\tfalse\n\t\t);\n\t}\n\n\tget isSpot() {\n\t\treturn this.marketId.isSpot;\n\t}\n\n\tget isPerp() {\n\t\treturn this.marketId.isPerp;\n\t}\n\n\tget marketTypeStr() {\n\t\treturn this.marketId.marketTypeStr;\n\t}\n\n\tget key() {\n\t\treturn this.marketId.key;\n\t}\n\n\t// @deprecated : Use uiSymbols.marketDisplaySymbol instead\n\tget marketName() {\n\t\treturn `${this.market.symbol}${this.isSpot ? '/USDC' : ''}`;\n\t}\n\n\t// @deprecated : Use uiSymbols.marketSymbol instead\n\tget symbol() {\n\t\treturn this.market.symbol;\n\t}\n\n\tget isUsdcMarket() {\n\t\treturn this.isSpot && this.marketIndex === USDC_SPOT_MARKET_INDEX;\n\t}\n\n\tget isStableCoinMarket() {\n\t\treturn (\n\t\t\tthis.isSpot &&\n\t\t\tENUM_UTILS.match(this.market.oracleSource, OracleSource.PYTH_STABLE_COIN)\n\t\t);\n\t}\n\n\tget isPredictionMarket() {\n\t\treturn (\n\t\t\tthis.isPerp &&\n\t\t\tUIMarket.checkIsPredictionMarket(this.market as PerpMarketConfig)\n\t\t);\n\t}\n\n\tget precision() {\n\t\tif (this.marketId.isPerp) {\n\t\t\treturn BASE_PRECISION;\n\t\t} else {\n\t\t\treturn (this.market as SpotMarketConfig).precision;\n\t\t}\n\t}\n\n\tget precisionExp() {\n\t\tif (this.marketId.isPerp) {\n\t\t\treturn BASE_PRECISION_EXP;\n\t\t} else {\n\t\t\treturn (this.market as SpotMarketConfig).precisionExp;\n\t\t}\n\t}\n\n\tequals(other: UIMarket) {\n\t\treturn this.marketId.equals(other.marketId);\n\t}\n\n\t// @deprecated : Use uiSymbols.baseAssetSymbol instead\n\tbaseAssetSymbol(removePrefix = false) {\n\t\tlet baseAssetSymbol = this.isPerp\n\t\t\t? (this.market as PerpMarketConfig).baseAssetSymbol\n\t\t\t: this.market.symbol;\n\n\t\tif (removePrefix) {\n\t\t\tbaseAssetSymbol = baseAssetSymbol.replace('1K', '').replace('1M', '');\n\t\t}\n\n\t\treturn baseAssetSymbol;\n\t}\n\n\tprotected setUiSymbols() {\n\t\tinvariant(this.marketId, 'MarketId not set');\n\n\t\tconst marketSymbol = this.getMarketSymbol();\n\t\tconst marketDisplaySymbol = this.getMarketDisplaySymbol();\n\t\tconst baseAssetSymbol = this.getBaseAssetSymbol();\n\t\tconst baseAssetDisplaySymbol = this.getBaseAssetDisplaySymbol();\n\n\t\tthis.uiSymbols = {\n\t\t\tmarketSymbol,\n\t\t\tmarketDisplaySymbol,\n\t\t\tbaseAssetSymbol,\n\t\t\tbaseAssetDisplaySymbol,\n\t\t};\n\t}\n\n\tprivate getMarketSymbol(): MarketSymbol {\n\t\tif (this.marketId.isPerp) {\n\t\t\treturn this.market.symbol as MarketSymbol;\n\t\t} else {\n\t\t\treturn this.market.symbol as MarketSymbol;\n\t\t}\n\t}\n\n\tprivate getMarketDisplaySymbol(): MarketDisplaySymbol {\n\t\tif (this.marketId.isPerp) {\n\t\t\treturn this.market.symbol as MarketDisplaySymbol;\n\t\t} else {\n\t\t\tconst marketConfig = this.market as SpotMarketConfig;\n\t\t\tswitch (marketConfig.poolId) {\n\t\t\t\tcase MAIN_POOL_ID:\n\t\t\t\t\treturn marketConfig.symbol as MarketDisplaySymbol;\n\t\t\t\tcase JLP_POOL_ID:\n\t\t\t\t\treturn `${marketConfig.symbol.split('-')[0]}` as MarketDisplaySymbol;\n\t\t\t\tcase LST_POOL_ID:\n\t\t\t\t\treturn `${marketConfig.symbol.split('-')[0]}` as MarketDisplaySymbol;\n\t\t\t\tcase EXPONENT_POOL_ID: {\n\t\t\t\t\t/*\n\t\t\t\t\tExample market symbol conversions:\n\t\t\t\t\tPT-fragSOL-15JUN25-3 => PT-fragSOL-15JUN25\n\t\t\t\t\tPT-kySOL-10JUL25-3 => PT-kySOL-10JUL25\n\t\t\t\t\tJitoSOL-3 => JitoSOL\n\t\t\t\t\tJTO-3 => JTO\n\t\t\t\t*/\n\t\t\t\t\treturn (\n\t\t\t\t\t\tmarketConfig.symbol.startsWith('PT-')\n\t\t\t\t\t\t\t? marketConfig.symbol.slice(\n\t\t\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\t\t\tmarketConfig.symbol.lastIndexOf('-')\n\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t: marketConfig.symbol.split('-')[0]\n\t\t\t\t\t) as MarketDisplaySymbol;\n\t\t\t\t}\n\t\t\t\tcase SACRED_POOL_ID:\n\t\t\t\t\treturn `${marketConfig.symbol.split('-')[0]}` as MarketDisplaySymbol;\n\t\t\t\tdefault:\n\t\t\t\t\treturn marketConfig.symbol as MarketDisplaySymbol;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate getBaseAssetSymbol(): BaseAssetSymbol {\n\t\tif (this.marketId.isPerp) {\n\t\t\treturn (this.market as PerpMarketConfig).baseAssetSymbol\n\t\t\t\t.replace('1K', '')\n\t\t\t\t.replace('1M', '') as BaseAssetSymbol;\n\t\t} else {\n\t\t\treturn this.getMarketDisplaySymbol() as unknown as BaseAssetSymbol; // Currently no cases where SPOT baseAssetSymbol is different from marketDisplaySymbol\n\t\t}\n\t}\n\n\tprivate getBaseAssetDisplaySymbol(): BaseAssetDisplaySymbol {\n\t\tif (this.marketId.isPerp) {\n\t\t\treturn (this.market as PerpMarketConfig)\n\t\t\t\t.baseAssetSymbol as BaseAssetDisplaySymbol;\n\t\t} else {\n\t\t\tconst marketConfig = this.market as SpotMarketConfig;\n\t\t\tswitch (marketConfig.poolId) {\n\t\t\t\tcase EXPONENT_POOL_ID: {\n\t\t\t\t\t/*\n\t\t\t\t\tExample market symbol conversions:\n\t\t\t\t\tPT-fragSOL-15JUN25-3 => fragSOL\n\t\t\t\t\tPT-kySOL-10JUL25-3 => kySOL\n\t\t\t\t\tJitoSOL-3 => JitoSOL\n\t\t\t\t\tJTO-3 => JTO\n\t\t\t\t*/\n\t\t\t\t\treturn (\n\t\t\t\t\t\tmarketConfig.symbol.startsWith('PT-')\n\t\t\t\t\t\t\t? marketConfig.symbol.split('-')[1]\n\t\t\t\t\t\t\t: marketConfig.symbol.split('-')[0]\n\t\t\t\t\t) as BaseAssetDisplaySymbol;\n\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\treturn marketConfig.symbol as BaseAssetDisplaySymbol;\n\t\t\t}\n\t\t}\n\t}\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { PerpMarketAccount, SpotMarketAccount } from
|
|
1
|
+
import { PerpMarketAccount, SpotMarketAccount } from '@drift-labs/sdk';
|
|
2
2
|
/**
|
|
3
3
|
* Converts a size and precision exponent to the number of decimals in the size.
|
|
4
4
|
* Size can refer to the step size or the tick size of a market.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"precisions.js","sourceRoot":"","sources":["../../../src/utils/markets/precisions.ts"],"names":[],"mappings":";;;AAAA,
|
|
1
|
+
{"version":3,"file":"precisions.js","sourceRoot":"","sources":["../../../src/utils/markets/precisions.ts"],"names":[],"mappings":";;;AAAA,yCAOyB;AAEzB;;;GAGG;AACI,MAAM,mBAAmB,GAAG,CAAC,IAAQ,EAAE,YAAgB,EAAE,EAAE;IACjE,MAAM,aAAa,GAAG,YAAM,CAAC,IAAI,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC,WAAW,EAAE,CAAC;IACpE,IAAI,aAAa,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QACjC,OAAO,aAAa,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;IAC3C,CAAC;IACD,OAAO,CAAC,CAAC;AACV,CAAC,CAAC;AANW,QAAA,mBAAmB,uBAM9B;AAEK,MAAM,kBAAkB,GAAG,CAAC,iBAAoC,EAAE,EAAE;IAC1E,MAAM,QAAQ,GAAG,iBAAiB,CAAC,GAAG,CAAC,aAAa,CAAC;IACrD,MAAM,QAAQ,GAAG,iBAAiB,CAAC,GAAG,CAAC,aAAa,CAAC;IAErD,OAAO;QACN,gBAAgB,EAAE,IAAA,2BAAmB,EAAC,QAAQ,EAAE,wBAAkB,CAAC;QACnE,gBAAgB,EAAE,IAAA,2BAAmB,EAAC,QAAQ,EAAE,yBAAmB,CAAC;KACpE,CAAC;AACH,CAAC,CAAC;AARW,QAAA,kBAAkB,sBAQ7B;AAEK,MAAM,kBAAkB,GAAG,CAAC,iBAAoC,EAAE,EAAE;IAC1E,MAAM,QAAQ,GAAG,iBAAiB,CAAC,aAAa,CAAC;IACjD,MAAM,QAAQ,GAAG,iBAAiB,CAAC,aAAa,CAAC;IAEjD,OAAO;QACN,gBAAgB,EAAE,IAAA,2BAAmB,EAAC,QAAQ,EAAE,wBAAkB,CAAC;QACnE,gBAAgB,EAAE,IAAA,2BAAmB,EAAC,QAAQ,EAAE,yBAAmB,CAAC;KACpE,CAAC;AACH,CAAC,CAAC;AARW,QAAA,kBAAkB,sBAQ7B","sourcesContent":["import {\n\tBASE_PRECISION_EXP,\n\tBigNum,\n\tBN,\n\tPerpMarketAccount,\n\tQUOTE_PRECISION_EXP,\n\tSpotMarketAccount,\n} from '@drift-labs/sdk';\n\n/**\n * Converts a size and precision exponent to the number of decimals in the size.\n * Size can refer to the step size or the tick size of a market.\n */\nexport const getDecimalsFromSize = (size: BN, precisionExp: BN) => {\n\tconst formattedSize = BigNum.from(size, precisionExp).prettyPrint();\n\tif (formattedSize.includes('.')) {\n\t\treturn formattedSize.split('.')[1].length;\n\t}\n\treturn 0;\n};\n\nexport const getPerpMarketSizes = (perpMarketAccount: PerpMarketAccount) => {\n\tconst stepSize = perpMarketAccount.amm.orderStepSize;\n\tconst tickSize = perpMarketAccount.amm.orderTickSize;\n\n\treturn {\n\t\tstepSizeDecimals: getDecimalsFromSize(stepSize, BASE_PRECISION_EXP),\n\t\ttickSizeDecimals: getDecimalsFromSize(tickSize, QUOTE_PRECISION_EXP),\n\t};\n};\n\nexport const getSpotMarketSizes = (spotMarketAccount: SpotMarketAccount) => {\n\tconst stepSize = spotMarketAccount.orderStepSize;\n\tconst tickSize = spotMarketAccount.orderTickSize;\n\n\treturn {\n\t\tstepSizeDecimals: getDecimalsFromSize(stepSize, BASE_PRECISION_EXP),\n\t\ttickSizeDecimals: getDecimalsFromSize(tickSize, QUOTE_PRECISION_EXP),\n\t};\n};\n"]}
|