@drift-labs/sdk 0.2.0-master.1 → 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 (142) hide show
  1. package/lib/accounts/types.d.ts +1 -0
  2. package/lib/admin.d.ts +8 -5
  3. package/lib/admin.js +43 -11
  4. package/lib/clearingHouse.d.ts +35 -20
  5. package/lib/clearingHouse.js +497 -154
  6. package/lib/clearingHouseUser.d.ts +12 -17
  7. package/lib/clearingHouseUser.js +97 -88
  8. package/lib/config.js +1 -1
  9. package/lib/constants/banks.d.ts +2 -2
  10. package/lib/constants/banks.js +12 -4
  11. package/lib/constants/numericConstants.d.ts +4 -0
  12. package/lib/constants/numericConstants.js +5 -1
  13. package/lib/events/eventList.js +3 -0
  14. package/lib/events/types.d.ts +2 -1
  15. package/lib/factory/bigNum.d.ts +9 -2
  16. package/lib/factory/bigNum.js +50 -16
  17. package/lib/idl/clearing_house.json +858 -177
  18. package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  19. package/lib/index.d.ts +4 -2
  20. package/lib/index.js +8 -2
  21. package/lib/math/amm.d.ts +6 -1
  22. package/lib/math/amm.js +124 -41
  23. package/lib/math/auction.js +4 -1
  24. package/lib/math/bankBalance.d.ts +3 -1
  25. package/lib/math/bankBalance.js +54 -1
  26. package/lib/math/margin.d.ts +11 -0
  27. package/lib/math/margin.js +72 -0
  28. package/lib/math/market.d.ts +4 -1
  29. package/lib/math/market.js +35 -1
  30. package/lib/math/orders.d.ts +2 -2
  31. package/lib/math/orders.js +18 -11
  32. package/lib/math/position.d.ts +8 -0
  33. package/lib/math/position.js +44 -12
  34. package/lib/math/repeg.js +1 -1
  35. package/lib/math/trade.d.ts +1 -1
  36. package/lib/math/trade.js +7 -10
  37. package/lib/orderParams.d.ts +14 -5
  38. package/lib/orderParams.js +8 -96
  39. package/lib/orders.d.ts +2 -4
  40. package/lib/orders.js +7 -161
  41. package/lib/slot/SlotSubscriber.d.ts +7 -0
  42. package/lib/slot/SlotSubscriber.js +3 -0
  43. package/lib/{mockUSDCFaucet.d.ts → tokenFaucet.d.ts} +8 -5
  44. package/lib/{mockUSDCFaucet.js → tokenFaucet.js} +63 -51
  45. package/lib/tx/retryTxSender.js +9 -2
  46. package/lib/tx/utils.js +1 -1
  47. package/lib/types.d.ts +159 -15
  48. package/lib/types.js +59 -1
  49. package/lib/util/computeUnits.js +1 -1
  50. package/lib/util/getTokenAddress.d.ts +2 -0
  51. package/lib/util/getTokenAddress.js +9 -0
  52. package/package.json +3 -3
  53. package/src/accounts/bulkAccountLoader.js +197 -0
  54. package/src/accounts/bulkUserSubscription.js +33 -0
  55. package/src/accounts/pollingClearingHouseAccountSubscriber.js +311 -0
  56. package/src/accounts/pollingOracleSubscriber.js +93 -0
  57. package/src/accounts/pollingTokenAccountSubscriber.js +90 -0
  58. package/src/accounts/pollingUserAccountSubscriber.js +132 -0
  59. package/src/accounts/types.js +10 -0
  60. package/src/accounts/utils.js +7 -0
  61. package/src/accounts/webSocketAccountSubscriber.js +93 -0
  62. package/src/accounts/webSocketClearingHouseAccountSubscriber.js +233 -0
  63. package/src/accounts/webSocketUserAccountSubscriber.js +62 -0
  64. package/src/addresses/marketAddresses.js +26 -0
  65. package/src/admin.ts +66 -14
  66. package/src/assert/assert.js +9 -0
  67. package/src/clearingHouse.ts +836 -254
  68. package/src/clearingHouseConfig.js +2 -0
  69. package/src/clearingHouseUser.ts +219 -121
  70. package/src/clearingHouseUserConfig.js +2 -0
  71. package/src/config.ts +1 -1
  72. package/src/constants/banks.js +42 -0
  73. package/src/constants/banks.ts +14 -4
  74. package/src/constants/markets.js +42 -0
  75. package/src/constants/numericConstants.js +41 -0
  76. package/src/constants/numericConstants.ts +5 -0
  77. package/src/events/eventList.js +77 -0
  78. package/src/events/eventList.ts +3 -0
  79. package/src/events/eventSubscriber.js +139 -0
  80. package/src/events/fetchLogs.js +50 -0
  81. package/src/events/pollingLogProvider.js +64 -0
  82. package/src/events/sort.js +44 -0
  83. package/src/events/txEventCache.js +71 -0
  84. package/src/events/types.js +20 -0
  85. package/src/events/types.ts +2 -0
  86. package/src/events/webSocketLogProvider.js +41 -0
  87. package/src/examples/makeTradeExample.js +80 -0
  88. package/src/factory/bigNum.js +390 -0
  89. package/src/factory/bigNum.ts +65 -18
  90. package/src/factory/oracleClient.js +20 -0
  91. package/src/idl/clearing_house.json +858 -177
  92. package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
  93. package/src/index.js +69 -0
  94. package/src/index.ts +4 -2
  95. package/src/math/amm.js +369 -0
  96. package/src/math/amm.ts +207 -52
  97. package/src/math/auction.js +42 -0
  98. package/src/math/auction.ts +5 -1
  99. package/src/math/bankBalance.ts +98 -1
  100. package/src/math/conversion.js +11 -0
  101. package/src/math/funding.js +248 -0
  102. package/src/math/margin.ts +124 -0
  103. package/src/math/market.ts +66 -1
  104. package/src/math/oracles.js +26 -0
  105. package/src/math/orders.ts +17 -13
  106. package/src/math/position.ts +63 -9
  107. package/src/math/repeg.js +128 -0
  108. package/src/math/repeg.ts +2 -1
  109. package/src/math/state.js +15 -0
  110. package/src/math/trade.js +253 -0
  111. package/src/math/trade.ts +23 -25
  112. package/src/math/utils.js +0 -1
  113. package/src/mockUSDCFaucet.js +280 -0
  114. package/src/oracles/oracleClientCache.js +19 -0
  115. package/src/oracles/pythClient.js +46 -0
  116. package/src/oracles/quoteAssetOracleClient.js +32 -0
  117. package/src/oracles/switchboardClient.js +69 -0
  118. package/src/oracles/types.js +2 -0
  119. package/src/orderParams.js +20 -0
  120. package/src/orderParams.ts +20 -141
  121. package/src/orders.ts +10 -287
  122. package/src/slot/SlotSubscriber.js +39 -0
  123. package/src/slot/SlotSubscriber.ts +11 -1
  124. package/src/token/index.js +38 -0
  125. package/src/tokenFaucet.js +189 -0
  126. package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +82 -70
  127. package/src/tx/retryTxSender.ts +11 -3
  128. package/src/tx/types.js +2 -0
  129. package/src/tx/utils.js +17 -0
  130. package/src/tx/utils.ts +1 -1
  131. package/src/types.js +125 -0
  132. package/src/types.ts +155 -17
  133. package/src/userName.js +20 -0
  134. package/src/util/computeUnits.js +21 -11
  135. package/src/util/computeUnits.ts +1 -1
  136. package/src/util/getTokenAddress.js +9 -0
  137. package/src/util/getTokenAddress.ts +18 -0
  138. package/src/util/promiseTimeout.js +14 -0
  139. package/src/util/tps.js +27 -0
  140. package/src/wallet.js +35 -0
  141. package/tests/bn/test.ts +2 -0
  142. package/src/util/computeUnits.js.map +0 -1
