@oracle-agent/oracle 0.35.20 → 0.35.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +24 -1
  2. package/dist/agent-lifecycle.mjs +3 -0
  3. package/dist/assets/skills/oracle-desk-product/SKILL.md +23 -17
  4. package/dist/assets/skills/oracle-mcp-install/SKILL.md +17 -22
  5. package/dist/assets/skills/protocol-api-key-integration/SKILL.md +14 -11
  6. package/dist/assets/skills/self-custodial-onchain-execution/SKILL.md +14 -13
  7. package/dist/assets/skills/trade-loop-circuit-breaker/SKILL.md +1 -1
  8. package/dist/bin/desk-server.mjs +36 -36
  9. package/dist/bin/oracle-data-mcp.mjs +17 -17
  10. package/dist/bin/oracle-mev-arb-shadow.mjs +4 -4
  11. package/dist/bin/oracle-mev-shadow.mjs +6 -6
  12. package/dist/bin/oracle-public-server.mjs +5 -5
  13. package/dist/bin/oracle-route.mjs +11 -11
  14. package/dist/bin/oracle-scan.mjs +15 -15
  15. package/dist/bin/oracle.mjs +19 -10
  16. package/dist/cli/commands/chat.mjs +200 -200
  17. package/dist/cli/commands/context.mjs +16 -0
  18. package/dist/cli/commands/doctor.mjs +7 -7
  19. package/dist/cli/commands/eval.mjs +113 -113
  20. package/dist/cli/commands/extension-policy.mjs +1 -1
  21. package/dist/cli/commands/governance-prepare.mjs +5 -0
  22. package/dist/cli/commands/lifecycle.mjs +17 -0
  23. package/dist/cli/commands/model.mjs +204 -204
  24. package/dist/cli/commands/portfolio-risk.mjs +4 -0
  25. package/dist/cli/commands/position-health.mjs +4 -0
  26. package/dist/cli/commands/quickstart.mjs +5 -5
  27. package/dist/cli/commands/safety-intelligence.mjs +4 -0
  28. package/dist/cli/commands/sign.mjs +1 -1
  29. package/dist/cli/commands/signer.mjs +22 -22
  30. package/dist/cli/commands/snipe.mjs +4 -4
  31. package/dist/cli/commands/swap.mjs +13 -13
  32. package/dist/cli/commands/tax-lots.mjs +4 -0
  33. package/dist/cli/commands/venues.mjs +2 -2
  34. package/dist/context-graph.mjs +3 -0
  35. package/dist/data/desk-data.mjs +34 -34
  36. package/dist/data/providers/lp-destination-discovery.mjs +6 -0
  37. package/dist/data/providers/lp-liquidity-ranker.mjs +1 -0
  38. package/dist/index.mjs +50 -48
  39. package/dist/local-signer/anvil-attestation-worker.mjs +1 -1
  40. package/dist/local-signer/runtime.mjs +1 -1
  41. package/dist/router/index.mjs +3 -3
  42. package/dist/router/prepare-bridge.mjs +2 -2
  43. package/dist/scanner/index.mjs +4 -4
  44. package/dist/tenant-rbac.mjs +1 -1
  45. package/dist/workflow-telemetry.mjs +1 -1
  46. package/package.json +5 -1
  47. package/public/eval-report.json +2 -2
  48. package/public/oracle-splash/brand/liquidlaunch.webp +0 -0
  49. package/public/oracle-splash/brand/markets.webp +0 -0
  50. package/public/oracle-splash/brand/motion.webp +0 -0
  51. package/public/oracle-splash/brand/nest.webp +0 -0
  52. package/public/oracle-splash/brand/outcome.webp +0 -0
  53. package/public/oracle-splash/brand/silhouette.webp +0 -0
  54. package/public/oracle-splash/brand/tradexyz.webp +0 -0
  55. package/public/oracle-splash/index.html +9 -9
  56. package/server.json +2 -2
  57. package/dist/assets/skills/oracle-best-execution.md +0 -27
  58. package/dist/assets/skills/oracle-desk.md +0 -27
  59. package/dist/assets/skills/oracle-receipts.md +0 -29
