@drift-labs/sdk 2.20.0-beta.0 → 2.20.0-beta.1
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 +2 -1
- package/lib/accounts/bulkAccountLoader.js +7 -7
- package/lib/accounts/fetch.d.ts +1 -0
- package/lib/accounts/fetch.js +8 -4
- package/lib/accounts/pollingDriftClientAccountSubscriber.js +7 -7
- package/lib/accounts/pollingTokenAccountSubscriber.js +2 -2
- package/lib/accounts/pollingUserAccountSubscriber.js +2 -2
- package/lib/accounts/pollingUserStatsAccountSubscriber.js +2 -2
- package/lib/accounts/types.d.ts +5 -4
- package/lib/accounts/webSocketAccountSubscriber.js +1 -1
- package/lib/accounts/webSocketDriftClientAccountSubscriber.js +3 -3
- package/lib/addresses/marketAddresses.js +1 -1
- package/lib/addresses/pda.js +5 -1
- package/lib/adminClient.js +61 -57
- package/lib/config.d.ts +2 -2
- package/lib/constants/perpMarkets.d.ts +1 -1
- package/lib/constants/spotMarkets.d.ts +1 -1
- package/lib/dlob/DLOB.d.ts +6 -5
- package/lib/dlob/DLOB.js +105 -75
- package/lib/dlob/DLOBNode.d.ts +2 -2
- package/lib/dlob/DLOBNode.js +7 -7
- package/lib/dlob/DLOBOrders.d.ts +2 -2
- package/lib/dlob/NodeList.d.ts +1 -1
- package/lib/dlob/NodeList.js +2 -2
- package/lib/driftClient.d.ts +3 -2
- package/lib/driftClient.js +114 -95
- package/lib/driftClientConfig.d.ts +3 -3
- package/lib/events/eventSubscriber.js +2 -2
- package/lib/events/fetchLogs.d.ts +2 -2
- package/lib/events/pollingLogProvider.js +1 -1
- package/lib/events/types.d.ts +14 -14
- package/lib/examples/loadDlob.js +2 -2
- package/lib/examples/makeTradeExample.js +9 -9
- package/lib/factory/bigNum.js +13 -13
- package/lib/factory/oracleClient.js +4 -4
- package/lib/idl/drift.json +1 -1
- package/lib/index.js +5 -1
- package/lib/math/amm.d.ts +1 -1
- package/lib/math/amm.js +23 -23
- package/lib/math/auction.js +6 -6
- package/lib/math/exchangeStatus.js +2 -2
- package/lib/math/funding.js +2 -2
- package/lib/math/margin.js +4 -4
- package/lib/math/market.js +15 -15
- package/lib/math/oracles.js +1 -1
- package/lib/math/orders.js +27 -24
- package/lib/math/position.js +5 -5
- package/lib/math/repeg.js +1 -1
- package/lib/math/spotBalance.js +9 -9
- package/lib/math/spotMarket.js +3 -3
- package/lib/math/spotPosition.js +3 -3
- package/lib/math/trade.d.ts +1 -1
- package/lib/math/trade.js +42 -42
- package/lib/math/utils.js +1 -1
- package/lib/oracles/oracleClientCache.js +1 -1
- package/lib/oracles/pythClient.js +1 -1
- package/lib/oracles/types.d.ts +2 -2
- package/lib/serum/types.d.ts +1 -1
- package/lib/slot/SlotSubscriber.d.ts +1 -1
- package/lib/tokenFaucet.js +5 -1
- package/lib/tx/retryTxSender.d.ts +1 -1
- package/lib/tx/retryTxSender.js +1 -1
- package/lib/tx/types.d.ts +1 -1
- package/lib/types.d.ts +65 -44
- package/lib/user.js +63 -63
- package/lib/userConfig.d.ts +2 -2
- package/lib/userMap/userMap.js +1 -1
- package/lib/userMap/userStatsMap.js +3 -3
- package/lib/userStats.js +2 -2
- package/lib/userStatsConfig.d.ts +2 -2
- package/package.json +1 -1
- package/src/accounts/bulkAccountLoader.ts +5 -5
- package/src/accounts/fetch.ts +8 -0
- package/src/dlob/DLOB.ts +55 -8
- package/src/driftClient.ts +28 -0
- package/src/idl/drift.json +1 -1
- package/src/math/orders.ts +5 -1
- package/src/types.ts +22 -0
- package/src/userMap/userStatsMap.ts +1 -4
- package/tests/amm/test.ts +24 -28
- package/tests/dlob/test.ts +67 -73
|
@@ -3,7 +3,7 @@ import { IWallet } from './types';
|
|
|
3
3
|
import { OracleInfo } from './oracles/types';
|
|
4
4
|
import { BulkAccountLoader } from './accounts/bulkAccountLoader';
|
|
5
5
|
import { DriftEnv } from './config';
|
|
6
|
-
export
|
|
6
|
+
export type DriftClientConfig = {
|
|
7
7
|
connection: Connection;
|
|
8
8
|
wallet: IWallet;
|
|
9
9
|
programID: PublicKey;
|
|
@@ -20,13 +20,13 @@ export declare type DriftClientConfig = {
|
|
|
20
20
|
userStats?: boolean;
|
|
21
21
|
authority?: PublicKey;
|
|
22
22
|
};
|
|
23
|
-
export
|
|
23
|
+
export type DriftClientSubscriptionConfig = {
|
|
24
24
|
type: 'websocket';
|
|
25
25
|
} | {
|
|
26
26
|
type: 'polling';
|
|
27
27
|
accountLoader: BulkAccountLoader;
|
|
28
28
|
};
|
|
29
|
-
|
|
29
|
+
type TxSenderConfig = {
|
|
30
30
|
type: 'retry';
|
|
31
31
|
timeout?: number;
|
|
32
32
|
retrySleep?: number;
|
|
@@ -20,7 +20,7 @@ class EventSubscriber {
|
|
|
20
20
|
this.txEventCache = new txEventCache_1.TxEventCache(this.options.maxTx);
|
|
21
21
|
this.eventListMap = new Map();
|
|
22
22
|
for (const eventType of this.options.eventTypes) {
|
|
23
|
-
this.eventListMap.set(eventType, new eventList_1.EventList(eventType, this.options.maxEventsPerType, sort_1.getSortFn(this.options.orderBy, this.options.orderDir, eventType), this.options.orderDir));
|
|
23
|
+
this.eventListMap.set(eventType, new eventList_1.EventList(eventType, this.options.maxEventsPerType, (0, sort_1.getSortFn)(this.options.orderBy, this.options.orderDir, eventType), this.options.orderDir));
|
|
24
24
|
}
|
|
25
25
|
this.eventEmitter = new events_1.EventEmitter();
|
|
26
26
|
if (this.options.logProviderConfig.type === 'websocket') {
|
|
@@ -80,7 +80,7 @@ class EventSubscriber {
|
|
|
80
80
|
let beforeTx = undefined;
|
|
81
81
|
const untilTx = this.options.untilTx;
|
|
82
82
|
while (txFetched < this.options.maxTx) {
|
|
83
|
-
const response = await fetchLogs_1.fetchLogs(this.connection, this.program.programId, this.options.commitment === 'finalized' ? 'finalized' : 'confirmed', beforeTx, untilTx);
|
|
83
|
+
const response = await (0, fetchLogs_1.fetchLogs)(this.connection, this.program.programId, this.options.commitment === 'finalized' ? 'finalized' : 'confirmed', beforeTx, untilTx);
|
|
84
84
|
if (response === undefined) {
|
|
85
85
|
break;
|
|
86
86
|
}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { Program } from '@project-serum/anchor';
|
|
2
2
|
import { Connection, Finality, PublicKey, TransactionResponse, TransactionSignature } from '@solana/web3.js';
|
|
3
3
|
import { WrappedEvents } from './types';
|
|
4
|
-
|
|
4
|
+
type Log = {
|
|
5
5
|
txSig: TransactionSignature;
|
|
6
6
|
slot: number;
|
|
7
7
|
logs: string[];
|
|
8
8
|
};
|
|
9
|
-
|
|
9
|
+
type FetchLogsResponse = {
|
|
10
10
|
earliestTx: string;
|
|
11
11
|
mostRecentTx: string;
|
|
12
12
|
earliestSlot: number;
|
|
@@ -20,7 +20,7 @@ class PollingLogProvider {
|
|
|
20
20
|
}
|
|
21
21
|
this.mutex = 1;
|
|
22
22
|
try {
|
|
23
|
-
const response = await fetchLogs_1.fetchLogs(this.connection, this.programId, this.finality, undefined, this.mostRecentSeenTx,
|
|
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
26
|
if (response === undefined) {
|
package/lib/events/types.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Commitment, TransactionSignature } from '@solana/web3.js';
|
|
2
2
|
import { DepositRecord, FundingPaymentRecord, FundingRateRecord, LiquidationRecord, NewUserRecord, OrderActionRecord, OrderRecord, SettlePnlRecord, LPRecord, InsuranceFundRecord, SpotInterestRecord, InsuranceFundStakeRecord, CurveRecord } from '../index';
|
|
3
|
-
export
|
|
3
|
+
export type EventSubscriptionOptions = {
|
|
4
4
|
eventTypes?: EventType[];
|
|
5
5
|
maxEventsPerType?: number;
|
|
6
6
|
orderBy?: EventSubscriptionOrderBy;
|
|
@@ -11,17 +11,17 @@ export declare type EventSubscriptionOptions = {
|
|
|
11
11
|
untilTx?: TransactionSignature;
|
|
12
12
|
};
|
|
13
13
|
export declare const DefaultEventSubscriptionOptions: EventSubscriptionOptions;
|
|
14
|
-
export
|
|
15
|
-
export
|
|
16
|
-
export
|
|
14
|
+
export type EventSubscriptionOrderBy = 'blockchain' | 'client';
|
|
15
|
+
export type EventSubscriptionOrderDirection = 'asc' | 'desc';
|
|
16
|
+
export type Event<T> = T & {
|
|
17
17
|
txSig: TransactionSignature;
|
|
18
18
|
slot: number;
|
|
19
19
|
};
|
|
20
|
-
export
|
|
20
|
+
export type WrappedEvent<Type extends EventType> = EventMap[Type] & {
|
|
21
21
|
eventType: Type;
|
|
22
22
|
};
|
|
23
|
-
export
|
|
24
|
-
export
|
|
23
|
+
export type WrappedEvents = WrappedEvent<EventType>[];
|
|
24
|
+
export type EventMap = {
|
|
25
25
|
DepositRecord: Event<DepositRecord>;
|
|
26
26
|
FundingPaymentRecord: Event<FundingPaymentRecord>;
|
|
27
27
|
LiquidationRecord: Event<LiquidationRecord>;
|
|
@@ -36,23 +36,23 @@ export declare type EventMap = {
|
|
|
36
36
|
InsuranceFundStakeRecord: Event<InsuranceFundStakeRecord>;
|
|
37
37
|
CurveRecord: Event<CurveRecord>;
|
|
38
38
|
};
|
|
39
|
-
export
|
|
40
|
-
export
|
|
39
|
+
export type EventType = keyof EventMap;
|
|
40
|
+
export type DriftEvent = Event<DepositRecord> | Event<FundingPaymentRecord> | Event<LiquidationRecord> | Event<FundingRateRecord> | Event<OrderRecord> | Event<OrderActionRecord> | Event<SettlePnlRecord> | Event<NewUserRecord> | Event<LPRecord> | Event<InsuranceFundRecord> | Event<SpotInterestRecord> | Event<InsuranceFundStakeRecord> | Event<CurveRecord>;
|
|
41
41
|
export interface EventSubscriberEvents {
|
|
42
42
|
newEvent: (event: WrappedEvent<EventType>) => void;
|
|
43
43
|
}
|
|
44
|
-
export
|
|
45
|
-
export
|
|
44
|
+
export type SortFn = (currentRecord: EventMap[EventType], newRecord: EventMap[EventType]) => 'less than' | 'greater than';
|
|
45
|
+
export type logProviderCallback = (txSig: TransactionSignature, slot: number, logs: string[], mostRecentBlockTime: number | undefined) => void;
|
|
46
46
|
export interface LogProvider {
|
|
47
47
|
isSubscribed(): boolean;
|
|
48
48
|
subscribe(callback: logProviderCallback, skipHistory?: boolean): boolean;
|
|
49
49
|
unsubscribe(): Promise<boolean>;
|
|
50
50
|
}
|
|
51
|
-
export
|
|
51
|
+
export type WebSocketLogProviderConfig = {
|
|
52
52
|
type: 'websocket';
|
|
53
53
|
};
|
|
54
|
-
export
|
|
54
|
+
export type PollingLogProviderConfig = {
|
|
55
55
|
type: 'polling';
|
|
56
56
|
frequency: number;
|
|
57
57
|
};
|
|
58
|
-
export
|
|
58
|
+
export type LogProviderConfig = WebSocketLogProviderConfig | PollingLogProviderConfig;
|
package/lib/examples/loadDlob.js
CHANGED
|
@@ -7,7 +7,7 @@ const __2 = require("..");
|
|
|
7
7
|
const env = 'mainnet-beta';
|
|
8
8
|
const main = async () => {
|
|
9
9
|
// Initialize Drift SDK
|
|
10
|
-
const sdkConfig = __2.initialize({ env });
|
|
10
|
+
const sdkConfig = (0, __2.initialize)({ env });
|
|
11
11
|
// Set up the Wallet and Provider
|
|
12
12
|
const privateKey = process.env.BOT_PRIVATE_KEY; // stored as an array string
|
|
13
13
|
const keypair = web3_js_1.Keypair.fromSecretKey(Uint8Array.from(JSON.parse(privateKey)));
|
|
@@ -24,7 +24,7 @@ const main = async () => {
|
|
|
24
24
|
connection,
|
|
25
25
|
wallet: provider.wallet,
|
|
26
26
|
programID: driftPublicKey,
|
|
27
|
-
...__2.getMarketsAndOraclesForSubscription(env),
|
|
27
|
+
...(0, __2.getMarketsAndOraclesForSubscription)(env),
|
|
28
28
|
accountSubscription: {
|
|
29
29
|
type: 'polling',
|
|
30
30
|
accountLoader: bulkAccountLoader,
|
|
@@ -14,7 +14,7 @@ exports.getTokenAddress = getTokenAddress;
|
|
|
14
14
|
const env = 'devnet';
|
|
15
15
|
const main = async () => {
|
|
16
16
|
// Initialize Drift SDK
|
|
17
|
-
const sdkConfig = __2.initialize({ env });
|
|
17
|
+
const sdkConfig = (0, __2.initialize)({ env });
|
|
18
18
|
// Set up the Wallet and Provider
|
|
19
19
|
const privateKey = process.env.BOT_PRIVATE_KEY; // stored as an array string
|
|
20
20
|
const keypair = web3_js_1.Keypair.fromSecretKey(Uint8Array.from(JSON.parse(privateKey)));
|
|
@@ -28,7 +28,7 @@ const main = async () => {
|
|
|
28
28
|
const lamportsBalance = await connection.getBalance(wallet.publicKey);
|
|
29
29
|
console.log('SOL balance:', lamportsBalance / 10 ** 9);
|
|
30
30
|
// Misc. other things to set up
|
|
31
|
-
const usdcTokenAddress = await exports.getTokenAddress(sdkConfig.USDC_MINT_ADDRESS, wallet.publicKey.toString());
|
|
31
|
+
const usdcTokenAddress = await (0, exports.getTokenAddress)(sdkConfig.USDC_MINT_ADDRESS, wallet.publicKey.toString());
|
|
32
32
|
// Set up the Drift Clearing House
|
|
33
33
|
const driftPublicKey = new web3_js_1.PublicKey(sdkConfig.DRIFT_PROGRAM_ID);
|
|
34
34
|
const bulkAccountLoader = new __2.BulkAccountLoader(connection, 'confirmed', 1000);
|
|
@@ -36,7 +36,7 @@ const main = async () => {
|
|
|
36
36
|
connection,
|
|
37
37
|
wallet: provider.wallet,
|
|
38
38
|
programID: driftPublicKey,
|
|
39
|
-
...__2.getMarketsAndOraclesForSubscription(env),
|
|
39
|
+
...(0, __2.getMarketsAndOraclesForSubscription)(env),
|
|
40
40
|
accountSubscription: {
|
|
41
41
|
type: 'polling',
|
|
42
42
|
accountLoader: bulkAccountLoader,
|
|
@@ -57,21 +57,21 @@ const main = async () => {
|
|
|
57
57
|
if (!userAccountExists) {
|
|
58
58
|
//// Create a Clearing House account by Depositing some USDC ($10,000 in this case)
|
|
59
59
|
const depositAmount = new anchor_1.BN(10000).mul(__2.QUOTE_PRECISION);
|
|
60
|
-
await driftClient.initializeUserAccountAndDepositCollateral(depositAmount, await exports.getTokenAddress(usdcTokenAddress.toString(), wallet.publicKey.toString()), spotMarkets_1.SpotMarkets['devnet'][0].marketIndex);
|
|
60
|
+
await driftClient.initializeUserAccountAndDepositCollateral(depositAmount, await (0, exports.getTokenAddress)(usdcTokenAddress.toString(), wallet.publicKey.toString()), spotMarkets_1.SpotMarkets['devnet'][0].marketIndex);
|
|
61
61
|
}
|
|
62
62
|
await user.subscribe();
|
|
63
63
|
// Get current price
|
|
64
64
|
const solMarketInfo = sdkConfig.PERP_MARKETS.find((market) => market.baseAssetSymbol === 'SOL');
|
|
65
65
|
const marketIndex = solMarketInfo.marketIndex;
|
|
66
|
-
const [bid, ask] = __1.calculateBidAskPrice(driftClient.getPerpMarketAccount(marketIndex).amm, driftClient.getOracleDataForPerpMarket(marketIndex));
|
|
67
|
-
const formattedBidPrice = __2.convertToNumber(bid, __2.PRICE_PRECISION);
|
|
68
|
-
const formattedAskPrice = __2.convertToNumber(ask, __2.PRICE_PRECISION);
|
|
66
|
+
const [bid, ask] = (0, __1.calculateBidAskPrice)(driftClient.getPerpMarketAccount(marketIndex).amm, driftClient.getOracleDataForPerpMarket(marketIndex));
|
|
67
|
+
const formattedBidPrice = (0, __2.convertToNumber)(bid, __2.PRICE_PRECISION);
|
|
68
|
+
const formattedAskPrice = (0, __2.convertToNumber)(ask, __2.PRICE_PRECISION);
|
|
69
69
|
console.log(`Current amm bid and ask price are $${formattedBidPrice} and $${formattedAskPrice}`);
|
|
70
70
|
// Estimate the slippage for a $5000 LONG trade
|
|
71
71
|
const solMarketAccount = driftClient.getPerpMarketAccount(solMarketInfo.marketIndex);
|
|
72
|
-
const slippage = __2.convertToNumber(__2.calculateTradeSlippage(__2.PositionDirection.LONG, new anchor_1.BN(1).mul(__1.BASE_PRECISION), solMarketAccount, 'base', driftClient.getOracleDataForPerpMarket(solMarketInfo.marketIndex))[0], __2.PRICE_PRECISION);
|
|
72
|
+
const slippage = (0, __2.convertToNumber)((0, __2.calculateTradeSlippage)(__2.PositionDirection.LONG, new anchor_1.BN(1).mul(__1.BASE_PRECISION), solMarketAccount, 'base', driftClient.getOracleDataForPerpMarket(solMarketInfo.marketIndex))[0], __2.PRICE_PRECISION);
|
|
73
73
|
console.log(`Slippage for a 1 SOL-PERP would be $${slippage}`);
|
|
74
|
-
await driftClient.placePerpOrder(__1.getMarketOrderParams({
|
|
74
|
+
await driftClient.placePerpOrder((0, __1.getMarketOrderParams)({
|
|
75
75
|
baseAssetAmount: new anchor_1.BN(1).mul(__1.BASE_PRECISION),
|
|
76
76
|
direction: __2.PositionDirection.LONG,
|
|
77
77
|
marketIndex: solMarketAccount.marketIndex,
|
package/lib/factory/bigNum.js
CHANGED
|
@@ -5,24 +5,24 @@ const anchor_1 = require("@project-serum/anchor");
|
|
|
5
5
|
const assert_1 = require("../assert/assert");
|
|
6
6
|
const numericConstants_1 = require("./../constants/numericConstants");
|
|
7
7
|
class BigNum {
|
|
8
|
+
static setLocale(locale) {
|
|
9
|
+
BigNum.delim = (1.1).toLocaleString(locale).slice(1, 2) || '.';
|
|
10
|
+
BigNum.spacer = (1000).toLocaleString(locale).slice(1, 2) || ',';
|
|
11
|
+
}
|
|
8
12
|
constructor(val, precisionVal = new anchor_1.BN(0)) {
|
|
9
13
|
this.toString = (base, length) => this.val.toString(base, length);
|
|
10
14
|
this.val = new anchor_1.BN(val);
|
|
11
15
|
this.precision = new anchor_1.BN(precisionVal);
|
|
12
16
|
}
|
|
13
|
-
static setLocale(locale) {
|
|
14
|
-
BigNum.delim = (1.1).toLocaleString(locale).slice(1, 2) || '.';
|
|
15
|
-
BigNum.spacer = (1000).toLocaleString(locale).slice(1, 2) || ',';
|
|
16
|
-
}
|
|
17
17
|
bigNumFromParam(bn) {
|
|
18
18
|
return anchor_1.BN.isBN(bn) ? BigNum.from(bn) : bn;
|
|
19
19
|
}
|
|
20
20
|
add(bn) {
|
|
21
|
-
assert_1.assert(bn.precision.eq(this.precision), 'Adding unequal precisions');
|
|
21
|
+
(0, assert_1.assert)(bn.precision.eq(this.precision), 'Adding unequal precisions');
|
|
22
22
|
return BigNum.from(this.val.add(bn.val), this.precision);
|
|
23
23
|
}
|
|
24
24
|
sub(bn) {
|
|
25
|
-
assert_1.assert(bn.precision.eq(this.precision), 'Subtracting unequal precisions');
|
|
25
|
+
(0, assert_1.assert)(bn.precision.eq(this.precision), 'Subtracting unequal precisions');
|
|
26
26
|
return BigNum.from(this.val.sub(bn.val), this.precision);
|
|
27
27
|
}
|
|
28
28
|
mul(bn) {
|
|
@@ -82,35 +82,35 @@ class BigNum {
|
|
|
82
82
|
gt(bn, ignorePrecision) {
|
|
83
83
|
const comparisonVal = this.bigNumFromParam(bn);
|
|
84
84
|
if (!ignorePrecision && !comparisonVal.eq(numericConstants_1.ZERO)) {
|
|
85
|
-
assert_1.assert(comparisonVal.precision.eq(this.precision), 'Trying to compare numbers with different precision. Yo can opt to ignore precision using the ignorePrecision parameter');
|
|
85
|
+
(0, assert_1.assert)(comparisonVal.precision.eq(this.precision), 'Trying to compare numbers with different precision. Yo can opt to ignore precision using the ignorePrecision parameter');
|
|
86
86
|
}
|
|
87
87
|
return this.val.gt(comparisonVal.val);
|
|
88
88
|
}
|
|
89
89
|
lt(bn, ignorePrecision) {
|
|
90
90
|
const comparisonVal = this.bigNumFromParam(bn);
|
|
91
91
|
if (!ignorePrecision && !comparisonVal.val.eq(numericConstants_1.ZERO)) {
|
|
92
|
-
assert_1.assert(comparisonVal.precision.eq(this.precision), 'Trying to compare numbers with different precision. Yo can opt to ignore precision using the ignorePrecision parameter');
|
|
92
|
+
(0, assert_1.assert)(comparisonVal.precision.eq(this.precision), 'Trying to compare numbers with different precision. Yo can opt to ignore precision using the ignorePrecision parameter');
|
|
93
93
|
}
|
|
94
94
|
return this.val.lt(comparisonVal.val);
|
|
95
95
|
}
|
|
96
96
|
gte(bn, ignorePrecision) {
|
|
97
97
|
const comparisonVal = this.bigNumFromParam(bn);
|
|
98
98
|
if (!ignorePrecision && !comparisonVal.val.eq(numericConstants_1.ZERO)) {
|
|
99
|
-
assert_1.assert(comparisonVal.precision.eq(this.precision), 'Trying to compare numbers with different precision. Yo can opt to ignore precision using the ignorePrecision parameter');
|
|
99
|
+
(0, assert_1.assert)(comparisonVal.precision.eq(this.precision), 'Trying to compare numbers with different precision. Yo can opt to ignore precision using the ignorePrecision parameter');
|
|
100
100
|
}
|
|
101
101
|
return this.val.gte(comparisonVal.val);
|
|
102
102
|
}
|
|
103
103
|
lte(bn, ignorePrecision) {
|
|
104
104
|
const comparisonVal = this.bigNumFromParam(bn);
|
|
105
105
|
if (!ignorePrecision && !comparisonVal.val.eq(numericConstants_1.ZERO)) {
|
|
106
|
-
assert_1.assert(comparisonVal.precision.eq(this.precision), 'Trying to compare numbers with different precision. Yo can opt to ignore precision using the ignorePrecision parameter');
|
|
106
|
+
(0, assert_1.assert)(comparisonVal.precision.eq(this.precision), 'Trying to compare numbers with different precision. Yo can opt to ignore precision using the ignorePrecision parameter');
|
|
107
107
|
}
|
|
108
108
|
return this.val.lte(comparisonVal.val);
|
|
109
109
|
}
|
|
110
110
|
eq(bn, ignorePrecision) {
|
|
111
111
|
const comparisonVal = this.bigNumFromParam(bn);
|
|
112
112
|
if (!ignorePrecision && !comparisonVal.val.eq(numericConstants_1.ZERO)) {
|
|
113
|
-
assert_1.assert(comparisonVal.precision.eq(this.precision), 'Trying to compare numbers with different precision. Yo can opt to ignore precision using the ignorePrecision parameter');
|
|
113
|
+
(0, assert_1.assert)(comparisonVal.precision.eq(this.precision), 'Trying to compare numbers with different precision. Yo can opt to ignore precision using the ignorePrecision parameter');
|
|
114
114
|
}
|
|
115
115
|
return this.val.eq(comparisonVal.val);
|
|
116
116
|
}
|
|
@@ -140,7 +140,7 @@ class BigNum {
|
|
|
140
140
|
* @returns
|
|
141
141
|
*/
|
|
142
142
|
print() {
|
|
143
|
-
assert_1.assert(this.precision.gte(numericConstants_1.ZERO), 'Tried to print a BN with precision lower than zero');
|
|
143
|
+
(0, assert_1.assert)(this.precision.gte(numericConstants_1.ZERO), 'Tried to print a BN with precision lower than zero');
|
|
144
144
|
const isNeg = this.isNeg();
|
|
145
145
|
const plainString = this.abs().toString();
|
|
146
146
|
const precisionNum = this.precision.toNumber();
|
|
@@ -409,7 +409,7 @@ class BigNum {
|
|
|
409
409
|
* @returns
|
|
410
410
|
*/
|
|
411
411
|
static from(val = numericConstants_1.ZERO, precision) {
|
|
412
|
-
assert_1.assert(new anchor_1.BN(precision).lt(new anchor_1.BN(100)), 'Tried to create a bignum with precision higher than 10^100');
|
|
412
|
+
(0, assert_1.assert)(new anchor_1.BN(precision).lt(new anchor_1.BN(100)), 'Tried to create a bignum with precision higher than 10^100');
|
|
413
413
|
return new BigNum(val, precision);
|
|
414
414
|
}
|
|
415
415
|
/**
|
|
@@ -7,19 +7,19 @@ const pythClient_1 = require("../oracles/pythClient");
|
|
|
7
7
|
const quoteAssetOracleClient_1 = require("../oracles/quoteAssetOracleClient");
|
|
8
8
|
const anchor_1 = require("@project-serum/anchor");
|
|
9
9
|
function getOracleClient(oracleSource, connection) {
|
|
10
|
-
if (types_1.isVariant(oracleSource, 'pyth')) {
|
|
10
|
+
if ((0, types_1.isVariant)(oracleSource, 'pyth')) {
|
|
11
11
|
return new pythClient_1.PythClient(connection);
|
|
12
12
|
}
|
|
13
|
-
if (types_1.isVariant(oracleSource, 'pyth1K')) {
|
|
13
|
+
if ((0, types_1.isVariant)(oracleSource, 'pyth1K')) {
|
|
14
14
|
return new pythClient_1.PythClient(connection, new anchor_1.BN(1000));
|
|
15
15
|
}
|
|
16
|
-
if (types_1.isVariant(oracleSource, 'pyth1M')) {
|
|
16
|
+
if ((0, types_1.isVariant)(oracleSource, 'pyth1M')) {
|
|
17
17
|
return new pythClient_1.PythClient(connection, new anchor_1.BN(1000000));
|
|
18
18
|
}
|
|
19
19
|
// if (isVariant(oracleSource, 'switchboard')) {
|
|
20
20
|
// return new SwitchboardClient(connection);
|
|
21
21
|
// }
|
|
22
|
-
if (types_1.isVariant(oracleSource, 'quoteAsset')) {
|
|
22
|
+
if ((0, types_1.isVariant)(oracleSource, 'quoteAsset')) {
|
|
23
23
|
return new quoteAssetOracleClient_1.QuoteAssetOracleClient();
|
|
24
24
|
}
|
|
25
25
|
throw new Error(`Unknown oracle source ${oracleSource}`);
|
package/lib/idl/drift.json
CHANGED
package/lib/index.js
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
3
|
if (k2 === undefined) k2 = k;
|
|
4
|
-
Object.
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
5
9
|
}) : (function(o, m, k, k2) {
|
|
6
10
|
if (k2 === undefined) k2 = k;
|
|
7
11
|
o[k2] = m[k];
|
package/lib/math/amm.d.ts
CHANGED
|
@@ -22,7 +22,7 @@ export declare function calculateBidAskPrice(amm: AMM, oraclePriceData: OraclePr
|
|
|
22
22
|
* @returns price : Precision PRICE_PRECISION
|
|
23
23
|
*/
|
|
24
24
|
export declare function calculatePrice(baseAssetReserves: BN, quoteAssetReserves: BN, pegMultiplier: BN): BN;
|
|
25
|
-
export
|
|
25
|
+
export type AssetType = 'quote' | 'base';
|
|
26
26
|
/**
|
|
27
27
|
* Calculates what the amm reserves would be after swapping a quote or base asset amount.
|
|
28
28
|
*
|
package/lib/math/amm.js
CHANGED
|
@@ -20,7 +20,7 @@ function calculateOptimalPegAndBudget(amm, oraclePriceData) {
|
|
|
20
20
|
const reservePriceBefore = calculatePrice(amm.baseAssetReserve, amm.quoteAssetReserve, amm.pegMultiplier);
|
|
21
21
|
const targetPrice = oraclePriceData.price;
|
|
22
22
|
const newPeg = calculatePegFromTargetPrice(targetPrice, amm.baseAssetReserve, amm.quoteAssetReserve);
|
|
23
|
-
const prePegCost = repeg_1.calculateRepegCost(amm, newPeg);
|
|
23
|
+
const prePegCost = (0, repeg_1.calculateRepegCost)(amm, newPeg);
|
|
24
24
|
const totalFeeLB = amm.totalExchangeFee.div(new anchor_1.BN(2));
|
|
25
25
|
const budget = anchor_1.BN.max(numericConstants_1.ZERO, amm.totalFeeMinusDistributions.sub(totalFeeLB));
|
|
26
26
|
let checkLowerBound = true;
|
|
@@ -42,7 +42,7 @@ function calculateOptimalPegAndBudget(amm, oraclePriceData) {
|
|
|
42
42
|
newTargetPrice = reservePriceBefore.sub(markAdj);
|
|
43
43
|
}
|
|
44
44
|
newOptimalPeg = calculatePegFromTargetPrice(newTargetPrice, amm.baseAssetReserve, amm.quoteAssetReserve);
|
|
45
|
-
newBudget = repeg_1.calculateRepegCost(amm, newOptimalPeg);
|
|
45
|
+
newBudget = (0, repeg_1.calculateRepegCost)(amm, newOptimalPeg);
|
|
46
46
|
checkLowerBound = false;
|
|
47
47
|
return [newTargetPrice, newOptimalPeg, newBudget, false];
|
|
48
48
|
}
|
|
@@ -57,12 +57,12 @@ function calculateNewAmm(amm, oraclePriceData) {
|
|
|
57
57
|
let pKNumer = new anchor_1.BN(1);
|
|
58
58
|
let pKDenom = new anchor_1.BN(1);
|
|
59
59
|
const [targetPrice, _newPeg, budget, _checkLowerBound] = calculateOptimalPegAndBudget(amm, oraclePriceData);
|
|
60
|
-
let prePegCost = repeg_1.calculateRepegCost(amm, _newPeg);
|
|
60
|
+
let prePegCost = (0, repeg_1.calculateRepegCost)(amm, _newPeg);
|
|
61
61
|
let newPeg = _newPeg;
|
|
62
62
|
if (prePegCost.gte(budget) && prePegCost.gt(numericConstants_1.ZERO)) {
|
|
63
63
|
[pKNumer, pKDenom] = [new anchor_1.BN(999), new anchor_1.BN(1000)];
|
|
64
|
-
const deficitMadeup = repeg_1.calculateAdjustKCost(amm, pKNumer, pKDenom);
|
|
65
|
-
assert_1.assert(deficitMadeup.lte(new anchor_1.BN(0)));
|
|
64
|
+
const deficitMadeup = (0, repeg_1.calculateAdjustKCost)(amm, pKNumer, pKDenom);
|
|
65
|
+
(0, assert_1.assert)(deficitMadeup.lte(new anchor_1.BN(0)));
|
|
66
66
|
prePegCost = budget.add(deficitMadeup.abs());
|
|
67
67
|
const newAmm = Object.assign({}, amm);
|
|
68
68
|
newAmm.baseAssetReserve = newAmm.baseAssetReserve.mul(pKNumer).div(pKDenom);
|
|
@@ -74,8 +74,8 @@ function calculateNewAmm(amm, oraclePriceData) {
|
|
|
74
74
|
: types_1.PositionDirection.LONG;
|
|
75
75
|
const [newQuoteAssetReserve, _newBaseAssetReserve] = calculateAmmReservesAfterSwap(newAmm, 'base', amm.baseAssetAmountWithAmm.abs(), getSwapDirection('base', directionToClose));
|
|
76
76
|
newAmm.terminalQuoteAssetReserve = newQuoteAssetReserve;
|
|
77
|
-
newPeg = repeg_1.calculateBudgetedPeg(newAmm, prePegCost, targetPrice);
|
|
78
|
-
prePegCost = repeg_1.calculateRepegCost(newAmm, newPeg);
|
|
77
|
+
newPeg = (0, repeg_1.calculateBudgetedPeg)(newAmm, prePegCost, targetPrice);
|
|
78
|
+
prePegCost = (0, repeg_1.calculateRepegCost)(newAmm, newPeg);
|
|
79
79
|
}
|
|
80
80
|
return [prePegCost, pKNumer, pKDenom, newPeg];
|
|
81
81
|
}
|
|
@@ -106,7 +106,7 @@ exports.calculateUpdatedAMM = calculateUpdatedAMM;
|
|
|
106
106
|
function calculateUpdatedAMMSpreadReserves(amm, direction, oraclePriceData) {
|
|
107
107
|
const newAmm = calculateUpdatedAMM(amm, oraclePriceData);
|
|
108
108
|
const [shortReserves, longReserves] = calculateSpreadReserves(newAmm, oraclePriceData);
|
|
109
|
-
const dirReserves = types_1.isVariant(direction, 'long')
|
|
109
|
+
const dirReserves = (0, types_1.isVariant)(direction, 'long')
|
|
110
110
|
? longReserves
|
|
111
111
|
: shortReserves;
|
|
112
112
|
const result = {
|
|
@@ -161,7 +161,7 @@ exports.calculatePrice = calculatePrice;
|
|
|
161
161
|
* @returns quoteAssetReserve and baseAssetReserve after swap. : Precision AMM_RESERVE_PRECISION
|
|
162
162
|
*/
|
|
163
163
|
function calculateAmmReservesAfterSwap(amm, inputAssetType, swapAmount, swapDirection) {
|
|
164
|
-
assert_1.assert(swapAmount.gte(numericConstants_1.ZERO), 'swapAmount must be greater than 0');
|
|
164
|
+
(0, assert_1.assert)(swapAmount.gte(numericConstants_1.ZERO), 'swapAmount must be greater than 0');
|
|
165
165
|
let newQuoteAssetReserve;
|
|
166
166
|
let newBaseAssetReserve;
|
|
167
167
|
if (inputAssetType === 'quote') {
|
|
@@ -251,16 +251,16 @@ function calculateVolSpreadBN(lastOracleConfPct, reservePrice, markStd, oracleSt
|
|
|
251
251
|
const volSpread = anchor_1.BN.max(lastOracleConfPct, marketAvgStdPct.div(new anchor_1.BN(2)));
|
|
252
252
|
const clampMin = numericConstants_1.PERCENTAGE_PRECISION.div(new anchor_1.BN(100));
|
|
253
253
|
const clampMax = numericConstants_1.PERCENTAGE_PRECISION.mul(new anchor_1.BN(16)).div(new anchor_1.BN(10));
|
|
254
|
-
const longVolSpreadFactor = __1.clampBN(longIntensity.mul(numericConstants_1.PERCENTAGE_PRECISION).div(anchor_1.BN.max(numericConstants_1.ONE, volume24H)), clampMin, clampMax);
|
|
255
|
-
const shortVolSpreadFactor = __1.clampBN(shortIntensity.mul(numericConstants_1.PERCENTAGE_PRECISION).div(anchor_1.BN.max(numericConstants_1.ONE, volume24H)), clampMin, clampMax);
|
|
254
|
+
const longVolSpreadFactor = (0, __1.clampBN)(longIntensity.mul(numericConstants_1.PERCENTAGE_PRECISION).div(anchor_1.BN.max(numericConstants_1.ONE, volume24H)), clampMin, clampMax);
|
|
255
|
+
const shortVolSpreadFactor = (0, __1.clampBN)(shortIntensity.mul(numericConstants_1.PERCENTAGE_PRECISION).div(anchor_1.BN.max(numericConstants_1.ONE, volume24H)), clampMin, clampMax);
|
|
256
256
|
const longVolSpread = anchor_1.BN.max(lastOracleConfPct, volSpread.mul(longVolSpreadFactor).div(numericConstants_1.PERCENTAGE_PRECISION));
|
|
257
257
|
const shortVolSpread = anchor_1.BN.max(lastOracleConfPct, volSpread.mul(shortVolSpreadFactor).div(numericConstants_1.PERCENTAGE_PRECISION));
|
|
258
258
|
return [longVolSpread, shortVolSpread];
|
|
259
259
|
}
|
|
260
260
|
exports.calculateVolSpreadBN = calculateVolSpreadBN;
|
|
261
261
|
function calculateSpreadBN(baseSpread, lastOracleReservePriceSpreadPct, lastOracleConfPct, maxSpread, quoteAssetReserve, terminalQuoteAssetReserve, pegMultiplier, baseAssetAmountWithAmm, reservePrice, totalFeeMinusDistributions, netRevenueSinceLastFunding, baseAssetReserve, minBaseAssetReserve, maxBaseAssetReserve, markStd, oracleStd, longIntensity, shortIntensity, volume24H, returnTerms = false) {
|
|
262
|
-
assert_1.assert(Number.isInteger(baseSpread));
|
|
263
|
-
assert_1.assert(Number.isInteger(maxSpread));
|
|
262
|
+
(0, assert_1.assert)(Number.isInteger(baseSpread));
|
|
263
|
+
(0, assert_1.assert)(Number.isInteger(maxSpread));
|
|
264
264
|
const spreadTerms = {
|
|
265
265
|
longVolSpread: 0,
|
|
266
266
|
shortVolSpread: 0,
|
|
@@ -390,7 +390,7 @@ function calculateSpread(amm, oraclePriceData, now) {
|
|
|
390
390
|
.mul(numericConstants_1.BID_ASK_SPREAD_PRECISION)
|
|
391
391
|
.div(reservePrice);
|
|
392
392
|
now = now || new anchor_1.BN(new Date().getTime() / 1000); //todo
|
|
393
|
-
const liveOracleStd = oracles_1.calculateLiveOracleStd(amm, oraclePriceData, now);
|
|
393
|
+
const liveOracleStd = (0, oracles_1.calculateLiveOracleStd)(amm, oraclePriceData, now);
|
|
394
394
|
const spreads = calculateSpreadBN(amm.baseSpread, targetMarkSpreadPct, confIntervalPct, amm.maxSpread, amm.quoteAssetReserve, amm.terminalQuoteAssetReserve, amm.pegMultiplier, amm.baseAssetAmountWithAmm, reservePrice, amm.totalFeeMinusDistributions, amm.netRevenueSinceLastFunding, amm.baseAssetReserve, amm.minBaseAssetReserve, amm.maxBaseAssetReserve, amm.markStd, liveOracleStd, amm.longIntensityVolume, amm.shortIntensityVolume, amm.volume24H);
|
|
395
395
|
const longSpread = spreads[0];
|
|
396
396
|
const shortSpread = spreads[1];
|
|
@@ -407,7 +407,7 @@ function calculateSpreadReserves(amm, oraclePriceData, now) {
|
|
|
407
407
|
}
|
|
408
408
|
const quoteAssetReserveDelta = amm.quoteAssetReserve.div(numericConstants_1.BID_ASK_SPREAD_PRECISION.div(new anchor_1.BN(spread / 2)));
|
|
409
409
|
let quoteAssetReserve;
|
|
410
|
-
if (types_1.isVariant(direction, 'long')) {
|
|
410
|
+
if ((0, types_1.isVariant)(direction, 'long')) {
|
|
411
411
|
quoteAssetReserve = amm.quoteAssetReserve.add(quoteAssetReserveDelta);
|
|
412
412
|
}
|
|
413
413
|
else {
|
|
@@ -453,10 +453,10 @@ exports.calculateSwapOutput = calculateSwapOutput;
|
|
|
453
453
|
* @param positionDirection
|
|
454
454
|
*/
|
|
455
455
|
function getSwapDirection(inputAssetType, positionDirection) {
|
|
456
|
-
if (types_1.isVariant(positionDirection, 'long') && inputAssetType === 'base') {
|
|
456
|
+
if ((0, types_1.isVariant)(positionDirection, 'long') && inputAssetType === 'base') {
|
|
457
457
|
return types_1.SwapDirection.REMOVE;
|
|
458
458
|
}
|
|
459
|
-
if (types_1.isVariant(positionDirection, 'short') && inputAssetType === 'quote') {
|
|
459
|
+
if ((0, types_1.isVariant)(positionDirection, 'short') && inputAssetType === 'quote') {
|
|
460
460
|
return types_1.SwapDirection.REMOVE;
|
|
461
461
|
}
|
|
462
462
|
return types_1.SwapDirection.ADD;
|
|
@@ -488,9 +488,9 @@ function calculateMaxBaseAssetAmountToTrade(amm, limit_price, direction, oracleP
|
|
|
488
488
|
.mul(amm.pegMultiplier)
|
|
489
489
|
.div(limit_price)
|
|
490
490
|
.div(numericConstants_1.PEG_PRECISION);
|
|
491
|
-
const newBaseAssetReserve = __1.squareRootBN(newBaseAssetReserveSquared);
|
|
491
|
+
const newBaseAssetReserve = (0, __1.squareRootBN)(newBaseAssetReserveSquared);
|
|
492
492
|
const [shortSpreadReserves, longSpreadReserves] = calculateSpreadReserves(amm, oraclePriceData, now);
|
|
493
|
-
const baseAssetReserveBefore = types_1.isVariant(direction, 'long')
|
|
493
|
+
const baseAssetReserveBefore = (0, types_1.isVariant)(direction, 'long')
|
|
494
494
|
? longSpreadReserves.baseAssetReserve
|
|
495
495
|
: shortSpreadReserves.baseAssetReserve;
|
|
496
496
|
if (newBaseAssetReserve.gt(baseAssetReserveBefore)) {
|
|
@@ -512,13 +512,13 @@ function calculateMaxBaseAssetAmountToTrade(amm, limit_price, direction, oracleP
|
|
|
512
512
|
}
|
|
513
513
|
exports.calculateMaxBaseAssetAmountToTrade = calculateMaxBaseAssetAmountToTrade;
|
|
514
514
|
function calculateQuoteAssetAmountSwapped(quoteAssetReserves, pegMultiplier, swapDirection) {
|
|
515
|
-
if (types_1.isVariant(swapDirection, 'remove')) {
|
|
515
|
+
if ((0, types_1.isVariant)(swapDirection, 'remove')) {
|
|
516
516
|
quoteAssetReserves = quoteAssetReserves.add(numericConstants_1.ONE);
|
|
517
517
|
}
|
|
518
518
|
let quoteAssetAmount = quoteAssetReserves
|
|
519
519
|
.mul(pegMultiplier)
|
|
520
520
|
.div(numericConstants_1.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO);
|
|
521
|
-
if (types_1.isVariant(swapDirection, 'remove')) {
|
|
521
|
+
if ((0, types_1.isVariant)(swapDirection, 'remove')) {
|
|
522
522
|
quoteAssetAmount = quoteAssetAmount.add(numericConstants_1.ONE);
|
|
523
523
|
}
|
|
524
524
|
return quoteAssetAmount;
|
|
@@ -527,12 +527,12 @@ exports.calculateQuoteAssetAmountSwapped = calculateQuoteAssetAmountSwapped;
|
|
|
527
527
|
function calculateMaxBaseAssetAmountFillable(amm, orderDirection) {
|
|
528
528
|
const maxFillSize = amm.baseAssetReserve.div(new anchor_1.BN(amm.maxFillReserveFraction));
|
|
529
529
|
let maxBaseAssetAmountOnSide;
|
|
530
|
-
if (types_1.isVariant(orderDirection, 'long')) {
|
|
530
|
+
if ((0, types_1.isVariant)(orderDirection, 'long')) {
|
|
531
531
|
maxBaseAssetAmountOnSide = anchor_1.BN.max(numericConstants_1.ZERO, amm.baseAssetReserve.sub(amm.minBaseAssetReserve));
|
|
532
532
|
}
|
|
533
533
|
else {
|
|
534
534
|
maxBaseAssetAmountOnSide = anchor_1.BN.max(numericConstants_1.ZERO, amm.maxBaseAssetReserve.sub(amm.baseAssetReserve));
|
|
535
535
|
}
|
|
536
|
-
return __1.standardizeBaseAssetAmount(anchor_1.BN.min(maxFillSize, maxBaseAssetAmountOnSide), amm.orderStepSize);
|
|
536
|
+
return (0, __1.standardizeBaseAssetAmount)(anchor_1.BN.min(maxFillSize, maxBaseAssetAmountOnSide), amm.orderStepSize);
|
|
537
537
|
}
|
|
538
538
|
exports.calculateMaxBaseAssetAmountFillable = calculateMaxBaseAssetAmountFillable;
|
package/lib/math/auction.js
CHANGED
|
@@ -18,10 +18,10 @@ function isFallbackAvailableLiquiditySource(order, minAuctionDuration, slot) {
|
|
|
18
18
|
}
|
|
19
19
|
exports.isFallbackAvailableLiquiditySource = isFallbackAvailableLiquiditySource;
|
|
20
20
|
function getAuctionPrice(order, slot, oraclePrice) {
|
|
21
|
-
if (types_1.isOneOfVariant(order.orderType, ['market', 'triggerMarket', 'limit'])) {
|
|
21
|
+
if ((0, types_1.isOneOfVariant)(order.orderType, ['market', 'triggerMarket', 'limit'])) {
|
|
22
22
|
return getAuctionPriceForFixedAuction(order, slot);
|
|
23
23
|
}
|
|
24
|
-
else if (types_1.isVariant(order.orderType, 'oracle')) {
|
|
24
|
+
else if ((0, types_1.isVariant)(order.orderType, 'oracle')) {
|
|
25
25
|
return getAuctionPriceForOracleOffsetAuction(order, slot, oraclePrice);
|
|
26
26
|
}
|
|
27
27
|
else {
|
|
@@ -37,7 +37,7 @@ function getAuctionPriceForFixedAuction(order, slot) {
|
|
|
37
37
|
return order.auctionEndPrice;
|
|
38
38
|
}
|
|
39
39
|
let priceDelta;
|
|
40
|
-
if (types_1.isVariant(order.direction, 'long')) {
|
|
40
|
+
if ((0, types_1.isVariant)(order.direction, 'long')) {
|
|
41
41
|
priceDelta = order.auctionEndPrice
|
|
42
42
|
.sub(order.auctionStartPrice)
|
|
43
43
|
.mul(deltaNumerator)
|
|
@@ -50,7 +50,7 @@ function getAuctionPriceForFixedAuction(order, slot) {
|
|
|
50
50
|
.div(deltaDenominator);
|
|
51
51
|
}
|
|
52
52
|
let price;
|
|
53
|
-
if (types_1.isVariant(order.direction, 'long')) {
|
|
53
|
+
if ((0, types_1.isVariant)(order.direction, 'long')) {
|
|
54
54
|
price = order.auctionStartPrice.add(priceDelta);
|
|
55
55
|
}
|
|
56
56
|
else {
|
|
@@ -67,7 +67,7 @@ function getAuctionPriceForOracleOffsetAuction(order, slot, oraclePrice) {
|
|
|
67
67
|
return order.auctionEndPrice.add(order.auctionEndPrice);
|
|
68
68
|
}
|
|
69
69
|
let priceOffsetDelta;
|
|
70
|
-
if (types_1.isVariant(order.direction, 'long')) {
|
|
70
|
+
if ((0, types_1.isVariant)(order.direction, 'long')) {
|
|
71
71
|
priceOffsetDelta = order.auctionEndPrice
|
|
72
72
|
.sub(order.auctionStartPrice)
|
|
73
73
|
.mul(deltaNumerator)
|
|
@@ -80,7 +80,7 @@ function getAuctionPriceForOracleOffsetAuction(order, slot, oraclePrice) {
|
|
|
80
80
|
.div(deltaDenominator);
|
|
81
81
|
}
|
|
82
82
|
let priceOffset;
|
|
83
|
-
if (types_1.isVariant(order.direction, 'long')) {
|
|
83
|
+
if ((0, types_1.isVariant)(order.direction, 'long')) {
|
|
84
84
|
priceOffset = order.auctionStartPrice.add(priceOffsetDelta);
|
|
85
85
|
}
|
|
86
86
|
else {
|
|
@@ -9,12 +9,12 @@ exports.exchangePaused = exchangePaused;
|
|
|
9
9
|
function fillPaused(state, market) {
|
|
10
10
|
return ((state.exchangeStatus & types_1.ExchangeStatus.FILL_PAUSED) ===
|
|
11
11
|
types_1.ExchangeStatus.FILL_PAUSED ||
|
|
12
|
-
types_1.isOneOfVariant(market.status, ['paused', 'fillPaused']));
|
|
12
|
+
(0, types_1.isOneOfVariant)(market.status, ['paused', 'fillPaused']));
|
|
13
13
|
}
|
|
14
14
|
exports.fillPaused = fillPaused;
|
|
15
15
|
function ammPaused(state, market) {
|
|
16
16
|
return ((state.exchangeStatus & types_1.ExchangeStatus.AMM_PAUSED) ===
|
|
17
17
|
types_1.ExchangeStatus.AMM_PAUSED ||
|
|
18
|
-
types_1.isOneOfVariant(market.status, ['paused', 'ammPaused']));
|
|
18
|
+
(0, types_1.isOneOfVariant)(market.status, ['paused', 'ammPaused']));
|
|
19
19
|
}
|
|
20
20
|
exports.ammPaused = ammPaused;
|
package/lib/math/funding.js
CHANGED
|
@@ -20,7 +20,7 @@ async function calculateAllEstimatedFundingRate(market, oraclePriceData, periodA
|
|
|
20
20
|
const secondsInHour = new anchor_1.BN(3600);
|
|
21
21
|
const hoursInDay = new anchor_1.BN(24);
|
|
22
22
|
const ONE = new anchor_1.BN(1);
|
|
23
|
-
if (types_1.isVariant(market.status, 'uninitialized')) {
|
|
23
|
+
if ((0, types_1.isVariant)(market.status, 'uninitialized')) {
|
|
24
24
|
return [numericConstants_1.ZERO, numericConstants_1.ZERO, numericConstants_1.ZERO, numericConstants_1.ZERO, numericConstants_1.ZERO];
|
|
25
25
|
}
|
|
26
26
|
const payFreq = new anchor_1.BN(market.amm.fundingPeriod);
|
|
@@ -32,7 +32,7 @@ async function calculateAllEstimatedFundingRate(market, oraclePriceData, periodA
|
|
|
32
32
|
const lastMarkPriceTwapTs = market.amm.lastMarkPriceTwapTs;
|
|
33
33
|
const timeSinceLastMarkChange = now.sub(lastMarkPriceTwapTs);
|
|
34
34
|
const markTwapTimeSinceLastUpdate = anchor_1.BN.max(secondsInHour, anchor_1.BN.max(numericConstants_1.ZERO, secondsInHour.sub(timeSinceLastMarkChange)));
|
|
35
|
-
const [bid, ask] = amm_1.calculateBidAskPrice(market.amm, oraclePriceData);
|
|
35
|
+
const [bid, ask] = (0, amm_1.calculateBidAskPrice)(market.amm, oraclePriceData);
|
|
36
36
|
const baseAssetPriceWithMantissa = bid.add(ask).div(new anchor_1.BN(2));
|
|
37
37
|
const markTwapWithMantissa = markTwapTimeSinceLastUpdate
|
|
38
38
|
.mul(lastMarkTwapWithMantissa)
|
package/lib/math/margin.js
CHANGED
|
@@ -11,10 +11,10 @@ imfFactor, liabilityWeight, precision) {
|
|
|
11
11
|
if (imfFactor.eq(numericConstants_1.ZERO)) {
|
|
12
12
|
return liabilityWeight;
|
|
13
13
|
}
|
|
14
|
-
const sizeSqrt = utils_1.squareRootBN(size.abs().mul(new anchor_1.BN(10)).add(new anchor_1.BN(1))); //1e9 -> 1e10 -> 1e5
|
|
14
|
+
const sizeSqrt = (0, utils_1.squareRootBN)(size.abs().mul(new anchor_1.BN(10)).add(new anchor_1.BN(1))); //1e9 -> 1e10 -> 1e5
|
|
15
15
|
const liabilityWeightNumerator = liabilityWeight.sub(liabilityWeight.div(new anchor_1.BN(5)));
|
|
16
16
|
const denom = new anchor_1.BN(100000).mul(numericConstants_1.SPOT_MARKET_IMF_PRECISION).div(precision);
|
|
17
|
-
assert_1.assert(denom.gt(numericConstants_1.ZERO));
|
|
17
|
+
(0, assert_1.assert)(denom.gt(numericConstants_1.ZERO));
|
|
18
18
|
const sizePremiumLiabilityWeight = liabilityWeightNumerator.add(sizeSqrt // 1e5
|
|
19
19
|
.mul(imfFactor)
|
|
20
20
|
.div(denom) // 1e5
|
|
@@ -28,7 +28,7 @@ imfFactor, assetWeight) {
|
|
|
28
28
|
if (imfFactor.eq(numericConstants_1.ZERO)) {
|
|
29
29
|
return assetWeight;
|
|
30
30
|
}
|
|
31
|
-
const sizeSqrt = utils_1.squareRootBN(size.abs().mul(new anchor_1.BN(10)).add(new anchor_1.BN(1))); //1e9 -> 1e10 -> 1e5
|
|
31
|
+
const sizeSqrt = (0, utils_1.squareRootBN)(size.abs().mul(new anchor_1.BN(10)).add(new anchor_1.BN(1))); //1e9 -> 1e10 -> 1e5
|
|
32
32
|
const imfNumerator = numericConstants_1.SPOT_MARKET_IMF_PRECISION.add(numericConstants_1.SPOT_MARKET_IMF_PRECISION.div(new anchor_1.BN(10)));
|
|
33
33
|
const sizeDiscountAssetWeight = imfNumerator
|
|
34
34
|
.mul(numericConstants_1.SPOT_MARKET_WEIGHT_PRECISION)
|
|
@@ -58,7 +58,7 @@ function calculateOraclePriceForPerpMargin(perpPosition, market, oraclePriceData
|
|
|
58
58
|
exports.calculateOraclePriceForPerpMargin = calculateOraclePriceForPerpMargin;
|
|
59
59
|
function calculateBaseAssetValueWithOracle(market, perpPosition, oraclePriceData, includeOpenOrders = false) {
|
|
60
60
|
let price = oraclePriceData.price;
|
|
61
|
-
if (types_1.isVariant(market.status, 'settlement')) {
|
|
61
|
+
if ((0, types_1.isVariant)(market.status, 'settlement')) {
|
|
62
62
|
price = market.expiryPrice;
|
|
63
63
|
}
|
|
64
64
|
const baseAssetAmount = includeOpenOrders
|