@drift-labs/sdk 2.49.0-beta.8 → 2.52.0-beta.0
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/VERSION +1 -1
- package/lib/accounts/{mockUserAccountSubscriber.d.ts → basicUserAccountSubscriber.d.ts} +2 -2
- package/lib/accounts/{mockUserAccountSubscriber.js → basicUserAccountSubscriber.js} +9 -6
- package/lib/accounts/pollingInsuranceFundStakeAccountSubscriber.js +0 -1
- package/lib/adminClient.d.ts +1 -0
- package/lib/adminClient.js +8 -0
- package/lib/constants/perpMarkets.js +40 -0
- package/lib/constants/spotMarkets.js +10 -0
- package/lib/decode/user.d.ts +3 -0
- package/lib/decode/user.js +329 -0
- package/lib/driftClient.d.ts +5 -1
- package/lib/driftClient.js +28 -7
- package/lib/examples/loadDlob.js +10 -5
- package/lib/idl/drift.json +32 -2
- package/lib/index.d.ts +2 -1
- package/lib/index.js +2 -1
- package/lib/math/state.d.ts +5 -0
- package/lib/math/state.js +27 -0
- package/lib/math/superStake.d.ts +43 -0
- package/lib/math/superStake.js +64 -22
- package/lib/orderSubscriber/OrderSubscriber.d.ts +3 -0
- package/lib/orderSubscriber/OrderSubscriber.js +17 -3
- package/lib/orderSubscriber/WebsocketSubscription.d.ts +1 -1
- package/lib/orderSubscriber/WebsocketSubscription.js +8 -6
- package/lib/orderSubscriber/types.d.ts +4 -1
- package/lib/types.d.ts +2 -1
- package/lib/user.d.ts +2 -1
- package/lib/user.js +13 -5
- package/lib/userMap/PollingSubscription.d.ts +15 -0
- package/lib/userMap/PollingSubscription.js +28 -0
- package/lib/userMap/WebsocketSubscription.d.ts +23 -0
- package/lib/userMap/WebsocketSubscription.js +41 -0
- package/lib/userMap/userMap.d.ts +16 -18
- package/lib/userMap/userMap.js +73 -34
- package/lib/userMap/userMapConfig.d.ts +21 -0
- package/lib/userMap/userMapConfig.js +2 -0
- package/package.json +2 -1
- package/src/accounts/{mockUserAccountSubscriber.ts → basicUserAccountSubscriber.ts} +8 -6
- package/src/accounts/pollingInsuranceFundStakeAccountSubscriber.ts +0 -1
- package/src/adminClient.ts +14 -0
- package/src/constants/perpMarkets.ts +40 -0
- package/src/constants/spotMarkets.ts +10 -0
- package/src/decode/user.ts +358 -0
- package/src/driftClient.ts +48 -7
- package/src/examples/loadDlob.ts +11 -6
- package/src/idl/drift.json +33 -3
- package/src/index.ts +2 -1
- package/src/math/state.ts +26 -0
- package/src/math/superStake.ts +108 -20
- package/src/orderSubscriber/OrderSubscriber.ts +33 -7
- package/src/orderSubscriber/WebsocketSubscription.ts +17 -16
- package/src/orderSubscriber/types.ts +15 -2
- package/src/types.ts +2 -1
- package/src/user.ts +19 -6
- package/src/userMap/PollingSubscription.ts +48 -0
- package/src/userMap/WebsocketSubscription.ts +76 -0
- package/src/userMap/userMap.ts +103 -70
- package/src/userMap/userMapConfig.ts +34 -0
- package/tests/amm/test.ts +6 -3
- package/tests/decode/test.ts +266 -0
- package/tests/decode/userAccountBufferStrings.ts +102 -0
- package/tests/dlob/helpers.ts +1 -0
- package/tests/dlob/test.ts +10 -8
- package/tests/user/helpers.ts +0 -1
package/lib/index.d.ts
CHANGED
|
@@ -19,7 +19,7 @@ export * from './accounts/pollingTokenAccountSubscriber';
|
|
|
19
19
|
export * from './accounts/pollingUserAccountSubscriber';
|
|
20
20
|
export * from './accounts/pollingUserStatsAccountSubscriber';
|
|
21
21
|
export * from './accounts/pollingInsuranceFundStakeAccountSubscriber';
|
|
22
|
-
export * from './accounts/
|
|
22
|
+
export * from './accounts/basicUserAccountSubscriber';
|
|
23
23
|
export * from './accounts/types';
|
|
24
24
|
export * from './addresses/pda';
|
|
25
25
|
export * from './adminClient';
|
|
@@ -55,6 +55,7 @@ export * from './math/margin';
|
|
|
55
55
|
export * from './math/insurance';
|
|
56
56
|
export * from './math/superStake';
|
|
57
57
|
export * from './math/spotPosition';
|
|
58
|
+
export * from './math/state';
|
|
58
59
|
export * from './marinade';
|
|
59
60
|
export * from './orderParams';
|
|
60
61
|
export * from './slot/SlotSubscriber';
|
package/lib/index.js
CHANGED
|
@@ -42,7 +42,7 @@ __exportStar(require("./accounts/pollingTokenAccountSubscriber"), exports);
|
|
|
42
42
|
__exportStar(require("./accounts/pollingUserAccountSubscriber"), exports);
|
|
43
43
|
__exportStar(require("./accounts/pollingUserStatsAccountSubscriber"), exports);
|
|
44
44
|
__exportStar(require("./accounts/pollingInsuranceFundStakeAccountSubscriber"), exports);
|
|
45
|
-
__exportStar(require("./accounts/
|
|
45
|
+
__exportStar(require("./accounts/basicUserAccountSubscriber"), exports);
|
|
46
46
|
__exportStar(require("./accounts/types"), exports);
|
|
47
47
|
__exportStar(require("./addresses/pda"), exports);
|
|
48
48
|
__exportStar(require("./adminClient"), exports);
|
|
@@ -78,6 +78,7 @@ __exportStar(require("./math/margin"), exports);
|
|
|
78
78
|
__exportStar(require("./math/insurance"), exports);
|
|
79
79
|
__exportStar(require("./math/superStake"), exports);
|
|
80
80
|
__exportStar(require("./math/spotPosition"), exports);
|
|
81
|
+
__exportStar(require("./math/state"), exports);
|
|
81
82
|
__exportStar(require("./marinade"), exports);
|
|
82
83
|
__exportStar(require("./orderParams"), exports);
|
|
83
84
|
__exportStar(require("./slot/SlotSubscriber"), exports);
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getMaxNumberOfSubAccounts = exports.calculateInitUserFee = void 0;
|
|
4
|
+
const __1 = require("../");
|
|
5
|
+
function calculateInitUserFee(stateAccount) {
|
|
6
|
+
const maxInitFee = new __1.BN(stateAccount.maxInitializeUserFee)
|
|
7
|
+
.mul(__1.LAMPORTS_PRECISION)
|
|
8
|
+
.divn(100);
|
|
9
|
+
const targetUtilization = __1.PERCENTAGE_PRECISION.muln(8).divn(10);
|
|
10
|
+
const accountSpaceUtilization = stateAccount.numberOfSubAccounts
|
|
11
|
+
.addn(1)
|
|
12
|
+
.mul(__1.PERCENTAGE_PRECISION)
|
|
13
|
+
.div(getMaxNumberOfSubAccounts(stateAccount));
|
|
14
|
+
if (accountSpaceUtilization.gt(targetUtilization)) {
|
|
15
|
+
return maxInitFee
|
|
16
|
+
.mul(accountSpaceUtilization.sub(targetUtilization))
|
|
17
|
+
.div(__1.PERCENTAGE_PRECISION.sub(targetUtilization));
|
|
18
|
+
}
|
|
19
|
+
else {
|
|
20
|
+
return __1.ZERO;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
exports.calculateInitUserFee = calculateInitUserFee;
|
|
24
|
+
function getMaxNumberOfSubAccounts(stateAccount) {
|
|
25
|
+
return new __1.BN(stateAccount.maxNumberOfSubAccounts).muln(100);
|
|
26
|
+
}
|
|
27
|
+
exports.getMaxNumberOfSubAccounts = getMaxNumberOfSubAccounts;
|
package/lib/math/superStake.d.ts
CHANGED
|
@@ -5,6 +5,30 @@ import { DriftClient } from '../driftClient';
|
|
|
5
5
|
import { BN } from '@coral-xyz/anchor';
|
|
6
6
|
import { User } from '../user';
|
|
7
7
|
import { DepositRecord } from '../types';
|
|
8
|
+
export type BSOL_STATS_API_RESPONSE = {
|
|
9
|
+
success: boolean;
|
|
10
|
+
stats?: {
|
|
11
|
+
conversion: {
|
|
12
|
+
bsol_to_sol: number;
|
|
13
|
+
sol_to_bsol: number;
|
|
14
|
+
};
|
|
15
|
+
apy: {
|
|
16
|
+
base: number;
|
|
17
|
+
blze: number;
|
|
18
|
+
total: number;
|
|
19
|
+
lending: number;
|
|
20
|
+
liquidity: number;
|
|
21
|
+
};
|
|
22
|
+
};
|
|
23
|
+
};
|
|
24
|
+
export type BSOL_EMISSIONS_API_RESPONSE = {
|
|
25
|
+
success: boolean;
|
|
26
|
+
emissions?: {
|
|
27
|
+
lend: number;
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
export declare function fetchBSolMetrics(): Promise<any>;
|
|
31
|
+
export declare function fetchBSolDriftEmissions(): Promise<any>;
|
|
8
32
|
export declare function findBestSuperStakeIxs({ marketIndex, amount, jupiterClient, driftClient, userAccountPublicKey, price, forceMarinade, onlyDirectRoutes, }: {
|
|
9
33
|
marketIndex: number;
|
|
10
34
|
amount: BN;
|
|
@@ -46,6 +70,25 @@ export declare function findBestJitoSolSuperStakeIxs({ amount, jupiterClient, dr
|
|
|
46
70
|
method: 'jupiter' | 'marinade';
|
|
47
71
|
price: number;
|
|
48
72
|
}>;
|
|
73
|
+
/**
|
|
74
|
+
* Finds best Jupiter Swap instructions for a generic lstMint
|
|
75
|
+
*
|
|
76
|
+
* Without doing any extra steps like checking if you can get a better rate by staking directly with that LST platform
|
|
77
|
+
*/
|
|
78
|
+
export declare function findBestLstSuperStakeIxs({ amount, lstMint, jupiterClient, driftClient, userAccountPublicKey, onlyDirectRoutes, lstMarketIndex, }: {
|
|
79
|
+
amount: BN;
|
|
80
|
+
lstMint: PublicKey;
|
|
81
|
+
lstMarketIndex: number;
|
|
82
|
+
jupiterClient: JupiterClient;
|
|
83
|
+
driftClient: DriftClient;
|
|
84
|
+
userAccountPublicKey?: PublicKey;
|
|
85
|
+
onlyDirectRoutes?: boolean;
|
|
86
|
+
}): Promise<{
|
|
87
|
+
ixs: TransactionInstruction[];
|
|
88
|
+
lookupTables: AddressLookupTableAccount[];
|
|
89
|
+
method: 'jupiter' | 'marinade';
|
|
90
|
+
price: number;
|
|
91
|
+
}>;
|
|
49
92
|
export type JITO_SOL_METRICS_ENDPOINT_RESPONSE = {
|
|
50
93
|
data: {
|
|
51
94
|
getStakePoolStats: {
|
package/lib/math/superStake.js
CHANGED
|
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.calculateEstimatedSuperStakeLiquidationPrice = exports.calculateSolEarned = exports.fetchJitoSolMetrics = exports.findBestJitoSolSuperStakeIxs = exports.findBestMSolSuperStakeIxs = exports.findBestSuperStakeIxs = void 0;
|
|
6
|
+
exports.calculateEstimatedSuperStakeLiquidationPrice = exports.calculateSolEarned = exports.fetchJitoSolMetrics = exports.findBestLstSuperStakeIxs = exports.findBestJitoSolSuperStakeIxs = exports.findBestMSolSuperStakeIxs = exports.findBestSuperStakeIxs = exports.fetchBSolDriftEmissions = exports.fetchBSolMetrics = void 0;
|
|
7
7
|
const web3_js_1 = require("@solana/web3.js");
|
|
8
8
|
const marinade_1 = require("../marinade");
|
|
9
9
|
const anchor_1 = require("@coral-xyz/anchor");
|
|
@@ -11,6 +11,14 @@ const types_1 = require("../types");
|
|
|
11
11
|
const numericConstants_1 = require("../constants/numericConstants");
|
|
12
12
|
const node_fetch_1 = __importDefault(require("node-fetch"));
|
|
13
13
|
const utils_1 = require("./utils");
|
|
14
|
+
async function fetchBSolMetrics() {
|
|
15
|
+
return await (0, node_fetch_1.default)('https://stake.solblaze.org/api/v1/stats');
|
|
16
|
+
}
|
|
17
|
+
exports.fetchBSolMetrics = fetchBSolMetrics;
|
|
18
|
+
async function fetchBSolDriftEmissions() {
|
|
19
|
+
return await (0, node_fetch_1.default)('https://stake.solblaze.org/api/v1/drift_emissions');
|
|
20
|
+
}
|
|
21
|
+
exports.fetchBSolDriftEmissions = fetchBSolDriftEmissions;
|
|
14
22
|
async function findBestSuperStakeIxs({ marketIndex, amount, jupiterClient, driftClient, userAccountPublicKey, price, forceMarinade, onlyDirectRoutes, }) {
|
|
15
23
|
if (marketIndex === 2) {
|
|
16
24
|
return findBestMSolSuperStakeIxs({
|
|
@@ -32,6 +40,17 @@ async function findBestSuperStakeIxs({ marketIndex, amount, jupiterClient, drift
|
|
|
32
40
|
onlyDirectRoutes,
|
|
33
41
|
});
|
|
34
42
|
}
|
|
43
|
+
else if (marketIndex === 8) {
|
|
44
|
+
return findBestLstSuperStakeIxs({
|
|
45
|
+
amount,
|
|
46
|
+
lstMint: driftClient.getSpotMarketAccount(8).mint,
|
|
47
|
+
lstMarketIndex: 8,
|
|
48
|
+
jupiterClient,
|
|
49
|
+
driftClient,
|
|
50
|
+
userAccountPublicKey,
|
|
51
|
+
onlyDirectRoutes,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
35
54
|
else {
|
|
36
55
|
throw new Error(`Unsupported superstake market index: ${marketIndex}`);
|
|
37
56
|
}
|
|
@@ -90,14 +109,30 @@ async function findBestMSolSuperStakeIxs({ amount, jupiterClient, driftClient, u
|
|
|
90
109
|
}
|
|
91
110
|
exports.findBestMSolSuperStakeIxs = findBestMSolSuperStakeIxs;
|
|
92
111
|
async function findBestJitoSolSuperStakeIxs({ amount, jupiterClient, driftClient, userAccountPublicKey, onlyDirectRoutes, }) {
|
|
112
|
+
return await findBestLstSuperStakeIxs({
|
|
113
|
+
amount,
|
|
114
|
+
jupiterClient,
|
|
115
|
+
driftClient,
|
|
116
|
+
userAccountPublicKey,
|
|
117
|
+
onlyDirectRoutes,
|
|
118
|
+
lstMint: driftClient.getSpotMarketAccount(6).mint,
|
|
119
|
+
lstMarketIndex: 6,
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
exports.findBestJitoSolSuperStakeIxs = findBestJitoSolSuperStakeIxs;
|
|
123
|
+
/**
|
|
124
|
+
* Finds best Jupiter Swap instructions for a generic lstMint
|
|
125
|
+
*
|
|
126
|
+
* Without doing any extra steps like checking if you can get a better rate by staking directly with that LST platform
|
|
127
|
+
*/
|
|
128
|
+
async function findBestLstSuperStakeIxs({ amount, lstMint, jupiterClient, driftClient, userAccountPublicKey, onlyDirectRoutes, lstMarketIndex, }) {
|
|
93
129
|
const solMint = driftClient.getSpotMarketAccount(1).mint;
|
|
94
|
-
const JitoSolMint = driftClient.getSpotMarketAccount(6).mint;
|
|
95
130
|
let jupiterPrice;
|
|
96
131
|
let bestRoute;
|
|
97
132
|
try {
|
|
98
133
|
const jupiterRoutes = await jupiterClient.getRoutes({
|
|
99
134
|
inputMint: solMint,
|
|
100
|
-
outputMint:
|
|
135
|
+
outputMint: lstMint,
|
|
101
136
|
amount,
|
|
102
137
|
onlyDirectRoutes,
|
|
103
138
|
});
|
|
@@ -110,7 +145,7 @@ async function findBestJitoSolSuperStakeIxs({ amount, jupiterClient, driftClient
|
|
|
110
145
|
}
|
|
111
146
|
const { ixs, lookupTables } = await driftClient.getJupiterSwapIx({
|
|
112
147
|
inMarketIndex: 1,
|
|
113
|
-
outMarketIndex:
|
|
148
|
+
outMarketIndex: lstMarketIndex,
|
|
114
149
|
route: bestRoute,
|
|
115
150
|
jupiterClient,
|
|
116
151
|
amount,
|
|
@@ -123,7 +158,7 @@ async function findBestJitoSolSuperStakeIxs({ amount, jupiterClient, driftClient
|
|
|
123
158
|
price: jupiterPrice,
|
|
124
159
|
};
|
|
125
160
|
}
|
|
126
|
-
exports.
|
|
161
|
+
exports.findBestLstSuperStakeIxs = findBestLstSuperStakeIxs;
|
|
127
162
|
const JITO_SOL_START_DATE = '2022-10-31T00:00:00Z';
|
|
128
163
|
async function fetchJitoSolMetrics() {
|
|
129
164
|
const res = await (0, node_fetch_1.default)('https://kobe.mainnet.jito.network/', {
|
|
@@ -213,12 +248,30 @@ async function calculateSolEarned({ marketIndex, user, depositRecords, }) {
|
|
|
213
248
|
lstRatios.set(timestamp, data);
|
|
214
249
|
}
|
|
215
250
|
};
|
|
251
|
+
const getBSolPrice = async (timestamps) => {
|
|
252
|
+
var _a, _b;
|
|
253
|
+
// Currently there's only one bSOL price, no timestamped data
|
|
254
|
+
// So just use the same price for every timestamp for now
|
|
255
|
+
const response = await fetchBSolMetrics();
|
|
256
|
+
if (response.status === 200) {
|
|
257
|
+
const data = (await response.json());
|
|
258
|
+
const bSolRatio = (_b = (_a = data === null || data === void 0 ? void 0 : data.stats) === null || _a === void 0 ? void 0 : _a.conversion) === null || _b === void 0 ? void 0 : _b.bsol_to_sol;
|
|
259
|
+
if (bSolRatio) {
|
|
260
|
+
timestamps.forEach((timestamp) => lstRatios.set(timestamp, bSolRatio));
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
// This block kind of assumes the record are all from the same market
|
|
265
|
+
// Otherwise the following code that checks the record.marketIndex would break
|
|
216
266
|
if (marketIndex === 2) {
|
|
217
267
|
await Promise.all(timestamps.map(getMsolPrice));
|
|
218
268
|
}
|
|
219
269
|
else if (marketIndex === 6) {
|
|
220
270
|
lstRatios = await getJitoSolHistoricalPriceMap(timestamps);
|
|
221
271
|
}
|
|
272
|
+
else if (marketIndex === 8) {
|
|
273
|
+
await getBSolPrice(timestamps);
|
|
274
|
+
}
|
|
222
275
|
let solEarned = numericConstants_1.ZERO;
|
|
223
276
|
for (const record of depositRecords) {
|
|
224
277
|
if (record.marketIndex === 1) {
|
|
@@ -229,23 +282,12 @@ async function calculateSolEarned({ marketIndex, user, depositRecords, }) {
|
|
|
229
282
|
solEarned = solEarned.add(record.amount);
|
|
230
283
|
}
|
|
231
284
|
}
|
|
232
|
-
else if (record.marketIndex === 2
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
const
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
}
|
|
239
|
-
else {
|
|
240
|
-
solEarned = solEarned.add(solAmount);
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
else if (record.marketIndex === 6) {
|
|
244
|
-
const jitoSolRatio = lstRatios.get(record.ts.toNumber());
|
|
245
|
-
const jitoSolRatioBN = new anchor_1.BN(jitoSolRatio * web3_js_1.LAMPORTS_PER_SOL);
|
|
246
|
-
const solAmount = record.amount
|
|
247
|
-
.mul(jitoSolRatioBN)
|
|
248
|
-
.div(numericConstants_1.LAMPORTS_PRECISION);
|
|
285
|
+
else if (record.marketIndex === 2 ||
|
|
286
|
+
record.marketIndex === 6 ||
|
|
287
|
+
record.marketIndex === 8) {
|
|
288
|
+
const lstRatio = lstRatios.get(record.ts.toNumber());
|
|
289
|
+
const lstRatioBN = new anchor_1.BN(lstRatio * web3_js_1.LAMPORTS_PER_SOL);
|
|
290
|
+
const solAmount = record.amount.mul(lstRatioBN).div(numericConstants_1.LAMPORTS_PRECISION);
|
|
249
291
|
if ((0, types_1.isVariant)(record.direction, 'deposit')) {
|
|
250
292
|
solEarned = solEarned.sub(solAmount);
|
|
251
293
|
}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
/// <reference types="node" />
|
|
2
|
+
/// <reference types="node" />
|
|
2
3
|
import { DriftClient } from '../driftClient';
|
|
3
4
|
import { UserAccount } from '../types';
|
|
4
5
|
import { Commitment } from '@solana/web3.js';
|
|
6
|
+
import { Buffer } from 'buffer';
|
|
5
7
|
import { DLOB } from '../dlob/DLOB';
|
|
6
8
|
import { OrderSubscriberConfig, OrderSubscriberEvents } from './types';
|
|
7
9
|
import { PollingSubscription } from './PollingSubscription';
|
|
@@ -20,6 +22,7 @@ export declare class OrderSubscriber {
|
|
|
20
22
|
fetchPromise?: Promise<void>;
|
|
21
23
|
fetchPromiseResolver: () => void;
|
|
22
24
|
mostRecentSlot: number;
|
|
25
|
+
decodeFn: (name: string, data: Buffer) => UserAccount;
|
|
23
26
|
constructor(config: OrderSubscriberConfig);
|
|
24
27
|
subscribe(): Promise<void>;
|
|
25
28
|
fetch(): Promise<void>;
|
|
@@ -9,8 +9,10 @@ const PollingSubscription_1 = require("./PollingSubscription");
|
|
|
9
9
|
const WebsocketSubscription_1 = require("./WebsocketSubscription");
|
|
10
10
|
const events_1 = require("events");
|
|
11
11
|
const index_1 = require("../index");
|
|
12
|
+
const user_1 = require("../decode/user");
|
|
12
13
|
class OrderSubscriber {
|
|
13
14
|
constructor(config) {
|
|
15
|
+
var _a;
|
|
14
16
|
this.usersAccounts = new Map();
|
|
15
17
|
this.driftClient = config.driftClient;
|
|
16
18
|
this.commitment = config.subscriptionConfig.commitment || 'processed';
|
|
@@ -28,6 +30,13 @@ class OrderSubscriber {
|
|
|
28
30
|
resubTimeoutMs: config.subscriptionConfig.resubTimeoutMs,
|
|
29
31
|
});
|
|
30
32
|
}
|
|
33
|
+
if ((_a = config.fastDecode) !== null && _a !== void 0 ? _a : true) {
|
|
34
|
+
this.decodeFn = (name, data) => (0, user_1.decodeUser)(data);
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
this.decodeFn =
|
|
38
|
+
this.driftClient.program.account.user.coder.accounts.decodeUnchecked.bind(this.driftClient.program.account.user.coder.accounts);
|
|
39
|
+
}
|
|
31
40
|
this.eventEmitter = new events_1.EventEmitter();
|
|
32
41
|
}
|
|
33
42
|
async subscribe() {
|
|
@@ -60,11 +69,15 @@ class OrderSubscriber {
|
|
|
60
69
|
const key = programAccount.pubkey.toString();
|
|
61
70
|
programAccountSet.add(key);
|
|
62
71
|
this.tryUpdateUserAccount(key, 'raw', programAccount.account.data, slot);
|
|
72
|
+
// give event loop a chance to breathe
|
|
73
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
63
74
|
}
|
|
64
75
|
for (const key of this.usersAccounts.keys()) {
|
|
65
76
|
if (!programAccountSet.has(key)) {
|
|
66
77
|
this.usersAccounts.delete(key);
|
|
67
78
|
}
|
|
79
|
+
// give event loop a chance to breathe
|
|
80
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
68
81
|
}
|
|
69
82
|
}
|
|
70
83
|
catch (e) {
|
|
@@ -79,6 +92,7 @@ class OrderSubscriber {
|
|
|
79
92
|
if (!this.mostRecentSlot || slot > this.mostRecentSlot) {
|
|
80
93
|
this.mostRecentSlot = slot;
|
|
81
94
|
}
|
|
95
|
+
this.eventEmitter.emit('updateReceived', new web3_js_1.PublicKey(key), slot, dataType);
|
|
82
96
|
const slotAndUserAccount = this.usersAccounts.get(key);
|
|
83
97
|
if (!slotAndUserAccount || slotAndUserAccount.slot <= slot) {
|
|
84
98
|
let userAccount;
|
|
@@ -91,19 +105,19 @@ class OrderSubscriber {
|
|
|
91
105
|
slotAndUserAccount.userAccount.lastActiveSlot.gt(newLastActiveSlot)) {
|
|
92
106
|
return;
|
|
93
107
|
}
|
|
94
|
-
userAccount =
|
|
95
|
-
this.driftClient.program.account.user.coder.accounts.decodeUnchecked('User', buffer);
|
|
108
|
+
userAccount = this.decodeFn('User', buffer);
|
|
96
109
|
}
|
|
97
110
|
else {
|
|
98
111
|
userAccount = data;
|
|
99
112
|
}
|
|
113
|
+
this.eventEmitter.emit('userUpdated', userAccount, new web3_js_1.PublicKey(key), slot, dataType);
|
|
100
114
|
const newOrders = userAccount.orders.filter((order) => {
|
|
101
115
|
var _a;
|
|
102
116
|
return order.slot.toNumber() > ((_a = slotAndUserAccount === null || slotAndUserAccount === void 0 ? void 0 : slotAndUserAccount.slot) !== null && _a !== void 0 ? _a : 0) &&
|
|
103
117
|
order.slot.toNumber() <= slot;
|
|
104
118
|
});
|
|
105
119
|
if (newOrders.length > 0) {
|
|
106
|
-
this.eventEmitter.emit('
|
|
120
|
+
this.eventEmitter.emit('orderCreated', userAccount, newOrders, new web3_js_1.PublicKey(key), slot, dataType);
|
|
107
121
|
}
|
|
108
122
|
if (userAccount.hasOpenOrder) {
|
|
109
123
|
this.usersAccounts.set(key, { slot, userAccount });
|
|
@@ -5,7 +5,7 @@ export declare class WebsocketSubscription {
|
|
|
5
5
|
private commitment;
|
|
6
6
|
private skipInitialLoad;
|
|
7
7
|
private resubTimeoutMs?;
|
|
8
|
-
private subscriber
|
|
8
|
+
private subscriber?;
|
|
9
9
|
constructor({ orderSubscriber, commitment, skipInitialLoad, resubTimeoutMs, }: {
|
|
10
10
|
orderSubscriber: OrderSubscriber;
|
|
11
11
|
commitment: Commitment;
|
|
@@ -11,12 +11,13 @@ class WebsocketSubscription {
|
|
|
11
11
|
this.resubTimeoutMs = resubTimeoutMs;
|
|
12
12
|
}
|
|
13
13
|
async subscribe() {
|
|
14
|
-
if (
|
|
15
|
-
|
|
16
|
-
filters: [(0, memcmp_1.getUserFilter)(), (0, memcmp_1.getNonIdleUserFilter)()],
|
|
17
|
-
commitment: this.commitment,
|
|
18
|
-
}, this.resubTimeoutMs);
|
|
14
|
+
if (this.subscriber) {
|
|
15
|
+
return;
|
|
19
16
|
}
|
|
17
|
+
this.subscriber = new webSocketProgramAccountSubscriber_1.WebSocketProgramAccountSubscriber('OrderSubscriber', 'User', this.orderSubscriber.driftClient.program, this.orderSubscriber.decodeFn, {
|
|
18
|
+
filters: [(0, memcmp_1.getUserFilter)(), (0, memcmp_1.getNonIdleUserFilter)()],
|
|
19
|
+
commitment: this.commitment,
|
|
20
|
+
}, this.resubTimeoutMs);
|
|
20
21
|
await this.subscriber.subscribe((accountId, account, context) => {
|
|
21
22
|
const userKey = accountId.toBase58();
|
|
22
23
|
this.orderSubscriber.tryUpdateUserAccount(userKey, 'decoded', account, context.slot);
|
|
@@ -28,7 +29,8 @@ class WebsocketSubscription {
|
|
|
28
29
|
async unsubscribe() {
|
|
29
30
|
if (!this.subscriber)
|
|
30
31
|
return;
|
|
31
|
-
this.subscriber.unsubscribe();
|
|
32
|
+
await this.subscriber.unsubscribe();
|
|
33
|
+
this.subscriber = undefined;
|
|
32
34
|
}
|
|
33
35
|
}
|
|
34
36
|
exports.WebsocketSubscription = WebsocketSubscription;
|
|
@@ -13,7 +13,10 @@ export type OrderSubscriberConfig = {
|
|
|
13
13
|
resubTimeoutMs?: number;
|
|
14
14
|
commitment?: Commitment;
|
|
15
15
|
};
|
|
16
|
+
fastDecode?: boolean;
|
|
16
17
|
};
|
|
17
18
|
export interface OrderSubscriberEvents {
|
|
18
|
-
|
|
19
|
+
orderCreated: (account: UserAccount, updatedOrders: Order[], pubkey: PublicKey, slot: number, dataType: 'raw' | 'decoded') => void;
|
|
20
|
+
userUpdated: (account: UserAccount, pubkey: PublicKey, slot: number, dataType: 'raw' | 'decoded') => void;
|
|
21
|
+
updateReceived: (pubkey: PublicKey, slot: number, dataType: 'raw' | 'decoded') => void;
|
|
19
22
|
}
|
package/lib/types.d.ts
CHANGED
|
@@ -629,6 +629,7 @@ export type StateAccount = {
|
|
|
629
629
|
lpCooldownTime: BN;
|
|
630
630
|
initialPctToLiquidate: number;
|
|
631
631
|
liquidationDuration: number;
|
|
632
|
+
maxInitializeUserFee: number;
|
|
632
633
|
};
|
|
633
634
|
export type PerpMarketAccount = {
|
|
634
635
|
status: MarketStatus;
|
|
@@ -913,8 +914,8 @@ export type Order = {
|
|
|
913
914
|
marketIndex: number;
|
|
914
915
|
price: BN;
|
|
915
916
|
baseAssetAmount: BN;
|
|
916
|
-
baseAssetAmountFilled: BN;
|
|
917
917
|
quoteAssetAmount: BN;
|
|
918
|
+
baseAssetAmountFilled: BN;
|
|
918
919
|
quoteAssetAmountFilled: BN;
|
|
919
920
|
direction: PositionDirection;
|
|
920
921
|
reduceOnly: boolean;
|
package/lib/user.d.ts
CHANGED
|
@@ -95,7 +95,7 @@ export declare class User {
|
|
|
95
95
|
* @returns : the dust base asset amount (ie, < stepsize)
|
|
96
96
|
* @returns : pnl from settle
|
|
97
97
|
*/
|
|
98
|
-
getPerpPositionWithLPSettle(marketIndex: number, originalPosition?: PerpPosition, burnLpShares?: boolean): [PerpPosition, BN, BN];
|
|
98
|
+
getPerpPositionWithLPSettle(marketIndex: number, originalPosition?: PerpPosition, burnLpShares?: boolean, includeRemainderInBaseAmount?: boolean): [PerpPosition, BN, BN];
|
|
99
99
|
/**
|
|
100
100
|
* calculates Buying Power = free collateral / initial margin ratio
|
|
101
101
|
* @returns : Precision QUOTE_PRECISION
|
|
@@ -196,6 +196,7 @@ export declare class User {
|
|
|
196
196
|
};
|
|
197
197
|
getTotalLiabilityValue(marginCategory?: MarginCategory): BN;
|
|
198
198
|
getTotalAssetValue(marginCategory?: MarginCategory): BN;
|
|
199
|
+
getNetUsdValue(): BN;
|
|
199
200
|
/**
|
|
200
201
|
* Calculates the all time P&L of the user.
|
|
201
202
|
*
|
package/lib/user.js
CHANGED
|
@@ -251,7 +251,7 @@ class User {
|
|
|
251
251
|
* @returns : the dust base asset amount (ie, < stepsize)
|
|
252
252
|
* @returns : pnl from settle
|
|
253
253
|
*/
|
|
254
|
-
getPerpPositionWithLPSettle(marketIndex, originalPosition, burnLpShares = false) {
|
|
254
|
+
getPerpPositionWithLPSettle(marketIndex, originalPosition, burnLpShares = false, includeRemainderInBaseAmount = false) {
|
|
255
255
|
var _a;
|
|
256
256
|
originalPosition =
|
|
257
257
|
(_a = originalPosition !== null && originalPosition !== void 0 ? originalPosition : this.getPerpPosition(marketIndex)) !== null && _a !== void 0 ? _a : this.getEmptyPosition(marketIndex);
|
|
@@ -396,7 +396,12 @@ class User {
|
|
|
396
396
|
else {
|
|
397
397
|
position.lastCumulativeFundingRate = numericConstants_1.ZERO;
|
|
398
398
|
}
|
|
399
|
-
|
|
399
|
+
const remainderBeforeRemoval = new _1.BN(position.remainderBaseAssetAmount);
|
|
400
|
+
if (includeRemainderInBaseAmount) {
|
|
401
|
+
position.baseAssetAmount = position.baseAssetAmount.add(remainderBeforeRemoval);
|
|
402
|
+
position.remainderBaseAssetAmount = 0;
|
|
403
|
+
}
|
|
404
|
+
return [position, remainderBeforeRemoval, pnl];
|
|
400
405
|
}
|
|
401
406
|
/**
|
|
402
407
|
* calculates Buying Power = free collateral / initial margin ratio
|
|
@@ -852,15 +857,18 @@ class User {
|
|
|
852
857
|
getTotalAssetValue(marginCategory) {
|
|
853
858
|
return this.getSpotMarketAssetValue(undefined, marginCategory, true).add(this.getUnrealizedPNL(true, undefined, marginCategory));
|
|
854
859
|
}
|
|
860
|
+
getNetUsdValue() {
|
|
861
|
+
const netSpotValue = this.getNetSpotMarketValue();
|
|
862
|
+
const unrealizedPnl = this.getUnrealizedPNL(true, undefined, undefined);
|
|
863
|
+
return netSpotValue.add(unrealizedPnl);
|
|
864
|
+
}
|
|
855
865
|
/**
|
|
856
866
|
* Calculates the all time P&L of the user.
|
|
857
867
|
*
|
|
858
868
|
* Net withdraws + Net spot market value + Net unrealized P&L -
|
|
859
869
|
*/
|
|
860
870
|
getTotalAllTimePnl() {
|
|
861
|
-
const
|
|
862
|
-
const unrealizedPnl = this.getUnrealizedPNL(true, undefined, undefined);
|
|
863
|
-
const netUsdValue = netBankValue.add(unrealizedPnl);
|
|
871
|
+
const netUsdValue = this.getNetUsdValue();
|
|
864
872
|
const totalDeposits = this.getUserAccount().totalDeposits;
|
|
865
873
|
const totalWithdraws = this.getUserAccount().totalWithdraws;
|
|
866
874
|
const totalPnl = netUsdValue.add(totalWithdraws).sub(totalDeposits);
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { UserMap } from './userMap';
|
|
2
|
+
export declare class PollingSubscription {
|
|
3
|
+
private userMap;
|
|
4
|
+
private frequency;
|
|
5
|
+
private skipInitialLoad;
|
|
6
|
+
intervalId?: ReturnType<typeof setTimeout>;
|
|
7
|
+
constructor({ userMap, frequency, skipInitialLoad, }: {
|
|
8
|
+
userMap: UserMap;
|
|
9
|
+
frequency: number;
|
|
10
|
+
skipInitialLoad?: boolean;
|
|
11
|
+
includeIdle?: boolean;
|
|
12
|
+
});
|
|
13
|
+
subscribe(): Promise<void>;
|
|
14
|
+
unsubscribe(): Promise<void>;
|
|
15
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PollingSubscription = void 0;
|
|
4
|
+
class PollingSubscription {
|
|
5
|
+
constructor({ userMap, frequency, skipInitialLoad = false, }) {
|
|
6
|
+
this.userMap = userMap;
|
|
7
|
+
this.frequency = frequency;
|
|
8
|
+
this.skipInitialLoad = skipInitialLoad;
|
|
9
|
+
}
|
|
10
|
+
async subscribe() {
|
|
11
|
+
if (this.intervalId) {
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
if (this.frequency > 0) {
|
|
15
|
+
this.intervalId = setInterval(this.userMap.sync.bind(this.userMap), this.frequency);
|
|
16
|
+
}
|
|
17
|
+
if (!this.skipInitialLoad) {
|
|
18
|
+
await this.userMap.sync();
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
async unsubscribe() {
|
|
22
|
+
if (this.intervalId) {
|
|
23
|
+
clearInterval(this.intervalId);
|
|
24
|
+
this.intervalId = undefined;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
exports.PollingSubscription = PollingSubscription;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
import { UserMap } from './userMap';
|
|
3
|
+
import { UserAccount } from '../types';
|
|
4
|
+
import { Commitment } from '@solana/web3.js';
|
|
5
|
+
export declare class WebsocketSubscription {
|
|
6
|
+
private userMap;
|
|
7
|
+
private commitment;
|
|
8
|
+
private skipInitialLoad;
|
|
9
|
+
private resubTimeoutMs?;
|
|
10
|
+
private includeIdle?;
|
|
11
|
+
private decodeFn;
|
|
12
|
+
private subscriber;
|
|
13
|
+
constructor({ userMap, commitment, skipInitialLoad, resubTimeoutMs, includeIdle, decodeFn, }: {
|
|
14
|
+
userMap: UserMap;
|
|
15
|
+
commitment: Commitment;
|
|
16
|
+
skipInitialLoad?: boolean;
|
|
17
|
+
resubTimeoutMs?: number;
|
|
18
|
+
includeIdle?: boolean;
|
|
19
|
+
decodeFn: (name: string, data: Buffer) => UserAccount;
|
|
20
|
+
});
|
|
21
|
+
subscribe(): Promise<void>;
|
|
22
|
+
unsubscribe(): Promise<void>;
|
|
23
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.WebsocketSubscription = void 0;
|
|
4
|
+
const memcmp_1 = require("../memcmp");
|
|
5
|
+
const webSocketProgramAccountSubscriber_1 = require("../accounts/webSocketProgramAccountSubscriber");
|
|
6
|
+
class WebsocketSubscription {
|
|
7
|
+
constructor({ userMap, commitment, skipInitialLoad = false, resubTimeoutMs, includeIdle = false, decodeFn, }) {
|
|
8
|
+
this.userMap = userMap;
|
|
9
|
+
this.commitment = commitment;
|
|
10
|
+
this.skipInitialLoad = skipInitialLoad;
|
|
11
|
+
this.resubTimeoutMs = resubTimeoutMs;
|
|
12
|
+
this.includeIdle = includeIdle || false;
|
|
13
|
+
this.decodeFn = decodeFn;
|
|
14
|
+
}
|
|
15
|
+
async subscribe() {
|
|
16
|
+
if (!this.subscriber) {
|
|
17
|
+
const filters = [(0, memcmp_1.getUserFilter)()];
|
|
18
|
+
if (!this.includeIdle) {
|
|
19
|
+
filters.push((0, memcmp_1.getNonIdleUserFilter)());
|
|
20
|
+
}
|
|
21
|
+
this.subscriber = new webSocketProgramAccountSubscriber_1.WebSocketProgramAccountSubscriber('UserMap', 'User', this.userMap.driftClient.program, this.decodeFn, {
|
|
22
|
+
filters,
|
|
23
|
+
commitment: this.commitment,
|
|
24
|
+
}, this.resubTimeoutMs);
|
|
25
|
+
}
|
|
26
|
+
await this.subscriber.subscribe((accountId, account, context) => {
|
|
27
|
+
const userKey = accountId.toBase58();
|
|
28
|
+
this.userMap.updateUserAccount(userKey, account, context.slot);
|
|
29
|
+
});
|
|
30
|
+
if (!this.skipInitialLoad) {
|
|
31
|
+
await this.userMap.sync();
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
async unsubscribe() {
|
|
35
|
+
if (!this.subscriber)
|
|
36
|
+
return;
|
|
37
|
+
await this.subscriber.unsubscribe();
|
|
38
|
+
this.subscriber = undefined;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
exports.WebsocketSubscription = WebsocketSubscription;
|