@drift-labs/common 1.0.16 → 1.0.18
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/EnvironmentConstants.js +2 -2
- package/lib/EnvironmentConstants.js.map +1 -1
- package/lib/clients/DlobWebsocketClient.d.ts +6 -0
- package/lib/clients/DlobWebsocketClient.js +24 -4
- package/lib/clients/DlobWebsocketClient.js.map +1 -1
- package/lib/clients/candleClient.js +12 -0
- package/lib/clients/candleClient.js.map +1 -1
- package/lib/clients/swiftClient.d.ts +1 -0
- package/lib/clients/swiftClient.js +79 -25
- package/lib/clients/swiftClient.js.map +1 -1
- package/lib/clients/tvFeed.d.ts +5 -1
- package/lib/clients/tvFeed.js +32 -5
- package/lib/clients/tvFeed.js.map +1 -1
- package/lib/common-ui-utils/commonUiUtils.d.ts +1 -2
- package/lib/common-ui-utils/commonUiUtils.js +38 -3
- package/lib/common-ui-utils/commonUiUtils.js.map +1 -1
- package/lib/common-ui-utils/order.d.ts +1 -2
- package/lib/common-ui-utils/order.js +9 -10
- package/lib/common-ui-utils/order.js.map +1 -1
- package/lib/common-ui-utils/user.js +23 -20
- package/lib/common-ui-utils/user.js.map +1 -1
- package/lib/constants/autogenerated/driftErrors.json +5 -1
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.d.ts +1 -1
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js +20 -5
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js.map +1 -1
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/types.d.ts +9 -1
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/types.js.map +1 -1
- package/lib/drift/Drift/clients/AuthorityDrift/index.d.ts +1 -1
- package/lib/drift/Drift/clients/AuthorityDrift/index.js.map +1 -1
- package/lib/drift/Drift/clients/CentralServerDrift/index.d.ts +18 -2
- package/lib/drift/Drift/clients/CentralServerDrift/index.js +54 -19
- package/lib/drift/Drift/clients/CentralServerDrift/index.js.map +1 -1
- package/lib/drift/base/actions/perp/settlePnl.d.ts +4 -3
- package/lib/drift/base/actions/perp/settlePnl.js +6 -3
- package/lib/drift/base/actions/perp/settlePnl.js.map +1 -1
- package/lib/drift/base/actions/spot/deposit.d.ts +10 -3
- package/lib/drift/base/actions/spot/deposit.js +22 -7
- package/lib/drift/base/actions/spot/deposit.js.map +1 -1
- package/lib/drift/base/actions/trade/editOrder.d.ts +2 -0
- package/lib/drift/base/actions/trade/editOrder.js +1 -0
- package/lib/drift/base/actions/trade/editOrder.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/auction.d.ts +4 -1
- package/lib/drift/base/actions/trade/openPerpOrder/auction.js +4 -4
- package/lib/drift/base/actions/trade/openPerpOrder/auction.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.d.ts +6 -4
- package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.js +6 -5
- package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.d.ts +13 -6
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js +26 -16
- 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 -4
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js +12 -15
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.d.ts +48 -11
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js +54 -18
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/positionMaxLeverage.d.ts +2 -2
- package/lib/drift/base/actions/trade/openPerpOrder/positionMaxLeverage.js +6 -2
- package/lib/drift/base/actions/trade/openPerpOrder/positionMaxLeverage.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/types.d.ts +5 -3
- package/lib/drift/base/actions/trade/openPerpOrder/types.js.map +1 -1
- package/lib/drift/base/actions/trade/swap.d.ts +6 -13
- package/lib/drift/base/actions/trade/swap.js +11 -36
- package/lib/drift/base/actions/trade/swap.js.map +1 -1
- package/lib/drift/base/actions/user/create.d.ts +3 -1
- package/lib/drift/base/actions/user/create.js +27 -8
- package/lib/drift/base/actions/user/create.js.map +1 -1
- package/lib/drift/cli.js +16 -2
- package/lib/drift/cli.js.map +1 -1
- package/lib/drift/utils/auctionParamsResponseMapper.d.ts +2 -1
- package/lib/drift/utils/auctionParamsResponseMapper.js +1 -1
- package/lib/drift/utils/auctionParamsResponseMapper.js.map +1 -1
- package/lib/drift/utils/orderParams.js +1 -1
- package/lib/drift/utils/orderParams.js.map +1 -1
- package/lib/serializableTypes.d.ts +1 -0
- package/lib/serializableTypes.js +4 -0
- package/lib/serializableTypes.js.map +1 -1
- package/lib/utils/driftEvents.js +18 -2
- package/lib/utils/driftEvents.js.map +1 -1
- package/lib/utils/logger.js +34 -3
- package/lib/utils/logger.js.map +1 -1
- package/lib/utils/signedMsgs.d.ts +1 -1
- package/lib/utils/signedMsgs.js +2 -2
- package/lib/utils/signedMsgs.js.map +1 -1
- package/lib/utils/token.d.ts +2 -1
- package/lib/utils/token.js +3 -2
- package/lib/utils/token.js.map +1 -1
- package/package.json +16 -4
|
@@ -1,12 +1,24 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.prepSignAndSendSwiftOrder = exports.sendSwiftOrder = exports.signSwiftOrderMsg = exports.AuctionSlotExpiredError = exports.prepSwiftOrder = exports.MINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = exports.SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = void 0;
|
|
3
|
+
exports.prepSignAndSendSwiftOrder = exports.sendSwiftOrder = exports.signSwiftOrderMsg = exports.AuctionSlotExpiredError = exports.prepSwiftOrder = exports.MINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = exports.SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = exports.MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = exports.USER_SIGNING_MESSAGE_BUFFER_SLOTS = void 0;
|
|
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
7
|
const swiftClient_1 = require("../../../../../../clients/swiftClient");
|
|
8
8
|
const types_1 = require("../../../../../../types");
|
|
9
9
|
const trading_1 = require("../../../../../../common-ui-utils/trading");
|
|
10
|
+
const web3_js_1 = require("@solana/web3.js");
|
|
11
|
+
/**
|
|
12
|
+
* 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).
|
|
13
|
+
*/
|
|
14
|
+
exports.USER_SIGNING_MESSAGE_BUFFER_SLOTS = 7;
|
|
15
|
+
/**
|
|
16
|
+
* Orders without auction require a higher buffer (kink of the SWIFT server handling non-auction orders)
|
|
17
|
+
*/
|
|
18
|
+
exports.MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 35;
|
|
19
|
+
/**
|
|
20
|
+
* Buffer slots from the end of the auction to prevent the signing of the order message.
|
|
21
|
+
*/
|
|
10
22
|
exports.SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 5;
|
|
11
23
|
exports.MINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 5;
|
|
12
24
|
/**
|
|
@@ -18,7 +30,7 @@ exports.MINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 5;
|
|
|
18
30
|
* @param currentSlot - Current blockchain slot number
|
|
19
31
|
* @param isDelegate - Whether this is a delegate order
|
|
20
32
|
* @param orderParams - Order parameters including main order and optional stop loss/take profit
|
|
21
|
-
* @param
|
|
33
|
+
* @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.
|
|
22
34
|
*
|
|
23
35
|
* @returns An object containing:
|
|
24
36
|
* - `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.
|
|
@@ -26,19 +38,28 @@ exports.MINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 5;
|
|
|
26
38
|
* - `slotForSignedMsg`: The slot number for the signed message
|
|
27
39
|
* - `signedMsgOrderUuid`: Unique identifier for the signed message order
|
|
28
40
|
*/
|
|
29
|
-
const prepSwiftOrder = ({ driftClient, takerUserAccount, currentSlot, isDelegate, orderParams,
|
|
41
|
+
const prepSwiftOrder = ({ driftClient, takerUserAccount, currentSlot, isDelegate, orderParams, userSigningSlotBuffer, builderParams, }) => {
|
|
30
42
|
var _a, _b;
|
|
31
43
|
const mainOrderParams = (0, sdk_2.getOrderParams)({
|
|
32
44
|
...orderParams.main,
|
|
33
45
|
auctionDuration: orderParams.main.auctionDuration || null, // swift server expects auctionDuration to be null if not set, won't handle 0
|
|
34
46
|
});
|
|
47
|
+
if (!userSigningSlotBuffer) {
|
|
48
|
+
userSigningSlotBuffer = mainOrderParams.auctionDuration
|
|
49
|
+
? exports.USER_SIGNING_MESSAGE_BUFFER_SLOTS
|
|
50
|
+
: exports.MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS;
|
|
51
|
+
}
|
|
52
|
+
// if it is not an auction order, there should be a minimum buffer used
|
|
53
|
+
if (!mainOrderParams.auctionDuration) {
|
|
54
|
+
userSigningSlotBuffer = Math.max(userSigningSlotBuffer, exports.MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS);
|
|
55
|
+
}
|
|
35
56
|
// buffer for time the user takes to sign a message and send to the swift server
|
|
36
|
-
const
|
|
57
|
+
const auctionStartSlot = new sdk_2.BN(currentSlot + userSigningSlotBuffer);
|
|
37
58
|
const signedMsgOrderUuid = (0, sdk_2.generateSignedMsgUuid)();
|
|
38
59
|
const baseSignedMsgOrderParamsMessage = {
|
|
39
60
|
signedMsgOrderParams: mainOrderParams,
|
|
40
61
|
uuid: signedMsgOrderUuid,
|
|
41
|
-
slot:
|
|
62
|
+
slot: auctionStartSlot,
|
|
42
63
|
stopLossOrderParams: orderParams.stopLoss
|
|
43
64
|
? {
|
|
44
65
|
baseAssetAmount: orderParams.stopLoss.baseAssetAmount,
|
|
@@ -75,7 +96,7 @@ const prepSwiftOrder = ({ driftClient, takerUserAccount, currentSlot, isDelegate
|
|
|
75
96
|
string: hexEncodedSwiftOrderMessage.toString(),
|
|
76
97
|
},
|
|
77
98
|
signedMsgOrderParamsMessage,
|
|
78
|
-
slotForSignedMsg,
|
|
99
|
+
slotForSignedMsg: auctionStartSlot,
|
|
79
100
|
signedMsgOrderUuid,
|
|
80
101
|
};
|
|
81
102
|
};
|
|
@@ -146,7 +167,7 @@ exports.signSwiftOrderMsg = signSwiftOrderMsg;
|
|
|
146
167
|
* @param signedMsgOrderUuid - Unique identifier for the signed message order
|
|
147
168
|
* @param takerAuthority - Public key of the taker authority
|
|
148
169
|
* @param signingAuthority - Public key of the signing authority
|
|
149
|
-
* @param
|
|
170
|
+
* @param slotsTillAuctionEnd - Number of slots till the end of the auction (optional)
|
|
150
171
|
* @param swiftConfirmationSlotBuffer - Slot buffer for swift server confirmation time (default: 15)
|
|
151
172
|
* @param onExpired - Callback function called when the order expires
|
|
152
173
|
* @param onErrored - Callback function called when the order encounters an error
|
|
@@ -155,9 +176,9 @@ exports.signSwiftOrderMsg = signSwiftOrderMsg;
|
|
|
155
176
|
* @returns Promise that resolves when the order processing is complete
|
|
156
177
|
*
|
|
157
178
|
*/
|
|
158
|
-
const sendSwiftOrder = ({ driftClient, marketId, hexEncodedSwiftOrderMessageString, signedMessage, signedMsgOrderUuid, takerAuthority, signingAuthority,
|
|
179
|
+
const sendSwiftOrder = ({ driftClient, marketId, hexEncodedSwiftOrderMessageString, signedMessage, signedMsgOrderUuid, takerAuthority, signingAuthority, slotsTillAuctionEnd, confirmationMultiplier, confirmationConnection, }) => {
|
|
159
180
|
const signedMsgUserOrdersAccountPubkey = (0, sdk_1.getSignedMsgUserAccountPublicKey)(driftClient.program.programId, takerAuthority);
|
|
160
|
-
const swiftOrderObservable = swiftClient_1.SwiftClient.sendAndConfirmSwiftOrderWS(driftClient.connection, driftClient, marketId.marketIndex, marketId.marketType, hexEncodedSwiftOrderMessageString, Buffer.from(signedMessage), takerAuthority, signedMsgUserOrdersAccountPubkey, signedMsgOrderUuid, (0, utils_1.getSwiftConfirmationTimeoutMs)(
|
|
181
|
+
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, utils_1.getSwiftConfirmationTimeoutMs)(slotsTillAuctionEnd, confirmationMultiplier), signingAuthority);
|
|
161
182
|
return swiftOrderObservable;
|
|
162
183
|
};
|
|
163
184
|
exports.sendSwiftOrder = sendSwiftOrder;
|
|
@@ -166,8 +187,8 @@ exports.sendSwiftOrder = sendSwiftOrder;
|
|
|
166
187
|
* Callbacks can be provided to handle the events of the Swift order.
|
|
167
188
|
* Returns a promise that resolves when the Swift order has reached a terminal state (i.e. confirmed, expired, or errored).
|
|
168
189
|
*/
|
|
169
|
-
const prepSignAndSendSwiftOrder = async ({ driftClient, subAccountId, userAccountPubKey, marketIndex,
|
|
170
|
-
var _a, _b, _c, _d, _e;
|
|
190
|
+
const prepSignAndSendSwiftOrder = async ({ driftClient, subAccountId, userAccountPubKey, marketIndex, userSigningSlotBuffer, swiftOptions, orderParams, builderParams, confirmationMultiplier, }) => {
|
|
191
|
+
var _a, _b, _c, _d, _e, _f;
|
|
171
192
|
const currentSlot = await driftClient.connection.getSlot('confirmed');
|
|
172
193
|
const { hexEncodedSwiftOrderMessage, signedMsgOrderUuid, signedMsgOrderParamsMessage, } = (0, exports.prepSwiftOrder)({
|
|
173
194
|
driftClient,
|
|
@@ -178,13 +199,26 @@ const prepSignAndSendSwiftOrder = async ({ driftClient, subAccountId, userAccoun
|
|
|
178
199
|
currentSlot,
|
|
179
200
|
isDelegate: swiftOptions.isDelegate || false,
|
|
180
201
|
orderParams,
|
|
181
|
-
|
|
202
|
+
userSigningSlotBuffer,
|
|
182
203
|
builderParams,
|
|
183
204
|
});
|
|
184
205
|
(_b = (_a = swiftOptions.callbacks) === null || _a === void 0 ? void 0 : _a.onOrderParamsMessagePrepped) === null || _b === void 0 ? void 0 : _b.call(_a, signedMsgOrderParamsMessage);
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
206
|
+
// both market and non-market orders can have auction durations.
|
|
207
|
+
//
|
|
208
|
+
// for market orders, the auction duration + user signing slot buffer is a good gauge for slots until auction end
|
|
209
|
+
//
|
|
210
|
+
// for non-market orders, if they have an auction duration, we use the maximum of MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS
|
|
211
|
+
// and the (auction duration + user signing slot buffer). This is because limit auctions can have very small auction durations,
|
|
212
|
+
// but the limit order is still valid to be placed even after the auction ends, hence we enforce a minimum duration so that
|
|
213
|
+
// short limit auction durations can still be placed
|
|
214
|
+
const isMarketOrder = utils_1.ENUM_UTILS.match(orderParams.main.orderType, sdk_1.OrderType.ORACLE) ||
|
|
215
|
+
utils_1.ENUM_UTILS.match(orderParams.main.orderType, sdk_1.OrderType.MARKET);
|
|
216
|
+
const slotsTillAuctionEnd = orderParams.main.auctionDuration
|
|
217
|
+
? isMarketOrder
|
|
218
|
+
? userSigningSlotBuffer + orderParams.main.auctionDuration
|
|
219
|
+
: Math.max(exports.MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS, userSigningSlotBuffer + orderParams.main.auctionDuration)
|
|
220
|
+
: exports.MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS;
|
|
221
|
+
const expirationTimeMs = Math.max(slotsTillAuctionEnd - exports.SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS, exports.MINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS) * sdk_1.SLOT_TIME_ESTIMATE_MS;
|
|
188
222
|
// Ensure that the user signs the message before the expiration time
|
|
189
223
|
const signedMessage = await (0, exports.signSwiftOrderMsg)({
|
|
190
224
|
wallet: swiftOptions.wallet,
|
|
@@ -194,7 +228,7 @@ const prepSignAndSendSwiftOrder = async ({ driftClient, subAccountId, userAccoun
|
|
|
194
228
|
});
|
|
195
229
|
(_d = (_c = swiftOptions.callbacks) === null || _c === void 0 ? void 0 : _c.onSigningSuccess) === null || _d === void 0 ? void 0 : _d.call(_c, signedMessage, signedMsgOrderUuid, signedMsgOrderParamsMessage);
|
|
196
230
|
// Initialize SwiftClient (required before using sendSwiftOrder)
|
|
197
|
-
swiftClient_1.SwiftClient.init(swiftOptions.swiftServerUrl);
|
|
231
|
+
swiftClient_1.SwiftClient.init(swiftOptions.swiftServerUrl, (_e = swiftOptions.source) !== null && _e !== void 0 ? _e : '');
|
|
198
232
|
// Create a promise-based wrapper for the sendSwiftOrder callback-based API
|
|
199
233
|
const swiftOrderObservable = (0, exports.sendSwiftOrder)({
|
|
200
234
|
driftClient,
|
|
@@ -203,8 +237,10 @@ const prepSignAndSendSwiftOrder = async ({ driftClient, subAccountId, userAccoun
|
|
|
203
237
|
signedMessage,
|
|
204
238
|
signedMsgOrderUuid,
|
|
205
239
|
takerAuthority: swiftOptions.wallet.takerAuthority,
|
|
206
|
-
signingAuthority: (
|
|
207
|
-
|
|
240
|
+
signingAuthority: (_f = swiftOptions.wallet.signingAuthority) !== null && _f !== void 0 ? _f : swiftOptions.wallet.takerAuthority,
|
|
241
|
+
slotsTillAuctionEnd,
|
|
242
|
+
confirmationMultiplier,
|
|
243
|
+
confirmationConnection: new web3_js_1.Connection(driftClient.connection.rpcEndpoint, 'processed'),
|
|
208
244
|
});
|
|
209
245
|
const wrapSwiftOrderEvent = (swiftOrderEvent) => {
|
|
210
246
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.ts"],"names":[],"mappings":";;;AAAA,yCAKyB;AACzB,yCAOyB;AACzB,mDAAwE;AACxE,uEAO+C;AAC/C,mDAAmD;AAGnD,uEAA0E;AAE7D,QAAA,2CAA2C,GAAG,CAAC,CAAC;AAChD,QAAA,mDAAmD,GAAG,CAAC,CAAC;AAsGrE;;;;;;;;;;;;;;;;GAgBG;AACI,MAAM,cAAc,GAAG,CAAC,EAC9B,WAAW,EACX,gBAAgB,EAChB,WAAW,EACX,UAAU,EACV,WAAW,EACX,UAAU,GAAG,EAAE,EACf,aAAa,GACS,EAUrB,EAAE;;IACH,MAAM,eAAe,GAAG,IAAA,oBAAc,EAAC;QACtC,GAAG,WAAW,CAAC,IAAI;QACnB,eAAe,EAAE,WAAW,CAAC,IAAI,CAAC,eAAe,IAAI,IAAI,EAAE,6EAA6E;KACxI,CAAC,CAAC;IAEH,gFAAgF;IAChF,MAAM,gBAAgB,GAAG,IAAI,QAAE,CAAC,WAAW,GAAG,UAAU,CAAC,CAAC;IAE1D,MAAM,kBAAkB,GAAG,IAAA,2BAAqB,GAAE,CAAC;IAEnD,MAAM,+BAA+B,G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AmB,CAAC,eAAe,CAAC,CAAC,CAAC;YAC1E,mBAAmB,CAAC,YAAY,CAAC,CAAC;QACnC,CAAC;IACF,CAAC,CAAC,CAAC;IAEH,OAAO,OAAO,CAAC;AAChB,CAAC,CAAC;AAlHW,QAAA,yBAAyB,6BAkHpC","sourcesContent":["import {\n\tgetSignedMsgUserAccountPublicKey,\n\tSignedMsgOrderParamsDelegateMessage,\n\tSignedMsgOrderParamsMessage,\n\tSLOT_TIME_ESTIMATE_MS,\n} from '@drift-labs/sdk';\nimport {\n\tBN,\n\tDriftClient,\n\tgenerateSignedMsgUuid,\n\tgetOrderParams,\n\tOptionalOrderParams,\n\tPublicKey,\n} from '@drift-labs/sdk';\nimport { getSwiftConfirmationTimeoutMs } from '../../../../../../utils';\nimport {\n\tSwiftClient,\n\tSwiftOrderConfirmedEvent,\n\tSwiftOrderErroredEvent,\n\tSwiftOrderEvent,\n\tSwiftOrderEventWithParams,\n\tSwiftOrderSentEvent,\n} from '../../../../../../clients/swiftClient';\nimport { MarketId } from '../../../../../../types';\nimport { Observable, Subscription } from 'rxjs';\nimport { OptionalTriggerOrderParams } from '../types';\nimport { TRADING_UTILS } from '../../../../../../common-ui-utils/trading';\n\nexport const SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 5;\nexport const MINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 5;\n\nexport interface SwiftOrderOptions {\n\twallet: {\n\t\tsignMessage: (message: Uint8Array) => Promise<Uint8Array>;\n\t\ttakerAuthority: PublicKey;\n\t\tsigningAuthority?: PublicKey;\n\t};\n\tswiftServerUrl: string;\n\tsignedMessageOrderSlotBuffer?: number;\n\tisDelegate?: boolean;\n\tcallbacks?: {\n\t\tonOrderParamsMessagePrepped?: (\n\t\t\torderParamsMessage:\n\t\t\t\t| SignedMsgOrderParamsMessage\n\t\t\t\t| SignedMsgOrderParamsDelegateMessage\n\t\t) => void;\n\t\tonSigningExpiry?: (\n\t\t\torderParamsMessage:\n\t\t\t\t| SignedMsgOrderParamsMessage\n\t\t\t\t| SignedMsgOrderParamsDelegateMessage\n\t\t) => void;\n\t\tonSigningSuccess?: (\n\t\t\tsignedMessage: Uint8Array,\n\t\t\t// we add the following here, because the onSigningSuccess callback is called before the order is sent to the swift server\n\t\t\torderUuid: Uint8Array,\n\t\t\torderParamsMessage:\n\t\t\t\t| SignedMsgOrderParamsMessage\n\t\t\t\t| SignedMsgOrderParamsDelegateMessage\n\t\t) => void;\n\t\tonSent?: (\n\t\t\tswiftSentEvent: SwiftOrderEventWithParams<SwiftOrderSentEvent>\n\t\t) => void;\n\t\tonConfirmed?: (\n\t\t\tswiftConfirmedEvent: SwiftOrderEventWithParams<SwiftOrderConfirmedEvent>\n\t\t) => void;\n\t\tonExpired?: (\n\t\t\tswiftExpiredEvent: SwiftOrderEventWithParams<SwiftOrderErroredEvent>\n\t\t) => void;\n\t\tonErrored?: (\n\t\t\tswiftErroredEvent: SwiftOrderEventWithParams<SwiftOrderErroredEvent>\n\t\t) => void;\n\t};\n}\n\nexport type SwiftOrderObservable = Observable<SwiftOrderEvent>;\n\ninterface PrepSwiftOrderParams {\n\t/** The Drift client instance */\n\tdriftClient: DriftClient;\n\t/** The taker user account information */\n\ttakerUserAccount: {\n\t\t/** Public key of the user account */\n\t\tpubKey: PublicKey;\n\t\t/** User account ID */\n\t\tsubAccountId: number;\n\t};\n\t/** Current blockchain slot number */\n\tcurrentSlot: number;\n\t/** Whether this is a delegate order */\n\tisDelegate: boolean;\n\t/** Order parameters including main order and optional stop loss/take profit */\n\torderParams: {\n\t\t/** Main order parameters */\n\t\tmain: OptionalOrderParams;\n\t\t/** Optional stop loss order parameters */\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t\t/** Optional take profit order parameters */\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\t/** Optional max leverage for the position */\n\t\tpositionMaxLeverage?: number;\n\t};\n\t/** Buffer slots to account for signing time (default: 2 slots ~1 second). If a user is required to manually sign the message, this should be a higher number. */\n\tslotBuffer?: number;\n\t/**\n\t * Optional builder code parameters for revenue sharing.\n\t * If provided, the builder will receive a portion of the trading fees.\n\t *\n\t * Prerequisites:\n\t * - User must have initialized a RevenueShareEscrow account\n\t * - Builder must be in the user's approved_builders list\n\t * - builderFeeTenthBps must not exceed the builder's max_fee_tenth_bps\n\t */\n\tbuilderParams?: {\n\t\t/**\n\t\t * Index of the builder in the user's approved_builders list.\n\t\t * This is the position (0-indexed) of the builder in the RevenueShareEscrow.approved_builders array.\n\t\t */\n\t\tbuilderIdx: number;\n\t\t/**\n\t\t * Fee to charge for this order, in tenths of basis points.\n\t\t * Must be <= the builder's max_fee_tenth_bps.\n\t\t *\n\t\t * Examples:\n\t\t * - 10 = 1 bps = 0.01%\n\t\t * - 50 = 5 bps = 0.05%\n\t\t * - 100 = 10 bps = 0.1%\n\t\t */\n\t\tbuilderFeeTenthBps: number;\n\t};\n}\n\n/**\n * Prepares a swift order by encoding the order parameters into a message format\n * suitable for signing and sending to the Swift server.\n *\n * @param driftClient - The Drift client instance\n * @param takerUserAccount - The taker user account information\n * @param currentSlot - Current blockchain slot number\n * @param isDelegate - Whether this is a delegate order\n * @param orderParams - Order parameters including main order and optional stop loss/take profit\n * @param slotBuffer - Buffer slots to account for signing time (default: 35 slots ~14 seconds). Use this default value if it is not an auction order, else used an estimate number of slots to sign the message.\n *\n * @returns An object containing:\n * - `hexEncodedSwiftOrderMessage`: The encoded order message in both Uint8Array and string formats. The Uint8Array format is for a wallet to sign, while the string format is used to send to the SWIFT server.\n * - `signedMsgOrderParamsMessage`: The signed message order parameters\n * - `slotForSignedMsg`: The slot number for the signed message\n * - `signedMsgOrderUuid`: Unique identifier for the signed message order\n */\nexport const prepSwiftOrder = ({\n\tdriftClient,\n\ttakerUserAccount,\n\tcurrentSlot,\n\tisDelegate,\n\torderParams,\n\tslotBuffer = 35,\n\tbuilderParams,\n}: PrepSwiftOrderParams): {\n\thexEncodedSwiftOrderMessage: {\n\t\tuInt8Array: Uint8Array;\n\t\tstring: string;\n\t};\n\tsignedMsgOrderParamsMessage:\n\t\t| SignedMsgOrderParamsMessage\n\t\t| SignedMsgOrderParamsDelegateMessage;\n\tslotForSignedMsg: BN;\n\tsignedMsgOrderUuid: Uint8Array;\n} => {\n\tconst mainOrderParams = getOrderParams({\n\t\t...orderParams.main,\n\t\tauctionDuration: orderParams.main.auctionDuration || null, // swift server expects auctionDuration to be null if not set, won't handle 0\n\t});\n\n\t// buffer for time the user takes to sign a message and send to the swift server\n\tconst slotForSignedMsg = new BN(currentSlot + slotBuffer);\n\n\tconst signedMsgOrderUuid = generateSignedMsgUuid();\n\n\tconst baseSignedMsgOrderParamsMessage = {\n\t\tsignedMsgOrderParams: mainOrderParams,\n\t\tuuid: signedMsgOrderUuid,\n\t\tslot: slotForSignedMsg,\n\t\tstopLossOrderParams: orderParams.stopLoss\n\t\t\t? {\n\t\t\t\t\tbaseAssetAmount: orderParams.stopLoss.baseAssetAmount,\n\t\t\t\t\ttriggerPrice: orderParams.stopLoss.triggerPrice,\n\t\t\t }\n\t\t\t: null,\n\t\ttakeProfitOrderParams: orderParams.takeProfit\n\t\t\t? {\n\t\t\t\t\tbaseAssetAmount: orderParams.takeProfit.baseAssetAmount,\n\t\t\t\t\ttriggerPrice: orderParams.takeProfit.triggerPrice,\n\t\t\t }\n\t\t\t: null,\n\t\tmaxMarginRatio: orderParams.positionMaxLeverage\n\t\t\t? TRADING_UTILS.convertLeverageToMarginRatio(\n\t\t\t\t\torderParams.positionMaxLeverage\n\t\t\t )\n\t\t\t: null,\n\t\t// Include builder params if provided\n\t\tbuilderIdx: builderParams?.builderIdx ?? null,\n\t\tbuilderFeeTenthBps: builderParams?.builderFeeTenthBps ?? null,\n\t};\n\n\tconst signedMsgOrderParamsMessage:\n\t\t| SignedMsgOrderParamsMessage\n\t\t| SignedMsgOrderParamsDelegateMessage = isDelegate\n\t\t? {\n\t\t\t\t...baseSignedMsgOrderParamsMessage,\n\t\t\t\ttakerPubkey: takerUserAccount.pubKey,\n\t\t }\n\t\t: {\n\t\t\t\t...baseSignedMsgOrderParamsMessage,\n\t\t\t\tsubAccountId: takerUserAccount.subAccountId,\n\t\t };\n\n\tconst encodedOrderMessage = driftClient.encodeSignedMsgOrderParamsMessage(\n\t\tsignedMsgOrderParamsMessage,\n\t\tisDelegate\n\t);\n\tconst hexEncodedSwiftOrderMessage = Buffer.from(\n\t\tencodedOrderMessage.toString('hex')\n\t);\n\n\treturn {\n\t\thexEncodedSwiftOrderMessage: {\n\t\t\tuInt8Array: new Uint8Array(hexEncodedSwiftOrderMessage),\n\t\t\tstring: hexEncodedSwiftOrderMessage.toString(),\n\t\t},\n\t\tsignedMsgOrderParamsMessage,\n\t\tslotForSignedMsg,\n\t\tsignedMsgOrderUuid,\n\t};\n};\n\n/**\n * Error thrown when an auction slot has expired\n */\nexport class AuctionSlotExpiredError extends Error {\n\tname = 'AuctionSlotExpiredError';\n\n\t/**\n\t * Creates an instance of AuctionSlotExpiredError\n\t * @param message - Error message (default: 'Auction slot expired')\n\t */\n\tconstructor(message: string = 'Auction slot expired') {\n\t\tsuper(message);\n\t\tif (Error.captureStackTrace) {\n\t\t\tError.captureStackTrace(this, AuctionSlotExpiredError);\n\t\t}\n\t}\n}\n\ninterface SignOrderMsgParams {\n\t/** Wallet instance with message signing capability */\n\twallet: {\n\t\t/** Function to sign a message */\n\t\tsignMessage: (message: Uint8Array) => Promise<Uint8Array>;\n\t};\n\t/** Hex-encoded swift order message to sign */\n\thexEncodedSwiftOrderMessage: Uint8Array;\n\t/** Time in milliseconds till the auction expires */\n\texpirationTimeMs: number;\n\t/** Callback function called when the auction expires */\n\tonExpired?: () => void;\n}\n\n/**\n * Signs a swift order message with slot expiration monitoring.\n * Continuously monitors the current slot and rejects with AuctionSlotExpiredError\n * if the auction slot expires before signing is complete.\n *\n * @param wallet - Wallet instance with message signing capability\n * @param hexEncodedSwiftOrderMessage - Hex-encoded swift order message to sign\n * @param expirationTimeMs - Time in milliseconds till the auction expires\n * @param onExpired - Callback function called when the auction expires\n *\n * @returns Promise resolving to the signed message as Uint8Array\n * @throws {AuctionSlotExpiredError} When the auction slot expires before signing completes\n */\nexport const signSwiftOrderMsg = async ({\n\twallet,\n\thexEncodedSwiftOrderMessage,\n\texpirationTimeMs,\n\tonExpired,\n}: SignOrderMsgParams): Promise<Uint8Array> => {\n\tlet timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n\ttry {\n\t\t// Sign the message\n\t\tconst signedMessagePromise = wallet.signMessage(\n\t\t\thexEncodedSwiftOrderMessage\n\t\t);\n\n\t\tconst signingExpiredPromise = new Promise<never>((_resolve, reject) => {\n\t\t\ttimeoutId = setTimeout(() => {\n\t\t\t\tonExpired?.();\n\t\t\t\treject(new AuctionSlotExpiredError());\n\t\t\t}, expirationTimeMs);\n\t\t});\n\n\t\t// Ensure that the user signs the message before the expiration time\n\t\tconst signedMessage = await Promise.race([\n\t\t\tsignedMessagePromise,\n\t\t\tsigningExpiredPromise,\n\t\t]);\n\n\t\treturn signedMessage;\n\t} finally {\n\t\tif (timeoutId) {\n\t\t\tclearTimeout(timeoutId);\n\t\t}\n\t}\n};\n\n/**\n * Parameters for sending a swift order to the Swift server\n * @interface SendSwiftOrderParams\n */\ninterface SendSwiftOrderParams {\n\t/** The Drift client instance */\n\tdriftClient: DriftClient;\n\t/** Market identifier for the order */\n\tmarketId: MarketId;\n\t/** Hex-encoded swift order message as string */\n\thexEncodedSwiftOrderMessageString: string;\n\t/** The signed message from the wallet */\n\tsignedMessage: Uint8Array;\n\t/** Unique identifier for the signed message order */\n\tsignedMsgOrderUuid: Uint8Array;\n\t/** Public key of the taker authority */\n\ttakerAuthority: PublicKey;\n\t/** Public key of the signing authority */\n\tsigningAuthority: PublicKey;\n\t/** Duration of the auction in slots (optional) */\n\tauctionDuration?: number;\n}\n\n/**\n * Sends a swift order to the Swift server and handles the response.\n * Monitors the order status and calls appropriate callback functions based on the response type.\n *\n * @param driftClient - The Drift client instance\n * @param marketId - Market identifier for the order\n * @param hexEncodedSwiftOrderMessageString - Hex-encoded swift order message as string\n * @param signedMessage - The signed message from the wallet\n * @param signedMsgOrderUuid - Unique identifier for the signed message order\n * @param takerAuthority - Public key of the taker authority\n * @param signingAuthority - Public key of the signing authority\n * @param auctionDurationSlot - Duration of the auction in slots (optional)\n * @param swiftConfirmationSlotBuffer - Slot buffer for swift server confirmation time (default: 15)\n * @param onExpired - Callback function called when the order expires\n * @param onErrored - Callback function called when the order encounters an error\n * @param onConfirmed - Callback function called when the order is confirmed\n *\n * @returns Promise that resolves when the order processing is complete\n *\n */\nexport const sendSwiftOrder = ({\n\tdriftClient,\n\tmarketId,\n\thexEncodedSwiftOrderMessageString,\n\tsignedMessage,\n\tsignedMsgOrderUuid,\n\ttakerAuthority,\n\tsigningAuthority,\n\tauctionDuration,\n}: SendSwiftOrderParams): SwiftOrderObservable => {\n\tconst signedMsgUserOrdersAccountPubkey = getSignedMsgUserAccountPublicKey(\n\t\tdriftClient.program.programId,\n\t\ttakerAuthority\n\t);\n\n\tconst swiftOrderObservable = SwiftClient.sendAndConfirmSwiftOrderWS(\n\t\tdriftClient.connection,\n\t\tdriftClient,\n\t\tmarketId.marketIndex,\n\t\tmarketId.marketType,\n\t\thexEncodedSwiftOrderMessageString,\n\t\tBuffer.from(signedMessage),\n\t\ttakerAuthority,\n\t\tsignedMsgUserOrdersAccountPubkey,\n\t\tsignedMsgOrderUuid,\n\t\tgetSwiftConfirmationTimeoutMs(auctionDuration ?? 0),\n\t\tsigningAuthority\n\t);\n\n\treturn swiftOrderObservable;\n};\n\ntype PrepSignAndSendSwiftOrderParams = {\n\tdriftClient: DriftClient;\n\tsubAccountId: number;\n\tuserAccountPubKey: PublicKey;\n\tmarketIndex: number;\n\tslotBuffer: number;\n\tswiftOptions: SwiftOrderOptions;\n\torderParams: {\n\t\tmain: OptionalOrderParams;\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t\t/**\n\t\t * Adjusts the max leverage of a position.\n\t\t */\n\t\tpositionMaxLeverage?: number;\n\t};\n\t/**\n\t * Optional builder code parameters for revenue sharing.\n\t * If provided, the builder will receive a portion of the trading fees.\n\t *\n\t * Prerequisites:\n\t * - User must have initialized a RevenueShareEscrow account\n\t * - Builder must be in the user's approved_builders list\n\t * - builderFeeTenthBps must not exceed the builder's max_fee_tenth_bps\n\t *\n\t * @example\n\t * ```typescript\n\t * builderParams: {\n\t * builderIdx: 0, // First builder in approved list\n\t * builderFeeTenthBps: 50 // 5 bps = 0.05%\n\t * }\n\t * ```\n\t */\n\tbuilderParams?: {\n\t\t/**\n\t\t * Index of the builder in the user's approved_builders list.\n\t\t */\n\t\tbuilderIdx: number;\n\t\t/**\n\t\t * Fee to charge for this order, in tenths of basis points.\n\t\t * Must be <= the builder's max_fee_tenth_bps.\n\t\t */\n\t\tbuilderFeeTenthBps: number;\n\t};\n};\n\n/**\n * Handles the full flow of the swift order, from preparing to signing and sending to the Swift server.\n * Callbacks can be provided to handle the events of the Swift order.\n * Returns a promise that resolves when the Swift order has reached a terminal state (i.e. confirmed, expired, or errored).\n */\nexport const prepSignAndSendSwiftOrder = async ({\n\tdriftClient,\n\tsubAccountId,\n\tuserAccountPubKey,\n\tmarketIndex,\n\tslotBuffer,\n\tswiftOptions,\n\torderParams,\n\tbuilderParams,\n}: PrepSignAndSendSwiftOrderParams): Promise<void> => {\n\tconst currentSlot = await driftClient.connection.getSlot('confirmed');\n\n\tconst {\n\t\thexEncodedSwiftOrderMessage,\n\t\tsignedMsgOrderUuid,\n\t\tsignedMsgOrderParamsMessage,\n\t} = prepSwiftOrder({\n\t\tdriftClient,\n\t\ttakerUserAccount: {\n\t\t\tpubKey: userAccountPubKey,\n\t\t\tsubAccountId: subAccountId,\n\t\t},\n\t\tcurrentSlot,\n\t\tisDelegate: swiftOptions.isDelegate || false,\n\t\torderParams,\n\t\tslotBuffer,\n\t\tbuilderParams,\n\t});\n\n\tswiftOptions.callbacks?.onOrderParamsMessagePrepped?.(\n\t\tsignedMsgOrderParamsMessage\n\t);\n\n\tconst expirationTimeMs =\n\t\tMath.max(\n\t\t\tslotBuffer +\n\t\t\t\t(orderParams.main.auctionDuration || 0) -\n\t\t\t\tSWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS,\n\t\t\tMINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS\n\t\t) * SLOT_TIME_ESTIMATE_MS;\n\n\t// Ensure that the user signs the message before the expiration time\n\tconst signedMessage = await signSwiftOrderMsg({\n\t\twallet: swiftOptions.wallet,\n\t\thexEncodedSwiftOrderMessage: hexEncodedSwiftOrderMessage.uInt8Array,\n\t\texpirationTimeMs,\n\t\tonExpired: () =>\n\t\t\tswiftOptions.callbacks?.onSigningExpiry?.(signedMsgOrderParamsMessage),\n\t});\n\n\tswiftOptions.callbacks?.onSigningSuccess?.(\n\t\tsignedMessage,\n\t\tsignedMsgOrderUuid,\n\t\tsignedMsgOrderParamsMessage\n\t);\n\n\t// Initialize SwiftClient (required before using sendSwiftOrder)\n\tSwiftClient.init(swiftOptions.swiftServerUrl);\n\n\t// Create a promise-based wrapper for the sendSwiftOrder callback-based API\n\tconst swiftOrderObservable = sendSwiftOrder({\n\t\tdriftClient,\n\t\tmarketId: MarketId.createPerpMarket(marketIndex),\n\t\thexEncodedSwiftOrderMessageString: hexEncodedSwiftOrderMessage.string,\n\t\tsignedMessage,\n\t\tsignedMsgOrderUuid,\n\t\ttakerAuthority: swiftOptions.wallet.takerAuthority,\n\t\tsigningAuthority:\n\t\t\tswiftOptions.wallet.signingAuthority ??\n\t\t\tswiftOptions.wallet.takerAuthority,\n\t\tauctionDuration: orderParams.main.auctionDuration || undefined,\n\t});\n\n\tconst wrapSwiftOrderEvent = <T extends SwiftOrderEvent>(\n\t\tswiftOrderEvent: T\n\t) => {\n\t\treturn {\n\t\t\t...swiftOrderEvent,\n\t\t\tswiftOrderUuid: signedMsgOrderUuid,\n\t\t\torderParamsMessage: signedMsgOrderParamsMessage,\n\t\t};\n\t};\n\n\tlet promiseResolver: (value: void | PromiseLike<void>) => void;\n\tconst promise = new Promise<void>((resolve) => {\n\t\tpromiseResolver = resolve;\n\t});\n\n\tconst handleTerminalEvent = (subscription: Subscription) => {\n\t\tsubscription.unsubscribe();\n\t\tpromiseResolver();\n\t};\n\n\tconst subscription = swiftOrderObservable.subscribe((swiftOrderEvent) => {\n\t\tif (swiftOrderEvent.type === 'sent') {\n\t\t\tswiftOptions.callbacks?.onSent?.(wrapSwiftOrderEvent(swiftOrderEvent));\n\t\t}\n\t\tif (swiftOrderEvent.type === 'confirmed') {\n\t\t\tswiftOptions.callbacks?.onConfirmed?.(\n\t\t\t\twrapSwiftOrderEvent(swiftOrderEvent)\n\t\t\t);\n\t\t\thandleTerminalEvent(subscription);\n\t\t}\n\t\tif (swiftOrderEvent.type === 'expired') {\n\t\t\tswiftOptions.callbacks?.onExpired?.(wrapSwiftOrderEvent(swiftOrderEvent));\n\t\t\thandleTerminalEvent(subscription);\n\t\t}\n\t\tif (swiftOrderEvent.type === 'errored') {\n\t\t\tswiftOptions.callbacks?.onErrored?.(wrapSwiftOrderEvent(swiftOrderEvent));\n\t\t\thandleTerminalEvent(subscription);\n\t\t}\n\t});\n\n\treturn promise;\n};\n"]}
|
|
1
|
+
{"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,CAAC;AAEnD;;GAEG;AACU,QAAA,+DAA+D,GAAG,EAAE,CAAC;AAElF;;GAEG;AACU,QAAA,2CAA2C,GAAG,CAAC,CAAC;AAChD,QAAA,mDAAmD,GAAG,CAAC,CAAC;AAqH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eAAe,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YACxC,MAAA,MAAA,YAAY,CAAC,SAAS,0CAAE,SAAS,mDAAG,mBAAmB,CAAC,eAAe,CAAC,CAAC,CAAC;YAC1E,mBAAmB,CAAC,YAAY,CAAC,CAAC;QACnC,CAAC;QACD,IAAI,eAAe,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YACxC,MAAA,MAAA,YAAY,CAAC,SAAS,0CAAE,SAAS,mDAAG,mBAAmB,CAAC,eAAe,CAAC,CAAC,CAAC;YAC1E,mBAAmB,CAAC,YAAY,CAAC,CAAC;QACnC,CAAC;IACF,CAAC,CAAC,CAAC;IAEH,OAAO,OAAO,CAAC;AAChB,CAAC,CAAC;AAzIW,QAAA,yBAAyB,6BAyIpC","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\nexport type SwiftOrderObservable = Observable<SwiftOrderEvent>;\n\ninterface PrepSwiftOrderParams {\n\t/** The Drift client instance */\n\tdriftClient: DriftClient;\n\t/** The taker user account information */\n\ttakerUserAccount: {\n\t\t/** Public key of the user account */\n\t\tpubKey: PublicKey;\n\t\t/** User account ID */\n\t\tsubAccountId: number;\n\t};\n\t/** Current blockchain slot number */\n\tcurrentSlot: number;\n\t/** Whether this is a delegate order */\n\tisDelegate: boolean;\n\t/** Order parameters including main order and optional stop loss/take profit */\n\torderParams: {\n\t\t/** Main order parameters */\n\t\tmain: OptionalOrderParams;\n\t\t/** Optional stop loss order parameters */\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t\t/** Optional take profit order parameters */\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\t/** Optional max leverage for the position */\n\t\tpositionMaxLeverage?: number;\n\t};\n\t/**\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} => {\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\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\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};\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\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};\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 currentSlot = await driftClient.connection.getSlot('confirmed');\n\n\tconst {\n\t\thexEncodedSwiftOrderMessage,\n\t\tsignedMsgOrderUuid,\n\t\tsignedMsgOrderParamsMessage,\n\t} = prepSwiftOrder({\n\t\tdriftClient,\n\t\ttakerUserAccount: {\n\t\t\tpubKey: userAccountPubKey,\n\t\t\tsubAccountId: subAccountId,\n\t\t},\n\t\tcurrentSlot,\n\t\tisDelegate: swiftOptions.isDelegate || false,\n\t\torderParams,\n\t\tuserSigningSlotBuffer,\n\t\tbuilderParams,\n\t});\n\n\tswiftOptions.callbacks?.onOrderParamsMessagePrepped?.(\n\t\tsignedMsgOrderParamsMessage\n\t);\n\n\t// both market and non-market orders can have auction durations.\n\t//\n\t// for market orders, the auction duration + user signing slot buffer is a good gauge for slots until auction end\n\t//\n\t// for non-market orders, if they have an auction duration, we use the maximum of MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS\n\t// and the (auction duration + user signing slot buffer). This is because limit auctions can have very small auction durations,\n\t// but the limit order is still valid to be placed even after the auction ends, hence we enforce a minimum duration so that\n\t// short limit auction durations can still be placed\n\tconst isMarketOrder =\n\t\tENUM_UTILS.match(orderParams.main.orderType, OrderType.ORACLE) ||\n\t\tENUM_UTILS.match(orderParams.main.orderType, OrderType.MARKET);\n\tconst slotsTillAuctionEnd = orderParams.main.auctionDuration\n\t\t? isMarketOrder\n\t\t\t? userSigningSlotBuffer + orderParams.main.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 + orderParams.main.auctionDuration\n\t\t\t )\n\t\t: MINIMUM_SWIFT_NON_AUCTION_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS;\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\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
|
import { DriftClient, User } from '@drift-labs/sdk';
|
|
2
|
-
import { TransactionInstruction } from '@solana/web3.js';
|
|
2
|
+
import { PublicKey, TransactionInstruction } from '@solana/web3.js';
|
|
3
3
|
/**
|
|
4
4
|
* Helper function to determine if leverage needs updating and create the instruction if needed.
|
|
5
5
|
* Returns the instruction to update position max leverage, or undefined if no update is needed.
|
|
6
6
|
*/
|
|
7
|
-
export declare function getPositionMaxLeverageIxIfNeeded(driftClient: DriftClient, user: User, marketIndex: number, positionMaxLeverage?: number): Promise<TransactionInstruction | undefined>;
|
|
7
|
+
export declare function getPositionMaxLeverageIxIfNeeded(driftClient: DriftClient, user: User, marketIndex: number, positionMaxLeverage?: number, signingAuthority?: PublicKey): Promise<TransactionInstruction | undefined>;
|
|
@@ -6,7 +6,7 @@ const trading_1 = require("../../../../../common-ui-utils/trading");
|
|
|
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.
|
|
8
8
|
*/
|
|
9
|
-
async function getPositionMaxLeverageIxIfNeeded(driftClient, user, marketIndex, positionMaxLeverage) {
|
|
9
|
+
async function getPositionMaxLeverageIxIfNeeded(driftClient, user, marketIndex, positionMaxLeverage, signingAuthority) {
|
|
10
10
|
if (!positionMaxLeverage) {
|
|
11
11
|
return undefined;
|
|
12
12
|
}
|
|
@@ -21,7 +21,11 @@ async function getPositionMaxLeverageIxIfNeeded(driftClient, user, marketIndex,
|
|
|
21
21
|
// 1. We have a target leverage to set, AND
|
|
22
22
|
// 2. Either there's no position yet (currentMarginRatio === 0) OR the margin ratios differ
|
|
23
23
|
if (targetMarginRatio && targetMarginRatio !== currentMarginRatio) {
|
|
24
|
-
return await driftClient.getUpdateUserPerpPositionCustomMarginRatioIx(marketIndex, targetMarginRatio, userAccount.subAccountId
|
|
24
|
+
return await driftClient.getUpdateUserPerpPositionCustomMarginRatioIx(marketIndex, targetMarginRatio, userAccount.subAccountId, {
|
|
25
|
+
userAccountPublicKey: user.getUserAccountPublicKey(),
|
|
26
|
+
authority: userAccount.authority,
|
|
27
|
+
signingAuthority,
|
|
28
|
+
});
|
|
25
29
|
}
|
|
26
30
|
return undefined;
|
|
27
31
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"positionMaxLeverage.js","sourceRoot":"","sources":["../../../../../../src/drift/base/actions/trade/openPerpOrder/positionMaxLeverage.ts"],"names":[],"mappings":";;;AAEA,oEAAuE;AAEvE;;;GAGG;AACI,KAAK,UAAU,gCAAgC,CACrD,WAAwB,EACxB,IAAU,EACV,WAAmB,EACnB,mBAA4B;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,uBAAa,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,
|
|
1
|
+
{"version":3,"file":"positionMaxLeverage.js","sourceRoot":"","sources":["../../../../../../src/drift/base/actions/trade/openPerpOrder/positionMaxLeverage.ts"],"names":[],"mappings":";;;AAEA,oEAAuE;AAEvE;;;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,uBAAa,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 '../../../../../common-ui-utils/trading';\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"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { BN, MarketType, PositionDirection, PostOnlyParams, ReferrerInfo } from '@drift-labs/sdk';
|
|
2
2
|
import { Transaction, VersionedTransaction } from '@solana/web3.js';
|
|
3
3
|
import { OptionalAuctionParamsRequestInputs } from './dlobServer';
|
|
4
|
+
import { AuctionParamsFetchedCallback } from '../../../../utils/auctionParamsResponseMapper';
|
|
4
5
|
export type TxnOrSwiftResult<T extends boolean> = T extends true ? void : Transaction | VersionedTransaction;
|
|
5
6
|
export type PlaceAndTakeParams = {
|
|
6
7
|
enable: false;
|
|
@@ -21,6 +22,7 @@ export interface LimitAuctionConfig {
|
|
|
21
22
|
referrerInfo?: ReferrerInfo;
|
|
22
23
|
auctionDurationPercentage?: number;
|
|
23
24
|
};
|
|
25
|
+
onAuctionParamsFetched?: AuctionParamsFetchedCallback;
|
|
24
26
|
}
|
|
25
27
|
export interface OptionalTriggerOrderParams {
|
|
26
28
|
baseAssetAmount?: BN;
|
|
@@ -51,12 +53,12 @@ export interface NonMarketOrderParamsConfig {
|
|
|
51
53
|
postOnly?: PostOnlyParams;
|
|
52
54
|
userOrderId?: number;
|
|
53
55
|
/**
|
|
54
|
-
*
|
|
55
|
-
* If
|
|
56
|
+
* The leverage to be used for this position.
|
|
57
|
+
* If different from current position's leverage, will add an instruction
|
|
56
58
|
* to update the position's maxMarginRatio before placing the order.
|
|
57
59
|
* Example: 5 for 5x leverage, 10 for 10x leverage
|
|
58
60
|
*/
|
|
59
|
-
positionMaxLeverage
|
|
61
|
+
positionMaxLeverage: number;
|
|
60
62
|
orderConfig: LimitOrderParamsOrderConfig | {
|
|
61
63
|
orderType: Extract<NonMarketOrderType, 'takeProfit' | 'stopLoss'>;
|
|
62
64
|
triggerPrice: BN;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../src/drift/base/actions/trade/openPerpOrder/types.ts"],"names":[],"mappings":"","sourcesContent":["import {\n\tBN,\n\tMarketType,\n\tPositionDirection,\n\tPostOnlyParams,\n\tReferrerInfo,\n} from '@drift-labs/sdk';\nimport { Transaction, VersionedTransaction } from '@solana/web3.js';\nimport { OptionalAuctionParamsRequestInputs } from './dlobServer';\n\nexport type TxnOrSwiftResult<T extends boolean> = T extends true\n\t? void\n\t: Transaction | VersionedTransaction;\n\nexport type PlaceAndTakeParams =\n\t| {\n\t\t\tenable: false;\n\t }\n\t| {\n\t\t\tenable: true;\n\t\t\tauctionDurationPercentage?: number;\n\t\t\treferrerInfo: ReferrerInfo | undefined;\n\t };\n\nexport type NonMarketOrderType =\n\t| 'limit'\n\t| 'takeProfit'\n\t| 'stopLoss'\n\t| 'oracleLimit';\n\nexport interface LimitAuctionConfig {\n\tenable: boolean;\n\tdlobServerHttpUrl: string;\n\tauctionStartPriceOffset: number;\n\toraclePrice?: BN; // used to calculate oracle price bands\n\toptionalLimitAuctionParams?: OptionalAuctionParamsRequestInputs;\n\tusePlaceAndTake?: {\n\t\tenable: boolean;\n\t\treferrerInfo?: ReferrerInfo; // needed for place and take fallback\n\t\tauctionDurationPercentage?: number;\n\t};\n}\n\nexport interface OptionalTriggerOrderParams {\n\tbaseAssetAmount?: BN;\n\ttriggerPrice: BN;\n\tlimitPrice?: BN;\n\treduceOnly?: boolean;\n}\n\nexport interface LimitOrderParamsOrderConfig {\n\torderType: Extract<NonMarketOrderType, 'limit'>;\n\tlimitPrice: BN;\n\tbracketOrders?: {\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t};\n\t/**\n\t * Limit orders can have an optional auction that allows it to go through the auction process.\n\t * Usually, the auction params are set up to the limit price, to allow for a possible improved\n\t * fill price. This is useful for when a limit order is crossing the orderbook.\n\t */\n\tlimitAuction?: LimitAuctionConfig;\n}\n\nexport interface NonMarketOrderParamsConfig {\n\tmarketIndex: number;\n\tmarketType: MarketType;\n\tdirection: PositionDirection;\n\tbaseAssetAmount: BN;\n\treduceOnly?: boolean;\n\tpostOnly?: PostOnlyParams;\n\tuserOrderId?: number;\n\t/**\n\t *
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../src/drift/base/actions/trade/openPerpOrder/types.ts"],"names":[],"mappings":"","sourcesContent":["import {\n\tBN,\n\tMarketType,\n\tPositionDirection,\n\tPostOnlyParams,\n\tReferrerInfo,\n} from '@drift-labs/sdk';\nimport { Transaction, VersionedTransaction } from '@solana/web3.js';\nimport { OptionalAuctionParamsRequestInputs } from './dlobServer';\nimport { AuctionParamsFetchedCallback } from '../../../../utils/auctionParamsResponseMapper';\n\nexport type TxnOrSwiftResult<T extends boolean> = T extends true\n\t? void\n\t: Transaction | VersionedTransaction;\n\nexport type PlaceAndTakeParams =\n\t| {\n\t\t\tenable: false;\n\t }\n\t| {\n\t\t\tenable: true;\n\t\t\tauctionDurationPercentage?: number;\n\t\t\treferrerInfo: ReferrerInfo | undefined;\n\t };\n\nexport type NonMarketOrderType =\n\t| 'limit'\n\t| 'takeProfit'\n\t| 'stopLoss'\n\t| 'oracleLimit';\n\nexport interface LimitAuctionConfig {\n\tenable: boolean;\n\tdlobServerHttpUrl: string;\n\tauctionStartPriceOffset: number;\n\toraclePrice?: BN; // used to calculate oracle price bands\n\toptionalLimitAuctionParams?: OptionalAuctionParamsRequestInputs;\n\tusePlaceAndTake?: {\n\t\tenable: boolean;\n\t\treferrerInfo?: ReferrerInfo; // needed for place and take fallback\n\t\tauctionDurationPercentage?: number;\n\t};\n\tonAuctionParamsFetched?: AuctionParamsFetchedCallback;\n}\n\nexport interface OptionalTriggerOrderParams {\n\tbaseAssetAmount?: BN;\n\ttriggerPrice: BN;\n\tlimitPrice?: BN;\n\treduceOnly?: boolean;\n}\n\nexport interface LimitOrderParamsOrderConfig {\n\torderType: Extract<NonMarketOrderType, 'limit'>;\n\tlimitPrice: BN;\n\tbracketOrders?: {\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t};\n\t/**\n\t * Limit orders can have an optional auction that allows it to go through the auction process.\n\t * Usually, the auction params are set up to the limit price, to allow for a possible improved\n\t * fill price. This is useful for when a limit order is crossing the orderbook.\n\t */\n\tlimitAuction?: LimitAuctionConfig;\n}\n\nexport interface NonMarketOrderParamsConfig {\n\tmarketIndex: number;\n\tmarketType: MarketType;\n\tdirection: PositionDirection;\n\tbaseAssetAmount: BN;\n\treduceOnly?: boolean;\n\tpostOnly?: PostOnlyParams;\n\tuserOrderId?: number;\n\t/**\n\t * The leverage to be used for this position.\n\t * If different from current position's leverage, will add an instruction\n\t * to update the position's maxMarginRatio before placing the order.\n\t * Example: 5 for 5x leverage, 10 for 10x leverage\n\t */\n\tpositionMaxLeverage: number;\n\torderConfig:\n\t\t| LimitOrderParamsOrderConfig\n\t\t| {\n\t\t\t\torderType: Extract<NonMarketOrderType, 'takeProfit' | 'stopLoss'>;\n\t\t\t\ttriggerPrice: BN;\n\t\t\t\tlimitPrice?: BN;\n\t\t }\n\t\t| {\n\t\t\t\torderType: Extract<NonMarketOrderType, 'oracleLimit'>;\n\t\t\t\toraclePriceOffset: BN;\n\t\t };\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { BN, DriftClient,
|
|
1
|
+
import { BN, DriftClient, TxParams, UnifiedQuoteResponse, UnifiedSwapClient, User } from '@drift-labs/sdk';
|
|
2
2
|
import { AddressLookupTableAccount, Transaction, TransactionInstruction, VersionedTransaction } from '@solana/web3.js';
|
|
3
3
|
/**
|
|
4
4
|
* Parameters for creating swap instruction details
|
|
@@ -7,14 +7,9 @@ interface CreateSwapIxDetailsParams {
|
|
|
7
7
|
/** The Drift client instance for interacting with the Drift protocol */
|
|
8
8
|
driftClient: DriftClient;
|
|
9
9
|
/** Quote response from swap provider containing swap route information */
|
|
10
|
-
quote:
|
|
11
|
-
/** Swap client instance for performing the swap
|
|
12
|
-
swapClient?: UnifiedSwapClient
|
|
13
|
-
/**
|
|
14
|
-
* @deprecated Use swapClient instead. This parameter is kept for backwards compatibility.
|
|
15
|
-
* Swap client instance for performing the swap
|
|
16
|
-
*/
|
|
17
|
-
jupiterClient?: JupiterClient;
|
|
10
|
+
quote: UnifiedQuoteResponse;
|
|
11
|
+
/** Swap client instance for performing the swap */
|
|
12
|
+
swapClient?: UnifiedSwapClient;
|
|
18
13
|
/** Market index of the token being swapped from */
|
|
19
14
|
swapFromMarketIndex: number;
|
|
20
15
|
/** Market index of the token being swapped to */
|
|
@@ -29,7 +24,6 @@ interface CreateSwapIxDetailsParams {
|
|
|
29
24
|
*
|
|
30
25
|
* @param driftClient - The Drift client instance
|
|
31
26
|
* @param swapClient - The swap client instance for performing the swap (supports UnifiedSwapClient or JupiterClient)
|
|
32
|
-
* @param jupiterClient - @deprecated Use swapClient instead. Kept for backwards compatibility.
|
|
33
27
|
* @param quote - Quote response from swap provider with routing information
|
|
34
28
|
* @param swapFromMarketIndex - Source token market index
|
|
35
29
|
* @param swapToMarketIndex - Destination token market index
|
|
@@ -39,7 +33,7 @@ interface CreateSwapIxDetailsParams {
|
|
|
39
33
|
* @returns ixs - Array of Solana transaction instructions for the swap
|
|
40
34
|
* @returns lookupTables - Address lookup table accounts for transaction compression
|
|
41
35
|
*/
|
|
42
|
-
export declare const createSwapIxDetails: ({ driftClient, swapClient,
|
|
36
|
+
export declare const createSwapIxDetails: ({ driftClient, swapClient, quote, swapFromMarketIndex, swapToMarketIndex, amount, user, }: CreateSwapIxDetailsParams) => Promise<{
|
|
43
37
|
ixs: TransactionInstruction[];
|
|
44
38
|
lookupTables: AddressLookupTableAccount[];
|
|
45
39
|
}>;
|
|
@@ -56,7 +50,6 @@ interface CreateSwapTxnParams extends CreateSwapIxDetailsParams {
|
|
|
56
50
|
*
|
|
57
51
|
* @param driftClient - The Drift client instance
|
|
58
52
|
* @param swapClient - The swap client instance for performing the swap (supports UnifiedSwapClient or JupiterClient)
|
|
59
|
-
* @param jupiterClient - @deprecated Use swapClient instead. Kept for backwards compatibility.
|
|
60
53
|
* @param quote - Quote response from swap provider with routing information
|
|
61
54
|
* @param swapFromMarketIndex - Source token market index
|
|
62
55
|
* @param swapToMarketIndex - Destination token market index
|
|
@@ -65,5 +58,5 @@ interface CreateSwapTxnParams extends CreateSwapIxDetailsParams {
|
|
|
65
58
|
* @param txParams - Transaction parameters for fees and compute units
|
|
66
59
|
* @returns Promise resolving to either a legacy Transaction or VersionedTransaction ready for signing
|
|
67
60
|
*/
|
|
68
|
-
export declare const createSwapTxn: ({ driftClient, swapClient,
|
|
61
|
+
export declare const createSwapTxn: ({ driftClient, swapClient, quote, swapFromMarketIndex, swapToMarketIndex, amount, user, txParams, }: CreateSwapTxnParams) => Promise<Transaction | VersionedTransaction>;
|
|
69
62
|
export {};
|
|
@@ -1,13 +1,11 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.createSwapTxn = exports.createSwapIxDetails = void 0;
|
|
4
|
-
const sdk_1 = require("@drift-labs/sdk");
|
|
5
4
|
/**
|
|
6
5
|
* Creates swap instruction details for a swap through Drift
|
|
7
6
|
*
|
|
8
7
|
* @param driftClient - The Drift client instance
|
|
9
8
|
* @param swapClient - The swap client instance for performing the swap (supports UnifiedSwapClient or JupiterClient)
|
|
10
|
-
* @param jupiterClient - @deprecated Use swapClient instead. Kept for backwards compatibility.
|
|
11
9
|
* @param quote - Quote response from swap provider with routing information
|
|
12
10
|
* @param swapFromMarketIndex - Source token market index
|
|
13
11
|
* @param swapToMarketIndex - Destination token market index
|
|
@@ -17,37 +15,16 @@ const sdk_1 = require("@drift-labs/sdk");
|
|
|
17
15
|
* @returns ixs - Array of Solana transaction instructions for the swap
|
|
18
16
|
* @returns lookupTables - Address lookup table accounts for transaction compression
|
|
19
17
|
*/
|
|
20
|
-
const createSwapIxDetails = async ({ driftClient, swapClient,
|
|
21
|
-
|
|
22
|
-
const
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
swapIxsDetails = await driftClient.getSwapIxV2({
|
|
31
|
-
swapClient: clientToUse,
|
|
32
|
-
outMarketIndex: swapToMarketIndex,
|
|
33
|
-
inMarketIndex: swapFromMarketIndex,
|
|
34
|
-
amount,
|
|
35
|
-
quote,
|
|
36
|
-
});
|
|
37
|
-
}
|
|
38
|
-
else {
|
|
39
|
-
// JupiterClient path
|
|
40
|
-
swapIxsDetails = await driftClient.getJupiterSwapIxV6({
|
|
41
|
-
jupiterClient: clientToUse,
|
|
42
|
-
outMarketIndex: swapToMarketIndex,
|
|
43
|
-
inMarketIndex: swapFromMarketIndex,
|
|
44
|
-
amount,
|
|
45
|
-
quote,
|
|
46
|
-
userAccountPublicKey: userPublicKey,
|
|
47
|
-
// we skip passing in the associated token accounts and have the swap client derive them instead.
|
|
48
|
-
// The swap client will also add the ixs to create the associated token accounts if they don't exist.
|
|
49
|
-
});
|
|
50
|
-
}
|
|
18
|
+
const createSwapIxDetails = async ({ driftClient, swapClient, quote, swapFromMarketIndex, swapToMarketIndex, amount, user, }) => {
|
|
19
|
+
const userPublicKey = user.userAccountPublicKey;
|
|
20
|
+
const swapIxsDetails = await driftClient.getSwapIxV2({
|
|
21
|
+
swapClient,
|
|
22
|
+
outMarketIndex: swapToMarketIndex,
|
|
23
|
+
inMarketIndex: swapFromMarketIndex,
|
|
24
|
+
amount,
|
|
25
|
+
quote,
|
|
26
|
+
userAccountPublicKey: userPublicKey,
|
|
27
|
+
});
|
|
51
28
|
return swapIxsDetails;
|
|
52
29
|
};
|
|
53
30
|
exports.createSwapIxDetails = createSwapIxDetails;
|
|
@@ -56,7 +33,6 @@ exports.createSwapIxDetails = createSwapIxDetails;
|
|
|
56
33
|
*
|
|
57
34
|
* @param driftClient - The Drift client instance
|
|
58
35
|
* @param swapClient - The swap client instance for performing the swap (supports UnifiedSwapClient or JupiterClient)
|
|
59
|
-
* @param jupiterClient - @deprecated Use swapClient instead. Kept for backwards compatibility.
|
|
60
36
|
* @param quote - Quote response from swap provider with routing information
|
|
61
37
|
* @param swapFromMarketIndex - Source token market index
|
|
62
38
|
* @param swapToMarketIndex - Destination token market index
|
|
@@ -65,11 +41,10 @@ exports.createSwapIxDetails = createSwapIxDetails;
|
|
|
65
41
|
* @param txParams - Transaction parameters for fees and compute units
|
|
66
42
|
* @returns Promise resolving to either a legacy Transaction or VersionedTransaction ready for signing
|
|
67
43
|
*/
|
|
68
|
-
const createSwapTxn = async ({ driftClient, swapClient,
|
|
44
|
+
const createSwapTxn = async ({ driftClient, swapClient, quote, swapFromMarketIndex, swapToMarketIndex, amount, user, txParams, }) => {
|
|
69
45
|
const swapIxsDetails = await (0, exports.createSwapIxDetails)({
|
|
70
46
|
driftClient,
|
|
71
47
|
swapClient,
|
|
72
|
-
jupiterClient,
|
|
73
48
|
quote,
|
|
74
49
|
swapFromMarketIndex,
|
|
75
50
|
swapToMarketIndex,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"swap.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/trade/swap.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"swap.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/trade/swap.ts"],"names":[],"mappings":";;;AAmCA;;;;;;;;;;;;;GAaG;AACI,MAAM,mBAAmB,GAAG,KAAK,EAAE,EACzC,WAAW,EACX,UAAU,EACV,KAAK,EACL,mBAAmB,EACnB,iBAAiB,EACjB,MAAM,EACN,IAAI,GACuB,EAGzB,EAAE;IACJ,MAAM,aAAa,GAAG,IAAI,CAAC,oBAAoB,CAAC;IAEhD,MAAM,cAAc,GAAG,MAAM,WAAW,CAAC,WAAW,CAAC;QACpD,UAAU;QACV,cAAc,EAAE,iBAAiB;QACjC,aAAa,EAAE,mBAAmB;QAClC,MAAM;QACN,KAAK;QACL,oBAAoB,EAAE,aAAa;KACnC,CAAC,CAAC;IAEH,OAAO,cAAc,CAAC;AACvB,CAAC,CAAC;AAxBW,QAAA,mBAAmB,uBAwB9B;AAWF;;;;;;;;;;;;GAYG;AACI,MAAM,aAAa,GAAG,KAAK,EAAE,EACnC,WAAW,EACX,UAAU,EACV,KAAK,EACL,mBAAmB,EACnB,iBAAiB,EACjB,MAAM,EACN,IAAI,EACJ,QAAQ,GACa,EAA+C,EAAE;IACtE,MAAM,cAAc,GAAG,MAAM,IAAA,2BAAmB,EAAC;QAChD,WAAW;QACX,UAAU;QACV,KAAK;QACL,mBAAmB;QACnB,iBAAiB;QACjB,MAAM;QACN,IAAI;KACJ,CAAC,CAAC;IAEH,MAAM,EAAE,GAAG,MAAM,WAAW,CAAC,gBAAgB,CAC5C,cAAc,CAAC,GAAG,EAClB,QAAQ,EACR,CAAC,EACD,cAAc,CAAC,YAAY,CAC3B,CAAC;IAEF,OAAO,EAAE,CAAC;AACX,CAAC,CAAC;AA5BW,QAAA,aAAa,iBA4BxB","sourcesContent":["import {\n\tBN,\n\tDriftClient,\n\tTxParams,\n\tUnifiedQuoteResponse,\n\tUnifiedSwapClient,\n\tUser,\n} from '@drift-labs/sdk';\nimport {\n\tAddressLookupTableAccount,\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\n\n/**\n * Parameters for creating swap instruction details\n */\ninterface CreateSwapIxDetailsParams {\n\t/** The Drift client instance for interacting with the Drift protocol */\n\tdriftClient: DriftClient;\n\t/** Quote response from swap provider containing swap route information */\n\tquote: UnifiedQuoteResponse;\n\t/** Swap client instance for performing the swap */\n\tswapClient?: UnifiedSwapClient;\n\t/** Market index of the token being swapped from */\n\tswapFromMarketIndex: number;\n\t/** Market index of the token being swapped to */\n\tswapToMarketIndex: number;\n\t/** Amount to swap in base units */\n\tamount: BN;\n\t/** User instance containing account information */\n\tuser: User;\n}\n\n/**\n * Creates swap instruction details for a swap through Drift\n *\n * @param driftClient - The Drift client instance\n * @param swapClient - The swap client instance for performing the swap (supports UnifiedSwapClient or JupiterClient)\n * @param quote - Quote response from swap provider with routing information\n * @param swapFromMarketIndex - Source token market index\n * @param swapToMarketIndex - Destination token market index\n * @param amount - Amount to swap in base units\n * @param user - User account instance\n * @returns Promise resolving to an object containing transaction instructions and lookup tables\n * @returns ixs - Array of Solana transaction instructions for the swap\n * @returns lookupTables - Address lookup table accounts for transaction compression\n */\nexport const createSwapIxDetails = async ({\n\tdriftClient,\n\tswapClient,\n\tquote,\n\tswapFromMarketIndex,\n\tswapToMarketIndex,\n\tamount,\n\tuser,\n}: CreateSwapIxDetailsParams): Promise<{\n\tixs: TransactionInstruction[];\n\tlookupTables: AddressLookupTableAccount[];\n}> => {\n\tconst userPublicKey = user.userAccountPublicKey;\n\n\tconst swapIxsDetails = await driftClient.getSwapIxV2({\n\t\tswapClient,\n\t\toutMarketIndex: swapToMarketIndex,\n\t\tinMarketIndex: swapFromMarketIndex,\n\t\tamount,\n\t\tquote,\n\t\tuserAccountPublicKey: userPublicKey,\n\t});\n\n\treturn swapIxsDetails;\n};\n\n/**\n * Parameters for creating a complete swap transaction\n * Extends CreateSwapIxDetailsParams with additional transaction parameters\n */\ninterface CreateSwapTxnParams extends CreateSwapIxDetailsParams {\n\t/** Transaction parameters including compute units, priority fees, and other options */\n\ttxParams?: TxParams;\n}\n\n/**\n * Creates a complete swap transaction ready for signing and submission\n *\n * @param driftClient - The Drift client instance\n * @param swapClient - The swap client instance for performing the swap (supports UnifiedSwapClient or JupiterClient)\n * @param quote - Quote response from swap provider with routing information\n * @param swapFromMarketIndex - Source token market index\n * @param swapToMarketIndex - Destination token market index\n * @param amount - Amount to swap in base units\n * @param user - User account instance\n * @param txParams - Transaction parameters for fees and compute units\n * @returns Promise resolving to either a legacy Transaction or VersionedTransaction ready for signing\n */\nexport const createSwapTxn = async ({\n\tdriftClient,\n\tswapClient,\n\tquote,\n\tswapFromMarketIndex,\n\tswapToMarketIndex,\n\tamount,\n\tuser,\n\ttxParams,\n}: CreateSwapTxnParams): Promise<Transaction | VersionedTransaction> => {\n\tconst swapIxsDetails = await createSwapIxDetails({\n\t\tdriftClient,\n\t\tswapClient,\n\t\tquote,\n\t\tswapFromMarketIndex,\n\t\tswapToMarketIndex,\n\t\tamount,\n\t\tuser,\n\t});\n\n\tconst tx = await driftClient.buildTransaction(\n\t\tswapIxsDetails.ixs,\n\t\ttxParams,\n\t\t0,\n\t\tswapIxsDetails.lookupTables\n\t);\n\n\treturn tx;\n};\n"]}
|
|
@@ -11,6 +11,7 @@ interface CreateUserAndDepositCollateralBaseIxsParams {
|
|
|
11
11
|
poolId?: number;
|
|
12
12
|
fromSubAccountId?: number;
|
|
13
13
|
customMaxMarginRatio?: number;
|
|
14
|
+
delegate?: PublicKey;
|
|
14
15
|
}
|
|
15
16
|
/**
|
|
16
17
|
* Creates transaction instructions for initializing a new user account and depositing collateral.
|
|
@@ -29,13 +30,14 @@ interface CreateUserAndDepositCollateralBaseIxsParams {
|
|
|
29
30
|
* @param poolId - The pool ID to associate the account with (defaults to MAIN_POOL_ID)
|
|
30
31
|
* @param fromSubAccountId - Optional sub-account ID to transfer funds from
|
|
31
32
|
* @param customMaxMarginRatio - Optional custom maximum margin ratio for the account
|
|
33
|
+
* @param delegate - Optional delegate public key for the account. Immediately assigns this as the delegate of the account.
|
|
32
34
|
*
|
|
33
35
|
* @returns Promise resolving to an object containing:
|
|
34
36
|
* - subAccountId: The ID of the newly created sub-account
|
|
35
37
|
* - userAccountPublicKey: The public key of the created user account
|
|
36
38
|
* - ixs: Array of transaction instructions to execute
|
|
37
39
|
*/
|
|
38
|
-
export declare const createUserAndDepositCollateralBaseIxs: ({ driftClient, amount, spotMarketConfig, authority, userStatsAccount, referrerName, accountName, poolId, fromSubAccountId, customMaxMarginRatio, }: CreateUserAndDepositCollateralBaseIxsParams) => Promise<{
|
|
40
|
+
export declare const createUserAndDepositCollateralBaseIxs: ({ driftClient, amount, spotMarketConfig, authority, userStatsAccount, referrerName, accountName, poolId, fromSubAccountId, customMaxMarginRatio, delegate, }: CreateUserAndDepositCollateralBaseIxsParams) => Promise<{
|
|
39
41
|
subAccountId: number;
|
|
40
42
|
userAccountPublicKey: PublicKey;
|
|
41
43
|
ixs: TransactionInstruction[];
|