@yuants/vendor-hyperliquid 0.9.9 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/dist/api/client.js +36 -2
  2. package/dist/api/client.js.map +1 -1
  3. package/dist/api/private-api.js +52 -41
  4. package/dist/api/private-api.js.map +1 -1
  5. package/dist/api/public-api.js +22 -11
  6. package/dist/api/public-api.js.map +1 -1
  7. package/dist/api/rate-limit.js +205 -0
  8. package/dist/api/rate-limit.js.map +1 -0
  9. package/dist/api/rate-limit.test.js +129 -0
  10. package/dist/api/rate-limit.test.js.map +1 -0
  11. package/dist/api/sign.js.map +1 -1
  12. package/dist/api/types.js.map +1 -1
  13. package/dist/index.js +0 -2
  14. package/dist/index.js.map +1 -1
  15. package/dist/services/accounts/spot.js.map +1 -1
  16. package/dist/services/exchange.js.map +1 -1
  17. package/dist/services/markets/quote.js.map +1 -1
  18. package/dist/services/ohlc-service.js.map +1 -1
  19. package/dist/services/orders/cancelOrder.js.map +1 -1
  20. package/dist/services/orders/listOrders.js +2 -2
  21. package/dist/services/orders/listOrders.js.map +1 -1
  22. package/dist/services/orders/modifyOrder.js.map +1 -1
  23. package/dist/services/quotes.js.map +1 -1
  24. package/dist/services/utils.js.map +1 -1
  25. package/lib/api/client.d.ts +1 -1
  26. package/lib/api/client.d.ts.map +1 -1
  27. package/lib/api/client.js +35 -1
  28. package/lib/api/client.js.map +1 -1
  29. package/lib/api/private-api.d.ts +67 -3
  30. package/lib/api/private-api.d.ts.map +1 -1
  31. package/lib/api/private-api.js +59 -43
  32. package/lib/api/private-api.js.map +1 -1
  33. package/lib/api/public-api.d.ts +61 -11
  34. package/lib/api/public-api.d.ts.map +1 -1
  35. package/lib/api/public-api.js +33 -12
  36. package/lib/api/public-api.js.map +1 -1
  37. package/lib/api/rate-limit.d.ts +21 -0
  38. package/lib/api/rate-limit.d.ts.map +1 -0
  39. package/lib/api/rate-limit.js +214 -0
  40. package/lib/api/rate-limit.js.map +1 -0
  41. package/lib/api/rate-limit.test.d.ts +2 -0
  42. package/lib/api/rate-limit.test.d.ts.map +1 -0
  43. package/lib/api/rate-limit.test.js +131 -0
  44. package/lib/api/rate-limit.test.js.map +1 -0
  45. package/lib/api/sign.js +5 -6
  46. package/lib/api/sign.js.map +1 -1
  47. package/lib/api/types.d.ts.map +1 -1
  48. package/lib/api/types.js.map +1 -1
  49. package/lib/index.d.ts +0 -2
  50. package/lib/index.d.ts.map +1 -1
  51. package/lib/index.js +0 -2
  52. package/lib/index.js.map +1 -1
  53. package/lib/services/accounts/perp.d.ts.map +1 -1
  54. package/lib/services/accounts/spot.d.ts.map +1 -1
  55. package/lib/services/accounts/spot.js.map +1 -1
  56. package/lib/services/exchange.js.map +1 -1
  57. package/lib/services/markets/product.d.ts.map +1 -1
  58. package/lib/services/markets/quote.js.map +1 -1
  59. package/lib/services/ohlc-service.js.map +1 -1
  60. package/lib/services/orders/cancelOrder.d.ts.map +1 -1
  61. package/lib/services/orders/cancelOrder.js.map +1 -1
  62. package/lib/services/orders/listOrders.d.ts.map +1 -1
  63. package/lib/services/orders/listOrders.js +2 -2
  64. package/lib/services/orders/listOrders.js.map +1 -1
  65. package/lib/services/orders/modifyOrder.d.ts.map +1 -1
  66. package/lib/services/orders/modifyOrder.js.map +1 -1
  67. package/lib/services/orders/submitOrder.d.ts.map +1 -1
  68. package/lib/services/quotes.js.map +1 -1
  69. package/lib/services/utils.d.ts +2 -2
  70. package/lib/services/utils.d.ts.map +1 -1
  71. package/lib/services/utils.js.map +1 -1
  72. package/lib/tsdoc-metadata.json +1 -1
  73. package/package.json +48 -48
  74. package/temp/build/typescript/ts_HOjXkPSo.json +1 -0
  75. package/temp/package-deps.json +27 -27
  76. package/temp/test/jest/haste-map-1a3370ad4952cc1cbecf8fc42c6e9732-7b2990dcc44090c4eba2c52e971c544c-6a2a6e27ca3579da37751287ea19ab4c +0 -0
  77. package/temp/test/jest/perf-cache-1a3370ad4952cc1cbecf8fc42c6e9732-da39a3ee5e6b4b0d3255bfef95601890 +1 -0
  78. package/temp/vendor-hyperliquid.api.json +18 -2
  79. package/dist/services/markets/interest-rate.js +0 -60
  80. package/dist/services/markets/interest-rate.js.map +0 -1
  81. package/dist/services/markets/ohlc.js +0 -110
  82. package/dist/services/markets/ohlc.js.map +0 -1
  83. package/lib/services/markets/interest-rate.d.ts +0 -2
  84. package/lib/services/markets/interest-rate.d.ts.map +0 -1
  85. package/lib/services/markets/interest-rate.js +0 -62
  86. package/lib/services/markets/interest-rate.js.map +0 -1
  87. package/lib/services/markets/ohlc.d.ts +0 -2
  88. package/lib/services/markets/ohlc.d.ts.map +0 -1
  89. package/lib/services/markets/ohlc.js +0 -112
  90. package/lib/services/markets/ohlc.js.map +0 -1
@@ -24,12 +24,12 @@ const mapOrder = (order) => {
24
24
  order_id: `${order.oid}`,
25
25
  account_id: '',
26
26
  product_id: encodePath('HYPERLIQUID', 'PERPETUAL', `${(_a = order.coin) === null || _a === void 0 ? void 0 : _a.trim()}-USD`),
27
- order_type: 'LIMIT',
27
+ order_type: 'LIMIT', // Hyperliquid primarily uses limit orders
28
28
  order_direction: mapOrderDirection(order.side),
29
29
  volume: Number.isFinite(volume) ? volume : 0,
30
30
  price: Number.isFinite(price) && price > 0 ? price : undefined,
31
31
  submit_at: Number((_b = order.timestamp) !== null && _b !== void 0 ? _b : Date.now()),
32
- order_status: 'open',
32
+ order_status: 'open', // Since these are open orders
33
33
  // Additional fields that might be useful
34
34
  comment: order.coin ? JSON.stringify({ asset_id: order.coin }) : undefined,
35
35
  };
