@yuants/vendor-hyperliquid 0.6.4 → 0.7.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 (109) hide show
  1. package/dist/api/private-api.js +1 -1
  2. package/dist/api/private-api.js.map +1 -1
  3. package/dist/api/sign.js.map +1 -0
  4. package/dist/api/types.js +4 -8
  5. package/dist/api/types.js.map +1 -1
  6. package/dist/index.js +1 -7
  7. package/dist/index.js.map +1 -1
  8. package/dist/services/accounts/perp.js +4 -16
  9. package/dist/services/accounts/perp.js.map +1 -1
  10. package/dist/services/accounts/spot.js +4 -5
  11. package/dist/services/accounts/spot.js.map +1 -1
  12. package/dist/services/exchange.js +79 -0
  13. package/dist/services/exchange.js.map +1 -0
  14. package/dist/services/markets/interest-rate.js +13 -7
  15. package/dist/services/markets/interest-rate.js.map +1 -1
  16. package/dist/services/markets/ohlc.js +11 -7
  17. package/dist/services/markets/ohlc.js.map +1 -1
  18. package/dist/services/markets/product.js +6 -6
  19. package/dist/services/markets/product.js.map +1 -1
  20. package/dist/services/markets/quote.js +4 -4
  21. package/dist/services/markets/quote.js.map +1 -1
  22. package/dist/services/orders/cancelOrder.js +1 -1
  23. package/dist/services/orders/cancelOrder.js.map +1 -1
  24. package/dist/services/orders/listOrders.js +17 -38
  25. package/dist/services/orders/listOrders.js.map +1 -1
  26. package/dist/services/orders/modifyOrder.js +2 -2
  27. package/dist/services/orders/modifyOrder.js.map +1 -1
  28. package/dist/services/orders/submitOrder.js +1 -1
  29. package/dist/services/orders/submitOrder.js.map +1 -1
  30. package/dist/{utils.js → services/utils.js} +13 -6
  31. package/dist/services/utils.js.map +1 -0
  32. package/lib/api/private-api.js +1 -1
  33. package/lib/api/private-api.js.map +1 -1
  34. package/lib/api/sign.d.ts.map +1 -0
  35. package/lib/api/sign.js.map +1 -0
  36. package/lib/api/types.d.ts +3 -4
  37. package/lib/api/types.d.ts.map +1 -1
  38. package/lib/api/types.js +6 -10
  39. package/lib/api/types.js.map +1 -1
  40. package/lib/index.d.ts +1 -6
  41. package/lib/index.d.ts.map +1 -1
  42. package/lib/index.js +1 -7
  43. package/lib/index.js.map +1 -1
  44. package/lib/services/accounts/perp.d.ts +1 -1
  45. package/lib/services/accounts/perp.d.ts.map +1 -1
  46. package/lib/services/accounts/perp.js +6 -18
  47. package/lib/services/accounts/perp.js.map +1 -1
  48. package/lib/services/accounts/spot.d.ts +1 -1
  49. package/lib/services/accounts/spot.d.ts.map +1 -1
  50. package/lib/services/accounts/spot.js +6 -7
  51. package/lib/services/accounts/spot.js.map +1 -1
  52. package/lib/services/exchange.d.ts +2 -0
  53. package/lib/services/exchange.d.ts.map +1 -0
  54. package/lib/services/exchange.js +81 -0
  55. package/lib/services/exchange.js.map +1 -0
  56. package/lib/services/markets/interest-rate.js +13 -7
  57. package/lib/services/markets/interest-rate.js.map +1 -1
  58. package/lib/services/markets/ohlc.js +10 -6
  59. package/lib/services/markets/ohlc.js.map +1 -1
  60. package/lib/services/markets/product.d.ts +2 -1
  61. package/lib/services/markets/product.d.ts.map +1 -1
  62. package/lib/services/markets/product.js +8 -6
  63. package/lib/services/markets/product.js.map +1 -1
  64. package/lib/services/markets/quote.js +4 -4
  65. package/lib/services/markets/quote.js.map +1 -1
  66. package/lib/services/orders/cancelOrder.js +1 -1
  67. package/lib/services/orders/cancelOrder.js.map +1 -1
  68. package/lib/services/orders/listOrders.d.ts +7 -3
  69. package/lib/services/orders/listOrders.d.ts.map +1 -1
  70. package/lib/services/orders/listOrders.js +21 -41
  71. package/lib/services/orders/listOrders.js.map +1 -1
  72. package/lib/services/orders/modifyOrder.d.ts.map +1 -1
  73. package/lib/services/orders/modifyOrder.js +7 -7
  74. package/lib/services/orders/modifyOrder.js.map +1 -1
  75. package/lib/services/orders/submitOrder.js +1 -1
  76. package/lib/services/orders/submitOrder.js.map +1 -1
  77. package/lib/{utils.d.ts → services/utils.d.ts} +4 -0
  78. package/lib/services/utils.d.ts.map +1 -0
  79. package/lib/{utils.js → services/utils.js} +15 -7
  80. package/lib/services/utils.js.map +1 -0
  81. package/package.json +15 -15
  82. package/temp/package-deps.json +37 -38
  83. package/dist/services/account-actions-with-credential.js +0 -36
  84. package/dist/services/account-actions-with-credential.js.map +0 -1
  85. package/dist/services/legacy.js +0 -51
  86. package/dist/services/legacy.js.map +0 -1
  87. package/dist/services/order-actions-with-credential.js +0 -20
  88. package/dist/services/order-actions-with-credential.js.map +0 -1
  89. package/dist/sign.js.map +0 -1
  90. package/dist/utils.js.map +0 -1
  91. package/lib/services/account-actions-with-credential.d.ts +0 -2
  92. package/lib/services/account-actions-with-credential.d.ts.map +0 -1
  93. package/lib/services/account-actions-with-credential.js +0 -38
  94. package/lib/services/account-actions-with-credential.js.map +0 -1
  95. package/lib/services/legacy.d.ts +0 -2
  96. package/lib/services/legacy.d.ts.map +0 -1
  97. package/lib/services/legacy.js +0 -53
  98. package/lib/services/legacy.js.map +0 -1
  99. package/lib/services/order-actions-with-credential.d.ts +0 -2
  100. package/lib/services/order-actions-with-credential.d.ts.map +0 -1
  101. package/lib/services/order-actions-with-credential.js +0 -22
  102. package/lib/services/order-actions-with-credential.js.map +0 -1
  103. package/lib/sign.d.ts.map +0 -1
  104. package/lib/sign.js.map +0 -1
  105. package/lib/utils.d.ts.map +0 -1
  106. package/lib/utils.js.map +0 -1
  107. /package/dist/{sign.js → api/sign.js} +0 -0
  108. /package/lib/{sign.d.ts → api/sign.d.ts} +0 -0
  109. /package/lib/{sign.js → api/sign.js} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"quote.js","sourceRoot":"","sources":["../../../src/services/markets/quote.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,E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eAAe,EAAE,YAAY,CAAC;KAC9C,CAAC,CACH;SACA,SAAS,EAAE,CAAC;CAChB;AAED,QAAQ,CAAC,OAAO,CAAC,cAAc,CAAC,OAAO,EAAE,EAAE,OAAO,EAAE,eAAe,EAAE,EAAE,CAAC,UAAU,EAAE,EAAE;IACpF,MAAM,CAAC,YAAY,EAAE,SAAS,CAAC,GAAG,UAAU,CAAC,UAAU,CAAC,CAAC;IACzD,IAAI,CAAC,YAAY,IAAI,CAAC,SAAS,EAAE;QAC/B,MAAM,IAAI,KAAK,CAAC,uBAAuB,UAAU,EAAE,CAAC,CAAC;KACtD;IACD,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC;AACxE,CAAC,CAAC,CAAC","sourcesContent":["import { IQuote } from '@yuants/data-quote';\nimport { Terminal } from '@yuants/protocol';\nimport { writeToSQL } from '@yuants/sql';\nimport { decodePath, encodePath } from '@yuants/utils';\nimport { defer, filter, map, mergeMap, repeat, retry, shareReplay, withLatestFrom } from 'rxjs';\nimport { getAllMids, getMetaAndAssetCtxs } from '../../api/public-api';\n\nconst terminal = Terminal.fromNodeEnv();\nconst ASSET_CTX_REFRESH_INTERVAL = Number(process.env.ASSET_CTX_REFRESH_INTERVAL ?? 5_000);\n\ntype HyperliquidAssetContext = Awaited<ReturnType<typeof getMetaAndAssetCtxs>>[1][number];\n\nconst assetCtxMap$ = defer(() => getMetaAndAssetCtxs()).pipe(\n map(([meta, assetCtxs]) => {\n const entries = meta?.universe?.map<[string, HyperliquidAssetContext | undefined]>((asset, index) => [\n asset.name,\n assetCtxs?.[index],\n ]);\n return new Map(entries?.filter(([, ctx]) => !!ctx) ?? []);\n }),\n repeat({ delay: ASSET_CTX_REFRESH_INTERVAL }),\n retry({ delay: 5000 }),\n shareReplay({ bufferSize: 1, refCount: true }),\n);\n\nconst quote$ = defer(() => getAllMids()).pipe(\n map((mids) => Object.entries(mids ?? {})),\n mergeMap((entries) => entries),\n withLatestFrom(assetCtxMap$),\n map(([entry, assetCtxMap]): Partial<IQuote> => {\n const [coin, price] = entry;\n const ctx = assetCtxMap.get(coin);\n return {\n datasource_id: 'HYPERLIQUID',\n product_id: encodePath('PERPETUAL', `${coin}-USD`),\n last_price: `${price}`,\n bid_price: `${price}`,\n ask_price: `${price}`,\n open_interest: `${ctx?.openInterest ?? 0}`,\n updated_at: new Date().toISOString(),\n };\n }),\n repeat({ delay: 1000 }),\n retry({ delay: 5000 }),\n shareReplay({ bufferSize: 1, refCount: true }),\n);\n\nconst shouldWriteQuoteToSQL = /^(1|true)$/i.test(process.env.WRITE_QUOTE_TO_SQL ?? '');\n\nif (shouldWriteQuoteToSQL) {\n quote$\n .pipe(\n writeToSQL({\n terminal,\n tableName: 'quote',\n writeInterval: 1000,\n conflictKeys: ['datasource_id', 'product_id'],\n }),\n )\n .subscribe();\n}\n\nterminal.channel.publishChannel('quote', { pattern: '^HYPERLIQUID/' }, (channel_id) => {\n const [datasourceId, productId] = decodePath(channel_id);\n if (!datasourceId || !productId) {\n throw new Error(`Invalid channel_id: ${channel_id}`);\n }\n return quote$.pipe(filter((quote) => quote.product_id === productId));\n});\n"]}