@@ -1,11 +1,11 @@
1
- var no=Object.defineProperty;var a=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var Ae=(e,t)=>{for(var r in t)no(e,r,{get:t[r],enumerable:!0})};import ve from"node:fs";import oo from"node:os";import X from"node:path";import{fileURLToPath as io}from"node:url";function Ve(){return process.env.ORACLE_FAKE_HOME||oo.homedir()}function ao(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function Z(){return ao()?process.env.ORACLE_CONFIG_DIR||X.join(Ve(),".config","oracle"):X.join(Ve(),".config","oracle")}function co(){return X.join(Z(),"desk.json")}function lo(){return X.join(Z(),"env")}function Y({force:e=!1}={}){if(Y._done&&!e)return Y._result||null;Y._done=!0;let t={},r=(o,i)=>{if(i==null)return;let s=String(i).trim();s&&(process.env[o]!=null&&String(process.env[o]).trim()!==""||(process.env[o]=s,t[o]=s))};try{let o=lo();if(ve.existsSync(o))for(let i of ve.readFileSync(o,"utf8").split(/\r?\n/)){let s=i.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!s||s[2].startsWith("#"))continue;let d=s[2];(d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'"))&&(d=d.slice(1,-1)),r(s[1],d)}}catch{}try{let o=co();if(ve.existsSync(o)){let i=JSON.parse(ve.readFileSync(o,"utf8"));i&&typeof i=="object"&&(r("ORACLE_DESK_URL",i.deskUrl||i.dataUrl||i.url),r("ORACLE_DATA_URL",i.dataUrl||i.deskUrl||i.url),r("ORACLE_API_URL",i.apiUrl||i.dataUrl||i.deskUrl),r("ORACLE_PUBLIC_URL",i.publicUrl||i.deskUrl||i.dataUrl),r("ORACLE_EXEC_URL",i.execUrl),r("MAD_DESK_URL",i.deskUrl||i.dataUrl))}}catch{}let n=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return n&&(r("ORACLE_DESK_URL",n),r("ORACLE_DATA_URL",n),r("ORACLE_API_URL",n),r("ORACLE_PUBLIC_URL",n),r("MAD_DESK_URL",n)),Y._result=Object.keys(t).length?t:null,Y._result}var so,S,ke=a(()=>{so=X.dirname(io(import.meta.url)),S=X.resolve(so,"../..");try{Y()}catch{}});function ur(e){return $o.get(Number(e))||null}function dr(e,t=process.env){let r=ur(e);if(!r)return null;for(let n of r.rpcEnv){let o=(t[n]||"").trim();if(o)return o}return null}var Oe,$o,Qe=a(()=>{Oe={robinhood:{chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC"],evm:!0},ethereum:{chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],evm:!0},polygon:{chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],evm:!0},arbitrum:{chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],evm:!0},base:{chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],evm:!0},hyperevm:{chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],evm:!0},bsc:{chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],evm:!0},avalanche:{chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],evm:!0},optimism:{chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],evm:!0},abstract:{chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],evm:!0},stable:{chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],evm:!0}},$o=new Map(Object.values(Oe).map(e=>[e.chainId,e]))});function ae(e){let t=e?.transactionHash||e?.hash||e?.txid||null;return t?{happened:!0,hash:String(t),note:null}:{happened:!1,hash:null,note:"no transaction hash \u2014 the action did not succeed"}}var et=a(()=>{});var fr=a(()=>{});var pr=a(()=>{});var ce=a(()=>{});var te=a(()=>{});var _e=a(()=>{ce();te()});import{isAddress as ic}from"ethers";var rt=a(()=>{_e();ce();te()});import{Interface as Do,isAddress as dc}from"ethers";var wc,mr=a(()=>{rt();ce();te();wc=new Do(["function approve(address spender,uint256 amount) returns (bool)"])});import{Interface as Fo,isAddress as yc}from"ethers";var Sc,Ac,wr=a(()=>{rt();ce();te();Sc=new Fo(["function approve(address spender,uint256 amount) returns (bool)"]),Ac=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"})});var z=a(()=>{});import{Interface as jo,MaxUint256 as Nc,isAddress as Cc,keccak256 as Rc,toUtf8Bytes as Lc}from"ethers";var jc,W=a(()=>{pr();mr();wr();z();te();jc=new jo(["function approve(address spender,uint256 amount) returns (bool)"])});var qc,Hc,Ne=a(()=>{qc=300*1e3,Hc=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});var Ce=a(()=>{W()});import{Address as Kc,NETWORK as Gc,OutScript as Jc,RawTx as Yc,SigHash as Xc,TEST_NETWORK as Zc,Transaction as Qc}from"@scure/btc-signer";var it=a(()=>{});import{createHash as Mo}from"node:crypto";import{base58 as nl}from"@scure/base";import{getCompiledTransactionMessageDecoder as il}from"@solana/transaction-messages";var hr,sl,st=a(()=>{hr=e=>Mo("sha256").update(`global:${e}`).digest().subarray(0,8).toString("hex"),sl=new Map([[hr("route"),{name:"route",prefixBytes:0}],[hr("shared_accounts_route"),{name:"shared_accounts_route",prefixBytes:1}]])});import V from"node:net";import qo from"node:dns";function Re(e){let t=String(e).toLowerCase().split("%")[0];if((t.match(/::/g)||[]).length>1)return null;let r=m=>{if(!m)return[];let l=m.split(":"),f=l.at(-1);if(f?.includes(".")){let u=f.split(".").map(Number);if(u.length!==4||u.some(b=>!Number.isInteger(b)||b<0||b>255))return null;l.splice(l.length-1,1,(u[0]<<8|u[1]).toString(16),(u[2]<<8|u[3]).toString(16))}return l.some(u=>!/^[0-9a-f]{1,4}$/.test(u))?null:l.map(u=>Number.parseInt(u,16))},[n,o]=t.split("::"),i=r(n),s=r(o);if(!i||!s)return null;let d=t.includes("::"),c=8-i.length-s.length;if(!d&&c!==0||d&&c<1)return null;let p=[...i,...Array(Math.max(0,c)).fill(0),...s];return p.length!==8?null:Uint8Array.from(p.flatMap(m=>[m>>8,m&255]))}function at(e,t,r){let n=Math.floor(r/8),o=r%8;for(let s=0;s<n;s+=1)if(e[s]!==t[s])return!1;if(!o)return!0;let i=255<<8-o;return(e[n]&i)===(t[n]&i)}function ct(e){if(V.isIPv4(e)){let t=e.split(".").map(Number);return!(t[0]===0||t[0]===10||t[0]===127||t[0]>=224||t[0]===100&&t[1]>=64&&t[1]<=127||t[0]===169&&t[1]===254||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&(t[1]===0||t[1]===2||t[1]===168)||t[0]===192&&t[1]===88&&t[2]===99||t[0]===198&&(t[1]===18||t[1]===19||t[1]===51)||t[0]===203&&t[1]===0&&t[2]===113)}if(V.isIPv6(e)){let t=Re(e);if(!t)return!1;let r=Re("::ffff:0:0");return at(t,r,96)?ct([...t.slice(12)].join(".")):at(t,Re("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([o,i])=>at(t,Re(o),i)):!1}return!1}function Uo(e){let t;try{t=new URL(String(e))}catch{return{ok:!1,error:`not a valid URL: ${String(e).slice(0,120)}`}}if(t.protocol!=="http:"&&t.protocol!=="https:")return{ok:!1,error:`refused protocol ${t.protocol} (only http/https)`};let r=t.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"");if(Ho.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=V.isIP(r);return n!==0&&!ct(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:t,host:r,isLiteralIp:n!==0}}async function lt(e,{lookupFn:t=qo.promises.lookup}={}){let r=Uo(e);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:V.isIPv6(r.host)?6:4}]};let n;try{n=await t(r.host,{all:!0,verbatim:!0})}catch{return{ok:!1,error:`refused: ${r.host} did not resolve`}}return!Array.isArray(n)||n.length===0||n.some(o=>!ct(o.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}async function ut({requireUndici:e=!1,importUndici:t=()=>import("undici")}={}){let r,n;try{let l=await t();r=l.Agent,n=l.fetch}catch(l){if(e)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${l?.message||l}`);return null}if(typeof r!="function"||typeof n!="function"){if(e)throw new Error("egress-guard: untrustedUrl pinning requires undici's Agent and fetch exports, which were not found on the imported module");return null}let o=l=>String(l).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),i=new Map,s=l=>(Array.isArray(l)?l:[l]).map(f=>typeof f=="string"?{address:f}:f).filter(f=>f&&f.address).map(f=>({address:f.address,family:f.family||(V.isIPv6(f.address)?6:4)})),d=(l,f,u)=>{i.set(o(l),s(typeof f=="string"?[{address:f,family:u}]:f))},c=l=>{let f=o(l);if(V.isIP(f))return[{address:f,family:V.isIPv6(f)?6:4}];let u=i.get(f);if(!u||!u.length)throw new Error(`refused: unpinned host ${l} during pinned fetch`);return u},p=new r({connect:{lookup(l,f,u){let b;try{b=c(l)}catch(h){return u(h)}return f?.all?u(null,b):u(null,b[0].address,b[0].family)}}}),m=zo((l,f={})=>n(l,{...f,dispatcher:p}),d);return{dispatcher:p,fetch:m,pin:d,resolve:c,async close(){try{await p.destroy()}catch{}}}}function zo(e,t){if(typeof e!="function")throw new Error("markPinCapableFetch: fetchImpl must be a function");if(typeof t!="function")throw new Error("markPinCapableFetch: pin must be a function");return e[dt]=Object.freeze({pin:t}),e}function ft(e){return typeof e=="function"&&typeof e[dt]?.pin=="function"}function gr(e,t,r){if(!ft(e))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");e[dt].pin(t,r)}var Ho,dt,yr=a(()=>{Ho=new Set(["localhost","metadata.google.internal","metadata.goog"]);dt=Symbol.for("oracle.egressGuard.pinCapableFetch")});import{createHash as br}from"node:crypto";function Jo(e){let t=String(e||"").toLowerCase();return Ir.includes(t)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(t)}function Yo(e){let t={};for(let[r,n]of Object.entries(e||{}))Jo(r)||(t[r]=n);return t}function Xo(e,t){if(!e)throw new Error(`HTTP redirect from ${t} missing Location`);let r=new URL(String(e),String(t));if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`HTTP redirect from ${t} used unsupported protocol ${r.protocol}`);return r.toString()}function Zo(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}function Ar(e){let t=String(e?.method||"");return t?!Qo.test(t):!1}function ti(e,t){if(e==="GET"&&t==null)return!0;if(e!=="POST"||t==null)return!1;let r=t;if(typeof t=="string")try{r=JSON.parse(t)}catch{return!1}return Array.isArray(r)?r.length>0&&r.every(Ar):!r||typeof r!="object"?!1:r.jsonrpc&&r.method?Ar(r):typeof r.type=="string"&&ei.has(r.type)&&r.action==null&&r.signature==null&&r.nonce==null}function ri(e,t,r,n={},o=null){let i={};for(let[f,u]of Object.entries(r||{}))i[f.toLowerCase()]=u;let s=Object.keys(i).filter(f=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(f)),c=[...new Set([...Ir,...s])].sort().map(f=>`${f}=${i[f]??""}`).join(`
2
- `),p=br("sha256").update(c).digest("hex").slice(0,32),m=`${n.untrustedUrl?"untrusted":"trusted"}:${n.maxResponseBytes??"unbounded"}`,l=o==null?"-":br("sha256").update(String(o)).digest("hex").slice(0,32);return`${e} ${t} ${m} ${p} ${l}`}function ni(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,xr):Math.min(250*2**e,xr)+Math.floor(Math.random()*100)}function ue(e,t={}){let r=new Error(e);return r.retryable=!1,Object.assign(r,t),r}function mt(e,t,r){return ue(`HTTP response from ${e} exceeded maxResponseBytes ${r} (${t})`,{oversize:!0})}function de(e){try{let t=e?.body?.cancel?.();t&&typeof t.then=="function"&&t.catch(()=>{})}catch{}}function ii(e){return e?e.byteLength??e.length??0:0}async function vr(e,t,{url:r,truncate:n=!1,onOversize:o}={}){if(t==null)return await e.text();let i=Number(e.headers?.get?.("content-length"));if(Number.isFinite(i)&&i>t&&(de(e),!n))throw mt(r,`content-length ${i}`,t);let s=e.body?.getReader?.();if(!s){let l=await e.text(),f=Buffer.byteLength(l,"utf8");if(f>t){if(!n)throw mt(r,`body ${f} bytes`,t);return Buffer.from(l,"utf8").subarray(0,t).toString("utf8")}return l}let d=[],c=0,p=!1;try{for(;;){let{value:l,done:f}=await s.read();if(f)break;if(l&&(d.push(Buffer.from(l)),c+=ii(l),c>t)){p=!0;break}}}finally{if(p)try{await s.cancel()}catch{}try{s.releaseLock?.()}catch{}}if(p&&(typeof o=="function"&&o(),!n))throw mt(r,`streamed ${c} bytes`,t);let m=Buffer.concat(d);return(p?m.subarray(0,t):m).toString("utf8")}function kr(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function si(e,{fetchImpl:t,method:r,headers:n,body:o,timeoutMs:i,lookupFn:s,realFetch:d,untrustedUrl:c=!1,maxResponseBytes:p=null,importUndici:m,validateResponse:l,signal:f}){let u=new AbortController,b=setTimeout(()=>u.abort(),i),h=f?typeof AbortSignal.any=="function"?AbortSignal.any([f,u.signal]):f:u.signal,w=null,I=t,T=s?{lookupFn:s}:{};if(c&&!d&&!ft(I))throw ue(`HTTP refused ${e}: untrustedUrl requires a pin-capable fetchImpl (see markPinCapableFetch in egress-guard.mjs) or no fetchImpl override so Oracle can pin the connection itself`);let g=async(y,{status:x=null}={})=>{let v=await lt(y,T);if(!v.ok)throw ue(x==null?`HTTP refused ${y}: ${v.error}`:`HTTP redirect to ${y} ${v.error}`,x==null?{}:{status:x});let E=new URL(y).hostname;if(d){if(w&&(await w.close(),w=null),!w)try{w=await ut({requireUndici:!0,...m?{importUndici:m}:{}})}catch(_){throw ue(x==null?`HTTP refused ${y}: ${_?.message||_}`:`HTTP redirect to ${y} refused: ${_?.message||_}`,x==null?{}:{status:x})}w.pin(E,v.addresses),I=w.fetch}else gr(I,E,v.addresses);return v};try{let y=String(e),x={...n||{}};c&&await g(y);for(let v=0;v<=Sr;v+=1){let E=await I(y,{method:r,headers:x,body:o,signal:h,redirect:"manual"});if(Ko.has(E.status)){if(r!=="GET"&&r!=="HEAD"){let L=await vr(E,p??Go,{url:y,truncate:!0}),j=new Error(`HTTP ${E.status} ${r} ${y} redirected non-idempotent request`);throw j.status=E.status,j.body=kr(L)??L.slice(0,300),j}if(v===Sr)throw de(E),new Error(`HTTP redirect loop for ${e}`);let C=E.headers?.get?.("location"),B;try{B=Xo(C,y)}catch(L){throw de(E),L}let D=!Zo(B,y);if(de(E),D&&(x=Yo(x)),c)await g(B,{status:E.status});else if(D){let L=await lt(B,T);if(!L.ok){let j=new Error(`HTTP redirect from ${y} ${L.error}`);throw j.status=E.status,j.retryable=!1,j}d&&L.addresses?.length&&(w||(w=await ut(m?{importUndici:m}:{})),w&&(w.pin(new URL(B).hostname,L.addresses),I=w.fetch))}y=B;continue}if(typeof l=="function")try{await l(E,{url:y})}catch(C){throw de(E),ue(C?.message||String(C))}let _=await vr(E,p,{url:y,onOversize:()=>u.abort()}),J=kr(_);if(!E.ok){let C=new Error(`HTTP ${E.status} ${r} ${y}`);throw C.status=E.status,C.retryAfter=E.headers?.get?.("retry-after")??null,C.body=J??_.slice(0,300),C}return J??_}throw new Error(`HTTP redirect loop for ${e}`)}finally{clearTimeout(b),w&&await w.close()}}async function Le(e,t={}){let r=t.fetchImpl||globalThis.fetch;if(typeof r!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let n=t.timeoutMs??12e3,o=(t.method||"GET").toUpperCase(),i={Accept:"application/json",...t.headers||{}},s=t.body;s!=null&&typeof s!="string"&&(i["Content-Type"]=i["Content-Type"]||"application/json",s=JSON.stringify(s));let d=Number.isInteger(t.retries)?Math.max(t.retries,0):Vo,c=t.lookupFn,p=!t.fetchImpl,m=t.untrustedUrl===!0,l=t.importUndici,f=t.validateResponse,u=t.signal,b=Number(t.maxResponseBytes),h=Number.isFinite(b)&&b>0?Math.floor(b):null,w=async()=>{let x;for(let v=0;v<=d;v++){u?.throwIfAborted?.();try{return await si(e,{fetchImpl:r,method:o,headers:i,body:s,timeoutMs:n,lookupFn:c,realFetch:p,untrustedUrl:m,maxResponseBytes:h,importUndici:l,validateResponse:f,signal:u})}catch(E){x=E;let _=E?.status,J=E?.name==="AbortError"||E?.name==="TimeoutError"||u?.aborted,C=new Set([408,425,429]),B=E?.retryable===!1?!1:_!=null?C.has(_)||Wo.has(_)&&Er.has(o):!J&&Er.has(o);if(v===d||!B)throw E;let D=ni(v,E?.retryAfter);u?await new Promise((L,j)=>{let ro=setTimeout(L,D);u.addEventListener("abort",()=>{clearTimeout(ro),j(u.reason||new DOMException("Aborted","AbortError"))},{once:!0})}):await oi(D)}}throw x};if(!(t.dedupe!==!1&&!u&&ti(o,s)))return w();let T=ri(o,e,i,{untrustedUrl:m,maxResponseBytes:h},s),g=pt.get(T);if(g)return g;let y=w().finally(()=>pt.delete(T));return pt.set(T,y),y}var Wo,Er,Vo,xr,Ir,Ko,Sr,Go,pt,Qo,ei,oi,$e=a(()=>{yr();Wo=new Set([408,425,429,500,502,503,504]),Er=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Vo=2,xr=4e3,Ir=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],Ko=new Set([301,302,303,307,308]),Sr=3,Go=64*1024;pt=new Map,Qo=/(?:^|_)(send|submit|broadcast|sign|requestAirdrop)(?=[A-Z_]|$)/i,ei=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);oi=e=>new Promise(t=>setTimeout(t,e))});var Or=a(()=>{$e()});var Tr=a(()=>{Or()});var Al,vl,ht=a(()=>{z();Tr();Al=Object.freeze({"perp-order":"order","hip3-order":"order","hip4-order":"order","perp-bracket":"order","perp-cancel":"cancel","perp-leverage":"leverage","perp-isolated-margin":"margin","builder-fee-approval":"approveBuilder","hype-stake-deposit":"stake","hype-stake-withdraw":"unstake","hype-delegate":"delegate","hype-undelegate":"delegate"}),vl=Object.freeze({"perp-order":"order","hip3-order":"order","hip4-order":"order","perp-bracket":"order","perp-cancel":"cancel","perp-leverage":"updateLeverage","perp-isolated-margin":"updateIsolatedMargin","builder-fee-approval":"approveBuilderFee","hype-stake-deposit":"cDeposit","hype-stake-withdraw":"cWithdraw","hype-delegate":"tokenDelegate","hype-undelegate":"tokenDelegate"})});var Ol,gt=a(()=>{z();Ol="0x"+"00".repeat(32)});var ai,Rl,yt=a(()=>{gt();z();ai=Object.freeze([["salt","uint256"],["maker","address"],["signer","address"],["tokenId","uint256"],["makerAmount","uint256"],["takerAmount","uint256"],["side","uint8"],["signatureType","uint8"],["timestamp","uint256"],["metadata","bytes32"],["builder","bytes32"]]),Rl=Object.freeze(ai.map(e=>e[0]))});var Pe=a(()=>{z()});import{TypedDataEncoder as Dl,getAddress as Fl,isAddress as jl}from"ethers";var li,ui,Rr=a(()=>{Ne();li=Object.freeze({1:"0x111111125421cA6dc452d289314280a0f8842A65",8453:"0x111111125421cA6dc452d289314280a0f8842A65",42161:"0x111111125421cA6dc452d289314280a0f8842A65",10:"0x111111125421cA6dc452d289314280a0f8842A65",137:"0x111111125421cA6dc452d289314280a0f8842A65",56:"0x111111125421cA6dc452d289314280a0f8842A65"}),ui=Object.freeze({Order:[{name:"salt",type:"uint256"},{name:"maker",type:"address"},{name:"receiver",type:"address"},{name:"makerAsset",type:"address"},{name:"takerAsset",type:"address"},{name:"makingAmount",type:"uint256"},{name:"takingAmount",type:"uint256"},{name:"makerTraits",type:"uint256"}]})});var Hl,Lr=a(()=>{Hl=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"})});var $r=a(()=>{});import{TypedDataEncoder as Yl,getAddress as Xl,isAddress as Zl}from"ethers";var di,iu,fi,su,Pr=a(()=>{$e();_e();Lr();$r();Ne();di=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),iu=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"}),fi=Object.freeze({Order:[{name:"sellToken",type:"address"},{name:"buyToken",type:"address"},{name:"receiver",type:"address"},{name:"sellAmount",type:"uint256"},{name:"buyAmount",type:"uint256"},{name:"validTo",type:"uint32"},{name:"appData",type:"bytes32"},{name:"feeAmount",type:"uint256"},{name:"kind",type:"string"},{name:"partiallyFillable",type:"bool"},{name:"sellTokenBalance",type:"string"},{name:"buyTokenBalance",type:"string"}]}),su=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]})});import{TypedDataEncoder as lu,getAddress as uu}from"ethers";var pu,bt=a(()=>{Rr();Pr();pu=Object.freeze(["https://limit-orders.1inch.io","https://api.1inch.dev/orderbook"])});import{Interface as Dr}from"ethers";var yi,Nu,bi,Cu,Ru,Lu,$u,Ei,Pu,Be=a(()=>{W();_e();Ne();Ce();it();st();ht();yt();Pe();bt();yi=new Set(["evm","evm-swap","evm-bridge","evm-nft","evm-order","btc","sol","hl","poly","lighter"]),Nu=Object.freeze({swap:5,bridge:5,perps:0,nft:0,mint:0,transfer:0,approve:0,delegate:0,identity:0,order:0,cancel:0,leverage:0,margin:0,approveBuilder:0,stake:0,unstake:0}),bi=Object.freeze({"0x04e45aaf":{provider:"uniswap-v3",action:"swap",layout:"router02-exact-input-single"},"0x414bf389":{provider:"uniswap-v3",action:"swap",layout:"swap-router-exact-input-single"},"0xc04b8d59":{provider:"uniswap-v3",action:"swap",layout:"exact-input-deadline"},"0xb858183f":{provider:"uniswap-v3",action:"swap",layout:"exact-input"},"0x5ae401dc":{provider:"uniswap-v3",action:"swap",layout:"multicall-deadline"},"0xa026383e":{provider:"aerodrome",action:"swap",layout:"aerodrome-exact-input-single"},"0x7b939232":{provider:"across-v3",action:"bridge",layout:"across-deposit-v3"}}),Cu=Object.freeze({"0x161ac21f":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-public"},"0xc2f6663a":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-allowlist"}}),Ru=new Dr(["function buySpecificNFT(uint256 tokenId,uint256 maxCost) payable","function sellNFT(uint256 tokenId,uint256 minPayout) payable"]),Lu=new Dr(["function mintAllowList(address nftContract,address feeRecipient,address minterIfNotPayer,uint256 quantity,(uint80 mintPrice,uint48 maxTotalMintableByWallet,uint48 startTime,uint48 endTime,uint48 dropStageIndex,uint32 maxTokenSupplyForStage,uint16 feeBps,bool restrictFeeRecipients) mintParams,bytes32[] proof) payable"]),$u=Object.freeze({"0xa0712d68":{provider:"nft-mint",action:"mint",layout:"mint-quantity"},"0x1249c58b":{provider:"nft-mint",action:"mint",layout:"mint-no-args"},"0x2db11544":{provider:"nft-mint",action:"mint",layout:"mint-quantity"},"0xefef39a1":{provider:"nft-mint",action:"mint",layout:"mint-quantity"},"0xa6f2ae3a":{provider:"nft-mint",action:"mint",layout:"mint-no-args"}}),Ei=Object.freeze([...yi]),Pu=Object.freeze({...bi})});import{encode as Fu}from"@msgpack/msgpack";import{keccak256 as Mu,verifyTypedData as qu}from"ethers";var Hu,Uu,Et=a(()=>{Hu=Object.freeze({name:"Exchange",version:"1",chainId:1337,verifyingContract:"0x0000000000000000000000000000000000000000"}),Uu=Object.freeze({Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]})});var xt=a(()=>{Pe()});import{ed25519 as Xu}from"@noble/curves/ed25519.js";import{base58 as Qu}from"@scure/base";import{RawTx as td,SigHash as rd,Transaction as nd}from"@scure/btc-signer";import{Transaction as id,keccak256 as sd,verifyTypedData as ad}from"ethers";var St=a(()=>{Et();xt()});import{base58 as md}from"@scure/base";var De=a(()=>{Be();Ce();W();St()});var jr=a(()=>{De();Be()});import{wordlists as Ai}from"ethers";function Oi(e){let t=String(e).trim().toLowerCase().split(/\s+/).filter(Boolean);return Ii.has(t.length)&&t.every(r=>Ai.en.getWordIndex(r)>=0)}function Ci(e){let t=Mr(e);return Ni.has(t)||_i.test(t)}function Mr(e){return String(e).replace(/[^a-z0-9]/gi,"").toLowerCase()}function Ri(e){let t=Mr(e);return[...vi].some(r=>t.includes(r))}function Li(e,t,r){if(typeof t=="string"){if(ki.some(n=>n.test(t))||Oi(t))throw new fe(r);if(Ti.test(t)&&!Ci(e))throw new fe(r)}}function At(e,t="$",r=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string")return Li(r,e,t),e;if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError(`action receipt: non-finite number at ${t}`);return e}if(typeof e=="bigint")return e.toString();if(Array.isArray(e))return e.map((o,i)=>At(o,`${t}[${i}]`,r));if(typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`action receipt: JSON-like value required at ${t}`);let n={};for(let o of Object.keys(e).sort()){let i=`${t}.${o}`;if(Ri(o))throw new fe(i);e[o]!==void 0&&(n[o]=At(e[o],i,o))}return n}function vt(e){return At(e)}var vi,ki,Ii,Ti,_i,Ni,fe,Fe=a(()=>{vi=new Set(["privatekey","privkey","secretkey","seedphrase","seed","mnemonic","passphrase","password","keystore","keymaterial","wif","xprv","xpriv","bearer","authorization","signature","apikey","credential"]),ki=[/\b[5KL][1-9A-HJ-NP-Za-km-z]{50,51}\b/,/\bxprv[0-9A-Za-z]{50,}\b/],Ii=new Set([12,15,18,21,24]);Ti=/^\s*(?:0x)?[0-9a-fA-F]{64}\s*$/,_i=/(hash|digest|root|salt|nonce|proof|commitment|sig|id)(?:e?s)?$/i,Ni=new Set(["calldata","data","publickey","pubkey","message","payload","input","extradata"]);fe=class extends Error{constructor(t){super(`action receipt refused: secret-bearing field at ${t}`),this.name="ActionReceiptSecretError",this.code="ACTION_RECEIPT_SECRET"}}});import{wordlists as _d}from"ethers";var qr,Cd,re=a(()=>{Fe();qr=64*1024,Cd=32*1024});var Bi,$d,Pd,Me=a(()=>{re();Bi=["schemaVersion","buildVersion","recordType","execution","custody"],$d=[...Bi,"recordHash"],Pd=Object.freeze({signed:new Set(["workflow.signed","legacy.signed"]),submitted:new Set(["workflow.submitted","legacy.broadcast"]),finalized:new Set(["workflow.finalized"]),reorged:new Set(["workflow.reorged"]),orphaned:new Set(["workflow.orphaned"]),compensating:new Set(["workflow.compensating"]),compensated:new Set(["workflow.compensated"])})});var Di,Yr,Md,_t=a(()=>{re();Me();Di=Object.freeze(["draft","checked","approval","signed","submitted","finalized","reorged","orphaned","compensating","compensated","failed","cancelled"]),Yr=Object.freeze(["workflow.drafted","workflow.checked","workflow.approval_requested","workflow.approval_granted","workflow.signed","workflow.submitted","workflow.finalized","workflow.reorged","workflow.orphaned","workflow.compensating","workflow.compensated","workflow.failed","workflow.cancelled","workflow.annotated"]),Md=new Set(Yr)});var Ui,Xr=a(()=>{re();_t();Ui=64*1024*1024});var Kd,Gd,Jd,Zr=a(()=>{Kd=Object.freeze(["chainId","agentAddress","accountAddress","actions","targets","maxValueWei","maxGasWei","maxSlippageBps","expiresAt","nonce","revocationKey"]),Gd=Object.freeze(["read","simulate"]),Jd=1440*60});function Nt(e){let t=String(e),r=t.toLowerCase().replace(/[\s._-]+/g,"");return zi.test(t)||Wi.includes(r)}function Vi(e){return e.replace(/"([A-Za-z0-9_-]+)"\s*:\s*"(?:0x)?([0-9a-fA-F]{64})"/g,(t,r)=>en.includes(String(r).toLowerCase().replace(/[_-]/g,""))?`"${r}":"<hex64>"`:t)}function tn(e){let t;try{t=JSON.stringify(e)}catch(o){throw new M("$",`unserializable-payload: ${String(o?.message||o)}`)}if(t===void 0)return"null";let r=Vi(t);for(let{rule:o,re:i}of Qr)if(i.test(r))throw new M("$<serialized>",o);if(/(?:^|[^0-9a-fA-Fx])0x[0-9a-fA-F]{64}(?![0-9a-fA-F])/.test(r))throw new M("$<serialized>","raw-32-byte-hex-embedded");return JSON.parse(t,(o,i)=>{if(o&&Nt(o))throw new M(`$<serialized>.${o}`,"forbidden-key-name");return i}),t}function H(e,t="$",r=new Set,n=""){if(e==null)return e;if(typeof e=="string"){let o=en.includes(String(n).toLowerCase().replace(/[_-]/g,""));for(let{rule:i,re:s}of Qr)if(!(o&&i.startsWith("raw-32-byte-hex"))&&s.test(e))throw new M(t,i);return e}if(typeof e!="object"||r.has(e)||(r.add(e),ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e;if(e instanceof Map){for(let[o,i]of e.entries()){if(typeof o=="string"&&Nt(o))throw new M(`${t}[${JSON.stringify(o)}]`,"forbidden-key-name");H(o,`${t}[key]`,r),H(i,`${t}[${String(o)}]`,r)}return e}if(e instanceof Set){let o=0;for(let i of e.values())H(i,`${t}[${o++}]`,r);return e}if(Array.isArray(e))return e.forEach((o,i)=>H(o,`${t}[${i}]`,r)),e;for(let[o,i]of Object.entries(e)){if(Nt(o))throw new M(`${t}.${o}`,"forbidden-key-name");H(i,`${t}.${o}`,r,o)}return e}var M,zi,Wi,Qr,en,Ct=a(()=>{Zr();M=class extends Error{constructor(t,r){super(`secret material must never appear in a public API object (at ${t}, rule: ${r})`),this.name="SecretLeakError",this.path=t,this.rule=r}},zi=/(private[_-]?key|secret|bearer|keystore|mnemonic|seed[_-]?phrase|passphrase|password|api[_-]?key|access[_-]?token|auth[_-]?token|session[_-]?token|signer[_-]?url|signature)/i,Wi=Object.freeze(["privkey","wif","xprv","seed"]);Qr=Object.freeze([{rule:"raw-32-byte-hex-key",re:/^0x[0-9a-fA-F]{64}$/},{rule:"raw-32-byte-hex-bare",re:/^[0-9a-fA-F]{64}$/},{rule:"extended-private-key",re:/\b(?:xprv|tprv|yprv|zprv)[1-9A-HJ-NP-Za-km-z]{107}\b/},{rule:"bitcoin-wif",re:/\b[59KLc][1-9A-HJ-NP-Za-km-z]{50,51}\b/},{rule:"bip39-mnemonic",re:/\b(?:[a-z]{3,8}\s+){11,23}[a-z]{3,8}\b/},{rule:"bearer-token",re:/bearer\s+[A-Za-z0-9._~+/=-]+/i},{rule:"pem-private-key",re:/-----BEGIN[A-Z ]*PRIVATE KEY-----/},{rule:"keystore-path",re:/keystore/i},{rule:"signer-url",re:/https?:\/\/\S*sign/i},{rule:"authorization-header",re:/authorization\s*:/i}]),en=Object.freeze(["grantid","id","hash","sha256","sha256hex","checksum","txhash","transactionhash","blockhash","digest","userophash","commithash","prevhash","intenthash","canonicalhash","payloadhash","requestid"])});var Rt,af,rn=a(()=>{Ct();Rt=Object.freeze(["intent","quote_comparison","simulation","prepared","approval","signed","broadcast","settlement","balance_delta","position"]),af=Object.freeze(Object.fromEntries(Rt.map((e,t)=>[e,Object.freeze(t+1<Rt.length?[Rt[t+1]]:[])])))});var Ki,nn=a(()=>{rn();re();Me();Ki=Object.freeze({intent:"draft",quote_comparison:"draft",simulation:"draft",prepared:"checked",approval:"approval",signed:"signed",broadcast:"submitted",settlement:"finalized",balance_delta:"compensated",position:"compensated"})});var on=a(()=>{re();Me();_t();Xr();nn()});var Ji,Yi,Xi,Wf,Vf,Kf,Gf,Jf,Zi,Yf,sn=a(()=>{Ji=Object.freeze(["owner","operator","agent","viewer"]),Yi=Object.freeze(["tenant","config","policy","grant","workflow","trade","receipt","audit","telemetry"]),Xi=Object.freeze({read:"read",create:"create",update:"update",delete:"delete",manage:"manage",prepare:"prepare",cancel:"cancel",export:"export",approve:"approve"}),Wf=Object.freeze(["owner"]),Vf=Object.freeze({ALLOW_ROLE_PERMISSION:"allow.role_permission",DENY_MISSING_CONTEXT:"deny.missing_context",DENY_INVALID_CONTEXT:"deny.invalid_context",DENY_INVALID_REQUEST:"deny.invalid_request",DENY_UNKNOWN_RESOURCE:"deny.unknown_resource",DENY_UNKNOWN_ACTION:"deny.unknown_action",DENY_UNBOUND_OBJECT:"deny.unbound_object",DENY_TENANT_MISMATCH:"deny.tenant_mismatch",DENY_RESOURCE_MISMATCH:"deny.resource_mismatch",DENY_ROLE_PERMISSION:"deny.role_permission",DENY_POLICY_NOT_APPROVER:"deny.policy_not_approver"}),Kf=new Set(Ji),Gf=new Set(Yi),Jf=new Set(Object.values(Xi)),Zi=Object.freeze({owner:Object.freeze(["tenant:read","tenant:manage","config:read","config:manage","policy:read","policy:manage","grant:read","grant:create","grant:update","grant:delete","grant:manage","workflow:read","workflow:create","workflow:update","workflow:delete","workflow:cancel","workflow:approve","trade:read","trade:prepare","receipt:read","receipt:export","audit:read","audit:export","telemetry:read","telemetry:create","telemetry:export"]),operator:Object.freeze(["tenant:read","config:read","policy:read","grant:read","workflow:read","workflow:create","workflow:update","workflow:cancel","trade:read","trade:prepare","receipt:read","audit:read","telemetry:read","telemetry:create"]),agent:Object.freeze(["tenant:read","config:read","policy:read","grant:read","workflow:read","workflow:create","workflow:update","trade:read","trade:prepare","receipt:read","telemetry:create"]),viewer:Object.freeze(["tenant:read","config:read","grant:read","workflow:read","trade:read","receipt:read","audit:read","telemetry:read"])}),Yf=Object.freeze(Object.fromEntries(Object.entries(Zi).map(([e,t])=>[e,Object.freeze([...t])])))});var Qi,es,ts,ep,tp,rp,np,op,ip,Lt=a(()=>{sn();Qi=Object.freeze(["succeeded","denied","invalid","failed","cancelled","timed_out","unavailable","skipped"]),es=Object.freeze(["workflow","task","intent","plan","run","event","eval"]),ts=Object.freeze(["taskId","intentId","planId","runId","eventId"]),ep=Object.freeze({maxAttributes:24,maxKeyLength:48,maxStringLength:256,maxArrayLength:8}),tp=new Set(Qi),rp=new Set(es),np=new Set(ts),op=Object.freeze(["authorization","bearer","cookie","credential","password","passphrase","secret","token","privatekey","privkey","seed","mnemonic","keystore","signature","prompt","systemmessage","usermessage","assistantmessage","rawtransaction","signedtransaction","serializedtransaction","transactionbytes","calldata","callbytes","inputdata"]),ip=Object.freeze({taskId:"x-oracle-task-id",intentId:"x-oracle-intent-id",planId:"x-oracle-plan-id",runId:"x-oracle-run-id",eventId:"x-oracle-event-id"})});var dp,an=a(()=>{on();Lt();dp=Object.freeze({"workflow.cancelled":"cancelled","workflow.failed":"failed"})});var gp,cn=a(()=>{Lt();gp=32*1024*1024});var bp,Ep,xp,ne=a(()=>{bp=Object.freeze({N:1<<17,r:8,p:1}),Ep=256*1024*1024,xp=16*1024});var Ap,ln=a(()=>{Ap=Object.freeze({1:{name:"ethereum",mode:"mempool-private",endpoints:["https://rpc.flashbots.net/fast","https://rpc.mevblocker.io"]},8453:{name:"base",mode:"sequencer",endpoints:["https://mainnet-sequencer.base.org"]},10:{name:"optimism",mode:"sequencer",endpoints:["https://mainnet-sequencer.optimism.io"]},42161:{name:"arbitrum",mode:"sequencer",endpoints:["https://arb1-sequencer.arbitrum.io/rpc"]},56:{name:"bsc",mode:"mempool-private",endpoints:["https://rpc.48.club","https://bsc.rpc.blxrbdn.com"]},137:{name:"polygon",mode:"mempool-private",endpoints:["https://polygon-bor-rpc.publicnode.com"]},43114:{name:"avalanche",mode:"public-only",endpoints:[]},999:{name:"hyperevm",mode:"public-only",endpoints:[]}})});import{homedir as $t}from"node:os";import{join as Pt}from"node:path";var un,rs,Op,dn=a(()=>{un=process.env.ORACLE_PUBLIC_DESKTOP==="1",rs=un?process.env.ORACLE_CONFIG_DIR||Pt($t(),".config","oracle"):Pt($t(),".config","oracle"),Op=un?rs:Pt($t(),".config","mad-desk")});var Rp,Lp,$p,fn=a(()=>{dn();Rp="0".repeat(64),Lp=Object.freeze({PREPARE:"exec.prepare",SIGN:"exec.sign",BROADCAST:"exec.broadcast",POLICY_REJECT:"policy.reject",AUTH_GRANT:"auth.grant",AUTH_OK:"auth.verify.ok",AUTH_FAIL:"auth.verify.fail"}),$p=Promise.resolve()});var Bt=a(()=>{fn();z();ne();De()});var mn=a(()=>{});var gn={};Ae(gn,{SIGN_TIME_REVIEW_VERSION:()=>ns,SignTimeReviewSecretError:()=>pe,createSignTimeReview:()=>hn});function Dt(e,t="$",r=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string"){let o=e.trim().split(/\s+/);if(cs.test(e)||ls.has(o.length)&&o.every(i=>/^[a-z]+$/i.test(i)))throw new pe(t);return e}if(typeof e=="bigint")return e.toString();if(typeof e=="number"){if(!Number.isSafeInteger(e))throw new TypeError(`sign-time review: safe integer required at ${t}`);return e}if(Array.isArray(e))return e.map((o,i)=>Dt(o,`${t}[${i}]`,r));K(e,t);let n={};for(let o of Object.keys(e).sort()){let i=o.replace(/[^a-z0-9]/gi,"");if(as.test(i))throw new pe(`${t}.${o}`);e[o]!==void 0&&(n[o]=Dt(e[o],`${t}.${o}`,o))}return n}function K(e,t){if(e==null||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`sign-time review: ${t} must be a plain object`);return e}function me(e,t){if(e==null||e==="")throw new TypeError(`sign-time review: ${t} required`);return e}function oe(e,t){let r=String(me(e,t)).toLowerCase();if(!os.test(r))throw new TypeError(`sign-time review: ${t} must be an EVM address`);return r}function q(e,t,{positive:r=!1}={}){try{let n=BigInt(me(e,t));if(n<0n||r&&n===0n)throw new Error;return n.toString()}catch{throw new TypeError(`sign-time review: ${t} must be an unsigned integer`)}}function Ft(e,t){if(typeof e!="string"||e.length===0||e.length>500||e!==e.trim())throw new TypeError(`sign-time review: ${t} must be non-empty text`);return e}function wn(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))wn(t);Object.freeze(e)}return e}function us(e,t){if(typeof e=="boolean")return{passed:e,reason:e?"passed":"failed"};K(e,t);let r=e.passed??e.ok??e.allowed;if(typeof r!="boolean")throw new TypeError(`sign-time review: ${t} needs a boolean result`);let n=e.reason??e.message??e.name??(r?"passed":"failed");return{...e,passed:r,reason:Ft(String(n),`${t}.reason`)}}function ds(e){if(!Array.isArray(e))throw new TypeError("sign-time review: policyChecks must be an array");let t=e.map((n,o)=>us(n,`policyChecks[${o}]`)),r=t.filter(n=>!n.passed);return{checks:t,passed:t.length-r.length,failed:r.length,reasons:r.map(n=>n.reason)}}function fs(e){if(e==null)return null;if(K(e,"simulation"),typeof e.status!="string"||!["ok","success","failed","error","unavailable","unknown"].includes(e.status))throw new TypeError("sign-time review: simulation.status is invalid");if(e.willRevert!==!0&&e.willRevert!==!1&&e.willRevert!==null)throw new TypeError("sign-time review: simulation.willRevert must be boolean or null");let t={status:e.status,willRevert:e.willRevert??null,summary:Ft(String(e.summary??"simulation result recorded"),"simulation.summary")};return e.gasEstimate!=null&&(t.gasEstimate=q(e.gasEstimate,"simulation.gasEstimate")),e.gasLimit!=null&&(t.gasLimit=q(e.gasLimit,"simulation.gasLimit")),t}function ps(e){if(e==null)return null;if(!Array.isArray(e)||e.length===0)throw new TypeError("sign-time review: assetDeltas must be a non-empty array");return e.map((t,r)=>{K(t,`assetDeltas[${r}]`);let n=q(t.before,`assetDeltas[${r}].before`),o=q(t.after,`assetDeltas[${r}].after`),i=(BigInt(o)-BigInt(n)).toString(),s;try{s=t.delta==null?i:BigInt(t.delta).toString()}catch{throw new TypeError(`sign-time review: assetDeltas[${r}].delta must be an integer`)}if(s!==i)throw new TypeError(`sign-time review: assetDeltas[${r}].delta does not match before/after`);return{...t,asset:Ft(String(me(t.asset??t.token,`assetDeltas[${r}].asset`)),`assetDeltas[${r}].asset`),before:n,after:o,delta:s}})}function ms(e){if(e==null)return[];if(!Array.isArray(e))throw new TypeError("sign-time review: approvalDeltas must be an array");return e.map((t,r)=>{K(t,`approvalDeltas[${r}]`);let n=q(t.amount??t.after,`approvalDeltas[${r}].amount`);if(t.revokeLike!=null&&typeof t.revokeLike!="boolean")throw new TypeError(`sign-time review: approvalDeltas[${r}].revokeLike must be boolean`);return{token:oe(t.token,`approvalDeltas[${r}].token`),spender:oe(t.spender,`approvalDeltas[${r}].spender`),owner:oe(t.owner,`approvalDeltas[${r}].owner`),amount:n,revokeLike:t.revokeLike??BigInt(n)===0n}})}function hn(e={}){K(e,"input");let t=Dt(e),r=t.tx==null?t:K(t.tx,"tx"),n=q(t.chainId??r.chainId,"chainId",{positive:!0}),o=oe(t.account??t.from??r.from,"account/from"),i=oe(t.destination??t.to??r.to,"destination/to"),s=String(me(t.prepareHash,"prepareHash")).toLowerCase();if(!ss.test(s))throw new TypeError("sign-time review: prepareHash must be a 32-byte hash");let d=t.route??t.venue;if(d==null)throw new TypeError("sign-time review: route/venue required");let c=t.decodedCalldata??t.decodedAction;if(c==null)throw new TypeError("sign-time review: decodedCalldata or decodedAction required");let p=String(me(t.calldata??t.data??r.data,"calldata/data")).toLowerCase();if(!is.test(p))throw new TypeError("sign-time review: calldata/data must be even-length hex");let m=t.policyChecks!==void 0&&t.policyChecks!==null,l=ds(m?t.policyChecks:[]),f=fs(t.simulation),u=ps(t.assetDeltas),b=ms(t.approvalDeltas),h=t.allowlistHits??[];if(!Array.isArray(h))throw new TypeError("sign-time review: allowlistHits must be an array");let w=f?.willRevert===!0||["failed","error"].includes(f?.status),I=f!=null&&f.willRevert===!1&&["ok","success"].includes(f.status),T=w||l.failed>0?"BLOCKED":I&&m&&l.checks.length>0&&u!=null?"READY":"UNKNOWN",g=typeof c=="string"?c:c.method??c.action??c.type??"transaction",y=`${T}: review ${g} on chain ${n}; policy ${l.passed} passed, ${l.failed} failed; ${u?.length??0} asset delta${u?.length===1?"":"s"}; local signature required`,x={reviewVersion:1,status:T,requiresLocalSignature:!0,signingLocal:!0,custody:"none",execution:"review-only",chainId:n,account:o,from:o,route:d,venue:t.venue??(typeof d=="string"?d:d.venue??d.provider??null),destination:i,to:i,...t.spender==null?{}:{spender:oe(t.spender,"spender")},prepareHash:s,...t.decodedCalldata!==void 0?{decodedCalldata:t.decodedCalldata}:{decodedAction:t.decodedAction},calldata:p,data:p,selector:p.length>=10?p.slice(0,10):null,value:q(t.value??r.value??0,"value"),...(t.gasEstimate??r.gasEstimate)==null?{}:{gasEstimate:q(t.gasEstimate??r.gasEstimate,"gasEstimate")},...(t.gasLimit??r.gasLimit)==null?{}:{gasLimit:q(t.gasLimit??r.gasLimit,"gasLimit")},simulation:f,policyChecks:l,allowlistHits:h,assetDeltas:u,approvalDeltas:b,summary:y};return wn(x)}var ns,os,is,ss,as,cs,ls,pe,jt=a(()=>{ns=1,os=/^0x[0-9a-f]{40}$/,is=/^0x(?:[0-9a-f]{2})*$/,ss=/^(?:0x)?[0-9a-f]{64}$/,as=/(privatekey|privkey|secretkey|seedphrase|mnemonic|passphrase|password|keystore|keymaterial|wif|xprv|xpriv|bearer|authorization|signature|apikey|credential)/i,cs=/\b(?:[5KL][1-9A-HJ-NP-Za-km-z]{50,51}|xprv[0-9A-Za-z]{50,})\b/,ls=new Set([12,15,18,21,24]),pe=class extends Error{constructor(t){super(`sign-time review refused: secret-bearing field at ${t}`),this.name="SignTimeReviewSecretError",this.code="SIGN_TIME_REVIEW_SECRET"}}});import{readFileSync as zp,readdirSync as Wp,existsSync as ws}from"node:fs";import{dirname as hs,join as we}from"node:path";import{fileURLToPath as gs}from"node:url";function ys(){let e=[we(he,"descriptors"),we(he,"clear-sign","descriptors"),we(he,"..","clear-sign","descriptors"),we(he,"..","..","clear-sign","descriptors"),we(he,"..","..","..","clear-sign","descriptors")];for(let t of e)if(ws(t))return t;return e[0]}var he,Jp,Yp,yn=a(()=>{W();he=hs(gs(import.meta.url));Jp=ys(),Yp=(1n<<256n)-1n});var bn=a(()=>{jt();W();yn()});import{Wallet as om}from"ethers";import{base58 as sm}from"@scure/base";import{ed25519 as cm}from"@noble/curves/ed25519.js";import{NETWORK as um,TEST_NETWORK as dm,WIF as fm,p2wpkh as pm}from"@scure/btc-signer";import{pubECDSA as wm}from"@scure/btc-signer/utils.js";var En=a(()=>{});var ym,bm,Em,xm,Sm,Am,vm,km,Im,Om,Tm,xn=a(()=>{Bt();ym=Object.freeze(["spot-limit-create","spot-limit-cancel","spot-order-status"]),bm=Object.freeze(["binance","bybit","okx","coinbase"]),Em=Object.freeze({binance:"https://api.binance.com",bybit:"https://api.bybit.com",okx:"https://openapi.okx.com",coinbase:"https://api.exchange.coinbase.com"}),xm=Object.freeze({binance:"/api/v3",bybit:"/v5/order",okx:"/api/v5/trade",coinbase:"/orders"}),Sm=Object.freeze(["version","surface","kind","venue","credentialRef","symbol","base","quote","side","baseSize","limitPrice","maxQuoteNotional","timeInForce","clientOrderId","expiresAtMs","venueOrderId","nonce","grantId","artifactHash"]),Am=Object.freeze(["market-create","withdraw","transfer","subaccount","leverage","futures","margin","convert","api-key"]),vm=Object.freeze(["url","host","path","method","headers","signature","apiKey","apiSecret","passphrase","privateKey","redirect","proxy"]),km=Object.freeze(["ccxt","binance-api-node","node-binance-api","coinbase-advanced-node","@okx-dex/okx-dex-sdk","bybit-api"]),Im=Object.freeze({perOrderQuote:"sealed-owner-policy",dailyGrossQuote:"sealed-owner-policy",scope:Object.freeze(["per-order","UTC-day","account","venue","quote"]),envelopeFieldIsNotCeiling:!0}),Om=Object.freeze({binanceRecvWindowMs:5e3,bybitWindowMs:5e3,maxLocalSkewMs:2e3}),Tm=Object.freeze({perSecond:1,perMinute:30,bind:"tighter"})});var Sn=a(()=>{ne()});var xs,An,He=a(()=>{xs=Object.freeze({binance:Object.freeze({create:["POST","/api/v3/order"],cancel:["DELETE","/api/v3/order"],status:["GET","/api/v3/order"]}),bybit:Object.freeze({create:["POST","/v5/order/create"],cancel:["POST","/v5/order/cancel"],status:["GET","/v5/order/realtime"]}),okx:Object.freeze({create:["POST","/api/v5/trade/order"],cancel:["POST","/api/v5/trade/cancel-order"],status:["GET","/api/v5/trade/order"]}),coinbase:Object.freeze({create:["POST","/orders"],cancel:["DELETE","/orders/{order_id}"],status:["GET","/orders/{order_id}"]})}),An=Object.freeze({binance:"https://api.binance.com",bybit:"https://api.bybit.com",okx:"https://openapi.okx.com",coinbase:"https://api.exchange.coinbase.com"})});var vn=a(()=>{He()});var Fm,kn=a(()=>{He();vn();Fm=256*1024});var In=a(()=>{He();kn()});var On=a(()=>{ne()});import N from"node:path";import Ss from"node:os";import{createHash as As,randomBytes as Cw}from"node:crypto";import{Interface as Mt,keccak256 as Lw}from"ethers";import{Transaction as Pw}from"@scure/btc-signer";import{ed25519 as Dw}from"@noble/curves/ed25519.js";function Tn(e){let t=process.env.ORACLE_SIGNER_STATE_DIR||N.join(process.env.XDG_STATE_HOME||N.join(Ss.homedir(),".local","state"),"oracle"),r=As("sha256").update(N.resolve(e)).digest("hex").slice(0,16);return{vault:N.join(e,"vault.json"),policy:N.join(e,"signer-policy.json"),policyKey:N.join(e,"policy-integrity-key"),policyAnchor:N.join(t,`signer-policy-${r}.high-water`),ledger:N.join(e,"signer-ledger.json"),ledgerAnchor:N.join(t,`signer-ledger-${r}.high-water`),cexOrders:N.join(e,"cex-orders.json"),cexOrdersAnchor:N.join(t,`cex-orders-${r}.high-water`),token:N.join(e,"signer-token"),lock:N.join(t,`signer-${r}.lock`),workflowLedger:N.join(e,"workflow-events.jsonl")}}var ph,mh,wh,_n=a(()=>{jr();an();cn();De();ne();ln();Bt();mn();W();bn();Be();Ce();St();ht();yt();Pe();xt();gt();Et();it();st();bt();En();xn();Sn();In();On();ph=new Mt(["function collection() view returns (address)","function token() view returns (address)","function robinhoodSwapFeeWei() view returns (uint256)","function quoteSpecificBuy(uint256 tokenId) view returns (uint256 totalCost,uint256 baseCost,uint256 fee,uint256 protocolFee,bool available)","function quoteSellNFT() view returns (uint256 netPayout,uint256 grossPayout,uint256 fee,uint256 protocolFee)","function inventory(uint256 tokenId) view returns (bool)","function buySpecificNFT(uint256 tokenId,uint256 maxCost) payable","function sellNFT(uint256 tokenId,uint256 minPayout) payable"]),mh=new Mt(["function decimals() view returns (uint8)","function allowance(address owner,address spender) view returns (uint256)"]),wh=new Mt(["function ownerOf(uint256 tokenId) view returns (address)","function getApproved(uint256 tokenId) view returns (address)","function isApprovedForAll(address owner,address operator) view returns (bool)"])});import qt from"node:fs";import Nn from"node:path";import{homedir as vs}from"node:os";function ks(){return process.env.ORACLE_CONFIG_DIR||Nn.join(vs(),".config","oracle")}function ge(){let e=Tn(Nn.join(ks(),"signer")),t=qt.existsSync(e.vault),r=qt.existsSync(e.lock),n=t?r?"disarmed":"armed-owner-confirmed":"inert-no-key";return{vaultExists:t,policyConfigured:qt.existsSync(e.policy),armed:t&&!r,disarmed:r,capabilities:{swap:n,bridge:n},autonomous:!1,note:"Keys stay on this machine. Exact confirmation is required before any broadcast."}}var Ih,Ht=a(()=>{et();fr();_n();ne();Ih=Object.freeze([{type:"function",function:{name:"vault_status",description:"Read local Oracle vault/signer readiness. Never returns key material.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"signer_status",description:"Ping the loopback signer. Fails closed if it is not running.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"signer_pending",description:"List pending local-signer artifacts. Read-only. Does not approve, sign, or broadcast.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"signer_queue",description:"Queue a prepared unsigned artifact on the loopback signer. Does not broadcast.",parameters:{type:"object",properties:{artifact:{type:"object"}},required:["artifact"],additionalProperties:!1}}},{type:"function",function:{name:"signer_ack",description:"Execute one pending artifact through the armed local signer (same path as Telegram Allow). Fails if the signer is not running or disarmed. Never holds keys.",parameters:{type:"object",properties:{id:{type:"string"},digest:{type:"string"}},additionalProperties:!1}}},{type:"function",function:{name:"signer_deny",description:"Drop one pending local-signer artifact. Nothing signed.",parameters:{type:"object",properties:{id:{type:"string"},digest:{type:"string"}},additionalProperties:!1}}},{type:"function",function:{name:"signer_execute",description:"Broadcast one already-confirmed local artifact. Requires a one-use confirmationNonce from the local signer TTY confirm. Cannot mint confirmation itself.",parameters:{type:"object",properties:{artifact:{type:"object"},confirmationNonce:{type:"string",minLength:32,maxLength:128}},required:["artifact","confirmationNonce"],additionalProperties:!1}}},{type:"function",function:{name:"signer_disarm",description:"Global kill switch. Stops the local signer from broadcasting.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"receipt_report",description:"Receipt or it did not happen. Requires transactionHash/hash/txid.",parameters:{type:"object",properties:{receipt:{type:"object"},transactionHash:{type:"string"},hash:{type:"string"},txid:{type:"string"}},additionalProperties:!1}}},{type:"function",function:{name:"watch_create",description:"Create an alert-only watch. Never execute.",parameters:{type:"object",properties:{chain:{type:"string"},token:{type:"string"},condition:{type:"string"},note:{type:"string"}},required:["chain","token","condition"],additionalProperties:!1}}},{type:"function",function:{name:"watch_list",description:"List local alert-only watches.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"portfolio_snapshot",description:"How to read the one portfolio snapshot. knownUsd is incomplete if a provider is missing.",parameters:{type:"object",properties:{},additionalProperties:!1}}}])});function Ue(e){return String(e||"").trim()||void 0}function Os(e,{required:t=!1}={}){let r=Ue(e)?.toLowerCase();if(!r){if(t)throw new Error("model provider is required");return}if(!Is.has(r))throw new Error(`unsupported provider: ${r}`);return r}function Ts(e,{required:t=!1}={}){let r=Ue(e);if(!r){if(t)throw new Error("model is required");return}if(r.includes("..")||r.startsWith("/")||!/^[a-zA-Z0-9._:/-]{1,200}$/.test(r))throw new Error("invalid model id");return r}function _s(e){let t=Ue(e);if(!t||t.length>2048)throw new Error("invalid custom base URL");let r;try{r=new URL(t)}catch{throw new Error("invalid custom base URL")}let n=r.hostname.toLowerCase().replace(/^\[|\]$/g,""),o=n==="localhost"||n==="127.0.0.1"||n==="::1";if(r.protocol!=="https:"&&!(r.protocol==="http:"&&o)||r.username||r.password||r.search||r.hash)throw new Error("custom base URL must use HTTPS or loopback HTTP without credentials, query, or fragment");return r.toString().replace(/\/+$/,"")}function Cn({provider:e,model:t,baseUrl:r}={},{requireModel:n=!1}={}){let o=Os(e),i=Ts(t,{required:n});if(o==="custom")return{provider:o,...i?{model:i}:{},baseUrl:_s(r)};if(Ue(r))throw new Error("baseUrl is only supported for the custom provider");return{...o?{provider:o}:{},...i?{model:i}:{}}}var Is,Rn=a(()=>{Is=new Set(["openrouter","openai","anthropic","xai","deepseek","gemini","kimi","mistral","nous","qwen","glm","local","ollama","custom","anthropic-oauth","openai-codex","xai-oauth"])});import Ln from"node:fs";import Ns from"node:path";function Rs(){return Ns.join(Z(),"model.json")}function ie(e){return String(e||"").trim()||void 0}function Ls(e={}){let t=ie(e.backend)?.toLowerCase()||"auto",r=Cn({provider:e.provider,model:e.model,baseUrl:e.baseUrl},{requireModel:t==="standalone"}),n=ie(e.apiKeyEnv),o=Number.parseInt(String(e.contextLength||""),10),i=ie(e.reasoningEffort),s=ie(e.computeHost||e.remoteHost),d=ie(e.computeUser||e.remoteUser),c=ie(e.computePath||e.remotePath);if(!Cs.has(t))throw new Error(`unsupported backend: ${t}`);if(process.env.ORACLE_PUBLIC_DESKTOP==="1"&&["remote","arch"].includes(t))throw new Error("remote compute backends are disabled in the public desktop");if(n&&!/^[A-Z][A-Z0-9_]*$/.test(n))throw new Error("api key env must be an uppercase environment variable name");if(t==="remote"&&!s)throw new Error("remote backend requires computeHost");return{backend:t,...r,...n?{apiKeyEnv:n}:{},...Number.isFinite(o)&&o>0?{contextLength:o}:{},...i?{reasoningEffort:i}:{},...s?{computeHost:s}:{},...d?{computeUser:d}:{},...c?{computePath:c}:{}}}function $n(){let e=Rs();if(!Ln.existsSync(e))return null;try{return Ls(JSON.parse(Ln.readFileSync(e,"utf8")))}catch{return null}}var Cs,Pn=a(()=>{ke();Rn();Cs=new Set(["auto","standalone","hermes","remote","arch"])});import{Interface as $s,getAddress as Ps}from"ethers";function Ut(e,t){try{return Ps(e).toLowerCase()}catch{throw new Error(`${t} must be a valid EVM address`)}}function Bs(e){let t=String(e||"").trim();if(!/^0x[0-9a-fA-F]{64}$/.test(t))throw new Error("txHash must be a 32-byte hex transaction hash");return t.toLowerCase()}function zt(e){return e==null?null:Number.parseInt(String(e),16)}function Fs(e,{rpcUrl:t,env:r=process.env}={}){if(t)return t;let n=dr(e,r);return n||Ds[Number(e)]||null}function Ms(e){let t=String(e||""),r=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!js.test(r))throw new Error(`evm-rpc: ${t} refused \u2014 @oracle-agent/oracle is prepare-only (read RPC only; no broadcast/sign)`);return r}function qs(e){let t=new Error(e?.message||JSON.stringify(e));return t.code=e?.code,t}function Hs(e){if(e?.error)throw qs(e.error);return e?.result}function Us(e,t,r){return`${e}
1
+ var Uo=Object.defineProperty;var c=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var Re=(e,t)=>{for(var r in t)Uo(e,r,{get:t[r],enumerable:!0})};import Le from"node:fs";import Mo from"node:os";import oe from"node:path";import{fileURLToPath as jo}from"node:url";function nt(){return process.env.ORACLE_FAKE_HOME||Mo.homedir()}function zo(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function ie(){return zo()?process.env.ORACLE_CONFIG_DIR||oe.join(nt(),".config","oracle"):oe.join(nt(),".config","oracle")}function Wo(){return oe.join(ie(),"desk.json")}function Vo(){return oe.join(ie(),"env")}function ne({force:e=!1}={}){if(ne._done&&!e)return ne._result||null;ne._done=!0;let t={},r=(o,i)=>{if(i==null)return;let s=String(i).trim();s&&(process.env[o]!=null&&String(process.env[o]).trim()!==""||(process.env[o]=s,t[o]=s))};try{let o=Vo();if(Le.existsSync(o))for(let i of Le.readFileSync(o,"utf8").split(/\r?\n/)){let s=i.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!s||s[2].startsWith("#"))continue;let p=s[2];(p.startsWith('"')&&p.endsWith('"')||p.startsWith("'")&&p.endsWith("'"))&&(p=p.slice(1,-1)),r(s[1],p)}}catch{}try{let o=Wo();if(Le.existsSync(o)){let i=JSON.parse(Le.readFileSync(o,"utf8"));i&&typeof i=="object"&&(r("ORACLE_DESK_URL",i.deskUrl||i.dataUrl||i.url),r("ORACLE_DATA_URL",i.dataUrl||i.deskUrl||i.url),r("ORACLE_API_URL",i.apiUrl||i.dataUrl||i.deskUrl),r("ORACLE_PUBLIC_URL",i.publicUrl||i.deskUrl||i.dataUrl),r("ORACLE_EXEC_URL",i.execUrl),r("MAD_DESK_URL",i.deskUrl||i.dataUrl))}}catch{}let n=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return n&&(r("ORACLE_DESK_URL",n),r("ORACLE_DATA_URL",n),r("ORACLE_API_URL",n),r("ORACLE_PUBLIC_URL",n),r("MAD_DESK_URL",n)),ne._result=Object.keys(t).length?t:null,ne._result}var Ho,O,Pe=c(()=>{Ho=oe.dirname(jo(import.meta.url)),O=oe.resolve(Ho,"../..");try{ne()}catch{}});import Q from"node:net";import fi from"node:dns";function $e(e){let t=String(e).toLowerCase().split("%")[0];if((t.match(/::/g)||[]).length>1)return null;let r=h=>{if(!h)return[];let l=h.split(":"),m=l.at(-1);if(m?.includes(".")){let d=m.split(".").map(Number);if(d.length!==4||d.some(b=>!Number.isInteger(b)||b<0||b>255))return null;l.splice(l.length-1,1,(d[0]<<8|d[1]).toString(16),(d[2]<<8|d[3]).toString(16))}return l.some(d=>!/^[0-9a-f]{1,4}$/.test(d))?null:l.map(d=>Number.parseInt(d,16))},[n,o]=t.split("::"),i=r(n),s=r(o);if(!i||!s)return null;let p=t.includes("::"),u=8-i.length-s.length;if(!p&&u!==0||p&&u<1)return null;let f=[...i,...Array(Math.max(0,u)).fill(0),...s];return f.length!==8?null:Uint8Array.from(f.flatMap(h=>[h>>8,h&255]))}function ct(e,t,r){let n=Math.floor(r/8),o=r%8;for(let s=0;s<n;s+=1)if(e[s]!==t[s])return!1;if(!o)return!0;let i=255<<8-o;return(e[n]&i)===(t[n]&i)}function ut(e){if(Q.isIPv4(e)){let t=e.split(".").map(Number);return!(t[0]===0||t[0]===10||t[0]===127||t[0]>=224||t[0]===100&&t[1]>=64&&t[1]<=127||t[0]===169&&t[1]===254||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&(t[1]===0||t[1]===2||t[1]===168)||t[0]===192&&t[1]===88&&t[2]===99||t[0]===198&&(t[1]===18||t[1]===19||t[1]===51)||t[0]===203&&t[1]===0&&t[2]===113)}if(Q.isIPv6(e)){let t=$e(e);if(!t)return!1;let r=$e("::ffff:0:0");return ct(t,r,96)?ut([...t.slice(12)].join(".")):ct(t,$e("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([o,i])=>ct(t,$e(o),i)):!1}return!1}function mi(e){let t;try{t=new URL(String(e))}catch{return{ok:!1,error:`not a valid URL: ${String(e).slice(0,120)}`}}if(t.protocol!=="http:"&&t.protocol!=="https:")return{ok:!1,error:`refused protocol ${t.protocol} (only http/https)`};let r=t.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"");if(pi.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=Q.isIP(r);return n!==0&&!ut(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:t,host:r,isLiteralIp:n!==0}}async function lt(e,{lookupFn:t=fi.promises.lookup}={}){let r=mi(e);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:Q.isIPv6(r.host)?6:4}]};let n;try{n=await t(r.host,{all:!0,verbatim:!0})}catch{return{ok:!1,error:`refused: ${r.host} did not resolve`}}return!Array.isArray(n)||n.length===0||n.some(o=>!ut(o.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}async function dt({requireUndici:e=!1,importUndici:t=()=>import("undici")}={}){let r,n;try{let l=await t();r=l.Agent,n=l.fetch}catch(l){if(e)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${l?.message||l}`);return null}if(typeof r!="function"||typeof n!="function"){if(e)throw new Error("egress-guard: untrustedUrl pinning requires undici's Agent and fetch exports, which were not found on the imported module");return null}let o=l=>String(l).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),i=new Map,s=l=>(Array.isArray(l)?l:[l]).map(m=>typeof m=="string"?{address:m}:m).filter(m=>m&&m.address).map(m=>({address:m.address,family:m.family||(Q.isIPv6(m.address)?6:4)})),p=(l,m,d)=>{i.set(o(l),s(typeof m=="string"?[{address:m,family:d}]:m))},u=l=>{let m=o(l);if(Q.isIP(m))return[{address:m,family:Q.isIPv6(m)?6:4}];let d=i.get(m);if(!d||!d.length)throw new Error(`refused: unpinned host ${l} during pinned fetch`);return d},f=new r({connect:{lookup(l,m,d){let b;try{b=u(l)}catch(y){return d(y)}return m?.all?d(null,b):d(null,b[0].address,b[0].family)}}}),h=hi((l,m={})=>n(l,{...m,dispatcher:f}),p);return{dispatcher:f,fetch:h,pin:p,resolve:u,async close(){try{await f.destroy()}catch{}}}}function hi(e,t){if(typeof e!="function")throw new Error("markPinCapableFetch: fetchImpl must be a function");if(typeof t!="function")throw new Error("markPinCapableFetch: pin must be a function");return e[ft]=Object.freeze({pin:t}),e}function pt(e){return typeof e=="function"&&typeof e[ft]?.pin=="function"}function Rr(e,t,r){if(!pt(e))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");e[ft].pin(t,r)}var pi,ft,Lr=c(()=>{pi=new Set(["localhost","metadata.google.internal","metadata.goog"]);ft=Symbol.for("oracle.egressGuard.pinCapableFetch")});import{createHash as Pr}from"node:crypto";function Ei(e){let t=String(e||"").toLowerCase();return Mr.includes(t)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(t)}function Si(e){let t={};for(let[r,n]of Object.entries(e||{}))Ei(r)||(t[r]=n);return t}function xi(e,t){if(!e)throw new Error(`HTTP redirect from ${t} missing Location`);let r=new URL(String(e),String(t));if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`HTTP redirect from ${t} used unsupported protocol ${r.protocol}`);return r.toString()}function vi(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}function Dr(e){let t=String(e?.method||"");return t?!Ai.test(t):!1}function ki(e,t){if(e==="GET"&&t==null)return!0;if(e!=="POST"||t==null)return!1;let r=t;if(typeof t=="string")try{r=JSON.parse(t)}catch{return!1}return Array.isArray(r)?r.length>0&&r.every(Dr):!r||typeof r!="object"?!1:r.jsonrpc&&r.method?Dr(r):typeof r.type=="string"&&Ii.has(r.type)&&r.action==null&&r.signature==null&&r.nonce==null}function Oi(e,t,r,n={},o=null){let i={};for(let[m,d]of Object.entries(r||{}))i[m.toLowerCase()]=d;let s=Object.keys(i).filter(m=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(m)),u=[...new Set([...Mr,...s])].sort().map(m=>`${m}=${i[m]??""}`).join(`
2
+ `),f=Pr("sha256").update(u).digest("hex").slice(0,32),h=`${n.untrustedUrl?"untrusted":"trusted"}:${n.maxResponseBytes??"unbounded"}`,l=o==null?"-":Pr("sha256").update(String(o)).digest("hex").slice(0,32);return`${e} ${t} ${h} ${f} ${l}`}function _i(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,Br):Math.min(250*2**e,Br)+Math.floor(Math.random()*100)}function he(e,t={}){let r=new Error(e);return r.retryable=!1,Object.assign(r,t),r}function ht(e,t,r){return he(`HTTP response from ${e} exceeded maxResponseBytes ${r} (${t})`,{oversize:!0})}function we(e){try{let t=e?.body?.cancel?.();t&&typeof t.then=="function"&&t.catch(()=>{})}catch{}}function Ti(e){return e?e.byteLength??e.length??0:0}async function qr(e,t,{url:r,truncate:n=!1,onOversize:o}={}){if(t==null)return await e.text();let i=Number(e.headers?.get?.("content-length"));if(Number.isFinite(i)&&i>t&&(we(e),!n))throw ht(r,`content-length ${i}`,t);let s=e.body?.getReader?.();if(!s){let l=await e.text(),m=Buffer.byteLength(l,"utf8");if(m>t){if(!n)throw ht(r,`body ${m} bytes`,t);return Buffer.from(l,"utf8").subarray(0,t).toString("utf8")}return l}let p=[],u=0,f=!1;try{for(;;){let{value:l,done:m}=await s.read();if(m)break;if(l&&(p.push(Buffer.from(l)),u+=Ti(l),u>t)){f=!0;break}}}finally{if(f)try{await s.cancel()}catch{}try{s.releaseLock?.()}catch{}}if(f&&(typeof o=="function"&&o(),!n))throw ht(r,`streamed ${u} bytes`,t);let h=Buffer.concat(p);return(f?h.subarray(0,t):h).toString("utf8")}function Ur(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function Ni(e,{fetchImpl:t,method:r,headers:n,body:o,timeoutMs:i,lookupFn:s,realFetch:p,untrustedUrl:u=!1,maxResponseBytes:f=null,importUndici:h,validateResponse:l,signal:m}){let d=new AbortController,b=setTimeout(()=>d.abort(),i),y=m?typeof AbortSignal.any=="function"?AbortSignal.any([m,d.signal]):m:d.signal,w=null,k=t,N=s?{lookupFn:s}:{};if(u&&!p&&!pt(k))throw he(`HTTP refused ${e}: untrustedUrl requires a pin-capable fetchImpl (see markPinCapableFetch in egress-guard.mjs) or no fetchImpl override so Oracle can pin the connection itself`);let S=async(g,{status:x=null}={})=>{let I=await lt(g,N);if(!I.ok)throw he(x==null?`HTTP refused ${g}: ${I.error}`:`HTTP redirect to ${g} ${I.error}`,x==null?{}:{status:x});let E=new URL(g).hostname;if(p){if(w&&(await w.close(),w=null),!w)try{w=await dt({requireUndici:!0,...h?{importUndici:h}:{}})}catch(v){throw he(x==null?`HTTP refused ${g}: ${v?.message||v}`:`HTTP redirect to ${g} refused: ${v?.message||v}`,x==null?{}:{status:x})}w.pin(E,I.addresses),k=w.fetch}else Rr(k,E,I.addresses);return I};try{let g=String(e),x={...n||{}};u&&await S(g);for(let I=0;I<=Fr;I+=1){let E=await k(g,{method:r,headers:x,body:o,signal:y,redirect:"manual"});if(yi.has(E.status)){if(r!=="GET"&&r!=="HEAD"){let F=await qr(E,f??bi,{url:g,truncate:!0}),K=new Error(`HTTP ${E.status} ${r} ${g} redirected non-idempotent request`);throw K.status=E.status,K.body=Ur(F)??F.slice(0,300),K}if(I===Fr)throw we(E),new Error(`HTTP redirect loop for ${e}`);let _=E.headers?.get?.("location"),P;try{P=xi(_,g)}catch(F){throw we(E),F}let M=!vi(P,g);if(we(E),M&&(x=Si(x)),u)await S(P,{status:E.status});else if(M){let F=await lt(P,N);if(!F.ok){let K=new Error(`HTTP redirect from ${g} ${F.error}`);throw K.status=E.status,K.retryable=!1,K}p&&F.addresses?.length&&(w||(w=await dt(h?{importUndici:h}:{})),w&&(w.pin(new URL(P).hostname,F.addresses),k=w.fetch))}g=P;continue}if(typeof l=="function")try{await l(E,{url:g})}catch(_){throw we(E),he(_?.message||String(_))}let v=await qr(E,f,{url:g,onOversize:()=>d.abort()}),J=Ur(v);if(!E.ok){let _=new Error(`HTTP ${E.status} ${r} ${g}`);throw _.status=E.status,_.retryAfter=E.headers?.get?.("retry-after")??null,_.body=J??v.slice(0,300),_}return J??v}throw new Error(`HTTP redirect loop for ${e}`)}finally{clearTimeout(b),w&&await w.close()}}async function U(e,t={}){let r=t.fetchImpl||globalThis.fetch;if(typeof r!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let n=t.timeoutMs??12e3,o=(t.method||"GET").toUpperCase(),i={Accept:"application/json",...t.headers||{}},s=t.body;s!=null&&typeof s!="string"&&(i["Content-Type"]=i["Content-Type"]||"application/json",s=JSON.stringify(s));let p=Number.isInteger(t.retries)?Math.max(t.retries,0):gi,u=t.lookupFn,f=!t.fetchImpl,h=t.untrustedUrl===!0,l=t.importUndici,m=t.validateResponse,d=t.signal,b=Number(t.maxResponseBytes),y=Number.isFinite(b)&&b>0?Math.floor(b):null,w=async()=>{let x;for(let I=0;I<=p;I++){d?.throwIfAborted?.();try{return await Ni(e,{fetchImpl:r,method:o,headers:i,body:s,timeoutMs:n,lookupFn:u,realFetch:f,untrustedUrl:h,maxResponseBytes:y,importUndici:l,validateResponse:m,signal:d})}catch(E){x=E;let v=E?.status,J=E?.name==="AbortError"||E?.name==="TimeoutError"||d?.aborted,_=new Set([408,425,429]),P=E?.retryable===!1?!1:v!=null?_.has(v)||wi.has(v)&&$r.has(o):!J&&$r.has(o);if(I===p||!P)throw E;let M=_i(I,E?.retryAfter);d?await new Promise((F,K)=>{let qo=setTimeout(F,M);d.addEventListener("abort",()=>{clearTimeout(qo),K(d.reason||new DOMException("Aborted","AbortError"))},{once:!0})}):await Ci(M)}}throw x};if(!(t.dedupe!==!1&&!d&&ki(o,s)))return w();let N=Oi(o,e,i,{untrustedUrl:h,maxResponseBytes:y},s),S=mt.get(N);if(S)return S;let g=w().finally(()=>mt.delete(N));return mt.set(N,g),g}var wi,$r,gi,Br,Mr,yi,Fr,bi,mt,Ai,Ii,Ci,$=c(()=>{Lr();wi=new Set([408,425,429,500,502,503,504]),$r=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),gi=2,Br=4e3,Mr=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],yi=new Set([301,302,303,307,308]),Fr=3,bi=64*1024;mt=new Map,Ai=/(?:^|_)(send|submit|broadcast|sign|requestAirdrop)(?=[A-Z_]|$)/i,Ii=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);Ci=e=>new Promise(t=>setTimeout(t,e))});function jr(e){return Ri.get(Number(e))||null}function Hr(e,t=process.env){let r=jr(e);if(!r)return null;for(let n of r.rpcEnv){let o=(t[n]||"").trim();if(o)return o}return null}var Be,Ri,wt=c(()=>{Be={robinhood:{chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC"],evm:!0},ethereum:{chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],evm:!0},polygon:{chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],evm:!0},arbitrum:{chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],evm:!0},base:{chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],evm:!0},hyperevm:{chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],evm:!0},bsc:{chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],evm:!0},avalanche:{chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],evm:!0},optimism:{chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],evm:!0},abstract:{chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],evm:!0},stable:{chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],evm:!0}},Ri=new Map(Object.values(Be).map(e=>[e.chainId,e]))});import{Interface as Li,getAddress as Pi}from"ethers";function gt(e,t){try{return Pi(e).toLowerCase()}catch{throw new Error(`${t} must be a valid EVM address`)}}function $i(e){let t=String(e||"").trim();if(!/^0x[0-9a-fA-F]{64}$/.test(t))throw new Error("txHash must be a 32-byte hex transaction hash");return t.toLowerCase()}function yt(e){return e==null?null:Number.parseInt(String(e),16)}function Fi(e,{rpcUrl:t,env:r=process.env}={}){if(t)return t;let n=Hr(e,r);return n||Bi[Number(e)]||null}function qi(e){let t=String(e||""),r=t.toLowerCase();if(t!==t.trim()||!/^[a-zA-Z0-9_]+$/.test(t)||!Di.test(r))throw new Error(`evm-rpc: ${t} refused \u2014 @oracle-agent/oracle is prepare-only (read RPC only; no broadcast/sign)`);return r}function Ui(e){let t=new Error(e?.message||JSON.stringify(e));return t.code=e?.code,t}function Mi(e){if(e?.error)throw Ui(e.error);return e?.result}function ji(e,t,r){return`${e}
3
3
  ${t}
4
- ${JSON.stringify(r??[])}`}async function zs(e,t,r){return Le(e,{method:"POST",body:t,fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3,signal:r.signal})}async function Wt(e,t,r=[],n={}){let o=String(t||""),i=Ms(o),s=Fs(e,n);if(!s)throw new Error(`No RPC URL for chainId ${e} (set env from chain registry rpcEnv or pass rpcUrl)`);if(i==="eth_chainid"&&n.cacheChainId!==!1){let m=Bn.get(s);if(m!=null)return m}let c=n.dedupe!==!1&&!n.signal?Us(s,o,r):null;if(c&&ye.has(c))return ye.get(c);let p=(async()=>{let m=await zs(s,{jsonrpc:"2.0",id:1,method:t,params:r},n),l=Hs(m);return i==="eth_chainid"&&typeof l=="string"&&Bn.set(s,l),l})();return c&&(ye.set(c,p),p.finally(()=>{ye.get(c)===p&&ye.delete(c)}).catch(()=>{})),p}async function Dn(e={},t={}){let r=Number(e.chainId??t.chainId??1),n=Bs(e.txHash||e.hash||e.transactionHash),o=await Wt(r,"eth_getTransactionReceipt",[n],t);if(!o)return{ok:!1,chainId:r,txHash:n,status:"pending",receipt:null,reason:"receipt pending"};let i=zt(o.status),s=i===1,d=i===1?"success":i===0?"reverted":"unknown",c=s?null:d==="reverted"?"transaction reverted":"unknown receipt status",p=e.expectedTo?Ut(e.expectedTo,"expectedTo"):null,m=o.to?Ut(o.to,"receipt.to"):null;return p&&m!==p&&(s=!1,c=`to mismatch: expected ${p}, got ${m||"null"}`),{ok:s,chainId:r,txHash:n,status:d,reason:c,statusCode:i,to:m,from:o.from?Ut(o.from,"receipt.from"):null,blockNumber:zt(o.blockNumber),transactionIndex:zt(o.transactionIndex),logs:Array.isArray(o.logs)?o.logs:[],receipt:o}}var Fh,Ds,js,ye,Bn,Fn=a(()=>{$e();Qe();Fh=new $s(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);Ds={1:"https://ethereum.publicnode.com",137:"https://polygon-bor-rpc.publicnode.com",42161:"https://arbitrum-one-rpc.publicnode.com",8453:"https://base-rpc.publicnode.com",10:"https://optimism-rpc.publicnode.com",988:"https://rpc.stable.xyz",56:"https://bsc-rpc.publicnode.com",43114:"https://avalanche-c-chain-rpc.publicnode.com",999:"https://rpc.hyperliquid.xyz/evm",2741:"https://api.mainnet.abs.xyz",4663:"https://rpc.mainnet.chain.robinhood.com"};js=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;ye=new Map,Bn=new Map});function Vt(e,t){if(!e||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`${t} must be a plain object`);return e}function Kt(e,t="control input"){try{H(e,t),tn(e)}catch(r){throw new TypeError(`${t} contains secret or custody material: ${r.message}`)}return e}function be(e,{required:t=[],optional:r=[]}={},n="object"){Vt(e,n);let o=new Set([...t,...r]),i=Object.keys(e).filter(s=>!o.has(s));if(i.length)throw new TypeError(`${n} has unknown field ${i[0]}`);for(let s of t)if(!Object.hasOwn(e,s))throw new TypeError(`${n}.${s} is required`);return e}function Gt(e,t,r=200,{lower:n=!1}={}){if(typeof e!="string"||!e.trim()||e.length>r||Ws.test(e))throw new TypeError(`${t} must be non-empty control-free text up to ${r} characters`);let o=e.trim();return n?o.toLowerCase():o}function Ee(e,t,r=80){let n=Gt(e,t,r,{lower:!0});if(!/^[a-z0-9][a-z0-9._:-]*$/.test(n))throw new TypeError(`${t} must be a lowercase identifier`);return n}function ze(e,t,{positive:r=!1}={}){if(!Number.isSafeInteger(e)||e<0||r&&e===0)throw new TypeError(`${t} must be a ${r?"positive":"non-negative"} safe integer`);return e}function R(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))R(t);Object.freeze(e)}return e}var Ws,Jt=a(()=>{Fe();Ct();Ws=/[\u0000-\u001f\u007f]/});function jn({family:e,chainId:t},r="chain"){let n=Ee(e,`${r}.family`,40),o;if(n==="evm"){if(typeof t=="number")o=String(ze(t,`${r}.chainId`,{positive:!0}));else if(o=Gt(t,`${r}.chainId`,40),!/^[1-9][0-9]*$/.test(o))throw new TypeError(`${r}.chainId must be a positive decimal EVM chain id`)}else o=Ee(t,`${r}.chainId`,80);return{family:n,chainId:o}}function Gs(e,t="chain"){return be(e,{required:["family","chainId"]},t),R(jn(e,t))}function Mn(e,t="finality rule"){Kt(e,t),Vt(e,t);let r=e.rule;if(!Vs.includes(r))throw new TypeError(`${t}.rule must be confirmations, finalizedTag, or checkpoint`);let n=r==="confirmations"?"confirmations":r;be(e,{required:["family","chainId","rule",n]},t);let o=jn(e,t);return r==="confirmations"?{...o,rule:r,confirmations:ze(e.confirmations,`${t}.confirmations`,{positive:!0})}:{...o,rule:r,[n]:Ee(e[n],`${t}.${n}`,80)}}function Yt(e){if(!Array.isArray(e))throw new TypeError("finality policy rules must be an array");let t=e.map((n,o)=>Mn(n,`finality policy rule ${o}`)),r=new Set;for(let n of t){let o=`${n.family}\0${n.chainId}`;if(r.has(o))throw new TypeError(`duplicate finality rule for ${n.family}:${n.chainId}`);r.add(o)}return R({policyVersion:1,rules:t})}function Js(e){if(be(e,{required:["policyVersion","rules"]},"finality policy"),e.policyVersion!==1||!Array.isArray(e.rules))throw new TypeError("unsupported finality policy");return Yt(e.rules)}function qn(e,t){let r=Gs(t,"finality query"),o=Js(e).rules.find(i=>i.family===r.family&&i.chainId===r.chainId);return o?R({status:"KNOWN",...r,rule:o}):R({status:G.UNKNOWN,reason:"MISSING_FINALITY_RULE",...r,rule:null})}function Ys(e,t){if(e==null)return null;Kt(e,"finality evidence");let r=t.rule==="confirmations"?"confirmations":t.rule;if(be(e,{required:["status"],optional:[r]},"finality evidence"),!Ks.includes(e.status))throw new TypeError("finality evidence.status is unknown");let n={status:e.status};return e[r]!=null&&(n[r]=t.rule==="confirmations"?ze(e.confirmations,"finality evidence.confirmations",{positive:!0}):Ee(e[r],`finality evidence.${r}`,80)),n}function Hn(e,t){if(!e||e.status===G.UNKNOWN||e.rule==null)return R({status:G.UNKNOWN,final:!1,reason:"MISSING_FINALITY_RULE"});let r=Mn(e.rule??e,"resolved finality rule"),n=Ys(t,r);if(n==null)return R({status:G.UNKNOWN,final:!1,reason:"MISSING_FINALITY_EVIDENCE"});if(n.status!=="LIVE")return R({status:G.UNKNOWN,final:!1,reason:`${n.status}_EVIDENCE`});let o=!1;return r.rule==="confirmations"?o=n.confirmations!=null&&n.confirmations>=r.confirmations:r.rule==="finalizedTag"?o=n.finalizedTag===r.finalizedTag:o=n.checkpoint===r.checkpoint,R({status:o?G.FINAL:G.INCLUDED,final:o,reason:o?"PINNED_RULE_SATISFIED":"PINNED_RULE_NOT_SATISFIED",rule:r})}var Vs,G,Ks,Un=a(()=>{Jt();Vs=Object.freeze(["confirmations","finalizedTag","checkpoint"]),G=Object.freeze({UNKNOWN:"UNKNOWN",INCLUDED:"INCLUDED",FINAL:"FINAL"}),Ks=Object.freeze(["LIVE","STALE","UNKNOWN","UNAVAILABLE"])});function Zs(e){if(e===!0||e===1||e==="1")return"SUCCESS";if(e===!1||e===0||e==="0")return"FAIL";if(typeof e!="string")return"UNKNOWN";let t=e.trim().toUpperCase();return["SUCCESS","SUCCEEDED","OK","EXECUTED"].includes(t)?"SUCCESS":["FAIL","FAILED","FAILURE","REVERTED","REJECTED"].includes(t)?"FAIL":"UNKNOWN"}function zn(e){return typeof e=="string"&&["FAIL","FAILED","FAILURE","ORPHAN","ORPHANED","REVERTED"].includes(e.trim().toUpperCase())}function Zt(e){return e==null?e:Array.isArray(e)?e.map(Zt):xe(e)?Object.fromEntries(Object.keys(e).sort().map(t=>[t,Zt(e[t])])):String(e)}function Qs(e,t,r,n){let o=A(e.finalityEvidence,n?.finality,e.evidence),i=A(e.finalityPolicy,e.policy);try{return i==null&&xe(e.finalityRule)&&(i=Yt([{family:t,chainId:r,...e.finalityRule}])),i==null||t==null||r==null?{status:"UNKNOWN",final:!1,reason:"MISSING_FINALITY_RULE"}:Hn(qn(i,{family:t,chainId:r}),o)}catch{return{status:"UNKNOWN",final:!1,reason:"MALFORMED_FINALITY_EVIDENCE"}}}function O(e,t,r){r!=null&&(e[t]=r)}function ea(e){return e==null?null:String(e).trim().toLowerCase()}function Xt(...e){let t=e.map(ea).filter(Boolean);return t.length<=1||t.every(r=>r===t[0])}function Wn(e={}){if(!xe(e))throw new TypeError("verified receipt: input object required");let t=vt(e),r=A(t.actionReceipt,t.receipt),n=xe(r)?r:t,o=A(t.observation,t.chainObservation,t.observedReceipt),i=xe(o),s=A(t.txHash,n.txHash,n.transactionHash,o?.txHash,o?.transactionHash),d=A(t.family,n.family,n.chain?.family,o?.family,o?.chain?.family),c=A(t.chainId,n.chainId,n.chain?.chainId,o?.chainId,o?.chain?.chainId),p=!Xt(t.txHash,n.txHash,n.transactionHash,o?.txHash,o?.transactionHash)||!Xt(t.family,n.family,n.chain?.family,o?.family,o?.chain?.family)||!Xt(t.chainId,n.chainId,n.chain?.chainId,o?.chainId,o?.chain?.chainId),m=Qs(t,d,c,i&&!p?o:null),l=Zs(A(o?.receiptStatus,o?.executionStatus,o?.status)),f=A(t.reconciliationStatus,t.reconciliation?.status,o?.reconciliationStatus),u=A(t.finalityState,t.finalityEvidence?.status,t.evidence?.status,o?.finalityState),b="UNKNOWN";zn(f)||!p&&(i&&l==="FAIL"||zn(u))?b="FAIL":!p&&s&&i&&l==="SUCCESS"&&["INCLUDED","FINAL"].includes(m.status)&&(b="SUCCESS");let h={verifiedReceiptVersion:Xs,status:b};p&&(h.reason="REFERENCE_MISMATCH"),O(h,"txHash",s),O(h,"chain",A(t.chain,n.chain,o?.chain)),O(h,"family",d),O(h,"chainId",c),O(h,"block",A(o?.block,t.block)),O(h,"blockState",A(o?.blockState,o?.inclusionState)),h.finalityState=m.status,O(h,"confirmations",A(o?.confirmations,o?.finality?.confirmations,t.finalityEvidence?.confirmations,t.evidence?.confirmations)),O(h,"observedAt",A(o?.observedAt,t.observedAt)),O(h,"route",A(t.route,n.route)),O(h,"prepareHash",A(t.prepareHash,n.prepareHash)),O(h,"policyOutcome",A(t.policyOutcome,n.policyOutcome,n.policyChecks));let w=A(t.balanceChanges,o?.balanceChanges,o?.balances,n.balanceChanges,n.balances);return w!=null&&(h.balanceChanges=Zt(w)),O(h,"createdAt",A(t.createdAt,n.createdAt)),O(h,"submittedAt",A(t.submittedAt,n.submittedAt)),O(h,"finalizedAt",A(t.finalizedAt,o?.finalizedAt)),O(h,"timestamps",A(t.timestamps,n.timestamps,o?.timestamps)),R(h)}var Xs,Jh,A,xe,Vn=a(()=>{Fe();Un();Jt();Xs=1,Jh=Object.freeze(["SUCCESS","FAIL","UNKNOWN"]),A=(...e)=>e.find(t=>t!=null),xe=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype});var Gn={};Ae(Gn,{observeEvmReceipt:()=>Kn,verifyEvmReceipt:()=>na});function ra(e){if(e==null)return null;let t=typeof e=="number"?e:Number.parseInt(String(e),16);return Number.isSafeInteger(t)?t:null}async function Kn({txHash:e,chainId:t,rpcUrl:r},n={}){let o=String(e||"").trim().toLowerCase();if(!ta.test(o))throw new TypeError("observe receipt: txHash must be a 32-byte hash");let i=Number(t);if(!Number.isSafeInteger(i)||i<=0)throw new TypeError("observe receipt: chainId required");let s=n.transactionReceipt||Dn,d=n.rpcCall||Wt,c={...n.rpcOptions||{},...r?{rpcUrl:r}:{}},p;try{p=await s({txHash:o,chainId:i},c)}catch(u){return{observation:null,reason:`RPC_UNAVAILABLE: ${u.message}`}}if(!p||p.receipt==null)return{observation:null,reason:p?.reason||"receipt pending"};let m=null,l=p.blockNumber;if(Number.isSafeInteger(l))try{let u=ra(await d(i,"eth_blockNumber",[],c));u!=null&&u>=l&&(m=u-l+1)}catch{}let f={txHash:o,family:"evm",chainId:String(i),receiptStatus:p.status==="success"?"SUCCESS":p.status==="reverted"?"FAIL":"UNKNOWN",block:l==null?void 0:String(l),observedAt:new Date().toISOString(),finality:{status:"LIVE",...m==null?{}:{confirmations:m}}};return m!=null&&(f.confirmations=m),{observation:f,reason:null}}async function na({txHash:e,chainId:t,confirmations:r=1,rpcUrl:n},o={}){let{observation:i,reason:s}=await Kn({txHash:e,chainId:t,rpcUrl:n},o),d=Wn({txHash:String(e).trim().toLowerCase(),family:"evm",chainId:String(Number(t)),finalityRule:{rule:"confirmations",confirmations:r},...i?{observation:i}:{}});return{receipt:d,observed:!!i,final:d.finalityState==="FINAL",requiredConfirmations:r,reason:s}}var ta,Jn=a(()=>{Fn();Vn();ta=/^0x[0-9a-f]{64}$/});var Yn={};Ae(Yn,{classifyReceipt:()=>ae,configDir:()=>aa,firstHourReport:()=>Qt,probeReceiptModule:()=>la,probeReviewModule:()=>ca,venueMap:()=>We});import oa from"node:path";import{homedir as ia}from"node:os";function aa(e=process.env){return e.ORACLE_CONFIG_DIR||oa.join(ia(),".config","oracle")}function We({env:e=process.env,vault:t=null}={}){let r=t||ge(),n=[];for(let[o,i]of Object.entries(Oe)){let s=(i.rpcEnv||[]).some(c=>String(e[c]||"").trim()),d="prepare";i.evm?s&&(d="live"):d="unavailable",n.push({key:o,chainId:i.chainId,name:i.name,family:"evm",status:d,execute:!!(r.vaultExists&&r.armed&&!r.disarmed),note:s?"rpc configured":"public read/prepare; set RPC for live reads"})}return n.push({key:"solana",chainId:null,name:"Solana",family:"sol",status:"prepare",execute:!1,note:"Jupiter quote/prepare; local sol signer"},{key:"bitcoin",chainId:null,name:"Bitcoin",family:"btc",status:"prepare",execute:!1,note:"Esplora read; local btc signer"},{key:"hyperliquid-l1",chainId:null,name:"Hyperliquid L1",family:"data",status:"live",execute:!1,note:"data/prepare only \u2014 not an EVM signer family"},{key:"polymarket",chainId:null,name:"Polymarket",family:"data",status:"live",execute:!1,note:"data/prepare only \u2014 not a signer family"}),n}function Qt({env:e=process.env,model:t=$n(),vault:r=ge(),signerReachable:n=!1,quote:o=null,reviewAvailable:i=!1,receiptAvailable:s=!1}={}){let d=[],c=(u,b,h,w=null)=>d.push({id:u,status:b,detail:h,fix:w}),p=(()=>{let[u,b]=process.versions.node.split(".").map(Number);return u>20||u===20&&b>=19})();c("node",p?"ok":"fail",`node ${process.versions.node}`,p?null:"install node >= 20.19"),t?t.backend==="hermes"?c("model","warn","backend=hermes (opt-in attach)","oracle model --backend standalone"):c("model","ok",`${t.backend||"auto"} ${t.provider||""} ${t.model||""}`.trim()):c("model","fail","no model.json","oracle setup model"),r.vaultExists?r.disarmed?c("vault","warn","vault present, DISARMED","oracle signer (re-arm after confirm)"):c("vault",r.armed?"ok":"warn",r.armed?"present, armed":"present, not armed"):c("vault","fail","no local vault","oracle sign init");let m=e.ORACLE_SIGNER_HOST||"127.0.0.1";if(sa.has(m)?c("signer",n?"ok":"warn",n?`loopback ${m}:${e.ORACLE_SIGNER_PORT||9462}`:"loopback signer not reachable",n?null:"oracle signer"):c("signer","fail",`signer host ${m} is not loopback`,"unset ORACLE_SIGNER_HOST"),!o)c("quote","warn","quote not probed",null);else if(o.ok){let u=String(o.detail||"net quote returned");c("quote","ok",u.length>140?`${u.slice(0,140)}\u2026`:u)}else c("quote","warn",o.detail||"quote unavailable","check network / oracle data serve");c("review",i?"ok":"fail",i?"sign-time review renders decoded action, policy hits, approval deltas":"sign-time review module missing from this build",i?null:"reinstall @oracle-agent/oracle (src/control/sign-time-review.mjs)"),c("receipt",s?"ok":"fail",s?"oracle receipt verifies on-chain state (SUCCESS/FAIL/UNKNOWN, finality-pinned)":"verified-receipt observer missing from this build",s?null:"reinstall @oracle-agent/oracle (src/desk/observe-receipt.mjs)");let l=d.some(u=>u.status==="fail"),f=d.filter(u=>u.status==="ok").length;return{ok:!l,checks:d,firstRunScore:{ok:f,total:d.length,label:`${f}/${d.length} first-run hops green`},venues:We({env:e,vault:r})}}async function ca(){try{return typeof(await Promise.resolve().then(()=>(jt(),gn))).createSignTimeReview=="function"}catch{return!1}}async function la(){try{let e=await Promise.resolve().then(()=>(Jn(),Gn));return typeof e.observeReceipt=="function"||typeof e.default=="function"||Object.values(e).some(t=>typeof t=="function")}catch{return!1}}var sa,er=a(()=>{Qe();Ht();Pn();et();sa=new Set(["127.0.0.1","::1","localhost"])});var Zn={};Ae(Zn,{classifyReceipt:()=>ae,default:()=>fa,detailText:()=>Xn,firstHourReport:()=>Qt,probeQuote:()=>da,probeSigner:()=>ua,symbol:()=>Se,vaultStatus:()=>ge});async function ua(e=process.env){let t=e.ORACLE_SIGNER_HOST||"127.0.0.1",r=e.ORACLE_SIGNER_PORT||9462;try{return(await fetch(`http://${t}:${r}/status`,{signal:AbortSignal.timeout(1500)})).ok}catch{return!1}}function Se(e){let t=String(e??"?").replace(/[^\w.$-]/g,"");return t.length>12?`${t.slice(0,12)}...`:t||"?"}function Xn(e,t=120){let r=String(e??"").replace(/[\u0000-\u001f\u007f-\u009f]/g," ").replace(/\s+/g," ").trim();return r?r.length>t?`${r.slice(0,t)}...`:r:"quote failed"}async function da(){try{let e=await fetch("https://api.dexscreener.com/latest/dex/search?q=WETH%20USDC",{signal:AbortSignal.timeout(4e3)});if(!e.ok)return{ok:!1,detail:`dexscreener ${e.status}`};let r=(await e.json())?.pairs?.[0];return!r?.chainId||!r?.priceUsd?{ok:!1,detail:"no pair"}:{ok:!0,detail:`${Se(r.chainId)} ${Se(r.baseToken?.symbol)}/${Se(r.quoteToken?.symbol)} $${Se(r.priceUsd)}`}}catch(e){return{ok:!1,detail:Xn(e instanceof Error?e.message:"quote failed")}}}var fa,Qn=a(()=>{er();Ht();fa={name:"venues",summary:"label every shipped venue live / prepare / unavailable",group:"read",usage:"oracle venues [--json]",async run(e){let t=e.argv.includes("--json"),r=We();if(t)return process.stdout.write(`${JSON.stringify({venues:r},null,2)}
4
+ ${JSON.stringify(r??[])}`}async function Hi(e,t,r){return U(e,{method:"POST",body:t,fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3,signal:r.signal})}async function H(e,t,r=[],n={}){let o=String(t||""),i=qi(o),s=Fi(e,n);if(!s)throw new Error(`No RPC URL for chainId ${e} (set env from chain registry rpcEnv or pass rpcUrl)`);if(i==="eth_chainid"&&n.cacheChainId!==!1){let h=zr.get(s);if(h!=null)return h}let u=n.dedupe!==!1&&!n.signal?ji(s,o,r):null;if(u&&ge.has(u))return ge.get(u);let f=(async()=>{let h=await Hi(s,{jsonrpc:"2.0",id:1,method:t,params:r},n),l=Mi(h);return i==="eth_chainid"&&typeof l=="string"&&zr.set(s,l),l})();return u&&(ge.set(u,f),f.finally(()=>{ge.get(u)===f&&ge.delete(u)}).catch(()=>{})),f}async function Wr(e={},t={}){let r=Number(e.chainId??t.chainId??1),n=$i(e.txHash||e.hash||e.transactionHash),o=await H(r,"eth_getTransactionReceipt",[n],t);if(!o)return{ok:!1,chainId:r,txHash:n,status:"pending",receipt:null,reason:"receipt pending"};let i=yt(o.status),s=i===1,p=i===1?"success":i===0?"reverted":"unknown",u=s?null:p==="reverted"?"transaction reverted":"unknown receipt status",f=e.expectedTo?gt(e.expectedTo,"expectedTo"):null,h=o.to?gt(o.to,"receipt.to"):null;return f&&h!==f&&(s=!1,u=`to mismatch: expected ${f}, got ${h||"null"}`),{ok:s,chainId:r,txHash:n,status:p,reason:u,statusCode:i,to:h,from:o.from?gt(o.from,"receipt.from"):null,blockNumber:yt(o.blockNumber),transactionIndex:yt(o.transactionIndex),logs:Array.isArray(o.logs)?o.logs:[],receipt:o}}var tu,Bi,Di,ge,zr,z=c(()=>{$();wt();tu=new Li(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);Bi={1:"https://ethereum.publicnode.com",137:"https://polygon-bor-rpc.publicnode.com",42161:"https://arbitrum-one-rpc.publicnode.com",8453:"https://base-rpc.publicnode.com",10:"https://optimism-rpc.publicnode.com",988:"https://rpc.stable.xyz",56:"https://bsc-rpc.publicnode.com",43114:"https://avalanche-c-chain-rpc.publicnode.com",999:"https://rpc.hyperliquid.xyz/evm",2741:"https://api.mainnet.abs.xyz",4663:"https://rpc.mainnet.chain.robinhood.com"};Di=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;ge=new Map,zr=new Map});var bt=c(()=>{});var au,Fe=c(()=>{$();bt();au=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"})});var ye=c(()=>{});var ce=c(()=>{});var W=c(()=>{ye();ce()});var Wi,pu,L=c(()=>{Wi=300*1e3,pu=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});import{Interface as Vr,getAddress as wu,isAddress as gu}from"ethers";var St,xu,vu,xt=c(()=>{z();Fe();W();L();St={1:{name:"ethereum",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",weth:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",usdc:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},8453:{name:"base",quoter:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",router:"0x2626664c2603336E57B271c5C0b26F421741e481",weth:"0x4200000000000000000000000000000000000006",usdc:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"},42161:{name:"arbitrum",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",weth:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",usdc:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"},4663:{name:"robinhood",quoter:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",router:"0xcaf681a66d020601342297493863e78c959e5cb2",weth:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",usdc:"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"},999:{name:"hyperevm",weth:"0x5555555555555555555555555555555555555555",usdc:"0xB8CE59FC3717ada4C02eaDF9682A9e934F625ebb"},10:{name:"optimism",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",weth:"0x4200000000000000000000000000000000000006",usdc:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85"},56:{name:"bsc",quoter:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",router:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",weth:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",usdc:"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d"},137:{name:"polygon",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",weth:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",usdc:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"},43114:{name:"avalanche",quoter:"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F",router:"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE",weth:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",usdc:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"}},xu=new Vr(["function quoteExactInputSingle((address tokenIn, address tokenOut, uint256 amountIn, uint24 fee, uint160 sqrtPriceLimitX96) params) returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)","function quoteExactInput(bytes path, uint256 amountIn) returns (uint256 amountOut, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate)"]),vu=new Vr(["function exactInputSingle((address tokenIn,address tokenOut,uint24 fee,address recipient,uint256 amountIn,uint256 amountOutMinimum,uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)","function multicall(uint256 deadline,bytes[] data) payable returns (bytes[] results)"])});import{AbiCoder as Ki,Interface as vt,getAddress as Ou,isAddress as _u,keccak256 as Cu}from"ethers";var Pu,At,$u,Bu,Fu,Du,qu,It=c(()=>{z();Fe();W();L();Pu=Ki.defaultAbiCoder(),At={1:{name:"ethereum",poolManager:"0x000000000004444c5dc75cB358380D2e3dE08A90",quoter:"0x52f0e24d1c21c8a0cb1e5a5dd6198556bd9e1203",stateView:"0x7ffe42c4a5deea5b0fec41c94c136cf115597227",universalRouter:"0x66a9893cc07d91d95644aedd05d03f95e1dba8af",weth:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",usdc:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},10:{name:"optimism",poolManager:"0x9a13f98cb987694c9f086b1f5eb990eea8264ec3",quoter:"0x1f3131a13296fb91c90870043742c3cdbff1a8d7",stateView:"0xc18a3169788f4f75a170290584eca6395c75ecdb",universalRouter:"0x851116d9223fabed8e56c0e6b8ad0c31d98b3507",weth:"0x4200000000000000000000000000000000000006",usdc:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85"},56:{name:"bsc",poolManager:"0x28e2ea090877bf75740558f6bfb36a5ffee9e9df",quoter:"0x9f75dd27d6664c475b90e105573e550ff69437b0",stateView:"0xd13dd3d6e93f276fafc9db9e6bb47c1180aee0c4",universalRouter:"0x1906c1d672b88cd1b9ac7593301ca990f94eae07",weth:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",usdc:"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d"},137:{name:"polygon",poolManager:"0x67366782805870060151383f4bbff9dab53e5cd6",quoter:"0xb3d5c3dfc3a7aebff71895a7191796bffc2c81b9",stateView:"0x5ea1bd7974c8a611cbab0bdcafcb1d9cc9b3ba5a",universalRouter:"0x1095692a6237d83c6a72f3f5efedb9a670c49223",weth:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",usdc:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"},8453:{name:"base",poolManager:"0x498581fF718922c3f8e6A244956aF099B2652b2b",quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",stateView:"0xa3c0c9b65bad0b08107aa264b0f3db444b867a71",universalRouter:"0x6ff5693b99212da76ad316178a184ab56d299b43",weth:"0x4200000000000000000000000000000000000006",usdc:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"},42161:{name:"arbitrum",poolManager:"0x360e68faccca8ca495c1b759fd9eee466db9fb32",quoter:"0x3972c00f7ed4885e145823eb7c655375d275a1c5",stateView:"0x76fd297e2d437cd7f76d50f01afe6160f86e9990",universalRouter:"0xa51afafe0263b40edaef0df8781ea9aa03e381a3",weth:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",usdc:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"},43114:{name:"avalanche",poolManager:"0x06380c0e0912312b5150364b9dc4542ba0dbbc85",quoter:"0xbe40675bb704506a3c2ccfb762dcfd1e979845c2",stateView:"0xc3c9e198c735a4b97e3e683f391ccbdd60b69286",universalRouter:"0x94b75331ae8d42c1b61065089b7d48fe14aa73b7",weth:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",usdc:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"},4663:{name:"robinhood",poolManager:"0x8366a39cc670b4001a1121b8f6a443a643e40951",quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",stateView:"0xf3334192d15450cdd385c8b70e03f9a6bd9e673b",universalRouter:"0x8876789976dEcBfCbBbe364623C63652db8C0904",weth:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",usdc:"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"}},$u=new vt(["function quoteExactInputSingle(((address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey,bool zeroForOne,uint128 exactAmount,bytes hookData) params) returns (uint256 amountOut, uint256 gasEstimate)","function quoteExactOutputSingle(((address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey,bool zeroForOne,uint128 exactAmount,bytes hookData) params) returns (uint256 amountIn, uint256 gasEstimate)"]),Bu=new vt(["function execute(bytes commands,bytes[] inputs,uint256 deadline) payable"]),Fu=new vt(["function getSlot0(bytes32 poolId) view returns (uint160 sqrtPriceX96,int24 tick,uint24 protocolFee,uint24 lpFee)","function getLiquidity(bytes32 poolId) view returns (uint128 liquidity)"]),Du=Object.freeze([[13,"beforeInitialize"],[12,"afterInitialize"],[11,"beforeAddLiquidity"],[10,"afterAddLiquidity"],[9,"beforeRemoveLiquidity"],[8,"afterRemoveLiquidity"],[7,"beforeSwap"],[6,"afterSwap"],[5,"beforeDonate"],[4,"afterDonate"],[3,"beforeSwapReturnsDelta"],[2,"afterSwapReturnsDelta"],[1,"afterAddLiquidityReturnsDelta"],[0,"afterRemoveLiquidityReturnsDelta"]]),qu=(1n<<14n)-1n});var _t=c(()=>{});import{Contract as Xu,JsonRpcProvider as Qu}from"ethers";var Kr=c(()=>{});var rl,Ue=c(()=>{Kr();rl=Object.freeze({swap:5,bridge:5,perps:0,nft:0})});var Yr=c(()=>{$();W();_t();L();Ue()});var Jr=c(()=>{$();W();L();Ue()});var Me=c(()=>{});var Zr=c(()=>{$();W();Me();L()});var Cl,en=c(()=>{Cl=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"})});import{TypedDataEncoder as Pl,getAddress as $l,isAddress as Bl}from"ethers";var Xi,Hl,Qi,zl,Ct=c(()=>{$();W();en();_t();L();Xi=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),Hl=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"}),Qi=Object.freeze({Order:[{name:"sellToken",type:"address"},{name:"buyToken",type:"address"},{name:"receiver",type:"address"},{name:"sellAmount",type:"uint256"},{name:"buyAmount",type:"uint256"},{name:"validTo",type:"uint32"},{name:"appData",type:"bytes32"},{name:"feeAmount",type:"uint256"},{name:"kind",type:"string"},{name:"partiallyFillable",type:"bool"},{name:"sellTokenBalance",type:"string"},{name:"buyTokenBalance",type:"string"}]}),zl=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]})});function Ee(e){let t=e?.transactionHash||e?.hash||e?.txid||null;return t?{happened:!0,hash:String(t),note:null}:{happened:!1,hash:null,note:"no transaction hash \u2014 the action did not succeed"}}var Bt=c(()=>{});var dn=c(()=>{});var fn=c(()=>{});import{isAddress as up}from"ethers";var Ft=c(()=>{W();ye();ce()});import{Interface as Sa,isAddress as hp}from"ethers";var bp,pn=c(()=>{Ft();ye();ce();bp=new Sa(["function approve(address spender,uint256 amount) returns (bool)"])});import{Interface as xa,isAddress as xp}from"ethers";var kp,Op,mn=c(()=>{Ft();ye();ce();kp=new xa(["function approve(address spender,uint256 amount) returns (bool)"]),Op=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"})});var Z=c(()=>{});import{Interface as va,MaxUint256 as Pp,isAddress as $p,keccak256 as Bp,toUtf8Bytes as Fp}from"ethers";var Hp,ee=c(()=>{fn();pn();mn();Z();ce();Hp=new va(["function approve(address spender,uint256 amount) returns (bool)"])});var We=c(()=>{ee()});import{Address as Gp,NETWORK as Yp,OutScript as Jp,RawTx as Xp,SigHash as Qp,TEST_NETWORK as Zp,Transaction as em}from"@scure/btc-signer";var Ut=c(()=>{});import{createHash as Aa}from"node:crypto";import{base58 as om}from"@scure/base";import{getCompiledTransactionMessageDecoder as am}from"@solana/transaction-messages";var hn,sm,Mt=c(()=>{hn=e=>Aa("sha256").update(`global:${e}`).digest().subarray(0,8).toString("hex"),sm=new Map([[hn("route"),{name:"route",prefixBytes:0}],[hn("shared_accounts_route"),{name:"shared_accounts_route",prefixBytes:1}]])});var wn=c(()=>{$()});var gn=c(()=>{wn()});var ym,bm,Ht=c(()=>{Z();gn();ym=Object.freeze({"perp-order":"order","hip3-order":"order","hip4-order":"order","perp-bracket":"order","perp-cancel":"cancel","perp-leverage":"leverage","perp-isolated-margin":"margin","builder-fee-approval":"approveBuilder","hype-stake-deposit":"stake","hype-stake-withdraw":"unstake","hype-delegate":"delegate","hype-undelegate":"delegate"}),bm=Object.freeze({"perp-order":"order","hip3-order":"order","hip4-order":"order","perp-bracket":"order","perp-cancel":"cancel","perp-leverage":"updateLeverage","perp-isolated-margin":"updateIsolatedMargin","builder-fee-approval":"approveBuilderFee","hype-stake-deposit":"cDeposit","hype-stake-withdraw":"cWithdraw","hype-delegate":"tokenDelegate","hype-undelegate":"tokenDelegate"})});var xm,zt=c(()=>{Z();xm="0x"+"00".repeat(32)});var Ia,Om,Wt=c(()=>{zt();Z();Ia=Object.freeze([["salt","uint256"],["maker","address"],["signer","address"],["tokenId","uint256"],["makerAmount","uint256"],["takerAmount","uint256"],["side","uint8"],["signatureType","uint8"],["timestamp","uint256"],["metadata","bytes32"],["builder","bytes32"]]),Om=Object.freeze(Ia.map(e=>e[0]))});var Ve=c(()=>{Z()});import{TypedDataEncoder as Rm,getAddress as Lm,isAddress as Pm}from"ethers";var ka,Oa,Sn=c(()=>{L();ka=Object.freeze({1:"0x111111125421cA6dc452d289314280a0f8842A65",8453:"0x111111125421cA6dc452d289314280a0f8842A65",42161:"0x111111125421cA6dc452d289314280a0f8842A65",10:"0x111111125421cA6dc452d289314280a0f8842A65",137:"0x111111125421cA6dc452d289314280a0f8842A65",56:"0x111111125421cA6dc452d289314280a0f8842A65"}),Oa=Object.freeze({Order:[{name:"salt",type:"uint256"},{name:"maker",type:"address"},{name:"receiver",type:"address"},{name:"makerAsset",type:"address"},{name:"takerAsset",type:"address"},{name:"makingAmount",type:"uint256"},{name:"takingAmount",type:"uint256"},{name:"makerTraits",type:"uint256"}]})});import{TypedDataEncoder as Dm,getAddress as qm}from"ethers";var jm,Vt=c(()=>{Sn();Ct();jm=Object.freeze(["https://limit-orders.1inch.io","https://api.1inch.dev/orderbook"])});import{Interface as vn}from"ethers";var La,oh,Pa,ih,ah,sh,ch,$a,uh,Ke=c(()=>{ee();W();L();We();Ut();Mt();Ht();Wt();Ve();Vt();La=new Set(["evm","evm-swap","evm-bridge","evm-nft","evm-order","btc","sol","hl","poly","lighter"]),oh=Object.freeze({swap:5,bridge:5,perps:0,nft:0,mint:0,transfer:0,approve:0,delegate:0,identity:0,order:0,cancel:0,leverage:0,margin:0,approveBuilder:0,stake:0,unstake:0}),Pa=Object.freeze({"0x04e45aaf":{provider:"uniswap-v3",action:"swap",layout:"router02-exact-input-single"},"0x414bf389":{provider:"uniswap-v3",action:"swap",layout:"swap-router-exact-input-single"},"0xc04b8d59":{provider:"uniswap-v3",action:"swap",layout:"exact-input-deadline"},"0xb858183f":{provider:"uniswap-v3",action:"swap",layout:"exact-input"},"0x5ae401dc":{provider:"uniswap-v3",action:"swap",layout:"multicall-deadline"},"0xa026383e":{provider:"aerodrome",action:"swap",layout:"aerodrome-exact-input-single"},"0x7b939232":{provider:"across-v3",action:"bridge",layout:"across-deposit-v3"}}),ih=Object.freeze({"0x161ac21f":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-public"},"0xc2f6663a":{provider:"opensea-nft",action:"mint",layout:"seadrop-mint-allowlist"}}),ah=new vn(["function buySpecificNFT(uint256 tokenId,uint256 maxCost) payable","function sellNFT(uint256 tokenId,uint256 minPayout) payable"]),sh=new vn(["function mintAllowList(address nftContract,address feeRecipient,address minterIfNotPayer,uint256 quantity,(uint80 mintPrice,uint48 maxTotalMintableByWallet,uint48 startTime,uint48 endTime,uint48 dropStageIndex,uint32 maxTokenSupplyForStage,uint16 feeBps,bool restrictFeeRecipients) mintParams,bytes32[] proof) payable"]),ch=Object.freeze({"0xa0712d68":{provider:"nft-mint",action:"mint",layout:"mint-quantity"},"0x1249c58b":{provider:"nft-mint",action:"mint",layout:"mint-no-args"},"0x2db11544":{provider:"nft-mint",action:"mint",layout:"mint-quantity"},"0xefef39a1":{provider:"nft-mint",action:"mint",layout:"mint-quantity"},"0xa6f2ae3a":{provider:"nft-mint",action:"mint",layout:"mint-no-args"}}),$a=Object.freeze([...La]),uh=Object.freeze({...Pa})});import{encode as fh}from"@msgpack/msgpack";import{keccak256 as mh,verifyTypedData as hh}from"ethers";var wh,gh,Kt=c(()=>{wh=Object.freeze({name:"Exchange",version:"1",chainId:1337,verifyingContract:"0x0000000000000000000000000000000000000000"}),gh=Object.freeze({Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]})});var Gt=c(()=>{Ve()});import{ed25519 as Ih}from"@noble/curves/ed25519.js";import{base58 as Oh}from"@scure/base";import{RawTx as Ch,SigHash as Th,Transaction as Nh}from"@scure/btc-signer";import{Transaction as Lh,keccak256 as Ph,verifyTypedData as $h}from"ethers";var Yt=c(()=>{Kt();Gt()});import{base58 as jh}from"@scure/base";var Ge=c(()=>{Ke();We();ee();Yt()});var In=c(()=>{Ge();Ke()});import{wordlists as Da}from"ethers";function ja(e){let t=String(e).trim().toLowerCase().split(/\s+/).filter(Boolean);return Ma.has(t.length)&&t.every(r=>Da.en.getWordIndex(r)>=0)}function Va(e){let t=kn(e);return Wa.has(t)||za.test(t)}function kn(e){return String(e).replace(/[^a-z0-9]/gi,"").toLowerCase()}function Ka(e){let t=kn(e);return[...qa].some(r=>t.includes(r))}function Ga(e,t,r){if(typeof t=="string"){if(Ua.some(n=>n.test(t))||ja(t))throw new xe(r);if(Ha.test(t)&&!Va(e))throw new xe(r)}}function Jt(e,t="$",r=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string")return Ga(r,e,t),e;if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError(`action receipt: non-finite number at ${t}`);return e}if(typeof e=="bigint")return e.toString();if(Array.isArray(e))return e.map((o,i)=>Jt(o,`${t}[${i}]`,r));if(typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`action receipt: JSON-like value required at ${t}`);let n={};for(let o of Object.keys(e).sort()){let i=`${t}.${o}`;if(Ka(o))throw new xe(i);e[o]!==void 0&&(n[o]=Jt(e[o],i,o))}return n}function Xt(e){return Jt(e)}var qa,Ua,Ma,Ha,za,Wa,xe,Ye=c(()=>{qa=new Set(["privatekey","privkey","secretkey","seedphrase","seed","mnemonic","passphrase","password","keystore","keymaterial","wif","xprv","xpriv","bearer","authorization","signature","apikey","credential"]),Ua=[/\b[5KL][1-9A-HJ-NP-Za-km-z]{50,51}\b/,/\bxprv[0-9A-Za-z]{50,}\b/],Ma=new Set([12,15,18,21,24]);Ha=/^\s*(?:0x)?[0-9a-fA-F]{64}\s*$/,za=/(hash|digest|root|salt|nonce|proof|commitment|sig|id)(?:e?s)?$/i,Wa=new Set(["calldata","data","publickey","pubkey","message","payload","input","extradata"]);xe=class extends Error{constructor(t){super(`action receipt refused: secret-bearing field at ${t}`),this.name="ActionReceiptSecretError",this.code="ACTION_RECEIPT_SECRET"}}});import{wordlists as nw}from"ethers";var On,iw,le=c(()=>{Ye();On=64*1024,iw=32*1024});var Xa,cw,uw,Xe=c(()=>{le();Xa=["schemaVersion","buildVersion","recordType","execution","custody"],cw=[...Xa,"recordHash"],uw=Object.freeze({signed:new Set(["workflow.signed","legacy.signed"]),submitted:new Set(["workflow.submitted","legacy.broadcast"]),finalized:new Set(["workflow.finalized"]),reorged:new Set(["workflow.reorged"]),orphaned:new Set(["workflow.orphaned"]),compensating:new Set(["workflow.compensating"]),compensated:new Set(["workflow.compensated"])})});var Qa,Bn,mw,rr=c(()=>{le();Xe();Qa=Object.freeze(["draft","checked","approval","signed","submitted","finalized","reorged","orphaned","compensating","compensated","failed","cancelled"]),Bn=Object.freeze(["workflow.drafted","workflow.checked","workflow.approval_requested","workflow.approval_granted","workflow.signed","workflow.submitted","workflow.finalized","workflow.reorged","workflow.orphaned","workflow.compensating","workflow.compensated","workflow.failed","workflow.cancelled","workflow.annotated"]),mw=new Set(Bn)});var os,Fn=c(()=>{le();rr();os=64*1024*1024});var Sw,xw,vw,Dn=c(()=>{Sw=Object.freeze(["chainId","agentAddress","accountAddress","actions","targets","maxValueWei","maxGasWei","maxSlippageBps","expiresAt","nonce","revocationKey"]),xw=Object.freeze(["read","simulate"]),vw=1440*60});function nr(e){let t=String(e),r=t.toLowerCase().replace(/[\s._-]+/g,"");return is.test(t)||as.includes(r)}function ss(e){return e.replace(/"([A-Za-z0-9_-]+)"\s*:\s*"(?:0x)?([0-9a-fA-F]{64})"/g,(t,r)=>Un.includes(String(r).toLowerCase().replace(/[_-]/g,""))?`"${r}":"<hex64>"`:t)}function Mn(e){let t;try{t=JSON.stringify(e)}catch(o){throw new G("$",`unserializable-payload: ${String(o?.message||o)}`)}if(t===void 0)return"null";let r=ss(t);for(let{rule:o,re:i}of qn)if(i.test(r))throw new G("$<serialized>",o);if(/(?:^|[^0-9a-fA-Fx])0x[0-9a-fA-F]{64}(?![0-9a-fA-F])/.test(r))throw new G("$<serialized>","raw-32-byte-hex-embedded");return JSON.parse(t,(o,i)=>{if(o&&nr(o))throw new G(`$<serialized>.${o}`,"forbidden-key-name");return i}),t}function X(e,t="$",r=new Set,n=""){if(e==null)return e;if(typeof e=="string"){let o=Un.includes(String(n).toLowerCase().replace(/[_-]/g,""));for(let{rule:i,re:s}of qn)if(!(o&&i.startsWith("raw-32-byte-hex"))&&s.test(e))throw new G(t,i);return e}if(typeof e!="object"||r.has(e)||(r.add(e),ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e;if(e instanceof Map){for(let[o,i]of e.entries()){if(typeof o=="string"&&nr(o))throw new G(`${t}[${JSON.stringify(o)}]`,"forbidden-key-name");X(o,`${t}[key]`,r),X(i,`${t}[${String(o)}]`,r)}return e}if(e instanceof Set){let o=0;for(let i of e.values())X(i,`${t}[${o++}]`,r);return e}if(Array.isArray(e))return e.forEach((o,i)=>X(o,`${t}[${i}]`,r)),e;for(let[o,i]of Object.entries(e)){if(nr(o))throw new G(`${t}.${o}`,"forbidden-key-name");X(i,`${t}.${o}`,r,o)}return e}var G,is,as,qn,Un,or=c(()=>{Dn();G=class extends Error{constructor(t,r){super(`secret material must never appear in a public API object (at ${t}, rule: ${r})`),this.name="SecretLeakError",this.path=t,this.rule=r}},is=/(private[_-]?key|secret|bearer|keystore|mnemonic|seed[_-]?phrase|passphrase|password|api[_-]?key|access[_-]?token|auth[_-]?token|session[_-]?token|signer[_-]?url|signature)/i,as=Object.freeze(["privkey","wif","xprv","seed"]);qn=Object.freeze([{rule:"raw-32-byte-hex-key",re:/^0x[0-9a-fA-F]{64}$/},{rule:"raw-32-byte-hex-bare",re:/^[0-9a-fA-F]{64}$/},{rule:"extended-private-key",re:/\b(?:xprv|tprv|yprv|zprv)[1-9A-HJ-NP-Za-km-z]{107}\b/},{rule:"bitcoin-wif",re:/\b[59KLc][1-9A-HJ-NP-Za-km-z]{50,51}\b/},{rule:"bip39-mnemonic",re:/\b(?:[a-z]{3,8}\s+){11,23}[a-z]{3,8}\b/},{rule:"bearer-token",re:/bearer\s+[A-Za-z0-9._~+/=-]+/i},{rule:"pem-private-key",re:/-----BEGIN[A-Z ]*PRIVATE KEY-----/},{rule:"keystore-path",re:/keystore/i},{rule:"signer-url",re:/https?:\/\/\S*sign/i},{rule:"authorization-header",re:/authorization\s*:/i}]),Un=Object.freeze(["grantid","id","hash","sha256","sha256hex","checksum","txhash","transactionhash","blockhash","digest","userophash","commithash","prevhash","intenthash","canonicalhash","payloadhash","requestid"])});var ir,Pw,jn=c(()=>{or();ir=Object.freeze(["intent","quote_comparison","simulation","prepared","approval","signed","broadcast","settlement","balance_delta","position"]),Pw=Object.freeze(Object.fromEntries(ir.map((e,t)=>[e,Object.freeze(t+1<ir.length?[ir[t+1]]:[])])))});var cs,Hn=c(()=>{jn();le();Xe();cs=Object.freeze({intent:"draft",quote_comparison:"draft",simulation:"draft",prepared:"checked",approval:"approval",signed:"signed",broadcast:"submitted",settlement:"finalized",balance_delta:"compensated",position:"compensated"})});var zn=c(()=>{le();Xe();rr();Fn();Hn()});var ls,ds,fs,yg,bg,Eg,Sg,xg,ps,vg,Wn=c(()=>{ls=Object.freeze(["owner","operator","agent","viewer"]),ds=Object.freeze(["tenant","config","policy","grant","workflow","trade","receipt","audit","telemetry","context","lifecycle"]),fs=Object.freeze({read:"read",create:"create",update:"update",delete:"delete",manage:"manage",prepare:"prepare",cancel:"cancel",export:"export",approve:"approve"}),yg=Object.freeze(["owner"]),bg=Object.freeze({ALLOW_ROLE_PERMISSION:"allow.role_permission",DENY_MISSING_CONTEXT:"deny.missing_context",DENY_INVALID_CONTEXT:"deny.invalid_context",DENY_INVALID_REQUEST:"deny.invalid_request",DENY_UNKNOWN_RESOURCE:"deny.unknown_resource",DENY_UNKNOWN_ACTION:"deny.unknown_action",DENY_UNBOUND_OBJECT:"deny.unbound_object",DENY_TENANT_MISMATCH:"deny.tenant_mismatch",DENY_RESOURCE_MISMATCH:"deny.resource_mismatch",DENY_ROLE_PERMISSION:"deny.role_permission",DENY_POLICY_NOT_APPROVER:"deny.policy_not_approver"}),Eg=new Set(ls),Sg=new Set(ds),xg=new Set(Object.values(fs)),ps=Object.freeze({owner:Object.freeze(["tenant:read","tenant:manage","config:read","config:manage","policy:read","policy:manage","grant:read","grant:create","grant:update","grant:delete","grant:manage","workflow:read","workflow:create","workflow:update","workflow:delete","workflow:cancel","workflow:approve","trade:read","trade:prepare","receipt:read","receipt:export","audit:read","audit:export","telemetry:read","telemetry:create","telemetry:export","context:read","context:create","context:update","context:delete","context:manage","context:export","lifecycle:read","lifecycle:create","lifecycle:update","lifecycle:delete","lifecycle:manage","lifecycle:approve","lifecycle:export"]),operator:Object.freeze(["tenant:read","config:read","policy:read","grant:read","workflow:read","workflow:create","workflow:update","workflow:cancel","trade:read","trade:prepare","receipt:read","audit:read","telemetry:read","telemetry:create","context:read","context:create","context:update","context:delete","lifecycle:read","lifecycle:create","lifecycle:update","lifecycle:manage"]),agent:Object.freeze(["tenant:read","config:read","policy:read","grant:read","workflow:read","workflow:create","workflow:update","trade:read","trade:prepare","receipt:read","telemetry:create","context:read","context:create","context:update","lifecycle:read"]),viewer:Object.freeze(["tenant:read","config:read","grant:read","workflow:read","trade:read","receipt:read","audit:read","telemetry:read","context:read","lifecycle:read"])}),vg=Object.freeze(Object.fromEntries(Object.entries(ps).map(([e,t])=>[e,Object.freeze([...t])])))});var ms,hs,ws,Og,_g,Cg,Tg,Ng,Rg,ar=c(()=>{Wn();ms=Object.freeze(["succeeded","denied","invalid","failed","cancelled","timed_out","unavailable","skipped"]),hs=Object.freeze(["workflow","task","intent","plan","run","event","eval"]),ws=Object.freeze(["taskId","intentId","planId","runId","eventId"]),Og=Object.freeze({maxAttributes:24,maxKeyLength:48,maxStringLength:256,maxArrayLength:8}),_g=new Set(ms),Cg=new Set(hs),Tg=new Set(ws),Ng=Object.freeze(["authorization","bearer","cookie","credential","password","passphrase","secret","token","privatekey","privkey","seed","mnemonic","keystore","signature","prompt","systemmessage","usermessage","assistantmessage","rawtransaction","signedtransaction","serializedtransaction","transactionbytes","calldata","callbytes","inputdata"]),Rg=Object.freeze({taskId:"x-oracle-task-id",intentId:"x-oracle-intent-id",planId:"x-oracle-plan-id",runId:"x-oracle-run-id",eventId:"x-oracle-event-id"})});var Dg,Vn=c(()=>{zn();ar();Dg=Object.freeze({"workflow.cancelled":"cancelled","workflow.failed":"failed"})});var zg,Kn=c(()=>{ar();zg=32*1024*1024});var Vg,Kg,Gg,de=c(()=>{Vg=Object.freeze({N:1<<17,r:8,p:1}),Kg=256*1024*1024,Gg=16*1024});var Jg,Gn=c(()=>{Jg=Object.freeze({1:{name:"ethereum",mode:"mempool-private",endpoints:["https://rpc.flashbots.net/fast","https://rpc.mevblocker.io"]},8453:{name:"base",mode:"sequencer",endpoints:["https://mainnet-sequencer.base.org"]},10:{name:"optimism",mode:"sequencer",endpoints:["https://mainnet-sequencer.optimism.io"]},42161:{name:"arbitrum",mode:"sequencer",endpoints:["https://arb1-sequencer.arbitrum.io/rpc"]},56:{name:"bsc",mode:"mempool-private",endpoints:["https://rpc.48.club","https://bsc.rpc.blxrbdn.com"]},137:{name:"polygon",mode:"mempool-private",endpoints:["https://polygon-bor-rpc.publicnode.com"]},43114:{name:"avalanche",mode:"public-only",endpoints:[]},999:{name:"hyperevm",mode:"public-only",endpoints:[]}})});import{homedir as sr}from"node:os";import{join as cr}from"node:path";var Yn,gs,ey,Jn=c(()=>{Yn=process.env.ORACLE_PUBLIC_DESKTOP==="1",gs=Yn?process.env.ORACLE_CONFIG_DIR||cr(sr(),".config","oracle"):cr(sr(),".config","oracle"),ey=Yn?gs:cr(sr(),".config","mad-desk")});var iy,ay,sy,Xn=c(()=>{Jn();iy="0".repeat(64),ay=Object.freeze({PREPARE:"exec.prepare",SIGN:"exec.sign",BROADCAST:"exec.broadcast",POLICY_REJECT:"policy.reject",AUTH_GRANT:"auth.grant",AUTH_OK:"auth.verify.ok",AUTH_FAIL:"auth.verify.fail"}),sy=Promise.resolve()});var ur=c(()=>{Xn();Z();de();Ge()});var Zn=c(()=>{});var ro={};Re(ro,{SIGN_TIME_REVIEW_VERSION:()=>ys,SignTimeReviewSecretError:()=>ve,createSignTimeReview:()=>to});function lr(e,t="$",r=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string"){let o=e.trim().split(/\s+/);if(vs.test(e)||As.has(o.length)&&o.every(i=>/^[a-z]+$/i.test(i)))throw new ve(t);return e}if(typeof e=="bigint")return e.toString();if(typeof e=="number"){if(!Number.isSafeInteger(e))throw new TypeError(`sign-time review: safe integer required at ${t}`);return e}if(Array.isArray(e))return e.map((o,i)=>lr(o,`${t}[${i}]`,r));te(e,t);let n={};for(let o of Object.keys(e).sort()){let i=o.replace(/[^a-z0-9]/gi,"");if(xs.test(i))throw new ve(`${t}.${o}`);e[o]!==void 0&&(n[o]=lr(e[o],`${t}.${o}`,o))}return n}function te(e,t){if(e==null||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`sign-time review: ${t} must be a plain object`);return e}function Ae(e,t){if(e==null||e==="")throw new TypeError(`sign-time review: ${t} required`);return e}function fe(e,t){let r=String(Ae(e,t)).toLowerCase();if(!bs.test(r))throw new TypeError(`sign-time review: ${t} must be an EVM address`);return r}function Y(e,t,{positive:r=!1}={}){try{let n=BigInt(Ae(e,t));if(n<0n||r&&n===0n)throw new Error;return n.toString()}catch{throw new TypeError(`sign-time review: ${t} must be an unsigned integer`)}}function dr(e,t){if(typeof e!="string"||e.length===0||e.length>500||e!==e.trim())throw new TypeError(`sign-time review: ${t} must be non-empty text`);return e}function eo(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))eo(t);Object.freeze(e)}return e}function Is(e,t){if(typeof e=="boolean")return{passed:e,reason:e?"passed":"failed"};te(e,t);let r=e.passed??e.ok??e.allowed;if(typeof r!="boolean")throw new TypeError(`sign-time review: ${t} needs a boolean result`);let n=e.reason??e.message??e.name??(r?"passed":"failed");return{...e,passed:r,reason:dr(String(n),`${t}.reason`)}}function ks(e){if(!Array.isArray(e))throw new TypeError("sign-time review: policyChecks must be an array");let t=e.map((n,o)=>Is(n,`policyChecks[${o}]`)),r=t.filter(n=>!n.passed);return{checks:t,passed:t.length-r.length,failed:r.length,reasons:r.map(n=>n.reason)}}function Os(e){if(e==null)return null;if(te(e,"simulation"),typeof e.status!="string"||!["ok","success","failed","error","unavailable","unknown"].includes(e.status))throw new TypeError("sign-time review: simulation.status is invalid");if(e.willRevert!==!0&&e.willRevert!==!1&&e.willRevert!==null)throw new TypeError("sign-time review: simulation.willRevert must be boolean or null");let t={status:e.status,willRevert:e.willRevert??null,summary:dr(String(e.summary??"simulation result recorded"),"simulation.summary")};return e.gasEstimate!=null&&(t.gasEstimate=Y(e.gasEstimate,"simulation.gasEstimate")),e.gasLimit!=null&&(t.gasLimit=Y(e.gasLimit,"simulation.gasLimit")),t}function _s(e){if(e==null)return null;if(!Array.isArray(e)||e.length===0)throw new TypeError("sign-time review: assetDeltas must be a non-empty array");return e.map((t,r)=>{te(t,`assetDeltas[${r}]`);let n=Y(t.before,`assetDeltas[${r}].before`),o=Y(t.after,`assetDeltas[${r}].after`),i=(BigInt(o)-BigInt(n)).toString(),s;try{s=t.delta==null?i:BigInt(t.delta).toString()}catch{throw new TypeError(`sign-time review: assetDeltas[${r}].delta must be an integer`)}if(s!==i)throw new TypeError(`sign-time review: assetDeltas[${r}].delta does not match before/after`);return{...t,asset:dr(String(Ae(t.asset??t.token,`assetDeltas[${r}].asset`)),`assetDeltas[${r}].asset`),before:n,after:o,delta:s}})}function Cs(e){if(e==null)return[];if(!Array.isArray(e))throw new TypeError("sign-time review: approvalDeltas must be an array");return e.map((t,r)=>{te(t,`approvalDeltas[${r}]`);let n=Y(t.amount??t.after,`approvalDeltas[${r}].amount`);if(t.revokeLike!=null&&typeof t.revokeLike!="boolean")throw new TypeError(`sign-time review: approvalDeltas[${r}].revokeLike must be boolean`);return{token:fe(t.token,`approvalDeltas[${r}].token`),spender:fe(t.spender,`approvalDeltas[${r}].spender`),owner:fe(t.owner,`approvalDeltas[${r}].owner`),amount:n,revokeLike:t.revokeLike??BigInt(n)===0n}})}function to(e={}){te(e,"input");let t=lr(e),r=t.tx==null?t:te(t.tx,"tx"),n=Y(t.chainId??r.chainId,"chainId",{positive:!0}),o=fe(t.account??t.from??r.from,"account/from"),i=fe(t.destination??t.to??r.to,"destination/to"),s=String(Ae(t.prepareHash,"prepareHash")).toLowerCase();if(!Ss.test(s))throw new TypeError("sign-time review: prepareHash must be a 32-byte hash");let p=t.route??t.venue;if(p==null)throw new TypeError("sign-time review: route/venue required");let u=t.decodedCalldata??t.decodedAction;if(u==null)throw new TypeError("sign-time review: decodedCalldata or decodedAction required");let f=String(Ae(t.calldata??t.data??r.data,"calldata/data")).toLowerCase();if(!Es.test(f))throw new TypeError("sign-time review: calldata/data must be even-length hex");let h=t.policyChecks!==void 0&&t.policyChecks!==null,l=ks(h?t.policyChecks:[]),m=Os(t.simulation),d=_s(t.assetDeltas),b=Cs(t.approvalDeltas),y=t.allowlistHits??[];if(!Array.isArray(y))throw new TypeError("sign-time review: allowlistHits must be an array");let w=m?.willRevert===!0||["failed","error"].includes(m?.status),k=m!=null&&m.willRevert===!1&&["ok","success"].includes(m.status),N=w||l.failed>0?"BLOCKED":k&&h&&l.checks.length>0&&d!=null?"READY":"UNKNOWN",S=typeof u=="string"?u:u.method??u.action??u.type??"transaction",g=`${N}: review ${S} on chain ${n}; policy ${l.passed} passed, ${l.failed} failed; ${d?.length??0} asset delta${d?.length===1?"":"s"}; local signature required`,x={reviewVersion:1,status:N,requiresLocalSignature:!0,signingLocal:!0,custody:"none",execution:"review-only",chainId:n,account:o,from:o,route:p,venue:t.venue??(typeof p=="string"?p:p.venue??p.provider??null),destination:i,to:i,...t.spender==null?{}:{spender:fe(t.spender,"spender")},prepareHash:s,...t.decodedCalldata!==void 0?{decodedCalldata:t.decodedCalldata}:{decodedAction:t.decodedAction},calldata:f,data:f,selector:f.length>=10?f.slice(0,10):null,value:Y(t.value??r.value??0,"value"),...(t.gasEstimate??r.gasEstimate)==null?{}:{gasEstimate:Y(t.gasEstimate??r.gasEstimate,"gasEstimate")},...(t.gasLimit??r.gasLimit)==null?{}:{gasLimit:Y(t.gasLimit??r.gasLimit,"gasLimit")},simulation:m,policyChecks:l,allowlistHits:y,assetDeltas:d,approvalDeltas:b,summary:g};return eo(x)}var ys,bs,Es,Ss,xs,vs,As,ve,fr=c(()=>{ys=1,bs=/^0x[0-9a-f]{40}$/,Es=/^0x(?:[0-9a-f]{2})*$/,Ss=/^(?:0x)?[0-9a-f]{64}$/,xs=/(privatekey|privkey|secretkey|seedphrase|mnemonic|passphrase|password|keystore|keymaterial|wif|xprv|xpriv|bearer|authorization|signature|apikey|credential)/i,vs=/\b(?:[5KL][1-9A-HJ-NP-Za-km-z]{50,51}|xprv[0-9A-Za-z]{50,})\b/,As=new Set([12,15,18,21,24]),ve=class extends Error{constructor(t){super(`sign-time review refused: secret-bearing field at ${t}`),this.name="SignTimeReviewSecretError",this.code="SIGN_TIME_REVIEW_SECRET"}}});import{readFileSync as gy,readdirSync as yy,existsSync as Ts}from"node:fs";import{dirname as Ns,join as Ie}from"node:path";import{fileURLToPath as Rs}from"node:url";function Ls(){let e=[Ie(ke,"descriptors"),Ie(ke,"clear-sign","descriptors"),Ie(ke,"..","clear-sign","descriptors"),Ie(ke,"..","..","clear-sign","descriptors"),Ie(ke,"..","..","..","clear-sign","descriptors")];for(let t of e)if(Ts(t))return t;return e[0]}var ke,xy,vy,no=c(()=>{ee();ke=Ns(Rs(import.meta.url));xy=Ls(),vy=(1n<<256n)-1n});var oo=c(()=>{fr();ee();no()});import{Wallet as Ny}from"ethers";import{base58 as Ly}from"@scure/base";import{ed25519 as $y}from"@noble/curves/ed25519.js";import{NETWORK as Fy,TEST_NETWORK as Dy,WIF as qy,p2wpkh as Uy}from"@scure/btc-signer";import{pubECDSA as jy}from"@scure/btc-signer/utils.js";var io=c(()=>{});var Wy,Vy,Ky,Gy,Yy,Jy,Xy,Qy,Zy,e0,t0,ao=c(()=>{ur();Wy=Object.freeze(["spot-limit-create","spot-limit-cancel","spot-order-status"]),Vy=Object.freeze(["binance","bybit","okx","coinbase"]),Ky=Object.freeze({binance:"https://api.binance.com",bybit:"https://api.bybit.com",okx:"https://openapi.okx.com",coinbase:"https://api.exchange.coinbase.com"}),Gy=Object.freeze({binance:"/api/v3",bybit:"/v5/order",okx:"/api/v5/trade",coinbase:"/orders"}),Yy=Object.freeze(["version","surface","kind","venue","credentialRef","symbol","base","quote","side","baseSize","limitPrice","maxQuoteNotional","timeInForce","clientOrderId","expiresAtMs","venueOrderId","nonce","grantId","artifactHash"]),Jy=Object.freeze(["market-create","withdraw","transfer","subaccount","leverage","futures","margin","convert","api-key"]),Xy=Object.freeze(["url","host","path","method","headers","signature","apiKey","apiSecret","passphrase","privateKey","redirect","proxy"]),Qy=Object.freeze(["ccxt","binance-api-node","node-binance-api","coinbase-advanced-node","@okx-dex/okx-dex-sdk","bybit-api"]),Zy=Object.freeze({perOrderQuote:"sealed-owner-policy",dailyGrossQuote:"sealed-owner-policy",scope:Object.freeze(["per-order","UTC-day","account","venue","quote"]),envelopeFieldIsNotCeiling:!0}),e0=Object.freeze({binanceRecvWindowMs:5e3,bybitWindowMs:5e3,maxLocalSkewMs:2e3}),t0=Object.freeze({perSecond:1,perMinute:30,bind:"tighter"})});var so=c(()=>{de()});var Bs,co,Ze=c(()=>{Bs=Object.freeze({binance:Object.freeze({create:["POST","/api/v3/order"],cancel:["DELETE","/api/v3/order"],status:["GET","/api/v3/order"]}),bybit:Object.freeze({create:["POST","/v5/order/create"],cancel:["POST","/v5/order/cancel"],status:["GET","/v5/order/realtime"]}),okx:Object.freeze({create:["POST","/api/v5/trade/order"],cancel:["POST","/api/v5/trade/cancel-order"],status:["GET","/api/v5/trade/order"]}),coinbase:Object.freeze({create:["POST","/orders"],cancel:["DELETE","/orders/{order_id}"],status:["GET","/orders/{order_id}"]})}),co=Object.freeze({binance:"https://api.binance.com",bybit:"https://api.bybit.com",okx:"https://openapi.okx.com",coinbase:"https://api.exchange.coinbase.com"})});var uo=c(()=>{Ze()});var d0,lo=c(()=>{Ze();uo();d0=256*1024});var fo=c(()=>{Ze();lo()});var po=c(()=>{de()});import R from"node:path";import Fs from"node:os";import{createHash as Ds,randomBytes as ob}from"node:crypto";import{Interface as pr,keccak256 as ab}from"ethers";import{Transaction as cb}from"@scure/btc-signer";import{ed25519 as lb}from"@noble/curves/ed25519.js";function mo(e){let t=process.env.ORACLE_SIGNER_STATE_DIR||R.join(process.env.XDG_STATE_HOME||R.join(Fs.homedir(),".local","state"),"oracle"),r=Ds("sha256").update(R.resolve(e)).digest("hex").slice(0,16);return{vault:R.join(e,"vault.json"),policy:R.join(e,"signer-policy.json"),policyKey:R.join(e,"policy-integrity-key"),policyAnchor:R.join(t,`signer-policy-${r}.high-water`),ledger:R.join(e,"signer-ledger.json"),ledgerAnchor:R.join(t,`signer-ledger-${r}.high-water`),cexOrders:R.join(e,"cex-orders.json"),cexOrdersAnchor:R.join(t,`cex-orders-${r}.high-water`),token:R.join(e,"signer-token"),lock:R.join(t,`signer-${r}.lock`),workflowLedger:R.join(e,"workflow-events.jsonl")}}var Ub,Mb,jb,ho=c(()=>{In();Vn();Kn();Ge();de();Gn();ur();Zn();ee();oo();Ke();We();Yt();Ht();Wt();Ve();Gt();zt();Kt();Ut();Mt();Vt();io();ao();so();fo();po();Ub=new pr(["function collection() view returns (address)","function token() view returns (address)","function robinhoodSwapFeeWei() view returns (uint256)","function quoteSpecificBuy(uint256 tokenId) view returns (uint256 totalCost,uint256 baseCost,uint256 fee,uint256 protocolFee,bool available)","function quoteSellNFT() view returns (uint256 netPayout,uint256 grossPayout,uint256 fee,uint256 protocolFee)","function inventory(uint256 tokenId) view returns (bool)","function buySpecificNFT(uint256 tokenId,uint256 maxCost) payable","function sellNFT(uint256 tokenId,uint256 minPayout) payable"]),Mb=new pr(["function decimals() view returns (uint8)","function allowance(address owner,address spender) view returns (uint256)"]),jb=new pr(["function ownerOf(uint256 tokenId) view returns (address)","function getApproved(uint256 tokenId) view returns (address)","function isApprovedForAll(address owner,address operator) view returns (bool)"])});import mr from"node:fs";import wo from"node:path";import{homedir as qs}from"node:os";function Us(){return process.env.ORACLE_CONFIG_DIR||wo.join(qs(),".config","oracle")}function Oe(){let e=mo(wo.join(Us(),"signer")),t=mr.existsSync(e.vault),r=mr.existsSync(e.lock),n=t?r?"disarmed":"armed-owner-confirmed":"inert-no-key";return{vaultExists:t,policyConfigured:mr.existsSync(e.policy),armed:t&&!r,disarmed:r,capabilities:{swap:n,bridge:n},autonomous:!1,note:"Keys stay on this machine. Exact confirmation is required before any broadcast."}}var Zb,hr=c(()=>{Bt();dn();ho();de();Zb=Object.freeze([{type:"function",function:{name:"vault_status",description:"Read local Oracle vault/signer readiness. Never returns key material.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"signer_status",description:"Ping the loopback signer. Fails closed if it is not running.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"signer_pending",description:"List pending local-signer artifacts. Read-only. Does not approve, sign, or broadcast.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"signer_queue",description:"Queue a prepared unsigned artifact on the loopback signer. Does not broadcast.",parameters:{type:"object",properties:{artifact:{type:"object"}},required:["artifact"],additionalProperties:!1}}},{type:"function",function:{name:"signer_ack",description:"Execute one pending artifact through the armed local signer (same path as Telegram Allow). Fails if the signer is not running or disarmed. Never holds keys.",parameters:{type:"object",properties:{id:{type:"string"},digest:{type:"string"}},additionalProperties:!1}}},{type:"function",function:{name:"signer_deny",description:"Drop one pending local-signer artifact. Nothing signed.",parameters:{type:"object",properties:{id:{type:"string"},digest:{type:"string"}},additionalProperties:!1}}},{type:"function",function:{name:"signer_execute",description:"Broadcast one already-confirmed local artifact. Requires a one-use confirmationNonce from the local signer TTY confirm. Cannot mint confirmation itself.",parameters:{type:"object",properties:{artifact:{type:"object"},confirmationNonce:{type:"string",minLength:32,maxLength:128}},required:["artifact","confirmationNonce"],additionalProperties:!1}}},{type:"function",function:{name:"signer_disarm",description:"Global kill switch. Stops the local signer from broadcasting.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"receipt_report",description:"Receipt or it did not happen. Requires transactionHash/hash/txid.",parameters:{type:"object",properties:{receipt:{type:"object"},transactionHash:{type:"string"},hash:{type:"string"},txid:{type:"string"}},additionalProperties:!1}}},{type:"function",function:{name:"watch_create",description:"Create an alert-only watch. Never execute.",parameters:{type:"object",properties:{chain:{type:"string"},token:{type:"string"},condition:{type:"string"},note:{type:"string"}},required:["chain","token","condition"],additionalProperties:!1}}},{type:"function",function:{name:"watch_list",description:"List local alert-only watches.",parameters:{type:"object",properties:{},additionalProperties:!1}}},{type:"function",function:{name:"portfolio_snapshot",description:"How to read the one portfolio snapshot. knownUsd is incomplete if a provider is missing.",parameters:{type:"object",properties:{},additionalProperties:!1}}}])});function et(e){return String(e||"").trim()||void 0}function js(e,{required:t=!1}={}){let r=et(e)?.toLowerCase();if(!r){if(t)throw new Error("model provider is required");return}if(!Ms.has(r))throw new Error(`unsupported provider: ${r}`);return r}function Hs(e,{required:t=!1}={}){let r=et(e);if(!r){if(t)throw new Error("model is required");return}if(r.includes("..")||r.startsWith("/")||!/^[a-zA-Z0-9._:/-]{1,200}$/.test(r))throw new Error("invalid model id");return r}function zs(e){let t=et(e);if(!t||t.length>2048)throw new Error("invalid custom base URL");let r;try{r=new URL(t)}catch{throw new Error("invalid custom base URL")}let n=r.hostname.toLowerCase().replace(/^\[|\]$/g,""),o=n==="localhost"||n==="127.0.0.1"||n==="::1";if(r.protocol!=="https:"&&!(r.protocol==="http:"&&o)||r.username||r.password||r.search||r.hash)throw new Error("custom base URL must use HTTPS or loopback HTTP without credentials, query, or fragment");return r.toString().replace(/\/+$/,"")}function go({provider:e,model:t,baseUrl:r}={},{requireModel:n=!1}={}){let o=js(e),i=Hs(t,{required:n});if(o==="custom")return{provider:o,...i?{model:i}:{},baseUrl:zs(r)};if(et(r))throw new Error("baseUrl is only supported for the custom provider");return{...o?{provider:o}:{},...i?{model:i}:{}}}var Ms,yo=c(()=>{Ms=new Set(["openrouter","openai","anthropic","xai","deepseek","gemini","kimi","mistral","nous","qwen","glm","local","ollama","custom","anthropic-oauth","openai-codex","xai-oauth"])});import bo from"node:fs";import Ws from"node:path";function Ks(){return Ws.join(ie(),"model.json")}function pe(e){return String(e||"").trim()||void 0}function Gs(e={}){let t=pe(e.backend)?.toLowerCase()||"auto",r=go({provider:e.provider,model:e.model,baseUrl:e.baseUrl},{requireModel:t==="standalone"}),n=pe(e.apiKeyEnv),o=Number.parseInt(String(e.contextLength||""),10),i=pe(e.reasoningEffort),s=pe(e.computeHost||e.remoteHost),p=pe(e.computeUser||e.remoteUser),u=pe(e.computePath||e.remotePath);if(!Vs.has(t))throw new Error(`unsupported backend: ${t}`);if(process.env.ORACLE_PUBLIC_DESKTOP==="1"&&["remote","arch"].includes(t))throw new Error("remote compute backends are disabled in the public desktop");if(n&&!/^[A-Z][A-Z0-9_]*$/.test(n))throw new Error("api key env must be an uppercase environment variable name");if(t==="remote"&&!s)throw new Error("remote backend requires computeHost");return{backend:t,...r,...n?{apiKeyEnv:n}:{},...Number.isFinite(o)&&o>0?{contextLength:o}:{},...i?{reasoningEffort:i}:{},...s?{computeHost:s}:{},...p?{computeUser:p}:{},...u?{computePath:u}:{}}}function Eo(){let e=Ks();if(!bo.existsSync(e))return null;try{return Gs(JSON.parse(bo.readFileSync(e,"utf8")))}catch{return null}}var Vs,So=c(()=>{Pe();yo();Vs=new Set(["auto","standalone","hermes","remote","arch"])});function wr(e,t){if(!e||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`${t} must be a plain object`);return e}function gr(e,t="control input"){try{X(e,t),Mn(e)}catch(r){throw new TypeError(`${t} contains secret or custody material: ${r.message}`)}return e}function _e(e,{required:t=[],optional:r=[]}={},n="object"){wr(e,n);let o=new Set([...t,...r]),i=Object.keys(e).filter(s=>!o.has(s));if(i.length)throw new TypeError(`${n} has unknown field ${i[0]}`);for(let s of t)if(!Object.hasOwn(e,s))throw new TypeError(`${n}.${s} is required`);return e}function yr(e,t,r=200,{lower:n=!1}={}){if(typeof e!="string"||!e.trim()||e.length>r||Ys.test(e))throw new TypeError(`${t} must be non-empty control-free text up to ${r} characters`);let o=e.trim();return n?o.toLowerCase():o}function Ce(e,t,r=80){let n=yr(e,t,r,{lower:!0});if(!/^[a-z0-9][a-z0-9._:-]*$/.test(n))throw new TypeError(`${t} must be a lowercase identifier`);return n}function tt(e,t,{positive:r=!1}={}){if(!Number.isSafeInteger(e)||e<0||r&&e===0)throw new TypeError(`${t} must be a ${r?"positive":"non-negative"} safe integer`);return e}function B(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))B(t);Object.freeze(e)}return e}var Ys,br=c(()=>{Ye();or();Ys=/[\u0000-\u001f\u007f]/});function xo({family:e,chainId:t},r="chain"){let n=Ce(e,`${r}.family`,40),o;if(n==="evm"){if(typeof t=="number")o=String(tt(t,`${r}.chainId`,{positive:!0}));else if(o=yr(t,`${r}.chainId`,40),!/^[1-9][0-9]*$/.test(o))throw new TypeError(`${r}.chainId must be a positive decimal EVM chain id`)}else o=Ce(t,`${r}.chainId`,80);return{family:n,chainId:o}}function Qs(e,t="chain"){return _e(e,{required:["family","chainId"]},t),B(xo(e,t))}function vo(e,t="finality rule"){gr(e,t),wr(e,t);let r=e.rule;if(!Js.includes(r))throw new TypeError(`${t}.rule must be confirmations, finalizedTag, or checkpoint`);let n=r==="confirmations"?"confirmations":r;_e(e,{required:["family","chainId","rule",n]},t);let o=xo(e,t);return r==="confirmations"?{...o,rule:r,confirmations:tt(e.confirmations,`${t}.confirmations`,{positive:!0})}:{...o,rule:r,[n]:Ce(e[n],`${t}.${n}`,80)}}function Er(e){if(!Array.isArray(e))throw new TypeError("finality policy rules must be an array");let t=e.map((n,o)=>vo(n,`finality policy rule ${o}`)),r=new Set;for(let n of t){let o=`${n.family}\0${n.chainId}`;if(r.has(o))throw new TypeError(`duplicate finality rule for ${n.family}:${n.chainId}`);r.add(o)}return B({policyVersion:1,rules:t})}function Zs(e){if(_e(e,{required:["policyVersion","rules"]},"finality policy"),e.policyVersion!==1||!Array.isArray(e.rules))throw new TypeError("unsupported finality policy");return Er(e.rules)}function Ao(e,t){let r=Qs(t,"finality query"),o=Zs(e).rules.find(i=>i.family===r.family&&i.chainId===r.chainId);return o?B({status:"KNOWN",...r,rule:o}):B({status:re.UNKNOWN,reason:"MISSING_FINALITY_RULE",...r,rule:null})}function ec(e,t){if(e==null)return null;gr(e,"finality evidence");let r=t.rule==="confirmations"?"confirmations":t.rule;if(_e(e,{required:["status"],optional:[r]},"finality evidence"),!Xs.includes(e.status))throw new TypeError("finality evidence.status is unknown");let n={status:e.status};return e[r]!=null&&(n[r]=t.rule==="confirmations"?tt(e.confirmations,"finality evidence.confirmations",{positive:!0}):Ce(e[r],`finality evidence.${r}`,80)),n}function Io(e,t){if(!e||e.status===re.UNKNOWN||e.rule==null)return B({status:re.UNKNOWN,final:!1,reason:"MISSING_FINALITY_RULE"});let r=vo(e.rule??e,"resolved finality rule"),n=ec(t,r);if(n==null)return B({status:re.UNKNOWN,final:!1,reason:"MISSING_FINALITY_EVIDENCE"});if(n.status!=="LIVE")return B({status:re.UNKNOWN,final:!1,reason:`${n.status}_EVIDENCE`});let o=!1;return r.rule==="confirmations"?o=n.confirmations!=null&&n.confirmations>=r.confirmations:r.rule==="finalizedTag"?o=n.finalizedTag===r.finalizedTag:o=n.checkpoint===r.checkpoint,B({status:o?re.FINAL:re.INCLUDED,final:o,reason:o?"PINNED_RULE_SATISFIED":"PINNED_RULE_NOT_SATISFIED",rule:r})}var Js,re,Xs,ko=c(()=>{br();Js=Object.freeze(["confirmations","finalizedTag","checkpoint"]),re=Object.freeze({UNKNOWN:"UNKNOWN",INCLUDED:"INCLUDED",FINAL:"FINAL"}),Xs=Object.freeze(["LIVE","STALE","UNKNOWN","UNAVAILABLE"])});function rc(e){if(e===!0||e===1||e==="1")return"SUCCESS";if(e===!1||e===0||e==="0")return"FAIL";if(typeof e!="string")return"UNKNOWN";let t=e.trim().toUpperCase();return["SUCCESS","SUCCEEDED","OK","EXECUTED"].includes(t)?"SUCCESS":["FAIL","FAILED","FAILURE","REVERTED","REJECTED"].includes(t)?"FAIL":"UNKNOWN"}function Oo(e){return typeof e=="string"&&["FAIL","FAILED","FAILURE","ORPHAN","ORPHANED","REVERTED"].includes(e.trim().toUpperCase())}function xr(e){return e==null?e:Array.isArray(e)?e.map(xr):Te(e)?Object.fromEntries(Object.keys(e).sort().map(t=>[t,xr(e[t])])):String(e)}function nc(e,t,r,n){let o=A(e.finalityEvidence,n?.finality,e.evidence),i=A(e.finalityPolicy,e.policy);try{return i==null&&Te(e.finalityRule)&&(i=Er([{family:t,chainId:r,...e.finalityRule}])),i==null||t==null||r==null?{status:"UNKNOWN",final:!1,reason:"MISSING_FINALITY_RULE"}:Io(Ao(i,{family:t,chainId:r}),o)}catch{return{status:"UNKNOWN",final:!1,reason:"MALFORMED_FINALITY_EVIDENCE"}}}function T(e,t,r){r!=null&&(e[t]=r)}function oc(e){return e==null?null:String(e).trim().toLowerCase()}function Sr(...e){let t=e.map(oc).filter(Boolean);return t.length<=1||t.every(r=>r===t[0])}function _o(e={}){if(!Te(e))throw new TypeError("verified receipt: input object required");let t=Xt(e),r=A(t.actionReceipt,t.receipt),n=Te(r)?r:t,o=A(t.observation,t.chainObservation,t.observedReceipt),i=Te(o),s=A(t.txHash,n.txHash,n.transactionHash,o?.txHash,o?.transactionHash),p=A(t.family,n.family,n.chain?.family,o?.family,o?.chain?.family),u=A(t.chainId,n.chainId,n.chain?.chainId,o?.chainId,o?.chain?.chainId),f=!Sr(t.txHash,n.txHash,n.transactionHash,o?.txHash,o?.transactionHash)||!Sr(t.family,n.family,n.chain?.family,o?.family,o?.chain?.family)||!Sr(t.chainId,n.chainId,n.chain?.chainId,o?.chainId,o?.chain?.chainId),h=nc(t,p,u,i&&!f?o:null),l=rc(A(o?.receiptStatus,o?.executionStatus,o?.status)),m=A(t.reconciliationStatus,t.reconciliation?.status,o?.reconciliationStatus),d=A(t.finalityState,t.finalityEvidence?.status,t.evidence?.status,o?.finalityState),b="UNKNOWN";Oo(m)||!f&&(i&&l==="FAIL"||Oo(d))?b="FAIL":!f&&s&&i&&l==="SUCCESS"&&["INCLUDED","FINAL"].includes(h.status)&&(b="SUCCESS");let y={verifiedReceiptVersion:tc,status:b};f&&(y.reason="REFERENCE_MISMATCH"),T(y,"txHash",s),T(y,"chain",A(t.chain,n.chain,o?.chain)),T(y,"family",p),T(y,"chainId",u),T(y,"block",A(o?.block,t.block)),T(y,"blockState",A(o?.blockState,o?.inclusionState)),y.finalityState=h.status,T(y,"confirmations",A(o?.confirmations,o?.finality?.confirmations,t.finalityEvidence?.confirmations,t.evidence?.confirmations)),T(y,"observedAt",A(o?.observedAt,t.observedAt)),T(y,"route",A(t.route,n.route)),T(y,"prepareHash",A(t.prepareHash,n.prepareHash)),T(y,"policyOutcome",A(t.policyOutcome,n.policyOutcome,n.policyChecks));let w=A(t.balanceChanges,o?.balanceChanges,o?.balances,n.balanceChanges,n.balances);return w!=null&&(y.balanceChanges=xr(w)),T(y,"createdAt",A(t.createdAt,n.createdAt)),T(y,"submittedAt",A(t.submittedAt,n.submittedAt)),T(y,"finalizedAt",A(t.finalizedAt,o?.finalizedAt)),T(y,"timestamps",A(t.timestamps,n.timestamps,o?.timestamps)),B(y)}var tc,wE,A,Te,Co=c(()=>{Ye();ko();br();tc=1,wE=Object.freeze(["SUCCESS","FAIL","UNKNOWN"]),A=(...e)=>e.find(t=>t!=null),Te=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype});var No={};Re(No,{observeEvmReceipt:()=>To,verifyEvmReceipt:()=>sc});function ac(e){if(e==null)return null;let t=typeof e=="number"?e:Number.parseInt(String(e),16);return Number.isSafeInteger(t)?t:null}async function To({txHash:e,chainId:t,rpcUrl:r},n={}){let o=String(e||"").trim().toLowerCase();if(!ic.test(o))throw new TypeError("observe receipt: txHash must be a 32-byte hash");let i=Number(t);if(!Number.isSafeInteger(i)||i<=0)throw new TypeError("observe receipt: chainId required");let s=n.transactionReceipt||Wr,p=n.rpcCall||H,u={...n.rpcOptions||{},...r?{rpcUrl:r}:{}},f;try{f=await s({txHash:o,chainId:i},u)}catch(d){return{observation:null,reason:`RPC_UNAVAILABLE: ${d.message}`}}if(!f||f.receipt==null)return{observation:null,reason:f?.reason||"receipt pending"};let h=null,l=f.blockNumber;if(Number.isSafeInteger(l))try{let d=ac(await p(i,"eth_blockNumber",[],u));d!=null&&d>=l&&(h=d-l+1)}catch{}let m={txHash:o,family:"evm",chainId:String(i),receiptStatus:f.status==="success"?"SUCCESS":f.status==="reverted"?"FAIL":"UNKNOWN",block:l==null?void 0:String(l),observedAt:new Date().toISOString(),finality:{status:"LIVE",...h==null?{}:{confirmations:h}}};return h!=null&&(m.confirmations=h),{observation:m,reason:null}}async function sc({txHash:e,chainId:t,confirmations:r=1,rpcUrl:n},o={}){let{observation:i,reason:s}=await To({txHash:e,chainId:t,rpcUrl:n},o),p=_o({txHash:String(e).trim().toLowerCase(),family:"evm",chainId:String(Number(t)),finalityRule:{rule:"confirmations",confirmations:r},...i?{observation:i}:{}});return{receipt:p,observed:!!i,final:p.finalityState==="FINAL",requiredConfirmations:r,reason:s}}var ic,Ro=c(()=>{z();Co();ic=/^0x[0-9a-f]{64}$/});var Lo={};Re(Lo,{classifyReceipt:()=>Ee,configDir:()=>dc,firstHourReport:()=>vr,probeReceiptModule:()=>pc,probeReviewModule:()=>fc,venueMap:()=>rt});import cc from"node:path";import{homedir as uc}from"node:os";function dc(e=process.env){return e.ORACLE_CONFIG_DIR||cc.join(uc(),".config","oracle")}function rt({env:e=process.env,vault:t=null}={}){let r=t||Oe(),n=[];for(let[o,i]of Object.entries(Be)){let s=(i.rpcEnv||[]).some(u=>String(e[u]||"").trim()),p="prepare";i.evm?s&&(p="live"):p="unavailable",n.push({key:o,chainId:i.chainId,name:i.name,family:"evm",status:p,execute:!!(r.vaultExists&&r.armed&&!r.disarmed),note:s?"rpc configured":"public read/prepare; set RPC for live reads"})}return n.push({key:"solana",chainId:null,name:"Solana",family:"sol",status:"prepare",execute:!1,note:"Jupiter quote/prepare; local sol signer"},{key:"bitcoin",chainId:null,name:"Bitcoin",family:"btc",status:"prepare",execute:!1,note:"Esplora read; local btc signer"},{key:"hyperliquid-l1",chainId:null,name:"Hyperliquid L1",family:"data",status:"live",execute:!1,note:"data/prepare only \u2014 not an EVM signer family"},{key:"polymarket",chainId:null,name:"Polymarket",family:"data",status:"live",execute:!1,note:"data/prepare only \u2014 not a signer family"}),n}function vr({env:e=process.env,model:t=Eo(),vault:r=Oe(),signerReachable:n=!1,quote:o=null,reviewAvailable:i=!1,receiptAvailable:s=!1}={}){let p=[],u=(d,b,y,w=null)=>p.push({id:d,status:b,detail:y,fix:w}),f=(()=>{let[d,b]=process.versions.node.split(".").map(Number);return d>20||d===20&&b>=19})();u("node",f?"ok":"fail",`node ${process.versions.node}`,f?null:"install node >= 20.19"),t?t.backend==="hermes"?u("model","warn","backend=hermes (opt-in attach)","oracle model --backend standalone"):u("model","ok",`${t.backend||"auto"} ${t.provider||""} ${t.model||""}`.trim()):u("model","fail","no model.json","oracle setup model"),r.vaultExists?r.disarmed?u("vault","warn","vault present, DISARMED","oracle signer (re-arm after confirm)"):u("vault",r.armed?"ok":"warn",r.armed?"present, armed":"present, not armed"):u("vault","fail","no local vault","oracle sign init");let h=e.ORACLE_SIGNER_HOST||"127.0.0.1";if(lc.has(h)?u("signer",n?"ok":"warn",n?`loopback ${h}:${e.ORACLE_SIGNER_PORT||9462}`:"loopback signer not reachable",n?null:"oracle signer"):u("signer","fail",`signer host ${h} is not loopback`,"unset ORACLE_SIGNER_HOST"),!o)u("quote","warn","quote not probed",null);else if(o.ok){let d=String(o.detail||"net quote returned");u("quote","ok",d.length>140?`${d.slice(0,140)}\u2026`:d)}else u("quote","warn",o.detail||"quote unavailable","check network / oracle data serve");u("review",i?"ok":"fail",i?"sign-time review renders decoded action, policy hits, approval deltas":"sign-time review module missing from this build",i?null:"reinstall @oracle-agent/oracle (src/control/sign-time-review.mjs)"),u("receipt",s?"ok":"fail",s?"oracle receipt verifies on-chain state (SUCCESS/FAIL/UNKNOWN, finality-pinned)":"verified-receipt observer missing from this build",s?null:"reinstall @oracle-agent/oracle (src/desk/observe-receipt.mjs)");let l=p.some(d=>d.status==="fail"),m=p.filter(d=>d.status==="ok").length;return{ok:!l,checks:p,firstRunScore:{ok:m,total:p.length,label:`${m}/${p.length} first-run hops green`},venues:rt({env:e,vault:r})}}async function fc(){try{return typeof(await Promise.resolve().then(()=>(fr(),ro))).createSignTimeReview=="function"}catch{return!1}}async function pc(){try{let e=await Promise.resolve().then(()=>(Ro(),No));return typeof e.observeReceipt=="function"||typeof e.default=="function"||Object.values(e).some(t=>typeof t=="function")}catch{return!1}}var lc,Ar=c(()=>{wt();hr();So();Bt();lc=new Set(["127.0.0.1","::1","localhost"])});var $o={};Re($o,{classifyReceipt:()=>Ee,default:()=>wc,detailText:()=>Po,firstHourReport:()=>vr,probeQuote:()=>hc,probeSigner:()=>mc,symbol:()=>Ne,vaultStatus:()=>Oe});async function mc(e=process.env){let t=e.ORACLE_SIGNER_HOST||"127.0.0.1",r=e.ORACLE_SIGNER_PORT||9462;try{return(await fetch(`http://${t}:${r}/status`,{signal:AbortSignal.timeout(1500)})).ok}catch{return!1}}function Ne(e){let t=String(e??"?").replace(/[^\w.$-]/g,"");return t.length>12?`${t.slice(0,12)}...`:t||"?"}function Po(e,t=120){let r=String(e??"").replace(/[\u0000-\u001f\u007f-\u009f]/g," ").replace(/\s+/g," ").trim();return r?r.length>t?`${r.slice(0,t)}...`:r:"quote failed"}async function hc(){try{let e=await fetch("https://api.dexscreener.com/latest/dex/search?q=WETH%20USDC",{signal:AbortSignal.timeout(4e3)});if(!e.ok)return{ok:!1,detail:`dexscreener ${e.status}`};let r=(await e.json())?.pairs?.[0];return!r?.chainId||!r?.priceUsd?{ok:!1,detail:"no pair"}:{ok:!0,detail:`${Ne(r.chainId)} ${Ne(r.baseToken?.symbol)}/${Ne(r.quoteToken?.symbol)} $${Ne(r.priceUsd)}`}}catch(e){return{ok:!1,detail:Po(e instanceof Error?e.message:"quote failed")}}}var wc,Bo=c(()=>{Ar();hr();wc={name:"venues",summary:"label every shipped venue live / prepare / unavailable",group:"read",usage:"oracle venues [--json]",async run(e){let t=e.argv.includes("--json"),r=rt();if(t)return process.stdout.write(`${JSON.stringify({venues:r},null,2)}
5
5
  `),0;for(let n of r)process.stdout.write(`${n.status.padEnd(12)} ${n.key.padEnd(16)} ${n.name} exec=${n.execute?"local":"no"}
6
- `);return 0}}});import se from"node:fs";import eo from"node:path";import rr from"node:fs";import Q from"node:path";ke();var fo="0.19.0",va=`hermes-agent==${fo}`;var tr="0.12.1",ka=Object.freeze({posix:Object.freeze({url:`https://github.com/astral-sh/uv/releases/download/${tr}/uv-installer.sh`,sha256:"d3f5412d38c99f9d024901843bf98206f0d2c6dbe64df40d0b740e2751ca62c1"}),windows:Object.freeze({url:`https://github.com/astral-sh/uv/releases/download/${tr}/uv-installer.ps1`,sha256:"b9ec035151bfbb11d616dbd69886498d885551489eddf095ea3c0ad59f640eb0"})});function po(){return Q.join(Z(),"runtime")}function mo(){return Q.join(po(),"venv")}function wo(e){let t=process.platform==="win32"?"Scripts":"bin",r=process.platform==="win32"?`${e}.exe`:e;return Q.join(mo(),t,r)}function ho(){return wo("hermes")}function go(e){let t=process.platform==="win32"&&!Q.extname(e)?["",".exe",".cmd",".bat"]:[""];for(let r of(process.env.PATH||"").split(Q.delimiter))if(r)for(let n of t){let o=Q.join(r,`${e}${n}`);try{if(rr.existsSync(o))return o}catch{}}return null}function nr(){if(process.env.ORACLE_HERMES_BIN)return{ok:!0,bin:process.env.ORACLE_HERMES_BIN,source:"env"};let e=ho();if(rr.existsSync(e))return{ok:!0,bin:e,source:"managed"};let t=go("hermes");return t?{ok:!0,bin:t,source:"path"}:{ok:!1,bin:null,source:null}}import U from"node:fs";import k from"node:path";ke();import{existsSync as ir,readFileSync as yo}from"node:fs";import{dirname as or,join as Ke}from"node:path";import{fileURLToPath as bo}from"node:url";function Eo(e){let t=or(bo(e));for(let r=0;r<8;r+=1){let n=Ke(t,"package.json");if(ir(n))try{let i=JSON.parse(yo(n,"utf8"));if(i&&typeof i.version=="string")return t}catch{}let o=or(t);if(o===t)break;t=o}throw new Error(`oracle: could not resolve package root from ${e}`)}function sr(e,t){let r=Eo(t),n=Ke(r,e);return ir(n)?n:Ke(r,"dist","assets",e)}var xo=Object.freeze([{id:"oracle",label:"Oracle Native",kind:"oracle",bins:["oracle"],website:!0,detect:!0},{id:"hermes",label:"Hermes Agent",kind:"mcp",bins:["hermes"],mcpTarget:"generic",configKey:"hermes",website:!0,detect:!0},{id:"claude",label:"Claude Code",kind:"mcp",bins:["claude"],mcpTarget:"claude-code",configKey:"claudeCode",website:!0,detect:!0},{id:"claude-desktop",label:"Claude Desktop",kind:"mcp",bins:[],mcpTarget:"claude-desktop",configKey:"claudeDesktop",website:!0,detect:!1},{id:"chatgpt",label:"ChatGPT",kind:"mcp",bins:[],mcpTarget:"chatgpt",configKey:"chatgpt",website:!0,detect:!1},{id:"codex",label:"OpenAI Codex",kind:"mcp",bins:["codex"],mcpTarget:"codex",configKey:"codex",website:!0,detect:!0},{id:"cursor",label:"Cursor",kind:"mcp",bins:["cursor","cursor-agent"],mcpTarget:"cursor",configKey:"cursor",website:!0,detect:!0},{id:"windsurf",label:"Windsurf",kind:"mcp",bins:["windsurf"],mcpTarget:"vscode",configKey:"windsurf",website:!0,detect:!0},{id:"vscode",label:"VS Code / Copilot",kind:"mcp",bins:["code","code-insiders"],mcpTarget:"vscode",configKey:"vscode",website:!0,detect:!0},{id:"openclaw",label:"OpenClaw",kind:"mcp",bins:["openclaw","claw"],mcpTarget:"generic",configKey:"openclaw",website:!0,detect:!0},{id:"perplexity",label:"Perplexity",kind:"mcp",bins:["perplexity","pplx"],mcpTarget:"generic",configKey:"perplexity",website:!0,detect:!0},{id:"manus",label:"Manus",kind:"mcp",bins:["manus"],mcpTarget:"generic",configKey:"manus",website:!0,detect:!0},{id:"prime",label:"Prime Intellect Agent",kind:"mcp",bins:["prime-agent","prime"],mcpTarget:"generic",configKey:"prime",website:!1,detect:!0},{id:"opencode",label:"OpenCode",kind:"mcp",bins:["opencode"],mcpTarget:"generic",configKey:"opencode",website:!1,detect:!0},{id:"aider",label:"Aider",kind:"mcp",bins:["aider"],mcpTarget:"generic",configKey:"aider",website:!1,detect:!0},{id:"continue",label:"Continue",kind:"mcp",bins:["continue"],mcpTarget:"vscode",configKey:"continue",website:!1,detect:!0},{id:"goose",label:"Goose",kind:"mcp",bins:["goose"],mcpTarget:"generic",configKey:"goose",website:!1,detect:!0},{id:"amp",label:"Amp",kind:"mcp",bins:["amp"],mcpTarget:"generic",configKey:"amp",website:!1,detect:!0},{id:"generic",label:"Generic MCP",kind:"mcp",bins:[],mcpTarget:"generic",configKey:"genericMcp",website:!0,detect:!1}]);function ar(){return xo.filter(e=>e.website)}var Ge=Object.freeze(["long_horizon","recursive_fanout","continual_learn","evidence_first","prepare_only"]);function Je(e=process.env){let t=String(e?.ORACLE_RESEARCH_MODE??e?.ORACLE_RLM_MODE??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"||t==="research"}var ee=Object.freeze(["oracle_cli","memory_add","memory_remove","memory_search","skill_load","skill_create","skill_list","cron_add","cron_list","cron_remove","meta_analyze","web_fetch","web_search","file_read","file_write","mcp_list","mcp_call","todo_list","todo_set","session_search","research_delegate","rlm","deep_research","clarify","code_eval","learn_skill","workspace_artifact","research_artifact","portfolio_analyze","trade_lifecycle","signal_score","vault_status","signer_status","signer_execute","signer_disarm","receipt_report","watch_create","watch_list","portfolio_snapshot","vision_analyze","browser_exec","xurl","knowledge_search"]),So="deny",La=256*1024;var $a=Object.freeze({version:1,source:"default",defaultDecision:So,allow:ee,deny:Object.freeze([])});var Ao=Object.freeze(["oracle_cli","memory_search","skill_load","skill_list","web_fetch","web_search","todo_list","todo_set","session_search","research_delegate","rlm","deep_research","clarify","code_eval","research_artifact","portfolio_analyze","trade_lifecycle","signal_score","vault_status","signer_status","receipt_report","watch_list","portfolio_snapshot","vision_analyze","knowledge_search"]),Pa=new Set(Ao);var Ye=Object.freeze(["wallet","pool","nft_floor","hl_flow","prediction_market"]),Da=Object.freeze({wallets:"wallet",smart_wallet:"wallet",pools:"pool",new_pool:"pool",nft:"nft_floor",nft_floors:"nft_floor",hyperliquid:"hl_flow",prediction:"prediction_market",prediction_markets:"prediction_market"}),F=(e,t=0,r=1)=>Math.min(r,Math.max(t,e)),$=e=>Number.isFinite(Number(e))?Number(e):null,vo=e=>Math.round(e*1e4)/1e4;function P(e,t,r,n=!0){!n||r===null||!Number.isFinite(r)||e.push({feature:t,value:vo(r)})}function ko(e,t){let r=$(e.repeatBuys??e.repeat_buys??e.buyCount),n=$(e.walletWinRate??e.winRate);P(t,"repeat_buys",r===null?null:F((r-1)/4)*.38),P(t,"wallet_win_rate",n===null?null:(F(n)-.5)*.5)}function Io(e,t){let r=$(e.ageHours??e.poolAgeHours),n=$(e.liquidityUsd??e.liquidity),o=e.liquidityLocked??e.locked;P(t,"pool_age",r===null?null:r<24?-.42:F(r/720)*.12),P(t,"liquidity",n===null?null:(F(Math.log10(Math.max(1,n))/7)-.5)*.28),P(t,"liquidity_lock",o==null?null:o?.12:-.28)}function Oo(e,t){let r=$(e.floorChange??e.floorChangePct),n=$(e.sales??e.saleCount);P(t,"floor_change",r===null?null:F(r,-1,1)*.35),P(t,"sales_depth",n===null?null:F(n/50)*.18)}function To(e,t){let r=$(e.flowImbalance??e.imbalance),n=$(e.fundingRate??e.funding);P(t,"flow_imbalance",r===null?null:F(r,-1,1)*.42),P(t,"funding",n===null?null:-F(n*100,-1,1)*.12)}function _o(e,t){let r=$(e.marketProbability??e.marketPrice??e.probability),n=$(e.fairProbability??e.referenceProbability??e.fairValue);P(t,"probability_mispricing",r===null||n===null?null:F(n-r,-1,1)*.65);let o=$(e.liquidityUsd??e.liquidity);P(t,"market_liquidity",o===null?null:F(Math.log10(Math.max(1,o))/6)*.12)}var Fa=Object.freeze({wallet:ko,pool:Io,nft_floor:Oo,hl_flow:To,prediction_market:_o});function Xe(e){try{return U.existsSync(e)}catch{return!1}}function Ie(e){for(let t of e)if(t&&Xe(t))return t;return null}function Ze(e){try{return sr(e,import.meta.url)}catch{return null}}function No(){let e=[k.join(S,"dist/data/desk-data.mjs"),k.join(S,"data/desk-data.mjs"),k.join(S,"src/data/desk-data.mjs")];for(let n of e)if(Xe(n))try{let i=U.readFileSync(n,"utf8").match(/\bid\s*:\s*["'][a-z0-9-]+["']/gi)||[],s=new Set(i.map(d=>d.toLowerCase()));if(s.size>=20)return{count:s.size,detail:`${s.size} provider ids (bundled desk-data)`}}catch{}let t=[k.join(S,"src/data/providers"),k.join(S,"dist/data/providers"),k.join(S,"data/providers")],r=Ie(t);if(!r)return{count:0,detail:"providers dir missing"};try{let n=U.readdirSync(r).filter(o=>o.endsWith(".mjs"));return{count:n.length,detail:`${n.length} provider modules`}}catch(n){return{count:0,detail:n instanceof Error?n.message:String(n)}}}function cr(){let e=Ie([Ze("skills"),k.join(S,"skills"),k.join(S,"dist/assets/skills"),k.join(S,"assets/skills")]);if(!e)return{count:0,trading:[],building:[]};let t=U.readdirSync(e),r=t.filter(o=>/trade|swap|snipe|farm|hyperliquid|poly|best-exec|circuit|meme|token-research|rfq/i.test(o)),n=t.filter(o=>/launch|builder|protocol|nft|dex-launch|token-launch|security|contract/i.test(o));return{count:t.length,trading:r,building:n}}function Co(){let e=Ie([Ze("protocols/templates"),k.join(S,"protocols/templates"),k.join(S,"dist/assets/protocols/templates"),k.join(S,"assets/protocols/templates")]);return e?U.readdirSync(e).filter(r=>!r.startsWith(".")):cr().building.some(r=>/protocol-builder|dex-launch|token-launch/i.test(r))?["(via skills: protocol-builder / launch packs)"]:[]}function Ro(){let e=Ie([Ze("profiles"),k.join(S,"profiles"),k.join(S,"dist/assets/profiles"),k.join(S,"assets/profiles")]);return e?U.readdirSync(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith("_")).map(t=>t.name):[]}function Lo(){try{if(ee.includes("trade_lifecycle")&&!ee.some(t=>/broadcast|wallet_sign/.test(t)))return!0}catch{}let e=[k.join(S,"src/capability-posture.mjs"),k.join(S,"dist/capability-posture.mjs"),k.join(S,"capability-posture.mjs"),k.join(S,"dist/public-control/policy-schema.mjs"),k.join(S,"README.md"),k.join(S,"package.json")];for(let t of e)if(Xe(t))try{let r=U.readFileSync(t,"utf8");if(/prepare-only|never takes your key|never.*broadcast/i.test(r))return!0}catch{}return!1}function lr(e=process.env){let t=[],r=(g,y,x,v=1)=>{t.push({id:g,status:y,detail:x,weight:v})},[n,o]=process.versions.node.split(".").map(Number),i=n>20||n===20&&o>=19;r("node",i?"ok":"fail",`node ${process.versions.node}`,2);let d=["oracle_cli","research_delegate","trade_lifecycle","signal_score","skill_load","learn_skill","code_eval","cron_add","web_fetch"].filter(g=>!ee.includes(g));r("agent_tools",d.length===0?"ok":"warn",d.length===0?`safe tools ${ee.length}; signal_score present`:`missing tools: ${d.join(",")}`,3),r("research_attributes","ok",`attrs [${Ge.join(", ")}]; mode=${Je(e)?"ON":"off"}`,2);let c=No();r("providers",c.count>=40?"ok":c.count>=10?"warn":"fail",c.detail,3);let p=cr();r("skills_trading_build",p.trading.length>=5&&p.building.length>=4?"ok":p.count>=10?"warn":"fail",`${p.count} skills; trading=${p.trading.length} building=${p.building.length}`,3);let m=Co();r("protocol_templates",m.length>=2?"ok":"warn",m.length?m.join(", "):"none",2);let l=Ro();r("profiles",l.includes("protocol-builder")&&l.includes("oracle")?"ok":l.length>=1?"warn":"fail",l.join(", ")||"none",2),r("signals_engine",Ye.length>=4?"ok":"fail",`types: ${Ye.join(", ")} (cold / no hot exec)`,2);let f=ar();r("harness_roster",f.length>=8?"ok":"warn",`${f.length} supported harnesses; Oracle native default; MCP inbound only`,2),r("custody_prepare_only",Lo()?"ok":"fail","public plane prepare-only",4);let u=e.ORACLE_DATA_URL||"http://127.0.0.1:8787";r("data_url","ok",u,1);let b=0,h=0;for(let g of t)h+=g.weight,g.status==="ok"?b+=g.weight:g.status==="warn"&&(b+=g.weight*.5);let w=h?Math.round(b/h*100):0,I=!t.some(g=>g.status==="fail")&&w>=70,T=I?`AGENTIC READY ${w}% \u2014 Oracle is the crypto control plane (prepare-only); pair coding harnesses via MCP for build.`:`AGENTIC GAPS ${w}% \u2014 fix fail/warn checks before calling Oracle the default crypto harness.`;return{ok:I,score:b,max:h,pct:w,summary:T,researchMode:Je(e),attributes:[...Ge],packageRoot:S,checks:t}}function to(){let[e,t]=process.versions.node.split(".").map(Number);return e>20||e===20&&t>=19}function pa(e){if(!se.existsSync(e))return{};let t={};for(let r of se.readFileSync(e,"utf8").split(/\r?\n/)){let n=r.match(/^([A-Z0-9_]+)=(.*)$/);n&&(t[n[1]]=n[2])}return t}async function ma(e){let t=e.replace(/\/$/,"");return(await Promise.all(["/health","/public/health"].map(async n=>{try{return(await fetch(t+n)).ok}catch{return!1}}))).some(Boolean)}var dg={name:"doctor",summary:"check the read plane (+ optional --agentic readiness score)",group:"read",usage:"oracle doctor [--json] [--agentic] [--first-hour]",async run(e){let t=e.argv.includes("--json"),r=e.argv.includes("--agentic"),n=e.argv.includes("--first-hour"),o=[],i=!1,s=(g,y,x,v=null)=>{o.push({id:g,status:y,detail:x,fix:v}),y==="fail"&&(i=!0)};s("node",to()?"ok":"fail",`node ${process.versions.node}`,to()?null:"install node >= 20.19");let d=e.paths.oracleExecEnvPath(),c=pa(d),p=process.env.ORACLE_ROUTE_ATTESTATION_SECRET||process.env.MAD_ROUTE_ATTESTATION_SECRET||process.env.ORACLE_ATTESTATION_SECRET||process.env.ORACLE_STAMP_HMAC_SECRET||c.ORACLE_ROUTE_ATTESTATION_SECRET||c.MAD_ROUTE_ATTESTATION_SECRET||c.ORACLE_ATTESTATION_SECRET||c.ORACLE_STAMP_HMAC_SECRET;s("attestation_secret",p?"ok":"warn",p?"present":"missing",p?null:"run oracle init --apply (writes ~/.config/oracle/exec.env)");let m=process.env.ORACLE_DATA_URL||"http://127.0.0.1:8787",l=await ma(m),f=e.paths.loadDeskRouting&&(process.env.ORACLE_DESK_URL||process.env.ORACLE_PUBLIC_URL)?`desk ${process.env.ORACLE_DESK_URL||process.env.ORACLE_PUBLIC_URL}`:null;s("data_server",l?"ok":"warn",l?`reachable ${m}${f?` (${f})`:""}`:`down ${m}`,l?null:m.includes("127.0.0.1")||m.includes("localhost")?"oracle data serve OR set ~/.config/oracle/desk.json to YOUR_DESK_HOST":"check the desk URL in ~/.config/oracle/desk.json (/public/health)");let u=nr();s("harness_model","ok","Oracle native harness is default; external harnesses are inbound MCP only (oracle harness detect)",null),s("hermes_opt_in","ok",u.ok?`detected ${u.bin} (${u.source}) \u2014 unused unless explicitly opted in`:"not detected \u2014 native-only OK",null);let b=eo.join(e.paths.hermesRoot(),"profiles"),h=0;se.existsSync(b)&&(h=se.readdirSync(b,{withFileTypes:!0}).filter(g=>g.isDirectory()).length),s("hermes_lanes","ok",h>0?`${h} profile dir(s) (optional surface)`:"no Hermes lane profiles (native-only OK)",null);{let g=eo.join(b,"oracle",".env"),y=[];if(se.existsSync(g)){let x=se.readFileSync(g,"utf8");/^TELEGRAM_BOT_TOKEN=.+/m.test(x)&&y.push("telegram"),/^DISCORD_BOT_TOKEN=.+/m.test(x)&&y.push("discord"),/^SLACK_BOT_TOKEN=.+/m.test(x)&&y.push("slack")}y.length?u.ok?s("messaging","ok",`${y.join("/")} configured \xB7 runtime ${u.source}`,null):s("messaging","warn",`${y.join("/")} token set but messaging runtime missing \u2014 bot cannot answer`,"oracle bootstrap, then oracle setup gateway restart"):s("messaging","ok","no channel tokens configured (optional \u2014 oracle setup)",null)}let w=null;if(r){w=lr(process.env);for(let g of w.checks)s(`agentic_${g.id}`,g.status,g.detail,null)}let I=null;if(n){let{firstHourReport:g,probeReviewModule:y,probeReceiptModule:x}=await Promise.resolve().then(()=>(er(),Yn)),{probeSigner:v,probeQuote:E}=await Promise.resolve().then(()=>(Qn(),Zn)),[_,J,C,B]=await Promise.all([v(process.env),E(),y(),x()]);I=g({signerReachable:_,quote:J,reviewAvailable:C,receiptAvailable:B});for(let D of I.checks)s(`hour_${D.id}`,D.status,D.detail,D.fix);s("hour_score",I.ok?"ok":"warn",I.firstRunScore.label,null)}let T={ok:!i&&(w?w.ok:!0)&&(I?I.ok:!0),checks:o,...I?{firstHour:I}:{},...w?{agentic:{pct:w.pct,summary:w.summary,attributes:w.attributes,researchMode:w.researchMode}}:{}};if(t)process.stdout.write(JSON.stringify(T,null,2)+`
7
- `);else{for(let g of o)process.stdout.write(`${g.status.toUpperCase().padEnd(4)} ${g.id}: ${g.detail}
8
- `),g.fix&&process.stdout.write(` fix: ${g.fix}
6
+ `);return 0}}});import me from"node:fs";import Fo from"node:path";import kr from"node:fs";import ae from"node:path";Pe();var Go="0.19.0",_c=`hermes-agent==${Go}`;var Ir="0.12.1",Cc=Object.freeze({posix:Object.freeze({url:`https://github.com/astral-sh/uv/releases/download/${Ir}/uv-installer.sh`,sha256:"d3f5412d38c99f9d024901843bf98206f0d2c6dbe64df40d0b740e2751ca62c1"}),windows:Object.freeze({url:`https://github.com/astral-sh/uv/releases/download/${Ir}/uv-installer.ps1`,sha256:"b9ec035151bfbb11d616dbd69886498d885551489eddf095ea3c0ad59f640eb0"})});function Yo(){return ae.join(ie(),"runtime")}function Jo(){return ae.join(Yo(),"venv")}function Xo(e){let t=process.platform==="win32"?"Scripts":"bin",r=process.platform==="win32"?`${e}.exe`:e;return ae.join(Jo(),t,r)}function Qo(){return Xo("hermes")}function Zo(e){let t=process.platform==="win32"&&!ae.extname(e)?["",".exe",".cmd",".bat"]:[""];for(let r of(process.env.PATH||"").split(ae.delimiter))if(r)for(let n of t){let o=ae.join(r,`${e}${n}`);try{if(kr.existsSync(o))return o}catch{}}return null}function Or(){if(process.env.ORACLE_HERMES_BIN)return{ok:!0,bin:process.env.ORACLE_HERMES_BIN,source:"env"};let e=Qo();if(kr.existsSync(e))return{ok:!0,bin:e,source:"managed"};let t=Zo("hermes");return t?{ok:!0,bin:t,source:"path"}:{ok:!1,bin:null,source:null}}import be from"node:fs";import C from"node:path";Pe();import{existsSync as Cr,readFileSync as ei}from"node:fs";import{dirname as _r,join as ot}from"node:path";import{fileURLToPath as ti}from"node:url";function ri(e){let t=_r(ti(e));for(let r=0;r<8;r+=1){let n=ot(t,"package.json");if(Cr(n))try{let i=JSON.parse(ei(n,"utf8"));if(i&&typeof i.version=="string")return t}catch{}let o=_r(t);if(o===t)break;t=o}throw new Error(`oracle: could not resolve package root from ${e}`)}function Tr(e,t){let r=ri(t),n=ot(r,e);return Cr(n)?n:ot(r,"dist","assets",e)}var ni=Object.freeze([{id:"oracle",label:"Oracle Native",kind:"oracle",bins:["oracle"],website:!0,detect:!0},{id:"hermes",label:"Hermes Agent",kind:"mcp",bins:["hermes"],mcpTarget:"generic",configKey:"hermes",website:!0,detect:!0},{id:"claude",label:"Claude Code",kind:"mcp",bins:["claude"],mcpTarget:"claude-code",configKey:"claudeCode",website:!0,detect:!0},{id:"claude-desktop",label:"Claude Desktop",kind:"mcp",bins:[],mcpTarget:"claude-desktop",configKey:"claudeDesktop",website:!0,detect:!1},{id:"chatgpt",label:"ChatGPT",kind:"mcp",bins:[],mcpTarget:"chatgpt",configKey:"chatgpt",website:!0,detect:!1},{id:"codex",label:"OpenAI Codex",kind:"mcp",bins:["codex"],mcpTarget:"codex",configKey:"codex",website:!0,detect:!0},{id:"cursor",label:"Cursor",kind:"mcp",bins:["cursor","cursor-agent"],mcpTarget:"cursor",configKey:"cursor",website:!0,detect:!0},{id:"windsurf",label:"Windsurf",kind:"mcp",bins:["windsurf"],mcpTarget:"vscode",configKey:"windsurf",website:!0,detect:!0},{id:"vscode",label:"VS Code / Copilot",kind:"mcp",bins:["code","code-insiders"],mcpTarget:"vscode",configKey:"vscode",website:!0,detect:!0},{id:"openclaw",label:"OpenClaw",kind:"mcp",bins:["openclaw","claw"],mcpTarget:"generic",configKey:"openclaw",website:!0,detect:!0},{id:"perplexity",label:"Perplexity",kind:"mcp",bins:["perplexity","pplx"],mcpTarget:"generic",configKey:"perplexity",website:!0,detect:!0},{id:"manus",label:"Manus",kind:"mcp",bins:["manus"],mcpTarget:"generic",configKey:"manus",website:!0,detect:!0},{id:"prime",label:"Prime Intellect Agent",kind:"mcp",bins:["prime-agent","prime"],mcpTarget:"generic",configKey:"prime",website:!1,detect:!0},{id:"opencode",label:"OpenCode",kind:"mcp",bins:["opencode"],mcpTarget:"generic",configKey:"opencode",website:!1,detect:!0},{id:"aider",label:"Aider",kind:"mcp",bins:["aider"],mcpTarget:"generic",configKey:"aider",website:!1,detect:!0},{id:"continue",label:"Continue",kind:"mcp",bins:["continue"],mcpTarget:"vscode",configKey:"continue",website:!1,detect:!0},{id:"goose",label:"Goose",kind:"mcp",bins:["goose"],mcpTarget:"generic",configKey:"goose",website:!1,detect:!0},{id:"amp",label:"Amp",kind:"mcp",bins:["amp"],mcpTarget:"generic",configKey:"amp",website:!1,detect:!0},{id:"generic",label:"Generic MCP",kind:"mcp",bins:[],mcpTarget:"generic",configKey:"genericMcp",website:!0,detect:!1}]);function Nr(){return ni.filter(e=>e.website)}var it=Object.freeze(["long_horizon","recursive_fanout","continual_learn","evidence_first","prepare_only"]);function at(e=process.env){let t=String(e?.ORACLE_RESEARCH_MODE??e?.ORACLE_RLM_MODE??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"||t==="research"}var se=Object.freeze(["oracle_cli","memory_add","memory_remove","memory_search","skill_load","skill_create","skill_list","cron_add","cron_list","cron_remove","meta_analyze","web_fetch","web_search","file_read","file_write","mcp_list","mcp_call","todo_list","todo_set","session_search","research_delegate","rlm","deep_research","clarify","code_eval","learn_skill","workspace_artifact","research_artifact","portfolio_analyze","tax_lots","position_health","governance_prepare","safety_intelligence","portfolio_risk","trade_lifecycle","signal_score","vault_status","signer_status","signer_execute","signer_disarm","receipt_report","watch_create","watch_list","portfolio_snapshot","vision_analyze","browser_exec","xurl","knowledge_search"]),oi="deny",Fc=256*1024;var Dc=Object.freeze({version:1,source:"default",defaultDecision:oi,allow:se,deny:Object.freeze([])});var ii=Object.freeze(["oracle_cli","memory_search","skill_load","skill_list","web_fetch","web_search","todo_list","todo_set","session_search","research_delegate","rlm","deep_research","clarify","code_eval","research_artifact","portfolio_analyze","tax_lots","position_health","governance_prepare","safety_intelligence","portfolio_risk","trade_lifecycle","signal_score","vault_status","signer_status","receipt_report","watch_list","portfolio_snapshot","vision_analyze","knowledge_search"]),qc=new Set(ii);var st=Object.freeze(["wallet","pool","nft_floor","hl_flow","prediction_market"]),Mc=Object.freeze({wallets:"wallet",smart_wallet:"wallet",pools:"pool",new_pool:"pool",nft:"nft_floor",nft_floors:"nft_floor",hyperliquid:"hl_flow",prediction:"prediction_market",prediction_markets:"prediction_market"}),j=(e,t=0,r=1)=>Math.min(r,Math.max(t,e)),D=e=>Number.isFinite(Number(e))?Number(e):null,ai=e=>Math.round(e*1e4)/1e4;function q(e,t,r,n=!0){!n||r===null||!Number.isFinite(r)||e.push({feature:t,value:ai(r)})}function si(e,t){let r=D(e.repeatBuys??e.repeat_buys??e.buyCount),n=D(e.walletWinRate??e.winRate);q(t,"repeat_buys",r===null?null:j((r-1)/4)*.38),q(t,"wallet_win_rate",n===null?null:(j(n)-.5)*.5)}function ci(e,t){let r=D(e.ageHours??e.poolAgeHours),n=D(e.liquidityUsd??e.liquidity),o=e.liquidityLocked??e.locked;q(t,"pool_age",r===null?null:r<24?-.42:j(r/720)*.12),q(t,"liquidity",n===null?null:(j(Math.log10(Math.max(1,n))/7)-.5)*.28),q(t,"liquidity_lock",o==null?null:o?.12:-.28)}function ui(e,t){let r=D(e.floorChange??e.floorChangePct),n=D(e.sales??e.saleCount);q(t,"floor_change",r===null?null:j(r,-1,1)*.35),q(t,"sales_depth",n===null?null:j(n/50)*.18)}function li(e,t){let r=D(e.flowImbalance??e.imbalance),n=D(e.fundingRate??e.funding);q(t,"flow_imbalance",r===null?null:j(r,-1,1)*.42),q(t,"funding",n===null?null:-j(n*100,-1,1)*.12)}function di(e,t){let r=D(e.marketProbability??e.marketPrice??e.probability),n=D(e.fairProbability??e.referenceProbability??e.fairValue);q(t,"probability_mispricing",r===null||n===null?null:j(n-r,-1,1)*.65);let o=D(e.liquidityUsd??e.liquidity);q(t,"market_liquidity",o===null?null:j(Math.log10(Math.max(1,o))/6)*.12)}var jc=Object.freeze({wallet:si,pool:ci,nft_floor:ui,hl_flow:li,prediction_market:di});xt();It();z();import{Interface as tn,getAddress as qd,id as ta,isAddress as Ud}from"ethers";z();var ju=Object.freeze({1:"assertion failed",17:"arithmetic overflow or underflow",18:"division or modulo by zero",33:"invalid enum value",34:"invalid storage byte array encoding",49:"pop() on an empty array",50:"array index out of bounds",65:"out of memory",81:"call to an uninitialized function pointer"});var zu=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),kt=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),Ot=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"});var Gi=Object.freeze({FULL:"FULL",NO_GAS:"NO_GAS",FAILED:"FAILED"});Yr();Jr();Zr();$();W();Me();L();Ct();xt();It();$();var fd=Object.freeze({across:["across"],relay:["relaychain","relay"],lifi:["jumper-(li.fi-powered)","lifi"],stargate:["stargate-v2","stargate-v1","stargate"],hop:["hop-protocol","hop"],debridge:["debridge"],synapse:["synapse"],connext:["connext"],cbridge:["celer-bridge","celer-cbridge","cbridge"],celer:["celer-bridge","celer-cbridge","cbridge"],squid:["squid"],symbiosis:["symbiosis"],wormhole:["wormhole"],mayan:["mayan"],allbridge:["allbridge"],thorchain:["thorchain"]});Ue();z();L();var Rd=Object.freeze({TRANSACTION:"unsigned-transaction",TYPED_DATA_ORDER:"typed-data-order"});var Ld=new Set(["0x0000000000000000000000000000000000000000","0x000000000000000000000000000000000000dead","0x0000000000000000000000000000000000000001","0x00000000000000000000000000000000000a1ce5"].map(e=>e.toLowerCase()));var Pd=Object.freeze(["operation","exactOutput","amountOut","multihop","path","positionManager","modifyLiquidities","commands","actions"]);L();var rn=Object.freeze({1:Object.freeze({name:"ethereum",positionManager:"0xC36442b4a4522E871399CD717aBDD847Ab11FE88",wrappedNative:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",venue:"uniswap-v3",source:"https://docs.uniswap.org/contracts/v3/reference/deployments/ethereum-deployments"}),8453:Object.freeze({name:"base",positionManager:"0x03a520b32C04BF3bEEf7BEb72E919cf822Ed34f1",wrappedNative:"0x4200000000000000000000000000000000000006",venue:"uniswap-v3",source:"https://docs.uniswap.org/contracts/v3/reference/deployments/base-deployments"})}),Wd=new tn(["function ownerOf(uint256 tokenId) view returns (address)","function positions(uint256 tokenId) view returns (uint96 nonce,address operator,address token0,address token1,uint24 fee,int24 tickLower,int24 tickUpper,uint128 liquidity,uint256 feeGrowthInside0LastX128,uint256 feeGrowthInside1LastX128,uint128 tokensOwed0,uint128 tokensOwed1)","function decreaseLiquidity((uint256 tokenId,uint128 liquidity,uint256 amount0Min,uint256 amount1Min,uint256 deadline) params) payable returns (uint256 amount0,uint256 amount1)","function collect((uint256 tokenId,address recipient,uint128 amount0Max,uint128 amount1Max) params) payable returns (uint256 amount0,uint256 amount1)","function multicall(bytes[] data) payable returns (bytes[] results)"]),Vd=new tn(["function withdraw(uint256 wad)"]),Kd=(1n<<128n)-1n;var Gd=ta("Transfer(address,address,uint256)").toLowerCase();$();Me();L();import{getAddress as Zd,Interface as je,TypedDataEncoder as ef,parseUnits as tf}from"ethers";var na="fulfillAdvancedOrder(((address offerer,address zone,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount)[] offer,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount,address recipient)[] consideration,uint8 orderType,uint256 startTime,uint256 endTime,bytes32 zoneHash,uint256 salt,bytes32 conduitKey,uint256 totalOriginalConsiderationItems) parameters,uint120 numerator,uint120 denominator,bytes signature,bytes extraData) advancedOrder,(uint256 orderIndex,uint8 side,uint256 index,uint256 identifier,bytes32[] criteriaProof)[] criteriaResolvers,bytes32 fulfillerConduitKey,address recipient)",sf=new je([`function ${na}`]),cf=new je(["function mintPublic(address nftContract,address feeRecipient,address minterIfNotPayer,uint256 quantity) payable","function mintAllowList(address nftContract,address feeRecipient,address minterIfNotPayer,uint256 quantity,(uint80 mintPrice,uint48 maxTotalMintableByWallet,uint48 startTime,uint48 endTime,uint48 dropStageIndex,uint32 maxTokenSupplyForStage,uint16 feeBps,bool restrictFeeRecipients) mintParams,bytes32[] proof) payable"]),oa=Object.freeze(["blast","base","ethereum","zora","arbitrum","sei","avalanche","polygon","optimism","ape_chain","flow","b3","soneium","ronin","bera_chain","solana","shape","unichain","gunzilla","abstract","animechain","hyperevm","somnia","monad","hyperliquid","megaeth","ink","robinhood","stablechain"]),uf=new Set(oa);var nn=Object.freeze({robinhood:4663,ethereum:1,base:8453,arbitrum:42161,optimism:10,polygon:137,avalanche:43114,zora:7777777,blast:81457,sei:1329,ape_chain:33139,b3:8333,soneium:1868,ronin:2020,bera_chain:80094,shape:360,unichain:130,gunzilla:43419,abstract:2741,animechain:69e3,hyperevm:999,somnia:5031,monad:143,megaeth:4326,ink:57073,stablechain:988});var lf=Object.freeze({OrderComponents:[{name:"offerer",type:"address"},{name:"zone",type:"address"},{name:"offer",type:"OfferItem[]"},{name:"consideration",type:"ConsiderationItem[]"},{name:"orderType",type:"uint8"},{name:"startTime",type:"uint256"},{name:"endTime",type:"uint256"},{name:"zoneHash",type:"bytes32"},{name:"salt",type:"uint256"},{name:"conduitKey",type:"bytes32"},{name:"counter",type:"uint256"}],OfferItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"}],ConsiderationItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"},{name:"recipient",type:"address"}]});var df=new je(["function setApprovalForAll(address operator,bool approved)"]),ff=new je(["function cancel((address offerer,address zone,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount)[] offer,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount,address recipient)[] consideration,uint8 orderType,uint256 startTime,uint256 endTime,bytes32 zoneHash,uint256 salt,bytes32 conduitKey,uint256 counter)[] orders) returns (bool cancelled)"]);z();Fe();$();z();z();bt();var Tt=Object.freeze([{key:"ethereum",chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://etherscan.io",dexscreenerSlug:"ethereum",venueKind:"uniswap-v3",wrappedNative:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",stableQuoteAssets:["0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48","0xdAC17F958D2ee523a2206206994597C13D831ec7"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.71 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}}]},{key:"optimism",chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://optimistic.etherscan.io",dexscreenerSlug:"optimism",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",stableQuoteAssets:["0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85","0x94b008aA00579c1307B0EF2c499aD98a8ce58e58"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1905.23 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}}]},{key:"bsc",chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],nativeCurrency:{symbol:"BNB",decimals:18},explorer:"https://bscscan.com",dexscreenerSlug:"bsc",venueKind:"uniswap-v3",wrappedNative:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",stableQuoteAssets:["0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d","0x55d398326f99059fF775485246999027B3197955"],venues:[{kind:"quoter",address:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WBNB->USDC fee 500 quoted 413.86 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}},{kind:"router",address:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}}]},{key:"polygon",chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],nativeCurrency:{symbol:"POL",decimals:18},explorer:"https://polygonscan.com",dexscreenerSlug:"polygon",venueKind:"uniswap-v3",wrappedNative:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",stableQuoteAssets:["0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359","0xc2132D05D31c914a87C6611C10748AEb04B58e8F"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WMATIC->USDC fee 500 quoted 0.0720 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}}]},{key:"stable",chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],nativeCurrency:{symbol:"USDT0",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x5d442b349590a6048Eb2dC0eC346cAA5F47A9ab5",venues:[{kind:"quoter",address:"0xb070179E7032CdA868b53e6C1742F80c9e940d1A",label:"Uniswap V3 QuoterV2 (canonical)",verified:{method:"Stable is on the OFFICIAL Uniswap v3 Deployments List (governance-recognised 2026-05-12, UAC process completed 2026-04, deployed by Protofire), so this is a canonical deployment rather than a fork. eth_getCode returned 8273 bytes, the same size as the canonical quoter on the seven already-verified chains. Functional probe on a live pool (TOAST -> USDT0, fee 10000): 100 in -> 0.000003, 1000 -> 0.000031, 10000 -> 0.000319 USDT0. Output scales monotonically with input, which is a working quoter answering, not a revert. Two of three sampled pools carry non-zero liquidity. NOTE: the pools discovered so far are thin, so real routing size is limited -- the venue is proved, deep liquidity is not.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:988}},{kind:"router",address:"0x32eaf9B5d5F2CD7361c5012890C943D7de84C22a",label:"Uniswap SwapRouter02 (canonical)",verified:{method:"eth_getCode returned 24497 bytes. Cross-checked on-chain rather than trusted from docs: router.factory() returns 0x88f0a512ef09175d456bc9547f914f48c013e4aa, the same v3 core factory that created the pools quoted above, and router.WETH9() returns the wrappedNative recorded on this chain entry. Address published in the Stable docs DEX reference and the Uniswap deployments list.",source:"docs.stable.xyz/en/reference/dexes + on-chain factory()/WETH9() round-trip",date:"2026-08-05",chainId:988}}]},{key:"hyperevm",chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],nativeCurrency:{symbol:"HYPE",decimals:18},dexscreenerSlug:"hyperevm",venueKind:"uniswap-v3",wrappedNative:"0x5555555555555555555555555555555555555555",venues:[{kind:"quoter",address:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",label:"HyperSwap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle(1 WHYPE -> USDT0) returned live output on all four fee tiers (100: 57.3385, 500: 57.4187, 3000: 57.3237, 10000: 56.1963 USDT0). Decimals read on-chain: WHYPE 18, USDT0 6. Best tier checked against an INDEPENDENT control the same minute -- Hyperliquid allMids put HYPE at 57.3205, so the pool is 0.171% from the perp mid, which is the right shape for fee plus impact rather than a wrong contract or a decimals bug.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}},{kind:"router",address:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D",label:"HyperSwap V3 SwapRouter",verified:{method:"eth_getCode returned 12070 bytes, and it is the router paired with the quoter proved above -- the same pair already shipped in UNI_V3_VENUES[999].hyperswap, which is the map the quote/prepare path actually routes through.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}}]},{key:"abstract",chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x3439153EB7AF838Ad19d56E1571FBD09333C2809",venues:[{kind:"quoter",address:"0x728BD3eC25D5EDBafebB84F3d67367Cd9EBC7693",label:"Uniswap V3 QuoterV2 (Abstract deployment)",verified:{method:"Abstract is a ZK-stack chain, so CREATE2 addresses differ and the canonical Uniswap addresses are NOT valid here -- probing them returns codesize 0, which is what previously made this chain look like it had no V3 at all. Found the real deployment from live traffic instead: scanned recent Swap(...) logs, took the busiest pool, read pool.factory() = 0xa1160e73b63f322ae88cc2d8e700833e71d0b2a1, then enumerated that factory's deployer (0xf3d63166F0Ca56C3c1A3508FcE03Ff0Cf3Fb691e) and probed each of its 56 contracts with a real quoteExactInputSingle call. Exactly one answered: 1 WETH -> 1846.475731 USDC.e at fee 500. Independent sanity check: the pool's own slot0() spot price is 1873.11 USDC.e per WETH, so the quoter sits ~1.4% below spot, the right shape for fee plus price impact on this size.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:2741}},{kind:"router",address:"0x7712FA47387542819d4E35A23f8116C90C18767C",label:"Uniswap SwapRouter02 (Abstract deployment)",verified:{method:"eth_getCode returned 167392 bytes and the runtime contains the exactInputSingle selector. router.factory() matches the factory proved above and router.WETH9() matches the wrappedNative on this entry. Chosen over its byte-identical twin (0xfD6257F4...) because this is the address real users actually route through: it appeared as tx.to on live swaps against the WETH/USDC.e pool.",source:"on-chain factory()/WETH9() round-trip + live swap tx.to sampling",date:"2026-08-05",chainId:2741}}]},{key:"robinhood",chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC","ROBINHOOD_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},dexscreenerSlug:"robinhood",venueKind:"uniswap-v3",wrappedNative:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",stableQuoteAssets:["0x5fc5360d0400a0fd4f2af552add042d716f1d168"],venues:[{kind:"quoter",address:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDG fee 100 quoted 1866.58 USDG, and USDG->CASHCAT fee 10000 quoted a live amount). A contract that correctly prices known pairs IS a working V3 quoter",source:"live eth_call against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"router",address:"0xcaf681a66d020601342297493863e78c959e5cb2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode (24497 bytes) on this chain and the paired quoter at the same deployment passed a live functional quote",source:"live eth_getCode against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"factory",address:"0x1f7d7550b1b028f7571e69a784071f0205fd2efa",label:"Uniswap V3 Factory",verified:{method:"eth_getCode returned real bytecode (24535 bytes) and a PoolCreated log scan over this factory returned 76 pools in ~9000 recent blocks",source:"live eth_getLogs against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}}]},{key:"base",chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://basescan.org",dexscreenerSlug:"base",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",stableQuoteAssets:["0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"],venues:[{kind:"quoter",address:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",label:"Uniswap V3 QuoterV2 (Base)",verified:{method:"functional probe: quoteExactInputSingle returned WETH->USDC at fee 500 = 1908.44 USDC, a live sane price. The canonical mainnet quoter address also has bytecode on Base but does NOT price this pair, which is exactly the false positive a codesize-only check accepts",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router",address:"0x2626664c2603336E57B271c5C0b26F421741e481",label:"Uniswap V3 SwapRouter02 (Base)",verified:{method:"eth_getCode returned real bytecode and the paired Base quoter passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router-v2",address:"0x4752ba5DBc23f44D87826276BF6Fd6b1C372aD24",label:"Uniswap V2 Router02 (Base)",verified:{method:"eth_getCode returned 17891 bytes; live getAmountsOut on WETH->USDC round-tripped to 98.75% (2x0.30% fee + impact)",source:"https://docs.uniswap.org/contracts/v2/reference/smart-contracts/v2-deployments",date:"2026-07-30",chainId:8453}}]},{key:"arbitrum",chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://arbiscan.io",dexscreenerSlug:"arbitrum",venueKind:"uniswap-v3",wrappedNative:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",stableQuoteAssets:["0xaf88d065e77c8cC2239327C5EDb3A432268e5831","0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.72 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}}]},{key:"avalanche",chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],nativeCurrency:{symbol:"AVAX",decimals:18},explorer:"https://snowtrace.io",dexscreenerSlug:"avalanche",venueKind:"uniswap-v3",wrappedNative:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",stableQuoteAssets:["0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"],venues:[{kind:"quoter",address:"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WAVAX->USDC fee 500 quoted 6.48 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}},{kind:"router",address:"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}}]}]);var He=new Map,ia=Object.keys(St).map(Number),aa=Object.keys(At).map(Number),sa=Object.keys(rn).map(Number),Rt=Tt.map(e=>e.chainId),ca=[...new Set(Object.values(nn))],Nt=new Set,on=!1;function an(e){if(!e||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Object.values(e))an(t);return Object.freeze(e)}function a(e){if(!e?.id)throw new Error("registerProvider requires id");if(!e.venue)throw new Error("registerProvider requires venue");if(!Array.isArray(e.ops))throw new Error("registerProvider requires ops[]");let t=String(e.id);if(on&&Nt.has(t))throw new Error(`registerProvider refuses to overwrite built-in provider: ${t}`);return He.set(t,{chainIds:e.chainIds||[],auth:e.auth||"none",description:e.description||"",baseEnv:e.baseEnv||[],...e,id:t}),He.get(t)}function Lt({venue:e,op:t}={}){let r=[...He.values()];return e&&(r=r.filter(n=>n.venue===e)),t&&(r=r.filter(n=>n.ops.includes(t))),r}function ua(){Nt.clear();for(let[e,t]of He)Nt.add(e),an(t);on=!0}a({id:"hl-info",venue:"hl",chainIds:[],auth:"none",ops:["health","allMids","l2Book","outcomeMeta","clearinghouse","userFills","meta","metaAndAssetCtxs","candleSnapshot","openOrders","frontendOpenOrders","userState","spotMeta"],baseEnv:["HL_INFO_URL","HL_API_URL"],description:"Hyperliquid public /info"});a({id:"hl-vaults",venue:"hyperliquid-vaults",chainIds:[],auth:"none",ops:["health","summaries","details","userEquities","tracker"],execution:"read-only",baseEnv:["HL_INFO_URL","HL_API_URL"],description:"Read-only Hyperliquid vault summaries, vault details, user vault equities, and HLP tracking."});a({id:"hl-precompiles",venue:"hyperliquid",chainIds:[999],auth:"none",ops:["health","read","l1BlockNumber","markPx","oraclePx","spotPx","position","spotBalance","vaultEquity","withdrawable"],execution:"read-only",baseEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],description:"HyperEVM L1Read precompiles (0x800-0x809). eth_call only. Includes HLP vault equity. No CoreWriter."});a({id:"protocol-templates",venue:"protocol-builder",chainIds:[],auth:"none",ops:["health","list","listNative","gate","prepareDeploy","buildNative","eval"],description:"Gated EVM templates plus deterministic Solana program and Bitcoin policy scaffolds. Native bundles require chain-specific compile, tests, and simulation before any unsigned deploy/funding prepare. NOT a firm audit."});a({id:"poly-public",venue:"poly",chainIds:[137],auth:"none",ops:["health","time","markets","book","midpoint","spread","price","events"],execution:"read-only",baseEnv:["POLY_CLOB_URL","POLY_GAMMA_URL"],description:"Polymarket CLOB + Gamma public REST"});a({id:"poly-clob",venue:"poly",chainIds:[137],auth:"none",ops:["health","prepareOrder"],execution:"prepare",localSignerSurfaces:["poly"],description:"Polymarket CLOB unsigned EIP-712 order prepare plus owner-operated local-signer submit. Hosted/keyless remains prepare-only."});a({id:"hl-delta-neutral",venue:"hyperliquid",chainIds:[],auth:"none",ops:["health","scan","quote","prepare","loop"],execution:"prepare",localSignerSurfaces:["hl"],description:"Hyperliquid funding carry. Armed through the existing hl signer. Hosted/keyless remains prepare-only. Not automated."});a({id:"lighter-delta-neutral",venue:"lighter",chainIds:[],auth:"none",ops:["health","scan","quote","prepare","loop"],execution:"prepare",localSignerSurfaces:["lighter"],description:"Lighter.xyz funding carry. Armed through the official sendTx local-signer. Hosted/keyless remains prepare-only. Not automated."});a({id:"portfolio",venue:"multichain-wallet",chainIds:[1,10,56,137,988,999,2741,4663,8453,42161,43114],auth:"none",ops:["health","balances","snapshot","history","valueGraph"],execution:"read-only",description:"Read-only balance aggregation across configured EVM chains, Solana, Bitcoin, and Hyperliquid, plus profile-local observation snapshots, history, and value graphs with explicit partial coverage."});a({id:"nft-portfolio",venue:"multichain-nft-wallet",chainIds:[1,10,137,988,999,2741,4663,8453,42161,43114],auth:"optionalApiKey",ops:["health","inventory","gallery","pnl","prepareList","traitSnipe"],execution:"prepare",baseEnv:["OPENSEA_API_KEY","MAGICEDEN_API_KEY","SATFLOW_API_KEY"],description:"Normalized EVM, Solana, and Bitcoin NFT inventory, static contact-sheet galleries, explicit PnL coverage, user-confirmed unsigned listing preparation, and evidence-gated trait-snipe buy intents."});a({id:"evm-simulate",venue:"onchain-simulation",chainIds:[1,10,56,137,988,999,2741,4663,8453,42161,43114],auth:"none",ops:["health","simulate"],execution:"read",baseEnv:[],description:"Pre-sign EVM transaction simulation: eth_call at pending state to catch reverts, decoded revert reasons (Error(string), Panic codes, custom-error selectors), and a buffered gas estimate. Distinguishes a genuine revert from an unreachable node \u2014 an infra failure is never reported as 'would fail'. A pass reflects current chain state and is explicitly not a guarantee."});a({id:"nft-mint",venue:"onchain-mint",chainIds:[1,10,56,137,988,999,2741,4663,8453,42161,43114],auth:"none",ops:["health","discover","prepare","priceGas","createTrigger","checkOpen"],execution:"prepare",localSignerSurfaces:["evm-nft"],baseEnv:[],description:"EVM NFT mints: discover the collection's mint entrypoint from bytecode, price a competitive EIP-1559 bid from fee-history percentiles, enforce gas-war caps, surface contract risk, and hand execution to the local signer after explicit arming and bounded grant."});a({id:"universal-mint-router",venue:"universal-nft-mint",chainIds:[],auth:"optionalApiKey",ops:["health","capabilities","prepare"],execution:"prepare",baseEnv:["OPENSEA_API_KEY"],description:"Prepare-only exact universal mint routing across reviewed EVM and Ordinals adapters. Universal Solana mint is RESEARCH_ONLY and disabled until canonical serialized-message decoding ships; the separate Magic Eden marketplace provider is unchanged. It never signs or broadcasts."});a({id:"universal-nft-lifecycle",venue:"universal-nft-lifecycle",chainIds:[],auth:"optionalApiKey",ops:["health","capabilities","route"],execution:"read",baseEnv:["OPENSEA_API_KEY","MAGICEDEN_API_KEY","SATFLOW_API_KEY"],description:"Read-only NFT lifecycle route discovery. It does not prepare, sign, or broadcast artifacts; callers must invoke and review the selected provider operation separately."});for(let[e,t,r]of[["universal-evm-nft-transfer","evm-nft-transfer","Exact unsigned ERC-721/ERC-1155 safeTransferFrom preparation."],["universal-solana-nft-transfer","solana-nft-transfer","Exact unsigned verified Metaplex NFT/Core transfer preparation."],["universal-ordinals-transfer","bitcoin-nft-transfer","Exact unsigned Ordinals PSBT transfer-plan preparation."]])a({id:e,venue:t,chainIds:[],auth:"none",ops:["health","prepare"],execution:"prepare",description:r});a({id:"contract-risk",venue:"onchain-bytecode",chainIds:[1,10,56,137,988,999,2741,4663,8453,42161,43114],auth:"none",ops:["health","scan"],execution:"read",baseEnv:[],description:"Structural contract risk from on-chain bytecode: retained owner powers (mint, blacklist, pause, fee changes) and upgradeability across EIP-1967, legacy zeppelinos, and EIP-1822 proxy slots. Complements behavioural sell simulation. Never reports 'safe' \u2014 a clean scan is weak evidence, not a guarantee."});a({id:"evm-token-sniper",venue:"evm-token-launches",chainIds:Rt,auth:"none",ops:["health","scan"],execution:"prepare",localSignerSurfaces:["evm-swap"],baseEnv:Tt.flatMap(e=>e.rpcEnv),description:"One generic EVM token-sniping path across every configured EVM chain: live identity, pools, structural risk, sell simulation, quote, guarded transaction preparation, and local-signer execution handoff. Robinhood Chain is the default, not a special implementation."});a({id:"evm-rpc",venue:"evm",chainIds:[1,137,42161,8453,10,4663,999],auth:"none",ops:["health","healthAll","blockNumber","chainId","getBalance","call","erc20Allowance","erc20Balance","transactionReceipt"],baseEnv:["ETH_RPC_URL","POLYGON_RPC_URL","RH_CHAIN_RPC","BASE_RPC_URL","ARBITRUM_RPC_URL"],description:"EVM JSON-RPC multi-chain (env RPC or public fallbacks)"});a({id:"solana-rpc",venue:"solana",chainIds:[],auth:"none",ops:["health","latestBlockhash","getBalance","tokenAccounts","simulate"],baseEnv:["SOLANA_RPC_URL"],description:"Solana mainnet JSON-RPC read/prepare surface (no key, no signing, no broadcast)"});a({id:"bitcoin-esplora",venue:"bitcoin",chainIds:[],auth:"none",ops:["health","tipHeight","fees","address","utxos","tx","decode"],execution:"read-only",baseEnv:["BTC_ESPLORA_URL","BTC_NETWORK"],description:"Bitcoin L1 via Esplora (mempool.space/Blockstream). Reads only on data plane. User-signed broadcast is bitcoin_send on exec MCP. No Core RPC, no house keys. Wallets: Xverse/UniSat/Leather/OKX/Phantom"});a({id:"bitcoin-meta",venue:"bitcoin-metaprotocol",chainIds:[],auth:"optionalApiKey",ops:["health","runeBalances","inscriptions","inscriptionInfo","inscriptionChildren","ordBlockInfo"],execution:"read-only",baseEnv:["BTC_META_API_URL","UNISAT_API_KEY","BESTINSLOT_API_KEY"],description:"Bitcoin ordinals/runes reads. Keyless tier via ordinals.com recursive (inscriptionInfo/children/blockInfo); address-indexed ops (inscriptions, runeBalances) need a keyed indexer. Hiro is deprecated (410) and Magic Eden BTC is dead \u2014 use satflow for market."});a({id:"satflow",venue:"bitcoin-marketplace",chainIds:[],auth:"apiKey",ops:["health","collectionFloors","collectionStats","item","walletContents","floorListings","preparePurchase","prepareList"],execution:"prepare",localSignerSurfaces:["btc"],baseEnv:["SATFLOW_API_KEY","SATFLOW_API_URL"],description:"Satflow ordinals+runes marketplace (api.satflow.com). Primary BTC NFT market after Magic Eden BTC sunset. PSBT intents for buy/list; key via x-api-key."});a({id:"jupiter",venue:"solana-dex",chainIds:[],auth:"none",ops:["health","venues","quote","prepare"],execution:"prepare",localSignerSurfaces:["sol"],baseEnv:["JUPITER_SWAP_API_URL","SOLANA_RPC_URL"],description:"Jupiter Swap API v1 quote + local-signer Solana swap handoff"});a({id:"hl-perps",venue:"hyperliquid",chainIds:[],auth:"none",ops:["health","assetInfo","prepareOrder","prepareCancel","prepareLeverage","prepareIsolatedMargin","prepareBracket","prepareBuilderApproval"],execution:"prepare",localSignerSurfaces:["hl"],notes:"Hyperliquid perp, HIP-3, and HIP-4 outcome orders through local-signer L1 action handoff."});a({id:"hl-markets",venue:"hyperliquid",chainIds:[],auth:"none",ops:["health","markets","leaderboards","coin","spot"],notes:"Joined Hyperliquid market datapoints for the Hyperliquid agent. Read-only."});a({id:"hl-entry-state",venue:"hyperliquid",chainIds:[],auth:"none",ops:["health","see","qualify","lock","list","watch"],execution:"read-only",description:"SEE/ENTER/MANAGE for discretionary HL perps: compose sourced /info fields, qualify a side, lock the state only after a fill receipt, and alert_only-diff live vs that lock. Never signs."});a({id:"hl-staking",venue:"hypercore-staking",chainIds:[],auth:"none",ops:["health","validators","delegatorSummary","delegations","rewards","history","preflight","prepareStakeDeposit","prepareStakeWithdraw","prepareDelegate"],execution:"prepare",localSignerSurfaces:["hl"],baseEnv:["HL_INFO_URL","HL_EXCHANGE_URL","HL_TESTNET"],description:"Hyperliquid HyperCore HYPE staking. Public reads plus local-signer EIP-712 execution for cDeposit / cWithdraw / tokenDelegate after arming. Hosted/keyless remains prepare-only."});a({id:"magiceden-sol",venue:"solana-nft",chainIds:[],auth:"optionalApiKey",ops:["health","stats","listings","tokenListings","prepareBuy","prepareList","prepareMint"],execution:"prepare",baseEnv:["MAGICEDEN_API_KEY","MAGICEDEN_API_URL"],description:"Magic Eden Solana NFT market. Reads (stats/listings) are keyless; buy/list/mint instruction builders need MAGICEDEN_API_KEY and return an unsigned base64 transaction for the user's Solana wallet. Never signs or broadcasts."});a({id:"defillama",venue:"prices",chainIds:[],auth:"none",ops:["health","prices","pricesBySymbol","protocols","yields","stablecoins","dexVolumes"],baseEnv:["DEFILLAMA_COINS_URL","DEFILLAMA_API_URL"],description:"DeFiLlama public prices + protocols TVL"});a({id:"lifi",venue:"dex",chainIds:[1,10,56,137,988,999,2741,4663,8453,42161,43114],auth:"none",ops:["health","quote","prepare","chains"],execution:"prepare",baseEnv:["LIFI_API_URL"],description:"LI.FI public cross-chain / DEX aggregator quotes (no key)"});a({id:"dexscreener",venue:"dex",chainIds:[],auth:"none",ops:["health","token","search","pair"],baseEnv:["DEXSCREENER_API_URL"],description:"DexScreener public token/pair discovery"});a({id:"uniswap-v3",venue:"dex",chainIds:ia,auth:"none",ops:["health","quote","prepare","quotePath","ethUsdc","chains"],execution:"prepare",localSignerSurfaces:["evm-swap"],baseEnv:["ETH_RPC_URL","BASE_RPC_URL","ARBITRUM_RPC_URL","OPTIMISM_RPC_URL","BSC_RPC_URL","POLYGON_RPC_URL","AVALANCHE_RPC_URL","RH_CHAIN_RPC"],description:"Uniswap V3 QuoterV2 exact-in quotes via eth_call across official deployments plus Robinhood Chain, no key"});a({id:"lp-exit",venue:"dex",chainIds:sa,auth:"none",ops:["health","inspect","prepareRemove","prepareSettlement","prepareUnwrap","chains"],execution:"prepare",baseEnv:["ETH_RPC_URL","BASE_RPC_URL"],description:"Receipt-gated Uniswap V3 LP exit into native asset: remove/collect, net-route token legs, then unwrap. Unsigned only."});a({id:"lp-liquidity-ranker",venue:"dex",chainIds:Rt,auth:"none",ops:["health","rank"],execution:"read-only",description:"Cross-chain LP destination analysis: deepest liquidity and net-best migration are separate, exact canonical mappings required."});a({id:"lp-destination-discovery",venue:"dex",chainIds:Rt,auth:"none",ops:["health","discover"],execution:"read-only",description:"Live exact-address LP pool discovery across configured chains; reports deepest liquidity separately from cost-qualified migration evidence."});a({id:"uniswap-v4",venue:"dex",chainIds:aa,auth:"none",ops:["health","quote","inspectHook","prepare","chains"],execution:"prepare",baseEnv:["ETH_RPC_URL","BASE_RPC_URL","ARBITRUM_RPC_URL","OPTIMISM_RPC_URL","BSC_RPC_URL","POLYGON_RPC_URL","AVALANCHE_RPC_URL","RH_CHAIN_RPC"],description:"Uniswap V4 quotes, hook permission/code/pool-state inspection, and guarded unsigned Universal Router preparation across official deployments plus Robinhood Chain."});a({id:"x402",venue:"payments",chainIds:[],auth:"none",ops:["health","inspect","prepare"],execution:"prepare",description:"x402 v2 PAYMENT-REQUIRED inspection and explicit-cap exact-payment templates. Never signs, calls a facilitator, or retries a paid request."});a({id:"bankr",venue:"wallet-data",chainIds:[],auth:"apiKey",ops:["health","wallet","portfolio","swapQuote"],execution:"read-only",baseEnv:["BANKR_API_KEY","BANKR_API_URL"],description:"Bankr Wallet API read-only identity, portfolio, and swap quotes. Oracle excludes Bankr swap, transfer, sign, submit, agent, and LLM endpoints."});a({id:"aerodrome",venue:"dex",chainIds:[8453],auth:"none",ops:["health","quote","prepare","chains"],execution:"prepare",localSignerSurfaces:["evm-swap"],baseEnv:["BASE_RPC_URL"],description:"Aerodrome Slipstream CL on Base \u2014 QuoterV2 + SwapRouter exact-input via eth_call (tickSpacing, no key)"});a({id:"zerox",venue:"dex",chainIds:[1,10,137,8453,42161],auth:"apiKey",ops:["health","price","quote","prepare"],execution:"prepare",baseEnv:["ZEROX_API_KEY","ZEROX_API_URL"],description:"0x Swap API v2 price/quote/prepare \u2014 requires ZEROX_API_KEY (unconfigured without key; no Oracle key shipped)"});a({id:"across",venue:"bridge",chainIds:[1,10,137,42161,8453],auth:"none",ops:["health","suggestedFees"],baseEnv:["ACROSS_API_URL"],description:"Across bridge suggested-fees (public)"});a({id:"hop",venue:"bridge",chainIds:[1,10,137,42161],auth:"none",ops:["health","quote"],baseEnv:["HOP_API_URL"],description:"Hop Protocol bridge quotes (public)"});a({id:"relay",venue:"bridge",chainIds:[1,10,137,8453,42161],auth:"none",ops:["health","quote","prepare"],execution:"prepare",baseEnv:["RELAY_API_URL"],description:"Relay.link bridge/swap quotes (public)"});a({id:"cowswap",venue:"dex",chainIds:[1,100,42161,8453],auth:"none",ops:["health","quote","prepareOrder","order","status","chains","arm"],execution:"armed-local",localSignerSurfaces:["evm-order"],baseEnv:[],description:"CowSwap batch auction. Quote is public; Allow posts official api.cow.fi orders."});a({id:"oneinch",venue:"dex",chainIds:[1,10,137,8453,42161],auth:"apiKey",ops:["health","quote","prepare","approveSpender"],execution:"prepare",baseEnv:["ONEINCH_API_KEY","ONEINCH_API_URL"],description:"1inch Swap API v6 quote/prepare \u2014 requires ONEINCH_API_KEY (unconfigured without key; no Oracle key shipped)"});a({id:"hl-ws",venue:"hl",chainIds:[],auth:"none",ops:["health","allMids","l2Book","snapshot"],baseEnv:["HL_WS_URL"],description:"Hyperliquid short-lived WS snapshots (allMids/l2Book)"});a({id:"poly-ws",venue:"poly",chainIds:[137],auth:"none",ops:["health","book","snapshot"],baseEnv:["POLY_WS_URL"],description:"Polymarket CLOB short-lived WS market snapshots"});a({id:"anvil-nft",venue:"robinhood-nft",chainIds:[4663],auth:"optionalApiKey",ops:["health","markets","quoteSpecificBuy","quoteSell","scanCollection","scanAllMarkets","scanCrossVenueArb","scanAllMarketsArb","prepareSpecificBuy","prepareSell"],execution:"prepare",localSignerSurfaces:["evm-nft"],baseEnv:["RH_CHAIN_RPC","OPENSEA_API_KEY","OPENSEA_ENV_FILE"],description:"All-market Anvil discovery and exact-token arbitrage, with exact buy and sell execution through the armed owner-local signer after human confirmation"});a({id:"stonkbrokers",venue:"robinhood-nft",chainIds:[4663],auth:"optionalApiKey",ops:["health","quoteBrokerBuy","scanBrokerLoot","prepareBrokerBuy","brokerDesk","clockInStatus","prepareClockIn"],execution:"prepare",baseEnv:["RH_CHAIN_RPC"],description:"Unsigned StonkBrokers Broker Desk discovery, nested-loot verification, and bounded local-only preparations"});a({id:"opensea-nft",venue:"nft",chainIds:ca,auth:"apiKey",ops:["health","collection","floor","bestListings","bestListing","bestOffer","accountNfts","accountPnl","prepareMint","prepareList","prepareCancel"],execution:"prepare",baseEnv:["OPENSEA_API_KEY","OPENSEA_ENV_FILE"],description:"OpenSea multichain NFT inventory, floors, and unsigned bounded mint, listing, and listing-cancellation preparations; opaque buy/sweep fulfillment is disabled"});a({id:"local-marketplace",venue:"local-p2",chainIds:[],auth:"none",ops:["health","createListing","listListings","cancelListing","createOffer","armFill"],execution:"prepare",localSignerSurfaces:["evm-nft"],description:"Owner-local P2 catalog stored under ~/.config/oracle. Additive and isolated from OpenSea, Magic Eden, Satflow, Bisq, Anvil, and Polymarket. Listings are armed for the owner-local signer; sign-and-broadcast is an explicit createLocalMarketplace().instructFill instruction. Generic signHash is refused."});a({id:"local-x402",venue:"local-x402",chainIds:[],auth:"none",ops:["health","createIntent","listIntents","cancelIntent","armPayment"],execution:"prepare",localSignerSurfaces:["evm-swap"],description:"Owner-local x402 payment budgets under ~/.config/oracle. Additive and isolated from OpenSea and Telegram. Intents are armed; sign-and-broadcast is an explicit createLocalX402().instructPay instruction. Generic signHash is refused."});a({id:"local-pack-registry",venue:"local-packs",chainIds:[],auth:"none",ops:["health","registerPack","listPacks","revokePack"],execution:"read-only",description:"Owner-local third-party pack REGISTRY under ~/.config/oracle. Catalog only: packs are never loaded or executed. Isolated from OpenSea and Telegram."});a({id:"erc8004-identity",venue:"agent-identity",chainIds:[],auth:"none",ops:["health","prepareIdentityRegistration","prepareAgentURIUpdate","inspectIdentity","arm"],execution:"armed-local",localSignerSurfaces:["evm"],baseEnv:["ORACLE_ERC8004_CHAIN_ID","ORACLE_ERC8004_IDENTITY_REGISTRY"],description:"Draft ERC-8004 identity. Public prepare is keyless; Allow broadcasts type-2 register/setAgentURI."});a({id:"hyperevm-dex",venue:"hyperevm",chainIds:[999],auth:"none",ops:["health","search","token"],baseEnv:["HYPEREVM_RPC_URL"],description:"HyperEVM pair discovery via DexScreener + optional RPC"});a({id:"geckoterminal",venue:"dex-data",chainIds:[],auth:"none",ops:["health","networks","pool","token","ohlcv"],baseEnv:["GECKOTERMINAL_API_URL"],description:"GeckoTerminal public networks, pools, tokens, and OHLCV"});a({id:"curve",venue:"dex",chainIds:[1,10,56,137,988,999,4663,8453,42161,43114],auth:"none",ops:["health","openapi","pools","quote","prepare"],execution:"prepare",baseEnv:["CURVE_API_URL"],description:"Curve public pool registry API + RouterNG validated single-hop prepare"});a({id:"gmx",venue:"perps-data",chainIds:[42161,43114],auth:"none",ops:["health","tickers","markets","marketsInfo","tokens","prepareOrder","positions","orderStatus","verifyOrder"],execution:"intent",baseEnv:[],description:"GMX v2 public oracle/markets plus guarded async order intents on Arbitrum and Avalanche"});a({id:"morpho",venue:"lending-data",chainIds:[1,10,137,2741,8453,42161,4663,999,988],auth:"none",ops:["health","markets","vaults","prepareVault"],execution:"intent",baseEnv:["MORPHO_API_URL"],description:"Morpho public GraphQL markets/vaults + guarded ERC-4626 vault intents"});a({id:"balancer",venue:"dex",chainIds:[1,10,137,42161,43114,8453],auth:"none",ops:["health","pools","quote","prepare"],execution:"prepare",baseEnv:["BALANCER_API_URL"],description:"Balancer public GraphQL pool data + v3 Router exact-input prepare (Polygon read-only)"});a({id:"pendle",venue:"yield",chainIds:[1,10,56,8453,42161,999],auth:"none",ops:["health","markets","quote","prepare"],execution:"prepare",baseEnv:["PENDLE_API_URL"],description:"Pendle public yield-market API + Hosted SDK direct Convert prepare"});a({id:"odos",venue:"dex",chainIds:[1,10,56,137,8453,42161,43114,4663],auth:"none",ops:["health"],execution:"unavailable",deprecated:{since:"2026-07-30",reason:"Odos sunset the public SOR API; /sor/quote/v2 and v3 both return 410 Gone",evidence:"sunset: Thu, 30 Jul 2026 12:00:00 GMT response header"},baseEnv:["ODOS_API_URL"],description:"Odos public SOR (DEPRECATED upstream 2026-07-30 -- endpoint returns 410)"});a({id:"blockscout",venue:"explorer",chainIds:[1,10,137,8453,42161],auth:"none",ops:["health","stats","address","token"],baseEnv:[],description:"Verified public Blockscout REST v2 instances"});a({id:"paraswap",venue:"dex",chainIds:[1,10,56,137,8453,42161,43114,4663],auth:"none",ops:["health","tokens","price","quote","prepare"],execution:"prepare",baseEnv:["PARASWAP_API_URL"],description:"ParaSwap/Velora public price routes + validated transaction builder"});a({id:"rfq",venue:"intent-rfq",chainIds:[1,10,56,137,8453,42161,43114,4663],auth:"none",ops:["health","intent","quote"],execution:"prepare",baseEnv:["ZEROX_API_KEY","ONEINCH_API_KEY"],description:"Cross-chain RFQ intent normalizer and firm-quote fanout over reviewed venues. Prepares artifacts only, never signs or broadcasts."});a({id:"execution-strategies",venue:"oracle-native",chainIds:[],auth:"none",ops:["health","plan"],execution:"plan-only",baseEnv:[],description:"Oracle-native TWAP, VWAP, POV, iceberg, and implementation-shortfall planners. No Tread.fi/API dependency. Plans never sign or broadcast; every slice requires a fresh best-execution quote, policy check, simulation, confirmation, wallet signature, and receipt."});a({id:"polygon-staking",venue:"polygon-staking",chainIds:[137],auth:"none",ops:["health","validators","validatorDetail"],baseEnv:["POLYGON_STAKING_API_URL"],description:"Polygon POS staking validators"});a({id:"babylon-staking",venue:"btc-staking",chainIds:[],auth:"none",ops:["health","stats","finalityProviders","delegations"],execution:"read-only",baseEnv:["BABYLON_STAKING_API_URL"],description:"Babylon native BTC staking (staking-api.babylonlabs.io v2). Keyless per-staker positions from a PUBLIC key alone \u2014 APR, TVL, finality-provider roster, and delegations. Read-only; staking/unbonding is user-wallet."});a({id:"mempool-mining",venue:"btc-mining",chainIds:[],auth:"none",ops:["health","difficulty","poolShare","hashrate","rewardStats"],execution:"read-only",baseEnv:["MEMPOOL_API_URL"],description:"Bitcoin mining + network security telemetry via mempool.space /api/v1/mining. Difficulty retarget, pool concentration (top-1/top-3 share), hashrate trend, subsidy-vs-fee split."});a({id:"liquid-esplora",venue:"liquid",chainIds:[],auth:"none",ops:["health","tipHeight","addressInfo","assetInfo"],execution:"read-only",baseEnv:["LIQUID_ESPLORA_URL"],description:"Liquid Network (Blockstream sidechain) via Esplora. Same schema as bitcoin-esplora plus multi-asset issuance/peg stats. Confidential addresses return TXO counts only \u2014 amounts are blinded on chain and reported as such."});a({id:"hiro-stacks",venue:"stacks",chainIds:[],auth:"none",ops:["health","networkInfo","stackingInfo","poxCycles","blocks"],execution:"read-only",baseEnv:["HIRO_API_URL","HIRO_API_KEY"],description:"Stacks (Bitcoin L2) via Hiro public API. Network tip, PoX stacking state (the BTC-yield mechanism), and historical reward cycles. Keyless tier is ~20 rps; HIRO_API_KEY is optional and never required."});a({id:"tron-public",venue:"tron",chainIds:[],auth:"none",ops:["health","account","trc20Balances","trc20Transfers","chainParameters"],execution:"read-only",localSignerSurfaces:[],baseEnv:["TRON_API_URL","TRONGRID_API_KEY"],description:"Tron mainnet via public TronGrid. TRX balance, TRC20 token balances, USDT-TRC20 transfer history, chain parameters. Tron carries the largest USDT float of any chain. Keyless; TRONGRID_API_KEY only raises the rate ceiling and never travels to a non-TronGrid host."});a({id:"ton-public",venue:"ton",chainIds:[],auth:"none",ops:["health","accountState","jettonBalances","transactions"],execution:"read-only",localSignerSurfaces:[],baseEnv:["TON_API_URL","TONCENTER_API_KEY"],description:"TON via public toncenter. Account state + nanoton balance, jetton (TON's ERC20) balances, transaction history. The settlement layer for Telegram-native assets. Keyless; TONCENTER_API_KEY only raises the rate ceiling."});a({id:"cosmos-lcd",venue:"cosmos",chainIds:[],auth:"none",ops:["health","chains","balances","delegations","denomTrace"],execution:"read-only",localSignerSurfaces:[],baseEnv:["COSMOS_LCD_URL","COSMOS_CHAIN"],description:"Cosmos SDK chains via keyless LCD/REST \u2014 one provider, many chains (cosmoshub default, plus osmosis/celestia/injective/neutron/dydx/noble/kava, or any LCD via COSMOS_LCD_URL_<CHAIN>). Bank balances, staking delegations + unbondings + rewards, and IBC denom-trace resolution for ibc/<hash> denoms."});a({id:"sui-public",venue:"sui",chainIds:[],auth:"none",ops:["health"],execution:"unavailable",deprecated:{since:"2026-08-25",reason:"Sui public fullnodes return JSON-RPC -32601 because the JSON-RPC surface is deprecated",evidence:"Migrate the provider to Sui GraphQL or gRPC before restoring it to the live roster"},localSignerSurfaces:[],baseEnv:["SUI_RPC_URL"],description:"QUARANTINED: Sui public JSON-RPC is deprecated. A GraphQL or gRPC replacement has not shipped."});a({id:"aptos-public",venue:"aptos",chainIds:[],auth:"none",ops:["health","account","resources","coinBalances"],execution:"read-only",localSignerSurfaces:[],baseEnv:["APTOS_FULLNODE_URL","APTOS_API_KEY"],description:"Aptos mainnet via the public fullnode REST API. Ledger info, account sequence/auth key, Move resources, and coin balances (0x1::coin::balance view with a CoinStore resource fallback). Read-only; the transaction submit door is never called."});a({id:"ordinals-runes",venue:"btc-runes",chainIds:[],auth:"none",ops:["health","blockHeight","blockInfo","satInfo","runeInfo"],execution:"read-only",baseEnv:["ORDINALS_BASE_URL"],description:"Runes + sat/block index via a public ord server (ordinals.com). /r/blockheight is PLAIN TEXT; the /runes listing is 406 'JSON API disabled' so only per-rune lookup exists; rune names must drop the bullet spacer (UNCOMMONGOODS)."});a({id:"mempool-lightning",venue:"btc-lightning",chainIds:[],auth:"none",ops:["health","statistics","nodeRankings","nodeCountries"],execution:"read-only",baseEnv:["MEMPOOL_API_URL"],description:"Lightning Network topology via mempool.space. Capacity/channel/node aggregates, node rankings, country distribution. STALE-PRONE: the crawler snapshot has been observed weeks behind, so every response carries ageDays + a stale flag."});a({id:"bob-rootstock",venue:"btc-l2",chainIds:[60808,30],auth:"none",ops:["health","stats","addressInfo","tokenBalances"],execution:"read-only",baseEnv:["BOB_EXPLORER_URL","ROOTSTOCK_EXPLORER_URL"],description:"BOB (60808) and Rootstock (30) \u2014 the EVM Bitcoin L2s \u2014 via their Blockscout v2 instances (identical schema, one code path). Chain stats, gas prices, native balances, token holdings. Pass chainId 'all' to fan out."});a({id:"bisq-markets",venue:"bisq",chainIds:[],auth:"none",ops:["health","markets","ticker","trades"],execution:"read-only",baseEnv:["BISQ_MARKETS_URL"],description:"Bisq non-KYC P2P BTC price discovery (markets.bisq.network). Value is the BASIS against centralized spot, not the absolute print: volume is thin and the last trade can be hours old, so trade age is always reported."});a({id:"social-intel",venue:"oracle-social",chainIds:[],auth:"none",ops:["health","trendingTokens","trendingCas","keywordMentions","smartAccounts","narratives"],execution:"read-only",localSignerSurfaces:[],baseEnv:["ORACLE_SOCIAL_INTEL_STORE","ORACLE_SOCIAL_INTEL_STALE_MIN"],description:"Local curated-account crypto social intelligence. Sample = graded caller list, NOT a firehose; every response reports sample size and snapshot age."});a({id:"magiceden-ordinals",venue:"btc-ordinals-market",chainIds:[],auth:"none",ops:["health","collectionStat"],execution:"read-only",baseEnv:["MAGICEDEN_ORD_API_URL","MAGICEDEN_API_KEY","MAGICEDEN_PROBE_COLLECTION"],description:"Magic Eden ordinals collection stats. DEGRADED UPSTREAM: /v2/ord/btc/* returned 503 'no healthy upstream' on every verification attempt. health() reports ok:false while it is down and collectionStat() returns upstreamDown:true with fallback 'satflow' instead of throwing. Only /stat is wired; 600 req/min documented."});a({id:"braiins-insights",venue:"btc-mining",chainIds:[],auth:"none",ops:["health","priceStats","poolStats"],execution:"read-only",baseEnv:["BRAIINS_INSIGHTS_URL"],description:"Braiins mining insights \u2014 BTC price tick + per-pool block/hashrate distribution. Use insights.braiins.com (302s to learn.braiins.com, followed transparently); pool.braiins.com/api is 403 and is NOT the public API."});a({id:"pyth-price-feeds",venue:"solana-oracle",chainIds:[],auth:"none",ops:["health","latestPrice","latestPrices","feedDirectory"],baseEnv:["PYTH_HERMES_URL"],description:"Pyth Network: Solana price feeds with confidence intervals, real-time updates, zero auth"});a({id:"solend-lending",venue:"solana-lending",chainIds:[],auth:"none",ops:["health","markets","reserves"],baseEnv:["SAVE_API_URL"],description:"Solend/Save lending: markets + per-reserve supply/borrow APY, Solana's Aave equivalent (keyless)"});a({id:"jito-mev",venue:"solana-mev",chainIds:[],auth:"none",ops:["health","recentBundles","tipFloor"],baseEnv:["JITO_API_URL"],description:"Jito MEV: recent bundles, tippers, tip floor \u2014 real-time Solana MEV data (keyless)"});a({id:"sanctum-lst",venue:"solana-staking",chainIds:[],auth:"none",ops:["health","lstList","apyAll","apyIndividual"],baseEnv:["SANCTUM_API_URL"],description:"Sanctum LST: liquid staking tokens with per-token APY \u2014 JitoSOL, mSOL, bSOL, compSOL, pathSOL, etc. (keyless)"});a({id:"kamino-strategies",venue:"solana-yield",chainIds:[],auth:"none",ops:["health","strategies","strategyMetrics"],baseEnv:["KAMINO_API_URL"],description:"Kamino: live yield strategies with APY, TVL, vault balances (keyless)"});a({id:"meteora-dlmm",venue:"solana-dex",chainIds:[],auth:"none",ops:["health","pools","poolSearch"],baseEnv:["METEORA_API_URL"],description:"Meteora DLMM: concentrated liquidity pools via amm-v2 API, distinct from Jupiter DEX routes (keyless)"});a({id:"aave-v3",venue:"evm-lending",chainIds:[1,10,56,137,59144,1088,534352,8453,42161,43114,5e3,1868],auth:"none",ops:["health","markets","marketReserves","chains"],baseEnv:["AAVE_V3_API_URL"],description:"Aave V3 GraphQL: multi-chain lending, full market + reserve schema with supplyInfo/borrowInfo (keyless)"});a({id:"cow-protocol",venue:"evm-intent",chainIds:[1,100,42161],auth:"none",ops:["health","auction","openOrders","recentTrades"],baseEnv:["COW_API_URL"],description:"CoW Protocol: intent/solver auction data, open orders, trades \u2014 intent-based DEX not covered by existing providers (keyless)"});a({id:"relayscan-mev",venue:"evm-mev",chainIds:[1],auth:"none",ops:["health","overview","builderProfit","dailyStats"],baseEnv:["RELAYSCAN_API_URL"],description:"Relayscan: MEV relay overview, builder profit rankings, daily block stats (keyless)"});a({id:"birdeye-tokens",venue:"solana-tokens",chainIds:[],auth:"none",ops:["health","tokenList"],baseEnv:["BIRDEYE_API_URL"],description:"Birdeye public token list: Solana tokens ranked by 24h volume, market cap (keyless)"});a({id:"das-assets",venue:"solana-nft",chainIds:[],auth:"none",ops:["health","assetsByOwner","searchAssets","assetProof"],baseEnv:["SOLANA_RPC_URL"],description:"Digital Asset Standard (DAS): compressed NFT reads via public Solana RPC \u2014 getAssetsByOwner, searchAssets, assetProof. No Helius key needed."});a({id:"symbiotic-restaking",venue:"evm-restaking",chainIds:[1],auth:"none",ops:["health","vaults","vaultDetail"],baseEnv:["SYMBIOTIC_API_URL"],description:"Symbiotic restaking: vaults with collateral data, approved status, operator metadata (keyless)"});a({id:"beefy-yields",venue:"evm-yield",chainIds:[1,10,56,137,8453,42161,43114,250,1088],auth:"none",ops:["health","apy","apyBreakdown"],baseEnv:["BEEFY_API_URL"],description:"Beefy Finance: cross-chain yield aggregator vaults with APY breakdowns (keyless)"});a({id:"across-bridge",venue:"evm-bridge",chainIds:[1,10,42161,8453,324,59144],auth:"none",ops:["health","pools","suggestedFees"],baseEnv:["ACROSS_API_URL"],description:"Across bridge: pool liquidity + APY per bridge pool with suggested fees (keyless)"});a({id:"spark-lend",venue:"evm-lending",chainIds:[1],auth:"none",ops:["health","markets"],baseEnv:["SPARK_API_URL"],description:"Spark Lend / Sky Savings: ERC-4626 vault APY + TVL + user count (keyless)"});a({id:"l2beat-tvl",venue:"evm-l2",chainIds:[],auth:"none",ops:["health","tvl","activity"],baseEnv:["L2BEAT_API_URL"],description:"L2Beat: L2 scaling TVL, project-level breakdowns, activity metrics (keyless)"});a({id:"celestia-da",venue:"evm-da",chainIds:[],auth:"none",ops:["health","stats","blockStats"],baseEnv:["CELENIUM_API_URL"],description:"Celestia DA via Celenium: blob stats, block-level blob counts, network metrics (keyless)"});a({id:"limit-order",venue:"1inch-lop",chainIds:[1,10,56,137,8453,42161],auth:"none",ops:["health","prepare","arm"],execution:"armed-local",localSignerSurfaces:["evm-order"],description:"1inch Limit Order Protocol v4. Queues on the local signer; Allow posts the order."});a({id:"jupiter-dca",venue:"jupiter",chainIds:[],auth:"none",ops:["health","prepare","arm"],execution:"armed-local",localSignerSurfaces:["sol"],description:"Jupiter limit/DCA. Unsigned tx queues on the sol signer; Allow submits."});a({id:"protective-monitors",venue:"oracle-intel",chainIds:[],auth:"none",ops:["health","depeg","oracleDeviation","exploitFeed","goplus","liquidationLadder"],execution:"read-only",description:"Alert-only depeg, oracle deviation, exploit feed, GoPlus second opinion, liquidation ladder."});a({id:"funding-scanner",venue:"perps",chainIds:[],auth:"none",ops:["health","scan"],execution:"read-only",description:"Cross-venue funding carry ranked net of fee drag. Failed venues stay FAILED."});a({id:"perp-universal",venue:"perps",chainIds:[],auth:"none",ops:["health","fundingAll","prepareOrder"],execution:"prepare-only",description:"Live fundingAll across HL/GMX/dYdX + honest FAILED Drift/Vertex. prepareOrder unsigned."});a({id:"onchain-options",venue:"options",chainIds:[],auth:"none",ops:["health","rank"],execution:"read-only",description:"Local Black-Scholes ranking. No arm until official Derive/Lyra domain is pinned."});a({id:"holder-clusters",venue:"oracle-intel",chainIds:[],auth:"none",ops:["health","score"],execution:"read-only",description:"Heuristic holder HHI + common-funding clusters. Not identity."});a({id:"kalshi",venue:"prediction",chainIds:[],auth:"none",ops:["health","markets"],execution:"read-only",description:"Kalshi market catalog read-only. Trading may be US-restricted. Prepare refused."});a({id:"derive-options",venue:"options",chainIds:[],auth:"none",ops:["health"],execution:"unavailable",deprecated:{since:"2026-08-25",reason:"No official Derive EIP-712 domain or contract is pinned, so prepare remains unavailable",evidence:"prepareOption() in onchain-options.mjs refuses unconditionally"},description:"UNAVAILABLE: Derive execution has no pinned official domain. Use onchain-options for local ranking."});a({id:"limitless",venue:"prediction",chainIds:[],auth:"none",ops:["health","markets"],execution:"read-only",description:"Limitless market catalog. Prepare refused \u2014 no grant-bound decoder."});a({id:"dov-vaults",venue:"options",chainIds:[],auth:"none",ops:["health"],execution:"unavailable",deprecated:{since:"2026-08-25",reason:"The reviewed DOV vault registry is empty, so every vault read refuses",evidence:"REVIEWED_DOV_VAULTS.length is zero and no reviewed code hash is pinned"},description:"UNAVAILABLE: the reviewed DOV vault registry is empty and every read fails closed."});a({id:"prediction-match",venue:"prediction",chainIds:[],auth:"none",ops:["health","match"],execution:"read-only",description:"Cross-venue event match. Same title is not a match."});a({id:"tee-attestation",venue:"identity",chainIds:[],auth:"none",ops:["health","verify"],execution:"read-only",description:"TEE schema stub. Hardware unavailable. Unknown root unverified."});a({id:"keeper-mirror",venue:"oracle-intel",chainIds:[],auth:"none",ops:["health"],execution:"read-only",description:"Keeper alert-mirror. Off by default. No execute path."});a({id:"erc7715-permissions",venue:"aa",chainIds:[],auth:"none",ops:["health","normalize"],execution:"read-only",description:"ERC-7715 permission normalize. Wildcards refused. aa allowlist empty."});a({id:"erc7710-delegation",venue:"aa",chainIds:[],auth:"none",ops:["health","inspect"],execution:"read-only",description:"ERC-7710 delegation inspect. Missing revocation/expiry fails closed."});a({id:"binance-public",venue:"cex",chainIds:[],auth:"none",ops:["health","ticker","orderbook","funding","markPrice","openInterest","fundingHistory"],execution:"read-only",localSignerSurfaces:[],baseEnv:["BINANCE_API_URL","BINANCE_FAPI_URL"],description:"Binance public spot + USD-M perp market data (ticker, depth, premiumIndex funding, open interest). Keyless reads only; no trading endpoints."});a({id:"okx-public",venue:"cex",chainIds:[],auth:"none",ops:["health","ticker","orderbook","funding","markPrice","openInterest"],execution:"read-only",localSignerSurfaces:[],baseEnv:["OKX_API_URL"],description:"OKX public v5 market data (ticker, books, swap funding-rate, mark-price, open-interest). Keyless reads only; no trading endpoints."});a({id:"bybit-public",venue:"cex",chainIds:[],auth:"none",ops:["health","ticker","orderbook","funding","markPrice","openInterest","fundingHistory"],execution:"read-only",localSignerSurfaces:[],baseEnv:["BYBIT_API_URL"],description:"Bybit public v5 market data (spot/linear tickers, orderbook, funding, open interest). Keyless reads only; no trading endpoints."});a({id:"cex-basis",venue:"cex",chainIds:[],auth:"none",ops:["health","basis","fundingSpread","legs"],execution:"read-only",localSignerSurfaces:[],baseEnv:["BINANCE_API_URL","OKX_API_URL","BYBIT_API_URL","HL_INFO_URL"],description:"Cross-venue perp basis and annualized funding spreads across Binance, OKX, Bybit and Hyperliquid public data. Analysis only, no sizing and no prepare."});a({id:"snapshot-governance",venue:"governance",chainIds:[],auth:"none",ops:["health","spaces","proposals","activeProposals","proposal","votes","votingPower"],execution:"read-only",localSignerSurfaces:[],baseEnv:["SNAPSHOT_API_URL"],description:"Snapshot.org off-chain governance reads: spaces, proposals, proposal detail, an address's votes and voting power. Never signs a vote."});a({id:"tally-governance",venue:"governance",chainIds:[1,10,42161],auth:"none",ops:["health","governors","info","proposals","proposal","voterStatus","tallyProposals"],execution:"read-only",localSignerSurfaces:[],baseEnv:["TALLY_API_URL","TALLY_API_KEY"],description:"Governor Bravo / OZ Governor on-chain proposal state and vote tallies for major DAOs, plus optional keyed Tally metadata. Read-only ABI has no vote/queue/execute selector."});a({id:"stablecoin-peg",venue:"oracle-intel",chainIds:[],auth:"none",ops:["health","scan"],execution:"read-only",localSignerSurfaces:[],baseEnv:[],description:"Peg-deviation scan across major and Hyperliquid-native stables. Ranks by absolute bps from $1 and classifies normal/watch/warn/depeg. Unpriced is unknown, never on-peg. Read-only composition of DefiLlama/Pyth/DexScreener."});ua();var Vf=Object.freeze(["live","needs_key","deprecated","soft_fail","hard_down"]),la=new Set(["apiKey","agentKey"]),da=/(?:API_KEY|ACCESS_KEY|SECRET|TOKEN|CREDENTIAL|AUTH|ENV_FILE)$/i,fa=/(?:URL|URI|HOST|ENDPOINT|RPC)$/i;function pa(e={}){return la.has(e.auth)?(Array.isArray(e.baseEnv)?e.baseEnv:[]).filter(t=>da.test(t)&&!fa.test(t)):[]}function ze(e={}){return e.execution==="unavailable"||!!e.deprecated}function ma(e={},t={},{env:r=process.env}={}){let n;if(ze(e))n="deprecated";else if(t?.ok===!0)n="live";else{let o=pa(e);o.length>0&&!o.some(s=>String(r?.[s]||"").trim())?n="needs_key":e.softFail?n="soft_fail":n="hard_down"}return Object.freeze({provider:e.id||null,class:n,hardDown:n==="hard_down",quarantined:n==="deprecated",probe:t})}function sn(e=[],t=null,{env:r=process.env}={}){let n=t?.providers&&typeof t.providers=="object"?t.providers:{},o={live:0,needs_key:0,deprecated:0,soft_fail:0,hard_down:0,unknown:0},i={},s=[],p=[];for(let u of e){if(!ze(u)&&!Object.hasOwn(n,u.id)){o.unknown+=1,i[u.id]=Object.freeze({provider:u.id,class:"unknown",hardDown:!1,quarantined:!1});continue}let f=ma(u,n[u.id],{env:r});i[u.id]=f,o[f.class]+=1,f.hardDown&&s.push(u.id),f.quarantined&&p.push(u.id)}return Object.freeze({ok:s.length===0,roster:e.length,probed:t!=null,counts:Object.freeze(o),hardDown:s.length,hardDownIds:Object.freeze(s),quarantined:p.length,quarantinedIds:Object.freeze(p),classifications:Object.freeze(i)})}function cn(e){try{return be.existsSync(e)}catch{return!1}}function Pt(e){for(let t of e)if(t&&cn(t))return t;return null}function $t(e){try{return Tr(e,import.meta.url)}catch{return null}}function ha(){let e=Lt(),t=e.filter(ze).map(r=>r.id);return Object.freeze({source:"catalog",count:e.length,live:e.length-t.length,quarantined:t.length,quarantinedIds:Object.freeze(t)})}function un(){let e=Pt([$t("skills"),C.join(O,"skills"),C.join(O,"dist/assets/skills"),C.join(O,"assets/skills")]);if(!e)return{count:0,trading:[],building:[]};let t=be.readdirSync(e),r=t.filter(o=>/trade|swap|snipe|farm|hyperliquid|poly|best-exec|circuit|meme|token-research|rfq/i.test(o)),n=t.filter(o=>/launch|builder|protocol|nft|dex-launch|token-launch|security|contract/i.test(o));return{count:t.length,trading:r,building:n}}function wa(){let e=Pt([$t("protocols/templates"),C.join(O,"protocols/templates"),C.join(O,"dist/assets/protocols/templates"),C.join(O,"assets/protocols/templates")]);return e?be.readdirSync(e).filter(r=>!r.startsWith(".")):un().building.some(r=>/protocol-builder|dex-launch|token-launch/i.test(r))?["(via skills: protocol-builder / launch packs)"]:[]}function ga(){let e=Pt([$t("profiles"),C.join(O,"profiles"),C.join(O,"dist/assets/profiles"),C.join(O,"assets/profiles")]);return e?be.readdirSync(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&!t.name.startsWith("_")).map(t=>t.name):[]}function ya(){try{if(se.includes("trade_lifecycle")&&!se.some(t=>/broadcast|wallet_sign/.test(t)))return!0}catch{}let e=[C.join(O,"src/capability-posture.mjs"),C.join(O,"dist/capability-posture.mjs"),C.join(O,"capability-posture.mjs"),C.join(O,"dist/public-control/policy-schema.mjs"),C.join(O,"README.md"),C.join(O,"package.json")];for(let t of e)if(cn(t))try{let r=be.readFileSync(t,"utf8");if(/prepare-only|never takes your key|never.*broadcast/i.test(r))return!0}catch{}return!1}function ln(e=process.env,{health:t=null}={}){let r=[],n=(v,J,_,P=1)=>{r.push({id:v,status:J,detail:_,weight:P})},[o,i]=process.versions.node.split(".").map(Number),s=o>20||o===20&&i>=19;n("node",s?"ok":"fail",`node ${process.versions.node}`,2);let u=["oracle_cli","research_delegate","trade_lifecycle","signal_score","skill_load","learn_skill","code_eval","cron_add","web_fetch"].filter(v=>!se.includes(v));n("agent_tools",u.length===0?"ok":"warn",u.length===0?`safe tools ${se.length}; signal_score present`:`missing tools: ${u.join(",")}`,3),n("research_attributes","ok",`attrs [${it.join(", ")}]; mode=${at(e)?"ON":"off"}`,2);let f=ha(),h=f.quarantinedIds.length?`: ${f.quarantinedIds.join(", ")}`:"";n("providers",f.count>=40?"ok":f.count>=10?"warn":"fail",`${f.count} providers from catalog, ${f.live} live, ${f.quarantined} quarantined${h}`,3);let l=sn(Lt(),t,{env:e}),m=l.hardDown>0?"fail":l.quarantined>0||l.counts.needs_key>0||l.counts.unknown>0?"warn":"ok",d=l.hardDownIds.length?`; hard_down_ids=${l.hardDownIds.join(",")}`:"";n("provider_health",m,`live=${l.counts.live} needs_key=${l.counts.needs_key} deprecated=${l.counts.deprecated} soft_fail=${l.counts.soft_fail} hard_down=${l.counts.hard_down} unknown=${l.counts.unknown}${d}`,3);let b=un();n("skills_trading_build",b.trading.length>=5&&b.building.length>=4?"ok":b.count>=10?"warn":"fail",`${b.count} skills; trading=${b.trading.length} building=${b.building.length}`,3);let y=wa();n("protocol_templates",y.length>=2?"ok":"warn",y.length?y.join(", "):"none",2);let w=ga();n("profiles",w.includes("protocol-builder")&&w.includes("oracle")?"ok":w.length>=1?"warn":"fail",w.join(", ")||"none",2),n("signals_engine",st.length>=4?"ok":"fail",`types: ${st.join(", ")} (cold / no hot exec)`,2);let k=Nr();n("harness_roster",k.length>=8?"ok":"warn",`${k.length} supported harnesses; Oracle native default; MCP inbound only`,2),n("custody_prepare_only",ya()?"ok":"fail","public plane prepare-only",4);let N=e.ORACLE_DATA_URL||"http://127.0.0.1:8787";n("data_url","ok",N,1);let S=0,g=0;for(let v of r)g+=v.weight,v.status==="ok"?S+=v.weight:v.status==="warn"&&(S+=v.weight*.5);let x=g?Math.round(S/g*100):0,I=!r.some(v=>v.status==="fail")&&x>=70,E=I?`AGENTIC READY ${x}% \u2014 Oracle is the crypto control plane (prepare-only); pair coding harnesses via MCP for build.`:`AGENTIC GAPS ${x}% \u2014 fix fail/warn checks before calling Oracle the default crypto harness.`;return{ok:I,score:S,max:g,pct:x,summary:E,researchMode:at(e),attributes:[...it],packageRoot:O,checks:r}}function Do(){let[e,t]=process.versions.node.split(".").map(Number);return e>20||e===20&&t>=19}function gc(e){if(!me.existsSync(e))return{};let t={};for(let r of me.readFileSync(e,"utf8").split(/\r?\n/)){let n=r.match(/^([A-Z0-9_]+)=(.*)$/);n&&(t[n[1]]=n[2])}return t}async function yc(e){let t=e.replace(/\/$/,"");return(await Promise.all(["/health","/public/health"].map(async n=>{try{return(await fetch(t+n)).ok}catch{return!1}}))).some(Boolean)}var RE={name:"doctor",summary:"check the read plane (+ optional --agentic readiness score)",group:"read",usage:"oracle doctor [--json] [--agentic] [--first-hour]",async run(e){let t=e.argv.includes("--json"),r=e.argv.includes("--agentic"),n=e.argv.includes("--first-hour"),o=[],i=!1,s=(S,g,x,I=null)=>{o.push({id:S,status:g,detail:x,fix:I}),g==="fail"&&(i=!0)};s("node",Do()?"ok":"fail",`node ${process.versions.node}`,Do()?null:"install node >= 20.19");let p=e.paths.oracleExecEnvPath(),u=gc(p),f=process.env.ORACLE_ROUTE_ATTESTATION_SECRET||process.env.MAD_ROUTE_ATTESTATION_SECRET||process.env.ORACLE_ATTESTATION_SECRET||process.env.ORACLE_STAMP_HMAC_SECRET||u.ORACLE_ROUTE_ATTESTATION_SECRET||u.MAD_ROUTE_ATTESTATION_SECRET||u.ORACLE_ATTESTATION_SECRET||u.ORACLE_STAMP_HMAC_SECRET;s("attestation_secret",f?"ok":"warn",f?"present":"missing",f?null:"run oracle init --apply (writes ~/.config/oracle/exec.env)");let h=process.env.ORACLE_DATA_URL||"http://127.0.0.1:8787",l=await yc(h),m=e.paths.loadDeskRouting&&(process.env.ORACLE_DESK_URL||process.env.ORACLE_PUBLIC_URL)?`desk ${process.env.ORACLE_DESK_URL||process.env.ORACLE_PUBLIC_URL}`:null;s("data_server",l?"ok":"warn",l?`reachable ${h}${m?` (${m})`:""}`:`down ${h}`,l?null:h.includes("127.0.0.1")||h.includes("localhost")?"oracle data serve OR set ~/.config/oracle/desk.json to YOUR_DESK_HOST":"check the desk URL in ~/.config/oracle/desk.json (/public/health)");let d=Or();s("harness_model","ok","Oracle native harness is default; external harnesses are inbound MCP only (oracle harness detect)",null),s("hermes_opt_in","ok",d.ok?`detected ${d.bin} (${d.source}) \u2014 unused unless explicitly opted in`:"not detected \u2014 native-only OK",null);let b=Fo.join(e.paths.hermesRoot(),"profiles"),y=0;me.existsSync(b)&&(y=me.readdirSync(b,{withFileTypes:!0}).filter(S=>S.isDirectory()).length),s("hermes_lanes","ok",y>0?`${y} profile dir(s) (optional surface)`:"no Hermes lane profiles (native-only OK)",null);{let S=Fo.join(b,"oracle",".env"),g=[];if(me.existsSync(S)){let x=me.readFileSync(S,"utf8");/^TELEGRAM_BOT_TOKEN=.+/m.test(x)&&g.push("telegram"),/^DISCORD_BOT_TOKEN=.+/m.test(x)&&g.push("discord"),/^SLACK_BOT_TOKEN=.+/m.test(x)&&g.push("slack")}g.length?d.ok?s("messaging","ok",`${g.join("/")} configured \xB7 runtime ${d.source}`,null):s("messaging","warn",`${g.join("/")} token set but messaging runtime missing \u2014 bot cannot answer`,"oracle bootstrap, then oracle setup gateway restart"):s("messaging","ok","no channel tokens configured (optional \u2014 oracle setup)",null)}let w=null;if(r){w=ln(process.env);for(let S of w.checks)s(`agentic_${S.id}`,S.status,S.detail,null)}let k=null;if(n){let{firstHourReport:S,probeReviewModule:g,probeReceiptModule:x}=await Promise.resolve().then(()=>(Ar(),Lo)),{probeSigner:I,probeQuote:E}=await Promise.resolve().then(()=>(Bo(),$o)),[v,J,_,P]=await Promise.all([I(process.env),E(),g(),x()]);k=S({signerReachable:v,quote:J,reviewAvailable:_,receiptAvailable:P});for(let M of k.checks)s(`hour_${M.id}`,M.status,M.detail,M.fix);s("hour_score",k.ok?"ok":"warn",k.firstRunScore.label,null)}let N={ok:!i&&(w?w.ok:!0)&&(k?k.ok:!0),checks:o,...k?{firstHour:k}:{},...w?{agentic:{pct:w.pct,summary:w.summary,attributes:w.attributes,researchMode:w.researchMode}}:{}};if(t)process.stdout.write(JSON.stringify(N,null,2)+`
7
+ `);else{for(let S of o)process.stdout.write(`${S.status.toUpperCase().padEnd(4)} ${S.id}: ${S.detail}
8
+ `),S.fix&&process.stdout.write(` fix: ${S.fix}
9
9
  `);w&&process.stdout.write(`
10
10
  ${w.summary}
11
- `)}return T.ok?0:1}};export{dg as default};
11
+ `)}return N.ok?0:1}};export{RE as default};