@drift-labs/sdk 0.1.19-master.2 → 0.1.21-master.4

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 (143) hide show
  1. package/lib/accounts/bulkAccountLoader.d.ts +31 -0
  2. package/lib/accounts/bulkAccountLoader.js +177 -0
  3. package/lib/accounts/bulkUserSubscription.d.ts +7 -0
  4. package/lib/accounts/bulkUserSubscription.js +28 -0
  5. package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts +49 -0
  6. package/lib/accounts/pollingClearingHouseAccountSubscriber.js +228 -0
  7. package/lib/accounts/pollingTokenAccountSubscriber.d.ts +25 -0
  8. package/lib/accounts/pollingTokenAccountSubscriber.js +79 -0
  9. package/lib/accounts/pollingUserAccountSubscriber.d.ts +32 -0
  10. package/lib/accounts/pollingUserAccountSubscriber.js +136 -0
  11. package/lib/accounts/types.d.ts +38 -3
  12. package/lib/accounts/utils.d.ts +1 -0
  13. package/lib/accounts/utils.js +7 -0
  14. package/lib/accounts/webSocketAccountSubscriber.d.ts +6 -3
  15. package/lib/accounts/webSocketAccountSubscriber.js +43 -12
  16. package/lib/accounts/{defaultClearingHouseAccountSubscriber.d.ts → webSocketClearingHouseAccountSubscriber.d.ts} +8 -3
  17. package/lib/accounts/{defaultClearingHouseAccountSubscriber.js → webSocketClearingHouseAccountSubscriber.js} +30 -4
  18. package/lib/accounts/{defaultUserAccountSubscriber.d.ts → webSocketUserAccountSubscriber.d.ts} +6 -3
  19. package/lib/accounts/{defaultUserAccountSubscriber.js → webSocketUserAccountSubscriber.js} +16 -4
  20. package/lib/addresses.d.ts +4 -1
  21. package/lib/addresses.js +28 -1
  22. package/lib/admin.d.ts +10 -4
  23. package/lib/admin.js +54 -17
  24. package/lib/assert/assert.d.ts +0 -1
  25. package/lib/clearingHouse.d.ts +39 -4
  26. package/lib/clearingHouse.js +334 -23
  27. package/lib/clearingHouseUser.d.ts +27 -6
  28. package/lib/clearingHouseUser.js +125 -45
  29. package/lib/config.d.ts +0 -1
  30. package/lib/constants/markets.d.ts +2 -2
  31. package/lib/constants/markets.js +28 -15
  32. package/lib/constants/numericConstants.d.ts +4 -2
  33. package/lib/constants/numericConstants.js +16 -17
  34. package/lib/examples/makeTradeExample.d.ts +0 -1
  35. package/lib/examples/makeTradeExample.js +6 -6
  36. package/lib/factory/clearingHouse.d.ts +25 -0
  37. package/lib/factory/clearingHouse.js +64 -0
  38. package/lib/factory/clearingHouseUser.d.ts +19 -0
  39. package/lib/factory/clearingHouseUser.js +34 -0
  40. package/lib/idl/clearing_house.json +1066 -39
  41. package/lib/index.d.ts +11 -3
  42. package/lib/index.js +12 -2
  43. package/lib/math/amm.d.ts +3 -1
  44. package/lib/math/amm.js +128 -15
  45. package/lib/math/conversion.d.ts +1 -2
  46. package/lib/math/conversion.js +1 -1
  47. package/lib/math/funding.d.ts +0 -1
  48. package/lib/math/funding.js +1 -1
  49. package/lib/math/insuranceFund.d.ts +2 -2
  50. package/lib/math/insuranceFund.js +3 -6
  51. package/lib/math/market.d.ts +2 -2
  52. package/lib/math/market.js +12 -2
  53. package/lib/math/orders.d.ts +3 -0
  54. package/lib/math/orders.js +32 -0
  55. package/lib/math/position.d.ts +6 -3
  56. package/lib/math/position.js +21 -10
  57. package/lib/math/trade.d.ts +0 -1
  58. package/lib/math/trade.js +16 -16
  59. package/lib/math/utils.d.ts +2 -2
  60. package/lib/math/utils.js +3 -3
  61. package/lib/mockUSDCFaucet.d.ts +2 -2
  62. package/lib/orderParams.d.ts +7 -0
  63. package/lib/orderParams.js +108 -0
  64. package/lib/orders.d.ts +6 -0
  65. package/lib/orders.js +136 -0
  66. package/lib/pythClient.d.ts +0 -1
  67. package/lib/pythClient.js +1 -1
  68. package/lib/token/index.d.ts +3 -0
  69. package/lib/token/index.js +38 -0
  70. package/lib/tx/defaultTxSender.d.ts +0 -1
  71. package/lib/tx/types.d.ts +0 -1
  72. package/lib/tx/utils.d.ts +0 -1
  73. package/lib/types.d.ts +147 -3
  74. package/lib/types.js +36 -1
  75. package/lib/util/computeUnits.d.ts +0 -1
  76. package/lib/util/tps.d.ts +0 -1
  77. package/lib/wallet.d.ts +0 -1
  78. package/package.json +11 -3
  79. package/src/accounts/bulkAccountLoader.ts +215 -0
  80. package/src/accounts/bulkUserSubscription.ts +28 -0
  81. package/src/accounts/pollingClearingHouseAccountSubscriber.ts +326 -0
  82. package/src/accounts/pollingTokenAccountSubscriber.ts +99 -0
  83. package/src/accounts/pollingUserAccountSubscriber.ts +194 -0
  84. package/src/accounts/types.ts +48 -1
  85. package/src/accounts/utils.ts +3 -0
  86. package/src/accounts/webSocketAccountSubscriber.ts +67 -17
  87. package/src/accounts/{defaultClearingHouseAccountSubscriber.ts → webSocketClearingHouseAccountSubscriber.ts} +51 -1
  88. package/src/accounts/{defaultUserAccountSubscriber.ts → webSocketUserAccountSubscriber.ts} +33 -3
  89. package/src/addresses.ts +37 -0
  90. package/src/admin.ts +92 -24
  91. package/src/clearingHouse.ts +455 -22
  92. package/src/clearingHouseUser.ts +155 -18
  93. package/src/constants/markets.ts +17 -1
  94. package/src/constants/numericConstants.ts +3 -1
  95. package/src/examples/makeTradeExample.ts +4 -1
  96. package/src/factory/clearingHouse.ts +125 -0
  97. package/src/factory/clearingHouseUser.ts +73 -0
  98. package/src/idl/clearing_house.json +1066 -39
  99. package/src/index.ts +11 -2
  100. package/src/math/amm.ts +169 -14
  101. package/src/math/conversion.ts +1 -1
  102. package/src/math/insuranceFund.ts +1 -1
  103. package/src/math/market.ts +28 -2
  104. package/src/math/orders.ts +44 -0
  105. package/src/math/position.ts +24 -4
  106. package/src/math/utils.ts +1 -1
  107. package/src/mockUSDCFaucet.ts +1 -1
  108. package/src/orderParams.ts +151 -0
  109. package/src/orders.ts +236 -0
  110. package/src/token/index.ts +37 -0
  111. package/src/types.ts +130 -2
  112. package/tsconfig.json +0 -1
  113. package/lib/accounts/defaultClearingHouseAccountSubscriber.d.ts.map +0 -1
  114. package/lib/accounts/defaultUserAccountSubscriber.d.ts.map +0 -1
  115. package/lib/accounts/types.d.ts.map +0 -1
  116. package/lib/accounts/webSocketAccountSubscriber.d.ts.map +0 -1
  117. package/lib/addresses.d.ts.map +0 -1
  118. package/lib/admin.d.ts.map +0 -1
  119. package/lib/assert/assert.d.ts.map +0 -1
  120. package/lib/clearingHouse.d.ts.map +0 -1
  121. package/lib/clearingHouseUser.d.ts.map +0 -1
  122. package/lib/config.d.ts.map +0 -1
  123. package/lib/constants/markets.d.ts.map +0 -1
  124. package/lib/constants/numericConstants.d.ts.map +0 -1
  125. package/lib/examples/makeTradeExample.d.ts.map +0 -1
  126. package/lib/index.d.ts.map +0 -1
  127. package/lib/math/amm.d.ts.map +0 -1
  128. package/lib/math/conversion.d.ts.map +0 -1
  129. package/lib/math/funding.d.ts.map +0 -1
  130. package/lib/math/insuranceFund.d.ts.map +0 -1
  131. package/lib/math/market.d.ts.map +0 -1
  132. package/lib/math/position.d.ts.map +0 -1
  133. package/lib/math/trade.d.ts.map +0 -1
  134. package/lib/math/utils.d.ts.map +0 -1
  135. package/lib/mockUSDCFaucet.d.ts.map +0 -1
  136. package/lib/pythClient.d.ts.map +0 -1
  137. package/lib/tx/defaultTxSender.d.ts.map +0 -1
  138. package/lib/tx/types.d.ts.map +0 -1
  139. package/lib/tx/utils.d.ts.map +0 -1
  140. package/lib/types.d.ts.map +0 -1
  141. package/lib/util/computeUnits.d.ts.map +0 -1
  142. package/lib/util/tps.d.ts.map +0 -1
  143. package/lib/wallet.d.ts.map +0 -1