package/src/orders.ts CHANGED
@@ -1,177 +1,9 @@
1
- import {
2
- isVariant,
3
- MarketAccount,
4
- Order,
5
- PositionDirection,
6
- SwapDirection,
7
- UserAccount,
8
- UserPosition,
9
- } from './types';
10
- import {
11
- BN,
12
- calculateAmmReservesAfterSwap,
13
- calculateBaseAssetValue,
14
- calculateSpreadReserves,
15
- ClearingHouseUser,
16
- isOrderRiskIncreasingInSameDirection,
17
- standardizeBaseAssetAmount,
18
- TEN_THOUSAND,
19
- } from '.';
20
- import {
21
- calculateMarkPrice,
22
- calculateNewMarketAfterTrade,
23
- } from './math/market';
24
- import {
25
- AMM_TO_QUOTE_PRECISION_RATIO,
26
- TWO,
27
- PEG_PRECISION,
28
- ZERO,
29
- } from './constants/numericConstants';
1
+ import { isVariant, MarketAccount, Order, PositionDirection } from './types';
2
+ import { BN, standardizeBaseAssetAmount } from '.';
3
+ import { ZERO } from './constants/numericConstants';
30
4
  import { calculateMaxBaseAssetAmountToTrade } from './math/amm';
31
- import {
32
- findDirectionToClose,
33
- positionCurrentDirection,
34
- } from './math/position';
35
5
  import { OraclePriceData } from '.';
