@prophecy-dev/sdk 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Y=Object.defineProperty;var Be=Object.getOwnPropertyDescriptor;var $e=Object.getOwnPropertyNames;var Fe=Object.prototype.hasOwnProperty;var Ye=(e,t)=>()=>(e&&(t=e(e=0)),t);var G=(e,t)=>{for(var r in t)Y(e,r,{get:t[r],enumerable:!0})},Ve=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of $e(t))!Fe.call(e,i)&&i!==r&&Y(e,i,{get:()=>t[i],enumerable:!(n=Be(t,i))||n.enumerable});return e};var qe=e=>Ve(Y({},"__esModule",{value:!0}),e);var q={};G(q,{ApiError:()=>m,authedDelete:()=>V,authedPost:()=>f,get:()=>o,post:()=>g});async function E(e,t={}){let r={"Content-Type":"application/json",...t.headers},n=await fetch(e,{method:t.method??"GET",headers:r,body:t.body?JSON.stringify(t.body):void 0});if(!n.ok){let i=await n.json().catch(()=>null);throw new m(n.status,i)}return n.json()}function o(e,t,r){let n=new URL(t,e);if(r)for(let[i,a]of Object.entries(r))a!==void 0&&n.searchParams.set(i,String(a));return E(n)}function g(e,t,r){return E(new URL(t,e),{method:"POST",body:r})}function f(e,t,r,n){return E(new URL(t,e),{method:"POST",body:r,headers:{Authorization:`Bearer ${n}`}})}function V(e,t,r){return E(new URL(t,e),{method:"DELETE",headers:{Authorization:`Bearer ${r}`}})}var m,u=Ye(()=>{"use strict";m=class extends Error{constructor(r,n){super(`API error ${r}`);this.status=r;this.body=n;this.name="ApiError"}}});var ze={};G(ze,{ACTIVE_MARKET_CAP:()=>le,ApiError:()=>m,BANNED_DOMAINS:()=>l,CATEGORIES:()=>h,DEFAULT_CATEGORY:()=>b,DEFAULT_DURATION_HOURS:()=>y,DEFAULT_LIQUIDITY:()=>oe,DEFAULT_RESOLUTION_HOURS:()=>ue,DEFAULT_TRADING_START_BUFFER_SECONDS:()=>ce,DURATION_HINTS:()=>w,ENTITY_TYPES:()=>v,LOW_CONFIDENCE_OVERRIDE:()=>T,MARKET_DEFAULTS:()=>he,MAX_BINARY_PROBABILITY:()=>B,MAX_DURATION_HOURS:()=>D,MAX_OPTION_PROBABILITY:()=>F,MIN_BINARY_PROBABILITY:()=>M,MIN_DURATION_HOURS:()=>U,MIN_OPTION_PROBABILITY:()=>$,RESOLUTION_CONFIDENCE_THRESHOLD:()=>ae,SIMILARITY_THRESHOLD:()=>se,VIRALITY_THRESHOLD:()=>ie,buildCarouselPrompt:()=>Pe,buildEntityExtractionPrompt:()=>Ae,buildGroupingPrompt:()=>we,buildMarketGenerationPrompt:()=>be,buildNewsContextPrompt:()=>Ie,buildProbabilityEstimationPrompt:()=>Ee,buildReframePrompt:()=>ve,buildResolutionEvalPrompt:()=>Te,buildUrlGuidanceBlock:()=>Re,clampBinaryProbability:()=>xe,clampDuration:()=>P,createCache:()=>x,createChainClient:()=>_,createEventsApiNamespace:()=>C,createMarketDefinition:()=>ne,createProphecyClient:()=>te,getEventRating:()=>R,getPPLeaderboard:()=>N,getPnLLeaderboard:()=>S,getVolumeLeaderboard:()=>O,googleNewsFallbackUrl:()=>Ne,isBannedDomain:()=>Ce,isValidUrl:()=>_e,marketDefinitionSchema:()=>L,normalizeOptionProbabilities:()=>ke,parseLlmMarketJson:()=>Se,previewRating:()=>A,rateMarketDraft:()=>I,signCreateMarketPermit:()=>De,signTradePermit:()=>Ue});module.exports=qe(ze);u();function j(e){return{prompt:e.prompt,answer_type:e.answerType,source_urls:e.sourceUrls,min_agreement:e.minAgreement,trading_start:e.tradingStart,trading_end:e.tradingEnd,resolution_start:e.resolutionStart,resolution_end:e.resolutionEnd}}function He(e){return{ratedAt:e.rated_at,finalScore:e.final_score,ratingBand:{rating:e.rating_band.rating,minScore:e.rating_band.min_score,maxScore:e.rating_band.max_score,definition:e.rating_band.definition},criteria:e.criteria.map(t=>({key:t.key,name:t.name,criterionType:t.criterion_type,evaluation:t.evaluation,status:t.status,summary:t.summary,weight:t.weight,score:t.score,weightedScore:t.weighted_score}))}}async function A(e,t){return g(e,"/v1/arbiter/preview",j(t))}async function I(e,t){let r=await g(e,"/v1/arbiter/preview",j(t));return He(r)}async function R(e,t,r){return o(e,`/v1/arbiter/events/${t}/${r}`)}function x(e={}){let t=e.defaultTtlMs??15e3,r=new Map;return{get(n){if(t===0)return;let i=r.get(n);if(i){if(Date.now()>i.expiresAt){r.delete(n);return}return i.data}},set(n,i,a){let s=a??t;s!==0&&r.set(n,{data:i,expiresAt:Date.now()+s})},invalidate(n){for(let i of r.keys())i.startsWith(n)&&r.delete(i)},clear(){r.clear()}}}var p=require("viem"),We=[{inputs:[{internalType:"uint256",name:"venueId",type:"uint256"},{internalType:"address",name:"user",type:"address"}],name:"getNonce",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],k=[{inputs:[{internalType:"uint256",name:"marketId",type:"uint256"},{internalType:"address",name:"user",type:"address"}],name:"getUserPosition",outputs:[{components:[{internalType:"uint256",name:"yes",type:"uint256"},{internalType:"uint256",name:"no",type:"uint256"},{internalType:"bool",name:"claimed",type:"bool"}],internalType:"struct IProphecyCore.SharePosition",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"marketId",type:"uint256"}],name:"getMarketCore",outputs:[{components:[{internalType:"uint256",name:"tradingStartTs",type:"uint256"},{internalType:"uint256",name:"tradingEndTs",type:"uint256"},{internalType:"uint256",name:"resolutionStartTs",type:"uint256"},{internalType:"uint256",name:"resolutionEndTs",type:"uint256"},{internalType:"address",name:"creator",type:"address"},{internalType:"address",name:"resolver",type:"address"},{internalType:"address",name:"stakeToken",type:"address"},{internalType:"bool",name:"resolved",type:"bool"},{internalType:"uint8",name:"outcome",type:"uint8"},{internalType:"uint256",name:"totalYesShares",type:"uint256"},{internalType:"uint256",name:"totalNoShares",type:"uint256"},{internalType:"uint256",name:"totalShares",type:"uint256"},{internalType:"uint256",name:"participantCount",type:"uint256"},{internalType:"uint256",name:"initialLiquidityBase",type:"uint256"},{internalType:"uint256",name:"feeBps",type:"uint256"}],internalType:"struct IProphecyCore.MarketCore",name:"core",type:"tuple"},{internalType:"string",name:"name",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"marketId",type:"uint256"}],name:"getCurrentReserves",outputs:[{internalType:"uint256",name:"yesPool",type:"uint256"},{internalType:"uint256",name:"noPool",type:"uint256"}],stateMutability:"view",type:"function"}],Ge=[{inputs:[{internalType:"uint256",name:"marketId",type:"uint256"}],name:"claimSettlement",outputs:[{internalType:"uint256",name:"payout",type:"uint256"}],stateMutability:"nonpayable",type:"function"}];function _(e){let t=(0,p.defineChain)({id:e.chainId,name:`Somnia (${e.chainId})`,nativeCurrency:{name:"STT",symbol:"STT",decimals:18},rpcUrls:{default:{http:[e.rpcUrl]}}}),r=(0,p.createPublicClient)({chain:t,transport:(0,p.http)(e.rpcUrl)});return{async getVenueNonce(n,i){return r.readContract({address:e.venueRegistryAddress,abi:We,functionName:"getNonce",args:[n,i]})},async getMarketCore(n){let[i,a]=await r.readContract({address:e.prophecyCoreAddress,abi:k,functionName:"getMarketCore",args:[n]});return{core:i,name:a}},async getReserves(n){let[i,a]=await r.readContract({address:e.prophecyCoreAddress,abi:k,functionName:"getCurrentReserves",args:[n]});return{yesPool:i,noPool:a}},async getUserPosition(n,i){return await r.readContract({address:e.prophecyCoreAddress,abi:k,functionName:"getUserPosition",args:[n,i]})},async getUserPositions(n,i){if(n.length===0)return[];let a=n.map(d=>({address:e.prophecyCoreAddress,abi:k,functionName:"getUserPosition",args:[d,i]}));return(await r.multicall({contracts:a})).map(d=>d.status!=="success"?null:d.result)},encodeClaimSettlement(n){if(!e.prophecySettlementAddress)throw new Error("prophecySettlementAddress is required in ChainConfig for claim operations");return{to:e.prophecySettlementAddress,data:(0,p.encodeFunctionData)({abi:Ge,functionName:"claimSettlement",args:[n]})}}}}function K(e,t){return{venueId:e,getAuthHeader:()=>`Bearer ${t}`}}function J(e,t){async function r(n,i){let a=new URL(`/v1/events${n}`,e),s=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:t.getAuthHeader()},body:JSON.stringify(i)});if(!s.ok){let d=await s.json().catch(()=>null),{ApiError:Me}=await Promise.resolve().then(()=>(u(),q));throw new Me(s.status,d)}return s.json()}return{socialShare:(n,i)=>r("/social-share",{wallet:n,marketId:i}),receiptInspect:(n,i)=>r("/receipt-inspect",{wallet:n,marketId:i}),dailyChallenge:n=>r("/daily-challenge",{wallet:n})}}u();function C(e,t){return{async search(r){let n=new URL("/v0/events",e);if(r?.q&&n.searchParams.set("q",r.q),r?.venue&&n.searchParams.set("venue",r.venue),r?.tag&&n.searchParams.set("tag",r.tag),r?.created_by&&n.searchParams.set("created_by",r.created_by),r?.sort&&n.searchParams.set("sort",r.sort),r?.order&&n.searchParams.set("order",r.order),r?.limit&&n.searchParams.set("limit",String(r.limit)),r?.cursor&&n.searchParams.set("cursor",r.cursor),r?.status)for(let s of r.status)n.searchParams.append("status",s);let i=await fetch(n,{headers:{"Content-Type":"application/json"}});if(!i.ok)throw new m(i.status,await i.json().catch(()=>null));let a=await i.json();return{items:a.items,hasMore:a.has_more,nextCursor:a.next_cursor}},async get(r,n){let i=`event:${r}:${n}`,a=t.get(i);if(a)return a;let s=await o(e,`/v0/events/${r}/${n}`);return t.set(i,s),s}}}u();function X(e,t,r){return{async eligibility(n){return o(e,`/v1/faucet/eligibility?wallet=${n.toLowerCase()}&venue=${t}`)},async claim(n){return r?f(e,"/v1/faucet/claim",{wallet:n.toLowerCase()},r.getAuthHeader()):{success:!1,error:"venueId and venueApiKey required for faucet claims"}}}}u();async function N(e,t){return o(e,"/v1/stats/top-traders",{venue:t?.venue,limit:t?.limit})}async function S(e,t){return o(e,"/v0/leaderboard/pnl",{venue:t?.venue,period:t?.period,limit:t?.limit,cursor:t?.cursor})}async function O(e,t){return o(e,"/v0/leaderboard/volume",{venue:t?.venue,period:t?.period,limit:t?.limit,cursor:t?.cursor})}u();function z(e,t){return{async search(r){let n=new URL("/v0/markets",e);if(r?.q&&n.searchParams.set("q",r.q),r?.venue&&n.searchParams.set("venue",r.venue),r?.sort&&n.searchParams.set("sort",r.sort),r?.order&&n.searchParams.set("order",r.order),r?.limit&&n.searchParams.set("limit",String(r.limit)),r?.cursor&&n.searchParams.set("cursor",r.cursor),r?.status)for(let a of r.status)n.searchParams.append("status",a);let i=await fetch(n,{headers:{"Content-Type":"application/json"}});if(!i.ok){let{ApiError:a}=await Promise.resolve().then(()=>(u(),q));throw new a(i.status,await i.json().catch(()=>null))}return i.json()},async get(r,n){let i=`market:${r}:${n}`,a=t.get(i);if(a)return a;let s=await o(e,`/v0/markets/${r}/${n}`);return t.set(i,s),s}}}u();function Q(e,t){return{async active(){let r="season:active",n=t.get(r);if(n!==void 0)return n;let i=await o(e,"/v1/seasons/active").catch(()=>null);return t.set(r,i,6e4),i},async config(){let r="season:config",n=t.get(r);if(n!==void 0)return n;let i=await o(e,"/v1/seasons/active/config").catch(()=>null);return t.set(r,i,6e4),i}}}u();function Z(e,t){return{async points(r,n){let i=`user:${r}:points:${n?.season??"current"}`,a=t.get(i);if(a)return a;let s=await o(e,`/v1/points/${r}`,n?.season?{season:n.season}:void 0);return t.set(i,s),s},async dashboard(r,n){let i=`user:${r}:dashboard:${n?.venue??"all"}`,a=t.get(i);if(a)return a;let s=await o(e,`/v1/users/${r}/dashboard`,n?.venue?{venue:n.venue}:void 0);return t.set(i,s),s},linkWallet:r=>g(e,"/v1/identity/link",r),linkedWallets:r=>o(e,`/v1/identity/${r}`)}}u();function ee(e,t){return{markets:{async list(r,n){let i=`venue:${r}:markets:${n?.status??"all"}`,a=t.get(i);if(a)return a;let s=await o(e,`/v1/venues/${r}/markets`,{status:n?.status});return t.set(i,s),s},async add(r,n,i){let a=await f(e,`/v1/venues/${r}/markets`,{markets:n},i);return t.invalidate(`venue:${r}`),a},async remove(r,n,i,a){let s=await V(e,`/v1/venues/${r}/markets/${n}/${i}`,a);return t.invalidate(`venue:${r}`),s}},async stats(r,n){let i=`venue:${r}:stats:${n??"current"}`,a=t.get(i);if(a)return a;let s=await o(e,`/v1/points/venue/${r}`,n?{season:n}:void 0);return t.set(i,s),s},invalidate:r=>t.invalidate(`venue:${r}`),clearCache:()=>t.invalidate("venue:")}}function te(e){let t=x(e.cache),r=_({chainId:e.chainId,rpcUrl:e.rpcUrl,venueRegistryAddress:e.venueRegistryAddress,prophecyCoreAddress:e.prophecyCoreAddress,prophecySettlementAddress:e.prophecySettlementAddress}),n=e.venueId&&e.venueApiKey?K(e.venueId,e.venueApiKey):null,i={socialShare:()=>Promise.reject(new Error("venueId and venueApiKey required for event reporting")),receiptInspect:()=>Promise.reject(new Error("venueId and venueApiKey required for event reporting")),dailyChallenge:()=>Promise.reject(new Error("venueId and venueApiKey required for event reporting"))};return{chain:r,markets:z(e.dataApiUrl,t),eventsApi:C(e.dataApiUrl,t),venue:ee(e.partnersApiUrl,t),user:Z(e.partnersApiUrl,t),season:Q(e.partnersApiUrl,t),leaderboard:{pp:a=>N(e.partnersApiUrl,a),pnl:a=>S(e.dataApiUrl,a),volume:a=>O(e.dataApiUrl,a)},faucet:X(e.partnersApiUrl,e.venueId??"",n),events:n?J(e.partnersApiUrl,n):i,arbiter:{rate:a=>I(e.partnersApiUrl,a),preview:a=>A(e.partnersApiUrl,a),eventRating:(a,s)=>R(e.partnersApiUrl,a,s)},auth:n}}u();var re=require("ai"),c=require("zod"),L=c.z.object({type:c.z.enum(["ai","creator"]).describe("ai = verifiable from URL, creator = manual resolution"),name:c.z.string().describe("Market title \u2014 frames the specific prediction"),description:c.z.string().describe("What will be extracted / resolution criteria"),tradingStartTs:c.z.string().describe("ISO 8601 \u2014 when trading opens"),tradingEndTs:c.z.string().describe("ISO 8601 \u2014 when trading closes"),resolutionStartTs:c.z.string().describe("ISO 8601 \u2014 when resolution can begin"),resolutionEndTs:c.z.string().describe("ISO 8601 \u2014 resolution deadline"),extractionPrompt:c.z.string().optional().describe("Prompt used to extract the answer from sources"),urls:c.z.array(c.z.string()).optional().describe("Credible source URLs (2-4 recommended)"),options:c.z.array(c.z.string()).optional().describe("Possible outcomes for string extractions"),expectedOutcome:c.z.string().optional().describe("The user's prediction \u2014 inferred from the question"),resultType:c.z.enum(["string","number"]).optional().describe("Type of extraction result")});function je(){return`You are a prediction market configurator. Given a user's question or prediction, create a structured market definition.
1
+ "use strict";var Y=Object.defineProperty;var Be=Object.getOwnPropertyDescriptor;var $e=Object.getOwnPropertyNames;var Fe=Object.prototype.hasOwnProperty;var Ye=(e,t)=>()=>(e&&(t=e(e=0)),t);var G=(e,t)=>{for(var r in t)Y(e,r,{get:t[r],enumerable:!0})},Ve=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of $e(t))!Fe.call(e,a)&&a!==r&&Y(e,a,{get:()=>t[a],enumerable:!(n=Be(t,a))||n.enumerable});return e};var qe=e=>Ve(Y({},"__esModule",{value:!0}),e);var q={};G(q,{ApiError:()=>m,authedDelete:()=>V,authedPost:()=>f,get:()=>s,post:()=>g});async function A(e,t={}){let r={"Content-Type":"application/json",...t.headers},n=await fetch(e,{method:t.method??"GET",headers:r,body:t.body?JSON.stringify(t.body):void 0});if(!n.ok){let a=await n.json().catch(()=>null);throw new m(n.status,a)}return n.json()}function s(e,t,r){let n=new URL(t,e);if(r)for(let[a,i]of Object.entries(r))i!==void 0&&n.searchParams.set(a,String(i));return A(n)}function g(e,t,r){return A(new URL(t,e),{method:"POST",body:r})}function f(e,t,r,n){return A(new URL(t,e),{method:"POST",body:r,headers:{Authorization:`Bearer ${n}`}})}function V(e,t,r){return A(new URL(t,e),{method:"DELETE",headers:{Authorization:`Bearer ${r}`}})}var m,u=Ye(()=>{"use strict";m=class extends Error{constructor(r,n){super(`API error ${r}`);this.status=r;this.body=n;this.name="ApiError"}}});var ze={};G(ze,{ACTIVE_MARKET_CAP:()=>le,ApiError:()=>m,BANNED_DOMAINS:()=>l,CATEGORIES:()=>h,DEFAULT_CATEGORY:()=>b,DEFAULT_DURATION_HOURS:()=>y,DEFAULT_LIQUIDITY:()=>se,DEFAULT_RESOLUTION_HOURS:()=>ue,DEFAULT_TRADING_START_BUFFER_SECONDS:()=>ce,DURATION_HINTS:()=>w,ENTITY_TYPES:()=>v,LOW_CONFIDENCE_OVERRIDE:()=>T,MARKET_DEFAULTS:()=>he,MAX_BINARY_PROBABILITY:()=>B,MAX_DURATION_HOURS:()=>D,MAX_OPTION_PROBABILITY:()=>F,MIN_BINARY_PROBABILITY:()=>M,MIN_DURATION_HOURS:()=>U,MIN_OPTION_PROBABILITY:()=>$,RESOLUTION_CONFIDENCE_THRESHOLD:()=>ie,SIMILARITY_THRESHOLD:()=>oe,VIRALITY_THRESHOLD:()=>ae,buildCarouselPrompt:()=>Ee,buildEntityExtractionPrompt:()=>Ie,buildGroupingPrompt:()=>we,buildMarketGenerationPrompt:()=>be,buildNewsContextPrompt:()=>Pe,buildProbabilityEstimationPrompt:()=>Ae,buildReframePrompt:()=>ve,buildResolutionEvalPrompt:()=>Te,buildUrlGuidanceBlock:()=>Re,clampBinaryProbability:()=>ke,clampDuration:()=>E,createCache:()=>k,createChainClient:()=>C,createEventsApiNamespace:()=>_,createMarketDefinition:()=>ne,createProphecyClient:()=>te,getEventRating:()=>R,getPPLeaderboard:()=>N,getPnLLeaderboard:()=>O,getVolumeLeaderboard:()=>S,googleNewsFallbackUrl:()=>Ne,isBannedDomain:()=>_e,isValidUrl:()=>Ce,marketDefinitionSchema:()=>L,normalizeOptionProbabilities:()=>xe,parseLlmMarketJson:()=>Oe,previewRating:()=>I,rateMarketDraft:()=>P,signCreateMarketPermit:()=>De,signTradePermit:()=>Ue});module.exports=qe(ze);u();function j(e){return{prompt:e.prompt,answer_type:e.answerType,source_urls:e.sourceUrls,min_agreement:e.minAgreement,trading_start:e.tradingStart,trading_end:e.tradingEnd,resolution_start:e.resolutionStart,resolution_end:e.resolutionEnd}}function We(e){return{ratedAt:e.rated_at,finalScore:e.final_score,ratingBand:{rating:e.rating_band.rating,minScore:e.rating_band.min_score,maxScore:e.rating_band.max_score,definition:e.rating_band.definition},criteria:e.criteria.map(t=>({key:t.key,name:t.name,criterionType:t.criterion_type,evaluation:t.evaluation,status:t.status,summary:t.summary,weight:t.weight,score:t.score,weightedScore:t.weighted_score}))}}async function I(e,t){return g(e,"/v1/arbiter/preview",j(t))}async function P(e,t){let r=await g(e,"/v1/arbiter/preview",j(t));return We(r)}async function R(e,t,r){return s(e,`/v1/arbiter/events/${t}/${r}`)}function k(e={}){let t=e.defaultTtlMs??15e3,r=new Map;return{get(n){if(t===0)return;let a=r.get(n);if(a){if(Date.now()>a.expiresAt){r.delete(n);return}return a.data}},set(n,a,i){let o=i??t;o!==0&&r.set(n,{data:a,expiresAt:Date.now()+o})},invalidate(n){for(let a of r.keys())a.startsWith(n)&&r.delete(a)},clear(){r.clear()}}}var p=require("viem"),He=[{inputs:[{internalType:"uint256",name:"venueId",type:"uint256"},{internalType:"address",name:"user",type:"address"}],name:"getNonce",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}],x=[{inputs:[{internalType:"uint256",name:"marketId",type:"uint256"},{internalType:"address",name:"user",type:"address"}],name:"getUserPosition",outputs:[{components:[{internalType:"uint256",name:"yes",type:"uint256"},{internalType:"uint256",name:"no",type:"uint256"},{internalType:"bool",name:"claimed",type:"bool"}],internalType:"struct IProphecyCore.SharePosition",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"marketId",type:"uint256"}],name:"getMarketCore",outputs:[{components:[{internalType:"uint256",name:"tradingStartTs",type:"uint256"},{internalType:"uint256",name:"tradingEndTs",type:"uint256"},{internalType:"uint256",name:"resolutionStartTs",type:"uint256"},{internalType:"uint256",name:"resolutionEndTs",type:"uint256"},{internalType:"address",name:"creator",type:"address"},{internalType:"address",name:"resolver",type:"address"},{internalType:"address",name:"stakeToken",type:"address"},{internalType:"bool",name:"resolved",type:"bool"},{internalType:"uint8",name:"outcome",type:"uint8"},{internalType:"uint256",name:"totalYesShares",type:"uint256"},{internalType:"uint256",name:"totalNoShares",type:"uint256"},{internalType:"uint256",name:"totalShares",type:"uint256"},{internalType:"uint256",name:"participantCount",type:"uint256"},{internalType:"uint256",name:"initialLiquidityBase",type:"uint256"},{internalType:"uint256",name:"feeBps",type:"uint256"}],internalType:"struct IProphecyCore.MarketCore",name:"core",type:"tuple"},{internalType:"string",name:"name",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"marketId",type:"uint256"}],name:"getCurrentReserves",outputs:[{internalType:"uint256",name:"yesPool",type:"uint256"},{internalType:"uint256",name:"noPool",type:"uint256"}],stateMutability:"view",type:"function"}],Ge=[{inputs:[{internalType:"uint256",name:"marketId",type:"uint256"}],name:"claimSettlement",outputs:[{internalType:"uint256",name:"payout",type:"uint256"}],stateMutability:"nonpayable",type:"function"}];function C(e){let t=(0,p.defineChain)({id:e.chainId,name:`Somnia (${e.chainId})`,nativeCurrency:{name:"STT",symbol:"STT",decimals:18},rpcUrls:{default:{http:[e.rpcUrl]}}}),r=(0,p.createPublicClient)({chain:t,transport:(0,p.http)(e.rpcUrl)});return{async getVenueNonce(n,a){return r.readContract({address:e.venueRegistryAddress,abi:He,functionName:"getNonce",args:[n,a]})},async getMarketCore(n){let[a,i]=await r.readContract({address:e.prophecyCoreAddress,abi:x,functionName:"getMarketCore",args:[n]});return{core:a,name:i}},async getReserves(n){let[a,i]=await r.readContract({address:e.prophecyCoreAddress,abi:x,functionName:"getCurrentReserves",args:[n]});return{yesPool:a,noPool:i}},async getUserPosition(n,a){return await r.readContract({address:e.prophecyCoreAddress,abi:x,functionName:"getUserPosition",args:[n,a]})},async getUserPositions(n,a){if(n.length===0)return[];let i=n.map(d=>({address:e.prophecyCoreAddress,abi:x,functionName:"getUserPosition",args:[d,a]}));return(await r.multicall({contracts:i})).map(d=>d.status!=="success"?null:d.result)},encodeClaimSettlement(n){if(!e.prophecySettlementAddress)throw new Error("prophecySettlementAddress is required in ChainConfig for claim operations");return{to:e.prophecySettlementAddress,data:(0,p.encodeFunctionData)({abi:Ge,functionName:"claimSettlement",args:[n]})}}}}function K(e,t){return{venueId:e,getAuthHeader:()=>`Bearer ${t}`}}function J(e,t){async function r(n,a){let i=new URL(`/v1/events${n}`,e),o=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:t.getAuthHeader()},body:JSON.stringify(a)});if(!o.ok){let d=await o.json().catch(()=>null),{ApiError:Me}=await Promise.resolve().then(()=>(u(),q));throw new Me(o.status,d)}return o.json()}return{socialShare:(n,a)=>r("/social-share",{wallet:n,marketId:a}),receiptInspect:(n,a)=>r("/receipt-inspect",{wallet:n,marketId:a}),dailyChallenge:n=>r("/daily-challenge",{wallet:n})}}u();function _(e,t){return{async search(r){let n=new URL("/v0/events",e);if(r?.q&&n.searchParams.set("q",r.q),r?.venue&&n.searchParams.set("venue",r.venue),r?.tag&&n.searchParams.set("tag",r.tag),r?.created_by&&n.searchParams.set("created_by",r.created_by),r?.sort&&n.searchParams.set("sort",r.sort),r?.order&&n.searchParams.set("order",r.order),r?.limit&&n.searchParams.set("limit",String(r.limit)),r?.cursor&&n.searchParams.set("cursor",r.cursor),r?.status)for(let o of r.status)n.searchParams.append("status",o);let a=await fetch(n,{headers:{"Content-Type":"application/json"}});if(!a.ok)throw new m(a.status,await a.json().catch(()=>null));let i=await a.json();return{items:i.items,hasMore:i.has_more,nextCursor:i.next_cursor}},async get(r,n){let a=`event:${r}:${n}`,i=t.get(a);if(i)return i;let o=await s(e,`/v0/events/${r}/${n}`);return t.set(a,o),o}}}u();function X(e,t,r){return{async eligibility(n){return s(e,`/v1/faucet/eligibility?wallet=${n.toLowerCase()}&venue=${t}`)},async claim(n){return r?f(e,"/v1/faucet/claim",{wallet:n.toLowerCase()},r.getAuthHeader()):{success:!1,error:"venueId and venueApiKey required for faucet claims"}}}}u();async function N(e,t){return s(e,"/v1/stats/top-traders",{venue:t?.venue,limit:t?.limit})}async function O(e,t){return s(e,"/v0/leaderboard/pnl",{venue:t?.venue,period:t?.period,limit:t?.limit,cursor:t?.cursor})}async function S(e,t){return s(e,"/v0/leaderboard/volume",{venue:t?.venue,period:t?.period,limit:t?.limit,cursor:t?.cursor})}u();function z(e,t){return{async search(r){let n=new URL("/v0/markets",e);if(r?.q&&n.searchParams.set("q",r.q),r?.venue&&n.searchParams.set("venue",r.venue),r?.sort&&n.searchParams.set("sort",r.sort),r?.order&&n.searchParams.set("order",r.order),r?.limit&&n.searchParams.set("limit",String(r.limit)),r?.cursor&&n.searchParams.set("cursor",r.cursor),r?.status)for(let i of r.status)n.searchParams.append("status",i);let a=await fetch(n,{headers:{"Content-Type":"application/json"}});if(!a.ok){let{ApiError:i}=await Promise.resolve().then(()=>(u(),q));throw new i(a.status,await a.json().catch(()=>null))}return a.json()},async get(r,n){let a=`market:${r}:${n}`,i=t.get(a);if(i)return i;let o=await s(e,`/v0/markets/${r}/${n}`);return t.set(a,o),o}}}u();function Q(e,t){return{async active(){let r="season:active",n=t.get(r);if(n!==void 0)return n;let a=await s(e,"/v1/seasons/active").catch(()=>null);return t.set(r,a,6e4),a},async config(){let r="season:config",n=t.get(r);if(n!==void 0)return n;let a=await s(e,"/v1/seasons/active/config").catch(()=>null);return t.set(r,a,6e4),a}}}u();function Z(e,t){return{async points(r,n){let a=`user:${r}:points:${n?.season??"current"}`,i=t.get(a);if(i)return i;let o=await s(e,`/v1/points/${r}`,n?.season?{season:n.season}:void 0);return t.set(a,o),o},async dashboard(r,n){let a=`user:${r}:dashboard:${n?.venue??"all"}`,i=t.get(a);if(i)return i;let o=await s(e,`/v1/users/${r}/dashboard`,n?.venue?{venue:n.venue}:void 0);return t.set(a,o),o},linkWallet:r=>g(e,"/v1/identity/link",r),linkedWallets:r=>s(e,`/v1/identity/${r}`)}}u();function ee(e,t){return{markets:{async list(r,n){let a=`venue:${r}:markets:${n?.status??"all"}`,i=t.get(a);if(i)return i;let o=await s(e,`/v1/venues/${r}/markets`,{status:n?.status});return t.set(a,o),o},async add(r,n,a){let i=await f(e,`/v1/venues/${r}/markets`,{markets:n},a);return t.invalidate(`venue:${r}`),i},async remove(r,n,a,i){let o=await V(e,`/v1/venues/${r}/markets/${n}/${a}`,i);return t.invalidate(`venue:${r}`),o}},async stats(r,n){let a=`venue:${r}:stats:${n??"current"}`,i=t.get(a);if(i)return i;let o=await s(e,`/v1/points/venue/${r}`,n?{season:n}:void 0);return t.set(a,o),o},invalidate:r=>t.invalidate(`venue:${r}`),clearCache:()=>t.invalidate("venue:")}}function te(e){let t=k(e.cache),r=C({chainId:e.chainId,rpcUrl:e.rpcUrl,venueRegistryAddress:e.venueRegistryAddress,prophecyCoreAddress:e.prophecyCoreAddress,prophecySettlementAddress:e.prophecySettlementAddress}),n=e.venueId&&e.venueApiKey?K(e.venueId,e.venueApiKey):null,a={socialShare:()=>Promise.reject(new Error("venueId and venueApiKey required for event reporting")),receiptInspect:()=>Promise.reject(new Error("venueId and venueApiKey required for event reporting")),dailyChallenge:()=>Promise.reject(new Error("venueId and venueApiKey required for event reporting"))};return{chain:r,markets:z(e.dataApiUrl,t),eventsApi:_(e.dataApiUrl,t),venue:ee(e.partnersApiUrl,t),user:Z(e.partnersApiUrl,t),season:Q(e.partnersApiUrl,t),leaderboard:{pp:i=>N(e.partnersApiUrl,i),pnl:i=>O(e.dataApiUrl,i),volume:i=>S(e.dataApiUrl,i)},faucet:X(e.partnersApiUrl,e.venueId??"",n),events:n?J(e.partnersApiUrl,n):a,arbiter:{rate:i=>P(e.partnersApiUrl,i),preview:i=>I(e.partnersApiUrl,i),eventRating:(i,o)=>R(e.partnersApiUrl,i,o)},auth:n}}u();var re=require("ai"),c=require("zod"),L=c.z.object({type:c.z.enum(["ai","creator"]).describe("ai = verifiable from URL, creator = manual resolution"),name:c.z.string().describe("Market title \u2014 frames the specific prediction"),description:c.z.string().describe("What will be extracted / resolution criteria"),tradingStartTs:c.z.string().describe("ISO 8601 \u2014 when trading opens"),tradingEndTs:c.z.string().describe("ISO 8601 \u2014 when trading closes"),resolutionStartTs:c.z.string().describe("ISO 8601 \u2014 when resolution can begin"),resolutionEndTs:c.z.string().describe("ISO 8601 \u2014 resolution deadline"),extractionPrompt:c.z.string().optional().describe("Prompt used to extract the answer from sources"),urls:c.z.array(c.z.string()).optional().describe("Credible source URLs (2-4 recommended)"),options:c.z.array(c.z.string()).optional().describe("Possible outcomes for string extractions"),expectedOutcome:c.z.string().optional().describe("The user's prediction \u2014 inferred from the question"),resultType:c.z.enum(["string","number"]).optional().describe("Type of extraction result")});function je(){return`You are a prediction market configurator. Given a user's question or prediction, create a structured market definition.
2
2
 
3
3
  Today's date (UTC) is: ${new Date().toISOString().split("T")[0]}
4
4
 
@@ -23,9 +23,25 @@ Set appropriate timestamps:
23
23
  User timezone: ${e.userTimeZone}. Interpret relative dates accordingly.`:"",{text:n}=await(0,re.generateText)({model:e.model,system:`${t}
24
24
 
25
25
  Respond ONLY with valid JSON matching this schema. No markdown, no explanation.
26
- Schema: ${JSON.stringify(L.shape)}`,prompt:`Create a prediction market for: "${e.question}"${r}`});return L.parse(JSON.parse(n))}var h=["crypto","sport","pop_culture","technology","politics","science","entertainment"],b="politics",v=["country","person","company","team","crypto","topic"],ie=6,ae=4,se=.85,y=168,U=1,D=720,M=.05,B=.95,$=.02,F=.95,oe="100",ce=60,ue=1,le=5e3,l=["x.com","twitter.com","charts.spotify.com","xtracker.polymarket.com","www.youtube.com","youtube.com","www.espncricinfo.com","espncricinfo.com","liquipedia.net","www.dotabuff.com","dotabuff.com","www.premierleague.com","premierleague.com","gol.gg","www.gol.gg"],w={crypto:"1-4h",sport:"4-12h",news:"18-24h",politics:"18-24h"},de={"9-10":"massive global interest (Super Bowl, elections)","7-8":"mainstream (top-20 crypto, major sports leagues, significant news)","5-6":"niche interest","1-4":"very low interest"},me={"9-10":"URL always contains the answer (CoinGecko, ESPN scoreboard)","7-8":"URL very likely has the answer (major news, official standings)","4-6":"uncertain (general news, social media)","1-3":"unlikely to have a clear answer"},pe={explicit:{min:.9,max:1,label:"URL explicitly states the outcome"},strong:{min:.5,max:.8,label:"Strong but indirect evidence"},tangential:{min:.1,max:.4,label:"Tangentially related content"},none:{min:0,max:.1,label:"No relevant information \u2014 UNKNOWN"}},T=.6,ge={frontrunner:{min:.1,max:.3},midfield:{min:.02,max:.08},backmarker:{min:.002,max:.02}},he={categories:h,defaultCategory:b,entityTypes:v,viralityThreshold:6,resolutionConfidenceThreshold:4,similarityThreshold:.85,defaultDurationHours:168,minDurationHours:1,maxDurationHours:720,minBinaryProbability:.05,maxBinaryProbability:.95,minOptionProbability:.02,maxOptionProbability:.95,defaultLiquidity:"100",defaultTradingStartBufferSeconds:60,defaultResolutionHours:1,activeMarketCap:5e3,bannedDomains:l,durationHints:w,lowConfidenceOverride:T};function ye(){return new Date().toUTCString()}function Ke(){return new Date().toISOString().slice(0,10)}function H(e){return`BANNED RESOLUTION DOMAINS (JS-rendered/auth-walled): ${e.join(", ")}. Use alternatives or set confidence \u2264 2.`}function fe(e){return e.join("|")}function be(e){let t={categories:h,defaultDurationHours:168,bannedDomains:l,...e};return`You are a prediction market designer for Prophecy, a blockchain-based prediction market platform. Given a user's natural language prompt, generate a complete, well-structured prediction market.
27
-
28
- CURRENT DATE/TIME: ${ye()}
26
+ Schema: ${JSON.stringify(L.shape)}`,prompt:`Create a prediction market for: "${e.question}"${r}`});return L.parse(JSON.parse(n))}var h=["crypto","sport","pop_culture","technology","politics","science","entertainment"],b="politics",v=["country","person","company","team","crypto","topic"],ae=6,ie=4,oe=.85,y=168,U=1,D=720,M=.05,B=.95,$=.02,F=.95,se="100",ce=60,ue=1,le=5e3,l=["x.com","twitter.com","charts.spotify.com","xtracker.polymarket.com","www.youtube.com","youtube.com","www.espncricinfo.com","espncricinfo.com","liquipedia.net","www.dotabuff.com","dotabuff.com","www.premierleague.com","premierleague.com","gol.gg","www.gol.gg"],w={crypto:"1-4h",sport:"4-12h",news:"18-24h",politics:"18-24h"},de={"9-10":"massive global interest (Super Bowl, elections)","7-8":"mainstream (top-20 crypto, major sports leagues, significant news)","5-6":"niche interest","1-4":"very low interest"},me={"9-10":"URL always contains the answer (CoinGecko, ESPN scoreboard)","7-8":"URL very likely has the answer (major news, official standings)","4-6":"uncertain (general news, social media)","1-3":"unlikely to have a clear answer"},pe={explicit:{min:.9,max:1,label:"URL explicitly states the outcome"},strong:{min:.5,max:.8,label:"Strong but indirect evidence"},tangential:{min:.1,max:.4,label:"Tangentially related content"},none:{min:0,max:.1,label:"No relevant information \u2014 UNKNOWN"}},T=.6,ge={frontrunner:{min:.1,max:.3},midfield:{min:.02,max:.08},backmarker:{min:.002,max:.02}},he={categories:h,defaultCategory:b,entityTypes:v,viralityThreshold:6,resolutionConfidenceThreshold:4,similarityThreshold:.85,defaultDurationHours:168,minDurationHours:1,maxDurationHours:720,minBinaryProbability:.05,maxBinaryProbability:.95,minOptionProbability:.02,maxOptionProbability:.95,defaultLiquidity:"100",defaultTradingStartBufferSeconds:60,defaultResolutionHours:1,activeMarketCap:5e3,bannedDomains:l,durationHints:w,lowConfidenceOverride:T};function ye(){return new Date().toUTCString()}function Ke(){return new Date().toISOString().slice(0,10)}function W(e){return`BANNED RESOLUTION DOMAINS (JS-rendered/auth-walled): ${e.join(", ")}. Use alternatives or set confidence \u2264 2.`}function fe(e){return e.join("|")}function be(e){let t={categories:h,defaultDurationHours:168,bannedDomains:l,includeResolutionMeta:!1,stalenessMode:"strict",requireCompleteOptions:!1,includeContentGuidelines:!1,...e},r=ye(),n=t.includeResolutionMeta?`
27
+ "resolution_url_confidence": 7,
28
+ "is_already_decided": false,
29
+ "already_decided_reason": "",`:"",a=t.requireCompleteOptions?`- For multi-option markets (e.g., "Who will win?"), include ALL plausible options \u2014 do NOT truncate to a short list. Always include an "Other" option as the last choice.
30
+ - For multi-option markets, use web search to verify the options are CURRENT participants.`:'- For multi-option markets (e.g. "who will win"), use web search to verify the options are CURRENT participants. Always include an "Other" option as the last choice.',i=t.stalenessMode==="lenient"?`Staleness detection:
31
+ - ONLY set "is_already_decided": true if you have CONCRETE EVIDENCE that the event has ALREADY OCCURRED or the result is ALREADY KNOWN as of ${r}.
32
+ - Common stale patterns: awards already given, matches already played, deadlines already passed.
33
+ - If you cannot find information about an event, that does NOT mean it already happened. The user may be creating a market about something niche, internal, or not yet public. When in doubt, set "is_already_decided": false.`:`Staleness detection \u2014 CRITICAL:
34
+ - If the event has ALREADY OCCURRED or the result is ALREADY KNOWN as of ${r}, set "is_already_decided": true and explain in "already_decided_reason".
35
+ - Common stale patterns: awards already given, matches already played, nominations already announced, elections already held, records already broken, deadlines already passed.
36
+ - If unsure whether an event has happened, err on the side of caution and mark it as decided with a reason.
37
+ - Only create markets for events that are genuinely upcoming or currently unresolved.`,o=t.includeContentGuidelines?`
38
+ Content guidelines:
39
+ - No markets about violence, hate speech, self-harm, or illegal activity
40
+ - No markets that could manipulate real-world outcomes
41
+ - Markets should be verifiable using publicly available information`:"";return`You are a prediction market designer for Prophecy, a blockchain-based prediction market platform. Given a user's natural language prompt, generate a complete, well-structured prediction market.
42
+
43
+ CURRENT DATE/TIME: ${r}
44
+ Use this to assess whether events have already occurred or deadlines have passed.
29
45
 
30
46
  Return ONLY valid JSON (no markdown, no code fences) with this exact structure:
31
47
  {
@@ -38,38 +54,47 @@ Return ONLY valid JSON (no markdown, no code fences) with this exact structure:
38
54
  "category": "${fe(t.categories)}",
39
55
  "subcategory": "a more specific subcategory",
40
56
  "tags": ["relevant", "tags", "for", "discovery"],
41
- "trading_end_time": "ISO 8601 UTC timestamp when trading should close",
42
- "suggested_duration_hours": ${t.defaultDurationHours},
43
- "source_references": ["https://relevant-source.com/specific-page"],
57
+ "trading_end_time": "REQUIRED \u2014 ISO 8601 UTC timestamp when trading should close (e.g. 2026-04-22T00:00:00Z)",
58
+ "suggested_duration_hours": "ONLY if no specific date \u2014 hours until trading closes (1-720)",
59
+ "source_references": ["https://relevant-source.com/specific-page"],${n}
44
60
  "news_context": [{"title": "Article headline", "url": "https://source.com/article", "source": "Publication Name"}]
45
61
  }
46
62
 
47
63
  News context (news_context field):
48
64
  - Include 2-4 real, relevant news articles that provide background context for this market.
49
65
  - Each entry needs: "title" (article headline), "url" (full URL to the article), "source" (publication name).
50
- - Only include articles you found via web search \u2014 do NOT fabricate URLs. Return [] if none found.
66
+ - Prefer recent articles from reputable sources. Only include articles you found via web search \u2014 do NOT fabricate URLs.
67
+ - If you cannot find relevant articles, return an empty array [].
51
68
 
52
69
  Rules:
53
70
  - The question must be specific, unambiguous, and have a clear resolution date or condition
54
71
  - CRITICAL: The event MUST be in the future. Use web search to verify the current state of events.
55
72
  - If the user says "next X", search to find what the ACTUAL next upcoming X is \u2014 do NOT rely on your training data for schedules, fixtures, or dates.
56
73
  - If a specific event has ALREADY HAPPENED (results exist), do NOT create a market for it. Find the next upcoming instance instead.
57
- - Example: if user says "next F1 race winner" and the Australian GP already happened, find the actual next race on the calendar.
58
74
  - If the user specifies custom options (not yes/no), use those options instead
59
- - For multi-option markets (e.g. "who will win"), use web search to verify the options are CURRENT participants. For sports, use the current season's roster/entry list \u2014 not last year's. For elections, use confirmed candidates. Always include an "Other" option as the last choice.
75
+ ${a}
60
76
  - expected_result should be one of the options
61
- - trading_end_time (PREFERRED): When the user mentions a specific date or the event has a known deadline, set trading_end_time to an ISO 8601 UTC timestamp. This is more precise than suggested_duration_hours. Example: "before April 22" \u2192 set trading_end_time to "2026-04-22T00:00:00Z".
62
- - suggested_duration_hours: Fallback when no specific date is mentioned (1-720 hours). The market MUST end BEFORE the event resolves \u2014 set duration so trading closes just before the event starts/result is announced.
77
+ - CRITICAL \u2014 TRADING END TIME: You MUST always set trading_end_time to an ISO 8601 UTC timestamp. Calculate this from the user's prompt:
78
+ - If the user mentions a date (e.g. "before April 22"), use that date: "2026-04-22T00:00:00Z"
79
+ - If the user mentions a timeframe (e.g. "this week"), calculate the end of that period
80
+ - If no date is mentioned, calculate from now + a reasonable duration for the event type
81
+ - The trading_end_time must ALWAYS be set. Do NOT leave it as the example string.
82
+ - suggested_duration_hours: Backup field. Set this to the number of hours between now and trading_end_time. If you set trading_end_time correctly, this field is derived from it.
63
83
  - source_references should be real, relevant websites that could help verify the outcome \u2014 use FULL URLs to specific pages, not just domains
84
+ - source_references[0] is the URL the AI resolution agent will actually VISIT to determine the outcome. It must be a FULL URL to a specific page containing the relevant data.
64
85
  - Do NOT guess URL path segments you are unsure about (e.g., race numbers, event IDs). Use stable hub/event pages instead.
65
- - The prompt field is what the AI resolver will see when resolving the market \u2014 make it a clear, answerable question
86
+ - If you cannot find a reliable, specific URL, use a Google News search URL as fallback: https://news.google.com/search?q=relevant+search+terms
87
+ - The prompt field is what the AI resolver will see when resolving the market \u2014 make it a clear, answerable question with instructions on what data to check
66
88
  - Keep descriptions concise but informative
67
89
  - Tags should be lowercase, relevant keywords
68
90
  ${t.urlGuidance?`
69
91
  ${t.urlGuidance}`:""}
92
+
93
+ ${i}
94
+ ${o}
70
95
  ${t.extraInstructions?`
71
96
  ${t.extraInstructions}`:""}
72
- ${H(t.bannedDomains)}`}function ve(e){let t={categories:h,durationHints:w,bannedDomains:l,...e},r=Object.entries(t.durationHints).map(([n,i])=>`${n} ${i}`).join(", ");return`You are a prediction market designer for Prophecy, a blockchain-based prediction market platform. Reframe market candidates as SHORT-DURATION prediction markets with clear, near-term resolution.
97
+ ${W(t.bannedDomains)}`}function ve(e){let t={categories:h,durationHints:w,bannedDomains:l,...e},r=Object.entries(t.durationHints).map(([n,a])=>`${n} ${a}`).join(", ");return`You are a prediction market designer for Prophecy, a blockchain-based prediction market platform. Reframe market candidates as SHORT-DURATION prediction markets with clear, near-term resolution.
73
98
 
74
99
  MARKET FORMAT:
75
100
 
@@ -102,8 +127,8 @@ QUESTION NAMING \u2014 be SPECIFIC:
102
127
  Always include teams/competitors + competition, price thresholds + timeframe, specific event/award names, who + what + when. A reader must understand the question without additional context.
103
128
 
104
129
  SCORING:
105
- - virality_score (1-10): ${Object.entries(de).map(([n,i])=>`${n} ${i}`).join(", ")}.
106
- - resolution_url_confidence (1-10): ${Object.entries(me).map(([n,i])=>`${n} ${i}`).join(", ")}.
130
+ - virality_score (1-10): ${Object.entries(de).map(([n,a])=>`${n} ${a}`).join(", ")}.
131
+ - resolution_url_confidence (1-10): ${Object.entries(me).map(([n,a])=>`${n} ${a}`).join(", ")}.
107
132
 
108
133
  SOURCE-SPECIFIC RULES:
109
134
  - Crypto: Use CoinGecko coin pages, confidence 9-10, duration 1-6h.
@@ -111,7 +136,7 @@ SOURCE-SPECIFIC RULES:
111
136
  - News: Find specific data-rich pages. For search-based: use news.google.com/search?q=... URLs.
112
137
  - Polymarket: Keep same trading_end_time, proposition, deadline, threshold. Use outcomePrices for probabilities. EXCEPTION: convert hidden multi-outcome as above.
113
138
 
114
- ${H(t.bannedDomains)}
139
+ ${W(t.bannedDomains)}
115
140
 
116
141
  source_references[0] is the URL the AI resolver visits. Must be a FULL URL to a specific page with relevant data. The "prompt" field tells the resolver exactly what to look for on that page.
117
142
  ${t.extraInstructions?`
@@ -163,7 +188,7 @@ Respond with ONLY valid JSON (no markdown, no code fences):
163
188
  "reasoning": "Quote or cite the specific evidence from the URL content that supports your answer, or explain why the URL content was insufficient"
164
189
  }
165
190
  ${t.extraInstructions?`
166
- ${t.extraInstructions}`:""}`}function Pe(e){let t={maxSlots:10,...e};return`You are a prediction market curator selecting events for a homepage carousel.
191
+ ${t.extraInstructions}`:""}`}function Ee(e){let t={maxSlots:10,...e};return`You are a prediction market curator selecting events for a homepage carousel.
167
192
 
168
193
  Pick exactly ${t.maxSlots} events from the candidate list to maximize engagement. Selection criteria (priority order):
169
194
  1. Trending & timely \u2014 cross-reference with Polymarket trending data. Prefer current hot topics.
@@ -177,7 +202,7 @@ ${t.extraCriteria?`7. ${t.extraCriteria}`:""}
177
202
  ONLY select from candidate event ids. Return ONLY raw JSON:
178
203
  {"selected_event_ids": [123, 456, ...], "reasoning": "Brief explanation"}
179
204
  ${t.extraInstructions?`
180
- ${t.extraInstructions}`:""}`}function Ee(e){let t={calibration:ge,...e},r=t.calibration;return`You are a world-class probability estimation expert with deep domain knowledge. Given a group of mutually exclusive outcomes, estimate realistic probabilities that each will occur. Your probabilities MUST sum to exactly 1.0.
205
+ ${t.extraInstructions}`:""}`}function Ae(e){let t={calibration:ge,...e},r=t.calibration;return`You are a world-class probability estimation expert with deep domain knowledge. Given a group of mutually exclusive outcomes, estimate realistic probabilities that each will occur. Your probabilities MUST sum to exactly 1.0.
181
206
 
182
207
  Current date: ${Ke()}
183
208
 
@@ -194,7 +219,7 @@ CALIBRATION RULES \u2014 critical for realistic odds:
194
219
 
195
220
  Return ONLY a JSON object mapping each option name (exactly as given) to its probability. No explanation.
196
221
  ${t.extraInstructions?`
197
- ${t.extraInstructions}`:""}`}function Ae(e){let t={entityTypes:v,maxEntities:2,...e};return`Analyze this prediction market question and extract the PRIMARY visual entity that should be shown as a thumbnail image.
222
+ ${t.extraInstructions}`:""}`}function Ie(e){let t={entityTypes:v,maxEntities:2,...e};return`Analyze this prediction market question and extract the PRIMARY visual entity that should be shown as a thumbnail image.
198
223
 
