investing 0.1.310 → 0.1.312
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +123 -167
- package/dist/{archiver-web.es-C5dgnXMM.js → archiver-web.es-B69gABHP.js} +1 -1
- package/dist/{archiver-web.es-DLoy_R54.cjs → archiver-web.es-fg4bLLZa.cjs} +1 -1
- package/dist/bookmakerAnalysis-Bfo1zUVm.js +1 -0
- package/dist/bookmakerAnalysis-CHn1W8uX.cjs +1 -0
- package/dist/callGrok-D0D7zBHK.js +1 -0
- package/dist/callGrok-DWO719mN.cjs +1 -0
- package/dist/db/index.d.ts +0 -189
- package/dist/db/index.d.ts.map +1 -1
- package/dist/db/schema.d.ts +0 -200
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/events-BJOyGWeU.cjs +1 -0
- package/dist/events-OvBb8rgy.js +1 -0
- package/dist/index-D7fsk2gy.js +15 -0
- package/dist/index-_V1Ql5Es.cjs +13 -0
- package/dist/index.d.ts +1 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/leaders/zulu.d.ts +5 -35
- package/dist/leaders/zulu.d.ts.map +1 -1
- package/dist/live-data/dukascopy-client.d.ts +2 -19
- package/dist/live-data/dukascopy-client.d.ts.map +1 -1
- package/dist/llm/debate-generator.d.ts +0 -7
- package/dist/llm/debate-generator.d.ts.map +1 -1
- package/dist/polymarket-updown-15-limit-order-bot-DCC8HE9Z.cjs +1 -0
- package/dist/polymarket-updown-15-limit-order-bot-Dv5oGAF4.js +1 -0
- package/dist/prediction/api/analytics.d.ts.map +1 -1
- package/dist/prediction/api/leaderboard.d.ts +11 -29
- package/dist/prediction/api/leaderboard.d.ts.map +1 -1
- package/dist/prediction/api/markets.d.ts.map +1 -1
- package/dist/prediction/api/prices.d.ts.map +1 -1
- package/dist/prediction/db/markets.d.ts +0 -13
- package/dist/prediction/db/markets.d.ts.map +1 -1
- package/dist/prediction/db/trade-history.d.ts +0 -35
- package/dist/prediction/db/trade-history.d.ts.map +1 -1
- package/dist/prediction/index.d.ts +0 -7
- package/dist/prediction/index.d.ts.map +1 -1
- package/dist/prediction/sync/incremental-markets.d.ts.map +1 -1
- package/dist/prediction/sync/leaderboard.d.ts +1 -1
- package/dist/prediction/sync/leaderboard.d.ts.map +1 -1
- package/dist/prediction/sync/markets.d.ts +2 -2
- package/dist/prediction/sync/markets.d.ts.map +1 -1
- package/dist/prediction/sync/orchestration.d.ts +1 -1
- package/dist/prediction/sync/trade-history.d.ts.map +1 -1
- package/dist/predictos/agents/bookmaker-agent.d.ts.map +1 -0
- package/dist/predictos/agents/event-analysis-agent.d.ts.map +1 -0
- package/dist/{prediction-markets → predictos}/agents/index.d.ts +1 -5
- package/dist/predictos/agents/index.d.ts.map +1 -0
- package/dist/predictos/agents/index.js +1 -0
- package/dist/predictos/agents/index.mjs +1 -0
- package/dist/predictos/agents/mapper-agent.d.ts.map +1 -0
- package/dist/{prediction-markets → predictos}/agents/polyfactual-research.d.ts +1 -1
- package/dist/predictos/agents/polyfactual-research.d.ts.map +1 -0
- package/dist/predictos/agents/polymarket-position-tracker.d.ts.map +1 -0
- package/dist/{prediction-markets → predictos}/agents/polymarket-put-order.d.ts +1 -1
- package/dist/predictos/agents/polymarket-put-order.d.ts.map +1 -0
- package/dist/predictos/agents/polymarket-updown-15-limit-order-bot.d.ts.map +1 -0
- package/dist/predictos/agents/x402-seller.d.ts.map +1 -0
- package/dist/predictos/ai/callBlockRun.d.ts.map +1 -0
- package/dist/predictos/ai/callGrok.d.ts.map +1 -0
- package/dist/predictos/ai/callOpenAI.d.ts.map +1 -0
- package/dist/predictos/ai/http.d.ts.map +1 -0
- package/dist/{prediction-markets → predictos}/ai/index.d.ts +1 -1
- package/dist/predictos/ai/index.d.ts.map +1 -0
- package/dist/predictos/ai/index.js +1 -0
- package/dist/predictos/ai/index.mjs +1 -0
- package/dist/predictos/ai/prompts/analyzeEventMarkets.d.ts.map +1 -0
- package/dist/predictos/ai/prompts/arbitrageAnalysis.d.ts.map +1 -0
- package/dist/predictos/ai/prompts/bookmakerAnalysis.d.ts.map +1 -0
- package/dist/predictos/ai/prompts/searchQueryGenerator.d.ts.map +1 -0
- package/dist/predictos/ai/types.d.ts.map +1 -0
- package/dist/predictos/arbitrage.d.ts.map +1 -0
- package/dist/predictos/arbitrage.js +1 -0
- package/dist/predictos/arbitrage.mjs +1 -0
- package/dist/{prediction-markets → predictos}/clients/polyfactual.d.ts +1 -1
- package/dist/predictos/clients/polyfactual.d.ts.map +1 -0
- package/dist/{prediction-markets → predictos}/clients/polymarket.d.ts +1 -1
- package/dist/predictos/clients/polymarket.d.ts.map +1 -0
- package/dist/{prediction-markets → predictos}/clients/x402.d.ts +1 -1
- package/dist/predictos/clients/x402.d.ts.map +1 -0
- package/dist/{prediction-markets → predictos}/data/kalshi.d.ts +1 -1
- package/dist/predictos/data/kalshi.d.ts.map +1 -0
- package/dist/predictos/data/kalshi.js +1 -0
- package/dist/predictos/data/kalshi.mjs +1 -0
- package/dist/{prediction-markets → predictos}/data/polymarket.d.ts +1 -1
- package/dist/predictos/data/polymarket.d.ts.map +1 -0
- package/dist/predictos/data/polymarket.js +1 -0
- package/dist/predictos/data/polymarket.mjs +1 -0
- package/dist/predictos/events.d.ts.map +1 -0
- package/dist/{prediction-markets → predictos}/index.d.ts +5 -8
- package/dist/predictos/index.d.ts.map +1 -0
- package/dist/predictos/index.js +1 -0
- package/dist/predictos/index.mjs +1 -0
- package/dist/{prediction-markets → predictos}/types.d.ts +6 -121
- package/dist/predictos/types.d.ts.map +1 -0
- package/dist/searchQueryGenerator-DIIs9xw5.js +1 -0
- package/dist/searchQueryGenerator-rCVblXJS.cjs +1 -0
- package/dist/stocks/index.d.ts +1 -2
- package/dist/stocks/index.d.ts.map +1 -1
- package/dist/stocks/quote-cache-service.d.ts +2 -11
- package/dist/stocks/quote-cache-service.d.ts.map +1 -1
- package/dist/stocks/unified-quote-service.d.ts +6 -15
- package/dist/stocks/unified-quote-service.d.ts.map +1 -1
- package/dist/stocks/yahoo-finance-wrapper.d.ts +6 -75
- package/dist/stocks/yahoo-finance-wrapper.d.ts.map +1 -1
- package/dist/trading-agents/agents/debate-facilitator.d.ts +3 -3
- package/dist/trading-agents/agents/debate-facilitator.d.ts.map +1 -1
- package/dist/trading-agents/agents/fund-manager.d.ts +2 -4
- package/dist/trading-agents/agents/fund-manager.d.ts.map +1 -1
- package/dist/trading-agents/agents/improved-researchers.d.ts +3 -3
- package/dist/trading-agents/agents/improved-researchers.d.ts.map +1 -1
- package/dist/trading-agents/agents/market-analyst.d.ts +2 -2
- package/dist/trading-agents/agents/market-analyst.d.ts.map +1 -1
- package/dist/trading-agents/agents/news-analyst.d.ts +2 -2
- package/dist/trading-agents/agents/news-analyst.d.ts.map +1 -1
- package/dist/trading-agents/agents/researchers.d.ts +4 -4
- package/dist/trading-agents/agents/researchers.d.ts.map +1 -1
- package/dist/trading-agents/agents/risk-team.d.ts +4 -4
- package/dist/trading-agents/agents/risk-team.d.ts.map +1 -1
- package/dist/trading-agents/agents/trader.d.ts +2 -2
- package/dist/trading-agents/agents/trader.d.ts.map +1 -1
- package/dist/trading-agents/graph/trading-graph.d.ts +2 -28
- package/dist/trading-agents/graph/trading-graph.d.ts.map +1 -1
- package/dist/trading-agents/index.d.ts +0 -4
- package/dist/trading-agents/index.d.ts.map +1 -1
- package/dist/trading-agents/types/index.d.ts +4 -27
- package/dist/trading-agents/types/index.d.ts.map +1 -1
- package/dist/trading-agents/utils/llm-client.d.ts +1 -4
- package/dist/trading-agents/utils/llm-client.d.ts.map +1 -1
- package/package.json +50 -21
- package/THIRD_PARTY_NOTICES.md +0 -144
- package/dist/index-6F5HGB0V.js +0 -15
- package/dist/index-kfghRBr2.cjs +0 -13
- package/dist/prediction/analysis/polymarket-wallet-trust.d.ts +0 -60
- package/dist/prediction/analysis/polymarket-wallet-trust.d.ts.map +0 -1
- package/dist/prediction/analysis/position-reconstruction.d.ts +0 -130
- package/dist/prediction/analysis/position-reconstruction.d.ts.map +0 -1
- package/dist/prediction/analysis/position-settlement.d.ts +0 -99
- package/dist/prediction/analysis/position-settlement.d.ts.map +0 -1
- package/dist/prediction/analysis/r-multiple.d.ts +0 -159
- package/dist/prediction/analysis/r-multiple.d.ts.map +0 -1
- package/dist/prediction/analysis/trust-score.d.ts +0 -158
- package/dist/prediction/analysis/trust-score.d.ts.map +0 -1
- package/dist/prediction/sync/refill-limits.d.ts +0 -9
- package/dist/prediction/sync/refill-limits.d.ts.map +0 -1
- package/dist/prediction/sync/refill.d.ts +0 -34
- package/dist/prediction/sync/refill.d.ts.map +0 -1
- package/dist/prediction/utils/token-ids.d.ts +0 -17
- package/dist/prediction/utils/token-ids.d.ts.map +0 -1
- package/dist/prediction-markets/adapters/trading-agents.d.ts +0 -21
- package/dist/prediction-markets/adapters/trading-agents.d.ts.map +0 -1
- package/dist/prediction-markets/agents/bookmaker-agent.d.ts.map +0 -1
- package/dist/prediction-markets/agents/event-analysis-agent.d.ts.map +0 -1
- package/dist/prediction-markets/agents/index.d.ts.map +0 -1
- package/dist/prediction-markets/agents/kalshi-momentum-agent.d.ts +0 -7
- package/dist/prediction-markets/agents/kalshi-momentum-agent.d.ts.map +0 -1
- package/dist/prediction-markets/agents/mapper-agent.d.ts.map +0 -1
- package/dist/prediction-markets/agents/polyfactual-research.d.ts.map +0 -1
- package/dist/prediction-markets/agents/polymarket-position-tracker.d.ts.map +0 -1
- package/dist/prediction-markets/agents/polymarket-put-order.d.ts.map +0 -1
- package/dist/prediction-markets/agents/polymarket-updown-15-limit-order-bot.d.ts.map +0 -1
- package/dist/prediction-markets/agents/x402-seller.d.ts.map +0 -1
- package/dist/prediction-markets/ai/callBlockRun.d.ts.map +0 -1
- package/dist/prediction-markets/ai/callGrok.d.ts.map +0 -1
- package/dist/prediction-markets/ai/callOpenAI.d.ts.map +0 -1
- package/dist/prediction-markets/ai/http.d.ts.map +0 -1
- package/dist/prediction-markets/ai/index.d.ts.map +0 -1
- package/dist/prediction-markets/ai/prompts/analyzeEventMarkets.d.ts.map +0 -1
- package/dist/prediction-markets/ai/prompts/arbitrageAnalysis.d.ts.map +0 -1
- package/dist/prediction-markets/ai/prompts/bookmakerAnalysis.d.ts.map +0 -1
- package/dist/prediction-markets/ai/prompts/searchQueryGenerator.d.ts.map +0 -1
- package/dist/prediction-markets/ai/types.d.ts.map +0 -1
- package/dist/prediction-markets/arbitrage.d.ts.map +0 -1
- package/dist/prediction-markets/clients/polyfactual.d.ts.map +0 -1
- package/dist/prediction-markets/clients/polymarket.d.ts.map +0 -1
- package/dist/prediction-markets/clients/x402.d.ts.map +0 -1
- package/dist/prediction-markets/data/kalshi.d.ts.map +0 -1
- package/dist/prediction-markets/data/polymarket.d.ts.map +0 -1
- package/dist/prediction-markets/events.d.ts.map +0 -1
- package/dist/prediction-markets/execution/paper.d.ts +0 -19
- package/dist/prediction-markets/execution/paper.d.ts.map +0 -1
- package/dist/prediction-markets/index.cjs +0 -1
- package/dist/prediction-markets/index.d.ts.map +0 -1
- package/dist/prediction-markets/index.mjs +0 -1
- package/dist/prediction-markets/kalshi-momentum.LICENSE +0 -21
- package/dist/prediction-markets/strategies/btc15m-fusion.d.ts +0 -27
- package/dist/prediction-markets/strategies/btc15m-fusion.d.ts.map +0 -1
- package/dist/prediction-markets/strategies/copy-trade-sizing.d.ts +0 -27
- package/dist/prediction-markets/strategies/copy-trade-sizing.d.ts.map +0 -1
- package/dist/prediction-markets/strategies/gabagool.d.ts +0 -26
- package/dist/prediction-markets/strategies/gabagool.d.ts.map +0 -1
- package/dist/prediction-markets/strategies/kalshi-momentum.d.ts +0 -13
- package/dist/prediction-markets/strategies/kalshi-momentum.d.ts.map +0 -1
- package/dist/prediction-markets/types.d.ts.map +0 -1
- package/dist/prediction-markets/validation.d.ts +0 -5
- package/dist/prediction-markets/validation.d.ts.map +0 -1
- package/dist/scripted-llm-B-UTs08L.js +0 -1
- package/dist/scripted-llm-CmDVkhyH.cjs +0 -1
- package/dist/stocks/strategies/bb-rsi-breakout.d.ts +0 -63
- package/dist/stocks/strategies/bb-rsi-breakout.d.ts.map +0 -1
- package/dist/stocks/strategies/ema-crossover.d.ts +0 -51
- package/dist/stocks/strategies/ema-crossover.d.ts.map +0 -1
- package/dist/strategy-signals/data/fixture-data-provider.d.ts +0 -8
- package/dist/strategy-signals/data/fixture-data-provider.d.ts.map +0 -1
- package/dist/strategy-signals/data/openbb-mapping.d.ts +0 -7
- package/dist/strategy-signals/data/openbb-mapping.d.ts.map +0 -1
- package/dist/strategy-signals/demo.d.ts +0 -446
- package/dist/strategy-signals/demo.d.ts.map +0 -1
- package/dist/strategy-signals/execution.d.ts +0 -18
- package/dist/strategy-signals/execution.d.ts.map +0 -1
- package/dist/strategy-signals/fixtures/openbb-data/bars.d.ts +0 -10
- package/dist/strategy-signals/fixtures/openbb-data/bars.d.ts.map +0 -1
- package/dist/strategy-signals/index.d.ts +0 -36
- package/dist/strategy-signals/index.d.ts.map +0 -1
- package/dist/strategy-signals/indicators/spread-aware-momentum.d.ts +0 -31
- package/dist/strategy-signals/indicators/spread-aware-momentum.d.ts.map +0 -1
- package/dist/strategy-signals/proposal.d.ts +0 -10
- package/dist/strategy-signals/proposal.d.ts.map +0 -1
- package/dist/strategy-signals/report.d.ts +0 -6
- package/dist/strategy-signals/report.d.ts.map +0 -1
- package/dist/strategy-signals/risk-gate.d.ts +0 -3
- package/dist/strategy-signals/risk-gate.d.ts.map +0 -1
- package/dist/strategy-signals/sources/btc15m-fusion.d.ts +0 -16
- package/dist/strategy-signals/sources/btc15m-fusion.d.ts.map +0 -1
- package/dist/strategy-signals/sources/copy-trade-sizing.d.ts +0 -15
- package/dist/strategy-signals/sources/copy-trade-sizing.d.ts.map +0 -1
- package/dist/strategy-signals/sources/gabagool.d.ts +0 -12
- package/dist/strategy-signals/sources/gabagool.d.ts.map +0 -1
- package/dist/strategy-signals/sources/hedge-fund-technicals.d.ts +0 -42
- package/dist/strategy-signals/sources/hedge-fund-technicals.d.ts.map +0 -1
- package/dist/strategy-signals/sources/kalshi-momentum.d.ts +0 -10
- package/dist/strategy-signals/sources/kalshi-momentum.d.ts.map +0 -1
- package/dist/strategy-signals/sources/kalshi-vibe-guards.d.ts +0 -15
- package/dist/strategy-signals/sources/kalshi-vibe-guards.d.ts.map +0 -1
- package/dist/strategy-signals/sources/kalshi-vibe.d.ts +0 -11
- package/dist/strategy-signals/sources/kalshi-vibe.d.ts.map +0 -1
- package/dist/strategy-signals/sources/red-flags.d.ts +0 -13
- package/dist/strategy-signals/sources/red-flags.d.ts.map +0 -1
- package/dist/strategy-signals/sources/spread-aware-momentum.d.ts +0 -11
- package/dist/strategy-signals/sources/spread-aware-momentum.d.ts.map +0 -1
- package/dist/strategy-signals/survival-posture.d.ts +0 -13
- package/dist/strategy-signals/survival-posture.d.ts.map +0 -1
- package/dist/strategy-signals/types.d.ts +0 -138
- package/dist/strategy-signals/types.d.ts.map +0 -1
- package/dist/strategy-signals/validate.d.ts +0 -15
- package/dist/strategy-signals/validate.d.ts.map +0 -1
- package/dist/strategy-signals/venues/kalshi-venue-mapping.d.ts +0 -3
- package/dist/strategy-signals/venues/kalshi-venue-mapping.d.ts.map +0 -1
- package/dist/strategy-signals/venues/mock-equity-broker.d.ts +0 -16
- package/dist/strategy-signals/venues/mock-equity-broker.d.ts.map +0 -1
- package/dist/strategy-signals/venues/mock-venue.d.ts +0 -14
- package/dist/strategy-signals/venues/mock-venue.d.ts.map +0 -1
- package/dist/strategy-signals/venues/pmxt-venue-mapping.d.ts +0 -7
- package/dist/strategy-signals/venues/pmxt-venue-mapping.d.ts.map +0 -1
- package/dist/trading-agents/agents/risk-judge.d.ts +0 -13
- package/dist/trading-agents/agents/risk-judge.d.ts.map +0 -1
- package/dist/trading-agents/index.cjs +0 -1
- package/dist/trading-agents/index.mjs +0 -1
- package/dist/trading-agents/utils/parse-final-line.d.ts +0 -7
- package/dist/trading-agents/utils/parse-final-line.d.ts.map +0 -1
- package/dist/trading-agents/utils/scripted-llm.d.ts +0 -17
- package/dist/trading-agents/utils/scripted-llm.d.ts.map +0 -1
- package/dist/trading-agents/utils/strategy-prompt.d.ts +0 -6
- package/dist/trading-agents/utils/strategy-prompt.d.ts.map +0 -1
- package/dist/trading-agents-Bh9OORHe.js +0 -1
- package/dist/trading-agents-C8M7tbB0.cjs +0 -1
- package/dist/validate-C1MS8RhG.js +0 -1
- package/dist/validate-DBxPUXqH.cjs +0 -1
- /package/dist/{prediction-markets → predictos}/agents/bookmaker-agent.d.ts +0 -0
- /package/dist/{prediction-markets → predictos}/agents/event-analysis-agent.d.ts +0 -0
- /package/dist/{prediction-markets → predictos}/agents/mapper-agent.d.ts +0 -0
- /package/dist/{prediction-markets → predictos}/agents/polymarket-position-tracker.d.ts +0 -0
- /package/dist/{prediction-markets → predictos}/agents/polymarket-updown-15-limit-order-bot.d.ts +0 -0
- /package/dist/{prediction-markets → predictos}/agents/x402-seller.d.ts +0 -0
- /package/dist/{prediction-markets → predictos}/ai/callBlockRun.d.ts +0 -0
- /package/dist/{prediction-markets → predictos}/ai/callGrok.d.ts +0 -0
- /package/dist/{prediction-markets → predictos}/ai/callOpenAI.d.ts +0 -0
- /package/dist/{prediction-markets → predictos}/ai/http.d.ts +0 -0
- /package/dist/{prediction-markets → predictos}/ai/prompts/analyzeEventMarkets.d.ts +0 -0
- /package/dist/{prediction-markets → predictos}/ai/prompts/arbitrageAnalysis.d.ts +0 -0
- /package/dist/{prediction-markets → predictos}/ai/prompts/bookmakerAnalysis.d.ts +0 -0
- /package/dist/{prediction-markets → predictos}/ai/prompts/searchQueryGenerator.d.ts +0 -0
- /package/dist/{prediction-markets → predictos}/ai/types.d.ts +0 -0
- /package/dist/{prediction-markets → predictos}/arbitrage.d.ts +0 -0
- /package/dist/{prediction-markets → predictos}/events.d.ts +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Wallet as e}from"ethers";import{ClobClient as t,Side as n,OrderType as r}from"@polymarket/clob-client";import{i as o,a as s,e as a}from"./validate-C1MS8RhG.js";function i(e){if(e instanceof Error){const t=e.message.toLowerCase();return t.includes("connection")||t.includes("tls")||t.includes("timeout")||t.includes("eof")||t.includes("network")||t.includes("fetch failed")}return!1}function c(e){return new Promise(t=>setTimeout(t,e))}async function l(e,t,n=12e4){const r=new AbortController,o=setTimeout(()=>r.abort(),n);try{const n=await fetch(e,{...t,signal:r.signal});return clearTimeout(o),n}catch(s){if(clearTimeout(o),s instanceof Error&&"AbortError"===s.name)throw new Error(`Request timeout after ${n}ms`);throw s}}async function u(e,t,n,r="gpt-4.1",o=3,s={}){const a=s.apiKey??process.env.OPENAI_API_KEY;if(!a)throw new Error("OPENAI_API_KEY environment variable is not set");const u={model:r,input:[{role:"system",content:t},{role:"user",content:e}],text:{format:{type:n}}};let m=null;for(let p=0;p<=o;p++)try{const e=await l("https://api.openai.com/v1/responses",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify(u)},12e4);if(!e.ok){const t=await e.text(),n=new Error(`OpenAI API error: ${e.status} ${e.statusText} - ${t}`);if(e.status>=400&&e.status<500&&429!==e.status)throw n;if(m=n,p<o){const e=Math.min(1e3*Math.pow(2,p),1e4);console.warn(`OpenAI API error (attempt ${p+1}/${o+1}), retrying in ${e}ms...`),await c(e);continue}throw n}return await e.json()}catch(d){if(m=d instanceof Error?d:new Error(String(d)),!i(d)&&0===p)throw m;if(p>=o)throw m;const e=Math.min(1e3*Math.pow(2,p),1e4);console.warn(`Network error (attempt ${p+1}/${o+1}): ${m.message}. Retrying in ${e}ms...`),await c(e)}throw m||new Error("Unknown error occurred")}async function m(e,t,n,r="grok-4-1-fast-reasoning",o=3,s,a={}){const u=a.apiKey??process.env.XAI_API_KEY;if(!u)throw new Error("XAI_API_KEY environment variable is not set");const m={model:r,input:[{role:"system",content:t},{role:"user",content:e}],...s&&s.length>0&&{tools:s.map(e=>({type:e}))},response_format:{type:n}};let d=null;for(let h=0;h<=o;h++)try{const e=await l("https://api.x.ai/v1/responses",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${u}`},body:JSON.stringify(m)},12e4);if(!e.ok){const t=await e.text(),n=new Error(`Grok API error: ${e.status} ${e.statusText} - ${t}`);if(e.status>=400&&e.status<500&&429!==e.status)throw n;if(d=n,h<o){const e=Math.min(1e3*Math.pow(2,h),1e4);console.warn(`Grok API error (attempt ${h+1}/${o+1}), retrying in ${e}ms...`),await c(e);continue}throw n}return await e.json()}catch(p){if(d=p instanceof Error?p:new Error(String(p)),!i(p)&&0===h)throw d;if(h>=o)throw d;const e=Math.min(1e3*Math.pow(2,h),1e4);console.warn(`Network error (attempt ${h+1}/${o+1}): ${d.message}. Retrying in ${e}ms...`),await c(e)}throw d||new Error("Unknown error occurred")}const d="https://blockrun.ai/api/v1/chat/completions",p={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},h={"blockrun/gpt-4o":"openai/gpt-4o","blockrun/gpt-4o-mini":"openai/gpt-4o-mini","blockrun/gpt-4.1":"openai/gpt-4.1","blockrun/gpt-5":"openai/gpt-5","blockrun/o1":"openai/o1","blockrun/o3-mini":"openai/o3-mini","blockrun/claude-sonnet-4":"anthropic/claude-sonnet-4","blockrun/claude-opus-4":"anthropic/claude-opus-4","blockrun/claude-haiku":"anthropic/claude-3-5-haiku-latest","blockrun/grok-3":"xai/grok-3","blockrun/grok-3-fast":"xai/grok-3-fast","blockrun/grok-3-mini":"xai/grok-3-mini","blockrun/gemini-2.5-pro":"google/gemini-2.5-pro-preview-06-05","blockrun/gemini-2.5-flash":"google/gemini-2.5-flash-preview-05-20","blockrun/deepseek-chat":"deepseek/deepseek-chat","blockrun/deepseek-reasoner":"deepseek/deepseek-reasoner","blockrun/qwen-max":"qwen/qwen-max","blockrun/qwen-plus":"qwen/qwen-plus"};function f(e){return e.startsWith("blockrun/")||e in h}async function y(t,n,r){console.log("[BlockRun] Creating x402 payment header for Base mainnet...");const o=new e(t),s=o.address;console.log("[BlockRun] Wallet address:",s);const a=function(){const e=new Uint8Array(32);return crypto.getRandomValues(e),`0x${Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}`}(),i=Math.floor(Date.now()/1e3),c=i-600,l=i+(n.maxTimeoutSeconds||300),u={from:s,to:n.payTo,value:n.amount||n.maxAmountRequired||"0",validAfter:c.toString(),validBefore:l.toString(),nonce:a},m=n.extra||{name:"USD Coin",version:"2"},d={name:m.name||"USD Coin",version:m.version||"2",chainId:8453,verifyingContract:n.asset},h=await o.signTypedData(d,p,{from:s,to:n.payTo,value:BigInt(n.amount||n.maxAmountRequired||"0"),validAfter:BigInt(c),validBefore:BigInt(l),nonce:a});console.log("[BlockRun] Payment signature created");const f={x402Version:n.x402Version||2,resource:{url:r,description:"BlockRun AI Chat Completion",mimeType:"application/json"},accepted:{scheme:n.scheme||"exact",network:n.network,asset:n.asset,amount:n.amount||n.maxAmountRequired||"0",payTo:n.payTo,maxTimeoutSeconds:n.maxTimeoutSeconds||300,extra:n.extra||{}},payload:{authorization:u,signature:h}};return btoa(JSON.stringify(f))}function g(e){try{const t=BigInt(e);return`$${(Number(t)/1e6).toFixed(6)}`}catch{return"Unknown"}}async function k(e,t,n,r="blockrun/gpt-4o",o=3,s=!1,a={}){const u=a.walletKey??process.env.BLOCKRUN_WALLET_KEY;if(!u)throw new Error("BLOCKRUN_WALLET_KEY environment variable is not set. BlockRun uses wallet-based micropayments instead of API keys. Set your Base chain private key (0x-prefixed hex) to use BlockRun.");const m=function(e){return e in h?h[e]:(e.includes("/"),e)}(r);console.log("[BlockRun] Using model:",m);const p={model:m,messages:[{role:"system",content:t},{role:"user",content:e}],..."json_object"===n&&{response_format:{type:"json_object"}},...s&&m.startsWith("xai/")&&{search:!0}};let f,k=null;for(let h=0;h<=o;h++)try{console.log("[BlockRun] Making request (attempt",h+1,")...");const e=await l(d,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)},12e4);if(402!==e.status){if(e.ok){return w(await e.json(),f)}const t=await e.text(),n=new Error(`BlockRun API error: ${e.status} ${e.statusText} - ${t}`);if(e.status>=400&&e.status<500&&429!==e.status)throw n;if(k=n,h<o){const e=Math.min(1e3*Math.pow(2,h),1e4);console.warn(`[BlockRun] Error (attempt ${h+1}), retrying in ${e}ms...`),await c(e);continue}throw n}const t=e.headers.get("payment-required");if(!t)throw new Error("BlockRun returned 402 but no payment-required header found");let n;try{const e=atob(t),r=JSON.parse(e),o=(r.accepts||[r]).find(e=>"eip155:8453"===e.network||"base"===e.network);if(!o)throw new Error("BlockRun does not accept Base network payments");n=o,n.x402Version=r.x402Version||2}catch(v){throw new Error(`Failed to parse payment requirements: ${v}`)}f=g(n.amount||n.maxAmountRequired||"0"),console.log("[BlockRun] Payment required:",f);const r=await y(u,n,d);console.log("[BlockRun] Making paid request...");const s=await l(d,{method:"POST",headers:{"Content-Type":"application/json","PAYMENT-SIGNATURE":r},body:JSON.stringify(p)},12e4);if(!s.ok){const e=await s.text(),t=new Error(`BlockRun payment failed: ${s.status} ${s.statusText} - ${e}`);if(s.status>=400&&s.status<500&&429!==s.status)throw t;if(k=t,h<o){const e=Math.min(1e3*Math.pow(2,h),1e4);console.warn(`[BlockRun] Payment error (attempt ${h+1}), retrying in ${e}ms...`),await c(e);continue}throw t}const a=await s.json();return console.log("[BlockRun] Request successful, cost:",f),w(a,f)}catch(S){if(k=S instanceof Error?S:new Error(String(S)),!i(S)&&0===h)throw k;if(h>=o)throw k;const e=Math.min(1e3*Math.pow(2,h),1e4);console.warn(`[BlockRun] Network error (attempt ${h+1}): ${k.message}. Retrying in ${e}ms...`),await c(e)}throw k||new Error("Unknown error occurred")}function w(e,t){const n=e.choices||[],r=e.usage||{},o=n[0]?.message?.content||"";return{created_at:e.created||Math.floor(Date.now()/1e3),id:e.id||`blockrun-${Date.now()}`,model:e.model||"unknown",object:"response",output:[{content:[{type:"output_text",text:o}],id:`msg-${Date.now()}`,role:"assistant",type:"message",status:"completed"}],temperature:null,top_p:null,usage:{input_tokens:r.prompt_tokens||0,output_tokens:r.completion_tokens||0,total_tokens:r.total_tokens||0},status:"completed",blockrun:{paymentCost:t,citations:e.citations||void 0}}}async function v(){try{const e=await fetch("https://blockrun.ai/api/v1/models",{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)return console.warn("[BlockRun] Failed to fetch models, using defaults"),S();const t=await e.json();return(t.data||t.models||[]).map(e=>({id:`blockrun/${e.id}`,name:e.name||e.id,provider:e.provider||"unknown",description:e.description||""}))}catch{return console.warn("[BlockRun] Error fetching models, using defaults"),S()}}function S(){return Object.entries(h).map(([e,t])=>{const[n,r]=t.split("/");return{id:e,name:r,provider:n,description:`${n} ${r} via BlockRun x402`}})}function P(e,t,n,r,o,s){const a=o?.includes("x_search"),i=o?.includes("web_search");let c="";a&&(c+="\nYou have access to X (Twitter) search. Use it to find the latest posts, news, and sentiment about this event. When you find relevant posts that back your analysis, include their URLs in your response."),i&&(c+="\nYou have access to web search. Use it to find the latest news articles, reports, and analysis about this event. When you find relevant resources that back your analysis, include their URLs in your response.");return{systemPrompt:`You are a financial analyst expert in the field of prediction markets (posted on ${r}) that understands the latest news, events, and market trends.\nYour expertise lies in deeply analyzing prediction markets for a specific event, identifying if there's alpha (mispricing) opportunity, and providing a clear recommendation on which side (YES or NO) is more likely to win based on your analysis.\nYou always provide a short analysisSummary of your findings, less than 270 characters, that is very conversational and understandable by a non-expert who just wants to understand which side it might make more sense to buy into.\n${c}${s?`\n### VERY IMPORTANT: The user has provided specific commands that you MUST prioritize over everything else:\n${s}`:""}\nYour output is ALWAYS in JSON format and you are VERY STRICT about it. You must return valid JSON that matches the exact schema specified.`,userPrompt:`# Task: Deep Analysis of an Event's Prediction Markets\n\nYou are analyzing all markets for a specific event (${t}) to determine:\n1. Whether there is an alpha (mispricing) opportunity in any of the markets\n2. Which market has the best alpha opportunity (if any)\n3. Which side (YES or NO) is more likely to win for that market\n4. Your confidence level in this assessment\n\n## User's query/input/question About This Event\n${n}\n\n## Platform: ${r}\n\n## Event Markets (${e.length} market${1!==e.length?"s":""})\n\n${JSON.stringify(e,null,2)}\n\n## Your Analysis Process\n\n1. **Understand the event**: Review all markets to understand the overall event and how the markets relate to each other\n2. **Analyze each market**: For each market, understand the title/question, description, outcomes, and resolution rules\n3. **Assess current pricing**: \n - For Kalshi: \`last_price\` field (0-100) represents the current implied probability for YES\n - For Polymarket: \`outcomePrices\` field contains an array like ["0.21", "0.79"] where the first value is the YES probability (multiply by 100 to get percentage)\n4. **Research and assess**: Use your knowledge of current events, news, trends, and fundamental factors to estimate actual probabilities\n5. **Find the best opportunity**: Identify which market (if any) has the best alpha opportunity\n6. **Consider context**: Take into account liquidity, volume, open interest, expiration/end dates, and market status\n7. **Answer the user's question**: Address the specific question asked about this event\n\n## What is Alpha?\n\nAlpha in prediction markets occurs when there's a mispricing between:\n- **Market Probability**: The current market price represents the market's collective assessment\n- **Actual Probability**: Your assessment based on the latest information, trends, and analysis\n\n### Example:\nIf the market prices an event at 30% (YES side), but your analysis suggests it should be 60%, there's a 30-point alpha opportunity in buying YES.\nConversely, if the market prices at 70% but you believe it should be 40%, there's alpha in buying NO.\n\n## Output Format\n\nReturn your analysis in JSON format with the following fields. Focus on the SINGLE BEST market opportunity (or the most relevant market if no alpha exists):\n\n{\n "event_ticker": "string - event ticker identifier",\n "ticker": "string - market ticker identifier for the best opportunity",\n "title": "string - market title",\n "marketProbability": number - current market probability (0-100),\n "estimatedActualProbability": number - your estimated actual probability (0-100),\n "alphaOpportunity": number - the difference (positive = buy yes, negative = buy no),\n "hasAlpha": boolean - whether you believe there is meaningful alpha (|alphaOpportunity| >= 5),\n "predictedWinner": "string - either 'YES' or 'NO' - which side you think will win",\n "winnerConfidence": number - confidence that your predicted winner will win (0-100),\n "recommendedAction": "string - either 'BUY YES', 'BUY NO', or 'NO TRADE' if no alpha",\n "reasoning": "string - detailed explanation of your analysis, including relevant trends, news, and factors. If there are multiple markets, explain why you chose this one.",\n "confidence": number - your confidence in this overall assessment (0-100),\n "keyFactors": ["string"] - array of key factors influencing your assessment,\n "risks": ["string"] - array of risks that could affect your prediction,\n "questionAnswer": "string - direct answer to the user's specific query/input/question",\n "analysisSummary": "string - brief summary of your findings under 270 characters"${a?',\n "xSources": ["string"] - array of X (Twitter) post URLs that back your analysis (include 2-4 relevant posts)':""}${i?',\n "webSources": ["string"] - array of web URLs (news articles, reports, etc.) that back your analysis (include 2-4 relevant resources)':""}\n}\n\n## Important Notes\n\n- Be thorough in your analysis - consider all markets for this event\n- If there are multiple markets, explain why you selected the one you did as the best opportunity\n- Consider both sides of the argument before making your recommendation\n- If you don't find meaningful alpha (|alphaOpportunity| < 5) in ANY market, set hasAlpha to false and recommendedAction to "NO TRADE"\n- Your predictedWinner should be the side you think will ultimately win (YES or NO), regardless of alpha\n- winnerConfidence is specifically about which side wins, while confidence is about your overall analysis quality\n- Be conservative with confidence scores - only assign high confidence when you have strong evidence\n- Your reasoning should be specific and reference actual trends, news, or data when possible\n- Address the user's query/input/question directly in the questionAnswer field\n- The analysisSummary should be conversational and to-the-point, no hype or emojis${a?"\n- IMPORTANT: Include 2-4 relevant X (Twitter) post URLs in xSources that back your analysis - these should be real posts you found via search":""}${i?"\n- IMPORTANT: Include 2-4 relevant web URLs (news articles, reports) in webSources that back your analysis - these should be real resources you found via search":""}\n${s?`\n### VERY IMPORTANT:Below are the user commands - Make sure to prioritize their ask over everything else\n${s}\n`:""}\nNow analyze these markets and provide your assessment. Return your response in the exact JSON format specified above.`}}function E(e,t,n,r){const o=e.length>0?e.map((e,t)=>`\n### Agent ${t+1}: ${e.model}\n- **Ticker**: ${e.analysis.ticker}\n- **Title**: ${e.analysis.title}\n- **Market Probability**: ${e.analysis.marketProbability}%\n- **Estimated Actual Probability**: ${e.analysis.estimatedActualProbability}%\n- **Alpha Opportunity**: ${e.analysis.alphaOpportunity>0?"+":""}${e.analysis.alphaOpportunity}%\n- **Has Alpha**: ${e.analysis.hasAlpha}\n- **Predicted Winner**: ${e.analysis.predictedWinner}\n- **Winner Confidence**: ${e.analysis.winnerConfidence}%\n- **Recommended Action**: ${e.analysis.recommendedAction}\n- **Confidence**: ${e.analysis.confidence}%\n- **Reasoning**: ${e.analysis.reasoning}\n- **Key Factors**: ${e.analysis.keyFactors.join("; ")}\n- **Risks**: ${e.analysis.risks.join("; ")}\n- **Analysis Summary**: ${e.analysis.analysisSummary}\n`).join("\n"):"(No AI agent analyses provided)",s=t.length>0?t.map((e,t)=>`\n### PayAI Data Source ${t+1}: ${e.seller}\n- **Query**: ${e.query}\n- **Response Data** (first 3000 chars):\n\`\`\`\n${e.response}\n\`\`\`\n`).join("\n"):"";e.length,t.length;return{systemPrompt:"You are a senior financial analyst who specializes in synthesizing multiple expert opinions on prediction markets.\nYour task is to combine and consolidate analyses from multiple AI agents and external data sources (PayAI sellers) into a single, authoritative assessment.\nYou weigh each agent's analysis based on their confidence levels and the consistency of their reasoning.\nWhen agents disagree, you provide balanced perspective on both sides before making a final recommendation.\nYou also incorporate external data from PayAI sellers (news, research, etc.) to inform your assessment.\nYour output is ALWAYS in JSON format and you are VERY STRICT about it. You must return valid JSON that matches the exact schema specified.",userPrompt:`# Task: Aggregate Multiple Data Sources\n\nYou are consolidating data from ${[e.length>0?`${e.length} AI agent${e.length>1?"s":""}`:"",t.length>0?`${t.length} PayAI data source${t.length>1?"s":""}`:""].filter(Boolean).join(" and ")} for the ${r} event: ${n}\n\n## Individual Agent Analyses\n${o}\n${s?`\n## PayAI External Data Sources\n${s}`:""}\n\n## Your Task\n\nReview all data sources and create a consolidated assessment that:\n1. **Identifies consensus**: Where do AI agents agree?\n2. **Highlights disagreements**: Where do agents disagree, and what are the arguments on each side?\n3. **Weighs confidence**: Give more weight to high-confidence analyses with strong reasoning\n4. **Incorporates external data**: Use PayAI data sources (news, research, etc.) to inform and validate agent analyses\n5. **Synthesizes findings**: Create a final recommendation that accounts for all perspectives and external data\n\n## Output Format\n\nReturn your consolidated analysis in JSON format:\n\n{\n "event_ticker": "string - event identifier",\n "ticker": "string - the market ticker most agents recommend or the best opportunity",\n "title": "string - market title",\n "marketProbability": number - consensus market probability (0-100),\n "estimatedActualProbability": number - consolidated estimated probability (0-100),\n "alphaOpportunity": number - consolidated alpha assessment,\n "hasAlpha": boolean - whether consolidated view shows meaningful alpha,\n "predictedWinner": "string - either 'YES' or 'NO'",\n "winnerConfidence": number - consolidated confidence (0-100),\n "recommendedAction": "string - either 'BUY YES', 'BUY NO', or 'NO TRADE'",\n "reasoning": "string - synthesized reasoning that accounts for all agent perspectives, noting agreements and disagreements",\n "confidence": number - overall consolidated confidence (0-100),\n "keyFactors": ["string"] - combined and deduplicated key factors from all agents,\n "risks": ["string"] - combined and deduplicated risks from all agents,\n "questionAnswer": "string - consolidated answer based on all agent analyses",\n "analysisSummary": "string - brief consolidated summary under 270 characters",\n "agentConsensus": {\n "agreementLevel": "string - 'high' (>80% agree), 'medium' (50-80%), or 'low' (<50%)",\n "majorityRecommendation": "string - what most agents recommended",\n "dissenting": ["string"] - any dissenting opinions summarized\n }\n}\n\n## Important Notes\n\n- If agents strongly disagree (low consensus), be more conservative with confidence\n- Highlight when there's unanimous agreement vs split opinions\n- The agentConsensus field helps users understand how aligned the agents were\n- Your reasoning should explicitly mention which agents agreed/disagreed and why\n- Be balanced - don't ignore minority opinions if they have valid points\n- PayAI external data (news, research) should be used to validate and inform agent analyses\n- If external data contradicts agent analyses, note this in your reasoning\n- External data is especially useful for recent events or time-sensitive information\n\nNow consolidate all data sources and provide your synthesized assessment.`}}function b(e){const{sourceMarket:t,searchResults:n,searchPlatform:r}=e,o="polymarket"===r?"Polymarket":"Kalshi";return{systemPrompt:"You are an expert financial analyst specializing in prediction market arbitrage opportunities.\n\nYour task is to:\n1. Determine if the source market and any of the search results represent the SAME underlying event/question\n2. If they do, calculate whether there's an arbitrage opportunity based on price differences\n3. Provide clear, actionable analysis\n\nYou understand that arbitrage in prediction markets works as follows:\n- If you can buy YES on one market and NO on another market for the same event\n- And the combined cost is less than $1.00 (or 100%), you have guaranteed profit\n- The profit = $1.00 - (YES price + NO price)\n\nImportant considerations:\n- Markets must represent the EXACT same event with the same resolution criteria\n- Even small wording differences can lead to different outcomes\n- Be conservative in matching - when in doubt, say they're NOT the same market\n- Consider timing differences (different end dates = different markets)\n\nYour output must be valid JSON matching the exact schema specified.",userPrompt:`# Arbitrage Analysis Task\n\n## Source Market (from ${"polymarket"===t.source?"Polymarket":"Kalshi"})\n\n**Name:** ${t.name}\n**Identifier:** ${t.identifier}\n**YES Price:** ${t.yesPrice}% \n**NO Price:** ${t.noPrice}%\n**URL:** ${t.url}\n\n${t.rawData?`**Raw Data:**\n\`\`\`json\n${JSON.stringify(t.rawData,null,2)}\n\`\`\``:""}\n\n## Search Results from ${o}\n\n${0===n.length?"No matching markets found on "+o:`Found ${n.length} potential matches:\n\n\`\`\`json\n${JSON.stringify(n,null,2)}\n\`\`\``}\n\n## Your Analysis Task\n\n1. **Market Matching**: Examine each search result and determine if ANY of them represent the SAME event as the source market. Consider:\n - Is the question/title asking about the same thing?\n - Are the resolution criteria likely to be the same?\n - Are the time frames compatible?\n - Could slight wording differences lead to different outcomes?\n\n2. **If Same Market Found**: Calculate the arbitrage opportunity:\n - Compare YES prices across both markets\n - Compare NO prices across both markets\n - The arb exists if: (lowest YES price) + (lowest NO price) < 100\n - Calculate exact profit percentage\n\n3. **Build Response**: Return your analysis in the exact JSON format below.\n\n## Output Format\n\nReturn a JSON object with this exact structure:\n\n{\n "isSameMarket": boolean,\n "sameMarketConfidence": number (0-100),\n "marketComparisonReasoning": "string explaining why you believe the markets are/aren't the same",\n "matchedMarket": {\n "source": "${r}",\n "name": "string - market title/name",\n "identifier": "string - the identifier field from the matched search result",\n "yesPrice": number (0-100),\n "noPrice": number (0-100),\n "volume": number or null,\n "liquidity": number or null,\n "url": "string - market URL (see URL format below)"\n } or null if no match found,\n "arbitrage": {\n "hasArbitrage": boolean,\n "profitPercent": number or null,\n "strategy": {\n "buyYesOn": "${t.source}" or "${r}",\n "buyYesPrice": number,\n "buyNoOn": "${t.source}" or "${r}",\n "buyNoPrice": number,\n "totalCost": number,\n "guaranteedPayout": 100,\n "netProfit": number\n } or null\n },\n "summary": "string - 2-3 sentence summary of findings",\n "risks": ["array of strings - potential risks or caveats"],\n "recommendation": "string - clear actionable recommendation"\n}\n\n## Important Notes\n\n- For Polymarket markets, the URL format is: https://polymarket.com/event/[identifier]\n- For Kalshi markets, the URL format is: https://kalshi.com/events/[identifier]\n- Each search result has an "identifier" field - use it to build the URL\n- ${"polymarket"===r?"Polymarket prices in outcomePrices are decimals (0.45 = 45%)":"Kalshi prices are already in percentage (45 = 45%)"}\n- Only report arbitrage if you're at least 80% confident the markets are the same\n- If no matching market is found, set isSameMarket to false and explain why\n\nNow analyze the markets and provide your assessment.`}}function I(e){const{title:t,sourcePlatform:n,targetPlatform:r}=e;return{systemPrompt:'You are a search query optimizer for prediction markets.\n\nYour task is to extract the 1-2 MOST IMPORTANT keywords from an event title that would best match similar events on another platform.\n\nRules:\n1. Return ONLY 1-2 words, no more\n2. Focus on unique identifiers: names, specific events, dates, numbers\n3. Remove common words like "will", "the", "be", "in", etc.\n4. Prioritize proper nouns (people, companies, places)\n5. If there\'s a person\'s name, that\'s usually the best keyword\n6. For numeric targets (prices, percentages), include the key number\n\nExamples:\n- "Will Bitcoin reach $100,000 by end of 2025?" → "Bitcoin"\n- "Will Elon Musk tweet about Dogecoin this week?" → "Elon Musk"\n- "Jensen Huang mentions at CES 2026" → "Jensen"\n- "Will the Fed cut interest rates in January?" → "Fed rates"\n- "Trump wins 2024 election" → "Trump"\n- "Apple stock above $200" → "Apple"\n\nReturn ONLY the search query, nothing else. No quotes, no explanation.',userPrompt:`Extract the best 1-2 word search query from this ${n} event title to search on ${r}:\n\n"${t}"\n\nSearch query:`}}async function A(e,t={}){const{method:n="GET",headers:r={},params:o={},apiKey:s}=t,a=function(e){const t=e??process.env.DFLOW_API_KEY;if(!t)throw new Error("DFLOW_API_KEY is not configured. Get your API key from DFlow: https://x.com/dflow");return t}(s),i=new URLSearchParams;Object.entries(o).forEach(([e,t])=>{null!=t&&i.append(e,String(t))});const c=i.toString(),l=`https://a.prediction-markets-api.dflow.net/api/v1${e}${c?`?${c}`:""}`,u=await fetch(l,{method:n,headers:{"Content-Type":"application/json","x-api-key":a,...r}});if(!u.ok){const e=await u.text();throw new Error(`DFlow API error: ${u.status} ${u.statusText} - ${e}`)}return await u.json()}async function $(e,t){return(await A(`/event/${e}`,{params:{withNestedMarkets:!0},apiKey:t})).markets}function T(e){return`https://kalshi.com/markets/${e.split("-")[0]}`}function x(e){const t=e??process.env.DOME_API_KEY;if(!t)throw new Error("DOME_API_KEY environment variable is not set");return t}async function O(e,t={}){const{method:n="GET",headers:r={},params:o={},apiKey:s}=t,a=new URLSearchParams;Object.entries(o).forEach(([e,t])=>{null!=t&&a.append(e,String(t))});const i=a.toString(),c=`https://api.domeapi.io/v1${e}${i?`?${i}`:""}`,l=await fetch(c,{method:n,headers:{"Content-Type":"application/json",Authorization:`Bearer ${x(s)}`,...r}});if(!l.ok){const e=await l.text();throw new Error(`Dome API error: ${l.status} ${l.statusText} - ${e}`)}return await l.json()}async function C(e,t){return O("/polymarket/markets",{params:e,apiKey:t})}async function R(e,t="open",n){const r=await async function(e,t){return O("/kalshi/markets",{params:{cursor:e?.cursor,limit:e?.limit,event_ticker:e?.eventTicker,status:e?.status},apiKey:t})}({eventTicker:e,status:t,limit:100},n);return r.markets}function M(e){return`https://kalshi.com/markets/${e.split("-")[0]}`}function U(e){return`https://polymarket.com/event/${e}`}const D=["gpt-5.2","gpt-5.1","gpt-5-nano","gpt-4.1","gpt-4.1-mini"];function N(e){return f(e)?"blockrun":function(e){return D.includes(e)||e.startsWith("gpt-")}(e)?"openai":"grok"}async function q(e,t={}){const n=Date.now(),{markets:r,eventIdentifier:o,pmType:s,model:a,question:i,tools:c,userCommand:l}=e;if(!r||!Array.isArray(r)||0===r.length)throw new Error("Missing or invalid 'markets' parameter");if(!o)throw new Error("Missing required parameter: 'eventIdentifier'");if(!s||"Kalshi"!==s&&"Polymarket"!==s)throw new Error("Invalid 'pmType'. Must be 'Kalshi' or 'Polymarket'");if(!a)throw new Error("Missing required parameter: 'model'");const d=N(a),p=i||"What is the best trading opportunity in this market? Analyze the probability and provide a recommendation.",{systemPrompt:h,userPrompt:f}=P(r,o,p,s,c,l);let y,g,w,v,S;if("blockrun"===d){const e=c?.includes("x_search")||c?.includes("web_search"),n=await k(f,h,"json_object",a,3,e,{walletKey:t.blockrunWalletKey});y=n.model,g=n.usage?.total_tokens,w=n.blockrun?.paymentCost;const r=[];for(const t of n.output)if("message"===t.type){const e=t;r.push(...e.content)}v=r.map(e=>e.text).filter(e=>void 0!==e).join("\n")}else if("openai"===d){const e=await u(f,h,"json_object",a,3,{apiKey:t.openaiApiKey});y=e.model,g=e.usage?.total_tokens;const n=[];for(const t of e.output)if("message"===t.type){const e=t;n.push(...e.content)}v=n.map(e=>e.text).filter(e=>void 0!==e).join("\n")}else{const e=await m(f,h,"json_object",a,3,c,{apiKey:t.xaiApiKey});y=e.model,g=e.usage?.total_tokens;const n=[];for(const t of e.output)if("message"===t.type){const e=t;n.push(...e.content)}v=n.map(e=>e.text).filter(e=>void 0!==e).join("\n")}try{S=JSON.parse(v)}catch{throw new Error(`Failed to parse AI response as JSON (model ${y}): ${v.substring(0,200)}`)}return{analysis:S,model:y,tokensUsed:g,paymentCost:w,processingTimeMs:Date.now()-n}}const L=["gpt-5.2","gpt-5.1","gpt-5-nano","gpt-4.1","gpt-4.1-mini"];async function Y(e,t={}){const n=Date.now(),{analyses:r,x402Results:o,eventIdentifier:s,pmType:a,model:i}=e,c=r&&Array.isArray(r)&&r.length>0,l=o&&Array.isArray(o)&&o.length>0;if(!c&&!l)throw new Error("Missing or invalid 'analyses' or 'x402Results' parameter");const d=(r?.length||0)+(o?.length||0);if(d<2)throw new Error("Need at least 2 data sources (analyses + PayAI results) to aggregate");if(!s)throw new Error("Missing required parameter: 'eventIdentifier'");if(!a||"Kalshi"!==a&&"Polymarket"!==a)throw new Error("Invalid 'pmType'. Must be 'Kalshi' or 'Polymarket'");if(!i)throw new Error("Missing required parameter: 'model'");const p=function(e){return L.includes(e)||e.startsWith("gpt-")}(i),h=(r||[]).map(e=>({agentId:e.agentId,model:e.model,analysis:e.analysis})),{systemPrompt:f,userPrompt:y}=E(h,o||[],s,a);let g,k,w,v;if(p){const e=await u(y,f,"json_object",i,3,{apiKey:t.openaiApiKey});g=e.model,k=e.usage?.total_tokens;const n=[];for(const t of e.output)if("message"===t.type){const e=t;n.push(...e.content)}w=n.map(e=>e.text).filter(e=>void 0!==e).join("\n")}else{const e=await m(y,f,"json_object",i,3,void 0,{apiKey:t.xaiApiKey});g=e.model,k=e.usage?.total_tokens;const n=[];for(const t of e.output)if("message"===t.type){const e=t;n.push(...e.content)}w=n.map(e=>e.text).filter(e=>void 0!==e).join("\n")}try{v=JSON.parse(w)}catch{throw new Error(`Failed to parse AI response as JSON (model ${g}): ${w.substring(0,200)}`)}return{analysis:v,model:g,tokensUsed:k,agentsAggregated:d,processingTimeMs:Date.now()-n}}class _ extends Error{constructor(e="Agents recommend NO TRADE - no order to place"){super(e),this.name="NoTradeError"}}function F(e,t,n){if(t.closed)throw new Error("Market is closed");if(!1===t.acceptingOrders)throw new Error("Market is not accepting orders");if(!t.clobTokenIds)throw new Error("Missing clobTokenIds in market data");const[r,o]=function(e){try{const t=JSON.parse(e);if(Array.isArray(t)&&t.length>=2)return[t[0],t[1]];throw new Error("Invalid token IDs format")}catch{throw new Error(`Failed to parse clobTokenIds: ${e}`)}}(t.clobTokenIds),s=function(e){try{return JSON.parse(e)}catch{return["Yes","No"]}}(t.outcomes||'["Yes", "No"]'),a=function(e){try{return JSON.parse(e).map(e=>parseFloat(e))}catch{return[.5,.5]}}(t.outcomePrices||'["0.5", "0.5"]'),i="BUY YES"===e.recommendedAction,c=i?"YES":"NO",l=s.findIndex(e=>"yes"===e.toLowerCase()||"up"===e.toLowerCase()),u=s.findIndex(e=>"no"===e.toLowerCase()||"down"===e.toLowerCase());let m,d;i?(m=0===l?r:o,d=a[l>=0?l:0]):(m=0===u?r:o,d=a[u>=0?u:1]);const p=t.minimumTickSize||"0.01",h=t.negRisk??false,f=function(e,t){const n=parseFloat(t);return Math.round(e/n)*n}(d,p),y=n/f,g=Math.floor(y);if(g<5)throw new Error(`Budget too small. At current price (${(100*f).toFixed(1)}%), minimum budget is $${(5*f).toFixed(2)} for 5 shares`);const k=`BUY ${g} shares of ${c} @ ${(100*f).toFixed(1)}% for ~$${(g*f).toFixed(2)} on "${t.title||t.question||"Unknown Market"}"`;return{tokenId:m,price:f,side:"BUY",size:g,feeRateBps:0,tickSize:p,negRisk:h,conditionId:t.conditionId||"",marketSlug:t.slug||"",orderDescription:k}}function j(e){const{platform:t,analysisResult:n,marketData:r,budgetUsd:o}=e;if(!t||"Polymarket"!==t&&"Kalshi"!==t)throw new Error("Invalid platform. Must be 'Polymarket' or 'Kalshi'");if(!n||!n.recommendedAction)throw new Error("Missing analysisResult or recommendedAction");if("NO TRADE"===n.recommendedAction)throw new _;if(!r)throw new Error("Missing marketData");if("number"!=typeof o||o<1||o>100)throw new Error("Invalid budgetUsd. Must be between $1 and $100");if("Kalshi"===t)throw new Error("Kalshi autonomous mode coming soon! Currently only Polymarket is supported.");return{platform:"Polymarket",orderParams:F(n,r,o),analysis:{recommendedAction:n.recommendedAction,side:"BUY YES"===n.recommendedAction?"YES":"NO",confidence:n.winnerConfidence}}}function B(e,t){if(!Number.isInteger(e)||e<0||e>100)throw new Error(`${t} must be an integer from 0 through 100`)}function K(e,t){if("string"!=typeof e||!e.trim()||e!==e.trim())throw new Error("ticker must be a non-empty market identifier without surrounding whitespace");if("string"!=typeof t||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/.test(t)||!Number.isFinite(Date.parse(t))||/* @__PURE__ */new Date(`${t.slice(0,10)}T00:00:00.000Z`).toISOString().slice(0,10)!==t.slice(0,10))throw new Error("timestamp must be a valid ISO date-time with an explicit timezone")}function z(e){if(!e)throw new Error("A market tick is required");K(e.ticker,e.timestamp),B(e.yesPriceCents,"tick.yesPriceCents")}function J(e,t){return`${e}:${t}`}function W(e){if(!e.positions||"object"!=typeof e.positions||Array.isArray(e.positions))throw new Error("Initial paper portfolio positions must be a position map");return{...e,positions:Object.fromEntries(Object.entries(e.positions).map(([e,t])=>[e,{...t}]))}}class V{state;maxPositionPerMarket;constructor(e){if(!Number.isSafeInteger(e.initialCashCents)||e.initialCashCents<0)throw new Error("initialCashCents must be a non-negative integer");if(!Number.isSafeInteger(e.maxPositionPerMarket)||e.maxPositionPerMarket<=0)throw new Error("maxPositionPerMarket must be a positive integer");this.maxPositionPerMarket=e.maxPositionPerMarket,this.state=e.initialPortfolio?W(e.initialPortfolio):{initialCashCents:e.initialCashCents,cashCents:e.initialCashCents,positions:{},realizedPnlCents:0,unrealizedPnlCents:0,equityCents:e.initialCashCents},this.validateInitialPortfolio(),this.revalue()}mark(e){z(e);for(const t of["YES","NO"]){const n=this.state.positions[J(e.ticker,t)];n&&(n.markPriceCents="YES"===t?e.yesPriceCents:100-e.yesPriceCents)}return this.revalue(),this.snapshot()}execute(e){try{K(e.ticker,e.timestamp),B(e.priceCents,"priceCents")}catch(s){return this.reject(e,s.message)}if("BUY"!==e.action&&"SELL"!==e.action&&"HOLD"!==e.action)return this.reject(e,"action must be BUY, SELL or HOLD");if("HOLD"===e.action)return null!==e.outcome||0!==e.quantity?this.reject(e,"HOLD requires a null outcome and zero quantity"):{status:"SKIPPED",intent:e,reason:e.reason,portfolio:this.snapshot()};if("YES"!==e.outcome&&"NO"!==e.outcome||!Number.isSafeInteger(e.quantity)||e.quantity<=0)return this.reject(e,"Executable intents require an outcome and positive integer quantity");const t=J(e.ticker,e.outcome),n=this.state.positions[t];if("BUY"===e.action){const r=(n?.quantity??0)+e.quantity;if(Object.values(this.state.positions).filter(t=>t.ticker===e.ticker).reduce((e,t)=>e+t.quantity,0)+e.quantity>this.maxPositionPerMarket)return this.reject(e,"Position limit exceeded");const o=e.priceCents*e.quantity;if(!Number.isSafeInteger(o))return this.reject(e,"Order cost exceeds safe integer cents");if(o>this.state.cashCents)return this.reject(e,"Insufficient paper cash");const s=n?n.averageEntryPriceCents*n.quantity:0,a={ticker:e.ticker,outcome:e.outcome,quantity:r,averageEntryPriceCents:(s+o)/r,markPriceCents:e.priceCents,unrealizedPnlCents:0};return this.state.cashCents-=o,this.state.positions[t]=a,this.revalue(),{status:"FILLED",intent:e,fill:{priceCents:e.priceCents,quantity:e.quantity,cashChangeCents:-o,realizedPnlCents:0},portfolio:this.snapshot()}}if(!n||n.quantity<e.quantity)return this.reject(e,"Insufficient paper position");const r=e.priceCents*e.quantity;if(!Number.isSafeInteger(this.state.cashCents+r))return this.reject(e,"Paper cash exceeds safe integer cents");const o=(e.priceCents-n.averageEntryPriceCents)*e.quantity;return n.quantity-=e.quantity,n.markPriceCents=e.priceCents,this.state.cashCents+=r,this.state.realizedPnlCents+=o,0===n.quantity&&delete this.state.positions[t],this.revalue(),{status:"FILLED",intent:e,fill:{priceCents:e.priceCents,quantity:e.quantity,cashChangeCents:r,realizedPnlCents:o},portfolio:this.snapshot()}}snapshot(){return W(this.state)}reject(e,t){return{status:"REJECTED",intent:e,reason:t,portfolio:this.snapshot()}}validateInitialPortfolio(){const e=this.state;if(!Number.isSafeInteger(e.initialCashCents)||e.initialCashCents<0||!Number.isSafeInteger(e.cashCents)||e.cashCents<0||!Number.isFinite(e.realizedPnlCents))throw new Error("Invalid initial paper portfolio cash or realized P&L");const t=/* @__PURE__ */new Map;for(const[n,r]of Object.entries(e.positions)){if("string"!=typeof r.ticker||!r.ticker.trim()||r.ticker!==r.ticker.trim()||"YES"!==r.outcome&&"NO"!==r.outcome||n!==J(r.ticker,r.outcome)||!Number.isSafeInteger(r.quantity)||r.quantity<=0||!Number.isFinite(r.averageEntryPriceCents)||r.averageEntryPriceCents<0||r.averageEntryPriceCents>100)throw new Error("Invalid initial paper position");B(r.markPriceCents,"position.markPriceCents");const e=(t.get(r.ticker)??0)+r.quantity;if(e>this.maxPositionPerMarket)throw new Error("Initial portfolio exceeds position limit");t.set(r.ticker,e)}}revalue(){let e=0,t=0;for(const n of Object.values(this.state.positions))n.unrealizedPnlCents=(n.markPriceCents-n.averageEntryPriceCents)*n.quantity,e+=n.markPriceCents*n.quantity,t+=n.unrealizedPnlCents;this.state.unrealizedPnlCents=t,this.state.equityCents=this.state.cashCents+e}}const G={lookback:5,momentumThreshold:3,positionSize:10,profitTargetCents:5,stopLossCents:3,maxPosition:50};function X(){return{directions:[],tradesExecuted:0}}function H(e={}){const t={...G,...e};for(const[n,r]of Object.entries(t))if(!Number.isSafeInteger(r)||r<=0)throw new Error(`${n} must be a positive integer`);if(t.momentumThreshold>t.lookback)throw new Error("momentumThreshold cannot exceed lookback");return t}function Q(e,t){if(!Array.isArray(e.directions)||e.directions.length>t.lookback||e.directions.some(e=>-1!==e&&0!==e&&1!==e)||!Number.isSafeInteger(e.tradesExecuted)||e.tradesExecuted<0)throw new Error("Invalid momentum history or trade count");if(void 0!==e.lastYesPriceCents)B(e.lastYesPriceCents,"state.lastYesPriceCents"),K(e.ticker,e.lastTimestamp);else if(e.directions.length||e.ticker||e.lastTimestamp)throw new Error("Momentum history requires a previous price, market and timestamp");if(e.position){const n=e.position;if(!n.ticker||e.ticker&&n.ticker!==e.ticker||"YES"!==n.outcome&&"NO"!==n.outcome||!Number.isSafeInteger(n.quantity)||n.quantity<=0||n.quantity>t.maxPosition||!Number.isFinite(n.entryPriceCents)||n.entryPriceCents<0||n.entryPriceCents>100)throw new Error("Invalid momentum position")}}function Z(e,t){return"YES"===t?e:100-e}function ee(e,t){return{action:"HOLD",outcome:null,ticker:e.ticker,quantity:0,priceCents:e.yesPriceCents,timestamp:e.timestamp,reason:t}}function te(e,t,n){if(z(e),H(n),Q(t,n),t.ticker&&t.ticker!==e.ticker||t.position&&t.position.ticker!==e.ticker)throw new Error("Momentum state cannot be reused across markets");if(t.lastTimestamp&&Date.parse(e.timestamp)<=Date.parse(t.lastTimestamp))throw new Error("Market ticks must have strictly increasing timestamps");const r=void 0===t.lastYesPriceCents?0:e.yesPriceCents>t.lastYesPriceCents?1:e.yesPriceCents<t.lastYesPriceCents?-1:0,o=void 0===t.lastYesPriceCents?[...t.directions]:[...t.directions,r].slice(-n.lookback),s={...t,directions:o,ticker:e.ticker,lastTimestamp:e.timestamp,lastYesPriceCents:e.yesPriceCents,position:t.position?{...t.position}:void 0};if(t.position){const r=Z(e.yesPriceCents,t.position.outcome),a=r-t.position.entryPriceCents,i=o.slice(-2),c=2===i.length&&("YES"===t.position.outcome&&i.every(e=>-1===e)||"NO"===t.position.outcome&&i.every(e=>1===e)),l=a>=n.profitTargetCents?`Profit target reached (${a}c per contract)`:a<=-n.stopLossCents?`Stop loss reached (${a}c per contract)`:c?"Momentum reversed":null;return l?{state:s,intent:{action:"SELL",outcome:t.position.outcome,ticker:e.ticker,quantity:t.position.quantity,priceCents:r,timestamp:e.timestamp,reason:l}}:{state:s,intent:ee(e,"Open position remains within exit thresholds")}}if(n.positionSize>n.maxPosition)return{state:s,intent:ee(e,"Configured position size exceeds the position limit")};if(o.length<n.momentumThreshold)return{state:s,intent:ee(e,"Waiting for enough price directions")};const a=o.slice(-n.momentumThreshold),i=a.every(e=>1===e)?"YES":a.every(e=>-1===e)?"NO":null;return i?{state:s,intent:{action:"BUY",outcome:i,ticker:e.ticker,quantity:n.positionSize,priceCents:Z(e.yesPriceCents,i),timestamp:e.timestamp,reason:`${n.momentumThreshold} consecutive YES-price ${"YES"===i?"increases":"decreases"}`}}:{state:s,intent:ee(e,"No consecutive momentum signal")}}function ne(e,t){if("FILLED"!==t.status||!t.fill||!t.intent.outcome)return e;if("BUY"!==t.intent.action&&"SELL"!==t.intent.action)return e;const n=t.portfolio.positions[`${t.intent.ticker}:${t.intent.outcome}`];return{...e,position:n?{ticker:n.ticker,outcome:n.outcome,quantity:n.quantity,entryPriceCents:n.averageEntryPriceCents}:void 0,tradesExecuted:e.tradesExecuted+1}}function re(e){return`$${(e/100).toFixed(2)}`}function oe(e,t){if(!t)return e;if(!["BUY","SELL","HOLD"].includes(t.action)||!Number.isFinite(t.confidence)||t.confidence<0||t.confidence>1||!(t.timestamp instanceof Date)||!Number.isFinite(t.timestamp.getTime())||"string"!=typeof t.reasoning)throw new Error("Research review returned an invalid TradeSignal");return t.action===e.action?e:{...e,action:"HOLD",outcome:null,quantity:0,reason:`Research review vetoed ${e.action} ${e.outcome}: ${t.reasoning}`}}function*se(e){if(!Array.isArray(e.ticks)||0===e.ticks.length)throw new Error("At least one recorded market tick is required");const t=H(e.config),n=e.initialStrategyState??{directions:[],tradesExecuted:0};Q(n,t);let r={...n,directions:[...n.directions],position:n.position?{...n.position}:void 0},o=r.lastTimestamp?Date.parse(r.lastTimestamp):-1/0;for(const h of e.ticks){if(z(h),h.ticker!==e.ticks[0].ticker||r.ticker&&h.ticker!==r.ticker)throw new Error("A momentum replay must contain ticks for exactly one market");if(Date.parse(h.timestamp)<=o)throw new Error("Market ticks must have strictly increasing timestamps");o=Date.parse(h.timestamp)}const s=e.initialCashCents??e.initialPortfolio?.initialCashCents??1e4;if(e.initialPortfolio&&s!==e.initialPortfolio.initialCashCents)throw new Error("initialCashCents must match the resumed portfolio");const a=new V({initialCashCents:s,maxPositionPerMarket:t.maxPosition,initialPortfolio:e.initialPortfolio}),i=Object.values(a.snapshot().positions),c=r.position;if(i.length!==(c?1:0)||c&&(c.ticker!==e.ticks[0].ticker||i[0].ticker!==c.ticker||i[0].outcome!==c.outcome||i[0].quantity!==c.quantity||i[0].averageEntryPriceCents!==c.entryPriceCents))throw new Error("Initial strategy position must match the paper portfolio");const l=[];for(const h of e.ticks){a.mark(h);const e=te(h,r,t),n=yield{intent:e.intent,portfolio:a.snapshot()},o=a.execute(oe(e.intent,n));r=ne(e.state,o),l.push({tick:{...h},intent:e.intent,...n?{researchSignal:{...n,timestamp:new Date(n.timestamp)}}:{},execution:o,strategyState:{...r,directions:[...r.directions],position:r.position?{...r.position}:void 0}})}const u=a.snapshot(),m=l.filter(e=>"FILLED"===e.execution.status).length,d=l.filter(e=>"REJECTED"===e.execution.status).length,p=r.position?`${r.position.quantity} ${r.position.outcome} on ${r.position.ticker}`:"none";return{mode:"paper",config:t,steps:l,strategyState:r,portfolio:u,report:["Kalshi momentum paper replay",`Ticks processed: ${l.length}`,`Paper fills: ${m}; rejected: ${d}`,`Open position: ${p}`,`Cash: ${re(u.cashCents)}`,`Realized P&L: ${re(u.realizedPnlCents)}`,`Unrealized P&L: ${re(u.unrealizedPnlCents)}`,`Equity: ${re(u.equityCents)}`].join("\n")}}function ae(e){const t=se(e);let n=t.next();for(;!n.done;)n=t.next();return n.value}async function ie(e,t){const n=se(e);let r=n.next();for(;!r.done;){const{intent:e,portfolio:o}=r.value,s="HOLD"===e.action?void 0:await t({...e},o);if("HOLD"!==e.action&&!s)throw new Error("Research review must return a TradeSignal");r=n.next(s)}return r.value}const ce="https://deep-research-api.thekid-solana.workers.dev",le=3e5;async function ue(e,t,n=3e5){const r=new AbortController,o=setTimeout(()=>r.abort(),n);try{const n=await fetch(e,{...t,signal:r.signal});return clearTimeout(o),n}catch(s){if(clearTimeout(o),s instanceof Error&&"AbortError"===s.name)throw new Error(`Request timeout after ${n}ms`);throw s}}async function me(e,t=!0){const n=function(){const e=process.env.POLYFACTUAL_API_KEY;if(!e)throw new Error("POLYFACTUAL_API_KEY environment variable is not set");return e}();if(e.length>1e3)throw new Error("Query exceeds maximum length of 1000 characters");if(!e.trim())throw new Error("Query cannot be empty");const r={query:e,text:t};console.log("Calling Polyfactual API with query:",e.substring(0,100)+(e.length>100?"...":""));const o=await ue(`${ce}/answer`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":n},body:JSON.stringify(r)},le);if(!o.ok){let e;switch(o.status){case 400:e="Bad request: Invalid query format or validation error";break;case 401:e="Unauthorized: Invalid API key";break;case 429:e="Rate limit exceeded: Please wait before making another request";break;case 500:e="Internal server error: Polyfactual service is temporarily unavailable";break;default:e=`Polyfactual API error: ${o.status} ${o.statusText}`}try{const t=await o.json();!t.success&&t.error&&(e=t.error)}catch{}throw new Error(e)}const s=await o.json();if(!s.success)throw new Error(s.error||"Unknown error from Polyfactual API");return console.log("Polyfactual response received successfully"),s}const de=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,checkPolyfactualHealth:async function(){try{return(await ue(`${ce}/health`,{method:"GET"},1e4)).ok}catch{return!1}},generatePolyfactualAnswer:me},Symbol.toStringTag,{value:"Module"}));async function pe(e){const t=Date.now(),{query:n}=e;if(!n||"string"!=typeof n)return console.log("Missing or invalid query parameter"),{success:!1,error:"Missing required parameter: 'query'",metadata:{requestId:crypto.randomUUID(),timestamp:/* @__PURE__ */(new Date).toISOString(),query:"",processingTimeMs:Date.now()-t}};const r=n.trim();if(!r)return console.log("Empty query parameter"),{success:!1,error:"Query cannot be empty",metadata:{requestId:crypto.randomUUID(),timestamp:/* @__PURE__ */(new Date).toISOString(),query:"",processingTimeMs:Date.now()-t}};try{console.log("Starting Polyfactual research for query:",r.substring(0,100));const e=(await me(r,!0)).data,n=e?.answer||JSON.stringify(e),o=e?.citations||[],s=Date.now()-t;return console.log("Request completed in",s,"ms"),{success:!0,answer:"string"==typeof n?n:JSON.stringify(n),citations:Array.isArray(o)?o:[],data:e,metadata:{requestId:crypto.randomUUID(),timestamp:/* @__PURE__ */(new Date).toISOString(),query:r,processingTimeMs:s}}}catch(o){console.error("Error:",o);const e=Date.now()-t;return{success:!1,error:o instanceof Error?o.message:"An unexpected error occurred",metadata:{requestId:crypto.randomUUID(),timestamp:/* @__PURE__ */(new Date).toISOString(),query:"",processingTimeMs:e}}}}const he={BASE_MAINNET:"eip155:8453",BASE:"base",SOLANA_MAINNET:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",SOLANA:"solana"},fe={base:8453,"eip155:8453":8453},ye={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]};function ge(){const e=process.env.X402_SOLANA_PRIVATE_KEY,t=process.env.X402_EVM_PRIVATE_KEY,n=process.env.X402_DISCOVERY_URL,r=process.env.X402_FACILITATOR_URL;return console.log("[x402] Config loaded:"),console.log("[x402] - Discovery URL:",n||"(not set)"),console.log("[x402] - EVM Private Key:",t?"(set)":"(not set)"),console.log("[x402] - Solana Private Key:",e?"(set)":"(not set)"),{solanaPrivateKey:e,evmPrivateKey:t,discoveryUrl:n,facilitatorUrl:r}}function ke(e){return"solana"===e||e.startsWith("solana:")}function we(e){return"base"===e||e.startsWith("eip155:")}function ve(e,t){if(!e)return"Unknown";try{const t=BigInt(e),n=10n**6n;return`$${(Number(t)/Number(n)).toFixed(4)}`}catch{return"Unknown"}}async function Se(e,t,n,r){console.log("[x402] Creating EVM payment header for Base mainnet...");const{ethers:o}=await(import("ethers")),s=new o.Wallet(e),a=s.address;console.log("[x402] From address:",a);const i=function(){const e=new Uint8Array(32);return crypto.getRandomValues(e),`0x${Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}`}(),c=Math.floor(Date.now()/1e3),l=c-600,u=c+(t.maxTimeoutSeconds||60),m={from:a,to:t.payTo,value:t.amount||t.maxAmountRequired||"0",validAfter:l.toString(),validBefore:u.toString(),nonce:i};console.log("[x402] Authorization:",m);const d=t.extra||{name:"USD Coin",version:"2"},p=(h=t.network,fe[h]||8453);var h;const f={name:d.name||"USD Coin",version:d.version||"2",chainId:p,verifyingContract:t.asset};console.log("[x402] Domain:",f);const y=await s.signTypedData(f,ye,{from:a,to:t.payTo,value:BigInt(t.amount||t.maxAmountRequired||"0"),validAfter:BigInt(l),validBefore:BigInt(u),nonce:i});console.log("[x402] Signature created");const g={x402Version:n,resource:r||{url:"",description:"",mimeType:"application/json"},accepted:{scheme:t.scheme||"exact",network:t.network,asset:t.asset,amount:t.amount||t.maxAmountRequired||"0",payTo:t.payTo,maxTimeoutSeconds:t.maxTimeoutSeconds||60,extra:t.extra||{}},payload:{authorization:m,signature:y}};console.log("[x402] Payment payload (v2 format):",JSON.stringify(g,null,2));return btoa(JSON.stringify(g))}function Pe(e,t){if(t?.name&&"string"==typeof t.name)return t.name;if(t?.title&&"string"==typeof t.title)return t.title;try{const t=new URL(e),n=t.pathname.split("/").filter(Boolean);if(n.length>0){return n[n.length-1].replace(/[-_]/g," ").replace(/\b\w/g,e=>e.toUpperCase())}return t.hostname}catch{return e.substring(0,30)+"..."}}function Ee(e,t){if(t?.description&&"string"==typeof t.description)return t.description;for(const n of e){if(n.description)return n.description;if(n.outputSchema?.input?.queryParams){const e=Object.entries(n.outputSchema.input.queryParams);if(e.length>0)return`Accepts: ${e.map(([e,t])=>`${e} (${t.type})`).join(", ")}`}}}function be(e){const t=[...new Set((e.accepts||[]).map(e=>e?.network).filter(e=>!!e))];let n,r="Unknown";for(const o of e.accepts||[]){const e=o?.amount||o?.maxAmountRequired;if(!e)continue;const t=ve(e,o.network);"Unknown"!==t&&("Unknown"===r||t<r)&&(r=t)}for(const o of e.accepts||[]){if(o?.outputSchema?.input?.queryParams){n=Object.entries(o.outputSchema.input.queryParams).map(([e,t])=>`${e}: ${t?.description||t?.type||"any"}`).join(", ");break}if(o?.outputSchema?.input?.bodyParams){n=Object.entries(o.outputSchema.input.bodyParams).map(([e,t])=>`${e}: ${t?.description||t?.type||"any"}`).join(", ");break}}return{id:e.resource||"",name:Pe(e.resource||"",e.metadata),description:Ee(e.accepts||[],e.metadata),resourceUrl:e.resource||"",priceUsdc:r,networks:t,lastUpdated:e.lastUpdated||/* @__PURE__ */(new Date).toISOString(),inputDescription:n}}async function Ie(e){const t=ge();if(!t.discoveryUrl)throw new Error("X402_DISCOVERY_URL environment variable is not set");const n=new URLSearchParams;e?.type&&n.set("type",e.type),e?.limit&&n.set("limit",e.limit.toString()),e?.offset&&n.set("offset",e.offset.toString());const r=n.toString(),o=`${t.discoveryUrl}${r?`?${r}`:""}`;console.log("[x402] Fetching bazaar sellers from:",o);try{const t=await fetch(o,{method:"GET",headers:{"Content-Type":"application/json",Accept:"application/json"}});if(!t.ok){let e;if((t.headers.get("content-type")||"").includes("application/json")){const n=await t.json().catch(()=>({}));e=n.error||n.message||t.statusText}else e=`Received non-JSON response (status ${t.status}). Check discovery URL configuration.`;throw new Error(`Failed to fetch bazaar sellers (${t.status}): ${e}`)}const n=await t.json();console.log("[x402] Raw response keys:",Object.keys(n));let r=[];Array.isArray(n)?r=n:n.items&&Array.isArray(n.items)?r=n.items:n.resources&&Array.isArray(n.resources)?r=n.resources:(console.log("[x402] Unexpected response structure:",JSON.stringify(n).substring(0,500)),r=[]),console.log("[x402] Found",r.length,"sellers in bazaar");let a=[];for(const e of r)try{const t=be(e);a.push(t)}catch(s){console.warn("[x402] Failed to transform seller:",e?.resource,s)}return e?.network&&(a=a.filter(t=>t.networks.includes(e.network))),a}catch(a){if(console.error("[x402] Error fetching bazaar sellers:",a),a instanceof Error)throw new Error(`x402 Bazaar error: ${a.message}. Discovery URL: ${o}`);throw a}}async function Ae(e,t,n){const r=ge();console.log("[x402] Calling seller:",e),console.log("[x402] Query:",t),n&&console.log("[x402] Preferred network:",n);try{const s=new URL(e);if(t)try{const e=JSON.parse(t);for(const[t,n]of Object.entries(e))s.searchParams.set(t,String(n))}catch{s.searchParams.set("q",t)}console.log("[x402] Request URL:",s.toString());const a=await fetch(s.toString(),{method:"GET",headers:{"Content-Type":"application/json",Accept:"application/json"}});if(console.log("[x402] Initial response status:",a.status),402!==a.status){if(a.ok){return{success:!0,data:await a.json(),paymentInfo:{network:"free"}}}const e=await a.text();throw new Error(`Unexpected response status: ${a.status}. Body: ${e.substring(0,200)}`)}const i=await a.json();console.log("[x402] Payment requirements received:",JSON.stringify(i,null,2));const c=i.x402Version||1,l=i.resource||{url:s.toString(),description:i.description||"",mimeType:i.mimeType||"application/json"};console.log("[x402] Resource info:",JSON.stringify(l));const u=i.accepts||[];console.log("[x402] Available payment options count:",u.length);for(const e of u)console.log(`[x402] Option - network: ${e.network}, scheme: ${e.scheme}, extra:`,JSON.stringify(e.extra));let m,d,p;if(n&&(m=u.find(e=>e.network===n),m&&(d=ke(m.network)?"solana":"evm")),m||(r.solanaPrivateKey&&(m=u.find(e=>ke(e.network)),m&&(d="solana",console.log("[x402] Using Solana mainnet for payment"))),!m&&r.evmPrivateKey&&(m=u.find(e=>we(e.network)),m&&(d="evm",console.log("[x402] Using EVM (Base mainnet) for payment")))),!m||!d){const e=u.map(e=>e.network).join(", "),t=[];return r.evmPrivateKey&&t.push("EVM (Base)"),r.solanaPrivateKey&&t.push("Solana"),{success:!1,error:`No compatible payment option found. Seller accepts: [${e}]. You have keys for: [${t.join(", ")||"none"}].`}}if(console.log("[x402] Selected payment network:",m.network),"solana"===d){if(!r.solanaPrivateKey)return{success:!1,error:"Solana private key not configured. Set X402_SOLANA_PRIVATE_KEY environment variable.",paymentInfo:{cost:ve(m.amount||m.maxAmountRequired,m.network),network:m.network}};p=await async function(e,t,n,r){console.log("[x402] Creating Solana payment header for mainnet...");const{Keypair:o,PublicKey:s,Transaction:a,TransactionInstruction:i,Connection:c,ComputeBudgetProgram:l}=await(import("@solana/web3.js")),{getAssociatedTokenAddress:u,createTransferCheckedInstruction:m,TOKEN_PROGRAM_ID:d,TOKEN_2022_PROGRAM_ID:p}=await(import("@solana/spl-token")),h=await(import("bs58"));let f;try{const t=h.default.decode(e);f=o.fromSecretKey(t)}catch{throw new Error("Invalid Solana private key. Must be base58 encoded.")}const y=f.publicKey;console.log("[x402] From address:",y.toBase58());const g=t.extra?.feePayer;if(!g)throw new Error("feePayer is required in paymentRequirements.extra for Solana payments");const k=new s(g);console.log("[x402] Fee payer:",k.toBase58());const w=new s(t.payTo),v=new s(t.asset),S=t.amount||t.maxAmountRequired;if(!S)throw new Error("amount or maxAmountRequired is required in paymentRequirements");const P=BigInt(S);console.log("[x402] To address:",w.toBase58()),console.log("[x402] Mint (USDC):",v.toBase58()),console.log("[x402] Amount:",P.toString());const E=await u(v,y,!1,d),b=await u(v,w,!1,d);console.log("[x402] Source ATA:",E.toBase58()),console.log("[x402] Destination ATA:",b.toBase58());const I=new c(process.env.SOLANA_RPC_URL||"https://api.mainnet-beta.solana.com","confirmed"),{blockhash:A,lastValidBlockHeight:$}=await I.getLatestBlockhash("confirmed");console.log("[x402] Got blockhash:",A.substring(0,20)+"...");const T=new a;T.feePayer=k,T.recentBlockhash=A;const x=l.setComputeUnitLimit({units:1e5}),O=l.setComputeUnitPrice({microLamports:5e4});T.add(x),T.add(O);const C=m(E,v,b,y,P,6,[],d);T.add(C),T.partialSign(f),console.log("[x402] Transaction created and partially signed");const R=T.serialize({requireAllSignatures:!1,verifySignatures:!1}).toString("base64");console.log("[x402] Transaction serialized, length:",R.length);const M={x402Version:n,resource:r||{url:"",description:"",mimeType:"application/json"},accepted:{scheme:t.scheme||"exact",network:t.network,asset:t.asset,amount:t.amount||t.maxAmountRequired||"0",payTo:t.payTo,maxTimeoutSeconds:t.maxTimeoutSeconds||60,extra:t.extra||{}},payload:{transaction:R}};console.log("[x402] Payment payload (v2 format):",JSON.stringify(M,null,2));const U=btoa(JSON.stringify(M));return console.log("[x402] Payment header created"),U}(r.solanaPrivateKey,m,c,l)}else{if(!r.evmPrivateKey)return{success:!1,error:"EVM private key not configured. Set X402_EVM_PRIVATE_KEY environment variable.",paymentInfo:{cost:ve(m.amount||m.maxAmountRequired,m.network),network:m.network}};p=await Se(r.evmPrivateKey,m,c,l)}console.log("[x402] Payment header created, making paid request...");const h=await fetch(s.toString(),{method:"GET",headers:{"Content-Type":"application/json",Accept:"application/json","PAYMENT-SIGNATURE":p,"X-Payment":p}});if(console.log("[x402] Paid response status:",h.status),!h.ok){const e=await h.text();console.error("[x402] Paid request failed:",e);try{const t=JSON.parse(e);return{success:!1,error:t.error||t.message||`Payment failed: ${h.status}`,paymentInfo:{cost:ve(m.amount||m.maxAmountRequired,m.network),network:m.network}}}catch{return{success:!1,error:`Payment failed (${h.status}): ${e.substring(0,200)}`,paymentInfo:{cost:ve(m.amount||m.maxAmountRequired,m.network),network:m.network}}}}const f=await h.text();let y;console.log("[x402] Raw seller response (first 1000 chars):",f.substring(0,1e3)),f.length>1e3&&console.log("[x402] Response truncated, total length:",f.length);try{y=JSON.parse(f);const e=JSON.stringify(y,null,2);console.log("[x402] Parsed seller response (first 1000 chars):",e.substring(0,1e3))}catch(o){console.log("[x402] Response is not JSON, returning as text"),y={rawText:f}}const g=h.headers.get("X-Payment-Receipt");return console.log("[x402] Payment receipt header:",g||"none"),{success:!0,data:y,paymentInfo:{txId:g||void 0,cost:ve(m.amount||m.maxAmountRequired,m.network),network:m.network}}}catch(s){return console.error("[x402] Error calling seller:",s),{success:!1,error:s instanceof Error?s.message:"Unknown error"}}}async function $e(){const e=ge();if(!e.discoveryUrl)return!1;try{return(await fetch(`${e.discoveryUrl}?limit=1`,{method:"GET",headers:{Accept:"application/json"}})).ok}catch{return!1}}const Te=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,NETWORKS:he,callX402Seller:Ae,checkX402Health:$e,isEvmNetwork:we,isSolanaNetwork:ke,listBazaarSellers:Ie,parseUsdcPrice:ve,transformSellerToInfo:be},Symbol.toStringTag,{value:"Module"}));async function xe(e){const t=Date.now(),n=e;console.log("[x402-seller] Action:",n.action);const{action:r}=n;try{switch(r){case"health":{const e=await $e(),n=process.env.X402_DISCOVERY_URL;return{success:!0,healthy:e,config:{discoveryUrl:n,preferredNetwork:process.env.X402_PREFERRED_NETWORK},metadata:{requestId:crypto.randomUUID(),timestamp:/* @__PURE__ */(new Date).toISOString(),processingTimeMs:Date.now()-t}}}case"list":{const e=n;try{const n=await Ie({network:e.network,type:e.type||"http",limit:e.limit,offset:e.offset});return{success:!0,sellers:n,metadata:{requestId:crypto.randomUUID(),timestamp:/* @__PURE__ */(new Date).toISOString(),processingTimeMs:Date.now()-t,total:n.length}}}catch(o){return console.error("[x402-seller] Error listing sellers:",o),{success:!1,error:o instanceof Error?o.message:"Failed to list sellers",metadata:{requestId:crypto.randomUUID(),timestamp:/* @__PURE__ */(new Date).toISOString(),processingTimeMs:Date.now()-t,total:0}}}}case"call":{const e=n;if(!e.resourceUrl)return{success:!1,error:"Missing required parameter: 'resourceUrl'"};if(!e.query)return{success:!1,error:"Missing required parameter: 'query'"};const r=e.network||he.SOLANA_MAINNET;try{const n=await Ae(e.resourceUrl,e.query,r);return{success:n.success,data:n.data,error:n.error,metadata:{requestId:crypto.randomUUID(),timestamp:/* @__PURE__ */(new Date).toISOString(),processingTimeMs:Date.now()-t,paymentTxId:n.paymentInfo?.txId,costUsdc:n.paymentInfo?.cost,network:r}}}catch(o){return console.error("[x402-seller] Error calling seller:",o),{success:!1,error:o instanceof Error?o.message:"Failed to call seller",metadata:{requestId:crypto.randomUUID(),timestamp:/* @__PURE__ */(new Date).toISOString(),processingTimeMs:Date.now()-t,network:r}}}}case"networks":{const e=he;return{success:!0,networks:[{id:e.SOLANA_MAINNET,name:"Solana Mainnet",type:"solana"},{id:e.SOLANA_DEVNET,name:"Solana Devnet",type:"solana"},{id:e.BASE_MAINNET,name:"Base Mainnet",type:"evm"},{id:e.BASE_SEPOLIA,name:"Base Sepolia",type:"evm"}],metadata:{requestId:crypto.randomUUID(),timestamp:/* @__PURE__ */(new Date).toISOString(),processingTimeMs:Date.now()-t}}}default:return{success:!1,error:`Unknown action: '${r}'. Valid actions: 'list', 'call', 'health', 'networks'`}}}catch(o){return console.error("[x402-seller] Unhandled error:",o),{success:!1,error:o instanceof Error?o.message:"An unexpected error occurred",metadata:{requestId:crypto.randomUUID(),timestamp:/* @__PURE__ */(new Date).toISOString(),processingTimeMs:Date.now()-t}}}}const Oe={BTC:"btc-updown-15m-",SOL:"sol-updown-15m-",ETH:"eth-updown-15m-",XRP:"xrp-updown-15m-"};function Ce(e,t){return`${Oe[e]}${t}`}function Re(e){return new Date(1e3*e).toISOString().slice(11,19)+" UTC"}function Me(e,t,n){return{timestamp:/* @__PURE__ */(new Date).toISOString(),level:e,message:t,details:n}}function Ue(e){const t=JSON.parse(e);if(!Array.isArray(t)||t.length<2)throw new Error(`Expected 2 token IDs, got ${t.length}`);return[t[0],t[1]]}const De="https://clob.polymarket.com",Ne="https://data-api.polymarket.com";class qe{config;logs=[];clobClient=null;constructor(e){this.config={...e,signatureType:e.signatureType??1}}getLogs(){return[...this.logs]}clearLogs(){this.logs=[]}log(e,t,n){this.logs.push(Me(e,t,n)),console.log(`[${e}] ${t}`,n||"")}async initClobClient(){if(this.clobClient)return this.clobClient;const{privateKey:n,proxyAddress:r,signatureType:o}=this.config;this.log("INFO","Initializing Polymarket CLOB client...");try{const s=new e(n),a=new t(De,137,s),i=await a.createOrDeriveApiKey();return this.log("INFO","API credentials derived successfully"),this.clobClient=new t(De,137,s,i,o,r),this.log("SUCCESS","CLOB client initialized",{funder:`${r.slice(0,10)}...${r.slice(-8)}`,signatureType:o}),this.clobClient}catch(s){const e=s instanceof Error?s.message:String(s);throw this.log("ERROR",`Failed to initialize CLOB client: ${e}`),s}}async getMarketBySlug(e){const t=`https://gamma-api.polymarket.com/markets/slug/${e}`;this.log("INFO",`Fetching market data for slug: ${e}`);try{const n=await fetch(t,{method:"GET",headers:{"Content-Type":"application/json"}});if(!n.ok){if(404===n.status)return this.log("WARN",`Market not found: ${e}`),null;throw new Error(`Gamma API error: ${n.status} ${n.statusText}`)}const r=await n.json();return this.log("SUCCESS",`Found market: ${r.title||e}`),r}catch(n){throw this.log("ERROR",`Failed to fetch market: ${n instanceof Error?n.message:String(n)}`),n}}extractTokenIds(e){const t=e.clobTokenIds;if(!t)throw new Error("No clobTokenIds found in market data");const[n,r]=Ue(t);return this.log("INFO","Extracted token IDs",{up:`${n.slice(0,16)}...${n.slice(-8)}`,down:`${r.slice(0,16)}...${r.slice(-8)}`}),{up:n,down:r}}async placeOrder(e){const{privateKey:t,proxyAddress:o}=this.config;if(!t)return this.log("ERROR","Missing private key for order placement"),{success:!1,errorMsg:"Missing private key. Please set POLYMARKET_WALLET_PRIVATE_KEY."};if(!o)return this.log("ERROR","Missing proxy address for order placement"),{success:!1,errorMsg:"Missing proxy address. Please set POLYMARKET_PROXY_WALLET_ADDRESS."};this.log("INFO",`Placing ${e.side} order`,{tokenId:`${e.tokenId.slice(0,16)}...`,price:e.price,size:Math.floor(e.size)});try{const t=await this.initClobClient(),o=await t.createAndPostOrder({tokenID:e.tokenId,price:e.price,side:"BUY"===e.side?n.BUY:n.SELL,size:Math.floor(e.size),feeRateBps:0},{tickSize:"0.01",negRisk:false},r.GTC);return this.log("SUCCESS","Order placed successfully",{orderId:o?.orderID||o?.id,status:o?.status}),{success:!0,orderId:o?.orderID||o?.id,status:o?.status||"submitted"}}catch(s){const e=s instanceof Error?s.message:String(s);return this.log("ERROR",`Failed to place order: ${e}`),{success:!1,errorMsg:e}}}async placeStraddleOrders(e,t,n){const r=n/t;this.log("INFO","Placing straddle orders",{price:`${(100*t).toFixed(1)}%`,sizeUsd:`$${n}`,shares:Math.floor(r)});return{up:await this.placeOrder({tokenId:e.up,price:t,size:r,side:"BUY"}),down:await this.placeOrder({tokenId:e.down,price:t,size:r,side:"BUY"})}}calculateLadderRungs(e,t=49,n=35,r=1.5){const o=Math.ceil(t/100*5*100)/100,s=[];for(let p=t;p>=n;p--)s.push(p);let a=[...s],i=a.length;for(;i>1;){const t=[];for(let e=0;e<i;e++){const n=Math.exp(-r*e/i);t.push(n)}const n=t.reduce((e,t)=>e+t,0);if(e*t.map(e=>e/n)[i-1]>=o)break;i--,a=s.slice(0,i)}const c=[],l=[];for(let p=0;p<i;p++){const e=Math.exp(-r*p/i);l.push(e)}const u=l.reduce((e,t)=>e+t,0),m=l.map(e=>e/u);for(let p=0;p<i;p++){const t=a[p],n=100*m[p],r=e*m[p];c.push({pricePercent:t,priceDecimal:t/100,sizeUsd:Math.round(100*r)/100,allocationPercent:Math.round(100*n)/100})}const d=a[a.length-1];return this.log("INFO",`Calculated ladder with ${i} rungs`,{maxPrice:`${t}%`,effectiveMinPrice:`${d}%`,requestedMinPrice:`${n}%`,taperFactor:r,totalBankroll:`$${e}`,minRungAllocation:`$${c[c.length-1]?.sizeUsd||0}`}),d>n&&this.log("WARN",`Bankroll too small for full ladder range. Adjusted min price from ${n}% to ${d}%`),c}async placeLadderOrders(e,t,n=49,r=35,o=1.5){const s=this.calculateLadderRungs(t,n,r,o);this.log("INFO","Placing ladder orders",{totalRungs:s.length,totalBankroll:`$${t}`,priceRange:`${n}% → ${r}%`});const a=[];let i=0;const c=2*s.length;for(const l of s){if(l.sizeUsd<1){this.log("WARN",`Skipping rung at ${l.pricePercent}% - allocation too small ($${l.sizeUsd.toFixed(2)})`);continue}const t=l.sizeUsd/l.priceDecimal;if(Math.floor(t)<5){this.log("WARN",`Skipping rung at ${l.pricePercent}% - would result in < 5 shares`);continue}this.log("INFO",`Placing ladder rung at ${l.pricePercent}%`,{sizeUsd:`$${l.sizeUsd.toFixed(2)}`,shares:Math.floor(t),allocation:`${l.allocationPercent.toFixed(1)}%`});const n=await this.placeOrder({tokenId:e.up,price:l.priceDecimal,size:t,side:"BUY"});n.success&&i++;const r=await this.placeOrder({tokenId:e.down,price:l.priceDecimal,size:t,side:"BUY"});r.success&&i++,a.push({pricePercent:l.pricePercent,sizeUsd:l.sizeUsd,up:n,down:r})}return this.log("SUCCESS","Ladder orders complete",{totalOrders:c,successfulOrders:i,successRate:`${(i/c*100).toFixed(1)}%`}),{rungs:s,results:a,totalOrders:c,successfulOrders:i}}async getPositions(e){try{const{proxyAddress:t}=this.config,n=new URLSearchParams;n.append("user",t),n.append("sizeThreshold","0"),e?.market&&n.append("market",e.market);const r=`${Ne}/positions?${n.toString()}`;this.log("INFO","Fetching positions from Data API",{user:`${t.slice(0,10)}...`,...e});const o=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`Data API error: ${o.status} ${o.statusText}`);const s=await o.json();return this.log("SUCCESS",`Found ${(s||[]).length} positions`),s||[]}catch(t){const e=t instanceof Error?t.message:String(t);return this.log("ERROR",`Failed to get positions: ${e}`),[]}}async getActivity(e){try{const{proxyAddress:t}=this.config,n=new URLSearchParams;n.append("user",t),n.append("type","TRADE"),n.append("limit","500"),e?.market&&n.append("market",e.market);const r=`${Ne}/activity?${n.toString()}`;this.log("INFO","Fetching activity from Data API",{user:`${t.slice(0,10)}...`,...e});const o=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`Data API error: ${o.status} ${o.statusText}`);const s=await o.json();return this.log("SUCCESS",`Found ${(s||[]).length} trades`),s||[]}catch(t){const e=t instanceof Error?t.message:String(t);return this.log("ERROR",`Failed to get activity: ${e}`),[]}}async getOrder(e){try{const t=await this.initClobClient();this.log("INFO",`Fetching order: ${e.slice(0,16)}...`);const n=await t.getOrder(e);return n?this.log("SUCCESS","Order found",{status:n.status,size_matched:n.size_matched,original_size:n.original_size}):this.log("WARN",`Order not found: ${e}`),n||null}catch(t){const e=t instanceof Error?t.message:String(t);return this.log("ERROR",`Failed to get order: ${e}`),null}}determinePairStatus(e,t){const n=e.shares>0,r=t.shares>0;if(!n&&!r)return e.pendingShares>0||t.pendingShares>0?"PENDING":"NO_POSITION";if(n&&!r)return"DIRECTIONAL_YES";if(!n&&r)return"DIRECTIONAL_NO";const o=e.avgPrice+t.avgPrice;return o<.995?"PROFIT_LOCKED":o<=1.005?"BREAK_EVEN":"LOSS_RISK"}async getMarketPosition(e,t,n){this.log("INFO",`Fetching position for ${e} via Data API`);try{const r=await this.getPositions(),o=r.find(e=>e.asset===t.up),s=r.find(e=>e.asset===t.down),a={shares:o?.size||0,costUsd:o?Math.round(o.size*o.avgPrice*100)/100:0,avgPrice:o?.avgPrice||0,ordersPlaced:0,ordersFilled:o?1:0,pendingShares:0},i={shares:s?.size||0,costUsd:s?Math.round(s.size*s.avgPrice*100)/100:0,avgPrice:s?.avgPrice||0,ordersPlaced:0,ordersFilled:s?1:0,pendingShares:0},c=this.determinePairStatus(a,i),l=a.shares>0,u=i.shares>0;let m=null,d=0,p=0,h=0,f=0,y=0;if(l&&u){m=Math.round(1e4*(a.avgPrice+i.avgPrice))/1e4,d=Math.min(a.shares,i.shares),p=d;const e=d*a.avgPrice,t=d*i.avgPrice;h=Math.round(100*(e+t))/100,f=Math.round(100*(p-h))/100,y=h>0?Math.round(f/h*1e4)/100:0}const g={marketSlug:e,marketTitle:n,tokenIds:t,yes:a,no:i,pairCost:m,status:c,minShares:d,guaranteedPayout:p,totalCost:h,guaranteedProfit:f,returnPercent:y,lastUpdated:/* @__PURE__ */(new Date).toISOString()};return this.log("SUCCESS","Position fetched from Data API",{status:c,pairCost:m,yesShares:a.shares,noShares:i.shares,guaranteedProfit:f>0?`$${f}`:"N/A"}),g}catch(r){const o=r instanceof Error?r.message:String(r);this.log("ERROR",`Failed to get position: ${o}`);const s={shares:0,costUsd:0,avgPrice:0,ordersPlaced:0,ordersFilled:0,pendingShares:0};return{marketSlug:e,marketTitle:n,tokenIds:t,yes:s,no:s,pairCost:null,status:"NO_POSITION",minShares:0,guaranteedPayout:0,totalCost:0,guaranteedProfit:0,returnPercent:0,lastUpdated:/* @__PURE__ */(new Date).toISOString()}}}}function Le(){const e=process.env.POLYMARKET_WALLET_PRIVATE_KEY,t=process.env.POLYMARKET_PROXY_WALLET_ADDRESS,n=parseInt(process.env.POLYMARKET_SIGNATURE_TYPE||"1",10);if(!e)throw new Error("POLYMARKET_WALLET_PRIVATE_KEY environment variable is required");if(!t)throw new Error("POLYMARKET_PROXY_WALLET_ADDRESS environment variable is required");return new qe({privateKey:e,proxyAddress:t,signatureType:n})}const Ye=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,ASSET_SLUG_PREFIXES:Oe,PolymarketClient:qe,buildMarketSlug:Ce,createClientFromEnv:Le,createLogEntry:Me,formatTimeShort:Re,parseTokenIds:Ue},Symbol.toStringTag,{value:"Module"}));async function _e(e){const t=Date.now(),n=e;let r,o,s,a,i,c,l;try{r=Le()}catch(p){return{success:!1,error:`Failed to initialize Polymarket client: ${p instanceof Error?p.message:String(p)}`,metadata:{requestId:crypto.randomUUID(),timestamp:/* @__PURE__ */(new Date).toISOString(),processingTimeMs:Date.now()-t}}}let u="",m="0.01",d=!1;try{if(n.orderParams){console.log("Using mapper mode with pre-calculated order params");const e=n.orderParams;if(!e.tokenId)return{success:!1,error:"Missing orderParams.tokenId",metadata:{requestId:crypto.randomUUID(),timestamp:/* @__PURE__ */(new Date).toISOString(),processingTimeMs:Date.now()-t}};o=e.tokenId,s=e.price,a=e.size,m=e.tickSize||"0.01",d=e.negRisk??!1,c=e.conditionId,l=e.marketSlug,i="YES",console.log("Mapper order params:",{tokenId:`${o.slice(0,16)}...`,price:s,size:a,tickSize:m,negRisk:d})}else{console.log("Using legacy mode - calculating order params");const{conditionId:e,marketSlug:m,side:d,budgetUsd:p,price:h}=n;if(!e)return{success:!1,error:"Missing required parameter: 'conditionId' or 'orderParams'",metadata:{requestId:crypto.randomUUID(),timestamp:/* @__PURE__ */(new Date).toISOString(),processingTimeMs:Date.now()-t}};if(!m)return{success:!1,error:"Missing required parameter: 'marketSlug'",metadata:{requestId:crypto.randomUUID(),timestamp:/* @__PURE__ */(new Date).toISOString(),processingTimeMs:Date.now()-t}};if(!d||"YES"!==d&&"NO"!==d)return{success:!1,error:"Invalid 'side'. Must be 'YES' or 'NO'",metadata:{requestId:crypto.randomUUID(),timestamp:/* @__PURE__ */(new Date).toISOString(),processingTimeMs:Date.now()-t}};if("number"!=typeof p||p<1||p>100)return{success:!1,error:"Invalid 'budgetUsd'. Must be between $1 and $100",metadata:{requestId:crypto.randomUUID(),timestamp:/* @__PURE__ */(new Date).toISOString(),processingTimeMs:Date.now()-t}};c=e,l=m,i=d,console.log("Fetching market data for:",l);const f=await r.getMarketBySlug(l);if(!f)return{success:!1,error:`Market not found: ${l}`,metadata:{requestId:crypto.randomUUID(),timestamp:/* @__PURE__ */(new Date).toISOString(),processingTimeMs:Date.now()-t}};if(!f.acceptingOrders)return{success:!1,error:"Market is not accepting orders",metadata:{requestId:crypto.randomUUID(),timestamp:/* @__PURE__ */(new Date).toISOString(),processingTimeMs:Date.now()-t}};if(f.closed)return{success:!1,error:"Market is closed",metadata:{requestId:crypto.randomUUID(),timestamp:/* @__PURE__ */(new Date).toISOString(),processingTimeMs:Date.now()-t}};u=f.title;const y=r.extractTokenIds(f),g=JSON.parse(f.outcomes||'["Yes", "No"]'),k=JSON.parse(f.outcomePrices||'["0.5", "0.5"]'),w=g.findIndex(e=>"yes"===e.toLowerCase()||"up"===e.toLowerCase()),v=g.findIndex(e=>"no"===e.toLowerCase()||"down"===e.toLowerCase());let S;if("YES"===i?(o=0===w?y.up:y.down,S=parseFloat(k[w>=0?w:0])):(o=0===v?y.up:y.down,S=parseFloat(k[v>=0?v:1])),s=h??S,a=p/s,Math.floor(a)<5)return{success:!1,error:`Budget too small. At current price (${(100*s).toFixed(1)}%), minimum budget is $${(5*s).toFixed(2)}`,metadata:{requestId:crypto.randomUUID(),timestamp:/* @__PURE__ */(new Date).toISOString(),processingTimeMs:Date.now()-t}}}console.log("Placing order:",{side:i,tokenId:`${o.slice(0,16)}...`,price:s,size:Math.floor(a)});const e=await r.placeOrder({tokenId:o,price:s,size:a,side:"BUY"}),p={success:e.success,orderId:e.orderId,status:e.status,errorMsg:e.errorMsg,tokenId:o,side:i,price:s,size:Math.floor(a),costUsd:Math.round(a*s*100)/100},h=Date.now()-t;return console.log("Request completed in",h,"ms"),e.success?{success:!0,data:{order:p,market:{slug:l,title:u,conditionId:c}},metadata:{requestId:crypto.randomUUID(),timestamp:/* @__PURE__ */(new Date).toISOString(),processingTimeMs:h}}:{success:!1,error:e.errorMsg||"Order placement failed",data:{order:p,market:{slug:l,title:u,conditionId:c}},metadata:{requestId:crypto.randomUUID(),timestamp:/* @__PURE__ */(new Date).toISOString(),processingTimeMs:h}}}catch(p){return console.error("Unhandled error:",p),{success:!1,error:p instanceof Error?p.message:"An unexpected error occurred",metadata:{requestId:crypto.randomUUID(),timestamp:/* @__PURE__ */(new Date).toISOString(),processingTimeMs:Date.now()-t}}}}function Fe(){const e=Math.floor(Date.now()/1e3);return 900*Math.floor(e/900)}async function je(e){const t=[];try{const{asset:r,marketSlug:o,tokenIds:s}=e;if(!r||!function(e){return["BTC","SOL","ETH","XRP"].includes(e.toUpperCase())}(r))return t.push(Me("ERROR","Invalid or missing asset",{asset:r})),{success:!1,error:"Invalid asset. Must be one of: BTC, SOL, ETH, XRP",logs:t};const a=r.toUpperCase();let i;try{i=Le()}catch(n){const e=n instanceof Error?n.message:String(n);return t.push(Me("ERROR",`Failed to initialize client: ${e}`)),{success:!1,error:`Client initialization failed: ${e}`,logs:t}}const c=Fe(),l=o||Ce(a,c);t.push(Me("INFO",`Checking position for market: ${l}`));let u,m=s;if(!m){const e=await i.getMarketBySlug(l);if(t.push(...i.getLogs()),i.clearLogs(),!e)return t.push(Me("WARN","Market not found - may not be created yet")),{success:!1,error:"Market not found - may not be created yet",logs:t};u=e.title;try{m=i.extractTokenIds(e),t.push(...i.getLogs()),i.clearLogs()}catch(n){const e=n instanceof Error?n.message:String(n);return t.push(Me("ERROR",`Failed to extract token IDs: ${e}`)),{success:!1,error:`Token extraction failed: ${e}`,logs:t}}}const d=await i.getMarketPosition(l,m,u);return t.push(...i.getLogs()),i.clearLogs(),{success:!0,data:{asset:a,position:d},logs:t}}catch(n){const e=n instanceof Error?n.message:String(n);return t.push(Me("ERROR",`Unhandled error: ${e}`)),{success:!1,error:e,logs:t}}}function Be(){const e=Math.floor(Date.now()/1e3);return 900*Math.ceil(e/900)}async function Ke(e){const t=[];try{const{asset:r,price:o,sizeUsd:s,ladder:a}=e;if(!r||!function(e){return["BTC","SOL","ETH","XRP"].includes(e.toUpperCase())}(r))return t.push(Me("ERROR","Invalid or missing asset",{asset:r})),{success:!1,error:"Invalid asset. Must be one of: BTC, SOL, ETH, XRP",logs:t};const i=r.toUpperCase(),c=a?.enabled??!1,l=o?o/100:.48,u=s||25,m={enabled:c,maxPrice:a?.maxPrice??49,minPrice:a?.minPrice??35,taperFactor:a?.taperFactor??1.5};c&&t.push(Me("INFO","Ladder mode enabled",{maxPrice:`${m.maxPrice}%`,minPrice:`${m.minPrice}%`,taperFactor:m.taperFactor,totalBankroll:`$${u}`}));const d=Be(),p=Ce(i,d);let h,f;try{h=Le()}catch(n){const e=n instanceof Error?n.message:String(n);return t.push(Me("ERROR",`Failed to initialize client: ${e}`)),{success:!1,error:`Client initialization failed: ${e}`,logs:t}}try{const e=await h.getMarketBySlug(p);if(t.push(...h.getLogs()),h.clearLogs(),e){let r;try{r=h.extractTokenIds(e),t.push(...h.getLogs()),h.clearLogs()}catch(n){const r=n instanceof Error?n.message:String(n);return t.push(Me("ERROR",`Failed to extract token IDs: ${r}`)),f={marketSlug:p,marketTitle:e.title,marketStartTime:Re(d),targetTimestamp:d,error:`Token extraction failed: ${r}`},{success:!1,error:f.error,data:{asset:i,pricePercent:100*l,sizeUsd:u,ladderMode:c,market:f},logs:t}}if(c){const n=await h.placeLadderOrders(r,u,m.maxPrice,m.minPrice,m.taperFactor);t.push(...h.getLogs()),h.clearLogs();const o=n.results.map(e=>({pricePercent:e.pricePercent,sizeUsd:e.sizeUsd,up:e.up,down:e.down}));f={marketSlug:p,marketTitle:e.title,marketStartTime:Re(d),targetTimestamp:d,ladderOrdersPlaced:o,ladderTotalOrders:n.totalOrders,ladderSuccessfulOrders:n.successfulOrders}}else{const n=await h.placeStraddleOrders(r,l,u);t.push(...h.getLogs()),h.clearLogs(),f={marketSlug:p,marketTitle:e.title,marketStartTime:Re(d),targetTimestamp:d,ordersPlaced:n}}}else f={marketSlug:p,marketStartTime:Re(d),targetTimestamp:d,error:"Market not found - may not be created yet"}}catch(n){const e=n instanceof Error?n.message:String(n);t.push(Me("ERROR",`Error processing market ${p}: ${e}`)),f={marketSlug:p,marketStartTime:Re(d),targetTimestamp:d,error:e}}return{success:!f.error,data:{asset:i,pricePercent:100*l,sizeUsd:u,ladderMode:c,market:f},logs:t}}catch(n){const e=n instanceof Error?n.message:String(n);return t.push(Me("ERROR",`Unhandled error: ${e}`)),{success:!1,error:e,logs:t}}}const ze="https://gamma-api.polymarket.com",Je=["gpt-5.2","gpt-5.1","gpt-5-nano","gpt-4.1","gpt-4.1-mini"];function We(e){return Je.includes(e)||e.startsWith("gpt-")}function Ve(e,t){return"polymarket"===e?`https://polymarket.com/event/${t}`:`https://kalshi.com/events/${t}`}async function Ge(e,t={}){const n=Date.now(),{url:r,model:o}=e;if(!r)throw new Error("Missing required parameter: 'url'");if(!o)throw new Error("Missing required parameter: 'model'");const s=function(e){const t=e.toLowerCase();return t.includes("polymarket.com")?"polymarket":t.includes("kalshi.com")?"kalshi":null}(r);if(!s)throw new Error("Invalid URL. Must be a Polymarket or Kalshi market URL.");let a=null;const i="polymarket"===s?"kalshi":"polymarket";if("polymarket"===s){const e=function(e){try{const t=new URL(e).pathname.split("/").filter(e=>e);return"event"===t[0]&&t.length>=2?t[1]:null}catch{return null}}(r);if(!e)throw new Error("Could not extract event slug from Polymarket URL");a=await async function(e){try{const t=`${ze}/events/slug/${e}`,n=await fetch(t);if(!n.ok)return console.error("Polymarket event fetch error:",n.status),null;const r=await n.json(),o=[];if(r.markets&&Array.isArray(r.markets))for(const e of r.markets){const t=e.question||e.title||"";let n=50;if(e.outcomePrices)try{const t=JSON.parse(e.outcomePrices);n=100*parseFloat(t[0])}catch{}t&&o.push({title:t,yesPrice:n})}return{eventTitle:r.title||e.replace(/-/g," "),markets:o,source:"polymarket",identifier:r.slug||e}}catch(t){return console.error("Error fetching Polymarket event:",t),null}}(e)}else{const e=function(e){try{const t=new URL(e).pathname.split("/").filter(e=>e);return("markets"===t[0]||"events"===t[0])&&t.length>=2?(t.length>=4?t[t.length-1]:t[1]).toUpperCase():null}catch{return null}}(r);if(!e)throw new Error("Could not extract ticker from Kalshi URL");a=await async function(e,t){try{const n=await A(`/event/${e}`,{params:{withNestedMarkets:!0},apiKey:t}),r=[];if(n.markets&&Array.isArray(n.markets))for(const e of n.markets){const t=e.yesSubTitle||"";let n=50;if(e.yesBid&&e.yesAsk){n=(parseFloat(e.yesBid)+parseFloat(e.yesAsk))/2*100}else e.yesBid?n=100*parseFloat(e.yesBid):e.yesAsk&&(n=100*parseFloat(e.yesAsk));t&&r.push({title:t,yesPrice:n})}return{eventTitle:n.title||e,markets:r,source:"kalshi",identifier:e}}catch(n){return console.error("Error fetching Kalshi event:",n),null}}(e,t.dflowApiKey)}if(!a||0===a.markets.length)throw new Error(`Could not fetch event data from ${s}. The event may not exist or have no markets.`);const c=await async function(e,t,n,r,o){const{systemPrompt:s,userPrompt:a}=I({title:e,sourcePlatform:t,targetPlatform:n});let i;if(We(r)){const e=await u(a,s,"text",r,1,{apiKey:o.openaiApiKey}),t=[];for(const n of e.output)if("message"===n.type){const e=n;t.push(...e.content)}i=t.map(e=>e.text).filter(e=>void 0!==e).join("").trim()}else{const e=await m(a,s,"text",r,1,void 0,{apiKey:o.xaiApiKey}),t=[];for(const n of e.output)if("message"===n.type){const e=n;t.push(...e.content)}i=t.map(e=>e.text).filter(e=>void 0!==e).join("").trim()}return i.replace(/['"]/g,"").trim().split(/\s+/).slice(0,2).join(" ")}(a.eventTitle,s,i,o,t);let l;if(l="polymarket"===i?await async function(e){try{const t=`${ze}/public-search?q=${encodeURIComponent(e)}&events_status=open`,n=await fetch(t);if(!n.ok)return console.error("Polymarket search error:",n.status),[];const r=await n.json(),o=[];if(r.events&&Array.isArray(r.events))for(const e of r.events){const t=e.slug;if(e.markets&&Array.isArray(e.markets))for(const n of e.markets){const e=n.question||n.title||"";let r=50;if(n.outcomePrices)try{const e=JSON.parse(n.outcomePrices);r=100*parseFloat(e[0])}catch{}e&&o.push({title:e,yesPrice:r,identifier:t})}}return o}catch(t){return console.error("Error searching Polymarket:",t),[]}}(c):await async function(e,t){try{const n=await A("/search",{params:{q:e,event_status:"open",withNestedMarkets:!0},apiKey:t}),r=[];if(n.events&&Array.isArray(n.events))for(const e of n.events){const t=e.ticker;if(e.markets&&Array.isArray(e.markets))for(const n of e.markets){const e=n.yesSubTitle||n.title||"";let o=50;if(n.yesAsk&&n.yesBid){o=(parseFloat(n.yesAsk)+parseFloat(n.yesBid))/2*100}else n.yesAsk?o=100*parseFloat(n.yesAsk):n.yesBid&&(o=100*parseFloat(n.yesBid));e&&r.push({title:e,yesPrice:o,identifier:t})}}return r}catch(n){return console.error("Error searching Kalshi:",n),[]}}(c,t.dflowApiKey),0===l.length){const e={source:s,name:a.eventTitle,identifier:a.identifier,yesPrice:a.markets[0]?.yesPrice||50,noPrice:100-(a.markets[0]?.yesPrice||50),url:Ve(s,a.identifier),rawData:{eventTitle:a.eventTitle,markets:a.markets}};return{analysis:{isSameMarket:!1,sameMarketConfidence:0,marketComparisonReasoning:`No matching markets found on ${i} for query "${c}"`,polymarketData:"polymarket"===s?e:void 0,kalshiData:"kalshi"===s?e:void 0,arbitrage:{hasArbitrage:!1},summary:`No matching markets found on ${i}. Cannot determine arbitrage opportunity.`,risks:["No matching market found on the other platform"],recommendation:"Try a different event or check if the market exists on both platforms."},model:"none",sourceMarket:s,searchedMarket:i,processingTimeMs:Date.now()-n}}const{analysis:d,modelUsed:p,tokensUsed:h}=await async function(e,t,n,r,o){const s={source:e.source,name:e.eventTitle,identifier:e.identifier,yesPrice:e.markets[0]?.yesPrice||50,noPrice:100-(e.markets[0]?.yesPrice||50),url:Ve(e.source,e.identifier)};s.rawData={eventTitle:e.eventTitle,markets:e.markets};const{systemPrompt:a,userPrompt:i}=b({sourceMarket:s,searchResults:t,searchPlatform:n});let c,l,d;if(We(r)){const e=await u(i,a,"json_object",r,3,{apiKey:o.openaiApiKey});l=e.model,d=e.usage?.total_tokens;const t=[];for(const n of e.output)if("message"===n.type){const e=n;t.push(...e.content)}c=t.map(e=>e.text).filter(e=>void 0!==e).join("\n")}else{const e=await m(i,a,"json_object",r,3,void 0,{apiKey:o.xaiApiKey});l=e.model,d=e.usage?.total_tokens;const t=[];for(const n of e.output)if("message"===n.type){const e=n;t.push(...e.content)}c=t.map(e=>e.text).filter(e=>void 0!==e).join("\n")}const p=JSON.parse(c);return{analysis:{isSameMarket:p.isSameMarket,sameMarketConfidence:p.sameMarketConfidence,marketComparisonReasoning:p.marketComparisonReasoning,polymarketData:"polymarket"===e.source?s:p.matchedMarket||void 0,kalshiData:"kalshi"===e.source?s:p.matchedMarket||void 0,arbitrage:p.arbitrage,summary:p.summary,risks:p.risks,recommendation:p.recommendation},modelUsed:l,tokensUsed:d}}(a,l,i,o,t);return{analysis:d,model:p,tokensUsed:h,sourceMarket:s,searchedMarket:i,processingTimeMs:Date.now()-n}}async function Xe(e,t={}){const n=Date.now(),{url:r}=e;if(!r)throw new Error("Missing required parameter: 'url'");const{pmType:o,urlSource:s}=function(e){const t=e.toLowerCase();return t.includes("jup.ag/prediction")?{pmType:"Kalshi",urlSource:"jupiter"}:t.includes("kalshi")?{pmType:"Kalshi",urlSource:"kalshi"}:t.includes("polymarket")?{pmType:"Polymarket",urlSource:"polymarket"}:{pmType:null,urlSource:null}}(r);if(!o||!s)throw new Error("Could not detect prediction market type from URL. Use Kalshi, Polymarket, or Jupiter prediction market URLs.");let a,i,c,l;if("Kalshi"===o){let e;if("jupiter"===s)e=function(e){const t=e.split("?")[0].split("/"),n=t[t.length-1];return n&&n.length>0?n.toUpperCase():null}(r);else{const t=r.split("/");e=t[t.length-1]?.toUpperCase()||null}if(!e)throw new Error("Could not extract event ticker from URL");a=e,l="dflow";try{c=await $(e,t.dflowApiKey)}catch(u){const t=u instanceof Error?u.message:"Unknown error",n=t.includes("404")||t.toLowerCase().includes("not found");throw new Error(n?`Event '${e}' not found on Kalshi (via DFlow).`:`Failed to fetch markets: ${t}`)}}else{const e=function(e){const t=e.split("?")[0].split("/");return t[t.length-1]||null}(r);if(!e)throw new Error("Could not extract event slug from URL");a=e,l="gamma";try{const{eventId:t,markets:n}=await async function(e){const t=[`https://gamma-api.polymarket.com/events?slug=${encodeURIComponent(e)}`,`https://gamma-api.polymarket.com/events/${encodeURIComponent(e)}`];for(const n of t)try{const e=await fetch(n);if(!e.ok){console.warn(`Gamma API endpoint ${n} returned ${e.status}`);continue}const t=await e.json(),r=Array.isArray(t)?t[0]:t;if(r&&r.markets&&Array.isArray(r.markets))return{eventId:void 0!==r.id&&null!==r.id?String(r.id):null,markets:r.markets}}catch(u){console.warn(`Error fetching from Gamma API ${n}:`,u)}return console.warn(`Could not fetch Polymarket event for slug ${e} from Gamma API`),{eventId:null,markets:[]}}(e);c=n,i=t||void 0}catch(u){const t=u instanceof Error?u.message:"Unknown error",n=t.includes("404")||t.toLowerCase().includes("not found");throw new Error(n?`Event '${e}' not found on Polymarket.`:`Failed to fetch markets from Polymarket: ${t}`)}}if(0===c.length)throw new Error(`No markets found for '${a}' on ${o}.`);return{eventIdentifier:a,eventId:i,pmType:o,urlSource:s,markets:c,marketsCount:c.length,dataProvider:l,processingTimeMs:Date.now()-n}}const He={id:"kalshi-momentum",upstream:"kalshi-bot-api/examples/momentum_bot.py",run(e,t){const n=H(e.config),r=e.venue??"kalshi";if(!o(t.evaluationTime))throw new Error("invalid evaluation time");if(t.account&&s(t.account).length)throw new Error("invalid momentum account");let a={directions:[],tradesExecuted:0};const i=e.ticks;for(let s=0;s<i.length;s++){const e=i[s];if(!o(e.timestamp)||Date.parse(e.timestamp)>Date.parse(t.evaluationTime)||s>0&&(e.ticker!==i[0].ticker||Date.parse(e.timestamp)<=Date.parse(i[s-1].timestamp)))throw new Error("ticks must be one market in strictly increasing UTC order without future data");s<i.length-1&&(a=te(e,a,n).state)}const c=i.at(-1);if(!c)return[{sourceId:this.id,upstream:this.upstream,kind:"signal",instrument:{type:"event",venue:r,marketId:e.marketId??"empty"},action:"HOLD",confidence:n.momentumThreshold/n.lookback,reasoning:"no ticks",asOf:t.evaluationTime}];if("event"===t.account?.kind&&t.account.venue===r){const e=Object.values(t.account.portfolio.positions).filter(e=>e.ticker===c.ticker&&e.quantity>0);if(e.length>1)throw new Error("momentum supports one outcome holding");const n=e[0];n&&(a.position={ticker:n.ticker,outcome:n.outcome,quantity:n.quantity,entryPriceCents:n.averageEntryPriceCents})}const l=te(c,a,n).intent;return[{sourceId:this.id,upstream:this.upstream,kind:"HOLD"===l.action?"signal":"order",instrument:{type:"event",venue:r,marketId:c.ticker,...l.outcome?{outcome:l.outcome}:{}},action:l.action,confidence:n.momentumThreshold/n.lookback,reasoning:`${l.reason}; confidence = momentumThreshold / lookback`,asOf:c.timestamp,..."HOLD"===l.action?{}:{order:l}}]}};function Qe(e){if(!Number.isFinite(e)||e<0||e>100)throw new Error(`invalid execution price ${e}¢`);if(Math.abs(e-Math.round(e))>=1e-9)throw new Error(`sub-cent price ${e}¢ is not executable by the paper executor`);return Math.round(e)}function Ze(e){const{proposal:t,finalQuantity:n,verdict:r,judge:o,fundManager:s}=e;if(!["BUY","SELL"].includes(t.action)||!["PROCEED","BLOCK","REDUCE"].includes(o.kind))throw new Error("invalid approval action or judge decision");if(!r.allowed||"BLOCK"===o.kind||!["APPROVE","MODIFY"].includes(s.decision)||s.proposalId!==t.proposalId||!a(n)||0===n||!a(t.quantity)||!a(r.maxQuantity)||!a(s.quantity)||n>Math.min(t.quantity,r.maxQuantity,s.quantity)||"REDUCE"===o.kind&&(!a(o.maxQuantity)||n>o.maxQuantity))throw new Error("invalid or exceeded execution approval")}function et(e){Ze(e);const t=e.proposal;if("event"!==t.instrument.type||!t.outcome||void 0===t.limitPriceCents)throw new Error("event approval required");return{action:t.action,ticker:t.instrument.marketId,outcome:t.outcome,quantity:e.finalQuantity,priceCents:Qe(t.limitPriceCents),timestamp:t.asOf,reason:`Approved ${t.proposalId}`}}function tt(e){const t=100*e;if(!Number.isFinite(t)||t<=0||!Number.isSafeInteger(Math.round(t))||Math.abs(t-Math.round(t))>=1e-9)throw new Error("unsupported stock price; fixture fills require whole cents");return Math.round(t)}function nt(e,t,n){Ze(e);const r=e.proposal;if("equity"!==r.instrument.type||!Number.isFinite(t)||t<=0||!n||"equity"!==n.kind||s(n).length)throw new Error("equity execution needs a current account and positive fixture close");const o=tt(t),a=Math.min(e.finalQuantity,"BUY"===r.action?Math.floor(n.cashCents/o):n.shares[r.instrument.symbol]?.quantity??0);if(0===a)throw new Error("zero affordable or held shares");return{symbol:r.instrument.symbol,qty:a,side:"BUY"===r.action?"buy":"sell",type:"market",time_in_force:"day"}}function rt(e,t){return{summary:"Recorded binary-contract strategy research; prices and cash are cents.",findings:[e.reason,`Strategy intent: ${e.action} ${e.outcome??""} ${e.quantity} contracts at ${e.priceCents} cents.`,"SELL closes the named outcome; it does not buy the opposite outcome."],recommendations:["Review the unchanged intent. A different action or quantity means HOLD for this replay.","Paper cash, inventory and position limits remain authoritative."],data:{intent:{...e},cashCents:t.cashCents,positions:t.positions,equityCents:t.equityCents}}}async function ot(e,t,n,r){const o=new Date(t.timestamp).toISOString(),s={sourceId:He.id,upstream:He.upstream,kind:"HOLD"===t.action?"signal":"order",instrument:{type:"event",venue:"kalshi",marketId:t.ticker,...t.outcome?{outcome:t.outcome}:{}},action:t.action,confidence:.75,reasoning:t.reason,asOf:o,..."HOLD"!==t.action?{order:{...t,timestamp:o}}:{},evidence:{research:JSON.stringify(rt(t,n))}},{state:a,signal:i}=await e.propagate(t.ticker,o.slice(0,10),{instrument:s.instrument,strategySignals:[s],account:{kind:"event",venue:"kalshi",portfolio:n},evaluationTime:o,sources:{[He.id]:He}}),c={...i,reasoning:[a.investmentDebateState.judgeDecision,a.traderInvestmentPlan,a.finalRiskAdjustedPlan,a.fundManagerDecision,a.riskReviewReason].filter(Boolean).join("\n\n")||i.reasoning},l=e=>({...c,action:"HOLD",reasoning:`${e}\n\n${c.reasoning}`});if("BUY"===t.action&&!/FINAL DECISION:\s*INVEST\s*$/i.test(a.investmentDebateState.judgeDecision))return l("Investment judge did not approve entry");if(r?.fundManagerReview||a.approval){const e=a.approval;if(!e||"APPROVE"!==e.fundManager.decision)return l("Missing explicit unchanged FundManager approval");try{const n=et(e);if(n.action!==t.action||n.outcome!==t.outcome||n.quantity!==t.quantity||n.priceCents!==t.priceCents||n.ticker!==t.ticker||Date.parse(n.timestamp)!==Date.parse(t.timestamp))return l("Approved proposal differs from the original intent")}catch{return l("Invalid execution approval")}}return c}export{rt as A,h as B,ot as C,G as D,Y as E,q as F,ae as G,ie as H,V as I,j as J,pe as K,je as L,_e as M,_ as N,Ke as O,xe as P,I as Q,c as R,Te as S,et as T,Qe as U,tt as V,He as W,nt as X,P as a,ne as b,b as c,E as d,M as e,T as f,U as g,k as h,m as i,u as j,X as k,A as l,O as m,te as n,l as o,Ge as p,R as q,Xe as r,$ as s,C as t,f as u,i as v,v as w,H as x,de as y,Ye as z};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty;const e=require("ethers"),t=require("@polymarket/clob-client"),n=require("./validate-DBxPUXqH.cjs");function r(e){if(e instanceof Error){const t=e.message.toLowerCase();return t.includes("connection")||t.includes("tls")||t.includes("timeout")||t.includes("eof")||t.includes("network")||t.includes("fetch failed")}return!1}function o(e){return new Promise(t=>setTimeout(t,e))}async function s(e,t,n=12e4){const r=new AbortController,o=setTimeout(()=>r.abort(),n);try{const n=await fetch(e,{...t,signal:r.signal});return clearTimeout(o),n}catch(s){if(clearTimeout(o),s instanceof Error&&"AbortError"===s.name)throw new Error(`Request timeout after ${n}ms`);throw s}}async function a(e,t,n,a="gpt-4.1",i=3,c={}){const l=c.apiKey??process.env.OPENAI_API_KEY;if(!l)throw new Error("OPENAI_API_KEY environment variable is not set");const u={model:a,input:[{role:"system",content:t},{role:"user",content:e}],text:{format:{type:n}}};let m=null;for(let p=0;p<=i;p++)try{const e=await s("https://api.openai.com/v1/responses",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`},body:JSON.stringify(u)},12e4);if(!e.ok){const t=await e.text(),n=new Error(`OpenAI API error: ${e.status} ${e.statusText} - ${t}`);if(e.status>=400&&e.status<500&&429!==e.status)throw n;if(m=n,p<i){const e=Math.min(1e3*Math.pow(2,p),1e4);console.warn(`OpenAI API error (attempt ${p+1}/${i+1}), retrying in ${e}ms...`),await o(e);continue}throw n}return await e.json()}catch(d){if(m=d instanceof Error?d:new Error(String(d)),!r(d)&&0===p)throw m;if(p>=i)throw m;const e=Math.min(1e3*Math.pow(2,p),1e4);console.warn(`Network error (attempt ${p+1}/${i+1}): ${m.message}. Retrying in ${e}ms...`),await o(e)}throw m||new Error("Unknown error occurred")}async function i(e,t,n,a="grok-4-1-fast-reasoning",i=3,c,l={}){const u=l.apiKey??process.env.XAI_API_KEY;if(!u)throw new Error("XAI_API_KEY environment variable is not set");const m={model:a,input:[{role:"system",content:t},{role:"user",content:e}],...c&&c.length>0&&{tools:c.map(e=>({type:e}))},response_format:{type:n}};let d=null;for(let h=0;h<=i;h++)try{const e=await s("https://api.x.ai/v1/responses",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${u}`},body:JSON.stringify(m)},12e4);if(!e.ok){const t=await e.text(),n=new Error(`Grok API error: ${e.status} ${e.statusText} - ${t}`);if(e.status>=400&&e.status<500&&429!==e.status)throw n;if(d=n,h<i){const e=Math.min(1e3*Math.pow(2,h),1e4);console.warn(`Grok API error (attempt ${h+1}/${i+1}), retrying in ${e}ms...`),await o(e);continue}throw n}return await e.json()}catch(p){if(d=p instanceof Error?p:new Error(String(p)),!r(p)&&0===h)throw d;if(h>=i)throw d;const e=Math.min(1e3*Math.pow(2,h),1e4);console.warn(`Network error (attempt ${h+1}/${i+1}): ${d.message}. Retrying in ${e}ms...`),await o(e)}throw d||new Error("Unknown error occurred")}const c="https://blockrun.ai/api/v1/chat/completions",l={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},u={"blockrun/gpt-4o":"openai/gpt-4o","blockrun/gpt-4o-mini":"openai/gpt-4o-mini","blockrun/gpt-4.1":"openai/gpt-4.1","blockrun/gpt-5":"openai/gpt-5","blockrun/o1":"openai/o1","blockrun/o3-mini":"openai/o3-mini","blockrun/claude-sonnet-4":"anthropic/claude-sonnet-4","blockrun/claude-opus-4":"anthropic/claude-opus-4","blockrun/claude-haiku":"anthropic/claude-3-5-haiku-latest","blockrun/grok-3":"xai/grok-3","blockrun/grok-3-fast":"xai/grok-3-fast","blockrun/grok-3-mini":"xai/grok-3-mini","blockrun/gemini-2.5-pro":"google/gemini-2.5-pro-preview-06-05","blockrun/gemini-2.5-flash":"google/gemini-2.5-flash-preview-05-20","blockrun/deepseek-chat":"deepseek/deepseek-chat","blockrun/deepseek-reasoner":"deepseek/deepseek-reasoner","blockrun/qwen-max":"qwen/qwen-max","blockrun/qwen-plus":"qwen/qwen-plus"};function m(e){return e.startsWith("blockrun/")||e in u}async function d(t,n,r){console.log("[BlockRun] Creating x402 payment header for Base mainnet...");const o=new e.Wallet(t),s=o.address;console.log("[BlockRun] Wallet address:",s);const a=function(){const e=new Uint8Array(32);return crypto.getRandomValues(e),`0x${Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}`}(),i=Math.floor(Date.now()/1e3),c=i-600,u=i+(n.maxTimeoutSeconds||300),m={from:s,to:n.payTo,value:n.amount||n.maxAmountRequired||"0",validAfter:c.toString(),validBefore:u.toString(),nonce:a},d=n.extra||{name:"USD Coin",version:"2"},p={name:d.name||"USD Coin",version:d.version||"2",chainId:8453,verifyingContract:n.asset},h=await o.signTypedData(p,l,{from:s,to:n.payTo,value:BigInt(n.amount||n.maxAmountRequired||"0"),validAfter:BigInt(c),validBefore:BigInt(u),nonce:a});console.log("[BlockRun] Payment signature created");const f={x402Version:n.x402Version||2,resource:{url:r,description:"BlockRun AI Chat Completion",mimeType:"application/json"},accepted:{scheme:n.scheme||"exact",network:n.network,asset:n.asset,amount:n.amount||n.maxAmountRequired||"0",payTo:n.payTo,maxTimeoutSeconds:n.maxTimeoutSeconds||300,extra:n.extra||{}},payload:{authorization:m,signature:h}};return btoa(JSON.stringify(f))}function p(e){try{const t=BigInt(e);return`$${(Number(t)/1e6).toFixed(6)}`}catch{return"Unknown"}}async function h(e,t,n,a="blockrun/gpt-4o",i=3,l=!1,m={}){const h=m.walletKey??process.env.BLOCKRUN_WALLET_KEY;if(!h)throw new Error("BLOCKRUN_WALLET_KEY environment variable is not set. BlockRun uses wallet-based micropayments instead of API keys. Set your Base chain private key (0x-prefixed hex) to use BlockRun.");const y=function(e){return e in u?u[e]:(e.includes("/"),e)}(a);console.log("[BlockRun] Using model:",y);const g={model:y,messages:[{role:"system",content:t},{role:"user",content:e}],..."json_object"===n&&{response_format:{type:"json_object"}},...l&&y.startsWith("xai/")&&{search:!0}};let k,w=null;for(let u=0;u<=i;u++)try{console.log("[BlockRun] Making request (attempt",u+1,")...");const e=await s(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(g)},12e4);if(402!==e.status){if(e.ok){return f(await e.json(),k)}const t=await e.text(),n=new Error(`BlockRun API error: ${e.status} ${e.statusText} - ${t}`);if(e.status>=400&&e.status<500&&429!==e.status)throw n;if(w=n,u<i){const e=Math.min(1e3*Math.pow(2,u),1e4);console.warn(`[BlockRun] Error (attempt ${u+1}), retrying in ${e}ms...`),await o(e);continue}throw n}const t=e.headers.get("payment-required");if(!t)throw new Error("BlockRun returned 402 but no payment-required header found");let n;try{const e=atob(t),r=JSON.parse(e),o=(r.accepts||[r]).find(e=>"eip155:8453"===e.network||"base"===e.network);if(!o)throw new Error("BlockRun does not accept Base network payments");n=o,n.x402Version=r.x402Version||2}catch(v){throw new Error(`Failed to parse payment requirements: ${v}`)}k=p(n.amount||n.maxAmountRequired||"0"),console.log("[BlockRun] Payment required:",k);const r=await d(h,n,c);console.log("[BlockRun] Making paid request...");const a=await s(c,{method:"POST",headers:{"Content-Type":"application/json","PAYMENT-SIGNATURE":r},body:JSON.stringify(g)},12e4);if(!a.ok){const e=await a.text(),t=new Error(`BlockRun payment failed: ${a.status} ${a.statusText} - ${e}`);if(a.status>=400&&a.status<500&&429!==a.status)throw t;if(w=t,u<i){const e=Math.min(1e3*Math.pow(2,u),1e4);console.warn(`[BlockRun] Payment error (attempt ${u+1}), retrying in ${e}ms...`),await o(e);continue}throw t}const l=await a.json();return console.log("[BlockRun] Request successful, cost:",k),f(l,k)}catch(P){if(w=P instanceof Error?P:new Error(String(P)),!r(P)&&0===u)throw w;if(u>=i)throw w;const e=Math.min(1e3*Math.pow(2,u),1e4);console.warn(`[BlockRun] Network error (attempt ${u+1}): ${w.message}. Retrying in ${e}ms...`),await o(e)}throw w||new Error("Unknown error occurred")}function f(e,t){const n=e.choices||[],r=e.usage||{},o=n[0]?.message?.content||"";return{created_at:e.created||Math.floor(Date.now()/1e3),id:e.id||`blockrun-${Date.now()}`,model:e.model||"unknown",object:"response",output:[{content:[{type:"output_text",text:o}],id:`msg-${Date.now()}`,role:"assistant",type:"message",status:"completed"}],temperature:null,top_p:null,usage:{input_tokens:r.prompt_tokens||0,output_tokens:r.completion_tokens||0,total_tokens:r.total_tokens||0},status:"completed",blockrun:{paymentCost:t,citations:e.citations||void 0}}}function y(){return Object.entries(u).map(([e,t])=>{const[n,r]=t.split("/");return{id:e,name:r,provider:n,description:`${n} ${r} via BlockRun x402`}})}function g(e,t,n,r,o,s){const a=o?.includes("x_search"),i=o?.includes("web_search");let c="";a&&(c+="\nYou have access to X (Twitter) search. Use it to find the latest posts, news, and sentiment about this event. When you find relevant posts that back your analysis, include their URLs in your response."),i&&(c+="\nYou have access to web search. Use it to find the latest news articles, reports, and analysis about this event. When you find relevant resources that back your analysis, include their URLs in your response.");return{systemPrompt:`You are a financial analyst expert in the field of prediction markets (posted on ${r}) that understands the latest news, events, and market trends.\nYour expertise lies in deeply analyzing prediction markets for a specific event, identifying if there's alpha (mispricing) opportunity, and providing a clear recommendation on which side (YES or NO) is more likely to win based on your analysis.\nYou always provide a short analysisSummary of your findings, less than 270 characters, that is very conversational and understandable by a non-expert who just wants to understand which side it might make more sense to buy into.\n${c}${s?`\n### VERY IMPORTANT: The user has provided specific commands that you MUST prioritize over everything else:\n${s}`:""}\nYour output is ALWAYS in JSON format and you are VERY STRICT about it. You must return valid JSON that matches the exact schema specified.`,userPrompt:`# Task: Deep Analysis of an Event's Prediction Markets\n\nYou are analyzing all markets for a specific event (${t}) to determine:\n1. Whether there is an alpha (mispricing) opportunity in any of the markets\n2. Which market has the best alpha opportunity (if any)\n3. Which side (YES or NO) is more likely to win for that market\n4. Your confidence level in this assessment\n\n## User's query/input/question About This Event\n${n}\n\n## Platform: ${r}\n\n## Event Markets (${e.length} market${1!==e.length?"s":""})\n\n${JSON.stringify(e,null,2)}\n\n## Your Analysis Process\n\n1. **Understand the event**: Review all markets to understand the overall event and how the markets relate to each other\n2. **Analyze each market**: For each market, understand the title/question, description, outcomes, and resolution rules\n3. **Assess current pricing**: \n - For Kalshi: \`last_price\` field (0-100) represents the current implied probability for YES\n - For Polymarket: \`outcomePrices\` field contains an array like ["0.21", "0.79"] where the first value is the YES probability (multiply by 100 to get percentage)\n4. **Research and assess**: Use your knowledge of current events, news, trends, and fundamental factors to estimate actual probabilities\n5. **Find the best opportunity**: Identify which market (if any) has the best alpha opportunity\n6. **Consider context**: Take into account liquidity, volume, open interest, expiration/end dates, and market status\n7. **Answer the user's question**: Address the specific question asked about this event\n\n## What is Alpha?\n\nAlpha in prediction markets occurs when there's a mispricing between:\n- **Market Probability**: The current market price represents the market's collective assessment\n- **Actual Probability**: Your assessment based on the latest information, trends, and analysis\n\n### Example:\nIf the market prices an event at 30% (YES side), but your analysis suggests it should be 60%, there's a 30-point alpha opportunity in buying YES.\nConversely, if the market prices at 70% but you believe it should be 40%, there's alpha in buying NO.\n\n## Output Format\n\nReturn your analysis in JSON format with the following fields. Focus on the SINGLE BEST market opportunity (or the most relevant market if no alpha exists):\n\n{\n "event_ticker": "string - event ticker identifier",\n "ticker": "string - market ticker identifier for the best opportunity",\n "title": "string - market title",\n "marketProbability": number - current market probability (0-100),\n "estimatedActualProbability": number - your estimated actual probability (0-100),\n "alphaOpportunity": number - the difference (positive = buy yes, negative = buy no),\n "hasAlpha": boolean - whether you believe there is meaningful alpha (|alphaOpportunity| >= 5),\n "predictedWinner": "string - either 'YES' or 'NO' - which side you think will win",\n "winnerConfidence": number - confidence that your predicted winner will win (0-100),\n "recommendedAction": "string - either 'BUY YES', 'BUY NO', or 'NO TRADE' if no alpha",\n "reasoning": "string - detailed explanation of your analysis, including relevant trends, news, and factors. If there are multiple markets, explain why you chose this one.",\n "confidence": number - your confidence in this overall assessment (0-100),\n "keyFactors": ["string"] - array of key factors influencing your assessment,\n "risks": ["string"] - array of risks that could affect your prediction,\n "questionAnswer": "string - direct answer to the user's specific query/input/question",\n "analysisSummary": "string - brief summary of your findings under 270 characters"${a?',\n "xSources": ["string"] - array of X (Twitter) post URLs that back your analysis (include 2-4 relevant posts)':""}${i?',\n "webSources": ["string"] - array of web URLs (news articles, reports, etc.) that back your analysis (include 2-4 relevant resources)':""}\n}\n\n## Important Notes\n\n- Be thorough in your analysis - consider all markets for this event\n- If there are multiple markets, explain why you selected the one you did as the best opportunity\n- Consider both sides of the argument before making your recommendation\n- If you don't find meaningful alpha (|alphaOpportunity| < 5) in ANY market, set hasAlpha to false and recommendedAction to "NO TRADE"\n- Your predictedWinner should be the side you think will ultimately win (YES or NO), regardless of alpha\n- winnerConfidence is specifically about which side wins, while confidence is about your overall analysis quality\n- Be conservative with confidence scores - only assign high confidence when you have strong evidence\n- Your reasoning should be specific and reference actual trends, news, or data when possible\n- Address the user's query/input/question directly in the questionAnswer field\n- The analysisSummary should be conversational and to-the-point, no hype or emojis${a?"\n- IMPORTANT: Include 2-4 relevant X (Twitter) post URLs in xSources that back your analysis - these should be real posts you found via search":""}${i?"\n- IMPORTANT: Include 2-4 relevant web URLs (news articles, reports) in webSources that back your analysis - these should be real resources you found via search":""}\n${s?`\n### VERY IMPORTANT:Below are the user commands - Make sure to prioritize their ask over everything else\n${s}\n`:""}\nNow analyze these markets and provide your assessment. Return your response in the exact JSON format specified above.`}}function k(e,t,n,r){const o=e.length>0?e.map((e,t)=>`\n### Agent ${t+1}: ${e.model}\n- **Ticker**: ${e.analysis.ticker}\n- **Title**: ${e.analysis.title}\n- **Market Probability**: ${e.analysis.marketProbability}%\n- **Estimated Actual Probability**: ${e.analysis.estimatedActualProbability}%\n- **Alpha Opportunity**: ${e.analysis.alphaOpportunity>0?"+":""}${e.analysis.alphaOpportunity}%\n- **Has Alpha**: ${e.analysis.hasAlpha}\n- **Predicted Winner**: ${e.analysis.predictedWinner}\n- **Winner Confidence**: ${e.analysis.winnerConfidence}%\n- **Recommended Action**: ${e.analysis.recommendedAction}\n- **Confidence**: ${e.analysis.confidence}%\n- **Reasoning**: ${e.analysis.reasoning}\n- **Key Factors**: ${e.analysis.keyFactors.join("; ")}\n- **Risks**: ${e.analysis.risks.join("; ")}\n- **Analysis Summary**: ${e.analysis.analysisSummary}\n`).join("\n"):"(No AI agent analyses provided)",s=t.length>0?t.map((e,t)=>`\n### PayAI Data Source ${t+1}: ${e.seller}\n- **Query**: ${e.query}\n- **Response Data** (first 3000 chars):\n\`\`\`\n${e.response}\n\`\`\`\n`).join("\n"):"";e.length,t.length;return{systemPrompt:"You are a senior financial analyst who specializes in synthesizing multiple expert opinions on prediction markets.\nYour task is to combine and consolidate analyses from multiple AI agents and external data sources (PayAI sellers) into a single, authoritative assessment.\nYou weigh each agent's analysis based on their confidence levels and the consistency of their reasoning.\nWhen agents disagree, you provide balanced perspective on both sides before making a final recommendation.\nYou also incorporate external data from PayAI sellers (news, research, etc.) to inform your assessment.\nYour output is ALWAYS in JSON format and you are VERY STRICT about it. You must return valid JSON that matches the exact schema specified.",userPrompt:`# Task: Aggregate Multiple Data Sources\n\nYou are consolidating data from ${[e.length>0?`${e.length} AI agent${e.length>1?"s":""}`:"",t.length>0?`${t.length} PayAI data source${t.length>1?"s":""}`:""].filter(Boolean).join(" and ")} for the ${r} event: ${n}\n\n## Individual Agent Analyses\n${o}\n${s?`\n## PayAI External Data Sources\n${s}`:""}\n\n## Your Task\n\nReview all data sources and create a consolidated assessment that:\n1. **Identifies consensus**: Where do AI agents agree?\n2. **Highlights disagreements**: Where do agents disagree, and what are the arguments on each side?\n3. **Weighs confidence**: Give more weight to high-confidence analyses with strong reasoning\n4. **Incorporates external data**: Use PayAI data sources (news, research, etc.) to inform and validate agent analyses\n5. **Synthesizes findings**: Create a final recommendation that accounts for all perspectives and external data\n\n## Output Format\n\nReturn your consolidated analysis in JSON format:\n\n{\n "event_ticker": "string - event identifier",\n "ticker": "string - the market ticker most agents recommend or the best opportunity",\n "title": "string - market title",\n "marketProbability": number - consensus market probability (0-100),\n "estimatedActualProbability": number - consolidated estimated probability (0-100),\n "alphaOpportunity": number - consolidated alpha assessment,\n "hasAlpha": boolean - whether consolidated view shows meaningful alpha,\n "predictedWinner": "string - either 'YES' or 'NO'",\n "winnerConfidence": number - consolidated confidence (0-100),\n "recommendedAction": "string - either 'BUY YES', 'BUY NO', or 'NO TRADE'",\n "reasoning": "string - synthesized reasoning that accounts for all agent perspectives, noting agreements and disagreements",\n "confidence": number - overall consolidated confidence (0-100),\n "keyFactors": ["string"] - combined and deduplicated key factors from all agents,\n "risks": ["string"] - combined and deduplicated risks from all agents,\n "questionAnswer": "string - consolidated answer based on all agent analyses",\n "analysisSummary": "string - brief consolidated summary under 270 characters",\n "agentConsensus": {\n "agreementLevel": "string - 'high' (>80% agree), 'medium' (50-80%), or 'low' (<50%)",\n "majorityRecommendation": "string - what most agents recommended",\n "dissenting": ["string"] - any dissenting opinions summarized\n }\n}\n\n## Important Notes\n\n- If agents strongly disagree (low consensus), be more conservative with confidence\n- Highlight when there's unanimous agreement vs split opinions\n- The agentConsensus field helps users understand how aligned the agents were\n- Your reasoning should explicitly mention which agents agreed/disagreed and why\n- Be balanced - don't ignore minority opinions if they have valid points\n- PayAI external data (news, research) should be used to validate and inform agent analyses\n- If external data contradicts agent analyses, note this in your reasoning\n- External data is especially useful for recent events or time-sensitive information\n\nNow consolidate all data sources and provide your synthesized assessment.`}}function w(e){const{sourceMarket:t,searchResults:n,searchPlatform:r}=e,o="polymarket"===r?"Polymarket":"Kalshi";return{systemPrompt:"You are an expert financial analyst specializing in prediction market arbitrage opportunities.\n\nYour task is to:\n1. Determine if the source market and any of the search results represent the SAME underlying event/question\n2. If they do, calculate whether there's an arbitrage opportunity based on price differences\n3. Provide clear, actionable analysis\n\nYou understand that arbitrage in prediction markets works as follows:\n- If you can buy YES on one market and NO on another market for the same event\n- And the combined cost is less than $1.00 (or 100%), you have guaranteed profit\n- The profit = $1.00 - (YES price + NO price)\n\nImportant considerations:\n- Markets must represent the EXACT same event with the same resolution criteria\n- Even small wording differences can lead to different outcomes\n- Be conservative in matching - when in doubt, say they're NOT the same market\n- Consider timing differences (different end dates = different markets)\n\nYour output must be valid JSON matching the exact schema specified.",userPrompt:`# Arbitrage Analysis Task\n\n## Source Market (from ${"polymarket"===t.source?"Polymarket":"Kalshi"})\n\n**Name:** ${t.name}\n**Identifier:** ${t.identifier}\n**YES Price:** ${t.yesPrice}% \n**NO Price:** ${t.noPrice}%\n**URL:** ${t.url}\n\n${t.rawData?`**Raw Data:**\n\`\`\`json\n${JSON.stringify(t.rawData,null,2)}\n\`\`\``:""}\n\n## Search Results from ${o}\n\n${0===n.length?"No matching markets found on "+o:`Found ${n.length} potential matches:\n\n\`\`\`json\n${JSON.stringify(n,null,2)}\n\`\`\``}\n\n## Your Analysis Task\n\n1. **Market Matching**: Examine each search result and determine if ANY of them represent the SAME event as the source market. Consider:\n - Is the question/title asking about the same thing?\n - Are the resolution criteria likely to be the same?\n - Are the time frames compatible?\n - Could slight wording differences lead to different outcomes?\n\n2. **If Same Market Found**: Calculate the arbitrage opportunity:\n - Compare YES prices across both markets\n - Compare NO prices across both markets\n - The arb exists if: (lowest YES price) + (lowest NO price) < 100\n - Calculate exact profit percentage\n\n3. **Build Response**: Return your analysis in the exact JSON format below.\n\n## Output Format\n\nReturn a JSON object with this exact structure:\n\n{\n "isSameMarket": boolean,\n "sameMarketConfidence": number (0-100),\n "marketComparisonReasoning": "string explaining why you believe the markets are/aren't the same",\n "matchedMarket": {\n "source": "${r}",\n "name": "string - market title/name",\n "identifier": "string - the identifier field from the matched search result",\n "yesPrice": number (0-100),\n "noPrice": number (0-100),\n "volume": number or null,\n "liquidity": number or null,\n "url": "string - market URL (see URL format below)"\n } or null if no match found,\n "arbitrage": {\n "hasArbitrage": boolean,\n "profitPercent": number or null,\n "strategy": {\n "buyYesOn": "${t.source}" or "${r}",\n "buyYesPrice": number,\n "buyNoOn": "${t.source}" or "${r}",\n "buyNoPrice": number,\n "totalCost": number,\n "guaranteedPayout": 100,\n "netProfit": number\n } or null\n },\n "summary": "string - 2-3 sentence summary of findings",\n "risks": ["array of strings - potential risks or caveats"],\n "recommendation": "string - clear actionable recommendation"\n}\n\n## Important Notes\n\n- For Polymarket markets, the URL format is: https://polymarket.com/event/[identifier]\n- For Kalshi markets, the URL format is: https://kalshi.com/events/[identifier]\n- Each search result has an "identifier" field - use it to build the URL\n- ${"polymarket"===r?"Polymarket prices in outcomePrices are decimals (0.45 = 45%)":"Kalshi prices are already in percentage (45 = 45%)"}\n- Only report arbitrage if you're at least 80% confident the markets are the same\n- If no matching market is found, set isSameMarket to false and explain why\n\nNow analyze the markets and provide your assessment.`}}function v(e){const{title:t,sourcePlatform:n,targetPlatform:r}=e;return{systemPrompt:'You are a search query optimizer for prediction markets.\n\nYour task is to extract the 1-2 MOST IMPORTANT keywords from an event title that would best match similar events on another platform.\n\nRules:\n1. Return ONLY 1-2 words, no more\n2. Focus on unique identifiers: names, specific events, dates, numbers\n3. Remove common words like "will", "the", "be", "in", etc.\n4. Prioritize proper nouns (people, companies, places)\n5. If there\'s a person\'s name, that\'s usually the best keyword\n6. For numeric targets (prices, percentages), include the key number\n\nExamples:\n- "Will Bitcoin reach $100,000 by end of 2025?" → "Bitcoin"\n- "Will Elon Musk tweet about Dogecoin this week?" → "Elon Musk"\n- "Jensen Huang mentions at CES 2026" → "Jensen"\n- "Will the Fed cut interest rates in January?" → "Fed rates"\n- "Trump wins 2024 election" → "Trump"\n- "Apple stock above $200" → "Apple"\n\nReturn ONLY the search query, nothing else. No quotes, no explanation.',userPrompt:`Extract the best 1-2 word search query from this ${n} event title to search on ${r}:\n\n"${t}"\n\nSearch query:`}}async function P(e,t={}){const{method:n="GET",headers:r={},params:o={},apiKey:s}=t,a=function(e){const t=e??process.env.DFLOW_API_KEY;if(!t)throw new Error("DFLOW_API_KEY is not configured. Get your API key from DFlow: https://x.com/dflow");return t}(s),i=new URLSearchParams;Object.entries(o).forEach(([e,t])=>{null!=t&&i.append(e,String(t))});const c=i.toString(),l=`https://a.prediction-markets-api.dflow.net/api/v1${e}${c?`?${c}`:""}`,u=await fetch(l,{method:n,headers:{"Content-Type":"application/json","x-api-key":a,...r}});if(!u.ok){const e=await u.text();throw new Error(`DFlow API error: ${u.status} ${u.statusText} - ${e}`)}return await u.json()}async function S(e,t){return(await P(`/event/${e}`,{params:{withNestedMarkets:!0},apiKey:t})).markets}function b(e){const t=e??process.env.DOME_API_KEY;if(!t)throw new Error("DOME_API_KEY environment variable is not set");return t}async function E(e,t={}){const{method:n="GET",headers:r={},params:o={},apiKey:s}=t,a=new URLSearchParams;Object.entries(o).forEach(([e,t])=>{null!=t&&a.append(e,String(t))});const i=a.toString(),c=`https://api.domeapi.io/v1${e}${i?`?${i}`:""}`,l=await fetch(c,{method:n,headers:{"Content-Type":"application/json",Authorization:`Bearer ${b(s)}`,...r}});if(!l.ok){const e=await l.text();throw new Error(`Dome API error: ${l.status} ${l.statusText} - ${e}`)}return await l.json()}const I=["gpt-5.2","gpt-5.1","gpt-5-nano","gpt-4.1","gpt-4.1-mini"];function x(e){return m(e)?"blockrun":function(e){return I.includes(e)||e.startsWith("gpt-")}(e)?"openai":"grok"}const A=["gpt-5.2","gpt-5.1","gpt-5-nano","gpt-4.1","gpt-4.1-mini"];class $ extends Error{constructor(e="Agents recommend NO TRADE - no order to place"){super(e),this.name="NoTradeError"}}function O(e,t,n){if(t.closed)throw new Error("Market is closed");if(!1===t.acceptingOrders)throw new Error("Market is not accepting orders");if(!t.clobTokenIds)throw new Error("Missing clobTokenIds in market data");const[r,o]=function(e){try{const t=JSON.parse(e);if(Array.isArray(t)&&t.length>=2)return[t[0],t[1]];throw new Error("Invalid token IDs format")}catch{throw new Error(`Failed to parse clobTokenIds: ${e}`)}}(t.clobTokenIds),s=function(e){try{return JSON.parse(e)}catch{return["Yes","No"]}}(t.outcomes||'["Yes", "No"]'),a=function(e){try{return JSON.parse(e).map(e=>parseFloat(e))}catch{return[.5,.5]}}(t.outcomePrices||'["0.5", "0.5"]'),i="BUY YES"===e.recommendedAction,c=i?"YES":"NO",l=s.findIndex(e=>"yes"===e.toLowerCase()||"up"===e.toLowerCase()),u=s.findIndex(e=>"no"===e.toLowerCase()||"down"===e.toLowerCase());let m,d;i?(m=0===l?r:o,d=a[l>=0?l:0]):(m=0===u?r:o,d=a[u>=0?u:1]);const p=t.minimumTickSize||"0.01",h=t.negRisk??false,f=function(e,t){const n=parseFloat(t);return Math.round(e/n)*n}(d,p),y=n/f,g=Math.floor(y);if(g<5)throw new Error(`Budget too small. At current price (${(100*f).toFixed(1)}%), minimum budget is $${(5*f).toFixed(2)} for 5 shares`);const k=`BUY ${g} shares of ${c} @ ${(100*f).toFixed(1)}% for ~$${(g*f).toFixed(2)} on "${t.title||t.question||"Unknown Market"}"`;return{tokenId:m,price:f,side:"BUY",size:g,feeRateBps:0,tickSize:p,negRisk:h,conditionId:t.conditionId||"",marketSlug:t.slug||"",orderDescription:k}}function T(e,t){if(!Number.isInteger(e)||e<0||e>100)throw new Error(`${t} must be an integer from 0 through 100`)}function C(e,t){if("string"!=typeof e||!e.trim()||e!==e.trim())throw new Error("ticker must be a non-empty market identifier without surrounding whitespace");if("string"!=typeof t||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/.test(t)||!Number.isFinite(Date.parse(t))||new Date(`${t.slice(0,10)}T00:00:00.000Z`).toISOString().slice(0,10)!==t.slice(0,10))throw new Error("timestamp must be a valid ISO date-time with an explicit timezone")}function R(e){if(!e)throw new Error("A market tick is required");C(e.ticker,e.timestamp),T(e.yesPriceCents,"tick.yesPriceCents")}function M(e,t){return`${e}:${t}`}function U(e){if(!e.positions||"object"!=typeof e.positions||Array.isArray(e.positions))throw new Error("Initial paper portfolio positions must be a position map");return{...e,positions:Object.fromEntries(Object.entries(e.positions).map(([e,t])=>[e,{...t}]))}}class D{state;maxPositionPerMarket;constructor(e){if(!Number.isSafeInteger(e.initialCashCents)||e.initialCashCents<0)throw new Error("initialCashCents must be a non-negative integer");if(!Number.isSafeInteger(e.maxPositionPerMarket)||e.maxPositionPerMarket<=0)throw new Error("maxPositionPerMarket must be a positive integer");this.maxPositionPerMarket=e.maxPositionPerMarket,this.state=e.initialPortfolio?U(e.initialPortfolio):{initialCashCents:e.initialCashCents,cashCents:e.initialCashCents,positions:{},realizedPnlCents:0,unrealizedPnlCents:0,equityCents:e.initialCashCents},this.validateInitialPortfolio(),this.revalue()}mark(e){R(e);for(const t of["YES","NO"]){const n=this.state.positions[M(e.ticker,t)];n&&(n.markPriceCents="YES"===t?e.yesPriceCents:100-e.yesPriceCents)}return this.revalue(),this.snapshot()}execute(e){try{C(e.ticker,e.timestamp),T(e.priceCents,"priceCents")}catch(s){return this.reject(e,s.message)}if("BUY"!==e.action&&"SELL"!==e.action&&"HOLD"!==e.action)return this.reject(e,"action must be BUY, SELL or HOLD");if("HOLD"===e.action)return null!==e.outcome||0!==e.quantity?this.reject(e,"HOLD requires a null outcome and zero quantity"):{status:"SKIPPED",intent:e,reason:e.reason,portfolio:this.snapshot()};if("YES"!==e.outcome&&"NO"!==e.outcome||!Number.isSafeInteger(e.quantity)||e.quantity<=0)return this.reject(e,"Executable intents require an outcome and positive integer quantity");const t=M(e.ticker,e.outcome),n=this.state.positions[t];if("BUY"===e.action){const r=(n?.quantity??0)+e.quantity;if(Object.values(this.state.positions).filter(t=>t.ticker===e.ticker).reduce((e,t)=>e+t.quantity,0)+e.quantity>this.maxPositionPerMarket)return this.reject(e,"Position limit exceeded");const o=e.priceCents*e.quantity;if(!Number.isSafeInteger(o))return this.reject(e,"Order cost exceeds safe integer cents");if(o>this.state.cashCents)return this.reject(e,"Insufficient paper cash");const s=n?n.averageEntryPriceCents*n.quantity:0,a={ticker:e.ticker,outcome:e.outcome,quantity:r,averageEntryPriceCents:(s+o)/r,markPriceCents:e.priceCents,unrealizedPnlCents:0};return this.state.cashCents-=o,this.state.positions[t]=a,this.revalue(),{status:"FILLED",intent:e,fill:{priceCents:e.priceCents,quantity:e.quantity,cashChangeCents:-o,realizedPnlCents:0},portfolio:this.snapshot()}}if(!n||n.quantity<e.quantity)return this.reject(e,"Insufficient paper position");const r=e.priceCents*e.quantity;if(!Number.isSafeInteger(this.state.cashCents+r))return this.reject(e,"Paper cash exceeds safe integer cents");const o=(e.priceCents-n.averageEntryPriceCents)*e.quantity;return n.quantity-=e.quantity,n.markPriceCents=e.priceCents,this.state.cashCents+=r,this.state.realizedPnlCents+=o,0===n.quantity&&delete this.state.positions[t],this.revalue(),{status:"FILLED",intent:e,fill:{priceCents:e.priceCents,quantity:e.quantity,cashChangeCents:r,realizedPnlCents:o},portfolio:this.snapshot()}}snapshot(){return U(this.state)}reject(e,t){return{status:"REJECTED",intent:e,reason:t,portfolio:this.snapshot()}}validateInitialPortfolio(){const e=this.state;if(!Number.isSafeInteger(e.initialCashCents)||e.initialCashCents<0||!Number.isSafeInteger(e.cashCents)||e.cashCents<0||!Number.isFinite(e.realizedPnlCents))throw new Error("Invalid initial paper portfolio cash or realized P&L");const t=new Map;for(const[n,r]of Object.entries(e.positions)){if("string"!=typeof r.ticker||!r.ticker.trim()||r.ticker!==r.ticker.trim()||"YES"!==r.outcome&&"NO"!==r.outcome||n!==M(r.ticker,r.outcome)||!Number.isSafeInteger(r.quantity)||r.quantity<=0||!Number.isFinite(r.averageEntryPriceCents)||r.averageEntryPriceCents<0||r.averageEntryPriceCents>100)throw new Error("Invalid initial paper position");T(r.markPriceCents,"position.markPriceCents");const e=(t.get(r.ticker)??0)+r.quantity;if(e>this.maxPositionPerMarket)throw new Error("Initial portfolio exceeds position limit");t.set(r.ticker,e)}}revalue(){let e=0,t=0;for(const n of Object.values(this.state.positions))n.unrealizedPnlCents=(n.markPriceCents-n.averageEntryPriceCents)*n.quantity,e+=n.markPriceCents*n.quantity,t+=n.unrealizedPnlCents;this.state.unrealizedPnlCents=t,this.state.equityCents=this.state.cashCents+e}}const N={lookback:5,momentumThreshold:3,positionSize:10,profitTargetCents:5,stopLossCents:3,maxPosition:50};function q(){return{directions:[],tradesExecuted:0}}function L(e={}){const t={...N,...e};for(const[n,r]of Object.entries(t))if(!Number.isSafeInteger(r)||r<=0)throw new Error(`${n} must be a positive integer`);if(t.momentumThreshold>t.lookback)throw new Error("momentumThreshold cannot exceed lookback");return t}function Y(e,t){if(!Array.isArray(e.directions)||e.directions.length>t.lookback||e.directions.some(e=>-1!==e&&0!==e&&1!==e)||!Number.isSafeInteger(e.tradesExecuted)||e.tradesExecuted<0)throw new Error("Invalid momentum history or trade count");if(void 0!==e.lastYesPriceCents)T(e.lastYesPriceCents,"state.lastYesPriceCents"),C(e.ticker,e.lastTimestamp);else if(e.directions.length||e.ticker||e.lastTimestamp)throw new Error("Momentum history requires a previous price, market and timestamp");if(e.position){const n=e.position;if(!n.ticker||e.ticker&&n.ticker!==e.ticker||"YES"!==n.outcome&&"NO"!==n.outcome||!Number.isSafeInteger(n.quantity)||n.quantity<=0||n.quantity>t.maxPosition||!Number.isFinite(n.entryPriceCents)||n.entryPriceCents<0||n.entryPriceCents>100)throw new Error("Invalid momentum position")}}function _(e,t){return"YES"===t?e:100-e}function j(e,t){return{action:"HOLD",outcome:null,ticker:e.ticker,quantity:0,priceCents:e.yesPriceCents,timestamp:e.timestamp,reason:t}}function B(e,t,n){if(R(e),L(n),Y(t,n),t.ticker&&t.ticker!==e.ticker||t.position&&t.position.ticker!==e.ticker)throw new Error("Momentum state cannot be reused across markets");if(t.lastTimestamp&&Date.parse(e.timestamp)<=Date.parse(t.lastTimestamp))throw new Error("Market ticks must have strictly increasing timestamps");const r=void 0===t.lastYesPriceCents?0:e.yesPriceCents>t.lastYesPriceCents?1:e.yesPriceCents<t.lastYesPriceCents?-1:0,o=void 0===t.lastYesPriceCents?[...t.directions]:[...t.directions,r].slice(-n.lookback),s={...t,directions:o,ticker:e.ticker,lastTimestamp:e.timestamp,lastYesPriceCents:e.yesPriceCents,position:t.position?{...t.position}:void 0};if(t.position){const r=_(e.yesPriceCents,t.position.outcome),a=r-t.position.entryPriceCents,i=o.slice(-2),c=2===i.length&&("YES"===t.position.outcome&&i.every(e=>-1===e)||"NO"===t.position.outcome&&i.every(e=>1===e)),l=a>=n.profitTargetCents?`Profit target reached (${a}c per contract)`:a<=-n.stopLossCents?`Stop loss reached (${a}c per contract)`:c?"Momentum reversed":null;return l?{state:s,intent:{action:"SELL",outcome:t.position.outcome,ticker:e.ticker,quantity:t.position.quantity,priceCents:r,timestamp:e.timestamp,reason:l}}:{state:s,intent:j(e,"Open position remains within exit thresholds")}}if(n.positionSize>n.maxPosition)return{state:s,intent:j(e,"Configured position size exceeds the position limit")};if(o.length<n.momentumThreshold)return{state:s,intent:j(e,"Waiting for enough price directions")};const a=o.slice(-n.momentumThreshold),i=a.every(e=>1===e)?"YES":a.every(e=>-1===e)?"NO":null;return i?{state:s,intent:{action:"BUY",outcome:i,ticker:e.ticker,quantity:n.positionSize,priceCents:_(e.yesPriceCents,i),timestamp:e.timestamp,reason:`${n.momentumThreshold} consecutive YES-price ${"YES"===i?"increases":"decreases"}`}}:{state:s,intent:j(e,"No consecutive momentum signal")}}function F(e,t){if("FILLED"!==t.status||!t.fill||!t.intent.outcome)return e;if("BUY"!==t.intent.action&&"SELL"!==t.intent.action)return e;const n=t.portfolio.positions[`${t.intent.ticker}:${t.intent.outcome}`];return{...e,position:n?{ticker:n.ticker,outcome:n.outcome,quantity:n.quantity,entryPriceCents:n.averageEntryPriceCents}:void 0,tradesExecuted:e.tradesExecuted+1}}function K(e){return`$${(e/100).toFixed(2)}`}function z(e,t){if(!t)return e;if(!["BUY","SELL","HOLD"].includes(t.action)||!Number.isFinite(t.confidence)||t.confidence<0||t.confidence>1||!(t.timestamp instanceof Date)||!Number.isFinite(t.timestamp.getTime())||"string"!=typeof t.reasoning)throw new Error("Research review returned an invalid TradeSignal");return t.action===e.action?e:{...e,action:"HOLD",outcome:null,quantity:0,reason:`Research review vetoed ${e.action} ${e.outcome}: ${t.reasoning}`}}function*J(e){if(!Array.isArray(e.ticks)||0===e.ticks.length)throw new Error("At least one recorded market tick is required");const t=L(e.config),n=e.initialStrategyState??{directions:[],tradesExecuted:0};Y(n,t);let r={...n,directions:[...n.directions],position:n.position?{...n.position}:void 0},o=r.lastTimestamp?Date.parse(r.lastTimestamp):-1/0;for(const h of e.ticks){if(R(h),h.ticker!==e.ticks[0].ticker||r.ticker&&h.ticker!==r.ticker)throw new Error("A momentum replay must contain ticks for exactly one market");if(Date.parse(h.timestamp)<=o)throw new Error("Market ticks must have strictly increasing timestamps");o=Date.parse(h.timestamp)}const s=e.initialCashCents??e.initialPortfolio?.initialCashCents??1e4;if(e.initialPortfolio&&s!==e.initialPortfolio.initialCashCents)throw new Error("initialCashCents must match the resumed portfolio");const a=new D({initialCashCents:s,maxPositionPerMarket:t.maxPosition,initialPortfolio:e.initialPortfolio}),i=Object.values(a.snapshot().positions),c=r.position;if(i.length!==(c?1:0)||c&&(c.ticker!==e.ticks[0].ticker||i[0].ticker!==c.ticker||i[0].outcome!==c.outcome||i[0].quantity!==c.quantity||i[0].averageEntryPriceCents!==c.entryPriceCents))throw new Error("Initial strategy position must match the paper portfolio");const l=[];for(const h of e.ticks){a.mark(h);const e=B(h,r,t),n=yield{intent:e.intent,portfolio:a.snapshot()},o=a.execute(z(e.intent,n));r=F(e.state,o),l.push({tick:{...h},intent:e.intent,...n?{researchSignal:{...n,timestamp:new Date(n.timestamp)}}:{},execution:o,strategyState:{...r,directions:[...r.directions],position:r.position?{...r.position}:void 0}})}const u=a.snapshot(),m=l.filter(e=>"FILLED"===e.execution.status).length,d=l.filter(e=>"REJECTED"===e.execution.status).length,p=r.position?`${r.position.quantity} ${r.position.outcome} on ${r.position.ticker}`:"none";return{mode:"paper",config:t,steps:l,strategyState:r,portfolio:u,report:["Kalshi momentum paper replay",`Ticks processed: ${l.length}`,`Paper fills: ${m}; rejected: ${d}`,`Open position: ${p}`,`Cash: ${K(u.cashCents)}`,`Realized P&L: ${K(u.realizedPnlCents)}`,`Unrealized P&L: ${K(u.unrealizedPnlCents)}`,`Equity: ${K(u.equityCents)}`].join("\n")}}const W="https://deep-research-api.thekid-solana.workers.dev",V=3e5;async function G(e,t,n=3e5){const r=new AbortController,o=setTimeout(()=>r.abort(),n);try{const n=await fetch(e,{...t,signal:r.signal});return clearTimeout(o),n}catch(s){if(clearTimeout(o),s instanceof Error&&"AbortError"===s.name)throw new Error(`Request timeout after ${n}ms`);throw s}}async function X(e,t=!0){const n=function(){const e=process.env.POLYFACTUAL_API_KEY;if(!e)throw new Error("POLYFACTUAL_API_KEY environment variable is not set");return e}();if(e.length>1e3)throw new Error("Query exceeds maximum length of 1000 characters");if(!e.trim())throw new Error("Query cannot be empty");const r={query:e,text:t};console.log("Calling Polyfactual API with query:",e.substring(0,100)+(e.length>100?"...":""));const o=await G(`${W}/answer`,{method:"POST",headers:{"Content-Type":"application/json","X-API-Key":n},body:JSON.stringify(r)},V);if(!o.ok){let e;switch(o.status){case 400:e="Bad request: Invalid query format or validation error";break;case 401:e="Unauthorized: Invalid API key";break;case 429:e="Rate limit exceeded: Please wait before making another request";break;case 500:e="Internal server error: Polyfactual service is temporarily unavailable";break;default:e=`Polyfactual API error: ${o.status} ${o.statusText}`}try{const t=await o.json();!t.success&&t.error&&(e=t.error)}catch{}throw new Error(e)}const s=await o.json();if(!s.success)throw new Error(s.error||"Unknown error from Polyfactual API");return console.log("Polyfactual response received successfully"),s}const H=Object.freeze(Object.defineProperty({__proto__:null,checkPolyfactualHealth:async function(){try{return(await G(`${W}/health`,{method:"GET"},1e4)).ok}catch{return!1}},generatePolyfactualAnswer:X},Symbol.toStringTag,{value:"Module"}));const Q={BASE_MAINNET:"eip155:8453",BASE:"base",SOLANA_MAINNET:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",SOLANA:"solana"},Z={base:8453,"eip155:8453":8453},ee={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]};function te(){const e=process.env.X402_SOLANA_PRIVATE_KEY,t=process.env.X402_EVM_PRIVATE_KEY,n=process.env.X402_DISCOVERY_URL,r=process.env.X402_FACILITATOR_URL;return console.log("[x402] Config loaded:"),console.log("[x402] - Discovery URL:",n||"(not set)"),console.log("[x402] - EVM Private Key:",t?"(set)":"(not set)"),console.log("[x402] - Solana Private Key:",e?"(set)":"(not set)"),{solanaPrivateKey:e,evmPrivateKey:t,discoveryUrl:n,facilitatorUrl:r}}function ne(e){return"solana"===e||e.startsWith("solana:")}function re(e){return"base"===e||e.startsWith("eip155:")}function oe(e,t){if(!e)return"Unknown";try{const t=BigInt(e),n=10n**6n;return`$${(Number(t)/Number(n)).toFixed(4)}`}catch{return"Unknown"}}async function se(e,t,n,r){console.log("[x402] Creating EVM payment header for Base mainnet...");const{ethers:o}=await(import("ethers")),s=new o.Wallet(e),a=s.address;console.log("[x402] From address:",a);const i=function(){const e=new Uint8Array(32);return crypto.getRandomValues(e),`0x${Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}`}(),c=Math.floor(Date.now()/1e3),l=c-600,u=c+(t.maxTimeoutSeconds||60),m={from:a,to:t.payTo,value:t.amount||t.maxAmountRequired||"0",validAfter:l.toString(),validBefore:u.toString(),nonce:i};console.log("[x402] Authorization:",m);const d=t.extra||{name:"USD Coin",version:"2"},p=(h=t.network,Z[h]||8453);var h;const f={name:d.name||"USD Coin",version:d.version||"2",chainId:p,verifyingContract:t.asset};console.log("[x402] Domain:",f);const y=await s.signTypedData(f,ee,{from:a,to:t.payTo,value:BigInt(t.amount||t.maxAmountRequired||"0"),validAfter:BigInt(l),validBefore:BigInt(u),nonce:i});console.log("[x402] Signature created");const g={x402Version:n,resource:r||{url:"",description:"",mimeType:"application/json"},accepted:{scheme:t.scheme||"exact",network:t.network,asset:t.asset,amount:t.amount||t.maxAmountRequired||"0",payTo:t.payTo,maxTimeoutSeconds:t.maxTimeoutSeconds||60,extra:t.extra||{}},payload:{authorization:m,signature:y}};console.log("[x402] Payment payload (v2 format):",JSON.stringify(g,null,2));return btoa(JSON.stringify(g))}function ae(e,t){if(t?.name&&"string"==typeof t.name)return t.name;if(t?.title&&"string"==typeof t.title)return t.title;try{const t=new URL(e),n=t.pathname.split("/").filter(Boolean);if(n.length>0){return n[n.length-1].replace(/[-_]/g," ").replace(/\b\w/g,e=>e.toUpperCase())}return t.hostname}catch{return e.substring(0,30)+"..."}}function ie(e,t){if(t?.description&&"string"==typeof t.description)return t.description;for(const n of e){if(n.description)return n.description;if(n.outputSchema?.input?.queryParams){const e=Object.entries(n.outputSchema.input.queryParams);if(e.length>0)return`Accepts: ${e.map(([e,t])=>`${e} (${t.type})`).join(", ")}`}}}function ce(e){const t=[...new Set((e.accepts||[]).map(e=>e?.network).filter(e=>!!e))];let n,r="Unknown";for(const o of e.accepts||[]){const e=o?.amount||o?.maxAmountRequired;if(!e)continue;const t=oe(e,o.network);"Unknown"!==t&&("Unknown"===r||t<r)&&(r=t)}for(const o of e.accepts||[]){if(o?.outputSchema?.input?.queryParams){n=Object.entries(o.outputSchema.input.queryParams).map(([e,t])=>`${e}: ${t?.description||t?.type||"any"}`).join(", ");break}if(o?.outputSchema?.input?.bodyParams){n=Object.entries(o.outputSchema.input.bodyParams).map(([e,t])=>`${e}: ${t?.description||t?.type||"any"}`).join(", ");break}}return{id:e.resource||"",name:ae(e.resource||"",e.metadata),description:ie(e.accepts||[],e.metadata),resourceUrl:e.resource||"",priceUsdc:r,networks:t,lastUpdated:e.lastUpdated||(new Date).toISOString(),inputDescription:n}}async function le(e){const t=te();if(!t.discoveryUrl)throw new Error("X402_DISCOVERY_URL environment variable is not set");const n=new URLSearchParams;e?.type&&n.set("type",e.type),e?.limit&&n.set("limit",e.limit.toString()),e?.offset&&n.set("offset",e.offset.toString());const r=n.toString(),o=`${t.discoveryUrl}${r?`?${r}`:""}`;console.log("[x402] Fetching bazaar sellers from:",o);try{const t=await fetch(o,{method:"GET",headers:{"Content-Type":"application/json",Accept:"application/json"}});if(!t.ok){let e;if((t.headers.get("content-type")||"").includes("application/json")){const n=await t.json().catch(()=>({}));e=n.error||n.message||t.statusText}else e=`Received non-JSON response (status ${t.status}). Check discovery URL configuration.`;throw new Error(`Failed to fetch bazaar sellers (${t.status}): ${e}`)}const n=await t.json();console.log("[x402] Raw response keys:",Object.keys(n));let r=[];Array.isArray(n)?r=n:n.items&&Array.isArray(n.items)?r=n.items:n.resources&&Array.isArray(n.resources)?r=n.resources:(console.log("[x402] Unexpected response structure:",JSON.stringify(n).substring(0,500)),r=[]),console.log("[x402] Found",r.length,"sellers in bazaar");let a=[];for(const e of r)try{const t=ce(e);a.push(t)}catch(s){console.warn("[x402] Failed to transform seller:",e?.resource,s)}return e?.network&&(a=a.filter(t=>t.networks.includes(e.network))),a}catch(a){if(console.error("[x402] Error fetching bazaar sellers:",a),a instanceof Error)throw new Error(`x402 Bazaar error: ${a.message}. Discovery URL: ${o}`);throw a}}async function ue(e,t,n){const r=te();console.log("[x402] Calling seller:",e),console.log("[x402] Query:",t),n&&console.log("[x402] Preferred network:",n);try{const s=new URL(e);if(t)try{const e=JSON.parse(t);for(const[t,n]of Object.entries(e))s.searchParams.set(t,String(n))}catch{s.searchParams.set("q",t)}console.log("[x402] Request URL:",s.toString());const a=await fetch(s.toString(),{method:"GET",headers:{"Content-Type":"application/json",Accept:"application/json"}});if(console.log("[x402] Initial response status:",a.status),402!==a.status){if(a.ok){return{success:!0,data:await a.json(),paymentInfo:{network:"free"}}}const e=await a.text();throw new Error(`Unexpected response status: ${a.status}. Body: ${e.substring(0,200)}`)}const i=await a.json();console.log("[x402] Payment requirements received:",JSON.stringify(i,null,2));const c=i.x402Version||1,l=i.resource||{url:s.toString(),description:i.description||"",mimeType:i.mimeType||"application/json"};console.log("[x402] Resource info:",JSON.stringify(l));const u=i.accepts||[];console.log("[x402] Available payment options count:",u.length);for(const e of u)console.log(`[x402] Option - network: ${e.network}, scheme: ${e.scheme}, extra:`,JSON.stringify(e.extra));let m,d,p;if(n&&(m=u.find(e=>e.network===n),m&&(d=ne(m.network)?"solana":"evm")),m||(r.solanaPrivateKey&&(m=u.find(e=>ne(e.network)),m&&(d="solana",console.log("[x402] Using Solana mainnet for payment"))),!m&&r.evmPrivateKey&&(m=u.find(e=>re(e.network)),m&&(d="evm",console.log("[x402] Using EVM (Base mainnet) for payment")))),!m||!d){const e=u.map(e=>e.network).join(", "),t=[];return r.evmPrivateKey&&t.push("EVM (Base)"),r.solanaPrivateKey&&t.push("Solana"),{success:!1,error:`No compatible payment option found. Seller accepts: [${e}]. You have keys for: [${t.join(", ")||"none"}].`}}if(console.log("[x402] Selected payment network:",m.network),"solana"===d){if(!r.solanaPrivateKey)return{success:!1,error:"Solana private key not configured. Set X402_SOLANA_PRIVATE_KEY environment variable.",paymentInfo:{cost:oe(m.amount||m.maxAmountRequired,m.network),network:m.network}};p=await async function(e,t,n,r){console.log("[x402] Creating Solana payment header for mainnet...");const{Keypair:o,PublicKey:s,Transaction:a,TransactionInstruction:i,Connection:c,ComputeBudgetProgram:l}=await(import("@solana/web3.js")),{getAssociatedTokenAddress:u,createTransferCheckedInstruction:m,TOKEN_PROGRAM_ID:d,TOKEN_2022_PROGRAM_ID:p}=await(import("@solana/spl-token")),h=await(import("bs58"));let f;try{const t=h.default.decode(e);f=o.fromSecretKey(t)}catch{throw new Error("Invalid Solana private key. Must be base58 encoded.")}const y=f.publicKey;console.log("[x402] From address:",y.toBase58());const g=t.extra?.feePayer;if(!g)throw new Error("feePayer is required in paymentRequirements.extra for Solana payments");const k=new s(g);console.log("[x402] Fee payer:",k.toBase58());const w=new s(t.payTo),v=new s(t.asset),P=t.amount||t.maxAmountRequired;if(!P)throw new Error("amount or maxAmountRequired is required in paymentRequirements");const S=BigInt(P);console.log("[x402] To address:",w.toBase58()),console.log("[x402] Mint (USDC):",v.toBase58()),console.log("[x402] Amount:",S.toString());const b=await u(v,y,!1,d),E=await u(v,w,!1,d);console.log("[x402] Source ATA:",b.toBase58()),console.log("[x402] Destination ATA:",E.toBase58());const I=new c(process.env.SOLANA_RPC_URL||"https://api.mainnet-beta.solana.com","confirmed"),{blockhash:x,lastValidBlockHeight:A}=await I.getLatestBlockhash("confirmed");console.log("[x402] Got blockhash:",x.substring(0,20)+"...");const $=new a;$.feePayer=k,$.recentBlockhash=x;const O=l.setComputeUnitLimit({units:1e5}),T=l.setComputeUnitPrice({microLamports:5e4});$.add(O),$.add(T);const C=m(b,v,E,y,S,6,[],d);$.add(C),$.partialSign(f),console.log("[x402] Transaction created and partially signed");const R=$.serialize({requireAllSignatures:!1,verifySignatures:!1}).toString("base64");console.log("[x402] Transaction serialized, length:",R.length);const M={x402Version:n,resource:r||{url:"",description:"",mimeType:"application/json"},accepted:{scheme:t.scheme||"exact",network:t.network,asset:t.asset,amount:t.amount||t.maxAmountRequired||"0",payTo:t.payTo,maxTimeoutSeconds:t.maxTimeoutSeconds||60,extra:t.extra||{}},payload:{transaction:R}};console.log("[x402] Payment payload (v2 format):",JSON.stringify(M,null,2));const U=btoa(JSON.stringify(M));return console.log("[x402] Payment header created"),U}(r.solanaPrivateKey,m,c,l)}else{if(!r.evmPrivateKey)return{success:!1,error:"EVM private key not configured. Set X402_EVM_PRIVATE_KEY environment variable.",paymentInfo:{cost:oe(m.amount||m.maxAmountRequired,m.network),network:m.network}};p=await se(r.evmPrivateKey,m,c,l)}console.log("[x402] Payment header created, making paid request...");const h=await fetch(s.toString(),{method:"GET",headers:{"Content-Type":"application/json",Accept:"application/json","PAYMENT-SIGNATURE":p,"X-Payment":p}});if(console.log("[x402] Paid response status:",h.status),!h.ok){const e=await h.text();console.error("[x402] Paid request failed:",e);try{const t=JSON.parse(e);return{success:!1,error:t.error||t.message||`Payment failed: ${h.status}`,paymentInfo:{cost:oe(m.amount||m.maxAmountRequired,m.network),network:m.network}}}catch{return{success:!1,error:`Payment failed (${h.status}): ${e.substring(0,200)}`,paymentInfo:{cost:oe(m.amount||m.maxAmountRequired,m.network),network:m.network}}}}const f=await h.text();let y;console.log("[x402] Raw seller response (first 1000 chars):",f.substring(0,1e3)),f.length>1e3&&console.log("[x402] Response truncated, total length:",f.length);try{y=JSON.parse(f);const e=JSON.stringify(y,null,2);console.log("[x402] Parsed seller response (first 1000 chars):",e.substring(0,1e3))}catch(o){console.log("[x402] Response is not JSON, returning as text"),y={rawText:f}}const g=h.headers.get("X-Payment-Receipt");return console.log("[x402] Payment receipt header:",g||"none"),{success:!0,data:y,paymentInfo:{txId:g||void 0,cost:oe(m.amount||m.maxAmountRequired,m.network),network:m.network}}}catch(s){return console.error("[x402] Error calling seller:",s),{success:!1,error:s instanceof Error?s.message:"Unknown error"}}}async function me(){const e=te();if(!e.discoveryUrl)return!1;try{return(await fetch(`${e.discoveryUrl}?limit=1`,{method:"GET",headers:{Accept:"application/json"}})).ok}catch{return!1}}const de=Object.freeze(Object.defineProperty({__proto__:null,NETWORKS:Q,callX402Seller:ue,checkX402Health:me,isEvmNetwork:re,isSolanaNetwork:ne,listBazaarSellers:le,parseUsdcPrice:oe,transformSellerToInfo:ce},Symbol.toStringTag,{value:"Module"}));const pe={BTC:"btc-updown-15m-",SOL:"sol-updown-15m-",ETH:"eth-updown-15m-",XRP:"xrp-updown-15m-"};function he(e,t){return`${pe[e]}${t}`}function fe(e){return new Date(1e3*e).toISOString().slice(11,19)+" UTC"}function ye(e,t,n){return{timestamp:(new Date).toISOString(),level:e,message:t,details:n}}function ge(e){const t=JSON.parse(e);if(!Array.isArray(t)||t.length<2)throw new Error(`Expected 2 token IDs, got ${t.length}`);return[t[0],t[1]]}const ke="https://clob.polymarket.com",we="https://data-api.polymarket.com";class ve{config;logs=[];clobClient=null;constructor(e){this.config={...e,signatureType:e.signatureType??1}}getLogs(){return[...this.logs]}clearLogs(){this.logs=[]}log(e,t,n){this.logs.push(ye(e,t,n)),console.log(`[${e}] ${t}`,n||"")}async initClobClient(){if(this.clobClient)return this.clobClient;const{privateKey:n,proxyAddress:r,signatureType:o}=this.config;this.log("INFO","Initializing Polymarket CLOB client...");try{const s=new e.Wallet(n),a=new t.ClobClient(ke,137,s),i=await a.createOrDeriveApiKey();return this.log("INFO","API credentials derived successfully"),this.clobClient=new t.ClobClient(ke,137,s,i,o,r),this.log("SUCCESS","CLOB client initialized",{funder:`${r.slice(0,10)}...${r.slice(-8)}`,signatureType:o}),this.clobClient}catch(s){const e=s instanceof Error?s.message:String(s);throw this.log("ERROR",`Failed to initialize CLOB client: ${e}`),s}}async getMarketBySlug(e){const t=`https://gamma-api.polymarket.com/markets/slug/${e}`;this.log("INFO",`Fetching market data for slug: ${e}`);try{const n=await fetch(t,{method:"GET",headers:{"Content-Type":"application/json"}});if(!n.ok){if(404===n.status)return this.log("WARN",`Market not found: ${e}`),null;throw new Error(`Gamma API error: ${n.status} ${n.statusText}`)}const r=await n.json();return this.log("SUCCESS",`Found market: ${r.title||e}`),r}catch(n){throw this.log("ERROR",`Failed to fetch market: ${n instanceof Error?n.message:String(n)}`),n}}extractTokenIds(e){const t=e.clobTokenIds;if(!t)throw new Error("No clobTokenIds found in market data");const[n,r]=ge(t);return this.log("INFO","Extracted token IDs",{up:`${n.slice(0,16)}...${n.slice(-8)}`,down:`${r.slice(0,16)}...${r.slice(-8)}`}),{up:n,down:r}}async placeOrder(e){const{privateKey:n,proxyAddress:r}=this.config;if(!n)return this.log("ERROR","Missing private key for order placement"),{success:!1,errorMsg:"Missing private key. Please set POLYMARKET_WALLET_PRIVATE_KEY."};if(!r)return this.log("ERROR","Missing proxy address for order placement"),{success:!1,errorMsg:"Missing proxy address. Please set POLYMARKET_PROXY_WALLET_ADDRESS."};this.log("INFO",`Placing ${e.side} order`,{tokenId:`${e.tokenId.slice(0,16)}...`,price:e.price,size:Math.floor(e.size)});try{const n=await this.initClobClient(),r=await n.createAndPostOrder({tokenID:e.tokenId,price:e.price,side:"BUY"===e.side?t.Side.BUY:t.Side.SELL,size:Math.floor(e.size),feeRateBps:0},{tickSize:"0.01",negRisk:false},t.OrderType.GTC);return this.log("SUCCESS","Order placed successfully",{orderId:r?.orderID||r?.id,status:r?.status}),{success:!0,orderId:r?.orderID||r?.id,status:r?.status||"submitted"}}catch(o){const e=o instanceof Error?o.message:String(o);return this.log("ERROR",`Failed to place order: ${e}`),{success:!1,errorMsg:e}}}async placeStraddleOrders(e,t,n){const r=n/t;this.log("INFO","Placing straddle orders",{price:`${(100*t).toFixed(1)}%`,sizeUsd:`$${n}`,shares:Math.floor(r)});return{up:await this.placeOrder({tokenId:e.up,price:t,size:r,side:"BUY"}),down:await this.placeOrder({tokenId:e.down,price:t,size:r,side:"BUY"})}}calculateLadderRungs(e,t=49,n=35,r=1.5){const o=Math.ceil(t/100*5*100)/100,s=[];for(let p=t;p>=n;p--)s.push(p);let a=[...s],i=a.length;for(;i>1;){const t=[];for(let e=0;e<i;e++){const n=Math.exp(-r*e/i);t.push(n)}const n=t.reduce((e,t)=>e+t,0);if(e*t.map(e=>e/n)[i-1]>=o)break;i--,a=s.slice(0,i)}const c=[],l=[];for(let p=0;p<i;p++){const e=Math.exp(-r*p/i);l.push(e)}const u=l.reduce((e,t)=>e+t,0),m=l.map(e=>e/u);for(let p=0;p<i;p++){const t=a[p],n=100*m[p],r=e*m[p];c.push({pricePercent:t,priceDecimal:t/100,sizeUsd:Math.round(100*r)/100,allocationPercent:Math.round(100*n)/100})}const d=a[a.length-1];return this.log("INFO",`Calculated ladder with ${i} rungs`,{maxPrice:`${t}%`,effectiveMinPrice:`${d}%`,requestedMinPrice:`${n}%`,taperFactor:r,totalBankroll:`$${e}`,minRungAllocation:`$${c[c.length-1]?.sizeUsd||0}`}),d>n&&this.log("WARN",`Bankroll too small for full ladder range. Adjusted min price from ${n}% to ${d}%`),c}async placeLadderOrders(e,t,n=49,r=35,o=1.5){const s=this.calculateLadderRungs(t,n,r,o);this.log("INFO","Placing ladder orders",{totalRungs:s.length,totalBankroll:`$${t}`,priceRange:`${n}% → ${r}%`});const a=[];let i=0;const c=2*s.length;for(const l of s){if(l.sizeUsd<1){this.log("WARN",`Skipping rung at ${l.pricePercent}% - allocation too small ($${l.sizeUsd.toFixed(2)})`);continue}const t=l.sizeUsd/l.priceDecimal;if(Math.floor(t)<5){this.log("WARN",`Skipping rung at ${l.pricePercent}% - would result in < 5 shares`);continue}this.log("INFO",`Placing ladder rung at ${l.pricePercent}%`,{sizeUsd:`$${l.sizeUsd.toFixed(2)}`,shares:Math.floor(t),allocation:`${l.allocationPercent.toFixed(1)}%`});const n=await this.placeOrder({tokenId:e.up,price:l.priceDecimal,size:t,side:"BUY"});n.success&&i++;const r=await this.placeOrder({tokenId:e.down,price:l.priceDecimal,size:t,side:"BUY"});r.success&&i++,a.push({pricePercent:l.pricePercent,sizeUsd:l.sizeUsd,up:n,down:r})}return this.log("SUCCESS","Ladder orders complete",{totalOrders:c,successfulOrders:i,successRate:`${(i/c*100).toFixed(1)}%`}),{rungs:s,results:a,totalOrders:c,successfulOrders:i}}async getPositions(e){try{const{proxyAddress:t}=this.config,n=new URLSearchParams;n.append("user",t),n.append("sizeThreshold","0"),e?.market&&n.append("market",e.market);const r=`${we}/positions?${n.toString()}`;this.log("INFO","Fetching positions from Data API",{user:`${t.slice(0,10)}...`,...e});const o=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`Data API error: ${o.status} ${o.statusText}`);const s=await o.json();return this.log("SUCCESS",`Found ${(s||[]).length} positions`),s||[]}catch(t){const e=t instanceof Error?t.message:String(t);return this.log("ERROR",`Failed to get positions: ${e}`),[]}}async getActivity(e){try{const{proxyAddress:t}=this.config,n=new URLSearchParams;n.append("user",t),n.append("type","TRADE"),n.append("limit","500"),e?.market&&n.append("market",e.market);const r=`${we}/activity?${n.toString()}`;this.log("INFO","Fetching activity from Data API",{user:`${t.slice(0,10)}...`,...e});const o=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`Data API error: ${o.status} ${o.statusText}`);const s=await o.json();return this.log("SUCCESS",`Found ${(s||[]).length} trades`),s||[]}catch(t){const e=t instanceof Error?t.message:String(t);return this.log("ERROR",`Failed to get activity: ${e}`),[]}}async getOrder(e){try{const t=await this.initClobClient();this.log("INFO",`Fetching order: ${e.slice(0,16)}...`);const n=await t.getOrder(e);return n?this.log("SUCCESS","Order found",{status:n.status,size_matched:n.size_matched,original_size:n.original_size}):this.log("WARN",`Order not found: ${e}`),n||null}catch(t){const e=t instanceof Error?t.message:String(t);return this.log("ERROR",`Failed to get order: ${e}`),null}}determinePairStatus(e,t){const n=e.shares>0,r=t.shares>0;if(!n&&!r)return e.pendingShares>0||t.pendingShares>0?"PENDING":"NO_POSITION";if(n&&!r)return"DIRECTIONAL_YES";if(!n&&r)return"DIRECTIONAL_NO";const o=e.avgPrice+t.avgPrice;return o<.995?"PROFIT_LOCKED":o<=1.005?"BREAK_EVEN":"LOSS_RISK"}async getMarketPosition(e,t,n){this.log("INFO",`Fetching position for ${e} via Data API`);try{const r=await this.getPositions(),o=r.find(e=>e.asset===t.up),s=r.find(e=>e.asset===t.down),a={shares:o?.size||0,costUsd:o?Math.round(o.size*o.avgPrice*100)/100:0,avgPrice:o?.avgPrice||0,ordersPlaced:0,ordersFilled:o?1:0,pendingShares:0},i={shares:s?.size||0,costUsd:s?Math.round(s.size*s.avgPrice*100)/100:0,avgPrice:s?.avgPrice||0,ordersPlaced:0,ordersFilled:s?1:0,pendingShares:0},c=this.determinePairStatus(a,i),l=a.shares>0,u=i.shares>0;let m=null,d=0,p=0,h=0,f=0,y=0;if(l&&u){m=Math.round(1e4*(a.avgPrice+i.avgPrice))/1e4,d=Math.min(a.shares,i.shares),p=d;const e=d*a.avgPrice,t=d*i.avgPrice;h=Math.round(100*(e+t))/100,f=Math.round(100*(p-h))/100,y=h>0?Math.round(f/h*1e4)/100:0}const g={marketSlug:e,marketTitle:n,tokenIds:t,yes:a,no:i,pairCost:m,status:c,minShares:d,guaranteedPayout:p,totalCost:h,guaranteedProfit:f,returnPercent:y,lastUpdated:(new Date).toISOString()};return this.log("SUCCESS","Position fetched from Data API",{status:c,pairCost:m,yesShares:a.shares,noShares:i.shares,guaranteedProfit:f>0?`$${f}`:"N/A"}),g}catch(r){const o=r instanceof Error?r.message:String(r);this.log("ERROR",`Failed to get position: ${o}`);const s={shares:0,costUsd:0,avgPrice:0,ordersPlaced:0,ordersFilled:0,pendingShares:0};return{marketSlug:e,marketTitle:n,tokenIds:t,yes:s,no:s,pairCost:null,status:"NO_POSITION",minShares:0,guaranteedPayout:0,totalCost:0,guaranteedProfit:0,returnPercent:0,lastUpdated:(new Date).toISOString()}}}}function Pe(){const e=process.env.POLYMARKET_WALLET_PRIVATE_KEY,t=process.env.POLYMARKET_PROXY_WALLET_ADDRESS,n=parseInt(process.env.POLYMARKET_SIGNATURE_TYPE||"1",10);if(!e)throw new Error("POLYMARKET_WALLET_PRIVATE_KEY environment variable is required");if(!t)throw new Error("POLYMARKET_PROXY_WALLET_ADDRESS environment variable is required");return new ve({privateKey:e,proxyAddress:t,signatureType:n})}const Se=Object.freeze(Object.defineProperty({__proto__:null,ASSET_SLUG_PREFIXES:pe,PolymarketClient:ve,buildMarketSlug:he,createClientFromEnv:Pe,createLogEntry:ye,formatTimeShort:fe,parseTokenIds:ge},Symbol.toStringTag,{value:"Module"}));function be(){const e=Math.floor(Date.now()/1e3);return 900*Math.floor(e/900)}function Ee(){const e=Math.floor(Date.now()/1e3);return 900*Math.ceil(e/900)}const Ie="https://gamma-api.polymarket.com",xe=["gpt-5.2","gpt-5.1","gpt-5-nano","gpt-4.1","gpt-4.1-mini"];function Ae(e){return xe.includes(e)||e.startsWith("gpt-")}function $e(e,t){return"polymarket"===e?`https://polymarket.com/event/${t}`:`https://kalshi.com/events/${t}`}const Oe={id:"kalshi-momentum",upstream:"kalshi-bot-api/examples/momentum_bot.py",run(e,t){const r=L(e.config),o=e.venue??"kalshi";if(!n.isUtcTime(t.evaluationTime))throw new Error("invalid evaluation time");if(t.account&&n.validateAccount(t.account).length)throw new Error("invalid momentum account");let s={directions:[],tradesExecuted:0};const a=e.ticks;for(let l=0;l<a.length;l++){const e=a[l];if(!n.isUtcTime(e.timestamp)||Date.parse(e.timestamp)>Date.parse(t.evaluationTime)||l>0&&(e.ticker!==a[0].ticker||Date.parse(e.timestamp)<=Date.parse(a[l-1].timestamp)))throw new Error("ticks must be one market in strictly increasing UTC order without future data");l<a.length-1&&(s=B(e,s,r).state)}const i=a.at(-1);if(!i)return[{sourceId:this.id,upstream:this.upstream,kind:"signal",instrument:{type:"event",venue:o,marketId:e.marketId??"empty"},action:"HOLD",confidence:r.momentumThreshold/r.lookback,reasoning:"no ticks",asOf:t.evaluationTime}];if("event"===t.account?.kind&&t.account.venue===o){const e=Object.values(t.account.portfolio.positions).filter(e=>e.ticker===i.ticker&&e.quantity>0);if(e.length>1)throw new Error("momentum supports one outcome holding");const n=e[0];n&&(s.position={ticker:n.ticker,outcome:n.outcome,quantity:n.quantity,entryPriceCents:n.averageEntryPriceCents})}const c=B(i,s,r).intent;return[{sourceId:this.id,upstream:this.upstream,kind:"HOLD"===c.action?"signal":"order",instrument:{type:"event",venue:o,marketId:i.ticker,...c.outcome?{outcome:c.outcome}:{}},action:c.action,confidence:r.momentumThreshold/r.lookback,reasoning:`${c.reason}; confidence = momentumThreshold / lookback`,asOf:i.timestamp,..."HOLD"===c.action?{}:{order:c}}]}};function Te(e){if(!Number.isFinite(e)||e<0||e>100)throw new Error(`invalid execution price ${e}¢`);if(Math.abs(e-Math.round(e))>=1e-9)throw new Error(`sub-cent price ${e}¢ is not executable by the paper executor`);return Math.round(e)}function Ce(e){const{proposal:t,finalQuantity:r,verdict:o,judge:s,fundManager:a}=e;if(!["BUY","SELL"].includes(t.action)||!["PROCEED","BLOCK","REDUCE"].includes(s.kind))throw new Error("invalid approval action or judge decision");if(!o.allowed||"BLOCK"===s.kind||!["APPROVE","MODIFY"].includes(a.decision)||a.proposalId!==t.proposalId||!n.isQuantity(r)||0===r||!n.isQuantity(t.quantity)||!n.isQuantity(o.maxQuantity)||!n.isQuantity(a.quantity)||r>Math.min(t.quantity,o.maxQuantity,a.quantity)||"REDUCE"===s.kind&&(!n.isQuantity(s.maxQuantity)||r>s.maxQuantity))throw new Error("invalid or exceeded execution approval")}function Re(e){Ce(e);const t=e.proposal;if("event"!==t.instrument.type||!t.outcome||void 0===t.limitPriceCents)throw new Error("event approval required");return{action:t.action,ticker:t.instrument.marketId,outcome:t.outcome,quantity:e.finalQuantity,priceCents:Te(t.limitPriceCents),timestamp:t.asOf,reason:`Approved ${t.proposalId}`}}function Me(e){const t=100*e;if(!Number.isFinite(t)||t<=0||!Number.isSafeInteger(Math.round(t))||Math.abs(t-Math.round(t))>=1e-9)throw new Error("unsupported stock price; fixture fills require whole cents");return Math.round(t)}function Ue(e,t){return{summary:"Recorded binary-contract strategy research; prices and cash are cents.",findings:[e.reason,`Strategy intent: ${e.action} ${e.outcome??""} ${e.quantity} contracts at ${e.priceCents} cents.`,"SELL closes the named outcome; it does not buy the opposite outcome."],recommendations:["Review the unchanged intent. A different action or quantity means HOLD for this replay.","Paper cash, inventory and position limits remain authoritative."],data:{intent:{...e},cashCents:t.cashCents,positions:t.positions,equityCents:t.equityCents}}}exports.BLOCKRUN_MODELS=u,exports.DEFAULT_KALSHI_MOMENTUM_CONFIG=N,exports.InMemoryPaperExecutor=D,exports.NoTradeError=$,exports.analyzeEventMarketsPrompt=g,exports.applyMomentumExecution=F,exports.arbitrageAnalysisPrompt=w,exports.bookmakerAnalysisPrompt=k,exports.buildKalshiMarketUrl=function(e){return`https://kalshi.com/markets/${e.split("-")[0]}`},exports.buildKalshiMarketUrl$1=function(e){return`https://kalshi.com/markets/${e.split("-")[0]}`},exports.buildPolymarketUrl=function(e){return`https://polymarket.com/event/${e}`},exports.callBlockRunResponses=h,exports.callGrokResponses=i,exports.callOpenAIResponses=a,exports.createKalshiMomentumState=q,exports.dflowRequest=P,exports.domeRequest=E,exports.equityPriceCents=Me,exports.evaluateKalshiMomentumTick=B,exports.fetchWithTimeout=s,exports.findArbitrage=async function(e,t={}){const n=Date.now(),{url:r,model:o}=e;if(!r)throw new Error("Missing required parameter: 'url'");if(!o)throw new Error("Missing required parameter: 'model'");const s=function(e){const t=e.toLowerCase();return t.includes("polymarket.com")?"polymarket":t.includes("kalshi.com")?"kalshi":null}(r);if(!s)throw new Error("Invalid URL. Must be a Polymarket or Kalshi market URL.");let c=null;const l="polymarket"===s?"kalshi":"polymarket";if("polymarket"===s){const e=function(e){try{const t=new URL(e).pathname.split("/").filter(e=>e);return"event"===t[0]&&t.length>=2?t[1]:null}catch{return null}}(r);if(!e)throw new Error("Could not extract event slug from Polymarket URL");c=await async function(e){try{const t=`${Ie}/events/slug/${e}`,n=await fetch(t);if(!n.ok)return console.error("Polymarket event fetch error:",n.status),null;const r=await n.json(),o=[];if(r.markets&&Array.isArray(r.markets))for(const e of r.markets){const t=e.question||e.title||"";let n=50;if(e.outcomePrices)try{const t=JSON.parse(e.outcomePrices);n=100*parseFloat(t[0])}catch{}t&&o.push({title:t,yesPrice:n})}return{eventTitle:r.title||e.replace(/-/g," "),markets:o,source:"polymarket",identifier:r.slug||e}}catch(t){return console.error("Error fetching Polymarket event:",t),null}}(e)}else{const e=function(e){try{const t=new URL(e).pathname.split("/").filter(e=>e);return("markets"===t[0]||"events"===t[0])&&t.length>=2?(t.length>=4?t[t.length-1]:t[1]).toUpperCase():null}catch{return null}}(r);if(!e)throw new Error("Could not extract ticker from Kalshi URL");c=await async function(e,t){try{const n=await P(`/event/${e}`,{params:{withNestedMarkets:!0},apiKey:t}),r=[];if(n.markets&&Array.isArray(n.markets))for(const e of n.markets){const t=e.yesSubTitle||"";let n=50;if(e.yesBid&&e.yesAsk){n=(parseFloat(e.yesBid)+parseFloat(e.yesAsk))/2*100}else e.yesBid?n=100*parseFloat(e.yesBid):e.yesAsk&&(n=100*parseFloat(e.yesAsk));t&&r.push({title:t,yesPrice:n})}return{eventTitle:n.title||e,markets:r,source:"kalshi",identifier:e}}catch(n){return console.error("Error fetching Kalshi event:",n),null}}(e,t.dflowApiKey)}if(!c||0===c.markets.length)throw new Error(`Could not fetch event data from ${s}. The event may not exist or have no markets.`);const u=await async function(e,t,n,r,o){const{systemPrompt:s,userPrompt:c}=v({title:e,sourcePlatform:t,targetPlatform:n});let l;if(Ae(r)){const e=await a(c,s,"text",r,1,{apiKey:o.openaiApiKey}),t=[];for(const n of e.output)if("message"===n.type){const e=n;t.push(...e.content)}l=t.map(e=>e.text).filter(e=>void 0!==e).join("").trim()}else{const e=await i(c,s,"text",r,1,void 0,{apiKey:o.xaiApiKey}),t=[];for(const n of e.output)if("message"===n.type){const e=n;t.push(...e.content)}l=t.map(e=>e.text).filter(e=>void 0!==e).join("").trim()}return l.replace(/['"]/g,"").trim().split(/\s+/).slice(0,2).join(" ")}(c.eventTitle,s,l,o,t);let m;if(m="polymarket"===l?await async function(e){try{const t=`${Ie}/public-search?q=${encodeURIComponent(e)}&events_status=open`,n=await fetch(t);if(!n.ok)return console.error("Polymarket search error:",n.status),[];const r=await n.json(),o=[];if(r.events&&Array.isArray(r.events))for(const e of r.events){const t=e.slug;if(e.markets&&Array.isArray(e.markets))for(const n of e.markets){const e=n.question||n.title||"";let r=50;if(n.outcomePrices)try{const e=JSON.parse(n.outcomePrices);r=100*parseFloat(e[0])}catch{}e&&o.push({title:e,yesPrice:r,identifier:t})}}return o}catch(t){return console.error("Error searching Polymarket:",t),[]}}(u):await async function(e,t){try{const n=await P("/search",{params:{q:e,event_status:"open",withNestedMarkets:!0},apiKey:t}),r=[];if(n.events&&Array.isArray(n.events))for(const e of n.events){const t=e.ticker;if(e.markets&&Array.isArray(e.markets))for(const n of e.markets){const e=n.yesSubTitle||n.title||"";let o=50;if(n.yesAsk&&n.yesBid){o=(parseFloat(n.yesAsk)+parseFloat(n.yesBid))/2*100}else n.yesAsk?o=100*parseFloat(n.yesAsk):n.yesBid&&(o=100*parseFloat(n.yesBid));e&&r.push({title:e,yesPrice:o,identifier:t})}}return r}catch(n){return console.error("Error searching Kalshi:",n),[]}}(u,t.dflowApiKey),0===m.length){const e={source:s,name:c.eventTitle,identifier:c.identifier,yesPrice:c.markets[0]?.yesPrice||50,noPrice:100-(c.markets[0]?.yesPrice||50),url:$e(s,c.identifier),rawData:{eventTitle:c.eventTitle,markets:c.markets}};return{analysis:{isSameMarket:!1,sameMarketConfidence:0,marketComparisonReasoning:`No matching markets found on ${l} for query "${u}"`,polymarketData:"polymarket"===s?e:void 0,kalshiData:"kalshi"===s?e:void 0,arbitrage:{hasArbitrage:!1},summary:`No matching markets found on ${l}. Cannot determine arbitrage opportunity.`,risks:["No matching market found on the other platform"],recommendation:"Try a different event or check if the market exists on both platforms."},model:"none",sourceMarket:s,searchedMarket:l,processingTimeMs:Date.now()-n}}const{analysis:d,modelUsed:p,tokensUsed:h}=await async function(e,t,n,r,o){const s={source:e.source,name:e.eventTitle,identifier:e.identifier,yesPrice:e.markets[0]?.yesPrice||50,noPrice:100-(e.markets[0]?.yesPrice||50),url:$e(e.source,e.identifier)};s.rawData={eventTitle:e.eventTitle,markets:e.markets};const{systemPrompt:c,userPrompt:l}=w({sourceMarket:s,searchResults:t,searchPlatform:n});let u,m,d;if(Ae(r)){const e=await a(l,c,"json_object",r,3,{apiKey:o.openaiApiKey});m=e.model,d=e.usage?.total_tokens;const t=[];for(const n of e.output)if("message"===n.type){const e=n;t.push(...e.content)}u=t.map(e=>e.text).filter(e=>void 0!==e).join("\n")}else{const e=await i(l,c,"json_object",r,3,void 0,{apiKey:o.xaiApiKey});m=e.model,d=e.usage?.total_tokens;const t=[];for(const n of e.output)if("message"===n.type){const e=n;t.push(...e.content)}u=t.map(e=>e.text).filter(e=>void 0!==e).join("\n")}const p=JSON.parse(u);return{analysis:{isSameMarket:p.isSameMarket,sameMarketConfidence:p.sameMarketConfidence,marketComparisonReasoning:p.marketComparisonReasoning,polymarketData:"polymarket"===e.source?s:p.matchedMarket||void 0,kalshiData:"kalshi"===e.source?s:p.matchedMarket||void 0,arbitrage:p.arbitrage,summary:p.summary,risks:p.risks,recommendation:p.recommendation},modelUsed:m,tokensUsed:d}}(c,m,l,o,t);return{analysis:d,model:p,tokensUsed:h,sourceMarket:s,searchedMarket:l,processingTimeMs:Date.now()-n}},exports.getEvents=async function(e,t={}){const n=Date.now(),{url:r}=e;if(!r)throw new Error("Missing required parameter: 'url'");const{pmType:o,urlSource:s}=function(e){const t=e.toLowerCase();return t.includes("jup.ag/prediction")?{pmType:"Kalshi",urlSource:"jupiter"}:t.includes("kalshi")?{pmType:"Kalshi",urlSource:"kalshi"}:t.includes("polymarket")?{pmType:"Polymarket",urlSource:"polymarket"}:{pmType:null,urlSource:null}}(r);if(!o||!s)throw new Error("Could not detect prediction market type from URL. Use Kalshi, Polymarket, or Jupiter prediction market URLs.");let a,i,c,l;if("Kalshi"===o){let e;if("jupiter"===s)e=function(e){const t=e.split("?")[0].split("/"),n=t[t.length-1];return n&&n.length>0?n.toUpperCase():null}(r);else{const t=r.split("/");e=t[t.length-1]?.toUpperCase()||null}if(!e)throw new Error("Could not extract event ticker from URL");a=e,l="dflow";try{c=await S(e,t.dflowApiKey)}catch(u){const t=u instanceof Error?u.message:"Unknown error",n=t.includes("404")||t.toLowerCase().includes("not found");throw new Error(n?`Event '${e}' not found on Kalshi (via DFlow).`:`Failed to fetch markets: ${t}`)}}else{const e=function(e){const t=e.split("?")[0].split("/");return t[t.length-1]||null}(r);if(!e)throw new Error("Could not extract event slug from URL");a=e,l="gamma";try{const{eventId:t,markets:n}=await async function(e){const t=[`https://gamma-api.polymarket.com/events?slug=${encodeURIComponent(e)}`,`https://gamma-api.polymarket.com/events/${encodeURIComponent(e)}`];for(const n of t)try{const e=await fetch(n);if(!e.ok){console.warn(`Gamma API endpoint ${n} returned ${e.status}`);continue}const t=await e.json(),r=Array.isArray(t)?t[0]:t;if(r&&r.markets&&Array.isArray(r.markets))return{eventId:void 0!==r.id&&null!==r.id?String(r.id):null,markets:r.markets}}catch(u){console.warn(`Error fetching from Gamma API ${n}:`,u)}return console.warn(`Could not fetch Polymarket event for slug ${e} from Gamma API`),{eventId:null,markets:[]}}(e);c=n,i=t||void 0}catch(u){const t=u instanceof Error?u.message:"Unknown error",n=t.includes("404")||t.toLowerCase().includes("not found");throw new Error(n?`Event '${e}' not found on Polymarket.`:`Failed to fetch markets from Polymarket: ${t}`)}}if(0===c.length)throw new Error(`No markets found for '${a}' on ${o}.`);return{eventIdentifier:a,eventId:i,pmType:o,urlSource:s,markets:c,marketsCount:c.length,dataProvider:l,processingTimeMs:Date.now()-n}},exports.getKalshiMarketsByEvent=async function(e,t="open",n){return(await async function(e,t){return E("/kalshi/markets",{params:{cursor:e?.cursor,limit:e?.limit,event_ticker:e?.eventTicker,status:e?.status},apiKey:t})}({eventTicker:e,status:t,limit:100},n)).markets},exports.getKalshiMarketsByEvent$1=S,exports.getPolymarketMarkets=async function(e,t){return E("/polymarket/markets",{params:e,apiKey:t})},exports.isBlockRunModel=m,exports.isRetryableError=r,exports.kalshiMomentumSource=Oe,exports.listBlockRunModels=async function(){try{const e=await fetch("https://blockrun.ai/api/v1/models",{method:"GET",headers:{Accept:"application/json"}});if(!e.ok)return console.warn("[BlockRun] Failed to fetch models, using defaults"),y();const t=await e.json();return(t.data||t.models||[]).map(e=>({id:`blockrun/${e.id}`,name:e.name||e.id,provider:e.provider||"unknown",description:e.description||""}))}catch{return console.warn("[BlockRun] Error fetching models, using defaults"),y()}},exports.normalizeKalshiMomentumConfig=L,exports.polyfactual=H,exports.polymarket=Se,exports.predictionMarketResearch=Ue,exports.reviewPredictionMarketIntent=async function(e,t,n,r){const o=new Date(t.timestamp).toISOString(),s={sourceId:Oe.id,upstream:Oe.upstream,kind:"HOLD"===t.action?"signal":"order",instrument:{type:"event",venue:"kalshi",marketId:t.ticker,...t.outcome?{outcome:t.outcome}:{}},action:t.action,confidence:.75,reasoning:t.reason,asOf:o,..."HOLD"!==t.action?{order:{...t,timestamp:o}}:{},evidence:{research:JSON.stringify(Ue(t,n))}},{state:a,signal:i}=await e.propagate(t.ticker,o.slice(0,10),{instrument:s.instrument,strategySignals:[s],account:{kind:"event",venue:"kalshi",portfolio:n},evaluationTime:o,sources:{[Oe.id]:Oe}}),c={...i,reasoning:[a.investmentDebateState.judgeDecision,a.traderInvestmentPlan,a.finalRiskAdjustedPlan,a.fundManagerDecision,a.riskReviewReason].filter(Boolean).join("\n\n")||i.reasoning},l=e=>({...c,action:"HOLD",reasoning:`${e}\n\n${c.reasoning}`});if("BUY"===t.action&&!/FINAL DECISION:\s*INVEST\s*$/i.test(a.investmentDebateState.judgeDecision))return l("Investment judge did not approve entry");if(r?.fundManagerReview||a.approval){const e=a.approval;if(!e||"APPROVE"!==e.fundManager.decision)return l("Missing explicit unchanged FundManager approval");try{const n=Re(e);if(n.action!==t.action||n.outcome!==t.outcome||n.quantity!==t.quantity||n.priceCents!==t.priceCents||n.ticker!==t.ticker||Date.parse(n.timestamp)!==Date.parse(t.timestamp))return l("Approved proposal differs from the original intent")}catch{return l("Invalid execution approval")}}return c},exports.runBookmakerAgent=async function(e,t={}){const n=Date.now(),{analyses:r,x402Results:o,eventIdentifier:s,pmType:c,model:l}=e,u=r&&Array.isArray(r)&&r.length>0,m=o&&Array.isArray(o)&&o.length>0;if(!u&&!m)throw new Error("Missing or invalid 'analyses' or 'x402Results' parameter");const d=(r?.length||0)+(o?.length||0);if(d<2)throw new Error("Need at least 2 data sources (analyses + PayAI results) to aggregate");if(!s)throw new Error("Missing required parameter: 'eventIdentifier'");if(!c||"Kalshi"!==c&&"Polymarket"!==c)throw new Error("Invalid 'pmType'. Must be 'Kalshi' or 'Polymarket'");if(!l)throw new Error("Missing required parameter: 'model'");const p=function(e){return A.includes(e)||e.startsWith("gpt-")}(l),h=(r||[]).map(e=>({agentId:e.agentId,model:e.model,analysis:e.analysis})),{systemPrompt:f,userPrompt:y}=k(h,o||[],s,c);let g,w,v,P;if(p){const e=await a(y,f,"json_object",l,3,{apiKey:t.openaiApiKey});g=e.model,w=e.usage?.total_tokens;const n=[];for(const t of e.output)if("message"===t.type){const e=t;n.push(...e.content)}v=n.map(e=>e.text).filter(e=>void 0!==e).join("\n")}else{const e=await i(y,f,"json_object",l,3,void 0,{apiKey:t.xaiApiKey});g=e.model,w=e.usage?.total_tokens;const n=[];for(const t of e.output)if("message"===t.type){const e=t;n.push(...e.content)}v=n.map(e=>e.text).filter(e=>void 0!==e).join("\n")}try{P=JSON.parse(v)}catch{throw new Error(`Failed to parse AI response as JSON (model ${g}): ${v.substring(0,200)}`)}return{analysis:P,model:g,tokensUsed:w,agentsAggregated:d,processingTimeMs:Date.now()-n}},exports.runEventAnalysisAgent=async function(e,t={}){const n=Date.now(),{markets:r,eventIdentifier:o,pmType:s,model:c,question:l,tools:u,userCommand:m}=e;if(!r||!Array.isArray(r)||0===r.length)throw new Error("Missing or invalid 'markets' parameter");if(!o)throw new Error("Missing required parameter: 'eventIdentifier'");if(!s||"Kalshi"!==s&&"Polymarket"!==s)throw new Error("Invalid 'pmType'. Must be 'Kalshi' or 'Polymarket'");if(!c)throw new Error("Missing required parameter: 'model'");const d=x(c),p=l||"What is the best trading opportunity in this market? Analyze the probability and provide a recommendation.",{systemPrompt:f,userPrompt:y}=g(r,o,p,s,u,m);let k,w,v,P,S;if("blockrun"===d){const e=u?.includes("x_search")||u?.includes("web_search"),n=await h(y,f,"json_object",c,3,e,{walletKey:t.blockrunWalletKey});k=n.model,w=n.usage?.total_tokens,v=n.blockrun?.paymentCost;const r=[];for(const t of n.output)if("message"===t.type){const e=t;r.push(...e.content)}P=r.map(e=>e.text).filter(e=>void 0!==e).join("\n")}else if("openai"===d){const e=await a(y,f,"json_object",c,3,{apiKey:t.openaiApiKey});k=e.model,w=e.usage?.total_tokens;const n=[];for(const t of e.output)if("message"===t.type){const e=t;n.push(...e.content)}P=n.map(e=>e.text).filter(e=>void 0!==e).join("\n")}else{const e=await i(y,f,"json_object",c,3,u,{apiKey:t.xaiApiKey});k=e.model,w=e.usage?.total_tokens;const n=[];for(const t of e.output)if("message"===t.type){const e=t;n.push(...e.content)}P=n.map(e=>e.text).filter(e=>void 0!==e).join("\n")}try{S=JSON.parse(P)}catch{throw new Error(`Failed to parse AI response as JSON (model ${k}): ${P.substring(0,200)}`)}return{analysis:S,model:k,tokensUsed:w,paymentCost:v,processingTimeMs:Date.now()-n}},exports.runKalshiMomentumPaperAgent=function(e){const t=J(e);let n=t.next();for(;!n.done;)n=t.next();return n.value},exports.runKalshiMomentumPaperAgentWithResearch=async function(e,t){const n=J(e);let r=n.next();for(;!r.done;){const{intent:e,portfolio:o}=r.value,s="HOLD"===e.action?void 0:await t({...e},o);if("HOLD"!==e.action&&!s)throw new Error("Research review must return a TradeSignal");r=n.next(s)}return r.value},exports.runMapperAgent=function(e){const{platform:t,analysisResult:n,marketData:r,budgetUsd:o}=e;if(!t||"Polymarket"!==t&&"Kalshi"!==t)throw new Error("Invalid platform. Must be 'Polymarket' or 'Kalshi'");if(!n||!n.recommendedAction)throw new Error("Missing analysisResult or recommendedAction");if("NO TRADE"===n.recommendedAction)throw new $;if(!r)throw new Error("Missing marketData");if("number"!=typeof o||o<1||o>100)throw new Error("Invalid budgetUsd. Must be between $1 and $100");if("Kalshi"===t)throw new Error("Kalshi autonomous mode coming soon! Currently only Polymarket is supported.");return{platform:"Polymarket",orderParams:O(n,r,o),analysis:{recommendedAction:n.recommendedAction,side:"BUY YES"===n.recommendedAction?"YES":"NO",confidence:n.winnerConfidence}}},exports.runPolyfactualResearch=async function(e){const t=Date.now(),{query:n}=e;if(!n||"string"!=typeof n)return console.log("Missing or invalid query parameter"),{success:!1,error:"Missing required parameter: 'query'",metadata:{requestId:crypto.randomUUID(),timestamp:(new Date).toISOString(),query:"",processingTimeMs:Date.now()-t}};const r=n.trim();if(!r)return console.log("Empty query parameter"),{success:!1,error:"Query cannot be empty",metadata:{requestId:crypto.randomUUID(),timestamp:(new Date).toISOString(),query:"",processingTimeMs:Date.now()-t}};try{console.log("Starting Polyfactual research for query:",r.substring(0,100));const e=(await X(r,!0)).data,n=e?.answer||JSON.stringify(e),o=e?.citations||[],s=Date.now()-t;return console.log("Request completed in",s,"ms"),{success:!0,answer:"string"==typeof n?n:JSON.stringify(n),citations:Array.isArray(o)?o:[],data:e,metadata:{requestId:crypto.randomUUID(),timestamp:(new Date).toISOString(),query:r,processingTimeMs:s}}}catch(o){console.error("Error:",o);const e=Date.now()-t;return{success:!1,error:o instanceof Error?o.message:"An unexpected error occurred",metadata:{requestId:crypto.randomUUID(),timestamp:(new Date).toISOString(),query:"",processingTimeMs:e}}}},exports.runPolymarketPositionTracker=async function(e){const t=[];try{const{asset:r,marketSlug:o,tokenIds:s}=e;if(!r||!function(e){return["BTC","SOL","ETH","XRP"].includes(e.toUpperCase())}(r))return t.push(ye("ERROR","Invalid or missing asset",{asset:r})),{success:!1,error:"Invalid asset. Must be one of: BTC, SOL, ETH, XRP",logs:t};const a=r.toUpperCase();let i;try{i=Pe()}catch(n){const e=n instanceof Error?n.message:String(n);return t.push(ye("ERROR",`Failed to initialize client: ${e}`)),{success:!1,error:`Client initialization failed: ${e}`,logs:t}}const c=be(),l=o||he(a,c);t.push(ye("INFO",`Checking position for market: ${l}`));let u,m=s;if(!m){const e=await i.getMarketBySlug(l);if(t.push(...i.getLogs()),i.clearLogs(),!e)return t.push(ye("WARN","Market not found - may not be created yet")),{success:!1,error:"Market not found - may not be created yet",logs:t};u=e.title;try{m=i.extractTokenIds(e),t.push(...i.getLogs()),i.clearLogs()}catch(n){const e=n instanceof Error?n.message:String(n);return t.push(ye("ERROR",`Failed to extract token IDs: ${e}`)),{success:!1,error:`Token extraction failed: ${e}`,logs:t}}}const d=await i.getMarketPosition(l,m,u);return t.push(...i.getLogs()),i.clearLogs(),{success:!0,data:{asset:a,position:d},logs:t}}catch(n){const e=n instanceof Error?n.message:String(n);return t.push(ye("ERROR",`Unhandled error: ${e}`)),{success:!1,error:e,logs:t}}},exports.runPolymarketPutOrder=async function(e){const t=Date.now(),n=e;let r,o,s,a,i,c,l;try{r=Pe()}catch(p){return{success:!1,error:`Failed to initialize Polymarket client: ${p instanceof Error?p.message:String(p)}`,metadata:{requestId:crypto.randomUUID(),timestamp:(new Date).toISOString(),processingTimeMs:Date.now()-t}}}let u="",m="0.01",d=!1;try{if(n.orderParams){console.log("Using mapper mode with pre-calculated order params");const e=n.orderParams;if(!e.tokenId)return{success:!1,error:"Missing orderParams.tokenId",metadata:{requestId:crypto.randomUUID(),timestamp:(new Date).toISOString(),processingTimeMs:Date.now()-t}};o=e.tokenId,s=e.price,a=e.size,m=e.tickSize||"0.01",d=e.negRisk??!1,c=e.conditionId,l=e.marketSlug,i="YES",console.log("Mapper order params:",{tokenId:`${o.slice(0,16)}...`,price:s,size:a,tickSize:m,negRisk:d})}else{console.log("Using legacy mode - calculating order params");const{conditionId:e,marketSlug:m,side:d,budgetUsd:p,price:h}=n;if(!e)return{success:!1,error:"Missing required parameter: 'conditionId' or 'orderParams'",metadata:{requestId:crypto.randomUUID(),timestamp:(new Date).toISOString(),processingTimeMs:Date.now()-t}};if(!m)return{success:!1,error:"Missing required parameter: 'marketSlug'",metadata:{requestId:crypto.randomUUID(),timestamp:(new Date).toISOString(),processingTimeMs:Date.now()-t}};if(!d||"YES"!==d&&"NO"!==d)return{success:!1,error:"Invalid 'side'. Must be 'YES' or 'NO'",metadata:{requestId:crypto.randomUUID(),timestamp:(new Date).toISOString(),processingTimeMs:Date.now()-t}};if("number"!=typeof p||p<1||p>100)return{success:!1,error:"Invalid 'budgetUsd'. Must be between $1 and $100",metadata:{requestId:crypto.randomUUID(),timestamp:(new Date).toISOString(),processingTimeMs:Date.now()-t}};c=e,l=m,i=d,console.log("Fetching market data for:",l);const f=await r.getMarketBySlug(l);if(!f)return{success:!1,error:`Market not found: ${l}`,metadata:{requestId:crypto.randomUUID(),timestamp:(new Date).toISOString(),processingTimeMs:Date.now()-t}};if(!f.acceptingOrders)return{success:!1,error:"Market is not accepting orders",metadata:{requestId:crypto.randomUUID(),timestamp:(new Date).toISOString(),processingTimeMs:Date.now()-t}};if(f.closed)return{success:!1,error:"Market is closed",metadata:{requestId:crypto.randomUUID(),timestamp:(new Date).toISOString(),processingTimeMs:Date.now()-t}};u=f.title;const y=r.extractTokenIds(f),g=JSON.parse(f.outcomes||'["Yes", "No"]'),k=JSON.parse(f.outcomePrices||'["0.5", "0.5"]'),w=g.findIndex(e=>"yes"===e.toLowerCase()||"up"===e.toLowerCase()),v=g.findIndex(e=>"no"===e.toLowerCase()||"down"===e.toLowerCase());let P;if("YES"===i?(o=0===w?y.up:y.down,P=parseFloat(k[w>=0?w:0])):(o=0===v?y.up:y.down,P=parseFloat(k[v>=0?v:1])),s=h??P,a=p/s,Math.floor(a)<5)return{success:!1,error:`Budget too small. At current price (${(100*s).toFixed(1)}%), minimum budget is $${(5*s).toFixed(2)}`,metadata:{requestId:crypto.randomUUID(),timestamp:(new Date).toISOString(),processingTimeMs:Date.now()-t}}}console.log("Placing order:",{side:i,tokenId:`${o.slice(0,16)}...`,price:s,size:Math.floor(a)});const e=await r.placeOrder({tokenId:o,price:s,size:a,side:"BUY"}),p={success:e.success,orderId:e.orderId,status:e.status,errorMsg:e.errorMsg,tokenId:o,side:i,price:s,size:Math.floor(a),costUsd:Math.round(a*s*100)/100},h=Date.now()-t;return console.log("Request completed in",h,"ms"),e.success?{success:!0,data:{order:p,market:{slug:l,title:u,conditionId:c}},metadata:{requestId:crypto.randomUUID(),timestamp:(new Date).toISOString(),processingTimeMs:h}}:{success:!1,error:e.errorMsg||"Order placement failed",data:{order:p,market:{slug:l,title:u,conditionId:c}},metadata:{requestId:crypto.randomUUID(),timestamp:(new Date).toISOString(),processingTimeMs:h}}}catch(p){return console.error("Unhandled error:",p),{success:!1,error:p instanceof Error?p.message:"An unexpected error occurred",metadata:{requestId:crypto.randomUUID(),timestamp:(new Date).toISOString(),processingTimeMs:Date.now()-t}}}},exports.runPolymarketUpDown15LimitOrderBot=async function(e){const t=[];try{const{asset:r,price:o,sizeUsd:s,ladder:a}=e;if(!r||!function(e){return["BTC","SOL","ETH","XRP"].includes(e.toUpperCase())}(r))return t.push(ye("ERROR","Invalid or missing asset",{asset:r})),{success:!1,error:"Invalid asset. Must be one of: BTC, SOL, ETH, XRP",logs:t};const i=r.toUpperCase(),c=a?.enabled??!1,l=o?o/100:.48,u=s||25,m={enabled:c,maxPrice:a?.maxPrice??49,minPrice:a?.minPrice??35,taperFactor:a?.taperFactor??1.5};c&&t.push(ye("INFO","Ladder mode enabled",{maxPrice:`${m.maxPrice}%`,minPrice:`${m.minPrice}%`,taperFactor:m.taperFactor,totalBankroll:`$${u}`}));const d=Ee(),p=he(i,d);let h,f;try{h=Pe()}catch(n){const e=n instanceof Error?n.message:String(n);return t.push(ye("ERROR",`Failed to initialize client: ${e}`)),{success:!1,error:`Client initialization failed: ${e}`,logs:t}}try{const e=await h.getMarketBySlug(p);if(t.push(...h.getLogs()),h.clearLogs(),e){let r;try{r=h.extractTokenIds(e),t.push(...h.getLogs()),h.clearLogs()}catch(n){const r=n instanceof Error?n.message:String(n);return t.push(ye("ERROR",`Failed to extract token IDs: ${r}`)),f={marketSlug:p,marketTitle:e.title,marketStartTime:fe(d),targetTimestamp:d,error:`Token extraction failed: ${r}`},{success:!1,error:f.error,data:{asset:i,pricePercent:100*l,sizeUsd:u,ladderMode:c,market:f},logs:t}}if(c){const n=await h.placeLadderOrders(r,u,m.maxPrice,m.minPrice,m.taperFactor);t.push(...h.getLogs()),h.clearLogs();const o=n.results.map(e=>({pricePercent:e.pricePercent,sizeUsd:e.sizeUsd,up:e.up,down:e.down}));f={marketSlug:p,marketTitle:e.title,marketStartTime:fe(d),targetTimestamp:d,ladderOrdersPlaced:o,ladderTotalOrders:n.totalOrders,ladderSuccessfulOrders:n.successfulOrders}}else{const n=await h.placeStraddleOrders(r,l,u);t.push(...h.getLogs()),h.clearLogs(),f={marketSlug:p,marketTitle:e.title,marketStartTime:fe(d),targetTimestamp:d,ordersPlaced:n}}}else f={marketSlug:p,marketStartTime:fe(d),targetTimestamp:d,error:"Market not found - may not be created yet"}}catch(n){const e=n instanceof Error?n.message:String(n);t.push(ye("ERROR",`Error processing market ${p}: ${e}`)),f={marketSlug:p,marketStartTime:fe(d),targetTimestamp:d,error:e}}return{success:!f.error,data:{asset:i,pricePercent:100*l,sizeUsd:u,ladderMode:c,market:f},logs:t}}catch(n){const e=n instanceof Error?n.message:String(n);return t.push(ye("ERROR",`Unhandled error: ${e}`)),{success:!1,error:e,logs:t}}},exports.runX402Seller=async function(e){const t=Date.now(),n=e;console.log("[x402-seller] Action:",n.action);const{action:r}=n;try{switch(r){case"health":{const e=await me(),n=process.env.X402_DISCOVERY_URL;return{success:!0,healthy:e,config:{discoveryUrl:n,preferredNetwork:process.env.X402_PREFERRED_NETWORK},metadata:{requestId:crypto.randomUUID(),timestamp:(new Date).toISOString(),processingTimeMs:Date.now()-t}}}case"list":{const e=n;try{const n=await le({network:e.network,type:e.type||"http",limit:e.limit,offset:e.offset});return{success:!0,sellers:n,metadata:{requestId:crypto.randomUUID(),timestamp:(new Date).toISOString(),processingTimeMs:Date.now()-t,total:n.length}}}catch(o){return console.error("[x402-seller] Error listing sellers:",o),{success:!1,error:o instanceof Error?o.message:"Failed to list sellers",metadata:{requestId:crypto.randomUUID(),timestamp:(new Date).toISOString(),processingTimeMs:Date.now()-t,total:0}}}}case"call":{const e=n;if(!e.resourceUrl)return{success:!1,error:"Missing required parameter: 'resourceUrl'"};if(!e.query)return{success:!1,error:"Missing required parameter: 'query'"};const r=e.network||Q.SOLANA_MAINNET;try{const n=await ue(e.resourceUrl,e.query,r);return{success:n.success,data:n.data,error:n.error,metadata:{requestId:crypto.randomUUID(),timestamp:(new Date).toISOString(),processingTimeMs:Date.now()-t,paymentTxId:n.paymentInfo?.txId,costUsdc:n.paymentInfo?.cost,network:r}}}catch(o){return console.error("[x402-seller] Error calling seller:",o),{success:!1,error:o instanceof Error?o.message:"Failed to call seller",metadata:{requestId:crypto.randomUUID(),timestamp:(new Date).toISOString(),processingTimeMs:Date.now()-t,network:r}}}}case"networks":{const e=Q;return{success:!0,networks:[{id:e.SOLANA_MAINNET,name:"Solana Mainnet",type:"solana"},{id:e.SOLANA_DEVNET,name:"Solana Devnet",type:"solana"},{id:e.BASE_MAINNET,name:"Base Mainnet",type:"evm"},{id:e.BASE_SEPOLIA,name:"Base Sepolia",type:"evm"}],metadata:{requestId:crypto.randomUUID(),timestamp:(new Date).toISOString(),processingTimeMs:Date.now()-t}}}default:return{success:!1,error:`Unknown action: '${r}'. Valid actions: 'list', 'call', 'health', 'networks'`}}}catch(o){return console.error("[x402-seller] Unhandled error:",o),{success:!1,error:o instanceof Error?o.message:"An unexpected error occurred",metadata:{requestId:crypto.randomUUID(),timestamp:(new Date).toISOString(),processingTimeMs:Date.now()-t}}}},exports.searchQueryGeneratorPrompt=v,exports.sleep=o,exports.toEquityOrder=function(e,t,r){Ce(e);const o=e.proposal;if("equity"!==o.instrument.type||!Number.isFinite(t)||t<=0||!r||"equity"!==r.kind||n.validateAccount(r).length)throw new Error("equity execution needs a current account and positive fixture close");const s=Me(t),a=Math.min(e.finalQuantity,"BUY"===o.action?Math.floor(r.cashCents/s):r.shares[o.instrument.symbol]?.quantity??0);if(0===a)throw new Error("zero affordable or held shares");return{symbol:o.instrument.symbol,qty:a,side:"BUY"===o.action?"buy":"sell",type:"market",time_in_force:"day"}},exports.toExecutableCents=Te,exports.toPredictionMarketIntent=Re,exports.x402=de;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const e=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),t=e=>"number"==typeof e&&Number.isSafeInteger(e)&&e>=0,i=e=>"number"==typeof e&&Number.isFinite(e),n=e=>"string"==typeof e&&e.length>0&&e.trim()===e,s=e=>"string"==typeof e&&/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?Z$/.test(e)&&Number.isFinite(Date.parse(e));function r(t){return e(t)?"equity"===t.type?n(t.symbol)?[]:["symbol required"]:"event"===t.type&&n(t.venue)&&n(t.marketId)?void 0!==t.outcome&&"YES"!==t.outcome&&"NO"!==t.outcome?["invalid outcome"]:[]:["invalid instrument"]:["instrument must be an object"]}function o(e,t){return"equity"===e.type?"equity"===t.type&&e.symbol===t.symbol:!("event"!==t.type||e.venue!==t.venue||e.marketId!==t.marketId||e.outcome&&t.outcome&&e.outcome!==t.outcome)}function a(a,u){if(!e(a))return["signal must be an object"];const c=r(a.instrument);for(const e of["sourceId","upstream","reasoning"])n(a[e])||c.push(`${e} must be trimmed nonempty text`);["signal","recommendation","order","portfolio"].includes(String(a.kind))||c.push("invalid kind"),["BUY","SELL","HOLD"].includes(String(a.action))||c.push("invalid action");for(const e of["confidence","probability"])"confidence"!==e&&void 0===a[e]||!(!i(a[e])||a[e]<0||a[e]>1)||c.push(`invalid ${e}`);s(a.asOf)||c.push("asOf must be ISO UTC");const d=0===r(a.instrument).length,m=a.instrument;u&&d&&!o(m,u)&&c.push("instrument mismatch");const l=e=>i(e)&&e>=0&&(!d||"event"!==m.type||e<=100);if(void 0!==a.sizing&&(e(a.sizing)?(void 0===a.sizing.quantity||t(a.sizing.quantity)||c.push("invalid sizing quantity"),void 0===a.sizing.limitPriceCents||l(a.sizing.limitPriceCents)||c.push("invalid sizing price"),"HOLD"===a.action&&Number(a.sizing.quantity)>0&&c.push("HOLD carries quantity")):c.push("invalid sizing")),"order"===a.kind||void 0!==a.order)if(e(a.order)){const e=a.order;(!d||"event"!==m.type||e.ticker!==m.marketId||e.action!==a.action||m.outcome&&e.outcome!==m.outcome)&&c.push("nested order mismatch"),"YES"===e.outcome||"NO"===e.outcome||"HOLD"===a.action&&null===e.outcome||c.push("invalid order outcome"),t(e.quantity)&&l(e.priceCents)&&n(e.reason)&&s(e.timestamp)&&e.timestamp===a.asOf||c.push("invalid order fields"),"HOLD"===a.action&&Number(e.quantity)>0&&c.push("HOLD carries order")}else c.push("order required");if("portfolio"===a.kind||void 0!==a.targets)if(Array.isArray(a.targets)&&a.targets.length){const i=/* @__PURE__ */new Set;for(const n of a.targets){if(!e(n)){c.push("invalid target");continue}d&&"event"===m.type&&n.ticker===m.marketId&&["YES","NO"].includes(String(n.outcome))&&t(n.quantity)&&l(n.priceCents)||c.push("invalid target fields");const s=`${n.ticker}:${n.outcome}`;i.has(s)&&c.push("duplicate target"),i.add(s),"HOLD"===a.action&&Number(n.quantity)>0&&c.push("HOLD carries target")}}else c.push("targets required");return void 0===a.evidence||e(a.evidence)&&!Object.values(a.evidence).some(e=>"string"!=typeof e&&!i(e))||c.push("invalid evidence"),c}function u(i){return e(i)&&t(i.maxPositionPerMarket)&&0!==i.maxPositionPerMarket&&(void 0===i.maxOpenPositions||t(i.maxOpenPositions))?[]:["invalid risk limits"]}function c(t){return!e(t)||!n(t.label)||!i(t.sizeMultiplier)||t.sizeMultiplier<0||t.sizeMultiplier>1||"boolean"!=typeof t.allowNewEntries?["invalid risk posture"]:[]}function d(s){return e(s)?"equity"===s.kind?t(s.cashCents)&&e(s.shares)?Object.entries(s.shares).some(([s,r])=>!n(s)||!e(r)||!t(r.quantity)||!i(r.averagePriceCents)||r.averagePriceCents<0)?["invalid share holding"]:[]:["invalid equity account"]:"event"===s.kind&&n(s.venue)&&e(s.portfolio)&&t(s.portfolio.cashCents)&&e(s.portfolio.positions)?Object.entries(s.portfolio.positions).some(([s,r])=>!e(r)||!n(r.ticker)||!["YES","NO"].includes(String(r.outcome))||s!==`${r.ticker}:${r.outcome}`||!t(r.quantity)||!i(r.averageEntryPriceCents)||r.averageEntryPriceCents<0||r.averageEntryPriceCents>100||!i(r.markPriceCents)||r.markPriceCents<0||r.markPriceCents>100)?["invalid contract holding"]:[]:["invalid event account"]:["account required"]}function m(e,t,n,r){const o=[],u=[];if(!Array.isArray(e))return{valid:o,rejected:[{input:e,reasons:["signals must be an array"]}]};for(const c of e){const e=a(c,t);if(s(n)||e.push("invalid evaluation time"),!e.length){const t=c,s=Date.parse(n)-Date.parse(t.asOf);r&&t.sourceId!==r.id&&e.push("source identity mismatch"),s<0&&e.push("future signal"),void 0!==r?.maxSignalAgeMs&&(!i(r.maxSignalAgeMs)||r.maxSignalAgeMs<0||s>r.maxSignalAgeMs)&&e.push("stale signal or invalid freshness limit")}e.length?u.push({input:c,reasons:e}):o.push(c)}return{valid:o,rejected:u}}export{d as a,u as b,c,r as d,t as e,e as f,s as i,o as m,m as p,a as v};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";const e=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),t=e=>"number"==typeof e&&Number.isSafeInteger(e)&&e>=0,i=e=>"number"==typeof e&&Number.isFinite(e),n=e=>"string"==typeof e&&e.length>0&&e.trim()===e,s=e=>"string"==typeof e&&/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?Z$/.test(e)&&Number.isFinite(Date.parse(e));function r(t){return e(t)?"equity"===t.type?n(t.symbol)?[]:["symbol required"]:"event"===t.type&&n(t.venue)&&n(t.marketId)?void 0!==t.outcome&&"YES"!==t.outcome&&"NO"!==t.outcome?["invalid outcome"]:[]:["invalid instrument"]:["instrument must be an object"]}function o(e,t){return"equity"===e.type?"equity"===t.type&&e.symbol===t.symbol:!("event"!==t.type||e.venue!==t.venue||e.marketId!==t.marketId||e.outcome&&t.outcome&&e.outcome!==t.outcome)}function a(a,u){if(!e(a))return["signal must be an object"];const c=r(a.instrument);for(const e of["sourceId","upstream","reasoning"])n(a[e])||c.push(`${e} must be trimmed nonempty text`);["signal","recommendation","order","portfolio"].includes(String(a.kind))||c.push("invalid kind"),["BUY","SELL","HOLD"].includes(String(a.action))||c.push("invalid action");for(const e of["confidence","probability"])"confidence"!==e&&void 0===a[e]||!(!i(a[e])||a[e]<0||a[e]>1)||c.push(`invalid ${e}`);s(a.asOf)||c.push("asOf must be ISO UTC");const d=0===r(a.instrument).length,l=a.instrument;u&&d&&!o(l,u)&&c.push("instrument mismatch");const m=e=>i(e)&&e>=0&&(!d||"event"!==l.type||e<=100);if(void 0!==a.sizing&&(e(a.sizing)?(void 0===a.sizing.quantity||t(a.sizing.quantity)||c.push("invalid sizing quantity"),void 0===a.sizing.limitPriceCents||m(a.sizing.limitPriceCents)||c.push("invalid sizing price"),"HOLD"===a.action&&Number(a.sizing.quantity)>0&&c.push("HOLD carries quantity")):c.push("invalid sizing")),"order"===a.kind||void 0!==a.order)if(e(a.order)){const e=a.order;(!d||"event"!==l.type||e.ticker!==l.marketId||e.action!==a.action||l.outcome&&e.outcome!==l.outcome)&&c.push("nested order mismatch"),"YES"===e.outcome||"NO"===e.outcome||"HOLD"===a.action&&null===e.outcome||c.push("invalid order outcome"),t(e.quantity)&&m(e.priceCents)&&n(e.reason)&&s(e.timestamp)&&e.timestamp===a.asOf||c.push("invalid order fields"),"HOLD"===a.action&&Number(e.quantity)>0&&c.push("HOLD carries order")}else c.push("order required");if("portfolio"===a.kind||void 0!==a.targets)if(Array.isArray(a.targets)&&a.targets.length){const i=new Set;for(const n of a.targets){if(!e(n)){c.push("invalid target");continue}d&&"event"===l.type&&n.ticker===l.marketId&&["YES","NO"].includes(String(n.outcome))&&t(n.quantity)&&m(n.priceCents)||c.push("invalid target fields");const s=`${n.ticker}:${n.outcome}`;i.has(s)&&c.push("duplicate target"),i.add(s),"HOLD"===a.action&&Number(n.quantity)>0&&c.push("HOLD carries target")}}else c.push("targets required");return void 0===a.evidence||e(a.evidence)&&!Object.values(a.evidence).some(e=>"string"!=typeof e&&!i(e))||c.push("invalid evidence"),c}exports.isQuantity=t,exports.isRecord=e,exports.isUtcTime=s,exports.matchesInstrument=o,exports.partitionValidSignals=function(e,t,n,r){const o=[],u=[];if(!Array.isArray(e))return{valid:o,rejected:[{input:e,reasons:["signals must be an array"]}]};for(const c of e){const e=a(c,t);if(s(n)||e.push("invalid evaluation time"),!e.length){const t=c,s=Date.parse(n)-Date.parse(t.asOf);r&&t.sourceId!==r.id&&e.push("source identity mismatch"),s<0&&e.push("future signal"),void 0!==r?.maxSignalAgeMs&&(!i(r.maxSignalAgeMs)||r.maxSignalAgeMs<0||s>r.maxSignalAgeMs)&&e.push("stale signal or invalid freshness limit")}e.length?u.push({input:c,reasons:e}):o.push(c)}return{valid:o,rejected:u}},exports.validateAccount=function(s){return e(s)?"equity"===s.kind?t(s.cashCents)&&e(s.shares)?Object.entries(s.shares).some(([s,r])=>!n(s)||!e(r)||!t(r.quantity)||!i(r.averagePriceCents)||r.averagePriceCents<0)?["invalid share holding"]:[]:["invalid equity account"]:"event"===s.kind&&n(s.venue)&&e(s.portfolio)&&t(s.portfolio.cashCents)&&e(s.portfolio.positions)?Object.entries(s.portfolio.positions).some(([s,r])=>!e(r)||!n(r.ticker)||!["YES","NO"].includes(String(r.outcome))||s!==`${r.ticker}:${r.outcome}`||!t(r.quantity)||!i(r.averageEntryPriceCents)||r.averageEntryPriceCents<0||r.averageEntryPriceCents>100||!i(r.markPriceCents)||r.markPriceCents<0||r.markPriceCents>100)?["invalid contract holding"]:[]:["invalid event account"]:["account required"]},exports.validateInstrument=r,exports.validateLimits=function(i){return e(i)&&t(i.maxPositionPerMarket)&&0!==i.maxPositionPerMarket&&(void 0===i.maxOpenPositions||t(i.maxOpenPositions))?[]:["invalid risk limits"]},exports.validatePosture=function(t){return!e(t)||!n(t.label)||!i(t.sizeMultiplier)||t.sizeMultiplier<0||t.sizeMultiplier>1||"boolean"!=typeof t.allowNewEntries?["invalid risk posture"]:[]},exports.validateSignal=a;
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
/package/dist/{prediction-markets → predictos}/agents/polymarket-updown-15-limit-order-bot.d.ts
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|