36
6
 
37
- export function calculateNewStateAfterOrder(
38
- userAccount: UserAccount,
39
- userPosition: UserPosition,
40
- market: MarketAccount,
41
- order: Order
42
- ): [UserAccount, UserPosition, MarketAccount] | null {
43
- if (isVariant(order.status, 'init')) {
44
- return null;
45
- }
46
-
47
- const baseAssetAmountToTrade = calculateBaseAssetAmountMarketCanExecute(
48
- market,
49
- order
50
- );
51
- if (baseAssetAmountToTrade.lt(market.amm.baseAssetAmountStepSize)) {
52
- return null;
53
- }
54
-
55
- const userAccountAfter = Object.assign({}, userAccount);
56
- const userPositionAfter = Object.assign({}, userPosition);
57
-
58
- const currentPositionDirection = positionCurrentDirection(userPosition);
59
- const increasePosition =
60
- userPosition.baseAssetAmount.eq(ZERO) ||
61
- isSameDirection(order.direction, currentPositionDirection);
62
-
63
- if (increasePosition) {
64
- const marketAfter = calculateNewMarketAfterTrade(
65
- baseAssetAmountToTrade,
66
- order.direction,
67
- market
68
- );
69
-
70
- const { quoteAssetAmountSwapped, baseAssetAmountSwapped } =
71
- calculateAmountSwapped(market, marketAfter);
72
-
73
- userPositionAfter.baseAssetAmount = userPositionAfter.baseAssetAmount.add(
74
- baseAssetAmountSwapped
75
- );
76
- userPositionAfter.quoteAssetAmount = userPositionAfter.quoteAssetAmount.add(
77
- quoteAssetAmountSwapped
78
- );
79
-
80
- return [userAccountAfter, userPositionAfter, marketAfter];
81
- } else {
82
- const reversePosition = baseAssetAmountToTrade.gt(
83
- userPosition.baseAssetAmount.abs()
84
- );
85
-
86
- if (reversePosition) {
87
- const intermediateMarket = calculateNewMarketAfterTrade(
88
- userPosition.baseAssetAmount,
89
- findDirectionToClose(userPosition),
90
- market
91
- );
92
-
93
- const { quoteAssetAmountSwapped: baseAssetValue } =
94
- calculateAmountSwapped(market, intermediateMarket);
95
-
96
- let pnl;
97
- if (isVariant(currentPositionDirection, 'long')) {
98
- pnl = baseAssetValue.sub(userPosition.quoteAssetAmount);
99
- } else {
100
- pnl = userPosition.quoteAssetAmount.sub(baseAssetValue);
101
- }
102
-
103
- userAccountAfter.collateral = userAccountAfter.collateral.add(pnl);
104
-
105
- const baseAssetAmountLeft = baseAssetAmountToTrade.sub(
106
- userPosition.baseAssetAmount.abs()
107
- );
108
-
109
- const marketAfter = calculateNewMarketAfterTrade(
110
- baseAssetAmountLeft,
111
- order.direction,
112
- intermediateMarket
113
- );
114
-
115
- const { quoteAssetAmountSwapped, baseAssetAmountSwapped } =
116
- calculateAmountSwapped(intermediateMarket, marketAfter);
117
-
118
- userPositionAfter.quoteAssetAmount = quoteAssetAmountSwapped;
119
- userPositionAfter.baseAssetAmount = baseAssetAmountSwapped;
120
-
121
- return [userAccountAfter, userPositionAfter, marketAfter];
122
- } else {
123
- const marketAfter = calculateNewMarketAfterTrade(
124
- baseAssetAmountToTrade,
125
- order.direction,
126
- market
127
- );
128
-
129
- const {
130
- quoteAssetAmountSwapped: baseAssetValue,
131
- baseAssetAmountSwapped,
132
- } = calculateAmountSwapped(market, marketAfter);
133
-
134
- const costBasisRealized = userPosition.quoteAssetAmount
135
- .mul(baseAssetAmountSwapped.abs())
136
- .div(userPosition.baseAssetAmount.abs());
137
-
138
- let pnl;
139
- if (isVariant(currentPositionDirection, 'long')) {
140
- pnl = baseAssetValue.sub(costBasisRealized);
141
- } else {
142
- pnl = costBasisRealized.sub(baseAssetValue);
143
- }
144
-
145
- userAccountAfter.collateral = userAccountAfter.collateral.add(pnl);
146
-
147
- userPositionAfter.baseAssetAmount = userPositionAfter.baseAssetAmount.add(
148
- baseAssetAmountSwapped
149
- );
150
- userPositionAfter.quoteAssetAmount =
151
- userPositionAfter.quoteAssetAmount.sub(costBasisRealized);
152
-
153
- return [userAccountAfter, userPositionAfter, marketAfter];
154
- }
155
- }
156
- }
157
-
158
- function calculateAmountSwapped(
159
- marketBefore: MarketAccount,
160
- marketAfter: MarketAccount
161
- ): { quoteAssetAmountSwapped: BN; baseAssetAmountSwapped: BN } {
162
- return {
163
- quoteAssetAmountSwapped: marketBefore.amm.quoteAssetReserve
164
- .sub(marketAfter.amm.quoteAssetReserve)
165
- .abs()
166
- .mul(marketBefore.amm.pegMultiplier)
167
- .div(PEG_PRECISION)
168
- .div(AMM_TO_QUOTE_PRECISION_RATIO),
169
- baseAssetAmountSwapped: marketBefore.amm.baseAssetReserve.sub(
170
- marketAfter.amm.baseAssetReserve
171
- ),
172
- };
173
- }
174
-
175
7
  export function calculateBaseAssetAmountMarketCanExecute(
176
8
  market: MarketAccount,
177
9
  order: Order,
@@ -182,7 +14,6 @@ export function calculateBaseAssetAmountMarketCanExecute(
182
14
  } else if (isVariant(order.orderType, 'triggerLimit')) {
183
15
  return calculateAmountToTradeForTriggerLimit(market, order);
184
16
  } else if (isVariant(order.orderType, 'market')) {
185
- // should never be a market order queued
186
17
  return ZERO;
187
18
  } else {
188
19
  return calculateAmountToTradeForTriggerMarket(market, order);
@@ -201,20 +32,14 @@ export function calculateAmountToTradeForLimit(
201
32
  'Cant calculate limit price for oracle offset oracle without OraclePriceData'
202
33
  );
203
34
  }
204
- const floatingPrice = oraclePriceData.price.add(order.oraclePriceOffset);
205
- if (order.postOnly) {
206
- limitPrice = isVariant(order.direction, 'long')
207
- ? BN.min(order.price, floatingPrice)
208
- : BN.max(order.price, floatingPrice);
209
- } else {
210
- limitPrice = floatingPrice;
211
- }
35
+ limitPrice = oraclePriceData.price.add(order.oraclePriceOffset);
212
36
  }
