opentool 0.8.29 → 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.
package/README.md CHANGED
@@ -179,8 +179,7 @@ Test the payment flow:
179
179
  # Start dev server
180
180
  WALLET_ADDRESS=0x... npx opentool dev --input tools
181
181
 
182
- # Test with the x402 client
183
- PRIVATE_KEY=0x... bun examples/full-metadata/test-x402.ts
182
+ # Test with your x402 client/facilitator implementation
184
183
  ```
185
184
 
186
185
  Or test manually:
@@ -213,21 +212,20 @@ Tools without this export stay HTTP-only, which is useful when you want selectiv
213
212
 
214
213
  ### Testing with MCP Inspector
215
214
 
216
- The `examples/full-metadata` project has an `inspector.json` config ready to go:
215
+ You can run MCP Inspector against your local tool set:
217
216
 
218
217
  ```bash
219
- cd examples/full-metadata
220
- npx mcp-inspector --config inspector.json --server opentool-dev
218
+ npx mcp-inspector --server "npx opentool dev --input tools"
221
219
  ```
222
220
 
223
- Copy `.env.example` to `.env` and add your credentials if you're using wallet/payment features. The inspector starts `opentool dev` automatically, so you only need one terminal. Only tools with `mcp = { enabled: true }` show up in the inspector - HTTP-only tools keep running on localhost.
221
+ Only tools with `mcp = { enabled: true }` show up in the inspector - HTTP-only tools keep running on localhost.
224
222
 
225
223
  ### Quick x402 test with curl
226
224
 
227
- 1. Start the dev server against the example tools:
225
+ 1. Start the dev server:
228
226
 
229
227
  ```bash
230
- npx opentool dev --input examples/full-metadata/tools
228
+ npx opentool dev --input tools
231
229
  ```
232
230
 
233
231
  2. Trigger the paywall and inspect the returned payment requirements:
@@ -392,32 +390,14 @@ Push your repo to GitHub and connect it to [OpenPond](https://openpond.ai):
392
390
  3. Deploys to AWS Lambda with Function URLs
393
391
  4. Done - your tools are live
394
392
 
395
- ## Examples
393
+ ## Example Usage
396
394
 
397
- Check `examples/full-metadata/` for a complete example with payment and discovery features.
398
-
399
- ### Testing Examples Locally
395
+ Build your own tool folder (for example `tools/`) and run:
400
396
 
401
397
  ```bash
