@drift-labs/common 1.0.13 → 1.0.16
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 +82 -0
- package/lib/clients/DlobWebsocketClient.js +226 -0
- package/lib/clients/DlobWebsocketClient.js.map +1 -0
- package/lib/clients/swiftClient.js +1 -0
- package/lib/clients/swiftClient.js.map +1 -1
- package/lib/common-ui-utils/commonUiUtils.d.ts +22 -3
- package/lib/common-ui-utils/commonUiUtils.js +15 -8
- 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 +8 -1
- package/lib/common-ui-utils/order.js +3 -2
- 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 +58 -3
- 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/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 +3 -2
- package/lib/drift/Drift/clients/CentralServerDrift/index.js +52 -49
- 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/trade/editOrder.d.ts +3 -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 +3 -1
- package/lib/drift/base/actions/trade/openPerpOrder/auction.js +2 -2
- package/lib/drift/base/actions/trade/openPerpOrder/auction.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.d.ts +2 -6
- package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.d.ts +6 -3
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js +6 -6
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.d.ts +2 -0
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js +3 -2
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js +2 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.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/index.d.ts +1 -0
- package/lib/index.js +1 -0
- package/lib/index.js.map +1 -1
- package/lib/utils/MultiplexWebSocket.d.ts +4 -2
- package/lib/utils/MultiplexWebSocket.js +18 -9
- package/lib/utils/MultiplexWebSocket.js.map +1 -1
- package/lib/utils/ResultSlotIncrementer.d.ts +31 -0
- package/lib/utils/ResultSlotIncrementer.js +83 -0
- package/lib/utils/ResultSlotIncrementer.js.map +1 -0
- package/lib/utils/index.d.ts +3 -1
- package/lib/utils/index.js +7 -1
- package/lib/utils/index.js.map +1 -1
- package/lib/utils/math.js +1 -1
- package/lib/utils/math.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 -0
- package/lib/utils/signedMsgs.js +10 -0
- package/lib/utils/signedMsgs.js.map +1 -0
- package/package.json +1 -1
|
@@ -33,7 +33,7 @@ exports.createMultipleOpenPerpNonMarketOrderIx = createMultipleOpenPerpNonMarket
|
|
|
33
33
|
*/
|
|
34
34
|
const createOpenPerpNonMarketOrderIxs = async (params) => {
|
|
35
35
|
var _a, _b, _c, _d, _e, _f, _g, _h, _j;
|
|
36
|
-
const { driftClient, user, marketIndex, direction, reduceOnly = false, postOnly = sdk_1.PostOnlyParams.NONE, orderConfig, userOrderId = 0, positionMaxLeverage, mainSignerOverride, } = params;
|
|
36
|
+
const { driftClient, user, marketIndex, direction, reduceOnly = false, postOnly = sdk_1.PostOnlyParams.NONE, orderConfig, userOrderId = 0, positionMaxLeverage, mainSignerOverride, highLeverageOptions, } = params;
|
|
37
37
|
// Support both new (amount + assetType) and legacy (baseAssetAmount) approaches
|
|
38
38
|
const finalBaseAssetAmount = (0, orderParams_1.resolveBaseAssetAmount)({
|
|
39
39
|
amount: 'amount' in params ? params.amount : undefined,
|
|
@@ -82,6 +82,7 @@ const createOpenPerpNonMarketOrderIxs = async (params) => {
|
|
|
82
82
|
optionalAuctionParamsInputs: orderConfig.limitAuction.optionalLimitAuctionParams,
|
|
83
83
|
auctionDurationPercentage: orderConfig.limitAuction.usePlaceAndTake.auctionDurationPercentage,
|
|
84
84
|
referrerInfo: orderConfig.limitAuction.usePlaceAndTake.referrerInfo,
|
|
85
|
+
highLeverageOptions,
|
|
85
86
|
});
|
|
86
87
|
allIxs.push(placeAndTakeIx);
|
|
87
88
|
createdPlaceAndTakeIx = true;
|
|
@@ -111,7 +112,7 @@ const createOpenPerpNonMarketOrderIxs = async (params) => {
|
|
|
111
112
|
const totalQuoteAmount = finalBaseAssetAmount
|
|
112
113
|
.mul(oraclePrice)
|
|
113
114
|
.div(sdk_1.BASE_PRECISION);
|
|
114
|
-
const bitFlags = common_ui_utils_1.ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(marketIndex, driftClient, user, totalQuoteAmount, direction);
|
|
115
|
+
const bitFlags = common_ui_utils_1.ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(marketIndex, driftClient, user, totalQuoteAmount, direction, highLeverageOptions);
|
|
115
116
|
orderParams.bitFlags = bitFlags;
|
|
116
117
|
allOrders.push(orderParams);
|
|
117
118
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.ts"],"names":[],"mappings":";;;AAAA,yCAUyB;AAOzB,sDAG2B;AAC3B,kEAG0C;AAC1C,mDAAqD;AACrD,uEAAuE;AACvE,gEAA6E;AAQ7E,gEAA0E;AAC1E,wCAAwD;AAoDxD;;GAEG;AACI,MAAM,sCAAsC,GAAG,KAAK,EAAE,MAW5D,EAAmC,EAAE;IACrC,MAAM,EAAE,WAAW,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,GAAG,MAAM,CAAC;IAEvE,MAAM,WAAW,GAAG,kBAAkB,CAAC,GAAG,CAAC,uCAAyB,CAAC,CAAC;IAEtE,IAAI,MAAM,CAAC,qBAAqB,IAAI,WAAW,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;Q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WAAW,CAAC,gBAAgB,CACnE,YAAY,EACZ,MAAM,CAAC,QAAQ,CACf,CAAC;IAEF,OAAO,yBAAyB,CAAC;AAClC,CAAC,CAAC;AAbW,QAAA,+BAA+B,mCAa1C;AAEK,MAAM,4BAA4B,GAAG,KAAK,EAChD,MAAyE,EAC1C,EAAE;IACjC,MAAM,EAAE,YAAY,EAAE,QAAQ,EAAE,WAAW,EAAE,GAAG,MAAM,CAAC;IAEvD,wDAAwD;IACxD,IAAI,QAAQ,EAAE,CAAC;QACd,IAAI,WAAW,CAAC,SAAS,KAAK,OAAO,EAAE,CAAC;YACvC,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;QAC/D,CAAC;QAED,IAAI,CAAC,YAAY,EAAE,CAAC;YACnB,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;QACnE,CAAC;QAED,IACC,MAAM,CAAC,QAAQ;YACf,CAAC,kBAAU,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,EAAE,oBAAc,CAAC,IAAI,CAAC,EACtD,CAAC;YACF,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;QAClE,CAAC;QAED,MAAM,gBAAgB,GAAG,MAAM,IAAA,6BAAqB,EAAC;YACpD,GAAG,MAAM;YACT,YAAY;YACZ,WAAW;SACX,CAAC,CAAC;QAEH,OAAO,gBAAuC,CAAC;IAChD,CAAC;IAED,MAAM,cAAc,GAAG,MAAM,IAAA,uCAA+B,EAAC,MAAM,CAAC,CAAC;IAErE,OAAO,cAAqC,CAAC;AAC9C,CAAC,CAAC;AAlCW,QAAA,4BAA4B,gCAkCvC","sourcesContent":["import {\n\tDriftClient,\n\tUser,\n\tBN,\n\tMarketType,\n\tPostOnlyParams,\n\tOptionalOrderParams,\n\tPositionDirection,\n\tOrderParamsBitFlag,\n\tBASE_PRECISION,\n} from '@drift-labs/sdk';\nimport {\n\tPublicKey,\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport {\n\tprepSignAndSendSwiftOrder,\n\tSwiftOrderOptions,\n} from '../openSwiftOrder';\nimport {\n\tbuildNonMarketOrderParams,\n\tresolveBaseAssetAmount,\n} from '../../../../../utils/orderParams';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport { ORDER_COMMON_UTILS } from '../../../../../../common-ui-utils';\nimport { createPlaceAndTakePerpMarketOrderIx } from '../openPerpMarketOrder';\nimport {\n\tTxnOrSwiftResult,\n\tLimitAuctionConfig,\n\tLimitOrderParamsOrderConfig,\n\tNonMarketOrderParamsConfig,\n} from '../types';\nimport { WithTxnParams } from '../../../../types';\nimport { getPositionMaxLeverageIxIfNeeded } from '../positionMaxLeverage';\nimport { getLimitAuctionOrderParams } from '../auction';\n\nexport interface OpenPerpNonMarketOrderBaseParams\n\textends Omit<NonMarketOrderParamsConfig, 'marketType' | 'baseAssetAmount'> {\n\tdriftClient: DriftClient;\n\tuser: User;\n\t// Either new approach\n\tamount?: BN;\n\tassetType?: 'base' | 'quote';\n\t// Or legacy approach\n\tbaseAssetAmount?: BN;\n\t// Common optional params\n\treduceOnly?: boolean;\n\tpostOnly?: PostOnlyParams;\n\tuserOrderId?: number;\n\tautoEnterHighLeverageModeBufferPct?: number;\n\t/**\n\t * If provided, will override the main signer for the order. Otherwise, the main signer will be the user's authority.\n\t * This is only applicable for non-SWIFT orders.\n\t */\n\tmainSignerOverride?: PublicKey;\n\t/**\n\t * Optional builder code parameters for revenue sharing.\n\t * Only applicable for Swift orders for now.\n\t */\n\tbuilderParams?: {\n\t\tbuilderIdx: number;\n\t\tbuilderFeeTenthBps: number;\n\t};\n}\n\nexport interface OpenPerpNonMarketOrderParamsWithSwift\n\textends OpenPerpNonMarketOrderBaseParams {\n\tswiftOptions: SwiftOrderOptions;\n}\n\nexport type OpenPerpNonMarketOrderParams<\n\tT extends boolean = boolean,\n\tS extends Omit<SwiftOrderOptions, 'swiftServerUrl'> = Omit<\n\t\tSwiftOrderOptions,\n\t\t'swiftServerUrl'\n\t>\n> = T extends true\n\t? OpenPerpNonMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tswiftOptions: S;\n\t }\n\t: OpenPerpNonMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tswiftOptions?: never;\n\t };\n\n/**\n * Creates a transaction instruction to open multiple non-market orders.\n */\nexport const createMultipleOpenPerpNonMarketOrderIx = async (params: {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\torderParamsConfigs: NonMarketOrderParamsConfig[];\n\tenterHighLeverageMode?: boolean;\n\t/**\n\t * If provided, will override the main signer for the order. Otherwise, the main signer will be the user's authority.\n\t */\n\tmainSignerOverride?: PublicKey;\n}): Promise<TransactionInstruction> => {\n\tconst { driftClient, orderParamsConfigs, mainSignerOverride } = params;\n\n\tconst orderParams = orderParamsConfigs.map(buildNonMarketOrderParams);\n\n\tif (params.enterHighLeverageMode && orderParams.length > 0) {\n\t\torderParams[0].bitFlags = OrderParamsBitFlag.UpdateHighLeverageMode;\n\t}\n\n\tconst placeOrderIx = await driftClient.getPlaceOrdersIx(\n\t\torderParams,\n\t\tundefined,\n\t\t{\n\t\t\tauthority: mainSignerOverride,\n\t\t}\n\t);\n\treturn placeOrderIx;\n};\n\n/**\n * Creates a transaction instruction to open a non-market order.\n * Allows for bracket orders to be opened in the same transaction.\n *\n * If `limitAuction` is enabled, a placeAndTake order is created to simulate a market auction order,\n * with the end price being the limit price.\n */\nexport const createOpenPerpNonMarketOrderIxs = async (\n\tparams: OpenPerpNonMarketOrderBaseParams\n): Promise<TransactionInstruction[]> => {\n\tconst {\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\tdirection,\n\t\treduceOnly = false,\n\t\tpostOnly = PostOnlyParams.NONE,\n\t\torderConfig,\n\t\tuserOrderId = 0,\n\t\tpositionMaxLeverage,\n\t\tmainSignerOverride,\n\t} = params;\n\t// Support both new (amount + assetType) and legacy (baseAssetAmount) approaches\n\tconst finalBaseAssetAmount = resolveBaseAssetAmount({\n\t\tamount: 'amount' in params ? params.amount : undefined,\n\t\tassetType: 'assetType' in params ? params.assetType : undefined,\n\t\tbaseAssetAmount:\n\t\t\t'baseAssetAmount' in params ? params.baseAssetAmount : undefined,\n\t\tlimitPrice:\n\t\t\t'limitPrice' in params.orderConfig\n\t\t\t\t? params.orderConfig.limitPrice\n\t\t\t\t: undefined,\n\t});\n\n\tif (!finalBaseAssetAmount || finalBaseAssetAmount.isZero()) {\n\t\tthrow new Error('Final base asset amount must be greater than zero');\n\t}\n\n\tconst allOrders: OptionalOrderParams[] = [];\n\tconst allIxs: TransactionInstruction[] = [];\n\n\tconst leverageIx = await getPositionMaxLeverageIxIfNeeded(\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\tpositionMaxLeverage\n\t);\n\tif (leverageIx) {\n\t\tallIxs.push(leverageIx);\n\t}\n\n\t// handle limit auction\n\tif (\n\t\torderConfig.orderType === 'limit' &&\n\t\torderConfig.limitAuction?.enable &&\n\t\tENUM_UTILS.match(postOnly, PostOnlyParams.NONE)\n\t) {\n\t\tconst limitAuctionOrderParams = await getLimitAuctionOrderParams({\n\t\t\t...params,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\torderConfig: orderConfig as LimitOrderParamsOrderConfig & {\n\t\t\t\tlimitAuction: LimitAuctionConfig;\n\t\t\t},\n\t\t});\n\n\t\tlet createdPlaceAndTakeIx = false;\n\n\t\t// if it is a limit auction order, we create a placeAndTake order to simulate a market order.\n\t\t// this is useful when a limit order is crossing, and we want to achieve the best fill price through a placeAndTake.\n\t\t// falls back to limit order with auction params if the placeAndTake order creation fails\n\t\tif (\n\t\t\tlimitAuctionOrderParams.auctionDuration &&\n\t\t\tlimitAuctionOrderParams.auctionDuration > 0 &&\n\t\t\torderConfig.limitAuction?.usePlaceAndTake?.enable\n\t\t) {\n\t\t\ttry {\n\t\t\t\tconst placeAndTakeIx = await createPlaceAndTakePerpMarketOrderIx({\n\t\t\t\t\tassetType: 'base',\n\t\t\t\t\tamount: finalBaseAssetAmount,\n\t\t\t\t\tdirection,\n\t\t\t\t\tdlobServerHttpUrl: orderConfig.limitAuction.dlobServerHttpUrl,\n\t\t\t\t\tmarketIndex,\n\t\t\t\t\tdriftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tuserOrderId,\n\t\t\t\t\toptionalAuctionParamsInputs:\n\t\t\t\t\t\torderConfig.limitAuction.optionalLimitAuctionParams,\n\t\t\t\t\tauctionDurationPercentage:\n\t\t\t\t\t\torderConfig.limitAuction.usePlaceAndTake.auctionDurationPercentage,\n\t\t\t\t\treferrerInfo: orderConfig.limitAuction.usePlaceAndTake.referrerInfo,\n\t\t\t\t});\n\t\t\t\tallIxs.push(placeAndTakeIx);\n\t\t\t\tcreatedPlaceAndTakeIx = true;\n\t\t\t} catch (e) {\n\t\t\t\tconsole.error(\n\t\t\t\t\t'Failed to create placeAndTake order for limit auction order',\n\t\t\t\t\te\n\t\t\t\t);\n\t\t\t\tcreatedPlaceAndTakeIx = false;\n\t\t\t}\n\t\t}\n\n\t\t// fallback to normal limit order with auction params\n\t\tif (!createdPlaceAndTakeIx) {\n\t\t\tallOrders.push(limitAuctionOrderParams);\n\t\t}\n\t} else {\n\t\tconst orderParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\torderConfig,\n\t\t\treduceOnly,\n\t\t\tpostOnly,\n\t\t\tuserOrderId,\n\t\t});\n\n\t\tconst oraclePrice =\n\t\t\tdriftClient.getOracleDataForPerpMarket(marketIndex).price;\n\t\tconst totalQuoteAmount = finalBaseAssetAmount\n\t\t\t.mul(oraclePrice)\n\t\t\t.div(BASE_PRECISION);\n\n\t\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\t\tmarketIndex,\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\ttotalQuoteAmount,\n\t\t\tdirection\n\t\t);\n\t\torderParams.bitFlags = bitFlags;\n\n\t\tallOrders.push(orderParams);\n\t}\n\n\tconst bracketOrdersDirection = ENUM_UTILS.match(\n\t\tdirection,\n\t\tPositionDirection.LONG\n\t)\n\t\t? PositionDirection.SHORT\n\t\t: PositionDirection.LONG;\n\n\tif ('bracketOrders' in orderConfig && orderConfig.bracketOrders?.takeProfit) {\n\t\tconst takeProfitParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount:\n\t\t\t\torderConfig.bracketOrders.takeProfit.baseAssetAmount ??\n\t\t\t\tfinalBaseAssetAmount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'takeProfit',\n\t\t\t\ttriggerPrice: orderConfig.bracketOrders.takeProfit.triggerPrice,\n\t\t\t\tlimitPrice: orderConfig.bracketOrders.takeProfit.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: orderConfig.bracketOrders.takeProfit.reduceOnly ?? true,\n\t\t});\n\t\tallOrders.push(takeProfitParams);\n\t}\n\n\tif ('bracketOrders' in orderConfig && orderConfig.bracketOrders?.stopLoss) {\n\t\tconst stopLossParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount:\n\t\t\t\torderConfig.bracketOrders.stopLoss.baseAssetAmount ??\n\t\t\t\tfinalBaseAssetAmount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'stopLoss',\n\t\t\t\ttriggerPrice: orderConfig.bracketOrders.stopLoss.triggerPrice,\n\t\t\t\tlimitPrice: orderConfig.bracketOrders.stopLoss.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: orderConfig.bracketOrders.stopLoss.reduceOnly ?? true,\n\t\t});\n\t\tallOrders.push(stopLossParams);\n\t}\n\n\tif (allOrders.length > 0) {\n\t\tconst placeOrderIx = await driftClient.getPlaceOrdersIx(\n\t\t\tallOrders,\n\t\t\tundefined,\n\t\t\t{\n\t\t\t\tauthority: mainSignerOverride,\n\t\t\t}\n\t\t);\n\t\tallIxs.push(placeOrderIx);\n\t}\n\n\treturn allIxs;\n};\n\nexport const MINIMUM_SWIFT_LIMIT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 35;\n\nexport const createSwiftLimitOrder = async (\n\tparams: OpenPerpNonMarketOrderParamsWithSwift & {\n\t\torderConfig: LimitOrderParamsOrderConfig;\n\t}\n): Promise<void> => {\n\tconst { driftClient, user, marketIndex, swiftOptions, orderConfig } = params;\n\n\tconst limitPrice = orderConfig.limitPrice;\n\n\tif (limitPrice.isZero()) {\n\t\tthrow new Error('LIMIT orders require limitPrice');\n\t}\n\n\t// Support both new (amount + assetType) and legacy (baseAssetAmount) approaches\n\tconst finalBaseAssetAmount = resolveBaseAssetAmount({\n\t\tamount: 'amount' in params ? params.amount : undefined,\n\t\tassetType: 'assetType' in params ? params.assetType : undefined,\n\t\tbaseAssetAmount:\n\t\t\t'baseAssetAmount' in params ? params.baseAssetAmount : undefined,\n\t\tlimitPrice,\n\t});\n\n\tconst orderParams = orderConfig.limitAuction?.enable\n\t\t? await getLimitAuctionOrderParams({\n\t\t\t\t...params,\n\t\t\t\tmarketType: MarketType.PERP,\n\t\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\t\torderConfig: orderConfig as LimitOrderParamsOrderConfig & {\n\t\t\t\t\tlimitAuction: LimitAuctionConfig;\n\t\t\t\t},\n\t\t })\n\t\t: buildNonMarketOrderParams({\n\t\t\t\tmarketIndex,\n\t\t\t\tmarketType: MarketType.PERP,\n\t\t\t\tdirection: params.direction,\n\t\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\t\torderConfig,\n\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\tpostOnly: params.postOnly,\n\t\t\t\tuserOrderId: params.userOrderId,\n\t\t });\n\n\tconst userAccount = user.getUserAccount();\n\tconst slotBuffer = Math.max(\n\t\t(swiftOptions.signedMessageOrderSlotBuffer || 0) +\n\t\t\t(orderParams.auctionDuration || 0),\n\t\tMINIMUM_SWIFT_LIMIT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS\n\t); // limit orders require a much larger buffer, to replace the auction duration usually found in market orders\n\n\tawait prepSignAndSendSwiftOrder({\n\t\tdriftClient,\n\t\tsubAccountId: userAccount.subAccountId,\n\t\tuserAccountPubKey: user.userAccountPublicKey,\n\t\tmarketIndex,\n\t\tslotBuffer,\n\t\tswiftOptions,\n\t\torderParams: {\n\t\t\tmain: orderParams,\n\t\t\ttakeProfit: orderConfig.bracketOrders?.takeProfit,\n\t\t\tstopLoss: orderConfig.bracketOrders?.stopLoss,\n\t\t\tpositionMaxLeverage: params.positionMaxLeverage,\n\t\t},\n\t\tbuilderParams: params.builderParams,\n\t});\n};\n\nexport const createOpenPerpNonMarketOrderTxn = async (\n\tparams: WithTxnParams<OpenPerpNonMarketOrderBaseParams>\n): Promise<Transaction | VersionedTransaction> => {\n\tconst { driftClient } = params;\n\n\tconst instructions = await createOpenPerpNonMarketOrderIxs(params);\n\n\tconst openPerpNonMarketOrderTxn = await driftClient.buildTransaction(\n\t\tinstructions,\n\t\tparams.txParams\n\t);\n\n\treturn openPerpNonMarketOrderTxn;\n};\n\nexport const createOpenPerpNonMarketOrder = async <T extends boolean>(\n\tparams: WithTxnParams<OpenPerpNonMarketOrderParams<T, SwiftOrderOptions>>\n): Promise<TxnOrSwiftResult<T>> => {\n\tconst { swiftOptions, useSwift, orderConfig } = params;\n\n\t// If useSwift is true, return the Swift result directly\n\tif (useSwift) {\n\t\tif (orderConfig.orderType !== 'limit') {\n\t\t\tthrow new Error('Only limit orders are supported with Swift');\n\t\t}\n\n\t\tif (!swiftOptions) {\n\t\t\tthrow new Error('swiftOptions is required when useSwift is true');\n\t\t}\n\n\t\tif (\n\t\t\tparams.postOnly &&\n\t\t\t!ENUM_UTILS.match(params.postOnly, PostOnlyParams.NONE)\n\t\t) {\n\t\t\tthrow new Error('Post only orders are not supported with Swift');\n\t\t}\n\n\t\tconst swiftOrderResult = await createSwiftLimitOrder({\n\t\t\t...params,\n\t\t\tswiftOptions,\n\t\t\torderConfig,\n\t\t});\n\n\t\treturn swiftOrderResult as TxnOrSwiftResult<T>;\n\t}\n\n\tconst marketOrderTxn = await createOpenPerpNonMarketOrderTxn(params);\n\n\treturn marketOrderTxn as TxnOrSwiftResult<T>;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.ts"],"names":[],"mappings":";;;AAAA,yCAUyB;AAOzB,sDAG2B;AAC3B,kEAG0C;AAC1C,mDAAqD;AACrD,uEAG2C;AAC3C,gEAA6E;AAQ7E,gEAA0E;AAC1E,wCAAwD;AAqDxD;;GAEG;AACI,MAAM,sCAAsC,GAAG,KAAK,EAAE,MAW5D,EAAmC,EAAE;IACrC,MAAM,EAAE,WAAW,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,GAAG,MAAM,CAAC;IAEvE,MAAM,WAAW,GAAG,kBAAkB,CAAC,GAAG,CAAC,uCAAyB,CAAC,CAAC;IAEtE,IAAI,MAAM,CAAC,qBAAqB,IAAI,WAAW,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC5D,WAAW,CAAC,CAAC,CAAC,CAAC,QAAQ,GAAG,wBAAkB,CAAC,sBAAsB,CAAC;IACrE,CAAC;IAED,MAAM,YAAY,GAAG,MAAM,WAAW,CAAC,gBAAgB,CACtD,WAAW,EACX,SAAS,EACT;QACC,SAAS,EAAE,kBAAkB;KAC7B,CACD,CAAC;IACF,OAAO,YAAY,CAAC;AACrB,CAAC,CAAC;AA5BW,QAAA,sCAAsC,0CA4BjD;AAEF;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WAAW,EAAE,GAAG,MAAM,CAAC;IAEvD,wDAAwD;IACxD,IAAI,QAAQ,EAAE,CAAC;QACd,IAAI,WAAW,CAAC,SAAS,KAAK,OAAO,EAAE,CAAC;YACvC,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;QAC/D,CAAC;QAED,IAAI,CAAC,YAAY,EAAE,CAAC;YACnB,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;QACnE,CAAC;QAED,IACC,MAAM,CAAC,QAAQ;YACf,CAAC,kBAAU,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,EAAE,oBAAc,CAAC,IAAI,CAAC,EACtD,CAAC;YACF,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;QAClE,CAAC;QAED,MAAM,gBAAgB,GAAG,MAAM,IAAA,6BAAqB,EAAC;YACpD,GAAG,MAAM;YACT,YAAY;YACZ,WAAW;SACX,CAAC,CAAC;QAEH,OAAO,gBAAuC,CAAC;IAChD,CAAC;IAED,MAAM,cAAc,GAAG,MAAM,IAAA,uCAA+B,EAAC,MAAM,CAAC,CAAC;IAErE,OAAO,cAAqC,CAAC;AAC9C,CAAC,CAAC;AAlCW,QAAA,4BAA4B,gCAkCvC","sourcesContent":["import {\n\tDriftClient,\n\tUser,\n\tBN,\n\tMarketType,\n\tPostOnlyParams,\n\tOptionalOrderParams,\n\tPositionDirection,\n\tOrderParamsBitFlag,\n\tBASE_PRECISION,\n} from '@drift-labs/sdk';\nimport {\n\tPublicKey,\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport {\n\tprepSignAndSendSwiftOrder,\n\tSwiftOrderOptions,\n} from '../openSwiftOrder';\nimport {\n\tbuildNonMarketOrderParams,\n\tresolveBaseAssetAmount,\n} from '../../../../../utils/orderParams';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport {\n\tHighLeverageOptions,\n\tORDER_COMMON_UTILS,\n} from '../../../../../../common-ui-utils';\nimport { createPlaceAndTakePerpMarketOrderIx } from '../openPerpMarketOrder';\nimport {\n\tTxnOrSwiftResult,\n\tLimitAuctionConfig,\n\tLimitOrderParamsOrderConfig,\n\tNonMarketOrderParamsConfig,\n} from '../types';\nimport { WithTxnParams } from '../../../../types';\nimport { getPositionMaxLeverageIxIfNeeded } from '../positionMaxLeverage';\nimport { getLimitAuctionOrderParams } from '../auction';\n\nexport interface OpenPerpNonMarketOrderBaseParams\n\textends Omit<NonMarketOrderParamsConfig, 'marketType' | 'baseAssetAmount'> {\n\tdriftClient: DriftClient;\n\tuser: User;\n\t// Either new approach\n\tamount?: BN;\n\tassetType?: 'base' | 'quote';\n\t// Or legacy approach\n\tbaseAssetAmount?: BN;\n\t// Common optional params\n\treduceOnly?: boolean;\n\tpostOnly?: PostOnlyParams;\n\tuserOrderId?: number;\n\tautoEnterHighLeverageModeBufferPct?: number;\n\t/**\n\t * If provided, will override the main signer for the order. Otherwise, the main signer will be the user's authority.\n\t * This is only applicable for non-SWIFT orders.\n\t */\n\tmainSignerOverride?: PublicKey;\n\t/**\n\t * Optional builder code parameters for revenue sharing.\n\t * Only applicable for Swift orders for now.\n\t */\n\tbuilderParams?: {\n\t\tbuilderIdx: number;\n\t\tbuilderFeeTenthBps: number;\n\t};\n\thighLeverageOptions?: HighLeverageOptions;\n}\n\nexport interface OpenPerpNonMarketOrderParamsWithSwift\n\textends OpenPerpNonMarketOrderBaseParams {\n\tswiftOptions: SwiftOrderOptions;\n}\n\nexport type OpenPerpNonMarketOrderParams<\n\tT extends boolean = boolean,\n\tS extends Omit<SwiftOrderOptions, 'swiftServerUrl'> = Omit<\n\t\tSwiftOrderOptions,\n\t\t'swiftServerUrl'\n\t>\n> = T extends true\n\t? OpenPerpNonMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tswiftOptions: S;\n\t }\n\t: OpenPerpNonMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tswiftOptions?: never;\n\t };\n\n/**\n * Creates a transaction instruction to open multiple non-market orders.\n */\nexport const createMultipleOpenPerpNonMarketOrderIx = async (params: {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\torderParamsConfigs: NonMarketOrderParamsConfig[];\n\tenterHighLeverageMode?: boolean;\n\t/**\n\t * If provided, will override the main signer for the order. Otherwise, the main signer will be the user's authority.\n\t */\n\tmainSignerOverride?: PublicKey;\n}): Promise<TransactionInstruction> => {\n\tconst { driftClient, orderParamsConfigs, mainSignerOverride } = params;\n\n\tconst orderParams = orderParamsConfigs.map(buildNonMarketOrderParams);\n\n\tif (params.enterHighLeverageMode && orderParams.length > 0) {\n\t\torderParams[0].bitFlags = OrderParamsBitFlag.UpdateHighLeverageMode;\n\t}\n\n\tconst placeOrderIx = await driftClient.getPlaceOrdersIx(\n\t\torderParams,\n\t\tundefined,\n\t\t{\n\t\t\tauthority: mainSignerOverride,\n\t\t}\n\t);\n\treturn placeOrderIx;\n};\n\n/**\n * Creates a transaction instruction to open a non-market order.\n * Allows for bracket orders to be opened in the same transaction.\n *\n * If `limitAuction` is enabled, a placeAndTake order is created to simulate a market auction order,\n * with the end price being the limit price.\n */\nexport const createOpenPerpNonMarketOrderIxs = async (\n\tparams: OpenPerpNonMarketOrderBaseParams\n): Promise<TransactionInstruction[]> => {\n\tconst {\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\tdirection,\n\t\treduceOnly = false,\n\t\tpostOnly = PostOnlyParams.NONE,\n\t\torderConfig,\n\t\tuserOrderId = 0,\n\t\tpositionMaxLeverage,\n\t\tmainSignerOverride,\n\t\thighLeverageOptions,\n\t} = params;\n\t// Support both new (amount + assetType) and legacy (baseAssetAmount) approaches\n\tconst finalBaseAssetAmount = resolveBaseAssetAmount({\n\t\tamount: 'amount' in params ? params.amount : undefined,\n\t\tassetType: 'assetType' in params ? params.assetType : undefined,\n\t\tbaseAssetAmount:\n\t\t\t'baseAssetAmount' in params ? params.baseAssetAmount : undefined,\n\t\tlimitPrice:\n\t\t\t'limitPrice' in params.orderConfig\n\t\t\t\t? params.orderConfig.limitPrice\n\t\t\t\t: undefined,\n\t});\n\n\tif (!finalBaseAssetAmount || finalBaseAssetAmount.isZero()) {\n\t\tthrow new Error('Final base asset amount must be greater than zero');\n\t}\n\n\tconst allOrders: OptionalOrderParams[] = [];\n\tconst allIxs: TransactionInstruction[] = [];\n\n\tconst leverageIx = await getPositionMaxLeverageIxIfNeeded(\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\tpositionMaxLeverage\n\t);\n\tif (leverageIx) {\n\t\tallIxs.push(leverageIx);\n\t}\n\n\t// handle limit auction\n\tif (\n\t\torderConfig.orderType === 'limit' &&\n\t\torderConfig.limitAuction?.enable &&\n\t\tENUM_UTILS.match(postOnly, PostOnlyParams.NONE)\n\t) {\n\t\tconst limitAuctionOrderParams = await getLimitAuctionOrderParams({\n\t\t\t...params,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\torderConfig: orderConfig as LimitOrderParamsOrderConfig & {\n\t\t\t\tlimitAuction: LimitAuctionConfig;\n\t\t\t},\n\t\t});\n\n\t\tlet createdPlaceAndTakeIx = false;\n\n\t\t// if it is a limit auction order, we create a placeAndTake order to simulate a market order.\n\t\t// this is useful when a limit order is crossing, and we want to achieve the best fill price through a placeAndTake.\n\t\t// falls back to limit order with auction params if the placeAndTake order creation fails\n\t\tif (\n\t\t\tlimitAuctionOrderParams.auctionDuration &&\n\t\t\tlimitAuctionOrderParams.auctionDuration > 0 &&\n\t\t\torderConfig.limitAuction?.usePlaceAndTake?.enable\n\t\t) {\n\t\t\ttry {\n\t\t\t\tconst placeAndTakeIx = await createPlaceAndTakePerpMarketOrderIx({\n\t\t\t\t\tassetType: 'base',\n\t\t\t\t\tamount: finalBaseAssetAmount,\n\t\t\t\t\tdirection,\n\t\t\t\t\tdlobServerHttpUrl: orderConfig.limitAuction.dlobServerHttpUrl,\n\t\t\t\t\tmarketIndex,\n\t\t\t\t\tdriftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tuserOrderId,\n\t\t\t\t\toptionalAuctionParamsInputs:\n\t\t\t\t\t\torderConfig.limitAuction.optionalLimitAuctionParams,\n\t\t\t\t\tauctionDurationPercentage:\n\t\t\t\t\t\torderConfig.limitAuction.usePlaceAndTake.auctionDurationPercentage,\n\t\t\t\t\treferrerInfo: orderConfig.limitAuction.usePlaceAndTake.referrerInfo,\n\t\t\t\t\thighLeverageOptions,\n\t\t\t\t});\n\t\t\t\tallIxs.push(placeAndTakeIx);\n\t\t\t\tcreatedPlaceAndTakeIx = true;\n\t\t\t} catch (e) {\n\t\t\t\tconsole.error(\n\t\t\t\t\t'Failed to create placeAndTake order for limit auction order',\n\t\t\t\t\te\n\t\t\t\t);\n\t\t\t\tcreatedPlaceAndTakeIx = false;\n\t\t\t}\n\t\t}\n\n\t\t// fallback to normal limit order with auction params\n\t\tif (!createdPlaceAndTakeIx) {\n\t\t\tallOrders.push(limitAuctionOrderParams);\n\t\t}\n\t} else {\n\t\tconst orderParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\torderConfig,\n\t\t\treduceOnly,\n\t\t\tpostOnly,\n\t\t\tuserOrderId,\n\t\t});\n\n\t\tconst oraclePrice =\n\t\t\tdriftClient.getOracleDataForPerpMarket(marketIndex).price;\n\t\tconst totalQuoteAmount = finalBaseAssetAmount\n\t\t\t.mul(oraclePrice)\n\t\t\t.div(BASE_PRECISION);\n\n\t\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\t\tmarketIndex,\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\ttotalQuoteAmount,\n\t\t\tdirection,\n\t\t\thighLeverageOptions\n\t\t);\n\t\torderParams.bitFlags = bitFlags;\n\n\t\tallOrders.push(orderParams);\n\t}\n\n\tconst bracketOrdersDirection = ENUM_UTILS.match(\n\t\tdirection,\n\t\tPositionDirection.LONG\n\t)\n\t\t? PositionDirection.SHORT\n\t\t: PositionDirection.LONG;\n\n\tif ('bracketOrders' in orderConfig && orderConfig.bracketOrders?.takeProfit) {\n\t\tconst takeProfitParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount:\n\t\t\t\torderConfig.bracketOrders.takeProfit.baseAssetAmount ??\n\t\t\t\tfinalBaseAssetAmount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'takeProfit',\n\t\t\t\ttriggerPrice: orderConfig.bracketOrders.takeProfit.triggerPrice,\n\t\t\t\tlimitPrice: orderConfig.bracketOrders.takeProfit.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: orderConfig.bracketOrders.takeProfit.reduceOnly ?? true,\n\t\t});\n\t\tallOrders.push(takeProfitParams);\n\t}\n\n\tif ('bracketOrders' in orderConfig && orderConfig.bracketOrders?.stopLoss) {\n\t\tconst stopLossParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount:\n\t\t\t\torderConfig.bracketOrders.stopLoss.baseAssetAmount ??\n\t\t\t\tfinalBaseAssetAmount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'stopLoss',\n\t\t\t\ttriggerPrice: orderConfig.bracketOrders.stopLoss.triggerPrice,\n\t\t\t\tlimitPrice: orderConfig.bracketOrders.stopLoss.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: orderConfig.bracketOrders.stopLoss.reduceOnly ?? true,\n\t\t});\n\t\tallOrders.push(stopLossParams);\n\t}\n\n\tif (allOrders.length > 0) {\n\t\tconst placeOrderIx = await driftClient.getPlaceOrdersIx(\n\t\t\tallOrders,\n\t\t\tundefined,\n\t\t\t{\n\t\t\t\tauthority: mainSignerOverride,\n\t\t\t}\n\t\t);\n\t\tallIxs.push(placeOrderIx);\n\t}\n\n\treturn allIxs;\n};\n\nexport const MINIMUM_SWIFT_LIMIT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 35;\n\nexport const createSwiftLimitOrder = async (\n\tparams: OpenPerpNonMarketOrderParamsWithSwift & {\n\t\torderConfig: LimitOrderParamsOrderConfig;\n\t}\n): Promise<void> => {\n\tconst { driftClient, user, marketIndex, swiftOptions, orderConfig } = params;\n\n\tconst limitPrice = orderConfig.limitPrice;\n\n\tif (limitPrice.isZero()) {\n\t\tthrow new Error('LIMIT orders require limitPrice');\n\t}\n\n\t// Support both new (amount + assetType) and legacy (baseAssetAmount) approaches\n\tconst finalBaseAssetAmount = resolveBaseAssetAmount({\n\t\tamount: 'amount' in params ? params.amount : undefined,\n\t\tassetType: 'assetType' in params ? params.assetType : undefined,\n\t\tbaseAssetAmount:\n\t\t\t'baseAssetAmount' in params ? params.baseAssetAmount : undefined,\n\t\tlimitPrice,\n\t});\n\n\tconst orderParams = orderConfig.limitAuction?.enable\n\t\t? await getLimitAuctionOrderParams({\n\t\t\t\t...params,\n\t\t\t\tmarketType: MarketType.PERP,\n\t\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\t\torderConfig: orderConfig as LimitOrderParamsOrderConfig & {\n\t\t\t\t\tlimitAuction: LimitAuctionConfig;\n\t\t\t\t},\n\t\t })\n\t\t: buildNonMarketOrderParams({\n\t\t\t\tmarketIndex,\n\t\t\t\tmarketType: MarketType.PERP,\n\t\t\t\tdirection: params.direction,\n\t\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\t\torderConfig,\n\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\tpostOnly: params.postOnly,\n\t\t\t\tuserOrderId: params.userOrderId,\n\t\t });\n\n\tconst userAccount = user.getUserAccount();\n\tconst slotBuffer = Math.max(\n\t\t(swiftOptions.signedMessageOrderSlotBuffer || 0) +\n\t\t\t(orderParams.auctionDuration || 0),\n\t\tMINIMUM_SWIFT_LIMIT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS\n\t); // limit orders require a much larger buffer, to replace the auction duration usually found in market orders\n\n\tawait prepSignAndSendSwiftOrder({\n\t\tdriftClient,\n\t\tsubAccountId: userAccount.subAccountId,\n\t\tuserAccountPubKey: user.userAccountPublicKey,\n\t\tmarketIndex,\n\t\tslotBuffer,\n\t\tswiftOptions,\n\t\torderParams: {\n\t\t\tmain: orderParams,\n\t\t\ttakeProfit: orderConfig.bracketOrders?.takeProfit,\n\t\t\tstopLoss: orderConfig.bracketOrders?.stopLoss,\n\t\t\tpositionMaxLeverage: params.positionMaxLeverage,\n\t\t},\n\t\tbuilderParams: params.builderParams,\n\t});\n};\n\nexport const createOpenPerpNonMarketOrderTxn = async (\n\tparams: WithTxnParams<OpenPerpNonMarketOrderBaseParams>\n): Promise<Transaction | VersionedTransaction> => {\n\tconst { driftClient } = params;\n\n\tconst instructions = await createOpenPerpNonMarketOrderIxs(params);\n\n\tconst openPerpNonMarketOrderTxn = await driftClient.buildTransaction(\n\t\tinstructions,\n\t\tparams.txParams\n\t);\n\n\treturn openPerpNonMarketOrderTxn;\n};\n\nexport const createOpenPerpNonMarketOrder = async <T extends boolean>(\n\tparams: WithTxnParams<OpenPerpNonMarketOrderParams<T, SwiftOrderOptions>>\n): Promise<TxnOrSwiftResult<T>> => {\n\tconst { swiftOptions, useSwift, orderConfig } = params;\n\n\t// If useSwift is true, return the Swift result directly\n\tif (useSwift) {\n\t\tif (orderConfig.orderType !== 'limit') {\n\t\t\tthrow new Error('Only limit orders are supported with Swift');\n\t\t}\n\n\t\tif (!swiftOptions) {\n\t\t\tthrow new Error('swiftOptions is required when useSwift is true');\n\t\t}\n\n\t\tif (\n\t\t\tparams.postOnly &&\n\t\t\t!ENUM_UTILS.match(params.postOnly, PostOnlyParams.NONE)\n\t\t) {\n\t\t\tthrow new Error('Post only orders are not supported with Swift');\n\t\t}\n\n\t\tconst swiftOrderResult = await createSwiftLimitOrder({\n\t\t\t...params,\n\t\t\tswiftOptions,\n\t\t\torderConfig,\n\t\t});\n\n\t\treturn swiftOrderResult as TxnOrSwiftResult<T>;\n\t}\n\n\tconst marketOrderTxn = await createOpenPerpNonMarketOrderTxn(params);\n\n\treturn marketOrderTxn as TxnOrSwiftResult<T>;\n};\n"]}
|
|
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.prepSignAndSendSwiftOrder = exports.sendSwiftOrder = exports.signSwiftOrderMsg = exports.AuctionSlotExpiredError = exports.prepSwiftOrder = exports.MINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = exports.SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = void 0;
|
|
4
4
|
const sdk_1 = require("@drift-labs/sdk");
|
|
5
5
|
const sdk_2 = require("@drift-labs/sdk");
|
|
6
|
+
const utils_1 = require("../../../../../../utils");
|
|
6
7
|
const swiftClient_1 = require("../../../../../../clients/swiftClient");
|
|
7
8
|
const types_1 = require("../../../../../../types");
|
|
8
9
|
const trading_1 = require("../../../../../../common-ui-utils/trading");
|
|
@@ -156,7 +157,7 @@ exports.signSwiftOrderMsg = signSwiftOrderMsg;
|
|
|
156
157
|
*/
|
|
157
158
|
const sendSwiftOrder = ({ driftClient, marketId, hexEncodedSwiftOrderMessageString, signedMessage, signedMsgOrderUuid, takerAuthority, signingAuthority, auctionDuration, }) => {
|
|
158
159
|
const signedMsgUserOrdersAccountPubkey = (0, sdk_1.getSignedMsgUserAccountPublicKey)(driftClient.program.programId, takerAuthority);
|
|
159
|
-
const swiftOrderObservable = swiftClient_1.SwiftClient.sendAndConfirmSwiftOrderWS(driftClient.connection, driftClient, marketId.marketIndex, marketId.marketType, hexEncodedSwiftOrderMessageString, Buffer.from(signedMessage), takerAuthority, signedMsgUserOrdersAccountPubkey, signedMsgOrderUuid, ((auctionDuration !== null && auctionDuration !== void 0 ? auctionDuration : 0)
|
|
160
|
+
const swiftOrderObservable = swiftClient_1.SwiftClient.sendAndConfirmSwiftOrderWS(driftClient.connection, driftClient, marketId.marketIndex, marketId.marketType, hexEncodedSwiftOrderMessageString, Buffer.from(signedMessage), takerAuthority, signedMsgUserOrdersAccountPubkey, signedMsgOrderUuid, (0, utils_1.getSwiftConfirmationTimeoutMs)(auctionDuration !== null && auctionDuration !== void 0 ? auctionDuration : 0), signingAuthority);
|
|
160
161
|
return swiftOrderObservable;
|
|
161
162
|
};
|
|
162
163
|
exports.sendSwiftOrder = sendSwiftOrder;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.ts"],"names":[],"mappings":";;;AAAA,yCAKyB;AACzB,yCAOyB;AACzB,uEAO+C;AAC/C,mDAAmD;AAGnD,uEAA0E;AAE7D,QAAA,2CAA2C,GAAG,CAAC,CAAC;AAChD,QAAA,mDAAmD,GAAG,CAAC,CAAC;AAsGrE;;;;;;;;;;;;;;;;GAgBG;AACI,MAAM,cAAc,GAAG,CAAC,EAC9B,WAAW,EACX,gBAAgB,EAChB,WAAW,EACX,UAAU,EACV,WAAW,EACX,UAAU,GAAG,EAAE,EACf,aAAa,GACS,EAUrB,EAAE;;IACH,MAAM,eAAe,GAAG,IAAA,oBAAc,EAAC;QACtC,GAAG,WAAW,CAAC,IAAI;QACnB,eAAe,EAAE,WAAW,CAAC,IAAI,CAAC,eAAe,IAAI,IAAI,EAAE,6EAA6E;KACxI,CAAC,CAAC;IAEH,gFAAgF;IAChF,MAAM,gBAAgB,GAAG,IAAI,QAAE,CAAC,WAAW,GAAG,UAAU,CAAC,CAAC;IAE1D,MAAM,kBAAkB,GAAG,IAAA,2BAAqB,GAAE,CAAC;IAEnD,MAAM,+BAA+B,GAAG;QACvC,oBAAoB,EAAE,eAAe;QACrC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AAe,CAAC,CAAC,CAAC;YAC1E,mBAAmB,CAAC,YAAY,CAAC,CAAC;QACnC,CAAC;IACF,CAAC,CAAC,CAAC;IAEH,OAAO,OAAO,CAAC;AAChB,CAAC,CAAC;AAlHW,QAAA,yBAAyB,6BAkHpC","sourcesContent":["import {\n\tgetSignedMsgUserAccountPublicKey,\n\tSignedMsgOrderParamsDelegateMessage,\n\tSignedMsgOrderParamsMessage,\n\tSLOT_TIME_ESTIMATE_MS,\n} from '@drift-labs/sdk';\nimport {\n\tBN,\n\tDriftClient,\n\tgenerateSignedMsgUuid,\n\tgetOrderParams,\n\tOptionalOrderParams,\n\tPublicKey,\n} from '@drift-labs/sdk';\nimport {\n\tSwiftClient,\n\tSwiftOrderConfirmedEvent,\n\tSwiftOrderErroredEvent,\n\tSwiftOrderEvent,\n\tSwiftOrderEventWithParams,\n\tSwiftOrderSentEvent,\n} from '../../../../../../clients/swiftClient';\nimport { MarketId } from '../../../../../../types';\nimport { Observable, Subscription } from 'rxjs';\nimport { OptionalTriggerOrderParams } from '../types';\nimport { TRADING_UTILS } from '../../../../../../common-ui-utils/trading';\n\nexport const SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 5;\nexport const MINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 5;\n\nexport interface SwiftOrderOptions {\n\twallet: {\n\t\tsignMessage: (message: Uint8Array) => Promise<Uint8Array>;\n\t\ttakerAuthority: PublicKey;\n\t\tsigningAuthority?: PublicKey;\n\t};\n\tswiftServerUrl: string;\n\tsignedMessageOrderSlotBuffer?: number;\n\tisDelegate?: boolean;\n\tcallbacks?: {\n\t\tonOrderParamsMessagePrepped?: (\n\t\t\torderParamsMessage:\n\t\t\t\t| SignedMsgOrderParamsMessage\n\t\t\t\t| SignedMsgOrderParamsDelegateMessage\n\t\t) => void;\n\t\tonSigningExpiry?: (\n\t\t\torderParamsMessage:\n\t\t\t\t| SignedMsgOrderParamsMessage\n\t\t\t\t| SignedMsgOrderParamsDelegateMessage\n\t\t) => void;\n\t\tonSigningSuccess?: (\n\t\t\tsignedMessage: Uint8Array,\n\t\t\t// we add the following here, because the onSigningSuccess callback is called before the order is sent to the swift server\n\t\t\torderUuid: Uint8Array,\n\t\t\torderParamsMessage:\n\t\t\t\t| SignedMsgOrderParamsMessage\n\t\t\t\t| SignedMsgOrderParamsDelegateMessage\n\t\t) => void;\n\t\tonSent?: (\n\t\t\tswiftSentEvent: SwiftOrderEventWithParams<SwiftOrderSentEvent>\n\t\t) => void;\n\t\tonConfirmed?: (\n\t\t\tswiftConfirmedEvent: SwiftOrderEventWithParams<SwiftOrderConfirmedEvent>\n\t\t) => void;\n\t\tonExpired?: (\n\t\t\tswiftExpiredEvent: SwiftOrderEventWithParams<SwiftOrderErroredEvent>\n\t\t) => void;\n\t\tonErrored?: (\n\t\t\tswiftErroredEvent: SwiftOrderEventWithParams<SwiftOrderErroredEvent>\n\t\t) => void;\n\t};\n}\n\nexport type SwiftOrderObservable = Observable<SwiftOrderEvent>;\n\ninterface PrepSwiftOrderParams {\n\t/** The Drift client instance */\n\tdriftClient: DriftClient;\n\t/** The taker user account information */\n\ttakerUserAccount: {\n\t\t/** Public key of the user account */\n\t\tpubKey: PublicKey;\n\t\t/** User account ID */\n\t\tsubAccountId: number;\n\t};\n\t/** Current blockchain slot number */\n\tcurrentSlot: number;\n\t/** Whether this is a delegate order */\n\tisDelegate: boolean;\n\t/** Order parameters including main order and optional stop loss/take profit */\n\torderParams: {\n\t\t/** Main order parameters */\n\t\tmain: OptionalOrderParams;\n\t\t/** Optional stop loss order parameters */\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t\t/** Optional take profit order parameters */\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\t/** Optional max leverage for the position */\n\t\tpositionMaxLeverage?: number;\n\t};\n\t/** Buffer slots to account for signing time (default: 2 slots ~1 second). If a user is required to manually sign the message, this should be a higher number. */\n\tslotBuffer?: number;\n\t/**\n\t * Optional builder code parameters for revenue sharing.\n\t * If provided, the builder will receive a portion of the trading fees.\n\t *\n\t * Prerequisites:\n\t * - User must have initialized a RevenueShareEscrow account\n\t * - Builder must be in the user's approved_builders list\n\t * - builderFeeTenthBps must not exceed the builder's max_fee_tenth_bps\n\t */\n\tbuilderParams?: {\n\t\t/**\n\t\t * Index of the builder in the user's approved_builders list.\n\t\t * This is the position (0-indexed) of the builder in the RevenueShareEscrow.approved_builders array.\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\t * Examples:\n\t\t * - 10 = 1 bps = 0.01%\n\t\t * - 50 = 5 bps = 0.05%\n\t\t * - 100 = 10 bps = 0.1%\n\t\t */\n\t\tbuilderFeeTenthBps: number;\n\t};\n}\n\n/**\n * Prepares a swift order by encoding the order parameters into a message format\n * suitable for signing and sending to the Swift server.\n *\n * @param driftClient - The Drift client instance\n * @param takerUserAccount - The taker user account information\n * @param currentSlot - Current blockchain slot number\n * @param isDelegate - Whether this is a delegate order\n * @param orderParams - Order parameters including main order and optional stop loss/take profit\n * @param slotBuffer - Buffer slots to account for signing time (default: 35 slots ~14 seconds). Use this default value if it is not an auction order, else used an estimate number of slots to sign the message.\n *\n * @returns An object containing:\n * - `hexEncodedSwiftOrderMessage`: The encoded order message in both Uint8Array and string formats. The Uint8Array format is for a wallet to sign, while the string format is used to send to the SWIFT server.\n * - `signedMsgOrderParamsMessage`: The signed message order parameters\n * - `slotForSignedMsg`: The slot number for the signed message\n * - `signedMsgOrderUuid`: Unique identifier for the signed message order\n */\nexport const prepSwiftOrder = ({\n\tdriftClient,\n\ttakerUserAccount,\n\tcurrentSlot,\n\tisDelegate,\n\torderParams,\n\tslotBuffer = 35,\n\tbuilderParams,\n}: PrepSwiftOrderParams): {\n\thexEncodedSwiftOrderMessage: {\n\t\tuInt8Array: Uint8Array;\n\t\tstring: string;\n\t};\n\tsignedMsgOrderParamsMessage:\n\t\t| SignedMsgOrderParamsMessage\n\t\t| SignedMsgOrderParamsDelegateMessage;\n\tslotForSignedMsg: BN;\n\tsignedMsgOrderUuid: Uint8Array;\n} => {\n\tconst mainOrderParams = getOrderParams({\n\t\t...orderParams.main,\n\t\tauctionDuration: orderParams.main.auctionDuration || null, // swift server expects auctionDuration to be null if not set, won't handle 0\n\t});\n\n\t// buffer for time the user takes to sign a message and send to the swift server\n\tconst slotForSignedMsg = new BN(currentSlot + slotBuffer);\n\n\tconst signedMsgOrderUuid = generateSignedMsgUuid();\n\n\tconst baseSignedMsgOrderParamsMessage = {\n\t\tsignedMsgOrderParams: mainOrderParams,\n\t\tuuid: signedMsgOrderUuid,\n\t\tslot: slotForSignedMsg,\n\t\tstopLossOrderParams: orderParams.stopLoss\n\t\t\t? {\n\t\t\t\t\tbaseAssetAmount: orderParams.stopLoss.baseAssetAmount,\n\t\t\t\t\ttriggerPrice: orderParams.stopLoss.triggerPrice,\n\t\t\t }\n\t\t\t: null,\n\t\ttakeProfitOrderParams: orderParams.takeProfit\n\t\t\t? {\n\t\t\t\t\tbaseAssetAmount: orderParams.takeProfit.baseAssetAmount,\n\t\t\t\t\ttriggerPrice: orderParams.takeProfit.triggerPrice,\n\t\t\t }\n\t\t\t: null,\n\t\tmaxMarginRatio: orderParams.positionMaxLeverage\n\t\t\t? TRADING_UTILS.convertLeverageToMarginRatio(\n\t\t\t\t\torderParams.positionMaxLeverage\n\t\t\t )\n\t\t\t: null,\n\t\t// Include builder params if provided\n\t\tbuilderIdx: builderParams?.builderIdx ?? null,\n\t\tbuilderFeeTenthBps: builderParams?.builderFeeTenthBps ?? null,\n\t};\n\n\tconst signedMsgOrderParamsMessage:\n\t\t| SignedMsgOrderParamsMessage\n\t\t| SignedMsgOrderParamsDelegateMessage = isDelegate\n\t\t? {\n\t\t\t\t...baseSignedMsgOrderParamsMessage,\n\t\t\t\ttakerPubkey: takerUserAccount.pubKey,\n\t\t }\n\t\t: {\n\t\t\t\t...baseSignedMsgOrderParamsMessage,\n\t\t\t\tsubAccountId: takerUserAccount.subAccountId,\n\t\t };\n\n\tconst encodedOrderMessage = driftClient.encodeSignedMsgOrderParamsMessage(\n\t\tsignedMsgOrderParamsMessage,\n\t\tisDelegate\n\t);\n\tconst hexEncodedSwiftOrderMessage = Buffer.from(\n\t\tencodedOrderMessage.toString('hex')\n\t);\n\n\treturn {\n\t\thexEncodedSwiftOrderMessage: {\n\t\t\tuInt8Array: new Uint8Array(hexEncodedSwiftOrderMessage),\n\t\t\tstring: hexEncodedSwiftOrderMessage.toString(),\n\t\t},\n\t\tsignedMsgOrderParamsMessage,\n\t\tslotForSignedMsg,\n\t\tsignedMsgOrderUuid,\n\t};\n};\n\n/**\n * Error thrown when an auction slot has expired\n */\nexport class AuctionSlotExpiredError extends Error {\n\tname = 'AuctionSlotExpiredError';\n\n\t/**\n\t * Creates an instance of AuctionSlotExpiredError\n\t * @param message - Error message (default: 'Auction slot expired')\n\t */\n\tconstructor(message: string = 'Auction slot expired') {\n\t\tsuper(message);\n\t\tif (Error.captureStackTrace) {\n\t\t\tError.captureStackTrace(this, AuctionSlotExpiredError);\n\t\t}\n\t}\n}\n\ninterface SignOrderMsgParams {\n\t/** Wallet instance with message signing capability */\n\twallet: {\n\t\t/** Function to sign a message */\n\t\tsignMessage: (message: Uint8Array) => Promise<Uint8Array>;\n\t};\n\t/** Hex-encoded swift order message to sign */\n\thexEncodedSwiftOrderMessage: Uint8Array;\n\t/** Time in milliseconds till the auction expires */\n\texpirationTimeMs: number;\n\t/** Callback function called when the auction expires */\n\tonExpired?: () => void;\n}\n\n/**\n * Signs a swift order message with slot expiration monitoring.\n * Continuously monitors the current slot and rejects with AuctionSlotExpiredError\n * if the auction slot expires before signing is complete.\n *\n * @param wallet - Wallet instance with message signing capability\n * @param hexEncodedSwiftOrderMessage - Hex-encoded swift order message to sign\n * @param expirationTimeMs - Time in milliseconds till the auction expires\n * @param onExpired - Callback function called when the auction expires\n *\n * @returns Promise resolving to the signed message as Uint8Array\n * @throws {AuctionSlotExpiredError} When the auction slot expires before signing completes\n */\nexport const signSwiftOrderMsg = async ({\n\twallet,\n\thexEncodedSwiftOrderMessage,\n\texpirationTimeMs,\n\tonExpired,\n}: SignOrderMsgParams): Promise<Uint8Array> => {\n\tlet timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n\ttry {\n\t\t// Sign the message\n\t\tconst signedMessagePromise = wallet.signMessage(\n\t\t\thexEncodedSwiftOrderMessage\n\t\t);\n\n\t\tconst signingExpiredPromise = new Promise<never>((_resolve, reject) => {\n\t\t\ttimeoutId = setTimeout(() => {\n\t\t\t\tonExpired?.();\n\t\t\t\treject(new AuctionSlotExpiredError());\n\t\t\t}, expirationTimeMs);\n\t\t});\n\n\t\t// Ensure that the user signs the message before the expiration time\n\t\tconst signedMessage = await Promise.race([\n\t\t\tsignedMessagePromise,\n\t\t\tsigningExpiredPromise,\n\t\t]);\n\n\t\treturn signedMessage;\n\t} finally {\n\t\tif (timeoutId) {\n\t\t\tclearTimeout(timeoutId);\n\t\t}\n\t}\n};\n\n/**\n * Parameters for sending a swift order to the Swift server\n * @interface SendSwiftOrderParams\n */\ninterface SendSwiftOrderParams {\n\t/** The Drift client instance */\n\tdriftClient: DriftClient;\n\t/** Market identifier for the order */\n\tmarketId: MarketId;\n\t/** Hex-encoded swift order message as string */\n\thexEncodedSwiftOrderMessageString: string;\n\t/** The signed message from the wallet */\n\tsignedMessage: Uint8Array;\n\t/** Unique identifier for the signed message order */\n\tsignedMsgOrderUuid: Uint8Array;\n\t/** Public key of the taker authority */\n\ttakerAuthority: PublicKey;\n\t/** Public key of the signing authority */\n\tsigningAuthority: PublicKey;\n\t/** Duration of the auction in slots (optional) */\n\tauctionDuration?: number;\n}\n\n/**\n * Sends a swift order to the Swift server and handles the response.\n * Monitors the order status and calls appropriate callback functions based on the response type.\n *\n * @param driftClient - The Drift client instance\n * @param marketId - Market identifier for the order\n * @param hexEncodedSwiftOrderMessageString - Hex-encoded swift order message as string\n * @param signedMessage - The signed message from the wallet\n * @param signedMsgOrderUuid - Unique identifier for the signed message order\n * @param takerAuthority - Public key of the taker authority\n * @param signingAuthority - Public key of the signing authority\n * @param auctionDurationSlot - Duration of the auction in slots (optional)\n * @param swiftConfirmationSlotBuffer - Slot buffer for swift server confirmation time (default: 15)\n * @param onExpired - Callback function called when the order expires\n * @param onErrored - Callback function called when the order encounters an error\n * @param onConfirmed - Callback function called when the order is confirmed\n *\n * @returns Promise that resolves when the order processing is complete\n *\n */\nexport const sendSwiftOrder = ({\n\tdriftClient,\n\tmarketId,\n\thexEncodedSwiftOrderMessageString,\n\tsignedMessage,\n\tsignedMsgOrderUuid,\n\ttakerAuthority,\n\tsigningAuthority,\n\tauctionDuration,\n}: SendSwiftOrderParams): SwiftOrderObservable => {\n\tconst signedMsgUserOrdersAccountPubkey = getSignedMsgUserAccountPublicKey(\n\t\tdriftClient.program.programId,\n\t\ttakerAuthority\n\t);\n\n\tconst swiftOrderObservable = SwiftClient.sendAndConfirmSwiftOrderWS(\n\t\tdriftClient.connection,\n\t\tdriftClient,\n\t\tmarketId.marketIndex,\n\t\tmarketId.marketType,\n\t\thexEncodedSwiftOrderMessageString,\n\t\tBuffer.from(signedMessage),\n\t\ttakerAuthority,\n\t\tsignedMsgUserOrdersAccountPubkey,\n\t\tsignedMsgOrderUuid,\n\t\t((auctionDuration ?? 0) + 15) * SLOT_TIME_ESTIMATE_MS,\n\t\tsigningAuthority\n\t);\n\n\treturn swiftOrderObservable;\n};\n\ntype PrepSignAndSendSwiftOrderParams = {\n\tdriftClient: DriftClient;\n\tsubAccountId: number;\n\tuserAccountPubKey: PublicKey;\n\tmarketIndex: number;\n\tslotBuffer: number;\n\tswiftOptions: SwiftOrderOptions;\n\torderParams: {\n\t\tmain: OptionalOrderParams;\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t\t/**\n\t\t * Adjusts the max leverage of a position.\n\t\t */\n\t\tpositionMaxLeverage?: number;\n\t};\n\t/**\n\t * Optional builder code parameters for revenue sharing.\n\t * If provided, the builder will receive a portion of the trading fees.\n\t *\n\t * Prerequisites:\n\t * - User must have initialized a RevenueShareEscrow account\n\t * - Builder must be in the user's approved_builders list\n\t * - builderFeeTenthBps must not exceed the builder's max_fee_tenth_bps\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};\n\n/**\n * Handles the full flow of the swift order, from preparing to signing and sending to the Swift server.\n * Callbacks can be provided to handle the events of the Swift order.\n * Returns a promise that resolves when the Swift order has reached a terminal state (i.e. confirmed, expired, or errored).\n */\nexport const prepSignAndSendSwiftOrder = async ({\n\tdriftClient,\n\tsubAccountId,\n\tuserAccountPubKey,\n\tmarketIndex,\n\tslotBuffer,\n\tswiftOptions,\n\torderParams,\n\tbuilderParams,\n}: PrepSignAndSendSwiftOrderParams): Promise<void> => {\n\tconst currentSlot = await driftClient.connection.getSlot('confirmed');\n\n\tconst {\n\t\thexEncodedSwiftOrderMessage,\n\t\tsignedMsgOrderUuid,\n\t\tsignedMsgOrderParamsMessage,\n\t} = prepSwiftOrder({\n\t\tdriftClient,\n\t\ttakerUserAccount: {\n\t\t\tpubKey: userAccountPubKey,\n\t\t\tsubAccountId: subAccountId,\n\t\t},\n\t\tcurrentSlot,\n\t\tisDelegate: swiftOptions.isDelegate || false,\n\t\torderParams,\n\t\tslotBuffer,\n\t\tbuilderParams,\n\t});\n\n\tswiftOptions.callbacks?.onOrderParamsMessagePrepped?.(\n\t\tsignedMsgOrderParamsMessage\n\t);\n\n\tconst expirationTimeMs =\n\t\tMath.max(\n\t\t\tslotBuffer +\n\t\t\t\t(orderParams.main.auctionDuration || 0) -\n\t\t\t\tSWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS,\n\t\t\tMINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS\n\t\t) * SLOT_TIME_ESTIMATE_MS;\n\n\t// Ensure that the user signs the message before the expiration time\n\tconst signedMessage = await signSwiftOrderMsg({\n\t\twallet: swiftOptions.wallet,\n\t\thexEncodedSwiftOrderMessage: hexEncodedSwiftOrderMessage.uInt8Array,\n\t\texpirationTimeMs,\n\t\tonExpired: () =>\n\t\t\tswiftOptions.callbacks?.onSigningExpiry?.(signedMsgOrderParamsMessage),\n\t});\n\n\tswiftOptions.callbacks?.onSigningSuccess?.(\n\t\tsignedMessage,\n\t\tsignedMsgOrderUuid,\n\t\tsignedMsgOrderParamsMessage\n\t);\n\n\t// Initialize SwiftClient (required before using sendSwiftOrder)\n\tSwiftClient.init(swiftOptions.swiftServerUrl);\n\n\t// Create a promise-based wrapper for the sendSwiftOrder callback-based API\n\tconst swiftOrderObservable = sendSwiftOrder({\n\t\tdriftClient,\n\t\tmarketId: MarketId.createPerpMarket(marketIndex),\n\t\thexEncodedSwiftOrderMessageString: hexEncodedSwiftOrderMessage.string,\n\t\tsignedMessage,\n\t\tsignedMsgOrderUuid,\n\t\ttakerAuthority: swiftOptions.wallet.takerAuthority,\n\t\tsigningAuthority:\n\t\t\tswiftOptions.wallet.signingAuthority ??\n\t\t\tswiftOptions.wallet.takerAuthority,\n\t\tauctionDuration: orderParams.main.auctionDuration || undefined,\n\t});\n\n\tconst wrapSwiftOrderEvent = <T extends SwiftOrderEvent>(\n\t\tswiftOrderEvent: T\n\t) => {\n\t\treturn {\n\t\t\t...swiftOrderEvent,\n\t\t\tswiftOrderUuid: signedMsgOrderUuid,\n\t\t\torderParamsMessage: signedMsgOrderParamsMessage,\n\t\t};\n\t};\n\n\tlet promiseResolver: (value: void | PromiseLike<void>) => void;\n\tconst promise = new Promise<void>((resolve) => {\n\t\tpromiseResolver = resolve;\n\t});\n\n\tconst handleTerminalEvent = (subscription: Subscription) => {\n\t\tsubscription.unsubscribe();\n\t\tpromiseResolver();\n\t};\n\n\tconst subscription = swiftOrderObservable.subscribe((swiftOrderEvent) => {\n\t\tif (swiftOrderEvent.type === 'sent') {\n\t\t\tswiftOptions.callbacks?.onSent?.(wrapSwiftOrderEvent(swiftOrderEvent));\n\t\t}\n\t\tif (swiftOrderEvent.type === 'confirmed') {\n\t\t\tswiftOptions.callbacks?.onConfirmed?.(\n\t\t\t\twrapSwiftOrderEvent(swiftOrderEvent)\n\t\t\t);\n\t\t\thandleTerminalEvent(subscription);\n\t\t}\n\t\tif (swiftOrderEvent.type === 'expired') {\n\t\t\tswiftOptions.callbacks?.onExpired?.(wrapSwiftOrderEvent(swiftOrderEvent));\n\t\t\thandleTerminalEvent(subscription);\n\t\t}\n\t\tif (swiftOrderEvent.type === 'errored') {\n\t\t\tswiftOptions.callbacks?.onErrored?.(wrapSwiftOrderEvent(swiftOrderEvent));\n\t\t\thandleTerminalEvent(subscription);\n\t\t}\n\t});\n\n\treturn promise;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.ts"],"names":[],"mappings":";;;AAAA,yCAKyB;AACzB,yCAOyB;AACzB,mDAAwE;AACxE,uEAO+C;AAC/C,mDAAmD;AAGnD,uEAA0E;AAE7D,QAAA,2CAA2C,GAAG,CAAC,CAAC;AAChD,QAAA,mDAAmD,GAAG,CAAC,CAAC;AAsGrE;;;;;;;;;;;;;;;;GAgBG;AACI,MAAM,cAAc,GAAG,CAAC,EAC9B,WAAW,EACX,gBAAgB,EAChB,WAAW,EACX,UAAU,EACV,WAAW,EACX,UAAU,GAAG,EAAE,EACf,aAAa,GACS,EAUrB,EAAE;;IACH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C;QACnC,CAAC;QACD,IAAI,eAAe,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YACxC,MAAA,MAAA,YAAY,CAAC,SAAS,0CAAE,SAAS,mDAAG,mBAAmB,CAAC,eAAe,CAAC,CAAC,CAAC;YAC1E,mBAAmB,CAAC,YAAY,CAAC,CAAC;QACnC,CAAC;QACD,IAAI,eAAe,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YACxC,MAAA,MAAA,YAAY,CAAC,SAAS,0CAAE,SAAS,mDAAG,mBAAmB,CAAC,eAAe,CAAC,CAAC,CAAC;YAC1E,mBAAmB,CAAC,YAAY,CAAC,CAAC;QACnC,CAAC;IACF,CAAC,CAAC,CAAC;IAEH,OAAO,OAAO,CAAC;AAChB,CAAC,CAAC;AAlHW,QAAA,yBAAyB,6BAkHpC","sourcesContent":["import {\n\tgetSignedMsgUserAccountPublicKey,\n\tSignedMsgOrderParamsDelegateMessage,\n\tSignedMsgOrderParamsMessage,\n\tSLOT_TIME_ESTIMATE_MS,\n} from '@drift-labs/sdk';\nimport {\n\tBN,\n\tDriftClient,\n\tgenerateSignedMsgUuid,\n\tgetOrderParams,\n\tOptionalOrderParams,\n\tPublicKey,\n} from '@drift-labs/sdk';\nimport { getSwiftConfirmationTimeoutMs } from '../../../../../../utils';\nimport {\n\tSwiftClient,\n\tSwiftOrderConfirmedEvent,\n\tSwiftOrderErroredEvent,\n\tSwiftOrderEvent,\n\tSwiftOrderEventWithParams,\n\tSwiftOrderSentEvent,\n} from '../../../../../../clients/swiftClient';\nimport { MarketId } from '../../../../../../types';\nimport { Observable, Subscription } from 'rxjs';\nimport { OptionalTriggerOrderParams } from '../types';\nimport { TRADING_UTILS } from '../../../../../../common-ui-utils/trading';\n\nexport const SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 5;\nexport const MINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 5;\n\nexport interface SwiftOrderOptions {\n\twallet: {\n\t\tsignMessage: (message: Uint8Array) => Promise<Uint8Array>;\n\t\ttakerAuthority: PublicKey;\n\t\tsigningAuthority?: PublicKey;\n\t};\n\tswiftServerUrl: string;\n\tsignedMessageOrderSlotBuffer?: number;\n\tisDelegate?: boolean;\n\tcallbacks?: {\n\t\tonOrderParamsMessagePrepped?: (\n\t\t\torderParamsMessage:\n\t\t\t\t| SignedMsgOrderParamsMessage\n\t\t\t\t| SignedMsgOrderParamsDelegateMessage\n\t\t) => void;\n\t\tonSigningExpiry?: (\n\t\t\torderParamsMessage:\n\t\t\t\t| SignedMsgOrderParamsMessage\n\t\t\t\t| SignedMsgOrderParamsDelegateMessage\n\t\t) => void;\n\t\tonSigningSuccess?: (\n\t\t\tsignedMessage: Uint8Array,\n\t\t\t// we add the following here, because the onSigningSuccess callback is called before the order is sent to the swift server\n\t\t\torderUuid: Uint8Array,\n\t\t\torderParamsMessage:\n\t\t\t\t| SignedMsgOrderParamsMessage\n\t\t\t\t| SignedMsgOrderParamsDelegateMessage\n\t\t) => void;\n\t\tonSent?: (\n\t\t\tswiftSentEvent: SwiftOrderEventWithParams<SwiftOrderSentEvent>\n\t\t) => void;\n\t\tonConfirmed?: (\n\t\t\tswiftConfirmedEvent: SwiftOrderEventWithParams<SwiftOrderConfirmedEvent>\n\t\t) => void;\n\t\tonExpired?: (\n\t\t\tswiftExpiredEvent: SwiftOrderEventWithParams<SwiftOrderErroredEvent>\n\t\t) => void;\n\t\tonErrored?: (\n\t\t\tswiftErroredEvent: SwiftOrderEventWithParams<SwiftOrderErroredEvent>\n\t\t) => void;\n\t};\n}\n\nexport type SwiftOrderObservable = Observable<SwiftOrderEvent>;\n\ninterface PrepSwiftOrderParams {\n\t/** The Drift client instance */\n\tdriftClient: DriftClient;\n\t/** The taker user account information */\n\ttakerUserAccount: {\n\t\t/** Public key of the user account */\n\t\tpubKey: PublicKey;\n\t\t/** User account ID */\n\t\tsubAccountId: number;\n\t};\n\t/** Current blockchain slot number */\n\tcurrentSlot: number;\n\t/** Whether this is a delegate order */\n\tisDelegate: boolean;\n\t/** Order parameters including main order and optional stop loss/take profit */\n\torderParams: {\n\t\t/** Main order parameters */\n\t\tmain: OptionalOrderParams;\n\t\t/** Optional stop loss order parameters */\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t\t/** Optional take profit order parameters */\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\t/** Optional max leverage for the position */\n\t\tpositionMaxLeverage?: number;\n\t};\n\t/** Buffer slots to account for signing time (default: 2 slots ~1 second). If a user is required to manually sign the message, this should be a higher number. */\n\tslotBuffer?: number;\n\t/**\n\t * Optional builder code parameters for revenue sharing.\n\t * If provided, the builder will receive a portion of the trading fees.\n\t *\n\t * Prerequisites:\n\t * - User must have initialized a RevenueShareEscrow account\n\t * - Builder must be in the user's approved_builders list\n\t * - builderFeeTenthBps must not exceed the builder's max_fee_tenth_bps\n\t */\n\tbuilderParams?: {\n\t\t/**\n\t\t * Index of the builder in the user's approved_builders list.\n\t\t * This is the position (0-indexed) of the builder in the RevenueShareEscrow.approved_builders array.\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\t * Examples:\n\t\t * - 10 = 1 bps = 0.01%\n\t\t * - 50 = 5 bps = 0.05%\n\t\t * - 100 = 10 bps = 0.1%\n\t\t */\n\t\tbuilderFeeTenthBps: number;\n\t};\n}\n\n/**\n * Prepares a swift order by encoding the order parameters into a message format\n * suitable for signing and sending to the Swift server.\n *\n * @param driftClient - The Drift client instance\n * @param takerUserAccount - The taker user account information\n * @param currentSlot - Current blockchain slot number\n * @param isDelegate - Whether this is a delegate order\n * @param orderParams - Order parameters including main order and optional stop loss/take profit\n * @param slotBuffer - Buffer slots to account for signing time (default: 35 slots ~14 seconds). Use this default value if it is not an auction order, else used an estimate number of slots to sign the message.\n *\n * @returns An object containing:\n * - `hexEncodedSwiftOrderMessage`: The encoded order message in both Uint8Array and string formats. The Uint8Array format is for a wallet to sign, while the string format is used to send to the SWIFT server.\n * - `signedMsgOrderParamsMessage`: The signed message order parameters\n * - `slotForSignedMsg`: The slot number for the signed message\n * - `signedMsgOrderUuid`: Unique identifier for the signed message order\n */\nexport const prepSwiftOrder = ({\n\tdriftClient,\n\ttakerUserAccount,\n\tcurrentSlot,\n\tisDelegate,\n\torderParams,\n\tslotBuffer = 35,\n\tbuilderParams,\n}: PrepSwiftOrderParams): {\n\thexEncodedSwiftOrderMessage: {\n\t\tuInt8Array: Uint8Array;\n\t\tstring: string;\n\t};\n\tsignedMsgOrderParamsMessage:\n\t\t| SignedMsgOrderParamsMessage\n\t\t| SignedMsgOrderParamsDelegateMessage;\n\tslotForSignedMsg: BN;\n\tsignedMsgOrderUuid: Uint8Array;\n} => {\n\tconst mainOrderParams = getOrderParams({\n\t\t...orderParams.main,\n\t\tauctionDuration: orderParams.main.auctionDuration || null, // swift server expects auctionDuration to be null if not set, won't handle 0\n\t});\n\n\t// buffer for time the user takes to sign a message and send to the swift server\n\tconst slotForSignedMsg = new BN(currentSlot + slotBuffer);\n\n\tconst signedMsgOrderUuid = generateSignedMsgUuid();\n\n\tconst baseSignedMsgOrderParamsMessage = {\n\t\tsignedMsgOrderParams: mainOrderParams,\n\t\tuuid: signedMsgOrderUuid,\n\t\tslot: slotForSignedMsg,\n\t\tstopLossOrderParams: orderParams.stopLoss\n\t\t\t? {\n\t\t\t\t\tbaseAssetAmount: orderParams.stopLoss.baseAssetAmount,\n\t\t\t\t\ttriggerPrice: orderParams.stopLoss.triggerPrice,\n\t\t\t }\n\t\t\t: null,\n\t\ttakeProfitOrderParams: orderParams.takeProfit\n\t\t\t? {\n\t\t\t\t\tbaseAssetAmount: orderParams.takeProfit.baseAssetAmount,\n\t\t\t\t\ttriggerPrice: orderParams.takeProfit.triggerPrice,\n\t\t\t }\n\t\t\t: null,\n\t\tmaxMarginRatio: orderParams.positionMaxLeverage\n\t\t\t? TRADING_UTILS.convertLeverageToMarginRatio(\n\t\t\t\t\torderParams.positionMaxLeverage\n\t\t\t )\n\t\t\t: null,\n\t\t// Include builder params if provided\n\t\tbuilderIdx: builderParams?.builderIdx ?? null,\n\t\tbuilderFeeTenthBps: builderParams?.builderFeeTenthBps ?? null,\n\t};\n\n\tconst signedMsgOrderParamsMessage:\n\t\t| SignedMsgOrderParamsMessage\n\t\t| SignedMsgOrderParamsDelegateMessage = isDelegate\n\t\t? {\n\t\t\t\t...baseSignedMsgOrderParamsMessage,\n\t\t\t\ttakerPubkey: takerUserAccount.pubKey,\n\t\t }\n\t\t: {\n\t\t\t\t...baseSignedMsgOrderParamsMessage,\n\t\t\t\tsubAccountId: takerUserAccount.subAccountId,\n\t\t };\n\n\tconst encodedOrderMessage = driftClient.encodeSignedMsgOrderParamsMessage(\n\t\tsignedMsgOrderParamsMessage,\n\t\tisDelegate\n\t);\n\tconst hexEncodedSwiftOrderMessage = Buffer.from(\n\t\tencodedOrderMessage.toString('hex')\n\t);\n\n\treturn {\n\t\thexEncodedSwiftOrderMessage: {\n\t\t\tuInt8Array: new Uint8Array(hexEncodedSwiftOrderMessage),\n\t\t\tstring: hexEncodedSwiftOrderMessage.toString(),\n\t\t},\n\t\tsignedMsgOrderParamsMessage,\n\t\tslotForSignedMsg,\n\t\tsignedMsgOrderUuid,\n\t};\n};\n\n/**\n * Error thrown when an auction slot has expired\n */\nexport class AuctionSlotExpiredError extends Error {\n\tname = 'AuctionSlotExpiredError';\n\n\t/**\n\t * Creates an instance of AuctionSlotExpiredError\n\t * @param message - Error message (default: 'Auction slot expired')\n\t */\n\tconstructor(message: string = 'Auction slot expired') {\n\t\tsuper(message);\n\t\tif (Error.captureStackTrace) {\n\t\t\tError.captureStackTrace(this, AuctionSlotExpiredError);\n\t\t}\n\t}\n}\n\ninterface SignOrderMsgParams {\n\t/** Wallet instance with message signing capability */\n\twallet: {\n\t\t/** Function to sign a message */\n\t\tsignMessage: (message: Uint8Array) => Promise<Uint8Array>;\n\t};\n\t/** Hex-encoded swift order message to sign */\n\thexEncodedSwiftOrderMessage: Uint8Array;\n\t/** Time in milliseconds till the auction expires */\n\texpirationTimeMs: number;\n\t/** Callback function called when the auction expires */\n\tonExpired?: () => void;\n}\n\n/**\n * Signs a swift order message with slot expiration monitoring.\n * Continuously monitors the current slot and rejects with AuctionSlotExpiredError\n * if the auction slot expires before signing is complete.\n *\n * @param wallet - Wallet instance with message signing capability\n * @param hexEncodedSwiftOrderMessage - Hex-encoded swift order message to sign\n * @param expirationTimeMs - Time in milliseconds till the auction expires\n * @param onExpired - Callback function called when the auction expires\n *\n * @returns Promise resolving to the signed message as Uint8Array\n * @throws {AuctionSlotExpiredError} When the auction slot expires before signing completes\n */\nexport const signSwiftOrderMsg = async ({\n\twallet,\n\thexEncodedSwiftOrderMessage,\n\texpirationTimeMs,\n\tonExpired,\n}: SignOrderMsgParams): Promise<Uint8Array> => {\n\tlet timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n\ttry {\n\t\t// Sign the message\n\t\tconst signedMessagePromise = wallet.signMessage(\n\t\t\thexEncodedSwiftOrderMessage\n\t\t);\n\n\t\tconst signingExpiredPromise = new Promise<never>((_resolve, reject) => {\n\t\t\ttimeoutId = setTimeout(() => {\n\t\t\t\tonExpired?.();\n\t\t\t\treject(new AuctionSlotExpiredError());\n\t\t\t}, expirationTimeMs);\n\t\t});\n\n\t\t// Ensure that the user signs the message before the expiration time\n\t\tconst signedMessage = await Promise.race([\n\t\t\tsignedMessagePromise,\n\t\t\tsigningExpiredPromise,\n\t\t]);\n\n\t\treturn signedMessage;\n\t} finally {\n\t\tif (timeoutId) {\n\t\t\tclearTimeout(timeoutId);\n\t\t}\n\t}\n};\n\n/**\n * Parameters for sending a swift order to the Swift server\n * @interface SendSwiftOrderParams\n */\ninterface SendSwiftOrderParams {\n\t/** The Drift client instance */\n\tdriftClient: DriftClient;\n\t/** Market identifier for the order */\n\tmarketId: MarketId;\n\t/** Hex-encoded swift order message as string */\n\thexEncodedSwiftOrderMessageString: string;\n\t/** The signed message from the wallet */\n\tsignedMessage: Uint8Array;\n\t/** Unique identifier for the signed message order */\n\tsignedMsgOrderUuid: Uint8Array;\n\t/** Public key of the taker authority */\n\ttakerAuthority: PublicKey;\n\t/** Public key of the signing authority */\n\tsigningAuthority: PublicKey;\n\t/** Duration of the auction in slots (optional) */\n\tauctionDuration?: number;\n}\n\n/**\n * Sends a swift order to the Swift server and handles the response.\n * Monitors the order status and calls appropriate callback functions based on the response type.\n *\n * @param driftClient - The Drift client instance\n * @param marketId - Market identifier for the order\n * @param hexEncodedSwiftOrderMessageString - Hex-encoded swift order message as string\n * @param signedMessage - The signed message from the wallet\n * @param signedMsgOrderUuid - Unique identifier for the signed message order\n * @param takerAuthority - Public key of the taker authority\n * @param signingAuthority - Public key of the signing authority\n * @param auctionDurationSlot - Duration of the auction in slots (optional)\n * @param swiftConfirmationSlotBuffer - Slot buffer for swift server confirmation time (default: 15)\n * @param onExpired - Callback function called when the order expires\n * @param onErrored - Callback function called when the order encounters an error\n * @param onConfirmed - Callback function called when the order is confirmed\n *\n * @returns Promise that resolves when the order processing is complete\n *\n */\nexport const sendSwiftOrder = ({\n\tdriftClient,\n\tmarketId,\n\thexEncodedSwiftOrderMessageString,\n\tsignedMessage,\n\tsignedMsgOrderUuid,\n\ttakerAuthority,\n\tsigningAuthority,\n\tauctionDuration,\n}: SendSwiftOrderParams): SwiftOrderObservable => {\n\tconst signedMsgUserOrdersAccountPubkey = getSignedMsgUserAccountPublicKey(\n\t\tdriftClient.program.programId,\n\t\ttakerAuthority\n\t);\n\n\tconst swiftOrderObservable = SwiftClient.sendAndConfirmSwiftOrderWS(\n\t\tdriftClient.connection,\n\t\tdriftClient,\n\t\tmarketId.marketIndex,\n\t\tmarketId.marketType,\n\t\thexEncodedSwiftOrderMessageString,\n\t\tBuffer.from(signedMessage),\n\t\ttakerAuthority,\n\t\tsignedMsgUserOrdersAccountPubkey,\n\t\tsignedMsgOrderUuid,\n\t\tgetSwiftConfirmationTimeoutMs(auctionDuration ?? 0),\n\t\tsigningAuthority\n\t);\n\n\treturn swiftOrderObservable;\n};\n\ntype PrepSignAndSendSwiftOrderParams = {\n\tdriftClient: DriftClient;\n\tsubAccountId: number;\n\tuserAccountPubKey: PublicKey;\n\tmarketIndex: number;\n\tslotBuffer: number;\n\tswiftOptions: SwiftOrderOptions;\n\torderParams: {\n\t\tmain: OptionalOrderParams;\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t\t/**\n\t\t * Adjusts the max leverage of a position.\n\t\t */\n\t\tpositionMaxLeverage?: number;\n\t};\n\t/**\n\t * Optional builder code parameters for revenue sharing.\n\t * If provided, the builder will receive a portion of the trading fees.\n\t *\n\t * Prerequisites:\n\t * - User must have initialized a RevenueShareEscrow account\n\t * - Builder must be in the user's approved_builders list\n\t * - builderFeeTenthBps must not exceed the builder's max_fee_tenth_bps\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};\n\n/**\n * Handles the full flow of the swift order, from preparing to signing and sending to the Swift server.\n * Callbacks can be provided to handle the events of the Swift order.\n * Returns a promise that resolves when the Swift order has reached a terminal state (i.e. confirmed, expired, or errored).\n */\nexport const prepSignAndSendSwiftOrder = async ({\n\tdriftClient,\n\tsubAccountId,\n\tuserAccountPubKey,\n\tmarketIndex,\n\tslotBuffer,\n\tswiftOptions,\n\torderParams,\n\tbuilderParams,\n}: PrepSignAndSendSwiftOrderParams): Promise<void> => {\n\tconst currentSlot = await driftClient.connection.getSlot('confirmed');\n\n\tconst {\n\t\thexEncodedSwiftOrderMessage,\n\t\tsignedMsgOrderUuid,\n\t\tsignedMsgOrderParamsMessage,\n\t} = prepSwiftOrder({\n\t\tdriftClient,\n\t\ttakerUserAccount: {\n\t\t\tpubKey: userAccountPubKey,\n\t\t\tsubAccountId: subAccountId,\n\t\t},\n\t\tcurrentSlot,\n\t\tisDelegate: swiftOptions.isDelegate || false,\n\t\torderParams,\n\t\tslotBuffer,\n\t\tbuilderParams,\n\t});\n\n\tswiftOptions.callbacks?.onOrderParamsMessagePrepped?.(\n\t\tsignedMsgOrderParamsMessage\n\t);\n\n\tconst expirationTimeMs =\n\t\tMath.max(\n\t\t\tslotBuffer +\n\t\t\t\t(orderParams.main.auctionDuration || 0) -\n\t\t\t\tSWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS,\n\t\t\tMINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS\n\t\t) * SLOT_TIME_ESTIMATE_MS;\n\n\t// Ensure that the user signs the message before the expiration time\n\tconst signedMessage = await signSwiftOrderMsg({\n\t\twallet: swiftOptions.wallet,\n\t\thexEncodedSwiftOrderMessage: hexEncodedSwiftOrderMessage.uInt8Array,\n\t\texpirationTimeMs,\n\t\tonExpired: () =>\n\t\t\tswiftOptions.callbacks?.onSigningExpiry?.(signedMsgOrderParamsMessage),\n\t});\n\n\tswiftOptions.callbacks?.onSigningSuccess?.(\n\t\tsignedMessage,\n\t\tsignedMsgOrderUuid,\n\t\tsignedMsgOrderParamsMessage\n\t);\n\n\t// Initialize SwiftClient (required before using sendSwiftOrder)\n\tSwiftClient.init(swiftOptions.swiftServerUrl);\n\n\t// Create a promise-based wrapper for the sendSwiftOrder callback-based API\n\tconst swiftOrderObservable = sendSwiftOrder({\n\t\tdriftClient,\n\t\tmarketId: MarketId.createPerpMarket(marketIndex),\n\t\thexEncodedSwiftOrderMessageString: hexEncodedSwiftOrderMessage.string,\n\t\tsignedMessage,\n\t\tsignedMsgOrderUuid,\n\t\ttakerAuthority: swiftOptions.wallet.takerAuthority,\n\t\tsigningAuthority:\n\t\t\tswiftOptions.wallet.signingAuthority ??\n\t\t\tswiftOptions.wallet.takerAuthority,\n\t\tauctionDuration: orderParams.main.auctionDuration || undefined,\n\t});\n\n\tconst wrapSwiftOrderEvent = <T extends SwiftOrderEvent>(\n\t\tswiftOrderEvent: T\n\t) => {\n\t\treturn {\n\t\t\t...swiftOrderEvent,\n\t\t\tswiftOrderUuid: signedMsgOrderUuid,\n\t\t\torderParamsMessage: signedMsgOrderParamsMessage,\n\t\t};\n\t};\n\n\tlet promiseResolver: (value: void | PromiseLike<void>) => void;\n\tconst promise = new Promise<void>((resolve) => {\n\t\tpromiseResolver = resolve;\n\t});\n\n\tconst handleTerminalEvent = (subscription: Subscription) => {\n\t\tsubscription.unsubscribe();\n\t\tpromiseResolver();\n\t};\n\n\tconst subscription = swiftOrderObservable.subscribe((swiftOrderEvent) => {\n\t\tif (swiftOrderEvent.type === 'sent') {\n\t\t\tswiftOptions.callbacks?.onSent?.(wrapSwiftOrderEvent(swiftOrderEvent));\n\t\t}\n\t\tif (swiftOrderEvent.type === 'confirmed') {\n\t\t\tswiftOptions.callbacks?.onConfirmed?.(\n\t\t\t\twrapSwiftOrderEvent(swiftOrderEvent)\n\t\t\t);\n\t\t\thandleTerminalEvent(subscription);\n\t\t}\n\t\tif (swiftOrderEvent.type === 'expired') {\n\t\t\tswiftOptions.callbacks?.onExpired?.(wrapSwiftOrderEvent(swiftOrderEvent));\n\t\t\thandleTerminalEvent(subscription);\n\t\t}\n\t\tif (swiftOrderEvent.type === 'errored') {\n\t\t\tswiftOptions.callbacks?.onErrored?.(wrapSwiftOrderEvent(swiftOrderEvent));\n\t\t\thandleTerminalEvent(subscription);\n\t\t}\n\t});\n\n\treturn promise;\n};\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { BN, DriftClient, JupiterClient, QuoteResponse, TxParams, User } from '@drift-labs/sdk';
|
|
1
|
+
import { BN, DriftClient, JupiterClient, QuoteResponse, TxParams, UnifiedSwapClient, User } from '@drift-labs/sdk';
|
|
2
2
|
import { AddressLookupTableAccount, Transaction, TransactionInstruction, VersionedTransaction } from '@solana/web3.js';
|
|
3
3
|
/**
|
|
4
4
|
* Parameters for creating swap instruction details
|
|
@@ -6,10 +6,15 @@ import { AddressLookupTableAccount, Transaction, TransactionInstruction, Version
|
|
|
6
6
|
interface CreateSwapIxDetailsParams {
|
|
7
7
|
/** The Drift client instance for interacting with the Drift protocol */
|
|
8
8
|
driftClient: DriftClient;
|
|
9
|
-
/** Quote response from
|
|
9
|
+
/** Quote response from swap provider containing swap route information */
|
|
10
10
|
quote: QuoteResponse;
|
|
11
|
-
/**
|
|
12
|
-
|
|
11
|
+
/** Swap client instance for performing the swap (supports UnifiedSwapClient or JupiterClient) */
|
|
12
|
+
swapClient?: UnifiedSwapClient | JupiterClient;
|
|
13
|
+
/**
|
|
14
|
+
* @deprecated Use swapClient instead. This parameter is kept for backwards compatibility.
|
|
15
|
+
* Swap client instance for performing the swap
|
|
16
|
+
*/
|
|
17
|
+
jupiterClient?: JupiterClient;
|
|
13
18
|
/** Market index of the token being swapped from */
|
|
14
19
|
swapFromMarketIndex: number;
|
|
15
20
|
/** Market index of the token being swapped to */
|
|
@@ -20,11 +25,12 @@ interface CreateSwapIxDetailsParams {
|
|
|
20
25
|
user: User;
|
|
21
26
|
}
|
|
22
27
|
/**
|
|
23
|
-
* Creates swap instruction details for a
|
|
28
|
+
* Creates swap instruction details for a swap through Drift
|
|
24
29
|
*
|
|
25
30
|
* @param driftClient - The Drift client instance
|
|
26
|
-
* @param
|
|
27
|
-
* @param
|
|
31
|
+
* @param swapClient - The swap client instance for performing the swap (supports UnifiedSwapClient or JupiterClient)
|
|
32
|
+
* @param jupiterClient - @deprecated Use swapClient instead. Kept for backwards compatibility.
|
|
33
|
+
* @param quote - Quote response from swap provider with routing information
|
|
28
34
|
* @param swapFromMarketIndex - Source token market index
|
|
29
35
|
* @param swapToMarketIndex - Destination token market index
|
|
30
36
|
* @param amount - Amount to swap in base units
|
|
@@ -33,7 +39,7 @@ interface CreateSwapIxDetailsParams {
|
|
|
33
39
|
* @returns ixs - Array of Solana transaction instructions for the swap
|
|
34
40
|
* @returns lookupTables - Address lookup table accounts for transaction compression
|
|
35
41
|
*/
|
|
36
|
-
export declare const createSwapIxDetails: ({ driftClient, jupiterClient, quote, swapFromMarketIndex, swapToMarketIndex, amount, user, }: CreateSwapIxDetailsParams) => Promise<{
|
|
42
|
+
export declare const createSwapIxDetails: ({ driftClient, swapClient, jupiterClient, quote, swapFromMarketIndex, swapToMarketIndex, amount, user, }: CreateSwapIxDetailsParams) => Promise<{
|
|
37
43
|
ixs: TransactionInstruction[];
|
|
38
44
|
lookupTables: AddressLookupTableAccount[];
|
|
39
45
|
}>;
|
|
@@ -49,8 +55,9 @@ interface CreateSwapTxnParams extends CreateSwapIxDetailsParams {
|
|
|
49
55
|
* Creates a complete swap transaction ready for signing and submission
|
|
50
56
|
*
|
|
51
57
|
* @param driftClient - The Drift client instance
|
|
52
|
-
* @param
|
|
53
|
-
* @param
|
|
58
|
+
* @param swapClient - The swap client instance for performing the swap (supports UnifiedSwapClient or JupiterClient)
|
|
59
|
+
* @param jupiterClient - @deprecated Use swapClient instead. Kept for backwards compatibility.
|
|
60
|
+
* @param quote - Quote response from swap provider with routing information
|
|
54
61
|
* @param swapFromMarketIndex - Source token market index
|
|
55
62
|
* @param swapToMarketIndex - Destination token market index
|
|
56
63
|
* @param amount - Amount to swap in base units
|
|
@@ -58,5 +65,5 @@ interface CreateSwapTxnParams extends CreateSwapIxDetailsParams {
|
|
|
58
65
|
* @param txParams - Transaction parameters for fees and compute units
|
|
59
66
|
* @returns Promise resolving to either a legacy Transaction or VersionedTransaction ready for signing
|
|
60
67
|
*/
|
|
61
|
-
export declare const createSwapTxn: ({ driftClient, jupiterClient, quote, swapFromMarketIndex, swapToMarketIndex, amount, user, txParams, }: CreateSwapTxnParams) => Promise<Transaction | VersionedTransaction>;
|
|
68
|
+
export declare const createSwapTxn: ({ driftClient, swapClient, jupiterClient, quote, swapFromMarketIndex, swapToMarketIndex, amount, user, txParams, }: CreateSwapTxnParams) => Promise<Transaction | VersionedTransaction>;
|
|
62
69
|
export {};
|
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.createSwapTxn = exports.createSwapIxDetails = void 0;
|
|
4
|
+
const sdk_1 = require("@drift-labs/sdk");
|
|
4
5
|
/**
|
|
5
|
-
* Creates swap instruction details for a
|
|
6
|
+
* Creates swap instruction details for a swap through Drift
|
|
6
7
|
*
|
|
7
8
|
* @param driftClient - The Drift client instance
|
|
8
|
-
* @param
|
|
9
|
-
* @param
|
|
9
|
+
* @param swapClient - The swap client instance for performing the swap (supports UnifiedSwapClient or JupiterClient)
|
|
10
|
+
* @param jupiterClient - @deprecated Use swapClient instead. Kept for backwards compatibility.
|
|
11
|
+
* @param quote - Quote response from swap provider with routing information
|
|
10
12
|
* @param swapFromMarketIndex - Source token market index
|
|
11
13
|
* @param swapToMarketIndex - Destination token market index
|
|
12
14
|
* @param amount - Amount to swap in base units
|
|
@@ -15,18 +17,37 @@ exports.createSwapTxn = exports.createSwapIxDetails = void 0;
|
|
|
15
17
|
* @returns ixs - Array of Solana transaction instructions for the swap
|
|
16
18
|
* @returns lookupTables - Address lookup table accounts for transaction compression
|
|
17
19
|
*/
|
|
18
|
-
const createSwapIxDetails = async ({ driftClient, jupiterClient, quote, swapFromMarketIndex, swapToMarketIndex, amount, user, }) => {
|
|
20
|
+
const createSwapIxDetails = async ({ driftClient, swapClient, jupiterClient, quote, swapFromMarketIndex, swapToMarketIndex, amount, user, }) => {
|
|
21
|
+
// Use swapClient if provided, otherwise fall back to jupiterClient for backwards compatibility
|
|
22
|
+
const clientToUse = swapClient || jupiterClient;
|
|
23
|
+
if (!clientToUse) {
|
|
24
|
+
throw new Error('Either swapClient or jupiterClient must be provided');
|
|
25
|
+
}
|
|
19
26
|
const userPublicKey = user.getUserAccountPublicKey();
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
27
|
+
let swapIxsDetails;
|
|
28
|
+
// Use the appropriate method based on client type
|
|
29
|
+
if (clientToUse instanceof sdk_1.UnifiedSwapClient) {
|
|
30
|
+
swapIxsDetails = await driftClient.getSwapIxV2({
|
|
31
|
+
swapClient: clientToUse,
|
|
32
|
+
outMarketIndex: swapToMarketIndex,
|
|
33
|
+
inMarketIndex: swapFromMarketIndex,
|
|
34
|
+
amount,
|
|
35
|
+
quote,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
// JupiterClient path
|
|
40
|
+
swapIxsDetails = await driftClient.getJupiterSwapIxV6({
|
|
41
|
+
jupiterClient: clientToUse,
|
|
42
|
+
outMarketIndex: swapToMarketIndex,
|
|
43
|
+
inMarketIndex: swapFromMarketIndex,
|
|
44
|
+
amount,
|
|
45
|
+
quote,
|
|
46
|
+
userAccountPublicKey: userPublicKey,
|
|
47
|
+
// we skip passing in the associated token accounts and have the swap client derive them instead.
|
|
48
|
+
// The swap client will also add the ixs to create the associated token accounts if they don't exist.
|
|
49
|
+
});
|
|
50
|
+
}
|
|
30
51
|
return swapIxsDetails;
|
|
31
52
|
};
|
|
32
53
|
exports.createSwapIxDetails = createSwapIxDetails;
|
|
@@ -34,8 +55,9 @@ exports.createSwapIxDetails = createSwapIxDetails;
|
|
|
34
55
|
* Creates a complete swap transaction ready for signing and submission
|
|
35
56
|
*
|
|
36
57
|
* @param driftClient - The Drift client instance
|
|
37
|
-
* @param
|
|
38
|
-
* @param
|
|
58
|
+
* @param swapClient - The swap client instance for performing the swap (supports UnifiedSwapClient or JupiterClient)
|
|
59
|
+
* @param jupiterClient - @deprecated Use swapClient instead. Kept for backwards compatibility.
|
|
60
|
+
* @param quote - Quote response from swap provider with routing information
|
|
39
61
|
* @param swapFromMarketIndex - Source token market index
|
|
40
62
|
* @param swapToMarketIndex - Destination token market index
|
|
41
63
|
* @param amount - Amount to swap in base units
|
|
@@ -43,9 +65,10 @@ exports.createSwapIxDetails = createSwapIxDetails;
|
|
|
43
65
|
* @param txParams - Transaction parameters for fees and compute units
|
|
44
66
|
* @returns Promise resolving to either a legacy Transaction or VersionedTransaction ready for signing
|
|
45
67
|
*/
|
|
46
|
-
const createSwapTxn = async ({ driftClient, jupiterClient, quote, swapFromMarketIndex, swapToMarketIndex, amount, user, txParams, }) => {
|
|
68
|
+
const createSwapTxn = async ({ driftClient, swapClient, jupiterClient, quote, swapFromMarketIndex, swapToMarketIndex, amount, user, txParams, }) => {
|
|
47
69
|
const swapIxsDetails = await (0, exports.createSwapIxDetails)({
|
|
48
70
|
driftClient,
|
|
71
|
+
swapClient,
|
|
49
72
|
jupiterClient,
|
|
50
73
|
quote,
|
|
51
74
|
swapFromMarketIndex,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"swap.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/trade/swap.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"swap.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/trade/swap.ts"],"names":[],"mappings":";;;AAAA,yCAQyB;AAiCzB;;;;;;;;;;;;;;GAcG;AACI,MAAM,mBAAmB,GAAG,KAAK,EAAE,EACzC,WAAW,EACX,UAAU,EACV,aAAa,EACb,KAAK,EACL,mBAAmB,EACnB,iBAAiB,EACjB,MAAM,EACN,IAAI,GACuB,EAGzB,EAAE;IACJ,+FAA+F;IAC/F,MAAM,WAAW,GAAG,UAAU,IAAI,aAAa,CAAC;IAEhD,IAAI,CAAC,WAAW,EAAE,CAAC;QAClB,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;IACxE,CAA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n\tDriftClient,\n\tJupiterClient,\n\tQuoteResponse,\n\tTxParams,\n\tUnifiedSwapClient,\n\tUser,\n} from '@drift-labs/sdk';\nimport {\n\tAddressLookupTableAccount,\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\n\n/**\n * Parameters for creating swap instruction details\n */\ninterface CreateSwapIxDetailsParams {\n\t/** The Drift client instance for interacting with the Drift protocol */\n\tdriftClient: DriftClient;\n\t/** Quote response from swap provider containing swap route information */\n\tquote: QuoteResponse;\n\t/** Swap client instance for performing the swap (supports UnifiedSwapClient or JupiterClient) */\n\tswapClient?: UnifiedSwapClient | JupiterClient;\n\t/**\n\t * @deprecated Use swapClient instead. This parameter is kept for backwards compatibility.\n\t * Swap client instance for performing the swap\n\t */\n\tjupiterClient?: JupiterClient;\n\t/** Market index of the token being swapped from */\n\tswapFromMarketIndex: number;\n\t/** Market index of the token being swapped to */\n\tswapToMarketIndex: number;\n\t/** Amount to swap in base units */\n\tamount: BN;\n\t/** User instance containing account information */\n\tuser: User;\n}\n\n/**\n * Creates swap instruction details for a swap through Drift\n *\n * @param driftClient - The Drift client instance\n * @param swapClient - The swap client instance for performing the swap (supports UnifiedSwapClient or JupiterClient)\n * @param jupiterClient - @deprecated Use swapClient instead. Kept for backwards compatibility.\n * @param quote - Quote response from swap provider with routing information\n * @param swapFromMarketIndex - Source token market index\n * @param swapToMarketIndex - Destination token market index\n * @param amount - Amount to swap in base units\n * @param user - User account instance\n * @returns Promise resolving to an object containing transaction instructions and lookup tables\n * @returns ixs - Array of Solana transaction instructions for the swap\n * @returns lookupTables - Address lookup table accounts for transaction compression\n */\nexport const createSwapIxDetails = async ({\n\tdriftClient,\n\tswapClient,\n\tjupiterClient,\n\tquote,\n\tswapFromMarketIndex,\n\tswapToMarketIndex,\n\tamount,\n\tuser,\n}: CreateSwapIxDetailsParams): Promise<{\n\tixs: TransactionInstruction[];\n\tlookupTables: AddressLookupTableAccount[];\n}> => {\n\t// Use swapClient if provided, otherwise fall back to jupiterClient for backwards compatibility\n\tconst clientToUse = swapClient || jupiterClient;\n\n\tif (!clientToUse) {\n\t\tthrow new Error('Either swapClient or jupiterClient must be provided');\n\t}\n\n\tconst userPublicKey = user.getUserAccountPublicKey();\n\n\tlet swapIxsDetails: {\n\t\tixs: TransactionInstruction[];\n\t\tlookupTables: AddressLookupTableAccount[];\n\t};\n\n\t// Use the appropriate method based on client type\n\tif (clientToUse instanceof UnifiedSwapClient) {\n\t\tswapIxsDetails = await driftClient.getSwapIxV2({\n\t\t\tswapClient: clientToUse,\n\t\t\toutMarketIndex: swapToMarketIndex,\n\t\t\tinMarketIndex: swapFromMarketIndex,\n\t\t\tamount,\n\t\t\tquote,\n\t\t});\n\t} else {\n\t\t// JupiterClient path\n\t\tswapIxsDetails = await driftClient.getJupiterSwapIxV6({\n\t\t\tjupiterClient: clientToUse,\n\t\t\toutMarketIndex: swapToMarketIndex,\n\t\t\tinMarketIndex: swapFromMarketIndex,\n\t\t\tamount,\n\t\t\tquote,\n\t\t\tuserAccountPublicKey: userPublicKey,\n\t\t\t// we skip passing in the associated token accounts and have the swap client derive them instead.\n\t\t\t// The swap client will also add the ixs to create the associated token accounts if they don't exist.\n\t\t});\n\t}\n\n\treturn swapIxsDetails;\n};\n\n/**\n * Parameters for creating a complete swap transaction\n * Extends CreateSwapIxDetailsParams with additional transaction parameters\n */\ninterface CreateSwapTxnParams extends CreateSwapIxDetailsParams {\n\t/** Transaction parameters including compute units, priority fees, and other options */\n\ttxParams?: TxParams;\n}\n\n/**\n * Creates a complete swap transaction ready for signing and submission\n *\n * @param driftClient - The Drift client instance\n * @param swapClient - The swap client instance for performing the swap (supports UnifiedSwapClient or JupiterClient)\n * @param jupiterClient - @deprecated Use swapClient instead. Kept for backwards compatibility.\n * @param quote - Quote response from swap provider with routing information\n * @param swapFromMarketIndex - Source token market index\n * @param swapToMarketIndex - Destination token market index\n * @param amount - Amount to swap in base units\n * @param user - User account instance\n * @param txParams - Transaction parameters for fees and compute units\n * @returns Promise resolving to either a legacy Transaction or VersionedTransaction ready for signing\n */\nexport const createSwapTxn = async ({\n\tdriftClient,\n\tswapClient,\n\tjupiterClient,\n\tquote,\n\tswapFromMarketIndex,\n\tswapToMarketIndex,\n\tamount,\n\tuser,\n\ttxParams,\n}: CreateSwapTxnParams): Promise<Transaction | VersionedTransaction> => {\n\tconst swapIxsDetails = await createSwapIxDetails({\n\t\tdriftClient,\n\t\tswapClient,\n\t\tjupiterClient,\n\t\tquote,\n\t\tswapFromMarketIndex,\n\t\tswapToMarketIndex,\n\t\tamount,\n\t\tuser,\n\t});\n\n\tconst tx = await driftClient.buildTransaction(\n\t\tswapIxsDetails.ixs,\n\t\ttxParams,\n\t\t0,\n\t\tswapIxsDetails.lookupTables\n\t);\n\n\treturn tx;\n};\n"]}
|
package/lib/index.d.ts
CHANGED
|
@@ -31,6 +31,7 @@ export * from './clients/candleClient';
|
|
|
31
31
|
export * from './clients/marketDataFeed';
|
|
32
32
|
export * from './clients/swiftClient';
|
|
33
33
|
export * from './clients/tvFeed';
|
|
34
|
+
export * from './clients/DlobWebsocketClient';
|
|
34
35
|
export * from './utils/pollingSequenceGuard';
|
|
35
36
|
export * from './utils/driftEvents';
|
|
36
37
|
export * from './utils/MultiplexWebSocket';
|
package/lib/index.js
CHANGED
|
@@ -51,6 +51,7 @@ __exportStar(require("./clients/candleClient"), exports);
|
|
|
51
51
|
__exportStar(require("./clients/marketDataFeed"), exports);
|
|
52
52
|
__exportStar(require("./clients/swiftClient"), exports);
|
|
53
53
|
__exportStar(require("./clients/tvFeed"), exports);
|
|
54
|
+
__exportStar(require("./clients/DlobWebsocketClient"), exports);
|
|
54
55
|
__exportStar(require("./utils/pollingSequenceGuard"), exports);
|
|
55
56
|
__exportStar(require("./utils/driftEvents"), exports);
|
|
56
57
|
__exportStar(require("./utils/MultiplexWebSocket"), exports);
|
package/lib/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,2CAAyB;AACzB,mDAAiC;AACjC,0CAAwB;AACxB,yDAAuC;AACvC,0CAAwB;AACxB,gDAA8B;AAC9B,oDAAkC;AAClC,sDAAoC;AACpC,yDAAuC;AACvC,uDAAqC;AACrC,gEAA8C;AAC9C,qDAAmC;AACnC,gDAA8B;AAC9B,+CAA6B;AAC7B,iDAA+B;AAC/B,yDAAuC;AACvC,oDAAkC;AAClC,8CAA4B;AAC5B,wEAAsD;AACtD,yDAAuC;AACvC,oDAAkC;AAClC,wDAAsC;AACtC,qDAAmC;AACnC,gDAA8B;AAC9B,sDAAoC;AACpC,+EAA6D;AAC7D,sEAAoD;AACpD,wDAAsC;AACtC,oDAAkC;AAClC,yDAAuC;AACvC,2DAAyC;AACzC,wDAAsC;AACtC,mDAAiC;AACjC,+DAA6C;AAC7C,sDAAoC;AACpC,6DAA2C;AAC3C,mEAAiD;AACjD,0DAAwC;AACxC,+CAA6B;AAC7B,uDAAqC;AACrC,iDAA+B;AAC/B,0CAAwB;AAExB,0BAA0B;AAC1B,gHAA4E;AAEnE,sBAFF,iCAAW,CAEE;AADpB,gHAA4E;AACtD,sBADf,iCAAW,CACe;AAEjC,kGAAqE;AAC5D,sBADF,0BAAW,CACE","sourcesContent":["export * from './Config';\nexport * from './chartConstants';\nexport * from './types';\nexport * from './EnvironmentConstants';\nexport * from './utils';\nexport * from './utils/index';\nexport * from './utils/s3Buckets';\nexport * from './serializableTypes';\nexport * from './utils/candles/Candle';\nexport * from './utils/featureFlags';\nexport * from './utils/WalletConnectionState';\nexport * from './utils/rpcLatency';\nexport * from './utils/token';\nexport * from './utils/math';\nexport * from './utils/logger';\nexport * from './utils/equalityChecks';\nexport * from './common-ui-utils';\nexport * from './constants';\nexport * from './actions/actionHelpers/actionHelpers';\nexport * from './utils/SharedInterval';\nexport * from './utils/Stopwatch';\nexport * from './utils/priority-fees';\nexport * from './utils/superstake';\nexport * from './utils/fetch';\nexport * from './utils/priceImpact';\nexport * from './utils/dlob-server/DlobServerWebsocketUtils';\nexport * from './common-ui-utils/settings/settings';\nexport * from './utils/priority-fees';\nexport * from './utils/orderbook';\nexport * from './clients/candleClient';\nexport * from './clients/marketDataFeed';\nexport * from './clients/swiftClient';\nexport * from './clients/tvFeed';\nexport * from './utils/pollingSequenceGuard';\nexport * from './utils/driftEvents';\nexport * from './utils/MultiplexWebSocket';\nexport * from './utils/SlotBasedResultValidator';\nexport * from './utils/CircularBuffers';\nexport * from './utils/rxjs';\nexport * from './utils/priorityFees';\nexport * from './utils/NumLib';\nexport * from './drift';\n\n// External Program Errors\nimport JupV4Errors from './constants/autogenerated/jup-v4-error-codes.json';\nimport JupV6Errors from './constants/autogenerated/jup-v6-error-codes.json';\nexport { JupV4Errors, JupV6Errors };\n\nimport DriftErrors from './constants/autogenerated/driftErrors.json';\nexport { DriftErrors };\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,2CAAyB;AACzB,mDAAiC;AACjC,0CAAwB;AACxB,yDAAuC;AACvC,0CAAwB;AACxB,gDAA8B;AAC9B,oDAAkC;AAClC,sDAAoC;AACpC,yDAAuC;AACvC,uDAAqC;AACrC,gEAA8C;AAC9C,qDAAmC;AACnC,gDAA8B;AAC9B,+CAA6B;AAC7B,iDAA+B;AAC/B,yDAAuC;AACvC,oDAAkC;AAClC,8CAA4B;AAC5B,wEAAsD;AACtD,yDAAuC;AACvC,oDAAkC;AAClC,wDAAsC;AACtC,qDAAmC;AACnC,gDAA8B;AAC9B,sDAAoC;AACpC,+EAA6D;AAC7D,sEAAoD;AACpD,wDAAsC;AACtC,oDAAkC;AAClC,yDAAuC;AACvC,2DAAyC;AACzC,wDAAsC;AACtC,mDAAiC;AACjC,gEAA8C;AAC9C,+DAA6C;AAC7C,sDAAoC;AACpC,6DAA2C;AAC3C,mEAAiD;AACjD,0DAAwC;AACxC,+CAA6B;AAC7B,uDAAqC;AACrC,iDAA+B;AAC/B,0CAAwB;AAExB,0BAA0B;AAC1B,gHAA4E;AAEnE,sBAFF,iCAAW,CAEE;AADpB,gHAA4E;AACtD,sBADf,iCAAW,CACe;AAEjC,kGAAqE;AAC5D,sBADF,0BAAW,CACE","sourcesContent":["export * from './Config';\nexport * from './chartConstants';\nexport * from './types';\nexport * from './EnvironmentConstants';\nexport * from './utils';\nexport * from './utils/index';\nexport * from './utils/s3Buckets';\nexport * from './serializableTypes';\nexport * from './utils/candles/Candle';\nexport * from './utils/featureFlags';\nexport * from './utils/WalletConnectionState';\nexport * from './utils/rpcLatency';\nexport * from './utils/token';\nexport * from './utils/math';\nexport * from './utils/logger';\nexport * from './utils/equalityChecks';\nexport * from './common-ui-utils';\nexport * from './constants';\nexport * from './actions/actionHelpers/actionHelpers';\nexport * from './utils/SharedInterval';\nexport * from './utils/Stopwatch';\nexport * from './utils/priority-fees';\nexport * from './utils/superstake';\nexport * from './utils/fetch';\nexport * from './utils/priceImpact';\nexport * from './utils/dlob-server/DlobServerWebsocketUtils';\nexport * from './common-ui-utils/settings/settings';\nexport * from './utils/priority-fees';\nexport * from './utils/orderbook';\nexport * from './clients/candleClient';\nexport * from './clients/marketDataFeed';\nexport * from './clients/swiftClient';\nexport * from './clients/tvFeed';\nexport * from './clients/DlobWebsocketClient';\nexport * from './utils/pollingSequenceGuard';\nexport * from './utils/driftEvents';\nexport * from './utils/MultiplexWebSocket';\nexport * from './utils/SlotBasedResultValidator';\nexport * from './utils/CircularBuffers';\nexport * from './utils/rxjs';\nexport * from './utils/priorityFees';\nexport * from './utils/NumLib';\nexport * from './drift';\n\n// External Program Errors\nimport JupV4Errors from './constants/autogenerated/jup-v4-error-codes.json';\nimport JupV6Errors from './constants/autogenerated/jup-v6-error-codes.json';\nexport { JupV4Errors, JupV6Errors };\n\nimport DriftErrors from './constants/autogenerated/driftErrors.json';\nexport { DriftErrors };\n"]}
|
|
@@ -9,10 +9,11 @@ type WebSocketSubscriptionProps<T = Record<string, unknown>> = {
|
|
|
9
9
|
unsubscribeMessage: string;
|
|
10
10
|
onError: (err?: any) => void;
|
|
11
11
|
onMessage: (message: WebSocketMessage<T>) => void;
|
|
12
|
-
messageFilter
|
|
13
|
-
errorMessageFilter
|
|
12
|
+
messageFilter?: (message: WebSocketMessage<T>) => boolean;
|
|
13
|
+
errorMessageFilter?: (message: WebSocketMessage<T>) => boolean;
|
|
14
14
|
onClose?: () => void;
|
|
15
15
|
enableHeartbeatMonitoring?: boolean;
|
|
16
|
+
heartbeatTimeoutMs?: number;
|
|
16
17
|
};
|
|
17
18
|
type WebSocketSubscriptionState<T = Record<string, unknown>> = WebSocketSubscriptionProps<T> & {
|
|
18
19
|
hasSentSubscribeMessage?: boolean;
|
|
@@ -63,6 +64,7 @@ export declare class MultiplexWebSocket<T = Record<string, unknown>> implements
|
|
|
63
64
|
private closeTimeout;
|
|
64
65
|
private heartbeatTimeout;
|
|
65
66
|
private heartbeatMonitoringEnabled;
|
|
67
|
+
private heartbeatTimeoutMs;
|
|
66
68
|
private constructor();
|
|
67
69
|
/**
|
|
68
70
|
* Creates a new virtual websocket subscription. If an existing websocket for the given URL exists, the subscription will be added to the existing websocket.
|