@reyaxyz/sdk 0.151.4 → 0.152.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/README.md +1 -1
  2. package/dist/services/orders/index.js +1 -1
  3. package/dist/services/orders/index.js.map +1 -1
  4. package/dist/services/orders/nonce.js +37 -0
  5. package/dist/services/orders/nonce.js.map +1 -0
  6. package/dist/services/orders/orderV2.js +416 -89
  7. package/dist/services/orders/orderV2.js.map +1 -1
  8. package/dist/services/orders/triggerSettlementHeadroom.js +51 -0
  9. package/dist/services/orders/triggerSettlementHeadroom.js.map +1 -0
  10. package/dist/services/orders/types.js.map +1 -1
  11. package/dist/types/services/orders/index.d.ts +1 -1
  12. package/dist/types/services/orders/index.d.ts.map +1 -1
  13. package/dist/types/services/orders/nonce.d.ts +2 -0
  14. package/dist/types/services/orders/nonce.d.ts.map +1 -0
  15. package/dist/types/services/orders/orderV2.d.ts +194 -14
  16. package/dist/types/services/orders/orderV2.d.ts.map +1 -1
  17. package/dist/types/services/orders/triggerSettlementHeadroom.d.ts +33 -0
  18. package/dist/types/services/orders/triggerSettlementHeadroom.d.ts.map +1 -0
  19. package/dist/types/services/orders/types.d.ts +1 -11
  20. package/dist/types/services/orders/types.d.ts.map +1 -1
  21. package/package.json +8 -7
  22. package/src/services/orders/index.ts +1 -1
  23. package/src/services/orders/nonce.ts +34 -0
  24. package/src/services/orders/orderV2.ts +731 -122
  25. package/src/services/orders/triggerSettlementHeadroom.ts +56 -0
  26. package/src/services/orders/types.ts +0 -15
  27. package/dist/services/orders/order.js +0 -231
  28. package/dist/services/orders/order.js.map +0 -1
  29. package/dist/types/services/orders/order.d.ts +0 -4
  30. package/dist/types/services/orders/order.d.ts.map +0 -1
  31. package/src/services/orders/order.ts +0 -214
