opentool 0.8.3 → 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';
@@ -1649,6 +1650,38 @@ function resolveConfig(options) {
1649
1650
  }
1650
1651
  return { baseUrl: normalizedBaseUrl, apiKey, fetchFn };
1651
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
+ }
1652
1685
  async function store(input, options) {
1653
1686
  const { baseUrl, apiKey, fetchFn } = resolveConfig(options);
1654
1687
  const url = `${baseUrl}/apps/positions/tx`;
@@ -1731,6 +1764,34 @@ async function retrieve(params, options) {
1731
1764
  }
1732
1765
  return data;
1733
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
+ }
1734
1795
  var CACHE_TTL_MS = 5 * 60 * 1e3;
1735
1796
  var API_BASES = {
1736
1797
  mainnet: "https://api.hyperliquid.xyz",
@@ -2066,6 +2127,181 @@ function assertPositiveNumber(value, label) {
2066
2127
  }
2067
2128
  }
2068
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
+
2069
2305
  // src/adapters/hyperliquid/exchange.ts
2070
2306
  var HyperliquidExchangeClient = class {
2071
2307
  constructor(args) {
@@ -2581,203 +2817,28 @@ async function postExchange(env, body) {
2581
2817
  return null;
2582
2818
  }
2583
2819
  })();
