@drift-labs/common 1.0.59 → 1.0.61

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 (284) hide show
  1. package/lib/_deprecated/common-math.d.ts +10 -0
  2. package/lib/_deprecated/common-math.js +9 -0
  3. package/lib/_deprecated/common-math.js.map +1 -0
  4. package/lib/_deprecated/common-ui-utils.d.ts +248 -0
  5. package/lib/_deprecated/common-ui-utils.js +59 -0
  6. package/lib/_deprecated/common-ui-utils.js.map +1 -0
  7. package/lib/_deprecated/equality-checks.d.ts +2 -0
  8. package/lib/_deprecated/equality-checks.js +7 -0
  9. package/lib/_deprecated/equality-checks.js.map +1 -0
  10. package/lib/{common-ui-utils/market.d.ts → _deprecated/market-utils.d.ts} +5 -7
  11. package/lib/_deprecated/market-utils.js +18 -0
  12. package/lib/_deprecated/market-utils.js.map +1 -0
  13. package/lib/_deprecated/order-utils.d.ts +12 -0
  14. package/lib/_deprecated/order-utils.js +18 -0
  15. package/lib/_deprecated/order-utils.js.map +1 -0
  16. package/lib/_deprecated/trading-utils.d.ts +52 -0
  17. package/lib/_deprecated/trading-utils.js +27 -0
  18. package/lib/_deprecated/trading-utils.js.map +1 -0
  19. package/lib/_deprecated/user-utils.d.ts +17 -0
  20. package/lib/_deprecated/user-utils.js +12 -0
  21. package/lib/_deprecated/user-utils.js.map +1 -0
  22. package/lib/_deprecated/utils.d.ts +40 -0
  23. package/lib/_deprecated/utils.js +47 -0
  24. package/lib/_deprecated/utils.js.map +1 -0
  25. package/lib/clients/tvFeed.js +2 -2
  26. package/lib/clients/tvFeed.js.map +1 -1
  27. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js +8 -8
  28. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js.map +1 -1
  29. package/lib/drift/Drift/clients/AuthorityDrift/index.js +9 -9
  30. package/lib/drift/Drift/clients/AuthorityDrift/index.js.map +1 -1
  31. package/lib/drift/Drift/clients/CentralServerDrift/index.js +5 -4
  32. package/lib/drift/Drift/clients/CentralServerDrift/index.js.map +1 -1
  33. package/lib/drift/base/actions/trade/editOrder.d.ts +1 -1
  34. package/lib/drift/base/actions/trade/editOrder.js.map +1 -1
  35. package/lib/drift/base/actions/trade/margin.js +4 -4
  36. package/lib/drift/base/actions/trade/margin.js.map +1 -1
  37. package/lib/drift/base/actions/trade/openPerpOrder/auction.d.ts +1 -1
  38. package/lib/drift/base/actions/trade/openPerpOrder/auction.js +4 -3
  39. package/lib/drift/base/actions/trade/openPerpOrder/auction.js.map +1 -1
  40. package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.js +2 -2
  41. package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.js.map +1 -1
  42. package/lib/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.js +2 -2
  43. package/lib/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.js.map +1 -1
  44. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.d.ts +1 -1
  45. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js +4 -4
  46. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js.map +1 -1
  47. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.d.ts +4 -4
  48. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js +60 -32
  49. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js.map +1 -1
  50. package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js +4 -3
  51. package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js.map +1 -1
  52. package/lib/drift/base/actions/trade/openPerpOrder/positionMaxLeverage.js +2 -2
  53. package/lib/drift/base/actions/trade/openPerpOrder/positionMaxLeverage.js.map +1 -1
  54. package/lib/drift/base/actions/trade/openPerpOrder/types.d.ts +5 -0
  55. package/lib/drift/base/actions/trade/openPerpOrder/types.js.map +1 -1
  56. package/lib/drift/base/actions/user/create.js +2 -2
  57. package/lib/drift/base/actions/user/create.js.map +1 -1
  58. package/lib/drift/base/details/user/balances.js +2 -2
  59. package/lib/drift/base/details/user/balances.js.map +1 -1
  60. package/lib/drift/base/details/user/positions.js +2 -2
  61. package/lib/drift/base/details/user/positions.js.map +1 -1
  62. package/lib/index.d.ts +28 -28
  63. package/lib/index.js +44 -29
  64. package/lib/index.js.map +1 -1
  65. package/lib/utils/accounts/index.d.ts +6 -0
  66. package/lib/utils/accounts/index.js +23 -0
  67. package/lib/utils/accounts/index.js.map +1 -0
  68. package/lib/utils/accounts/init.d.ts +22 -0
  69. package/lib/utils/accounts/init.js +90 -0
  70. package/lib/utils/accounts/init.js.map +1 -0
  71. package/lib/utils/accounts/keys.d.ts +22 -0
  72. package/lib/utils/accounts/keys.js +36 -0
  73. package/lib/utils/accounts/keys.js.map +1 -0
  74. package/lib/utils/accounts/multiple.d.ts +14 -0
  75. package/lib/utils/accounts/multiple.js +45 -0
  76. package/lib/utils/accounts/multiple.js.map +1 -0
  77. package/lib/utils/accounts/signature.d.ts +6 -0
  78. package/lib/utils/accounts/signature.js +53 -0
  79. package/lib/utils/accounts/signature.js.map +1 -0
  80. package/lib/utils/accounts/subaccounts.d.ts +8 -0
  81. package/lib/utils/accounts/subaccounts.js +31 -0
  82. package/lib/utils/accounts/subaccounts.js.map +1 -0
  83. package/lib/utils/{WalletConnectionState.d.ts → accounts/wallet.d.ts} +7 -1
  84. package/lib/utils/{WalletConnectionState.js → accounts/wallet.js} +32 -2
  85. package/lib/utils/accounts/wallet.js.map +1 -0
  86. package/lib/utils/core/arrays.d.ts +2 -0
  87. package/lib/utils/core/arrays.js +25 -0
  88. package/lib/utils/core/arrays.js.map +1 -0
  89. package/lib/utils/core/async.d.ts +5 -0
  90. package/lib/utils/core/async.js +17 -0
  91. package/lib/utils/core/async.js.map +1 -0
  92. package/lib/utils/core/cache.d.ts +1 -0
  93. package/lib/utils/core/cache.js +40 -0
  94. package/lib/utils/core/cache.js.map +1 -0
  95. package/lib/utils/core/data-structures.d.ts +30 -0
  96. package/lib/utils/core/data-structures.js +84 -0
  97. package/lib/utils/core/data-structures.js.map +1 -0
  98. package/lib/utils/{equalityChecks.d.ts → core/equality.d.ts} +1 -1
  99. package/lib/utils/{equalityChecks.js → core/equality.js} +3 -3
  100. package/lib/utils/core/equality.js.map +1 -0
  101. package/lib/utils/core/fetch.js.map +1 -0
  102. package/lib/utils/core/index.d.ts +7 -0
  103. package/lib/utils/core/index.js +24 -0
  104. package/lib/utils/core/index.js.map +1 -0
  105. package/lib/utils/core/serialization.d.ts +30 -0
  106. package/lib/utils/core/serialization.js +92 -0
  107. package/lib/utils/core/serialization.js.map +1 -0
  108. package/lib/utils/{enum.js → enum/index.js} +1 -1
  109. package/lib/utils/enum/index.js.map +1 -0
  110. package/lib/utils/index.d.ts +11 -176
  111. package/lib/utils/index.js +25 -594
  112. package/lib/utils/index.js.map +1 -1
  113. package/lib/utils/markets/balances.d.ts +6 -0
  114. package/lib/utils/markets/balances.js +29 -0
  115. package/lib/utils/markets/balances.js.map +1 -0
  116. package/lib/utils/markets/config.d.ts +5 -0
  117. package/lib/utils/markets/config.js +24 -0
  118. package/lib/utils/markets/config.js.map +1 -0
  119. package/lib/utils/markets/index.d.ts +6 -0
  120. package/lib/utils/markets/index.js +23 -0
  121. package/lib/utils/markets/index.js.map +1 -0
  122. package/lib/utils/markets/interest.d.ts +25 -0
  123. package/lib/utils/markets/interest.js +65 -0
  124. package/lib/utils/markets/interest.js.map +1 -0
  125. package/lib/utils/markets/leverage.d.ts +12 -0
  126. package/lib/utils/markets/leverage.js +60 -0
  127. package/lib/utils/markets/leverage.js.map +1 -0
  128. package/lib/utils/markets/operations.d.ts +21 -0
  129. package/lib/utils/markets/operations.js +59 -0
  130. package/lib/utils/markets/operations.js.map +1 -0
  131. package/lib/utils/math/bignum.d.ts +3 -0
  132. package/lib/utils/math/bignum.js +16 -0
  133. package/lib/utils/math/bignum.js.map +1 -0
  134. package/lib/utils/math/bn.d.ts +7 -0
  135. package/lib/utils/math/bn.js +58 -0
  136. package/lib/utils/math/bn.js.map +1 -0
  137. package/lib/utils/math/index.d.ts +7 -0
  138. package/lib/utils/math/index.js +24 -0
  139. package/lib/utils/math/index.js.map +1 -0
  140. package/lib/utils/math/numbers.d.ts +13 -0
  141. package/lib/utils/math/numbers.js +56 -0
  142. package/lib/utils/math/numbers.js.map +1 -0
  143. package/lib/utils/math/precision.d.ts +19 -0
  144. package/lib/utils/math/precision.js +73 -0
  145. package/lib/utils/math/precision.js.map +1 -0
  146. package/lib/utils/math/price.d.ts +12 -0
  147. package/lib/utils/math/price.js +45 -0
  148. package/lib/utils/math/price.js.map +1 -0
  149. package/lib/utils/math/sort.d.ts +13 -0
  150. package/lib/utils/math/sort.js +33 -0
  151. package/lib/utils/math/sort.js.map +1 -0
  152. package/lib/utils/math/spread.d.ts +8 -0
  153. package/lib/utils/math/spread.js +87 -0
  154. package/lib/utils/math/spread.js.map +1 -0
  155. package/lib/utils/orderbook/index.js +4 -4
  156. package/lib/utils/orderbook/index.js.map +1 -1
  157. package/lib/utils/orders/filters.d.ts +7 -0
  158. package/lib/utils/orders/filters.js +31 -0
  159. package/lib/utils/orders/filters.js.map +1 -0
  160. package/lib/utils/orders/flags.d.ts +12 -0
  161. package/lib/utils/orders/flags.js +44 -0
  162. package/lib/utils/orders/flags.js.map +1 -0
  163. package/lib/utils/orders/index.d.ts +6 -0
  164. package/lib/utils/orders/index.js +23 -0
  165. package/lib/utils/orders/index.js.map +1 -0
  166. package/lib/utils/orders/labels.d.ts +4 -0
  167. package/lib/utils/orders/labels.js +122 -0
  168. package/lib/utils/orders/labels.js.map +1 -0
  169. package/lib/utils/orders/misc.d.ts +11 -0
  170. package/lib/utils/orders/misc.js +27 -0
  171. package/lib/utils/orders/misc.js.map +1 -0
  172. package/lib/utils/orders/oracle.d.ts +5 -0
  173. package/lib/utils/orders/oracle.js +23 -0
  174. package/lib/utils/orders/oracle.js.map +1 -0
  175. package/lib/utils/orders/sort.d.ts +38 -0
  176. package/lib/utils/orders/sort.js +83 -0
  177. package/lib/utils/orders/sort.js.map +1 -0
  178. package/lib/utils/positions/index.d.ts +2 -0
  179. package/lib/{common-ui-utils → utils/positions}/index.js +1 -5
  180. package/lib/utils/positions/index.js.map +1 -0
  181. package/lib/utils/positions/open.d.ts +4 -0
  182. package/lib/{common-ui-utils/user.js → utils/positions/open.js} +10 -81
  183. package/lib/utils/positions/open.js.map +1 -0
  184. package/lib/utils/positions/user.d.ts +37 -0
  185. package/lib/utils/positions/user.js +74 -0
  186. package/lib/utils/positions/user.js.map +1 -0
  187. package/lib/utils/settings/settings.js.map +1 -0
  188. package/lib/utils/strings/convert.d.ts +11 -0
  189. package/lib/utils/{strings.js → strings/convert.js} +2 -51
  190. package/lib/utils/strings/convert.js.map +1 -0
  191. package/lib/utils/strings/format.d.ts +14 -0
  192. package/lib/utils/strings/format.js +61 -0
  193. package/lib/utils/strings/format.js.map +1 -0
  194. package/lib/utils/strings/index.d.ts +4 -0
  195. package/lib/utils/strings/index.js +21 -0
  196. package/lib/utils/strings/index.js.map +1 -0
  197. package/lib/utils/strings/parse.d.ts +4 -0
  198. package/lib/utils/strings/parse.js +25 -0
  199. package/lib/utils/strings/parse.js.map +1 -0
  200. package/lib/utils/strings/status.d.ts +15 -0
  201. package/lib/utils/strings/status.js +21 -0
  202. package/lib/utils/strings/status.js.map +1 -0
  203. package/lib/utils/token/account.d.ts +16 -0
  204. package/lib/utils/token/account.js +36 -0
  205. package/lib/utils/token/account.js.map +1 -0
  206. package/lib/utils/{token.d.ts → token/address.d.ts} +2 -7
  207. package/lib/utils/token/address.js +30 -0
  208. package/lib/utils/token/address.js.map +1 -0
  209. package/lib/utils/token/index.d.ts +3 -0
  210. package/lib/utils/token/index.js +20 -0
  211. package/lib/utils/token/index.js.map +1 -0
  212. package/lib/utils/token/instructions.d.ts +3 -0
  213. package/lib/utils/token/instructions.js +17 -0
  214. package/lib/utils/token/instructions.js.map +1 -0
  215. package/lib/utils/trading/auction.d.ts +82 -0
  216. package/lib/utils/trading/auction.js +208 -0
  217. package/lib/utils/trading/auction.js.map +1 -0
  218. package/lib/utils/trading/index.d.ts +7 -0
  219. package/lib/utils/trading/index.js +24 -0
  220. package/lib/utils/trading/index.js.map +1 -0
  221. package/lib/utils/trading/leverage.d.ts +18 -0
  222. package/lib/utils/trading/leverage.js +79 -0
  223. package/lib/utils/trading/leverage.js.map +1 -0
  224. package/lib/utils/trading/liquidation.d.ts +22 -0
  225. package/lib/utils/trading/liquidation.js +67 -0
  226. package/lib/utils/trading/liquidation.js.map +1 -0
  227. package/lib/utils/trading/lp.d.ts +4 -0
  228. package/lib/utils/trading/lp.js +20 -0
  229. package/lib/utils/trading/lp.js.map +1 -0
  230. package/lib/utils/trading/pnl.d.ts +34 -0
  231. package/lib/utils/trading/pnl.js +88 -0
  232. package/lib/utils/trading/pnl.js.map +1 -0
  233. package/lib/utils/trading/price.d.ts +12 -0
  234. package/lib/utils/trading/price.js +36 -0
  235. package/lib/utils/trading/price.js.map +1 -0
  236. package/lib/utils/trading/size.d.ts +27 -0
  237. package/lib/utils/trading/size.js +83 -0
  238. package/lib/utils/trading/size.js.map +1 -0
  239. package/lib/utils/{validation.d.ts → validation/address.d.ts} +1 -2
  240. package/lib/utils/{validation.js → validation/address.js} +4 -6
  241. package/lib/utils/validation/address.js.map +1 -0
  242. package/lib/utils/validation/index.d.ts +3 -0
  243. package/lib/utils/validation/index.js +20 -0
  244. package/lib/utils/validation/index.js.map +1 -0
  245. package/lib/utils/validation/input.d.ts +3 -0
  246. package/lib/utils/validation/input.js +33 -0
  247. package/lib/utils/validation/input.js.map +1 -0
  248. package/lib/utils/validation/notional.d.ts +2 -0
  249. package/lib/utils/validation/notional.js +8 -0
  250. package/lib/utils/validation/notional.js.map +1 -0
  251. package/package.json +90 -3
  252. package/lib/common-ui-utils/commonUiUtils.d.ts +0 -251
  253. package/lib/common-ui-utils/commonUiUtils.js +0 -647
  254. package/lib/common-ui-utils/commonUiUtils.js.map +0 -1
  255. package/lib/common-ui-utils/index.d.ts +0 -6
  256. package/lib/common-ui-utils/index.js.map +0 -1
  257. package/lib/common-ui-utils/market.js +0 -134
  258. package/lib/common-ui-utils/market.js.map +0 -1
  259. package/lib/common-ui-utils/order.d.ts +0 -25
  260. package/lib/common-ui-utils/order.js +0 -191
  261. package/lib/common-ui-utils/order.js.map +0 -1
  262. package/lib/common-ui-utils/settings/settings.js.map +0 -1
  263. package/lib/common-ui-utils/trading.d.ts +0 -79
  264. package/lib/common-ui-utils/trading.js +0 -313
  265. package/lib/common-ui-utils/trading.js.map +0 -1
  266. package/lib/common-ui-utils/user.d.ts +0 -18
  267. package/lib/common-ui-utils/user.js.map +0 -1
  268. package/lib/utils/WalletConnectionState.js.map +0 -1
  269. package/lib/utils/enum.js.map +0 -1
  270. package/lib/utils/equalityChecks.js.map +0 -1
  271. package/lib/utils/fetch.js.map +0 -1
  272. package/lib/utils/math.d.ts +0 -31
  273. package/lib/utils/math.js +0 -181
  274. package/lib/utils/math.js.map +0 -1
  275. package/lib/utils/strings.d.ts +0 -34
  276. package/lib/utils/strings.js.map +0 -1
  277. package/lib/utils/token.js +0 -45
  278. package/lib/utils/token.js.map +0 -1
  279. package/lib/utils/validation.js.map +0 -1
  280. /package/lib/utils/{fetch.d.ts → core/fetch.d.ts} +0 -0
  281. /package/lib/utils/{fetch.js → core/fetch.js} +0 -0
  282. /package/lib/utils/{enum.d.ts → enum/index.d.ts} +0 -0
  283. /package/lib/{common-ui-utils → utils}/settings/settings.d.ts +0 -0
  284. /package/lib/{common-ui-utils → utils}/settings/settings.js +0 -0
