@oracle-agent/oracle 0.35.4 → 0.35.6

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 (40) hide show
  1. package/README.md +1 -1
  2. package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
  3. package/dist/bin/desk-server.mjs +25 -23
  4. package/dist/bin/oracle-data-mcp.mjs +13 -11
  5. package/dist/bin/oracle-gateway.mjs +35 -35
  6. package/dist/bin/oracle-mev-arb-shadow.mjs +7 -5
  7. package/dist/bin/oracle-mev-shadow.mjs +7 -5
  8. package/dist/bin/oracle-public-server.mjs +6 -4
  9. package/dist/bin/oracle-route.mjs +22 -20
  10. package/dist/bin/oracle-scan.mjs +14 -12
  11. package/dist/bin/oracle-telegram-mcp.mjs +10 -10
  12. package/dist/bin/oracle.mjs +7 -5
  13. package/dist/cli/commands/chat.mjs +166 -164
  14. package/dist/cli/commands/doctor.mjs +3 -3
  15. package/dist/cli/commands/eval.mjs +113 -113
  16. package/dist/cli/commands/farm.mjs +14 -14
  17. package/dist/cli/commands/follow.mjs +16 -14
  18. package/dist/cli/commands/model.mjs +170 -168
  19. package/dist/cli/commands/project.mjs +17 -0
  20. package/dist/cli/commands/resolve.mjs +8 -6
  21. package/dist/cli/commands/shadow.mjs +21 -0
  22. package/dist/cli/commands/signer.mjs +10 -10
  23. package/dist/cli/commands/snipe.mjs +10 -8
  24. package/dist/cli/commands/strategy.mjs +5 -5
  25. package/dist/cli/commands/swap.mjs +27 -25
  26. package/dist/cli/commands/telegram.mjs +10 -10
  27. package/dist/cli/commands/venues.mjs +2 -2
  28. package/dist/data/desk-data.mjs +23 -21
  29. package/dist/data/names.mjs +4 -2
  30. package/dist/data/providers/farming.mjs +2 -2
  31. package/dist/index.mjs +37 -35
  32. package/dist/local-signer/index.mjs +3 -3
  33. package/dist/local-signer/runtime.mjs +9 -9
  34. package/dist/nft/universal-mint-router.mjs +5 -3
  35. package/dist/router/index.mjs +4 -2
  36. package/dist/router/prepare-bridge.mjs +2 -2
  37. package/dist/scanner/index.mjs +5 -3
  38. package/dist/strategy/index.mjs +3 -3
  39. package/package.json +1 -1
  40. package/public/oracle-splash/index.html +2 -2