2584
- if (!response.ok) {
2585
- throw new HyperliquidApiError("Hyperliquid exchange action failed.", {
2586
- status: response.status,
2587
- statusText: response.statusText,
2588
- body: json ?? (text ? text : null)
2589
- });
2590
- }
2591
- if (!json) {
2592
- throw new HyperliquidApiError("Hyperliquid exchange action failed.", {
2593
- status: response.status,
2594
- statusText: response.statusText,
2595
- body: text ? text : null
2596
- });
2597
- }
2598
- if (json.status !== "ok") {
2599
- throw new HyperliquidApiError("Hyperliquid exchange returned error.", {
2600
- status: response.status,
2601
- statusText: response.statusText,
2602
- body: json
2603
- });
2604
- }
2605
- return json;
2606
- }
2607
-
2608
- // src/adapters/hyperliquid/info.ts
2609
- async function postInfo(environment, payload) {
2610
- const baseUrl = API_BASES[environment];
2611
- const response = await fetch(`${baseUrl}/info`, {
2612
- method: "POST",
2613
- headers: { "content-type": "application/json" },
2614
- body: JSON.stringify(payload)
2615
- });
2616
- const data = await response.json().catch(() => null);
2617
- if (!response.ok) {
2618
- throw new HyperliquidApiError(
2619
- "Hyperliquid info request failed.",
2620
- data ?? { status: response.status }
2621
- );
2622
- }
2623
- return data;
2624
- }
2625
- var HyperliquidInfoClient = class {
2626
- constructor(environment = "mainnet") {
2627
- this.environment = environment;
2628
- }
2629
- meta() {
2630
- return fetchHyperliquidMeta(this.environment);
2631
- }
2632
- metaAndAssetCtxs() {
2633
- return fetchHyperliquidMetaAndAssetCtxs(this.environment);
2634
- }
2635
- spotMeta() {
2636
- return fetchHyperliquidSpotMeta(this.environment);
2637
- }
2638
- spotMetaAndAssetCtxs() {
2639
- return fetchHyperliquidSpotMetaAndAssetCtxs(this.environment);
2640
- }
2641
- assetCtxs() {
2642
- return fetchHyperliquidAssetCtxs(this.environment);
2643
- }
2644
- spotAssetCtxs() {
2645
- return fetchHyperliquidSpotAssetCtxs(this.environment);
2646
- }
2647
- openOrders(user) {
2648
- return fetchHyperliquidOpenOrders({ user, environment: this.environment });
2649
- }
2650
- frontendOpenOrders(user) {
2651
- return fetchHyperliquidFrontendOpenOrders({
2652
- user,
2653
- environment: this.environment
2654
- });
2655
- }
2656
- orderStatus(user, oid) {
2657
- return fetchHyperliquidOrderStatus({
2658
- user,
2659
- oid,
2660
- environment: this.environment
2661
- });
2662
- }
2663
- historicalOrders(user) {
2664
- return fetchHyperliquidHistoricalOrders({
2665
- user,
2666
- environment: this.environment
2667
- });
2668
- }
2669
- userFills(user) {
2670
- return fetchHyperliquidUserFills({ user, environment: this.environment });
2671
- }
2672
- userFillsByTime(user, startTime, endTime) {
2673
- return fetchHyperliquidUserFillsByTime({
2674
- user,
2675
- startTime,
2676
- endTime,
2677
- environment: this.environment
2678
- });
2679
- }
2680
- userRateLimit(user) {
2681
- return fetchHyperliquidUserRateLimit({
2682
- user,
2683
- environment: this.environment
2684
- });
2685
- }
2686
- preTransferCheck(user, source) {
2687
- return fetchHyperliquidPreTransferCheck({
2688
- user,
2689
- source,
2690
- environment: this.environment
2691
- });
2692
- }
2693
- spotClearinghouseState(user) {
2694
- return fetchHyperliquidSpotClearinghouseState({
2695
- user,
2696
- environment: this.environment
2697
- });
2698
- }
2699
- };
2700
- async function fetchHyperliquidMeta(environment = "mainnet") {
2701
- return postInfo(environment, { type: "meta" });
2702
- }
2703
- async function fetchHyperliquidMetaAndAssetCtxs(environment = "mainnet") {
2704
- return postInfo(environment, { type: "metaAndAssetCtxs" });
2705
- }
2706
- async function fetchHyperliquidSpotMeta(environment = "mainnet") {
2707
- return postInfo(environment, { type: "spotMeta" });
2708
- }
2709
- async function fetchHyperliquidSpotMetaAndAssetCtxs(environment = "mainnet") {
2710
- return postInfo(environment, { type: "spotMetaAndAssetCtxs" });
2711
- }
2712
- async function fetchHyperliquidAssetCtxs(environment = "mainnet") {
2713
- return postInfo(environment, { type: "assetCtxs" });
2714
- }
2715
- async function fetchHyperliquidSpotAssetCtxs(environment = "mainnet") {
2716
- return postInfo(environment, { type: "spotAssetCtxs" });
2717
- }
2718
- async function fetchHyperliquidOpenOrders(params) {
2719
- const env = params.environment ?? "mainnet";
2720
- return postInfo(env, { type: "openOrders", user: normalizeAddress(params.user) });
2721
- }
2722
- async function fetchHyperliquidFrontendOpenOrders(params) {
2723
- const env = params.environment ?? "mainnet";
2724
- return postInfo(env, {
2725
- type: "frontendOpenOrders",
2726
- user: normalizeAddress(params.user)
2727
- });
2728
- }
2729
- async function fetchHyperliquidOrderStatus(params) {
2730
- const env = params.environment ?? "mainnet";
2731
- return postInfo(env, {
2732
- type: "orderStatus",
2733
- user: normalizeAddress(params.user),
2734
- oid: params.oid
2735
- });
2736
- }
2737
- async function fetchHyperliquidHistoricalOrders(params) {
2738
- const env = params.environment ?? "mainnet";
2739
- return postInfo(env, {
2740
- type: "historicalOrders",
2741
- user: normalizeAddress(params.user)
2742
- });
2743
- }
2744
- async function fetchHyperliquidUserFills(params) {
2745
- const env = params.environment ?? "mainnet";
2746
- return postInfo(env, {
2747
- type: "userFills",
2748
- user: normalizeAddress(params.user)
2749
- });
2750
- }
2751
- async function fetchHyperliquidUserFillsByTime(params) {
2752
- const env = params.environment ?? "mainnet";
2753
- return postInfo(env, {
2754
- type: "userFillsByTime",
2755
- user: normalizeAddress(params.user),
2756
- startTime: params.startTime,
2757
- endTime: params.endTime
2758
- });
2759
- }
2760
- async function fetchHyperliquidUserRateLimit(params) {
2761
- const env = params.environment ?? "mainnet";
2762
- return postInfo(env, {
2763
- type: "userRateLimit",
2764
- user: normalizeAddress(params.user)
2765
- });
2766
- }
2767
- async function fetchHyperliquidPreTransferCheck(params) {
2768
- const env = params.environment ?? "mainnet";
2769
- return postInfo(env, {
2770
- type: "preTransferCheck",
2771
- user: normalizeAddress(params.user),
2772
- source: normalizeAddress(params.source)
2773
- });
2774
- }
2775
- async function fetchHyperliquidSpotClearinghouseState(params) {
2776
- const env = params.environment ?? "mainnet";
2777
- return postInfo(env, {
2778
- type: "spotClearinghouseState",
2779
- user: normalizeAddress(params.user)
2780
- });
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;
2781
2842
  }
2782
2843
 
2783
2844
  // src/adapters/hyperliquid/index.ts
@@ -3167,6 +3228,833 @@ var __hyperliquidInternals = {
3167
3228
  createL1ActionHash,
3168
3229
  splitSignature
3169
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
+ }
3170
4058
 
3171
4059
  // src/ai/errors.ts
3172
4060
  var AIError = class extends Error {
@@ -4475,6 +5363,9 @@ async function loadAndValidateTools(toolsDir, options = {}) {
4475
5363
  if (typeof schedule.enabled === "boolean") {
4476
5364
  normalizedSchedule.authoredEnabled = schedule.enabled;
4477
5365
  }
5366
+ if (typeof schedule.notifyEmail === "boolean") {
5367
+ normalizedSchedule.notifyEmail = schedule.notifyEmail;
5368
+ }
4478
5369
  }
4479
5370
  if (hasPOST) {
4480
5371
  if (!schema) {
@@ -4768,6 +5659,6 @@ function timestamp() {
4768
5659
  return (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").slice(0, 19);
4769
5660
  }
4770
5661
 
4771
- 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, setHyperliquidPortfolioMargin, 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 };
4772
5663
  //# sourceMappingURL=index.js.map
4773
5664
  //# sourceMappingURL=index.js.map