@drift-labs/sdk 0.1.36-master.5 → 0.2.0-master.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/lib/accounts/bulkAccountLoader.d.ts +7 -6
- package/lib/accounts/bulkAccountLoader.js +83 -93
- package/lib/accounts/bulkUserSubscription.js +13 -57
- package/lib/accounts/fetch.d.ts +4 -0
- package/lib/accounts/fetch.js +18 -0
- package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts +34 -38
- package/lib/accounts/pollingClearingHouseAccountSubscriber.js +224 -224
- package/lib/accounts/pollingOracleSubscriber.d.ts +3 -3
- package/lib/accounts/pollingOracleSubscriber.js +37 -49
- package/lib/accounts/pollingTokenAccountSubscriber.d.ts +3 -3
- package/lib/accounts/pollingTokenAccountSubscriber.js +35 -50
- package/lib/accounts/pollingUserAccountSubscriber.d.ts +7 -13
- package/lib/accounts/pollingUserAccountSubscriber.js +71 -134
- package/lib/accounts/types.d.ts +34 -41
- package/lib/accounts/webSocketAccountSubscriber.d.ts +6 -4
- package/lib/accounts/webSocketAccountSubscriber.js +39 -35
- package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +33 -28
- package/lib/accounts/webSocketClearingHouseAccountSubscriber.js +153 -185
- package/lib/accounts/webSocketUserAccountSubscriber.d.ts +5 -11
- package/lib/accounts/webSocketUserAccountSubscriber.js +22 -67
- package/lib/addresses/marketAddresses.d.ts +4 -0
- package/lib/addresses/marketAddresses.js +15 -0
- package/lib/addresses/pda.d.ts +12 -0
- package/lib/addresses/pda.js +83 -0
- package/lib/admin.d.ts +8 -12
- package/lib/admin.js +366 -490
- package/lib/clearingHouse.d.ts +84 -103
- package/lib/clearingHouse.js +779 -810
- package/lib/clearingHouseConfig.d.ts +34 -0
- package/lib/clearingHouseConfig.js +2 -0
- package/lib/clearingHouseUser.d.ts +19 -18
- package/lib/clearingHouseUser.js +157 -115
- package/lib/clearingHouseUserConfig.d.ts +14 -0
- package/lib/clearingHouseUserConfig.js +2 -0
- package/lib/config.d.ts +12 -0
- package/lib/config.js +35 -4
- package/lib/constants/banks.d.ts +16 -0
- package/lib/constants/banks.js +34 -0
- package/lib/constants/markets.d.ts +8 -3
- package/lib/constants/markets.js +13 -206
- package/lib/constants/numericConstants.d.ts +16 -0
- package/lib/constants/numericConstants.js +22 -6
- package/lib/events/eventList.d.ts +22 -0
- package/lib/events/eventList.js +77 -0
- package/lib/events/eventSubscriber.d.ts +34 -0
- package/lib/events/eventSubscriber.js +126 -0
- package/lib/events/fetchLogs.d.ts +13 -0
- package/lib/events/fetchLogs.js +39 -0
- package/lib/events/pollingLogProvider.d.ts +15 -0
- package/lib/events/pollingLogProvider.js +53 -0
- package/lib/events/sort.d.ts +2 -0
- package/lib/events/sort.js +44 -0
- package/lib/events/txEventCache.d.ts +24 -0
- package/lib/events/txEventCache.js +71 -0
- package/lib/events/types.d.ts +49 -0
- package/lib/events/types.js +20 -0
- package/lib/events/webSocketLogProvider.d.ts +12 -0
- package/lib/events/webSocketLogProvider.js +30 -0
- package/lib/examples/makeTradeExample.js +26 -27
- package/lib/factory/bigNum.d.ts +112 -0
- package/lib/factory/bigNum.js +356 -0
- package/lib/factory/oracleClient.d.ts +1 -2
- package/lib/factory/oracleClient.js +6 -2
- package/lib/idl/clearing_house.json +1739 -2287
- package/lib/index.d.ts +13 -4
- package/lib/index.js +13 -4
- package/lib/math/amm.d.ts +19 -29
- package/lib/math/amm.js +129 -179
- package/lib/math/auction.d.ts +5 -0
- package/lib/math/auction.js +39 -0
- package/lib/math/bankBalance.d.ts +9 -0
- package/lib/math/bankBalance.js +75 -0
- package/lib/math/conversion.d.ts +0 -1
- package/lib/math/conversion.js +1 -5
- package/lib/math/funding.d.ts +6 -6
- package/lib/math/funding.js +158 -175
- package/lib/math/market.d.ts +6 -6
- package/lib/math/market.js +10 -9
- package/lib/math/oracles.d.ts +3 -0
- package/lib/math/oracles.js +26 -0
- package/lib/math/orders.d.ts +5 -0
- package/lib/math/orders.js +31 -1
- package/lib/math/position.d.ts +7 -4
- package/lib/math/position.js +27 -9
- package/lib/math/repeg.d.ts +22 -0
- package/lib/math/repeg.js +128 -0
- package/lib/math/trade.d.ts +13 -8
- package/lib/math/trade.js +85 -22
- package/lib/mockUSDCFaucet.js +87 -116
- package/lib/oracles/oracleClientCache.d.ts +8 -0
- package/lib/oracles/oracleClientCache.js +19 -0
- package/lib/oracles/pythClient.d.ts +3 -5
- package/lib/oracles/pythClient.js +12 -30
- package/lib/oracles/quoteAssetOracleClient.d.ts +9 -0
- package/lib/oracles/quoteAssetOracleClient.js +21 -0
- package/lib/oracles/switchboardClient.d.ts +3 -5
- package/lib/oracles/switchboardClient.js +29 -47
- package/lib/oracles/types.d.ts +7 -1
- package/lib/orders.d.ts +6 -6
- package/lib/orders.js +10 -9
- package/lib/slot/SlotSubscriber.d.ts +12 -0
- package/lib/slot/SlotSubscriber.js +23 -0
- package/lib/tx/retryTxSender.d.ts +2 -2
- package/lib/tx/retryTxSender.js +108 -123
- package/lib/tx/types.d.ts +5 -1
- package/lib/tx/utils.d.ts +1 -1
- package/lib/tx/utils.js +11 -2
- package/lib/types.d.ts +105 -98
- package/lib/types.js +13 -1
- package/lib/userName.d.ts +4 -0
- package/lib/userName.js +20 -0
- package/lib/util/computeUnits.js +10 -21
- package/lib/util/tps.js +11 -22
- package/lib/wallet.js +7 -20
- package/package.json +10 -3
- package/src/accounts/bulkAccountLoader.ts +26 -15
- package/src/accounts/bulkUserSubscription.ts +1 -45
- package/src/accounts/fetch.ts +33 -0
- package/src/accounts/pollingClearingHouseAccountSubscriber.ts +249 -214
- package/src/accounts/pollingOracleSubscriber.ts +16 -8
- package/src/accounts/pollingTokenAccountSubscriber.ts +11 -8
- package/src/accounts/pollingUserAccountSubscriber.ts +21 -86
- package/src/accounts/types.ts +41 -70
- package/src/accounts/webSocketAccountSubscriber.ts +33 -16
- package/src/accounts/webSocketClearingHouseAccountSubscriber.ts +190 -240
- package/src/accounts/webSocketUserAccountSubscriber.ts +11 -71
- package/src/addresses/marketAddresses.ts +18 -0
- package/src/addresses/pda.ts +118 -0
- package/src/admin.ts +209 -267
- package/src/clearingHouse.ts +921 -829
- package/src/clearingHouseConfig.ts +37 -0
- package/src/clearingHouseUser.ts +280 -127
- package/src/clearingHouseUserConfig.ts +18 -0
- package/src/config.ts +54 -1
- package/src/constants/banks.ts +43 -0
- package/src/constants/markets.ts +16 -207
- package/src/constants/numericConstants.ts +33 -5
- package/src/events/eventList.ts +94 -0
- package/src/events/eventSubscriber.ts +194 -0
- package/src/events/fetchLogs.ts +80 -0
- package/src/events/pollingLogProvider.ts +79 -0
- package/src/events/sort.ts +65 -0
- package/src/events/txEventCache.ts +74 -0
- package/src/events/types.ts +98 -0
- package/src/events/webSocketLogProvider.ts +38 -0
- package/src/examples/makeTradeExample.ts +20 -11
- package/src/factory/bigNum.ts +507 -0
- package/src/factory/oracleClient.ts +7 -4
- package/src/idl/clearing_house.json +1739 -2287
- package/src/index.ts +13 -4
- package/src/math/amm.ts +229 -245
- package/src/math/auction.ts +39 -0
- package/src/math/bankBalance.ts +112 -0
- package/src/math/conversion.ts +1 -11
- package/src/math/funding.ts +12 -9
- package/src/math/market.ts +37 -30
- package/src/math/oracles.ts +36 -0
- package/src/math/orders.ts +38 -0
- package/src/math/position.ts +48 -13
- package/src/math/repeg.ts +175 -0
- package/src/math/trade.ts +114 -36
- package/src/math/utils.js +27 -0
- package/src/math/utils.js.map +1 -0
- package/src/oracles/oracleClientCache.ts +20 -0
- package/src/oracles/pythClient.ts +5 -11
- package/src/oracles/quoteAssetOracleClient.ts +25 -0
- package/src/oracles/switchboardClient.ts +16 -24
- package/src/oracles/types.ts +8 -1
- package/src/orders.ts +35 -20
- package/src/slot/SlotSubscriber.ts +32 -0
- package/src/tx/retryTxSender.ts +6 -4
- package/src/tx/types.ts +6 -1
- package/src/tx/utils.ts +22 -3
- package/src/types.ts +108 -110
- package/src/userName.ts +20 -0
- package/src/util/computeUnits.js +17 -0
- package/src/util/computeUnits.js.map +1 -0
- package/tests/bn/test.ts +255 -0
- package/tsconfig.json +12 -12
- package/lib/addresses.d.ts +0 -9
- package/lib/addresses.js +0 -87
- package/lib/constants/accounts.d.ts +0 -15
- package/lib/constants/accounts.js +0 -18
- package/lib/factory/clearingHouse.d.ts +0 -35
- package/lib/factory/clearingHouse.js +0 -81
- package/lib/factory/clearingHouseUser.d.ts +0 -19
- package/lib/factory/clearingHouseUser.js +0 -34
- package/lib/math/insuranceFund.d.ts +0 -15
- package/lib/math/insuranceFund.js +0 -33
- package/lib/tx/defaultTxSender.d.ts +0 -8
- package/lib/tx/defaultTxSender.js +0 -12
- package/src/addresses.ts +0 -71
- package/src/constants/accounts.ts +0 -26
- package/src/factory/clearingHouse.ts +0 -173
- package/src/factory/clearingHouseUser.ts +0 -73
- package/src/math/insuranceFund.ts +0 -29
- package/src/tx/defaultTxSender.ts +0 -24
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/// <reference types="bn.js" />
|
|
2
|
+
import { ConfirmOptions, Connection, PublicKey } from '@solana/web3.js';
|
|
3
|
+
import { IWallet } from './types';
|
|
4
|
+
import { BN } from '@project-serum/anchor';
|
|
5
|
+
import { OracleInfo } from './oracles/types';
|
|
6
|
+
import { BulkAccountLoader } from './accounts/bulkAccountLoader';
|
|
7
|
+
import { DriftEnv } from './config';
|
|
8
|
+
export declare type ClearingHouseConfig = {
|
|
9
|
+
connection: Connection;
|
|
10
|
+
wallet: IWallet;
|
|
11
|
+
programID: PublicKey;
|
|
12
|
+
accountSubscription?: ClearingHouseSubscriptionConfig;
|
|
13
|
+
opts?: ConfirmOptions;
|
|
14
|
+
txSenderConfig?: TxSenderConfig;
|
|
15
|
+
userIds?: number[];
|
|
16
|
+
activeUserId?: number;
|
|
17
|
+
marketIndexes?: BN[];
|
|
18
|
+
bankIndexes?: BN[];
|
|
19
|
+
oracleInfos?: OracleInfo[];
|
|
20
|
+
env?: DriftEnv;
|
|
21
|
+
};
|
|
22
|
+
declare type ClearingHouseSubscriptionConfig = {
|
|
23
|
+
type: 'websocket';
|
|
24
|
+
} | {
|
|
25
|
+
type: 'polling';
|
|
26
|
+
accountLoader: BulkAccountLoader;
|
|
27
|
+
};
|
|
28
|
+
declare type TxSenderConfig = {
|
|
29
|
+
type: 'retry';
|
|
30
|
+
timeout?: number;
|
|
31
|
+
retrySleep?: number;
|
|
32
|
+
additionalConnections?: Connection[];
|
|
33
|
+
};
|
|
34
|
+
export {};
|
|
@@ -4,27 +4,20 @@ import { PublicKey } from '@solana/web3.js';
|
|
|
4
4
|
import { EventEmitter } from 'events';
|
|
5
5
|
import StrictEventEmitter from 'strict-event-emitter-types';
|
|
6
6
|
import { ClearingHouse } from './clearingHouse';
|
|
7
|
-
import { MarginCategory, Order, UserAccount,
|
|
8
|
-
import { UserAccountSubscriber, UserAccountEvents } from './accounts/types';
|
|
7
|
+
import { MarginCategory, Order, UserAccount, UserPosition } from './types';
|
|
8
|
+
import { UserAccountSubscriber, UserAccountEvents, DataAndSlot } from './accounts/types';
|
|
9
9
|
import { PositionDirection, BN } from '.';
|
|
10
|
+
import { OraclePriceData } from './oracles/types';
|
|
11
|
+
import { ClearingHouseUserConfig } from './clearingHouseUserConfig';
|
|
10
12
|
export declare class ClearingHouseUser {
|
|
11
13
|
clearingHouse: ClearingHouse;
|
|
12
|
-
|
|
14
|
+
userAccountPublicKey: PublicKey;
|
|
13
15
|
accountSubscriber: UserAccountSubscriber;
|
|
14
|
-
userAccountPublicKey?: PublicKey;
|
|
15
|
-
userOrdersAccountPublicKey?: PublicKey;
|
|
16
16
|
_isSubscribed: boolean;
|
|
17
17
|
eventEmitter: StrictEventEmitter<EventEmitter, UserAccountEvents>;
|
|
18
18
|
get isSubscribed(): boolean;
|
|
19
19
|
set isSubscribed(val: boolean);
|
|
20
|
-
|
|
21
|
-
* @deprecated You should use getClearingHouseUser factory method instead
|
|
22
|
-
* @param clearingHouse
|
|
23
|
-
* @param authority
|
|
24
|
-
* @returns
|
|
25
|
-
*/
|
|
26
|
-
static from(clearingHouse: ClearingHouse, authority: PublicKey): ClearingHouseUser;
|
|
27
|
-
constructor(clearingHouse: ClearingHouse, authority: PublicKey, accountSubscriber: UserAccountSubscriber);
|
|
20
|
+
constructor(config: ClearingHouseUserConfig);
|
|
28
21
|
/**
|
|
29
22
|
* Subscribe to ClearingHouseUser state accounts
|
|
30
23
|
* @returns SusbcriptionSuccess result
|
|
@@ -36,8 +29,7 @@ export declare class ClearingHouseUser {
|
|
|
36
29
|
fetchAccounts(): Promise<void>;
|
|
37
30
|
unsubscribe(): Promise<void>;
|
|
38
31
|
getUserAccount(): UserAccount;
|
|
39
|
-
|
|
40
|
-
getUserOrdersAccount(): UserOrdersAccount | undefined;
|
|
32
|
+
getUserAccountAndSlot(): DataAndSlot<UserAccount> | undefined;
|
|
41
33
|
/**
|
|
42
34
|
* Gets the user's current position for a given market. If the user has no position returns undefined
|
|
43
35
|
* @param marketIndex
|
|
@@ -55,8 +47,7 @@ export declare class ClearingHouseUser {
|
|
|
55
47
|
* @returns Order
|
|
56
48
|
*/
|
|
57
49
|
getOrderByUserOrderId(userOrderId: number): Order | undefined;
|
|
58
|
-
getUserAccountPublicKey():
|
|
59
|
-
getUserOrdersAccountPublicKey(): Promise<PublicKey>;
|
|
50
|
+
getUserAccountPublicKey(): PublicKey;
|
|
60
51
|
exists(): Promise<boolean>;
|
|
61
52
|
/**
|
|
62
53
|
* calculates Buying Power = FC * MAX_LEVERAGE
|
|
@@ -78,13 +69,21 @@ export declare class ClearingHouseUser {
|
|
|
78
69
|
* @returns : Precision QUOTE_PRECISION
|
|
79
70
|
*/
|
|
80
71
|
getUnrealizedPNL(withFunding?: boolean, marketIndex?: BN): BN;
|
|
72
|
+
/**
|
|
73
|
+
* calculates unrealized position price pnl
|
|
74
|
+
* @returns : Precision QUOTE_PRECISION
|
|
75
|
+
*/
|
|
76
|
+
getUnsettledPNL(marketIndex?: BN): BN;
|
|
81
77
|
/**
|
|
82
78
|
* calculates unrealized funding payment pnl
|
|
83
79
|
* @returns : Precision QUOTE_PRECISION
|
|
84
80
|
*/
|
|
85
81
|
getUnrealizedFundingPNL(marketIndex?: BN): BN;
|
|
82
|
+
getTotalLiability(): BN;
|
|
83
|
+
getCollateralValue(bankIndex?: BN): BN;
|
|
86
84
|
/**
|
|
87
85
|
* calculates TotalCollateral: collateral + unrealized pnl
|
|
86
|
+
* TODO: rename to total equity (for perpetuals swaps)
|
|
88
87
|
* @returns : Precision QUOTE_PRECISION
|
|
89
88
|
*/
|
|
90
89
|
getTotalCollateral(): BN;
|
|
@@ -97,7 +96,7 @@ export declare class ClearingHouseUser {
|
|
|
97
96
|
* calculates position value from closing 100%
|
|
98
97
|
* @returns : Precision QUOTE_PRECISION
|
|
99
98
|
*/
|
|
100
|
-
getPositionValue(marketIndex: BN): BN;
|
|
99
|
+
getPositionValue(marketIndex: BN, oraclePriceData: OraclePriceData): BN;
|
|
101
100
|
getPositionSide(currentPosition: Pick<UserPosition, 'baseAssetAmount'>): PositionDirection | undefined;
|
|
102
101
|
/**
|
|
103
102
|
* calculates average exit price for closing 100% of position
|
|
@@ -183,4 +182,6 @@ export declare class ClearingHouseUser {
|
|
|
183
182
|
* @returns positionValue : Precision QUOTE_PRECISION
|
|
184
183
|
*/
|
|
185
184
|
private getTotalPositionValueExcludingMarket;
|
|
185
|
+
private getOracleDataForMarket;
|
|
186
|
+
private getOracleDataForBank;
|
|
186
187
|
}
|
package/lib/clearingHouseUser.js
CHANGED
|
@@ -1,27 +1,25 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
-
});
|
|
10
|
-
};
|
|
11
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
3
|
exports.ClearingHouseUser = void 0;
|
|
13
4
|
const types_1 = require("./types");
|
|
14
5
|
const position_1 = require("./math/position");
|
|
15
6
|
const numericConstants_1 = require("./constants/numericConstants");
|
|
16
7
|
const _1 = require(".");
|
|
17
|
-
const
|
|
18
|
-
const
|
|
8
|
+
const bankBalance_1 = require("./math/bankBalance");
|
|
9
|
+
const pollingUserAccountSubscriber_1 = require("./accounts/pollingUserAccountSubscriber");
|
|
10
|
+
const webSocketUserAccountSubscriber_1 = require("./accounts/webSocketUserAccountSubscriber");
|
|
19
11
|
class ClearingHouseUser {
|
|
20
|
-
constructor(
|
|
12
|
+
constructor(config) {
|
|
13
|
+
var _a;
|
|
21
14
|
this._isSubscribed = false;
|
|
22
|
-
this.clearingHouse = clearingHouse;
|
|
23
|
-
this.
|
|
24
|
-
|
|
15
|
+
this.clearingHouse = config.clearingHouse;
|
|
16
|
+
this.userAccountPublicKey = config.userAccountPublicKey;
|
|
17
|
+
if (((_a = config.accountSubscription) === null || _a === void 0 ? void 0 : _a.type) === 'polling') {
|
|
18
|
+
this.accountSubscriber = new pollingUserAccountSubscriber_1.PollingUserAccountSubscriber(config.clearingHouse.program, config.userAccountPublicKey, config.accountSubscription.accountLoader);
|
|
19
|
+
}
|
|
20
|
+
else {
|
|
21
|
+
this.accountSubscriber = new webSocketUserAccountSubscriber_1.WebSocketUserAccountSubscriber(config.clearingHouse.program, config.userAccountPublicKey);
|
|
22
|
+
}
|
|
25
23
|
this.eventEmitter = this.accountSubscriber.eventEmitter;
|
|
26
24
|
}
|
|
27
25
|
get isSubscribed() {
|
|
@@ -30,52 +28,29 @@ class ClearingHouseUser {
|
|
|
30
28
|
set isSubscribed(val) {
|
|
31
29
|
this._isSubscribed = val;
|
|
32
30
|
}
|
|
33
|
-
/**
|
|
34
|
-
* @deprecated You should use getClearingHouseUser factory method instead
|
|
35
|
-
* @param clearingHouse
|
|
36
|
-
* @param authority
|
|
37
|
-
* @returns
|
|
38
|
-
*/
|
|
39
|
-
static from(clearingHouse, authority) {
|
|
40
|
-
if (clearingHouse.accountSubscriber.type !== 'websocket')
|
|
41
|
-
throw 'This method only works for clearing houses with a websocket account listener. Try using the getClearingHouseUser factory method to initialize a ClearingHouseUser instead';
|
|
42
|
-
const config = (0, clearingHouseUser_1.getWebSocketClearingHouseUserConfig)(clearingHouse, authority);
|
|
43
|
-
return (0, clearingHouseUser_1.getClearingHouseUser)(config);
|
|
44
|
-
}
|
|
45
31
|
/**
|
|
46
32
|
* Subscribe to ClearingHouseUser state accounts
|
|
47
33
|
* @returns SusbcriptionSuccess result
|
|
48
34
|
*/
|
|
49
|
-
subscribe() {
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
yield this.clearingHouse.subscribe();
|
|
53
|
-
this.isSubscribed = yield this.accountSubscriber.subscribe();
|
|
54
|
-
return this.isSubscribed;
|
|
55
|
-
});
|
|
35
|
+
async subscribe() {
|
|
36
|
+
this.isSubscribed = await this.accountSubscriber.subscribe();
|
|
37
|
+
return this.isSubscribed;
|
|
56
38
|
}
|
|
57
39
|
/**
|
|
58
40
|
* Forces the accountSubscriber to fetch account updates from rpc
|
|
59
41
|
*/
|
|
60
|
-
fetchAccounts() {
|
|
61
|
-
|
|
62
|
-
yield this.accountSubscriber.fetch();
|
|
63
|
-
});
|
|
42
|
+
async fetchAccounts() {
|
|
43
|
+
await this.accountSubscriber.fetch();
|
|
64
44
|
}
|
|
65
|
-
unsubscribe() {
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
this.isSubscribed = false;
|
|
69
|
-
});
|
|
45
|
+
async unsubscribe() {
|
|
46
|
+
await this.accountSubscriber.unsubscribe();
|
|
47
|
+
this.isSubscribed = false;
|
|
70
48
|
}
|
|
71
49
|
getUserAccount() {
|
|
72
|
-
return this.accountSubscriber.
|
|
50
|
+
return this.accountSubscriber.getUserAccountAndSlot().data;
|
|
73
51
|
}
|
|
74
|
-
|
|
75
|
-
return this.accountSubscriber.
|
|
76
|
-
}
|
|
77
|
-
getUserOrdersAccount() {
|
|
78
|
-
return this.accountSubscriber.getUserOrdersAccount();
|
|
52
|
+
getUserAccountAndSlot() {
|
|
53
|
+
return this.accountSubscriber.getUserAccountAndSlot();
|
|
79
54
|
}
|
|
80
55
|
/**
|
|
81
56
|
* Gets the user's current position for a given market. If the user has no position returns undefined
|
|
@@ -83,7 +58,7 @@ class ClearingHouseUser {
|
|
|
83
58
|
* @returns userPosition
|
|
84
59
|
*/
|
|
85
60
|
getUserPosition(marketIndex) {
|
|
86
|
-
return this.
|
|
61
|
+
return this.getUserAccount().positions.find((position) => position.marketIndex.eq(marketIndex));
|
|
87
62
|
}
|
|
88
63
|
getEmptyPosition(marketIndex) {
|
|
89
64
|
return {
|
|
@@ -91,7 +66,11 @@ class ClearingHouseUser {
|
|
|
91
66
|
lastCumulativeFundingRate: numericConstants_1.ZERO,
|
|
92
67
|
marketIndex,
|
|
93
68
|
quoteAssetAmount: numericConstants_1.ZERO,
|
|
69
|
+
quoteEntryAmount: numericConstants_1.ZERO,
|
|
94
70
|
openOrders: numericConstants_1.ZERO,
|
|
71
|
+
unsettledPnl: numericConstants_1.ZERO,
|
|
72
|
+
openBids: numericConstants_1.ZERO,
|
|
73
|
+
openAsks: numericConstants_1.ZERO,
|
|
95
74
|
};
|
|
96
75
|
}
|
|
97
76
|
/**
|
|
@@ -99,39 +78,21 @@ class ClearingHouseUser {
|
|
|
99
78
|
* @returns Order
|
|
100
79
|
*/
|
|
101
80
|
getOrder(orderId) {
|
|
102
|
-
return this.
|
|
81
|
+
return this.getUserAccount().orders.find((order) => order.orderId.eq(orderId));
|
|
103
82
|
}
|
|
104
83
|
/**
|
|
105
84
|
* @param userOrderId
|
|
106
85
|
* @returns Order
|
|
107
86
|
*/
|
|
108
87
|
getOrderByUserOrderId(userOrderId) {
|
|
109
|
-
return this.
|
|
88
|
+
return this.getUserAccount().orders.find((order) => order.userOrderId === userOrderId);
|
|
110
89
|
}
|
|
111
90
|
getUserAccountPublicKey() {
|
|
112
|
-
return
|
|
113
|
-
if (this.userAccountPublicKey) {
|
|
114
|
-
return this.userAccountPublicKey;
|
|
115
|
-
}
|
|
116
|
-
this.userAccountPublicKey = yield (0, addresses_1.getUserAccountPublicKey)(this.clearingHouse.program.programId, this.authority);
|
|
117
|
-
return this.userAccountPublicKey;
|
|
118
|
-
});
|
|
119
|
-
}
|
|
120
|
-
getUserOrdersAccountPublicKey() {
|
|
121
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
122
|
-
if (this.userOrdersAccountPublicKey) {
|
|
123
|
-
return this.userOrdersAccountPublicKey;
|
|
124
|
-
}
|
|
125
|
-
this.userOrdersAccountPublicKey = yield (0, _1.getUserOrdersAccountPublicKey)(this.clearingHouse.program.programId, yield this.getUserAccountPublicKey());
|
|
126
|
-
return this.userOrdersAccountPublicKey;
|
|
127
|
-
});
|
|
91
|
+
return this.userAccountPublicKey;
|
|
128
92
|
}
|
|
129
|
-
exists() {
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
const userAccountRPCResponse = yield this.clearingHouse.connection.getParsedAccountInfo(userAccountPublicKey);
|
|
133
|
-
return userAccountRPCResponse.value !== null;
|
|
134
|
-
});
|
|
93
|
+
async exists() {
|
|
94
|
+
const userAccountRPCResponse = await this.clearingHouse.connection.getParsedAccountInfo(this.userAccountPublicKey);
|
|
95
|
+
return userAccountRPCResponse.value !== null;
|
|
135
96
|
}
|
|
136
97
|
/**
|
|
137
98
|
* calculates Buying Power = FC * MAX_LEVERAGE
|
|
@@ -153,34 +114,49 @@ class ClearingHouseUser {
|
|
|
153
114
|
return freeCollateral.gte(numericConstants_1.ZERO) ? freeCollateral : numericConstants_1.ZERO;
|
|
154
115
|
}
|
|
155
116
|
getInitialMarginRequirement() {
|
|
156
|
-
return this.
|
|
157
|
-
|
|
158
|
-
|
|
117
|
+
return this.getUserAccount()
|
|
118
|
+
.positions.reduce((marginRequirement, marketPosition) => {
|
|
119
|
+
const market = this.clearingHouse.getMarketAccount(marketPosition.marketIndex);
|
|
120
|
+
return marginRequirement.add((0, _1.calculateBaseAssetValue)(market, marketPosition, this.getOracleDataForMarket(market.marketIndex))
|
|
159
121
|
.mul(new _1.BN(market.marginRatioInitial))
|
|
160
122
|
.div(numericConstants_1.MARGIN_PRECISION));
|
|
161
|
-
}, numericConstants_1.ZERO)
|
|
123
|
+
}, numericConstants_1.ZERO)
|
|
124
|
+
.add(this.getTotalLiability());
|
|
162
125
|
}
|
|
163
126
|
/**
|
|
164
127
|
* @returns The partial margin requirement in USDC. : QUOTE_PRECISION
|
|
165
128
|
*/
|
|
166
129
|
getPartialMarginRequirement() {
|
|
167
|
-
return this.
|
|
168
|
-
|
|
169
|
-
|
|
130
|
+
return this.getUserAccount()
|
|
131
|
+
.positions.reduce((marginRequirement, marketPosition) => {
|
|
132
|
+
const market = this.clearingHouse.getMarketAccount(marketPosition.marketIndex);
|
|
133
|
+
return marginRequirement.add((0, _1.calculateBaseAssetValue)(market, marketPosition, this.getOracleDataForMarket(market.marketIndex))
|
|
170
134
|
.mul(new _1.BN(market.marginRatioPartial))
|
|
171
135
|
.div(numericConstants_1.MARGIN_PRECISION));
|
|
172
|
-
}, numericConstants_1.ZERO)
|
|
136
|
+
}, numericConstants_1.ZERO)
|
|
137
|
+
.add(this.getTotalLiability());
|
|
173
138
|
}
|
|
174
139
|
/**
|
|
175
140
|
* calculates unrealized position price pnl
|
|
176
141
|
* @returns : Precision QUOTE_PRECISION
|
|
177
142
|
*/
|
|
178
143
|
getUnrealizedPNL(withFunding, marketIndex) {
|
|
179
|
-
return this.
|
|
144
|
+
return this.getUserAccount()
|
|
145
|
+
.positions.filter((pos) => marketIndex ? pos.marketIndex === marketIndex : true)
|
|
146
|
+
.reduce((pnl, marketPosition) => {
|
|
147
|
+
const market = this.clearingHouse.getMarketAccount(marketPosition.marketIndex);
|
|
148
|
+
return pnl.add((0, _1.calculatePositionPNL)(market, marketPosition, withFunding, this.getOracleDataForMarket(market.marketIndex)));
|
|
149
|
+
}, numericConstants_1.ZERO);
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* calculates unrealized position price pnl
|
|
153
|
+
* @returns : Precision QUOTE_PRECISION
|
|
154
|
+
*/
|
|
155
|
+
getUnsettledPNL(marketIndex) {
|
|
156
|
+
return this.getUserAccount()
|
|
180
157
|
.positions.filter((pos) => marketIndex ? pos.marketIndex === marketIndex : true)
|
|
181
158
|
.reduce((pnl, marketPosition) => {
|
|
182
|
-
|
|
183
|
-
return pnl.add((0, _1.calculatePositionPNL)(market, marketPosition, withFunding));
|
|
159
|
+
return pnl.add(marketPosition.unsettledPnl);
|
|
184
160
|
}, numericConstants_1.ZERO);
|
|
185
161
|
}
|
|
186
162
|
/**
|
|
@@ -188,39 +164,88 @@ class ClearingHouseUser {
|
|
|
188
164
|
* @returns : Precision QUOTE_PRECISION
|
|
189
165
|
*/
|
|
190
166
|
getUnrealizedFundingPNL(marketIndex) {
|
|
191
|
-
return this.
|
|
167
|
+
return this.getUserAccount()
|
|
192
168
|
.positions.filter((pos) => marketIndex ? pos.marketIndex === marketIndex : true)
|
|
193
169
|
.reduce((pnl, marketPosition) => {
|
|
194
|
-
const market = this.clearingHouse.
|
|
170
|
+
const market = this.clearingHouse.getMarketAccount(marketPosition.marketIndex);
|
|
195
171
|
return pnl.add((0, _1.calculatePositionFundingPNL)(market, marketPosition));
|
|
196
172
|
}, numericConstants_1.ZERO);
|
|
197
173
|
}
|
|
174
|
+
getTotalLiability() {
|
|
175
|
+
return this.getUserAccount().bankBalances.reduce((totalAssetValue, bankBalance) => {
|
|
176
|
+
if (bankBalance.balance.eq(numericConstants_1.ZERO) ||
|
|
177
|
+
(0, types_1.isVariant)(bankBalance.balanceType, 'deposit')) {
|
|
178
|
+
return totalAssetValue;
|
|
179
|
+
}
|
|
180
|
+
// Todo this needs to account for whether it's based on initial or maintenance requirements
|
|
181
|
+
const bankAccount = this.clearingHouse.getBankAccount(bankBalance.bankIndex);
|
|
182
|
+
const tokenAmount = (0, bankBalance_1.getTokenAmount)(bankBalance.balance, bankAccount, bankBalance.balanceType);
|
|
183
|
+
return totalAssetValue.add(tokenAmount
|
|
184
|
+
.mul(this.getOracleDataForBank(bankAccount.bankIndex).price)
|
|
185
|
+
.mul(bankAccount.initialLiabilityWeight)
|
|
186
|
+
.div(numericConstants_1.BANK_WEIGHT_PRECISION)
|
|
187
|
+
.div(numericConstants_1.MARK_PRICE_PRECISION));
|
|
188
|
+
}, numericConstants_1.ZERO);
|
|
189
|
+
}
|
|
190
|
+
getCollateralValue(bankIndex) {
|
|
191
|
+
return this.getUserAccount().bankBalances.reduce((totalAssetValue, bankBalance) => {
|
|
192
|
+
if (bankBalance.balance.eq(numericConstants_1.ZERO) ||
|
|
193
|
+
(bankIndex !== undefined && !bankBalance.bankIndex.eq(bankIndex))) {
|
|
194
|
+
return totalAssetValue;
|
|
195
|
+
}
|
|
196
|
+
// Todo this needs to account for whether it's based on initial or maintenance requirements
|
|
197
|
+
const bankAccount = this.clearingHouse.getBankAccount(bankBalance.bankIndex);
|
|
198
|
+
let tokenAmount = (0, bankBalance_1.getTokenAmount)(bankBalance.balance, bankAccount, bankBalance.balanceType);
|
|
199
|
+
if ((0, types_1.isVariant)(bankBalance.balanceType, 'borrow')) {
|
|
200
|
+
tokenAmount = tokenAmount.mul(new _1.BN(-1));
|
|
201
|
+
}
|
|
202
|
+
return totalAssetValue.add(tokenAmount
|
|
203
|
+
.mul(this.getOracleDataForBank(bankAccount.bankIndex).price)
|
|
204
|
+
.div(numericConstants_1.MARK_PRICE_PRECISION));
|
|
205
|
+
}, numericConstants_1.ZERO);
|
|
206
|
+
}
|
|
198
207
|
/**
|
|
199
208
|
* calculates TotalCollateral: collateral + unrealized pnl
|
|
209
|
+
* TODO: rename to total equity (for perpetuals swaps)
|
|
200
210
|
* @returns : Precision QUOTE_PRECISION
|
|
201
211
|
*/
|
|
202
212
|
getTotalCollateral() {
|
|
203
|
-
|
|
204
|
-
|
|
213
|
+
return this.getUserAccount()
|
|
214
|
+
.bankBalances.reduce((totalAssetValue, bankBalance) => {
|
|
215
|
+
if (bankBalance.balance.eq(numericConstants_1.ZERO) ||
|
|
216
|
+
(0, types_1.isVariant)(bankBalance.balanceType, 'borrow')) {
|
|
217
|
+
return totalAssetValue;
|
|
218
|
+
}
|
|
219
|
+
// Todo this needs to account for whether it's based on initial or maintenance requirements
|
|
220
|
+
const bankAccount = this.clearingHouse.getBankAccount(bankBalance.bankIndex);
|
|
221
|
+
const tokenAmount = (0, bankBalance_1.getTokenAmount)(bankBalance.balance, bankAccount, bankBalance.balanceType);
|
|
222
|
+
return totalAssetValue.add(tokenAmount
|
|
223
|
+
.mul(this.getOracleDataForBank(bankAccount.bankIndex).price)
|
|
224
|
+
.mul(bankAccount.initialAssetWeight)
|
|
225
|
+
.div(numericConstants_1.BANK_WEIGHT_PRECISION)
|
|
226
|
+
.div(numericConstants_1.MARK_PRICE_PRECISION));
|
|
227
|
+
}, numericConstants_1.ZERO)
|
|
228
|
+
.add(this.getUnrealizedPNL(true))
|
|
229
|
+
.add(this.getUnsettledPNL());
|
|
205
230
|
}
|
|
206
231
|
/**
|
|
207
232
|
* calculates sum of position value across all positions
|
|
208
233
|
* @returns : Precision QUOTE_PRECISION
|
|
209
234
|
*/
|
|
210
235
|
getTotalPositionValue() {
|
|
211
|
-
return this.
|
|
212
|
-
const market = this.clearingHouse.
|
|
213
|
-
return positionValue.add((0, _1.calculateBaseAssetValue)(market, marketPosition));
|
|
236
|
+
return this.getUserAccount().positions.reduce((positionValue, marketPosition) => {
|
|
237
|
+
const market = this.clearingHouse.getMarketAccount(marketPosition.marketIndex);
|
|
238
|
+
return positionValue.add((0, _1.calculateBaseAssetValue)(market, marketPosition, this.getOracleDataForMarket(market.marketIndex)));
|
|
214
239
|
}, numericConstants_1.ZERO);
|
|
215
240
|
}
|
|
216
241
|
/**
|
|
217
242
|
* calculates position value from closing 100%
|
|
218
243
|
* @returns : Precision QUOTE_PRECISION
|
|
219
244
|
*/
|
|
220
|
-
getPositionValue(marketIndex) {
|
|
245
|
+
getPositionValue(marketIndex, oraclePriceData) {
|
|
221
246
|
const userPosition = this.getUserPosition(marketIndex) || this.getEmptyPosition(marketIndex);
|
|
222
|
-
const market = this.clearingHouse.
|
|
223
|
-
return (0, _1.calculateBaseAssetValue)(market, userPosition);
|
|
247
|
+
const market = this.clearingHouse.getMarketAccount(userPosition.marketIndex);
|
|
248
|
+
return (0, _1.calculateBaseAssetValue)(market, userPosition, oraclePriceData);
|
|
224
249
|
}
|
|
225
250
|
getPositionSide(currentPosition) {
|
|
226
251
|
if (currentPosition.baseAssetAmount.gt(numericConstants_1.ZERO)) {
|
|
@@ -238,11 +263,12 @@ class ClearingHouseUser {
|
|
|
238
263
|
* @returns : Precision MARK_PRICE_PRECISION
|
|
239
264
|
*/
|
|
240
265
|
getPositionEstimatedExitPriceAndPnl(position, amountToClose) {
|
|
241
|
-
const market = this.clearingHouse.
|
|
266
|
+
const market = this.clearingHouse.getMarketAccount(position.marketIndex);
|
|
242
267
|
const entryPrice = (0, position_1.calculateEntryPrice)(position);
|
|
268
|
+
const oraclePriceData = this.getOracleDataForMarket(position.marketIndex);
|
|
243
269
|
if (amountToClose) {
|
|
244
270
|
if (amountToClose.eq(numericConstants_1.ZERO)) {
|
|
245
|
-
return [(0, _1.calculateMarkPrice)(market), numericConstants_1.ZERO];
|
|
271
|
+
return [(0, _1.calculateMarkPrice)(market, oraclePriceData), numericConstants_1.ZERO];
|
|
246
272
|
}
|
|
247
273
|
position = {
|
|
248
274
|
baseAssetAmount: amountToClose,
|
|
@@ -251,7 +277,7 @@ class ClearingHouseUser {
|
|
|
251
277
|
quoteAssetAmount: position.quoteAssetAmount,
|
|
252
278
|
};
|
|
253
279
|
}
|
|
254
|
-
const baseAssetValue = (0, _1.calculateBaseAssetValue)(market, position);
|
|
280
|
+
const baseAssetValue = (0, _1.calculateBaseAssetValue)(market, position, oraclePriceData);
|
|
255
281
|
if (position.baseAssetAmount.eq(numericConstants_1.ZERO)) {
|
|
256
282
|
return [numericConstants_1.ZERO, numericConstants_1.ZERO];
|
|
257
283
|
}
|
|
@@ -284,7 +310,7 @@ class ClearingHouseUser {
|
|
|
284
310
|
* @returns : Precision TEN_THOUSAND
|
|
285
311
|
*/
|
|
286
312
|
getMaxLeverage(marketIndex, category = 'Initial') {
|
|
287
|
-
const market = this.clearingHouse.
|
|
313
|
+
const market = this.clearingHouse.getMarketAccount(marketIndex);
|
|
288
314
|
let marginRatioCategory;
|
|
289
315
|
switch (category) {
|
|
290
316
|
case 'Initial':
|
|
@@ -326,12 +352,11 @@ class ClearingHouseUser {
|
|
|
326
352
|
* @returns
|
|
327
353
|
*/
|
|
328
354
|
needsToSettleFundingPayment() {
|
|
329
|
-
const
|
|
330
|
-
for (const userPosition of this.getUserPositionsAccount().positions) {
|
|
355
|
+
for (const userPosition of this.getUserAccount().positions) {
|
|
331
356
|
if (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
|
|
332
357
|
continue;
|
|
333
358
|
}
|
|
334
|
-
const market =
|
|
359
|
+
const market = this.clearingHouse.getMarketAccount(userPosition.marketIndex);
|
|
335
360
|
if (market.amm.cumulativeFundingRateLong.eq(userPosition.lastCumulativeFundingRate) ||
|
|
336
361
|
market.amm.cumulativeFundingRateShort.eq(userPosition.lastCumulativeFundingRate)) {
|
|
337
362
|
continue;
|
|
@@ -371,18 +396,22 @@ class ClearingHouseUser {
|
|
|
371
396
|
baseAssetAmount: proposedBaseAssetAmount,
|
|
372
397
|
lastCumulativeFundingRate: currentMarketPosition.lastCumulativeFundingRate,
|
|
373
398
|
quoteAssetAmount: new _1.BN(0),
|
|
399
|
+
quoteEntryAmount: new _1.BN(0),
|
|
374
400
|
openOrders: new _1.BN(0),
|
|
401
|
+
unsettledPnl: new _1.BN(0),
|
|
402
|
+
openBids: new _1.BN(0),
|
|
403
|
+
openAsks: new _1.BN(0),
|
|
375
404
|
};
|
|
376
405
|
if (proposedBaseAssetAmount.eq(numericConstants_1.ZERO))
|
|
377
406
|
return new _1.BN(-1);
|
|
378
|
-
const market = this.clearingHouse.
|
|
379
|
-
const proposedMarketPositionValue = (0, _1.calculateBaseAssetValue)(market, proposedMarketPosition);
|
|
407
|
+
const market = this.clearingHouse.getMarketAccount(proposedMarketPosition.marketIndex);
|
|
408
|
+
const proposedMarketPositionValue = (0, _1.calculateBaseAssetValue)(market, proposedMarketPosition, this.getOracleDataForMarket(market.marketIndex));
|
|
380
409
|
// total position value after trade
|
|
381
410
|
const totalPositionValueAfterTrade = totalPositionValueExcludingTargetMarket.add(proposedMarketPositionValue);
|
|
382
|
-
const marginRequirementExcludingTargetMarket = this.
|
|
411
|
+
const marginRequirementExcludingTargetMarket = this.getUserAccount().positions.reduce((totalMarginRequirement, position) => {
|
|
383
412
|
if (!position.marketIndex.eq(marketPosition.marketIndex)) {
|
|
384
|
-
const market = this.clearingHouse.
|
|
385
|
-
const positionValue = (0, _1.calculateBaseAssetValue)(market, position);
|
|
413
|
+
const market = this.clearingHouse.getMarketAccount(position.marketIndex);
|
|
414
|
+
const positionValue = (0, _1.calculateBaseAssetValue)(market, position, this.getOracleDataForMarket(market.marketIndex));
|
|
386
415
|
const marketMarginRequirement = positionValue
|
|
387
416
|
.mul(partial
|
|
388
417
|
? new _1.BN(market.marginRatioPartial)
|
|
@@ -426,13 +455,13 @@ class ClearingHouseUser {
|
|
|
426
455
|
}
|
|
427
456
|
let markPriceAfterTrade;
|
|
428
457
|
if (positionBaseSizeChange.eq(numericConstants_1.ZERO)) {
|
|
429
|
-
markPriceAfterTrade = (0, _1.calculateMarkPrice)(this.clearingHouse.
|
|
458
|
+
markPriceAfterTrade = (0, _1.calculateMarkPrice)(this.clearingHouse.getMarketAccount(marketPosition.marketIndex), this.getOracleDataForMarket(marketPosition.marketIndex));
|
|
430
459
|
}
|
|
431
460
|
else {
|
|
432
461
|
const direction = positionBaseSizeChange.gt(numericConstants_1.ZERO)
|
|
433
462
|
? _1.PositionDirection.LONG
|
|
434
463
|
: _1.PositionDirection.SHORT;
|
|
435
|
-
markPriceAfterTrade = (0, _1.calculateTradeSlippage)(direction, positionBaseSizeChange.abs(), this.clearingHouse.
|
|
464
|
+
markPriceAfterTrade = (0, _1.calculateTradeSlippage)(direction, positionBaseSizeChange.abs(), this.clearingHouse.getMarketAccount(marketPosition.marketIndex), 'base', this.getOracleDataForMarket(marketPosition.marketIndex))[3]; // newPrice after swap
|
|
436
465
|
}
|
|
437
466
|
if (priceDelta.gt(markPriceAfterTrade)) {
|
|
438
467
|
return new _1.BN(-1);
|
|
@@ -457,7 +486,7 @@ class ClearingHouseUser {
|
|
|
457
486
|
.neg();
|
|
458
487
|
return this.liquidationPrice({
|
|
459
488
|
marketIndex: positionMarketIndex,
|
|
460
|
-
}, closeBaseAmount);
|
|
489
|
+
}, closeBaseAmount, true);
|
|
461
490
|
}
|
|
462
491
|
/**
|
|
463
492
|
* Get the maximum trade size for a given market, taking into account the user's current leverage, positions, collateral, etc.
|
|
@@ -490,10 +519,11 @@ class ClearingHouseUser {
|
|
|
490
519
|
const targetingSameSide = !currentPosition
|
|
491
520
|
? true
|
|
492
521
|
: targetSide === currentPositionSide;
|
|
522
|
+
const oracleData = this.getOracleDataForMarket(targetMarketIndex);
|
|
493
523
|
// add any position we have on the opposite side of the current trade, because we can "flip" the size of this position without taking any extra leverage.
|
|
494
524
|
const oppositeSizeValueUSDC = targetingSameSide
|
|
495
525
|
? numericConstants_1.ZERO
|
|
496
|
-
: this.getPositionValue(targetMarketIndex);
|
|
526
|
+
: this.getPositionValue(targetMarketIndex, oracleData);
|
|
497
527
|
let maxPositionSize = this.getBuyingPower(targetMarketIndex);
|
|
498
528
|
if (maxPositionSize.gte(numericConstants_1.ZERO)) {
|
|
499
529
|
if (oppositeSizeValueUSDC.eq(numericConstants_1.ZERO)) {
|
|
@@ -508,8 +538,8 @@ class ClearingHouseUser {
|
|
|
508
538
|
else {
|
|
509
539
|
// current leverage is greater than max leverage - can only reduce position size
|
|
510
540
|
if (!targetingSameSide) {
|
|
511
|
-
const market = this.clearingHouse.
|
|
512
|
-
const marketPositionValue = this.getPositionValue(targetMarketIndex);
|
|
541
|
+
const market = this.clearingHouse.getMarketAccount(targetMarketIndex);
|
|
542
|
+
const marketPositionValue = this.getPositionValue(targetMarketIndex, oracleData);
|
|
513
543
|
const totalCollateral = this.getTotalCollateral();
|
|
514
544
|
const marginRequirement = this.getInitialMarginRequirement();
|
|
515
545
|
const marginFreedByClosing = marketPositionValue
|
|
@@ -547,7 +577,8 @@ class ClearingHouseUser {
|
|
|
547
577
|
accountLeverageRatioAfterTrade(targetMarketIndex, tradeQuoteAmount, tradeSide) {
|
|
548
578
|
const currentPosition = this.getUserPosition(targetMarketIndex) ||
|
|
549
579
|
this.getEmptyPosition(targetMarketIndex);
|
|
550
|
-
|
|
580
|
+
const oracleData = this.getOracleDataForMarket(targetMarketIndex);
|
|
581
|
+
let currentPositionQuoteAmount = this.getPositionValue(targetMarketIndex, oracleData);
|
|
551
582
|
const currentSide = currentPosition && currentPosition.baseAssetAmount.isNeg()
|
|
552
583
|
? _1.PositionDirection.SHORT
|
|
553
584
|
: _1.PositionDirection.LONG;
|
|
@@ -591,11 +622,22 @@ class ClearingHouseUser {
|
|
|
591
622
|
getTotalPositionValueExcludingMarket(marketToIgnore) {
|
|
592
623
|
const currentMarketPosition = this.getUserPosition(marketToIgnore) ||
|
|
593
624
|
this.getEmptyPosition(marketToIgnore);
|
|
625
|
+
const oracleData = this.getOracleDataForMarket(marketToIgnore);
|
|
594
626
|
let currentMarketPositionValueUSDC = numericConstants_1.ZERO;
|
|
595
627
|
if (currentMarketPosition) {
|
|
596
|
-
currentMarketPositionValueUSDC = this.getPositionValue(marketToIgnore);
|
|
628
|
+
currentMarketPositionValueUSDC = this.getPositionValue(marketToIgnore, oracleData);
|
|
597
629
|
}
|
|
598
630
|
return this.getTotalPositionValue().sub(currentMarketPositionValueUSDC);
|
|
599
631
|
}
|
|
632
|
+
getOracleDataForMarket(marketIndex) {
|
|
633
|
+
const oracleKey = this.clearingHouse.getMarketAccount(marketIndex).amm.oracle;
|
|
634
|
+
const oracleData = this.clearingHouse.getOraclePriceDataAndSlot(oracleKey).data;
|
|
635
|
+
return oracleData;
|
|
636
|
+
}
|
|
637
|
+
getOracleDataForBank(bankIndex) {
|
|
638
|
+
const oracleKey = this.clearingHouse.getBankAccount(bankIndex).oracle;
|
|
639
|
+
const oracleData = this.clearingHouse.getOraclePriceDataAndSlot(oracleKey).data;
|
|
640
|
+
return oracleData;
|
|
641
|
+
}
|
|
600
642
|
}
|
|
601
643
|
exports.ClearingHouseUser = ClearingHouseUser;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { ClearingHouse } from './clearingHouse';
|
|
2
|
+
import { PublicKey } from '@solana/web3.js';
|
|
3
|
+
import { BulkAccountLoader } from './accounts/bulkAccountLoader';
|
|
4
|
+
export declare type ClearingHouseUserConfig = {
|
|
5
|
+
accountSubscription?: ClearingHouseUserAccountSubscriptionConfig;
|
|
6
|
+
clearingHouse: ClearingHouse;
|
|
7
|
+
userAccountPublicKey: PublicKey;
|
|
8
|
+
};
|
|
9
|
+
export declare type ClearingHouseUserAccountSubscriptionConfig = {
|
|
10
|
+
type: 'websocket';
|
|
11
|
+
} | {
|
|
12
|
+
type: 'polling';
|
|
13
|
+
accountLoader: BulkAccountLoader;
|
|
14
|
+
};
|
package/lib/config.d.ts
CHANGED
|
@@ -1,8 +1,15 @@
|
|
|
1
|
+
/// <reference types="bn.js" />
|
|
2
|
+
import { MarketConfig } from './constants/markets';
|
|
3
|
+
import { BankConfig } from './constants/banks';
|
|
4
|
+
import { BN } from '@project-serum/anchor';
|
|
5
|
+
import { OracleInfo } from './oracles/types';
|
|
1
6
|
declare type DriftConfig = {
|
|
2
7
|
ENV: DriftEnv;
|
|
3
8
|
PYTH_ORACLE_MAPPING_ADDRESS: string;
|
|
4
9
|
CLEARING_HOUSE_PROGRAM_ID: string;
|
|
5
10
|
USDC_MINT_ADDRESS: string;
|
|
11
|
+
MARKETS: MarketConfig[];
|
|
12
|
+
BANKS: BankConfig[];
|
|
6
13
|
};
|
|
7
14
|
export declare type DriftEnv = 'devnet' | 'mainnet-beta';
|
|
8
15
|
export declare const configs: {
|
|
@@ -20,4 +27,9 @@ export declare const initialize: (props: {
|
|
|
20
27
|
env: DriftEnv;
|
|
21
28
|
overrideEnv?: Partial<DriftConfig>;
|
|
22
29
|
}) => DriftConfig;
|
|
30
|
+
export declare function getMarketsBanksAndOraclesForSubscription(env: DriftEnv): {
|
|
31
|
+
marketIndexes: BN[];
|
|
32
|
+
bankIndexes: BN[];
|
|
33
|
+
oracleInfos: OracleInfo[];
|
|
34
|
+
};
|
|
23
35
|
export {};
|