@drift-labs/sdk 0.2.0-master.25 → 0.2.0-master.26

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 (184) hide show
  1. package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts +13 -13
  2. package/lib/accounts/pollingClearingHouseAccountSubscriber.js +27 -27
  3. package/lib/accounts/types.d.ts +8 -9
  4. package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +14 -14
  5. package/lib/accounts/webSocketClearingHouseAccountSubscriber.js +35 -34
  6. package/lib/addresses/pda.d.ts +7 -6
  7. package/lib/addresses/pda.js +31 -27
  8. package/lib/admin.d.ts +9 -6
  9. package/lib/admin.js +83 -42
  10. package/lib/clearingHouse.d.ts +69 -42
  11. package/lib/clearingHouse.js +753 -277
  12. package/lib/clearingHouseConfig.d.ts +2 -2
  13. package/lib/clearingHouseUser.d.ts +16 -16
  14. package/lib/clearingHouseUser.js +139 -119
  15. package/lib/config.d.ts +7 -7
  16. package/lib/config.js +20 -20
  17. package/lib/constants/numericConstants.d.ts +12 -12
  18. package/lib/constants/numericConstants.js +13 -13
  19. package/lib/constants/{markets.d.ts → perpMarkets.d.ts} +5 -5
  20. package/{src/constants/markets.js → lib/constants/perpMarkets.js} +4 -4
  21. package/lib/constants/{banks.d.ts → spotMarkets.d.ts} +6 -6
  22. package/lib/constants/{banks.js → spotMarkets.js} +16 -16
  23. package/lib/events/types.d.ts +2 -1
  24. package/lib/events/types.js +1 -0
  25. package/lib/examples/makeTradeExample.js +7 -7
  26. package/lib/idl/clearing_house.json +1008 -279
  27. package/lib/index.d.ts +5 -3
  28. package/lib/index.js +5 -3
  29. package/lib/math/amm.d.ts +2 -2
  30. package/lib/math/amm.js +1 -1
  31. package/lib/math/funding.d.ts +6 -6
  32. package/lib/math/funding.js +2 -1
  33. package/lib/math/margin.d.ts +4 -4
  34. package/lib/math/margin.js +18 -11
  35. package/lib/math/market.d.ts +10 -9
  36. package/lib/math/market.js +29 -6
  37. package/lib/math/oracles.d.ts +2 -1
  38. package/lib/math/oracles.js +11 -1
  39. package/lib/math/orders.d.ts +5 -5
  40. package/lib/math/position.d.ts +13 -13
  41. package/lib/math/position.js +19 -19
  42. package/lib/math/spotBalance.d.ts +19 -0
  43. package/lib/math/spotBalance.js +176 -0
  44. package/lib/math/spotMarket.d.ts +4 -0
  45. package/lib/math/spotMarket.js +8 -0
  46. package/lib/math/spotPosition.d.ts +2 -0
  47. package/lib/math/spotPosition.js +8 -0
  48. package/lib/math/state.js +2 -2
  49. package/lib/math/trade.d.ts +4 -4
  50. package/lib/orderParams.d.ts +4 -4
  51. package/lib/orderParams.js +12 -4
  52. package/lib/serum/serumSubscriber.d.ts +23 -0
  53. package/lib/serum/serumSubscriber.js +41 -0
  54. package/lib/serum/types.d.ts +11 -0
  55. package/lib/serum/types.js +2 -0
  56. package/lib/tx/retryTxSender.d.ts +1 -1
  57. package/lib/tx/retryTxSender.js +4 -2
  58. package/lib/tx/types.d.ts +1 -1
  59. package/lib/types.d.ts +123 -33
  60. package/lib/types.js +31 -9
  61. package/my-script/.env +7 -0
  62. package/my-script/getUserStats.ts +106 -0
  63. package/my-script/multiConnections.ts +119 -0
  64. package/my-script/test-regex.ts +11 -0
  65. package/my-script/utils.ts +52 -0
  66. package/package.json +1 -1
  67. package/src/accounts/bulkAccountLoader.js +249 -0
  68. package/src/accounts/bulkUserStatsSubscription.js +75 -0
  69. package/src/accounts/bulkUserSubscription.js +75 -0
  70. package/src/accounts/fetch.js +92 -0
  71. package/src/accounts/pollingClearingHouseAccountSubscriber.js +465 -0
  72. package/src/accounts/pollingClearingHouseAccountSubscriber.ts +38 -38
  73. package/src/accounts/pollingOracleSubscriber.js +156 -0
  74. package/src/accounts/pollingTokenAccountSubscriber.js +141 -0
  75. package/src/accounts/pollingUserAccountSubscriber.js +208 -0
  76. package/src/accounts/pollingUserStatsAccountSubscriber.js +208 -0
  77. package/src/accounts/types.js +28 -0
  78. package/src/accounts/types.ts +11 -9
  79. package/src/accounts/utils.js +7 -0
  80. package/src/accounts/webSocketAccountSubscriber.js +138 -0
  81. package/src/accounts/webSocketClearingHouseAccountSubscriber.js +433 -0
  82. package/src/accounts/webSocketClearingHouseAccountSubscriber.ts +59 -52
  83. package/src/accounts/webSocketUserAccountSubscriber.js +113 -0
  84. package/src/accounts/webSocketUserStatsAccountSubsriber.js +113 -0
  85. package/src/addresses/pda.js +186 -0
  86. package/src/addresses/pda.ts +49 -44
  87. package/src/admin.js +1284 -0
  88. package/src/admin.ts +140 -47
  89. package/src/assert/assert.js +1 -1
  90. package/src/clearingHouse.js +3433 -0
  91. package/src/clearingHouse.ts +1083 -378
  92. package/src/clearingHouseConfig.js +2 -0
  93. package/src/clearingHouseConfig.ts +2 -2
  94. package/src/clearingHouseUser.js +874 -0
  95. package/src/clearingHouseUser.ts +232 -168
  96. package/src/clearingHouseUserConfig.js +2 -0
  97. package/src/clearingHouseUserStats.js +115 -0
  98. package/src/clearingHouseUserStatsConfig.js +2 -0
  99. package/src/config.js +80 -0
  100. package/src/config.ts +29 -29
  101. package/src/constants/numericConstants.js +18 -11
  102. package/src/constants/numericConstants.ts +17 -15
  103. package/{lib/constants/markets.js → src/constants/perpMarkets.js} +11 -11
  104. package/src/constants/{markets.ts → perpMarkets.ts} +5 -5
  105. package/src/constants/spotMarkets.js +51 -0
  106. package/src/constants/{banks.ts → spotMarkets.ts} +19 -19
  107. package/src/events/eventList.js +66 -23
  108. package/src/events/eventSubscriber.js +202 -0
  109. package/src/events/fetchLogs.js +117 -0
  110. package/src/events/pollingLogProvider.js +113 -0
  111. package/src/events/sort.js +41 -0
  112. package/src/events/txEventCache.js +22 -19
  113. package/src/events/types.js +25 -0
  114. package/src/events/types.ts +3 -0
  115. package/src/events/webSocketLogProvider.js +76 -0
  116. package/src/examples/makeTradeExample.ts +10 -8
  117. package/src/factory/bigNum.js +183 -180
  118. package/src/factory/oracleClient.js +9 -9
  119. package/src/idl/clearing_house.json +1008 -279
  120. package/src/index.js +75 -0
  121. package/src/index.ts +5 -3
  122. package/src/math/amm.js +422 -0
  123. package/src/math/amm.ts +6 -3
  124. package/src/math/auction.js +10 -10
  125. package/src/math/conversion.js +4 -3
  126. package/src/math/funding.js +223 -175
  127. package/src/math/funding.ts +7 -7
  128. package/src/math/insurance.js +27 -0
  129. package/src/math/margin.js +77 -0
  130. package/src/math/margin.ts +34 -23
  131. package/src/math/market.js +105 -0
  132. package/src/math/market.ts +71 -19
  133. package/src/math/oracles.js +40 -10
  134. package/src/math/oracles.ts +18 -1
  135. package/src/math/orders.js +153 -0
  136. package/src/math/orders.ts +5 -5
  137. package/src/math/position.js +172 -0
  138. package/src/math/position.ts +31 -31
  139. package/src/math/repeg.js +40 -40
  140. package/src/math/spotBalance.js +176 -0
  141. package/src/math/spotBalance.ts +290 -0
  142. package/src/math/spotMarket.js +8 -0
  143. package/src/math/spotMarket.ts +9 -0
  144. package/src/math/spotPosition.js +8 -0
  145. package/src/math/spotPosition.ts +6 -0
  146. package/src/math/state.ts +2 -2
  147. package/src/math/trade.js +81 -74
  148. package/src/math/trade.ts +4 -4
  149. package/src/math/utils.js +8 -7
  150. package/src/oracles/oracleClientCache.js +10 -9
  151. package/src/oracles/pythClient.js +52 -17
  152. package/src/oracles/quoteAssetOracleClient.js +44 -13
  153. package/src/oracles/switchboardClient.js +69 -37
  154. package/src/oracles/types.js +1 -1
  155. package/src/orderParams.js +14 -6
  156. package/src/orderParams.ts +16 -8
  157. package/src/serum/serumSubscriber.js +102 -0
  158. package/src/serum/serumSubscriber.ts +80 -0
  159. package/src/serum/types.js +2 -0
  160. package/src/serum/types.ts +13 -0
  161. package/src/slot/SlotSubscriber.js +67 -20
  162. package/src/token/index.js +4 -4
  163. package/src/tokenFaucet.js +288 -154
  164. package/src/tx/retryTxSender.js +280 -0
  165. package/src/tx/retryTxSender.ts +5 -2
  166. package/src/tx/types.js +1 -1
  167. package/src/tx/types.ts +2 -1
  168. package/src/tx/utils.js +7 -6
  169. package/src/types.js +216 -0
  170. package/src/types.ts +110 -33
  171. package/src/userName.js +5 -5
  172. package/src/util/computeUnits.js +46 -11
  173. package/src/util/promiseTimeout.js +5 -5
  174. package/src/util/tps.js +46 -12
  175. package/src/wallet.js +55 -18
  176. package/lib/math/bankBalance.d.ts +0 -15
  177. package/lib/math/bankBalance.js +0 -150
  178. package/src/addresses/marketAddresses.js +0 -26
  179. package/src/constants/banks.js +0 -42
  180. package/src/examples/makeTradeExample.js +0 -80
  181. package/src/math/bankBalance.ts +0 -258
  182. package/src/math/state.js +0 -15
  183. package/src/math/utils.js.map +0 -1
  184. package/src/util/getTokenAddress.js +0 -9
