@drift-labs/sdk 0.2.0-master.11 → 0.2.0-master.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/lib/clearingHouse.d.ts +7 -2
  2. package/lib/clearingHouse.js +157 -37
  3. package/lib/clearingHouseUser.d.ts +10 -15
  4. package/lib/clearingHouseUser.js +92 -74
  5. package/lib/config.js +1 -1
  6. package/lib/constants/banks.d.ts +2 -2
  7. package/lib/constants/banks.js +4 -3
  8. package/lib/constants/numericConstants.d.ts +2 -0
  9. package/lib/constants/numericConstants.js +3 -1
  10. package/lib/events/eventList.js +3 -0
  11. package/lib/events/types.d.ts +2 -1
  12. package/lib/factory/bigNum.d.ts +1 -0
  13. package/lib/factory/bigNum.js +37 -11
  14. package/lib/idl/clearing_house.json +97 -19
  15. package/lib/index.d.ts +1 -0
  16. package/lib/index.js +1 -0
  17. package/lib/math/bankBalance.d.ts +3 -1
  18. package/lib/math/bankBalance.js +54 -1
  19. package/lib/math/margin.d.ts +11 -0
  20. package/lib/math/margin.js +72 -0
  21. package/lib/math/market.d.ts +4 -1
  22. package/lib/math/market.js +35 -1
  23. package/lib/math/position.d.ts +8 -0
  24. package/lib/math/position.js +42 -12
  25. package/lib/orders.d.ts +1 -2
  26. package/lib/orders.js +2 -77
  27. package/lib/tokenFaucet.d.ts +1 -0
  28. package/lib/tokenFaucet.js +23 -12
  29. package/lib/tx/retryTxSender.js +9 -2
  30. package/lib/types.d.ts +24 -3
  31. package/lib/types.js +6 -0
  32. package/lib/util/getTokenAddress.d.ts +2 -0
  33. package/lib/util/getTokenAddress.js +9 -0
  34. package/package.json +1 -1
  35. package/src/clearingHouse.ts +301 -47
  36. package/src/clearingHouseConfig.js +2 -0
  37. package/src/clearingHouseUser.ts +213 -104
  38. package/src/clearingHouseUserConfig.js +2 -0
  39. package/src/config.ts +1 -1
  40. package/src/constants/banks.js +42 -0
  41. package/src/constants/banks.ts +6 -3
  42. package/src/constants/markets.js +42 -0
  43. package/src/constants/numericConstants.js +41 -0
  44. package/src/constants/numericConstants.ts +3 -0
  45. package/src/events/eventList.ts +3 -0
  46. package/src/events/types.ts +2 -0
  47. package/src/factory/bigNum.js +37 -11
  48. package/src/factory/bigNum.ts +43 -13
  49. package/src/idl/clearing_house.json +97 -19
  50. package/src/index.js +67 -98
  51. package/src/index.ts +1 -0
  52. package/src/math/bankBalance.ts +98 -1
  53. package/src/math/margin.ts +124 -0
  54. package/src/math/market.ts +66 -1
  55. package/src/math/position.ts +59 -9
  56. package/src/orders.ts +4 -157
  57. package/src/tokenFaucet.js +189 -0
  58. package/src/tokenFaucet.ts +38 -15
  59. package/src/tx/retryTxSender.ts +11 -3
  60. package/src/types.js +12 -1
  61. package/src/types.ts +25 -3
  62. package/src/{accounts/fetch.js → util/computeUnits.js} +11 -13
  63. package/src/util/getTokenAddress.js +9 -0
  64. package/src/util/getTokenAddress.ts +18 -0
  65. package/tests/bn/test.ts +2 -0
  66. package/src/addresses/pda.js +0 -104
  67. package/src/math/bankBalance.js +0 -75
  68. package/src/math/market.js +0 -57
  69. package/src/math/orders.js +0 -110
  70. package/src/math/position.js +0 -140
  71. package/src/orders.js +0 -134
  72. package/src/tx/retryTxSender.js +0 -188
