@reyaxyz/sdk 0.146.5-perpob.89 → 0.146.5-perpob.95

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.
@@ -47,7 +47,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
47
47
  }
48
48
  };
49
49
  Object.defineProperty(exports, "__esModule", { value: true });
50
- exports.modifyMEOrder = exports.cancelAllAfter = exports.closePosition = exports.createIOCOrder = exports.massCancelMEOrders = exports.cancelMEOrder = exports.createOrder = void 0;
50
+ exports.modifyMEOrder = exports.cancelAllAfter = exports.closePosition = exports.createIOCOrder = exports.massCancelMEOrders = exports.cancelMEOrder = exports.createOrder = exports.toOnChainTimeInForce = exports.toOnChainOrderType = void 0;
51
51
  var ethers_1 = require("ethers");
52
52
  var api_v2_sdk_1 = require("@reyaxyz/api-v2-sdk");
53
53
  var common_1 = require("@reyaxyz/common");
@@ -77,6 +77,7 @@ var toOnChainOrderType = function (orderType) {
77
77
  throw new Error("Unsupported orderType: ".concat(orderType));
78
78
  }
79
79
  };
80
+ exports.toOnChainOrderType = toOnChainOrderType;
80
81
  // Maps the REST-surface `TimeInForce` to the numeric value signed into
81
82
  // `OrderDetails.timeInForce`, matching the off-chain verifier's
82
83
  // REST_TIME_IN_FORCE_TO_NUMERIC (common-backend signature-validation):
@@ -89,8 +90,11 @@ var toOnChainTimeInForce = function (timeInForce) {
89
90
  return 1;
90
91
  case 'GTT':
91
92
  return 2;
93
+ default:
94
+ throw new Error("Unsupported timeInForce: ".concat(timeInForce));
92
95
  }
93
96
  };
97
+ exports.toOnChainTimeInForce = toOnChainTimeInForce;
94
98
  var DEFAULT_DEADLINE_SECONDS = 30;
