@reyaxyz/sdk 0.130.6 → 0.131.0

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.
package/README.md CHANGED
@@ -6,5 +6,5 @@
6
6
 
7
7
  | Statements | Branches | Functions | Lines |
8
8
  | --------------------------- | ----------------------- | ------------------------- | ----------------- |
9
- | ![Statements](https://img.shields.io/badge/statements-8.79%25-red.svg?style=flat) | ![Branches](https://img.shields.io/badge/branches-4.08%25-red.svg?style=flat) | ![Functions](https://img.shields.io/badge/functions-3.89%25-red.svg?style=flat) | ![Lines](https://img.shields.io/badge/lines-8.45%25-red.svg?style=flat) |
9
+ | ![Statements](https://img.shields.io/badge/statements-8.09%25-red.svg?style=flat) | ![Branches](https://img.shields.io/badge/branches-3.06%25-red.svg?style=flat) | ![Functions](https://img.shields.io/badge/functions-3.75%25-red.svg?style=flat) | ![Lines](https://img.shields.io/badge/lines-7.77%25-red.svg?style=flat) |
10
10
 
@@ -39,7 +39,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
39
39
  return (mod && mod.__esModule) ? mod : { "default": mod };
40
40
  };
41
41
  Object.defineProperty(exports, "__esModule", { value: true });
42
- exports.closeOrder = exports.matchOrder = void 0;
42
+ exports.closeOrder = exports.closeOrderV2 = exports.closeOrderV1 = exports.matchOrder = void 0;
43
43
  var encode_1 = require("./encode");
44
44
  var signAndBroadcastTransaction_1 = require("../signAndBroadcastTransaction");
45
45
  var common_1 = require("@reyaxyz/common");
@@ -47,14 +47,56 @@ var bignumber_js_1 = __importDefault(require("bignumber.js"));
47
47
  var common_2 = require("@reyaxyz/common");
48
48
  var common_3 = require("@reyaxyz/common");
49
49
  var network_1 = require("../../utils/network");
50
- var matchOrder = function (params) { return __awaiter(void 0, void 0, void 0, function () {
51
- var snappedAmount, slippageFactor, orderPriceLimit, orderBase, chainId, _a, data, eip712Payload, eip712Signature, result;
50
+ var ethers_1 = require("ethers");
51
+ var executeMarketOrderViaOrdersGateway = function (params) { return __awaiter(void 0, void 0, void 0, function () {
52
+ var inputs, reyaChainId, creationTimestampMs, creationTimestampSeconds, _a, signature, nonce, fnSig, fnArgs, _b, ogInterface, data, result;
53
+ return __generator(this, function (_c) {
54
+ switch (_c.label) {
55
+ case 0:
56
+ inputs = ethers_1.AbiCoder.defaultAbiCoder().encode(['int256', 'uint256'], [params.order.baseE18, params.order.priceLimitE18]);
57
+ reyaChainId = (0, network_1.getReyaNetwork)();
58
+ creationTimestampMs = Date.now();
59
+ creationTimestampSeconds = Math.floor(creationTimestampMs / 1000);
60
+ return [4 /*yield*/, (0, common_1.signOrdersGatewayOrder)(params.signer, reyaChainId, params.marginAccountId, params.marketId, params.exchangeId, params.counterpartyAccountIds, params.order.type, inputs, creationTimestampSeconds + common_1.ORDERS_GATEWAY_DEADLINE_IN_SECONDS, creationTimestampMs)];
61
+ case 1:
62
+ _a = _c.sent(), signature = _a.signature, nonce = _a.nonce;
63
+ fnSig = 'execute';
64
+ _b = [params.marginAccountId,
65
+ params.marketId,
66
+ params.exchangeId,
67
+ params.counterpartyAccountIds,
68
+ params.order.type,
69
+ inputs];
70
+ return [4 /*yield*/, params.signer.getAddress()];
71
+ case 2:
72
+ fnArgs = [
73
+ _b.concat([
74
+ _c.sent(),
75
+ nonce
76
+ ]),
77
+ [signature.v, signature.r, signature.s, signature.deadline]
78
+ ];
79
+ ogInterface = new ethers_1.Interface(common_1.OrdersGatewayAbi);
80
+ data = ogInterface.encodeFunctionData(fnSig, fnArgs);
81
+ return [4 /*yield*/, (0, signAndBroadcastTransaction_1.signAndBroadcastTransaction)(data, reyaChainId, common_2.ContractType.ORDERS_GATEWAY_PROXY, {
82
+ accountId: params.marginAccountId,
83
+ marketId: params.marketId,
84
+ tradeSource: params.tradeSource,
85
+ })];
86
+ case 3:
87
+ result = _c.sent();
88
+ return [2 /*return*/, result];
89
+ }
90
+ });
91
+ }); };
92
+ var matchOrderV1 = function (params) { return __awaiter(void 0, void 0, void 0, function () {
93
+ var snappedAmount, orderBaseE18, slippageFactor, orderPriceLimitE18, chainId, _a, data, eip712Payload, eip712Signature, result;
52
94
  var _b, _c, _d, _e, _f, _g;
53
95
  return __generator(this, function (_h) {
54
96
  switch (_h.label) {
55
97
  case 0:
56
98
  if (params.amountInBase === 0) {
57
- throw new Error('Position base can not be 0');
99
+ throw new Error('Order cannot be of size zero.');
58
100
  }
59
101
  snappedAmount = (0, bignumber_js_1.default)(params.amountInBase)
60
102
  .abs()
@@ -69,11 +111,11 @@ var matchOrder = function (params) { return __awaiter(void 0, void 0, void 0, fu
69
111
  console.error("Minimum trade amount ".concat(params.market.minOrderSizeBase, ". Entered amount ").concat(snappedAmount, ", ").concat(params.amountInBase));
70
112
  throw new Error("Minimum trade amount ".concat(params.market.minOrderSizeBase));
71
113
  }
114
+ orderBaseE18 = (0, common_3.scale)(18)(snappedAmount);
72
115
  slippageFactor = 40;
73
- orderPriceLimit = (0, common_1.calculatePriceLimitForTrade)(params.market.currentPrice, snappedAmount, slippageFactor);
74
- orderBase = (0, common_3.scale)(18)(snappedAmount);
116
+ orderPriceLimitE18 = (0, common_1.calculatePriceLimitForTrade)(params.market.currentPrice, snappedAmount, slippageFactor);
75
117
  chainId = (0, network_1.getReyaNetwork)();
76
- return [4 /*yield*/, (0, encode_1.encodeMatchOrder)(params.signer, chainId, params.owner.coreSigNonce, params.marginAccountId, orderBase, orderPriceLimit, params.market.counterpartyAccountIds, params.market.id, params.market.exchangeId)];
118
+ return [4 /*yield*/, (0, encode_1.encodeMatchOrder)(params.signer, chainId, params.owner.coreSigNonce, params.marginAccountId, orderBaseE18, orderPriceLimitE18, params.market.counterpartyAccountIds, params.market.id, params.market.exchangeId)];
77
119
  case 1:
78
120
  _a = _h.sent(), data = _a.calldata, eip712Payload = _a.payload, eip712Signature = _a.signature;
79
121
  return [4 /*yield*/, (0, signAndBroadcastTransaction_1.signAndBroadcastTransaction)(data, chainId, common_2.ContractType.PERIPHERY_PROXY, {
@@ -105,9 +147,67 @@ var matchOrder = function (params) { return __awaiter(void 0, void 0, void 0, fu
105
147
  }
106
148
  });
107
149
  }); };
108
- exports.matchOrder = matchOrder;
109
- var closeOrder = function (params) { return __awaiter(void 0, void 0, void 0, function () {
110
- var closingBase, slippageFactor, orderPriceLimit, chainId, _a, data, eip712Payload, eip712Signature, result;
150
+ var matchOrderV2 = function (params) { return __awaiter(void 0, void 0, void 0, function () {
151
+ var snappedAmount, orderBaseE18, slippageFactor, orderPriceLimitE18, result;
152
+ var _a, _b, _c, _d, _e, _f;
153
+ return __generator(this, function (_g) {
154
+ switch (_g.label) {
155
+ case 0:
156
+ if (params.amountInBase === 0) {
157
+ throw new Error('Order cannot be of size zero.');
158
+ }
159
+ snappedAmount = (0, bignumber_js_1.default)(params.amountInBase)
160
+ .abs()
161
+ .dividedBy(params.market.baseSpacing)
162
+ .integerValue(bignumber_js_1.default.ROUND_FLOOR)
163
+ .multipliedBy(params.market.baseSpacing)
164
+ .toNumber();
165
+ if (params.amountInBase < 0) {
166
+ snappedAmount = -snappedAmount;
167
+ }
168
+ if (Math.abs(snappedAmount) < params.market.minOrderSizeBase) {
169
+ console.error("Minimum trade amount ".concat(params.market.minOrderSizeBase, ". Entered amount ").concat(snappedAmount, ", ").concat(params.amountInBase));
170
+ throw new Error("Minimum trade amount ".concat(params.market.minOrderSizeBase));
171
+ }
172
+ orderBaseE18 = (0, common_3.scale)(18)(snappedAmount);
173
+ slippageFactor = 40;
174
+ orderPriceLimitE18 = (0, common_1.calculatePriceLimitForTrade)(params.market.currentPrice, snappedAmount, slippageFactor);
175
+ return [4 /*yield*/, executeMarketOrderViaOrdersGateway({
176
+ signer: params.signer,
177
+ marginAccountId: params.marginAccountId,
178
+ counterpartyAccountIds: params.market.counterpartyAccountIds,
179
+ marketId: params.market.id,
180
+ exchangeId: params.market.exchangeId,
181
+ tradeSource: params.tradeSource,
182
+ order: {
183
+ baseE18: orderBaseE18,
184
+ priceLimitE18: orderPriceLimitE18,
185
+ type: common_1.OrdersGatewayOrderType.MARKET_ORDER,
186
+ },
187
+ })];
188
+ case 1:
189
+ result = _g.sent();
190
+ return [2 /*return*/, {
191
+ transactionHash: (result === null || result === void 0 ? void 0 : result.txHash) || null,
192
+ coreSigNonce: Number(result === null || result === void 0 ? void 0 : result.coreSigNonce) || null,
193
+ xpBoost: ((_a = result.miscellaneous) === null || _a === void 0 ? void 0 : _a.tradeXpBoost) || 0,
194
+ lotteryXpBoost: ((_b = result.miscellaneous) === null || _b === void 0 ? void 0 : _b.lotteryXpBoost) || 0,
195
+ isNftWon: ((_c = result.miscellaneous) === null || _c === void 0 ? void 0 : _c.xpNftAwarded) || false,
196
+ marginAccountId: params.marginAccountId,
197
+ xpEarned: ((_d = result.miscellaneous) === null || _d === void 0 ? void 0 : _d.xpEarned) || 0,
198
+ executionPrice: ((_e = result.tradeDetails) === null || _e === void 0 ? void 0 : _e.executionPrice) || 0,
199
+ base: ((_f = result.tradeDetails) === null || _f === void 0 ? void 0 : _f.base) || 0,
200
+ positions: result.positions,
201
+ orders: result.orders,
202
+ accounts: result.accounts,
203
+ }];
204
+ }
205
+ });
206
+ }); };
207
+ var isMatchOrderV2 = process.env.MATCH_ORDER_VIA_ORDERS_GATEWAY_ENABLED === 'true' || false;
208
+ exports.matchOrder = isMatchOrderV2 ? matchOrderV2 : matchOrderV1;
209
+ var closeOrderV1 = function (params) { return __awaiter(void 0, void 0, void 0, function () {
210
+ var closingBase, slippageFactor, orderPriceLimitE18, chainId, _a, data, eip712Payload, eip712Signature, result;
111
211
  var _b, _c, _d, _e, _f, _g;
112
212
  return __generator(this, function (_h) {
113
213
  switch (_h.label) {
@@ -132,9 +232,9 @@ var closeOrder = function (params) { return __awaiter(void 0, void 0, void 0, fu
132
232
  }
133
233
  }
134
234
  slippageFactor = 40;
135
- orderPriceLimit = (0, common_1.calculatePriceLimitForTrade)(params.market.currentPrice, -closingBase, slippageFactor);
235
+ orderPriceLimitE18 = (0, common_1.calculatePriceLimitForTrade)(params.market.currentPrice, -closingBase, slippageFactor);
136
236
  chainId = (0, network_1.getReyaNetwork)();
137
- return [4 /*yield*/, (0, encode_1.encodeMatchOrder)(params.signer, chainId, params.owner.coreSigNonce, params.marginAccountId, -(0, common_3.scale)(18)(closingBase), orderPriceLimit, params.market.counterpartyAccountIds, params.market.id, params.market.exchangeId)];
237
+ return [4 /*yield*/, (0, encode_1.encodeMatchOrder)(params.signer, chainId, params.owner.coreSigNonce, params.marginAccountId, -(0, common_3.scale)(18)(closingBase), orderPriceLimitE18, params.market.counterpartyAccountIds, params.market.id, params.market.exchangeId)];
138
238
  case 1:
139
239
  _a = _h.sent(), data = _a.calldata, eip712Payload = _a.payload, eip712Signature = _a.signature;
140
240
  return [4 /*yield*/, (0, signAndBroadcastTransaction_1.signAndBroadcastTransaction)(data, chainId, common_2.ContractType.PERIPHERY_PROXY, {
@@ -162,5 +262,63 @@ var closeOrder = function (params) { return __awaiter(void 0, void 0, void 0, fu
162
262
  }
163
263
  });
164
264
  }); };
165
- exports.closeOrder = closeOrder;
265
+ exports.closeOrderV1 = closeOrderV1;
266
+ var closeOrderV2 = function (params) { return __awaiter(void 0, void 0, void 0, function () {
267
+ var closingBase, slippageFactor, orderPriceLimit, result;
268
+ var _a, _b, _c, _d, _e, _f;
269
+ return __generator(this, function (_g) {
270
+ switch (_g.label) {
271
+ case 0:
272
+ if (params.orderBase === 0) {
273
+ throw new Error('Position is already closed.');
274
+ }
275
+ closingBase = 0;
276
+ if (params.type === 'full') {
277
+ closingBase = params.orderBase;
278
+ }
279
+ else {
280
+ closingBase = params.closingOrderBase;
281
+ if (closingBase === 0) {
282
+ throw new Error('Specified base to close is zero.');
283
+ }
284
+ if (closingBase * params.orderBase < 0) {
285
+ throw new Error('Specified base to close is in different direction that the actual order.');
286
+ }
287
+ if (Math.abs(closingBase) > Math.abs(params.orderBase)) {
288
+ throw new Error('Specified base to close is larger than the actual order.');
289
+ }
290
+ }
291
+ slippageFactor = 40;
292
+ orderPriceLimit = (0, common_1.calculatePriceLimitForTrade)(params.market.currentPrice, -closingBase, slippageFactor);
293
+ return [4 /*yield*/, executeMarketOrderViaOrdersGateway({
294
+ signer: params.signer,
295
+ marginAccountId: params.marginAccountId,
296
+ counterpartyAccountIds: params.market.counterpartyAccountIds,
297
+ marketId: params.market.id,
298
+ exchangeId: params.market.exchangeId,
299
+ order: {
300
+ baseE18: -(0, common_3.scale)(18)(closingBase),
301
+ priceLimitE18: orderPriceLimit,
302
+ type: common_1.OrdersGatewayOrderType.REDUCE_ONLY_MARKET_ORDER,
303
+ },
304
+ })];
305
+ case 1:
306
+ result = _g.sent();
307
+ return [2 /*return*/, {
308
+ transactionHash: (result === null || result === void 0 ? void 0 : result.txHash) || null,
309
+ coreSigNonce: Number(result === null || result === void 0 ? void 0 : result.coreSigNonce) || null,
310
+ xpBoost: ((_a = result.miscellaneous) === null || _a === void 0 ? void 0 : _a.tradeXpBoost) || 0,
311
+ lotteryXpBoost: ((_b = result.miscellaneous) === null || _b === void 0 ? void 0 : _b.lotteryXpBoost) || 0,
312
+ isNftWon: ((_c = result.miscellaneous) === null || _c === void 0 ? void 0 : _c.xpNftAwarded) || false,
313
+ marginAccountId: params.marginAccountId,
314
+ xpEarned: ((_d = result.miscellaneous) === null || _d === void 0 ? void 0 : _d.xpEarned) || 0,
315
+ executionPrice: ((_e = result.tradeDetails) === null || _e === void 0 ? void 0 : _e.executionPrice) || 0,
316
+ base: ((_f = result.tradeDetails) === null || _f === void 0 ? void 0 : _f.base) || 0,
317
+ }];
318
+ }
319
+ });
320
+ }); };
321
+ exports.closeOrderV2 = closeOrderV2;
322
+ var isCloseOrderV2 = process.env.CLOSE_ORDER_VIA_ORDERS_GATEWAY_ENABLED === 'true' || false;
323
+ exports.closeOrder = isCloseOrderV2 ? exports.closeOrderV2 : exports.closeOrderV1;
166
324
  //# sourceMappingURL=order.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"order.js","sourceRoot":"/","sources":["services/orders/order.ts"],"names":[],"mappings":";;;;;;;;;;;;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C,eAAe;wBACvC,QAAQ,EAAE,CAAA,MAAA,MAAM,CAAC,aAAa,0CAAE,QAAQ,KAAI,CAAC;wBAC7C,cAAc,EAAE,CAAA,MAAA,MAAM,CAAC,YAAY,0CAAE,cAAc,KAAI,CAAC;wBACxD,IAAI,EAAE,CAAA,MAAA,MAAM,CAAC,YAAY,0CAAE,IAAI,KAAI,CAAC;qBACrC,EAAC;;;KACH,CAAC;AAhFW,QAAA,UAAU,cAgFrB","sourcesContent":["import {\n CloseOrderParams,\n CloseOrderResult,\n MatchOrderParams,\n MatchOrderResult,\n} from './types';\nimport { encodeMatchOrder } from './encode';\nimport { signAndBroadcastTransaction } from '../signAndBroadcastTransaction';\nimport { calculatePriceLimitForTrade } from '@reyaxyz/common';\nimport BigNumber from 'bignumber.js';\nimport { ContractType } from '@reyaxyz/common';\nimport { scale } from '@reyaxyz/common';\nimport { getReyaNetwork } from '../../utils/network';\n\nexport const matchOrder = async (\n params: MatchOrderParams,\n): Promise<MatchOrderResult> => {\n if (params.amountInBase === 0) {\n throw new Error('Position base can not be 0');\n }\n\n let snappedAmount = BigNumber(params.amountInBase)\n .abs()\n .dividedBy(params.market.baseSpacing)\n .integerValue(BigNumber.ROUND_FLOOR)\n .multipliedBy(params.market.baseSpacing)\n .toNumber();\n\n if (params.amountInBase < 0) {\n snappedAmount = -snappedAmount;\n }\n\n if (Math.abs(snappedAmount) < params.market.minOrderSizeBase) {\n console.error(\n `Minimum trade amount ${params.market.minOrderSizeBase}. Entered amount ${snappedAmount}, ${params.amountInBase}`,\n );\n throw new Error(`Minimum trade amount ${params.market.minOrderSizeBase}`);\n }\n\n const slippageFactor = 40; // 2.5%\n\n // add rounding here\n const orderPriceLimit = calculatePriceLimitForTrade(\n params.market.currentPrice,\n snappedAmount,\n slippageFactor,\n );\n\n const orderBase = scale(18)(snappedAmount);\n const chainId = getReyaNetwork();\n\n const {\n calldata: data,\n payload: eip712Payload,\n signature: eip712Signature,\n } = await encodeMatchOrder(\n params.signer,\n chainId,\n params.owner.coreSigNonce,\n params.marginAccountId,\n orderBase,\n orderPriceLimit,\n params.market.counterpartyAccountIds,\n params.market.id,\n params.market.exchangeId,\n );\n\n const result = await signAndBroadcastTransaction(\n data,\n chainId,\n ContractType.PERIPHERY_PROXY,\n {\n action: 'matchOrder',\n accountId: params.marginAccountId,\n marketId: params.market.id,\n tradeSource: params.tradeSource,\n matchOrder: {\n userEIP712Signature: eip712Signature,\n eip712Payload,\n },\n },\n );\n\n return {\n transactionHash: result?.txHash || null,\n coreSigNonce: Number(result?.coreSigNonce) || null,\n xpBoost: result.miscellaneous?.tradeXpBoost || 0,\n lotteryXpBoost: result.miscellaneous?.lotteryXpBoost || 0,\n isNftWon: result.miscellaneous?.xpNftAwarded || false,\n marginAccountId: params.marginAccountId,\n xpEarned: result.miscellaneous?.xpEarned || 0,\n executionPrice: result.tradeDetails?.executionPrice || 0,\n base: result.tradeDetails?.base || 0,\n positions: result.positions,\n orders: result.orders,\n accounts: result.accounts,\n };\n};\n\nexport const closeOrder = async (\n params: CloseOrderParams,\n): Promise<CloseOrderResult> => {\n if (params.orderBase === 0) {\n throw new Error('Position is already closed.');\n }\n\n let closingBase: number = 0;\n if (params.type === 'full') {\n closingBase = params.orderBase;\n } else {\n closingBase = params.closingOrderBase;\n\n if (closingBase === 0) {\n throw new Error('Specified base to close is zero.');\n }\n\n if (closingBase * params.orderBase < 0) {\n throw new Error(\n 'Specified base to close is in different direction that the actual order.',\n );\n }\n\n if (Math.abs(closingBase) > Math.abs(params.orderBase)) {\n throw new Error(\n 'Specified base to close is larger than the actual order.',\n );\n }\n }\n\n const slippageFactor = 40; // 2.5%\n const orderPriceLimit = calculatePriceLimitForTrade(\n params.market.currentPrice,\n -closingBase,\n slippageFactor,\n );\n\n const chainId = getReyaNetwork();\n const {\n calldata: data,\n payload: eip712Payload,\n signature: eip712Signature,\n } = await encodeMatchOrder(\n params.signer,\n chainId,\n params.owner.coreSigNonce,\n params.marginAccountId,\n -scale(18)(closingBase),\n orderPriceLimit,\n params.market.counterpartyAccountIds,\n params.market.id,\n params.market.exchangeId,\n );\n\n const result = await signAndBroadcastTransaction(\n data,\n chainId,\n ContractType.PERIPHERY_PROXY,\n {\n action: 'closeOrder',\n accountId: params.marginAccountId,\n marketId: params.market.id,\n matchOrder: {\n userEIP712Signature: eip712Signature,\n eip712Payload,\n },\n },\n );\n\n return {\n transactionHash: result?.txHash || null,\n coreSigNonce: Number(result?.coreSigNonce) || null,\n xpBoost: result.miscellaneous?.tradeXpBoost || 0,\n lotteryXpBoost: result.miscellaneous?.lotteryXpBoost || 0,\n isNftWon: result.miscellaneous?.xpNftAwarded || false,\n marginAccountId: params.marginAccountId,\n xpEarned: result.miscellaneous?.xpEarned || 0,\n executionPrice: result.tradeDetails?.executionPrice || 0,\n base: result.tradeDetails?.base || 0,\n };\n};\n"]}
1
+ {"version":3,"file":"order.js","sourceRoot":"/","sources":["services/orders/order.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA,mCAA4C;AAC5C,8EAA6E;AAC7E,0CAOyB;AACzB,8DAAqC;AACrC,0CAA+C;AAC/C,0CAAwC;AACxC,+CAAqD;AACrD,iCAA6C;AAE7C,IAAM,kCAAkC,GAAG,UACzC,MAAsC;;;;;gBAEhC,MAAM,GAAG,iBAAQ,CAAC,eAAe,EAAE,CAAC,MAAM,CAC9C,CAAC,QAAQ,EAAE,SAAS,CAAC,EACrB,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,MAAM,CAAC,KAAK,CAAC,aAAa,CAAC,CACnD,CAAC;gBAEI,WAAW,GAAG,IAAA,wBAAc,GAAE,CAAC;gBAC/B,mBAAmB,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;gBACjC,wBAAwB,GAAG,IAAI,CAAC,KAAK,CAAC,mBAAmB,GAAG,IAAI,CAAC,CAAC;gBAE3C,qBAAM,IAAA,+BAAsB,EACvD,MAAM,CAAC,MAAM,EAC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MarketOrderParams,\n} from './types';\nimport { encodeMatchOrder } from './encode';\nimport { signAndBroadcastTransaction } from '../signAndBroadcastTransaction';\nimport {\n calculatePriceLimitForTrade,\n ORDERS_GATEWAY_DEADLINE_IN_SECONDS,\n OrdersGatewayAbi,\n OrdersGatewayOrderType,\n signOrdersGatewayOrder,\n TransactionExecutionOutput,\n} from '@reyaxyz/common';\nimport BigNumber from 'bignumber.js';\nimport { ContractType } from '@reyaxyz/common';\nimport { scale } from '@reyaxyz/common';\nimport { getReyaNetwork } from '../../utils/network';\nimport { AbiCoder, Interface } from 'ethers';\n\nconst executeMarketOrderViaOrdersGateway = async (\n params: OrdersGatewayMarketOrderParams,\n): Promise<TransactionExecutionOutput> => {\n const inputs = AbiCoder.defaultAbiCoder().encode(\n ['int256', 'uint256'],\n [params.order.baseE18, params.order.priceLimitE18],\n );\n\n const reyaChainId = getReyaNetwork();\n const creationTimestampMs = Date.now();\n const creationTimestampSeconds = Math.floor(creationTimestampMs / 1000);\n\n const { signature, nonce } = await signOrdersGatewayOrder(\n params.signer,\n reyaChainId,\n params.marginAccountId,\n params.marketId,\n params.exchangeId,\n params.counterpartyAccountIds,\n params.order.type,\n inputs,\n creationTimestampSeconds + ORDERS_GATEWAY_DEADLINE_IN_SECONDS,\n creationTimestampMs,\n );\n\n const fnSig = 'execute';\n const fnArgs = [\n [\n params.marginAccountId,\n params.marketId,\n params.exchangeId,\n params.counterpartyAccountIds,\n params.order.type,\n inputs,\n await params.signer.getAddress(),\n nonce,\n ],\n [signature.v, signature.r, signature.s, signature.deadline],\n ];\n\n const ogInterface = new Interface(OrdersGatewayAbi);\n const data = ogInterface.encodeFunctionData(fnSig, fnArgs);\n\n const result = await signAndBroadcastTransaction(\n data,\n reyaChainId,\n ContractType.ORDERS_GATEWAY_PROXY,\n {\n accountId: params.marginAccountId,\n marketId: params.marketId,\n tradeSource: params.tradeSource,\n },\n );\n\n return result;\n};\n\nconst matchOrderV1 = async (\n params: MatchOrderParams,\n): Promise<MatchOrderResult> => {\n if (params.amountInBase === 0) {\n throw new Error('Order cannot be of size zero.');\n }\n\n let snappedAmount = BigNumber(params.amountInBase)\n .abs()\n .dividedBy(params.market.baseSpacing)\n .integerValue(BigNumber.ROUND_FLOOR)\n .multipliedBy(params.market.baseSpacing)\n .toNumber();\n\n if (params.amountInBase < 0) {\n snappedAmount = -snappedAmount;\n }\n\n if (Math.abs(snappedAmount) < params.market.minOrderSizeBase) {\n console.error(\n `Minimum trade amount ${params.market.minOrderSizeBase}. Entered amount ${snappedAmount}, ${params.amountInBase}`,\n );\n throw new Error(`Minimum trade amount ${params.market.minOrderSizeBase}`);\n }\n\n const orderBaseE18 = scale(18)(snappedAmount);\n const slippageFactor = 40; // 2.5%\n const orderPriceLimitE18 = calculatePriceLimitForTrade(\n params.market.currentPrice,\n snappedAmount,\n slippageFactor,\n );\n\n const chainId = getReyaNetwork();\n\n const {\n calldata: data,\n payload: eip712Payload,\n signature: eip712Signature,\n } = await encodeMatchOrder(\n params.signer,\n chainId,\n params.owner.coreSigNonce,\n params.marginAccountId,\n orderBaseE18,\n orderPriceLimitE18,\n params.market.counterpartyAccountIds,\n params.market.id,\n params.market.exchangeId,\n );\n\n const result = await signAndBroadcastTransaction(\n data,\n chainId,\n ContractType.PERIPHERY_PROXY,\n {\n action: 'matchOrder',\n accountId: params.marginAccountId,\n marketId: params.market.id,\n tradeSource: params.tradeSource,\n matchOrder: {\n userEIP712Signature: eip712Signature,\n eip712Payload,\n },\n },\n );\n\n return {\n transactionHash: result?.txHash || null,\n coreSigNonce: Number(result?.coreSigNonce) || null,\n xpBoost: result.miscellaneous?.tradeXpBoost || 0,\n lotteryXpBoost: result.miscellaneous?.lotteryXpBoost || 0,\n isNftWon: result.miscellaneous?.xpNftAwarded || false,\n marginAccountId: params.marginAccountId,\n xpEarned: result.miscellaneous?.xpEarned || 0,\n executionPrice: result.tradeDetails?.executionPrice || 0,\n base: result.tradeDetails?.base || 0,\n positions: result.positions,\n orders: result.orders,\n accounts: result.accounts,\n };\n};\n\nconst matchOrderV2 = async (\n params: MatchOrderParams,\n): Promise<MatchOrderResult> => {\n if (params.amountInBase === 0) {\n throw new Error('Order cannot be of size zero.');\n }\n\n let snappedAmount = BigNumber(params.amountInBase)\n .abs()\n .dividedBy(params.market.baseSpacing)\n .integerValue(BigNumber.ROUND_FLOOR)\n .multipliedBy(params.market.baseSpacing)\n .toNumber();\n\n if (params.amountInBase < 0) {\n snappedAmount = -snappedAmount;\n }\n\n if (Math.abs(snappedAmount) < params.market.minOrderSizeBase) {\n console.error(\n `Minimum trade amount ${params.market.minOrderSizeBase}. Entered amount ${snappedAmount}, ${params.amountInBase}`,\n );\n throw new Error(`Minimum trade amount ${params.market.minOrderSizeBase}`);\n }\n\n const orderBaseE18 = scale(18)(snappedAmount);\n const slippageFactor = 40; // 2.5%\n const orderPriceLimitE18 = calculatePriceLimitForTrade(\n params.market.currentPrice,\n snappedAmount,\n slippageFactor,\n );\n\n const result = await executeMarketOrderViaOrdersGateway({\n signer: params.signer,\n marginAccountId: params.marginAccountId,\n counterpartyAccountIds: params.market.counterpartyAccountIds,\n marketId: params.market.id,\n exchangeId: params.market.exchangeId,\n tradeSource: params.tradeSource,\n order: {\n baseE18: orderBaseE18,\n priceLimitE18: orderPriceLimitE18,\n type: OrdersGatewayOrderType.MARKET_ORDER,\n },\n });\n\n return {\n transactionHash: result?.txHash || null,\n coreSigNonce: Number(result?.coreSigNonce) || null,\n xpBoost: result.miscellaneous?.tradeXpBoost || 0,\n lotteryXpBoost: result.miscellaneous?.lotteryXpBoost || 0,\n isNftWon: result.miscellaneous?.xpNftAwarded || false,\n marginAccountId: params.marginAccountId,\n xpEarned: result.miscellaneous?.xpEarned || 0,\n executionPrice: result.tradeDetails?.executionPrice || 0,\n base: result.tradeDetails?.base || 0,\n positions: result.positions,\n orders: result.orders,\n accounts: result.accounts,\n };\n};\n\nconst isMatchOrderV2 =\n process.env.MATCH_ORDER_VIA_ORDERS_GATEWAY_ENABLED === 'true' || false;\nexport const matchOrder = isMatchOrderV2 ? matchOrderV2 : matchOrderV1;\n\nexport const closeOrderV1 = async (\n params: CloseOrderParams,\n): Promise<CloseOrderResult> => {\n if (params.orderBase === 0) {\n throw new Error('Position is already closed.');\n }\n\n let closingBase: number = 0;\n if (params.type === 'full') {\n closingBase = params.orderBase;\n } else {\n closingBase = params.closingOrderBase;\n\n if (closingBase === 0) {\n throw new Error('Specified base to close is zero.');\n }\n\n if (closingBase * params.orderBase < 0) {\n throw new Error(\n 'Specified base to close is in different direction that the actual order.',\n );\n }\n\n if (Math.abs(closingBase) > Math.abs(params.orderBase)) {\n throw new Error(\n 'Specified base to close is larger than the actual order.',\n );\n }\n }\n\n const slippageFactor = 40; // 2.5%\n const orderPriceLimitE18 = calculatePriceLimitForTrade(\n params.market.currentPrice,\n -closingBase,\n slippageFactor,\n );\n\n const chainId = getReyaNetwork();\n const {\n calldata: data,\n payload: eip712Payload,\n signature: eip712Signature,\n } = await encodeMatchOrder(\n params.signer,\n chainId,\n params.owner.coreSigNonce,\n params.marginAccountId,\n -scale(18)(closingBase),\n orderPriceLimitE18,\n params.market.counterpartyAccountIds,\n params.market.id,\n params.market.exchangeId,\n );\n\n const result = await signAndBroadcastTransaction(\n data,\n chainId,\n ContractType.PERIPHERY_PROXY,\n {\n action: 'closeOrder',\n accountId: params.marginAccountId,\n marketId: params.market.id,\n matchOrder: {\n userEIP712Signature: eip712Signature,\n eip712Payload,\n },\n },\n );\n\n return {\n transactionHash: result?.txHash || null,\n coreSigNonce: Number(result?.coreSigNonce) || null,\n xpBoost: result.miscellaneous?.tradeXpBoost || 0,\n lotteryXpBoost: result.miscellaneous?.lotteryXpBoost || 0,\n isNftWon: result.miscellaneous?.xpNftAwarded || false,\n marginAccountId: params.marginAccountId,\n xpEarned: result.miscellaneous?.xpEarned || 0,\n executionPrice: result.tradeDetails?.executionPrice || 0,\n base: result.tradeDetails?.base || 0,\n };\n};\n\nexport const closeOrderV2 = async (\n params: CloseOrderParams,\n): Promise<CloseOrderResult> => {\n if (params.orderBase === 0) {\n throw new Error('Position is already closed.');\n }\n\n let closingBase: number = 0;\n if (params.type === 'full') {\n closingBase = params.orderBase;\n } else {\n closingBase = params.closingOrderBase;\n\n if (closingBase === 0) {\n throw new Error('Specified base to close is zero.');\n }\n\n if (closingBase * params.orderBase < 0) {\n throw new Error(\n 'Specified base to close is in different direction that the actual order.',\n );\n }\n\n if (Math.abs(closingBase) > Math.abs(params.orderBase)) {\n throw new Error(\n 'Specified base to close is larger than the actual order.',\n );\n }\n }\n\n const slippageFactor = 40; // 2.5%\n const orderPriceLimit = calculatePriceLimitForTrade(\n params.market.currentPrice,\n -closingBase,\n slippageFactor,\n );\n\n const result = await executeMarketOrderViaOrdersGateway({\n signer: params.signer,\n marginAccountId: params.marginAccountId,\n counterpartyAccountIds: params.market.counterpartyAccountIds,\n marketId: params.market.id,\n exchangeId: params.market.exchangeId,\n order: {\n baseE18: -scale(18)(closingBase),\n priceLimitE18: orderPriceLimit,\n type: OrdersGatewayOrderType.REDUCE_ONLY_MARKET_ORDER,\n },\n });\n\n return {\n transactionHash: result?.txHash || null,\n coreSigNonce: Number(result?.coreSigNonce) || null,\n xpBoost: result.miscellaneous?.tradeXpBoost || 0,\n lotteryXpBoost: result.miscellaneous?.lotteryXpBoost || 0,\n isNftWon: result.miscellaneous?.xpNftAwarded || false,\n marginAccountId: params.marginAccountId,\n xpEarned: result.miscellaneous?.xpEarned || 0,\n executionPrice: result.tradeDetails?.executionPrice || 0,\n base: result.tradeDetails?.base || 0,\n };\n};\n\nconst isCloseOrderV2 =\n process.env.CLOSE_ORDER_VIA_ORDERS_GATEWAY_ENABLED === 'true' || false;\nexport const closeOrder = isCloseOrderV2 ? closeOrderV2 : closeOrderV1;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"/","sources":["services/orders/types.ts"],"names":[],"mappings":"","sourcesContent":["import { Signer, JsonRpcSigner } from 'ethers';\nimport {\n CoreCommandsEIP712SignatureAndPayload,\n MarginAccountEntity,\n MarketEntity,\n MethodParameters,\n OwnerMetadataEntity,\n PositionEntity,\n TransactionExecutionOutput,\n} from '@reyaxyz/common';\n\nexport type MarketParams = {\n id: MarketEntity['id'];\n exchangeId: MarketEntity['orderInfo']['exchangeId'];\n counterpartyAccountIds: MarketEntity['orderInfo']['counterpartyAccountIds'];\n currentPrice: number;\n minOrderSizeBase: MarketEntity['minOrderSizeBase'];\n baseSpacing: MarketEntity['baseSpacing'];\n};\n\nexport type MatchOrderParams = {\n signer: Signer | JsonRpcSigner;\n owner: Pick<OwnerMetadataEntity, 'coreSigNonce'>;\n marginAccountId: MarginAccountEntity['id'];\n amountInBase: number; // amount in base\n market: MarketParams;\n tradeSource?: 'reya' | 'rage' | 'other';\n};\n\nexport type CloseOrderParams = {\n signer: Signer | JsonRpcSigner;\n owner: Pick<OwnerMetadataEntity, 'coreSigNonce'>;\n marginAccountId: MarginAccountEntity['id'];\n orderBase: PositionEntity['base'];\n market: MarketParams;\n} & (\n | {\n type: 'full';\n }\n | {\n type: 'partial';\n closingOrderBase: number;\n }\n);\n\nexport type MatchOrderResult = {\n transactionHash: string | null;\n coreSigNonce: OwnerMetadataEntity['coreSigNonce'] | null;\n xpBoost: number;\n lotteryXpBoost: number;\n isNftWon: boolean;\n marginAccountId: MarginAccountEntity['id'];\n xpEarned: number;\n executionPrice: number;\n base: number;\n positions?: TransactionExecutionOutput['positions'];\n orders?: TransactionExecutionOutput['orders'];\n accounts?: TransactionExecutionOutput['accounts'];\n};\n\nexport type CloseOrderResult = {\n transactionHash: string | null;\n coreSigNonce: OwnerMetadataEntity['coreSigNonce'] | null;\n xpBoost: number;\n lotteryXpBoost: number;\n isNftWon: boolean;\n marginAccountId: MarginAccountEntity['id'];\n xpEarned: number;\n executionPrice: number;\n base: number;\n};\n\nexport type MethodParametersAndEIP712Payload = MethodParameters &\n CoreCommandsEIP712SignatureAndPayload;\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"/","sources":["services/orders/types.ts"],"names":[],"mappings":"","sourcesContent":["import { Signer, JsonRpcSigner } from 'ethers';\nimport {\n CoreCommandsEIP712SignatureAndPayload,\n MarginAccountEntity,\n MarketEntity,\n MethodParameters,\n OrdersGatewayOrderType,\n OwnerMetadataEntity,\n PositionEntity,\n TransactionExecutionOutput,\n} from '@reyaxyz/common';\n\nexport type MarketParams = {\n id: MarketEntity['id'];\n exchangeId: MarketEntity['orderInfo']['exchangeId'];\n counterpartyAccountIds: MarketEntity['orderInfo']['counterpartyAccountIds'];\n currentPrice: number;\n minOrderSizeBase: MarketEntity['minOrderSizeBase'];\n baseSpacing: MarketEntity['baseSpacing'];\n};\n\nexport type MatchOrderParams = {\n signer: Signer | JsonRpcSigner;\n owner: Pick<OwnerMetadataEntity, 'coreSigNonce'>;\n marginAccountId: MarginAccountEntity['id'];\n amountInBase: number; // amount in base\n market: MarketParams;\n tradeSource?: 'reya' | 'rage' | 'other';\n};\n\nexport type CloseOrderParams = {\n signer: Signer | JsonRpcSigner;\n owner: Pick<OwnerMetadataEntity, 'coreSigNonce'>;\n marginAccountId: MarginAccountEntity['id'];\n orderBase: PositionEntity['base'];\n market: MarketParams;\n} & (\n | {\n type: 'full';\n }\n | {\n type: 'partial';\n closingOrderBase: number;\n }\n);\n\nexport type MatchOrderResult = {\n transactionHash: string | null;\n coreSigNonce: OwnerMetadataEntity['coreSigNonce'] | null;\n xpBoost: number;\n lotteryXpBoost: number;\n isNftWon: boolean;\n marginAccountId: MarginAccountEntity['id'];\n xpEarned: number;\n executionPrice: number;\n base: number;\n positions?: TransactionExecutionOutput['positions'];\n orders?: TransactionExecutionOutput['orders'];\n accounts?: TransactionExecutionOutput['accounts'];\n};\n\nexport type CloseOrderResult = {\n transactionHash: string | null;\n coreSigNonce: OwnerMetadataEntity['coreSigNonce'] | null;\n xpBoost: number;\n lotteryXpBoost: number;\n isNftWon: boolean;\n marginAccountId: MarginAccountEntity['id'];\n xpEarned: number;\n executionPrice: number;\n base: number;\n};\n\nexport type MethodParametersAndEIP712Payload = MethodParameters &\n CoreCommandsEIP712SignatureAndPayload;\n\nexport type OrdersGatewayMarketOrderParams = {\n signer: Signer | JsonRpcSigner;\n marginAccountId: MarginAccountEntity['id'];\n marketId: MarketEntity['id'];\n counterpartyAccountIds: MarketEntity['orderInfo']['counterpartyAccountIds'];\n exchangeId: MarketEntity['orderInfo']['exchangeId'];\n order: {\n baseE18: bigint;\n priceLimitE18: bigint;\n type:\n | OrdersGatewayOrderType.MARKET_ORDER\n | OrdersGatewayOrderType.REDUCE_ONLY_MARKET_ORDER;\n };\n tradeSource?: 'reya' | 'rage' | 'other';\n};\n"]}
@@ -1,4 +1,6 @@
1
1
  import { CloseOrderParams, CloseOrderResult, MatchOrderParams, MatchOrderResult } from './types';
2
2
  export declare const matchOrder: (params: MatchOrderParams) => Promise<MatchOrderResult>;
3
+ export declare const closeOrderV1: (params: CloseOrderParams) => Promise<CloseOrderResult>;
4
+ export declare const closeOrderV2: (params: CloseOrderParams) => Promise<CloseOrderResult>;
3
5
  export declare const closeOrder: (params: CloseOrderParams) => Promise<CloseOrderResult>;
4
6
  //# sourceMappingURL=order.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"order.d.ts","sourceRoot":"/","sources":["services/orders/order.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EACjB,MAAM,SAAS,CAAC;AASjB,eAAO,MAAM,UAAU,WACb,gBAAgB,KACvB,QAAQ,gBAAgB,CAiF1B,CAAC;AAEF,eAAO,MAAM,UAAU,WACb,gBAAgB,KACvB,QAAQ,gBAAgB,CA8E1B,CAAC"}
1
+ {"version":3,"file":"order.d.ts","sourceRoot":"/","sources":["services/orders/order.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAEjB,MAAM,SAAS,CAAC;AA8NjB,eAAO,MAAM,UAAU,WAnJb,gBAAgB,KACvB,QAAQ,gBAAgB,CAkJ2C,CAAC;AAEvE,eAAO,MAAM,YAAY,WACf,gBAAgB,KACvB,QAAQ,gBAAgB,CA8E1B,CAAC;AAEF,eAAO,MAAM,YAAY,WACf,gBAAgB,KACvB,QAAQ,gBAAgB,CA2D1B,CAAC;AAIF,eAAO,MAAM,UAAU,WAlJb,gBAAgB,KACvB,QAAQ,gBAAgB,CAiJ2C,CAAC"}
@@ -1,5 +1,5 @@
1
1
  import { Signer, JsonRpcSigner } from 'ethers';
2
- import { CoreCommandsEIP712SignatureAndPayload, MarginAccountEntity, MarketEntity, MethodParameters, OwnerMetadataEntity, PositionEntity, TransactionExecutionOutput } from '@reyaxyz/common';
2
+ import { CoreCommandsEIP712SignatureAndPayload, MarginAccountEntity, MarketEntity, MethodParameters, OrdersGatewayOrderType, OwnerMetadataEntity, PositionEntity, TransactionExecutionOutput } from '@reyaxyz/common';
3
3
  export type MarketParams = {
4
4
  id: MarketEntity['id'];
5
5
  exchangeId: MarketEntity['orderInfo']['exchangeId'];
@@ -54,4 +54,17 @@ export type CloseOrderResult = {
54
54
  base: number;
55
55
  };
56
56
  export type MethodParametersAndEIP712Payload = MethodParameters & CoreCommandsEIP712SignatureAndPayload;
57
+ export type OrdersGatewayMarketOrderParams = {
58
+ signer: Signer | JsonRpcSigner;
59
+ marginAccountId: MarginAccountEntity['id'];
60
+ marketId: MarketEntity['id'];
61
+ counterpartyAccountIds: MarketEntity['orderInfo']['counterpartyAccountIds'];
62
+ exchangeId: MarketEntity['orderInfo']['exchangeId'];
63
+ order: {
64
+ baseE18: bigint;
65
+ priceLimitE18: bigint;
66
+ type: OrdersGatewayOrderType.MARKET_ORDER | OrdersGatewayOrderType.REDUCE_ONLY_MARKET_ORDER;
67
+ };
68
+ tradeSource?: 'reya' | 'rage' | 'other';
69
+ };
57
70
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"/","sources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C,wBAAwB,CAAC,CAAC;IAC5E,UAAU,EAAE,YAAY,CAAC,WAAW,CAAC,CAAC,YAAY,CAAC,CAAC;IACpD,KAAK,EAAE;QACL,OAAO,EAAE,MAAM,CAAC;QAChB,aAAa,EAAE,MAAM,CAAC;QACtB,IAAI,EACA,sBAAsB,CAAC,YAAY,GACnC,sBAAsB,CAAC,wBAAwB,CAAC;KACrD,CAAC;IACF,WAAW,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC;CACzC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reyaxyz/sdk",
3
- "version": "0.130.6",
3
+ "version": "0.131.0",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "registry": "https://registry.npmjs.org"
@@ -29,11 +29,11 @@
29
29
  "generate:coverage-badges": "npx istanbul-badges-readme --silent"
30
30
  },
31
31
  "dependencies": {
32
- "@reyaxyz/common": "0.274.4",
32
+ "@reyaxyz/common": "0.275.0",
33
33
  "axios": "^1.6.2",
34
34
  "bignumber.js": "^9.1.2",
35
35
  "ethers": "6.9.0"
36
36
  },
37
37
  "packageManager": "pnpm@8.3.1",
38
- "gitHead": "b16328fd4fcad352c0099099f7a4326e2cc90884"
38
+ "gitHead": "09cb76961daa610f13180f612a26fa5e418961bf"
39
39
  }
@@ -3,20 +3,86 @@ import {
3
3
  CloseOrderResult,
4
4
  MatchOrderParams,
5
5
  MatchOrderResult,
6
+ OrdersGatewayMarketOrderParams,
6
7
  } from './types';
7
8
  import { encodeMatchOrder } from './encode';
8
9
  import { signAndBroadcastTransaction } from '../signAndBroadcastTransaction';
9
- import { calculatePriceLimitForTrade } from '@reyaxyz/common';
10
+ import {
11
+ calculatePriceLimitForTrade,
12
+ ORDERS_GATEWAY_DEADLINE_IN_SECONDS,
13
+ OrdersGatewayAbi,
14
+ OrdersGatewayOrderType,
15
+ signOrdersGatewayOrder,
16
+ TransactionExecutionOutput,
17
+ } from '@reyaxyz/common';
10
18
  import BigNumber from 'bignumber.js';
11
19
  import { ContractType } from '@reyaxyz/common';
12
20
  import { scale } from '@reyaxyz/common';
13
21
  import { getReyaNetwork } from '../../utils/network';
22
+ import { AbiCoder, Interface } from 'ethers';
23
+
24
+ const executeMarketOrderViaOrdersGateway = async (
25
+ params: OrdersGatewayMarketOrderParams,
26
+ ): Promise<TransactionExecutionOutput> => {
27
+ const inputs = AbiCoder.defaultAbiCoder().encode(
28
+ ['int256', 'uint256'],
29
+ [params.order.baseE18, params.order.priceLimitE18],
30
+ );
31
+
32
+ const reyaChainId = getReyaNetwork();
33
+ const creationTimestampMs = Date.now();
34
+ const creationTimestampSeconds = Math.floor(creationTimestampMs / 1000);
35
+
36
+ const { signature, nonce } = await signOrdersGatewayOrder(
37
+ params.signer,
38
+ reyaChainId,
39
+ params.marginAccountId,
40
+ params.marketId,
41
+ params.exchangeId,
42
+ params.counterpartyAccountIds,
43
+ params.order.type,
44
+ inputs,
45
+ creationTimestampSeconds + ORDERS_GATEWAY_DEADLINE_IN_SECONDS,
46
+ creationTimestampMs,
47
+ );
48
+
49
+ const fnSig = 'execute';
50
+ const fnArgs = [
51
+ [
52
+ params.marginAccountId,
53
+ params.marketId,
54
+ params.exchangeId,
55
+ params.counterpartyAccountIds,
56
+ params.order.type,
57
+ inputs,
58
+ await params.signer.getAddress(),
59
+ nonce,
60
+ ],
61
+ [signature.v, signature.r, signature.s, signature.deadline],
62
+ ];
63
+
64
+ const ogInterface = new Interface(OrdersGatewayAbi);
65
+ const data = ogInterface.encodeFunctionData(fnSig, fnArgs);
66
+
67
+ const result = await signAndBroadcastTransaction(
68
+ data,
69
+ reyaChainId,
70
+ ContractType.ORDERS_GATEWAY_PROXY,
71
+ {
72
+ accountId: params.marginAccountId,
73
+ marketId: params.marketId,
74
+ tradeSource: params.tradeSource,
75
+ },
76
+ );
77
+
78
+ return result;
79
+ };
14
80
 
15
- export const matchOrder = async (
81
+ const matchOrderV1 = async (
16
82
  params: MatchOrderParams,
17
83
  ): Promise<MatchOrderResult> => {
18
84
  if (params.amountInBase === 0) {
19
- throw new Error('Position base can not be 0');
85
+ throw new Error('Order cannot be of size zero.');
20
86
  }
21
87
 
22
88
  let snappedAmount = BigNumber(params.amountInBase)
@@ -37,16 +103,14 @@ export const matchOrder = async (
37
103
  throw new Error(`Minimum trade amount ${params.market.minOrderSizeBase}`);
38
104
  }
39
105
 
106
+ const orderBaseE18 = scale(18)(snappedAmount);
40
107
  const slippageFactor = 40; // 2.5%
41
-
42
- // add rounding here
43
- const orderPriceLimit = calculatePriceLimitForTrade(
108
+ const orderPriceLimitE18 = calculatePriceLimitForTrade(
44
109
  params.market.currentPrice,
45
110
  snappedAmount,
46
111
  slippageFactor,
47
112
  );
48
113
 
49
- const orderBase = scale(18)(snappedAmount);
50
114
  const chainId = getReyaNetwork();
51
115
 
52
116
  const {
@@ -58,8 +122,8 @@ export const matchOrder = async (
58
122
  chainId,
59
123
  params.owner.coreSigNonce,
60
124
  params.marginAccountId,
61
- orderBase,
62
- orderPriceLimit,
125
+ orderBaseE18,
126
+ orderPriceLimitE18,
63
127
  params.market.counterpartyAccountIds,
64
128
  params.market.id,
65
129
  params.market.exchangeId,
@@ -97,7 +161,74 @@ export const matchOrder = async (
97
161
  };
98
162
  };
99
163
 
100
- export const closeOrder = async (
164
+ const matchOrderV2 = async (
165
+ params: MatchOrderParams,
166
+ ): Promise<MatchOrderResult> => {
167
+ if (params.amountInBase === 0) {
168
+ throw new Error('Order cannot be of size zero.');
169
+ }
170
+
171
+ let snappedAmount = BigNumber(params.amountInBase)
172
+ .abs()
173
+ .dividedBy(params.market.baseSpacing)
174
+ .integerValue(BigNumber.ROUND_FLOOR)
175
+ .multipliedBy(params.market.baseSpacing)
176
+ .toNumber();
177
+
178
+ if (params.amountInBase < 0) {
179
+ snappedAmount = -snappedAmount;
180
+ }
181
+
182
+ if (Math.abs(snappedAmount) < params.market.minOrderSizeBase) {
183
+ console.error(
184
+ `Minimum trade amount ${params.market.minOrderSizeBase}. Entered amount ${snappedAmount}, ${params.amountInBase}`,
185
+ );
186
+ throw new Error(`Minimum trade amount ${params.market.minOrderSizeBase}`);
187
+ }
188
+
189
+ const orderBaseE18 = scale(18)(snappedAmount);
190
+ const slippageFactor = 40; // 2.5%
191
+ const orderPriceLimitE18 = calculatePriceLimitForTrade(
192
+ params.market.currentPrice,
193
+ snappedAmount,
194
+ slippageFactor,
195
+ );
196
+
197
+ const result = await executeMarketOrderViaOrdersGateway({
198
+ signer: params.signer,
199
+ marginAccountId: params.marginAccountId,
200
+ counterpartyAccountIds: params.market.counterpartyAccountIds,
201
+ marketId: params.market.id,
202
+ exchangeId: params.market.exchangeId,
203
+ tradeSource: params.tradeSource,
204
+ order: {
205
+ baseE18: orderBaseE18,
206
+ priceLimitE18: orderPriceLimitE18,
207
+ type: OrdersGatewayOrderType.MARKET_ORDER,
208
+ },
209
+ });
210
+
211
+ return {
212
+ transactionHash: result?.txHash || null,
213
+ coreSigNonce: Number(result?.coreSigNonce) || null,
214
+ xpBoost: result.miscellaneous?.tradeXpBoost || 0,
215
+ lotteryXpBoost: result.miscellaneous?.lotteryXpBoost || 0,
216
+ isNftWon: result.miscellaneous?.xpNftAwarded || false,
217
+ marginAccountId: params.marginAccountId,
218
+ xpEarned: result.miscellaneous?.xpEarned || 0,
219
+ executionPrice: result.tradeDetails?.executionPrice || 0,
220
+ base: result.tradeDetails?.base || 0,
221
+ positions: result.positions,
222
+ orders: result.orders,
223
+ accounts: result.accounts,
224
+ };
225
+ };
226
+
227
+ const isMatchOrderV2 =
228
+ process.env.MATCH_ORDER_VIA_ORDERS_GATEWAY_ENABLED === 'true' || false;
229
+ export const matchOrder = isMatchOrderV2 ? matchOrderV2 : matchOrderV1;
230
+
231
+ export const closeOrderV1 = async (
101
232
  params: CloseOrderParams,
102
233
  ): Promise<CloseOrderResult> => {
103
234
  if (params.orderBase === 0) {
@@ -128,7 +259,7 @@ export const closeOrder = async (
128
259
  }
129
260
 
130
261
  const slippageFactor = 40; // 2.5%
131
- const orderPriceLimit = calculatePriceLimitForTrade(
262
+ const orderPriceLimitE18 = calculatePriceLimitForTrade(
132
263
  params.market.currentPrice,
133
264
  -closingBase,
134
265
  slippageFactor,
@@ -145,7 +276,7 @@ export const closeOrder = async (
145
276
  params.owner.coreSigNonce,
146
277
  params.marginAccountId,
147
278
  -scale(18)(closingBase),
148
- orderPriceLimit,
279
+ orderPriceLimitE18,
149
280
  params.market.counterpartyAccountIds,
150
281
  params.market.id,
151
282
  params.market.exchangeId,
@@ -178,3 +309,70 @@ export const closeOrder = async (
178
309
  base: result.tradeDetails?.base || 0,
179
310
  };
180
311
  };
312
+
313
+ export const closeOrderV2 = async (
314
+ params: CloseOrderParams,
315
+ ): Promise<CloseOrderResult> => {
316
+ if (params.orderBase === 0) {
317
+ throw new Error('Position is already closed.');
318
+ }
319
+
320
+ let closingBase: number = 0;
321
+ if (params.type === 'full') {
322
+ closingBase = params.orderBase;
323
+ } else {
324
+ closingBase = params.closingOrderBase;
325
+
326
+ if (closingBase === 0) {
327
+ throw new Error('Specified base to close is zero.');
328
+ }
329
+
330
+ if (closingBase * params.orderBase < 0) {
331
+ throw new Error(
332
+ 'Specified base to close is in different direction that the actual order.',
333
+ );
334
+ }
335
+
336
+ if (Math.abs(closingBase) > Math.abs(params.orderBase)) {
337
+ throw new Error(
338
+ 'Specified base to close is larger than the actual order.',
339
+ );
340
+ }
341
+ }
342
+
343
+ const slippageFactor = 40; // 2.5%
344
+ const orderPriceLimit = calculatePriceLimitForTrade(
345
+ params.market.currentPrice,
346
+ -closingBase,
347
+ slippageFactor,
348
+ );
349
+
350
+ const result = await executeMarketOrderViaOrdersGateway({
351
+ signer: params.signer,
352
+ marginAccountId: params.marginAccountId,
353
+ counterpartyAccountIds: params.market.counterpartyAccountIds,
354
+ marketId: params.market.id,
355
+ exchangeId: params.market.exchangeId,
356
+ order: {
357
+ baseE18: -scale(18)(closingBase),
358
+ priceLimitE18: orderPriceLimit,
359
+ type: OrdersGatewayOrderType.REDUCE_ONLY_MARKET_ORDER,
360
+ },
361
+ });
362
+
363
+ return {
364
+ transactionHash: result?.txHash || null,
365
+ coreSigNonce: Number(result?.coreSigNonce) || null,
366
+ xpBoost: result.miscellaneous?.tradeXpBoost || 0,
367
+ lotteryXpBoost: result.miscellaneous?.lotteryXpBoost || 0,
368
+ isNftWon: result.miscellaneous?.xpNftAwarded || false,
369
+ marginAccountId: params.marginAccountId,
370
+ xpEarned: result.miscellaneous?.xpEarned || 0,
371
+ executionPrice: result.tradeDetails?.executionPrice || 0,
372
+ base: result.tradeDetails?.base || 0,
373
+ };
374
+ };
375
+
376
+ const isCloseOrderV2 =
377
+ process.env.CLOSE_ORDER_VIA_ORDERS_GATEWAY_ENABLED === 'true' || false;
378
+ export const closeOrder = isCloseOrderV2 ? closeOrderV2 : closeOrderV1;
@@ -4,6 +4,7 @@ import {
4
4
  MarginAccountEntity,
5
5
  MarketEntity,
6
6
  MethodParameters,
7
+ OrdersGatewayOrderType,
7
8
  OwnerMetadataEntity,
8
9
  PositionEntity,
9
10
  TransactionExecutionOutput,
@@ -72,3 +73,19 @@ export type CloseOrderResult = {
72
73
 
73
74
  export type MethodParametersAndEIP712Payload = MethodParameters &
74
75
  CoreCommandsEIP712SignatureAndPayload;
76
+
77
+ export type OrdersGatewayMarketOrderParams = {
78
+ signer: Signer | JsonRpcSigner;
79
+ marginAccountId: MarginAccountEntity['id'];
80
+ marketId: MarketEntity['id'];
81
+ counterpartyAccountIds: MarketEntity['orderInfo']['counterpartyAccountIds'];
82
+ exchangeId: MarketEntity['orderInfo']['exchangeId'];
83
+ order: {
84
+ baseE18: bigint;
85
+ priceLimitE18: bigint;
86
+ type:
87
+ | OrdersGatewayOrderType.MARKET_ORDER
88
+ | OrdersGatewayOrderType.REDUCE_ONLY_MARKET_ORDER;
89
+ };
90
+ tradeSource?: 'reya' | 'rage' | 'other';
91
+ };