@exagent/agent 0.1.39 → 0.1.40

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/cli.js CHANGED
@@ -3398,9 +3398,9 @@ var path7 = __toESM(require("path"));
3398
3398
 
3399
3399
  // src/runtime.ts
3400
3400
  var import_sdk = require("@exagent/sdk");
3401
- var import_viem7 = require("viem");
3402
- var import_chains5 = require("viem/chains");
3403
- var import_accounts5 = require("viem/accounts");
3401
+ var import_viem11 = require("viem");
3402
+ var import_chains8 = require("viem/chains");
3403
+ var import_accounts8 = require("viem/accounts");
3404
3404
 
3405
3405
  // src/position-tracker.ts
3406
3406
  init_market();
@@ -4000,6 +4000,49 @@ var PerpConfigSchema = import_zod.z.object({
4000
4000
  /** Allowed perp instruments (e.g. ["ETH", "BTC", "SOL"]). If empty, all instruments allowed. */
4001
4001
  allowedInstruments: import_zod.z.array(import_zod.z.string()).optional()
4002
4002
  }).optional();
4003
+ var PredictionConfigSchema = import_zod.z.object({
4004
+ /** Enable prediction market trading */
4005
+ enabled: import_zod.z.boolean().default(false),
4006
+ /** Polymarket CLOB API URL */
4007
+ clobApiUrl: import_zod.z.string().url().default("https://clob.polymarket.com"),
4008
+ /** Gamma API URL for market discovery */
4009
+ gammaApiUrl: import_zod.z.string().url().default("https://gamma-api.polymarket.com"),
4010
+ /** Polygon RPC URL */
4011
+ polygonRpcUrl: import_zod.z.string().url().optional(),
4012
+ /** CLOB API key (L2 auth) — derived from wallet signature if not provided */
4013
+ clobApiKey: import_zod.z.string().optional(),
4014
+ /** CLOB API secret (L2 auth) */
4015
+ clobApiSecret: import_zod.z.string().optional(),
4016
+ /** CLOB API passphrase (L2 auth) */
4017
+ clobApiPassphrase: import_zod.z.string().optional(),
4018
+ /** Private key for the prediction relayer (calls recordPerpTrade on Base). Falls back to agent wallet. */
4019
+ predictionRelayerKey: import_zod.z.string().optional(),
4020
+ /** Maximum notional per trade in USD (default: 500) */
4021
+ maxNotionalUSD: import_zod.z.number().min(1).default(500),
4022
+ /** Maximum total exposure across all markets in USD (default: 5000) */
4023
+ maxTotalExposureUSD: import_zod.z.number().min(1).default(5e3),
4024
+ /** Target USDC allocation on Polygon in USD (default: 100) */
4025
+ polygonAllocationUSD: import_zod.z.number().min(1).default(100),
4026
+ /** Allowed market categories (empty = all categories) */
4027
+ allowedCategories: import_zod.z.array(import_zod.z.string()).optional(),
4028
+ /** Fee bridge threshold in USD — accumulated fees are bridged to Base when exceeded (default: 10) */
4029
+ feeBridgeThresholdUSD: import_zod.z.number().min(1).default(10),
4030
+ /** Prediction vault configuration (ERC-4626 + ERC-1271 on Polygon) */
4031
+ vault: import_zod.z.object({
4032
+ /** Enable vault mode for prediction trading */
4033
+ enabled: import_zod.z.boolean().default(false),
4034
+ /** PredictionVaultFactory address on Polygon */
4035
+ factoryAddress: import_zod.z.string(),
4036
+ /** PredictionFeeCollector address on Polygon */
4037
+ feeCollectorAddress: import_zod.z.string().optional(),
4038
+ /** Existing vault address (if already created) */
4039
+ vaultAddress: import_zod.z.string().optional(),
4040
+ /** Agent's fee recipient address */
4041
+ feeRecipient: import_zod.z.string().optional(),
4042
+ /** Whether agent is verified (higher deposit cap) */
4043
+ isVerified: import_zod.z.boolean().default(false)
4044
+ }).optional()
4045
+ }).optional();
4003
4046
  var AgentConfigSchema = import_zod.z.object({
4004
4047
  // Identity (from on-chain registration)
4005
4048
  agentId: import_zod.z.union([import_zod.z.number().positive(), import_zod.z.string()]),
@@ -4019,6 +4062,8 @@ var AgentConfigSchema = import_zod.z.object({
4019
4062
  relay: RelayConfigSchema,
4020
4063
  // Perp trading configuration (Hyperliquid)
4021
4064
  perp: PerpConfigSchema,
4065
+ // Prediction market configuration (Polymarket)
4066
+ prediction: PredictionConfigSchema,
4022
4067
  // Allowed tokens (addresses)
4023
4068
  allowedTokens: import_zod.z.array(import_zod.z.string()).optional()
4024
4069
  });
@@ -4390,7 +4435,7 @@ var VaultManager = class {
4390
4435
 
4391
4436
  // src/relay.ts
4392
4437
  var import_ws2 = __toESM(require("ws"));
4393
- var import_accounts4 = require("viem/accounts");
4438
+ var import_accounts7 = require("viem/accounts");
4394
4439
 
4395
4440
  // src/index.ts
4396
4441
  init_store();
@@ -5643,224 +5688,2031 @@ var CORE_DEPOSIT_WALLET_ABI = (0, import_viem6.parseAbi)([
5643
5688
  "function deposit(uint256 amount, uint32 destinationDex) external"
5644
5689
  ]);
5645
5690
 
5646
- // src/secure-env.ts
5647
- var crypto = __toESM(require("crypto"));
5648
- var fs = __toESM(require("fs"));
5649
- var path = __toESM(require("path"));
5650
- var ALGORITHM = "aes-256-gcm";
5651
- var PBKDF2_ITERATIONS = 1e5;
5652
- var SALT_LENGTH = 32;
5653
- var IV_LENGTH = 16;
5654
- var KEY_LENGTH = 32;
5655
- var SENSITIVE_PATTERNS = [
5656
- /PRIVATE_KEY$/i,
5657
- /_API_KEY$/i,
5658
- /API_KEY$/i,
5659
- /_SECRET$/i,
5660
- /^OPENAI_API_KEY$/i,
5661
- /^ANTHROPIC_API_KEY$/i,
5662
- /^GOOGLE_AI_API_KEY$/i,
5663
- /^DEEPSEEK_API_KEY$/i,
5664
- /^MISTRAL_API_KEY$/i,
5665
- /^GROQ_API_KEY$/i,
5666
- /^TOGETHER_API_KEY$/i
5667
- ];
5668
- function isSensitiveKey(key) {
5669
- return SENSITIVE_PATTERNS.some((pattern) => pattern.test(key));
5670
- }
5671
- function deriveKey(passphrase, salt) {
5672
- return crypto.pbkdf2Sync(passphrase, salt, PBKDF2_ITERATIONS, KEY_LENGTH, "sha256");
5673
- }
5674
- function encryptValue(value, key) {
5675
- const iv = crypto.randomBytes(IV_LENGTH);
5676
- const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
5677
- let encrypted = cipher.update(value, "utf8", "hex");
5678
- encrypted += cipher.final("hex");
5679
- const tag = cipher.getAuthTag();
5680
- return {
5681
- iv: iv.toString("hex"),
5682
- encrypted,
5683
- tag: tag.toString("hex")
5684
- };
5685
- }
5686
- function decryptValue(encrypted, key, iv, tag) {
5687
- const decipher = crypto.createDecipheriv(
5688
- ALGORITHM,
5689
- key,
5690
- Buffer.from(iv, "hex")
5691
- );
5692
- decipher.setAuthTag(Buffer.from(tag, "hex"));
5693
- let decrypted = decipher.update(encrypted, "hex", "utf8");
5694
- decrypted += decipher.final("utf8");
5695
- return decrypted;
5696
- }
5697
- function parseEnvFile(content) {
5698
- const entries = [];
5699
- for (const line of content.split("\n")) {
5700
- const trimmed = line.trim();
5701
- if (!trimmed || trimmed.startsWith("#")) continue;
5702
- const eqIndex = trimmed.indexOf("=");
5703
- if (eqIndex === -1) continue;
5704
- const key = trimmed.slice(0, eqIndex).trim();
5705
- let value = trimmed.slice(eqIndex + 1).trim();
5706
- if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
5707
- value = value.slice(1, -1);
5708
- }
5709
- if (key && value) {
5710
- entries.push({ key, value });
5711
- }
5691
+ // src/prediction/types.ts
5692
+ var DEFAULT_PREDICTION_CONFIG = {
5693
+ clobApiUrl: "https://clob.polymarket.com",
5694
+ gammaApiUrl: "https://gamma-api.polymarket.com",
5695
+ polygonRpcUrl: "https://polygon-rpc.com",
5696
+ maxNotionalUSD: 1e3,
5697
+ maxTotalExposureUSD: 5e3,
5698
+ polygonAllocationUSD: 100,
5699
+ feeBridgeThresholdUSD: 10
5700
+ };
5701
+ var POLYGON_CHAIN_ID = 137;
5702
+ var POLYMARKET_SIGNATURE_TYPE_EOA = 0;
5703
+ var POLYMARKET_SIGNATURE_TYPE_GNOSIS_SAFE = 1;
5704
+ var POLYGON_USDC_ADDRESS = "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359";
5705
+ var POLYGON_TOKEN_MESSENGER_V2 = "0x28b5a0e9C621a5BadaA536219b3a228C8168cf5d";
5706
+ var POLYGON_MESSAGE_TRANSMITTER_V2 = "0x81D40F21F12A8F0E3252Bccb954D722d4c464B64";
5707
+ var CCTP_DOMAIN_BASE = 6;
5708
+ var CCTP_DOMAIN_POLYGON = 7;
5709
+ var PREDICTION_INSTRUMENT_PREFIX = "POLY:";
5710
+
5711
+ // src/prediction/client.ts
5712
+ var import_clob_client = require("@polymarket/clob-client");
5713
+ var import_ethers = require("ethers");
5714
+ var PolymarketClient = class {
5715
+ config;
5716
+ clobClient = null;
5717
+ apiCreds = null;
5718
+ signer;
5719
+ walletAddress;
5720
+ /** Vault mode: when true, orders use maker=vaultAddress with POLY_GNOSIS_SAFE signature type */
5721
+ vaultMode;
5722
+ /** Vault contract address (only set in vault mode) */
5723
+ vaultAddress;
5724
+ /** Cache for Gamma API market data (conditionId -> market) */
5725
+ marketCache = /* @__PURE__ */ new Map();
5726
+ CACHE_TTL_MS = 6e4;
5727
+ // 60 seconds
5728
+ constructor(privateKey, config, vaultOpts) {
5729
+ this.config = { ...DEFAULT_PREDICTION_CONFIG, ...config };
5730
+ this.signer = new import_ethers.Wallet(privateKey);
5731
+ this.walletAddress = this.signer.address;
5732
+ this.vaultMode = vaultOpts?.vaultMode ?? false;
5733
+ this.vaultAddress = vaultOpts?.vaultAddress;
5712
5734
  }
5713
- return entries;
5714
- }
5715
- function encryptEnvFile(envPath, passphrase, deleteOriginal = false) {
5716
- if (!fs.existsSync(envPath)) {
5717
- throw new Error(`File not found: ${envPath}`);
5735
+ // ============================================================
5736
+ // INITIALIZATION
5737
+ // ============================================================
5738
+ /**
5739
+ * Initialize the CLOB client with L2 API credentials.
5740
+ * Must be called once before placing orders.
5741
+ */
5742
+ async initialize() {
5743
+ const initClient = new import_clob_client.ClobClient(
5744
+ this.config.clobApiUrl,
5745
+ POLYGON_CHAIN_ID,
5746
+ this.signer
5747
+ );
5748
+ this.apiCreds = await initClient.createOrDeriveApiKey();
5749
+ const signatureType = this.vaultMode ? POLYMARKET_SIGNATURE_TYPE_GNOSIS_SAFE : POLYMARKET_SIGNATURE_TYPE_EOA;
5750
+ this.clobClient = new import_clob_client.ClobClient(
5751
+ this.config.clobApiUrl,
5752
+ POLYGON_CHAIN_ID,
5753
+ this.signer,
5754
+ this.apiCreds,
5755
+ signatureType
5756
+ );
5757
+ if (this.vaultMode) {
5758
+ console.log(`Polymarket CLOB initialized in VAULT MODE \u2014 maker: ${this.vaultAddress}, signer: ${this.walletAddress}`);
5759
+ } else {
5760
+ console.log(`Polymarket CLOB initialized for ${this.walletAddress}`);
5761
+ }
5718
5762
  }
5719
- const content = fs.readFileSync(envPath, "utf-8");
5720
- const entries = parseEnvFile(content);
5721
- if (entries.length === 0) {
5722
- throw new Error("No environment variables found in file");
5763
+ /**
5764
+ * Check if the client is initialized with CLOB credentials.
5765
+ */
5766
+ get isInitialized() {
5767
+ return this.clobClient !== null && this.apiCreds !== null;
5723
5768
  }
5724
- const salt = crypto.randomBytes(SALT_LENGTH);
5725
- const key = deriveKey(passphrase, salt);
5726
- const encryptedEntries = entries.map(({ key: envKey, value }) => {
5727
- if (isSensitiveKey(envKey)) {
5728
- const { iv, encrypted, tag } = encryptValue(value, key);
5729
- return {
5730
- key: envKey,
5731
- value: encrypted,
5732
- encrypted: true,
5733
- iv,
5734
- tag
5735
- };
5736
- }
5769
+ // ============================================================
5770
+ // CLOB API ORDER BOOK & PRICES
5771
+ // ============================================================
5772
+ /**
5773
+ * Get the order book for a specific outcome token.
5774
+ */
5775
+ async getOrderBook(tokenId) {
5776
+ this.ensureInitialized();
5777
+ const book = await this.clobClient.getOrderBook(tokenId);
5737
5778
  return {
5738
- key: envKey,
5739
- value,
5740
- encrypted: false
5779
+ bids: (book.bids || []).map((b) => ({ price: parseFloat(b.price), size: parseFloat(b.size) })),
5780
+ asks: (book.asks || []).map((a) => ({ price: parseFloat(a.price), size: parseFloat(a.size) }))
5741
5781
  };
5742
- });
5743
- const encryptedEnv = {
5744
- version: 1,
5745
- salt: salt.toString("hex"),
5746
- entries: encryptedEntries
5747
- };
5748
- const encPath = envPath + ".enc";
5749
- fs.writeFileSync(encPath, JSON.stringify(encryptedEnv, null, 2), { mode: 384 });
5750
- if (deleteOriginal) {
5751
- fs.unlinkSync(envPath);
5752
5782
  }
5753
- const sensitiveCount = encryptedEntries.filter((e) => e.encrypted).length;
5754
- const plainCount = encryptedEntries.filter((e) => !e.encrypted).length;
5755
- console.log(
5756
- `Encrypted ${sensitiveCount} sensitive values (${plainCount} non-sensitive kept as plaintext)`
5757
- );
5758
- return encPath;
5759
- }
5760
- function decryptEnvFile(encPath, passphrase) {
5761
- if (!fs.existsSync(encPath)) {
5762
- throw new Error(`Encrypted env file not found: ${encPath}`);
5783
+ /**
5784
+ * Get the midpoint price for an outcome token.
5785
+ */
5786
+ async getMidpointPrice(tokenId) {
5787
+ const book = await this.getOrderBook(tokenId);
5788
+ if (book.bids.length === 0 || book.asks.length === 0) return 0;
5789
+ return (book.bids[0].price + book.asks[0].price) / 2;
5763
5790
  }
5764
- const content = JSON.parse(fs.readFileSync(encPath, "utf-8"));
5765
- if (content.version !== 1) {
5766
- throw new Error(`Unsupported encrypted env version: ${content.version}`);
5791
+ /**
5792
+ * Get the last trade price for an outcome token.
5793
+ */
5794
+ async getLastTradePrice(tokenId) {
5795
+ this.ensureInitialized();
5796
+ const resp = await this.clobClient.getLastTradePrice(tokenId);
5797
+ return parseFloat(resp?.price || "0");
5767
5798
  }
5768
- const salt = Buffer.from(content.salt, "hex");
5769
- const key = deriveKey(passphrase, salt);
5770
- const result = {};
5771
- for (const entry of content.entries) {
5772
- if (entry.encrypted) {
5773
- if (!entry.iv || !entry.tag) {
5774
- throw new Error(`Missing encryption metadata for ${entry.key}`);
5775
- }
5776
- try {
5777
- result[entry.key] = decryptValue(entry.value, key, entry.iv, entry.tag);
5778
- } catch {
5779
- throw new Error(
5780
- `Failed to decrypt ${entry.key}. Wrong passphrase or corrupted data.`
5781
- );
5782
- }
5783
- } else {
5784
- result[entry.key] = entry.value;
5785
- }
5799
+ // ============================================================
5800
+ // CLOB API ORDERS
5801
+ // ============================================================
5802
+ /**
5803
+ * Place a limit order on the CLOB.
5804
+ */
5805
+ async placeLimitOrder(params) {
5806
+ this.ensureInitialized();
5807
+ const order = await this.clobClient.createAndPostOrder({
5808
+ tokenID: params.tokenId,
5809
+ price: params.price,
5810
+ side: params.side,
5811
+ size: params.size
5812
+ });
5813
+ return {
5814
+ orderId: order?.orderID || "",
5815
+ success: !!order?.orderID
5816
+ };
5786
5817
  }
5787
- return result;
5788
- }
5789
- function loadSecureEnv(basePath, passphrase) {
5790
- const encPath = path.join(basePath, ".env.enc");
5791
- const envPath = path.join(basePath, ".env");
5792
- if (fs.existsSync(encPath)) {
5793
- if (!passphrase) {
5794
- passphrase = process.env.EXAGENT_PASSPHRASE;
5795
- }
5796
- if (!passphrase) {
5797
- console.warn("");
5798
- console.warn("WARNING: Found .env.enc but no passphrase provided.");
5799
- console.warn(" Set EXAGENT_PASSPHRASE environment variable or");
5800
- console.warn(" pass --passphrase when running the agent.");
5801
- console.warn(" Falling back to plaintext .env file.");
5802
- console.warn("");
5803
- } else {
5804
- const vars = decryptEnvFile(encPath, passphrase);
5805
- for (const [key, value] of Object.entries(vars)) {
5806
- process.env[key] = value;
5807
- }
5818
+ /**
5819
+ * Place a market order (aggressive limit at best available price).
5820
+ */
5821
+ async placeMarketOrder(params) {
5822
+ this.ensureInitialized();
5823
+ const order = await this.clobClient.createMarketOrder({
5824
+ tokenID: params.tokenId,
5825
+ amount: params.amount,
5826
+ side: params.side
5827
+ });
5828
+ const result = await this.clobClient.postOrder(order);
5829
+ return {
5830
+ orderId: result?.orderID || "",
5831
+ success: !!result?.orderID
5832
+ };
5833
+ }
5834
+ /**
5835
+ * Cancel an open order by ID.
5836
+ */
5837
+ async cancelOrder(orderId) {
5838
+ this.ensureInitialized();
5839
+ try {
5840
+ await this.clobClient.cancelOrder({ orderID: orderId });
5808
5841
  return true;
5842
+ } catch {
5843
+ return false;
5809
5844
  }
5810
5845
  }
5811
- if (fs.existsSync(envPath)) {
5812
- const content = fs.readFileSync(envPath, "utf-8");
5813
- const entries = parseEnvFile(content);
5814
- const sensitiveKeys = entries.filter(({ key }) => isSensitiveKey(key)).map(({ key }) => key);
5815
- if (sensitiveKeys.length > 0) {
5816
- console.warn("");
5817
- console.warn("WARNING: Sensitive values stored in plaintext .env file:");
5818
- for (const key of sensitiveKeys) {
5819
- console.warn(` - ${key}`);
5820
- }
5821
- console.warn("");
5822
- console.warn(' Run "npx @exagent/agent encrypt" to secure your keys.');
5823
- console.warn("");
5846
+ /**
5847
+ * Cancel all open orders.
5848
+ */
5849
+ async cancelAllOrders() {
5850
+ this.ensureInitialized();
5851
+ try {
5852
+ await this.clobClient.cancelAll();
5853
+ return true;
5854
+ } catch {
5855
+ return false;
5824
5856
  }
5825
- return false;
5826
5857
  }
5827
- return false;
5828
- }
5829
-
5830
- // src/index.ts
5831
- var AGENT_VERSION = "0.1.39";
5832
-
5833
- // src/relay.ts
5834
- var RelayClient = class {
5835
- config;
5836
- ws = null;
5837
- authenticated = false;
5838
- authRejected = false;
5839
- reconnectAttempts = 0;
5840
- maxReconnectAttempts = 50;
5841
- reconnectTimer = null;
5842
- heartbeatTimer = null;
5843
- stopped = false;
5844
- constructor(config) {
5845
- this.config = config;
5858
+ /**
5859
+ * Get open orders for the agent's wallet.
5860
+ */
5861
+ async getOpenOrders() {
5862
+ this.ensureInitialized();
5863
+ return this.clobClient.getOpenOrders();
5846
5864
  }
5847
5865
  /**
5848
- * Connect to the relay server
5866
+ * Get trade history (fills) for the agent's wallet.
5849
5867
  */
5850
- async connect() {
5851
- if (this.stopped) return;
5852
- const wsUrl = this.config.relay.apiUrl.replace(/^https?:\/\//, (m) => m.includes("https") ? "wss://" : "ws://").replace(/\/$/, "") + "/ws/agent";
5853
- return new Promise((resolve, reject) => {
5854
- try {
5855
- this.ws = new import_ws2.default(wsUrl);
5856
- } catch (error) {
5857
- console.error("Relay: Failed to create WebSocket:", error);
5858
- this.scheduleReconnect();
5859
- reject(error);
5860
- return;
5861
- }
5862
- const connectTimeout = setTimeout(() => {
5863
- if (!this.authenticated) {
5868
+ async getTradeHistory() {
5869
+ this.ensureInitialized();
5870
+ const trades = await this.clobClient.getTrades();
5871
+ return (trades || []).map((t) => this.parseRawFill(t));
5872
+ }
5873
+ // ============================================================
5874
+ // GAMMA API — MARKET DISCOVERY (public, no auth)
5875
+ // ============================================================
5876
+ /**
5877
+ * Get active prediction markets from Gamma API.
5878
+ */
5879
+ async getMarkets(params) {
5880
+ const query = new URLSearchParams();
5881
+ if (params?.limit) query.set("limit", String(params.limit));
5882
+ if (params?.offset) query.set("offset", String(params.offset));
5883
+ if (params?.active !== void 0) query.set("active", String(params.active));
5884
+ if (params?.category) query.set("tag", params.category);
5885
+ const url = `${this.config.gammaApiUrl}/markets?${query.toString()}`;
5886
+ const resp = await fetch(url);
5887
+ if (!resp.ok) throw new Error(`Gamma API error: ${resp.status} ${await resp.text()}`);
5888
+ const raw = await resp.json();
5889
+ return (raw || []).map((m) => this.parseGammaMarket(m));
5890
+ }
5891
+ /**
5892
+ * Get a single market by condition ID.
5893
+ */
5894
+ async getMarketByConditionId(conditionId) {
5895
+ const cached = this.marketCache.get(conditionId);
5896
+ if (cached && Date.now() - cached.cachedAt < this.CACHE_TTL_MS) {
5897
+ return cached.market;
5898
+ }
5899
+ const url = `${this.config.gammaApiUrl}/markets?condition_id=${conditionId}`;
5900
+ const resp = await fetch(url);
5901
+ if (!resp.ok) return null;
5902
+ const raw = await resp.json();
5903
+ if (!raw || raw.length === 0) return null;
5904
+ const market = this.parseGammaMarket(raw[0]);
5905
+ this.marketCache.set(conditionId, { market, cachedAt: Date.now() });
5906
+ return market;
5907
+ }
5908
+ /**
5909
+ * Search markets by query string.
5910
+ */
5911
+ async searchMarkets(query, limit = 20) {
5912
+ const url = `${this.config.gammaApiUrl}/markets?_q=${encodeURIComponent(query)}&limit=${limit}&active=true`;
5913
+ const resp = await fetch(url);
5914
+ if (!resp.ok) return [];
5915
+ const raw = await resp.json();
5916
+ return (raw || []).map((m) => this.parseGammaMarket(m));
5917
+ }
5918
+ /**
5919
+ * Get trending markets sorted by volume.
5920
+ */
5921
+ async getTrendingMarkets(limit = 10) {
5922
+ const url = `${this.config.gammaApiUrl}/markets?active=true&limit=${limit}&order=volume24hr&ascending=false`;
5923
+ const resp = await fetch(url);
5924
+ if (!resp.ok) return [];
5925
+ const raw = await resp.json();
5926
+ return (raw || []).map((m) => this.parseGammaMarket(m));
5927
+ }
5928
+ // ============================================================
5929
+ // WALLET ADDRESS
5930
+ // ============================================================
5931
+ getWalletAddress() {
5932
+ return this.walletAddress;
5933
+ }
5934
+ /**
5935
+ * Get the effective maker address for CLOB orders.
5936
+ * In vault mode, this is the vault contract address.
5937
+ * In normal mode, this is the agent's EOA address.
5938
+ */
5939
+ getMakerAddress() {
5940
+ return this.vaultMode && this.vaultAddress ? this.vaultAddress : this.walletAddress;
5941
+ }
5942
+ /**
5943
+ * Whether the client is operating in vault mode.
5944
+ */
5945
+ get isVaultMode() {
5946
+ return this.vaultMode;
5947
+ }
5948
+ /**
5949
+ * Get the vault address (null if not in vault mode).
5950
+ */
5951
+ getVaultAddress() {
5952
+ return this.vaultAddress;
5953
+ }
5954
+ // ============================================================
5955
+ // PRIVATE HELPERS
5956
+ // ============================================================
5957
+ ensureInitialized() {
5958
+ if (!this.clobClient) {
5959
+ throw new Error("PolymarketClient not initialized. Call initialize() first.");
5960
+ }
5961
+ }
5962
+ parseGammaMarket(raw) {
5963
+ const outcomes = raw.outcomes ? JSON.parse(raw.outcomes) : ["Yes", "No"];
5964
+ const outcomePrices = raw.outcomePrices ? JSON.parse(raw.outcomePrices) : [0, 0];
5965
+ const outcomeTokenIds = raw.clobTokenIds ? JSON.parse(raw.clobTokenIds) : [];
5966
+ return {
5967
+ conditionId: raw.conditionId || raw.condition_id || "",
5968
+ question: raw.question || "",
5969
+ description: raw.description || "",
5970
+ category: raw.groupItemTitle || raw.category || "Other",
5971
+ outcomes,
5972
+ outcomeTokenIds,
5973
+ outcomePrices: outcomePrices.map((p) => parseFloat(p) || 0),
5974
+ volume24h: parseFloat(raw.volume24hr || raw.volume24h || "0"),
5975
+ liquidity: parseFloat(raw.liquidity || "0"),
5976
+ endDate: raw.endDate ? new Date(raw.endDate).getTime() / 1e3 : 0,
5977
+ active: raw.active !== false && raw.closed !== true,
5978
+ resolved: raw.resolved === true,
5979
+ winningOutcome: raw.winningOutcome,
5980
+ resolutionSource: raw.resolutionSource || void 0,
5981
+ uniqueTraders: raw.uniqueTraders || void 0
5982
+ };
5983
+ }
5984
+ parseRawFill(raw) {
5985
+ const tokenId = raw.asset_id || void 0;
5986
+ const marketConditionId = raw.market || raw.asset_id || "";
5987
+ return {
5988
+ orderId: raw.orderId || raw.order_id || "",
5989
+ tradeId: raw.id || raw.tradeId || "",
5990
+ marketConditionId,
5991
+ outcomeIndex: raw.outcome_index ?? (raw.side === "BUY" ? 0 : 1),
5992
+ side: raw.side === "BUY" || raw.side === "buy" ? "BUY" : "SELL",
5993
+ price: String(raw.price || "0"),
5994
+ size: String(raw.size || "0"),
5995
+ fee: String(raw.fee || "0"),
5996
+ timestamp: raw.timestamp || raw.created_at ? new Date(raw.created_at).getTime() : Date.now(),
5997
+ isMaker: raw.maker_order || raw.is_maker || false,
5998
+ tokenId
5999
+ };
6000
+ }
6001
+ };
6002
+
6003
+ // src/prediction/signer.ts
6004
+ var import_viem7 = require("viem");
6005
+ function tradeIdToBytes32(tradeId) {
6006
+ if (tradeId.startsWith("0x") && tradeId.length === 66) {
6007
+ return tradeId;
6008
+ }
6009
+ return (0, import_viem7.keccak256)((0, import_viem7.encodePacked)(["string"], [tradeId]));
6010
+ }
6011
+ function encodePredictionInstrument(conditionId, outcomeIndex) {
6012
+ return `${PREDICTION_INSTRUMENT_PREFIX}${conditionId}:${outcomeIndex}`;
6013
+ }
6014
+ function calculatePredictionFee(notionalUSD) {
6015
+ return notionalUSD * 20n / 10000n;
6016
+ }
6017
+
6018
+ // src/prediction/order-manager.ts
6019
+ var PredictionOrderManager = class {
6020
+ client;
6021
+ config;
6022
+ /** Recent fills tracked for recording */
6023
+ recentFills = [];
6024
+ MAX_RECENT_FILLS = 100;
6025
+ constructor(client, config) {
6026
+ this.client = client;
6027
+ this.config = config;
6028
+ }
6029
+ // ============================================================
6030
+ // ORDER PLACEMENT
6031
+ // ============================================================
6032
+ /**
6033
+ * Execute a prediction trade signal.
6034
+ * Routes to limit or market order based on signal.orderType.
6035
+ */
6036
+ async executeSignal(signal) {
6037
+ try {
6038
+ const violation = this.checkRiskLimits(signal);
6039
+ if (violation) {
6040
+ return { success: false, status: "error", error: violation };
6041
+ }
6042
+ const market = await this.client.getMarketByConditionId(signal.marketConditionId);
6043
+ if (!market) {
6044
+ return { success: false, status: "error", error: `Market not found: ${signal.marketConditionId}` };
6045
+ }
6046
+ if (!market.active) {
6047
+ return { success: false, status: "error", error: `Market is closed: ${signal.marketQuestion}` };
6048
+ }
6049
+ const tokenId = market.outcomeTokenIds[signal.outcomeIndex];
6050
+ if (!tokenId) {
6051
+ return { success: false, status: "error", error: `Invalid outcome index ${signal.outcomeIndex} for market` };
6052
+ }
6053
+ const isBuy = signal.action === "buy_yes" || signal.action === "buy_no";
6054
+ const side = isBuy ? "BUY" : "SELL";
6055
+ let result;
6056
+ if (signal.orderType === "market") {
6057
+ result = await this.client.placeMarketOrder({
6058
+ tokenId,
6059
+ amount: signal.amount,
6060
+ side
6061
+ });
6062
+ } else {
6063
+ result = await this.client.placeLimitOrder({
6064
+ tokenId,
6065
+ price: signal.limitPrice,
6066
+ size: signal.amount,
6067
+ side
6068
+ });
6069
+ }
6070
+ if (result.success) {
6071
+ console.log(
6072
+ `Prediction order placed: ${signal.action} ${signal.amount} @ $${signal.limitPrice} \u2014 "${signal.marketQuestion}" \u2014 order: ${result.orderId}`
6073
+ );
6074
+ return {
6075
+ success: true,
6076
+ orderId: result.orderId,
6077
+ status: signal.orderType === "market" ? "filled" : "resting"
6078
+ };
6079
+ }
6080
+ return { success: false, status: "error", error: "Order placement failed" };
6081
+ } catch (error) {
6082
+ const message = error instanceof Error ? error.message : String(error);
6083
+ console.error(`Prediction order failed for "${signal.marketQuestion}":`, message);
6084
+ return { success: false, status: "error", error: message };
6085
+ }
6086
+ }
6087
+ /**
6088
+ * Cancel an open order by ID.
6089
+ */
6090
+ async cancelOrder(orderId) {
6091
+ return this.client.cancelOrder(orderId);
6092
+ }
6093
+ /**
6094
+ * Cancel all open orders.
6095
+ */
6096
+ async cancelAllOrders() {
6097
+ return this.client.cancelAllOrders();
6098
+ }
6099
+ // ============================================================
6100
+ // FILL TRACKING
6101
+ // ============================================================
6102
+ /**
6103
+ * Poll for new fills since last check.
6104
+ * Returns fills that haven't been seen before.
6105
+ */
6106
+ async pollNewFills() {
6107
+ try {
6108
+ const allFills = await this.client.getTradeHistory();
6109
+ const seenIds = new Set(this.recentFills.map((f) => f.tradeId));
6110
+ const newFills = allFills.filter((f) => !seenIds.has(f.tradeId));
6111
+ for (const fill of newFills) {
6112
+ this.recentFills.push(fill);
6113
+ if (this.recentFills.length > this.MAX_RECENT_FILLS) {
6114
+ this.recentFills.shift();
6115
+ }
6116
+ }
6117
+ return newFills;
6118
+ } catch (error) {
6119
+ const message = error instanceof Error ? error.message : String(error);
6120
+ console.error("Failed to poll prediction fills:", message);
6121
+ return [];
6122
+ }
6123
+ }
6124
+ /**
6125
+ * Get recent fills (from local cache).
6126
+ */
6127
+ getRecentFills() {
6128
+ return [...this.recentFills];
6129
+ }
6130
+ // ============================================================
6131
+ // RISK CHECKS
6132
+ // ============================================================
6133
+ /**
6134
+ * Check if a signal violates risk limits.
6135
+ * Returns error string if violated, null if OK.
6136
+ */
6137
+ checkRiskLimits(signal) {
6138
+ if (signal.amount > this.config.maxNotionalUSD) {
6139
+ return `Trade amount $${signal.amount} exceeds max notional $${this.config.maxNotionalUSD}`;
6140
+ }
6141
+ if (signal.limitPrice <= 0 || signal.limitPrice >= 1) {
6142
+ return `Limit price ${signal.limitPrice} out of bounds (must be 0.01-0.99)`;
6143
+ }
6144
+ if (signal.confidence < 0.3) {
6145
+ return `Confidence ${signal.confidence} below minimum threshold (0.3)`;
6146
+ }
6147
+ if (this.config.allowedCategories && this.config.allowedCategories.length > 0) {
6148
+ }
6149
+ return null;
6150
+ }
6151
+ };
6152
+
6153
+ // src/prediction/position-manager.ts
6154
+ var PredictionPositionManager = class {
6155
+ client;
6156
+ config;
6157
+ /** Local position tracking (conditionId:outcomeIndex -> position data) */
6158
+ positions = /* @__PURE__ */ new Map();
6159
+ /** Cache TTL */
6160
+ lastPriceRefresh = 0;
6161
+ PRICE_REFRESH_MS = 1e4;
6162
+ // 10 seconds
6163
+ constructor(client, config) {
6164
+ this.client = client;
6165
+ this.config = config;
6166
+ }
6167
+ // ============================================================
6168
+ // POSITION QUERIES
6169
+ // ============================================================
6170
+ /**
6171
+ * Get all open prediction positions with current prices.
6172
+ */
6173
+ async getPositions(forceRefresh = false) {
6174
+ if (forceRefresh || Date.now() - this.lastPriceRefresh > this.PRICE_REFRESH_MS) {
6175
+ await this.refreshPrices();
6176
+ }
6177
+ return Array.from(this.positions.values()).filter((p) => p.balance > 0).map((p) => this.toExternalPosition(p));
6178
+ }
6179
+ /**
6180
+ * Get a specific position.
6181
+ */
6182
+ async getPosition(conditionId, outcomeIndex) {
6183
+ const key = `${conditionId}:${outcomeIndex}`;
6184
+ const pos = this.positions.get(key);
6185
+ if (!pos || pos.balance <= 0) return null;
6186
+ return this.toExternalPosition(pos);
6187
+ }
6188
+ /**
6189
+ * Get account summary (balances, exposure, PnL).
6190
+ */
6191
+ async getAccountSummary() {
6192
+ const positions = await this.getPositions();
6193
+ const totalExposure = positions.reduce((sum, p) => sum + p.costBasis, 0);
6194
+ const totalUnrealizedPnl = positions.reduce((sum, p) => sum + p.unrealizedPnl, 0);
6195
+ const openMarkets = new Set(positions.map((p) => p.marketConditionId));
6196
+ return {
6197
+ polygonUSDC: 0,
6198
+ // Filled in by runtime from on-chain balance
6199
+ baseUSDC: 0,
6200
+ // Filled in by runtime from on-chain balance
6201
+ totalExposure,
6202
+ totalUnrealizedPnl,
6203
+ openMarketCount: openMarkets.size,
6204
+ openPositionCount: positions.length,
6205
+ pendingFees: 0
6206
+ // Filled in by recorder
6207
+ };
6208
+ }
6209
+ /**
6210
+ * Get total exposure across all positions.
6211
+ */
6212
+ getTotalExposure() {
6213
+ let total = 0;
6214
+ for (const pos of this.positions.values()) {
6215
+ if (pos.balance > 0) total += pos.totalCostBasis;
6216
+ }
6217
+ return total;
6218
+ }
6219
+ /**
6220
+ * Get total unrealized PnL.
6221
+ */
6222
+ getTotalUnrealizedPnl() {
6223
+ let total = 0;
6224
+ for (const pos of this.positions.values()) {
6225
+ if (pos.balance > 0) {
6226
+ total += (pos.currentPrice - pos.averageEntryPrice) * pos.balance;
6227
+ }
6228
+ }
6229
+ return total;
6230
+ }
6231
+ // ============================================================
6232
+ // FILL PROCESSING
6233
+ // ============================================================
6234
+ /**
6235
+ * Process a fill and update position tracking.
6236
+ * Called when a new fill is detected by the order manager.
6237
+ */
6238
+ processFill(fill) {
6239
+ const key = `${fill.marketConditionId}:${fill.outcomeIndex}`;
6240
+ let pos = this.positions.get(key);
6241
+ const price = parseFloat(fill.price);
6242
+ const size = parseFloat(fill.size);
6243
+ if (!pos) {
6244
+ pos = {
6245
+ marketConditionId: fill.marketConditionId,
6246
+ outcomeIndex: fill.outcomeIndex,
6247
+ marketQuestion: fill.marketQuestion || "",
6248
+ tokenId: fill.tokenId || "",
6249
+ balance: 0,
6250
+ totalBought: 0,
6251
+ totalSold: 0,
6252
+ totalCostBasis: 0,
6253
+ totalProceeds: 0,
6254
+ averageEntryPrice: 0,
6255
+ currentPrice: price,
6256
+ category: void 0,
6257
+ endDate: void 0
6258
+ };
6259
+ this.positions.set(key, pos);
6260
+ } else if (!pos.tokenId && fill.tokenId) {
6261
+ pos.tokenId = fill.tokenId;
6262
+ }
6263
+ if (fill.side === "BUY") {
6264
+ const oldCost = pos.averageEntryPrice * pos.balance;
6265
+ const newCost = price * size;
6266
+ pos.balance += size;
6267
+ pos.totalBought += size;
6268
+ pos.totalCostBasis += newCost;
6269
+ pos.averageEntryPrice = pos.balance > 0 ? (oldCost + newCost) / pos.balance : 0;
6270
+ } else {
6271
+ pos.balance -= size;
6272
+ pos.totalSold += size;
6273
+ pos.totalProceeds += price * size;
6274
+ if (pos.balance < 0) pos.balance = 0;
6275
+ }
6276
+ }
6277
+ /**
6278
+ * Process multiple fills (batch update).
6279
+ */
6280
+ processFills(fills) {
6281
+ for (const fill of fills) {
6282
+ this.processFill(fill);
6283
+ }
6284
+ }
6285
+ // ============================================================
6286
+ // MARKET RESOLUTION
6287
+ // ============================================================
6288
+ /**
6289
+ * Mark a market as resolved. Positions settle at $0 or $1.
6290
+ */
6291
+ resolveMarket(conditionId, winningOutcome) {
6292
+ for (const [key, pos] of this.positions.entries()) {
6293
+ if (pos.marketConditionId === conditionId) {
6294
+ const isWinner = pos.outcomeIndex === winningOutcome;
6295
+ pos.currentPrice = isWinner ? 1 : 0;
6296
+ if (pos.balance > 0) {
6297
+ pos.totalProceeds += pos.currentPrice * pos.balance;
6298
+ pos.totalSold += pos.balance;
6299
+ pos.balance = 0;
6300
+ }
6301
+ }
6302
+ }
6303
+ }
6304
+ // ============================================================
6305
+ // PERSISTENCE
6306
+ // ============================================================
6307
+ /**
6308
+ * Export position state for persistence across restarts.
6309
+ */
6310
+ exportState() {
6311
+ return Array.from(this.positions.values());
6312
+ }
6313
+ /**
6314
+ * Import position state from previous session.
6315
+ */
6316
+ importState(state) {
6317
+ this.positions.clear();
6318
+ for (const pos of state) {
6319
+ const key = `${pos.marketConditionId}:${pos.outcomeIndex}`;
6320
+ this.positions.set(key, pos);
6321
+ }
6322
+ }
6323
+ // ============================================================
6324
+ // PRIVATE
6325
+ // ============================================================
6326
+ /**
6327
+ * Refresh current prices for all open positions from CLOB.
6328
+ */
6329
+ async refreshPrices() {
6330
+ const openPositions = Array.from(this.positions.values()).filter((p) => p.balance > 0);
6331
+ await Promise.all(
6332
+ openPositions.map(async (pos) => {
6333
+ try {
6334
+ if (!pos.tokenId) {
6335
+ const market = await this.client.getMarketByConditionId(pos.marketConditionId);
6336
+ if (market && market.outcomeTokenIds[pos.outcomeIndex]) {
6337
+ pos.tokenId = market.outcomeTokenIds[pos.outcomeIndex];
6338
+ }
6339
+ }
6340
+ if (pos.tokenId) {
6341
+ const price = await this.client.getMidpointPrice(pos.tokenId);
6342
+ if (price > 0) pos.currentPrice = price;
6343
+ }
6344
+ } catch {
6345
+ }
6346
+ })
6347
+ );
6348
+ this.lastPriceRefresh = Date.now();
6349
+ }
6350
+ toExternalPosition(pos) {
6351
+ const unrealizedPnl = pos.balance > 0 ? (pos.currentPrice - pos.averageEntryPrice) * pos.balance : 0;
6352
+ return {
6353
+ marketConditionId: pos.marketConditionId,
6354
+ marketQuestion: pos.marketQuestion,
6355
+ outcomeIndex: pos.outcomeIndex,
6356
+ outcomeLabel: pos.outcomeIndex === 0 ? "Yes" : "No",
6357
+ tokenId: pos.tokenId,
6358
+ balance: pos.balance,
6359
+ averageEntryPrice: pos.averageEntryPrice,
6360
+ currentPrice: pos.currentPrice,
6361
+ unrealizedPnl,
6362
+ costBasis: pos.totalCostBasis - pos.totalProceeds,
6363
+ endDate: pos.endDate,
6364
+ category: pos.category
6365
+ };
6366
+ }
6367
+ };
6368
+
6369
+ // src/prediction/recorder.ts
6370
+ var import_viem8 = require("viem");
6371
+ var import_chains5 = require("viem/chains");
6372
+ var import_accounts4 = require("viem/accounts");
6373
+ var ROUTER_ADDRESS2 = "0x1BCFa13f677fDCf697D8b7d5120f544817F1de1A";
6374
+ var ROUTER_ABI2 = [
6375
+ {
6376
+ type: "function",
6377
+ name: "recordPerpTrade",
6378
+ stateMutability: "nonpayable",
6379
+ inputs: [
6380
+ { name: "agentId", type: "uint256" },
6381
+ { name: "configHash", type: "bytes32" },
6382
+ { name: "instrument", type: "string" },
6383
+ { name: "isLong", type: "bool" },
6384
+ { name: "notionalUSD", type: "uint256" },
6385
+ { name: "feeUSD", type: "uint256" },
6386
+ { name: "fillId", type: "bytes32" }
6387
+ ],
6388
+ outputs: [{ name: "", type: "bool" }]
6389
+ }
6390
+ ];
6391
+ var MAX_RETRIES2 = 3;
6392
+ var RETRY_DELAY_MS2 = 5e3;
6393
+ var PredictionTradeRecorder = class {
6394
+ publicClient;
6395
+ walletClient;
6396
+ account;
6397
+ agentId;
6398
+ configHash;
6399
+ /** Retry queue for failed recordings */
6400
+ retryQueue = [];
6401
+ /** Set of fill IDs already recorded (or in-progress) to prevent local dups */
6402
+ recordedFills = /* @__PURE__ */ new Set();
6403
+ /** Timer for processing retry queue */
6404
+ retryTimer = null;
6405
+ /** Accumulated fees pending bridge to Base treasury (in USD, 6-decimal) */
6406
+ accumulatedFees = 0n;
6407
+ constructor(opts) {
6408
+ this.agentId = opts.agentId;
6409
+ this.configHash = opts.configHash;
6410
+ this.account = (0, import_accounts4.privateKeyToAccount)(opts.privateKey);
6411
+ const rpcUrl = opts.rpcUrl || "https://mainnet.base.org";
6412
+ const transport = (0, import_viem8.http)(rpcUrl, { timeout: 6e4 });
6413
+ this.publicClient = (0, import_viem8.createPublicClient)({
6414
+ chain: import_chains5.base,
6415
+ transport
6416
+ });
6417
+ this.walletClient = (0, import_viem8.createWalletClient)({
6418
+ chain: import_chains5.base,
6419
+ transport,
6420
+ account: this.account
6421
+ });
6422
+ this.retryTimer = setInterval(() => this.processRetryQueue(), RETRY_DELAY_MS2);
6423
+ }
6424
+ // ============================================================
6425
+ // PUBLIC API
6426
+ // ============================================================
6427
+ /**
6428
+ * Record a prediction fill on-chain.
6429
+ * Converts the Polymarket fill into recordPerpTrade params with POLY: prefix.
6430
+ */
6431
+ async recordFill(fill) {
6432
+ const fillId = tradeIdToBytes32(fill.tradeId);
6433
+ const fillIdStr = fillId.toLowerCase();
6434
+ if (this.recordedFills.has(fillIdStr)) {
6435
+ return { success: true };
6436
+ }
6437
+ this.recordedFills.add(fillIdStr);
6438
+ const notionalUSD = this.calculateNotionalUSD(fill);
6439
+ const feeUSD = calculatePredictionFee(notionalUSD);
6440
+ const params = {
6441
+ agentId: this.agentId,
6442
+ configHash: this.configHash,
6443
+ instrument: encodePredictionInstrument(fill.marketConditionId, fill.outcomeIndex),
6444
+ isLong: fill.side === "BUY",
6445
+ notionalUSD,
6446
+ feeUSD,
6447
+ fillId
6448
+ };
6449
+ this.accumulatedFees += feeUSD;
6450
+ return this.submitRecord(params);
6451
+ }
6452
+ /**
6453
+ * Update the config hash (when epoch changes).
6454
+ */
6455
+ updateConfigHash(configHash) {
6456
+ this.configHash = configHash;
6457
+ }
6458
+ /**
6459
+ * Get the number of fills pending retry.
6460
+ */
6461
+ get pendingRetries() {
6462
+ return this.retryQueue.length;
6463
+ }
6464
+ /**
6465
+ * Get the number of fills recorded (local dedup set size).
6466
+ */
6467
+ get recordedCount() {
6468
+ return this.recordedFills.size;
6469
+ }
6470
+ /**
6471
+ * Get accumulated fees pending bridge (6-decimal USD).
6472
+ */
6473
+ get pendingFees() {
6474
+ return this.accumulatedFees;
6475
+ }
6476
+ /**
6477
+ * Get accumulated fees as human-readable USD.
6478
+ */
6479
+ get pendingFeesUSD() {
6480
+ return Number(this.accumulatedFees) / 1e6;
6481
+ }
6482
+ /**
6483
+ * Reset accumulated fees (after bridge to treasury).
6484
+ */
6485
+ resetAccumulatedFees() {
6486
+ this.accumulatedFees = 0n;
6487
+ }
6488
+ /**
6489
+ * Stop the recorder (clear retry timer).
6490
+ */
6491
+ stop() {
6492
+ if (this.retryTimer) {
6493
+ clearInterval(this.retryTimer);
6494
+ this.retryTimer = null;
6495
+ }
6496
+ }
6497
+ // ============================================================
6498
+ // PRIVATE
6499
+ // ============================================================
6500
+ /**
6501
+ * Submit a recordPerpTrade transaction on Base.
6502
+ */
6503
+ async submitRecord(params) {
6504
+ try {
6505
+ const { request } = await this.publicClient.simulateContract({
6506
+ address: ROUTER_ADDRESS2,
6507
+ abi: ROUTER_ABI2,
6508
+ functionName: "recordPerpTrade",
6509
+ args: [
6510
+ params.agentId,
6511
+ params.configHash,
6512
+ params.instrument,
6513
+ params.isLong,
6514
+ params.notionalUSD,
6515
+ params.feeUSD,
6516
+ params.fillId
6517
+ ],
6518
+ account: this.account
6519
+ });
6520
+ const txHash = await this.walletClient.writeContract(request);
6521
+ const action = params.isLong ? "BUY" : "SELL";
6522
+ console.log(
6523
+ `Prediction trade recorded: ${action} ${params.instrument} $${Number(params.notionalUSD) / 1e6} \u2014 tx: ${txHash}`
6524
+ );
6525
+ return { success: true, txHash };
6526
+ } catch (error) {
6527
+ const message = error instanceof Error ? error.message : String(error);
6528
+ if (message.includes("FillAlreadyProcessed") || message.includes("already recorded")) {
6529
+ console.log(`Prediction fill already recorded on-chain: ${params.fillId}`);
6530
+ return { success: true };
6531
+ }
6532
+ console.error(`Failed to record prediction trade: ${message}`);
6533
+ this.retryQueue.push({
6534
+ params,
6535
+ retries: 0,
6536
+ lastAttempt: Date.now()
6537
+ });
6538
+ return { success: false, error: message };
6539
+ }
6540
+ }
6541
+ /**
6542
+ * Process the retry queue — attempt to re-submit failed recordings.
6543
+ */
6544
+ async processRetryQueue() {
6545
+ if (this.retryQueue.length === 0) return;
6546
+ const now = Date.now();
6547
+ const toRetry = this.retryQueue.filter(
6548
+ (item) => now - item.lastAttempt >= RETRY_DELAY_MS2
6549
+ );
6550
+ for (const item of toRetry) {
6551
+ item.retries++;
6552
+ item.lastAttempt = now;
6553
+ if (item.retries > MAX_RETRIES2) {
6554
+ console.error(
6555
+ `Prediction trade recording permanently failed after ${MAX_RETRIES2} retries: ${item.params.instrument} ${item.params.fillId}`
6556
+ );
6557
+ const idx = this.retryQueue.indexOf(item);
6558
+ if (idx >= 0) this.retryQueue.splice(idx, 1);
6559
+ continue;
6560
+ }
6561
+ console.log(
6562
+ `Retrying prediction trade recording (attempt ${item.retries}/${MAX_RETRIES2}): ${item.params.instrument}`
6563
+ );
6564
+ const result = await this.submitRecord(item.params);
6565
+ if (result.success) {
6566
+ const idx = this.retryQueue.indexOf(item);
6567
+ if (idx >= 0) this.retryQueue.splice(idx, 1);
6568
+ }
6569
+ }
6570
+ }
6571
+ // ============================================================
6572
+ // CONVERSION HELPERS
6573
+ // ============================================================
6574
+ /**
6575
+ * Calculate notional USD from a fill (6-decimal).
6576
+ * notionalUSD = price * size * 1e6
6577
+ */
6578
+ calculateNotionalUSD(fill) {
6579
+ const price = parseFloat(fill.price);
6580
+ const size = parseFloat(fill.size);
6581
+ return BigInt(Math.round(price * size * 1e6));
6582
+ }
6583
+ };
6584
+
6585
+ // src/prediction/market-browser.ts
6586
+ var MarketBrowser = class {
6587
+ gammaUrl;
6588
+ allowedCategories;
6589
+ /** Cache for market listings */
6590
+ listCache = /* @__PURE__ */ new Map();
6591
+ CACHE_TTL_MS = 6e4;
6592
+ constructor(config) {
6593
+ const merged = { ...DEFAULT_PREDICTION_CONFIG, ...config };
6594
+ this.gammaUrl = merged.gammaApiUrl;
6595
+ this.allowedCategories = merged.allowedCategories || [];
6596
+ }
6597
+ // ============================================================
6598
+ // PUBLIC API
6599
+ // ============================================================
6600
+ /**
6601
+ * Get active markets, optionally filtered by category.
6602
+ * Results are sorted by volume (highest first).
6603
+ */
6604
+ async getActiveMarkets(params) {
6605
+ const limit = params?.limit || 20;
6606
+ const offset = params?.offset || 0;
6607
+ const cacheKey = `active:${params?.category || "all"}:${limit}:${offset}`;
6608
+ const cached = this.listCache.get(cacheKey);
6609
+ if (cached && Date.now() - cached.cachedAt < this.CACHE_TTL_MS) {
6610
+ return cached.data;
6611
+ }
6612
+ const query = new URLSearchParams({
6613
+ active: "true",
6614
+ closed: "false",
6615
+ limit: String(limit),
6616
+ offset: String(offset),
6617
+ order: "volume24hr",
6618
+ ascending: "false"
6619
+ });
6620
+ if (params?.category) query.set("tag", params.category);
6621
+ const markets = await this.fetchGamma(`/markets?${query.toString()}`);
6622
+ const parsed = markets.map((m) => this.parseMarket(m));
6623
+ const filtered = this.allowedCategories.length > 0 ? parsed.filter(
6624
+ (m) => this.allowedCategories.some((c) => m.category.toLowerCase().includes(c.toLowerCase()))
6625
+ ) : parsed;
6626
+ this.listCache.set(cacheKey, { data: filtered, cachedAt: Date.now() });
6627
+ return filtered;
6628
+ }
6629
+ /**
6630
+ * Search markets by query text.
6631
+ */
6632
+ async searchMarkets(query, limit = 20) {
6633
+ const params = new URLSearchParams({
6634
+ _q: query,
6635
+ limit: String(limit),
6636
+ active: "true"
6637
+ });
6638
+ const markets = await this.fetchGamma(`/markets?${params.toString()}`);
6639
+ return markets.map((m) => this.parseMarket(m));
6640
+ }
6641
+ /**
6642
+ * Get trending markets (highest 24h volume).
6643
+ */
6644
+ async getTrendingMarkets(limit = 10) {
6645
+ return this.getActiveMarkets({ limit });
6646
+ }
6647
+ /**
6648
+ * Get markets expiring soon (within N days).
6649
+ */
6650
+ async getExpiringMarkets(withinDays = 7, limit = 20) {
6651
+ const markets = await this.getActiveMarkets({ limit: 100 });
6652
+ const cutoff = Date.now() / 1e3 + withinDays * 86400;
6653
+ return markets.filter((m) => m.endDate > 0 && m.endDate < cutoff).sort((a, b) => a.endDate - b.endDate).slice(0, limit);
6654
+ }
6655
+ /**
6656
+ * Get recently resolved markets (for PnL tracking).
6657
+ */
6658
+ async getRecentlyResolved(limit = 20) {
6659
+ const params = new URLSearchParams({
6660
+ closed: "true",
6661
+ limit: String(limit),
6662
+ order: "endDate",
6663
+ ascending: "false"
6664
+ });
6665
+ const markets = await this.fetchGamma(`/markets?${params.toString()}`);
6666
+ return markets.map((m) => this.parseMarket(m)).filter((m) => m.resolved);
6667
+ }
6668
+ /**
6669
+ * Get a single market's details by condition ID.
6670
+ */
6671
+ async getMarketDetail(conditionId) {
6672
+ const markets = await this.fetchGamma(`/markets?condition_id=${conditionId}`);
6673
+ if (!markets || markets.length === 0) return null;
6674
+ return this.parseMarket(markets[0]);
6675
+ }
6676
+ /**
6677
+ * Build a concise market summary string for LLM context.
6678
+ * Keeps the prompt token count manageable.
6679
+ */
6680
+ formatMarketsForLLM(markets, maxMarkets = 15) {
6681
+ const subset = markets.slice(0, maxMarkets);
6682
+ const lines = subset.map((m, i) => {
6683
+ const prices = m.outcomePrices.map((p, j) => `${m.outcomes[j]}: ${(p * 100).toFixed(1)}%`).join(", ");
6684
+ const vol = m.volume24h >= 1e3 ? `$${(m.volume24h / 1e3).toFixed(1)}K` : `$${m.volume24h.toFixed(0)}`;
6685
+ const endStr = m.endDate > 0 ? new Date(m.endDate * 1e3).toISOString().split("T")[0] : "TBD";
6686
+ return `${i + 1}. [${m.category}] "${m.question}" \u2014 ${prices} | Vol: ${vol} | Ends: ${endStr} | ID: ${m.conditionId}`;
6687
+ });
6688
+ return lines.join("\n");
6689
+ }
6690
+ // ============================================================
6691
+ // PRIVATE
6692
+ // ============================================================
6693
+ async fetchGamma(path8) {
6694
+ const url = `${this.gammaUrl}${path8}`;
6695
+ const resp = await fetch(url);
6696
+ if (!resp.ok) {
6697
+ console.error(`Gamma API error: ${resp.status} for ${url}`);
6698
+ return [];
6699
+ }
6700
+ const data = await resp.json();
6701
+ return Array.isArray(data) ? data : [];
6702
+ }
6703
+ parseMarket(raw) {
6704
+ const outcomes = raw.outcomes ? JSON.parse(raw.outcomes) : ["Yes", "No"];
6705
+ const outcomePrices = raw.outcomePrices ? JSON.parse(raw.outcomePrices) : [0, 0];
6706
+ const outcomeTokenIds = raw.clobTokenIds ? JSON.parse(raw.clobTokenIds) : [];
6707
+ return {
6708
+ conditionId: raw.conditionId || raw.condition_id || "",
6709
+ question: raw.question || "",
6710
+ description: raw.description || "",
6711
+ category: raw.groupItemTitle || raw.category || "Other",
6712
+ outcomes,
6713
+ outcomeTokenIds,
6714
+ outcomePrices: outcomePrices.map((p) => parseFloat(p) || 0),
6715
+ volume24h: parseFloat(raw.volume24hr || raw.volume24h || "0"),
6716
+ liquidity: parseFloat(raw.liquidity || "0"),
6717
+ endDate: raw.endDate ? new Date(raw.endDate).getTime() / 1e3 : 0,
6718
+ active: raw.active !== false && raw.closed !== true,
6719
+ resolved: raw.resolved === true,
6720
+ winningOutcome: raw.winningOutcome,
6721
+ resolutionSource: raw.resolutionSource || void 0,
6722
+ uniqueTraders: raw.uniqueTraders || void 0
6723
+ };
6724
+ }
6725
+ };
6726
+
6727
+ // src/prediction/funding.ts
6728
+ var import_viem9 = require("viem");
6729
+ var import_chains6 = require("viem/chains");
6730
+ var import_accounts5 = require("viem/accounts");
6731
+ var CONTRACTS = {
6732
+ // Base
6733
+ BASE_USDC: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
6734
+ BASE_TOKEN_MESSENGER_V2: "0x28b5a0e9C621a5BadaA536219b3a228C8168cf5d",
6735
+ BASE_MESSAGE_TRANSMITTER_V2: "0x81D40F21F12A8F0E3252Bccb954D722d4c464B64",
6736
+ // Polygon
6737
+ POLYGON_USDC: POLYGON_USDC_ADDRESS,
6738
+ POLYGON_TOKEN_MESSENGER_V2,
6739
+ POLYGON_MESSAGE_TRANSMITTER_V2
6740
+ };
6741
+ var IRIS_API_URL = "https://iris-api.circle.com/v1/attestations";
6742
+ var MIN_BRIDGE_AMOUNT = 1000000n;
6743
+ var ERC20_ABI2 = (0, import_viem9.parseAbi)([
6744
+ "function approve(address spender, uint256 amount) external returns (bool)",
6745
+ "function balanceOf(address account) external view returns (uint256)",
6746
+ "function allowance(address owner, address spender) external view returns (uint256)"
6747
+ ]);
6748
+ var TOKEN_MESSENGER_V2_ABI2 = (0, import_viem9.parseAbi)([
6749
+ "function depositForBurn(uint256 amount, uint32 destinationDomain, bytes32 mintRecipient, address burnToken) external returns (uint64 nonce)",
6750
+ "event DepositForBurn(uint64 indexed nonce, address indexed burnToken, uint256 amount, address indexed depositor, bytes32 mintRecipient, uint32 destinationDomain, bytes32 destinationTokenMessenger, bytes32 destinationCaller)"
6751
+ ]);
6752
+ var MESSAGE_TRANSMITTER_V2_ABI2 = (0, import_viem9.parseAbi)([
6753
+ "function receiveMessage(bytes message, bytes attestation) external returns (bool success)",
6754
+ "event MessageSent(bytes message)"
6755
+ ]);
6756
+ var PredictionFunding = class {
6757
+ basePublic;
6758
+ baseWallet;
6759
+ polygonPublic;
6760
+ polygonWallet;
6761
+ account;
6762
+ /** Override recipient for deposits to Polygon (vault address in vault mode) */
6763
+ polygonRecipient;
6764
+ constructor(config) {
6765
+ this.account = (0, import_accounts5.privateKeyToAccount)(config.privateKey);
6766
+ this.polygonRecipient = config.polygonRecipient;
6767
+ const baseTransport = (0, import_viem9.http)(config.baseRpcUrl || "https://mainnet.base.org", { timeout: 6e4 });
6768
+ const polygonTransport = (0, import_viem9.http)(config.polygonRpcUrl || "https://polygon-rpc.com", { timeout: 6e4 });
6769
+ this.basePublic = (0, import_viem9.createPublicClient)({ chain: import_chains6.base, transport: baseTransport });
6770
+ this.baseWallet = (0, import_viem9.createWalletClient)({ chain: import_chains6.base, transport: baseTransport, account: this.account });
6771
+ this.polygonPublic = (0, import_viem9.createPublicClient)({ chain: import_chains6.polygon, transport: polygonTransport });
6772
+ this.polygonWallet = (0, import_viem9.createWalletClient)({ chain: import_chains6.polygon, transport: polygonTransport, account: this.account });
6773
+ }
6774
+ // ============================================================
6775
+ // BALANCE QUERIES
6776
+ // ============================================================
6777
+ /** Get USDC balance on Base (6-decimal) */
6778
+ async getBaseUSDCBalance() {
6779
+ return this.basePublic.readContract({
6780
+ address: CONTRACTS.BASE_USDC,
6781
+ abi: ERC20_ABI2,
6782
+ functionName: "balanceOf",
6783
+ args: [this.account.address]
6784
+ });
6785
+ }
6786
+ /** Get USDC balance on Polygon (6-decimal) */
6787
+ async getPolygonUSDCBalance() {
6788
+ return this.polygonPublic.readContract({
6789
+ address: CONTRACTS.POLYGON_USDC,
6790
+ abi: ERC20_ABI2,
6791
+ functionName: "balanceOf",
6792
+ args: [this.account.address]
6793
+ });
6794
+ }
6795
+ /** Get MATIC balance on Polygon for gas (wei) */
6796
+ async getPolygonGasBalance() {
6797
+ return this.polygonPublic.getBalance({ address: this.account.address });
6798
+ }
6799
+ // ============================================================
6800
+ // DEPOSIT: Base → Polygon
6801
+ // ============================================================
6802
+ /**
6803
+ * Bridge USDC from Base to Polygon via CCTP V2.
6804
+ *
6805
+ * Steps:
6806
+ * 1. Approve USDC on Base for TokenMessengerV2
6807
+ * 2. Call depositForBurn (Base → Polygon)
6808
+ * 3. Wait for Circle attestation (~1-5 minutes)
6809
+ * 4. Call receiveMessage on Polygon
6810
+ */
6811
+ async depositToPolygon(amount, onStep) {
6812
+ const startTime = Date.now();
6813
+ if (amount < MIN_BRIDGE_AMOUNT) {
6814
+ return { success: false, amount, error: "Amount below minimum (1 USDC)" };
6815
+ }
6816
+ try {
6817
+ onStep?.("approve_usdc");
6818
+ await this.approveIfNeeded(
6819
+ this.basePublic,
6820
+ this.baseWallet,
6821
+ CONTRACTS.BASE_USDC,
6822
+ CONTRACTS.BASE_TOKEN_MESSENGER_V2,
6823
+ amount
6824
+ );
6825
+ onStep?.("cctp_burn");
6826
+ const recipient = this.polygonRecipient ?? this.account.address;
6827
+ const mintRecipient = this.addressToBytes32(recipient);
6828
+ const burnHash = await this.baseWallet.writeContract({
6829
+ address: CONTRACTS.BASE_TOKEN_MESSENGER_V2,
6830
+ abi: TOKEN_MESSENGER_V2_ABI2,
6831
+ functionName: "depositForBurn",
6832
+ args: [amount, CCTP_DOMAIN_POLYGON, mintRecipient, CONTRACTS.BASE_USDC]
6833
+ });
6834
+ const burnReceipt = await this.basePublic.waitForTransactionReceipt({ hash: burnHash });
6835
+ const messageBytes = this.extractMessageFromReceipt(burnReceipt);
6836
+ if (!messageBytes) {
6837
+ return { success: false, amount, burnTxHash: burnHash, error: "Failed to extract CCTP message from burn tx" };
6838
+ }
6839
+ onStep?.("wait_attestation");
6840
+ const attestation = await this.waitForAttestation(messageBytes);
6841
+ if (!attestation) {
6842
+ return { success: false, amount, burnTxHash: burnHash, error: "Attestation timeout (15 min)" };
6843
+ }
6844
+ onStep?.("cctp_receive");
6845
+ const receiveHash = await this.polygonWallet.writeContract({
6846
+ address: CONTRACTS.POLYGON_MESSAGE_TRANSMITTER_V2,
6847
+ abi: MESSAGE_TRANSMITTER_V2_ABI2,
6848
+ functionName: "receiveMessage",
6849
+ args: [messageBytes, attestation]
6850
+ });
6851
+ await this.polygonPublic.waitForTransactionReceipt({ hash: receiveHash });
6852
+ console.log(`CCTP deposit complete: ${Number(amount) / 1e6} USDC Base \u2192 Polygon in ${((Date.now() - startTime) / 1e3).toFixed(0)}s`);
6853
+ return {
6854
+ success: true,
6855
+ amount,
6856
+ burnTxHash: burnHash,
6857
+ receiveTxHash: receiveHash,
6858
+ duration: Date.now() - startTime
6859
+ };
6860
+ } catch (error) {
6861
+ const message = error instanceof Error ? error.message : String(error);
6862
+ console.error("CCTP deposit to Polygon failed:", message);
6863
+ return { success: false, amount, error: message, duration: Date.now() - startTime };
6864
+ }
6865
+ }
6866
+ // ============================================================
6867
+ // WITHDRAW: Polygon → Base
6868
+ // ============================================================
6869
+ /**
6870
+ * Bridge USDC from Polygon back to Base via CCTP V2.
6871
+ * Used for fee collection (bridge accumulated fees to Base treasury).
6872
+ */
6873
+ async withdrawToBase(amount, onStep) {
6874
+ const startTime = Date.now();
6875
+ if (amount < MIN_BRIDGE_AMOUNT) {
6876
+ return { success: false, amount, error: "Amount below minimum (1 USDC)" };
6877
+ }
6878
+ try {
6879
+ onStep?.("approve_usdc");
6880
+ await this.approveIfNeeded(
6881
+ this.polygonPublic,
6882
+ this.polygonWallet,
6883
+ CONTRACTS.POLYGON_USDC,
6884
+ CONTRACTS.POLYGON_TOKEN_MESSENGER_V2,
6885
+ amount
6886
+ );
6887
+ onStep?.("cctp_burn");
6888
+ const mintRecipient = this.addressToBytes32(this.account.address);
6889
+ const burnHash = await this.polygonWallet.writeContract({
6890
+ address: CONTRACTS.POLYGON_TOKEN_MESSENGER_V2,
6891
+ abi: TOKEN_MESSENGER_V2_ABI2,
6892
+ functionName: "depositForBurn",
6893
+ args: [amount, CCTP_DOMAIN_BASE, mintRecipient, CONTRACTS.POLYGON_USDC]
6894
+ });
6895
+ const burnReceipt = await this.polygonPublic.waitForTransactionReceipt({ hash: burnHash });
6896
+ const messageBytes = this.extractMessageFromReceipt(burnReceipt);
6897
+ if (!messageBytes) {
6898
+ return { success: false, amount, burnTxHash: burnHash, error: "Failed to extract CCTP message" };
6899
+ }
6900
+ onStep?.("wait_attestation");
6901
+ const attestation = await this.waitForAttestation(messageBytes);
6902
+ if (!attestation) {
6903
+ return { success: false, amount, burnTxHash: burnHash, error: "Attestation timeout" };
6904
+ }
6905
+ onStep?.("cctp_receive");
6906
+ const receiveHash = await this.baseWallet.writeContract({
6907
+ address: CONTRACTS.BASE_MESSAGE_TRANSMITTER_V2,
6908
+ abi: MESSAGE_TRANSMITTER_V2_ABI2,
6909
+ functionName: "receiveMessage",
6910
+ args: [messageBytes, attestation]
6911
+ });
6912
+ await this.basePublic.waitForTransactionReceipt({ hash: receiveHash });
6913
+ console.log(`CCTP withdrawal complete: ${Number(amount) / 1e6} USDC Polygon \u2192 Base in ${((Date.now() - startTime) / 1e3).toFixed(0)}s`);
6914
+ return {
6915
+ success: true,
6916
+ amount,
6917
+ burnTxHash: burnHash,
6918
+ receiveTxHash: receiveHash,
6919
+ duration: Date.now() - startTime
6920
+ };
6921
+ } catch (error) {
6922
+ const message = error instanceof Error ? error.message : String(error);
6923
+ console.error("CCTP withdrawal to Base failed:", message);
6924
+ return { success: false, amount, error: message, duration: Date.now() - startTime };
6925
+ }
6926
+ }
6927
+ // ============================================================
6928
+ // PRIVATE HELPERS
6929
+ // ============================================================
6930
+ /** Convert address to bytes32 (left-padded) for CCTP mintRecipient */
6931
+ addressToBytes32(address) {
6932
+ return `0x000000000000000000000000${address.slice(2)}`;
6933
+ }
6934
+ /** Approve USDC spend if needed (maxUint256 pattern) */
6935
+ async approveIfNeeded(publicClient, walletClient, token, spender, amount) {
6936
+ const allowance = await publicClient.readContract({
6937
+ address: token,
6938
+ abi: ERC20_ABI2,
6939
+ functionName: "allowance",
6940
+ args: [this.account.address, spender]
6941
+ });
6942
+ if (allowance < amount) {
6943
+ const maxUint256 = 2n ** 256n - 1n;
6944
+ const hash = await walletClient.writeContract({
6945
+ address: token,
6946
+ abi: ERC20_ABI2,
6947
+ functionName: "approve",
6948
+ args: [spender, maxUint256]
6949
+ });
6950
+ await publicClient.waitForTransactionReceipt({ hash });
6951
+ }
6952
+ }
6953
+ /** Extract MessageSent bytes from a CCTP burn transaction receipt */
6954
+ extractMessageFromReceipt(receipt) {
6955
+ for (const log of receipt.logs || []) {
6956
+ try {
6957
+ if (log.topics[0] === "0x8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b036") {
6958
+ return log.data;
6959
+ }
6960
+ } catch {
6961
+ continue;
6962
+ }
6963
+ }
6964
+ return null;
6965
+ }
6966
+ /** Wait for Circle attestation (polls Iris API) */
6967
+ async waitForAttestation(messageBytes, timeoutMs = 9e5) {
6968
+ const { keccak256: keccak2565 } = await import("viem");
6969
+ const messageHash = keccak2565(messageBytes);
6970
+ const start = Date.now();
6971
+ const pollInterval = 5e3;
6972
+ while (Date.now() - start < timeoutMs) {
6973
+ try {
6974
+ const resp = await fetch(`${IRIS_API_URL}/${messageHash}`);
6975
+ if (resp.ok) {
6976
+ const data = await resp.json();
6977
+ if (data.status === "complete" && data.attestation) {
6978
+ return data.attestation;
6979
+ }
6980
+ }
6981
+ } catch {
6982
+ }
6983
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
6984
+ }
6985
+ return null;
6986
+ }
6987
+ };
6988
+
6989
+ // src/prediction/vault-manager.ts
6990
+ var import_viem10 = require("viem");
6991
+ var import_chains7 = require("viem/chains");
6992
+ var import_accounts6 = require("viem/accounts");
6993
+ var ERC20_ABI3 = (0, import_viem10.parseAbi)([
6994
+ "function approve(address spender, uint256 amount) external returns (bool)",
6995
+ "function balanceOf(address account) external view returns (uint256)",
6996
+ "function allowance(address owner, address spender) external view returns (uint256)"
6997
+ ]);
6998
+ var VAULT_FACTORY_ABI2 = (0, import_viem10.parseAbi)([
6999
+ "function createVault(uint256 agentId, address agentWallet, uint256 seedAmount, string name, string symbol, address feeRecipient, bool isVerified, bytes agentSig) external returns (address)",
7000
+ "function vaults(uint256 agentId) external view returns (address)",
7001
+ "function isFactoryVault(address vault) external view returns (bool)",
7002
+ "function MIN_SEED_AMOUNT() external view returns (uint256)"
7003
+ ]);
7004
+ var VAULT_ABI2 = (0, import_viem10.parseAbi)([
7005
+ // ERC-4626
7006
+ "function deposit(uint256 assets, address receiver) external returns (uint256)",
7007
+ "function withdraw(uint256 assets, address receiver, address owner) external returns (uint256)",
7008
+ "function redeem(uint256 shares, address receiver, address owner) external returns (uint256)",
7009
+ "function redeemMax(address receiver, address owner) external returns (uint256)",
7010
+ "function totalAssets() external view returns (uint256)",
7011
+ "function totalSupply() external view returns (uint256)",
7012
+ "function balanceOf(address account) external view returns (uint256)",
7013
+ "function convertToAssets(uint256 shares) external view returns (uint256)",
7014
+ "function convertToShares(uint256 assets) external view returns (uint256)",
7015
+ // Vault-specific views
7016
+ "function sharePrice() external view returns (uint256)",
7017
+ "function availableTradingBalance() external view returns (uint256)",
7018
+ "function currentExposureBps() external view returns (uint256)",
7019
+ "function cachedCtfValue() external view returns (uint256)",
7020
+ "function lastCtfUpdate() external view returns (uint256)",
7021
+ "function depositCap() external view returns (uint256)",
7022
+ "function agentSeedAmount() external view returns (uint256)",
7023
+ "function circuitBreakerActive() external view returns (bool)",
7024
+ "function paused() external view returns (bool)",
7025
+ "function pendingTradingVolume() external view returns (uint256)",
7026
+ "function getTrackedTokenCount() external view returns (uint256)",
7027
+ "function agentWallet() external view returns (address)",
7028
+ "function agentId() external view returns (uint256)",
7029
+ "function isVerified() external view returns (bool)",
7030
+ "function maxExposureBps() external view returns (uint256)",
7031
+ // Keeper functions
7032
+ "function updatePositionValues(uint256[] tokenIds, uint256[] values) external",
7033
+ "function collectTradingFees(uint256 volume) external",
7034
+ // Emergency
7035
+ "function emergencyWithdraw() external returns (uint256)"
7036
+ ]);
7037
+ var PredictionVaultManager = class {
7038
+ config;
7039
+ publicClient;
7040
+ walletClient;
7041
+ account;
7042
+ /** Resolved vault address (discovered or created) */
7043
+ vaultAddress = null;
7044
+ /** NAV update timer */
7045
+ navTimer = null;
7046
+ /** Fee collection timer */
7047
+ feeTimer = null;
7048
+ /** Last known accumulated trading volume (for delta tracking) */
7049
+ lastReportedVolume = 0n;
7050
+ constructor(privateKey, config) {
7051
+ this.config = config;
7052
+ this.account = (0, import_accounts6.privateKeyToAccount)(privateKey);
7053
+ const transport = (0, import_viem10.http)(config.polygonRpcUrl, { timeout: 6e4 });
7054
+ this.publicClient = (0, import_viem10.createPublicClient)({ chain: import_chains7.polygon, transport });
7055
+ this.walletClient = (0, import_viem10.createWalletClient)({
7056
+ chain: import_chains7.polygon,
7057
+ transport,
7058
+ account: this.account
7059
+ });
7060
+ if (config.vaultAddress) {
7061
+ this.vaultAddress = config.vaultAddress;
7062
+ }
7063
+ }
7064
+ // ============================================================
7065
+ // INITIALIZATION
7066
+ // ============================================================
7067
+ /**
7068
+ * Initialize the vault manager — discover existing vault or prepare for creation.
7069
+ */
7070
+ async initialize() {
7071
+ if (!this.vaultAddress) {
7072
+ try {
7073
+ const vaultAddr = await this.publicClient.readContract({
7074
+ address: this.config.factoryAddress,
7075
+ abi: VAULT_FACTORY_ABI2,
7076
+ functionName: "vaults",
7077
+ args: [this.config.agentId]
7078
+ });
7079
+ if (vaultAddr && vaultAddr !== "0x0000000000000000000000000000000000000000") {
7080
+ this.vaultAddress = vaultAddr;
7081
+ console.log(`Discovered existing prediction vault: ${this.vaultAddress}`);
7082
+ }
7083
+ } catch {
7084
+ console.log("No existing prediction vault found \u2014 create one via createVault()");
7085
+ }
7086
+ }
7087
+ if (this.vaultAddress) {
7088
+ console.log(`Prediction vault manager initialized for vault: ${this.vaultAddress}`);
7089
+ }
7090
+ }
7091
+ /**
7092
+ * Get the vault address (null if no vault exists).
7093
+ */
7094
+ getVaultAddress() {
7095
+ return this.vaultAddress;
7096
+ }
7097
+ /**
7098
+ * Whether a vault has been created/discovered.
7099
+ */
7100
+ get hasVault() {
7101
+ return this.vaultAddress !== null;
7102
+ }
7103
+ // ============================================================
7104
+ // VAULT CREATION
7105
+ // ============================================================
7106
+ /**
7107
+ * Create a new prediction vault via PredictionVaultFactory.
7108
+ *
7109
+ * Deploys PredictionVault on Polygon with:
7110
+ * - Agent's EOA as the authorized signer for ERC-1271
7111
+ * - Seed USDC transferred from agent wallet to vault
7112
+ * - Deposit cap = seed × multiplier (10x unverified, 100x verified)
7113
+ */
7114
+ async createVault(seedAmount, name, symbol) {
7115
+ if (this.vaultAddress) {
7116
+ return { success: false, error: `Vault already exists: ${this.vaultAddress}` };
7117
+ }
7118
+ try {
7119
+ const message = (0, import_viem10.keccak256)(
7120
+ (0, import_viem10.encodePacked)(
7121
+ ["uint256", "address", "address"],
7122
+ [this.config.agentId, this.account.address, this.config.factoryAddress]
7123
+ )
7124
+ );
7125
+ const agentSig = await this.account.signMessage({ message: { raw: message } });
7126
+ await this.approveIfNeeded(
7127
+ POLYGON_USDC_ADDRESS,
7128
+ this.config.factoryAddress,
7129
+ seedAmount
7130
+ );
7131
+ const hash = await this.walletClient.writeContract({
7132
+ address: this.config.factoryAddress,
7133
+ abi: VAULT_FACTORY_ABI2,
7134
+ functionName: "createVault",
7135
+ args: [
7136
+ this.config.agentId,
7137
+ this.account.address,
7138
+ seedAmount,
7139
+ name,
7140
+ symbol,
7141
+ this.config.feeRecipient,
7142
+ this.config.isVerified ?? false,
7143
+ agentSig
7144
+ ]
7145
+ });
7146
+ const receipt = await this.publicClient.waitForTransactionReceipt({ hash });
7147
+ const vaultAddr = await this.publicClient.readContract({
7148
+ address: this.config.factoryAddress,
7149
+ abi: VAULT_FACTORY_ABI2,
7150
+ functionName: "vaults",
7151
+ args: [this.config.agentId]
7152
+ });
7153
+ this.vaultAddress = vaultAddr;
7154
+ console.log(`Prediction vault created: ${this.vaultAddress} (seed: ${(0, import_viem10.formatUnits)(seedAmount, 6)} USDC)`);
7155
+ return {
7156
+ success: true,
7157
+ vaultAddress: this.vaultAddress,
7158
+ txHash: hash
7159
+ };
7160
+ } catch (error) {
7161
+ const message = error instanceof Error ? error.message : String(error);
7162
+ console.error("Failed to create prediction vault:", message);
7163
+ return { success: false, error: message };
7164
+ }
7165
+ }
7166
+ // ============================================================
7167
+ // DEPOSITS & WITHDRAWALS
7168
+ // ============================================================
7169
+ /**
7170
+ * Deposit USDC into the prediction vault.
7171
+ * Returns the number of shares received.
7172
+ */
7173
+ async deposit(amount) {
7174
+ if (!this.vaultAddress) {
7175
+ return { success: false, error: "No vault exists" };
7176
+ }
7177
+ try {
7178
+ await this.approveIfNeeded(
7179
+ POLYGON_USDC_ADDRESS,
7180
+ this.vaultAddress,
7181
+ amount
7182
+ );
7183
+ const hash = await this.walletClient.writeContract({
7184
+ address: this.vaultAddress,
7185
+ abi: VAULT_ABI2,
7186
+ functionName: "deposit",
7187
+ args: [amount, this.account.address]
7188
+ });
7189
+ const receipt = await this.publicClient.waitForTransactionReceipt({ hash });
7190
+ const shares = await this.publicClient.readContract({
7191
+ address: this.vaultAddress,
7192
+ abi: VAULT_ABI2,
7193
+ functionName: "balanceOf",
7194
+ args: [this.account.address]
7195
+ });
7196
+ console.log(`Deposited ${(0, import_viem10.formatUnits)(amount, 6)} USDC into prediction vault`);
7197
+ return { success: true, shares, txHash: hash };
7198
+ } catch (error) {
7199
+ const message = error instanceof Error ? error.message : String(error);
7200
+ console.error("Vault deposit failed:", message);
7201
+ return { success: false, error: message };
7202
+ }
7203
+ }
7204
+ /**
7205
+ * Withdraw USDC from the prediction vault.
7206
+ * Redeems all shares and returns the USDC received (net of fees).
7207
+ */
7208
+ async withdrawAll() {
7209
+ if (!this.vaultAddress) {
7210
+ return { success: false, error: "No vault exists" };
7211
+ }
7212
+ try {
7213
+ const hash = await this.walletClient.writeContract({
7214
+ address: this.vaultAddress,
7215
+ abi: VAULT_ABI2,
7216
+ functionName: "redeemMax",
7217
+ args: [this.account.address, this.account.address]
7218
+ });
7219
+ const receipt = await this.publicClient.waitForTransactionReceipt({ hash });
7220
+ const balance = await this.publicClient.readContract({
7221
+ address: POLYGON_USDC_ADDRESS,
7222
+ abi: ERC20_ABI3,
7223
+ functionName: "balanceOf",
7224
+ args: [this.account.address]
7225
+ });
7226
+ console.log("Withdrew all shares from prediction vault");
7227
+ return { success: true, assets: balance, txHash: hash };
7228
+ } catch (error) {
7229
+ const message = error instanceof Error ? error.message : String(error);
7230
+ console.error("Vault withdrawal failed:", message);
7231
+ return { success: false, error: message };
7232
+ }
7233
+ }
7234
+ /**
7235
+ * Emergency withdraw with penalty.
7236
+ */
7237
+ async emergencyWithdraw() {
7238
+ if (!this.vaultAddress) {
7239
+ return { success: false, error: "No vault exists" };
7240
+ }
7241
+ try {
7242
+ const hash = await this.walletClient.writeContract({
7243
+ address: this.vaultAddress,
7244
+ abi: VAULT_ABI2,
7245
+ functionName: "emergencyWithdraw",
7246
+ args: []
7247
+ });
7248
+ await this.publicClient.waitForTransactionReceipt({ hash });
7249
+ console.log("Emergency withdrew from prediction vault (penalty applied)");
7250
+ return { success: true, txHash: hash };
7251
+ } catch (error) {
7252
+ const message = error instanceof Error ? error.message : String(error);
7253
+ return { success: false, error: message };
7254
+ }
7255
+ }
7256
+ // ============================================================
7257
+ // VAULT STATUS
7258
+ // ============================================================
7259
+ /**
7260
+ * Get comprehensive vault status.
7261
+ */
7262
+ async getVaultStatus() {
7263
+ if (!this.vaultAddress) {
7264
+ return {
7265
+ vaultAddress: "0x0000000000000000000000000000000000000000",
7266
+ hasVault: false,
7267
+ totalAssets: 0n,
7268
+ totalSupply: 0n,
7269
+ sharePrice: 0,
7270
+ usdcBalance: 0n,
7271
+ cachedCtfValue: 0n,
7272
+ currentExposureBps: 0,
7273
+ depositCap: 0n,
7274
+ seedAmount: 0n,
7275
+ circuitBreakerActive: false,
7276
+ isPaused: false,
7277
+ lastCtfUpdate: 0,
7278
+ pendingTradingVolume: 0n,
7279
+ trackedTokenCount: 0
7280
+ };
7281
+ }
7282
+ try {
7283
+ const [
7284
+ totalAssets,
7285
+ totalSupply,
7286
+ sharePrice,
7287
+ usdcBalance,
7288
+ cachedCtfValue,
7289
+ currentExposureBps,
7290
+ depositCap,
7291
+ seedAmount,
7292
+ circuitBreakerActive,
7293
+ isPaused,
7294
+ lastCtfUpdate,
7295
+ pendingTradingVolume,
7296
+ trackedTokenCount
7297
+ ] = await Promise.all([
7298
+ this.publicClient.readContract({ address: this.vaultAddress, abi: VAULT_ABI2, functionName: "totalAssets" }),
7299
+ this.publicClient.readContract({ address: this.vaultAddress, abi: VAULT_ABI2, functionName: "totalSupply" }),
7300
+ this.publicClient.readContract({ address: this.vaultAddress, abi: VAULT_ABI2, functionName: "sharePrice" }),
7301
+ this.publicClient.readContract({ address: POLYGON_USDC_ADDRESS, abi: ERC20_ABI3, functionName: "balanceOf", args: [this.vaultAddress] }),
7302
+ this.publicClient.readContract({ address: this.vaultAddress, abi: VAULT_ABI2, functionName: "cachedCtfValue" }),
7303
+ this.publicClient.readContract({ address: this.vaultAddress, abi: VAULT_ABI2, functionName: "currentExposureBps" }),
7304
+ this.publicClient.readContract({ address: this.vaultAddress, abi: VAULT_ABI2, functionName: "depositCap" }),
7305
+ this.publicClient.readContract({ address: this.vaultAddress, abi: VAULT_ABI2, functionName: "agentSeedAmount" }),
7306
+ this.publicClient.readContract({ address: this.vaultAddress, abi: VAULT_ABI2, functionName: "circuitBreakerActive" }),
7307
+ this.publicClient.readContract({ address: this.vaultAddress, abi: VAULT_ABI2, functionName: "paused" }),
7308
+ this.publicClient.readContract({ address: this.vaultAddress, abi: VAULT_ABI2, functionName: "lastCtfUpdate" }),
7309
+ this.publicClient.readContract({ address: this.vaultAddress, abi: VAULT_ABI2, functionName: "pendingTradingVolume" }),
7310
+ this.publicClient.readContract({ address: this.vaultAddress, abi: VAULT_ABI2, functionName: "getTrackedTokenCount" })
7311
+ ]);
7312
+ return {
7313
+ vaultAddress: this.vaultAddress,
7314
+ hasVault: true,
7315
+ totalAssets,
7316
+ totalSupply,
7317
+ sharePrice: Number(sharePrice) / 1e6,
7318
+ usdcBalance,
7319
+ cachedCtfValue,
7320
+ currentExposureBps: Number(currentExposureBps),
7321
+ depositCap,
7322
+ seedAmount,
7323
+ circuitBreakerActive,
7324
+ isPaused,
7325
+ lastCtfUpdate: Number(lastCtfUpdate),
7326
+ pendingTradingVolume,
7327
+ trackedTokenCount: Number(trackedTokenCount)
7328
+ };
7329
+ } catch (error) {
7330
+ const message = error instanceof Error ? error.message : String(error);
7331
+ console.error("Failed to read vault status:", message);
7332
+ return {
7333
+ vaultAddress: this.vaultAddress,
7334
+ hasVault: true,
7335
+ totalAssets: 0n,
7336
+ totalSupply: 0n,
7337
+ sharePrice: 0,
7338
+ usdcBalance: 0n,
7339
+ cachedCtfValue: 0n,
7340
+ currentExposureBps: 0,
7341
+ depositCap: 0n,
7342
+ seedAmount: 0n,
7343
+ circuitBreakerActive: false,
7344
+ isPaused: false,
7345
+ lastCtfUpdate: 0,
7346
+ pendingTradingVolume: 0n,
7347
+ trackedTokenCount: 0
7348
+ };
7349
+ }
7350
+ }
7351
+ // ============================================================
7352
+ // KEEPER: NAV UPDATES
7353
+ // ============================================================
7354
+ /**
7355
+ * Update cached CTF position values (keeper function).
7356
+ * Fetches CLOB midpoint prices for all tracked tokens and updates the vault.
7357
+ *
7358
+ * @param tokenIds - CTF token IDs
7359
+ * @param values - USD values in 6-decimal (midpoint price × balance for each token)
7360
+ */
7361
+ async updatePositionValues(tokenIds, values) {
7362
+ if (!this.vaultAddress) {
7363
+ return { success: false, error: "No vault exists" };
7364
+ }
7365
+ try {
7366
+ const hash = await this.walletClient.writeContract({
7367
+ address: this.vaultAddress,
7368
+ abi: VAULT_ABI2,
7369
+ functionName: "updatePositionValues",
7370
+ args: [tokenIds, values]
7371
+ });
7372
+ await this.publicClient.waitForTransactionReceipt({ hash });
7373
+ console.log(`Updated ${tokenIds.length} position values in prediction vault`);
7374
+ return { success: true, txHash: hash };
7375
+ } catch (error) {
7376
+ const message = error instanceof Error ? error.message : String(error);
7377
+ console.error("Failed to update position values:", message);
7378
+ return { success: false, error: message };
7379
+ }
7380
+ }
7381
+ /**
7382
+ * Collect trading fees based on reported volume (keeper function).
7383
+ * Transfers 0.2% of volume as fees to PredictionFeeCollector.
7384
+ *
7385
+ * @param volume - Trading volume to report (6-decimal USDC)
7386
+ */
7387
+ async collectTradingFees(volume) {
7388
+ if (!this.vaultAddress) {
7389
+ return { success: false, error: "No vault exists" };
7390
+ }
7391
+ try {
7392
+ const hash = await this.walletClient.writeContract({
7393
+ address: this.vaultAddress,
7394
+ abi: VAULT_ABI2,
7395
+ functionName: "collectTradingFees",
7396
+ args: [volume]
7397
+ });
7398
+ await this.publicClient.waitForTransactionReceipt({ hash });
7399
+ const feeAmount = volume * 20n / 10000n;
7400
+ console.log(`Collected trading fees: ${(0, import_viem10.formatUnits)(feeAmount, 6)} USDC from ${(0, import_viem10.formatUnits)(volume, 6)} USDC volume`);
7401
+ return { success: true, txHash: hash };
7402
+ } catch (error) {
7403
+ const message = error instanceof Error ? error.message : String(error);
7404
+ console.error("Failed to collect trading fees:", message);
7405
+ return { success: false, error: message };
7406
+ }
7407
+ }
7408
+ // ============================================================
7409
+ // KEEPER LOOPS
7410
+ // ============================================================
7411
+ /**
7412
+ * Start the keeper loops (NAV updates + fee collection).
7413
+ * These run on timers and automatically update vault state.
7414
+ *
7415
+ * @param getPositionValues - Callback that returns current CTF position values
7416
+ * (token IDs and their midpoint-price USD values)
7417
+ * @param getAccumulatedVolume - Callback that returns accumulated trading volume
7418
+ * since last fee collection
7419
+ */
7420
+ startKeeperLoops(getPositionValues, getAccumulatedVolume) {
7421
+ if (!this.vaultAddress) {
7422
+ console.log("Cannot start keeper loops \u2014 no vault exists");
7423
+ return;
7424
+ }
7425
+ const navInterval = this.config.navUpdateIntervalMs ?? 15 * 60 * 1e3;
7426
+ this.navTimer = setInterval(async () => {
7427
+ try {
7428
+ const { tokenIds, values } = await getPositionValues();
7429
+ if (tokenIds.length > 0) {
7430
+ await this.updatePositionValues(tokenIds, values);
7431
+ }
7432
+ } catch (error) {
7433
+ console.error("Keeper NAV update failed:", error instanceof Error ? error.message : error);
7434
+ }
7435
+ }, navInterval);
7436
+ const feeInterval = this.config.feeCollectionIntervalMs ?? 24 * 60 * 60 * 1e3;
7437
+ this.feeTimer = setInterval(async () => {
7438
+ try {
7439
+ const currentVolume = getAccumulatedVolume();
7440
+ const volumeDelta = currentVolume - this.lastReportedVolume;
7441
+ if (volumeDelta > 0n) {
7442
+ await this.collectTradingFees(volumeDelta);
7443
+ this.lastReportedVolume = currentVolume;
7444
+ }
7445
+ } catch (error) {
7446
+ console.error("Keeper fee collection failed:", error instanceof Error ? error.message : error);
7447
+ }
7448
+ }, feeInterval);
7449
+ console.log(`Keeper loops started (NAV: every ${navInterval / 6e4}min, fees: every ${feeInterval / 36e5}h)`);
7450
+ }
7451
+ /**
7452
+ * Stop keeper loops.
7453
+ */
7454
+ stopKeeperLoops() {
7455
+ if (this.navTimer) {
7456
+ clearInterval(this.navTimer);
7457
+ this.navTimer = null;
7458
+ }
7459
+ if (this.feeTimer) {
7460
+ clearInterval(this.feeTimer);
7461
+ this.feeTimer = null;
7462
+ }
7463
+ console.log("Keeper loops stopped");
7464
+ }
7465
+ // ============================================================
7466
+ // CLEANUP
7467
+ // ============================================================
7468
+ /**
7469
+ * Stop all timers and clean up.
7470
+ */
7471
+ stop() {
7472
+ this.stopKeeperLoops();
7473
+ }
7474
+ // ============================================================
7475
+ // PRIVATE HELPERS
7476
+ // ============================================================
7477
+ /** Approve USDC spend if needed (maxUint256 pattern) */
7478
+ async approveIfNeeded(token, spender, amount) {
7479
+ const allowance = await this.publicClient.readContract({
7480
+ address: token,
7481
+ abi: ERC20_ABI3,
7482
+ functionName: "allowance",
7483
+ args: [this.account.address, spender]
7484
+ });
7485
+ if (allowance < amount) {
7486
+ const maxUint256 = 2n ** 256n - 1n;
7487
+ const hash = await this.walletClient.writeContract({
7488
+ address: token,
7489
+ abi: ERC20_ABI3,
7490
+ functionName: "approve",
7491
+ args: [spender, maxUint256]
7492
+ });
7493
+ await this.publicClient.waitForTransactionReceipt({ hash });
7494
+ }
7495
+ }
7496
+ };
7497
+
7498
+ // src/secure-env.ts
7499
+ var crypto = __toESM(require("crypto"));
7500
+ var fs = __toESM(require("fs"));
7501
+ var path = __toESM(require("path"));
7502
+ var ALGORITHM = "aes-256-gcm";
7503
+ var PBKDF2_ITERATIONS = 1e5;
7504
+ var SALT_LENGTH = 32;
7505
+ var IV_LENGTH = 16;
7506
+ var KEY_LENGTH = 32;
7507
+ var SENSITIVE_PATTERNS = [
7508
+ /PRIVATE_KEY$/i,
7509
+ /_API_KEY$/i,
7510
+ /API_KEY$/i,
7511
+ /_SECRET$/i,
7512
+ /^OPENAI_API_KEY$/i,
7513
+ /^ANTHROPIC_API_KEY$/i,
7514
+ /^GOOGLE_AI_API_KEY$/i,
7515
+ /^DEEPSEEK_API_KEY$/i,
7516
+ /^MISTRAL_API_KEY$/i,
7517
+ /^GROQ_API_KEY$/i,
7518
+ /^TOGETHER_API_KEY$/i
7519
+ ];
7520
+ function isSensitiveKey(key) {
7521
+ return SENSITIVE_PATTERNS.some((pattern) => pattern.test(key));
7522
+ }
7523
+ function deriveKey(passphrase, salt) {
7524
+ return crypto.pbkdf2Sync(passphrase, salt, PBKDF2_ITERATIONS, KEY_LENGTH, "sha256");
7525
+ }
7526
+ function encryptValue(value, key) {
7527
+ const iv = crypto.randomBytes(IV_LENGTH);
7528
+ const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
7529
+ let encrypted = cipher.update(value, "utf8", "hex");
7530
+ encrypted += cipher.final("hex");
7531
+ const tag = cipher.getAuthTag();
7532
+ return {
7533
+ iv: iv.toString("hex"),
7534
+ encrypted,
7535
+ tag: tag.toString("hex")
7536
+ };
7537
+ }
7538
+ function decryptValue(encrypted, key, iv, tag) {
7539
+ const decipher = crypto.createDecipheriv(
7540
+ ALGORITHM,
7541
+ key,
7542
+ Buffer.from(iv, "hex")
7543
+ );
7544
+ decipher.setAuthTag(Buffer.from(tag, "hex"));
7545
+ let decrypted = decipher.update(encrypted, "hex", "utf8");
7546
+ decrypted += decipher.final("utf8");
7547
+ return decrypted;
7548
+ }
7549
+ function parseEnvFile(content) {
7550
+ const entries = [];
7551
+ for (const line of content.split("\n")) {
7552
+ const trimmed = line.trim();
7553
+ if (!trimmed || trimmed.startsWith("#")) continue;
7554
+ const eqIndex = trimmed.indexOf("=");
7555
+ if (eqIndex === -1) continue;
7556
+ const key = trimmed.slice(0, eqIndex).trim();
7557
+ let value = trimmed.slice(eqIndex + 1).trim();
7558
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
7559
+ value = value.slice(1, -1);
7560
+ }
7561
+ if (key && value) {
7562
+ entries.push({ key, value });
7563
+ }
7564
+ }
7565
+ return entries;
7566
+ }
7567
+ function encryptEnvFile(envPath, passphrase, deleteOriginal = false) {
7568
+ if (!fs.existsSync(envPath)) {
7569
+ throw new Error(`File not found: ${envPath}`);
7570
+ }
7571
+ const content = fs.readFileSync(envPath, "utf-8");
7572
+ const entries = parseEnvFile(content);
7573
+ if (entries.length === 0) {
7574
+ throw new Error("No environment variables found in file");
7575
+ }
7576
+ const salt = crypto.randomBytes(SALT_LENGTH);
7577
+ const key = deriveKey(passphrase, salt);
7578
+ const encryptedEntries = entries.map(({ key: envKey, value }) => {
7579
+ if (isSensitiveKey(envKey)) {
7580
+ const { iv, encrypted, tag } = encryptValue(value, key);
7581
+ return {
7582
+ key: envKey,
7583
+ value: encrypted,
7584
+ encrypted: true,
7585
+ iv,
7586
+ tag
7587
+ };
7588
+ }
7589
+ return {
7590
+ key: envKey,
7591
+ value,
7592
+ encrypted: false
7593
+ };
7594
+ });
7595
+ const encryptedEnv = {
7596
+ version: 1,
7597
+ salt: salt.toString("hex"),
7598
+ entries: encryptedEntries
7599
+ };
7600
+ const encPath = envPath + ".enc";
7601
+ fs.writeFileSync(encPath, JSON.stringify(encryptedEnv, null, 2), { mode: 384 });
7602
+ if (deleteOriginal) {
7603
+ fs.unlinkSync(envPath);
7604
+ }
7605
+ const sensitiveCount = encryptedEntries.filter((e) => e.encrypted).length;
7606
+ const plainCount = encryptedEntries.filter((e) => !e.encrypted).length;
7607
+ console.log(
7608
+ `Encrypted ${sensitiveCount} sensitive values (${plainCount} non-sensitive kept as plaintext)`
7609
+ );
7610
+ return encPath;
7611
+ }
7612
+ function decryptEnvFile(encPath, passphrase) {
7613
+ if (!fs.existsSync(encPath)) {
7614
+ throw new Error(`Encrypted env file not found: ${encPath}`);
7615
+ }
7616
+ const content = JSON.parse(fs.readFileSync(encPath, "utf-8"));
7617
+ if (content.version !== 1) {
7618
+ throw new Error(`Unsupported encrypted env version: ${content.version}`);
7619
+ }
7620
+ const salt = Buffer.from(content.salt, "hex");
7621
+ const key = deriveKey(passphrase, salt);
7622
+ const result = {};
7623
+ for (const entry of content.entries) {
7624
+ if (entry.encrypted) {
7625
+ if (!entry.iv || !entry.tag) {
7626
+ throw new Error(`Missing encryption metadata for ${entry.key}`);
7627
+ }
7628
+ try {
7629
+ result[entry.key] = decryptValue(entry.value, key, entry.iv, entry.tag);
7630
+ } catch {
7631
+ throw new Error(
7632
+ `Failed to decrypt ${entry.key}. Wrong passphrase or corrupted data.`
7633
+ );
7634
+ }
7635
+ } else {
7636
+ result[entry.key] = entry.value;
7637
+ }
7638
+ }
7639
+ return result;
7640
+ }
7641
+ function loadSecureEnv(basePath, passphrase) {
7642
+ const encPath = path.join(basePath, ".env.enc");
7643
+ const envPath = path.join(basePath, ".env");
7644
+ if (fs.existsSync(encPath)) {
7645
+ if (!passphrase) {
7646
+ passphrase = process.env.EXAGENT_PASSPHRASE;
7647
+ }
7648
+ if (!passphrase) {
7649
+ console.warn("");
7650
+ console.warn("WARNING: Found .env.enc but no passphrase provided.");
7651
+ console.warn(" Set EXAGENT_PASSPHRASE environment variable or");
7652
+ console.warn(" pass --passphrase when running the agent.");
7653
+ console.warn(" Falling back to plaintext .env file.");
7654
+ console.warn("");
7655
+ } else {
7656
+ const vars = decryptEnvFile(encPath, passphrase);
7657
+ for (const [key, value] of Object.entries(vars)) {
7658
+ process.env[key] = value;
7659
+ }
7660
+ return true;
7661
+ }
7662
+ }
7663
+ if (fs.existsSync(envPath)) {
7664
+ const content = fs.readFileSync(envPath, "utf-8");
7665
+ const entries = parseEnvFile(content);
7666
+ const sensitiveKeys = entries.filter(({ key }) => isSensitiveKey(key)).map(({ key }) => key);
7667
+ if (sensitiveKeys.length > 0) {
7668
+ console.warn("");
7669
+ console.warn("WARNING: Sensitive values stored in plaintext .env file:");
7670
+ for (const key of sensitiveKeys) {
7671
+ console.warn(` - ${key}`);
7672
+ }
7673
+ console.warn("");
7674
+ console.warn(' Run "npx @exagent/agent encrypt" to secure your keys.');
7675
+ console.warn("");
7676
+ }
7677
+ return false;
7678
+ }
7679
+ return false;
7680
+ }
7681
+
7682
+ // src/index.ts
7683
+ var AGENT_VERSION = "0.1.40";
7684
+
7685
+ // src/relay.ts
7686
+ var RelayClient = class {
7687
+ config;
7688
+ ws = null;
7689
+ authenticated = false;
7690
+ authRejected = false;
7691
+ reconnectAttempts = 0;
7692
+ maxReconnectAttempts = 50;
7693
+ reconnectTimer = null;
7694
+ heartbeatTimer = null;
7695
+ stopped = false;
7696
+ constructor(config) {
7697
+ this.config = config;
7698
+ }
7699
+ /**
7700
+ * Connect to the relay server
7701
+ */
7702
+ async connect() {
7703
+ if (this.stopped) return;
7704
+ const wsUrl = this.config.relay.apiUrl.replace(/^https?:\/\//, (m) => m.includes("https") ? "wss://" : "ws://").replace(/\/$/, "") + "/ws/agent";
7705
+ return new Promise((resolve, reject) => {
7706
+ try {
7707
+ this.ws = new import_ws2.default(wsUrl);
7708
+ } catch (error) {
7709
+ console.error("Relay: Failed to create WebSocket:", error);
7710
+ this.scheduleReconnect();
7711
+ reject(error);
7712
+ return;
7713
+ }
7714
+ const connectTimeout = setTimeout(() => {
7715
+ if (!this.authenticated) {
5864
7716
  console.error("Relay: Connection timeout");
5865
7717
  this.ws?.close();
5866
7718
  this.scheduleReconnect();
@@ -5921,10 +7773,10 @@ var RelayClient = class {
5921
7773
  * Authenticate with the relay server using wallet signature
5922
7774
  */
5923
7775
  async authenticate() {
5924
- const account = (0, import_accounts4.privateKeyToAccount)(this.config.privateKey);
7776
+ const account = (0, import_accounts7.privateKeyToAccount)(this.config.privateKey);
5925
7777
  const timestamp = Math.floor(Date.now() / 1e3);
5926
7778
  const message = `ExagentRelay:${this.config.agentId}:${timestamp}`;
5927
- const signature = await (0, import_accounts4.signMessage)({
7779
+ const signature = await (0, import_accounts7.signMessage)({
5928
7780
  message,
5929
7781
  privateKey: this.config.privateKey
5930
7782
  });
@@ -6153,6 +8005,30 @@ var AgentRuntime = class {
6153
8005
  cachedPerpMarginUsed = 0;
6154
8006
  cachedPerpLeverage = 0;
6155
8007
  cachedPerpOpenPositions = 0;
8008
+ // Prediction market components (null if prediction not enabled)
8009
+ predictionClient = null;
8010
+ predictionOrders = null;
8011
+ predictionPositions = null;
8012
+ predictionRecorder = null;
8013
+ predictionFunding = null;
8014
+ predictionBrowser = null;
8015
+ predictionStrategy = null;
8016
+ // Two-layer prediction control (mirrors perp pattern):
8017
+ // predictionConnected = Polymarket infrastructure initialized (CLOB client, recorder ready)
8018
+ // predictionTradingActive = Dedicated prediction trading cycle is mandated to run
8019
+ predictionConnected = false;
8020
+ predictionTradingActive = false;
8021
+ // Cached prediction data for synchronous heartbeat inclusion
8022
+ cachedPredictionPolygonUSDC = 0;
8023
+ cachedPredictionBaseUSDC = 0;
8024
+ cachedPredictionExposure = 0;
8025
+ cachedPredictionOpenMarkets = 0;
8026
+ cachedPredictionOpenPositions = 0;
8027
+ cachedPredictionUnrealizedPnl = 0;
8028
+ // Prediction vault manager (null if vault mode not enabled)
8029
+ predictionVaultManager = null;
8030
+ // Cached vault status for synchronous heartbeat
8031
+ cachedPredictionVaultStatus = void 0;
6156
8032
  constructor(config, options) {
6157
8033
  this.config = config;
6158
8034
  this.startInPaperMode = options?.paperMode ?? false;
@@ -6200,6 +8076,7 @@ var AgentRuntime = class {
6200
8076
  }
6201
8077
  await this.initializeVaultManager();
6202
8078
  await this.initializePerp();
8079
+ await this.initializePrediction();
6203
8080
  await this.initializeRelay();
6204
8081
  console.log("Agent initialized successfully");
6205
8082
  }
@@ -6289,10 +8166,10 @@ var AgentRuntime = class {
6289
8166
  };
6290
8167
  this.perpClient = new HyperliquidClient(config);
6291
8168
  const perpKey = perpConfig.perpRelayerKey || this.config.privateKey;
6292
- const account = (0, import_accounts5.privateKeyToAccount)(perpKey);
6293
- const walletClient = (0, import_viem7.createWalletClient)({
8169
+ const account = (0, import_accounts8.privateKeyToAccount)(perpKey);
8170
+ const walletClient = (0, import_viem11.createWalletClient)({
6294
8171
  chain: { id: 42161, name: "Arbitrum", nativeCurrency: { name: "ETH", symbol: "ETH", decimals: 18 }, rpcUrls: { default: { http: ["https://arb1.arbitrum.io/rpc"] } } },
6295
- transport: (0, import_viem7.http)("https://arb1.arbitrum.io/rpc", { timeout: 6e4 }),
8172
+ transport: (0, import_viem11.http)("https://arb1.arbitrum.io/rpc", { timeout: 6e4 }),
6296
8173
  account
6297
8174
  });
6298
8175
  this.perpSigner = new HyperliquidSigner(walletClient);
@@ -6368,6 +8245,101 @@ var AgentRuntime = class {
6368
8245
  console.warn("Perp trading will be disabled for this session");
6369
8246
  }
6370
8247
  }
8248
+ /**
8249
+ * Initialize Polymarket prediction market components.
8250
+ * Only initializes if prediction is enabled in config AND risk universe >= 2.
8251
+ */
8252
+ async initializePrediction() {
8253
+ const predictionConfig = this.config.prediction;
8254
+ if (!predictionConfig?.enabled) {
8255
+ console.log("Prediction markets: Disabled");
8256
+ return;
8257
+ }
8258
+ if (this.riskUniverse < 2) {
8259
+ console.warn(`Prediction markets: Blocked by risk universe ${this.riskUniverse} (need >= 2)`);
8260
+ return;
8261
+ }
8262
+ try {
8263
+ const config = {
8264
+ enabled: true,
8265
+ clobApiUrl: predictionConfig.clobApiUrl || "https://clob.polymarket.com",
8266
+ gammaApiUrl: predictionConfig.gammaApiUrl || "https://gamma-api.polymarket.com",
8267
+ polygonRpcUrl: predictionConfig.polygonRpcUrl || "https://polygon-rpc.com",
8268
+ maxNotionalUSD: predictionConfig.maxNotionalUSD ?? 500,
8269
+ maxTotalExposureUSD: predictionConfig.maxTotalExposureUSD ?? 5e3,
8270
+ polygonAllocationUSD: predictionConfig.polygonAllocationUSD ?? 100,
8271
+ allowedCategories: predictionConfig.allowedCategories,
8272
+ feeBridgeThresholdUSD: predictionConfig.feeBridgeThresholdUSD ?? 10
8273
+ };
8274
+ const vaultConfig = predictionConfig.vault;
8275
+ let vaultOpts;
8276
+ if (vaultConfig?.enabled && vaultConfig.factoryAddress) {
8277
+ this.predictionVaultManager = new PredictionVaultManager(
8278
+ this.config.privateKey,
8279
+ {
8280
+ enabled: true,
8281
+ factoryAddress: vaultConfig.factoryAddress,
8282
+ feeCollectorAddress: vaultConfig.feeCollectorAddress || "0x0000000000000000000000000000000000000000",
8283
+ polygonRpcUrl: predictionConfig.polygonRpcUrl || "https://polygon-rpc.com",
8284
+ vaultAddress: vaultConfig.vaultAddress,
8285
+ agentId: BigInt(this.config.agentId),
8286
+ feeRecipient: vaultConfig.feeRecipient || this.client.address,
8287
+ isVerified: vaultConfig.isVerified ?? false
8288
+ }
8289
+ );
8290
+ await this.predictionVaultManager.initialize();
8291
+ if (this.predictionVaultManager.hasVault) {
8292
+ const vaultAddr = this.predictionVaultManager.getVaultAddress();
8293
+ vaultOpts = { vaultMode: true, vaultAddress: vaultAddr };
8294
+ console.log(` Vault mode: ENABLED \u2014 vault ${vaultAddr}`);
8295
+ } else {
8296
+ console.log(" Vault mode: configured but no vault exists \u2014 create one via command center");
8297
+ }
8298
+ }
8299
+ this.predictionClient = new PolymarketClient(this.config.privateKey, config, vaultOpts);
8300
+ await this.predictionClient.initialize();
8301
+ this.predictionOrders = new PredictionOrderManager(this.predictionClient, config);
8302
+ this.predictionPositions = new PredictionPositionManager(this.predictionClient, config);
8303
+ this.predictionBrowser = new MarketBrowser(config);
8304
+ const recorderKey = predictionConfig.predictionRelayerKey || this.config.privateKey;
8305
+ this.predictionRecorder = new PredictionTradeRecorder({
8306
+ privateKey: recorderKey,
8307
+ rpcUrl: this.getRpcUrl(),
8308
+ agentId: BigInt(this.config.agentId),
8309
+ configHash: this.configHash
8310
+ });
8311
+ this.predictionFunding = new PredictionFunding({
8312
+ privateKey: this.config.privateKey,
8313
+ baseRpcUrl: this.getRpcUrl(),
8314
+ polygonRpcUrl: predictionConfig.polygonRpcUrl,
8315
+ ...vaultOpts?.vaultMode && vaultOpts?.vaultAddress && {
8316
+ polygonRecipient: vaultOpts.vaultAddress
8317
+ }
8318
+ });
8319
+ this.predictionConnected = true;
8320
+ console.log(`Polymarket: Connected`);
8321
+ console.log(` CLOB: ${config.clobApiUrl}`);
8322
+ console.log(` Max notional: $${config.maxNotionalUSD}, Max exposure: $${config.maxTotalExposureUSD}`);
8323
+ if (config.allowedCategories?.length) {
8324
+ console.log(` Categories: ${config.allowedCategories.join(", ")}`);
8325
+ }
8326
+ try {
8327
+ const polygonBalance = await this.predictionFunding.getPolygonUSDCBalance();
8328
+ const polygonUSDC = Number(polygonBalance) / 1e6;
8329
+ this.cachedPredictionPolygonUSDC = polygonUSDC;
8330
+ console.log(` Polygon USDC: $${polygonUSDC.toFixed(2)}`);
8331
+ if (polygonUSDC < 1) {
8332
+ console.warn(" No USDC on Polygon \u2014 bridge required before trading");
8333
+ }
8334
+ } catch {
8335
+ console.warn(" Could not check Polygon USDC balance");
8336
+ }
8337
+ } catch (error) {
8338
+ const message = error instanceof Error ? error.message : String(error);
8339
+ console.error(`Prediction initialization failed: ${message}`);
8340
+ console.warn("Prediction market trading will be disabled for this session");
8341
+ }
8342
+ }
6371
8343
  /**
6372
8344
  * Ensure the current wallet is linked to the agent.
6373
8345
  * If the trading wallet differs from the owner, enters a recovery loop
@@ -6532,9 +8504,9 @@ var AgentRuntime = class {
6532
8504
  const message = error instanceof Error ? error.message : String(error);
6533
8505
  if (message.includes("insufficient funds") || message.includes("intrinsic gas too low") || message.includes("exceeds the balance")) {
6534
8506
  const ccUrl = `https://exagent.io/agents/${encodeURIComponent(this.config.name)}/command-center`;
6535
- const publicClientInstance = (0, import_viem7.createPublicClient)({
6536
- chain: import_chains5.base,
6537
- transport: (0, import_viem7.http)(this.getRpcUrl(), { timeout: 6e4 })
8507
+ const publicClientInstance = (0, import_viem11.createPublicClient)({
8508
+ chain: import_chains8.base,
8509
+ transport: (0, import_viem11.http)(this.getRpcUrl(), { timeout: 6e4 })
6538
8510
  });
6539
8511
  console.log("");
6540
8512
  console.log("=== ETH NEEDED FOR GAS ===");
@@ -6902,6 +8874,224 @@ var AgentRuntime = class {
6902
8874
  }
6903
8875
  break;
6904
8876
  }
8877
+ case "enable_polymarket":
8878
+ if (this.predictionConnected) {
8879
+ this.relay?.sendCommandResult(cmd.id, true, "Polymarket already connected");
8880
+ break;
8881
+ }
8882
+ if (!this.config.prediction?.enabled) {
8883
+ this.relay?.sendCommandResult(cmd.id, false, "Prediction trading not configured in agent config");
8884
+ break;
8885
+ }
8886
+ if (this.riskUniverse < 2) {
8887
+ this.relay?.sendCommandResult(cmd.id, false, `Risk universe ${this.riskUniverse} too low (need >= 2)`);
8888
+ break;
8889
+ }
8890
+ try {
8891
+ await this.initializePrediction();
8892
+ if (this.predictionConnected) {
8893
+ this.relay?.sendCommandResult(cmd.id, true, "Polymarket connected");
8894
+ this.relay?.sendMessage(
8895
+ "system",
8896
+ "success",
8897
+ "Polymarket Enabled",
8898
+ 'Polymarket infrastructure connected. Use "Start Prediction Trading" to begin a dedicated prediction cycle.'
8899
+ );
8900
+ } else {
8901
+ this.relay?.sendCommandResult(cmd.id, false, "Failed to connect to Polymarket");
8902
+ }
8903
+ } catch (error) {
8904
+ const msg = error instanceof Error ? error.message : String(error);
8905
+ this.relay?.sendCommandResult(cmd.id, false, `Polymarket init failed: ${msg}`);
8906
+ }
8907
+ this.sendRelayStatus();
8908
+ break;
8909
+ case "disable_polymarket":
8910
+ if (!this.predictionConnected) {
8911
+ this.relay?.sendCommandResult(cmd.id, true, "Polymarket already disconnected");
8912
+ break;
8913
+ }
8914
+ this.predictionTradingActive = false;
8915
+ this.predictionConnected = false;
8916
+ this.predictionClient = null;
8917
+ this.predictionOrders = null;
8918
+ this.predictionPositions = null;
8919
+ this.predictionRecorder = null;
8920
+ this.predictionFunding = null;
8921
+ this.predictionBrowser = null;
8922
+ console.log("Polymarket disabled via command center");
8923
+ this.relay?.sendCommandResult(cmd.id, true, "Polymarket disconnected");
8924
+ this.relay?.sendMessage(
8925
+ "system",
8926
+ "info",
8927
+ "Polymarket Disabled",
8928
+ "Polymarket infrastructure disconnected."
8929
+ );
8930
+ this.sendRelayStatus();
8931
+ break;
8932
+ case "start_prediction_trading":
8933
+ if (!this.predictionConnected) {
8934
+ this.relay?.sendCommandResult(cmd.id, false, "Polymarket not connected. Enable Polymarket first.");
8935
+ break;
8936
+ }
8937
+ if (this.predictionTradingActive) {
8938
+ this.relay?.sendCommandResult(cmd.id, true, "Prediction trading already active");
8939
+ break;
8940
+ }
8941
+ this.predictionTradingActive = true;
8942
+ if (this.mode !== "trading") {
8943
+ this.mode = "trading";
8944
+ this.isRunning = true;
8945
+ }
8946
+ console.log("Prediction trading mandated via command center");
8947
+ this.relay?.sendCommandResult(cmd.id, true, "Prediction trading cycle active");
8948
+ this.relay?.sendMessage(
8949
+ "system",
8950
+ "success",
8951
+ "Prediction Trading Active",
8952
+ "Dedicated prediction trading cycle is now running every interval."
8953
+ );
8954
+ this.sendRelayStatus();
8955
+ break;
8956
+ case "stop_prediction_trading":
8957
+ if (!this.predictionTradingActive) {
8958
+ this.relay?.sendCommandResult(cmd.id, true, "Prediction trading already stopped");
8959
+ break;
8960
+ }
8961
+ this.predictionTradingActive = false;
8962
+ console.log("Prediction trading cycle stopped via command center");
8963
+ this.relay?.sendCommandResult(cmd.id, true, "Prediction trading cycle stopped");
8964
+ this.relay?.sendMessage(
8965
+ "system",
8966
+ "info",
8967
+ "Prediction Trading Stopped",
8968
+ "Dedicated prediction cycle stopped. Polymarket remains connected."
8969
+ );
8970
+ this.sendRelayStatus();
8971
+ break;
8972
+ case "update_prediction_params": {
8973
+ const predParams = cmd.params || {};
8974
+ let predUpdated = false;
8975
+ if (this.config.prediction && predParams.maxNotionalUSD !== void 0) {
8976
+ const val = Number(predParams.maxNotionalUSD);
8977
+ if (val >= 1) {
8978
+ this.config.prediction.maxNotionalUSD = val;
8979
+ predUpdated = true;
8980
+ }
8981
+ }
8982
+ if (this.config.prediction && predParams.maxTotalExposureUSD !== void 0) {
8983
+ const val = Number(predParams.maxTotalExposureUSD);
8984
+ if (val >= 1) {
8985
+ this.config.prediction.maxTotalExposureUSD = val;
8986
+ predUpdated = true;
8987
+ }
8988
+ }
8989
+ if (predUpdated) {
8990
+ this.relay?.sendCommandResult(cmd.id, true, "Prediction parameters updated");
8991
+ this.relay?.sendMessage(
8992
+ "config_updated",
8993
+ "info",
8994
+ "Prediction Params Updated",
8995
+ `Max notional: $${this.config.prediction?.maxNotionalUSD}, Max exposure: $${this.config.prediction?.maxTotalExposureUSD}`
8996
+ );
8997
+ } else {
8998
+ this.relay?.sendCommandResult(cmd.id, false, "No valid prediction parameters provided");
8999
+ }
9000
+ break;
9001
+ }
9002
+ case "create_prediction_vault": {
9003
+ if (!this.predictionVaultManager) {
9004
+ this.relay?.sendCommandResult(cmd.id, false, "Vault mode not configured. Set prediction.vault config.");
9005
+ break;
9006
+ }
9007
+ if (this.predictionVaultManager.hasVault) {
9008
+ const addr = this.predictionVaultManager.getVaultAddress();
9009
+ this.relay?.sendCommandResult(cmd.id, true, `Vault already exists: ${addr}`);
9010
+ break;
9011
+ }
9012
+ try {
9013
+ const vaultParams = cmd.params || {};
9014
+ const seedAmount = BigInt(Number(vaultParams.seedAmount || 100) * 1e6);
9015
+ const name = vaultParams.name || `Prediction Fund ${this.config.agentId}`;
9016
+ const symbol = vaultParams.symbol || `pxAGT${this.config.agentId}`;
9017
+ const result = await this.predictionVaultManager.createVault(seedAmount, name, symbol);
9018
+ if (result.success) {
9019
+ this.relay?.sendCommandResult(cmd.id, true, `Vault created: ${result.vaultAddress}`);
9020
+ this.relay?.sendMessage(
9021
+ "prediction_vault_created",
9022
+ "success",
9023
+ "Prediction Vault Created",
9024
+ `Vault deployed at ${result.vaultAddress} with ${Number(seedAmount) / 1e6} USDC seed`,
9025
+ { vaultAddress: result.vaultAddress, txHash: result.txHash }
9026
+ );
9027
+ } else {
9028
+ this.relay?.sendCommandResult(cmd.id, false, result.error || "Vault creation failed");
9029
+ }
9030
+ } catch (error) {
9031
+ const msg = error instanceof Error ? error.message : String(error);
9032
+ this.relay?.sendCommandResult(cmd.id, false, `Vault creation failed: ${msg}`);
9033
+ }
9034
+ this.sendRelayStatus();
9035
+ break;
9036
+ }
9037
+ case "deposit_prediction_vault": {
9038
+ if (!this.predictionVaultManager?.hasVault) {
9039
+ this.relay?.sendCommandResult(cmd.id, false, "No prediction vault exists");
9040
+ break;
9041
+ }
9042
+ try {
9043
+ const amount = BigInt(Number(cmd.params?.amount || 0) * 1e6);
9044
+ if (amount <= 0n) {
9045
+ this.relay?.sendCommandResult(cmd.id, false, "Amount must be positive");
9046
+ break;
9047
+ }
9048
+ const result = await this.predictionVaultManager.deposit(amount);
9049
+ if (result.success) {
9050
+ this.relay?.sendCommandResult(cmd.id, true, `Deposited ${Number(amount) / 1e6} USDC`);
9051
+ this.relay?.sendMessage(
9052
+ "prediction_vault_deposit",
9053
+ "success",
9054
+ "Vault Deposit",
9055
+ `${Number(amount) / 1e6} USDC deposited into prediction vault`,
9056
+ { amount: Number(amount) / 1e6, txHash: result.txHash }
9057
+ );
9058
+ } else {
9059
+ this.relay?.sendCommandResult(cmd.id, false, result.error || "Deposit failed");
9060
+ }
9061
+ } catch (error) {
9062
+ const msg = error instanceof Error ? error.message : String(error);
9063
+ this.relay?.sendCommandResult(cmd.id, false, `Deposit failed: ${msg}`);
9064
+ }
9065
+ this.sendRelayStatus();
9066
+ break;
9067
+ }
9068
+ case "withdraw_prediction_vault": {
9069
+ if (!this.predictionVaultManager?.hasVault) {
9070
+ this.relay?.sendCommandResult(cmd.id, false, "No prediction vault exists");
9071
+ break;
9072
+ }
9073
+ try {
9074
+ const isEmergency = cmd.params?.emergency === true;
9075
+ const result = isEmergency ? await this.predictionVaultManager.emergencyWithdraw() : await this.predictionVaultManager.withdrawAll();
9076
+ if (result.success) {
9077
+ this.relay?.sendCommandResult(cmd.id, true, isEmergency ? "Emergency withdrawn (penalty applied)" : "Withdrawn all shares");
9078
+ this.relay?.sendMessage(
9079
+ "prediction_vault_withdraw",
9080
+ isEmergency ? "warning" : "success",
9081
+ isEmergency ? "Emergency Withdrawal" : "Vault Withdrawal",
9082
+ isEmergency ? "Emergency withdrawn with penalty" : "All shares redeemed from prediction vault",
9083
+ { emergency: isEmergency, txHash: result.txHash }
9084
+ );
9085
+ } else {
9086
+ this.relay?.sendCommandResult(cmd.id, false, result.error || "Withdrawal failed");
9087
+ }
9088
+ } catch (error) {
9089
+ const msg = error instanceof Error ? error.message : String(error);
9090
+ this.relay?.sendCommandResult(cmd.id, false, `Withdrawal failed: ${msg}`);
9091
+ }
9092
+ this.sendRelayStatus();
9093
+ break;
9094
+ }
6905
9095
  case "start_paper_trading":
6906
9096
  if (this.mode === "paper") {
6907
9097
  this.relay?.sendCommandResult(cmd.id, true, "Already paper trading");
@@ -7029,7 +9219,7 @@ var AgentRuntime = class {
7029
9219
  try {
7030
9220
  const onChain = await this.client.registry.getConfigHash(BigInt(this.config.agentId));
7031
9221
  if (onChain === this.pendingConfigHash) {
7032
- this.configHash = this.pendingConfigHash;
9222
+ this.updateConfigHashEverywhere(this.pendingConfigHash);
7033
9223
  this.pendingConfigHash = null;
7034
9224
  console.log("Config verified on-chain! Your agent will now appear on the leaderboard.");
7035
9225
  this.relay?.sendMessage(
@@ -7042,6 +9232,34 @@ var AgentRuntime = class {
7042
9232
  } catch {
7043
9233
  }
7044
9234
  }
9235
+ /**
9236
+ * Periodically sync config hash from on-chain to detect external changes.
9237
+ * This catches cases where the config was changed via the website or another
9238
+ * session while this agent is running. Without this, all trades and recordings
9239
+ * fail with ConfigMismatch until the agent is restarted.
9240
+ *
9241
+ * Called from sendRelayStatus at most every 5 minutes (timestamp-throttled).
9242
+ */
9243
+ lastConfigSyncAt = 0;
9244
+ async syncConfigHashFromChain() {
9245
+ try {
9246
+ const onChain = await this.client.registry.getConfigHash(BigInt(this.config.agentId));
9247
+ if (onChain && onChain !== this.configHash && onChain !== "0x0000000000000000000000000000000000000000000000000000000000000000") {
9248
+ console.log(`Config hash changed on-chain (external update detected): ${this.configHash} \u2192 ${onChain}`);
9249
+ this.updateConfigHashEverywhere(onChain);
9250
+ }
9251
+ } catch {
9252
+ }
9253
+ }
9254
+ /**
9255
+ * Propagate a config hash update to runtime + all consumers (recorders).
9256
+ * Ensures executor, perp recorder, and prediction recorder all stay in sync.
9257
+ */
9258
+ updateConfigHashEverywhere(newHash) {
9259
+ this.configHash = newHash;
9260
+ this.perpRecorder?.updateConfigHash(newHash);
9261
+ this.predictionRecorder?.updateConfigHash(newHash);
9262
+ }
7045
9263
  /**
7046
9264
  * Send current status to the relay
7047
9265
  */
@@ -7052,6 +9270,11 @@ var AgentRuntime = class {
7052
9270
  this.lastConfigCheckAt = Date.now();
7053
9271
  this.checkPendingConfigApproval();
7054
9272
  }
9273
+ const CONFIG_SYNC_INTERVAL_MS = 3e5;
9274
+ if (!this.pendingConfigHash && Date.now() - this.lastConfigSyncAt >= CONFIG_SYNC_INTERVAL_MS) {
9275
+ this.lastConfigSyncAt = Date.now();
9276
+ this.syncConfigHashFromChain();
9277
+ }
7055
9278
  const vaultConfig = this.config.vault || { policy: "disabled" };
7056
9279
  const status = {
7057
9280
  mode: this.mode,
@@ -7089,6 +9312,19 @@ var AgentRuntime = class {
7089
9312
  effectiveLeverage: this.cachedPerpLeverage,
7090
9313
  pendingRecords: this.perpRecorder?.pendingRetries ?? 0
7091
9314
  } : void 0,
9315
+ prediction: this.predictionConnected ? {
9316
+ enabled: true,
9317
+ trading: this.predictionTradingActive,
9318
+ polygonUSDC: this.cachedPredictionPolygonUSDC,
9319
+ baseUSDC: this.cachedPredictionBaseUSDC,
9320
+ totalExposure: this.cachedPredictionExposure,
9321
+ openMarkets: this.cachedPredictionOpenMarkets,
9322
+ openPositions: this.cachedPredictionOpenPositions,
9323
+ unrealizedPnl: this.cachedPredictionUnrealizedPnl,
9324
+ pendingFees: this.predictionRecorder?.pendingFeesUSD ?? 0,
9325
+ pendingRecords: this.predictionRecorder?.pendingRetries ?? 0,
9326
+ vault: this.cachedPredictionVaultStatus
9327
+ } : void 0,
7092
9328
  positions: this.positionTracker ? this.positionTracker.getPositionSummary(this.lastPrices) : void 0,
7093
9329
  paper: this.mode === "paper" && this.paperPortfolio ? (() => {
7094
9330
  const summary = this.paperPortfolio.getSummary(this.lastPrices);
@@ -7131,6 +9367,39 @@ var AgentRuntime = class {
7131
9367
  }).catch(() => {
7132
9368
  });
7133
9369
  }
9370
+ if (this.predictionConnected && this.predictionPositions && this.predictionFunding) {
9371
+ this.predictionPositions.getAccountSummary().then((summary) => {
9372
+ this.cachedPredictionExposure = summary.totalExposure;
9373
+ this.cachedPredictionOpenMarkets = summary.openMarketCount;
9374
+ this.cachedPredictionOpenPositions = summary.openPositionCount;
9375
+ this.cachedPredictionUnrealizedPnl = summary.totalUnrealizedPnl;
9376
+ }).catch(() => {
9377
+ });
9378
+ this.predictionFunding.getPolygonUSDCBalance().then((bal) => {
9379
+ this.cachedPredictionPolygonUSDC = Number(bal) / 1e6;
9380
+ }).catch(() => {
9381
+ });
9382
+ this.predictionFunding.getBaseUSDCBalance().then((bal) => {
9383
+ this.cachedPredictionBaseUSDC = Number(bal) / 1e6;
9384
+ }).catch(() => {
9385
+ });
9386
+ if (this.predictionVaultManager?.hasVault) {
9387
+ this.predictionVaultManager.getVaultStatus().then((vs) => {
9388
+ if (vs.hasVault) {
9389
+ this.cachedPredictionVaultStatus = {
9390
+ address: vs.vaultAddress,
9391
+ totalAssets: Number(vs.totalAssets) / 1e6,
9392
+ sharePrice: vs.sharePrice,
9393
+ cachedCtfValue: Number(vs.cachedCtfValue) / 1e6,
9394
+ currentExposureBps: vs.currentExposureBps,
9395
+ circuitBreakerActive: vs.circuitBreakerActive,
9396
+ isPaused: vs.isPaused
9397
+ };
9398
+ }
9399
+ }).catch(() => {
9400
+ });
9401
+ }
9402
+ }
7134
9403
  }
7135
9404
  /**
7136
9405
  * Run a single trading cycle
@@ -7328,6 +9597,15 @@ var AgentRuntime = class {
7328
9597
  this.relay?.sendMessage("system", "error", "Perp Cycle Error", message);
7329
9598
  }
7330
9599
  }
9600
+ if (!isPaper && this.predictionConnected && this.predictionTradingActive) {
9601
+ try {
9602
+ await this.runPredictionCycle();
9603
+ } catch (error) {
9604
+ const message = error instanceof Error ? error.message : String(error);
9605
+ console.error("Error in prediction cycle:", message);
9606
+ this.relay?.sendMessage("system", "error", "Prediction Cycle Error", message);
9607
+ }
9608
+ }
7331
9609
  this.sendRelayStatus();
7332
9610
  }
7333
9611
  /**
@@ -7388,6 +9666,101 @@ var AgentRuntime = class {
7388
9666
  }
7389
9667
  }
7390
9668
  }
9669
+ /**
9670
+ * Run a single prediction market trading cycle.
9671
+ * Fetches active markets, positions, calls prediction strategy, executes signals.
9672
+ * Fills are recorded on Base via Router.recordPerpTrade() with POLY: prefix.
9673
+ */
9674
+ async runPredictionCycle() {
9675
+ if (!this.predictionClient || !this.predictionOrders || !this.predictionPositions || !this.predictionRecorder || !this.predictionBrowser || !this.predictionConnected) return;
9676
+ const predictionConfig = this.config.prediction;
9677
+ if (!predictionConfig?.enabled) return;
9678
+ console.log(" [POLY] Running prediction cycle...");
9679
+ try {
9680
+ const newFills = await this.predictionOrders.pollNewFills();
9681
+ if (newFills.length > 0) {
9682
+ console.log(` [POLY] ${newFills.length} new fill(s) detected`);
9683
+ for (const fill of newFills) {
9684
+ this.predictionPositions.processFill(fill);
9685
+ const result = await this.predictionRecorder.recordFill(fill);
9686
+ if (result.success) {
9687
+ this.relay?.sendMessage(
9688
+ "prediction_fill",
9689
+ "success",
9690
+ "Prediction Fill",
9691
+ `${fill.side} ${fill.size} @ $${parseFloat(fill.price).toFixed(2)} \u2014 market ${fill.marketConditionId.slice(0, 12)}...`,
9692
+ { tradeId: fill.tradeId, side: fill.side, size: fill.size, price: fill.price, txHash: result.txHash }
9693
+ );
9694
+ }
9695
+ }
9696
+ }
9697
+ } catch (error) {
9698
+ const message = error instanceof Error ? error.message : String(error);
9699
+ console.warn(" [POLY] Fill polling failed:", message);
9700
+ }
9701
+ const account = await this.predictionPositions.getAccountSummary();
9702
+ const positions = await this.predictionPositions.getPositions();
9703
+ console.log(` [POLY] Polygon USDC: $${account.polygonUSDC.toFixed(2)}, Positions: ${positions.length}, Exposure: $${account.totalExposure.toFixed(2)}`);
9704
+ if (!this.predictionStrategy) {
9705
+ return;
9706
+ }
9707
+ let markets;
9708
+ try {
9709
+ const category = predictionConfig.allowedCategories?.[0];
9710
+ markets = await this.predictionBrowser.getActiveMarkets({
9711
+ limit: 50,
9712
+ category
9713
+ });
9714
+ } catch (error) {
9715
+ const message = error instanceof Error ? error.message : String(error);
9716
+ console.error(" [POLY] Market fetch error:", message);
9717
+ return;
9718
+ }
9719
+ let signals;
9720
+ try {
9721
+ signals = await this.predictionStrategy(
9722
+ markets,
9723
+ positions,
9724
+ account,
9725
+ this.llm,
9726
+ this.config
9727
+ );
9728
+ } catch (error) {
9729
+ const message = error instanceof Error ? error.message : String(error);
9730
+ console.error(" [POLY] Strategy error:", message);
9731
+ return;
9732
+ }
9733
+ console.log(` [POLY] Strategy generated ${signals.length} signals`);
9734
+ for (const signal of signals) {
9735
+ if (signal.action === "hold") continue;
9736
+ const result = await this.predictionOrders.executeSignal(signal);
9737
+ if (result.success) {
9738
+ console.log(` [POLY] Order placed: ${signal.action} "${signal.marketQuestion.slice(0, 50)}..." \u2014 ${result.status}`);
9739
+ } else {
9740
+ console.warn(` [POLY] Order failed: ${signal.action} \u2014 ${result.error}`);
9741
+ }
9742
+ }
9743
+ const pendingFees = this.predictionRecorder.pendingFeesUSD;
9744
+ const threshold = predictionConfig.feeBridgeThresholdUSD ?? 10;
9745
+ if (pendingFees >= threshold && this.predictionFunding) {
9746
+ console.log(` [POLY] Bridging $${pendingFees.toFixed(2)} in accumulated fees to Base...`);
9747
+ const feeAmount = BigInt(Math.floor(pendingFees * 1e6));
9748
+ try {
9749
+ const bridgeResult = await this.predictionFunding.withdrawToBase(feeAmount, (step) => {
9750
+ console.log(` [POLY] Fee bridge: ${step}`);
9751
+ });
9752
+ if (bridgeResult.success) {
9753
+ this.predictionRecorder.resetAccumulatedFees();
9754
+ console.log(` [POLY] Fee bridge complete: $${pendingFees.toFixed(2)} \u2192 Base`);
9755
+ } else {
9756
+ console.warn(` [POLY] Fee bridge failed: ${bridgeResult.error}`);
9757
+ }
9758
+ } catch (error) {
9759
+ const message = error instanceof Error ? error.message : String(error);
9760
+ console.warn(` [POLY] Fee bridge error: ${message}`);
9761
+ }
9762
+ }
9763
+ }
7391
9764
  /**
7392
9765
  * Check if ETH balance is below threshold and notify.
7393
9766
  * Returns true if trading should continue, false if ETH is critically low.
@@ -7439,6 +9812,14 @@ var AgentRuntime = class {
7439
9812
  if (this.perpRecorder) {
7440
9813
  this.perpRecorder.stop();
7441
9814
  }
9815
+ this.predictionConnected = false;
9816
+ this.predictionTradingActive = false;
9817
+ if (this.predictionVaultManager) {
9818
+ this.predictionVaultManager.stop();
9819
+ }
9820
+ if (this.predictionRecorder) {
9821
+ this.predictionRecorder.stop();
9822
+ }
7442
9823
  if (this.relay) {
7443
9824
  this.relay.disconnect();
7444
9825
  }
@@ -7456,8 +9837,8 @@ var AgentRuntime = class {
7456
9837
  * for Frontier agents trading outside the whitelist) stay visible.
7457
9838
  */
7458
9839
  getTokensToTrack() {
7459
- const base6 = this.config.allowedTokens || this.getDefaultTokens();
7460
- const baseSet = new Set(base6.map((t) => t.toLowerCase()));
9840
+ const base8 = this.config.allowedTokens || this.getDefaultTokens();
9841
+ const baseSet = new Set(base8.map((t) => t.toLowerCase()));
7461
9842
  const trackedPositions = this.positionTracker.getPositions();
7462
9843
  const extras = [];
7463
9844
  for (const pos of trackedPositions) {
@@ -7480,7 +9861,7 @@ var AgentRuntime = class {
7480
9861
  console.log(`Auto-tracking ${extras.length} additional token(s) from position history`);
7481
9862
  }
7482
9863
  const resolver = this.marketData.getResolver();
7483
- const allTokens = [...base6, ...extras];
9864
+ const allTokens = [...base8, ...extras];
7484
9865
  const filtered = allTokens.filter((t) => !resolver.isUnresolvable(t.toLowerCase()));
7485
9866
  const dropped = allTokens.length - filtered.length;
7486
9867
  if (dropped > 0) {
@@ -7633,7 +10014,7 @@ var AgentRuntime = class {
7633
10014
  };
7634
10015
 
7635
10016
  // src/cli.ts
7636
- var import_accounts6 = require("viem/accounts");
10017
+ var import_accounts9 = require("viem/accounts");
7637
10018
  (0, import_dotenv2.config)();
7638
10019
  var program = new import_commander.Command();
7639
10020
  program.name("exagent").description("Exagent autonomous trading agent").version("0.1.0");
@@ -7741,8 +10122,8 @@ async function checkFirstRunSetup(configPath) {
7741
10122
  console.log("");
7742
10123
  console.log("[WALLET] Generating a new wallet for your agent...");
7743
10124
  console.log("");
7744
- const generatedKey = (0, import_accounts6.generatePrivateKey)();
7745
- const account = (0, import_accounts6.privateKeyToAccount)(generatedKey);
10125
+ const generatedKey = (0, import_accounts9.generatePrivateKey)();
10126
+ const account = (0, import_accounts9.privateKeyToAccount)(generatedKey);
7746
10127
  privateKey = generatedKey;
7747
10128
  walletAddress = account.address;
7748
10129
  console.log(" New wallet created!");
@@ -7773,7 +10154,7 @@ async function checkFirstRunSetup(configPath) {
7773
10154
  process.exit(1);
7774
10155
  }
7775
10156
  try {
7776
- const account = (0, import_accounts6.privateKeyToAccount)(privateKey);
10157
+ const account = (0, import_accounts9.privateKeyToAccount)(privateKey);
7777
10158
  walletAddress = account.address;
7778
10159
  console.log("");
7779
10160
  console.log(` Wallet address: ${walletAddress}`);
@@ -8268,8 +10649,8 @@ program.command("export-key").description("Display your trading wallet private k
8268
10649
  console.error("");
8269
10650
  process.exit(1);
8270
10651
  }
8271
- const { privateKeyToAccount: privateKeyToAccount7 } = await import("viem/accounts");
8272
- const account = privateKeyToAccount7(privateKey);
10652
+ const { privateKeyToAccount: privateKeyToAccount10 } = await import("viem/accounts");
10653
+ const account = privateKeyToAccount10(privateKey);
8273
10654
  console.log("");
8274
10655
  console.log("=".repeat(60));
8275
10656
  console.log(" WALLET PRIVATE KEY EXPORT");