1
+ {"version":3,"file":"quote.js","sourceRoot":"","sources":["../../../src/services/markets/quote.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,MAAM,CAAC;AAChG,OAAO,EAAE,UAAU,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAEvE,MAAM,QAAQ,GAA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CAAC,UAAU,EAAE,EAAE;IACpF,MAAM,CAAC,YAAY,CAAC,GAAG,UAAU,CAAC,UAAU,CAAC,CAAC;IAC9C,IAAI,YAAY,KAAK,aAAa,EAAE;QAClC,MAAM,IAAI,KAAK,CAAC,uBAAuB,UAAU,EAAE,CAAC,CAAC;KACtD;IACD,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,UAAU,KAAK,UAAU,CAAC,CAAC,CAAC;AACzE,CAAC,CAAC,CAAC","sourcesContent":["import { IQuote } from '@yuants/data-quote';\nimport { Terminal } from '@yuants/protocol';\nimport { writeToSQL } from '@yuants/sql';\nimport { decodePath, encodePath } from '@yuants/utils';\nimport { defer, filter, map, mergeMap, repeat, retry, shareReplay, withLatestFrom } from 'rxjs';\nimport { getAllMids, getMetaAndAssetCtxs } from '../../api/public-api';\n\nconst terminal = Terminal.fromNodeEnv();\nconst ASSET_CTX_REFRESH_INTERVAL = Number(process.env.ASSET_CTX_REFRESH_INTERVAL ?? 5_000);\n\ntype HyperliquidAssetContext = Awaited<ReturnType<typeof getMetaAndAssetCtxs>>[1][number];\n\nconst assetCtxMap$ = defer(() => getMetaAndAssetCtxs()).pipe(\n map(([meta, assetCtxs]) => {\n const entries = meta?.universe?.map<[string, HyperliquidAssetContext | undefined]>((asset, index) => [\n asset.name,\n assetCtxs?.[index],\n ]);\n return new Map(entries?.filter(([, ctx]) => !!ctx) ?? []);\n }),\n repeat({ delay: ASSET_CTX_REFRESH_INTERVAL }),\n retry({ delay: 5000 }),\n shareReplay({ bufferSize: 1, refCount: true }),\n);\n\nconst quote$ = defer(() => getAllMids()).pipe(\n map((mids) => Object.entries(mids ?? {})),\n mergeMap((entries) => entries),\n withLatestFrom(assetCtxMap$),\n map(([entry, assetCtxMap]): Partial<IQuote> => {\n const [coin, price] = entry;\n const ctx = assetCtxMap.get(coin);\n return {\n datasource_id: 'HYPERLIQUID',\n product_id: encodePath('HYPERLIQUID', 'PERPETUAL', `${coin}-USD`),\n last_price: `${price}`,\n bid_price: `${price}`,\n ask_price: `${price}`,\n open_interest: `${ctx?.openInterest ?? 0}`,\n updated_at: new Date().toISOString(),\n };\n }),\n repeat({ delay: 1000 }),\n retry({ delay: 5000 }),\n shareReplay({ bufferSize: 1, refCount: true }),\n);\n\nconst shouldWriteQuoteToSQL = /^(1|true)$/i.test(process.env.WRITE_QUOTE_TO_SQL ?? '');\n\nif (shouldWriteQuoteToSQL) {\n quote$\n .pipe(\n writeToSQL({\n terminal,\n tableName: 'quote',\n writeInterval: 1000,\n conflictKeys: ['datasource_id', 'product_id'],\n }),\n )\n .subscribe();\n}\n\nterminal.channel.publishChannel('quote', { pattern: '^HYPERLIQUID/' }, (channel_id) => {\n const [datasourceId] = decodePath(channel_id);\n if (datasourceId !== 'HYPERLIQUID') {\n throw new Error(`Invalid channel_id: ${channel_id}`);\n }\n return quote$.pipe(filter((quote) => quote.product_id === channel_id));\n});\n"]}
@@ -1,4 +1,4 @@
1
- import { resolveAssetInfo } from '../../utils';
1
+ import { resolveAssetInfo } from '../utils';
2
2
  import { cancelOrder } from '../../api/private-api';
3
3
  export const cancelOrderAction = async (credential, order) => {
4
4
  var _a, _b, _c;
@@ -1 +1 @@
1
- {"version":3,"file":"cancelOrder.js","sourceRoot":"","sources":["../../../src/services/orders/cancelOrder.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAEpD,MAAM,CAAC,MAAM,iBAAiB,GAAG,KAAK,EAAE,UAAuB,EAAE,KAAa,EAAE,EAAE;;IAChF,MAAM,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IACvC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE;QAC7B,MAAM,IAAI,KAAK,CAAC,qBAAqB,KAAK,CAAC,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":["import { IOrder } from '@yuants/data-order';\nimport { ICredential } from '../../api/types';\nimport { resolveAssetInfo } from '../../utils';\nimport { cancelOrder } from '../../api/private-api';\n\nexport const cancelOrderAction = async (credential: ICredential, order: IOrder) => {\n const orderId = Number(order.order_id);\n if (!Number.isFinite(orderId)) {\n throw new Error(`Invalid order_id: ${order.order_id}`);\n }\n const assetId = (() => {\n if (order.comment) {\n try {\n const parsed = JSON.parse(order.comment);\n if (typeof parsed?.asset_id === 'number') {\n return parsed.asset_id;\n }\n } catch {\n // ignore\n }\n }\n return undefined;\n })();\n const resolvedAsset = assetId ?? (await resolveAssetInfo(order.product_id)).assetId;\n const res = await cancelOrder(credential, { cancels: [{ a: resolvedAsset, o: orderId }] });\n const status = res?.response?.data?.statuses;\n const error =\n res?.status !== 'ok'\n ? 'API ERROR'\n : Array.isArray(status) && typeof status[0] !== 'string'\n ? status[0]?.error\n : undefined;\n\n if (error) throw new Error(error);\n};\n"]}
1
+ {"version":3,"file":"cancelOrder.js","sourceRoot":"","sources":["../../../src/services/orders/cancelOrder.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAC5C,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAEpD,MAAM,CAAC,MAAM,iBAAiB,GAAG,KAAK,EAAE,UAAuB,EAAE,KAAa,EAAE,EAAE;;IAChF,MAAM,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IACvC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE;QAC7B,MAAM,IAAI,KAAK,CAAC,qBAAqB,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC;KACxD;IACD,MAAM,OAAO,GAAG,CAAC,GAAG,EAAE;QACpB,IAAI,KAAK,CAAC,OAAO,EAAE;YACjB,IAAI;gBACF,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;gBACzC,IAAI,OAAO,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,QAAQ,CAAA,KAAK,QAAQ,EAAE;oBACxC,OAAO,MAAM,CAAC,QAAQ,CAAC;iBACxB;aACF;YAAC,WAAM;gBACN,SAAS;aACV;SACF;QACD,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC,EAAE,CAAC;IACL,MAAM,aAAa,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,CAAC,MAAM,gBAAgB,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,OAAO,CAAC;IACpF,MAAM,GAAG,GAAG,MAAM,WAAW,CAAC,UAAU,EAAE,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,aAAa,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC,CAAC;IAC3F,MAAM,MAAM,GAAG,MAAA,MAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,QAAQ,0CAAE,IAAI,0CAAE,QAAQ,CAAC;IAC7C,MAAM,KAAK,GACT,CAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,MAAM,MAAK,IAAI;QAClB,CAAC,CAAC,WAAW;QACb,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,OAAO,MAAM,CAAC,CAAC,CAAC,KAAK,QAAQ;YACxD,CAAC,CAAC,MAAA,MAAM,CAAC,CAAC,CAAC,0CAAE,KAAK;YAClB,CAAC,CAAC,SAAS,CAAC;IAEhB,IAAI,KAAK;QAAE,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC;AACpC,CAAC,CAAC","sourcesContent":["import { IOrder } from '@yuants/data-order';\nimport { ICredential } from '../../api/types';\nimport { resolveAssetInfo } from '../utils';\nimport { cancelOrder } from '../../api/private-api';\n\nexport const cancelOrderAction = async (credential: ICredential, order: IOrder) => {\n const orderId = Number(order.order_id);\n if (!Number.isFinite(orderId)) {\n throw new Error(`Invalid order_id: ${order.order_id}`);\n }\n const assetId = (() => {\n if (order.comment) {\n try {\n const parsed = JSON.parse(order.comment);\n if (typeof parsed?.asset_id === 'number') {\n return parsed.asset_id;\n }\n } catch {\n // ignore\n }\n }\n return undefined;\n })();\n const resolvedAsset = assetId ?? (await resolveAssetInfo(order.product_id)).assetId;\n const res = await cancelOrder(credential, { cancels: [{ a: resolvedAsset, o: orderId }] });\n const status = res?.response?.data?.statuses;\n const error =\n res?.status !== 'ok'\n ? 'API ERROR'\n : Array.isArray(status) && typeof status[0] !== 'string'\n ? status[0]?.error\n : undefined;\n\n if (error) throw new Error(error);\n};\n"]}
@@ -1,7 +1,5 @@
1
- import { getAddressFromCredential } from '../../api/types';
1
+ import { decodePath, encodePath, formatTime } from '@yuants/utils';
2
2
  import { getUserOpenOrders } from '../../api/public-api';
3
- import { encodePath } from '@yuants/utils';
4
- import { formatTime } from '@yuants/utils';
5
3
  /**
6
4
  * Map order direction based on side and reduce-only logic
7
5
  */
@@ -18,14 +16,14 @@ const mapOrderDirection = (side) => {
18
16
  /**
19
17
  * Map Hyperliquid order to Yuan IOrder format
20
18
  */
21
- const mapOrder = (order, account_id) => {
19
+ const mapOrder = (order) => {
22
20
  var _a, _b;
23
21
  const volume = Number(order.sz) || 0;
24
22
  const price = Number(order.limitPx) || 0;
25
23
  return {
26
24
  order_id: `${order.oid}`,
27
- account_id,
28
- product_id: encodePath('PERPETUAL', `${(_a = order.coin) === null || _a === void 0 ? void 0 : _a.trim()}-USD`),
25
+ account_id: '',
26
+ product_id: encodePath('HYPERLIQUID', 'PERPETUAL', `${(_a = order.coin) === null || _a === void 0 ? void 0 : _a.trim()}-USD`),
29
27
  order_type: 'LIMIT',
30
28
  order_direction: mapOrderDirection(order.side),
31
29
  volume: Number.isFinite(volume) ? volume : 0,
@@ -36,30 +34,14 @@ const mapOrder = (order, account_id) => {
36
34
  comment: order.coin ? JSON.stringify({ asset_id: order.coin }) : undefined,
37
35
  };
38
36
  };
39
- /**
40
- * Check if account is spot account
41
- */
42
- const isSpotAccount = (account_id) => account_id.endsWith('/spot/USDC');
43
- /**
44
- * List spot orders (currently no dedicated API, so return empty)
45
- * Note: Hyperliquid doesn't seem to have a separate spot orders API in the current documentation
46
- * This would need to be implemented when spot trading APIs become available
47
- */
48
- const listSpotOrders = async (credential, account_id) => {
49
- console.info(`[${formatTime(Date.now())}] Listing spot orders for ${account_id}`);
50
- // For now, return empty array as spot orders are not supported via current API
51
- // This would need to be implemented when Hyperliquid provides spot orders API
52
- console.warn(`[${formatTime(Date.now())}] Spot orders not yet supported via Hyperliquid API`);
53
- return [];
54
- };
55
37
  /**
56
38
  * List perpetual orders
57
39
  */
58
- const listPerpOrders = async (credential, account_id) => {
59
- console.info(`[${formatTime(Date.now())}] Listing perpetual orders for ${account_id}`);
40
+ export const listPerpOrders = async (credential) => {
41
+ console.info(`[${formatTime(Date.now())}] Listing perpetual orders for ${credential.address}`);
60
42
  try {
61
- const orders = await getUserOpenOrders({ user: getAddressFromCredential(credential) });
62
- return orders.map((order) => mapOrder(order, account_id));
43
+ const orders = await getUserOpenOrders({ user: credential.address });
44
+ return orders.map((order) => mapOrder(order));
63
45
  }
64
46
  catch (error) {
65
47
  const errorMessage = error instanceof Error ? error.message : 'Unknown error';
@@ -68,20 +50,17 @@ const listPerpOrders = async (credential, account_id) => {
68
50
  }
69
51
  };
70
52
  /**
71
- * List orders implementation
53
+ * List orders by product_id
72
54
  */
73
- export const listOrders = async (credential, account_id) => {
74
- console.info(`[${formatTime(Date.now())}] Listing orders for account: ${account_id}`);
75
- try {
76
- if (isSpotAccount(account_id)) {
77
- return await listSpotOrders(credential, account_id);
78
- }
79
- return await listPerpOrders(credential, account_id);
55
+ export const listOrdersByProductId = async (credential, product_id) => {
56
+ const [exchange, instType] = decodePath(product_id);
57
+ if (exchange !== 'HYPERLIQUID') {
58
+ throw new Error(`Invalid product_id for Hyperliquid: ${product_id}`);
80
59
  }
81
- catch (error) {
82
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
83
- console.error(`[${formatTime(Date.now())}] Failed to list orders for ${account_id}: ${errorMessage}`);
84
- throw new Error(`Failed to list orders: ${errorMessage}`);
60
+ if (instType !== 'PERPETUAL') {
61
+ return [];
85
62
  }
63
+ const orders = await listPerpOrders(credential);
64
+ return orders.filter((order) => order.product_id === product_id);
86
65
  };
87
66
  //# sourceMappingURL=listOrders.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"listOrders.js","sourceRoot":"","sources":["../../../src/services/orders/listOrders.ts"],"names":[],"mappings":"AACA,OAAO,EAAe,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AACxE,OAAO,EAAE,iBAAiB,EAAwB,MAAM,sBAAsB,CAAC;AAC/E,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAI3C;;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;QAChD,OAAO,WAAW,CAAC;KACpB;IACD,IAAI,UAAU,KAAK,KAAK,IAAI,UAAU,KAAK,MAAM,EAAE;QACjD,OAAO,YAAY,CAAC;KACrB;IACD,OAAO,WAAW,CAAC;AACrB,CAAC,CAAC;AAEF;;GAEG;AACH,MAAM,QAAQ,GAAG,CAAC,KAAU,EAAE,UAAkB,EAAU,EAAE;;IAC1D,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC;IACrC,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IAEzC,OAAO;QACL,QAAQ,EAAE,GAAG,KAAK,CAAC,GAAG,EAAE;QACxB,UAAU;QACV,UAAU,EAAE,UAAU,CAAC,WAAW,EAAE,GA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O,CAAC,KAAK,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,+BAA+B,UAAU,KAAK,YAAY,EAAE,CAAC,CAAC;QACtG,MAAM,IAAI,KAAK,CAAC,0BAA0B,YAAY,EAAE,CAAC,CAAC;KAC3D;AACH,CAAC,CAAC","sourcesContent":["import { IActionHandlerOfListOrders, IOrder } from '@yuants/data-order';\nimport { ICredential, getAddressFromCredential } from '../../api/types';\nimport { getUserOpenOrders, getUserTokenBalances } from '../../api/public-api';\nimport { encodePath } from '@yuants/utils';\nimport { formatTime } from '@yuants/utils';\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, account_id: string): 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('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 * Check if account is spot account\n */\nconst isSpotAccount = (account_id: string) => account_id.endsWith('/spot/USDC');\n\n/**\n * List spot orders (currently no dedicated API, so return empty)\n * Note: Hyperliquid doesn't seem to have a separate spot orders API in the current documentation\n * This would need to be implemented when spot trading APIs become available\n */\nconst listSpotOrders = async (credential: ICredential, account_id: string): Promise<IOrder[]> => {\n console.info(`[${formatTime(Date.now())}] Listing spot orders for ${account_id}`);\n\n // For now, return empty array as spot orders are not supported via current API\n // This would need to be implemented when Hyperliquid provides spot orders API\n console.warn(`[${formatTime(Date.now())}] Spot orders not yet supported via Hyperliquid API`);\n\n return [];\n};\n\n/**\n * List perpetual orders\n */\nconst listPerpOrders = async (credential: ICredential, account_id: string): Promise<IOrder[]> => {\n console.info(`[${formatTime(Date.now())}] Listing perpetual orders for ${account_id}`);\n\n try {\n const orders = await getUserOpenOrders({ user: getAddressFromCredential(credential) });\n return orders.map((order) => mapOrder(order, account_id));\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 implementation\n */\nexport const listOrders: IActionHandlerOfListOrders<ICredential> = async (credential, account_id) => {\n console.info(`[${formatTime(Date.now())}] Listing orders for account: ${account_id}`);\n\n try {\n if (isSpotAccount(account_id)) {\n return await listSpotOrders(credential, account_id);\n }\n\n return await listPerpOrders(credential, account_id);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n console.error(`[${formatTime(Date.now())}] Failed to list orders for ${account_id}: ${errorMessage}`);\n throw new Error(`Failed to list orders: ${errorMessage}`);\n }\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,C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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 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,6 +1,6 @@
1
- import { buildOrderPayload } from '../../utils';
2
- import { modifyOrder as modifyOrderApi } from '../../api/private-api';
3
1
  import { formatTime } from '@yuants/utils';
2
+ import { modifyOrder as modifyOrderApi } from '../../api/private-api';
3
+ import { buildOrderPayload } from '../utils';
4
4
  /**
5
5
  * 修改订单 - 使用 Hyperliquid 原生 modify order API
6
6
  *
@@ -1 +1 @@
1
- {"version":3,"file":"modifyOrder.js","sourceRoot":"","sources":["../../../src/services/orders/modifyOrder.ts"],"names":[],"mappings":"AAEA,OAAO,EAAoB,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAClE,OAAO,EAAE,WAAW,IAAI,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACtE,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAE3C;;;;;;;;;;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;YAC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IAAI,CAAC,GAAG,EAAE,CAAC,WAAW,KAAK,CAAC,QAAQ,wBAAwB,CAAC,CAAC;KAC3F;IAAC,OAAO,KAAK,EAAE;QACd,MAAM,YAAY,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,eAAe,CAAC;QAC9E,OAAO,CAAC,KAAK,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,4BAA4B,KAAK,CAAC,QAAQ,KAAK,YAAY,EAAE,CAAC,CAAC;QACvG,MAAM,IAAI,KAAK,CAAC,2BAA2B,YAAY,EAAE,CAAC,CAAC;KAC5D;AACH,CAAC,CAAC","sourcesContent":["import { IOrder } from '@yuants/data-order';\nimport { ICredential } from '../../api/types';\nimport { resolveAssetInfo, buildOrderPayload } from '../../utils';\nimport { modifyOrder as modifyOrderApi } from '../../api/private-api';\nimport { formatTime } from '@yuants/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
+ {"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;Q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AK,CAAC,OAAO,CAAC,CAAC,CAAC,eAAe,CAAC;QAC9E,OAAO,CAAC,KAAK,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,4BAA4B,KAAK,CAAC,QAAQ,KAAK,YAAY,EAAE,CAAC,CAAC;QACvG,MAAM,IAAI,KAAK,CAAC,2BAA2B,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 }\n};\n"]}
@@ -1,5 +1,5 @@
1
1
  import { placeOrder } from '../../api/private-api';
2
- import { buildOrderPayload } from '../../utils';
2
+ import { buildOrderPayload } from '../utils';
3
3
  export const submitOrder = async (credential, order) => {
4
4
  var _a, _b, _c, _d, _e, _f, _g, _h;
5
5
  const { orderParams } = await buildOrderPayload(order);
@@ -1 +1 @@
1
- {"version":3,"file":"submitOrder.js","sourceRoot":"","sources":["../../../src/services/orders/submitOrder.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAEnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAEhD,MAAM,CAAC,MAAM,WAAW,GAAG,KAAK,EAAE,UAAuB,EAAE,KAAa,EAAiC,EAAE;;IACzG,MAAM,EAAE,WAAW,EAAE,GAAG,MAAM,iBAAiB,CAAC,KAAK,CAAC,CAAC;IACvD,MAAM,GAAG,GAAG,MAAM,UAAU,CAAC,UAAU,EAAE,EAAE,MAAM,EAAE,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;IACpE,MAAM,MAAM,GAAG,MAAA,MAAA,MAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,QAAQ,0CAAE,IAAI,0CAAE,QAAQ,0CAAG,CAAC,CAAC,CAAC;IAClD,MAAM,OAAO,GACX,MAAA,MAAA,MAAA,MAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,OAAO,0CAAE,GAAG,mCAAI,MAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,MAAM,0CAAE,GAAG,mCAAK,MAAc,aAAd,MAAM,uBAAN,MAAM,CAAU,GAAG,mCAAK,MAAc,aAAd,MAAM,uBAAN,MAAM,CAAU,OAAO,CAAC;IAClG,MAAM,KAAK,GACT,CAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,MAAM,MAAK,IAAI,CAAC,CAAC,CAAC,cAAc,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,KAAK,EAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;IACxG,IAAI,KAAK;QAAE,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC;IAClC,IAAI,OAAO,KAAK,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;IAC5E,OAAO,EAAE,QAAQ,EAAE,GAAG,OAAO,EAAE,EAAE,CAAC;AACpC,CAAC,CAAC","sourcesContent":["import { IOrder } from '@yuants/data-order';\nimport { placeOrder } from '../../api/private-api';\nimport { ICredential } from '../../api/types';\nimport { buildOrderPayload } from '../../utils';\n\nexport const submitOrder = async (credential: ICredential, order: IOrder): Promise<{ order_id: string }> => {\n const { orderParams } = await buildOrderPayload(order);\n const res = await placeOrder(credential, { orders: [orderParams] });\n const status = res?.response?.data?.statuses?.[0];\n const orderId =\n status?.resting?.oid ?? status?.filled?.oid ?? (status as any)?.oid ?? (status as any)?.orderId;\n const error =\n res?.status !== 'ok' ? `API ERROR: ${JSON.stringify(res)}` : status?.error ? status.error : undefined;\n if (error) throw new Error(error);\n if (orderId === undefined) throw new Error('No order ID returned from API');\n return { order_id: `${orderId}` };\n};\n"]}
1
+ {"version":3,"file":"submitOrder.js","sourceRoot":"","sources":["../../../src/services/orders/submitOrder.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAEnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAE7C,MAAM,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../api/private-api';\nimport { ICredential } from '../../api/types';\nimport { buildOrderPayload } from '../utils';\n\nexport const submitOrder = async (credential: ICredential, order: IOrder): Promise<{ order_id: string }> => {\n const { orderParams } = await buildOrderPayload(order);\n const res = await placeOrder(credential, { orders: [orderParams] });\n const status = res?.response?.data?.statuses?.[0];\n const orderId =\n status?.resting?.oid ?? status?.filled?.oid ?? (status as any)?.oid ?? (status as any)?.orderId;\n const error =\n res?.status !== 'ok' ? `API ERROR: ${JSON.stringify(res)}` : status?.error ? status.error : undefined;\n if (error) throw new Error(error);\n if (orderId === undefined) throw new Error('No order ID returned from API');\n return { order_id: `${orderId}` };\n};\n"]}
@@ -1,6 +1,17 @@
1
1
  import { createCache } from '@yuants/cache';
2
2
  import { decodePath } from '@yuants/utils';
3
- import { getAllMids, getPerpetualsMetaData, getSpotMetaData } from './api/public-api';
3
+ import { getAllMids, getPerpetualsMetaData, getSpotMetaData } from '../api/public-api';
4
+ export const parseProductPath = (product_id) => {
5
+ const [exchange, instType, symbol] = decodePath(product_id);
6
+ if (exchange !== 'HYPERLIQUID' || !instType || !symbol) {
7
+ throw new Error(`Invalid product_id: ${product_id}`);
8
+ }
9
+ if (instType !== "PERPETUAL" /* InstrumentType.PERPETUAL */ && instType !== "SPOT" /* InstrumentType.SPOT */) {
10
+ throw new Error(`Unsupported instrument type: ${instType}`);
11
+ }
12
+ const baseCurrency = symbol.split('-')[0];
13
+ return { instType, baseCurrency };
14
+ };
4
15
  const CACHE_TTL = 60000;
5
16
  const MID_TTL = 5000;
6
17
  // Create caches using createCache utility
@@ -31,11 +42,7 @@ const midPriceCache = createCache(async () => {
31
42
  return map;
32
43
  }, { expire: MID_TTL });
33
44
  export const resolveAssetInfo = async (product_id) => {
34
- const [instType, symbol] = decodePath(product_id);
35
- if (!instType || !symbol) {
36
- throw new Error(`Invalid product_id: ${product_id}`);
37
- }
38
- const baseCurrency = symbol.split('-')[0];
45
+ const { instType, baseCurrency } = parseProductPath(product_id);
39
46
  if (instType === "PERPETUAL" /* InstrumentType.PERPETUAL */) {
40
47
  const map = (await perpMetaCache.query('perp'));
41
48
  const info = map.get(baseCurrency);
@@ -0,0 +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,qBAAqB,EAAE,CAAC;IAC3C,MAAM,GAAG,GAAG,IAAI,GAAG,EAAmD,CAAC;IACvE,IAA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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"]}
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getUserFills = exports.modifyOrder = exports.cancelOrder = exports.placeOrder = void 0;
4
4
  const ethers_1 = require("ethers");
5
- const sign_1 = require("../sign");
5
+ const sign_1 = require("./sign");
6
6
  const client_1 = require("./client");
7
7
  const walletCache = new Map();
8
8
  const getWallet = (credential) => {
@@ -1 +1 @@
1
- {"version":3,"file":"private-api.js","sourceRoot":"","sources":["../../src/api/private-api.ts"],"names":[],"mappings":";;;AAAA,mCAAgC;AAChC,kCAAuC;AACvC,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;QAC5C,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC,WAAW,EAAE,IAAI,eAAM,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC,CAAC;KAC7E;IACD,OAAO,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC,WAAW,CAAE,CAAC;AAClD,CAAC,CAAC;AAEF;;;;;;;GAOG;AACI,MAAM,UAAU,GAAG,KAAK,EAC7B,UAAuB,EACvB,MAKC,EACD,EAAE;;IACF,MAAM,MAAM,GAAwB;QAClC,IAAI,EAAE,OAAO;QACb,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,QAAQ,EAAE,IAAI;KACf,CAAC;IACF,IAAI,MAAM,CAAC,OAAO,EAAE;QAClB,MAAM,CAAC,SAAS,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC;KACpC;IACD,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IACzB,MAAM,SAAS,GAAG,MAAM,IAAA,mBAAY,EAClC,SAAS,CAAC,UAAU,CAAC,EACrB,MAAM,EACN,MAAA,MAAM,CAAC,YAAY,mCAAI,IAAI,EAC3B,KAAK,EACL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AAA,MAAM,CAAC,YAAY,mCAAI,IAAI,EAC3B,IAAI,CACL,CAAC;IACF,OAAO,IAAA,gBAAO,EAAC,MAAM,EAAE,UAAU,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC;AACnE,CAAC,CAAC;AAxBW,QAAA,WAAW,eAwBtB;AAEF;;;;;;GAMG;AACI,MAAM,YAAY,GAAG,KAAK,EAC/B,UAAuB,EACvB,MAAiD,EACjD,EAAE;IACF,MAAM,MAAM,GAAG,SAAS,CAAC,UAAU,CAAC,CAAC;IACrC,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;IAE/B,MAAM,WAAW,GAAQ;QACvB,IAAI,EAAE,WAAW;QACjB,IAAI,EAAE,OAAO;KACd,CAAC;IAEF,IAAI,MAAM,aAAN,MAAM,uBAAN,MAAM,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,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AC,CAAC;IACrC,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;IAE/B,MAAM,WAAW,GAAQ;QACvB,IAAI,EAAE,WAAW;QACjB,IAAI,EAAE,OAAO;KACd,CAAC;IAEF,IAAI,MAAM,aAAN,MAAM,uBAAN,MAAM,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"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sign.d.ts","sourceRoot":"","sources":["../../src/api/sign.ts"],"names":[],"mappings":"AACA,OAAO,EAAa,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE3C,UAAU,YAAY;IACpB,MAAM,EAAE,MAAM,CAAC;IACf,YAAY,EAAE,MAAM,CAAC;CACtB;AAED,UAAU,SAAS;IACjB,MAAM,EAAE;QACN,OAAO,EAAE,MAAM,CAAC;QAChB,IAAI,EAAE,MAAM,CAAC;QACb,iBAAiB,EAAE,MAAM,CAAC;QAC1B,OAAO,EAAE,MAAM,CAAC;KACjB,CAAC;IACF,KAAK,EAAE;QACL,KAAK,EAAE,KAAK,CAAC;YAAE,IAAI,EAAE,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AAY,GAAG,qBAAqB,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;IAC5D,MAAM,IAAI,GAAG,SAAS,CAAC,YAAY,CAAC,CAAC;IACrC,OAAO,MAAM,SAAS,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;AACvC,CAAC;AAZD,oCAYC","sourcesContent":["import { encode } from '@msgpack/msgpack';\nimport { keccak256, Wallet } from 'ethers';\n\ninterface PhantomAgent {\n source: string;\n connectionId: string;\n}\n\ninterface L1Payload {\n domain: {\n chainId: number;\n name: string;\n verifyingContract: string;\n version: string;\n };\n types: {\n Agent: Array<{ name: string; type: string }>;\n EIP712Domain: Array<{ name: string; type: string }>;\n };\n primaryType: string;\n message: PhantomAgent;\n}\n\ninterface Signature {\n r: string;\n s: string;\n v: number;\n}\n\nfunction addressToBytes(address: string): Uint8Array {\n const cleanAddress = address.startsWith('0x') ? address.slice(2) : address;\n return new Uint8Array(Buffer.from(cleanAddress, 'hex'));\n}\n\nfunction actionHash(\n action: any,\n vaultAddress: string | null,\n nonce: number,\n expiresAfter: number | null,\n): string {\n let data: any = new Uint8Array(encode(action));\n\n const nonceBytes = new Uint8Array(8);\n const nonceView = new DataView(nonceBytes.buffer);\n nonceView.setBigUint64(0, BigInt(nonce), false); // false = big endian\n data = concatUint8Arrays(data, nonceBytes);\n\n if (vaultAddress == null) {\n data = concatUint8Arrays(data, new Uint8Array([0x00]));\n } else {\n data = concatUint8Arrays(data, new Uint8Array([0x01]));\n data = concatUint8Arrays(data, addressToBytes(vaultAddress));\n }\n if (expiresAfter != null) {\n data = concatUint8Arrays(data, new Uint8Array([0x00]));\n const expiresBytes = new Uint8Array(8);\n const expiresView = new DataView(expiresBytes.buffer);\n expiresView.setBigUint64(0, BigInt(expiresAfter), false); // false = big endian\n data = concatUint8Arrays(data, expiresBytes);\n }\n\n return keccak256(data);\n}\n\nfunction concatUint8Arrays(...arrays: Uint8Array[]): Uint8Array {\n const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n\n for (const arr of arrays) {\n result.set(arr, offset);\n offset += arr.length;\n }\n\n return result;\n}\n\nfunction constructPhantomAgent(hash: string, isMainnet: boolean): PhantomAgent {\n return {\n source: isMainnet ? 'a' : 'b',\n connectionId: hash,\n };\n}\n\nfunction l1Payload(phantomAgent: PhantomAgent): L1Payload {\n return {\n domain: {\n chainId: 1337,\n name: 'Exchange',\n verifyingContract: '0x0000000000000000000000000000000000000000',\n version: '1',\n },\n types: {\n Agent: [\n { name: 'source', type: 'string' },\n { name: 'connectionId', type: 'bytes32' },\n ],\n EIP712Domain: [\n { name: 'name', type: 'string' },\n { name: 'version', type: 'string' },\n { name: 'chainId', type: 'uint256' },\n { name: 'verifyingContract', type: 'address' },\n ],\n },\n primaryType: 'Agent',\n message: phantomAgent,\n };\n}\n\nasync function signInner(wallet: Wallet, data: L1Payload): Promise<Signature> {\n const signature = await wallet.signTypedData(data.domain, { Agent: data.types.Agent }, data.message);\n\n const r = signature.slice(0, 66);\n const s = '0x' + signature.slice(66, 130);\n const v = parseInt(signature.slice(130, 132), 16);\n\n return { r, s, v };\n}\n\n/**\n * 签署 L1 动作\n *\n * @param wallet - 以太坊钱包实例\n * @param action - 要签署的动作数据\n * @param activePool - 活跃池地址(可以为 null)\n * @param nonce - 随机数\n * @param expiresAfter - 过期时间(可以为 null)\n * @param isMainnet - 是否为主网\n * @returns 签名对象\n */\nexport async function signL1Action(\n wallet: Wallet,\n action: any,\n activePool: string | null,\n nonce: number,\n expiresAfter: number | null,\n isMainnet: boolean,\n): Promise<Signature> {\n const hash = actionHash(action, activePool, nonce, expiresAfter);\n const phantomAgent = constructPhantomAgent(hash, isMainnet);\n const data = l1Payload(phantomAgent);\n return await signInner(wallet, data);\n}\n\nexport { actionHash, addressToBytes, constructPhantomAgent, l1Payload };\n"]}
@@ -4,13 +4,12 @@
4
4
  */
5
5
  export interface ICredential {
6
6
  private_key: string;
7
+ address: string;
7
8
  }
8
9
  /**
9
- * 从凭证获取地址
10
- * @param credential 凭证对象
11
- * @returns 钱包地址
10
+ * 获取凭证唯一标识
12
11
  */
13
- export declare const getAddressFromCredential: (credential: ICredential) => string;
12
+ export declare const getCredentialId: (credential: ICredential) => string;
14
13
  /**
15
14
  * 创建凭证对象
16
15
  * @param private_key 私钥
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/api/types.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,MAAM,WAAW,WAAW;IAC1B,WAAW,EAAE,MAAM,CAAC;CACrB;AAED;;;;GAIG;AACH,eAAO,MAAM,wBAAwB,eAAgB,WAAW,KAAG,MAGlE,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,gBAAiB,MAAM,KAAG,WAEtD,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,oBAAoB,QAAO,WAMvC,CAAC"}
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/api/types.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,MAAM,WAAW,WAAW;IAC1B,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;GAEG;AACH,eAAO,MAAM,eAAe,eAAgB,WAAW,KAAG,MACP,CAAC;AAEpD;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,gBAAiB,MAAM,KAAG,WAGtD,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,oBAAoB,QAAO,WAMvC,CAAC"}
package/lib/api/types.js CHANGED
@@ -1,24 +1,20 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getDefaultCredential = exports.createCredential = exports.getAddressFromCredential = void 0;
3
+ exports.getDefaultCredential = exports.createCredential = exports.getCredentialId = void 0;
4
4
  const ethers_1 = require("ethers");
5
5
  /**
6
- * 从凭证获取地址
7
- * @param credential 凭证对象
8
- * @returns 钱包地址
6
+ * 获取凭证唯一标识
9
7
  */
10
- const getAddressFromCredential = (credential) => {
11
- const wallet = new ethers_1.Wallet(credential.private_key);
12
- return wallet.address;
13
- };
14
- exports.getAddressFromCredential = getAddressFromCredential;
8
+ const getCredentialId = (credential) => `HYPERLIQUID/${credential.address.toLowerCase()}`;
9
+ exports.getCredentialId = getCredentialId;
15
10
  /**
16
11
  * 创建凭证对象
17
12
  * @param private_key 私钥
18
13
  * @returns 凭证对象
19
14
  */
20
15
  const createCredential = (private_key) => {
21
- return { private_key };
16
+ const wallet = new ethers_1.Wallet(private_key);
17
+ return { private_key, address: wallet.address };
22
18
  };
23
19
  exports.createCredential = createCredential;
24
20
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/api/types.ts"],"names":[],"mappings":";;;AAAA,mCAAgC;AAUhC;;;;GAIG;AACI,MAAM,wBAAwB,GAAG,CAAC,UAAuB,EAAU,EAAE;IAC1E,MAAM,MAAM,GAAG,IAAI,eAAM,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC;IAClD,OAAO,MAAM,CAAC,OAAO,CAAC;AACxB,CAAC,CAAC;AAHW,QAAA,wBAAwB,4BAGnC;AAEF;;;;GAIG;AACI,MAAM,gBAAgB,GAAG,CAAC,WAAmB,EAAe,EAAE;IACnE,OAAO,EAAE,WAAW,EAAE,CAAC;AACzB,CAAC,CAAC;AAFW,QAAA,gBAAgB,oBAE3B;AAEF;;;GAGG;AACI,MAAM,oBAAoB,GAAG,GAAgB,EAAE;IACpD,MAAM,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC;IAC5C,IAAI,CAAC,WAAW,EAAE;QAChB,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAC;KAC5E;IACD,OAAO,IAAA,wBAAgB,EAAC,WAAW,CAAC,CAAC;AACvC,CAAC,CAAC;AANW,QAAA,oBAAoB,wBAM/B","sourcesContent":["import { Wallet } from 'ethers';\n\n/**\n * Hyperliquid 凭证接口\n * 仅包含核心数据,行为方法通过辅助函数提供\n */\nexport interface ICredential {\n private_key: string;\n}\n\n/**\n * 从凭证获取地址\n * @param credential 凭证对象\n * @returns 钱包地址\n */\nexport const getAddressFromCredential = (credential: ICredential): string => {\n const wallet = new Wallet(credential.private_key);\n return wallet.address;\n};\n\n/**\n * 创建凭证对象\n * @param private_key 私钥\n * @returns 凭证对象\n */\nexport const createCredential = (private_key: string): ICredential => {\n return { private_key };\n};\n\n/**\n * 获取默认凭证(从环境变量)\n * @returns 默认凭证对象\n */\nexport const getDefaultCredential = (): ICredential => {\n const private_key = process.env.PRIVATE_KEY;\n if (!private_key) {\n throw new Error('Missing Hyperliquid credential: PRIVATE_KEY must be set');\n }\n return createCredential(private_key);\n};\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/api/types.ts"],"names":[],"mappings":";;;AAAA,mCAAgC;AAWhC;;GAEG;AACI,MAAM,eAAe,GAAG,CAAC,UAAuB,EAAU,EAAE,CACjE,eAAe,UAAU,CAAC,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC;AADvC,QAAA,eAAe,mBACwB;AAEpD;;;;GAIG;AACI,MAAM,gBAAgB,GAAG,CAAC,WAAmB,EAAe,EAAE;IACnE,MAAM,MAAM,GAAG,IAAI,eAAM,CAAC,WAAW,CAAC,CAAC;IACvC,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,CAAC;AAClD,CAAC,CAAC;AAHW,QAAA,gBAAgB,oBAG3B;AAEF;;;GAGG;AACI,MAAM,oBAAoB,GAAG,GAAgB,EAAE;IACpD,MAAM,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC;IAC5C,IAAI,CAAC,WAAW,EAAE;QAChB,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAC;KAC5E;IACD,OAAO,IAAA,wBAAgB,EAAC,WAAW,CAAC,CAAC;AACvC,CAAC,CAAC;AANW,QAAA,oBAAoB,wBAM/B","sourcesContent":["import { Wallet } from 'ethers';\n\n/**\n * Hyperliquid 凭证接口\n * 仅包含核心数据,行为方法通过辅助函数提供\n */\nexport interface ICredential {\n private_key: string;\n address: string;\n}\n\n/**\n * 获取凭证唯一标识\n */\nexport const getCredentialId = (credential: ICredential): string =>\n `HYPERLIQUID/${credential.address.toLowerCase()}`;\n\n/**\n * 创建凭证对象\n * @param private_key 私钥\n * @returns 凭证对象\n */\nexport const createCredential = (private_key: string): ICredential => {\n const wallet = new Wallet(private_key);\n return { private_key, address: wallet.address };\n};\n\n/**\n * 获取默认凭证(从环境变量)\n * @returns 默认凭证对象\n */\nexport const getDefaultCredential = (): ICredential => {\n const private_key = process.env.PRIVATE_KEY;\n if (!private_key) {\n throw new Error('Missing Hyperliquid credential: PRIVATE_KEY must be set');\n }\n return createCredential(private_key);\n};\n"]}
package/lib/index.d.ts CHANGED
@@ -1,11 +1,6 @@
1
- import './services/account-actions-with-credential';
2
- import './services/legacy';
1
+ import './services/exchange';
3
2
  import './services/markets/interest-rate';
4
3
  import './services/markets/ohlc';
5
4
  import './services/markets/product';
6
5
  import './services/markets/quote';
7
- import './services/order-actions-with-credential';
8
- import './services/orders/cancelOrder';
9
- import './services/orders/modifyOrder';
10
- import './services/orders/submitOrder';
11
6
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,4CAA4C,CAAC;AACpD,OAAO,mBAAmB,CAAC;AAC3B,OAAO,kCAAkC,CAAC;AAC1C,OAAO,yBAAyB,CAAC;AACjC,OAAO,4BAA4B,CAAC;AACpC,OAAO,0BAA0B,CAAC;AAClC,OAAO,0CAA0C,CAAC;AAClD,OAAO,+BAA+B,CAAC;AACvC,OAAO,+BAA+B,CAAC;AACvC,OAAO,+BAA+B,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,qBAAqB,CAAC;AAC7B,OAAO,kCAAkC,CAAC;AAC1C,OAAO,yBAAyB,CAAC;AACjC,OAAO,4BAA4B,CAAC;AACpC,OAAO,0BAA0B,CAAC"}
package/lib/index.js CHANGED
@@ -1,14 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- // Import services from new structure
4
- require("./services/account-actions-with-credential");
5
- require("./services/legacy");
3
+ require("./services/exchange");
6
4
  require("./services/markets/interest-rate");
7
5
  require("./services/markets/ohlc");
8
6
  require("./services/markets/product");
9
7
  require("./services/markets/quote");
10
- require("./services/order-actions-with-credential");
11
- require("./services/orders/cancelOrder");
12
- require("./services/orders/modifyOrder");
13
- require("./services/orders/submitOrder");
14
8
  //# sourceMappingURL=index.js.map
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;AAAA,qCAAqC;AACrC,sDAAoD;AACpD,6BAA2B;AAC3B,4CAA0C;AAC1C,mCAAiC;AACjC,sCAAoC;AACpC,oCAAkC;AAClC,oDAAkD;AAClD,yCAAuC;AACvC,yCAAuC;AACvC,yCAAuC","sourcesContent":["// Import services from new structure\nimport './services/account-actions-with-credential';\nimport './services/legacy';\nimport './services/markets/interest-rate';\nimport './services/markets/ohlc';\nimport './services/markets/product';\nimport './services/markets/quote';\nimport './services/order-actions-with-credential';\nimport './services/orders/cancelOrder';\nimport './services/orders/modifyOrder';\nimport './services/orders/submitOrder';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;AAAA,+BAA6B;AAC7B,4CAA0C;AAC1C,mCAAiC;AACjC,sCAAoC;AACpC,oCAAkC","sourcesContent":["import './services/exchange';\nimport './services/markets/interest-rate';\nimport './services/markets/ohlc';\nimport './services/markets/product';\nimport './services/markets/quote';\n"]}
@@ -3,5 +3,5 @@ import { ICredential } from '../../api/types';
3
3
  /**
4
4
  * Get account info for perpetual account
5
5
  */
6
- export declare const getPerpAccountInfo: (credential: ICredential, account_id: string) => Promise<IPosition[]>;
6
+ export declare const getPerpPositions: (credential: ICredential) => Promise<IPosition[]>;
7
7
  //# sourceMappingURL=perp.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"perp.d.ts","sourceRoot":"","sources":["../../../src/services/accounts/perp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAGjD,OAAO,EAA4B,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAExE;;GAEG;AACH,eAAO,MAAM,kBAAkB,eAAsB,WAAW,cAAc,MAAM,yBAmCnF,CAAC"}
1
+ {"version":3,"file":"perp.d.ts","sourceRoot":"","sources":["../../../src/services/accounts/perp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAGjD,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE9C;;GAEG;AACH,eAAO,MAAM,gBAAgB,eAAsB,WAAW,yBAuB7D,CAAC"}
@@ -1,20 +1,19 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getPerpAccountInfo = void 0;
3
+ exports.getPerpPositions = void 0;
4
4
  const utils_1 = require("@yuants/utils");
5
5
  const public_api_1 = require("../../api/public-api");
6
- const types_1 = require("../../api/types");
7
6
  /**
8
7
  * Get account info for perpetual account
9
8
  */
10
- const getPerpAccountInfo = async (credential, account_id) => {
11
- console.info(`[${(0, utils_1.formatTime)(Date.now())}] Getting perp account info for ${account_id}`);
12
- const summary = await (0, public_api_1.getUserPerpetualsAccountSummary)({ user: (0, types_1.getAddressFromCredential)(credential) });
9
+ const getPerpPositions = async (credential) => {
10
+ console.info(`[${(0, utils_1.formatTime)(Date.now())}] Getting perp account info for ${credential.address}`);
11
+ const summary = await (0, public_api_1.getUserPerpetualsAccountSummary)({ user: credential.address });
13
12
  // Map positions
14
13
  const positions = summary.assetPositions.map((position) => ({
15
14
  position_id: `${position.position.coin}-USD`,
16
15
  datasource_id: 'HYPERLIQUID',
17
- product_id: (0, utils_1.encodePath)('PERPETUAL', `${position.position.coin}-USD`),
16
+ product_id: (0, utils_1.encodePath)('HYPERLIQUID', 'PERPETUAL', `${position.position.coin}-USD`),
18
17
  direction: +position.position.szi > 0 ? 'LONG' : 'SHORT',
19
18
  volume: Math.abs(+position.position.szi),
20
19
  free_volume: Math.abs(+position.position.szi),
@@ -24,18 +23,7 @@ const getPerpAccountInfo = async (credential, account_id) => {
24
23
  valuation: +position.position.positionValue,
25
24
  margin: +position.position.marginUsed,
26
25
  }));
27
- // Map orders
28
- const mapOrderDirection = (side) => {
29
- const normalized = side.toUpperCase();
30
- if (normalized === 'BID' || normalized === 'BUY') {
31
- return 'OPEN_LONG';
32
- }
33
- if (normalized === 'ASK' || normalized === 'SELL') {
34
- return 'OPEN_SHORT';
35
- }
36
- return 'OPEN_LONG';
37
- };
38
26
  return positions;
39
27
  };
40
- exports.getPerpAccountInfo = getPerpAccountInfo;
28
+ exports.getPerpPositions = getPerpPositions;
41
29
  //# sourceMappingURL=perp.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"perp.js","sourceRoot":"","sources":["../../../src/services/accounts/perp.ts"],"names":[],"mappings":";;;AACA,yCAAuD;AACvD,qDAAuE;AACvE,2CAAwE;AAExE;;GAEG;AACI,MAAM,kBAAkB,GAAG,KAAK,EAAE,UAAuB,EAAE,UAAkB,EAAE,EAAE;IACtF,OAAO,CAAC,IAAI,CAAC,IAAI,IAAA,kBAAU,EAAC,IAAI,CAAC,GAAG,EAAE,CAAC,mCAAmC,UAAU,EAAE,CAAC,CAAC;IAExF,MAAM,OAAO,GAAG,MAAM,IAAA,4CAA+B,EAAC,EAAE,IAAI,EAAE,IAAA,gCAAwB,EAAC,UAAU,CAAC,EAAE,CAAC,CAAC;IAEtG,gBAAgB;IAChB,MAAM,SAAS,GAAG,OAAO,CAAC,cA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D,OAAO,WAAW,CAAC;IACrB,CAAC,CAAC;IAEF,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC;AAnCW,QAAA,kBAAkB,sBAmC7B","sourcesContent":["import { IPosition } from '@yuants/data-account';\nimport { encodePath, formatTime } from '@yuants/utils';\nimport { getUserPerpetualsAccountSummary } from '../../api/public-api';\nimport { getAddressFromCredential, ICredential } from '../../api/types';\n\n/**\n * Get account info for perpetual account\n */\nexport const getPerpAccountInfo = async (credential: ICredential, account_id: string) => {\n console.info(`[${formatTime(Date.now())}] Getting perp account info for ${account_id}`);\n\n const summary = await getUserPerpetualsAccountSummary({ user: getAddressFromCredential(credential) });\n\n // Map positions\n const positions = summary.assetPositions.map(\n (position): IPosition => ({\n position_id: `${position.position.coin}-USD`,\n datasource_id: 'HYPERLIQUID',\n product_id: encodePath('PERPETUAL', `${position.position.coin}-USD`),\n direction: +position.position.szi > 0 ? 'LONG' : 'SHORT',\n volume: Math.abs(+position.position.szi),\n free_volume: Math.abs(+position.position.szi),\n position_price: +position.position.entryPx,\n closable_price: Math.abs(+position.position.positionValue / +position.position.szi || 0),\n floating_profit: +position.position.unrealizedPnl,\n valuation: +position.position.positionValue,\n margin: +position.position.marginUsed,\n }),\n );\n\n // Map orders\n const mapOrderDirection = (side: string) => {\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 return positions;\n};\n"]}
1
+ {"version":3,"file":"perp.js","sourceRoot":"","sources":["../../../src/services/accounts/perp.ts"],"names":[],"mappings":";;;AACA,yCAAuD;AACvD,qDAAuE;AAGvE;;GAEG;AACI,MAAM,gBAAgB,GAAG,KAAK,EAAE,UAAuB,EAAE,EAAE;IAChE,OAAO,CAAC,IAAI,CAAC,IAAI,IAAA,kBAAU,EAAC,IAAI,CAAC,GAAG,EAAE,CAAC,mCAAmC,UAAU,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yuants/data-account';\nimport { encodePath, formatTime } from '@yuants/utils';\nimport { getUserPerpetualsAccountSummary } from '../../api/public-api';\nimport { ICredential } from '../../api/types';\n\n/**\n * Get account info for perpetual account\n */\nexport const getPerpPositions = async (credential: ICredential) => {\n console.info(`[${formatTime(Date.now())}] Getting perp account info for ${credential.address}`);\n\n const summary = await getUserPerpetualsAccountSummary({ user: credential.address });\n\n // Map positions\n const positions = summary.assetPositions.map(\n (position): IPosition => ({\n position_id: `${position.position.coin}-USD`,\n datasource_id: 'HYPERLIQUID',\n product_id: encodePath('HYPERLIQUID', 'PERPETUAL', `${position.position.coin}-USD`),\n direction: +position.position.szi > 0 ? 'LONG' : 'SHORT',\n volume: Math.abs(+position.position.szi),\n free_volume: Math.abs(+position.position.szi),\n position_price: +position.position.entryPx,\n closable_price: Math.abs(+position.position.positionValue / +position.position.szi || 0),\n floating_profit: +position.position.unrealizedPnl,\n valuation: +position.position.positionValue,\n margin: +position.position.marginUsed,\n }),\n );\n\n return positions;\n};\n"]}
@@ -3,5 +3,5 @@ import { ICredential } from '../../api/types';
3
3
  /**
4
4
  * Get account info for spot account
5
5
  */
6
- export declare const getSpotAccountInfo: (credential: ICredential, account_id: string) => Promise<IPosition[]>;
6
+ export declare const getSpotPositions: (credential: ICredential) => Promise<IPosition[]>;
7
7
  //# sourceMappingURL=spot.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"spot.d.ts","sourceRoot":"","sources":["../../../src/services/accounts/spot.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAoB,MAAM,sBAAsB,CAAC;AAGnE,OAAO,EAA4B,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAExE;;GAEG;AACH,eAAO,MAAM,kBAAkB,eAAsB,WAAW,cAAc,MAAM,yBAqBnF,CAAC"}
1
+ {"version":3,"file":"spot.d.ts","sourceRoot":"","sources":["../../../src/services/accounts/spot.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAoB,MAAM,sBAAsB,CAAC;AAGnE,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE9C;;GAEG;AACH,eAAO,MAAM,gBAAgB,eAAsB,WAAW,yBAqB7D,CAAC"}