199
224
  Return ONLY valid JSON (no markdown) with this structure:
200
225
  {
@@ -223,7 +248,7 @@ Examples:
223
248
  - "Lakers vs Celtics game" \u2192 [{"type": "team", "name": "Los Angeles Lakers", "searchQuery": "Lakers logo"}]
224
249
  - "S&P 500 price movement" \u2192 [{"type": "topic", "name": "S&P 500", "searchQuery": "stock market chart"}]
225
250
  ${t.extraInstructions?`
226
- ${t.extraInstructions}`:""}`}function Ie(e){let t={maxArticles:4,preferredSources:["ESPN","BBC","Reuters","CoinDesk","Bloomberg","AP News"],...e};return`You are a news research assistant. Given a prediction market question, find 2-${t.maxArticles} real, currently accessible news articles that provide relevant background context for this market.
251
+ ${t.extraInstructions}`:""}`}function Pe(e){let t={maxArticles:4,preferredSources:["ESPN","BBC","Reuters","CoinDesk","Bloomberg","AP News"],...e};return`You are a news research assistant. Given a prediction market question, find 2-${t.maxArticles} real, currently accessible news articles that provide relevant background context for this market.
227
252
 
228
253
  Return ONLY valid JSON (no markdown, no code fences) \u2014 an array of objects:
229
254
  [{"title": "Article headline", "url": "https://full-url.com/article", "source": "Publication Name"}]
@@ -254,8 +279,8 @@ Source-specific URL guidance:
254
279
  - News: Find the most specific, data-rich page possible. For search-based resolution: Use Google News search URLs like https://news.google.com/search?q=specific+search+terms.
255
280
  - Pop culture / entertainment: Use official announcement pages or news search URLs.
256
281
 
257
- ${H(t.bannedDomains)}
282
+ ${W(t.bannedDomains)}
258
283
  If the only resolution URL for a market would be a banned domain, either find an alternative or set resolution_url_confidence to 2 or below.
259
284
  ${t.extraGuidance?`
260
- ${t.extraGuidance}`:""}`}function P(e,t){let r=t?.min??1,n=t?.max??720,i=t?.fallback??168,a=typeof e=="number"&&Number.isFinite(e)?e:i;return Math.min(n,Math.max(r,a))}function xe(e,t){let r=t?.min??.05,n=t?.max??.95;return Math.min(n,Math.max(r,e))}function ke(e,t){let r=t?.min??.02,n=t?.max??.95,i=e.map(s=>Math.min(n,Math.max(r,s))),a=i.reduce((s,d)=>s+d,0);return a===0?e.map(()=>1/e.length):i.map(s=>s/a)}function _e(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function Ce(e,t){let r=new Set(t??l);try{let n=new URL(e).hostname;return r.has(n)||r.has(n.replace(/^www\./,""))}catch{return!1}}function Ne(e){let t=e.replace(/[?!.,;:'"]/g,"").split(/\s+/).slice(0,10).join("+");return`https://news.google.com/search?q=${encodeURIComponent(t)}`}function Se(e){let t=e.trim();if(t.includes("```")){let a=t.match(/```(?:json)?\s*([\s\S]*?)```/);a?.[1]&&(t=a[1].trim())}if(!t.startsWith("{")){let a=t.indexOf("{");a!==-1&&(t=t.slice(a))}if(t.includes("}")){let a=t.lastIndexOf("}");t=t.slice(0,a+1)}t=t.replace(/"(?:[^"\\]|\\.)*"/g,a=>a.replace(/\n/g,"\\n").replace(/\r/g,"\\r")),t=t.replace(/,\s*([}\]])/g,"$1");let r;try{r=JSON.parse(t)}catch{throw new Error("Failed to parse LLM response as JSON. Please try again.")}let n=r;if(typeof n.question!="string"||!n.question)throw new Error("Generated market is missing a question");if(!Array.isArray(n.options)||n.options.length<2)throw new Error("Generated market must have at least 2 options");let i;if(typeof n.trading_end_time=="string"&&n.trading_end_time){let a=new Date(n.trading_end_time),s=Date.now();!Number.isNaN(a.getTime())&&a.getTime()>s?i=P((a.getTime()-s)/36e5):i=P(n.suggested_duration_hours)}else i=P(n.suggested_duration_hours);return{question:n.question,description:n.description||"",resolution_criteria:n.resolution_criteria||"",prompt:n.prompt||n.question,options:n.options,expected_result:n.expected_result||n.options[0]||"",category:n.category||b,subcategory:n.subcategory||"",tags:Array.isArray(n.tags)?n.tags:[],suggested_duration_hours:i,source_references:Array.isArray(n.source_references)?n.source_references:[],_raw:n}}var W=require("viem/accounts"),Oe=60,Le={name:"VenueRegistry",version:"1"},Je={CreateMarketPermit:[{name:"name",type:"string"},{name:"venueId",type:"uint256"},{name:"tradingStartTs",type:"uint256"},{name:"tradingEndTs",type:"uint256"},{name:"resolutionStartTs",type:"uint256"},{name:"resolutionEndTs",type:"uint256"},{name:"stakeToken",type:"address"},{name:"initialLiquidityBase",type:"uint256"},{name:"noMatchOutcome",type:"uint8"},{name:"resolverType",type:"uint8"},{name:"creator",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},Xe={TradePermit:[{name:"marketId",type:"uint256"},{name:"venueId",type:"uint256"},{name:"user",type:"address"},{name:"amount",type:"uint256"},{name:"action",type:"uint8"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]};async function Ue(e){let t=(0,W.privateKeyToAccount)(e.operatorPrivateKey),r=BigInt(Math.floor(Date.now()/1e3)+Oe);return{signature:await t.signTypedData({domain:{...Le,chainId:e.chainId,verifyingContract:e.venueRegistryAddress},types:Xe,primaryType:"TradePermit",message:{marketId:e.marketId,venueId:e.venueId,user:e.user,amount:e.amount,action:e.action,nonce:e.nonce,deadline:r}}),signer:t.address,deadline:r}}async function De(e){let t=(0,W.privateKeyToAccount)(e.operatorPrivateKey),r=BigInt(Math.floor(Date.now()/1e3)+Oe);return{signature:await t.signTypedData({domain:{...Le,chainId:e.chainId,verifyingContract:e.venueRegistryAddress},types:Je,primaryType:"CreateMarketPermit",message:{name:e.name,venueId:e.venueId,tradingStartTs:BigInt(e.tradingStartTs),tradingEndTs:BigInt(e.tradingEndTs),resolutionStartTs:BigInt(e.resolutionStartTs),resolutionEndTs:BigInt(e.resolutionEndTs),stakeToken:e.stakeToken,initialLiquidityBase:e.initialLiquidityBase,noMatchOutcome:e.noMatchOutcome,resolverType:e.resolverType,creator:e.creator,nonce:e.nonce,deadline:r}}),signer:t.address,deadline:r}}0&&(module.exports={ACTIVE_MARKET_CAP,ApiError,BANNED_DOMAINS,CATEGORIES,DEFAULT_CATEGORY,DEFAULT_DURATION_HOURS,DEFAULT_LIQUIDITY,DEFAULT_RESOLUTION_HOURS,DEFAULT_TRADING_START_BUFFER_SECONDS,DURATION_HINTS,ENTITY_TYPES,LOW_CONFIDENCE_OVERRIDE,MARKET_DEFAULTS,MAX_BINARY_PROBABILITY,MAX_DURATION_HOURS,MAX_OPTION_PROBABILITY,MIN_BINARY_PROBABILITY,MIN_DURATION_HOURS,MIN_OPTION_PROBABILITY,RESOLUTION_CONFIDENCE_THRESHOLD,SIMILARITY_THRESHOLD,VIRALITY_THRESHOLD,buildCarouselPrompt,buildEntityExtractionPrompt,buildGroupingPrompt,buildMarketGenerationPrompt,buildNewsContextPrompt,buildProbabilityEstimationPrompt,buildReframePrompt,buildResolutionEvalPrompt,buildUrlGuidanceBlock,clampBinaryProbability,clampDuration,createCache,createChainClient,createEventsApiNamespace,createMarketDefinition,createProphecyClient,getEventRating,getPPLeaderboard,getPnLLeaderboard,getVolumeLeaderboard,googleNewsFallbackUrl,isBannedDomain,isValidUrl,marketDefinitionSchema,normalizeOptionProbabilities,parseLlmMarketJson,previewRating,rateMarketDraft,signCreateMarketPermit,signTradePermit});
285
+ ${t.extraGuidance}`:""}`}function E(e,t){let r=t?.min??1,n=t?.max??720,a=t?.fallback??168,i=typeof e=="number"&&Number.isFinite(e)?e:a;return Math.min(n,Math.max(r,i))}function ke(e,t){let r=t?.min??.05,n=t?.max??.95;return Math.min(n,Math.max(r,e))}function xe(e,t){let r=t?.min??.02,n=t?.max??.95,a=e.map(o=>Math.min(n,Math.max(r,o))),i=a.reduce((o,d)=>o+d,0);return i===0?e.map(()=>1/e.length):a.map(o=>o/i)}function Ce(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function _e(e,t){let r=new Set(t??l);try{let n=new URL(e).hostname;return r.has(n)||r.has(n.replace(/^www\./,""))}catch{return!1}}function Ne(e){let t=e.replace(/[?!.,;:'"]/g,"").split(/\s+/).slice(0,10).join("+");return`https://news.google.com/search?q=${encodeURIComponent(t)}`}function Oe(e){let t=e.trim();if(t.includes("```")){let i=t.match(/```(?:json)?\s*([\s\S]*?)```/);i?.[1]&&(t=i[1].trim())}if(!t.startsWith("{")){let i=t.indexOf("{");i!==-1&&(t=t.slice(i))}if(t.includes("}")){let i=t.lastIndexOf("}");t=t.slice(0,i+1)}t=t.replace(/"(?:[^"\\]|\\.)*"/g,i=>i.replace(/\n/g,"\\n").replace(/\r/g,"\\r")),t=t.replace(/,\s*([}\]])/g,"$1");let r;try{r=JSON.parse(t)}catch{throw new Error("Failed to parse LLM response as JSON. Please try again.")}let n=r;if(typeof n.question!="string"||!n.question)throw new Error("Generated market is missing a question");if(!Array.isArray(n.options)||n.options.length<2)throw new Error("Generated market must have at least 2 options");let a;if(typeof n.trading_end_time=="string"&&n.trading_end_time){let i=new Date(n.trading_end_time),o=Date.now();!Number.isNaN(i.getTime())&&i.getTime()>o?a=E((i.getTime()-o)/36e5):a=E(n.suggested_duration_hours)}else a=E(n.suggested_duration_hours);return{question:n.question,description:n.description||"",resolution_criteria:n.resolution_criteria||"",prompt:n.prompt||n.question,options:n.options,expected_result:n.expected_result||n.options[0]||"",category:n.category||b,subcategory:n.subcategory||"",tags:Array.isArray(n.tags)?n.tags:[],suggested_duration_hours:a,source_references:Array.isArray(n.source_references)?n.source_references:[],_raw:n}}var H=require("viem/accounts"),Se=60,Le={name:"VenueRegistry",version:"1"},Je={CreateMarketPermit:[{name:"name",type:"string"},{name:"venueId",type:"uint256"},{name:"tradingStartTs",type:"uint256"},{name:"tradingEndTs",type:"uint256"},{name:"resolutionStartTs",type:"uint256"},{name:"resolutionEndTs",type:"uint256"},{name:"stakeToken",type:"address"},{name:"initialLiquidityBase",type:"uint256"},{name:"noMatchOutcome",type:"uint8"},{name:"resolverType",type:"uint8"},{name:"creator",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},Xe={TradePermit:[{name:"marketId",type:"uint256"},{name:"venueId",type:"uint256"},{name:"user",type:"address"},{name:"amount",type:"uint256"},{name:"action",type:"uint8"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]};async function Ue(e){let t=(0,H.privateKeyToAccount)(e.operatorPrivateKey),r=BigInt(Math.floor(Date.now()/1e3)+Se);return{signature:await t.signTypedData({domain:{...Le,chainId:e.chainId,verifyingContract:e.venueRegistryAddress},types:Xe,primaryType:"TradePermit",message:{marketId:e.marketId,venueId:e.venueId,user:e.user,amount:e.amount,action:e.action,nonce:e.nonce,deadline:r}}),signer:t.address,deadline:r}}async function De(e){let t=(0,H.privateKeyToAccount)(e.operatorPrivateKey),r=BigInt(Math.floor(Date.now()/1e3)+Se);return{signature:await t.signTypedData({domain:{...Le,chainId:e.chainId,verifyingContract:e.venueRegistryAddress},types:Je,primaryType:"CreateMarketPermit",message:{name:e.name,venueId:e.venueId,tradingStartTs:BigInt(e.tradingStartTs),tradingEndTs:BigInt(e.tradingEndTs),resolutionStartTs:BigInt(e.resolutionStartTs),resolutionEndTs:BigInt(e.resolutionEndTs),stakeToken:e.stakeToken,initialLiquidityBase:e.initialLiquidityBase,noMatchOutcome:e.noMatchOutcome,resolverType:e.resolverType,creator:e.creator,nonce:e.nonce,deadline:r}}),signer:t.address,deadline:r}}0&&(module.exports={ACTIVE_MARKET_CAP,ApiError,BANNED_DOMAINS,CATEGORIES,DEFAULT_CATEGORY,DEFAULT_DURATION_HOURS,DEFAULT_LIQUIDITY,DEFAULT_RESOLUTION_HOURS,DEFAULT_TRADING_START_BUFFER_SECONDS,DURATION_HINTS,ENTITY_TYPES,LOW_CONFIDENCE_OVERRIDE,MARKET_DEFAULTS,MAX_BINARY_PROBABILITY,MAX_DURATION_HOURS,MAX_OPTION_PROBABILITY,MIN_BINARY_PROBABILITY,MIN_DURATION_HOURS,MIN_OPTION_PROBABILITY,RESOLUTION_CONFIDENCE_THRESHOLD,SIMILARITY_THRESHOLD,VIRALITY_THRESHOLD,buildCarouselPrompt,buildEntityExtractionPrompt,buildGroupingPrompt,buildMarketGenerationPrompt,buildNewsContextPrompt,buildProbabilityEstimationPrompt,buildReframePrompt,buildResolutionEvalPrompt,buildUrlGuidanceBlock,clampBinaryProbability,clampDuration,createCache,createChainClient,createEventsApiNamespace,createMarketDefinition,createProphecyClient,getEventRating,getPPLeaderboard,getPnLLeaderboard,getVolumeLeaderboard,googleNewsFallbackUrl,isBannedDomain,isValidUrl,marketDefinitionSchema,normalizeOptionProbabilities,parseLlmMarketJson,previewRating,rateMarketDraft,signCreateMarketPermit,signTradePermit});
261
286
  //# sourceMappingURL=index.cjs.map