@drift-labs/sdk 0.2.0-temp.1 → 2.0.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/README.md +27 -29
- package/lib/accounts/bulkAccountLoader.d.ts +2 -0
- package/lib/accounts/bulkAccountLoader.js +36 -29
- package/lib/accounts/bulkUserStatsSubscription.d.ts +7 -0
- package/lib/accounts/bulkUserStatsSubscription.js +21 -0
- package/lib/accounts/bulkUserSubscription.d.ts +2 -2
- package/lib/accounts/bulkUserSubscription.js +0 -1
- package/lib/accounts/fetch.d.ts +2 -1
- package/lib/accounts/fetch.js +9 -1
- package/lib/accounts/{pollingClearingHouseAccountSubscriber.d.ts → pollingDriftClientAccountSubscriber.d.ts} +20 -25
- package/lib/accounts/{pollingClearingHouseAccountSubscriber.js → pollingDriftClientAccountSubscriber.js} +45 -49
- package/lib/accounts/{pollingOracleSubscriber.d.ts → pollingOracleAccountSubscriber.d.ts} +2 -2
- package/lib/accounts/{pollingOracleSubscriber.js → pollingOracleAccountSubscriber.js} +3 -3
- package/lib/accounts/pollingUserAccountSubscriber.d.ts +1 -1
- package/lib/accounts/pollingUserAccountSubscriber.js +5 -11
- package/lib/accounts/pollingUserStatsAccountSubscriber.d.ts +27 -0
- package/lib/accounts/pollingUserStatsAccountSubscriber.js +107 -0
- package/lib/accounts/types.d.ts +26 -15
- package/lib/accounts/webSocketDriftClientAccountSubscriber.d.ts +49 -0
- package/lib/accounts/{webSocketClearingHouseAccountSubscriber.js → webSocketDriftClientAccountSubscriber.js} +47 -45
- package/lib/accounts/webSocketUserStatsAccountSubsriber.d.ts +20 -0
- package/lib/accounts/webSocketUserStatsAccountSubsriber.js +47 -0
- package/lib/addresses/marketAddresses.d.ts +1 -3
- package/lib/addresses/marketAddresses.js +1 -1
- package/lib/addresses/pda.d.ts +15 -9
- package/lib/addresses/pda.js +73 -35
- package/lib/adminClient.d.ts +65 -0
- package/lib/adminClient.js +637 -0
- package/lib/config.d.ts +10 -10
- package/lib/config.js +26 -22
- package/lib/constants/numericConstants.d.ts +29 -12
- package/lib/constants/numericConstants.js +40 -21
- package/lib/constants/perpMarkets.d.ts +18 -0
- package/lib/constants/{markets.js → perpMarkets.js} +20 -9
- package/lib/constants/spotMarkets.d.ts +19 -0
- package/lib/constants/spotMarkets.js +63 -0
- package/lib/dlob/DLOB.d.ts +82 -0
- package/lib/dlob/DLOB.js +694 -0
- package/lib/dlob/DLOBNode.d.ts +54 -0
- package/lib/dlob/DLOBNode.js +77 -0
- package/lib/dlob/NodeList.d.ts +27 -0
- package/lib/dlob/NodeList.js +144 -0
- package/lib/driftClient.d.ts +234 -0
- package/lib/driftClient.js +2108 -0
- package/lib/{clearingHouseConfig.d.ts → driftClientConfig.d.ts} +9 -9
- package/lib/{clearingHouseConfig.js → driftClientConfig.js} +0 -0
- package/lib/events/eventList.js +3 -0
- package/lib/events/eventSubscriber.d.ts +5 -2
- package/lib/events/eventSubscriber.js +25 -11
- package/lib/events/fetchLogs.d.ts +13 -2
- package/lib/events/fetchLogs.js +45 -14
- package/lib/events/pollingLogProvider.d.ts +2 -1
- package/lib/events/pollingLogProvider.js +7 -3
- package/lib/events/sort.js +8 -11
- package/lib/events/types.d.ts +11 -3
- package/lib/events/types.js +8 -0
- package/lib/events/webSocketLogProvider.js +1 -1
- package/lib/examples/makeTradeExample.js +30 -18
- package/lib/factory/bigNum.d.ts +8 -4
- package/lib/factory/bigNum.js +109 -19
- package/lib/idl/drift.json +8392 -0
- package/lib/index.d.ts +29 -12
- package/lib/index.js +29 -12
- package/lib/math/amm.d.ts +9 -6
- package/lib/math/amm.js +91 -38
- package/lib/math/conversion.js +1 -1
- package/lib/math/exchangeStatus.d.ts +4 -0
- package/lib/math/exchangeStatus.js +18 -0
- package/lib/math/funding.d.ts +6 -6
- package/lib/math/funding.js +23 -21
- package/lib/math/insurance.d.ts +4 -0
- package/lib/math/insurance.js +27 -0
- package/lib/math/margin.d.ts +11 -0
- package/lib/math/margin.js +82 -0
- package/lib/math/market.d.ts +14 -9
- package/lib/math/market.js +70 -10
- package/lib/math/oracles.d.ts +4 -0
- package/lib/math/oracles.js +36 -8
- package/lib/math/orders.d.ts +16 -6
- package/lib/math/orders.js +97 -17
- package/lib/math/position.d.ts +27 -13
- package/lib/math/position.js +91 -37
- package/lib/math/repeg.js +17 -8
- package/lib/math/spotBalance.d.ts +22 -0
- package/lib/math/spotBalance.js +192 -0
- package/lib/math/spotMarket.d.ts +4 -0
- package/lib/math/spotMarket.js +8 -0
- package/lib/math/spotPosition.d.ts +6 -0
- package/lib/math/spotPosition.js +23 -0
- package/lib/math/trade.d.ts +10 -10
- package/lib/math/trade.js +27 -31
- package/lib/oracles/pythClient.js +1 -1
- package/lib/oracles/quoteAssetOracleClient.js +1 -1
- package/lib/oracles/switchboardClient.js +1 -1
- package/lib/orderParams.d.ts +4 -4
- package/lib/orderParams.js +12 -4
- package/lib/serum/serumFulfillmentConfigMap.d.ts +10 -0
- package/lib/serum/serumFulfillmentConfigMap.js +17 -0
- package/lib/serum/serumSubscriber.d.ts +27 -0
- package/lib/serum/serumSubscriber.js +56 -0
- package/lib/serum/types.d.ts +11 -0
- package/{src/oracles → lib/serum}/types.js +0 -0
- package/lib/tokenFaucet.d.ts +1 -0
- package/lib/tokenFaucet.js +23 -12
- package/lib/tx/retryTxSender.d.ts +1 -1
- package/lib/tx/retryTxSender.js +13 -4
- package/lib/tx/types.d.ts +1 -1
- package/lib/types.d.ts +631 -222
- package/lib/types.js +137 -24
- package/lib/user.d.ts +228 -0
- package/lib/user.js +959 -0
- package/lib/userConfig.d.ts +14 -0
- package/lib/{clearingHouseUserConfig.js → userConfig.js} +0 -0
- package/lib/userMap/userMap.d.ts +41 -0
- package/lib/userMap/userMap.js +85 -0
- package/lib/userMap/userStatsMap.d.ts +19 -0
- package/lib/userMap/userStatsMap.js +68 -0
- package/lib/userName.d.ts +1 -0
- package/lib/userName.js +3 -2
- package/lib/userStats.d.ts +18 -0
- package/lib/userStats.js +49 -0
- package/lib/userStatsConfig.d.ts +14 -0
- package/{src/clearingHouseConfig.js → lib/userStatsConfig.js} +0 -0
- package/lib/util/getTokenAddress.d.ts +2 -0
- package/lib/util/getTokenAddress.js +9 -0
- package/package.json +12 -5
- package/src/accounts/bulkAccountLoader.ts +44 -34
- package/src/accounts/bulkUserStatsSubscription.ts +33 -0
- package/src/accounts/bulkUserSubscription.ts +2 -3
- package/src/accounts/fetch.ts +27 -2
- package/src/accounts/{pollingClearingHouseAccountSubscriber.ts → pollingDriftClientAccountSubscriber.ts} +65 -75
- package/src/accounts/{pollingOracleSubscriber.ts → pollingOracleAccountSubscriber.ts} +2 -2
- package/src/accounts/pollingUserAccountSubscriber.ts +5 -12
- package/src/accounts/pollingUserStatsAccountSubscriber.ts +166 -0
- package/src/accounts/types.ts +35 -15
- package/src/accounts/{webSocketClearingHouseAccountSubscriber.ts → webSocketDriftClientAccountSubscriber.ts} +78 -73
- package/src/accounts/webSocketUserStatsAccountSubsriber.ts +80 -0
- package/src/addresses/marketAddresses.ts +3 -4
- package/src/addresses/pda.ts +105 -33
- package/src/adminClient.ts +1207 -0
- package/src/config.ts +41 -34
- package/src/constants/numericConstants.ts +59 -26
- package/src/constants/{markets.ts → perpMarkets.ts} +22 -11
- package/src/constants/spotMarkets.ts +83 -0
- package/src/dlob/DLOB.ts +1120 -0
- package/src/dlob/DLOBNode.ts +155 -0
- package/src/dlob/NodeList.ts +195 -0
- package/src/driftClient.ts +3594 -0
- package/src/{clearingHouseConfig.ts → driftClientConfig.ts} +9 -8
- package/src/events/eventList.ts +3 -0
- package/src/events/eventSubscriber.ts +36 -14
- package/src/events/fetchLogs.ts +60 -15
- package/src/events/pollingLogProvider.ts +11 -3
- package/src/events/sort.ts +11 -15
- package/src/events/types.ts +27 -2
- package/src/events/webSocketLogProvider.ts +1 -1
- package/src/examples/makeTradeExample.js +152 -75
- package/src/examples/makeTradeExample.ts +44 -28
- package/src/factory/bigNum.ts +150 -22
- package/src/idl/drift.json +8392 -0
- package/src/idl/pyth.json +98 -2
- package/src/index.ts +29 -12
- package/src/math/amm.ts +161 -48
- package/src/math/conversion.ts +2 -2
- package/src/math/exchangeStatus.ts +31 -0
- package/src/math/funding.ts +41 -31
- package/src/math/insurance.ts +35 -0
- package/src/math/margin.ts +133 -0
- package/src/math/market.ts +143 -14
- package/src/math/oracles.ts +63 -9
- package/src/math/orders.ts +168 -26
- package/src/math/position.ts +133 -59
- package/src/math/repeg.ts +19 -9
- package/src/math/spotBalance.ts +319 -0
- package/src/math/spotMarket.ts +9 -0
- package/src/math/spotPosition.ts +47 -0
- package/src/math/trade.ts +33 -37
- package/src/oracles/pythClient.ts +2 -2
- package/src/oracles/quoteAssetOracleClient.ts +2 -2
- package/src/oracles/switchboardClient.ts +2 -2
- package/src/orderParams.ts +16 -8
- package/src/serum/serumFulfillmentConfigMap.ts +26 -0
- package/src/serum/serumSubscriber.ts +99 -0
- package/src/serum/types.ts +13 -0
- package/src/tokenFaucet.ts +38 -15
- package/src/tx/retryTxSender.ts +16 -5
- package/src/tx/types.ts +2 -1
- package/src/types.ts +594 -195
- package/src/user.ts +1599 -0
- package/src/{clearingHouseUserConfig.ts → userConfig.ts} +5 -5
- package/src/userMap/userMap.ts +124 -0
- package/src/userMap/userStatsMap.ts +108 -0
- package/src/userName.ts +2 -1
- package/src/userStats.ts +75 -0
- package/src/userStatsConfig.ts +18 -0
- package/src/util/getTokenAddress.ts +18 -0
- package/tests/bn/test.ts +46 -11
- package/tests/dlob/helpers.ts +619 -0
- package/tests/dlob/test.ts +4586 -0
- package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +0 -49
- package/lib/admin.d.ts +0 -44
- package/lib/admin.js +0 -438
- package/lib/clearingHouse.d.ts +0 -146
- package/lib/clearingHouse.js +0 -1154
- package/lib/clearingHouseUser.d.ts +0 -187
- package/lib/clearingHouseUser.js +0 -634
- package/lib/clearingHouseUserConfig.d.ts +0 -14
- package/lib/constants/banks.d.ts +0 -16
- package/lib/constants/banks.js +0 -41
- package/lib/constants/markets.d.ts +0 -19
- package/lib/idl/clearing_house.json +0 -4464
- package/lib/math/bankBalance.d.ts +0 -9
- package/lib/math/bankBalance.js +0 -75
- package/lib/math/state.d.ts +0 -8
- package/lib/math/state.js +0 -15
- package/lib/orders.d.ts +0 -8
- package/lib/orders.js +0 -134
- package/src/accounts/bulkAccountLoader.js +0 -197
- package/src/accounts/bulkUserSubscription.js +0 -33
- package/src/accounts/pollingClearingHouseAccountSubscriber.js +0 -311
- package/src/accounts/pollingOracleSubscriber.js +0 -93
- package/src/accounts/pollingTokenAccountSubscriber.js +0 -90
- package/src/accounts/pollingUserAccountSubscriber.js +0 -132
- package/src/accounts/types.js +0 -10
- package/src/accounts/utils.js +0 -7
- package/src/accounts/webSocketAccountSubscriber.js +0 -93
- package/src/accounts/webSocketClearingHouseAccountSubscriber.js +0 -233
- package/src/accounts/webSocketUserAccountSubscriber.js +0 -62
- package/src/addresses/marketAddresses.js +0 -26
- package/src/admin.js +0 -517
- package/src/admin.ts +0 -730
- package/src/clearingHouse.ts +0 -1828
- package/src/clearingHouseUser.ts +0 -978
- package/src/clearingHouseUserConfig.js +0 -2
- package/src/config.js +0 -67
- package/src/constants/banks.js +0 -42
- package/src/constants/banks.ts +0 -50
- package/src/constants/markets.js +0 -42
- package/src/constants/numericConstants.js +0 -41
- package/src/events/eventSubscriber.js +0 -139
- package/src/events/fetchLogs.js +0 -50
- package/src/events/pollingLogProvider.js +0 -64
- package/src/events/sort.js +0 -44
- package/src/events/txEventCache.js +0 -71
- package/src/events/types.js +0 -20
- package/src/events/webSocketLogProvider.js +0 -41
- package/src/factory/bigNum.js +0 -390
- package/src/factory/oracleClient.js +0 -20
- package/src/idl/clearing_house.json +0 -4464
- package/src/index.js +0 -69
- package/src/math/amm.js +0 -369
- package/src/math/auction.js +0 -42
- package/src/math/bankBalance.ts +0 -112
- package/src/math/conversion.js +0 -11
- package/src/math/funding.js +0 -248
- package/src/math/oracles.js +0 -26
- package/src/math/repeg.js +0 -128
- package/src/math/state.js +0 -15
- package/src/math/state.ts +0 -14
- package/src/math/trade.js +0 -253
- package/src/math/utils.js +0 -26
- package/src/math/utils.js.map +0 -1
- package/src/mockUSDCFaucet.js +0 -280
- package/src/oracles/oracleClientCache.js +0 -19
- package/src/oracles/pythClient.js +0 -46
- package/src/oracles/quoteAssetOracleClient.js +0 -32
- package/src/oracles/switchboardClient.js +0 -69
- package/src/orderParams.js +0 -20
- package/src/orders.ts +0 -245
- package/src/slot/SlotSubscriber.js +0 -39
- package/src/tokenFaucet.js +0 -189
- package/src/types.js +0 -125
- package/src/userName.js +0 -20
- package/src/wallet.js +0 -35
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
/// <reference types="bn.js" />
|
|
2
|
-
import { BankAccount, BankBalanceType } from '../types';
|
|
3
|
-
import { BN } from '@project-serum/anchor';
|
|
4
|
-
export declare function getBalance(tokenAmount: BN, bank: BankAccount, balanceType: BankBalanceType): BN;
|
|
5
|
-
export declare function getTokenAmount(balanceAmount: BN, bank: BankAccount, balanceType: BankBalanceType): BN;
|
|
6
|
-
export declare function calculateInterestAccumulated(bank: BankAccount, now: BN): {
|
|
7
|
-
borrowInterest: BN;
|
|
8
|
-
depositInterest: BN;
|
|
9
|
-
};
|
package/lib/math/bankBalance.js
DELETED
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.calculateInterestAccumulated = exports.getTokenAmount = exports.getBalance = void 0;
|
|
4
|
-
const types_1 = require("../types");
|
|
5
|
-
const anchor_1 = require("@project-serum/anchor");
|
|
6
|
-
const numericConstants_1 = require("../constants/numericConstants");
|
|
7
|
-
function getBalance(tokenAmount, bank, balanceType) {
|
|
8
|
-
const precisionIncrease = numericConstants_1.TEN.pow(new anchor_1.BN(16 - bank.decimals));
|
|
9
|
-
const cumulativeInterest = (0, types_1.isVariant)(balanceType, 'deposit')
|
|
10
|
-
? bank.cumulativeDepositInterest
|
|
11
|
-
: bank.cumulativeBorrowInterest;
|
|
12
|
-
let balance = tokenAmount.mul(precisionIncrease).div(cumulativeInterest);
|
|
13
|
-
if (!balance.eq(numericConstants_1.ZERO) && (0, types_1.isVariant)(balanceType, 'borrow')) {
|
|
14
|
-
balance = balance.add(numericConstants_1.ONE);
|
|
15
|
-
}
|
|
16
|
-
return balance;
|
|
17
|
-
}
|
|
18
|
-
exports.getBalance = getBalance;
|
|
19
|
-
function getTokenAmount(balanceAmount, bank, balanceType) {
|
|
20
|
-
const precisionDecrease = numericConstants_1.TEN.pow(new anchor_1.BN(16 - bank.decimals));
|
|
21
|
-
const cumulativeInterest = (0, types_1.isVariant)(balanceType, 'deposit')
|
|
22
|
-
? bank.cumulativeDepositInterest
|
|
23
|
-
: bank.cumulativeBorrowInterest;
|
|
24
|
-
return balanceAmount.mul(cumulativeInterest).div(precisionDecrease);
|
|
25
|
-
}
|
|
26
|
-
exports.getTokenAmount = getTokenAmount;
|
|
27
|
-
function calculateInterestAccumulated(bank, now) {
|
|
28
|
-
const token_deposit_amount = getTokenAmount(bank.depositBalance, bank, types_1.BankBalanceType.DEPOSIT);
|
|
29
|
-
const token_borrow_amount = getTokenAmount(bank.borrowBalance, bank, types_1.BankBalanceType.BORROW);
|
|
30
|
-
let utilization;
|
|
31
|
-
if (token_borrow_amount.eq(numericConstants_1.ZERO) && token_deposit_amount.eq(numericConstants_1.ZERO)) {
|
|
32
|
-
utilization = numericConstants_1.ZERO;
|
|
33
|
-
}
|
|
34
|
-
else if (token_deposit_amount.eq(numericConstants_1.ZERO)) {
|
|
35
|
-
utilization = numericConstants_1.BANK_UTILIZATION_PRECISION;
|
|
36
|
-
}
|
|
37
|
-
else {
|
|
38
|
-
utilization = token_borrow_amount
|
|
39
|
-
.mul(numericConstants_1.BANK_UTILIZATION_PRECISION)
|
|
40
|
-
.div(token_deposit_amount);
|
|
41
|
-
}
|
|
42
|
-
let interest_rate;
|
|
43
|
-
if (utilization.gt(bank.optimalUtilization)) {
|
|
44
|
-
const surplusUtilization = utilization.sub(bank.optimalUtilization);
|
|
45
|
-
const borrowRateSlope = bank.maxBorrowRate
|
|
46
|
-
.sub(bank.optimalBorrowRate)
|
|
47
|
-
.mul(numericConstants_1.BANK_UTILIZATION_PRECISION)
|
|
48
|
-
.div(numericConstants_1.BANK_UTILIZATION_PRECISION.sub(bank.optimalUtilization));
|
|
49
|
-
interest_rate = bank.optimalBorrowRate.add(surplusUtilization.mul(borrowRateSlope).div(numericConstants_1.BANK_UTILIZATION_PRECISION));
|
|
50
|
-
}
|
|
51
|
-
else {
|
|
52
|
-
const borrowRateSlope = bank.optimalBorrowRate
|
|
53
|
-
.mul(numericConstants_1.BANK_UTILIZATION_PRECISION)
|
|
54
|
-
.div(numericConstants_1.BANK_UTILIZATION_PRECISION.sub(bank.optimalUtilization));
|
|
55
|
-
interest_rate = utilization
|
|
56
|
-
.mul(borrowRateSlope)
|
|
57
|
-
.div(numericConstants_1.BANK_UTILIZATION_PRECISION);
|
|
58
|
-
}
|
|
59
|
-
const timeSinceLastUpdate = now.sub(bank.lastUpdated);
|
|
60
|
-
const modifiedBorrowRate = interest_rate.mul(timeSinceLastUpdate);
|
|
61
|
-
const modifiedDepositRate = modifiedBorrowRate
|
|
62
|
-
.mul(utilization)
|
|
63
|
-
.div(numericConstants_1.BANK_UTILIZATION_PRECISION);
|
|
64
|
-
const borrowInterest = bank.cumulativeBorrowInterest
|
|
65
|
-
.mul(modifiedBorrowRate)
|
|
66
|
-
.div(numericConstants_1.ONE_YEAR)
|
|
67
|
-
.div(numericConstants_1.BANK_INTEREST_PRECISION)
|
|
68
|
-
.add(numericConstants_1.ONE);
|
|
69
|
-
const depositInterest = bank.cumulativeDepositInterest
|
|
70
|
-
.mul(modifiedDepositRate)
|
|
71
|
-
.div(numericConstants_1.ONE_YEAR)
|
|
72
|
-
.div(numericConstants_1.BANK_INTEREST_PRECISION);
|
|
73
|
-
return { borrowInterest, depositInterest };
|
|
74
|
-
}
|
|
75
|
-
exports.calculateInterestAccumulated = calculateInterestAccumulated;
|
package/lib/math/state.d.ts
DELETED
package/lib/math/state.js
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.getExchangeFee = void 0;
|
|
4
|
-
/**
|
|
5
|
-
* Get the clearing house percent fee charged on notional of taking trades
|
|
6
|
-
*
|
|
7
|
-
* @param state
|
|
8
|
-
* @returns Precision : basis points (bps)
|
|
9
|
-
*/
|
|
10
|
-
function getExchangeFee(state) {
|
|
11
|
-
const exchangeFee = state.feeStructure.feeNumerator.toNumber() /
|
|
12
|
-
state.feeStructure.feeDenominator.toNumber();
|
|
13
|
-
return exchangeFee;
|
|
14
|
-
}
|
|
15
|
-
exports.getExchangeFee = getExchangeFee;
|
package/lib/orders.d.ts
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
/// <reference types="bn.js" />
|
|
2
|
-
import { MarketAccount, Order, UserAccount, UserPosition } from './types';
|
|
3
|
-
import { BN } from '.';
|
|
4
|
-
import { OraclePriceData } from '.';
|
|
5
|
-
export declare function calculateNewStateAfterOrder(userAccount: UserAccount, userPosition: UserPosition, market: MarketAccount, order: Order): [UserAccount, UserPosition, MarketAccount] | null;
|
|
6
|
-
export declare function calculateBaseAssetAmountMarketCanExecute(market: MarketAccount, order: Order, oraclePriceData?: OraclePriceData): BN;
|
|
7
|
-
export declare function calculateAmountToTradeForLimit(market: MarketAccount, order: Order, oraclePriceData?: OraclePriceData): BN;
|
|
8
|
-
export declare function calculateAmountToTradeForTriggerLimit(market: MarketAccount, order: Order): BN;
|
package/lib/orders.js
DELETED
|
@@ -1,134 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.calculateAmountToTradeForTriggerLimit = exports.calculateAmountToTradeForLimit = exports.calculateBaseAssetAmountMarketCanExecute = exports.calculateNewStateAfterOrder = void 0;
|
|
4
|
-
const types_1 = require("./types");
|
|
5
|
-
const _1 = require(".");
|
|
6
|
-
const market_1 = require("./math/market");
|
|
7
|
-
const numericConstants_1 = require("./constants/numericConstants");
|
|
8
|
-
const amm_1 = require("./math/amm");
|
|
9
|
-
const position_1 = require("./math/position");
|
|
10
|
-
function calculateNewStateAfterOrder(userAccount, userPosition, market, order) {
|
|
11
|
-
if ((0, types_1.isVariant)(order.status, 'init')) {
|
|
12
|
-
return null;
|
|
13
|
-
}
|
|
14
|
-
const baseAssetAmountToTrade = calculateBaseAssetAmountMarketCanExecute(market, order);
|
|
15
|
-
if (baseAssetAmountToTrade.lt(market.amm.baseAssetAmountStepSize)) {
|
|
16
|
-
return null;
|
|
17
|
-
}
|
|
18
|
-
const userAccountAfter = Object.assign({}, userAccount);
|
|
19
|
-
const userPositionAfter = Object.assign({}, userPosition);
|
|
20
|
-
const currentPositionDirection = (0, position_1.positionCurrentDirection)(userPosition);
|
|
21
|
-
const increasePosition = userPosition.baseAssetAmount.eq(numericConstants_1.ZERO) ||
|
|
22
|
-
isSameDirection(order.direction, currentPositionDirection);
|
|
23
|
-
if (increasePosition) {
|
|
24
|
-
const marketAfter = (0, market_1.calculateNewMarketAfterTrade)(baseAssetAmountToTrade, order.direction, market);
|
|
25
|
-
const { quoteAssetAmountSwapped, baseAssetAmountSwapped } = calculateAmountSwapped(market, marketAfter);
|
|
26
|
-
userPositionAfter.baseAssetAmount = userPositionAfter.baseAssetAmount.add(baseAssetAmountSwapped);
|
|
27
|
-
userPositionAfter.quoteAssetAmount = userPositionAfter.quoteAssetAmount.add(quoteAssetAmountSwapped);
|
|
28
|
-
return [userAccountAfter, userPositionAfter, marketAfter];
|
|
29
|
-
}
|
|
30
|
-
else {
|
|
31
|
-
const reversePosition = baseAssetAmountToTrade.gt(userPosition.baseAssetAmount.abs());
|
|
32
|
-
if (reversePosition) {
|
|
33
|
-
const intermediateMarket = (0, market_1.calculateNewMarketAfterTrade)(userPosition.baseAssetAmount, (0, position_1.findDirectionToClose)(userPosition), market);
|
|
34
|
-
const { quoteAssetAmountSwapped: baseAssetValue } = calculateAmountSwapped(market, intermediateMarket);
|
|
35
|
-
let pnl;
|
|
36
|
-
if ((0, types_1.isVariant)(currentPositionDirection, 'long')) {
|
|
37
|
-
pnl = baseAssetValue.sub(userPosition.quoteAssetAmount);
|
|
38
|
-
}
|
|
39
|
-
else {
|
|
40
|
-
pnl = userPosition.quoteAssetAmount.sub(baseAssetValue);
|
|
41
|
-
}
|
|
42
|
-
userAccountAfter.collateral = userAccountAfter.collateral.add(pnl);
|
|
43
|
-
const baseAssetAmountLeft = baseAssetAmountToTrade.sub(userPosition.baseAssetAmount.abs());
|
|
44
|
-
const marketAfter = (0, market_1.calculateNewMarketAfterTrade)(baseAssetAmountLeft, order.direction, intermediateMarket);
|
|
45
|
-
const { quoteAssetAmountSwapped, baseAssetAmountSwapped } = calculateAmountSwapped(intermediateMarket, marketAfter);
|
|
46
|
-
userPositionAfter.quoteAssetAmount = quoteAssetAmountSwapped;
|
|
47
|
-
userPositionAfter.baseAssetAmount = baseAssetAmountSwapped;
|
|
48
|
-
return [userAccountAfter, userPositionAfter, marketAfter];
|
|
49
|
-
}
|
|
50
|
-
else {
|
|
51
|
-
const marketAfter = (0, market_1.calculateNewMarketAfterTrade)(baseAssetAmountToTrade, order.direction, market);
|
|
52
|
-
const { quoteAssetAmountSwapped: baseAssetValue, baseAssetAmountSwapped, } = calculateAmountSwapped(market, marketAfter);
|
|
53
|
-
const costBasisRealized = userPosition.quoteAssetAmount
|
|
54
|
-
.mul(baseAssetAmountSwapped.abs())
|
|
55
|
-
.div(userPosition.baseAssetAmount.abs());
|
|
56
|
-
let pnl;
|
|
57
|
-
if ((0, types_1.isVariant)(currentPositionDirection, 'long')) {
|
|
58
|
-
pnl = baseAssetValue.sub(costBasisRealized);
|
|
59
|
-
}
|
|
60
|
-
else {
|
|
61
|
-
pnl = costBasisRealized.sub(baseAssetValue);
|
|
62
|
-
}
|
|
63
|
-
userAccountAfter.collateral = userAccountAfter.collateral.add(pnl);
|
|
64
|
-
userPositionAfter.baseAssetAmount = userPositionAfter.baseAssetAmount.add(baseAssetAmountSwapped);
|
|
65
|
-
userPositionAfter.quoteAssetAmount =
|
|
66
|
-
userPositionAfter.quoteAssetAmount.sub(costBasisRealized);
|
|
67
|
-
return [userAccountAfter, userPositionAfter, marketAfter];
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
exports.calculateNewStateAfterOrder = calculateNewStateAfterOrder;
|
|
72
|
-
function calculateAmountSwapped(marketBefore, marketAfter) {
|
|
73
|
-
return {
|
|
74
|
-
quoteAssetAmountSwapped: marketBefore.amm.quoteAssetReserve
|
|
75
|
-
.sub(marketAfter.amm.quoteAssetReserve)
|
|
76
|
-
.abs()
|
|
77
|
-
.mul(marketBefore.amm.pegMultiplier)
|
|
78
|
-
.div(numericConstants_1.PEG_PRECISION)
|
|
79
|
-
.div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO),
|
|
80
|
-
baseAssetAmountSwapped: marketBefore.amm.baseAssetReserve.sub(marketAfter.amm.baseAssetReserve),
|
|
81
|
-
};
|
|
82
|
-
}
|
|
83
|
-
function calculateBaseAssetAmountMarketCanExecute(market, order, oraclePriceData) {
|
|
84
|
-
if ((0, types_1.isVariant)(order.orderType, 'limit')) {
|
|
85
|
-
return calculateAmountToTradeForLimit(market, order, oraclePriceData);
|
|
86
|
-
}
|
|
87
|
-
else if ((0, types_1.isVariant)(order.orderType, 'triggerLimit')) {
|
|
88
|
-
return calculateAmountToTradeForTriggerLimit(market, order);
|
|
89
|
-
}
|
|
90
|
-
else if ((0, types_1.isVariant)(order.orderType, 'market')) {
|
|
91
|
-
return numericConstants_1.ZERO;
|
|
92
|
-
}
|
|
93
|
-
else {
|
|
94
|
-
return calculateAmountToTradeForTriggerMarket(market, order);
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
exports.calculateBaseAssetAmountMarketCanExecute = calculateBaseAssetAmountMarketCanExecute;
|
|
98
|
-
function calculateAmountToTradeForLimit(market, order, oraclePriceData) {
|
|
99
|
-
let limitPrice = order.price;
|
|
100
|
-
if (!order.oraclePriceOffset.eq(numericConstants_1.ZERO)) {
|
|
101
|
-
if (!oraclePriceData) {
|
|
102
|
-
throw Error('Cant calculate limit price for oracle offset oracle without OraclePriceData');
|
|
103
|
-
}
|
|
104
|
-
limitPrice = oraclePriceData.price.add(order.oraclePriceOffset);
|
|
105
|
-
}
|
|
106
|
-
const [maxAmountToTrade, direction] = (0, amm_1.calculateMaxBaseAssetAmountToTrade)(market.amm, limitPrice, order.direction, oraclePriceData);
|
|
107
|
-
const baseAssetAmount = (0, _1.standardizeBaseAssetAmount)(maxAmountToTrade, market.amm.baseAssetAmountStepSize);
|
|
108
|
-
// Check that directions are the same
|
|
109
|
-
const sameDirection = isSameDirection(direction, order.direction);
|
|
110
|
-
if (!sameDirection) {
|
|
111
|
-
return numericConstants_1.ZERO;
|
|
112
|
-
}
|
|
113
|
-
return baseAssetAmount.gt(order.baseAssetAmount)
|
|
114
|
-
? order.baseAssetAmount
|
|
115
|
-
: baseAssetAmount;
|
|
116
|
-
}
|
|
117
|
-
exports.calculateAmountToTradeForLimit = calculateAmountToTradeForLimit;
|
|
118
|
-
function calculateAmountToTradeForTriggerLimit(market, order) {
|
|
119
|
-
if (!order.triggered) {
|
|
120
|
-
return numericConstants_1.ZERO;
|
|
121
|
-
}
|
|
122
|
-
return calculateAmountToTradeForLimit(market, order);
|
|
123
|
-
}
|
|
124
|
-
exports.calculateAmountToTradeForTriggerLimit = calculateAmountToTradeForTriggerLimit;
|
|
125
|
-
function isSameDirection(firstDirection, secondDirection) {
|
|
126
|
-
return (((0, types_1.isVariant)(firstDirection, 'long') && (0, types_1.isVariant)(secondDirection, 'long')) ||
|
|
127
|
-
((0, types_1.isVariant)(firstDirection, 'short') && (0, types_1.isVariant)(secondDirection, 'short')));
|
|
128
|
-
}
|
|
129
|
-
function calculateAmountToTradeForTriggerMarket(market, order) {
|
|
130
|
-
if (!order.triggered) {
|
|
131
|
-
return numericConstants_1.ZERO;
|
|
132
|
-
}
|
|
133
|
-
return order.baseAssetAmount;
|
|
134
|
-
}
|
|
@@ -1,197 +0,0 @@
|
|
|
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
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
-
exports.BulkAccountLoader = void 0;
|
|
13
|
-
const uuid_1 = require("uuid");
|
|
14
|
-
const promiseTimeout_1 = require("../util/promiseTimeout");
|
|
15
|
-
const GET_MULTIPLE_ACCOUNTS_CHUNK_SIZE = 99;
|
|
16
|
-
const oneMinute = 60 * 1000;
|
|
17
|
-
class BulkAccountLoader {
|
|
18
|
-
constructor(connection, commitment, pollingFrequency) {
|
|
19
|
-
this.accountsToLoad = new Map();
|
|
20
|
-
this.bufferAndSlotMap = new Map();
|
|
21
|
-
this.errorCallbacks = new Map();
|
|
22
|
-
this.lastTimeLoadingPromiseCleared = Date.now();
|
|
23
|
-
this.mostRecentSlot = 0;
|
|
24
|
-
this.connection = connection;
|
|
25
|
-
this.commitment = commitment;
|
|
26
|
-
this.pollingFrequency = pollingFrequency;
|
|
27
|
-
}
|
|
28
|
-
addAccount(publicKey, callback) {
|
|
29
|
-
const existingSize = this.accountsToLoad.size;
|
|
30
|
-
const callbackId = uuid_1.v4();
|
|
31
|
-
const existingAccountToLoad = this.accountsToLoad.get(publicKey.toString());
|
|
32
|
-
if (existingAccountToLoad) {
|
|
33
|
-
existingAccountToLoad.callbacks.set(callbackId, callback);
|
|
34
|
-
}
|
|
35
|
-
else {
|
|
36
|
-
const callbacks = new Map();
|
|
37
|
-
callbacks.set(callbackId, callback);
|
|
38
|
-
const newAccountToLoad = {
|
|
39
|
-
publicKey,
|
|
40
|
-
callbacks,
|
|
41
|
-
};
|
|
42
|
-
this.accountsToLoad.set(publicKey.toString(), newAccountToLoad);
|
|
43
|
-
}
|
|
44
|
-
if (existingSize === 0) {
|
|
45
|
-
this.startPolling();
|
|
46
|
-
}
|
|
47
|
-
// if a new account needs to be polled, remove the cached loadPromise in case client calls load immediately after
|
|
48
|
-
this.loadPromise = undefined;
|
|
49
|
-
return callbackId;
|
|
50
|
-
}
|
|
51
|
-
removeAccount(publicKey, callbackId) {
|
|
52
|
-
const existingAccountToLoad = this.accountsToLoad.get(publicKey.toString());
|
|
53
|
-
if (existingAccountToLoad) {
|
|
54
|
-
existingAccountToLoad.callbacks.delete(callbackId);
|
|
55
|
-
if (existingAccountToLoad.callbacks.size === 0) {
|
|
56
|
-
this.accountsToLoad.delete(existingAccountToLoad.publicKey.toString());
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
if (this.accountsToLoad.size === 0) {
|
|
60
|
-
this.stopPolling();
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
addErrorCallbacks(callback) {
|
|
64
|
-
const callbackId = uuid_1.v4();
|
|
65
|
-
this.errorCallbacks.set(callbackId, callback);
|
|
66
|
-
return callbackId;
|
|
67
|
-
}
|
|
68
|
-
removeErrorCallbacks(callbackId) {
|
|
69
|
-
this.errorCallbacks.delete(callbackId);
|
|
70
|
-
}
|
|
71
|
-
chunks(array, size) {
|
|
72
|
-
return new Array(Math.ceil(array.length / size))
|
|
73
|
-
.fill(null)
|
|
74
|
-
.map((_, index) => index * size)
|
|
75
|
-
.map((begin) => array.slice(begin, begin + size));
|
|
76
|
-
}
|
|
77
|
-
load() {
|
|
78
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
79
|
-
if (this.loadPromise) {
|
|
80
|
-
const now = Date.now();
|
|
81
|
-
if (now - this.lastTimeLoadingPromiseCleared > oneMinute) {
|
|
82
|
-
this.loadPromise = undefined;
|
|
83
|
-
}
|
|
84
|
-
else {
|
|
85
|
-
return this.loadPromise;
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
this.loadPromise = new Promise((resolver) => {
|
|
89
|
-
this.loadPromiseResolver = resolver;
|
|
90
|
-
});
|
|
91
|
-
this.lastTimeLoadingPromiseCleared = Date.now();
|
|
92
|
-
try {
|
|
93
|
-
const chunks = this.chunks(Array.from(this.accountsToLoad.values()), GET_MULTIPLE_ACCOUNTS_CHUNK_SIZE);
|
|
94
|
-
yield Promise.all(chunks.map((chunk) => {
|
|
95
|
-
return this.loadChunk(chunk);
|
|
96
|
-
}));
|
|
97
|
-
}
|
|
98
|
-
catch (e) {
|
|
99
|
-
console.error(`Error in bulkAccountLoader.load()`);
|
|
100
|
-
console.error(e);
|
|
101
|
-
for (const [_, callback] of this.errorCallbacks) {
|
|
102
|
-
callback(e);
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
finally {
|
|
106
|
-
this.loadPromiseResolver();
|
|
107
|
-
this.loadPromise = undefined;
|
|
108
|
-
}
|
|
109
|
-
});
|
|
110
|
-
}
|
|
111
|
-
loadChunk(accountsToLoad) {
|
|
112
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
113
|
-
if (accountsToLoad.length === 0) {
|
|
114
|
-
return;
|
|
115
|
-
}
|
|
116
|
-
const args = [
|
|
117
|
-
accountsToLoad.map((accountToLoad) => {
|
|
118
|
-
return accountToLoad.publicKey.toBase58();
|
|
119
|
-
}),
|
|
120
|
-
{ commitment: this.commitment },
|
|
121
|
-
];
|
|
122
|
-
const rpcResponse = yield promiseTimeout_1.promiseTimeout(
|
|
123
|
-
// @ts-ignore
|
|
124
|
-
this.connection._rpcRequest('getMultipleAccounts', args), 10 * 1000 // 30 second timeout
|
|
125
|
-
);
|
|
126
|
-
if (rpcResponse === null) {
|
|
127
|
-
this.log('request to rpc timed out');
|
|
128
|
-
return;
|
|
129
|
-
}
|
|
130
|
-
const newSlot = rpcResponse.result.context.slot;
|
|
131
|
-
if (newSlot > this.mostRecentSlot) {
|
|
132
|
-
this.mostRecentSlot = newSlot;
|
|
133
|
-
}
|
|
134
|
-
for (const i in accountsToLoad) {
|
|
135
|
-
const accountToLoad = accountsToLoad[i];
|
|
136
|
-
const key = accountToLoad.publicKey.toString();
|
|
137
|
-
const oldRPCResponse = this.bufferAndSlotMap.get(key);
|
|
138
|
-
let newBuffer = undefined;
|
|
139
|
-
if (rpcResponse.result.value[i]) {
|
|
140
|
-
const raw = rpcResponse.result.value[i].data[0];
|
|
141
|
-
const dataType = rpcResponse.result.value[i].data[1];
|
|
142
|
-
newBuffer = Buffer.from(raw, dataType);
|
|
143
|
-
}
|
|
144
|
-
if (!oldRPCResponse) {
|
|
145
|
-
this.bufferAndSlotMap.set(key, {
|
|
146
|
-
slot: newSlot,
|
|
147
|
-
buffer: newBuffer,
|
|
148
|
-
});
|
|
149
|
-
this.handleAccountCallbacks(accountToLoad, newBuffer, newSlot);
|
|
150
|
-
continue;
|
|
151
|
-
}
|
|
152
|
-
if (newSlot <= oldRPCResponse.slot) {
|
|
153
|
-
continue;
|
|
154
|
-
}
|
|
155
|
-
const oldBuffer = oldRPCResponse.buffer;
|
|
156
|
-
if (newBuffer && (!oldBuffer || !newBuffer.equals(oldBuffer))) {
|
|
157
|
-
this.bufferAndSlotMap.set(key, {
|
|
158
|
-
slot: newSlot,
|
|
159
|
-
buffer: newBuffer,
|
|
160
|
-
});
|
|
161
|
-
this.handleAccountCallbacks(accountToLoad, newBuffer, newSlot);
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
});
|
|
165
|
-
}
|
|
166
|
-
handleAccountCallbacks(accountToLoad, buffer, slot) {
|
|
167
|
-
for (const [_, callback] of accountToLoad.callbacks) {
|
|
168
|
-
callback(buffer, slot);
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
getBufferAndSlot(publicKey) {
|
|
172
|
-
return this.bufferAndSlotMap.get(publicKey.toString());
|
|
173
|
-
}
|
|
174
|
-
startPolling() {
|
|
175
|
-
if (this.intervalId) {
|
|
176
|
-
return;
|
|
177
|
-
}
|
|
178
|
-
this.intervalId = setInterval(this.load.bind(this), this.pollingFrequency);
|
|
179
|
-
}
|
|
180
|
-
stopPolling() {
|
|
181
|
-
if (this.intervalId) {
|
|
182
|
-
clearInterval(this.intervalId);
|
|
183
|
-
this.intervalId = undefined;
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
log(msg) {
|
|
187
|
-
console.log(msg);
|
|
188
|
-
}
|
|
189
|
-
updatePollingFrequency(pollingFrequency) {
|
|
190
|
-
this.stopPolling();
|
|
191
|
-
this.pollingFrequency = pollingFrequency;
|
|
192
|
-
if (this.accountsToLoad.size > 0) {
|
|
193
|
-
this.startPolling();
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
}
|
|
197
|
-
exports.BulkAccountLoader = BulkAccountLoader;
|
|
@@ -1,33 +0,0 @@
|
|
|
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
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
-
exports.bulkPollingUserSubscribe = void 0;
|
|
13
|
-
/**
|
|
14
|
-
* @param users
|
|
15
|
-
* @param accountLoader
|
|
16
|
-
*/
|
|
17
|
-
function bulkPollingUserSubscribe(users, accountLoader) {
|
|
18
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
19
|
-
if (users.length === 0) {
|
|
20
|
-
yield accountLoader.load();
|
|
21
|
-
return;
|
|
22
|
-
}
|
|
23
|
-
yield Promise.all(users.map((user) => {
|
|
24
|
-
// Pull the keys from the authority map so we can skip fetching them in addToAccountLoader
|
|
25
|
-
return user.accountSubscriber.addToAccountLoader();
|
|
26
|
-
}));
|
|
27
|
-
yield accountLoader.load();
|
|
28
|
-
yield Promise.all(users.map((user) => __awaiter(this, void 0, void 0, function* () {
|
|
29
|
-
return user.subscribe();
|
|
30
|
-
})));
|
|
31
|
-
});
|
|
32
|
-
}
|
|
33
|
-
exports.bulkPollingUserSubscribe = bulkPollingUserSubscribe;
|