@drift-labs/common 1.0.13 → 1.0.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/clients/DlobWebsocketClient.d.ts +82 -0
- package/lib/clients/DlobWebsocketClient.js +226 -0
- package/lib/clients/DlobWebsocketClient.js.map +1 -0
- package/lib/clients/swiftClient.js +1 -0
- package/lib/clients/swiftClient.js.map +1 -1
- package/lib/common-ui-utils/commonUiUtils.d.ts +22 -3
- package/lib/common-ui-utils/commonUiUtils.js +15 -8
- package/lib/common-ui-utils/commonUiUtils.js.map +1 -1
- package/lib/common-ui-utils/market.d.ts +5 -0
- package/lib/common-ui-utils/market.js +19 -11
- package/lib/common-ui-utils/market.js.map +1 -1
- package/lib/common-ui-utils/order.d.ts +8 -1
- package/lib/common-ui-utils/order.js +3 -2
- package/lib/common-ui-utils/order.js.map +1 -1
- package/lib/common-ui-utils/user.d.ts +5 -0
- package/lib/common-ui-utils/user.js +58 -3
- package/lib/common-ui-utils/user.js.map +1 -1
- package/lib/constants/markets.d.ts +4 -0
- package/lib/constants/markets.js +5 -1
- package/lib/constants/markets.js.map +1 -1
- package/lib/constants/superstake.js.map +1 -1
- package/lib/drift/Drift/clients/AuthorityDrift/DriftL2OrderbookManager.d.ts +1 -1
- package/lib/drift/Drift/clients/AuthorityDrift/DriftL2OrderbookManager.js.map +1 -1
- package/lib/drift/Drift/clients/AuthorityDrift/index.d.ts +1 -1
- package/lib/drift/Drift/clients/AuthorityDrift/index.js.map +1 -1
- package/lib/drift/Drift/clients/CentralServerDrift/index.d.ts +3 -2
- package/lib/drift/Drift/clients/CentralServerDrift/index.js +52 -49
- package/lib/drift/Drift/clients/CentralServerDrift/index.js.map +1 -1
- package/lib/drift/Drift/data/PollingDlob.d.ts +1 -1
- package/lib/drift/Drift/data/PollingDlob.js.map +1 -1
- package/lib/drift/base/actions/trade/editOrder.d.ts +3 -0
- package/lib/drift/base/actions/trade/editOrder.js.map +1 -1
- package/lib/drift/base/actions/trade/index.d.ts +1 -0
- package/lib/drift/base/actions/trade/index.js +1 -0
- package/lib/drift/base/actions/trade/index.js.map +1 -1
- package/lib/drift/base/actions/trade/margin.d.ts +24 -0
- package/lib/drift/base/actions/trade/margin.js +48 -0
- package/lib/drift/base/actions/trade/margin.js.map +1 -0
- package/lib/drift/base/actions/trade/openPerpOrder/auction.d.ts +3 -1
- package/lib/drift/base/actions/trade/openPerpOrder/auction.js +2 -2
- package/lib/drift/base/actions/trade/openPerpOrder/auction.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.d.ts +2 -6
- package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.d.ts +6 -3
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js +6 -6
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.d.ts +2 -0
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js +3 -2
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js +2 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/swap.d.ts +18 -11
- package/lib/drift/base/actions/trade/swap.js +40 -17
- package/lib/drift/base/actions/trade/swap.js.map +1 -1
- package/lib/index.d.ts +1 -0
- package/lib/index.js +1 -0
- package/lib/index.js.map +1 -1
- package/lib/utils/MultiplexWebSocket.d.ts +4 -2
- package/lib/utils/MultiplexWebSocket.js +18 -9
- package/lib/utils/MultiplexWebSocket.js.map +1 -1
- package/lib/utils/ResultSlotIncrementer.d.ts +31 -0
- package/lib/utils/ResultSlotIncrementer.js +83 -0
- package/lib/utils/ResultSlotIncrementer.js.map +1 -0
- package/lib/utils/index.d.ts +3 -1
- package/lib/utils/index.js +7 -1
- package/lib/utils/index.js.map +1 -1
- package/lib/utils/math.js +1 -1
- package/lib/utils/math.js.map +1 -1
- package/lib/utils/orderbook/constants.d.ts +2 -0
- package/lib/utils/orderbook/constants.js +5 -0
- package/lib/utils/orderbook/constants.js.map +1 -0
- package/lib/utils/orderbook/index.d.ts +38 -59
- package/lib/utils/orderbook/index.js +285 -1
- package/lib/utils/orderbook/index.js.map +1 -1
- package/lib/utils/orderbook/types.d.ts +101 -0
- package/lib/utils/orderbook/types.js +9 -0
- package/lib/utils/orderbook/types.js.map +1 -0
- package/lib/utils/signedMsgs.d.ts +1 -0
- package/lib/utils/signedMsgs.js +10 -0
- package/lib/utils/signedMsgs.js.map +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { MarketId, deserializeL2Response, OrderbookGrouping, DlobServerChannel } from '..';
|
|
2
|
+
import { Observable } from 'rxjs';
|
|
3
|
+
import { ResultSlotIncrementer } from '../utils/ResultSlotIncrementer';
|
|
4
|
+
import { RawL2Output } from '../utils/orderbook/types';
|
|
5
|
+
export type OrderbookChannelTypes = Extract<DlobServerChannel, 'orderbook' | 'orderbook_indicative'>;
|
|
6
|
+
export interface DlobWebsocketClientConfig {
|
|
7
|
+
websocketUrl: string;
|
|
8
|
+
enableIndicativeOrderbook?: boolean;
|
|
9
|
+
resultSlotIncrementer?: ResultSlotIncrementer;
|
|
10
|
+
onFallback?: (marketId: MarketId) => void;
|
|
11
|
+
}
|
|
12
|
+
export interface MarketSubscription {
|
|
13
|
+
marketId: MarketId;
|
|
14
|
+
channel: OrderbookChannelTypes;
|
|
15
|
+
grouping?: OrderbookGrouping;
|
|
16
|
+
}
|
|
17
|
+
export interface ProcessedMarketData {
|
|
18
|
+
marketId: MarketId;
|
|
19
|
+
rawData: RawL2Output;
|
|
20
|
+
deserializedData: ReturnType<typeof deserializeL2Response>;
|
|
21
|
+
slot: number;
|
|
22
|
+
}
|
|
23
|
+
export declare class DlobWebsocketClient {
|
|
24
|
+
private config;
|
|
25
|
+
private subscriptions;
|
|
26
|
+
private resultIncrementer;
|
|
27
|
+
private destroy$;
|
|
28
|
+
private marketSubscriptions$;
|
|
29
|
+
private rawMessages$;
|
|
30
|
+
constructor(config: DlobWebsocketClientConfig);
|
|
31
|
+
/**
|
|
32
|
+
* Get an observable stream of processed market data for specific markets
|
|
33
|
+
*/
|
|
34
|
+
getMarketDataStream(marketIds: MarketId[]): Observable<ProcessedMarketData>;
|
|
35
|
+
/**
|
|
36
|
+
* Subscribe to market data for given markets
|
|
37
|
+
*/
|
|
38
|
+
subscribeToMarkets(markets: {
|
|
39
|
+
marketId: MarketId;
|
|
40
|
+
grouping?: OrderbookGrouping;
|
|
41
|
+
}[]): void;
|
|
42
|
+
/**
|
|
43
|
+
* Unsubscribe from all markets
|
|
44
|
+
*/
|
|
45
|
+
unsubscribeAll(): void;
|
|
46
|
+
/**
|
|
47
|
+
* Handle tab return to prevent "speed run" through queued messages
|
|
48
|
+
*/
|
|
49
|
+
handleTabReturn(): void;
|
|
50
|
+
/**
|
|
51
|
+
* Reset slot tracking for clean state on reconnection
|
|
52
|
+
*/
|
|
53
|
+
resetSlotTracking(): void;
|
|
54
|
+
/**
|
|
55
|
+
* Destroy the client and clean up all subscriptions
|
|
56
|
+
*/
|
|
57
|
+
destroy(): void;
|
|
58
|
+
/**
|
|
59
|
+
* Sets up the subscription management pipeline that handles market data subscriptions.
|
|
60
|
+
* This pipeline:
|
|
61
|
+
* 1. Watches for changes in market subscriptions
|
|
62
|
+
* 2. Only processes changes when the subscription list actually changes
|
|
63
|
+
* 3. Manages the lifecycle of websocket subscriptions
|
|
64
|
+
* 4. Cleans up when the client is destroyed
|
|
65
|
+
*/
|
|
66
|
+
private setupSubscriptionManagement;
|
|
67
|
+
/**
|
|
68
|
+
* Manages the lifecycle of websocket subscriptions by:
|
|
69
|
+
* 1. Comparing current subscriptions with new subscriptions
|
|
70
|
+
* 2. Unsubscribing from any subscriptions that are no longer needed
|
|
71
|
+
* 3. Creating new subscriptions for markets that weren't previously subscribed
|
|
72
|
+
*
|
|
73
|
+
* @param newSubscriptions - The new set of market subscriptions to maintain
|
|
74
|
+
* @returns An empty observable since this is a side-effect operation
|
|
75
|
+
*/
|
|
76
|
+
private manageNewSubscriptions;
|
|
77
|
+
private createSubscription;
|
|
78
|
+
private processRawMessage;
|
|
79
|
+
private tryParse;
|
|
80
|
+
private getSubscriptionKey;
|
|
81
|
+
}
|
|
82
|
+
export default DlobWebsocketClient;
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
"use strict";
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.DlobWebsocketClient = void 0;
|
|
5
|
+
const __1 = require("..");
|
|
6
|
+
const rxjs_1 = require("rxjs");
|
|
7
|
+
const operators_1 = require("rxjs/operators");
|
|
8
|
+
const ResultSlotIncrementer_1 = require("../utils/ResultSlotIncrementer");
|
|
9
|
+
const MultiplexWebSocket_1 = require("../utils/MultiplexWebSocket");
|
|
10
|
+
class DlobWebsocketClient {
|
|
11
|
+
constructor(config) {
|
|
12
|
+
this.subscriptions = new Map();
|
|
13
|
+
this.destroy$ = new rxjs_1.Subject();
|
|
14
|
+
// Subjects for reactive streams
|
|
15
|
+
this.marketSubscriptions$ = new rxjs_1.BehaviorSubject([]);
|
|
16
|
+
this.rawMessages$ = new rxjs_1.Subject();
|
|
17
|
+
this.config = config;
|
|
18
|
+
this.resultIncrementer =
|
|
19
|
+
config.resultSlotIncrementer || new ResultSlotIncrementer_1.ResultSlotIncrementer();
|
|
20
|
+
this.setupSubscriptionManagement();
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Get an observable stream of processed market data for specific markets
|
|
24
|
+
*/
|
|
25
|
+
getMarketDataStream(marketIds) {
|
|
26
|
+
return this.rawMessages$.pipe((0, operators_1.filter)(({ marketId }) => marketIds.some((id) => id.key === marketId.key)), (0, operators_1.map)(({ marketId, channel, data }) => this.processRawMessage(marketId, channel, data)), (0, operators_1.filter)((result) => result !== null), (0, operators_1.catchError)((error) => {
|
|
27
|
+
console.error('Caught error in getMarketDataStream', error);
|
|
28
|
+
return rxjs_1.EMPTY;
|
|
29
|
+
}), (0, operators_1.takeUntil)(this.destroy$), (0, operators_1.share)());
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Subscribe to market data for given markets
|
|
33
|
+
*/
|
|
34
|
+
subscribeToMarkets(markets) {
|
|
35
|
+
const subscriptions = markets.map(({ marketId, grouping }) => ({
|
|
36
|
+
marketId,
|
|
37
|
+
channel: this.config.enableIndicativeOrderbook
|
|
38
|
+
? 'orderbook_indicative'
|
|
39
|
+
: 'orderbook',
|
|
40
|
+
grouping,
|
|
41
|
+
}));
|
|
42
|
+
this.marketSubscriptions$.next(subscriptions);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Unsubscribe from all markets
|
|
46
|
+
*/
|
|
47
|
+
unsubscribeAll() {
|
|
48
|
+
this.marketSubscriptions$.next([]);
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Handle tab return to prevent "speed run" through queued messages
|
|
52
|
+
*/
|
|
53
|
+
handleTabReturn() {
|
|
54
|
+
this.resultIncrementer.handleTabReturn();
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Reset slot tracking for clean state on reconnection
|
|
58
|
+
*/
|
|
59
|
+
resetSlotTracking() {
|
|
60
|
+
// Get all current subscription keys and reset their slot tracking
|
|
61
|
+
for (const subscriptionKey of this.subscriptions.keys()) {
|
|
62
|
+
// Extract marketId and channel from subscription key
|
|
63
|
+
const [marketKey, channel] = subscriptionKey.split('_');
|
|
64
|
+
const resultKey = `${channel}_${marketKey}`;
|
|
65
|
+
this.resultIncrementer.resetKey(resultKey);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Destroy the client and clean up all subscriptions
|
|
70
|
+
*/
|
|
71
|
+
destroy() {
|
|
72
|
+
this.destroy$.next();
|
|
73
|
+
this.destroy$.complete();
|
|
74
|
+
this.subscriptions.forEach(({ unsubscribe }) => unsubscribe());
|
|
75
|
+
this.subscriptions.clear();
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Sets up the subscription management pipeline that handles market data subscriptions.
|
|
79
|
+
* This pipeline:
|
|
80
|
+
* 1. Watches for changes in market subscriptions
|
|
81
|
+
* 2. Only processes changes when the subscription list actually changes
|
|
82
|
+
* 3. Manages the lifecycle of websocket subscriptions
|
|
83
|
+
* 4. Cleans up when the client is destroyed
|
|
84
|
+
*/
|
|
85
|
+
setupSubscriptionManagement() {
|
|
86
|
+
this.marketSubscriptions$
|
|
87
|
+
.pipe(
|
|
88
|
+
// Only emit when the subscription list actually changes
|
|
89
|
+
// Uses JSON.stringify for deep comparison of subscription arrays
|
|
90
|
+
(0, operators_1.distinctUntilChanged)((prev, curr) => JSON.stringify(prev) === JSON.stringify(curr)),
|
|
91
|
+
// Switch to managing the new set of subscriptions
|
|
92
|
+
// This will cancel any previous subscription management
|
|
93
|
+
(0, operators_1.switchMap)((subscriptions) => this.manageNewSubscriptions(subscriptions)),
|
|
94
|
+
// Clean up when the client is destroyed
|
|
95
|
+
(0, operators_1.takeUntil)(this.destroy$))
|
|
96
|
+
.subscribe();
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Manages the lifecycle of websocket subscriptions by:
|
|
100
|
+
* 1. Comparing current subscriptions with new subscriptions
|
|
101
|
+
* 2. Unsubscribing from any subscriptions that are no longer needed
|
|
102
|
+
* 3. Creating new subscriptions for markets that weren't previously subscribed
|
|
103
|
+
*
|
|
104
|
+
* @param newSubscriptions - The new set of market subscriptions to maintain
|
|
105
|
+
* @returns An empty observable since this is a side-effect operation
|
|
106
|
+
*/
|
|
107
|
+
manageNewSubscriptions(newSubscriptions) {
|
|
108
|
+
// Get sets of subscription keys for efficient comparison
|
|
109
|
+
const currentKeys = new Set(this.subscriptions.keys());
|
|
110
|
+
const newKeys = new Set(newSubscriptions.map((sub) => this.getSubscriptionKey(sub)));
|
|
111
|
+
// Unsubscribe from removed subscriptions
|
|
112
|
+
for (const key of currentKeys) {
|
|
113
|
+
if (!newKeys.has(key)) {
|
|
114
|
+
const subscription = this.subscriptions.get(key);
|
|
115
|
+
if (subscription) {
|
|
116
|
+
subscription.unsubscribe();
|
|
117
|
+
this.subscriptions.delete(key);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
// Subscribe to new subscriptions
|
|
122
|
+
for (const subscription of newSubscriptions) {
|
|
123
|
+
const key = this.getSubscriptionKey(subscription);
|
|
124
|
+
if (!currentKeys.has(key)) {
|
|
125
|
+
this.createSubscription(subscription);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return rxjs_1.EMPTY;
|
|
129
|
+
}
|
|
130
|
+
createSubscription(subscription) {
|
|
131
|
+
var _a, _b;
|
|
132
|
+
const { marketId, channel, grouping } = subscription;
|
|
133
|
+
const subscriptionKey = this.getSubscriptionKey(subscription);
|
|
134
|
+
try {
|
|
135
|
+
const { unsubscribe } = MultiplexWebSocket_1.MultiplexWebSocket.createWebSocketSubscription({
|
|
136
|
+
wsUrl: this.config.websocketUrl,
|
|
137
|
+
enableHeartbeatMonitoring: true,
|
|
138
|
+
subscriptionId: `${this.config.websocketUrl}_dlob_liquidity_${marketId.key}`,
|
|
139
|
+
subscribeMessage: JSON.stringify(__1.DLOB_SERVER_WEBSOCKET_UTILS.getSubscriptionProps({
|
|
140
|
+
type: channel,
|
|
141
|
+
market: marketId,
|
|
142
|
+
grouping,
|
|
143
|
+
})),
|
|
144
|
+
unsubscribeMessage: JSON.stringify(__1.DLOB_SERVER_WEBSOCKET_UTILS.getUnsubscriptionProps({
|
|
145
|
+
type: channel,
|
|
146
|
+
market: marketId,
|
|
147
|
+
grouping,
|
|
148
|
+
})),
|
|
149
|
+
onMessage: (message) => {
|
|
150
|
+
this.rawMessages$.next({
|
|
151
|
+
marketId,
|
|
152
|
+
channel: message.channel,
|
|
153
|
+
data: message.data,
|
|
154
|
+
});
|
|
155
|
+
},
|
|
156
|
+
messageFilter: (message) => {
|
|
157
|
+
return __1.DLOB_SERVER_WEBSOCKET_UTILS.getMessageFilter({
|
|
158
|
+
type: channel,
|
|
159
|
+
market: marketId,
|
|
160
|
+
grouping,
|
|
161
|
+
})(message);
|
|
162
|
+
},
|
|
163
|
+
onError: (error) => {
|
|
164
|
+
var _a, _b;
|
|
165
|
+
console.error('Caught error in createSubscription', error);
|
|
166
|
+
(_b = (_a = this.config).onFallback) === null || _b === void 0 ? void 0 : _b.call(_a, marketId);
|
|
167
|
+
},
|
|
168
|
+
errorMessageFilter: (message) => {
|
|
169
|
+
if (message === null || message === void 0 ? void 0 : message.error) {
|
|
170
|
+
return true;
|
|
171
|
+
}
|
|
172
|
+
return false;
|
|
173
|
+
},
|
|
174
|
+
});
|
|
175
|
+
this.subscriptions.set(subscriptionKey, { unsubscribe });
|
|
176
|
+
}
|
|
177
|
+
catch (error) {
|
|
178
|
+
console.error('Failed to create subscription:', error);
|
|
179
|
+
(_b = (_a = this.config).onFallback) === null || _b === void 0 ? void 0 : _b.call(_a, marketId);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
processRawMessage(marketId, channel, data) {
|
|
183
|
+
var _a, _b;
|
|
184
|
+
try {
|
|
185
|
+
const parsed = this.tryParse(data);
|
|
186
|
+
const resultKey = `${channel}_${marketId.key}`;
|
|
187
|
+
const messageTimestamp = Date.now(); // Capture when we received this message
|
|
188
|
+
const validResult = this.resultIncrementer.handleResult(resultKey, (_a = parsed.slot) !== null && _a !== void 0 ? _a : 0, messageTimestamp);
|
|
189
|
+
if (!validResult) {
|
|
190
|
+
return null; // Skip results which aren't slot-increasing or are filtered due to tab return
|
|
191
|
+
}
|
|
192
|
+
const deserializedData = (0, __1.deserializeL2Response)(parsed);
|
|
193
|
+
return {
|
|
194
|
+
marketId,
|
|
195
|
+
rawData: parsed,
|
|
196
|
+
deserializedData,
|
|
197
|
+
slot: (_b = parsed.slot) !== null && _b !== void 0 ? _b : 0,
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
catch (error) {
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
tryParse(data) {
|
|
205
|
+
try {
|
|
206
|
+
return JSON.parse(data, (key, value) => {
|
|
207
|
+
// If the value is a number and it's too large to be safely represented as a JavaScript number,
|
|
208
|
+
// convert it to a string to prevent precision loss
|
|
209
|
+
if (typeof value === 'number' && !Number.isSafeInteger(value)) {
|
|
210
|
+
return value.toString();
|
|
211
|
+
}
|
|
212
|
+
return value;
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
catch (e) {
|
|
216
|
+
return data;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
getSubscriptionKey(subscription) {
|
|
220
|
+
const { marketId, channel, grouping } = subscription;
|
|
221
|
+
return `${marketId.key}_${channel}${grouping ? `_${grouping}` : ''}`;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
exports.DlobWebsocketClient = DlobWebsocketClient;
|
|
225
|
+
exports.default = DlobWebsocketClient;
|
|
226
|
+
//# sourceMappingURL=DlobWebsocketClient.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"DlobWebsocketClient.js","sourceRoot":"","sources":["../../src/clients/DlobWebsocketClient.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;;;;AAEb,0BAMY;AACZ,+BAAmE;AACnE,8CAQwB;AACxB,0EAAuE;AACvE,oEAAiE;AA4BjE,MAAa,mBAAmB;IAc/B,YAAY,MAAiC;QAZrC,kBAAa,GAAG,IAAI,GAAG,EAAuC,CAAC;QAE/D,aAAQ,GAAG,IAAI,cAAO,EAAQ,CAAC;QAEvC,gCAAgC;QACxB,yBAAoB,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;gBACR,OAAO,EAAE,MAAM;gBACf,gBAAgB;gBAChB,IAAI,EAAE,MAAA,MAAM,CAAC,IAAI,mCAAI,CAAC;aACtB,CAAC;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,OAAO,IAAI,CAAC;QACb,CAAC;IACF,CAAC;IAEO,QAAQ,CAAC,IAAa;QAC7B,IAAI,CAAC;YACJ,OAAO,IAAI,CAAC,KAAK,CAAC,IAAc,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE;gBAChD,+FAA+F;gBAC/F,mDAAmD;gBACnD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,EAAE,CAAC;oBAC/D,OAAO,KAAK,CAAC,QAAQ,EAAE,CAAC;gBACzB,CAAC;gBACD,OAAO,KAAK,CAAC;YACd,CAAC,CAAC,CAAC;QACJ,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACZ,OAAO,IAAI,CAAC;QACb,CAAC;IACF,CAAC;IAEO,kBAAkB,CAAC,YAAgC;QAC1D,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,GAAG,YAAY,CAAC;QACrD,OAAO,GAAG,QAAQ,CAAC,GAAG,IAAI,OAAO,GAAG,QAAQ,CAAC,CAAC,CAAC,IAAI,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;IACtE,CAAC;CACD;AAtRD,kDAsRC;AAED,kBAAe,mBAAmB,CAAC","sourcesContent":["'use client';\n\nimport {\n\tMarketId,\n\tdeserializeL2Response,\n\tOrderbookGrouping,\n\tDLOB_SERVER_WEBSOCKET_UTILS,\n\tDlobServerChannel,\n} from '..';\nimport { Observable, Subject, BehaviorSubject, EMPTY } from 'rxjs';\nimport {\n\tmap,\n\tfilter,\n\tcatchError,\n\ttakeUntil,\n\tshare,\n\tdistinctUntilChanged,\n\tswitchMap,\n} from 'rxjs/operators';\nimport { ResultSlotIncrementer } from '../utils/ResultSlotIncrementer';\nimport { MultiplexWebSocket } from '../utils/MultiplexWebSocket';\nimport { RawL2Output } from '../utils/orderbook/types';\n\nexport type OrderbookChannelTypes = Extract<\n\tDlobServerChannel,\n\t'orderbook' | 'orderbook_indicative'\n>;\n\nexport interface DlobWebsocketClientConfig {\n\twebsocketUrl: string;\n\tenableIndicativeOrderbook?: boolean;\n\tresultSlotIncrementer?: ResultSlotIncrementer;\n\tonFallback?: (marketId: MarketId) => void;\n}\n\nexport interface MarketSubscription {\n\tmarketId: MarketId;\n\tchannel: OrderbookChannelTypes;\n\tgrouping?: OrderbookGrouping;\n}\n\nexport interface ProcessedMarketData {\n\tmarketId: MarketId;\n\trawData: RawL2Output;\n\tdeserializedData: ReturnType<typeof deserializeL2Response>;\n\tslot: number;\n}\n\nexport class DlobWebsocketClient {\n\tprivate config: DlobWebsocketClientConfig;\n\tprivate subscriptions = new Map<string, { unsubscribe: () => void }>();\n\tprivate resultIncrementer: ResultSlotIncrementer;\n\tprivate destroy$ = new Subject<void>();\n\n\t// Subjects for reactive streams\n\tprivate marketSubscriptions$ = new BehaviorSubject<MarketSubscription[]>([]);\n\tprivate rawMessages$ = new Subject<{\n\t\tmarketId: MarketId;\n\t\tchannel: string;\n\t\tdata: string;\n\t}>();\n\n\tconstructor(config: DlobWebsocketClientConfig) {\n\t\tthis.config = config;\n\t\tthis.resultIncrementer =\n\t\t\tconfig.resultSlotIncrementer || new ResultSlotIncrementer();\n\n\t\tthis.setupSubscriptionManagement();\n\t}\n\n\t/**\n\t * Get an observable stream of processed market data for specific markets\n\t */\n\tgetMarketDataStream(marketIds: MarketId[]): Observable<ProcessedMarketData> {\n\t\treturn this.rawMessages$.pipe(\n\t\t\tfilter(({ marketId }) => marketIds.some((id) => id.key === marketId.key)),\n\t\t\tmap(({ marketId, channel, data }) =>\n\t\t\t\tthis.processRawMessage(marketId, channel, data)\n\t\t\t),\n\t\t\tfilter((result): result is ProcessedMarketData => result !== null),\n\t\t\tcatchError((error) => {\n\t\t\t\tconsole.error('Caught error in getMarketDataStream', error);\n\t\t\t\treturn EMPTY;\n\t\t\t}),\n\t\t\ttakeUntil(this.destroy$),\n\t\t\tshare()\n\t\t);\n\t}\n\n\t/**\n\t * Subscribe to market data for given markets\n\t */\n\tsubscribeToMarkets(\n\t\tmarkets: {\n\t\t\tmarketId: MarketId;\n\t\t\tgrouping?: OrderbookGrouping;\n\t\t}[]\n\t): void {\n\t\tconst subscriptions: MarketSubscription[] = markets.map(\n\t\t\t({ marketId, grouping }) => ({\n\t\t\t\tmarketId,\n\t\t\t\tchannel: this.config.enableIndicativeOrderbook\n\t\t\t\t\t? 'orderbook_indicative'\n\t\t\t\t\t: 'orderbook',\n\t\t\t\tgrouping,\n\t\t\t})\n\t\t);\n\n\t\tthis.marketSubscriptions$.next(subscriptions);\n\t}\n\n\t/**\n\t * Unsubscribe from all markets\n\t */\n\tunsubscribeAll(): void {\n\t\tthis.marketSubscriptions$.next([]);\n\t}\n\n\t/**\n\t * Handle tab return to prevent \"speed run\" through queued messages\n\t */\n\thandleTabReturn(): void {\n\t\tthis.resultIncrementer.handleTabReturn();\n\t}\n\n\t/**\n\t * Reset slot tracking for clean state on reconnection\n\t */\n\tresetSlotTracking(): void {\n\t\t// Get all current subscription keys and reset their slot tracking\n\t\tfor (const subscriptionKey of this.subscriptions.keys()) {\n\t\t\t// Extract marketId and channel from subscription key\n\t\t\tconst [marketKey, channel] = subscriptionKey.split('_');\n\t\t\tconst resultKey = `${channel}_${marketKey}`;\n\t\t\tthis.resultIncrementer.resetKey(resultKey);\n\t\t}\n\t}\n\n\t/**\n\t * Destroy the client and clean up all subscriptions\n\t */\n\tdestroy(): void {\n\t\tthis.destroy$.next();\n\t\tthis.destroy$.complete();\n\t\tthis.subscriptions.forEach(({ unsubscribe }) => unsubscribe());\n\t\tthis.subscriptions.clear();\n\t}\n\n\t/**\n\t * Sets up the subscription management pipeline that handles market data subscriptions.\n\t * This pipeline:\n\t * 1. Watches for changes in market subscriptions\n\t * 2. Only processes changes when the subscription list actually changes\n\t * 3. Manages the lifecycle of websocket subscriptions\n\t * 4. Cleans up when the client is destroyed\n\t */\n\tprivate setupSubscriptionManagement(): void {\n\t\tthis.marketSubscriptions$\n\t\t\t.pipe(\n\t\t\t\t// Only emit when the subscription list actually changes\n\t\t\t\t// Uses JSON.stringify for deep comparison of subscription arrays\n\t\t\t\tdistinctUntilChanged(\n\t\t\t\t\t(prev, curr) => JSON.stringify(prev) === JSON.stringify(curr)\n\t\t\t\t),\n\t\t\t\t// Switch to managing the new set of subscriptions\n\t\t\t\t// This will cancel any previous subscription management\n\t\t\t\tswitchMap((subscriptions) =>\n\t\t\t\t\tthis.manageNewSubscriptions(subscriptions)\n\t\t\t\t),\n\t\t\t\t// Clean up when the client is destroyed\n\t\t\t\ttakeUntil(this.destroy$)\n\t\t\t)\n\t\t\t.subscribe();\n\t}\n\n\t/**\n\t * Manages the lifecycle of websocket subscriptions by:\n\t * 1. Comparing current subscriptions with new subscriptions\n\t * 2. Unsubscribing from any subscriptions that are no longer needed\n\t * 3. Creating new subscriptions for markets that weren't previously subscribed\n\t *\n\t * @param newSubscriptions - The new set of market subscriptions to maintain\n\t * @returns An empty observable since this is a side-effect operation\n\t */\n\tprivate manageNewSubscriptions(\n\t\tnewSubscriptions: MarketSubscription[]\n\t): Observable<never> {\n\t\t// Get sets of subscription keys for efficient comparison\n\t\tconst currentKeys = new Set(this.subscriptions.keys());\n\t\tconst newKeys = new Set(\n\t\t\tnewSubscriptions.map((sub) => this.getSubscriptionKey(sub))\n\t\t);\n\n\t\t// Unsubscribe from removed subscriptions\n\t\tfor (const key of currentKeys) {\n\t\t\tif (!newKeys.has(key)) {\n\t\t\t\tconst subscription = this.subscriptions.get(key);\n\t\t\t\tif (subscription) {\n\t\t\t\t\tsubscription.unsubscribe();\n\t\t\t\t\tthis.subscriptions.delete(key);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Subscribe to new subscriptions\n\t\tfor (const subscription of newSubscriptions) {\n\t\t\tconst key = this.getSubscriptionKey(subscription);\n\t\t\tif (!currentKeys.has(key)) {\n\t\t\t\tthis.createSubscription(subscription);\n\t\t\t}\n\t\t}\n\n\t\treturn EMPTY;\n\t}\n\n\tprivate createSubscription(subscription: MarketSubscription): void {\n\t\tconst { marketId, channel, grouping } = subscription;\n\t\tconst subscriptionKey = this.getSubscriptionKey(subscription);\n\n\t\ttry {\n\t\t\tconst { unsubscribe } = MultiplexWebSocket.createWebSocketSubscription<{\n\t\t\t\tchannel: string;\n\t\t\t\tdata: string;\n\t\t\t}>({\n\t\t\t\twsUrl: this.config.websocketUrl,\n\t\t\t\tenableHeartbeatMonitoring: true,\n\t\t\t\tsubscriptionId: `${this.config.websocketUrl}_dlob_liquidity_${marketId.key}`,\n\t\t\t\tsubscribeMessage: JSON.stringify(\n\t\t\t\t\tDLOB_SERVER_WEBSOCKET_UTILS.getSubscriptionProps({\n\t\t\t\t\t\ttype: channel,\n\t\t\t\t\t\tmarket: marketId,\n\t\t\t\t\t\tgrouping,\n\t\t\t\t\t})\n\t\t\t\t),\n\t\t\t\tunsubscribeMessage: JSON.stringify(\n\t\t\t\t\tDLOB_SERVER_WEBSOCKET_UTILS.getUnsubscriptionProps({\n\t\t\t\t\t\ttype: channel,\n\t\t\t\t\t\tmarket: marketId,\n\t\t\t\t\t\tgrouping,\n\t\t\t\t\t})\n\t\t\t\t),\n\t\t\t\tonMessage: (message: { channel: string; data: string }) => {\n\t\t\t\t\tthis.rawMessages$.next({\n\t\t\t\t\t\tmarketId,\n\t\t\t\t\t\tchannel: message.channel,\n\t\t\t\t\t\tdata: message.data,\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\tmessageFilter: (message: { channel: string; data: string }) => {\n\t\t\t\t\treturn DLOB_SERVER_WEBSOCKET_UTILS.getMessageFilter({\n\t\t\t\t\t\ttype: channel,\n\t\t\t\t\t\tmarket: marketId,\n\t\t\t\t\t\tgrouping,\n\t\t\t\t\t})(message);\n\t\t\t\t},\n\t\t\t\tonError: (error?: any) => {\n\t\t\t\t\tconsole.error('Caught error in createSubscription', error);\n\t\t\t\t\tthis.config.onFallback?.(marketId);\n\t\t\t\t},\n\t\t\t\terrorMessageFilter: (message?: any) => {\n\t\t\t\t\tif (message?.error) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\treturn false;\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tthis.subscriptions.set(subscriptionKey, { unsubscribe });\n\t\t} catch (error) {\n\t\t\tconsole.error('Failed to create subscription:', error);\n\t\t\tthis.config.onFallback?.(marketId);\n\t\t}\n\t}\n\n\tprivate processRawMessage(\n\t\tmarketId: MarketId,\n\t\tchannel: string,\n\t\tdata: string\n\t): ProcessedMarketData | null {\n\t\ttry {\n\t\t\tconst parsed = this.tryParse(data) as RawL2Output;\n\t\t\tconst resultKey = `${channel}_${marketId.key}`;\n\t\t\tconst messageTimestamp = Date.now(); // Capture when we received this message\n\n\t\t\tconst validResult = this.resultIncrementer.handleResult(\n\t\t\t\tresultKey,\n\t\t\t\tparsed.slot ?? 0,\n\t\t\t\tmessageTimestamp\n\t\t\t);\n\n\t\t\tif (!validResult) {\n\t\t\t\treturn null; // Skip results which aren't slot-increasing or are filtered due to tab return\n\t\t\t}\n\n\t\t\tconst deserializedData = deserializeL2Response(parsed);\n\n\t\t\treturn {\n\t\t\t\tmarketId,\n\t\t\t\trawData: parsed,\n\t\t\t\tdeserializedData,\n\t\t\t\tslot: parsed.slot ?? 0,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate tryParse(data: unknown): unknown {\n\t\ttry {\n\t\t\treturn JSON.parse(data as string, (key, value) => {\n\t\t\t\t// If the value is a number and it's too large to be safely represented as a JavaScript number,\n\t\t\t\t// convert it to a string to prevent precision loss\n\t\t\t\tif (typeof value === 'number' && !Number.isSafeInteger(value)) {\n\t\t\t\t\treturn value.toString();\n\t\t\t\t}\n\t\t\t\treturn value;\n\t\t\t});\n\t\t} catch (e) {\n\t\t\treturn data;\n\t\t}\n\t}\n\n\tprivate getSubscriptionKey(subscription: MarketSubscription): string {\n\t\tconst { marketId, channel, grouping } = subscription;\n\t\treturn `${marketId.key}_${channel}${grouping ? `_${grouping}` : ''}`;\n\t}\n}\n\nexport default DlobWebsocketClient;\n"]}
|
|
@@ -109,6 +109,7 @@ class SwiftClient {
|
|
|
109
109
|
};
|
|
110
110
|
}
|
|
111
111
|
static async confirmSwiftOrderWS(connection, client, signedMsgUserOrdersAccount, signedMsgOrderUuid, confirmDuration) {
|
|
112
|
+
(0, logger_1.allEnvDlog)('swiftClient', 'confirmSwiftOrderWS - confirmation duration', confirmDuration);
|
|
112
113
|
return new Promise((resolve, reject) => {
|
|
113
114
|
const timeout = setTimeout(() => {
|
|
114
115
|
reject(new Error('Order not found'));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"swiftClient.js","sourceRoot":"","sources":["../../src/clients/swiftClient.ts"],"names":[],"mappings":";;;AACA,yCASyB;AACzB,+BAA8C;AAC9C,4CAA6C;AA4C7C,MAAa,WAAW;IAMhB,MAAM,CAAC,IAAI,CAAC,OAAe,EAAE,mBAA4B;QAC/D,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,mBAAmB,GAAG,mBAAmB,CAAC;IAChD,CAAC;IAEO,MAAM,CAAC,GAAG,CAAC,GAAW;QAC7B,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;YACnB,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;QAChD,CAAC;QAED,OAAO,IAAI,OAAO,CACjB,CAAC,GAAG,EAAE,EAAE;YACP,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC;gBAC3B,GAAG,IAAI,CAAC,eAAe,EAAE;aACzB,CAAC,CAAC;YAEH,KAAK,CAAC,GAAG,IAAI,CAAC,OAAO,GAAG,GAAG,EAAE,EAAE;g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,0BAA0B,CAC9B,UAAU,EACV,WAAW,EACX,UAAU,EACV,OAAO,EACP,SAAS,EACT,WAAW,EACX,eAAe,EACf,gBAAgB,CAChB,CAAC;QACH,CAAC,CAAC,CAAC;IACJ,CAAC;IAEM,MAAM,CAAC,0BAA0B,CACvC,UAAsB,EACtB,MAAmB,EACnB,WAAmB,EACnB,UAAsB,EACtB,OAAe,EACf,SAAiB,EACjB,WAAsB,EACtB,gCAA2C,EAC3C,kBAA8B,EAC9B,eAAuB,EACvB,gBAA2B;QAE3B,OAAO,IAAI,iBAAU,CAAkB,CAAC,UAAU,EAAE,EAAE;YACrD,IAAI,CAAC,4BAA4B,CAChC,UAAU,EACV,UAAU,EACV,MAAM,EACN,WAAW,EACX,UAAU,EACV,OAAO,EACP,SAAS,EACT,WAAW,EACX,gCAAgC,EAChC,kBAAkB,EAClB,eAAe,EACf,gBAAgB,CAChB,CAAC;QACH,CAAC,CAAC,CAAC;IACJ,CAAC;IAEM,MAAM,CAAC,KAAK,CAAC,oBAAoB;QACvC,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;QAC3C,OAAO,QAAQ,CAAC,MAAM,KAAK,GAAG,CAAC;IAChC,CAAC;IAEO,MAAM,CAAC,eAAe;;QAC7B,OAAO;YACN,cAAc,EAAE,kBAAkB;YAClC,yBAAyB,EAAE,MAAA,IAAI,CAAC,mBAAmB,mCAAI,SAAS;SAChE,CAAC;IACH,CAAC;IAEM,MAAM,CAAC,oBAAoB,CAAC,SAAoB;QACtD,OAAO,IAAI,CAAC,mBAAmB,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;IACrD,CAAC;;AApeF,kCAqeC;AApee,mBAAO,GAAG,EAAE,CAAC;AAGrB,+BAAmB,GAAgB,CAAC,eAAS,CAAC,MAAM,EAAE,eAAS,CAAC,KAAK,CAAC,CAAC","sourcesContent":["import { AccountInfo, Connection, PublicKey } from '@solana/web3.js';\nimport {\n\tDriftClient,\n\tMarketType,\n\tOrderType,\n\tSignedMsgOrderParamsDelegateMessage,\n\tSignedMsgOrderParamsMessage,\n\tSignedMsgUserOrdersAccount,\n\tdigestSignature,\n\tisVariant,\n} from '@drift-labs/sdk';\nimport { Observable, Subscriber } from 'rxjs';\nimport { allEnvDlog } from '../utils/logger';\nexport type SwiftServerOrderProcessResponse = {\n\terror?: string;\n\tmessage: string;\n};\n\ntype ClientResponse<T = void> = Promise<{\n\tsuccess: boolean;\n\tbody?: T;\n\tmessage?: string;\n\tstatus?: number;\n}>;\n\ntype BaseSwiftOrderEvent = {\n\thash: string;\n};\n\nexport interface SwiftOrderSentEvent extends BaseSwiftOrderEvent {\n\ttype: 'sent';\n}\n\nexport interface SwiftOrderErroredEvent extends BaseSwiftOrderEvent {\n\ttype: 'errored' | 'expired';\n\tmessage?: string;\n\tstatus?: number;\n}\n\nexport interface SwiftOrderConfirmedEvent extends BaseSwiftOrderEvent {\n\ttype: 'confirmed';\n\torderId: string;\n}\n\nexport type SwiftOrderEvent =\n\t| SwiftOrderErroredEvent\n\t| SwiftOrderConfirmedEvent\n\t| SwiftOrderSentEvent;\n\nexport type SwiftOrderEventWithParams<T extends SwiftOrderEvent> = T & {\n\tswiftOrderUuid: Uint8Array;\n\torderParamsMessage:\n\t\t| SignedMsgOrderParamsMessage\n\t\t| SignedMsgOrderParamsDelegateMessage;\n};\n\nexport class SwiftClient {\n\tprivate static baseUrl = '';\n\tprivate static swiftClientConsumer?: string;\n\n\tstatic supportedOrderTypes: OrderType[] = [OrderType.MARKET, OrderType.LIMIT];\n\n\tpublic static init(baseUrl: string, swiftClientConsumer?: string) {\n\t\tthis.baseUrl = baseUrl;\n\t\tthis.swiftClientConsumer = swiftClientConsumer;\n\t}\n\n\tprivate static get(url: string) {\n\t\tif (!this.baseUrl) {\n\t\t\tthrow new Error('SwiftClient not initialized');\n\t\t}\n\n\t\treturn new Promise<{ success: boolean; body: string; status: number }>(\n\t\t\t(res) => {\n\t\t\t\tconst headers = new Headers({\n\t\t\t\t\t...this.getSwiftHeaders(),\n\t\t\t\t});\n\n\t\t\t\tfetch(`${this.baseUrl}${url}`, {\n\t\t\t\t\theaders,\n\t\t\t\t})\n\t\t\t\t\t.then(async (response) => {\n\t\t\t\t\t\tif (!response.ok) {\n\t\t\t\t\t\t\tres({\n\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\tbody: await response.text(),\n\t\t\t\t\t\t\t\tstatus: response.status,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tres({\n\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\tbody: await response.text(),\n\t\t\t\t\t\t\tstatus: response.status,\n\t\t\t\t\t\t});\n\t\t\t\t\t})\n\t\t\t\t\t.catch((err) => {\n\t\t\t\t\t\tres({ success: false, body: err, status: 0 });\n\t\t\t\t\t});\n\t\t\t}\n\t\t);\n\t}\n\n\tprivate static post(url: string, bodyObject: any) {\n\t\tif (!this.baseUrl) {\n\t\t\tthrow new Error('SwiftClient not initialized');\n\t\t}\n\n\t\tconst requestOptions = {\n\t\t\tmethod: 'POST',\n\t\t\theaders: { ...this.getSwiftHeaders() },\n\t\t\tbody: JSON.stringify(bodyObject),\n\t\t};\n\n\t\treturn new Promise<{\n\t\t\tsuccess: boolean;\n\t\t\tbody: SwiftServerOrderProcessResponse;\n\t\t\tstatus: number;\n\t\t}>((res) => {\n\t\t\tconst postRequest = new Request(`${this.baseUrl}${url}`, requestOptions);\n\n\t\t\tfetch(postRequest)\n\t\t\t\t.then(async (response) => {\n\t\t\t\t\tlet resBody: SwiftServerOrderProcessResponse | null = null;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tresBody =\n\t\t\t\t\t\t\t(await response.json()) as SwiftServerOrderProcessResponse;\n\n\t\t\t\t\t\tres({\n\t\t\t\t\t\t\tsuccess: response.ok,\n\t\t\t\t\t\t\tbody: resBody,\n\t\t\t\t\t\t\tstatus: response.status,\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tallEnvDlog('swiftClient', 'Error reading response body', err);\n\n\t\t\t\t\t\tres({\n\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\tbody: err as any,\n\t\t\t\t\t\t\tstatus: response.status,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.catch((err) => {\n\t\t\t\t\tres({ success: false, body: err, status: 0 });\n\t\t\t\t});\n\t\t});\n\t}\n\n\tstatic async sendSwiftOrder(\n\t\tmarketIndex: number,\n\t\tmarketType: MarketType,\n\t\tmessage: string,\n\t\tsignature: Buffer,\n\t\ttakerPubkey: PublicKey,\n\t\tsigningAuthority?: PublicKey\n\t): ClientResponse<{\n\t\thash: string;\n\t}> {\n\t\tconst requestPayload = {\n\t\t\tmarket_index: marketIndex,\n\t\t\tmarket_type: isVariant(marketType, 'perp') ? 'perp' : 'spot',\n\t\t\tmessage,\n\t\t\tsignature: signature.toString('base64'),\n\t\t\tsigning_authority: signingAuthority?.toBase58() ?? '',\n\t\t\ttaker_authority: takerPubkey.toBase58(),\n\t\t};\n\n\t\tconst response = await this.post('/orders', requestPayload);\n\n\t\tif (response.status !== 200) {\n\t\t\tconsole.error(\n\t\t\t\t`Non-200 status code received for sent Swift order: ${response.status}`\n\t\t\t);\n\t\t\tallEnvDlog('swiftClient', 'full non-200 response body', response.body);\n\t\t\treturn {\n\t\t\t\tmessage:\n\t\t\t\t\tresponse.body?.error ||\n\t\t\t\t\tresponse.body?.message ||\n\t\t\t\t\t`HTTP ${response.status}: Error from Swift server`,\n\t\t\t\tstatus: response.status,\n\t\t\t\tsuccess: false,\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tmessage: `Successfully sent Swift order`,\n\t\t\tbody: {\n\t\t\t\thash: digestSignature(Uint8Array.from(signature)),\n\t\t\t},\n\t\t\tsuccess: true,\n\t\t\tstatus: 200,\n\t\t};\n\t}\n\n\tstatic async confirmSwiftOrderWS(\n\t\tconnection: Connection,\n\t\tclient: DriftClient,\n\t\tsignedMsgUserOrdersAccount: PublicKey,\n\t\tsignedMsgOrderUuid: Uint8Array,\n\t\tconfirmDuration: number\n\t): Promise<number | undefined> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\treject(new Error('Order not found'));\n\t\t\t}, confirmDuration);\n\n\t\t\tconnection\n\t\t\t\t.getAccountInfo(signedMsgUserOrdersAccount, 'confirmed')\n\t\t\t\t.then((accountInfo) => {\n\t\t\t\t\tif (!accountInfo) {\n\t\t\t\t\t\treject(new Error('Swift message account not found'));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst order = this.findOrderInSignedMsgUserOrdersAccount(\n\t\t\t\t\t\tclient,\n\t\t\t\t\t\taccountInfo,\n\t\t\t\t\t\tsignedMsgOrderUuid\n\t\t\t\t\t);\n\n\t\t\t\t\tif (order) {\n\t\t\t\t\t\tallEnvDlog(\n\t\t\t\t\t\t\t'swiftClient',\n\t\t\t\t\t\t\t'confirmed in initial fetch orderID\\n',\n\t\t\t\t\t\t\torder.orderId\n\t\t\t\t\t\t);\n\t\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\t\tresolve(order.orderId);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\tconst subId = connection.onAccountChange(\n\t\t\t\tsignedMsgUserOrdersAccount,\n\t\t\t\t(accountInfo) => {\n\t\t\t\t\tconst order = this.findOrderInSignedMsgUserOrdersAccount(\n\t\t\t\t\t\tclient,\n\t\t\t\t\t\taccountInfo,\n\t\t\t\t\t\tsignedMsgOrderUuid\n\t\t\t\t\t);\n\t\t\t\t\tif (order) {\n\t\t\t\t\t\tallEnvDlog(\n\t\t\t\t\t\t\t'swiftClient',\n\t\t\t\t\t\t\t'confirmed in onAccountChange orderID\\n',\n\t\t\t\t\t\t\torder.orderId\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconnection.removeAccountChangeListener(subId);\n\t\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\t\tresolve(order.orderId);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t'confirmed'\n\t\t\t);\n\t\t});\n\t}\n\n\tstatic findOrderInSignedMsgUserOrdersAccount(\n\t\tclient: DriftClient,\n\t\tordersAccount: AccountInfo<Buffer>,\n\t\tsignedMsgOrderUuid: Uint8Array\n\t) {\n\t\tconst accountDecoder =\n\t\t\tclient.program.account.signedMsgUserOrders.coder.accounts.decodeUnchecked.bind(\n\t\t\t\tclient.program.account.signedMsgUserOrders.coder.accounts\n\t\t\t);\n\t\tconst decodedAccount = accountDecoder(\n\t\t\t'SignedMsgUserOrders',\n\t\t\tordersAccount.data\n\t\t) as SignedMsgUserOrdersAccount;\n\t\tallEnvDlog(\n\t\t\t'swiftClient findOrder',\n\t\t\t'decodedAccount\\n',\n\t\t\tdecodedAccount,\n\t\t\tsignedMsgOrderUuid.toString()\n\t\t);\n\t\tconst order = decodedAccount.signedMsgOrderData.find(\n\t\t\t(order) => order.uuid.toString() === signedMsgOrderUuid.toString()\n\t\t);\n\t\tallEnvDlog('swiftClient findOrder', 'order\\n', order);\n\t\treturn order;\n\t}\n\n\tstatic async confirmSwiftOrder(\n\t\thash: string,\n\t\tconfirmDuration: number\n\t): Promise<\n\t\tClientResponse<\n\t\t\t| {\n\t\t\t\t\torderId: string;\n\t\t\t\t\tstatus: 'confirmed';\n\t\t\t }\n\t\t\t| {\n\t\t\t\t\tstatus: 'expired';\n\t\t\t }\n\t\t>\n\t> {\n\t\tconst expireTime = Date.now() + confirmDuration;\n\n\t\twhile (Date.now() < expireTime) {\n\t\t\tconst confirmResponse = await this.get(\n\t\t\t\t`/confirmation/hash-status?hash=${encodeURIComponent(hash)}`\n\t\t\t);\n\n\t\t\tif (confirmResponse.status === 200) {\n\t\t\t\tconsole.log('Confirmed hash: ', hash);\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\tstatus: 200,\n\t\t\t\t\tmessage: 'Confirmed hash: ' + hash,\n\t\t\t\t\tbody: {\n\t\t\t\t\t\torderId: confirmResponse.body,\n\t\t\t\t\t\tstatus: 'confirmed',\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} else if (\n\t\t\t\tconfirmResponse.status >= 500 ||\n\t\t\t\tconfirmResponse.status < 200\n\t\t\t) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, 1000));\n\t\t}\n\n\t\tconsole.error('Failed to confirm hash: ', hash);\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tstatus: 408,\n\t\t\tmessage: 'Failed to confirm hash: ' + hash,\n\t\t\tbody: {\n\t\t\t\tstatus: 'expired',\n\t\t\t},\n\t\t};\n\t}\n\n\tstatic async handleSwiftOrderSubscriber(\n\t\tsubscriber: Subscriber<SwiftOrderEvent>,\n\t\tmarketIndex: number,\n\t\tmarketType: MarketType,\n\t\tmessage: string,\n\t\tsignature: Buffer,\n\t\ttakerPubkey: PublicKey,\n\t\tconfirmDuration: number,\n\t\tsigningAuthority?: PublicKey\n\t) {\n\t\t// First send the order\n\t\tconst sendResponse = await this.sendSwiftOrder(\n\t\t\tmarketIndex,\n\t\t\tmarketType,\n\t\t\tmessage,\n\t\t\tsignature,\n\t\t\ttakerPubkey,\n\t\t\tsigningAuthority\n\t\t);\n\n\t\tif (!sendResponse.success) {\n\t\t\tsubscriber.next({\n\t\t\t\ttype: 'errored',\n\t\t\t\thash: '',\n\t\t\t\tmessage: sendResponse.message,\n\t\t\t\tstatus: sendResponse.status,\n\t\t\t});\n\t\t\tsubscriber.error();\n\t\t\treturn;\n\t\t} else {\n\t\t\tsubscriber.next({\n\t\t\t\ttype: 'sent',\n\t\t\t\thash: sendResponse.body.hash,\n\t\t\t});\n\t\t}\n\n\t\tconst hash = sendResponse.body.hash;\n\n\t\t// Then confirm it\n\t\tconst confirmResponse = await this.confirmSwiftOrder(hash, confirmDuration);\n\n\t\tif (!confirmResponse.success) {\n\t\t\tsubscriber.next({\n\t\t\t\ttype: confirmResponse.body.status as 'expired',\n\t\t\t\thash,\n\t\t\t\tmessage: confirmResponse.message,\n\t\t\t\tstatus: confirmResponse.status,\n\t\t\t});\n\t\t\tsubscriber.error();\n\t\t}\n\t\tif (confirmResponse.body.status === 'confirmed') {\n\t\t\tsubscriber.next({\n\t\t\t\ttype: 'confirmed',\n\t\t\t\torderId: confirmResponse.body.orderId,\n\t\t\t\thash,\n\t\t\t});\n\t\t\tsubscriber.complete();\n\t\t}\n\t}\n\tstatic async handleSwiftOrderSubscriberWS(\n\t\tsubscriber: Subscriber<SwiftOrderEvent>,\n\t\tconnection: Connection,\n\t\tclient: DriftClient,\n\t\tmarketIndex: number,\n\t\tmarketType: MarketType,\n\t\tmessage: string,\n\t\tsignature: Buffer,\n\t\ttakerPubkey: PublicKey,\n\t\tsignedMsgUserOrdersAccountPubkey: PublicKey,\n\t\tsignedMsgOrderUuid: Uint8Array,\n\t\tconfirmDuration: number,\n\t\tsigningAuthority?: PublicKey\n\t) {\n\t\t// First send the order\n\t\tconst sendResponse = await this.sendSwiftOrder(\n\t\t\tmarketIndex,\n\t\t\tmarketType,\n\t\t\tmessage,\n\t\t\tsignature,\n\t\t\ttakerPubkey,\n\t\t\tsigningAuthority\n\t\t);\n\t\tallEnvDlog('swiftClient', 'sendResponse\\n', sendResponse);\n\n\t\tif (!sendResponse.success) {\n\t\t\tsubscriber.next({\n\t\t\t\ttype: 'errored',\n\t\t\t\thash: '',\n\t\t\t\tmessage: 'Error from swift node: ' + sendResponse.message,\n\t\t\t\tstatus: sendResponse.status,\n\t\t\t});\n\t\t\tsubscriber.error();\n\t\t\treturn;\n\t\t} else {\n\t\t\tsubscriber.next({\n\t\t\t\ttype: 'sent',\n\t\t\t\thash: sendResponse.body.hash,\n\t\t\t});\n\t\t}\n\n\t\tconst hash = sendResponse.body.hash;\n\n\t\t// Then confirm it\n\t\tconst orderID = await this.confirmSwiftOrderWS(\n\t\t\tconnection,\n\t\t\tclient,\n\t\t\tsignedMsgUserOrdersAccountPubkey,\n\t\t\tsignedMsgOrderUuid,\n\t\t\tconfirmDuration\n\t\t).catch((err) => {\n\t\t\tallEnvDlog('swiftClient', 'confirmSwiftOrderWS error', err);\n\t\t\tsubscriber.next({\n\t\t\t\ttype: 'expired',\n\t\t\t\thash,\n\t\t\t\tmessage: 'Order failed to confirm',\n\t\t\t\tstatus: 408,\n\t\t\t});\n\t\t\tsubscriber.error();\n\t\t});\n\n\t\tif (!orderID) {\n\t\t\tsubscriber.next({\n\t\t\t\ttype: 'expired',\n\t\t\t\thash,\n\t\t\t\tmessage: 'Order failed to confirm',\n\t\t\t\tstatus: 408,\n\t\t\t});\n\t\t\tsubscriber.error();\n\t\t} else {\n\t\t\tsubscriber.next({\n\t\t\t\ttype: 'confirmed',\n\t\t\t\torderId: orderID.toString(),\n\t\t\t\thash,\n\t\t\t});\n\t\t\tsubscriber.complete();\n\t\t}\n\t}\n\n\tpublic static sendAndConfirmSwiftOrder(\n\t\tmarketIndex: number,\n\t\tmarketType: MarketType,\n\t\tmessage: string,\n\t\tsignature: Buffer,\n\t\ttakerPubkey: PublicKey,\n\t\tconfirmDuration: number,\n\t\tsigningAuthority: PublicKey\n\t): Observable<SwiftOrderEvent> {\n\t\treturn new Observable<SwiftOrderEvent>((subscriber) => {\n\t\t\tthis.handleSwiftOrderSubscriber(\n\t\t\t\tsubscriber,\n\t\t\t\tmarketIndex,\n\t\t\t\tmarketType,\n\t\t\t\tmessage,\n\t\t\t\tsignature,\n\t\t\t\ttakerPubkey,\n\t\t\t\tconfirmDuration,\n\t\t\t\tsigningAuthority\n\t\t\t);\n\t\t});\n\t}\n\n\tpublic static sendAndConfirmSwiftOrderWS(\n\t\tconnection: Connection,\n\t\tclient: DriftClient,\n\t\tmarketIndex: number,\n\t\tmarketType: MarketType,\n\t\tmessage: string,\n\t\tsignature: Buffer,\n\t\ttakerPubkey: PublicKey,\n\t\tsignedMsgUserOrdersAccountPubkey: PublicKey,\n\t\tsignedMsgOrderUuid: Uint8Array,\n\t\tconfirmDuration: number,\n\t\tsigningAuthority: PublicKey\n\t): Observable<SwiftOrderEvent> {\n\t\treturn new Observable<SwiftOrderEvent>((subscriber) => {\n\t\t\tthis.handleSwiftOrderSubscriberWS(\n\t\t\t\tsubscriber,\n\t\t\t\tconnection,\n\t\t\t\tclient,\n\t\t\t\tmarketIndex,\n\t\t\t\tmarketType,\n\t\t\t\tmessage,\n\t\t\t\tsignature,\n\t\t\t\ttakerPubkey,\n\t\t\t\tsignedMsgUserOrdersAccountPubkey,\n\t\t\t\tsignedMsgOrderUuid,\n\t\t\t\tconfirmDuration,\n\t\t\t\tsigningAuthority\n\t\t\t);\n\t\t});\n\t}\n\n\tpublic static async isSwiftServerHealthy(): Promise<boolean> {\n\t\tconst response = await this.get('/health');\n\t\treturn response.status === 200;\n\t}\n\n\tprivate static getSwiftHeaders(): Record<string, string> {\n\t\treturn {\n\t\t\t'Content-Type': 'application/json',\n\t\t\t'X-Swift-Client-Consumer': this.swiftClientConsumer ?? 'default',\n\t\t};\n\t}\n\n\tpublic static isSupportedOrderType(orderType: OrderType) {\n\t\treturn this.supportedOrderTypes.includes(orderType);\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"swiftClient.js","sourceRoot":"","sources":["../../src/clients/swiftClient.ts"],"names":[],"mappings":";;;AACA,yCASyB;AACzB,+BAA8C;AAC9C,4CAA6C;AA4C7C,MAAa,WAAW;IAMhB,MAAM,CAAC,IAAI,CAAC,OAAe,EAAE,mBAA4B;QAC/D,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,mBAAmB,GAAG,mBAAmB,CAAC;IAChD,CAAC;IAEO,MAAM,CAAC,GAAG,CAAC,GAAW;QAC7B,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;YACnB,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CA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C,oBAAoB,CAAC,SAAoB;QACtD,OAAO,IAAI,CAAC,mBAAmB,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;IACrD,CAAC;;AAzeF,kCA0eC;AAzee,mBAAO,GAAG,EAAE,CAAC;AAGrB,+BAAmB,GAAgB,CAAC,eAAS,CAAC,MAAM,EAAE,eAAS,CAAC,KAAK,CAAC,CAAC","sourcesContent":["import { AccountInfo, Connection, PublicKey } from '@solana/web3.js';\nimport {\n\tDriftClient,\n\tMarketType,\n\tOrderType,\n\tSignedMsgOrderParamsDelegateMessage,\n\tSignedMsgOrderParamsMessage,\n\tSignedMsgUserOrdersAccount,\n\tdigestSignature,\n\tisVariant,\n} from '@drift-labs/sdk';\nimport { Observable, Subscriber } from 'rxjs';\nimport { allEnvDlog } from '../utils/logger';\nexport type SwiftServerOrderProcessResponse = {\n\terror?: string;\n\tmessage: string;\n};\n\ntype ClientResponse<T = void> = Promise<{\n\tsuccess: boolean;\n\tbody?: T;\n\tmessage?: string;\n\tstatus?: number;\n}>;\n\ntype BaseSwiftOrderEvent = {\n\thash: string;\n};\n\nexport interface SwiftOrderSentEvent extends BaseSwiftOrderEvent {\n\ttype: 'sent';\n}\n\nexport interface SwiftOrderErroredEvent extends BaseSwiftOrderEvent {\n\ttype: 'errored' | 'expired';\n\tmessage?: string;\n\tstatus?: number;\n}\n\nexport interface SwiftOrderConfirmedEvent extends BaseSwiftOrderEvent {\n\ttype: 'confirmed';\n\torderId: string;\n}\n\nexport type SwiftOrderEvent =\n\t| SwiftOrderErroredEvent\n\t| SwiftOrderConfirmedEvent\n\t| SwiftOrderSentEvent;\n\nexport type SwiftOrderEventWithParams<T extends SwiftOrderEvent> = T & {\n\tswiftOrderUuid: Uint8Array;\n\torderParamsMessage:\n\t\t| SignedMsgOrderParamsMessage\n\t\t| SignedMsgOrderParamsDelegateMessage;\n};\n\nexport class SwiftClient {\n\tprivate static baseUrl = '';\n\tprivate static swiftClientConsumer?: string;\n\n\tstatic supportedOrderTypes: OrderType[] = [OrderType.MARKET, OrderType.LIMIT];\n\n\tpublic static init(baseUrl: string, swiftClientConsumer?: string) {\n\t\tthis.baseUrl = baseUrl;\n\t\tthis.swiftClientConsumer = swiftClientConsumer;\n\t}\n\n\tprivate static get(url: string) {\n\t\tif (!this.baseUrl) {\n\t\t\tthrow new Error('SwiftClient not initialized');\n\t\t}\n\n\t\treturn new Promise<{ success: boolean; body: string; status: number }>(\n\t\t\t(res) => {\n\t\t\t\tconst headers = new Headers({\n\t\t\t\t\t...this.getSwiftHeaders(),\n\t\t\t\t});\n\n\t\t\t\tfetch(`${this.baseUrl}${url}`, {\n\t\t\t\t\theaders,\n\t\t\t\t})\n\t\t\t\t\t.then(async (response) => {\n\t\t\t\t\t\tif (!response.ok) {\n\t\t\t\t\t\t\tres({\n\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\tbody: await response.text(),\n\t\t\t\t\t\t\t\tstatus: response.status,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tres({\n\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\tbody: await response.text(),\n\t\t\t\t\t\t\tstatus: response.status,\n\t\t\t\t\t\t});\n\t\t\t\t\t})\n\t\t\t\t\t.catch((err) => {\n\t\t\t\t\t\tres({ success: false, body: err, status: 0 });\n\t\t\t\t\t});\n\t\t\t}\n\t\t);\n\t}\n\n\tprivate static post(url: string, bodyObject: any) {\n\t\tif (!this.baseUrl) {\n\t\t\tthrow new Error('SwiftClient not initialized');\n\t\t}\n\n\t\tconst requestOptions = {\n\t\t\tmethod: 'POST',\n\t\t\theaders: { ...this.getSwiftHeaders() },\n\t\t\tbody: JSON.stringify(bodyObject),\n\t\t};\n\n\t\treturn new Promise<{\n\t\t\tsuccess: boolean;\n\t\t\tbody: SwiftServerOrderProcessResponse;\n\t\t\tstatus: number;\n\t\t}>((res) => {\n\t\t\tconst postRequest = new Request(`${this.baseUrl}${url}`, requestOptions);\n\n\t\t\tfetch(postRequest)\n\t\t\t\t.then(async (response) => {\n\t\t\t\t\tlet resBody: SwiftServerOrderProcessResponse | null = null;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tresBody =\n\t\t\t\t\t\t\t(await response.json()) as SwiftServerOrderProcessResponse;\n\n\t\t\t\t\t\tres({\n\t\t\t\t\t\t\tsuccess: response.ok,\n\t\t\t\t\t\t\tbody: resBody,\n\t\t\t\t\t\t\tstatus: response.status,\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tallEnvDlog('swiftClient', 'Error reading response body', err);\n\n\t\t\t\t\t\tres({\n\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\tbody: err as any,\n\t\t\t\t\t\t\tstatus: response.status,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.catch((err) => {\n\t\t\t\t\tres({ success: false, body: err, status: 0 });\n\t\t\t\t});\n\t\t});\n\t}\n\n\tstatic async sendSwiftOrder(\n\t\tmarketIndex: number,\n\t\tmarketType: MarketType,\n\t\tmessage: string,\n\t\tsignature: Buffer,\n\t\ttakerPubkey: PublicKey,\n\t\tsigningAuthority?: PublicKey\n\t): ClientResponse<{\n\t\thash: string;\n\t}> {\n\t\tconst requestPayload = {\n\t\t\tmarket_index: marketIndex,\n\t\t\tmarket_type: isVariant(marketType, 'perp') ? 'perp' : 'spot',\n\t\t\tmessage,\n\t\t\tsignature: signature.toString('base64'),\n\t\t\tsigning_authority: signingAuthority?.toBase58() ?? '',\n\t\t\ttaker_authority: takerPubkey.toBase58(),\n\t\t};\n\n\t\tconst response = await this.post('/orders', requestPayload);\n\n\t\tif (response.status !== 200) {\n\t\t\tconsole.error(\n\t\t\t\t`Non-200 status code received for sent Swift order: ${response.status}`\n\t\t\t);\n\t\t\tallEnvDlog('swiftClient', 'full non-200 response body', response.body);\n\t\t\treturn {\n\t\t\t\tmessage:\n\t\t\t\t\tresponse.body?.error ||\n\t\t\t\t\tresponse.body?.message ||\n\t\t\t\t\t`HTTP ${response.status}: Error from Swift server`,\n\t\t\t\tstatus: response.status,\n\t\t\t\tsuccess: false,\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tmessage: `Successfully sent Swift order`,\n\t\t\tbody: {\n\t\t\t\thash: digestSignature(Uint8Array.from(signature)),\n\t\t\t},\n\t\t\tsuccess: true,\n\t\t\tstatus: 200,\n\t\t};\n\t}\n\n\tstatic async confirmSwiftOrderWS(\n\t\tconnection: Connection,\n\t\tclient: DriftClient,\n\t\tsignedMsgUserOrdersAccount: PublicKey,\n\t\tsignedMsgOrderUuid: Uint8Array,\n\t\tconfirmDuration: number\n\t): Promise<number | undefined> {\n\t\tallEnvDlog(\n\t\t\t'swiftClient',\n\t\t\t'confirmSwiftOrderWS - confirmation duration',\n\t\t\tconfirmDuration\n\t\t);\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\treject(new Error('Order not found'));\n\t\t\t}, confirmDuration);\n\n\t\t\tconnection\n\t\t\t\t.getAccountInfo(signedMsgUserOrdersAccount, 'confirmed')\n\t\t\t\t.then((accountInfo) => {\n\t\t\t\t\tif (!accountInfo) {\n\t\t\t\t\t\treject(new Error('Swift message account not found'));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst order = this.findOrderInSignedMsgUserOrdersAccount(\n\t\t\t\t\t\tclient,\n\t\t\t\t\t\taccountInfo,\n\t\t\t\t\t\tsignedMsgOrderUuid\n\t\t\t\t\t);\n\n\t\t\t\t\tif (order) {\n\t\t\t\t\t\tallEnvDlog(\n\t\t\t\t\t\t\t'swiftClient',\n\t\t\t\t\t\t\t'confirmed in initial fetch orderID\\n',\n\t\t\t\t\t\t\torder.orderId\n\t\t\t\t\t\t);\n\t\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\t\tresolve(order.orderId);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\tconst subId = connection.onAccountChange(\n\t\t\t\tsignedMsgUserOrdersAccount,\n\t\t\t\t(accountInfo) => {\n\t\t\t\t\tconst order = this.findOrderInSignedMsgUserOrdersAccount(\n\t\t\t\t\t\tclient,\n\t\t\t\t\t\taccountInfo,\n\t\t\t\t\t\tsignedMsgOrderUuid\n\t\t\t\t\t);\n\t\t\t\t\tif (order) {\n\t\t\t\t\t\tallEnvDlog(\n\t\t\t\t\t\t\t'swiftClient',\n\t\t\t\t\t\t\t'confirmed in onAccountChange orderID\\n',\n\t\t\t\t\t\t\torder.orderId\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconnection.removeAccountChangeListener(subId);\n\t\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\t\tresolve(order.orderId);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t'confirmed'\n\t\t\t);\n\t\t});\n\t}\n\n\tstatic findOrderInSignedMsgUserOrdersAccount(\n\t\tclient: DriftClient,\n\t\tordersAccount: AccountInfo<Buffer>,\n\t\tsignedMsgOrderUuid: Uint8Array\n\t) {\n\t\tconst accountDecoder =\n\t\t\tclient.program.account.signedMsgUserOrders.coder.accounts.decodeUnchecked.bind(\n\t\t\t\tclient.program.account.signedMsgUserOrders.coder.accounts\n\t\t\t);\n\t\tconst decodedAccount = accountDecoder(\n\t\t\t'SignedMsgUserOrders',\n\t\t\tordersAccount.data\n\t\t) as SignedMsgUserOrdersAccount;\n\t\tallEnvDlog(\n\t\t\t'swiftClient findOrder',\n\t\t\t'decodedAccount\\n',\n\t\t\tdecodedAccount,\n\t\t\tsignedMsgOrderUuid.toString()\n\t\t);\n\t\tconst order = decodedAccount.signedMsgOrderData.find(\n\t\t\t(order) => order.uuid.toString() === signedMsgOrderUuid.toString()\n\t\t);\n\t\tallEnvDlog('swiftClient findOrder', 'order\\n', order);\n\t\treturn order;\n\t}\n\n\tstatic async confirmSwiftOrder(\n\t\thash: string,\n\t\tconfirmDuration: number\n\t): Promise<\n\t\tClientResponse<\n\t\t\t| {\n\t\t\t\t\torderId: string;\n\t\t\t\t\tstatus: 'confirmed';\n\t\t\t }\n\t\t\t| {\n\t\t\t\t\tstatus: 'expired';\n\t\t\t }\n\t\t>\n\t> {\n\t\tconst expireTime = Date.now() + confirmDuration;\n\n\t\twhile (Date.now() < expireTime) {\n\t\t\tconst confirmResponse = await this.get(\n\t\t\t\t`/confirmation/hash-status?hash=${encodeURIComponent(hash)}`\n\t\t\t);\n\n\t\t\tif (confirmResponse.status === 200) {\n\t\t\t\tconsole.log('Confirmed hash: ', hash);\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\tstatus: 200,\n\t\t\t\t\tmessage: 'Confirmed hash: ' + hash,\n\t\t\t\t\tbody: {\n\t\t\t\t\t\torderId: confirmResponse.body,\n\t\t\t\t\t\tstatus: 'confirmed',\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} else if (\n\t\t\t\tconfirmResponse.status >= 500 ||\n\t\t\t\tconfirmResponse.status < 200\n\t\t\t) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, 1000));\n\t\t}\n\n\t\tconsole.error('Failed to confirm hash: ', hash);\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tstatus: 408,\n\t\t\tmessage: 'Failed to confirm hash: ' + hash,\n\t\t\tbody: {\n\t\t\t\tstatus: 'expired',\n\t\t\t},\n\t\t};\n\t}\n\n\tstatic async handleSwiftOrderSubscriber(\n\t\tsubscriber: Subscriber<SwiftOrderEvent>,\n\t\tmarketIndex: number,\n\t\tmarketType: MarketType,\n\t\tmessage: string,\n\t\tsignature: Buffer,\n\t\ttakerPubkey: PublicKey,\n\t\tconfirmDuration: number,\n\t\tsigningAuthority?: PublicKey\n\t) {\n\t\t// First send the order\n\t\tconst sendResponse = await this.sendSwiftOrder(\n\t\t\tmarketIndex,\n\t\t\tmarketType,\n\t\t\tmessage,\n\t\t\tsignature,\n\t\t\ttakerPubkey,\n\t\t\tsigningAuthority\n\t\t);\n\n\t\tif (!sendResponse.success) {\n\t\t\tsubscriber.next({\n\t\t\t\ttype: 'errored',\n\t\t\t\thash: '',\n\t\t\t\tmessage: sendResponse.message,\n\t\t\t\tstatus: sendResponse.status,\n\t\t\t});\n\t\t\tsubscriber.error();\n\t\t\treturn;\n\t\t} else {\n\t\t\tsubscriber.next({\n\t\t\t\ttype: 'sent',\n\t\t\t\thash: sendResponse.body.hash,\n\t\t\t});\n\t\t}\n\n\t\tconst hash = sendResponse.body.hash;\n\n\t\t// Then confirm it\n\t\tconst confirmResponse = await this.confirmSwiftOrder(hash, confirmDuration);\n\n\t\tif (!confirmResponse.success) {\n\t\t\tsubscriber.next({\n\t\t\t\ttype: confirmResponse.body.status as 'expired',\n\t\t\t\thash,\n\t\t\t\tmessage: confirmResponse.message,\n\t\t\t\tstatus: confirmResponse.status,\n\t\t\t});\n\t\t\tsubscriber.error();\n\t\t}\n\t\tif (confirmResponse.body.status === 'confirmed') {\n\t\t\tsubscriber.next({\n\t\t\t\ttype: 'confirmed',\n\t\t\t\torderId: confirmResponse.body.orderId,\n\t\t\t\thash,\n\t\t\t});\n\t\t\tsubscriber.complete();\n\t\t}\n\t}\n\tstatic async handleSwiftOrderSubscriberWS(\n\t\tsubscriber: Subscriber<SwiftOrderEvent>,\n\t\tconnection: Connection,\n\t\tclient: DriftClient,\n\t\tmarketIndex: number,\n\t\tmarketType: MarketType,\n\t\tmessage: string,\n\t\tsignature: Buffer,\n\t\ttakerPubkey: PublicKey,\n\t\tsignedMsgUserOrdersAccountPubkey: PublicKey,\n\t\tsignedMsgOrderUuid: Uint8Array,\n\t\tconfirmDuration: number,\n\t\tsigningAuthority?: PublicKey\n\t) {\n\t\t// First send the order\n\t\tconst sendResponse = await this.sendSwiftOrder(\n\t\t\tmarketIndex,\n\t\t\tmarketType,\n\t\t\tmessage,\n\t\t\tsignature,\n\t\t\ttakerPubkey,\n\t\t\tsigningAuthority\n\t\t);\n\t\tallEnvDlog('swiftClient', 'sendResponse\\n', sendResponse);\n\n\t\tif (!sendResponse.success) {\n\t\t\tsubscriber.next({\n\t\t\t\ttype: 'errored',\n\t\t\t\thash: '',\n\t\t\t\tmessage: 'Error from swift node: ' + sendResponse.message,\n\t\t\t\tstatus: sendResponse.status,\n\t\t\t});\n\t\t\tsubscriber.error();\n\t\t\treturn;\n\t\t} else {\n\t\t\tsubscriber.next({\n\t\t\t\ttype: 'sent',\n\t\t\t\thash: sendResponse.body.hash,\n\t\t\t});\n\t\t}\n\n\t\tconst hash = sendResponse.body.hash;\n\n\t\t// Then confirm it\n\t\tconst orderID = await this.confirmSwiftOrderWS(\n\t\t\tconnection,\n\t\t\tclient,\n\t\t\tsignedMsgUserOrdersAccountPubkey,\n\t\t\tsignedMsgOrderUuid,\n\t\t\tconfirmDuration\n\t\t).catch((err) => {\n\t\t\tallEnvDlog('swiftClient', 'confirmSwiftOrderWS error', err);\n\t\t\tsubscriber.next({\n\t\t\t\ttype: 'expired',\n\t\t\t\thash,\n\t\t\t\tmessage: 'Order failed to confirm',\n\t\t\t\tstatus: 408,\n\t\t\t});\n\t\t\tsubscriber.error();\n\t\t});\n\n\t\tif (!orderID) {\n\t\t\tsubscriber.next({\n\t\t\t\ttype: 'expired',\n\t\t\t\thash,\n\t\t\t\tmessage: 'Order failed to confirm',\n\t\t\t\tstatus: 408,\n\t\t\t});\n\t\t\tsubscriber.error();\n\t\t} else {\n\t\t\tsubscriber.next({\n\t\t\t\ttype: 'confirmed',\n\t\t\t\torderId: orderID.toString(),\n\t\t\t\thash,\n\t\t\t});\n\t\t\tsubscriber.complete();\n\t\t}\n\t}\n\n\tpublic static sendAndConfirmSwiftOrder(\n\t\tmarketIndex: number,\n\t\tmarketType: MarketType,\n\t\tmessage: string,\n\t\tsignature: Buffer,\n\t\ttakerPubkey: PublicKey,\n\t\tconfirmDuration: number,\n\t\tsigningAuthority: PublicKey\n\t): Observable<SwiftOrderEvent> {\n\t\treturn new Observable<SwiftOrderEvent>((subscriber) => {\n\t\t\tthis.handleSwiftOrderSubscriber(\n\t\t\t\tsubscriber,\n\t\t\t\tmarketIndex,\n\t\t\t\tmarketType,\n\t\t\t\tmessage,\n\t\t\t\tsignature,\n\t\t\t\ttakerPubkey,\n\t\t\t\tconfirmDuration,\n\t\t\t\tsigningAuthority\n\t\t\t);\n\t\t});\n\t}\n\n\tpublic static sendAndConfirmSwiftOrderWS(\n\t\tconnection: Connection,\n\t\tclient: DriftClient,\n\t\tmarketIndex: number,\n\t\tmarketType: MarketType,\n\t\tmessage: string,\n\t\tsignature: Buffer,\n\t\ttakerPubkey: PublicKey,\n\t\tsignedMsgUserOrdersAccountPubkey: PublicKey,\n\t\tsignedMsgOrderUuid: Uint8Array,\n\t\tconfirmDuration: number,\n\t\tsigningAuthority: PublicKey\n\t): Observable<SwiftOrderEvent> {\n\t\treturn new Observable<SwiftOrderEvent>((subscriber) => {\n\t\t\tthis.handleSwiftOrderSubscriberWS(\n\t\t\t\tsubscriber,\n\t\t\t\tconnection,\n\t\t\t\tclient,\n\t\t\t\tmarketIndex,\n\t\t\t\tmarketType,\n\t\t\t\tmessage,\n\t\t\t\tsignature,\n\t\t\t\ttakerPubkey,\n\t\t\t\tsignedMsgUserOrdersAccountPubkey,\n\t\t\t\tsignedMsgOrderUuid,\n\t\t\t\tconfirmDuration,\n\t\t\t\tsigningAuthority\n\t\t\t);\n\t\t});\n\t}\n\n\tpublic static async isSwiftServerHealthy(): Promise<boolean> {\n\t\tconst response = await this.get('/health');\n\t\treturn response.status === 200;\n\t}\n\n\tprivate static getSwiftHeaders(): Record<string, string> {\n\t\treturn {\n\t\t\t'Content-Type': 'application/json',\n\t\t\t'X-Swift-Client-Consumer': this.swiftClientConsumer ?? 'default',\n\t\t};\n\t}\n\n\tpublic static isSupportedOrderType(orderType: OrderType) {\n\t\treturn this.supportedOrderTypes.includes(orderType);\n\t}\n}\n"]}
|
|
@@ -9,7 +9,10 @@ export declare const COMMON_UI_UTILS: {
|
|
|
9
9
|
isAuctionEmpty: (auctionParams: AuctionParams) => boolean;
|
|
10
10
|
getUIOrderTypeFromSdkOrderType: (orderType: OrderType, triggerCondition: import("@drift-labs/sdk").OrderTriggerCondition, direction: PositionDirection, oracleOffset: BigNum) => import("src/types").UIOrderTypeValue;
|
|
11
11
|
getPerpAuctionDuration: (priceDiff: BN, price: BN, contractTier: import("@drift-labs/sdk").ContractTier) => number;
|
|
12
|
-
getPerpOrderParamsBitFlags: (marketIndex: number, driftClient: DriftClient, userAccount: User, quoteSize: BN, side: PositionDirection,
|
|
12
|
+
getPerpOrderParamsBitFlags: (marketIndex: number, driftClient: DriftClient, userAccount: User, quoteSize: BN, side: PositionDirection, highLeverageOptions?: {
|
|
13
|
+
numOfOpenHighLeverageSpots?: number;
|
|
14
|
+
enterHighLeverageModeBufferPct?: number;
|
|
15
|
+
}) => number;
|
|
13
16
|
getBaseAssetSymbol: (marketName: string, removePrefix?: boolean) => string;
|
|
14
17
|
getPausedOperations: (marketAccount: import("@drift-labs/sdk").SpotMarketAccount | import("@drift-labs/sdk").PerpMarketAccount) => string[];
|
|
15
18
|
PerpOperationsMap: {
|
|
@@ -43,6 +46,11 @@ export declare const COMMON_UI_UTILS: {
|
|
|
43
46
|
highLeverageMaxLeverage: number;
|
|
44
47
|
hasHighLeverage: boolean;
|
|
45
48
|
};
|
|
49
|
+
getMaxLeverageForMarketAccount: (marketType: MarketType, marketAccount: import("@drift-labs/sdk").SpotMarketAccount | import("@drift-labs/sdk").PerpMarketAccount) => {
|
|
50
|
+
maxLeverage: number;
|
|
51
|
+
highLeverageMaxLeverage: number;
|
|
52
|
+
hasHighLeverage: boolean;
|
|
53
|
+
};
|
|
46
54
|
calculatePnlPctFromPosition: (pnl: BN, position: import("src/types").OpenPosition, marginUsed?: BN) => number;
|
|
47
55
|
calculatePotentialProfit: (props: {
|
|
48
56
|
currentPositionSize: BigNum;
|
|
@@ -98,12 +106,17 @@ export declare const COMMON_UI_UTILS: {
|
|
|
98
106
|
subAccountId: number;
|
|
99
107
|
authority: PublicKey;
|
|
100
108
|
}) => Promise<boolean>;
|
|
109
|
+
getUserMaxLeverageForMarket: (user: User, marketIndex: number, marketLeverageDetails: {
|
|
110
|
+
regularMaxLeverage: number;
|
|
111
|
+
highLeverageMaxLeverage: number;
|
|
112
|
+
hasHighLeverage: boolean;
|
|
113
|
+
}, uiSavedMaxLeverage?: number) => number;
|
|
101
114
|
abbreviateAddress: (address: string | PublicKey, length?: number) => string;
|
|
102
115
|
calculateAverageEntryPrice: (quoteAssetAmount: BigNum, baseAssetAmount: BigNum) => BigNum;
|
|
103
116
|
chunks: typeof chunks;
|
|
104
117
|
compareSignatures: (original: string, hashed: string) => Promise<boolean>;
|
|
105
118
|
createPlaceholderIWallet: (walletPubKey?: PublicKey) => IWalletV2;
|
|
106
|
-
deriveMarketOrderParams: ({ marketType, marketIndex, direction, maxLeverageSelected, maxLeverageOrderSize, baseAmount, reduceOnly, allowInfSlippage, oraclePrice, bestPrice, entryPrice, worstPrice, markPrice, auctionDuration, auctionStartPriceOffset, auctionEndPriceOffset, auctionStartPriceOffsetFrom, auctionEndPriceOffsetFrom, auctionPriceCaps, slippageTolerance, isOracleOrder, additionalEndPriceBuffer, forceUpToSlippage, }: {
|
|
119
|
+
deriveMarketOrderParams: ({ marketType, marketIndex, direction, maxLeverageSelected, maxLeverageOrderSize, baseAmount, reduceOnly, allowInfSlippage, oraclePrice, bestPrice, entryPrice, worstPrice, markPrice, auctionDuration, auctionStartPriceOffset, auctionEndPriceOffset, auctionStartPriceOffsetFrom, auctionEndPriceOffsetFrom, auctionPriceCaps, slippageTolerance, isOracleOrder, additionalEndPriceBuffer, forceUpToSlippage, bestBidPrice, bestAskPrice, ensureCrossingEndPrice, }: {
|
|
107
120
|
marketType: MarketType;
|
|
108
121
|
marketIndex: number;
|
|
109
122
|
direction: PositionDirection;
|
|
@@ -130,6 +143,9 @@ export declare const COMMON_UI_UTILS: {
|
|
|
130
143
|
isOracleOrder?: boolean;
|
|
131
144
|
additionalEndPriceBuffer?: BN;
|
|
132
145
|
forceUpToSlippage?: boolean;
|
|
146
|
+
bestBidPrice?: BN;
|
|
147
|
+
bestAskPrice?: BN;
|
|
148
|
+
ensureCrossingEndPrice?: boolean;
|
|
133
149
|
}) => OptionalOrderParams & {
|
|
134
150
|
constrainedBySlippage?: boolean;
|
|
135
151
|
};
|
|
@@ -156,7 +172,7 @@ export declare const COMMON_UI_UTILS: {
|
|
|
156
172
|
oraclePriceBands?: [BN, BN];
|
|
157
173
|
}) => AuctionParams;
|
|
158
174
|
getLpSharesAmountForQuote: (driftClient: DriftClient, marketIndex: number, quoteAmount: BN) => BigNum;
|
|
159
|
-
getMarketAuctionParams: ({ direction, startPriceFromSettings, endPriceFromSettings, limitPrice, duration, auctionStartPriceOffset, auctionEndPriceOffset, additionalEndPriceBuffer, forceUpToSlippage, }: {
|
|
175
|
+
getMarketAuctionParams: ({ direction, startPriceFromSettings, endPriceFromSettings, limitPrice, duration, auctionStartPriceOffset, auctionEndPriceOffset, additionalEndPriceBuffer, forceUpToSlippage, bestBidPrice, bestAskPrice, ensureCrossingEndPrice, }: {
|
|
160
176
|
direction: PositionDirection;
|
|
161
177
|
startPriceFromSettings: BN;
|
|
162
178
|
endPriceFromSettings: BN;
|
|
@@ -170,6 +186,9 @@ export declare const COMMON_UI_UTILS: {
|
|
|
170
186
|
auctionEndPriceOffset: number;
|
|
171
187
|
additionalEndPriceBuffer?: BN;
|
|
172
188
|
forceUpToSlippage?: boolean;
|
|
189
|
+
bestBidPrice?: BN;
|
|
190
|
+
bestAskPrice?: BN;
|
|
191
|
+
ensureCrossingEndPrice?: boolean;
|
|
173
192
|
}) => AuctionParams;
|
|
174
193
|
getMarketKey: (marketIndex: number, marketType: MarketType) => string;
|
|
175
194
|
getMarketOrderLimitPrice: ({ direction, baselinePrice, slippageTolerance, }: {
|
|
@@ -242,7 +242,7 @@ const getMarketOrderLimitPrice = ({ direction, baselinePrice, slippageTolerance,
|
|
|
242
242
|
}
|
|
243
243
|
return limitPrice;
|
|
244
244
|
};
|
|
245
|
-
const getMarketAuctionParams = ({ direction, startPriceFromSettings, endPriceFromSettings, limitPrice, duration, auctionStartPriceOffset, auctionEndPriceOffset, additionalEndPriceBuffer, forceUpToSlippage, }) => {
|
|
245
|
+
const getMarketAuctionParams = ({ direction, startPriceFromSettings, endPriceFromSettings, limitPrice, duration, auctionStartPriceOffset, auctionEndPriceOffset, additionalEndPriceBuffer, forceUpToSlippage, bestBidPrice, bestAskPrice, ensureCrossingEndPrice, }) => {
|
|
246
246
|
let auctionStartPrice;
|
|
247
247
|
let auctionEndPrice;
|
|
248
248
|
let constrainedBySlippage;
|
|
@@ -269,6 +269,10 @@ const getMarketAuctionParams = ({ direction, startPriceFromSettings, endPriceFro
|
|
|
269
269
|
auctionEndPrice = auctionEndPrice.add(additionalEndPriceBuffer);
|
|
270
270
|
constrainedBySlippage = limitPrice.lt(auctionEndPrice);
|
|
271
271
|
}
|
|
272
|
+
// if ensureCrossingEndPrice is passed, ensure auction end price crosses bestAskPrice
|
|
273
|
+
if (ensureCrossingEndPrice && bestAskPrice) {
|
|
274
|
+
auctionEndPrice = sdk_1.BN.max(auctionEndPrice, bestAskPrice.add(auctionEndPriceBuffer));
|
|
275
|
+
}
|
|
272
276
|
auctionStartPrice = sdk_1.BN.min(auctionStartPrice, auctionEndPrice);
|
|
273
277
|
}
|
|
274
278
|
else {
|
|
@@ -292,6 +296,10 @@ const getMarketAuctionParams = ({ direction, startPriceFromSettings, endPriceFro
|
|
|
292
296
|
auctionEndPrice = auctionEndPrice.sub(additionalEndPriceBuffer);
|
|
293
297
|
constrainedBySlippage = limitPrice.gt(auctionEndPrice);
|
|
294
298
|
}
|
|
299
|
+
// if ensureCrossingEndPrice is passed, ensure auction end price crosses bestBidPrice
|
|
300
|
+
if (ensureCrossingEndPrice && bestBidPrice) {
|
|
301
|
+
auctionEndPrice = sdk_1.BN.min(auctionEndPrice, bestBidPrice.sub(auctionEndPriceBuffer));
|
|
302
|
+
}
|
|
295
303
|
auctionStartPrice = sdk_1.BN.max(auctionStartPrice, auctionEndPrice);
|
|
296
304
|
}
|
|
297
305
|
return {
|
|
@@ -306,7 +314,7 @@ const getMarketAuctionParams = ({ direction, startPriceFromSettings, endPriceFro
|
|
|
306
314
|
* @param param0
|
|
307
315
|
* @returns
|
|
308
316
|
*/
|
|
309
|
-
const deriveMarketOrderParams = ({ marketType, marketIndex, direction, maxLeverageSelected, maxLeverageOrderSize, baseAmount, reduceOnly, allowInfSlippage, oraclePrice, bestPrice, entryPrice, worstPrice, markPrice, auctionDuration, auctionStartPriceOffset, auctionEndPriceOffset, auctionStartPriceOffsetFrom, auctionEndPriceOffsetFrom, auctionPriceCaps, slippageTolerance, isOracleOrder, additionalEndPriceBuffer, forceUpToSlippage, }) => {
|
|
317
|
+
const deriveMarketOrderParams = ({ marketType, marketIndex, direction, maxLeverageSelected, maxLeverageOrderSize, baseAmount, reduceOnly, allowInfSlippage, oraclePrice, bestPrice, entryPrice, worstPrice, markPrice, auctionDuration, auctionStartPriceOffset, auctionEndPriceOffset, auctionStartPriceOffsetFrom, auctionEndPriceOffsetFrom, auctionPriceCaps, slippageTolerance, isOracleOrder, additionalEndPriceBuffer, forceUpToSlippage, bestBidPrice, bestAskPrice, ensureCrossingEndPrice, }) => {
|
|
310
318
|
const priceObject = getPriceObject({
|
|
311
319
|
oraclePrice,
|
|
312
320
|
markPrice,
|
|
@@ -336,6 +344,9 @@ const deriveMarketOrderParams = ({ marketType, marketIndex, direction, maxLevera
|
|
|
336
344
|
auctionEndPriceOffset: auctionEndPriceOffset,
|
|
337
345
|
additionalEndPriceBuffer,
|
|
338
346
|
forceUpToSlippage,
|
|
347
|
+
bestBidPrice,
|
|
348
|
+
bestAskPrice,
|
|
349
|
+
ensureCrossingEndPrice,
|
|
339
350
|
});
|
|
340
351
|
let orderParams = (0, sdk_1.getMarketOrderParams)({
|
|
341
352
|
marketType,
|
|
@@ -349,16 +360,12 @@ const deriveMarketOrderParams = ({ marketType, marketIndex, direction, maxLevera
|
|
|
349
360
|
if (isOracleOrder) {
|
|
350
361
|
// wont work if oracle is zero
|
|
351
362
|
if (!oraclePrice.eq(sdk_1.ZERO)) {
|
|
352
|
-
// BEST (slippageLimitPrice, auctionEndPrice)
|
|
353
|
-
const oracleAuctionEndPrice = (0, sdk_1.isVariant)(direction, 'long')
|
|
354
|
-
? sdk_1.BN.min(limitPrice, auctionParams.auctionEndPrice)
|
|
355
|
-
: sdk_1.BN.max(limitPrice, auctionParams.auctionEndPrice);
|
|
356
363
|
const oracleAuctionParams = (0, sdk_1.deriveOracleAuctionParams)({
|
|
357
364
|
direction: direction,
|
|
358
365
|
oraclePrice,
|
|
359
366
|
auctionStartPrice: auctionParams.auctionStartPrice,
|
|
360
|
-
auctionEndPrice:
|
|
361
|
-
limitPrice:
|
|
367
|
+
auctionEndPrice: auctionParams.auctionEndPrice,
|
|
368
|
+
limitPrice: auctionParams.auctionEndPrice,
|
|
362
369
|
auctionPriceCaps: auctionPriceCaps,
|
|
363
370
|
});
|
|
364
371
|
orderParams = {
|