@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 { __assign, __awaiter, __extends, __generator, __read } from "tslib";
2
1
  import { BigNumber } from "@ethersproject/bignumber";
3
2
  import { HashZero } from "@ethersproject/constants";
4
3
  import { BUY_SIDE, SELL_SIDE, ZERO_ADDRESS, ZERO_ORDER_ID, } from "./nodeSDKTypes";
@@ -10,8 +9,7 @@ import WriteAccessHandler from "./writeAccessHandler";
10
9
  * gas-payments.
11
10
  * @extends WriteAccessHandler
12
11
  */
13
- var OrderReferrerTool = /** @class */ (function (_super) {
14
- __extends(OrderReferrerTool, _super);
12
+ export default class OrderReferrerTool extends WriteAccessHandler {
15
13
  /**
16
14
  * Constructor.
17
15
  * @param {NodeSDKConfig} config Configuration object, see PerpetualDataHandler.readSDKConfig.
@@ -31,11 +29,10 @@ var OrderReferrerTool = /** @class */ (function (_super) {
31
29
  *
32
30
  * @param {string | Signer} signer Private key or ethers Signer of the account
33
31
  */
34
- function OrderReferrerTool(config, signer) {
35
- var _this = _super.call(this, config, signer) || this;
32
+ constructor(config, signer) {
33
+ super(config, signer);
36
34
  // override parent's gas limit with a lower number
37
- _this.gasLimit = 4000000;
38
- return _this;
35
+ this.gasLimit = 4000000;
39
36
  }
40
37
  /**
41
38
  * Executes an order by symbol and ID. This action interacts with the blockchain and incurs gas costs.
@@ -71,64 +68,46 @@ var OrderReferrerTool = /** @class */ (function (_super) {
71
68
  * main();
72
69
  * @returns Transaction object.
73
70
  */
74
- OrderReferrerTool.prototype.executeOrder = function (symbol, orderId, referrerAddr, submission, overrides) {
75
- var _a;
76
- return __awaiter(this, void 0, void 0, function () {
77
- var orderBookSC;
78
- return __generator(this, function (_b) {
79
- switch (_b.label) {
80
- case 0:
81
- if (this.proxyContract == null || this.signer == null) {
82
- throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
83
- }
84
- orderBookSC = this.getOrderBookContract(symbol);
85
- if (typeof referrerAddr == "undefined") {
86
- referrerAddr = this.traderAddr;
87
- }
88
- if (!(submission == undefined)) return [3 /*break*/, 2];
89
- return [4 /*yield*/, this.priceFeedGetter.fetchLatestFeedPriceInfoForPerpetual(symbol)];
90
- case 1:
91
- submission = _b.sent();
92
- _b.label = 2;
93
- case 2:
94
- if (!overrides || overrides.value == undefined) {
95
- overrides = __assign({ value: submission.timestamps.length * this.PRICE_UPDATE_FEE_GWEI, gasLimit: (_a = overrides === null || overrides === void 0 ? void 0 : overrides.gasLimit) !== null && _a !== void 0 ? _a : this.gasLimit }, overrides);
96
- }
97
- return [4 /*yield*/, orderBookSC.executeOrder(orderId, referrerAddr, submission.priceFeedVaas, submission.timestamps, overrides)];
98
- case 3: return [2 /*return*/, _b.sent()];
99
- }
100
- });
101
- });
102
- };
103
- OrderReferrerTool.prototype.executeOrders = function (symbol, orderIds, referrerAddr, submission, overrides) {
104
- var _a;
105
- return __awaiter(this, void 0, void 0, function () {
106
- var orderBookSC;
107
- return __generator(this, function (_b) {
108
- switch (_b.label) {
109
- case 0:
110
- if (this.proxyContract == null || this.signer == null) {
111
- throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
112
- }
113
- orderBookSC = this.getOrderBookContract(symbol);
114
- if (typeof referrerAddr == "undefined") {
115
- referrerAddr = this.traderAddr;
116
- }
117
- if (!(submission == undefined)) return [3 /*break*/, 2];
118
- return [4 /*yield*/, this.priceFeedGetter.fetchLatestFeedPriceInfoForPerpetual(symbol)];
119
- case 1:
120
- submission = _b.sent();
121
- _b.label = 2;
122
- case 2:
123
- if (!overrides || overrides.value == undefined) {
124
- overrides = __assign({ value: submission.timestamps.length * this.PRICE_UPDATE_FEE_GWEI, gasLimit: (_a = overrides === null || overrides === void 0 ? void 0 : overrides.gasLimit) !== null && _a !== void 0 ? _a : this.gasLimit }, overrides);
125
- }
126
- return [4 /*yield*/, orderBookSC.executeOrders(orderIds, referrerAddr, submission === null || submission === void 0 ? void 0 : submission.priceFeedVaas, submission === null || submission === void 0 ? void 0 : submission.timestamps, overrides)];
127
- case 3: return [2 /*return*/, _b.sent()];
128
- }
129
- });
130
- });
131
- };
71
+ async executeOrder(symbol, orderId, referrerAddr, submission, overrides) {
72
+ if (this.proxyContract == null || this.signer == null) {
73
+ throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
74
+ }
75
+ const orderBookSC = this.getOrderBookContract(symbol);
76
+ if (typeof referrerAddr == "undefined") {
77
+ referrerAddr = this.traderAddr;
78
+ }
79
+ if (submission == undefined) {
80
+ submission = await this.priceFeedGetter.fetchLatestFeedPriceInfoForPerpetual(symbol);
81
+ }
82
+ if (!overrides || overrides.value == undefined) {
83
+ overrides = {
84
+ value: submission.timestamps.length * this.PRICE_UPDATE_FEE_GWEI,
85
+ gasLimit: overrides?.gasLimit ?? this.gasLimit,
86
+ ...overrides,
87
+ };
88
+ }
89
+ return await orderBookSC.executeOrder(orderId, referrerAddr, submission.priceFeedVaas, submission.timestamps, overrides);
90
+ }
91
+ async executeOrders(symbol, orderIds, referrerAddr, submission, overrides) {
92
+ if (this.proxyContract == null || this.signer == null) {
93
+ throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
94
+ }
95
+ const orderBookSC = this.getOrderBookContract(symbol);
96
+ if (typeof referrerAddr == "undefined") {
97
+ referrerAddr = this.traderAddr;
98
+ }
99
+ if (submission == undefined) {
100
+ submission = await this.priceFeedGetter.fetchLatestFeedPriceInfoForPerpetual(symbol);
101
+ }
102
+ if (!overrides || overrides.value == undefined) {
103
+ overrides = {
104
+ value: submission.timestamps.length * this.PRICE_UPDATE_FEE_GWEI,
105
+ gasLimit: overrides?.gasLimit ?? this.gasLimit,
106
+ ...overrides,
107
+ };
108
+ }
109
+ return await orderBookSC.executeOrders(orderIds, referrerAddr, submission?.priceFeedVaas, submission?.timestamps, overrides);
110
+ }
132
111
  /**
133
112
  * All the orders in the order book for a given symbol that are currently open.
134
113
  * @param {string} symbol Symbol of the form ETH-USD-MATIC.
@@ -149,20 +128,10 @@ var OrderReferrerTool = /** @class */ (function (_super) {
149
128
  *
150
129
  * @returns Array with all open orders and their IDs.
151
130
  */
152
- OrderReferrerTool.prototype.getAllOpenOrders = function (symbol, overrides) {
153
- return __awaiter(this, void 0, void 0, function () {
154
- var totalOrders;
155
- return __generator(this, function (_a) {
156
- switch (_a.label) {
157
- case 0: return [4 /*yield*/, this.numberOfOpenOrders(symbol, overrides)];
158
- case 1:
159
- totalOrders = _a.sent();
160
- return [4 /*yield*/, this.pollLimitOrders(symbol, totalOrders, ZERO_ORDER_ID, overrides)];
161
- case 2: return [2 /*return*/, _a.sent()];
162
- }
163
- });
164
- });
165
- };
131
+ async getAllOpenOrders(symbol, overrides) {
132
+ let totalOrders = await this.numberOfOpenOrders(symbol, overrides);
133
+ return await this.pollLimitOrders(symbol, totalOrders, ZERO_ORDER_ID, overrides);
134
+ }
166
135
  /**
167
136
  * Total number of limit orders for this symbol, excluding those that have been cancelled/removed.
168
137
  * @param {string} symbol Symbol of the form ETH-USD-MATIC.
@@ -183,24 +152,14 @@ var OrderReferrerTool = /** @class */ (function (_super) {
183
152
  *
184
153
  * @returns {number} Number of open orders.
185
154
  */
186
- OrderReferrerTool.prototype.numberOfOpenOrders = function (symbol, overrides) {
187
- return __awaiter(this, void 0, void 0, function () {
188
- var orderBookSC, numOrders;
189
- return __generator(this, function (_a) {
190
- switch (_a.label) {
191
- case 0:
192
- if (this.proxyContract == null) {
193
- throw Error("no proxy contract initialized. Use createProxyInstance().");
194
- }
195
- orderBookSC = this.getOrderBookContract(symbol);
196
- return [4 /*yield*/, orderBookSC.numberOfOrderBookDigests(overrides || {})];
197
- case 1:
198
- numOrders = _a.sent();
199
- return [2 /*return*/, Number(numOrders)];
200
- }
201
- });
202
- });
203
- };
155
+ async numberOfOpenOrders(symbol, overrides) {
156
+ if (this.proxyContract == null) {
157
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
158
+ }
159
+ const orderBookSC = this.getOrderBookContract(symbol);
160
+ let numOrders = await orderBookSC.numberOfOrderBookDigests(overrides || {});
161
+ return Number(numOrders);
162
+ }
204
163
  /**
205
164
  * Get order from the digest (=id)
206
165
  * @param symbol symbol of order book, e.g. ETH-USD-MATIC
@@ -223,26 +182,15 @@ var OrderReferrerTool = /** @class */ (function (_super) {
223
182
  *
224
183
  * @returns order or undefined
225
184
  */
226
- OrderReferrerTool.prototype.getOrderById = function (symbol, id, overrides) {
227
- return __awaiter(this, void 0, void 0, function () {
228
- var ob, smartContractOrder, order;
229
- return __generator(this, function (_a) {
230
- switch (_a.label) {
231
- case 0: return [4 /*yield*/, this.getOrderBookContract(symbol)];
232
- case 1:
233
- ob = _a.sent();
234
- return [4 /*yield*/, ob.orderOfDigest(id, overrides || {})];
235
- case 2:
236
- smartContractOrder = _a.sent();
237
- if (smartContractOrder.traderAddr == ZERO_ADDRESS) {
238
- return [2 /*return*/, undefined];
239
- }
240
- order = OrderReferrerTool.fromSmartContractOrder(smartContractOrder, this.symbolToPerpStaticInfo);
241
- return [2 /*return*/, order];
242
- }
243
- });
244
- });
245
- };
185
+ async getOrderById(symbol, id, overrides) {
186
+ let ob = await this.getOrderBookContract(symbol);
187
+ let smartContractOrder = await ob.orderOfDigest(id, overrides || {});
188
+ if (smartContractOrder.traderAddr == ZERO_ADDRESS) {
189
+ return undefined;
190
+ }
191
+ let order = OrderReferrerTool.fromSmartContractOrder(smartContractOrder, this.symbolToPerpStaticInfo);
192
+ return order;
193
+ }
246
194
  /**
247
195
  * Get a list of active conditional orders in the order book.
248
196
  * This a read-only action and does not incur in gas costs.
@@ -266,35 +214,25 @@ var OrderReferrerTool = /** @class */ (function (_super) {
266
214
  *
267
215
  * @returns Array of orders and corresponding order IDs
268
216
  */
269
- OrderReferrerTool.prototype.pollLimitOrders = function (symbol, numElements, startAfter, overrides) {
270
- return __awaiter(this, void 0, void 0, function () {
271
- var orderBookSC, _a, orders, orderIds, userFriendlyOrders, orderIdsOut, k;
272
- return __generator(this, function (_b) {
273
- switch (_b.label) {
274
- case 0:
275
- if (this.proxyContract == null) {
276
- throw Error("no proxy contract initialized. Use createProxyInstance().");
277
- }
278
- orderBookSC = this.getOrderBookContract(symbol);
279
- if (typeof startAfter == "undefined") {
280
- startAfter = ZERO_ORDER_ID;
281
- }
282
- return [4 /*yield*/, orderBookSC.pollLimitOrders(startAfter, BigNumber.from(numElements), overrides || {})];
283
- case 1:
284
- _a = __read.apply(void 0, [_b.sent(), 2]), orders = _a[0], orderIds = _a[1];
285
- userFriendlyOrders = new Array();
286
- orderIdsOut = [];
287
- k = 0;
288
- while (k < orders.length && orders[k].traderAddr != ZERO_ADDRESS) {
289
- userFriendlyOrders.push(WriteAccessHandler.fromClientOrder(orders[k], this.symbolToPerpStaticInfo));
290
- orderIdsOut.push(orderIds[k]);
291
- k++;
292
- }
293
- return [2 /*return*/, [userFriendlyOrders, orderIdsOut]];
294
- }
295
- });
296
- });
297
- };
217
+ async pollLimitOrders(symbol, numElements, startAfter, overrides) {
218
+ if (this.proxyContract == null) {
219
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
220
+ }
221
+ const orderBookSC = this.getOrderBookContract(symbol);
222
+ if (typeof startAfter == "undefined") {
223
+ startAfter = ZERO_ORDER_ID;
224
+ }
225
+ let [orders, orderIds] = await orderBookSC.pollLimitOrders(startAfter, BigNumber.from(numElements), overrides || {});
226
+ let userFriendlyOrders = new Array();
227
+ let orderIdsOut = [];
228
+ let k = 0;
229
+ while (k < orders.length && orders[k].traderAddr != ZERO_ADDRESS) {
230
+ userFriendlyOrders.push(WriteAccessHandler.fromClientOrder(orders[k], this.symbolToPerpStaticInfo));
231
+ orderIdsOut.push(orderIds[k]);
232
+ k++;
233
+ }
234
+ return [userFriendlyOrders, orderIdsOut];
235
+ }
298
236
  /**
299
237
  * Check if a conditional order can be executed
300
238
  * @param order order structure
@@ -317,41 +255,22 @@ var OrderReferrerTool = /** @class */ (function (_super) {
317
255
  * main();
318
256
  * @returns true if order can be executed for the current state of the perpetuals
319
257
  */
320
- OrderReferrerTool.prototype.isTradeable = function (order, blockTimestamp, indexPrices, overrides) {
321
- return __awaiter(this, void 0, void 0, function () {
322
- var obj, orderPrice, markPrice, currentBlock;
323
- return __generator(this, function (_a) {
324
- switch (_a.label) {
325
- case 0:
326
- if (this.proxyContract == null) {
327
- throw Error("no proxy contract initialized. Use createProxyInstance().");
328
- }
329
- if (!(indexPrices == undefined)) return [3 /*break*/, 2];
330
- return [4 /*yield*/, this.priceFeedGetter.fetchPricesForPerpetual(order.symbol)];
331
- case 1:
332
- obj = _a.sent();
333
- indexPrices = [obj.idxPrices[0], obj.idxPrices[1]];
334
- _a.label = 2;
335
- case 2: return [4 /*yield*/, PerpetualDataHandler._queryPerpetualPrice(order.symbol, order.quantity, this.symbolToPerpStaticInfo, this.proxyContract, indexPrices, overrides)];
336
- case 3:
337
- orderPrice = _a.sent();
338
- return [4 /*yield*/, PerpetualDataHandler._queryPerpetualMarkPrice(order.symbol, this.symbolToPerpStaticInfo, this.proxyContract, indexPrices, overrides)];
339
- case 4:
340
- markPrice = _a.sent();
341
- if (!(blockTimestamp == undefined)) return [3 /*break*/, 7];
342
- return [4 /*yield*/, this.provider.getBlockNumber()];
343
- case 5:
344
- currentBlock = _a.sent();
345
- return [4 /*yield*/, this.provider.getBlock(currentBlock)];
346
- case 6:
347
- blockTimestamp = (_a.sent()).timestamp;
348
- _a.label = 7;
349
- case 7: return [4 /*yield*/, this._isTradeable(order, orderPrice, markPrice, blockTimestamp, this.symbolToPerpStaticInfo, overrides)];
350
- case 8: return [2 /*return*/, _a.sent()];
351
- }
352
- });
353
- });
354
- };
258
+ async isTradeable(order, blockTimestamp, indexPrices, overrides) {
259
+ if (this.proxyContract == null) {
260
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
261
+ }
262
+ if (indexPrices == undefined) {
263
+ let obj = await this.priceFeedGetter.fetchPricesForPerpetual(order.symbol);
264
+ indexPrices = [obj.idxPrices[0], obj.idxPrices[1]];
265
+ }
266
+ let orderPrice = await PerpetualDataHandler._queryPerpetualPrice(order.symbol, order.quantity, this.symbolToPerpStaticInfo, this.proxyContract, indexPrices, overrides);
267
+ let markPrice = await PerpetualDataHandler._queryPerpetualMarkPrice(order.symbol, this.symbolToPerpStaticInfo, this.proxyContract, indexPrices, overrides);
268
+ if (blockTimestamp == undefined) {
269
+ const currentBlock = await this.provider.getBlockNumber();
270
+ blockTimestamp = (await this.provider.getBlock(currentBlock)).timestamp;
271
+ }
272
+ return await this._isTradeable(order, orderPrice, markPrice, blockTimestamp, this.symbolToPerpStaticInfo, overrides);
273
+ }
355
274
  /**
356
275
  * Check for a batch of orders on the same perpetual whether they can be traded
357
276
  * @param orders orders belonging to 1 perpetual
@@ -359,57 +278,32 @@ var OrderReferrerTool = /** @class */ (function (_super) {
359
278
  * if not defined.
360
279
  * @returns array of tradeable boolean
361
280
  */
362
- OrderReferrerTool.prototype.isTradeableBatch = function (orders, blockTimestamp, indexPrices, overrides) {
363
- return __awaiter(this, void 0, void 0, function () {
364
- var obj, orderPrice, markPrice, currentBlock;
365
- var _this = this;
366
- return __generator(this, function (_a) {
367
- switch (_a.label) {
368
- case 0:
369
- if (orders.length == 0) {
370
- return [2 /*return*/, []];
371
- }
372
- if (this.proxyContract == null) {
373
- throw Error("no proxy contract initialized. Use createProxyInstance().");
374
- }
375
- if (orders.filter(function (o) { return o.symbol == orders[0].symbol; }).length < orders.length) {
376
- throw Error("all orders in a batch must have the same symbol");
377
- }
378
- if (!(indexPrices == undefined)) return [3 /*break*/, 2];
379
- return [4 /*yield*/, this.priceFeedGetter.fetchPricesForPerpetual(orders[0].symbol)];
380
- case 1:
381
- obj = _a.sent();
382
- indexPrices = [obj.idxPrices[0], obj.idxPrices[1], obj.mktClosed[0], obj.mktClosed[1]];
383
- _a.label = 2;
384
- case 2:
385
- if (indexPrices[2] || indexPrices[3]) {
386
- // market closed
387
- return [2 /*return*/, orders.map(function () { return false; })];
388
- }
389
- return [4 /*yield*/, Promise.all(orders.map(function (o) {
390
- return PerpetualDataHandler._queryPerpetualPrice(o.symbol, o.quantity, _this.symbolToPerpStaticInfo, _this.proxyContract, [indexPrices[0], indexPrices[1]], overrides);
391
- }))];
392
- case 3:
393
- orderPrice = _a.sent();
394
- return [4 /*yield*/, PerpetualDataHandler._queryPerpetualMarkPrice(orders[0].symbol, this.symbolToPerpStaticInfo, this.proxyContract, [indexPrices[0], indexPrices[1]], overrides)];
395
- case 4:
396
- markPrice = _a.sent();
397
- if (!(blockTimestamp == undefined)) return [3 /*break*/, 7];
398
- return [4 /*yield*/, this.provider.getBlockNumber()];
399
- case 5:
400
- currentBlock = _a.sent();
401
- return [4 /*yield*/, this.provider.getBlock(currentBlock)];
402
- case 6:
403
- blockTimestamp = (_a.sent()).timestamp;
404
- _a.label = 7;
405
- case 7: return [4 /*yield*/, Promise.all(orders.map(function (o, idx) {
406
- return _this._isTradeable(o, orderPrice[idx], markPrice, blockTimestamp, _this.symbolToPerpStaticInfo, overrides);
407
- }))];
408
- case 8: return [2 /*return*/, _a.sent()];
409
- }
410
- });
411
- });
412
- };
281
+ async isTradeableBatch(orders, blockTimestamp, indexPrices, overrides) {
282
+ if (orders.length == 0) {
283
+ return [];
284
+ }
285
+ if (this.proxyContract == null) {
286
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
287
+ }
288
+ if (orders.filter((o) => o.symbol == orders[0].symbol).length < orders.length) {
289
+ throw Error("all orders in a batch must have the same symbol");
290
+ }
291
+ if (indexPrices == undefined) {
292
+ let obj = await this.priceFeedGetter.fetchPricesForPerpetual(orders[0].symbol);
293
+ indexPrices = [obj.idxPrices[0], obj.idxPrices[1], obj.mktClosed[0], obj.mktClosed[1]];
294
+ }
295
+ if (indexPrices[2] || indexPrices[3]) {
296
+ // market closed
297
+ return orders.map(() => false);
298
+ }
299
+ let orderPrice = await Promise.all(orders.map((o) => PerpetualDataHandler._queryPerpetualPrice(o.symbol, o.quantity, this.symbolToPerpStaticInfo, this.proxyContract, [indexPrices[0], indexPrices[1]], overrides)));
300
+ let markPrice = await PerpetualDataHandler._queryPerpetualMarkPrice(orders[0].symbol, this.symbolToPerpStaticInfo, this.proxyContract, [indexPrices[0], indexPrices[1]], overrides);
301
+ if (blockTimestamp == undefined) {
302
+ const currentBlock = await this.provider.getBlockNumber();
303
+ blockTimestamp = (await this.provider.getBlock(currentBlock)).timestamp;
304
+ }
305
+ return await Promise.all(orders.map((o, idx) => this._isTradeable(o, orderPrice[idx], markPrice, blockTimestamp, this.symbolToPerpStaticInfo, overrides)));
306
+ }
413
307
  /**
414
308
  * Can the order be executed?
415
309
  * @param order order struct
@@ -419,95 +313,78 @@ var OrderReferrerTool = /** @class */ (function (_super) {
419
313
  * @param symbolToPerpInfoMap metadata
420
314
  * @returns true if trading conditions met, false otherwise
421
315
  */
422
- OrderReferrerTool.prototype._isTradeable = function (order, tradePrice, markPrice, blockTimestamp, symbolToPerpInfoMap, overrides) {
423
- return __awaiter(this, void 0, void 0, function () {
424
- var nextBlockTimestamp, lotSize, limitPrice, orderBookContract, parentStatus;
425
- return __generator(this, function (_a) {
426
- switch (_a.label) {
427
- case 0:
428
- // check expiration date
429
- if (order.deadline != undefined && order.deadline < Date.now() / 1000) {
430
- console.log("order expired");
431
- return [2 /*return*/, false];
432
- }
433
- nextBlockTimestamp = blockTimestamp + 2;
434
- // TODO: replace 2 by a chain-dependent constant - 1 for zkEVM
435
- if (nextBlockTimestamp < order.executionTimestamp) {
436
- console.log("execution deferred to ".concat(order.executionTimestamp - nextBlockTimestamp, " more seconds"));
437
- return [2 /*return*/, false];
438
- }
439
- if (order.submittedTimestamp != undefined &&
440
- nextBlockTimestamp < order.submittedTimestamp + OrderReferrerTool.TRADE_DELAY) {
441
- // next block should be in ~2 seconds, so + 2
442
- console.log("on hold for ".concat(OrderReferrerTool.TRADE_DELAY + order.submittedTimestamp - nextBlockTimestamp, " more seconds"));
443
- return [2 /*return*/, false];
444
- }
445
- lotSize = PerpetualDataHandler._getLotSize(order.symbol, symbolToPerpInfoMap);
446
- if (order.quantity < lotSize) {
447
- // console.log(`order size too small: ${order.quantity} < ${lotSize}`);
448
- return [2 /*return*/, false];
449
- }
450
- // check limit price: fromSmartContractOrder will set it to undefined when not tradeable
451
- if (order.limitPrice == undefined) {
452
- // console.log("limit price undefined");
453
- return [2 /*return*/, false];
454
- }
455
- limitPrice = order.limitPrice;
456
- if ((order.side == BUY_SIDE && tradePrice > limitPrice) || (order.side == SELL_SIDE && tradePrice < limitPrice)) {
457
- // console.log(`limit price not met: ${limitPrice} ${order.side} @ ${tradePrice}`);
458
- return [2 /*return*/, false];
459
- }
460
- // check stop price
461
- if (order.stopPrice != undefined &&
462
- ((order.side == BUY_SIDE && markPrice < order.stopPrice) ||
463
- (order.side == SELL_SIDE && markPrice > order.stopPrice))) {
464
- // console.log("stop price not met");
465
- return [2 /*return*/, false];
466
- }
467
- if (!(order.parentChildOrderIds != undefined &&
468
- order.parentChildOrderIds[0] == HashZero &&
469
- order.parentChildOrderIds[1] != HashZero)) return [3 /*break*/, 2];
470
- orderBookContract = this.getOrderBookContract(order.symbol);
471
- return [4 /*yield*/, orderBookContract.getOrderStatus(order.parentChildOrderIds[1], overrides || {})];
472
- case 1:
473
- parentStatus = _a.sent();
474
- if (parentStatus == 2 || parentStatus == 3) {
475
- // console.log("parent not executed/cancelled");
476
- // parent is open or unknown
477
- return [2 /*return*/, false];
478
- }
479
- return [2 /*return*/, true];
480
- case 2:
481
- // all checks passed -> order is tradeable
482
- return [2 /*return*/, true];
483
- }
484
- });
485
- });
486
- };
316
+ async _isTradeable(order, tradePrice, markPrice, blockTimestamp, symbolToPerpInfoMap, overrides) {
317
+ // check expiration date
318
+ if (order.deadline != undefined && order.deadline < Date.now() / 1000) {
319
+ console.log("order expired");
320
+ return false;
321
+ }
322
+ const nextBlockTimestamp = blockTimestamp + 2;
323
+ // TODO: replace 2 by a chain-dependent constant - 1 for zkEVM
324
+ if (nextBlockTimestamp < order.executionTimestamp) {
325
+ console.log(`execution deferred to ${order.executionTimestamp - nextBlockTimestamp} more seconds`);
326
+ return false;
327
+ }
328
+ if (order.submittedTimestamp != undefined &&
329
+ nextBlockTimestamp < order.submittedTimestamp + OrderReferrerTool.TRADE_DELAY) {
330
+ // next block should be in ~2 seconds, so + 2
331
+ console.log(`on hold for ${OrderReferrerTool.TRADE_DELAY + order.submittedTimestamp - nextBlockTimestamp} more seconds`);
332
+ return false;
333
+ }
334
+ // check order size
335
+ const lotSize = PerpetualDataHandler._getLotSize(order.symbol, symbolToPerpInfoMap);
336
+ if (order.quantity < lotSize) {
337
+ // console.log(`order size too small: ${order.quantity} < ${lotSize}`);
338
+ return false;
339
+ }
340
+ // check limit price: fromSmartContractOrder will set it to undefined when not tradeable
341
+ if (order.limitPrice == undefined) {
342
+ // console.log("limit price undefined");
343
+ return false;
344
+ }
345
+ let limitPrice = order.limitPrice;
346
+ if ((order.side == BUY_SIDE && tradePrice > limitPrice) || (order.side == SELL_SIDE && tradePrice < limitPrice)) {
347
+ // console.log(`limit price not met: ${limitPrice} ${order.side} @ ${tradePrice}`);
348
+ return false;
349
+ }
350
+ // check stop price
351
+ if (order.stopPrice != undefined &&
352
+ ((order.side == BUY_SIDE && markPrice < order.stopPrice) ||
353
+ (order.side == SELL_SIDE && markPrice > order.stopPrice))) {
354
+ // console.log("stop price not met");
355
+ return false;
356
+ }
357
+ //check dependency
358
+ if (order.parentChildOrderIds != undefined &&
359
+ order.parentChildOrderIds[0] == HashZero &&
360
+ order.parentChildOrderIds[1] != HashZero) {
361
+ // order has a parent
362
+ const orderBookContract = this.getOrderBookContract(order.symbol);
363
+ const parentStatus = await orderBookContract.getOrderStatus(order.parentChildOrderIds[1], overrides || {});
364
+ if (parentStatus == 2 || parentStatus == 3) {
365
+ // console.log("parent not executed/cancelled");
366
+ // parent is open or unknown
367
+ return false;
368
+ }
369
+ return true;
370
+ }
371
+ // all checks passed -> order is tradeable
372
+ return true;
373
+ }
487
374
  /**
488
375
  * Wrapper of static method to use after mappings have been loaded into memory.
489
376
  * @param scOrder Perpetual order as received in the proxy events.
490
377
  * @returns A user-friendly order struct.
491
378
  */
492
- OrderReferrerTool.prototype.smartContractOrderToOrder = function (scOrder) {
379
+ smartContractOrderToOrder(scOrder) {
493
380
  return PerpetualDataHandler.fromSmartContractOrder(scOrder, this.symbolToPerpStaticInfo);
494
- };
495
- OrderReferrerTool.prototype.getTransactionCount = function (blockTag) {
496
- return __awaiter(this, void 0, void 0, function () {
497
- return __generator(this, function (_a) {
498
- switch (_a.label) {
499
- case 0:
500
- if (this.signer == null) {
501
- throw Error("no wallet initialized. Use createProxyInstance().");
502
- }
503
- return [4 /*yield*/, this.signer.getTransactionCount(blockTag)];
504
- case 1: return [2 /*return*/, _a.sent()];
505
- }
506
- });
507
- });
508
- };
509
- OrderReferrerTool.TRADE_DELAY = 4;
510
- return OrderReferrerTool;
511
- }(WriteAccessHandler));
512
- export default OrderReferrerTool;
381
+ }
382
+ async getTransactionCount(blockTag) {
383
+ if (this.signer == null) {
384
+ throw Error("no wallet initialized. Use createProxyInstance().");
385
+ }
386
+ return await this.signer.getTransactionCount(blockTag);
387
+ }
388
+ }
389
+ OrderReferrerTool.TRADE_DELAY = 4;
513
390
  //# sourceMappingURL=orderReferrerTool.js.map