213
37
 
214
38
  const [maxAmountToTrade, direction] = calculateMaxBaseAssetAmountToTrade(
215
39
  market.amm,
216
40
  limitPrice,
217
- order.direction
41
+ order.direction,
42
+ oraclePriceData
218
43
  );
219
44
 
220
45
  const baseAssetAmount = standardizeBaseAssetAmount(
@@ -237,14 +62,8 @@ export function calculateAmountToTradeForTriggerLimit(
237
62
  market: MarketAccount,
238
63
  order: Order
239
64
  ): BN {
240
- if (order.baseAssetAmountFilled.eq(ZERO)) {
241
- const baseAssetAmount = calculateAmountToTradeForTriggerMarket(
242
- market,
243
- order
244
- );
245
- if (baseAssetAmount.eq(ZERO)) {
246
- return ZERO;
247
- }
65
+ if (!order.triggered) {
66
+ return ZERO;
248
67
  }
249
68
 
250
69
  return calculateAmountToTradeForLimit(market, order);
@@ -264,105 +83,9 @@ function calculateAmountToTradeForTriggerMarket(
264
83
  market: MarketAccount,
265
84
  order: Order
266
85
  ): BN {
267
- return isTriggerConditionSatisfied(market, order)
268
- ? order.baseAssetAmount
269
- : ZERO;
270
- }
271
-
272
- function isTriggerConditionSatisfied(
273
- market: MarketAccount,
274
- order: Order,
275
- oraclePriceData?: OraclePriceData
276
- ): boolean {
277
- const markPrice = calculateMarkPrice(market, oraclePriceData);
278
- if (isVariant(order.triggerCondition, 'above')) {
279
- return markPrice.gt(order.triggerPrice);
280
- } else {
281
- return markPrice.lt(order.triggerPrice);
282
- }
283
- }
284
-
285
- export function calculateBaseAssetAmountUserCanExecute(
286
- market: MarketAccount,
287
- order: Order,
288
- user: ClearingHouseUser,
289
- oraclePriceData?: OraclePriceData
290
- ): BN {
291
- const maxLeverage = user.getMaxLeverage(order.marketIndex, 'Initial');
292
- const freeCollateral = user.getFreeCollateral();
293
- let quoteAssetAmount: BN;
294
- if (isOrderRiskIncreasingInSameDirection(user, order)) {
295
- quoteAssetAmount = freeCollateral.mul(maxLeverage).div(TEN_THOUSAND);
296
- } else {
297
- const position =
298
- user.getUserPosition(order.marketIndex) ||
299
- user.getEmptyPosition(order.marketIndex);
300
- const positionValue = calculateBaseAssetValue(
301
- market,
302
- position,
303
- oraclePriceData
304
- );
305
- quoteAssetAmount = freeCollateral
306
- .mul(maxLeverage)
307
- .div(TEN_THOUSAND)
308
- .add(positionValue.mul(TWO));
309
- }
310
-
311
- if (quoteAssetAmount.lte(ZERO)) {
86
+ if (!order.triggered) {
312
87
  return ZERO;
313
88
  }
314
89
 
315
- const swapDirection = isVariant(order.direction, 'long')
316
- ? SwapDirection.ADD
317
- : SwapDirection.REMOVE;
318
-
319
- const useSpread = !order.postOnly;
320
- let amm: Parameters<typeof calculateAmmReservesAfterSwap>[0];
321
- if (useSpread) {
322
- const { baseAssetReserve, quoteAssetReserve } = calculateSpreadReserves(
323
- market.amm,
324
- order.direction,
325
- oraclePriceData
326
- );
327
- amm = {
328
- baseAssetReserve,
329
- quoteAssetReserve,
330
- sqrtK: market.amm.sqrtK,
331
- pegMultiplier: market.amm.pegMultiplier,
332
- };
333
- } else {
334
- amm = market.amm;
335
- }
336
-
337
- const baseAssetReservesBefore = amm.baseAssetReserve;
338
- const [_, baseAssetReservesAfter] = calculateAmmReservesAfterSwap(
339
- amm,
340
- 'quote',
341
- quoteAssetAmount,
342
- swapDirection
343
- );
344
-
345
- let baseAssetAmount = baseAssetReservesBefore
346
- .sub(baseAssetReservesAfter)
347
- .abs();
348
- if (order.reduceOnly) {
349
- const position =
350
- user.getUserPosition(order.marketIndex) ||
351
- user.getEmptyPosition(order.marketIndex);
352
- if (
353
- isVariant(order.direction, 'long') &&
354
- position.baseAssetAmount.gte(ZERO)
355
- ) {
356
- baseAssetAmount = ZERO;
357
- } else if (
358
- isVariant(order.direction, 'short') &&
359
- position.baseAssetAmount.lte(ZERO)
360
- ) {
361
- baseAssetAmount = ZERO;
362
- } else {
363
- BN.min(baseAssetAmount, position.baseAssetAmount.abs());
364
- }
365
- }
366
-
367
- return baseAssetAmount;
90
+ return order.baseAssetAmount;
368
91
  }
@@ -0,0 +1,39 @@
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.SlotSubscriber = void 0;
13
+ const events_1 = require("events");
14
+ class SlotSubscriber {
15
+ constructor(connection, _config) {
16
+ this.connection = connection;
17
+ this.eventEmitter = new events_1.EventEmitter();
18
+ }
19
+ subscribe() {
20
+ return __awaiter(this, void 0, void 0, function* () {
21
+ this.currentSlot = yield this.connection.getSlot('confirmed');
22
+ this.subscriptionId = this.connection.onSlotChange((slotInfo) => {
23
+ this.currentSlot = slotInfo.slot;
24
+ this.eventEmitter.emit('newSlot', slotInfo.slot);
25
+ });
26
+ });
27
+ }
28
+ getSlot() {
29
+ return this.currentSlot;
30
+ }
31
+ unsubscribe() {
32
+ return __awaiter(this, void 0, void 0, function* () {
33
+ if (this.subscriptionId) {
34
+ yield this.connection.removeSlotChangeListener(this.subscriptionId);
35
+ }
36
+ });
37
+ }
38
+ }
39
+ exports.SlotSubscriber = SlotSubscriber;
@@ -1,22 +1,32 @@
1
1
  import { Connection } from '@solana/web3.js';
2
+ import { EventEmitter } from 'events';
3
+ import StrictEventEmitter from 'strict-event-emitter-types/types/src';
2
4
 
3
5
  // eslint-disable-next-line @typescript-eslint/ban-types
4
6
  type SlotSubscriberConfig = {}; // for future customization
5
7
 
8
+ export interface SlotSubscriberEvents {
9
+ newSlot: (newSlot: number) => void;
10
+ }
11
+
6
12
  export class SlotSubscriber {
7
13
  currentSlot: number;
8
14
  subscriptionId: number;
15
+ eventEmitter: StrictEventEmitter<EventEmitter, SlotSubscriberEvents>;
9
16
 
10
17
  public constructor(
11
18
  private connection: Connection,
12
19
  _config?: SlotSubscriberConfig
13
- ) {}
20
+ ) {
21
+ this.eventEmitter = new EventEmitter();
22
+ }
14
23
 
15
24
  public async subscribe(): Promise<void> {
16
25
  this.currentSlot = await this.connection.getSlot('confirmed');
17
26
 
18
27
  this.subscriptionId = this.connection.onSlotChange((slotInfo) => {
19
28
  this.currentSlot = slotInfo.slot;
29
+ this.eventEmitter.emit('newSlot', slotInfo.slot);
20
30
  });
21
31
  }
22
32
 
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseTokenAccount = void 0;
4
+ const spl_token_1 = require("@solana/spl-token");
5
+ const web3_js_1 = require("@solana/web3.js");
6
+ function parseTokenAccount(data) {
7
+ const accountInfo = spl_token_1.AccountLayout.decode(data);
8
+ accountInfo.mint = new web3_js_1.PublicKey(accountInfo.mint);
9
+ accountInfo.owner = new web3_js_1.PublicKey(accountInfo.owner);
10
+ accountInfo.amount = spl_token_1.u64.fromBuffer(accountInfo.amount);
11
+ if (accountInfo.delegateOption === 0) {
12
+ accountInfo.delegate = null;
13
+ // eslint-disable-next-line new-cap
14
+ accountInfo.delegatedAmount = new spl_token_1.u64(0);
15
+ }
16
+ else {
17
+ accountInfo.delegate = new web3_js_1.PublicKey(accountInfo.delegate);
18
+ accountInfo.delegatedAmount = spl_token_1.u64.fromBuffer(accountInfo.delegatedAmount);
19
+ }
20
+ accountInfo.isInitialized = accountInfo.state !== 0;
21
+ accountInfo.isFrozen = accountInfo.state === 2;
22
+ if (accountInfo.isNativeOption === 1) {
23
+ accountInfo.rentExemptReserve = spl_token_1.u64.fromBuffer(accountInfo.isNative);
24
+ accountInfo.isNative = true;
25
+ }
26
+ else {
27
+ accountInfo.rentExemptReserve = null;
28
+ accountInfo.isNative = false;
29
+ }
30
+ if (accountInfo.closeAuthorityOption === 0) {
31
+ accountInfo.closeAuthority = null;
32
+ }
33
+ else {
34
+ accountInfo.closeAuthority = new web3_js_1.PublicKey(accountInfo.closeAuthority);
35
+ }
36
+ return accountInfo;
37
+ }
38
+ exports.parseTokenAccount = parseTokenAccount;
@@ -0,0 +1,189 @@
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
+ var __importDefault = (this && this.__importDefault) || function (mod) {
31
+ return (mod && mod.__esModule) ? mod : { "default": mod };
32
+ };
33
+ Object.defineProperty(exports, "__esModule", { value: true });
34
+ exports.TokenFaucet = void 0;
35
+ const anchor = __importStar(require("@project-serum/anchor"));
36
+ const anchor_1 = require("@project-serum/anchor");
37
+ const spl_token_1 = require("@solana/spl-token");
38
+ const web3_js_1 = require("@solana/web3.js");
39
+ const token_faucet_json_1 = __importDefault(require("./idl/token_faucet.json"));
40
+ class TokenFaucet {
41
+ constructor(connection, wallet, programId, mint, opts) {
42
+ this.connection = connection;
43
+ this.wallet = wallet;
44
+ this.opts = opts || anchor_1.AnchorProvider.defaultOptions();
45
+ const provider = new anchor_1.AnchorProvider(connection, wallet, this.opts);
46
+ this.provider = provider;
47
+ this.program = new anchor_1.Program(token_faucet_json_1.default, programId, provider);
48
+ this.mint = mint;
49
+ }
50
+ getFaucetConfigPublicKeyAndNonce() {
51
+ return __awaiter(this, void 0, void 0, function* () {
52
+ return anchor.web3.PublicKey.findProgramAddress([
53
+ Buffer.from(anchor.utils.bytes.utf8.encode('faucet_config')),
54
+ this.mint.toBuffer(),
55
+ ], this.program.programId);
56
+ });
57
+ }
58
+ getMintAuthority() {
59
+ return __awaiter(this, void 0, void 0, function* () {
60
+ return (yield anchor.web3.PublicKey.findProgramAddress([
61
+ Buffer.from(anchor.utils.bytes.utf8.encode('mint_authority')),
62
+ this.mint.toBuffer(),
63
+ ], this.program.programId))[0];
64
+ });
65
+ }
66
+ getFaucetConfigPublicKey() {
67
+ return __awaiter(this, void 0, void 0, function* () {
68
+ return (yield this.getFaucetConfigPublicKeyAndNonce())[0];
69
+ });
70
+ }
71
+ initialize() {
72
+ return __awaiter(this, void 0, void 0, function* () {
73
+ const [faucetConfigPublicKey] = yield this.getFaucetConfigPublicKeyAndNonce();
74
+ return yield this.program.rpc.initialize({
75
+ accounts: {
76
+ faucetConfig: faucetConfigPublicKey,
77
+ admin: this.wallet.publicKey,
78
+ mintAccount: this.mint,
79
+ rent: web3_js_1.SYSVAR_RENT_PUBKEY,
80
+ systemProgram: anchor.web3.SystemProgram.programId,
81
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
82
+ },
83
+ });
84
+ });
85
+ }
86
+ fetchState() {
87
+ return __awaiter(this, void 0, void 0, function* () {
88
+ return yield this.program.account.faucetConfig.fetch(yield this.getFaucetConfigPublicKey());
89
+ });
90
+ }
91
+ mintToUserIx(userTokenAccount, amount) {
92
+ return __awaiter(this, void 0, void 0, function* () {
93
+ return this.program.instruction.mintToUser(amount, {
94
+ accounts: {
95
+ faucetConfig: yield this.getFaucetConfigPublicKey(),
96
+ mintAccount: this.mint,
97
+ userTokenAccount,
98
+ mintAuthority: yield this.getMintAuthority(),
99
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
100
+ },
101
+ });
102
+ });
103
+ }
104
+ mintToUser(userTokenAccount, amount) {
105
+ return __awaiter(this, void 0, void 0, function* () {
106
+ const mintIx = yield this.mintToUserIx(userTokenAccount, amount);
107
+ const tx = new web3_js_1.Transaction().add(mintIx);
108
+ const txSig = yield this.program.provider.sendAndConfirm(tx, [], this.opts);
109
+ return txSig;
110
+ });
111
+ }
112
+ transferMintAuthority() {
113
+ return __awaiter(this, void 0, void 0, function* () {
114
+ return yield this.program.rpc.transferMintAuthority({
115
+ accounts: {
116
+ faucetConfig: yield this.getFaucetConfigPublicKey(),
117
+ mintAccount: this.mint,
118
+ mintAuthority: yield this.getMintAuthority(),
119
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
120
+ admin: this.wallet.publicKey,
121
+ },
122
+ });
123
+ });
124
+ }
125
+ createAssociatedTokenAccountAndMintTo(userPublicKey, amount) {
126
+ return __awaiter(this, void 0, void 0, function* () {
127
+ const tx = new web3_js_1.Transaction();
128
+ const [associatedTokenPublicKey, createAssociatedAccountIx, mintToTx] = yield this.createAssociatedTokenAccountAndMintToInstructions(userPublicKey, amount);
129
+ let associatedTokenAccountExists = false;
130
+ try {
131
+ const assosciatedTokenAccount = yield this.connection.getAccountInfo(associatedTokenPublicKey);
132
+ associatedTokenAccountExists = !!assosciatedTokenAccount;
133
+ }
134
+ catch (e) {
135
+ // token account doesn't exist
136
+ associatedTokenAccountExists = false;
137
+ }
138
+ const skipAccountCreation = associatedTokenAccountExists;
139
+ if (!skipAccountCreation)
140
+ tx.add(createAssociatedAccountIx);
141
+ tx.add(mintToTx);
142
+ const txSig = yield this.program.provider.sendAndConfirm(tx, [], this.opts);
143
+ return [associatedTokenPublicKey, txSig];
144
+ });
145
+ }
146
+ createAssociatedTokenAccountAndMintToInstructions(userPublicKey, amount) {
147
+ return __awaiter(this, void 0, void 0, function* () {
148
+ const state = yield this.fetchState();
149
+ const associateTokenPublicKey = yield this.getAssosciatedMockUSDMintAddress({ userPubKey: userPublicKey });
150
+ const createAssociatedAccountIx = spl_token_1.Token.createAssociatedTokenAccountInstruction(spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID, spl_token_1.TOKEN_PROGRAM_ID, state.mint, associateTokenPublicKey, userPublicKey, this.wallet.publicKey);
151
+ const mintToIx = yield this.mintToUserIx(associateTokenPublicKey, amount);
152
+ return [associateTokenPublicKey, createAssociatedAccountIx, mintToIx];
153
+ });
154
+ }
155
+ getAssosciatedMockUSDMintAddress(props) {
156
+ return __awaiter(this, void 0, void 0, function* () {
157
+ const state = yield this.fetchState();
158
+ return spl_token_1.Token.getAssociatedTokenAddress(spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID, spl_token_1.TOKEN_PROGRAM_ID, state.mint, props.userPubKey);
159
+ });
160
+ }
161
+ getTokenAccountInfo(props) {
162
+ return __awaiter(this, void 0, void 0, function* () {
163
+ const assosciatedKey = yield this.getAssosciatedMockUSDMintAddress(props);
164
+ const state = yield this.fetchState();
165
+ const token = new spl_token_1.Token(this.connection, state.mint, spl_token_1.TOKEN_PROGRAM_ID,
166
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
167
+ // @ts-ignore
168
+ this.provider.payer);
169
+ return yield token.getAccountInfo(assosciatedKey);
170
+ });
171
+ }
172
+ subscribeToTokenAccount(props) {
173
+ return __awaiter(this, void 0, void 0, function* () {
174
+ try {
175
+ const tokenAccountKey = yield this.getAssosciatedMockUSDMintAddress(props);
176
+ props.callback(yield this.getTokenAccountInfo(props));
177
+ // Couldn't find a way to do it using anchor framework subscription, someone on serum discord recommended this way
178
+ this.connection.onAccountChange(tokenAccountKey, (_accountInfo /* accountInfo is a buffer which we don't know how to deserialize */) => __awaiter(this, void 0, void 0, function* () {
179
+ props.callback(yield this.getTokenAccountInfo(props));
180
+ }));
181
+ return true;
182
+ }
183
+ catch (e) {
184
+ return false;
185
+ }
186
+ });
187
+ }
188
+ }
189
+ exports.TokenFaucet = TokenFaucet;