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

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 (114) hide show
  1. package/lib/accounts/fetch.d.ts +2 -1
  2. package/lib/accounts/fetch.js +9 -1
  3. package/lib/accounts/pollingUserStatsAccountSubscriber.d.ts +27 -0
  4. package/lib/accounts/pollingUserStatsAccountSubscriber.js +113 -0
  5. package/lib/accounts/types.d.ts +14 -1
  6. package/lib/accounts/webSocketUserStatsAccountSubsriber.d.ts +20 -0
  7. package/lib/accounts/webSocketUserStatsAccountSubsriber.js +47 -0
  8. package/lib/addresses/pda.d.ts +1 -0
  9. package/lib/addresses/pda.js +8 -1
  10. package/lib/admin.d.ts +2 -0
  11. package/lib/admin.js +18 -0
  12. package/lib/clearingHouse.d.ts +24 -3
  13. package/lib/clearingHouse.js +352 -51
  14. package/lib/clearingHouseConfig.d.ts +1 -0
  15. package/lib/clearingHouseUser.d.ts +15 -15
  16. package/lib/clearingHouseUser.js +185 -73
  17. package/lib/clearingHouseUserStats.d.ts +17 -0
  18. package/lib/clearingHouseUserStats.js +36 -0
  19. package/lib/clearingHouseUserStatsConfig.d.ts +14 -0
  20. package/lib/clearingHouseUserStatsConfig.js +2 -0
  21. package/lib/config.js +1 -1
  22. package/lib/constants/banks.d.ts +2 -2
  23. package/lib/constants/banks.js +4 -3
  24. package/lib/constants/numericConstants.d.ts +2 -0
  25. package/lib/constants/numericConstants.js +3 -1
  26. package/lib/events/eventList.js +3 -0
  27. package/lib/events/types.d.ts +2 -1
  28. package/lib/factory/bigNum.d.ts +1 -0
  29. package/lib/factory/bigNum.js +37 -11
  30. package/lib/idl/clearing_house.json +692 -58
  31. package/lib/index.d.ts +1 -0
  32. package/lib/index.js +1 -0
  33. package/lib/math/amm.js +2 -2
  34. package/lib/math/bankBalance.d.ts +7 -1
  35. package/lib/math/bankBalance.js +76 -1
  36. package/lib/math/margin.d.ts +11 -0
  37. package/lib/math/margin.js +72 -0
  38. package/lib/math/market.d.ts +4 -1
  39. package/lib/math/market.js +35 -1
  40. package/lib/math/oracles.d.ts +3 -0
  41. package/lib/math/oracles.js +25 -5
  42. package/lib/math/position.d.ts +8 -0
  43. package/lib/math/position.js +43 -12
  44. package/lib/math/trade.js +2 -2
  45. package/lib/orders.d.ts +1 -2
  46. package/lib/orders.js +2 -77
  47. package/lib/tokenFaucet.d.ts +1 -0
  48. package/lib/tokenFaucet.js +23 -12
  49. package/lib/tx/retryTxSender.js +9 -2
  50. package/lib/types.d.ts +78 -10
  51. package/lib/types.js +12 -0
  52. package/lib/util/getTokenAddress.d.ts +2 -0
  53. package/lib/util/getTokenAddress.js +9 -0
  54. package/package.json +1 -1
  55. package/src/accounts/fetch.ts +27 -2
  56. package/src/accounts/pollingUserStatsAccountSubscriber.ts +172 -0
  57. package/src/accounts/types.ts +18 -0
  58. package/src/accounts/webSocketUserStatsAccountSubsriber.ts +80 -0
  59. package/src/addresses/pda.ts +13 -0
  60. package/src/admin.ts +29 -1
  61. package/src/clearingHouse.ts +619 -62
  62. package/src/clearingHouseConfig.ts +1 -0
  63. package/src/clearingHouseUser.ts +317 -105
  64. package/src/clearingHouseUserStats.ts +53 -0
  65. package/src/clearingHouseUserStatsConfig.ts +18 -0
  66. package/src/config.ts +1 -1
  67. package/src/constants/banks.js +42 -0
  68. package/src/constants/banks.ts +6 -3
  69. package/src/constants/markets.js +42 -0
  70. package/src/constants/numericConstants.js +41 -0
  71. package/src/constants/numericConstants.ts +3 -0
  72. package/src/events/eventList.ts +3 -0
  73. package/src/events/types.ts +2 -0
  74. package/src/factory/bigNum.js +37 -11
  75. package/src/factory/bigNum.ts +43 -13
  76. package/src/idl/clearing_house.json +692 -58
  77. package/src/index.ts +1 -0
  78. package/src/math/amm.ts +8 -5
  79. package/src/math/bankBalance.ts +147 -1
  80. package/src/math/margin.ts +124 -0
  81. package/src/math/market.ts +66 -1
  82. package/src/math/oracles.ts +42 -5
  83. package/src/math/position.ts +60 -9
  84. package/src/math/trade.ts +2 -2
  85. package/src/orders.ts +4 -157
  86. package/src/tokenFaucet.js +189 -0
  87. package/src/tokenFaucet.ts +38 -15
  88. package/src/tx/retryTxSender.ts +11 -3
  89. package/src/types.js +12 -1
  90. package/src/types.ts +83 -10
  91. package/src/{accounts/fetch.js → util/computeUnits.js} +11 -13
  92. package/src/util/getTokenAddress.js +9 -0
  93. package/src/util/getTokenAddress.ts +18 -0
  94. package/tests/bn/test.ts +2 -0
  95. package/src/accounts/bulkAccountLoader.js +0 -197
  96. package/src/accounts/bulkUserSubscription.js +0 -33
  97. package/src/accounts/pollingClearingHouseAccountSubscriber.js +0 -311
  98. package/src/accounts/pollingOracleSubscriber.js +0 -93
  99. package/src/accounts/pollingTokenAccountSubscriber.js +0 -90
  100. package/src/accounts/pollingUserAccountSubscriber.js +0 -132
  101. package/src/accounts/types.js +0 -10
  102. package/src/accounts/utils.js +0 -7
  103. package/src/accounts/webSocketAccountSubscriber.js +0 -93
  104. package/src/accounts/webSocketClearingHouseAccountSubscriber.js +0 -233
  105. package/src/accounts/webSocketUserAccountSubscriber.js +0 -62
  106. package/src/addresses/pda.js +0 -104
  107. package/src/index.js +0 -100
  108. package/src/math/bankBalance.js +0 -75
  109. package/src/math/market.js +0 -57
  110. package/src/math/orders.js +0 -110
  111. package/src/math/position.js +0 -140
  112. package/src/mockUSDCFaucet.js +0 -280
  113. package/src/orders.js +0 -134
  114. package/src/tx/retryTxSender.js +0 -188
