@d8x/perpetuals-sdk 0.7.4 → 0.7.6

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 (128) hide show
  1. package/dist/cjs/accountTrade.js +134 -239
  2. package/dist/cjs/accountTrade.js.map +1 -1
  3. package/dist/cjs/brokerTool.js +144 -290
  4. package/dist/cjs/brokerTool.js.map +1 -1
  5. package/dist/cjs/contracts/factories/ERC20__factory.js +9 -12
  6. package/dist/cjs/contracts/factories/ERC20__factory.js.map +1 -1
  7. package/dist/cjs/contracts/factories/IPerpetualManager__factory.js +9 -12
  8. package/dist/cjs/contracts/factories/IPerpetualManager__factory.js.map +1 -1
  9. package/dist/cjs/contracts/factories/LimitOrderBookFactory__factory.js +9 -12
  10. package/dist/cjs/contracts/factories/LimitOrderBookFactory__factory.js.map +1 -1
  11. package/dist/cjs/contracts/factories/LimitOrderBook__factory.js +9 -12
  12. package/dist/cjs/contracts/factories/LimitOrderBook__factory.js.map +1 -1
  13. package/dist/cjs/contracts/factories/MockTokenSwap__factory.js +9 -12
  14. package/dist/cjs/contracts/factories/MockTokenSwap__factory.js.map +1 -1
  15. package/dist/cjs/contracts/factories/ShareToken__factory.js +9 -12
  16. package/dist/cjs/contracts/factories/ShareToken__factory.js.map +1 -1
  17. package/dist/cjs/contracts/factories/zkevmTestnet/IPerpetualManager__factory.js +9 -12
  18. package/dist/cjs/contracts/factories/zkevmTestnet/IPerpetualManager__factory.js.map +1 -1
  19. package/dist/cjs/contracts/factories/zkevmTestnet/LimitOrderBookFactory__factory.js +9 -12
  20. package/dist/cjs/contracts/factories/zkevmTestnet/LimitOrderBookFactory__factory.js.map +1 -1
  21. package/dist/cjs/contracts/factories/zkevmTestnet/LimitOrderBook__factory.js +9 -12
  22. package/dist/cjs/contracts/factories/zkevmTestnet/LimitOrderBook__factory.js.map +1 -1
  23. package/dist/cjs/contracts/factories/zkevmTestnet/ShareToken__factory.js +9 -12
  24. package/dist/cjs/contracts/factories/zkevmTestnet/ShareToken__factory.js.map +1 -1
  25. package/dist/cjs/contracts/index.js +1 -1
  26. package/dist/cjs/d8XMath.d.ts +7 -0
  27. package/dist/cjs/d8XMath.js +81 -61
  28. package/dist/cjs/d8XMath.js.map +1 -1
  29. package/dist/cjs/index.js +11 -11
  30. package/dist/cjs/index.js.map +1 -1
  31. package/dist/cjs/liquidatorTool.js +80 -137
  32. package/dist/cjs/liquidatorTool.js.map +1 -1
  33. package/dist/cjs/liquidityProviderTool.js +33 -64
  34. package/dist/cjs/liquidityProviderTool.js.map +1 -1
  35. package/dist/cjs/marketData.d.ts +8 -1
  36. package/dist/cjs/marketData.js +641 -949
  37. package/dist/cjs/marketData.js.map +1 -1
  38. package/dist/cjs/nodeSDKTypes.d.ts +1 -0
  39. package/dist/cjs/nodeSDKTypes.js +10 -22
  40. package/dist/cjs/nodeSDKTypes.js.map +1 -1
  41. package/dist/cjs/orderReferrerTool.js +200 -321
  42. package/dist/cjs/orderReferrerTool.js.map +1 -1
  43. package/dist/cjs/perpetualDataHandler.d.ts +11 -0
  44. package/dist/cjs/perpetualDataHandler.js +422 -535
  45. package/dist/cjs/perpetualDataHandler.js.map +1 -1
  46. package/dist/cjs/perpetualEventHandler.js +129 -190
  47. package/dist/cjs/perpetualEventHandler.js.map +1 -1
  48. package/dist/cjs/priceFeeds.js +223 -335
  49. package/dist/cjs/priceFeeds.js.map +1 -1
  50. package/dist/cjs/traderDigests.js +20 -23
  51. package/dist/cjs/traderDigests.js.map +1 -1
  52. package/dist/cjs/traderInterface.js +54 -87
  53. package/dist/cjs/traderInterface.js.map +1 -1
  54. package/dist/cjs/triangulator.js +34 -38
  55. package/dist/cjs/triangulator.js.map +1 -1
  56. package/dist/cjs/utils.js +18 -32
  57. package/dist/cjs/utils.js.map +1 -1
  58. package/dist/cjs/version.d.ts +1 -1
  59. package/dist/cjs/version.js +1 -1
  60. package/dist/cjs/writeAccessHandler.js +78 -112
  61. package/dist/cjs/writeAccessHandler.js.map +1 -1
  62. package/dist/esm/accountTrade.js +126 -233
  63. package/dist/esm/accountTrade.js.map +1 -1
  64. package/dist/esm/brokerTool.js +136 -284
  65. package/dist/esm/brokerTool.js.map +1 -1
  66. package/dist/esm/contracts/factories/ERC20__factory.js +8 -12
  67. package/dist/esm/contracts/factories/ERC20__factory.js.map +1 -1
  68. package/dist/esm/contracts/factories/IPerpetualManager__factory.js +8 -12
  69. package/dist/esm/contracts/factories/IPerpetualManager__factory.js.map +1 -1
  70. package/dist/esm/contracts/factories/LimitOrderBookFactory__factory.js +8 -12
  71. package/dist/esm/contracts/factories/LimitOrderBookFactory__factory.js.map +1 -1
  72. package/dist/esm/contracts/factories/LimitOrderBook__factory.js +8 -12
  73. package/dist/esm/contracts/factories/LimitOrderBook__factory.js.map +1 -1
  74. package/dist/esm/contracts/factories/MockTokenSwap__factory.js +8 -12
  75. package/dist/esm/contracts/factories/MockTokenSwap__factory.js.map +1 -1
  76. package/dist/esm/contracts/factories/ShareToken__factory.js +8 -12
  77. package/dist/esm/contracts/factories/ShareToken__factory.js.map +1 -1
  78. package/dist/esm/contracts/factories/zkevmTestnet/IPerpetualManager__factory.js +8 -12
  79. package/dist/esm/contracts/factories/zkevmTestnet/IPerpetualManager__factory.js.map +1 -1
  80. package/dist/esm/contracts/factories/zkevmTestnet/LimitOrderBookFactory__factory.js +8 -12
  81. package/dist/esm/contracts/factories/zkevmTestnet/LimitOrderBookFactory__factory.js.map +1 -1
  82. package/dist/esm/contracts/factories/zkevmTestnet/LimitOrderBook__factory.js +8 -12
  83. package/dist/esm/contracts/factories/zkevmTestnet/LimitOrderBook__factory.js.map +1 -1
  84. package/dist/esm/contracts/factories/zkevmTestnet/ShareToken__factory.js +8 -12
  85. package/dist/esm/contracts/factories/zkevmTestnet/ShareToken__factory.js.map +1 -1
  86. package/dist/esm/d8XMath.d.ts +7 -0
  87. package/dist/esm/d8XMath.js +77 -58
  88. package/dist/esm/d8XMath.js.map +1 -1
  89. package/dist/esm/liquidatorTool.js +77 -136
  90. package/dist/esm/liquidatorTool.js.map +1 -1
  91. package/dist/esm/liquidityProviderTool.js +30 -63
  92. package/dist/esm/liquidityProviderTool.js.map +1 -1
  93. package/dist/esm/marketData.d.ts +8 -1
  94. package/dist/esm/marketData.js +632 -942
  95. package/dist/esm/marketData.js.map +1 -1
  96. package/dist/esm/nodeSDKTypes.d.ts +1 -0
  97. package/dist/esm/nodeSDKTypes.js +36 -48
  98. package/dist/esm/nodeSDKTypes.js.map +1 -1
  99. package/dist/esm/orderReferrerTool.js +194 -317
  100. package/dist/esm/orderReferrerTool.js.map +1 -1
  101. package/dist/esm/perpetualDataHandler.d.ts +11 -0
  102. package/dist/esm/perpetualDataHandler.js +413 -528
  103. package/dist/esm/perpetualDataHandler.js.map +1 -1
  104. package/dist/esm/perpetualEventHandler.js +126 -188
  105. package/dist/esm/perpetualEventHandler.js.map +1 -1
  106. package/dist/esm/priceFeeds.js +218 -332
  107. package/dist/esm/priceFeeds.js.map +1 -1
  108. package/dist/esm/traderDigests.js +15 -19
  109. package/dist/esm/traderDigests.js.map +1 -1
  110. package/dist/esm/traderInterface.js +48 -83
  111. package/dist/esm/traderInterface.js.map +1 -1
  112. package/dist/esm/triangulator.js +34 -39
  113. package/dist/esm/triangulator.js.map +1 -1
  114. package/dist/esm/utils.js +16 -30
  115. package/dist/esm/utils.js.map +1 -1
  116. package/dist/esm/version.d.ts +1 -1
  117. package/dist/esm/version.js +1 -1
  118. package/dist/esm/version.js.map +1 -1
  119. package/dist/esm/writeAccessHandler.js +70 -106
  120. package/dist/esm/writeAccessHandler.js.map +1 -1
  121. package/package.json +1 -1
  122. package/src/d8XMath.ts +21 -0
  123. package/src/liquidityProviderTool.ts +5 -4
  124. package/src/marketData.ts +26 -0
  125. package/src/nodeSDKTypes.ts +1 -0
  126. package/src/perpetualDataHandler.ts +27 -0
  127. package/src/version.ts +1 -1
  128. package/src/writeAccessHandler.ts +3 -3
@@ -1,4 +1,3 @@
1
- import { __awaiter, __extends, __generator, __read, __spreadArray, __values } from "tslib";
2
1
  import { BigNumber } from "@ethersproject/bignumber";
3
2
  import { StaticJsonRpcProvider } from "@ethersproject/providers";
4
3
  import { formatUnits } from "@ethersproject/units";
@@ -13,8 +12,7 @@ import { contractSymbolToSymbol, toBytes4 } from "./utils";
13
12
  * No gas required for the queries here.
14
13
  * @extends PerpetualDataHandler
15
14
  */
