@oracle-agent/oracle 0.35.49 → 0.35.51
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 +3 -2
- package/artifacts/specialist-packs/oracle-full-crypto.json +11 -0
- package/dist/agent-sessions.mjs +19 -19
- package/dist/artifacts/token-dashboard.mjs +1 -1
- package/dist/assets/profiles/near-agent/SOUL.md +46 -0
- package/dist/assets/profiles/near-agent/profile.json +30 -0
- package/dist/assets/profiles/oracle/SOUL.md +1 -0
- package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
- package/dist/assets/skills/oracle-near/SKILL.md +66 -0
- package/dist/automation-plan.mjs +1 -1
- package/dist/bin/desk-server.mjs +33 -33
- package/dist/bin/oracle-data-mcp.mjs +16 -16
- package/dist/bin/oracle-gateway.mjs +3 -3
- package/dist/bin/oracle-launch-radar-shadow.mjs +3 -3
- package/dist/bin/oracle-mev-arb-shadow.mjs +4 -4
- package/dist/bin/oracle-mev-shadow.mjs +4 -4
- package/dist/bin/oracle-public-server.mjs +5 -5
- package/dist/bin/oracle-route.mjs +27 -27
- package/dist/bin/oracle-scan.mjs +3 -3
- package/dist/bin/oracle-telegram-mcp.mjs +1 -1
- package/dist/chains.mjs +1 -1
- package/dist/cli/commands/account.mjs +22 -22
- package/dist/cli/commands/agent-session.mjs +23 -23
- package/dist/cli/commands/auth.mjs +16 -15
- package/dist/cli/commands/chain.mjs +5 -5
- package/dist/cli/commands/chat.mjs +310 -228
- package/dist/cli/commands/data.mjs +37 -37
- package/dist/cli/commands/doctor.mjs +5 -5
- package/dist/cli/commands/eval.mjs +249 -167
- package/dist/cli/commands/farm.mjs +1 -1
- package/dist/cli/commands/follow.mjs +4 -4
- package/dist/cli/commands/harness.mjs +5 -5
- package/dist/cli/commands/mint.mjs +11 -11
- package/dist/cli/commands/model.mjs +313 -231
- package/dist/cli/commands/project.mjs +8 -7
- package/dist/cli/commands/quickstart.mjs +2 -2
- package/dist/cli/commands/receipt.mjs +2 -2
- package/dist/cli/commands/resolve.mjs +4 -4
- package/dist/cli/commands/session-vault.mjs +4 -4
- package/dist/cli/commands/setup.mjs +53 -52
- package/dist/cli/commands/snipe.mjs +13 -13
- package/dist/cli/commands/strategy.mjs +5 -5
- package/dist/cli/commands/swap.mjs +11 -11
- package/dist/cli/commands/telegram.mjs +7 -7
- package/dist/cli/commands/venues.mjs +1 -1
- package/dist/cli/project-access.mjs +4 -3
- package/dist/data/desk-data.mjs +31 -31
- package/dist/data/holder-table.mjs +2 -2
- package/dist/data/market-tape.mjs +1 -1
- 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/launch-radar/index.mjs +5 -5
- package/dist/lp/index.mjs +4 -4
- package/dist/nft/universal-mint-router.mjs +4 -4
- package/dist/notifications/index.mjs +1 -1
- package/dist/router/index.mjs +3 -3
- package/dist/router/prepare-bridge.mjs +2 -2
- package/dist/router/prepare-route.mjs +3 -3
- package/dist/scanner/index.mjs +3 -3
- package/dist/strategy/index.mjs +4 -4
- package/dist/task.mjs +1 -1
- package/dist/teams/index.mjs +6 -6
- package/dist/telegram/chart-card.mjs +5 -5
- package/dist/telegram/market-commands.mjs +1 -1
- package/dist/tui/standalone-client.mjs +179 -97
- package/package.json +2 -2
- package/public/oracle-splash/assets/desktop-app.jpg +0 -0
- package/public/oracle-splash/docs/browser-and-web/index.html +2 -2
- package/public/oracle-splash/docs/connectors/index.html +2 -2
- package/public/oracle-splash/docs/getting-started/index.html +2 -2
- package/public/oracle-splash/docs/index.html +3 -3
- package/public/oracle-splash/docs/reference/index.html +2 -2
- package/public/oracle-splash/docs/security/index.html +2 -2
- package/public/oracle-splash/docs/using-oracle/index.html +2 -2
- package/public/oracle-splash/download/index.html +219 -5
- package/public/oracle-splash/downloads/index.html +1 -1
- package/public/oracle-splash/eval/index.html +19 -19
- package/public/oracle-splash/eval/releases/oracle-0.35.49.json +852 -0
- package/public/oracle-splash/index.html +262 -37
- package/public/oracle-splash/pricing/index.html +215 -1
- package/public/oracle-splash/security/index.html +215 -1
- package/public/oracle-splash/what-it-does/index.html +215 -1
- package/public/oracle-splash/where-it-works/index.html +215 -1
- package/server.json +2 -2
package/dist/bin/oracle-scan.mjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createHash as Pt}from"node:crypto";import{types as M}from"node:util";import{AsyncLocalStorage as St}from"node:async_hooks";var At=new St,xt=["http","retry","shared"],Ct=512;function ce(t){let e=At.getStore();if(!e||e.closed||!xt.includes(t))return null;if(e.spans.length>=Ct)return e.droppedSpans++,null;let r={stage:t,startMs:e.now()-e.start,durationMs:null,outcome:"pending",status:null};return e.spans.push(r),(n,s=null)=>{e.closed||r.durationMs!==null||(r.durationMs=Math.max(0,e.now()-e.start-r.startMs),r.outcome=n==="succeeded"?"succeeded":"failed",r.status=Number.isInteger(s)&&s>=100&&s<=599?s:null)}}import W from"node:net";import Tt from"node:dns";var It=new Set(["localhost","metadata.google.internal","metadata.goog"]);function ue(t){let e=String(t).toLowerCase().split("%")[0];if((e.match(/::/g)||[]).length>1)return null;let r=a=>{if(!a)return[];let p=a.split(":"),h=p.at(-1);if(h?.includes(".")){let f=h.split(".").map(Number);if(f.length!==4||f.some(d=>!Number.isInteger(d)||d<0||d>255))return null;p.splice(p.length-1,1,(f[0]<<8|f[1]).toString(16),(f[2]<<8|f[3]).toString(16))}return p.some(f=>!/^[0-9a-f]{1,4}$/.test(f))?null:p.map(f=>Number.parseInt(f,16))},[n,s]=e.split("::"),o=r(n),i=r(s);if(!o||!i)return null;let u=e.includes("::"),c=8-o.length-i.length;if(!u&&c!==0||u&&c<1)return null;let l=[...o,...Array(Math.max(0,c)).fill(0),...i];return l.length!==8?null:Uint8Array.from(l.flatMap(a=>[a>>8,a&255]))}function ye(t,e,r){let n=Math.floor(r/8),s=r%8;for(let i=0;i<n;i+=1)if(t[i]!==e[i])return!1;if(!s)return!0;let o=255<<8-s;return(t[n]&o)===(e[n]&o)}function ge(t){if(W.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(W.isIPv6(t)){let e=ue(t);if(!e)return!1;let r=ue("::ffff:0:0");return ye(e,r,96)?ge([...e.slice(12)].join(".")):ye(e,ue("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([s,o])=>ye(e,ue(s),o)):!1}return!1}function kt(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(It.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=W.isIP(r);return n!==0&&!ge(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:e,host:r,isLiteralIp:n!==0}}async function we(t,{lookupFn:e=Tt.promises.lookup}={}){let r=kt(t);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:W.isIPv6(r.host)?6:4}]};let n;if(process.env.ORACLE_HOSTED_EGRESS_PROXY)return{ok:!0,url:r.url,addresses:[]};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(s=>!ge(s.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}function Ot(t=process.env){let e=t.ORACLE_HOSTED_EGRESS_PROXY||"";if(!e)return null;let r;try{r=new URL(e)}catch{throw new Error("egress-guard: ORACLE_HOSTED_EGRESS_PROXY is not a URL")}if(r.protocol!=="http:"||!["127.0.0.1","::1","localhost","[::1]"].includes(r.hostname)||!r.port||r.username||r.password)throw new Error("egress-guard: egress proxy must be an exact loopback http origin");let n=t.ORACLE_HOSTED_EGRESS_TOKEN||"";if(!/^[A-Za-z0-9_-]{43}$/.test(n))throw new Error("egress-guard: egress proxy token is missing");return{uri:r.origin,token:n}}async function ve({requireUndici:t=!1,importUndici:e=()=>import("undici")}={}){let r,n,s;try{s=await e(),r=s.Agent,n=s.fetch}catch(f){if(t)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${f?.message||f}`);return null}if(typeof r!="function"||typeof n!="function"){if(t)throw new Error("egress-guard: untrustedUrl pinning requires undici's Agent and fetch exports, which were not found on the imported module");return null}let o=f=>String(f).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),i=new Map,u=f=>(Array.isArray(f)?f:[f]).map(d=>typeof d=="string"?{address:d}:d).filter(d=>d&&d.address).map(d=>({address:d.address,family:d.family||(W.isIPv6(d.address)?6:4)})),c=(f,d,m)=>{i.set(o(f),u(typeof d=="string"?[{address:d,family:m}]:d))},l=f=>{let d=o(f);if(W.isIP(d))return[{address:d,family:W.isIPv6(d)?6:4}];let m=i.get(d);if(!m||!m.length)throw new Error(`refused: unpinned host ${f} during pinned fetch`);return m},a=Ot(),p=a&&typeof s.ProxyAgent=="function"?new s.ProxyAgent({uri:a.uri,token:`Bearer ${a.token}`,connectTimeout:1e4}):new r({connect:{lookup(f,d,m){let b;try{b=l(f)}catch(E){return m(E)}return d?.all?m(null,b):m(null,b[0].address,b[0].family)}}}),h=Nt((f,d={})=>n(f,{...d,dispatcher:p}),c);return{dispatcher:p,fetch:h,pin:c,resolve:l,async close(){try{await p.destroy()}catch{}}}}var Ee=Symbol.for("oracle.egressGuard.pinCapableFetch");function Nt(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[Ee]=Object.freeze({pin:e}),t}function Se(t){return typeof t=="function"&&typeof t[Ee]?.pin=="function"}function $e(t,e,r){if(!Se(t))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");t[Ee].pin(e,r)}var Rt=new Set([408,425,429,500,502,503,504]),Fe=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),_t=2,De=4e3,Lt=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,Ut=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,qt=AbortSignal.prototype.throwIfAborted,Bt=EventTarget.prototype.addEventListener,je=EventTarget.prototype.removeEventListener,He=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null,te=t=>t?Lt.call(t):!1,$t=t=>t?Ut.call(t):void 0,Ft=new Set([301,302,303,307,308]),de=3,qr=64*1024,H=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});function k(t){return V(`HTTP JSON body refused: ${t}`)}function Dt(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 M[e]=="function"&&M[e](t))}function jt(t){let e=[],r=0,n=0,s=0,o=0,i=new WeakSet,u=a=>{if(r+=Buffer.byteLength(a,"utf8"),r>H.bytes)throw k("serialized byte limit exceeded");e.push(a)},c=a=>{if(Buffer.byteLength(a,"utf8")>H.bytes)throw k("serialized byte limit exceeded");return JSON.stringify(a)},l=(a,p)=>{if(n+=1,n>H.nodes)throw k("node limit exceeded");if(p>H.depth)throw k("depth limit exceeded");if(a===null){u("null");return}if(typeof a=="string"){u(c(a));return}if(typeof a=="boolean"){u(a?"true":"false");return}if(typeof a=="number"){if(!Number.isFinite(a))throw k("non-finite number");u(Object.is(a,-0)?"0":String(a));return}if(typeof a!="object")throw k("unsupported non-JSON value");if(M.isProxy(a))throw k("proxy value");if(Dt(a))throw k("unsupported exotic object");if(i.has(a))throw k("cyclic value");i.add(a);try{if(Object.getOwnPropertySymbols(a).length>0)throw k("symbol-keyed fields are unsupported");if(Array.isArray(a)){let d=Object.getPrototypeOf(a),m=0;for(;d!==null;){if(M.isProxy(d))throw k("proxy array prototype");if(m+=1,m>H.depth)throw k("array prototype depth limit exceeded");d=Object.getPrototypeOf(d)}if(a.length>H.arrayLength)throw k("array length limit exceeded");for(let E=0;E<a.length;E+=1){let P=Object.getOwnPropertyDescriptor(a,String(E));if(!P||!Object.hasOwn(P,"value")||P.enumerable!==!0)throw k("array entries must be dense enumerable own data")}let b=0;for(let E in a){if(o+=1,o>H.fields)throw k("enumeration limit exceeded");if(Object.hasOwn(a,E)&&(b+=1,b>a.length))throw k("named array fields are unsupported")}if(b!==a.length)throw k("array entries must be dense enumerable own data");u("[");for(let E=0;E<a.length;E+=1)E&&u(","),l(Object.getOwnPropertyDescriptor(a,String(E)).value,p+1);u("]");return}let h=Object.getPrototypeOf(a);if(h!==Object.prototype&&h!==null)throw k("non-plain object");let f=[];for(let d in a){if(o+=1,o>H.fields)throw k("enumeration limit exceeded");if(!Object.hasOwn(a,d))continue;if(s+=1,s>H.fields)throw k("field limit exceeded");let m=Object.getOwnPropertyDescriptor(a,d);if(!m||!Object.hasOwn(m,"value")||m.enumerable!==!0)throw k("object fields must be enumerable own data");f.push([d,m.value])}u("{");for(let d=0;d<f.length;d+=1)d&&u(","),u(c(f[d][0])),u(":"),l(f[d][1],p+1);u("}")}finally{i.delete(a)}};return l(t,0),e.join("")}function Ht(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(M.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 s=n.toLowerCase();if(r.has(s))throw new TypeError("HTTP headers contain a duplicate canonical name");r.add(s);let o=Object.getOwnPropertyDescriptor(t,n);if(!o||!Object.hasOwn(o,"value"))throw new TypeError("HTTP headers must contain own data properties");let i=o.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 Mt(){return Object.assign(Object.create(null),{Accept:"application/json"})}function Vt(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 zt(t,e){return new URL(String(t)).origin===new URL(String(e)).origin}var Ae=new Map,Me=new WeakMap,Ve=1;function le(t){if((typeof t!="object"||t===null)&&typeof t!="function")return`${typeof t}:${String(t)}`;let e=Me.get(t);return e||(e=Ve,Ve+=1,Me.set(t,e)),`reference:${e}`}var Wt=new Set(["eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","getHealth","minimumLedgerSlot","net_version","simulateTransaction","web3_clientVersion"]),Kt=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);function ze(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?Wt.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 We(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(ze);if(!r||typeof r!="object")return!1;if(Object.hasOwn(r,"jsonrpc")||Object.hasOwn(r,"method"))return ze(r);let n=Object.hasOwn(r,"type")?r.type:null;return typeof n=="string"&&Kt.has(n)&&(!Object.hasOwn(r,"action")||r.action==null)&&(!Object.hasOwn(r,"signature")||r.signature==null)&&(!Object.hasOwn(r,"nonce")||r.nonce==null)}function Gt(t,e,r,n={},s=null){let o=Pt("sha256"),i=(c,l)=>{let a=String(l);o.update(String(Buffer.byteLength(c,"utf8"))).update(":").update(c),o.update("=").update(String(Buffer.byteLength(a,"utf8"))).update(":").update(a).update(`
|
|
3
|
-
`)};i("method",t),i("url",e),Object.keys(r||{}).map((c,l)=>({name:c.toLowerCase(),order:l,value:String(r[c])})).sort((c,l)=>c.name.localeCompare(l.name)||c.order-l.order).forEach((c,l)=>{i(`header-name-${l}`,c.name),i(`header-value-${l}`,c.value)}),i("body",s??"-");for(let c of["untrustedUrl","maxResponseBytes","sameOriginRedirectsOnly","redirectPolicy","maxRedirects","timeoutMs","retries","fetchImpl","realFetch","lookupFn","importUndici","validateResponse"])i(`context-${c}`,n[c]??"-");return o.digest("hex")}function Qt(t,e){let r=Number(e);return Number.isFinite(r)&&r>0?Math.min(r*1e3,De):Math.min(250*2**t,De)+Math.floor(Math.random()*100)}var Yt=t=>new Promise(e=>setTimeout(e,t));function V(t,e={}){let r=new Error(t);return r.retryable=!1,Object.assign(r,e),r}function xe(t,e,r){return V(`HTTP response from ${t} exceeded maxResponseBytes ${r} (${e})`,{oversize:!0})}function K(t){try{let e=t?.body?.cancel?.();e&&typeof e.then=="function"&&e.catch(()=>{})}catch{}}function Jt(t){return t?t.byteLength??t.length??0:0}async function Xt(t,e,{url:r,truncate:n=!1,onOversize:s}={}){if(e==null)return await t.text();let o=Number(t.headers?.get?.("content-length"));if(Number.isFinite(o)&&o>e&&(K(t),!n))throw xe(r,`content-length ${o}`,e);let i=t.body?.getReader?.();if(!i){let p=await t.text(),h=Buffer.byteLength(p,"utf8");if(h>e){if(!n)throw xe(r,`body ${h} bytes`,e);return Buffer.from(p,"utf8").subarray(0,e).toString("utf8")}return p}let u=[],c=0,l=!1;try{for(;;){let{value:p,done:h}=await i.read();if(h)break;if(p&&(u.push(Buffer.from(p)),c+=Jt(p),c>e)){l=!0;break}}}finally{if(l)try{await i.cancel()}catch{}try{i.releaseLock?.()}catch{}}if(l&&(typeof s=="function"&&s(),!n))throw xe(r,`streamed ${c} bytes`,e);let a=Buffer.concat(u);return(l?a.subarray(0,e):a).toString("utf8")}function Zt(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function er(t,{fetchImpl:e,method:r,headers:n,body:s,timeoutMs:o,lookupFn:i,realFetch:u,untrustedUrl:c=!1,maxResponseBytes:l=null,sameOriginRedirectsOnly:a=!1,importUndici:p,validateResponse:h,signal:f,redirectPolicy:d="follow",maxRedirects:m=de}){let b=null,E=e,P=i?{lookupFn:i}:{};if(c&&!u&&!Se(E))throw V(`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 R=new AbortController,U=setTimeout(()=>R.abort(),o),O=f?He?He([f,R.signal]):f:R.signal,C=async(v,{status:T=null}={})=>{let S=await we(v,P);if(!S.ok)throw V(T==null?`HTTP refused ${v}: ${S.error}`:`HTTP redirect to ${v} ${S.error}`,T==null?{}:{status:T});let _=new URL(v).hostname;if(u){if(b&&(await b.close(),b=null),!b)try{b=await ve({requireUndici:!0,...p?{importUndici:p}:{}})}catch(y){throw V(T==null?`HTTP refused ${v}: ${y?.message||y}`:`HTTP redirect to ${v} refused: ${y?.message||y}`,T==null?{}:{status:T})}b.pin(_,S.addresses),E=b.fetch}else $e(E,_,S.addresses);return S};try{let v=String(t),T=Object.assign(Object.create(null),n||{});c&&await C(v);for(let S=0;S<=m;S+=1){let _=Object.assign(Object.create(null),{method:r,headers:T,body:s,signal:O,redirect:"manual",dispatcher:void 0}),y=await E(v,_);if((d==="error"||m===0)&&y.status>=300&&y.status<400)throw K(y),V(`HTTP ${y.status} ${r} redirect refused`,{status:y.status,redirectRefused:!0});if(Ft.has(y.status)){let q=a===!0&&r==="POST"&&[307,308].includes(y.status)&&We(r,s);if(r!=="GET"&&r!=="HEAD"&&!q){K(y);let N=new Error(`HTTP ${y.status} ${r} ${v} redirected non-idempotent request`);throw N.status=y.status,N}if(S===m)throw K(y),V(`HTTP ${y.status} ${r} redirect budget exhausted`,{status:y.status,redirectRefused:!0});let _e=y.headers?.get?.("location"),$;try{$=Vt(_e,v)}catch(N){throw K(y),N}let z=!zt($,v);if(K(y),z&&r==="POST"){let N=new Error(`HTTP ${y.status} ${r} cross-origin redirect refused`);throw N.status=y.status,N}if(z&&a){let N=new Error(`HTTP ${y.status} ${r} cross-origin redirect refused`);throw N.status=y.status,N.retryable=!1,N}if(z&&(T=Mt(T)),c)await C($,{status:y.status});else if(z){let N=await we($,P);if(!N.ok){let x=new Error(`HTTP redirect from ${v} ${N.error}`);throw x.status=y.status,x.retryable=!1,x}u&&N.addresses?.length&&(b||(b=await ve(p?{importUndici:p}:{})),b&&(b.pin(new URL($).hostname,N.addresses),E=b.fetch))}v=$;continue}if(typeof h=="function")try{await h(y,{url:v})}catch(q){throw K(y),V(q?.message||String(q))}let L=await Xt(y,l,{url:v,onOversize:()=>R.abort()}),X=Zt(L);if(!y.ok){let q=new Error(`HTTP ${y.status} ${r} ${v}`);throw q.status=y.status,q.retryAfter=y.headers?.get?.("retry-after")??null,q.body=X??L.slice(0,300),q}return X??L}throw new Error(`HTTP redirect loop for ${t}`)}catch(v){if(R.signal.aborted&&!te(f)){let T=v&&(typeof v=="object"||typeof v=="function")&&!M.isProxy(v)?v:null,S=T?Object.getOwnPropertyDescriptor(T,"oversize"):null;if(!(S&&Object.hasOwn(S,"value")&&S.value===!0))try{if(!T)throw new TypeError("unsafe rejection");Object.defineProperties(T,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}})}catch{let y=new Error("HTTP request timed out");throw Object.defineProperties(y,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}}),y}}throw v}finally{clearTimeout(U),b&&await b.close()}}async function pe(t,e={}){if(e!=null&&typeof e!="object"&&typeof e!="function")throw new TypeError("HTTP options must be an object");if(e!=null&&M.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 x of Object.getOwnPropertyNames(e)){let A=Object.getOwnPropertyDescriptor(e,x);if(!(x==="toJSON"&&A&&Object.hasOwn(A,"value")&&A.value===void 0)){if(!r.has(x))throw new TypeError("HTTP options contain unknown fields");if(!A||!A.enumerable||!Object.hasOwn(A,"value"))throw new TypeError("HTTP options must contain enumerable own data properties")}}}let n=x=>{if(e==null||!Object.hasOwn(e,x))return;let A=Object.getOwnPropertyDescriptor(e,x);if(!A||!Object.hasOwn(A,"value"))throw new TypeError("HTTP options must contain own data properties");return A.value};if(typeof t!="string"||t.length===0||t.length>8192)throw new TypeError("HTTP URL must be a bounded string");let s=n("method");if(s!==void 0&&(typeof s!="string"||!/^[A-Za-z]+$/u.test(s)))throw new TypeError("HTTP method must be a string token");let o=n("timeoutMs");if(o!==void 0&&(!Number.isInteger(o)||o<1||o>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 u=n("redirectPolicy");if(u!==void 0&&u!=="follow"&&u!=="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>de))throw new TypeError(`HTTP maxRedirects must be an integer from 0 through ${de}`);if(u==="error"&&c!==void 0&&c!==0)throw new TypeError('HTTP redirectPolicy "error" requires maxRedirects 0 when supplied');let l=u??"follow",a=l==="error"?0:c??de;for(let x of["dedupe","untrustedUrl","sameOriginRedirectsOnly"]){let A=n(x);if(A!==void 0&&typeof A!="boolean")throw new TypeError(`HTTP ${x} must be boolean`)}let p=n("maxResponseBytes");if(p!==void 0&&(!Number.isInteger(p)||p<1||p>64*1024*1024))throw new TypeError("HTTP maxResponseBytes must be a bounded integer");let h=n("signal");if(h!==void 0){if(M.isProxy(h)||!(h instanceof AbortSignal))throw new TypeError("HTTP signal must be a native AbortSignal");try{te(h)}catch{throw new TypeError("HTTP signal must be a native AbortSignal")}}for(let x of["importUndici","lookupFn","validateResponse"]){let A=n(x);if(A!==void 0&&typeof A!="function")throw new TypeError(`HTTP ${x} must be a function`)}let f=n("fetchImpl"),d=f||globalThis.fetch;if(typeof d!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let m=o??12e3,b=(s||"GET").toUpperCase(),E=n("headers"),P=Ht(E),R=Object.assign(Object.create(null),P);Object.keys(R).some(x=>x.toLowerCase()==="accept")||(R.Accept="application/json");let U=n("body");U!=null&&typeof U!="string"&&(Object.keys(R).find(A=>A.toLowerCase()==="content-type")||(R["Content-Type"]="application/json"),U=jt(U));let O=i??_t,C=n("lookupFn"),v=!f,T=n("untrustedUrl")===!0,S=n("sameOriginRedirectsOnly")===!0,_=n("importUndici"),y=n("validateResponse"),L=h,X=p??null,q=async()=>{let x;for(let A=0;A<=O;A++){L&&qt.call(L);let Le=ce("http");try{let j=await er(t,{fetchImpl:d,method:b,headers:R,body:U,timeoutMs:m,lookupFn:C,realFetch:v,untrustedUrl:T,maxResponseBytes:X,sameOriginRedirectsOnly:S,importUndici:_,validateResponse:y,signal:L,redirectPolicy:l,maxRedirects:a});return Le?.("succeeded"),j}catch(j){x=j;let Y=be=>{if(!j||typeof j!="object"&&typeof j!="function"||M.isProxy(j))return;let Z=Object.getOwnPropertyDescriptor(j,be);return Z&&Object.hasOwn(Z,"value")?Z.value:void 0},ie=Y("status");Le?.("failed",ie);let gt=Y("oracleTimeout")===!0||Y("name")==="AbortError"||Y("name")==="TimeoutError"||te(L),wt=new Set([408,425,429]),vt=Y("retryable")===!1?!1:ie!=null?wt.has(ie)||Rt.has(ie)&&Fe.has(b):!gt&&Fe.has(b);if(A===O||!vt)throw j;let Ue=Qt(A,Y("retryAfter")),Et=ce("retry"),qe=!1;try{L?await new Promise((be,Z)=>{let Be,ee=()=>{clearTimeout(Be),je.call(L,"abort",ee),Z($t(L)||new DOMException("Aborted","AbortError"))};if(te(L)){ee();return}Be=setTimeout(()=>{je.call(L,"abort",ee),be()},Ue),Bt.call(L,"abort",ee,{once:!0}),te(L)&&ee()}):await Yt(Ue),qe=!0}finally{Et?.(qe?"succeeded":"failed")}}}throw x};if(!(n("dedupe")!==!1&&!L&&We(b,U)))return q();let $=Gt(b,t,R,{untrustedUrl:T,maxResponseBytes:X,sameOriginRedirectsOnly:S,redirectPolicy:l,maxRedirects:a,timeoutMs:m,retries:O,fetchImpl:le(d),realFetch:v,lookupFn:le(C),importUndici:le(_),validateResponse:le(y)},U),z=Ae.get($);if(z){let x=ce("shared");try{let A=await z;return x?.("succeeded"),A}catch(A){throw x?.("failed"),A}}let N=q().finally(()=>Ae.delete($));return Ae.set($,N),N}async function Ke(t,e,r){let n=Array.from(t),s=Math.max(1,Math.min(Number(e)||1,n.length||1)),o=new Array(n.length),i=0;return await Promise.all(Array.from({length:s},async()=>{for(;i<n.length;){let u=i++;o[u]=await r(n[u],u)}})),o}var Ce={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}};var tr=new Map(Object.values(Ce).map(t=>[t.chainId,t]));function Ge(t){return tr.get(Number(t))||null}function Qe(t,e=process.env){let r=Ge(t);if(!r)return null;for(let n of r.rpcEnv){let s=(e[n]||"").trim();if(s)return s}return null}import{Interface as rr,getAddress as nr}from"ethers";var Ye=new rr(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);function Je(t,e){try{return nr(t).toLowerCase()}catch{throw new Error(`${e} must be a valid EVM address`)}}var or={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 sr(t,{rpcUrl:e,env:r=process.env}={}){if(e)return e;let n=Qe(t,r);return n||or[Number(t)]||null}var ar=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function ir(t){let e=String(t||""),r=e.toLowerCase();if(e!==e.trim()||!/^[a-zA-Z0-9_]+$/.test(e)||!ar.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 re=new Map,Xe=new Map;function cr(t){let e=new Error(t?.message||JSON.stringify(t));return e.code=t?.code,e}function ur(t){if(t?.error)throw cr(t.error);return t?.result}function lr(t,e,r){return`${t}
|
|
2
|
+
import{createHash as Pt}from"node:crypto";import{types as M}from"node:util";import{AsyncLocalStorage as St}from"node:async_hooks";var xt=new St,At=["http","retry","shared"],Ct=512;function ce(t){let e=xt.getStore();if(!e||e.closed||!At.includes(t))return null;if(e.spans.length>=Ct)return e.droppedSpans++,null;let r={stage:t,startMs:e.now()-e.start,durationMs:null,outcome:"pending",status:null};return e.spans.push(r),(n,s=null)=>{e.closed||r.durationMs!==null||(r.durationMs=Math.max(0,e.now()-e.start-r.startMs),r.outcome=n==="succeeded"?"succeeded":"failed",r.status=Number.isInteger(s)&&s>=100&&s<=599?s:null)}}import W from"node:net";import Tt from"node:dns";var It=new Set(["localhost","metadata.google.internal","metadata.goog"]);function ue(t){let e=String(t).toLowerCase().split("%")[0];if((e.match(/::/g)||[]).length>1)return null;let r=a=>{if(!a)return[];let p=a.split(":"),h=p.at(-1);if(h?.includes(".")){let f=h.split(".").map(Number);if(f.length!==4||f.some(d=>!Number.isInteger(d)||d<0||d>255))return null;p.splice(p.length-1,1,(f[0]<<8|f[1]).toString(16),(f[2]<<8|f[3]).toString(16))}return p.some(f=>!/^[0-9a-f]{1,4}$/.test(f))?null:p.map(f=>Number.parseInt(f,16))},[n,s]=e.split("::"),o=r(n),i=r(s);if(!o||!i)return null;let u=e.includes("::"),c=8-o.length-i.length;if(!u&&c!==0||u&&c<1)return null;let l=[...o,...Array(Math.max(0,c)).fill(0),...i];return l.length!==8?null:Uint8Array.from(l.flatMap(a=>[a>>8,a&255]))}function ye(t,e,r){let n=Math.floor(r/8),s=r%8;for(let i=0;i<n;i+=1)if(t[i]!==e[i])return!1;if(!s)return!0;let o=255<<8-s;return(t[n]&o)===(e[n]&o)}function ge(t){if(W.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(W.isIPv6(t)){let e=ue(t);if(!e)return!1;let r=ue("::ffff:0:0");return ye(e,r,96)?ge([...e.slice(12)].join(".")):ye(e,ue("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([s,o])=>ye(e,ue(s),o)):!1}return!1}function Ot(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(It.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let n=W.isIP(r);return n!==0&&!ge(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:e,host:r,isLiteralIp:n!==0}}async function we(t,{lookupFn:e=Tt.promises.lookup}={}){let r=Ot(t);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:W.isIPv6(r.host)?6:4}]};let n;if(process.env.ORACLE_HOSTED_EGRESS_PROXY)return{ok:!0,url:r.url,addresses:[]};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(s=>!ge(s.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:n}}function kt(t=process.env){let e=t.ORACLE_HOSTED_EGRESS_PROXY||"";if(!e)return null;let r;try{r=new URL(e)}catch{throw new Error("egress-guard: ORACLE_HOSTED_EGRESS_PROXY is not a URL")}if(r.protocol!=="http:"||!["127.0.0.1","::1","localhost","[::1]"].includes(r.hostname)||!r.port||r.username||r.password)throw new Error("egress-guard: egress proxy must be an exact loopback http origin");let n=t.ORACLE_HOSTED_EGRESS_TOKEN||"";if(!/^[A-Za-z0-9_-]{43}$/.test(n))throw new Error("egress-guard: egress proxy token is missing");return{uri:r.origin,token:n}}async function ve({requireUndici:t=!1,importUndici:e=()=>import("undici")}={}){let r,n,s;try{s=await e(),r=s.Agent,n=s.fetch}catch(f){if(t)throw new Error(`egress-guard: untrustedUrl pinning requires the undici package, which failed to load: ${f?.message||f}`);return null}if(typeof r!="function"||typeof n!="function"){if(t)throw new Error("egress-guard: untrustedUrl pinning requires undici's Agent and fetch exports, which were not found on the imported module");return null}let o=f=>String(f).toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,""),i=new Map,u=f=>(Array.isArray(f)?f:[f]).map(d=>typeof d=="string"?{address:d}:d).filter(d=>d&&d.address).map(d=>({address:d.address,family:d.family||(W.isIPv6(d.address)?6:4)})),c=(f,d,m)=>{i.set(o(f),u(typeof d=="string"?[{address:d,family:m}]:d))},l=f=>{let d=o(f);if(W.isIP(d))return[{address:d,family:W.isIPv6(d)?6:4}];let m=i.get(d);if(!m||!m.length)throw new Error(`refused: unpinned host ${f} during pinned fetch`);return m},a=kt(),p=a&&typeof s.ProxyAgent=="function"?new s.ProxyAgent({uri:a.uri,token:`Bearer ${a.token}`,connectTimeout:1e4}):new r({connect:{lookup(f,d,m){let b;try{b=l(f)}catch(E){return m(E)}return d?.all?m(null,b):m(null,b[0].address,b[0].family)}}}),h=Nt((f,d={})=>n(f,{...d,dispatcher:p}),c);return{dispatcher:p,fetch:h,pin:c,resolve:l,async close(){try{await p.destroy()}catch{}}}}var Ee=Symbol.for("oracle.egressGuard.pinCapableFetch");function Nt(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[Ee]=Object.freeze({pin:e}),t}function Se(t){return typeof t=="function"&&typeof t[Ee]?.pin=="function"}function Be(t,e,r){if(!Se(t))throw new Error("pinFetchToAddresses: fetchImpl is not pin-capable");t[Ee].pin(e,r)}var Rt=new Set([408,425,429,500,502,503,504]),Fe=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),_t=2,De=4e3,Lt=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,Ut=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,qt=AbortSignal.prototype.throwIfAborted,$t=EventTarget.prototype.addEventListener,je=EventTarget.prototype.removeEventListener,He=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null,te=t=>t?Lt.call(t):!1,Bt=t=>t?Ut.call(t):void 0,Ft=new Set([301,302,303,307,308]),de=3,qr=64*1024,H=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});function O(t){return V(`HTTP JSON body refused: ${t}`)}function Dt(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 M[e]=="function"&&M[e](t))}function jt(t){let e=[],r=0,n=0,s=0,o=0,i=new WeakSet,u=a=>{if(r+=Buffer.byteLength(a,"utf8"),r>H.bytes)throw O("serialized byte limit exceeded");e.push(a)},c=a=>{if(Buffer.byteLength(a,"utf8")>H.bytes)throw O("serialized byte limit exceeded");return JSON.stringify(a)},l=(a,p)=>{if(n+=1,n>H.nodes)throw O("node limit exceeded");if(p>H.depth)throw O("depth limit exceeded");if(a===null){u("null");return}if(typeof a=="string"){u(c(a));return}if(typeof a=="boolean"){u(a?"true":"false");return}if(typeof a=="number"){if(!Number.isFinite(a))throw O("non-finite number");u(Object.is(a,-0)?"0":String(a));return}if(typeof a!="object")throw O("unsupported non-JSON value");if(M.isProxy(a))throw O("proxy value");if(Dt(a))throw O("unsupported exotic object");if(i.has(a))throw O("cyclic value");i.add(a);try{if(Object.getOwnPropertySymbols(a).length>0)throw O("symbol-keyed fields are unsupported");if(Array.isArray(a)){let d=Object.getPrototypeOf(a),m=0;for(;d!==null;){if(M.isProxy(d))throw O("proxy array prototype");if(m+=1,m>H.depth)throw O("array prototype depth limit exceeded");d=Object.getPrototypeOf(d)}if(a.length>H.arrayLength)throw O("array length limit exceeded");for(let E=0;E<a.length;E+=1){let P=Object.getOwnPropertyDescriptor(a,String(E));if(!P||!Object.hasOwn(P,"value")||P.enumerable!==!0)throw O("array entries must be dense enumerable own data")}let b=0;for(let E in a){if(o+=1,o>H.fields)throw O("enumeration limit exceeded");if(Object.hasOwn(a,E)&&(b+=1,b>a.length))throw O("named array fields are unsupported")}if(b!==a.length)throw O("array entries must be dense enumerable own data");u("[");for(let E=0;E<a.length;E+=1)E&&u(","),l(Object.getOwnPropertyDescriptor(a,String(E)).value,p+1);u("]");return}let h=Object.getPrototypeOf(a);if(h!==Object.prototype&&h!==null)throw O("non-plain object");let f=[];for(let d in a){if(o+=1,o>H.fields)throw O("enumeration limit exceeded");if(!Object.hasOwn(a,d))continue;if(s+=1,s>H.fields)throw O("field limit exceeded");let m=Object.getOwnPropertyDescriptor(a,d);if(!m||!Object.hasOwn(m,"value")||m.enumerable!==!0)throw O("object fields must be enumerable own data");f.push([d,m.value])}u("{");for(let d=0;d<f.length;d+=1)d&&u(","),u(c(f[d][0])),u(":"),l(f[d][1],p+1);u("}")}finally{i.delete(a)}};return l(t,0),e.join("")}function Ht(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(M.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 s=n.toLowerCase();if(r.has(s))throw new TypeError("HTTP headers contain a duplicate canonical name");r.add(s);let o=Object.getOwnPropertyDescriptor(t,n);if(!o||!Object.hasOwn(o,"value"))throw new TypeError("HTTP headers must contain own data properties");let i=o.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 Mt(){return Object.assign(Object.create(null),{Accept:"application/json"})}function Vt(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 zt(t,e){return new URL(String(t)).origin===new URL(String(e)).origin}var xe=new Map,Me=new WeakMap,Ve=1;function le(t){if((typeof t!="object"||t===null)&&typeof t!="function")return`${typeof t}:${String(t)}`;let e=Me.get(t);return e||(e=Ve,Ve+=1,Me.set(t,e)),`reference:${e}`}var Wt=new Set(["eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","getHealth","minimumLedgerSlot","net_version","simulateTransaction","web3_clientVersion"]),Kt=new Set(["allMids","l2Book","outcomeMeta","spotClearinghouseState","userFills","meta","metaAndAssetCtxs","perpDexs","candleSnapshot","fundingHistory","openOrders","frontendOpenOrders","clearinghouseState","spotMeta","validatorSummaries","delegatorSummary","delegations","delegatorRewards","delegatorHistory","maxBuilderFee"]);function ze(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?Wt.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 We(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(ze);if(!r||typeof r!="object")return!1;if(Object.hasOwn(r,"jsonrpc")||Object.hasOwn(r,"method"))return ze(r);let n=Object.hasOwn(r,"type")?r.type:null;return typeof n=="string"&&Kt.has(n)&&(!Object.hasOwn(r,"action")||r.action==null)&&(!Object.hasOwn(r,"signature")||r.signature==null)&&(!Object.hasOwn(r,"nonce")||r.nonce==null)}function Gt(t,e,r,n={},s=null){let o=Pt("sha256"),i=(c,l)=>{let a=String(l);o.update(String(Buffer.byteLength(c,"utf8"))).update(":").update(c),o.update("=").update(String(Buffer.byteLength(a,"utf8"))).update(":").update(a).update(`
|
|
3
|
+
`)};i("method",t),i("url",e),Object.keys(r||{}).map((c,l)=>({name:c.toLowerCase(),order:l,value:String(r[c])})).sort((c,l)=>c.name.localeCompare(l.name)||c.order-l.order).forEach((c,l)=>{i(`header-name-${l}`,c.name),i(`header-value-${l}`,c.value)}),i("body",s??"-");for(let c of["untrustedUrl","maxResponseBytes","sameOriginRedirectsOnly","redirectPolicy","maxRedirects","timeoutMs","retries","fetchImpl","realFetch","lookupFn","importUndici","validateResponse"])i(`context-${c}`,n[c]??"-");return o.digest("hex")}function Qt(t,e){let r=Number(e);return Number.isFinite(r)&&r>0?Math.min(r*1e3,De):Math.min(250*2**t,De)+Math.floor(Math.random()*100)}var Yt=t=>new Promise(e=>setTimeout(e,t));function V(t,e={}){let r=new Error(t);return r.retryable=!1,Object.assign(r,e),r}function Ae(t,e,r){return V(`HTTP response from ${t} exceeded maxResponseBytes ${r} (${e})`,{oversize:!0})}function K(t){try{let e=t?.body?.cancel?.();e&&typeof e.then=="function"&&e.catch(()=>{})}catch{}}function Jt(t){return t?t.byteLength??t.length??0:0}async function Xt(t,e,{url:r,truncate:n=!1,onOversize:s}={}){if(e==null)return await t.text();let o=Number(t.headers?.get?.("content-length"));if(Number.isFinite(o)&&o>e&&(K(t),!n))throw Ae(r,`content-length ${o}`,e);let i=t.body?.getReader?.();if(!i){let p=await t.text(),h=Buffer.byteLength(p,"utf8");if(h>e){if(!n)throw Ae(r,`body ${h} bytes`,e);return Buffer.from(p,"utf8").subarray(0,e).toString("utf8")}return p}let u=[],c=0,l=!1;try{for(;;){let{value:p,done:h}=await i.read();if(h)break;if(p&&(u.push(Buffer.from(p)),c+=Jt(p),c>e)){l=!0;break}}}finally{if(l)try{await i.cancel()}catch{}try{i.releaseLock?.()}catch{}}if(l&&(typeof s=="function"&&s(),!n))throw Ae(r,`streamed ${c} bytes`,e);let a=Buffer.concat(u);return(l?a.subarray(0,e):a).toString("utf8")}function Zt(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function er(t,{fetchImpl:e,method:r,headers:n,body:s,timeoutMs:o,lookupFn:i,realFetch:u,untrustedUrl:c=!1,maxResponseBytes:l=null,sameOriginRedirectsOnly:a=!1,importUndici:p,validateResponse:h,signal:f,redirectPolicy:d="follow",maxRedirects:m=de}){let b=null,E=e,P=i?{lookupFn:i}:{};if(c&&!u&&!Se(E))throw V(`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 R=new AbortController,U=setTimeout(()=>R.abort(),o),k=f?He?He([f,R.signal]):f:R.signal,C=async(v,{status:T=null}={})=>{let S=await we(v,P);if(!S.ok)throw V(T==null?`HTTP refused ${v}: ${S.error}`:`HTTP redirect to ${v} ${S.error}`,T==null?{}:{status:T});let _=new URL(v).hostname;if(u){if(b&&(await b.close(),b=null),!b)try{b=await ve({requireUndici:!0,...p?{importUndici:p}:{}})}catch(y){throw V(T==null?`HTTP refused ${v}: ${y?.message||y}`:`HTTP redirect to ${v} refused: ${y?.message||y}`,T==null?{}:{status:T})}b.pin(_,S.addresses),E=b.fetch}else Be(E,_,S.addresses);return S};try{let v=String(t),T=Object.assign(Object.create(null),n||{});c&&await C(v);for(let S=0;S<=m;S+=1){let _=Object.assign(Object.create(null),{method:r,headers:T,body:s,signal:k,redirect:"manual",dispatcher:void 0}),y=await E(v,_);if((d==="error"||m===0)&&y.status>=300&&y.status<400)throw K(y),V(`HTTP ${y.status} ${r} redirect refused`,{status:y.status,redirectRefused:!0});if(Ft.has(y.status)){let q=a===!0&&r==="POST"&&[307,308].includes(y.status)&&We(r,s);if(r!=="GET"&&r!=="HEAD"&&!q){K(y);let N=new Error(`HTTP ${y.status} ${r} ${v} redirected non-idempotent request`);throw N.status=y.status,N}if(S===m)throw K(y),V(`HTTP ${y.status} ${r} redirect budget exhausted`,{status:y.status,redirectRefused:!0});let _e=y.headers?.get?.("location"),B;try{B=Vt(_e,v)}catch(N){throw K(y),N}let z=!zt(B,v);if(K(y),z&&r==="POST"){let N=new Error(`HTTP ${y.status} ${r} cross-origin redirect refused`);throw N.status=y.status,N}if(z&&a){let N=new Error(`HTTP ${y.status} ${r} cross-origin redirect refused`);throw N.status=y.status,N.retryable=!1,N}if(z&&(T=Mt(T)),c)await C(B,{status:y.status});else if(z){let N=await we(B,P);if(!N.ok){let A=new Error(`HTTP redirect from ${v} ${N.error}`);throw A.status=y.status,A.retryable=!1,A}u&&N.addresses?.length&&(b||(b=await ve(p?{importUndici:p}:{})),b&&(b.pin(new URL(B).hostname,N.addresses),E=b.fetch))}v=B;continue}if(typeof h=="function")try{await h(y,{url:v})}catch(q){throw K(y),V(q?.message||String(q))}let L=await Xt(y,l,{url:v,onOversize:()=>R.abort()}),X=Zt(L);if(!y.ok){let q=new Error(`HTTP ${y.status} ${r} ${v}`);throw q.status=y.status,q.retryAfter=y.headers?.get?.("retry-after")??null,q.body=X??L.slice(0,300),q}return X??L}throw new Error(`HTTP redirect loop for ${t}`)}catch(v){if(R.signal.aborted&&!te(f)){let T=v&&(typeof v=="object"||typeof v=="function")&&!M.isProxy(v)?v:null,S=T?Object.getOwnPropertyDescriptor(T,"oversize"):null;if(!(S&&Object.hasOwn(S,"value")&&S.value===!0))try{if(!T)throw new TypeError("unsafe rejection");Object.defineProperties(T,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}})}catch{let y=new Error("HTTP request timed out");throw Object.defineProperties(y,{oracleTimeout:{value:!0,enumerable:!1},retryable:{value:!1,enumerable:!1}}),y}}throw v}finally{clearTimeout(U),b&&await b.close()}}async function pe(t,e={}){if(e!=null&&typeof e!="object"&&typeof e!="function")throw new TypeError("HTTP options must be an object");if(e!=null&&M.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 A of Object.getOwnPropertyNames(e)){let x=Object.getOwnPropertyDescriptor(e,A);if(!(A==="toJSON"&&x&&Object.hasOwn(x,"value")&&x.value===void 0)){if(!r.has(A))throw new TypeError("HTTP options contain unknown fields");if(!x||!x.enumerable||!Object.hasOwn(x,"value"))throw new TypeError("HTTP options must contain enumerable own data properties")}}}let n=A=>{if(e==null||!Object.hasOwn(e,A))return;let x=Object.getOwnPropertyDescriptor(e,A);if(!x||!Object.hasOwn(x,"value"))throw new TypeError("HTTP options must contain own data properties");return x.value};if(typeof t!="string"||t.length===0||t.length>8192)throw new TypeError("HTTP URL must be a bounded string");let s=n("method");if(s!==void 0&&(typeof s!="string"||!/^[A-Za-z]+$/u.test(s)))throw new TypeError("HTTP method must be a string token");let o=n("timeoutMs");if(o!==void 0&&(!Number.isInteger(o)||o<1||o>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 u=n("redirectPolicy");if(u!==void 0&&u!=="follow"&&u!=="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>de))throw new TypeError(`HTTP maxRedirects must be an integer from 0 through ${de}`);if(u==="error"&&c!==void 0&&c!==0)throw new TypeError('HTTP redirectPolicy "error" requires maxRedirects 0 when supplied');let l=u??"follow",a=l==="error"?0:c??de;for(let A of["dedupe","untrustedUrl","sameOriginRedirectsOnly"]){let x=n(A);if(x!==void 0&&typeof x!="boolean")throw new TypeError(`HTTP ${A} must be boolean`)}let p=n("maxResponseBytes");if(p!==void 0&&(!Number.isInteger(p)||p<1||p>64*1024*1024))throw new TypeError("HTTP maxResponseBytes must be a bounded integer");let h=n("signal");if(h!==void 0){if(M.isProxy(h)||!(h instanceof AbortSignal))throw new TypeError("HTTP signal must be a native AbortSignal");try{te(h)}catch{throw new TypeError("HTTP signal must be a native AbortSignal")}}for(let A of["importUndici","lookupFn","validateResponse"]){let x=n(A);if(x!==void 0&&typeof x!="function")throw new TypeError(`HTTP ${A} must be a function`)}let f=n("fetchImpl"),d=f||globalThis.fetch;if(typeof d!="function")throw new Error("fetch unavailable \u2014 pass opts.fetchImpl");let m=o??12e3,b=(s||"GET").toUpperCase(),E=n("headers"),P=Ht(E),R=Object.assign(Object.create(null),P);Object.keys(R).some(A=>A.toLowerCase()==="accept")||(R.Accept="application/json");let U=n("body");U!=null&&typeof U!="string"&&(Object.keys(R).find(x=>x.toLowerCase()==="content-type")||(R["Content-Type"]="application/json"),U=jt(U));let k=i??_t,C=n("lookupFn"),v=!f,T=n("untrustedUrl")===!0,S=n("sameOriginRedirectsOnly")===!0,_=n("importUndici"),y=n("validateResponse"),L=h,X=p??null,q=async()=>{let A;for(let x=0;x<=k;x++){L&&qt.call(L);let Le=ce("http");try{let j=await er(t,{fetchImpl:d,method:b,headers:R,body:U,timeoutMs:m,lookupFn:C,realFetch:v,untrustedUrl:T,maxResponseBytes:X,sameOriginRedirectsOnly:S,importUndici:_,validateResponse:y,signal:L,redirectPolicy:l,maxRedirects:a});return Le?.("succeeded"),j}catch(j){A=j;let Y=be=>{if(!j||typeof j!="object"&&typeof j!="function"||M.isProxy(j))return;let Z=Object.getOwnPropertyDescriptor(j,be);return Z&&Object.hasOwn(Z,"value")?Z.value:void 0},ie=Y("status");Le?.("failed",ie);let gt=Y("oracleTimeout")===!0||Y("name")==="AbortError"||Y("name")==="TimeoutError"||te(L),wt=new Set([408,425,429]),vt=Y("retryable")===!1?!1:ie!=null?wt.has(ie)||Rt.has(ie)&&Fe.has(b):!gt&&Fe.has(b);if(x===k||!vt)throw j;let Ue=Qt(x,Y("retryAfter")),Et=ce("retry"),qe=!1;try{L?await new Promise((be,Z)=>{let $e,ee=()=>{clearTimeout($e),je.call(L,"abort",ee),Z(Bt(L)||new DOMException("Aborted","AbortError"))};if(te(L)){ee();return}$e=setTimeout(()=>{je.call(L,"abort",ee),be()},Ue),$t.call(L,"abort",ee,{once:!0}),te(L)&&ee()}):await Yt(Ue),qe=!0}finally{Et?.(qe?"succeeded":"failed")}}}throw A};if(!(n("dedupe")!==!1&&!L&&We(b,U)))return q();let B=Gt(b,t,R,{untrustedUrl:T,maxResponseBytes:X,sameOriginRedirectsOnly:S,redirectPolicy:l,maxRedirects:a,timeoutMs:m,retries:k,fetchImpl:le(d),realFetch:v,lookupFn:le(C),importUndici:le(_),validateResponse:le(y)},U),z=xe.get(B);if(z){let A=ce("shared");try{let x=await z;return A?.("succeeded"),x}catch(x){throw A?.("failed"),x}}let N=q().finally(()=>xe.delete(B));return xe.set(B,N),N}async function Ke(t,e,r){let n=Array.from(t),s=Math.max(1,Math.min(Number(e)||1,n.length||1)),o=new Array(n.length),i=0;return await Promise.all(Array.from({length:s},async()=>{for(;i<n.length;){let u=i++;o[u]=await r(n[u],u)}})),o}var Ce={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},elysium:{chainId:1339,name:"Elysium",rpcEnv:["ELYSIUM_RPC_URL"],evm:!0,readOnly:!0}};var tr=new Map(Object.values(Ce).map(t=>[t.chainId,t]));function Ge(t){return tr.get(Number(t))||null}function Qe(t,e=process.env){let r=Ge(t);if(!r)return null;for(let n of r.rpcEnv){let s=(e[n]||"").trim();if(s)return s}return null}import{Interface as rr,getAddress as nr}from"ethers";var Ye=new rr(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);function Je(t,e){try{return nr(t).toLowerCase()}catch{throw new Error(`${e} must be a valid EVM address`)}}var or={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",1339:"https://rpc.elysiumchain.tech"};function sr(t,{rpcUrl:e,env:r=process.env}={}){if(e)return e;let n=Qe(t,r);return n||or[Number(t)]||null}var ar=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;function ir(t){let e=String(t||""),r=e.toLowerCase();if(e!==e.trim()||!/^[a-zA-Z0-9_]+$/.test(e)||!ar.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 re=new Map,Xe=new Map;function cr(t){let e=new Error(t?.message||JSON.stringify(t));return e.code=t?.code,e}function ur(t){if(t?.error)throw cr(t.error);return t?.result}function lr(t,e,r){return`${t}
|
|
4
4
|
${e}
|
|
5
5
|
${JSON.stringify(r??[])}`}async function dr(t,e,r){return pe(t,{method:"POST",body:e,fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??12e3,signal:r.signal})}async function F(t,e,r=[],n={}){let s=String(e||""),o=ir(s),i=sr(t,n);if(!i)throw new Error(`No RPC URL for chainId ${t} (set env from chain registry rpcEnv or pass rpcUrl)`);if(o==="eth_chainid"&&n.cacheChainId!==!1){let a=Xe.get(i);if(a!=null)return a}let c=n.dedupe!==!1&&!n.signal?lr(i,s,r):null;if(c&&re.has(c))return re.get(c);let l=(async()=>{let a=await dr(i,{jsonrpc:"2.0",id:1,method:e,params:r},n),p=ur(a);return o==="eth_chainid"&&typeof p=="string"&&Xe.set(i,p),p})();return c&&(re.set(c,l),l.finally(()=>{re.get(c)===l&&re.delete(c)}).catch(()=>{})),l}async function Ze(t,e={}){let r=await F(t,"eth_blockNumber",[],e);return parseInt(r,16)}async function et(t,e,r={}){if(!e)throw new Error("rpcGetBalance requires address");let n=await F(t,"eth_getBalance",[e,"latest"],r);return{chainId:Number(t),address:e,balanceWei:BigInt(n).toString(),balanceHex:n}}async function tt(t={},e={}){let r=Number(t.chainId??e.chainId??1),n=Je(t.token||t.tokenAddress,"token"),s=Je(t.account||t.owner||t.address,"account"),o=Ye.encodeFunctionData("balanceOf",[s]),i=await F(r,"eth_call",[{to:n,data:o},t.blockTag||"latest"],e),u=Ye.decodeFunctionResult("balanceOf",i),c=BigInt(u[0]);return{chainId:r,token:n,account:s,balance:c.toString(),balanceHex:`0x${c.toString(16)}`,blockTag:t.blockTag||"latest"}}var pr=new Set(["usdc","usdt","usdg","dai","usd1","usde","pyusd"]);function rt(t,e){let r=String(t||"").toLowerCase(),n=String(e?.quote||e?.quoteToken?.address||"").toLowerCase(),s=String(e?.base||e?.baseToken?.address||"").toLowerCase();return n===r?{address:e.base||e.baseToken?.address,symbol:e.baseToken?.symbol}:s===r?{address:e.quote||e.quoteToken?.address,symbol:e.quoteToken?.symbol}:{address:e.quote||e.quoteToken?.address,symbol:e.quoteToken?.symbol}}function Te(t,e=[],{stables:r=[],wrappedNative:n=null}={}){let s=String(t||"").toLowerCase(),o=new Set((r||[]).map(c=>String(c).toLowerCase())),i=String(n||"").toLowerCase(),u=(e||[]).map((c,l)=>{let a=rt(s,c),p=String(a.address||"").toLowerCase(),h=String(a.symbol||"").toLowerCase(),f=Number(c.liquidityUsd??c.liquidity?.usd),d=Number.isFinite(f)?f:0,m=String(c.dex||c.dexId||"").toLowerCase(),b=0;return o.has(p)||pr.has(h)?b=300:i&&p===i&&(b=100),m.includes("v4")?b+=20:m.includes("v3")?b+=10:(m.includes("v2")||m.includes("raydium")||m.includes("orca")||m.includes("meteora"))&&(b+=8),{pool:c,score:b*1e12+d,index:l,otherAddr:p,liquidityUsd:d}});return u.sort((c,l)=>l.score-c.score||c.index-l.index),u.map(c=>c.pool)}function nt(t,e=[]){let r=Array.isArray(e)?e:[];return r.length&&rt(t,r[0]).address||null}var fr="https://api.dexscreener.com",Qr=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"});function hr(t={}){return(t.baseUrl||process.env.DEXSCREENER_API_URL||fr).replace(/\/$/,"")}function mr(t,e){if(typeof t!="string"&&typeof t!="number")throw new Error(`${e} required`);let r=String(t).trim();if(!r||r.length>128||!/^[A-Za-z0-9][A-Za-z0-9._:+~-]*$/u.test(r))throw new Error(`${e} must be a valid path component of at most 128 characters`);return encodeURIComponent(r)}function br(t,e){return pe(`${hr(e)}${t}`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}async function ot(t,e={}){return br(`/latest/dex/tokens/${mr(t,"tokenAddress")}`,e)}var ne=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),w=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),g=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"}),yr=/^0x[0-9a-fA-F]{40}$/;function gr(t={}){let e=[],r=[];if(!t||typeof t!="object")return{ok:!1,errors:["definition must be an object"],warnings:r};if((!Number.isInteger(t.chainId)||t.chainId<=0)&&e.push("chainId must be a positive integer"),(typeof t.key!="string"||!/^[a-z][a-z0-9-]*$/.test(t.key||""))&&e.push('key must be a lowercase slug (e.g. "base")'),(typeof t.name!="string"||!t.name.trim())&&e.push("name is required"),!Array.isArray(t.rpcEnv)||t.rpcEnv.length===0)e.push("rpcEnv must list at least one environment variable name");else for(let s of t.rpcEnv)(typeof s!="string"||!/^[A-Z][A-Z0-9_]*$/.test(s))&&e.push(`rpcEnv entry "${s}" should be an UPPER_SNAKE env var name`);if(t.nativeCurrency){let s=t.nativeCurrency;(typeof s.symbol!="string"||!s.symbol)&&e.push("nativeCurrency.symbol is required when nativeCurrency is set"),Number.isInteger(s.decimals)||e.push("nativeCurrency.decimals must be an integer")}for(let[s,o]of(t.venues||[]).entries()){let i=`venues[${s}]`;if(!o||typeof o!="object"){e.push(`${i} must be an object`);continue}yr.test(o.address||"")||e.push(`${i}.address is not a valid 20-byte address`),/^0x0{40}$/.test(o.address||"")&&e.push(`${i}.address is the zero address -- placeholder left in place?`),o.kind||e.push(`${i}.kind is required (router|quoter|factory|...)`),o.verified?(o.verified.method||e.push(`${i}.verified.method is required`),o.verified.source||e.push(`${i}.verified.source is required`),o.verified.date||r.push(`${i}.verified.date missing -- add one so staleness is visible`)):e.push(`${i} must record verification: { verified: { method, source, date } }. An unverified venue stays blocked.`)}let n=t.capabilities||{};for(let s of Object.keys(n))ne.includes(s)?typeof n[s]!="function"&&e.push(`capability "${s}" must be a function`):e.push(`unknown capability "${s}"`);return Object.keys(n).length===0&&r.push("scanner implements no capabilities -- it can only be registered, not used"),n.prepareUnsignedTx&&!n.quote&&r.push("prepareUnsignedTx without quote: no priced expectation to validate the built tx against"),n.prepareUnsignedTx&&!n.sellSimulation&&r.push("prepareUnsignedTx without sellSimulation: cannot prove an asset is exitable before buying"),{ok:e.length===0,errors:e,warnings:r}}function wr(t){let{ok:e,errors:r,warnings:n}=gr(t);if(!e)throw new Error(`invalid scanner for ${t?.key??"<unknown>"}:
|
|
6
6
|
- ${r.join(`
|
|
7
|
-
- `)}`);let s=t.capabilities||{},o=ne.filter(u=>typeof s[u]=="function"),i={key:t.key,chainId:t.chainId,name:t.name,rpcEnv:[...t.rpcEnv],nativeCurrency:t.nativeCurrency?{...t.nativeCurrency}:null,wrappedNative:t.wrappedNative||null,explorer:t.explorer||null,venues:(t.venues||[]).map(u=>({...u})),warnings:n,capabilities(){return{chainId:t.chainId,key:t.key,supported:[...o],unsupported:ne.filter(u=>!o.includes(u))}},supports(u){return o.includes(u)}};for(let u of ne)o.includes(u)?i[u]=async(...c)=>s[u](...c,{scanner:i}):i[u]=async()=>{throw new Error(`${t.key} (chain ${t.chainId}) does not implement "${u}". Supported: ${o.join(", ")||"none"}. An unimplemented capability is absent, not assumed -- implement it or treat this chain as fail-closed for that operation.`)};return Object.freeze(i)}var oe=new Map;function st(t){let e=wr(t);return oe.set(e.chainId,e),e}function Ie(t){return oe.get(Number(t))||null}function fe(){return[...oe.values()]}function at(){let t={};for(let e of oe.values())t[e.chainId]={key:e.key,name:e.name,...e.capabilities(),venueCount:e.venues.length,failClosed:e.venues.length===0};return{generatedAt:new Date().toISOString(),chainCount:oe.size,capabilities:[...ne],chains:t}}var Oe={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},B=t=>BigInt(t).toString(16).padStart(64,"0"),se=t=>t.slice(2).toLowerCase().padStart(64,"0");function vr(t,e){return`0x${Oe.getAmountsOut}`+B(t)+B(64)+B(e.length)+e.map(se).join("")}function Er(t){if(!t||t==="0x")return null;let e=t.slice(2);if(e.length<128)return null;let r=Number(BigInt(`0x${e.slice(64,128)}`));if(!Number.isFinite(r)||r<1||r>16)return null;let n=[];for(let s=0;s<r;s++){let o=128+s*64;if(e.length<o+64)return null;n.push(BigInt(`0x${e.slice(o,o+64)}`))}return n}function ke(t,e="router"){return(t?.venues||[]).find(n=>n.kind===e)?.address??null}var Ne=100;function Sr(t,e){let r=Number(e);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>Ne)throw new Error(`slippageBps ${r} exceeds the ${Ne} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(t)*BigInt(1e4-Math.floor(r))/10000n}function it(t){let{chainId:e,wrappedNative:r}=t;async function n(s,o,i,u){let c=await F(e,"eth_call",[{to:s,data:vr(o,i)},"latest"],u);return Er(c?.result??c)}return{async quote({tokenIn:s,tokenOut:o,amountIn:i,path:u},c={}){let l=ke(c.scanner);if(!l)return{chainId:e,evidence:w.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let a=u||[s,o];if(a.some(h=>!/^0x[0-9a-fA-F]{40}$/.test(h||"")))throw new Error("quote requires valid 20-byte addresses");let p=await n(l,i,a,c);return p?{chainId:e,router:l,path:a,amountIn:String(i),amountOut:p[p.length-1].toString(),hops:a.length-1,evidence:w.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:e,router:l,path:a,evidence:w.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:s,amountIn:o,base:i},u={}){let c=ke(u.scanner),l=i||r;if(l&&String(s).toLowerCase()===String(l).toLowerCase())return{chainId:e,token:s,verdict:g.UNKNOWN,evidence:w.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!c||!l)return{chainId:e,token:s,verdict:g.UNKNOWN,evidence:w.UNAVAILABLE,reason:c?"no wrappedNative configured for this chain, so no base asset to round-trip against":"no verified router configured for this chain"};let a=await n(c,o,[l,s],u);if(!a)return{chainId:e,token:s,verdict:g.FAIL,evidence:w.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let p=a[a.length-1];if(p===0n)return{chainId:e,token:s,verdict:g.FAIL,evidence:w.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let h=await n(c,p,[s,l],u);if(!h)return{chainId:e,token:s,verdict:g.FAIL,evidence:w.LIVE,leg:"sell",bought:p.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let f=h[h.length-1],d=Number(f*10000n/BigInt(o)),m=g.PASS,b="round trip completes with expected fee/impact loss";return d<5e3?(m=g.FAIL,b=`round trip returns only ${(d/100).toFixed(2)}% -- punitive tax or no real liquidity`):d<9e3&&(m=g.CAUTION,b=`round trip returns ${(d/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,token:s,base:l,router:c,verdict:m,reason:b,amountIn:String(o),bought:p.toString(),returned:f.toString(),retentionBps:d,evidence:w.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:s,tokenOut:o,amountIn:i,recipient:u,slippageBps:c=50,deadlineSeconds:l=900,path:a},p={}){let h=p.scanner,f=ke(h);if(!f)throw new Error(`chain ${e} has no verified router; preparing a swap stays fail-closed. Add a venue with recorded provenance first (see docs/adding-a-chain.md).`);if(!/^0x[0-9a-fA-F]{40}$/.test(u||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let d=a||[s,o],m=await this.quote({tokenIn:s,tokenOut:o,amountIn:i,path:d},p);if(m.evidence!==w.LIVE)throw new Error(`cannot prepare without a live quote (${m.evidence}: ${m.reason??"no reason given"})`);let b=Sr(m.amountOut,c);if(b<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let E=BigInt(Math.floor(Date.now()/1e3)+Number(l)),P=r&&d[0].toLowerCase()===r.toLowerCase()&&p.useNative,R=P?`0x${Oe.swapExactETHForTokens}`+B(b)+B(128)+se(u)+B(E)+B(d.length)+d.map(se).join(""):`0x${Oe.swapExactTokensForTokens}`+B(i)+B(b)+B(160)+se(u)+B(E)+B(d.length)+d.map(se).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:e,tx:{to:f,data:R,value:P?`0x${BigInt(i).toString(16)}`:"0x0"},guard:{quotedOut:m.amountOut,minOut:b.toString(),slippageBps:c,maxSlippageBps:Ne,deadline:E.toString()},requires:P?[]:[{step:"approve",token:d[0],spender:f,amount:String(i)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}var Ar=[100,500,3e3,1e4],ct={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},G=t=>BigInt(t).toString(16).padStart(64,"0"),ae=t=>t.slice(2).toLowerCase().padStart(64,"0"),ut=/^0x[0-9a-fA-F]{40}$/,Re=100;function xr(t,e){let r=Number(e);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>Re)throw new Error(`slippageBps ${r} exceeds the ${Re} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(t)*BigInt(1e4-Math.floor(r))/10000n}function Pe(t,e){return(t?.venues||[]).find(r=>r.kind===e)?.address??null}function lt(t){let{chainId:e,wrappedNative:r}=t;async function n({quoter:o,tokenIn:i,tokenOut:u,amountIn:c,fee:l},a){let p=`0x${ct.quoteExactInputSingle}`+ae(i)+ae(u)+G(c)+G(l)+G(0),h=await F(e,"eth_call",[{to:o,data:p},"latest"],a).catch(()=>null),f=h?.result??h;if(!f||f==="0x"||f.length<66)return null;let d=BigInt(`0x${f.slice(2,66)}`);return d>0n?d:null}async function s({quoter:o,tokenIn:i,tokenOut:u,amountIn:c},l){let a=await Promise.all(Ar.map(async h=>{let f=await n({quoter:o,tokenIn:i,tokenOut:u,amountIn:c,fee:h},l);return{fee:h,amountOut:f?f.toString():null,out:f}})),p=null;for(let h of a)h.out&&(!p||h.out>p.amountOut)&&(p={fee:h.fee,amountOut:h.out});return{best:p,tried:a.map(({fee:h,amountOut:f})=>({fee:h,amountOut:f}))}}return{async quote({tokenIn:o,tokenOut:i,amountIn:u},c={}){let l=Pe(c.scanner,"quoter");if(!l)return{chainId:e,evidence:w.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let h of[o,i])if(!ut.test(h||""))throw new Error("quote requires valid 20-byte addresses");let{best:a,tried:p}=await s({quoter:l,tokenIn:o,tokenOut:i,amountIn:u},c);return a?{chainId:e,venue:"uniswap-v3",quoter:l,tokenIn:o,tokenOut:i,amountIn:String(u),amountOut:a.amountOut.toString(),fee:a.fee,useNative:!!r&&String(o).toLowerCase()===String(r).toLowerCase(),triedFeeTiers:p,evidence:w.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:e,quoter:l,tokenIn:o,tokenOut:i,triedFeeTiers:p,evidence:w.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:o,amountIn:i,base:u},c={}){let l=Pe(c.scanner,"quoter"),a=(t.stableQuoteAssets||[]).map(O=>String(O).toLowerCase()),p=null;!u&&typeof t.resolveQuoteAsset=="function"&&(p=await t.resolveQuoteAsset(o,c).catch(()=>null));let h=String(o).toLowerCase(),f=String(r||"").toLowerCase();if(f&&h===f)return{chainId:e,token:o,verdict:g.UNKNOWN,evidence:w.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};let d=u||p||(a[0]&&h!==a[0]?a[0]:null)||r;if(d&&h===String(d).toLowerCase())return{chainId:e,token:o,verdict:g.UNKNOWN,evidence:w.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!l||!d)return{chainId:e,token:o,verdict:g.UNKNOWN,evidence:w.UNAVAILABLE,reason:l?"no wrappedNative configured, so there is no base asset to round-trip against":"no verified quoter configured for this chain"};let m=await s({quoter:l,tokenIn:d,tokenOut:o,amountIn:i},c);if(!m.best){let O=a.find(C=>C&&C!==String(d).toLowerCase()&&C!==String(o).toLowerCase());if(O){let C=await s({quoter:l,tokenIn:O,tokenOut:o,amountIn:i},c);if(C.best){let v=await s({quoter:l,tokenIn:o,tokenOut:O,amountIn:C.best.amountOut},c);if(v.best){let T=v.best.amountOut,S=Number(T*10000n/BigInt(i)),_=g.PASS,y="round trip vs dollar book completes with expected fee/impact loss";return S<5e3?(_=g.FAIL,y=`round trip vs dollar book returns only ${(S/100).toFixed(2)}% -- punitive tax or no real liquidity`):S<9e3&&(_=g.CAUTION,y=`round trip vs dollar book returns ${(S/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,venue:"uniswap-v3",token:o,base:O,quoteAsset:O,verdict:_,reason:y,amountIn:String(i),bought:C.best.amountOut.toString(),returned:T.toString(),retentionBps:S,buyFee:C.best.fee,sellFee:v.best.fee,evidence:w.LIVE,note:"Quoted against the dollar book, not wrapped native. A missing WETH pool is not a honeypot."}}}}return{chainId:e,token:o,verdict:g.FAIL,evidence:w.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier against wrapped native or the dollar book"}}let b=await s({quoter:l,tokenIn:o,tokenOut:d,amountIn:m.best.amountOut},c);if(!b.best){let O=a.find(C=>C&&C!==String(d).toLowerCase()&&C!==String(o).toLowerCase());if(O){let C=await s({quoter:l,tokenIn:O,tokenOut:o,amountIn:i},c),v=C.best?await s({quoter:l,tokenIn:o,tokenOut:O,amountIn:C.best.amountOut},c):{best:null};if(C.best&&v.best){let T=v.best.amountOut,S=Number(T*10000n/BigInt(i)),_=g.PASS,y="round trip vs dollar book completes; missing WETH sell pool is not a honeypot";return S<5e3?(_=g.FAIL,y=`dollar-book round trip returns only ${(S/100).toFixed(2)}%`):S<9e3&&(_=g.CAUTION,y=`dollar-book round trip returns ${(S/100).toFixed(2)}%`),{chainId:e,venue:"uniswap-v3",token:o,base:O,quoteAsset:O,verdict:_,reason:y,amountIn:String(i),bought:C.best.amountOut.toString(),returned:T.toString(),retentionBps:S,buyFee:C.best.fee,sellFee:v.best.fee,evidence:w.LIVE,note:"Sell vs wrapped native failed; dollar book succeeded. Not labelled honeypot."}}}return{chainId:e,token:o,verdict:g.FAIL,evidence:w.LIVE,leg:"sell",bought:m.best.amountOut.toString(),reason:"SELL LEG FAILED against wrapped native and the dollar book. This is the honeypot signature: do not trade."}}let E=b.best.amountOut,P=Number(E*10000n/BigInt(i)),R=g.PASS,U="round trip completes with expected fee/impact loss";return P<5e3?(R=g.FAIL,U=`round trip returns only ${(P/100).toFixed(2)}% -- punitive tax or no real liquidity`):P<9e3&&(R=g.CAUTION,U=`round trip returns ${(P/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,venue:"uniswap-v3",token:o,base:d,verdict:R,reason:U,amountIn:String(i),bought:m.best.amountOut.toString(),returned:E.toString(),retentionBps:P,buyFee:m.best.fee,sellFee:b.best.fee,evidence:w.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:o,tokenOut:i,amountIn:u,recipient:c,slippageBps:l=50,fee:a},p={}){let h=Pe(p.scanner,"router");if(!h)throw new Error(`chain ${e} has no verified V3 router; preparing a swap stays fail-closed. Add a venue with recorded provenance first (see docs/adding-a-chain.md).`);if(!ut.test(c||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let f=await this.quote({tokenIn:o,tokenOut:i,amountIn:u},p);if(f.evidence!==w.LIVE)throw new Error(`cannot prepare without a live quote (${f.evidence}: ${f.reason??"no reason given"})`);let d=a??f.fee,m=xr(f.amountOut,l);if(m<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let b=!!(p.useNative||f.useNative)&&r&&String(o).toLowerCase()===String(r).toLowerCase(),E=`0x${ct.exactInputSingle}`+ae(o)+ae(i)+G(d)+ae(c)+G(u)+G(m)+G(0);return{unsigned:!0,signedBy:"user-wallet",chainId:e,venue:"uniswap-v3",tx:{to:h,data:E,value:b?String(u):"0x0"},guard:{quotedOut:f.amountOut,minOut:m.toString(),slippageBps:l,maxSlippageBps:Re,fee:d},requires:b?[]:[{step:"approve",token:o,spender:h,amount:String(u)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}var he={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function dt(t){if(!t||t==="0x")return null;try{return BigInt(t)}catch{return null}}function pt(t){if(!t||t==="0x")return null;let e=t.slice(2);if(e.length>=128){let n=Number(BigInt(`0x${e.slice(64,128)}`));if(n>0&&n<=256&&e.length>=128+n*2){let s=e.slice(128,128+n*2),o=Buffer.from(s,"hex").toString("utf8").replace(/\0+$/,"");if(o)return o}}return Buffer.from(e.slice(0,64),"hex").toString("utf8").replace(/\0+$/,"")||null}function Cr(t){let{chainId:e}=t;async function r(n,s,o){return F(e,"eth_call",[{to:n,data:s},"latest"],o)}return{async blockNumber(n={}){let s=await Ze(e,n);return{chainId:e,blockNumber:s?.blockNumber??s,evidence:w.LIVE}},async nativeBalance(n,s={}){let o=await et(e,n,s);return{chainId:e,address:n,wei:o?.wei??o?.balance??null,symbol:t.nativeCurrency?.symbol??null,decimals:t.nativeCurrency?.decimals??18,evidence:w.LIVE}},async tokenBalance({token:n,owner:s},o={}){let i=await tt({chainId:e,token:n,owner:s},o);return{chainId:e,token:n,owner:s,raw:i?.balance??i,evidence:w.LIVE}},async resolveToken(n,s={}){if(!/^0x[0-9a-fA-F]{40}$/.test(n||""))return{chainId:e,token:n,evidence:w.UNKNOWN,error:"resolveToken needs a 20-byte address; symbol lookup is a market-data concern"};let[o,i,u,c]=await Promise.all([r(n,he.decimals,s).catch(()=>null),r(n,he.symbol,s).catch(()=>null),r(n,he.name,s).catch(()=>null),r(n,he.totalSupply,s).catch(()=>null)]),l=dt(o?.result??o),a=l!==null||i?.result||u?.result,p={chainId:e,address:n,decimals:l===null?null:Number(l),symbol:pt(i?.result??i),name:pt(u?.result??u),totalSupply:(dt(c?.result??c)??null)?.toString()??null,evidence:a?w.LIVE:w.UNKNOWN};return a||(p.warning="no ERC-20 metadata returned -- may not be a token contract"),p},async resolvePools(n,s={}){let o=t.dexscreenerSlug;if(!o)return{chainId:e,token:n,pools:[],evidence:w.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let i=await ot(n,s).catch(()=>null),c=(i?.pairs||i?.data?.pairs||[]).filter(a=>String(a.chainId).toLowerCase()===String(o).toLowerCase()).map(a=>({pair:a.pairAddress,dex:a.dexId,base:a.baseToken?.address,quote:a.quoteToken?.address,liquidityUsd:a.liquidity?.usd??null,priceUsd:a.priceUsd??null,volume24hUsd:a.volume?.h24??null,createdAt:a.pairCreatedAt??null})).sort((a,p)=>(p.liquidityUsd??0)-(a.liquidityUsd??0)),l=Te(n,c,{stables:t.stableQuoteAssets||[],wrappedNative:t.wrappedNative});return{chainId:e,token:n,pools:l,topPool:l[0]||null,quoteAsset:nt(n,l),evidence:l.length?w.LIVE:w.UNKNOWN}},async scanBlocks({fromBlock:n,toBlock:s,address:o,topics:i,chunkSize:u=2e3}={},c={}){if(!Number.isInteger(n)||!Number.isInteger(s))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(s<n)throw new Error("toBlock must be >= fromBlock");let l=[],a=[];for(let h=n;h<=s;h+=u){let f=Math.min(h+u-1,s);a.push([h,f])}let p=await Ke(a,4,async([h,f])=>{let d={fromBlock:`0x${h.toString(16)}`,toBlock:`0x${f.toString(16)}`};o&&(d.address=o),i&&(d.topics=i);let m=await F(e,"eth_getLogs",[d],c).catch(b=>({error:String(b?.message||b)}));return{start:h,end:f,res:m}});for(let{start:h,end:f,res:d}of p){if(d?.error)return{chainId:e,fromBlock:n,toBlock:s,logs:l,complete:!1,failedAt:[h,f],error:d.error,evidence:w.UNKNOWN};for(let m of d?.result??d??[])l.push(m)}return{chainId:e,fromBlock:n,toBlock:s,logs:l,complete:!0,chunks:a.length,evidence:w.LIVE}},async scoreRisk(n,s={}){let o=[],i=g.PASS,u=a=>{let p={[g.PASS]:0,[g.CAUTION]:1,[g.UNKNOWN]:2,[g.FAIL]:3};p[a]>p[i]&&(i=a)},[c,l]=await Promise.all([this.resolveToken(n,s),this.resolvePools(n,s)]);if(c.evidence!==w.LIVE?(o.push({check:"erc20-metadata",result:g.UNKNOWN,detail:c.warning}),u(g.UNKNOWN)):o.push({check:"erc20-metadata",result:g.PASS,detail:`${c.symbol} / ${c.decimals}d`}),l.evidence===w.UNAVAILABLE)o.push({check:"liquidity",result:g.UNKNOWN,detail:l.reason}),u(g.UNKNOWN);else if(!l.pools.length)o.push({check:"liquidity",result:g.FAIL,detail:"no pool with liquidity found"}),u(g.FAIL);else{let a=l.pools[0],p=a.liquidityUsd??0;p<5e3?(o.push({check:"liquidity",result:g.CAUTION,detail:`top pool only $${p}`}),u(g.CAUTION)):o.push({check:"liquidity",result:g.PASS,detail:`$${p} on ${a.dex}`}),a.createdAt&&Date.now()-a.createdAt<24*3600*1e3&&(o.push({check:"age",result:g.CAUTION,detail:"pool under 24h old"}),u(g.CAUTION))}if(typeof this.sellSimulation=="function"){let a=await this.sellSimulation({token:n,amountIn:(10n**16n).toString()},s).catch(p=>({verdict:g.UNKNOWN,reason:String(p?.message||p)}));o.push({check:"sellability",result:a.verdict,detail:a.retentionBps!=null?`round trip returns ${(a.retentionBps/100).toFixed(2)}% -- ${a.reason}`:a.reason}),u(a.verdict)}else o.push({check:"sellability",result:g.UNKNOWN,detail:"no verified router on this chain, so a round-trip sell simulation cannot run. Treat as unproven -- a buy path is not an exit path."}),u(g.UNKNOWN);return{chainId:e,token:n,verdict:i,checks:o,note:"Structural checks only. UNKNOWN is not PASS. A token is not tradeable until a sell simulation succeeds."}}}}function ft(t){let r={...Cr(t)},n=new Set((t.venues||[]).map(o=>o.kind));t.venueKind==="uniswap-v3"&&n.has("quoter")&&n.has("router")?Object.assign(r,lt({chainId:t.chainId,wrappedNative:t.wrappedNative,stableQuoteAssets:t.stableQuoteAssets||[],resolveQuoteAsset:async(o,i)=>(await r.resolvePools(o,i)).quoteAsset||null})):t.venueKind==="uniswap-v2"&&n.has("router")&&Object.assign(r,it({chainId:t.chainId,wrappedNative:t.wrappedNative}));let s={};for(let[o,i]of Object.entries(r))s[o]=i.bind(r);return{key:t.key,chainId:t.chainId,name:t.name,rpcEnv:t.rpcEnv,nativeCurrency:t.nativeCurrency,explorer:t.explorer,venues:t.venues||[],capabilities:s}}var ht=Object.freeze([{key:"ethereum",chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://etherscan.io",dexscreenerSlug:"ethereum",venueKind:"uniswap-v3",wrappedNative:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",stableQuoteAssets:["0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48","0xdAC17F958D2ee523a2206206994597C13D831ec7"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.71 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}}]},{key:"optimism",chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://optimistic.etherscan.io",dexscreenerSlug:"optimism",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",stableQuoteAssets:["0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85","0x94b008aA00579c1307B0EF2c499aD98a8ce58e58"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1905.23 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}}]},{key:"bsc",chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],nativeCurrency:{symbol:"BNB",decimals:18},explorer:"https://bscscan.com",dexscreenerSlug:"bsc",venueKind:"uniswap-v3",wrappedNative:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",stableQuoteAssets:["0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d","0x55d398326f99059fF775485246999027B3197955"],venues:[{kind:"quoter",address:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WBNB->USDC fee 500 quoted 413.86 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}},{kind:"router",address:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}}]},{key:"polygon",chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],nativeCurrency:{symbol:"POL",decimals:18},explorer:"https://polygonscan.com",dexscreenerSlug:"polygon",venueKind:"uniswap-v3",wrappedNative:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",stableQuoteAssets:["0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359","0xc2132D05D31c914a87C6611C10748AEb04B58e8F"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WMATIC->USDC fee 500 quoted 0.0720 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}}]},{key:"stable",chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],nativeCurrency:{symbol:"USDT0",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x5d442b349590a6048Eb2dC0eC346cAA5F47A9ab5",venues:[{kind:"quoter",address:"0xb070179E7032CdA868b53e6C1742F80c9e940d1A",label:"Uniswap V3 QuoterV2 (canonical)",verified:{method:"Stable is on the OFFICIAL Uniswap v3 Deployments List (governance-recognised 2026-05-12, UAC process completed 2026-04, deployed by Protofire), so this is a canonical deployment rather than a fork. eth_getCode returned 8273 bytes, the same size as the canonical quoter on the seven already-verified chains. Functional probe on a live pool (TOAST -> USDT0, fee 10000): 100 in -> 0.000003, 1000 -> 0.000031, 10000 -> 0.000319 USDT0. Output scales monotonically with input, which is a working quoter answering, not a revert. Two of three sampled pools carry non-zero liquidity. NOTE: the pools discovered so far are thin, so real routing size is limited -- the venue is proved, deep liquidity is not.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:988}},{kind:"router",address:"0x32eaf9B5d5F2CD7361c5012890C943D7de84C22a",label:"Uniswap SwapRouter02 (canonical)",verified:{method:"eth_getCode returned 24497 bytes. Cross-checked on-chain rather than trusted from docs: router.factory() returns 0x88f0a512ef09175d456bc9547f914f48c013e4aa, the same v3 core factory that created the pools quoted above, and router.WETH9() returns the wrappedNative recorded on this chain entry. Address published in the Stable docs DEX reference and the Uniswap deployments list.",source:"docs.stable.xyz/en/reference/dexes + on-chain factory()/WETH9() round-trip",date:"2026-08-05",chainId:988}}]},{key:"hyperevm",chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],nativeCurrency:{symbol:"HYPE",decimals:18},dexscreenerSlug:"hyperevm",venueKind:"uniswap-v3",wrappedNative:"0x5555555555555555555555555555555555555555",venues:[{kind:"quoter",address:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",label:"HyperSwap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle(1 WHYPE -> USDT0) returned live output on all four fee tiers (100: 57.3385, 500: 57.4187, 3000: 57.3237, 10000: 56.1963 USDT0). Decimals read on-chain: WHYPE 18, USDT0 6. Best tier checked against an INDEPENDENT control the same minute -- Hyperliquid allMids put HYPE at 57.3205, so the pool is 0.171% from the perp mid, which is the right shape for fee plus impact rather than a wrong contract or a decimals bug.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}},{kind:"router",address:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D",label:"HyperSwap V3 SwapRouter",verified:{method:"eth_getCode returned 12070 bytes, and it is the router paired with the quoter proved above -- the same pair already shipped in UNI_V3_VENUES[999].hyperswap, which is the map the quote/prepare path actually routes through.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}}]},{key:"abstract",chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x3439153EB7AF838Ad19d56E1571FBD09333C2809",venues:[{kind:"quoter",address:"0x728BD3eC25D5EDBafebB84F3d67367Cd9EBC7693",label:"Uniswap V3 QuoterV2 (Abstract deployment)",verified:{method:"Abstract is a ZK-stack chain, so CREATE2 addresses differ and the canonical Uniswap addresses are NOT valid here -- probing them returns codesize 0, which is what previously made this chain look like it had no V3 at all. Found the real deployment from live traffic instead: scanned recent Swap(...) logs, took the busiest pool, read pool.factory() = 0xa1160e73b63f322ae88cc2d8e700833e71d0b2a1, then enumerated that factory's deployer (0xf3d63166F0Ca56C3c1A3508FcE03Ff0Cf3Fb691e) and probed each of its 56 contracts with a real quoteExactInputSingle call. Exactly one answered: 1 WETH -> 1846.475731 USDC.e at fee 500. Independent sanity check: the pool's own slot0() spot price is 1873.11 USDC.e per WETH, so the quoter sits ~1.4% below spot, the right shape for fee plus price impact on this size.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:2741}},{kind:"router",address:"0x7712FA47387542819d4E35A23f8116C90C18767C",label:"Uniswap SwapRouter02 (Abstract deployment)",verified:{method:"eth_getCode returned 167392 bytes and the runtime contains the exactInputSingle selector. router.factory() matches the factory proved above and router.WETH9() matches the wrappedNative on this entry. Chosen over its byte-identical twin (0xfD6257F4...) because this is the address real users actually route through: it appeared as tx.to on live swaps against the WETH/USDC.e pool.",source:"on-chain factory()/WETH9() round-trip + live swap tx.to sampling",date:"2026-08-05",chainId:2741}}]},{key:"robinhood",chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC","ROBINHOOD_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},dexscreenerSlug:"robinhood",venueKind:"uniswap-v3",wrappedNative:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",stableQuoteAssets:["0x5fc5360d0400a0fd4f2af552add042d716f1d168"],venues:[{kind:"quoter",address:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDG fee 100 quoted 1866.58 USDG, and USDG->CASHCAT fee 10000 quoted a live amount). A contract that correctly prices known pairs IS a working V3 quoter",source:"live eth_call against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"router",address:"0xcaf681a66d020601342297493863e78c959e5cb2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode (24497 bytes) on this chain and the paired quoter at the same deployment passed a live functional quote",source:"live eth_getCode against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"factory",address:"0x1f7d7550b1b028f7571e69a784071f0205fd2efa",label:"Uniswap V3 Factory",verified:{method:"eth_getCode returned real bytecode (24535 bytes) and a PoolCreated log scan over this factory returned 76 pools in ~9000 recent blocks",source:"live eth_getLogs against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}}]},{key:"base",chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://basescan.org",dexscreenerSlug:"base",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",stableQuoteAssets:["0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"],venues:[{kind:"quoter",address:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",label:"Uniswap V3 QuoterV2 (Base)",verified:{method:"functional probe: quoteExactInputSingle returned WETH->USDC at fee 500 = 1908.44 USDC, a live sane price. The canonical mainnet quoter address also has bytecode on Base but does NOT price this pair, which is exactly the false positive a codesize-only check accepts",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router",address:"0x2626664c2603336E57B271c5C0b26F421741e481",label:"Uniswap V3 SwapRouter02 (Base)",verified:{method:"eth_getCode returned real bytecode and the paired Base quoter passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router-v2",address:"0x4752ba5DBc23f44D87826276BF6Fd6b1C372aD24",label:"Uniswap V2 Router02 (Base)",verified:{method:"eth_getCode returned 17891 bytes; live getAmountsOut on WETH->USDC round-tripped to 98.75% (2x0.30% fee + impact)",source:"https://docs.uniswap.org/contracts/v2/reference/smart-contracts/v2-deployments",date:"2026-07-30",chainId:8453}}]},{key:"arbitrum",chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://arbiscan.io",dexscreenerSlug:"arbitrum",venueKind:"uniswap-v3",wrappedNative:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",stableQuoteAssets:["0xaf88d065e77c8cC2239327C5EDb3A432268e5831","0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.72 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}}]},{key:"avalanche",chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],nativeCurrency:{symbol:"AVAX",decimals:18},explorer:"https://snowtrace.io",dexscreenerSlug:"avalanche",venueKind:"uniswap-v3",wrappedNative:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",stableQuoteAssets:["0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"],venues:[{kind:"quoter",address:"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WAVAX->USDC fee 500 quoted 6.48 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}},{kind:"router",address:"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}}]}]);function mt(){return ht.map(t=>st(ft(t)))}mt();var[bt,...yt]=process.argv.slice(2),me=yt.includes("--json"),I=yt.filter(t=>t!=="--json");function J(t){t||D("missing <chain>");let e=Ie(Number(t));if(e)return e;let r=fe().find(n=>n.key===String(t).toLowerCase());if(r)return r;D(`unknown chain "${t}". Known: ${fe().map(n=>`${n.key}(${n.chainId})`).join(", ")}`)}function D(t){console.error(`error: ${t}`),process.exit(1)}function Q(t){process.stdout.write(`${JSON.stringify(t,null,2)}
|
|
7
|
+
- `)}`);let s=t.capabilities||{},o=ne.filter(u=>typeof s[u]=="function"),i={key:t.key,chainId:t.chainId,name:t.name,rpcEnv:[...t.rpcEnv],nativeCurrency:t.nativeCurrency?{...t.nativeCurrency}:null,wrappedNative:t.wrappedNative||null,explorer:t.explorer||null,venues:(t.venues||[]).map(u=>({...u})),warnings:n,capabilities(){return{chainId:t.chainId,key:t.key,supported:[...o],unsupported:ne.filter(u=>!o.includes(u))}},supports(u){return o.includes(u)}};for(let u of ne)o.includes(u)?i[u]=async(...c)=>s[u](...c,{scanner:i}):i[u]=async()=>{throw new Error(`${t.key} (chain ${t.chainId}) does not implement "${u}". Supported: ${o.join(", ")||"none"}. An unimplemented capability is absent, not assumed -- implement it or treat this chain as fail-closed for that operation.`)};return Object.freeze(i)}var oe=new Map;function st(t){let e=wr(t);return oe.set(e.chainId,e),e}function Ie(t){return oe.get(Number(t))||null}function fe(){return[...oe.values()]}function at(){let t={};for(let e of oe.values())t[e.chainId]={key:e.key,name:e.name,...e.capabilities(),venueCount:e.venues.length,failClosed:e.venues.length===0};return{generatedAt:new Date().toISOString(),chainCount:oe.size,capabilities:[...ne],chains:t}}var ke={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},$=t=>BigInt(t).toString(16).padStart(64,"0"),se=t=>t.slice(2).toLowerCase().padStart(64,"0");function vr(t,e){return`0x${ke.getAmountsOut}`+$(t)+$(64)+$(e.length)+e.map(se).join("")}function Er(t){if(!t||t==="0x")return null;let e=t.slice(2);if(e.length<128)return null;let r=Number(BigInt(`0x${e.slice(64,128)}`));if(!Number.isFinite(r)||r<1||r>16)return null;let n=[];for(let s=0;s<r;s++){let o=128+s*64;if(e.length<o+64)return null;n.push(BigInt(`0x${e.slice(o,o+64)}`))}return n}function Oe(t,e="router"){return(t?.venues||[]).find(n=>n.kind===e)?.address??null}var Ne=100;function Sr(t,e){let r=Number(e);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>Ne)throw new Error(`slippageBps ${r} exceeds the ${Ne} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(t)*BigInt(1e4-Math.floor(r))/10000n}function it(t){let{chainId:e,wrappedNative:r}=t;async function n(s,o,i,u){let c=await F(e,"eth_call",[{to:s,data:vr(o,i)},"latest"],u);return Er(c?.result??c)}return{async quote({tokenIn:s,tokenOut:o,amountIn:i,path:u},c={}){let l=Oe(c.scanner);if(!l)return{chainId:e,evidence:w.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let a=u||[s,o];if(a.some(h=>!/^0x[0-9a-fA-F]{40}$/.test(h||"")))throw new Error("quote requires valid 20-byte addresses");let p=await n(l,i,a,c);return p?{chainId:e,router:l,path:a,amountIn:String(i),amountOut:p[p.length-1].toString(),hops:a.length-1,evidence:w.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:e,router:l,path:a,evidence:w.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:s,amountIn:o,base:i},u={}){let c=Oe(u.scanner),l=i||r;if(l&&String(s).toLowerCase()===String(l).toLowerCase())return{chainId:e,token:s,verdict:g.UNKNOWN,evidence:w.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!c||!l)return{chainId:e,token:s,verdict:g.UNKNOWN,evidence:w.UNAVAILABLE,reason:c?"no wrappedNative configured for this chain, so no base asset to round-trip against":"no verified router configured for this chain"};let a=await n(c,o,[l,s],u);if(!a)return{chainId:e,token:s,verdict:g.FAIL,evidence:w.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let p=a[a.length-1];if(p===0n)return{chainId:e,token:s,verdict:g.FAIL,evidence:w.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let h=await n(c,p,[s,l],u);if(!h)return{chainId:e,token:s,verdict:g.FAIL,evidence:w.LIVE,leg:"sell",bought:p.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let f=h[h.length-1],d=Number(f*10000n/BigInt(o)),m=g.PASS,b="round trip completes with expected fee/impact loss";return d<5e3?(m=g.FAIL,b=`round trip returns only ${(d/100).toFixed(2)}% -- punitive tax or no real liquidity`):d<9e3&&(m=g.CAUTION,b=`round trip returns ${(d/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,token:s,base:l,router:c,verdict:m,reason:b,amountIn:String(o),bought:p.toString(),returned:f.toString(),retentionBps:d,evidence:w.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:s,tokenOut:o,amountIn:i,recipient:u,slippageBps:c=50,deadlineSeconds:l=900,path:a},p={}){let h=p.scanner,f=Oe(h);if(!f)throw new Error(`chain ${e} has no verified router; preparing a swap stays fail-closed. Add a venue with recorded provenance first (see docs/adding-a-chain.md).`);if(!/^0x[0-9a-fA-F]{40}$/.test(u||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let d=a||[s,o],m=await this.quote({tokenIn:s,tokenOut:o,amountIn:i,path:d},p);if(m.evidence!==w.LIVE)throw new Error(`cannot prepare without a live quote (${m.evidence}: ${m.reason??"no reason given"})`);let b=Sr(m.amountOut,c);if(b<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let E=BigInt(Math.floor(Date.now()/1e3)+Number(l)),P=r&&d[0].toLowerCase()===r.toLowerCase()&&p.useNative,R=P?`0x${ke.swapExactETHForTokens}`+$(b)+$(128)+se(u)+$(E)+$(d.length)+d.map(se).join(""):`0x${ke.swapExactTokensForTokens}`+$(i)+$(b)+$(160)+se(u)+$(E)+$(d.length)+d.map(se).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:e,tx:{to:f,data:R,value:P?`0x${BigInt(i).toString(16)}`:"0x0"},guard:{quotedOut:m.amountOut,minOut:b.toString(),slippageBps:c,maxSlippageBps:Ne,deadline:E.toString()},requires:P?[]:[{step:"approve",token:d[0],spender:f,amount:String(i)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}var xr=[100,500,3e3,1e4],ct={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},G=t=>BigInt(t).toString(16).padStart(64,"0"),ae=t=>t.slice(2).toLowerCase().padStart(64,"0"),ut=/^0x[0-9a-fA-F]{40}$/,Re=100;function Ar(t,e){let r=Number(e);if(!Number.isFinite(r)||r<0)throw new Error("slippageBps must be a non-negative number");if(r>Re)throw new Error(`slippageBps ${r} exceeds the ${Re} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(t)*BigInt(1e4-Math.floor(r))/10000n}function Pe(t,e){return(t?.venues||[]).find(r=>r.kind===e)?.address??null}function lt(t){let{chainId:e,wrappedNative:r}=t;async function n({quoter:o,tokenIn:i,tokenOut:u,amountIn:c,fee:l},a){let p=`0x${ct.quoteExactInputSingle}`+ae(i)+ae(u)+G(c)+G(l)+G(0),h=await F(e,"eth_call",[{to:o,data:p},"latest"],a).catch(()=>null),f=h?.result??h;if(!f||f==="0x"||f.length<66)return null;let d=BigInt(`0x${f.slice(2,66)}`);return d>0n?d:null}async function s({quoter:o,tokenIn:i,tokenOut:u,amountIn:c},l){let a=await Promise.all(xr.map(async h=>{let f=await n({quoter:o,tokenIn:i,tokenOut:u,amountIn:c,fee:h},l);return{fee:h,amountOut:f?f.toString():null,out:f}})),p=null;for(let h of a)h.out&&(!p||h.out>p.amountOut)&&(p={fee:h.fee,amountOut:h.out});return{best:p,tried:a.map(({fee:h,amountOut:f})=>({fee:h,amountOut:f}))}}return{async quote({tokenIn:o,tokenOut:i,amountIn:u},c={}){let l=Pe(c.scanner,"quoter");if(!l)return{chainId:e,evidence:w.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let h of[o,i])if(!ut.test(h||""))throw new Error("quote requires valid 20-byte addresses");let{best:a,tried:p}=await s({quoter:l,tokenIn:o,tokenOut:i,amountIn:u},c);return a?{chainId:e,venue:"uniswap-v3",quoter:l,tokenIn:o,tokenOut:i,amountIn:String(u),amountOut:a.amountOut.toString(),fee:a.fee,useNative:!!r&&String(o).toLowerCase()===String(r).toLowerCase(),triedFeeTiers:p,evidence:w.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:e,quoter:l,tokenIn:o,tokenOut:i,triedFeeTiers:p,evidence:w.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:o,amountIn:i,base:u},c={}){let l=Pe(c.scanner,"quoter"),a=(t.stableQuoteAssets||[]).map(k=>String(k).toLowerCase()),p=null;!u&&typeof t.resolveQuoteAsset=="function"&&(p=await t.resolveQuoteAsset(o,c).catch(()=>null));let h=String(o).toLowerCase(),f=String(r||"").toLowerCase();if(f&&h===f)return{chainId:e,token:o,verdict:g.UNKNOWN,evidence:w.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};let d=u||p||(a[0]&&h!==a[0]?a[0]:null)||r;if(d&&h===String(d).toLowerCase())return{chainId:e,token:o,verdict:g.UNKNOWN,evidence:w.UNAVAILABLE,reason:"token is the base asset for this chain, so there is nothing to round-trip against. Sellability must be judged against a different quote asset."};if(!l||!d)return{chainId:e,token:o,verdict:g.UNKNOWN,evidence:w.UNAVAILABLE,reason:l?"no wrappedNative configured, so there is no base asset to round-trip against":"no verified quoter configured for this chain"};let m=await s({quoter:l,tokenIn:d,tokenOut:o,amountIn:i},c);if(!m.best){let k=a.find(C=>C&&C!==String(d).toLowerCase()&&C!==String(o).toLowerCase());if(k){let C=await s({quoter:l,tokenIn:k,tokenOut:o,amountIn:i},c);if(C.best){let v=await s({quoter:l,tokenIn:o,tokenOut:k,amountIn:C.best.amountOut},c);if(v.best){let T=v.best.amountOut,S=Number(T*10000n/BigInt(i)),_=g.PASS,y="round trip vs dollar book completes with expected fee/impact loss";return S<5e3?(_=g.FAIL,y=`round trip vs dollar book returns only ${(S/100).toFixed(2)}% -- punitive tax or no real liquidity`):S<9e3&&(_=g.CAUTION,y=`round trip vs dollar book returns ${(S/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,venue:"uniswap-v3",token:o,base:k,quoteAsset:k,verdict:_,reason:y,amountIn:String(i),bought:C.best.amountOut.toString(),returned:T.toString(),retentionBps:S,buyFee:C.best.fee,sellFee:v.best.fee,evidence:w.LIVE,note:"Quoted against the dollar book, not wrapped native. A missing WETH pool is not a honeypot."}}}}return{chainId:e,token:o,verdict:g.FAIL,evidence:w.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier against wrapped native or the dollar book"}}let b=await s({quoter:l,tokenIn:o,tokenOut:d,amountIn:m.best.amountOut},c);if(!b.best){let k=a.find(C=>C&&C!==String(d).toLowerCase()&&C!==String(o).toLowerCase());if(k){let C=await s({quoter:l,tokenIn:k,tokenOut:o,amountIn:i},c),v=C.best?await s({quoter:l,tokenIn:o,tokenOut:k,amountIn:C.best.amountOut},c):{best:null};if(C.best&&v.best){let T=v.best.amountOut,S=Number(T*10000n/BigInt(i)),_=g.PASS,y="round trip vs dollar book completes; missing WETH sell pool is not a honeypot";return S<5e3?(_=g.FAIL,y=`dollar-book round trip returns only ${(S/100).toFixed(2)}%`):S<9e3&&(_=g.CAUTION,y=`dollar-book round trip returns ${(S/100).toFixed(2)}%`),{chainId:e,venue:"uniswap-v3",token:o,base:k,quoteAsset:k,verdict:_,reason:y,amountIn:String(i),bought:C.best.amountOut.toString(),returned:T.toString(),retentionBps:S,buyFee:C.best.fee,sellFee:v.best.fee,evidence:w.LIVE,note:"Sell vs wrapped native failed; dollar book succeeded. Not labelled honeypot."}}}return{chainId:e,token:o,verdict:g.FAIL,evidence:w.LIVE,leg:"sell",bought:m.best.amountOut.toString(),reason:"SELL LEG FAILED against wrapped native and the dollar book. This is the honeypot signature: do not trade."}}let E=b.best.amountOut,P=Number(E*10000n/BigInt(i)),R=g.PASS,U="round trip completes with expected fee/impact loss";return P<5e3?(R=g.FAIL,U=`round trip returns only ${(P/100).toFixed(2)}% -- punitive tax or no real liquidity`):P<9e3&&(R=g.CAUTION,U=`round trip returns ${(P/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:e,venue:"uniswap-v3",token:o,base:d,verdict:R,reason:U,amountIn:String(i),bought:m.best.amountOut.toString(),returned:E.toString(),retentionBps:P,buyFee:m.best.fee,sellFee:b.best.fee,evidence:w.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:o,tokenOut:i,amountIn:u,recipient:c,slippageBps:l=50,fee:a},p={}){let h=Pe(p.scanner,"router");if(!h)throw new Error(`chain ${e} has no verified V3 router; preparing a swap stays fail-closed. Add a venue with recorded provenance first (see docs/adding-a-chain.md).`);if(!ut.test(c||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let f=await this.quote({tokenIn:o,tokenOut:i,amountIn:u},p);if(f.evidence!==w.LIVE)throw new Error(`cannot prepare without a live quote (${f.evidence}: ${f.reason??"no reason given"})`);let d=a??f.fee,m=Ar(f.amountOut,l);if(m<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let b=!!(p.useNative||f.useNative)&&r&&String(o).toLowerCase()===String(r).toLowerCase(),E=`0x${ct.exactInputSingle}`+ae(o)+ae(i)+G(d)+ae(c)+G(u)+G(m)+G(0);return{unsigned:!0,signedBy:"user-wallet",chainId:e,venue:"uniswap-v3",tx:{to:h,data:E,value:b?String(u):"0x0"},guard:{quotedOut:f.amountOut,minOut:m.toString(),slippageBps:l,maxSlippageBps:Re,fee:d},requires:b?[]:[{step:"approve",token:o,spender:h,amount:String(u)}],note:"UNSIGNED. Re-verify the guard against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."}}}}var he={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"};function dt(t){if(!t||t==="0x")return null;try{return BigInt(t)}catch{return null}}function pt(t){if(!t||t==="0x")return null;let e=t.slice(2);if(e.length>=128){let n=Number(BigInt(`0x${e.slice(64,128)}`));if(n>0&&n<=256&&e.length>=128+n*2){let s=e.slice(128,128+n*2),o=Buffer.from(s,"hex").toString("utf8").replace(/\0+$/,"");if(o)return o}}return Buffer.from(e.slice(0,64),"hex").toString("utf8").replace(/\0+$/,"")||null}function Cr(t){let{chainId:e}=t;async function r(n,s,o){return F(e,"eth_call",[{to:n,data:s},"latest"],o)}return{async blockNumber(n={}){let s=await Ze(e,n);return{chainId:e,blockNumber:s?.blockNumber??s,evidence:w.LIVE}},async nativeBalance(n,s={}){let o=await et(e,n,s);return{chainId:e,address:n,wei:o?.wei??o?.balance??null,symbol:t.nativeCurrency?.symbol??null,decimals:t.nativeCurrency?.decimals??18,evidence:w.LIVE}},async tokenBalance({token:n,owner:s},o={}){let i=await tt({chainId:e,token:n,owner:s},o);return{chainId:e,token:n,owner:s,raw:i?.balance??i,evidence:w.LIVE}},async resolveToken(n,s={}){if(!/^0x[0-9a-fA-F]{40}$/.test(n||""))return{chainId:e,token:n,evidence:w.UNKNOWN,error:"resolveToken needs a 20-byte address; symbol lookup is a market-data concern"};let[o,i,u,c]=await Promise.all([r(n,he.decimals,s).catch(()=>null),r(n,he.symbol,s).catch(()=>null),r(n,he.name,s).catch(()=>null),r(n,he.totalSupply,s).catch(()=>null)]),l=dt(o?.result??o),a=l!==null||i?.result||u?.result,p={chainId:e,address:n,decimals:l===null?null:Number(l),symbol:pt(i?.result??i),name:pt(u?.result??u),totalSupply:(dt(c?.result??c)??null)?.toString()??null,evidence:a?w.LIVE:w.UNKNOWN};return a||(p.warning="no ERC-20 metadata returned -- may not be a token contract"),p},async resolvePools(n,s={}){let o=t.dexscreenerSlug;if(!o)return{chainId:e,token:n,pools:[],evidence:w.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let i=await ot(n,s).catch(()=>null),c=(i?.pairs||i?.data?.pairs||[]).filter(a=>String(a.chainId).toLowerCase()===String(o).toLowerCase()).map(a=>({pair:a.pairAddress,dex:a.dexId,base:a.baseToken?.address,quote:a.quoteToken?.address,liquidityUsd:a.liquidity?.usd??null,priceUsd:a.priceUsd??null,volume24hUsd:a.volume?.h24??null,createdAt:a.pairCreatedAt??null})).sort((a,p)=>(p.liquidityUsd??0)-(a.liquidityUsd??0)),l=Te(n,c,{stables:t.stableQuoteAssets||[],wrappedNative:t.wrappedNative});return{chainId:e,token:n,pools:l,topPool:l[0]||null,quoteAsset:nt(n,l),evidence:l.length?w.LIVE:w.UNKNOWN}},async scanBlocks({fromBlock:n,toBlock:s,address:o,topics:i,chunkSize:u=2e3}={},c={}){if(!Number.isInteger(n)||!Number.isInteger(s))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(s<n)throw new Error("toBlock must be >= fromBlock");let l=[],a=[];for(let h=n;h<=s;h+=u){let f=Math.min(h+u-1,s);a.push([h,f])}let p=await Ke(a,4,async([h,f])=>{let d={fromBlock:`0x${h.toString(16)}`,toBlock:`0x${f.toString(16)}`};o&&(d.address=o),i&&(d.topics=i);let m=await F(e,"eth_getLogs",[d],c).catch(b=>({error:String(b?.message||b)}));return{start:h,end:f,res:m}});for(let{start:h,end:f,res:d}of p){if(d?.error)return{chainId:e,fromBlock:n,toBlock:s,logs:l,complete:!1,failedAt:[h,f],error:d.error,evidence:w.UNKNOWN};for(let m of d?.result??d??[])l.push(m)}return{chainId:e,fromBlock:n,toBlock:s,logs:l,complete:!0,chunks:a.length,evidence:w.LIVE}},async scoreRisk(n,s={}){let o=[],i=g.PASS,u=a=>{let p={[g.PASS]:0,[g.CAUTION]:1,[g.UNKNOWN]:2,[g.FAIL]:3};p[a]>p[i]&&(i=a)},[c,l]=await Promise.all([this.resolveToken(n,s),this.resolvePools(n,s)]);if(c.evidence!==w.LIVE?(o.push({check:"erc20-metadata",result:g.UNKNOWN,detail:c.warning}),u(g.UNKNOWN)):o.push({check:"erc20-metadata",result:g.PASS,detail:`${c.symbol} / ${c.decimals}d`}),l.evidence===w.UNAVAILABLE)o.push({check:"liquidity",result:g.UNKNOWN,detail:l.reason}),u(g.UNKNOWN);else if(!l.pools.length)o.push({check:"liquidity",result:g.FAIL,detail:"no pool with liquidity found"}),u(g.FAIL);else{let a=l.pools[0],p=a.liquidityUsd??0;p<5e3?(o.push({check:"liquidity",result:g.CAUTION,detail:`top pool only $${p}`}),u(g.CAUTION)):o.push({check:"liquidity",result:g.PASS,detail:`$${p} on ${a.dex}`}),a.createdAt&&Date.now()-a.createdAt<24*3600*1e3&&(o.push({check:"age",result:g.CAUTION,detail:"pool under 24h old"}),u(g.CAUTION))}if(typeof this.sellSimulation=="function"){let a=await this.sellSimulation({token:n,amountIn:(10n**16n).toString()},s).catch(p=>({verdict:g.UNKNOWN,reason:String(p?.message||p)}));o.push({check:"sellability",result:a.verdict,detail:a.retentionBps!=null?`round trip returns ${(a.retentionBps/100).toFixed(2)}% -- ${a.reason}`:a.reason}),u(a.verdict)}else o.push({check:"sellability",result:g.UNKNOWN,detail:"no verified router on this chain, so a round-trip sell simulation cannot run. Treat as unproven -- a buy path is not an exit path."}),u(g.UNKNOWN);return{chainId:e,token:n,verdict:i,checks:o,note:"Structural checks only. UNKNOWN is not PASS. A token is not tradeable until a sell simulation succeeds."}}}}function ft(t){let r={...Cr(t)},n=new Set((t.venues||[]).map(o=>o.kind));t.venueKind==="uniswap-v3"&&n.has("quoter")&&n.has("router")?Object.assign(r,lt({chainId:t.chainId,wrappedNative:t.wrappedNative,stableQuoteAssets:t.stableQuoteAssets||[],resolveQuoteAsset:async(o,i)=>(await r.resolvePools(o,i)).quoteAsset||null})):t.venueKind==="uniswap-v2"&&n.has("router")&&Object.assign(r,it({chainId:t.chainId,wrappedNative:t.wrappedNative}));let s={};for(let[o,i]of Object.entries(r))s[o]=i.bind(r);return{key:t.key,chainId:t.chainId,name:t.name,rpcEnv:t.rpcEnv,nativeCurrency:t.nativeCurrency,explorer:t.explorer,venues:t.venues||[],capabilities:s}}var ht=Object.freeze([{key:"ethereum",chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://etherscan.io",dexscreenerSlug:"ethereum",venueKind:"uniswap-v3",wrappedNative:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",stableQuoteAssets:["0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48","0xdAC17F958D2ee523a2206206994597C13D831ec7"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.71 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}}]},{key:"optimism",chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://optimistic.etherscan.io",dexscreenerSlug:"optimism",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",stableQuoteAssets:["0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85","0x94b008aA00579c1307B0EF2c499aD98a8ce58e58"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1905.23 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}}]},{key:"bsc",chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],nativeCurrency:{symbol:"BNB",decimals:18},explorer:"https://bscscan.com",dexscreenerSlug:"bsc",venueKind:"uniswap-v3",wrappedNative:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",stableQuoteAssets:["0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d","0x55d398326f99059fF775485246999027B3197955"],venues:[{kind:"quoter",address:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WBNB->USDC fee 500 quoted 413.86 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}},{kind:"router",address:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}}]},{key:"polygon",chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],nativeCurrency:{symbol:"POL",decimals:18},explorer:"https://polygonscan.com",dexscreenerSlug:"polygon",venueKind:"uniswap-v3",wrappedNative:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",stableQuoteAssets:["0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359","0xc2132D05D31c914a87C6611C10748AEb04B58e8F"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WMATIC->USDC fee 500 quoted 0.0720 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}}]},{key:"stable",chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],nativeCurrency:{symbol:"USDT0",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x5d442b349590a6048Eb2dC0eC346cAA5F47A9ab5",venues:[{kind:"quoter",address:"0xb070179E7032CdA868b53e6C1742F80c9e940d1A",label:"Uniswap V3 QuoterV2 (canonical)",verified:{method:"Stable is on the OFFICIAL Uniswap v3 Deployments List (governance-recognised 2026-05-12, UAC process completed 2026-04, deployed by Protofire), so this is a canonical deployment rather than a fork. eth_getCode returned 8273 bytes, the same size as the canonical quoter on the seven already-verified chains. Functional probe on a live pool (TOAST -> USDT0, fee 10000): 100 in -> 0.000003, 1000 -> 0.000031, 10000 -> 0.000319 USDT0. Output scales monotonically with input, which is a working quoter answering, not a revert. Two of three sampled pools carry non-zero liquidity. NOTE: the pools discovered so far are thin, so real routing size is limited -- the venue is proved, deep liquidity is not.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:988}},{kind:"router",address:"0x32eaf9B5d5F2CD7361c5012890C943D7de84C22a",label:"Uniswap SwapRouter02 (canonical)",verified:{method:"eth_getCode returned 24497 bytes. Cross-checked on-chain rather than trusted from docs: router.factory() returns 0x88f0a512ef09175d456bc9547f914f48c013e4aa, the same v3 core factory that created the pools quoted above, and router.WETH9() returns the wrappedNative recorded on this chain entry. Address published in the Stable docs DEX reference and the Uniswap deployments list.",source:"docs.stable.xyz/en/reference/dexes + on-chain factory()/WETH9() round-trip",date:"2026-08-05",chainId:988}}]},{key:"hyperevm",chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],nativeCurrency:{symbol:"HYPE",decimals:18},dexscreenerSlug:"hyperevm",venueKind:"uniswap-v3",wrappedNative:"0x5555555555555555555555555555555555555555",venues:[{kind:"quoter",address:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",label:"HyperSwap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle(1 WHYPE -> USDT0) returned live output on all four fee tiers (100: 57.3385, 500: 57.4187, 3000: 57.3237, 10000: 56.1963 USDT0). Decimals read on-chain: WHYPE 18, USDT0 6. Best tier checked against an INDEPENDENT control the same minute -- Hyperliquid allMids put HYPE at 57.3205, so the pool is 0.171% from the perp mid, which is the right shape for fee plus impact rather than a wrong contract or a decimals bug.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}},{kind:"router",address:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D",label:"HyperSwap V3 SwapRouter",verified:{method:"eth_getCode returned 12070 bytes, and it is the router paired with the quoter proved above -- the same pair already shipped in UNI_V3_VENUES[999].hyperswap, which is the map the quote/prepare path actually routes through.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}}]},{key:"abstract",chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x3439153EB7AF838Ad19d56E1571FBD09333C2809",venues:[{kind:"quoter",address:"0x728BD3eC25D5EDBafebB84F3d67367Cd9EBC7693",label:"Uniswap V3 QuoterV2 (Abstract deployment)",verified:{method:"Abstract is a ZK-stack chain, so CREATE2 addresses differ and the canonical Uniswap addresses are NOT valid here -- probing them returns codesize 0, which is what previously made this chain look like it had no V3 at all. Found the real deployment from live traffic instead: scanned recent Swap(...) logs, took the busiest pool, read pool.factory() = 0xa1160e73b63f322ae88cc2d8e700833e71d0b2a1, then enumerated that factory's deployer (0xf3d63166F0Ca56C3c1A3508FcE03Ff0Cf3Fb691e) and probed each of its 56 contracts with a real quoteExactInputSingle call. Exactly one answered: 1 WETH -> 1846.475731 USDC.e at fee 500. Independent sanity check: the pool's own slot0() spot price is 1873.11 USDC.e per WETH, so the quoter sits ~1.4% below spot, the right shape for fee plus price impact on this size.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:2741}},{kind:"router",address:"0x7712FA47387542819d4E35A23f8116C90C18767C",label:"Uniswap SwapRouter02 (Abstract deployment)",verified:{method:"eth_getCode returned 167392 bytes and the runtime contains the exactInputSingle selector. router.factory() matches the factory proved above and router.WETH9() matches the wrappedNative on this entry. Chosen over its byte-identical twin (0xfD6257F4...) because this is the address real users actually route through: it appeared as tx.to on live swaps against the WETH/USDC.e pool.",source:"on-chain factory()/WETH9() round-trip + live swap tx.to sampling",date:"2026-08-05",chainId:2741}}]},{key:"robinhood",chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC","ROBINHOOD_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},dexscreenerSlug:"robinhood",venueKind:"uniswap-v3",wrappedNative:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",stableQuoteAssets:["0x5fc5360d0400a0fd4f2af552add042d716f1d168"],venues:[{kind:"quoter",address:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDG fee 100 quoted 1866.58 USDG, and USDG->CASHCAT fee 10000 quoted a live amount). A contract that correctly prices known pairs IS a working V3 quoter",source:"live eth_call against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"router",address:"0xcaf681a66d020601342297493863e78c959e5cb2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode (24497 bytes) on this chain and the paired quoter at the same deployment passed a live functional quote",source:"live eth_getCode against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"factory",address:"0x1f7d7550b1b028f7571e69a784071f0205fd2efa",label:"Uniswap V3 Factory",verified:{method:"eth_getCode returned real bytecode (24535 bytes) and a PoolCreated log scan over this factory returned 76 pools in ~9000 recent blocks",source:"live eth_getLogs against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}}]},{key:"base",chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://basescan.org",dexscreenerSlug:"base",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",stableQuoteAssets:["0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"],venues:[{kind:"quoter",address:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",label:"Uniswap V3 QuoterV2 (Base)",verified:{method:"functional probe: quoteExactInputSingle returned WETH->USDC at fee 500 = 1908.44 USDC, a live sane price. The canonical mainnet quoter address also has bytecode on Base but does NOT price this pair, which is exactly the false positive a codesize-only check accepts",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router",address:"0x2626664c2603336E57B271c5C0b26F421741e481",label:"Uniswap V3 SwapRouter02 (Base)",verified:{method:"eth_getCode returned real bytecode and the paired Base quoter passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router-v2",address:"0x4752ba5DBc23f44D87826276BF6Fd6b1C372aD24",label:"Uniswap V2 Router02 (Base)",verified:{method:"eth_getCode returned 17891 bytes; live getAmountsOut on WETH->USDC round-tripped to 98.75% (2x0.30% fee + impact)",source:"https://docs.uniswap.org/contracts/v2/reference/smart-contracts/v2-deployments",date:"2026-07-30",chainId:8453}}]},{key:"arbitrum",chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://arbiscan.io",dexscreenerSlug:"arbitrum",venueKind:"uniswap-v3",wrappedNative:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",stableQuoteAssets:["0xaf88d065e77c8cC2239327C5EDb3A432268e5831","0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.72 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}}]},{key:"avalanche",chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],nativeCurrency:{symbol:"AVAX",decimals:18},explorer:"https://snowtrace.io",dexscreenerSlug:"avalanche",venueKind:"uniswap-v3",wrappedNative:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",stableQuoteAssets:["0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"],venues:[{kind:"quoter",address:"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WAVAX->USDC fee 500 quoted 6.48 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}},{kind:"router",address:"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}}]}]);function mt(){return ht.map(t=>st(ft(t)))}mt();var[bt,...yt]=process.argv.slice(2),me=yt.includes("--json"),I=yt.filter(t=>t!=="--json");function J(t){t||D("missing <chain>");let e=Ie(Number(t));if(e)return e;let r=fe().find(n=>n.key===String(t).toLowerCase());if(r)return r;D(`unknown chain "${t}". Known: ${fe().map(n=>`${n.key}(${n.chainId})`).join(", ")}`)}function D(t){console.error(`error: ${t}`),process.exit(1)}function Q(t){process.stdout.write(`${JSON.stringify(t,null,2)}
|
|
8
8
|
`)}function Tr(t,e){let r=String(e?.message||e);return/rpc|fetch|ECONN|timeout|provider/i.test(r)?`${r}
|
|
9
9
|
|
|
10
10
|
This chain reads its RPC from: ${t.rpcEnv.join(" or ")}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import{createInterface as ht}from"node:readline";var P=Object.freeze({maxRequestBytes:256*1024,maxResponseBytes:2*1024*1024,maxTools:256,maxToolNameLength:64,maxArgumentBytes:128*1024,defaultCallTimeoutMs:3e4,maxCallTimeoutMs:6e4,maxConcurrentCalls:32}),bt=/^[A-Za-z0-9_-]{1,64}$/;function Z(t,e){return{jsonrpc:"2.0",id:t??null,result:e}}function A(t,e,r){return{jsonrpc:"2.0",id:t??null,error:{code:e,message:r}}}function gt(t){return!!(t&&typeof t=="object"&&!Array.isArray(t)&&t.jsonrpc==="2.0"&&typeof t.method=="string"&&t.method.length>0)}function yt(t){if(!Array.isArray(t))return[];let e=[],r=new Set;for(let o of t){if(e.length>=P.maxTools)break;if(!o||typeof o!="object"||Array.isArray(o))continue;let n=typeof o.name=="string"?o.name.trim():"";if(!bt.test(n)||r.has(n))continue;r.add(n);let i=o.inputSchema&&typeof o.inputSchema=="object"&&!Array.isArray(o.inputSchema)?{...o.inputSchema}:{type:"object",properties:{},additionalProperties:!1};i.type==="object"&&i.additionalProperties===void 0&&(i.additionalProperties=!1),e.push({...o,name:n,inputSchema:i})}return e}function wt(t){let e=Number(t)||P.defaultCallTimeoutMs;return Math.min(Math.max(e,1),P.maxCallTimeoutMs)}async function xt(t,e,r){let o;try{return await Promise.race([t,new Promise((n,i)=>{o=setTimeout(()=>{let s=new Error("tool call timed out");s.code="ORACLE_MCP_TIMEOUT",i(s);try{r?.()}catch{}},e)})])}finally{clearTimeout(o)}}function St(t){return t===null?"null":Array.isArray(t)?"array":Number.isInteger(t)?"integer":typeof t}function X(t,e,r="arguments",o=0){if(!e||typeof e!="object"||Array.isArray(e))return null;if(o>12)return`${r} exceeded the nesting limit`;if(Array.isArray(e.oneOf)&&e.oneOf.length&&!e.oneOf.some(i=>X(t,i,r,o+1)===null))return`${r} did not match an allowed shape`;if(Array.isArray(e.anyOf)&&e.anyOf.length&&!e.anyOf.some(i=>X(t,i,r,o+1)===null))return`${r} did not match a required alternative`;if(Array.isArray(e.enum)&&!e.enum.some(n=>Object.is(n,t)))return`${r} must be one of the allowed values`;if(Object.hasOwn(e,"const")&&!Object.is(e.const,t))return`${r} must equal the required constant`;if(e.type){let n=St(t);if(!(e.type==="number"?typeof t=="number"&&Number.isFinite(t):e.type==="integer"?Number.isSafeInteger(t):n===e.type))return`${r} must be ${e.type}`}if(typeof t=="string"){let n=Math.min(Number.isSafeInteger(e.maxLength)?e.maxLength:16384,16384);if(t.length>n)return`${r} exceeded the string limit`;if(Number.isSafeInteger(e.minLength)&&t.length<e.minLength)return`${r} is too short`}if(Array.isArray(t)){let n=Math.min(Number.isSafeInteger(e.maxItems)?e.maxItems:1e3,1e3);if(t.length>n)return`${r} exceeded the array limit`;if(Number.isSafeInteger(e.minItems)&&t.length<e.minItems)return`${r} has too few items`;if(e.items)for(let i=0;i<t.length;i+=1){let s=X(t[i],e.items,`${r}[${i}]`,o+1);if(s)return s}}if(t&&typeof t=="object"&&!Array.isArray(t)){let n=Object.keys(t);if(n.length>256)return`${r} exceeded the property limit`;let i=e.properties&&typeof e.properties=="object"?e.properties:{};for(let s of Array.isArray(e.required)?e.required:[])if(!Object.hasOwn(t,s))return`${r}.${s} is required`;if(e.additionalProperties===!1&&n.find(l=>!Object.hasOwn(i,l))!==void 0)return`${r} contains an unsupported property`;for(let s of n){if(!Object.hasOwn(i,s))continue;let l=X(t[s],i[s],`${r}.${s}`,o+1);if(l)return l}}return null}function kt(t,e={}){let r=yt(t?.tools),o=new Set(r.map(c=>c.name)),n=new Map(r.map(c=>[c.name,c])),i=typeof t?.name=="string"&&t.name?t.name.slice(0,80):"oracle-mcp",s=typeof t?.version=="string"&&t.version?t.version.slice(0,40):"1",l=wt(e.callTimeoutMs),d=!1;return async function(u){let f=u?.id??null;if(!gt(u))return A(f,-32600,"invalid request");if(u.method==="initialize")return d=!0,Z(f,{protocolVersion:u.params?.protocolVersion??"2025-03-26",capabilities:{tools:{}},serverInfo:{name:i,version:s}});if(u.method==="notifications/initialized")return null;if(u.method==="ping")return Z(f,{});if(!d)return A(f,-32002,"server not initialized");if(u.method==="tools/list")return Z(f,{tools:r});if(u.method==="tools/call"){let h=u.params?.name,b=u.params?.arguments??{};if(typeof h!="string"||!o.has(h))return A(f,-32602,"unknown tool");if(!b||typeof b!="object"||Array.isArray(b))return A(f,-32602,"tool arguments must be an object");let p;try{p=JSON.stringify(b)}catch{return A(f,-32602,"tool arguments are not serializable")}if(Buffer.byteLength(p)>P.maxArgumentBytes)return A(f,-32602,"tool arguments exceeded the size limit");let y=X(b,n.get(h)?.inputSchema);if(y)return A(f,-32602,y);try{let w=new AbortController,$=await xt(Promise.resolve(t.call(h,b,{signal:w.signal})),l,()=>w.abort(new Error("tool call timed out")));return Z(f,$)}catch(w){if(w?.code==="ORACLE_MCP_TIMEOUT")return A(f,-32001,"tool call timed out");let $=typeof w?.message=="string"?w.message.replace(/\s+/g," ").trim():"",M=/\b(requires?|must be|missing|unknown|invalid|expected|unsupported|out of range|too (?:large|small|long|many)|not a|cannot convert)\b/i.test($),K=/https?:\/\/|[/~][\w.-]+\/|0x[0-9a-fA-F]{8,}|[A-Za-z0-9+/_-]{24,}={0,2}|\b(?:secret|apikey|api[-_ ]key|private[-_ ]?key|token|password|credential|seed|mnemonic)s?\b/i.test($.replace(/\btoken(?:In|Out|s\b)/g,"asset"));return M&&!K&&$.length<=200?A(f,-32e3,`tool call failed: ${$}`):A(f,-32e3,"tool call failed")}}return A(f,-32601,"method not found")}}function Se(t,e={}){let r=e.input||process.stdin,o=e.output||process.stdout,n=Math.min(Math.max(Number(e.maxRequestBytes)||P.maxRequestBytes,64),P.maxRequestBytes),i=Math.min(Math.max(Number(e.maxResponseBytes)||P.maxResponseBytes,256),P.maxResponseBytes),s=Math.min(Math.max(Number(e.maxConcurrentCalls)||P.maxConcurrentCalls,1),P.maxConcurrentCalls),l=s*8,d=kt(t,e),c={closed:!1,inflight:0},u=ht({input:r,terminal:!1,crlfDelay:1/0}),f=0,h=[],b=!1,p=!1;function y(){if(c.closed||c.readerClosed)return;let E=c.inflight>=s||h.length>0||p;E&&!b?(b=!0,u.pause(),typeof r.pause=="function"&&r.pause()):!E&&b&&(b=!1,typeof r.resume=="function"&&r.resume(),u.resume())}function w(E){if(!E||c.closed)return;let O=JSON.stringify(E);Buffer.byteLength(O)>i&&(O=JSON.stringify(A(E.id,-32003,"response exceeded the size limit"))),o.write(`${O}
|
|
3
3
|
`)===!1&&!p&&(p=!0,y(),o.once("drain",()=>{p=!1,M()}))}function $(E){c.inflight+=1,y(),Promise.resolve(d(E)).then(w).catch(()=>w(A(E?.id,-32603,"internal error"))).finally(()=>{c.inflight-=1,M()})}function M(){for(;!c.closed&&!p&&c.inflight<s&&h.length>0;)$(h.shift());y()}function K(){c.closed||(w(A(null,-32700,"request exceeded the size limit")),c.closed=!0,u.close(),typeof r.destroy=="function"&&r.destroy())}return r.on("data",E=>{if(c.closed)return;let O=String(E).split(`
|
|
4
|
-
`);for(let H=0;H<O.length;H+=1){if(f+=Buffer.byteLength(O[H]),f>n){K();return}H<O.length-1&&(f=0)}}),u.on("line",E=>{if(c.closed)return;if(Buffer.byteLength(E)>n){K();return}let O;try{O=JSON.parse(E)}catch{w(A(null,-32700,"parse error"));return}if(h.length>=l){w(A(O?.id,-32e3,"server busy"));return}h.push(O),M()}),u.on("close",()=>{c.readerClosed=!0,e.exitOnClose!==!1&&(process.exitCode=0)}),c}import{createHash as kr,randomBytes as Er}from"node:crypto";import{mkdirSync as Ar,readFileSync as Ir,writeFileSync as Cr}from"node:fs";import{homedir as Or}from"node:os";import{dirname as vr,join as Ge}from"node:path";function ke(t){let e=String(t||"").trim();if(!e||e.includes("ts.net")||!/^https:\/\//i.test(e))return null;try{return new URL(e)}catch{return null}}var At=/^[A-Z0-9][A-Z0-9._-]{0,11}$/;function Ee(t,{coin:e,side:r,sizeUsd:o,leverage:n,venue:i,confirm:s,user:l}={}){let d=ke(t);if(!d)return null;if(e&&At.test(String(e).toUpperCase())&&d.searchParams.set("coin",String(e).toUpperCase()),(r==="long"||r==="short")&&d.searchParams.set("side",r),Number.isFinite(Number(o))&&Number(o)>=1&&d.searchParams.set("size",String(Math.min(1e5,Math.round(Number(o))))),Number.isInteger(Number(n))&&Number(n)>=1&&d.searchParams.set("lev",String(Math.min(50,Number(n)))),i){let c=String(i).toLowerCase()==="hl"?"hyperliquid":String(i).toLowerCase();d.searchParams.set("venue",c)}else d.searchParams.get("venue")||d.searchParams.set("venue","hyperliquid");return d.searchParams.set("view","perps"),d.searchParams.set("build","1"),s&&/^[0-9a-f]{32}$/i.test(String(s))&&d.searchParams.set("confirm",String(s).toLowerCase()),l&&/^0x[0-9a-fA-F]{40}$/.test(String(l))&&d.searchParams.set("user",String(l).toLowerCase()),d.toString()}var se={robinhood:{chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC"],evm:!0},ethereum:{chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],evm:!0},polygon:{chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],evm:!0},arbitrum:{chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],evm:!0},base:{chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],evm:!0},hyperevm:{chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],evm:!0},bsc:{chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],evm:!0},avalanche:{chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],evm:!0},optimism:{chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],evm:!0},abstract:{chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],evm:!0},stable:{chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],evm:!0}};var It=new Map(Object.values(se).map(t=>[t.chainId,t]));function ae(t){return It.get(Number(t))||null}var Ct=Object.freeze([{key:"ethereum",chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://etherscan.io",dexscreenerSlug:"ethereum",venueKind:"uniswap-v3",wrappedNative:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",stableQuoteAssets:["0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48","0xdAC17F958D2ee523a2206206994597C13D831ec7"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.71 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}}]},{key:"optimism",chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://optimistic.etherscan.io",dexscreenerSlug:"optimism",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",stableQuoteAssets:["0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85","0x94b008aA00579c1307B0EF2c499aD98a8ce58e58"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1905.23 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}}]},{key:"bsc",chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],nativeCurrency:{symbol:"BNB",decimals:18},explorer:"https://bscscan.com",dexscreenerSlug:"bsc",venueKind:"uniswap-v3",wrappedNative:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",stableQuoteAssets:["0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d","0x55d398326f99059fF775485246999027B3197955"],venues:[{kind:"quoter",address:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WBNB->USDC fee 500 quoted 413.86 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}},{kind:"router",address:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}}]},{key:"polygon",chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],nativeCurrency:{symbol:"POL",decimals:18},explorer:"https://polygonscan.com",dexscreenerSlug:"polygon",venueKind:"uniswap-v3",wrappedNative:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",stableQuoteAssets:["0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359","0xc2132D05D31c914a87C6611C10748AEb04B58e8F"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WMATIC->USDC fee 500 quoted 0.0720 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}}]},{key:"stable",chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],nativeCurrency:{symbol:"USDT0",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x5d442b349590a6048Eb2dC0eC346cAA5F47A9ab5",venues:[{kind:"quoter",address:"0xb070179E7032CdA868b53e6C1742F80c9e940d1A",label:"Uniswap V3 QuoterV2 (canonical)",verified:{method:"Stable is on the OFFICIAL Uniswap v3 Deployments List (governance-recognised 2026-05-12, UAC process completed 2026-04, deployed by Protofire), so this is a canonical deployment rather than a fork. eth_getCode returned 8273 bytes, the same size as the canonical quoter on the seven already-verified chains. Functional probe on a live pool (TOAST -> USDT0, fee 10000): 100 in -> 0.000003, 1000 -> 0.000031, 10000 -> 0.000319 USDT0. Output scales monotonically with input, which is a working quoter answering, not a revert. Two of three sampled pools carry non-zero liquidity. NOTE: the pools discovered so far are thin, so real routing size is limited -- the venue is proved, deep liquidity is not.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:988}},{kind:"router",address:"0x32eaf9B5d5F2CD7361c5012890C943D7de84C22a",label:"Uniswap SwapRouter02 (canonical)",verified:{method:"eth_getCode returned 24497 bytes. Cross-checked on-chain rather than trusted from docs: router.factory() returns 0x88f0a512ef09175d456bc9547f914f48c013e4aa, the same v3 core factory that created the pools quoted above, and router.WETH9() returns the wrappedNative recorded on this chain entry. Address published in the Stable docs DEX reference and the Uniswap deployments list.",source:"docs.stable.xyz/en/reference/dexes + on-chain factory()/WETH9() round-trip",date:"2026-08-05",chainId:988}}]},{key:"hyperevm",chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],nativeCurrency:{symbol:"HYPE",decimals:18},dexscreenerSlug:"hyperevm",venueKind:"uniswap-v3",wrappedNative:"0x5555555555555555555555555555555555555555",venues:[{kind:"quoter",address:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",label:"HyperSwap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle(1 WHYPE -> USDT0) returned live output on all four fee tiers (100: 57.3385, 500: 57.4187, 3000: 57.3237, 10000: 56.1963 USDT0). Decimals read on-chain: WHYPE 18, USDT0 6. Best tier checked against an INDEPENDENT control the same minute -- Hyperliquid allMids put HYPE at 57.3205, so the pool is 0.171% from the perp mid, which is the right shape for fee plus impact rather than a wrong contract or a decimals bug.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}},{kind:"router",address:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D",label:"HyperSwap V3 SwapRouter",verified:{method:"eth_getCode returned 12070 bytes, and it is the router paired with the quoter proved above -- the same pair already shipped in UNI_V3_VENUES[999].hyperswap, which is the map the quote/prepare path actually routes through.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}}]},{key:"abstract",chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x3439153EB7AF838Ad19d56E1571FBD09333C2809",venues:[{kind:"quoter",address:"0x728BD3eC25D5EDBafebB84F3d67367Cd9EBC7693",label:"Uniswap V3 QuoterV2 (Abstract deployment)",verified:{method:"Abstract is a ZK-stack chain, so CREATE2 addresses differ and the canonical Uniswap addresses are NOT valid here -- probing them returns codesize 0, which is what previously made this chain look like it had no V3 at all. Found the real deployment from live traffic instead: scanned recent Swap(...) logs, took the busiest pool, read pool.factory() = 0xa1160e73b63f322ae88cc2d8e700833e71d0b2a1, then enumerated that factory's deployer (0xf3d63166F0Ca56C3c1A3508FcE03Ff0Cf3Fb691e) and probed each of its 56 contracts with a real quoteExactInputSingle call. Exactly one answered: 1 WETH -> 1846.475731 USDC.e at fee 500. Independent sanity check: the pool's own slot0() spot price is 1873.11 USDC.e per WETH, so the quoter sits ~1.4% below spot, the right shape for fee plus price impact on this size.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:2741}},{kind:"router",address:"0x7712FA47387542819d4E35A23f8116C90C18767C",label:"Uniswap SwapRouter02 (Abstract deployment)",verified:{method:"eth_getCode returned 167392 bytes and the runtime contains the exactInputSingle selector. router.factory() matches the factory proved above and router.WETH9() matches the wrappedNative on this entry. Chosen over its byte-identical twin (0xfD6257F4...) because this is the address real users actually route through: it appeared as tx.to on live swaps against the WETH/USDC.e pool.",source:"on-chain factory()/WETH9() round-trip + live swap tx.to sampling",date:"2026-08-05",chainId:2741}}]},{key:"robinhood",chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC","ROBINHOOD_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},dexscreenerSlug:"robinhood",venueKind:"uniswap-v3",wrappedNative:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",stableQuoteAssets:["0x5fc5360d0400a0fd4f2af552add042d716f1d168"],venues:[{kind:"quoter",address:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDG fee 100 quoted 1866.58 USDG, and USDG->CASHCAT fee 10000 quoted a live amount). A contract that correctly prices known pairs IS a working V3 quoter",source:"live eth_call against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"router",address:"0xcaf681a66d020601342297493863e78c959e5cb2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode (24497 bytes) on this chain and the paired quoter at the same deployment passed a live functional quote",source:"live eth_getCode against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"factory",address:"0x1f7d7550b1b028f7571e69a784071f0205fd2efa",label:"Uniswap V3 Factory",verified:{method:"eth_getCode returned real bytecode (24535 bytes) and a PoolCreated log scan over this factory returned 76 pools in ~9000 recent blocks",source:"live eth_getLogs against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}}]},{key:"base",chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://basescan.org",dexscreenerSlug:"base",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",stableQuoteAssets:["0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"],venues:[{kind:"quoter",address:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",label:"Uniswap V3 QuoterV2 (Base)",verified:{method:"functional probe: quoteExactInputSingle returned WETH->USDC at fee 500 = 1908.44 USDC, a live sane price. The canonical mainnet quoter address also has bytecode on Base but does NOT price this pair, which is exactly the false positive a codesize-only check accepts",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router",address:"0x2626664c2603336E57B271c5C0b26F421741e481",label:"Uniswap V3 SwapRouter02 (Base)",verified:{method:"eth_getCode returned real bytecode and the paired Base quoter passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router-v2",address:"0x4752ba5DBc23f44D87826276BF6Fd6b1C372aD24",label:"Uniswap V2 Router02 (Base)",verified:{method:"eth_getCode returned 17891 bytes; live getAmountsOut on WETH->USDC round-tripped to 98.75% (2x0.30% fee + impact)",source:"https://docs.uniswap.org/contracts/v2/reference/smart-contracts/v2-deployments",date:"2026-07-30",chainId:8453}}]},{key:"arbitrum",chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://arbiscan.io",dexscreenerSlug:"arbitrum",venueKind:"uniswap-v3",wrappedNative:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",stableQuoteAssets:["0xaf88d065e77c8cC2239327C5EDb3A432268e5831","0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.72 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}}]},{key:"avalanche",chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],nativeCurrency:{symbol:"AVAX",decimals:18},explorer:"https://snowtrace.io",dexscreenerSlug:"avalanche",venueKind:"uniswap-v3",wrappedNative:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",stableQuoteAssets:["0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"],venues:[{kind:"quoter",address:"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WAVAX->USDC fee 500 quoted 6.48 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}},{kind:"router",address:"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}}]}]);var Ot=Object.freeze({1:"https://eth.blockscout.com",10:"https://explorer.optimism.io",137:"https://polygon.blockscout.com",324:"https://zksync.blockscout.com",8453:"https://base.blockscout.com",42161:"https://arbitrum.blockscout.com",534352:"https://scrollscan.com"});var yn=Object.freeze([100,50,25]),wn=Object.freeze([100,50,25,10]);var m="UNKNOWN",An=Object.freeze(["token","launch","hip3","hip4","polymarket","twap","bridge","swap","approve"]),vt=/[_*[\]`]/g;function a(t){return x(t)?String(t).replace(vt,e=>`\\${e}`):m}function x(t){return t==null?!1:typeof t=="number"?Number.isFinite(t):typeof t=="string"?t.trim()!=="":!0}function L(t){if(!x(t))return m;let e=String(t).replace(/`/g,"");return e===""?m:`\`${e}\``}function z(t,{decimals:e=2}={}){if(!x(t))return m;let r=Number(t);return Number.isFinite(r)?r.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:e}):m}function S(t,{decimals:e=2}={}){let r=z(t,{decimals:e});return r===m?m:`${r} USD`}function ce(t,{decimals:e=2}={}){let r=z(t,{decimals:e});return r===m?m:`${r}%`}function ee(t){let e=z(t,{decimals:0});return e===m?m:`${e} bps`}function V(t,e){if(!x(t))return m;let r=Number(e);if(!Number.isInteger(r)||r<0||r>77)return m;let o;try{o=BigInt(typeof t=="string"?t.trim():t)}catch{return m}let n=o<0n,i=n?-o:o,s=10n**BigInt(r),l=(i/s).toString(),d=(i%s).toString().padStart(r,"0").replace(/0+$/,"");return`${n?"-":""}${l}${d?`.${d}`:""}`}function ue(t){if(typeof t=="number"&&Number.isFinite(t))return t<0||t>1?m:t>=.75?"HIGH":t>=.4?"MEDIUM":"LOW";if(typeof t=="string"){let e=t.trim().toUpperCase();if(e==="HIGH"||e==="MEDIUM"||e==="LOW")return e}return m}function q(t={}){let e=t.chainId;if(!x(e)||!Number.isFinite(Number(e)))return x(t.chain)?a(t.chain):m;let o=ae(e)?.name||(x(t.chain)?String(t.chain):m);return`${a(o)} (chainId ${Number(e)})`}function Ae(t={}){return a(t.venue??t.dex??t.pool?.venue)}function $t(t){return t==null?"NONE (text card only)":typeof t=="string"?t.trim()?L(t):"NONE (text card only)":t.error||t.ok===!1||t.available===!1?`UNAVAILABLE${x(t.error)?` \u2014 ${a(t.error)}`:""} (text card stands)`:x(t.url)?L(t.url):"NONE (text card only)"}function Y(t={},{now:e=Date.now()}={}){let r=t.grant??t.session??null;if(!r||typeof r!="object")return{allowed:!1,reason:"no local grant/session",actions:[]};if(r.local===!1)return{allowed:!1,reason:"grant is not local",actions:[]};if(r.revoked===!0)return{allowed:!1,reason:"grant revoked",actions:[]};let o=r.expiresAt??r.expiry;if(x(o)){let i=typeof o=="number"?o:Date.parse(o);if(!Number.isFinite(i))return{allowed:!1,reason:"grant expiry unreadable",actions:[]};if(i<=e)return{allowed:!1,reason:"grant expired",actions:[]}}return{allowed:!0,reason:"valid local grant",actions:Array.isArray(r.actions)&&r.actions.length?r.actions.slice():["BUY","SELL"]}}function Tt(t){let e=Y(t);return e.allowed?`${e.actions.map(r=>a(r)).join(" / ")} (${a(e.reason)})`:`prepare-only \u2014 ${a(e.reason)}`}function B(t,e,r={}){let o=[`*${t}*`];for(let n of e){if(!n)continue;let[i,s]=n;o.push(`${i}: ${s==null||s===""?m:s}`)}return o.push(`Chart: ${$t(r.chart)}`),o.push(`Actions: ${Tt(r)}`),Array.isArray(r.warnings)&&r.warnings.length&&o.push(`Warnings: ${r.warnings.map(n=>a(n)).join("; ")}`),(x(r.source)||x(r.fetchedAt))&&o.push(`Source: ${a(r.source)} at ${a(r.fetchedAt)}`),o.join(`
|
|
4
|
+
`);for(let H=0;H<O.length;H+=1){if(f+=Buffer.byteLength(O[H]),f>n){K();return}H<O.length-1&&(f=0)}}),u.on("line",E=>{if(c.closed)return;if(Buffer.byteLength(E)>n){K();return}let O;try{O=JSON.parse(E)}catch{w(A(null,-32700,"parse error"));return}if(h.length>=l){w(A(O?.id,-32e3,"server busy"));return}h.push(O),M()}),u.on("close",()=>{c.readerClosed=!0,e.exitOnClose!==!1&&(process.exitCode=0)}),c}import{createHash as kr,randomBytes as Er}from"node:crypto";import{mkdirSync as Ar,readFileSync as Ir,writeFileSync as Cr}from"node:fs";import{homedir as Or}from"node:os";import{dirname as vr,join as Ge}from"node:path";function ke(t){let e=String(t||"").trim();if(!e||e.includes("ts.net")||!/^https:\/\//i.test(e))return null;try{return new URL(e)}catch{return null}}var At=/^[A-Z0-9][A-Z0-9._-]{0,11}$/;function Ee(t,{coin:e,side:r,sizeUsd:o,leverage:n,venue:i,confirm:s,user:l}={}){let d=ke(t);if(!d)return null;if(e&&At.test(String(e).toUpperCase())&&d.searchParams.set("coin",String(e).toUpperCase()),(r==="long"||r==="short")&&d.searchParams.set("side",r),Number.isFinite(Number(o))&&Number(o)>=1&&d.searchParams.set("size",String(Math.min(1e5,Math.round(Number(o))))),Number.isInteger(Number(n))&&Number(n)>=1&&d.searchParams.set("lev",String(Math.min(50,Number(n)))),i){let c=String(i).toLowerCase()==="hl"?"hyperliquid":String(i).toLowerCase();d.searchParams.set("venue",c)}else d.searchParams.get("venue")||d.searchParams.set("venue","hyperliquid");return d.searchParams.set("view","perps"),d.searchParams.set("build","1"),s&&/^[0-9a-f]{32}$/i.test(String(s))&&d.searchParams.set("confirm",String(s).toLowerCase()),l&&/^0x[0-9a-fA-F]{40}$/.test(String(l))&&d.searchParams.set("user",String(l).toLowerCase()),d.toString()}var se={robinhood:{chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC"],evm:!0},ethereum:{chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],evm:!0},polygon:{chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],evm:!0},arbitrum:{chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],evm:!0},base:{chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],evm:!0},hyperevm:{chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],evm:!0},bsc:{chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],evm:!0},avalanche:{chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],evm:!0},optimism:{chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],evm:!0},abstract:{chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],evm:!0},stable:{chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],evm:!0},elysium:{chainId:1339,name:"Elysium",rpcEnv:["ELYSIUM_RPC_URL"],evm:!0,readOnly:!0}};var It=new Map(Object.values(se).map(t=>[t.chainId,t]));function ae(t){return It.get(Number(t))||null}var Ct=Object.freeze([{key:"ethereum",chainId:1,name:"Ethereum",rpcEnv:["ETH_RPC_URL","ETHEREUM_RPC_URL","MAINNET_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://etherscan.io",dexscreenerSlug:"ethereum",venueKind:"uniswap-v3",wrappedNative:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",stableQuoteAssets:["0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48","0xdAC17F958D2ee523a2206206994597C13D831ec7"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.71 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:1}}]},{key:"optimism",chainId:10,name:"OP Mainnet",rpcEnv:["OPTIMISM_RPC_URL","OP_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://optimistic.etherscan.io",dexscreenerSlug:"optimism",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",stableQuoteAssets:["0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85","0x94b008aA00579c1307B0EF2c499aD98a8ce58e58"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1905.23 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:10}}]},{key:"bsc",chainId:56,name:"BNB Smart Chain",rpcEnv:["BSC_RPC_URL","BNB_RPC_URL"],nativeCurrency:{symbol:"BNB",decimals:18},explorer:"https://bscscan.com",dexscreenerSlug:"bsc",venueKind:"uniswap-v3",wrappedNative:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",stableQuoteAssets:["0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d","0x55d398326f99059fF775485246999027B3197955"],venues:[{kind:"quoter",address:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WBNB->USDC fee 500 quoted 413.86 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}},{kind:"router",address:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:56}}]},{key:"polygon",chainId:137,name:"Polygon",rpcEnv:["POLYGON_RPC_URL","POLYGON_RPC"],nativeCurrency:{symbol:"POL",decimals:18},explorer:"https://polygonscan.com",dexscreenerSlug:"polygon",venueKind:"uniswap-v3",wrappedNative:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",stableQuoteAssets:["0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359","0xc2132D05D31c914a87C6611C10748AEb04B58e8F"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WMATIC->USDC fee 500 quoted 0.0720 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:137}}]},{key:"stable",chainId:988,name:"Stable Mainnet",rpcEnv:["STABLE_RPC_URL","STABLE_RPC"],nativeCurrency:{symbol:"USDT0",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x5d442b349590a6048Eb2dC0eC346cAA5F47A9ab5",venues:[{kind:"quoter",address:"0xb070179E7032CdA868b53e6C1742F80c9e940d1A",label:"Uniswap V3 QuoterV2 (canonical)",verified:{method:"Stable is on the OFFICIAL Uniswap v3 Deployments List (governance-recognised 2026-05-12, UAC process completed 2026-04, deployed by Protofire), so this is a canonical deployment rather than a fork. eth_getCode returned 8273 bytes, the same size as the canonical quoter on the seven already-verified chains. Functional probe on a live pool (TOAST -> USDT0, fee 10000): 100 in -> 0.000003, 1000 -> 0.000031, 10000 -> 0.000319 USDT0. Output scales monotonically with input, which is a working quoter answering, not a revert. Two of three sampled pools carry non-zero liquidity. NOTE: the pools discovered so far are thin, so real routing size is limited -- the venue is proved, deep liquidity is not.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:988}},{kind:"router",address:"0x32eaf9B5d5F2CD7361c5012890C943D7de84C22a",label:"Uniswap SwapRouter02 (canonical)",verified:{method:"eth_getCode returned 24497 bytes. Cross-checked on-chain rather than trusted from docs: router.factory() returns 0x88f0a512ef09175d456bc9547f914f48c013e4aa, the same v3 core factory that created the pools quoted above, and router.WETH9() returns the wrappedNative recorded on this chain entry. Address published in the Stable docs DEX reference and the Uniswap deployments list.",source:"docs.stable.xyz/en/reference/dexes + on-chain factory()/WETH9() round-trip",date:"2026-08-05",chainId:988}}]},{key:"hyperevm",chainId:999,name:"HyperEVM",rpcEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],nativeCurrency:{symbol:"HYPE",decimals:18},dexscreenerSlug:"hyperevm",venueKind:"uniswap-v3",wrappedNative:"0x5555555555555555555555555555555555555555",venues:[{kind:"quoter",address:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",label:"HyperSwap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle(1 WHYPE -> USDT0) returned live output on all four fee tiers (100: 57.3385, 500: 57.4187, 3000: 57.3237, 10000: 56.1963 USDT0). Decimals read on-chain: WHYPE 18, USDT0 6. Best tier checked against an INDEPENDENT control the same minute -- Hyperliquid allMids put HYPE at 57.3205, so the pool is 0.171% from the perp mid, which is the right shape for fee plus impact rather than a wrong contract or a decimals bug.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}},{kind:"router",address:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D",label:"HyperSwap V3 SwapRouter",verified:{method:"eth_getCode returned 12070 bytes, and it is the router paired with the quoter proved above -- the same pair already shipped in UNI_V3_VENUES[999].hyperswap, which is the map the quote/prepare path actually routes through.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:999}}]},{key:"abstract",chainId:2741,name:"Abstract",rpcEnv:["ABSTRACT_RPC_URL","ABS_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},venueKind:"uniswap-v3",wrappedNative:"0x3439153EB7AF838Ad19d56E1571FBD09333C2809",venues:[{kind:"quoter",address:"0x728BD3eC25D5EDBafebB84F3d67367Cd9EBC7693",label:"Uniswap V3 QuoterV2 (Abstract deployment)",verified:{method:"Abstract is a ZK-stack chain, so CREATE2 addresses differ and the canonical Uniswap addresses are NOT valid here -- probing them returns codesize 0, which is what previously made this chain look like it had no V3 at all. Found the real deployment from live traffic instead: scanned recent Swap(...) logs, took the busiest pool, read pool.factory() = 0xa1160e73b63f322ae88cc2d8e700833e71d0b2a1, then enumerated that factory's deployer (0xf3d63166F0Ca56C3c1A3508FcE03Ff0Cf3Fb691e) and probed each of its 56 contracts with a real quoteExactInputSingle call. Exactly one answered: 1 WETH -> 1846.475731 USDC.e at fee 500. Independent sanity check: the pool's own slot0() spot price is 1873.11 USDC.e per WETH, so the quoter sits ~1.4% below spot, the right shape for fee plus price impact on this size.",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-08-05",chainId:2741}},{kind:"router",address:"0x7712FA47387542819d4E35A23f8116C90C18767C",label:"Uniswap SwapRouter02 (Abstract deployment)",verified:{method:"eth_getCode returned 167392 bytes and the runtime contains the exactInputSingle selector. router.factory() matches the factory proved above and router.WETH9() matches the wrappedNative on this entry. Chosen over its byte-identical twin (0xfD6257F4...) because this is the address real users actually route through: it appeared as tx.to on live swaps against the WETH/USDC.e pool.",source:"on-chain factory()/WETH9() round-trip + live swap tx.to sampling",date:"2026-08-05",chainId:2741}}]},{key:"robinhood",chainId:4663,name:"Robinhood Chain",rpcEnv:["RH_CHAIN_RPC","ROBINHOOD_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},dexscreenerSlug:"robinhood",venueKind:"uniswap-v3",wrappedNative:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",stableQuoteAssets:["0x5fc5360d0400a0fd4f2af552add042d716f1d168"],venues:[{kind:"quoter",address:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDG fee 100 quoted 1866.58 USDG, and USDG->CASHCAT fee 10000 quoted a live amount). A contract that correctly prices known pairs IS a working V3 quoter",source:"live eth_call against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"router",address:"0xcaf681a66d020601342297493863e78c959e5cb2",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode (24497 bytes) on this chain and the paired quoter at the same deployment passed a live functional quote",source:"live eth_getCode against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}},{kind:"factory",address:"0x1f7d7550b1b028f7571e69a784071f0205fd2efa",label:"Uniswap V3 Factory",verified:{method:"eth_getCode returned real bytecode (24535 bytes) and a PoolCreated log scan over this factory returned 76 pools in ~9000 recent blocks",source:"live eth_getLogs against rpc.mainnet.chain.robinhood.com",date:"2026-07-31",chainId:4663}}]},{key:"base",chainId:8453,name:"Base",rpcEnv:["BASE_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://basescan.org",dexscreenerSlug:"base",venueKind:"uniswap-v3",wrappedNative:"0x4200000000000000000000000000000000000006",stableQuoteAssets:["0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"],venues:[{kind:"quoter",address:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",label:"Uniswap V3 QuoterV2 (Base)",verified:{method:"functional probe: quoteExactInputSingle returned WETH->USDC at fee 500 = 1908.44 USDC, a live sane price. The canonical mainnet quoter address also has bytecode on Base but does NOT price this pair, which is exactly the false positive a codesize-only check accepts",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router",address:"0x2626664c2603336E57B271c5C0b26F421741e481",label:"Uniswap V3 SwapRouter02 (Base)",verified:{method:"eth_getCode returned real bytecode and the paired Base quoter passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:8453}},{kind:"router-v2",address:"0x4752ba5DBc23f44D87826276BF6Fd6b1C372aD24",label:"Uniswap V2 Router02 (Base)",verified:{method:"eth_getCode returned 17891 bytes; live getAmountsOut on WETH->USDC round-tripped to 98.75% (2x0.30% fee + impact)",source:"https://docs.uniswap.org/contracts/v2/reference/smart-contracts/v2-deployments",date:"2026-07-30",chainId:8453}}]},{key:"arbitrum",chainId:42161,name:"Arbitrum One",rpcEnv:["ARBITRUM_RPC_URL","ARB_RPC_URL"],nativeCurrency:{symbol:"ETH",decimals:18},explorer:"https://arbiscan.io",dexscreenerSlug:"arbitrum",venueKind:"uniswap-v3",wrappedNative:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",stableQuoteAssets:["0xaf88d065e77c8cC2239327C5EDb3A432268e5831","0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9"],venues:[{kind:"quoter",address:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WETH->USDC fee 500 quoted 1908.72 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}},{kind:"router",address:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:42161}}]},{key:"avalanche",chainId:43114,name:"Avalanche C-Chain",rpcEnv:["AVALANCHE_RPC_URL","AVAX_RPC_URL"],nativeCurrency:{symbol:"AVAX",decimals:18},explorer:"https://snowtrace.io",dexscreenerSlug:"avalanche",venueKind:"uniswap-v3",wrappedNative:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",stableQuoteAssets:["0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"],venues:[{kind:"quoter",address:"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F",label:"Uniswap V3 QuoterV2",verified:{method:"functional probe, not a codesize check: quoteExactInputSingle returned a live sane price (WAVAX->USDC fee 500 quoted 6.48 USDC). A contract that correctly prices a known pair IS a working V3 quoter",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}},{kind:"router",address:"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE",label:"Uniswap V3 SwapRouter02",verified:{method:"eth_getCode returned real bytecode on this chain and the paired quoter at the same deployment passed a live functional quote",source:"scripts/verify-v3-venues.mjs (re-runnable)",date:"2026-07-30",chainId:43114}}]}]);var Ot=Object.freeze({1:"https://eth.blockscout.com",10:"https://explorer.optimism.io",137:"https://polygon.blockscout.com",324:"https://zksync.blockscout.com",8453:"https://base.blockscout.com",42161:"https://arbitrum.blockscout.com",534352:"https://scrollscan.com"});var yn=Object.freeze([100,50,25]),wn=Object.freeze([100,50,25,10]);var m="UNKNOWN",An=Object.freeze(["token","launch","hip3","hip4","polymarket","twap","bridge","swap","approve"]),vt=/[_*[\]`]/g;function a(t){return x(t)?String(t).replace(vt,e=>`\\${e}`):m}function x(t){return t==null?!1:typeof t=="number"?Number.isFinite(t):typeof t=="string"?t.trim()!=="":!0}function L(t){if(!x(t))return m;let e=String(t).replace(/`/g,"");return e===""?m:`\`${e}\``}function z(t,{decimals:e=2}={}){if(!x(t))return m;let r=Number(t);return Number.isFinite(r)?r.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:e}):m}function S(t,{decimals:e=2}={}){let r=z(t,{decimals:e});return r===m?m:`${r} USD`}function ce(t,{decimals:e=2}={}){let r=z(t,{decimals:e});return r===m?m:`${r}%`}function ee(t){let e=z(t,{decimals:0});return e===m?m:`${e} bps`}function V(t,e){if(!x(t))return m;let r=Number(e);if(!Number.isInteger(r)||r<0||r>77)return m;let o;try{o=BigInt(typeof t=="string"?t.trim():t)}catch{return m}let n=o<0n,i=n?-o:o,s=10n**BigInt(r),l=(i/s).toString(),d=(i%s).toString().padStart(r,"0").replace(/0+$/,"");return`${n?"-":""}${l}${d?`.${d}`:""}`}function ue(t){if(typeof t=="number"&&Number.isFinite(t))return t<0||t>1?m:t>=.75?"HIGH":t>=.4?"MEDIUM":"LOW";if(typeof t=="string"){let e=t.trim().toUpperCase();if(e==="HIGH"||e==="MEDIUM"||e==="LOW")return e}return m}function q(t={}){let e=t.chainId;if(!x(e)||!Number.isFinite(Number(e)))return x(t.chain)?a(t.chain):m;let o=ae(e)?.name||(x(t.chain)?String(t.chain):m);return`${a(o)} (chainId ${Number(e)})`}function Ae(t={}){return a(t.venue??t.dex??t.pool?.venue)}function $t(t){return t==null?"NONE (text card only)":typeof t=="string"?t.trim()?L(t):"NONE (text card only)":t.error||t.ok===!1||t.available===!1?`UNAVAILABLE${x(t.error)?` \u2014 ${a(t.error)}`:""} (text card stands)`:x(t.url)?L(t.url):"NONE (text card only)"}function Y(t={},{now:e=Date.now()}={}){let r=t.grant??t.session??null;if(!r||typeof r!="object")return{allowed:!1,reason:"no local grant/session",actions:[]};if(r.local===!1)return{allowed:!1,reason:"grant is not local",actions:[]};if(r.revoked===!0)return{allowed:!1,reason:"grant revoked",actions:[]};let o=r.expiresAt??r.expiry;if(x(o)){let i=typeof o=="number"?o:Date.parse(o);if(!Number.isFinite(i))return{allowed:!1,reason:"grant expiry unreadable",actions:[]};if(i<=e)return{allowed:!1,reason:"grant expired",actions:[]}}return{allowed:!0,reason:"valid local grant",actions:Array.isArray(r.actions)&&r.actions.length?r.actions.slice():["BUY","SELL"]}}function Tt(t){let e=Y(t);return e.allowed?`${e.actions.map(r=>a(r)).join(" / ")} (${a(e.reason)})`:`prepare-only \u2014 ${a(e.reason)}`}function B(t,e,r={}){let o=[`*${t}*`];for(let n of e){if(!n)continue;let[i,s]=n;o.push(`${i}: ${s==null||s===""?m:s}`)}return o.push(`Chart: ${$t(r.chart)}`),o.push(`Actions: ${Tt(r)}`),Array.isArray(r.warnings)&&r.warnings.length&&o.push(`Warnings: ${r.warnings.map(n=>a(n)).join("; ")}`),(x(r.source)||x(r.fetchedAt))&&o.push(`Source: ${a(r.source)} at ${a(r.fetchedAt)}`),o.join(`
|
|
5
5
|
`)}function D(t){let e=ue(t.confidence);return e===m?null:["Confidence",e]}function _t(t){let e=t.quote;if(!e||typeof e!="object")return[];let r=x(e.decimals)?V(e.amountOutRaw??e.out??e.raw,e.decimals):m;return[["Quote out (raw)",L(e.amountOutRaw??e.out??e.raw)],["Quote out",r===m?m:`${a(r)} ${a(e.symbol??"")}`.trim()]]}function Ie(t){let e=t.autoSlippage;if(!e||typeof e!="object")return["Auto-slippage",m];let r=ee(e.selectedBps),o=ee(e.capBps);return["Auto-slippage",r===m&&o===m?m:`${r} selected, cap ${o}`]}function Nt(t={}){let e=t||{};return B(`ORACLE TOKEN \u2014 ${a(e.symbol??e.token??e.name)}`,[["Chain",q(e)],["Venue",Ae(e)],["Name",a(e.name)],["Address",L(e.address??e.mint??e.contract)],["Price",S(e.priceUsd,{decimals:8})],["Market cap",S(e.marketCapUsd)],["Liquidity",S(e.liquidityUsd)],["Volume 24h",S(e.volume24hUsd)],["Change 24h",ce(e.priceChange24h)],["Fee tier",x(e.feeTier)?`${ee(Number(e.feeTier)/100)} (${z(e.feeTier,{decimals:0})})`:m],["Age",a(e.age)],..._t(e),Ie(e),D(e)],e)}function Rt(t={}){let e=t||{};return B(`ORACLE LAUNCH \u2014 ${a(e.symbol??e.token??e.name)}`,[["Chain",q(e)],["Venue",Ae(e)],["Address",L(e.address??e.mint??e.contract)],["Pool",L(e.pool?.address??e.poolAddress??e.pool)],["Liquidity",S(e.liquidityUsd)],["Route ready",a(e.routeReady)],["Sellable",a(e.sellable)],["Sell sim",a(e.sellSimulation??e.sellSim)],["Smart wallets",a(e.smartWalletOverlap)],["Risk",a(e.risk??e.riskStatus)],["Prepared ticket",a(e.preparedTicket??e.ticketStatus)],Ie(e),D(e)],e)}function Pt(t={}){let e=t||{};return B(`ORACLE HIP-3 \u2014 ${a(e.market??e.coin??e.name)}`,[["Venue",`Hyperliquid builder-dex ${a(e.dexName?`${e.dexName} (${e.dex})`:e.dex)}`],["Market",a(e.market??e.coin)],["Mark",S(e.markPx,{decimals:6})],["Oracle",S(e.oraclePx,{decimals:6})],["Funding",ce(e.funding,{decimals:6})],["Open interest",S(e.openInterestUsd)],["Depth",a(e.depth)],["Liquidation notes",a(e.liquidationNotes??e.riskNotes)],["Account context",a(e.accountContext)],D(e)],e)}function Lt(t={}){let e=t||{};return B(`ORACLE HIP-4 \u2014 ${a(e.event??e.market??e.name)}`,[["Venue",`Hyperliquid HIP-4 ${a(e.dex??"outcome")}`],["Event",a(e.event)],["Outcome",a(e.outcome)],["Market id",L(e.marketId??e.market)],["Bid",S(e.bid,{decimals:6})],["Ask",S(e.ask,{decimals:6})],["Depth",a(e.depth)],["Edge",ce(e.edge)],["Position",a(e.position)],D(e)],e)}function Mt(t={}){let e=t||{};return B(`ORACLE POLYMARKET \u2014 ${a(e.event??e.market??e.name)}`,[["Venue","Polymarket CLOB"],["Event",a(e.event)],["Market",a(e.market)],["Market id",L(e.marketId??e.conditionId??e.tokenId)],["Yes",S(e.yesPrice,{decimals:4})],["No",S(e.noPrice,{decimals:4})],["Best bid / ask",`${S(e.bestBid,{decimals:4})} / ${S(e.bestAsk,{decimals:4})}`],["Volume",S(e.volumeUsd)],["Resolution risk",a(e.resolutionRisk)],["Order intent",a(e.orderIntent)],D(e)],e)}function Bt(t={}){let e=t||{},r=x(e.completedSplits)&&x(e.totalSplits)?`${z(e.completedSplits,{decimals:0})} / ${z(e.totalSplits,{decimals:0})}`:m;return B(`ORACLE TWAP \u2014 ${a(e.pair??e.symbol??e.name)}`,[["Chain",q(e)],["Side",a(e.side??e.direction)],["Amount",`${a(V(e.amountTotal??e.amount,e.decimals??18))} ${a(e.symbol??"")}`.trim()],["Splits",`${z(e.totalSplits,{decimals:0})} over ${a(e.window)}`],["Progress",r],["Avg price",S(e.averagePrice,{decimals:6})],["Next split",a(e.nextSplitAt)],["Slippage cap",ee(e.slippageBps)],["Status",a(e.status)],D(e)],e)}function Dt(t={}){let e=t||{},r=e.approval??e.revokeCheck??{},o=r.needsRevoke&&r.spender?`revoke.cash \u2014 ${a(r.spender)}`:r.needsRevoke===!1?"revoke.cash \u2014 clean":"revoke.cash \u2014 unchecked";return B(`ORACLE BRIDGE \u2014 ${a(e.pair??e.fromSymbol)} \u2192 ${a(e.toSymbol??"")}`.replace(/→ $/,""),[["Bridging","deBridge \xB7 LI.FI \u2014 best route wins"],["From chain",q({chainId:e.fromChainId,chain:e.fromChain})],["To chain",q({chainId:e.toChainId,chain:e.toChain})],["Amount",`${a(V(e.amount,e.fromDecimals??18))} ${a(e.fromSymbol??"")}`.trim()],["Best route",a(e.bestRoute??e.winner)],["Est. received",`${a(V(e.amountOut,e.toDecimals??18))} ${a(e.toSymbol??"")}`.trim()],["Fee",S(e.feeUsd)],["Est. time",a(e.estimatedTime)],["Revoke check",o],["All providers",a(e.providers?.join(", "))],["Preparable",a(e.preparable)],D(e)],e)}function Ut(t){let r=(Array.isArray(t)?t:[]).slice(1,4).map(o=>{let n=a(o.source??o.venue??o.name),i=o.improvementBps==null&&o.deltaBps==null?null:Number(o.improvementBps??o.deltaBps),s=Number.isFinite(i)?`${Math.abs(i).toFixed(0)} bps behind`:"spread UNKNOWN";return`${n} (${s})`});return r.length?r.join("; "):m}function Ft(t){let e=t.rankedOn??t.swap?.rankedOn??t.best?.rankedOn;return x(e)?a(e):m}function qt(t={}){let e=t||{},r=e.swap&&typeof e.swap=="object"?e.swap:e,o=e.bridge&&typeof e.bridge=="object"?e.bridge:null,n=r.best??r.winner??{},i=`${a(e.tokenInSymbol??e.fromSymbol??"IN")} \u2192 ${a(e.tokenOutSymbol??e.toSymbol??"OUT")}`,s=[["Intent",a(e.intent??"swap")],["Chain",q({chainId:e.chainId??r.chainId,chain:e.chain??r.chain})],["Pair",i],["Amount in",`${a(V(e.amountIn??r.amountIn,e.decimalsIn??18))} ${a(e.tokenInSymbol??"")}`.trim()],["Best swap",a(n.source??n.venue??r.bestRoute??e.bestRoute)],["Net out",`${a(V(n.netOut??n.amountOut??r.amountOut,e.decimalsOut??18))} ${a(e.tokenOutSymbol??"")}`.trim()],["Ranked on",Ft(r)],["Gas accounted",a(n.costAccounted===!0?"yes":n.costAccounted===!1?"no \u2014 gross ranking may flatter this route":null)],["Spread vs next",x(r.improvementBps)?`${a(r.improvementBps)} bps`:m],["Runners-up",Ut(r.routes??e.routes)]];if(o){let l=o.best??o.winner??{};s.push(["Best bridge",a(l.source??o.bestRoute??e.bestBridge)],["Bridge out",`${a(V(l.netOut??l.amountOut??o.amountOut,e.bridgeDecimalsOut??e.decimalsOut??18))} ${a(e.bridgeOutSymbol??e.tokenOutSymbol??"")}`.trim()],["Bridge to",q({chainId:o.toChainId??e.toChainId,chain:o.toChain??e.toChain})],["Est. time",a(o.estimatedTime??l.meta?.durationSeconds)])}else s.push(["Best bridge","same-chain \u2014 use Best swap"]);return s.push(["Preparable",a(e.preparable??n.executionReady)],D(e)),B(`ORACLE SWAP \u2014 ${i}`,s,e)}function jt(t={}){let e=t||{};return B("ORACLE APPROVE \u2014 local signer",[["Pending id",L(e.id??(typeof e.digest=="string"?e.digest.slice(0,8):null))],["Surface",a(e.surface)],["Action",a(e.action)],["Chain",q({chainId:e.chain??e.chainId,chain:e.chainName})],["To",L(e.to??e.destination)],["Value",x(e.value)?a(e.value):m],["Signer",a(e.armed===!0?"running + armed":e.armed===!1?"running, disarmed":"not running")],D({confidence:e.confidence??(e.armed===!0?"high":"low")})],e)}var In=Object.freeze({token:Nt,launch:Rt,hip3:Pt,hip4:Lt,polymarket:Mt,twap:Bt,bridge:Dt,swap:qt,approve:jt});import{AbiCoder as tr,Interface as rr,getAddress as Le,isAddress as nr}from"ethers";import{AbiCoder as er,Interface as fe,getAddress as Eo,isAddress as Ao,keccak256 as Io}from"ethers";import{AsyncLocalStorage as Ht}from"node:async_hooks";var vn=new Ht;var Dn=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted")?.get,Un=Object.getOwnPropertyDescriptor(AbortSignal.prototype,"reason")?.get,Fn=AbortSignal.prototype.throwIfAborted,qn=EventTarget.prototype.addEventListener,jn=EventTarget.prototype.removeEventListener,Hn=typeof AbortSignal.any=="function"?AbortSignal.any.bind(AbortSignal):null;var zn=64*1024,Vn=Object.freeze({depth:32,nodes:1e4,fields:1e4,arrayLength:1e4,bytes:1024*1024});import{Interface as Vt,getAddress as Jn}from"ethers";var Zn=new Vt(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);var io=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"});import{createHash as Kt,createHmac as Wt,timingSafeEqual as bo}from"node:crypto";var Gt=2,Xt=300*1e3,Yt=(()=>{let t=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(t)&&t>0?t:1800*1e3})();function le(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${t.map(le).join(",")}]`:`{${Object.keys(t).sort().map(r=>`${JSON.stringify(r)}:${le(t[r])}`).join(",")}}`}function Ce(t){let e=String(t?.ORACLE_STAMP_HMAC_SECRET||"").trim();return e.length>=16?e:""}function Oe(t=process.env){return Ce(process.env)||Ce(t)}function Qt(t){let{prepareHash:e,prepareMac:r,note:o,...n}=t||{};return n}function Jt(t){let e=Qt(t);return Kt("sha256").update(le(e)).digest("hex")}function Zt(t,e=Oe()){return e?Wt("sha256",e).update(String(t)).digest("hex"):""}function de(t,{provider:e,kind:r,env:o=process.env,nowMs:n=Date.now(),expiresAtMs:i}={}){if(!t||typeof t!="object")throw new Error("stampPrepared: payload object required");let s=Object.prototype.hasOwnProperty.call(t,"oraclePrepared");if(s&&typeof t.oraclePrepared!="boolean")throw new Error("stampPrepared: oraclePrepared must be boolean");let l={...t,provider:t.provider||e,kind:t.kind||r,requiresUserSignature:t.requiresUserSignature!==!1,signingReady:!1,broadcastReady:!1,executionReady:!1,oraclePrepared:s?t.oraclePrepared:!0};if(!l.provider)throw new Error("stampPrepared: provider required");if(!l.kind)throw new Error("stampPrepared: kind required");let d=Number(n),c=i==null?d+Xt:Number(i),u=c-d;if(!Number.isSafeInteger(d)||!Number.isSafeInteger(c)||u<=0||u>Yt)throw new Error("stampPrepared: bounded preparedAt/expiresAt required");let h={...l,preparedAt:d,expiresAt:c,prepareVersion:Gt},b=Jt(h),p=Oe(o),y=p?Zt(b,p):void 0,w={...h,prepareHash:b};return y&&(w.prepareMac=y),w}var To=er.defaultAbiCoder();var ve={1:{name:"ethereum",poolManager:"0x000000000004444c5dc75cB358380D2e3dE08A90",quoter:"0x52f0e24d1c21c8a0cb1e5a5dd6198556bd9e1203",stateView:"0x7ffe42c4a5deea5b0fec41c94c136cf115597227",universalRouter:"0x66a9893cc07d91d95644aedd05d03f95e1dba8af",weth:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",usdc:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},10:{name:"optimism",poolManager:"0x9a13f98cb987694c9f086b1f5eb990eea8264ec3",quoter:"0x1f3131a13296fb91c90870043742c3cdbff1a8d7",stateView:"0xc18a3169788f4f75a170290584eca6395c75ecdb",universalRouter:"0x851116d9223fabed8e56c0e6b8ad0c31d98b3507",weth:"0x4200000000000000000000000000000000000006",usdc:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85"},56:{name:"bsc",poolManager:"0x28e2ea090877bf75740558f6bfb36a5ffee9e9df",quoter:"0x9f75dd27d6664c475b90e105573e550ff69437b0",stateView:"0xd13dd3d6e93f276fafc9db9e6bb47c1180aee0c4",universalRouter:"0x1906c1d672b88cd1b9ac7593301ca990f94eae07",weth:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",usdc:"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d"},137:{name:"polygon",poolManager:"0x67366782805870060151383f4bbff9dab53e5cd6",quoter:"0xb3d5c3dfc3a7aebff71895a7191796bffc2c81b9",stateView:"0x5ea1bd7974c8a611cbab0bdcafcb1d9cc9b3ba5a",universalRouter:"0x1095692a6237d83c6a72f3f5efedb9a670c49223",weth:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",usdc:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"},8453:{name:"base",poolManager:"0x498581fF718922c3f8e6A244956aF099B2652b2b",quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",stateView:"0xa3c0c9b65bad0b08107aa264b0f3db444b867a71",universalRouter:"0x6ff5693b99212da76ad316178a184ab56d299b43",weth:"0x4200000000000000000000000000000000000006",usdc:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"},42161:{name:"arbitrum",poolManager:"0x360e68faccca8ca495c1b759fd9eee466db9fb32",quoter:"0x3972c00f7ed4885e145823eb7c655375d275a1c5",stateView:"0x76fd297e2d437cd7f76d50f01afe6160f86e9990",universalRouter:"0xa51afafe0263b40edaef0df8781ea9aa03e381a3",weth:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",usdc:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"},43114:{name:"avalanche",poolManager:"0x06380c0e0912312b5150364b9dc4542ba0dbbc85",quoter:"0xbe40675bb704506a3c2ccfb762dcfd1e979845c2",stateView:"0xc3c9e198c735a4b97e3e683f391ccbdd60b69286",universalRouter:"0x94b75331ae8d42c1b61065089b7d48fe14aa73b7",weth:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",usdc:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"},4663:{name:"robinhood",poolManager:"0x8366a39cc670b4001a1121b8f6a443a643e40951",quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",stateView:"0xf3334192d15450cdd385c8b70e03f9a6bd9e673b",universalRouter:"0x8876789976dEcBfCbBbe364623C63652db8C0904",weth:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",usdc:"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"}};var _o=new fe(["function quoteExactInputSingle(((address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey,bool zeroForOne,uint128 exactAmount,bytes hookData) params) returns (uint256 amountOut, uint256 gasEstimate)","function quoteExactOutputSingle(((address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey,bool zeroForOne,uint128 exactAmount,bytes hookData) params) returns (uint256 amountIn, uint256 gasEstimate)"]),No=new fe(["function execute(bytes commands,bytes[] inputs,uint256 deadline) payable"]),Ro=new fe(["function getSlot0(bytes32 poolId) view returns (uint160 sqrtPriceX96,int24 tick,uint24 protocolFee,uint24 lpFee)","function getLiquidity(bytes32 poolId) view returns (uint128 liquidity)"]),Po=Object.freeze([[13,"beforeInitialize"],[12,"afterInitialize"],[11,"beforeAddLiquidity"],[10,"afterAddLiquidity"],[9,"beforeRemoveLiquidity"],[8,"afterRemoveLiquidity"],[7,"beforeSwap"],[6,"afterSwap"],[5,"beforeDonate"],[4,"afterDonate"],[3,"beforeSwapReturnsDelta"],[2,"afterSwapReturnsDelta"],[1,"afterAddLiquidityReturnsDelta"],[0,"afterRemoveLiquidityReturnsDelta"]]),Lo=(1n<<14n)-1n;var Me=tr.defaultAbiCoder(),j="0x0000000000000000000000000000000000000000",$e="0x000000000022D473030F116dDEE9F6B43aC78BA3",Te=-887272,_e=887272,_=(1n<<128n)-1n,or=(1n<<256n)-1n,ir=(1n<<24n)-1n,Ne=30,Re=600,T=Object.freeze({INCREASE_LIQUIDITY:0,DECREASE_LIQUIDITY:1,MINT_POSITION:2,BURN_POSITION:3,SETTLE_PAIR:13,TAKE_PAIR:17,CLOSE_CURRENCY:18,SWEEP:20}),sr=Object.freeze(Object.fromEntries(Object.entries(T).map(([t,e])=>[e,t]))),ar=Object.freeze(["mint","decrease","collect","burn","rebalance"]),Be=new rr(["function modifyLiquidities(bytes unlockData, uint256 deadline) payable"]),cr=Be.getFunction("modifyLiquidities").selector,ur="tuple(address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks)",lr=Object.freeze({MINT_POSITION:Object.freeze([ur,"int24","int24","uint256","uint128","uint128","address","bytes"]),INCREASE_LIQUIDITY:Object.freeze(["uint256","uint256","uint128","uint128","bytes"]),DECREASE_LIQUIDITY:Object.freeze(["uint256","uint256","uint128","uint128","bytes"]),BURN_POSITION:Object.freeze(["uint256","uint128","uint128","bytes"]),SETTLE_PAIR:Object.freeze(["address","address"]),TAKE_PAIR:Object.freeze(["address","address","address"]),CLOSE_CURRENCY:Object.freeze(["address"]),SWEEP:Object.freeze(["address","address"])});function g(t){throw new Error(`uniswap-v4-lp: ${t}`)}function R(t,e){(t==null||t==="")&&g(`${e} address required`);let r=String(t);return nr(r)||g(`${e} is not a valid address: ${r}`),Le(r)}function k(t,e,{max:r=or,min:o=0n}={}){(t==null||t==="")&&g(`${e} required`);let n;try{n=typeof t=="bigint"?t:BigInt(String(t))}catch{g(`${e} must be an integer, got ${String(t)}`)}return n<o&&g(`${e} must be >= ${o}`),n>r&&g(`${e} exceeds ${e==="fee"?"uint24":r===_?"uint128":"uint256"}`),n}function Pe(t,e){let r=Number(t);return Number.isInteger(r)||g(`${e} must be an integer tick`),(r<Te||r>_e)&&g(`${e} ${r} outside [${Te}, ${_e}]`),r}function te(t){return t==null||t===""||String(t).toLowerCase()!=="0x"&&g("opaque hookData is inspect-only until a hook-specific adapter exists"),"0x"}function De(t={}){(!t||typeof t!="object")&&g("poolKey required");let e=t.currency0==null||t.currency0===""?j:R(t.currency0,"poolKey.currency0"),r=R(t.currency1,"poolKey.currency1");BigInt(e)>=BigInt(r)&&g("poolKey.currency0 must sort below currency1 (V4 PoolKey invariant); reordering would target a different pool");let o=Number(k(t.fee,"fee",{max:ir})),n=Number(t.tickSpacing);(!Number.isInteger(n)||n<=0||n>32767)&&g(`poolKey.tickSpacing must be a positive int16, got ${t.tickSpacing}`);let i=t.hooks==null||t.hooks===""?j:R(t.hooks,"poolKey.hooks");return{currency0:e,currency1:r,fee:o,tickSpacing:n,hooks:i}}function Ue(t,e,r){let o=Pe(t,"tickLower"),n=Pe(e,"tickUpper");return o>=n&&g(`tickLower ${o} must be below tickUpper ${n}`),(o%r!==0||n%r!==0)&&g(`ticks must be multiples of tickSpacing ${r} (got ${o}, ${n})`),{tickLower:o,tickUpper:n}}function dr(t){let e=Number(t);return(!Number.isSafeInteger(e)||e<=0)&&g("deadline (unix seconds) required"),e}function Fe(t){return`0x${t.map(e=>e.toString(16).padStart(2,"0")).join("")}`}function N(t,e){return Me.encode(lr[t],e)}function fr(t,e){return(!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length||t.length===0)&&g("actions and params must be equal-length non-empty arrays"),Me.encode(["bytes","bytes[]"],[Fe(t),e])}function re({chainId:t,positionManager:e,actions:r,params:o,deadline:n,value:i,summary:s,extra:l={}}){let d=fr(r,o),c=Be.encodeFunctionData("modifyLiquidities",[d,BigInt(n)]);return Object.freeze({chainId:Number(t),to:e,data:c,value:i.toString(),deadline:n,actions:r.map(u=>sr[u]),actionsHex:Fe(r),summary:s,...l})}function ne(t){let e=Number(t.chainId);(!Number.isInteger(e)||e<=0)&&g("chainId required");let r=R(t.positionManager,"positionManager");return{chainId:e,positionManager:r,deadline:dr(t.deadline)}}function pr(t={}){let{chainId:e,positionManager:r,deadline:o}=ne(t),n=De(t.poolKey),{tickLower:i,tickUpper:s}=Ue(t.tickLower,t.tickUpper,n.tickSpacing),l=k(t.liquidity,"liquidity");l===0n&&g("liquidity must be > 0 for mint");let d=k(t.amount0Max,"amount0Max",{max:_}),c=k(t.amount1Max,"amount1Max",{max:_}),u=R(t.owner,"owner"),f=te(t.hookData),h=n.currency0===j,b=[T.MINT_POSITION,T.SETTLE_PAIR],p=[N("MINT_POSITION",[n,i,s,l,d,c,u,f]),N("SETTLE_PAIR",[n.currency0,n.currency1])];h&&(b.push(T.SWEEP),p.push(N("SWEEP",[j,u])));let y=h?d:0n,w=`mint v4 LP ${n.currency0}/${n.currency1} fee ${n.fee} ticks [${i}, ${s}] liquidity ${l} (max ${d} / ${c}) to ${u}${h?" paying native value":""}${n.hooks!==j?` hooked ${n.hooks}`:""}`;return re({chainId:e,positionManager:r,actions:b,params:p,deadline:o,value:y,summary:w,extra:{poolKey:n,tickLower:i,tickUpper:s,owner:u,requiresApproval:He(n,{amount0Max:d,amount1Max:c})}})}function qe(t={}){let{chainId:e,positionManager:r,deadline:o}=ne(t),n=k(t.tokenId,"tokenId"),i=k(t.liquidity,"liquidity"),s=k(t.amount0Min,"amount0Min",{max:_}),l=k(t.amount1Min,"amount1Min",{max:_}),{currency0:d,currency1:c}=je(t),u=R(t.recipient??t.owner,"recipient"),f=te(t.hookData),h=[T.DECREASE_LIQUIDITY,T.TAKE_PAIR],b=[N("DECREASE_LIQUIDITY",[n,i,s,l,f]),N("TAKE_PAIR",[d,c,u])],p=i===0n?`collect fees on v4 LP #${n} to ${u}`:`decrease v4 LP #${n} by ${i} liquidity (min ${s} / ${l}) to ${u}`;return re({chainId:e,positionManager:r,actions:h,params:b,deadline:o,value:0n,summary:p,extra:{tokenId:n.toString(),recipient:u,currency0:d,currency1:c}})}function mr(t={}){return qe({...t,liquidity:0n,amount0Min:0n,amount1Min:0n})}function hr(t={}){let{chainId:e,positionManager:r,deadline:o}=ne(t),n=k(t.tokenId,"tokenId"),i=k(t.amount0Min,"amount0Min",{max:_}),s=k(t.amount1Min,"amount1Min",{max:_}),{currency0:l,currency1:d}=je(t),c=R(t.recipient??t.owner,"recipient"),u=te(t.hookData),f=[T.BURN_POSITION,T.TAKE_PAIR],h=[N("BURN_POSITION",[n,i,s,u]),N("TAKE_PAIR",[l,d,c])];return re({chainId:e,positionManager:r,actions:f,params:h,deadline:o,value:0n,summary:`burn v4 LP #${n} (min ${i} / ${s}) to ${c}`,extra:{tokenId:n.toString(),recipient:c,currency0:l,currency1:d}})}function br(t={}){let{chainId:e,positionManager:r,deadline:o}=ne(t),n=t.burn||{},i=t.mint||{},s=k(n.tokenId,"burn.tokenId"),l=k(n.amount0Min??0n,"burn.amount0Min",{max:_}),d=k(n.amount1Min??0n,"burn.amount1Min",{max:_}),c=De(i.poolKey);c.currency0===j&&g("rebalance refuses native currency pools: shortfall msg.value cannot be sized offline");let{tickLower:u,tickUpper:f}=Ue(i.tickLower,i.tickUpper,c.tickSpacing),h=k(i.liquidity,"mint.liquidity");h===0n&&g("mint.liquidity must be > 0 for rebalance");let b=k(i.amount0Max,"mint.amount0Max",{max:_}),p=k(i.amount1Max,"mint.amount1Max",{max:_}),y=R(i.owner??t.owner,"owner"),w=te(i.hookData??n.hookData),$=[T.BURN_POSITION,T.MINT_POSITION,T.CLOSE_CURRENCY,T.CLOSE_CURRENCY],M=[N("BURN_POSITION",[s,l,d,w]),N("MINT_POSITION",[c,u,f,h,b,p,y,w]),N("CLOSE_CURRENCY",[c.currency0]),N("CLOSE_CURRENCY",[c.currency1])];return re({chainId:e,positionManager:r,actions:$,params:M,deadline:o,value:0n,summary:`rebalance v4 LP: burn #${s} then mint ${c.currency0}/${c.currency1} fee ${c.fee} ticks [${u}, ${f}] liquidity ${h} (max ${b} / ${p}) to ${y}, one unlock`,extra:{burnTokenId:s.toString(),poolKey:c,tickLower:u,tickUpper:f,owner:y,requiresApproval:He(c,{amount0Max:b,amount1Max:p})}})}function je(t){let e=t.poolKey&&typeof t.poolKey=="object"?t.poolKey:t,r=e.currency0==null||e.currency0===""?j:R(e.currency0,"currency0"),o=R(e.currency1,"currency1");return BigInt(r)>=BigInt(o)&&g("currency0 must sort below currency1"),{currency0:r,currency1:o}}function He(t,{amount0Max:e,amount1Max:r}){let o=[];return t.currency0!==j&&o.push({token:t.currency0,spender:$e,amount:e.toString()}),o.push({token:t.currency1,spender:$e,amount:r.toString()}),{note:"PositionManager settles ERC-20 debt via Permit2; token\u2192Permit2 approval and a Permit2 allowance for PositionManager are both required",approvals:o}}var gr=Object.freeze({mint:pr,decrease:qe,collect:mr,burn:hr,rebalance:br});function ze(t={},e={}){let r=e.chains||ve,o=Number(t.chainId);(!Number.isInteger(o)||o<=0)&&g("chainId required");let n=r[o];n||g(`unsupported chainId ${o} (supported: ${Object.keys(r).join(", ")})`),n.positionManager||g(`no v4 PositionManager registered for chain ${o} (${n.name||"unnamed"})`);let i=String(t.kind||"").toLowerCase(),s=gr[i];s||g(`unknown kind ${t.kind} (expected ${ar.join("|")})`);let l=Number(t.deadlineSec);(!Number.isInteger(l)||l<Ne||l>Re)&&g(`deadlineSec must be an integer from ${Ne} through ${Re}`);let c=Number(e.nowSeconds??Math.floor(Date.now()/1e3))+l,u=t.params&&typeof t.params=="object"?t.params:{},f=s({...u,chainId:o,positionManager:Le(n.positionManager),deadline:c}),h=t.from??u.owner??u.recipient??null,b=h?R(h,"from"):null,p={...f},{to:y,data:w,value:$,summary:M,actions:K,actionsHex:E,requiresApproval:O=null}=f;for(let H of["to","data","value","summary","actions","actionsHex","requiresApproval","chainId","deadline"])delete p[H];return de({provider:"uniswap-v4-lp",kind:`univ4-lp-${i}`,lpKind:i,prepareReady:!0,calldataReady:!0,executionReady:!1,executionAllowed:!1,requiresUserSignature:!0,requiresWalletSignature:!0,backendSigner:!1,unsigned:!0,houseSigned:!1,signingReady:!1,broadcastReady:!1,simulate:null,chainId:o,chainName:n.name||null,deadline:c,summary:M,plan:{actions:K,actionsHex:E,selector:cr},detail:p,requiresApproval:O,transaction:{chainId:o,from:b,to:y,data:w,value:$},notes:["prepare-only: user wallet must sign","one modifyLiquidities unlock; Telegram never sends","action bytes verified against v4-periphery Actions.sol; simulate before signing"]},{provider:"uniswap-v4-lp",kind:`univ4-lp-${i}`,env:e.env,nowMs:e.nowMs})}var Ve=1e3,I="unknown",yr=/^[a-z0-9-]{4,40}$/i;function v(t){return t==null?!1:typeof t=="number"?Number.isFinite(t):typeof t=="string"?t.trim()!==""&&t.trim().toLowerCase()!==I:!0}function Q(t,{estimate:e=!0,signed:r=!1}={}){if(!v(t))return I;let o=Number(t);if(!Number.isFinite(o))return I;let n=Math.abs(o),i=n>=1e3?n.toLocaleString("en-US",{maximumFractionDigits:0}):n.toFixed(2),s=o<0?"-":r&&o>0?"+":"";return`${e?"~":""}${s}$${i}`}function pe(t){if(!v(t))return I;let e=Number(t);return Number.isFinite(e)?e===0?"0":e>=1e3?e.toLocaleString("en-US",{maximumFractionDigits:2}):e>=1?e.toFixed(4):e.toPrecision(4):I}function wr(t){if(!v(t))return I;let e=Number(t);return Number.isFinite(e)?`${(e/1e4).toFixed(e%100===0?2:3)}%`:a(t)}function xr(t){let e={1:"Ethereum",10:"Optimism",56:"BSC",137:"Polygon",8453:"Base",42161:"Arbitrum",43114:"Avalanche",4663:"Robinhood"},r=Number(t);return Number.isInteger(r)?e[r]?`${e[r]} (${r})`:`chain ${r}`:I}function Sr(t){if(!t||typeof t!="object")return`Decision: ${I}`;let e=v(t.action)?String(t.action).toUpperCase():I,r=v(t.mode)?String(t.mode):"alert_only",o=v(t.reason)?a(t.reason):I;return`Decision: ${a(e)} (${a(r)}) \u2014 ${o}`}function Ke(t={}){let r=[`*LP ${v(t.pair)?a(t.pair):I} \xB7 ${a(xr(t.chainId))}*`,`Net: ${Q(t.netUsd,{signed:!0})}`,`Fees ${Q(t.feesUsd)} \xB7 IL ${Q(t.ilUsd)} \xB7 Gas ${Q(t.gasUsd)} \xB7 Slip ${Q(t.slippageUsd)}`,`Range: ${pe(t.rangeLower)} \u2013 ${pe(t.rangeUpper)} \xB7 now ${pe(t.priceNow)} \xB7 ${typeof t.inRange=="boolean"?t.inRange?"IN range":"OUT of range":`range ${I}`}`,`Fee tier: ${wr(t.feeTier)}`,Sr(t.decision)];(v(t.source)||v(t.observedAt))&&r.push(`Source: ${v(t.source)?a(t.source):I} at ${v(t.observedAt)?a(t.observedAt):I}`),r.push("Buttons open the graph or queue an unsigned prepare. Telegram never sends.");let o=r.join(`
|
|
6
6
|
`);return o.length>Ve&&(o=`${o.slice(0,Ve-1)}\u2026`),o}function We({platform:t="telegram",artifactId:e,hasGrant:r=!1,openUrl:o,collectUrl:n}={}){let i=String(e||"").trim().toLowerCase();if(!yr.test(i))return{kind:"text_menu",text:"no LP artifact to continue",cancelHint:""};let s=[];v(o)&&s.push({text:"Open",url:String(o)}),s.push({text:"Refresh",callback_data:`oracle:card:refresh:${i}`});let l=[v(n)?{text:"Collect",url:String(n)}:{text:"Collect",callback_data:`oracle:card:collect:${i}`}];r&&l.push({text:"Rebalance",callback_data:`oracle:card:rebalance:${i}`}),l.push({text:"Exit",callback_data:`oracle:card:exit:${i}`});let d=[s,l].filter(f=>f.length>0),c=r?"Collect/Rebalance/Exit queue unsigned prepares. Sign in your wallet. Telegram never sends.":"Collect/Exit queue unsigned prepares. Rebalance needs a local grant. Telegram never sends.";return String(t)==="telegram"?{kind:"inline_keyboard",replyMarkup:{inline_keyboard:d},cancelHint:c}:{kind:"text_menu",text:d.flat().map(f=>f.text).join(" / "),cancelHint:c}}var Xe=Object.freeze(["deepen","refresh","prepare","ta","fa","long","short","allow","deny","bag","follow","rebalance","exit","collect"]),Ye=Object.freeze({rebalance:"rebalance",exit:"burn",collect:"collect"}),$r=new Set(Xe),he=/^[a-z0-9-]{4,40}$/i,Qe=/^[0-9a-f]{32}$/,Je=/^\d+$/,Tr=new RegExp(`^oracle:card:(${Xe.join("|")}):([a-z0-9-]{4,40})$`,"i");function be(t=process.env){return Ge(t.ORACLE_CONFIG_DIR||Ge(Or(),".config","oracle"),"telegram-cards.json")}function W(){return{links:{},artifacts:{},threads:{}}}var J=W();function ge(){return J}function Ze(t,{readFile:e=Ir}={}){try{let r=JSON.parse(String(e(t)));J={links:r.links&&typeof r.links=="object"?r.links:{},artifacts:r.artifacts&&typeof r.artifacts=="object"?r.artifacts:{},threads:r.threads&&typeof r.threads=="object"?r.threads:{}}}catch{J=W()}return J}function et(t,e=J,{writeFile:r=Cr,mkdir:o=Ar}={}){o(vr(t),{recursive:!0,mode:448}),r(t,JSON.stringify(e),{mode:384})}function U(t){return t==null?!1:typeof t=="string"?t.trim()!=="":!0}function tt(t){return kr("sha256").update(String(t)).digest("hex")}var _r=new Set(["tokenId","poolKey","burnTokenId"]);function me(t){if(Array.isArray(t))return t.map(me);if(!t||typeof t!="object")return t;let e={};for(let[r,o]of Object.entries(t))!_r.has(r)&&/(secret|token|key|seed|private|password|mnemonic|auth)/i.test(r)||(e[r]=me(o));return e}function rt(t){return String(t?.kind||"").toLowerCase()==="lp"}function Nr(t){let r=String(t||"").trim().match(Tr);return r?{action:r[1].toLowerCase(),artifactId:r[2].toLowerCase()}:null}function Rr({platform:t="telegram",artifactId:e,openUrl:r,hasGrant:o=!1}={}){let n=String(e||"").trim().toLowerCase();if(!he.test(n))return{kind:"text_menu",text:"no artifact to continue",cancelHint:""};let i=[],s=[{text:"TA",callback_data:`oracle:card:ta:${n}`},{text:"FA",callback_data:`oracle:card:fa:${n}`}],l=f=>Ee(r,{side:f}),d=l("long"),c=l("short"),u=d&&c?[{text:"LONG",url:d},{text:"SHORT",url:c}]:[{text:"LONG",callback_data:`oracle:card:long:${n}`},{text:"SHORT",callback_data:`oracle:card:short:${n}`}];return U(r)?(i.push([{text:"Open",url:String(r)},s[0]]),i.push(u),i.push(o?[s[1],{text:"Prep",callback_data:`oracle:card:prepare:${n}`}]:[s[1]])):(i.push(s),i.push(u),o&&i.push([{text:"Prep",callback_data:`oracle:card:prepare:${n}`}])),String(t)==="telegram"?{kind:"inline_keyboard",replyMarkup:{inline_keyboard:i.filter(f=>f.length>0)},cancelHint:"LONG/SHORT open the graph. CONFIRM there. Telegram never sends."}:{kind:"text_menu",text:"TA / FA / LONG / SHORT",cancelHint:""}}function nt(t,e){return rt(t)?We({artifactId:t.id,openUrl:t.openUrl,collectUrl:t.payload?.lp?.collectUrl,hasGrant:e}):Rr({artifactId:t.id,openUrl:t.openUrl,hasGrant:e})}function ot(t={}){if(rt(t)&&t.payload?.lp?.card&&typeof t.payload.lp.card=="object")return Ke(t.payload.lp.card);let r=[`*${U(t.title)?a(t.title):"Oracle artifact"}*`,`Kind: ${U(t.kind)?a(t.kind):m}`,`Id: ${U(t.id)?`\`${String(t.id).replace(/`/g,"")}\``:m}`,`Summary: ${U(t.summary)?a(t.summary):m}`],o=ue(t.confidence);o!==m&&r.push(`Confidence: ${o}`),(U(t.source)||U(t.fetchedAt))&&r.push(`Source: ${a(t.source)} at ${a(t.fetchedAt)}`),Array.isArray(t.warnings)&&t.warnings.length&&r.push(`Warnings: ${t.warnings.map(i=>a(i)).join("; ")}`);let n=Y(t);return r.push(n.allowed?"Actions: TA / FA / LONG / SHORT open the graph. Execute on CONFIRM there.":`Actions: TA / FA / LONG / SHORT \u2014 ${a(n.reason)}`),r.join(`
|
|
7
7
|
`)}function Pr(t,e={},{now:r=Date.now()}={}){let o=t||W(),n=String(e.id||"").trim().toLowerCase();if(!he.test(n))throw new TypeError("artifact id required");let i={id:n,kind:String(e.kind||"thesis"),title:String(e.title||"Oracle artifact"),summary:String(e.summary||""),openUrl:U(e.openUrl)?String(e.openUrl):null,confidence:e.confidence,source:e.source||"oracle",fetchedAt:e.fetchedAt||new Date(r).toISOString(),warnings:Array.isArray(e.warnings)?e.warnings.map(String):[],payload:me(e.payload||{}),wallet:/^0x[0-9a-f]{40}$/i.test(String(e.wallet||""))?String(e.wallet).toLowerCase():null,walletLabel:U(e.walletLabel)?String(e.walletLabel).slice(0,64):null,chainId:Number.isInteger(Number(e.chainId))&&Number(e.chainId)>0?Number(e.chainId):null,createdAt:new Date(r).toISOString()};return o.artifacts[n]=i,i}function ye(t,{chatId:e,artifactId:r,now:o=Date.now()}={}){let n=t||W(),i=String(e||"").trim(),s=String(r||"").trim().toLowerCase();if(!i)throw new TypeError("chat id required");if(!he.test(s))throw new TypeError("artifact id required");return n.threads[i]={artifactId:s,updatedAt:o},n.threads[i]}function it(t,{chatId:e,text:r}={}){let o=String(e||"").trim(),n=String(r||"").trim();if(!o||!n||/^\//.test(n))return null;let i=t?.threads?.[o];if(!i?.artifactId)return null;let s=t.artifacts?.[i.artifactId];return s?`Continue artifact ${s.id} (${s.kind}). Prior: ${s.summary||s.title}. User: ${n}`:null}function st(t,{ownerId:e,botUsername:r,now:o=Date.now(),ttlMs:n=600*1e3,token:i,randomBytes:s=Er}={}){let l=t||W(),d=String(e||"").trim(),c=String(r||"").replace(/^@/,"").trim();if(!Je.test(d))throw new TypeError("owner Telegram id required");if(!/^[A-Za-z0-9_]{5,32}$/.test(c))throw new TypeError("bot username required");let u=i||s(16).toString("hex");if(!Qe.test(u))throw new TypeError("link token must be 32 hex chars");return l.links[tt(u)]={ownerId:d,expiresAt:o+Number(n)},{token:u,url:`https://t.me/${c}?start=${u}`,expiresAt:o+Number(n)}}function at(t,{token:e,telegramUserId:r,now:o=Date.now()}={}){let n=t||W(),i=String(e||"").trim(),s=String(r||"").trim();if(!Qe.test(i))return{ok:!1,error:"invalid start token"};if(!Je.test(s))return{ok:!1,error:"invalid telegram user"};let l=tt(i),d=n.links[l];return d?(delete n.links[l],Number(d.expiresAt)<=o?{ok:!1,error:"start token expired"}:String(d.ownerId)!==s?{ok:!1,error:"start token is bound to a different owner"}:{ok:!0,ownerId:s}):{ok:!1,error:"unknown or already used start token"}}function Lr(t,e,{now:r,prepareLp:o=ze}={}){let n=Ye[e],i=t.payload?.lp&&typeof t.payload.lp=="object"?t.payload.lp:{},s=i[n]&&typeof i[n]=="object"?i[n]:null,l={artifactId:t.id,action:e,lpKind:n,unsigned:!0,broadcast:!1};if(!s||i.chainId==null)return{...l,envelope:null,reason:`artifact carries no ${n} params; desk must gather them`};try{let d=o({chainId:i.chainId,kind:n,params:s,deadlineSec:i.deadlineSec??300,from:i.owner??s.owner??s.recipient},{nowSeconds:Math.floor(Number(r)/1e3),nowMs:r});return{...l,envelope:d,reason:null}}catch(d){return{...l,envelope:null,reason:String(d?.message||d)}}}function oe(t){let e=String(t||"");return e.length>=12?`${e.slice(0,6)}\u2026${e.slice(-4)}`:e}function ct(t,{data:e,chatId:r,grant:o=null,now:n=Date.now(),prepareLp:i,guest:s=!1,followStore:l=null,bagReader:d=null}={}){let c=Nr(e);if(!c)return null;if(!$r.has(c.action))return{text:"That card action is not available.",buttons:null};let u=t?.artifacts?.[c.artifactId];if(!u)return{text:"That artifact is gone. Ask again and I will issue a new card.",buttons:null};if(r&&ye(t,{chatId:r,artifactId:u.id,now:n}),c.action==="follow"||c.action==="bag"){if(s)return{text:"Owner only.",buttons:null,prompt:null};let p=String(u.wallet||"").toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(p))return{text:"No wallet on this card.",buttons:null,prompt:null};if(c.action==="follow"){if(!l||typeof l.add!="function")return{text:"Follow list is not available here.",buttons:null,prompt:null};let y=l.add({address:p,chainId:u.chainId??null,label:u.walletLabel??null,source:"tap"});return y.added?{text:`Following ${oe(p)}. Alerts on its buys and sells from now.`,buttons:null,prompt:null,follow:y}:y.reason==="already-following"?{text:`Already following ${oe(p)}.`,buttons:null,prompt:null,follow:y}:{text:`Not following ${oe(p)}: ${y.reason}.`,buttons:null,prompt:null,follow:y}}return typeof d!="function"?{text:"Bag is not available here.",buttons:null,prompt:null}:{text:`Reading bag for ${oe(p)}\u2026`,buttons:null,prompt:null,bag:d({chainId:u.chainId??null,address:p})}}let f=Y({grant:o},{now:n}),h=nt(u,f.allowed);if(c.action==="refresh")return{text:ot(u),buttons:h,prompt:null};if(c.action==="deepen")return{text:null,buttons:null,prompt:`Deepen artifact ${u.id} (${u.kind}). Prior: ${u.summary||u.title}. Be terse. Do not sign or broadcast.`};if(c.action==="ta")return{text:null,buttons:null,prompt:`TA artifact ${u.id}. Prior: ${u.summary||u.title}. Run deterministic TA on the coin/venue in the artifact (RSI divergence, S/R, candle patterns). Reply in this Telegram chat with the verdict rows and say what was drawn. Do not sign or broadcast.`};if(c.action==="fa")return{text:null,buttons:null,prompt:`FA artifact ${u.id}. Prior: ${u.summary||u.title}. Run per-coin FA (funding, OI, book, premium) plus the separate MACRO thesis (M1/M2/Fed BS/net liquidity) if relevant. Cite receipts. Stay in this Telegram chat. Do not sign or broadcast.`};if(c.action==="allow")return{text:"Allow is the graph. Open the ticket there and CONFIRM. Telegram did not send.",buttons:null,prompt:null};if(c.action==="deny")return{text:`Denied ${u.id}. Ticket cancelled. Nothing signed.`,buttons:null,prompt:null};if(c.action==="long"||c.action==="short")return{text:null,buttons:null,prompt:`Open the live graph ticket for a ${c.action} on artifact ${u.id}. Prior: ${u.summary||u.title}. Size from the connected HL account. Execute only on CONFIRM on the graph. Never sign from Telegram.`};let b=c.action==="prepare"?"Prepare":c.action[0].toUpperCase()+c.action.slice(1);if(!f.allowed)return{text:`${b} blocked \u2014 ${f.reason}. Deepen and Refresh still work.`,buttons:h,prompt:null};if(c.action in Ye){let p=Lr(u,c.action,{now:n,prepareLp:i});return{text:p.envelope?`Queued unsigned ${p.lpKind} for LP ${u.id} (${p.envelope.plan.actions.join("+")}, one modifyLiquidities). Nothing signed. Sign in your wallet.`:`${b} for ${u.id} needs inputs \u2014 ${p.reason}. Nothing signed.`,buttons:h,prompt:null,prepare:p}}return{text:`Queued unsigned prepare for ${u.id}. Nothing signed. Allow/Deny still required.`,buttons:h,prompt:null,prepare:{artifactId:u.id,unsigned:!0,broadcast:!1}}}function ut(t={},{grant:e=null,now:r=Date.now(),state:o}={}){let n=o||ge(),i=String(t.id||`art-${Math.abs(Number(r)).toString(36)}`).toLowerCase().slice(0,40),s=Pr(n,{...t,id:i},{now:r}),l=Y({grant:e},{now:r});return{text:ot({...s,grant:e}),replyMarkup:nt(s,l.allowed).replyMarkup,artifact:s,state:n}}var lt=`oracle telegram \u2014 TrueNorth-style interactive cards (native, no Hermes)
|