@drift-labs/common 1.0.14 → 1.0.17
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/clients/DlobWebsocketClient.d.ts +8 -1
- package/lib/clients/DlobWebsocketClient.js +29 -9
- package/lib/clients/DlobWebsocketClient.js.map +1 -1
- package/lib/clients/candleClient.js +12 -0
- package/lib/clients/candleClient.js.map +1 -1
- package/lib/clients/redisClient.d.ts +1 -0
- package/lib/clients/swiftClient.d.ts +1 -0
- package/lib/clients/swiftClient.js +19 -5
- package/lib/clients/swiftClient.js.map +1 -1
- package/lib/clients/tvFeed.d.ts +4 -1
- package/lib/clients/tvFeed.js +29 -3
- package/lib/clients/tvFeed.js.map +1 -1
- package/lib/common-ui-utils/commonUiUtils.d.ts +22 -3
- package/lib/common-ui-utils/commonUiUtils.js +53 -11
- package/lib/common-ui-utils/commonUiUtils.js.map +1 -1
- package/lib/common-ui-utils/market.d.ts +5 -0
- package/lib/common-ui-utils/market.js +19 -11
- package/lib/common-ui-utils/market.js.map +1 -1
- package/lib/common-ui-utils/order.d.ts +7 -1
- package/lib/common-ui-utils/order.js +9 -9
- package/lib/common-ui-utils/order.js.map +1 -1
- package/lib/common-ui-utils/user.d.ts +5 -0
- package/lib/common-ui-utils/user.js +57 -0
- package/lib/common-ui-utils/user.js.map +1 -1
- package/lib/constants/markets.d.ts +4 -0
- package/lib/constants/markets.js +5 -1
- package/lib/constants/markets.js.map +1 -1
- package/lib/constants/superstake.js.map +1 -1
- package/lib/drift/Drift/clients/AuthorityDrift/DriftL2OrderbookManager.d.ts +1 -1
- package/lib/drift/Drift/clients/AuthorityDrift/DriftL2OrderbookManager.js.map +1 -1
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js +6 -0
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js.map +1 -1
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/types.d.ts +1 -0
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/types.js.map +1 -1
- package/lib/drift/Drift/clients/AuthorityDrift/index.d.ts +1 -1
- package/lib/drift/Drift/clients/AuthorityDrift/index.js.map +1 -1
- package/lib/drift/Drift/clients/CentralServerDrift/index.d.ts +19 -2
- package/lib/drift/Drift/clients/CentralServerDrift/index.js +102 -64
- package/lib/drift/Drift/clients/CentralServerDrift/index.js.map +1 -1
- package/lib/drift/Drift/data/PollingDlob.d.ts +1 -1
- package/lib/drift/Drift/data/PollingDlob.js.map +1 -1
- package/lib/drift/base/actions/perp/settlePnl.d.ts +4 -3
- package/lib/drift/base/actions/perp/settlePnl.js +6 -3
- package/lib/drift/base/actions/perp/settlePnl.js.map +1 -1
- package/lib/drift/base/actions/spot/deposit.d.ts +10 -3
- package/lib/drift/base/actions/spot/deposit.js +22 -7
- package/lib/drift/base/actions/spot/deposit.js.map +1 -1
- package/lib/drift/base/actions/trade/editOrder.d.ts +5 -0
- package/lib/drift/base/actions/trade/editOrder.js +1 -0
- package/lib/drift/base/actions/trade/editOrder.js.map +1 -1
- package/lib/drift/base/actions/trade/index.d.ts +1 -0
- package/lib/drift/base/actions/trade/index.js +1 -0
- package/lib/drift/base/actions/trade/index.js.map +1 -1
- package/lib/drift/base/actions/trade/margin.d.ts +24 -0
- package/lib/drift/base/actions/trade/margin.js +48 -0
- package/lib/drift/base/actions/trade/margin.js.map +1 -0
- package/lib/drift/base/actions/trade/openPerpOrder/auction.d.ts +6 -1
- package/lib/drift/base/actions/trade/openPerpOrder/auction.js +4 -4
- package/lib/drift/base/actions/trade/openPerpOrder/auction.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.d.ts +8 -5
- package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.js +6 -5
- package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.d.ts +13 -5
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js +18 -15
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.d.ts +3 -4
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js +11 -11
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.d.ts +40 -11
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js +49 -15
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/types.d.ts +5 -3
- package/lib/drift/base/actions/trade/openPerpOrder/types.js.map +1 -1
- package/lib/drift/base/actions/trade/swap.d.ts +18 -11
- package/lib/drift/base/actions/trade/swap.js +40 -17
- package/lib/drift/base/actions/trade/swap.js.map +1 -1
- package/lib/drift/base/actions/user/create.d.ts +3 -1
- package/lib/drift/base/actions/user/create.js +21 -7
- package/lib/drift/base/actions/user/create.js.map +1 -1
- package/lib/drift/cli.js +16 -2
- package/lib/drift/cli.js.map +1 -1
- package/lib/drift/utils/auctionParamsResponseMapper.d.ts +2 -1
- package/lib/drift/utils/auctionParamsResponseMapper.js +1 -1
- package/lib/drift/utils/auctionParamsResponseMapper.js.map +1 -1
- package/lib/drift/utils/orderParams.js +1 -1
- package/lib/drift/utils/orderParams.js.map +1 -1
- package/lib/utils/driftEvents.js +18 -2
- package/lib/utils/driftEvents.js.map +1 -1
- package/lib/utils/index.d.ts +1 -0
- package/lib/utils/logger.js +34 -3
- package/lib/utils/logger.js.map +1 -1
- package/lib/utils/orderbook/constants.d.ts +2 -0
- package/lib/utils/orderbook/constants.js +5 -0
- package/lib/utils/orderbook/constants.js.map +1 -0
- package/lib/utils/orderbook/index.d.ts +38 -59
- package/lib/utils/orderbook/index.js +285 -1
- package/lib/utils/orderbook/index.js.map +1 -1
- package/lib/utils/orderbook/types.d.ts +101 -0
- package/lib/utils/orderbook/types.js +9 -0
- package/lib/utils/orderbook/types.js.map +1 -0
- package/lib/utils/signedMsgs.d.ts +1 -1
- package/lib/utils/signedMsgs.js +2 -2
- package/lib/utils/signedMsgs.js.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"user.js","sourceRoot":"","sources":["../../src/common-ui-utils/user.ts"],"names":[],"mappings":";;;AAAA,yCA0ByB;AACzB,oCAAkD;AAClD,uCAA0C;AAC1C,oCAAsC;AAEtC,MAAM,mBAAmB,GAAG,CAC3B,WAAwB,EACxB,aAA6B,EAC7B,IAAU,EACV,gBAAoC,EACpC,iBAA+C,EAC9B,EAAE;IACnB,MAAM,gBAAgB,GAAG,WAAW,CAAC,eAAe,EAAE,CAAC,gBAAgB,CAAC;IAExE,MAAM,SAAS,GAAmB,aAAa;SAC7C,MAAM,CACN,CAAC,QAAQ,EAAE,EAAE,CACZ,CAAC,QAAQ,CAAC,eAAe,CAAC,EAAE,CAAC,UAAI,CAAC;QAClC,CAAC,QAAQ,CAAC,gBAAgB,CAAC,EAAE,CAAC,UAAI,CAAC;QACnC,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC,UAAI,CAAC,CAC5B;SACA,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE;;QACjB,MAAM,gBAAgB,GAAG,gBAAgB,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;QAChE,MAAM,UAAU,GAAG,WAAW,CAAC,oBAAoB,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;QAE1E,MAAM,cAAc,GAAG,WAAW,CAAC,oBAAoB,CACtD,6BAAuB,CACvB,CAAC;QAEF,MAAM,eAAe,GAAG,WAAW,CAAC,0BAA0B,CAC7D,QAAQ,CAAC,WAAW,CACpB,CAAC;QAEF,IAAI,WAAW,GAAG,eAAe,CAAC,KAAK,CAAC;QAExC,kGAAkG;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OAAO,WAAW,KAAK,IAAI,CAAC;AAC7B,CAAC,CAAC;AAEW,QAAA,UAAU,GAAG;IACzB,mBAAmB;IACnB,wBAAwB;CACxB,CAAC","sourcesContent":["import {\n\tBASE_PRECISION_EXP,\n\tBN,\n\tBigNum,\n\tDriftClient,\n\tMarketStatus,\n\tONE,\n\tPRICE_PRECISION,\n\tPRICE_PRECISION_EXP,\n\tPerpMarketConfig,\n\tPerpPosition,\n\tPositionDirection,\n\tPublicKey,\n\tQUOTE_PRECISION_EXP,\n\tQUOTE_SPOT_MARKET_INDEX,\n\tUser,\n\tZERO,\n\tcalculateClaimablePnl,\n\tcalculateCostBasis,\n\tcalculateEntryPrice,\n\tcalculateFeesAndFundingPnl,\n\tcalculatePositionPNL,\n\tgetUserAccountPublicKeySync,\n\tcalculateUnsettledFundingPnl,\n\tisOracleValid,\n\tAMM_RESERVE_PRECISION,\n} from '@drift-labs/sdk';\nimport { OpenPosition, UIMarket } from '../types';\nimport { TRADING_UTILS } from './trading';\nimport { ENUM_UTILS } from '../utils';\n\nconst getOpenPositionData = (\n\tdriftClient: DriftClient,\n\tuserPositions: PerpPosition[],\n\tuser: User,\n\tperpMarketLookup: PerpMarketConfig[],\n\tmarkPriceCallback?: (marketIndex: number) => BN\n): OpenPosition[] => {\n\tconst oracleGuardRails = driftClient.getStateAccount().oracleGuardRails;\n\n\tconst newResult: OpenPosition[] = userPositions\n\t\t.filter(\n\t\t\t(position) =>\n\t\t\t\t!position.baseAssetAmount.eq(ZERO) ||\n\t\t\t\t!position.quoteAssetAmount.eq(ZERO) ||\n\t\t\t\t!position.lpShares.eq(ZERO)\n\t\t)\n\t\t.map((position) => {\n\t\t\tconst perpMarketConfig = perpMarketLookup[position.marketIndex];\n\t\t\tconst perpMarket = driftClient.getPerpMarketAccount(position.marketIndex);\n\n\t\t\tconst usdcSpotMarket = driftClient.getSpotMarketAccount(\n\t\t\t\tQUOTE_SPOT_MARKET_INDEX\n\t\t\t);\n\n\t\t\tconst oraclePriceData = driftClient.getOracleDataForPerpMarket(\n\t\t\t\tposition.marketIndex\n\t\t\t);\n\n\t\t\tlet oraclePrice = oraclePriceData.price;\n\n\t\t\t// mark price fetched with a callback so we don't need extra dlob server calls. fallback to oracle\n\t\t\tlet markPrice = markPriceCallback\n\t\t\t\t? markPriceCallback(position.marketIndex) ?? oraclePriceData.price\n\t\t\t\t: oraclePriceData.price;\n\n\t\t\tlet estExitPrice = user.getPositionEstimatedExitPriceAndPnl(\n\t\t\t\tposition,\n\t\t\t\tposition.baseAssetAmount\n\t\t\t)[0];\n\n\t\t\tconst entryPrice = calculateEntryPrice(position);\n\n\t\t\tconst isShort = position.baseAssetAmount.isNeg();\n\n\t\t\tif (UIMarket.checkIsPredictionMarket(perpMarketConfig)) {\n\t\t\t\tconst isResolved =\n\t\t\t\t\tENUM_UTILS.match(perpMarket?.status, MarketStatus.SETTLEMENT) ||\n\t\t\t\t\tENUM_UTILS.match(perpMarket?.status, MarketStatus.DELISTED);\n\n\t\t\t\tif (isResolved) {\n\t\t\t\t\tconst resolvedToNo = perpMarket.expiryPrice.lte(\n\t\t\t\t\t\tZERO.add(perpMarket.amm.orderTickSize)\n\t\t\t\t\t);\n\n\t\t\t\t\tconst price = resolvedToNo\n\t\t\t\t\t\t? ZERO.mul(PRICE_PRECISION)\n\t\t\t\t\t\t: ONE.mul(PRICE_PRECISION);\n\n\t\t\t\t\testExitPrice = price;\n\t\t\t\t\tmarkPrice = price;\n\t\t\t\t\toraclePrice = price;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// if for any reason oracle or mark price blips to 0, fallback to the other one so we don't show a crazy pnl\n\t\t\tif (markPrice.lte(ZERO) && oraclePrice.gt(ZERO)) {\n\t\t\t\tmarkPrice = oraclePrice;\n\t\t\t}\n\n\t\t\tif (oraclePrice.lte(ZERO) && markPrice.gt(ZERO)) {\n\t\t\t\toraclePrice = markPrice;\n\t\t\t}\n\n\t\t\tconst pnlVsMark = TRADING_UTILS.calculatePotentialProfit({\n\t\t\t\tcurrentPositionSize: BigNum.from(\n\t\t\t\t\tposition.baseAssetAmount.abs(),\n\t\t\t\t\tBASE_PRECISION_EXP\n\t\t\t\t),\n\t\t\t\tcurrentPositionDirection: isShort\n\t\t\t\t\t? PositionDirection.SHORT\n\t\t\t\t\t: PositionDirection.LONG,\n\t\t\t\tcurrentPositionEntryPrice: BigNum.from(entryPrice, PRICE_PRECISION_EXP),\n\t\t\t\ttradeDirection: isShort\n\t\t\t\t\t? PositionDirection.LONG\n\t\t\t\t\t: PositionDirection.SHORT,\n\t\t\t\texitBaseSize: BigNum.from(\n\t\t\t\t\tposition.baseAssetAmount.abs(),\n\t\t\t\t\tBASE_PRECISION_EXP\n\t\t\t\t),\n\t\t\t\texitPrice: BigNum.from(markPrice, PRICE_PRECISION_EXP),\n\t\t\t\ttakerFeeBps: 0,\n\t\t\t}).estimatedProfit.shiftTo(QUOTE_PRECISION_EXP).val;\n\n\t\t\tconst pnlVsOracle = TRADING_UTILS.calculatePotentialProfit({\n\t\t\t\tcurrentPositionSize: BigNum.from(\n\t\t\t\t\tposition.baseAssetAmount.abs(),\n\t\t\t\t\tBASE_PRECISION_EXP\n\t\t\t\t),\n\t\t\t\tcurrentPositionDirection: isShort\n\t\t\t\t\t? PositionDirection.SHORT\n\t\t\t\t\t: PositionDirection.LONG,\n\t\t\t\tcurrentPositionEntryPrice: BigNum.from(entryPrice, PRICE_PRECISION_EXP),\n\t\t\t\ttradeDirection: isShort\n\t\t\t\t\t? PositionDirection.LONG\n\t\t\t\t\t: PositionDirection.SHORT,\n\t\t\t\texitBaseSize: BigNum.from(\n\t\t\t\t\tposition.baseAssetAmount.abs(),\n\t\t\t\t\tBASE_PRECISION_EXP\n\t\t\t\t),\n\t\t\t\texitPrice: BigNum.from(oraclePrice, PRICE_PRECISION_EXP),\n\t\t\t\ttakerFeeBps: 0,\n\t\t\t}).estimatedProfit.shiftTo(QUOTE_PRECISION_EXP).val;\n\n\t\t\treturn {\n\t\t\t\tmarketIndex: position.marketIndex,\n\t\t\t\tmarketSymbol: perpMarketConfig.symbol,\n\t\t\t\tdirection: isShort ? 'short' : 'long',\n\t\t\t\tnotional: position.baseAssetAmount\n\t\t\t\t\t.abs()\n\t\t\t\t\t.mul(markPrice)\n\t\t\t\t\t.div(AMM_RESERVE_PRECISION),\n\t\t\t\tbaseSize: position.baseAssetAmount,\n\t\t\t\tmarkPrice,\n\t\t\t\tentryPrice,\n\t\t\t\texitPrice: estExitPrice,\n\t\t\t\tliqPrice: user.liquidationPrice(position.marketIndex, ZERO),\n\t\t\t\tquoteAssetNotionalAmount: position.quoteAssetAmount,\n\t\t\t\tquoteEntryAmount: position.quoteEntryAmount,\n\t\t\t\tquoteBreakEvenAmount: position.quoteBreakEvenAmount,\n\t\t\t\tpnlVsMark,\n\t\t\t\tpnlVsOracle,\n\t\t\t\tunsettledPnl: calculateClaimablePnl(\n\t\t\t\t\tperpMarket,\n\t\t\t\t\tusdcSpotMarket,\n\t\t\t\t\tposition,\n\t\t\t\t\toraclePriceData\n\t\t\t\t),\n\t\t\t\tunsettledFundingPnl: calculateUnsettledFundingPnl(perpMarket, position),\n\t\t\t\t// Includes both settled and unsettled funding as well as fees\n\t\t\t\tfeesAndFundingPnl: calculateFeesAndFundingPnl(perpMarket, position),\n\t\t\t\ttotalUnrealizedPnl: calculatePositionPNL(\n\t\t\t\t\tperpMarket,\n\t\t\t\t\tposition,\n\t\t\t\t\ttrue,\n\t\t\t\t\toraclePriceData\n\t\t\t\t),\n\t\t\t\tunrealizedFundingPnl: user.getUnrealizedFundingPNL(\n\t\t\t\t\tposition.marketIndex\n\t\t\t\t),\n\t\t\t\tlastCumulativeFundingRate: position.lastCumulativeFundingRate,\n\t\t\t\topenOrders: position.openOrders,\n\t\t\t\tcostBasis: calculateCostBasis(position),\n\t\t\t\trealizedPnl: position.settledPnl,\n\t\t\t\tpnlIsClaimable: isOracleValid(\n\t\t\t\t\tperpMarket,\n\t\t\t\t\toraclePriceData,\n\t\t\t\t\toracleGuardRails,\n\t\t\t\t\tperpMarket.amm.lastUpdateSlot?.toNumber()\n\t\t\t\t),\n\t\t\t\tlpShares: position.lpShares,\n\t\t\t\tremainderBaseAmount: position.remainderBaseAssetAmount ?? 0,\n\t\t\t\tlpDeriskPrice: user.liquidationPrice(\n\t\t\t\t\tposition.marketIndex,\n\t\t\t\t\tundefined,\n\t\t\t\t\tundefined,\n\t\t\t\t\t'Initial',\n\t\t\t\t\ttrue\n\t\t\t\t),\n\t\t\t\tmaxMarginRatio: position.maxMarginRatio,\n\t\t\t};\n\t\t});\n\n\treturn newResult;\n};\n\nconst checkIfUserAccountExists = async (\n\tdriftClient: DriftClient,\n\tconfig:\n\t\t| {\n\t\t\t\ttype: 'userPubKey';\n\t\t\t\tuserPubKey: PublicKey;\n\t\t }\n\t\t| {\n\t\t\t\ttype: 'subAccountId';\n\t\t\t\tsubAccountId: number;\n\t\t\t\tauthority: PublicKey;\n\t\t }\n) => {\n\tlet userPubKey: PublicKey;\n\n\tif (config.type === 'userPubKey') {\n\t\tuserPubKey = config.userPubKey;\n\t} else {\n\t\tuserPubKey = getUserAccountPublicKeySync(\n\t\t\tdriftClient.program.programId,\n\t\t\tconfig.authority,\n\t\t\tconfig.subAccountId\n\t\t);\n\t}\n\n\tconst accountInfo = await driftClient.connection.getAccountInfo(userPubKey);\n\n\treturn accountInfo !== null;\n};\n\nexport const USER_UTILS = {\n\tgetOpenPositionData,\n\tcheckIfUserAccountExists,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"user.js","sourceRoot":"","sources":["../../src/common-ui-utils/user.ts"],"names":[],"mappings":";;;AAAA,yCA0ByB;AACzB,oCAAkD;AAClD,uCAA0C;AAC1C,oCAAsC;AAEtC,MAAM,mBAAmB,GAAG,CAC3B,WAAwB,EACxB,aAA6B,EAC7B,IAAU,EACV,gBAAoC,EACpC,iBAA+C,EAC9B,EAAE;IACnB,MAAM,gBAAgB,GAAG,WAAW,CAAC,eAAe,EAAE,CAAC,gBAAgB,C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POT_MARKET_INDEX,\n\tUser,\n\tZERO,\n\tcalculateClaimablePnl,\n\tcalculateCostBasis,\n\tcalculateEntryPrice,\n\tcalculateFeesAndFundingPnl,\n\tcalculatePositionPNL,\n\tgetUserAccountPublicKeySync,\n\tcalculateUnsettledFundingPnl,\n\tisOracleValid,\n\tAMM_RESERVE_PRECISION,\n} from '@drift-labs/sdk';\nimport { OpenPosition, UIMarket } from '../types';\nimport { TRADING_UTILS } from './trading';\nimport { ENUM_UTILS } from '../utils';\n\nconst getOpenPositionData = (\n\tdriftClient: DriftClient,\n\tuserPositions: PerpPosition[],\n\tuser: User,\n\tperpMarketLookup: PerpMarketConfig[],\n\tmarkPriceCallback?: (marketIndex: number) => BN\n): OpenPosition[] => {\n\tconst oracleGuardRails = driftClient.getStateAccount().oracleGuardRails;\n\n\tconst newResult: OpenPosition[] = userPositions\n\t\t.filter(\n\t\t\t(position) =>\n\t\t\t\t!position.baseAssetAmount.eq(ZERO) ||\n\t\t\t\t!position.quoteAssetAmount.eq(ZERO) ||\n\t\t\t\t!position.lpShares.eq(ZERO)\n\t\t)\n\t\t.map((position) => {\n\t\t\tconst perpMarketConfig = perpMarketLookup[position.marketIndex];\n\t\t\tconst perpMarket = driftClient.getPerpMarketAccount(position.marketIndex);\n\n\t\t\tconst usdcSpotMarket = driftClient.getSpotMarketAccount(\n\t\t\t\tQUOTE_SPOT_MARKET_INDEX\n\t\t\t);\n\n\t\t\tconst oraclePriceData = driftClient.getOracleDataForPerpMarket(\n\t\t\t\tposition.marketIndex\n\t\t\t);\n\n\t\t\tlet oraclePrice = oraclePriceData.price;\n\n\t\t\t// mark price fetched with a callback so we don't need extra dlob server calls. fallback to oracle\n\t\t\tlet markPrice = markPriceCallback\n\t\t\t\t? markPriceCallback(position.marketIndex) ?? oraclePriceData.price\n\t\t\t\t: oraclePriceData.price;\n\n\t\t\tlet estExitPrice = user.getPositionEstimatedExitPriceAndPnl(\n\t\t\t\tposition,\n\t\t\t\tposition.baseAssetAmount\n\t\t\t)[0];\n\n\t\t\tconst entryPrice = calculateEntryPrice(position);\n\n\t\t\tconst isShort = position.baseAssetAmount.isNeg();\n\n\t\t\tif (UIMarket.checkIsPredictionMarket(perpMarketConfig)) {\n\t\t\t\tconst isResolved =\n\t\t\t\t\tENUM_UTILS.match(perpMarket?.status, MarketStatus.SETTLEMENT) ||\n\t\t\t\t\tENUM_UTILS.match(perpMarket?.status, MarketStatus.DELISTED);\n\n\t\t\t\tif (isResolved) {\n\t\t\t\t\tconst resolvedToNo = perpMarket.expiryPrice.lte(\n\t\t\t\t\t\tZERO.add(perpMarket.amm.orderTickSize)\n\t\t\t\t\t);\n\n\t\t\t\t\tconst price = resolvedToNo\n\t\t\t\t\t\t? ZERO.mul(PRICE_PRECISION)\n\t\t\t\t\t\t: ONE.mul(PRICE_PRECISION);\n\n\t\t\t\t\testExitPrice = price;\n\t\t\t\t\tmarkPrice = price;\n\t\t\t\t\toraclePrice = price;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// if for any reason oracle or mark price blips to 0, fallback to the other one so we don't show a crazy pnl\n\t\t\tif (markPrice.lte(ZERO) && oraclePrice.gt(ZERO)) {\n\t\t\t\tmarkPrice = oraclePrice;\n\t\t\t}\n\n\t\t\tif (oraclePrice.lte(ZERO) && markPrice.gt(ZERO)) {\n\t\t\t\toraclePrice = markPrice;\n\t\t\t}\n\n\t\t\tconst pnlVsMark = TRADING_UTILS.calculatePotentialProfit({\n\t\t\t\tcurrentPositionSize: BigNum.from(\n\t\t\t\t\tposition.baseAssetAmount.abs(),\n\t\t\t\t\tBASE_PRECISION_EXP\n\t\t\t\t),\n\t\t\t\tcurrentPositionDirection: isShort\n\t\t\t\t\t? PositionDirection.SHORT\n\t\t\t\t\t: PositionDirection.LONG,\n\t\t\t\tcurrentPositionEntryPrice: BigNum.from(entryPrice, PRICE_PRECISION_EXP),\n\t\t\t\ttradeDirection: isShort\n\t\t\t\t\t? PositionDirection.LONG\n\t\t\t\t\t: PositionDirection.SHORT,\n\t\t\t\texitBaseSize: BigNum.from(\n\t\t\t\t\tposition.baseAssetAmount.abs(),\n\t\t\t\t\tBASE_PRECISION_EXP\n\t\t\t\t),\n\t\t\t\texitPrice: BigNum.from(markPrice, PRICE_PRECISION_EXP),\n\t\t\t\ttakerFeeBps: 0,\n\t\t\t}).estimatedProfit.shiftTo(QUOTE_PRECISION_EXP).val;\n\n\t\t\tconst pnlVsOracle = TRADING_UTILS.calculatePotentialProfit({\n\t\t\t\tcurrentPositionSize: BigNum.from(\n\t\t\t\t\tposition.baseAssetAmount.abs(),\n\t\t\t\t\tBASE_PRECISION_EXP\n\t\t\t\t),\n\t\t\t\tcurrentPositionDirection: isShort\n\t\t\t\t\t? PositionDirection.SHORT\n\t\t\t\t\t: PositionDirection.LONG,\n\t\t\t\tcurrentPositionEntryPrice: BigNum.from(entryPrice, PRICE_PRECISION_EXP),\n\t\t\t\ttradeDirection: isShort\n\t\t\t\t\t? PositionDirection.LONG\n\t\t\t\t\t: PositionDirection.SHORT,\n\t\t\t\texitBaseSize: BigNum.from(\n\t\t\t\t\tposition.baseAssetAmount.abs(),\n\t\t\t\t\tBASE_PRECISION_EXP\n\t\t\t\t),\n\t\t\t\texitPrice: BigNum.from(oraclePrice, PRICE_PRECISION_EXP),\n\t\t\t\ttakerFeeBps: 0,\n\t\t\t}).estimatedProfit.shiftTo(QUOTE_PRECISION_EXP).val;\n\n\t\t\treturn {\n\t\t\t\tmarketIndex: position.marketIndex,\n\t\t\t\tmarketSymbol: perpMarketConfig.symbol,\n\t\t\t\tdirection: isShort ? 'short' : 'long',\n\t\t\t\tnotional: position.baseAssetAmount\n\t\t\t\t\t.abs()\n\t\t\t\t\t.mul(markPrice)\n\t\t\t\t\t.div(AMM_RESERVE_PRECISION),\n\t\t\t\tbaseSize: position.baseAssetAmount,\n\t\t\t\tmarkPrice,\n\t\t\t\tentryPrice,\n\t\t\t\texitPrice: estExitPrice,\n\t\t\t\tliqPrice: user.liquidationPrice(position.marketIndex, ZERO),\n\t\t\t\tquoteAssetNotionalAmount: position.quoteAssetAmount,\n\t\t\t\tquoteEntryAmount: position.quoteEntryAmount,\n\t\t\t\tquoteBreakEvenAmount: position.quoteBreakEvenAmount,\n\t\t\t\tpnlVsMark,\n\t\t\t\tpnlVsOracle,\n\t\t\t\tunsettledPnl: calculateClaimablePnl(\n\t\t\t\t\tperpMarket,\n\t\t\t\t\tusdcSpotMarket,\n\t\t\t\t\tposition,\n\t\t\t\t\toraclePriceData\n\t\t\t\t),\n\t\t\t\tunsettledFundingPnl: calculateUnsettledFundingPnl(perpMarket, position),\n\t\t\t\t// Includes both settled and unsettled funding as well as fees\n\t\t\t\tfeesAndFundingPnl: calculateFeesAndFundingPnl(perpMarket, position),\n\t\t\t\ttotalUnrealizedPnl: calculatePositionPNL(\n\t\t\t\t\tperpMarket,\n\t\t\t\t\tposition,\n\t\t\t\t\ttrue,\n\t\t\t\t\toraclePriceData\n\t\t\t\t),\n\t\t\t\tunrealizedFundingPnl: user.getUnrealizedFundingPNL(\n\t\t\t\t\tposition.marketIndex\n\t\t\t\t),\n\t\t\t\tlastCumulativeFundingRate: position.lastCumulativeFundingRate,\n\t\t\t\topenOrders: position.openOrders,\n\t\t\t\tcostBasis: calculateCostBasis(position),\n\t\t\t\trealizedPnl: position.settledPnl,\n\t\t\t\tpnlIsClaimable: isOracleValid(\n\t\t\t\t\tperpMarket,\n\t\t\t\t\toraclePriceData,\n\t\t\t\t\toracleGuardRails,\n\t\t\t\t\tperpMarket.amm.lastUpdateSlot?.toNumber()\n\t\t\t\t),\n\t\t\t\tlpShares: position.lpShares,\n\t\t\t\tremainderBaseAmount: position.remainderBaseAssetAmount ?? 0,\n\t\t\t\tlpDeriskPrice: user.liquidationPrice(\n\t\t\t\t\tposition.marketIndex,\n\t\t\t\t\tundefined,\n\t\t\t\t\tundefined,\n\t\t\t\t\t'Initial',\n\t\t\t\t\ttrue\n\t\t\t\t),\n\t\t\t\tmaxMarginRatio: position.maxMarginRatio,\n\t\t\t};\n\t\t});\n\n\treturn newResult;\n};\n\nconst checkIfUserAccountExists = async (\n\tdriftClient: DriftClient,\n\tconfig:\n\t\t| {\n\t\t\t\ttype: 'userPubKey';\n\t\t\t\tuserPubKey: PublicKey;\n\t\t }\n\t\t| {\n\t\t\t\ttype: 'subAccountId';\n\t\t\t\tsubAccountId: number;\n\t\t\t\tauthority: PublicKey;\n\t\t }\n) => {\n\tlet userPubKey: PublicKey;\n\n\tif (config.type === 'userPubKey') {\n\t\tuserPubKey = config.userPubKey;\n\t} else {\n\t\tuserPubKey = getUserAccountPublicKeySync(\n\t\t\tdriftClient.program.programId,\n\t\t\tconfig.authority,\n\t\t\tconfig.subAccountId\n\t\t);\n\t}\n\n\tconst accountInfo = await driftClient.connection.getAccountInfo(userPubKey);\n\n\treturn accountInfo !== null;\n};\n\n/**\n * A user's max leverage for a market is stored on-chain in the `PerpPosition` struct of the `UserAccount`.\n * There are a few scenarios for how a market's max leverage is defined:\n *\n * 1. When the user does not have a position (\"empty\" or not) in the market in their `UserAccount` data,\n * and creates an order for the market, an \"empty\" `PerpPosition` will be upsert to the `UserAccount` data,\n * and will contain the max margin ratio set by the user. Note that the `UserAccount` data can store up\n * to 8 `PerpPosition` structs, and most of the time the majority of the `PerpPosition` structs will be\n * \"empty\" if the user does not have the max 8 perp positions open. The max leverage is then derived from\n * the max margin ratio set in the `PerpPosition` struct.\n *\n * 2. If the user has a position (\"empty\" or not), but no open orders and is provided with a saved max leverage,\n * the saved max leverage is used.\n *\n * 3. When the user does not have a position (\"empty\" or not), it is expected of the UI to store and persist\n * the max leverage in the UI client.\n *\n * 4. In cases where the user has a position before the market max leverage feature was shipped, the\n * position is not expected to have a max margin ratio set, and the UI should display the regular max\n * leverage for the market, unless the user is already in High Leverage Mode, in which case the UI should\n * display the high leverage max leverage for the market (if any).\n */\nconst getUserMaxLeverageForMarket = (\n\tuser: User | undefined,\n\tmarketIndex: number,\n\tmarketLeverageDetails: {\n\t\tregularMaxLeverage: number;\n\t\thighLeverageMaxLeverage: number;\n\t\thasHighLeverage: boolean;\n\t},\n\tuiSavedMaxLeverage?: number\n) => {\n\t// if no saved max leverage is provided, return the regular max leverage for the market\n\tconst DEFAULT_MAX_LEVERAGE =\n\t\tuiSavedMaxLeverage ?? marketLeverageDetails.regularMaxLeverage;\n\n\tif (!user) {\n\t\treturn DEFAULT_MAX_LEVERAGE;\n\t}\n\n\tconst openOrClosedPosition = user.getPerpPosition(marketIndex); // this position does not have to be open, it can be a closed position (a.k.a \"empty\") but has max margin ratio set.\n\n\tif (!openOrClosedPosition) {\n\t\treturn DEFAULT_MAX_LEVERAGE;\n\t}\n\n\tconst positionHasMaxMarginRatioSet = !!openOrClosedPosition.maxMarginRatio;\n\tconst isPositionOpen = !openOrClosedPosition.baseAssetAmount.eq(ZERO);\n\tconst hasNoOpenOrders = openOrClosedPosition.openOrders === 0;\n\n\tif (positionHasMaxMarginRatioSet) {\n\t\t// Special case: open position with no orders - use UI saved value if available\n\t\tif (isPositionOpen && hasNoOpenOrders && uiSavedMaxLeverage) {\n\t\t\treturn uiSavedMaxLeverage;\n\t\t}\n\n\t\treturn parseFloat(\n\t\t\t((1 / openOrClosedPosition.maxMarginRatio) * 10000).toFixed(2)\n\t\t);\n\t}\n\n\tif (isPositionOpen) {\n\t\t// user has an existing position from before PML ship (this means no max margin ratio set onchain yet)\n\t\t// display max leverage for the leverage mode their account is in\n\t\tconst isUserInHighLeverageMode = user.isHighLeverageMode('Initial');\n\t\tconst grandfatheredMaxLev = isUserInHighLeverageMode\n\t\t\t? marketLeverageDetails.hasHighLeverage\n\t\t\t\t? marketLeverageDetails.highLeverageMaxLeverage\n\t\t\t\t: marketLeverageDetails.regularMaxLeverage\n\t\t\t: marketLeverageDetails.regularMaxLeverage;\n\t\treturn grandfatheredMaxLev;\n\t}\n\n\t// user has closed position with no margin ratio set, return default value\n\treturn DEFAULT_MAX_LEVERAGE;\n};\n\nexport const USER_UTILS = {\n\tgetOpenPositionData,\n\tcheckIfUserAccountExists,\n\tgetUserMaxLeverageForMarket,\n};\n"]}
|
|
@@ -1,2 +1,6 @@
|
|
|
1
1
|
export declare const USDC_SPOT_MARKET_INDEX = 0;
|
|
2
|
+
export declare const SOL_SPOT_MARKET_INDEX = 1;
|
|
3
|
+
export declare const WBTC_SPOT_MARKET_INDEX = 3;
|
|
4
|
+
export declare const WETH_SPOT_MARKET_INDEX = 4;
|
|
5
|
+
export declare const CBBTC_SPOT_MARKET_INDEX = 27;
|
|
2
6
|
export declare const DEFAULT_MAX_MARKET_LEVERAGE = 10;
|
package/lib/constants/markets.js
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.DEFAULT_MAX_MARKET_LEVERAGE = exports.USDC_SPOT_MARKET_INDEX = void 0;
|
|
3
|
+
exports.DEFAULT_MAX_MARKET_LEVERAGE = exports.CBBTC_SPOT_MARKET_INDEX = exports.WETH_SPOT_MARKET_INDEX = exports.WBTC_SPOT_MARKET_INDEX = exports.SOL_SPOT_MARKET_INDEX = exports.USDC_SPOT_MARKET_INDEX = void 0;
|
|
4
4
|
exports.USDC_SPOT_MARKET_INDEX = 0;
|
|
5
|
+
exports.SOL_SPOT_MARKET_INDEX = 1;
|
|
6
|
+
exports.WBTC_SPOT_MARKET_INDEX = 3;
|
|
7
|
+
exports.WETH_SPOT_MARKET_INDEX = 4;
|
|
8
|
+
exports.CBBTC_SPOT_MARKET_INDEX = 27;
|
|
5
9
|
exports.DEFAULT_MAX_MARKET_LEVERAGE = 10;
|
|
6
10
|
//# sourceMappingURL=markets.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"markets.js","sourceRoot":"","sources":["../../src/constants/markets.ts"],"names":[],"mappings":";;;AAAa,QAAA,sBAAsB,GAAG,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"markets.js","sourceRoot":"","sources":["../../src/constants/markets.ts"],"names":[],"mappings":";;;AAAa,QAAA,sBAAsB,GAAG,CAAC,CAAC;AAC3B,QAAA,qBAAqB,GAAG,CAAC,CAAC;AAC1B,QAAA,sBAAsB,GAAG,CAAC,CAAC;AAC3B,QAAA,sBAAsB,GAAG,CAAC,CAAC;AAC3B,QAAA,uBAAuB,GAAG,EAAE,CAAC;AAE7B,QAAA,2BAA2B,GAAG,EAAE,CAAC","sourcesContent":["export const USDC_SPOT_MARKET_INDEX = 0;\nexport const SOL_SPOT_MARKET_INDEX = 1;\nexport const WBTC_SPOT_MARKET_INDEX = 3;\nexport const WETH_SPOT_MARKET_INDEX = 4;\nexport const CBBTC_SPOT_MARKET_INDEX = 27;\n\nexport const DEFAULT_MAX_MARKET_LEVERAGE = 10;\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"superstake.js","sourceRoot":"","sources":["../../src/constants/superstake.ts"],"names":[],"mappings":";;;AAAA,yCAAuE;AAiB1D,QAAA,KAAK,GAAQ;IACzB,MAAM,EAAE,MAAM;IACd,gBAAgB,EAAE,iBAAiB;IACnC,UAAU,EAAE,wBAAkB,CAAC,CAAC,CAAC;IACjC,OAAO,EAAE,WAAW;IACpB,WAAW,EAAE,CAAC;IACd,eAAe,EAAE,CAAC;IAClB,eAAe,EAAE,IAAI;CACrB,CAAC;AAEW,QAAA,QAAQ,GAAQ;IAC5B,MAAM,EAAE,SAAS;IACjB,gBAAgB,EAAE,qBAAqB;IACvC,UAAU,EAAE,wBAAkB,CAAC,CAAC,CAAC;IACjC,OAAO,EAAE,cAAc;IACvB,WAAW,EAAE,GAAG;IAChB,eAAe,EAAE,GAAG;IACpB,eAAe,EAAE,IAAI;CACrB,CAAC;AAEW,QAAA,KAAK,GAAQ;IACzB,MAAM,EAAE,MAAM;IACd,gBAAgB,EAAE,kBAAkB;IACpC,UAAU,EAAE,wBAAkB,CAAC,CAAC,CAAC;IACjC,OAAO,EAAE,WAAW;IACpB,WAAW,EAAE,GAAG;IAChB,eAAe,EAAE,GAAG;IACpB,oBAAoB,EAAE,MAAM;IAC5B,eAAe,EAAE,IAAI;CACrB,CAAC;AAEF;;GAEG;AACU,QAAA,kBAAkB,GAAU,CAAC,aAAK,EAAE,gBAAQ,EAAE,aAAK,CAAC,CAAC;AAElE;;GAEG;AACU,QAAA,sBAAsB,GAAwB;IAC1D,CAAC,aAAK,CAAC,MAAM,CAAC,EAAE,aAAK;IACrB,CAAC,gBAAQ,CAAC,MAAM,CAAC,EAAE,gBAAQ;IAC3B,CAAC,aAAK,CAAC,MAAM,CAAC,EAAE,aAAK;CACrB,CAAC","sourcesContent":["import { MainnetSpotMarkets, SpotMarketConfig } from '@drift-labs/sdk';\n\nexport type LST = {\n\tsymbol: string; // symbol is added as a config because JitoSOL's symbol in the spotMarket is jitoSOL\n\tdriftAccountName: string;\n\tspotMarket: SpotMarketConfig;\n\tlogoUrl: string;\n\t// maxLeverage set manually for now, but would be nice if we make it derived from the asset weight later on\n\tmaxLeverage: number;\n\t// Default leverage to start the form out with when switching to the lst\n\tdefaultLeverage: number;\n\t// Symbol of the token offered as emissions if there's an emissions APY on top of the normal APY\n\temissionsTokenSymbol?: string;\n\t// use direct route for
|
|
1
|
+
{"version":3,"file":"superstake.js","sourceRoot":"","sources":["../../src/constants/superstake.ts"],"names":[],"mappings":";;;AAAA,yCAAuE;AAiB1D,QAAA,KAAK,GAAQ;IACzB,MAAM,EAAE,MAAM;IACd,gBAAgB,EAAE,iBAAiB;IACnC,UAAU,EAAE,wBAAkB,CAAC,CAAC,CAAC;IACjC,OAAO,EAAE,WAAW;IACpB,WAAW,EAAE,CAAC;IACd,eAAe,EAAE,CAAC;IAClB,eAAe,EAAE,IAAI;CACrB,CAAC;AAEW,QAAA,QAAQ,GAAQ;IAC5B,MAAM,EAAE,SAAS;IACjB,gBAAgB,EAAE,qBAAqB;IACvC,UAAU,EAAE,wBAAkB,CAAC,CAAC,CAAC;IACjC,OAAO,EAAE,cAAc;IACvB,WAAW,EAAE,GAAG;IAChB,eAAe,EAAE,GAAG;IACpB,eAAe,EAAE,IAAI;CACrB,CAAC;AAEW,QAAA,KAAK,GAAQ;IACzB,MAAM,EAAE,MAAM;IACd,gBAAgB,EAAE,kBAAkB;IACpC,UAAU,EAAE,wBAAkB,CAAC,CAAC,CAAC;IACjC,OAAO,EAAE,WAAW;IACpB,WAAW,EAAE,GAAG;IAChB,eAAe,EAAE,GAAG;IACpB,oBAAoB,EAAE,MAAM;IAC5B,eAAe,EAAE,IAAI;CACrB,CAAC;AAEF;;GAEG;AACU,QAAA,kBAAkB,GAAU,CAAC,aAAK,EAAE,gBAAQ,EAAE,aAAK,CAAC,CAAC;AAElE;;GAEG;AACU,QAAA,sBAAsB,GAAwB;IAC1D,CAAC,aAAK,CAAC,MAAM,CAAC,EAAE,aAAK;IACrB,CAAC,gBAAQ,CAAC,MAAM,CAAC,EAAE,gBAAQ;IAC3B,CAAC,aAAK,CAAC,MAAM,CAAC,EAAE,aAAK;CACrB,CAAC","sourcesContent":["import { MainnetSpotMarkets, SpotMarketConfig } from '@drift-labs/sdk';\n\nexport type LST = {\n\tsymbol: string; // symbol is added as a config because JitoSOL's symbol in the spotMarket is jitoSOL\n\tdriftAccountName: string;\n\tspotMarket: SpotMarketConfig;\n\tlogoUrl: string;\n\t// maxLeverage set manually for now, but would be nice if we make it derived from the asset weight later on\n\tmaxLeverage: number;\n\t// Default leverage to start the form out with when switching to the lst\n\tdefaultLeverage: number;\n\t// Symbol of the token offered as emissions if there's an emissions APY on top of the normal APY\n\temissionsTokenSymbol?: string;\n\t// use direct route for swap\n\tonlyDirectRoute?: boolean;\n};\n\nexport const M_SOL: LST = {\n\tsymbol: 'mSOL',\n\tdriftAccountName: 'Super Stake SOL',\n\tspotMarket: MainnetSpotMarkets[2],\n\tlogoUrl: '/mSol.svg',\n\tmaxLeverage: 3,\n\tdefaultLeverage: 2,\n\tonlyDirectRoute: true,\n};\n\nexport const JITO_SOL: LST = {\n\tsymbol: 'JitoSOL',\n\tdriftAccountName: 'Super Stake JitoSOL',\n\tspotMarket: MainnetSpotMarkets[6],\n\tlogoUrl: '/jitoSol.svg',\n\tmaxLeverage: 1.8,\n\tdefaultLeverage: 1.4,\n\tonlyDirectRoute: true,\n};\n\nexport const B_SOL: LST = {\n\tsymbol: 'bSOL',\n\tdriftAccountName: 'Super Stake bSOL',\n\tspotMarket: MainnetSpotMarkets[8],\n\tlogoUrl: '/bsol.svg',\n\tmaxLeverage: 2.5,\n\tdefaultLeverage: 1.8,\n\temissionsTokenSymbol: 'BLZE',\n\tonlyDirectRoute: true,\n};\n\n/**\n * All LSTs that support one-click superstaking\n */\nexport const SUPERSTAKE_ALL_LST: LST[] = [M_SOL, JITO_SOL, B_SOL];\n\n/**\n * All LSTs that support one-click superstaking\n */\nexport const SUPERSTAKE_ALL_LST_MAP: Record<string, LST> = {\n\t[M_SOL.symbol]: M_SOL,\n\t[JITO_SOL.symbol]: JITO_SOL,\n\t[B_SOL.symbol]: B_SOL,\n};\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Subscription } from 'rxjs';
|
|
2
2
|
import { MarketId } from '../../../../types';
|
|
3
|
-
import { L2WithOracleAndMarketData } from '../../../../utils/orderbook';
|
|
3
|
+
import { L2WithOracleAndMarketData } from '../../../../utils/orderbook/types';
|
|
4
4
|
import { OrderbookGrouping } from '../../../../utils/dlob-server/DlobServerWebsocketUtils';
|
|
5
5
|
interface DriftL2OrderbookSubscription {
|
|
6
6
|
marketId: MarketId;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DriftL2OrderbookManager.js","sourceRoot":"","sources":["../../../../../src/drift/Drift/clients/AuthorityDrift/DriftL2OrderbookManager.ts"],"names":[],"mappings":";;;AAAA,+BAA6C;AAE7C,
|
|
1
|
+
{"version":3,"file":"DriftL2OrderbookManager.js","sourceRoot":"","sources":["../../../../../src/drift/Drift/clients/AuthorityDrift/DriftL2OrderbookManager.ts"],"names":[],"mappings":";;;AAAA,+BAA6C;A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AC,CAAC;IACjD,CAAC;IAED;;OAEG;IACI,OAAO;QACb,IAAI,CAAC,WAAW,EAAE,CAAC;QACnB,IAAI,CAAC,eAAe,CAAC,QAAQ,EAAE,CAAC;QAChC,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC;IACxB,CAAC;CACD;AAxKD,0DAwKC","sourcesContent":["import { Subject, Subscription } from 'rxjs';\nimport { MarketId } from '../../../../types';\nimport { deserializeL2Response } from '../../../../utils/orderbook';\nimport {\n\tL2WithOracleAndMarketData,\n\tRawL2Output,\n} from '../../../../utils/orderbook/types';\nimport { MultiplexWebSocket } from '../../../../utils/MultiplexWebSocket';\nimport {\n\tDLOB_SERVER_WEBSOCKET_UTILS,\n\tOrderbookGrouping,\n} from '../../../../utils/dlob-server/DlobServerWebsocketUtils';\n\ninterface DriftL2OrderbookSubscription {\n\tmarketId: MarketId;\n\tchannel: 'orderbook_indicative' | 'orderbook';\n\tgrouping: OrderbookGrouping;\n}\n\ninterface DlobMessage {\n\tchannel: string;\n\tdata: string;\n\terror?: any;\n}\n\nexport interface DriftL2OrderbookManagerConfig {\n\twsUrl: string;\n\tsubscriptionConfig?: DriftL2OrderbookSubscription;\n}\n\nexport class DriftL2OrderbookManager {\n\tprivate _orderbook: L2WithOracleAndMarketData | null = null;\n\tprivate wsUrl: string;\n\tprivate _subscriptionConfig?: DriftL2OrderbookSubscription;\n\tprivate updatesSubject$ = new Subject<L2WithOracleAndMarketData>();\n\tprivate websocketSubscription: { unsubscribe: () => void } | null = null;\n\n\tconstructor(config: DriftL2OrderbookManagerConfig) {\n\t\tthis.wsUrl = config.wsUrl;\n\t\tthis._subscriptionConfig = config.subscriptionConfig;\n\t}\n\n\tget store() {\n\t\treturn this._orderbook ? { ...this._orderbook } : null;\n\t}\n\n\tget subscriptionConfig() {\n\t\treturn this._subscriptionConfig;\n\t}\n\n\t/**\n\t * Subscribe to orderbook updates via websocket\n\t */\n\tpublic async subscribe(): Promise<void> {\n\t\tif (this.websocketSubscription) {\n\t\t\tconsole.error('There is already a subscription to the orderbook');\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this._subscriptionConfig) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst subscriptionId = `orderbook-${Date.now()}`;\n\t\tconst grouping = this._subscriptionConfig.grouping;\n\n\t\tconst subscribeMessage = JSON.stringify(\n\t\t\tDLOB_SERVER_WEBSOCKET_UTILS.getSubscriptionProps({\n\t\t\t\ttype: 'orderbook_indicative',\n\t\t\t\tmarket: this._subscriptionConfig.marketId,\n\t\t\t\tgrouping,\n\t\t\t})\n\t\t);\n\n\t\tconst unsubscribeMessage = JSON.stringify(\n\t\t\tDLOB_SERVER_WEBSOCKET_UTILS.getUnsubscriptionProps({\n\t\t\t\ttype: 'orderbook_indicative',\n\t\t\t\tmarket: this._subscriptionConfig.marketId,\n\t\t\t\tgrouping,\n\t\t\t})\n\t\t);\n\n\t\tconst messageFilter = DLOB_SERVER_WEBSOCKET_UTILS.getMessageFilter({\n\t\t\ttype: this._subscriptionConfig.channel,\n\t\t\tmarket: this._subscriptionConfig.marketId,\n\t\t\tgrouping,\n\t\t});\n\n\t\tthis.websocketSubscription = MultiplexWebSocket.createWebSocketSubscription(\n\t\t\t{\n\t\t\t\twsUrl: this.wsUrl,\n\t\t\t\tsubscriptionId,\n\t\t\t\tsubscribeMessage,\n\t\t\t\tunsubscribeMessage,\n\t\t\t\tonMessage: (message: DlobMessage) => {\n\t\t\t\t\tthis.handleWebSocketMessage(message);\n\t\t\t\t},\n\t\t\t\tonError: (error) => {\n\t\t\t\t\tconsole.error('OrderbookManager WebSocket error:', error);\n\t\t\t\t},\n\t\t\t\tmessageFilter: (message: DlobMessage) => {\n\t\t\t\t\treturn messageFilter(message);\n\t\t\t\t},\n\t\t\t\terrorMessageFilter: (message: DlobMessage) => {\n\t\t\t\t\treturn !!message.error;\n\t\t\t\t},\n\t\t\t\tonClose: () => {\n\t\t\t\t\tconsole.log('OrderbookManager WebSocket connection closed');\n\t\t\t\t},\n\t\t\t\tenableHeartbeatMonitoring: true,\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Unsubscribe from orderbook updates\n\t */\n\tpublic unsubscribe(): void {\n\t\tif (this.websocketSubscription) {\n\t\t\tthis.websocketSubscription.unsubscribe();\n\t\t\tthis.websocketSubscription = null;\n\t\t}\n\t}\n\n\t/**\n\t * Update market keys for subscription\n\t */\n\tpublic updateSubscription(\n\t\torderbookSubscription: Pick<DriftL2OrderbookSubscription, 'marketId'> &\n\t\t\tPartial<DriftL2OrderbookSubscription>\n\t): void {\n\t\t// check if subscription config is changing\n\n\t\tthis._subscriptionConfig = {\n\t\t\t...this._subscriptionConfig,\n\t\t\t...orderbookSubscription,\n\t\t};\n\n\t\tthis.unsubscribe();\n\t\tthis.subscribe();\n\t}\n\n\tprivate tryParse(data: unknown): unknown {\n\t\ttry {\n\t\t\treturn JSON.parse(data as string, (key, value) => {\n\t\t\t\t// If the value is a number and it's too large to be safely represented as a JavaScript number,\n\t\t\t\t// convert it to a string to prevent precision loss\n\t\t\t\tif (typeof value === 'number' && !Number.isSafeInteger(value)) {\n\t\t\t\t\treturn value.toString();\n\t\t\t\t}\n\t\t\t\treturn value;\n\t\t\t});\n\t\t} catch (e) {\n\t\t\treturn data;\n\t\t}\n\t}\n\n\t/**\n\t * Handle incoming websocket messages\n\t */\n\tprivate handleWebSocketMessage({ data }: DlobMessage): void {\n\t\ttry {\n\t\t\tconst parsedData = this.tryParse(data) as RawL2Output;\n\n\t\t\t// TODO: result slot incrementer\n\n\t\t\tconst deserializedOrderbook = deserializeL2Response(parsedData);\n\t\t\tthis._orderbook = deserializedOrderbook;\n\t\t\tthis.updatesSubject$.next(deserializedOrderbook);\n\t\t} catch (error) {\n\t\t\tconsole.error('Error processing orderbook websocket message:', error);\n\t\t}\n\t}\n\n\t/**\n\t * Get orderbook data for a specific market\n\t */\n\tpublic getOrderbookData(): L2WithOracleAndMarketData | null {\n\t\treturn this._orderbook || null;\n\t}\n\n\t/**\n\t * Subscribe to orderbook updates\n\t */\n\tpublic onUpdate(\n\t\tcallback: (orderbookLookup: L2WithOracleAndMarketData) => void\n\t): Subscription {\n\t\treturn this.updatesSubject$.subscribe(callback);\n\t}\n\n\t/**\n\t * Destroy the manager and clean up resources\n\t */\n\tpublic destroy(): void {\n\t\tthis.unsubscribe();\n\t\tthis.updatesSubject$.complete();\n\t\tthis._orderbook = null;\n\t}\n}\n"]}
|
|
@@ -325,6 +325,7 @@ class DriftOperations {
|
|
|
325
325
|
marketIndex: params.marketIndex,
|
|
326
326
|
optionalAuctionParamsInputs: params.orderConfig.optionalAuctionParamsInputs,
|
|
327
327
|
builderParams: params.builderParams,
|
|
328
|
+
positionMaxLeverage: params.positionMaxLeverage,
|
|
328
329
|
});
|
|
329
330
|
return swiftOrderResult;
|
|
330
331
|
}
|
|
@@ -340,6 +341,7 @@ class DriftOperations {
|
|
|
340
341
|
optionalAuctionParamsInputs: params.orderConfig.optionalAuctionParamsInputs,
|
|
341
342
|
dlobServerHttpUrl: this.dlobServerHttpUrl,
|
|
342
343
|
useSwift: false,
|
|
344
|
+
positionMaxLeverage: params.positionMaxLeverage,
|
|
343
345
|
});
|
|
344
346
|
const { txSig } = await this.driftClient.sendTransaction(result);
|
|
345
347
|
return txSig;
|
|
@@ -376,6 +378,7 @@ class DriftOperations {
|
|
|
376
378
|
...params.orderConfig.swiftOptions,
|
|
377
379
|
},
|
|
378
380
|
builderParams: params.builderParams,
|
|
381
|
+
positionMaxLeverage: params.positionMaxLeverage,
|
|
379
382
|
});
|
|
380
383
|
return swiftOrderResult;
|
|
381
384
|
}
|
|
@@ -396,6 +399,7 @@ class DriftOperations {
|
|
|
396
399
|
postOnly: params.postOnly,
|
|
397
400
|
useSwift: false,
|
|
398
401
|
txParams: this.getTxParams(),
|
|
402
|
+
positionMaxLeverage: params.positionMaxLeverage,
|
|
399
403
|
});
|
|
400
404
|
const { txSig } = await this.driftClient.sendTransaction(txn);
|
|
401
405
|
return txSig;
|
|
@@ -418,6 +422,7 @@ class DriftOperations {
|
|
|
418
422
|
reduceOnly: params.reduceOnly,
|
|
419
423
|
useSwift: false,
|
|
420
424
|
txParams: this.getTxParams(),
|
|
425
|
+
positionMaxLeverage: params.positionMaxLeverage,
|
|
421
426
|
});
|
|
422
427
|
const { txSig } = await this.driftClient.sendTransaction(txn);
|
|
423
428
|
return txSig;
|
|
@@ -437,6 +442,7 @@ class DriftOperations {
|
|
|
437
442
|
reduceOnly: params.reduceOnly,
|
|
438
443
|
useSwift: false,
|
|
439
444
|
txParams: this.getTxParams(),
|
|
445
|
+
positionMaxLeverage: params.positionMaxLeverage,
|
|
440
446
|
});
|
|
441
447
|
const { txSig } = await this.driftClient.sendTransaction(txn);
|
|
442
448
|
return txSig;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/drift/Drift/clients/AuthorityDrift/DriftOperations/index.ts"],"names":[],"mappings":";;;AAAA,yCAYyB;AAEzB,kEAAqE;AACrE,wDAAwD;AACxD,oEAAuE;AAEvE,mEAAyE;AACzE,iEAA6F;AAC7F,qEAA2E;AAC3E,iEAAqE;AACrE,uEAA6E;AAW7E,4EAAmF;AACnF,0GAG0E;AAC1E,8DAAoE;AACpE,gHAAmH;AACnH,wGAAwG;AAExG;;;;;;;GAOG;AACH,MAAa,eAAe;IAS3B;;;;;;OAMG;IACH,YACS,WAAwB,EACxB,mBAA2C,EAC3C,iBAAyB,EACzB,cAAsB,EACtB,cAA4B;QAJ5B,gBAAW,GAAX,WAAW,CAAa;QACxB,wBAAmB,GAAnB,mBAAmB,CAAwB;QAC3C,sBAAiB,GAAjB,iBAAiB,CAAQ;QACzB,mBAAc,GAAd,cAAc,CAAQ;QACtB,mBAAc,GAAd,cAAc,CAAc;IAClC,CAAC;IAEJ;;;OAGG;IACH,WAAW,CAAC,SAA6B;;QACxC,MAAM,iBAAiB,GAAG,IAAI,CAAC,KAAK,CACnC,MAAA,IAAI,CAAC,cAAc,E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AM,IAAI,CAAC,WAAW,CAAC,eAAe,CAAC,YAAY,CAAC,CAAC;QAEvE,OAAO,KAAK,CAAC;IACd,CAAC;IAED,KAAK,CAAC,YAAY,CACjB,MAA0B;QAE1B,MAAM,EAAE,YAAY,EAAE,QAAQ,EAAE,GAAG,MAAM,CAAC;QAE1C,MAAM,WAAW,GAAG,IAAI,CAAC,mBAAmB,EAAE,CAAC,OAAO,CACrD,YAAY,EACZ,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,SAAS,CACjC,CAAC;QAEF,IAAI,CAAC,WAAW,EAAE,CAAC;YAClB,MAAM,IAAI,KAAK,CAAC,gBAAgB,CAAC,CAAC;QACnC,CAAC;QAED,MAAM,eAAe,GAAG,MAAM,IAAA,mCAAqB,EAAC;YACnD,WAAW,EAAE,IAAI,CAAC,WAAW;YAC7B,IAAI,EAAE,WAAW,CAAC,UAAU;YAC5B,QAAQ;YACR,QAAQ,EAAE,IAAI,CAAC,WAAW,EAAE;SAC5B,CAAC,CAAC;QAEH,MAAM,EAAE,KAAK,EAAE,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,eAAe,CAAC,eAAe,CAAC,CAAC;QAE1E,OAAO,KAAK,CAAC;IACd,CAAC;;AAnsBF,0CAosBC;AAnsBgB,iCAAiB,GAAa;IAC7C,iBAAiB,EAAE,KAAM;IACzB,wBAAwB,EAAE,IAAI;IAC9B,4BAA4B,EAAE,GAAG;CACjC,CAAC;AAEc,uCAAuB,GAAG,IAAI,GAAG,EAAE,GAAG,OAAS,CAAC,CAAC,+GAA+G;AA+rBjL;;;;;;;;;;;GAWG","sourcesContent":["import {\n\tBigNum,\n\tDriftClient,\n\tJupiterClient,\n\tMarketType,\n\tMAX_LEVERAGE_ORDER_SIZE,\n\tQuoteResponse,\n\tSwapMode,\n\tTxParams,\n\tUser,\n\tUserStatsAccount,\n\tZERO,\n} from '@drift-labs/sdk';\nimport { TransactionSignature } from '@solana/web3.js';\nimport { MARKET_UTILS } from '../../../../../common-ui-utils/market';\nimport { MAIN_POOL_ID } from '../../../../../constants';\nimport { TRADING_UTILS } from '../../../../../common-ui-utils/trading';\nimport { UserAccountCache } from '../../../stores/UserAccountCache';\nimport { createDepositTxn } from '../../../../base/actions/spot/deposit';\nimport { createUserAndDepositCollateralBaseTxn } from '../../../../base/actions/user/create';\nimport { createWithdrawTxn } from '../../../../base/actions/spot/withdraw';\nimport { deleteUserTxn } from '../../../../base/actions/user/delete';\nimport { createSettlePnlTxn } from '../../../../base/actions/perp/settlePnl';\nimport {\n\tCreateUserAndDepositParams,\n\tDepositParams,\n\tWithdrawParams,\n\tPerpOrderParams,\n\tSwapParams,\n\tSettleAccountPnlParams,\n\tCancelOrdersParams,\n\tCreateRevenueShareEscrowParams,\n} from './types';\nimport { createCancelOrdersTxn } from '../../../../base/actions/trade/cancelOrder';\nimport {\n\tcreateOpenPerpMarketOrder,\n\tOpenPerpMarketOrderParams,\n} from '../../../../base/actions/trade/openPerpOrder/openPerpMarketOrder';\nimport { createSwapTxn } from '../../../../base/actions/trade/swap';\nimport { createOpenPerpNonMarketOrder } from '../../../../base/actions/trade/openPerpOrder/openPerpNonMarketOrder';\nimport { createRevenueShareEscrowTxn } from '../../../../base/actions/builder/createRevenueShareEscrow';\n\n/**\n * Handles majority of the relevant operations on the Drift program including deposits,\n * withdrawals, position management, and trading operations.\n *\n * This class encapsulates the trading logic and provides a clean API for\n * executing various trading operations while handling common patterns like\n * token address resolution and transaction preparation.\n */\nexport class DriftOperations {\n\tstatic readonly DEFAULT_TX_PARAMS: TxParams = {\n\t\tcomputeUnitsPrice: 50_000,\n\t\tuseSimulatedComputeUnits: true,\n\t\tcomputeUnitsBufferMultiplier: 1.3,\n\t};\n\n\tstatic readonly MAX_COMPUTE_UNITS_PRICE = 1e15 / 10 / 1_400_000; // 1e15 = 1 SOL worth of micro lamports; 1e15 / 10 = 0.1 SOL worth of micro lamports; 1.4M = max compute units;\n\n\t/**\n\t * Creates a new DriftOperations instance.\n\t *\n\t * @param driftClient - The DriftClient instance for executing transactions\n\t * @param getUserAccountCache - Function to get the user account cache. We lazily load the user account cache, so that we always get the latest user account data.\n\t * @param getPriorityFee - Function to get current priority fee in micro lamports\n\t */\n\tconstructor(\n\t\tprivate driftClient: DriftClient,\n\t\tprivate getUserAccountCache: () => UserAccountCache,\n\t\tprivate dlobServerHttpUrl: string,\n\t\tprivate swiftServerUrl: string,\n\t\tprivate getPriorityFee: () => number\n\t) {}\n\n\t/**\n\t * Gets transaction parameters with dynamic priority fees.\n\t * Falls back to default if priority fee function is not available.\n\t */\n\tgetTxParams(overrides?: Partial<TxParams>): TxParams {\n\t\tconst unsafePriorityFee = Math.floor(\n\t\t\tthis.getPriorityFee() ??\n\t\t\t\tDriftOperations.DEFAULT_TX_PARAMS.computeUnitsPrice\n\t\t);\n\n\t\tconst safePriorityFee = Math.min(\n\t\t\tunsafePriorityFee,\n\t\t\tDriftOperations.MAX_COMPUTE_UNITS_PRICE\n\t\t);\n\n\t\treturn {\n\t\t\t...DriftOperations.DEFAULT_TX_PARAMS,\n\t\t\tcomputeUnitsPrice: safePriorityFee,\n\t\t\t...overrides,\n\t\t};\n\t}\n\n\t/**\n\t * Creates a new user account and deposits initial collateral.\n\t *\n\t * This method handles the complete onboarding flow for new users including:\n\t * - Validating that the subaccount doesn't already exist\n\t * - Resolving referrer information if provided\n\t * - Getting the correct token address for deposits\n\t * - Creating the user account with custom leverage settings\n\t * - Subscribing to the new user's account updates\n\t *\n\t * @param params - The parameters for user creation and initial deposit\n\t * @returns Promise resolving to transaction signature and user account public key\n\t *\n\t * @throws Error if subaccount already exists\n\t *\n\t * @example\n\t * ```typescript\n\t * const result = await tradingOps.createUserAndDeposit({\n\t * depositAmount: new BigNum(100),\n\t * depositSpotMarketIndex: 0, // USDC\n\t * name: \"Trading Account\",\n\t * maxLeverage: 5,\n\t * subAccountId: 0\n\t * });\n\t * ```\n\t */\n\tasync createUserAndDeposit(params: CreateUserAndDepositParams): Promise<{\n\t\ttxSig: TransactionSignature;\n\t\tuser: User;\n\t}> {\n\t\tconst {\n\t\t\tdepositAmount,\n\t\t\tdepositSpotMarketIndex,\n\t\t\tnewAccountName,\n\t\t\tmaxLeverage,\n\t\t\tpoolId = MAIN_POOL_ID,\n\t\t\treferrerName,\n\t\t} = params;\n\n\t\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tdepositSpotMarketIndex\n\t\t);\n\n\t\tconst customMaxMarginRatio = TRADING_UTILS.convertLeverageToMarginRatio(\n\t\t\tmaxLeverage ?? 0\n\t\t);\n\n\t\tlet userStatsAccount: UserStatsAccount | undefined = undefined;\n\n\t\ttry {\n\t\t\tuserStatsAccount = this.driftClient.userStats?.getAccount();\n\t\t} catch (error) {\n\t\t\t// ignore\n\t\t}\n\n\t\tconst { transaction, subAccountId } =\n\t\t\tawait createUserAndDepositCollateralBaseTxn({\n\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\tamount: depositAmount.val,\n\t\t\t\tspotMarketConfig: spotMarketConfig,\n\t\t\t\tauthority: this.driftClient.wallet.publicKey,\n\t\t\t\tuserStatsAccount: userStatsAccount,\n\t\t\t\taccountName: newAccountName,\n\t\t\t\treferrerName,\n\t\t\t\tcustomMaxMarginRatio,\n\t\t\t\tpoolId,\n\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(transaction);\n\n\t\tawait this.driftClient.addUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t); // adds user to driftclient's user map, subscribes to user account data\n\t\tconst user = this.driftClient.getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tuser.eventEmitter.on('update', () => {\n\t\t\tthis.getUserAccountCache().updateUserAccount(user);\n\t\t});\n\n\t\treturn {\n\t\t\ttxSig,\n\t\t\tuser,\n\t\t};\n\t}\n\n\t/**\n\t * Creates a RevenueShareEscrow account for the user.\n\t *\n\t * @param params - The parameters for creating a RevenueShareEscrow account\n\t * @returns Promise resolving to the transaction signature of the creation\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.createRevenueShareEscrow({\n\t * numOrders: 16,\n\t * builder: {\n\t * builderAuthority: new PublicKey(\"builderAuthority\"),\n\t * maxFeeTenthBps: 100,\n\t * },\n\t * });\n\t * ```\n\t */\n\tasync createRevenueShareEscrow(\n\t\tparams: CreateRevenueShareEscrowParams\n\t): Promise<TransactionSignature> {\n\t\tconst txn = await createRevenueShareEscrowTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tauthority: this.driftClient.wallet.publicKey,\n\t\t\tnumOrders: params.numOrders ?? 16,\n\t\t\tbuilder: params.builder,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Deletes a user account.\n\t *\n\t * This method removes a user's sub-account from the Drift.\n\t *\n\t * @param subAccountId - The ID of the sub-account to delete\n\t * @returns A promise that resolves to the transaction signature of the deletion\n\t *\n\t * @throws {Error} When the user account is not found in the cache\n\t *\n\t * @example\n\t * ```typescript\n\t * // Delete user sub-account with ID 0\n\t * const txSignature = await tradingOps.deleteUser(0);\n\t * console.log('User deleted with transaction:', txSignature);\n\t * ```\n\t */\n\tasync deleteUser(subAccountId: number): Promise<TransactionSignature> {\n\t\tconst user = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!user) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst deleteTxn = await deleteUserTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuserPublicKey: user.userClient.userAccountPublicKey,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(deleteTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Deposits collateral into a user's spot market position.\n\t *\n\t * This method handles depositing tokens into a user's account, with optional\n\t * support for max borrow repayment scenarios where the deposit amount may be\n\t * over-estimated to ensure complete repayment of borrowed funds.\n\t *\n\t * @param params - The deposit parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.deposit({\n\t * subAccountId: 0,\n\t * amount: new BigNum(50),\n\t * spotMarketIndex: 0, // USDC\n\t * isMaxBorrowRepayment: false\n\t * });\n\t * ```\n\t */\n\tasync deposit(params: DepositParams): Promise<TransactionSignature> {\n\t\tconst { subAccountId, amount, spotMarketIndex, isMaxBorrowRepayment } =\n\t\t\tparams;\n\n\t\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tspotMarketIndex\n\t\t);\n\n\t\tconst user = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!user) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst depositTxn = await createDepositTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuser: user.userClient,\n\t\t\tamount: amount,\n\t\t\tspotMarketConfig: spotMarketConfig,\n\t\t\tisMaxBorrowRepayment,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(depositTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Withdraws collateral from a user's spot market position.\n\t *\n\t * This method handles withdrawing tokens from a user's account with options\n\t * for borrowing (if allowBorrow is true) or reduce-only withdrawals. For max\n\t * withdrawals with reduce-only, the amount is over-estimated to ensure\n\t * complete withdrawal.\n\t *\n\t * @param params - The withdrawal parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.withdraw({\n\t * subAccountId: 0,\n\t * amount: new BigNum(25),\n\t * spotMarketIndex: 0, // USDC\n\t * allowBorrow: false,\n\t * isMax: false\n\t * });\n\t * ```\n\t */\n\tasync withdraw(params: WithdrawParams): Promise<TransactionSignature> {\n\t\tconst {\n\t\t\tsubAccountId,\n\t\t\tamount,\n\t\t\tspotMarketIndex,\n\t\t\tisBorrow = false,\n\t\t\tisMax = false,\n\t\t} = params;\n\n\t\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tspotMarketIndex\n\t\t);\n\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst withdrawTxn = await createWithdrawTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tamount,\n\t\t\tspotMarketConfig,\n\t\t\tuser: accountData.userClient,\n\t\t\tisBorrow,\n\t\t\tisMax,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(withdrawTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Opens a perpetual market order (placeholder for future implementation).\n\t *\n\t * This method will handle opening long or short positions in perpetual markets\n\t * with support for market and limit orders, reduce-only orders, and post-only orders.\n\t *\n\t * @param params - The perp order parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.openPerpMarketOrder({\n\t * marketIndex: 0, // SOL-PERP\n\t * direction: 'long',\n\t * baseAssetAmount: new BigNum(1), // 1 SOL\n\t * orderType: 'market',\n\t * subAccountId: 0\n\t * });\n\t * ```\n\t */\n\tasync openPerpOrder(\n\t\tparams: PerpOrderParams\n\t): Promise<TransactionSignature | void> {\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tparams.subAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst user = accountData.userClient;\n\n\t\tconst processBracketOrders = (bracketOrdersInput?: {\n\t\t\ttakeProfitPrice?: BigNum;\n\t\t\tstopLossPrice?: BigNum;\n\t\t}) => {\n\t\t\tconst bracketOrders: OpenPerpMarketOrderParams['bracketOrders'] = {};\n\n\t\t\tif (bracketOrdersInput?.takeProfitPrice) {\n\t\t\t\tbracketOrders.takeProfit = {\n\t\t\t\t\ttriggerPrice: bracketOrdersInput.takeProfitPrice.val,\n\t\t\t\t\tbaseAssetAmount: params.size.val,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (bracketOrdersInput?.stopLossPrice) {\n\t\t\t\tbracketOrders.stopLoss = {\n\t\t\t\t\ttriggerPrice: bracketOrdersInput.stopLossPrice.val,\n\t\t\t\t\tbaseAssetAmount: params.size.val,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn bracketOrders;\n\t\t};\n\n\t\tconst amountBN = params.isMaxLeverage\n\t\t\t? MAX_LEVERAGE_ORDER_SIZE\n\t\t\t: params.size.val;\n\n\t\tswitch (params.orderConfig.orderType) {\n\t\t\tcase 'market': {\n\t\t\t\tconst useSwift = !params.orderConfig.disableSwift;\n\n\t\t\t\tconst bracketOrders = processBracketOrders(\n\t\t\t\t\tparams.orderConfig.bracketOrders\n\t\t\t\t);\n\n\t\t\t\t// we split the logic for SWIFT and non-SWIFT orders to achieve better type inference\n\t\t\t\tif (useSwift) {\n\t\t\t\t\tconst swiftOrderResult = await createOpenPerpMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\tuseSwift: true,\n\t\t\t\t\t\tswiftOptions: {\n\t\t\t\t\t\t\twallet: {\n\t\t\t\t\t\t\t\t// @ts-ignore TODO: we might want to add signMessage to the IWallet interface\n\t\t\t\t\t\t\t\tsignMessage: this.driftClient.wallet.signMessage,\n\t\t\t\t\t\t\t\ttakerAuthority: this.driftClient.wallet.publicKey,\n\t\t\t\t\t\t\t\tsigningAuthority: this.driftClient.wallet.publicKey,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tswiftServerUrl: this.swiftServerUrl,\n\t\t\t\t\t\t\t...params.orderConfig.swiftOptions,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\tdlobServerHttpUrl: this.dlobServerHttpUrl,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\toptionalAuctionParamsInputs:\n\t\t\t\t\t\t\tparams.orderConfig.optionalAuctionParamsInputs,\n\t\t\t\t\t\tbuilderParams: params.builderParams,\n\t\t\t\t\t});\n\n\t\t\t\t\treturn swiftOrderResult;\n\t\t\t\t} else {\n\t\t\t\t\tconst result = await createOpenPerpMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\toptionalAuctionParamsInputs:\n\t\t\t\t\t\t\tparams.orderConfig.optionalAuctionParamsInputs,\n\t\t\t\t\t\tdlobServerHttpUrl: this.dlobServerHttpUrl,\n\t\t\t\t\t\tuseSwift: false,\n\t\t\t\t\t});\n\n\t\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(result);\n\n\t\t\t\t\treturn txSig;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcase 'limit': {\n\t\t\t\tconst useSwift = !params.orderConfig.disableSwift;\n\n\t\t\t\tconst bracketOrders = processBracketOrders(\n\t\t\t\t\tparams.orderConfig.bracketOrders\n\t\t\t\t);\n\n\t\t\t\t// we split the logic for SWIFT and non-SWIFT orders to achieve better type inference\n\t\t\t\tif (useSwift) {\n\t\t\t\t\tconst swiftOrderResult = await createOpenPerpNonMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\torderConfig: {\n\t\t\t\t\t\t\torderType: 'limit',\n\t\t\t\t\t\t\tlimitPrice: params.orderConfig.limitPrice.val,\n\t\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\t},\n\t\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\t\tpostOnly: params.postOnly,\n\t\t\t\t\t\tuseSwift: true,\n\t\t\t\t\t\tswiftOptions: {\n\t\t\t\t\t\t\twallet: {\n\t\t\t\t\t\t\t\t// @ts-ignore TODO: we might want to add signMessage to the IWallet interface\n\t\t\t\t\t\t\t\tsignMessage: this.driftClient.wallet.signMessage,\n\t\t\t\t\t\t\t\ttakerAuthority: this.driftClient.wallet.publicKey,\n\t\t\t\t\t\t\t\tsigningAuthority: this.driftClient.wallet.publicKey,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tswiftServerUrl: this.swiftServerUrl,\n\t\t\t\t\t\t\t...params.orderConfig.swiftOptions,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tbuilderParams: params.builderParams,\n\t\t\t\t\t});\n\n\t\t\t\t\treturn swiftOrderResult;\n\t\t\t\t} else {\n\t\t\t\t\tconst txn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\torderConfig: {\n\t\t\t\t\t\t\torderType: 'limit',\n\t\t\t\t\t\t\tlimitPrice: params.orderConfig.limitPrice.val,\n\t\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\t},\n\t\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\t\tpostOnly: params.postOnly,\n\t\t\t\t\t\tuseSwift: false,\n\t\t\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t\t\t});\n\n\t\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\t\t\t\treturn txSig;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcase 'takeProfit':\n\t\t\tcase 'stopLoss': {\n\t\t\t\tconst txn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\tamount: amountBN,\n\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\torderConfig: {\n\t\t\t\t\t\torderType: params.orderConfig.orderType,\n\t\t\t\t\t\ttriggerPrice: params.orderConfig.triggerPrice.val,\n\t\t\t\t\t\tlimitPrice: params.orderConfig.limitPrice?.val ?? ZERO,\n\t\t\t\t\t},\n\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\tuseSwift: false,\n\t\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t\t});\n\n\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\t\t\treturn txSig;\n\t\t\t}\n\t\t\tcase 'oracleLimit': {\n\t\t\t\tconst txn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\tamount: amountBN,\n\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\torderConfig: {\n\t\t\t\t\t\torderType: 'oracleLimit',\n\t\t\t\t\t\toraclePriceOffset: params.orderConfig.oraclePriceOffset.val,\n\t\t\t\t\t},\n\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\tuseSwift: false,\n\t\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t\t});\n\n\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\t\t\treturn txSig;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tconst _exhaustiveCheck: never = params.orderConfig;\n\t\t\t\tthrow new Error('Invalid order type');\n\t\t\t}\n\t\t}\n\t}\n\n\tasync getSwapQuote(\n\t\tparams: Omit<SwapParams, 'jupiterQuote'> & {\n\t\t\tslippageBps?: number;\n\t\t\tswapMode?: SwapMode;\n\t\t\tonlyDirectRoutes?: boolean;\n\t\t}\n\t): Promise<QuoteResponse> {\n\t\tconst jupiterClient = new JupiterClient({\n\t\t\tconnection: this.driftClient.connection,\n\t\t});\n\n\t\tconst inputMint = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tparams.fromMarketIndex\n\t\t).mint;\n\t\tconst outputMint = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tparams.toMarketIndex\n\t\t).mint;\n\n\t\tconst jupiterQuote = await jupiterClient.getQuote({\n\t\t\tinputMint,\n\t\t\toutputMint,\n\t\t\tamount: params.amount.val,\n\t\t\tslippageBps: params.slippageBps,\n\t\t\tswapMode: params.swapMode,\n\t\t\tonlyDirectRoutes: params.onlyDirectRoutes,\n\t\t});\n\n\t\treturn jupiterQuote;\n\t}\n\n\t/**\n\t * Executes a swap between two spot markets (placeholder for future implementation).\n\t *\n\t * This method will handle swapping between different spot markets through\n\t * the Drift protocol's swap functionality.\n\t *\n\t * @param params - The swap parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.executeSwap({\n\t * fromMarketIndex: 0, // USDC\n\t * toMarketIndex: 1, // SOL\n\t * amount: new BigNum(100),\n\t * subAccountId: 0,\n\t * minReceiveAmount: new BigNum(0.5)\n\t * });\n\t * ```\n\t */\n\tasync swap(params: SwapParams): Promise<TransactionSignature> {\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tparams.subAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst jupiterClient = new JupiterClient({\n\t\t\tconnection: this.driftClient.connection,\n\t\t});\n\n\t\tconst jupiterQuote = params.jupiterQuote\n\t\t\t? params.jupiterQuote\n\t\t\t: await this.getSwapQuote(params);\n\n\t\tconst swapTxn = await createSwapTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tjupiterClient,\n\t\t\tuser: accountData.userClient,\n\t\t\tswapFromMarketIndex: params.fromMarketIndex,\n\t\t\tswapToMarketIndex: params.toMarketIndex,\n\t\t\tamount: params.amount.val,\n\t\t\tquote: jupiterQuote,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(swapTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Settles P&L and funding for all perp position.\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.settlePnl({\n\t * subAccountId: 0,\n\t * marketIndex: 0, // SOL-PERP\n\t * counterpartySubAccountId: 1\n\t * });\n\t * ```\n\t */\n\tasync settleAccountPnl(\n\t\tparams: SettleAccountPnlParams\n\t): Promise<TransactionSignature> {\n\t\tconst { subAccountId } = params;\n\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst marketIndexes = accountData.openPerpPositions.map(\n\t\t\t(position) => position.marketIndex\n\t\t);\n\n\t\tconst settlePnlTxn = await createSettlePnlTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuser: accountData.userClient,\n\t\t\tmarketIndexes,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(settlePnlTxn);\n\n\t\treturn txSig;\n\t}\n\n\tasync cancelOrders(\n\t\tparams: CancelOrdersParams\n\t): Promise<TransactionSignature> {\n\t\tconst { subAccountId, orderIds } = params;\n\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst cancelOrdersTxn = await createCancelOrdersTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuser: accountData.userClient,\n\t\t\torderIds,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(cancelOrdersTxn);\n\n\t\treturn txSig;\n\t}\n}\n\n/**\n * TODO:\n * - transfer between subaccounts\n * - close position?\n * - close multiple positions\n * - edit open order\n * - create user only\n *\n * - open spot order\n * - rename subaccount\n * - withdraw dust positions\n */\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/drift/Drift/clients/AuthorityDrift/DriftOperations/index.ts"],"names":[],"mappings":";;;AAAA,yCAYyB;AAEzB,kEAAqE;AACrE,wDAAwD;AACxD,oEAAuE;AAEvE,mEAAyE;AACzE,iEAA6F;AAC7F,qEAA2E;AAC3E,iEAAqE;AACrE,uEAA6E;AAW7E,4EAAmF;AACnF,0GAG0E;AAC1E,8DAAoE;AACpE,gHAAmH;AACnH,wGAAwG;AAExG;;;;;;;GAOG;AACH,MAAa,eAAe;IAS3B;;;;;;OAMG;IACH,YACS,WAAwB,EACxB,mBAA2C,EAC3C,iBAAyB,EACzB,cAAsB,E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AG,MAAM,IAAI,CAAC,WAAW,CAAC,eAAe,CAAC,eAAe,CAAC,CAAC;QAE1E,OAAO,KAAK,CAAC;IACd,CAAC;;AAzsBF,0CA0sBC;AAzsBgB,iCAAiB,GAAa;IAC7C,iBAAiB,EAAE,KAAM;IACzB,wBAAwB,EAAE,IAAI;IAC9B,4BAA4B,EAAE,GAAG;CACjC,CAAC;AAEc,uCAAuB,GAAG,IAAI,GAAG,EAAE,GAAG,OAAS,CAAC,CAAC,+GAA+G;AAqsBjL;;;;;;;;;;;GAWG","sourcesContent":["import {\n\tBigNum,\n\tDriftClient,\n\tJupiterClient,\n\tMarketType,\n\tMAX_LEVERAGE_ORDER_SIZE,\n\tQuoteResponse,\n\tSwapMode,\n\tTxParams,\n\tUser,\n\tUserStatsAccount,\n\tZERO,\n} from '@drift-labs/sdk';\nimport { TransactionSignature } from '@solana/web3.js';\nimport { MARKET_UTILS } from '../../../../../common-ui-utils/market';\nimport { MAIN_POOL_ID } from '../../../../../constants';\nimport { TRADING_UTILS } from '../../../../../common-ui-utils/trading';\nimport { UserAccountCache } from '../../../stores/UserAccountCache';\nimport { createDepositTxn } from '../../../../base/actions/spot/deposit';\nimport { createUserAndDepositCollateralBaseTxn } from '../../../../base/actions/user/create';\nimport { createWithdrawTxn } from '../../../../base/actions/spot/withdraw';\nimport { deleteUserTxn } from '../../../../base/actions/user/delete';\nimport { createSettlePnlTxn } from '../../../../base/actions/perp/settlePnl';\nimport {\n\tCreateUserAndDepositParams,\n\tDepositParams,\n\tWithdrawParams,\n\tPerpOrderParams,\n\tSwapParams,\n\tSettleAccountPnlParams,\n\tCancelOrdersParams,\n\tCreateRevenueShareEscrowParams,\n} from './types';\nimport { createCancelOrdersTxn } from '../../../../base/actions/trade/cancelOrder';\nimport {\n\tcreateOpenPerpMarketOrder,\n\tOpenPerpMarketOrderParams,\n} from '../../../../base/actions/trade/openPerpOrder/openPerpMarketOrder';\nimport { createSwapTxn } from '../../../../base/actions/trade/swap';\nimport { createOpenPerpNonMarketOrder } from '../../../../base/actions/trade/openPerpOrder/openPerpNonMarketOrder';\nimport { createRevenueShareEscrowTxn } from '../../../../base/actions/builder/createRevenueShareEscrow';\n\n/**\n * Handles majority of the relevant operations on the Drift program including deposits,\n * withdrawals, position management, and trading operations.\n *\n * This class encapsulates the trading logic and provides a clean API for\n * executing various trading operations while handling common patterns like\n * token address resolution and transaction preparation.\n */\nexport class DriftOperations {\n\tstatic readonly DEFAULT_TX_PARAMS: TxParams = {\n\t\tcomputeUnitsPrice: 50_000,\n\t\tuseSimulatedComputeUnits: true,\n\t\tcomputeUnitsBufferMultiplier: 1.3,\n\t};\n\n\tstatic readonly MAX_COMPUTE_UNITS_PRICE = 1e15 / 10 / 1_400_000; // 1e15 = 1 SOL worth of micro lamports; 1e15 / 10 = 0.1 SOL worth of micro lamports; 1.4M = max compute units;\n\n\t/**\n\t * Creates a new DriftOperations instance.\n\t *\n\t * @param driftClient - The DriftClient instance for executing transactions\n\t * @param getUserAccountCache - Function to get the user account cache. We lazily load the user account cache, so that we always get the latest user account data.\n\t * @param getPriorityFee - Function to get current priority fee in micro lamports\n\t */\n\tconstructor(\n\t\tprivate driftClient: DriftClient,\n\t\tprivate getUserAccountCache: () => UserAccountCache,\n\t\tprivate dlobServerHttpUrl: string,\n\t\tprivate swiftServerUrl: string,\n\t\tprivate getPriorityFee: () => number\n\t) {}\n\n\t/**\n\t * Gets transaction parameters with dynamic priority fees.\n\t * Falls back to default if priority fee function is not available.\n\t */\n\tgetTxParams(overrides?: Partial<TxParams>): TxParams {\n\t\tconst unsafePriorityFee = Math.floor(\n\t\t\tthis.getPriorityFee() ??\n\t\t\t\tDriftOperations.DEFAULT_TX_PARAMS.computeUnitsPrice\n\t\t);\n\n\t\tconst safePriorityFee = Math.min(\n\t\t\tunsafePriorityFee,\n\t\t\tDriftOperations.MAX_COMPUTE_UNITS_PRICE\n\t\t);\n\n\t\treturn {\n\t\t\t...DriftOperations.DEFAULT_TX_PARAMS,\n\t\t\tcomputeUnitsPrice: safePriorityFee,\n\t\t\t...overrides,\n\t\t};\n\t}\n\n\t/**\n\t * Creates a new user account and deposits initial collateral.\n\t *\n\t * This method handles the complete onboarding flow for new users including:\n\t * - Validating that the subaccount doesn't already exist\n\t * - Resolving referrer information if provided\n\t * - Getting the correct token address for deposits\n\t * - Creating the user account with custom leverage settings\n\t * - Subscribing to the new user's account updates\n\t *\n\t * @param params - The parameters for user creation and initial deposit\n\t * @returns Promise resolving to transaction signature and user account public key\n\t *\n\t * @throws Error if subaccount already exists\n\t *\n\t * @example\n\t * ```typescript\n\t * const result = await tradingOps.createUserAndDeposit({\n\t * depositAmount: new BigNum(100),\n\t * depositSpotMarketIndex: 0, // USDC\n\t * name: \"Trading Account\",\n\t * maxLeverage: 5,\n\t * subAccountId: 0\n\t * });\n\t * ```\n\t */\n\tasync createUserAndDeposit(params: CreateUserAndDepositParams): Promise<{\n\t\ttxSig: TransactionSignature;\n\t\tuser: User;\n\t}> {\n\t\tconst {\n\t\t\tdepositAmount,\n\t\t\tdepositSpotMarketIndex,\n\t\t\tnewAccountName,\n\t\t\tmaxLeverage,\n\t\t\tpoolId = MAIN_POOL_ID,\n\t\t\treferrerName,\n\t\t} = params;\n\n\t\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tdepositSpotMarketIndex\n\t\t);\n\n\t\tconst customMaxMarginRatio = TRADING_UTILS.convertLeverageToMarginRatio(\n\t\t\tmaxLeverage ?? 0\n\t\t);\n\n\t\tlet userStatsAccount: UserStatsAccount | undefined = undefined;\n\n\t\ttry {\n\t\t\tuserStatsAccount = this.driftClient.userStats?.getAccount();\n\t\t} catch (error) {\n\t\t\t// ignore\n\t\t}\n\n\t\tconst { transaction, subAccountId } =\n\t\t\tawait createUserAndDepositCollateralBaseTxn({\n\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\tamount: depositAmount.val,\n\t\t\t\tspotMarketConfig: spotMarketConfig,\n\t\t\t\tauthority: this.driftClient.wallet.publicKey,\n\t\t\t\tuserStatsAccount: userStatsAccount,\n\t\t\t\taccountName: newAccountName,\n\t\t\t\treferrerName,\n\t\t\t\tcustomMaxMarginRatio,\n\t\t\t\tpoolId,\n\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(transaction);\n\n\t\tawait this.driftClient.addUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t); // adds user to driftclient's user map, subscribes to user account data\n\t\tconst user = this.driftClient.getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tuser.eventEmitter.on('update', () => {\n\t\t\tthis.getUserAccountCache().updateUserAccount(user);\n\t\t});\n\n\t\treturn {\n\t\t\ttxSig,\n\t\t\tuser,\n\t\t};\n\t}\n\n\t/**\n\t * Creates a RevenueShareEscrow account for the user.\n\t *\n\t * @param params - The parameters for creating a RevenueShareEscrow account\n\t * @returns Promise resolving to the transaction signature of the creation\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.createRevenueShareEscrow({\n\t * numOrders: 16,\n\t * builder: {\n\t * builderAuthority: new PublicKey(\"builderAuthority\"),\n\t * maxFeeTenthBps: 100,\n\t * },\n\t * });\n\t * ```\n\t */\n\tasync createRevenueShareEscrow(\n\t\tparams: CreateRevenueShareEscrowParams\n\t): Promise<TransactionSignature> {\n\t\tconst txn = await createRevenueShareEscrowTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tauthority: this.driftClient.wallet.publicKey,\n\t\t\tnumOrders: params.numOrders ?? 16,\n\t\t\tbuilder: params.builder,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Deletes a user account.\n\t *\n\t * This method removes a user's sub-account from the Drift.\n\t *\n\t * @param subAccountId - The ID of the sub-account to delete\n\t * @returns A promise that resolves to the transaction signature of the deletion\n\t *\n\t * @throws {Error} When the user account is not found in the cache\n\t *\n\t * @example\n\t * ```typescript\n\t * // Delete user sub-account with ID 0\n\t * const txSignature = await tradingOps.deleteUser(0);\n\t * console.log('User deleted with transaction:', txSignature);\n\t * ```\n\t */\n\tasync deleteUser(subAccountId: number): Promise<TransactionSignature> {\n\t\tconst user = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!user) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst deleteTxn = await deleteUserTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuserPublicKey: user.userClient.userAccountPublicKey,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(deleteTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Deposits collateral into a user's spot market position.\n\t *\n\t * This method handles depositing tokens into a user's account, with optional\n\t * support for max borrow repayment scenarios where the deposit amount may be\n\t * over-estimated to ensure complete repayment of borrowed funds.\n\t *\n\t * @param params - The deposit parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.deposit({\n\t * subAccountId: 0,\n\t * amount: new BigNum(50),\n\t * spotMarketIndex: 0, // USDC\n\t * isMaxBorrowRepayment: false\n\t * });\n\t * ```\n\t */\n\tasync deposit(params: DepositParams): Promise<TransactionSignature> {\n\t\tconst { subAccountId, amount, spotMarketIndex, isMaxBorrowRepayment } =\n\t\t\tparams;\n\n\t\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tspotMarketIndex\n\t\t);\n\n\t\tconst user = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!user) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst depositTxn = await createDepositTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuser: user.userClient,\n\t\t\tamount: amount,\n\t\t\tspotMarketConfig: spotMarketConfig,\n\t\t\tisMaxBorrowRepayment,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(depositTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Withdraws collateral from a user's spot market position.\n\t *\n\t * This method handles withdrawing tokens from a user's account with options\n\t * for borrowing (if allowBorrow is true) or reduce-only withdrawals. For max\n\t * withdrawals with reduce-only, the amount is over-estimated to ensure\n\t * complete withdrawal.\n\t *\n\t * @param params - The withdrawal parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.withdraw({\n\t * subAccountId: 0,\n\t * amount: new BigNum(25),\n\t * spotMarketIndex: 0, // USDC\n\t * allowBorrow: false,\n\t * isMax: false\n\t * });\n\t * ```\n\t */\n\tasync withdraw(params: WithdrawParams): Promise<TransactionSignature> {\n\t\tconst {\n\t\t\tsubAccountId,\n\t\t\tamount,\n\t\t\tspotMarketIndex,\n\t\t\tisBorrow = false,\n\t\t\tisMax = false,\n\t\t} = params;\n\n\t\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tspotMarketIndex\n\t\t);\n\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst withdrawTxn = await createWithdrawTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tamount,\n\t\t\tspotMarketConfig,\n\t\t\tuser: accountData.userClient,\n\t\t\tisBorrow,\n\t\t\tisMax,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(withdrawTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Opens a perpetual market order (placeholder for future implementation).\n\t *\n\t * This method will handle opening long or short positions in perpetual markets\n\t * with support for market and limit orders, reduce-only orders, and post-only orders.\n\t *\n\t * @param params - The perp order parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.openPerpMarketOrder({\n\t * marketIndex: 0, // SOL-PERP\n\t * direction: 'long',\n\t * baseAssetAmount: new BigNum(1), // 1 SOL\n\t * orderType: 'market',\n\t * subAccountId: 0\n\t * });\n\t * ```\n\t */\n\tasync openPerpOrder(\n\t\tparams: PerpOrderParams\n\t): Promise<TransactionSignature | void> {\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tparams.subAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst user = accountData.userClient;\n\n\t\tconst processBracketOrders = (bracketOrdersInput?: {\n\t\t\ttakeProfitPrice?: BigNum;\n\t\t\tstopLossPrice?: BigNum;\n\t\t}) => {\n\t\t\tconst bracketOrders: OpenPerpMarketOrderParams['bracketOrders'] = {};\n\n\t\t\tif (bracketOrdersInput?.takeProfitPrice) {\n\t\t\t\tbracketOrders.takeProfit = {\n\t\t\t\t\ttriggerPrice: bracketOrdersInput.takeProfitPrice.val,\n\t\t\t\t\tbaseAssetAmount: params.size.val,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (bracketOrdersInput?.stopLossPrice) {\n\t\t\t\tbracketOrders.stopLoss = {\n\t\t\t\t\ttriggerPrice: bracketOrdersInput.stopLossPrice.val,\n\t\t\t\t\tbaseAssetAmount: params.size.val,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn bracketOrders;\n\t\t};\n\n\t\tconst amountBN = params.isMaxLeverage\n\t\t\t? MAX_LEVERAGE_ORDER_SIZE\n\t\t\t: params.size.val;\n\n\t\tswitch (params.orderConfig.orderType) {\n\t\t\tcase 'market': {\n\t\t\t\tconst useSwift = !params.orderConfig.disableSwift;\n\n\t\t\t\tconst bracketOrders = processBracketOrders(\n\t\t\t\t\tparams.orderConfig.bracketOrders\n\t\t\t\t);\n\n\t\t\t\t// we split the logic for SWIFT and non-SWIFT orders to achieve better type inference\n\t\t\t\tif (useSwift) {\n\t\t\t\t\tconst swiftOrderResult = await createOpenPerpMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\tuseSwift: true,\n\t\t\t\t\t\tswiftOptions: {\n\t\t\t\t\t\t\twallet: {\n\t\t\t\t\t\t\t\t// @ts-ignore TODO: we might want to add signMessage to the IWallet interface\n\t\t\t\t\t\t\t\tsignMessage: this.driftClient.wallet.signMessage,\n\t\t\t\t\t\t\t\ttakerAuthority: this.driftClient.wallet.publicKey,\n\t\t\t\t\t\t\t\tsigningAuthority: this.driftClient.wallet.publicKey,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tswiftServerUrl: this.swiftServerUrl,\n\t\t\t\t\t\t\t...params.orderConfig.swiftOptions,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\tdlobServerHttpUrl: this.dlobServerHttpUrl,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\toptionalAuctionParamsInputs:\n\t\t\t\t\t\t\tparams.orderConfig.optionalAuctionParamsInputs,\n\t\t\t\t\t\tbuilderParams: params.builderParams,\n\t\t\t\t\t\tpositionMaxLeverage: params.positionMaxLeverage,\n\t\t\t\t\t});\n\n\t\t\t\t\treturn swiftOrderResult;\n\t\t\t\t} else {\n\t\t\t\t\tconst result = await createOpenPerpMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\toptionalAuctionParamsInputs:\n\t\t\t\t\t\t\tparams.orderConfig.optionalAuctionParamsInputs,\n\t\t\t\t\t\tdlobServerHttpUrl: this.dlobServerHttpUrl,\n\t\t\t\t\t\tuseSwift: false,\n\t\t\t\t\t\tpositionMaxLeverage: params.positionMaxLeverage,\n\t\t\t\t\t});\n\n\t\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(result);\n\n\t\t\t\t\treturn txSig;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcase 'limit': {\n\t\t\t\tconst useSwift = !params.orderConfig.disableSwift;\n\n\t\t\t\tconst bracketOrders = processBracketOrders(\n\t\t\t\t\tparams.orderConfig.bracketOrders\n\t\t\t\t);\n\n\t\t\t\t// we split the logic for SWIFT and non-SWIFT orders to achieve better type inference\n\t\t\t\tif (useSwift) {\n\t\t\t\t\tconst swiftOrderResult = await createOpenPerpNonMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\torderConfig: {\n\t\t\t\t\t\t\torderType: 'limit',\n\t\t\t\t\t\t\tlimitPrice: params.orderConfig.limitPrice.val,\n\t\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\t},\n\t\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\t\tpostOnly: params.postOnly,\n\t\t\t\t\t\tuseSwift: true,\n\t\t\t\t\t\tswiftOptions: {\n\t\t\t\t\t\t\twallet: {\n\t\t\t\t\t\t\t\t// @ts-ignore TODO: we might want to add signMessage to the IWallet interface\n\t\t\t\t\t\t\t\tsignMessage: this.driftClient.wallet.signMessage,\n\t\t\t\t\t\t\t\ttakerAuthority: this.driftClient.wallet.publicKey,\n\t\t\t\t\t\t\t\tsigningAuthority: this.driftClient.wallet.publicKey,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tswiftServerUrl: this.swiftServerUrl,\n\t\t\t\t\t\t\t...params.orderConfig.swiftOptions,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tbuilderParams: params.builderParams,\n\t\t\t\t\t\tpositionMaxLeverage: params.positionMaxLeverage,\n\t\t\t\t\t});\n\n\t\t\t\t\treturn swiftOrderResult;\n\t\t\t\t} else {\n\t\t\t\t\tconst txn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\torderConfig: {\n\t\t\t\t\t\t\torderType: 'limit',\n\t\t\t\t\t\t\tlimitPrice: params.orderConfig.limitPrice.val,\n\t\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\t},\n\t\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\t\tpostOnly: params.postOnly,\n\t\t\t\t\t\tuseSwift: false,\n\t\t\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t\t\t\tpositionMaxLeverage: params.positionMaxLeverage,\n\t\t\t\t\t});\n\n\t\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\t\t\t\treturn txSig;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcase 'takeProfit':\n\t\t\tcase 'stopLoss': {\n\t\t\t\tconst txn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\tamount: amountBN,\n\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\torderConfig: {\n\t\t\t\t\t\torderType: params.orderConfig.orderType,\n\t\t\t\t\t\ttriggerPrice: params.orderConfig.triggerPrice.val,\n\t\t\t\t\t\tlimitPrice: params.orderConfig.limitPrice?.val ?? ZERO,\n\t\t\t\t\t},\n\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\tuseSwift: false,\n\t\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t\t\tpositionMaxLeverage: params.positionMaxLeverage,\n\t\t\t\t});\n\n\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\t\t\treturn txSig;\n\t\t\t}\n\t\t\tcase 'oracleLimit': {\n\t\t\t\tconst txn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\tamount: amountBN,\n\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\torderConfig: {\n\t\t\t\t\t\torderType: 'oracleLimit',\n\t\t\t\t\t\toraclePriceOffset: params.orderConfig.oraclePriceOffset.val,\n\t\t\t\t\t},\n\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\tuseSwift: false,\n\t\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t\t\tpositionMaxLeverage: params.positionMaxLeverage,\n\t\t\t\t});\n\n\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\t\t\treturn txSig;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tconst _exhaustiveCheck: never = params.orderConfig;\n\t\t\t\tthrow new Error('Invalid order type');\n\t\t\t}\n\t\t}\n\t}\n\n\tasync getSwapQuote(\n\t\tparams: Omit<SwapParams, 'jupiterQuote'> & {\n\t\t\tslippageBps?: number;\n\t\t\tswapMode?: SwapMode;\n\t\t\tonlyDirectRoutes?: boolean;\n\t\t}\n\t): Promise<QuoteResponse> {\n\t\tconst jupiterClient = new JupiterClient({\n\t\t\tconnection: this.driftClient.connection,\n\t\t});\n\n\t\tconst inputMint = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tparams.fromMarketIndex\n\t\t).mint;\n\t\tconst outputMint = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tparams.toMarketIndex\n\t\t).mint;\n\n\t\tconst jupiterQuote = await jupiterClient.getQuote({\n\t\t\tinputMint,\n\t\t\toutputMint,\n\t\t\tamount: params.amount.val,\n\t\t\tslippageBps: params.slippageBps,\n\t\t\tswapMode: params.swapMode,\n\t\t\tonlyDirectRoutes: params.onlyDirectRoutes,\n\t\t});\n\n\t\treturn jupiterQuote;\n\t}\n\n\t/**\n\t * Executes a swap between two spot markets (placeholder for future implementation).\n\t *\n\t * This method will handle swapping between different spot markets through\n\t * the Drift protocol's swap functionality.\n\t *\n\t * @param params - The swap parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.executeSwap({\n\t * fromMarketIndex: 0, // USDC\n\t * toMarketIndex: 1, // SOL\n\t * amount: new BigNum(100),\n\t * subAccountId: 0,\n\t * minReceiveAmount: new BigNum(0.5)\n\t * });\n\t * ```\n\t */\n\tasync swap(params: SwapParams): Promise<TransactionSignature> {\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tparams.subAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst jupiterClient = new JupiterClient({\n\t\t\tconnection: this.driftClient.connection,\n\t\t});\n\n\t\tconst jupiterQuote = params.jupiterQuote\n\t\t\t? params.jupiterQuote\n\t\t\t: await this.getSwapQuote(params);\n\n\t\tconst swapTxn = await createSwapTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tjupiterClient,\n\t\t\tuser: accountData.userClient,\n\t\t\tswapFromMarketIndex: params.fromMarketIndex,\n\t\t\tswapToMarketIndex: params.toMarketIndex,\n\t\t\tamount: params.amount.val,\n\t\t\tquote: jupiterQuote,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(swapTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Settles P&L and funding for all perp position.\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.settlePnl({\n\t * subAccountId: 0,\n\t * marketIndex: 0, // SOL-PERP\n\t * counterpartySubAccountId: 1\n\t * });\n\t * ```\n\t */\n\tasync settleAccountPnl(\n\t\tparams: SettleAccountPnlParams\n\t): Promise<TransactionSignature> {\n\t\tconst { subAccountId } = params;\n\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst marketIndexes = accountData.openPerpPositions.map(\n\t\t\t(position) => position.marketIndex\n\t\t);\n\n\t\tconst settlePnlTxn = await createSettlePnlTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuser: accountData.userClient,\n\t\t\tmarketIndexes,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(settlePnlTxn);\n\n\t\treturn txSig;\n\t}\n\n\tasync cancelOrders(\n\t\tparams: CancelOrdersParams\n\t): Promise<TransactionSignature> {\n\t\tconst { subAccountId, orderIds } = params;\n\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst cancelOrdersTxn = await createCancelOrdersTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuser: accountData.userClient,\n\t\t\torderIds,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(cancelOrdersTxn);\n\n\t\treturn txSig;\n\t}\n}\n\n/**\n * TODO:\n * - transfer between subaccounts\n * - close position?\n * - close multiple positions\n * - edit open order\n * - create user only\n *\n * - open spot order\n * - rename subaccount\n * - withdraw dust positions\n */\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../src/drift/Drift/clients/AuthorityDrift/DriftOperations/types.ts"],"names":[],"mappings":"","sourcesContent":["import {\n\tBigNum,\n\tPositionDirection,\n\tPostOnlyParams,\n\tPublicKey,\n\tQuoteResponse,\n} from '@drift-labs/sdk';\nimport { OptionalAuctionParamsRequestInputs } from '../../../../base/actions/trade/openPerpOrder/dlobServer';\nimport { SwiftOrderOptions } from '../../../../base/actions/trade/openPerpOrder/openSwiftOrder';\n\n/**\n * Interface for deposit operation parameters.\n */\nexport interface DepositParams {\n\tsubAccountId: number;\n\tamount: BigNum;\n\tspotMarketIndex: number;\n\tisMaxBorrowRepayment?: boolean;\n}\n\n/**\n * Interface for withdraw operation parameters.\n */\nexport interface WithdrawParams {\n\tsubAccountId: number;\n\tamount: BigNum;\n\tspotMarketIndex: number;\n\tisBorrow?: boolean;\n\tisMax?: boolean;\n}\n\n/**\n * Interface for create user and deposit operation parameters.\n */\nexport interface CreateUserAndDepositParams {\n\tdepositAmount: BigNum;\n\tdepositSpotMarketIndex: number;\n\tnewAccountName?: string;\n\tmaxLeverage?: number;\n\tpoolId?: number;\n\tsubAccountId?: number;\n\treferrerName?: string;\n}\n\nexport interface CreateRevenueShareEscrowParams {\n\tnumOrders?: number;\n\tbuilder?: {\n\t\tbuilderAuthority: PublicKey;\n\t\tmaxFeeTenthBps: number;\n\t};\n}\n\n/**\n * Interface for perp market order parameters.\n */\nexport type PerpOrderParams = {\n\tsubAccountId: number;\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\tassetType: 'base' | 'quote';\n\tsize: BigNum;\n\treduceOnly?: boolean;\n\tpostOnly?: PostOnlyParams;\n\tisMaxLeverage?: boolean;\n\t/**\n\t * Optional builder code parameters for revenue sharing.\n\t * Only applicable for Swift orders for now (market and limit orders with Swift enabled).\n\t *\n\t * @example\n\t * ```typescript\n\t * builderParams: {\n\t * builderIdx: 0, // First builder in approved list\n\t * builderFeeTenthBps: 50 // 5 bps = 0.05%\n\t * }\n\t * ```\n\t */\n\tbuilderParams?: {\n\t\t/**\n\t\t * Index of the builder in the user's approved_builders list.\n\t\t */\n\t\tbuilderIdx: number;\n\t\t/**\n\t\t * Fee to charge for this order, in tenths of basis points.\n\t\t * Must be <= the builder's max_fee_tenth_bps.\n\t\t */\n\t\tbuilderFeeTenthBps: number;\n\t};\n\torderConfig:\n\t\t| {\n\t\t\t\torderType: 'market';\n\t\t\t\tdisableSwift?: boolean;\n\t\t\t\toptionalAuctionParamsInputs?: OptionalAuctionParamsRequestInputs;\n\t\t\t\tpostOnly?: never;\n\t\t\t\tbracketOrders?: {\n\t\t\t\t\ttakeProfitPrice?: BigNum;\n\t\t\t\t\tstopLossPrice?: BigNum;\n\t\t\t\t};\n\t\t\t\tswiftOptions?: Omit<SwiftOrderOptions, 'wallet' | 'swiftServerUrl'>;\n\t\t }\n\t\t| {\n\t\t\t\torderType: 'limit';\n\t\t\t\tlimitPrice: BigNum;\n\t\t\t\tdisableSwift?: boolean;\n\t\t\t\tbracketOrders?: {\n\t\t\t\t\ttakeProfitPrice?: BigNum;\n\t\t\t\t\tstopLossPrice?: BigNum;\n\t\t\t\t};\n\t\t\t\tswiftOptions?: Omit<SwiftOrderOptions, 'wallet' | 'swiftServerUrl'>;\n\t\t }\n\t\t| {\n\t\t\t\torderType: 'takeProfit' | 'stopLoss';\n\t\t\t\ttriggerPrice: BigNum;\n\t\t\t\tlimitPrice?: BigNum;\n\t\t }\n\t\t| {\n\t\t\t\torderType: 'oracleLimit';\n\t\t\t\toraclePriceOffset: BigNum;\n\t\t };\n};\n\n/**\n * Interface for swap operation parameters.\n */\nexport interface SwapParams {\n\tfromMarketIndex: number;\n\ttoMarketIndex: number;\n\tamount: BigNum;\n\tsubAccountId: number;\n\tjupiterQuote?: QuoteResponse;\n}\n\n/**\n * Interface for settle account P&Ls.\n */\nexport interface SettleAccountPnlParams {\n\tsubAccountId: number;\n}\n\nexport interface CancelOrdersParams {\n\tsubAccountId: number;\n\torderIds: number[];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../src/drift/Drift/clients/AuthorityDrift/DriftOperations/types.ts"],"names":[],"mappings":"","sourcesContent":["import {\n\tBigNum,\n\tPositionDirection,\n\tPostOnlyParams,\n\tPublicKey,\n\tQuoteResponse,\n} from '@drift-labs/sdk';\nimport { OptionalAuctionParamsRequestInputs } from '../../../../base/actions/trade/openPerpOrder/dlobServer';\nimport { SwiftOrderOptions } from '../../../../base/actions/trade/openPerpOrder/openSwiftOrder';\n\n/**\n * Interface for deposit operation parameters.\n */\nexport interface DepositParams {\n\tsubAccountId: number;\n\tamount: BigNum;\n\tspotMarketIndex: number;\n\tisMaxBorrowRepayment?: boolean;\n}\n\n/**\n * Interface for withdraw operation parameters.\n */\nexport interface WithdrawParams {\n\tsubAccountId: number;\n\tamount: BigNum;\n\tspotMarketIndex: number;\n\tisBorrow?: boolean;\n\tisMax?: boolean;\n}\n\n/**\n * Interface for create user and deposit operation parameters.\n */\nexport interface CreateUserAndDepositParams {\n\tdepositAmount: BigNum;\n\tdepositSpotMarketIndex: number;\n\tnewAccountName?: string;\n\tmaxLeverage?: number;\n\tpoolId?: number;\n\tsubAccountId?: number;\n\treferrerName?: string;\n}\n\nexport interface CreateRevenueShareEscrowParams {\n\tnumOrders?: number;\n\tbuilder?: {\n\t\tbuilderAuthority: PublicKey;\n\t\tmaxFeeTenthBps: number;\n\t};\n}\n\n/**\n * Interface for perp market order parameters.\n */\nexport type PerpOrderParams = {\n\tsubAccountId: number;\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\tassetType: 'base' | 'quote';\n\tsize: BigNum;\n\tpositionMaxLeverage: number;\n\treduceOnly?: boolean;\n\tpostOnly?: PostOnlyParams;\n\tisMaxLeverage?: boolean;\n\t/**\n\t * Optional builder code parameters for revenue sharing.\n\t * Only applicable for Swift orders for now (market and limit orders with Swift enabled).\n\t *\n\t * @example\n\t * ```typescript\n\t * builderParams: {\n\t * builderIdx: 0, // First builder in approved list\n\t * builderFeeTenthBps: 50 // 5 bps = 0.05%\n\t * }\n\t * ```\n\t */\n\tbuilderParams?: {\n\t\t/**\n\t\t * Index of the builder in the user's approved_builders list.\n\t\t */\n\t\tbuilderIdx: number;\n\t\t/**\n\t\t * Fee to charge for this order, in tenths of basis points.\n\t\t * Must be <= the builder's max_fee_tenth_bps.\n\t\t */\n\t\tbuilderFeeTenthBps: number;\n\t};\n\torderConfig:\n\t\t| {\n\t\t\t\torderType: 'market';\n\t\t\t\tdisableSwift?: boolean;\n\t\t\t\toptionalAuctionParamsInputs?: OptionalAuctionParamsRequestInputs;\n\t\t\t\tpostOnly?: never;\n\t\t\t\tbracketOrders?: {\n\t\t\t\t\ttakeProfitPrice?: BigNum;\n\t\t\t\t\tstopLossPrice?: BigNum;\n\t\t\t\t};\n\t\t\t\tswiftOptions?: Omit<SwiftOrderOptions, 'wallet' | 'swiftServerUrl'>;\n\t\t }\n\t\t| {\n\t\t\t\torderType: 'limit';\n\t\t\t\tlimitPrice: BigNum;\n\t\t\t\tdisableSwift?: boolean;\n\t\t\t\tbracketOrders?: {\n\t\t\t\t\ttakeProfitPrice?: BigNum;\n\t\t\t\t\tstopLossPrice?: BigNum;\n\t\t\t\t};\n\t\t\t\tswiftOptions?: Omit<SwiftOrderOptions, 'wallet' | 'swiftServerUrl'>;\n\t\t }\n\t\t| {\n\t\t\t\torderType: 'takeProfit' | 'stopLoss';\n\t\t\t\ttriggerPrice: BigNum;\n\t\t\t\tlimitPrice?: BigNum;\n\t\t }\n\t\t| {\n\t\t\t\torderType: 'oracleLimit';\n\t\t\t\toraclePriceOffset: BigNum;\n\t\t };\n};\n\n/**\n * Interface for swap operation parameters.\n */\nexport interface SwapParams {\n\tfromMarketIndex: number;\n\ttoMarketIndex: number;\n\tamount: BigNum;\n\tsubAccountId: number;\n\tjupiterQuote?: QuoteResponse;\n}\n\n/**\n * Interface for settle account P&Ls.\n */\nexport interface SettleAccountPnlParams {\n\tsubAccountId: number;\n}\n\nexport interface CancelOrdersParams {\n\tsubAccountId: number;\n\torderIds: number[];\n}\n"]}
|
|
@@ -9,7 +9,7 @@ import { Subscription } from 'rxjs';
|
|
|
9
9
|
import { EnhancedAccountData, UserAccountLookup } from '../../stores/UserAccountCache';
|
|
10
10
|
import { PriorityFeeSubscriberConfig } from '@drift-labs/sdk';
|
|
11
11
|
import { CreateUserAndDepositParams, DepositParams, WithdrawParams, PerpOrderParams, SwapParams, SettleAccountPnlParams, CancelOrdersParams, CreateRevenueShareEscrowParams } from './DriftOperations/types';
|
|
12
|
-
import { L2WithOracleAndMarketData } from '../../../../utils/orderbook';
|
|
12
|
+
import { L2WithOracleAndMarketData } from '../../../../utils/orderbook/types';
|
|
13
13
|
import { OrderbookGrouping } from '../../../../utils/dlob-server/DlobServerWebsocketUtils';
|
|
14
14
|
export interface AuthorityDriftConfig {
|
|
15
15
|
solanaRpcEndpoint: string;
|