@@ -1,104 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
- }) : (function(o, m, k, k2) {
6
- if (k2 === undefined) k2 = k;
7
- o[k2] = m[k];
8
- }));
9
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
- Object.defineProperty(o, "default", { enumerable: true, value: v });
11
- }) : function(o, v) {
12
- o["default"] = v;
13
- });
14
- var __importStar = (this && this.__importStar) || function (mod) {
15
- if (mod && mod.__esModule) return mod;
16
- var result = {};
17
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
- __setModuleDefault(result, mod);
19
- return result;
20
- };
21
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
22
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
23
- return new (P || (P = Promise))(function (resolve, reject) {
24
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
25
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
26
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
27
- step((generator = generator.apply(thisArg, _arguments || [])).next());
28
- });
29
- };
30
- Object.defineProperty(exports, "__esModule", { value: true });
31
- exports.getBankVaultAuthorityPublicKey = exports.getBankVaultPublicKey = exports.getBankPublicKey = exports.getMarketPublicKey = exports.getUserAccountPublicKeySync = exports.getUserAccountPublicKey = exports.getUserAccountPublicKeyAndNonce = exports.getClearingHouseStateAccountPublicKey = exports.getClearingHouseStateAccountPublicKeyAndNonce = void 0;
32
- const anchor = __importStar(require("@project-serum/anchor"));
33
- function getClearingHouseStateAccountPublicKeyAndNonce(programId) {
34
- return __awaiter(this, void 0, void 0, function* () {
35
- return anchor.web3.PublicKey.findProgramAddress([Buffer.from(anchor.utils.bytes.utf8.encode('clearing_house'))], programId);
36
- });
37
- }
38
- exports.getClearingHouseStateAccountPublicKeyAndNonce = getClearingHouseStateAccountPublicKeyAndNonce;
39
- function getClearingHouseStateAccountPublicKey(programId) {
40
- return __awaiter(this, void 0, void 0, function* () {
41
- return (yield getClearingHouseStateAccountPublicKeyAndNonce(programId))[0];
42
- });
43
- }
44
- exports.getClearingHouseStateAccountPublicKey = getClearingHouseStateAccountPublicKey;
45
- function getUserAccountPublicKeyAndNonce(programId, authority, userId = 0) {
46
- return __awaiter(this, void 0, void 0, function* () {
47
- return anchor.web3.PublicKey.findProgramAddress([
48
- Buffer.from(anchor.utils.bytes.utf8.encode('user')),
49
- authority.toBuffer(),
50
- Uint8Array.from([userId]),
51
- ], programId);
52
- });
53
- }
54
- exports.getUserAccountPublicKeyAndNonce = getUserAccountPublicKeyAndNonce;
55
- function getUserAccountPublicKey(programId, authority, userId = 0) {
56
- return __awaiter(this, void 0, void 0, function* () {
57
- return (yield getUserAccountPublicKeyAndNonce(programId, authority, userId))[0];
58
- });
59
- }
60
- exports.getUserAccountPublicKey = getUserAccountPublicKey;
61
- function getUserAccountPublicKeySync(programId, authority, userId = 0) {
62
- return anchor.web3.PublicKey.findProgramAddressSync([
63
- Buffer.from(anchor.utils.bytes.utf8.encode('user')),
64
- authority.toBuffer(),
65
- Uint8Array.from([userId]),
66
- ], programId)[0];
67
- }
68
- exports.getUserAccountPublicKeySync = getUserAccountPublicKeySync;
69
- function getMarketPublicKey(programId, marketIndex) {
70
- return __awaiter(this, void 0, void 0, function* () {
71
- return (yield anchor.web3.PublicKey.findProgramAddress([
72
- Buffer.from(anchor.utils.bytes.utf8.encode('market')),
73
- marketIndex.toArrayLike(Buffer, 'le', 8),
74
- ], programId))[0];
75
- });
76
- }
77
- exports.getMarketPublicKey = getMarketPublicKey;
78
- function getBankPublicKey(programId, bankIndex) {
79
- return __awaiter(this, void 0, void 0, function* () {
80
- return (yield anchor.web3.PublicKey.findProgramAddress([
81
- Buffer.from(anchor.utils.bytes.utf8.encode('bank')),
82
- bankIndex.toArrayLike(Buffer, 'le', 8),
83
- ], programId))[0];
84
- });
85
- }
86
- exports.getBankPublicKey = getBankPublicKey;
87
- function getBankVaultPublicKey(programId, bankIndex) {
88
- return __awaiter(this, void 0, void 0, function* () {
89
- return (yield anchor.web3.PublicKey.findProgramAddress([
90
- Buffer.from(anchor.utils.bytes.utf8.encode('bank_vault')),
91
- bankIndex.toArrayLike(Buffer, 'le', 8),
92
- ], programId))[0];
93
- });
94
- }
95
- exports.getBankVaultPublicKey = getBankVaultPublicKey;
96
- function getBankVaultAuthorityPublicKey(programId, bankIndex) {
97
- return __awaiter(this, void 0, void 0, function* () {
98
- return (yield anchor.web3.PublicKey.findProgramAddress([
99
- Buffer.from(anchor.utils.bytes.utf8.encode('bank_vault_authority')),
100
- bankIndex.toArrayLike(Buffer, 'le', 8),
101
- ], programId))[0];
102
- });
103
- }
104
- exports.getBankVaultAuthorityPublicKey = getBankVaultAuthorityPublicKey;
@@ -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 = 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) && 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 = 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;
@@ -1,57 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.calculateOracleSpread = exports.calculateMarkOracleSpread = exports.calculateNewMarketAfterTrade = exports.calculateAskPrice = exports.calculateBidPrice = exports.calculateMarkPrice = void 0;
4
- const types_1 = require("../types");
5
- const amm_1 = require("./amm");
6
- /**
7
- * Calculates market mark price
8
- *
9
- * @param market
10
- * @return markPrice : Precision MARK_PRICE_PRECISION
11
- */
12
- function calculateMarkPrice(market, oraclePriceData) {
13
- const newAmm = amm_1.calculateUpdatedAMM(market.amm, oraclePriceData);
14
- return amm_1.calculatePrice(newAmm.baseAssetReserve, newAmm.quoteAssetReserve, newAmm.pegMultiplier);
15
- }
16
- exports.calculateMarkPrice = calculateMarkPrice;
17
- /**
18
- * Calculates market bid price
19
- *
20
- * @param market
21
- * @return bidPrice : Precision MARK_PRICE_PRECISION
22
- */
23
- function calculateBidPrice(market, oraclePriceData) {
24
- const { baseAssetReserve, quoteAssetReserve, newPeg } = amm_1.calculateUpdatedAMMSpreadReserves(market.amm, types_1.PositionDirection.SHORT, oraclePriceData);
25
- return amm_1.calculatePrice(baseAssetReserve, quoteAssetReserve, newPeg);
26
- }
27
- exports.calculateBidPrice = calculateBidPrice;
28
- /**
29
- * Calculates market ask price
30
- *
31
- * @param market
32
- * @return bidPrice : Precision MARK_PRICE_PRECISION
33
- */
34
- function calculateAskPrice(market, oraclePriceData) {
35
- const { baseAssetReserve, quoteAssetReserve, newPeg } = amm_1.calculateUpdatedAMMSpreadReserves(market.amm, types_1.PositionDirection.LONG, oraclePriceData);
36
- return amm_1.calculatePrice(baseAssetReserve, quoteAssetReserve, newPeg);
37
- }
38
- exports.calculateAskPrice = calculateAskPrice;
39
- function calculateNewMarketAfterTrade(baseAssetAmount, direction, market) {
40
- const [newQuoteAssetReserve, newBaseAssetReserve] = amm_1.calculateAmmReservesAfterSwap(market.amm, 'base', baseAssetAmount.abs(), amm_1.getSwapDirection('base', direction));
41
- const newAmm = Object.assign({}, market.amm);
42
- const newMarket = Object.assign({}, market);
43
- newMarket.amm = newAmm;
44
- newMarket.amm.quoteAssetReserve = newQuoteAssetReserve;
45
- newMarket.amm.baseAssetReserve = newBaseAssetReserve;
46
- return newMarket;
47
- }
48
- exports.calculateNewMarketAfterTrade = calculateNewMarketAfterTrade;
49
- function calculateMarkOracleSpread(market, oraclePriceData) {
50
- const markPrice = calculateMarkPrice(market, oraclePriceData);
51
- return calculateOracleSpread(markPrice, oraclePriceData);
52
- }
53
- exports.calculateMarkOracleSpread = calculateMarkOracleSpread;
54
- function calculateOracleSpread(price, oraclePriceData) {
55
- return price.sub(oraclePriceData.price);
56
- }
57
- exports.calculateOracleSpread = calculateOracleSpread;
@@ -1,110 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getLimitPrice = exports.standardizeBaseAssetAmount = exports.isOrderReduceOnly = exports.isOrderRiskIncreasingInSameDirection = exports.isOrderRiskIncreasing = void 0;
4
- const types_1 = require("../types");
5
- const numericConstants_1 = require("../constants/numericConstants");
6
- const anchor_1 = require("@project-serum/anchor");
7
- const auction_1 = require("./auction");
8
- const market_1 = require("./market");
9
- function isOrderRiskIncreasing(user, order) {
10
- if (types_1.isVariant(order.status, 'init')) {
11
- return false;
12
- }
13
- const position = user.getUserPosition(order.marketIndex) ||
14
- user.getEmptyPosition(order.marketIndex);
15
- // if no position exists, it's risk increasing
16
- if (position.baseAssetAmount.eq(numericConstants_1.ZERO)) {
17
- return true;
18
- }
19
- // if position is long and order is long
20
- if (position.baseAssetAmount.gt(numericConstants_1.ZERO) && types_1.isVariant(order.direction, 'long')) {
21
- return true;
22
- }
23
- // if position is short and order is short
24
- if (position.baseAssetAmount.lt(numericConstants_1.ZERO) &&
25
- types_1.isVariant(order.direction, 'short')) {
26
- return true;
27
- }
28
- const baseAssetAmountToFill = order.baseAssetAmount.sub(order.baseAssetAmountFilled);
29
- // if order will flip position
30
- if (baseAssetAmountToFill.gt(position.baseAssetAmount.abs().mul(numericConstants_1.TWO))) {
31
- return true;
32
- }
33
- return false;
34
- }
35
- exports.isOrderRiskIncreasing = isOrderRiskIncreasing;
36
- function isOrderRiskIncreasingInSameDirection(user, order) {
37
- if (types_1.isVariant(order.status, 'init')) {
38
- return false;
39
- }
40
- const position = user.getUserPosition(order.marketIndex) ||
41
- user.getEmptyPosition(order.marketIndex);
42
- // if no position exists, it's risk increasing
43
- if (position.baseAssetAmount.eq(numericConstants_1.ZERO)) {
44
- return true;
45
- }
46
- // if position is long and order is long
47
- if (position.baseAssetAmount.gt(numericConstants_1.ZERO) && types_1.isVariant(order.direction, 'long')) {
48
- return true;
49
- }
50
- // if position is short and order is short
51
- if (position.baseAssetAmount.lt(numericConstants_1.ZERO) &&
52
- types_1.isVariant(order.direction, 'short')) {
53
- return true;
54
- }
55
- return false;
56
- }
57
- exports.isOrderRiskIncreasingInSameDirection = isOrderRiskIncreasingInSameDirection;
58
- function isOrderReduceOnly(user, order) {
59
- if (types_1.isVariant(order.status, 'init')) {
60
- return false;
61
- }
62
- const position = user.getUserPosition(order.marketIndex) ||
63
- user.getEmptyPosition(order.marketIndex);
64
- // if position is long and order is long
65
- if (position.baseAssetAmount.gte(numericConstants_1.ZERO) &&
66
- types_1.isVariant(order.direction, 'long')) {
67
- return false;
68
- }
69
- // if position is short and order is short
70
- if (position.baseAssetAmount.lte(numericConstants_1.ZERO) &&
71
- types_1.isVariant(order.direction, 'short')) {
72
- return false;
73
- }
74
- return true;
75
- }
76
- exports.isOrderReduceOnly = isOrderReduceOnly;
77
- function standardizeBaseAssetAmount(baseAssetAmount, stepSize) {
78
- const remainder = baseAssetAmount.mod(stepSize);
79
- return baseAssetAmount.sub(remainder);
80
- }
81
- exports.standardizeBaseAssetAmount = standardizeBaseAssetAmount;
82
- function getLimitPrice(order, market, oraclePriceData, slot) {
83
- let limitPrice;
84
- if (!order.oraclePriceOffset.eq(numericConstants_1.ZERO)) {
85
- limitPrice = oraclePriceData.price.add(order.oraclePriceOffset);
86
- }
87
- else if (types_1.isOneOfVariant(order.orderType, ['market', 'triggerMarket'])) {
88
- if (auction_1.isAuctionComplete(order, slot)) {
89
- limitPrice = auction_1.getAuctionPrice(order, slot);
90
- }
91
- else if (!order.price.eq(numericConstants_1.ZERO)) {
92
- limitPrice = order.price;
93
- }
94
- else if (types_1.isVariant(order.direction, 'long')) {
95
- const askPrice = market_1.calculateAskPrice(market, oraclePriceData);
96
- const delta = askPrice.div(new anchor_1.BN(market.amm.maxSlippageRatio));
97
- limitPrice = askPrice.add(delta);
98
- }
99
- else {
100
- const bidPrice = market_1.calculateBidPrice(market, oraclePriceData);
101
- const delta = bidPrice.div(new anchor_1.BN(market.amm.maxSlippageRatio));
102
- limitPrice = bidPrice.sub(delta);
103
- }
104
- }
105
- else {
106
- limitPrice = order.price;
107
- }
108
- return limitPrice;
109
- }
110
- exports.getLimitPrice = getLimitPrice;
@@ -1,140 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isEmptyPosition = exports.positionCurrentDirection = exports.findDirectionToClose = exports.calculateEntryPrice = exports.positionIsAvailable = exports.calculatePositionFundingPNL = exports.calculatePositionPNL = exports.calculateBaseAssetValue = void 0;
4
- const __1 = require("../");
5
- const numericConstants_1 = require("../constants/numericConstants");
6
- const types_1 = require("../types");
7
- const amm_1 = require("./amm");
8
- /**
9
- * calculateBaseAssetValue
10
- * = market value of closing entire position
11
- * @param market
12
- * @param userPosition
13
- * @param oraclePriceData
14
- * @returns Base Asset Value. : Precision QUOTE_PRECISION
15
- */
16
- function calculateBaseAssetValue(market, userPosition, oraclePriceData) {
17
- if (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
18
- return numericConstants_1.ZERO;
19
- }
20
- const directionToClose = findDirectionToClose(userPosition);
21
- let prepegAmm;
22
- if (market.amm.baseSpread > 0) {
23
- const { baseAssetReserve, quoteAssetReserve, sqrtK, newPeg } = amm_1.calculateUpdatedAMMSpreadReserves(market.amm, directionToClose, oraclePriceData);
24
- prepegAmm = {
25
- baseAssetReserve,
26
- quoteAssetReserve,
27
- sqrtK: sqrtK,
28
- pegMultiplier: newPeg,
29
- };
30
- }
31
- else {
32
- prepegAmm = amm_1.calculateUpdatedAMM(market.amm, oraclePriceData);
33
- }
34
- const [newQuoteAssetReserve, _] = amm_1.calculateAmmReservesAfterSwap(prepegAmm, 'base', userPosition.baseAssetAmount.abs(), amm_1.getSwapDirection('base', directionToClose));
35
- switch (directionToClose) {
36
- case types_1.PositionDirection.SHORT:
37
- return prepegAmm.quoteAssetReserve
38
- .sub(newQuoteAssetReserve)
39
- .mul(prepegAmm.pegMultiplier)
40
- .div(numericConstants_1.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO);
41
- case types_1.PositionDirection.LONG:
42
- return newQuoteAssetReserve
43
- .sub(prepegAmm.quoteAssetReserve)
44
- .mul(prepegAmm.pegMultiplier)
45
- .div(numericConstants_1.AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO)
46
- .add(numericConstants_1.ONE);
47
- }
48
- }
49
- exports.calculateBaseAssetValue = calculateBaseAssetValue;
50
- /**
51
- * calculatePositionPNL
52
- * = BaseAssetAmount * (Avg Exit Price - Avg Entry Price)
53
- * @param market
54
- * @param marketPosition
55
- * @param withFunding (adds unrealized funding payment pnl to result)
56
- * @returns BaseAssetAmount : Precision QUOTE_PRECISION
57
- */
58
- function calculatePositionPNL(market, marketPosition, withFunding = false, oraclePriceData) {
59
- if (marketPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
60
- return numericConstants_1.ZERO;
61
- }
62
- const baseAssetValue = calculateBaseAssetValue(market, marketPosition, oraclePriceData);
63
- let pnl;
64
- if (marketPosition.baseAssetAmount.gt(numericConstants_1.ZERO)) {
65
- pnl = baseAssetValue.sub(marketPosition.quoteAssetAmount);
66
- }
67
- else {
68
- pnl = marketPosition.quoteAssetAmount.sub(baseAssetValue);
69
- }
70
- if (withFunding) {
71
- const fundingRatePnL = calculatePositionFundingPNL(market, marketPosition).div(numericConstants_1.PRICE_TO_QUOTE_PRECISION);
72
- pnl = pnl.add(fundingRatePnL);
73
- }
74
- return pnl;
75
- }
76
- exports.calculatePositionPNL = calculatePositionPNL;
77
- /**
78
- *
79
- * @param market
80
- * @param marketPosition
81
- * @returns // TODO-PRECISION
82
- */
83
- function calculatePositionFundingPNL(market, marketPosition) {
84
- if (marketPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
85
- return numericConstants_1.ZERO;
86
- }
87
- let ammCumulativeFundingRate;
88
- if (marketPosition.baseAssetAmount.gt(numericConstants_1.ZERO)) {
89
- ammCumulativeFundingRate = market.amm.cumulativeFundingRateLong;
90
- }
91
- else {
92
- ammCumulativeFundingRate = market.amm.cumulativeFundingRateShort;
93
- }
94
- const perPositionFundingRate = ammCumulativeFundingRate
95
- .sub(marketPosition.lastCumulativeFundingRate)
96
- .mul(marketPosition.baseAssetAmount)
97
- .div(numericConstants_1.AMM_RESERVE_PRECISION)
98
- .div(numericConstants_1.FUNDING_PAYMENT_PRECISION)
99
- .mul(new __1.BN(-1));
100
- return perPositionFundingRate;
101
- }
102
- exports.calculatePositionFundingPNL = calculatePositionFundingPNL;
103
- function positionIsAvailable(position) {
104
- return (position.baseAssetAmount.eq(numericConstants_1.ZERO) &&
105
- position.openOrders.eq(numericConstants_1.ZERO) &&
106
- position.unsettledPnl.eq(numericConstants_1.ZERO));
107
- }
108
- exports.positionIsAvailable = positionIsAvailable;
109
- /**
110
- *
111
- * @param userPosition
112
- * @returns Precision: MARK_PRICE_PRECISION (10^10)
113
- */
114
- function calculateEntryPrice(userPosition) {
115
- if (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
116
- return numericConstants_1.ZERO;
117
- }
118
- return userPosition.quoteAssetAmount
119
- .mul(numericConstants_1.MARK_PRICE_PRECISION)
120
- .mul(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO)
121
- .div(userPosition.baseAssetAmount)
122
- .abs();
123
- }
124
- exports.calculateEntryPrice = calculateEntryPrice;
125
- function findDirectionToClose(userPosition) {
126
- return userPosition.baseAssetAmount.gt(numericConstants_1.ZERO)
127
- ? types_1.PositionDirection.SHORT
128
- : types_1.PositionDirection.LONG;
129
- }
130
- exports.findDirectionToClose = findDirectionToClose;
131
- function positionCurrentDirection(userPosition) {
132
- return userPosition.baseAssetAmount.gte(numericConstants_1.ZERO)
133
- ? types_1.PositionDirection.LONG
134
- : types_1.PositionDirection.SHORT;
135
- }
136
- exports.positionCurrentDirection = positionCurrentDirection;
137
- function isEmptyPosition(userPosition) {
138
- return (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO) && userPosition.openOrders.eq(numericConstants_1.ZERO));
139
- }
140
- exports.isEmptyPosition = isEmptyPosition;
package/src/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 (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 = position_1.positionCurrentDirection(userPosition);
21
- const increasePosition = userPosition.baseAssetAmount.eq(numericConstants_1.ZERO) ||
22
- isSameDirection(order.direction, currentPositionDirection);
23
- if (increasePosition) {
24
- const marketAfter = 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 = market_1.calculateNewMarketAfterTrade(userPosition.baseAssetAmount, position_1.findDirectionToClose(userPosition), market);
34
- const { quoteAssetAmountSwapped: baseAssetValue } = calculateAmountSwapped(market, intermediateMarket);
35
- let pnl;
36
- if (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 = 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 = 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 (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 (types_1.isVariant(order.orderType, 'limit')) {
85
- return calculateAmountToTradeForLimit(market, order, oraclePriceData);
86
- }
87
- else if (types_1.isVariant(order.orderType, 'triggerLimit')) {
88
- return calculateAmountToTradeForTriggerLimit(market, order);
89
- }
90
- else if (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] = amm_1.calculateMaxBaseAssetAmountToTrade(market.amm, limitPrice, order.direction);
107
- const baseAssetAmount = _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 ((types_1.isVariant(firstDirection, 'long') && types_1.isVariant(secondDirection, 'long')) ||
127
- (types_1.isVariant(firstDirection, 'short') && 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
- }