@@ -1,647 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
- Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.COMMON_UI_UTILS = exports.abbreviateAddress = void 0;
30
- const sdk_1 = require("@drift-labs/sdk");
31
- const utils_1 = require("../utils");
32
- const web3_js_1 = require("@solana/web3.js");
33
- const bcryptjs_react_1 = __importDefault(require("bcryptjs-react"));
34
- const tweetnacl_1 = __importStar(require("tweetnacl"));
35
- const spl_token_1 = require("@solana/spl-token");
36
- const user_1 = require("./user");
37
- const trading_1 = require("./trading");
38
- const market_1 = require("./market");
39
- const order_1 = require("./order");
40
- const trade_1 = require("../constants/trade");
41
- // Cache for common UI string patterns to reduce memory allocation
42
- const uiStringCache = new Map();
43
- const MAX_UI_STRING_CACHE_SIZE = 2000;
44
- // Helper function to cache common string patterns
45
- function getCachedUiString(pattern, ...values) {
46
- const cacheKey = `${pattern}:${values.join(':')}`;
47
- if (uiStringCache.has(cacheKey)) {
48
- return uiStringCache.get(cacheKey);
49
- }
50
- let result;
51
- switch (pattern) {
52
- case 'abbreviate': {
53
- const [authString, length] = values;
54
- result = `${authString.slice(0, length)}\u2026${authString.slice(-length)}`;
55
- break;
56
- }
57
- case 'userKey': {
58
- const [userId, authority] = values;
59
- result = `${userId}_${authority}`;
60
- break;
61
- }
62
- case 'marketKey': {
63
- const [marketType, marketIndex] = values;
64
- result = `${marketType}_${marketIndex}`;
65
- break;
66
- }
67
- default:
68
- result = values.join('_');
69
- }
70
- // Cache if not too large
71
- if (uiStringCache.size < MAX_UI_STRING_CACHE_SIZE) {
72
- uiStringCache.set(cacheKey, result);
73
- }
74
- return result;
75
- }
76
- // When creating an account, try 5 times over 5 seconds to wait for the new account to hit the blockchain.
77
- const ACCOUNT_INITIALIZATION_RETRY_DELAY_MS = 1000;
78
- const ACCOUNT_INITIALIZATION_RETRY_ATTEMPTS = 5;
79
- const abbreviateAddress = (address, length = 4) => {
80
- if (!address)
81
- return '';
82
- const authString = address.toString();
83
- return getCachedUiString('abbreviate', authString, length);
84
- };
85
- exports.abbreviateAddress = abbreviateAddress;
86
- /**
87
- * Get a unique key for an authority's subaccount
88
- * @param userId
89
- * @param authority
90
- * @returns
91
- */
92
- const getUserKey = (userId, authority) => {
93
- if (userId == undefined || !authority)
94
- return '';
95
- return getCachedUiString('userKey', userId, authority.toString());
96
- };
97
- /**
98
- * Get the authority and subAccountId from a user's account key
99
- * @param key
100
- * @returns
101
- */
102
- const getIdAndAuthorityFromKey = (key) => {
103
- const splitKey = key === null || key === void 0 ? void 0 : key.split('_');
104
- if (!splitKey || splitKey.length !== 2)
105
- return { userId: undefined, userAuthority: undefined };
106
- return {
107
- userId: Number(splitKey[0]),
108
- userAuthority: new sdk_1.PublicKey(splitKey[1]),
109
- };
110
- };
111
- const fetchCurrentSubaccounts = (driftClient) => {
112
- return driftClient.getUsers().map((user) => user.getUserAccount());
113
- };
114
- const fetchUserClientsAndAccounts = (driftClient) => {
115
- const accounts = fetchCurrentSubaccounts(driftClient);
116
- const allUsersAndUserAccounts = accounts.map((acct) => {
117
- return {
118
- user: driftClient.getUser(acct.subAccountId, acct.authority),
119
- userAccount: acct,
120
- };
121
- });
122
- return allUsersAndUserAccounts;
123
- };
124
- const awaitAccountInitializationChainState = async (driftClient, userId, authority) => {
125
- var _a;
126
- const user = driftClient.getUser(userId, authority);
127
- if (!user.isSubscribed) {
128
- await user.subscribe();
129
- }
130
- let retryCount = 0;
131
- do {
132
- try {
133
- await updateUserAccount(user);
134
- if (((_a = user === null || user === void 0 ? void 0 : user.getUserAccountAndSlot()) === null || _a === void 0 ? void 0 : _a.data) !== undefined) {
135
- return true;
136
- }
137
- }
138
- catch (err) {
139
- retryCount++;
140
- await (0, utils_1.sleep)(ACCOUNT_INITIALIZATION_RETRY_DELAY_MS);
141
- }
142
- } while (retryCount < ACCOUNT_INITIALIZATION_RETRY_ATTEMPTS);
143
- throw new Error('awaitAccountInitializationFailed');
144
- };
145
- /**
146
- * Using your own callback to do the account initialization, this method will run the initialization step, switch to the drift user, await for the account to be available on chain, subscribe to the user account, and switch to the user account using the drift client.
147
- *
148
- * It provides extra callbacks to handle steps directly after the initialiation tx, and after fully initializing+subscribing to the account.
149
- *
150
- * Callbacks available:
151
- * - initializationStep: This callback should send the transaction to initialize the user account
152
- * - postInitializationStep: This callback will run after the successful initialization transaction, but before trying to load/subscribe to the new account
153
- * - handleSuccessStep: This callback will run after everything has initialized+subscribed successfully
154
- *
155
- * // TODO : Need to do the subscription step
156
- */
157
- const initializeAndSubscribeToNewUserAccount = async (driftClient, userIdToInit, authority, callbacks) => {
158
- var _a;
159
- await driftClient.addUser(userIdToInit, authority);
160
- const accountAlreadyExisted = await ((_a = driftClient
161
- .getUser(userIdToInit)) === null || _a === void 0 ? void 0 : _a.exists());
162
- // Do the account initialization step
163
- let result = await callbacks.initializationStep();
164
- // Fetch account to make sure it's loaded
165
- await updateUserAccount(driftClient.getUser(userIdToInit));
166
- if (!result) {
167
- return 'failed_initializationStep';
168
- }
169
- // Do the post-initialization step
170
- result = callbacks.postInitializationStep
171
- ? await callbacks.postInitializationStep()
172
- : result;
173
- if (!result) {
174
- return 'failed_postInitializationStep';
175
- }
176
- // Await the account initialization step to update the blockchain
177
- result = await awaitAccountInitializationChainState(driftClient, userIdToInit, authority);
178
- if (!result) {
179
- return 'failed_awaitAccountInitializationChainState';
180
- }
181
- await driftClient.switchActiveUser(userIdToInit, authority);
182
- // Do the subscription step
183
- // Run the success handler
184
- result = callbacks.handleSuccessStep
185
- ? await callbacks.handleSuccessStep(accountAlreadyExisted)
186
- : result;
187
- if (!result) {
188
- return 'failed_handleSuccessStep';
189
- }
190
- return 'ok';
191
- };
192
- async function updateUserAccount(user) {
193
- const publicKey = user.userAccountPublicKey;
194
- try {
195
- const dataAndContext = await user.driftClient.program.account.user.fetchAndContext(publicKey, 'processed');
196
- user.accountSubscriber.updateData(dataAndContext.data, dataAndContext.context.slot);
197
- }
198
- catch (e) {
199
- // noop
200
- }
201
- }
202
- const getMarketKey = (marketIndex, marketType) => getCachedUiString('marketKey', utils_1.ENUM_UTILS.toStr(marketType), marketIndex);
203
- /**
204
- * Creates an IWallet wrapper, with redundant methods. If a `walletPubKey` is passed in,
205
- * the `publicKey` will be based on that.
206
- */
207
- const createPlaceholderIWallet = (walletPubKey) => {
208
- const newKeypair = walletPubKey
209
- ? new web3_js_1.Keypair({
210
- publicKey: walletPubKey.toBytes(),
211
- secretKey: new web3_js_1.Keypair().publicKey.toBytes(),
212
- })
213
- : new web3_js_1.Keypair();
214
- const newWallet = {
215
- publicKey: newKeypair.publicKey,
216
- //@ts-ignore
217
- signTransaction: () => {
218
- return Promise.resolve();
219
- },
220
- //@ts-ignore
221
- signAllTransactions: () => {
222
- return Promise.resolve();
223
- },
224
- //@ts-ignore
225
- signMessage: () => {
226
- return Promise.resolve();
227
- },
228
- };
229
- return newWallet;
230
- };
231
- const getSignatureVerificationMessageForSettings = (authority, signTs) => {
232
- return new TextEncoder().encode(`Verify you are the owner of this wallet to update trade settings: \n${authority.toBase58()}\n\nThis signature will be valid for the next 30 minutes.\n\nTS: ${signTs.toString()}`);
233
- };
234
- const verifySignature = (signature, message, pubKey) => {
235
- return tweetnacl_1.sign.detached.verify(message, signature, pubKey.toBytes());
236
- };
237
- const hashSignature = async (signature) => {
238
- bcryptjs_react_1.default.setRandomFallback((num) => {
239
- return Array.from(tweetnacl_1.default.randomBytes(num));
240
- });
241
- const hashedSignature = await bcryptjs_react_1.default.hash(signature, bcryptjs_react_1.default.genSaltSync(10));
242
- return hashedSignature;
243
- };
244
- const compareSignatures = async (original, hashed) => {
245
- const signaturesMatch = await bcryptjs_react_1.default.compare(original, hashed);
246
- return signaturesMatch;
247
- };
248
- /* Trading-related helper functions */
249
- const calculateAverageEntryPrice = (quoteAssetAmount, baseAssetAmount) => {
250
- if (baseAssetAmount.eqZero())
251
- return sdk_1.BigNum.zero();
252
- return sdk_1.BigNum.from(quoteAssetAmount.val
253
- .mul(sdk_1.PRICE_PRECISION)
254
- .mul(sdk_1.AMM_TO_QUOTE_PRECISION_RATIO)
255
- .div(baseAssetAmount.shiftTo(sdk_1.BASE_PRECISION_EXP).val)
256
- .abs(), sdk_1.PRICE_PRECISION_EXP);
257
- };
258
- const getMarketOrderLimitPrice = ({ direction, baselinePrice, slippageTolerance, }) => {
259
- let limitPrice;
260
- if (!baselinePrice)
261
- return sdk_1.ZERO;
262
- if (slippageTolerance === 0)
263
- return baselinePrice;
264
- // infinite slippage capped at 15% currently
265
- if (slippageTolerance == undefined)
266
- slippageTolerance = 15;
267
- // if manually entered, cap at 99%
268
- if (slippageTolerance > 99)
269
- slippageTolerance = 99;
270
- let limitPricePctDiff;
271
- if ((0, sdk_1.isVariant)(direction, 'long')) {
272
- limitPricePctDiff = sdk_1.PRICE_PRECISION.add(new sdk_1.BN(slippageTolerance * sdk_1.PRICE_PRECISION.toNumber()).div(new sdk_1.BN(100)));
273
- limitPrice = baselinePrice.mul(limitPricePctDiff).div(sdk_1.PRICE_PRECISION);
274
- }
275
- else {
276
- limitPricePctDiff = sdk_1.PRICE_PRECISION.sub(new sdk_1.BN(slippageTolerance * sdk_1.PRICE_PRECISION.toNumber()).div(new sdk_1.BN(100)));
277
- limitPrice = baselinePrice.mul(limitPricePctDiff).div(sdk_1.PRICE_PRECISION);
278
- }
279
- return limitPrice;
280
- };
281
- const getMarketAuctionParams = ({ direction, startPriceFromSettings, endPriceFromSettings, limitPrice, duration, auctionStartPriceOffset, auctionEndPriceOffset, additionalEndPriceBuffer, forceUpToSlippage, bestBidPrice, bestAskPrice, ensureCrossingEndPrice, }) => {
282
- let auctionStartPrice;
283
- let auctionEndPrice;
284
- let constrainedBySlippage;
285
- const auctionEndPriceBuffer = sdk_1.BigNum.from(sdk_1.PRICE_PRECISION).scale(Math.abs(auctionEndPriceOffset * 100), 10000).val;
286
- const auctionStartPriceBuffer = sdk_1.BigNum.from(startPriceFromSettings).scale(Math.abs(auctionStartPriceOffset * 100), 10000).val;
287
- if ((0, sdk_1.isVariant)(direction, 'long')) {
288
- auctionStartPrice = startPriceFromSettings.sub(auctionStartPriceBuffer);
289
- const worstPriceToUse = sdk_1.BN.max(endPriceFromSettings, startPriceFromSettings); // Handles edge cases like if the worst price on the book was better than the oracle price, and the settings are asking to be relative to the oracle price
290
- auctionEndPrice = sdk_1.PRICE_PRECISION.add(auctionEndPriceBuffer)
291
- .mul(worstPriceToUse)
292
- .div(sdk_1.PRICE_PRECISION);
293
- constrainedBySlippage = limitPrice.lt(auctionEndPrice);
294
- // if forceUpToSlippage is passed, use max slippage price as end price
295
- if (forceUpToSlippage) {
296
- auctionEndPrice = limitPrice;
297
- constrainedBySlippage = false;
298
- }
299
- else {
300
- // use BEST (limit price, auction end price) as end price
301
- auctionEndPrice = sdk_1.BN.min(limitPrice, auctionEndPrice);
302
- }
303
- // apply additional buffer if provided
304
- if (additionalEndPriceBuffer) {
305
- auctionEndPrice = auctionEndPrice.add(additionalEndPriceBuffer);
306
- constrainedBySlippage = limitPrice.lt(auctionEndPrice);
307
- }
308
- // if ensureCrossingEndPrice is passed, ensure auction end price crosses bestAskPrice
309
- if (ensureCrossingEndPrice && bestAskPrice) {
310
- auctionEndPrice = sdk_1.BN.max(auctionEndPrice, bestAskPrice.add(auctionEndPriceBuffer));
311
- }
312
- auctionStartPrice = sdk_1.BN.min(auctionStartPrice, auctionEndPrice);
313
- }
314
- else {
315
- auctionStartPrice = startPriceFromSettings.add(auctionStartPriceBuffer);
316
- const worstPriceToUse = sdk_1.BN.min(endPriceFromSettings, startPriceFromSettings); // Handles edge cases like if the worst price on the book was better than the oracle price, and the settings are asking to be relative to the oracle price
317
- auctionEndPrice = sdk_1.PRICE_PRECISION.sub(auctionEndPriceBuffer)
318
- .mul(worstPriceToUse)
319
- .div(sdk_1.PRICE_PRECISION);
320
- constrainedBySlippage = limitPrice.gt(auctionEndPrice);
321
- // if forceUpToSlippage is passed, use max slippage price as end price
322
- if (forceUpToSlippage) {
323
- auctionEndPrice = limitPrice;
324
- constrainedBySlippage = false;
325
- }
326
- else {
327
- // use BEST (limit price, auction end price) as end price
328
- auctionEndPrice = sdk_1.BN.max(limitPrice, auctionEndPrice);
329
- }
330
- // apply additional buffer if provided
331
- if (additionalEndPriceBuffer) {
332
- auctionEndPrice = auctionEndPrice.sub(additionalEndPriceBuffer);
333
- constrainedBySlippage = limitPrice.gt(auctionEndPrice);
334
- }
335
- // if ensureCrossingEndPrice is passed, ensure auction end price crosses bestBidPrice
336
- if (ensureCrossingEndPrice && bestBidPrice) {
337
- auctionEndPrice = sdk_1.BN.min(auctionEndPrice, bestBidPrice.sub(auctionEndPriceBuffer));
338
- }
339
- auctionStartPrice = sdk_1.BN.max(auctionStartPrice, auctionEndPrice);
340
- }
341
- return {
342
- auctionStartPrice,
343
- auctionEndPrice,
344
- auctionDuration: duration,
345
- constrainedBySlippage,
346
- };
347
- };
348
- /**
349
- * Helper function which derived market order params from the CORE data that is used to create them.
350
- * @param param0
351
- * @returns
352
- */
353
- const deriveMarketOrderParams = ({ marketType, marketIndex, direction, maxLeverageSelected, maxLeverageOrderSize, baseAmount, reduceOnly, allowInfSlippage, oraclePrice, bestPrice, entryPrice, worstPrice, markPrice, auctionDuration, auctionStartPriceOffset, auctionEndPriceOffset, auctionStartPriceOffsetFrom, auctionEndPriceOffsetFrom, auctionPriceCaps, slippageTolerance, isOracleOrder, additionalEndPriceBuffer, forceUpToSlippage, bestBidPrice, bestAskPrice, ensureCrossingEndPrice, }) => {
354
- const priceObject = getPriceObject({
355
- oraclePrice,
356
- markPrice,
357
- bestOffer: bestPrice,
358
- entryPrice,
359
- worstPrice,
360
- direction,
361
- });
362
- // max slippage price
363
- let limitPrice = getMarketOrderLimitPrice({
364
- direction,
365
- baselinePrice: priceObject[auctionStartPriceOffsetFrom],
366
- slippageTolerance: allowInfSlippage ? undefined : slippageTolerance,
367
- });
368
- if (additionalEndPriceBuffer) {
369
- limitPrice = (0, sdk_1.isVariant)(direction, 'long')
370
- ? limitPrice.add(additionalEndPriceBuffer)
371
- : limitPrice.sub(additionalEndPriceBuffer);
372
- }
373
- const auctionParams = getMarketAuctionParams({
374
- direction,
375
- startPriceFromSettings: priceObject[auctionStartPriceOffsetFrom],
376
- endPriceFromSettings: priceObject[auctionEndPriceOffsetFrom],
377
- limitPrice,
378
- duration: auctionDuration,
379
- auctionStartPriceOffset: auctionStartPriceOffset,
380
- auctionEndPriceOffset: auctionEndPriceOffset,
381
- additionalEndPriceBuffer,
382
- forceUpToSlippage,
383
- bestBidPrice,
384
- bestAskPrice,
385
- ensureCrossingEndPrice,
386
- });
387
- let orderParams = (0, sdk_1.getMarketOrderParams)({
388
- marketType,
389
- marketIndex,
390
- direction,
391
- baseAssetAmount: maxLeverageSelected ? maxLeverageOrderSize : baseAmount,
392
- reduceOnly,
393
- price: allowInfSlippage ? undefined : limitPrice,
394
- ...auctionParams,
395
- });
396
- if (isOracleOrder) {
397
- // wont work if oracle is zero
398
- if (!oraclePrice.eq(sdk_1.ZERO)) {
399
- const oracleAuctionParams = (0, sdk_1.deriveOracleAuctionParams)({
400
- direction: direction,
401
- oraclePrice,
402
- auctionStartPrice: auctionParams.auctionStartPrice,
403
- auctionEndPrice: auctionParams.auctionEndPrice,
404
- limitPrice: auctionParams.auctionEndPrice,
405
- auctionPriceCaps: auctionPriceCaps,
406
- });
407
- orderParams = {
408
- ...orderParams,
409
- ...oracleAuctionParams,
410
- price: undefined,
411
- orderType: sdk_1.OrderType.ORACLE,
412
- };
413
- }
414
- }
415
- return orderParams;
416
- };
417
- const getLimitAuctionParams = ({ direction, inputPrice, startPriceFromSettings, duration, auctionStartPriceOffset, oraclePriceBands, }) => {
418
- let limitAuctionParams = trade_1.EMPTY_AUCTION_PARAMS;
419
- const auctionStartPriceBuffer = inputPrice.scale(Math.abs(auctionStartPriceOffset * 100), 10000).val;
420
- if ((0, sdk_1.isVariant)(direction, 'long') &&
421
- startPriceFromSettings &&
422
- startPriceFromSettings.lt(inputPrice.val) &&
423
- startPriceFromSettings.gt(sdk_1.ZERO)) {
424
- limitAuctionParams = {
425
- auctionStartPrice: startPriceFromSettings.sub(auctionStartPriceBuffer),
426
- auctionEndPrice: inputPrice.val,
427
- auctionDuration: duration,
428
- };
429
- }
430
- else if ((0, sdk_1.isVariant)(direction, 'short') &&
431
- startPriceFromSettings &&
432
- startPriceFromSettings.gt(sdk_1.ZERO) &&
433
- startPriceFromSettings.gt(inputPrice.val)) {
434
- limitAuctionParams = {
435
- auctionStartPrice: startPriceFromSettings.add(auctionStartPriceBuffer),
436
- auctionEndPrice: inputPrice.val,
437
- auctionDuration: duration,
438
- };
439
- }
440
- if (oraclePriceBands && limitAuctionParams.auctionDuration) {
441
- const [minPrice, maxPrice] = oraclePriceBands;
442
- // start and end price cant be outside of the oracle price bands
443
- limitAuctionParams.auctionStartPrice = sdk_1.BN.max(sdk_1.BN.min(limitAuctionParams.auctionStartPrice, maxPrice), minPrice);
444
- limitAuctionParams.auctionEndPrice = sdk_1.BN.max(sdk_1.BN.min(limitAuctionParams.auctionEndPrice, maxPrice), minPrice);
445
- }
446
- return limitAuctionParams;
447
- };
448
- const getPriceObject = ({ oraclePrice, bestOffer, entryPrice, worstPrice, markPrice, direction, }) => {
449
- let best;
450
- const nonZeroOptions = [oraclePrice, bestOffer, markPrice].filter((price) => price !== undefined && (price === null || price === void 0 ? void 0 : price.gt(sdk_1.ZERO)));
451
- if (nonZeroOptions.length === 0) {
452
- // console.error('Unable to create valid auction params');
453
- return {
454
- oracle: sdk_1.ZERO,
455
- bestOffer: sdk_1.ZERO,
456
- entry: sdk_1.ZERO,
457
- best: sdk_1.ZERO,
458
- worst: sdk_1.ZERO,
459
- mark: sdk_1.ZERO,
460
- };
461
- }
462
- if ((0, sdk_1.isVariant)(direction, 'long')) {
463
- best = nonZeroOptions.reduce((a, b) => (a.lt(b) ? a : b)); // lowest price
464
- }
465
- else {
466
- best = nonZeroOptions.reduce((a, b) => (a.gt(b) ? a : b)); // highest price
467
- }
468
- // if zero values come through, fallback to nonzero value
469
- return {
470
- oracle: (oraclePrice === null || oraclePrice === void 0 ? void 0 : oraclePrice.gt(sdk_1.ZERO)) ? oraclePrice : best,
471
- bestOffer: (bestOffer === null || bestOffer === void 0 ? void 0 : bestOffer.gt(sdk_1.ZERO)) ? bestOffer : best,
472
- entry: entryPrice,
473
- best,
474
- worst: worstPrice,
475
- mark: (markPrice === null || markPrice === void 0 ? void 0 : markPrice.gt(sdk_1.ZERO)) ? markPrice : best,
476
- };
477
- };
478
- /* LP Utils */
479
- const getLpSharesAmountForQuote = (driftClient, marketIndex, quoteAmount) => {
480
- const tenMillionBigNum = sdk_1.BigNum.fromPrint('10000000', sdk_1.QUOTE_PRECISION_EXP);
481
- const pricePerLpShare = sdk_1.BigNum.from(driftClient.getQuoteValuePerLpShare(marketIndex), sdk_1.QUOTE_PRECISION_EXP);
482
- return sdk_1.BigNum.from(quoteAmount, sdk_1.QUOTE_PRECISION_EXP)
483
- .scale(tenMillionBigNum.toNum(), pricePerLpShare.mul(tenMillionBigNum).toNum())
484
- .shiftTo(sdk_1.AMM_RESERVE_PRECISION_EXP);
485
- };
486
- const getQuoteValueForLpShares = (driftClient, marketIndex, sharesAmount) => {
487
- const pricePerLpShare = sdk_1.BigNum.from(driftClient.getQuoteValuePerLpShare(marketIndex), sdk_1.QUOTE_PRECISION_EXP).shiftTo(sdk_1.AMM_RESERVE_PRECISION_EXP);
488
- const lpSharesBigNum = sdk_1.BigNum.from(sharesAmount, sdk_1.AMM_RESERVE_PRECISION_EXP);
489
- return lpSharesBigNum.mul(pricePerLpShare).shiftTo(sdk_1.QUOTE_PRECISION_EXP);
490
- };
491
- const getTokenAddress = (mintAddress, userPubKey) => {
492
- return (0, spl_token_1.getAssociatedTokenAddress)(mintAddress, userPubKey, true);
493
- };
494
- const getBalanceFromTokenAccountResult = (account) => {
495
- var _a, _b, _c, _d;
496
- return (_d = (_c = (_b = (_a = account === null || account === void 0 ? void 0 : account.account.data) === null || _a === void 0 ? void 0 : _a.parsed) === null || _b === void 0 ? void 0 : _b.info) === null || _c === void 0 ? void 0 : _c.tokenAmount) === null || _d === void 0 ? void 0 : _d.uiAmount;
497
- };
498
- const getTokenAccount = async (connection, mintAddress, userPubKey) => {
499
- const tokenAccounts = await connection.getParsedTokenAccountsByOwner(userPubKey, { mint: mintAddress });
500
- const associatedAddress = await (0, spl_token_1.getAssociatedTokenAddress)(mintAddress, userPubKey, true);
501
- const targetAccount = tokenAccounts.value.filter((account) => account.pubkey.equals(associatedAddress))[0] || tokenAccounts.value[0];
502
- const anotherBalanceExists = tokenAccounts.value.find((account) => {
503
- return (!!getBalanceFromTokenAccountResult(account) &&
504
- !account.pubkey.equals(targetAccount.pubkey));
505
- });
506
- let tokenAccountWarning = false;
507
- if (anotherBalanceExists) {
508
- tokenAccountWarning = true;
509
- }
510
- return {
511
- tokenAccount: targetAccount,
512
- tokenAccountWarning,
513
- };
514
- };
515
- const getMultipleAccounts = async (connection, keys, commitment) => {
516
- const result = await Promise.all(chunks(keys, 99).map((chunk) => getMultipleAccountsCore(connection, chunk, commitment)));
517
- const array = result
518
- .map((a) => a.array
519
- .map((acc) => {
520
- if (!acc) {
521
- return undefined;
522
- }
523
- const { data, ...rest } = acc;
524
- const obj = {
525
- ...rest,
526
- data: Buffer.from(data[0], 'base64'),
527
- };
528
- return obj;
529
- })
530
- .filter((_) => _))
531
- .flat();
532
- return { keys, array };
533
- };
534
- const getMultipleAccountsCore = async (connection, keys, commitment) => {
535
- const args = connection._buildArgs([keys], commitment, 'base64');
536
- const unsafeRes = await connection._rpcRequest('getMultipleAccounts', args);
537
- if (unsafeRes.error) {
538
- throw new Error('failed to get info about account ' + unsafeRes.error.message);
539
- }
540
- if (unsafeRes.result.value) {
541
- const array = unsafeRes.result.value;
542
- return { keys, array };
543
- }
544
- // TODO: fix
545
- throw new Error();
546
- };
547
- const userExists = async (driftClient, userId, authority) => {
548
- let userAccountExists = false;
549
- try {
550
- const user = driftClient.getUser(userId, authority);
551
- userAccountExists = await user.exists();
552
- }
553
- catch (e) {
554
- // user account does not exist so we leave userAccountExists false
555
- }
556
- return userAccountExists;
557
- };
558
- function chunks(array, size) {
559
- return Array.apply(0, new Array(Math.ceil(array.length / size))).map((_, index) => array.slice(index * size, (index + 1) * size));
560
- }
561
- /**
562
- * Trim trailing zeros from a numerical string
563
- * @param str - numerical string to format
564
- * @param zerosToShow - max number of zeros to show after the decimal. Similar to number.toFixed() but won't trim non-zero values. Optional, default value is 1
565
- */
566
- const trimTrailingZeros = (str, zerosToShow = 1) => {
567
- // Ignore strings with no decimal point
568
- if (!str.includes('.'))
569
- return str;
570
- const sides = str.split('.');
571
- sides[1] = sides[1].replace(/0+$/, '');
572
- if (sides[1].length < zerosToShow) {
573
- const zerosToAdd = zerosToShow - sides[1].length;
574
- sides[1] = `${sides[1]}${Array(zerosToAdd).fill('0').join('')}`;
575
- }
576
- if (sides[1].length === 0) {
577
- return sides[0];
578
- }
579
- else {
580
- return sides.join('.');
581
- }
582
- };
583
- const formatTokenInputCurried = (setAmount, spotMarketConfig) => (newAmount) => {
584
- var _a, _b;
585
- if (isNaN(+newAmount))
586
- return;
587
- if (newAmount === '') {
588
- setAmount('');
589
- return;
590
- }
591
- const lastChar = newAmount[newAmount.length - 1];
592
- // if last char of string is a decimal point, don't format
593
- if (lastChar === '.') {
594
- setAmount(newAmount);
595
- return;
596
- }
597
- if (lastChar === '0') {
598
- // if last char of string is a zero in the decimal places, cut it off if it exceeds precision
599
- const numOfDigitsAfterDecimal = (_b = (_a = newAmount.split('.')[1]) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0;
600
- if (numOfDigitsAfterDecimal > spotMarketConfig.precisionExp.toNumber()) {
601
- setAmount(newAmount.slice(0, -1));
602
- }
603
- else {
604
- setAmount(newAmount);
605
- }
606
- return;
607
- }
608
- const formattedAmount = Number((+newAmount).toFixed(spotMarketConfig.precisionExp.toNumber()));
609
- setAmount(formattedAmount.toString());
610
- };
611
- // --- Export The Utils
612
- exports.COMMON_UI_UTILS = {
613
- abbreviateAddress: exports.abbreviateAddress,
614
- calculateAverageEntryPrice,
615
- chunks,
616
- compareSignatures,
617
- createPlaceholderIWallet,
618
- deriveMarketOrderParams,
619
- fetchCurrentSubaccounts,
620
- fetchUserClientsAndAccounts,
621
- formatTokenInputCurried,
622
- getBalanceFromTokenAccountResult,
623
- getIdAndAuthorityFromKey,
624
- getLimitAuctionParams,
625
- getLpSharesAmountForQuote,
626
- getMarketAuctionParams,
627
- getMarketKey,
628
- getMarketOrderLimitPrice,
629
- getMultipleAccounts,
630
- getMultipleAccountsCore,
631
- getPriceObject,
632
- getQuoteValueForLpShares,
633
- getSignatureVerificationMessageForSettings,
634
- getTokenAccount,
635
- getTokenAddress,
636
- getUserKey,
637
- hashSignature,
638
- initializeAndSubscribeToNewUserAccount,
639
- userExists,
640
- verifySignature,
641
- trimTrailingZeros,
642
- ...user_1.USER_UTILS,
643
- ...trading_1.TRADING_UTILS,
644
- ...market_1.MARKET_UTILS,
645
- ...order_1.ORDER_COMMON_UTILS,
646
- };
647
- //# sourceMappingURL=commonUiUtils.js.map