opentool 0.8.1 → 0.8.4

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/dist/index.js CHANGED
@@ -14,6 +14,7 @@ import { createAccount } from '@turnkey/viem';
14
14
  import { encode } from '@msgpack/msgpack';
15
15
  import { keccak_256 } from '@noble/hashes/sha3';
16
16
  import { hexToBytes, concatBytes, bytesToHex } from '@noble/hashes/utils';
17
+ import { createHmac, randomBytes } from 'crypto';
17
18
  import { tmpdir } from 'os';
18
19
  import { build } from 'esbuild';
19
20
  import { createRequire } from 'module';
@@ -1479,6 +1480,29 @@ async function createTurnkeyProvider(config) {
1479
1480
  };
1480
1481
  }
1481
1482
 
1483
+ // src/wallet/env.ts
1484
+ function readTrimmed(name) {
1485
+ const value = process.env[name];
1486
+ const trimmed = typeof value === "string" ? value.trim() : "";
1487
+ return trimmed.length ? trimmed : void 0;
1488
+ }
1489
+ function readTurnkeyEnv() {
1490
+ const suborgId = readTrimmed("TURNKEY_SUBORG_ID");
1491
+ if (!suborgId) return void 0;
1492
+ const apiPublicKey = readTrimmed("TURNKEY_API_PUBLIC_KEY");
1493
+ const apiPrivateKey = readTrimmed("TURNKEY_API_PRIVATE_KEY");
1494
+ const signWith = readTrimmed("TURNKEY_WALLET_ADDRESS");
1495
+ if (!apiPublicKey || !apiPrivateKey || !signWith) return void 0;
1496
+ const apiBaseUrl = readTrimmed("TURNKEY_API_BASE_URL");
1497
+ return {
1498
+ organizationId: suborgId,
1499
+ apiPublicKey,
1500
+ apiPrivateKey,
1501
+ signWith,
1502
+ ...apiBaseUrl ? { apiBaseUrl } : {}
1503
+ };
1504
+ }
1505
+
1482
1506
  // src/wallet/index.ts
