@drift-labs/sdk 2.0.11 → 2.0.12
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/adminClient.d.ts +2 -1
- package/lib/adminClient.js +9 -0
- package/lib/config.js +1 -1
- package/lib/constants/spotMarkets.js +1 -1
- package/lib/events/pollingLogProvider.js +1 -1
- package/lib/idl/drift.json +40 -2
- package/lib/types.d.ts +8 -0
- package/lib/types.js +6 -1
- package/lib/user.d.ts +18 -4
- package/lib/user.js +93 -11
- package/lib/userMap/userMap.d.ts +1 -2
- package/lib/userMap/userMap.js +0 -40
- package/lib/userMap/userStatsMap.d.ts +1 -2
- package/lib/userMap/userStatsMap.js +0 -65
- package/package.json +1 -1
- package/src/adminClient.ts +14 -0
- package/src/assert/assert.js +9 -0
- package/src/config.ts +1 -1
- package/src/constants/spotMarkets.ts +1 -1
- package/src/events/eventList.js +77 -0
- package/src/events/pollingLogProvider.ts +2 -2
- package/src/examples/makeTradeExample.js +157 -0
- package/src/idl/drift.json +40 -2
- package/src/token/index.js +38 -0
- package/src/tx/types.js +2 -0
- package/src/tx/utils.js +17 -0
- package/src/types.ts +5 -0
- package/src/user.ts +133 -15
- package/src/userMap/userMap.ts +0 -44
- package/src/userMap/userStatsMap.ts +0 -76
- package/src/util/computeUnits.js +27 -0
- package/src/util/getTokenAddress.js +9 -0
- package/src/util/promiseTimeout.js +14 -0
- package/src/util/tps.js +27 -0
package/lib/adminClient.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/// <reference types="bn.js" />
|
|
2
2
|
import { PublicKey, TransactionSignature } from '@solana/web3.js';
|
|
3
|
-
import { FeeStructure, OracleGuardRails, OracleSource, ExchangeStatus, MarketStatus, ContractTier, AssetTier } from './types';
|
|
3
|
+
import { FeeStructure, OracleGuardRails, OracleSource, ExchangeStatus, MarketStatus, ContractTier, AssetTier, SpotFulfillmentConfigStatus } from './types';
|
|
4
4
|
import { BN } from '@project-serum/anchor';
|
|
5
5
|
import { DriftClient } from './driftClient';
|
|
6
6
|
export declare class AdminClient extends DriftClient {
|
|
@@ -43,6 +43,7 @@ export declare class AdminClient extends DriftClient {
|
|
|
43
43
|
updatePerpMarketExpiry(perpMarketIndex: number, expiryTs: BN): Promise<TransactionSignature>;
|
|
44
44
|
updateSpotMarketOracle(spotMarketIndex: number, oracle: PublicKey, oracleSource: OracleSource): Promise<TransactionSignature>;
|
|
45
45
|
updateSpotMarketOrdersEnabled(spotMarketIndex: number, ordersEnabled: boolean): Promise<TransactionSignature>;
|
|
46
|
+
updateSerumFulfillmentConfigStatus(serumFulfillmentConfig: PublicKey, status: SpotFulfillmentConfigStatus): Promise<TransactionSignature>;
|
|
46
47
|
updateSpotMarketExpiry(spotMarketIndex: number, expiryTs: BN): Promise<TransactionSignature>;
|
|
47
48
|
updateWhitelistMint(whitelistMint?: PublicKey): Promise<TransactionSignature>;
|
|
48
49
|
updateDiscountMint(discountMint: PublicKey): Promise<TransactionSignature>;
|
package/lib/adminClient.js
CHANGED
|
@@ -467,6 +467,15 @@ class AdminClient extends driftClient_1.DriftClient {
|
|
|
467
467
|
},
|
|
468
468
|
});
|
|
469
469
|
}
|
|
470
|
+
async updateSerumFulfillmentConfigStatus(serumFulfillmentConfig, status) {
|
|
471
|
+
return await this.program.rpc.updateSerumFulfillmentConfigStatus(status, {
|
|
472
|
+
accounts: {
|
|
473
|
+
admin: this.wallet.publicKey,
|
|
474
|
+
state: await this.getStatePublicKey(),
|
|
475
|
+
serumFulfillmentConfig,
|
|
476
|
+
},
|
|
477
|
+
});
|
|
478
|
+
}
|
|
470
479
|
async updateSpotMarketExpiry(spotMarketIndex, expiryTs) {
|
|
471
480
|
return await this.program.rpc.updateSpotMarketExpiry(expiryTs, {
|
|
472
481
|
accounts: {
|
package/lib/config.js
CHANGED
|
@@ -19,7 +19,7 @@ exports.configs = {
|
|
|
19
19
|
PYTH_ORACLE_MAPPING_ADDRESS: 'AHtgzX45WTKfkPG53L6WYhGEXwQkN1BVknET3sVsLL8J',
|
|
20
20
|
DRIFT_PROGRAM_ID: 'dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH',
|
|
21
21
|
USDC_MINT_ADDRESS: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
|
|
22
|
-
SERUM_V3: '
|
|
22
|
+
SERUM_V3: 'srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX',
|
|
23
23
|
V2_ALPHA_TICKET_MINT_ADDRESS: 'Cmvhycb6LQvvzaShGw4iDHRLzeSSryioAsU98DSSkMNa',
|
|
24
24
|
PERP_MARKETS: perpMarkets_1.MainnetPerpMarkets,
|
|
25
25
|
SPOT_MARKETS: spotMarkets_1.MainnetSpotMarkets,
|
|
@@ -54,7 +54,7 @@ exports.MainnetSpotMarkets = [
|
|
|
54
54
|
mint: new web3_js_1.PublicKey(exports.WRAPPED_SOL_MINT),
|
|
55
55
|
precision: numericConstants_1.LAMPORTS_PRECISION,
|
|
56
56
|
precisionExp: numericConstants_1.LAMPORTS_EXP,
|
|
57
|
-
serumMarket: new web3_js_1.PublicKey('
|
|
57
|
+
serumMarket: new web3_js_1.PublicKey('8BnEgHoWFysVcuFFX7QztDmzuH8r5ZFvyP3sYwn1XTh6'),
|
|
58
58
|
},
|
|
59
59
|
];
|
|
60
60
|
exports.SpotMarkets = {
|
|
@@ -23,10 +23,10 @@ class PollingLogProvider {
|
|
|
23
23
|
const response = await (0, fetchLogs_1.fetchLogs)(this.connection, this.programId, this.finality, undefined, this.mostRecentSeenTx,
|
|
24
24
|
// If skipping history, only fetch one log back, not the maximum amount available
|
|
25
25
|
skipHistory && this.firstFetch ? 1 : undefined);
|
|
26
|
-
this.firstFetch = false;
|
|
27
26
|
if (response === undefined) {
|
|
28
27
|
return;
|
|
29
28
|
}
|
|
29
|
+
this.firstFetch = false;
|
|
30
30
|
const { mostRecentTx, transactionLogs } = response;
|
|
31
31
|
for (const { txSig, slot, logs } of transactionLogs) {
|
|
32
32
|
callback(txSig, slot, logs, response.mostRecentBlockTime);
|
package/lib/idl/drift.json
CHANGED
|
@@ -2070,6 +2070,34 @@
|
|
|
2070
2070
|
}
|
|
2071
2071
|
]
|
|
2072
2072
|
},
|
|
2073
|
+
{
|
|
2074
|
+
"name": "updateSerumFulfillmentConfigStatus",
|
|
2075
|
+
"accounts": [
|
|
2076
|
+
{
|
|
2077
|
+
"name": "state",
|
|
2078
|
+
"isMut": false,
|
|
2079
|
+
"isSigner": false
|
|
2080
|
+
},
|
|
2081
|
+
{
|
|
2082
|
+
"name": "serumFulfillmentConfig",
|
|
2083
|
+
"isMut": true,
|
|
2084
|
+
"isSigner": false
|
|
2085
|
+
},
|
|
2086
|
+
{
|
|
2087
|
+
"name": "admin",
|
|
2088
|
+
"isMut": true,
|
|
2089
|
+
"isSigner": true
|
|
2090
|
+
}
|
|
2091
|
+
],
|
|
2092
|
+
"args": [
|
|
2093
|
+
{
|
|
2094
|
+
"name": "status",
|
|
2095
|
+
"type": {
|
|
2096
|
+
"defined": "SpotFulfillmentConfigStatus"
|
|
2097
|
+
}
|
|
2098
|
+
}
|
|
2099
|
+
]
|
|
2100
|
+
},
|
|
2073
2101
|
{
|
|
2074
2102
|
"name": "updateSerumVault",
|
|
2075
2103
|
"accounts": [
|
|
@@ -4184,7 +4212,7 @@
|
|
|
4184
4212
|
{
|
|
4185
4213
|
"name": "status",
|
|
4186
4214
|
"type": {
|
|
4187
|
-
"defined": "
|
|
4215
|
+
"defined": "SpotFulfillmentConfigStatus"
|
|
4188
4216
|
}
|
|
4189
4217
|
},
|
|
4190
4218
|
{
|
|
@@ -6206,7 +6234,7 @@
|
|
|
6206
6234
|
}
|
|
6207
6235
|
},
|
|
6208
6236
|
{
|
|
6209
|
-
"name": "
|
|
6237
|
+
"name": "SpotFulfillmentConfigStatus",
|
|
6210
6238
|
"type": {
|
|
6211
6239
|
"kind": "enum",
|
|
6212
6240
|
"variants": [
|
|
@@ -8423,6 +8451,16 @@
|
|
|
8423
8451
|
"code": 6218,
|
|
8424
8452
|
"name": "InvalidPerpPosition",
|
|
8425
8453
|
"msg": "Invalid Perp Position"
|
|
8454
|
+
},
|
|
8455
|
+
{
|
|
8456
|
+
"code": 6219,
|
|
8457
|
+
"name": "InvalidLiquidation",
|
|
8458
|
+
"msg": "Invalid Liquidation"
|
|
8459
|
+
},
|
|
8460
|
+
{
|
|
8461
|
+
"code": 6220,
|
|
8462
|
+
"name": "SpotFulfillmentConfigDisabled",
|
|
8463
|
+
"msg": "Spot Fulfullment Config Disabled"
|
|
8426
8464
|
}
|
|
8427
8465
|
]
|
|
8428
8466
|
}
|
package/lib/types.d.ts
CHANGED
|
@@ -284,6 +284,14 @@ export declare class SettlePnlExplanation {
|
|
|
284
284
|
expiredPosition: {};
|
|
285
285
|
};
|
|
286
286
|
}
|
|
287
|
+
export declare class SpotFulfillmentConfigStatus {
|
|
288
|
+
static readonly ENABLED: {
|
|
289
|
+
enabled: {};
|
|
290
|
+
};
|
|
291
|
+
static readonly DISABLED: {
|
|
292
|
+
disabled: {};
|
|
293
|
+
};
|
|
294
|
+
}
|
|
287
295
|
export declare class StakeAction {
|
|
288
296
|
static readonly STAKE: {
|
|
289
297
|
stake: {};
|
package/lib/types.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.DefaultOrderParams = exports.LiquidationType = exports.LPAction = exports.TradeSide = exports.getVariant = exports.isOneOfVariant = exports.isVariant = exports.StakeAction = exports.SettlePnlExplanation = exports.DepositExplanation = exports.SpotFulfillmentStatus = exports.SpotFulfillmentType = exports.OrderTriggerCondition = exports.OrderActionExplanation = exports.OrderAction = exports.OrderStatus = exports.MarketType = exports.OrderType = exports.OracleSource = exports.DepositDirection = exports.PositionDirection = exports.SpotBalanceType = exports.SwapDirection = exports.AssetTier = exports.ContractTier = exports.ContractType = exports.UserStatus = exports.MarketStatus = exports.ExchangeStatus = void 0;
|
|
3
|
+
exports.DefaultOrderParams = exports.LiquidationType = exports.LPAction = exports.TradeSide = exports.getVariant = exports.isOneOfVariant = exports.isVariant = exports.StakeAction = exports.SpotFulfillmentConfigStatus = exports.SettlePnlExplanation = exports.DepositExplanation = exports.SpotFulfillmentStatus = exports.SpotFulfillmentType = exports.OrderTriggerCondition = exports.OrderActionExplanation = exports.OrderAction = exports.OrderStatus = exports.MarketType = exports.OrderType = exports.OracleSource = exports.DepositDirection = exports.PositionDirection = exports.SpotBalanceType = exports.SwapDirection = exports.AssetTier = exports.ContractTier = exports.ContractType = exports.UserStatus = exports.MarketStatus = exports.ExchangeStatus = void 0;
|
|
4
4
|
const _1 = require(".");
|
|
5
5
|
// # Utility Types / Enums / Constants
|
|
6
6
|
class ExchangeStatus {
|
|
@@ -172,6 +172,11 @@ class SettlePnlExplanation {
|
|
|
172
172
|
exports.SettlePnlExplanation = SettlePnlExplanation;
|
|
173
173
|
SettlePnlExplanation.NONE = { none: {} };
|
|
174
174
|
SettlePnlExplanation.EXPIRED_POSITION = { expiredPosition: {} };
|
|
175
|
+
class SpotFulfillmentConfigStatus {
|
|
176
|
+
}
|
|
177
|
+
exports.SpotFulfillmentConfigStatus = SpotFulfillmentConfigStatus;
|
|
178
|
+
SpotFulfillmentConfigStatus.ENABLED = { enabled: {} };
|
|
179
|
+
SpotFulfillmentConfigStatus.DISABLED = { disabled: {} };
|
|
175
180
|
class StakeAction {
|
|
176
181
|
}
|
|
177
182
|
exports.StakeAction = StakeAction;
|
package/lib/user.d.ts
CHANGED
|
@@ -97,6 +97,7 @@ export declare class User {
|
|
|
97
97
|
* @returns The maintenance margin requirement in USDC. : QUOTE_PRECISION
|
|
98
98
|
*/
|
|
99
99
|
getMaintenanceMarginRequirement(liquidationBuffer?: BN): BN;
|
|
100
|
+
getActivePerpPositions(): PerpPosition[];
|
|
100
101
|
/**
|
|
101
102
|
* calculates unrealized position price pnl
|
|
102
103
|
* @returns : Precision QUOTE_PRECISION
|
|
@@ -117,6 +118,11 @@ export declare class User {
|
|
|
117
118
|
* @returns : Precision QUOTE_PRECISION
|
|
118
119
|
*/
|
|
119
120
|
getTotalCollateral(marginCategory?: MarginCategory): BN;
|
|
121
|
+
/**
|
|
122
|
+
* calculates User Health by comparing total collateral and maint. margin requirement
|
|
123
|
+
* @returns : number (value from [0, 100])
|
|
124
|
+
*/
|
|
125
|
+
getHealth(): number;
|
|
120
126
|
/**
|
|
121
127
|
* calculates sum of position value across all positions in margin system
|
|
122
128
|
* @returns : Precision QUOTE_PRECISION
|
|
@@ -138,8 +144,8 @@ export declare class User {
|
|
|
138
144
|
* @returns : Precision TEN_THOUSAND
|
|
139
145
|
*/
|
|
140
146
|
getLeverage(): BN;
|
|
141
|
-
getTotalLiabilityValue(): BN;
|
|
142
|
-
getTotalAssetValue(): BN;
|
|
147
|
+
getTotalLiabilityValue(marginCategory?: MarginCategory): BN;
|
|
148
|
+
getTotalAssetValue(marginCategory?: MarginCategory): BN;
|
|
143
149
|
/**
|
|
144
150
|
* calculates max allowable leverage exceeding hitting requirement category
|
|
145
151
|
* @params category {Initial, Maintenance}
|
|
@@ -150,7 +156,7 @@ export declare class User {
|
|
|
150
156
|
* calculates margin ratio: total collateral / |total position value|
|
|
151
157
|
* @returns : Precision TEN_THOUSAND
|
|
152
158
|
*/
|
|
153
|
-
getMarginRatio(): BN;
|
|
159
|
+
getMarginRatio(marginCategory?: MarginCategory): BN;
|
|
154
160
|
canBeLiquidated(): boolean;
|
|
155
161
|
isBeingLiquidated(): boolean;
|
|
156
162
|
isBankrupt(): boolean;
|
|
@@ -160,7 +166,15 @@ export declare class User {
|
|
|
160
166
|
*/
|
|
161
167
|
needsToSettleFundingPayment(): boolean;
|
|
162
168
|
/**
|
|
163
|
-
* Calculate the liquidation price of a position, with optional parameter to calculate the liquidation price after a trade
|
|
169
|
+
* Calculate the liquidation price of a perp position, with optional parameter to calculate the liquidation price after a trade
|
|
170
|
+
* @param PerpPosition
|
|
171
|
+
* @param positionBaseSizeChange // change in position size to calculate liquidation price for : Precision 10^13
|
|
172
|
+
* @param partial
|
|
173
|
+
* @returns Precision : PRICE_PRECISION
|
|
174
|
+
*/
|
|
175
|
+
spotLiquidationPrice(spotPosition: Pick<SpotPosition, 'marketIndex'>): BN;
|
|
176
|
+
/**
|
|
177
|
+
* Calculate the liquidation price of a perp position, with optional parameter to calculate the liquidation price after a trade
|
|
164
178
|
* @param PerpPosition
|
|
165
179
|
* @param positionBaseSizeChange // change in position size to calculate liquidation price for : Precision 10^13
|
|
166
180
|
* @param partial
|
package/lib/user.js
CHANGED
|
@@ -270,14 +270,20 @@ class User {
|
|
|
270
270
|
getMaintenanceMarginRequirement(liquidationBuffer) {
|
|
271
271
|
return this.getMarginRequirement('Maintenance', liquidationBuffer);
|
|
272
272
|
}
|
|
273
|
+
getActivePerpPositions() {
|
|
274
|
+
return this.getUserAccount().perpPositions.filter((pos) => !pos.baseAssetAmount.eq(numericConstants_1.ZERO) ||
|
|
275
|
+
!pos.quoteAssetAmount.eq(numericConstants_1.ZERO) ||
|
|
276
|
+
!(pos.openOrders == 0) ||
|
|
277
|
+
!pos.lpShares.eq(numericConstants_1.ZERO));
|
|
278
|
+
}
|
|
273
279
|
/**
|
|
274
280
|
* calculates unrealized position price pnl
|
|
275
281
|
* @returns : Precision QUOTE_PRECISION
|
|
276
282
|
*/
|
|
277
283
|
getUnrealizedPNL(withFunding, marketIndex, withWeightMarginCategory) {
|
|
278
284
|
const quoteSpotMarket = this.driftClient.getQuoteSpotMarketAccount();
|
|
279
|
-
return this.
|
|
280
|
-
.
|
|
285
|
+
return this.getActivePerpPositions()
|
|
286
|
+
.filter((pos) => (marketIndex ? pos.marketIndex === marketIndex : true))
|
|
281
287
|
.reduce((unrealizedPnl, perpPosition) => {
|
|
282
288
|
const market = this.driftClient.getPerpMarketAccount(perpPosition.marketIndex);
|
|
283
289
|
const oraclePriceData = this.getOracleDataForPerpMarket(market.marketIndex);
|
|
@@ -436,12 +442,48 @@ class User {
|
|
|
436
442
|
getTotalCollateral(marginCategory = 'Initial') {
|
|
437
443
|
return this.getSpotMarketAssetValue(undefined, marginCategory, true).add(this.getUnrealizedPNL(true, undefined, marginCategory));
|
|
438
444
|
}
|
|
445
|
+
/**
|
|
446
|
+
* calculates User Health by comparing total collateral and maint. margin requirement
|
|
447
|
+
* @returns : number (value from [0, 100])
|
|
448
|
+
*/
|
|
449
|
+
getHealth() {
|
|
450
|
+
const userAccount = this.getUserAccount();
|
|
451
|
+
if ((0, types_1.isVariant)(userAccount.status, 'beingLiquidated') ||
|
|
452
|
+
(0, types_1.isVariant)(userAccount.status, 'bankrupt')) {
|
|
453
|
+
return 0;
|
|
454
|
+
}
|
|
455
|
+
const totalCollateral = this.getTotalCollateral('Maintenance');
|
|
456
|
+
const maintenanceMarginReq = this.getMaintenanceMarginRequirement();
|
|
457
|
+
let health;
|
|
458
|
+
if (maintenanceMarginReq.eq(numericConstants_1.ZERO) && totalCollateral.gte(numericConstants_1.ZERO)) {
|
|
459
|
+
health = 100;
|
|
460
|
+
}
|
|
461
|
+
else if (totalCollateral.lte(numericConstants_1.ZERO)) {
|
|
462
|
+
health = 0;
|
|
463
|
+
}
|
|
464
|
+
else {
|
|
465
|
+
// const totalCollateral = this.getTotalCollateral('Initial');
|
|
466
|
+
// const maintenanceMarginReq = this.getMaintenanceMarginRequirement();
|
|
467
|
+
const marginRatio = this.getMarginRatio().toNumber() / numericConstants_1.MARGIN_PRECISION.toNumber();
|
|
468
|
+
const maintenanceRatio = (maintenanceMarginReq.toNumber() / totalCollateral.toNumber()) *
|
|
469
|
+
marginRatio;
|
|
470
|
+
const healthP1 = Math.max(0, (marginRatio - maintenanceRatio) * 100) + 1;
|
|
471
|
+
health = Math.min(1, Math.log(healthP1) / Math.log(100)) * 100;
|
|
472
|
+
if (health > 1) {
|
|
473
|
+
health = Math.round(health);
|
|
474
|
+
}
|
|
475
|
+
else {
|
|
476
|
+
health = Math.round(health * 100) / 100;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
return health;
|
|
480
|
+
}
|
|
439
481
|
/**
|
|
440
482
|
* calculates sum of position value across all positions in margin system
|
|
441
483
|
* @returns : Precision QUOTE_PRECISION
|
|
442
484
|
*/
|
|
443
485
|
getTotalPerpPositionValue(marginCategory, liquidationBuffer, includeOpenOrders) {
|
|
444
|
-
return this.
|
|
486
|
+
return this.getActivePerpPositions().reduce((totalPerpValue, perpPosition) => {
|
|
445
487
|
const market = this.driftClient.getPerpMarketAccount(perpPosition.marketIndex);
|
|
446
488
|
if (perpPosition.lpShares.gt(numericConstants_1.ZERO)) {
|
|
447
489
|
// is an lp
|
|
@@ -557,11 +599,11 @@ class User {
|
|
|
557
599
|
}
|
|
558
600
|
return totalLiabilityValue.mul(numericConstants_1.TEN_THOUSAND).div(totalAssetValue);
|
|
559
601
|
}
|
|
560
|
-
getTotalLiabilityValue() {
|
|
561
|
-
return this.getTotalPerpPositionValue(
|
|
602
|
+
getTotalLiabilityValue(marginCategory) {
|
|
603
|
+
return this.getTotalPerpPositionValue(marginCategory, undefined, true).add(this.getSpotMarketLiabilityValue(undefined, marginCategory, undefined, true));
|
|
562
604
|
}
|
|
563
|
-
getTotalAssetValue() {
|
|
564
|
-
return this.getSpotMarketAssetValue(undefined,
|
|
605
|
+
getTotalAssetValue(marginCategory) {
|
|
606
|
+
return this.getSpotMarketAssetValue(undefined, marginCategory, true).add(this.getUnrealizedPNL(true, undefined, marginCategory));
|
|
565
607
|
}
|
|
566
608
|
/**
|
|
567
609
|
* calculates max allowable leverage exceeding hitting requirement category
|
|
@@ -593,12 +635,12 @@ class User {
|
|
|
593
635
|
* calculates margin ratio: total collateral / |total position value|
|
|
594
636
|
* @returns : Precision TEN_THOUSAND
|
|
595
637
|
*/
|
|
596
|
-
getMarginRatio() {
|
|
597
|
-
const totalLiabilityValue = this.getTotalLiabilityValue();
|
|
638
|
+
getMarginRatio(marginCategory) {
|
|
639
|
+
const totalLiabilityValue = this.getTotalLiabilityValue(marginCategory);
|
|
598
640
|
if (totalLiabilityValue.eq(numericConstants_1.ZERO)) {
|
|
599
641
|
return numericConstants_1.BN_MAX;
|
|
600
642
|
}
|
|
601
|
-
const totalAssetValue = this.getTotalAssetValue();
|
|
643
|
+
const totalAssetValue = this.getTotalAssetValue(marginCategory);
|
|
602
644
|
return totalAssetValue.mul(numericConstants_1.TEN_THOUSAND).div(totalLiabilityValue);
|
|
603
645
|
}
|
|
604
646
|
canBeLiquidated() {
|
|
@@ -640,7 +682,47 @@ class User {
|
|
|
640
682
|
return false;
|
|
641
683
|
}
|
|
642
684
|
/**
|
|
643
|
-
* Calculate the liquidation price of a position, with optional parameter to calculate the liquidation price after a trade
|
|
685
|
+
* Calculate the liquidation price of a perp position, with optional parameter to calculate the liquidation price after a trade
|
|
686
|
+
* @param PerpPosition
|
|
687
|
+
* @param positionBaseSizeChange // change in position size to calculate liquidation price for : Precision 10^13
|
|
688
|
+
* @param partial
|
|
689
|
+
* @returns Precision : PRICE_PRECISION
|
|
690
|
+
*/
|
|
691
|
+
spotLiquidationPrice(spotPosition) {
|
|
692
|
+
const currentSpotPosition = this.getSpotPosition(spotPosition.marketIndex);
|
|
693
|
+
const mtc = this.getTotalCollateral('Maintenance');
|
|
694
|
+
const mmr = this.getMaintenanceMarginRequirement();
|
|
695
|
+
const deltaValueToLiq = mtc.sub(mmr); // QUOTE_PRECISION
|
|
696
|
+
const currentSpotMarket = this.driftClient.getSpotMarketAccount(spotPosition.marketIndex);
|
|
697
|
+
const tokenAmount = (0, spotBalance_1.getTokenAmount)(currentSpotPosition.scaledBalance, currentSpotMarket, currentSpotPosition.balanceType);
|
|
698
|
+
const tokenAmountQP = tokenAmount
|
|
699
|
+
.mul(numericConstants_1.QUOTE_PRECISION)
|
|
700
|
+
.div(new _1.BN(10 ** currentSpotMarket.decimals));
|
|
701
|
+
if (tokenAmountQP.abs().eq(numericConstants_1.ZERO)) {
|
|
702
|
+
return new _1.BN(-1);
|
|
703
|
+
}
|
|
704
|
+
let liqPriceDelta;
|
|
705
|
+
if ((0, types_1.isVariant)(currentSpotPosition.balanceType, 'borrow')) {
|
|
706
|
+
liqPriceDelta = deltaValueToLiq
|
|
707
|
+
.mul(numericConstants_1.PRICE_PRECISION)
|
|
708
|
+
.mul(numericConstants_1.SPOT_MARKET_WEIGHT_PRECISION)
|
|
709
|
+
.div(tokenAmountQP)
|
|
710
|
+
.div(new _1.BN(currentSpotMarket.maintenanceLiabilityWeight));
|
|
711
|
+
}
|
|
712
|
+
else {
|
|
713
|
+
liqPriceDelta = deltaValueToLiq
|
|
714
|
+
.mul(numericConstants_1.PRICE_PRECISION)
|
|
715
|
+
.mul(numericConstants_1.SPOT_MARKET_WEIGHT_PRECISION)
|
|
716
|
+
.div(tokenAmountQP)
|
|
717
|
+
.div(new _1.BN(currentSpotMarket.maintenanceAssetWeight))
|
|
718
|
+
.mul(new _1.BN(-1));
|
|
719
|
+
}
|
|
720
|
+
const currentPrice = this.driftClient.getOracleDataForSpotMarket(spotPosition.marketIndex).price;
|
|
721
|
+
const liqPrice = currentPrice.add(liqPriceDelta);
|
|
722
|
+
return liqPrice;
|
|
723
|
+
}
|
|
724
|
+
/**
|
|
725
|
+
* Calculate the liquidation price of a perp position, with optional parameter to calculate the liquidation price after a trade
|
|
644
726
|
* @param PerpPosition
|
|
645
727
|
* @param positionBaseSizeChange // change in position size to calculate liquidation price for : Precision 10^13
|
|
646
728
|
* @param partial
|
package/lib/userMap/userMap.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { User, DriftClient, OrderRecord, UserSubscriptionConfig
|
|
1
|
+
import { User, DriftClient, OrderRecord, UserSubscriptionConfig } from '..';
|
|
2
2
|
import { PublicKey } from '@solana/web3.js';
|
|
3
3
|
export interface UserMapInterface {
|
|
4
4
|
fetchAllUsers(): Promise<void>;
|
|
@@ -37,7 +37,6 @@ export declare class UserMap implements UserMapInterface {
|
|
|
37
37
|
*/
|
|
38
38
|
getUserAuthority(key: string): PublicKey | undefined;
|
|
39
39
|
updateWithOrderRecord(record: OrderRecord): Promise<void>;
|
|
40
|
-
updateWithEventRecord(record: WrappedEvent<any>): Promise<void>;
|
|
41
40
|
values(): IterableIterator<User>;
|
|
42
41
|
size(): number;
|
|
43
42
|
}
|
package/lib/userMap/userMap.js
CHANGED
|
@@ -80,46 +80,6 @@ class UserMap {
|
|
|
80
80
|
await this.addPubkey(record.user);
|
|
81
81
|
}
|
|
82
82
|
}
|
|
83
|
-
async updateWithEventRecord(record) {
|
|
84
|
-
if (record.eventType === 'DepositRecord') {
|
|
85
|
-
const depositRecord = record;
|
|
86
|
-
await this.mustGet(depositRecord.user.toString());
|
|
87
|
-
}
|
|
88
|
-
else if (record.eventType === 'FundingPaymentRecord') {
|
|
89
|
-
const fundingPaymentRecord = record;
|
|
90
|
-
await this.mustGet(fundingPaymentRecord.user.toString());
|
|
91
|
-
}
|
|
92
|
-
else if (record.eventType === 'LiquidationRecord') {
|
|
93
|
-
const liqRecord = record;
|
|
94
|
-
await this.mustGet(liqRecord.user.toString());
|
|
95
|
-
await this.mustGet(liqRecord.liquidator.toString());
|
|
96
|
-
}
|
|
97
|
-
else if (record.eventType === 'OrderRecord') {
|
|
98
|
-
const orderRecord = record;
|
|
99
|
-
await this.updateWithOrderRecord(orderRecord);
|
|
100
|
-
}
|
|
101
|
-
else if (record.eventType === 'OrderActionRecord') {
|
|
102
|
-
const actionRecord = record;
|
|
103
|
-
if (actionRecord.taker) {
|
|
104
|
-
await this.mustGet(actionRecord.taker.toString());
|
|
105
|
-
}
|
|
106
|
-
if (actionRecord.maker) {
|
|
107
|
-
await this.mustGet(actionRecord.maker.toString());
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
else if (record.eventType === 'SettlePnlRecord') {
|
|
111
|
-
const settlePnlRecord = record;
|
|
112
|
-
await this.mustGet(settlePnlRecord.user.toString());
|
|
113
|
-
}
|
|
114
|
-
else if (record.eventType === 'NewUserRecord') {
|
|
115
|
-
const newUserRecord = record;
|
|
116
|
-
await this.mustGet(newUserRecord.user.toString());
|
|
117
|
-
}
|
|
118
|
-
else if (record.eventType === 'LPRecord') {
|
|
119
|
-
const lpRecord = record;
|
|
120
|
-
await this.mustGet(lpRecord.user.toString());
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
83
|
values() {
|
|
124
84
|
return this.userMap.values();
|
|
125
85
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DriftClient, OrderRecord, UserStats, UserStatsSubscriptionConfig
|
|
1
|
+
import { DriftClient, OrderRecord, UserStats, UserStatsSubscriptionConfig } from '..';
|
|
2
2
|
import { PublicKey } from '@solana/web3.js';
|
|
3
3
|
import { UserMap } from './userMap';
|
|
4
4
|
export declare class UserStatsMap {
|
|
@@ -12,7 +12,6 @@ export declare class UserStatsMap {
|
|
|
12
12
|
fetchAllUserStats(): Promise<void>;
|
|
13
13
|
addUserStat(authority: PublicKey): Promise<void>;
|
|
14
14
|
updateWithOrderRecord(record: OrderRecord, userMap: UserMap): Promise<void>;
|
|
15
|
-
updateWithEventRecord(record: WrappedEvent<any>, userMap?: UserMap): Promise<void>;
|
|
16
15
|
has(authorityPublicKey: string): boolean;
|
|
17
16
|
get(authorityPublicKey: string): UserStats;
|
|
18
17
|
mustGet(authorityPublicKey: string): Promise<UserStats>;
|
|
@@ -49,71 +49,6 @@ class UserStatsMap {
|
|
|
49
49
|
this.addUserStat(user.getUserAccount().authority);
|
|
50
50
|
}
|
|
51
51
|
}
|
|
52
|
-
async updateWithEventRecord(record, userMap) {
|
|
53
|
-
if (record.eventType === 'DepositRecord') {
|
|
54
|
-
const depositRecord = record;
|
|
55
|
-
await this.mustGet(depositRecord.userAuthority.toString());
|
|
56
|
-
}
|
|
57
|
-
else if (record.eventType === 'FundingPaymentRecord') {
|
|
58
|
-
const fundingPaymentRecord = record;
|
|
59
|
-
await this.mustGet(fundingPaymentRecord.userAuthority.toString());
|
|
60
|
-
}
|
|
61
|
-
else if (record.eventType === 'LiquidationRecord') {
|
|
62
|
-
if (!userMap) {
|
|
63
|
-
return;
|
|
64
|
-
}
|
|
65
|
-
const liqRecord = record;
|
|
66
|
-
const user = await userMap.mustGet(liqRecord.user.toString());
|
|
67
|
-
await this.mustGet(user.getUserAccount().authority.toString());
|
|
68
|
-
const liquidatorUser = await userMap.mustGet(liqRecord.liquidator.toString());
|
|
69
|
-
await this.mustGet(liquidatorUser.getUserAccount().authority.toString());
|
|
70
|
-
}
|
|
71
|
-
else if (record.eventType === 'OrderRecord') {
|
|
72
|
-
if (!userMap) {
|
|
73
|
-
return;
|
|
74
|
-
}
|
|
75
|
-
const orderRecord = record;
|
|
76
|
-
await userMap.updateWithOrderRecord(orderRecord);
|
|
77
|
-
}
|
|
78
|
-
else if (record.eventType === 'OrderActionRecord') {
|
|
79
|
-
if (!userMap) {
|
|
80
|
-
return;
|
|
81
|
-
}
|
|
82
|
-
const actionRecord = record;
|
|
83
|
-
if (actionRecord.taker) {
|
|
84
|
-
const taker = await userMap.mustGet(actionRecord.taker.toString());
|
|
85
|
-
await this.mustGet(taker.getUserAccount().authority.toString());
|
|
86
|
-
}
|
|
87
|
-
if (actionRecord.maker) {
|
|
88
|
-
const maker = await userMap.mustGet(actionRecord.maker.toString());
|
|
89
|
-
await this.mustGet(maker.getUserAccount().authority.toString());
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
else if (record.eventType === 'SettlePnlRecord') {
|
|
93
|
-
if (!userMap) {
|
|
94
|
-
return;
|
|
95
|
-
}
|
|
96
|
-
const settlePnlRecord = record;
|
|
97
|
-
const user = await userMap.mustGet(settlePnlRecord.user.toString());
|
|
98
|
-
await this.mustGet(user.getUserAccount().authority.toString());
|
|
99
|
-
}
|
|
100
|
-
else if (record.eventType === 'NewUserRecord') {
|
|
101
|
-
const newUserRecord = record;
|
|
102
|
-
await this.mustGet(newUserRecord.userAuthority.toString());
|
|
103
|
-
}
|
|
104
|
-
else if (record.eventType === 'LPRecord') {
|
|
105
|
-
if (!userMap) {
|
|
106
|
-
return;
|
|
107
|
-
}
|
|
108
|
-
const lpRecord = record;
|
|
109
|
-
const user = await userMap.mustGet(lpRecord.user.toString());
|
|
110
|
-
await this.mustGet(user.getUserAccount().authority.toString());
|
|
111
|
-
}
|
|
112
|
-
else if (record.eventType === 'InsuranceFundStakeRecord') {
|
|
113
|
-
const ifStakeRecord = record;
|
|
114
|
-
await this.mustGet(ifStakeRecord.userAuthority.toString());
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
52
|
has(authorityPublicKey) {
|
|
118
53
|
return this.userStatsMap.has(authorityPublicKey);
|
|
119
54
|
}
|
package/package.json
CHANGED
package/src/adminClient.ts
CHANGED
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
MarketStatus,
|
|
12
12
|
ContractTier,
|
|
13
13
|
AssetTier,
|
|
14
|
+
SpotFulfillmentConfigStatus,
|
|
14
15
|
} from './types';
|
|
15
16
|
import { DEFAULT_MARKET_NAME, encodeName } from './userName';
|
|
16
17
|
import { BN } from '@project-serum/anchor';
|
|
@@ -881,6 +882,19 @@ export class AdminClient extends DriftClient {
|
|
|
881
882
|
});
|
|
882
883
|
}
|
|
883
884
|
|
|
885
|
+
public async updateSerumFulfillmentConfigStatus(
|
|
886
|
+
serumFulfillmentConfig: PublicKey,
|
|
887
|
+
status: SpotFulfillmentConfigStatus
|
|
888
|
+
): Promise<TransactionSignature> {
|
|
889
|
+
return await this.program.rpc.updateSerumFulfillmentConfigStatus(status, {
|
|
890
|
+
accounts: {
|
|
891
|
+
admin: this.wallet.publicKey,
|
|
892
|
+
state: await this.getStatePublicKey(),
|
|
893
|
+
serumFulfillmentConfig,
|
|
894
|
+
},
|
|
895
|
+
});
|
|
896
|
+
}
|
|
897
|
+
|
|
884
898
|
public async updateSpotMarketExpiry(
|
|
885
899
|
spotMarketIndex: number,
|
|
886
900
|
expiryTs: BN
|
package/src/config.ts
CHANGED
|
@@ -42,7 +42,7 @@ export const configs: { [key in DriftEnv]: DriftConfig } = {
|
|
|
42
42
|
PYTH_ORACLE_MAPPING_ADDRESS: 'AHtgzX45WTKfkPG53L6WYhGEXwQkN1BVknET3sVsLL8J',
|
|
43
43
|
DRIFT_PROGRAM_ID: 'dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH',
|
|
44
44
|
USDC_MINT_ADDRESS: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
|
|
45
|
-
SERUM_V3: '
|
|
45
|
+
SERUM_V3: 'srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX',
|
|
46
46
|
V2_ALPHA_TICKET_MINT_ADDRESS:
|
|
47
47
|
'Cmvhycb6LQvvzaShGw4iDHRLzeSSryioAsU98DSSkMNa',
|
|
48
48
|
PERP_MARKETS: MainnetPerpMarkets,
|
|
@@ -73,7 +73,7 @@ export const MainnetSpotMarkets: SpotMarketConfig[] = [
|
|
|
73
73
|
mint: new PublicKey(WRAPPED_SOL_MINT),
|
|
74
74
|
precision: LAMPORTS_PRECISION,
|
|
75
75
|
precisionExp: LAMPORTS_EXP,
|
|
76
|
-
serumMarket: new PublicKey('
|
|
76
|
+
serumMarket: new PublicKey('8BnEgHoWFysVcuFFX7QztDmzuH8r5ZFvyP3sYwn1XTh6'),
|
|
77
77
|
},
|
|
78
78
|
];
|
|
79
79
|
|