@@ -1,8 +1,9 @@
1
+ /// <reference types="bn.js" />
1
2
  import * as anchor from '@project-serum/anchor';
2
3
  import { Program, Provider } from '@project-serum/anchor';
3
4
  import { AccountInfo } from '@solana/spl-token';
4
5
  import { ConfirmOptions, Connection, PublicKey, TransactionInstruction, TransactionSignature } from '@solana/web3.js';
5
- import BN from 'bn.js';
6
+ import { BN } from '.';
6
7
  import { IWallet } from './types';
7
8
  export declare class MockUSDCFaucet {
8
9
  connection: Connection;
@@ -33,4 +34,3 @@ export declare class MockUSDCFaucet {
33
34
  callback: (accountInfo: AccountInfo) => void;
34
35
  }): Promise<boolean>;
35
36
  }
36
- //# sourceMappingURL=mockUSDCFaucet.d.ts.map
@@ -0,0 +1,7 @@
1
+ /// <reference types="bn.js" />
2
+ import { OrderParams, OrderTriggerCondition, PositionDirection } from './types';
3
+ import { BN } from '@project-serum/anchor';
4
+ export declare function getLimitOrderParams(marketIndex: BN, direction: PositionDirection, baseAssetAmount: BN, price: BN, reduceOnly: boolean, discountToken?: boolean, referrer?: boolean, userOrderId?: number): OrderParams;
5
+ export declare function getTriggerMarketOrderParams(marketIndex: BN, direction: PositionDirection, baseAssetAmount: BN, triggerPrice: BN, triggerCondition: OrderTriggerCondition, reduceOnly: boolean, discountToken?: boolean, referrer?: boolean, userOrderId?: number): OrderParams;
6
+ export declare function getTriggerLimitOrderParams(marketIndex: BN, direction: PositionDirection, baseAssetAmount: BN, price: BN, triggerPrice: BN, triggerCondition: OrderTriggerCondition, reduceOnly: boolean, discountToken?: boolean, referrer?: boolean, userOrderId?: number): OrderParams;
7
+ export declare function getMarketOrderParams(marketIndex: BN, direction: PositionDirection, quoteAssetAmount: BN, baseAssetAmount: BN, reduceOnly: boolean, price?: BN, discountToken?: boolean, referrer?: boolean): OrderParams;
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getMarketOrderParams = exports.getTriggerLimitOrderParams = exports.getTriggerMarketOrderParams = exports.getLimitOrderParams = void 0;
4
+ const types_1 = require("./types");
5
+ const numericConstants_1 = require("./constants/numericConstants");
6
+ function getLimitOrderParams(marketIndex, direction, baseAssetAmount, price, reduceOnly, discountToken = false, referrer = false, userOrderId = 0) {
7
+ return {
8
+ orderType: types_1.OrderType.LIMIT,
9
+ userOrderId,
10
+ marketIndex,
11
+ direction,
12
+ quoteAssetAmount: numericConstants_1.ZERO,
13
+ baseAssetAmount,
14
+ price,
15
+ reduceOnly,
16
+ postOnly: false,
17
+ immediateOrCancel: false,
18
+ positionLimit: numericConstants_1.ZERO,
19
+ padding0: true,
20
+ padding1: numericConstants_1.ZERO,
21
+ optionalAccounts: {
22
+ discountToken,
23
+ referrer,
24
+ },
25
+ triggerCondition: types_1.OrderTriggerCondition.ABOVE,
26
+ triggerPrice: numericConstants_1.ZERO,
27
+ oraclePriceOffset: numericConstants_1.ZERO,
28
+ };
29
+ }
30
+ exports.getLimitOrderParams = getLimitOrderParams;
31
+ function getTriggerMarketOrderParams(marketIndex, direction, baseAssetAmount, triggerPrice, triggerCondition, reduceOnly, discountToken = false, referrer = false, userOrderId = 0) {
32
+ return {
33
+ orderType: types_1.OrderType.TRIGGER_MARKET,
34
+ userOrderId,
35
+ marketIndex,
36
+ direction,
37
+ quoteAssetAmount: numericConstants_1.ZERO,
38
+ baseAssetAmount,
39
+ price: numericConstants_1.ZERO,
40
+ reduceOnly,
41
+ postOnly: false,
42
+ immediateOrCancel: false,
43
+ positionLimit: numericConstants_1.ZERO,
44
+ padding0: true,
45
+ padding1: numericConstants_1.ZERO,
46
+ optionalAccounts: {
47
+ discountToken,
48
+ referrer,
49
+ },
50
+ triggerCondition,
51
+ triggerPrice,
52
+ oraclePriceOffset: numericConstants_1.ZERO,
53
+ };
54
+ }
55
+ exports.getTriggerMarketOrderParams = getTriggerMarketOrderParams;
56
+ function getTriggerLimitOrderParams(marketIndex, direction, baseAssetAmount, price, triggerPrice, triggerCondition, reduceOnly, discountToken = false, referrer = false, userOrderId = 0) {
57
+ return {
58
+ orderType: types_1.OrderType.TRIGGER_LIMIT,
59
+ userOrderId,
60
+ marketIndex,
61
+ direction,
62
+ quoteAssetAmount: numericConstants_1.ZERO,
63
+ baseAssetAmount,
64
+ price,
65
+ reduceOnly,
66
+ postOnly: false,
67
+ immediateOrCancel: false,
68
+ positionLimit: numericConstants_1.ZERO,
69
+ padding0: true,
70
+ padding1: numericConstants_1.ZERO,
71
+ optionalAccounts: {
72
+ discountToken,
73
+ referrer,
74
+ },
75
+ triggerCondition,
76
+ triggerPrice,
77
+ oraclePriceOffset: numericConstants_1.ZERO,
78
+ };
79
+ }
80
+ exports.getTriggerLimitOrderParams = getTriggerLimitOrderParams;
81
+ function getMarketOrderParams(marketIndex, direction, quoteAssetAmount, baseAssetAmount, reduceOnly, price = numericConstants_1.ZERO, discountToken = false, referrer = false) {
82
+ if (baseAssetAmount.eq(numericConstants_1.ZERO) && quoteAssetAmount.eq(numericConstants_1.ZERO)) {
83
+ throw Error('baseAssetAmount or quoteAssetAmount must be zero');
84
+ }
85
+ return {
86
+ orderType: types_1.OrderType.MARKET,
87
+ userOrderId: 0,
88
+ marketIndex,
89
+ direction,
90
+ quoteAssetAmount,
91
+ baseAssetAmount,
92
+ price,
93
+ reduceOnly,
94
+ postOnly: false,
95
+ immediateOrCancel: false,
96
+ positionLimit: numericConstants_1.ZERO,
97
+ padding0: true,
98
+ padding1: numericConstants_1.ZERO,
99
+ optionalAccounts: {
100
+ discountToken,
101
+ referrer,
102
+ },
103
+ triggerCondition: types_1.OrderTriggerCondition.ABOVE,
104
+ triggerPrice: numericConstants_1.ZERO,
105
+ oraclePriceOffset: numericConstants_1.ZERO,
106
+ };
107
+ }
108
+ exports.getMarketOrderParams = getMarketOrderParams;
@@ -0,0 +1,6 @@
1
+ /// <reference types="bn.js" />
2
+ import { Market, Order, UserAccount, UserPosition } from './types';
3
+ import { BN } from '.';
4
+ export declare function calculateNewStateAfterOrder(userAccount: UserAccount, userPosition: UserPosition, market: Market, order: Order): [UserAccount, UserPosition, Market] | null;
5
+ export declare function calculateAmountToTradeForLimit(market: Market, order: Order): BN;
6
+ export declare function calculateAmountToTradeForTriggerLimit(market: Market, order: Order): BN;
package/lib/orders.js ADDED
@@ -0,0 +1,136 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.calculateAmountToTradeForTriggerLimit = exports.calculateAmountToTradeForLimit = exports.calculateNewStateAfterOrder = void 0;
4
+ const types_1 = require("./types");
5
+ const market_1 = require("./math/market");
6
+ const numericConstants_1 = require("./constants/numericConstants");
7
+ const amm_1 = require("./math/amm");
8
+ const position_1 = require("./math/position");
9
+ function calculateNewStateAfterOrder(userAccount, userPosition, market, order) {
10
+ if (types_1.isVariant(order.status, 'init')) {
11
+ return null;
12
+ }
13
+ const baseAssetAmountToTrade = calculateAmountToTrade(market, order);
14
+ if (baseAssetAmountToTrade.lt(market.amm.minimumBaseAssetTradeSize)) {
15
+ return null;
16
+ }
17
+ const userAccountAfter = Object.assign({}, userAccount);
18
+ const userPositionAfter = Object.assign({}, userPosition);
19
+ const currentPositionDirection = position_1.positionCurrentDirection(userPosition);
20
+ const increasePosition = userPosition.baseAssetAmount.eq(numericConstants_1.ZERO) ||
21
+ isSameDirection(order.direction, currentPositionDirection);
22
+ if (increasePosition) {
23
+ const marketAfter = market_1.calculateNewMarketAfterTrade(baseAssetAmountToTrade, order.direction, market);
24
+ const { quoteAssetAmountSwapped, baseAssetAmountSwapped } = calculateAmountSwapped(market, marketAfter);
25
+ userPositionAfter.baseAssetAmount = userPositionAfter.baseAssetAmount.add(baseAssetAmountSwapped);
26
+ userPositionAfter.quoteAssetAmount = userPositionAfter.quoteAssetAmount.add(quoteAssetAmountSwapped);
27
+ return [userAccountAfter, userPositionAfter, marketAfter];
28
+ }
29
+ else {
30
+ const reversePosition = baseAssetAmountToTrade.gt(userPosition.baseAssetAmount.abs());
31
+ if (reversePosition) {
32
+ const intermediateMarket = market_1.calculateNewMarketAfterTrade(userPosition.baseAssetAmount, position_1.findDirectionToClose(userPosition), market);
33
+ const { quoteAssetAmountSwapped: baseAssetValue } = calculateAmountSwapped(market, intermediateMarket);
34
+ let pnl;
35
+ if (types_1.isVariant(currentPositionDirection, 'long')) {
36
+ pnl = baseAssetValue.sub(userPosition.quoteAssetAmount);
37
+ }
38
+ else {
39
+ pnl = userPosition.quoteAssetAmount.sub(baseAssetValue);
40
+ }
41
+ userAccountAfter.collateral = userAccountAfter.collateral.add(pnl);
42
+ const baseAssetAmountLeft = baseAssetAmountToTrade.sub(userPosition.baseAssetAmount.abs());
43
+ const marketAfter = market_1.calculateNewMarketAfterTrade(baseAssetAmountLeft, order.direction, intermediateMarket);
44
+ const { quoteAssetAmountSwapped, baseAssetAmountSwapped } = calculateAmountSwapped(intermediateMarket, marketAfter);
45
+ userPositionAfter.quoteAssetAmount = quoteAssetAmountSwapped;
46
+ userPositionAfter.baseAssetAmount = baseAssetAmountSwapped;
47
+ return [userAccountAfter, userPositionAfter, marketAfter];
48
+ }
49
+ else {
50
+ const marketAfter = market_1.calculateNewMarketAfterTrade(baseAssetAmountToTrade, order.direction, market);
51
+ const { quoteAssetAmountSwapped: baseAssetValue, baseAssetAmountSwapped, } = calculateAmountSwapped(market, marketAfter);
52
+ const costBasisRealized = userPosition.quoteAssetAmount
53
+ .mul(baseAssetAmountSwapped.abs())
54
+ .div(userPosition.baseAssetAmount.abs());
55
+ let pnl;
56
+ if (types_1.isVariant(currentPositionDirection, 'long')) {
57
+ pnl = baseAssetValue.sub(costBasisRealized);
58
+ }
59
+ else {
60
+ pnl = costBasisRealized.sub(baseAssetValue);
61
+ }
62
+ userAccountAfter.collateral = userAccountAfter.collateral.add(pnl);
63
+ userPositionAfter.baseAssetAmount = userPositionAfter.baseAssetAmount.add(baseAssetAmountSwapped);
64
+ userPositionAfter.quoteAssetAmount =
65
+ userPositionAfter.quoteAssetAmount.sub(costBasisRealized);
66
+ return [userAccountAfter, userPositionAfter, marketAfter];
67
+ }
68
+ }
69
+ }
70
+ exports.calculateNewStateAfterOrder = calculateNewStateAfterOrder;
71
+ function calculateAmountSwapped(marketBefore, marketAfter) {
72
+ return {
73
+ quoteAssetAmountSwapped: marketBefore.amm.quoteAssetReserve
74
+ .sub(marketAfter.amm.quoteAssetReserve)
75
+ .abs()
76
+ .mul(marketBefore.amm.pegMultiplier)
77
+ .div(numericConstants_1.PEG_PRECISION)
78
+ .div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO),
79
+ baseAssetAmountSwapped: marketBefore.amm.baseAssetReserve.sub(marketAfter.amm.baseAssetReserve),
80
+ };
81
+ }
82
+ function calculateAmountToTrade(market, order) {
83
+ if (types_1.isVariant(order.orderType, 'limit')) {
84
+ return calculateAmountToTradeForLimit(market, order);
85
+ }
86
+ else if (types_1.isVariant(order.orderType, 'triggerLimit')) {
87
+ return calculateAmountToTradeForTriggerLimit(market, order);
88
+ }
89
+ else if (types_1.isVariant(order.orderType, 'market')) {
90
+ // should never be a market order queued
91
+ return numericConstants_1.ZERO;
92
+ }
93
+ else {
94
+ return calculateAmountToTradeForTriggerMarket(market, order);
95
+ }
96
+ }
97
+ function calculateAmountToTradeForLimit(market, order) {
98
+ const [maxAmountToTrade, direction] = amm_1.calculateMaxBaseAssetAmountToTrade(market.amm, order.price);
99
+ // Check that directions are the same
100
+ const sameDirection = isSameDirection(direction, order.direction);
101
+ if (!sameDirection) {
102
+ return numericConstants_1.ZERO;
103
+ }
104
+ return maxAmountToTrade.gt(order.baseAssetAmount)
105
+ ? order.baseAssetAmount
106
+ : maxAmountToTrade;
107
+ }
108
+ exports.calculateAmountToTradeForLimit = calculateAmountToTradeForLimit;
109
+ function calculateAmountToTradeForTriggerLimit(market, order) {
110
+ if (order.baseAssetAmountFilled.eq(numericConstants_1.ZERO)) {
111
+ const baseAssetAmount = calculateAmountToTradeForTriggerMarket(market, order);
112
+ if (baseAssetAmount.eq(numericConstants_1.ZERO)) {
113
+ return numericConstants_1.ZERO;
114
+ }
115
+ }
116
+ return calculateAmountToTradeForLimit(market, order);
117
+ }
118
+ exports.calculateAmountToTradeForTriggerLimit = calculateAmountToTradeForTriggerLimit;
119
+ function isSameDirection(firstDirection, secondDirection) {
120
+ return ((types_1.isVariant(firstDirection, 'long') && types_1.isVariant(secondDirection, 'long')) ||
121
+ (types_1.isVariant(firstDirection, 'short') && types_1.isVariant(secondDirection, 'short')));
122
+ }
123
+ function calculateAmountToTradeForTriggerMarket(market, order) {
124
+ return isTriggerConditionSatisfied(market, order)
125
+ ? order.baseAssetAmount
126
+ : numericConstants_1.ZERO;
127
+ }
128
+ function isTriggerConditionSatisfied(market, order) {
129
+ const markPrice = market_1.calculateMarkPrice(market);
130
+ if (types_1.isVariant(order.triggerCondition, 'above')) {
131
+ return markPrice.gt(order.triggerPrice);
132
+ }
133
+ else {
134
+ return markPrice.lt(order.triggerPrice);
135
+ }
136
+ }
@@ -5,4 +5,3 @@ export declare class PythClient {
5
5
  constructor(connection: Connection);
6
6
  getPriceData(pricePublicKey: PublicKey): Promise<PriceData>;
7
7
  }
