@drift-labs/common 1.0.58 → 1.0.60
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/_deprecated/common-math.d.ts +10 -0
- package/lib/_deprecated/common-math.js +9 -0
- package/lib/_deprecated/common-math.js.map +1 -0
- package/lib/_deprecated/common-ui-utils.d.ts +248 -0
- package/lib/_deprecated/common-ui-utils.js +59 -0
- package/lib/_deprecated/common-ui-utils.js.map +1 -0
- package/lib/_deprecated/equality-checks.d.ts +2 -0
- package/lib/_deprecated/equality-checks.js +7 -0
- package/lib/_deprecated/equality-checks.js.map +1 -0
- package/lib/{common-ui-utils/market.d.ts → _deprecated/market-utils.d.ts} +5 -7
- package/lib/_deprecated/market-utils.js +18 -0
- package/lib/_deprecated/market-utils.js.map +1 -0
- package/lib/_deprecated/order-utils.d.ts +12 -0
- package/lib/_deprecated/order-utils.js +18 -0
- package/lib/_deprecated/order-utils.js.map +1 -0
- package/lib/_deprecated/trading-utils.d.ts +52 -0
- package/lib/_deprecated/trading-utils.js +27 -0
- package/lib/_deprecated/trading-utils.js.map +1 -0
- package/lib/_deprecated/user-utils.d.ts +17 -0
- package/lib/_deprecated/user-utils.js +12 -0
- package/lib/_deprecated/user-utils.js.map +1 -0
- package/lib/_deprecated/utils.d.ts +40 -0
- package/lib/_deprecated/utils.js +47 -0
- package/lib/_deprecated/utils.js.map +1 -0
- package/lib/clients/tvFeed.js +2 -2
- package/lib/clients/tvFeed.js.map +1 -1
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js +8 -8
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js.map +1 -1
- package/lib/drift/Drift/clients/AuthorityDrift/index.js +9 -9
- package/lib/drift/Drift/clients/AuthorityDrift/index.js.map +1 -1
- package/lib/drift/Drift/clients/CentralServerDrift/index.js +2 -2
- package/lib/drift/Drift/clients/CentralServerDrift/index.js.map +1 -1
- package/lib/drift/base/actions/trade/editOrder.d.ts +1 -1
- package/lib/drift/base/actions/trade/editOrder.js.map +1 -1
- package/lib/drift/base/actions/trade/margin.js +4 -4
- package/lib/drift/base/actions/trade/margin.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/auction.d.ts +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/auction.js +4 -3
- package/lib/drift/base/actions/trade/openPerpOrder/auction.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.js +2 -2
- package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.js +2 -2
- package/lib/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.d.ts +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js +4 -4
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.d.ts +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js +2 -2
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js +4 -3
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/positionMaxLeverage.js +2 -2
- package/lib/drift/base/actions/trade/openPerpOrder/positionMaxLeverage.js.map +1 -1
- package/lib/drift/base/actions/user/create.js +2 -2
- package/lib/drift/base/actions/user/create.js.map +1 -1
- package/lib/drift/base/details/user/balances.js +2 -2
- package/lib/drift/base/details/user/balances.js.map +1 -1
- package/lib/drift/base/details/user/positions.js +2 -2
- package/lib/drift/base/details/user/positions.js.map +1 -1
- package/lib/index.d.ts +28 -28
- package/lib/index.js +44 -29
- package/lib/index.js.map +1 -1
- package/lib/utils/accounts/index.d.ts +6 -0
- package/lib/utils/accounts/index.js +23 -0
- package/lib/utils/accounts/index.js.map +1 -0
- package/lib/utils/accounts/init.d.ts +22 -0
- package/lib/utils/accounts/init.js +90 -0
- package/lib/utils/accounts/init.js.map +1 -0
- package/lib/utils/accounts/keys.d.ts +22 -0
- package/lib/utils/accounts/keys.js +36 -0
- package/lib/utils/accounts/keys.js.map +1 -0
- package/lib/utils/accounts/multiple.d.ts +14 -0
- package/lib/utils/accounts/multiple.js +45 -0
- package/lib/utils/accounts/multiple.js.map +1 -0
- package/lib/utils/accounts/signature.d.ts +6 -0
- package/lib/utils/accounts/signature.js +53 -0
- package/lib/utils/accounts/signature.js.map +1 -0
- package/lib/utils/accounts/subaccounts.d.ts +8 -0
- package/lib/utils/accounts/subaccounts.js +31 -0
- package/lib/utils/accounts/subaccounts.js.map +1 -0
- package/lib/utils/{WalletConnectionState.d.ts → accounts/wallet.d.ts} +7 -1
- package/lib/utils/{WalletConnectionState.js → accounts/wallet.js} +32 -2
- package/lib/utils/accounts/wallet.js.map +1 -0
- package/lib/utils/core/arrays.d.ts +2 -0
- package/lib/utils/core/arrays.js +25 -0
- package/lib/utils/core/arrays.js.map +1 -0
- package/lib/utils/core/async.d.ts +5 -0
- package/lib/utils/core/async.js +17 -0
- package/lib/utils/core/async.js.map +1 -0
- package/lib/utils/core/cache.d.ts +1 -0
- package/lib/utils/core/cache.js +40 -0
- package/lib/utils/core/cache.js.map +1 -0
- package/lib/utils/core/data-structures.d.ts +30 -0
- package/lib/utils/core/data-structures.js +84 -0
- package/lib/utils/core/data-structures.js.map +1 -0
- package/lib/utils/{equalityChecks.d.ts → core/equality.d.ts} +1 -1
- package/lib/utils/{equalityChecks.js → core/equality.js} +3 -3
- package/lib/utils/core/equality.js.map +1 -0
- package/lib/utils/core/fetch.js.map +1 -0
- package/lib/utils/core/index.d.ts +7 -0
- package/lib/utils/core/index.js +24 -0
- package/lib/utils/core/index.js.map +1 -0
- package/lib/utils/core/serialization.d.ts +30 -0
- package/lib/utils/core/serialization.js +92 -0
- package/lib/utils/core/serialization.js.map +1 -0
- package/lib/utils/{enum.js → enum/index.js} +1 -1
- package/lib/utils/enum/index.js.map +1 -0
- package/lib/utils/index.d.ts +11 -176
- package/lib/utils/index.js +25 -594
- package/lib/utils/index.js.map +1 -1
- package/lib/utils/markets/balances.d.ts +6 -0
- package/lib/utils/markets/balances.js +29 -0
- package/lib/utils/markets/balances.js.map +1 -0
- package/lib/utils/markets/config.d.ts +5 -0
- package/lib/utils/markets/config.js +24 -0
- package/lib/utils/markets/config.js.map +1 -0
- package/lib/utils/markets/index.d.ts +6 -0
- package/lib/utils/markets/index.js +23 -0
- package/lib/utils/markets/index.js.map +1 -0
- package/lib/utils/markets/interest.d.ts +25 -0
- package/lib/utils/markets/interest.js +65 -0
- package/lib/utils/markets/interest.js.map +1 -0
- package/lib/utils/markets/leverage.d.ts +12 -0
- package/lib/utils/markets/leverage.js +60 -0
- package/lib/utils/markets/leverage.js.map +1 -0
- package/lib/utils/markets/operations.d.ts +21 -0
- package/lib/utils/markets/operations.js +59 -0
- package/lib/utils/markets/operations.js.map +1 -0
- package/lib/utils/math/bignum.d.ts +3 -0
- package/lib/utils/math/bignum.js +16 -0
- package/lib/utils/math/bignum.js.map +1 -0
- package/lib/utils/math/bn.d.ts +7 -0
- package/lib/utils/math/bn.js +58 -0
- package/lib/utils/math/bn.js.map +1 -0
- package/lib/utils/math/index.d.ts +7 -0
- package/lib/utils/math/index.js +24 -0
- package/lib/utils/math/index.js.map +1 -0
- package/lib/utils/math/numbers.d.ts +13 -0
- package/lib/utils/math/numbers.js +56 -0
- package/lib/utils/math/numbers.js.map +1 -0
- package/lib/utils/math/precision.d.ts +19 -0
- package/lib/utils/math/precision.js +73 -0
- package/lib/utils/math/precision.js.map +1 -0
- package/lib/utils/math/price.d.ts +12 -0
- package/lib/utils/math/price.js +45 -0
- package/lib/utils/math/price.js.map +1 -0
- package/lib/utils/math/sort.d.ts +13 -0
- package/lib/utils/math/sort.js +33 -0
- package/lib/utils/math/sort.js.map +1 -0
- package/lib/utils/math/spread.d.ts +8 -0
- package/lib/utils/math/spread.js +87 -0
- package/lib/utils/math/spread.js.map +1 -0
- package/lib/utils/orderbook/index.js +4 -4
- package/lib/utils/orderbook/index.js.map +1 -1
- package/lib/utils/orders/filters.d.ts +7 -0
- package/lib/utils/orders/filters.js +31 -0
- package/lib/utils/orders/filters.js.map +1 -0
- package/lib/utils/orders/flags.d.ts +12 -0
- package/lib/utils/orders/flags.js +44 -0
- package/lib/utils/orders/flags.js.map +1 -0
- package/lib/utils/orders/index.d.ts +6 -0
- package/lib/utils/orders/index.js +23 -0
- package/lib/utils/orders/index.js.map +1 -0
- package/lib/utils/orders/labels.d.ts +4 -0
- package/lib/utils/orders/labels.js +122 -0
- package/lib/utils/orders/labels.js.map +1 -0
- package/lib/utils/orders/misc.d.ts +11 -0
- package/lib/utils/orders/misc.js +27 -0
- package/lib/utils/orders/misc.js.map +1 -0
- package/lib/utils/orders/oracle.d.ts +5 -0
- package/lib/utils/orders/oracle.js +23 -0
- package/lib/utils/orders/oracle.js.map +1 -0
- package/lib/utils/orders/sort.d.ts +38 -0
- package/lib/utils/orders/sort.js +83 -0
- package/lib/utils/orders/sort.js.map +1 -0
- package/lib/utils/positions/index.d.ts +2 -0
- package/lib/{common-ui-utils → utils/positions}/index.js +1 -5
- package/lib/utils/positions/index.js.map +1 -0
- package/lib/utils/positions/open.d.ts +4 -0
- package/lib/{common-ui-utils/user.js → utils/positions/open.js} +10 -81
- package/lib/utils/positions/open.js.map +1 -0
- package/lib/utils/positions/user.d.ts +37 -0
- package/lib/utils/positions/user.js +74 -0
- package/lib/utils/positions/user.js.map +1 -0
- package/lib/utils/settings/settings.js.map +1 -0
- package/lib/utils/strings/convert.d.ts +11 -0
- package/lib/utils/{strings.js → strings/convert.js} +2 -51
- package/lib/utils/strings/convert.js.map +1 -0
- package/lib/utils/strings/format.d.ts +14 -0
- package/lib/utils/strings/format.js +61 -0
- package/lib/utils/strings/format.js.map +1 -0
- package/lib/utils/strings/index.d.ts +4 -0
- package/lib/utils/strings/index.js +21 -0
- package/lib/utils/strings/index.js.map +1 -0
- package/lib/utils/strings/parse.d.ts +4 -0
- package/lib/utils/strings/parse.js +25 -0
- package/lib/utils/strings/parse.js.map +1 -0
- package/lib/utils/strings/status.d.ts +15 -0
- package/lib/utils/strings/status.js +21 -0
- package/lib/utils/strings/status.js.map +1 -0
- package/lib/utils/token/account.d.ts +16 -0
- package/lib/utils/token/account.js +36 -0
- package/lib/utils/token/account.js.map +1 -0
- package/lib/utils/{token.d.ts → token/address.d.ts} +2 -7
- package/lib/utils/token/address.js +30 -0
- package/lib/utils/token/address.js.map +1 -0
- package/lib/utils/token/index.d.ts +3 -0
- package/lib/utils/token/index.js +20 -0
- package/lib/utils/token/index.js.map +1 -0
- package/lib/utils/token/instructions.d.ts +3 -0
- package/lib/utils/token/instructions.js +17 -0
- package/lib/utils/token/instructions.js.map +1 -0
- package/lib/utils/trading/auction.d.ts +82 -0
- package/lib/utils/trading/auction.js +208 -0
- package/lib/utils/trading/auction.js.map +1 -0
- package/lib/utils/trading/index.d.ts +7 -0
- package/lib/utils/trading/index.js +24 -0
- package/lib/utils/trading/index.js.map +1 -0
- package/lib/utils/trading/leverage.d.ts +18 -0
- package/lib/utils/trading/leverage.js +79 -0
- package/lib/utils/trading/leverage.js.map +1 -0
- package/lib/utils/trading/liquidation.d.ts +22 -0
- package/lib/utils/trading/liquidation.js +67 -0
- package/lib/utils/trading/liquidation.js.map +1 -0
- package/lib/utils/trading/lp.d.ts +4 -0
- package/lib/utils/trading/lp.js +20 -0
- package/lib/utils/trading/lp.js.map +1 -0
- package/lib/utils/trading/pnl.d.ts +34 -0
- package/lib/utils/trading/pnl.js +88 -0
- package/lib/utils/trading/pnl.js.map +1 -0
- package/lib/utils/trading/price.d.ts +12 -0
- package/lib/utils/trading/price.js +36 -0
- package/lib/utils/trading/price.js.map +1 -0
- package/lib/utils/trading/size.d.ts +27 -0
- package/lib/utils/trading/size.js +83 -0
- package/lib/utils/trading/size.js.map +1 -0
- package/lib/utils/{validation.d.ts → validation/address.d.ts} +1 -2
- package/lib/utils/{validation.js → validation/address.js} +4 -6
- package/lib/utils/validation/address.js.map +1 -0
- package/lib/utils/validation/index.d.ts +3 -0
- package/lib/utils/validation/index.js +20 -0
- package/lib/utils/validation/index.js.map +1 -0
- package/lib/utils/validation/input.d.ts +3 -0
- package/lib/utils/validation/input.js +33 -0
- package/lib/utils/validation/input.js.map +1 -0
- package/lib/utils/validation/notional.d.ts +2 -0
- package/lib/utils/validation/notional.js +8 -0
- package/lib/utils/validation/notional.js.map +1 -0
- package/package.json +92 -5
- package/lib/common-ui-utils/commonUiUtils.d.ts +0 -251
- package/lib/common-ui-utils/commonUiUtils.js +0 -647
- package/lib/common-ui-utils/commonUiUtils.js.map +0 -1
- package/lib/common-ui-utils/index.d.ts +0 -6
- package/lib/common-ui-utils/index.js.map +0 -1
- package/lib/common-ui-utils/market.js +0 -134
- package/lib/common-ui-utils/market.js.map +0 -1
- package/lib/common-ui-utils/order.d.ts +0 -25
- package/lib/common-ui-utils/order.js +0 -191
- package/lib/common-ui-utils/order.js.map +0 -1
- package/lib/common-ui-utils/settings/settings.js.map +0 -1
- package/lib/common-ui-utils/trading.d.ts +0 -79
- package/lib/common-ui-utils/trading.js +0 -313
- package/lib/common-ui-utils/trading.js.map +0 -1
- package/lib/common-ui-utils/user.d.ts +0 -18
- package/lib/common-ui-utils/user.js.map +0 -1
- package/lib/utils/WalletConnectionState.js.map +0 -1
- package/lib/utils/enum.js.map +0 -1
- package/lib/utils/equalityChecks.js.map +0 -1
- package/lib/utils/fetch.js.map +0 -1
- package/lib/utils/math.d.ts +0 -31
- package/lib/utils/math.js +0 -181
- package/lib/utils/math.js.map +0 -1
- package/lib/utils/strings.d.ts +0 -34
- package/lib/utils/strings.js.map +0 -1
- package/lib/utils/token.js +0 -45
- package/lib/utils/token.js.map +0 -1
- package/lib/utils/validation.js.map +0 -1
- /package/lib/utils/{fetch.d.ts → core/fetch.d.ts} +0 -0
- /package/lib/utils/{fetch.js → core/fetch.js} +0 -0
- /package/lib/utils/{enum.d.ts → enum/index.d.ts} +0 -0
- /package/lib/{common-ui-utils → utils}/settings/settings.d.ts +0 -0
- /package/lib/{common-ui-utils → utils}/settings/settings.js +0 -0
|
@@ -5,7 +5,7 @@ const sdk_1 = require("@drift-labs/sdk");
|
|
|
5
5
|
const openSwiftOrder_1 = require("../openSwiftOrder");
|
|
6
6
|
const orderParams_1 = require("../../../../../utils/orderParams");
|
|
7
7
|
const utils_1 = require("../../../../../../utils");
|
|
8
|
-
const
|
|
8
|
+
const order_utils_1 = require("../../../../../../_deprecated/order-utils");
|
|
9
9
|
const openPerpMarketOrder_1 = require("../openPerpMarketOrder");
|
|
10
10
|
const positionMaxLeverage_1 = require("../positionMaxLeverage");
|
|
11
11
|
const auction_1 = require("../auction");
|
|
@@ -142,7 +142,7 @@ const createOpenPerpNonMarketOrderIxs = async (params) => {
|
|
|
142
142
|
postOnly,
|
|
143
143
|
userOrderId,
|
|
144
144
|
});
|
|
145
|
-
const bitFlags =
|
|
145
|
+
const bitFlags = order_utils_1.ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(marketIndex, driftClient, user, positionMaxLeverage, highLeverageOptions);
|
|
146
146
|
orderParams.bitFlags = bitFlags;
|
|
147
147
|
allOrders.push(orderParams);
|
|
148
148
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.ts"],"names":[],"mappings":";;;AAAA,yCAUyB;AAOzB,sDAK2B;AAC3B,kEAG0C;AAC1C,mDAAqD;AACrD,uEAG2C;AAC3C,gEAA6E;AAS7E,gEAA0E;AAC1E,wCAAwD;AACxD,wEAGoC;AAkEpC,6BAA6B;AAC7B;;GA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AM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;QACnE,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;AA3BW,QAAA,4BAA4B,gCA2BvC","sourcesContent":["import {\n\tDriftClient,\n\tUser,\n\tBN,\n\tMarketType,\n\tPostOnlyParams,\n\tOptionalOrderParams,\n\tPositionDirection,\n\tOrderParamsBitFlag,\n\tOrderType,\n} from '@drift-labs/sdk';\nimport {\n\tPublicKey,\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport {\n\tprepSignAndSendSwiftOrder,\n\tprepSwiftOrderMessage,\n\tSwiftOrderOptions,\n\tSwiftOrderMessage,\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\tIsolatedPositionDepositsOverride,\n} from '../types';\nimport { WithTxnParams } from '../../../../types';\nimport { getPositionMaxLeverageIxIfNeeded } from '../positionMaxLeverage';\nimport { getLimitAuctionOrderParams } from '../auction';\nimport {\n\tgetIsolatedPositionDepositIxIfNeeded,\n\tresolveIsolatedPositionDepositsWithOverride,\n} from '../isolatedPositionDeposit';\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\t/**\n\t * Position margin mode to use for the order.\n\t * When 'isolated', auto-computes isolated position deposit from positionMaxLeverage,\n\t * and any additional isolated position deposits need to replenish under-collateralized positions.\n\t * If not provided, the position margin mode will be derived from the user's position margin mode,\n\t * and if that does not exist, it will default to 'cross'.\n\t */\n\tmarginMode?: 'isolated' | 'cross';\n\t/**\n\t * Pre-computed isolated position deposits override. When provided,\n\t * skips auto-compute and uses these values directly.\n\t */\n\tisolatedPositionDepositsOverride?: IsolatedPositionDepositsOverride;\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// TODO: add isolated margin?\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\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\tmarginMode,\n\t\tmainSignerOverride,\n\t\thighLeverageOptions,\n\t\tisolatedPositionDepositsOverride,\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 resolvedDeposits = resolveIsolatedPositionDepositsWithOverride(\n\t\tisolatedPositionDepositsOverride,\n\t\t{\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tmarketIndex,\n\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\tdirection,\n\t\t\tpositionMaxLeverage,\n\t\t\tmarginMode,\n\t\t\treplenishUnderwaterPositions: true,\n\t\t\tnumOfOpenHighLeverageSpots:\n\t\t\t\thighLeverageOptions?.numOfOpenHighLeverageSpots,\n\t\t}\n\t);\n\n\tconst mainIsolatedPositionDeposit = resolvedDeposits?.mainDeposit;\n\tconst resolvedAdditionalDeposits =\n\t\tresolvedDeposits?.additionalIsolatedPositionDeposits;\n\n\tconst allOrders: OptionalOrderParams[] = [];\n\tconst allIxs: TransactionInstruction[] = [];\n\n\t// Fetch all deposit/leverage ixs in parallel\n\tconst [leverageIx, additionalDepositIxs, isolatedPositionDepositIx] =\n\t\tawait Promise.all([\n\t\t\tgetPositionMaxLeverageIxIfNeeded(\n\t\t\t\tdriftClient,\n\t\t\t\tuser,\n\t\t\t\tmarketIndex,\n\t\t\t\tpositionMaxLeverage,\n\t\t\t\tmainSignerOverride\n\t\t\t),\n\t\t\tresolvedAdditionalDeposits?.length\n\t\t\t\t? Promise.all(\n\t\t\t\t\t\tresolvedAdditionalDeposits.map((deposit) =>\n\t\t\t\t\t\t\tgetIsolatedPositionDepositIxIfNeeded(\n\t\t\t\t\t\t\t\tdriftClient,\n\t\t\t\t\t\t\t\tuser,\n\t\t\t\t\t\t\t\tdeposit.marketIndex,\n\t\t\t\t\t\t\t\tdeposit.amount,\n\t\t\t\t\t\t\t\tmainSignerOverride\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t)\n\t\t\t\t )\n\t\t\t\t: Promise.resolve([] as (TransactionInstruction | undefined)[]),\n\t\t\tgetIsolatedPositionDepositIxIfNeeded(\n\t\t\t\tdriftClient,\n\t\t\t\tuser,\n\t\t\t\tmarketIndex,\n\t\t\t\tmainIsolatedPositionDeposit,\n\t\t\t\tmainSignerOverride\n\t\t\t),\n\t\t]);\n\n\tif (leverageIx) {\n\t\tallIxs.push(leverageIx);\n\t}\n\tfor (const ix of additionalDepositIxs) {\n\t\tif (ix) {\n\t\t\tallIxs.push(ix);\n\t\t}\n\t}\n\tif (isolatedPositionDepositIx) {\n\t\tallIxs.push(isolatedPositionDepositIx);\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\torderType: OrderType.LIMIT,\n\t\t\t\t\tprice: orderConfig.limitPrice,\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\treduceOnly,\n\t\t\t\t\tpositionMaxLeverage,\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 bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\t\tmarketIndex,\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tpositionMaxLeverage,\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\n/**\n * Shared prep logic for swift limit orders: validates limit price, resolves base asset amount,\n * computes order params (with or without limit auction), and resolves the user account.\n */\nasync function prepSwiftLimitOrderData(\n\tparams: OpenPerpNonMarketOrderBaseParams & {\n\t\torderConfig: LimitOrderParamsOrderConfig;\n\t}\n) {\n\tconst { user, marketIndex, 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\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\n\treturn { userAccount, orderParams };\n}\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 { userAccount, orderParams } = await prepSwiftLimitOrderData(params);\n\n\tconst resolvedDeposits = resolveIsolatedPositionDepositsWithOverride(\n\t\tparams.isolatedPositionDepositsOverride,\n\t\t{\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tmarketIndex,\n\t\t\tbaseAssetAmount: orderParams.baseAssetAmount,\n\t\t\tdirection: orderParams.direction,\n\t\t\tpositionMaxLeverage: params.positionMaxLeverage,\n\t\t\tmarginMode: params.marginMode,\n\t\t\treplenishUnderwaterPositions: false, // Swift doesn't support additional deposits, so throw on underwater positions\n\t\t\tnumOfOpenHighLeverageSpots:\n\t\t\t\tparams.highLeverageOptions?.numOfOpenHighLeverageSpots,\n\t\t}\n\t);\n\n\tawait prepSignAndSendSwiftOrder({\n\t\tdriftClient,\n\t\tsubAccountId: userAccount.subAccountId,\n\t\tuserAccountPubKey: user.userAccountPublicKey,\n\t\tmarketIndex,\n\t\tuserSigningSlotBuffer: swiftOptions.userSigningSlotBuffer,\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\tisolatedPositionDeposit: resolvedDeposits?.mainDeposit,\n\t\t},\n\t\tbuilderParams: params.builderParams,\n\t});\n};\n\nexport type CreateSwiftLimitOrderMessageParams = Omit<\n\tOpenPerpNonMarketOrderBaseParams,\n\t'mainSignerOverride'\n> & {\n\torderConfig: LimitOrderParamsOrderConfig;\n\tisDelegate?: boolean;\n\tuserSigningSlotBuffer?: number;\n};\n\n/**\n * Prepares a Swift limit order message without signing or sending it.\n *\n * @returns The prepared SwiftOrderMessage ready for client-side signing and sending\n */\nexport const createSwiftLimitOrderMessage = async (\n\tparams: CreateSwiftLimitOrderMessageParams\n): Promise<SwiftOrderMessage> => {\n\tconst {\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\torderConfig,\n\t\tisDelegate = false,\n\t\tuserSigningSlotBuffer,\n\t} = params;\n\n\tconst { userAccount, orderParams } = await prepSwiftLimitOrderData(params);\n\n\tconst resolvedDeposits = resolveIsolatedPositionDepositsWithOverride(\n\t\tparams.isolatedPositionDepositsOverride,\n\t\t{\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tmarketIndex,\n\t\t\tbaseAssetAmount: orderParams.baseAssetAmount,\n\t\t\tdirection: orderParams.direction,\n\t\t\tpositionMaxLeverage: params.positionMaxLeverage,\n\t\t\tmarginMode: params.marginMode,\n\t\t\treplenishUnderwaterPositions: false, // Swift doesn't support additional deposits, so throw on underwater positions\n\t\t\tnumOfOpenHighLeverageSpots:\n\t\t\t\tparams.highLeverageOptions?.numOfOpenHighLeverageSpots,\n\t\t}\n\t);\n\n\treturn prepSwiftOrderMessage({\n\t\tdriftClient,\n\t\tsubAccountId: userAccount.subAccountId,\n\t\tuserAccountPubKey: user.userAccountPublicKey,\n\t\tmarketIndex,\n\t\tuserSigningSlotBuffer,\n\t\tisDelegate,\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\tisolatedPositionDeposit: resolvedDeposits?.mainDeposit,\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\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,sDAK2B;AAC3B,kEAG0C;AAC1C,mDAAqD;AACrD,2EAA+E;AAE/E,gEAA6E;AAS7E,gEAA0E;AAC1E,wCAAwD;AACxD,wEAGoC;AAkEpC,6BAA6B;AAC7B;;GAEG;AACI,MAAM,sCAAsC,GAAG,KAAK,EAAE,MAS5D,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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O,cAAqC,CAAC;AAC9C,CAAC,CAAC;AA3BW,QAAA,4BAA4B,gCA2BvC","sourcesContent":["import {\n\tDriftClient,\n\tUser,\n\tBN,\n\tMarketType,\n\tPostOnlyParams,\n\tOptionalOrderParams,\n\tPositionDirection,\n\tOrderParamsBitFlag,\n\tOrderType,\n} from '@drift-labs/sdk';\nimport {\n\tPublicKey,\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport {\n\tprepSignAndSendSwiftOrder,\n\tprepSwiftOrderMessage,\n\tSwiftOrderOptions,\n\tSwiftOrderMessage,\n} from '../openSwiftOrder';\nimport {\n\tbuildNonMarketOrderParams,\n\tresolveBaseAssetAmount,\n} from '../../../../../utils/orderParams';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport { ORDER_COMMON_UTILS } from '../../../../../../_deprecated/order-utils';\nimport { HighLeverageOptions } from '../../../../../../utils/orders';\nimport { createPlaceAndTakePerpMarketOrderIx } from '../openPerpMarketOrder';\nimport {\n\tTxnOrSwiftResult,\n\tLimitAuctionConfig,\n\tLimitOrderParamsOrderConfig,\n\tNonMarketOrderParamsConfig,\n\tIsolatedPositionDepositsOverride,\n} from '../types';\nimport { WithTxnParams } from '../../../../types';\nimport { getPositionMaxLeverageIxIfNeeded } from '../positionMaxLeverage';\nimport { getLimitAuctionOrderParams } from '../auction';\nimport {\n\tgetIsolatedPositionDepositIxIfNeeded,\n\tresolveIsolatedPositionDepositsWithOverride,\n} from '../isolatedPositionDeposit';\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\t/**\n\t * Position margin mode to use for the order.\n\t * When 'isolated', auto-computes isolated position deposit from positionMaxLeverage,\n\t * and any additional isolated position deposits need to replenish under-collateralized positions.\n\t * If not provided, the position margin mode will be derived from the user's position margin mode,\n\t * and if that does not exist, it will default to 'cross'.\n\t */\n\tmarginMode?: 'isolated' | 'cross';\n\t/**\n\t * Pre-computed isolated position deposits override. When provided,\n\t * skips auto-compute and uses these values directly.\n\t */\n\tisolatedPositionDepositsOverride?: IsolatedPositionDepositsOverride;\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// TODO: add isolated margin?\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\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\tmarginMode,\n\t\tmainSignerOverride,\n\t\thighLeverageOptions,\n\t\tisolatedPositionDepositsOverride,\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 resolvedDeposits = resolveIsolatedPositionDepositsWithOverride(\n\t\tisolatedPositionDepositsOverride,\n\t\t{\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tmarketIndex,\n\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\tdirection,\n\t\t\tpositionMaxLeverage,\n\t\t\tmarginMode,\n\t\t\treplenishUnderwaterPositions: true,\n\t\t\tnumOfOpenHighLeverageSpots:\n\t\t\t\thighLeverageOptions?.numOfOpenHighLeverageSpots,\n\t\t}\n\t);\n\n\tconst mainIsolatedPositionDeposit = resolvedDeposits?.mainDeposit;\n\tconst resolvedAdditionalDeposits =\n\t\tresolvedDeposits?.additionalIsolatedPositionDeposits;\n\n\tconst allOrders: OptionalOrderParams[] = [];\n\tconst allIxs: TransactionInstruction[] = [];\n\n\t// Fetch all deposit/leverage ixs in parallel\n\tconst [leverageIx, additionalDepositIxs, isolatedPositionDepositIx] =\n\t\tawait Promise.all([\n\t\t\tgetPositionMaxLeverageIxIfNeeded(\n\t\t\t\tdriftClient,\n\t\t\t\tuser,\n\t\t\t\tmarketIndex,\n\t\t\t\tpositionMaxLeverage,\n\t\t\t\tmainSignerOverride\n\t\t\t),\n\t\t\tresolvedAdditionalDeposits?.length\n\t\t\t\t? Promise.all(\n\t\t\t\t\t\tresolvedAdditionalDeposits.map((deposit) =>\n\t\t\t\t\t\t\tgetIsolatedPositionDepositIxIfNeeded(\n\t\t\t\t\t\t\t\tdriftClient,\n\t\t\t\t\t\t\t\tuser,\n\t\t\t\t\t\t\t\tdeposit.marketIndex,\n\t\t\t\t\t\t\t\tdeposit.amount,\n\t\t\t\t\t\t\t\tmainSignerOverride\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t)\n\t\t\t\t )\n\t\t\t\t: Promise.resolve([] as (TransactionInstruction | undefined)[]),\n\t\t\tgetIsolatedPositionDepositIxIfNeeded(\n\t\t\t\tdriftClient,\n\t\t\t\tuser,\n\t\t\t\tmarketIndex,\n\t\t\t\tmainIsolatedPositionDeposit,\n\t\t\t\tmainSignerOverride\n\t\t\t),\n\t\t]);\n\n\tif (leverageIx) {\n\t\tallIxs.push(leverageIx);\n\t}\n\tfor (const ix of additionalDepositIxs) {\n\t\tif (ix) {\n\t\t\tallIxs.push(ix);\n\t\t}\n\t}\n\tif (isolatedPositionDepositIx) {\n\t\tallIxs.push(isolatedPositionDepositIx);\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\torderType: OrderType.LIMIT,\n\t\t\t\t\tprice: orderConfig.limitPrice,\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\treduceOnly,\n\t\t\t\t\tpositionMaxLeverage,\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 bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\t\tmarketIndex,\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tpositionMaxLeverage,\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\n/**\n * Shared prep logic for swift limit orders: validates limit price, resolves base asset amount,\n * computes order params (with or without limit auction), and resolves the user account.\n */\nasync function prepSwiftLimitOrderData(\n\tparams: OpenPerpNonMarketOrderBaseParams & {\n\t\torderConfig: LimitOrderParamsOrderConfig;\n\t}\n) {\n\tconst { user, marketIndex, 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\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\n\treturn { userAccount, orderParams };\n}\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 { userAccount, orderParams } = await prepSwiftLimitOrderData(params);\n\n\tconst resolvedDeposits = resolveIsolatedPositionDepositsWithOverride(\n\t\tparams.isolatedPositionDepositsOverride,\n\t\t{\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tmarketIndex,\n\t\t\tbaseAssetAmount: orderParams.baseAssetAmount,\n\t\t\tdirection: orderParams.direction,\n\t\t\tpositionMaxLeverage: params.positionMaxLeverage,\n\t\t\tmarginMode: params.marginMode,\n\t\t\treplenishUnderwaterPositions: false, // Swift doesn't support additional deposits, so throw on underwater positions\n\t\t\tnumOfOpenHighLeverageSpots:\n\t\t\t\tparams.highLeverageOptions?.numOfOpenHighLeverageSpots,\n\t\t}\n\t);\n\n\tawait prepSignAndSendSwiftOrder({\n\t\tdriftClient,\n\t\tsubAccountId: userAccount.subAccountId,\n\t\tuserAccountPubKey: user.userAccountPublicKey,\n\t\tmarketIndex,\n\t\tuserSigningSlotBuffer: swiftOptions.userSigningSlotBuffer,\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\tisolatedPositionDeposit: resolvedDeposits?.mainDeposit,\n\t\t},\n\t\tbuilderParams: params.builderParams,\n\t});\n};\n\nexport type CreateSwiftLimitOrderMessageParams = Omit<\n\tOpenPerpNonMarketOrderBaseParams,\n\t'mainSignerOverride'\n> & {\n\torderConfig: LimitOrderParamsOrderConfig;\n\tisDelegate?: boolean;\n\tuserSigningSlotBuffer?: number;\n};\n\n/**\n * Prepares a Swift limit order message without signing or sending it.\n *\n * @returns The prepared SwiftOrderMessage ready for client-side signing and sending\n */\nexport const createSwiftLimitOrderMessage = async (\n\tparams: CreateSwiftLimitOrderMessageParams\n): Promise<SwiftOrderMessage> => {\n\tconst {\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\torderConfig,\n\t\tisDelegate = false,\n\t\tuserSigningSlotBuffer,\n\t} = params;\n\n\tconst { userAccount, orderParams } = await prepSwiftLimitOrderData(params);\n\n\tconst resolvedDeposits = resolveIsolatedPositionDepositsWithOverride(\n\t\tparams.isolatedPositionDepositsOverride,\n\t\t{\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tmarketIndex,\n\t\t\tbaseAssetAmount: orderParams.baseAssetAmount,\n\t\t\tdirection: orderParams.direction,\n\t\t\tpositionMaxLeverage: params.positionMaxLeverage,\n\t\t\tmarginMode: params.marginMode,\n\t\t\treplenishUnderwaterPositions: false, // Swift doesn't support additional deposits, so throw on underwater positions\n\t\t\tnumOfOpenHighLeverageSpots:\n\t\t\t\tparams.highLeverageOptions?.numOfOpenHighLeverageSpots,\n\t\t}\n\t);\n\n\treturn prepSwiftOrderMessage({\n\t\tdriftClient,\n\t\tsubAccountId: userAccount.subAccountId,\n\t\tuserAccountPubKey: user.userAccountPublicKey,\n\t\tmarketIndex,\n\t\tuserSigningSlotBuffer,\n\t\tisDelegate,\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\tisolatedPositionDeposit: resolvedDeposits?.mainDeposit,\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\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"]}
|
|
@@ -4,9 +4,10 @@ exports.prepSignAndSendSwiftOrder = exports.prepSwiftOrderMessage = exports.send
|
|
|
4
4
|
const sdk_1 = require("@drift-labs/sdk");
|
|
5
5
|
const sdk_2 = require("@drift-labs/sdk");
|
|
6
6
|
const utils_1 = require("../../../../../../utils");
|
|
7
|
+
const signedMsgs_1 = require("../../../../../../utils/signedMsgs");
|
|
7
8
|
const swiftClient_1 = require("../../../../../../clients/swiftClient");
|
|
8
9
|
const types_1 = require("../../../../../../types");
|
|
9
|
-
const
|
|
10
|
+
const trading_utils_1 = require("../../../../../../_deprecated/trading-utils");
|
|
10
11
|
const web3_js_1 = require("@solana/web3.js");
|
|
11
12
|
/**
|
|
12
13
|
* Buffer slots to account for signing of message by the user (default: 7 slots ~3 second, assumes user have to approves the signing in a UI wallet).
|
|
@@ -74,7 +75,7 @@ const prepSwiftOrder = ({ driftClient, takerUserAccount, currentSlot, isDelegate
|
|
|
74
75
|
}
|
|
75
76
|
: null,
|
|
76
77
|
maxMarginRatio: orderParams.positionMaxLeverage
|
|
77
|
-
?
|
|
78
|
+
? trading_utils_1.TRADING_UTILS.convertLeverageToMarginRatio(orderParams.positionMaxLeverage)
|
|
78
79
|
: null,
|
|
79
80
|
isolatedPositionDeposit: (_b = orderParams.isolatedPositionDeposit) !== null && _b !== void 0 ? _b : null,
|
|
80
81
|
// Include builder params if provided
|
|
@@ -181,7 +182,7 @@ exports.signSwiftOrderMsg = signSwiftOrderMsg;
|
|
|
181
182
|
*/
|
|
182
183
|
const sendSwiftOrder = ({ driftClient, marketId, hexEncodedSwiftOrderMessageString, signedMessage, signedMsgOrderUuid, takerAuthority, signingAuthority, slotsTillAuctionEnd, confirmationMultiplier, confirmationConnection, }) => {
|
|
183
184
|
const signedMsgUserOrdersAccountPubkey = (0, sdk_1.getSignedMsgUserAccountPublicKey)(driftClient.program.programId, takerAuthority);
|
|
184
|
-
const swiftOrderObservable = swiftClient_1.SwiftClient.sendAndConfirmSwiftOrderWS(confirmationConnection !== null && confirmationConnection !== void 0 ? confirmationConnection : driftClient.connection, driftClient, marketId.marketIndex, marketId.marketType, hexEncodedSwiftOrderMessageString, Buffer.from(signedMessage), takerAuthority, signedMsgUserOrdersAccountPubkey, signedMsgOrderUuid, (0,
|
|
185
|
+
const swiftOrderObservable = swiftClient_1.SwiftClient.sendAndConfirmSwiftOrderWS(confirmationConnection !== null && confirmationConnection !== void 0 ? confirmationConnection : driftClient.connection, driftClient, marketId.marketIndex, marketId.marketType, hexEncodedSwiftOrderMessageString, Buffer.from(signedMessage), takerAuthority, signedMsgUserOrdersAccountPubkey, signedMsgOrderUuid, (0, signedMsgs_1.getSwiftConfirmationTimeoutMs)(slotsTillAuctionEnd, confirmationMultiplier), signingAuthority);
|
|
185
186
|
return swiftOrderObservable;
|
|
186
187
|
};
|
|
187
188
|
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,yCAMyB;AACzB,yCAOyB;AACzB,mDAGiC;AACjC,uEAO+C;AAC/C,mDAAmD;AAGnD,uEAA0E;AAC1E,6CAA6C;AAE7C;;GAEG;AACU,QAAA,iCAAiC,GAAG,CAAC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AAC;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;AA9GW,QAAA,yBAAyB,6BA8GpC","sourcesContent":["import {\n\tgetSignedMsgUserAccountPublicKey,\n\tOrderType,\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\tENUM_UTILS,\n\tgetSwiftConfirmationTimeoutMs,\n} 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';\nimport { Connection } from '@solana/web3.js';\n\n/**\n * Buffer slots to account for signing of message by the user (default: 7 slots ~3 second, assumes user have to approves the signing in a UI wallet).\n */\nexport const USER_SIGNING_MESSAGE_BUFFER_SLOTS = 7;\n\n/**\n * Orders without auction require a higher buffer (kink of the SWIFT server handling non-auction orders)\n */\nexport const MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 35;\n\n/**\n * Buffer slots from the end of the auction to prevent the signing of the order message.\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\t/**\n\t * Buffer slots to account for the user to sign the message. Affects the auction start slot.\n\t * If order is not an auction order, it is not encouraged to use this buffer.\n\t */\n\tuserSigningSlotBuffer?: number;\n\tisDelegate?: boolean;\n\t/**\n\t * Multiplier for the SWIFT confirmation timeout (after sending SWIFT order). Default is 1.\n\t */\n\tconfirmationMultiplier?: number;\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\t/**\n\t * Used for internal tracking of the source of the swift order.\n\t */\n\tsource?: string;\n}\n\n/**\n * Represents a prepared SWIFT order message that is ready to be signed and sent.\n * This is the output of the \"prep\" step, before signing occurs.\n *\n * Consumers should:\n * 1. Sign `hexEncodedSwiftOrderMessage.uInt8Array` with the user's wallet\n * 2. Send the signed message along with the other fields to the SWIFT server\n */\nexport interface SwiftOrderMessage {\n\t/** The encoded order message in both Uint8Array (for signing) and string (for sending) formats */\n\thexEncodedSwiftOrderMessage: {\n\t\tuInt8Array: Uint8Array;\n\t\tstring: string;\n\t};\n\t/** The order parameters message that was encoded */\n\tsignedMsgOrderParamsMessage:\n\t\t| SignedMsgOrderParamsMessage\n\t\t| SignedMsgOrderParamsDelegateMessage;\n\t/** The slot number used for the signed message */\n\tslotForSignedMsg: BN;\n\t/** Unique identifier for the signed message order */\n\tsignedMsgOrderUuid: Uint8Array;\n\t/** The market index this order is for */\n\tmarketIndex: number;\n\t/** Number of slots till the auction ends (used for confirmation timeout) */\n\tslotsTillAuctionEnd: number;\n\t/** Time in milliseconds before the signing window expires */\n\texpirationTimeMs: number;\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\t/** Optional isolated position deposit amount */\n\t\tisolatedPositionDeposit?: BN;\n\t};\n\t/**\n\t * Buffer slots to account for the user to sign the message. Affects the auction start slot.\n\t * If order is not an auction order, it is not encouraged to use this buffer.\n\t */\n\tuserSigningSlotBuffer?: 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 userSigningSlotBuffer - Buffer slots to account for the user to sign the message. Affects the auction start slot. If order is not an auction order, it is not encouraged to use this buffer.\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\tuserSigningSlotBuffer,\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\tresolvedUserSigningSlotBuffer: number;\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\tif (!userSigningSlotBuffer) {\n\t\tuserSigningSlotBuffer = mainOrderParams.auctionDuration\n\t\t\t? USER_SIGNING_MESSAGE_BUFFER_SLOTS\n\t\t\t: MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS;\n\t}\n\n\t// if it is not an auction order, there should be a minimum buffer used\n\tif (!mainOrderParams.auctionDuration) {\n\t\tuserSigningSlotBuffer = Math.max(\n\t\t\tuserSigningSlotBuffer,\n\t\t\tMINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS\n\t\t);\n\t}\n\n\t// buffer for time the user takes to sign a message and send to the swift server\n\tconst auctionStartSlot = new BN(currentSlot + userSigningSlotBuffer);\n\n\tconst signedMsgOrderUuid = generateSignedMsgUuid();\n\n\tconsole.log(\n\t\t'DEBUG swift prep orderParams.isolatedPositionDeposit',\n\t\torderParams.isolatedPositionDeposit?.toString()\n\t);\n\n\tconst baseSignedMsgOrderParamsMessage = {\n\t\tsignedMsgOrderParams: mainOrderParams,\n\t\tuuid: signedMsgOrderUuid,\n\t\tslot: auctionStartSlot,\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\tisolatedPositionDeposit: orderParams.isolatedPositionDeposit ?? 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: auctionStartSlot,\n\t\tsignedMsgOrderUuid,\n\t\tresolvedUserSigningSlotBuffer: userSigningSlotBuffer,\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/** Number of slots till the end of the auction (optional) */\n\tslotsTillAuctionEnd: number;\n\t/** Multiplier for the SWIFT confirmation timeout (after sending SWIFT order) */\n\tconfirmationMultiplier?: number;\n\t/** Optionally send a different connection for the confirmation step, possibly for a faster commitment */\n\tconfirmationConnection?: Connection;\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 slotsTillAuctionEnd - Number of slots till the end of the auction (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\tslotsTillAuctionEnd,\n\tconfirmationMultiplier,\n\tconfirmationConnection,\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\tconfirmationConnection ?? driftClient.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(slotsTillAuctionEnd, confirmationMultiplier),\n\t\tsigningAuthority\n\t);\n\n\treturn swiftOrderObservable;\n};\n\n/**\n * Computes the timing parameters for a SWIFT order:\n * - slotsTillAuctionEnd: how many slots until the auction is considered ended\n * - expirationTimeMs: how long (in ms) the user has to sign before the window expires\n *\n * For market orders, auction duration + signing buffer is used directly.\n * For non-market orders, a minimum is enforced because limit auctions can have\n * very small durations but the order is still valid after the auction ends.\n */\nconst computeSwiftOrderTiming = (\n\tmainOrderParams: OptionalOrderParams,\n\tuserSigningSlotBuffer: number\n): { slotsTillAuctionEnd: number; expirationTimeMs: number } => {\n\tconst isMarketOrder =\n\t\tENUM_UTILS.match(mainOrderParams.orderType, OrderType.ORACLE) ||\n\t\tENUM_UTILS.match(mainOrderParams.orderType, OrderType.MARKET);\n\tconst slotsTillAuctionEnd = mainOrderParams.auctionDuration\n\t\t? isMarketOrder\n\t\t\t? userSigningSlotBuffer + mainOrderParams.auctionDuration\n\t\t\t: Math.max(\n\t\t\t\t\tMINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS,\n\t\t\t\t\tuserSigningSlotBuffer + mainOrderParams.auctionDuration\n\t\t\t )\n\t\t: MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS;\n\n\tconst expirationTimeMs =\n\t\tMath.max(\n\t\t\tslotsTillAuctionEnd - SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS,\n\t\t\tMINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS\n\t\t) * SLOT_TIME_ESTIMATE_MS;\n\n\treturn { slotsTillAuctionEnd, expirationTimeMs };\n};\n\ntype PrepSwiftOrderMessageParams = {\n\tdriftClient: DriftClient;\n\tsubAccountId: number;\n\tuserAccountPubKey: PublicKey;\n\tmarketIndex: number;\n\tuserSigningSlotBuffer: number;\n\tisDelegate?: boolean;\n\torderParams: {\n\t\tmain: OptionalOrderParams;\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t\tpositionMaxLeverage?: number;\n\t\tisolatedPositionDeposit?: BN;\n\t};\n\tbuilderParams?: {\n\t\tbuilderIdx: number;\n\t\tbuilderFeeTenthBps: number;\n\t};\n};\n\n/**\n * Prepares a SWIFT order message without signing or sending it.\n * Returns all data needed for the consumer to sign and send the order themselves.\n *\n * This is useful for server-side contexts (e.g., CentralServerDrift) where\n * the server prepares the message but the client handles signing and sending.\n */\nexport const prepSwiftOrderMessage = async ({\n\tdriftClient,\n\tsubAccountId,\n\tuserAccountPubKey,\n\tmarketIndex,\n\tuserSigningSlotBuffer,\n\tisDelegate = false,\n\torderParams,\n\tbuilderParams,\n}: PrepSwiftOrderMessageParams): Promise<SwiftOrderMessage> => {\n\tconst currentSlot = await driftClient.connection.getSlot('confirmed');\n\n\tconst {\n\t\thexEncodedSwiftOrderMessage,\n\t\tsignedMsgOrderUuid,\n\t\tsignedMsgOrderParamsMessage,\n\t\tslotForSignedMsg,\n\t\tresolvedUserSigningSlotBuffer,\n\t} = prepSwiftOrder({\n\t\tdriftClient,\n\t\ttakerUserAccount: {\n\t\t\tpubKey: userAccountPubKey,\n\t\t\tsubAccountId,\n\t\t},\n\t\tcurrentSlot,\n\t\tisDelegate,\n\t\torderParams,\n\t\tuserSigningSlotBuffer,\n\t\tbuilderParams,\n\t});\n\n\tconst { slotsTillAuctionEnd, expirationTimeMs } = computeSwiftOrderTiming(\n\t\torderParams.main,\n\t\tresolvedUserSigningSlotBuffer\n\t);\n\n\treturn {\n\t\thexEncodedSwiftOrderMessage,\n\t\tsignedMsgOrderParamsMessage,\n\t\tslotForSignedMsg,\n\t\tsignedMsgOrderUuid,\n\t\tmarketIndex,\n\t\tslotsTillAuctionEnd,\n\t\texpirationTimeMs,\n\t};\n};\n\ntype PrepSignAndSendSwiftOrderParams = {\n\tdriftClient: DriftClient;\n\tsubAccountId: number;\n\tuserAccountPubKey: PublicKey;\n\tmarketIndex: number;\n\tuserSigningSlotBuffer: number;\n\tswiftOptions: SwiftOrderOptions;\n\t/** Multiplier for the SWIFT confirmation timeout (after sending SWIFT order). Default is 1.\n\t *\n\t * Higher multiplier means longer confirmation timeout.\n\t */\n\tconfirmationMultiplier?: number;\n\tconfirmationConnection?: Connection;\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\t/**\n\t\t * Optional isolated position deposit amount for isolated positions.\n\t\t */\n\t\tisolatedPositionDeposit?: BN;\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\tuserSigningSlotBuffer,\n\tswiftOptions,\n\torderParams,\n\tbuilderParams,\n\tconfirmationMultiplier,\n}: PrepSignAndSendSwiftOrderParams): Promise<void> => {\n\tconst {\n\t\thexEncodedSwiftOrderMessage,\n\t\tsignedMsgOrderUuid,\n\t\tsignedMsgOrderParamsMessage,\n\t\tslotsTillAuctionEnd,\n\t\texpirationTimeMs,\n\t} = await prepSwiftOrderMessage({\n\t\tdriftClient,\n\t\tsubAccountId,\n\t\tuserAccountPubKey,\n\t\tmarketIndex,\n\t\tuserSigningSlotBuffer,\n\t\tisDelegate: swiftOptions.isDelegate || false,\n\t\torderParams,\n\t\tbuilderParams,\n\t});\n\n\tswiftOptions.callbacks?.onOrderParamsMessagePrepped?.(\n\t\tsignedMsgOrderParamsMessage\n\t);\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, swiftOptions.source ?? '');\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\tslotsTillAuctionEnd,\n\t\tconfirmationMultiplier,\n\t\tconfirmationConnection: new Connection(\n\t\t\tdriftClient.connection.rpcEndpoint,\n\t\t\t'processed'\n\t\t),\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,yCAMyB;AACzB,yCAOyB;AACzB,mDAAqD;AACrD,mEAAmF;AACnF,uEAO+C;AAC/C,mDAAmD;AAGnD,+EAA4E;AAC5E,6CAA6C;AAE7C;;GAEG;AACU,QAAA,iCAAiC,GAAG,CAAC,CAAC;AAEnD;;GAEG;AACU,QAAA,+DAA+D,GAAG,EAAE,CAAC;AAElF;;GAEG;AACU,QAAA,2CAA2C,GAAG,CAAC,CAAC;AAChD,QAAA,mDAAmD,GAAG,CAAC,CAAC;AAqJrE;;;;;;;;;;;;;;;;GAgBG;AACI,MAAM,cAAc,GAAG,CAAC,EAC9B,WAAW,EACX,gBAAgB,EAChB,WAAW,EACX,UAAU,EACV,WAAW,EACX,qBAAqB,EACrB,aAAa,GACS,EAWrB,EAAE;;IACH,MAAM,eAAe,GAAG,IAAA,oBAAc,EAAC;QACtC,GAAG,WAAW,CAAC,IAAI;QACnB,eAAe,EAAE,WAAW,CAAC,IAAI,CAAC,eAAe,IAAI,IAAI,EAAE,6EA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s/sdk';\nimport {\n\tBN,\n\tDriftClient,\n\tgenerateSignedMsgUuid,\n\tgetOrderParams,\n\tOptionalOrderParams,\n\tPublicKey,\n} from '@drift-labs/sdk';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport { getSwiftConfirmationTimeoutMs } from '../../../../../../utils/signedMsgs';\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 '../../../../../../_deprecated/trading-utils';\nimport { Connection } from '@solana/web3.js';\n\n/**\n * Buffer slots to account for signing of message by the user (default: 7 slots ~3 second, assumes user have to approves the signing in a UI wallet).\n */\nexport const USER_SIGNING_MESSAGE_BUFFER_SLOTS = 7;\n\n/**\n * Orders without auction require a higher buffer (kink of the SWIFT server handling non-auction orders)\n */\nexport const MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 35;\n\n/**\n * Buffer slots from the end of the auction to prevent the signing of the order message.\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\t/**\n\t * Buffer slots to account for the user to sign the message. Affects the auction start slot.\n\t * If order is not an auction order, it is not encouraged to use this buffer.\n\t */\n\tuserSigningSlotBuffer?: number;\n\tisDelegate?: boolean;\n\t/**\n\t * Multiplier for the SWIFT confirmation timeout (after sending SWIFT order). Default is 1.\n\t */\n\tconfirmationMultiplier?: number;\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\t/**\n\t * Used for internal tracking of the source of the swift order.\n\t */\n\tsource?: string;\n}\n\n/**\n * Represents a prepared SWIFT order message that is ready to be signed and sent.\n * This is the output of the \"prep\" step, before signing occurs.\n *\n * Consumers should:\n * 1. Sign `hexEncodedSwiftOrderMessage.uInt8Array` with the user's wallet\n * 2. Send the signed message along with the other fields to the SWIFT server\n */\nexport interface SwiftOrderMessage {\n\t/** The encoded order message in both Uint8Array (for signing) and string (for sending) formats */\n\thexEncodedSwiftOrderMessage: {\n\t\tuInt8Array: Uint8Array;\n\t\tstring: string;\n\t};\n\t/** The order parameters message that was encoded */\n\tsignedMsgOrderParamsMessage:\n\t\t| SignedMsgOrderParamsMessage\n\t\t| SignedMsgOrderParamsDelegateMessage;\n\t/** The slot number used for the signed message */\n\tslotForSignedMsg: BN;\n\t/** Unique identifier for the signed message order */\n\tsignedMsgOrderUuid: Uint8Array;\n\t/** The market index this order is for */\n\tmarketIndex: number;\n\t/** Number of slots till the auction ends (used for confirmation timeout) */\n\tslotsTillAuctionEnd: number;\n\t/** Time in milliseconds before the signing window expires */\n\texpirationTimeMs: number;\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\t/** Optional isolated position deposit amount */\n\t\tisolatedPositionDeposit?: BN;\n\t};\n\t/**\n\t * Buffer slots to account for the user to sign the message. Affects the auction start slot.\n\t * If order is not an auction order, it is not encouraged to use this buffer.\n\t */\n\tuserSigningSlotBuffer?: 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 userSigningSlotBuffer - Buffer slots to account for the user to sign the message. Affects the auction start slot. If order is not an auction order, it is not encouraged to use this buffer.\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\tuserSigningSlotBuffer,\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\tresolvedUserSigningSlotBuffer: number;\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\tif (!userSigningSlotBuffer) {\n\t\tuserSigningSlotBuffer = mainOrderParams.auctionDuration\n\t\t\t? USER_SIGNING_MESSAGE_BUFFER_SLOTS\n\t\t\t: MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS;\n\t}\n\n\t// if it is not an auction order, there should be a minimum buffer used\n\tif (!mainOrderParams.auctionDuration) {\n\t\tuserSigningSlotBuffer = Math.max(\n\t\t\tuserSigningSlotBuffer,\n\t\t\tMINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS\n\t\t);\n\t}\n\n\t// buffer for time the user takes to sign a message and send to the swift server\n\tconst auctionStartSlot = new BN(currentSlot + userSigningSlotBuffer);\n\n\tconst signedMsgOrderUuid = generateSignedMsgUuid();\n\n\tconsole.log(\n\t\t'DEBUG swift prep orderParams.isolatedPositionDeposit',\n\t\torderParams.isolatedPositionDeposit?.toString()\n\t);\n\n\tconst baseSignedMsgOrderParamsMessage = {\n\t\tsignedMsgOrderParams: mainOrderParams,\n\t\tuuid: signedMsgOrderUuid,\n\t\tslot: auctionStartSlot,\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\tisolatedPositionDeposit: orderParams.isolatedPositionDeposit ?? 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: auctionStartSlot,\n\t\tsignedMsgOrderUuid,\n\t\tresolvedUserSigningSlotBuffer: userSigningSlotBuffer,\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/** Number of slots till the end of the auction (optional) */\n\tslotsTillAuctionEnd: number;\n\t/** Multiplier for the SWIFT confirmation timeout (after sending SWIFT order) */\n\tconfirmationMultiplier?: number;\n\t/** Optionally send a different connection for the confirmation step, possibly for a faster commitment */\n\tconfirmationConnection?: Connection;\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 slotsTillAuctionEnd - Number of slots till the end of the auction (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\tslotsTillAuctionEnd,\n\tconfirmationMultiplier,\n\tconfirmationConnection,\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\tconfirmationConnection ?? driftClient.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(slotsTillAuctionEnd, confirmationMultiplier),\n\t\tsigningAuthority\n\t);\n\n\treturn swiftOrderObservable;\n};\n\n/**\n * Computes the timing parameters for a SWIFT order:\n * - slotsTillAuctionEnd: how many slots until the auction is considered ended\n * - expirationTimeMs: how long (in ms) the user has to sign before the window expires\n *\n * For market orders, auction duration + signing buffer is used directly.\n * For non-market orders, a minimum is enforced because limit auctions can have\n * very small durations but the order is still valid after the auction ends.\n */\nconst computeSwiftOrderTiming = (\n\tmainOrderParams: OptionalOrderParams,\n\tuserSigningSlotBuffer: number\n): { slotsTillAuctionEnd: number; expirationTimeMs: number } => {\n\tconst isMarketOrder =\n\t\tENUM_UTILS.match(mainOrderParams.orderType, OrderType.ORACLE) ||\n\t\tENUM_UTILS.match(mainOrderParams.orderType, OrderType.MARKET);\n\tconst slotsTillAuctionEnd = mainOrderParams.auctionDuration\n\t\t? isMarketOrder\n\t\t\t? userSigningSlotBuffer + mainOrderParams.auctionDuration\n\t\t\t: Math.max(\n\t\t\t\t\tMINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS,\n\t\t\t\t\tuserSigningSlotBuffer + mainOrderParams.auctionDuration\n\t\t\t )\n\t\t: MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS;\n\n\tconst expirationTimeMs =\n\t\tMath.max(\n\t\t\tslotsTillAuctionEnd - SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS,\n\t\t\tMINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS\n\t\t) * SLOT_TIME_ESTIMATE_MS;\n\n\treturn { slotsTillAuctionEnd, expirationTimeMs };\n};\n\ntype PrepSwiftOrderMessageParams = {\n\tdriftClient: DriftClient;\n\tsubAccountId: number;\n\tuserAccountPubKey: PublicKey;\n\tmarketIndex: number;\n\tuserSigningSlotBuffer: number;\n\tisDelegate?: boolean;\n\torderParams: {\n\t\tmain: OptionalOrderParams;\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t\tpositionMaxLeverage?: number;\n\t\tisolatedPositionDeposit?: BN;\n\t};\n\tbuilderParams?: {\n\t\tbuilderIdx: number;\n\t\tbuilderFeeTenthBps: number;\n\t};\n};\n\n/**\n * Prepares a SWIFT order message without signing or sending it.\n * Returns all data needed for the consumer to sign and send the order themselves.\n *\n * This is useful for server-side contexts (e.g., CentralServerDrift) where\n * the server prepares the message but the client handles signing and sending.\n */\nexport const prepSwiftOrderMessage = async ({\n\tdriftClient,\n\tsubAccountId,\n\tuserAccountPubKey,\n\tmarketIndex,\n\tuserSigningSlotBuffer,\n\tisDelegate = false,\n\torderParams,\n\tbuilderParams,\n}: PrepSwiftOrderMessageParams): Promise<SwiftOrderMessage> => {\n\tconst currentSlot = await driftClient.connection.getSlot('confirmed');\n\n\tconst {\n\t\thexEncodedSwiftOrderMessage,\n\t\tsignedMsgOrderUuid,\n\t\tsignedMsgOrderParamsMessage,\n\t\tslotForSignedMsg,\n\t\tresolvedUserSigningSlotBuffer,\n\t} = prepSwiftOrder({\n\t\tdriftClient,\n\t\ttakerUserAccount: {\n\t\t\tpubKey: userAccountPubKey,\n\t\t\tsubAccountId,\n\t\t},\n\t\tcurrentSlot,\n\t\tisDelegate,\n\t\torderParams,\n\t\tuserSigningSlotBuffer,\n\t\tbuilderParams,\n\t});\n\n\tconst { slotsTillAuctionEnd, expirationTimeMs } = computeSwiftOrderTiming(\n\t\torderParams.main,\n\t\tresolvedUserSigningSlotBuffer\n\t);\n\n\treturn {\n\t\thexEncodedSwiftOrderMessage,\n\t\tsignedMsgOrderParamsMessage,\n\t\tslotForSignedMsg,\n\t\tsignedMsgOrderUuid,\n\t\tmarketIndex,\n\t\tslotsTillAuctionEnd,\n\t\texpirationTimeMs,\n\t};\n};\n\ntype PrepSignAndSendSwiftOrderParams = {\n\tdriftClient: DriftClient;\n\tsubAccountId: number;\n\tuserAccountPubKey: PublicKey;\n\tmarketIndex: number;\n\tuserSigningSlotBuffer: number;\n\tswiftOptions: SwiftOrderOptions;\n\t/** Multiplier for the SWIFT confirmation timeout (after sending SWIFT order). Default is 1.\n\t *\n\t * Higher multiplier means longer confirmation timeout.\n\t */\n\tconfirmationMultiplier?: number;\n\tconfirmationConnection?: Connection;\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\t/**\n\t\t * Optional isolated position deposit amount for isolated positions.\n\t\t */\n\t\tisolatedPositionDeposit?: BN;\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\tuserSigningSlotBuffer,\n\tswiftOptions,\n\torderParams,\n\tbuilderParams,\n\tconfirmationMultiplier,\n}: PrepSignAndSendSwiftOrderParams): Promise<void> => {\n\tconst {\n\t\thexEncodedSwiftOrderMessage,\n\t\tsignedMsgOrderUuid,\n\t\tsignedMsgOrderParamsMessage,\n\t\tslotsTillAuctionEnd,\n\t\texpirationTimeMs,\n\t} = await prepSwiftOrderMessage({\n\t\tdriftClient,\n\t\tsubAccountId,\n\t\tuserAccountPubKey,\n\t\tmarketIndex,\n\t\tuserSigningSlotBuffer,\n\t\tisDelegate: swiftOptions.isDelegate || false,\n\t\torderParams,\n\t\tbuilderParams,\n\t});\n\n\tswiftOptions.callbacks?.onOrderParamsMessagePrepped?.(\n\t\tsignedMsgOrderParamsMessage\n\t);\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, swiftOptions.source ?? '');\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\tslotsTillAuctionEnd,\n\t\tconfirmationMultiplier,\n\t\tconfirmationConnection: new Connection(\n\t\t\tdriftClient.connection.rpcEndpoint,\n\t\t\t'processed'\n\t\t),\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,7 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.getPositionMaxLeverageIxIfNeeded = void 0;
|
|
4
|
-
const
|
|
4
|
+
const trading_utils_1 = require("../../../../../_deprecated/trading-utils");
|
|
5
5
|
/**
|
|
6
6
|
* Helper function to determine if leverage needs updating and create the instruction if needed.
|
|
7
7
|
* Returns the instruction to update position max leverage, or undefined if no update is needed.
|
|
@@ -14,7 +14,7 @@ async function getPositionMaxLeverageIxIfNeeded(driftClient, user, marketIndex,
|
|
|
14
14
|
const userAccount = user.getUserAccount();
|
|
15
15
|
const currentPosition = userAccount.perpPositions.find((pos) => pos.marketIndex === marketIndex);
|
|
16
16
|
// Convert leverage to margin ratio
|
|
17
|
-
const targetMarginRatio =
|
|
17
|
+
const targetMarginRatio = trading_utils_1.TRADING_UTILS.convertLeverageToMarginRatio(positionMaxLeverage);
|
|
18
18
|
// Check if leverage needs updating
|
|
19
19
|
const currentMarginRatio = (currentPosition === null || currentPosition === void 0 ? void 0 : currentPosition.maxMarginRatio) || 0;
|
|
20
20
|
// Only create instruction if:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"positionMaxLeverage.js","sourceRoot":"","sources":["../../../../../../src/drift/base/actions/trade/openPerpOrder/positionMaxLeverage.ts"],"names":[],"mappings":";;;AAEA,
|
|
1
|
+
{"version":3,"file":"positionMaxLeverage.js","sourceRoot":"","sources":["../../../../../../src/drift/base/actions/trade/openPerpOrder/positionMaxLeverage.ts"],"names":[],"mappings":";;;AAEA,4EAAyE;AAEzE;;;GAGG;AACI,KAAK,UAAU,gCAAgC,CACrD,WAAwB,EACxB,IAAU,EACV,WAAmB,EACnB,mBAA4B,EAC5B,gBAA4B;IAE5B,IAAI,CAAC,mBAAmB,EAAE,CAAC;QAC1B,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,oCAAoC;IACpC,MAAM,WAAW,GAAG,IAAI,CAAC,cAAc,EAAE,CAAC;IAC1C,MAAM,eAAe,GAAG,WAAW,CAAC,aAAa,CAAC,IAAI,CACrD,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,WAAW,KAAK,WAAW,CACxC,CAAC;IAEF,mCAAmC;IACnC,MAAM,iBAAiB,GACtB,6BAAa,CAAC,4BAA4B,CAAC,mBAAmB,CAAC,CAAC;IAEjE,mCAAmC;IACnC,MAAM,kBAAkB,GAAG,CAAA,eAAe,aAAf,eAAe,uBAAf,eAAe,CAAE,cAAc,KAAI,CAAC,CAAC;IAEhE,8BAA8B;IAC9B,2CAA2C;IAC3C,2FAA2F;IAC3F,IAAI,iBAAiB,IAAI,iBAAiB,KAAK,kBAAkB,EAAE,CAAC;QACnE,OAAO,MAAM,WAAW,CAAC,4CAA4C,CACpE,WAAW,EACX,iBAAiB,EACjB,WAAW,CAAC,YAAY,EACxB;YACC,oBAAoB,EAAE,IAAI,CAAC,uBAAuB,EAAE;YACpD,SAAS,EAAE,WAAW,CAAC,SAAS;YAChC,gBAAgB;SAChB,CACD,CAAC;IACH,CAAC;IAED,OAAO,SAAS,CAAC;AAClB,CAAC;AAzCD,4EAyCC","sourcesContent":["import { DriftClient, User } from '@drift-labs/sdk';\nimport { PublicKey, TransactionInstruction } from '@solana/web3.js';\nimport { TRADING_UTILS } from '../../../../../_deprecated/trading-utils';\n\n/**\n * Helper function to determine if leverage needs updating and create the instruction if needed.\n * Returns the instruction to update position max leverage, or undefined if no update is needed.\n */\nexport async function getPositionMaxLeverageIxIfNeeded(\n\tdriftClient: DriftClient,\n\tuser: User,\n\tmarketIndex: number,\n\tpositionMaxLeverage?: number,\n\tsigningAuthority?: PublicKey\n): Promise<TransactionInstruction | undefined> {\n\tif (!positionMaxLeverage) {\n\t\treturn undefined;\n\t}\n\n\t// Get current position if it exists\n\tconst userAccount = user.getUserAccount();\n\tconst currentPosition = userAccount.perpPositions.find(\n\t\t(pos) => pos.marketIndex === marketIndex\n\t);\n\n\t// Convert leverage to margin ratio\n\tconst targetMarginRatio =\n\t\tTRADING_UTILS.convertLeverageToMarginRatio(positionMaxLeverage);\n\n\t// Check if leverage needs updating\n\tconst currentMarginRatio = currentPosition?.maxMarginRatio || 0;\n\n\t// Only create instruction if:\n\t// 1. We have a target leverage to set, AND\n\t// 2. Either there's no position yet (currentMarginRatio === 0) OR the margin ratios differ\n\tif (targetMarginRatio && targetMarginRatio !== currentMarginRatio) {\n\t\treturn await driftClient.getUpdateUserPerpPositionCustomMarginRatioIx(\n\t\t\tmarketIndex,\n\t\t\ttargetMarginRatio,\n\t\t\tuserAccount.subAccountId,\n\t\t\t{\n\t\t\t\tuserAccountPublicKey: user.getUserAccountPublicKey(),\n\t\t\t\tauthority: userAccount.authority,\n\t\t\t\tsigningAuthority,\n\t\t\t}\n\t\t);\n\t}\n\n\treturn undefined;\n}\n"]}
|
|
@@ -5,7 +5,7 @@ const sdk_1 = require("@drift-labs/sdk");
|
|
|
5
5
|
const token_1 = require("../../../../utils/token");
|
|
6
6
|
const accountNames_1 = require("../../constants/accountNames");
|
|
7
7
|
const pools_1 = require("../../../../constants/pools");
|
|
8
|
-
const
|
|
8
|
+
const user_utils_1 = require("../../../../_deprecated/user-utils");
|
|
9
9
|
/**
|
|
10
10
|
* Creates transaction instructions for initializing a new user account and depositing collateral.
|
|
11
11
|
*
|
|
@@ -45,7 +45,7 @@ const createUserAndDepositCollateralBaseIxs = async ({ driftClient, amount, spot
|
|
|
45
45
|
const referrerNameAccountPromise = referrerName
|
|
46
46
|
? driftClient.fetchReferrerNameAccount(referrerName)
|
|
47
47
|
: Promise.resolve(undefined);
|
|
48
|
-
const subaccountExistsPromise =
|
|
48
|
+
const subaccountExistsPromise = user_utils_1.USER_UTILS.checkIfUserAccountExists(driftClient, {
|
|
49
49
|
type: 'subAccountId',
|
|
50
50
|
subAccountId: nextSubaccountId,
|
|
51
51
|
authority,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/user/create.ts"],"names":[],"mappings":";;;AAAA,yCAWyB;AACzB,mDAA+E;AAC/E,+DAAgF;AAChF,uDAA2D;AAM3D,2DAA8D;AAqB9D;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACI,MAAM,qCAAqC,GAAG,KAAK,EAAE,EAC3D,WAAW,EACX,MAAM,EACN,gBAAgB,EAChB,SAAS,EACT,gBAAgB,EAChB,YAAY,EACZ,WAAW,EACX,MAAM,GAAG,oBAAY,EACrB,gBAAgB,EAChB,oBAAoB,EACpB,QAAQ,EACR,cAAc,GAC+B,EAI3C,EAAE;;IACJ,MAAM,gBAAgB,GAAG,MAAA,gBAAgB,aAAhB,gBAAgB,uBAAhB,gBAAgB,CAAE,0BAA0B,mCAAI,CAAC,CAAC,CAAC,yBAAyB;IAErG,2FAA2F;IAC3F,MAAM,iBAAiB,GAAG,WAAW,CAAC,oBAAoB,CACzD,gBAAgB,CAAC,WAAW,CAC5B,CAAC;IAEF,IAAI,CAAC,iBAAiB,EAAE,CAAC;QACxB,MAAM,IAAI,KAAK,CACd,kDAAkD,gBAAgB,CAAC,WAAW,EAAE,CAChF,CAAC;IACH,CAAC;IAED,6EAA6E;IAC7E,MAAM,mBAAmB,GAAG,cAAc,aAAd,cAAc,cAAd,cAAc,GAAI,SAAS,CAAC;IACxD,MAAM,oCAAoC,GACzC,IAAA,4CAAoC,EACnC,iBAAiB,EACjB,mBAAmB,CACnB,CAAC;IACH,MAAM,0BAA0B,GAC/B,YAAY;QACX,CAAC,CAAC,WAAW,CAAC,wBAAwB,CAAC,YAAY,CAAC;QACpD,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IAC/B,MAAM,uBAAuB,GAAG,iBAAU,CAAC,wBAAwB,CAClE,WAAW,EACX;QACC,IAAI,EAAE,cAAc;QACpB,YAAY,EAAE,gBAAgB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AuB,CAAC,QAAQ,EAAE;YACpD,YAAY,EAAE,gBAAgB;YAC9B,oBAAoB,EAAE,uBAAuB;YAC7C,SAAS;SACR,CAAC;QACJ,CAAC,CAAC,SAAS,CAAC;IAEb,IAAI,UAAU,EAAE,CAAC;QAChB,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IACtB,CAAC;IAED,OAAO;QACN,YAAY,EAAE,gBAAgB;QAC9B,oBAAoB;QACpB,GAAG;KACH,CAAC;AACH,CAAC,CAAC;AAjHW,QAAA,qCAAqC,yCAiHhD;AAOF;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACI,MAAM,qCAAqC,GAAG,KAAK,EAAE,EAC3D,WAAW,EACX,MAAM,EACN,gBAAgB,EAChB,SAAS,EACT,gBAAgB,EAChB,YAAY,EACZ,WAAW,EACX,MAAM,GAAG,oBAAY,EACrB,gBAAgB,EAChB,oBAAoB,EACpB,QAAQ,EACR,cAAc,GAC+B,EAI3C,EAAE;IACJ,MAAM,EAAE,GAAG,EAAE,oBAAoB,EAAE,YAAY,EAAE,GAChD,MAAM,IAAA,6CAAqC,EAAC;QAC3C,WAAW;QACX,MAAM;QACN,gBAAgB;QAChB,SAAS;QACT,gBAAgB;QAChB,YAAY;QACZ,WAAW;QACX,MAAM;QACN,gBAAgB;QAChB,oBAAoB;QACpB,cAAc;KACd,CAAC,CAAC;IAEJ,MAAM,EAAE,GAAG,MAAM,WAAW,CAAC,gBAAgB,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;IAE7D,OAAO,EAAE,WAAW,EAAE,EAAE,EAAE,oBAAoB,EAAE,YAAY,EAAE,CAAC;AAChE,CAAC,CAAC;AApCW,QAAA,qCAAqC,yCAoChD","sourcesContent":["import {\n\tBN,\n\tDriftClient,\n\tgetUserAccountPublicKeySync,\n\tPublicKey,\n\tReferrerInfo,\n\tReferrerNameAccount,\n\tSpotMarketConfig,\n\tTxParams,\n\tUserStatsAccount,\n\tZERO,\n} from '@drift-labs/sdk';\nimport { getTokenAddressForDepositAndWithdraw } from '../../../../utils/token';\nimport { DEFAULT_ACCOUNT_NAMES_BY_POOL_ID } from '../../constants/accountNames';\nimport { MAIN_POOL_ID } from '../../../../constants/pools';\nimport {\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport { USER_UTILS } from '../../../../common-ui-utils/user';\n\ninterface CreateUserAndDepositCollateralBaseIxsParams {\n\tdriftClient: DriftClient;\n\tamount: BN;\n\tspotMarketConfig: SpotMarketConfig;\n\tauthority: PublicKey;\n\tuserStatsAccount: UserStatsAccount | undefined;\n\treferrerName?: string;\n\taccountName?: string;\n\tpoolId?: number;\n\tfromSubAccountId?: number;\n\tcustomMaxMarginRatio?: number;\n\tdelegate?: PublicKey;\n\t/**\n\t * Optional external wallet to deposit from. If provided, the deposit will be made\n\t * from this wallet instead of the authority wallet.\n\t */\n\texternalWallet?: PublicKey;\n}\n\n/**\n * Creates transaction instructions for initializing a new user account and depositing collateral.\n *\n * This function generates the necessary transaction instructions to:\n * 1. Initialize a new user account in the Drift protocol\n * 2. Deposit collateral into the newly created account\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param amount - The amount of collateral to deposit (in base units)\n * @param spotMarketConfig - The spot market config of the deposit collateral\n * @param authority - The public key of the account authority (wallet owner)\n * @param userStatsAccount - Existing user stats account, used to determine next sub-account ID\n * @param referrerName - Optional name of the referrer for referral tracking\n * @param accountName - Optional custom name for the account (defaults to pool-specific name)\n * @param poolId - The pool ID to associate the account with (defaults to MAIN_POOL_ID)\n * @param fromSubAccountId - Optional sub-account ID to transfer funds from\n * @param customMaxMarginRatio - Optional custom maximum margin ratio for the account\n * @param delegate - Optional delegate public key for the account. Immediately assigns this as the delegate of the account.\n * @param externalWallet - Optional external wallet to deposit from (instead of authority wallet)\n *\n * @returns Promise resolving to an object containing:\n * - subAccountId: The ID of the newly created sub-account\n * - userAccountPublicKey: The public key of the created user account\n * - ixs: Array of transaction instructions to execute\n */\nexport const createUserAndDepositCollateralBaseIxs = async ({\n\tdriftClient,\n\tamount,\n\tspotMarketConfig,\n\tauthority,\n\tuserStatsAccount,\n\treferrerName,\n\taccountName,\n\tpoolId = MAIN_POOL_ID,\n\tfromSubAccountId,\n\tcustomMaxMarginRatio,\n\tdelegate,\n\texternalWallet,\n}: CreateUserAndDepositCollateralBaseIxsParams): Promise<{\n\tsubAccountId: number;\n\tuserAccountPublicKey: PublicKey;\n\tixs: TransactionInstruction[];\n}> => {\n\tconst nextSubaccountId = userStatsAccount?.numberOfSubAccountsCreated ?? 0; // userId is zero indexed\n\n\t// Get the spot market account to determine the correct token program for Token-2022 tokens\n\tconst spotMarketAccount = driftClient.getSpotMarketAccount(\n\t\tspotMarketConfig.marketIndex\n\t);\n\n\tif (!spotMarketAccount) {\n\t\tthrow new Error(\n\t\t\t`Spot market account not found for market index ${spotMarketConfig.marketIndex}`\n\t\t);\n\t}\n\n\t// Use external wallet for token address if provided, otherwise use authority\n\tconst depositSourceWallet = externalWallet ?? authority;\n\tconst associatedDepositTokenAddressPromise =\n\t\tgetTokenAddressForDepositAndWithdraw(\n\t\t\tspotMarketAccount,\n\t\t\tdepositSourceWallet\n\t\t);\n\tconst referrerNameAccountPromise: Promise<ReferrerNameAccount | undefined> =\n\t\treferrerName\n\t\t\t? driftClient.fetchReferrerNameAccount(referrerName)\n\t\t\t: Promise.resolve(undefined);\n\tconst subaccountExistsPromise = USER_UTILS.checkIfUserAccountExists(\n\t\tdriftClient,\n\t\t{\n\t\t\ttype: 'subAccountId',\n\t\t\tsubAccountId: nextSubaccountId,\n\t\t\tauthority,\n\t\t}\n\t);\n\n\tconst [associatedDepositTokenAddress, referrerNameAccount, subaccountExists] =\n\t\tawait Promise.all([\n\t\t\tassociatedDepositTokenAddressPromise,\n\t\t\treferrerNameAccountPromise,\n\t\t\tsubaccountExistsPromise,\n\t\t]);\n\n\tif (subaccountExists) {\n\t\tthrow new Error('Subaccount already exists');\n\t}\n\n\tconst accountNameToUse =\n\t\taccountName ??\n\t\t(poolId !== MAIN_POOL_ID || nextSubaccountId === 0\n\t\t\t? DEFAULT_ACCOUNT_NAMES_BY_POOL_ID[poolId]\n\t\t\t: `Account ${nextSubaccountId}`);\n\n\tconst referrerInfo: ReferrerInfo | undefined = referrerNameAccount\n\t\t? {\n\t\t\t\treferrer: referrerNameAccount.user,\n\t\t\t\treferrerStats: referrerNameAccount.userStats,\n\t\t }\n\t\t: undefined;\n\n\tconst { ixs: createAndDepositIxs, userAccountPublicKey } =\n\t\tawait driftClient.createInitializeUserAccountAndDepositCollateralIxs(\n\t\t\tamount,\n\t\t\tassociatedDepositTokenAddress,\n\t\t\tspotMarketConfig.marketIndex,\n\t\t\tnextSubaccountId,\n\t\t\taccountNameToUse,\n\t\t\tfromSubAccountId,\n\t\t\treferrerInfo,\n\t\t\tZERO,\n\t\t\tcustomMaxMarginRatio,\n\t\t\tpoolId,\n\t\t\texternalWallet ? { externalWallet } : undefined\n\t\t);\n\tconst ixs: TransactionInstruction[] = [...createAndDepositIxs];\n\n\tconst nextSubAccountPublicKey = getUserAccountPublicKeySync(\n\t\tdriftClient.program.programId,\n\t\tauthority,\n\t\tnextSubaccountId\n\t);\n\tconst delegateIx = delegate\n\t\t? await driftClient.getUpdateUserDelegateIx(delegate, {\n\t\t\t\tsubAccountId: nextSubaccountId,\n\t\t\t\tuserAccountPublicKey: nextSubAccountPublicKey,\n\t\t\t\tauthority,\n\t\t })\n\t\t: undefined;\n\n\tif (delegateIx) {\n\t\tixs.push(delegateIx);\n\t}\n\n\treturn {\n\t\tsubAccountId: nextSubaccountId,\n\t\tuserAccountPublicKey,\n\t\tixs,\n\t};\n};\n\ninterface CreateUserAndDepositCollateralBaseTxnParams\n\textends CreateUserAndDepositCollateralBaseIxsParams {\n\ttxParams?: TxParams;\n}\n\n/**\n * Creates a complete transaction for initializing a new user account and depositing collateral.\n *\n * This function is a higher-level wrapper around `createUserAndDepositCollateralBaseIxs` that:\n * 1. Generates the necessary transaction instructions\n * 2. Builds a complete transaction ready for signing and submission\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param amount - The amount of collateral to deposit (in base units)\n * @param spotMarketConfig - The spot market config of the deposit collateral\n * @param authority - The public key of the account authority (wallet owner)\n * @param userStatsAccount - Existing user stats account, used to determine next sub-account ID\n * @param referrerName - Optional name of the referrer for referral tracking\n * @param accountName - Optional custom name for the account (defaults to pool-specific name)\n * @param poolId - The pool ID to associate the account with (defaults to MAIN_POOL_ID)\n * @param fromSubAccountId - Optional sub-account ID to transfer funds from\n * @param customMaxMarginRatio - Optional custom maximum margin ratio for the account\n * @param txParams - Transaction parameters for building the transaction (compute units, priority fees, etc.)\n * @param externalWallet - Optional external wallet to deposit from (instead of authority wallet)\n *\n * @returns Promise resolving to an object containing:\n * - transaction: The built transaction ready for signing (Transaction or VersionedTransaction)\n * - userAccountPublicKey: The public key of the created user account\n * - subAccountId: The ID of the newly created sub-account\n */\nexport const createUserAndDepositCollateralBaseTxn = async ({\n\tdriftClient,\n\tamount,\n\tspotMarketConfig,\n\tauthority,\n\tuserStatsAccount,\n\treferrerName,\n\taccountName,\n\tpoolId = MAIN_POOL_ID,\n\tfromSubAccountId,\n\tcustomMaxMarginRatio,\n\ttxParams,\n\texternalWallet,\n}: CreateUserAndDepositCollateralBaseTxnParams): Promise<{\n\ttransaction: Transaction | VersionedTransaction;\n\tuserAccountPublicKey: PublicKey;\n\tsubAccountId: number;\n}> => {\n\tconst { ixs, userAccountPublicKey, subAccountId } =\n\t\tawait createUserAndDepositCollateralBaseIxs({\n\t\t\tdriftClient,\n\t\t\tamount,\n\t\t\tspotMarketConfig,\n\t\t\tauthority,\n\t\t\tuserStatsAccount,\n\t\t\treferrerName,\n\t\t\taccountName,\n\t\t\tpoolId,\n\t\t\tfromSubAccountId,\n\t\t\tcustomMaxMarginRatio,\n\t\t\texternalWallet,\n\t\t});\n\n\tconst tx = await driftClient.buildTransaction(ixs, txParams);\n\n\treturn { transaction: tx, userAccountPublicKey, subAccountId };\n};\n"]}
|
|
1
|
+
{"version":3,"file":"create.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/user/create.ts"],"names":[],"mappings":";;;AAAA,yCAWyB;AACzB,mDAA+E;AAC/E,+DAAgF;AAChF,uDAA2D;AAM3D,mEAAgE;AAqBhE;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACI,MAAM,qCAAqC,GAAG,KAAK,EAAE,EAC3D,WAAW,EACX,MAAM,EACN,gBAAgB,EAChB,SAAS,EACT,gBAAgB,EAChB,YAAY,EACZ,WAAW,EACX,MAAM,GAAG,oBAAY,EACrB,gBAAgB,EAChB,oBAAoB,EACpB,QAAQ,EACR,cAAc,GAC+B,EAI3C,EAAE;;IACJ,MAAM,gBAAgB,GAAG,MAAA,gBAAgB,aAAhB,gBAAgB,uBAAhB,gBAAgB,CAAE,0BAA0B,mCAAI,CAAC,CAAC,CAAC,yBAAyB;IAErG,2FAA2F;IAC3F,MAAM,iBAAiB,GAAG,WAAW,CAAC,oBAAoB,CACzD,gBAAgB,CAAC,WAAW,CAC5B,CAAC;IAEF,IAAI,CAAC,iBAAiB,EAAE,CAAC;QACxB,MAAM,IAAI,KAAK,CACd,kDAAkD,gBAAgB,CAAC,WAAW,EAAE,CAChF,CAAC;IACH,CAAC;IAED,6EAA6E;IAC7E,MAAM,mBAAmB,GAAG,cAAc,aAAd,cAAc,cAAd,cAAc,GAAI,SAAS,CAAC;IACxD,MAAM,oCAAoC,GACzC,IAAA,4CAAoC,EACnC,iBAAiB,EACjB,mBAAmB,CACnB,CAAC;IACH,MAAM,0BAA0B,GAC/B,YAAY;QACX,CAAC,CAAC,WAAW,CAAC,wBAAwB,CAAC,YAAY,CAAC;QACpD,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IAC/B,MAAM,uBAAuB,GAAG,uBAAU,CAAC,wBAAwB,CAClE,WAAW,EACX;QACC,IAAI,EAAE,cAAc;QACpB,YAAY,EAAE,gBAA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BAAuB,CAAC,QAAQ,EAAE;YACpD,YAAY,EAAE,gBAAgB;YAC9B,oBAAoB,EAAE,uBAAuB;YAC7C,SAAS;SACR,CAAC;QACJ,CAAC,CAAC,SAAS,CAAC;IAEb,IAAI,UAAU,EAAE,CAAC;QAChB,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IACtB,CAAC;IAED,OAAO;QACN,YAAY,EAAE,gBAAgB;QAC9B,oBAAoB;QACpB,GAAG;KACH,CAAC;AACH,CAAC,CAAC;AAjHW,QAAA,qCAAqC,yCAiHhD;AAOF;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACI,MAAM,qCAAqC,GAAG,KAAK,EAAE,EAC3D,WAAW,EACX,MAAM,EACN,gBAAgB,EAChB,SAAS,EACT,gBAAgB,EAChB,YAAY,EACZ,WAAW,EACX,MAAM,GAAG,oBAAY,EACrB,gBAAgB,EAChB,oBAAoB,EACpB,QAAQ,EACR,cAAc,GAC+B,EAI3C,EAAE;IACJ,MAAM,EAAE,GAAG,EAAE,oBAAoB,EAAE,YAAY,EAAE,GAChD,MAAM,IAAA,6CAAqC,EAAC;QAC3C,WAAW;QACX,MAAM;QACN,gBAAgB;QAChB,SAAS;QACT,gBAAgB;QAChB,YAAY;QACZ,WAAW;QACX,MAAM;QACN,gBAAgB;QAChB,oBAAoB;QACpB,cAAc;KACd,CAAC,CAAC;IAEJ,MAAM,EAAE,GAAG,MAAM,WAAW,CAAC,gBAAgB,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;IAE7D,OAAO,EAAE,WAAW,EAAE,EAAE,EAAE,oBAAoB,EAAE,YAAY,EAAE,CAAC;AAChE,CAAC,CAAC;AApCW,QAAA,qCAAqC,yCAoChD","sourcesContent":["import {\n\tBN,\n\tDriftClient,\n\tgetUserAccountPublicKeySync,\n\tPublicKey,\n\tReferrerInfo,\n\tReferrerNameAccount,\n\tSpotMarketConfig,\n\tTxParams,\n\tUserStatsAccount,\n\tZERO,\n} from '@drift-labs/sdk';\nimport { getTokenAddressForDepositAndWithdraw } from '../../../../utils/token';\nimport { DEFAULT_ACCOUNT_NAMES_BY_POOL_ID } from '../../constants/accountNames';\nimport { MAIN_POOL_ID } from '../../../../constants/pools';\nimport {\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport { USER_UTILS } from '../../../../_deprecated/user-utils';\n\ninterface CreateUserAndDepositCollateralBaseIxsParams {\n\tdriftClient: DriftClient;\n\tamount: BN;\n\tspotMarketConfig: SpotMarketConfig;\n\tauthority: PublicKey;\n\tuserStatsAccount: UserStatsAccount | undefined;\n\treferrerName?: string;\n\taccountName?: string;\n\tpoolId?: number;\n\tfromSubAccountId?: number;\n\tcustomMaxMarginRatio?: number;\n\tdelegate?: PublicKey;\n\t/**\n\t * Optional external wallet to deposit from. If provided, the deposit will be made\n\t * from this wallet instead of the authority wallet.\n\t */\n\texternalWallet?: PublicKey;\n}\n\n/**\n * Creates transaction instructions for initializing a new user account and depositing collateral.\n *\n * This function generates the necessary transaction instructions to:\n * 1. Initialize a new user account in the Drift protocol\n * 2. Deposit collateral into the newly created account\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param amount - The amount of collateral to deposit (in base units)\n * @param spotMarketConfig - The spot market config of the deposit collateral\n * @param authority - The public key of the account authority (wallet owner)\n * @param userStatsAccount - Existing user stats account, used to determine next sub-account ID\n * @param referrerName - Optional name of the referrer for referral tracking\n * @param accountName - Optional custom name for the account (defaults to pool-specific name)\n * @param poolId - The pool ID to associate the account with (defaults to MAIN_POOL_ID)\n * @param fromSubAccountId - Optional sub-account ID to transfer funds from\n * @param customMaxMarginRatio - Optional custom maximum margin ratio for the account\n * @param delegate - Optional delegate public key for the account. Immediately assigns this as the delegate of the account.\n * @param externalWallet - Optional external wallet to deposit from (instead of authority wallet)\n *\n * @returns Promise resolving to an object containing:\n * - subAccountId: The ID of the newly created sub-account\n * - userAccountPublicKey: The public key of the created user account\n * - ixs: Array of transaction instructions to execute\n */\nexport const createUserAndDepositCollateralBaseIxs = async ({\n\tdriftClient,\n\tamount,\n\tspotMarketConfig,\n\tauthority,\n\tuserStatsAccount,\n\treferrerName,\n\taccountName,\n\tpoolId = MAIN_POOL_ID,\n\tfromSubAccountId,\n\tcustomMaxMarginRatio,\n\tdelegate,\n\texternalWallet,\n}: CreateUserAndDepositCollateralBaseIxsParams): Promise<{\n\tsubAccountId: number;\n\tuserAccountPublicKey: PublicKey;\n\tixs: TransactionInstruction[];\n}> => {\n\tconst nextSubaccountId = userStatsAccount?.numberOfSubAccountsCreated ?? 0; // userId is zero indexed\n\n\t// Get the spot market account to determine the correct token program for Token-2022 tokens\n\tconst spotMarketAccount = driftClient.getSpotMarketAccount(\n\t\tspotMarketConfig.marketIndex\n\t);\n\n\tif (!spotMarketAccount) {\n\t\tthrow new Error(\n\t\t\t`Spot market account not found for market index ${spotMarketConfig.marketIndex}`\n\t\t);\n\t}\n\n\t// Use external wallet for token address if provided, otherwise use authority\n\tconst depositSourceWallet = externalWallet ?? authority;\n\tconst associatedDepositTokenAddressPromise =\n\t\tgetTokenAddressForDepositAndWithdraw(\n\t\t\tspotMarketAccount,\n\t\t\tdepositSourceWallet\n\t\t);\n\tconst referrerNameAccountPromise: Promise<ReferrerNameAccount | undefined> =\n\t\treferrerName\n\t\t\t? driftClient.fetchReferrerNameAccount(referrerName)\n\t\t\t: Promise.resolve(undefined);\n\tconst subaccountExistsPromise = USER_UTILS.checkIfUserAccountExists(\n\t\tdriftClient,\n\t\t{\n\t\t\ttype: 'subAccountId',\n\t\t\tsubAccountId: nextSubaccountId,\n\t\t\tauthority,\n\t\t}\n\t);\n\n\tconst [associatedDepositTokenAddress, referrerNameAccount, subaccountExists] =\n\t\tawait Promise.all([\n\t\t\tassociatedDepositTokenAddressPromise,\n\t\t\treferrerNameAccountPromise,\n\t\t\tsubaccountExistsPromise,\n\t\t]);\n\n\tif (subaccountExists) {\n\t\tthrow new Error('Subaccount already exists');\n\t}\n\n\tconst accountNameToUse =\n\t\taccountName ??\n\t\t(poolId !== MAIN_POOL_ID || nextSubaccountId === 0\n\t\t\t? DEFAULT_ACCOUNT_NAMES_BY_POOL_ID[poolId]\n\t\t\t: `Account ${nextSubaccountId}`);\n\n\tconst referrerInfo: ReferrerInfo | undefined = referrerNameAccount\n\t\t? {\n\t\t\t\treferrer: referrerNameAccount.user,\n\t\t\t\treferrerStats: referrerNameAccount.userStats,\n\t\t }\n\t\t: undefined;\n\n\tconst { ixs: createAndDepositIxs, userAccountPublicKey } =\n\t\tawait driftClient.createInitializeUserAccountAndDepositCollateralIxs(\n\t\t\tamount,\n\t\t\tassociatedDepositTokenAddress,\n\t\t\tspotMarketConfig.marketIndex,\n\t\t\tnextSubaccountId,\n\t\t\taccountNameToUse,\n\t\t\tfromSubAccountId,\n\t\t\treferrerInfo,\n\t\t\tZERO,\n\t\t\tcustomMaxMarginRatio,\n\t\t\tpoolId,\n\t\t\texternalWallet ? { externalWallet } : undefined\n\t\t);\n\tconst ixs: TransactionInstruction[] = [...createAndDepositIxs];\n\n\tconst nextSubAccountPublicKey = getUserAccountPublicKeySync(\n\t\tdriftClient.program.programId,\n\t\tauthority,\n\t\tnextSubaccountId\n\t);\n\tconst delegateIx = delegate\n\t\t? await driftClient.getUpdateUserDelegateIx(delegate, {\n\t\t\t\tsubAccountId: nextSubaccountId,\n\t\t\t\tuserAccountPublicKey: nextSubAccountPublicKey,\n\t\t\t\tauthority,\n\t\t })\n\t\t: undefined;\n\n\tif (delegateIx) {\n\t\tixs.push(delegateIx);\n\t}\n\n\treturn {\n\t\tsubAccountId: nextSubaccountId,\n\t\tuserAccountPublicKey,\n\t\tixs,\n\t};\n};\n\ninterface CreateUserAndDepositCollateralBaseTxnParams\n\textends CreateUserAndDepositCollateralBaseIxsParams {\n\ttxParams?: TxParams;\n}\n\n/**\n * Creates a complete transaction for initializing a new user account and depositing collateral.\n *\n * This function is a higher-level wrapper around `createUserAndDepositCollateralBaseIxs` that:\n * 1. Generates the necessary transaction instructions\n * 2. Builds a complete transaction ready for signing and submission\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param amount - The amount of collateral to deposit (in base units)\n * @param spotMarketConfig - The spot market config of the deposit collateral\n * @param authority - The public key of the account authority (wallet owner)\n * @param userStatsAccount - Existing user stats account, used to determine next sub-account ID\n * @param referrerName - Optional name of the referrer for referral tracking\n * @param accountName - Optional custom name for the account (defaults to pool-specific name)\n * @param poolId - The pool ID to associate the account with (defaults to MAIN_POOL_ID)\n * @param fromSubAccountId - Optional sub-account ID to transfer funds from\n * @param customMaxMarginRatio - Optional custom maximum margin ratio for the account\n * @param txParams - Transaction parameters for building the transaction (compute units, priority fees, etc.)\n * @param externalWallet - Optional external wallet to deposit from (instead of authority wallet)\n *\n * @returns Promise resolving to an object containing:\n * - transaction: The built transaction ready for signing (Transaction or VersionedTransaction)\n * - userAccountPublicKey: The public key of the created user account\n * - subAccountId: The ID of the newly created sub-account\n */\nexport const createUserAndDepositCollateralBaseTxn = async ({\n\tdriftClient,\n\tamount,\n\tspotMarketConfig,\n\tauthority,\n\tuserStatsAccount,\n\treferrerName,\n\taccountName,\n\tpoolId = MAIN_POOL_ID,\n\tfromSubAccountId,\n\tcustomMaxMarginRatio,\n\ttxParams,\n\texternalWallet,\n}: CreateUserAndDepositCollateralBaseTxnParams): Promise<{\n\ttransaction: Transaction | VersionedTransaction;\n\tuserAccountPublicKey: PublicKey;\n\tsubAccountId: number;\n}> => {\n\tconst { ixs, userAccountPublicKey, subAccountId } =\n\t\tawait createUserAndDepositCollateralBaseIxs({\n\t\t\tdriftClient,\n\t\t\tamount,\n\t\t\tspotMarketConfig,\n\t\t\tauthority,\n\t\t\tuserStatsAccount,\n\t\t\treferrerName,\n\t\t\taccountName,\n\t\t\tpoolId,\n\t\t\tfromSubAccountId,\n\t\t\tcustomMaxMarginRatio,\n\t\t\texternalWallet,\n\t\t});\n\n\tconst tx = await driftClient.buildTransaction(ixs, txParams);\n\n\treturn { transaction: tx, userAccountPublicKey, subAccountId };\n};\n"]}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.getSpotBalanceInfo = void 0;
|
|
4
4
|
const sdk_1 = require("@drift-labs/sdk");
|
|
5
|
-
const
|
|
5
|
+
const market_utils_1 = require("../../../../_deprecated/market-utils");
|
|
6
6
|
/**
|
|
7
7
|
* Derives essential balance display information from a User's SpotPosition.
|
|
8
8
|
*
|
|
@@ -20,7 +20,7 @@ const market_1 = require("../../../../common-ui-utils/market");
|
|
|
20
20
|
* @returns SpotBalanceInfo object containing the three essential balance metrics
|
|
21
21
|
*/
|
|
22
22
|
const getSpotBalanceInfo = (driftClient, user, marketIndex, oraclePrice) => {
|
|
23
|
-
const spotMarketConfig =
|
|
23
|
+
const spotMarketConfig = market_utils_1.MARKET_UTILS.getMarketConfig(driftClient.env, sdk_1.MarketType.SPOT, marketIndex);
|
|
24
24
|
const baseBalance = user.getTokenAmount(marketIndex);
|
|
25
25
|
const baseBalanceBigNum = sdk_1.BigNum.from(baseBalance, spotMarketConfig.precisionExp);
|
|
26
26
|
const notionalBalance = baseBalanceBigNum
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"balances.js","sourceRoot":"","sources":["../../../../../src/drift/base/details/user/balances.ts"],"names":[],"mappings":";;;AAAA,yCAQyB;AACzB
|
|
1
|
+
{"version":3,"file":"balances.js","sourceRoot":"","sources":["../../../../../src/drift/base/details/user/balances.ts"],"names":[],"mappings":";;;AAAA,yCAQyB;AACzB,uEAAoE;AA2BpE;;;;;;;;;;;;;;;GAeG;AACI,MAAM,kBAAkB,GAAG,CACjC,WAAwB,EACxB,IAAU,EACV,WAAmB,EACnB,WAAe,EACG,EAAE;IACpB,MAAM,gBAAgB,GAAG,2BAAY,CAAC,eAAe,CACpD,WAAW,CAAC,GAAG,EACf,gBAAU,CAAC,IAAI,EACf,WAAW,CACX,CAAC;IAEF,MAAM,WAAW,GAAG,IAAI,CAAC,cAAc,CAAC,WAAW,CAAC,CAAC;IACrD,MAAM,iBAAiB,GAAG,YAAM,CAAC,IAAI,CACpC,WAAW,EACX,gBAAgB,CAAC,YAAY,CAC7B,CAAC;IAEF,MAAM,eAAe,GAAG,iBAAiB;SACvC,GAAG,CAAC,YAAM,CAAC,IAAI,CAAC,WAAW,EAAE,yBAAmB,CAAC,CAAC;SAClD,OAAO,CAAC,yBAAmB,CAAC,CAAC;IAE/B,MAAM,QAAQ,GAAG,IAAI,CAAC,oBAAoB,CAAC,WAAW,CAAC,CAAC;IACxD,MAAM,gBAAgB,GAAG,YAAM,CAAC,IAAI,CAAC,QAAQ,EAAE,yBAAmB,CAAC,CAAC;IAEpE,OAAO;QACN,WAAW;QACX,WAAW,EAAE,iBAAiB;QAC9B,eAAe;QACf,gBAAgB;KAChB,CAAC;AACH,CAAC,CAAC;AA/BW,QAAA,kBAAkB,sBA+B7B","sourcesContent":["import {\n\tBigNum,\n\tBN,\n\tDriftClient,\n\tMarketType,\n\tPRICE_PRECISION_EXP,\n\tQUOTE_PRECISION_EXP,\n\tUser,\n} from '@drift-labs/sdk';\nimport { MARKET_UTILS } from '../../../../_deprecated/market-utils';\n\n/**\n * Essential balance information for a spot market position.\n * Contains the three key metrics needed for balance display and analysis.\n */\nexport interface SpotBalanceInfo {\n\tmarketIndex: number;\n\t/**\n\t * Net balance in base asset terms (deposits - borrows).\n\t * Positive values indicate net deposits, negative values indicate net borrows.\n\t */\n\tbaseBalance: BigNum;\n\n\t/**\n\t * USD notional value of the net balance based on oracle price.\n\t * This represents the current market value of the position.\n\t */\n\tnotionalBalance: BigNum;\n\n\t/**\n\t * Oracle price at which this balance would contribute to account liquidation.\n\t * Returns zero if liquidation price cannot be calculated.\n\t */\n\tliquidationPrice: BigNum;\n}\n\n/**\n * Derives essential balance display information from a User's SpotPosition.\n *\n * Key features:\n * - Calculates net balance (deposits minus borrows) in base asset terms\n * - Computes USD notional value using current oracle price\n * - Determines liquidation price for the specific market\n * - Handles edge cases like zero balances and invalid liquidation prices\n *\n * @param driftClient - The DriftClient instance.\n * @param user - The User instance.\n * @param marketIndex - The market index for the spot market.\n * @param oraclePrice - The oracle price for the spot market.\n *\n * @returns SpotBalanceInfo object containing the three essential balance metrics\n */\nexport const getSpotBalanceInfo = (\n\tdriftClient: DriftClient,\n\tuser: User,\n\tmarketIndex: number,\n\toraclePrice: BN\n): SpotBalanceInfo => {\n\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\tdriftClient.env,\n\t\tMarketType.SPOT,\n\t\tmarketIndex\n\t);\n\n\tconst baseBalance = user.getTokenAmount(marketIndex);\n\tconst baseBalanceBigNum = BigNum.from(\n\t\tbaseBalance,\n\t\tspotMarketConfig.precisionExp\n\t);\n\n\tconst notionalBalance = baseBalanceBigNum\n\t\t.mul(BigNum.from(oraclePrice, PRICE_PRECISION_EXP))\n\t\t.shiftTo(QUOTE_PRECISION_EXP);\n\n\tconst liqPrice = user.spotLiquidationPrice(marketIndex);\n\tconst liquidationPrice = BigNum.from(liqPrice, PRICE_PRECISION_EXP);\n\n\treturn {\n\t\tmarketIndex,\n\t\tbaseBalance: baseBalanceBigNum,\n\t\tnotionalBalance,\n\t\tliquidationPrice,\n\t};\n};\n"]}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.getPositionInfo = exports.getPriceBasedPositionInfo = void 0;
|
|
4
4
|
const sdk_1 = require("@drift-labs/sdk");
|
|
5
|
-
const
|
|
5
|
+
const trading_utils_1 = require("../../../../_deprecated/trading-utils");
|
|
6
6
|
const utils_1 = require("../../../../utils");
|
|
7
7
|
const constants_1 = require("../../../../constants");
|
|
8
8
|
/**
|
|
@@ -44,7 +44,7 @@ const getPriceBasedPositionInfo = (driftClient, perpPosition, referencePrice, ac
|
|
|
44
44
|
}
|
|
45
45
|
}
|
|
46
46
|
// position pnl
|
|
47
|
-
const positionNotionalPnlBN =
|
|
47
|
+
const positionNotionalPnlBN = trading_utils_1.TRADING_UTILS.calculatePotentialProfit({
|
|
48
48
|
currentPositionSize: baseSizeBigNum,
|
|
49
49
|
currentPositionDirection: isShortPosition
|
|
50
50
|
? sdk_1.PositionDirection.SHORT
|