1483
1507
  function resolveChainSlug(reference) {
1484
1508
  if (reference === void 0) {
@@ -1522,22 +1546,9 @@ function getRpcUrl(chain, options) {
1522
1546
  }
1523
1547
  async function wallet(options = {}) {
1524
1548
  const envPrivateKey = process.env.PRIVATE_KEY?.trim();
1525
- const envTurnkey = {
1526
- organizationId: process.env.TURNKEY_SUBORG_ID?.trim(),
1527
- apiPublicKey: process.env.TURNKEY_API_PUBLIC_KEY?.trim(),
1528
- apiPrivateKey: process.env.TURNKEY_API_PRIVATE_KEY?.trim(),
1529
- signWith: process.env.TURNKEY_WALLET_ADDRESS?.trim(),
1530
- apiBaseUrl: process.env.TURNKEY_API_BASE_URL?.trim()
1531
- };
1549
+ const envTurnkey = readTurnkeyEnv();
1532
1550
  const effectivePrivateKey = options.privateKey ?? envPrivateKey;
1533
- const hasTurnkeyEnv = envTurnkey.organizationId && envTurnkey.apiPublicKey && envTurnkey.apiPrivateKey && envTurnkey.signWith;
1534
- const effectiveTurnkey = options.turnkey ?? (hasTurnkeyEnv ? {
1535
- organizationId: envTurnkey.organizationId,
1536
- apiPublicKey: envTurnkey.apiPublicKey,
1537
- apiPrivateKey: envTurnkey.apiPrivateKey,
1538
- signWith: envTurnkey.signWith,
1539
- ...envTurnkey.apiBaseUrl ? { apiBaseUrl: envTurnkey.apiBaseUrl } : {}
1540
- } : void 0);
1551
+ const effectiveTurnkey = options.turnkey ?? envTurnkey;
1541
1552
  if (effectivePrivateKey && effectiveTurnkey) {
1542
1553
  throw new Error("wallet() cannot be initialized with both privateKey and turnkey credentials");
1543
1554
  }
@@ -1639,6 +1650,38 @@ function resolveConfig(options) {
1639
1650
  }
1640
1651
  return { baseUrl: normalizedBaseUrl, apiKey, fetchFn };
1641
1652
  }
1653
+ async function requestJson(url, options, init) {
1654
+ const { apiKey, fetchFn } = resolveConfig(options);
1655
+ const response = await fetchFn(url, {
1656
+ ...init,
1657
+ headers: {
1658
+ "content-type": "application/json",
1659
+ "openpond-api-key": apiKey,
1660
+ ...init.headers ?? {}
1661
+ }
1662
+ });
1663
+ if (!response.ok) {
1664
+ let body;
1665
+ try {
1666
+ body = await response.json();
1667
+ } catch {
1668
+ body = await response.text().catch(() => void 0);
1669
+ }
1670
+ throw new StoreError(
1671
+ `Request failed with status ${response.status}`,
1672
+ response.status,
1673
+ body
1674
+ );
1675
+ }
1676
+ if (response.status === 204) {
1677
+ return null;
1678
+ }
1679
+ try {
1680
+ return await response.json();
1681
+ } catch {
1682
+ return await response.text().catch(() => null);
1683
+ }
1684
+ }
1642
1685
  async function store(input, options) {
1643
1686
  const { baseUrl, apiKey, fetchFn } = resolveConfig(options);
1644
1687
  const url = `${baseUrl}/apps/positions/tx`;
@@ -1721,6 +1764,34 @@ async function retrieve(params, options) {
1721
1764
  }
1722
1765
  return data;
1723
1766
  }
1767
+ async function getMyTools(options) {
1768
+ const { baseUrl } = resolveConfig(options);
1769
+ const url = `${baseUrl}/apps/tools`;
1770
+ const data = await requestJson(url, options, { method: "GET" });
1771
+ return data;
1772
+ }
1773
+ async function getMyPerformance(options) {
1774
+ const { baseUrl } = resolveConfig(options);
1775
+ const url = `${baseUrl}/apps/performance`;
1776
+ return requestJson(url, options, { method: "GET" });
1777
+ }
1778
+ async function postAgentDigest(input, options) {
1779
+ const { baseUrl } = resolveConfig(options);
1780
+ const url = `${baseUrl}/apps/agent/digest`;
1781
+ return requestJson(url, options, {
1782
+ method: "POST",
1783
+ body: JSON.stringify(input)
1784
+ });
1785
+ }
1786
+ async function executeTool(input, options) {
1787
+ const { baseUrl } = resolveConfig(options);
1788
+ const url = `${baseUrl}/apps/tools/execute`;
1789
+ const data = await requestJson(url, options, {
1790
+ method: "POST",
1791
+ body: JSON.stringify(input)
1792
+ });
1793
+ return data;
1794
+ }
1724
1795
  var CACHE_TTL_MS = 5 * 60 * 1e3;
1725
1796
  var API_BASES = {
1726
1797
  mainnet: "https://api.hyperliquid.xyz",
@@ -1957,6 +2028,37 @@ async function signApproveBuilderFee(args) {
1957
2028
  });
1958
2029
  return splitSignature(signatureHex);
1959
2030
  }
2031
+ async function signUserPortfolioMargin(args) {
2032
+ const { wallet: wallet2, action } = args;
2033
+ const domain = {
2034
+ name: "HyperliquidSignTransaction",
2035
+ version: "1",
2036
+ chainId: Number.parseInt(action.signatureChainId, 16),
2037
+ verifyingContract: ZERO_ADDRESS
2038
+ };
2039
+ const message = {
2040
+ enabled: action.enabled,
2041
+ hyperliquidChain: action.hyperliquidChain,
2042
+ user: action.user,
2043
+ nonce: BigInt(action.nonce)
2044
+ };
2045
+ const types = {
2046
+ "HyperliquidTransaction:UserPortfolioMargin": [
2047
+ { name: "enabled", type: "bool" },
2048
+ { name: "hyperliquidChain", type: "string" },
2049
+ { name: "user", type: "address" },
2050
+ { name: "nonce", type: "uint64" }
2051
+ ]
2052
+ };
2053
+ const signatureHex = await wallet2.walletClient.signTypedData({
2054
+ account: wallet2.account,
2055
+ domain,
2056
+ types,
2057
+ primaryType: "HyperliquidTransaction:UserPortfolioMargin",
2058
+ message
2059
+ });
2060
+ return splitSignature(signatureHex);
2061
+ }
1960
2062
  function splitSignature(signature) {
1961
2063
  const cleaned = signature.slice(2);
1962
2064
  const rHex = `0x${cleaned.slice(0, 64)}`;
@@ -2025,6 +2127,181 @@ function assertPositiveNumber(value, label) {
2025
2127
  }
2026
2128
  }
2027
2129
 
2130
+ // src/adapters/hyperliquid/info.ts
2131
+ async function postInfo(environment, payload) {
2132
+ const baseUrl = API_BASES[environment];
2133
+ const response = await fetch(`${baseUrl}/info`, {
2134
+ method: "POST",
2135
+ headers: { "content-type": "application/json" },
2136
+ body: JSON.stringify(payload)
2137
+ });
2138
+ const data = await response.json().catch(() => null);
2139
+ if (!response.ok) {
2140
+ throw new HyperliquidApiError(
2141
+ "Hyperliquid info request failed.",
2142
+ data ?? { status: response.status }
2143
+ );
2144
+ }
2145
+ return data;
2146
+ }
2147
+ var HyperliquidInfoClient = class {
2148
+ constructor(environment = "mainnet") {
2149
+ this.environment = environment;
2150
+ }
2151
+ meta() {
2152
+ return fetchHyperliquidMeta(this.environment);
2153
+ }
2154
+ metaAndAssetCtxs() {
2155
+ return fetchHyperliquidMetaAndAssetCtxs(this.environment);
2156
+ }
2157
+ spotMeta() {
2158
+ return fetchHyperliquidSpotMeta(this.environment);
2159
+ }
2160
+ spotMetaAndAssetCtxs() {
2161
+ return fetchHyperliquidSpotMetaAndAssetCtxs(this.environment);
2162
+ }
2163
+ assetCtxs() {
2164
+ return fetchHyperliquidAssetCtxs(this.environment);
2165
+ }
2166
+ spotAssetCtxs() {
2167
+ return fetchHyperliquidSpotAssetCtxs(this.environment);
2168
+ }
2169
+ openOrders(user) {
2170
+ return fetchHyperliquidOpenOrders({ user, environment: this.environment });
2171
+ }
2172
+ frontendOpenOrders(user) {
2173
+ return fetchHyperliquidFrontendOpenOrders({
2174
+ user,
2175
+ environment: this.environment
2176
+ });
2177
+ }
2178
+ orderStatus(user, oid) {
2179
+ return fetchHyperliquidOrderStatus({
2180
+ user,
2181
+ oid,
2182
+ environment: this.environment
2183
+ });
2184
+ }
2185
+ historicalOrders(user) {
2186
+ return fetchHyperliquidHistoricalOrders({
2187
+ user,
2188
+ environment: this.environment
2189
+ });
2190
+ }
2191
+ userFills(user) {
2192
+ return fetchHyperliquidUserFills({ user, environment: this.environment });
2193
+ }
2194
+ userFillsByTime(user, startTime, endTime) {
2195
+ return fetchHyperliquidUserFillsByTime({
2196
+ user,
2197
+ startTime,
2198
+ endTime,
2199
+ environment: this.environment
2200
+ });
2201
+ }
2202
+ userRateLimit(user) {
2203
+ return fetchHyperliquidUserRateLimit({
2204
+ user,
2205
+ environment: this.environment
2206
+ });
2207
+ }
2208
+ preTransferCheck(user, source) {
2209
+ return fetchHyperliquidPreTransferCheck({
2210
+ user,
2211
+ source,
2212
+ environment: this.environment
2213
+ });
2214
+ }
2215
+ spotClearinghouseState(user) {
2216
+ return fetchHyperliquidSpotClearinghouseState({
2217
+ user,
2218
+ environment: this.environment
2219
+ });
2220
+ }
2221
+ };
2222
+ async function fetchHyperliquidMeta(environment = "mainnet") {
2223
+ return postInfo(environment, { type: "meta" });
2224
+ }
2225
+ async function fetchHyperliquidMetaAndAssetCtxs(environment = "mainnet") {
2226
+ return postInfo(environment, { type: "metaAndAssetCtxs" });
2227
+ }
2228
+ async function fetchHyperliquidSpotMeta(environment = "mainnet") {
2229
+ return postInfo(environment, { type: "spotMeta" });
2230
+ }
2231
+ async function fetchHyperliquidSpotMetaAndAssetCtxs(environment = "mainnet") {
2232
+ return postInfo(environment, { type: "spotMetaAndAssetCtxs" });
2233
+ }
2234
+ async function fetchHyperliquidAssetCtxs(environment = "mainnet") {
2235
+ return postInfo(environment, { type: "assetCtxs" });
2236
+ }
2237
+ async function fetchHyperliquidSpotAssetCtxs(environment = "mainnet") {
2238
+ return postInfo(environment, { type: "spotAssetCtxs" });
2239
+ }
2240
+ async function fetchHyperliquidOpenOrders(params) {
2241
+ const env = params.environment ?? "mainnet";
2242
+ return postInfo(env, { type: "openOrders", user: normalizeAddress(params.user) });
2243
+ }
2244
+ async function fetchHyperliquidFrontendOpenOrders(params) {
2245
+ const env = params.environment ?? "mainnet";
2246
+ return postInfo(env, {
2247
+ type: "frontendOpenOrders",
2248
+ user: normalizeAddress(params.user)
2249
+ });
2250
+ }
2251
+ async function fetchHyperliquidOrderStatus(params) {
2252
+ const env = params.environment ?? "mainnet";
2253
+ return postInfo(env, {
2254
+ type: "orderStatus",
2255
+ user: normalizeAddress(params.user),
2256
+ oid: params.oid
2257
+ });
2258
+ }
2259
+ async function fetchHyperliquidHistoricalOrders(params) {
2260
+ const env = params.environment ?? "mainnet";
2261
+ return postInfo(env, {
2262
+ type: "historicalOrders",
2263
+ user: normalizeAddress(params.user)
2264
+ });
2265
+ }
2266
+ async function fetchHyperliquidUserFills(params) {
2267
+ const env = params.environment ?? "mainnet";
2268
+ return postInfo(env, {
2269
+ type: "userFills",
2270
+ user: normalizeAddress(params.user)
2271
+ });
2272
+ }
2273
+ async function fetchHyperliquidUserFillsByTime(params) {
2274
+ const env = params.environment ?? "mainnet";
2275
+ return postInfo(env, {
2276
+ type: "userFillsByTime",
2277
+ user: normalizeAddress(params.user),
2278
+ startTime: params.startTime,
2279
+ endTime: params.endTime
2280
+ });
2281
+ }
2282
+ async function fetchHyperliquidUserRateLimit(params) {
2283
+ const env = params.environment ?? "mainnet";
2284
+ return postInfo(env, {
2285
+ type: "userRateLimit",
2286
+ user: normalizeAddress(params.user)
2287
+ });
2288
+ }
2289
+ async function fetchHyperliquidPreTransferCheck(params) {
2290
+ const env = params.environment ?? "mainnet";
2291
+ return postInfo(env, {
2292
+ type: "preTransferCheck",
2293
+ user: normalizeAddress(params.user),
2294
+ source: normalizeAddress(params.source)
2295
+ });
2296
+ }
2297
+ async function fetchHyperliquidSpotClearinghouseState(params) {
2298
+ const env = params.environment ?? "mainnet";
2299
+ return postInfo(env, {
2300
+ type: "spotClearinghouseState",
2301
+ user: normalizeAddress(params.user)
2302
+ });
2303
+ }
2304
+
2028
2305
  // src/adapters/hyperliquid/exchange.ts
2029
2306
  var HyperliquidExchangeClient = class {
2030
2307
  constructor(args) {
@@ -2157,7 +2434,58 @@ var HyperliquidExchangeClient = class {
2157
2434
  ...params
2158
2435
  });
2159
2436
  }
2437
+ setPortfolioMargin(params) {
2438
+ const base2 = {
2439
+ wallet: this.wallet,
2440
+ enabled: params.enabled,
2441
+ environment: this.environment,
2442
+ vaultAddress: this.vaultAddress,
2443
+ expiresAfter: this.expiresAfter,
2444
+ nonceSource: this.nonceSource
2445
+ };
2446
+ return setHyperliquidPortfolioMargin(
2447
+ params.user ? { ...base2, user: params.user } : base2
2448
+ );
2449
+ }
2160
2450
  };