@@ -1,2 +1,4 @@
1
- import{keccak_256 as G}from"@noble/hashes/sha3.js";import{createHash as xe}from"node:crypto";import T from"node:net";import be from"node:dns";var ye=new Set(["localhost","metadata.google.internal","metadata.goog"]);function B(t){let e=String(t).toLowerCase().split("%")[0];if((e.match(/::/g)||[]).length>1)return null;let n=d=>{if(!d)return[];let s=d.split(":"),a=s.at(-1);if(a?.includes(".")){let c=a.split(".").map(Number);if(c.length!==4||c.some(y=>!Number.isInteger(y)||y<0||y>255))return null;s.splice(s.length-1,1,(c[0]<<8|c[1]).toString(16),(c[2]<<8|c[3]).toString(16))}return s.some(c=>!/^[0-9a-f]{1,4}$/.test(c))?null:s.map(c=>Number.parseInt(c,16))},[r,o]=e.split("::"),u=n(r),i=n(o);if(!u||!i)return null;let f=e.includes("::"),p=8-u.length-i.length;if(!f&&p!==0||f&&p<1)return null;let m=[...u,...Array(Math.max(0,p)).fill(0),...i];return m.length!==8?null:Uint8Array.from(m.flatMap(d=>[d>>8,d&255]))}function U(t,e,n){let r=Math.floor(n/8),o=n%8;for(let i=0;i<r;i+=1)if(t[i]!==e[i])return!1;if(!o)return!0;let u=255<<8-o;return(t[r]&u)===(e[r]&u)}function O(t){if(T.isIPv4(t)){let e=t.split(".").map(Number);return!(e[0]===0||e[0]===10||e[0]===127||e[0]>=224||e[0]===100&&e[1]>=64&&e[1]<=127||e[0]===169&&e[1]===254||e[0]===172&&e[1]>=16&&e[1]<=31||e[0]===192&&(e[1]===0||e[1]===2||e[1]===168)||e[0]===192&&e[1]===88&&e[2]===99||e[0]===198&&(e[1]===18||e[1]===19||e[1]===51)||e[0]===203&&e[1]===0&&e[2]===113)}if(T.isIPv6(t)){let e=B(t);if(!e)return!1;let n=B("::ffff:0:0");return U(e,n,96)?O([...e.slice(12)].join(".")):U(e,B("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([o,u])=>U(e,B(o),u)):!1}return!1}function ge(t){let e;try{e=new URL(String(t))}catch{return{ok:!1,error:`not a valid URL: ${String(t).slice(0,120)}`}}if(e.protocol!=="http:"&&e.protocol!=="https:")return{ok:!1,error:`refused protocol ${e.protocol} (only http/https)`};let n=e.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"");if(ye.has(n)||n.endsWith(".localhost")||n.endsWith(".internal"))return{ok:!1,error:`refused internal host ${n}`};let r=T.isIP(n);return r!==0&&!O(n)?{ok:!1,error:`refused private address ${n}`}:{ok:!0,url:e,host:n,isLiteralIp:r!==0}}async function F(t,{lookupFn:e=be.promises.lookup}={}){let n=ge(t);if(!n.ok)return n;if(n.isLiteralIp)return{ok:!0,url:n.url,addresses:[{address:n.host,family:T.isIPv6(n.host)?6:4}]};let r;try{r=await e(n.host,{all:!0,verbatim:!0})}catch{return{ok:!1,error:`refused: ${n.host} did not resolve`}}return!Array.isArray(r)||r.length===0||r.some(o=>!O(o.address))?{ok:!1,error:`refused: ${n.host} resolves to a non-public address`}:{ok:!0,url:n.url,addresses:r}}async function D({requireUndici:t=!1,importUndici:e=()=>import("undici")}={}){let n,r;try{let s=await e();n=s.Agent,r=s.fetch}catch(s){if(t)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${s?.message||s}`);return null}if(typeof n!="function"||typeof r!="function"){if(t)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=s=>String(s).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),u=new Map,i=s=>(Array.isArray(s)?s:[s]).map(a=>typeof a=="string"?{address:a}:a).filter(a=>a&&a.address).map(a=>({address:a.address,family:a.family||(T.isIPv6(a.address)?6:4)})),f=(s,a,c)=>{u.set(o(s),i(typeof a=="string"?[{address:a,family:c}]:a))},p=s=>{let a=o(s);if(T.isIP(a))return[{address:a,family:T.isIPv6(a)?6:4}];let c=u.get(a);if(!c||!c.length)throw new Error(`refused: unpinned host ${s} during pinned fetch`);return c},m=new n({connect:{lookup(s,a,c){let y;try{y=p(s)}catch(v){return c(v)}return a?.all?c(null,y):c(null,y[0].address,y[0].family)}}}),d=Ee((s,a={})=>r(s,{...a,dispatcher:m}),f);return{dispatcher:m,fetch:d,pin:f,resolve:p,async close(){try{await m.destroy()}catch{}}}}var j=Symbol.for("oracle.egressGuard.pinCapableFetch");function Ee(t,e){if(typeof t!="function")throw new Error("markPinCapableFetch: fetchImpl must be a function");if(typeof e!="function")throw new Error("markPinCapableFetch: pin must be a function");return t[j]=Object.freeze({pin:e}),t}function z(t){return typeof t=="function"&&typeof t[j]?.pin=="function"}function X(t,e,n){if(!z(t))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");t[j].pin(e,n)}var Re=new Set([408,425,429,500,502,503,504]),Z=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Se=2,Q=4e3,re=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],Ae=new Set([301,302,303,307,308]),ee=3,Te=64*1024;function _e(t){let e=String(t||"").toLowerCase();return re.includes(e)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(e)}function Ie(t){let e={};for(let[n,r]of Object.entries(t||{}))_e(n)||(e[n]=r);return e}function ve(t,e){if(!t)throw new Error(`HTTP redirect from ${e} missing Location`);let n=new URL(String(t),String(e));if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error(`HTTP redirect from ${e} used unsupported protocol ${n.protocol}`);return n.toString()}function Ce(t,e){return new URL(String(t)).origin===new URL(String(e)).origin}var V=new Map;function Pe(t,e,n,r={}){let o={};for(let[d,s]of Object.entries(n||{}))o[d.toLowerCase()]=s;let u=Object.keys(o).filter(d=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(d)),f=[...new Set([...re,...u])].sort().map(d=>`${d}=${o[d]??""}`).join(`
2
- `),p=xe("sha256").update(f).digest("hex").slice(0,32),m=`${r.untrustedUrl?"untrusted":"trusted"}:${r.maxResponseBytes??"unbounded"}`;return`${t} ${e} ${m} ${p}`}function ke(t,e){let n=Number(e);return Number.isFinite(n)&&n>0?Math.min(n*1e3,Q):Math.min(250*2**t,Q)+Math.floor(Math.random()*100)}var $e=t=>new Promise(e=>setTimeout(e,t));function L(t,e={}){let n=new Error(t);return n.retryable=!1,Object.assign(n,e),n}function Y(t,e,n){return L(`HTTP response from ${t} exceeded maxResponseBytes ${n} (${e})`,{oversize:!0})}function N(t){try{let e=t?.body?.cancel?.();e&&typeof e.then=="function"&&e.catch(()=>{})}catch{}}function Le(t){return t?t.byteLength??t.length??0:0}async function te(t,e,{url:n,truncate:r=!1,onOversize:o}={}){if(e==null)return await t.text();let u=Number(t.headers?.get?.("content-length"));if(Number.isFinite(u)&&u>e&&(N(t),!r))throw Y(n,`content-length ${u}`,e);let i=t.body?.getReader?.();if(!i){let s=await t.text(),a=Buffer.byteLength(s,"utf8");if(a>e){if(!r)throw Y(n,`body ${a} bytes`,e);return Buffer.from(s,"utf8").subarray(0,e).toString("utf8")}return s}let f=[],p=0,m=!1;try{for(;;){let{value:s,done:a}=await i.read();if(a)break;if(s&&(f.push(Buffer.from(s)),p+=Le(s),p>e)){m=!0;break}}}finally{if(m)try{await i.cancel()}catch{}try{i.releaseLock?.()}catch{}}if(m&&(typeof o=="function"&&o(),!r))throw Y(n,`streamed ${p} bytes`,e);let d=Buffer.concat(f);return(m?d.subarray(0,e):d).toString("utf8")}function ne(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Ne(t,{fetchImpl:e,method:n,headers:r,body:o,timeoutMs:u,lookupFn:i,realFetch:f,untrustedUrl:p=!1,maxResponseBytes:m=null,importUndici:d,validateResponse:s,signal:a}){let c=new AbortController,y=setTimeout(()=>c.abort(),u),v=a?typeof AbortSignal.any=="function"?AbortSignal.any([a,c.signal]):a:c.signal,w=null,C=e,P=i?{lookupFn:i}:{};if(p&&!f&&!z(C))throw L(`HTTP refused ${t}: untrustedUrl requires a pin-capable fetchImpl (see markPinCapableFetch in egress-guard.mjs) or no fetchImpl override so Oracle can pin the connection itself`);let k=async(h,{status:g=null}={})=>{let b=await F(h,P);if(!b.ok)throw L(g==null?`HTTP refused ${h}: ${b.error}`:`HTTP redirect to ${h} ${b.error}`,g==null?{}:{status:g});let l=new URL(h).hostname;if(f){if(w&&(await w.close(),w=null),!w)try{w=await D({requireUndici:!0,...d?{importUndici:d}:{}})}catch(E){throw L(g==null?`HTTP refused ${h}: ${E?.message||E}`:`HTTP redirect to ${h} refused: ${E?.message||E}`,g==null?{}:{status:g})}w.pin(l,b.addresses),C=w.fetch}else X(C,l,b.addresses);return b};try{let h=String(t),g={...r||{}};p&&await k(h);for(let b=0;b<=ee;b+=1){let l=await C(h,{method:n,headers:g,body:o,signal:v,redirect:"manual"});if(Ae.has(l.status)){if(n!=="GET"&&n!=="HEAD"){let R=await te(l,m??Te,{url:h,truncate:!0}),S=new Error(`HTTP ${l.status} ${n} ${h} redirected non-idempotent request`);throw S.status=l.status,S.body=ne(R)??R.slice(0,300),S}if(b===ee)throw N(l),new Error(`HTTP redirect loop for ${t}`);let x=l.headers?.get?.("location"),A;try{A=ve(x,h)}catch(R){throw N(l),R}let $=!Ce(A,h);if(N(l),$&&(g=Ie(g)),p)await k(A,{status:l.status});else if($){let R=await F(A,P);if(!R.ok){let S=new Error(`HTTP redirect from ${h} ${R.error}`);throw S.status=l.status,S.retryable=!1,S}f&&R.addresses?.length&&(w||(w=await D(d?{importUndici:d}:{})),w&&(w.pin(new URL(A).hostname,R.addresses),C=w.fetch))}h=A;continue}if(typeof s=="function")try{await s(l,{url:h})}catch(x){throw N(l),L(x?.message||String(x))}let E=await te(l,m,{url:h,onOversize:()=>c.abort()}),H=ne(E);if(!l.ok){let x=new Error(`HTTP ${l.status} ${n} ${h}`);throw x.status=l.status,x.retryAfter=l.headers?.get?.("retry-after")??null,x.body=H??E.slice(0,300),x}return H??E}throw new Error(`HTTP redirect loop for ${t}`)}finally{clearTimeout(y),w&&await w.close()}}async function oe(t,e={}){let n=e.fetchImpl||globalThis.fetch;if(typeof n!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let r=e.timeoutMs??12e3,o=(e.method||"GET").toUpperCase(),u={Accept:"application/json",...e.headers||{}},i=e.body;i!=null&&typeof i!="string"&&(u["Content-Type"]=u["Content-Type"]||"application/json",i=JSON.stringify(i));let f=Number.isInteger(e.retries)?Math.max(e.retries,0):Se,p=e.lookupFn,m=!e.fetchImpl,d=e.untrustedUrl===!0,s=e.importUndici,a=e.validateResponse,c=e.signal,y=Number(e.maxResponseBytes),v=Number.isFinite(y)&&y>0?Math.floor(y):null,w=async()=>{let g;for(let b=0;b<=f;b++){c?.throwIfAborted?.();try{return await Ne(t,{fetchImpl:n,method:o,headers:u,body:i,timeoutMs:r,lookupFn:p,realFetch:m,untrustedUrl:d,maxResponseBytes:v,importUndici:s,validateResponse:a,signal:c})}catch(l){g=l;let E=l?.status,H=l?.name==="AbortError"||l?.name==="TimeoutError"||c?.aborted,x=new Set([408,425,429]),A=l?.retryable===!1?!1:E!=null?x.has(E)||Re.has(E)&&Z.has(o):!H&&Z.has(o);if(b===f||!A)throw l;let $=ke(b,l?.retryAfter);c?await new Promise((R,S)=>{let we=setTimeout(R,$);c.addEventListener("abort",()=>{clearTimeout(we),S(c.reason||new DOMException("Aborted","AbortError"))},{once:!0})}):await $e($)}}throw g};if(!(e.dedupe!==!1&&!c&&o==="GET"&&i==null))return w();let P=Pe(o,t,u,{untrustedUrl:d,maxResponseBytes:v}),k=V.get(P);if(k)return k;let h=w().finally(()=>V.delete(P));return V.set(P,h),h}var se={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}},He=new Map(Object.values(se).map(t=>[t.chainId,t]));function ae(t){return He.get(Number(t))||null}function ce(t,e=process.env){let n=ae(t);if(!n)return null;for(let r of n.rpcEnv){let o=(e[r]||"").trim();if(o)return o}return null}import{Interface as Be,getAddress as ut}from"ethers";var lt=new Be(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);var Me={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"};function Ue(t,{rpcUrl:e,env:n=process.env}={}){if(e)return e;let r=ce(t,n);return r||Me[Number(t)]||null}var Oe=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function Fe(t){let e=String(t||""),n=e.toLowerCase();if(e!==e.trim()||!/^[a-zA-Z0-9_]+$/.test(e)||!Oe.test(n))throw new Error(`evm-rpc: ${e} refused \u2014 @oracle-agent/oracle is prepare-only (read RPC only; no broadcast/sign)`);return n}async function ie(t,e,n=[],r={}){let o=String(e||"");Fe(o);let u=Ue(t,r);if(!u)throw new Error(`No RPC URL for chainId ${t} (set env from chain registry rpcEnv or pass rpcUrl)`);let f=await oe(u,{method:"POST",body:{jsonrpc:"2.0",id:1,method:e,params:n},fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3,signal:r.signal});if(f?.error){let p=new Error(f.error.message||JSON.stringify(f.error));throw p.code=f.error.code,p}return f.result}var q=999,W=1,De=8453,ue="0x1d9d87eBc14e71490bB87f1C39F65BDB979f3cb7",je="0x4d5e4ed4D5e4A160Fa136853597cDc2eBBe66494",le="0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",ze="0xC6d566A56A1aFf6508b41f6c90ff131615583BCD",Ve=".80002105.reverse",fe=/^0x[a-fA-F0-9]{40}$/,J=new TextEncoder,de=t=>"0x"+Buffer.from(t).toString("hex"),_=t=>de(G(J.encode(t))).slice(0,10),pe=t=>t.toLowerCase().replace(/^0x/,"").padStart(64,"0");function M(t){let e=new Uint8Array(32);if(t)for(let n of String(t).split(".").reverse()){let r=G(J.encode(n)),o=new Uint8Array(64);o.set(e,0),o.set(r,32),e=G(o)}return de(e)}function K(t){if(!t||t==="0x"||/^0x0*$/.test(t))return"";try{let e=t.slice(2),n=parseInt(e.slice(0,64),16)*2,r=parseInt(e.slice(n,n+64),16);if(!Number.isFinite(r)||r<=0)return"";let o=e.slice(n+64,n+64+r*2);return Buffer.from(o,"hex").toString("utf8")}catch{return""}}function ht(t){let e=J.encode(String(t)),n=e.length.toString(16).padStart(64,"0"),r=Buffer.from(e).toString("hex").padEnd(Math.ceil(e.length/32)*64,"0");return"0000000000000000000000000000000000000000000000000000000000000020"+n+r}async function I(t,e,n){try{return await ie(t,"eth_call",[{to:e,data:n},"latest"])}catch{return null}}async function Ye(t){let e=await I(q,ue,_("primaryName(address)")+pe(t)),n=K(e);return n?n.endsWith(".hl")?n:`${n}.hl`:null}async function Ge(t){let e=await I(q,je,_("getName(address)")+pe(t)),n=K(e);return n?n.endsWith(".hype")?n:`${n}.hype`:null}async function he(t,e,n){let r=await I(t,n,_("name(bytes32)")+e.slice(2));return K(r)||null}async function We(t){let e=M(`${t.slice(2).toLowerCase()}.addr.reverse`),n=await I(W,le,_("resolver(bytes32)")+e.slice(2));if(!n)return null;let r="0x"+n.slice(-40);return/^0x0+$/.test(r)?null:he(W,e,r)}async function qe(t){let e=M(t.slice(2).toLowerCase()+Ve);return he(De,e,ze)}var me=[{source:"hl",fn:Ye},{source:"hype",fn:Ge},{source:"ens",fn:We},{source:"basename",fn:qe}];async function mt(t){if(!fe.test(String(t||"").trim()))return null;let e=String(t).trim();for(let{source:n,fn:r}of me){let o=await r(e);if(o)return{name:o,source:n,address:e}}return null}async function Je(t){let e=M(t),n=await I(q,ue,_("ownerOf(uint256)")+e.slice(2));if(!n||n.length<66)return null;let r="0x"+n.slice(-40);return/^0x0+$/.test(r)?null:r}async function Ke(t,e,n){let r=M(e),o=await I(t,n,_("resolver(bytes32)")+r.slice(2));if(!o)return null;let u="0x"+o.slice(-40);if(/^0x0+$/.test(u))return null;let i=await I(t,u,_("addr(bytes32)")+r.slice(2));if(!i)return null;let f="0x"+i.slice(-40);return/^0x0+$/.test(f)?null:f}async function Xe(t){let e=String(t||"").trim().toLowerCase();if(!e||!e.includes("."))return null;if(e.endsWith(".hl")){let n=await Je(e);return n?{address:n,source:"hl",name:e}:null}if(e.endsWith(".eth")){let n=await Ke(W,e,le);return n?{address:n,source:e.endsWith(".base.eth")?"basename":"ens",name:e}:null}return null}async function wt(t){let e=String(t||"").trim();return fe.test(e)?{address:e,source:"address",name:null}:Xe(e)}var bt=me.map(t=>t.source);export{fe as ADDRESS_RE,bt as NAME_SOURCES,K as decodeAbiString,ht as encodeAbiString,mt as lookupName,M as namehash,Xe as resolveName,wt as toAddress};
1
+ import{keccak_256 as q}from"@noble/hashes/sha3.js";import{createHash as Q}from"node:crypto";import _ from"node:net";import Se from"node:dns";var Re=new Set(["localhost","metadata.google.internal","metadata.goog"]);function M(t){let e=String(t).toLowerCase().split("%")[0];if((e.match(/::/g)||[]).length>1)return null;let n=d=>{if(!d)return[];let o=d.split(":"),s=o.at(-1);if(s?.includes(".")){let u=s.split(".").map(Number);if(u.length!==4||u.some(g=>!Number.isInteger(g)||g<0||g>255))return null;o.splice(o.length-1,1,(u[0]<<8|u[1]).toString(16),(u[2]<<8|u[3]).toString(16))}return o.some(u=>!/^[0-9a-f]{1,4}$/.test(u))?null:o.map(u=>Number.parseInt(u,16))},[r,a]=e.split("::"),i=n(r),c=n(a);if(!i||!c)return null;let m=e.includes("::"),f=8-i.length-c.length;if(!m&&f!==0||m&&f<1)return null;let p=[...i,...Array(Math.max(0,f)).fill(0),...c];return p.length!==8?null:Uint8Array.from(p.flatMap(d=>[d>>8,d&255]))}function U(t,e,n){let r=Math.floor(n/8),a=n%8;for(let c=0;c<r;c+=1)if(t[c]!==e[c])return!1;if(!a)return!0;let i=255<<8-a;return(t[r]&i)===(e[r]&i)}function F(t){if(_.isIPv4(t)){let e=t.split(".").map(Number);return!(e[0]===0||e[0]===10||e[0]===127||e[0]>=224||e[0]===100&&e[1]>=64&&e[1]<=127||e[0]===169&&e[1]===254||e[0]===172&&e[1]>=16&&e[1]<=31||e[0]===192&&(e[1]===0||e[1]===2||e[1]===168)||e[0]===192&&e[1]===88&&e[2]===99||e[0]===198&&(e[1]===18||e[1]===19||e[1]===51)||e[0]===203&&e[1]===0&&e[2]===113)}if(_.isIPv6(t)){let e=M(t);if(!e)return!1;let n=M("::ffff:0:0");return U(e,n,96)?F([...e.slice(12)].join(".")):U(e,M("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([a,i])=>U(e,M(a),i)):!1}return!1}function xe(t){let e;try{e=new URL(String(t))}catch{return{ok:!1,error:`not a valid URL: ${String(t).slice(0,120)}`}}if(e.protocol!=="http:"&&e.protocol!=="https:")return{ok:!1,error:`refused protocol ${e.protocol} (only http/https)`};let n=e.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"");if(Re.has(n)||n.endsWith(".localhost")||n.endsWith(".internal"))return{ok:!1,error:`refused internal host ${n}`};let r=_.isIP(n);return r!==0&&!F(n)?{ok:!1,error:`refused private address ${n}`}:{ok:!0,url:e,host:n,isLiteralIp:r!==0}}async function D(t,{lookupFn:e=Se.promises.lookup}={}){let n=xe(t);if(!n.ok)return n;if(n.isLiteralIp)return{ok:!0,url:n.url,addresses:[{address:n.host,family:_.isIPv6(n.host)?6:4}]};let r;try{r=await e(n.host,{all:!0,verbatim:!0})}catch{return{ok:!1,error:`refused: ${n.host} did not resolve`}}return!Array.isArray(r)||r.length===0||r.some(a=>!F(a.address))?{ok:!1,error:`refused: ${n.host} resolves to a non-public address`}:{ok:!0,url:n.url,addresses:r}}async function j({requireUndici:t=!1,importUndici:e=()=>import("undici")}={}){let n,r;try{let o=await e();n=o.Agent,r=o.fetch}catch(o){if(t)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${o?.message||o}`);return null}if(typeof n!="function"||typeof r!="function"){if(t)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 a=o=>String(o).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),i=new Map,c=o=>(Array.isArray(o)?o:[o]).map(s=>typeof s=="string"?{address:s}:s).filter(s=>s&&s.address).map(s=>({address:s.address,family:s.family||(_.isIPv6(s.address)?6:4)})),m=(o,s,u)=>{i.set(a(o),c(typeof s=="string"?[{address:s,family:u}]:s))},f=o=>{let s=a(o);if(_.isIP(s))return[{address:s,family:_.isIPv6(s)?6:4}];let u=i.get(s);if(!u||!u.length)throw new Error(`refused: unpinned host ${o} during pinned fetch`);return u},p=new n({connect:{lookup(o,s,u){let g;try{g=f(o)}catch(I){return u(I)}return s?.all?u(null,g):u(null,g[0].address,g[0].family)}}}),d=Ae((o,s={})=>r(o,{...s,dispatcher:p}),m);return{dispatcher:p,fetch:d,pin:m,resolve:f,async close(){try{await p.destroy()}catch{}}}}var z=Symbol.for("oracle.egressGuard.pinCapableFetch");function Ae(t,e){if(typeof t!="function")throw new Error("markPinCapableFetch: fetchImpl must be a function");if(typeof e!="function")throw new Error("markPinCapableFetch: pin must be a function");return t[z]=Object.freeze({pin:e}),t}function V(t){return typeof t=="function"&&typeof t[z]?.pin=="function"}function Z(t,e,n){if(!V(t))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");t[z].pin(e,n)}var _e=new Set([408,425,429,500,502,503,504]),ee=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Te=2,te=4e3,ae=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],Ce=new Set([301,302,303,307,308]),ne=3,Ie=64*1024;function ve(t){let e=String(t||"").toLowerCase();return ae.includes(e)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(e)}function Pe(t){let e={};for(let[n,r]of Object.entries(t||{}))ve(n)||(e[n]=r);return e}function ke(t,e){if(!t)throw new Error(`HTTP redirect from ${e} missing Location`);let n=new URL(String(t),String(e));if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error(`HTTP redirect from ${e} used unsupported protocol ${n.protocol}`);return n.toString()}function $e(t,e){return new URL(String(t)).origin===new URL(String(e)).origin}var Y=new Map,Ne=/(?:^|_)(send|submit|broadcast|sign|requestAirdrop)(?=[A-Z_]|$)/i,Le=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);function re(t){let e=String(t?.method||"");return e?!Ne.test(e):!1}function He(t,e){if(t==="GET"&&e==null)return!0;if(t!=="POST"||e==null)return!1;let n=e;if(typeof e=="string")try{n=JSON.parse(e)}catch{return!1}return Array.isArray(n)?n.length>0&&n.every(re):!n||typeof n!="object"?!1:n.jsonrpc&&n.method?re(n):typeof n.type=="string"&&Le.has(n.type)&&n.action==null&&n.signature==null&&n.nonce==null}function Be(t,e,n,r={},a=null){let i={};for(let[s,u]of Object.entries(n||{}))i[s.toLowerCase()]=u;let c=Object.keys(i).filter(s=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(s)),f=[...new Set([...ae,...c])].sort().map(s=>`${s}=${i[s]??""}`).join(`
2
+ `),p=Q("sha256").update(f).digest("hex").slice(0,32),d=`${r.untrustedUrl?"untrusted":"trusted"}:${r.maxResponseBytes??"unbounded"}`,o=a==null?"-":Q("sha256").update(String(a)).digest("hex").slice(0,32);return`${t} ${e} ${d} ${p} ${o}`}function Me(t,e){let n=Number(e);return Number.isFinite(n)&&n>0?Math.min(n*1e3,te):Math.min(250*2**t,te)+Math.floor(Math.random()*100)}var Oe=t=>new Promise(e=>setTimeout(e,t));function N(t,e={}){let n=new Error(t);return n.retryable=!1,Object.assign(n,e),n}function G(t,e,n){return N(`HTTP response from ${t} exceeded maxResponseBytes ${n} (${e})`,{oversize:!0})}function L(t){try{let e=t?.body?.cancel?.();e&&typeof e.then=="function"&&e.catch(()=>{})}catch{}}function Ue(t){return t?t.byteLength??t.length??0:0}async function oe(t,e,{url:n,truncate:r=!1,onOversize:a}={}){if(e==null)return await t.text();let i=Number(t.headers?.get?.("content-length"));if(Number.isFinite(i)&&i>e&&(L(t),!r))throw G(n,`content-length ${i}`,e);let c=t.body?.getReader?.();if(!c){let o=await t.text(),s=Buffer.byteLength(o,"utf8");if(s>e){if(!r)throw G(n,`body ${s} bytes`,e);return Buffer.from(o,"utf8").subarray(0,e).toString("utf8")}return o}let m=[],f=0,p=!1;try{for(;;){let{value:o,done:s}=await c.read();if(s)break;if(o&&(m.push(Buffer.from(o)),f+=Ue(o),f>e)){p=!0;break}}}finally{if(p)try{await c.cancel()}catch{}try{c.releaseLock?.()}catch{}}if(p&&(typeof a=="function"&&a(),!r))throw G(n,`streamed ${f} bytes`,e);let d=Buffer.concat(m);return(p?d.subarray(0,e):d).toString("utf8")}function se(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Fe(t,{fetchImpl:e,method:n,headers:r,body:a,timeoutMs:i,lookupFn:c,realFetch:m,untrustedUrl:f=!1,maxResponseBytes:p=null,importUndici:d,validateResponse:o,signal:s}){let u=new AbortController,g=setTimeout(()=>u.abort(),i),I=s?typeof AbortSignal.any=="function"?AbortSignal.any([s,u.signal]):s:u.signal,w=null,v=e,P=c?{lookupFn:c}:{};if(f&&!m&&!V(v))throw N(`HTTP refused ${t}: untrustedUrl requires a pin-capable fetchImpl (see markPinCapableFetch in egress-guard.mjs) or no fetchImpl override so Oracle can pin the connection itself`);let k=async(h,{status:b=null}={})=>{let y=await D(h,P);if(!y.ok)throw N(b==null?`HTTP refused ${h}: ${y.error}`:`HTTP redirect to ${h} ${y.error}`,b==null?{}:{status:b});let l=new URL(h).hostname;if(m){if(w&&(await w.close(),w=null),!w)try{w=await j({requireUndici:!0,...d?{importUndici:d}:{}})}catch(E){throw N(b==null?`HTTP refused ${h}: ${E?.message||E}`:`HTTP redirect to ${h} refused: ${E?.message||E}`,b==null?{}:{status:b})}w.pin(l,y.addresses),v=w.fetch}else Z(v,l,y.addresses);return y};try{let h=String(t),b={...r||{}};f&&await k(h);for(let y=0;y<=ne;y+=1){let l=await v(h,{method:n,headers:b,body:a,signal:I,redirect:"manual"});if(Ce.has(l.status)){if(n!=="GET"&&n!=="HEAD"){let R=await oe(l,p??Ie,{url:h,truncate:!0}),x=new Error(`HTTP ${l.status} ${n} ${h} redirected non-idempotent request`);throw x.status=l.status,x.body=se(R)??R.slice(0,300),x}if(y===ne)throw L(l),new Error(`HTTP redirect loop for ${t}`);let S=l.headers?.get?.("location"),A;try{A=ke(S,h)}catch(R){throw L(l),R}let $=!$e(A,h);if(L(l),$&&(b=Pe(b)),f)await k(A,{status:l.status});else if($){let R=await D(A,P);if(!R.ok){let x=new Error(`HTTP redirect from ${h} ${R.error}`);throw x.status=l.status,x.retryable=!1,x}m&&R.addresses?.length&&(w||(w=await j(d?{importUndici:d}:{})),w&&(w.pin(new URL(A).hostname,R.addresses),v=w.fetch))}h=A;continue}if(typeof o=="function")try{await o(l,{url:h})}catch(S){throw L(l),N(S?.message||String(S))}let E=await oe(l,p,{url:h,onOversize:()=>u.abort()}),B=se(E);if(!l.ok){let S=new Error(`HTTP ${l.status} ${n} ${h}`);throw S.status=l.status,S.retryAfter=l.headers?.get?.("retry-after")??null,S.body=B??E.slice(0,300),S}return B??E}throw new Error(`HTTP redirect loop for ${t}`)}finally{clearTimeout(g),w&&await w.close()}}async function ce(t,e={}){let n=e.fetchImpl||globalThis.fetch;if(typeof n!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let r=e.timeoutMs??12e3,a=(e.method||"GET").toUpperCase(),i={Accept:"application/json",...e.headers||{}},c=e.body;c!=null&&typeof c!="string"&&(i["Content-Type"]=i["Content-Type"]||"application/json",c=JSON.stringify(c));let m=Number.isInteger(e.retries)?Math.max(e.retries,0):Te,f=e.lookupFn,p=!e.fetchImpl,d=e.untrustedUrl===!0,o=e.importUndici,s=e.validateResponse,u=e.signal,g=Number(e.maxResponseBytes),I=Number.isFinite(g)&&g>0?Math.floor(g):null,w=async()=>{let b;for(let y=0;y<=m;y++){u?.throwIfAborted?.();try{return await Fe(t,{fetchImpl:n,method:a,headers:i,body:c,timeoutMs:r,lookupFn:f,realFetch:p,untrustedUrl:d,maxResponseBytes:I,importUndici:o,validateResponse:s,signal:u})}catch(l){b=l;let E=l?.status,B=l?.name==="AbortError"||l?.name==="TimeoutError"||u?.aborted,S=new Set([408,425,429]),A=l?.retryable===!1?!1:E!=null?S.has(E)||_e.has(E)&&ee.has(a):!B&&ee.has(a);if(y===m||!A)throw l;let $=Me(y,l?.retryAfter);u?await new Promise((R,x)=>{let Ee=setTimeout(R,$);u.addEventListener("abort",()=>{clearTimeout(Ee),x(u.reason||new DOMException("Aborted","AbortError"))},{once:!0})}):await Oe($)}}throw b};if(!(e.dedupe!==!1&&!u&&He(a,c)))return w();let P=Be(a,t,i,{untrustedUrl:d,maxResponseBytes:I},c),k=Y.get(P);if(k)return k;let h=w().finally(()=>Y.delete(P));return Y.set(P,h),h}var ie={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}},De=new Map(Object.values(ie).map(t=>[t.chainId,t]));function ue(t){return De.get(Number(t))||null}function le(t,e=process.env){let n=ue(t);if(!n)return null;for(let r of n.rpcEnv){let a=(e[r]||"").trim();if(a)return a}return null}import{Interface as je,getAddress as bt}from"ethers";var Et=new je(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);var ze={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"};function Ve(t,{rpcUrl:e,env:n=process.env}={}){if(e)return e;let r=le(t,n);return r||ze[Number(t)]||null}var Ye=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function Ge(t){let e=String(t||""),n=e.toLowerCase();if(e!==e.trim()||!/^[a-zA-Z0-9_]+$/.test(e)||!Ye.test(n))throw new Error(`evm-rpc: ${e} refused \u2014 @oracle-agent/oracle is prepare-only (read RPC only; no broadcast/sign)`);return n}var H=new Map,fe=new Map;function qe(t){let e=new Error(t?.message||JSON.stringify(t));return e.code=t?.code,e}function Je(t){if(t?.error)throw qe(t.error);return t?.result}function We(t,e,n){return`${t}
3
+ ${e}
4
+ ${JSON.stringify(n??[])}`}async function Ke(t,e,n){return ce(t,{method:"POST",body:e,fetchImpl:n.fetchImpl,timeoutMs:n.timeoutMs??12e3,signal:n.signal})}async function de(t,e,n=[],r={}){let a=String(e||""),i=Ge(a),c=Ve(t,r);if(!c)throw new Error(`No RPC URL for chainId ${t} (set env from chain registry rpcEnv or pass rpcUrl)`);if(i==="eth_chainid"&&r.cacheChainId!==!1){let d=fe.get(c);if(d!=null)return d}let f=r.dedupe!==!1&&!r.signal?We(c,a,n):null;if(f&&H.has(f))return H.get(f);let p=(async()=>{let d=await Ke(c,{jsonrpc:"2.0",id:1,method:e,params:n},r),o=Je(d);return i==="eth_chainid"&&typeof o=="string"&&fe.set(c,o),o})();return f&&(H.set(f,p),p.finally(()=>{H.get(f)===p&&H.delete(f)}).catch(()=>{})),p}var W=999,J=1,Xe=8453,pe="0x1d9d87eBc14e71490bB87f1C39F65BDB979f3cb7",Ze="0x4d5e4ed4D5e4A160Fa136853597cDc2eBBe66494",he="0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",Qe="0xC6d566A56A1aFf6508b41f6c90ff131615583BCD",et=".80002105.reverse",me=/^0x[a-fA-F0-9]{40}$/,K=new TextEncoder,we=t=>"0x"+Buffer.from(t).toString("hex"),T=t=>we(q(K.encode(t))).slice(0,10),ye=t=>t.toLowerCase().replace(/^0x/,"").padStart(64,"0");function O(t){let e=new Uint8Array(32);if(t)for(let n of String(t).split(".").reverse()){let r=q(K.encode(n)),a=new Uint8Array(64);a.set(e,0),a.set(r,32),e=q(a)}return we(e)}function X(t){if(!t||t==="0x"||/^0x0*$/.test(t))return"";try{let e=t.slice(2),n=parseInt(e.slice(0,64),16)*2,r=parseInt(e.slice(n,n+64),16);if(!Number.isFinite(r)||r<=0)return"";let a=e.slice(n+64,n+64+r*2);return Buffer.from(a,"hex").toString("utf8")}catch{return""}}function At(t){let e=K.encode(String(t)),n=e.length.toString(16).padStart(64,"0"),r=Buffer.from(e).toString("hex").padEnd(Math.ceil(e.length/32)*64,"0");return"0000000000000000000000000000000000000000000000000000000000000020"+n+r}async function C(t,e,n){try{return await de(t,"eth_call",[{to:e,data:n},"latest"])}catch{return null}}async function tt(t){let e=await C(W,pe,T("primaryName(address)")+ye(t)),n=X(e);return n?n.endsWith(".hl")?n:`${n}.hl`:null}async function nt(t){let e=await C(W,Ze,T("getName(address)")+ye(t)),n=X(e);return n?n.endsWith(".hype")?n:`${n}.hype`:null}async function ge(t,e,n){let r=await C(t,n,T("name(bytes32)")+e.slice(2));return X(r)||null}async function rt(t){let e=O(`${t.slice(2).toLowerCase()}.addr.reverse`),n=await C(J,he,T("resolver(bytes32)")+e.slice(2));if(!n)return null;let r="0x"+n.slice(-40);return/^0x0+$/.test(r)?null:ge(J,e,r)}async function ot(t){let e=O(t.slice(2).toLowerCase()+et);return ge(Xe,e,Qe)}var be=[{source:"hl",fn:tt},{source:"hype",fn:nt},{source:"ens",fn:rt},{source:"basename",fn:ot}];async function _t(t){if(!me.test(String(t||"").trim()))return null;let e=String(t).trim();return(await Promise.all(be.map(async({source:r,fn:a})=>{try{let i=await a(e);return i?{name:i,source:r,address:e}:null}catch{return null}}))).find(Boolean)||null}async function st(t){let e=O(t),n=await C(W,pe,T("ownerOf(uint256)")+e.slice(2));if(!n||n.length<66)return null;let r="0x"+n.slice(-40);return/^0x0+$/.test(r)?null:r}async function at(t,e,n){let r=O(e),a=await C(t,n,T("resolver(bytes32)")+r.slice(2));if(!a)return null;let i="0x"+a.slice(-40);if(/^0x0+$/.test(i))return null;let c=await C(t,i,T("addr(bytes32)")+r.slice(2));if(!c)return null;let m="0x"+c.slice(-40);return/^0x0+$/.test(m)?null:m}async function ct(t){let e=String(t||"").trim().toLowerCase();if(!e||!e.includes("."))return null;if(e.endsWith(".hl")){let n=await st(e);return n?{address:n,source:"hl",name:e}:null}if(e.endsWith(".eth")){let n=await at(J,e,he);return n?{address:n,source:e.endsWith(".base.eth")?"basename":"ens",name:e}:null}return null}async function Tt(t){let e=String(t||"").trim();return me.test(e)?{address:e,source:"address",name:null}:ct(e)}var Ct=be.map(t=>t.source);export{me as ADDRESS_RE,Ct as NAME_SOURCES,X as decodeAbiString,At as encodeAbiString,_t as lookupName,O as namehash,ct as resolveName,Tt as toAddress};
@@ -1,2 +1,2 @@
1
- import{createHash as ce}from"node:crypto";import M from"node:net";import ae from"node:dns";var ie=new Set(["localhost","metadata.google.internal","metadata.goog"]);function F(t){let e=String(t).toLowerCase().split("%")[0];if((e.match(/::/g)||[]).length>1)return null;let r=d=>{if(!d)return[];let i=d.split(":"),s=i.at(-1);if(s?.includes(".")){let c=s.split(".").map(Number);if(c.length!==4||c.some(m=>!Number.isInteger(m)||m<0||m>255))return null;i.splice(i.length-1,1,(c[0]<<8|c[1]).toString(16),(c[2]<<8|c[3]).toString(16))}return i.some(c=>!/^[0-9a-f]{1,4}$/.test(c))?null:i.map(c=>Number.parseInt(c,16))},[n,o]=e.split("::"),l=r(n),a=r(o);if(!l||!a)return null;let p=e.includes("::"),h=8-l.length-a.length;if(!p&&h!==0||p&&h<1)return null;let u=[...l,...Array(Math.max(0,h)).fill(0),...a];return u.length!==8?null:Uint8Array.from(u.flatMap(d=>[d>>8,d&255]))}function U(t,e,r){let n=Math.floor(r/8),o=r%8;for(let a=0;a<n;a+=1)if(t[a]!==e[a])return!1;if(!o)return!0;let l=255<<8-o;return(t[n]&l)===(e[n]&l)}function H(t){if(M.isIPv4(t)){let e=t.split(".").map(Number);return!(e[0]===0||e[0]===10||e[0]===127||e[0]>=224||e[0]===100&&e[1]>=64&&e[1]<=127||e[0]===169&&e[1]===254||e[0]===172&&e[1]>=16&&e[1]<=31||e[0]===192&&(e[1]===0||e[1]===2||e[1]===168)||e[0]===192&&e[1]===88&&e[2]===99||e[0]===198&&(e[1]===18||e[1]===19||e[1]===51)||e[0]===203&&e[1]===0&&e[2]===113)}if(M.isIPv6(t)){let e=F(t);if(!e)return!1;let r=F("::ffff:0:0");return U(e,r,96)?H([...e.slice(12)].join(".")):U(e,F("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([o,l])=>U(e,F(o),l)):!1}return!1}function se(t){let e;try{e=new URL(String(t))}catch{return{ok:!1,error:`not a valid URL: ${String(t).slice(0,120)}`}}if(e.protocol!=="http:"&&e.protocol!=="https:")return{ok:!1,error:`refused protocol ${e.protocol} (only http/https)`};let r=e.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"");if(ie.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=M.isIP(r);return n!==0&&!H(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:e,host:r,isLiteralIp:n!==0}}async function O(t,{lookupFn:e=ae.promises.lookup}={}){let r=se(t);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:M.isIPv6(r.host)?6:4}]};let n;try{n=await e(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=>!H(o.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}async function B({requireUndici:t=!1,importUndici:e=()=>import("undici")}={}){let r,n;try{let i=await e();r=i.Agent,n=i.fetch}catch(i){if(t)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${i?.message||i}`);return null}if(typeof r!="function"||typeof n!="function"){if(t)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=i=>String(i).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),l=new Map,a=i=>(Array.isArray(i)?i:[i]).map(s=>typeof s=="string"?{address:s}:s).filter(s=>s&&s.address).map(s=>({address:s.address,family:s.family||(M.isIPv6(s.address)?6:4)})),p=(i,s,c)=>{l.set(o(i),a(typeof s=="string"?[{address:s,family:c}]:s))},h=i=>{let s=o(i);if(M.isIP(s))return[{address:s,family:M.isIPv6(s)?6:4}];let c=l.get(s);if(!c||!c.length)throw new Error(`refused: unpinned host ${i} during pinned fetch`);return c},u=new r({connect:{lookup(i,s,c){let m;try{m=h(i)}catch(k){return c(k)}return s?.all?c(null,m):c(null,m[0].address,m[0].family)}}}),d=le((i,s={})=>n(i,{...s,dispatcher:u}),p);return{dispatcher:u,fetch:d,pin:p,resolve:h,async close(){try{await u.destroy()}catch{}}}}var j=Symbol.for("oracle.egressGuard.pinCapableFetch");function le(t,e){if(typeof t!="function")throw new Error("markPinCapableFetch: fetchImpl must be a function");if(typeof e!="function")throw new Error("markPinCapableFetch: pin must be a function");return t[j]=Object.freeze({pin:e}),t}function q(t){return typeof t=="function"&&typeof t[j]?.pin=="function"}function W(t,e,r){if(!q(t))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");t[j].pin(e,r)}var ue=new Set([408,425,429,500,502,503,504]),G=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),de=2,Y=4e3,Q=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],pe=new Set([301,302,303,307,308]),J=3,fe=64*1024;function he(t){let e=String(t||"").toLowerCase();return Q.includes(e)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(e)}function me(t){let e={};for(let[r,n]of Object.entries(t||{}))he(r)||(e[r]=n);return e}function ge(t,e){if(!t)throw new Error(`HTTP redirect from ${e} missing Location`);let r=new URL(String(t),String(e));if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`HTTP redirect from ${e} used unsupported protocol ${r.protocol}`);return r.toString()}function ye(t,e){return new URL(String(t)).origin===new URL(String(e)).origin}var z=new Map;function we(t,e,r,n={}){let o={};for(let[d,i]of Object.entries(r||{}))o[d.toLowerCase()]=i;let l=Object.keys(o).filter(d=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(d)),p=[...new Set([...Q,...l])].sort().map(d=>`${d}=${o[d]??""}`).join(`
2
- `),h=ce("sha256").update(p).digest("hex").slice(0,32),u=`${n.untrustedUrl?"untrusted":"trusted"}:${n.maxResponseBytes??"unbounded"}`;return`${t} ${e} ${u} ${h}`}function be(t,e){let r=Number(e);return Number.isFinite(r)&&r>0?Math.min(r*1e3,Y):Math.min(250*2**t,Y)+Math.floor(Math.random()*100)}var Ae=t=>new Promise(e=>setTimeout(e,t));function _(t,e={}){let r=new Error(t);return r.retryable=!1,Object.assign(r,e),r}function V(t,e,r){return _(`HTTP response from ${t} exceeded maxResponseBytes ${r} (${e})`,{oversize:!0})}function D(t){try{let e=t?.body?.cancel?.();e&&typeof e.then=="function"&&e.catch(()=>{})}catch{}}function ve(t){return t?t.byteLength??t.length??0:0}async function K(t,e,{url:r,truncate:n=!1,onOversize:o}={}){if(e==null)return await t.text();let l=Number(t.headers?.get?.("content-length"));if(Number.isFinite(l)&&l>e&&(D(t),!n))throw V(r,`content-length ${l}`,e);let a=t.body?.getReader?.();if(!a){let i=await t.text(),s=Buffer.byteLength(i,"utf8");if(s>e){if(!n)throw V(r,`body ${s} bytes`,e);return Buffer.from(i,"utf8").subarray(0,e).toString("utf8")}return i}let p=[],h=0,u=!1;try{for(;;){let{value:i,done:s}=await a.read();if(s)break;if(i&&(p.push(Buffer.from(i)),h+=ve(i),h>e)){u=!0;break}}}finally{if(u)try{await a.cancel()}catch{}try{a.releaseLock?.()}catch{}}if(u&&(typeof o=="function"&&o(),!n))throw V(r,`streamed ${h} bytes`,e);let d=Buffer.concat(p);return(u?d.subarray(0,e):d).toString("utf8")}function X(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Pe(t,{fetchImpl:e,method:r,headers:n,body:o,timeoutMs:l,lookupFn:a,realFetch:p,untrustedUrl:h=!1,maxResponseBytes:u=null,importUndici:d,validateResponse:i,signal:s}){let c=new AbortController,m=setTimeout(()=>c.abort(),l),k=s?typeof AbortSignal.any=="function"?AbortSignal.any([s,c.signal]):s:c.signal,y=null,T=e,x=a?{lookupFn:a}:{};if(h&&!p&&!q(T))throw _(`HTTP refused ${t}: untrustedUrl requires a pin-capable fetchImpl (see markPinCapableFetch in egress-guard.mjs) or no fetchImpl override so Oracle can pin the connection itself`);let I=async(g,{status:b=null}={})=>{let w=await O(g,x);if(!w.ok)throw _(b==null?`HTTP refused ${g}: ${w.error}`:`HTTP redirect to ${g} ${w.error}`,b==null?{}:{status:b});let f=new URL(g).hostname;if(p){if(y&&(await y.close(),y=null),!y)try{y=await B({requireUndici:!0,...d?{importUndici:d}:{}})}catch(A){throw _(b==null?`HTTP refused ${g}: ${A?.message||A}`:`HTTP redirect to ${g} refused: ${A?.message||A}`,b==null?{}:{status:b})}y.pin(f,w.addresses),T=y.fetch}else W(T,f,w.addresses);return w};try{let g=String(t),b={...n||{}};h&&await I(g);for(let w=0;w<=J;w+=1){let f=await T(g,{method:r,headers:b,body:o,signal:k,redirect:"manual"});if(pe.has(f.status)){if(r!=="GET"&&r!=="HEAD"){let P=await K(f,u??fe,{url:g,truncate:!0}),E=new Error(`HTTP ${f.status} ${r} ${g} redirected non-idempotent request`);throw E.status=f.status,E.body=X(P)??P.slice(0,300),E}if(w===J)throw D(f),new Error(`HTTP redirect loop for ${t}`);let v=f.headers?.get?.("location"),$;try{$=ge(v,g)}catch(P){throw D(f),P}let R=!ye($,g);if(D(f),R&&(b=me(b)),h)await I($,{status:f.status});else if(R){let P=await O($,x);if(!P.ok){let E=new Error(`HTTP redirect from ${g} ${P.error}`);throw E.status=f.status,E.retryable=!1,E}p&&P.addresses?.length&&(y||(y=await B(d?{importUndici:d}:{})),y&&(y.pin(new URL($).hostname,P.addresses),T=y.fetch))}g=$;continue}if(typeof i=="function")try{await i(f,{url:g})}catch(v){throw D(f),_(v?.message||String(v))}let A=await K(f,u,{url:g,onOversize:()=>c.abort()}),N=X(A);if(!f.ok){let v=new Error(`HTTP ${f.status} ${r} ${g}`);throw v.status=f.status,v.retryAfter=f.headers?.get?.("retry-after")??null,v.body=N??A.slice(0,300),v}return N??A}throw new Error(`HTTP redirect loop for ${t}`)}finally{clearTimeout(m),y&&await y.close()}}async function Z(t,e={}){let r=e.fetchImpl||globalThis.fetch;if(typeof r!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let n=e.timeoutMs??12e3,o=(e.method||"GET").toUpperCase(),l={Accept:"application/json",...e.headers||{}},a=e.body;a!=null&&typeof a!="string"&&(l["Content-Type"]=l["Content-Type"]||"application/json",a=JSON.stringify(a));let p=Number.isInteger(e.retries)?Math.max(e.retries,0):de,h=e.lookupFn,u=!e.fetchImpl,d=e.untrustedUrl===!0,i=e.importUndici,s=e.validateResponse,c=e.signal,m=Number(e.maxResponseBytes),k=Number.isFinite(m)&&m>0?Math.floor(m):null,y=async()=>{let b;for(let w=0;w<=p;w++){c?.throwIfAborted?.();try{return await Pe(t,{fetchImpl:r,method:o,headers:l,body:a,timeoutMs:n,lookupFn:h,realFetch:u,untrustedUrl:d,maxResponseBytes:k,importUndici:i,validateResponse:s,signal:c})}catch(f){b=f;let A=f?.status,N=f?.name==="AbortError"||f?.name==="TimeoutError"||c?.aborted,v=new Set([408,425,429]),$=f?.retryable===!1?!1:A!=null?v.has(A)||ue.has(A)&&G.has(o):!N&&G.has(o);if(w===p||!$)throw f;let R=be(w,f?.retryAfter);c?await new Promise((P,E)=>{let oe=setTimeout(P,R);c.addEventListener("abort",()=>{clearTimeout(oe),E(c.reason||new DOMException("Aborted","AbortError"))},{once:!0})}):await Ae(R)}}throw b};if(!(e.dedupe!==!1&&!c&&o==="GET"&&a==null))return y();let x=we(o,t,l,{untrustedUrl:d,maxResponseBytes:k}),I=z.get(x);if(I)return I;let g=y().finally(()=>z.delete(x));return z.set(x,g),g}var ke="https://yields.llama.fi";async function ee(t={},e={}){let r=(e.yieldsBaseUrl||process.env.DEFILLAMA_YIELDS_URL||ke).replace(/\/$/,""),n=await Z(`${r}/pools`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??3e4}),o=Array.isArray(n?.data)?n.data:[];t.chain&&(o=o.filter(a=>String(a.chain).toLowerCase()===String(t.chain).toLowerCase())),t.project&&(o=o.filter(a=>String(a.project).toLowerCase()===String(t.project).toLowerCase())),t.stablecoin!=null&&(o=o.filter(a=>!!a.stablecoin==!!t.stablecoin)),o.sort((a,p)=>Number(p.tvlUsd||0)-Number(a.tvlUsd||0));let l=Math.min(5e3,Math.max(1,Number(t.limit||o.length||1)));return{...n,data:o.slice(0,l)}}var xe=Object.freeze([{id:"stable-loop",label:"Stablecoin loop",risk:"Conservative",targetDelta:"0.00",setup:"Supply USDC, borrow a second major stable, redeposit inside the same protocol or campaign.",exposure:"Borrow APR spike, depeg, collateral-factor change, protocol cap change.",hedge:"No perp hedge by default. Cap leverage, diversify stables, and keep unwind triggers explicit.",monitor:"Borrow APR, utilization, oracle health, depeg distance, reward dilution.",exit:"Unwind if borrow APR exceeds reward-adjusted APR or any stable trades outside the defined band."},{id:"collateral-hedge",label:"Collateral plus perp hedge",risk:"Balanced",targetDelta:"~0.00",setup:"Supply a volatile asset as collateral, borrow stables, and short the collateral notional on a liquid perp venue.",exposure:"Liquidation risk, funding cost, hedge slippage, borrow APR drift.",hedge:"Short collateral notional on a liquid perp venue; rebalance when delta drifts past the band.",monitor:"Health factor, funding, mark price, borrow APR, hedge margin.",exit:"Cut when funding turns persistently negative against the position or health factor nears the floor."},{id:"lp-hedge",label:"LP incentive hedge",risk:"Aggressive",targetDelta:"range-dependent",setup:"Provide concentrated liquidity for incentives and short the estimated volatile-token delta.",exposure:"Impermanent loss, range breaks, reward dilution, exit slippage.",hedge:"Short the estimated volatile-token delta and recompute after material price or range moves.",monitor:"Position delta, range utilization, fee APR, rewards, funding, exit slippage.",exit:"Withdraw when incentives dilute, liquidity caps fill, or expected reward no longer beats IL plus opportunity cost."},{id:"quest-farming",label:"Testnet and quest farming",risk:"Conservative",targetDelta:"n/a",setup:"Complete real protocol tasks with consistent, genuine usage from wallets you actually control.",exposure:"Eligibility rules change, sybil filters, unpaid effort, opportunity cost.",hedge:"No financial hedge. Diversify across campaigns so no single ruleset dominates the outcome.",monitor:"Campaign rules, snapshot windows, task eligibility evidence, wallet hygiene.",exit:"Stop once snapshot risk rises, campaign rules change, or the probability-adjusted expected value turns negative."},{id:"liquidity-usage",label:"Liquidity and route usage",risk:"Balanced",targetDelta:"varies",setup:"Route genuine volume and provide liquidity where usage is a stated eligibility signal.",exposure:"IL, slippage, gas burn, bridge fees, lockup discount.",hedge:"Size positions so IL and fees stay inside the modelled reward, and hedge volatile legs when material.",monitor:"Volume attribution, fee drag, reward accrual, lockup terms.",exit:"Withdraw when incentives dilute or expected reward no longer beats IL plus opportunity cost."},{id:"governance-usage",label:"Governance and ecosystem usage",risk:"Conservative",targetDelta:"n/a",setup:"Participate in governance and ecosystem surfaces where real contribution is the eligibility signal.",exposure:"Vanity activity with no eligibility weight, lock-up of governance assets.",hedge:"No financial hedge. Weight effort toward actions with documented eligibility evidence.",monitor:"Proposal participation, delegation terms, lock durations, published criteria.",exit:"Stop contributing effort once criteria change or the probability-adjusted value turns negative."}]),Se={"stable-loop":"No default perp hedge. Bound leverage and monitor depeg plus borrow APR.","collateral-hedge":"Short the collateral notional on a liquid perp venue and rebalance when delta drifts.","lp-hedge":"Short the estimated volatile-token delta and recompute after material price or range moves."},Te={"stable-loop":"Borrow APR, utilization, stable peg, reward dilution, health factor.","collateral-hedge":"Health factor, funding, mark price, borrow APR, hedge margin.","lp-hedge":"Position delta, range utilization, fee APR, rewards, funding, exit slippage."},Ee={"stable-loop":["Prepare supply for the stable collateral leg.","Prepare borrow only after health factor and borrow APR pass the method limits.","Prepare redeposit or unwind steps as separate wallet-signed actions."],"collateral-hedge":["Prepare collateral supply after sizing liquidation buffer.","Prepare stable borrow if borrow APR remains inside the method limit.","Open or adjust the perp short on the selected hedge venue, then record hedge size."],"lp-hedge":["Prepare LP add only after checking pool depth, range, and expected position delta.","Short the estimated volatile-token delta on the selected hedge venue.","Prepare LP remove if the range breaks or net APR turns negative."]};function C(t){let e=typeof t=="number"?t:Number(t);return Number.isFinite(e)?e:null}function L(t,e="unknown"){if(typeof t!="string")return e;let r=t.trim();return r===""?e:r.slice(0,96)}function te(t){let e=L(t.symbol,"").toUpperCase(),r=L(t.exposure,"").toLowerCase(),n=C(t.apy)??0,o=C(t.tvlUsd)??0;return n<=0||o<=0?null:t.stablecoin===!0?"stable-loop":e.includes("-")||r.includes("multi")?"lp-hedge":/ETH|BTC|SOL|HYPE|BNB|AVAX|MATIC|OP|ARB/.test(e)?"collateral-hedge":null}function re(t,e){let r=C(t.tvlUsd)??0,n=L(t.ilRisk,"").toLowerCase(),o=L(t.predictions?.predictedClass,"").toLowerCase(),l=e==="stable-loop"?3:e==="collateral-hedge"?6:9;return r<1e6?l+=6:r<1e7&&(l+=3),(n.includes("yes")||n.includes("high"))&&(l+=3),o.includes("down")&&(l+=2),Math.min(35,Math.max(0,l))}function ne(t){let e=te(t);if(!e)return null;let r=C(t.apy)??0,n=C(t.apyBase)??0,o=Math.max(0,C(t.apyReward)??Math.max(0,r-n)),l=Math.max(0,C(t.tvlUsd)??0),a=re(t,e),p=e==="stable-loop"?4:e==="collateral-hedge"?6:0,h=e==="stable-loop"?0:e==="collateral-hedge"?4:5,u=l<5e6?1.2:.5,d=r-p-h-u-a,i=d<1?"Avoid":r>80||l<1e7?"Watchlist":d>=8?"Farmable":"Watchlist",s=L(t.project),c=L(t.symbol),m=L(t.chain);return{id:L(t.pool,`${m}:${s}:${c}`),recipe:e,label:`${s} ${c}`,chain:m,project:s,symbol:c,tvlUsd:l,rewardApr:o,nativeApr:n,estimatedBorrowApr:p,estimatedFundingApr:h,gasApr:u,riskHaircut:a,netApr:d,verdict:i,exposure:L(t.exposure,e==="stable-loop"?"stablecoin":e==="lp-hedge"?"multi-asset LP":"single-asset collateral"),hedge:Se[e],monitor:Te[e],prepareSteps:[`Verify ${s} contracts and reward terms on ${m}.`,"Set wallet grant with chain, protocol, max value, slippage, and TTL before preparing any transaction.",...Ee[e]],source:"DeFiLlama yields"}}async function Le(t={},e={}){let r=Math.min(24,Math.max(3,Number(t.limit??12)||12)),n=Number(t.minTvl??2e6),o=new Date().toISOString(),l="read-only discovery and prepare-plan design; no signing or broadcast";try{let a=await ee({chain:t.chain&&t.chain!=="all"?t.chain:void 0,limit:5e3},e),p=Array.isArray(a?.data)?a.data:[],h=p.map(ne).filter(u=>u!==null).filter(u=>u.tvlUsd>=n).filter(u=>u.rewardApr+u.nativeApr<=300).sort((u,d)=>d.netApr-u.netApr||d.tvlUsd-u.tvlUsd).slice(0,r);return{configured:!0,live:!0,source:"DeFiLlama yields",generatedAt:o,chain:t.chain??"all",considered:p.length,consideredNote:"deepest pools by TVL from the DeFiLlama yields feed",candidates:h,posture:l}}catch(a){return{configured:!1,live:!1,source:"DeFiLlama yields",generatedAt:o,chain:t.chain??"all",considered:0,consideredNote:"deepest pools by TVL from the DeFiLlama yields feed",error:String(a?.message||a),candidates:[],posture:l}}}function S(t,e,r,n){let o=typeof t=="number"?t:Number(t);return Number.isFinite(o)?Math.min(n,Math.max(r,o)):e}function $e(t={}){let e=S(t.wallets,5,1,500),r=S(t.tasksWeekly,6,0,500),n=S(t.hoursWeekly,4,0,168),o=S(t.hourlyCost,25,0,1e4),l=S(t.gasPerTask,.4,0,1e4),a=S(t.bridgeMonthly,12,0,1e5),p=S(t.expectedReward,900,0,1e7),h=S(t.probability,22,0,100)/100,u=S(t.sybilHaircut,25,0,100)/100,d=S(t.lockupMonths,6,0,120),i=r*e*4.33,s=i*l,c=n*4.33*o,m=s+c+a,k=Math.max(0,1-d*.015),y=e*p*h,T=y*(1-u)*k,x=T-m,I=m>0?x/m*100:null,g=e*p>0?m/(e*p*(1-u)*(k||1))*100:null;return{inputs:{wallets:e,tasksWeekly:r,hoursWeekly:n,hourlyCost:o,gasPerTask:l,bridgeMonthly:a,expectedReward:p,probabilityPct:h*100,sybilHaircutPct:u*100,lockupMonths:d},monthlyTasks:i,monthlyGas:s,laborMonthly:c,monthlyCost:m,lockupDiscount:k,grossExpectedValue:y,adjustedExpectedValue:T,netExpectedValue:x,roiPct:I,breakevenProbabilityPct:g,verdict:x>0?"positive-ev":"negative-ev",posture:"estimate on your own inputs; not a payout promise and not financial advice"}}var He={FARMING_METHODS:xe,discoverFarms:Le,scorePool:ne,classifyPool:te,riskHaircut:re,airdropEV:$e};export{xe as FARMING_METHODS,$e as airdropEV,te as classifyPool,He as default,Le as discoverFarms,re as riskHaircut,ne as scorePool};
1
+ import{createHash as Y}from"node:crypto";import M from"node:net";import se from"node:dns";var le=new Set(["localhost","metadata.google.internal","metadata.goog"]);function F(t){let e=String(t).toLowerCase().split("%")[0];if((e.match(/::/g)||[]).length>1)return null;let r=d=>{if(!d)return[];let s=d.split(":"),o=s.at(-1);if(o?.includes(".")){let c=o.split(".").map(Number);if(c.length!==4||c.some(m=>!Number.isInteger(m)||m<0||m>255))return null;s.splice(s.length-1,1,(c[0]<<8|c[1]).toString(16),(c[2]<<8|c[3]).toString(16))}return s.some(c=>!/^[0-9a-f]{1,4}$/.test(c))?null:s.map(c=>Number.parseInt(c,16))},[n,a]=e.split("::"),l=r(n),i=r(a);if(!l||!i)return null;let p=e.includes("::"),h=8-l.length-i.length;if(!p&&h!==0||p&&h<1)return null;let u=[...l,...Array(Math.max(0,h)).fill(0),...i];return u.length!==8?null:Uint8Array.from(u.flatMap(d=>[d>>8,d&255]))}function H(t,e,r){let n=Math.floor(r/8),a=r%8;for(let i=0;i<n;i+=1)if(t[i]!==e[i])return!1;if(!a)return!0;let l=255<<8-a;return(t[n]&l)===(e[n]&l)}function O(t){if(M.isIPv4(t)){let e=t.split(".").map(Number);return!(e[0]===0||e[0]===10||e[0]===127||e[0]>=224||e[0]===100&&e[1]>=64&&e[1]<=127||e[0]===169&&e[1]===254||e[0]===172&&e[1]>=16&&e[1]<=31||e[0]===192&&(e[1]===0||e[1]===2||e[1]===168)||e[0]===192&&e[1]===88&&e[2]===99||e[0]===198&&(e[1]===18||e[1]===19||e[1]===51)||e[0]===203&&e[1]===0&&e[2]===113)}if(M.isIPv6(t)){let e=F(t);if(!e)return!1;let r=F("::ffff:0:0");return H(e,r,96)?O([...e.slice(12)].join(".")):H(e,F("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([a,l])=>H(e,F(a),l)):!1}return!1}function ce(t){let e;try{e=new URL(String(t))}catch{return{ok:!1,error:`not a valid URL: ${String(t).slice(0,120)}`}}if(e.protocol!=="http:"&&e.protocol!=="https:")return{ok:!1,error:`refused protocol ${e.protocol} (only http/https)`};let r=e.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"");if(le.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=M.isIP(r);return n!==0&&!O(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:e,host:r,isLiteralIp:n!==0}}async function U(t,{lookupFn:e=se.promises.lookup}={}){let r=ce(t);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:M.isIPv6(r.host)?6:4}]};let n;try{n=await e(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(a=>!O(a.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}async function B({requireUndici:t=!1,importUndici:e=()=>import("undici")}={}){let r,n;try{let s=await e();r=s.Agent,n=s.fetch}catch(s){if(t)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${s?.message||s}`);return null}if(typeof r!="function"||typeof n!="function"){if(t)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 a=s=>String(s).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),l=new Map,i=s=>(Array.isArray(s)?s:[s]).map(o=>typeof o=="string"?{address:o}:o).filter(o=>o&&o.address).map(o=>({address:o.address,family:o.family||(M.isIPv6(o.address)?6:4)})),p=(s,o,c)=>{l.set(a(s),i(typeof o=="string"?[{address:o,family:c}]:o))},h=s=>{let o=a(s);if(M.isIP(o))return[{address:o,family:M.isIPv6(o)?6:4}];let c=l.get(o);if(!c||!c.length)throw new Error(`refused: unpinned host ${s} during pinned fetch`);return c},u=new r({connect:{lookup(s,o,c){let m;try{m=h(s)}catch(P){return c(P)}return o?.all?c(null,m):c(null,m[0].address,m[0].family)}}}),d=ue((s,o={})=>n(s,{...o,dispatcher:u}),p);return{dispatcher:u,fetch:d,pin:p,resolve:h,async close(){try{await u.destroy()}catch{}}}}var j=Symbol.for("oracle.egressGuard.pinCapableFetch");function ue(t,e){if(typeof t!="function")throw new Error("markPinCapableFetch: fetchImpl must be a function");if(typeof e!="function")throw new Error("markPinCapableFetch: pin must be a function");return t[j]=Object.freeze({pin:e}),t}function q(t){return typeof t=="function"&&typeof t[j]?.pin=="function"}function V(t,e,r){if(!q(t))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");t[j].pin(e,r)}var de=new Set([408,425,429,500,502,503,504]),G=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),pe=2,J=4e3,ee=["authorization","x-api-key","x-tensor-api-key","0x-api-key","api-key","cookie","proxy-authorization"],fe=new Set([301,302,303,307,308]),K=3,he=64*1024;function me(t){let e=String(t||"").toLowerCase();return ee.includes(e)||/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(e)}function ge(t){let e={};for(let[r,n]of Object.entries(t||{}))me(r)||(e[r]=n);return e}function ye(t,e){if(!t)throw new Error(`HTTP redirect from ${e} missing Location`);let r=new URL(String(t),String(e));if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`HTTP redirect from ${e} used unsupported protocol ${r.protocol}`);return r.toString()}function we(t,e){return new URL(String(t)).origin===new URL(String(e)).origin}var z=new Map,be=/(?:^|_)(send|submit|broadcast|sign|requestAirdrop)(?=[A-Z_]|$)/i,Ae=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);function X(t){let e=String(t?.method||"");return e?!be.test(e):!1}function Se(t,e){if(t==="GET"&&e==null)return!0;if(t!=="POST"||e==null)return!1;let r=e;if(typeof e=="string")try{r=JSON.parse(e)}catch{return!1}return Array.isArray(r)?r.length>0&&r.every(X):!r||typeof r!="object"?!1:r.jsonrpc&&r.method?X(r):typeof r.type=="string"&&Ae.has(r.type)&&r.action==null&&r.signature==null&&r.nonce==null}function ve(t,e,r,n={},a=null){let l={};for(let[o,c]of Object.entries(r||{}))l[o.toLowerCase()]=c;let i=Object.keys(l).filter(o=>/(^|-)(api[-_]?key|key|token|secret|auth|authorization|session|cookie|signature|access)(-|$)/.test(o)),h=[...new Set([...ee,...i])].sort().map(o=>`${o}=${l[o]??""}`).join(`
2
+ `),u=Y("sha256").update(h).digest("hex").slice(0,32),d=`${n.untrustedUrl?"untrusted":"trusted"}:${n.maxResponseBytes??"unbounded"}`,s=a==null?"-":Y("sha256").update(String(a)).digest("hex").slice(0,32);return`${t} ${e} ${d} ${u} ${s}`}function Pe(t,e){let r=Number(e);return Number.isFinite(r)&&r>0?Math.min(r*1e3,J):Math.min(250*2**t,J)+Math.floor(Math.random()*100)}var ke=t=>new Promise(e=>setTimeout(e,t));function _(t,e={}){let r=new Error(t);return r.retryable=!1,Object.assign(r,e),r}function W(t,e,r){return _(`HTTP response from ${t} exceeded maxResponseBytes ${r} (${e})`,{oversize:!0})}function D(t){try{let e=t?.body?.cancel?.();e&&typeof e.then=="function"&&e.catch(()=>{})}catch{}}function xe(t){return t?t.byteLength??t.length??0:0}async function Z(t,e,{url:r,truncate:n=!1,onOversize:a}={}){if(e==null)return await t.text();let l=Number(t.headers?.get?.("content-length"));if(Number.isFinite(l)&&l>e&&(D(t),!n))throw W(r,`content-length ${l}`,e);let i=t.body?.getReader?.();if(!i){let s=await t.text(),o=Buffer.byteLength(s,"utf8");if(o>e){if(!n)throw W(r,`body ${o} bytes`,e);return Buffer.from(s,"utf8").subarray(0,e).toString("utf8")}return s}let p=[],h=0,u=!1;try{for(;;){let{value:s,done:o}=await i.read();if(o)break;if(s&&(p.push(Buffer.from(s)),h+=xe(s),h>e)){u=!0;break}}}finally{if(u)try{await i.cancel()}catch{}try{i.releaseLock?.()}catch{}}if(u&&(typeof a=="function"&&a(),!n))throw W(r,`streamed ${h} bytes`,e);let d=Buffer.concat(p);return(u?d.subarray(0,e):d).toString("utf8")}function Q(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Te(t,{fetchImpl:e,method:r,headers:n,body:a,timeoutMs:l,lookupFn:i,realFetch:p,untrustedUrl:h=!1,maxResponseBytes:u=null,importUndici:d,validateResponse:s,signal:o}){let c=new AbortController,m=setTimeout(()=>c.abort(),l),P=o?typeof AbortSignal.any=="function"?AbortSignal.any([o,c.signal]):o:c.signal,y=null,T=e,k=i?{lookupFn:i}:{};if(h&&!p&&!q(T))throw _(`HTTP refused ${t}: untrustedUrl requires a pin-capable fetchImpl (see markPinCapableFetch in egress-guard.mjs) or no fetchImpl override so Oracle can pin the connection itself`);let I=async(g,{status:b=null}={})=>{let w=await U(g,k);if(!w.ok)throw _(b==null?`HTTP refused ${g}: ${w.error}`:`HTTP redirect to ${g} ${w.error}`,b==null?{}:{status:b});let f=new URL(g).hostname;if(p){if(y&&(await y.close(),y=null),!y)try{y=await B({requireUndici:!0,...d?{importUndici:d}:{}})}catch(A){throw _(b==null?`HTTP refused ${g}: ${A?.message||A}`:`HTTP redirect to ${g} refused: ${A?.message||A}`,b==null?{}:{status:b})}y.pin(f,w.addresses),T=y.fetch}else V(T,f,w.addresses);return w};try{let g=String(t),b={...n||{}};h&&await I(g);for(let w=0;w<=K;w+=1){let f=await T(g,{method:r,headers:b,body:a,signal:P,redirect:"manual"});if(fe.has(f.status)){if(r!=="GET"&&r!=="HEAD"){let v=await Z(f,u??he,{url:g,truncate:!0}),E=new Error(`HTTP ${f.status} ${r} ${g} redirected non-idempotent request`);throw E.status=f.status,E.body=Q(v)??v.slice(0,300),E}if(w===K)throw D(f),new Error(`HTTP redirect loop for ${t}`);let S=f.headers?.get?.("location"),$;try{$=ye(S,g)}catch(v){throw D(f),v}let C=!we($,g);if(D(f),C&&(b=ge(b)),h)await I($,{status:f.status});else if(C){let v=await U($,k);if(!v.ok){let E=new Error(`HTTP redirect from ${g} ${v.error}`);throw E.status=f.status,E.retryable=!1,E}p&&v.addresses?.length&&(y||(y=await B(d?{importUndici:d}:{})),y&&(y.pin(new URL($).hostname,v.addresses),T=y.fetch))}g=$;continue}if(typeof s=="function")try{await s(f,{url:g})}catch(S){throw D(f),_(S?.message||String(S))}let A=await Z(f,u,{url:g,onOversize:()=>c.abort()}),N=Q(A);if(!f.ok){let S=new Error(`HTTP ${f.status} ${r} ${g}`);throw S.status=f.status,S.retryAfter=f.headers?.get?.("retry-after")??null,S.body=N??A.slice(0,300),S}return N??A}throw new Error(`HTTP redirect loop for ${t}`)}finally{clearTimeout(m),y&&await y.close()}}async function te(t,e={}){let r=e.fetchImpl||globalThis.fetch;if(typeof r!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let n=e.timeoutMs??12e3,a=(e.method||"GET").toUpperCase(),l={Accept:"application/json",...e.headers||{}},i=e.body;i!=null&&typeof i!="string"&&(l["Content-Type"]=l["Content-Type"]||"application/json",i=JSON.stringify(i));let p=Number.isInteger(e.retries)?Math.max(e.retries,0):pe,h=e.lookupFn,u=!e.fetchImpl,d=e.untrustedUrl===!0,s=e.importUndici,o=e.validateResponse,c=e.signal,m=Number(e.maxResponseBytes),P=Number.isFinite(m)&&m>0?Math.floor(m):null,y=async()=>{let b;for(let w=0;w<=p;w++){c?.throwIfAborted?.();try{return await Te(t,{fetchImpl:r,method:a,headers:l,body:i,timeoutMs:n,lookupFn:h,realFetch:u,untrustedUrl:d,maxResponseBytes:P,importUndici:s,validateResponse:o,signal:c})}catch(f){b=f;let A=f?.status,N=f?.name==="AbortError"||f?.name==="TimeoutError"||c?.aborted,S=new Set([408,425,429]),$=f?.retryable===!1?!1:A!=null?S.has(A)||de.has(A)&&G.has(a):!N&&G.has(a);if(w===p||!$)throw f;let C=Pe(w,f?.retryAfter);c?await new Promise((v,E)=>{let ie=setTimeout(v,C);c.addEventListener("abort",()=>{clearTimeout(ie),E(c.reason||new DOMException("Aborted","AbortError"))},{once:!0})}):await ke(C)}}throw b};if(!(e.dedupe!==!1&&!c&&Se(a,i)))return y();let k=ve(a,t,l,{untrustedUrl:d,maxResponseBytes:P},i),I=z.get(k);if(I)return I;let g=y().finally(()=>z.delete(k));return z.set(k,g),g}var Ee="https://yields.llama.fi";async function re(t={},e={}){let r=(e.yieldsBaseUrl||process.env.DEFILLAMA_YIELDS_URL||Ee).replace(/\/$/,""),n=await te(`${r}/pools`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??3e4}),a=Array.isArray(n?.data)?n.data:[];t.chain&&(a=a.filter(i=>String(i.chain).toLowerCase()===String(t.chain).toLowerCase())),t.project&&(a=a.filter(i=>String(i.project).toLowerCase()===String(t.project).toLowerCase())),t.stablecoin!=null&&(a=a.filter(i=>!!i.stablecoin==!!t.stablecoin)),a.sort((i,p)=>Number(p.tvlUsd||0)-Number(i.tvlUsd||0));let l=Math.min(5e3,Math.max(1,Number(t.limit||a.length||1)));return{...n,data:a.slice(0,l)}}var Le=Object.freeze([{id:"stable-loop",label:"Stablecoin loop",risk:"Conservative",targetDelta:"0.00",setup:"Supply USDC, borrow a second major stable, redeposit inside the same protocol or campaign.",exposure:"Borrow APR spike, depeg, collateral-factor change, protocol cap change.",hedge:"No perp hedge by default. Cap leverage, diversify stables, and keep unwind triggers explicit.",monitor:"Borrow APR, utilization, oracle health, depeg distance, reward dilution.",exit:"Unwind if borrow APR exceeds reward-adjusted APR or any stable trades outside the defined band."},{id:"collateral-hedge",label:"Collateral plus perp hedge",risk:"Balanced",targetDelta:"~0.00",setup:"Supply a volatile asset as collateral, borrow stables, and short the collateral notional on a liquid perp venue.",exposure:"Liquidation risk, funding cost, hedge slippage, borrow APR drift.",hedge:"Short collateral notional on a liquid perp venue; rebalance when delta drifts past the band.",monitor:"Health factor, funding, mark price, borrow APR, hedge margin.",exit:"Cut when funding turns persistently negative against the position or health factor nears the floor."},{id:"lp-hedge",label:"LP incentive hedge",risk:"Aggressive",targetDelta:"range-dependent",setup:"Provide concentrated liquidity for incentives and short the estimated volatile-token delta.",exposure:"Impermanent loss, range breaks, reward dilution, exit slippage.",hedge:"Short the estimated volatile-token delta and recompute after material price or range moves.",monitor:"Position delta, range utilization, fee APR, rewards, funding, exit slippage.",exit:"Withdraw when incentives dilute, liquidity caps fill, or expected reward no longer beats IL plus opportunity cost."},{id:"quest-farming",label:"Testnet and quest farming",risk:"Conservative",targetDelta:"n/a",setup:"Complete real protocol tasks with consistent, genuine usage from wallets you actually control.",exposure:"Eligibility rules change, sybil filters, unpaid effort, opportunity cost.",hedge:"No financial hedge. Diversify across campaigns so no single ruleset dominates the outcome.",monitor:"Campaign rules, snapshot windows, task eligibility evidence, wallet hygiene.",exit:"Stop once snapshot risk rises, campaign rules change, or the probability-adjusted expected value turns negative."},{id:"liquidity-usage",label:"Liquidity and route usage",risk:"Balanced",targetDelta:"varies",setup:"Route genuine volume and provide liquidity where usage is a stated eligibility signal.",exposure:"IL, slippage, gas burn, bridge fees, lockup discount.",hedge:"Size positions so IL and fees stay inside the modelled reward, and hedge volatile legs when material.",monitor:"Volume attribution, fee drag, reward accrual, lockup terms.",exit:"Withdraw when incentives dilute or expected reward no longer beats IL plus opportunity cost."},{id:"governance-usage",label:"Governance and ecosystem usage",risk:"Conservative",targetDelta:"n/a",setup:"Participate in governance and ecosystem surfaces where real contribution is the eligibility signal.",exposure:"Vanity activity with no eligibility weight, lock-up of governance assets.",hedge:"No financial hedge. Weight effort toward actions with documented eligibility evidence.",monitor:"Proposal participation, delegation terms, lock durations, published criteria.",exit:"Stop contributing effort once criteria change or the probability-adjusted value turns negative."}]),$e={"stable-loop":"No default perp hedge. Bound leverage and monitor depeg plus borrow APR.","collateral-hedge":"Short the collateral notional on a liquid perp venue and rebalance when delta drifts.","lp-hedge":"Short the estimated volatile-token delta and recompute after material price or range moves."},Ie={"stable-loop":"Borrow APR, utilization, stable peg, reward dilution, health factor.","collateral-hedge":"Health factor, funding, mark price, borrow APR, hedge margin.","lp-hedge":"Position delta, range utilization, fee APR, rewards, funding, exit slippage."},Me={"stable-loop":["Prepare supply for the stable collateral leg.","Prepare borrow only after health factor and borrow APR pass the method limits.","Prepare redeposit or unwind steps as separate wallet-signed actions."],"collateral-hedge":["Prepare collateral supply after sizing liquidation buffer.","Prepare stable borrow if borrow APR remains inside the method limit.","Open or adjust the perp short on the selected hedge venue, then record hedge size."],"lp-hedge":["Prepare LP add only after checking pool depth, range, and expected position delta.","Short the estimated volatile-token delta on the selected hedge venue.","Prepare LP remove if the range breaks or net APR turns negative."]};function R(t){let e=typeof t=="number"?t:Number(t);return Number.isFinite(e)?e:null}function L(t,e="unknown"){if(typeof t!="string")return e;let r=t.trim();return r===""?e:r.slice(0,96)}function ne(t){let e=L(t.symbol,"").toUpperCase(),r=L(t.exposure,"").toLowerCase(),n=R(t.apy)??0,a=R(t.tvlUsd)??0;return n<=0||a<=0?null:t.stablecoin===!0?"stable-loop":e.includes("-")||r.includes("multi")?"lp-hedge":/ETH|BTC|SOL|HYPE|BNB|AVAX|MATIC|OP|ARB/.test(e)?"collateral-hedge":null}function oe(t,e){let r=R(t.tvlUsd)??0,n=L(t.ilRisk,"").toLowerCase(),a=L(t.predictions?.predictedClass,"").toLowerCase(),l=e==="stable-loop"?3:e==="collateral-hedge"?6:9;return r<1e6?l+=6:r<1e7&&(l+=3),(n.includes("yes")||n.includes("high"))&&(l+=3),a.includes("down")&&(l+=2),Math.min(35,Math.max(0,l))}function ae(t){let e=ne(t);if(!e)return null;let r=R(t.apy)??0,n=R(t.apyBase)??0,a=Math.max(0,R(t.apyReward)??Math.max(0,r-n)),l=Math.max(0,R(t.tvlUsd)??0),i=oe(t,e),p=e==="stable-loop"?4:e==="collateral-hedge"?6:0,h=e==="stable-loop"?0:e==="collateral-hedge"?4:5,u=l<5e6?1.2:.5,d=r-p-h-u-i,s=d<1?"Avoid":r>80||l<1e7?"Watchlist":d>=8?"Farmable":"Watchlist",o=L(t.project),c=L(t.symbol),m=L(t.chain);return{id:L(t.pool,`${m}:${o}:${c}`),recipe:e,label:`${o} ${c}`,chain:m,project:o,symbol:c,tvlUsd:l,rewardApr:a,nativeApr:n,estimatedBorrowApr:p,estimatedFundingApr:h,gasApr:u,riskHaircut:i,netApr:d,verdict:s,exposure:L(t.exposure,e==="stable-loop"?"stablecoin":e==="lp-hedge"?"multi-asset LP":"single-asset collateral"),hedge:$e[e],monitor:Ie[e],prepareSteps:[`Verify ${o} contracts and reward terms on ${m}.`,"Set wallet grant with chain, protocol, max value, slippage, and TTL before preparing any transaction.",...Me[e]],source:"DeFiLlama yields"}}async function Re(t={},e={}){let r=Math.min(24,Math.max(3,Number(t.limit??12)||12)),n=Number(t.minTvl??2e6),a=new Date().toISOString(),l="read-only discovery and prepare-plan design; no signing or broadcast";try{let i=await re({chain:t.chain&&t.chain!=="all"?t.chain:void 0,limit:5e3},e),p=Array.isArray(i?.data)?i.data:[],h=p.map(ae).filter(u=>u!==null).filter(u=>u.tvlUsd>=n).filter(u=>u.rewardApr+u.nativeApr<=300).sort((u,d)=>d.netApr-u.netApr||d.tvlUsd-u.tvlUsd).slice(0,r);return{configured:!0,live:!0,source:"DeFiLlama yields",generatedAt:a,chain:t.chain??"all",considered:p.length,consideredNote:"deepest pools by TVL from the DeFiLlama yields feed",candidates:h,posture:l}}catch(i){return{configured:!1,live:!1,source:"DeFiLlama yields",generatedAt:a,chain:t.chain??"all",considered:0,consideredNote:"deepest pools by TVL from the DeFiLlama yields feed",error:String(i?.message||i),candidates:[],posture:l}}}function x(t,e,r,n){let a=typeof t=="number"?t:Number(t);return Number.isFinite(a)?Math.min(n,Math.max(r,a)):e}function Ce(t={}){let e=x(t.wallets,5,1,500),r=x(t.tasksWeekly,6,0,500),n=x(t.hoursWeekly,4,0,168),a=x(t.hourlyCost,25,0,1e4),l=x(t.gasPerTask,.4,0,1e4),i=x(t.bridgeMonthly,12,0,1e5),p=x(t.expectedReward,900,0,1e7),h=x(t.probability,22,0,100)/100,u=x(t.sybilHaircut,25,0,100)/100,d=x(t.lockupMonths,6,0,120),s=r*e*4.33,o=s*l,c=n*4.33*a,m=o+c+i,P=Math.max(0,1-d*.015),y=e*p*h,T=y*(1-u)*P,k=T-m,I=m>0?k/m*100:null,g=e*p>0?m/(e*p*(1-u)*(P||1))*100:null;return{inputs:{wallets:e,tasksWeekly:r,hoursWeekly:n,hourlyCost:a,gasPerTask:l,bridgeMonthly:i,expectedReward:p,probabilityPct:h*100,sybilHaircutPct:u*100,lockupMonths:d},monthlyTasks:s,monthlyGas:o,laborMonthly:c,monthlyCost:m,lockupDiscount:P,grossExpectedValue:y,adjustedExpectedValue:T,netExpectedValue:k,roiPct:I,breakevenProbabilityPct:g,verdict:k>0?"positive-ev":"negative-ev",posture:"estimate on your own inputs; not a payout promise and not financial advice"}}var qe={FARMING_METHODS:Le,discoverFarms:Re,scorePool:ae,classifyPool:ne,riskHaircut:oe,airdropEV:Ce};export{Le as FARMING_METHODS,Ce as airdropEV,ne as classifyPool,qe as default,Re as discoverFarms,oe as riskHaircut,ae as scorePool};