8
- //# sourceMappingURL=pythClient.d.ts.map
package/lib/pythClient.js CHANGED
@@ -18,7 +18,7 @@ class PythClient {
18
18
  getPriceData(pricePublicKey) {
19
19
  return __awaiter(this, void 0, void 0, function* () {
20
20
  const account = yield this.connection.getAccountInfo(pricePublicKey);
21
- return (0, client_1.parsePriceData)(account.data);
21
+ return client_1.parsePriceData(account.data);
22
22
  });
23
23
  }
24
24
  }
@@ -0,0 +1,3 @@
1
+ /// <reference types="node" />
2
+ import { AccountInfo } from '@solana/spl-token';
3
+ export declare function parseTokenAccount(data: Buffer): AccountInfo;
@@ -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;
@@ -6,4 +6,3 @@ export declare class DefaultTxSender implements TxSender {
6
6
  constructor(provider: Provider);
7
7
  send(tx: Transaction, additionalSigners?: Array<Signer>, opts?: ConfirmOptions): Promise<TransactionSignature>;
8
8
  }
9
- //# sourceMappingURL=defaultTxSender.d.ts.map
package/lib/tx/types.d.ts CHANGED
@@ -2,4 +2,3 @@ import { ConfirmOptions, Signer, Transaction, TransactionSignature } from '@sola
2
2
  export interface TxSender {
3
3
  send(tx: Transaction, additionalSigners?: Array<Signer>, opts?: ConfirmOptions): Promise<TransactionSignature>;
4
4
  }