95
99
  var isZeroClientOrderId = function (clientOrderId) {
96
100
  return clientOrderId !== undefined && /^0+$/.test(clientOrderId.trim());
@@ -139,11 +143,11 @@ var createOrder = function (params) { return __awaiter(void 0, void 0, void 0, f
139
143
  accountId: params.accountId,
140
144
  marketId: params.marketId,
141
145
  exchangeId: params.exchangeId,
142
- orderType: toOnChainOrderType(params.orderType),
146
+ orderType: (0, exports.toOnChainOrderType)(params.orderType),
143
147
  quantity: quantity,
144
148
  limitPrice: limitPrice,
145
149
  triggerPrice: triggerPrice,
146
- timeInForce: toOnChainTimeInForce(params.timeInForce),
150
+ timeInForce: (0, exports.toOnChainTimeInForce)(params.timeInForce),
147
151
  clientOrderId: BigInt((_d = params.clientOrderId) !== null && _d !== void 0 ? _d : 0),
148
152
  reduceOnly: (_e = params.reduceOnly) !== null && _e !== void 0 ? _e : false,
149
153
  postOnly: (_f = params.postOnly) !== null && _f !== void 0 ? _f : false,
@@ -407,11 +411,11 @@ var modifyMEOrder = function (params) { return __awaiter(void 0, void 0, void 0,
407
411
  accountId: params.accountId,
408
412
  marketId: params.marketId,
409
413
  exchangeId: params.exchangeId,
410
- orderType: toOnChainOrderType(params.orderType),
414
+ orderType: (0, exports.toOnChainOrderType)(params.orderType),
411
415
  quantity: quantity,
412
416
  limitPrice: limitPrice,
413
417
  triggerPrice: triggerPrice,
414
- timeInForce: toOnChainTimeInForce(params.timeInForce),
418
+ timeInForce: (0, exports.toOnChainTimeInForce)(params.timeInForce),
415
419
  clientOrderId: BigInt((_c = params.clientOrderId) !== null && _c !== void 0 ? _c : '0'),
416
420
  reduceOnly: (_d = params.reduceOnly) !== null && _d !== void 0 ? _d : false,
417
421
  postOnly: params.postOnly,
@@ -1 +1 @@
1
- {"version":3,"file":"orderV2.js","sourceRoot":"/","sources":["services/orders/orderV2.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iCAA2D;AAC3D,kDAU6B;AAC7B,0CAMyB;AACzB,+CAAqD;AACrD,uCAA4C;AAC5C,iCAAoC;AAEpC,2EAA2E;AAC3E,+EAA+E;AAC/E,yEAAyE;AACzE,oDAAoD;AACpD,IAAM,mBAAmB,GAAG,UAAC,KAAyB;IACpD,IAAM,OAAO,GAAG,KAAK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AI,EAAE,EAAE;4BACjD,CAAC,CAAC,EAAE,CAAC,KACP,MAAM,EAAE,MAAM,CAAC,MAAM,EACrB,SAAS,EAAE,MAAM,CAAC,SAAS,EAC3B,UAAU,EAAE,MAAM,CAAC,UAAU,EAC7B,KAAK,EAAE,MAAM,CAAC,KAAK,EACnB,SAAS,EAAE,MAAM,CAAC,SAAS,EAC3B,WAAW,EAAE,MAAM,CAAC,WAAW,KAC5B,CAAC,MAAM,CAAC,SAAS,KAAK,SAAS,IAAI,EAAE,SAAS,EAAE,MAAM,CAAC,SAAS,EAAE,CAAC;4BACtE,uEAAuE;4BACvE,uEAAuE;4BACvE,UAAU,EAAE,MAAA,MAAM,CAAC,UAAU,mCAAI,KAAK,EACtC,OAAO,EAAE,MAAM,CAAC,OAAO,EACvB,GAAG,EAAE,MAAM,CAAC,GAAG,EACf,QAAQ,EAAE,MAAM,CAAC,QAAQ,KACtB,CAAC,MAAM,CAAC,YAAY,KAAK,SAAS;4BACnC,MAAM,CAAC,YAAY,KAAK,CAAC,IAAI,EAAE,YAAY,EAAE,MAAM,CAAC,YAAY,EAAE,CAAC,KACrE,SAAS,EAAE,mBAAmB,EAC9B,KAAK,EAAE,KAAK,CAAC,QAAQ,EAAE,EACvB,YAAY,EAAE,aAAa,EAC3B,QAAQ,UAAA,GACT;qBACF,CAAC,EAAA;;gBA1BI,QAAQ,GAAG,SA0Bf;gBAEF,sBAAO,QAAQ,EAAC;;;KACjB,CAAC;AA/GW,QAAA,aAAa,iBA+GxB","sourcesContent":["import { Signer, JsonRpcSigner, parseUnits } from 'ethers';\nimport {\n OrderEntryApi,\n Configuration,\n CreateOrderResponse,\n OrderType,\n TimeInForce,\n CancelOrderResponse,\n MassCancelResponse,\n CancelAllAfterResponse,\n ModifyOrderResponse,\n} from '@reyaxyz/api-v2-sdk';\nimport {\n signOrder,\n signMEOrderCancel,\n signMEMassCancel,\n signMECancelAllAfter,\n OrderType as OnChainOrderType,\n} from '@reyaxyz/common';\nimport { getReyaNetwork } from '../../utils/network';\nimport { getSdkConfig } from '../../config';\nimport { nextNonce } from './nonce';\n\n// A provided, non-zero order id. '' / whitespace / '0' / all-zeros are the\n// engine's \"not provided\" sentinels; normalize them consistently across cancel\n// + modify so a caller passing orderId:'0' (or '') can't sign/target the\n// sentinel or slip past the \"requires an id\" guard.\nconst isProvidedNonZeroId = (value: string | undefined): value is string => {\n const trimmed = value?.trim();\n return !!trimmed && !/^0+$/.test(trimmed);\n};\n\n// Maps the REST-surface `OrderType` (string: 'LIMIT' / 'STOP_LOSS' / 'TAKE_PROFIT',\n// from @reyaxyz/api-v2-sdk) to the on-chain numeric enum signed into\n// `OrderDetails.orderType` (0 / 1 / 2, from @reyaxyz/common).\nconst toOnChainOrderType = (orderType: OrderType): OnChainOrderType => {\n switch (orderType) {\n case 'LIMIT':\n return OnChainOrderType.Limit;\n case 'STOP_LOSS':\n return OnChainOrderType.StopLoss;\n case 'TAKE_PROFIT':\n return OnChainOrderType.TakeProfit;\n default:\n throw new Error(`Unsupported orderType: ${orderType}`);\n }\n};\n\n// Maps the REST-surface `TimeInForce` to the numeric value signed into\n// `OrderDetails.timeInForce`, matching the off-chain verifier's\n// REST_TIME_IN_FORCE_TO_NUMERIC (common-backend signature-validation):\n// GTC=0, IOC=1, GTT=2.\nconst toOnChainTimeInForce = (timeInForce: TimeInForce): number => {\n switch (timeInForce) {\n case 'GTC':\n return 0;\n case 'IOC':\n return 1;\n case 'GTT':\n return 2;\n }\n};\n\nexport type CreateOrderParams = {\n signer: Signer | JsonRpcSigner;\n accountId: number;\n exchangeId: number;\n /** Unified market id: core_id for perp, core_id + 1e10 for spot. */\n marketId: number;\n isBuy: boolean;\n limitPx: string;\n qty: string;\n symbol: string;\n orderType: OrderType;\n timeInForce: TimeInForce;\n /** Required for STOP_LOSS / TAKE_PROFIT; omit for LIMIT. */\n triggerPx?: string;\n /** Perp only; spot markets must set this to false / omit. */\n reduceOnly?: boolean;\n /**\n * Maker-only intent. Signed into OrderDetails. Valid on GTC/GTT; the API\n * rejects it on IOC + TP/SL. Omit / false for a normal order.\n */\n postOnly?: boolean;\n /** Off-chain correlation id. Signed but not on-chain-enforced. */\n clientOrderId?: string;\n /** Unix seconds. On-chain order lifetime; omit for no-expiry orders. */\n expiresAfter?: number;\n /**\n * Unix seconds. EIP-712 signature deadline (envelope). API-enforced at entry.\n * Defaults to now + 30s when omitted.\n */\n deadline?: number;\n /**\n * Optional explicit nonce. Must be strictly greater than the signer's last\n * accepted nonce on the backend. Defaults to a per-signer monotonic µs value.\n */\n nonce?: bigint;\n};\n\nexport type CancelMEOrderParams = {\n signer: Signer | JsonRpcSigner;\n accountId: number;\n marketId: number;\n symbol: string;\n orderId?: string;\n clientOrderId?: string;\n /** Unix seconds; EIP-712 signature deadline. Defaults to now + 30s. */\n deadline?: number;\n /** Optional explicit nonce; otherwise per-signer monotonic µs. */\n nonce?: bigint;\n};\n\nexport type MassCancelMEOrdersParams = {\n signer: Signer | JsonRpcSigner;\n accountId: number;\n marketId?: number;\n symbol?: string;\n /** Unix seconds; EIP-712 signature deadline. Defaults to now + 30s. */\n deadline?: number;\n /** Optional explicit nonce; otherwise per-signer monotonic µs. */\n nonce?: bigint;\n};\n\nconst DEFAULT_DEADLINE_SECONDS = 30;\n\nconst isZeroClientOrderId = (clientOrderId: string | undefined): boolean =>\n clientOrderId !== undefined && /^0+$/.test(clientOrderId.trim());\n\nconst assertNonZeroClientOrderId = (\n clientOrderId: string | undefined,\n): void => {\n if (isZeroClientOrderId(clientOrderId)) {\n throw new Error('clientOrderId must be omitted rather than set to 0');\n }\n};\n\n// Spot unified market ids are offset by 1e10 (see CreateOrderParams.marketId).\n// Spot markets don't support reduceOnly, so reject it at the SDK boundary\n// rather than sign a request the backend will reject.\nconst SPOT_MARKET_ID_OFFSET = 10_000_000_000;\n\nexport const createOrder = async (\n params: CreateOrderParams,\n): Promise<CreateOrderResponse> => {\n assertNonZeroClientOrderId(params.clientOrderId);\n\n const reyaChainId = getReyaNetwork();\n const config = getSdkConfig();\n\n if (\n (params.orderType === OrderType.STOP_LOSS ||\n params.orderType === OrderType.TAKE_PROFIT) &&\n params.triggerPx === undefined\n ) {\n throw new Error(`triggerPx is required for ${params.orderType} orders`);\n }\n\n if (params.reduceOnly && params.marketId >= SPOT_MARKET_ID_OFFSET) {\n throw new Error('reduceOnly is not supported for spot markets');\n }\n\n const signerAddress = await params.signer.getAddress();\n const defaultDeadline =\n Math.floor(Date.now() / 1000) + DEFAULT_DEADLINE_SECONDS;\n const deadline = params.deadline ?? defaultDeadline;\n const expiresAfter = params.expiresAfter ?? 0;\n const nonce = params.nonce ?? nextNonce(signerAddress);\n\n // On-chain `OrderDetails.quantity` is signed int256 (E18): positive for buy,\n // negative for sell. The REST surface keeps `isBuy + qty` (unsigned) for\n // symmetry with the rest of the API; reconstruct the signed value here.\n //\n // Use `parseUnits(str, 18)` to match the off-chain verifier exactly\n // (signature-validation/index.ts). The previous `scale(18)(parseFloat(str))`\n // diverged for |x| < 1e-6 or >= 1e21 (parseFloat exponential form) → a\n // signature mismatch on extreme sizes.\n const quantity = params.isBuy\n ? parseUnits(params.qty, 18)\n : -parseUnits(params.qty, 18);\n const limitPrice = parseUnits(params.limitPx, 18);\n const triggerPrice = params.triggerPx\n ? parseUnits(params.triggerPx, 18)\n : BigInt(0);\n\n const { serializedSignature } = await signOrder(params.signer, reyaChainId, {\n accountId: params.accountId,\n marketId: params.marketId,\n exchangeId: params.exchangeId,\n orderType: toOnChainOrderType(params.orderType),\n quantity,\n limitPrice,\n triggerPrice,\n timeInForce: toOnChainTimeInForce(params.timeInForce),\n clientOrderId: BigInt(params.clientOrderId ?? 0),\n reduceOnly: params.reduceOnly ?? false,\n postOnly: params.postOnly ?? false,\n expiresAfter: BigInt(expiresAfter),\n nonce,\n deadline,\n });\n\n const apiConfig = new Configuration({\n basePath: `${config.apiEndpoint}/v2`,\n });\n\n const orderEntryApi = new OrderEntryApi(apiConfig);\n\n const response = await orderEntryApi.createOrder({\n createOrderRequest: {\n exchangeId: params.exchangeId,\n symbol: params.symbol,\n accountId: params.accountId,\n isBuy: params.isBuy,\n limitPx: params.limitPx,\n qty: params.qty,\n orderType: params.orderType,\n timeInForce: params.timeInForce,\n ...(params.triggerPx !== undefined && { triggerPx: params.triggerPx }),\n ...(params.reduceOnly !== undefined && { reduceOnly: params.reduceOnly }),\n ...(params.postOnly !== undefined && { postOnly: params.postOnly }),\n ...(params.clientOrderId !== undefined && {\n clientOrderId: params.clientOrderId,\n }),\n signature: serializedSignature,\n nonce: nonce.toString(),\n signerWallet: signerAddress,\n deadline,\n ...(params.expiresAfter !== undefined &&\n params.expiresAfter !== 0 && { expiresAfter }),\n },\n });\n\n return response;\n};\n\nexport const cancelMEOrder = async (\n params: CancelMEOrderParams,\n): Promise<CancelOrderResponse> => {\n assertNonZeroClientOrderId(params.clientOrderId);\n\n const reyaChainId = getReyaNetwork();\n const config = getSdkConfig();\n\n // Validation: at least one of orderId or clientOrderId must be provided.\n // Without this check the SDK would sign for `cancel(orderId=0, clOrdId=0)`\n // and the API would either reject with a cryptic signature-mismatch error\n // or — worse — accept and look up a sentinel \"order zero\" that doesn't\n // exist. Better to surface the misuse at the SDK boundary. (PRO-81 C.2.26)\n // Treat '0' as \"not provided\" for both ids — '0' is the engine's\n // not-provided sentinel, so a caller passing clientOrderId:'0' (or\n // orderId:'0') must NOT slip past this guard and sign the sentinel\n // cancel(0,0) it is meant to block. (PRO-81 C.2.26)\n const orderIdProvided = isProvidedNonZeroId(params.orderId);\n const clientOrderIdProvided = isProvidedNonZeroId(params.clientOrderId);\n if (!orderIdProvided && !clientOrderIdProvided) {\n throw new Error(\n 'cancelMEOrder requires either `orderId` or `clientOrderId`',\n );\n }\n\n // When orderId is set, it is the canonical handle — drop clientOrderId\n // from both the signature and the request body. Forwarding both creates\n // ambiguity in server logging and would let a malicious / buggy caller\n // sign one order id while requesting cancellation by a different\n // (client-supplied) id. (PRO-81 C.2.26)\n const signedOrderId = orderIdProvided ? BigInt(params.orderId!) : BigInt(0);\n const signedClOrdId =\n !orderIdProvided && clientOrderIdProvided\n ? BigInt(params.clientOrderId!)\n : BigInt(0);\n\n const signerAddress = await params.signer.getAddress();\n const defaultDeadline =\n Math.floor(Date.now() / 1000) + DEFAULT_DEADLINE_SECONDS;\n const deadline = params.deadline ?? defaultDeadline;\n const nonce = params.nonce ?? nextNonce(signerAddress);\n\n const signature = await signMEOrderCancel(\n params.signer,\n reyaChainId,\n params.accountId,\n params.marketId,\n signedOrderId,\n signedClOrdId,\n nonce,\n deadline,\n );\n\n const apiConfig = new Configuration({\n basePath: `${config.apiEndpoint}/v2`,\n });\n\n const orderEntryApi = new OrderEntryApi(apiConfig);\n\n const response = await orderEntryApi.cancelOrder({\n cancelOrderRequest: {\n accountId: params.accountId,\n symbol: params.symbol,\n orderId: orderIdProvided ? params.orderId!.trim() : undefined,\n // See validation block above: clientOrderId is suppressed in the body\n // whenever orderId is the canonical handle.\n clientOrderId: orderIdProvided ? undefined : params.clientOrderId?.trim(),\n signature: signature,\n nonce: nonce.toString(),\n deadline,\n },\n });\n\n return response;\n};\n\nexport const massCancelMEOrders = async (\n params: MassCancelMEOrdersParams,\n): Promise<MassCancelResponse> => {\n const reyaChainId = getReyaNetwork();\n const config = getSdkConfig();\n\n // Validation: symbol and marketId must be provided together or not at all.\n // The API resolves a symbol → marketId server-side; the signature locks\n // marketId at sign time. If only one is provided we'd ship a body whose\n // server-derived marketId doesn't match the signed marketId (=> opaque\n // signature-validation failure), or — worse — a body that silently\n // cancels the wrong market. (PRO-81 C.2.26)\n const hasSymbol = params.symbol !== undefined;\n const hasMarketId = params.marketId !== undefined;\n if (hasSymbol !== hasMarketId) {\n throw new Error(\n 'massCancelMEOrders requires both `symbol` and `marketId` together, or neither (to mass-cancel across all markets)',\n );\n }\n\n const signerAddress = await params.signer.getAddress();\n const defaultDeadline =\n Math.floor(Date.now() / 1000) + DEFAULT_DEADLINE_SECONDS;\n const deadline = params.deadline ?? defaultDeadline;\n const nonce = params.nonce ?? nextNonce(signerAddress);\n\n const signature = await signMEMassCancel(\n params.signer,\n reyaChainId,\n params.accountId,\n params.marketId ?? 0,\n nonce,\n deadline,\n );\n\n const apiConfig = new Configuration({\n basePath: `${config.apiEndpoint}/v2`,\n });\n\n const orderEntryApi = new OrderEntryApi(apiConfig);\n\n const response = await orderEntryApi.cancelAll({\n massCancelRequest: {\n accountId: params.accountId,\n symbol: params.symbol,\n signature: signature,\n nonce: nonce.toString(),\n deadline,\n },\n });\n\n return response;\n};\n\n// Convenience wrapper: LIMIT order with IOC timeInForce. UI teams may call\n// createOrder directly with `timeInForce: TimeInForce.IOC` instead.\nexport const createIOCOrder = async (\n params: Omit<CreateOrderParams, 'timeInForce'>,\n): Promise<CreateOrderResponse> => {\n return createOrder({\n ...params,\n timeInForce: TimeInForce.IOC,\n });\n};\n\nexport type ClosePositionParams = {\n signer: Signer | JsonRpcSigner;\n accountId: number;\n exchangeId: number;\n marketId: number;\n /** Closing direction — opposite of the current position side. */\n isBuy: boolean;\n /** Slippage gate. */\n limitPx: string;\n /** Position size to close. */\n qty: string;\n symbol: string;\n clientOrderId?: string;\n /** Unix seconds; EIP-712 signature deadline. Defaults to now + 30s. */\n deadline?: number;\n /** Optional explicit nonce override; otherwise generated per-signer. */\n nonce?: bigint;\n};\n\n// Convenience wrapper: close a perp position by submitting a reduce-only LIMIT\n// IOC. The ME will bust fills that overflow the position at the clearing layer.\nexport const closePosition = async (\n params: ClosePositionParams,\n): Promise<CreateOrderResponse> => {\n return createOrder({\n signer: params.signer,\n accountId: params.accountId,\n exchangeId: params.exchangeId,\n marketId: params.marketId,\n isBuy: params.isBuy,\n limitPx: params.limitPx,\n qty: params.qty,\n symbol: params.symbol,\n orderType: OrderType.LIMIT,\n timeInForce: TimeInForce.IOC,\n reduceOnly: true,\n clientOrderId: params.clientOrderId,\n deadline: params.deadline,\n nonce: params.nonce,\n });\n};\n\nexport type CancelAllAfterParams = {\n signer: Signer | JsonRpcSigner;\n accountId: number;\n /**\n * Countdown duration in milliseconds. `0` disarms; any non-zero value must\n * be within [5000, 60000] and arms a fresh countdown of that duration,\n * replacing any previously armed one (re-arming = the refresh/heartbeat).\n * Recommended pattern: arm with 30000 and refresh every ~10-15s.\n */\n timeoutMs: number;\n deadline?: number;\n /**\n * Optional explicit nonce; otherwise a per-signer monotonic µs value. Must be\n * strictly greater than the signer's last accepted nonce on the backend. Note\n * the backend CONSUMES the nonce even when the request later fails (see\n * `cancelAllAfter` below) — an explicit-nonce caller must advance it before\n * retrying; the default `nextNonce` does so automatically.\n */\n nonce?: bigint;\n};\n\nconst CANCEL_ALL_AFTER_TIMEOUT_MIN_MS = 5000;\nconst CANCEL_ALL_AFTER_TIMEOUT_MAX_MS = 60000;\n\n/**\n * Arm, refresh, or disarm the account-scoped cancel-on-disconnect\n * dead-man's-switch. The countdown lives in the matching engine; when it\n * elapses, all of the account's open orders (all markets) are mass-cancelled.\n *\n * Nonce is consumed even on failure: the backend commits the signed nonce\n * atomically when it validates the request, BEFORE forwarding to the matching\n * engine. A failed forward (matching engine unavailable / transport error /\n * ME-side rejection) still burns the nonce — it is not rolled back. On retry\n * you MUST use a strictly higher nonce, or the backend rejects it as\n * `INVALID_NONCE_ERROR`. When `nonce` is omitted this is automatic: the\n * per-signer monotonic `nextNonce` always returns a value greater than the\n * last one it issued, so a plain retry self-recovers. Only callers passing an\n * explicit `nonce` need to advance it themselves before retrying.\n */\nexport const cancelAllAfter = async (\n params: CancelAllAfterParams,\n): Promise<CancelAllAfterResponse> => {\n const reyaChainId = getReyaNetwork();\n const config = getSdkConfig();\n\n // Fail fast on an out-of-range timeout before burning a nonce on a request\n // the server will reject with INPUT_VALIDATION_ERROR anyway.\n if (\n !Number.isInteger(params.timeoutMs) ||\n params.timeoutMs < 0 ||\n (params.timeoutMs !== 0 &&\n (params.timeoutMs < CANCEL_ALL_AFTER_TIMEOUT_MIN_MS ||\n params.timeoutMs > CANCEL_ALL_AFTER_TIMEOUT_MAX_MS))\n ) {\n throw new Error(\n `cancelAllAfter timeoutMs must be 0 (disarm) or between ${CANCEL_ALL_AFTER_TIMEOUT_MIN_MS} and ${CANCEL_ALL_AFTER_TIMEOUT_MAX_MS} milliseconds`,\n );\n }\n\n const signerAddress = await params.signer.getAddress();\n const defaultDeadline =\n Math.floor(Date.now() / 1000) + DEFAULT_DEADLINE_SECONDS;\n const deadline = params.deadline ?? defaultDeadline;\n const nonce = params.nonce ?? nextNonce(signerAddress);\n\n const signature = await signMECancelAllAfter(\n params.signer,\n reyaChainId,\n params.accountId,\n params.timeoutMs,\n nonce,\n deadline,\n );\n\n const apiConfig = new Configuration({\n basePath: `${config.apiEndpoint}/v2`,\n });\n\n const orderEntryApi = new OrderEntryApi(apiConfig);\n\n const response = await orderEntryApi.cancelAllAfter({\n cancelAllAfterRequest: {\n accountId: params.accountId,\n timeoutMs: params.timeoutMs,\n signature: signature,\n nonce: nonce.toString(),\n signerWallet: signerAddress,\n deadline,\n },\n });\n\n return response;\n};\n\nexport type ModifyMEOrderParams = {\n signer: Signer | JsonRpcSigner;\n accountId: number;\n exchangeId: number;\n /** Unified market id: core_id for perp, core_id + 1e10 for spot. */\n marketId: number;\n symbol: string;\n /** Targeting: provide `orderId`, or a non-zero `clientOrderId`; both may be provided. */\n orderId?: string;\n clientOrderId?: string;\n /**\n * Full post-modify order state. The SDK does not fetch the resting order —\n * the caller supplies every field, and the EIP-712 signature commits to\n * all of them. Modifiable fields are limitPx, qty, postOnly, expiresAfter,\n * and triggerPx. There is no omitted-means-inherited shorthand, so unchanged\n * values must be restated explicitly; LIMIT orders omit triggerPx and sign\n * triggerPrice = 0. Non-modifiable fields (isBuy, orderType, timeInForce,\n * reduceOnly) must match the resting order's values.\n */\n isBuy: boolean;\n limitPx: string;\n /** TOTAL order quantity (not remaining); must exceed the order's cumQty. */\n qty: string;\n orderType: OrderType;\n timeInForce: TimeInForce;\n triggerPx?: string;\n reduceOnly?: boolean;\n /** Post-modify maker-only flag. Required — restate the resting order's value to keep it. */\n postOnly: boolean;\n /** Unix seconds. Post-modify on-chain order lifetime; omit for no-expiry orders. */\n expiresAfter?: number;\n /**\n * Resting order's clientOrderId, signed into OrderDetails.clientOrderId.\n * If orderId is absent this is also the lookup target and must be non-zero.\n * If orderId is present, orderId targets and clientOrderId only restates the\n * immutable; omit it when the resting order has no client id.\n */\n /** Unix seconds; EIP-712 signature deadline. Defaults to now + 30s. */\n deadline?: number;\n /** Optional explicit nonce; otherwise per-signer monotonic µs. */\n nonce?: bigint;\n};\n\n/**\n * Modify a resting order in place. The order keeps its orderId and\n * clientOrderId; queue priority is preserved only for a qty decrease at an\n * unchanged limitPx. The params carry the COMPLETE post-modify state; a request\n * restating the resting order's exact current state is rejected with\n * EMPTY_MODIFY_ERROR.\n */\nexport const modifyMEOrder = async (\n params: ModifyMEOrderParams,\n): Promise<ModifyOrderResponse> => {\n assertNonZeroClientOrderId(params.clientOrderId);\n\n const reyaChainId = getReyaNetwork();\n const config = getSdkConfig();\n\n // Validate targeting before signing so misuse doesn't burn a nonce. `orderId`\n // wins when both are present; `clientOrderId` still rides along as the\n // restated signed immutable.\n const hasOrderId = isProvidedNonZeroId(params.orderId);\n const hasClientOrderIdTarget = isProvidedNonZeroId(params.clientOrderId);\n if (!hasOrderId && !hasClientOrderIdTarget) {\n throw new Error(\n 'modifyMEOrder requires `orderId` or a non-zero `clientOrderId`',\n );\n }\n\n // triggerPx is required for trigger orders — without it we would silently\n // sign triggerPrice=0. Fail at the SDK boundary (mirrors the cancel/mass-\n // cancel SDK-boundary validation) instead of signing a 0-trigger order.\n if (\n (params.orderType === OrderType.STOP_LOSS ||\n params.orderType === OrderType.TAKE_PROFIT) &&\n params.triggerPx === undefined\n ) {\n throw new Error(`triggerPx is required for ${params.orderType} orders`);\n }\n\n if (params.reduceOnly && params.marketId >= SPOT_MARKET_ID_OFFSET) {\n throw new Error('reduceOnly is not supported for spot markets');\n }\n\n const signerAddress = await params.signer.getAddress();\n const defaultDeadline =\n Math.floor(Date.now() / 1000) + DEFAULT_DEADLINE_SECONDS;\n const deadline = params.deadline ?? defaultDeadline;\n const nonce = params.nonce ?? nextNonce(signerAddress);\n\n // Sign over the exact integers the off-chain verifier reconstructs with\n // `parseUnits(str, 18)` (signature-validation/index.ts). The previous\n // `scale(18)(parseFloat(str))` diverged for |x| < 1e-6 or >= 1e21\n // (parseFloat renders those in exponential form, which `scale` mishandles)\n // → a signature mismatch on extreme sizes. `parseUnits` is exact.\n const quantity = params.isBuy\n ? parseUnits(params.qty, 18)\n : -parseUnits(params.qty, 18);\n const limitPrice = parseUnits(params.limitPx, 18);\n const triggerPrice = params.triggerPx\n ? parseUnits(params.triggerPx, 18)\n : BigInt(0);\n\n const { serializedSignature } = await signOrder(params.signer, reyaChainId, {\n accountId: params.accountId,\n marketId: params.marketId,\n exchangeId: params.exchangeId,\n orderType: toOnChainOrderType(params.orderType),\n quantity,\n limitPrice,\n triggerPrice,\n timeInForce: toOnChainTimeInForce(params.timeInForce),\n clientOrderId: BigInt(params.clientOrderId ?? '0'),\n reduceOnly: params.reduceOnly ?? false,\n postOnly: params.postOnly,\n expiresAfter: BigInt(params.expiresAfter ?? 0),\n nonce,\n deadline,\n });\n\n const apiConfig = new Configuration({\n basePath: `${config.apiEndpoint}/v2`,\n });\n\n const orderEntryApi = new OrderEntryApi(apiConfig);\n\n // Full restate: the body must carry the COMPLETE signed OrderDetails so it\n // reproduces the signed digest exactly (the off-chain verifier\n // `isModifyOrderSignatureValid` reconstructs from these fields, defaulting\n // omitted ones — e.g. timeInForce -> 'GTC', reduceOnly -> false — which would\n // mis-verify a GTT/reduce-only order). The immutables are restated at the\n // resting order's values; the ME rejects a mismatch with MODIFY_IMMUTABLE_MISMATCH.\n const response = await orderEntryApi.modifyOrder({\n modifyOrderRequest: {\n ...(hasOrderId ? { orderId: params.orderId!.trim() } : {}),\n ...(hasClientOrderIdTarget\n ? { clientOrderId: params.clientOrderId!.trim() }\n : {}),\n symbol: params.symbol,\n accountId: params.accountId,\n exchangeId: params.exchangeId,\n isBuy: params.isBuy,\n orderType: params.orderType,\n timeInForce: params.timeInForce,\n ...(params.triggerPx !== undefined && { triggerPx: params.triggerPx }),\n // reduceOnly is a required immutable on ModifyOrderRequest; default to\n // false to match what was signed above (`params.reduceOnly ?? false`).\n reduceOnly: params.reduceOnly ?? false,\n limitPx: params.limitPx,\n qty: params.qty,\n postOnly: params.postOnly,\n ...(params.expiresAfter !== undefined &&\n params.expiresAfter !== 0 && { expiresAfter: params.expiresAfter }),\n signature: serializedSignature,\n nonce: nonce.toString(),\n signerWallet: signerAddress,\n deadline,\n },\n });\n\n return response;\n};\n"]}
1
+ {"version":3,"file":"orderV2.js","sourceRoot":"/","sources":["services/orders/orderV2.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iCAA2D;AAC3D,kDAU6B;AAC7B,0CAMyB;AACzB,+CAAqD;AACrD,uCAA4C;AAC5C,iCAAoC;AAEpC,2EAA2E;AAC3E,+EAA+E;AAC/E,yEAAyE;AACzE,oDAAoD;AACpD,IAAM,mBAAmB,GAAG,UAAC,KAAyB;IACpD,IAAM,OAAO,GAAG,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,IAAI,EAAE,CAAC;IAC9B,OAAO,CAAC,CAAC,OAAO,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AAC5C,CAAC,CAAC;AAEF,oFAAoF;AACpF,qEAAqE;AACrE,8DAA8D;AACvD,IAAM,kBAAkB,GAAG,UAAC,SAAoB;IACrD,QAAQ,SAAS,EAAE,CAAC;QAClB,KAAK,OAAO;YACV,OAAO,kBAAgB,CAAC,KAAK,CAAC;QAChC,KAAK,WAAW;YACd,OAAO,kBAAgB,CAAC,QAAQ,CAAC;QACnC,KAAK,aAAa;YAChB,OAAO,kBAAgB,CAAC,UAAU,CAAC;QACrC;YACE,MAAM,IAAI,KAAK,CAAC,iCAA0B,SAAS,CAAE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C,SAAS,EAAE,CAAC;4BACtE,uEAAuE;4BACvE,uEAAuE;4BACvE,UAAU,EAAE,MAAA,MAAM,CAAC,UAAU,mCAAI,KAAK,EACtC,OAAO,EAAE,MAAM,CAAC,OAAO,EACvB,GAAG,EAAE,MAAM,CAAC,GAAG,EACf,QAAQ,EAAE,MAAM,CAAC,QAAQ,KACtB,CAAC,MAAM,CAAC,YAAY,KAAK,SAAS;4BACnC,MAAM,CAAC,YAAY,KAAK,CAAC,IAAI,EAAE,YAAY,EAAE,MAAM,CAAC,YAAY,EAAE,CAAC,KACrE,SAAS,EAAE,mBAAmB,EAC9B,KAAK,EAAE,KAAK,CAAC,QAAQ,EAAE,EACvB,YAAY,EAAE,aAAa,EAC3B,QAAQ,UAAA,GACT;qBACF,CAAC,EAAA;;gBA1BI,QAAQ,GAAG,SA0Bf;gBAEF,sBAAO,QAAQ,EAAC;;;KACjB,CAAC;AA/GW,QAAA,aAAa,iBA+GxB","sourcesContent":["import { Signer, JsonRpcSigner, parseUnits } from 'ethers';\nimport {\n OrderEntryApi,\n Configuration,\n CreateOrderResponse,\n OrderType,\n TimeInForce,\n CancelOrderResponse,\n MassCancelResponse,\n CancelAllAfterResponse,\n ModifyOrderResponse,\n} from '@reyaxyz/api-v2-sdk';\nimport {\n signOrder,\n signMEOrderCancel,\n signMEMassCancel,\n signMECancelAllAfter,\n OrderType as OnChainOrderType,\n} from '@reyaxyz/common';\nimport { getReyaNetwork } from '../../utils/network';\nimport { getSdkConfig } from '../../config';\nimport { nextNonce } from './nonce';\n\n// A provided, non-zero order id. '' / whitespace / '0' / all-zeros are the\n// engine's \"not provided\" sentinels; normalize them consistently across cancel\n// + modify so a caller passing orderId:'0' (or '') can't sign/target the\n// sentinel or slip past the \"requires an id\" guard.\nconst isProvidedNonZeroId = (value: string | undefined): value is string => {\n const trimmed = value?.trim();\n return !!trimmed && !/^0+$/.test(trimmed);\n};\n\n// Maps the REST-surface `OrderType` (string: 'LIMIT' / 'STOP_LOSS' / 'TAKE_PROFIT',\n// from @reyaxyz/api-v2-sdk) to the on-chain numeric enum signed into\n// `OrderDetails.orderType` (0 / 1 / 2, from @reyaxyz/common).\nexport const toOnChainOrderType = (orderType: OrderType): OnChainOrderType => {\n switch (orderType) {\n case 'LIMIT':\n return OnChainOrderType.Limit;\n case 'STOP_LOSS':\n return OnChainOrderType.StopLoss;\n case 'TAKE_PROFIT':\n return OnChainOrderType.TakeProfit;\n default:\n throw new Error(`Unsupported orderType: ${orderType}`);\n }\n};\n\n// Maps the REST-surface `TimeInForce` to the numeric value signed into\n// `OrderDetails.timeInForce`, matching the off-chain verifier's\n// REST_TIME_IN_FORCE_TO_NUMERIC (common-backend signature-validation):\n// GTC=0, IOC=1, GTT=2.\nexport const toOnChainTimeInForce = (timeInForce: TimeInForce): number => {\n switch (timeInForce) {\n case 'GTC':\n return 0;\n case 'IOC':\n return 1;\n case 'GTT':\n return 2;\n default:\n throw new Error(`Unsupported timeInForce: ${timeInForce}`);\n }\n};\n\nexport type CreateOrderParams = {\n signer: Signer | JsonRpcSigner;\n accountId: number;\n exchangeId: number;\n /** Unified market id: core_id for perp, core_id + 1e10 for spot. */\n marketId: number;\n isBuy: boolean;\n limitPx: string;\n qty: string;\n symbol: string;\n orderType: OrderType;\n timeInForce: TimeInForce;\n /** Required for STOP_LOSS / TAKE_PROFIT; omit for LIMIT. */\n triggerPx?: string;\n /** Perp only; spot markets must set this to false / omit. */\n reduceOnly?: boolean;\n /**\n * Maker-only intent. Signed into OrderDetails. Valid on GTC/GTT; the API\n * rejects it on IOC + TP/SL. Omit / false for a normal order.\n */\n postOnly?: boolean;\n /** Off-chain correlation id. Signed but not on-chain-enforced. */\n clientOrderId?: string;\n /** Unix seconds. On-chain order lifetime; omit for no-expiry orders. */\n expiresAfter?: number;\n /**\n * Unix seconds. EIP-712 signature deadline (envelope). API-enforced at entry.\n * Defaults to now + 30s when omitted.\n */\n deadline?: number;\n /**\n * Optional explicit nonce. Must be strictly greater than the signer's last\n * accepted nonce on the backend. Defaults to a per-signer monotonic µs value.\n */\n nonce?: bigint;\n};\n\nexport type CancelMEOrderParams = {\n signer: Signer | JsonRpcSigner;\n accountId: number;\n marketId: number;\n symbol: string;\n orderId?: string;\n clientOrderId?: string;\n /** Unix seconds; EIP-712 signature deadline. Defaults to now + 30s. */\n deadline?: number;\n /** Optional explicit nonce; otherwise per-signer monotonic µs. */\n nonce?: bigint;\n};\n\nexport type MassCancelMEOrdersParams = {\n signer: Signer | JsonRpcSigner;\n accountId: number;\n marketId?: number;\n symbol?: string;\n /** Unix seconds; EIP-712 signature deadline. Defaults to now + 30s. */\n deadline?: number;\n /** Optional explicit nonce; otherwise per-signer monotonic µs. */\n nonce?: bigint;\n};\n\nconst DEFAULT_DEADLINE_SECONDS = 30;\n\nconst isZeroClientOrderId = (clientOrderId: string | undefined): boolean =>\n clientOrderId !== undefined && /^0+$/.test(clientOrderId.trim());\n\nconst assertNonZeroClientOrderId = (\n clientOrderId: string | undefined,\n): void => {\n if (isZeroClientOrderId(clientOrderId)) {\n throw new Error('clientOrderId must be omitted rather than set to 0');\n }\n};\n\n// Spot unified market ids are offset by 1e10 (see CreateOrderParams.marketId).\n// Spot markets don't support reduceOnly, so reject it at the SDK boundary\n// rather than sign a request the backend will reject.\nconst SPOT_MARKET_ID_OFFSET = 10_000_000_000;\n\nexport const createOrder = async (\n params: CreateOrderParams,\n): Promise<CreateOrderResponse> => {\n assertNonZeroClientOrderId(params.clientOrderId);\n\n const reyaChainId = getReyaNetwork();\n const config = getSdkConfig();\n\n if (\n (params.orderType === OrderType.STOP_LOSS ||\n params.orderType === OrderType.TAKE_PROFIT) &&\n params.triggerPx === undefined\n ) {\n throw new Error(`triggerPx is required for ${params.orderType} orders`);\n }\n\n if (params.reduceOnly && params.marketId >= SPOT_MARKET_ID_OFFSET) {\n throw new Error('reduceOnly is not supported for spot markets');\n }\n\n const signerAddress = await params.signer.getAddress();\n const defaultDeadline =\n Math.floor(Date.now() / 1000) + DEFAULT_DEADLINE_SECONDS;\n const deadline = params.deadline ?? defaultDeadline;\n const expiresAfter = params.expiresAfter ?? 0;\n const nonce = params.nonce ?? nextNonce(signerAddress);\n\n // On-chain `OrderDetails.quantity` is signed int256 (E18): positive for buy,\n // negative for sell. The REST surface keeps `isBuy + qty` (unsigned) for\n // symmetry with the rest of the API; reconstruct the signed value here.\n //\n // Use `parseUnits(str, 18)` to match the off-chain verifier exactly\n // (signature-validation/index.ts). The previous `scale(18)(parseFloat(str))`\n // diverged for |x| < 1e-6 or >= 1e21 (parseFloat exponential form) → a\n // signature mismatch on extreme sizes.\n const quantity = params.isBuy\n ? parseUnits(params.qty, 18)\n : -parseUnits(params.qty, 18);\n const limitPrice = parseUnits(params.limitPx, 18);\n const triggerPrice = params.triggerPx\n ? parseUnits(params.triggerPx, 18)\n : BigInt(0);\n\n const { serializedSignature } = await signOrder(params.signer, reyaChainId, {\n accountId: params.accountId,\n marketId: params.marketId,\n exchangeId: params.exchangeId,\n orderType: toOnChainOrderType(params.orderType),\n quantity,\n limitPrice,\n triggerPrice,\n timeInForce: toOnChainTimeInForce(params.timeInForce),\n clientOrderId: BigInt(params.clientOrderId ?? 0),\n reduceOnly: params.reduceOnly ?? false,\n postOnly: params.postOnly ?? false,\n expiresAfter: BigInt(expiresAfter),\n nonce,\n deadline,\n });\n\n const apiConfig = new Configuration({\n basePath: `${config.apiEndpoint}/v2`,\n });\n\n const orderEntryApi = new OrderEntryApi(apiConfig);\n\n const response = await orderEntryApi.createOrder({\n createOrderRequest: {\n exchangeId: params.exchangeId,\n symbol: params.symbol,\n accountId: params.accountId,\n isBuy: params.isBuy,\n limitPx: params.limitPx,\n qty: params.qty,\n orderType: params.orderType,\n timeInForce: params.timeInForce,\n ...(params.triggerPx !== undefined && { triggerPx: params.triggerPx }),\n ...(params.reduceOnly !== undefined && { reduceOnly: params.reduceOnly }),\n ...(params.postOnly !== undefined && { postOnly: params.postOnly }),\n ...(params.clientOrderId !== undefined && {\n clientOrderId: params.clientOrderId,\n }),\n signature: serializedSignature,\n nonce: nonce.toString(),\n signerWallet: signerAddress,\n deadline,\n ...(params.expiresAfter !== undefined &&\n params.expiresAfter !== 0 && { expiresAfter }),\n },\n });\n\n return response;\n};\n\nexport const cancelMEOrder = async (\n params: CancelMEOrderParams,\n): Promise<CancelOrderResponse> => {\n assertNonZeroClientOrderId(params.clientOrderId);\n\n const reyaChainId = getReyaNetwork();\n const config = getSdkConfig();\n\n // Validation: at least one of orderId or clientOrderId must be provided.\n // Without this check the SDK would sign for `cancel(orderId=0, clOrdId=0)`\n // and the API would either reject with a cryptic signature-mismatch error\n // or — worse — accept and look up a sentinel \"order zero\" that doesn't\n // exist. Better to surface the misuse at the SDK boundary. (PRO-81 C.2.26)\n // Treat '0' as \"not provided\" for both ids — '0' is the engine's\n // not-provided sentinel, so a caller passing clientOrderId:'0' (or\n // orderId:'0') must NOT slip past this guard and sign the sentinel\n // cancel(0,0) it is meant to block. (PRO-81 C.2.26)\n const orderIdProvided = isProvidedNonZeroId(params.orderId);\n const clientOrderIdProvided = isProvidedNonZeroId(params.clientOrderId);\n if (!orderIdProvided && !clientOrderIdProvided) {\n throw new Error(\n 'cancelMEOrder requires either `orderId` or `clientOrderId`',\n );\n }\n\n // When orderId is set, it is the canonical handle — drop clientOrderId\n // from both the signature and the request body. Forwarding both creates\n // ambiguity in server logging and would let a malicious / buggy caller\n // sign one order id while requesting cancellation by a different\n // (client-supplied) id. (PRO-81 C.2.26)\n const signedOrderId = orderIdProvided ? BigInt(params.orderId!) : BigInt(0);\n const signedClOrdId =\n !orderIdProvided && clientOrderIdProvided\n ? BigInt(params.clientOrderId!)\n : BigInt(0);\n\n const signerAddress = await params.signer.getAddress();\n const defaultDeadline =\n Math.floor(Date.now() / 1000) + DEFAULT_DEADLINE_SECONDS;\n const deadline = params.deadline ?? defaultDeadline;\n const nonce = params.nonce ?? nextNonce(signerAddress);\n\n const signature = await signMEOrderCancel(\n params.signer,\n reyaChainId,\n params.accountId,\n params.marketId,\n signedOrderId,\n signedClOrdId,\n nonce,\n deadline,\n );\n\n const apiConfig = new Configuration({\n basePath: `${config.apiEndpoint}/v2`,\n });\n\n const orderEntryApi = new OrderEntryApi(apiConfig);\n\n const response = await orderEntryApi.cancelOrder({\n cancelOrderRequest: {\n accountId: params.accountId,\n symbol: params.symbol,\n orderId: orderIdProvided ? params.orderId!.trim() : undefined,\n // See validation block above: clientOrderId is suppressed in the body\n // whenever orderId is the canonical handle.\n clientOrderId: orderIdProvided ? undefined : params.clientOrderId?.trim(),\n signature: signature,\n nonce: nonce.toString(),\n deadline,\n },\n });\n\n return response;\n};\n\nexport const massCancelMEOrders = async (\n params: MassCancelMEOrdersParams,\n): Promise<MassCancelResponse> => {\n const reyaChainId = getReyaNetwork();\n const config = getSdkConfig();\n\n // Validation: symbol and marketId must be provided together or not at all.\n // The API resolves a symbol → marketId server-side; the signature locks\n // marketId at sign time. If only one is provided we'd ship a body whose\n // server-derived marketId doesn't match the signed marketId (=> opaque\n // signature-validation failure), or — worse — a body that silently\n // cancels the wrong market. (PRO-81 C.2.26)\n const hasSymbol = params.symbol !== undefined;\n const hasMarketId = params.marketId !== undefined;\n if (hasSymbol !== hasMarketId) {\n throw new Error(\n 'massCancelMEOrders requires both `symbol` and `marketId` together, or neither (to mass-cancel across all markets)',\n );\n }\n\n const signerAddress = await params.signer.getAddress();\n const defaultDeadline =\n Math.floor(Date.now() / 1000) + DEFAULT_DEADLINE_SECONDS;\n const deadline = params.deadline ?? defaultDeadline;\n const nonce = params.nonce ?? nextNonce(signerAddress);\n\n const signature = await signMEMassCancel(\n params.signer,\n reyaChainId,\n params.accountId,\n params.marketId ?? 0,\n nonce,\n deadline,\n );\n\n const apiConfig = new Configuration({\n basePath: `${config.apiEndpoint}/v2`,\n });\n\n const orderEntryApi = new OrderEntryApi(apiConfig);\n\n const response = await orderEntryApi.cancelAll({\n massCancelRequest: {\n accountId: params.accountId,\n symbol: params.symbol,\n signature: signature,\n nonce: nonce.toString(),\n deadline,\n },\n });\n\n return response;\n};\n\n// Convenience wrapper: LIMIT order with IOC timeInForce. UI teams may call\n// createOrder directly with `timeInForce: TimeInForce.IOC` instead.\nexport const createIOCOrder = async (\n params: Omit<CreateOrderParams, 'timeInForce'>,\n): Promise<CreateOrderResponse> => {\n return createOrder({\n ...params,\n timeInForce: TimeInForce.IOC,\n });\n};\n\nexport type ClosePositionParams = {\n signer: Signer | JsonRpcSigner;\n accountId: number;\n exchangeId: number;\n marketId: number;\n /** Closing direction — opposite of the current position side. */\n isBuy: boolean;\n /** Slippage gate. */\n limitPx: string;\n /** Position size to close. */\n qty: string;\n symbol: string;\n clientOrderId?: string;\n /** Unix seconds; EIP-712 signature deadline. Defaults to now + 30s. */\n deadline?: number;\n /** Optional explicit nonce override; otherwise generated per-signer. */\n nonce?: bigint;\n};\n\n// Convenience wrapper: close a perp position by submitting a reduce-only LIMIT\n// IOC. The ME will bust fills that overflow the position at the clearing layer.\nexport const closePosition = async (\n params: ClosePositionParams,\n): Promise<CreateOrderResponse> => {\n return createOrder({\n signer: params.signer,\n accountId: params.accountId,\n exchangeId: params.exchangeId,\n marketId: params.marketId,\n isBuy: params.isBuy,\n limitPx: params.limitPx,\n qty: params.qty,\n symbol: params.symbol,\n orderType: OrderType.LIMIT,\n timeInForce: TimeInForce.IOC,\n reduceOnly: true,\n clientOrderId: params.clientOrderId,\n deadline: params.deadline,\n nonce: params.nonce,\n });\n};\n\nexport type CancelAllAfterParams = {\n signer: Signer | JsonRpcSigner;\n accountId: number;\n /**\n * Countdown duration in milliseconds. `0` disarms; any non-zero value must\n * be within [5000, 60000] and arms a fresh countdown of that duration,\n * replacing any previously armed one (re-arming = the refresh/heartbeat).\n * Recommended pattern: arm with 30000 and refresh every ~10-15s.\n */\n timeoutMs: number;\n deadline?: number;\n /**\n * Optional explicit nonce; otherwise a per-signer monotonic µs value. Must be\n * strictly greater than the signer's last accepted nonce on the backend. Note\n * the backend CONSUMES the nonce even when the request later fails (see\n * `cancelAllAfter` below) — an explicit-nonce caller must advance it before\n * retrying; the default `nextNonce` does so automatically.\n */\n nonce?: bigint;\n};\n\nconst CANCEL_ALL_AFTER_TIMEOUT_MIN_MS = 5000;\nconst CANCEL_ALL_AFTER_TIMEOUT_MAX_MS = 60000;\n\n/**\n * Arm, refresh, or disarm the account-scoped cancel-on-disconnect\n * dead-man's-switch. The countdown lives in the matching engine; when it\n * elapses, all of the account's open orders (all markets) are mass-cancelled.\n *\n * Nonce is consumed even on failure: the backend commits the signed nonce\n * atomically when it validates the request, BEFORE forwarding to the matching\n * engine. A failed forward (matching engine unavailable / transport error /\n * ME-side rejection) still burns the nonce — it is not rolled back. On retry\n * you MUST use a strictly higher nonce, or the backend rejects it as\n * `INVALID_NONCE_ERROR`. When `nonce` is omitted this is automatic: the\n * per-signer monotonic `nextNonce` always returns a value greater than the\n * last one it issued, so a plain retry self-recovers. Only callers passing an\n * explicit `nonce` need to advance it themselves before retrying.\n */\nexport const cancelAllAfter = async (\n params: CancelAllAfterParams,\n): Promise<CancelAllAfterResponse> => {\n const reyaChainId = getReyaNetwork();\n const config = getSdkConfig();\n\n // Fail fast on an out-of-range timeout before burning a nonce on a request\n // the server will reject with INPUT_VALIDATION_ERROR anyway.\n if (\n !Number.isInteger(params.timeoutMs) ||\n params.timeoutMs < 0 ||\n (params.timeoutMs !== 0 &&\n (params.timeoutMs < CANCEL_ALL_AFTER_TIMEOUT_MIN_MS ||\n params.timeoutMs > CANCEL_ALL_AFTER_TIMEOUT_MAX_MS))\n ) {\n throw new Error(\n `cancelAllAfter timeoutMs must be 0 (disarm) or between ${CANCEL_ALL_AFTER_TIMEOUT_MIN_MS} and ${CANCEL_ALL_AFTER_TIMEOUT_MAX_MS} milliseconds`,\n );\n }\n\n const signerAddress = await params.signer.getAddress();\n const defaultDeadline =\n Math.floor(Date.now() / 1000) + DEFAULT_DEADLINE_SECONDS;\n const deadline = params.deadline ?? defaultDeadline;\n const nonce = params.nonce ?? nextNonce(signerAddress);\n\n const signature = await signMECancelAllAfter(\n params.signer,\n reyaChainId,\n params.accountId,\n params.timeoutMs,\n nonce,\n deadline,\n );\n\n const apiConfig = new Configuration({\n basePath: `${config.apiEndpoint}/v2`,\n });\n\n const orderEntryApi = new OrderEntryApi(apiConfig);\n\n const response = await orderEntryApi.cancelAllAfter({\n cancelAllAfterRequest: {\n accountId: params.accountId,\n timeoutMs: params.timeoutMs,\n signature: signature,\n nonce: nonce.toString(),\n signerWallet: signerAddress,\n deadline,\n },\n });\n\n return response;\n};\n\nexport type ModifyMEOrderParams = {\n signer: Signer | JsonRpcSigner;\n accountId: number;\n exchangeId: number;\n /** Unified market id: core_id for perp, core_id + 1e10 for spot. */\n marketId: number;\n symbol: string;\n /** Targeting: provide `orderId`, or a non-zero `clientOrderId`; both may be provided. */\n orderId?: string;\n clientOrderId?: string;\n /**\n * Full post-modify order state. The SDK does not fetch the resting order —\n * the caller supplies every field, and the EIP-712 signature commits to\n * all of them. Modifiable fields are limitPx, qty, postOnly, expiresAfter,\n * and triggerPx. There is no omitted-means-inherited shorthand, so unchanged\n * values must be restated explicitly; LIMIT orders omit triggerPx and sign\n * triggerPrice = 0. Non-modifiable fields (isBuy, orderType, timeInForce,\n * reduceOnly) must match the resting order's values.\n */\n isBuy: boolean;\n limitPx: string;\n /** TOTAL order quantity (not remaining); must exceed the order's cumQty. */\n qty: string;\n orderType: OrderType;\n timeInForce: TimeInForce;\n triggerPx?: string;\n reduceOnly?: boolean;\n /** Post-modify maker-only flag. Required — restate the resting order's value to keep it. */\n postOnly: boolean;\n /** Unix seconds. Post-modify on-chain order lifetime; omit for no-expiry orders. */\n expiresAfter?: number;\n /**\n * Resting order's clientOrderId, signed into OrderDetails.clientOrderId.\n * If orderId is absent this is also the lookup target and must be non-zero.\n * If orderId is present, orderId targets and clientOrderId only restates the\n * immutable; omit it when the resting order has no client id.\n */\n /** Unix seconds; EIP-712 signature deadline. Defaults to now + 30s. */\n deadline?: number;\n /** Optional explicit nonce; otherwise per-signer monotonic µs. */\n nonce?: bigint;\n};\n\n/**\n * Modify a resting order in place. The order keeps its orderId and\n * clientOrderId; queue priority is preserved only for a qty decrease at an\n * unchanged limitPx. The params carry the COMPLETE post-modify state; a request\n * restating the resting order's exact current state is rejected with\n * EMPTY_MODIFY_ERROR.\n */\nexport const modifyMEOrder = async (\n params: ModifyMEOrderParams,\n): Promise<ModifyOrderResponse> => {\n assertNonZeroClientOrderId(params.clientOrderId);\n\n const reyaChainId = getReyaNetwork();\n const config = getSdkConfig();\n\n // Validate targeting before signing so misuse doesn't burn a nonce. `orderId`\n // wins when both are present; `clientOrderId` still rides along as the\n // restated signed immutable.\n const hasOrderId = isProvidedNonZeroId(params.orderId);\n const hasClientOrderIdTarget = isProvidedNonZeroId(params.clientOrderId);\n if (!hasOrderId && !hasClientOrderIdTarget) {\n throw new Error(\n 'modifyMEOrder requires `orderId` or a non-zero `clientOrderId`',\n );\n }\n\n // triggerPx is required for trigger orders — without it we would silently\n // sign triggerPrice=0. Fail at the SDK boundary (mirrors the cancel/mass-\n // cancel SDK-boundary validation) instead of signing a 0-trigger order.\n if (\n (params.orderType === OrderType.STOP_LOSS ||\n params.orderType === OrderType.TAKE_PROFIT) &&\n params.triggerPx === undefined\n ) {\n throw new Error(`triggerPx is required for ${params.orderType} orders`);\n }\n\n if (params.reduceOnly && params.marketId >= SPOT_MARKET_ID_OFFSET) {\n throw new Error('reduceOnly is not supported for spot markets');\n }\n\n const signerAddress = await params.signer.getAddress();\n const defaultDeadline =\n Math.floor(Date.now() / 1000) + DEFAULT_DEADLINE_SECONDS;\n const deadline = params.deadline ?? defaultDeadline;\n const nonce = params.nonce ?? nextNonce(signerAddress);\n\n // Sign over the exact integers the off-chain verifier reconstructs with\n // `parseUnits(str, 18)` (signature-validation/index.ts). The previous\n // `scale(18)(parseFloat(str))` diverged for |x| < 1e-6 or >= 1e21\n // (parseFloat renders those in exponential form, which `scale` mishandles)\n // → a signature mismatch on extreme sizes. `parseUnits` is exact.\n const quantity = params.isBuy\n ? parseUnits(params.qty, 18)\n : -parseUnits(params.qty, 18);\n const limitPrice = parseUnits(params.limitPx, 18);\n const triggerPrice = params.triggerPx\n ? parseUnits(params.triggerPx, 18)\n : BigInt(0);\n\n const { serializedSignature } = await signOrder(params.signer, reyaChainId, {\n accountId: params.accountId,\n marketId: params.marketId,\n exchangeId: params.exchangeId,\n orderType: toOnChainOrderType(params.orderType),\n quantity,\n limitPrice,\n triggerPrice,\n timeInForce: toOnChainTimeInForce(params.timeInForce),\n clientOrderId: BigInt(params.clientOrderId ?? '0'),\n reduceOnly: params.reduceOnly ?? false,\n postOnly: params.postOnly,\n expiresAfter: BigInt(params.expiresAfter ?? 0),\n nonce,\n deadline,\n });\n\n const apiConfig = new Configuration({\n basePath: `${config.apiEndpoint}/v2`,\n });\n\n const orderEntryApi = new OrderEntryApi(apiConfig);\n\n // Full restate: the body must carry the COMPLETE signed OrderDetails so it\n // reproduces the signed digest exactly (the off-chain verifier\n // `isModifyOrderSignatureValid` reconstructs from these fields, defaulting\n // omitted ones — e.g. timeInForce -> 'GTC', reduceOnly -> false — which would\n // mis-verify a GTT/reduce-only order). The immutables are restated at the\n // resting order's values; the ME rejects a mismatch with MODIFY_IMMUTABLE_MISMATCH.\n const response = await orderEntryApi.modifyOrder({\n modifyOrderRequest: {\n ...(hasOrderId ? { orderId: params.orderId!.trim() } : {}),\n ...(hasClientOrderIdTarget\n ? { clientOrderId: params.clientOrderId!.trim() }\n : {}),\n symbol: params.symbol,\n accountId: params.accountId,\n exchangeId: params.exchangeId,\n isBuy: params.isBuy,\n orderType: params.orderType,\n timeInForce: params.timeInForce,\n ...(params.triggerPx !== undefined && { triggerPx: params.triggerPx }),\n // reduceOnly is a required immutable on ModifyOrderRequest; default to\n // false to match what was signed above (`params.reduceOnly ?? false`).\n reduceOnly: params.reduceOnly ?? false,\n limitPx: params.limitPx,\n qty: params.qty,\n postOnly: params.postOnly,\n ...(params.expiresAfter !== undefined &&\n params.expiresAfter !== 0 && { expiresAfter: params.expiresAfter }),\n signature: serializedSignature,\n nonce: nonce.toString(),\n signerWallet: signerAddress,\n deadline,\n },\n });\n\n return response;\n};\n"]}
@@ -1,5 +1,8 @@
1
1
  import { Signer, JsonRpcSigner } from 'ethers';
2
2
  import { CreateOrderResponse, OrderType, TimeInForce, CancelOrderResponse, MassCancelResponse, CancelAllAfterResponse, ModifyOrderResponse } from '@reyaxyz/api-v2-sdk';
3
+ import { OrderType as OnChainOrderType } from '@reyaxyz/common';
4
+ export declare const toOnChainOrderType: (orderType: OrderType) => OnChainOrderType;
5
+ export declare const toOnChainTimeInForce: (timeInForce: TimeInForce) => number;
3
6
  export type CreateOrderParams = {
4
7
  signer: Signer | JsonRpcSigner;
5
8
  accountId: number;
@@ -1 +1 @@
1
- {"version":3,"file":"orderV2.d.ts","sourceRoot":"/","sources":["services/orders/orderV2.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,aAAa,EAAc,MAAM,QAAQ,CAAC;AAC3D,OAAO,EAGL,mBAAmB,EACnB,SAAS,EACT,WAAW,EACX,mBAAmB,EACnB,kBAAkB,EAClB,sBAAsB,EACtB,mBAAmB,EACpB,MAAM,qBAAqB,CAAC;AAoD7B,MAAM,MAAM,iBAAiB,GAAG;IAC9B,MAAM,EAAE,MAAM,GAAG,aAAa,CAAC;IAC/B,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,oEAAoE;IACpE,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,OAAO,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,SAAS,CAAC;IACrB,WAAW,EAAE,WAAW,CAAC;IACzB,4DAA4D;IAC5D,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,6DAA6D;IAC7D,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;;;OAGG;IACH,QAAQ,CAAC,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AAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,oEAAoE;IACpE,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,yFAAyF;IACzF,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;;;;;;;OAQG;IACH,KAAK,EAAE,OAAO,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,4EAA4E;IAC5E,GAAG,EAAE,MAAM,CAAC;IACZ,SAAS,EAAE,SAAS,CAAC;IACrB,WAAW,EAAE,WAAW,CAAC;IACzB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,4FAA4F;IAC5F,QAAQ,EAAE,OAAO,CAAC;IAClB,oFAAoF;IACpF,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;;;OAKG;IACH,uEAAuE;IACvE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,kEAAkE;IAClE,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,aAAa,WAChB,mBAAmB,KAC1B,QAAQ,mBAAmB,CA6G7B,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reyaxyz/sdk",
3
- "version": "0.146.5-perpob.89+8cd52a28c",
3
+ "version": "0.146.5-perpob.95+51d1c9d66",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "registry": "https://registry.npmjs.org"
@@ -31,12 +31,12 @@
31
31
  "test:cancel-spot-order": "npx ts-node scripts/test-cancel-spot-order.ts"
32
32
  },
33
33
  "dependencies": {
34
- "@reyaxyz/api-v2-sdk": "0.303.1-perpob.89+8cd52a28c",
35
- "@reyaxyz/common": "0.344.1-perpob.89+8cd52a28c",
34
+ "@reyaxyz/api-v2-sdk": "0.303.1-perpob.95+51d1c9d66",
35
+ "@reyaxyz/common": "0.344.1-perpob.95+51d1c9d66",
36
36
  "axios": "1.6.2",
37
37
  "bignumber.js": "9.1.2",
38
38
  "ethers": "6.9.0"
39
39
  },
40
40
  "packageManager": "pnpm@8.3.1",
41
- "gitHead": "8cd52a28cb75ac8d3f58a2a658f5821e21db65a0"
41
+ "gitHead": "51d1c9d668c68f0391ed33f957576bc4cc2dbe59"
42
42
  }
@@ -33,7 +33,7 @@ const isProvidedNonZeroId = (value: string | undefined): value is string => {
33
33
  // Maps the REST-surface `OrderType` (string: 'LIMIT' / 'STOP_LOSS' / 'TAKE_PROFIT',
34
34
  // from @reyaxyz/api-v2-sdk) to the on-chain numeric enum signed into
35
35
  // `OrderDetails.orderType` (0 / 1 / 2, from @reyaxyz/common).
36
- const toOnChainOrderType = (orderType: OrderType): OnChainOrderType => {
36
+ export const toOnChainOrderType = (orderType: OrderType): OnChainOrderType => {
37
37
  switch (orderType) {
38
38
  case 'LIMIT':
39
39
  return OnChainOrderType.Limit;
@@ -50,7 +50,7 @@ const toOnChainOrderType = (orderType: OrderType): OnChainOrderType => {
50
50
  // `OrderDetails.timeInForce`, matching the off-chain verifier's
51
51
  // REST_TIME_IN_FORCE_TO_NUMERIC (common-backend signature-validation):
52
52
  // GTC=0, IOC=1, GTT=2.
53
- const toOnChainTimeInForce = (timeInForce: TimeInForce): number => {
53
+ export const toOnChainTimeInForce = (timeInForce: TimeInForce): number => {
54
54
  switch (timeInForce) {
55
55
  case 'GTC':
56
56
  return 0;
@@ -58,6 +58,8 @@ const toOnChainTimeInForce = (timeInForce: TimeInForce): number => {
58
58
  return 1;
59
59
  case 'GTT':
60
60
  return 2;
61
+ default:
62
+ throw new Error(`Unsupported timeInForce: ${timeInForce}`);
61
63
  }
62
64
  };
63
65