@@ -1,150 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.calculateWithdrawLimit = exports.calculateInterestAccumulated = exports.calculateLiabilityWeight = exports.calculateAssetWeight = 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
- const margin_1 = require("./margin");
8
- function getBalance(tokenAmount, bank, balanceType) {
9
- const precisionIncrease = numericConstants_1.TEN.pow(new anchor_1.BN(16 - bank.decimals));
10
- const cumulativeInterest = (0, types_1.isVariant)(balanceType, 'deposit')
11
- ? bank.cumulativeDepositInterest
12
- : bank.cumulativeBorrowInterest;
13
- let balance = tokenAmount.mul(precisionIncrease).div(cumulativeInterest);
14
- if (!balance.eq(numericConstants_1.ZERO) && (0, types_1.isVariant)(balanceType, 'borrow')) {
15
- balance = balance.add(numericConstants_1.ONE);
16
- }
17
- return balance;
18
- }
19
- exports.getBalance = getBalance;
20
- function getTokenAmount(balanceAmount, bank, balanceType) {
21
- const precisionDecrease = numericConstants_1.TEN.pow(new anchor_1.BN(16 - bank.decimals));
22
- const cumulativeInterest = (0, types_1.isVariant)(balanceType, 'deposit')
23
- ? bank.cumulativeDepositInterest
24
- : bank.cumulativeBorrowInterest;
25
- return balanceAmount.mul(cumulativeInterest).div(precisionDecrease);
26
- }
27
- exports.getTokenAmount = getTokenAmount;
28
- function calculateAssetWeight(balanceAmount, bank, marginCategory) {
29
- const sizePrecision = numericConstants_1.TEN.pow(new anchor_1.BN(bank.decimals));
30
- let sizeInAmmReservePrecision;
31
- if (sizePrecision.gt(numericConstants_1.AMM_RESERVE_PRECISION)) {
32
- sizeInAmmReservePrecision = balanceAmount.div(sizePrecision.div(numericConstants_1.AMM_RESERVE_PRECISION));
33
- }
34
- else {
35
- sizeInAmmReservePrecision = balanceAmount
36
- .mul(numericConstants_1.AMM_RESERVE_PRECISION)
37
- .div(sizePrecision);
38
- }
39
- let assetWeight;
40
- switch (marginCategory) {
41
- case 'Initial':
42
- assetWeight = (0, margin_1.calculateSizeDiscountAssetWeight)(sizeInAmmReservePrecision, bank.imfFactor, bank.initialAssetWeight);
43
- break;
44
- case 'Maintenance':
45
- assetWeight = (0, margin_1.calculateSizeDiscountAssetWeight)(sizeInAmmReservePrecision, bank.imfFactor, bank.maintenanceAssetWeight);
46
- break;
47
- default:
48
- assetWeight = bank.initialAssetWeight;
49
- break;
50
- }
51
- return assetWeight;
52
- }
53
- exports.calculateAssetWeight = calculateAssetWeight;
54
- function calculateLiabilityWeight(balanceAmount, bank, marginCategory) {
55
- const sizePrecision = numericConstants_1.TEN.pow(new anchor_1.BN(bank.decimals));
56
- let sizeInAmmReservePrecision;
57
- if (sizePrecision.gt(numericConstants_1.AMM_RESERVE_PRECISION)) {
58
- sizeInAmmReservePrecision = balanceAmount.div(sizePrecision.div(numericConstants_1.AMM_RESERVE_PRECISION));
59
- }
60
- else {
61
- sizeInAmmReservePrecision = balanceAmount
62
- .mul(numericConstants_1.AMM_RESERVE_PRECISION)
63
- .div(sizePrecision);
64
- }
65
- let assetWeight;
66
- switch (marginCategory) {
67
- case 'Initial':
68
- assetWeight = (0, margin_1.calculateSizePremiumLiabilityWeight)(sizeInAmmReservePrecision, bank.imfFactor, bank.initialLiabilityWeight, numericConstants_1.BANK_WEIGHT_PRECISION);
69
- break;
70
- case 'Maintenance':
71
- assetWeight = (0, margin_1.calculateSizePremiumLiabilityWeight)(sizeInAmmReservePrecision, bank.imfFactor, bank.maintenanceLiabilityWeight, numericConstants_1.BANK_WEIGHT_PRECISION);
72
- break;
73
- default:
74
- assetWeight = bank.initialLiabilityWeight;
75
- break;
76
- }
77
- return assetWeight;
78
- }
79
- exports.calculateLiabilityWeight = calculateLiabilityWeight;
80
- function calculateInterestAccumulated(bank, now) {
81
- const token_deposit_amount = getTokenAmount(bank.depositBalance, bank, types_1.BankBalanceType.DEPOSIT);
82
- const token_borrow_amount = getTokenAmount(bank.borrowBalance, bank, types_1.BankBalanceType.BORROW);
83
- let utilization;
84
- if (token_borrow_amount.eq(numericConstants_1.ZERO) && token_deposit_amount.eq(numericConstants_1.ZERO)) {
85
- utilization = numericConstants_1.ZERO;
86
- }
87
- else if (token_deposit_amount.eq(numericConstants_1.ZERO)) {
88
- utilization = numericConstants_1.BANK_UTILIZATION_PRECISION;
89
- }
90
- else {
91
- utilization = token_borrow_amount
92
- .mul(numericConstants_1.BANK_UTILIZATION_PRECISION)
93
- .div(token_deposit_amount);
94
- }
95
- let interest_rate;
96
- if (utilization.gt(bank.optimalUtilization)) {
97
- const surplusUtilization = utilization.sub(bank.optimalUtilization);
98
- const borrowRateSlope = bank.maxBorrowRate
99
- .sub(bank.optimalBorrowRate)
100
- .mul(numericConstants_1.BANK_UTILIZATION_PRECISION)
101
- .div(numericConstants_1.BANK_UTILIZATION_PRECISION.sub(bank.optimalUtilization));
102
- interest_rate = bank.optimalBorrowRate.add(surplusUtilization.mul(borrowRateSlope).div(numericConstants_1.BANK_UTILIZATION_PRECISION));
103
- }
104
- else {
105
- const borrowRateSlope = bank.optimalBorrowRate
106
- .mul(numericConstants_1.BANK_UTILIZATION_PRECISION)
107
- .div(numericConstants_1.BANK_UTILIZATION_PRECISION.sub(bank.optimalUtilization));
108
- interest_rate = utilization
109
- .mul(borrowRateSlope)
110
- .div(numericConstants_1.BANK_UTILIZATION_PRECISION);
111
- }
112
- const timeSinceLastUpdate = now.sub(bank.lastInterestTs);
113
- const modifiedBorrowRate = interest_rate.mul(timeSinceLastUpdate);
114
- const modifiedDepositRate = modifiedBorrowRate
115
- .mul(utilization)
116
- .div(numericConstants_1.BANK_UTILIZATION_PRECISION);
117
- const borrowInterest = bank.cumulativeBorrowInterest
118
- .mul(modifiedBorrowRate)
119
- .div(numericConstants_1.ONE_YEAR)
120
- .div(numericConstants_1.BANK_INTEREST_PRECISION)
121
- .add(numericConstants_1.ONE);
122
- const depositInterest = bank.cumulativeDepositInterest
123
- .mul(modifiedDepositRate)
124
- .div(numericConstants_1.ONE_YEAR)
125
- .div(numericConstants_1.BANK_INTEREST_PRECISION);
126
- return { borrowInterest, depositInterest };
127
- }
128
- exports.calculateInterestAccumulated = calculateInterestAccumulated;
129
- function calculateWithdrawLimit(bank, now) {
130
- const bankDepositTokenAmount = getTokenAmount(bank.depositBalance, bank, types_1.BankBalanceType.DEPOSIT);
131
- const bankBorrowTokenAmount = getTokenAmount(bank.borrowBalance, bank, types_1.BankBalanceType.BORROW);
132
- const twentyFourHours = new anchor_1.BN(60 * 60 * 24);
133
- const sinceLast = now.sub(bank.lastTwapTs);
134
- const sinceStart = anchor_1.BN.max(numericConstants_1.ZERO, twentyFourHours.sub(sinceLast));
135
- const borrowTokenTwapLive = bank.borrowTokenTwap
136
- .mul(sinceStart)
137
- .add(bankBorrowTokenAmount.mul(sinceLast))
138
- .div(sinceLast.add(sinceLast));
139
- const depositTokenTwapLive = bank.depositTokenTwap
140
- .mul(sinceStart)
141
- .add(bankDepositTokenAmount.mul(sinceLast))
142
- .div(sinceLast.add(sinceLast));
143
- const maxBorrowTokens = anchor_1.BN.min(anchor_1.BN.max(bankDepositTokenAmount.div(new anchor_1.BN(6)), borrowTokenTwapLive.add(borrowTokenTwapLive.div(new anchor_1.BN(5)))), bankDepositTokenAmount.sub(bankDepositTokenAmount.div(new anchor_1.BN(10)))); // between ~15-90% utilization with friction on twap
144
- const minDepositTokens = depositTokenTwapLive.sub(anchor_1.BN.min(anchor_1.BN.max(depositTokenTwapLive.div(new anchor_1.BN(5)), bank.withdrawGuardThreshold), depositTokenTwapLive));
145
- return {
146
- borrowLimit: maxBorrowTokens.sub(bankBorrowTokenAmount),
147
- withdrawLimit: bankDepositTokenAmount.sub(minDepositTokens),
148
- };
149
- }
150
- exports.calculateWithdrawLimit = calculateWithdrawLimit;
@@ -1,26 +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.getMarketAddress = void 0;
13
- const pda_1 = require("./pda");
14
- const CACHE = new Map();
15
- function getMarketAddress(programId, marketIndex) {
16
- return __awaiter(this, void 0, void 0, function* () {
17
- const cacheKey = `${programId.toString()}-${marketIndex.toString()}`;
18
- if (CACHE.has(cacheKey)) {
19
- return CACHE.get(cacheKey);
20
- }
21
- const publicKey = yield pda_1.getMarketPublicKey(programId, marketIndex);
22
- CACHE.set(cacheKey, publicKey);
23
- return publicKey;
24
- });
25
- }
26
- exports.getMarketAddress = getMarketAddress;
@@ -1,42 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Banks = exports.MainnetBanks = exports.DevnetBanks = exports.WRAPPED_SOL_MINT = void 0;
4
- const web3_js_1 = require("@solana/web3.js");
5
- const __1 = require("../");
6
- exports.WRAPPED_SOL_MINT = new web3_js_1.PublicKey('So11111111111111111111111111111111111111112');
7
- exports.DevnetBanks = [
8
- {
9
- symbol: 'USDC',
10
- bankIndex: new __1.BN(0),
11
- oracle: web3_js_1.PublicKey.default,
12
- oracleSource: __1.OracleSource.QUOTE_ASSET,
13
- mint: new web3_js_1.PublicKey('8zGuJQqwhZafTah7Uc7Z4tXRnguqkn5KLFAP8oV6PHe2'),
14
- },
15
- {
16
- symbol: 'SOL',
17
- bankIndex: new __1.BN(1),
18
- oracle: new web3_js_1.PublicKey('J83w4HKfqxwcq3BEMMkPFSppX3gqekLyLJBexebFVkix'),
19
- oracleSource: __1.OracleSource.PYTH,
20
- mint: new web3_js_1.PublicKey(exports.WRAPPED_SOL_MINT),
21
- },
22
- {
23
- symbol: 'BTC',
24
- bankIndex: new __1.BN(2),
25
- oracle: new web3_js_1.PublicKey('HovQMDrbAgAYPCmHVSrezcSmkMtXSSUsLDFANExrZh2J'),
26
- oracleSource: __1.OracleSource.PYTH,
27
- mint: new web3_js_1.PublicKey('3BZPwbcqB5kKScF3TEXxwNfx5ipV13kbRVDvfVp5c6fv'),
28
- },
29
- ];
30
- exports.MainnetBanks = [
31
- {
32
- symbol: 'USDC',
33
- bankIndex: new __1.BN(0),
34
- oracle: web3_js_1.PublicKey.default,
35
- oracleSource: __1.OracleSource.QUOTE_ASSET,
36
- mint: new web3_js_1.PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'),
37
- },
38
- ];
39
- exports.Banks = {
40
- devnet: exports.DevnetBanks,
41
- 'mainnet-beta': exports.MainnetBanks,
42
- };
@@ -1,80 +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.getTokenAddress = void 0;
13
- const anchor_1 = require("@project-serum/anchor");
14
- const __1 = require("..");
15
- const spl_token_1 = require("@solana/spl-token");
16
- const web3_js_1 = require("@solana/web3.js");
17
- const __2 = require("..");
18
- const banks_1 = require("../constants/banks");
19
- const getTokenAddress = (mintAddress, userPubKey) => {
20
- return spl_token_1.Token.getAssociatedTokenAddress(new web3_js_1.PublicKey(`ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL`), spl_token_1.TOKEN_PROGRAM_ID, new web3_js_1.PublicKey(mintAddress), new web3_js_1.PublicKey(userPubKey));
21
- };
22
- exports.getTokenAddress = getTokenAddress;
23
- const main = () => __awaiter(void 0, void 0, void 0, function* () {
24
- // Initialize Drift SDK
25
- const sdkConfig = __2.initialize({ env: 'devnet' });
26
- // Set up the Wallet and Provider
27
- const privateKey = process.env.BOT_PRIVATE_KEY; // stored as an array string
28
- const keypair = web3_js_1.Keypair.fromSecretKey(Uint8Array.from(JSON.parse(privateKey)));
29
- const wallet = new __1.Wallet(keypair);
30
- // Set up the Connection
31
- const rpcAddress = process.env.RPC_ADDRESS; // can use: https://api.devnet.solana.com for devnet; https://api.mainnet-beta.solana.com for mainnet;
32
- const connection = new web3_js_1.Connection(rpcAddress);
33
- // Set up the Provider
34
- const provider = new anchor_1.AnchorProvider(connection, wallet, anchor_1.AnchorProvider.defaultOptions());
35
- // Check SOL Balance
36
- const lamportsBalance = yield connection.getBalance(wallet.publicKey);
37
- console.log('SOL balance:', lamportsBalance / Math.pow(10, 9));
38
- // Misc. other things to set up
39
- const usdcTokenAddress = yield exports.getTokenAddress(sdkConfig.USDC_MINT_ADDRESS, wallet.publicKey.toString());
40
- // Set up the Drift Clearing House
41
- const clearingHousePublicKey = new web3_js_1.PublicKey(sdkConfig.CLEARING_HOUSE_PROGRAM_ID);
42
- const clearingHouse = new __2.ClearingHouse({
43
- connection,
44
- wallet: provider.wallet,
45
- programID: clearingHousePublicKey,
46
- });
47
- yield clearingHouse.subscribe();
48
- // Set up Clearing House user client
49
- const user = new __2.ClearingHouseUser({
50
- clearingHouse,
51
- userAccountPublicKey: yield clearingHouse.getUserAccountPublicKey(),
52
- });
53
- //// Check if clearing house account exists for the current wallet
54
- const userAccountExists = yield user.exists();
55
- if (!userAccountExists) {
56
- //// Create a Clearing House account by Depositing some USDC ($10,000 in this case)
57
- const depositAmount = new anchor_1.BN(10000).mul(__2.QUOTE_PRECISION);
58
- yield clearingHouse.initializeUserAccountAndDepositCollateral(depositAmount, yield exports.getTokenAddress(usdcTokenAddress.toString(), wallet.publicKey.toString()), banks_1.Banks['devnet'][0].bankIndex);
59
- }
60
- yield user.subscribe();
61
- // Get current price
62
- const solMarketInfo = sdkConfig.MARKETS.find((market) => market.baseAssetSymbol === 'SOL');
63
- const currentMarketPrice = __2.calculateMarkPrice(clearingHouse.getMarketAccount(solMarketInfo.marketIndex), undefined);
64
- const formattedPrice = __2.convertToNumber(currentMarketPrice, __2.MARK_PRICE_PRECISION);
65
- console.log(`Current Market Price is $${formattedPrice}`);
66
- // Estimate the slippage for a $5000 LONG trade
67
- const solMarketAccount = clearingHouse.getMarketAccount(solMarketInfo.marketIndex);
68
- const longAmount = new anchor_1.BN(5000).mul(__2.QUOTE_PRECISION);
69
- const slippage = __2.convertToNumber(__2.calculateTradeSlippage(__2.PositionDirection.LONG, longAmount, solMarketAccount, 'quote', undefined)[0], __2.MARK_PRICE_PRECISION);
70
- console.log(`Slippage for a $5000 LONG on the SOL market would be $${slippage}`);
71
- // Make a $5000 LONG trade
72
- yield clearingHouse.openPosition(__2.PositionDirection.LONG, longAmount, solMarketInfo.marketIndex);
73
- console.log(`LONGED $5000 SOL`);
74
- // Reduce the position by $2000
75
- const reduceAmount = new anchor_1.BN(2000).mul(__2.QUOTE_PRECISION);
76
- yield clearingHouse.openPosition(__2.PositionDirection.SHORT, reduceAmount, solMarketInfo.marketIndex);
77
- // Close the rest of the position
78
- yield clearingHouse.closePosition(solMarketInfo.marketIndex);
79
- });
80
- main();
@@ -1,258 +0,0 @@
1
- import {
2
- BankAccount,
3
- BankBalanceType,
4
- isVariant,
5
- MarginCategory,
6
- } from '../types';
7
- import { BN } from '@project-serum/anchor';
8
- import {
9
- BANK_UTILIZATION_PRECISION,
10
- ONE,
11
- TEN,
12
- ZERO,
13
- BANK_INTEREST_PRECISION,
14
- BANK_WEIGHT_PRECISION,
15
- ONE_YEAR,
16
- AMM_RESERVE_PRECISION,
17
- } from '../constants/numericConstants';
18
- import {
19
- calculateSizeDiscountAssetWeight,
20
- calculateSizePremiumLiabilityWeight,
21
- } from './margin';
22
-
23
- export function getBalance(
24
- tokenAmount: BN,
25
- bank: BankAccount,
26
- balanceType: BankBalanceType
27
- ): BN {
28
- const precisionIncrease = TEN.pow(new BN(16 - bank.decimals));
29
-
30
- const cumulativeInterest = isVariant(balanceType, 'deposit')
31
- ? bank.cumulativeDepositInterest
32
- : bank.cumulativeBorrowInterest;
33
-
34
- let balance = tokenAmount.mul(precisionIncrease).div(cumulativeInterest);
35
-
36
- if (!balance.eq(ZERO) && isVariant(balanceType, 'borrow')) {
37
- balance = balance.add(ONE);
38
- }
39
-
40
- return balance;
41
- }
42
-
43
- export function getTokenAmount(
44
- balanceAmount: BN,
45
- bank: BankAccount,
46
- balanceType: BankBalanceType
47
- ): BN {
48
- const precisionDecrease = TEN.pow(new BN(16 - bank.decimals));
49
-
50
- const cumulativeInterest = isVariant(balanceType, 'deposit')
51
- ? bank.cumulativeDepositInterest
52
- : bank.cumulativeBorrowInterest;
53
-
54
- return balanceAmount.mul(cumulativeInterest).div(precisionDecrease);
55
- }
56
-
57
- export function calculateAssetWeight(
58
- balanceAmount: BN,
59
- bank: BankAccount,
60
- marginCategory: MarginCategory
61
- ): BN {
62
- const sizePrecision = TEN.pow(new BN(bank.decimals));
63
- let sizeInAmmReservePrecision;
64
- if (sizePrecision.gt(AMM_RESERVE_PRECISION)) {
65
- sizeInAmmReservePrecision = balanceAmount.div(
66
- sizePrecision.div(AMM_RESERVE_PRECISION)
67
- );
68
- } else {
69
- sizeInAmmReservePrecision = balanceAmount
70
- .mul(AMM_RESERVE_PRECISION)
71
- .div(sizePrecision);
72
- }
73
-
74
- let assetWeight;
75
-
76
- switch (marginCategory) {
77
- case 'Initial':
78
- assetWeight = calculateSizeDiscountAssetWeight(
79
- sizeInAmmReservePrecision,
80
- bank.imfFactor,
81
- bank.initialAssetWeight
82
- );
83
- break;
84
- case 'Maintenance':
85
- assetWeight = calculateSizeDiscountAssetWeight(
86
- sizeInAmmReservePrecision,
87
- bank.imfFactor,
88
- bank.maintenanceAssetWeight
89
- );
90
- break;
91
- default:
92
- assetWeight = bank.initialAssetWeight;
93
- break;
94
- }
95
-
96
- return assetWeight;
97
- }
98
-
99
- export function calculateLiabilityWeight(
100
- balanceAmount: BN,
101
- bank: BankAccount,
102
- marginCategory: MarginCategory
103
- ): BN {
104
- const sizePrecision = TEN.pow(new BN(bank.decimals));
105
- let sizeInAmmReservePrecision;
106
- if (sizePrecision.gt(AMM_RESERVE_PRECISION)) {
107
- sizeInAmmReservePrecision = balanceAmount.div(
108
- sizePrecision.div(AMM_RESERVE_PRECISION)
109
- );
110
- } else {
111
- sizeInAmmReservePrecision = balanceAmount
112
- .mul(AMM_RESERVE_PRECISION)
113
- .div(sizePrecision);
114
- }
115
-
116
- let assetWeight;
117
-
118
- switch (marginCategory) {
119
- case 'Initial':
120
- assetWeight = calculateSizePremiumLiabilityWeight(
121
- sizeInAmmReservePrecision,
122
- bank.imfFactor,
123
- bank.initialLiabilityWeight,
124
- BANK_WEIGHT_PRECISION
125
- );
126
- break;
127
- case 'Maintenance':
128
- assetWeight = calculateSizePremiumLiabilityWeight(
129
- sizeInAmmReservePrecision,
130
- bank.imfFactor,
131
- bank.maintenanceLiabilityWeight,
132
- BANK_WEIGHT_PRECISION
133
- );
134
- break;
135
- default:
136
- assetWeight = bank.initialLiabilityWeight;
137
- break;
138
- }
139
-
140
- return assetWeight;
141
- }
142
-
143
- export function calculateInterestAccumulated(
144
- bank: BankAccount,
145
- now: BN
146
- ): { borrowInterest: BN; depositInterest: BN } {
147
- const token_deposit_amount = getTokenAmount(
148
- bank.depositBalance,
149
- bank,
150
- BankBalanceType.DEPOSIT
151
- );
152
- const token_borrow_amount = getTokenAmount(
153
- bank.borrowBalance,
154
- bank,
155
- BankBalanceType.BORROW
156
- );
157
-
158
- let utilization: BN;
159
- if (token_borrow_amount.eq(ZERO) && token_deposit_amount.eq(ZERO)) {
160
- utilization = ZERO;
161
- } else if (token_deposit_amount.eq(ZERO)) {
162
- utilization = BANK_UTILIZATION_PRECISION;
163
- } else {
164
- utilization = token_borrow_amount
165
- .mul(BANK_UTILIZATION_PRECISION)
166
- .div(token_deposit_amount);
167
- }
168
-
169
- let interest_rate: BN;
170
- if (utilization.gt(bank.optimalUtilization)) {
171
- const surplusUtilization = utilization.sub(bank.optimalUtilization);
172
- const borrowRateSlope = bank.maxBorrowRate
173
- .sub(bank.optimalBorrowRate)
174
- .mul(BANK_UTILIZATION_PRECISION)
175
- .div(BANK_UTILIZATION_PRECISION.sub(bank.optimalUtilization));
176
-
177
- interest_rate = bank.optimalBorrowRate.add(
178
- surplusUtilization.mul(borrowRateSlope).div(BANK_UTILIZATION_PRECISION)
179
- );
180
- } else {
181
- const borrowRateSlope = bank.optimalBorrowRate
182
- .mul(BANK_UTILIZATION_PRECISION)
183
- .div(BANK_UTILIZATION_PRECISION.sub(bank.optimalUtilization));
184
-
185
- interest_rate = utilization
186
- .mul(borrowRateSlope)
187
- .div(BANK_UTILIZATION_PRECISION);
188
- }
189
-
190
- const timeSinceLastUpdate = now.sub(bank.lastInterestTs);
191
-
192
- const modifiedBorrowRate = interest_rate.mul(timeSinceLastUpdate);
193
-
194
- const modifiedDepositRate = modifiedBorrowRate
195
- .mul(utilization)
196
- .div(BANK_UTILIZATION_PRECISION);
197
-
198
- const borrowInterest = bank.cumulativeBorrowInterest
199
- .mul(modifiedBorrowRate)
200
- .div(ONE_YEAR)
201
- .div(BANK_INTEREST_PRECISION)
202
- .add(ONE);
203
- const depositInterest = bank.cumulativeDepositInterest
204
- .mul(modifiedDepositRate)
205
- .div(ONE_YEAR)
206
- .div(BANK_INTEREST_PRECISION);
207
-
208
- return { borrowInterest, depositInterest };
209
- }
210
-
211
- export function calculateWithdrawLimit(
212
- bank: BankAccount,
213
- now: BN
214
- ): { borrowLimit: BN; withdrawLimit: BN } {
215
- const bankDepositTokenAmount = getTokenAmount(
216
- bank.depositBalance,
217
- bank,
218
- BankBalanceType.DEPOSIT
219
- );
220
- const bankBorrowTokenAmount = getTokenAmount(
221
- bank.borrowBalance,
222
- bank,
223
- BankBalanceType.BORROW
224
- );
225
-
226
- const twentyFourHours = new BN(60 * 60 * 24);
227
- const sinceLast = now.sub(bank.lastTwapTs);
228
- const sinceStart = BN.max(ZERO, twentyFourHours.sub(sinceLast));
229
- const borrowTokenTwapLive = bank.borrowTokenTwap
230
- .mul(sinceStart)
231
- .add(bankBorrowTokenAmount.mul(sinceLast))
232
- .div(sinceLast.add(sinceLast));
233
-
234
- const depositTokenTwapLive = bank.depositTokenTwap
235
- .mul(sinceStart)
236
- .add(bankDepositTokenAmount.mul(sinceLast))
237
- .div(sinceLast.add(sinceLast));
238
-
239
- const maxBorrowTokens = BN.min(
240
- BN.max(
241
- bankDepositTokenAmount.div(new BN(6)),
242
- borrowTokenTwapLive.add(borrowTokenTwapLive.div(new BN(5)))
243
- ),
244
- bankDepositTokenAmount.sub(bankDepositTokenAmount.div(new BN(10)))
245
- ); // between ~15-90% utilization with friction on twap
246
-
247
- const minDepositTokens = depositTokenTwapLive.sub(
248
- BN.min(
249
- BN.max(depositTokenTwapLive.div(new BN(5)), bank.withdrawGuardThreshold),
250
- depositTokenTwapLive
251
- )
252
- );
253
-
254
- return {
255
- borrowLimit: maxBorrowTokens.sub(bankBorrowTokenAmount),
256
- withdrawLimit: bankDepositTokenAmount.sub(minDepositTokens),
257
- };
258
- }
package/src/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;
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["utils.ts"],"names":[],"mappings":";;;AAAA,2BAAyB;AAElB,MAAM,YAAY,GAAG,CAAC,CAAC,EAAE,SAAS,GAAG,IAAI,MAAE,CAAC,CAAC,CAAC,EAAE,EAAE;IACxD,mCAAmC;IACnC,IAAI,CAAC,GAAG,CAAC,CAAC;IAEV,8CAA8C;IAC9C,IAAI,IAAI,CAAC;IAET,oCAAoC;IACpC,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,MAAM,GAAG,GAAG,IAAI,MAAE,CAAC,CAAC,CAAC,CAAC;IAEtB,6DAA6D;IAC7D,OAAO,KAAK,GAAG,MAAM,CAAC,gBAAgB,EAAE;QACvC,KAAK,EAAE,CAAC;QAER,0BAA0B;QAC1B,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAEhC,sBAAsB;QACtB,IAAI,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,SAAS,CAAC;YAAE,MAAM;QAE5C,cAAc;QACd,CAAC,GAAG,IAAI,CAAC;KACT;IAED,OAAO,IAAI,CAAC;AACb,CAAC,CAAC;AA1BW,QAAA,YAAY,gBA0BvB"}
@@ -1,9 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getTokenAddress = void 0;
4
- const spl_token_1 = require("@solana/spl-token");
5
- const web3_js_1 = require("@solana/web3.js");
6
- const getTokenAddress = (mintAddress, userPubKey) => {
7
- return spl_token_1.Token.getAssociatedTokenAddress(spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID, spl_token_1.TOKEN_PROGRAM_ID, new web3_js_1.PublicKey(mintAddress), new web3_js_1.PublicKey(userPubKey));
8
- };
9
- exports.getTokenAddress = getTokenAddress;