@@ -1,62 +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.WebSocketUserAccountSubscriber = void 0;
13
- const types_1 = require("./types");
14
- const events_1 = require("events");
15
- const webSocketAccountSubscriber_1 = require("./webSocketAccountSubscriber");
16
- class WebSocketUserAccountSubscriber {
17
- constructor(program, userAccountPublicKey) {
18
- this.isSubscribed = false;
19
- this.program = program;
20
- this.userAccountPublicKey = userAccountPublicKey;
21
- this.eventEmitter = new events_1.EventEmitter();
22
- }
23
- subscribe() {
24
- return __awaiter(this, void 0, void 0, function* () {
25
- if (this.isSubscribed) {
26
- return true;
27
- }
28
- this.userDataAccountSubscriber = new webSocketAccountSubscriber_1.WebSocketAccountSubscriber('user', this.program, this.userAccountPublicKey);
29
- yield this.userDataAccountSubscriber.subscribe((data) => {
30
- this.eventEmitter.emit('userAccountUpdate', data);
31
- this.eventEmitter.emit('update');
32
- });
33
- this.eventEmitter.emit('update');
34
- this.isSubscribed = true;
35
- return true;
36
- });
37
- }
38
- fetch() {
39
- return __awaiter(this, void 0, void 0, function* () {
40
- yield Promise.all([this.userDataAccountSubscriber.fetch()]);
41
- });
42
- }
43
- unsubscribe() {
44
- return __awaiter(this, void 0, void 0, function* () {
45
- if (!this.isSubscribed) {
46
- return;
47
- }
48
- yield Promise.all([this.userDataAccountSubscriber.unsubscribe()]);
49
- this.isSubscribed = false;
50
- });
51
- }
52
- assertIsSubscribed() {
53
- if (!this.isSubscribed) {
54
- throw new types_1.NotSubscribedError('You must call `subscribe` before using this function');
55
- }
56
- }
57
- getUserAccountAndSlot() {
58
- this.assertIsSubscribed();
59
- return this.userDataAccountSubscriber.dataAndSlot;
60
- }
61
- }
62
- exports.WebSocketUserAccountSubscriber = WebSocketUserAccountSubscriber;
@@ -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;
package/src/index.js DELETED
@@ -1,100 +0,0 @@
1
- 'use strict';
2
- var __createBinding =
3
- (this && this.__createBinding) ||
4
- (Object.create
5
- ? function (o, m, k, k2) {
6
- if (k2 === undefined) k2 = k;
7
- Object.defineProperty(o, k2, {
8
- enumerable: true,
9
- get: function () {
10
- return m[k];
11
- },
12
- });
13
- }
14
- : function (o, m, k, k2) {
15
- if (k2 === undefined) k2 = k;
16
- o[k2] = m[k];
17
- });
18
- var __exportStar =
19
- (this && this.__exportStar) ||
20
- function (m, exports) {
21
- for (var p in m)
22
- if (p !== 'default' && !Object.prototype.hasOwnProperty.call(exports, p))
23
- __createBinding(exports, m, p);
24
- };
25
- var __importDefault =
26
- (this && this.__importDefault) ||
27
- function (mod) {
28
- return mod && mod.__esModule ? mod : { default: mod };
29
- };
30
- Object.defineProperty(exports, '__esModule', { value: true });
31
- exports.pyth = exports.PublicKey = exports.BN = void 0;
32
- const anchor_1 = require('@project-serum/anchor');
33
- Object.defineProperty(exports, 'BN', {
34
- enumerable: true,
35
- get: function () {
36
- return anchor_1.BN;
37
- },
38
- });
39
- const web3_js_1 = require('@solana/web3.js');
40
- Object.defineProperty(exports, 'PublicKey', {
41
- enumerable: true,
42
- get: function () {
43
- return web3_js_1.PublicKey;
44
- },
45
- });
46
- const client_1 = __importDefault(require('@pythnetwork/client'));
47
- exports.pyth = client_1.default;
48
- __exportStar(require('./tokenFaucet'), exports);
49
- __exportStar(require('./oracles/types'), exports);
50
- __exportStar(require('./oracles/pythClient'), exports);
51
- __exportStar(require('./oracles/switchboardClient'), exports);
52
- __exportStar(require('./types'), exports);
53
- __exportStar(require('./constants/markets'), exports);
54
- __exportStar(require('./accounts/fetch'), exports);
55
- __exportStar(
56
- require('./accounts/webSocketClearingHouseAccountSubscriber'),
57
- exports
58
- );
59
- __exportStar(require('./accounts/bulkAccountLoader'), exports);
60
- __exportStar(require('./accounts/bulkUserSubscription'), exports);
61
- __exportStar(
62
- require('./accounts/pollingClearingHouseAccountSubscriber'),
63
- exports
64
- );
65
- __exportStar(require('./accounts/pollingOracleSubscriber'), exports);
66
- __exportStar(require('./accounts/pollingTokenAccountSubscriber'), exports);
67
- __exportStar(require('./accounts/types'), exports);
68
- __exportStar(require('./addresses/pda'), exports);
69
- __exportStar(require('./admin'), exports);
70
- __exportStar(require('./clearingHouseUser'), exports);
71
- __exportStar(require('./clearingHouseUserConfig'), exports);
72
- __exportStar(require('./clearingHouse'), exports);
73
- __exportStar(require('./factory/oracleClient'), exports);
74
- __exportStar(require('./factory/bigNum'), exports);
75
- __exportStar(require('./events/types'), exports);
76
- __exportStar(require('./events/eventSubscriber'), exports);
77
- __exportStar(require('./math/auction'), exports);
78
- __exportStar(require('./math/conversion'), exports);
79
- __exportStar(require('./math/funding'), exports);
80
- __exportStar(require('./math/market'), exports);
81
- __exportStar(require('./math/position'), exports);
82
- __exportStar(require('./math/oracles'), exports);
83
- __exportStar(require('./math/amm'), exports);
84
- __exportStar(require('./math/trade'), exports);
85
- __exportStar(require('./math/orders'), exports);
86
- __exportStar(require('./math/repeg'), exports);
87
- __exportStar(require('./orders'), exports);
88
- __exportStar(require('./orderParams'), exports);
89
- __exportStar(require('./slot/SlotSubscriber'), exports);
90
- __exportStar(require('./wallet'), exports);
91
- __exportStar(require('./types'), exports);
92
- __exportStar(require('./math/utils'), exports);
93
- __exportStar(require('./config'), exports);
94
- __exportStar(require('./constants/numericConstants'), exports);
95
- __exportStar(require('./tx/retryTxSender'), exports);
96
- __exportStar(require('./util/computeUnits'), exports);
97
- __exportStar(require('./util/tps'), exports);
98
- __exportStar(require('./math/bankBalance'), exports);
99
- __exportStar(require('./constants/banks'), exports);
100
- __exportStar(require('./clearingHouseConfig'), exports);
@@ -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;