16
- var MarketData = /** @class */ (function (_super) {
17
- __extends(MarketData, _super);
15
+ export default class MarketData extends PerpetualDataHandler {
18
16
  /**
19
17
  * Constructor
20
18
  * @param {NodeSDKConfig} config Configuration object, see
@@ -33,8 +31,8 @@ var MarketData = /** @class */ (function (_super) {
33
31
  * main();
34
32
  *
35
33
  */
36
- function MarketData(config) {
37
- return _super.call(this, config) || this;
34
+ constructor(config) {
35
+ super(config);
38
36
  }
39
37
  /**
40
38
  * Initialize the marketData-Class with this function
@@ -42,43 +40,33 @@ var MarketData = /** @class */ (function (_super) {
42
40
  * about perpetual currencies
43
41
  * @param provider optional provider
44
42
  */
45
- MarketData.prototype.createProxyInstance = function (provider, overrides) {
46
- return __awaiter(this, void 0, void 0, function () {
47
- return __generator(this, function (_a) {
48
- switch (_a.label) {
49
- case 0:
50
- if (provider == undefined) {
51
- this.provider = new StaticJsonRpcProvider(this.nodeURL);
52
- }
53
- else {
54
- this.provider = provider;
55
- }
56
- return [4 /*yield*/, this.initContractsAndData(this.provider, overrides)];
57
- case 1:
58
- _a.sent();
59
- return [2 /*return*/];
60
- }
61
- });
62
- });
63
- };
43
+ async createProxyInstance(provider, overrides) {
44
+ if (provider == undefined) {
45
+ this.provider = new StaticJsonRpcProvider(this.nodeURL);
46
+ }
47
+ else {
48
+ this.provider = provider;
49
+ }
50
+ await this.initContractsAndData(this.provider, overrides);
51
+ }
64
52
  /**
65
53
  * Get the proxy address
66
54
  * @returns Address of the perpetual proxy contract
67
55
  */
68
- MarketData.prototype.getProxyAddress = function () {
56
+ getProxyAddress() {
69
57
  if (this.proxyContract == null) {
70
58
  throw Error("no proxy contract initialized. Use createProxyInstance().");
71
59
  }
72
60
  return this.proxyContract.address;
73
- };
61
+ }
74
62
  /**
75
63
  * Convert the smart contract output of an order into a convenient format of type "Order"
76
64
  * @param smOrder SmartContractOrder, as obtained e.g., by PerpetualLimitOrderCreated event
77
65
  * @returns more convenient format of order, type "Order"
78
66
  */
79
- MarketData.prototype.smartContractOrderToOrder = function (smOrder) {
67
+ smartContractOrderToOrder(smOrder) {
80
68
  return PerpetualDataHandler.fromSmartContractOrder(smOrder, this.symbolToPerpStaticInfo);
81
- };
69
+ }
82
70
  /**
83
71
  * Get contract instance. Useful for event listening.
84
72
  * @example
@@ -97,12 +85,12 @@ var MarketData = /** @class */ (function (_super) {
97
85
  *
98
86
  * @returns read-only proxy instance
99
87
  */
100
- MarketData.prototype.getReadOnlyProxyInstance = function () {
88
+ getReadOnlyProxyInstance() {
101
89
  if (this.proxyContract == null) {
102
90
  throw Error("no proxy contract initialized. Use createProxyInstance().");
103
91
  }
104
92
  return this.proxyContract;
105
- };
93
+ }
106
94
  /**
107
95
  * Information about the products traded in the exchange.
108
96
  * @example
@@ -121,20 +109,12 @@ var MarketData = /** @class */ (function (_super) {
121
109
  *
122
110
  * @returns {ExchangeInfo} Array of static data for all the pools and perpetuals in the system.
123
111
  */
124
- MarketData.prototype.exchangeInfo = function (overrides) {
125
- return __awaiter(this, void 0, void 0, function () {
126
- return __generator(this, function (_a) {
127
- switch (_a.label) {
128
- case 0:
129
- if (this.proxyContract == null) {
130
- throw Error("no proxy contract initialized. Use createProxyInstance().");
131
- }
132
- return [4 /*yield*/, MarketData._exchangeInfo(this.proxyContract, this.poolStaticInfos, this.symbolToPerpStaticInfo, this.perpetualIdToSymbol, this.nestedPerpetualIDs, this.symbolList, this.priceFeedGetter, overrides)];
133
- case 1: return [2 /*return*/, _a.sent()];
134
- }
135
- });
136
- });
137
- };
112
+ async exchangeInfo(overrides) {
113
+ if (this.proxyContract == null) {
114
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
115
+ }
116
+ return await MarketData._exchangeInfo(this.proxyContract, this.poolStaticInfos, this.symbolToPerpStaticInfo, this.perpetualIdToSymbol, this.nestedPerpetualIDs, this.symbolList, this.priceFeedGetter, overrides);
117
+ }
138
118
  /**
139
119
  * All open orders for a trader-address and a symbol.
140
120
  * @param {string} traderAddr Address of the trader for which we get the open orders.
@@ -156,58 +136,40 @@ var MarketData = /** @class */ (function (_super) {
156
136
  *
157
137
  * @returns For each perpetual an array of open orders and corresponding order-ids.
158
138
  */
159
- MarketData.prototype.openOrders = function (traderAddr, symbol, overrides) {
160
- return __awaiter(this, void 0, void 0, function () {
161
- var resArray, symbols, prom, k, p, res;
162
- return __generator(this, function (_a) {
163
- switch (_a.label) {
164
- case 0:
165
- resArray = [];
166
- if (!(symbol.split("-").length == 1)) return [3 /*break*/, 2];
167
- symbols = this.getPerpetualSymbolsInPool(symbol);
168
- prom = [];
169
- for (k = 0; k < symbols.length; k++) {
170
- p = this._openOrdersOfPerpetual(traderAddr, symbols[k], overrides);
171
- prom.push(p);
172
- }
173
- return [4 /*yield*/, Promise.all(prom)];
174
- case 1:
175
- resArray = _a.sent();
176
- return [3 /*break*/, 4];
177
- case 2: return [4 /*yield*/, this._openOrdersOfPerpetual(traderAddr, symbol, overrides)];
178
- case 3:
179
- res = _a.sent();
180
- resArray.push(res);
181
- _a.label = 4;
182
- case 4: return [2 /*return*/, resArray];
183
- }
184
- });
185
- });
186
- };
139
+ async openOrders(traderAddr, symbol, overrides) {
140
+ // open orders requested only for given symbol
141
+ let resArray = [];
142
+ if (symbol.split("-").length == 1) {
143
+ // pool symbol
144
+ const symbols = this.getPerpetualSymbolsInPool(symbol);
145
+ let prom = [];
146
+ for (let k = 0; k < symbols.length; k++) {
147
+ let p = this._openOrdersOfPerpetual(traderAddr, symbols[k], overrides);
148
+ prom.push(p);
149
+ }
150
+ resArray = await Promise.all(prom);
151
+ }
152
+ else {
153
+ let res = await this._openOrdersOfPerpetual(traderAddr, symbol, overrides);
154
+ resArray.push(res);
155
+ }
156
+ return resArray;
157
+ }
187
158
  /**
188
159
  * All open orders for a trader-address and a given perpetual symbol.
189
160
  * @param {string} traderAddr Address of the trader for which we get the open orders.
190
161
  * @param {string} symbol perpetual-symbol of the form ETH-USD-MATIC
191
162
  * @returns open orders and order ids
192
163
  */
193
- MarketData.prototype._openOrdersOfPerpetual = function (traderAddr, symbol, overrides) {
194
- return __awaiter(this, void 0, void 0, function () {
195
- var orderBookContract, _a, orders, digests;
196
- return __generator(this, function (_b) {
197
- switch (_b.label) {
198
- case 0:
199
- orderBookContract = this.getOrderBookContract(symbol);
200
- return [4 /*yield*/, Promise.all([
201
- this.openOrdersOnOrderBook(traderAddr, orderBookContract, overrides),
202
- MarketData.orderIdsOfTrader(traderAddr, orderBookContract, overrides),
203
- ])];
204
- case 1:
205
- _a = __read.apply(void 0, [_b.sent(), 2]), orders = _a[0], digests = _a[1];
206
- return [2 /*return*/, { orders: orders, orderIds: digests }];
207
- }
208
- });
209
- });
210
- };
164
+ async _openOrdersOfPerpetual(traderAddr, symbol, overrides) {
165
+ // open orders requested only for given symbol
166
+ let orderBookContract = this.getOrderBookContract(symbol);
167
+ let [orders, digests] = await Promise.all([
168
+ this.openOrdersOnOrderBook(traderAddr, orderBookContract, overrides),
169
+ MarketData.orderIdsOfTrader(traderAddr, orderBookContract, overrides),
170
+ ]);
171
+ return { orders: orders, orderIds: digests };
172
+ }
211
173
  /**
212
174
  * Information about the position open by a given trader in a given perpetual contract, or
213
175
  * for all perpetuals in a pool
@@ -230,59 +192,38 @@ var MarketData = /** @class */ (function (_super) {
230
192
  *
231
193
  * @returns {MarginAccount[]} Array of position risks of trader.
232
194
  */
233
- MarketData.prototype.positionRisk = function (traderAddr, symbol, overrides) {
234
- return __awaiter(this, void 0, void 0, function () {
235
- var resArray, symbols, prom, k, p, res;
236
- return __generator(this, function (_a) {
237
- switch (_a.label) {
238
- case 0:
239
- if (this.proxyContract == null) {
240
- throw Error("no proxy contract initialized. Use createProxyInstance().");
241
- }
242
- resArray = [];
243
- if (!(symbol.split("-").length == 1)) return [3 /*break*/, 2];
244
- symbols = this.getPerpetualSymbolsInPool(symbol);
245
- prom = [];
246
- for (k = 0; k < symbols.length; k++) {
247
- p = this._positionRiskForTraderInPerpetual(traderAddr, symbols[k], overrides);
248
- prom.push(p);
249
- }
250
- return [4 /*yield*/, Promise.all(prom)];
251
- case 1:
252
- resArray = _a.sent();
253
- return [3 /*break*/, 4];
254
- case 2: return [4 /*yield*/, this._positionRiskForTraderInPerpetual(traderAddr, symbol, overrides)];
255
- case 3:
256
- res = _a.sent();
257
- resArray.push(res);
258
- _a.label = 4;
259
- case 4: return [2 /*return*/, resArray];
260
- }
261
- });
262
- });
263
- };
195
+ async positionRisk(traderAddr, symbol, overrides) {
196
+ if (this.proxyContract == null) {
197
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
198
+ }
199
+ let resArray = [];
200
+ if (symbol.split("-").length == 1) {
201
+ // pool symbol
202
+ const symbols = this.getPerpetualSymbolsInPool(symbol);
203
+ let prom = [];
204
+ for (let k = 0; k < symbols.length; k++) {
205
+ let p = this._positionRiskForTraderInPerpetual(traderAddr, symbols[k], overrides);
206
+ prom.push(p);
207
+ }
208
+ resArray = await Promise.all(prom);
209
+ }
210
+ else {
211
+ let res = await this._positionRiskForTraderInPerpetual(traderAddr, symbol, overrides);
212
+ resArray.push(res);
213
+ }
214
+ return resArray;
215
+ }
264
216
  /**
265
217
  * Information about the position open by a given trader in a given perpetual contract.
266
218
  * @param {string} traderAddr Address of the trader for which we get the position risk.
267
219
  * @param {string} symbol perpetual symbol of the form ETH-USD-MATIC
268
220
  * @returns MarginAccount struct for the trader
269
221
  */
270
- MarketData.prototype._positionRiskForTraderInPerpetual = function (traderAddr, symbol, overrides) {
271
- return __awaiter(this, void 0, void 0, function () {
272
- var obj, mgnAcct;
273
- return __generator(this, function (_a) {
274
- switch (_a.label) {
275
- case 0: return [4 /*yield*/, this.priceFeedGetter.fetchPricesForPerpetual(symbol)];
276
- case 1:
277
- obj = _a.sent();
278
- return [4 /*yield*/, PerpetualDataHandler.getMarginAccount(traderAddr, symbol, this.symbolToPerpStaticInfo, this.proxyContract, [obj.idxPrices[0], obj.idxPrices[1]], overrides)];
279
- case 2:
280
- mgnAcct = _a.sent();
281
- return [2 /*return*/, mgnAcct];
282
- }
283
- });
284
- });
285
- };
222
+ async _positionRiskForTraderInPerpetual(traderAddr, symbol, overrides) {
223
+ let obj = await this.priceFeedGetter.fetchPricesForPerpetual(symbol);
224
+ let mgnAcct = await PerpetualDataHandler.getMarginAccount(traderAddr, symbol, this.symbolToPerpStaticInfo, this.proxyContract, [obj.idxPrices[0], obj.idxPrices[1]], overrides);
225
+ return mgnAcct;
226
+ }
286
227
  /**
287
228
  * Estimates what the position risk will be if a given order is executed.
288
229
  * @param traderAddr Address of trader
@@ -291,119 +232,118 @@ var MarketData = /** @class */ (function (_super) {
291
232
  * @param indexPriceInfo Index prices and market status (open/closed)
292
233
  * @returns Position risk after trade
293
234
  */
294
- MarketData.prototype.positionRiskOnTrade = function (traderAddr, order, account, indexPriceInfo, overrides) {
295
- var _a, _b, _c, _d, _e;
296
- return __awaiter(this, void 0, void 0, function () {
297
- var obj, lotSizeBC, perpetualState, _f, S2, S3, Sm, currentMarginCashCC, currentPositionBC, currentLockedInQC, tradeAmountBC, newPositionBC, newSide, tradePrice, _g, poolId, exchangeFeeTbps, exchangeFeeCC, brokerFeeCC, referralFeeCC, isClose, isOpen, isFlip, keepPositionLvgOnClose, traderDepositCC, targetLvg, initialMarginRate, _h, b0, pos0, deltaCashCC, deltaLockedQC, pnl, newLockedInValueQC, newMarginCashCC, newEntryPrice, newMarginBalanceCC, newLeverage, _j, S2Liq, S3Liq, tau, newPositionRisk;
298
- return __generator(this, function (_k) {
299
- switch (_k.label) {
300
- case 0:
301
- if (this.proxyContract == null) {
302
- throw Error("no proxy contract initialized. Use createProxyInstance().");
303
- }
304
- if (!(account == undefined)) return [3 /*break*/, 2];
305
- return [4 /*yield*/, this.positionRisk(traderAddr, order.symbol, overrides)];
306
- case 1:
307
- account = (_k.sent())[0];
308
- _k.label = 2;
309
- case 2:
310
- if (!(indexPriceInfo == undefined)) return [3 /*break*/, 4];
311
- return [4 /*yield*/, this.priceFeedGetter.fetchPricesForPerpetual(account.symbol)];
312
- case 3:
313
- obj = _k.sent();
314
- indexPriceInfo = [obj.idxPrices[0], obj.idxPrices[1], obj.mktClosed[0], obj.mktClosed[1]];
315
- _k.label = 4;
316
- case 4:
317
- lotSizeBC = MarketData._getLotSize(account.symbol, this.symbolToPerpStaticInfo);
318
- // Too small, no change to account
319
- if (Math.abs(order.quantity) < lotSizeBC) {
320
- return [2 /*return*/, { newPositionRisk: account, orderCost: 0 }];
321
- }
322
- return [4 /*yield*/, this.getPerpetualState(order.symbol, indexPriceInfo, overrides)];
323
- case 5:
324
- perpetualState = _k.sent();
325
- _f = __read([perpetualState.indexPrice, perpetualState.collToQuoteIndexPrice, perpetualState.markPrice], 3), S2 = _f[0], S3 = _f[1], Sm = _f[2];
326
- currentMarginCashCC = account.collateralCC;
327
- currentPositionBC = (account.side == BUY_SIDE ? 1 : -1) * account.positionNotionalBaseCCY;
328
- currentLockedInQC = account.entryPrice * currentPositionBC;
329
- tradeAmountBC = Math.abs(order.quantity) * (order.side == BUY_SIDE ? 1 : -1);
330
- newPositionBC = currentPositionBC + tradeAmountBC;
331
- if (Math.abs(newPositionBC) < 10 * lotSizeBC) {
332
- // fully closed
333
- tradeAmountBC = -currentPositionBC;
334
- newPositionBC = 0;
335
- }
336
- newSide = newPositionBC > 0 ? BUY_SIDE : newPositionBC < 0 ? SELL_SIDE : CLOSED_SIDE;
337
- if (!((_a = order.limitPrice) !== null && _a !== void 0)) return [3 /*break*/, 6];
338
- _g = _a;
339
- return [3 /*break*/, 8];
340
- case 6: return [4 /*yield*/, this.getPerpetualPrice(order.symbol, tradeAmountBC, [indexPriceInfo[0], indexPriceInfo[1]], overrides)];
341
- case 7:
342
- _g = (_k.sent());
343
- _k.label = 8;
344
- case 8:
345
- tradePrice = _g;
346
- poolId = PerpetualDataHandler._getPoolIdFromSymbol(order.symbol, this.poolStaticInfos);
347
- return [4 /*yield*/, this.proxyContract.queryExchangeFee(poolId, traderAddr, (_b = order.brokerAddr) !== null && _b !== void 0 ? _b : ZERO_ADDRESS, overrides || {})];
348
- case 9:
349
- exchangeFeeTbps = _k.sent();
350
- exchangeFeeCC = (Math.abs(tradeAmountBC) * exchangeFeeTbps * 1e-5 * S2) / S3;
351
- brokerFeeCC = (Math.abs(tradeAmountBC) * ((_c = order.brokerFeeTbps) !== null && _c !== void 0 ? _c : 0) * 1e-5 * S2) / S3;
352
- referralFeeCC = this.symbolToPerpStaticInfo.get(account.symbol).referralRebate;
353
- isClose = newPositionBC == 0 || newPositionBC * tradeAmountBC < 0;
354
- isOpen = newPositionBC != 0 && (currentPositionBC == 0 || tradeAmountBC * currentPositionBC > 0);
355
- isFlip = Math.abs(newPositionBC) > Math.abs(currentPositionBC) && !isOpen;
356
- keepPositionLvgOnClose = ((_d = order.keepPositionLvg) !== null && _d !== void 0 ? _d : false) && !isOpen;
357
- if (order.leverage == undefined || newPositionBC == 0 || (!isOpen && !isFlip && !keepPositionLvgOnClose)) {
358
- traderDepositCC = 0;
359
- targetLvg = 0;
360
- }
361
- else {
362
- initialMarginRate = this.symbolToPerpStaticInfo.get(account.symbol).initialMarginRate;
363
- targetLvg = isFlip || isOpen ? (_e = order.leverage) !== null && _e !== void 0 ? _e : 1 / initialMarginRate : 0;
364
- _h = __read(isOpen ? [0, 0] : [account.collateralCC, currentPositionBC], 2), b0 = _h[0], pos0 = _h[1];
365
- traderDepositCC = getDepositAmountForLvgTrade(b0, pos0, tradeAmountBC, targetLvg, tradePrice, S3, Sm);
366
- // fees are paid from wallet in this case
367
- traderDepositCC += exchangeFeeCC + brokerFeeCC + referralFeeCC;
368
- }
369
- deltaCashCC = (-tradeAmountBC * (tradePrice - S2)) / S3;
370
- deltaLockedQC = tradeAmountBC * S2;
371
- if (isClose) {
372
- pnl = account.entryPrice * tradeAmountBC - deltaLockedQC;
373
- deltaLockedQC += pnl;
374
- deltaCashCC += pnl / S3;
375
- }
376
- // funding and fees
377
- deltaCashCC = deltaCashCC + account.unrealizedFundingCollateralCCY - exchangeFeeCC - brokerFeeCC - referralFeeCC;
378
- newLockedInValueQC = currentLockedInQC + deltaLockedQC;
379
- newMarginCashCC = currentMarginCashCC + deltaCashCC + traderDepositCC;
380
- newEntryPrice = newPositionBC == 0 ? 0 : Math.abs(newLockedInValueQC / newPositionBC);
381
- newMarginBalanceCC = newMarginCashCC + (newPositionBC * Sm - newLockedInValueQC) / S3;
382
- newLeverage = newPositionBC == 0
383
- ? 0
384
- : newMarginBalanceCC <= 0
385
- ? Infinity
386
- : (Math.abs(newPositionBC) * Sm) / S3 / newMarginBalanceCC;
387
- _j = __read(MarketData._getLiquidationParams(account.symbol, newLockedInValueQC, newPositionBC, newMarginCashCC, Sm, S3, this.symbolToPerpStaticInfo), 3), S2Liq = _j[0], S3Liq = _j[1], tau = _j[2];
388
- newPositionRisk = {
389
- symbol: account.symbol,
390
- positionNotionalBaseCCY: Math.abs(newPositionBC),
391
- side: newSide,
392
- entryPrice: newEntryPrice,
393
- leverage: newLeverage,
394
- markPrice: Sm,
395
- unrealizedPnlQuoteCCY: newPositionBC * Sm - newLockedInValueQC,
396
- unrealizedFundingCollateralCCY: 0,
397
- collateralCC: newMarginCashCC,
398
- collToQuoteConversion: S3,
399
- liquidationPrice: [S2Liq, S3Liq],
400
- liquidationLvg: 1 / tau,
401
- };
402
- return [2 /*return*/, { newPositionRisk: newPositionRisk, orderCost: traderDepositCC }];
403
- }
404
- });
405
- });
406
- };
235
+ async positionRiskOnTrade(traderAddr, order, account, indexPriceInfo, overrides) {
236
+ if (this.proxyContract == null) {
237
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
238
+ }
239
+ // fetch undefined data
240
+ if (account == undefined) {
241
+ account = (await this.positionRisk(traderAddr, order.symbol, overrides))[0];
242
+ }
243
+ if (indexPriceInfo == undefined) {
244
+ let obj = await this.priceFeedGetter.fetchPricesForPerpetual(account.symbol);
245
+ indexPriceInfo = [obj.idxPrices[0], obj.idxPrices[1], obj.mktClosed[0], obj.mktClosed[1]];
246
+ }
247
+ let lotSizeBC = MarketData._getLotSize(account.symbol, this.symbolToPerpStaticInfo);
248
+ // Too small, no change to account
249
+ if (Math.abs(order.quantity) < lotSizeBC) {
250
+ return { newPositionRisk: account, orderCost: 0 };
251
+ }
252
+ // Current state:
253
+ // perp (for FXs and such)
254
+ let perpetualState = await this.getPerpetualState(order.symbol, indexPriceInfo, overrides);
255
+ let [S2, S3, Sm] = [perpetualState.indexPrice, perpetualState.collToQuoteIndexPrice, perpetualState.markPrice];
256
+ // cash in margin account: upon trading, unpaid funding will be realized
257
+ let currentMarginCashCC = account.collateralCC;
258
+ // signed position, still correct if side is closed (==0)
259
+ let currentPositionBC = (account.side == BUY_SIDE ? 1 : -1) * account.positionNotionalBaseCCY;
260
+ // signed locked-in value
261
+ let currentLockedInQC = account.entryPrice * currentPositionBC;
262
+ // New trader state:
263
+ // signed trade amount
264
+ let tradeAmountBC = Math.abs(order.quantity) * (order.side == BUY_SIDE ? 1 : -1);
265
+ // signed position
266
+ let newPositionBC = currentPositionBC + tradeAmountBC;
267
+ if (Math.abs(newPositionBC) < 10 * lotSizeBC) {
268
+ // fully closed
269
+ tradeAmountBC = -currentPositionBC;
270
+ newPositionBC = 0;
271
+ }
272
+ let newSide = newPositionBC > 0 ? BUY_SIDE : newPositionBC < 0 ? SELL_SIDE : CLOSED_SIDE;
273
+ // price for this order = limit price (conservative) if given, else the current perp price
274
+ let tradePrice = order.limitPrice ??
275
+ (await this.getPerpetualPrice(order.symbol, tradeAmountBC, [indexPriceInfo[0], indexPriceInfo[1]], overrides));
276
+ // fees
277
+ let poolId = PerpetualDataHandler._getPoolIdFromSymbol(order.symbol, this.poolStaticInfos);
278
+ let exchangeFeeTbps = await this.proxyContract.queryExchangeFee(poolId, traderAddr, order.brokerAddr ?? ZERO_ADDRESS, overrides || {});
279
+ let exchangeFeeCC = (Math.abs(tradeAmountBC) * exchangeFeeTbps * 1e-5 * S2) / S3;
280
+ let brokerFeeCC = (Math.abs(tradeAmountBC) * (order.brokerFeeTbps ?? 0) * 1e-5 * S2) / S3;
281
+ let referralFeeCC = this.symbolToPerpStaticInfo.get(account.symbol).referralRebate;
282
+ // Trade type:
283
+ let isClose = newPositionBC == 0 || newPositionBC * tradeAmountBC < 0;
284
+ let isOpen = newPositionBC != 0 && (currentPositionBC == 0 || tradeAmountBC * currentPositionBC > 0); // regular open, no flip
285
+ let isFlip = Math.abs(newPositionBC) > Math.abs(currentPositionBC) && !isOpen; // flip position sign, not fully closed
286
+ let keepPositionLvgOnClose = (order.keepPositionLvg ?? false) && !isOpen;
287
+ // Contract: _doMarginCollateralActions
288
+ // No collateral actions if
289
+ // 1) leverage is not set or
290
+ // 2) fully closed after trade or
291
+ // 3) is a partial closing, it doesn't flip, and keep lvg flag is not set
292
+ let traderDepositCC;
293
+ let targetLvg;
294
+ if (order.leverage == undefined || newPositionBC == 0 || (!isOpen && !isFlip && !keepPositionLvgOnClose)) {
295
+ traderDepositCC = 0;
296
+ targetLvg = 0;
297
+ }
298
+ else {
299
+ // 1) opening and flipping trades need to specify a leverage: default to max if not given
300
+ // 2) for others it's ignored, set target to 0
301
+ let initialMarginRate = this.symbolToPerpStaticInfo.get(account.symbol).initialMarginRate;
302
+ targetLvg = isFlip || isOpen ? order.leverage ?? 1 / initialMarginRate : 0;
303
+ let [b0, pos0] = isOpen ? [0, 0] : [account.collateralCC, currentPositionBC];
304
+ traderDepositCC = getDepositAmountForLvgTrade(b0, pos0, tradeAmountBC, targetLvg, tradePrice, S3, Sm);
305
+ // fees are paid from wallet in this case
306
+ traderDepositCC += exchangeFeeCC + brokerFeeCC + referralFeeCC;
307
+ }
308
+ // Contract: _executeTrade
309
+ let deltaCashCC = (-tradeAmountBC * (tradePrice - S2)) / S3;
310
+ let deltaLockedQC = tradeAmountBC * S2;
311
+ if (isClose) {
312
+ let pnl = account.entryPrice * tradeAmountBC - deltaLockedQC;
313
+ deltaLockedQC += pnl;
314
+ deltaCashCC += pnl / S3;
315
+ }
316
+ // funding and fees
317
+ deltaCashCC = deltaCashCC + account.unrealizedFundingCollateralCCY - exchangeFeeCC - brokerFeeCC - referralFeeCC;
318
+ // New cash, locked-in, entry price & leverage after trade
319
+ let newLockedInValueQC = currentLockedInQC + deltaLockedQC;
320
+ let newMarginCashCC = currentMarginCashCC + deltaCashCC + traderDepositCC;
321
+ let newEntryPrice = newPositionBC == 0 ? 0 : Math.abs(newLockedInValueQC / newPositionBC);
322
+ let newMarginBalanceCC = newMarginCashCC + (newPositionBC * Sm - newLockedInValueQC) / S3;
323
+ let newLeverage = newPositionBC == 0
324
+ ? 0
325
+ : newMarginBalanceCC <= 0
326
+ ? Infinity
327
+ : (Math.abs(newPositionBC) * Sm) / S3 / newMarginBalanceCC;
328
+ // Liquidation params
329
+ let [S2Liq, S3Liq, tau] = MarketData._getLiquidationParams(account.symbol, newLockedInValueQC, newPositionBC, newMarginCashCC, Sm, S3, this.symbolToPerpStaticInfo);
330
+ // New position risk
331
+ let newPositionRisk = {
332
+ symbol: account.symbol,
333
+ positionNotionalBaseCCY: Math.abs(newPositionBC),
334
+ side: newSide,
335
+ entryPrice: newEntryPrice,
336
+ leverage: newLeverage,
337
+ markPrice: Sm,
338
+ unrealizedPnlQuoteCCY: newPositionBC * Sm - newLockedInValueQC,
339
+ unrealizedFundingCollateralCCY: 0,
340
+ collateralCC: newMarginCashCC,
341
+ collToQuoteConversion: S3,
342
+ liquidationPrice: [S2Liq, S3Liq],
343
+ liquidationLvg: 1 / tau,
344
+ };
345
+ return { newPositionRisk: newPositionRisk, orderCost: traderDepositCC };
346
+ }
407
347
  /**
408
348
  * Estimates what the position risk will be if given amount of collateral is added/removed from the account.
409
349
  * @param traderAddr Address of trader
@@ -411,90 +351,80 @@ var MarketData = /** @class */ (function (_super) {
411
351
  * @param currentPositionRisk Position risk before
412
352
  * @returns {MarginAccount} Position risk after
413
353
  */
414
- MarketData.prototype.positionRiskOnCollateralAction = function (deltaCollateral, account, indexPriceInfo, overrides) {
415
- return __awaiter(this, void 0, void 0, function () {
416
- var obj, perpetualState, _a, S2, S3, Sm, positionBC, lockedInQC, newMarginCashCC, newMarginBalanceCC, newLeverage, _b, S2Liq, S3Liq, tau, newPositionRisk;
417
- return __generator(this, function (_c) {
418
- switch (_c.label) {
419
- case 0:
420
- if (this.proxyContract == null) {
421
- throw Error("no proxy contract initialized. Use createProxyInstance().");
422
- }
423
- if (deltaCollateral + account.collateralCC + account.unrealizedFundingCollateralCCY < 0) {
424
- throw Error("not enough margin to remove");
425
- }
426
- if (!(indexPriceInfo == undefined)) return [3 /*break*/, 2];
427
- return [4 /*yield*/, this.priceFeedGetter.fetchPricesForPerpetual(account.symbol)];
428
- case 1:
429
- obj = _c.sent();
430
- indexPriceInfo = [obj.idxPrices[0], obj.idxPrices[1], obj.mktClosed[0], obj.mktClosed[1]];
431
- _c.label = 2;
432
- case 2: return [4 /*yield*/, this.getPerpetualState(account.symbol, indexPriceInfo, overrides)];
433
- case 3:
434
- perpetualState = _c.sent();
435
- _a = __read([perpetualState.indexPrice, perpetualState.collToQuoteIndexPrice, perpetualState.markPrice], 3), S2 = _a[0], S3 = _a[1], Sm = _a[2];
436
- // no position: just increase collateral and kill liquidation vars
437
- if (account.positionNotionalBaseCCY == 0) {
438
- return [2 /*return*/, {
439
- symbol: account.symbol,
440
- positionNotionalBaseCCY: account.positionNotionalBaseCCY,
441
- side: account.side,
442
- entryPrice: account.entryPrice,
443
- leverage: account.leverage,
444
- markPrice: Sm,
445
- unrealizedPnlQuoteCCY: account.unrealizedPnlQuoteCCY,
446
- unrealizedFundingCollateralCCY: account.unrealizedFundingCollateralCCY,
447
- collateralCC: account.collateralCC + deltaCollateral,
448
- collToQuoteConversion: S3,
449
- liquidationPrice: [0, undefined],
450
- liquidationLvg: Infinity,
451
- }];
452
- }
453
- positionBC = account.positionNotionalBaseCCY * (account.side == BUY_SIDE ? 1 : -1);
454
- lockedInQC = account.entryPrice * positionBC;
455
- newMarginCashCC = account.collateralCC + deltaCollateral;
456
- newMarginBalanceCC = newMarginCashCC + account.unrealizedFundingCollateralCCY + (positionBC * Sm - lockedInQC) / S3;
457
- if (newMarginBalanceCC <= 0) {
458
- return [2 /*return*/, {
459
- symbol: account.symbol,
460
- positionNotionalBaseCCY: account.positionNotionalBaseCCY,
461
- side: account.side,
462
- entryPrice: account.entryPrice,
463
- leverage: Infinity,
464
- markPrice: Sm,
465
- unrealizedPnlQuoteCCY: account.unrealizedPnlQuoteCCY,
466
- unrealizedFundingCollateralCCY: account.unrealizedFundingCollateralCCY,
467
- collateralCC: newMarginCashCC,
468
- collToQuoteConversion: S3,
469
- liquidationPrice: [S2, S3],
470
- liquidationLvg: 0,
471
- }];
472
- }
473
- newLeverage = (Math.abs(positionBC) * Sm) / S3 / newMarginBalanceCC;
474
- _b = __read(MarketData._getLiquidationParams(account.symbol, lockedInQC, positionBC, newMarginCashCC, Sm, S3, this.symbolToPerpStaticInfo), 3), S2Liq = _b[0], S3Liq = _b[1], tau = _b[2];
475
- newPositionRisk = {
476
- symbol: account.symbol,
477
- positionNotionalBaseCCY: account.positionNotionalBaseCCY,
478
- side: account.side,
479
- entryPrice: account.entryPrice,
480
- leverage: newLeverage,
481
- markPrice: Sm,
482
- unrealizedPnlQuoteCCY: account.unrealizedPnlQuoteCCY,
483
- unrealizedFundingCollateralCCY: account.unrealizedFundingCollateralCCY,
484
- collateralCC: newMarginCashCC,
485
- collToQuoteConversion: S3,
486
- liquidationPrice: [S2Liq, S3Liq],
487
- liquidationLvg: 1 / tau,
488
- };
489
- return [2 /*return*/, newPositionRisk];
490
- }
491
- });
492
- });
493
- };
494
- MarketData._getLiquidationParams = function (symbol, lockedInQC, signedPositionBC, marginCashCC, markPrice, collToQuoteConversion, symbolToPerpStaticInfo) {
495
- var S2Liq, S3Liq;
496
- var tau = symbolToPerpStaticInfo.get(symbol).maintenanceMarginRate;
497
- var ccyType = symbolToPerpStaticInfo.get(symbol).collateralCurrencyType;
354
+ async positionRiskOnCollateralAction(deltaCollateral, account, indexPriceInfo, overrides) {
355
+ if (this.proxyContract == null) {
356
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
357
+ }
358
+ if (deltaCollateral + account.collateralCC + account.unrealizedFundingCollateralCCY < 0) {
359
+ throw Error("not enough margin to remove");
360
+ }
361
+ if (indexPriceInfo == undefined) {
362
+ let obj = await this.priceFeedGetter.fetchPricesForPerpetual(account.symbol);
363
+ indexPriceInfo = [obj.idxPrices[0], obj.idxPrices[1], obj.mktClosed[0], obj.mktClosed[1]];
364
+ }
365
+ let perpetualState = await this.getPerpetualState(account.symbol, indexPriceInfo, overrides);
366
+ let [S2, S3, Sm] = [perpetualState.indexPrice, perpetualState.collToQuoteIndexPrice, perpetualState.markPrice];
367
+ // no position: just increase collateral and kill liquidation vars
368
+ if (account.positionNotionalBaseCCY == 0) {
369
+ return {
370
+ symbol: account.symbol,
371
+ positionNotionalBaseCCY: account.positionNotionalBaseCCY,
372
+ side: account.side,
373
+ entryPrice: account.entryPrice,
374
+ leverage: account.leverage,
375
+ markPrice: Sm,
376
+ unrealizedPnlQuoteCCY: account.unrealizedPnlQuoteCCY,
377
+ unrealizedFundingCollateralCCY: account.unrealizedFundingCollateralCCY,
378
+ collateralCC: account.collateralCC + deltaCollateral,
379
+ collToQuoteConversion: S3,
380
+ liquidationPrice: [0, undefined],
381
+ liquidationLvg: Infinity,
382
+ };
383
+ }
384
+ let positionBC = account.positionNotionalBaseCCY * (account.side == BUY_SIDE ? 1 : -1);
385
+ let lockedInQC = account.entryPrice * positionBC;
386
+ let newMarginCashCC = account.collateralCC + deltaCollateral;
387
+ let newMarginBalanceCC = newMarginCashCC + account.unrealizedFundingCollateralCCY + (positionBC * Sm - lockedInQC) / S3;
388
+ if (newMarginBalanceCC <= 0) {
389
+ return {
390
+ symbol: account.symbol,
391
+ positionNotionalBaseCCY: account.positionNotionalBaseCCY,
392
+ side: account.side,
393
+ entryPrice: account.entryPrice,
394
+ leverage: Infinity,
395
+ markPrice: Sm,
396
+ unrealizedPnlQuoteCCY: account.unrealizedPnlQuoteCCY,
397
+ unrealizedFundingCollateralCCY: account.unrealizedFundingCollateralCCY,
398
+ collateralCC: newMarginCashCC,
399
+ collToQuoteConversion: S3,
400
+ liquidationPrice: [S2, S3],
401
+ liquidationLvg: 0,
402
+ };
403
+ }
404
+ let newLeverage = (Math.abs(positionBC) * Sm) / S3 / newMarginBalanceCC;
405
+ // Liquidation params
406
+ let [S2Liq, S3Liq, tau] = MarketData._getLiquidationParams(account.symbol, lockedInQC, positionBC, newMarginCashCC, Sm, S3, this.symbolToPerpStaticInfo);
407
+ // New position risk
408
+ let newPositionRisk = {
409
+ symbol: account.symbol,
410
+ positionNotionalBaseCCY: account.positionNotionalBaseCCY,
411
+ side: account.side,
412
+ entryPrice: account.entryPrice,
413
+ leverage: newLeverage,
414
+ markPrice: Sm,
415
+ unrealizedPnlQuoteCCY: account.unrealizedPnlQuoteCCY,
416
+ unrealizedFundingCollateralCCY: account.unrealizedFundingCollateralCCY,
417
+ collateralCC: newMarginCashCC,
418
+ collToQuoteConversion: S3,
419
+ liquidationPrice: [S2Liq, S3Liq],
420
+ liquidationLvg: 1 / tau,
421
+ };
422
+ return newPositionRisk;
423
+ }
424
+ static _getLiquidationParams(symbol, lockedInQC, signedPositionBC, marginCashCC, markPrice, collToQuoteConversion, symbolToPerpStaticInfo) {
425
+ let S2Liq, S3Liq;
426
+ let tau = symbolToPerpStaticInfo.get(symbol).maintenanceMarginRate;
427
+ let ccyType = symbolToPerpStaticInfo.get(symbol).collateralCurrencyType;
498
428
  if (ccyType == CollaterlCCY.BASE) {
499
429
  S2Liq = calculateLiquidationPriceCollateralBase(lockedInQC, signedPositionBC, marginCashCC, tau);
500
430
  S3Liq = S2Liq;
@@ -510,90 +440,53 @@ var MarketData = /** @class */ (function (_super) {
510
440
  S2Liq = S2Liq < 0 ? 0 : S2Liq;
511
441
  S3Liq = S3Liq && S3Liq < 0 ? 0 : S3Liq;
512
442
  return [S2Liq, S3Liq, tau];
513
- };
443
+ }
514
444
  /**
515
445
  * Gets the wallet balance in the collateral currency corresponding to a given perpetual symbol.
516
446
  * @param address Address to check
517
447
  * @param symbol Symbol of the form ETH-USD-MATIC.
518
448
  * @returns Balance
519
449
  */
520
- MarketData.prototype.getWalletBalance = function (address, symbol, overrides) {
521
- return __awaiter(this, void 0, void 0, function () {
522
- var poolIdx, marginTokenAddr, token, walletBalance, decimals;
523
- return __generator(this, function (_a) {
524
- switch (_a.label) {
525
- case 0:
526
- poolIdx = this.getPoolStaticInfoIndexFromSymbol(symbol);
527
- marginTokenAddr = this.poolStaticInfos[poolIdx].poolMarginTokenAddr;
528
- token = ERC20__factory.connect(marginTokenAddr, this.provider);
529
- return [4 /*yield*/, token.balanceOf(address, overrides || {})];
530
- case 1:
531
- walletBalance = _a.sent();
532
- return [4 /*yield*/, token.decimals(overrides || {})];
533
- case 2:
534
- decimals = _a.sent();
535
- return [2 /*return*/, Number(formatUnits(walletBalance, decimals))];
536
- }
537
- });
538
- });
539
- };
450
+ async getWalletBalance(address, symbol, overrides) {
451
+ let poolIdx = this.getPoolStaticInfoIndexFromSymbol(symbol);
452
+ let marginTokenAddr = this.poolStaticInfos[poolIdx].poolMarginTokenAddr;
453
+ let token = ERC20__factory.connect(marginTokenAddr, this.provider);
454
+ let walletBalance = await token.balanceOf(address, overrides || {});
455
+ let decimals = await token.decimals(overrides || {});
456
+ return Number(formatUnits(walletBalance, decimals));
457
+ }
540
458
  /**
541
459
  * Get the address' balance of the pool share token
542
460
  * @param address address of the liquidity provider
543
461
  * @param symbolOrId Symbol of the form ETH-USD-MATIC, or MATIC (collateral only), or Pool-Id
544
462
  */
545
- MarketData.prototype.getPoolShareTokenBalance = function (address, symbolOrId, overrides) {
546
- return __awaiter(this, void 0, void 0, function () {
547
- var poolId;
548
- return __generator(this, function (_a) {
549
- poolId = this._poolSymbolOrIdToPoolId(symbolOrId);
550
- return [2 /*return*/, this._getPoolShareTokenBalanceFromId(address, poolId, overrides)];
551
- });
552
- });
553
- };
463
+ async getPoolShareTokenBalance(address, symbolOrId, overrides) {
464
+ let poolId = this._poolSymbolOrIdToPoolId(symbolOrId);
465
+ return this._getPoolShareTokenBalanceFromId(address, poolId, overrides);
466
+ }
554
467
  /**
555
468
  * Query the pool share token holdings of address
556
469
  * @param address address of token holder
557
470
  * @param poolId pool id
558
471
  * @returns pool share token balance of address
559
472
  */
560
- MarketData.prototype._getPoolShareTokenBalanceFromId = function (address, poolId, overrides) {
561
- return __awaiter(this, void 0, void 0, function () {
562
- var shareTokenAddr, shareToken, d18ShareTokenBalanceOfAddr;
563
- return __generator(this, function (_a) {
564
- switch (_a.label) {
565
- case 0:
566
- shareTokenAddr = this.poolStaticInfos[poolId - 1].shareTokenAddr;
567
- shareToken = ERC20__factory.connect(shareTokenAddr, this.provider);
568
- return [4 /*yield*/, shareToken.balanceOf(address, overrides || {})];
569
- case 1:
570
- d18ShareTokenBalanceOfAddr = _a.sent();
571
- return [2 /*return*/, dec18ToFloat(d18ShareTokenBalanceOfAddr)];
572
- }
573
- });
574
- });
575
- };
473
+ async _getPoolShareTokenBalanceFromId(address, poolId, overrides) {
474
+ let shareTokenAddr = this.poolStaticInfos[poolId - 1].shareTokenAddr;
475
+ let shareToken = ERC20__factory.connect(shareTokenAddr, this.provider);
476
+ let d18ShareTokenBalanceOfAddr = await shareToken.balanceOf(address, overrides || {});
477
+ return dec18ToFloat(d18ShareTokenBalanceOfAddr);
478
+ }
576
479
  /**
577
480
  * Value of pool token in collateral currency
578
481
  * @param symbolOrId symbol of the form ETH-USD-MATIC, MATIC (collateral), or poolId
579
482
  * @returns current pool share token price in collateral currency
580
483
  */
581
- MarketData.prototype.getShareTokenPrice = function (symbolOrId, overrides) {
582
- return __awaiter(this, void 0, void 0, function () {
583
- var poolId, priceDec18, price;
584
- return __generator(this, function (_a) {
585
- switch (_a.label) {
586
- case 0:
587
- poolId = this._poolSymbolOrIdToPoolId(symbolOrId);
588
- return [4 /*yield*/, this.proxyContract.getShareTokenPriceD18(poolId, overrides || {})];
589
- case 1:
590
- priceDec18 = _a.sent();
591
- price = dec18ToFloat(priceDec18);
592
- return [2 /*return*/, price];
593
- }
594
- });
595
- });
596
- };
484
+ async getShareTokenPrice(symbolOrId, overrides) {
485
+ let poolId = this._poolSymbolOrIdToPoolId(symbolOrId);
486
+ const priceDec18 = await this.proxyContract.getShareTokenPriceD18(poolId, overrides || {});
487
+ const price = dec18ToFloat(priceDec18);
488
+ return price;
489
+ }
597
490
  /**
598
491
  * Value of the pool share tokens for this liquidity provider
599
492
  * in poolSymbol-currency (e.g. MATIC, USDC).
@@ -614,36 +507,24 @@ var MarketData = /** @class */ (function (_super) {
614
507
  * main();
615
508
  * @returns the value (in collateral tokens) of the pool share, #share tokens, shareTokenAddress
616
509
  */
617
- MarketData.prototype.getParticipationValue = function (address, symbolOrId, overrides) {
618
- return __awaiter(this, void 0, void 0, function () {
619
- var poolId, shareTokens, priceDec18, price, value, shareTokenAddr;
620
- return __generator(this, function (_a) {
621
- switch (_a.label) {
622
- case 0:
623
- poolId = this._poolSymbolOrIdToPoolId(symbolOrId);
624
- return [4 /*yield*/, this._getPoolShareTokenBalanceFromId(address, poolId, overrides)];
625
- case 1:
626
- shareTokens = _a.sent();
627
- return [4 /*yield*/, this.proxyContract.getShareTokenPriceD18(poolId, overrides || {})];
628
- case 2:
629
- priceDec18 = _a.sent();
630
- price = dec18ToFloat(priceDec18);
631
- value = price * shareTokens;
632
- shareTokenAddr = this.poolStaticInfos[poolId - 1].shareTokenAddr;
633
- return [2 /*return*/, {
634
- value: value,
635
- shareTokenBalance: shareTokens,
636
- poolShareToken: shareTokenAddr,
637
- }];
638
- }
639
- });
640
- });
641
- };
642
- MarketData.prototype._poolSymbolOrIdToPoolId = function (poolSymbolOrId) {
510
+ async getParticipationValue(address, symbolOrId, overrides) {
511
+ let poolId = this._poolSymbolOrIdToPoolId(symbolOrId);
512
+ const shareTokens = await this._getPoolShareTokenBalanceFromId(address, poolId, overrides);
513
+ const priceDec18 = await this.proxyContract.getShareTokenPriceD18(poolId, overrides || {});
514
+ const price = dec18ToFloat(priceDec18);
515
+ const value = price * shareTokens;
516
+ const shareTokenAddr = this.poolStaticInfos[poolId - 1].shareTokenAddr;
517
+ return {
518
+ value: value,
519
+ shareTokenBalance: shareTokens,
520
+ poolShareToken: shareTokenAddr,
521
+ };
522
+ }
523
+ _poolSymbolOrIdToPoolId(poolSymbolOrId) {
643
524
  if (this.proxyContract == null || this.poolStaticInfos.length == 0) {
644
525
  throw Error("no proxy contract or wallet or data initialized. Use createProxyInstance().");
645
526
  }
646
- var poolId;
527
+ let poolId;
647
528
  if (isNaN(Number(poolSymbolOrId))) {
648
529
  poolId = PerpetualDataHandler._getPoolIdFromSymbol(poolSymbolOrId, this.poolStaticInfos);
649
530
  }
@@ -651,7 +532,7 @@ var MarketData = /** @class */ (function (_super) {
651
532
  poolId = Number(poolSymbolOrId);
652
533
  }
653
534
  return poolId;
654
- };
535
+ }
655
536
  /**
656
537
  * Gets the maximal order size to open positions (increase size),
657
538
  * considering the existing position, state of the perpetual
@@ -660,44 +541,24 @@ var MarketData = /** @class */ (function (_super) {
660
541
  * @param positionRisk Current position risk (as seen in positionRisk)
661
542
  * @returns Maximal trade size, not signed
662
543
  */
663
- MarketData.prototype.maxOrderSizeForTrader = function (side, positionRisk, overrides) {
664
- return __awaiter(this, void 0, void 0, function () {
665
- var curPosition, perpId, perpMaxPositionABK;
666
- return __generator(this, function (_a) {
667
- switch (_a.label) {
668
- case 0:
669
- curPosition = side == BUY_SIDE ? positionRisk.positionNotionalBaseCCY : -positionRisk.positionNotionalBaseCCY;
670
- perpId = this.getPerpIdFromSymbol(positionRisk.symbol);
671
- return [4 /*yield*/, this.proxyContract.getMaxSignedOpenTradeSizeForPos(perpId, floatToABK64x64(curPosition), side == BUY_SIDE, overrides || {})];
672
- case 1:
673
- perpMaxPositionABK = _a.sent();
674
- return [2 /*return*/, ABK64x64ToFloat(perpMaxPositionABK.abs())];
675
- }
676
- });
677
- });
678
- };
544
+ async maxOrderSizeForTrader(side, positionRisk, overrides) {
545
+ let curPosition = side == BUY_SIDE ? positionRisk.positionNotionalBaseCCY : -positionRisk.positionNotionalBaseCCY;
546
+ let perpId = this.getPerpIdFromSymbol(positionRisk.symbol);
547
+ let perpMaxPositionABK = await this.proxyContract.getMaxSignedOpenTradeSizeForPos(perpId, floatToABK64x64(curPosition), side == BUY_SIDE, overrides || {});
548
+ return ABK64x64ToFloat(perpMaxPositionABK.abs());
549
+ }
679
550
  /**
680
551
  *
681
552
  * @param side BUY_SIDE or SELL_SIDE
682
553
  * @param symbol of the form ETH-USD-MATIC.
683
554
  * @returns signed maximal position size in base currency
684
555
  */
685
- MarketData.prototype.maxSignedPosition = function (side, symbol, overrides) {
686
- return __awaiter(this, void 0, void 0, function () {
687
- var perpId, isBuy, maxSignedPos;
688
- return __generator(this, function (_a) {
689
- switch (_a.label) {
690
- case 0:
691
- perpId = this.getPerpIdFromSymbol(symbol);
692
- isBuy = side == BUY_SIDE;
693
- return [4 /*yield*/, this.proxyContract.getMaxSignedOpenTradeSizeForPos(perpId, BigNumber.from(0), isBuy, overrides || {})];
694
- case 1:
695
- maxSignedPos = _a.sent();
696
- return [2 /*return*/, ABK64x64ToFloat(maxSignedPos)];
697
- }
698
- });
699
- });
700
- };
556
+ async maxSignedPosition(side, symbol, overrides) {
557
+ let perpId = this.getPerpIdFromSymbol(symbol);
558
+ let isBuy = side == BUY_SIDE;
559
+ let maxSignedPos = await this.proxyContract.getMaxSignedOpenTradeSizeForPos(perpId, BigNumber.from(0), isBuy, overrides || {});
560
+ return ABK64x64ToFloat(maxSignedPos);
561
+ }
701
562
  /**
702
563
  * Uses the Oracle(s) in the exchange to get the latest price of a given index in a given currency, if a route exists.
703
564
  * @param {string} base Index name, e.g. ETH.
@@ -718,23 +579,13 @@ var MarketData = /** @class */ (function (_super) {
718
579
  *
719
580
  * @returns {number} Price of index in given currency.
720
581
  */
721
- MarketData.prototype.getOraclePrice = function (base, quote, overrides) {
722
- return __awaiter(this, void 0, void 0, function () {
723
- var px;
724
- return __generator(this, function (_a) {
725
- switch (_a.label) {
726
- case 0:
727
- if (!this.proxyContract) {
728
- throw Error("no proxy contract initialized. Use createProxyInstance().");
729
- }
730
- return [4 /*yield*/, this.proxyContract.getOraclePrice([toBytes4(base), toBytes4(quote)], overrides || {})];
731
- case 1:
732
- px = _a.sent();
733
- return [2 /*return*/, px == undefined ? undefined : ABK64x64ToFloat(px)];
734
- }
735
- });
736
- });
737
- };
582
+ async getOraclePrice(base, quote, overrides) {
583
+ if (!this.proxyContract) {
584
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
585
+ }
586
+ let px = await this.proxyContract.getOraclePrice([toBytes4(base), toBytes4(quote)], overrides || {});
587
+ return px == undefined ? undefined : ABK64x64ToFloat(px);
588
+ }
738
589
  /**
739
590
  *
740
591
  * @param symbol Symbol of the form ETH-USD-MATIC
@@ -742,24 +593,14 @@ var MarketData = /** @class */ (function (_super) {
742
593
  * @param overrides
743
594
  * @returns Order status ()
744
595
  */
745
- MarketData.prototype.getOrderStatus = function (symbol, orderId, overrides) {
746
- return __awaiter(this, void 0, void 0, function () {
747
- var orderBookContract, status;
748
- return __generator(this, function (_a) {
749
- switch (_a.label) {
750
- case 0:
751
- if (!this.proxyContract) {
752
- throw Error("no proxy contract initialized. Use createProxyInstance().");
753
- }
754
- orderBookContract = this.getOrderBookContract(symbol);
755
- return [4 /*yield*/, orderBookContract.getOrderStatus(orderId, overrides || {})];
756
- case 1:
757
- status = _a.sent();
758
- return [2 /*return*/, status];
759
- }
760
- });
761
- });
762
- };
596
+ async getOrderStatus(symbol, orderId, overrides) {
597
+ if (!this.proxyContract) {
598
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
599
+ }
600
+ const orderBookContract = this.getOrderBookContract(symbol);
601
+ let status = await orderBookContract.getOrderStatus(orderId, overrides || {});
602
+ return status;
603
+ }
763
604
  /**
764
605
  * Get the current mark price
765
606
  * @param symbol symbol of the form ETH-USD-MATIC
@@ -779,27 +620,16 @@ var MarketData = /** @class */ (function (_super) {
779
620
  *
780
621
  * @returns mark price
781
622
  */
782
- MarketData.prototype.getMarkPrice = function (symbol, indexPrices) {
783
- return __awaiter(this, void 0, void 0, function () {
784
- var obj;
785
- return __generator(this, function (_a) {
786
- switch (_a.label) {
787
- case 0:
788
- if (this.proxyContract == null) {
789
- throw Error("no proxy contract initialized. Use createProxyInstance().");
790
- }
791
- if (!(indexPrices == undefined)) return [3 /*break*/, 2];
792
- return [4 /*yield*/, this.priceFeedGetter.fetchPricesForPerpetual(symbol)];
793
- case 1:
794
- obj = _a.sent();
795
- indexPrices = [obj.idxPrices[0], obj.idxPrices[1]];
796
- _a.label = 2;
797
- case 2: return [4 /*yield*/, PerpetualDataHandler._queryPerpetualMarkPrice(symbol, this.symbolToPerpStaticInfo, this.proxyContract, indexPrices)];
798
- case 3: return [2 /*return*/, _a.sent()];
799
- }
800
- });
801
- });
802
- };
623
+ async getMarkPrice(symbol, indexPrices) {
624
+ if (this.proxyContract == null) {
625
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
626
+ }
627
+ if (indexPrices == undefined) {
628
+ let obj = await this.priceFeedGetter.fetchPricesForPerpetual(symbol);
629
+ indexPrices = [obj.idxPrices[0], obj.idxPrices[1]];
630
+ }
631
+ return await PerpetualDataHandler._queryPerpetualMarkPrice(symbol, this.symbolToPerpStaticInfo, this.proxyContract, indexPrices);
632
+ }
803
633
  /**
804
634
  * get the current price for a given quantity
805
635
  * @param symbol symbol of the form ETH-USD-MATIC
@@ -820,69 +650,72 @@ var MarketData = /** @class */ (function (_super) {
820
650
  *
821
651
  * @returns price (number)
822
652
  */
823
- MarketData.prototype.getPerpetualPrice = function (symbol, quantity, indexPrices, overrides) {
824
- return __awaiter(this, void 0, void 0, function () {
825
- var obj;
826
- return __generator(this, function (_a) {
827
- switch (_a.label) {
828
- case 0:
829
- if (this.proxyContract == null) {
830
- throw Error("no proxy contract initialized. Use createProxyInstance().");
831
- }
832
- if (!(indexPrices == undefined)) return [3 /*break*/, 2];
833
- return [4 /*yield*/, this.priceFeedGetter.fetchPricesForPerpetual(symbol)];
834
- case 1:
835
- obj = _a.sent();
836
- indexPrices = [obj.idxPrices[0], obj.idxPrices[1]];
837
- _a.label = 2;
838
- case 2: return [4 /*yield*/, PerpetualDataHandler._queryPerpetualPrice(symbol, quantity, this.symbolToPerpStaticInfo, this.proxyContract, indexPrices, overrides)];
839
- case 3: return [2 /*return*/, _a.sent()];
840
- }
841
- });
842
- });
843
- };
653
+ async getPerpetualPrice(symbol, quantity, indexPrices, overrides) {
654
+ if (this.proxyContract == null) {
655
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
656
+ }
657
+ if (indexPrices == undefined) {
658
+ // fetch from API
659
+ let obj = await this.priceFeedGetter.fetchPricesForPerpetual(symbol);
660
+ indexPrices = [obj.idxPrices[0], obj.idxPrices[1]];
661
+ }
662
+ return await PerpetualDataHandler._queryPerpetualPrice(symbol, quantity, this.symbolToPerpStaticInfo, this.proxyContract, indexPrices, overrides);
663
+ }
844
664
  /**
845
665
  * Query recent perpetual state from blockchain
846
666
  * @param symbol symbol of the form ETH-USD-MATIC
847
667
  * @param indexPrices S2 and S3 prices/isMarketOpen if not provided fetch via REST API
848
668
  * @returns PerpetualState reference
849
669
  */
850
- MarketData.prototype.getPerpetualState = function (symbol, indexPriceInfo, overrides) {
851
- return __awaiter(this, void 0, void 0, function () {
852
- var obj, state;
853
- return __generator(this, function (_a) {
854
- switch (_a.label) {
855
- case 0:
856
- if (this.proxyContract == null) {
857
- throw Error("no proxy contract initialized. Use createProxyInstance().");
858
- }
859
- if (!(indexPriceInfo == undefined)) return [3 /*break*/, 2];
860
- return [4 /*yield*/, this.priceFeedGetter.fetchPricesForPerpetual(symbol)];
861
- case 1:
862
- obj = _a.sent();
863
- indexPriceInfo = [obj.idxPrices[0], obj.idxPrices[1], obj.mktClosed[0], obj.mktClosed[1]];
864
- _a.label = 2;
865
- case 2: return [4 /*yield*/, PerpetualDataHandler._queryPerpetualState(symbol, this.symbolToPerpStaticInfo, this.proxyContract, indexPriceInfo, overrides)];
866
- case 3:
867
- state = _a.sent();
868
- return [2 /*return*/, state];
869
- }
870
- });
871
- });
872
- };
670
+ async getPerpetualState(symbol, indexPriceInfo, overrides) {
671
+ if (this.proxyContract == null) {
672
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
673
+ }
674
+ if (indexPriceInfo == undefined) {
675
+ let obj = await this.priceFeedGetter.fetchPricesForPerpetual(symbol);
676
+ indexPriceInfo = [obj.idxPrices[0], obj.idxPrices[1], obj.mktClosed[0], obj.mktClosed[1]];
677
+ }
678
+ let state = await PerpetualDataHandler._queryPerpetualState(symbol, this.symbolToPerpStaticInfo, this.proxyContract, indexPriceInfo, overrides);
679
+ return state;
680
+ }
681
+ /**
682
+ * Query recent pool state from blockchain, not including perpetual states
683
+ * @param symbol symbol of the form USDC
684
+ * @param indexPrices S2 and S3 prices/isMarketOpen if not provided fetch via REST API
685
+ * @returns PoolState reference
686
+ */
687
+ async getPoolState(poolSymbol, overrides) {
688
+ if (this.proxyContract == null) {
689
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
690
+ }
691
+ const poolId = this._poolSymbolOrIdToPoolId(poolSymbol);
692
+ const pool = await this.proxyContract.getLiquidityPool(poolId, overrides || {});
693
+ let state = {
694
+ isRunning: pool.isRunning,
695
+ poolSymbol: poolSymbol,
696
+ marginTokenAddr: pool.marginTokenAddress,
697
+ poolShareTokenAddr: pool.shareTokenAddress,
698
+ defaultFundCashCC: ABK64x64ToFloat(pool.fDefaultFundCashCC),
699
+ pnlParticipantCashCC: ABK64x64ToFloat(pool.fPnLparticipantsCashCC),
700
+ totalTargetAMMFundSizeCC: ABK64x64ToFloat(pool.fTargetAMMFundSize),
701
+ brokerCollateralLotSize: ABK64x64ToFloat(pool.fBrokerCollateralLotSize),
702
+ perpetuals: [],
703
+ };
704
+ return state;
705
+ }
873
706
  /**
874
707
  * Query perpetual static info.
875
708
  * This information is queried once at createProxyInstance-time and remains static after that.
876
709
  * @param symbol symbol of the form ETH-USD-MATIC
877
710
  * @returns PerpetualStaticInfo copy.
878
711
  */
879
- MarketData.prototype.getPerpetualStaticInfo = function (symbol) {
880
- var perpInfo = this.symbolToPerpStaticInfo.get(symbol);
712
+ getPerpetualStaticInfo(symbol) {
713
+ let perpInfo = this.symbolToPerpStaticInfo.get(symbol);
881
714
  if (perpInfo == undefined) {
882
- throw Error("Perpetual with symbol ".concat(symbol, " not found. Check symbol or use createProxyInstance()."));
715
+ throw Error(`Perpetual with symbol ${symbol} not found. Check symbol or use createProxyInstance().`);
883
716
  }
884
717
  // return new copy, not a reference
885
- var res = {
718
+ let res = {
886
719
  id: perpInfo.id,
887
720
  poolId: perpInfo.poolId,
888
721
  limitOrderBookAddr: perpInfo.limitOrderBookAddr,
@@ -896,7 +729,7 @@ var MarketData = /** @class */ (function (_super) {
896
729
  priceIds: perpInfo.priceIds,
897
730
  };
898
731
  return res;
899
- };
732
+ }
900
733
  /**
901
734
  * get the current mid-price for a perpetual
902
735
  * @param symbol symbol of the form ETH-USD-MATIC
@@ -916,20 +749,12 @@ var MarketData = /** @class */ (function (_super) {
916
749
  *
917
750
  * @returns {number} price
918
751
  */
919
- MarketData.prototype.getPerpetualMidPrice = function (symbol) {
920
- return __awaiter(this, void 0, void 0, function () {
921
- return __generator(this, function (_a) {
922
- switch (_a.label) {
923
- case 0:
924
- if (this.proxyContract == null) {
925
- throw Error("no proxy contract initialized. Use createProxyInstance().");
926
- }
927
- return [4 /*yield*/, this.getPerpetualPrice(symbol, 0)];
928
- case 1: return [2 /*return*/, _a.sent()];
929
- }
930
- });
931
- });
932
- };
752
+ async getPerpetualMidPrice(symbol) {
753
+ if (this.proxyContract == null) {
754
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
755
+ }
756
+ return await this.getPerpetualPrice(symbol, 0);
757
+ }
933
758
  /**
934
759
  * Query smart contract to get user orders and convert to user friendly order format.
935
760
  * @param {string} traderAddr Address of trader.
@@ -937,35 +762,24 @@ var MarketData = /** @class */ (function (_super) {
937
762
  * @returns {Order[]} Array of user friendly order struct.
938
763
  * @ignore
939
764
  */
940
- MarketData.prototype.openOrdersOnOrderBook = function (traderAddr, orderBookContract, overrides) {
941
- return __awaiter(this, void 0, void 0, function () {
942
- var userFriendlyOrders, haveMoreOrders, from, bulkSize, orders, k;
943
- return __generator(this, function (_a) {
944
- switch (_a.label) {
945
- case 0:
946
- userFriendlyOrders = new Array();
947
- haveMoreOrders = true;
948
- from = 0;
949
- bulkSize = 15;
950
- _a.label = 1;
951
- case 1:
952
- if (!haveMoreOrders) return [3 /*break*/, 3];
953
- return [4 /*yield*/, orderBookContract.getOrders(traderAddr, from, bulkSize, overrides || {})];
954
- case 2:
955
- orders = _a.sent();
956
- k = 0;
957
- while (k < orders.length && orders[k].traderAddr !== ZERO_ADDRESS) {
958
- userFriendlyOrders.push(PerpetualDataHandler.fromClientOrder(orders[k], this.symbolToPerpStaticInfo));
959
- k++;
960
- }
961
- haveMoreOrders = orders[orders.length - 1].traderAddr !== ZERO_ADDRESS;
962
- from = from + bulkSize;
963
- return [3 /*break*/, 1];
964
- case 3: return [2 /*return*/, userFriendlyOrders];
965
- }
966
- });
967
- });
968
- };
765
+ async openOrdersOnOrderBook(traderAddr, orderBookContract, overrides) {
766
+ //eliminate empty orders and map to user friendly orders
767
+ let userFriendlyOrders = new Array();
768
+ let haveMoreOrders = true;
769
+ let from = 0;
770
+ const bulkSize = 15;
771
+ while (haveMoreOrders) {
772
+ let orders = await orderBookContract.getOrders(traderAddr, from, bulkSize, overrides || {});
773
+ let k = 0;
774
+ while (k < orders.length && orders[k].traderAddr !== ZERO_ADDRESS) {
775
+ userFriendlyOrders.push(PerpetualDataHandler.fromClientOrder(orders[k], this.symbolToPerpStaticInfo));
776
+ k++;
777
+ }
778
+ haveMoreOrders = orders[orders.length - 1].traderAddr !== ZERO_ADDRESS;
779
+ from = from + bulkSize;
780
+ }
781
+ return userFriendlyOrders;
782
+ }
969
783
  /**
970
784
  *
971
785
  * @param traderAddr Address of the trader
@@ -973,25 +787,16 @@ var MarketData = /** @class */ (function (_super) {
973
787
  * @returns Array of order-id's
974
788
  * @ignore
975
789
  */
976
- MarketData.orderIdsOfTrader = function (traderAddr, orderBookContract, overrides) {
977
- return __awaiter(this, void 0, void 0, function () {
978
- var digestsRaw, k, digests;
979
- return __generator(this, function (_a) {
980
- switch (_a.label) {
981
- case 0: return [4 /*yield*/, orderBookContract.limitDigestsOfTrader(traderAddr, 0, 15, overrides || {})];
982
- case 1:
983
- digestsRaw = _a.sent();
984
- k = 0;
985
- digests = [];
986
- while (k < digestsRaw.length && BigNumber.from(digestsRaw[k]).gt(0)) {
987
- digests.push(digestsRaw[k]);
988
- k++;
989
- }
990
- return [2 /*return*/, digests];
991
- }
992
- });
993
- });
994
- };
790
+ static async orderIdsOfTrader(traderAddr, orderBookContract, overrides) {
791
+ let digestsRaw = await orderBookContract.limitDigestsOfTrader(traderAddr, 0, 15, overrides || {});
792
+ let k = 0;
793
+ let digests = [];
794
+ while (k < digestsRaw.length && BigNumber.from(digestsRaw[k]).gt(0)) {
795
+ digests.push(digestsRaw[k]);
796
+ k++;
797
+ }
798
+ return digests;
799
+ }
995
800
  /**
996
801
  * Query the available margin conditional on the given (or current) index prices
997
802
  * Result is in collateral currency
@@ -1000,165 +805,106 @@ var MarketData = /** @class */ (function (_super) {
1000
805
  * @param indexPrices optional index prices, will otherwise fetch from REST API
1001
806
  * @returns available margin in collateral currency
1002
807
  */
1003
- MarketData.prototype.getAvailableMargin = function (traderAddr, symbol, indexPrices, overrides) {
1004
- return __awaiter(this, void 0, void 0, function () {
1005
- var obj, perpID, traderState, idx_availableMargin, mgn;
1006
- return __generator(this, function (_a) {
1007
- switch (_a.label) {
1008
- case 0:
1009
- if (!this.proxyContract) {
1010
- throw Error("no proxy contract initialized. Use createProxyInstance().");
1011
- }
1012
- if (!(indexPrices == undefined)) return [3 /*break*/, 2];
1013
- return [4 /*yield*/, this.priceFeedGetter.fetchPricesForPerpetual(symbol)];
1014
- case 1:
1015
- obj = _a.sent();
1016
- indexPrices = [obj.idxPrices[0], obj.idxPrices[1]];
1017
- _a.label = 2;
1018
- case 2:
1019
- perpID = PerpetualDataHandler.symbolToPerpetualId(symbol, this.symbolToPerpStaticInfo);
1020
- return [4 /*yield*/, this.proxyContract.getTraderState(perpID, traderAddr, indexPrices.map(function (x) { return floatToABK64x64(x); }), overrides || {})];
1021
- case 3:
1022
- traderState = _a.sent();
1023
- idx_availableMargin = 1;
1024
- mgn = ABK64x64ToFloat(traderState[idx_availableMargin]);
1025
- return [2 /*return*/, mgn];
1026
- }
1027
- });
1028
- });
1029
- };
808
+ async getAvailableMargin(traderAddr, symbol, indexPrices, overrides) {
809
+ if (!this.proxyContract) {
810
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
811
+ }
812
+ if (indexPrices == undefined) {
813
+ // fetch from API
814
+ let obj = await this.priceFeedGetter.fetchPricesForPerpetual(symbol);
815
+ indexPrices = [obj.idxPrices[0], obj.idxPrices[1]];
816
+ }
817
+ let perpID = PerpetualDataHandler.symbolToPerpetualId(symbol, this.symbolToPerpStaticInfo);
818
+ let traderState = await this.proxyContract.getTraderState(perpID, traderAddr, indexPrices.map((x) => floatToABK64x64(x)), overrides || {});
819
+ const idx_availableMargin = 1;
820
+ let mgn = ABK64x64ToFloat(traderState[idx_availableMargin]);
821
+ return mgn;
822
+ }
1030
823
  /**
1031
824
  * Calculate a type of exchange loyality score based on trader volume
1032
825
  * @param traderAddr address of the trader
1033
826
  * @param brokerAddr address of the trader's broker or undefined
1034
827
  * @returns a loyality score (4 worst, 1 best)
1035
828
  */
1036
- MarketData.prototype.getTraderLoyalityScore = function (traderAddr, brokerAddr, overrides) {
1037
- return __awaiter(this, void 0, void 0, function () {
1038
- var brokerProm, traderProm, k, brkrVol_1, trdrVol_1, totalBrokerVolume, totalTraderVolume, brkrVol, trdrVol, k, volumeCap, score, rank4;
1039
- return __generator(this, function (_a) {
1040
- switch (_a.label) {
1041
- case 0:
1042
- if (this.proxyContract == null) {
1043
- throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
1044
- }
1045
- brokerProm = [];
1046
- traderProm = [];
1047
- for (k = 0; k < this.poolStaticInfos.length; k++) {
1048
- if (brokerAddr != "" && brokerAddr != undefined) {
1049
- brkrVol_1 = this.proxyContract.getCurrentBrokerVolume(this.poolStaticInfos[k].poolId, brokerAddr, overrides || {});
1050
- brokerProm.push(brkrVol_1);
1051
- }
1052
- trdrVol_1 = this.proxyContract.getCurrentTraderVolume(this.poolStaticInfos[k].poolId, traderAddr, overrides || {});
1053
- traderProm.push(trdrVol_1);
1054
- }
1055
- totalBrokerVolume = 0;
1056
- totalTraderVolume = 0;
1057
- return [4 /*yield*/, Promise.all(brokerProm)];
1058
- case 1:
1059
- brkrVol = _a.sent();
1060
- return [4 /*yield*/, Promise.all(traderProm)];
1061
- case 2:
1062
- trdrVol = _a.sent();
1063
- for (k = 0; k < this.poolStaticInfos.length; k++) {
1064
- if (brokerAddr != "" && brokerAddr != undefined) {
1065
- totalBrokerVolume += ABK64x64ToFloat(brkrVol[k]);
1066
- }
1067
- totalTraderVolume += ABK64x64ToFloat(trdrVol[k]);
1068
- }
1069
- volumeCap = 500000;
1070
- score = totalBrokerVolume == 0 ? totalTraderVolume / volumeCap : totalBrokerVolume;
1071
- rank4 = 1 + Math.floor(Math.min(score, 1 - 1e-15) * 4);
1072
- // desired ranking starts at 4 (worst) and ends at 1 (best)
1073
- return [2 /*return*/, 5 - rank4];
1074
- }
1075
- });
1076
- });
1077
- };
829
+ async getTraderLoyalityScore(traderAddr, brokerAddr, overrides) {
830
+ if (this.proxyContract == null) {
831
+ throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
832
+ }
833
+ // loop over all pools and query volumes
834
+ let brokerProm = [];
835
+ let traderProm = [];
836
+ for (let k = 0; k < this.poolStaticInfos.length; k++) {
837
+ if (brokerAddr != "" && brokerAddr != undefined) {
838
+ let brkrVol = this.proxyContract.getCurrentBrokerVolume(this.poolStaticInfos[k].poolId, brokerAddr, overrides || {});
839
+ brokerProm.push(brkrVol);
840
+ }
841
+ let trdrVol = this.proxyContract.getCurrentTraderVolume(this.poolStaticInfos[k].poolId, traderAddr, overrides || {});
842
+ traderProm.push(trdrVol);
843
+ }
844
+ // sum
845
+ let totalBrokerVolume = 0;
846
+ let totalTraderVolume = 0;
847
+ let brkrVol = await Promise.all(brokerProm);
848
+ let trdrVol = await Promise.all(traderProm);
849
+ for (let k = 0; k < this.poolStaticInfos.length; k++) {
850
+ if (brokerAddr != "" && brokerAddr != undefined) {
851
+ totalBrokerVolume += ABK64x64ToFloat(brkrVol[k]);
852
+ }
853
+ totalTraderVolume += ABK64x64ToFloat(trdrVol[k]);
854
+ }
855
+ const volumeCap = 500000;
856
+ let score = totalBrokerVolume == 0 ? totalTraderVolume / volumeCap : totalBrokerVolume;
857
+ // 5 different equally spaced categories: (4 is best, 1 worst)
858
+ let rank4 = 1 + Math.floor(Math.min(score, 1 - 1e-15) * 4);
859
+ // desired ranking starts at 4 (worst) and ends at 1 (best)
860
+ return 5 - rank4;
861
+ }
1078
862
  /**
1079
863
  * Get all off-chain prices
1080
864
  * @param _symbolToPerpStaticInfo mapping: PerpetualStaticInfo for each perpetual
1081
865
  * @param _priceFeedGetter priceFeed class from which we can get offchain price data
1082
866
  * @returns mapping of symbol-pair (e.g. BTC-USD) to price/isMarketClosed
1083
867
  */
1084
- MarketData._getAllIndexPrices = function (_symbolToPerpStaticInfo, _priceFeedGetter) {
1085
- return __awaiter(this, void 0, void 0, function () {
1086
- var allSym, _a, _b, perpSymbol, sInfo, allSymArr, idxPriceMap;
1087
- var e_1, _c;
1088
- return __generator(this, function (_d) {
1089
- switch (_d.label) {
1090
- case 0:
1091
- allSym = new Set();
1092
- try {
1093
- for (_a = __values(_symbolToPerpStaticInfo.keys()), _b = _a.next(); !_b.done; _b = _a.next()) {
1094
- perpSymbol = _b.value;
1095
- sInfo = _symbolToPerpStaticInfo.get(perpSymbol);
1096
- allSym.add(sInfo.S2Symbol);
1097
- if (sInfo.S3Symbol != "") {
1098
- allSym.add(sInfo.S3Symbol);
1099
- }
1100
- }
1101
- }
1102
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1103
- finally {
1104
- try {
1105
- if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
1106
- }
1107
- finally { if (e_1) throw e_1.error; }
1108
- }
1109
- allSymArr = Array.from(allSym.values());
1110
- return [4 /*yield*/, _priceFeedGetter.fetchPrices(allSymArr)];
1111
- case 1:
1112
- idxPriceMap = _d.sent();
1113
- return [2 /*return*/, idxPriceMap];
1114
- }
1115
- });
1116
- });
1117
- };
868
+ static async _getAllIndexPrices(_symbolToPerpStaticInfo, _priceFeedGetter) {
869
+ // get all prices from off-chain price-sources
870
+ let allSym = new Set();
871
+ for (let perpSymbol of _symbolToPerpStaticInfo.keys()) {
872
+ let sInfo = _symbolToPerpStaticInfo.get(perpSymbol);
873
+ allSym.add(sInfo.S2Symbol);
874
+ if (sInfo.S3Symbol != "") {
875
+ allSym.add(sInfo.S3Symbol);
876
+ }
877
+ }
878
+ let allSymArr = Array.from(allSym.values());
879
+ let idxPriceMap = await _priceFeedGetter.fetchPrices(allSymArr);
880
+ return idxPriceMap;
881
+ }
1118
882
  /**
1119
883
  * Get market open/closed status
1120
884
  * @param symbol Perpetual symbol of the form ETH-USD-MATIC
1121
885
  * @returns True if the market is closed
1122
886
  */
1123
- MarketData.prototype.isMarketClosed = function (symbol) {
1124
- return __awaiter(this, void 0, void 0, function () {
1125
- return __generator(this, function (_a) {
1126
- switch (_a.label) {
1127
- case 0:
1128
- if (this.proxyContract == null) {
1129
- throw Error("no proxy contract initialized. Use createProxyInstance().");
1130
- }
1131
- return [4 /*yield*/, MarketData._isMarketClosed(symbol, this.symbolToPerpStaticInfo, this.priceFeedGetter)];
1132
- case 1: return [2 /*return*/, _a.sent()];
1133
- }
1134
- });
1135
- });
1136
- };
1137
- MarketData._isMarketClosed = function (symbol, _symbolToPerpStaticInfo, _priceFeedGetter) {
1138
- return __awaiter(this, void 0, void 0, function () {
1139
- var sInfo, priceSymbols, priceInfos;
1140
- return __generator(this, function (_a) {
1141
- switch (_a.label) {
1142
- case 0:
1143
- sInfo = _symbolToPerpStaticInfo.get(symbol);
1144
- priceSymbols = [];
1145
- if ((sInfo === null || sInfo === void 0 ? void 0 : sInfo.S2Symbol) != undefined && sInfo.S2Symbol != "") {
1146
- priceSymbols.push(sInfo.S2Symbol);
1147
- }
1148
- if ((sInfo === null || sInfo === void 0 ? void 0 : sInfo.S3Symbol) != undefined && sInfo.S3Symbol != "") {
1149
- priceSymbols.push(sInfo.S3Symbol);
1150
- }
1151
- if (priceSymbols.length == 0) {
1152
- throw new Error("symbol not found");
1153
- }
1154
- return [4 /*yield*/, _priceFeedGetter.fetchPrices(priceSymbols)];
1155
- case 1:
1156
- priceInfos = _a.sent();
1157
- return [2 /*return*/, __spreadArray([], __read(priceInfos.values()), false).some(function (p) { return p[1]; })];
1158
- }
1159
- });
1160
- });
1161
- };
887
+ async isMarketClosed(symbol) {
888
+ if (this.proxyContract == null) {
889
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
890
+ }
891
+ return await MarketData._isMarketClosed(symbol, this.symbolToPerpStaticInfo, this.priceFeedGetter);
892
+ }
893
+ static async _isMarketClosed(symbol, _symbolToPerpStaticInfo, _priceFeedGetter) {
894
+ const sInfo = _symbolToPerpStaticInfo.get(symbol);
895
+ let priceSymbols = [];
896
+ if (sInfo?.S2Symbol != undefined && sInfo.S2Symbol != "") {
897
+ priceSymbols.push(sInfo.S2Symbol);
898
+ }
899
+ if (sInfo?.S3Symbol != undefined && sInfo.S3Symbol != "") {
900
+ priceSymbols.push(sInfo.S3Symbol);
901
+ }
902
+ if (priceSymbols.length == 0) {
903
+ throw new Error("symbol not found");
904
+ }
905
+ const priceInfos = await _priceFeedGetter.fetchPrices(priceSymbols);
906
+ return [...priceInfos.values()].some((p) => p[1]);
907
+ }
1162
908
  /**
1163
909
  * Collect all mid-prices
1164
910
  * @param _proxyContract contract instance
@@ -1168,182 +914,126 @@ var MarketData = /** @class */ (function (_super) {
1168
914
  * @param _idxPriceMap symbol to price/market closed
1169
915
  * @returns perpetual symbol to mid-prices mapping
1170
916
  */
1171
- MarketData._queryMidPrices = function (_proxyContract, _nestedPerpetualIDs, _symbolToPerpStaticInfo, _perpetualIdToSymbol, _idxPriceMap, overrides) {
1172
- return __awaiter(this, void 0, void 0, function () {
1173
- var chunkSize, perpetualIDChunks, midPriceMap, k, indexPrices, j, id, symbol3s, info, S2, S3, fMidPrice, j, id, symbol3s;
1174
- return __generator(this, function (_a) {
1175
- switch (_a.label) {
1176
- case 0:
1177
- chunkSize = 10;
1178
- perpetualIDChunks = PerpetualDataHandler.nestedIDsToChunks(chunkSize, _nestedPerpetualIDs);
1179
- midPriceMap = new Map();
1180
- k = 0;
1181
- _a.label = 1;
1182
- case 1:
1183
- if (!(k < perpetualIDChunks.length)) return [3 /*break*/, 4];
1184
- indexPrices = [];
1185
- // collect/order all index prices
1186
- for (j = 0; j < perpetualIDChunks[k].length; j++) {
1187
- id = perpetualIDChunks[k][j];
1188
- symbol3s = _perpetualIdToSymbol.get(id);
1189
- info = _symbolToPerpStaticInfo.get(symbol3s);
1190
- S2 = floatToABK64x64(_idxPriceMap.get(info.S2Symbol)[0]);
1191
- S3 = BigNumber.from(0);
1192
- if (info.S3Symbol != "") {
1193
- S3 = floatToABK64x64(_idxPriceMap.get(info.S3Symbol)[0]);
1194
- }
1195
- indexPrices.push(S2);
1196
- indexPrices.push(S3);
1197
- }
1198
- return [4 /*yield*/, _proxyContract.queryMidPrices(perpetualIDChunks[k], indexPrices, overrides || {})];
1199
- case 2:
1200
- fMidPrice = _a.sent();
1201
- for (j = 0; j < fMidPrice.length; j++) {
1202
- id = perpetualIDChunks[k][j];
1203
- symbol3s = _perpetualIdToSymbol.get(id);
1204
- midPriceMap.set(symbol3s, ABK64x64ToFloat(fMidPrice[j]));
1205
- }
1206
- _a.label = 3;
1207
- case 3:
1208
- k++;
1209
- return [3 /*break*/, 1];
1210
- case 4: return [2 /*return*/, midPriceMap];
1211
- }
1212
- });
1213
- });
1214
- };
1215
- MarketData._queryPoolStates = function (_proxyContract, _poolStaticInfos, _numPools, overrides) {
1216
- return __awaiter(this, void 0, void 0, function () {
1217
- var chunkSize, iFrom, poolStates, pools, k, poolSymbol, poolState;
1218
- return __generator(this, function (_a) {
1219
- switch (_a.label) {
1220
- case 0:
1221
- chunkSize = 5;
1222
- iFrom = 1;
1223
- poolStates = [];
1224
- _a.label = 1;
1225
- case 1:
1226
- if (!(iFrom <= _numPools)) return [3 /*break*/, 3];
1227
- return [4 /*yield*/, _proxyContract.getLiquidityPools(iFrom, iFrom + chunkSize, overrides || {})];
1228
- case 2:
1229
- pools = _a.sent();
1230
- for (k = 0; k < pools.length; k++) {
1231
- poolSymbol = _poolStaticInfos[iFrom + k - 1].poolMarginSymbol;
1232
- poolState = {
1233
- isRunning: pools[k].isRunning,
1234
- poolSymbol: poolSymbol,
1235
- marginTokenAddr: pools[k].marginTokenAddress,
1236
- poolShareTokenAddr: pools[k].shareTokenAddress,
1237
- defaultFundCashCC: ABK64x64ToFloat(pools[k].fDefaultFundCashCC),
1238
- pnlParticipantCashCC: ABK64x64ToFloat(pools[k].fPnLparticipantsCashCC),
1239
- totalTargetAMMFundSizeCC: ABK64x64ToFloat(pools[k].fTargetAMMFundSize),
1240
- brokerCollateralLotSize: ABK64x64ToFloat(pools[k].fBrokerCollateralLotSize),
1241
- perpetuals: [],
1242
- };
1243
- poolStates.push(poolState);
1244
- }
1245
- iFrom = iFrom + chunkSize + 1;
1246
- return [3 /*break*/, 1];
1247
- case 3: return [2 /*return*/, poolStates];
1248
- }
1249
- });
1250
- });
1251
- };
1252
- MarketData._queryPerpetualStates = function (_proxyContract, _nestedPerpetualIDs, _symbolList, overrides) {
1253
- return __awaiter(this, void 0, void 0, function () {
1254
- var chunkSize, perpetualIDChunks, perpStateInfos, k, perps, j, PerpetualState;
1255
- return __generator(this, function (_a) {
1256
- switch (_a.label) {
1257
- case 0:
1258
- chunkSize = 10;
1259
- perpetualIDChunks = PerpetualDataHandler.nestedIDsToChunks(chunkSize, _nestedPerpetualIDs);
1260
- perpStateInfos = new Array();
1261
- k = 0;
1262
- _a.label = 1;
1263
- case 1:
1264
- if (!(k < perpetualIDChunks.length)) return [3 /*break*/, 4];
1265
- return [4 /*yield*/, _proxyContract.getPerpetuals(perpetualIDChunks[k], overrides || {})];
1266
- case 2:
1267
- perps = _a.sent();
1268
- for (j = 0; j < perps.length; j++) {
1269
- PerpetualState = {
1270
- id: perps[j].id,
1271
- state: PERP_STATE_STR[perps[j].state],
1272
- baseCurrency: contractSymbolToSymbol(perps[j].S2BaseCCY, _symbolList),
1273
- quoteCurrency: contractSymbolToSymbol(perps[j].S2QuoteCCY, _symbolList),
1274
- indexPrice: 0,
1275
- collToQuoteIndexPrice: 0,
1276
- markPrice: ABK64x64ToFloat(perps[j].currentMarkPremiumRate.fPrice),
1277
- midPrice: 0,
1278
- currentFundingRateBps: 1e4 * ABK64x64ToFloat(perps[j].fCurrentFundingRate),
1279
- openInterestBC: ABK64x64ToFloat(perps[j].fOpenInterest),
1280
- isMarketClosed: false, //fill later
1281
- };
1282
- perpStateInfos.push(PerpetualState);
1283
- }
1284
- _a.label = 3;
1285
- case 3:
1286
- k++;
1287
- return [3 /*break*/, 1];
1288
- case 4: return [2 /*return*/, perpStateInfos];
917
+ static async _queryMidPrices(_proxyContract, _nestedPerpetualIDs, _symbolToPerpStaticInfo, _perpetualIdToSymbol, _idxPriceMap, overrides) {
918
+ // what is the maximal number of queries at once?
919
+ const chunkSize = 10;
920
+ let perpetualIDChunks = PerpetualDataHandler.nestedIDsToChunks(chunkSize, _nestedPerpetualIDs);
921
+ let midPriceMap = new Map();
922
+ for (let k = 0; k < perpetualIDChunks.length; k++) {
923
+ let indexPrices = [];
924
+ // collect/order all index prices
925
+ for (let j = 0; j < perpetualIDChunks[k].length; j++) {
926
+ let id = perpetualIDChunks[k][j];
927
+ let symbol3s = _perpetualIdToSymbol.get(id);
928
+ let info = _symbolToPerpStaticInfo.get(symbol3s);
929
+ let S2 = floatToABK64x64(_idxPriceMap.get(info.S2Symbol)[0]);
930
+ let S3 = BigNumber.from(0);
931
+ if (info.S3Symbol != "") {
932
+ S3 = floatToABK64x64(_idxPriceMap.get(info.S3Symbol)[0]);
1289
933
  }
1290
- });
1291
- });
1292
- };
1293
- MarketData._exchangeInfo = function (_proxyContract, _poolStaticInfos, _symbolToPerpStaticInfo, _perpetualIdToSymbol, _nestedPerpetualIDs, _symbolList, _priceFeedGetter, overrides) {
1294
- return __awaiter(this, void 0, void 0, function () {
1295
- var factory, info, numPools, idxPriceMap, midPriceMap, poolStateInfos, perpStateInfos, k, perp, symbol3s, info_1, idxPriceS2Pair, idxPriceS3Pair, indexS3, poolId;
1296
- return __generator(this, function (_a) {
1297
- switch (_a.label) {
1298
- case 0:
1299
- factory = _poolStaticInfos[0].oracleFactoryAddr;
1300
- info = { pools: [], oracleFactoryAddr: factory, proxyAddr: _proxyContract.address };
1301
- numPools = _nestedPerpetualIDs.length;
1302
- return [4 /*yield*/, MarketData._getAllIndexPrices(_symbolToPerpStaticInfo, _priceFeedGetter)];
1303
- case 1:
1304
- idxPriceMap = _a.sent();
1305
- return [4 /*yield*/, MarketData._queryMidPrices(_proxyContract, _nestedPerpetualIDs, _symbolToPerpStaticInfo, _perpetualIdToSymbol, idxPriceMap, overrides)];
1306
- case 2:
1307
- midPriceMap = _a.sent();
1308
- return [4 /*yield*/, MarketData._queryPoolStates(_proxyContract, _poolStaticInfos, numPools, overrides)];
1309
- case 3:
1310
- poolStateInfos = _a.sent();
1311
- return [4 /*yield*/, MarketData._queryPerpetualStates(_proxyContract, _nestedPerpetualIDs, _symbolList, overrides)];
1312
- case 4:
1313
- perpStateInfos = _a.sent();
1314
- // put together all info
1315
- for (k = 0; k < perpStateInfos.length; k++) {
1316
- perp = perpStateInfos[k];
1317
- symbol3s = _perpetualIdToSymbol.get(perp.id);
1318
- info_1 = _symbolToPerpStaticInfo.get(symbol3s);
1319
- idxPriceS2Pair = idxPriceMap.get(info_1.S2Symbol);
1320
- idxPriceS3Pair = [0, false];
1321
- perp.isMarketClosed = idxPriceS2Pair[1];
1322
- if (info_1.S3Symbol != "") {
1323
- idxPriceS3Pair = idxPriceMap.get(info_1.S3Symbol);
1324
- perp.isMarketClosed = perp.isMarketClosed || idxPriceS3Pair[1];
1325
- }
1326
- perp.indexPrice = idxPriceS2Pair[0];
1327
- perp.markPrice = idxPriceS2Pair[0] * (1 + perp.markPrice); // currently filled with mark premium rate
1328
- indexS3 = 1;
1329
- if (info_1.collateralCurrencyType == COLLATERAL_CURRENCY_BASE) {
1330
- indexS3 = idxPriceS2Pair[0];
1331
- }
1332
- else if (info_1.collateralCurrencyType == COLLATERAL_CURRENCY_QUANTO) {
1333
- indexS3 = idxPriceS3Pair[0];
1334
- }
1335
- perp.collToQuoteIndexPrice = indexS3;
1336
- perp.midPrice = midPriceMap.get(symbol3s);
1337
- poolId = info_1.poolId;
1338
- poolStateInfos[poolId - 1].perpetuals.push(perp);
1339
- }
1340
- info.pools = poolStateInfos;
1341
- return [2 /*return*/, info];
1342
- }
1343
- });
1344
- });
1345
- };
1346
- return MarketData;
1347
- }(PerpetualDataHandler));
1348
- export default MarketData;
934
+ indexPrices.push(S2);
935
+ indexPrices.push(S3);
936
+ }
937
+ let fMidPrice = await _proxyContract.queryMidPrices(perpetualIDChunks[k], indexPrices, overrides || {});
938
+ for (let j = 0; j < fMidPrice.length; j++) {
939
+ let id = perpetualIDChunks[k][j];
940
+ let symbol3s = _perpetualIdToSymbol.get(id);
941
+ midPriceMap.set(symbol3s, ABK64x64ToFloat(fMidPrice[j]));
942
+ }
943
+ }
944
+ return midPriceMap;
945
+ }
946
+ static async _queryPoolStates(_proxyContract, _poolStaticInfos, _numPools, overrides) {
947
+ const chunkSize = 5;
948
+ let iFrom = 1;
949
+ let poolStates = [];
950
+ while (iFrom <= _numPools) {
951
+ let pools = await _proxyContract.getLiquidityPools(iFrom, iFrom + chunkSize, overrides || {});
952
+ for (let k = 0; k < pools.length; k++) {
953
+ let poolSymbol = _poolStaticInfos[iFrom + k - 1].poolMarginSymbol;
954
+ let poolState = {
955
+ isRunning: pools[k].isRunning,
956
+ poolSymbol: poolSymbol,
957
+ marginTokenAddr: pools[k].marginTokenAddress,
958
+ poolShareTokenAddr: pools[k].shareTokenAddress,
959
+ defaultFundCashCC: ABK64x64ToFloat(pools[k].fDefaultFundCashCC),
960
+ pnlParticipantCashCC: ABK64x64ToFloat(pools[k].fPnLparticipantsCashCC),
961
+ totalTargetAMMFundSizeCC: ABK64x64ToFloat(pools[k].fTargetAMMFundSize),
962
+ brokerCollateralLotSize: ABK64x64ToFloat(pools[k].fBrokerCollateralLotSize),
963
+ perpetuals: [],
964
+ };
965
+ poolStates.push(poolState);
966
+ }
967
+ iFrom = iFrom + chunkSize + 1;
968
+ }
969
+ return poolStates;
970
+ }
971
+ static async _queryPerpetualStates(_proxyContract, _nestedPerpetualIDs, _symbolList, overrides) {
972
+ // what is the maximal number of queries at once?
973
+ const chunkSize = 10;
974
+ let perpetualIDChunks = PerpetualDataHandler.nestedIDsToChunks(chunkSize, _nestedPerpetualIDs);
975
+ let perpStateInfos = new Array();
976
+ for (let k = 0; k < perpetualIDChunks.length; k++) {
977
+ let perps = await _proxyContract.getPerpetuals(perpetualIDChunks[k], overrides || {});
978
+ for (let j = 0; j < perps.length; j++) {
979
+ let PerpetualState = {
980
+ id: perps[j].id,
981
+ state: PERP_STATE_STR[perps[j].state],
982
+ baseCurrency: contractSymbolToSymbol(perps[j].S2BaseCCY, _symbolList),
983
+ quoteCurrency: contractSymbolToSymbol(perps[j].S2QuoteCCY, _symbolList),
984
+ indexPrice: 0,
985
+ collToQuoteIndexPrice: 0,
986
+ markPrice: ABK64x64ToFloat(perps[j].currentMarkPremiumRate.fPrice),
987
+ midPrice: 0,
988
+ currentFundingRateBps: 1e4 * ABK64x64ToFloat(perps[j].fCurrentFundingRate),
989
+ openInterestBC: ABK64x64ToFloat(perps[j].fOpenInterest),
990
+ isMarketClosed: false, //fill later
991
+ };
992
+ perpStateInfos.push(PerpetualState);
993
+ }
994
+ }
995
+ return perpStateInfos;
996
+ }
997
+ static async _exchangeInfo(_proxyContract, _poolStaticInfos, _symbolToPerpStaticInfo, _perpetualIdToSymbol, _nestedPerpetualIDs, _symbolList, _priceFeedGetter, overrides) {
998
+ // get the factory address (shared among all pools)
999
+ let factory = _poolStaticInfos[0].oracleFactoryAddr;
1000
+ let info = { pools: [], oracleFactoryAddr: factory, proxyAddr: _proxyContract.address };
1001
+ const numPools = _nestedPerpetualIDs.length;
1002
+ // get all prices from off-chain price-sources
1003
+ let idxPriceMap = await MarketData._getAllIndexPrices(_symbolToPerpStaticInfo, _priceFeedGetter);
1004
+ // query mid-prices from on-chain conditional on the off-chain prices
1005
+ let midPriceMap = await MarketData._queryMidPrices(_proxyContract, _nestedPerpetualIDs, _symbolToPerpStaticInfo, _perpetualIdToSymbol, idxPriceMap, overrides);
1006
+ let poolStateInfos = await MarketData._queryPoolStates(_proxyContract, _poolStaticInfos, numPools, overrides);
1007
+ let perpStateInfos = await MarketData._queryPerpetualStates(_proxyContract, _nestedPerpetualIDs, _symbolList, overrides);
1008
+ // put together all info
1009
+ for (let k = 0; k < perpStateInfos.length; k++) {
1010
+ const perp = perpStateInfos[k];
1011
+ let symbol3s = _perpetualIdToSymbol.get(perp.id);
1012
+ let info = _symbolToPerpStaticInfo.get(symbol3s);
1013
+ const idxPriceS2Pair = idxPriceMap.get(info.S2Symbol);
1014
+ let idxPriceS3Pair = [0, false];
1015
+ perp.isMarketClosed = idxPriceS2Pair[1];
1016
+ if (info.S3Symbol != "") {
1017
+ idxPriceS3Pair = idxPriceMap.get(info.S3Symbol);
1018
+ perp.isMarketClosed = perp.isMarketClosed || idxPriceS3Pair[1];
1019
+ }
1020
+ perp.indexPrice = idxPriceS2Pair[0];
1021
+ perp.markPrice = idxPriceS2Pair[0] * (1 + perp.markPrice); // currently filled with mark premium rate
1022
+ let indexS3 = 1;
1023
+ if (info.collateralCurrencyType == COLLATERAL_CURRENCY_BASE) {
1024
+ indexS3 = idxPriceS2Pair[0];
1025
+ }
1026
+ else if (info.collateralCurrencyType == COLLATERAL_CURRENCY_QUANTO) {
1027
+ indexS3 = idxPriceS3Pair[0];
1028
+ }
1029
+ perp.collToQuoteIndexPrice = indexS3;
1030
+ perp.midPrice = midPriceMap.get(symbol3s);
1031
+ // which pool?
1032
+ const poolId = info.poolId;
1033
+ poolStateInfos[poolId - 1].perpetuals.push(perp);
1034
+ }
1035
+ info.pools = poolStateInfos;
1036
+ return info;
1037
+ }
1038
+ }
1349
1039
  //# sourceMappingURL=marketData.js.map