2451
+ async function setHyperliquidPortfolioMargin(options) {
2452
+ const env = options.environment ?? "mainnet";
2453
+ if (!options.wallet?.account || !options.wallet.walletClient) {
2454
+ throw new Error(
2455
+ "Wallet with signing capability is required for portfolio margin."
2456
+ );
2457
+ }
2458
+ const nonce = options.nonce ?? options.walletNonceProvider?.() ?? options.wallet.nonceSource?.() ?? options.nonceSource?.() ?? Date.now();
2459
+ const signatureChainId = getSignatureChainId(env);
2460
+ const hyperliquidChain = HL_CHAIN_LABEL[env];
2461
+ const user = normalizeAddress(
2462
+ options.user ?? options.wallet.address
2463
+ );
2464
+ const action = {
2465
+ type: "userPortfolioMargin",
2466
+ enabled: Boolean(options.enabled),
2467
+ hyperliquidChain,
2468
+ signatureChainId,
2469
+ user,
2470
+ nonce
2471
+ };
2472
+ const signature = await signUserPortfolioMargin({
2473
+ wallet: options.wallet,
2474
+ action
2475
+ });
2476
+ const body = {
2477
+ action,
2478
+ nonce,
2479
+ signature
2480
+ };
2481
+ if (options.vaultAddress) {
2482
+ body.vaultAddress = normalizeAddress(options.vaultAddress);
2483
+ }
2484
+ if (typeof options.expiresAfter === "number") {
2485
+ body.expiresAfter = options.expiresAfter;
2486
+ }
2487
+ return postExchange(env, body);
2488
+ }
2161
2489
  async function cancelHyperliquidOrders(options) {
2162
2490
  options.cancels.forEach((c) => assertSymbol(c.symbol));
2163
2491
  const action = {
@@ -2474,198 +2802,43 @@ function assertPositiveDecimal(value, label) {
2474
2802
  }
2475
2803
  assertString(value, label);
2476
2804
  }
2477
- async function postExchange(env, body) {
2478
- const response = await fetch(`${API_BASES[env]}/exchange`, {
2479
- method: "POST",
2480
- headers: { "content-type": "application/json" },
2481
- body: JSON.stringify(body)
2482
- });
2483
- const json = await response.json().catch(() => null);
2484
- if (!response.ok || !json) {
2485
- throw new HyperliquidApiError(
2486
- "Hyperliquid exchange action failed.",
2487
- json ?? { status: response.status }
2488
- );
2489
- }
2490
- if (json.status !== "ok") {
2491
- throw new HyperliquidApiError("Hyperliquid exchange returned error.", json);
2492
- }
2493
- return json;
2494
- }
2495
-
2496
- // src/adapters/hyperliquid/info.ts
2497
- async function postInfo(environment, payload) {
2498
- const baseUrl = API_BASES[environment];
2499
- const response = await fetch(`${baseUrl}/info`, {
2500
- method: "POST",
2501
- headers: { "content-type": "application/json" },
2502
- body: JSON.stringify(payload)
2503
- });
2504
- const data = await response.json().catch(() => null);
2505
- if (!response.ok) {
2506
- throw new HyperliquidApiError(
2507
- "Hyperliquid info request failed.",
2508
- data ?? { status: response.status }
2509
- );
2510
- }
2511
- return data;
2512
- }
2513
- var HyperliquidInfoClient = class {
2514
- constructor(environment = "mainnet") {
2515
- this.environment = environment;
2516
- }
2517
- meta() {
2518
- return fetchHyperliquidMeta(this.environment);
2519
- }
2520
- metaAndAssetCtxs() {
2521
- return fetchHyperliquidMetaAndAssetCtxs(this.environment);
2522
- }
2523
- spotMeta() {
2524
- return fetchHyperliquidSpotMeta(this.environment);
2525
- }
2526
- spotMetaAndAssetCtxs() {
2527
- return fetchHyperliquidSpotMetaAndAssetCtxs(this.environment);
2528
- }
2529
- assetCtxs() {
2530
- return fetchHyperliquidAssetCtxs(this.environment);
2531
- }
2532
- spotAssetCtxs() {
2533
- return fetchHyperliquidSpotAssetCtxs(this.environment);
2534
- }
2535
- openOrders(user) {
2536
- return fetchHyperliquidOpenOrders({ user, environment: this.environment });
2537
- }
2538
- frontendOpenOrders(user) {
2539
- return fetchHyperliquidFrontendOpenOrders({
2540
- user,
2541
- environment: this.environment
2542
- });
2543
- }
2544
- orderStatus(user, oid) {
2545
- return fetchHyperliquidOrderStatus({
2546
- user,
2547
- oid,
2548
- environment: this.environment
2549
- });
2550
- }
2551
- historicalOrders(user) {
2552
- return fetchHyperliquidHistoricalOrders({
2553
- user,
2554
- environment: this.environment
2555
- });
2556
- }
2557
- userFills(user) {
2558
- return fetchHyperliquidUserFills({ user, environment: this.environment });
2559
- }
2560
- userFillsByTime(user, startTime, endTime) {
2561
- return fetchHyperliquidUserFillsByTime({
2562
- user,
2563
- startTime,
2564
- endTime,
2565
- environment: this.environment
2566
- });
2567
- }
2568
- userRateLimit(user) {
2569
- return fetchHyperliquidUserRateLimit({
2570
- user,
2571
- environment: this.environment
2572
- });
2573
- }
2574
- preTransferCheck(user, source) {
2575
- return fetchHyperliquidPreTransferCheck({
2576
- user,
2577
- source,
2578
- environment: this.environment
2579
- });
2580
- }
2581
- spotClearinghouseState(user) {
2582
- return fetchHyperliquidSpotClearinghouseState({
2583
- user,
2584
- environment: this.environment
2585
- });
2586
- }
2587
- };
2588
- async function fetchHyperliquidMeta(environment = "mainnet") {
2589
- return postInfo(environment, { type: "meta" });
2590
- }
2591
- async function fetchHyperliquidMetaAndAssetCtxs(environment = "mainnet") {
2592
- return postInfo(environment, { type: "metaAndAssetCtxs" });
2593
- }
2594
- async function fetchHyperliquidSpotMeta(environment = "mainnet") {
2595
- return postInfo(environment, { type: "spotMeta" });
2596
- }
2597
- async function fetchHyperliquidSpotMetaAndAssetCtxs(environment = "mainnet") {
2598
- return postInfo(environment, { type: "spotMetaAndAssetCtxs" });
2599
- }
2600
- async function fetchHyperliquidAssetCtxs(environment = "mainnet") {
2601
- return postInfo(environment, { type: "assetCtxs" });
2602
- }
2603
- async function fetchHyperliquidSpotAssetCtxs(environment = "mainnet") {
2604
- return postInfo(environment, { type: "spotAssetCtxs" });
2605
- }
2606
- async function fetchHyperliquidOpenOrders(params) {
2607
- const env = params.environment ?? "mainnet";
2608
- return postInfo(env, { type: "openOrders", user: normalizeAddress(params.user) });
2609
- }
2610
- async function fetchHyperliquidFrontendOpenOrders(params) {
2611
- const env = params.environment ?? "mainnet";
2612
- return postInfo(env, {
2613
- type: "frontendOpenOrders",
2614
- user: normalizeAddress(params.user)
2615
- });
2616
- }
2617
- async function fetchHyperliquidOrderStatus(params) {
2618
- const env = params.environment ?? "mainnet";
2619
- return postInfo(env, {
2620
- type: "orderStatus",
2621
- user: normalizeAddress(params.user),
2622
- oid: params.oid
2623
- });
2624
- }
2625
- async function fetchHyperliquidHistoricalOrders(params) {
2626
- const env = params.environment ?? "mainnet";
2627
- return postInfo(env, {
2628
- type: "historicalOrders",
2629
- user: normalizeAddress(params.user)
2630
- });
2631
- }
2632
- async function fetchHyperliquidUserFills(params) {
2633
- const env = params.environment ?? "mainnet";
2634
- return postInfo(env, {
2635
- type: "userFills",
2636
- user: normalizeAddress(params.user)
2637
- });
2638
- }
2639
- async function fetchHyperliquidUserFillsByTime(params) {
2640
- const env = params.environment ?? "mainnet";
2641
- return postInfo(env, {
2642
- type: "userFillsByTime",
2643
- user: normalizeAddress(params.user),
2644
- startTime: params.startTime,
2645
- endTime: params.endTime
2646
- });
2647
- }
2648
- async function fetchHyperliquidUserRateLimit(params) {
2649
- const env = params.environment ?? "mainnet";
2650
- return postInfo(env, {
2651
- type: "userRateLimit",
2652
- user: normalizeAddress(params.user)
2653
- });
2654
- }
2655
- async function fetchHyperliquidPreTransferCheck(params) {
2656
- const env = params.environment ?? "mainnet";
2657
- return postInfo(env, {
2658
- type: "preTransferCheck",
2659
- user: normalizeAddress(params.user),
2660
- source: normalizeAddress(params.source)
2661
- });
2662
- }
2663
- async function fetchHyperliquidSpotClearinghouseState(params) {
2664
- const env = params.environment ?? "mainnet";
2665
- return postInfo(env, {
2666
- type: "spotClearinghouseState",
2667
- user: normalizeAddress(params.user)
2805
+ async function postExchange(env, body) {
2806
+ const response = await fetch(`${API_BASES[env]}/exchange`, {
2807
+ method: "POST",
2808
+ headers: { "content-type": "application/json" },
2809
+ body: JSON.stringify(body)
2668
2810
  });
2811
+ const text = await response.text().catch(() => "");
2812
+ const json = (() => {
2813
+ if (!text) return null;
2814
+ try {
2815
+ return JSON.parse(text);
2816
+ } catch {
2817
+ return null;
2818
+ }
2819
+ })();
2820
+ if (!response.ok) {
2821
+ throw new HyperliquidApiError("Hyperliquid exchange action failed.", {
2822
+ status: response.status,
2823
+ statusText: response.statusText,
2824
+ body: json ?? (text ? text : null)
2825
+ });
2826
+ }
2827
+ if (!json) {
2828
+ throw new HyperliquidApiError("Hyperliquid exchange action failed.", {
2829
+ status: response.status,
2830
+ statusText: response.statusText,
2831
+ body: text ? text : null
2832
+ });
2833
+ }
2834
+ if (json.status !== "ok") {
2835
+ throw new HyperliquidApiError("Hyperliquid exchange returned error.", {
2836
+ status: response.status,
2837
+ statusText: response.statusText,
2838
+ body: json
2839
+ });
2840
+ }
2841
+ return json;
2669
2842
  }
2670
2843
 
2671
2844
  // src/adapters/hyperliquid/index.ts
@@ -3055,6 +3228,833 @@ var __hyperliquidInternals = {
3055
3228
  createL1ActionHash,
3056
3229
  splitSignature
3057
3230
  };
3231
+ var PolymarketApiError = class extends Error {
3232
+ constructor(message, response) {
3233
+ super(message);
3234
+ this.response = response;
3235
+ this.name = "PolymarketApiError";
3236
+ }
3237
+ };
3238
+ var PolymarketAuthError = class extends Error {
3239
+ constructor(message) {
3240
+ super(message);
3241
+ this.name = "PolymarketAuthError";
3242
+ }
3243
+ };
3244
+ var POLYMARKET_ENDPOINTS = {
3245
+ gamma: {
3246
+ mainnet: "https://gamma-api.polymarket.com",
3247
+ testnet: "https://gamma-api.polymarket.com"
3248
+ },
3249
+ clob: {
3250
+ mainnet: "https://clob.polymarket.com",
3251
+ testnet: "https://clob.polymarket.com"
3252
+ },
3253
+ data: {
3254
+ mainnet: "https://data-api.polymarket.com",
3255
+ testnet: "https://data-api.polymarket.com"
3256
+ }
3257
+ };
3258
+ var POLYMARKET_CHAIN_ID = {
3259
+ mainnet: 137,
3260
+ testnet: 80002
3261
+ };
3262
+ var POLYMARKET_EXCHANGE_ADDRESSES = {
3263
+ mainnet: {
3264
+ ctf: "0x4bfb41d5b3570defd03c39a9a4d8de6bd8b8982e",
3265
+ negRisk: "0xc5d563a36ae78145c45a50134d48a1215220f80a"
3266
+ },
3267
+ testnet: {
3268
+ ctf: "0xdfe02eb6733538f8ea35d585af8de5958ad99e40",
3269
+ negRisk: "0xdfe02eb6733538f8ea35d585af8de5958ad99e40"
3270
+ }
3271
+ };
3272
+ var POLYMARKET_CLOB_DOMAIN = {
3273
+ name: "Polymarket CTF Exchange",
3274
+ version: "1"
3275
+ };
3276
+ var POLYMARKET_CLOB_AUTH_DOMAIN = {
3277
+ name: "ClobAuthDomain",
3278
+ version: "1"
3279
+ };
3280
+ var ZERO_ADDRESS2 = "0x0000000000000000000000000000000000000000";
3281
+ function resolvePolymarketBaseUrl(service, environment) {
3282
+ return POLYMARKET_ENDPOINTS[service][environment];
3283
+ }
3284
+ function assertWalletSigner(wallet2) {
3285
+ if (!wallet2?.account || !wallet2.walletClient) {
3286
+ throw new Error("Polymarket requires a wallet with signing capabilities.");
3287
+ }
3288
+ }
3289
+ function toDecimalString2(value) {
3290
+ if (typeof value === "string") return value;
3291
+ if (typeof value === "bigint") return value.toString();
3292
+ if (!Number.isFinite(value)) {
3293
+ throw new Error("Numeric values must be finite.");
3294
+ }
3295
+ const asString = value.toString();
3296
+ if (/e/i.test(asString)) {
3297
+ const [mantissa, exponentPart] = asString.split(/e/i);
3298
+ const exponent = Number(exponentPart);
3299
+ const [integerPart, fractionalPart = ""] = mantissa.split(".");
3300
+ if (exponent >= 0) {
3301
+ return integerPart + fractionalPart.padEnd(exponent + fractionalPart.length, "0");
3302
+ }
3303
+ const zeros = "0".repeat(Math.abs(exponent) - 1);
3304
+ return `0.${zeros}${integerPart}${fractionalPart}`.replace(/\.0+$/, "");
3305
+ }
3306
+ return asString;
3307
+ }
3308
+ function normalizeArrayish(value) {
3309
+ if (Array.isArray(value)) return value;
3310
+ if (typeof value === "string") {
3311
+ const trimmed = value.trim();
3312
+ if (!trimmed) return [];
3313
+ if (trimmed.startsWith("[")) {
3314
+ try {
3315
+ const parsed = JSON.parse(trimmed);
3316
+ return Array.isArray(parsed) ? parsed : [];
3317
+ } catch {
3318
+ return [];
3319
+ }
3320
+ }
3321
+ return [trimmed];
3322
+ }
3323
+ return [];
3324
+ }
3325
+ function normalizeStringArrayish(value) {
3326
+ return normalizeArrayish(value).map((entry) => entry == null ? "" : String(entry).trim()).filter((entry) => entry.length > 0);
3327
+ }
3328
+ function normalizeNumberArrayish(value) {
3329
+ return normalizeArrayish(value).map(
3330
+ (entry) => typeof entry === "number" ? entry : Number.parseFloat(String(entry))
3331
+ ).filter((entry) => Number.isFinite(entry));
3332
+ }
3333
+ function normalizeTags(value) {
3334
+ if (!Array.isArray(value)) return [];
3335
+ const tags = value.map((entry) => {
3336
+ if (entry && typeof entry === "object") {
3337
+ const record = entry;
3338
+ const label = record.label ?? record.id ?? record.tag;
3339
+ return label ? String(label).trim() : "";
3340
+ }
3341
+ return String(entry ?? "").trim();
3342
+ }).filter((entry) => entry.length > 0);
3343
+ return Array.from(new Set(tags));
3344
+ }
3345
+ function parseOptionalDate(value) {
3346
+ if (!value) return null;
3347
+ if (typeof value === "string") {
3348
+ const trimmed = value.trim();
3349
+ return trimmed.length > 0 ? trimmed : null;
3350
+ }
3351
+ if (typeof value === "number" && Number.isFinite(value)) {
3352
+ const ts = value > 1e12 ? value : value * 1e3;
3353
+ const date = new Date(ts);
3354
+ return Number.isNaN(date.getTime()) ? null : date.toISOString();
3355
+ }
3356
+ return null;
3357
+ }
3358
+ function buildHmacSignature(args) {
3359
+ const timestamp2 = args.timestamp.toString();
3360
+ const method = args.method.toUpperCase();
3361
+ const path7 = args.path;
3362
+ const body = args.body == null ? "" : typeof args.body === "string" ? args.body : JSON.stringify(args.body);
3363
+ const payload = `${timestamp2}${method}${path7}${body}`;
3364
+ const key = Buffer.from(args.secret, "base64");
3365
+ return createHmac("sha256", key).update(payload).digest("hex");
3366
+ }
3367
+ function buildL2Headers(args) {
3368
+ const timestamp2 = args.timestamp ?? Math.floor(Date.now() / 1e3);
3369
+ const signature = buildHmacSignature({
3370
+ secret: args.credentials.secret,
3371
+ timestamp: timestamp2,
3372
+ method: args.method,
3373
+ path: args.path,
3374
+ body: args.body ?? null
3375
+ });
3376
+ return {
3377
+ POLY_ADDRESS: args.address,
3378
+ POLY_API_KEY: args.credentials.apiKey,
3379
+ POLY_PASSPHRASE: args.credentials.passphrase,
3380
+ POLY_TIMESTAMP: timestamp2.toString(),
3381
+ POLY_SIGNATURE: signature
3382
+ };
3383
+ }
3384
+ async function buildL1Headers(args) {
3385
+ assertWalletSigner(args.wallet);
3386
+ const timestamp2 = args.timestamp ?? Math.floor(Date.now() / 1e3);
3387
+ const nonce = args.nonce ?? Date.now();
3388
+ const chainId = POLYMARKET_CHAIN_ID[args.environment ?? "mainnet"];
3389
+ const address = args.wallet.address;
3390
+ const message = args.message ?? "Create or derive a Polymarket API key";
3391
+ const signature = await args.wallet.walletClient.signTypedData({
3392
+ account: args.wallet.account,
3393
+ domain: {
3394
+ ...POLYMARKET_CLOB_AUTH_DOMAIN,
3395
+ chainId
3396
+ },
3397
+ types: {
3398
+ ClobAuth: [
3399
+ { name: "address", type: "address" },
3400
+ { name: "timestamp", type: "string" },
3401
+ { name: "nonce", type: "uint256" },
3402
+ { name: "message", type: "string" }
3403
+ ]
3404
+ },
3405
+ primaryType: "ClobAuth",
3406
+ message: {
3407
+ address,
3408
+ timestamp: timestamp2.toString(),
3409
+ nonce: BigInt(nonce),
3410
+ message
3411
+ }
3412
+ });
3413
+ return {
3414
+ POLY_ADDRESS: address,
3415
+ POLY_TIMESTAMP: timestamp2.toString(),
3416
+ POLY_NONCE: nonce.toString(),
3417
+ POLY_SIGNATURE: signature
3418
+ };
3419
+ }
3420
+ function resolveExchangeAddress(args) {
3421
+ if (args.exchangeAddress) return args.exchangeAddress;
3422
+ const env = args.environment;
3423
+ return args.negRisk ? POLYMARKET_EXCHANGE_ADDRESSES[env].negRisk : POLYMARKET_EXCHANGE_ADDRESSES[env].ctf;
3424
+ }
3425
+ function parseUintString(value, name) {
3426
+ const trimmed = value.trim();
3427
+ if (!/^\d+$/.test(trimmed)) {
3428
+ throw new Error(`${name} must be a base-10 integer string.`);
3429
+ }
3430
+ return BigInt(trimmed);
3431
+ }
3432
+ function buildPolymarketOrderAmounts(args) {
3433
+ const priceStr = toDecimalString2(args.price);
3434
+ const sizeStr = toDecimalString2(args.size);
3435
+ if (!priceStr || !sizeStr) {
3436
+ throw new Error("Order price and size are required.");
3437
+ }
3438
+ const priceFloat = Number(priceStr);
3439
+ if (!Number.isFinite(priceFloat) || priceFloat <= 0 || priceFloat >= 1) {
3440
+ throw new Error("Order price must be between 0 and 1 (exclusive).");
3441
+ }
3442
+ const sizeFloat = Number(sizeStr);
3443
+ if (!Number.isFinite(sizeFloat) || sizeFloat <= 0) {
3444
+ throw new Error("Order size must be positive.");
3445
+ }
3446
+ let priceUnits = parseUnits(priceStr, 6);
3447
+ if (args.tickSize !== void 0) {
3448
+ const tickUnits = parseUnits(toDecimalString2(args.tickSize), 6);
3449
+ if (tickUnits <= 0n) {
3450
+ throw new Error("tickSize must be positive.");
3451
+ }
3452
+ priceUnits = priceUnits / tickUnits * tickUnits;
3453
+ }
3454
+ const sizeUnits = parseUnits(sizeStr, 6);
3455
+ const quoteUnits = priceUnits * sizeUnits / 1000000n;
3456
+ if (args.side === "BUY") {
3457
+ return { makerAmount: quoteUnits, takerAmount: sizeUnits };
3458
+ }
3459
+ return { makerAmount: sizeUnits, takerAmount: quoteUnits };
3460
+ }
3461
+ async function buildSignedOrderPayload(args) {
3462
+ assertWalletSigner(args.wallet);
3463
+ const environment = args.environment ?? "mainnet";
3464
+ const chainId = POLYMARKET_CHAIN_ID[environment];
3465
+ const exchangeAddress = resolveExchangeAddress({
3466
+ environment,
3467
+ ...args.negRisk !== void 0 ? { negRisk: args.negRisk } : {},
3468
+ ...args.exchangeAddress ? { exchangeAddress: args.exchangeAddress } : {}
3469
+ });
3470
+ const maker = args.maker ?? args.wallet.address;
3471
+ const signer = args.signer ?? args.wallet.address;
3472
+ const taker = args.taker ?? ZERO_ADDRESS2;
3473
+ const sideValue = args.side === "BUY" ? 0 : 1;
3474
+ const signatureType = args.signatureType ?? 0;
3475
+ const tokenIdValue = args.tokenId.startsWith("0x") ? BigInt(args.tokenId) : parseUintString(args.tokenId, "tokenId");
3476
+ const { makerAmount, takerAmount } = buildPolymarketOrderAmounts({
3477
+ side: args.side,
3478
+ price: args.price,
3479
+ size: args.size,
3480
+ ...args.tickSize !== void 0 ? { tickSize: args.tickSize } : {}
3481
+ });
3482
+ const salt = BigInt(`0x${randomBytes(16).toString("hex")}`);
3483
+ const expiration = BigInt(args.expiration ?? 0);
3484
+ const nonce = BigInt(args.nonce ?? 0);
3485
+ const feeRateBps = BigInt(args.feeRateBps ?? 0);
3486
+ const message = {
3487
+ salt,
3488
+ maker,
3489
+ signer,
3490
+ taker,
3491
+ tokenId: tokenIdValue,
3492
+ makerAmount,
3493
+ takerAmount,
3494
+ expiration,
3495
+ nonce,
3496
+ feeRateBps,
3497
+ side: sideValue,
3498
+ signatureType
3499
+ };
3500
+ const signature = await args.wallet.walletClient.signTypedData({
3501
+ account: args.wallet.account,
3502
+ domain: {
3503
+ ...POLYMARKET_CLOB_DOMAIN,
3504
+ chainId,
3505
+ verifyingContract: exchangeAddress
3506
+ },
3507
+ types: {
3508
+ Order: [
3509
+ { name: "salt", type: "uint256" },
3510
+ { name: "maker", type: "address" },
3511
+ { name: "signer", type: "address" },
3512
+ { name: "taker", type: "address" },
3513
+ { name: "tokenId", type: "uint256" },
3514
+ { name: "makerAmount", type: "uint256" },
3515
+ { name: "takerAmount", type: "uint256" },
3516
+ { name: "expiration", type: "uint256" },
3517
+ { name: "nonce", type: "uint256" },
3518
+ { name: "feeRateBps", type: "uint256" },
3519
+ { name: "side", type: "uint8" },
3520
+ { name: "signatureType", type: "uint8" }
3521
+ ]
3522
+ },
3523
+ primaryType: "Order",
3524
+ message
3525
+ });
3526
+ return {
3527
+ salt: message.salt.toString(),
3528
+ maker,
3529
+ signer,
3530
+ taker,
3531
+ tokenId: tokenIdValue.toString(),
3532
+ makerAmount: message.makerAmount.toString(),
3533
+ takerAmount: message.takerAmount.toString(),
3534
+ expiration: message.expiration.toString(),
3535
+ nonce: message.nonce.toString(),
3536
+ feeRateBps: message.feeRateBps.toString(),
3537
+ side: sideValue,
3538
+ signatureType,
3539
+ signature
3540
+ };
3541
+ }
3542
+
3543
+ // src/adapters/polymarket/exchange.ts
3544
+ async function resolveAuthContext(args) {
3545
+ if (args.wallet) {
3546
+ const credentials = args.credentials ?? await createPolymarketApiKey({
3547
+ wallet: args.wallet,
3548
+ ...args.environment ? { environment: args.environment } : {}
3549
+ });
3550
+ return {
3551
+ credentials,
3552
+ address: args.wallet.address
3553
+ };
3554
+ }
3555
+ if (args.walletAddress && args.credentials) {
3556
+ return { credentials: args.credentials, address: args.walletAddress };
3557
+ }
3558
+ throw new PolymarketAuthError(
3559
+ "Polymarket auth requires a wallet (preferred) or credentials + walletAddress."
3560
+ );
3561
+ }
3562
+ async function requestJson2(url, init) {
3563
+ const response = await fetch(url, init);
3564
+ const text = await response.text().catch(() => "");
3565
+ let data = null;
3566
+ try {
3567
+ data = text ? JSON.parse(text) : null;
3568
+ } catch {
3569
+ data = text;
3570
+ }
3571
+ if (!response.ok) {
3572
+ throw new PolymarketApiError(
3573
+ `Polymarket request failed (${response.status}).`,
3574
+ data ?? { status: response.status }
3575
+ );
3576
+ }
3577
+ return data;
3578
+ }
3579
+ function resolvePath(url) {
3580
+ const parsed = new URL(url);
3581
+ return `${parsed.pathname}${parsed.search}`;
3582
+ }
3583
+ async function createPolymarketApiKey(args) {
3584
+ const environment = args.environment ?? "mainnet";
3585
+ const baseUrl = resolvePolymarketBaseUrl("clob", environment);
3586
+ const url = `${baseUrl}/auth/api-key`;
3587
+ const headers = await buildL1Headers({
3588
+ wallet: args.wallet,
3589
+ environment,
3590
+ ...args.timestamp !== void 0 ? { timestamp: args.timestamp } : {},
3591
+ ...args.nonce !== void 0 ? { nonce: args.nonce } : {},
3592
+ ...args.message !== void 0 ? { message: args.message } : {}
3593
+ });
3594
+ const data = await requestJson2(url, {
3595
+ method: "POST",
3596
+ headers: {
3597
+ "content-type": "application/json",
3598
+ ...headers
3599
+ },
3600
+ body: JSON.stringify({})
3601
+ });
3602
+ if (!data?.apiKey || !data?.secret || !data?.passphrase) {
3603
+ throw new PolymarketAuthError("Failed to create Polymarket API key.");
3604
+ }
3605
+ return {
3606
+ apiKey: data.apiKey,
3607
+ secret: data.secret,
3608
+ passphrase: data.passphrase
3609
+ };
3610
+ }
3611
+ async function derivePolymarketApiKey(args) {
3612
+ const environment = args.environment ?? "mainnet";
3613
+ const baseUrl = resolvePolymarketBaseUrl("clob", environment);
3614
+ const url = `${baseUrl}/auth/derive-api-key`;
3615
+ const headers = await buildL1Headers({
3616
+ wallet: args.wallet,
3617
+ environment,
3618
+ ...args.timestamp !== void 0 ? { timestamp: args.timestamp } : {},
3619
+ ...args.nonce !== void 0 ? { nonce: args.nonce } : {},
3620
+ ...args.message !== void 0 ? { message: args.message } : {}
3621
+ });
3622
+ const data = await requestJson2(url, {
3623
+ method: "GET",
3624
+ headers: {
3625
+ "content-type": "application/json",
3626
+ ...headers
3627
+ }
3628
+ });
3629
+ if (!data?.apiKey || !data?.secret || !data?.passphrase) {
3630
+ throw new PolymarketAuthError("Failed to derive Polymarket API key.");
3631
+ }
3632
+ return {
3633
+ apiKey: data.apiKey,
3634
+ secret: data.secret,
3635
+ passphrase: data.passphrase
3636
+ };
3637
+ }
3638
+ async function placePolymarketOrder(args) {
3639
+ const environment = args.environment ?? "mainnet";
3640
+ const baseUrl = resolvePolymarketBaseUrl("clob", environment);
3641
+ const url = `${baseUrl}/order`;
3642
+ const signedOrder = await buildSignedOrderPayload({
3643
+ wallet: args.wallet,
3644
+ environment,
3645
+ ...args.order
3646
+ });
3647
+ const auth = await resolveAuthContext({
3648
+ wallet: args.wallet,
3649
+ ...args.credentials ? { credentials: args.credentials } : {},
3650
+ environment
3651
+ });
3652
+ const body = {
3653
+ order: signedOrder,
3654
+ owner: auth.credentials.apiKey,
3655
+ orderType: args.orderType ?? "GTC"
3656
+ };
3657
+ const headers = buildL2Headers({
3658
+ credentials: auth.credentials,
3659
+ address: auth.address,
3660
+ method: "POST",
3661
+ path: resolvePath(url),
3662
+ body
3663
+ });
3664
+ return await requestJson2(url, {
3665
+ method: "POST",
3666
+ headers: {
3667
+ "content-type": "application/json",
3668
+ ...headers
3669
+ },
3670
+ body: JSON.stringify(body)
3671
+ });
3672
+ }
3673
+ async function cancelPolymarketOrder(args) {
3674
+ const environment = args.environment ?? "mainnet";
3675
+ const baseUrl = resolvePolymarketBaseUrl("clob", environment);
3676
+ const url = `${baseUrl}/order`;
3677
+ const body = { orderID: args.orderId };
3678
+ const auth = await resolveAuthContext({
3679
+ ...args.wallet ? { wallet: args.wallet } : {},
3680
+ ...args.walletAddress ? { walletAddress: args.walletAddress } : {},
3681
+ ...args.credentials ? { credentials: args.credentials } : {},
3682
+ environment
3683
+ });
3684
+ const headers = buildL2Headers({
3685
+ credentials: auth.credentials,
3686
+ address: auth.address,
3687
+ method: "DELETE",
3688
+ path: resolvePath(url),
3689
+ body
3690
+ });
3691
+ return await requestJson2(url, {
3692
+ method: "DELETE",
3693
+ headers: {
3694
+ "content-type": "application/json",
3695
+ ...headers
3696
+ },
3697
+ body: JSON.stringify(body)
3698
+ });
3699
+ }
3700
+ async function cancelPolymarketOrders(args) {
3701
+ const environment = args.environment ?? "mainnet";
3702
+ const baseUrl = resolvePolymarketBaseUrl("clob", environment);
3703
+ const url = `${baseUrl}/orders`;
3704
+ const body = { orderIDs: args.orderIds };
3705
+ const auth = await resolveAuthContext({
3706
+ ...args.wallet ? { wallet: args.wallet } : {},
3707
+ ...args.walletAddress ? { walletAddress: args.walletAddress } : {},
3708
+ ...args.credentials ? { credentials: args.credentials } : {},
3709
+ environment
3710
+ });
3711
+ const headers = buildL2Headers({
3712
+ credentials: auth.credentials,
3713
+ address: auth.address,
3714
+ method: "DELETE",
3715
+ path: resolvePath(url),
3716
+ body
3717
+ });
3718
+ return await requestJson2(url, {
3719
+ method: "DELETE",
3720
+ headers: {
3721
+ "content-type": "application/json",
3722
+ ...headers
3723
+ },
3724
+ body: JSON.stringify(body)
3725
+ });
3726
+ }
3727
+ async function cancelAllPolymarketOrders(args) {
3728
+ const environment = args.environment ?? "mainnet";
3729
+ const baseUrl = resolvePolymarketBaseUrl("clob", environment);
3730
+ const url = `${baseUrl}/cancel-all`;
3731
+ const auth = await resolveAuthContext({
3732
+ ...args.wallet ? { wallet: args.wallet } : {},
3733
+ ...args.walletAddress ? { walletAddress: args.walletAddress } : {},
3734
+ ...args.credentials ? { credentials: args.credentials } : {},
3735
+ environment
3736
+ });
3737
+ const headers = buildL2Headers({
3738
+ credentials: auth.credentials,
3739
+ address: auth.address,
3740
+ method: "DELETE",
3741
+ path: resolvePath(url)
3742
+ });
3743
+ return await requestJson2(url, {
3744
+ method: "DELETE",
3745
+ headers: {
3746
+ "content-type": "application/json",
3747
+ ...headers
3748
+ }
3749
+ });
3750
+ }
3751
+ async function cancelMarketPolymarketOrders(args) {
3752
+ const environment = args.environment ?? "mainnet";
3753
+ const baseUrl = resolvePolymarketBaseUrl("clob", environment);
3754
+ const url = `${baseUrl}/cancel-market-orders`;
3755
+ const body = { market: args.tokenId };
3756
+ const auth = await resolveAuthContext({
3757
+ ...args.wallet ? { wallet: args.wallet } : {},
3758
+ ...args.walletAddress ? { walletAddress: args.walletAddress } : {},
3759
+ ...args.credentials ? { credentials: args.credentials } : {},
3760
+ environment
3761
+ });
3762
+ const headers = buildL2Headers({
3763
+ credentials: auth.credentials,
3764
+ address: auth.address,
3765
+ method: "DELETE",
3766
+ path: resolvePath(url),
3767
+ body
3768
+ });
3769
+ return await requestJson2(url, {
3770
+ method: "DELETE",
3771
+ headers: {
3772
+ "content-type": "application/json",
3773
+ ...headers
3774
+ },
3775
+ body: JSON.stringify(body)
3776
+ });
3777
+ }
3778
+ var PolymarketExchangeClient = class {
3779
+ constructor(args) {
3780
+ this.wallet = args.wallet;
3781
+ this.credentials = args.credentials;
3782
+ this.environment = args.environment ?? "mainnet";
3783
+ }
3784
+ async getCredentials() {
3785
+ if (this.cachedCredentials) return this.cachedCredentials;
3786
+ const resolved = await resolveAuthContext({
3787
+ wallet: this.wallet,
3788
+ ...this.credentials ? { credentials: this.credentials } : {},
3789
+ environment: this.environment
3790
+ });
3791
+ this.cachedCredentials = resolved.credentials;
3792
+ return resolved.credentials;
3793
+ }
3794
+ async placeOrder(order, orderType) {
3795
+ const credentials = await this.getCredentials();
3796
+ return placePolymarketOrder({
3797
+ wallet: this.wallet,
3798
+ credentials,
3799
+ environment: this.environment,
3800
+ order,
3801
+ ...orderType !== void 0 ? { orderType } : {}
3802
+ });
3803
+ }
3804
+ async cancelOrder(orderId) {
3805
+ const credentials = await this.getCredentials();
3806
+ return cancelPolymarketOrder({
3807
+ orderId,
3808
+ wallet: this.wallet,
3809
+ credentials,
3810
+ environment: this.environment
3811
+ });
3812
+ }
3813
+ async cancelOrders(orderIds) {
3814
+ const credentials = await this.getCredentials();
3815
+ return cancelPolymarketOrders({
3816
+ orderIds,
3817
+ wallet: this.wallet,
3818
+ credentials,
3819
+ environment: this.environment
3820
+ });
3821
+ }
3822
+ async cancelAll() {
3823
+ const credentials = await this.getCredentials();
3824
+ return cancelAllPolymarketOrders({
3825
+ wallet: this.wallet,
3826
+ credentials,
3827
+ environment: this.environment
3828
+ });
3829
+ }
3830
+ async cancelMarket(tokenId) {
3831
+ const credentials = await this.getCredentials();
3832
+ return cancelMarketPolymarketOrders({
3833
+ tokenId,
3834
+ wallet: this.wallet,
3835
+ credentials,
3836
+ environment: this.environment
3837
+ });
3838
+ }
3839
+ };
3840
+
3841
+ // src/adapters/polymarket/info.ts
3842
+ var DEFAULT_EVENT_LIMIT = 50;
3843
+ async function requestJson3(url, init) {
3844
+ const response = await fetch(url, init);
3845
+ const text = await response.text().catch(() => "");
3846
+ let data = null;
3847
+ try {
3848
+ data = text ? JSON.parse(text) : null;
3849
+ } catch {
3850
+ data = text;
3851
+ }
3852
+ if (!response.ok) {
3853
+ throw new PolymarketApiError(
3854
+ `Polymarket request failed (${response.status}).`,
3855
+ data ?? { status: response.status }
3856
+ );
3857
+ }
3858
+ return data;
3859
+ }
3860
+ function getString(value) {
3861
+ if (value == null) return null;
3862
+ const str = String(value).trim();
3863
+ return str.length ? str : null;
3864
+ }
3865
+ function normalizeOrderbookLevels(raw) {
3866
+ if (!Array.isArray(raw)) return [];
3867
+ return raw.map((entry) => {
3868
+ if (Array.isArray(entry)) {
3869
+ const [price, size] = entry;
3870
+ const p = Number(price);
3871
+ const s = Number(size);
3872
+ if (!Number.isFinite(p) || !Number.isFinite(s)) return null;
3873
+ return { price: p, size: s };
3874
+ }
3875
+ if (entry && typeof entry === "object") {
3876
+ const record = entry;
3877
+ const p = Number(record.price ?? record.p);
3878
+ const s = Number(record.size ?? record.s ?? record.quantity);
3879
+ if (!Number.isFinite(p) || !Number.isFinite(s)) return null;
3880
+ return { price: p, size: s };
3881
+ }
3882
+ return null;
3883
+ }).filter((entry) => Boolean(entry));
3884
+ }
3885
+ function normalizeGammaMarket(market, event) {
3886
+ const eventTags = normalizeTags(event?.tags);
3887
+ const marketTags = normalizeTags(market.tags);
3888
+ const mergedTags = Array.from(/* @__PURE__ */ new Set([...marketTags, ...eventTags]));
3889
+ const category = getString(market.category) ?? getString(event?.category) ?? getString(event?.title) ?? null;
3890
+ const normalized = {
3891
+ id: getString(market.id) ?? "",
3892
+ slug: getString(market.slug),
3893
+ question: getString(market.question),
3894
+ description: getString(market.description),
3895
+ eventId: getString(market.eventId ?? event?.id),
3896
+ eventSlug: getString(event?.slug),
3897
+ conditionId: getString(market.conditionId),
3898
+ marketMakerAddress: getString(market.marketMakerAddress),
3899
+ category,
3900
+ startDate: parseOptionalDate(market.startDate) ?? parseOptionalDate(event?.startDate) ?? parseOptionalDate(event?.eventStartTime),
3901
+ endDate: parseOptionalDate(market.endDate) ?? parseOptionalDate(event?.endDate) ?? parseOptionalDate(event?.eventEndTime),
3902
+ createdAt: parseOptionalDate(market.createdAt) ?? parseOptionalDate(event?.createdAt) ?? parseOptionalDate(event?.creationDate),
3903
+ updatedAt: parseOptionalDate(market.updatedAt) ?? parseOptionalDate(event?.updatedAt),
3904
+ closedTime: parseOptionalDate(market.closedTime) ?? parseOptionalDate(event?.closedTime),
3905
+ volume: getString(market.volume),
3906
+ liquidity: getString(market.liquidity),
3907
+ openInterest: getString(market.openInterest),
3908
+ outcomes: normalizeStringArrayish(market.outcomes),
3909
+ outcomePrices: normalizeNumberArrayish(market.outcomePrices),
3910
+ clobTokenIds: normalizeStringArrayish(market.clobTokenIds),
3911
+ icon: getString(market.icon),
3912
+ image: getString(market.image)
3913
+ };
3914
+ if (mergedTags.length) {
3915
+ normalized.tags = mergedTags;
3916
+ }
3917
+ if (typeof market.active === "boolean") {
3918
+ normalized.active = market.active;
3919
+ }
3920
+ if (typeof market.closed === "boolean") {
3921
+ normalized.closed = market.closed;
3922
+ }
3923
+ if (typeof market.resolved === "boolean") {
3924
+ normalized.resolved = market.resolved;
3925
+ }
3926
+ return normalized;
3927
+ }
3928
+ var PolymarketInfoClient = class {
3929
+ constructor(environment = "mainnet") {
3930
+ this.environment = environment;
3931
+ }
3932
+ markets(params = {}) {
3933
+ return fetchPolymarketMarkets({ ...params, environment: this.environment });
3934
+ }
3935
+ market(params) {
3936
+ return fetchPolymarketMarket({ ...params, environment: this.environment });
3937
+ }
3938
+ orderbook(tokenId) {
3939
+ return fetchPolymarketOrderbook({ tokenId, environment: this.environment });
3940
+ }
3941
+ price(tokenId, side) {
3942
+ return fetchPolymarketPrice({ tokenId, side, environment: this.environment });
3943
+ }
3944
+ midpoint(tokenId) {
3945
+ return fetchPolymarketMidpoint({ tokenId, environment: this.environment });
3946
+ }
3947
+ priceHistory(params) {
3948
+ return fetchPolymarketPriceHistory({ ...params, environment: this.environment });
3949
+ }
3950
+ };
3951
+ async function fetchPolymarketMarkets(params = {}) {
3952
+ if (params.active !== void 0 && params.active !== true) {
3953
+ throw new Error("Polymarket market list requires active=true.");
3954
+ }
3955
+ if (params.closed !== void 0 && params.closed !== false) {
3956
+ throw new Error("Polymarket market list requires closed=false.");
3957
+ }
3958
+ const environment = params.environment ?? "mainnet";
3959
+ const baseUrl = resolvePolymarketBaseUrl("gamma", environment);
3960
+ const url = new URL("/events", baseUrl);
3961
+ const limit = params.limit ?? DEFAULT_EVENT_LIMIT;
3962
+ const offset = params.offset ?? 0;
3963
+ url.searchParams.set("limit", String(limit));
3964
+ url.searchParams.set("offset", String(offset));
3965
+ url.searchParams.set("active", "true");
3966
+ url.searchParams.set("closed", "false");
3967
+ url.searchParams.set("order", params.order ?? "id");
3968
+ url.searchParams.set("ascending", params.ascending ? "true" : "false");
3969
+ if (params.tagId) url.searchParams.set("tag_id", params.tagId);
3970
+ if (params.relatedTags) url.searchParams.set("related_tags", "true");
3971
+ if (params.excludeTagId) url.searchParams.set("exclude_tag_id", params.excludeTagId);
3972
+ if (params.slug) url.searchParams.set("slug", params.slug);
3973
+ const data = await requestJson3(url.toString());
3974
+ const markets = data.flatMap(
3975
+ (event) => Array.isArray(event?.markets) ? event.markets.map(
3976
+ (market) => normalizeGammaMarket(market, event)
3977
+ ) : []
3978
+ );
3979
+ const filtered = params.category ? markets.filter(
3980
+ (market) => (market.category ?? "").toLowerCase().includes(params.category.toLowerCase())
3981
+ ) : markets;
3982
+ return typeof params.limit === "number" ? filtered.slice(0, params.limit) : filtered;
3983
+ }
3984
+ async function fetchPolymarketMarket(params) {
3985
+ const environment = params.environment ?? "mainnet";
3986
+ const baseUrl = resolvePolymarketBaseUrl("gamma", environment);
3987
+ if (params.slug) {
3988
+ const url = new URL(`/markets/slug/${params.slug}`, baseUrl);
3989
+ const data = await requestJson3(url.toString());
3990
+ if (!data) return null;
3991
+ return normalizeGammaMarket(data);
3992
+ }
3993
+ if (params.id) {
3994
+ const url = new URL(`/markets/${params.id}`, baseUrl);
3995
+ const data = await requestJson3(url.toString());
3996
+ if (!data) return null;
3997
+ return normalizeGammaMarket(data);
3998
+ }
3999
+ if (params.conditionId) {
4000
+ const url = new URL(`/markets`, baseUrl);
4001
+ url.searchParams.set("condition_id", params.conditionId);
4002
+ const data = await requestJson3(url.toString());
4003
+ if (!data) return null;
4004
+ const market = Array.isArray(data) ? data[0] : data;
4005
+ return market ? normalizeGammaMarket(market) : null;
4006
+ }
4007
+ throw new Error("id, slug, or conditionId is required.");
4008
+ }
4009
+ async function fetchPolymarketOrderbook(params) {
4010
+ const environment = params.environment ?? "mainnet";
4011
+ const baseUrl = resolvePolymarketBaseUrl("clob", environment);
4012
+ const url = new URL("/book", baseUrl);
4013
+ url.searchParams.set("token_id", params.tokenId);
4014
+ const data = await requestJson3(url.toString());
4015
+ return {
4016
+ market: params.tokenId,
4017
+ bids: normalizeOrderbookLevels(data.bids),
4018
+ asks: normalizeOrderbookLevels(data.asks),
4019
+ timestamp: getString(data.timestamp)
4020
+ };
4021
+ }
4022
+ async function fetchPolymarketPrice(params) {
4023
+ const environment = params.environment ?? "mainnet";
4024
+ const baseUrl = resolvePolymarketBaseUrl("clob", environment);
4025
+ const url = new URL("/price", baseUrl);
4026
+ url.searchParams.set("token_id", params.tokenId);
4027
+ url.searchParams.set("side", params.side);
4028
+ const data = await requestJson3(url.toString());
4029
+ const price = Number(data.price ?? data?.p);
4030
+ return Number.isFinite(price) ? price : null;
4031
+ }
4032
+ async function fetchPolymarketMidpoint(params) {
4033
+ const baseArgs = {
4034
+ tokenId: params.tokenId,
4035
+ ...params.environment ? { environment: params.environment } : {}
4036
+ };
4037
+ const buy = await fetchPolymarketPrice({ ...baseArgs, side: "BUY" });
4038
+ const sell = await fetchPolymarketPrice({ ...baseArgs, side: "SELL" });
4039
+ if (buy == null || sell == null) return null;
4040
+ return (buy + sell) / 2;
4041
+ }
4042
+ async function fetchPolymarketPriceHistory(params) {
4043
+ const environment = params.environment ?? "mainnet";
4044
+ const baseUrl = resolvePolymarketBaseUrl("clob", environment);
4045
+ const url = new URL("/prices-history", baseUrl);
4046
+ url.searchParams.set("market", params.tokenId);
4047
+ if (params.startTs) url.searchParams.set("startTs", params.startTs.toString());
4048
+ if (params.endTs) url.searchParams.set("endTs", params.endTs.toString());
4049
+ if (params.interval) url.searchParams.set("interval", params.interval);
4050
+ if (params.fidelity) url.searchParams.set("fidelity", params.fidelity.toString());
4051
+ const data = await requestJson3(url.toString());
4052
+ const points = Array.isArray(data) ? data : data?.history ?? [];
4053
+ return points.map((point) => ({
4054
+ t: Number(point.t),
4055
+ p: Number(point.p)
4056
+ })).filter((point) => Number.isFinite(point.t) && Number.isFinite(point.p));
4057
+ }
3058
4058
 
3059
4059
  // src/ai/errors.ts
3060
4060
  var AIError = class extends Error {
@@ -4363,6 +5363,9 @@ async function loadAndValidateTools(toolsDir, options = {}) {
4363
5363
  if (typeof schedule.enabled === "boolean") {
4364
5364
  normalizedSchedule.authoredEnabled = schedule.enabled;
4365
5365
  }
5366
+ if (typeof schedule.notifyEmail === "boolean") {
5367
+ normalizedSchedule.notifyEmail = schedule.notifyEmail;
5368
+ }
4366
5369
  }
4367
5370
  if (hasPOST) {
4368
5371
  if (!schema) {
@@ -4656,6 +5659,6 @@ function timestamp() {
4656
5659
  return (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").slice(0, 19);
4657
5660
  }
4658
5661
 
4659
- export { AIAbortError, AIError, AIFetchError, AIResponseError, DEFAULT_BASE_URL, DEFAULT_CHAIN, DEFAULT_FACILITATOR, DEFAULT_MODEL, DEFAULT_TIMEOUT_MS, DEFAULT_TOKENS, HTTP_METHODS2 as HTTP_METHODS, HyperliquidApiError, HyperliquidBuilderApprovalError, HyperliquidExchangeClient, HyperliquidGuardError, HyperliquidInfoClient, HyperliquidTermsError, PAYMENT_HEADERS, SUPPORTED_CURRENCIES, StoreError, WEBSEARCH_TOOL_DEFINITION, WEBSEARCH_TOOL_NAME, X402BrowserClient, X402Client, X402PaymentRequiredError, __hyperliquidInternals, approveHyperliquidBuilderFee, batchModifyHyperliquidOrders, cancelAllHyperliquidOrders, cancelHyperliquidOrders, cancelHyperliquidOrdersByCloid, cancelHyperliquidTwapOrder, chains, createAIClient, createDevServer, createHyperliquidSubAccount, createMcpAdapter, createMonotonicNonceFactory, createStdioServer, defineX402Payment, depositToHyperliquidBridge, ensureTextContent, fetchHyperliquidAssetCtxs, fetchHyperliquidClearinghouseState, fetchHyperliquidFrontendOpenOrders, fetchHyperliquidHistoricalOrders, fetchHyperliquidMeta, fetchHyperliquidMetaAndAssetCtxs, fetchHyperliquidOpenOrders, fetchHyperliquidOrderStatus, fetchHyperliquidPreTransferCheck, fetchHyperliquidSpotAssetCtxs, fetchHyperliquidSpotClearinghouseState, fetchHyperliquidSpotMeta, fetchHyperliquidSpotMetaAndAssetCtxs, fetchHyperliquidUserFills, fetchHyperliquidUserFillsByTime, fetchHyperliquidUserRateLimit, flattenMessageContent, generateMetadata, generateMetadataCommand, generateText, getHyperliquidMaxBuilderFee, getModelConfig, getRpcUrl, getX402PaymentContext, isStreamingSupported, isToolCallingSupported, listModels, loadAndValidateTools, modifyHyperliquidOrder, normalizeModelName, payX402, payX402WithWallet, placeHyperliquidOrder, placeHyperliquidTwapOrder, recordHyperliquidBuilderApproval, recordHyperliquidTermsAcceptance, registry, requireX402Payment, reserveHyperliquidRequestWeight, resolveConfig2 as resolveConfig, resolveRuntimePath, resolveToolset, responseToToolResponse, retrieve, scheduleHyperliquidCancel, sendHyperliquidSpot, store, streamText, tokens, transferHyperliquidSubAccount, updateHyperliquidIsolatedMargin, updateHyperliquidLeverage, validateCommand, wallet, walletToolkit, withX402Payment, withdrawFromHyperliquid };
5662
+ export { AIAbortError, AIError, AIFetchError, AIResponseError, DEFAULT_BASE_URL, DEFAULT_CHAIN, DEFAULT_FACILITATOR, DEFAULT_MODEL, DEFAULT_TIMEOUT_MS, DEFAULT_TOKENS, HTTP_METHODS2 as HTTP_METHODS, HyperliquidApiError, HyperliquidBuilderApprovalError, HyperliquidExchangeClient, HyperliquidGuardError, HyperliquidInfoClient, HyperliquidTermsError, PAYMENT_HEADERS, POLYMARKET_CHAIN_ID, POLYMARKET_CLOB_AUTH_DOMAIN, POLYMARKET_CLOB_DOMAIN, POLYMARKET_ENDPOINTS, POLYMARKET_EXCHANGE_ADDRESSES, PolymarketApiError, PolymarketAuthError, PolymarketExchangeClient, PolymarketInfoClient, SUPPORTED_CURRENCIES, StoreError, WEBSEARCH_TOOL_DEFINITION, WEBSEARCH_TOOL_NAME, X402BrowserClient, X402Client, X402PaymentRequiredError, __hyperliquidInternals, approveHyperliquidBuilderFee, batchModifyHyperliquidOrders, buildHmacSignature, buildL1Headers, buildL2Headers, buildPolymarketOrderAmounts, buildSignedOrderPayload, cancelAllHyperliquidOrders, cancelAllPolymarketOrders, cancelHyperliquidOrders, cancelHyperliquidOrdersByCloid, cancelHyperliquidTwapOrder, cancelMarketPolymarketOrders, cancelPolymarketOrder, cancelPolymarketOrders, chains, createAIClient, createDevServer, createHyperliquidSubAccount, createMcpAdapter, createMonotonicNonceFactory, createPolymarketApiKey, createStdioServer, defineX402Payment, depositToHyperliquidBridge, derivePolymarketApiKey, ensureTextContent, executeTool, fetchHyperliquidAssetCtxs, fetchHyperliquidClearinghouseState, fetchHyperliquidFrontendOpenOrders, fetchHyperliquidHistoricalOrders, fetchHyperliquidMeta, fetchHyperliquidMetaAndAssetCtxs, fetchHyperliquidOpenOrders, fetchHyperliquidOrderStatus, fetchHyperliquidPreTransferCheck, fetchHyperliquidSpotAssetCtxs, fetchHyperliquidSpotClearinghouseState, fetchHyperliquidSpotMeta, fetchHyperliquidSpotMetaAndAssetCtxs, fetchHyperliquidUserFills, fetchHyperliquidUserFillsByTime, fetchHyperliquidUserRateLimit, fetchPolymarketMarket, fetchPolymarketMarkets, fetchPolymarketMidpoint, fetchPolymarketOrderbook, fetchPolymarketPrice, fetchPolymarketPriceHistory, flattenMessageContent, generateMetadata, generateMetadataCommand, generateText, getHyperliquidMaxBuilderFee, getModelConfig, getMyPerformance, getMyTools, getRpcUrl, getX402PaymentContext, isStreamingSupported, isToolCallingSupported, listModels, loadAndValidateTools, modifyHyperliquidOrder, normalizeModelName, normalizeNumberArrayish, normalizeStringArrayish, payX402, payX402WithWallet, placeHyperliquidOrder, placeHyperliquidTwapOrder, placePolymarketOrder, postAgentDigest, recordHyperliquidBuilderApproval, recordHyperliquidTermsAcceptance, registry, requireX402Payment, reserveHyperliquidRequestWeight, resolveConfig2 as resolveConfig, resolveExchangeAddress, resolvePolymarketBaseUrl, resolveRuntimePath, resolveToolset, responseToToolResponse, retrieve, scheduleHyperliquidCancel, sendHyperliquidSpot, setHyperliquidPortfolioMargin, store, streamText, tokens, transferHyperliquidSubAccount, updateHyperliquidIsolatedMargin, updateHyperliquidLeverage, validateCommand, wallet, walletToolkit, withX402Payment, withdrawFromHyperliquid };
4660
5663
  //# sourceMappingURL=index.js.map
4661
5664
  //# sourceMappingURL=index.js.map