clodds 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/README.md +79 -47
  2. package/dist/agents/handlers/kalshi.d.ts +1 -2
  3. package/dist/agents/handlers/kalshi.js +369 -616
  4. package/dist/agents/handlers/kalshi.js.map +1 -1
  5. package/dist/agents/handlers/types.d.ts +1 -1
  6. package/dist/agents/index.d.ts +1 -1
  7. package/dist/agents/index.js +435 -710
  8. package/dist/agents/index.js.map +1 -1
  9. package/dist/bittensor/index.d.ts +3 -2
  10. package/dist/bittensor/index.js +44 -5
  11. package/dist/bittensor/index.js.map +1 -1
  12. package/dist/cli/commands/gateway.js +37 -2
  13. package/dist/cli/commands/gateway.js.map +1 -1
  14. package/dist/cli/commands/index.js +3 -2
  15. package/dist/cli/commands/index.js.map +1 -1
  16. package/dist/cli/index.js +6 -4
  17. package/dist/cli/index.js.map +1 -1
  18. package/dist/cron/index.d.ts +1 -1
  19. package/dist/cron/index.js +26 -34
  20. package/dist/cron/index.js.map +1 -1
  21. package/dist/db/index.d.ts +12 -0
  22. package/dist/db/index.js +51 -23
  23. package/dist/db/index.js.map +1 -1
  24. package/dist/db/migrations.js +36 -0
  25. package/dist/db/migrations.js.map +1 -1
  26. package/dist/evm/index.d.ts +1 -0
  27. package/dist/evm/index.js +2 -0
  28. package/dist/evm/index.js.map +1 -1
  29. package/dist/evm/pancakeswap.d.ts +55 -0
  30. package/dist/evm/pancakeswap.js +299 -0
  31. package/dist/evm/pancakeswap.js.map +1 -0
  32. package/dist/exchanges/lighter/index.d.ts +95 -0
  33. package/dist/exchanges/lighter/index.js +154 -0
  34. package/dist/exchanges/lighter/index.js.map +1 -0
  35. package/dist/gateway/server.d.ts +9 -0
  36. package/dist/gateway/server.js +208 -1
  37. package/dist/gateway/server.js.map +1 -1
  38. package/dist/gateway/signal-bus.d.ts +2 -43
  39. package/dist/gateway/signal-bus.js.map +1 -1
  40. package/dist/index.js +40 -3
  41. package/dist/index.js.map +1 -1
  42. package/dist/mcp/security.d.ts +44 -0
  43. package/dist/mcp/security.js +143 -0
  44. package/dist/mcp/security.js.map +1 -0
  45. package/dist/mcp/server.js +27 -2
  46. package/dist/mcp/server.js.map +1 -1
  47. package/dist/services/alt-data/index.d.ts +1 -1
  48. package/dist/sessions/index.js +66 -7
  49. package/dist/sessions/index.js.map +1 -1
  50. package/dist/signal-router/router.d.ts +1 -1
  51. package/dist/signal-router/types.d.ts +1 -1
  52. package/dist/skills/bundled/arbitrage/index.js +96 -63
  53. package/dist/skills/bundled/arbitrage/index.js.map +1 -1
  54. package/dist/skills/bundled/betfair/index.js +121 -83
  55. package/dist/skills/bundled/betfair/index.js.map +1 -1
  56. package/dist/skills/bundled/bridge/index.js +42 -13
  57. package/dist/skills/bundled/bridge/index.js.map +1 -1
  58. package/dist/skills/bundled/crypto-hft/index.js +267 -226
  59. package/dist/skills/bundled/crypto-hft/index.js.map +1 -1
  60. package/dist/skills/bundled/drift/index.js +83 -52
  61. package/dist/skills/bundled/drift/index.js.map +1 -1
  62. package/dist/skills/bundled/embeddings/index.js +87 -49
  63. package/dist/skills/bundled/embeddings/index.js.map +1 -1
  64. package/dist/skills/bundled/execution/index.js +47 -25
  65. package/dist/skills/bundled/execution/index.js.map +1 -1
  66. package/dist/skills/bundled/feeds/index.js +45 -25
  67. package/dist/skills/bundled/feeds/index.js.map +1 -1
  68. package/dist/skills/bundled/hyperliquid/index.js +91 -45
  69. package/dist/skills/bundled/hyperliquid/index.js.map +1 -1
  70. package/dist/skills/bundled/integrations/index.js +2 -1
  71. package/dist/skills/bundled/integrations/index.js.map +1 -1
  72. package/dist/skills/bundled/kamino/index.js +71 -43
  73. package/dist/skills/bundled/kamino/index.js.map +1 -1
  74. package/dist/skills/bundled/lighter/index.d.ts +19 -0
  75. package/dist/skills/bundled/lighter/index.js +385 -0
  76. package/dist/skills/bundled/lighter/index.js.map +1 -0
  77. package/dist/skills/bundled/marginfi/index.d.ts +21 -0
  78. package/dist/skills/bundled/marginfi/index.js +387 -0
  79. package/dist/skills/bundled/marginfi/index.js.map +1 -0
  80. package/dist/skills/bundled/opinion/index.js +44 -25
  81. package/dist/skills/bundled/opinion/index.js.map +1 -1
  82. package/dist/skills/bundled/pancakeswap/index.d.ts +19 -0
  83. package/dist/skills/bundled/pancakeswap/index.js +260 -0
  84. package/dist/skills/bundled/pancakeswap/index.js.map +1 -0
  85. package/dist/skills/bundled/setup/index.d.ts +16 -0
  86. package/dist/skills/bundled/setup/index.js +427 -0
  87. package/dist/skills/bundled/setup/index.js.map +1 -0
  88. package/dist/skills/bundled/solend/index.d.ts +22 -0
  89. package/dist/skills/bundled/solend/index.js +401 -0
  90. package/dist/skills/bundled/solend/index.js.map +1 -0
  91. package/dist/skills/bundled/trading-evm/index.js +42 -11
  92. package/dist/skills/bundled/trading-evm/index.js.map +1 -1
  93. package/dist/skills/errors.d.ts +20 -0
  94. package/dist/skills/errors.js +84 -0
  95. package/dist/skills/errors.js.map +1 -0
  96. package/dist/skills/executor.d.ts +1 -1
  97. package/dist/skills/executor.js +515 -41
  98. package/dist/skills/executor.js.map +1 -1
  99. package/dist/skills/help.d.ts +33 -0
  100. package/dist/skills/help.js +73 -0
  101. package/dist/skills/help.js.map +1 -0
  102. package/dist/solana/marginfi.d.ts +112 -0
  103. package/dist/solana/marginfi.js +340 -0
  104. package/dist/solana/marginfi.js.map +1 -0
  105. package/dist/solana/solend.d.ts +120 -0
  106. package/dist/solana/solend.js +261 -0
  107. package/dist/solana/solend.js.map +1 -0
  108. package/dist/trading/bridge.d.ts +1 -1
  109. package/dist/trading/position-bridge.d.ts +1 -1
  110. package/dist/types/signal-bus.d.ts +48 -0
  111. package/dist/types/signal-bus.js +9 -0
  112. package/dist/types/signal-bus.js.map +1 -0
  113. package/dist/types.d.ts +17 -0
  114. package/dist/utils/json-utils.d.ts +8 -8
  115. package/package.json +8 -6
@@ -50,7 +50,9 @@ const path_1 = require("path");
50
50
  const os_1 = require("os");
51
51
  const logger_1 = require("../utils/logger");
52
52
  const loader_1 = require("../skills/loader");
53
- const credentials_1 = require("../credentials");
53
+ // credentials module is private (gitignored) — lazy-load at runtime
54
+ const _credPath = '../credentials/index.js';
55
+ const _loadCredentials = () => Promise.resolve(`${_credPath}`).then(s => __importStar(require(s))).then(m => m.createCredentialsManager);
54
56
  const memory_1 = require("../memory");
55
57
  const index_1 = require("../security/index");
56
58
  const permissions_1 = require("../permissions");