@@ -1 +1 @@
1
- {"version":3,"file":"listOrders.js","sourceRoot":"","sources":["../../../src/services/orders/listOrders.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAEnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAIzD;;GAEG;AACH,MAAM,iBAAiB,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,UAAU,EAAE,CAAC,CAAC;KACtE;IACD,IAAI,QAAQ,KAAK,WAAW,EAAE;QAC5B,OAAO,EAAE,CAAC;KACX;IACD,MAAM,MAAM,GAAG,MAAM,cAAc,CAAC,UAAU,CAAC,CAAC;IAChD,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,UAAU,KAAK,UAAU,CAAC,CAAC;AACnE,CAAC,CAAC","sourcesContent":["import { IOrder } from '@yuants/data-order';\nimport { decodePath, encodePath, formatTime } from '@yuants/utils';\nimport { ICredential, getCredentialId } from '../../api/types';\nimport { getUserOpenOrders } from '../../api/public-api';\n\ntype OrderDirection = 'OPEN_LONG' | 'OPEN_SHORT' | 'CLOSE_LONG' | 'CLOSE_SHORT';\n\n/**\n * Map order direction based on side and reduce-only logic\n */\nconst mapOrderDirection = (side: string): OrderDirection => {\n const normalized = side.toUpperCase();\n if (normalized === 'BID' || normalized === 'BUY') {\n return 'OPEN_LONG';\n }\n if (normalized === 'ASK' || normalized === 'SELL') {\n return 'OPEN_SHORT';\n }\n return 'OPEN_LONG';\n};\n\n/**\n * Map Hyperliquid order to Yuan IOrder format\n */\nconst mapOrder = (order: any): IOrder => {\n const volume = Number(order.sz) || 0;\n const price = Number(order.limitPx) || 0;\n\n return {\n order_id: `${order.oid}`,\n account_id: '',\n product_id: encodePath('HYPERLIQUID', 'PERPETUAL', `${order.coin?.trim()}-USD`),\n order_type: 'LIMIT', // Hyperliquid primarily uses limit orders\n order_direction: mapOrderDirection(order.side),\n volume: Number.isFinite(volume) ? volume : 0,\n price: Number.isFinite(price) && price > 0 ? price : undefined,\n submit_at: Number(order.timestamp ?? Date.now()),\n order_status: 'open', // Since these are open orders\n // Additional fields that might be useful\n comment: order.coin ? JSON.stringify({ asset_id: order.coin }) : undefined,\n };\n};\n\n/**\n * List perpetual orders\n */\nexport const listPerpOrders = async (credential: ICredential): Promise<IOrder[]> => {\n console.info(`[${formatTime(Date.now())}] Listing perpetual orders for ${credential.address}`);\n\n try {\n const orders = await getUserOpenOrders({ user: credential.address });\n if (!orders || !Array.isArray(orders)) {\n return [];\n }\n return orders.map((order) => mapOrder(order));\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n console.error(`[${formatTime(Date.now())}] Failed to list perpetual orders: ${errorMessage}`);\n throw new Error(`Failed to list perpetual orders: ${errorMessage}`);\n }\n};\n\n/**\n * List orders by product_id\n */\nexport const listOrdersByProductId = async (\n credential: ICredential,\n product_id: string,\n): Promise<IOrder[]> => {\n const [exchange, instType] = decodePath(product_id);\n if (exchange !== 'HYPERLIQUID') {\n throw new Error(`Invalid product_id for Hyperliquid: ${product_id}`);\n }\n if (instType !== 'PERPETUAL') {\n return [];\n }\n const orders = await listPerpOrders(credential);\n return orders.filter((order) => order.product_id === product_id);\n};\n"]}
1
+ {"version":3,"file":"listOrders.js","sourceRoot":"","sources":["../../../src/services/orders/listOrders.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAEnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAIzD;;GAEG;AACH,MAAM,iBAAiB,GAAG,CAAC,IAAY,EAAkB,EAAE;IACzD,MAAM,UAAU,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;IACtC,IAAI,UAAU,KAAK,KAAK,IAAI,UAAU,KAAK,KAAK,EAAE,CAAC;QACjD,OAAO,WAAW,CAAC;IACrB,CAAC;IACD,IAAI,UAAU,KAAK,KAAK,IAAI,UAAU,KAAK,MAAM,EAAE,CAAC;QAClD,OAAO,YAAY,CAAC;IACtB,CAAC;IACD,OAAO,WAAW,CAAC;AACrB,CAAC,CAAC;AAEF;;GAEG;AACH,MAAM,QAAQ,GAAG,CAAC,KAAU,EAAU,EAAE;;IACtC,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,IAAI,CAAC,CA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nimport { ICredential, getCredentialId } from '../../api/types';\nimport { getUserOpenOrders } from '../../api/public-api';\n\ntype OrderDirection = 'OPEN_LONG' | 'OPEN_SHORT' | 'CLOSE_LONG' | 'CLOSE_SHORT';\n\n/**\n * Map order direction based on side and reduce-only logic\n */\nconst mapOrderDirection = (side: string): OrderDirection => {\n const normalized = side.toUpperCase();\n if (normalized === 'BID' || normalized === 'BUY') {\n return 'OPEN_LONG';\n }\n if (normalized === 'ASK' || normalized === 'SELL') {\n return 'OPEN_SHORT';\n }\n return 'OPEN_LONG';\n};\n\n/**\n * Map Hyperliquid order to Yuan IOrder format\n */\nconst mapOrder = (order: any): IOrder => {\n const volume = Number(order.sz) || 0;\n const price = Number(order.limitPx) || 0;\n\n return {\n order_id: `${order.oid}`,\n account_id: '',\n product_id: encodePath('HYPERLIQUID', 'PERPETUAL', `${order.coin?.trim()}-USD`),\n order_type: 'LIMIT', // Hyperliquid primarily uses limit orders\n order_direction: mapOrderDirection(order.side),\n volume: Number.isFinite(volume) ? volume : 0,\n price: Number.isFinite(price) && price > 0 ? price : undefined,\n submit_at: Number(order.timestamp ?? Date.now()),\n order_status: 'open', // Since these are open orders\n // Additional fields that might be useful\n comment: order.coin ? JSON.stringify({ asset_id: order.coin }) : undefined,\n };\n};\n\n/**\n * List perpetual orders\n */\nexport const listPerpOrders = async (credential: ICredential): Promise<IOrder[]> => {\n console.info(`[${formatTime(Date.now())}] Listing perpetual orders for ${credential.address}`);\n\n try {\n const orders = await getUserOpenOrders({ user: credential.address });\n if (!orders || !Array.isArray(orders)) {\n return [];\n }\n return orders.map((order) => mapOrder(order));\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n console.error(`[${formatTime(Date.now())}] Failed to list perpetual orders: ${errorMessage}`);\n throw new Error(`Failed to list perpetual orders: ${errorMessage}`);\n }\n};\n\n/**\n * List orders by product_id\n */\nexport const listOrdersByProductId = async (\n credential: ICredential,\n product_id: string,\n): Promise<IOrder[]> => {\n const [exchange, instType] = decodePath(product_id);\n if (exchange !== 'HYPERLIQUID') {\n throw new Error(`Invalid product_id for Hyperliquid: ${product_id}`);\n }\n if (instType !== 'PERPETUAL') {\n return [];\n }\n const orders = await listPerpOrders(credential);\n return orders.filter((order) => order.product_id === product_id);\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"modifyOrder.js","sourceRoot":"","sources":["../../../src/services/orders/modifyOrder.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAE3C,OAAO,EAAE,WAAW,IAAI,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACtE,OAAO,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAE7C;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,KAAK,EAAE,UAAuB,EAAE,KAAa,EAAiB,EAAE;;IACzF,OAAO,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,qBAAqB,KAAK,CAAC,QAAQ,QAAQ,KAAK,CAAC,UAAU,EAAE,CAAC,CAAC;IAEtG,IAAI;QACF,oBAAoB;QACpB,MAAM,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;QACvC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE;YAC7B,MAAM,IAAI,KAAK,CAAC,qBAAqB,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC;SACxD;QAED,sDAAsD;QACtD,MAAM,EAAE,WAAW,EAAE,GAAG,MAAM,iBAAiB,CAAC,KAAK,CAAC,CAAC;QAEvD,OAAO,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,qBAAqB,KAAK,CAAC,QAAQ,mBAAmB,EAAE;YAC7F,KAAK,EAAE,WAAW,CAAC,CAAC;YACpB,KAAK,EAAE,WAAW,CAAC,CAAC;YACpB,KAAK,EAAE,WAAW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A2B,YAAY,EAAE,CAAC,CAAC;KAC5D;AACH,CAAC,CAAC","sourcesContent":["import { IOrder } from '@yuants/data-order';\nimport { formatTime } from '@yuants/utils';\nimport { ICredential } from '../../api/types';\nimport { modifyOrder as modifyOrderApi } from '../../api/private-api';\nimport { buildOrderPayload } from '../utils';\n\n/**\n * 修改订单 - 使用 Hyperliquid 原生 modify order API\n *\n * Hyperliquid supports native order modification through the modify action:\n * https://hyperliquid.gitbook.io/hyperliquid-docs/for-develope../../api/exchange-endpoint#modify-an-order\n *\n * This is more efficient than cancel + place new as it:\n * 1. Maintains order priority in the order book\n * 2. Reduces API calls from 2 to 1\n * 3. Prevents race conditions where the cancelled order might be filled before new order is placed\n */\nexport const modifyOrder = async (credential: ICredential, order: IOrder): Promise<void> => {\n console.info(`[${formatTime(Date.now())}] Modifying order ${order.order_id} for ${order.product_id}`);\n\n try {\n // Validate order_id\n const orderId = Number(order.order_id);\n if (!Number.isFinite(orderId)) {\n throw new Error(`Invalid order_id: ${order.order_id}`);\n }\n\n // Build the new order payload with updated parameters\n const { orderParams } = await buildOrderPayload(order);\n\n console.info(`[${formatTime(Date.now())}] Modifying order ${order.order_id} with new params:`, {\n asset: orderParams.a,\n isBuy: orderParams.b,\n price: orderParams.p,\n size: orderParams.s,\n reduceOnly: orderParams.r,\n tif: orderParams.t.limit?.tif,\n });\n\n // Call Hyperliquid's native modify order API\n const result = await modifyOrderApi(credential, {\n oid: orderId,\n order: orderParams,\n });\n\n // Check if the modification was successful\n const status = result?.response?.data?.statuses?.[0];\n const error = result?.status !== 'ok' ? 'API ERROR' : status?.error ? status.error : undefined;\n\n if (error) {\n throw new Error(`Failed to modify order: ${error}`);\n }\n\n console.info(`[${formatTime(Date.now())}] Order ${order.order_id} modified successfully`);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n console.error(`[${formatTime(Date.now())}] Failed to modify order ${order.order_id}: ${errorMessage}`);\n throw new Error(`Failed to modify order: ${errorMessage}`);\n }\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port { modifyOrder as modifyOrderApi } from '../../api/private-api';\nimport { buildOrderPayload } from '../utils';\n\n/**\n * 修改订单 - 使用 Hyperliquid 原生 modify order API\n *\n * Hyperliquid supports native order modification through the modify action:\n * https://hyperliquid.gitbook.io/hyperliquid-docs/for-develope../../api/exchange-endpoint#modify-an-order\n *\n * This is more efficient than cancel + place new as it:\n * 1. Maintains order priority in the order book\n * 2. Reduces API calls from 2 to 1\n * 3. Prevents race conditions where the cancelled order might be filled before new order is placed\n */\nexport const modifyOrder = async (credential: ICredential, order: IOrder): Promise<void> => {\n console.info(`[${formatTime(Date.now())}] Modifying order ${order.order_id} for ${order.product_id}`);\n\n try {\n // Validate order_id\n const orderId = Number(order.order_id);\n if (!Number.isFinite(orderId)) {\n throw new Error(`Invalid order_id: ${order.order_id}`);\n }\n\n // Build the new order payload with updated parameters\n const { orderParams } = await buildOrderPayload(order);\n\n console.info(`[${formatTime(Date.now())}] Modifying order ${order.order_id} with new params:`, {\n asset: orderParams.a,\n isBuy: orderParams.b,\n price: orderParams.p,\n size: orderParams.s,\n reduceOnly: orderParams.r,\n tif: orderParams.t.limit?.tif,\n });\n\n // Call Hyperliquid's native modify order API\n const result = await modifyOrderApi(credential, {\n oid: orderId,\n order: orderParams,\n });\n\n // Check if the modification was successful\n const status = result?.response?.data?.statuses?.[0];\n const error = result?.status !== 'ok' ? 'API ERROR' : status?.error ? status.error : undefined;\n\n if (error) {\n throw new Error(`Failed to modify order: ${error}`);\n }\n\n console.info(`[${formatTime(Date.now())}] Order ${order.order_id} modified successfully`);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n console.error(`[${formatTime(Date.now())}] Failed to modify order ${order.order_id}: ${errorMessage}`);\n throw new Error(`Failed to modify order: ${errorMessage}`);\n }\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"quotes.js","sourceRoot":"","sources":["../../src/services/quotes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,kB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IAAI,CAAE,QAAQ,0CAAE,OAAO,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QACvC,MAAM,GAAG,GAAG,SAAS,aAAT,SAAS,uBAAT,SAAS,CAAG,KAAK,CAAC,CAAC;QAC/B,IAAI,CAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,IAAI,KAAI,GAAG,EAAE;YACtB,SAAS,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;SAChC;IACH,CAAC,CAAC,CAAC;IAEH,OAAO,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,EAAE;;QAAC,OAAA,CAAC;YAC3D,UAAU,EAAE,UAAU,CAAC,aAAa,EAAE,WAAW,EAAE,GAAG,IAAI,MAAM,CAAC;YACjE,UAAU,EAAE,IAAI,CAAC,GAAG,EAAE;YACtB,aAAa,EAAE,MAAA,GAAG,CAAC,YAAY,mCAAI,GAAG;YACtC,kBAAkB,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG;YACjE,mBAAmB,EAAE,MAAA,GAAG,CAAC,OAAO,mCAAI,GAAG;SACxC,CAAC,CAAA;KAAA,CAAC,CAAC;AACN,CAAC,CACF,CAAC","sourcesContent":["import { provideQuoteService } from '@yuants/exchange';\nimport { Terminal } from '@yuants/protocol';\nimport { encodePath } from '@yuants/utils';\nimport { getAllMids, getMetaAndAssetCtxs } from '../api/public-api';\n\nconst terminal = Terminal.fromNodeEnv();\n\nprovideQuoteService(\n terminal,\n {\n product_id_prefix: 'HYPERLIQUID/PERPETUAL/',\n fields: ['last_price', 'ask_price', 'bid_price'],\n },\n async (req) => {\n const mids = await getAllMids();\n\n return Object.entries(mids ?? {}).map(([coin, price]) => {\n return {\n product_id: encodePath('HYPERLIQUID', 'PERPETUAL', `${coin}-USD`),\n updated_at: Date.now(),\n last_price: `${price}`,\n bid_price: `${price}`,\n ask_price: `${price}`,\n };\n });\n },\n);\n\nprovideQuoteService(\n terminal,\n {\n product_id_prefix: 'HYPERLIQUID/PERPETUAL/',\n fields: ['open_interest', 'interest_rate_long', 'interest_rate_short'],\n },\n async (req) => {\n const [meta, assetCtxs] = await getMetaAndAssetCtxs();\n\n const coinToCtx = new Map<string, (typeof assetCtxs)[number]>();\n meta?.universe?.forEach((asset, index) => {\n const ctx = assetCtxs?.[index];\n if (asset?.name && ctx) {\n coinToCtx.set(asset.name, ctx);\n }\n });\n\n return Array.from(coinToCtx.entries()).map(([coin, ctx]) => ({\n product_id: encodePath('HYPERLIQUID', 'PERPETUAL', `${coin}-USD`),\n updated_at: Date.now(),\n open_interest: ctx.openInterest ?? '0',\n interest_rate_long: ctx.funding ? `${-Number(ctx.funding)}` : '0',\n interest_rate_short: ctx.funding ?? '0',\n }));\n },\n);\n"]}
1
+ {"version":3,"file":"quotes.js","sourceRoot":"","sources":["../../src/services/quotes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAEpE,MAAM,QAAQ,GAAG,QAAQ,CAAC,WAAW,EAAE,CAAC;AAExC,mBAAmB,CACjB,QAAQ,EACR;IACE,iBAAiB,EAAE,wBAAwB;IAC3C,MAAM,EAAE,CAAC,YAAY,EAAE,WAAW,EAAE,WAAW,CAAC;CACjD,EACD,KAAK,EAAE,GAAG,EAAE,EAAE;IACZ,MAAM,IAAI,GAAG,MAAM,UAAU,EAAE,CAAC;IAEhC,OAAO,MAAM,CAAC,OAAO,CAA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AAC,OAAA,CAAC;YAC3D,UAAU,EAAE,UAAU,CAAC,aAAa,EAAE,WAAW,EAAE,GAAG,IAAI,MAAM,CAAC;YACjE,UAAU,EAAE,IAAI,CAAC,GAAG,EAAE;YACtB,aAAa,EAAE,MAAA,GAAG,CAAC,YAAY,mCAAI,GAAG;YACtC,kBAAkB,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG;YACjE,mBAAmB,EAAE,MAAA,GAAG,CAAC,OAAO,mCAAI,GAAG;SACxC,CAAC,CAAA;KAAA,CAAC,CAAC;AACN,CAAC,CACF,CAAC","sourcesContent":["import { provideQuoteService } from '@yuants/exchange';\nimport { Terminal } from '@yuants/protocol';\nimport { encodePath } from '@yuants/utils';\nimport { getAllMids, getMetaAndAssetCtxs } from '../api/public-api';\n\nconst terminal = Terminal.fromNodeEnv();\n\nprovideQuoteService(\n terminal,\n {\n product_id_prefix: 'HYPERLIQUID/PERPETUAL/',\n fields: ['last_price', 'ask_price', 'bid_price'],\n },\n async (req) => {\n const mids = await getAllMids();\n\n return Object.entries(mids ?? {}).map(([coin, price]) => {\n return {\n product_id: encodePath('HYPERLIQUID', 'PERPETUAL', `${coin}-USD`),\n updated_at: Date.now(),\n last_price: `${price}`,\n bid_price: `${price}`,\n ask_price: `${price}`,\n };\n });\n },\n);\n\nprovideQuoteService(\n terminal,\n {\n product_id_prefix: 'HYPERLIQUID/PERPETUAL/',\n fields: ['open_interest', 'interest_rate_long', 'interest_rate_short'],\n },\n async (req) => {\n const [meta, assetCtxs] = await getMetaAndAssetCtxs();\n\n const coinToCtx = new Map<string, (typeof assetCtxs)[number]>();\n meta?.universe?.forEach((asset, index) => {\n const ctx = assetCtxs?.[index];\n if (asset?.name && ctx) {\n coinToCtx.set(asset.name, ctx);\n }\n });\n\n return Array.from(coinToCtx.entries()).map(([coin, ctx]) => ({\n product_id: encodePath('HYPERLIQUID', 'PERPETUAL', `${coin}-USD`),\n updated_at: Date.now(),\n open_interest: ctx.openInterest ?? '0',\n interest_rate_long: ctx.funding ? `${-Number(ctx.funding)}` : '0',\n interest_rate_short: ctx.funding ?? '0',\n }));\n },\n);\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/services/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAE5C,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,qBAAqB,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AASvF,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,UAAkB,EAAsD,EAAE;IACzG,MAAM,CAAC,QAAQ,EAAE,QAAQ,EAAE,MAAM,CAAC,GAAG,UAAU,CAAC,UAAU,CAAC,CAAC;IAC5D,IAAI,QAAQ,KAAK,aAAa,IAAI,CAAC,QAAQ,IAAI,CAAC,MAAM,EAAE;QACtD,MAAM,IAAI,KAAK,CAAC,uBAAuB,UAAU,EAAE,CAAC,CAAC;KACtD;IACD,IAAI,QAAQ,+CAA6B,IAAI,QAAQ,qCAAwB,EAAE;QAC7E,MAAM,IAAI,KAAK,CAAC,gCAAgC,QAAQ,EAAE,CAAC,CAAC;KAC7D;IACD,MAAM,YAAY,GAAG,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IAC1C,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,CAAC;AACpC,CAAC,CAAC;AAEF,MAAM,SAAS,GAAG,KAAM,CAAC;AACzB,MAAM,OAAO,GAAG,IAAK,CAAC;AAEtB,0CAA0C;AAC1C,MAAM,aAAa,GAAG,WAAW,CAC/B,KAAK,IAAI,EAAE;IACT,OAAO,CAAC,IAAI,CAAC,mDAAmD,CAAC,CAAC;IAClE,MAAM,IAAI,GAAG,MAAM,qBA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MAAM,EAAE;YACpB,CAAC,EAAE,UAAU;YACb,CAAC,EAAE,EAAE,KAAK,EAAE,EAAE,GAAG,EAAE,EAAE;SACtB;KACF,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,uBAAuB,GAAG,KAAK,EAAE,IAAY,EAAE,KAAc,EAAE,EAAE;IAC5E,MAAM,IAAI,GAAG,CAAC,MAAM,aAAa,CAAC,KAAK,CAAC,MAAM,CAAC,CAAE,CAAC;IAClD,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAE,CAAC;IAC5B,MAAM,QAAQ,GAAG,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;IACrC,OAAO,GAAG,GAAG,QAAQ,CAAC;AACxB,CAAC,CAAC","sourcesContent":["import { createCache } from '@yuants/cache';\nimport { IOrder } from '@yuants/data-order';\nimport { decodePath } from '@yuants/utils';\nimport { getAllMids, getPerpetualsMetaData, getSpotMetaData } from '../api/public-api';\n\nconst enum InstrumentType {\n PERPETUAL = 'PERPETUAL',\n SPOT = 'SPOT',\n}\n\ntype AssetInfo = { assetId: number; szDecimals: number; instType: InstrumentType; baseCurrency: string };\n\nexport const parseProductPath = (product_id: string): { instType: InstrumentType; baseCurrency: string } => {\n const [exchange, instType, symbol] = decodePath(product_id);\n if (exchange !== 'HYPERLIQUID' || !instType || !symbol) {\n throw new Error(`Invalid product_id: ${product_id}`);\n }\n if (instType !== InstrumentType.PERPETUAL && instType !== InstrumentType.SPOT) {\n throw new Error(`Unsupported instrument type: ${instType}`);\n }\n const baseCurrency = symbol.split('-')[0];\n return { instType, baseCurrency };\n};\n\nconst CACHE_TTL = 60_000;\nconst MID_TTL = 5_000;\n\n// Create caches using createCache utility\nconst perpMetaCache = createCache<Map<string, { assetId: number; szDecimals: number }>>(\n async () => {\n console.info(`[Hyperliquid] Refreshing perpetual metadata cache`);\n const meta = await getPerpetualsMetaData();\n const map = new Map<string, { assetId: number; szDecimals: number }>();\n meta.universe.forEach((token, index) =>\n map.set(token.name, { assetId: index, szDecimals: token.szDecimals }),\n );\n return map;\n },\n { expire: CACHE_TTL },\n);\n\nconst spotMetaCache = createCache<Map<string, { assetId: number; szDecimals: number }>>(\n async () => {\n console.info(`[Hyperliquid] Refreshing spot metadata cache`);\n const meta = await getSpotMetaData();\n const map = new Map<string, { assetId: number; szDecimals: number }>();\n meta.tokens.forEach((token) =>\n map.set(token.name, { assetId: token.index, szDecimals: token.szDecimals }),\n );\n return map;\n },\n { expire: CACHE_TTL },\n);\n\nconst midPriceCache = createCache<Map<string, number>>(\n async () => {\n console.info(`[Hyperliquid] Refreshing mid price cache`);\n const mids = await getAllMids();\n const map = new Map<string, number>();\n for (const [coin, price] of Object.entries(mids ?? {})) {\n const value = Number(price);\n if (Number.isFinite(value)) {\n map.set(coin, value);\n }\n }\n return map;\n },\n { expire: MID_TTL },\n);\n\nexport const resolveAssetInfo = async (product_id: string): Promise<AssetInfo> => {\n const { instType, baseCurrency } = parseProductPath(product_id);\n if (instType === InstrumentType.PERPETUAL) {\n const map = (await perpMetaCache.query('perp'))!;\n const info = map.get(baseCurrency)!;\n return { ...info, instType: InstrumentType.PERPETUAL, baseCurrency };\n }\n if (instType === InstrumentType.SPOT) {\n const map = (await spotMetaCache.query('spot'))!;\n const info = map.get(baseCurrency)!;\n return { ...info, instType: InstrumentType.SPOT, baseCurrency };\n }\n throw new Error(`Unsupported instrument type: ${instType}`);\n};\n\nexport const roundPrice = (price: number, instType: 'PERPETUAL' | 'SPOT', szDecimals: number): string => {\n const MAX_DECIMALS = instType === 'PERPETUAL' ? 6 : 8;\n const maxDecimalPlaces = Math.max(0, MAX_DECIMALS - szDecimals);\n if (!Number.isFinite(price)) {\n throw new Error(`Invalid price: ${price}`);\n }\n\n // Handle significant figures (max 5)\n const priceStr = price.toString();\n const significantFigures = priceStr.replace(/^0+\\.?0*/, '').replace(/\\./g, '').length;\n\n let roundedPrice = price;\n if (significantFigures > 5) {\n // Logic to round to 5 sig figs\n // This is complex to do perfectly with just numbers, but let's try to be safe\n const magnitude = Math.floor(Math.log10(Math.abs(price)));\n // We want 5 sig figs.\n // e.g. 123456 -> 123460 (mag 5, round to 10^(5-4)=10^1)\n // e.g. 0.00123456 -> 0.0012346 (mag -3, round to 10^(-3-4)=10^-7)\n const factor = Math.pow(10, magnitude - 4);\n roundedPrice = Math.round(price / factor) * factor;\n }\n\n // Now format to maxDecimalPlaces without scientific notation\n // Use toFixed which returns fixed point notation\n let s = roundedPrice.toFixed(maxDecimalPlaces);\n // Remove trailing zeros and decimal point if integer\n if (s.includes('.')) {\n s = s.replace(/\\.?0+$/, '');\n }\n return s;\n};\n\nconst resolvePrice = async (\n order: IOrder,\n instType: 'PERPETUAL' | 'SPOT',\n szDecimals: number,\n baseCurrency: string,\n) => {\n if (order.order_type === 'MARKET') {\n const mid = await getMidPriceWithSlippage(\n baseCurrency,\n order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT',\n );\n return roundPrice(mid, instType, szDecimals);\n }\n if (!order.price) {\n throw new Error('price is required for non-market orders');\n }\n return roundPrice(+order.price, instType, szDecimals);\n};\n\nexport const buildOrderPayload = async (order: IOrder) => {\n const assetInfo = await resolveAssetInfo(order.product_id);\n const isBuy = order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT';\n const reduceOnly = order.order_direction === 'CLOSE_LONG' || order.order_direction === 'CLOSE_SHORT';\n const price = await resolvePrice(order, assetInfo.instType, assetInfo.szDecimals, assetInfo.baseCurrency);\n const tif = order.order_type === 'MARKET' ? 'Ioc' : order.order_type === 'MAKER' ? 'Alo' : 'Gtc';\n return {\n assetInfo,\n orderParams: {\n a: assetInfo.assetId,\n b: isBuy,\n p: `${price}`,\n s: `${order.volume}`,\n r: reduceOnly,\n t: { limit: { tif } },\n },\n };\n};\n\nexport const getMidPriceWithSlippage = async (coin: string, isBuy: boolean) => {\n const mids = (await midPriceCache.query('mids'))!;\n const mid = mids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,KAAK,CAAC,MAAM,EAAE;YACpB,CAAC,EAAE,UAAU;YACb,CAAC,EAAE,EAAE,KAAK,EAAE,EAAE,GAAG,EAAE,EAAE;SACtB;KACF,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,uBAAuB,GAAG,KAAK,EAAE,IAAY,EAAE,KAAc,EAAE,EAAE;IAC5E,MAAM,IAAI,GAAG,CAAC,MAAM,aAAa,CAAC,KAAK,CAAC,MAAM,CAAC,CAAE,CAAC;IAClD,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAE,CAAC;IAC5B,MAAM,QAAQ,GAAG,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;IACrC,OAAO,GAAG,GAAG,QAAQ,CAAC;AACxB,CAAC,CAAC","sourcesContent":["import { createCache } from '@yuants/cache';\nimport { IOrder } from '@yuants/data-order';\nimport { decodePath } from '@yuants/utils';\nimport { getAllMids, getPerpetualsMetaData, getSpotMetaData } from '../api/public-api';\n\nconst enum InstrumentType {\n PERPETUAL = 'PERPETUAL',\n SPOT = 'SPOT',\n}\n\ntype AssetInfo = { assetId: number; szDecimals: number; instType: InstrumentType; baseCurrency: string };\n\nexport const parseProductPath = (product_id: string): { instType: InstrumentType; baseCurrency: string } => {\n const [exchange, instType, symbol] = decodePath(product_id);\n if (exchange !== 'HYPERLIQUID' || !instType || !symbol) {\n throw new Error(`Invalid product_id: ${product_id}`);\n }\n if (instType !== InstrumentType.PERPETUAL && instType !== InstrumentType.SPOT) {\n throw new Error(`Unsupported instrument type: ${instType}`);\n }\n const baseCurrency = symbol.split('-')[0];\n return { instType, baseCurrency };\n};\n\nconst CACHE_TTL = 60_000;\nconst MID_TTL = 5_000;\n\n// Create caches using createCache utility\nconst perpMetaCache = createCache<Map<string, { assetId: number; szDecimals: number }>>(\n async () => {\n console.info(`[Hyperliquid] Refreshing perpetual metadata cache`);\n const meta = await getPerpetualsMetaData();\n const map = new Map<string, { assetId: number; szDecimals: number }>();\n meta.universe.forEach((token, index) =>\n map.set(token.name, { assetId: index, szDecimals: token.szDecimals }),\n );\n return map;\n },\n { expire: CACHE_TTL },\n);\n\nconst spotMetaCache = createCache<Map<string, { assetId: number; szDecimals: number }>>(\n async () => {\n console.info(`[Hyperliquid] Refreshing spot metadata cache`);\n const meta = await getSpotMetaData();\n const map = new Map<string, { assetId: number; szDecimals: number }>();\n meta.tokens.forEach((token) =>\n map.set(token.name, { assetId: token.index, szDecimals: token.szDecimals }),\n );\n return map;\n },\n { expire: CACHE_TTL },\n);\n\nconst midPriceCache = createCache<Map<string, number>>(\n async () => {\n console.info(`[Hyperliquid] Refreshing mid price cache`);\n const mids = await getAllMids();\n const map = new Map<string, number>();\n for (const [coin, price] of Object.entries(mids ?? {})) {\n const value = Number(price);\n if (Number.isFinite(value)) {\n map.set(coin, value);\n }\n }\n return map;\n },\n { expire: MID_TTL },\n);\n\nexport const resolveAssetInfo = async (product_id: string): Promise<AssetInfo> => {\n const { instType, baseCurrency } = parseProductPath(product_id);\n if (instType === InstrumentType.PERPETUAL) {\n const map = (await perpMetaCache.query('perp'))!;\n const info = map.get(baseCurrency)!;\n return { ...info, instType: InstrumentType.PERPETUAL, baseCurrency };\n }\n if (instType === InstrumentType.SPOT) {\n const map = (await spotMetaCache.query('spot'))!;\n const info = map.get(baseCurrency)!;\n return { ...info, instType: InstrumentType.SPOT, baseCurrency };\n }\n throw new Error(`Unsupported instrument type: ${instType}`);\n};\n\nexport const roundPrice = (price: number, instType: 'PERPETUAL' | 'SPOT', szDecimals: number): string => {\n const MAX_DECIMALS = instType === 'PERPETUAL' ? 6 : 8;\n const maxDecimalPlaces = Math.max(0, MAX_DECIMALS - szDecimals);\n if (!Number.isFinite(price)) {\n throw new Error(`Invalid price: ${price}`);\n }\n\n // Handle significant figures (max 5)\n const priceStr = price.toString();\n const significantFigures = priceStr.replace(/^0+\\.?0*/, '').replace(/\\./g, '').length;\n\n let roundedPrice = price;\n if (significantFigures > 5) {\n // Logic to round to 5 sig figs\n // This is complex to do perfectly with just numbers, but let's try to be safe\n const magnitude = Math.floor(Math.log10(Math.abs(price)));\n // We want 5 sig figs.\n // e.g. 123456 -> 123460 (mag 5, round to 10^(5-4)=10^1)\n // e.g. 0.00123456 -> 0.0012346 (mag -3, round to 10^(-3-4)=10^-7)\n const factor = Math.pow(10, magnitude - 4);\n roundedPrice = Math.round(price / factor) * factor;\n }\n\n // Now format to maxDecimalPlaces without scientific notation\n // Use toFixed which returns fixed point notation\n let s = roundedPrice.toFixed(maxDecimalPlaces);\n // Remove trailing zeros and decimal point if integer\n if (s.includes('.')) {\n s = s.replace(/\\.?0+$/, '');\n }\n return s;\n};\n\nconst resolvePrice = async (\n order: IOrder,\n instType: 'PERPETUAL' | 'SPOT',\n szDecimals: number,\n baseCurrency: string,\n) => {\n if (order.order_type === 'MARKET') {\n const mid = await getMidPriceWithSlippage(\n baseCurrency,\n order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT',\n );\n return roundPrice(mid, instType, szDecimals);\n }\n if (!order.price) {\n throw new Error('price is required for non-market orders');\n }\n return roundPrice(+order.price, instType, szDecimals);\n};\n\nexport const buildOrderPayload = async (order: IOrder) => {\n const assetInfo = await resolveAssetInfo(order.product_id);\n const isBuy = order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT';\n const reduceOnly = order.order_direction === 'CLOSE_LONG' || order.order_direction === 'CLOSE_SHORT';\n const price = await resolvePrice(order, assetInfo.instType, assetInfo.szDecimals, assetInfo.baseCurrency);\n const tif = order.order_type === 'MARKET' ? 'Ioc' : order.order_type === 'MAKER' ? 'Alo' : 'Gtc';\n return {\n assetInfo,\n orderParams: {\n a: assetInfo.assetId,\n b: isBuy,\n p: `${price}`,\n s: `${order.volume}`,\n r: reduceOnly,\n t: { limit: { tif } },\n },\n };\n};\n\nexport const getMidPriceWithSlippage = async (coin: string, isBuy: boolean) => {\n const mids = (await midPriceCache.query('mids'))!;\n const mid = mids.get(coin)!;\n const slippage = isBuy ? 1.05 : 0.95;\n return mid * slippage;\n};\n"]}
@@ -1,4 +1,4 @@
1
- declare type HttpMethod = 'GET' | 'POST';
1
+ type HttpMethod = 'GET' | 'POST';
2
2
  export declare const request: <T = any>(method: HttpMethod, path: string, params?: any) => Promise<T>;
3
3
  export declare const requestWithFlowControl: <T = any>(method: HttpMethod, path: string, flowControl: {
4
4
  period: number;
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/api/client.ts"],"names":[],"mappings":"AAGA,aAAK,UAAU,GAAG,KAAK,GAAG,MAAM,CAAC;AA8EjC,eAAO,MAAM,OAAO,oBAAqB,UAAU,QAAQ,MAAM,WAAW,GAAG,eAClC,CAAC;AAE9C,eAAO,MAAM,sBAAsB,oBACzB,UAAU,QACZ,MAAM,eACC;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,WACrC,GAAG,eAYb,CAAC"}
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/api/client.ts"],"names":[],"mappings":"AAIA,KAAK,UAAU,GAAG,KAAK,GAAG,MAAM,CAAC;AA8HjC,eAAO,MAAM,OAAO,GAAI,CAAC,GAAG,GAAG,EAAE,QAAQ,UAAU,EAAE,MAAM,MAAM,EAAE,SAAS,GAAG,KAC5C,OAAO,CAAC,CAAC,CAAC,CAAC;AAE9C,eAAO,MAAM,sBAAsB,GAAU,CAAC,GAAG,GAAG,EAClD,QAAQ,UAAU,EAClB,MAAM,MAAM,EACZ,aAAa;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,EAC9C,SAAS,GAAG,eAYb,CAAC"}
package/lib/api/client.js CHANGED
@@ -3,7 +3,18 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.requestWithFlowControl = exports.request = void 0;
4
4
  const utils_1 = require("@yuants/utils");
5
5
  const rxjs_1 = require("rxjs");
6
+ const rate_limit_1 = require("./rate-limit");
6
7
  const BASE_URL = 'https://api.hyperliquid.xyz';
8
+ const getRequestKey = (ctx) => {
9
+ var _a, _b;
10
+ if (ctx.kind === 'info')
11
+ return `info:${(_a = ctx.infoType) !== null && _a !== void 0 ? _a : 'unknown'}`;
12
+ if (ctx.kind === 'exchange')
13
+ return `exchange:${(_b = ctx.exchangeActionType) !== null && _b !== void 0 ? _b : 'unknown'}`;
14
+ if (ctx.kind === 'explorer')
15
+ return `explorer:${ctx.path}`;
16
+ return `other:${ctx.path}`;
17
+ };
7
18
  const buildUrl = (path, method, params) => {
8
19
  const url = new URL(BASE_URL);
9
20
  url.pathname = path;
@@ -20,17 +31,40 @@ const callApi = async (method, path, params) => {
20
31
  const body = method === 'GET' ? '' : JSON.stringify(params !== null && params !== void 0 ? params : {});
21
32
  const headers = { 'Content-Type': 'application/json' };
22
33
  console.info((0, utils_1.formatTime)(Date.now()), method, url.href, body);
34
+ const requestContext = (0, rate_limit_1.getRestRequestContext)(method, path, params);
35
+ const requestKey = getRequestKey(requestContext);
36
+ const { estimatedExtraWeight } = (0, rate_limit_1.beforeRestRequest)({ method, url: url.href, path, kind: requestContext.kind, infoType: requestContext.infoType, requestKey }, requestContext);
23
37
  const res = await fetch(url.href, {
24
38
  method,
25
39
  headers,
26
40
  body: method === 'GET' ? undefined : body || undefined,
27
41
  });
28
42
  const retStr = await res.text();
43
+ if (res.status === 429) {
44
+ console.info((0, utils_1.formatTime)(Date.now()), 'HyperliquidResponse', method, url.href, `status=${res.status}`, retStr);
45
+ throw (0, utils_1.newError)('HYPERLIQUID_HTTP_429', {
46
+ status: res.status,
47
+ requestKey,
48
+ method,
49
+ path,
50
+ url: url.href,
51
+ response: retStr,
52
+ });
53
+ }
29
54
  try {
30
55
  if (process.env.LOG_LEVEL === 'DEBUG') {
31
56
  console.debug((0, utils_1.formatTime)(Date.now()), 'HyperliquidResponse', path, JSON.stringify(params), retStr);
32
57
  }
33
- return JSON.parse(retStr);
58
+ const response = JSON.parse(retStr);
59
+ await (0, rate_limit_1.afterRestResponse)({
60
+ method,
61
+ url: url.href,
62
+ path,
63
+ kind: requestContext.kind,
64
+ infoType: requestContext.infoType,
65
+ requestKey,
66
+ }, requestContext, response, estimatedExtraWeight);
67
+ return response;
34
68
  }
35
69
  catch (err) {
36
70
  console.error((0, utils_1.formatTime)(Date.now()), 'HyperliquidRequestFailed', path, JSON.stringify(params), retStr, err);
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/api/client.ts"],"names":[],"mappings":";;;AAAA,yCAAiD;AACjD,+BAA8G;AAI9G,MAAM,QAAQ,GAAG,6BAA6B,CAAC;AAE/C,MAAM,QAAQ,GAAG,CAAC,IAAY,EAAE,MAAkB,EAAE,MAAY,EAAE,EAAE;IAClE,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC9B,GAAG,CAAC,QAAQ,GAAG,IAAI,CAAC;IACpB,IAAI,MAAM,KAAK,KAAK,IAAI,MAAM,EAAE;QAC9B,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC;QAC9E,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,OAAO,EAAE;YAClC,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,GAAG,KAAK,CAAC,CAAC;SACvC;KACF;IACD,OAAO,GAAG,CAAC;AACb,CAAC,CAAC;AAEF,MAAM,OAAO,GAAG,KAAK,EAAE,MAAkB,EAAE,IAAY,EAAE,MAAY,EAAE,EAAE;IACvE,MAAM,GAAG,GAAG,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;IAC3C,MA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AC;AADjC,QAAA,OAAO,WAC0B;AAEvC,MAAM,sBAAsB,GAAG,KAAK,EACzC,MAAkB,EAClB,IAAY,EACZ,WAA8C,EAC9C,MAAY,EACZ,EAAE;;IACF,MAAM,UAAU,GAAG,gBAAgB,CAAC,IAAI,EAAE,WAAW,CAAC,MAAM,EAAE,WAAW,CAAC,KAAK,CAAC,CAAC;IACjF,MAAM,QAAQ,GAAG,IAAA,YAAI,GAAE,CAAC;IACxB,MAAM,IAAI,GAAG,UAAU,CAAC,eAAe,CAAC,IAAI,CAC1C,IAAA,aAAM,EAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,KAAK,QAAQ,CAAC,EAC5C,IAAA,eAAQ,EAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,IAAA,iBAAU,EAAC,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAA,SAAE,EAAC,IAAI,CAAC,CAAC,CAAC,EAC1E,IAAA,cAAO,EAAC,KAAM,CAAC,EACf,IAAA,kBAAW,EAAC,CAAC,CAAC,CACf,CAAC;IACF,UAAU,CAAC,YAAY,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC;IACjE,OAAO,CAAC,MAAA,CAAC,MAAM,IAAA,qBAAc,EAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,mCAAI,IAAI,CAAM,CAAC;AAC9D,CAAC,CAAC;AAhBW,QAAA,sBAAsB,0BAgBjC","sourcesContent":["import { UUID, formatTime } from '@yuants/utils';\nimport { Subject, filter, firstValueFrom, mergeMap, of, shareReplay, throwError, timeout, timer } from 'rxjs';\n\ntype HttpMethod = 'GET' | 'POST';\n\nconst BASE_URL = 'https://api.hyperliquid.xyz';\n\nconst buildUrl = (path: string, method: HttpMethod, params?: any) => {\n const url = new URL(BASE_URL);\n url.pathname = path;\n if (method === 'GET' && params) {\n const entries = Object.entries(params).sort(([a], [b]) => a.localeCompare(b));\n for (const [key, value] of entries) {\n url.searchParams.set(key, '' + value);\n }\n }\n return url;\n};\n\nconst callApi = async (method: HttpMethod, path: string, params?: any) => {\n const url = buildUrl(path, method, params);\n const body = method === 'GET' ? '' : JSON.stringify(params ?? {});\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n console.info(formatTime(Date.now()), method, url.href, body);\n const res = await fetch(url.href, {\n method,\n headers,\n body: method === 'GET' ? undefined : body || undefined,\n });\n const retStr = await res.text();\n try {\n if (process.env.LOG_LEVEL === 'DEBUG') {\n console.debug(formatTime(Date.now()), 'HyperliquidResponse', path, JSON.stringify(params), retStr);\n }\n return JSON.parse(retStr);\n } catch (err) {\n console.error(\n formatTime(Date.now()),\n 'HyperliquidRequestFailed',\n path,\n JSON.stringify(params),\n retStr,\n err,\n );\n throw err;\n }\n};\n\ntype FlowController = {\n requestQueue: Array<{ trace_id: string; method: HttpMethod; path: string; params?: any }>;\n responseChannel: Subject<{ trace_id: string; response?: any; error?: Error }>;\n};\n\nconst controllers = new Map<string, FlowController>();\n\nconst ensureController = (path: string, period: number, limit: number) => {\n if (controllers.has(path)) {\n return controllers.get(path)!;\n }\n const controller: FlowController = {\n requestQueue: [],\n responseChannel: new Subject(),\n };\n timer(0, period)\n .pipe(\n filter(() => controller.requestQueue.length > 0),\n mergeMap(() => controller.requestQueue.splice(0, limit)),\n mergeMap(async (request) => {\n try {\n const response = await callApi(request.method, request.path, request.params);\n return { trace_id: request.trace_id, response };\n } catch (error) {\n return { trace_id: request.trace_id, error: error as Error };\n }\n }),\n )\n .subscribe(controller.responseChannel);\n controllers.set(path, controller);\n return controller;\n};\n\nexport const request = <T = any>(method: HttpMethod, path: string, params?: any) =>\n callApi(method, path, params) as Promise<T>;\n\nexport const requestWithFlowControl = async <T = any>(\n method: HttpMethod,\n path: string,\n flowControl: { period: number; limit: number },\n params?: any,\n) => {\n const controller = ensureController(path, flowControl.period, flowControl.limit);\n const trace_id = UUID();\n const res$ = controller.responseChannel.pipe(\n filter((resp) => resp.trace_id === trace_id),\n mergeMap((resp) => (resp.error ? throwError(() => resp.error) : of(resp))),\n timeout(30_000),\n shareReplay(1),\n );\n controller.requestQueue.push({ trace_id, method, path, params });\n return ((await firstValueFrom(res$)).response ?? null) as T;\n};\n"]}
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/api/client.ts"],"names":[],"mappings":";;;AAAA,yCAA2D;AAC3D,+BAA8G;AAC9G,6CAA2F;AAI3F,MAAM,QAAQ,GAAG,6BAA6B,CAAC;AAE/C,MAAM,aAAa,GAAG,CAAC,GAA6C,EAAE,EAAE;;IACtE,IAAI,GAAG,CAAC,IAAI,KAAK,MAAM;QAAE,OAAO,QAAQ,MAAA,GAAG,CAAC,QAAQ,mCAAI,SAAS,EAAE,CAAC;IACpE,IAAI,GAAG,CAAC,IAAI,KAAK,UAAU;QAAE,OAAO,YAAY,MAAA,GAAG,CAAC,kBAAkB,mCAAI,SAAS,EAAE,CAAC;IACtF,IAAI,GAAG,CAAC,IAAI,KAAK,UAAU;QAAE,OAAO,YAAY,GAAG,CAAC,IAAI,EAAE,CAAC;IAC3D,OAAO,SAAS,GAAG,CAAC,IAAI,EAAE,CAAC;AAC7B,CAAC,CAAC;AAEF,MAAM,QAAQ,GAAG,CAAC,IAAY,EAAE,MAAkB,EAAE,MAAY,EAAE,EAAE;IAClE,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC9B,GAAG,CAAC,QAAQ,GAAG,IAAI,CAAC;IACpB,IAAI,MAAM,KAAK,KAAK,IAAI,MAAM,EAAE,CAAC;QAC/B,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,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,CAAC,CAAC,CAAC,QAAQ,mCAAI,IAAI,CAAM,CAAC;AAC9D,CAAC,CAAC;AAhBW,QAAA,sBAAsB,0BAgBjC","sourcesContent":["import { UUID, formatTime, newError } from '@yuants/utils';\nimport { Subject, filter, firstValueFrom, mergeMap, of, shareReplay, throwError, timeout, timer } from 'rxjs';\nimport { afterRestResponse, beforeRestRequest, getRestRequestContext } from './rate-limit';\n\ntype HttpMethod = 'GET' | 'POST';\n\nconst BASE_URL = 'https://api.hyperliquid.xyz';\n\nconst getRequestKey = (ctx: ReturnType<typeof getRestRequestContext>) => {\n if (ctx.kind === 'info') return `info:${ctx.infoType ?? 'unknown'}`;\n if (ctx.kind === 'exchange') return `exchange:${ctx.exchangeActionType ?? 'unknown'}`;\n if (ctx.kind === 'explorer') return `explorer:${ctx.path}`;\n return `other:${ctx.path}`;\n};\n\nconst buildUrl = (path: string, method: HttpMethod, params?: any) => {\n const url = new URL(BASE_URL);\n url.pathname = path;\n if (method === 'GET' && params) {\n const entries = Object.entries(params).sort(([a], [b]) => a.localeCompare(b));\n for (const [key, value] of entries) {\n url.searchParams.set(key, '' + value);\n }\n }\n return url;\n};\n\nconst callApi = async (method: HttpMethod, path: string, params?: any) => {\n const url = buildUrl(path, method, params);\n const body = method === 'GET' ? '' : JSON.stringify(params ?? {});\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n console.info(formatTime(Date.now()), method, url.href, body);\n\n const requestContext = getRestRequestContext(method, path, params);\n const requestKey = getRequestKey(requestContext);\n\n const { estimatedExtraWeight } = beforeRestRequest(\n { method, url: url.href, path, kind: requestContext.kind, infoType: requestContext.infoType, requestKey },\n requestContext,\n );\n\n const res = await fetch(url.href, {\n method,\n headers,\n body: method === 'GET' ? undefined : body || undefined,\n });\n const retStr = await res.text();\n if (res.status === 429) {\n console.info(\n formatTime(Date.now()),\n 'HyperliquidResponse',\n method,\n url.href,\n `status=${res.status}`,\n retStr,\n );\n throw newError('HYPERLIQUID_HTTP_429', {\n status: res.status,\n requestKey,\n method,\n path,\n url: url.href,\n response: retStr,\n });\n }\n try {\n if (process.env.LOG_LEVEL === 'DEBUG') {\n console.debug(formatTime(Date.now()), 'HyperliquidResponse', path, JSON.stringify(params), retStr);\n }\n const response = JSON.parse(retStr);\n await afterRestResponse(\n {\n method,\n url: url.href,\n path,\n kind: requestContext.kind,\n infoType: requestContext.infoType,\n requestKey,\n },\n requestContext,\n response,\n estimatedExtraWeight,\n );\n return response;\n } catch (err) {\n console.error(\n formatTime(Date.now()),\n 'HyperliquidRequestFailed',\n path,\n JSON.stringify(params),\n retStr,\n err,\n );\n throw err;\n }\n};\n\ntype FlowController = {\n requestQueue: Array<{ trace_id: string; method: HttpMethod; path: string; params?: any }>;\n responseChannel: Subject<{ trace_id: string; response?: any; error?: Error }>;\n};\n\nconst controllers = new Map<string, FlowController>();\n\nconst ensureController = (path: string, period: number, limit: number) => {\n if (controllers.has(path)) {\n return controllers.get(path)!;\n }\n const controller: FlowController = {\n requestQueue: [],\n responseChannel: new Subject(),\n };\n timer(0, period)\n .pipe(\n filter(() => controller.requestQueue.length > 0),\n mergeMap(() => controller.requestQueue.splice(0, limit)),\n mergeMap(async (request) => {\n try {\n const response = await callApi(request.method, request.path, request.params);\n return { trace_id: request.trace_id, response };\n } catch (error) {\n return { trace_id: request.trace_id, error: error as Error };\n }\n }),\n )\n .subscribe(controller.responseChannel);\n controllers.set(path, controller);\n return controller;\n};\n\nexport const request = <T = any>(method: HttpMethod, path: string, params?: any) =>\n callApi(method, path, params) as Promise<T>;\n\nexport const requestWithFlowControl = async <T = any>(\n method: HttpMethod,\n path: string,\n flowControl: { period: number; limit: number },\n params?: any,\n) => {\n const controller = ensureController(path, flowControl.period, flowControl.limit);\n const trace_id = UUID();\n const res$ = controller.responseChannel.pipe(\n filter((resp) => resp.trace_id === trace_id),\n mergeMap((resp) => (resp.error ? throwError(() => resp.error) : of(resp))),\n timeout(30_000),\n shareReplay(1),\n );\n controller.requestQueue.push({ trace_id, method, path, params });\n return ((await firstValueFrom(res$)).response ?? null) as T;\n};\n"]}
@@ -2,7 +2,7 @@ import { ICredential } from './types';
2
2
  /**
3
3
  * Order payload for placing orders on Hyperliquid
4
4
  */
5
- declare type OrderPayload = {
5
+ type OrderPayload = {
6
6
  /** Asset index (absolute) */
7
7
  a: number;
8
8
  /** Buy flag (true for buy, false for sell) */
@@ -35,12 +35,67 @@ declare type OrderPayload = {
35
35
  /**
36
36
  * Cancel order payload
37
37
  */
38
- declare type CancelPayload = {
38
+ type CancelPayload = {
39
39
  /** Asset index (absolute) */
40
40
  a: number;
41
41
  /** Order ID */
42
42
  o: number;
43
43
  };
44
+ type OrderAction = {
45
+ type: 'order';
46
+ orders: OrderPayload[];
47
+ grouping: 'na';
48
+ builder?: {
49
+ b: string;
50
+ f: number;
51
+ };
52
+ };
53
+ type CancelAction = {
54
+ type: 'cancel';
55
+ cancels: CancelPayload[];
56
+ };
57
+ type ModifyAction = {
58
+ type: 'modify';
59
+ oid: number | string;
60
+ order: OrderPayload;
61
+ };
62
+ type ExchangeAction = OrderAction | CancelAction | ModifyAction;
63
+ type L1Signature = {
64
+ r: string;
65
+ s: string;
66
+ v: number;
67
+ };
68
+ export declare const buildPlaceOrderAction: (params: {
69
+ orders: OrderPayload[];
70
+ builder?: {
71
+ b: string;
72
+ f: number;
73
+ };
74
+ }) => OrderAction;
75
+ export declare const buildCancelOrderAction: (params: {
76
+ cancels: CancelPayload[];
77
+ }) => {
78
+ type: "cancel";
79
+ cancels: CancelPayload[];
80
+ };
81
+ export declare const buildModifyOrderAction: (params: {
82
+ oid: number | string;
83
+ order: OrderPayload;
84
+ }) => {
85
+ type: "modify";
86
+ oid: string | number;
87
+ order: OrderPayload;
88
+ };
89
+ export declare const createSignedExchangeRequestBody: (credential: ICredential, action: ExchangeAction, options?: {
90
+ nonce?: number;
91
+ vaultAddress?: string;
92
+ expiresAfter?: number;
93
+ isMainnet?: boolean;
94
+ }) => Promise<{
95
+ action: ExchangeAction;
96
+ nonce: number;
97
+ signature: L1Signature;
98
+ }>;
44
99
  /**
45
100
  * Place orders on Hyperliquid exchange
46
101
  * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#place-an-order
@@ -84,6 +139,15 @@ export declare const modifyOrder: (credential: ICredential, params: {
84
139
  vaultAddress?: string;
85
140
  expiresAfter?: number;
86
141
  }) => Promise<any>;
142
+ export declare const buildUserFillsRequestBody: (credential: ICredential, params?: {
143
+ startTime?: number;
144
+ endTime?: number;
145
+ }) => {
146
+ type: "userFills";
147
+ user: string;
148
+ startTime?: number;
149
+ endTime?: number;
150
+ };
87
151
  /**
88
152
  * Get user's fill history (trade history) from Hyperliquid
89
153
  * API Endpoint: POST /info (type: userFills)
@@ -115,7 +179,7 @@ export declare const getUserFills: (credential: ICredential, params?: {
115
179
  positionAction: string;
116
180
  asset: number;
117
181
  tid: string;
118
- crossChain: any;
182
+ crossChain: unknown;
119
183
  }[];
120
184
  }>;
121
185
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"private-api.d.ts","sourceRoot":"","sources":["../../src/api/private-api.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAEtC;;GAEG;AACH,aAAK,YAAY,GAAG;IAClB,6BAA6B;IAC7B,CAAC,EAAE,MAAM,CAAC;IACV,8CAA8C;IAC9C,CAAC,EAAE,OAAO,CAAC;IACX,yBAAyB;IACzB,CAAC,EAAE,MAAM,CAAC;IACV,kBAAkB;IAClB,CAAC,EAAE,MAAM,CAAC;IACV,uBAAuB;IACvB,CAAC,EAAE,OAAO,CAAC;IACX,+BAA+B;IAC/B,CAAC,EAAE;QACD,8GAA8G;QAC9G,KAAK,CAAC,EAAE;YAAE,GAAG,EAAE,MAAM,CAAA;SAAE,CAAC;QACxB,kCAAkC;QAClC,OAAO,CAAC,EAAE;YACR,8BAA8B;YAC9B,QAAQ,EAAE,OAAO,CAAC;YAClB,2BAA2B;YAC3B,SAAS,EAA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W,EACvB,SAAS;IAAE,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE;WAGxC;QACL,IAAI,EAAE,MAAM,CAAC;QACb,MAAM,EAAE,MAAM,CAAC;QACf,IAAI,EAAE,MAAM,CAAC;QACb,IAAI,EAAE,MAAM,CAAC;QACb,IAAI,EAAE,MAAM,CAAC;QACb,EAAE,EAAE,MAAM,CAAC;QACX,EAAE,EAAE,MAAM,CAAC;QACX,GAAG,EAAE,MAAM,CAAC;QACZ,QAAQ,EAAE,MAAM,CAAC;QACjB,GAAG,EAAE,MAAM,CAAC;QACZ,QAAQ,EAAE,MAAM,CAAC;QACjB,UAAU,EAAE,MAAM,CAAC;QACnB,SAAS,EAAE,MAAM,CAAC;QAClB,GAAG,EAAE,MAAM,CAAC;QACZ,MAAM,EAAE,MAAM,CAAC;QACf,IAAI,EAAE,MAAM,CAAC;QACb,cAAc,EAAE,MAAM,CAAC;QACvB,KAAK,EAAE,MAAM,CAAC;QACd,GAAG,EAAE,MAAM,CAAC;QACZ,UAAU,EAAE,OAAO,CAAC;KACrB,EAAE;EAEN,CAAC"}
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getUserFills = exports.modifyOrder = exports.cancelOrder = exports.placeOrder = void 0;
3
+ exports.getUserFills = exports.buildUserFillsRequestBody = exports.modifyOrder = exports.cancelOrder = exports.placeOrder = exports.createSignedExchangeRequestBody = exports.buildModifyOrderAction = exports.buildCancelOrderAction = exports.buildPlaceOrderAction = void 0;
4
4
  const ethers_1 = require("ethers");
5
5
  const sign_1 = require("./sign");
6
6
  const client_1 = require("./client");
@@ -11,6 +11,31 @@ const getWallet = (credential) => {
11
11
  }
12
12
  return walletCache.get(credential.private_key);
13
13
  };
14
+ const buildPlaceOrderAction = (params) => {
15
+ const action = { type: 'order', orders: params.orders, grouping: 'na' };
16
+ if (!params.builder)
17
+ return action;
18
+ return Object.assign(Object.assign({}, action), { builder: params.builder });
19
+ };
20
+ exports.buildPlaceOrderAction = buildPlaceOrderAction;
21
+ const buildCancelOrderAction = (params) => ({
22
+ type: 'cancel',
23
+ cancels: params.cancels,
24
+ });
25
+ exports.buildCancelOrderAction = buildCancelOrderAction;
26
+ const buildModifyOrderAction = (params) => ({
27
+ type: 'modify',
28
+ oid: params.oid,
29
+ order: params.order,
30
+ });
31
+ exports.buildModifyOrderAction = buildModifyOrderAction;
32
+ const createSignedExchangeRequestBody = async (credential, action, options) => {
33
+ var _a, _b, _c, _d;
34
+ const nonce = (_a = options === null || options === void 0 ? void 0 : options.nonce) !== null && _a !== void 0 ? _a : Date.now();
35
+ const signature = await (0, sign_1.signL1Action)(getWallet(credential), action, (_b = options === null || options === void 0 ? void 0 : options.vaultAddress) !== null && _b !== void 0 ? _b : null, nonce, (_c = options === null || options === void 0 ? void 0 : options.expiresAfter) !== null && _c !== void 0 ? _c : null, (_d = options === null || options === void 0 ? void 0 : options.isMainnet) !== null && _d !== void 0 ? _d : true);
36
+ return { action, nonce, signature };
37
+ };
38
+ exports.createSignedExchangeRequestBody = createSignedExchangeRequestBody;
14
39
  /**
15
40
  * Place orders on Hyperliquid exchange
16
41
  * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#place-an-order
@@ -20,18 +45,12 @@ const getWallet = (credential) => {
20
45
  * @returns Promise resolving to exchange response
21
46
  */
22
47
  const placeOrder = async (credential, params) => {
23
- var _a, _b;
24
- const action = {
25
- type: 'order',
26
- orders: params.orders,
27
- grouping: 'na',
28
- };
29
- if (params.builder) {
30
- action['builder'] = params.builder;
31
- }
32
- const nonce = Date.now();
33
- const signature = await (0, sign_1.signL1Action)(getWallet(credential), action, (_a = params.vaultAddress) !== null && _a !== void 0 ? _a : null, nonce, (_b = params.expiresAfter) !== null && _b !== void 0 ? _b : null, true);
34
- return (0, client_1.request)('POST', 'exchange', { action, nonce, signature });
48
+ const action = (0, exports.buildPlaceOrderAction)(params);
49
+ const requestBody = await (0, exports.createSignedExchangeRequestBody)(credential, action, {
50
+ vaultAddress: params.vaultAddress,
51
+ expiresAfter: params.expiresAfter,
52
+ });
53
+ return (0, client_1.request)('POST', 'exchange', requestBody);
35
54
  };
36
55
  exports.placeOrder = placeOrder;
37
56
  /**
@@ -43,14 +62,12 @@ exports.placeOrder = placeOrder;
43
62
  * @returns Promise resolving to exchange response
44
63
  */
45
64
  const cancelOrder = async (credential, params) => {
46
- var _a, _b;
47
- const action = {
48
- type: 'cancel',
49
- cancels: params.cancels,
50
- };
51
- const nonce = Date.now();
52
- const signature = await (0, sign_1.signL1Action)(getWallet(credential), action, (_a = params.vaultAddress) !== null && _a !== void 0 ? _a : null, nonce, (_b = params.expiresAfter) !== null && _b !== void 0 ? _b : null, true);
53
- return (0, client_1.request)('POST', 'exchange', { action, nonce, signature });
65
+ const action = (0, exports.buildCancelOrderAction)(params);
66
+ const requestBody = await (0, exports.createSignedExchangeRequestBody)(credential, action, {
67
+ vaultAddress: params.vaultAddress,
68
+ expiresAfter: params.expiresAfter,
69
+ });
70
+ return (0, client_1.request)('POST', 'exchange', requestBody);
54
71
  };
55
72
  exports.cancelOrder = cancelOrder;
56
73
  /**
@@ -61,17 +78,28 @@ exports.cancelOrder = cancelOrder;
61
78
  * @returns Promise resolving to exchange response
62
79
  */
63
80
  const modifyOrder = async (credential, params) => {
64
- var _a, _b;
65
- const action = {
66
- type: 'modify',
67
- oid: params.oid,
68
- order: params.order,
69
- };
70
- const nonce = Date.now();
71
- const signature = await (0, sign_1.signL1Action)(getWallet(credential), action, (_a = params.vaultAddress) !== null && _a !== void 0 ? _a : null, nonce, (_b = params.expiresAfter) !== null && _b !== void 0 ? _b : null, true);
72
- return (0, client_1.request)('POST', 'exchange', { action, nonce, signature });
81
+ const action = (0, exports.buildModifyOrderAction)(params);
82
+ const requestBody = await (0, exports.createSignedExchangeRequestBody)(credential, action, {
83
+ vaultAddress: params.vaultAddress,
84
+ expiresAfter: params.expiresAfter,
85
+ });
86
+ return (0, client_1.request)('POST', 'exchange', requestBody);
73
87
  };
74
88
  exports.modifyOrder = modifyOrder;
89
+ const buildUserFillsRequestBody = (credential, params) => {
90
+ const requestBody = {
91
+ type: 'userFills',
92
+ user: credential.address,
93
+ };
94
+ if ((params === null || params === void 0 ? void 0 : params.startTime) != null) {
95
+ requestBody.startTime = params.startTime;
96
+ }
97
+ if ((params === null || params === void 0 ? void 0 : params.endTime) != null) {
98
+ requestBody.endTime = params.endTime;
99
+ }
100
+ return requestBody;
101
+ };
102
+ exports.buildUserFillsRequestBody = buildUserFillsRequestBody;
75
103
  /**
76
104
  * Get user's fill history (trade history) from Hyperliquid
77
105
  * API Endpoint: POST /info (type: userFills)
@@ -80,19 +108,7 @@ exports.modifyOrder = modifyOrder;
80
108
  * @returns Promise resolving to user fill history with detailed trade information
81
109
  */
82
110
  const getUserFills = async (credential, params) => {
83
- const wallet = getWallet(credential);
84
- const address = wallet.address;
85
- const requestBody = {
86
- type: 'userFills',
87
- user: address,
88
- };
89
- if (params === null || params === void 0 ? void 0 : params.startTime) {
90
- requestBody.startTime = params.startTime;
91
- }
92
- if (params === null || params === void 0 ? void 0 : params.endTime) {
93
- requestBody.endTime = params.endTime;
94
- }
95
- return (0, client_1.request)('POST', 'info', requestBody);
111
+ return (0, client_1.request)('POST', 'info', (0, exports.buildUserFillsRequestBody)(credential, params));
96
112
  };
97
113
  exports.getUserFills = getUserFills;
98
114
  //# sourceMappingURL=private-api.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"private-api.js","sourceRoot":"","sources":["../../src/api/private-api.ts"],"names":[],"mappings":";;;AAAA,mCAAgC;AAChC,iCAAsC;AACtC,qCAAmC;AAuDnC,MAAM,WAAW,GAAG,IAAI,GAAG,EAAkB,CAAC;AAE9C,MAAM,SAAS,GAAG,CAAC,UAAuB,EAAE,EAAE;IAC5C,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC,WAAW,CAAC,EAAE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AM,CAAE,SAAS,EAAE;QACrB,WAAW,CAAC,SAAS,GAAG,MAAM,CAAC,SAAS,CAAC;KAC1C;IAED,IAAI,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,OAAO,EAAE;QACnB,WAAW,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;KACtC;IAED,OAAO,IAAA,gBAAO,EAuBX,MAAM,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;AAClC,CAAC,CAAC;AA5CW,QAAA,YAAY,gBA4CvB","sourcesContent":["import { Wallet } from 'ethers';\nimport { signL1Action } from './sign';\nimport { request } from './client';\nimport { ICredential } from './types';\n\n/**\n * Order payload for placing orders on Hyperliquid\n */\ntype OrderPayload = {\n /** Asset index (absolute) */\n a: number;\n /** Buy flag (true for buy, false for sell) */\n b: boolean;\n /** Limit price string */\n p: string;\n /** Size string */\n s: string;\n /** Reduce only flag */\n r: boolean;\n /** Order type configuration */\n t: {\n /** Time in force for limit orders: \"Alo\" (Post-Only), \"Ioc\" (Immediate or Cancel), \"Gtc\" (Good til Cancel) */\n limit?: { tif: string };\n /** Trigger order configuration */\n trigger?: {\n /** Is market trigger price */\n isMarket: boolean;\n /** Trigger price string */\n triggerPx: string;\n /** Take profit/stop loss indicator */\n tpsl: string;\n };\n };\n /** Order fee coefficient */\n c?: number;\n};\n\n/**\n * Cancel order payload\n */\ntype CancelPayload = {\n /** Asset index (absolute) */\n a: number;\n /** Order ID */\n o: number;\n};\n\n/**\n * Modify order payload\n */\ntype ModifyOrderPayload = {\n /** Order ID to modify */\n oid: number | string;\n /** New order parameters */\n order: OrderPayload;\n};\n\nconst walletCache = new Map<string, Wallet>();\n\nconst getWallet = (credential: ICredential) => {\n if (!walletCache.has(credential.private_key)) {\n walletCache.set(credential.private_key, new Wallet(credential.private_key));\n }\n return walletCache.get(credential.private_key)!;\n};\n\n/**\n * Place orders on Hyperliquid exchange\n * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#place-an-order\n * API Endpoint: POST /exchange\n * @param credential - User credential containing private key for signing\n * @param params - Order placement parameters\n * @returns Promise resolving to exchange response\n */\nexport const placeOrder = async (\n credential: ICredential,\n params: {\n orders: OrderPayload[];\n builder?: { b: string; f: number };\n vaultAddress?: string;\n expiresAfter?: number;\n },\n) => {\n const action: Record<string, any> = {\n type: 'order',\n orders: params.orders,\n grouping: 'na',\n };\n if (params.builder) {\n action['builder'] = params.builder;\n }\n const nonce = Date.now();\n const signature = await signL1Action(\n getWallet(credential),\n action,\n params.vaultAddress ?? null,\n nonce,\n params.expiresAfter ?? null,\n true,\n );\n return request('POST', 'exchange', { action, nonce, signature });\n};\n\n/**\n * Cancel orders on Hyperliquid exchange\n * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s\n * API Endpoint: POST /exchange\n * @param credential - User credential containing private key for signing\n * @param params - Order cancellation parameters\n * @returns Promise resolving to exchange response\n */\nexport const cancelOrder = async (\n credential: ICredential,\n params: { cancels: CancelPayload[]; vaultAddress?: string; expiresAfter?: number },\n) => {\n const action: Record<string, any> = {\n type: 'cancel',\n cancels: params.cancels,\n };\n const nonce = Date.now();\n const signature = await signL1Action(\n getWallet(credential),\n action,\n params.vaultAddress ?? null,\n nonce,\n params.expiresAfter ?? null,\n true,\n );\n return request('POST', 'exchange', { action, nonce, signature });\n};\n\n/**\n * Modify an existing order on Hyperliquid exchange\n * API Endpoint: POST /exchange\n * @param credential - User credential containing private key for signing\n * @param params - Order modification parameters\n * @returns Promise resolving to exchange response\n */\nexport const modifyOrder = async (\n credential: ICredential,\n params: {\n oid: number | string;\n order: OrderPayload;\n vaultAddress?: string;\n expiresAfter?: number;\n },\n) => {\n const action: Record<string, any> = {\n type: 'modify',\n oid: params.oid,\n order: params.order,\n };\n const nonce = Date.now();\n const signature = await signL1Action(\n getWallet(credential),\n action,\n params.vaultAddress ?? null,\n nonce,\n params.expiresAfter ?? null,\n true,\n );\n return request('POST', 'exchange', { action, nonce, signature });\n};\n\n/**\n * Get user's fill history (trade history) from Hyperliquid\n * API Endpoint: POST /info (type: userFills)\n * @param credential - User credential containing private key for authentication\n * @param params - Optional time range parameters\n * @returns Promise resolving to user fill history with detailed trade information\n */\nexport const getUserFills = async (\n credential: ICredential,\n params?: { startTime?: number; endTime?: number },\n) => {\n const wallet = getWallet(credential);\n const address = wallet.address;\n\n const requestBody: any = {\n type: 'userFills',\n user: address,\n };\n\n if (params?.startTime) {\n requestBody.startTime = params.startTime;\n }\n\n if (params?.endTime) {\n requestBody.endTime = params.endTime;\n }\n\n return request<{\n fills: {\n time: number;\n feedId: string;\n hash: string;\n coin: string;\n side: string;\n px: string;\n sz: string;\n oid: number;\n startPos: string;\n fee: string;\n feeToken: string;\n closedSize: string;\n closedPnl: string;\n dir: string;\n source: string;\n type: string;\n positionAction: string;\n asset: number;\n tid: string;\n crossChain: any;\n }[];\n }>('POST', 'info', requestBody);\n};\n"]}
1
+ {"version":3,"file":"private-api.js","sourceRoot":"","sources":["../../src/api/private-api.ts"],"names":[],"mappings":";;;AAAA,mCAAgC;AAChC,iCAAsC;AACtC,qCAAmC;AA6EnC,MAAM,WAAW,GAAG,IAAI,GAAG,EAAkB,CAAC;AAE9C,MAAM,SAAS,GAAG,CAAC,UAAuB,EAAE,EAAE;IAC5C,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC,WAAW,CAAC,EAAE,CAAC;QAC7C,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC,WAAW,EAAE,IAAI,eAAM,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC,CAAC;IAC9E,CAAC;IACD,OAAO,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC,WAAW,CAAE,CAAC;AAClD,CAAC,CAAC;AAEK,MAAM,qBAAqB,GAAG,CAAC,MAGrC,EAAE,EAAE;IACH,MAAM,MAAM,GAAgB,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,MA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;AAfW,QAAA,WAAW,eAetB;AAEK,MAAM,yBAAyB,GAAG,CACvC,UAAuB,EACvB,MAAiD,EACjD,EAAE;IACF,MAAM,WAAW,GAA8E;QAC7F,IAAI,EAAE,WAAW;QACjB,IAAI,EAAE,UAAU,CAAC,OAAO;KACzB,CAAC;IAEF,IAAI,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,SAAS,KAAI,IAAI,EAAE,CAAC;QAC9B,WAAW,CAAC,SAAS,GAAG,MAAM,CAAC,SAAS,CAAC;IAC3C,CAAC;IAED,IAAI,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,OAAO,KAAI,IAAI,EAAE,CAAC;QAC5B,WAAW,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;IACvC,CAAC;IAED,OAAO,WAAW,CAAC;AACrB,CAAC,CAAC;AAlBW,QAAA,yBAAyB,6BAkBpC;AAEF;;;;;;GAMG;AACI,MAAM,YAAY,GAAG,KAAK,EAC/B,UAAuB,EACvB,MAAiD,EACjD,EAAE;IACF,OAAO,IAAA,gBAAO,EAuBX,MAAM,EAAE,MAAM,EAAE,IAAA,iCAAyB,EAAC,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC;AACpE,CAAC,CAAC;AA5BW,QAAA,YAAY,gBA4BvB","sourcesContent":["import { Wallet } from 'ethers';\nimport { signL1Action } from './sign';\nimport { request } from './client';\nimport { ICredential } from './types';\n\n/**\n * Order payload for placing orders on Hyperliquid\n */\ntype OrderPayload = {\n /** Asset index (absolute) */\n a: number;\n /** Buy flag (true for buy, false for sell) */\n b: boolean;\n /** Limit price string */\n p: string;\n /** Size string */\n s: string;\n /** Reduce only flag */\n r: boolean;\n /** Order type configuration */\n t: {\n /** Time in force for limit orders: \"Alo\" (Post-Only), \"Ioc\" (Immediate or Cancel), \"Gtc\" (Good til Cancel) */\n limit?: { tif: string };\n /** Trigger order configuration */\n trigger?: {\n /** Is market trigger price */\n isMarket: boolean;\n /** Trigger price string */\n triggerPx: string;\n /** Take profit/stop loss indicator */\n tpsl: string;\n };\n };\n /** Order fee coefficient */\n c?: number;\n};\n\n/**\n * Cancel order payload\n */\ntype CancelPayload = {\n /** Asset index (absolute) */\n a: number;\n /** Order ID */\n o: number;\n};\n\n/**\n * Modify order payload\n */\ntype ModifyOrderPayload = {\n /** Order ID to modify */\n oid: number | string;\n /** New order parameters */\n order: OrderPayload;\n};\n\ntype OrderAction = {\n type: 'order';\n orders: OrderPayload[];\n grouping: 'na';\n builder?: { b: string; f: number };\n};\n\ntype CancelAction = {\n type: 'cancel';\n cancels: CancelPayload[];\n};\n\ntype ModifyAction = {\n type: 'modify';\n oid: number | string;\n order: OrderPayload;\n};\n\ntype ExchangeAction = OrderAction | CancelAction | ModifyAction;\n\ntype L1Signature = { r: string; s: string; v: number };\n\nconst walletCache = new Map<string, Wallet>();\n\nconst getWallet = (credential: ICredential) => {\n if (!walletCache.has(credential.private_key)) {\n walletCache.set(credential.private_key, new Wallet(credential.private_key));\n }\n return walletCache.get(credential.private_key)!;\n};\n\nexport const buildPlaceOrderAction = (params: {\n orders: OrderPayload[];\n builder?: { b: string; f: number };\n}) => {\n const action: OrderAction = { type: 'order', orders: params.orders, grouping: 'na' };\n if (!params.builder) return action;\n return { ...action, builder: params.builder };\n};\n\nexport const buildCancelOrderAction = (params: { cancels: CancelPayload[] }) =>\n ({\n type: 'cancel',\n cancels: params.cancels,\n } satisfies CancelAction);\n\nexport const buildModifyOrderAction = (params: { oid: number | string; order: OrderPayload }) =>\n ({\n type: 'modify',\n oid: params.oid,\n order: params.order,\n } satisfies ModifyAction);\n\nexport const createSignedExchangeRequestBody = async (\n credential: ICredential,\n action: ExchangeAction,\n options?: { nonce?: number; vaultAddress?: string; expiresAfter?: number; isMainnet?: boolean },\n) => {\n const nonce = options?.nonce ?? Date.now();\n const signature: L1Signature = await signL1Action(\n getWallet(credential),\n action,\n options?.vaultAddress ?? null,\n nonce,\n options?.expiresAfter ?? null,\n options?.isMainnet ?? true,\n );\n return { action, nonce, signature };\n};\n\n/**\n * Place orders on Hyperliquid exchange\n * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#place-an-order\n * API Endpoint: POST /exchange\n * @param credential - User credential containing private key for signing\n * @param params - Order placement parameters\n * @returns Promise resolving to exchange response\n */\nexport const placeOrder = async (\n credential: ICredential,\n params: {\n orders: OrderPayload[];\n builder?: { b: string; f: number };\n vaultAddress?: string;\n expiresAfter?: number;\n },\n) => {\n const action = buildPlaceOrderAction(params);\n const requestBody = await createSignedExchangeRequestBody(credential, action, {\n vaultAddress: params.vaultAddress,\n expiresAfter: params.expiresAfter,\n });\n return request('POST', 'exchange', requestBody);\n};\n\n/**\n * Cancel orders on Hyperliquid exchange\n * API Docs: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint#cancel-order-s\n * API Endpoint: POST /exchange\n * @param credential - User credential containing private key for signing\n * @param params - Order cancellation parameters\n * @returns Promise resolving to exchange response\n */\nexport const cancelOrder = async (\n credential: ICredential,\n params: { cancels: CancelPayload[]; vaultAddress?: string; expiresAfter?: number },\n) => {\n const action = buildCancelOrderAction(params);\n const requestBody = await createSignedExchangeRequestBody(credential, action, {\n vaultAddress: params.vaultAddress,\n expiresAfter: params.expiresAfter,\n });\n return request('POST', 'exchange', requestBody);\n};\n\n/**\n * Modify an existing order on Hyperliquid exchange\n * API Endpoint: POST /exchange\n * @param credential - User credential containing private key for signing\n * @param params - Order modification parameters\n * @returns Promise resolving to exchange response\n */\nexport const modifyOrder = async (\n credential: ICredential,\n params: {\n oid: number | string;\n order: OrderPayload;\n vaultAddress?: string;\n expiresAfter?: number;\n },\n) => {\n const action = buildModifyOrderAction(params);\n const requestBody = await createSignedExchangeRequestBody(credential, action, {\n vaultAddress: params.vaultAddress,\n expiresAfter: params.expiresAfter,\n });\n return request('POST', 'exchange', requestBody);\n};\n\nexport const buildUserFillsRequestBody = (\n credential: ICredential,\n params?: { startTime?: number; endTime?: number },\n) => {\n const requestBody: { type: 'userFills'; user: string; startTime?: number; endTime?: number } = {\n type: 'userFills',\n user: credential.address,\n };\n\n if (params?.startTime != null) {\n requestBody.startTime = params.startTime;\n }\n\n if (params?.endTime != null) {\n requestBody.endTime = params.endTime;\n }\n\n return requestBody;\n};\n\n/**\n * Get user's fill history (trade history) from Hyperliquid\n * API Endpoint: POST /info (type: userFills)\n * @param credential - User credential containing private key for authentication\n * @param params - Optional time range parameters\n * @returns Promise resolving to user fill history with detailed trade information\n */\nexport const getUserFills = async (\n credential: ICredential,\n params?: { startTime?: number; endTime?: number },\n) => {\n return request<{\n fills: {\n time: number;\n feedId: string;\n hash: string;\n coin: string;\n side: string;\n px: string;\n sz: string;\n oid: number;\n startPos: string;\n fee: string;\n feeToken: string;\n closedSize: string;\n closedPnl: string;\n dir: string;\n source: string;\n type: string;\n positionAction: string;\n asset: number;\n tid: string;\n crossChain: unknown;\n }[];\n }>('POST', 'info', buildUserFillsRequestBody(credential, params));\n};\n"]}