@@ -1 +1 @@
1
- {"version":3,"file":"orderV2.js","sourceRoot":"/","sources":["services/orders/orderV2.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;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,CAAC,KAAK,CAAC,CAAC;gBAEI,qBAAM,IAAA,uBAAc,EAClD,MAAM,CAAC,MAAM,EACb,WAAW,EACX,MAAM,CAAC,SAAS,EAChB,MAAA,MAAM,CAAC,QAAQ,mCAAI,CAAC,EACpB,KAAK,EACL,YAAY,CACb,EAAA;;gBAPO,mBAAmB,GAAK,CAAA,SAO/B,CAAA,oBAP0B;gBASrB,SAAS,GAAG,IAAI,0BAAa,CAAC;oBAClC,QAAQ,EAAE,UAAG,MAAM,CAAC,WAAW,QAAK;iBACrC,CAAC,CAAC;gBAEG,aAAa,GAAG,IAAI,0BAAa,CAAC,SAAS,CAAC,CAAC;gBAElC,qBAAM,aAAa,CAAC,SAAS,CAAC;wBAC7C,iBAAiB,EAAE;4BACjB,MAAM,EAAE,MAAM,CAAC,MAAM;4BACrB,SAAS,EAAE,MAAM,CAAC,SAAS;4BAC3B,SAAS,EAAE,mBAAmB;4BAC9B,KAAK,EAAE,KAAK,CAAC,QAAQ,EAAE;4BACvB,YAAY,cAAA;yBACb;qBACF,CAAC,EAAA;;gBARI,QAAQ,GAAG,SAQf;gBAEF,sBAAO,QAAQ,EAAC;;;KACjB,CAAC;AA9CW,QAAA,oBAAoB,wBA8C/B","sourcesContent":["import { Signer, JsonRpcSigner, AbiCoder } from 'ethers';\nimport {\n OrderEntryApi,\n Configuration,\n CancelOrderResponse,\n CreateOrderResponse,\n MassCancelResponse,\n OrderType,\n TimeInForce,\n} from '@reyaxyz/api-v2-sdk';\nimport {\n signOrdersGatewayOrder,\n signOrderCancel,\n signMassCancel,\n OrdersGatewayOrderType,\n scale,\n CONDITIONAL_ORDER_SIG_DEADLINE,\n} from '@reyaxyz/common';\nimport { getReyaNetwork } from '../../utils/network';\nimport { getSdkConfig } from '../../config';\n\nconst DEFAULT_CANCEL_DEADLINE_SECONDS = 60;\n\nexport { TimeInForce };\n\nexport type CreateSpotOrderParams = {\n signer: Signer | JsonRpcSigner;\n accountId: number;\n exchangeId: number;\n marketId: number;\n isBuy: boolean;\n limitPx: string;\n qty: string;\n symbol: string;\n timeInForce: TimeInForce;\n clientOrderId?: number;\n};\n\nconst encodeSpotLimitOrderInputs = (\n isBuy: boolean,\n limitPx: string,\n qty: string,\n): string => {\n const baseDelta = isBuy\n ? scale(18)(parseFloat(qty))\n : -scale(18)(parseFloat(qty));\n const price = scale(18)(parseFloat(limitPx));\n return AbiCoder.defaultAbiCoder().encode(\n ['int256', 'uint256'],\n [baseDelta, price],\n );\n};\n\nexport const createSpotOrder = async (\n params: CreateSpotOrderParams,\n): Promise<CreateOrderResponse> => {\n const reyaChainId = getReyaNetwork();\n const config = getSdkConfig();\n\n const inputs = encodeSpotLimitOrderInputs(\n params.isBuy,\n params.limitPx,\n params.qty,\n );\n\n const creationTimestampMs = Date.now();\n // IOC orders are capped at 10 minutes by the API; GTC orders use the\n // conditional-order sentinel deadline so they rest until cancelled.\n const deadline = (() => {\n switch (params.timeInForce) {\n case TimeInForce.IOC:\n return Math.floor(creationTimestampMs / 1000) + 30;\n case TimeInForce.GTC:\n return CONDITIONAL_ORDER_SIG_DEADLINE;\n default:\n throw new Error(`Unsupported timeInForce: ${params.timeInForce}`);\n }\n })();\n\n // For spot orders, nonce is just the timestamp (uint64)\n const spotNonce = BigInt(creationTimestampMs);\n\n const { serializedSignature, nonce } = await signOrdersGatewayOrder(\n params.signer,\n reyaChainId,\n params.accountId,\n params.marketId,\n params.exchangeId,\n [],\n OrdersGatewayOrderType.LIMIT_ORDER_SPOT,\n inputs,\n deadline,\n creationTimestampMs,\n spotNonce, // custom nonce for spot orders\n );\n\n const signerAddress = await params.signer.getAddress();\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: OrderType.LIMIT,\n timeInForce: params.timeInForce,\n clientOrderId: params.clientOrderId,\n signature: serializedSignature,\n nonce: nonce.toString(),\n signerWallet: signerAddress,\n expiresAfter: deadline,\n },\n });\n\n return response;\n};\n\nexport type CancelSpotOrderParams = {\n signer: Signer | JsonRpcSigner;\n accountId: number;\n marketId: number;\n symbol: string;\n orderId?: string;\n clientOrderId?: number;\n expiresAfterSeconds?: number;\n};\n\nexport const cancelSpotOrder = async (\n params: CancelSpotOrderParams,\n): Promise<CancelOrderResponse> => {\n if (!params.orderId && params.clientOrderId === undefined) {\n throw new Error('Either orderId or clientOrderId must be provided');\n }\n\n const reyaChainId = getReyaNetwork();\n const config = getSdkConfig();\n\n const nowMs = Date.now();\n const expiresAfter =\n Math.floor(nowMs / 1000) +\n (params.expiresAfterSeconds ?? DEFAULT_CANCEL_DEADLINE_SECONDS);\n const nonce = BigInt(nowMs);\n\n const useOrderId = !!params.orderId;\n const signedOrderId = useOrderId ? BigInt(params.orderId!) : BigInt(0);\n const signedClOrdId = useOrderId ? BigInt(0) : BigInt(params.clientOrderId!);\n\n const { serializedSignature } = await signOrderCancel(\n params.signer,\n reyaChainId,\n params.accountId,\n params.marketId,\n signedOrderId,\n signedClOrdId,\n nonce,\n expiresAfter,\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 symbol: params.symbol,\n accountId: params.accountId,\n orderId: useOrderId ? params.orderId : undefined,\n clientOrderId: useOrderId ? undefined : params.clientOrderId,\n signature: serializedSignature,\n nonce: nonce.toString(),\n expiresAfter,\n },\n });\n\n return response;\n};\n\nexport type MassCancelSpotOrdersParams = {\n signer: Signer | JsonRpcSigner;\n accountId: number;\n symbol?: string;\n marketId?: number;\n expiresAfterSeconds?: number;\n};\n\nexport const massCancelSpotOrders = async (\n params: MassCancelSpotOrdersParams,\n): Promise<MassCancelResponse> => {\n const hasSymbol = params.symbol !== undefined;\n const hasMarketId = params.marketId !== undefined;\n if (hasSymbol !== hasMarketId) {\n throw new Error(\n 'symbol and marketId must be provided together (or both omitted to cancel across all markets)',\n );\n }\n\n const reyaChainId = getReyaNetwork();\n const config = getSdkConfig();\n\n const nowMs = Date.now();\n const expiresAfter =\n Math.floor(nowMs / 1000) +\n (params.expiresAfterSeconds ?? DEFAULT_CANCEL_DEADLINE_SECONDS);\n const nonce = BigInt(nowMs);\n\n const { serializedSignature } = await signMassCancel(\n params.signer,\n reyaChainId,\n params.accountId,\n params.marketId ?? 0,\n nonce,\n expiresAfter,\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 symbol: params.symbol,\n accountId: params.accountId,\n signature: serializedSignature,\n nonce: nonce.toString(),\n expiresAfter,\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,kDAW6B;AAC7B,0CAOyB;AACzB,+CAAqD;AACrD,uCAA4C;AAC5C,iCAAoC;AACpC,yEAAuE;AAEvE,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,SA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AI,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;;gBA9BI,QAAQ,GAAG,SA8Bf;gBAEF,sBAAO,QAAQ,EAAC;;;KACjB,CAAC;AA9KW,QAAA,aAAa,iBA8KxB","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 ModifyOrderRequest,\n} from '@reyaxyz/api-v2-sdk';\nimport {\n signOrder,\n signMEOrderCancel,\n signMEMassCancel,\n signMECancelAllAfter,\n OrderType as OnChainOrderType,\n fullPositionStopQuantity,\n} from '@reyaxyz/common';\nimport { getReyaNetwork } from '../../utils/network';\nimport { getSdkConfig } from '../../config';\nimport { nextNonce } from './nonce';\nimport { assertSettlementHeadroom } from './triggerSettlementHeadroom';\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 /**\n * Order quantity. Type-conditional, mirroring the modify-trigger path:\n * - LIMIT: REQUIRED — signed as ±qty (positive buy, negative sell) and sent\n * on the wire.\n * - STOP_LOSS / TAKE_PROFIT: OMIT — the signed quantity is the ±int256.max\n * full-position sentinel (sign from `isBuy`; protect the whole position)\n * and qty is dropped from the wire payload. Passing a qty on a trigger\n * create throws (the backend rejects it).\n */\n qty?: string;\n symbol: string;\n orderType: OrderType;\n /**\n * REQUIRED for every order class — signed and sent on the wire. On a\n * STOP_LOSS / TAKE_PROFIT it chooses what the stop becomes when it fires:\n * IOC fills what the book offers and cancels the rest, GTC rests the\n * remainder until cancelled, GTT rests it until one settlement headroom\n * before `expiresAfter`.\n */\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 * Seconds of settlement headroom a GTT `expiresAfter` must outlast. Defaults\n * to the production value; set it only for a deployment running a different\n * one.\n */\n settlementHeadroomSeconds?: number;\n /**\n * Optional explicit nonce. Must be strictly greater than the signer's last\n * accepted nonce in the matching engine. Defaults to a per-signer monotonic\n * µ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 const isTrigger =\n params.orderType === OrderType.STOP_LOSS ||\n params.orderType === OrderType.TAKE_PROFIT;\n\n if (\n isTrigger &&\n (params.reduceOnly !== undefined || params.postOnly !== undefined)\n ) {\n throw new Error('reduceOnly and postOnly must be omitted for TP/SL orders');\n }\n\n if (isTrigger && params.triggerPx === undefined) {\n throw new Error(`triggerPx is required for ${params.orderType} orders`);\n }\n\n // qty is type-conditional (mirrors the modify-trigger path):\n // - STOP_LOSS / TAKE_PROFIT: qty MUST be omitted; the signed quantity is\n // the ±int256.max full-position sentinel (sign from `isBuy`) and qty is\n // dropped from the wire below. The backend rejects a trigger create that\n // carries qty.\n // - LIMIT: qty is REQUIRED and signed as ±qty.\n // Validated up front (before a nonce is minted), like the triggerPx guard.\n if (isTrigger && params.qty !== undefined) {\n throw new Error(\n `qty must be omitted for ${params.orderType} orders (the signed quantity is the full-position sentinel)`,\n );\n }\n if (!isTrigger && params.qty === undefined) {\n throw new Error('qty is required for a LIMIT order');\n }\n\n // Convert once while validation is still side-effect free. timeInForce is\n // required for every order class — on a trigger it chooses what the fired\n // child becomes, so there is no value the SDK could supply on the caller's\n // behalf. Runtime callers can bypass the TypeScript type; reject a missing or\n // unrecognised value before resolving the signer or advancing its nonce.\n const onChainTimeInForce = toOnChainTimeInForce(params.timeInForce);\n\n // Only GTT carries a lifetime, for triggers as for book orders. On a trigger\n // the one timestamp bounds the armed window AND is the fired child's on-chain\n // settlement deadline; GTC and IOC triggers have no lifetime of their own.\n const hasExpiry =\n params.expiresAfter !== undefined && params.expiresAfter !== 0;\n if (params.timeInForce === TimeInForce.GTT && !hasExpiry) {\n throw new Error('expiresAfter is required for GTT orders');\n }\n if (params.timeInForce !== TimeInForce.GTT && hasExpiry) {\n throw new Error(\n 'expiresAfter must be omitted for IOC / GTC orders — only GTT carries a lifetime',\n );\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 // Venue admission rules the SDK can evaluate itself, checked while validation\n // is still side-effect free — a nonce burnt on an order the engine refuses\n // has to be resynced before the next one can be signed.\n if (hasExpiry) {\n assertSettlementHeadroom(\n params.expiresAfter!,\n params.settlementHeadroomSeconds,\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 expiresAfter = params.expiresAfter ?? 0;\n const nonce = params.nonce ?? nextNonce(signerAddress);\n\n // On-chain `OrderDetails.quantity` is signed int256 (E18 for real sizes): a\n // trigger signs the ±int256.max full-position sentinel — sign from `isBuy`\n // (−max sells out a long, +max buys back a short; reya-network #738 enforces\n // SL/TP <=> ±sentinel, and quantity 0 now reverts) — while a LIMIT signs ±qty\n // (positive buy, negative sell). The REST surface keeps `isBuy + qty`\n // (unsigned) for symmetry with the rest of the API; reconstruct the signed\n // 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 = isTrigger\n ? fullPositionStopQuantity(params.isBuy)\n : 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: onChainTimeInForce,\n clientOrderId: BigInt(params.clientOrderId ?? 0),\n reduceOnly: isTrigger ? false : params.reduceOnly ?? false,\n postOnly: isTrigger ? false : 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 is omitted on a trigger create (guaranteed undefined by the\n // isTrigger guard above); sent for a LIMIT create.\n ...(params.qty !== undefined && { 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 in the matching\n * engine. See `cancelAllAfter` below for retry semantics; the default\n * `nextNonce` advances 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 * The matching engine owns nonce replay protection. A request rejected by\n * local validation before it is forwarded does not consume its nonce. Once a\n * request is sent, a transport failure may be outcome-unknown, and a request\n * that reaches the matching engine may record its nonce in the WAL. Retry with\n * a strictly higher nonce after an ME response or transport uncertainty.\n * Reusing an explicit nonce is safe only after a definite local pre-forward\n * rejection. When `nonce` is omitted, `nextNonce` advances automatically.\n */\nexport const cancelAllAfter = async (\n params: CancelAllAfterParams,\n): Promise<CancelAllAfterResponse> => {\n const reyaChainId = getReyaNetwork();\n const config = getSdkConfig();\n\n // Fail fast before signing or sending a request the server will reject with\n // 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\ntype ModifyMEOrderCommonParams = {\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 /**\n * TOTAL order quantity (not remaining). Type-conditional, mirroring the\n * create-trigger path:\n * - LIMIT: REQUIRED — must exceed the order's cumQty; signed as the total\n * post-modify quantity.\n * - STOP_LOSS / TAKE_PROFIT: OMIT — the signed quantity restates the\n * ±int256.max full-position sentinel (sign from `isBuy`; protect the whole\n * position) and qty is dropped from the wire payload. Passing a qty on a\n * trigger modify throws (the backend rejects it).\n */\n qty?: string;\n /** Immutable; restate the resting order's value. */\n timeInForce: TimeInForce;\n triggerPx?: string;\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 /**\n * Seconds of settlement headroom a GTT `expiresAfter` must outlast. Defaults\n * to the production value; set it only for a deployment running a different\n * one.\n */\n settlementHeadroomSeconds?: number;\n /** Optional explicit nonce; otherwise per-signer monotonic µs. */\n nonce?: bigint;\n};\n\n// Keep the helper's discriminant/flag rules tied to the generated wire types.\n// LIMIT reduceOnly retains the helper's false default; raw requests require it.\ntype LimitModifyMEOrderFields = Pick<\n Extract<ModifyOrderRequest, { orderType: 'LIMIT' }>,\n 'orderType' | 'postOnly'\n> & { reduceOnly?: boolean };\ntype TriggerModifyMEOrderFields = Pick<\n Extract<ModifyOrderRequest, { orderType: 'STOP_LOSS' | 'TAKE_PROFIT' }>,\n 'orderType' | 'postOnly' | 'reduceOnly'\n>;\n\nexport type ModifyMEOrderParams = ModifyMEOrderCommonParams &\n (LimitModifyMEOrderFields | TriggerModifyMEOrderFields);\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 const isTrigger =\n params.orderType === OrderType.STOP_LOSS ||\n params.orderType === OrderType.TAKE_PROFIT;\n\n if (\n isTrigger &&\n (params.reduceOnly !== undefined || params.postOnly !== undefined)\n ) {\n throw new Error('reduceOnly and postOnly must be omitted for TP/SL orders');\n }\n\n if (!isTrigger && typeof params.postOnly !== 'boolean') {\n throw new Error('postOnly is required for LIMIT modifications');\n }\n\n // Convert once while validation is still side-effect free. Runtime callers\n // can bypass the TypeScript enum; reject those values before resolving the\n // signer or advancing its nonce.\n const onChainTimeInForce = toOnChainTimeInForce(params.timeInForce);\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 (isTrigger && params.triggerPx === undefined) {\n throw new Error(`triggerPx is required for ${params.orderType} orders`);\n }\n\n // qty is type-conditional (mirrors the create-trigger path):\n // - STOP_LOSS / TAKE_PROFIT: qty MUST be omitted; the signed quantity is\n // the ±int256.max full-position sentinel (sign from `isBuy`) and qty is\n // dropped from the wire below. The backend rejects a trigger modify that\n // carries qty.\n // - LIMIT: qty is REQUIRED and signed as the total post-modify quantity.\n // Validated up front (before a nonce is minted), like the triggerPx guard.\n if (isTrigger && params.qty !== undefined) {\n throw new Error(\n `qty must be omitted for ${params.orderType} orders (the signed quantity is the full-position sentinel)`,\n );\n }\n if (!isTrigger && params.qty === undefined) {\n throw new Error('qty is required when modifying a LIMIT order');\n }\n\n // Only GTT carries a lifetime, for triggers as for book orders. The modify\n // restates that pair immutably, so an inconsistent one can only be refused by\n // the backend — catch it here, before a nonce is minted and burnt.\n const hasExpiry =\n params.expiresAfter !== undefined && params.expiresAfter !== 0;\n if (params.timeInForce === TimeInForce.GTT && !hasExpiry) {\n throw new Error('expiresAfter is required for GTT orders');\n }\n if (params.timeInForce !== TimeInForce.GTT && hasExpiry) {\n throw new Error(\n 'expiresAfter must be omitted for IOC / GTC orders — only GTT carries a lifetime',\n );\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 // Same venue admission rule as the create path: a restated GTT lifetime must\n // still outlast the settlement headroom.\n if (hasExpiry) {\n assertSettlementHeadroom(\n params.expiresAfter!,\n params.settlementHeadroomSeconds,\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 // Signed quantity: a trigger restates the ±int256.max full-position sentinel\n // (sign from `isBuy`; reya-network #738); a LIMIT signs ±qty. Sign over the\n // exact integers the off-chain verifier reconstructs\n // with `parseUnits(str, 18)` (signature-validation/index.ts). The previous\n // `scale(18)(parseFloat(str))` diverged for |x| < 1e-6 or >= 1e21 (parseFloat\n // renders those in exponential form, which `scale` mishandles) → a signature\n // mismatch on extreme sizes. `parseUnits` is exact.\n const quantity = isTrigger\n ? fullPositionStopQuantity(params.isBuy)\n : 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: onChainTimeInForce,\n clientOrderId: BigInt(params.clientOrderId ?? '0'),\n reduceOnly: isTrigger ? false : params.reduceOnly ?? false,\n postOnly: isTrigger ? false : 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 with\n // `timeInForce` required and never defaulted, so an omitted one cannot\n // verify at all. The immutables are restated at the resting order's values;\n // 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 ...(params.orderType === OrderType.LIMIT\n ? {\n orderType: params.orderType,\n reduceOnly: params.reduceOnly ?? false,\n postOnly: params.postOnly,\n }\n : { orderType: params.orderType }),\n timeInForce: params.timeInForce,\n ...(params.triggerPx !== undefined && { triggerPx: params.triggerPx }),\n limitPx: params.limitPx,\n // qty is omitted on a trigger modify (guaranteed undefined by the\n // isTrigger guard above); sent for a LIMIT modify.\n ...(params.qty !== undefined && { qty: params.qty }),\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"]}
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ /**
3
+ * Client-side mirror of the one trigger-admission rule a client can evaluate on
4
+ * its own: the settlement headroom a `GTT` lifetime must outlast.
5
+ *
6
+ * The per-market limit band is deliberately NOT mirrored here. It is an
7
+ * engine-side admission rule derived from matching-engine config, it is not
8
+ * published on the API, and a client cannot compute it — a `limitPx` outside it
9
+ * is refused at admission with `TRIGGER_LIMIT_OUTSIDE_BAND_ERROR`.
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.assertSettlementHeadroom = exports.DEFAULT_SETTLEMENT_HEADROOM_SECONDS = void 0;
13
+ /**
14
+ * Settlement headroom of a production deployment, in seconds. A `GTT` lifetime
15
+ * must be STRICTLY greater than `now + headroom`, or the engine refuses the
16
+ * order with `ORDER_EXPIRES_TOO_SOON_ERROR`. It is a venue parameter and is not
17
+ * published on the API; a deployment that runs a different one is handled by
18
+ * the per-call `settlementHeadroomSeconds` override.
19
+ */
20
+ exports.DEFAULT_SETTLEMENT_HEADROOM_SECONDS = 60;
21
+ /**
22
+ * Refuse a `GTT` lifetime that does not outlast the settlement headroom.
23
+ *
24
+ * Independent of the `expiresAfter > deadline` coupling: a caller that pins a
25
+ * short deadline satisfies that check while still signing a lifetime the engine
26
+ * refuses. On a trigger the same deadline covers both phases, so the headroom
27
+ * bites there too.
28
+ *
29
+ * `expiresAfter` must be a positive safe integer (Unix seconds) and
30
+ * `headroomSeconds` a finite non-negative number; both are checked here rather
31
+ * than at the later `BigInt(expiresAfter)` conversion, so a `NaN`, `Infinity`,
32
+ * fractional or negative value fails at the validation boundary instead of
33
+ * after the signer has been resolved and a nonce minted.
34
+ */
35
+ var assertSettlementHeadroom = function (expiresAfter, headroomSeconds, nowSeconds) {
36
+ if (headroomSeconds === void 0) { headroomSeconds = exports.DEFAULT_SETTLEMENT_HEADROOM_SECONDS; }
37
+ if (nowSeconds === void 0) { nowSeconds = Math.floor(Date.now() / 1000); }
38
+ if (!Number.isSafeInteger(expiresAfter) || expiresAfter <= 0) {
39
+ throw new Error("expiresAfter=".concat(expiresAfter, " must be a positive integer Unix timestamp in seconds"));
40
+ }
41
+ if (!Number.isFinite(headroomSeconds) || headroomSeconds < 0) {
42
+ throw new Error("settlementHeadroomSeconds=".concat(headroomSeconds, " must be a finite, non-negative number of seconds"));
43
+ }
44
+ var earliestAdmissible = nowSeconds + headroomSeconds;
45
+ if (expiresAfter <= earliestAdmissible) {
46
+ throw new Error("expiresAfter=".concat(expiresAfter, " does not outlast the ").concat(headroomSeconds, "s settlement headroom ") +
47
+ "(needs > ".concat(earliestAdmissible, "). Pass settlementHeadroomSeconds if the target deployment runs a different one."));
48
+ }
49
+ };
50
+ exports.assertSettlementHeadroom = assertSettlementHeadroom;
51
+ //# sourceMappingURL=triggerSettlementHeadroom.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"triggerSettlementHeadroom.js","sourceRoot":"/","sources":["services/orders/triggerSettlementHeadroom.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;;AAEH;;;;;;GAMG;AACU,QAAA,mCAAmC,GAAG,EAAE,CAAC;AAEtD;;;;;;;;;;;;;GAaG;AACI,IAAM,wBAAwB,GAAG,UACtC,YAAoB,EACpB,eAA6D,EAC7D,UAAkD;IADlD,gCAAA,EAAA,kBAA0B,2CAAmC;IAC7D,2BAAA,EAAA,aAAqB,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;IAElD,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,YAAY,CAAC,IAAI,YAAY,IAAI,CAAC,EAAE,CAAC;QAC7D,MAAM,IAAI,KAAK,CACb,uBAAgB,YAAY,0DAAuD,CACpF,CAAC;IACJ,CAAC;IACD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,eAAe,CAAC,IAAI,eAAe,GAAG,CAAC,EAAE,CAAC;QAC7D,MAAM,IAAI,KAAK,CACb,oCAA6B,eAAe,sDAAmD,CAChG,CAAC;IACJ,CAAC;IACD,IAAM,kBAAkB,GAAG,UAAU,GAAG,eAAe,CAAC;IACxD,IAAI,YAAY,IAAI,kBAAkB,EAAE,CAAC;QACvC,MAAM,IAAI,KAAK,CACb,uBAAgB,YAAY,mCAAyB,eAAe,2BAAwB;YAC1F,mBAAY,kBAAkB,qFAAkF,CACnH,CAAC;IACJ,CAAC;AACH,CAAC,CAAC;AAtBW,QAAA,wBAAwB,4BAsBnC","sourcesContent":["/**\n * Client-side mirror of the one trigger-admission rule a client can evaluate on\n * its own: the settlement headroom a `GTT` lifetime must outlast.\n *\n * The per-market limit band is deliberately NOT mirrored here. It is an\n * engine-side admission rule derived from matching-engine config, it is not\n * published on the API, and a client cannot compute it — a `limitPx` outside it\n * is refused at admission with `TRIGGER_LIMIT_OUTSIDE_BAND_ERROR`.\n */\n\n/**\n * Settlement headroom of a production deployment, in seconds. A `GTT` lifetime\n * must be STRICTLY greater than `now + headroom`, or the engine refuses the\n * order with `ORDER_EXPIRES_TOO_SOON_ERROR`. It is a venue parameter and is not\n * published on the API; a deployment that runs a different one is handled by\n * the per-call `settlementHeadroomSeconds` override.\n */\nexport const DEFAULT_SETTLEMENT_HEADROOM_SECONDS = 60;\n\n/**\n * Refuse a `GTT` lifetime that does not outlast the settlement headroom.\n *\n * Independent of the `expiresAfter > deadline` coupling: a caller that pins a\n * short deadline satisfies that check while still signing a lifetime the engine\n * refuses. On a trigger the same deadline covers both phases, so the headroom\n * bites there too.\n *\n * `expiresAfter` must be a positive safe integer (Unix seconds) and\n * `headroomSeconds` a finite non-negative number; both are checked here rather\n * than at the later `BigInt(expiresAfter)` conversion, so a `NaN`, `Infinity`,\n * fractional or negative value fails at the validation boundary instead of\n * after the signer has been resolved and a nonce minted.\n */\nexport const assertSettlementHeadroom = (\n expiresAfter: number,\n headroomSeconds: number = DEFAULT_SETTLEMENT_HEADROOM_SECONDS,\n nowSeconds: number = Math.floor(Date.now() / 1000),\n): void => {\n if (!Number.isSafeInteger(expiresAfter) || expiresAfter <= 0) {\n throw new Error(\n `expiresAfter=${expiresAfter} must be a positive integer Unix timestamp in seconds`,\n );\n }\n if (!Number.isFinite(headroomSeconds) || headroomSeconds < 0) {\n throw new Error(\n `settlementHeadroomSeconds=${headroomSeconds} must be a finite, non-negative number of seconds`,\n );\n }\n const earliestAdmissible = nowSeconds + headroomSeconds;\n if (expiresAfter <= earliestAdmissible) {\n throw new Error(\n `expiresAfter=${expiresAfter} does not outlast the ${headroomSeconds}s settlement headroom ` +\n `(needs > ${earliestAdmissible}). Pass settlementHeadroomSeconds if the target deployment runs a different one.`,\n );\n }\n};\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 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 minOrderSizeBase: MarketEntity['minOrderSizeBase'];\n baseSpacing: MarketEntity['baseSpacing'];\n};\n\nexport type MatchOrderParams = {\n signer: Signer | JsonRpcSigner;\n marginAccountId: number;\n amountInBase: number; // amount in base\n market: MarketParams;\n tradeSource?: 'reya' | 'rage' | 'other';\n};\n\nexport type CloseOrderParams = {\n signer: Signer | JsonRpcSigner;\n marginAccountId: number;\n market: MarketParams;\n} & (\n | {\n type: 'full';\n }\n | {\n type: 'partial';\n orderBase: PositionEntity['base'];\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: number;\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: number;\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: number;\n marketId: MarketEntity['id'];\n counterpartyAccountIds: MarketEntity['orderInfo']['counterpartyAccountIds'];\n exchangeId: MarketEntity['orderInfo']['exchangeId'];\n orderType:\n | OrdersGatewayOrderType.MARKET_ORDER\n | OrdersGatewayOrderType.REDUCE_ONLY_MARKET_ORDER\n | OrdersGatewayOrderType.FULL_CLOSE_ORDER;\n orderInputs: string;\n tradeSource?: 'reya' | 'rage' | 'other';\n};\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 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 minOrderSizeBase: MarketEntity['minOrderSizeBase'];\n baseSpacing: MarketEntity['baseSpacing'];\n};\n\nexport type MatchOrderParams = {\n signer: Signer | JsonRpcSigner;\n marginAccountId: number;\n amountInBase: number; // amount in base\n market: MarketParams;\n tradeSource?: 'reya' | 'rage' | 'other';\n};\n\nexport type CloseOrderParams = {\n signer: Signer | JsonRpcSigner;\n marginAccountId: number;\n market: MarketParams;\n} & (\n | {\n type: 'full';\n }\n | {\n type: 'partial';\n orderBase: PositionEntity['base'];\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: number;\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: number;\n xpEarned: number;\n executionPrice: number;\n base: number;\n};\n\nexport type MethodParametersAndEIP712Payload = MethodParameters &\n CoreCommandsEIP712SignatureAndPayload;\n"]}
@@ -1,4 +1,4 @@
1
1
  export * from './types';
2
- export * from './order';
3
2
  export * from './orderV2';
3
+ export * from './triggerSettlementHeadroom';
4
4
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"/","sources":["services/orders/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC;AACxB,cAAc,SAAS,CAAC;AACxB,cAAc,WAAW,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"/","sources":["services/orders/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC;AACxB,cAAc,WAAW,CAAC;AAC1B,cAAc,6BAA6B,CAAC"}
@@ -0,0 +1,2 @@
1
+ export declare const nextNonce: (walletAddress: string) => bigint;
2
+ //# sourceMappingURL=nonce.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nonce.d.ts","sourceRoot":"/","sources":["services/orders/nonce.ts"],"names":[],"mappings":"AA0BA,eAAO,MAAM,SAAS,kBAAmB,MAAM,KAAG,MAOjD,CAAC"}
@@ -1,35 +1,215 @@
1
1
  import { Signer, JsonRpcSigner } from 'ethers';
2
- import { CancelOrderResponse, CreateOrderResponse, MassCancelResponse, TimeInForce } from '@reyaxyz/api-v2-sdk';
3
- export { TimeInForce };
4
- export type CreateSpotOrderParams = {
2
+ import { CreateOrderResponse, OrderType, TimeInForce, CancelOrderResponse, MassCancelResponse, CancelAllAfterResponse, ModifyOrderResponse, ModifyOrderRequest } 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;
6
+ export type CreateOrderParams = {
5
7
  signer: Signer | JsonRpcSigner;
6
8
  accountId: number;
7
9
  exchangeId: number;
10
+ /** Unified market id: core_id for perp, core_id + 1e10 for spot. */
8
11
  marketId: number;
9
12
  isBuy: boolean;
10
13
  limitPx: string;
11
- qty: string;
14
+ /**
15
+ * Order quantity. Type-conditional, mirroring the modify-trigger path:
16
+ * - LIMIT: REQUIRED — signed as ±qty (positive buy, negative sell) and sent
17
+ * on the wire.
18
+ * - STOP_LOSS / TAKE_PROFIT: OMIT — the signed quantity is the ±int256.max
19
+ * full-position sentinel (sign from `isBuy`; protect the whole position)
20
+ * and qty is dropped from the wire payload. Passing a qty on a trigger
21
+ * create throws (the backend rejects it).
22
+ */
23
+ qty?: string;
12
24
  symbol: string;
25
+ orderType: OrderType;
26
+ /**
27
+ * REQUIRED for every order class — signed and sent on the wire. On a
28
+ * STOP_LOSS / TAKE_PROFIT it chooses what the stop becomes when it fires:
29
+ * IOC fills what the book offers and cancels the rest, GTC rests the
30
+ * remainder until cancelled, GTT rests it until one settlement headroom
31
+ * before `expiresAfter`.
32
+ */
13
33
  timeInForce: TimeInForce;
14
- clientOrderId?: number;
34
+ /** Required for STOP_LOSS / TAKE_PROFIT; omit for LIMIT. */
35
+ triggerPx?: string;
36
+ /** Perp only; spot markets must set this to false / omit. */
37
+ reduceOnly?: boolean;
38
+ /**
39
+ * Maker-only intent. Signed into OrderDetails. Valid on GTC/GTT; the API
40
+ * rejects it on IOC + TP/SL. Omit / false for a normal order.
41
+ */
42
+ postOnly?: boolean;
43
+ /** Off-chain correlation id. Signed but not on-chain-enforced. */
44
+ clientOrderId?: string;
45
+ /** Unix seconds. On-chain order lifetime; omit for no-expiry orders. */
46
+ expiresAfter?: number;
47
+ /**
48
+ * Unix seconds. EIP-712 signature deadline (envelope). API-enforced at entry.
49
+ * Defaults to now + 30s when omitted.
50
+ */
51
+ deadline?: number;
52
+ /**
53
+ * Seconds of settlement headroom a GTT `expiresAfter` must outlast. Defaults
54
+ * to the production value; set it only for a deployment running a different
55
+ * one.
56
+ */
57
+ settlementHeadroomSeconds?: number;
58
+ /**
59
+ * Optional explicit nonce. Must be strictly greater than the signer's last
60
+ * accepted nonce in the matching engine. Defaults to a per-signer monotonic
61
+ * µs value.
62
+ */
63
+ nonce?: bigint;
15
64
  };
16
- export declare const createSpotOrder: (params: CreateSpotOrderParams) => Promise<CreateOrderResponse>;
17
- export type CancelSpotOrderParams = {
65
+ export type CancelMEOrderParams = {
18
66
  signer: Signer | JsonRpcSigner;
19
67
  accountId: number;
20
68
  marketId: number;
21
69
  symbol: string;
22
70
  orderId?: string;
23
- clientOrderId?: number;
24
- expiresAfterSeconds?: number;
71
+ clientOrderId?: string;
72
+ /** Unix seconds; EIP-712 signature deadline. Defaults to now + 30s. */
73
+ deadline?: number;
74
+ /** Optional explicit nonce; otherwise per-signer monotonic µs. */
75
+ nonce?: bigint;
25
76
  };
26
- export declare const cancelSpotOrder: (params: CancelSpotOrderParams) => Promise<CancelOrderResponse>;
27
- export type MassCancelSpotOrdersParams = {
77
+ export type MassCancelMEOrdersParams = {
28
78
  signer: Signer | JsonRpcSigner;
29
79
  accountId: number;
30
- symbol?: string;
31
80
  marketId?: number;
32
- expiresAfterSeconds?: number;
81
+ symbol?: string;
82
+ /** Unix seconds; EIP-712 signature deadline. Defaults to now + 30s. */
83
+ deadline?: number;
84
+ /** Optional explicit nonce; otherwise per-signer monotonic µs. */
85
+ nonce?: bigint;
86
+ };
87
+ export declare const createOrder: (params: CreateOrderParams) => Promise<CreateOrderResponse>;
88
+ export declare const cancelMEOrder: (params: CancelMEOrderParams) => Promise<CancelOrderResponse>;
89
+ export declare const massCancelMEOrders: (params: MassCancelMEOrdersParams) => Promise<MassCancelResponse>;
90
+ export declare const createIOCOrder: (params: Omit<CreateOrderParams, 'timeInForce'>) => Promise<CreateOrderResponse>;
91
+ export type ClosePositionParams = {
92
+ signer: Signer | JsonRpcSigner;
93
+ accountId: number;
94
+ exchangeId: number;
95
+ marketId: number;
96
+ /** Closing direction — opposite of the current position side. */
97
+ isBuy: boolean;
98
+ /** Slippage gate. */
99
+ limitPx: string;
100
+ /** Position size to close. */
101
+ qty: string;
102
+ symbol: string;
103
+ clientOrderId?: string;
104
+ /** Unix seconds; EIP-712 signature deadline. Defaults to now + 30s. */
105
+ deadline?: number;
106
+ /** Optional explicit nonce override; otherwise generated per-signer. */
107
+ nonce?: bigint;
108
+ };
109
+ export declare const closePosition: (params: ClosePositionParams) => Promise<CreateOrderResponse>;
110
+ export type CancelAllAfterParams = {
111
+ signer: Signer | JsonRpcSigner;
112
+ accountId: number;
113
+ /**
114
+ * Countdown duration in milliseconds. `0` disarms; any non-zero value must
115
+ * be within [5000, 60000] and arms a fresh countdown of that duration,
116
+ * replacing any previously armed one (re-arming = the refresh/heartbeat).
117
+ * Recommended pattern: arm with 30000 and refresh every ~10-15s.
118
+ */
119
+ timeoutMs: number;
120
+ deadline?: number;
121
+ /**
122
+ * Optional explicit nonce; otherwise a per-signer monotonic µs value. Must be
123
+ * strictly greater than the signer's last accepted nonce in the matching
124
+ * engine. See `cancelAllAfter` below for retry semantics; the default
125
+ * `nextNonce` advances automatically.
126
+ */
127
+ nonce?: bigint;
128
+ };
129
+ /**
130
+ * Arm, refresh, or disarm the account-scoped cancel-on-disconnect
131
+ * dead-man's-switch. The countdown lives in the matching engine; when it
132
+ * elapses, all of the account's open orders (all markets) are mass-cancelled.
133
+ *
134
+ * The matching engine owns nonce replay protection. A request rejected by
135
+ * local validation before it is forwarded does not consume its nonce. Once a
136
+ * request is sent, a transport failure may be outcome-unknown, and a request
137
+ * that reaches the matching engine may record its nonce in the WAL. Retry with
138
+ * a strictly higher nonce after an ME response or transport uncertainty.
139
+ * Reusing an explicit nonce is safe only after a definite local pre-forward
140
+ * rejection. When `nonce` is omitted, `nextNonce` advances automatically.
141
+ */
142
+ export declare const cancelAllAfter: (params: CancelAllAfterParams) => Promise<CancelAllAfterResponse>;
143
+ type ModifyMEOrderCommonParams = {
144
+ signer: Signer | JsonRpcSigner;
145
+ accountId: number;
146
+ exchangeId: number;
147
+ /** Unified market id: core_id for perp, core_id + 1e10 for spot. */
148
+ marketId: number;
149
+ symbol: string;
150
+ /** Targeting: provide `orderId`, or a non-zero `clientOrderId`; both may be provided. */
151
+ orderId?: string;
152
+ clientOrderId?: string;
153
+ /**
154
+ * Full post-modify order state. The SDK does not fetch the resting order —
155
+ * the caller supplies every field, and the EIP-712 signature commits to
156
+ * all of them. Modifiable fields are limitPx, qty, postOnly, expiresAfter,
157
+ * and triggerPx. There is no omitted-means-inherited shorthand, so unchanged
158
+ * values must be restated explicitly; LIMIT orders omit triggerPx and sign
159
+ * triggerPrice = 0. Non-modifiable fields (isBuy, orderType, timeInForce,
160
+ * reduceOnly) must match the resting order's values.
161
+ */
162
+ isBuy: boolean;
163
+ limitPx: string;
164
+ /**
165
+ * TOTAL order quantity (not remaining). Type-conditional, mirroring the
166
+ * create-trigger path:
167
+ * - LIMIT: REQUIRED — must exceed the order's cumQty; signed as the total
168
+ * post-modify quantity.
169
+ * - STOP_LOSS / TAKE_PROFIT: OMIT — the signed quantity restates the
170
+ * ±int256.max full-position sentinel (sign from `isBuy`; protect the whole
171
+ * position) and qty is dropped from the wire payload. Passing a qty on a
172
+ * trigger modify throws (the backend rejects it).
173
+ */
174
+ qty?: string;
175
+ /** Immutable; restate the resting order's value. */
176
+ timeInForce: TimeInForce;
177
+ triggerPx?: string;
178
+ /** Unix seconds. Post-modify on-chain order lifetime; omit for no-expiry orders. */
179
+ expiresAfter?: number;
180
+ /**
181
+ * Resting order's clientOrderId, signed into OrderDetails.clientOrderId.
182
+ * If orderId is absent this is also the lookup target and must be non-zero.
183
+ * If orderId is present, orderId targets and clientOrderId only restates the
184
+ * immutable; omit it when the resting order has no client id.
185
+ */
186
+ /** Unix seconds; EIP-712 signature deadline. Defaults to now + 30s. */
187
+ deadline?: number;
188
+ /**
189
+ * Seconds of settlement headroom a GTT `expiresAfter` must outlast. Defaults
190
+ * to the production value; set it only for a deployment running a different
191
+ * one.
192
+ */
193
+ settlementHeadroomSeconds?: number;
194
+ /** Optional explicit nonce; otherwise per-signer monotonic µs. */
195
+ nonce?: bigint;
196
+ };
197
+ type LimitModifyMEOrderFields = Pick<Extract<ModifyOrderRequest, {
198
+ orderType: 'LIMIT';
199
+ }>, 'orderType' | 'postOnly'> & {
200
+ reduceOnly?: boolean;
33
201
  };
34
- export declare const massCancelSpotOrders: (params: MassCancelSpotOrdersParams) => Promise<MassCancelResponse>;
202
+ type TriggerModifyMEOrderFields = Pick<Extract<ModifyOrderRequest, {
203
+ orderType: 'STOP_LOSS' | 'TAKE_PROFIT';
204
+ }>, 'orderType' | 'postOnly' | 'reduceOnly'>;
205
+ export type ModifyMEOrderParams = ModifyMEOrderCommonParams & (LimitModifyMEOrderFields | TriggerModifyMEOrderFields);
206
+ /**
207
+ * Modify a resting order in place. The order keeps its orderId and
208
+ * clientOrderId; queue priority is preserved only for a qty decrease at an
209
+ * unchanged limitPx. The params carry the COMPLETE post-modify state; a request
210
+ * restating the resting order's exact current state is rejected with
211
+ * EMPTY_MODIFY_ERROR.
212
+ */
213
+ export declare const modifyMEOrder: (params: ModifyMEOrderParams) => Promise<ModifyOrderResponse>;
214
+ export {};
35
215
  //# sourceMappingURL=orderV2.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"orderV2.d.ts","sourceRoot":"/","sources":["services/orders/orderV2.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CAAC;IACb,oDAAoD;IACpD,WAAW,EAAE,WAAW,CAAC;IACzB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,oFAAoF;IACpF,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;;;OAKG;IACH,uEAAuE;IACvE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;;OAIG;IACH,yBAAyB,CAAC,EAAE,MAAM,CAAC;IACnC,kEAAkE;IAClE,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC;AAIF,KAAK,wBAAwB,GAAG,IAAI,CAClC,OAAO,CAAC,kBAAkB,EAAE;IAAE,SAAS,EAAE,OAAO,CAAA;CAAE,CAAC,EACnD,WAAW,GAAG,UAAU,CACzB,GAAG;IAAE,UAAU,CAAC,EAAE,OAAO,CAAA;CAAE,CAAC;AAC7B,KAAK,0BAA0B,GAAG,IAAI,CACpC,OAAO,CAAC,kBAAkB,EAAE;IAAE,SAAS,EAAE,WAAW,GAAG,aAAa,CAAA;CAAE,CAAC,EACvE,WAAW,GAAG,UAAU,GAAG,YAAY,CACxC,CAAC;AAEF,MAAM,MAAM,mBAAmB,GAAG,yBAAyB,GACzD,CAAC,wBAAwB,GAAG,0BAA0B,CAAC,CAAC;AAE1D;;;;;;GAMG;AACH,eAAO,MAAM,aAAa,WAChB,mBAAmB,KAC1B,QAAQ,mBAAmB,CA4K7B,CAAC"}
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Client-side mirror of the one trigger-admission rule a client can evaluate on
3
+ * its own: the settlement headroom a `GTT` lifetime must outlast.
4
+ *
5
+ * The per-market limit band is deliberately NOT mirrored here. It is an
6
+ * engine-side admission rule derived from matching-engine config, it is not
7
+ * published on the API, and a client cannot compute it — a `limitPx` outside it
8
+ * is refused at admission with `TRIGGER_LIMIT_OUTSIDE_BAND_ERROR`.
9
+ */
10
+ /**
11
+ * Settlement headroom of a production deployment, in seconds. A `GTT` lifetime
12
+ * must be STRICTLY greater than `now + headroom`, or the engine refuses the
13
+ * order with `ORDER_EXPIRES_TOO_SOON_ERROR`. It is a venue parameter and is not
14
+ * published on the API; a deployment that runs a different one is handled by
15
+ * the per-call `settlementHeadroomSeconds` override.
16
+ */
17
+ export declare const DEFAULT_SETTLEMENT_HEADROOM_SECONDS = 60;
18
+ /**
19
+ * Refuse a `GTT` lifetime that does not outlast the settlement headroom.
20
+ *
21
+ * Independent of the `expiresAfter > deadline` coupling: a caller that pins a
22
+ * short deadline satisfies that check while still signing a lifetime the engine
23
+ * refuses. On a trigger the same deadline covers both phases, so the headroom
24
+ * bites there too.
25
+ *
26
+ * `expiresAfter` must be a positive safe integer (Unix seconds) and
27
+ * `headroomSeconds` a finite non-negative number; both are checked here rather
28
+ * than at the later `BigInt(expiresAfter)` conversion, so a `NaN`, `Infinity`,
29
+ * fractional or negative value fails at the validation boundary instead of
30
+ * after the signer has been resolved and a nonce minted.
31
+ */
32
+ export declare const assertSettlementHeadroom: (expiresAfter: number, headroomSeconds?: number, nowSeconds?: number) => void;
33
+ //# sourceMappingURL=triggerSettlementHeadroom.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"triggerSettlementHeadroom.d.ts","sourceRoot":"/","sources":["services/orders/triggerSettlementHeadroom.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH;;;;;;GAMG;AACH,eAAO,MAAM,mCAAmC,KAAK,CAAC;AAEtD;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,wBAAwB,iBACrB,MAAM,oBACH,MAAM,eACX,MAAM,KACjB,IAkBF,CAAC"}
@@ -1,5 +1,5 @@
1
1
  import { Signer, JsonRpcSigner } from 'ethers';
2
- import { CoreCommandsEIP712SignatureAndPayload, MarketEntity, MethodParameters, OrdersGatewayOrderType, OwnerMetadataEntity, PositionEntity, TransactionExecutionOutput } from '@reyaxyz/common';
2
+ import { CoreCommandsEIP712SignatureAndPayload, MarketEntity, MethodParameters, OwnerMetadataEntity, PositionEntity, TransactionExecutionOutput } from '@reyaxyz/common';
3
3
  export type MarketParams = {
4
4
  id: MarketEntity['id'];
5
5
  exchangeId: MarketEntity['orderInfo']['exchangeId'];
@@ -51,14 +51,4 @@ export type CloseOrderResult = {
51
51
  base: number;
52
52
  };
53
53
  export type MethodParametersAndEIP712Payload = MethodParameters & CoreCommandsEIP712SignatureAndPayload;
54
- export type OrdersGatewayMarketOrderParams = {
55
- signer: Signer | JsonRpcSigner;
56
- marginAccountId: number;
57
- marketId: MarketEntity['id'];
58
- counterpartyAccountIds: MarketEntity['orderInfo']['counterpartyAccountIds'];
59
- exchangeId: MarketEntity['orderInfo']['exchangeId'];
60
- orderType: OrdersGatewayOrderType.MARKET_ORDER | OrdersGatewayOrderType.REDUCE_ONLY_MARKET_ORDER | OrdersGatewayOrderType.FULL_CLOSE_ORDER;
61
- orderInputs: string;
62
- tradeSource?: 'reya' | 'rage' | 'other';
63
- };
64
54
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"/","sources":["services/orders/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AAC/C,OAAO,EACL,qCAAqC,EACrC,YAAY,EACZ,gBAAgB,EAChB,sBAAsB,EACtB,mBAAmB,EACnB,cAAc,EACd,0BAA0B,EAC3B,MAAM,iBAAiB,CAAC;AAEzB,MAAM,MAAM,YAAY,GAAG;IACzB,EAAE,EAAE,YAAY,CAAC,IAAI,CAAC,CAAC;IACvB,UAAU,EAAE,YAAY,CAAC,WAAW,CAAC,CAAC,YAAY,CAAC,CAAC;IACpD,sBAAsB,EAAE,YAAY,CAAC,WAAW,CAAC,CAAC,wBAAwB,CAAC,CAAC;IAC5E,gBAAgB,EAAE,YAAY,CAAC,kBAAkB,CAAC,CAAC;IACnD,WAAW,EAAE,YAAY,CAAC,aAAa,CAAC,CAAC;CAC1C,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG;IAC7B,MAAM,EAAE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eAAe,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,YAAY,EAAE,mBAAmB,CAAC,cAAc,CAAC,GAAG,IAAI,CAAC;IACzD,OAAO,EAAE,MAAM,CAAC;IAChB,cAAc,EAAE,MAAM,CAAC;IACvB,QAAQ,EAAE,OAAO,CAAC;IAClB,eAAe,EAAE,MAAM,CAAC;IACxB,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,MAAM,CAAC;IACvB,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,MAAM,MAAM,gCAAgC,GAAG,gBAAgB,GAC7D,qCAAqC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reyaxyz/sdk",
3
- "version": "0.151.4",
3
+ "version": "0.152.1",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "registry": "https://registry.npmjs.org"
@@ -24,19 +24,20 @@
24
24
  "code-quality:check": "npx concurrently 'pnpm ts:check' 'pnpm prettier:check' 'pnpm lint:check --quiet'",
25
25
  "lint:fix": "npx eslint --fix '{src,demo,tests}/**/*.{ts,tsx}'",
26
26
  "prettier:fix": "npx prettier --log-level silent --write './{src,demo,tests}/**/*.{ts,tsx}'",
27
- "test": "npx jest --silent",
27
+ "test": "pnpm test:types && npx jest --silent",
28
28
  "test:coverage": "jest test --coverage",
29
29
  "generate:coverage-badges": "npx istanbul-badges-readme --silent",
30
30
  "test:spot-order": "npx ts-node scripts/test-spot-order.ts",
31
- "test:cancel-spot-order": "npx ts-node scripts/test-cancel-spot-order.ts"
31
+ "test:cancel-spot-order": "npx ts-node scripts/test-cancel-spot-order.ts",
32
+ "test:types": "tsc -p tsconfig.test-types.json"
32
33
  },
33
34
  "dependencies": {
34
- "@reyaxyz/api-v2-sdk": "0.308.0",
35
- "@reyaxyz/common": "0.362.1",
35
+ "@reyaxyz/api-v2-sdk": "0.309.0",
36
+ "@reyaxyz/common": "0.364.0",
36
37
  "axios": "1.6.2",
37
38
  "bignumber.js": "9.1.2",
38
- "ethers": "6.9.0"
39
+ "ethers": "6.17.0"
39
40
  },
40
41
  "packageManager": "pnpm@8.3.1",
41
- "gitHead": "8dbf4da176ddaf08a9962f8a73824dfa9ded7e44"
42
+ "gitHead": "d550bc1ace1a4a7dd87331ba7abf76833c7f99df"
42
43
  }
@@ -1,3 +1,3 @@
1
1
  export * from './types';
2
- export * from './order';
3
2
  export * from './orderV2';
3
+ export * from './triggerSettlementHeadroom';