5
- //# sourceMappingURL=types.d.ts.map
package/lib/tx/utils.d.ts CHANGED
@@ -1,3 +1,2 @@
1
1
  import { Transaction, TransactionInstruction } from '@solana/web3.js';
2
2
  export declare function wrapInTx(instruction: TransactionInstruction): Transaction;
3
- //# sourceMappingURL=utils.d.ts.map
package/lib/types.d.ts CHANGED
@@ -1,5 +1,6 @@
1
+ /// <reference types="bn.js" />
1
2
  import { PublicKey, Transaction } from '@solana/web3.js';
2
- import BN from 'bn.js';
3
+ import { BN } from '.';
3
4
  export declare class SwapDirection {
4
5
  static readonly ADD: {
5
6
  add: {};
@@ -24,6 +25,65 @@ export declare class OracleSource {
24
25
  switchboard: {};
25
26
  };
26
27
  }
28
+ export declare class OrderType {
29
+ static readonly LIMIT: {
30
+ limit: {};
31
+ };
32
+ static readonly TRIGGER_MARKET: {
33
+ triggerMarket: {};
34
+ };
35
+ static readonly TRIGGER_LIMIT: {
36
+ triggerLimit: {};
37
+ };
38
+ static readonly MARKET: {
39
+ market: {};
40
+ };
41
+ }
42
+ export declare class OrderStatus {
43
+ static readonly INIT: {
44
+ init: {};
45
+ };
46
+ static readonly OPEN: {
47
+ open: {};
48
+ };
49
+ }
50
+ export declare class OrderDiscountTier {
51
+ static readonly NONE: {
52
+ none: {};
53
+ };
54
+ static readonly FIRST: {
55
+ first: {};
56
+ };
57
+ static readonly SECOND: {
58
+ second: {};
59
+ };
60
+ static readonly THIRD: {
61
+ third: {};
62
+ };
63
+ static readonly FOURTH: {
64
+ fourth: {};
65
+ };
66
+ }
67
+ export declare class OrderAction {
68
+ static readonly PLACE: {
69
+ place: {};
70
+ };
71
+ static readonly CANCEL: {
72
+ cancel: {};
73
+ };
74
+ static readonly FILL: {
75
+ fill: {};
76
+ };
77
+ }
78
+ export declare class OrderTriggerCondition {
79
+ static readonly ABOVE: {
80
+ above: {};
81
+ };
82
+ static readonly BELOW: {
83
+ below: {};
84
+ };
85
+ }
86
+ export declare function isVariant(object: unknown, type: string): boolean;
27
87
  export declare enum TradeSide {
28
88
  None = 0,
29
89
  Buy = 1,
@@ -54,6 +114,11 @@ export declare type LiquidationHistoryAccount = {
54
114
  head: BN;
55
115
  liquidationRecords: LiquidationRecord[];
56
116
  };
117
+ export declare type OrderHistoryAccount = {
118
+ head: BN;
119
+ lastOrderId: BN;
120
+ orderRecords: OrderRecord[];
121
+ };
57
122
  export declare type DepositRecord = {
58
123
  ts: BN;
59
124
  recordId: BN;
@@ -147,6 +212,20 @@ export declare type LiquidationRecord = {
147
212
  unrealizedPnl: BN;
148
213
  marginRatio: BN;
149
214
  };
215
+ export declare type OrderRecord = {
216
+ ts: BN;
217
+ recordId: BN;
218
+ order: Order;
219
+ user: PublicKey;
220
+ authority: PublicKey;
221
+ action: OrderAction;
222
+ filler: PublicKey;
223
+ baseAssetAmountFilled: BN;
224
+ quoteAssetAmountFilled: BN;
225
+ fee: BN;
226
+ fillerReward: BN;
227
+ tradeRecordId: BN;
228
+ };
150
229
  export declare type StateAccount = {
151
230
  admin: PublicKey;
152
231
  fundingPaused: boolean;
@@ -184,8 +263,14 @@ export declare type StateAccount = {
184
263
  discountMint: PublicKey;
185
264
  oracleGuardRails: OracleGuardRails;
186
265
  maxDeposit: BN;
266
+ orderState: PublicKey;
187
267
  extendedCurveHistory: PublicKey;
188
268
  };
269
+ export declare type OrderStateAccount = {
270
+ orderHistory: PublicKey;
271
+ orderFillerRewardStructure: OrderFillerRewardStructure;
272
+ minOrderQuoteAssetAmount: BN;
273
+ };
189
274
  export declare type MarketsAccount = {
190
275
  accountIndex: BN;
191
276
  markets: Market[];
@@ -220,7 +305,8 @@ export declare type AMM = {
220
305
  totalFeeMinusDistributions: BN;
221
306
  totalFeeWithdrawn: BN;
222
307
  totalFee: BN;
223
- minimumTradeSize: BN;
308
+ minimumQuoteAssetTradeSize: BN;
309
+ minimumBaseAssetTradeSize: BN;
224
310
  lastOraclePrice: BN;
225
311
  };
226
312
  export declare type UserPosition = {
@@ -228,6 +314,7 @@ export declare type UserPosition = {
228
314
  lastCumulativeFundingRate: BN;
229
315
  marketIndex: BN;
230
316
  quoteAssetAmount: BN;
317
+ openOrders: BN;
231
318
  };
232
319
  export declare type UserPositionsAccount = {
233
320
  positions: UserPosition[];
@@ -239,6 +326,59 @@ export declare type UserAccount = {
239
326
  cumulativeDeposits: BN;
240
327
  positions: PublicKey;
241
328
  totalFeePaid: BN;
329
+ totalTokenDiscount: BN;
330
+ totalReferralReward: BN;
331
+ totalRefereeDiscount: BN;
332
+ };
333
+ export declare type UserOrdersAccount = {
334
+ orders: Order[];
335
+ user: PublicKey;
336
+ };
337
+ export declare type Order = {
338
+ status: OrderStatus;
339
+ orderType: OrderType;
340
+ ts: BN;
341
+ orderId: BN;
342
+ userOrderId: number;
343
+ marketIndex: BN;
344
+ price: BN;
345
+ userBaseAssetAmount: BN;
346
+ baseAssetAmount: BN;
347
+ baseAssetAmountFilled: BN;
348
+ quoteAssetAmount: BN;
349
+ quoteAssetAmountFilled: BN;
350
+ fee: BN;
351
+ direction: PositionDirection;
352
+ reduceOnly: boolean;
353
+ triggerPrice: BN;
354
+ triggerCondition: OrderTriggerCondition;
355
+ discountTier: OrderDiscountTier;
356
+ referrer: PublicKey;
357
+ postOnly: boolean;
358
+ immediateOrCancel: boolean;
359
+ oraclePriceOffset: BN;
360
+ };
361
+ export declare type OrderParams = {
362
+ orderType: OrderType;
363
+ userOrderId: number;
364
+ direction: PositionDirection;
365
+ quoteAssetAmount: BN;
366
+ baseAssetAmount: BN;
367
+ price: BN;
368
+ marketIndex: BN;
369
+ reduceOnly: boolean;
370
+ postOnly: boolean;
371
+ immediateOrCancel: boolean;
372
+ triggerPrice: BN;
373
+ triggerCondition: OrderTriggerCondition;
374
+ positionLimit: BN;
375
+ oraclePriceOffset: BN;
376
+ padding0: boolean;
377
+ padding1: BN;
378
+ optionalAccounts: {
379
+ discountToken: boolean;
380
+ referrer: boolean;
381
+ };
242
382
  };
243
383
  export interface IWallet {
244
384
  signTransaction(tx: Transaction): Promise<Transaction>;
@@ -289,4 +429,8 @@ export declare type OracleGuardRails = {
289
429
  };
290
430
  useForLiquidations: boolean;
291
431
  };
292
- //# sourceMappingURL=types.d.ts.map
432
+ export declare type OrderFillerRewardStructure = {
433
+ rewardNumerator: BN;
434
+ rewardDenominator: BN;
435
+ timeBasedRewardLowerBound: BN;
436
+ };
package/lib/types.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TradeSide = exports.OracleSource = exports.PositionDirection = exports.SwapDirection = void 0;
3
+ exports.TradeSide = exports.isVariant = exports.OrderTriggerCondition = exports.OrderAction = exports.OrderDiscountTier = exports.OrderStatus = exports.OrderType = exports.OracleSource = exports.PositionDirection = exports.SwapDirection = void 0;
4
4
  // # Utility Types / Enums / Constants
5
5
  class SwapDirection {
6
6
  }
@@ -17,6 +17,41 @@ class OracleSource {
17
17
  exports.OracleSource = OracleSource;
18
18
  OracleSource.PYTH = { pyth: {} };
19
19
  OracleSource.SWITCHBOARD = { switchboard: {} };
20
+ class OrderType {
21
+ }
22
+ exports.OrderType = OrderType;
23
+ OrderType.LIMIT = { limit: {} };
24
+ OrderType.TRIGGER_MARKET = { triggerMarket: {} };
25
+ OrderType.TRIGGER_LIMIT = { triggerLimit: {} };
26
+ OrderType.MARKET = { market: {} };
27
+ class OrderStatus {
28
+ }
29
+ exports.OrderStatus = OrderStatus;
30
+ OrderStatus.INIT = { init: {} };
31
+ OrderStatus.OPEN = { open: {} };
32
+ class OrderDiscountTier {
33
+ }
34
+ exports.OrderDiscountTier = OrderDiscountTier;
35
+ OrderDiscountTier.NONE = { none: {} };
36
+ OrderDiscountTier.FIRST = { first: {} };
37
+ OrderDiscountTier.SECOND = { second: {} };
38
+ OrderDiscountTier.THIRD = { third: {} };
39
+ OrderDiscountTier.FOURTH = { fourth: {} };
40
+ class OrderAction {
41
+ }
42
+ exports.OrderAction = OrderAction;
43
+ OrderAction.PLACE = { place: {} };
44
+ OrderAction.CANCEL = { cancel: {} };
45
+ OrderAction.FILL = { fill: {} };
46
+ class OrderTriggerCondition {
47
+ }
48
+ exports.OrderTriggerCondition = OrderTriggerCondition;
49
+ OrderTriggerCondition.ABOVE = { above: {} };
50
+ OrderTriggerCondition.BELOW = { below: {} };
51
+ function isVariant(object, type) {
52
+ return object.hasOwnProperty(type);
53
+ }
54
+ exports.isVariant = isVariant;
20
55
  var TradeSide;
21
56
  (function (TradeSide) {
22
57
  TradeSide[TradeSide["None"] = 0] = "None";
@@ -1,3 +1,2 @@
1
1
  import { Connection, Finality, PublicKey } from '@solana/web3.js';
2
2
  export declare function findComputeUnitConsumption(programId: PublicKey, connection: Connection, txSignature: string, commitment?: Finality): Promise<number[]>;
3
- //# sourceMappingURL=computeUnits.d.ts.map
package/lib/util/tps.d.ts CHANGED
@@ -1,3 +1,2 @@
1
1
  import { Connection, PublicKey } from '@solana/web3.js';
2
2
  export declare function estimateTps(programId: PublicKey, connection: Connection, failed: boolean): Promise<number>;
3
- //# sourceMappingURL=tps.d.ts.map
package/lib/wallet.d.ts CHANGED
@@ -7,4 +7,3 @@ export declare class Wallet implements IWallet {
7
7
  signAllTransactions(txs: Transaction[]): Promise<Transaction[]>;
8
8
  get publicKey(): PublicKey;
9
9
  }
10
- //# sourceMappingURL=wallet.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drift-labs/sdk",
3
- "version": "0.1.19-master.2",
3
+ "version": "0.1.21-master.4",
4
4
  "main": "lib/index.js",
5
5
  "types": "lib/index.d.ts",
6
6
  "author": "crispheaney",
@@ -10,6 +10,7 @@
10
10
  "url": "git@github.com:drift-labs/protocol-v1.git"
11
11
  },
12
12
  "scripts": {
13
+ "lint": "eslint './**/*.{ts,tsx}' --quiet",
13
14
  "build": "yarn clean && tsc",
14
15
  "clean": "rm -rf lib",
15
16
  "patch-and-pub": "npm version patch --force && npm publish"
@@ -31,8 +32,15 @@
31
32
  "@pythnetwork/client": "^2.5.1",
32
33
  "@solana/spl-token": "^0.1.6",
33
34
  "@solana/web3.js": "^1.22.0",
34
- "@types/bn.js": "^5.1.0",
35
- "strict-event-emitter-types": "^2.0.0"
35
+ "strict-event-emitter-types": "^2.0.0",
36
+ "uuid": "^8.3.2"
37
+ },
38
+ "devDependencies": {
39
+ "@typescript-eslint/eslint-plugin": "^4.28.0",
40
+ "@typescript-eslint/parser": "^4.28.0",
41
+ "eslint": "^7.29.0",
42
+ "eslint-config-prettier": "^8.3.0",
43
+ "eslint-plugin-prettier": "^3.4.0"
36
44
  },
37
45
  "description": "SDK for Drift Protocol v1",
38
46
  "engines": {