402
- # Build and link the OpenTool package
403
- npm run build
404
- npm link
405
-
406
- # Test the example
407
- cd examples/full-metadata
408
- npm link opentool
409
- npm run build
410
-
411
- # Check the output
412
- cat dist/metadata.json
413
-
414
- # Test the MCP server
415
- echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}' | node dist/mcp-server.js
416
-
417
- # Or from repo root:
418
- npm run examples:build # Build example (CJS+ESM)
419
- npm run examples:validate # Validate metadata and tools
420
- npm run examples:metadata # Regenerate metadata.json
398
+ npx opentool validate --input tools
399
+ npx opentool metadata --input tools --output metadata.json
400
+ npx opentool build --input tools --output dist
421
401
  ```
422
402
 
423
403
  ## Metadata System
@@ -481,6 +481,16 @@ type SpotMetaResponse = {
481
481
  universe?: SpotUniverseItem[];
482
482
  tokens?: SpotToken[];
483
483
  };
484
+ type HyperliquidBarResolution = "1" | "5" | "15" | "30" | "60" | "240" | "1D" | "1W";
485
+ type HyperliquidBar = {
486
+ time: number;
487
+ open?: number;
488
+ high?: number;
489
+ low?: number;
490
+ close: number;
491
+ volume?: number;
492
+ [key: string]: unknown;
493
+ };
484
494
  type HyperliquidPerpMarketInfo = {
485
495
  symbol: string;
486
496
  price: number;
@@ -500,6 +510,14 @@ declare function maxDecimals(values: string[]): number;
500
510
  declare function toScaledInt(value: string, decimals: number): bigint;
501
511
  declare function formatScaledInt(value: bigint, decimals: number): string;
502
512
  declare function fetchHyperliquidAllMids(environment: HyperliquidEnvironment): Promise<Record<string, string | number>>;
513
+ declare function fetchHyperliquidBars(params: {
514
+ symbol: string;
515
+ resolution: HyperliquidBarResolution;
516
+ countBack: number;
517
+ fromSeconds?: number;
518
+ toSeconds?: number;
519
+ gatewayBase?: string | null;
520
+ }): Promise<HyperliquidBar[]>;
503
521
  declare function fetchHyperliquidTickSize(params: {
504
522
  environment: HyperliquidEnvironment;
505
523
  symbol: string;
@@ -650,4 +668,4 @@ declare const __hyperliquidInternals: {
650
668
  splitSignature: typeof splitSignature;
651
669
  };
652
670
 
653
- export { DEFAULT_HYPERLIQUID_MARKET_SLIPPAGE_BPS, type HyperliquidAbstraction, type HyperliquidAccountMode, HyperliquidApiError, type HyperliquidApproveBuilderFeeOptions, type HyperliquidApproveBuilderFeeResponse, HyperliquidBuilderApprovalError, type HyperliquidBuilderApprovalRecordInput, type HyperliquidBuilderFee, type HyperliquidChain, type HyperliquidClearinghouseState, type HyperliquidDepositResult, type HyperliquidEnvironment, HyperliquidExchangeClient, type HyperliquidExchangeResponse, type HyperliquidGrouping, HyperliquidGuardError, HyperliquidInfoClient, type HyperliquidMarketIdentityInput, type HyperliquidMarketType, type HyperliquidOrderIntent, type HyperliquidOrderOptions, type HyperliquidOrderResponse, type HyperliquidOrderStatus, type HyperliquidPerpMarketInfo, type HyperliquidProfileAsset, type HyperliquidProfileAssetInput, type HyperliquidProfileChain, type HyperliquidSpotMarketInfo, type HyperliquidStoreNetwork, HyperliquidTermsError, type HyperliquidTermsRecordInput, type HyperliquidTickSize, type HyperliquidTimeInForce, type HyperliquidTriggerOptions, type HyperliquidTriggerType, type HyperliquidWithdrawResult, type MarketIdentity, type NonceSource, __hyperliquidInternals, __hyperliquidMarketDataInternals, approveHyperliquidBuilderFee, batchModifyHyperliquidOrders, buildHyperliquidMarketIdentity, buildHyperliquidProfileAssets, buildHyperliquidSpotUsdPriceMap, cancelAllHyperliquidOrders, cancelHyperliquidOrders, cancelHyperliquidOrdersByCloid, cancelHyperliquidTwapOrder, computeHyperliquidMarketIocLimitPrice, createHyperliquidSubAccount, createMonotonicNonceFactory, depositToHyperliquidBridge, extractHyperliquidDex, extractHyperliquidOrderIds, fetchHyperliquidAllMids, fetchHyperliquidAssetCtxs, fetchHyperliquidClearinghouseState, fetchHyperliquidFrontendOpenOrders, fetchHyperliquidHistoricalOrders, fetchHyperliquidMeta, fetchHyperliquidMetaAndAssetCtxs, fetchHyperliquidOpenOrders, fetchHyperliquidOrderStatus, fetchHyperliquidPerpMarketInfo, fetchHyperliquidPreTransferCheck, fetchHyperliquidSizeDecimals, fetchHyperliquidSpotAccountValue, fetchHyperliquidSpotAssetCtxs, fetchHyperliquidSpotClearinghouseState, fetchHyperliquidSpotMarketInfo, fetchHyperliquidSpotMeta, fetchHyperliquidSpotMetaAndAssetCtxs, fetchHyperliquidSpotTickSize, fetchHyperliquidSpotUsdPriceMap, fetchHyperliquidTickSize, fetchHyperliquidUserFills, fetchHyperliquidUserFillsByTime, fetchHyperliquidUserRateLimit, formatHyperliquidMarketablePrice, formatHyperliquidOrderSize, formatHyperliquidPrice, formatHyperliquidSize, getHyperliquidMaxBuilderFee, isHyperliquidSpotSymbol, modifyHyperliquidOrder, normalizeHyperliquidBaseSymbol, normalizeHyperliquidMetaSymbol, normalizeSpotTokenName, parseSpotPairSymbol, placeHyperliquidOrder, placeHyperliquidTwapOrder, readHyperliquidAccountValue, readHyperliquidNumber, readHyperliquidPerpPosition, readHyperliquidPerpPositionSize, readHyperliquidSpotAccountValue, readHyperliquidSpotBalance, readHyperliquidSpotBalanceSize, recordHyperliquidBuilderApproval, recordHyperliquidTermsAcceptance, reserveHyperliquidRequestWeight, resolveHyperliquidAbstractionFromMode, resolveHyperliquidChain, resolveHyperliquidChainConfig, resolveHyperliquidErrorDetail, resolveHyperliquidOrderRef, resolveHyperliquidOrderSymbol, resolveHyperliquidPair, resolveHyperliquidProfileChain, resolveHyperliquidRpcEnvVar, resolveHyperliquidStoreNetwork, resolveHyperliquidSymbol, resolveSpotMidCandidates, resolveSpotTokenCandidates, roundHyperliquidPriceToTick, scheduleHyperliquidCancel, sendHyperliquidSpot, setHyperliquidAccountAbstractionMode, setHyperliquidDexAbstraction, setHyperliquidPortfolioMargin, transferHyperliquidSubAccount, updateHyperliquidIsolatedMargin, updateHyperliquidLeverage, withdrawFromHyperliquid };
671
+ export { DEFAULT_HYPERLIQUID_MARKET_SLIPPAGE_BPS, type HyperliquidAbstraction, type HyperliquidAccountMode, HyperliquidApiError, type HyperliquidApproveBuilderFeeOptions, type HyperliquidApproveBuilderFeeResponse, type HyperliquidBar, type HyperliquidBarResolution, HyperliquidBuilderApprovalError, type HyperliquidBuilderApprovalRecordInput, type HyperliquidBuilderFee, type HyperliquidChain, type HyperliquidClearinghouseState, type HyperliquidDepositResult, type HyperliquidEnvironment, HyperliquidExchangeClient, type HyperliquidExchangeResponse, type HyperliquidGrouping, HyperliquidGuardError, HyperliquidInfoClient, type HyperliquidMarketIdentityInput, type HyperliquidMarketType, type HyperliquidOrderIntent, type HyperliquidOrderOptions, type HyperliquidOrderResponse, type HyperliquidOrderStatus, type HyperliquidPerpMarketInfo, type HyperliquidProfileAsset, type HyperliquidProfileAssetInput, type HyperliquidProfileChain, type HyperliquidSpotMarketInfo, type HyperliquidStoreNetwork, HyperliquidTermsError, type HyperliquidTermsRecordInput, type HyperliquidTickSize, type HyperliquidTimeInForce, type HyperliquidTriggerOptions, type HyperliquidTriggerType, type HyperliquidWithdrawResult, type MarketIdentity, type NonceSource, __hyperliquidInternals, __hyperliquidMarketDataInternals, approveHyperliquidBuilderFee, batchModifyHyperliquidOrders, buildHyperliquidMarketIdentity, buildHyperliquidProfileAssets, buildHyperliquidSpotUsdPriceMap, cancelAllHyperliquidOrders, cancelHyperliquidOrders, cancelHyperliquidOrdersByCloid, cancelHyperliquidTwapOrder, computeHyperliquidMarketIocLimitPrice, createHyperliquidSubAccount, createMonotonicNonceFactory, depositToHyperliquidBridge, extractHyperliquidDex, extractHyperliquidOrderIds, fetchHyperliquidAllMids, fetchHyperliquidAssetCtxs, fetchHyperliquidBars, fetchHyperliquidClearinghouseState, fetchHyperliquidFrontendOpenOrders, fetchHyperliquidHistoricalOrders, fetchHyperliquidMeta, fetchHyperliquidMetaAndAssetCtxs, fetchHyperliquidOpenOrders, fetchHyperliquidOrderStatus, fetchHyperliquidPerpMarketInfo, fetchHyperliquidPreTransferCheck, fetchHyperliquidSizeDecimals, fetchHyperliquidSpotAccountValue, fetchHyperliquidSpotAssetCtxs, fetchHyperliquidSpotClearinghouseState, fetchHyperliquidSpotMarketInfo, fetchHyperliquidSpotMeta, fetchHyperliquidSpotMetaAndAssetCtxs, fetchHyperliquidSpotTickSize, fetchHyperliquidSpotUsdPriceMap, fetchHyperliquidTickSize, fetchHyperliquidUserFills, fetchHyperliquidUserFillsByTime, fetchHyperliquidUserRateLimit, formatHyperliquidMarketablePrice, formatHyperliquidOrderSize, formatHyperliquidPrice, formatHyperliquidSize, getHyperliquidMaxBuilderFee, isHyperliquidSpotSymbol, modifyHyperliquidOrder, normalizeHyperliquidBaseSymbol, normalizeHyperliquidMetaSymbol, normalizeSpotTokenName, parseSpotPairSymbol, placeHyperliquidOrder, placeHyperliquidTwapOrder, readHyperliquidAccountValue, readHyperliquidNumber, readHyperliquidPerpPosition, readHyperliquidPerpPositionSize, readHyperliquidSpotAccountValue, readHyperliquidSpotBalance, readHyperliquidSpotBalanceSize, recordHyperliquidBuilderApproval, recordHyperliquidTermsAcceptance, reserveHyperliquidRequestWeight, resolveHyperliquidAbstractionFromMode, resolveHyperliquidChain, resolveHyperliquidChainConfig, resolveHyperliquidErrorDetail, resolveHyperliquidOrderRef, resolveHyperliquidOrderSymbol, resolveHyperliquidPair, resolveHyperliquidProfileChain, resolveHyperliquidRpcEnvVar, resolveHyperliquidStoreNetwork, resolveHyperliquidSymbol, resolveSpotMidCandidates, resolveSpotTokenCandidates, roundHyperliquidPriceToTick, scheduleHyperliquidCancel, sendHyperliquidSpot, setHyperliquidAccountAbstractionMode, setHyperliquidDexAbstraction, setHyperliquidPortfolioMargin, transferHyperliquidSubAccount, updateHyperliquidIsolatedMargin, updateHyperliquidLeverage, withdrawFromHyperliquid };
@@ -6,11 +6,7 @@ import { hexToBytes, concatBytes, bytesToHex } from '@noble/hashes/utils';
6
6
  // src/adapters/hyperliquid/index.ts
7
7
 
8
8
  // src/store/index.ts
9
- var STORE_EVENT_LEVELS = [
10
- "decision",
11
- "execution",
12
- "lifecycle"
13
- ];
9
+ var STORE_EVENT_LEVELS = ["decision", "execution", "lifecycle"];
14
10
  var STORE_EVENT_LEVEL_SET = new Set(STORE_EVENT_LEVELS);
15
11
  var MARKET_REQUIRED_ACTIONS = [
16
12
  "swap",
@@ -77,7 +73,7 @@ var resolveEventLevel = (input) => {
77
73
  return null;
78
74
  };
79
75
  var normalizeStoreInput = (input) => {
80
- const metadata = { ...input.metadata ?? {} };
76
+ const metadata = { ...input.metadata };
81
77
  const eventLevel = resolveEventLevel({ ...input, metadata });
82
78
  if (eventLevel) {
83
79
  metadata.eventLevel = eventLevel;
@@ -96,9 +92,7 @@ function resolveConfig(options) {
96
92
  throw new StoreError("BASE_URL is required to store activity events");
97
93
  }
98
94
  if (!apiKey) {
99
- throw new StoreError(
100
- "OPENPOND_API_KEY is required to store activity events"
101
- );
95
+ throw new StoreError("OPENPOND_API_KEY is required to store activity events");
102
96
  }
103
97
  const normalizedBaseUrl = baseUrl.replace(/\/$/, "");
104
98
  const fetchFn = options?.fetchFn ?? globalThis.fetch;
@@ -113,15 +107,11 @@ async function store(input, options) {
113
107
  const eventLevel = normalizedInput.eventLevel;
114
108
  const normalizedAction = normalizeAction(normalizedInput.action);
115
109
  if (mode === "backtest" && !normalizedInput.backtestRunId) {
116
- throw new StoreError(
117
- `backtestRunId is required when mode is "backtest"`
118
- );
110
+ throw new StoreError(`backtestRunId is required when mode is "backtest"`);
119
111
  }
120
112
  if (eventLevel === "execution" || eventLevel === "lifecycle") {
121
113
  if (!normalizedAction || !EXECUTION_ACTIONS_SET.has(normalizedAction)) {
122
- throw new StoreError(
123
- `eventLevel "${eventLevel}" requires an execution action`
124
- );
114
+ throw new StoreError(`eventLevel "${eventLevel}" requires an execution action`);
125
115
  }
126
116
  }
127
117
  if (eventLevel === "execution" && !hasMarketIdentity(normalizedInput.market)) {
@@ -375,9 +365,7 @@ async function getUniverse(args) {
375
365
  const response = await args.fetcher(`${args.baseUrl}/info`, {
376
366
  method: "POST",
377
367
  headers: { "content-type": "application/json" },
378
- body: JSON.stringify(
379
- dexKey ? { type: "meta", dex: dexKey } : { type: "meta" }
380
- )
368
+ body: JSON.stringify(dexKey ? { type: "meta", dex: dexKey } : { type: "meta" })
381
369
  });
382
370
  const json = await response.json().catch(() => null);
383
371
  if (!response.ok || !json?.universe) {
@@ -415,9 +403,7 @@ async function getSpotMeta(args) {
415
403
  function resolveAssetIndex(symbol, universe) {
416
404
  const [raw] = symbol.split("-");
417
405
  const target = raw.trim();
418
- const index = universe.findIndex(
419
- (entry) => entry.name.toUpperCase() === target.toUpperCase()
420
- );
406
+ const index = universe.findIndex((entry) => entry.name.toUpperCase() === target.toUpperCase());
421
407
  if (index === -1) {
422
408
  throw new Error(`Unknown Hyperliquid asset symbol: ${symbol}`);
423
409
  }
@@ -447,9 +433,7 @@ async function getPerpDexs(args) {
447
433
  async function resolveDexIndex(args) {
448
434
  const dexs = await getPerpDexs(args);
449
435
  const target = args.dex.trim().toLowerCase();
450
- const index = dexs.findIndex(
451
- (entry) => entry?.name?.toLowerCase() === target
452
- );
436
+ const index = dexs.findIndex((entry) => entry?.name?.toLowerCase() === target);
453
437
  if (index === -1) {
454
438
  throw new Error(`Unknown Hyperliquid perp dex: ${args.dex}`);
455
439
  }
@@ -636,15 +620,7 @@ async function signL1Action(args) {
636
620
  return splitSignature(signatureHex);
637
621
  }
638
622
  async function signSpotSend(args) {
639
- const {
640
- wallet,
641
- hyperliquidChain,
642
- signatureChainId,
643
- destination,
644
- token,
645
- amount,
646
- time
647
- } = args;
623
+ const { wallet, hyperliquidChain, signatureChainId, destination, token, amount, time } = args;
648
624
  const domain = {
649
625
  name: "HyperliquidSignTransaction",
650
626
  version: "1",
@@ -1053,9 +1029,7 @@ var HyperliquidExchangeClient = class {
1053
1029
  this.expiresAfter = args.expiresAfter;
1054
1030
  const resolvedNonceSource = args.walletNonceProvider ?? args.wallet.nonceSource ?? args.nonceSource;
1055
1031
  if (!resolvedNonceSource) {
1056
- throw new Error(
1057
- "Wallet nonce source is required for Hyperliquid exchange actions."
1058
- );
1032
+ throw new Error("Wallet nonce source is required for Hyperliquid exchange actions.");
1059
1033
  }
1060
1034
  this.nonceSource = resolvedNonceSource;
1061
1035
  }
@@ -1185,9 +1159,7 @@ var HyperliquidExchangeClient = class {
1185
1159
  expiresAfter: this.expiresAfter,
1186
1160
  nonceSource: this.nonceSource
1187
1161
  };
1188
- return setHyperliquidDexAbstraction(
1189
- params.user ? { ...base, user: params.user } : base
1190
- );
1162
+ return setHyperliquidDexAbstraction(params.user ? { ...base, user: params.user } : base);
1191
1163
  }
1192
1164
  setAccountAbstractionMode(params) {
1193
1165
  const base = {
@@ -1211,24 +1183,18 @@ var HyperliquidExchangeClient = class {
1211
1183
  expiresAfter: this.expiresAfter,
1212
1184
  nonceSource: this.nonceSource
1213
1185
  };
1214
- return setHyperliquidPortfolioMargin(
1215
- params.user ? { ...base, user: params.user } : base
1216
- );
1186
+ return setHyperliquidPortfolioMargin(params.user ? { ...base, user: params.user } : base);
1217
1187
  }
1218
1188
  };
1219
1189
  async function setHyperliquidPortfolioMargin(options) {
1220
1190
  const env = options.environment ?? "mainnet";
1221
1191
  if (!options.wallet?.account || !options.wallet.walletClient) {
1222
- throw new Error(
1223
- "Wallet with signing capability is required for portfolio margin."
1224
- );
1192
+ throw new Error("Wallet with signing capability is required for portfolio margin.");
1225
1193
  }
1226
1194
  const nonce = options.nonce ?? options.walletNonceProvider?.() ?? options.wallet.nonceSource?.() ?? options.nonceSource?.() ?? Date.now();
1227
1195
  const signatureChainId = getSignatureChainId(env);
1228
1196
  const hyperliquidChain = HL_CHAIN_LABEL[env];
1229
- const user = normalizeAddress(
1230
- options.user ?? options.wallet.address
1231
- );
1197
+ const user = normalizeAddress(options.user ?? options.wallet.address);
1232
1198
  const action = {
1233
1199
  type: "userPortfolioMargin",
1234
1200
  enabled: Boolean(options.enabled),
@@ -1257,16 +1223,12 @@ async function setHyperliquidPortfolioMargin(options) {
1257
1223
  async function setHyperliquidDexAbstraction(options) {
1258
1224
  const env = options.environment ?? "mainnet";
1259
1225
  if (!options.wallet?.account || !options.wallet.walletClient) {
1260
- throw new Error(
1261
- "Wallet with signing capability is required for dex abstraction."
1262
- );
1226
+ throw new Error("Wallet with signing capability is required for dex abstraction.");
1263
1227
  }
1264
1228
  const nonce = options.nonce ?? options.walletNonceProvider?.() ?? options.wallet.nonceSource?.() ?? options.nonceSource?.() ?? Date.now();
1265
1229
  const signatureChainId = getSignatureChainId(env);
1266
1230
  const hyperliquidChain = HL_CHAIN_LABEL[env];
1267
- const user = normalizeAddress(
1268
- options.user ?? options.wallet.address
1269
- );
1231
+ const user = normalizeAddress(options.user ?? options.wallet.address);
1270
1232
  const action = {
1271
1233
  type: "userDexAbstraction",
1272
1234
  enabled: Boolean(options.enabled),
@@ -1295,16 +1257,12 @@ async function setHyperliquidDexAbstraction(options) {
1295
1257
  async function setHyperliquidAccountAbstractionMode(options) {
1296
1258
  const env = options.environment ?? "mainnet";
1297
1259
  if (!options.wallet?.account || !options.wallet.walletClient) {
1298
- throw new Error(
1299
- "Wallet with signing capability is required for account abstraction mode."
1300
- );
1260
+ throw new Error("Wallet with signing capability is required for account abstraction mode.");
1301
1261
  }
1302
1262
  const nonce = options.nonce ?? options.walletNonceProvider?.() ?? options.wallet.nonceSource?.() ?? options.nonceSource?.() ?? Date.now();
1303
1263
  const signatureChainId = getSignatureChainId(env);
1304
1264
  const hyperliquidChain = HL_CHAIN_LABEL[env];
1305
- const user = normalizeAddress(
1306
- options.user ?? options.wallet.address
1307
- );
1265
+ const user = normalizeAddress(options.user ?? options.wallet.address);
1308
1266
  const abstraction = resolveHyperliquidAbstractionFromMode(options.mode);
1309
1267
  const action = {
1310
1268
  type: "userSetAbstraction",
@@ -1346,14 +1304,10 @@ async function cancelHyperliquidOrdersByCloid(options) {
1346
1304
  options.cancels.forEach((c) => assertSymbol(c.symbol));
1347
1305
  const action = {
1348
1306
  type: "cancelByCloid",
1349
- cancels: await withAssetIndexes(
1350
- options,
1351
- options.cancels,
1352
- (idx, entry) => ({
1353
- asset: idx,
1354
- cloid: normalizeCloid(entry.cloid)
1355
- })
1356
- )
1307
+ cancels: await withAssetIndexes(options, options.cancels, (idx, entry) => ({
1308
+ asset: idx,
1309
+ cloid: normalizeCloid(entry.cloid)
1310
+ }))
1357
1311
  };
1358
1312
  return submitExchangeAction(options, action);
1359
1313
  }
@@ -2235,6 +2189,28 @@ function readHyperliquidSpotAccountValue(params) {
2235
2189
  // src/adapters/hyperliquid/market-data.ts
2236
2190
  var META_CACHE_TTL_MS = 5 * 60 * 1e3;
2237
2191
  var allMidsCache = /* @__PURE__ */ new Map();
2192
+ function resolveGatewayBase(override) {
2193
+ const value = override ?? process.env.OPENPOND_GATEWAY_URL ?? null;
2194
+ if (typeof value !== "string") {
2195
+ return null;
2196
+ }
2197
+ const trimmed = value.trim();
2198
+ if (!trimmed) {
2199
+ return null;
2200
+ }
2201
+ return trimmed.replace(/\/$/, "");
2202
+ }
2203
+ function normalizeGatewaySymbol(value) {
2204
+ const trimmed = value.trim();
2205
+ if (!trimmed) return trimmed;
2206
+ const idx = trimmed.indexOf(":");
2207
+ if (idx > 0) {
2208
+ const dex = trimmed.slice(0, idx).toLowerCase();
2209
+ const rest = trimmed.slice(idx + 1);
2210
+ return `${dex}:${rest.toUpperCase()}`;
2211
+ }
2212
+ return trimmed.toUpperCase();
2213
+ }
2238
2214
  function gcd(a, b) {
2239
2215
  let left = a < 0n ? -a : a;
2240
2216
  let right = b < 0n ? -b : b;
@@ -2282,10 +2258,7 @@ function formatScaledInt(value, decimals) {
2282
2258
  return `${negative ? "-" : ""}${integer.toString()}`;
2283
2259
  }
2284
2260
  const fractionStr = fraction.toString().padStart(decimals, "0");
2285
- return `${negative ? "-" : ""}${integer.toString()}.${fractionStr}`.replace(
2286
- /\.?0+$/,
2287
- ""
2288
- );
2261
+ return `${negative ? "-" : ""}${integer.toString()}.${fractionStr}`.replace(/\.?0+$/, "");
2289
2262
  }
2290
2263
  function resolveSpotSizeDecimals(meta, symbol) {
2291
2264
  const universe = meta.universe ?? [];
@@ -2355,6 +2328,37 @@ async function fetchHyperliquidAllMids(environment) {
2355
2328
  allMidsCache.set(cacheKey, { fetchedAt: Date.now(), mids: json });
2356
2329
  return json;
2357
2330
  }
2331
+ async function fetchHyperliquidBars(params) {
2332
+ const gatewayBase = resolveGatewayBase(params.gatewayBase);
2333
+ if (!gatewayBase) {
2334
+ throw new Error("OPENPOND_GATEWAY_URL is required.");
2335
+ }
2336
+ const normalizedCountBack = Math.max(1, Math.trunc(params.countBack));
2337
+ if (!Number.isFinite(normalizedCountBack) || normalizedCountBack <= 0) {
2338
+ throw new Error("countBack must be a positive integer.");
2339
+ }
2340
+ const url = new URL(`${gatewayBase}/v1/hyperliquid/bars`);
2341
+ url.searchParams.set("symbol", normalizeGatewaySymbol(params.symbol));
2342
+ url.searchParams.set("resolution", params.resolution);
2343
+ url.searchParams.set("countBack", normalizedCountBack.toString());
2344
+ if (typeof params.fromSeconds === "number" && Number.isFinite(params.fromSeconds)) {
2345
+ url.searchParams.set("from", Math.max(0, Math.trunc(params.fromSeconds)).toString());
2346
+ }
2347
+ if (typeof params.toSeconds === "number" && Number.isFinite(params.toSeconds)) {
2348
+ url.searchParams.set("to", Math.max(0, Math.trunc(params.toSeconds)).toString());
2349
+ }
2350
+ const response = await fetch(url.toString());
2351
+ if (!response.ok) {
2352
+ throw new Error(`Gateway error (${response.status})`);
2353
+ }
2354
+ const data = await response.json().catch(() => null);
2355
+ const bars = Array.isArray(data?.bars) ? data.bars : [];
2356
+ return bars.filter((bar) => {
2357
+ if (!bar || typeof bar !== "object") return false;
2358
+ const record = bar;
2359
+ return typeof record.close === "number" && Number.isFinite(record.close) && typeof record.time === "number" && Number.isFinite(record.time);
2360
+ });
2361
+ }
2358
2362
  async function fetchHyperliquidTickSize(params) {
2359
2363
  return fetchHyperliquidTickSizeForCoin(params.environment, params.symbol);
2360
2364
  }
@@ -2362,10 +2366,7 @@ async function fetchHyperliquidSpotTickSize(params) {
2362
2366
  if (!Number.isFinite(params.marketIndex)) {
2363
2367
  throw new Error("Hyperliquid spot market index is invalid.");
2364
2368
  }
2365
- return fetchHyperliquidTickSizeForCoin(
2366
- params.environment,
2367
- `@${params.marketIndex}`
2368
- );
2369
+ return fetchHyperliquidTickSizeForCoin(params.environment, `@${params.marketIndex}`);
2369
2370
  }
2370
2371
  async function fetchHyperliquidTickSizeForCoin(environment, coin) {
2371
2372
  const base = API_BASES[environment];
@@ -2379,9 +2380,7 @@ async function fetchHyperliquidTickSizeForCoin(environment, coin) {
2379
2380
  }
2380
2381
  const data = await res.json().catch(() => null);
2381
2382
  const levels = Array.isArray(data?.levels) ? data?.levels ?? [] : [];
2382
- const prices = levels.flatMap(
2383
- (side) => Array.isArray(side) ? side.map((entry) => String(entry?.px ?? "")) : []
2384
- ).filter((px) => px.length > 0);
2383
+ const prices = levels.flatMap((side) => Array.isArray(side) ? side.map((entry) => String(entry?.px ?? "")) : []).filter((px) => px.length > 0);
2385
2384
  if (prices.length < 2) {
2386
2385
  throw new Error(`Hyperliquid l2Book missing price levels for ${coin}`);
2387
2386
  }
@@ -2472,9 +2471,7 @@ async function fetchHyperliquidSpotMarketInfo(params) {
2472
2471
  price = readHyperliquidNumber(ctx?.markPx ?? ctx?.midPx ?? ctx?.oraclePx);
2473
2472
  }
2474
2473
  if (!price || price <= 0) {
2475
- throw new Error(
2476
- `No spot price available for ${normalizedBase}/${normalizedQuote}`
2477
- );
2474
+ throw new Error(`No spot price available for ${normalizedBase}/${normalizedQuote}`);
2478
2475
  }
2479
2476
  const marketIndex = typeof market?.index === "number" ? market.index : idx;
2480
2477
  return {
@@ -2624,9 +2621,7 @@ async function placeHyperliquidOrder(options) {
2624
2621
  } = options;
2625
2622
  const effectiveBuilder = BUILDER_CODE;
2626
2623
  if (!wallet?.account || !wallet.walletClient) {
2627
- throw new Error(
2628
- "Hyperliquid order signing requires a wallet with signing capabilities."
2629
- );
2624
+ throw new Error("Hyperliquid order signing requires a wallet with signing capabilities.");
2630
2625
  }
2631
2626
  if (!orders.length) {
2632
2627
  throw new Error("At least one order is required.");
@@ -2740,10 +2735,7 @@ async function placeHyperliquidOrder(options) {
2740
2735
  );
2741
2736
  if (errorStatuses.length) {
2742
2737
  const message = errorStatuses.map((entry) => entry.error).join(", ");
2743
- throw new HyperliquidApiError(
2744
- message || "Hyperliquid rejected the order.",
2745
- json
2746
- );
2738
+ throw new HyperliquidApiError(message || "Hyperliquid rejected the order.", json);
2747
2739
  }
2748
2740
  return json;
2749
2741
  }
@@ -2763,9 +2755,7 @@ async function depositToHyperliquidBridge(options) {
2763
2755
  const usdcAddress = getUsdcAddress(environment);
2764
2756
  const amountUnits = parseUnits(amount, 6);
2765
2757
  if (!wallet.walletClient || !wallet.publicClient) {
2766
- throw new Error(
2767
- "Wallet client and public client are required for deposit."
2768
- );
2758
+ throw new Error("Wallet client and public client are required for deposit.");
2769
2759
  }
2770
2760
  const walletClient = wallet.walletClient;
2771
2761
  const publicClient = wallet.publicClient;
@@ -2790,15 +2780,10 @@ async function depositToHyperliquidBridge(options) {
2790
2780
  }
2791
2781
  async function withdrawFromHyperliquid(options) {
2792
2782
  const { environment, amount, destination, wallet } = options;
2793
- const normalizedAmount = normalizePositiveDecimalString(
2794
- amount,
2795
- "Withdraw amount"
2796
- );
2783
+ const normalizedAmount = normalizePositiveDecimalString(amount, "Withdraw amount");
2797
2784
  const parsedAmount = Number.parseFloat(normalizedAmount);
2798
2785
  if (!wallet.account || !wallet.walletClient || !wallet.publicClient) {
2799
- throw new Error(
2800
- "Wallet client and public client are required for withdraw."
2801
- );
2786
+ throw new Error("Wallet client and public client are required for withdraw.");
2802
2787
  }
2803
2788
  const signatureChainId = getSignatureChainId(environment);
2804
2789
  const hyperliquidChain = HL_CHAIN_LABEL[environment];
@@ -2881,9 +2866,7 @@ async function fetchHyperliquidClearinghouseState(params) {
2881
2866
  async function approveHyperliquidBuilderFee(options) {
2882
2867
  const { environment, wallet, nonce, signatureChainId } = options;
2883
2868
  if (!wallet?.account || !wallet.walletClient) {
2884
- throw new Error(
2885
- "Hyperliquid builder approval requires a wallet with signing capabilities."
2886
- );
2869
+ throw new Error("Hyperliquid builder approval requires a wallet with signing capabilities.");
2887
2870
  }
2888
2871
  const maxFeeRateValue = BUILDER_CODE.fee / 1e3;
2889
2872
  const formattedPercent = `${maxFeeRateValue}%`;
@@ -3009,6 +2992,6 @@ var __hyperliquidInternals = {
3009
2992
  splitSignature
3010
2993
  };
3011
2994
 
3012
- export { DEFAULT_HYPERLIQUID_MARKET_SLIPPAGE_BPS, HyperliquidApiError, HyperliquidBuilderApprovalError, HyperliquidExchangeClient, HyperliquidGuardError, HyperliquidInfoClient, HyperliquidTermsError, __hyperliquidInternals, __hyperliquidMarketDataInternals, approveHyperliquidBuilderFee, batchModifyHyperliquidOrders, buildHyperliquidMarketIdentity, buildHyperliquidProfileAssets, buildHyperliquidSpotUsdPriceMap, cancelAllHyperliquidOrders, cancelHyperliquidOrders, cancelHyperliquidOrdersByCloid, cancelHyperliquidTwapOrder, computeHyperliquidMarketIocLimitPrice, createHyperliquidSubAccount, createMonotonicNonceFactory, depositToHyperliquidBridge, extractHyperliquidDex, extractHyperliquidOrderIds, fetchHyperliquidAllMids, fetchHyperliquidAssetCtxs, fetchHyperliquidClearinghouseState, fetchHyperliquidFrontendOpenOrders, fetchHyperliquidHistoricalOrders, fetchHyperliquidMeta, fetchHyperliquidMetaAndAssetCtxs, fetchHyperliquidOpenOrders, fetchHyperliquidOrderStatus, fetchHyperliquidPerpMarketInfo, fetchHyperliquidPreTransferCheck, fetchHyperliquidSizeDecimals, fetchHyperliquidSpotAccountValue, fetchHyperliquidSpotAssetCtxs, fetchHyperliquidSpotClearinghouseState, fetchHyperliquidSpotMarketInfo, fetchHyperliquidSpotMeta, fetchHyperliquidSpotMetaAndAssetCtxs, fetchHyperliquidSpotTickSize, fetchHyperliquidSpotUsdPriceMap, fetchHyperliquidTickSize, fetchHyperliquidUserFills, fetchHyperliquidUserFillsByTime, fetchHyperliquidUserRateLimit, formatHyperliquidMarketablePrice, formatHyperliquidOrderSize, formatHyperliquidPrice, formatHyperliquidSize, getHyperliquidMaxBuilderFee, isHyperliquidSpotSymbol, modifyHyperliquidOrder, normalizeHyperliquidBaseSymbol, normalizeHyperliquidMetaSymbol, normalizeSpotTokenName2 as normalizeSpotTokenName, parseSpotPairSymbol, placeHyperliquidOrder, placeHyperliquidTwapOrder, readHyperliquidAccountValue, readHyperliquidNumber, readHyperliquidPerpPosition, readHyperliquidPerpPositionSize, readHyperliquidSpotAccountValue, readHyperliquidSpotBalance, readHyperliquidSpotBalanceSize, recordHyperliquidBuilderApproval, recordHyperliquidTermsAcceptance, reserveHyperliquidRequestWeight, resolveHyperliquidAbstractionFromMode, resolveHyperliquidChain, resolveHyperliquidChainConfig, resolveHyperliquidErrorDetail, resolveHyperliquidOrderRef, resolveHyperliquidOrderSymbol, resolveHyperliquidPair, resolveHyperliquidProfileChain, resolveHyperliquidRpcEnvVar, resolveHyperliquidStoreNetwork, resolveHyperliquidSymbol, resolveSpotMidCandidates, resolveSpotTokenCandidates, roundHyperliquidPriceToTick, scheduleHyperliquidCancel, sendHyperliquidSpot, setHyperliquidAccountAbstractionMode, setHyperliquidDexAbstraction, setHyperliquidPortfolioMargin, transferHyperliquidSubAccount, updateHyperliquidIsolatedMargin, updateHyperliquidLeverage, withdrawFromHyperliquid };
2995
+ export { DEFAULT_HYPERLIQUID_MARKET_SLIPPAGE_BPS, HyperliquidApiError, HyperliquidBuilderApprovalError, HyperliquidExchangeClient, HyperliquidGuardError, HyperliquidInfoClient, HyperliquidTermsError, __hyperliquidInternals, __hyperliquidMarketDataInternals, approveHyperliquidBuilderFee, batchModifyHyperliquidOrders, buildHyperliquidMarketIdentity, buildHyperliquidProfileAssets, buildHyperliquidSpotUsdPriceMap, cancelAllHyperliquidOrders, cancelHyperliquidOrders, cancelHyperliquidOrdersByCloid, cancelHyperliquidTwapOrder, computeHyperliquidMarketIocLimitPrice, createHyperliquidSubAccount, createMonotonicNonceFactory, depositToHyperliquidBridge, extractHyperliquidDex, extractHyperliquidOrderIds, fetchHyperliquidAllMids, fetchHyperliquidAssetCtxs, fetchHyperliquidBars, fetchHyperliquidClearinghouseState, fetchHyperliquidFrontendOpenOrders, fetchHyperliquidHistoricalOrders, fetchHyperliquidMeta, fetchHyperliquidMetaAndAssetCtxs, fetchHyperliquidOpenOrders, fetchHyperliquidOrderStatus, fetchHyperliquidPerpMarketInfo, fetchHyperliquidPreTransferCheck, fetchHyperliquidSizeDecimals, fetchHyperliquidSpotAccountValue, fetchHyperliquidSpotAssetCtxs, fetchHyperliquidSpotClearinghouseState, fetchHyperliquidSpotMarketInfo, fetchHyperliquidSpotMeta, fetchHyperliquidSpotMetaAndAssetCtxs, fetchHyperliquidSpotTickSize, fetchHyperliquidSpotUsdPriceMap, fetchHyperliquidTickSize, fetchHyperliquidUserFills, fetchHyperliquidUserFillsByTime, fetchHyperliquidUserRateLimit, formatHyperliquidMarketablePrice, formatHyperliquidOrderSize, formatHyperliquidPrice, formatHyperliquidSize, getHyperliquidMaxBuilderFee, isHyperliquidSpotSymbol, modifyHyperliquidOrder, normalizeHyperliquidBaseSymbol, normalizeHyperliquidMetaSymbol, normalizeSpotTokenName2 as normalizeSpotTokenName, parseSpotPairSymbol, placeHyperliquidOrder, placeHyperliquidTwapOrder, readHyperliquidAccountValue, readHyperliquidNumber, readHyperliquidPerpPosition, readHyperliquidPerpPositionSize, readHyperliquidSpotAccountValue, readHyperliquidSpotBalance, readHyperliquidSpotBalanceSize, recordHyperliquidBuilderApproval, recordHyperliquidTermsAcceptance, reserveHyperliquidRequestWeight, resolveHyperliquidAbstractionFromMode, resolveHyperliquidChain, resolveHyperliquidChainConfig, resolveHyperliquidErrorDetail, resolveHyperliquidOrderRef, resolveHyperliquidOrderSymbol, resolveHyperliquidPair, resolveHyperliquidProfileChain, resolveHyperliquidRpcEnvVar, resolveHyperliquidStoreNetwork, resolveHyperliquidSymbol, resolveSpotMidCandidates, resolveSpotTokenCandidates, roundHyperliquidPriceToTick, scheduleHyperliquidCancel, sendHyperliquidSpot, setHyperliquidAccountAbstractionMode, setHyperliquidDexAbstraction, setHyperliquidPortfolioMargin, transferHyperliquidSubAccount, updateHyperliquidIsolatedMargin, updateHyperliquidLeverage, withdrawFromHyperliquid };
3013
2996
  //# sourceMappingURL=index.js.map
3014
2997
  //# sourceMappingURL=index.js.map