@@ -8750,21 +8752,15 @@ async function executeTool(toolName, toolInput, context) {
8750
8752
  if (!tokenId) {
8751
8753
  return JSON.stringify({ error: 'Could not determine token ID from original trade' });
8752
8754
  }
8753
- // Execute the copy trade via Python script
8754
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
8755
- const cmd = side === 'BUY'
8756
- ? `cd ${tradingDir} && python3 polymarket.py buy ${tokenId} ${price} ${copySize}`
8757
- : `cd ${tradingDir} && python3 polymarket.py sell ${tokenId} ${copySize} ${price}`;
8758
- const creds = polyCreds.data;
8759
- const userEnv = {
8760
- ...process.env,
8761
- PRIVATE_KEY: creds.privateKey,
8762
- POLY_FUNDER_ADDRESS: creds.funderAddress,
8763
- POLY_API_KEY: creds.apiKey,
8764
- POLY_API_SECRET: creds.apiSecret,
8765
- POLY_API_PASSPHRASE: creds.apiPassphrase,
8766
- };
8767
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8', env: userEnv });
8755
+ // Execute the copy trade via execution service
8756
+ const execSvc = context.tradingContext?.executionService;
8757
+ if (!execSvc) {
8758
+ return JSON.stringify({ error: 'Trading execution not available. Configure trading.enabled=true.' });
8759
+ }
8760
+ const orderResult = side === 'BUY'
8761
+ ? await execSvc.buyLimit({ platform: 'polymarket', marketId: tokenId, tokenId, price, size: copySize })
8762
+ : await execSvc.sellLimit({ platform: 'polymarket', marketId: tokenId, tokenId, price, size: copySize });
8763
+ const output = JSON.stringify(orderResult);
8768
8764
  await context.credentials.markSuccess(userId, 'polymarket');
8769
8765
  return JSON.stringify({
8770
8766
  result: {
@@ -9026,31 +9022,23 @@ async function executeTool(toolName, toolInput, context) {
9026
9022
  }
9027
9023
  const edge = (1 - sum) * 100;
9028
9024
  const profit = (size * 2) * (1 - sum);
9029
- // Execute both trades
9030
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
9031
- const creds = polyCreds.data;
9032
- const userEnv = {
9033
- ...process.env,
9034
- PRIVATE_KEY: creds.privateKey,
9035
- POLY_FUNDER_ADDRESS: creds.funderAddress,
9036
- POLY_API_KEY: creds.apiKey,
9037
- POLY_API_SECRET: creds.apiSecret,
9038
- POLY_API_PASSPHRASE: creds.apiPassphrase,
9039
- };
9025
+ // Execute both trades via execution service
9026
+ const execSvc = context.tradingContext?.executionService;
9027
+ if (!execSvc) {
9028
+ return JSON.stringify({ error: 'Trading execution not available. Configure trading.enabled=true.' });
9029
+ }
9040
9030
  // Buy YES
9041
- const yesCmd = `cd ${tradingDir} && python3 polymarket.py buy ${yesToken.token_id} ${yesAsk} ${size}`;
9042
- const yesOutput = (0, child_process_1.execSync)(yesCmd, { timeout: 30000, encoding: 'utf-8', env: userEnv });
9031
+ const yesResult = await execSvc.buyLimit({ platform: 'polymarket', marketId: yesToken.token_id, tokenId: yesToken.token_id, price: yesAsk, size });
9043
9032
  // Buy NO
9044
- const noCmd = `cd ${tradingDir} && python3 polymarket.py buy ${noToken.token_id} ${noAsk} ${size}`;
9045
- const noOutput = (0, child_process_1.execSync)(noCmd, { timeout: 30000, encoding: 'utf-8', env: userEnv });
9033
+ const noResult = await execSvc.buyLimit({ platform: 'polymarket', marketId: noToken.token_id, tokenId: noToken.token_id, price: noAsk, size });
9046
9034
  await context.credentials.markSuccess(userId, 'polymarket');
9047
9035
  return JSON.stringify({
9048
9036
  result: {
9049
9037
  status: 'executed',
9050
9038
  market: marketData.question?.slice(0, 50) || marketId,
9051
9039
  trades: [
9052
- { side: 'YES', price: `${Math.round(yesAsk * 100)}¢`, size, output: yesOutput.trim() },
9053
- { side: 'NO', price: `${Math.round(noAsk * 100)}¢`, size, output: noOutput.trim() },
9040
+ { side: 'YES', price: `${Math.round(yesAsk * 100)}¢`, size, result: yesResult },
9041
+ { side: 'NO', price: `${Math.round(noAsk * 100)}¢`, size, result: noResult },
9054
9042
  ],
9055
9043
  edge: `${edge.toFixed(2)}%`,
9056
9044
  expectedProfit: `$${profit.toFixed(2)}`,
@@ -9060,10 +9048,7 @@ async function executeTool(toolName, toolInput, context) {
9060
9048
  }
9061
9049
  catch (err) {
9062
9050
  const error = err;
9063
- if (error.stderr?.includes('auth') || error.stderr?.includes('401')) {
9064
- await context.credentials.markFailure(userId, 'polymarket');
9065
- }
9066
- return JSON.stringify({ error: 'Arbitrage execution failed', details: error.stderr || error.message });
9051
+ return JSON.stringify({ error: 'Arbitrage execution failed', details: error.message });
9067
9052
  }
9068
9053
  }
9069
9054
  // ============================================
@@ -9391,24 +9376,22 @@ async function executeTool(toolName, toolInput, context) {
9391
9376
  error: 'No Polymarket credentials set up. Use setup_polymarket_credentials first.',
9392
9377
  });
9393
9378
  }
9394
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
9395
- const cmd = `cd ${tradingDir} && python3 polymarket.py positions`;
9396
9379
  const creds = polyCreds.data;
9397
- const userEnv = {
9398
- ...process.env,
9399
- PRIVATE_KEY: creds.privateKey,
9400
- POLY_FUNDER_ADDRESS: creds.funderAddress,
9401
- POLY_API_KEY: creds.apiKey,
9402
- POLY_API_SECRET: creds.apiSecret,
9403
- POLY_API_PASSPHRASE: creds.apiPassphrase,
9404
- };
9380
+ const auth = getPolymarketApiKeyAuth(creds);
9381
+ if (!auth) {
9382
+ return JSON.stringify({ error: 'Incomplete Polymarket credentials.' });
9383
+ }
9405
9384
  try {
9406
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8', env: userEnv });
9407
- return JSON.stringify({ result: output.trim() });
9385
+ const { getPolymarketPositions } = await Promise.resolve().then(() => __importStar(require('../execution')));
9386
+ const positions = await getPolymarketPositions(auth);
9387
+ if (positions.length === 0) {
9388
+ return JSON.stringify({ result: 'No open positions.' });
9389
+ }
9390
+ return JSON.stringify({ positions, count: positions.length });
9408
9391
  }
9409
9392
  catch (err) {
9410
9393
  const error = err;
9411
- return JSON.stringify({ error: 'Failed to get positions', details: error.stderr || error.message });
9394
+ return JSON.stringify({ error: 'Failed to get positions', details: error.message });
9412
9395
  }
9413
9396
  }
9414
9397
  case 'polymarket_cancel_all': {
@@ -9438,15 +9421,19 @@ async function executeTool(toolName, toolInput, context) {
9438
9421
  case 'polymarket_orderbook': {
9439
9422
  // Orderbook is public - no credentials required
9440
9423
  const tokenId = toolInput.token_id;
9441
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
9442
- const cmd = `cd ${tradingDir} && python3 polymarket.py orderbook ${tokenId}`;
9443
9424
  try {
9444
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
9445
- return JSON.stringify({ result: output.trim() });
9425
+ const response = await fetch(`https://clob.polymarket.com/book?token_id=${tokenId}`);
9426
+ if (!response.ok) {
9427
+ return JSON.stringify({ error: `Orderbook fetch failed: ${response.status}` });
9428
+ }
9429
+ const data = await response.json();
9430
+ const bids = (data.bids || []).slice(0, 10);
9431
+ const asks = (data.asks || []).slice(0, 10);
9432
+ return JSON.stringify({ token_id: tokenId, bids, asks, bid_count: bids.length, ask_count: asks.length });
9446
9433
  }
9447
9434
  catch (err) {
9448
9435
  const error = err;
9449
- return JSON.stringify({ error: 'Orderbook fetch failed', details: error.stderr || error.message });
9436
+ return JSON.stringify({ error: 'Orderbook fetch failed', details: error.message });
9450
9437
  }
9451
9438
  }
9452
9439
  case 'polymarket_balance': {
@@ -9456,24 +9443,23 @@ async function executeTool(toolName, toolInput, context) {
9456
9443
  error: 'No Polymarket credentials set up. Use setup_polymarket_credentials first.',
9457
9444
  });
9458
9445
  }
9459
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
9460
- const cmd = `cd ${tradingDir} && python3 polymarket.py balance`;
9461
9446
  const creds = polyCreds.data;
9462
- const userEnv = {
9463
- ...process.env,
9464
- PRIVATE_KEY: creds.privateKey,
9465
- POLY_FUNDER_ADDRESS: creds.funderAddress,
9466
- POLY_API_KEY: creds.apiKey,
9467
- POLY_API_SECRET: creds.apiSecret,
9468
- POLY_API_PASSPHRASE: creds.apiPassphrase,
9469
- };
9447
+ const auth = getPolymarketApiKeyAuth(creds);
9448
+ if (!auth) {
9449
+ return JSON.stringify({ error: 'Incomplete Polymarket credentials.' });
9450
+ }
9470
9451
  try {
9471
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8', env: userEnv });
9472
- return JSON.stringify({ result: output.trim() });
9452
+ const { getPolymarketBalance } = await Promise.resolve().then(() => __importStar(require('../execution')));
9453
+ const { balance, allowance } = await getPolymarketBalance(auth);
9454
+ return JSON.stringify({
9455
+ balance: `$${balance.toFixed(2)} USDC`,
9456
+ allowance: `$${allowance.toFixed(2)} USDC`,
9457
+ raw: { balance, allowance },
9458
+ });
9473
9459
  }
9474
9460
  catch (err) {
9475
9461
  const error = err;
9476
- return JSON.stringify({ error: 'Balance fetch failed', details: error.stderr || error.message });
9462
+ return JSON.stringify({ error: 'Balance fetch failed', details: error.message });
9477
9463
  }
9478
9464
  }
9479
9465
  case 'polymarket_cancel': {
@@ -9855,103 +9841,80 @@ async function executeTool(toolName, toolInput, context) {
9855
9841
  error: 'No Polymarket credentials set up. Use setup_polymarket_credentials first.',
9856
9842
  });
9857
9843
  }
9858
- const marketId = toolInput.market_id;
9859
- const tokenId = toolInput.token_id;
9860
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
9861
- let cmd = `cd ${tradingDir} && python3 polymarket.py trades`;
9862
- if (marketId)
9863
- cmd += ` --market ${marketId}`;
9864
- if (tokenId)
9865
- cmd += ` --token ${tokenId}`;
9866
9844
  const creds = polyCreds.data;
9867
- const userEnv = {
9868
- ...process.env,
9869
- PRIVATE_KEY: creds.privateKey,
9870
- POLY_FUNDER_ADDRESS: creds.funderAddress,
9871
- POLY_API_KEY: creds.apiKey,
9872
- POLY_API_SECRET: creds.apiSecret,
9873
- POLY_API_PASSPHRASE: creds.apiPassphrase,
9874
- };
9845
+ const auth = getPolymarketApiKeyAuth(creds);
9846
+ if (!auth) {
9847
+ return JSON.stringify({ error: 'Incomplete Polymarket credentials.' });
9848
+ }
9875
9849
  try {
9876
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8', env: userEnv });
9850
+ const { getPolymarketTrades } = await Promise.resolve().then(() => __importStar(require('../execution')));
9851
+ const trades = await getPolymarketTrades(auth);
9877
9852
  await context.credentials.markSuccess(userId, 'polymarket');
9878
- return JSON.stringify({ result: 'Trade history', output: output.trim() });
9853
+ if (trades.length === 0) {
9854
+ return JSON.stringify({ result: 'No recent trades.' });
9855
+ }
9856
+ return JSON.stringify({ trades: trades.slice(0, 50), count: trades.length });
9879
9857
  }
9880
9858
  catch (err) {
9881
9859
  const error = err;
9882
- if (error.stderr?.includes('auth') || error.stderr?.includes('401')) {
9883
- await context.credentials.markFailure(userId, 'polymarket');
9884
- }
9885
- return JSON.stringify({ error: 'Trade history failed', details: error.stderr || error.message });
9860
+ return JSON.stringify({ error: 'Trade history failed', details: error.message });
9886
9861
  }
9887
9862
  }
9888
9863
  case 'polymarket_cancel_market': {
9889
- const polyCreds = context.tradingContext?.credentials.get('polymarket');
9890
- if (!polyCreds || polyCreds.platform !== 'polymarket') {
9891
- return JSON.stringify({
9892
- error: 'No Polymarket credentials set up. Use setup_polymarket_credentials first.',
9893
- });
9894
- }
9895
- const marketId = toolInput.market_id;
9896
- const tokenId = toolInput.token_id;
9897
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
9898
- let cmd = `cd ${tradingDir} && python3 polymarket.py cancel_market ${marketId}`;
9899
- if (tokenId)
9900
- cmd += ` ${tokenId}`;
9901
- const creds = polyCreds.data;
9902
- const userEnv = {
9903
- ...process.env,
9904
- PRIVATE_KEY: creds.privateKey,
9905
- POLY_FUNDER_ADDRESS: creds.funderAddress,
9906
- POLY_API_KEY: creds.apiKey,
9907
- POLY_API_SECRET: creds.apiSecret,
9908
- POLY_API_PASSPHRASE: creds.apiPassphrase,
9909
- };
9910
- try {
9911
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8', env: userEnv });
9912
- await context.credentials.markSuccess(userId, 'polymarket');
9913
- return JSON.stringify({ result: 'Orders cancelled for market', output: output.trim() });
9914
- }
9915
- catch (err) {
9916
- const error = err;
9917
- if (error.stderr?.includes('auth') || error.stderr?.includes('401')) {
9918
- await context.credentials.markFailure(userId, 'polymarket');
9864
+ const execSvc = context.tradingContext?.executionService;
9865
+ if (execSvc) {
9866
+ try {
9867
+ const marketId = toolInput.market_id;
9868
+ const cancelledCount = await execSvc.cancelAllOrders('polymarket', marketId);
9869
+ await context.credentials.markSuccess(userId, 'polymarket');
9870
+ return JSON.stringify({ result: 'Orders cancelled for market', cancelledCount });
9871
+ }
9872
+ catch (err) {
9873
+ const error = err;
9874
+ return JSON.stringify({ error: 'Cancel market orders failed', details: error.message });
9919
9875
  }
9920
- return JSON.stringify({ error: 'Cancel market orders failed', details: error.stderr || error.message });
9921
9876
  }
9877
+ return JSON.stringify({ error: 'Trading execution not available. Configure trading.enabled=true.' });
9922
9878
  }
9923
9879
  case 'polymarket_estimate_fill': {
9924
- const polyCreds = context.tradingContext?.credentials.get('polymarket');
9925
- if (!polyCreds || polyCreds.platform !== 'polymarket') {
9926
- return JSON.stringify({
9927
- error: 'No Polymarket credentials set up. Use setup_polymarket_credentials first.',
9928
- });
9929
- }
9880
+ // Estimate fill by fetching orderbook and calculating slippage
9930
9881
  const tokenId = toolInput.token_id;
9931
- const side = toolInput.side;
9882
+ const side = toolInput.side.toUpperCase();
9932
9883
  const amount = toolInput.amount;
9933
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
9934
- const cmd = `cd ${tradingDir} && python3 polymarket.py estimate_fill ${tokenId} ${side} ${amount}`;
9935
- const creds = polyCreds.data;
9936
- const userEnv = {
9937
- ...process.env,
9938
- PRIVATE_KEY: creds.privateKey,
9939
- POLY_FUNDER_ADDRESS: creds.funderAddress,
9940
- POLY_API_KEY: creds.apiKey,
9941
- POLY_API_SECRET: creds.apiSecret,
9942
- POLY_API_PASSPHRASE: creds.apiPassphrase,
9943
- };
9944
9884
  try {
9945
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8', env: userEnv });
9946
- await context.credentials.markSuccess(userId, 'polymarket');
9947
- return JSON.stringify({ result: 'Fill estimate', output: output.trim() });
9885
+ const response = await fetch(`https://clob.polymarket.com/book?token_id=${tokenId}`);
9886
+ if (!response.ok) {
9887
+ return JSON.stringify({ error: `Orderbook fetch failed: ${response.status}` });
9888
+ }
9889
+ const book = await response.json();
9890
+ const levels = side === 'BUY' ? (book.asks || []) : (book.bids || []);
9891
+ let remaining = amount;
9892
+ let totalCost = 0;
9893
+ const fills = [];
9894
+ for (const level of levels) {
9895
+ if (remaining <= 0)
9896
+ break;
9897
+ const levelSize = parseFloat(level.size);
9898
+ const levelPrice = parseFloat(level.price);
9899
+ const fillSize = Math.min(remaining, levelSize);
9900
+ totalCost += fillSize * levelPrice;
9901
+ fills.push({ price: level.price, size: fillSize });
9902
+ remaining -= fillSize;
9903
+ }
9904
+ const avgPrice = amount > 0 ? totalCost / (amount - remaining) : 0;
9905
+ return JSON.stringify({
9906
+ token_id: tokenId,
9907
+ side,
9908
+ requested: amount,
9909
+ filled: amount - remaining,
9910
+ unfilled: remaining,
9911
+ avg_price: avgPrice.toFixed(4),
9912
+ total_cost: totalCost.toFixed(2),
9913
+ fills,
9914
+ });
9948
9915
  }
9949
9916
  catch (err) {
9950
- const error = err;
9951
- if (error.stderr?.includes('auth') || error.stderr?.includes('401')) {
9952
- await context.credentials.markFailure(userId, 'polymarket');
9953
- }
9954
- return JSON.stringify({ error: 'Fill estimate failed', details: error.stderr || error.message });
9917
+ return JSON.stringify({ error: 'Fill estimate failed', details: err.message });
9955
9918
  }
9956
9919
  }
9957
9920
  case 'polymarket_market_info': {
@@ -10095,11 +10058,13 @@ async function executeTool(toolName, toolInput, context) {
10095
10058
  // ========== BATCH HANDLERS ==========
10096
10059
  case 'polymarket_midpoints_batch': {
10097
10060
  const tokenIds = toolInput.token_ids;
10098
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10099
- const cmd = `cd ${tradingDir} && python3 polymarket.py midpoints_batch ${tokenIds.join(',')}`;
10100
10061
  try {
10101
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
10102
- return output.trim();
10062
+ const results = await Promise.all(tokenIds.map(async (id) => {
10063
+ const r = await fetch(`https://clob.polymarket.com/midpoint?token_id=${id}`);
10064
+ const d = await r.json();
10065
+ return { token_id: id, mid: d.mid };
10066
+ }));
10067
+ return JSON.stringify(results);
10103
10068
  }
10104
10069
  catch (err) {
10105
10070
  return JSON.stringify({ error: err.message });
@@ -10107,12 +10072,13 @@ async function executeTool(toolName, toolInput, context) {
10107
10072
  }
10108
10073
  case 'polymarket_prices_batch': {
10109
10074
  const requests = toolInput.requests;
10110
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10111
- const requestsJson = JSON.stringify(requests);
10112
- const cmd = `cd ${tradingDir} && python3 polymarket.py prices_batch '${requestsJson}'`;
10113
10075
  try {
10114
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
10115
- return output.trim();
10076
+ const results = await Promise.all(requests.map(async (req) => {
10077
+ const r = await fetch(`https://clob.polymarket.com/price?token_id=${req.token_id}&side=${req.side}`);
10078
+ const d = await r.json();
10079
+ return { token_id: req.token_id, side: req.side, price: d.price };
10080
+ }));
10081
+ return JSON.stringify(results);
10116
10082
  }
10117
10083
  catch (err) {
10118
10084
  return JSON.stringify({ error: err.message });
@@ -10120,11 +10086,13 @@ async function executeTool(toolName, toolInput, context) {
10120
10086
  }
10121
10087
  case 'polymarket_spreads_batch': {
10122
10088
  const tokenIds = toolInput.token_ids;
10123
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10124
- const cmd = `cd ${tradingDir} && python3 polymarket.py spreads_batch ${tokenIds.join(',')}`;
10125
10089
  try {
10126
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
10127
- return output.trim();
10090
+ const results = await Promise.all(tokenIds.map(async (id) => {
10091
+ const r = await fetch(`https://clob.polymarket.com/spread?token_id=${id}`);
10092
+ const d = await r.json();
10093
+ return { token_id: id, spread: d.spread };
10094
+ }));
10095
+ return JSON.stringify(results);
10128
10096
  }
10129
10097
  catch (err) {
10130
10098
  return JSON.stringify({ error: err.message });
@@ -10132,11 +10100,13 @@ async function executeTool(toolName, toolInput, context) {
10132
10100
  }
10133
10101
  case 'polymarket_orderbooks_batch': {
10134
10102
  const tokenIds = toolInput.token_ids;
10135
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10136
- const cmd = `cd ${tradingDir} && python3 polymarket.py orderbooks_batch ${tokenIds.join(',')}`;
10137
10103
  try {
10138
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
10139
- return output.trim();
10104
+ const results = await Promise.all(tokenIds.map(async (id) => {
10105
+ const r = await fetch(`https://clob.polymarket.com/book?token_id=${id}`);
10106
+ const d = await r.json();
10107
+ return { token_id: id, bids: (d.bids || []).slice(0, 5), asks: (d.asks || []).slice(0, 5) };
10108
+ }));
10109
+ return JSON.stringify(results);
10140
10110
  }
10141
10111
  catch (err) {
10142
10112
  return JSON.stringify({ error: err.message });
@@ -10144,11 +10114,13 @@ async function executeTool(toolName, toolInput, context) {
10144
10114
  }
10145
10115
  case 'polymarket_last_trades_batch': {
10146
10116
  const tokenIds = toolInput.token_ids;
10147
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10148
- const cmd = `cd ${tradingDir} && python3 polymarket.py last_trades_batch ${tokenIds.join(',')}`;
10149
10117
  try {
10150
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
10151
- return output.trim();
10118
+ const results = await Promise.all(tokenIds.map(async (id) => {
10119
+ const r = await fetch(`https://clob.polymarket.com/last-trade-price?token_id=${id}`);
10120
+ const d = await r.json();
10121
+ return { token_id: id, price: d.price };
10122
+ }));
10123
+ return JSON.stringify(results);
10152
10124
  }
10153
10125
  catch (err) {
10154
10126
  return JSON.stringify({ error: err.message });
@@ -10250,28 +10222,15 @@ async function executeTool(toolName, toolInput, context) {
10250
10222
  }
10251
10223
  // ========== ORDER OPERATIONS HANDLERS ==========
10252
10224
  case 'polymarket_get_order': {
10253
- const polyCreds = context.tradingContext?.credentials.get('polymarket');
10254
- if (!polyCreds) {
10255
- return JSON.stringify({ error: 'No Polymarket credentials set up.' });
10256
- }
10257
- const orderId = toolInput.order_id;
10258
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10259
- const cmd = `cd ${tradingDir} && python3 polymarket.py get_order ${orderId}`;
10260
- const creds = polyCreds.data;
10261
- const userEnv = {
10262
- ...process.env,
10263
- PRIVATE_KEY: creds.privateKey,
10264
- POLY_FUNDER_ADDRESS: creds.funderAddress,
10265
- POLY_API_KEY: creds.apiKey,
10266
- POLY_API_SECRET: creds.apiSecret,
10267
- POLY_API_PASSPHRASE: creds.apiPassphrase,
10268
- };
10269
10225
  try {
10270
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8', env: userEnv });
10271
- return output.trim();
10226
+ const orderId = toolInput.order_id;
10227
+ const url = `https://clob.polymarket.com/order/${orderId}`;
10228
+ const response = await fetchPolymarketClob(context, url);
10229
+ const data = await response.json();
10230
+ return JSON.stringify(data);
10272
10231
  }
10273
10232
  catch (err) {
10274
- return JSON.stringify({ error: err.stderr || err.message });
10233
+ return JSON.stringify({ error: err.message });
10275
10234
  }
10276
10235
  }
10277
10236
  case 'polymarket_post_orders_batch': {
@@ -10311,415 +10270,206 @@ async function executeTool(toolName, toolInput, context) {
10311
10270
  return exposureError;
10312
10271
  }
10313
10272
  }
10314
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10315
- const ordersJson = JSON.stringify(orders);
10316
- const cmd = `cd ${tradingDir} && python3 polymarket.py post_orders_batch '${ordersJson}'`;
10317
- const creds = polyCreds.data;
10318
- const userEnv = {
10319
- ...process.env,
10320
- PRIVATE_KEY: creds.privateKey,
10321
- POLY_FUNDER_ADDRESS: creds.funderAddress,
10322
- POLY_API_KEY: creds.apiKey,
10323
- POLY_API_SECRET: creds.apiSecret,
10324
- POLY_API_PASSPHRASE: creds.apiPassphrase,
10325
- };
10326
- try {
10327
- const output = (0, child_process_1.execSync)(cmd, { timeout: 60000, encoding: 'utf-8', env: userEnv });
10328
- await context.credentials.markSuccess(userId, 'polymarket');
10329
- return output.trim();
10330
- }
10331
- catch (err) {
10332
- return JSON.stringify({ error: err.stderr || err.message });
10273
+ const execSvc = context.tradingContext?.executionService;
10274
+ if (execSvc) {
10275
+ try {
10276
+ const results = [];
10277
+ for (const order of orders) {
10278
+ const side = String(order.side || '').toUpperCase();
10279
+ const result = side === 'BUY'
10280
+ ? await execSvc.buyLimit({ platform: 'polymarket', marketId: order.token_id, tokenId: order.token_id, price: order.price, size: order.size })
10281
+ : await execSvc.sellLimit({ platform: 'polymarket', marketId: order.token_id, tokenId: order.token_id, price: order.price, size: order.size });
10282
+ results.push(result);
10283
+ }
10284
+ await context.credentials.markSuccess(userId, 'polymarket');
10285
+ return JSON.stringify({ results });
10286
+ }
10287
+ catch (err) {
10288
+ return JSON.stringify({ error: err.message });
10289
+ }
10333
10290
  }
10291
+ return JSON.stringify({ error: 'Trading execution not available.' });
10334
10292
  }
10335
10293
  case 'polymarket_cancel_orders_batch': {
10336
- const polyCreds = context.tradingContext?.credentials.get('polymarket');
10337
- if (!polyCreds) {
10338
- return JSON.stringify({ error: 'No Polymarket credentials set up.' });
10339
- }
10340
- const orderIds = toolInput.order_ids;
10341
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10342
- const cmd = `cd ${tradingDir} && python3 polymarket.py cancel_orders_batch ${orderIds.join(',')}`;
10343
- const creds = polyCreds.data;
10344
- const userEnv = {
10345
- ...process.env,
10346
- PRIVATE_KEY: creds.privateKey,
10347
- POLY_FUNDER_ADDRESS: creds.funderAddress,
10348
- POLY_API_KEY: creds.apiKey,
10349
- POLY_API_SECRET: creds.apiSecret,
10350
- POLY_API_PASSPHRASE: creds.apiPassphrase,
10351
- };
10352
- try {
10353
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8', env: userEnv });
10354
- await context.credentials.markSuccess(userId, 'polymarket');
10355
- return output.trim();
10356
- }
10357
- catch (err) {
10358
- return JSON.stringify({ error: err.stderr || err.message });
10294
+ const execSvc = context.tradingContext?.executionService;
10295
+ if (execSvc) {
10296
+ try {
10297
+ const orderIds = toolInput.order_ids;
10298
+ const results = [];
10299
+ for (const oid of orderIds) {
10300
+ const success = await execSvc.cancelOrder('polymarket', oid);
10301
+ results.push({ orderId: oid, success });
10302
+ }
10303
+ await context.credentials.markSuccess(userId, 'polymarket');
10304
+ return JSON.stringify({ result: 'Orders cancelled', cancelled: results });
10305
+ }
10306
+ catch (err) {
10307
+ return JSON.stringify({ error: err.message });
10308
+ }
10359
10309
  }
10310
+ return JSON.stringify({ error: 'Trading execution not available.' });
10360
10311
  }
10361
10312
  // ========== API KEY MANAGEMENT HANDLERS ==========
10362
- case 'polymarket_create_api_key': {
10363
- const polyCreds = context.tradingContext?.credentials.get('polymarket');
10364
- if (!polyCreds) {
10365
- return JSON.stringify({ error: 'No Polymarket credentials set up.' });
10366
- }
10367
- const nonce = toolInput.nonce || 0;
10368
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10369
- const cmd = `cd ${tradingDir} && python3 polymarket.py create_api_key ${nonce}`;
10370
- const creds = polyCreds.data;
10371
- const userEnv = {
10372
- ...process.env,
10373
- PRIVATE_KEY: creds.privateKey,
10374
- POLY_FUNDER_ADDRESS: creds.funderAddress,
10375
- };
10376
- try {
10377
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8', env: userEnv });
10378
- return output.trim();
10379
- }
10380
- catch (err) {
10381
- return JSON.stringify({ error: err.stderr || err.message });
10382
- }
10383
- }
10313
+ case 'polymarket_create_api_key':
10384
10314
  case 'polymarket_derive_api_key': {
10385
- const polyCreds = context.tradingContext?.credentials.get('polymarket');
10386
- if (!polyCreds) {
10387
- return JSON.stringify({ error: 'No Polymarket credentials set up.' });
10388
- }
10389
- const nonce = toolInput.nonce || 0;
10390
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10391
- const cmd = `cd ${tradingDir} && python3 polymarket.py derive_api_key ${nonce}`;
10392
- const creds = polyCreds.data;
10393
- const userEnv = {
10394
- ...process.env,
10395
- PRIVATE_KEY: creds.privateKey,
10396
- POLY_FUNDER_ADDRESS: creds.funderAddress,
10397
- };
10398
- try {
10399
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8', env: userEnv });
10400
- return output.trim();
10401
- }
10402
- catch (err) {
10403
- return JSON.stringify({ error: err.stderr || err.message });
10404
- }
10315
+ // These require L1 wallet signing which needs the private key signer — not available via REST alone
10316
+ return JSON.stringify({ error: 'API key creation requires wallet signing. Use the Polymarket web interface or CLI.' });
10405
10317
  }
10406
10318
  case 'polymarket_get_api_keys': {
10407
- const polyCreds = context.tradingContext?.credentials.get('polymarket');
10408
- if (!polyCreds) {
10409
- return JSON.stringify({ error: 'No Polymarket credentials set up.' });
10410
- }
10411
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10412
- const cmd = `cd ${tradingDir} && python3 polymarket.py get_api_keys`;
10413
- const creds = polyCreds.data;
10414
- const userEnv = {
10415
- ...process.env,
10416
- PRIVATE_KEY: creds.privateKey,
10417
- POLY_FUNDER_ADDRESS: creds.funderAddress,
10418
- POLY_API_KEY: creds.apiKey,
10419
- POLY_API_SECRET: creds.apiSecret,
10420
- POLY_API_PASSPHRASE: creds.apiPassphrase,
10421
- };
10422
10319
  try {
10423
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8', env: userEnv });
10424
- return output.trim();
10320
+ const response = await fetchPolymarketClob(context, 'https://clob.polymarket.com/api-keys');
10321
+ const data = await response.json();
10322
+ return JSON.stringify(data);
10425
10323
  }
10426
10324
  catch (err) {
10427
- return JSON.stringify({ error: err.stderr || err.message });
10325
+ return JSON.stringify({ error: err.message });
10428
10326
  }
10429
10327
  }
10430
10328
  case 'polymarket_delete_api_key': {
10431
- const polyCreds = context.tradingContext?.credentials.get('polymarket');
10432
- if (!polyCreds) {
10433
- return JSON.stringify({ error: 'No Polymarket credentials set up.' });
10434
- }
10435
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10436
- const cmd = `cd ${tradingDir} && python3 polymarket.py delete_api_key`;
10437
- const creds = polyCreds.data;
10438
- const userEnv = {
10439
- ...process.env,
10440
- PRIVATE_KEY: creds.privateKey,
10441
- POLY_FUNDER_ADDRESS: creds.funderAddress,
10442
- POLY_API_KEY: creds.apiKey,
10443
- POLY_API_SECRET: creds.apiSecret,
10444
- POLY_API_PASSPHRASE: creds.apiPassphrase,
10445
- };
10446
10329
  try {
10447
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8', env: userEnv });
10448
- return output.trim();
10330
+ const response = await fetchPolymarketClob(context, 'https://clob.polymarket.com/api-key', { method: 'DELETE' });
10331
+ const data = await response.json();
10332
+ return JSON.stringify(data);
10449
10333
  }
10450
10334
  catch (err) {
10451
- return JSON.stringify({ error: err.stderr || err.message });
10335
+ return JSON.stringify({ error: err.message });
10452
10336
  }
10453
10337
  }
10454
10338
  // ========== READ-ONLY API KEY HANDLERS ==========
10455
10339
  case 'polymarket_create_readonly_api_key': {
10456
- const polyCreds = context.tradingContext?.credentials.get('polymarket');
10457
- if (!polyCreds) {
10458
- return JSON.stringify({ error: 'No Polymarket credentials set up.' });
10459
- }
10460
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10461
- const cmd = `cd ${tradingDir} && python3 polymarket.py create_readonly_api_key`;
10462
- const creds = polyCreds.data;
10463
- const userEnv = {
10464
- ...process.env,
10465
- PRIVATE_KEY: creds.privateKey,
10466
- POLY_FUNDER_ADDRESS: creds.funderAddress,
10467
- POLY_API_KEY: creds.apiKey,
10468
- POLY_API_SECRET: creds.apiSecret,
10469
- POLY_API_PASSPHRASE: creds.apiPassphrase,
10470
- };
10471
10340
  try {
10472
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8', env: userEnv });
10473
- return output.trim();
10341
+ const response = await fetchPolymarketClob(context, 'https://clob.polymarket.com/readonly-api-key', { method: 'POST' });
10342
+ const data = await response.json();
10343
+ return JSON.stringify(data);
10474
10344
  }
10475
10345
  catch (err) {
10476
- return JSON.stringify({ error: err.stderr || err.message });
10346
+ return JSON.stringify({ error: err.message });
10477
10347
  }
10478
10348
  }
10479
10349
  case 'polymarket_get_readonly_api_keys': {
10480
- const polyCreds = context.tradingContext?.credentials.get('polymarket');
10481
- if (!polyCreds) {
10482
- return JSON.stringify({ error: 'No Polymarket credentials set up.' });
10483
- }
10484
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10485
- const cmd = `cd ${tradingDir} && python3 polymarket.py get_readonly_api_keys`;
10486
- const creds = polyCreds.data;
10487
- const userEnv = {
10488
- ...process.env,
10489
- PRIVATE_KEY: creds.privateKey,
10490
- POLY_FUNDER_ADDRESS: creds.funderAddress,
10491
- POLY_API_KEY: creds.apiKey,
10492
- POLY_API_SECRET: creds.apiSecret,
10493
- POLY_API_PASSPHRASE: creds.apiPassphrase,
10494
- };
10495
10350
  try {
10496
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8', env: userEnv });
10497
- return output.trim();
10351
+ const response = await fetchPolymarketClob(context, 'https://clob.polymarket.com/readonly-api-keys');
10352
+ const data = await response.json();
10353
+ return JSON.stringify(data);
10498
10354
  }
10499
10355
  catch (err) {
10500
- return JSON.stringify({ error: err.stderr || err.message });
10356
+ return JSON.stringify({ error: err.message });
10501
10357
  }
10502
10358
  }
10503
10359
  case 'polymarket_delete_readonly_api_key': {
10504
- const polyCreds = context.tradingContext?.credentials.get('polymarket');
10505
- if (!polyCreds) {
10506
- return JSON.stringify({ error: 'No Polymarket credentials set up.' });
10507
- }
10508
10360
  const apiKey = toolInput.api_key;
10509
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10510
- const cmd = `cd ${tradingDir} && python3 polymarket.py delete_readonly_api_key "${apiKey}"`;
10511
- const creds = polyCreds.data;
10512
- const userEnv = {
10513
- ...process.env,
10514
- PRIVATE_KEY: creds.privateKey,
10515
- POLY_FUNDER_ADDRESS: creds.funderAddress,
10516
- POLY_API_KEY: creds.apiKey,
10517
- POLY_API_SECRET: creds.apiSecret,
10518
- POLY_API_PASSPHRASE: creds.apiPassphrase,
10519
- };
10520
10361
  try {
10521
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8', env: userEnv });
10522
- return output.trim();
10362
+ const response = await fetchPolymarketClob(context, `https://clob.polymarket.com/readonly-api-key/${encodeURIComponent(apiKey)}`, { method: 'DELETE' });
10363
+ const data = await response.json();
10364
+ return JSON.stringify(data);
10523
10365
  }
10524
10366
  catch (err) {
10525
- return JSON.stringify({ error: err.stderr || err.message });
10367
+ return JSON.stringify({ error: err.message });
10526
10368
  }
10527
10369
  }
10528
10370
  case 'polymarket_validate_readonly_api_key': {
10529
- // This is a public endpoint - doesn't need user credentials
10530
10371
  const apiKey = toolInput.api_key;
10531
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10532
- const cmd = `cd ${tradingDir} && python3 polymarket.py validate_readonly_api_key "${apiKey}"`;
10533
10372
  try {
10534
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
10535
- return output.trim();
10373
+ const response = await fetch(`https://clob.polymarket.com/readonly-api-key/validate/${encodeURIComponent(apiKey)}`);
10374
+ const data = await response.json();
10375
+ return JSON.stringify(data);
10536
10376
  }
10537
10377
  catch (err) {
10538
- return JSON.stringify({ error: err.stderr || err.message });
10378
+ return JSON.stringify({ error: err.message });
10539
10379
  }
10540
10380
  }
10541
10381
  // ========== BALANCE & ALLOWANCE HANDLERS ==========
10542
10382
  case 'polymarket_get_balance_allowance': {
10543
- const polyCreds = context.tradingContext?.credentials.get('polymarket');
10544
- if (!polyCreds) {
10545
- return JSON.stringify({ error: 'No Polymarket credentials set up.' });
10546
- }
10547
10383
  const assetType = toolInput.asset_type;
10548
10384
  const tokenId = toolInput.token_id;
10549
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10550
- let cmd = `cd ${tradingDir} && python3 polymarket.py get_balance_allowance ${assetType}`;
10551
- if (tokenId)
10552
- cmd += ` ${tokenId}`;
10553
- const creds = polyCreds.data;
10554
- const userEnv = {
10555
- ...process.env,
10556
- PRIVATE_KEY: creds.privateKey,
10557
- POLY_FUNDER_ADDRESS: creds.funderAddress,
10558
- POLY_API_KEY: creds.apiKey,
10559
- POLY_API_SECRET: creds.apiSecret,
10560
- POLY_API_PASSPHRASE: creds.apiPassphrase,
10561
- };
10562
10385
  try {
10563
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8', env: userEnv });
10564
- return output.trim();
10386
+ let url = `https://clob.polymarket.com/balance-allowance?asset_type=${assetType}`;
10387
+ if (tokenId)
10388
+ url += `&token_id=${tokenId}`;
10389
+ const response = await fetchPolymarketClob(context, url);
10390
+ const data = await response.json();
10391
+ return JSON.stringify(data);
10565
10392
  }
10566
10393
  catch (err) {
10567
- return JSON.stringify({ error: err.stderr || err.message });
10394
+ return JSON.stringify({ error: err.message });
10568
10395
  }
10569
10396
  }
10570
10397
  case 'polymarket_update_balance_allowance': {
10571
- const polyCreds = context.tradingContext?.credentials.get('polymarket');
10572
- if (!polyCreds) {
10573
- return JSON.stringify({ error: 'No Polymarket credentials set up.' });
10574
- }
10575
10398
  const assetType = toolInput.asset_type;
10576
10399
  const tokenId = toolInput.token_id;
10577
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10578
- let cmd = `cd ${tradingDir} && python3 polymarket.py update_balance_allowance ${assetType}`;
10579
- if (tokenId)
10580
- cmd += ` ${tokenId}`;
10581
- const creds = polyCreds.data;
10582
- const userEnv = {
10583
- ...process.env,
10584
- PRIVATE_KEY: creds.privateKey,
10585
- POLY_FUNDER_ADDRESS: creds.funderAddress,
10586
- POLY_API_KEY: creds.apiKey,
10587
- POLY_API_SECRET: creds.apiSecret,
10588
- POLY_API_PASSPHRASE: creds.apiPassphrase,
10589
- };
10590
10400
  try {
10591
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8', env: userEnv });
10592
- return output.trim();
10401
+ const body = { asset_type: assetType };
10402
+ if (tokenId)
10403
+ body.token_id = tokenId;
10404
+ const response = await fetchPolymarketClob(context, 'https://clob.polymarket.com/balance-allowance', {
10405
+ method: 'POST',
10406
+ headers: { 'Content-Type': 'application/json' },
10407
+ body: JSON.stringify(body),
10408
+ });
10409
+ const data = await response.json();
10410
+ return JSON.stringify(data);
10593
10411
  }
10594
10412
  catch (err) {
10595
- return JSON.stringify({ error: err.stderr || err.message });
10413
+ return JSON.stringify({ error: err.message });
10596
10414
  }
10597
10415
  }
10598
10416
  // ========== ADVANCED FEATURES HANDLERS ==========
10599
10417
  case 'polymarket_heartbeat': {
10600
- const polyCreds = context.tradingContext?.credentials.get('polymarket');
10601
- if (!polyCreds) {
10602
- return JSON.stringify({ error: 'No Polymarket credentials set up.' });
10603
- }
10604
- const heartbeatId = toolInput.heartbeat_id;
10605
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10606
- let cmd = `cd ${tradingDir} && python3 polymarket.py heartbeat`;
10607
- if (heartbeatId)
10608
- cmd += ` ${heartbeatId}`;
10609
- const creds = polyCreds.data;
10610
- const userEnv = {
10611
- ...process.env,
10612
- PRIVATE_KEY: creds.privateKey,
10613
- POLY_FUNDER_ADDRESS: creds.funderAddress,
10614
- POLY_API_KEY: creds.apiKey,
10615
- POLY_API_SECRET: creds.apiSecret,
10616
- POLY_API_PASSPHRASE: creds.apiPassphrase,
10617
- };
10618
10418
  try {
10619
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8', env: userEnv });
10620
- return output.trim();
10419
+ const url = 'https://clob.polymarket.com/heartbeat';
10420
+ const response = await fetchPolymarketClob(context, url);
10421
+ const data = await response.json();
10422
+ return JSON.stringify(data);
10621
10423
  }
10622
10424
  catch (err) {
10623
- return JSON.stringify({ error: err.stderr || err.message });
10425
+ return JSON.stringify({ error: err.message });
10624
10426
  }
10625
10427
  }
10626
10428
  case 'polymarket_is_order_scoring': {
10627
- const polyCreds = context.tradingContext?.credentials.get('polymarket');
10628
- if (!polyCreds) {
10629
- return JSON.stringify({ error: 'No Polymarket credentials set up.' });
10630
- }
10631
10429
  const orderId = toolInput.order_id;
10632
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10633
- const cmd = `cd ${tradingDir} && python3 polymarket.py is_order_scoring ${orderId}`;
10634
- const creds = polyCreds.data;
10635
- const userEnv = {
10636
- ...process.env,
10637
- PRIVATE_KEY: creds.privateKey,
10638
- POLY_FUNDER_ADDRESS: creds.funderAddress,
10639
- POLY_API_KEY: creds.apiKey,
10640
- POLY_API_SECRET: creds.apiSecret,
10641
- POLY_API_PASSPHRASE: creds.apiPassphrase,
10642
- };
10643
10430
  try {
10644
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8', env: userEnv });
10645
- return output.trim();
10431
+ const response = await fetchPolymarketClob(context, `https://clob.polymarket.com/order-scoring?order_id=${orderId}`);
10432
+ const data = await response.json();
10433
+ return JSON.stringify(data);
10646
10434
  }
10647
10435
  catch (err) {
10648
- return JSON.stringify({ error: err.stderr || err.message });
10436
+ return JSON.stringify({ error: err.message });
10649
10437
  }
10650
10438
  }
10651
10439
  case 'polymarket_are_orders_scoring': {
10652
- const polyCreds = context.tradingContext?.credentials.get('polymarket');
10653
- if (!polyCreds) {
10654
- return JSON.stringify({ error: 'No Polymarket credentials set up.' });
10655
- }
10656
10440
  const orderIds = toolInput.order_ids;
10657
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10658
- const cmd = `cd ${tradingDir} && python3 polymarket.py are_orders_scoring ${orderIds.join(',')}`;
10659
- const creds = polyCreds.data;
10660
- const userEnv = {
10661
- ...process.env,
10662
- PRIVATE_KEY: creds.privateKey,
10663
- POLY_FUNDER_ADDRESS: creds.funderAddress,
10664
- POLY_API_KEY: creds.apiKey,
10665
- POLY_API_SECRET: creds.apiSecret,
10666
- POLY_API_PASSPHRASE: creds.apiPassphrase,
10667
- };
10668
10441
  try {
10669
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8', env: userEnv });
10670
- return output.trim();
10442
+ const response = await fetchPolymarketClob(context, `https://clob.polymarket.com/orders-scoring?order_ids=${orderIds.join(',')}`);
10443
+ const data = await response.json();
10444
+ return JSON.stringify(data);
10671
10445
  }
10672
10446
  catch (err) {
10673
- return JSON.stringify({ error: err.stderr || err.message });
10447
+ return JSON.stringify({ error: err.message });
10674
10448
  }
10675
10449
  }
10676
10450
  case 'polymarket_notifications': {
10677
- const polyCreds = context.tradingContext?.credentials.get('polymarket');
10678
- if (!polyCreds) {
10679
- return JSON.stringify({ error: 'No Polymarket credentials set up.' });
10680
- }
10681
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10682
- const cmd = `cd ${tradingDir} && python3 polymarket.py notifications`;
10683
- const creds = polyCreds.data;
10684
- const userEnv = {
10685
- ...process.env,
10686
- PRIVATE_KEY: creds.privateKey,
10687
- POLY_FUNDER_ADDRESS: creds.funderAddress,
10688
- POLY_API_KEY: creds.apiKey,
10689
- POLY_API_SECRET: creds.apiSecret,
10690
- POLY_API_PASSPHRASE: creds.apiPassphrase,
10691
- };
10692
10451
  try {
10693
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8', env: userEnv });
10694
- return output.trim();
10452
+ const response = await fetchPolymarketClob(context, 'https://clob.polymarket.com/notifications');
10453
+ const data = await response.json();
10454
+ return JSON.stringify(data);
10695
10455
  }
10696
10456
  catch (err) {
10697
- return JSON.stringify({ error: err.stderr || err.message });
10457
+ return JSON.stringify({ error: err.message });
10698
10458
  }
10699
10459
  }
10700
10460
  case 'polymarket_drop_notifications': {
10701
- const polyCreds = context.tradingContext?.credentials.get('polymarket');
10702
- if (!polyCreds) {
10703
- return JSON.stringify({ error: 'No Polymarket credentials set up.' });
10704
- }
10705
10461
  const notificationIds = toolInput.notification_ids;
10706
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10707
- const cmd = `cd ${tradingDir} && python3 polymarket.py drop_notifications ${notificationIds.join(',')}`;
10708
- const creds = polyCreds.data;
10709
- const userEnv = {
10710
- ...process.env,
10711
- PRIVATE_KEY: creds.privateKey,
10712
- POLY_FUNDER_ADDRESS: creds.funderAddress,
10713
- POLY_API_KEY: creds.apiKey,
10714
- POLY_API_SECRET: creds.apiSecret,
10715
- POLY_API_PASSPHRASE: creds.apiPassphrase,
10716
- };
10717
10462
  try {
10718
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8', env: userEnv });
10719
- return output.trim();
10463
+ const response = await fetchPolymarketClob(context, 'https://clob.polymarket.com/notifications', {
10464
+ method: 'DELETE',
10465
+ headers: { 'Content-Type': 'application/json' },
10466
+ body: JSON.stringify({ ids: notificationIds }),
10467
+ });
10468
+ const data = await response.json();
10469
+ return JSON.stringify(data);
10720
10470
  }
10721
10471
  catch (err) {
10722
- return JSON.stringify({ error: err.stderr || err.message });
10472
+ return JSON.stringify({ error: err.message });
10723
10473
  }
10724
10474
  }
10725
10475
  case 'polymarket_closed_only_mode': {
@@ -10734,28 +10484,27 @@ async function executeTool(toolName, toolInput, context) {
10734
10484
  }
10735
10485
  case 'polymarket_orderbook_hash': {
10736
10486
  const tokenId = toolInput.token_id;
10737
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10738
- const cmd = `cd ${tradingDir} && python3 polymarket.py orderbook_hash ${tokenId}`;
10739
10487
  try {
10740
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
10741
- return output.trim();
10488
+ const response = await fetch(`https://clob.polymarket.com/hash?token_id=${tokenId}`);
10489
+ const data = await response.json();
10490
+ return JSON.stringify(data);
10742
10491
  }
10743
10492
  catch (err) {
10744
- return JSON.stringify({ error: err.stderr || err.message });
10493
+ return JSON.stringify({ error: err.message });
10745
10494
  }
10746
10495
  }
10747
10496
  case 'polymarket_sampling_simplified_markets': {
10748
10497
  const nextCursor = toolInput.next_cursor;
10749
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10750
- let cmd = `cd ${tradingDir} && python3 polymarket.py sampling_simplified_markets`;
10751
- if (nextCursor)
10752
- cmd += ` "${nextCursor}"`;
10753
10498
  try {
10754
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
10755
- return output.trim();
10499
+ const url = nextCursor
10500
+ ? `https://clob.polymarket.com/sampling-simplified-markets?next_cursor=${nextCursor}`
10501
+ : 'https://clob.polymarket.com/sampling-simplified-markets';
10502
+ const response = await fetch(url);
10503
+ const data = await response.json();
10504
+ return JSON.stringify(data);
10756
10505
  }
10757
10506
  catch (err) {
10758
- return JSON.stringify({ error: err.stderr || err.message });
10507
+ return JSON.stringify({ error: err.message });
10759
10508
  }
10760
10509
  }
10761
10510
  // ============================================
@@ -10763,91 +10512,80 @@ async function executeTool(toolName, toolInput, context) {
10763
10512
  // ============================================
10764
10513
  case 'polymarket_event': {
10765
10514
  const eventId = toolInput.event_id;
10766
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10767
- const cmd = `cd ${tradingDir} && python3 polymarket.py event "${eventId}"`;
10768
10515
  try {
10769
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
10770
- return output.trim();
10516
+ const response = await fetch(`https://gamma-api.polymarket.com/events/${encodeURIComponent(eventId)}`);
10517
+ const data = await response.json();
10518
+ return JSON.stringify(data);
10771
10519
  }
10772
10520
  catch (err) {
10773
- return JSON.stringify({ error: err.stderr || err.message });
10521
+ return JSON.stringify({ error: err.message });
10774
10522
  }
10775
10523
  }
10776
10524
  case 'polymarket_event_by_slug': {
10777
10525
  const slug = toolInput.slug;
10778
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10779
- const cmd = `cd ${tradingDir} && python3 polymarket.py event_by_slug "${slug}"`;
10780
10526
  try {
10781
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
10782
- return output.trim();
10527
+ const response = await fetch(`https://gamma-api.polymarket.com/events?slug=${encodeURIComponent(slug)}`);
10528
+ const data = await response.json();
10529
+ return JSON.stringify(data);
10783
10530
  }
10784
10531
  catch (err) {
10785
- return JSON.stringify({ error: err.stderr || err.message });
10532
+ return JSON.stringify({ error: err.message });
10786
10533
  }
10787
10534
  }
10788
10535
  case 'polymarket_events': {
10789
- const limit = toolInput.limit;
10790
- const offset = toolInput.offset;
10791
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10792
- let cmd = `cd ${tradingDir} && python3 polymarket.py events`;
10793
- if (limit)
10794
- cmd += ` ${limit}`;
10795
- if (offset)
10796
- cmd += ` ${offset}`;
10536
+ const limit = toolInput.limit || 20;
10537
+ const offset = toolInput.offset || 0;
10797
10538
  try {
10798
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
10799
- return output.trim();
10539
+ const response = await fetch(`https://gamma-api.polymarket.com/events?_limit=${limit}&_offset=${offset}&active=true&closed=false`);
10540
+ const data = await response.json();
10541
+ return JSON.stringify(data);
10800
10542
  }
10801
10543
  catch (err) {
10802
- return JSON.stringify({ error: err.stderr || err.message });
10544
+ return JSON.stringify({ error: err.message });
10803
10545
  }
10804
10546
  }
10805
10547
  case 'polymarket_search_events': {
10806
10548
  const query = toolInput.query;
10807
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10808
- const cmd = `cd ${tradingDir} && python3 polymarket.py search_events "${query}"`;
10809
10549
  try {
10810
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
10811
- return output.trim();
10550
+ const response = await fetch(`https://gamma-api.polymarket.com/events?_q=${encodeURIComponent(query)}&_limit=20&active=true`);
10551
+ const data = await response.json();
10552
+ return JSON.stringify(data);
10812
10553
  }
10813
10554
  catch (err) {
10814
- return JSON.stringify({ error: err.stderr || err.message });
10555
+ return JSON.stringify({ error: err.message });
10815
10556
  }
10816
10557
  }
10817
10558
  case 'polymarket_event_tags': {
10818
10559
  const eventId = toolInput.event_id;
10819
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10820
- const cmd = `cd ${tradingDir} && python3 polymarket.py event_tags "${eventId}"`;
10821
10560
  try {
10822
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
10823
- return output.trim();
10561
+ const response = await fetch(`https://gamma-api.polymarket.com/events/${encodeURIComponent(eventId)}/tags`);
10562
+ const data = await response.json();
10563
+ return JSON.stringify(data);
10824
10564
  }
10825
10565
  catch (err) {
10826
- return JSON.stringify({ error: err.stderr || err.message });
10566
+ return JSON.stringify({ error: err.message });
10827
10567
  }
10828
10568
  }
10829
10569
  case 'polymarket_market_by_slug': {
10830
10570
  const slug = toolInput.slug;
10831
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10832
- const cmd = `cd ${tradingDir} && python3 polymarket.py market_by_slug "${slug}"`;
10833
10571
  try {
10834
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
10835
- return output.trim();
10572
+ const response = await fetch(`https://gamma-api.polymarket.com/markets?slug=${encodeURIComponent(slug)}`);
10573
+ const data = await response.json();
10574
+ return JSON.stringify(data);
10836
10575
  }
10837
10576
  catch (err) {
10838
- return JSON.stringify({ error: err.stderr || err.message });
10577
+ return JSON.stringify({ error: err.message });
10839
10578
  }
10840
10579
  }
10841
10580
  case 'polymarket_market_tags': {
10842
10581
  const marketId = toolInput.market_id;
10843
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10844
- const cmd = `cd ${tradingDir} && python3 polymarket.py market_tags "${marketId}"`;
10845
10582
  try {
10846
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
10847
- return output.trim();
10583
+ const response = await fetch(`https://gamma-api.polymarket.com/markets/${encodeURIComponent(marketId)}/tags`);
10584
+ const data = await response.json();
10585
+ return JSON.stringify(data);
10848
10586
  }
10849
10587
  catch (err) {
10850
- return JSON.stringify({ error: err.stderr || err.message });
10588
+ return JSON.stringify({ error: err.message });
10851
10589
  }
10852
10590
  }
10853
10591
  // ============================================
@@ -10855,111 +10593,101 @@ async function executeTool(toolName, toolInput, context) {
10855
10593
  // ============================================
10856
10594
  case 'polymarket_series': {
10857
10595
  const seriesId = toolInput.series_id;
10858
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10859
- let cmd = `cd ${tradingDir} && python3 polymarket.py series`;
10860
- if (seriesId)
10861
- cmd += ` "${seriesId}"`;
10862
10596
  try {
10863
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
10864
- return output.trim();
10597
+ const url = seriesId
10598
+ ? `https://gamma-api.polymarket.com/series/${encodeURIComponent(seriesId)}`
10599
+ : 'https://gamma-api.polymarket.com/series';
10600
+ const response = await fetch(url);
10601
+ const data = await response.json();
10602
+ return JSON.stringify(data);
10865
10603
  }
10866
10604
  catch (err) {
10867
- return JSON.stringify({ error: err.stderr || err.message });
10605
+ return JSON.stringify({ error: err.message });
10868
10606
  }
10869
10607
  }
10870
10608
  case 'polymarket_series_list': {
10871
- const limit = toolInput.limit;
10872
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10873
- let cmd = `cd ${tradingDir} && python3 polymarket.py series_list`;
10874
- if (limit)
10875
- cmd += ` ${limit}`;
10609
+ const limit = toolInput.limit || 20;
10876
10610
  try {
10877
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
10878
- return output.trim();
10611
+ const response = await fetch(`https://gamma-api.polymarket.com/series?_limit=${limit}`);
10612
+ const data = await response.json();
10613
+ return JSON.stringify(data);
10879
10614
  }
10880
10615
  catch (err) {
10881
- return JSON.stringify({ error: err.stderr || err.message });
10616
+ return JSON.stringify({ error: err.message });
10882
10617
  }
10883
10618
  }
10884
10619
  // ============================================
10885
10620
  // POLYMARKET GAMMA API - Tags
10886
10621
  // ============================================
10887
10622
  case 'polymarket_tags': {
10888
- const limit = toolInput.limit;
10889
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10890
- let cmd = `cd ${tradingDir} && python3 polymarket.py tags`;
10891
- if (limit)
10892
- cmd += ` ${limit}`;
10623
+ const limit = toolInput.limit || 50;
10893
10624
  try {
10894
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
10895
- return output.trim();
10625
+ const response = await fetch(`https://gamma-api.polymarket.com/tags?_limit=${limit}`);
10626
+ const data = await response.json();
10627
+ return JSON.stringify(data);
10896
10628
  }
10897
10629
  catch (err) {
10898
- return JSON.stringify({ error: err.stderr || err.message });
10630
+ return JSON.stringify({ error: err.message });
10899
10631
  }
10900
10632
  }
10901
10633
  case 'polymarket_tag': {
10902
10634
  const tagId = toolInput.tag_id;
10903
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10904
- const cmd = `cd ${tradingDir} && python3 polymarket.py tag "${tagId}"`;
10905
10635
  try {
10906
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
10907
- return output.trim();
10636
+ const response = await fetch(`https://gamma-api.polymarket.com/tags/${encodeURIComponent(tagId)}`);
10637
+ const data = await response.json();
10638
+ return JSON.stringify(data);
10908
10639
  }
10909
10640
  catch (err) {
10910
- return JSON.stringify({ error: err.stderr || err.message });
10641
+ return JSON.stringify({ error: err.message });
10911
10642
  }
10912
10643
  }
10913
10644
  case 'polymarket_tag_by_slug': {
10914
10645
  const slug = toolInput.slug;
10915
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10916
- const cmd = `cd ${tradingDir} && python3 polymarket.py tag_by_slug "${slug}"`;
10917
10646
  try {
10918
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
10919
- return output.trim();
10647
+ const response = await fetch(`https://gamma-api.polymarket.com/tags?slug=${encodeURIComponent(slug)}`);
10648
+ const data = await response.json();
10649
+ return JSON.stringify(data);
10920
10650
  }
10921
10651
  catch (err) {
10922
- return JSON.stringify({ error: err.stderr || err.message });
10652
+ return JSON.stringify({ error: err.message });
10923
10653
  }
10924
10654
  }
10925
10655
  case 'polymarket_tag_relations': {
10926
10656
  const tagId = toolInput.tag_id;
10927
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10928
- const cmd = `cd ${tradingDir} && python3 polymarket.py tag_relations "${tagId}"`;
10929
10657
  try {
10930
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
10931
- return output.trim();
10658
+ const response = await fetch(`https://gamma-api.polymarket.com/tags/${encodeURIComponent(tagId)}/relations`);
10659
+ const data = await response.json();
10660
+ return JSON.stringify(data);
10932
10661
  }
10933
10662
  catch (err) {
10934
- return JSON.stringify({ error: err.stderr || err.message });
10663
+ return JSON.stringify({ error: err.message });
10935
10664
  }
10936
10665
  }
10937
10666
  // ============================================
10938
10667
  // POLYMARKET GAMMA API - Sports
10939
10668
  // ============================================
10940
10669
  case 'polymarket_sports': {
10941
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10942
- const cmd = `cd ${tradingDir} && python3 polymarket.py sports`;
10943
10670
  try {
10944
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
10945
- return output.trim();
10671
+ const response = await fetch('https://gamma-api.polymarket.com/sports');
10672
+ const data = await response.json();
10673
+ return JSON.stringify(data);
10946
10674
  }
10947
10675
  catch (err) {
10948
- return JSON.stringify({ error: err.stderr || err.message });
10676
+ return JSON.stringify({ error: err.message });
10949
10677
  }
10950
10678
  }
10951
10679
  case 'polymarket_teams': {
10952
10680
  const sport = toolInput.sport;
10953
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10954
- let cmd = `cd ${tradingDir} && python3 polymarket.py teams`;
10955
- if (sport)
10956
- cmd += ` "${sport}"`;
10957
10681
  try {
10958
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
10959
- return output.trim();
10682
+ const url = sport
10683
+ ? `https://gamma-api.polymarket.com/teams?sport=${encodeURIComponent(sport)}`
10684
+ : 'https://gamma-api.polymarket.com/teams';
10685
+ const response = await fetch(url);
10686
+ const data = await response.json();
10687
+ return JSON.stringify(data);
10960
10688
  }
10961
10689
  catch (err) {
10962
- return JSON.stringify({ error: err.stderr || err.message });
10690
+ return JSON.stringify({ error: err.message });
10963
10691
  }
10964
10692
  }
10965
10693
  // ============================================
@@ -10967,26 +10695,24 @@ async function executeTool(toolName, toolInput, context) {
10967
10695
  // ============================================
10968
10696
  case 'polymarket_comments': {
10969
10697
  const marketId = toolInput.market_id;
10970
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10971
- const cmd = `cd ${tradingDir} && python3 polymarket.py comments "${marketId}"`;
10972
10698
  try {
10973
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
10974
- return output.trim();
10699
+ const response = await fetch(`https://gamma-api.polymarket.com/comments?market=${encodeURIComponent(marketId)}`);
10700
+ const data = await response.json();
10701
+ return JSON.stringify(data);
10975
10702
  }
10976
10703
  catch (err) {
10977
- return JSON.stringify({ error: err.stderr || err.message });
10704
+ return JSON.stringify({ error: err.message });
10978
10705
  }
10979
10706
  }
10980
10707
  case 'polymarket_user_comments': {
10981
10708
  const address = toolInput.address;
10982
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10983
- const cmd = `cd ${tradingDir} && python3 polymarket.py user_comments "${address}"`;
10984
10709
  try {
10985
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
10986
- return output.trim();
10710
+ const response = await fetch(`https://gamma-api.polymarket.com/comments?address=${encodeURIComponent(address)}`);
10711
+ const data = await response.json();
10712
+ return JSON.stringify(data);
10987
10713
  }
10988
10714
  catch (err) {
10989
- return JSON.stringify({ error: err.stderr || err.message });
10715
+ return JSON.stringify({ error: err.message });
10990
10716
  }
10991
10717
  }
10992
10718
  // ============================================
@@ -10994,193 +10720,192 @@ async function executeTool(toolName, toolInput, context) {
10994
10720
  // ============================================
10995
10721
  case 'polymarket_positions_value': {
10996
10722
  const address = toolInput.address;
10997
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
10998
- let cmd = `cd ${tradingDir} && python3 polymarket.py positions_value`;
10999
- if (address)
11000
- cmd += ` "${address}"`;
10723
+ const polyCreds = context.tradingContext?.credentials.get('polymarket');
10724
+ const walletAddr = address || polyCreds?.data?.funderAddress;
10725
+ if (!walletAddr)
10726
+ return JSON.stringify({ error: 'No address provided and no credentials set up.' });
11001
10727
  try {
11002
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
11003
- return output.trim();
10728
+ const response = await fetch(`https://data-api.polymarket.com/value?address=${walletAddr}`);
10729
+ const data = await response.json();
10730
+ return JSON.stringify(data);
11004
10731
  }
11005
10732
  catch (err) {
11006
- return JSON.stringify({ error: err.stderr || err.message });
10733
+ return JSON.stringify({ error: err.message });
11007
10734
  }
11008
10735
  }
11009
10736
  case 'polymarket_closed_positions': {
11010
10737
  const address = toolInput.address;
11011
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
11012
- let cmd = `cd ${tradingDir} && python3 polymarket.py closed_positions`;
11013
- if (address)
11014
- cmd += ` "${address}"`;
10738
+ const polyCreds = context.tradingContext?.credentials.get('polymarket');
10739
+ const walletAddr = address || polyCreds?.data?.funderAddress;
10740
+ if (!walletAddr)
10741
+ return JSON.stringify({ error: 'No address provided and no credentials set up.' });
11015
10742
  try {
11016
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
11017
- return output.trim();
10743
+ const response = await fetch(`https://data-api.polymarket.com/positions?address=${walletAddr}&closed=true&_limit=50`);
10744
+ const data = await response.json();
10745
+ return JSON.stringify(data);
11018
10746
  }
11019
10747
  catch (err) {
11020
- return JSON.stringify({ error: err.stderr || err.message });
10748
+ return JSON.stringify({ error: err.message });
11021
10749
  }
11022
10750
  }
11023
10751
  case 'polymarket_pnl_timeseries': {
11024
10752
  const address = toolInput.address;
11025
10753
  const interval = toolInput.interval;
11026
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
11027
- let cmd = `cd ${tradingDir} && python3 polymarket.py pnl_timeseries`;
11028
- if (address)
11029
- cmd += ` "${address}"`;
11030
- if (interval)
11031
- cmd += ` "${interval}"`;
10754
+ const polyCreds = context.tradingContext?.credentials.get('polymarket');
10755
+ const walletAddr = address || polyCreds?.data?.funderAddress;
10756
+ if (!walletAddr)
10757
+ return JSON.stringify({ error: 'No address provided and no credentials set up.' });
11032
10758
  try {
11033
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
11034
- return output.trim();
10759
+ let url = `https://data-api.polymarket.com/pnl/timeseries?address=${walletAddr}`;
10760
+ if (interval)
10761
+ url += `&interval=${interval}`;
10762
+ const response = await fetch(url);
10763
+ const data = await response.json();
10764
+ return JSON.stringify(data);
11035
10765
  }
11036
10766
  catch (err) {
11037
- return JSON.stringify({ error: err.stderr || err.message });
10767
+ return JSON.stringify({ error: err.message });
11038
10768
  }
11039
10769
  }
11040
10770
  case 'polymarket_overall_pnl': {
11041
10771
  const address = toolInput.address;
11042
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
11043
- let cmd = `cd ${tradingDir} && python3 polymarket.py overall_pnl`;
11044
- if (address)
11045
- cmd += ` "${address}"`;
10772
+ const polyCreds = context.tradingContext?.credentials.get('polymarket');
10773
+ const walletAddr = address || polyCreds?.data?.funderAddress;
10774
+ if (!walletAddr)
10775
+ return JSON.stringify({ error: 'No address provided and no credentials set up.' });
11046
10776
  try {
11047
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
11048
- return output.trim();
10777
+ const response = await fetch(`https://data-api.polymarket.com/pnl?address=${walletAddr}`);
10778
+ const data = await response.json();
10779
+ return JSON.stringify(data);
11049
10780
  }
11050
10781
  catch (err) {
11051
- return JSON.stringify({ error: err.stderr || err.message });
10782
+ return JSON.stringify({ error: err.message });
11052
10783
  }
11053
10784
  }
11054
10785
  case 'polymarket_user_rank': {
11055
10786
  const address = toolInput.address;
11056
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
11057
- let cmd = `cd ${tradingDir} && python3 polymarket.py user_rank`;
11058
- if (address)
11059
- cmd += ` "${address}"`;
10787
+ const polyCreds = context.tradingContext?.credentials.get('polymarket');
10788
+ const walletAddr = address || polyCreds?.data?.funderAddress;
10789
+ if (!walletAddr)
10790
+ return JSON.stringify({ error: 'No address provided and no credentials set up.' });
11060
10791
  try {
11061
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
11062
- return output.trim();
10792
+ const response = await fetch(`https://data-api.polymarket.com/rank?address=${walletAddr}`);
10793
+ const data = await response.json();
10794
+ return JSON.stringify(data);
11063
10795
  }
11064
10796
  catch (err) {
11065
- return JSON.stringify({ error: err.stderr || err.message });
10797
+ return JSON.stringify({ error: err.message });
11066
10798
  }
11067
10799
  }
11068
10800
  case 'polymarket_leaderboard': {
11069
- const limit = toolInput.limit;
11070
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
11071
- let cmd = `cd ${tradingDir} && python3 polymarket.py leaderboard`;
11072
- if (limit)
11073
- cmd += ` ${limit}`;
10801
+ const limit = toolInput.limit || 20;
11074
10802
  try {
11075
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
11076
- return output.trim();
10803
+ const response = await fetch(`https://data-api.polymarket.com/leaderboard?_limit=${limit}`);
10804
+ const data = await response.json();
10805
+ return JSON.stringify(data);
11077
10806
  }
11078
10807
  catch (err) {
11079
- return JSON.stringify({ error: err.stderr || err.message });
10808
+ return JSON.stringify({ error: err.message });
11080
10809
  }
11081
10810
  }
11082
10811
  case 'polymarket_top_holders': {
11083
10812
  const marketId = toolInput.market_id;
11084
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
11085
- const cmd = `cd ${tradingDir} && python3 polymarket.py top_holders "${marketId}"`;
11086
10813
  try {
11087
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
11088
- return output.trim();
10814
+ const response = await fetch(`https://data-api.polymarket.com/holders?market=${encodeURIComponent(marketId)}`);
10815
+ const data = await response.json();
10816
+ return JSON.stringify(data);
11089
10817
  }
11090
10818
  catch (err) {
11091
- return JSON.stringify({ error: err.stderr || err.message });
10819
+ return JSON.stringify({ error: err.message });
11092
10820
  }
11093
10821
  }
11094
10822
  case 'polymarket_user_activity': {
11095
10823
  const address = toolInput.address;
11096
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
11097
- let cmd = `cd ${tradingDir} && python3 polymarket.py user_activity`;
11098
- if (address)
11099
- cmd += ` "${address}"`;
10824
+ const polyCreds = context.tradingContext?.credentials.get('polymarket');
10825
+ const walletAddr = address || polyCreds?.data?.funderAddress;
10826
+ if (!walletAddr)
10827
+ return JSON.stringify({ error: 'No address provided and no credentials set up.' });
11100
10828
  try {
11101
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
11102
- return output.trim();
10829
+ const response = await fetch(`https://data-api.polymarket.com/activity?address=${walletAddr}`);
10830
+ const data = await response.json();
10831
+ return JSON.stringify(data);
11103
10832
  }
11104
10833
  catch (err) {
11105
- return JSON.stringify({ error: err.stderr || err.message });
10834
+ return JSON.stringify({ error: err.message });
11106
10835
  }
11107
10836
  }
11108
10837
  case 'polymarket_open_interest': {
11109
10838
  const marketId = toolInput.market_id;
11110
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
11111
- const cmd = `cd ${tradingDir} && python3 polymarket.py open_interest "${marketId}"`;
11112
10839
  try {
11113
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
11114
- return output.trim();
10840
+ const response = await fetch(`https://data-api.polymarket.com/open-interest?market=${encodeURIComponent(marketId)}`);
10841
+ const data = await response.json();
10842
+ return JSON.stringify(data);
11115
10843
  }
11116
10844
  catch (err) {
11117
- return JSON.stringify({ error: err.stderr || err.message });
10845
+ return JSON.stringify({ error: err.message });
11118
10846
  }
11119
10847
  }
11120
10848
  case 'polymarket_live_volume': {
11121
10849
  const eventId = toolInput.event_id;
11122
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
11123
- let cmd = `cd ${tradingDir} && python3 polymarket.py live_volume`;
11124
- if (eventId)
11125
- cmd += ` "${eventId}"`;
11126
10850
  try {
11127
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
11128
- return output.trim();
10851
+ const url = eventId
10852
+ ? `https://data-api.polymarket.com/volume?event=${encodeURIComponent(eventId)}`
10853
+ : 'https://data-api.polymarket.com/volume';
10854
+ const response = await fetch(url);
10855
+ const data = await response.json();
10856
+ return JSON.stringify(data);
11129
10857
  }
11130
10858
  catch (err) {
11131
- return JSON.stringify({ error: err.stderr || err.message });
10859
+ return JSON.stringify({ error: err.message });
11132
10860
  }
11133
10861
  }
11134
10862
  case 'polymarket_price_history': {
11135
10863
  const tokenId = toolInput.token_id;
11136
10864
  const interval = toolInput.interval;
11137
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
11138
- let cmd = `cd ${tradingDir} && python3 polymarket.py price_history "${tokenId}"`;
11139
- if (interval)
11140
- cmd += ` "${interval}"`;
11141
10865
  try {
11142
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
11143
- return output.trim();
10866
+ let url = `https://clob.polymarket.com/prices-history?market=${tokenId}`;
10867
+ if (interval)
10868
+ url += `&interval=${interval}`;
10869
+ const response = await fetch(url);
10870
+ const data = await response.json();
10871
+ return JSON.stringify(data);
11144
10872
  }
11145
10873
  catch (err) {
11146
- return JSON.stringify({ error: err.stderr || err.message });
10874
+ return JSON.stringify({ error: err.message });
11147
10875
  }
11148
10876
  }
11149
10877
  // ============================================
11150
10878
  // POLYMARKET REWARDS API
11151
10879
  // ============================================
11152
10880
  case 'polymarket_daily_rewards': {
11153
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
11154
- const cmd = `cd ${tradingDir} && python3 polymarket.py daily_rewards`;
11155
10881
  try {
11156
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
11157
- return output.trim();
10882
+ const response = await fetch('https://clob.polymarket.com/rewards/daily');
10883
+ const data = await response.json();
10884
+ return JSON.stringify(data);
11158
10885
  }
11159
10886
  catch (err) {
11160
- return JSON.stringify({ error: err.stderr || err.message });
10887
+ return JSON.stringify({ error: err.message });
11161
10888
  }
11162
10889
  }
11163
10890
  case 'polymarket_market_rewards': {
11164
10891
  const marketId = toolInput.market_id;
11165
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
11166
- const cmd = `cd ${tradingDir} && python3 polymarket.py market_rewards "${marketId}"`;
11167
10892
  try {
11168
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
11169
- return output.trim();
10893
+ const response = await fetch(`https://clob.polymarket.com/rewards/markets/${encodeURIComponent(marketId)}`);
10894
+ const data = await response.json();
10895
+ return JSON.stringify(data);
11170
10896
  }
11171
10897
  catch (err) {
11172
- return JSON.stringify({ error: err.stderr || err.message });
10898
+ return JSON.stringify({ error: err.message });
11173
10899
  }
11174
10900
  }
11175
10901
  case 'polymarket_reward_markets': {
11176
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
11177
- const cmd = `cd ${tradingDir} && python3 polymarket.py reward_markets`;
11178
10902
  try {
11179
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
11180
- return output.trim();
10903
+ const response = await fetch('https://clob.polymarket.com/rewards/markets');
10904
+ const data = await response.json();
10905
+ return JSON.stringify(data);
11181
10906
  }
11182
10907
  catch (err) {
11183
- return JSON.stringify({ error: err.stderr || err.message });
10908
+ return JSON.stringify({ error: err.message });
11184
10909
  }
11185
10910
  }
11186
10911
  // ============================================
@@ -11188,14 +10913,13 @@ async function executeTool(toolName, toolInput, context) {
11188
10913
  // ============================================
11189
10914
  case 'polymarket_profile': {
11190
10915
  const address = toolInput.address;
11191
- const tradingDir = (0, path_1.join)(__dirname, '..', '..', 'trading');
11192
- const cmd = `cd ${tradingDir} && python3 polymarket.py profile "${address}"`;
11193
10916
  try {
11194
- const output = (0, child_process_1.execSync)(cmd, { timeout: 30000, encoding: 'utf-8' });
11195
- return output.trim();
10917
+ const response = await fetch(`https://gamma-api.polymarket.com/profiles/${encodeURIComponent(address)}`);
10918
+ const data = await response.json();
10919
+ return JSON.stringify(data);
11196
10920
  }
11197
10921
  catch (err) {
11198
- return JSON.stringify({ error: err.stderr || err.message });
10922
+ return JSON.stringify({ error: err.message });
11199
10923
  }
11200
10924
  }
11201
10925
  // Kalshi handlers — migrated to handlers/kalshi.ts
@@ -15949,7 +15673,8 @@ async function createAgentManager(config, feeds, db, sessionManager, sendMessage
15949
15673
  }
15950
15674
  const client = new sdk_1.default({ apiKey });
15951
15675
  const skills = (0, loader_1.createSkillManager)(config.agents.defaults.workspace);
15952
- const credentials = (0, credentials_1.createCredentialsManager)(db);
15676
+ const createCredentialsManager = await _loadCredentials();
15677
+ const credentials = createCredentialsManager(db);
15953
15678
  const transcription = (0, transcription_1.createTranscriptionTool)(config.agents.defaults.workspace);
15954
15679
  const files = (0, files_1.createFileTool)(config.agents.defaults.workspace);
15955
15680
  const shellHistory = (0, shell_history_1.createShellHistoryTool)();