@oracle-agent/oracle 0.35.30 → 0.35.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -1
- package/dist/agent-lifecycle.mjs +3 -3
- package/dist/agent-sessions.mjs +9 -6
- package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
- package/dist/bin/desk-server.mjs +37 -37
- package/dist/bin/oracle-data-mcp.mjs +17 -17
- package/dist/bin/oracle-gateway.mjs +14 -14
- package/dist/bin/oracle-investigate.mjs +11 -0
- package/dist/bin/oracle-launch-radar-shadow.mjs +6 -6
- package/dist/bin/oracle-mev-arb-shadow.mjs +6 -6
- package/dist/bin/oracle-mev-shadow.mjs +6 -6
- package/dist/bin/oracle-public-server.mjs +5 -5
- package/dist/bin/oracle-route.mjs +22 -22
- package/dist/bin/oracle-scan.mjs +15 -15
- package/dist/cli/commands/agent-session.mjs +11 -0
- package/dist/cli/commands/chat.mjs +202 -199
- package/dist/cli/commands/context.mjs +6 -6
- package/dist/cli/commands/doctor.mjs +9 -9
- package/dist/cli/commands/eval.mjs +50 -50
- package/dist/cli/commands/farm.mjs +22 -22
- package/dist/cli/commands/follow.mjs +16 -16
- package/dist/cli/commands/lifecycle.mjs +6 -6
- package/dist/cli/commands/model.mjs +206 -203
- package/dist/cli/commands/quickstart.mjs +7 -7
- package/dist/cli/commands/receipt.mjs +12 -12
- package/dist/cli/commands/resolve.mjs +12 -12
- package/dist/cli/commands/sign.mjs +21 -13
- package/dist/cli/commands/signer.mjs +19 -19
- package/dist/cli/commands/snipe.mjs +11 -11
- package/dist/cli/commands/strategy.mjs +5 -5
- package/dist/cli/commands/swap.mjs +31 -31
- package/dist/cli/commands/venues.mjs +2 -2
- package/dist/context-graph.mjs +3 -3
- package/dist/data/desk-data.mjs +35 -35
- package/dist/data/names.mjs +3 -3
- package/dist/data/providers/farming.mjs +2 -2
- package/dist/data/providers/lp-destination-discovery.mjs +4 -4
- package/dist/index.mjs +49 -49
- package/dist/investigator/index.mjs +2 -0
- package/dist/launch-radar/index.mjs +5 -5
- package/dist/local-signer/anvil-attestation-worker.mjs +1 -1
- package/dist/local-signer/index.mjs +3 -3
- package/dist/local-signer/runtime.mjs +19 -19
- package/dist/nft/universal-mint-router.mjs +4 -4
- package/dist/router/index.mjs +3 -3
- package/dist/router/prepare-bridge.mjs +2 -2
- package/dist/scanner/index.mjs +4 -4
- package/dist/strategy/index.mjs +3 -3
- package/dist/teams/index.mjs +1 -1
- package/dist/tui/standalone-client.mjs +44 -44
- package/package.json +3 -1
- package/public/eval-report.json +2 -2
- package/public/oracle-splash/index.html +2 -2
- package/server.json +2 -2
package/dist/data/names.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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}
|
|
1
|
+
import{keccak_256 as ue}from"@noble/hashes/sha3.js";import{createHash as Ve}from"node:crypto";import{types as k}from"node:util";import B from"node:net";import De from"node:dns";var Fe=new Set(["localhost","metadata.google.internal","metadata.goog"]);function Y(t){let e=String(t).toLowerCase().split("%")[0];if((e.match(/::/g)||[]).length>1)return null;let r=o=>{if(!o)return[];let s=o.split(":"),l=s.at(-1);if(l?.includes(".")){let h=l.split(".").map(Number);if(h.length!==4||h.some(m=>!Number.isInteger(m)||m<0||m>255))return null;s.splice(s.length-1,1,(h[0]<<8|h[1]).toString(16),(h[2]<<8|h[3]).toString(16))}return s.some(h=>!/^[0-9a-f]{1,4}$/.test(h))?null:s.map(h=>Number.parseInt(h,16))},[n,a]=e.split("::"),u=r(n),i=r(a);if(!u||!i)return null;let d=e.includes("::"),c=8-u.length-i.length;if(!d&&c!==0||d&&c<1)return null;let p=[...u,...Array(Math.max(0,c)).fill(0),...i];return p.length!==8?null:Uint8Array.from(p.flatMap(o=>[o>>8,o&255]))}function ee(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 u=255<<8-a;return(t[n]&u)===(e[n]&u)}function te(t){if(B.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(B.isIPv6(t)){let e=Y(t);if(!e)return!1;let r=Y("::ffff:0:0");return ee(e,r,96)?te([...e.slice(12)].join(".")):ee(e,Y("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([a,u])=>ee(e,Y(a),u)):!1}return!1}function ze(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(Fe.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=B.isIP(r);return n!==0&&!te(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:e,host:r,isLiteralIp:n!==0}}async function re(t,{lookupFn:e=De.promises.lookup}={}){let r=ze(t);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:B.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=>!te(a.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}async function ne({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(/\.+$/,""),u=new Map,i=s=>(Array.isArray(s)?s:[s]).map(l=>typeof l=="string"?{address:l}:l).filter(l=>l&&l.address).map(l=>({address:l.address,family:l.family||(B.isIPv6(l.address)?6:4)})),d=(s,l,h)=>{u.set(a(s),i(typeof l=="string"?[{address:l,family:h}]:l))},c=s=>{let l=a(s);if(B.isIP(l))return[{address:l,family:B.isIPv6(l)?6:4}];let h=u.get(l);if(!h||!h.length)throw new Error(`refused: unpinned host ${s} during pinned fetch`);return h},p=new r({connect:{lookup(s,l,h){let m;try{m=c(s)}catch(S){return h(S)}return l?.all?h(null,m):h(null,m[0].address,m[0].family)}}}),o=Ge((s,l={})=>n(s,{...l,dispatcher:p}),d);return{dispatcher:p,fetch:o,pin:d,resolve:c,async close(){try{await p.destroy()}catch{}}}}var oe=Symbol.for("oracle.egressGuard.pinCapableFetch");function Ge(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[oe]=Object.freeze({pin:e}),t}function se(t){return typeof t=="function"&&typeof t[oe]?.pin=="function"}function ye(t,e,r){if(!se(t))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");t[oe].pin(e,r)}var Je=new Set([408,425,429,500,502,503,504]),we=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),We=2,be=4e3,Ye=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,Ke=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,qe=AbortSignal.prototype.throwIfAborted,Ze=EventTarget.prototype.addEventListener,ge=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null,ce=t=>t?Ye.call(t):!1,Xe=t=>t?Ke.call(t):void 0,Qe=new Set([301,302,303,307,308]),q=3,Ft=64*1024,C=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});function T(t){return j(`HTTP JSON body refused: ${t}`)}function et(t){return["isArgumentsObject","isArrayBuffer","isAnyArrayBuffer","isArrayBufferView","isBoxedPrimitive","isDataView","isDate","isExternal","isGeneratorObject","isKeyObject","isCryptoKey","isMap","isMapIterator","isModuleNamespaceObject","isNativeError","isPromise","isRegExp","isSet","isSetIterator","isTypedArray","isWeakMap","isWeakSet"].some(e=>typeof k[e]=="function"&&k[e](t))}function tt(t){let e=[],r=0,n=0,a=0,u=0,i=new WeakSet,d=o=>{if(r+=Buffer.byteLength(o,"utf8"),r>C.bytes)throw T("serialized byte limit exceeded");e.push(o)},c=o=>{if(Buffer.byteLength(o,"utf8")>C.bytes)throw T("serialized byte limit exceeded");return JSON.stringify(o)},p=(o,s)=>{if(n+=1,n>C.nodes)throw T("node limit exceeded");if(s>C.depth)throw T("depth limit exceeded");if(o===null){d("null");return}if(typeof o=="string"){d(c(o));return}if(typeof o=="boolean"){d(o?"true":"false");return}if(typeof o=="number"){if(!Number.isFinite(o))throw T("non-finite number");d(Object.is(o,-0)?"0":String(o));return}if(typeof o!="object")throw T("unsupported non-JSON value");if(k.isProxy(o))throw T("proxy value");if(et(o))throw T("unsupported exotic object");if(i.has(o))throw T("cyclic value");i.add(o);try{if(Object.getOwnPropertySymbols(o).length>0)throw T("symbol-keyed fields are unsupported");if(Array.isArray(o)){let m=Object.getPrototypeOf(o),S=0;for(;m!==null;){if(k.isProxy(m))throw T("proxy array prototype");if(S+=1,S>C.depth)throw T("array prototype depth limit exceeded");m=Object.getPrototypeOf(m)}if(o.length>C.arrayLength)throw T("array length limit exceeded");for(let A=0;A<o.length;A+=1){let N=Object.getOwnPropertyDescriptor(o,String(A));if(!N||!Object.hasOwn(N,"value")||N.enumerable!==!0)throw T("array entries must be dense enumerable own data")}let R=0;for(let A in o){if(u+=1,u>C.fields)throw T("enumeration limit exceeded");if(Object.hasOwn(o,A)&&(R+=1,R>o.length))throw T("named array fields are unsupported")}if(R!==o.length)throw T("array entries must be dense enumerable own data");d("[");for(let A=0;A<o.length;A+=1)A&&d(","),p(Object.getOwnPropertyDescriptor(o,String(A)).value,s+1);d("]");return}let l=Object.getPrototypeOf(o);if(l!==Object.prototype&&l!==null)throw T("non-plain object");let h=[];for(let m in o){if(u+=1,u>C.fields)throw T("enumeration limit exceeded");if(!Object.hasOwn(o,m))continue;if(a+=1,a>C.fields)throw T("field limit exceeded");let S=Object.getOwnPropertyDescriptor(o,m);if(!S||!Object.hasOwn(S,"value")||S.enumerable!==!0)throw T("object fields must be enumerable own data");h.push([m,S.value])}d("{");for(let m=0;m<h.length;m+=1)m&&d(","),d(c(h[m][0])),d(":"),p(h[m][1],s+1);d("}")}finally{i.delete(o)}};return p(t,0),e.join("")}function rt(t){let e=Object.create(null);if(t==null)return e;if(typeof t!="object"&&typeof t!="function")throw new TypeError("HTTP headers must be an object");if(k.isProxy(t))throw new TypeError("HTTP headers must not be a proxy");if(Object.getOwnPropertySymbols(t).length>0)throw new TypeError("HTTP headers must not contain symbol fields");let r=new Set;for(let n of Object.keys(t)){if(!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u.test(n))throw new TypeError("HTTP header names must be valid tokens");let a=n.toLowerCase();if(r.has(a))throw new TypeError("HTTP headers contain a duplicate canonical name");r.add(a);let u=Object.getOwnPropertyDescriptor(t,n);if(!u||!Object.hasOwn(u,"value"))throw new TypeError("HTTP headers must contain own data properties");let i=u.value;if(i==null||["object","function","symbol"].includes(typeof i))throw new TypeError("HTTP header values must be scalar");e[n]=String(i)}return e}function nt(){return Object.assign(Object.create(null),{Accept:"application/json"})}function ot(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 st(t,e){return new URL(String(t)).origin===new URL(String(e)).origin}var ie=new Map,Te=new WeakMap,Ee=1;function K(t){if((typeof t!="object"||t===null)&&typeof t!="function")return`${typeof t}:${String(t)}`;let e=Te.get(t);return e||(e=Ee,Ee+=1,Te.set(t,e)),`reference:${e}`}var it=new Set(["eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","getHealth","minimumLedgerSlot","net_version","simulateTransaction","web3_clientVersion"]),at=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);function Oe(t){if(!t||typeof t!="object"||Array.isArray(t)||!Object.hasOwn(t,"jsonrpc")||!Object.hasOwn(t,"method")||t.jsonrpc!=="2.0")return!1;let e=typeof t.method=="string"?t.method:"";return e?it.has(e)||/^get[A-Z0-9_]/u.test(e)||/^is[A-Z0-9_]/u.test(e)||/^eth_get[A-Z0-9_]/u.test(e):!1}function Pe(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}if(Array.isArray(r))return r.length>0&&r.every(Oe);if(!r||typeof r!="object")return!1;if(Object.hasOwn(r,"jsonrpc")||Object.hasOwn(r,"method"))return Oe(r);let n=Object.hasOwn(r,"type")?r.type:null;return typeof n=="string"&&at.has(n)&&(!Object.hasOwn(r,"action")||r.action==null)&&(!Object.hasOwn(r,"signature")||r.signature==null)&&(!Object.hasOwn(r,"nonce")||r.nonce==null)}function ct(t,e,r,n={},a=null){let u=Ve("sha256"),i=(c,p)=>{let o=String(p);u.update(String(Buffer.byteLength(c,"utf8"))).update(":").update(c),u.update("=").update(String(Buffer.byteLength(o,"utf8"))).update(":").update(o).update(`
|
|
2
|
+
`)};i("method",t),i("url",e),Object.keys(r||{}).map((c,p)=>({name:c.toLowerCase(),order:p,value:String(r[c])})).sort((c,p)=>c.name.localeCompare(p.name)||c.order-p.order).forEach((c,p)=>{i(`header-name-${p}`,c.name),i(`header-value-${p}`,c.value)}),i("body",a??"-");for(let c of["untrustedUrl","maxResponseBytes","sameOriginRedirectsOnly","redirectPolicy","maxRedirects","timeoutMs","retries","fetchImpl","realFetch","lookupFn","importUndici","validateResponse"])i(`context-${c}`,n[c]??"-");return u.digest("hex")}function ut(t,e){let r=Number(e);return Number.isFinite(r)&&r>0?Math.min(r*1e3,be):Math.min(250*2**t,be)+Math.floor(Math.random()*100)}var lt=t=>new Promise(e=>setTimeout(e,t));function j(t,e={}){let r=new Error(t);return r.retryable=!1,Object.assign(r,e),r}function ae(t,e,r){return j(`HTTP response from ${t} exceeded maxResponseBytes ${r} (${e})`,{oversize:!0})}function M(t){try{let e=t?.body?.cancel?.();e&&typeof e.then=="function"&&e.catch(()=>{})}catch{}}function ft(t){return t?t.byteLength??t.length??0:0}async function dt(t,e,{url:r,truncate:n=!1,onOversize:a}={}){if(e==null)return await t.text();let u=Number(t.headers?.get?.("content-length"));if(Number.isFinite(u)&&u>e&&(M(t),!n))throw ae(r,`content-length ${u}`,e);let i=t.body?.getReader?.();if(!i){let s=await t.text(),l=Buffer.byteLength(s,"utf8");if(l>e){if(!n)throw ae(r,`body ${l} bytes`,e);return Buffer.from(s,"utf8").subarray(0,e).toString("utf8")}return s}let d=[],c=0,p=!1;try{for(;;){let{value:s,done:l}=await i.read();if(l)break;if(s&&(d.push(Buffer.from(s)),c+=ft(s),c>e)){p=!0;break}}}finally{if(p)try{await i.cancel()}catch{}try{i.releaseLock?.()}catch{}}if(p&&(typeof a=="function"&&a(),!n))throw ae(r,`streamed ${c} bytes`,e);let o=Buffer.concat(d);return(p?o.subarray(0,e):o).toString("utf8")}function pt(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function ht(t,{fetchImpl:e,method:r,headers:n,body:a,timeoutMs:u,lookupFn:i,realFetch:d,untrustedUrl:c=!1,maxResponseBytes:p=null,sameOriginRedirectsOnly:o=!1,importUndici:s,validateResponse:l,signal:h,redirectPolicy:m="follow",maxRedirects:S=q}){let R=new AbortController,A=setTimeout(()=>R.abort(),u),N=h?ge?ge([h,R.signal]):h:R.signal,g=null,x=e,F=i?{lookupFn:i}:{};if(c&&!d&&!se(x))throw j(`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 G=async(y,{status:O=null}={})=>{let P=await re(y,F);if(!P.ok)throw j(O==null?`HTTP refused ${y}: ${P.error}`:`HTTP redirect to ${y} ${P.error}`,O==null?{}:{status:O});let H=new URL(y).hostname;if(d){if(g&&(await g.close(),g=null),!g)try{g=await ne({requireUndici:!0,...s?{importUndici:s}:{}})}catch(f){throw j(O==null?`HTTP refused ${y}: ${f?.message||f}`:`HTTP redirect to ${y} refused: ${f?.message||f}`,O==null?{}:{status:O})}g.pin(H,P.addresses),x=g.fetch}else ye(x,H,P.addresses);return P};try{let y=String(t),O=Object.assign(Object.create(null),n||{});c&&await G(y);for(let P=0;P<=S;P+=1){let H=Object.assign(Object.create(null),{method:r,headers:O,body:a,signal:N,redirect:"manual",dispatcher:void 0}),f=await x(y,H);if((m==="error"||S===0)&&f.status>=300&&f.status<400)throw M(f),j(`HTTP ${f.status} ${r} redirect refused`,{status:f.status,redirectRefused:!0});if(Qe.has(f.status)){let v=o===!0&&r==="POST"&&[307,308].includes(f.status)&&Pe(r,a);if(r!=="GET"&&r!=="HEAD"&&!v){M(f);let E=new Error(`HTTP ${f.status} ${r} ${y} redirected non-idempotent request`);throw E.status=f.status,E}if(P===S)throw M(f),j(`HTTP ${f.status} ${r} redirect budget exhausted`,{status:f.status,redirectRefused:!0});let he=f.headers?.get?.("location"),I;try{I=ot(he,y)}catch(E){throw M(f),E}let $=!st(I,y);if(M(f),$&&r==="POST"){let E=new Error(`HTTP ${f.status} ${r} cross-origin redirect refused`);throw E.status=f.status,E}if($&&o){let E=new Error(`HTTP ${f.status} ${r} cross-origin redirect refused`);throw E.status=f.status,E.retryable=!1,E}if($&&(O=nt(O)),c)await G(I,{status:f.status});else if($){let E=await re(I,F);if(!E.ok){let b=new Error(`HTTP redirect from ${y} ${E.error}`);throw b.status=f.status,b.retryable=!1,b}d&&E.addresses?.length&&(g||(g=await ne(s?{importUndici:s}:{})),g&&(g.pin(new URL(I).hostname,E.addresses),x=g.fetch))}y=I;continue}if(typeof l=="function")try{await l(f,{url:y})}catch(v){throw M(f),j(v?.message||String(v))}let _=await dt(f,p,{url:y,onOversize:()=>R.abort()}),V=pt(_);if(!f.ok){let v=new Error(`HTTP ${f.status} ${r} ${y}`);throw v.status=f.status,v.retryAfter=f.headers?.get?.("retry-after")??null,v.body=V??_.slice(0,300),v}return V??_}throw new Error(`HTTP redirect loop for ${t}`)}catch(y){if(R.signal.aborted&&!ce(h)){let O=y&&(typeof y=="object"||typeof y=="function")&&!k.isProxy(y)?y:null,P=O?Object.getOwnPropertyDescriptor(O,"oversize"):null;if(!(P&&Object.hasOwn(P,"value")&&P.value===!0))try{if(!O)throw new TypeError("unsafe rejection");Object.defineProperties(O,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}})}catch{let f=new Error("HTTP request timed out");throw Object.defineProperties(f,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}}),f}}throw y}finally{clearTimeout(A),g&&await g.close()}}async function Se(t,e={}){if(e!=null&&typeof e!="object"&&typeof e!="function")throw new TypeError("HTTP options must be an object");if(e!=null&&k.isProxy(e))throw new TypeError("HTTP options must not be a proxy");let r=new Set(["body","dedupe","fetchImpl","headers","importUndici","lookupFn","maxRedirects","maxResponseBytes","method","redirectPolicy","retries","sameOriginRedirectsOnly","signal","timeoutMs","untrustedUrl","validateResponse"]);if(e!=null){if(Object.getOwnPropertySymbols(e).length>0)throw new TypeError("HTTP options contain unknown fields");for(let b of Object.getOwnPropertyNames(e)){let w=Object.getOwnPropertyDescriptor(e,b);if(!(b==="toJSON"&&w&&Object.hasOwn(w,"value")&&w.value===void 0)){if(!r.has(b))throw new TypeError("HTTP options contain unknown fields");if(!w||!w.enumerable||!Object.hasOwn(w,"value"))throw new TypeError("HTTP options must contain enumerable own data properties")}}}let n=b=>{if(e==null||!Object.hasOwn(e,b))return;let w=Object.getOwnPropertyDescriptor(e,b);if(!w||!Object.hasOwn(w,"value"))throw new TypeError("HTTP options must contain own data properties");return w.value};if(typeof t!="string"||t.length===0||t.length>8192)throw new TypeError("HTTP URL must be a bounded string");let a=n("method");if(a!==void 0&&(typeof a!="string"||!/^[A-Za-z]+$/u.test(a)))throw new TypeError("HTTP method must be a string token");let u=n("timeoutMs");if(u!==void 0&&(!Number.isInteger(u)||u<1||u>12e4))throw new TypeError("HTTP timeoutMs must be a bounded integer");let i=n("retries");if(i!==void 0&&(!Number.isInteger(i)||i<0||i>10))throw new TypeError("HTTP retries must be a bounded integer");let d=n("redirectPolicy");if(d!==void 0&&d!=="follow"&&d!=="error")throw new TypeError('HTTP redirectPolicy must be "follow" or "error"');let c=n("maxRedirects");if(c!==void 0&&(!Number.isInteger(c)||c<0||c>q))throw new TypeError(`HTTP maxRedirects must be an integer from 0 through ${q}`);if(d==="error"&&c!==void 0&&c!==0)throw new TypeError('HTTP redirectPolicy "error" requires maxRedirects 0 when supplied');let p=d??"follow",o=p==="error"?0:c??q;for(let b of["dedupe","untrustedUrl","sameOriginRedirectsOnly"]){let w=n(b);if(w!==void 0&&typeof w!="boolean")throw new TypeError(`HTTP ${b} must be boolean`)}let s=n("maxResponseBytes");if(s!==void 0&&(!Number.isInteger(s)||s<1||s>64*1024*1024))throw new TypeError("HTTP maxResponseBytes must be a bounded integer");let l=n("signal");if(l!==void 0){if(k.isProxy(l)||!(l instanceof AbortSignal))throw new TypeError("HTTP signal must be a native AbortSignal");try{ce(l)}catch{throw new TypeError("HTTP signal must be a native AbortSignal")}}for(let b of["importUndici","lookupFn","validateResponse"]){let w=n(b);if(w!==void 0&&typeof w!="function")throw new TypeError(`HTTP ${b} must be a function`)}let h=n("fetchImpl"),m=h||globalThis.fetch;if(typeof m!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let S=u??12e3,R=(a||"GET").toUpperCase(),A=n("headers"),N=rt(A),g=Object.assign(Object.create(null),N);Object.keys(g).some(b=>b.toLowerCase()==="accept")||(g.Accept="application/json");let x=n("body");x!=null&&typeof x!="string"&&(Object.keys(g).find(w=>w.toLowerCase()==="content-type")||(g["Content-Type"]="application/json"),x=tt(x));let F=i??We,G=n("lookupFn"),y=!h,O=n("untrustedUrl")===!0,P=n("sameOriginRedirectsOnly")===!0,H=n("importUndici"),f=n("validateResponse"),_=l,V=s??null,v=async()=>{let b;for(let w=0;w<=F;w++){_&&qe.call(_);try{return await ht(t,{fetchImpl:m,method:R,headers:g,body:x,timeoutMs:S,lookupFn:G,realFetch:y,untrustedUrl:O,maxResponseBytes:V,sameOriginRedirectsOnly:P,importUndici:H,validateResponse:f,signal:_,redirectPolicy:p,maxRedirects:o})}catch(L){b=L;let z=Q=>{if(!L||typeof L!="object"&&typeof L!="function"||k.isProxy(L))return;let J=Object.getOwnPropertyDescriptor(L,Q);return J&&Object.hasOwn(J,"value")?J.value:void 0},X=z("status"),Le=z("oracleTimeout")===!0||z("name")==="AbortError"||z("name")==="TimeoutError"||ce(_),Be=new Set([408,425,429]),Me=z("retryable")===!1?!1:X!=null?Be.has(X)||Je.has(X)&&we.has(R):!Le&&we.has(R);if(w===F||!Me)throw L;let me=ut(w,z("retryAfter"));_?await new Promise((Q,J)=>{let Ue=setTimeout(Q,me);Ze.call(_,"abort",()=>{clearTimeout(Ue),J(Xe(_)||new DOMException("Aborted","AbortError"))},{once:!0})}):await lt(me)}}throw b};if(!(n("dedupe")!==!1&&!_&&Pe(R,x)))return v();let I=ct(R,t,g,{untrustedUrl:O,maxResponseBytes:V,sameOriginRedirectsOnly:P,redirectPolicy:p,maxRedirects:o,timeoutMs:S,retries:F,fetchImpl:K(m),realFetch:y,lookupFn:K(G),importUndici:K(H),validateResponse:K(f)},x),$=ie.get(I);if($)return $;let E=v().finally(()=>ie.delete(I));return ie.set(I,E),E}var Re={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}},mt=new Map(Object.values(Re).map(t=>[t.chainId,t]));function Ae(t){return mt.get(Number(t))||null}function xe(t,e=process.env){let r=Ae(t);if(!r)return null;for(let n of r.rpcEnv){let a=(e[n]||"").trim();if(a)return a}return null}import{Interface as yt,getAddress as Kt}from"ethers";var qt=new yt(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);var wt={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 bt(t,{rpcUrl:e,env:r=process.env}={}){if(e)return e;let n=xe(t,r);return n||wt[Number(t)]||null}var gt=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function Tt(t){let e=String(t||""),r=e.toLowerCase();if(e!==e.trim()||!/^[a-zA-Z0-9_]+$/.test(e)||!gt.test(r))throw new Error(`evm-rpc: ${e} refused \u2014 @oracle-agent/oracle is prepare-only (read RPC only; no broadcast/sign)`);return r}var W=new Map,_e=new Map;function Et(t){let e=new Error(t?.message||JSON.stringify(t));return e.code=t?.code,e}function Ot(t){if(t?.error)throw Et(t.error);return t?.result}function Pt(t,e,r){return`${t}
|
|
3
3
|
${e}
|
|
4
|
-
${JSON.stringify(
|
|
4
|
+
${JSON.stringify(r??[])}`}async function St(t,e,r){return Se(t,{method:"POST",body:e,fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3,signal:r.signal})}async function ve(t,e,r=[],n={}){let a=String(e||""),u=Tt(a),i=bt(t,n);if(!i)throw new Error(`No RPC URL for chainId ${t} (set env from chain registry rpcEnv or pass rpcUrl)`);if(u==="eth_chainid"&&n.cacheChainId!==!1){let o=_e.get(i);if(o!=null)return o}let c=n.dedupe!==!1&&!n.signal?Pt(i,a,r):null;if(c&&W.has(c))return W.get(c);let p=(async()=>{let o=await St(i,{jsonrpc:"2.0",id:1,method:e,params:r},n),s=Ot(o);return u==="eth_chainid"&&typeof s=="string"&&_e.set(i,s),s})();return c&&(W.set(c,p),p.finally(()=>{W.get(c)===p&&W.delete(c)}).catch(()=>{})),p}var fe=999,le=1,Rt=8453,Ie="0x1d9d87eBc14e71490bB87f1C39F65BDB979f3cb7",At="0x4d5e4ed4D5e4A160Fa136853597cDc2eBBe66494",Ce="0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",xt="0xC6d566A56A1aFf6508b41f6c90ff131615583BCD",_t=".80002105.reverse",ke=/^0x[a-fA-F0-9]{40}$/,de=new TextEncoder,He=t=>"0x"+Buffer.from(t).toString("hex"),U=t=>He(ue(de.encode(t))).slice(0,10),je=t=>t.toLowerCase().replace(/^0x/,"").padStart(64,"0");function Z(t){let e=new Uint8Array(32);if(t)for(let r of String(t).split(".").reverse()){let n=ue(de.encode(r)),a=new Uint8Array(64);a.set(e,0),a.set(n,32),e=ue(a)}return He(e)}function pe(t){if(!t||t==="0x"||/^0x0*$/.test(t))return"";try{let e=t.slice(2),r=parseInt(e.slice(0,64),16)*2,n=parseInt(e.slice(r,r+64),16);if(!Number.isFinite(n)||n<=0)return"";let a=e.slice(r+64,r+64+n*2);return Buffer.from(a,"hex").toString("utf8")}catch{return""}}function er(t){let e=de.encode(String(t)),r=e.length.toString(16).padStart(64,"0"),n=Buffer.from(e).toString("hex").padEnd(Math.ceil(e.length/32)*64,"0");return"0000000000000000000000000000000000000000000000000000000000000020"+r+n}async function D(t,e,r){try{return await ve(t,"eth_call",[{to:e,data:r},"latest"])}catch{return null}}async function vt(t){let e=await D(fe,Ie,U("primaryName(address)")+je(t)),r=pe(e);return r?r.endsWith(".hl")?r:`${r}.hl`:null}async function It(t){let e=await D(fe,At,U("getName(address)")+je(t)),r=pe(e);return r?r.endsWith(".hype")?r:`${r}.hype`:null}async function Ne(t,e,r){let n=await D(t,r,U("name(bytes32)")+e.slice(2));return pe(n)||null}async function Ct(t){let e=Z(`${t.slice(2).toLowerCase()}.addr.reverse`),r=await D(le,Ce,U("resolver(bytes32)")+e.slice(2));if(!r)return null;let n="0x"+r.slice(-40);return/^0x0+$/.test(n)?null:Ne(le,e,n)}async function kt(t){let e=Z(t.slice(2).toLowerCase()+_t);return Ne(Rt,e,xt)}var $e=[{source:"hl",fn:vt},{source:"hype",fn:It},{source:"ens",fn:Ct},{source:"basename",fn:kt}];async function tr(t){if(!ke.test(String(t||"").trim()))return null;let e=String(t).trim();return(await Promise.all($e.map(async({source:n,fn:a})=>{try{let u=await a(e);return u?{name:u,source:n,address:e}:null}catch{return null}}))).find(Boolean)||null}async function Ht(t){let e=Z(t),r=await D(fe,Ie,U("ownerOf(uint256)")+e.slice(2));if(!r||r.length<66)return null;let n="0x"+r.slice(-40);return/^0x0+$/.test(n)?null:n}async function jt(t,e,r){let n=Z(e),a=await D(t,r,U("resolver(bytes32)")+n.slice(2));if(!a)return null;let u="0x"+a.slice(-40);if(/^0x0+$/.test(u))return null;let i=await D(t,u,U("addr(bytes32)")+n.slice(2));if(!i)return null;let d="0x"+i.slice(-40);return/^0x0+$/.test(d)?null:d}async function Nt(t){let e=String(t||"").trim().toLowerCase();if(!e||!e.includes("."))return null;if(e.endsWith(".hl")){let r=await Ht(e);return r?{address:r,source:"hl",name:e}:null}if(e.endsWith(".eth")){let r=await jt(le,e,Ce);return r?{address:r,source:e.endsWith(".base.eth")?"basename":"ens",name:e}:null}return null}async function rr(t){let e=String(t||"").trim();return ke.test(e)?{address:e,source:"address",name:null}:Nt(e)}var nr=$e.map(t=>t.source);export{ke as ADDRESS_RE,nr as NAME_SOURCES,pe as decodeAbiString,er as encodeAbiString,tr as lookupName,Z as namehash,Nt as resolveName,rr as toAddress};
|
|
@@ -1,2 +1,2 @@
|
|
|
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};
|
|
1
|
+
import{createHash as Le}from"node:crypto";import{types as $}from"node:util";import B from"node:net";import xe from"node:dns";var ke=new Set(["localhost","metadata.google.internal","metadata.goog"]);function J(e){let t=String(e).toLowerCase().split("%")[0];if((t.match(/::/g)||[]).length>1)return null;let r=o=>{if(!o)return[];let l=o.split(":"),c=l.at(-1);if(c?.includes(".")){let p=c.split(".").map(Number);if(p.length!==4||p.some(y=>!Number.isInteger(y)||y<0||y>255))return null;l.splice(l.length-1,1,(p[0]<<8|p[1]).toString(16),(p[2]<<8|p[3]).toString(16))}return l.some(p=>!/^[0-9a-f]{1,4}$/.test(p))?null:l.map(p=>Number.parseInt(p,16))},[n,i]=t.split("::"),a=r(n),s=r(i);if(!a||!s)return null;let f=t.includes("::"),u=8-a.length-s.length;if(!f&&u!==0||f&&u<1)return null;let d=[...a,...Array(Math.max(0,u)).fill(0),...s];return d.length!==8?null:Uint8Array.from(d.flatMap(o=>[o>>8,o&255]))}function Q(e,t,r){let n=Math.floor(r/8),i=r%8;for(let s=0;s<n;s+=1)if(e[s]!==t[s])return!1;if(!i)return!0;let a=255<<8-i;return(e[n]&a)===(t[n]&a)}function ee(e){if(B.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(B.isIPv6(e)){let t=J(e);if(!t)return!1;let r=J("::ffff:0:0");return Q(t,r,96)?ee([...t.slice(12)].join(".")):Q(t,J("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([i,a])=>Q(t,J(i),a)):!1}return!1}function Re(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(ke.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=B.isIP(r);return n!==0&&!ee(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:t,host:r,isLiteralIp:n!==0}}async function te(e,{lookupFn:t=xe.promises.lookup}={}){let r=Re(e);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:B.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(i=>!ee(i.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}async function re({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 i=l=>String(l).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),a=new Map,s=l=>(Array.isArray(l)?l:[l]).map(c=>typeof c=="string"?{address:c}:c).filter(c=>c&&c.address).map(c=>({address:c.address,family:c.family||(B.isIPv6(c.address)?6:4)})),f=(l,c,p)=>{a.set(i(l),s(typeof c=="string"?[{address:c,family:p}]:c))},u=l=>{let c=i(l);if(B.isIP(c))return[{address:c,family:B.isIPv6(c)?6:4}];let p=a.get(c);if(!p||!p.length)throw new Error(`refused: unpinned host ${l} during pinned fetch`);return p},d=new r({connect:{lookup(l,c,p){let y;try{y=u(l)}catch(P){return p(P)}return c?.all?p(null,y):p(null,y[0].address,y[0].family)}}}),o=je((l,c={})=>n(l,{...c,dispatcher:d}),f);return{dispatcher:d,fetch:o,pin:f,resolve:u,async close(){try{await d.destroy()}catch{}}}}var ne=Symbol.for("oracle.egressGuard.pinCapableFetch");function je(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[ne]=Object.freeze({pin:t}),e}function oe(e){return typeof e=="function"&&typeof e[ne]?.pin=="function"}function ue(e,t,r){if(!oe(e))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");e[ne].pin(t,r)}var Ie=new Set([408,425,429,500,502,503,504]),de=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),_e=2,fe=4e3,$e=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,Me=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,He=AbortSignal.prototype.throwIfAborted,Ce=EventTarget.prototype.addEventListener,pe=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null,ae=e=>e?$e.call(e):!1,De=e=>e?Me.call(e):void 0,Ne=new Set([301,302,303,307,308]),K=3,ht=64*1024,_=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});function T(e){return C(`HTTP JSON body refused: ${e}`)}function Be(e){return["isArgumentsObject","isArrayBuffer","isAnyArrayBuffer","isArrayBufferView","isBoxedPrimitive","isDataView","isDate","isExternal","isGeneratorObject","isKeyObject","isCryptoKey","isMap","isMapIterator","isModuleNamespaceObject","isNativeError","isPromise","isRegExp","isSet","isSetIterator","isTypedArray","isWeakMap","isWeakSet"].some(t=>typeof $[t]=="function"&&$[t](e))}function Fe(e){let t=[],r=0,n=0,i=0,a=0,s=new WeakSet,f=o=>{if(r+=Buffer.byteLength(o,"utf8"),r>_.bytes)throw T("serialized byte limit exceeded");t.push(o)},u=o=>{if(Buffer.byteLength(o,"utf8")>_.bytes)throw T("serialized byte limit exceeded");return JSON.stringify(o)},d=(o,l)=>{if(n+=1,n>_.nodes)throw T("node limit exceeded");if(l>_.depth)throw T("depth limit exceeded");if(o===null){f("null");return}if(typeof o=="string"){f(u(o));return}if(typeof o=="boolean"){f(o?"true":"false");return}if(typeof o=="number"){if(!Number.isFinite(o))throw T("non-finite number");f(Object.is(o,-0)?"0":String(o));return}if(typeof o!="object")throw T("unsupported non-JSON value");if($.isProxy(o))throw T("proxy value");if(Be(o))throw T("unsupported exotic object");if(s.has(o))throw T("cyclic value");s.add(o);try{if(Object.getOwnPropertySymbols(o).length>0)throw T("symbol-keyed fields are unsupported");if(Array.isArray(o)){let y=Object.getPrototypeOf(o),P=0;for(;y!==null;){if($.isProxy(y))throw T("proxy array prototype");if(P+=1,P>_.depth)throw T("array prototype depth limit exceeded");y=Object.getPrototypeOf(y)}if(o.length>_.arrayLength)throw T("array length limit exceeded");for(let v=0;v<o.length;v+=1){let j=Object.getOwnPropertyDescriptor(o,String(v));if(!j||!Object.hasOwn(j,"value")||j.enumerable!==!0)throw T("array entries must be dense enumerable own data")}let A=0;for(let v in o){if(a+=1,a>_.fields)throw T("enumeration limit exceeded");if(Object.hasOwn(o,v)&&(A+=1,A>o.length))throw T("named array fields are unsupported")}if(A!==o.length)throw T("array entries must be dense enumerable own data");f("[");for(let v=0;v<o.length;v+=1)v&&f(","),d(Object.getOwnPropertyDescriptor(o,String(v)).value,l+1);f("]");return}let c=Object.getPrototypeOf(o);if(c!==Object.prototype&&c!==null)throw T("non-plain object");let p=[];for(let y in o){if(a+=1,a>_.fields)throw T("enumeration limit exceeded");if(!Object.hasOwn(o,y))continue;if(i+=1,i>_.fields)throw T("field limit exceeded");let P=Object.getOwnPropertyDescriptor(o,y);if(!P||!Object.hasOwn(P,"value")||P.enumerable!==!0)throw T("object fields must be enumerable own data");p.push([y,P.value])}f("{");for(let y=0;y<p.length;y+=1)y&&f(","),f(u(p[y][0])),f(":"),d(p[y][1],l+1);f("}")}finally{s.delete(o)}};return d(e,0),t.join("")}function Ue(e){let t=Object.create(null);if(e==null)return t;if(typeof e!="object"&&typeof e!="function")throw new TypeError("HTTP headers must be an object");if($.isProxy(e))throw new TypeError("HTTP headers must not be a proxy");if(Object.getOwnPropertySymbols(e).length>0)throw new TypeError("HTTP headers must not contain symbol fields");let r=new Set;for(let n of Object.keys(e)){if(!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u.test(n))throw new TypeError("HTTP header names must be valid tokens");let i=n.toLowerCase();if(r.has(i))throw new TypeError("HTTP headers contain a duplicate canonical name");r.add(i);let a=Object.getOwnPropertyDescriptor(e,n);if(!a||!Object.hasOwn(a,"value"))throw new TypeError("HTTP headers must contain own data properties");let s=a.value;if(s==null||["object","function","symbol"].includes(typeof s))throw new TypeError("HTTP header values must be scalar");t[n]=String(s)}return t}function ze(){return Object.assign(Object.create(null),{Accept:"application/json"})}function We(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 Ge(e,t){return new URL(String(e)).origin===new URL(String(t)).origin}var se=new Map,he=new WeakMap,ye=1;function Y(e){if((typeof e!="object"||e===null)&&typeof e!="function")return`${typeof e}:${String(e)}`;let t=he.get(e);return t||(t=ye,ye+=1,he.set(e,t)),`reference:${t}`}var Ve=new Set(["eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","getHealth","minimumLedgerSlot","net_version","simulateTransaction","web3_clientVersion"]),qe=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);function me(e){if(!e||typeof e!="object"||Array.isArray(e)||!Object.hasOwn(e,"jsonrpc")||!Object.hasOwn(e,"method")||e.jsonrpc!=="2.0")return!1;let t=typeof e.method=="string"?e.method:"";return t?Ve.has(t)||/^get[A-Z0-9_]/u.test(t)||/^is[A-Z0-9_]/u.test(t)||/^eth_get[A-Z0-9_]/u.test(t):!1}function ge(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}if(Array.isArray(r))return r.length>0&&r.every(me);if(!r||typeof r!="object")return!1;if(Object.hasOwn(r,"jsonrpc")||Object.hasOwn(r,"method"))return me(r);let n=Object.hasOwn(r,"type")?r.type:null;return typeof n=="string"&&qe.has(n)&&(!Object.hasOwn(r,"action")||r.action==null)&&(!Object.hasOwn(r,"signature")||r.signature==null)&&(!Object.hasOwn(r,"nonce")||r.nonce==null)}function Je(e,t,r,n={},i=null){let a=Le("sha256"),s=(u,d)=>{let o=String(d);a.update(String(Buffer.byteLength(u,"utf8"))).update(":").update(u),a.update("=").update(String(Buffer.byteLength(o,"utf8"))).update(":").update(o).update(`
|
|
2
|
+
`)};s("method",e),s("url",t),Object.keys(r||{}).map((u,d)=>({name:u.toLowerCase(),order:d,value:String(r[u])})).sort((u,d)=>u.name.localeCompare(d.name)||u.order-d.order).forEach((u,d)=>{s(`header-name-${d}`,u.name),s(`header-value-${d}`,u.value)}),s("body",i??"-");for(let u of["untrustedUrl","maxResponseBytes","sameOriginRedirectsOnly","redirectPolicy","maxRedirects","timeoutMs","retries","fetchImpl","realFetch","lookupFn","importUndici","validateResponse"])s(`context-${u}`,n[u]??"-");return a.digest("hex")}function Ye(e,t){let r=Number(t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,fe):Math.min(250*2**e,fe)+Math.floor(Math.random()*100)}var Ke=e=>new Promise(t=>setTimeout(t,e));function C(e,t={}){let r=new Error(e);return r.retryable=!1,Object.assign(r,t),r}function ie(e,t,r){return C(`HTTP response from ${e} exceeded maxResponseBytes ${r} (${t})`,{oversize:!0})}function F(e){try{let t=e?.body?.cancel?.();t&&typeof t.then=="function"&&t.catch(()=>{})}catch{}}function Ze(e){return e?e.byteLength??e.length??0:0}async function Xe(e,t,{url:r,truncate:n=!1,onOversize:i}={}){if(t==null)return await e.text();let a=Number(e.headers?.get?.("content-length"));if(Number.isFinite(a)&&a>t&&(F(e),!n))throw ie(r,`content-length ${a}`,t);let s=e.body?.getReader?.();if(!s){let l=await e.text(),c=Buffer.byteLength(l,"utf8");if(c>t){if(!n)throw ie(r,`body ${c} bytes`,t);return Buffer.from(l,"utf8").subarray(0,t).toString("utf8")}return l}let f=[],u=0,d=!1;try{for(;;){let{value:l,done:c}=await s.read();if(c)break;if(l&&(f.push(Buffer.from(l)),u+=Ze(l),u>t)){d=!0;break}}}finally{if(d)try{await s.cancel()}catch{}try{s.releaseLock?.()}catch{}}if(d&&(typeof i=="function"&&i(),!n))throw ie(r,`streamed ${u} bytes`,t);let o=Buffer.concat(f);return(d?o.subarray(0,t):o).toString("utf8")}function Qe(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function et(e,{fetchImpl:t,method:r,headers:n,body:i,timeoutMs:a,lookupFn:s,realFetch:f,untrustedUrl:u=!1,maxResponseBytes:d=null,sameOriginRedirectsOnly:o=!1,importUndici:l,validateResponse:c,signal:p,redirectPolicy:y="follow",maxRedirects:P=K}){let A=new AbortController,v=setTimeout(()=>A.abort(),a),j=p?pe?pe([p,A.signal]):p:A.signal,g=null,x=t,z=s?{lookupFn:s}:{};if(u&&!f&&!oe(x))throw C(`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(m,{status:S=null}={})=>{let E=await te(m,z);if(!E.ok)throw C(S==null?`HTTP refused ${m}: ${E.error}`:`HTTP redirect to ${m} ${E.error}`,S==null?{}:{status:S});let H=new URL(m).hostname;if(f){if(g&&(await g.close(),g=null),!g)try{g=await re({requireUndici:!0,...l?{importUndici:l}:{}})}catch(h){throw C(S==null?`HTTP refused ${m}: ${h?.message||h}`:`HTTP redirect to ${m} refused: ${h?.message||h}`,S==null?{}:{status:S})}g.pin(H,E.addresses),x=g.fetch}else ue(x,H,E.addresses);return E};try{let m=String(e),S=Object.assign(Object.create(null),n||{});u&&await G(m);for(let E=0;E<=P;E+=1){let H=Object.assign(Object.create(null),{method:r,headers:S,body:i,signal:j,redirect:"manual",dispatcher:void 0}),h=await x(m,H);if((y==="error"||P===0)&&h.status>=300&&h.status<400)throw F(h),C(`HTTP ${h.status} ${r} redirect refused`,{status:h.status,redirectRefused:!0});if(Ne.has(h.status)){let R=o===!0&&r==="POST"&&[307,308].includes(h.status)&&ge(r,i);if(r!=="GET"&&r!=="HEAD"&&!R){F(h);let O=new Error(`HTTP ${h.status} ${r} ${m} redirected non-idempotent request`);throw O.status=h.status,O}if(E===P)throw F(h),C(`HTTP ${h.status} ${r} redirect budget exhausted`,{status:h.status,redirectRefused:!0});let le=h.headers?.get?.("location"),L;try{L=We(le,m)}catch(O){throw F(h),O}let D=!Ge(L,m);if(F(h),D&&r==="POST"){let O=new Error(`HTTP ${h.status} ${r} cross-origin redirect refused`);throw O.status=h.status,O}if(D&&o){let O=new Error(`HTTP ${h.status} ${r} cross-origin redirect refused`);throw O.status=h.status,O.retryable=!1,O}if(D&&(S=ze(S)),u)await G(L,{status:h.status});else if(D){let O=await te(L,z);if(!O.ok){let b=new Error(`HTTP redirect from ${m} ${O.error}`);throw b.status=h.status,b.retryable=!1,b}f&&O.addresses?.length&&(g||(g=await re(l?{importUndici:l}:{})),g&&(g.pin(new URL(L).hostname,O.addresses),x=g.fetch))}m=L;continue}if(typeof c=="function")try{await c(h,{url:m})}catch(R){throw F(h),C(R?.message||String(R))}let k=await Xe(h,d,{url:m,onOversize:()=>A.abort()}),V=Qe(k);if(!h.ok){let R=new Error(`HTTP ${h.status} ${r} ${m}`);throw R.status=h.status,R.retryAfter=h.headers?.get?.("retry-after")??null,R.body=V??k.slice(0,300),R}return V??k}throw new Error(`HTTP redirect loop for ${e}`)}catch(m){if(A.signal.aborted&&!ae(p)){let S=m&&(typeof m=="object"||typeof m=="function")&&!$.isProxy(m)?m:null,E=S?Object.getOwnPropertyDescriptor(S,"oversize"):null;if(!(E&&Object.hasOwn(E,"value")&&E.value===!0))try{if(!S)throw new TypeError("unsafe rejection");Object.defineProperties(S,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}})}catch{let h=new Error("HTTP request timed out");throw Object.defineProperties(h,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}}),h}}throw m}finally{clearTimeout(v),g&&await g.close()}}async function we(e,t={}){if(t!=null&&typeof t!="object"&&typeof t!="function")throw new TypeError("HTTP options must be an object");if(t!=null&&$.isProxy(t))throw new TypeError("HTTP options must not be a proxy");let r=new Set(["body","dedupe","fetchImpl","headers","importUndici","lookupFn","maxRedirects","maxResponseBytes","method","redirectPolicy","retries","sameOriginRedirectsOnly","signal","timeoutMs","untrustedUrl","validateResponse"]);if(t!=null){if(Object.getOwnPropertySymbols(t).length>0)throw new TypeError("HTTP options contain unknown fields");for(let b of Object.getOwnPropertyNames(t)){let w=Object.getOwnPropertyDescriptor(t,b);if(!(b==="toJSON"&&w&&Object.hasOwn(w,"value")&&w.value===void 0)){if(!r.has(b))throw new TypeError("HTTP options contain unknown fields");if(!w||!w.enumerable||!Object.hasOwn(w,"value"))throw new TypeError("HTTP options must contain enumerable own data properties")}}}let n=b=>{if(t==null||!Object.hasOwn(t,b))return;let w=Object.getOwnPropertyDescriptor(t,b);if(!w||!Object.hasOwn(w,"value"))throw new TypeError("HTTP options must contain own data properties");return w.value};if(typeof e!="string"||e.length===0||e.length>8192)throw new TypeError("HTTP URL must be a bounded string");let i=n("method");if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z]+$/u.test(i)))throw new TypeError("HTTP method must be a string token");let a=n("timeoutMs");if(a!==void 0&&(!Number.isInteger(a)||a<1||a>12e4))throw new TypeError("HTTP timeoutMs must be a bounded integer");let s=n("retries");if(s!==void 0&&(!Number.isInteger(s)||s<0||s>10))throw new TypeError("HTTP retries must be a bounded integer");let f=n("redirectPolicy");if(f!==void 0&&f!=="follow"&&f!=="error")throw new TypeError('HTTP redirectPolicy must be "follow" or "error"');let u=n("maxRedirects");if(u!==void 0&&(!Number.isInteger(u)||u<0||u>K))throw new TypeError(`HTTP maxRedirects must be an integer from 0 through ${K}`);if(f==="error"&&u!==void 0&&u!==0)throw new TypeError('HTTP redirectPolicy "error" requires maxRedirects 0 when supplied');let d=f??"follow",o=d==="error"?0:u??K;for(let b of["dedupe","untrustedUrl","sameOriginRedirectsOnly"]){let w=n(b);if(w!==void 0&&typeof w!="boolean")throw new TypeError(`HTTP ${b} must be boolean`)}let l=n("maxResponseBytes");if(l!==void 0&&(!Number.isInteger(l)||l<1||l>64*1024*1024))throw new TypeError("HTTP maxResponseBytes must be a bounded integer");let c=n("signal");if(c!==void 0){if($.isProxy(c)||!(c instanceof AbortSignal))throw new TypeError("HTTP signal must be a native AbortSignal");try{ae(c)}catch{throw new TypeError("HTTP signal must be a native AbortSignal")}}for(let b of["importUndici","lookupFn","validateResponse"]){let w=n(b);if(w!==void 0&&typeof w!="function")throw new TypeError(`HTTP ${b} must be a function`)}let p=n("fetchImpl"),y=p||globalThis.fetch;if(typeof y!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let P=a??12e3,A=(i||"GET").toUpperCase(),v=n("headers"),j=Ue(v),g=Object.assign(Object.create(null),j);Object.keys(g).some(b=>b.toLowerCase()==="accept")||(g.Accept="application/json");let x=n("body");x!=null&&typeof x!="string"&&(Object.keys(g).find(w=>w.toLowerCase()==="content-type")||(g["Content-Type"]="application/json"),x=Fe(x));let z=s??_e,G=n("lookupFn"),m=!p,S=n("untrustedUrl")===!0,E=n("sameOriginRedirectsOnly")===!0,H=n("importUndici"),h=n("validateResponse"),k=c,V=l??null,R=async()=>{let b;for(let w=0;w<=z;w++){k&&He.call(k);try{return await et(e,{fetchImpl:y,method:A,headers:g,body:x,timeoutMs:P,lookupFn:G,realFetch:m,untrustedUrl:S,maxResponseBytes:V,sameOriginRedirectsOnly:E,importUndici:H,validateResponse:h,signal:k,redirectPolicy:d,maxRedirects:o})}catch(N){b=N;let W=X=>{if(!N||typeof N!="object"&&typeof N!="function"||$.isProxy(N))return;let q=Object.getOwnPropertyDescriptor(N,X);return q&&Object.hasOwn(q,"value")?q.value:void 0},Z=W("status"),Ae=W("oracleTimeout")===!0||W("name")==="AbortError"||W("name")==="TimeoutError"||ae(k),Se=new Set([408,425,429]),ve=W("retryable")===!1?!1:Z!=null?Se.has(Z)||Ie.has(Z)&&de.has(A):!Ae&&de.has(A);if(w===z||!ve)throw N;let ce=Ye(w,W("retryAfter"));k?await new Promise((X,q)=>{let Ee=setTimeout(X,ce);Ce.call(k,"abort",()=>{clearTimeout(Ee),q(De(k)||new DOMException("Aborted","AbortError"))},{once:!0})}):await Ke(ce)}}throw b};if(!(n("dedupe")!==!1&&!k&&ge(A,x)))return R();let L=Je(A,e,g,{untrustedUrl:S,maxResponseBytes:V,sameOriginRedirectsOnly:E,redirectPolicy:d,maxRedirects:o,timeoutMs:P,retries:z,fetchImpl:Y(y),realFetch:m,lookupFn:Y(G),importUndici:Y(H),validateResponse:Y(h)},x),D=se.get(L);if(D)return D;let O=R().finally(()=>se.delete(L));return se.set(L,O),O}var tt="https://yields.llama.fi";async function be(e={},t={}){let r=(t.yieldsBaseUrl||process.env.DEFILLAMA_YIELDS_URL||tt).replace(/\/$/,""),n=await we(`${r}/pools`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??3e4}),i=Array.isArray(n?.data)?n.data:[];e.chain&&(i=i.filter(s=>String(s.chain).toLowerCase()===String(e.chain).toLowerCase())),e.project&&(i=i.filter(s=>String(s.project).toLowerCase()===String(e.project).toLowerCase())),e.stablecoin!=null&&(i=i.filter(s=>!!s.stablecoin==!!e.stablecoin)),i.sort((s,f)=>Number(f.tvlUsd||0)-Number(s.tvlUsd||0));let a=Math.min(5e3,Math.max(1,Number(e.limit||i.length||1)));return{...n,data:i.slice(0,a)}}var rt=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."}]),nt={"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."},ot={"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."},st={"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 U(e){let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}function M(e,t="unknown"){if(typeof e!="string")return t;let r=e.trim();return r===""?t:r.slice(0,96)}function Te(e){let t=M(e.symbol,"").toUpperCase(),r=M(e.exposure,"").toLowerCase(),n=U(e.apy)??0,i=U(e.tvlUsd)??0;return n<=0||i<=0?null:e.stablecoin===!0?"stable-loop":t.includes("-")||r.includes("multi")?"lp-hedge":/ETH|BTC|SOL|HYPE|BNB|AVAX|MATIC|OP|ARB/.test(t)?"collateral-hedge":null}function Pe(e,t){let r=U(e.tvlUsd)??0,n=M(e.ilRisk,"").toLowerCase(),i=M(e.predictions?.predictedClass,"").toLowerCase(),a=t==="stable-loop"?3:t==="collateral-hedge"?6:9;return r<1e6?a+=6:r<1e7&&(a+=3),(n.includes("yes")||n.includes("high"))&&(a+=3),i.includes("down")&&(a+=2),Math.min(35,Math.max(0,a))}function Oe(e){let t=Te(e);if(!t)return null;let r=U(e.apy)??0,n=U(e.apyBase)??0,i=Math.max(0,U(e.apyReward)??Math.max(0,r-n)),a=Math.max(0,U(e.tvlUsd)??0),s=Pe(e,t),f=t==="stable-loop"?4:t==="collateral-hedge"?6:0,u=t==="stable-loop"?0:t==="collateral-hedge"?4:5,d=a<5e6?1.2:.5,o=r-f-u-d-s,l=o<1?"Avoid":r>80||a<1e7?"Watchlist":o>=8?"Farmable":"Watchlist",c=M(e.project),p=M(e.symbol),y=M(e.chain);return{id:M(e.pool,`${y}:${c}:${p}`),recipe:t,label:`${c} ${p}`,chain:y,project:c,symbol:p,tvlUsd:a,rewardApr:i,nativeApr:n,estimatedBorrowApr:f,estimatedFundingApr:u,gasApr:d,riskHaircut:s,netApr:o,verdict:l,exposure:M(e.exposure,t==="stable-loop"?"stablecoin":t==="lp-hedge"?"multi-asset LP":"single-asset collateral"),hedge:nt[t],monitor:ot[t],prepareSteps:[`Verify ${c} contracts and reward terms on ${y}.`,"Set wallet grant with chain, protocol, max value, slippage, and TTL before preparing any transaction.",...st[t]],source:"DeFiLlama yields"}}async function it(e={},t={}){let r=Math.min(24,Math.max(3,Number(e.limit??12)||12)),n=Number(e.minTvl??2e6),i=new Date().toISOString(),a="read-only discovery and prepare-plan design; no signing or broadcast";try{let s=await be({chain:e.chain&&e.chain!=="all"?e.chain:void 0,limit:5e3},t),f=Array.isArray(s?.data)?s.data:[],u=f.map(Oe).filter(d=>d!==null).filter(d=>d.tvlUsd>=n).filter(d=>d.rewardApr+d.nativeApr<=300).sort((d,o)=>o.netApr-d.netApr||o.tvlUsd-d.tvlUsd).slice(0,r);return{configured:!0,live:!0,source:"DeFiLlama yields",generatedAt:i,chain:e.chain??"all",considered:f.length,consideredNote:"deepest pools by TVL from the DeFiLlama yields feed",candidates:u,posture:a}}catch(s){return{configured:!1,live:!1,source:"DeFiLlama yields",generatedAt:i,chain:e.chain??"all",considered:0,consideredNote:"deepest pools by TVL from the DeFiLlama yields feed",error:String(s?.message||s),candidates:[],posture:a}}}function I(e,t,r,n){let i=typeof e=="number"?e:Number(e);return Number.isFinite(i)?Math.min(n,Math.max(r,i)):t}function at(e={}){let t=I(e.wallets,5,1,500),r=I(e.tasksWeekly,6,0,500),n=I(e.hoursWeekly,4,0,168),i=I(e.hourlyCost,25,0,1e4),a=I(e.gasPerTask,.4,0,1e4),s=I(e.bridgeMonthly,12,0,1e5),f=I(e.expectedReward,900,0,1e7),u=I(e.probability,22,0,100)/100,d=I(e.sybilHaircut,25,0,100)/100,o=I(e.lockupMonths,6,0,120),l=r*t*4.33,c=l*a,p=n*4.33*i,y=c+p+s,P=Math.max(0,1-o*.015),A=t*f*u,v=A*(1-d)*P,j=v-y,g=y>0?j/y*100:null,x=t*f>0?y/(t*f*(1-d)*(P||1))*100:null;return{inputs:{wallets:t,tasksWeekly:r,hoursWeekly:n,hourlyCost:i,gasPerTask:a,bridgeMonthly:s,expectedReward:f,probabilityPct:u*100,sybilHaircutPct:d*100,lockupMonths:o},monthlyTasks:l,monthlyGas:c,laborMonthly:p,monthlyCost:y,lockupDiscount:P,grossExpectedValue:A,adjustedExpectedValue:v,netExpectedValue:j,roiPct:g,breakevenProbabilityPct:x,verdict:j>0?"positive-ev":"negative-ev",posture:"estimate on your own inputs; not a payout promise and not financial advice"}}var bt={FARMING_METHODS:rt,discoverFarms:it,scorePool:Oe,classifyPool:Te,riskHaircut:Pe,airdropEV:at};export{rt as FARMING_METHODS,at as airdropEV,Te as classifyPool,bt as default,it as discoverFarms,Pe as riskHaircut,Oe as scorePool};
|