@prophecy-dev/sdk 0.1.0 → 0.1.2

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,KAAK,gBAAgB,EACrB,KAAK,aAAa,EAClB,KAAK,iBAAiB,EACtB,KAAK,oBAAoB,EACzB,eAAe,GAChB,MAAM,WAAW,CAAA;AAGlB,YAAY,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAA;AAGvC,YAAY,EAAE,WAAW,EAAE,MAAM,SAAS,CAAA;AAE1C,OAAO,EACL,KAAK,WAAW,EAChB,KAAK,WAAW,EAChB,iBAAiB,EACjB,KAAK,UAAU,EACf,KAAK,aAAa,GACnB,MAAM,SAAS,CAAA;AAChB,OAAO,EACL,oBAAoB,EACpB,KAAK,cAAc,EACnB,KAAK,oBAAoB,GAC1B,MAAM,UAAU,CAAA;AAGjB,YAAY,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,UAAU,CAAA;AAG5D,OAAO,EACL,wBAAwB,EACxB,KAAK,cAAc,EACnB,KAAK,SAAS,EACd,KAAK,eAAe,EACpB,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,EACrB,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,UAAU,EACf,KAAK,kBAAkB,EACvB,KAAK,UAAU,EACf,KAAK,kBAAkB,GACxB,MAAM,cAAc,CAAA;AAGrB,YAAY,EACV,iBAAiB,EACjB,iBAAiB,EACjB,eAAe,GAChB,MAAM,UAAU,CAAA;AAIjB,OAAO,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAA;AAGjC,OAAO,EACL,iBAAiB,EACjB,gBAAgB,EAChB,oBAAoB,EACpB,KAAK,mBAAmB,EACxB,KAAK,oBAAoB,EACzB,KAAK,kBAAkB,EACvB,KAAK,mBAAmB,EACxB,KAAK,sBAAsB,EAC3B,KAAK,uBAAuB,GAC7B,MAAM,eAAe,CAAA;AAGtB,YAAY,EAAE,aAAa,EAAE,MAAM,OAAO,CAAA;AAG1C,OAAO,EACL,sBAAsB,EACtB,KAAK,gBAAgB,EACrB,KAAK,qBAAqB,EAC1B,sBAAsB,GACvB,MAAM,mBAAmB,CAAA;AAG1B,YAAY,EACV,UAAU,EACV,gBAAgB,EAChB,mBAAmB,GACpB,MAAM,WAAW,CAAA;AAGlB,OAAO,EAAE,sBAAsB,EAAE,eAAe,EAAE,MAAM,WAAW,CAAA;AAGnE,YAAY,EACV,YAAY,EACZ,UAAU,EACV,eAAe,GAChB,MAAM,UAAU,CAAA;AAGjB,YAAY,EACV,iBAAiB,EACjB,YAAY,EACZ,gBAAgB,EAChB,mBAAmB,EACnB,aAAa,EACb,cAAc,EACd,aAAa,EACb,aAAa,EACb,cAAc,EACd,cAAc,GACf,MAAM,QAAQ,CAAA;AAGf,YAAY,EACV,eAAe,EACf,gBAAgB,EAChB,qBAAqB,EACrB,cAAc,EACd,UAAU,GACX,MAAM,SAAS,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,KAAK,gBAAgB,EACrB,KAAK,oBAAoB,EACzB,KAAK,aAAa,EAClB,KAAK,iBAAiB,EACtB,KAAK,oBAAoB,EACzB,KAAK,WAAW,EAChB,cAAc,EACd,aAAa,EACb,eAAe,GAChB,MAAM,WAAW,CAAA;AAGlB,YAAY,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAA;AAGvC,YAAY,EAAE,WAAW,EAAE,MAAM,SAAS,CAAA;AAC1C,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAA;AAErC,OAAO,EACL,KAAK,WAAW,EAChB,KAAK,WAAW,EAChB,iBAAiB,EACjB,KAAK,UAAU,EACf,KAAK,aAAa,GACnB,MAAM,SAAS,CAAA;AAChB,OAAO,EACL,oBAAoB,EACpB,KAAK,cAAc,EACnB,KAAK,oBAAoB,GAC1B,MAAM,UAAU,CAAA;AAGjB,YAAY,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,UAAU,CAAA;AAG5D,OAAO,EACL,wBAAwB,EACxB,KAAK,cAAc,EACnB,KAAK,SAAS,EACd,KAAK,eAAe,EACpB,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,EACrB,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,UAAU,EACf,KAAK,kBAAkB,EACvB,KAAK,UAAU,EACf,KAAK,kBAAkB,GACxB,MAAM,cAAc,CAAA;AAGrB,YAAY,EACV,iBAAiB,EACjB,iBAAiB,EACjB,eAAe,GAChB,MAAM,UAAU,CAAA;AAGjB,OAAO,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAA;AAGjC,OAAO,EACL,iBAAiB,EACjB,gBAAgB,EAChB,oBAAoB,EACpB,KAAK,mBAAmB,EACxB,KAAK,oBAAoB,EACzB,KAAK,kBAAkB,EACvB,KAAK,mBAAmB,EACxB,KAAK,sBAAsB,EAC3B,KAAK,uBAAuB,GAC7B,MAAM,eAAe,CAAA;AAGtB,YAAY,EAAE,aAAa,EAAE,MAAM,OAAO,CAAA;AAG1C,OAAO,EACL,sBAAsB,EACtB,KAAK,gBAAgB,EACrB,KAAK,qBAAqB,EAC1B,sBAAsB,GACvB,MAAM,mBAAmB,CAAA;AAG1B,OAAO,EACL,iBAAiB,EACjB,cAAc,EACd,KAAK,YAAY,EACjB,UAAU,EACV,gBAAgB,EAChB,sBAAsB,EACtB,iBAAiB,EACjB,wBAAwB,EACxB,oCAAoC,EACpC,cAAc,EACd,YAAY,EACZ,KAAK,UAAU,EACf,uBAAuB,EACvB,eAAe,EACf,sBAAsB,EACtB,kBAAkB,EAClB,sBAAsB,EACtB,KAAK,cAAc,EACnB,KAAK,oBAAoB,EACzB,sBAAsB,EACtB,kBAAkB,EAClB,sBAAsB,EACtB,+BAA+B,EAC/B,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,mBAAmB,CAAA;AAG1B,OAAO,EACL,mBAAmB,EACnB,2BAA2B,EAC3B,mBAAmB,EACnB,2BAA2B,EAC3B,sBAAsB,EACtB,gCAAgC,EAChC,kBAAkB,EAClB,yBAAyB,EACzB,qBAAqB,EACrB,KAAK,oBAAoB,EACzB,KAAK,4BAA4B,EACjC,KAAK,oBAAoB,EACzB,KAAK,4BAA4B,EACjC,KAAK,uBAAuB,EAC5B,KAAK,iCAAiC,EACtC,KAAK,mBAAmB,EACxB,KAAK,0BAA0B,EAC/B,KAAK,iBAAiB,GACvB,MAAM,kBAAkB,CAAA;AAGzB,OAAO,EACL,sBAAsB,EACtB,aAAa,EACb,KAAK,mBAAmB,EACxB,qBAAqB,EACrB,cAAc,EACd,UAAU,EACV,4BAA4B,EAC5B,kBAAkB,GACnB,MAAM,qBAAqB,CAAA;AAG5B,YAAY,EACV,UAAU,EACV,gBAAgB,EAChB,mBAAmB,GACpB,MAAM,WAAW,CAAA;AAGlB,OAAO,EAAE,sBAAsB,EAAE,eAAe,EAAE,MAAM,WAAW,CAAA;AAGnE,YAAY,EACV,YAAY,EACZ,UAAU,EACV,eAAe,GAChB,MAAM,UAAU,CAAA;AAGjB,YAAY,EACV,iBAAiB,EACjB,YAAY,EACZ,gBAAgB,EAChB,mBAAmB,EACnB,aAAa,EACb,cAAc,EACd,aAAa,EACb,aAAa,EACb,cAAc,EACd,cAAc,GACf,MAAM,QAAQ,CAAA;AAGf,YAAY,EACV,eAAe,EACf,gBAAgB,EAChB,qBAAqB,EACrB,cAAc,EACd,UAAU,GACX,MAAM,SAAS,CAAA"}
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- var U=Object.defineProperty;var B=(e,n)=>()=>(e&&(n=e(e=0)),n);var $=(e,n)=>{for(var t in n)U(e,t,{get:n[t],enumerable:!0})};var f={};$(f,{ApiError:()=>d,authedDelete:()=>b,authedPost:()=>p,get:()=>o,post:()=>l});async function g(e,n={}){let t={"Content-Type":"application/json",...n.headers},r=await fetch(e,{method:n.method??"GET",headers:t,body:n.body?JSON.stringify(n.body):void 0});if(!r.ok){let a=await r.json().catch(()=>null);throw new d(r.status,a)}return r.json()}function o(e,n,t){let r=new URL(n,e);if(t)for(let[a,i]of Object.entries(t))i!==void 0&&r.searchParams.set(a,String(i));return g(r)}function l(e,n,t){return g(new URL(n,e),{method:"POST",body:t})}function p(e,n,t,r){return g(new URL(n,e),{method:"POST",body:t,headers:{Authorization:`Bearer ${r}`}})}function b(e,n,t){return g(new URL(n,e),{method:"DELETE",headers:{Authorization:`Bearer ${t}`}})}var d,c=B(()=>{"use strict";d=class extends Error{constructor(t,r){super(`API error ${t}`);this.status=t;this.body=r;this.name="ApiError"}}});c();function q(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 O(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(n=>({key:n.key,name:n.name,criterionType:n.criterion_type,evaluation:n.evaluation,status:n.status,summary:n.summary,weight:n.weight,score:n.score,weightedScore:n.weighted_score}))}}async function v(e,n){let t=await l(e,"/v0/ratings/markets",q(n));return O(t)}import{createPublicClient as W,defineChain as F,encodeFunctionData as j,http as K}from"viem";var H=[{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"}],y=[{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"}],Y=[{inputs:[{internalType:"uint256",name:"marketId",type:"uint256"}],name:"claimSettlement",outputs:[{internalType:"uint256",name:"payout",type:"uint256"}],stateMutability:"nonpayable",type:"function"}];function h(e){let n=F({id:e.chainId,name:`Somnia (${e.chainId})`,nativeCurrency:{name:"STT",symbol:"STT",decimals:18},rpcUrls:{default:{http:[e.rpcUrl]}}}),t=W({chain:n,transport:K(e.rpcUrl)});return{async getVenueNonce(r,a){return t.readContract({address:e.venueRegistryAddress,abi:H,functionName:"getNonce",args:[r,a]})},async getMarketCore(r){let[a,i]=await t.readContract({address:e.prophecyCoreAddress,abi:y,functionName:"getMarketCore",args:[r]});return{core:a,name:i}},async getReserves(r){let[a,i]=await t.readContract({address:e.prophecyCoreAddress,abi:y,functionName:"getCurrentReserves",args:[r]});return{yesPool:a,noPool:i}},async getUserPosition(r,a){return await t.readContract({address:e.prophecyCoreAddress,abi:y,functionName:"getUserPosition",args:[r,a]})},async getUserPositions(r,a){if(r.length===0)return[];let i=r.map(m=>({address:e.prophecyCoreAddress,abi:y,functionName:"getUserPosition",args:[m,a]}));return(await t.multicall({contracts:i})).map(m=>m.status!=="success"?null:m.result)},encodeClaimSettlement(r){if(!e.prophecySettlementAddress)throw new Error("prophecySettlementAddress is required in ChainConfig for claim operations");return{to:e.prophecySettlementAddress,data:j({abi:Y,functionName:"claimSettlement",args:[r]})}}}}function A(e,n){return{venueId:e,getAuthHeader:()=>`Bearer ${n}`}}function x(e={}){let n=e.defaultTtlMs??15e3,t=new Map;return{get(r){if(n===0)return;let a=t.get(r);if(a){if(Date.now()>a.expiresAt){t.delete(r);return}return a.data}},set(r,a,i){let s=i??n;s!==0&&t.set(r,{data:a,expiresAt:Date.now()+s})},invalidate(r){for(let a of t.keys())a.startsWith(r)&&t.delete(a)},clear(){t.clear()}}}function w(e,n){async function t(r,a){let i=new URL(`/v1/events${r}`,e),s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:n.getAuthHeader()},body:JSON.stringify(a)});if(!s.ok){let m=await s.json().catch(()=>null),{ApiError:V}=await Promise.resolve().then(()=>(c(),f));throw new V(s.status,m)}return s.json()}return{socialShare:(r,a)=>t("/social-share",{wallet:r,marketId:a}),receiptInspect:(r,a)=>t("/receipt-inspect",{wallet:r,marketId:a}),dailyChallenge:r=>t("/daily-challenge",{wallet:r})}}c();function P(e,n){return{async search(t){let r=new URL("/v0/events",e);if(t?.query&&r.searchParams.set("q",t.query),t?.venue&&r.searchParams.set("venue",t.venue),t?.tag&&r.searchParams.set("tag",t.tag),t?.createdBy&&r.searchParams.set("created_by",t.createdBy),t?.sort&&r.searchParams.set("sort",t.sort),t?.order&&r.searchParams.set("order",t.order),t?.limit&&r.searchParams.set("limit",String(t.limit)),t?.cursor&&r.searchParams.set("cursor",t.cursor),t?.status)for(let s of t.status)r.searchParams.append("status",s);let a=await fetch(r,{headers:{"Content-Type":"application/json"}});if(!a.ok)throw new d(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(t,r){let a=`event:${t}:${r}`,i=n.get(a);if(i)return i;let s=await o(e,`/v0/events/${t}/${r}`);return n.set(a,s),s}}}c();function S(e,n,t){return{async eligibility(r){return o(e,`/v1/faucet/eligibility?wallet=${r.toLowerCase()}&venue=${n}`)},async claim(r){return t?p(e,"/v1/faucet/claim",{wallet:r.toLowerCase()},t.getAuthHeader()):{success:!1,error:"venueId and venueApiKey required for faucet claims"}}}}c();async function k(e,n){return o(e,"/v1/stats/top-traders",{venue:n?.venue,limit:n?.limit})}async function T(e,n){return o(e,"/v0/leaderboard/pnl",{venue:n?.venue,period:n?.period,limit:n?.limit,cursor:n?.cursor})}async function C(e,n){return o(e,"/v0/leaderboard/volume",{venue:n?.venue,period:n?.period,limit:n?.limit,cursor:n?.cursor})}c();function M(e,n){return{async search(t){let r=new URL("/v0/markets",e);if(t?.query&&r.searchParams.set("q",t.query),t?.venue&&r.searchParams.set("venue",t.venue),t?.sort&&r.searchParams.set("sort",t.sort),t?.order&&r.searchParams.set("order",t.order),t?.limit&&r.searchParams.set("limit",String(t.limit)),t?.cursor&&r.searchParams.set("cursor",t.cursor),t?.status)for(let i of t.status)r.searchParams.append("status",i);let a=await fetch(r,{headers:{"Content-Type":"application/json"}});if(!a.ok){let{ApiError:i}=await Promise.resolve().then(()=>(c(),f));throw new i(a.status,await a.json().catch(()=>null))}return a.json()},async get(t,r){let a=`market:${t}:${r}`,i=n.get(a);if(i)return i;let s=await o(e,`/v0/markets/${t}/${r}`);return n.set(a,s),s}}}c();function R(e,n){return{async active(){let t="season:active",r=n.get(t);if(r!==void 0)return r;let a=await o(e,"/v1/seasons/active").catch(()=>null);return n.set(t,a,6e4),a},async config(){let t="season:config",r=n.get(t);if(r!==void 0)return r;let a=await o(e,"/v1/seasons/active/config").catch(()=>null);return n.set(t,a,6e4),a}}}c();function _(e,n){return{async points(t,r){let a=`user:${t}:points:${r?.season??"current"}`,i=n.get(a);if(i)return i;let s=await o(e,`/v1/points/${t}`,r?.season?{season:r.season}:void 0);return n.set(a,s),s},async dashboard(t,r){let a=`user:${t}:dashboard:${r?.venue??"all"}`,i=n.get(a);if(i)return i;let s=await o(e,`/v1/users/${t}/dashboard`,r?.venue?{venue:r.venue}:void 0);return n.set(a,s),s},linkWallet:t=>l(e,"/v1/identity/link",t),linkedWallets:t=>o(e,`/v1/identity/${t}`)}}c();function I(e,n){return{markets:{async list(t,r){let a=`venue:${t}:markets:${r?.status??"all"}`,i=n.get(a);if(i)return i;let s=await o(e,`/v1/venues/${t}/markets`,{status:r?.status});return n.set(a,s),s},async add(t,r,a){let i=await p(e,`/v1/venues/${t}/markets`,{markets:r},a);return n.invalidate(`venue:${t}`),i},async remove(t,r,a,i){let s=await b(e,`/v1/venues/${t}/markets/${r}/${a}`,i);return n.invalidate(`venue:${t}`),s}},async stats(t,r){let a=`venue:${t}:stats:${r??"current"}`,i=n.get(a);if(i)return i;let s=await o(e,`/v1/points/venue/${t}`,r?{season:r}:void 0);return n.set(a,s),s},invalidate:t=>n.invalidate(`venue:${t}`),clearCache:()=>n.invalidate("venue:")}}function z(e){let n=x(e.cache),t=h({chainId:e.chainId,rpcUrl:e.rpcUrl,venueRegistryAddress:e.venueRegistryAddress,prophecyCoreAddress:e.prophecyCoreAddress,prophecySettlementAddress:e.prophecySettlementAddress}),r=e.venueId&&e.venueApiKey?A(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:t,markets:M(e.dataApiUrl,n),eventsApi:P(e.dataApiUrl,n),venue:I(e.partnersApiUrl,n),user:_(e.partnersApiUrl,n),season:R(e.partnersApiUrl,n),leaderboard:{pp:i=>k(e.partnersApiUrl,i),pnl:i=>T(e.dataApiUrl,i),volume:i=>C(e.dataApiUrl,i)},faucet:S(e.partnersApiUrl,e.venueId??"",r),events:r?w(e.partnersApiUrl,r):a,arbiter:e.arbiterUrl?{rate:i=>v(e.arbiterUrl,i)}:{rate:()=>Promise.reject(new Error("arbiterUrl is required in ProphecyClientConfig to rate markets"))},auth:r}}c();import{generateText as J}from"ai";import{z as u}from"zod";var E=u.object({type:u.enum(["ai","creator"]).describe("ai = verifiable from URL, creator = manual resolution"),name:u.string().describe("Market title \u2014 frames the specific prediction"),description:u.string().describe("What will be extracted / resolution criteria"),tradingStartTs:u.string().describe("ISO 8601 \u2014 when trading opens"),tradingEndTs:u.string().describe("ISO 8601 \u2014 when trading closes"),resolutionStartTs:u.string().describe("ISO 8601 \u2014 when resolution can begin"),resolutionEndTs:u.string().describe("ISO 8601 \u2014 resolution deadline"),extractionPrompt:u.string().optional().describe("Prompt used to extract the answer from sources"),urls:u.array(u.string()).optional().describe("Credible source URLs (2-4 recommended)"),options:u.array(u.string()).optional().describe("Possible outcomes for string extractions"),expectedOutcome:u.string().optional().describe("The user's prediction \u2014 inferred from the question"),resultType:u.enum(["string","number"]).optional().describe("Type of extraction result")});function G(){return`You are a prediction market configurator. Given a user's question or prediction, create a structured market definition.
1
+ var oe=Object.defineProperty;var ce=(e,t)=>()=>(e&&(t=e(e=0)),t);var ue=(e,t)=>{for(var r in t)oe(e,r,{get:t[r],enumerable:!0})};var I={};ue(I,{ApiError:()=>m,authedDelete:()=>A,authedPost:()=>g,get:()=>o,post:()=>p});async function f(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 f(n)}function p(e,t,r){return f(new URL(t,e),{method:"POST",body:r})}function g(e,t,r,n){return f(new URL(t,e),{method:"POST",body:r,headers:{Authorization:`Bearer ${n}`}})}function A(e,t,r){return f(new URL(t,e),{method:"DELETE",headers:{Authorization:`Bearer ${r}`}})}var m,u=ce(()=>{"use strict";m=class extends Error{constructor(r,n){super(`API error ${r}`);this.status=r;this.body=n;this.name="ApiError"}}});u();function q(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 le(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 R(e,t){return p(e,"/v1/arbiter/preview",q(t))}async function x(e,t){let r=await p(e,"/v1/arbiter/preview",q(t));return le(r)}async function k(e,t,r){return o(e,`/v1/arbiter/events/${t}/${r}`)}function _(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()}}}import{createPublicClient as de,defineChain as me,encodeFunctionData as pe,http as ge}from"viem";var 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"}],b=[{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"}],ye=[{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=me({id:e.chainId,name:`Somnia (${e.chainId})`,nativeCurrency:{name:"STT",symbol:"STT",decimals:18},rpcUrls:{default:{http:[e.rpcUrl]}}}),r=de({chain:t,transport:ge(e.rpcUrl)});return{async getVenueNonce(n,i){return r.readContract({address:e.venueRegistryAddress,abi:he,functionName:"getNonce",args:[n,i]})},async getMarketCore(n){let[i,a]=await r.readContract({address:e.prophecyCoreAddress,abi:b,functionName:"getMarketCore",args:[n]});return{core:i,name:a}},async getReserves(n){let[i,a]=await r.readContract({address:e.prophecyCoreAddress,abi:b,functionName:"getCurrentReserves",args:[n]});return{yesPool:i,noPool:a}},async getUserPosition(n,i){return await r.readContract({address:e.prophecyCoreAddress,abi:b,functionName:"getUserPosition",args:[n,i]})},async getUserPositions(n,i){if(n.length===0)return[];let a=n.map(l=>({address:e.prophecyCoreAddress,abi:b,functionName:"getUserPosition",args:[l,i]}));return(await r.multicall({contracts:a})).map(l=>l.status!=="success"?null:l.result)},encodeClaimSettlement(n){if(!e.prophecySettlementAddress)throw new Error("prophecySettlementAddress is required in ChainConfig for claim operations");return{to:e.prophecySettlementAddress,data:pe({abi:ye,functionName:"claimSettlement",args:[n]})}}}}function H(e,t){return{venueId:e,getAuthHeader:()=>`Bearer ${t}`}}function W(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 l=await s.json().catch(()=>null),{ApiError:se}=await Promise.resolve().then(()=>(u(),I));throw new se(s.status,l)}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 N(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 G(e,t,r){return{async eligibility(n){return o(e,`/v1/faucet/eligibility?wallet=${n.toLowerCase()}&venue=${t}`)},async claim(n){return r?g(e,"/v1/faucet/claim",{wallet:n.toLowerCase()},r.getAuthHeader()):{success:!1,error:"venueId and venueApiKey required for faucet claims"}}}}u();async function S(e,t){return o(e,"/v1/stats/top-traders",{venue:t?.venue,limit:t?.limit})}async function O(e,t){return o(e,"/v0/leaderboard/pnl",{venue:t?.venue,period:t?.period,limit:t?.limit,cursor:t?.cursor})}async function L(e,t){return o(e,"/v0/leaderboard/volume",{venue:t?.venue,period:t?.period,limit:t?.limit,cursor:t?.cursor})}u();function j(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(),I));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 K(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 J(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=>p(e,"/v1/identity/link",r),linkedWallets:r=>o(e,`/v1/identity/${r}`)}}u();function X(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 g(e,`/v1/venues/${r}/markets`,{markets:n},i);return t.invalidate(`venue:${r}`),a},async remove(r,n,i,a){let s=await A(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 fe(e){let t=_(e.cache),r=C({chainId:e.chainId,rpcUrl:e.rpcUrl,venueRegistryAddress:e.venueRegistryAddress,prophecyCoreAddress:e.prophecyCoreAddress,prophecySettlementAddress:e.prophecySettlementAddress}),n=e.venueId&&e.venueApiKey?H(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:j(e.dataApiUrl,t),eventsApi:N(e.dataApiUrl,t),venue:X(e.partnersApiUrl,t),user:J(e.partnersApiUrl,t),season:K(e.partnersApiUrl,t),leaderboard:{pp:a=>S(e.partnersApiUrl,a),pnl:a=>O(e.dataApiUrl,a),volume:a=>L(e.dataApiUrl,a)},faucet:G(e.partnersApiUrl,e.venueId??"",n),events:n?W(e.partnersApiUrl,n):i,arbiter:{rate:a=>x(e.partnersApiUrl,a),preview:a=>R(e.partnersApiUrl,a),eventRating:(a,s)=>k(e.partnersApiUrl,a,s)},auth:n}}u();import{generateText as be}from"ai";import{z as c}from"zod";var U=c.object({type:c.enum(["ai","creator"]).describe("ai = verifiable from URL, creator = manual resolution"),name:c.string().describe("Market title \u2014 frames the specific prediction"),description:c.string().describe("What will be extracted / resolution criteria"),tradingStartTs:c.string().describe("ISO 8601 \u2014 when trading opens"),tradingEndTs:c.string().describe("ISO 8601 \u2014 when trading closes"),resolutionStartTs:c.string().describe("ISO 8601 \u2014 when resolution can begin"),resolutionEndTs:c.string().describe("ISO 8601 \u2014 resolution deadline"),extractionPrompt:c.string().optional().describe("Prompt used to extract the answer from sources"),urls:c.array(c.string()).optional().describe("Credible source URLs (2-4 recommended)"),options:c.array(c.string()).optional().describe("Possible outcomes for string extractions"),expectedOutcome:c.string().optional().describe("The user's prediction \u2014 inferred from the question"),resultType:c.enum(["string","number"]).optional().describe("Type of extraction result")});function ve(){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
 
@@ -17,11 +17,245 @@ For creator-resolved markets:
17
17
 
18
18
  Set appropriate timestamps:
19
19
  - tradingStartTs: when trading opens (usually now or soon)
20
- - tradingEndTs: when trading closes (usually just before the event)
20
+ - tradingEndTs: when trading closes \u2014 CRITICAL: if the user mentions a specific date (e.g. "before April 22"), use that date. Do not estimate a duration that falls short of the stated deadline.
21
21
  - resolutionStartTs: when the outcome can be checked (usually when event concludes)
22
- - resolutionEndTs: deadline for resolution (usually hours/days after event)`}async function Z(e){let n=e.systemPrompt??G(),t=e.userTimeZone?`
23
- User timezone: ${e.userTimeZone}. Interpret relative dates accordingly.`:"",{text:r}=await J({model:e.model,system:`${n}
22
+ - resolutionEndTs: deadline for resolution (usually hours/days after event)`}async function we(e){let t=e.systemPrompt??ve(),r=e.userTimeZone?`
23
+ User timezone: ${e.userTimeZone}. Interpret relative dates accordingly.`:"",{text:n}=await be({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(E.shape)}`,prompt:`Create a prediction market for: "${e.question}"${t}`});return E.parse(JSON.parse(r))}import{privateKeyToAccount as L}from"viem/accounts";var N=60,D={name:"VenueRegistry",version:"1"},Q={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"}]},X={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 ee(e){let n=L(e.operatorPrivateKey),t=BigInt(Math.floor(Date.now()/1e3)+N);return{signature:await n.signTypedData({domain:{...D,chainId:e.chainId,verifyingContract:e.venueRegistryAddress},types:X,primaryType:"TradePermit",message:{marketId:e.marketId,venueId:e.venueId,user:e.user,amount:e.amount,action:e.action,nonce:e.nonce,deadline:t}}),signer:n.address,deadline:t}}async function te(e){let n=L(e.operatorPrivateKey),t=BigInt(Math.floor(Date.now()/1e3)+N);return{signature:await n.signTypedData({domain:{...D,chainId:e.chainId,verifyingContract:e.venueRegistryAddress},types:Q,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:t}}),signer:n.address,deadline:t}}export{d as ApiError,h as createChainClient,P as createEventsApiNamespace,Z as createMarketDefinition,z as createProphecyClient,k as getPPLeaderboard,T as getPnLLeaderboard,C as getVolumeLeaderboard,E as marketDefinitionSchema,v as rateMarketDraft,te as signCreateMarketPermit,ee as signTradePermit};
26
+ Schema: ${JSON.stringify(U.shape)}`,prompt:`Create a prediction market for: "${e.question}"${r}`});return U.parse(JSON.parse(n))}var h=["crypto","sport","pop_culture","technology","politics","science","entertainment"],v="politics",w=["country","person","company","team","crypto","topic"],Te=6,Pe=4,Ee=.85,y=168,D=1,M=720,B=.05,$=.95,F=.02,Y=.95,Ae="100",Ie=60,Re=1,xe=5e3,d=["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"],T={crypto:"1-4h",sport:"4-12h",news:"18-24h",politics:"18-24h"},z={"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"},Q={"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"},Z={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"}},P=.6,ee={frontrunner:{min:.1,max:.3},midfield:{min:.02,max:.08},backmarker:{min:.002,max:.02}},ke={categories:h,defaultCategory:v,entityTypes:w,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:d,durationHints:T,lowConfidenceOverride:P};function te(){return new Date().toUTCString()}function _e(){return new Date().toISOString().slice(0,10)}function V(e){return`BANNED RESOLUTION DOMAINS (JS-rendered/auth-walled): ${e.join(", ")}. Use alternatives or set confidence \u2264 2.`}function re(e){return e.join("|")}function Ce(e){let t={categories:h,defaultDurationHours:168,bannedDomains:d,...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: ${te()}
29
+
30
+ Return ONLY valid JSON (no markdown, no code fences) with this exact structure:
31
+ {
32
+ "question": "A clear, specific yes/no question or multi-option question",
33
+ "description": "2-3 sentence description explaining what this market is about and how it resolves",
34
+ "resolution_criteria": "Precise criteria for how this market will be resolved, including data sources",
35
+ "prompt": "Instructions for the AI resolver: what to look for on the resolution page and how to determine YES or NO",
36
+ "options": ["YES", "NO"],
37
+ "expected_result": "YES",
38
+ "category": "${re(t.categories)}",
39
+ "subcategory": "a more specific subcategory",
40
+ "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"],
44
+ "news_context": [{"title": "Article headline", "url": "https://source.com/article", "source": "Publication Name"}]
45
+ }
46
+
47
+ News context (news_context field):
48
+ - Include 2-4 real, relevant news articles that provide background context for this market.
49
+ - 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.
51
+
52
+ Rules:
53
+ - The question must be specific, unambiguous, and have a clear resolution date or condition
54
+ - CRITICAL: The event MUST be in the future. Use web search to verify the current state of events.
55
+ - 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
+ - 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
+ - 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.
60
+ - 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.
63
+ - source_references should be real, relevant websites that could help verify the outcome \u2014 use FULL URLs to specific pages, not just domains
64
+ - 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
66
+ - Keep descriptions concise but informative
67
+ - Tags should be lowercase, relevant keywords
68
+ ${t.urlGuidance?`
69
+ ${t.urlGuidance}`:""}
70
+ ${t.extraInstructions?`
71
+ ${t.extraInstructions}`:""}
72
+ ${V(t.bannedDomains)}`}function Ne(e){let t={categories:h,durationHints:T,bannedDomains:d,...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.
73
+
74
+ MARKET FORMAT:
75
+
76
+ BINARY (options: ["YES", "NO"]): For straightforward yes/no propositions \u2014 price targets, policy decisions, head-to-head matchups.
77
+
78
+ MULTI-OUTCOME (options: ["Option A", "Option B", ..., "Other"]): PREFER this for "who will win", "which X", or any question with 3+ possible outcomes. 3-8 options (including "Other"), each with >2% chance. Frame as "Who/Which/What will..." not yes/no.
79
+
80
+ HIDDEN MULTI-OUTCOME DETECTION \u2014 CRITICAL (overrides all other rules):
81
+ Convert binary to multi-outcome when the underlying reality is a multi-way contest. Test: "Could a different entity plausibly achieve this instead?" If yes \u2192 MUST convert.
82
+ - "Will [X] win [tournament/award]?" \u2192 "Who will win [tournament]?" with all realistic contenders
83
+ - "Will [X] be ranked #N / be first to [Y]?" \u2192 "Which [entity] will...?" with contenders
84
+ Examples: "Will Djokovic win the French Open?" \u2192 "Who will win the 2026 French Open?" with [Djokovic, Sinner, Alcaraz, Zverev, Other]
85
+ Do NOT convert genuinely binary questions: price targets, policy decisions, weather, head-to-head matches.
86
+ When converting, include 4-8 realistic contenders plus "Other".
87
+
88
+ Return ONLY valid JSON (no markdown, no code fences):
89
+ {"question":"...", "description":"2-3 sentences", "resolution_criteria":"...", "prompt":"AI resolver instructions", "options":["YES","NO"], "expected_result":"YES", "category":"${re(t.categories)}", "subcategory":"...", "tags":["lowercase"], "suggested_duration_hours":24, "trading_end_time":"ISO 8601 UTC (optional)", "source_references":["full URL"], "virality_score":7, "resolution_url_confidence":8, "is_already_decided":false, "already_decided_reason":"", "yes_probability":0.55, "option_probabilities":null, "news_context":[{"title":"...", "url":"...", "source":"..."}]}
90
+
91
+ FIELD GUIDANCE:
92
+ - prompt: Binary \u2192 tell agent what to check and YES/NO criteria. Multi-outcome \u2192 tell agent which option won, returning exact option string.
93
+ - yes_probability (binary, 0.0-1.0) OR option_probabilities (multi-outcome array summing to ~1.0). Use source prices/odds when available. Avoid extremes (<0.05 or >0.95).
94
+ - trading_end_time: preferred when event time is known. Close when event CONCLUDES (sports: kickoff + match duration + buffer; crypto: 1-6h; news: 2-6h; awards: ceremony end).
95
+ - suggested_duration_hours: fallback when trading_end_time not set. Vary durations \u2014 ${r}. Do NOT default to 24h.
96
+ - news_context: 2-4 real articles with title, url, source. Only include URLs you're confident exist. Empty array [] if none.
97
+
98
+ STALENESS \u2014 CRITICAL:
99
+ If the event has ALREADY OCCURRED or result is ALREADY KNOWN (check the date/time in user message), set "is_already_decided": true with reason. When unsure, err on the side of marking decided.
100
+
101
+ QUESTION NAMING \u2014 be SPECIFIC:
102
+ 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
+
104
+ SCORING:
105
+ - virality_score (1-10): ${Object.entries(z).map(([n,i])=>`${n} ${i}`).join(", ")}.
106
+ - resolution_url_confidence (1-10): ${Object.entries(Q).map(([n,i])=>`${n} ${i}`).join(", ")}.
107
+
108
+ SOURCE-SPECIFIC RULES:
109
+ - Crypto: Use CoinGecko coin pages, confidence 9-10, duration 1-6h.
110
+ - Sports: Use DATE-SPECIFIC ESPN scoreboards (e.g. espn.com/nba/scoreboard/_/date/20260301). Generic /scoreboard URLs will fail for past dates. BBC Sport date-specific URLs also work. Esports: HLTV results for CS, not gol.gg/op.gg homepages.
111
+ - News: Find specific data-rich pages. For search-based: use news.google.com/search?q=... URLs.
112
+ - Polymarket: Keep same trading_end_time, proposition, deadline, threshold. Use outcomePrices for probabilities. EXCEPTION: convert hidden multi-outcome as above.
113
+
114
+ ${V(t.bannedDomains)}
115
+
116
+ 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
+ ${t.extraInstructions?`
118
+ ${t.extraInstructions}`:""}`}function Se(e){let t={minOptions:4,maxOptions:10,...e};return`You are a prediction market analyst. Given a list of market candidate headlines, identify groups of candidates that are about the SAME underlying event or competition and should be combined into a single multi-outcome market instead of separate binary yes/no markets.
119
+
120
+ Examples of candidates that should be grouped:
121
+ - "Will Naomi Osaka win the 2026 WTA Miami Open?" + "Will Aryna Sabalenka win the 2026 WTA Miami Open?" \u2192 "Who will win the 2026 WTA Miami Open?" with all realistic contenders
122
+ - "Will OpenAI have the highest Chatbot Arena score?" + "Will Anthropic have the highest Chatbot Arena score?" \u2192 "Which AI lab will have the highest Chatbot Arena score?" with all major labs
123
+ - "Will Andrey Esipenko win the FIDE Candidates?" + "Will Fabiano Caruana win the FIDE Candidates?" \u2192 "Who will win the FIDE Candidates Tournament?" with all participants
124
+
125
+ Examples that should NOT be grouped:
126
+ - "Will Bitcoin hit $100k?" \u2014 standalone binary, not a multi-way competition
127
+ - "Will Liverpool beat Manchester City?" \u2014 head-to-head match, not a multi-way "who will win the league"
128
+ - Unrelated markets about different events
129
+
130
+ For each group you identify:
131
+ 1. Write the multi-outcome question (e.g., "Who will win X?")
132
+ 2. List ALL realistic options, not just the ones from the candidates. Add well-known contenders, favorites, and realistic possibilities that the source missed. Include "Other" as the last option.
133
+ 3. Aim for ${t.minOptions}-${t.maxOptions} options (including Other). Include anyone with a realistic chance (>2%).
134
+ 4. Only group candidates that are clearly about the same specific event/competition.
135
+
136
+ Return ONLY valid JSON (no markdown, no code fences):
137
+ { "groups": [{ "question": "...", "candidateIndices": [0, 3, 7], "options": ["Option A", "Option B", ..., "Other"] }] }
138
+
139
+ If no candidates should be grouped, return: { "groups": [] }
140
+ ${t.extraInstructions?`
141
+ ${t.extraInstructions}`:""}`}function Oe(e){let t={confidenceTiers:Z,lowConfidenceOverride:P,...e},r=t.confidenceTiers;return`You are evaluating whether a prediction market resolved correctly. You will be given the market question, resolution criteria, and content from a resolution URL. Your job is to determine the outcome based SOLELY on evidence found in the URL content.
142
+
143
+ EVIDENCE RULES:
144
+ - Your ONLY source of truth is the provided URL content. Nothing else.
145
+ - If the URL content does not explicitly contain the specific information needed to answer the question, return UNKNOWN with confidence below 0.1.
146
+ - This includes cases where: the page is a homepage or generic listing, the page doesn't mention the specific event/match/result, the page has related but not directly answering content, or the data is ambiguous.
147
+ - Do NOT use your training data, general knowledge, or prior beliefs. Even if you are certain you know the answer, you MUST return UNKNOWN unless the URL content itself contains the evidence.
148
+ - Do NOT reason about likely outcomes based on team strength, historical patterns, market context, or common sense.
149
+
150
+ CONFIDENCE RULES:
151
+ - Confidence measures how clearly the URL content answers the question \u2014 NOT how sure you are of the real-world answer.
152
+ - ${r.explicit.min}-${r.explicit.max}: ${r.explicit.label} (e.g. a scoreboard showing the final score, a price page showing the current price).
153
+ - ${r.strong.min}-${r.strong.max}: ${r.strong.label} (e.g. a match report that implies the result without stating the score).
154
+ - ${r.tangential.min}-${r.tangential.max}: ${r.tangential.label}.
155
+ - ${r.none.min}-${r.none.max}: ${r.none.label}. You MUST return UNKNOWN in this case.
156
+
157
+ Current date/time: ${te()}
158
+
159
+ Respond with ONLY valid JSON (no markdown, no code fences):
160
+ {
161
+ "outcome": "YES" or "NO" or "UNKNOWN",
162
+ "confidence": 0.0 to 1.0,
163
+ "reasoning": "Quote or cite the specific evidence from the URL content that supports your answer, or explain why the URL content was insufficient"
164
+ }
165
+ ${t.extraInstructions?`
166
+ ${t.extraInstructions}`:""}`}function Le(e){let t={maxSlots:10,...e};return`You are a prediction market curator selecting events for a homepage carousel.
167
+
168
+ Pick exactly ${t.maxSlots} events from the candidate list to maximize engagement. Selection criteria (priority order):
169
+ 1. Trending & timely \u2014 cross-reference with Polymarket trending data. Prefer current hot topics.
170
+ 2. Category diversity \u2014 spread across politics, sport, tech, pop_culture, crypto, entertainment, science.
171
+ 3. Urgency \u2014 events closing within 1-7 days beat distant ones.
172
+ 4. Volume signal \u2014 higher volume = more interest.
173
+ 5. De-prioritize lightning markets (5-min BTC) unless genuinely trending.
174
+ 6. Match Polymarket trends \u2014 prefer events covering the same hot topics.
175
+ ${t.extraCriteria?`7. ${t.extraCriteria}`:""}
176
+
177
+ ONLY select from candidate event ids. Return ONLY raw JSON:
178
+ {"selected_event_ids": [123, 456, ...], "reasoning": "Brief explanation"}
179
+ ${t.extraInstructions?`
180
+ ${t.extraInstructions}`:""}`}function Ue(e){let t={calibration:ee,...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
+
182
+ Current date: ${_e()}
183
+
184
+ CALIBRATION RULES \u2014 critical for realistic odds:
185
+ - Frontrunners/favorites should get MUCH higher probabilities than underdogs
186
+ - For sports with many competitors (F1, tennis draws, horse racing):
187
+ - Top 3-5 contenders: ${Math.round(r.frontrunner.min*100)}-${Math.round(r.frontrunner.max*100)}% each
188
+ - Midfield/competitive: ${Math.round(r.midfield.min*100)}-${Math.round(r.midfield.max*100)}% each
189
+ - Backmarkers/long shots: ${r.backmarker.min*100}-${r.backmarker.max*100}% each
190
+ - For team sports (soccer, basketball): use recent form, home advantage, head-to-head
191
+ - For politics: use polling data, expert consensus, incumbency advantage
192
+ - NEVER give near-uniform probabilities unless outcomes are genuinely equal
193
+ - Your estimates should resemble real betting/prediction market odds
194
+
195
+ Return ONLY a JSON object mapping each option name (exactly as given) to its probability. No explanation.
196
+ ${t.extraInstructions?`
197
+ ${t.extraInstructions}`:""}`}function De(e){let t={entityTypes:w,maxEntities:2,...e};return`Analyze this prediction market question and extract the PRIMARY visual entity that should be shown as a thumbnail image.
198
+
199
+ Return ONLY valid JSON (no markdown) with this structure:
200
+ {
201
+ "entities": [
202
+ {
203
+ "type": "${t.entityTypes.join("|")}",
204
+ "name": "exact name",
205
+ "searchQuery": "optimized search query for finding an image"
206
+ }
207
+ ]
208
+ }
209
+
210
+ Rules:
211
+ - Return at most ${t.maxEntities} entities, prioritizing the MOST VISUALLY DISTINCTIVE one first
212
+ - For geopolitical events (wars, treaties, sanctions): extract the PRIMARY country involved
213
+ - For sports: extract the team name (not the league)
214
+ - For people (politicians, celebrities, athletes): extract the person's full name
215
+ - For companies/stocks: extract the company name
216
+ - For crypto: extract the cryptocurrency name (e.g., "Bitcoin", not "BTC price")
217
+ - For abstract topics: use type "topic" with a concrete visual search query
218
+
219
+ Examples:
220
+ - "Will Bitcoin hit $100k?" \u2192 [{"type": "crypto", "name": "bitcoin"}]
221
+ - "Bank of Japan interest rate decision" \u2192 [{"type": "country", "name": "japan"}]
222
+ - "Will Trump win the election?" \u2192 [{"type": "person", "name": "Donald Trump", "searchQuery": "Donald Trump portrait"}]
223
+ - "Lakers vs Celtics game" \u2192 [{"type": "team", "name": "Los Angeles Lakers", "searchQuery": "Lakers logo"}]
224
+ - "S&P 500 price movement" \u2192 [{"type": "topic", "name": "S&P 500", "searchQuery": "stock market chart"}]
225
+ ${t.extraInstructions?`
226
+ ${t.extraInstructions}`:""}`}function Me(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
+
228
+ Return ONLY valid JSON (no markdown, no code fences) \u2014 an array of objects:
229
+ [{"title": "Article headline", "url": "https://full-url.com/article", "source": "Publication Name"}]
230
+
231
+ Rules:
232
+ - Only include articles you found via web search \u2014 do NOT fabricate or guess URLs.
233
+ - Prefer recent articles from reputable sources (${t.preferredSources.join(", ")}, etc.).
234
+ - For sports: match previews, team form, injury reports, head-to-head records.
235
+ - For crypto: price analysis, market commentary, regulatory news.
236
+ - For politics: polling data, policy analysis, expert commentary.
237
+ - If you cannot find relevant articles, return an empty array [].
238
+ ${t.extraInstructions?`
239
+ ${t.extraInstructions}`:""}`}function Be(e){let t={bannedDomains:d,...e};return`Resolution URL confidence rubric (resolution_url_confidence, 1-10):
240
+ - 9-10: URL always contains the answer (CoinGecko price page, ESPN scoreboard, official results page)
241
+ - 7-8: URL very likely has the answer (major news site live page, official standings)
242
+ - 4-6: URL might have relevant info but uncertain (general news article, social media)
243
+ - 1-3: URL unlikely to have a clear, machine-readable answer
244
+
245
+ Source-specific URL guidance:
246
+ - Crypto: Use CoinGecko coin pages (e.g., https://www.coingecko.com/en/coins/bitcoin) \u2014 these always show current price. Resolution URL confidence should be 9-10.
247
+ - Sports: ALWAYS use DATE-SPECIFIC scoreboards with the date parameter in the URL path. Generic scoreboards only show today's games and will fail for past dates.
248
+ - GOOD: "https://www.espn.com/nba/scoreboard/_/date/20260301" \u2014 shows March 1 games specifically
249
+ - BAD: "https://www.espn.com/nba/scoreboard" \u2014 only shows today's date, useless for past/future games
250
+ - BBC Sport date-specific URLs: "https://www.bbc.co.uk/sport/football/scores-fixtures/2026-02-28"
251
+ - For motorsport: Use the event hub page (e.g., "https://www.formula1.com/en/racing/2025/australia") which links to qualifying/race results.
252
+ - For esports: Use HLTV results (https://www.hltv.org/results) for CS, match-specific Liquipedia pages for LoL/Dota.
253
+ - Resolution URL confidence 7-9 for date-specific URLs, 3 or below for generic scoreboards.
254
+ - 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
+ - Pop culture / entertainment: Use official announcement pages or news search URLs.
256
+
257
+ ${V(t.bannedDomains)}
258
+ 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
+ ${t.extraGuidance?`
260
+ ${t.extraGuidance}`:""}`}function E(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 $e(e,t){let r=t?.min??.05,n=t?.max??.95;return Math.min(n,Math.max(r,e))}function Fe(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,l)=>s+l,0);return a===0?e.map(()=>1/e.length):i.map(s=>s/a)}function Ye(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function Ve(e,t){let r=new Set(t??d);try{let n=new URL(e).hostname;return r.has(n)||r.has(n.replace(/^www\./,""))}catch{return!1}}function qe(e){let t=e.replace(/[?!.,;:'"]/g,"").split(/\s+/).slice(0,10).join("+");return`https://news.google.com/search?q=${encodeURIComponent(t)}`}function He(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=E((a.getTime()-s)/36e5):i=E(n.suggested_duration_hours)}else i=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||v,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}}import{privateKeyToAccount as ne}from"viem/accounts";var ie=60,ae={name:"VenueRegistry",version:"1"},We={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"}]},Ge={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 je(e){let t=ne(e.operatorPrivateKey),r=BigInt(Math.floor(Date.now()/1e3)+ie);return{signature:await t.signTypedData({domain:{...ae,chainId:e.chainId,verifyingContract:e.venueRegistryAddress},types:Ge,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 Ke(e){let t=ne(e.operatorPrivateKey),r=BigInt(Math.floor(Date.now()/1e3)+ie);return{signature:await t.signTypedData({domain:{...ae,chainId:e.chainId,verifyingContract:e.venueRegistryAddress},types:We,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}}export{xe as ACTIVE_MARKET_CAP,m as ApiError,d as BANNED_DOMAINS,h as CATEGORIES,v as DEFAULT_CATEGORY,y as DEFAULT_DURATION_HOURS,Ae as DEFAULT_LIQUIDITY,Re as DEFAULT_RESOLUTION_HOURS,Ie as DEFAULT_TRADING_START_BUFFER_SECONDS,T as DURATION_HINTS,w as ENTITY_TYPES,P as LOW_CONFIDENCE_OVERRIDE,ke as MARKET_DEFAULTS,$ as MAX_BINARY_PROBABILITY,M as MAX_DURATION_HOURS,Y as MAX_OPTION_PROBABILITY,B as MIN_BINARY_PROBABILITY,D as MIN_DURATION_HOURS,F as MIN_OPTION_PROBABILITY,Pe as RESOLUTION_CONFIDENCE_THRESHOLD,Ee as SIMILARITY_THRESHOLD,Te as VIRALITY_THRESHOLD,Le as buildCarouselPrompt,De as buildEntityExtractionPrompt,Se as buildGroupingPrompt,Ce as buildMarketGenerationPrompt,Me as buildNewsContextPrompt,Ue as buildProbabilityEstimationPrompt,Ne as buildReframePrompt,Oe as buildResolutionEvalPrompt,Be as buildUrlGuidanceBlock,$e as clampBinaryProbability,E as clampDuration,_ as createCache,C as createChainClient,N as createEventsApiNamespace,we as createMarketDefinition,fe as createProphecyClient,k as getEventRating,S as getPPLeaderboard,O as getPnLLeaderboard,L as getVolumeLeaderboard,qe as googleNewsFallbackUrl,Ve as isBannedDomain,Ye as isValidUrl,U as marketDefinitionSchema,Fe as normalizeOptionProbabilities,He as parseLlmMarketJson,R as previewRating,x as rateMarketDraft,Ke as signCreateMarketPermit,je as signTradePermit};
27
261
  //# sourceMappingURL=index.js.map