@oracle-agent/oracle 0.35.54 → 0.35.56
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/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
- package/dist/bin/desk-server.mjs +1 -1
- package/dist/cli/commands/chat.mjs +221 -221
- package/dist/cli/commands/data.mjs +1 -1
- package/dist/cli/commands/doctor.mjs +5 -5
- package/dist/cli/commands/eval.mjs +150 -150
- package/dist/cli/commands/farm.mjs +16 -16
- package/dist/cli/commands/model.mjs +223 -223
- package/dist/cli/commands/quickstart.mjs +6 -6
- package/dist/cli/commands/sign.mjs +14 -14
- package/dist/cli/commands/signer.mjs +32 -25
- package/dist/cli/commands/venues.mjs +2 -2
- package/dist/data/desk-data.mjs +22 -22
- package/dist/data/providers/farming.mjs +2 -2
- package/dist/index.mjs +34 -34
- package/dist/local-signer/anvil-attestation-worker.mjs +1 -1
- package/dist/local-signer/index.mjs +5 -5
- package/dist/local-signer/runtime.mjs +21 -22
- package/dist/teams/index.mjs +7 -7
- package/dist/tui/standalone-client.mjs +102 -102
- package/package.json +1 -1
- 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 +3 -3
- package/public/oracle-splash/downloads/index.html +1 -1
- package/public/oracle-splash/index.html +6 -6
- package/server.json +2 -2
package/dist/bin/desk-server.mjs
CHANGED
|
@@ -5,7 +5,7 @@ ${t}
|
|
|
5
5
|
${JSON.stringify(n??[])}`}async function cA(e,t,n){return A(e,{method:"POST",body:t,fetchImpl:n.fetchImpl,timeoutMs:n.timeoutMs??12e3,signal:n.signal})}async function lA(e,t,n={}){if(!Array.isArray(t)||t.length===0)throw new Error("rpcBatch requires a non-empty calls array");if(t.length>oA)throw new Error(`rpcBatch: at most ${oA} calls`);for(let i of t)sA(i?.method);let r=Fd(e,n);if(!r)throw new Error(`No RPC URL for chainId ${e} (set env from chain registry rpcEnv or pass rpcUrl)`);let o=t.map((i,s)=>({jsonrpc:"2.0",id:s+1,method:i.method,params:i.params||[]}));try{let i=await cA(r,o,n);if(Array.isArray(i)&&i.length===t.length){let s=new Map(i.map(a=>[Number(a?.id),a]));return t.map((a,c)=>aA(s.get(c+1)??i[c]))}}catch{}return Promise.all(t.map(i=>ee(e,i.method,i.params||[],n)))}async function ee(e,t,n=[],r={}){let o=String(t||""),i=sA(o),s=Fd(e,r);if(!s)throw new Error(`No RPC URL for chainId ${e} (set env from chain registry rpcEnv or pass rpcUrl)`);if(i==="eth_chainid"&&r.cacheChainId!==!1){let u=iA.get(s);if(u!=null)return u}let c=r.dedupe!==!1&&!r.signal?fj(s,o,n):null;if(c&&vc.has(c))return vc.get(c);let l=(async()=>{let u=await cA(s,{jsonrpc:"2.0",id:1,method:t,params:n},r),d=aA(u);return i==="eth_chainid"&&typeof d=="string"&&iA.set(s,d),d})();return c&&(vc.set(c,l),l.finally(()=>{vc.get(c)===l&&vc.delete(c)}).catch(()=>{})),l}async function As(e,t={}){let[n,r]=await lA(e,[{method:"eth_blockNumber",params:[]},{method:"eth_chainId",params:[]}],t),o=parseInt(n,16),i=parseInt(r,16);return{ok:Number.isFinite(o)&&i===Number(e),chainId:Number(e),reportedChainId:i,blockNumber:o,name:Ec(e)?.name||null}}async function xc(e,t={}){let n=await ee(e,"eth_blockNumber",[],t);return parseInt(n,16)}async function Og(e,t={}){let n=await ee(e,"eth_chainId",[],t);return parseInt(n,16)}async function Tg(e,t={}){let n=await ee(e,"eth_gasPrice",[],t);if(n==null)return null;try{return BigInt(n)}catch{return null}}async function Ei(e,t,n={}){if(!t)throw new Error("rpcGetBalance requires address");let r=await ee(e,"eth_getBalance",[t,"latest"],n);return{chainId:Number(e),address:t,balanceWei:BigInt(r).toString(),balanceHex:r}}async function Ng(e={},t={}){let n=Number(e.chainId??t.chainId??1),r=So(e.token||e.tokenAddress,"token"),o=So(e.owner,"owner"),i=So(e.spender,"spender"),s=Ud.encodeFunctionData("allowance",[o,i]),a=await ee(n,"eth_call",[{to:r,data:s},e.blockTag||"latest"],t),c=Ud.decodeFunctionResult("allowance",a),l=BigInt(c[0]);return{chainId:n,token:r,owner:o,spender:i,allowance:l.toString(),allowanceHex:`0x${l.toString(16)}`,blockTag:e.blockTag||"latest"}}async function kc(e={},t={}){let n=Number(e.chainId??t.chainId??1),r=So(e.token||e.tokenAddress,"token"),o=So(e.account||e.owner||e.address,"account"),i=Ud.encodeFunctionData("balanceOf",[o]),s=await ee(n,"eth_call",[{to:r,data:i},e.blockTag||"latest"],t),a=Ud.decodeFunctionResult("balanceOf",s),c=BigInt(a[0]);return{chainId:n,token:r,account:o,balance:c.toString(),balanceHex:`0x${c.toString(16)}`,blockTag:e.blockTag||"latest"}}async function Ac(e={},t={}){let n=Number(e.chainId??t.chainId??1),r=uj(e.txHash||e.hash||e.transactionHash),o=await ee(n,"eth_getTransactionReceipt",[r],t);if(!o)return{ok:!1,chainId:n,txHash:r,status:"pending",receipt:null,reason:"receipt pending"};let i=Ig(o.status),s=i===1,a=i===1?"success":i===0?"reverted":"unknown",c=s?null:a==="reverted"?"transaction reverted":"unknown receipt status",l=e.expectedTo?So(e.expectedTo,"expectedTo"):null,u=o.to?So(o.to,"receipt.to"):null;return l&&u!==l&&(s=!1,c=`to mismatch: expected ${l}, got ${u||"null"}`),{ok:s,chainId:n,txHash:r,status:a,reason:c,statusCode:i,to:u,from:o.from?So(o.from,"receipt.from"):null,blockNumber:Ig(o.blockNumber),transactionIndex:Ig(o.transactionIndex),logs:Array.isArray(o.logs)?o.logs:[],receipt:o}}async function Pg(e={}){let t=e.chainIds||Object.values(Sc).map(r=>r.chainId),n={};return await Promise.all(t.map(async r=>{if(!rA(r)&&!_g[r]&&!Fd(r,e)){n[r]={ok:!1,error:"no rpc configured",chainId:r};return}try{n[r]=await As(r,e)}catch(o){n[r]={ok:!1,chainId:r,error:String(o.message||o)}}})),n}var Ud,_g,dj,oA,vc,iA,De=Y(()=>{V();Si();Ud=new cj(["function allowance(address owner,address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);_g={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"};dj=/^(?:eth_(?:call|blocknumber|chainid|get[a-z0-9]+|feehistory|gasprice|maxpriorityfeepergas|syncing|protocolversion|estimategas|createaccesslist)|net_(?:version|listening|peercount)|web3_(?:clientversion|sha3))$/;oA=32,vc=new Map,iA=new Map});function uA(e,t){let n=String(e||"").toLowerCase(),r=String(t?.quote||t?.quoteToken?.address||"").toLowerCase(),o=String(t?.base||t?.baseToken?.address||"").toLowerCase();return r===n?{address:t.base||t.baseToken?.address,symbol:t.baseToken?.symbol}:o===n?{address:t.quote||t.quoteToken?.address,symbol:t.quoteToken?.symbol}:{address:t.quote||t.quoteToken?.address,symbol:t.quoteToken?.symbol}}function Cg(e,t=[],{stables:n=[],wrappedNative:r=null}={}){let o=String(e||"").toLowerCase(),i=new Set((n||[]).map(c=>String(c).toLowerCase())),s=String(r||"").toLowerCase(),a=(t||[]).map((c,l)=>{let u=uA(o,c),d=String(u.address||"").toLowerCase(),p=String(u.symbol||"").toLowerCase(),f=Number(c.liquidityUsd??c.liquidity?.usd),m=Number.isFinite(f)?f:0,h=String(c.dex||c.dexId||"").toLowerCase(),g=0;return i.has(d)||mj.has(p)?g=300:s&&d===s&&(g=100),h.includes("v4")?g+=20:h.includes("v3")?g+=10:(h.includes("v2")||h.includes("raydium")||h.includes("orca")||h.includes("meteora"))&&(g+=8),{pool:c,score:g*1e12+m,index:l,otherAddr:d,liquidityUsd:m}});return a.sort((c,l)=>l.score-c.score||c.index-l.index),a.map(c=>c.pool)}function dA(e,t=[]){let n=Array.isArray(t)?t:[];return n.length&&uA(e,n[0]).address||null}var mj,Rg=Y(()=>{mj=new Set(["usdc","usdt","usdg","dai","usd1","usde","pyusd"])});function mA(e,t,n){let r=mt(t),o=mt(n),i=mt(e?.baseToken?.address),s=mt(e?.quoteToken?.address);return i===r&&s===o||i===o&&s===r}function hA(e){let t=Number(e?.liquidity?.usd);return Number.isFinite(t)&&t>=0?t:null}function gj(e,t,n){let r=mt(e?.baseToken?.address)===mt(t),o=r?e?.baseToken:e?.quoteToken,i=r?e?.quoteToken:e?.baseToken,s=a=>({address:a?.address??null,name:a?.name??null,symbol:a?.symbol??null});return Object.freeze({chainSlug:e?.chainId??null,dexId:e?.dexId??null,poolAddress:e?.pairAddress??null,url:e?.url??null,labels:Object.freeze([...e?.labels??[]]),token0:Object.freeze(s(o)),token1:Object.freeze(s(i)),priceNative:e?.priceNative??null,priceUsd:e?.priceUsd??null,txns:e?.txns??null,volume:e?.volume??null,priceChange:e?.priceChange??null,liquidity:e?.liquidity??null,liquidityUsd:hA(e),fdv:pA(e?.fdv),marketCap:pA(e?.marketCap),pairCreatedAt:e?.pairCreatedAt??null,info:e?.info??null,boosts:e?.boosts??null})}function gA(e={}){return(e.baseUrl||process.env.DEXSCREENER_API_URL||Lg).replace(/\/$/,"")}function vi(e,t){if(typeof e!="string"&&typeof e!="number")throw new Error(`${t} required`);let n=String(e).trim();if(!n||n.length>128||!/^[A-Za-z0-9][A-Za-z0-9._:+~-]*$/u.test(n))throw new Error(`${t} must be a valid path component of at most 128 characters`);return encodeURIComponent(n)}function yj(e){if(typeof e!="string")throw new Error("query required");let t=e.trim();if(!t||t.length>200||/[\u0000-\u001f\u007f]/u.test(t))throw new Error("query must contain 1 to 200 printable characters");return t}function jd(e=Is,t=Is){if(!Number.isInteger(e)||e<1||e>t)throw new Error(`limit must be an integer from 1 to ${t}`);return e}function Nr(e,t){return A(`${gA(t)}${e}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3})}function Hd(e,t){let r=(Array.isArray(e)?e:e==null?[]:[e]).slice(0,t);return Object.freeze({items:Object.freeze(r),count:r.length,limit:t})}function yA(e){let t=Array.isArray(e)?e:Array.isArray(e?.pairs)?e.pairs:[];return Object.freeze({schemaVersion:e&&!Array.isArray(e)?e.schemaVersion??null:null,pairs:Object.freeze(t),count:t.length})}async function bA(e={}){let n=(await A(`${gA(e)}/latest/dex/search?q=USDC`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3}))?.pairs?.length||0;return{ok:n>0,pairSample:n}}async function pr(e,t={}){return Nr(`/latest/dex/tokens/${vi(e,"tokenAddress")}`,t)}async function _c(e,t={}){return Nr(`/latest/dex/search?q=${encodeURIComponent(yj(e))}`,t)}async function wA(e,t,n={}){return Nr(`/latest/dex/pairs/${vi(e,"chainId")}/${vi(t,"pairAddress")}`,n)}async function SA({limit:e=Is}={},t={}){let n=jd(e);return Hd(await Nr("/token-profiles/latest/v1",t),n)}async function EA({limit:e=Is}={},t={}){let n=jd(e);return Hd(await Nr("/community-takeovers/latest/v1",t),n)}async function vA({limit:e=Is}={},t={}){let n=jd(e);return Hd(await Nr("/token-boosts/latest/v1",t),n)}async function xA({limit:e=Is}={},t={}){let n=jd(e);return Hd(await Nr("/token-boosts/top/v1",t),n)}async function kA({chainId:e,tokenAddress:t}={},n={}){let r=await Nr(`/token-pairs/v1/${vi(e,"chainId")}/${vi(t,"tokenAddress")}`,n);return yA(r)}async function AA({chainId:e,tokenAddresses:t}={},n={}){let r=Array.isArray(t)?t:typeof t=="string"?t.split(","):[];if(r.length<1||r.length>Ic)throw new Error(`tokenAddresses must contain 1 to ${Ic} addresses`);let o=r.map(s=>vi(s,"tokenAddress")).join(","),i=await Nr(`/tokens/v1/${vi(e,"chainId")}/${o}`,n);return yA(i)}async function IA({chainId:e,tokenA:t,tokenB:n,dexIds:r=[]}={},o={}){return(await Oc({chainId:e,tokenA:t,tokenB:n,dexIds:r},o))[0]??null}async function Oc({chainId:e,tokenA:t,tokenB:n,dexIds:r=[]}={},o={}){if(e==null||!t||!n)throw new Error("chainId, tokenA, and tokenB required");let i=mt(hj[Number(e)]||e),s=new Set(fA(r).filter(Boolean).map(mt)),a=[...new Set([t,n].map(p=>String(p)).filter(Boolean))],c=await Promise.allSettled(a.map(p=>pr(p,{...o,baseUrl:o.dexscreenerBaseUrl,timeoutMs:o.dexscreenerTimeoutMs??Math.min(Number(o.timeoutMs??4e3),4e3)}))),l=new Set,u=[];for(let p of c)if(p.status==="fulfilled")for(let f of p.value?.pairs||p.value?.data?.pairs||[]){let m=`${mt(f?.chainId)}:${mt(f?.dexId)}:${mt(f?.pairAddress)}`;l.has(m)||(l.add(m),u.push(f))}return u.filter(p=>mt(p?.chainId)===i).filter(p=>mA(p,t,n)).filter(p=>!s.size||s.has(mt(p?.dexId))).map(p=>({pairAddress:p.pairAddress??null,dexId:p.dexId??null,chainId:p.chainId??null,liquidityUsd:hA(p),pairCreatedAt:p.pairCreatedAt??null})).filter(p=>p.liquidityUsd!=null).sort((p,f)=>f.liquidityUsd-p.liquidityUsd)}async function _A({chainSlug:e,token0:t,token1:n,limit:r=10,dexIds:o=[]}={},i={}){if(!e||!t||!n)throw new Error("dexscreenerExactPairPools: chainSlug, token0, and token1 required");if(!Number.isInteger(r)||r<1||r>10)throw new Error("dexscreenerExactPairPools: limit must be an integer from 1 to 10");let s=new Set(fA(o).filter(Boolean).map(mt)),a=await Promise.allSettled([t,n].map(u=>pr(u,{...i,baseUrl:i.dexscreenerBaseUrl??i.baseUrl,timeoutMs:i.dexscreenerTimeoutMs??i.timeoutMs??12e3}))),c=new Set,l=[];for(let u of a)if(u.status==="fulfilled")for(let d of u.value?.pairs??u.value?.data?.pairs??[]){if(mt(d?.chainId)!==mt(e)||!mA(d,t,n)||s.size&&!s.has(mt(d?.dexId)))continue;let p=`${mt(d?.chainId)}:${mt(d?.pairAddress)}`;c.has(p)||(c.add(p),l.push(gj(d,t,n)))}return l.sort((u,d)=>(d.liquidityUsd??-1)-(u.liquidityUsd??-1)||String(u.poolAddress).localeCompare(String(d.poolAddress))).slice(0,r)}var Lg,hj,mt,fA,pA,Is,Ic,Pr=Y(()=>{V();Rg();Lg="https://api.dexscreener.com",hj=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avalanche",999:"hyperevm",4663:"robinhood"}),mt=e=>String(e??"").toLowerCase(),fA=e=>Array.isArray(e)?e:e==null?[]:[e];pA=e=>{if(e==null||e==="")return null;let t=Number(e);return Number.isFinite(t)?t:null};Is=100,Ic=30});import{readFileSync as wj}from"node:fs";import{homedir as Sj}from"node:os";import{join as zd}from"node:path";function Ej(){if(process.env.ORACLE_TEST_ISOLATE_SECRETS==="1"){let n=(process.env.ORACLE_EXEC_ENV_FILE||"").trim();return n?[n]:[]}let e=(process.env.ORACLE_EXEC_ENV_FILE||process.env.MAD_EXEC_ENV_FILE||"").trim(),t=Sj();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let n=(process.env.ORACLE_CONFIG_DIR||zd(t,".config","oracle")).trim();return[e,zd(n,"exec.env")].filter(Boolean)}return[e,zd(t,".config","oracle","exec.env"),zd(t,".config","mad-desk","exec.env")].filter(Boolean)}function OA(e,t,n){let r=e??process.env[t]??process.env[n];if(!String(r||"").trim())for(let o of Ej())try{let i=wj(o,"utf8"),s=i.match(new RegExp(`^${t}=(.*)$`,"m"))||i.match(new RegExp(`^${n}=(.*)$`,"m"));if(s&&(r=s[1].trim(),r))break}catch{}if(!String(r||"").trim())throw new Error(`${t} required for attestation. Set it in the environment, or place ${t}=<value> in ~/.config/oracle/exec.env`);return r}var TA=Y(()=>{});var NA=Y(()=>{});import{createHash as vj,createHmac as CA,timingSafeEqual as xj}from"node:crypto";function Wd(e){return Array.isArray(e)?`[${e.map(Wd).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Wd(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function RA(e,{required:t=!1}={}){try{return OA(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(n){if(t)throw n;return null}}function Mg(e){let{signature:t,...n}=e;return n}function LA(e,{secret:t}={}){let n=RA(t);return n?{...e,signature:CA("sha256",n).update(Wd(Mg(e))).digest("hex")}:e}function kj(e){let t=String(e||"").toLowerCase();if(!/^0x[0-9a-f]+$/.test(t)||t.length<10||t.length%2!==0)throw new Error("auto-slippage calldata must be even-length hex with a selector");return vj("sha256").update(Buffer.from(t.slice(2),"hex")).digest("hex")}function Ye(e,{chainId:t,venue:n,data:r,secret:o}={}){if(!e||e.mode!=="auto")throw new Error("bounded auto-slippage guard required");if(Number(e.chainId)!==Number(t))throw new Error("auto-slippage guard chain mismatch");if(String(e.venue).toLowerCase()!==String(n||"").toLowerCase())throw new Error("auto-slippage guard venue mismatch");let i=RA(o);if(i){let f=CA("sha256",i).update(Wd(Mg(e))).digest("hex");if(!Aj(e.signature,f))throw new Error("auto-slippage guard signature mismatch \u2014 refusing to bind a guard this Oracle did not issue")}let s=Number(e.selectedBps),a=Number(e.capBps);if(!Number.isInteger(s)||s<0||s>Vd||!Number.isInteger(a)||a<0||a>Vd||s>a)throw new Error("auto-slippage guard bounds are invalid");let c=BigInt(e.quoteAmountOut??0),l=BigInt(e.minAmountOut??0);if(c<=0n||l<=0n)throw new Error("auto-slippage guard amounts must be positive");let u=c*BigInt(1e4-s),d=u/10000n;if(u%10000n!==0n&&(d+=1n),l<d)throw new Error("auto-slippage guard is under-protected relative to its quote");let p=_j(r);if(p!=null&&p!==l)throw new Error(`auto-slippage: calldata encodes floor ${p}, not the guard floor ${l} \u2014 refusing to bind`);return LA({...Mg(e),calldataHash:kj(r)},{secret:o})}function Aj(e,t){let n=Buffer.from(String(e??""),"utf8"),r=Buffer.from(String(t??""),"utf8");return n.length!==r.length||n.length===0?!1:xj(n,r)}function $g(e,t=0){let n=Number(e);return Number.isFinite(n)?n:t}function Ij(e){let t=e==null?Vd:Number(e);if(!Number.isInteger(t)||t<0)throw new Error("auto-slippage cap must be a non-negative integer bps value");return Math.min(t,Vd)}function nn({liquidityUsd:e,priceChange5m:t=0,quoteAgeMs:n=0,crossChain:r=!1,requestedCapBps:o}={}){let i=$g(e,0),s=i>0?i>=25e4?5:i>=1e5?10:i>=5e4?20:i>=1e4?40:70:r?30:10,a=Math.min(60,Math.abs($g(t,0))*2),c=Math.min(40,Math.floor(Math.max(0,$g(n,0))/5e3)*5),l=Math.max(25,Math.ceil(20+s+a+c)),u=Ij(o);return{mode:"auto",requiredBps:l,selectedBps:Math.min(l,u),capBps:u,executable:l<=u}}function Bg({chainId:e,venue:t,quoteAmountOut:n,liquidityUsd:r,priceChange5m:o=0,quoteAgeMs:i=0,crossChain:s=!1,requestedCapBps:a,quotedAtMs:c=Date.now(),ttlMs:l=PA,secret:u}={}){let d=BigInt(n??0);if(d<=0n)throw new Error("auto-slippage guard requires positive quoteAmountOut");let p=nn({liquidityUsd:r,priceChange5m:o,quoteAgeMs:i,crossChain:s,requestedCapBps:a});if(!p.executable)throw new Error(`auto-slippage requires ${p.requiredBps} bps above hard/requested cap ${p.capBps}; route blocked`);let f=Number(c);if(!Number.isFinite(f))throw new Error("auto-slippage: quotedAtMs must be a finite number");let m=Math.min(3e4,Math.max(1e3,Number(l)||PA)),h=d*BigInt(1e4-p.selectedBps),g=h/10000n;if(h%10000n!==0n&&(g+=1n),g>d&&(g=d),d>0n&&g<=0n)throw new Error(`auto-slippage: quote ${d} is too small to express a ${p.selectedBps} bps floor without rounding to zero`);let y=Number((d-g)*10000n/(d===0n?1n:d));if(y>p.capBps)throw new Error(`auto-slippage: realised floor implies ${y} bps, above cap ${p.capBps} \u2014 refusing to issue a guard weaker than advertised`);return LA({mode:"auto",chainId:Number(e),venue:String(t||"unknown"),quoteAmountOut:d.toString(),minAmountOut:g.toString(),requiredBps:p.requiredBps,selectedBps:p.selectedBps,capBps:p.capBps,quotedAtMs:f,expiresAtMs:f+m},{secret:u})}function _j(e){let t=String(e||"");if(!/^0x[0-9a-fA-F]+$/.test(t)||t.length<10||t.length%2!==0)return null;let n=t.slice(0,10).toLowerCase(),r=[];for(let i=10;i+64<=t.length;i+=64)r.push(t.slice(i,i+64));let o=i=>r[i]==null?null:BigInt("0x"+r[i]);switch(n){case"0x414bf389":return o(6);case"0x04e45aaf":return o(5);case"0xc04b8d59":{let i=o(0);if(i==null)return null;let s=Number(i)/32;return!Number.isInteger(s)||s<0?null:o(s+4)}case"0xb858183f":{let i=o(0);if(i==null)return null;let s=Number(i)/32;return!Number.isInteger(s)||s<0?null:o(s+3)}case"0xa026383e":return o(6);case"0x38ed1739":case"0x5c11d795":return o(1);case"0x7ff36ab5":case"0xb6f9de95":return o(0);case"0x18cbafe5":case"0x791ac947":return o(1);default:return null}}function Ne(e,{chainId:t,venue:n,amountOut:r,liquidityUsd:o,priceChange5m:i,crossChain:s,requestedCapBps:a,quotedAtMs:c=Date.now(),ttlMs:l}={}){let u=Bg({chainId:t,venue:n,quoteAmountOut:r,liquidityUsd:o,priceChange5m:i,crossChain:s,requestedCapBps:a,quotedAtMs:c,ttlMs:l});return{...e,autoSlippage:u,amountOutMinimum:u.minAmountOut}}var Vd,PA,Gt=Y(()=>{TA();NA();Vd=100,PA=2e4});import{createHash as Oj,createHmac as Tj,timingSafeEqual as dfe}from"node:crypto";function Nj(e){let t=e==null||e===""?_s:Number(e);return!Number.isFinite(t)||t<0?_s:Math.min(t,Ug)}function Dg(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Dg).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${Dg(e[n])}`).join(",")}}`}function $A(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function BA(e=process.env){return $A(process.env)||$A(e)}function Pj(e){let{prepareHash:t,prepareMac:n,note:r,...o}=e||{};return o}function Cr(e){let t=Pj(e);return Oj("sha256").update(Dg(t)).digest("hex")}function DA(e,t=BA()){return t?Tj("sha256",t).update(String(e)).digest("hex"):""}function q(e,{provider:t,kind:n,env:r=process.env,nowMs:o=Date.now(),expiresAtMs:i}={}){if(!e||typeof e!="object")throw new Error("stampPrepared: payload object required");let s=Object.prototype.hasOwnProperty.call(e,"oraclePrepared");if(s&&typeof e.oraclePrepared!="boolean")throw new Error("stampPrepared: oraclePrepared must be boolean");let a={...e,provider:e.provider||t,kind:e.kind||n,requiresUserSignature:e.requiresUserSignature!==!1,signingReady:!1,broadcastReady:!1,executionReady:!1,oraclePrepared:s?e.oraclePrepared:!0};if(!a.provider)throw new Error("stampPrepared: provider required");if(!a.kind)throw new Error("stampPrepared: kind required");let c=Number(o),l=i==null?c+_s:Number(i),u=l-c;if(!Number.isSafeInteger(c)||!Number.isSafeInteger(l)||u<=0||u>Ug)throw new Error("stampPrepared: bounded preparedAt/expiresAt required");let p={...a,preparedAt:c,expiresAt:l,prepareVersion:MA},f=Cr(p),m=BA(r),h=m?DA(f,m):void 0,g={...p,prepareHash:f};return h&&(g.prepareMac=h),g}function Fg(e,{maxAgeMs:t=_s,nowMs:n=Date.now(),providers:r=null,kinds:o=null,label:i="operator"}={}){if(!e||typeof e!="object")throw new Error(`${i}: prepared envelope object required`);if(e.oraclePrepared!==!0)throw new Error(`${i}: prepared integrity envelope missing \u2014 use an @oracle-agent/oracle prepare result`);if(Number(e.prepareVersion)!==MA)throw new Error(`${i}: unsupported prepareVersion ${e.prepareVersion}`);let s=Cr(e);if(String(e.prepareHash||"")!==s)throw new Error(`${i}: prepareHash mismatch \u2014 payload was altered after prepare`);let a=Number(e.preparedAt),c=Number(e.expiresAt),l=Nj(t),u=n-a,d=c-a;if(!Number.isFinite(u)||!Number.isFinite(c)||!Number.isFinite(d)||u<0||d<=0||d>Ug||u>l||n>=c)throw new Error(`${i}: prepare envelope expired or clock-skewed (ageMs=${u}, max=${l})`);if(r&&!new Set(r).has(e.provider))throw new Error(`${i}: provider ${e.provider} not allowed here`);if(o&&!new Set(o).has(e.kind))throw new Error(`${i}: kind ${e.kind} not allowed here`);return!0}var MA,_s,Ug,ae=Y(()=>{MA=2,_s=300*1e3,Ug=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})()});var Gg={};vt(Gg,{PANCAKE_FEE_TIERS:()=>Gd,UNI_V3_CHAINS:()=>xt,UNI_V3_FEE_TIERS:()=>jA,UNI_V3_VENUES:()=>VA,uniV3Chains:()=>Wg,uniV3EthUsdc:()=>Yd,uniV3Health:()=>Vg,uniV3PrepareExactIn:()=>zg,uniV3QuoteExactIn:()=>Rr,uniV3QuoteExactInPath:()=>Hg});import{Interface as FA,getAddress as Tc,isAddress as qA}from"ethers";function jg(e,t){let n=Number(e),r=xt[n];if(!r)throw new Error(`uniswap-v3: unsupported chainId ${e} (supported: ${Object.keys(xt).join(", ")})`);let o=VA[n]||{};if(!t){if(!r.quoter||!r.router){let c=Object.keys(o).join(", ")||"none registered";throw new Error(`uniswap-v3: chain ${n} (${r.name}) has no canonical Uniswap v3 deployment -- name a venue explicitly (known: ${c})`)}return{chainId:n,venue:r.name,...r}}let i=String(t).toLowerCase();if(i===r.name&&r.quoter&&r.router)return{chainId:n,venue:r.name,...r};let s=o,a=s[i];if(!a){let c=[...r.quoter&&r.router?[r.name]:[],...Object.keys(s)].join(", ");throw new Error(`uniswap-v3: unknown venue "${t}" on chain ${n} (known: ${c})`)}return{chainId:n,venue:i,...r,quoter:a.quoter,router:a.router,feeTiers:a.feeTiers||null}}function qg(e,t){let n=xt[Number(t)];if(!e||e===HA||e===zA||/^eth$/i.test(String(e)))return Tc(n.weth);let r=String(e);if(/^weth$/i.test(r))return Tc(n.weth);if(/^usdc$/i.test(r))return Tc(n.usdc);if(!qA(r))throw new Error(`invalid token address: ${e}`);return Tc(r)}function Rj(e){let t=String(e||"uniswap").toLowerCase();return t==="uniswap"?["uniswap-v3","uniswap"]:t==="pancakeswap"?["pancakeswap-v3","pancakeswap"]:t==="hyperswap"?["hyperswap-v3","hyperswap"]:[t,`${t}-v3`]}function Lj(e,t){if(e.length!==t.length+1)throw new Error("path: fees.length must be tokens.length - 1");let n="0x";for(let r=0;r<t.length;r++)n+=e[r].slice(2).toLowerCase(),n+=Number(t[r]).toString(16).padStart(6,"0");return n+=e[e.length-1].slice(2).toLowerCase(),n}async function Rr(e={},t={}){let{chainId:n,quoter:r,router:o,feeTiers:i}=jg(e.chainId??8453,e.venue),s=qg(e.tokenIn||"WETH",n),a=qg(e.tokenOut||xt[n].usdc,n),c=BigInt(e.amountIn??0);if(c<=0n)throw new Error("amountIn required (raw base units)");let l=i&&i.length?i:jA,u=e.fee!=null?[Number(e.fee)]:e.tryFees===!1?[l[Math.min(2,l.length-1)]]:[...l],p=await Promise.all(u.map(async v=>{let k=Kd.encodeFunctionData("quoteExactInputSingle",[{tokenIn:s,tokenOut:a,amountIn:c,fee:v,sqrtPriceLimitX96:0n}]);try{let I=await ee(n,"eth_call",[{to:r,data:k},"latest"],t);if(!I||I==="0x")return{fee:v,ok:!1,error:"empty result"};let _=Kd.decodeFunctionResult("quoteExactInputSingle",I);return{fee:v,ok:!0,amountOut:_[0].toString(),sqrtPriceX96After:_[1].toString(),initializedTicksCrossed:Number(_[2]),gasEstimate:_[3].toString()}}catch(I){return{fee:v,ok:!1,error:String(I.message||I).slice(0,160)}}})),f=null;for(let v of p)v.ok&&(!f||BigInt(v.amountOut)>BigInt(f.amountOut))&&(f=v);if(!f){let v=p.map(k=>`${k.fee}:${k.error||"fail"}`).join("; ");throw new Error(`uniswap-v3 quote failed chain=${n}: ${v}`)}let m=e.liquidityUsd==null?await Oc({chainId:n,tokenA:s,tokenB:a,dexIds:Rj(e.venue)},t).catch(()=>[]):[],h={};await Promise.all(m.slice(0,8).map(async v=>{if(!(!v.pairAddress||!qA(v.pairAddress)))try{let k=await ee(n,"eth_call",[{to:v.pairAddress,data:Cj},"latest"],t),I=k&&k!=="0x"&&k.length<=66?Number.parseInt(k,16):NaN;if(!Number.isFinite(I)||I<=0||I>1e6)return;let _=h[I];(_==null||v.liquidityUsd>_.liquidityUsd)&&(h[I]=v)}catch{}}));let g=e.liquidityBandBps==null?50:Number(e.liquidityBandBps),y=null;if(e.fee==null&&g>0&&BigInt(f.amountOut)>0n){let v=BigInt(f.amountOut),I=p.filter(_=>_.ok&&Number((v-BigInt(_.amountOut))*10000n/v)<=g).filter(_=>h[_.fee]?.liquidityUsd!=null).sort((_,P)=>h[P.fee].liquidityUsd-h[_.fee].liquidityUsd)[0];I&&I.fee!==f.fee&&(y={priceBestFee:f.fee,chosenFee:I.fee,chosenPoolUsd:h[I.fee].liquidityUsd,bandBps:g},f=I)}let b=h[f.fee]??null,S=m[0]??null,w=b??S,E=e.liquidityUsd??b?.liquidityUsd??S?.liquidityUsd??null,x=e.liquidityUsd!=null?"caller":b?"pool":S?"pair":null;return Ne({venue:"uniswap-v3",chainId:n,chain:xt[n].name,quoter:r,tokenIn:s,tokenOut:a,amountIn:c.toString(),fee:f.fee,amountOut:f.amountOut,gasEstimate:f.gasEstimate,liquidityUsd:E,liquiditySource:w,liquidityAttribution:x,liquidityPick:y,sqrtPriceX96After:f.sqrtPriceX96After,initializedTicksCrossed:f.initializedTicksCrossed,triedFees:p,best:!0},{chainId:n,venue:o,amountOut:f.amountOut,liquidityUsd:E,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function Hg(e={},t={}){let{chainId:n,quoter:r,router:o}=jg(e.chainId??8453),i=(e.tokens||[]).map(p=>qg(p,n)),s=(e.fees||[]).map(Number);if(i.length<2)throw new Error("tokens[] need at least 2 addresses");let a=BigInt(e.amountIn??0);if(a<=0n)throw new Error("amountIn required");let c=Lj(i,s),l=Kd.encodeFunctionData("quoteExactInput",[c,a]),u=await ee(n,"eth_call",[{to:r,data:l},"latest"],t),d=Kd.decodeFunctionResult("quoteExactInput",u);return Ne({venue:"uniswap-v3",chainId:n,chain:xt[n].name,quoter:r,tokens:i,fees:s,path:c,amountIn:a.toString(),amountOut:d[0].toString(),gasEstimate:d[3].toString()},{chainId:n,venue:o,amountOut:d[0].toString(),liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function Yd(e={},t={}){let n=Number(e.chainId??8453),r=e.amountIn??"1000000000000000",o=await Rr({chainId:n,tokenIn:xt[n].weth,tokenOut:xt[n].usdc,amountIn:r,fee:e.fee},t),i=Number(o.amountOut)/1e6;return{...o,amountOutUsdc:i,pair:"WETH/USDC"}}async function zg(e={},t={}){let n=Number(e.chainId??8453),r=jg(n,e.venue),o=Tc(e.recipient),i=String(e.tokenIn||"WETH"),s=!e.tokenIn||i===HA||i===zA||/^eth$/i.test(i),a=await Rr(e,t),c=UA.encodeFunctionData("exactInputSingle",[{tokenIn:a.tokenIn,tokenOut:a.tokenOut,fee:a.fee,recipient:o,amountIn:BigInt(a.amountIn),amountOutMinimum:BigInt(a.amountOutMinimum),sqrtPriceLimitX96:0n}]),l=Math.min(600,Math.max(30,Number(e.deadlineSeconds??300))),d=Number(t.nowSeconds??Math.floor(Date.now()/1e3))+l,p=UA.encodeFunctionData("multicall",[d,[c]]);return q({provider:"uniswap-v3",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:n,deadline:d,quote:a,autoSlippage:a.autoSlippage,requiresApproval:s?null:{token:a.tokenIn,spender:r.router,amount:a.amountIn},transaction:{chainId:n,from:o,to:r.router,data:p,value:s?a.amountIn:"0",slippageGuard:Ye(a.autoSlippage,{chainId:n,venue:r.router,data:p})}},{provider:"uniswap-v3",kind:"univ3-swap-tx"})}async function Vg(e={}){let t=Number(e.chainId??8453);try{let n=await Yd({chainId:t,amountIn:"1000000000000000"},e);return{ok:!0,chainId:t,fee:n.fee,amountOutUsdc:n.amountOutUsdc,midPxHint:n.amountOutUsdc/.001}}catch(n){return{ok:!1,chainId:t,error:String(n.message||n).slice(0,200)}}}async function Wg(){return Object.entries(xt).map(([e,t])=>({chainId:Number(e),name:t.name,quoter:t.quoter,weth:t.weth,usdc:t.usdc}))}var xt,jA,Cj,Kd,UA,HA,zA,Gd,VA,xi=Y(()=>{De();Pr();Gt();ae();xt={1:{name:"ethereum",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",weth:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",usdc:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},8453:{name:"base",quoter:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",router:"0x2626664c2603336E57B271c5C0b26F421741e481",weth:"0x4200000000000000000000000000000000000006",usdc:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"},42161:{name:"arbitrum",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",weth:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",usdc:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"},4663:{name:"robinhood",quoter:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",router:"0xcaf681a66d020601342297493863e78c959e5cb2",weth:"0x0bd7d308f8e1639fab988df18a8011f41eacad73",usdc:"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"},999:{name:"hyperevm",weth:"0x5555555555555555555555555555555555555555",usdc:"0xB8CE59FC3717ada4C02eaDF9682A9e934F625ebb"},10:{name:"optimism",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",weth:"0x4200000000000000000000000000000000000006",usdc:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85"},56:{name:"bsc",quoter:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",router:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",weth:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",usdc:"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d"},137:{name:"polygon",quoter:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",router:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",weth:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",usdc:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"},43114:{name:"avalanche",quoter:"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F",router:"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE",weth:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",usdc:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"}},jA=[100,500,3e3,1e4],Cj="0xddca3f43",Kd=new FA(["function quoteExactInputSingle((address tokenIn, address tokenOut, uint256 amountIn, uint24 fee, uint160 sqrtPriceLimitX96) params) returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)","function quoteExactInput(bytes path, uint256 amountIn) returns (uint256 amountOut, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate)"]),UA=new FA(["function exactInputSingle((address tokenIn,address tokenOut,uint24 fee,address recipient,uint256 amountIn,uint256 amountOutMinimum,uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)","function multicall(uint256 deadline,bytes[] data) payable returns (bytes[] results)"]),HA="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",zA="0x0000000000000000000000000000000000000000",Gd=[100,500,2500,1e4],VA={56:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:Gd}},8453:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:Gd}},42161:{pancakeswap:{name:"pancakeswap",quoter:"0xB048Bbc1Ee6b733FFfCFb9e9CeF7375518e25997",router:"0x13f4EA83D0bd40E75C8222255bc855a974568Dd4",feeTiers:Gd}},999:{hyperswap:{name:"hyperswap",quoter:"0x03A918028f22D9E1473B7959C927AD7425A45C7C",router:"0x4E2960a8cd19B467b82d26D83fAcb0fAE26b094D"}}}});var iy={};vt(iy,{UNI_V4_CHAINS:()=>fn,UNI_V4_FEE_TIERS:()=>Jg,computeV4PoolId:()=>Qd,decodeV4HookPermissions:()=>Qg,uniV4Chains:()=>ry,uniV4Health:()=>oy,uniV4InspectHook:()=>ey,uniV4PrepareExactIn:()=>ny,uniV4QuoteExactIn:()=>Eo,uniV4QuoteExactOut:()=>ty});import{AbiCoder as $j,Interface as Kg,getAddress as rn,isAddress as Yg,keccak256 as GA}from"ethers";function Qg(e){let t=ki(e),n=Number(BigInt(t)&Bj),r=Object.fromEntries(WA.map(([s,a])=>[a,!!(n&1<<s)])),i=[["beforeSwapReturnsDelta","beforeSwap"],["afterSwapReturnsDelta","afterSwap"],["afterAddLiquidityReturnsDelta","afterAddLiquidity"],["afterRemoveLiquidityReturnsDelta","afterRemoveLiquidity"]].filter(([s,a])=>r[s]&&!r[a]).map(([s,a])=>`${s} requires ${a}`);return Object.freeze({address:t,mask:n,maskHex:`0x${n.toString(16).padStart(4,"0")}`,flags:Object.freeze(r),enabled:Object.freeze(WA.filter(([,s])=>r[s]).map(([,s])=>s)),valid:i.length===0,violations:Object.freeze(i)})}function Nc(e){let t=Number(e),n=fn[t];if(!n)throw new Error(`uniswap-v4: unsupported chainId ${e} (supported: ${Object.keys(fn).join(", ")})`);return{chainId:t,...n}}function ki(e){if(e==null||e==="")return Ut;let t=String(e);if(!Yg(t))throw new Error(`invalid Uniswap V4 hook address: ${e}`);return rn(t)}function Ns(e,t){let n=fn[Number(t)];if(Ts(e))return rn(Ut);let r=String(e);if(/^weth$/i.test(r))return rn(n.weth);if(/^usdc$/i.test(r)||/^usdg$/i.test(r))return rn(n.usdc);if(!Yg(r))throw new Error(`invalid token address: ${e}`);return rn(r)}function Ts(e){let t=String(e||"").trim().toLowerCase();return!t||t===qj.toLowerCase()||t===Ut.toLowerCase()||t==="eth"}function Qd({currency0:e,currency1:t,fee:n,tickSpacing:r,hooks:o=Ut}){let i=rn(e),s=rn(t);if(i.toLowerCase()===s.toLowerCase())throw new Error("poolKey currencies must differ");let[a,c]=i.toLowerCase()<s.toLowerCase()?[i,s]:[s,i],l=ki(o);return GA(Os.encode(["address","address","uint24","int24","address"],[a,c,Number(n),Number(r),l]))}function Zg({tokenIn:e,tokenOut:t,fee:n,tickSpacing:r,hooks:o=Ut}){let i=rn(e),s=rn(t),[a,c]=i.toLowerCase()<s.toLowerCase()?[i,s]:[s,i],l=i.toLowerCase()===a.toLowerCase();return{poolKey:{currency0:a,currency1:c,fee:Number(n),tickSpacing:Number(r),hooks:ki(o)},zeroForOne:l}}function jj({poolKey:e,poolId:t,tokenIn:n,tokenOut:r,fee:o,tickSpacing:i,hooks:s}){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("uniswap-v4 exact poolKey must be an object");let a=rn(e.currency0),c=rn(e.currency1);if(a.toLowerCase()>=c.toLowerCase())throw new Error("uniswap-v4 exact poolKey requires canonical currency ordering");let l=Number(e.fee),u=Number(e.tickSpacing);if(!Number.isInteger(l)||l<0||l>16777215)throw new Error("uniswap-v4 exact poolKey requires uint24 fee");if(!Number.isInteger(u)||u<-8388608||u>8388607)throw new Error("uniswap-v4 exact poolKey requires int24 tickSpacing");let d=ki(e.hooks),p={currency0:a,currency1:c,fee:l,tickSpacing:u,hooks:d},f=rn(n),m=rn(r);if(f.toLowerCase()===m.toLowerCase())throw new Error("tokenIn and tokenOut must differ");let h=new Set([a.toLowerCase(),c.toLowerCase()]);if(!h.has(f.toLowerCase())||!h.has(m.toLowerCase()))throw new Error("uniswap-v4 exact poolKey currencies do not match tokenIn/tokenOut");if(o!=null&&Number(o)!==l)throw new Error("uniswap-v4 exact poolKey fee conflicts with top-level fee");if(i!=null&&Number(i)!==u)throw new Error("uniswap-v4 exact poolKey tickSpacing conflicts with top-level tickSpacing");if(s!=null&&ki(s).toLowerCase()!==d.toLowerCase())throw new Error("uniswap-v4 exact poolKey hooks conflict with top-level hooks");let g=GA(Os.encode(["address","address","uint24","int24","address"],[a,c,l,u,d]));if(t!=null){if(!/^0x[0-9a-f]{64}$/i.test(String(t)))throw new Error("uniswap-v4 exact poolId must be bytes32");if(String(t).toLowerCase()!==g.toLowerCase())throw new Error(`uniswap-v4 exact poolId mismatch: expected ${g}`)}return{poolKey:p,poolId:g,zeroForOne:f.toLowerCase()===a.toLowerCase()}}function Hj({hook:e,codePresent:t,initialized:n,dynamicFee:r}){let o=Qg(e),i=o.enabled.some(l=>l.endsWith("ReturnsDelta")),s=o.flags.beforeSwap||o.flags.afterSwap||o.flags.beforeDonate||o.flags.afterDonate,a=[],c="none";return e!==Ut&&(c="low",a.push("nonzero hook requires independent contract review")),r&&(c="medium",a.push("pool uses a dynamic LP fee")),s&&(c="medium",a.push("hook runs during swap or donate flow")),i&&(c="high",a.push("hook can return custom accounting deltas")),o.valid||(c="critical",a.push(...o.violations)),r&&e===Ut&&(c="critical",a.push("dynamic-fee pool has no hook authority")),e!==Ut&&o.enabled.length===0&&(c="critical",a.push("nonzero hook declares no permissions")),n||(c="critical",a.push("pool is not initialized")),e!==Ut&&!t&&(c="critical",a.push("hook address has no deployed bytecode")),Object.freeze({tier:c,audited:!1,requiresReview:e!==Ut,returnsDelta:i,reasons:Object.freeze(a)})}async function ey(e={},t={}){let n=Nc(e.chainId??8453);if(!n.stateView)throw new Error(`uniswap-v4: no StateView on chain ${n.chainId}`);let r=Ns(e.tokenIn||"WETH",n.chainId),o=Ns(e.tokenOut||n.usdc,n.chainId),i=Number(e.fee),s=Number(e.tickSpacing);if(!Number.isInteger(i)||i<0||i>16777215)throw new Error("uniswap-v4 inspectHook requires uint24 fee");if(!Number.isInteger(s)||s<-8388608||s>8388607)throw new Error("uniswap-v4 inspectHook requires int24 tickSpacing");let a=ki(e.hooks),{poolKey:c}=Zg({tokenIn:r,tokenOut:o,fee:i,tickSpacing:s,hooks:a}),l=Qd(c),u=t.rpcCall||ee,d=Jd.encodeFunctionData("getSlot0",[l]),p=Jd.encodeFunctionData("getLiquidity",[l]),[f,m,h]=await Promise.all([u(n.chainId,"eth_call",[{to:n.stateView,data:d},"latest"],t),u(n.chainId,"eth_call",[{to:n.stateView,data:p},"latest"],t),a===Ut?Promise.resolve(null):u(n.chainId,"eth_getCode",[a,"latest"],t)]),g=Jd.decodeFunctionResult("getSlot0",f),y=Jd.decodeFunctionResult("getLiquidity",m)[0],b=g[0],S=b>0n,w=a===Ut?null:typeof h=="string"&&h!=="0x"&&h.length>4,E=!!(i&Xg),x=Hj({hook:a,codePresent:w,initialized:S,dynamicFee:E});return Object.freeze({venue:"uniswap-v4",chainId:n.chainId,stateView:n.stateView,poolId:l,poolKey:Object.freeze(c),pool:Object.freeze({initialized:S,sqrtPriceX96:b.toString(),tick:Number(g[1]),protocolFee:Number(g[2]),lpFee:Number(g[3]),liquidity:y.toString(),dynamicFee:E}),hook:Object.freeze({address:a,codePresent:w,codeBytes:w?(h.length-2)/2:0,permissions:Qg(a)}),risk:x})}async function Eo(e={},t={}){let{chainId:n,quoter:r,poolManager:o,universalRouter:i}=Nc(e.chainId??8453),s=Ns(e.tokenIn||"WETH",n),a=Ns(e.tokenOut||fn[n].usdc,n),c=BigInt(e.amountIn??0);if(c<=0n)throw new Error("amountIn required (raw base units)");if(c>0xffffffffffffffffffffffffffffffffn)throw new Error("amountIn exceeds uint128");let l=e.poolKey==null?null:jj({poolKey:e.poolKey,poolId:e.poolId,tokenIn:s,tokenOut:a,fee:e.fee,tickSpacing:e.tickSpacing,hooks:e.hooks}),u=l?[{fee:l.poolKey.fee,tickSpacing:l.poolKey.tickSpacing}]:e.fee!=null&&e.tickSpacing!=null?[{fee:Number(e.fee),tickSpacing:Number(e.tickSpacing)}]:e.tryTiers===!1?[{fee:500,tickSpacing:10}]:[...Jg],d=l?l.poolKey.hooks:e.hooks||Ut,f=await Promise.all(u.map(async I=>{let _=l||Zg({tokenIn:s,tokenOut:a,fee:I.fee,tickSpacing:I.tickSpacing,hooks:d}),{poolKey:P,zeroForOne:O}=_,F=Xd.encodeFunctionData("quoteExactInputSingle",[{poolKey:P,zeroForOne:O,exactAmount:c,hookData:"0x"}]);try{let M=await(t.rpcCall||ee)(n,"eth_call",[{to:r,data:F},"latest"],t);if(!M||M==="0x")return{...I,ok:!1,error:"empty result"};let $=Xd.decodeFunctionResult("quoteExactInputSingle",M);return{fee:I.fee,tickSpacing:I.tickSpacing,ok:!0,amountOut:$[0].toString(),gasEstimate:$[1].toString(),poolKey:P,zeroForOne:O,poolId:_.poolId||Qd({...P})}}catch(M){return{...I,ok:!1,error:String(M.message||M).slice(0,160)}}})),m=null;for(let I of f)I.ok&&(!m||BigInt(I.amountOut)>BigInt(m.amountOut))&&(m=I);if(!m){let I=f.map(_=>`${_.fee}/${_.tickSpacing}:${_.error||"fail"}`).join("; ");throw new Error(`uniswap-v4 quote failed chain=${n}: ${I}`)}let h=e.liquidityUsd==null?await Oc({chainId:n,tokenA:s,tokenB:a,dexIds:KA},t).catch(()=>[]):[],g=new Map;for(let I of h){let _=String(I.pairAddress||"").toLowerCase();_&&g.set(_,I)}let y=I=>g.get(String(I.poolId||"").toLowerCase())??null,b=e.liquidityBandBps==null?50:Number(e.liquidityBandBps),S=null;if(!l&&!(e.fee!=null&&e.tickSpacing!=null)&&b>0&&BigInt(m.amountOut)>0n){let I=BigInt(m.amountOut),P=f.filter(O=>O.ok&&Number((I-BigInt(O.amountOut))*10000n/I)<=b).filter(O=>y(O)?.liquidityUsd!=null).sort((O,F)=>y(F).liquidityUsd-y(O).liquidityUsd)[0];P&&P.poolId!==m.poolId&&(S={priceBestFee:m.fee,chosenFee:P.fee,chosenPoolUsd:y(P).liquidityUsd,bandBps:b},m=P)}let w=y(m),E=h[0]??null,x=w??E,v=e.liquidityUsd??w?.liquidityUsd??E?.liquidityUsd??null,k=e.liquidityUsd!=null?"caller":w?"pool":E?"pair":null;return Ne({venue:"uniswap-v4",chainId:n,chain:fn[n].name,poolManager:o,quoter:r,universalRouter:i||null,tokenIn:s,tokenOut:a,amountIn:c.toString(),fee:m.fee,tickSpacing:m.tickSpacing,hooks:m.poolKey.hooks,poolId:m.poolId,poolKey:Object.freeze({...m.poolKey}),zeroForOne:m.zeroForOne,amountOut:m.amountOut,gasEstimate:m.gasEstimate,liquidityUsd:v,liquiditySource:x,liquidityAttribution:k,liquidityPick:S,triedTiers:f,best:!0,executionReady:!1,prepareReady:typeof e.recipient=="string"&&Yg(e.recipient)&&Number.isInteger(Number(e.slippageBps))&&Number(e.slippageBps)>=0&&Number(e.slippageBps)<=100&&Number.isInteger(Number(e.deadlineSeconds))&&Number(e.deadlineSeconds)>=30&&Number(e.deadlineSeconds)<=600&&!Ts(e.tokenIn)&&!Ts(e.tokenOut)&&(e.hookData==null||String(e.hookData).toLowerCase()==="0x")&&m.poolKey.hooks===Ut&&!(m.fee&Xg)},{chainId:n,venue:i||r,amountOut:m.amountOut,liquidityUsd:v,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function ty(e={},t={}){let{chainId:n,quoter:r,poolManager:o,universalRouter:i}=Nc(e.chainId??8453),s=Ns(e.tokenIn||"WETH",n),a=Ns(e.tokenOut||fn[n].usdc,n),c=BigInt(e.amountOut??0);if(c<=0n)throw new Error("amountOut required (raw base units)");if(c>0xffffffffffffffffffffffffffffffffn)throw new Error("amountOut exceeds uint128");let l=e.fee!=null&&e.tickSpacing!=null?[{fee:Number(e.fee),tickSpacing:Number(e.tickSpacing)}]:e.tryTiers===!1?[{fee:500,tickSpacing:10}]:[...Jg],u=e.hooks||Ut,p=await Promise.all(l.map(async h=>{let{poolKey:g,zeroForOne:y}=Zg({tokenIn:s,tokenOut:a,fee:h.fee,tickSpacing:h.tickSpacing,hooks:u}),b=Xd.encodeFunctionData("quoteExactOutputSingle",[{poolKey:g,zeroForOne:y,exactAmount:c,hookData:"0x"}]);try{let S=await(t.rpcCall||ee)(n,"eth_call",[{to:r,data:b},"latest"],t);if(!S||S==="0x")return{...h,ok:!1,error:"empty result"};let w=Xd.decodeFunctionResult("quoteExactOutputSingle",S);return{fee:h.fee,tickSpacing:h.tickSpacing,ok:!0,amountIn:w[0].toString(),gasEstimate:w[1].toString(),poolKey:g,zeroForOne:y,poolId:Qd({...g})}}catch(S){return{...h,ok:!1,error:String(S.message||S).slice(0,160)}}})),f=null;for(let h of p)h.ok&&(!f||BigInt(h.amountIn)<BigInt(f.amountIn))&&(f=h);if(!f){let h=p.map(g=>`${g.fee}/${g.tickSpacing}:${g.error||"fail"}`).join("; ");throw new Error(`uniswap-v4 exact-output quote failed chain=${n}: ${h}`)}let m=e.liquidityUsd==null?await IA({chainId:n,tokenA:s,tokenB:a,dexIds:KA},t).catch(()=>null):null;return{venue:"uniswap-v4",chainId:n,chain:fn[n].name,poolManager:o,quoter:r,universalRouter:i||null,tokenIn:s,tokenOut:a,amountIn:f.amountIn,amountOut:c.toString(),gasEstimate:f.gasEstimate,fee:f.fee,tickSpacing:f.tickSpacing,hooks:f.poolKey.hooks,poolId:f.poolId,zeroForOne:f.zeroForOne,liquidityUsd:e.liquidityUsd??m?.liquidityUsd??null,liquiditySource:m,triedTiers:p,best:!0,executionReady:!1,prepareReady:!1}}async function ny(e={},t={}){if(["operation","exactOutput","amountOut","multihop","path","positionManager","modifyLiquidities","commands","actions"].some(x=>Object.hasOwn(e,x)))throw new Error("uniswap-v4 unsupported operation shape is inspect/quote-only");let r=Number(e.chainId??8453),o=Nc(r);if(ki(e.poolKey?.hooks??e.hooks)!==Ut)throw new Error("uniswap-v4 nonzero hooks are inspect/quote-only until a code-hash-specific adapter exists");if(Number(e.poolKey?.fee??e.fee)&Xg)throw new Error("uniswap-v4 dynamic-fee pools are inspect/quote-only until a code-hash-specific adapter exists");if(e.hookData!=null&&String(e.hookData).toLowerCase()!=="0x")throw new Error("uniswap-v4 opaque hookData is inspect/quote-only until a code-hash-specific adapter exists");if(!e.recipient)throw new Error("uniswap-v4 prepare requires recipient");let a=rn(e.recipient);if(e.slippageBps==null)throw new Error("uniswap-v4 prepare requires explicit slippageBps");let c=Number(e.slippageBps);if(!Number.isInteger(c)||c<0||c>100)throw new Error("slippageBps must be an integer from 0 through 100");if(e.deadlineSeconds==null)throw new Error("uniswap-v4 prepare requires explicit deadlineSeconds");let l=Number(e.deadlineSeconds);if(!Number.isInteger(l)||l<30||l>600)throw new Error("deadlineSeconds must be an integer from 30 through 600");let u=e.poolKey&&typeof e.poolKey=="object"?[e.poolKey.currency0,e.poolKey.currency1]:[];if(Ts(e.tokenIn)||Ts(e.tokenOut)||u.some(Ts))throw new Error("uniswap-v4 prepare currently requires ERC-20 tokenIn and tokenOut; native routes are not inferred");let d=await Eo(e,t);if(!o.universalRouter)throw new Error(`uniswap-v4: no Universal Router on chain ${r}`);let p=BigInt(d.amountOut)*BigInt(1e4-c)/10000n,f={currency0:d.zeroForOne?d.tokenIn:d.tokenOut,currency1:d.zeroForOne?d.tokenOut:d.tokenIn,fee:d.fee,tickSpacing:d.tickSpacing,hooks:d.hooks},h=Os.encode(["tuple(tuple(address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks) poolKey,bool zeroForOne,uint128 amountIn,uint128 amountOutMinimum,uint256 minHopPriceX36,bytes hookData)"],[[f,d.zeroForOne,BigInt(d.amountIn),p,0n,"0x"]]),g=Os.encode(["address","uint256"],[d.tokenIn,BigInt(d.amountIn)]),y=Os.encode(["address","uint256"],[d.tokenOut,p]),b=Os.encode(["bytes","bytes[]"],[Uj,[h,g,y]]),w=Number(t.nowSeconds??Math.floor(Date.now()/1e3))+l,E=Mj.encodeFunctionData("execute",[Dj,[b],w]);return q({provider:"uniswap-v4",prepareReady:!0,calldataReady:!0,executionReady:!1,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:r,deadline:w,quote:{...d,amountOutMinimum:p.toString(),slippageBps:c},hookInspection:null,requiresApproval:{token:d.tokenIn,spender:Fj,amount:d.amountIn,note:"Universal Router V4 settlement uses Permit2; Permit2 authorization for the Universal Router is also required"},transaction:{chainId:r,from:a,to:o.universalRouter,data:E,value:"0"}},{provider:"uniswap-v4",kind:"univ4-swap-tx"})}async function ry(){return Object.entries(fn).map(([e,t])=>({chainId:Number(e),name:t.name,poolManager:t.poolManager,quoter:t.quoter,stateView:t.stateView||null,universalRouter:t.universalRouter||null,weth:t.weth,usdc:t.usdc}))}async function oy(e={}){let t=Nc(e.chainId??8453),n=await ee(t.chainId,"eth_getCode",[t.quoter,"latest"],e),r=typeof n=="string"&&n!=="0x"&&n.length>4;return{ok:r,chainId:t.chainId,quoter:t.quoter,poolManager:t.poolManager,codeBytes:r?(n.length-2)/2:0}}var Os,Ut,fn,Jg,Xd,Mj,Jd,WA,Bj,Xg,Dj,Uj,Fj,qj,KA,Ps=Y(()=>{De();Pr();Gt();ae();Os=$j.defaultAbiCoder(),Ut="0x0000000000000000000000000000000000000000",fn={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"}},Jg=[{fee:100,tickSpacing:1},{fee:500,tickSpacing:10},{fee:3e3,tickSpacing:60},{fee:1e4,tickSpacing:200},{fee:25e3,tickSpacing:8}],Xd=new Kg(["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)"]),Mj=new Kg(["function execute(bytes commands,bytes[] inputs,uint256 deadline) payable"]),Jd=new Kg(["function getSlot0(bytes32 poolId) view returns (uint160 sqrtPriceX96,int24 tick,uint24 protocolFee,uint24 lpFee)","function getLiquidity(bytes32 poolId) view returns (uint128 liquidity)"]),WA=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"]]),Bj=(1n<<14n)-1n,Xg=8388608;Dj="0x10",Uj="0x060c0f",Fj="0x000000000022D473030F116dDEE9F6B43aC78BA3",qj="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";KA=["uniswap-v4","uniswapv4"]});function Zj(e={}){let t=[],n=[];if(!e||typeof e!="object")return{ok:!1,errors:["definition must be an object"],warnings:n};if((!Number.isInteger(e.chainId)||e.chainId<=0)&&t.push("chainId must be a positive integer"),(typeof e.key!="string"||!/^[a-z][a-z0-9-]*$/.test(e.key||""))&&t.push('key must be a lowercase slug (e.g. "base")'),(typeof e.name!="string"||!e.name.trim())&&t.push("name is required"),!Array.isArray(e.rpcEnv)||e.rpcEnv.length===0)t.push("rpcEnv must list at least one environment variable name");else for(let o of e.rpcEnv)(typeof o!="string"||!/^[A-Z][A-Z0-9_]*$/.test(o))&&t.push(`rpcEnv entry "${o}" should be an UPPER_SNAKE env var name`);if(e.nativeCurrency){let o=e.nativeCurrency;(typeof o.symbol!="string"||!o.symbol)&&t.push("nativeCurrency.symbol is required when nativeCurrency is set"),Number.isInteger(o.decimals)||t.push("nativeCurrency.decimals must be an integer")}for(let[o,i]of(e.venues||[]).entries()){let s=`venues[${o}]`;if(!i||typeof i!="object"){t.push(`${s} must be an object`);continue}Qj.test(i.address||"")||t.push(`${s}.address is not a valid 20-byte address`),/^0x0{40}$/.test(i.address||"")&&t.push(`${s}.address is the zero address -- placeholder left in place?`),i.kind||t.push(`${s}.kind is required (router|quoter|factory|...)`),i.verified?(i.verified.method||t.push(`${s}.verified.method is required`),i.verified.source||t.push(`${s}.verified.source is required`),i.verified.date||n.push(`${s}.verified.date missing -- add one so staleness is visible`)):t.push(`${s} must record verification: { verified: { method, source, date } }. An unverified venue stays blocked.`)}let r=e.capabilities||{};for(let o of Object.keys(r))Zd.includes(o)?typeof r[o]!="function"&&t.push(`capability "${o}" must be a function`):t.push(`unknown capability "${o}"`);return Object.keys(r).length===0&&n.push("scanner implements no capabilities -- it can only be registered, not used"),r.prepareUnsignedTx&&!r.quote&&n.push("prepareUnsignedTx without quote: no priced expectation to validate the built tx against"),r.prepareUnsignedTx&&!r.sellSimulation&&n.push("prepareUnsignedTx without sellSimulation: cannot prove an asset is exitable before buying"),{ok:t.length===0,errors:t,warnings:n}}function e3(e){let{ok:t,errors:n,warnings:r}=Zj(e);if(!t)throw new Error(`invalid scanner for ${e?.key??"<unknown>"}:
|
|
6
6
|
- ${n.join(`
|
|
7
7
|
- `)}`);let o=e.capabilities||{},i=Zd.filter(a=>typeof o[a]=="function"),s={key:e.key,chainId:e.chainId,name:e.name,rpcEnv:[...e.rpcEnv],nativeCurrency:e.nativeCurrency?{...e.nativeCurrency}:null,wrappedNative:e.wrappedNative||null,explorer:e.explorer||null,venues:(e.venues||[]).map(a=>({...a})),warnings:r,capabilities(){return{chainId:e.chainId,key:e.key,supported:[...i],unsupported:Zd.filter(a=>!i.includes(a))}},supports(a){return i.includes(a)}};for(let a of Zd)i.includes(a)?s[a]=async(...c)=>o[a](...c,{scanner:s}):s[a]=async()=>{throw new Error(`${e.key} (chain ${e.chainId}) does not implement "${a}". Supported: ${i.join(", ")||"none"}. An unimplemented capability is absent, not assumed -- implement it or treat this chain as fail-closed for that operation.`)};return Object.freeze(s)}function ay(e){let t=e3(e);return sy.set(t.chainId,t),t}function Cs(e){return sy.get(Number(e))||null}function ep(){return[...sy.values()]}var Zd,ue,ie,Qj,sy,vo=Y(()=>{Zd=Object.freeze(["blockNumber","nativeBalance","tokenBalance","resolveToken","resolvePools","scanBlocks","scoreRisk","quote","sellSimulation","prepareUnsignedTx"]),ue=Object.freeze({LIVE:"LIVE",CACHED:"CACHED",STALE:"STALE",UNKNOWN:"UNKNOWN",UNAVAILABLE:"UNAVAILABLE"}),ie=Object.freeze({PASS:"PASS",CAUTION:"CAUTION",FAIL:"FAIL",UNKNOWN:"UNKNOWN"}),Qj=/^0x[0-9a-fA-F]{40}$/;sy=new Map});function JA(e){let{source:t,amountOut:n,minOut:r=null,gasUsd:o=null,feeUsd:i=null,feeIncludedInAmountOut:s=!1,oracleFeeBps:a=0,estimatedGas:c=null,liquidityUsd:l=null,error:u=null,executionReady:d=!1,meta:p={}}=e||{};if(u||n==null)return{source:t,quality:Nn.FAILED,amountOut:null,error:u||"no amountOut returned"};let f=Pc(n);if(f==null||f<=0n)return{source:t,quality:Nn.FAILED,amountOut:null,error:"non-positive amountOut"};let m=Number(a);return{source:t,quality:o==null?Nn.NO_GAS:Nn.FULL,amountOut:f.toString(),minOut:Pc(r)?.toString()??null,gasUsd:o,feeUsd:i,feeIncludedInAmountOut:s===!0,oracleFeeBps:Number.isFinite(m)&&m>0?Math.floor(m):0,estimatedGas:c==null?null:String(c),liquidityUsd:l==null?null:Number(l),executionReady:d,meta:p}}async function QA(e,t,{divisor:n=1000n}={}){let r=Pc(t);if(r==null||r<=0n)return null;let o=r/n>0n?r/n:1n;if(o>=r)return null;let i,s;try{[i,s]=await Promise.all([e(o),e(r)])}catch{return null}let a=Pc(i),c=Pc(s);if(a==null||c==null||a<=0n)return null;let l=Number(a)/Number(o),u=Number(c)/Number(r);return!Number.isFinite(l)||!Number.isFinite(u)||l<=0?null:{impactPct:(1-u/l)*100,probeAmountIn:o.toString(),probeAmountOut:a.toString(),fullAmountOut:c.toString()}}function ZA(e,t,{maxImpactPct:n=25}={}){let r=[],o=[],i=(e.routes??[]).filter(a=>{let c=t?.[a.source];return c?c.impactPct>n?(r.push({source:a.source,impactPct:Number(c.impactPct.toFixed(2)),reason:`price impact ${c.impactPct.toFixed(1)}% exceeds ${n}% ceiling -- the venue cannot absorb this size near the quoted price`}),!1):!0:(o.push(a.source),!0)}),s=[...e.warnings??[]];return r.length&&s.push(`dropped ${r.length} route(s) on price impact: `+r.map(a=>`${a.source} (${a.impactPct}%)`).join(", ")),o.length&&s.push(`price impact NOT measured for: ${o.join(", ")}. These are unproven against thin liquidity, not proven safe.`),{...e,routes:i,best:i[0]??null,impactRejected:r,impactUnmeasured:o,warnings:s}}function cy(e,{destPriceUsd:t=null,destDecimals:n=null,liquidityFirst:r=!0,liquidityBandBps:o=50,gasPriceWei:i=null,nativePriceUsd:s=null}={}){let a=e.filter(I=>I.quality!==Nn.FAILED),c=e.filter(I=>I.quality===Nn.FAILED),l=t!=null&&t>0&&n!=null&&n>=0,u=Number(i),d=Number(s),p=Number.isFinite(u)&&u>0&&Number.isFinite(d)&&d>0,f=a.map(I=>{let _=BigInt(I.amountOut),P=0n,O=!1,F=!1,M=BigInt(I.oracleFeeBps??0),$=M>0n?_*M/10000n:0n;if(l){let C=I.gasUsd,j=Number(I.meta?.gasUnits??I.estimatedGas);if(C==null&&p&&Number.isFinite(j)&&j>0){let le=j*u/1e18*d;Number.isFinite(le)&&le>=0&&(C=le,F=!0)}let z=(C??0)+(I.feeIncludedInAmountOut?0:I.feeUsd??0);if(z>0){let le=z/t*10**n;Number.isFinite(le)&&le>=0&&(P=BigInt(Math.floor(le)),O=!0)}else C===0&&(O=!0)}let B=P+$,N=_>B?_-B:0n;return{...I,grossOut:_.toString(),netOut:N.toString(),costInDest:P.toString(),oracleFeeInDest:$.toString(),costAccounted:O,gasEstimated:F}}),m=Number(o)>0?Number(o):0,h=f.reduce((I,_)=>BigInt(_.netOut)>I?BigInt(_.netOut):I,0n),g=I=>h>0n?Number((h-BigInt(I))*10000n/h):0,y=[],b=(I,_)=>{let P=BigInt(I.netOut),O=BigInt(_.netOut);return P!==O?O>P?1:-1:String(I.source).localeCompare(String(_.source))},S=f.slice().sort(b)[0]??null;f.sort((I,_)=>{let P=g(I.netOut)<=m?0:1,O=g(_.netOut)<=m?0:1;if(r&&m>0&&P!==O)return P-O;if(r&&m>0){let F=I.liquidityUsd??-1,M=_.liquidityUsd??-1;if(F!==M)return M-F}return b(I,_)}),r&&m>0&&S&&f[0]&&f[0].source!==S.source&&y.push(`liquidity-first: chose ${f[0].source} (liquidity $${f[0].liquidityUsd??"unknown"}) over best-price ${S.source} within ${m} bps`);let w=f.filter(I=>!I.costAccounted).map(I=>I.source);l?w.length&&y.push(`gas not reported by: ${w.join(", ")}. These are ranked on gross output and may be overstated relative to gas-measured routes.`):y.push("destination price/decimals unavailable: ranked on GROSS output. Gas is not included, so a cheap-looking route may cost more to execute.");let E=f[0];if(l&&E&&E.costAccounted===!1){let I=f.find(_=>_.costAccounted&&g(_.netOut)<=m);I&&y.push(`winner ${E.source} has UNMEASURED gas; gas-measured ${I.source} is within ${m} bps and may net more once ${E.source}'s real gas is paid \u2014 prefer it if unsure.`)}let x=f.filter(I=>I.gasEstimated).map(I=>I.source);x.length&&y.push(`gas ESTIMATED (from gas units x current gas price, not measured) for: ${x.join(", ")}. Net includes this estimate so the ranking is gas-inclusive, but the on-chain gas may differ.`);let v=null,k=null;if(f.length>=2&&f[0].costAccounted&&f[1].costAccounted){let I=BigInt(f[0].netOut),_=BigInt(f[1].netOut);_>0n&&(v=Number((I-_)*10000n/_),k=`${f[0].source} vs ${f[1].source}`)}return{best:f[0]??null,routes:f,failed:c,improvementBps:v,spreadBasis:k,rankedOn:l?"net-of-cost":"gross",warnings:y}}async function tp(e,{timeoutMs:t=12e3}={}){let n=(o,i)=>{let s;return Promise.race([o,new Promise((a,c)=>{s=setTimeout(()=>c(new Error(`${i}: timeout`)),t)})]).finally(()=>clearTimeout(s))};return(await Promise.allSettled(e.map(o=>n(Promise.resolve().then(o.run),o.source)))).map((o,i)=>{let s=e[i].source;return o.status==="rejected"?JA({source:s,error:String(o.reason?.message||o.reason)}):JA({source:s,...o.value})})}var Nn,XA,Pc,ly=Y(()=>{vo();Nn=Object.freeze({FULL:"FULL",NO_GAS:"NO_GAS",FAILED:"FAILED"}),XA={1:"coingecko:ethereum",10:"coingecko:ethereum",56:"coingecko:binancecoin",137:"coingecko:matic-network",8453:"coingecko:ethereum",42161:"coingecko:ethereum",43114:"coingecko:avalanche-2",999:"coingecko:ethereum"},Pc=e=>{try{return e==null||e===""?null:BigInt(String(e).split(".")[0])}catch{return null}}});function uy(e){let t=String(e||"").trim();return/^0x[0-9a-fA-F]{40}$/.test(t)?t:xo}var xo,np=Y(()=>{xo="0x000000000000000000000000000000000000dEaD"});import{Contract as t3,JsonRpcProvider as n3}from"ethers";function c3(e){return a3.test(String(e||""))}async function rp(e,{contract:t=r3,rpc:n=i3,chainId:r=o3,balanceOf:o}={}){if(!c3(e))throw new Error("invalid-address");if(o)return BigInt(await o(e));let i=new n3(n,r,{staticNetwork:!0}),s=new t3(t,s3,i);return BigInt(await s.balanceOf(e))}var r3,o3,i3,s3,a3,dy=Y(()=>{r3="0x62FCFAf7573AD8B41a0FBF347AfEb85e06599A75",o3=999,i3="https://rpc.hyperliquid.xyz/evm",s3=["function balanceOf(address owner) view returns (uint256)"],a3=/^0x[a-fA-F0-9]{40}$/});import{existsSync as l3,readFileSync as u3,lstatSync as d3}from"node:fs";import{homedir as eI}from"node:os";import{join as py}from"node:path";function m3(e){let t=String(e||"swap").toLowerCase();return Object.prototype.hasOwnProperty.call(tI,t)?tI[t]:f3}function w3(e=process.env){if(process.env.ORACLE_TEST_ISOLATE_SECRETS==="1"){if(e[nI])return String(e[nI]);let t=e.ORACLE_CONFIG_DIR||py(eI(),".config","oracle");return py(t,"fee-recipient")}return py(eI(),".config","oracle","fee-recipient")}function fy(e=process.env){try{let t=w3(e);if(!l3(t)||d3(t).isSymbolicLink())return"";let n=u3(t,"utf8").trim().toLowerCase();return/^0x[a-f0-9]{40}$/.test(n)?n:""}catch{return""}}function S3(e,{fallback:t=0}={}){if(e==null)return t;if(String(e).trim()==="")return 0;let n=Number(e);return!Number.isFinite(n)||n<=0?0:Math.min(Math.floor(n),p3)}function E3({env:e=process.env,action:t="swap",admin:n=!1}={}){let r=String(e[g3]||"").trim(),o=String(e[y3]||b3).trim();if(n===!0)return{bps:0,recipient:"",integrator:o,action:t,applies:!1,reason:"admin-oracle"};let i=m3(t),s=S3(e[h3],{fallback:r?i:0}),a=Math.min(s,i);if(!a)return{bps:0,recipient:"",integrator:o,action:t,applies:!1,reason:"not-configured"};if(!/^0x[a-fA-F0-9]{40}$/.test(r))return{bps:0,recipient:"",integrator:o,action:t,applies:!1,reason:"no-recipient"};let c=fy(e);return!c||c!==r.toLowerCase()?{bps:0,recipient:"",integrator:o,action:t,applies:!1,reason:"recipient-not-pinned"}:{bps:a,recipient:r,integrator:o,action:t,applies:!0,reason:"configured"}}async function op({wallet:e,env:t=process.env,action:n="swap",holderCheck:r={},admin:o=!1}={}){let i=E3({env:t,action:n,admin:o});if(o===!0)return{...i,holderVerificationStatus:"admin-oracle"};let s=String(e||"").trim().toLowerCase();if(!/^0x[a-f0-9]{40}$/.test(s))return{...i,holderVerificationStatus:"wallet-required"};try{return BigInt(await rp(s,r))>0n?{...i,bps:0,applies:!1,reason:"locals-only-holder",holderVerificationStatus:"holder"}:{...i,holderVerificationStatus:"non-holder"}}catch{return{...i,holderVerificationStatus:"unavailable"}}}function rI(e){return e?.applies?`Oracle routing fee ${e.bps} bps (${(e.bps/100).toFixed(2)}%) to ${e.recipient}.`:e?.reason==="admin-oracle"?"No Oracle fee (admin Oracle).":e?.reason==="locals-only-holder"?"No Oracle fee (Locals Only holder).":"No Oracle fee."}function oI(e){return e?.applies?{integrator:e.integrator,fee:String(e.bps/1e4)}:{}}function iI(e){return e?.applies?{partner:e.integrator,partnerFeeBps:String(e.bps),partnerAddress:e.recipient}:{}}var p3,f3,tI,h3,g3,y3,nI,b3,Cc=Y(()=>{dy();p3=100,f3=5,tI=Object.freeze({swap:5,bridge:5,perps:0,nft:0});h3="ORACLE_INTEGRATOR_FEE_BPS",g3="ORACLE_INTEGRATOR_FEE_RECIPIENT",y3="ORACLE_INTEGRATOR_ID",nI="ORACLE_INTEGRATOR_FEE_RECIPIENT_PIN",b3="oracle"});var wy={};vt(wy,{LIFI_API:()=>sI,lifiChains:()=>by,lifiHealth:()=>gy,lifiPrepare:()=>yy,lifiQuote:()=>Lr});function hy(e={}){return(e.baseUrl||process.env.LIFI_API_URL||sI).replace(/\/$/,"")}function x3(e){let t=String(e||my).toLowerCase();return t===my.toLowerCase()||t===v3}function Rs(e,t){let n=String(e||"").trim();if(!/^0x[0-9a-fA-F]{40}$/.test(n))throw new Error(`lifi: ${t} must be a 20-byte address`);return n.toLowerCase()}async function gy(e={}){let t=await A(`${hy(e)}/chains`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3}),n=Array.isArray(t)?t.length:t?.chains?.length||0;return{ok:n>0,chainCount:n}}async function Lr(e={},t={}){let{fromChain:n,toChain:r=n,fromToken:o=my,toToken:i,fromAmount:s,fromAddress:a=xo}=e;if(n==null||!i||!s)throw new Error("lifiQuote requires fromChain, toToken, fromAmount");let c=new URLSearchParams({fromChain:String(n),toChain:String(r),fromToken:o,toToken:i,fromAmount:String(s),fromAddress:a}),l=nn({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(r)!==Number(n),requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!l.executable)throw new Error(`lifi: route requires ${l.requiredBps} bps above cap ${l.capBps}`);c.set("slippage",String(l.selectedBps/1e4));let u=await op({wallet:e.fromAddress,env:t.env,action:e.feeAction||"swap",holderCheck:t.holderCheck});for(let[g,y]of Object.entries(oI(u)))c.set(g,y);let d=await A(`${hy(t)}/quote?${c}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),p=d?.estimate?.toAmount||d?.toAmount;if(!p)return{...d,autoSlippagePolicy:l,oracleFee:u};let f=d?.transactionRequest?.to||d?.estimate?.approvalAddress||"lifi",m=Ne(d,{chainId:Number(n),venue:f,amountOut:p,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(r)!==Number(n),requestedCapBps:e.maxSlippageBps??e.slippageBps}),h=d?.estimate?.toAmountMin||d?.toAmountMin;if(h!=null&&BigInt(h)<BigInt(m.amountOutMinimum))throw new Error("lifi: provider transaction is under-protected versus bounded auto-slippage floor");return{...m,oracleFee:u}}async function yy(e={},t={}){let n=await Lr(e,t),r=n?.transactionRequest;if(!r?.to||!r?.data)throw new Error("lifi: quote did not return an executable transactionRequest");if(["nonce","authorizationList","maxFeePerBlobGas","blobVersionedHashes","blobs","kzg","signature","rawTransaction","signedTransaction","r","s","v"].find(d=>r[d]!=null))throw new Error("lifi: unsupported transaction authority");if(r.type!=null){let d=String(r.type).trim().toLowerCase();if(!/^(?:0x[0-9a-f]+|\d+)$/.test(d)||BigInt(d)>2n)throw new Error("lifi: unsupported transaction authority")}let i=Number(e.fromChain);if(r.chainId==null)throw new Error("lifi: transaction missing chain authority");if(Number(r.chainId)!==i)throw new Error("lifi: transaction chain mismatch");let s=e.fromAddress?Rs(e.fromAddress,"transaction sender"):r.from?Rs(r.from,"transaction sender"):null;if(!s)throw new Error("lifi: transaction missing sender authority");if(r.from&&Rs(r.from,"transaction sender")!==s)throw new Error("lifi: transaction sender mismatch");let a=Rs(r.to,"transaction target"),c=String(r.data);if(!/^0x(?:[0-9a-fA-F]{2})+$/.test(c))throw new Error("lifi: transaction calldata must be non-empty hex bytes");let l=String(r.value??"0x0");if(!/^(?:0x[0-9a-fA-F]+|\d+)$/.test(l))throw new Error("lifi: transaction value must be an unsigned integer string");let u=null;if(!x3(e.fromToken)){let d=n?.estimate?.approvalAddress||n?.approvalAddress;if(!d)throw new Error("lifi: ERC20 route missing approvalAddress");let p=n?.action?.fromToken?.address||n?.estimate?.fromToken?.address||e.fromToken;u={token:Rs(p,"approval token"),spender:Rs(d,"approval spender"),amount:String(e.fromAmount)}}return q({provider:"lifi",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:i,quote:n,autoSlippage:n.autoSlippage,requiresApproval:u,transaction:{chainId:i,from:s,to:a,data:c,value:l,...r.gasLimit!=null?{gasLimit:r.gasLimit}:{},slippageGuard:Ye(n.autoSlippage,{chainId:i,venue:a,data:c})}},{provider:"lifi",kind:"lifi-tx",env:t.env,nowMs:t.nowMs,expiresAtMs:t.expiresAtMs})}async function by(e={}){return A(`${hy(e)}/chains`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??12e3})}var sI,my,v3,Rc=Y(()=>{V();Gt();np();ae();Cc();sI="https://li.quest/v1";my="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",v3="0x0000000000000000000000000000000000000000"});var xy={};vt(xy,{PARASWAP_API:()=>aI,paraswapHealth:()=>vy,paraswapPrepare:()=>Ey,paraswapPrice:()=>$r,paraswapTokens:()=>ip});function Ls(e,t){let n=String(e||"");if(!/^0x[0-9a-fA-F]{40}$/.test(n))throw new Error(`${t} must be a 20-byte token address`);return n.toLowerCase()}async function ip(e={},t={}){let n=Number(e.chainId||1);return A(`${Sy(t)}/tokens/${n}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function $r(e={},t={}){let n=Number(e.chainId||e.network||1);if(e.amount==null)throw new Error("amount required");let r=new URLSearchParams({srcToken:Ls(e.srcToken,"srcToken"),destToken:Ls(e.destToken,"destToken"),amount:String(e.amount),srcDecimals:String(Number(e.srcDecimals)),destDecimals:String(Number(e.destDecimals)),side:String(e.side||"SELL").toUpperCase(),network:String(n),version:String(e.version||"6.2")});e.includeDEXS&&r.set("includeDEXS",String(e.includeDEXS)),e.excludeDEXS&&r.set("excludeDEXS",String(e.excludeDEXS));let o=await op({wallet:e.userAddress||e.fromAddress,env:t.env,action:e.feeAction||"swap",holderCheck:t.holderCheck});for(let[a,c]of Object.entries(iI(o)))r.set(a,c);let i=await A(`${Sy(t)}/prices?${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),s=i?.priceRoute?.destAmount;return s?{...Ne(i,{chainId:n,venue:i?.priceRoute?.contractAddress||"paraswap-quote",amountOut:s,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,quoteAgeMs:0,requestedCapBps:e.maxSlippageBps??e.slippageBps}),executionReady:!1,executionBlocker:"call prepare to bind the price route to a validated transaction",oracleFee:o}:{...i,executionReady:!1,oracleFee:o}}async function Ey(e={},t={}){if(String(e.side||"SELL").toUpperCase()!=="SELL")throw new Error("paraswap: agentic prepare currently supports exact-input SELL only");let n=Number(e.chainId||e.network||1),r=Ls(e.userAddress,"userAddress"),o=await $r(e,t),i=o?.priceRoute,s=String(i?.contractAddress||"").toLowerCase();if(!s)throw new Error("paraswap: price route missing contractAddress");let a={srcToken:Ls(e.srcToken,"srcToken"),destToken:Ls(e.destToken,"destToken"),srcAmount:String(i.srcAmount||e.amount),destAmount:String(o.amountOutMinimum),priceRoute:i,userAddress:r,ignoreChecks:!1,ignoreGasEstimate:!1};e.receiver&&(a.receiver=Ls(e.receiver,"receiver"));let c=await A(`${Sy(t)}/transactions/${n}`,{method:"POST",body:a,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??25e3});if(Number(c.chainId??n)!==n)throw new Error("paraswap: transaction chain mismatch");if(String(c.to||"").toLowerCase()!==s)throw new Error("paraswap: transaction target mismatch");if(c.from&&String(c.from).toLowerCase()!==r)throw new Error("paraswap: transaction sender mismatch");return q({provider:"paraswap",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:n,quote:o,autoSlippage:o.autoSlippage,requiresApproval:a.srcToken!=="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"?{token:a.srcToken,spender:i.tokenTransferProxy||s,amount:a.srcAmount}:null,transaction:{chainId:n,from:c.from||r,to:c.to,data:c.data,value:c.value??"0x0",...c.gas!=null?{gasLimit:c.gas}:{},slippageGuard:Ye(o.autoSlippage,{chainId:n,venue:c.to,data:c.data})}},{provider:"paraswap",kind:"paraswap-tx"})}async function vy(e={}){let t=await ip({chainId:1},e),n=Array.isArray(t?.tokens)?t.tokens.length:Object.keys(t?.tokens||{}).length;return{ok:n>0,tokenSample:n}}var aI,Sy,Lc=Y(()=>{V();Gt();ae();Cc();aI="https://api.paraswap.io",Sy=(e={})=>(e.baseUrl||process.env.PARASWAP_API_URL||aI).replace(/\/$/,"")});function Ue({provider:e,defaultUrl:t,hosts:n=[],url:r,strict:o=!1}){let s=(String(r??"").trim()||String(t)).replace(/\/$/,"");if(s===String(t).replace(/\/$/,""))return{baseUrl:s,trusted:!0,host:lI(t)};let a;try{a=new URL(s)}catch{throw new Error(`${e}: baseUrl must be an absolute http(s) URL`)}if(a.protocol!=="http:"&&a.protocol!=="https:")throw new Error(`${e}: baseUrl must be an absolute http(s) URL`);let c=a.host;if(!c)throw new Error(`${e}: baseUrl must be an absolute http(s) URL`);if(new Set([lI(t),...n]).has(c)){let u=/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(c);return a.protocol==="http:"&&!u?{baseUrl:s,trusted:!1,host:c,reason:"plaintext http downgrade"}:{baseUrl:s,trusted:!0,host:c}}if(String(process.env[cI]||"")==="1")return{baseUrl:s,trusted:!1,host:c};if(o)throw new Error(`${e}: refusing to call non-allowlisted host ${c} (set ${cI}=1 to permit it)`);return{baseUrl:s,trusted:!1,host:c}}function lI(e){let t=new URL(String(e));if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error("unsupported protocol");return t.host}function Pn(e){return typeof e=="string"&&e.length>0&&e.length<=4096&&!/[\s"\\[\]{},:]/u.test(e)?e:""}function Je(e,t,n){let r={...e};if(!n)return r;for(let[o,i]of Object.entries(t||{}))i&&(r[o]=i);return r}var cI,Pt=Y(()=>{cI="ORACLE_ALLOW_CUSTOM_PROVIDER_URL"});var Iy={};vt(Iy,{ZEROX_API:()=>uI,zeroxHealth:()=>ky,zeroxPrepare:()=>Ay,zeroxPrice:()=>ap,zeroxQuote:()=>ko});function dI(e={}){return Ue({provider:"zerox",defaultUrl:uI,hosts:["api.0x.org"],url:e.baseUrl||process.env.ZEROX_API_URL})}function pI(e={}){return dI(e).baseUrl}function sp(e={}){return e.apiKey||process.env.ZEROX_API_KEY||process.env.OX_API_KEY||process.env["0X_API_KEY"]||""}function fI(e={}){return Je({"0x-version":"v2",accept:"application/json"},{"0x-api-key":sp(e)},dI(e).trusted)}async function ky(e={}){if(!sp(e))return{ok:!1,configured:!1,error:"ZEROX_API_KEY not set"};try{let t=await ap({chainId:8453,sellToken:"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",buyToken:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",sellAmount:"1000000000000000"},e);return{ok:!0,configured:!0,buyAmount:t.buyAmount||t.grossBuyAmount}}catch(t){return{ok:!1,configured:!0,error:String(t.message||t).slice(0,160)}}}async function ap(e={},t={}){if(!sp(t))throw new Error("ZEROX_API_KEY required for 0x");let{chainId:n=8453,sellToken:r,buyToken:o,sellAmount:i,taker:s}=e;if(!r||!o||!i)throw new Error("zeroxPrice requires sellToken, buyToken, sellAmount");let a=new URLSearchParams({chainId:String(n),sellToken:r,buyToken:o,sellAmount:String(i)});return s&&a.set("taker",s),A(`${pI(t)}/swap/allowance-holder/price?${a}`,{headers:fI(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function ko(e={},t={}){if(!sp(t))throw new Error("ZEROX_API_KEY required for 0x");let{chainId:n=8453,sellToken:r,buyToken:o,sellAmount:i,taker:s}=e;if(!r||!o||!i)throw new Error("zeroxQuote requires sellToken, buyToken, sellAmount");let a=nn({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!a.executable)throw new Error(`0x: route requires ${a.requiredBps} bps above cap ${a.capBps}`);let c=new URLSearchParams({chainId:String(n),sellToken:r,buyToken:o,sellAmount:String(i),slippageBps:String(a.selectedBps)});s&&c.set("taker",s);let l=await A(`${pI(t)}/swap/allowance-holder/quote?${c}`,{headers:fI(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),u=l?.buyAmount||l?.grossBuyAmount;return u?Ne(l,{chainId:n,venue:l?.transaction?.to||l?.to||"0x",amountOut:u,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):{...l,autoSlippagePolicy:a}}async function Ay(e={},t={}){if(!e.taker)throw new Error("0x: taker required for executable prepare");let n=await ko(e,t),r=n?.transaction;if(!r?.to||!r?.data)throw new Error("0x: firm quote returned no transaction");let o=Number(e.chainId??8453),i=n?.issues?.allowance?.spender||n?.allowanceTarget;return q({provider:"zerox",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:o,quote:n,autoSlippage:n.autoSlippage,requiresApproval:n?.issues?.allowance?.actual!=null&&BigInt(n.issues.allowance.actual)<BigInt(e.sellAmount)?{token:e.sellToken,spender:i,amount:String(e.sellAmount)}:null,transaction:{chainId:o,from:e.taker,to:r.to,data:r.data,value:r.value??"0x0",...r.gas!=null?{gasLimit:r.gas}:{},slippageGuard:Ye(n.autoSlippage,{chainId:o,venue:r.to,data:r.data})}},{provider:"zerox",kind:"zerox-tx"})}var uI,$c=Y(()=>{V();Gt();Pt();ae();uI="https://api.0x.org"});function mI(e={}){return Ue({provider:"oneinch",defaultUrl:k3,hosts:["api.1inch.dev"],url:e.baseUrl||process.env.ONEINCH_API_URL})}function _y(e={}){return mI(e).baseUrl}function Mc(e={}){return e.apiKey||process.env.ONEINCH_API_KEY||process.env.ONE_INCH_API_KEY||""}function Oy(e={}){let t=Mc(e);return Je({accept:"application/json"},{Authorization:t?`Bearer ${t}`:""},mI(e).trusted)}async function hI(e={}){if(!Mc(e))return{ok:!1,configured:!1,error:"ONEINCH_API_KEY not set"};try{return{ok:!0,configured:!0,dstAmount:(await Bc({chainId:8453,src:"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",dst:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",amount:"1000000000000000"},e)).dstAmount}}catch(t){return{ok:!1,configured:!0,error:String(t.message||t).slice(0,160)}}}async function Bc(e={},t={}){if(!Mc(t))throw new Error("ONEINCH_API_KEY required for 1inch");let n=Number(e.chainId??1),{src:r,dst:o,amount:i}=e;if(!r||!o||!i)throw new Error("oneinchQuote requires src, dst, amount");let s=new URLSearchParams({src:r,dst:o,amount:String(i)}),a=await A(`${_y(t)}/${n}/quote?${s}`,{headers:Oy(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3});return a?.dstAmount?Ne(a,{chainId:n,venue:"1inch-quote",amountOut:a.dstAmount,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):a}function A3(e){return/^(eth|native|0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee)$/i.test(String(e||""))}async function Ty(e={},t={}){if(!Mc(t))throw new Error("ONEINCH_API_KEY required for 1inch");let n=Number(e.chainId??1);return A(`${_y(t)}/${n}/approve/spender`,{headers:Oy(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function gI(e={},t={}){if(!Mc(t))throw new Error("ONEINCH_API_KEY required for 1inch");let n=Number(e.chainId??1),{src:r,dst:o,amount:i}=e,s=e.from||e.fromAddress||e.userAddress||e.taker;if(!r||!o||!i||!s)throw new Error("oneinchPrepare requires src, dst, amount, from");let a=nn({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!a.executable)throw new Error(`1inch: route requires ${a.requiredBps} bps above cap ${a.capBps}`);let c=new URLSearchParams({src:r,dst:o,amount:String(i),from:s,slippage:String(a.selectedBps/100)});e.receiver&&c.set("receiver",e.receiver),e.referrer&&c.set("referrer",e.referrer),e.disableEstimate!=null&&c.set("disableEstimate",String(!!e.disableEstimate)),e.allowPartialFill!=null&&c.set("allowPartialFill",String(!!e.allowPartialFill)),e.includeProtocols&&c.set("includeProtocols",String(e.includeProtocols)),e.excludeProtocols&&c.set("excludeProtocols",String(e.excludeProtocols));let l=await A(`${_y(t)}/${n}/swap?${c}`,{headers:Oy(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??25e3}),u=l?.tx;if(!u?.to||!u?.data)throw new Error("1inch: swap returned no executable tx");if(u.from&&String(u.from).toLowerCase()!==String(s).toLowerCase())throw new Error("1inch: transaction sender mismatch");let d=l?.dstAmount||l?.toTokenAmount||l?.buyAmount;if(!d)throw new Error("1inch: swap response missing dstAmount");let p=Ne(l,{chainId:n,venue:u.to,amountOut:d,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}),f=null;if(!A3(r)){let m=l?.spender||l?.approvalAddress||(await Ty({chainId:n},t))?.address;if(!m)throw new Error("1inch: ERC-20 route missing approval spender");f={token:r,spender:m,amount:String(i)}}return q({provider:"oneinch",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:n,quote:p,autoSlippage:p.autoSlippage,requiresApproval:f,transaction:{chainId:n,from:u.from||s,to:u.to,data:u.data,value:u.value??"0x0",...u.gas!=null?{gasLimit:u.gas}:{},slippageGuard:Ye(p.autoSlippage,{chainId:n,venue:u.to,data:u.data})}},{provider:"oneinch",kind:"oneinch-tx"})}var k3,Ny=Y(()=>{V();Gt();Pt();ae();k3="https://api.1inch.dev/swap/v6.0"});function Py(e=process.env){return String(e.ORACLE_AUTONOMOUS_TRADING??"").trim()==="1"}function yI(e=process.env){return String(e.ORACLE_AUTONOMOUS_MINT??process.env.ORACLE_AUTONOMOUS_MINT??"").trim()==="1"}var eme,cp=Y(()=>{eme=Object.freeze({READ:"read",PREPARE:"prepare",EXECUTE:"execute",AUTONOMOUS:"autonomous"})});import lp from"node:fs";import _3 from"node:os";import Ms from"node:path";import{fileURLToPath as O3}from"node:url";function bI(){return process.env.ORACLE_FAKE_HOME||_3.homedir()}function N3(){return process.env.ORACLE_PUBLIC_DESKTOP==="1"}function up(){return N3()?process.env.ORACLE_CONFIG_DIR||Ms.join(bI(),".config","oracle"):Ms.join(bI(),".config","oracle")}function P3(){return Ms.join(up(),"desk.json")}function C3(){return Ms.join(up(),"env")}function $s({force:e=!1}={}){if($s._done&&!e)return $s._result||null;$s._done=!0;let t={},n=(o,i)=>{if(i==null)return;let s=String(i).trim();s&&(process.env[o]!=null&&String(process.env[o]).trim()!==""||(process.env[o]=s,t[o]=s))};try{let o=C3();if(lp.existsSync(o))for(let i of lp.readFileSync(o,"utf8").split(/\r?\n/)){let s=i.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/);if(!s||s[2].startsWith("#"))continue;let a=s[2];(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a=a.slice(1,-1)),n(s[1],a)}}catch{}try{let o=P3();if(lp.existsSync(o)){let i=JSON.parse(lp.readFileSync(o,"utf8"));i&&typeof i=="object"&&(n("ORACLE_DESK_URL",i.deskUrl||i.dataUrl||i.url),n("ORACLE_DATA_URL",i.dataUrl||i.deskUrl||i.url),n("ORACLE_API_URL",i.apiUrl||i.dataUrl||i.deskUrl),n("ORACLE_PUBLIC_URL",i.publicUrl||i.deskUrl||i.dataUrl),n("ORACLE_EXEC_URL",i.execUrl),n("MAD_DESK_URL",i.deskUrl||i.dataUrl))}}catch{}let r=process.env.ORACLE_DESK_URL||process.env.ORACLE_DATA_URL||"";return r&&(n("ORACLE_DESK_URL",r),n("ORACLE_DATA_URL",r),n("ORACLE_API_URL",r),n("ORACLE_PUBLIC_URL",r),n("MAD_DESK_URL",r)),$s._result=Object.keys(t).length?t:null,$s._result}var T3,sme,wI=Y(()=>{T3=Ms.dirname(O3(import.meta.url)),sme=Ms.resolve(T3,"../..");try{$s()}catch{}});var SI=Y(()=>{});import{createHash as R3}from"node:crypto";function EI(e,t){if(e==null||typeof e!="object"||Array.isArray(e))throw new TypeError(`prepare verification: ${t} must be an object`);return e}function Ry(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Ry).join(",")}]`:`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${Ry(e[n])}`).join(",")}}`}function U3(e){return R3("sha256").update(Ry(e),"utf8").digest("hex")}function Cy(e){let t=String(e||"").trim().toLowerCase().replace(/^0x/,"");return M3.test(t)?t:""}function F3(e,t="prepare verification"){if(EI(e,"prepared"),e.signed===!0)throw new Error(`${t}: prepared fact is signed`);if(e.broadcast===!0)throw new Error(`${t}: prepared fact claims broadcast`);for(let n of B3)if(e[n])throw new Error(`${t}: prepared fact carries ${n}`);for(let n of D3)if(e[n])throw new Error(`${t}: prepared fact claims executed ${n}`);return!0}function q3(e,t={}){let n=t.label||"prepare verification";if(EI(e,"artifact"),Number(e.version)!==L3)throw new Error(`${n}: unsupported verification artifact version`);if(e.kind!==$3)throw new Error(`${n}: verification artifact kind required`);if(e.custody!=="none")throw new Error(`${n}: verification artifact custody must be none`);if(e.execution!=="prepare-only")throw new Error(`${n}: verification artifact must stay prepare-only`);if(e.signingReady===!0||e.broadcastReady===!0||e.executionReady===!0)throw new Error(`${n}: verification artifact must not claim a ready execution flag`);if(e.attestation?.teeAttested===!0)throw new Error(`${n}: TEE attestation is not claimed or accepted`);if(!["ok","success","failed","error","unavailable","unknown"].includes(String(e.simulation?.status||"")))throw new Error(`${n}: simulation status required`);if(typeof e.intentSummary!="string"||!e.intentSummary.trim())throw new Error(`${n}: human-readable intent summary required`);if(!e.attestation||typeof e.attestation!="object")throw new Error(`${n}: attestation record required`);if(!Array.isArray(e.attestation.notClaimed)||!e.attestation.notClaimed.includes("tee-attestation"))throw new Error(`${n}: attestation must honestly exclude TEE claims`);let{artifactHash:r,...o}=e;if(Cy(r)!==U3(o))throw new Error(`${n}: artifactHash mismatch \u2014 verification artifact was altered`);if(t.prepareHash){let i=Cy(t.prepareHash),s=Cy(e.prepareHash);if(!i||i!==s)throw new Error(`${n}: verification artifact does not bind this prepare`)}return e}function vI(e,t={}){let n=t.label||"armPreparedAction";if(!e||typeof e!="object")throw new Error(`${n}: prepared object required`);let r=e.prepareVerification||e.verificationArtifact||e.deskCheckpoint?.prepareVerification||t.checkpoint?.prepareVerification;if(!r)throw new Error(`${n}: prepare verification artifact required before arm`);return q3(r,{label:n,...e.prepareHash?{prepareHash:e.prepareHash}:{}}),F3(e,n),r}var L3,$3,fme,M3,B3,D3,mme,xI=Y(()=>{SI();ae();L3=1,$3="prepare-verification",fme=Object.freeze({NONE:"none",PREPARE_CHECKSUM:"prepare-checksum",PREPARE_HMAC:"prepare-hmac"}),M3=/^(?:0x)?[0-9a-f]{64}$/i,B3=Object.freeze(["signature","signedTx","signedTransaction","rawTransaction","signedPayload","signedRaw"]),D3=Object.freeze(["txid","txHash","transactionHash","broadcastHash"]),mme=Object.freeze(["tee-attestation","remote-attestation","hardware-enclave","trusted-execution-environment","execution-authorization","signature","broadcast"])});var Dc={};vt(Dc,{armPreparedAction:()=>Y3,callSigner:()=>kI,queueOwnerAction:()=>AI});import{existsSync as j3,readFileSync as H3}from"node:fs";import{request as z3}from"node:http";import V3 from"node:path";function G3(e=process.env){let t=String(e.ORACLE_SIGNER_URL||W3).replace(/\/$/,""),n;try{n=new URL(t)}catch{return null}return n.hostname!=="127.0.0.1"&&n.hostname!=="localhost"&&n.hostname!=="::1"?null:n.origin}function K3(e=process.env){if(e.ORACLE_SIGNER_TOKEN)return String(e.ORACLE_SIGNER_TOKEN);let t=V3.join(up(),"signer","signer-token");return j3(t)?H3(t,"utf8").trim():null}function kI(e,{method:t="GET",body:n=null,env:r=process.env,timeoutMs:o=4e3}={}){let i=G3(r),s=K3(r);return!i||!s?Promise.resolve({ok:!1,error:"local signer is not running"}):new Promise(a=>{let c=new URL(e,i),l=n?Buffer.from(JSON.stringify(n)):null,u=z3({hostname:c.hostname,port:c.port||80,path:c.pathname,method:t,timeout:o,headers:{authorization:`Bearer ${s}`,origin:i,...l?{"content-type":"application/json","content-length":l.length}:{}}},d=>{let p=[];d.on("data",f=>p.push(f)),d.on("end",()=>{let f=Buffer.concat(p).toString("utf8"),m={};try{m=f?JSON.parse(f):{}}catch{m={error:"signer refused"}}a({httpStatus:d.statusCode,...m})})});u.on("timeout",()=>{u.destroy(),a({ok:!1,error:"local signer timed out"})}),u.on("error",()=>a({ok:!1,error:"local signer is not running"})),l&&u.write(l),u.end()})}async function AI(e,t=process.env){if(!e||e.version!==1||!e.surface)throw new Error("queueOwnerAction: version-1 surface envelope required");return kI("/pending",{method:"POST",body:{artifact:e},env:t,timeoutMs:8e3})}async function Y3(e,t=process.env){let n=e?.localSignerEnvelope||e?.envelope;if(!n||n.version!==1||!n.surface)throw new Error("armPreparedAction: prepared.localSignerEnvelope v1 required");return vI(e,{env:t,label:"armPreparedAction"}),AI(n,t)}var W3,Uc=Y(()=>{wI();xI();W3="http://127.0.0.1:9462"});var qy={};vt(qy,{COW_CANCEL_TYPES:()=>TI,COW_HOSTS:()=>pp,COW_ORDER_TYPES:()=>dp,COW_SETTLEMENT:()=>II,COW_VAULT_RELAYER:()=>_I,armCowOrder:()=>eH,buildArmedCowOrder:()=>Uy,cowCancelOrders:()=>sH,cowChains:()=>Fy,cowHealth:()=>By,cowOrder:()=>hp,cowOrderStatus:()=>mp,cowOrderUid:()=>tH,cowPrepareCancel:()=>oH,cowPrepareOrder:()=>Dy,cowQuote:()=>Br,cowSignCancel:()=>iH,cowSignOrder:()=>nH,cowSubmitSignedOrder:()=>rH,cowVerifyOrderFill:()=>cH});import{TypedDataEncoder as $y,getAddress as Fc,isAddress as J3}from"ethers";function fp(e,t={}){if(t.baseUrl)return t.baseUrl.replace(/\/$/,"");let n=pp[Number(e)];if(!n)throw new Error(`cowswap: unsupported chainId ${e}`);return n}function X3(e,t="v1",n={}){let r=fp(e,n);return t==="v1"?r:r.replace(/\/api\/v1$/,`/api/${t}`)}function Mr(e,t){let n=String(e||"").trim();if(!J3(n))throw new Error(`cowswap: ${t} must be an address`);return Fc(n).toLowerCase()}function Bs(e,t){try{let n=BigInt(String(e));if(n<0n)throw new Error("negative");return n.toString()}catch{throw new Error(`cowswap: ${t} must be a non-negative integer string`)}}function NI(e,t){let n=String(e||"").trim();if(!/^0x[0-9a-fA-F]{64}$/.test(n))throw new Error(`cowswap: ${t} must be bytes32 hex`);return n.toLowerCase()}function PI(e,t="uid"){let n=String(e||"").trim();if(!/^0x[0-9a-fA-F]{112}$/.test(n))throw new Error(`cowswap: ${t} must be 56-byte order UID hex`);return n.toLowerCase()}function Q3({digest:e,owner:t,validTo:n}={}){let r=NI(e,"order digest").slice(2),o=Mr(t,"owner").slice(2).toLowerCase(),i=Number(n);if(!Number.isInteger(i)||i<0||i>4294967295)throw new Error("cowswap: validTo must fit uint32");return`0x${r}${o}${i.toString(16).padStart(8,"0")}`.toLowerCase()}function My(e){let t=II[Number(e)];if(!t)throw new Error(`cowswap: settlement contract not registered for chain ${e}`);return{name:"Gnosis Protocol",version:"v2",chainId:Number(e),verifyingContract:Fc(t)}}function Z3(e={},t,n){let r=Mr(e.sellToken,"sellToken"),o=Mr(e.buyToken,"buyToken"),i=Mr(e.receiver||n,"receiver"),s=Number(e.validTo);if(!Number.isInteger(s)||s<=0)throw new Error("cowswap: quote.validTo required");let a=NI(e.appData||e.appDataHash||`0x${"0".repeat(64)}`,"appData");return{sellToken:r,buyToken:o,receiver:i,sellAmount:Bs(e.sellAmount,"sellAmount"),buyAmount:Bs(e.buyAmount,"buyAmount"),validTo:s,appData:a,feeAmount:Bs(e.feeAmount??"0","feeAmount"),kind:String(e.kind||"sell"),partiallyFillable:!!e.partiallyFillable,sellTokenBalance:String(e.sellTokenBalance||"erc20"),buyTokenBalance:String(e.buyTokenBalance||"erc20")}}async function By(e={}){try{let t=await Br({chainId:1,sellToken:Ly[1],buyToken:OI[1],sellAmountBeforeFee:"1000000000000000",from:xo},e);return{ok:!0,buyAmount:t.quote?.buyAmount||t.buyAmount}}catch(t){return{ok:!1,error:String(t.message||t).slice(0,160)}}}async function Br(e={},t={}){let n=Number(e.chainId??1),r=uy(e.from||e.owner),o=e.sellToken||Ly[n],i=e.buyToken||OI[n],s=String(e.sellAmountBeforeFee||e.sellAmount||"0");if(!o||!i||s==="0")throw new Error("cowQuote requires sellToken, buyToken, sellAmountBeforeFee");if(/eeeeeeee|native|^eth$/i.test(o)&&(o=Ly[n],!o))throw new Error("no WETH mapping for chain");let a={sellToken:o,buyToken:i,from:r,receiver:e.receiver||r,sellAmountBeforeFee:s,kind:e.kind||"sell",signingScheme:e.signingScheme||"eip1271"},c=await A(`${fp(n,t)}/quote`,{method:"POST",body:a,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),l=c?.quote?.buyAmount||c?.buyAmount;return l?Ne(c,{chainId:n,venue:"cowswap-order",amountOut:l,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}):c}async function Dy(e={},t={}){let n=Number(e.chainId??1),r=Mr(uy(e.from||e.owner||e.signer),"owner"),o=await Br({...e,chainId:n,from:r,signingScheme:e.signingScheme||"eip712"},t),i=Z3(o?.quote||o,n,r),s=My(n),a={domain:s,types:dp,primaryType:"Order",message:i},c=$y.hash(s,dp,i),l=_I[n];if(!l)throw new Error(`cowswap: vault relayer not registered for chain ${n}`);return q({provider:"cowswap",orderReady:!0,executionReady:!1,chainId:n,owner:r,signingScheme:"eip712",settlement:s.verifyingContract.toLowerCase(),vaultRelayer:Fc(l).toLowerCase(),quote:o,quoteId:o?.id??e.quoteId??null,typedData:a,cowGuard:{mode:"cow-order",version:1,provider:"cowswap",chainId:n,owner:r,settlement:s.verifyingContract.toLowerCase(),vaultRelayer:Fc(l).toLowerCase(),sellToken:i.sellToken,buyToken:i.buyToken,sellAmount:i.sellAmount,buyAmount:i.buyAmount,validTo:i.validTo,quoteId:o?.id??e.quoteId??null,typedDataHash:c,issuedAtMs:Date.now(),expiresAtMs:Math.min(i.validTo*1e3,Date.now()+2e4)},requiresApproval:{token:i.sellToken,spender:Fc(l).toLowerCase(),amount:i.sellAmount},localSignerEnvelope:Uy({chainId:n,owner:r,typedData:a,quoteId:o?.id??e.quoteId??null,cowGuard:{expiresAtMs:Math.min(i.validTo*1e3,Date.now()+2e4)}})},{provider:"cowswap",kind:"cow-order"})}function Uy(e={},t={}){let n=e.typedData;if(!n?.domain||!n?.types||!n?.message)throw new Error("cowswap: typedData required to arm");let r=Number(e.chainId??n.domain.chainId),o=pp[r];if(!o)throw new Error(`cowswap: unsupported chainId ${r}`);let i=Mr(e.owner,"owner"),s=Number(t.nowMs??Date.now()),a=$y.hash(n.domain,n.types,n.message);return Object.freeze({tradeId:`cow:${r}:${a.slice(2)}`,version:1,surface:"evm-order",action:"order",owner:i,destination:"cowswap",chainId:r,expiresAtMs:Number(e.cowGuard?.expiresAtMs??s+2e4),slippageBps:0,fee:{oracleFeeBps:0},artifact:Object.freeze({kind:"cow",chainId:r,submitTo:`${o}/orders`,quoteId:e.quoteId??null,domain:n.domain,types:n.types,message:n.message,typedData:n})})}async function eH(e={},t={}){let{queueOwnerAction:n}=await Promise.resolve().then(()=>(Uc(),Dc)),r=e.localSignerEnvelope||Uy(e,t);return{...await n(r,t.env),envelope:r,execution:"armed-local",exec:!1}}async function mp(e={},t={}){let n=Number(e.chainId??1),r=String(e.uid||e.orderUid||"").trim();if(!r)throw new Error("cowOrderStatus requires uid");return A(`${fp(n,t)}/orders/${encodeURIComponent(r)}/status`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function hp(e={},t={}){let n=Number(e.chainId??1),r=String(e.uid||e.orderUid||"").trim();if(!r)throw new Error("cowOrder requires uid");return A(`${fp(n,t)}/orders/${encodeURIComponent(r)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}function tH(e={}){let t=e.typedData||e,n=Number(e.chainId??t?.domain?.chainId),r=t?.message||e.order||e.message;if(!r)throw new Error("cowswap: typed order message required");let o=e.cowGuard?.typedDataHash||$y.hash(My(n),dp,r),i=e.owner||e.from||e.signer||r.receiver;return Q3({digest:o,owner:i,validTo:r.validTo})}async function nH(e={},t={}){throw new Error("cowswap.cowSignOrder refused: @oracle-agent/oracle is prepare-only. Sign with the user wallet; do not pass private keys here.")}async function rH(e={},t={}){throw new Error("cowswap.cowSubmitSignedOrder refused: @oracle-agent/oracle is prepare-only. Submit signed orders from the user wallet or local operator.")}function oH(e={}){let t=Number(e.chainId??1),n=Mr(e.owner||e.from||e.signer,"owner"),r=(e.orderUids||e.uids||[e.uid]).filter(Boolean).map((s,a)=>PI(s,`orderUids[${a}]`));if(!r.length)throw new Error("cowswap: orderUids required");let o=My(t);return q({provider:"cowswap",chainId:t,owner:n,orderUids:r,signingScheme:"eip712",typedData:{domain:o,types:TI,primaryType:"OrderCancellations",message:{orderUids:r}},cancelReady:!0,executableArtifact:!0},{provider:"cowswap",kind:"cow-cancel"})}async function iH(e={},t={}){throw new Error("cowswap.cowSignCancel refused: @oracle-agent/oracle is prepare-only. Cancel-sign with the user wallet.")}async function sH(e={},t={}){throw new Error("cowswap.cowCancelOrders refused: @oracle-agent/oracle is prepare-only. Cancel from the user wallet or local operator.")}function aH(e={}){return Bs(e.buyAmount??e.executedBuyAmount??"0","trade.buyAmount")}async function cH(e={},t={}){let n=Number(e.chainId??1),r=PI(e.uid||e.orderUid),o=t.order||await hp({chainId:n,uid:r},t),i=t.status||o.status||await mp({chainId:n,uid:r},t).catch(()=>null),s=t.trades||await A(`${X3(n,"v2",t)}/trades?orderUid=${encodeURIComponent(r)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),a=Array.isArray(s)?s:[],c=e.expectedOwner?Mr(e.expectedOwner,"expectedOwner"):null;if(c&&Mr(o.owner||a[0]?.owner||c,"owner")!==c)return{ok:!1,provider:"cowswap",chainId:n,uid:r,reason:"owner mismatch",order:o,status:i,trades:a};let l=0n;for(let p of a.filter(f=>String(f.orderUid||"").toLowerCase()===r))l+=BigInt(aH(p));l===0n&&o.executedBuyAmount!=null&&(l=BigInt(Bs(o.executedBuyAmount,"executedBuyAmount")));let u=e.minBuyAmount!=null?BigInt(Bs(e.minBuyAmount,"minBuyAmount")):0n,d=l>=u&&String(o.status||i?.status||"").toLowerCase()!=="expired";return{ok:d,provider:"cowswap",chainId:n,uid:r,status:o.status||i?.status||null,executedBuyAmount:l.toString(),minBuyAmount:e.minBuyAmount??null,trades:a,settlementTxs:[...new Set(a.map(p=>p.txHash).filter(Boolean))],order:o,orderStatus:i,reason:d?null:"insufficient fill or expired order"}}function Fy(){return Object.keys(pp).map(Number)}var pp,II,_I,Ly,OI,dp,TI,qc=Y(()=>{V();Gt();cp();np();ae();pp={1:"https://api.cow.fi/mainnet/api/v1",100:"https://api.cow.fi/xdai/api/v1",42161:"https://api.cow.fi/arbitrum_one/api/v1",8453:"https://api.cow.fi/base/api/v1"},II=Object.freeze({1:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",100:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",42161:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41",8453:"0x9008D19f58AAbD9eD0D60971565AA8510560ab41"}),_I=Object.freeze({1:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",100:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",42161:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",8453:"0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"}),Ly={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",8453:"0x4200000000000000000000000000000000000006",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"},OI={1:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",8453:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",42161:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"},dp=Object.freeze({Order:[{name:"sellToken",type:"address"},{name:"buyToken",type:"address"},{name:"receiver",type:"address"},{name:"sellAmount",type:"uint256"},{name:"buyAmount",type:"uint256"},{name:"validTo",type:"uint32"},{name:"appData",type:"bytes32"},{name:"feeAmount",type:"uint256"},{name:"kind",type:"string"},{name:"partiallyFillable",type:"bool"},{name:"sellTokenBalance",type:"string"},{name:"buyTokenBalance",type:"string"}]}),TI=Object.freeze({OrderCancellations:[{name:"orderUids",type:"bytes[]"}]})});function fH(e={}){return(e.baseUrl||process.env.DEFILLAMA_COINS_URL||lH).replace(/\/$/,"")}function CI(e={}){return(e.baseUrl||process.env.DEFILLAMA_API_URL||uH).replace(/\/$/,"")}function mH(e){let t=Array.isArray(e)?e:typeof e=="string"?e.split(","):[];return[...new Set(t.map(n=>String(n??"").trim()).filter(Boolean))].slice(0,100)}async function mn(e,t={}){let n=mH(e);if(!n.length)throw new Error("llamaPrices requires coins[]");let r=n.map(encodeURIComponent).join(",");return A(`${fH(t)}/prices/current/${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function RI(e={}){let n=(await mn(["coingecko:ethereum"],e))?.coins?.["coingecko:ethereum"];return{ok:!!n?.price,ethUsd:n?.price??null}}async function gp(e={}){return A(`${CI(e)}/protocols`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??2e4})}async function LI(e={},t={}){let n=(t.yieldsBaseUrl||process.env.DEFILLAMA_YIELDS_URL||dH).replace(/\/$/,""),r=await A(`${n}/pools`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??3e4}),o=Array.isArray(r?.data)?r.data:[];e.chain&&(o=o.filter(s=>String(s.chain).toLowerCase()===String(e.chain).toLowerCase())),e.project&&(o=o.filter(s=>String(s.project).toLowerCase()===String(e.project).toLowerCase())),e.stablecoin!=null&&(o=o.filter(s=>!!s.stablecoin==!!e.stablecoin)),o.sort((s,a)=>Number(a.tvlUsd||0)-Number(s.tvlUsd||0));let i=Math.min(5e3,Math.max(1,Number(e.limit||o.length||1)));return{...r,data:o.slice(0,i)}}async function yp(e={},t={}){let n=(t.stablecoinsBaseUrl||process.env.DEFILLAMA_STABLECOINS_URL||pH).replace(/\/$/,""),r=e.includePrices!==!1;return A(`${n}/stablecoins?includePrices=${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??3e4})}async function $I(e={},t={}){let n=encodeURIComponent(String(e.chain||"Ethereum")),r=new URLSearchParams({excludeTotalDataChart:String(e.includeChart!==!0),excludeTotalDataChartBreakdown:String(e.includeBreakdown!==!0),dataType:"dailyVolume"});return A(`${CI(t)}/overview/dexs/${n}?${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??3e4})}async function MI(e=["ethereum","bitcoin","solana"],t={}){let n=e.map(i=>`coingecko:${String(i).toLowerCase()}`),r=await mn(n,t),o={};for(let i of e){let s=`coingecko:${String(i).toLowerCase()}`;o[i]=r?.coins?.[s]||null}return o}var lH,uH,dH,pH,Ii=Y(()=>{V();lH="https://coins.llama.fi",uH="https://api.llama.fi",dH="https://yields.llama.fi",pH="https://stablecoins.llama.fi"});var Sp={};vt(Sp,{ACROSS_API:()=>BI,HOP_API:()=>DI,RANGO_API:()=>FI,RELAY_API:()=>UI,acrossHealth:()=>jy,acrossSuggestedFees:()=>bp,hopHealth:()=>Hy,hopQuote:()=>wp,rangoQuote:()=>SH,relayHealth:()=>Vy,relayPrepare:()=>Wy,relayQuote:()=>jc});async function jy(e={}){try{return{ok:!0,estimatedFillTimeSec:(await bp({token:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",destinationToken:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",originChainId:1,destinationChainId:42161,amount:"1000000000000000"},e)).estimatedFillTimeSec}}catch(t){return{ok:!1,error:String(t.message||t).slice(0,160)}}}async function bp(e={},t={}){let{token:n,destinationToken:r=n,originChainId:o,destinationChainId:i,amount:s}=e;if(!n||o==null||i==null||!s)throw new Error("acrossSuggestedFees requires token, originChainId, destinationChainId, amount");let a=new URLSearchParams({token:n,destinationToken:r,originChainId:String(o),destinationChainId:String(i),amount:String(s)}),c=(t.baseUrl||process.env.ACROSS_API_URL||BI).replace(/\/$/,"");return A(`${c}/suggested-fees?${a}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function Hy(e={}){try{let t=await wp({amount:"1000000000000000",token:"ETH",fromChain:"ethereum",toChain:"arbitrum",slippage:.5},e);return{ok:!0,estimatedRecieved:t.estimatedRecieved||t.estimatedReceived}}catch(t){return{ok:!1,error:String(t.message||t).slice(0,160)}}}async function wp(e={},t={}){let{amount:n,token:r="ETH",fromChain:o="ethereum",toChain:i="arbitrum"}=e;if(!n)throw new Error("hopQuote requires amount");let s=e.slippage==null?void 0:Math.round(Number(e.slippage)*100),a=nn({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:o!==i,requestedCapBps:e.maxSlippageBps??e.slippageBps??s});if(!a.executable)throw new Error(`hop: route requires ${a.requiredBps} bps above cap ${a.capBps}`);let c=new URLSearchParams({amount:String(n),token:r,fromChain:o,toChain:i,slippage:String(a.selectedBps/100)}),l=(t.baseUrl||process.env.HOP_API_URL||DI).replace(/\/$/,""),u=await A(`${l}/quote?${c}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),d=u?.estimatedRecieved||u?.estimatedReceived;return d?Ne(u,{chainId:Number(e.originChainId||e.chainId||gH[o]||0),venue:u?.tx?.to||"hop",amountOut:d,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:o!==i,requestedCapBps:e.maxSlippageBps??e.slippageBps??s}):{...u,autoSlippagePolicy:a}}function qI(e){return(e?.steps||[]).flatMap(t=>(t?.items||[]).filter(n=>n?.data?.to&&n?.data?.data).map(n=>({stepId:t.id,...n.data})))}function bH(e){let t=String(e?.data??"").toLowerCase();if(!t.startsWith(zy))return null;if(!/^0x[0-9a-f]{136}$/.test(t))throw new Error("relay: malformed ERC20 approval calldata");return{spender:`0x${t.slice(34,74)}`,amount:BigInt(`0x${t.slice(74,138)}`).toString()}}function wH(e){return qI(e).find(t=>!String(t.data).toLowerCase().startsWith(zy))??null}async function Vy(e={}){try{let t=await jc({user:xo,originChainId:1,destinationChainId:8453,originCurrency:"0x0000000000000000000000000000000000000000",destinationCurrency:"0x0000000000000000000000000000000000000000",amount:"1000000000000000",tradeType:"EXACT_INPUT"},e);return{ok:!0,hasSteps:Array.isArray(t.steps),stepCount:t.steps?.length||0}}catch(t){return{ok:!1,error:String(t.message||t).slice(0,160)}}}async function jc(e={},t={}){let{user:n=xo,originChainId:r,destinationChainId:o,originCurrency:i="0x0000000000000000000000000000000000000000",destinationCurrency:s="0x0000000000000000000000000000000000000000",amount:a,tradeType:c="EXACT_INPUT"}=e;if(r==null||o==null||!a)throw new Error("relayQuote requires originChainId, destinationChainId, amount");let l=nn({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(r)!==Number(o),requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!l.executable)throw new Error(`relay: route requires ${l.requiredBps} bps above cap ${l.capBps}`);let u=(t.baseUrl||process.env.RELAY_API_URL||UI).replace(/\/$/,""),d=await A(`${u}/quote`,{method:"POST",body:{user:n,originChainId:Number(r),destinationChainId:Number(o),originCurrency:i,destinationCurrency:s,amount:String(a),tradeType:c,slippageTolerance:String(l.selectedBps)},fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),p=d?.details?.currencyOut?.amount;if(!p||!/^\d+$/.test(String(p)))return{...d,autoSlippagePolicy:l};let f=wH(d);return Ne(d,{chainId:Number(r),venue:f?.to||"relay",amountOut:p,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,crossChain:Number(r)!==Number(o),requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function Wy(e={},t={}){let n=await jc(e,t),r=Number(e.originChainId),o=qI(n);if(!o.length)throw new Error("relay: quote returned no executable transaction items");let i=String(n?.autoSlippage?.venue||"").toLowerCase(),s=[],a=[];for(let u of o){if(u.chainId!=null&&Number(u.chainId)!==r)throw new Error("relay: transaction chain mismatch");if(e.user&&u.from&&String(u.from).toLowerCase()!==String(e.user).toLowerCase())throw new Error("relay: transaction sender mismatch");let d=bH(u);d?s.push({tx:u,approval:d}):a.push(u)}if(!a.length)throw new Error("relay: quote returned no bridge deposit transaction");if(a.some(u=>String(u.to).toLowerCase()!==i))throw new Error("relay: route execution target is not safely bound");if(s.length>1)throw new Error("relay: multiple token approvals are not supported");let c=null;if(s.length===1){let{tx:u,approval:d}=s[0],p=String(e.originCurrency||"").toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(p)||p===yH)throw new Error("relay: native route returned an ERC20 approval");if(String(u.to).toLowerCase()!==p)throw new Error("relay: approval token mismatch");if(d.amount!==String(e.amount))throw new Error("relay: approval amount must equal the exact input amount");if(!a.some(f=>String(f.to).toLowerCase()===d.spender))throw new Error("relay: approval spender does not match the bridge target");c={token:p,spender:d.spender,amount:String(e.amount)}}let l=o.map(u=>({chainId:r,from:u.from||e.user,to:u.to,data:u.data,value:u.value??"0x0",...u.gasLimit!=null||u.gas!=null?{gasLimit:u.gasLimit??u.gas}:{},...String(u.data).toLowerCase().startsWith(zy)?{}:{slippageGuard:Ye(n.autoSlippage,{chainId:r,venue:u.to,data:u.data})}}));return q({provider:"relay",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:r,quote:n,autoSlippage:n.autoSlippage,requiresApproval:c,destination:i,transactions:l},{provider:"relay",kind:"relay-tx",env:t.env,nowMs:t.nowMs,expiresAtMs:t.expiresAtMs})}async function SH({from:e,to:t,amount:n,slippage:r=1,enableCentralizedSwappers:o=!1}={},i={}){if(!e||!t||!n)throw new Error("rangoQuote requires from, to, amount");let s=i.env??process.env,a=i.rangoApiKey||s.RANGO_API_KEY;if(!a)throw new Error("rango: RANGO_API_KEY is required");let c=new URLSearchParams({from:e,to:t,amount:String(n),slippage:String(r),enableCentralizedSwappers:o?"true":"false",apiKey:a}),l=(i.rangoBaseUrl||process.env.RANGO_API_URL||FI).replace(/\/$/,""),u;try{u=await A(`${l}/basic/quote?${c}`,{fetchImpl:i.fetchImpl,timeoutMs:i.timeoutMs??2e4,retries:i.retries})}catch(d){let p=Number.isInteger(d?.status)?` (HTTP ${d.status})`:"";throw new Error(`rango: request failed${p}`)}if(u?.error||u?.resultType&&u.resultType!=="OK"){let d=String(u?.error||u.resultType).split(a).join("[redacted]").split(encodeURIComponent(a)).join("[redacted]").slice(0,160);throw new Error(`rango: ${d}`)}return{amountOut:u?.route?.outputAmount,feeUsd:u?.route?.feeUsd??null,estimatedTime:u?.route?.estimatedTimeInSeconds}}var BI,DI,UI,FI,gH,zy,yH,Ep=Y(()=>{V();Gt();np();ae();BI="https://across.to/api",DI="https://api.hop.exchange/v1",UI="https://api.relay.link",FI="https://api.rango.exchange",gH={ethereum:1,optimism:10,bsc:56,polygon:137,arbitrum:42161,avalanche:43114,base:8453};zy="0x095ea7b3",yH="0x0000000000000000000000000000000000000000"});function vp(e){if(!Array.isArray(e))return null;let t=0,n=!1;for(let r of e){let o=on(r?.amountUSD);o!=null&&(t+=o,n=!0)}return n?t:null}function jI(e){return Array.isArray(e)?e.flatMap((t,n)=>{let r=String(t?.amountUSD??"").trim();return/^\d+(?:\.\d+)?$/.test(r)?[{name:String(t?.name??t?.type??`cost-${n+1}`),amountUsd:r}]:[]}):[]}async function zI(e,t={}){let n=XA[Number(e)];if(!n)return null;try{let r=await mn([n],t);return on(r?.coins?.[n]?.price)}catch{return null}}async function EH(e={}){try{let t=await gp({...e,baseUrl:e.defillamaApiBaseUrl,timeoutMs:e.defillamaTimeoutMs??Math.min(Number(e.timeoutMs??5e3),5e3)});return Array.isArray(t)?t:[]}catch{return[]}}function vH(e,t={}){let n=Ao(t.tool||t.provider||t.bridge||t.protocol),r=[];return e==="lifi"&&n&&n!=="lifi"&&r.push(...HI[n]||[n]),r.push(...HI[Ao(e)]||[e]),r}function xH(e,t,n={}){let r=Array.isArray(e)?e:[],o=vH(t,n).map(Ao).filter(Boolean);for(let i of o){let s=r.find(c=>Ao(c?.slug)===i||Ao(c?.name)===i),a=on(s?.tvl);if(a!=null)return{liquidityUsd:a,protocol:s?.name??s?.slug??i}}for(let i of o){let s=r.find(c=>{let l=Ao(c?.category);return!l.includes("bridge")&&!l.includes("crosschain")?!1:Ao(c?.slug).includes(i)||Ao(c?.name).includes(i)}),a=on(s?.tvl);if(a!=null)return{liquidityUsd:a,protocol:s?.name??s?.slug??i}}return null}function Gy({chainId:e,tokenIn:t,tokenOut:n,amountIn:r,taker:o,slippageBps:i,decimalsIn:s,decimalsOut:a,nativePriceUsd:c=null,destDecimalsPromise:l=null,v4PoolKey:u=null,v4PoolId:d=null,v4LiquidityUsd:p=null,opts:f={}}){let m=[];return m.push({source:"lifi",run:async()=>{let h=await Lr({fromChain:e,toChain:e,fromToken:t,toToken:n,fromAmount:r},f),g=h?.estimate??h?.[0]?.estimate;return{amountOut:g?.toAmount,minOut:g?.toAmountMin,gasUsd:vp(g?.gasCosts),feeUsd:vp(g?.feeCosts),oracleFeeBps:h?.oracleFee?.applies?h.oracleFee.bps:0,meta:{tool:h?.tool??h?.toolDetails?.name,oracleFee:h?.oracleFee??null}}}}),s!=null&&m.push({source:"paraswap",run:async()=>{let h=a??(await Promise.resolve(l))?.decimals;if(h==null)throw new Error("paraswap needs destination decimals; none supplied or resolvable");let g=await $r({chainId:e,srcToken:t,destToken:n,amount:r,srcDecimals:s,destDecimals:h},f),y=g?.priceRoute;return{amountOut:y?.destAmount,gasUsd:on(y?.gasCostUSD),oracleFeeBps:g?.oracleFee?.applies?g.oracleFee.bps:0,meta:{bestRoute:y?.bestRoute?.[0]?.swaps?.[0]?.swapExchanges?.[0]?.exchange,oracleFee:g?.oracleFee??null}}}}),process.env.ZEROX_API_KEY&&m.push({source:"0x",run:async()=>{let h=await ko({chainId:e,sellToken:t,buyToken:n,sellAmount:r,taker:o},f),g=null,y=h?.totalNetworkFee,b=await Promise.resolve(c);return y!=null&&b&&(g=Number(y)/1e18*b),{amountOut:h?.buyAmount,minOut:h?.minBuyAmount,gasUsd:g,meta:{source:h?.route?.fills?.[0]?.source}}}}),process.env.ONEINCH_API_KEY&&m.push({source:"1inch",run:async()=>{let h=await Bc({chainId:e,src:t,dst:n,amount:r},f),g=null;return h?.gas!=null&&c&&(g=null),{amountOut:h?.dstAmount,gasUsd:g,meta:{gasUnits:h?.gas}}}}),m.push({source:"cow",run:async()=>{let h=await Br({chainId:e,sellToken:t,buyToken:n,sellAmountBeforeFee:String(r),from:o},f),g=h?.quote??h,y=g?.feeAmount;return{amountOut:g?.buyAmount,gasUsd:0,meta:{intent:!0,feeAmountInSellToken:y,settlement:"solver-executed"}}}}),fn[Number(e)]&&m.push({source:"uniswap-v4",run:async()=>{let h=u&&typeof u=="object"?{fee:u.fee,tickSpacing:u.tickSpacing,hooks:u.hooks,poolKey:u,poolId:d,liquidityUsd:p}:{},g=await Eo({chainId:e,tokenIn:t,tokenOut:n,amountIn:r,...h},f);return{amountOut:g?.amountOut,minOut:g?.minOut??g?.amountOutMinimum??null,gasUsd:null,liquidityUsd:g?.liquidityUsd??null,meta:{onchain:!0,venue:"uniswap-v4",fee:g?.fee,tickSpacing:g?.tickSpacing,poolId:g?.poolId,hooks:g?.hooks,gasUnits:g?.gasEstimate,quoter:g?.quoter,poolManager:g?.poolManager,prepareReady:g?.prepareReady===!0,executionReady:!1}}}}),xt[Number(e)]&&m.push({source:"uniswap-v3",run:async()=>{let h=await Rr({chainId:e,tokenIn:t,tokenOut:n,amountIn:r},f);return{amountOut:h?.amountOut,minOut:h?.minOut??h?.amountOutMinimum??null,gasUsd:null,liquidityUsd:h?.liquidityUsd??null,meta:{onchain:!0,fee:h?.fee,gasUnits:h?.gasEstimate,quoter:h?.quoter}}}}),m}function VI({fromChainId:e,toChainId:t,tokenIn:n,tokenOut:r,amountIn:o,taker:i,slippageBps:s,allowedSources:a,opts:c={}}){let l=[],u=null,d=async(f,m={})=>(u||=EH(c),xH(await u,f,m));if(l.push({source:"lifi",run:async()=>{let f=await Lr({fromChain:e,toChain:t,fromToken:n,toToken:r,fromAmount:o,fromAddress:i,slippageBps:s},c),m=f?.estimate??f?.[0]?.estimate,h=(f?.includedSteps??f?.steps??[]).map((b,S)=>({id:String(b?.id??`step-${S+1}`),type:String(b?.type??"route"),tool:String(b?.tool??b?.toolDetails?.name??"LI.FI"),fromChainId:Number(b?.action?.fromChainId??e),toChainId:Number(b?.action?.toChainId??t)})),g={tool:f?.tool??f?.toolDetails?.name,durationSeconds:on(m?.executionDuration),destinationDecimals:on(f?.action?.toToken?.decimals),routeSteps:h,feeCosts:jI(m?.feeCosts),gasCosts:jI(m?.gasCosts)},y=await d("lifi",g);return{amountOut:m?.toAmount,minOut:m?.toAmountMin,gasUsd:vp(m?.gasCosts),feeUsd:vp(m?.feeCosts),feeIncludedInAmountOut:!0,oracleFeeBps:f?.oracleFee?.applies?f.oracleFee.bps:0,liquidityUsd:y?.liquidityUsd??null,meta:{...g,liquidityProtocol:y?.protocol,oracleFee:f?.oracleFee??null}}}}),l.push({source:"relay",run:async()=>{let{relayQuote:f}=await Promise.resolve().then(()=>(Ep(),Sp)),m=await f({user:i,originChainId:e,destinationChainId:t,originCurrency:n,destinationCurrency:r,amount:String(o),slippageBps:s},c),h=m?.details,g=(m?.steps??[]).map((x,v)=>({id:String(x?.id??`step-${v+1}`),type:String(x?.kind??"transaction"),tool:"Relay",label:String(x?.description??x?.action??x?.id??`Step ${v+1}`),fromChainId:Number(e),toChainId:Number(t)})),y=String(m?.fees?.relayer?.amountUsd??"").trim(),b=String(m?.fees?.gas?.amountUsd??"").trim(),S=String(h?.totalImpact?.usd??"").trim(),w={durationSeconds:on(h?.timeEstimate),rate:h?.rate,destinationDecimals:on(h?.currencyOut?.currency?.decimals),routeSteps:g,feeCosts:[.../^\d+(?:\.\d+)?$/.test(y)?[{name:"relayer",amountUsd:y}]:[],.../^-?\d+(?:\.\d+)?$/.test(S)?[{name:"total-impact",amountUsd:S}]:[]],gasCosts:/^\d+(?:\.\d+)?$/.test(b)?[{name:"origin-gas",amountUsd:b}]:[]},E=await d("relay",w);return{amountOut:h?.currencyOut?.amount,minOut:h?.currencyOut?.minimumAmount,gasUsd:on(m?.fees?.gas?.amountUsd),feeUsd:on(m?.fees?.relayer?.amountUsd)??(on(h?.totalImpact?.usd)!=null?Math.abs(on(h.totalImpact.usd)):null),feeIncludedInAmountOut:!0,liquidityUsd:E?.liquidityUsd??null,meta:{...w,liquidityProtocol:E?.protocol}}}}),l.push({source:"across",run:async()=>{let{acrossSuggestedFees:f}=await Promise.resolve().then(()=>(Ep(),Sp)),m=await f({token:n,destinationToken:r,originChainId:e,destinationChainId:t,amount:String(o)},c),h=m?.totalRelayFee?.total,g=null;if(h!=null)try{let b=BigInt(String(o))-BigInt(String(h));b>0n&&(g=b.toString())}catch{}let y=await d("across");return{amountOut:g,gasUsd:null,liquidityUsd:y?.liquidityUsd??null,meta:{derivedFromFees:!0,durationSeconds:on(m?.estimatedFillTimeSec),limits:m?.limits?{min:m.limits.minDeposit,max:m.limits.maxDeposit}:void 0,liquidityProtocol:y?.protocol}}}}),!Array.isArray(a))return l;let p=new Set(a.map(f=>String(f).toLowerCase()));return l.filter(f=>p.has(f.source))}var on,Ao,HI,WI=Y(()=>{Rc();Lc();$c();Ny();qc();xi();Ps();Ii();ly();on=e=>{let t=Number(e);return Number.isFinite(t)?t:null};Ao=e=>String(e??"").toLowerCase().replace(/[^a-z0-9]/g,""),HI=Object.freeze({across:["across"],relay:["relaychain","relay"],lifi:["jumper-(li.fi-powered)","lifi"],stargate:["stargate-v2","stargate-v1","stargate"],hop:["hop-protocol","hop"],debridge:["debridge"],synapse:["synapse"],connext:["connext"],cbridge:["celer-bridge","celer-cbridge","cbridge"],celer:["celer-bridge","celer-cbridge","cbridge"],squid:["squid"],symbiosis:["symbiosis"],wormhole:["wormhole"],mayan:["mayan"],allbridge:["allbridge"],thorchain:["thorchain"]})});var JI={};vt(JI,{BRIDGE_REVIEW_SOURCES:()=>Ky,QUALITY:()=>Nn,bestBridgeRoute:()=>IH,bestSwapRoute:()=>Yy,formatComparisonNote:()=>xp,normalizeBridgeRouteOptions:()=>KI});function GI(e,t,n){let r=t.find(i=>ks(i));if(r==null)return null;let o=Ec(r)?.name||`chain ${r}`;return{kind:e,...n,best:null,routes:[],failed:[],improvementBps:null,spreadBasis:null,rankedOn:null,warnings:[],unsupported:!0,readOnlyChain:Number(r),sourcesTried:0,sourcesAnswered:0,note:`${o} (${r}) is registered read-only: no swap venue or route source covers it. This is UNSUPPORTED, not a failed quote. Oracle reads balances and calls there; it does not quote or prepare.`}}function AH(e){let t=e==null?50:Number(e);if(!Number.isInteger(t)||t<1||t>100)throw new Error("slippageBps must be an integer from 1 through 100");return t}function KI(e,t=Ky){let n=new Set((Array.isArray(t)?t:Ky).map(s=>String(s).toLowerCase())),r=(e?.routes??[]).filter(s=>n.has(s.source)),o=new Set(r.map(s=>s.source)),i=(e?.failed??[]).filter(s=>n.has(s.source)&&!o.has(s.source));return[...r,...i].map(s=>({provider:s.source,status:s.quality===Nn.FAILED?"unavailable":"quoted",amountOut:s.amountOut??null,minAmountOut:s.minOut??null,netAmountOut:s.netOut??null,feeUsd:s.feeUsd??null,gasUsd:s.gasUsd??null,etaSeconds:s.meta?.durationSeconds??null,decimalsOut:s.meta?.destinationDecimals??null,routeSteps:Array.isArray(s.meta?.routeSteps)?s.meta.routeSteps:[],feeCosts:Array.isArray(s.meta?.feeCosts)?s.meta.feeCosts:[],gasCosts:Array.isArray(s.meta?.gasCosts)?s.meta.gasCosts:[],selected:s.source===e?.best?.source,error:s.error??null}))}async function YI(e,t,n){let r=kH[Number(e)];if(!r)return{priceUsd:null,decimals:null};let o=`${r}:${t}`;try{let s=(await mn([o],n))?.coins?.[o],a=Number(s?.price),c=Number(s?.decimals);return{priceUsd:Number.isFinite(a)?a:null,decimals:Number.isFinite(c)?c:null}}catch{return{priceUsd:null,decimals:null}}}async function Yy(e,t={}){let{chainId:n,tokenIn:r,tokenOut:o,amountIn:i}=e;if(n==null||!r||!o||i==null)throw new Error("bestSwapRoute requires chainId, tokenIn, tokenOut, amountIn");let s=GI("swap",[n],{chainId:n,tokenIn:r,tokenOut:o,amountIn:String(i)});if(s)return s;let a=zI(n,t),c=YI(n,o,t),l=Tg(n,t).catch(()=>null),u=Gy({...e,nativePriceUsd:a,decimalsOut:e.decimalsOut,destDecimalsPromise:c,opts:t}),[d,p,f]=await Promise.all([tp(u,{timeoutMs:t.timeoutMs??12e3}),c,l]);a.catch(()=>{});let m=await a.then(y=>y,()=>null),h=cy(d,{destPriceUsd:p.priceUsd,destDecimals:e.decimalsOut??p.decimals,liquidityBandBps:t.liquidityBandBps??50,gasPriceWei:f,nativePriceUsd:m}),g=t.maxImpactPct===void 0?25:t.maxImpactPct;if(g!=null&&h.best){let y=h.best.source,S=await QA(async w=>{let E=Gy({...e,amountIn:w.toString(),nativePriceUsd:a,decimalsOut:e.decimalsOut,destDecimalsPromise:c,opts:t}).filter(v=>v.source===y);return E.length?(await tp(E,{timeoutMs:t.timeoutMs??12e3}))?.[0]?.amountOut??null:null},i);if(S){let w=ZA(h,{[y]:S},{maxImpactPct:g});return{kind:"swap",chainId:n,tokenIn:r,tokenOut:o,amountIn:String(i),...w,sourcesTried:u.length,sourcesAnswered:d.filter(E=>E.quality!==Nn.FAILED).length,note:xp(w,u.length),priceImpact:{[y]:Number(S.impactPct.toFixed(2))}}}}return{kind:"swap",chainId:n,tokenIn:r,tokenOut:o,amountIn:String(i),...h,sourcesTried:u.length,sourcesAnswered:d.filter(y=>y.quality!==Nn.FAILED).length,note:xp(h,u.length)}}async function IH(e,t={}){let{fromChainId:n,toChainId:r,tokenIn:o,tokenOut:i,amountIn:s}=e;if(n==null||r==null||!o||!i||s==null)throw new Error("bestBridgeRoute requires fromChainId, toChainId, tokenIn, tokenOut, amountIn");if(Number(n)===Number(r))throw new Error("bestBridgeRoute is for cross-chain; use bestSwapRoute for same-chain");let a=GI("bridge",[n,r],{fromChainId:n,toChainId:r,tokenIn:o,tokenOut:i,amountIn:String(s)});if(a)return a;let c=AH(e.slippageBps),l={...e,slippageBps:c},u=YI(r,i,t),d=VI({...l,opts:t}),[p,f]=await Promise.all([tp(d,{timeoutMs:t.timeoutMs??15e3}),u]),m=cy(p,{destPriceUsd:f.priceUsd,destDecimals:e.decimalsOut??f.decimals,liquidityFirst:!1,liquidityBandBps:0}),h=m.routes.map(g=>({source:g.source,seconds:g.meta?.durationSeconds??null})).filter(g=>g.seconds!=null);return{kind:"bridge",fromChainId:n,toChainId:r,tokenIn:o,tokenOut:i,amountIn:String(s),slippageBps:c,...m,routeOptions:KI(m,e.allowedSources),durations:h,sourcesTried:d.length,sourcesAnswered:p.filter(g=>g.quality!==Nn.FAILED).length,note:xp(m,d.length)}}function _H(e){let t=e?.meta?.oracleFee;return t?.applies?` \xB7 ${rI(t)}`:""}function xp(e,t){if(!e.best)return"no source returned a usable route";let n=e.routes.length,r=_H(e.best);if(n===1)return`only 1 of ${t} sources answered, so this is the ONLY route, not a proven best one. Treat it as unbenchmarked.`+r;if(e.improvementBps!=null){let o=e.improvementBps,i=o/100;if(o<.01)return`best of ${n} routes, ranked on ${e.rankedOn}: effectively tied with the runner-up (${e.spreadBasis}), inside quote noise. Re-quote before you size up.`+r;let s=i>=.01?`${i.toFixed(2)}%`:`${o.toFixed(2)}bps`;return`best of ${n} routes, ranked on ${e.rankedOn}: ${s} better than the runner-up (${e.spreadBasis})`+r}return`best of ${n} routes, ranked on ${e.rankedOn}. No spread quoted: the top routes report cost differently, so the margin is not comparable.`+r}var kH,Ky,Jy=Y(()=>{ly();WI();Cc();Ii();De();Si();kH={1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avax"},Ky=Object.freeze(["lifi","relay"])});function Ti(e,t,{required:n=!0,allowZero:r=!1}={}){if(e==null||e===""){if(n)throw new Error(`${t} required`);return null}let o;if(typeof e=="bigint")o=e;else if(typeof e=="number"){if(!Number.isSafeInteger(e))throw new Error(`${t} must be a safe integer`);o=BigInt(e)}else if(typeof e=="string"){let i=e.trim();if(i.startsWith("0x")||i.startsWith("0X"))o=BigInt(i);else{if(!FH.test(i))throw new Error(`${t} must be an integer wei string`);o=BigInt(i)}}else throw new Error(`${t} must be bigint, number, or integer string`);if(o<0n||!r&&o===0n)throw new Error(`${t} must be ${r?"non-negative":"positive"}`);return o}function qH(e){let t=Number(e);if(!Number.isSafeInteger(t)||t<=0)throw new Error("chainId must be a positive integer");return t}function jH(e={}){return e.maxFeePerGas!=null?Ti(e.maxFeePerGas,"maxFeePerGas"):e.gasPrice!=null?Ti(e.gasPrice,"gasPrice"):null}function nb(e={}){try{let t=qH(e.chainId??e.tx?.chainId),n=e.tx||e,r=e.policy||e,o=r.grant?.maxGasWei??e.grant?.maxGasWei,i=Ti(r.maxTotalGasWei??r.maxGasWei??o,"maxTotalGasWei"),s=Ti(n.gasLimit??n.gas,"gasLimit"),a=jH(n);if(a==null)throw new Error("maxFeePerGas or gasPrice required");let c=Ti(r.maxFeePerGasWei,"maxFeePerGasWei",{required:!1}),l=Ti(r.maxPriorityFeePerGasWei,"maxPriorityFeePerGasWei",{required:!1}),u=n.maxPriorityFeePerGas==null?null:Ti(n.maxPriorityFeePerGas,"maxPriorityFeePerGas"),d=s*a;return d>i?{ok:!1,status:"BLOCK",reason:`total gas ${d} exceeds cap ${i}`,chainId:t,totalGasWei:d.toString(),maxTotalGasWei:i.toString()}:c!=null&&a>c?{ok:!1,status:"BLOCK",reason:`unit fee ${a} exceeds cap ${c}`,chainId:t,unitFeeWei:a.toString(),maxFeePerGasWei:c.toString(),totalGasWei:d.toString(),maxTotalGasWei:i.toString()}:u!=null&&l!=null&&u>l?{ok:!1,status:"BLOCK",reason:`priority fee ${u} exceeds cap ${l}`,chainId:t,priorityFeeWei:u.toString(),maxPriorityFeePerGasWei:l.toString(),totalGasWei:d.toString(),maxTotalGasWei:i.toString()}:{ok:!0,status:"PASS",reason:"gas envelope within NFT mint gas-war caps",chainId:t,totalGasWei:d.toString(),maxTotalGasWei:i.toString(),unitFeeWei:a.toString(),maxFeePerGasWei:c?.toString()??null,priorityFeeWei:u?.toString()??null,maxPriorityFeePerGasWei:l?.toString()??null}}catch(t){return{ok:!1,status:"BLOCK",reason:String(t?.message||t)}}}function d_(e={}){let t=nb(e);if(!t.ok)throw new tb(t);return t}var FH,tb,rb=Y(()=>{FH=/^(0|[1-9][0-9]*)$/,tb=class extends Error{constructor(t){super(`nft gas-war limit: ${t.reason}`),this.name="NftGasWarLimitError",this.verdict=t}}});var pb={};vt(pb,{OPENSEA_ACCOUNT_CHAINS:()=>w_,OPENSEA_API:()=>y_,OPENSEA_EVM_CHAIN_IDS:()=>Vc,OPENSEA_NATIVE_PAYMENT_TOKEN:()=>YH,OPENSEA_ROBINHOOD_WETH:()=>JH,SEAPORT_FULFILL_ADVANCED_ORDER:()=>b_,openseaAccountNfts:()=>Hs,openseaAccountPnl:()=>zc,openseaBestListing:()=>Gc,openseaBestListings:()=>_p,openseaBestOffer:()=>Kc,openseaCollection:()=>js,openseaCollectionStats:()=>k_,openseaContext:()=>t9,openseaFloor:()=>ab,openseaHealth:()=>sb,openseaPrepareBuy:()=>lb,openseaPrepareCancel:()=>db,openseaPrepareList:()=>Jc,openseaPrepareMint:()=>Yc,openseaPrepareSweep:()=>ub});import{readFileSync as HH,existsSync as zH}from"node:fs";import{getAddress as VH,Interface as Ip,TypedDataEncoder as ib,parseUnits as WH}from"ethers";function XH(){let e=process.env.OPENSEA_ENV_FILE||`${process.env.HOME||""}/.config/locals-only/opensea.env`;if(!zH(e))return"";try{for(let t of HH(e,"utf8").split(`
|
|
8
|
-
`)){let n=t.match(/^\s*OPENSEA_API_KEY\s*=\s*(.+)\s*$/);if(n)return n[1].replace(/^["']|["']$/g,"").trim()}}catch{}return""}function fr(e={}){return e.apiKey?e.apiKey:e.allowAmbientCredentials===!1||e.allowDiskCredentials===!1?e.env?.OPENSEA_API_KEY||e.env?.OPEN_SEA_API_KEY||"":e.env?.OPENSEA_API_KEY||process.env.OPENSEA_API_KEY||process.env.OPEN_SEA_API_KEY||XH()}function E_(e={}){return Ue({provider:"opensea",defaultUrl:y_,hosts:["api.opensea.io","testnets-api.opensea.io"],url:e.baseUrl||process.env.OPENSEA_API_URL})}function Ur(e={}){return E_(e).baseUrl}function Fr(e={}){return Je({accept:"application/json"},{"x-api-key":fr(e)},E_(e).trusted)}function v_(e){let t=String(e||"ethereum").trim().toLowerCase();if(!KH.has(t))throw new Error(`opensea: unsupported account chain ${t}`);return t}function pe(e,t="address"){try{return VH(String(e||"").trim().toLowerCase())}catch{throw new Error(`opensea: invalid ${t}`)}}function x_(e,t=null){let n=String(e||"").trim();if(!n)throw new Error("opensea: account address required");if(t&&!S_.has(t)||!t&&/^0x[0-9a-fA-F]{40}$/.test(n))return pe(n,"account address");if(!/^[1-9A-HJ-NP-Za-km-z]{32,64}$/.test(n))throw new Error("opensea: invalid account address");return n}function QH(e,t){let n=String(e??"").trim();if(!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(n)||Number(n)<=0)throw new Error(`opensea: ${t} must be a positive plain decimal`);return n}function ZH(e,t){let n=Number(e);if(!Number.isSafeInteger(n)||n<=0)throw new Error(`opensea: ${t} must be a positive integer`);return n}function p_(e,t){let n=String(e||"").trim(),r=Date.parse(n);if(!n||!Number.isFinite(r))throw new Error(`opensea: ${t} must be an ISO 8601 timestamp`);return{text:new Date(r).toISOString(),ms:r}}function e9(e={},t,n){return{chain:t,owner:n,contract:e.contract||null,tokenId:e.identifier==null?null:String(e.identifier),tokenStandard:e.token_standard||null,quantity:e.quantity==null&&e.balance==null?null:String(e.quantity??e.balance),collection:e.collection||null,name:e.name||null,description:e.description||null,imageUrl:e.display_image_url||e.image_url||e.original_image_url||null,originalImageUrl:e.original_image_url||e.image_url||null,animationUrl:e.display_animation_url||e.original_animation_url||null,metadataUrl:e.metadata_url||null,marketplaceUrl:e.opensea_url||null,estimatedValueUsd:e.estimated_value_usd!=null&&Number.isFinite(Number(e.estimated_value_usd))?Number(e.estimated_value_usd):null,spam:e.is_disabled===!0,disabled:e.is_disabled===!0,nsfw:e.is_nsfw===!0,traits:Array.isArray(e.traits)?e.traits:[],updatedAt:e.updated_at||null,acquisitionCost:null,itemPnl:{status:"unavailable",reason:"OpenSea account inventory does not expose trustworthy per-item acquisition cost"}}}function t9(e={}){return{base:Ur(e),headers:Fr(e),fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs}}async function sb(e={}){if(!fr(e))return{ok:!1,configured:!1,error:"OPENSEA_API_KEY not set"};try{let t=await js("boredapeyachtclub",e);return{ok:!0,configured:!0,name:t.name||t.collection}}catch(t){return{ok:!1,configured:!0,error:String(t.message||t).slice(0,160)}}}async function js(e,t={}){if(!e)throw new Error("collection slug required");if(!fr(t))throw new Error("OPENSEA_API_KEY required");return A(`${Ur(t)}/collections/${encodeURIComponent(e)}`,{headers:Fr(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function k_(e,t={}){if(!e)throw new Error("collection slug required");if(!fr(t))throw new Error("OPENSEA_API_KEY required");return A(`${Ur(t)}/collections/${encodeURIComponent(e)}/stats`,{headers:Fr(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function ab(e,t={}){let n=await js(e,t),r=n.stats||n.total||{},o=n.floor_price??n.floorPrice??r.floor_price??r.floorPrice??null;if(o==null){let d=await k_(e,t);r=d?.total||d?.stats||d||{},o=r.floor_price??r.floorPrice??null}let i=(Array.isArray(n.contracts)?n.contracts:[]).map(d=>({chain:String(d?.chain||d?.chain_identifier||n.chain||"").trim().toLowerCase(),address:String(d?.address||d?.contract_address||d?.contract||"").trim()})).filter(d=>d.chain&&d.address),s=String(t.expectedChain||"").trim().toLowerCase(),a=String(t.expectedContract||"").trim(),c=null;if(s&&a){let d=p=>s==="solana"?p:p.toLowerCase();if(c=i.find(p=>p.chain===s&&d(p.address)===d(a))||null,!c)throw new Error("opensea: collection identity does not match held contract")}let l=c?.chain||String(n.chain||"").trim().toLowerCase()||i[0]?.chain||"",u=String(n.floor_price_symbol||n.floorPriceSymbol||r.floor_price_symbol||r.floorPriceSymbol||"").trim().toUpperCase()||null;return{slug:n.collection||e,name:n.name||null,floor:o,chain:l||null,contracts:i,currency:u,totalSupply:n.total_supply??r.total_supply??null,numOwners:n.num_owners??r.num_owners??null,raw:{contracts:i,fees:n.fees,category:n.category}}}async function Hs(e={},t={}){if(!fr(t))throw new Error("OPENSEA_API_KEY required");let n=v_(e.chain),r=x_(e.address||e.owner,n),o=Math.min(Math.max(Number(e.pageSize??e.limit??200)||200,1),200),i=Math.min(Math.max(Number(e.maxPages??5)||5,1),25),s=[],a=e.next?String(e.next):null,c=0;do{let l=new URL(`${Ur(t)}/chain/${encodeURIComponent(n)}/account/${encodeURIComponent(r)}/nfts`);l.searchParams.set("limit",String(o)),e.collection&&l.searchParams.set("collection",String(e.collection)),a&&l.searchParams.set("next",a);let u=await A(l.toString(),{headers:Fr(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4});for(let d of Array.isArray(u?.nfts)?u.nfts:[])s.push(e9(d,n,r));a=u?.next?String(u.next):null,c+=1}while(a&&c<i);return{provider:"opensea-nft",source:"opensea-account-inventory",chain:n,owner:r,count:s.length,pages:c,complete:!a,next:a,nfts:s,exec:!1,readOnly:!0}}async function zc(e={},t={}){if(!fr(t))throw new Error("OPENSEA_API_KEY required");let n=x_(e.address||e.owner),r=await A(`${Ur(t)}/account/${encodeURIComponent(n)}/pnl`,{headers:Fr(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4});return{provider:"opensea-nft",source:"opensea-indexed-account-pnl",address:n,scope:"OpenSea-indexed account trading PnL across supported currencies, not per-item NFT cost basis",methodology:"provider-indexed",realizedPnlUsd:r?.realized_pnl_usd??null,unrealizedPnlUsd:r?.unrealized_pnl_usd??null,totalPnlUsd:r?.total_pnl_usd??null,netInvestedUsd:r?.net_invested_usd??null,currentValueUsd:r?.current_value_usd??null,returnPercentage:r?.return_percentage??null,itemLevelPnlAvailable:!1,raw:r,exec:!1,readOnly:!0}}function Wc(e){let t=String(e||"").trim().toLowerCase(),n=Vc[t];if(!n)throw new Error(`opensea: unsupported EVM chain ${t||"(missing)"}`);return{chain:t,chainId:n}}function sn(e,t,{positive:n=!1}={}){let r=String(e??"").trim();if(!/^\d+$/.test(r))throw new Error(`opensea: ${t} must be an unsigned integer`);let o=BigInt(r);if(n&&o<=0n)throw new Error(`opensea: ${t} must be positive`);return o}function n9(e,t="transaction value"){let n;try{let r=String(e??"0").trim();if(!/^(?:0x[0-9a-fA-F]+|\d+)$/.test(r))throw new Error("invalid");n=BigInt(r)}catch{throw new Error(`opensea: ${t} must be a non-negative integer quantity`)}if(n<0n)throw new Error(`opensea: ${t} must be non-negative`);return{amount:n,hex:`0x${n.toString(16)}`}}function Hc(e){let t=String(e??"").trim();if(!/^\d+$/.test(t))throw new Error("opensea: tokenId must be an unsigned integer string");return t}function A_(e,t=10){let n=Number(e??1);if(!Number.isSafeInteger(n)||n<1||n>t)throw new Error(`opensea: quantity must be an integer from 1 through ${t}`);return n}function I_(e,t,n="listing expiry"){let r=e==null?"":String(e).trim(),o;if(/^\d+$/.test(r)){let i=Number(r);o=r.length<=10?i*1e3:i}else o=Date.parse(r);if(!r||!Number.isFinite(o))throw new Error(`opensea: ${n} missing or invalid`);if(o<=t)throw new Error(`opensea: ${n} is expired or stale`);return new Date(o).toISOString()}function r9(e){return!!e&&typeof e=="object"&&[0,1].includes(Number(e.itemType))}function o9(e,t){let n=Number(e?.itemType);if(![0,1].includes(n))throw new Error(`opensea: ${t} is not a native or ERC20 payment item`);let r=pe(e?.token,t);if(n===0&&r!==qs)throw new Error(`opensea: ${t} native payment item must use the zero address`);if(n===1&&r===qs)throw new Error(`opensea: ${t} ERC20 payment item must name a non-zero token contract`);return r}function i9(e,t){let n=sn(e?.startAmount,`${t} startAmount`),r=sn(e?.endAmount??e?.startAmount,`${t} endAmount`);if(n!==r)throw new Error(`opensea: ${t} must be a fixed amount, not a decaying range`);return n}function ob(e,t,{required:n=!0}={}){let r=(Array.isArray(e)?e:[]).filter(r9);if(!r.length){if(n)throw new Error(`opensea: ${t} contains no native or ERC20 payment item`);return{paymentToken:null,totalWei:0n,count:0}}let o=null,i=0n;for(let s of r){let a=o9(s,`${t} payment token`);if(o==null)o=a;else if(a!==o)throw new Error(`opensea: ${t} mixes more than one payment token`);i+=i9(s,`${t} payment amount`)}return{paymentToken:o,totalWei:i,count:r.length}}function hn(e,t){let n=String(e??"").trim();if(!/^\d+$/.test(n))throw new Error(`opensea: ${t} must be an unsigned integer`);return n}function f_(e,t){let n=String(e??"").trim().toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(n))throw new Error(`opensea: ${t} must be a 32-byte hex value`);return n}function __(e,t){return{itemType:Number(hn(e?.itemType,`${t} itemType`)),token:pe(e?.token,`${t} token`),identifierOrCriteria:hn(e?.identifierOrCriteria,`${t} identifierOrCriteria`),startAmount:hn(e?.startAmount,`${t} startAmount`),endAmount:hn(e?.endAmount,`${t} endAmount`)}}function a9(e,t){return{...__(e,t),recipient:pe(e?.recipient,`${t} recipient`)}}function c9(e,t){if(!e||typeof e!="object")throw new Error(`opensea: ${t} has no canonical Seaport protocol parameters`);let n=Array.isArray(e.offer)?e.offer:null,r=Array.isArray(e.consideration)?e.consideration:null;if(!n||!n.length)throw new Error(`opensea: ${t} canonical offer array is missing`);if(!r||!r.length)throw new Error(`opensea: ${t} canonical consideration array is missing`);return{offerer:pe(e.offerer,`${t} offerer`),zone:pe(e.zone,`${t} zone`),offer:n.map((o,i)=>__(o,`${t} offer[${i}]`)),consideration:r.map((o,i)=>a9(o,`${t} consideration[${i}]`)),orderType:Number(hn(e.orderType,`${t} orderType`)),startTime:hn(e.startTime,`${t} startTime`),endTime:hn(e.endTime,`${t} endTime`),zoneHash:f_(e.zoneHash,`${t} zoneHash`),salt:hn(e.salt,`${t} salt`),conduitKey:f_(e.conduitKey,`${t} conduitKey`),counter:hn(e.counter,`${t} counter`)}}function O_(e,t,n){let r=String(e?.order_hash??e?.orderHash??"").trim().toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(r))throw new Error(`opensea: invalid ${n} order hash`);let o=c9(t,n);if(ib.hashStruct("OrderComponents",s9,o).toLowerCase()!==r)throw new Error(`opensea: ${n} order hash does not match its canonical Seaport parameters`);return r}function T_(e,t){let n=Number(e?.itemType);if([4,5].includes(n))throw new Error(`opensea: ${t} is a criteria item, not a fixed token`);if(![2,3].includes(n))throw new Error(`opensea: ${t} must be an ERC-721 or ERC-1155 item`);let r=pe(e?.token,`${t} contract`),o=Hc(e?.identifierOrCriteria),i=sn(e?.startAmount,`${t} startAmount`,{positive:!0}),s=sn(e?.endAmount??e?.startAmount,`${t} endAmount`,{positive:!0});if(i!==s)throw new Error(`opensea: ${t} must be a fixed quantity, not a decaying range`);if(n===2&&i!==1n)throw new Error(`opensea: ${t} ERC-721 quantity must be exactly 1`);if(i>BigInt(Number.MAX_SAFE_INTEGER))throw new Error(`opensea: ${t} quantity exceeds safe integer range`);return{itemType:n,contract:r,tokenId:o,quantity:Number(i)}}function l9(e,t){let n=Array.isArray(e?.offer)?e.offer:[];if(n.some(o=>[4,5].includes(Number(o?.itemType))))throw new Error(`opensea: ${t} uses a criteria offer item, not a fixed token`);let r=n.filter(o=>[2,3].includes(Number(o?.itemType)));if(r.length!==1||n.length!==1)throw new Error(`opensea: ${t} must offer exactly one fixed ERC-721 or ERC-1155 item`);return T_(r[0],`${t} offer NFT`)}function u9(e,t,n){let r=Array.isArray(e?.consideration)?e.consideration:[];if(r.some(s=>[4,5].includes(Number(s?.itemType))))throw new Error(`opensea: ${n} uses a criteria consideration item, not a fixed token`);let o=r.filter(s=>[2,3].includes(Number(s?.itemType)));if(o.length!==1)throw new Error(`opensea: ${n} must require exactly one fixed ERC-721 or ERC-1155 consideration item`);let i=T_(o[0],`${n} consideration NFT`);if(i.tokenId!==t)throw new Error(`opensea: ${n} consideration token does not match the requested token`);return i}function d9(e,t,n,r){if(!(!e||typeof e!="object")){if(e.contract!=null&&String(e.contract).trim()!==""&&pe(e.contract,`${r} display contract`)!==t)throw new Error(`opensea: ${r} display asset contract disagrees with the canonical Seaport offer`);if(e.identifier!=null&&String(e.identifier).trim()!==""&&String(e.identifier).trim()!==n)throw new Error(`opensea: ${r} display asset token disagrees with the canonical Seaport offer`)}}function p9(e){let t=String(e??"").trim();return/^\d+$/.test(t)?t.length<=10?Number(t):Math.floor(Number(t)/1e3):Math.floor(Date.parse(t)/1e3)}function N_(e,t,n,r){let o=hn(t?.startTime,`${r} startTime`),i=hn(t?.endTime,`${r} endTime`),s=BigInt(Math.floor(n/1e3));if(BigInt(o)>s)throw new Error(`opensea: ${r} canonical startTime is in the future`);if(BigInt(i)<=s)throw new Error(`opensea: ${r} canonical endTime is expired or stale`);let a=I_(i,n,`${r} expiry`),c=e?.expiration_time??e?.expirationTime;if(c!=null&&String(c).trim()!==""&&p9(c)!==Number(i))throw new Error(`opensea: ${r} display expiry disagrees with the canonical order endTime`);return a}function f9(e,t,n){if(!e||typeof e!="object")throw new Error("opensea: invalid best listing");let r=String(e.chain||"").trim().toLowerCase();if(r!==t.chain)throw new Error("opensea: OpenSea returned a listing for the wrong chain");if(Vc[r]!==t.chainId)throw new Error("opensea: OpenSea listing chain id mismatch");if(String(e.status||"").toUpperCase()!=="ACTIVE")throw new Error("opensea: OpenSea returned a non-active listing");let i=e.protocol_data?.parameters,s=l9(i,"listing"),a=s.contract;if(t.contract&&a!==t.contract)throw new Error("opensea: OpenSea returned a listing for the wrong contract");let c=s.tokenId;d9(e.asset,a,c,"listing");let l=sn(e.price?.current?.value,"listing price",{positive:!0}),u=O_(e,i,"listing"),d=ob(i?.consideration,"listing consideration");if(d.totalWei!==l)throw new Error("opensea: listing consideration total does not equal the quoted listing price");return{orderHash:u,chain:t.chain,chainId:t.chainId,protocolAddress:pe(e.protocol_address,"listing protocol address"),contract:a,tokenId:c,quantity:s.quantity,priceWei:l.toString(),paymentToken:d.paymentToken,currency:String(e.price?.current?.currency||"").trim()||null,decimals:Number(e.price?.current?.decimals??18),expiry:N_(e,i,n,"listing"),counter:hn(i?.counter,"listing counter")}}async function _p(e={},t={}){if(!fr(t))throw new Error("OPENSEA_API_KEY required");let n=Wc(e.chain);n.contract=e.contract?pe(e.contract,"NFT contract"):null;let r=String(e.slug||"").trim();if(!r)throw new Error("opensea: collection slug required");let o=Number(e.limit??12);if(!Number.isSafeInteger(o)||o<1||o>50)throw new Error("opensea: listing limit must be 1 through 50");let i=new URL(`${Ur(t)}/listings/collection/${encodeURIComponent(r)}/best`);i.searchParams.set("limit",String(o)),e.next&&i.searchParams.set("next",String(e.next));let s=await A(i.toString(),{headers:Fr(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),a=Array.isArray(s?.listings)?s.listings:[];if(!a.length)throw new Error("opensea: no active best listings returned");let c=Number.isFinite(Number(t.nowMs))?Number(t.nowMs):Date.now();return{provider:"opensea-nft",source:"opensea-best-listings",chain:n.chain,chainId:n.chainId,slug:r,contract:n.contract,listings:a.map(l=>f9(l,n,c)),next:s?.next?String(s.next):null,exec:!1,readOnly:!0}}async function Gc(e={},t={}){let n=Hc(e.tokenId),r=Math.min(Math.max(Number(e.maxPages??20)||20,1),25),o=e.next?String(e.next):null,i=new Set;for(let s=1;s<=r;s+=1){let a=await _p({...e,tokenId:void 0,limit:50,next:o},t),c=a.listings.find(l=>l.tokenId===n);if(c)return{provider:"opensea-nft",source:"opensea-best-exact-listing",...c,pagesScanned:s,exact:!0,exec:!1,readOnly:!0};if(!a.next||i.has(a.next))break;i.add(a.next),o=a.next}throw new Error("opensea: no active exact NFT listing returned within page bound")}function m9(e,t,n,r){if(!e||typeof e!="object")throw new Error("opensea: invalid best offer");if(String(e.chain||"").trim().toLowerCase()!==t.chain)throw new Error("opensea: OpenSea returned an offer for the wrong chain");if(String(e.status||"").toUpperCase()!=="ACTIVE")throw new Error("opensea: OpenSea returned a non-active offer");let i=e.protocol_data?.parameters||{},a=u9(i,n,"offer").contract;if(t.contract&&a!==t.contract)throw new Error("opensea: OpenSea returned an offer for the wrong contract");let c=sn(e.price?.current?.value??e.price?.value,"offer value",{positive:!0}),l=ob(i.offer,"offer payment"),u=l.paymentToken;if(l.totalWei!==c)throw new Error("opensea: offer payment total does not equal the quoted gross offer");let d=ob(i.consideration,"offer fee",{required:!1});if(d.count&&d.paymentToken!==u)throw new Error("opensea: offer fee consideration uses a different token than the offer payment");if(d.totalWei>c)throw new Error("opensea: offer fee consideration exceeds the gross offer");let p=d.totalWei.toString(),f=(c-d.totalWei).toString();return{provider:"opensea-nft",source:"opensea-best-exact-offer",orderHash:O_(e,i,"offer"),chain:t.chain,chainId:t.chainId,protocolAddress:pe(e.protocol_address,"offer protocol address"),contract:a,tokenId:n,grossOfferWei:c.toString(),sellerNetWei:f,feeWei:p,paymentToken:u,currency:String(e.price?.current?.currency||e.price?.currency||"").trim()||null,decimals:Number(e.price?.current?.decimals??e.price?.decimals??18),expiry:N_(e,i,r,"offer"),counter:hn(i.counter,"offer counter"),exec:!1,readOnly:!0}}async function Kc(e={},t={}){if(!fr(t))throw new Error("OPENSEA_API_KEY required");let n=Wc(e.chain);n.contract=e.contract?pe(e.contract,"NFT contract"):null;let r=String(e.slug||"").trim();if(!r)throw new Error("opensea: collection slug required");let o=Hc(e.tokenId),i=await A(`${Ur(t)}/offers/collection/${encodeURIComponent(r)}/nfts/${encodeURIComponent(o)}/best`,{headers:Fr(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),s=i?.offer||(Array.isArray(i?.offers)?i.offers[0]:i);if(!s)throw new Error("opensea: no active exact NFT offer returned");let a=Number.isFinite(Number(t.nowMs))?Number(t.nowMs):Date.now();return m9(s,n,o,a)}function h9(e){if(e.userConfirmed!==!0)throw new Error("opensea: userConfirmed=true required after buyer, chain, contract, token, quantity, price cap, total cap, and expiry review")}function P_(e){if(!e||typeof e!="object")return!1;let t=String(e.action??e.type??e.method??"");return/approv|setapprovalforall|permit/i.test(t)?!0:Object.values(e).some(n=>n&&typeof n=="object"&&P_(n))}function C_(e){return!e||typeof e!="object"?!1:Object.keys(e).some(t=>/^(?:signed.*|rawtransaction|serializedtransaction|txsigned|r|s|v)$/i.test(t))}function R_(e){return!e||typeof e!="object"?!1:C_(e)?!0:Object.values(e).some(t=>t&&typeof t=="object"&&R_(t))}function L_(e,t=[],n=new Set){if(!e||typeof e!="object"||n.has(e))return t;n.add(e),e.transaction&&typeof e.transaction=="object"?t.push(e.transaction):e.tx&&typeof e.tx=="object"&&t.push(e.tx);for(let[r,o]of Object.entries(e))(r==="transaction"||r==="tx")&&o&&typeof o=="object"||o&&typeof o=="object"&&L_(o,t,n);return t}function m_(e){return e&&typeof e=="object"&&typeof e.value=="string"?e.value:e}function $_(e,{buyer:t,chainId:n,targets:r}){if(!e||typeof e!="object")throw new Error("opensea: transaction object required");if(C_(e))throw new Error("opensea: signed transaction material refused");if((e.from?pe(m_(e.from),"transaction buyer"):t)!==t)throw new Error("opensea: OpenSea returned a transaction for the wrong buyer");let i=pe(m_(e.to??e.target),"transaction target");if(!r.has(i))throw new Error("opensea: OpenSea returned a transaction for the wrong target");let s=e.data??e.calldata,a=e.input_data&&typeof e.input_data=="object"?e.input_data:e.input&&typeof e.input=="object"?e.input:null;if(s==null&&a){if(!String(e.function||"").replace(/^function\s+/,"").startsWith("fulfillAdvancedOrder("))throw new Error("opensea: only exact Seaport fulfillAdvancedOrder preparation is accepted");s=GH.encodeFunctionData("fulfillAdvancedOrder",[a.advancedOrder,a.criteriaResolvers,a.fulfillerConduitKey,a.recipient])}let c=String(s??"").trim().toLowerCase();if(!/^0x(?:[0-9a-f]{2})+$/.test(c))throw new Error("opensea: OpenSea returned invalid transaction calldata");let l=e.calldata_suffix==null?"":String(e.calldata_suffix).trim().toLowerCase();if(l){if(!/^0x[0-9a-f]{8}$/.test(l))throw new Error("opensea: invalid OpenSea calldata suffix");c.endsWith(l.slice(2))||(c+=l.slice(2))}let u=e.chainId??e.chain_id??e.chainIdentifier?.chainId;if(u!=null&&Number(u)!==n)throw new Error("opensea: OpenSea returned a transaction for the wrong chain");let d=n9(e.value_hex??e.valueHex??e.value??0);return{from:t,to:i,data:c,value:d.hex,chainId:n,valueWei:d.amount}}function Op(e){return{from:e.from,to:e.to,data:e.data,value:e.value,chainId:e.chainId,...e.gasLimit==null?{}:{gasLimit:e.gasLimit},...e.maxFeePerGas==null?{}:{maxFeePerGas:e.maxFeePerGas},...e.maxPriorityFeePerGas==null?{}:{maxPriorityFeePerGas:e.maxPriorityFeePerGas},...e.worstCaseFeeWei==null?{}:{worstCaseFeeWei:e.worstCaseFeeWei}}}async function cb(e,t,n){let r=n.provider,o=!!n.rpcUrl;if(!r&&!o)return{simulated:!1,gasEstimates:[]};let i=await rt(e,4,async c=>{let{chainId:l,...u}=Op(c);if(r){if(typeof r.call!="function"||typeof r.estimateGas!="function")throw new Error("opensea: supplied provider must implement call and estimateGas");let[,m]=await Promise.all([r.call(u),r.estimateGas(u)]);return BigInt(m).toString()}let{rpcCall:d}=await Promise.resolve().then(()=>(De(),qd)),p={...n,fetchImpl:n.rpcFetchImpl||n.fetchImpl},[,f]=await Promise.all([d(t,"eth_call",[u,"pending"],p),d(t,"eth_estimateGas",[u],p)]);return BigInt(f).toString()}),s=null,a=null;if(r&&typeof r.getFeeData=="function"){let c=await r.getFeeData();a=c?.maxPriorityFeePerGas==null?0n:BigInt(c.maxPriorityFeePerGas),s=c?.maxFeePerGas==null?c?.gasPrice==null?null:BigInt(c.gasPrice):BigInt(c.maxFeePerGas)}else if(o){let{rpcCall:c}=await Promise.resolve().then(()=>(De(),qd)),l={...n,fetchImpl:n.rpcFetchImpl||n.fetchImpl},u=BigInt(await c(t,"eth_gasPrice",[],l));try{a=BigInt(await c(t,"eth_maxPriorityFeePerGas",[],l))}catch{a=0n}let d=await c(t,"eth_getBlockByNumber",["pending",!1],l),f=(d?.baseFeePerGas==null?0n:BigInt(d.baseFeePerGas))*2n+a;s=u>f?u:f}return s!=null&&a!=null&&e.forEach((c,l)=>{let d=(BigInt(i[l])*120n+99n)/100n;c.gasLimit=d.toString(),c.maxPriorityFeePerGas=a.toString(),c.maxFeePerGas=s.toString(),c.worstCaseFeeWei=(d*s).toString()}),{simulated:!0,gasEstimates:i}}function g9(e,t){if(P_(e))throw new Error("opensea: approval steps are not permitted in NFT buy, sweep, or mint preparation");if(R_(e))throw new Error("opensea: signed transaction material refused");let n=L_(e);if(!n.length&&e&&typeof e=="object"&&(e.to||e.target)&&n.push(e),!n.length)throw new Error("opensea: OpenSea returned no transaction action");return n.map(r=>$_(r,t))}function y9(e,t,n={}){return q({...e,provider:"opensea-nft",kind:t,marketplace:"opensea",prepareReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,executionReady:!1,note:"Unsigned OpenSea EVM NFT transaction preparation only. The private signer must revalidate every bound field before the user signs or broadcasts."},n)}async function lb(e={},t={}){throw new Error("opensea: public buy preparation disabled until canonical Seaport calldata is independently decoded and fully bound")}async function ub(e={},t={}){throw new Error("opensea: public buy preparation disabled until canonical Seaport calldata is independently decoded and fully bound")}function b9(e,t,n){let o=(Array.isArray(e?.contracts)?e.contracts:[]).find(s=>String(s?.chain||t).toLowerCase()===t&&s?.address);if(!o)throw new Error("opensea: collection response contains no contract for requested chain");let i=pe(o.address,"collection NFT contract");if(i!==n)throw new Error("opensea: OpenSea returned the wrong collection contract");return i}async function Yc(e={},t={}){if(!fr(t))throw new Error("OPENSEA_API_KEY required");h9(e);let{chain:n,chainId:r}=Wc(e.chain),o=pe(e.buyer||e.minter||e.address,"buyer"),i=pe(e.contract,"NFT contract"),s=A_(e.quantity),a=sn(e.priceWei,"priceWei"),c=sn(e.maxTotalWei,"maxTotalWei"),l=Number.isFinite(Number(t.nowMs))?Number(t.nowMs):Date.now(),u=I_(e.expiry,l,"mint expiry");if(e.tokenId!=null)throw new Error("opensea: SeaDrop mint tokenId is unknown until the mined receipt and must not be caller supplied");let d=String(e.slug||"").trim();if(!d)throw new Error("opensea: collection slug required");let p=await js(d,t),f=b9(p,n,i),m=a*BigInt(s);if(m>c)throw new Error("opensea: mint total exceeds total cap");let h=await A(`${Ur(t)}/drops/${encodeURIComponent(d)}/mint`,{method:"POST",headers:Fr(t),body:{minter:o,quantity:s},fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??25e3,retries:0,dedupe:!1}),g=t.allowedMintTargets?.[n]??t.allowedMintTargets?.[r]??e.mintTarget,y=Array.isArray(g)?g:g?[g]:[];if(!y.length)throw new Error("opensea: reviewed SeaDrop mintTarget required");let b=new Set(y.map($=>pe($,"SeaDrop mint target"))),S=g9(h,{buyer:o,chainId:r,targets:b});if(S.length!==1)throw new Error("opensea: mint must contain exactly one SeaDrop transaction");let w,E,x=null,v;try{w=Ap.decodeFunctionData("mintPublic",S[0].data),E="public",v=Ap.encodeFunctionData("mintPublic",[w[0],w[1],w[2],w[3]])}catch{try{w=Ap.decodeFunctionData("mintAllowList",S[0].data),E="allowlist";let $=w[4],B=[...w[5]].map(String);if(B.length<1||B.length>64||B.some(z=>!/^0x[0-9a-fA-F]{64}$/.test(z)))throw new Error("opensea: allowlist mint requires a bounded canonical Merkle proof");let N=BigInt($.startTime),C=BigInt($.endTime),j=BigInt(Math.floor(l/1e3));if(N>j||C<=j)throw new Error("opensea: allowlist mint stage is not open");if(BigInt($.mintPrice)!==a)throw new Error("opensea: allowlist stage price does not match exact approved price");if(BigInt($.maxTotalMintableByWallet)<BigInt(s))throw new Error("opensea: allowlist wallet cap is below requested quantity");v=Ap.encodeFunctionData("mintAllowList",[w[0],w[1],w[2],w[3],$,B]),x={mintPrice:BigInt($.mintPrice).toString(),maxTotalMintableByWallet:BigInt($.maxTotalMintableByWallet).toString(),startTime:N.toString(),endTime:C.toString(),dropStageIndex:BigInt($.dropStageIndex).toString(),maxTokenSupplyForStage:BigInt($.maxTokenSupplyForStage).toString(),feeBps:Number($.feeBps),restrictFeeRecipients:!!$.restrictFeeRecipients,proof:B}}catch($){throw/opensea:/.test(String($?.message||""))?$:new Error("opensea: mint transaction must call reviewed SeaDrop mintPublic or mintAllowList")}}let k=pe(w[0],"mint NFT contract"),I=pe(w[1],"mint fee recipient"),_=pe(w[2],"mint recipient");if(k!==f)throw new Error("opensea: mint calldata collection mismatch");if(_!==o)throw new Error("opensea: mint calldata recipient mismatch");if(BigInt(w[3])!==BigInt(s))throw new Error("opensea: mint calldata quantity mismatch");if(v.toLowerCase()!==S[0].data.toLowerCase())throw new Error("opensea: mint calldata must be canonical with no suffix");let P=S.reduce(($,B)=>$+B.valueWei,0n);if(P!==m)throw new Error("opensea: mint transaction total does not match exact approved price and quantity");if(P>c)throw new Error("opensea: mint total exceeds total cap");let O=await cb(S,r,{...t,provider:e.provider||t.provider});if(O.simulated!==!0)throw new Error("opensea: mint RPC simulation required");let F=e.gasPolicy||t.gasPolicy||{maxTotalGasWei:e.maxGasWei,maxFeePerGasWei:e.maxFeePerGasWei,maxPriorityFeePerGasWei:e.maxPriorityFeePerGasWei},M=d_({chainId:r,tx:S[0],policy:F});return y9({action:"mint",mintType:E,...x?{stage:x}:{},chain:n,chainId:r,slug:d,buyer:o,contract:f,quantity:s,priceWei:a.toString(),totalWei:P.toString(),maxTotalWei:c.toString(),mintTarget:S[0].to,feeRecipient:I,expiry:u,transactions:S.map(Op),gasWar:M,...O},"nft-mint",{nowMs:l,expiresAtMs:Math.min(l+_s,Date.parse(u),x?Number(BigInt(x.endTime)*1000n):Number.MAX_SAFE_INTEGER)})}function w9(e={}){let t=v_(e.chain);if(S_.has(t))throw new Error("opensea: listing actions currently require an EVM NFT chain");let n=e.startTime||e.start_time?p_(e.startTime||e.start_time,"startTime"):{text:new Date().toISOString(),ms:Date.now()},r=p_(e.endTime||e.end_time,"endTime");if(r.ms<=n.ms)throw new Error("opensea: endTime must be after startTime");let o=String(e.tokenId??e.token_id??"").trim();if(!/^\d+$/.test(o))throw new Error("opensea: tokenId must be an unsigned integer string");return{chain:t,contract:pe(e.contract,"NFT contract"),token_id:o,quantity:ZH(e.quantity??1,"quantity"),price:{amount:QH(e.price?.amount??e.amount??e.priceAmount,"price amount"),currency:pe(e.price?.currency??e.currency??qs,"price currency")},start_time:n.text,end_time:r.text}}function g_(e,t){return e?.[t]||(e?.action===t?e:null)}function E9(e,{seller:t,item:n,chainId:r}){let o=Array.isArray(e?.steps)?e.steps:[],i=o.map(S=>g_(S,"createListingsAction")).find(Boolean)||o.find(S=>/createListings/i.test(String(S?.action||""))),s=i?.signatureRequest?.message??i?.typedData,a;try{a=typeof s=="string"?JSON.parse(s):s}catch{throw new Error("opensea: invalid listing typed-data JSON")}if(!a||a.primaryType!=="OrderComponents"||!a.domain||!a.message)throw new Error("opensea: exact Seaport OrderComponents action required");let c=a.domain;if(c.name!=="Seaport"||c.version!=="1.6"||Number(c.chainId)!==r)throw new Error("opensea: listing domain mismatch");let l=pe(c.verifyingContract,"listing protocol"),u=a.message;if(pe(u.offerer,"listing seller")!==t)throw new Error("opensea: listing seller mismatch");if(!Array.isArray(u.offer)||u.offer.length!==1)throw new Error("opensea: executable listing requires exactly one NFT offer");let d=u.offer[0];if(![2,3].includes(Number(d.itemType)))throw new Error("opensea: listing offer must be ERC721 or ERC1155");if(pe(d.token,"listing collection")!==n.contract||String(d.identifierOrCriteria)!==n.token_id)throw new Error("opensea: listing NFT mismatch");if(String(d.startAmount)!==String(n.quantity)||String(d.endAmount)!==String(n.quantity))throw new Error("opensea: listing quantity mismatch");if(Number(u.orderType)!==2)throw new Error("opensea: only FULL_RESTRICTED listings are executable");if(!Array.isArray(u.consideration)||!u.consideration.length)throw new Error("opensea: listing consideration required");let p=0n;for(let S of u.consideration){if(Number(S.itemType)!==0||pe(S.token,"listing payment token")!==qs)throw new Error("opensea: executable listings currently require native fixed-price consideration");let w=BigInt(S.startAmount),E=BigInt(S.endAmount);if(w<=0n||w!==E)throw new Error("opensea: listing consideration must be fixed and positive");pe(S.recipient,"listing consideration recipient"),p+=w}let f=WH(n.price.amount,18);if(p!==f)throw new Error("opensea: listing price mismatch");let m=BigInt(Math.floor(Date.parse(n.start_time)/1e3)),h=BigInt(Math.floor(Date.parse(n.end_time)/1e3));if(BigInt(u.startTime)!==m||BigInt(u.endTime)!==h)throw new Error("opensea: listing time bounds mismatch");let g=ib.hashStruct("OrderComponents",Fs,u),y=o.map(S=>g_(S,"itemApprovalAction")).find(Boolean)||o.find(S=>/setApprovalForAll/i.test(String(S?.action||""))),b=null;if(y){let S=y.transaction||y.itemApprovalAction?.transaction,w=$_(S,{buyer:t,chainId:r,targets:new Set([n.contract])}),E;try{E=h_.decodeFunctionData("setApprovalForAll",w.data)}catch{throw new Error("opensea: listing approval must be setApprovalForAll")}let x=pe(E[0],"listing approval operator");if(E[1]!==!0||w.valueWei!==0n)throw new Error("opensea: listing approval must grant one exact operator with zero value");if(h_.encodeFunctionData("setApprovalForAll",[x,!0]).toLowerCase()!==w.data.toLowerCase())throw new Error("opensea: listing approval calldata must be canonical");b={...w,operator:x}}return{protocolAddress:l,typedData:{domain:c,types:Fs,primaryType:"OrderComponents",message:u},orderHash:g,priceWei:p,approval:b}}async function Jc(e={},t={}){if(!fr(t))throw new Error("OPENSEA_API_KEY required");if(e.userConfirmed!==!0)throw new Error("opensea: userConfirmed=true required after NFT, marketplace, price, currency, and expiry review");let n=pe(e.seller||e.address||e.owner,"seller"),r=Array.isArray(e.items)&&e.items.length?e.items:[e];if(r.length!==1)throw new Error("opensea: executable listing preparation supports exactly one NFT per envelope");let o=r.map(w9);if(new Set(o.map(f=>f.chain)).size!==1)throw new Error("opensea: all prepared listing items must be on one chain");let s=e.useCreatorFee!==!1,a={address:n,items:o,use_creator_fee:s};e.taker&&(a.taker=pe(e.taker,"taker"));let c=await A(`${Ur(t)}/listings/actions`,{method:"POST",headers:Fr(t),body:a,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??25e3,retries:0,dedupe:!1}),{chainId:l}=Wc(o[0].chain),u=E9(c,{seller:n,item:o[0],chainId:l}),d=u.approval?[u.approval]:[],p=d.length?await cb(d,l,{...t,provider:e.provider||t.provider}):{simulated:!0};return q({provider:"opensea-nft",marketplace:"opensea",chain:o[0].chain,chainId:l,kind:"nft-list",action:"list",prepareReady:!0,executionReady:p.simulated===!0,signingReady:p.simulated===!0,broadcastReady:p.simulated===!0,requiresUserSignature:!0,requiresSeparateApproval:d.length>0,seller:n,contract:o[0].contract,tokenId:o[0].token_id,quantity:o[0].quantity,priceWei:u.priceWei.toString(),typedData:u.typedData,orderHash:u.orderHash,submission:{chain:o[0].chain,protocol:"seaport",protocolAddress:u.protocolAddress},transactions:d.map(Op),useCreatorFee:s,taker:a.taker||null,feeDisclosure:s?"Creator fees requested and bound into exact Seaport consideration recipients.":"Creator fees disabled by explicit request; every remaining consideration recipient is still bound.",...p})}async function db(e={},t={}){if(e.userConfirmed!==!0)throw new Error("opensea: userConfirmed=true required for listing cancellation");let{chain:n,chainId:r}=Wc(e.chain),o=pe(e.seller||e.address||e.owner,"seller"),i=pe(e.protocolAddress,"reviewed Seaport protocol address"),s=pe(e.contract,"NFT contract"),a=Hc(e.tokenId),c=A_(e.quantity),l=e.typedData;if(!l||l.primaryType!=="OrderComponents"||!l.domain||!l.message)throw new Error("opensea: exact Seaport OrderComponents typedData required for cancellation");for(let[k,I]of Object.entries(Fs)){let _=l.types?.[k];if(!Array.isArray(_)||_.length!==I.length||_.some((P,O)=>P?.name!==I[O].name||P?.type!==I[O].type))throw new Error("opensea: cancellation requires canonical Seaport types")}if(Object.keys(l.types||{}).filter(k=>k!=="EIP712Domain").sort().join(",")!==Object.keys(Fs).sort().join(","))throw new Error("opensea: cancellation requires canonical Seaport types");let d=l.domain;if(d.name!=="Seaport"||d.version!=="1.6"||Number(d.chainId)!==r)throw new Error("opensea: cancellation domain mismatch");let p=pe(d.verifyingContract,"Seaport cancellation target");if(p!==i)throw new Error("opensea: cancellation target mismatch");let f=l.message;if(pe(f.offerer,"listing seller")!==o)throw new Error("opensea: cancellation seller mismatch");if(!Array.isArray(f.offer)||f.offer.length!==1||!Array.isArray(f.consideration)||!f.consideration.length)throw new Error("opensea: cancellation requires one exact previously prepared listing order");if(Number(f.orderType)!==2)throw new Error("opensea: cancellation requires a FULL_RESTRICTED listing order");let m=f.offer[0];if(![2,3].includes(Number(m.itemType)))throw new Error("opensea: cancellation offer must be ERC721 or ERC1155");if(pe(m.token,"cancellation NFT contract")!==s)throw new Error("opensea: cancellation NFT contract mismatch");if(Hc(m.identifierOrCriteria)!==a)throw new Error("opensea: cancellation tokenId mismatch");let h=sn(m.startAmount,"cancellation offer startAmount",{positive:!0}),g=sn(m.endAmount,"cancellation offer endAmount",{positive:!0});if(h!==BigInt(c)||g!==BigInt(c))throw new Error("opensea: cancellation quantity mismatch");for(let k of f.consideration){if(Number(k.itemType)!==0||pe(k.token,"cancellation payment token")!==qs)throw new Error("opensea: cancellation requires native fixed-price consideration");let I=sn(k.startAmount,"cancellation consideration startAmount",{positive:!0}),_=sn(k.endAmount,"cancellation consideration endAmount",{positive:!0});if(I!==_)throw new Error("opensea: cancellation consideration must be fixed and positive");pe(k.recipient,"cancellation consideration recipient")}let y=sn(f.startTime,"cancellation startTime");if(sn(f.endTime,"cancellation endTime",{positive:!0})<=y)throw new Error("opensea: cancellation listing time bounds invalid");let S=ib.hashStruct("OrderComponents",Fs,f),w=String(e.orderHash||"").trim().toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(w)||w!==S.toLowerCase())throw new Error("opensea: cancellation order hash mismatch");let E=S9.encodeFunctionData("cancel",[[f]]),x=[{from:o,to:p,data:E,value:"0x0",valueWei:0n,chainId:r}],v=await cb(x,r,{...t,provider:e.provider||t.provider});if(v.simulated!==!0)throw new Error("opensea: cancellation RPC simulation required");return q({provider:"opensea-nft",marketplace:"opensea",kind:"nft-cancel",action:"cancel-listing",prepareReady:!0,chain:n,chainId:r,seller:o,contract:s,tokenId:a,quantity:c,protocolAddress:p,orderHash:S,typedData:{domain:d,types:Fs,primaryType:"OrderComponents",message:f},transactions:x.map(Op),...v,requiresUserSignature:!0},{provider:"opensea-nft",kind:"nft-cancel"})}var y_,b_,GH,Ap,w_,KH,S_,qs,YH,JH,Vc,s9,Fs,h_,S9,Ni=Y(()=>{V();Pt();ae();rb();y_="https://api.opensea.io/api/v2",b_="fulfillAdvancedOrder(((address offerer,address zone,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount)[] offer,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount,address recipient)[] consideration,uint8 orderType,uint256 startTime,uint256 endTime,bytes32 zoneHash,uint256 salt,bytes32 conduitKey,uint256 totalOriginalConsiderationItems) parameters,uint120 numerator,uint120 denominator,bytes signature,bytes extraData) advancedOrder,(uint256 orderIndex,uint8 side,uint256 index,uint256 identifier,bytes32[] criteriaProof)[] criteriaResolvers,bytes32 fulfillerConduitKey,address recipient)",GH=new Ip([`function ${b_}`]),Ap=new Ip(["function mintPublic(address nftContract,address feeRecipient,address minterIfNotPayer,uint256 quantity) payable","function mintAllowList(address nftContract,address feeRecipient,address minterIfNotPayer,uint256 quantity,(uint80 mintPrice,uint48 maxTotalMintableByWallet,uint48 startTime,uint48 endTime,uint48 dropStageIndex,uint32 maxTokenSupplyForStage,uint16 feeBps,bool restrictFeeRecipients) mintParams,bytes32[] proof) payable"]),w_=Object.freeze(["blast","base","ethereum","zora","arbitrum","sei","avalanche","polygon","optimism","ape_chain","flow","b3","soneium","ronin","bera_chain","solana","shape","unichain","gunzilla","abstract","animechain","hyperevm","somnia","monad","hyperliquid","megaeth","ink","robinhood","stablechain"]),KH=new Set(w_),S_=new Set(["solana","flow"]),qs="0x0000000000000000000000000000000000000000",YH=qs,JH="0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73";Vc=Object.freeze({robinhood:4663,ethereum:1,base:8453,arbitrum:42161,optimism:10,polygon:137,avalanche:43114,zora:7777777,blast:81457,sei:1329,ape_chain:33139,b3:8333,soneium:1868,ronin:2020,bera_chain:80094,shape:360,unichain:130,gunzilla:43419,abstract:2741,animechain:69e3,hyperevm:999,somnia:5031,monad:143,megaeth:4326,ink:57073,stablechain:988});s9=Object.freeze({OrderComponents:[{name:"offerer",type:"address"},{name:"zone",type:"address"},{name:"offer",type:"OfferItem[]"},{name:"consideration",type:"ConsiderationItem[]"},{name:"orderType",type:"uint8"},{name:"startTime",type:"uint256"},{name:"endTime",type:"uint256"},{name:"zoneHash",type:"bytes32"},{name:"salt",type:"uint256"},{name:"conduitKey",type:"bytes32"},{name:"counter",type:"uint256"}],OfferItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"}],ConsiderationItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"},{name:"recipient",type:"address"}]});Fs={OrderComponents:[{name:"offerer",type:"address"},{name:"zone",type:"address"},{name:"offer",type:"OfferItem[]"},{name:"consideration",type:"ConsiderationItem[]"},{name:"orderType",type:"uint8"},{name:"startTime",type:"uint256"},{name:"endTime",type:"uint256"},{name:"zoneHash",type:"bytes32"},{name:"salt",type:"uint256"},{name:"conduitKey",type:"bytes32"},{name:"counter",type:"uint256"}],OfferItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"}],ConsiderationItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"},{name:"recipient",type:"address"}]},h_=new Ip(["function setApprovalForAll(address operator,bool approved)"]),S9=new Ip(["function cancel((address offerer,address zone,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount)[] offer,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount,address recipient)[] consideration,uint8 orderType,uint256 startTime,uint256 endTime,bytes32 zoneHash,uint256 salt,bytes32 conduitKey,uint256 counter)[] orders) returns (bool cancelled)"])});function v9(e,t){return`0x${mb.getAmountsOut}`+Cn(e)+Cn(64)+Cn(t.length)+t.map(Xc).join("")}function x9(e){if(!e||e==="0x")return null;let t=e.slice(2);if(t.length<128)return null;let n=Number(BigInt(`0x${t.slice(64,128)}`));if(!Number.isFinite(n)||n<1||n>16)return null;let r=[];for(let o=0;o<n;o++){let i=128+o*64;if(t.length<i+64)return null;r.push(BigInt(`0x${t.slice(i,i+64)}`))}return r}function fb(e,t="router"){return(e?.venues||[]).find(r=>r.kind===t)?.address??null}function k9(e,t){let n=Number(t);if(!Number.isFinite(n)||n<0)throw new Error("slippageBps must be a non-negative number");if(n>hb)throw new Error(`slippageBps ${n} exceeds the ${hb} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(e)*BigInt(1e4-Math.floor(n))/10000n}function M_(e){let{chainId:t,wrappedNative:n}=e;async function r(o,i,s,a){let c=await ee(t,"eth_call",[{to:o,data:v9(i,s)},"latest"],a);return x9(c?.result??c)}return{async quote({tokenIn:o,tokenOut:i,amountIn:s,path:a},c={}){let l=fb(c.scanner);if(!l)return{chainId:t,evidence:ue.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let u=a||[o,i];if(u.some(p=>!/^0x[0-9a-fA-F]{40}$/.test(p||"")))throw new Error("quote requires valid 20-byte addresses");let d=await r(l,s,u,c);return d?{chainId:t,router:l,path:u,amountIn:String(s),amountOut:d[d.length-1].toString(),hops:u.length-1,evidence:ue.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:t,router:l,path:u,evidence:ue.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:o,amountIn:i,base:s},a={}){let c=fb(a.scanner),l=s||n;if(l&&String(o).toLowerCase()===String(l).toLowerCase())return{chainId:t,token:o,verdict:ie.UNKNOWN,evidence:ue.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:t,token:o,verdict:ie.UNKNOWN,evidence:ue.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 u=await r(c,i,[l,o],a);if(!u)return{chainId:t,token:o,verdict:ie.FAIL,evidence:ue.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let d=u[u.length-1];if(d===0n)return{chainId:t,token:o,verdict:ie.FAIL,evidence:ue.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let p=await r(c,d,[o,l],a);if(!p)return{chainId:t,token:o,verdict:ie.FAIL,evidence:ue.LIVE,leg:"sell",bought:d.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let f=p[p.length-1],m=Number(f*10000n/BigInt(i)),h=ie.PASS,g="round trip completes with expected fee/impact loss";return m<5e3?(h=ie.FAIL,g=`round trip returns only ${(m/100).toFixed(2)}% -- punitive tax or no real liquidity`):m<9e3&&(h=ie.CAUTION,g=`round trip returns ${(m/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,token:o,base:l,router:c,verdict:h,reason:g,amountIn:String(i),bought:d.toString(),returned:f.toString(),retentionBps:m,evidence:ue.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:o,tokenOut:i,amountIn:s,recipient:a,slippageBps:c=50,deadlineSeconds:l=900,path:u},d={}){let p=d.scanner,f=fb(p);if(!f)throw new Error(`chain ${t} 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(a||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let m=u||[o,i],h=await this.quote({tokenIn:o,tokenOut:i,amountIn:s,path:m},d);if(h.evidence!==ue.LIVE)throw new Error(`cannot prepare without a live quote (${h.evidence}: ${h.reason??"no reason given"})`);let g=k9(h.amountOut,c);if(g<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let y=BigInt(Math.floor(Date.now()/1e3)+Number(l)),b=n&&m[0].toLowerCase()===n.toLowerCase()&&d.useNative,S=b?`0x${mb.swapExactETHForTokens}`+Cn(g)+Cn(128)+Xc(a)+Cn(y)+Cn(m.length)+m.map(Xc).join(""):`0x${mb.swapExactTokensForTokens}`+Cn(s)+Cn(g)+Cn(160)+Xc(a)+Cn(y)+Cn(m.length)+m.map(Xc).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:t,tx:{to:f,data:S,value:b?`0x${BigInt(s).toString(16)}`:"0x0"},guard:{quotedOut:h.amountOut,minOut:g.toString(),slippageBps:c,maxSlippageBps:hb,deadline:y.toString()},requires:b?[]:[{step:"approve",token:m[0],spender:f,amount:String(s)}],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 mb,Cn,Xc,hb,B_=Y(()=>{De();vo();mb={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},Cn=e=>BigInt(e).toString(16).padStart(64,"0"),Xc=e=>e.slice(2).toLowerCase().padStart(64,"0");hb=100});function I9(e,t){let n=Number(t);if(!Number.isFinite(n)||n<0)throw new Error("slippageBps must be a non-negative number");if(n>yb)throw new Error(`slippageBps ${n} exceeds the ${yb} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(e)*BigInt(1e4-Math.floor(n))/10000n}function gb(e,t){return(e?.venues||[]).find(n=>n.kind===t)?.address??null}function F_(e){let{chainId:t,wrappedNative:n}=e;async function r({quoter:i,tokenIn:s,tokenOut:a,amountIn:c,fee:l},u){let d=`0x${D_.quoteExactInputSingle}`+Qc(s)+Qc(a)+Pi(c)+Pi(l)+Pi(0),p=await ee(t,"eth_call",[{to:i,data:d},"latest"],u).catch(()=>null),f=p?.result??p;if(!f||f==="0x"||f.length<66)return null;let m=BigInt(`0x${f.slice(2,66)}`);return m>0n?m:null}async function o({quoter:i,tokenIn:s,tokenOut:a,amountIn:c},l){let u=await Promise.all(A9.map(async p=>{let f=await r({quoter:i,tokenIn:s,tokenOut:a,amountIn:c,fee:p},l);return{fee:p,amountOut:f?f.toString():null,out:f}})),d=null;for(let p of u)p.out&&(!d||p.out>d.amountOut)&&(d={fee:p.fee,amountOut:p.out});return{best:d,tried:u.map(({fee:p,amountOut:f})=>({fee:p,amountOut:f}))}}return{async quote({tokenIn:i,tokenOut:s,amountIn:a},c={}){let l=gb(c.scanner,"quoter");if(!l)return{chainId:t,evidence:ue.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let p of[i,s])if(!U_.test(p||""))throw new Error("quote requires valid 20-byte addresses");let{best:u,tried:d}=await o({quoter:l,tokenIn:i,tokenOut:s,amountIn:a},c);return u?{chainId:t,venue:"uniswap-v3",quoter:l,tokenIn:i,tokenOut:s,amountIn:String(a),amountOut:u.amountOut.toString(),fee:u.fee,useNative:!!n&&String(i).toLowerCase()===String(n).toLowerCase(),triedFeeTiers:d,evidence:ue.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:t,quoter:l,tokenIn:i,tokenOut:s,triedFeeTiers:d,evidence:ue.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:i,amountIn:s,base:a},c={}){let l=gb(c.scanner,"quoter"),u=(e.stableQuoteAssets||[]).map(E=>String(E).toLowerCase()),d=null;!a&&typeof e.resolveQuoteAsset=="function"&&(d=await e.resolveQuoteAsset(i,c).catch(()=>null));let p=String(i).toLowerCase(),f=String(n||"").toLowerCase();if(f&&p===f)return{chainId:t,token:i,verdict:ie.UNKNOWN,evidence:ue.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 m=a||d||(u[0]&&p!==u[0]?u[0]:null)||n;if(m&&p===String(m).toLowerCase())return{chainId:t,token:i,verdict:ie.UNKNOWN,evidence:ue.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||!m)return{chainId:t,token:i,verdict:ie.UNKNOWN,evidence:ue.UNAVAILABLE,reason:l?"no wrappedNative configured, so there is no base asset to round-trip against":"no verified quoter configured for this chain"};let h=await o({quoter:l,tokenIn:m,tokenOut:i,amountIn:s},c);if(!h.best){let E=u.find(x=>x&&x!==String(m).toLowerCase()&&x!==String(i).toLowerCase());if(E){let x=await o({quoter:l,tokenIn:E,tokenOut:i,amountIn:s},c);if(x.best){let v=await o({quoter:l,tokenIn:i,tokenOut:E,amountIn:x.best.amountOut},c);if(v.best){let k=v.best.amountOut,I=Number(k*10000n/BigInt(s)),_=ie.PASS,P="round trip vs dollar book completes with expected fee/impact loss";return I<5e3?(_=ie.FAIL,P=`round trip vs dollar book returns only ${(I/100).toFixed(2)}% -- punitive tax or no real liquidity`):I<9e3&&(_=ie.CAUTION,P=`round trip vs dollar book returns ${(I/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:i,base:E,quoteAsset:E,verdict:_,reason:P,amountIn:String(s),bought:x.best.amountOut.toString(),returned:k.toString(),retentionBps:I,buyFee:x.best.fee,sellFee:v.best.fee,evidence:ue.LIVE,note:"Quoted against the dollar book, not wrapped native. A missing WETH pool is not a honeypot."}}}}return{chainId:t,token:i,verdict:ie.FAIL,evidence:ue.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier against wrapped native or the dollar book"}}let g=await o({quoter:l,tokenIn:i,tokenOut:m,amountIn:h.best.amountOut},c);if(!g.best){let E=u.find(x=>x&&x!==String(m).toLowerCase()&&x!==String(i).toLowerCase());if(E){let x=await o({quoter:l,tokenIn:E,tokenOut:i,amountIn:s},c),v=x.best?await o({quoter:l,tokenIn:i,tokenOut:E,amountIn:x.best.amountOut},c):{best:null};if(x.best&&v.best){let k=v.best.amountOut,I=Number(k*10000n/BigInt(s)),_=ie.PASS,P="round trip vs dollar book completes; missing WETH sell pool is not a honeypot";return I<5e3?(_=ie.FAIL,P=`dollar-book round trip returns only ${(I/100).toFixed(2)}%`):I<9e3&&(_=ie.CAUTION,P=`dollar-book round trip returns ${(I/100).toFixed(2)}%`),{chainId:t,venue:"uniswap-v3",token:i,base:E,quoteAsset:E,verdict:_,reason:P,amountIn:String(s),bought:x.best.amountOut.toString(),returned:k.toString(),retentionBps:I,buyFee:x.best.fee,sellFee:v.best.fee,evidence:ue.LIVE,note:"Sell vs wrapped native failed; dollar book succeeded. Not labelled honeypot."}}}return{chainId:t,token:i,verdict:ie.FAIL,evidence:ue.LIVE,leg:"sell",bought:h.best.amountOut.toString(),reason:"SELL LEG FAILED against wrapped native and the dollar book. This is the honeypot signature: do not trade."}}let y=g.best.amountOut,b=Number(y*10000n/BigInt(s)),S=ie.PASS,w="round trip completes with expected fee/impact loss";return b<5e3?(S=ie.FAIL,w=`round trip returns only ${(b/100).toFixed(2)}% -- punitive tax or no real liquidity`):b<9e3&&(S=ie.CAUTION,w=`round trip returns ${(b/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:i,base:m,verdict:S,reason:w,amountIn:String(s),bought:h.best.amountOut.toString(),returned:y.toString(),retentionBps:b,buyFee:h.best.fee,sellFee:g.best.fee,evidence:ue.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:i,tokenOut:s,amountIn:a,recipient:c,slippageBps:l=50,fee:u},d={}){let p=gb(d.scanner,"router");if(!p)throw new Error(`chain ${t} 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(!U_.test(c||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let f=await this.quote({tokenIn:i,tokenOut:s,amountIn:a},d);if(f.evidence!==ue.LIVE)throw new Error(`cannot prepare without a live quote (${f.evidence}: ${f.reason??"no reason given"})`);let m=u??f.fee,h=I9(f.amountOut,l);if(h<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let g=!!(d.useNative||f.useNative)&&n&&String(i).toLowerCase()===String(n).toLowerCase(),y=`0x${D_.exactInputSingle}`+Qc(i)+Qc(s)+Pi(m)+Qc(c)+Pi(a)+Pi(h)+Pi(0);return{unsigned:!0,signedBy:"user-wallet",chainId:t,venue:"uniswap-v3",tx:{to:p,data:y,value:g?String(a):"0x0"},guard:{quotedOut:f.amountOut,minOut:h.toString(),slippageBps:l,maxSlippageBps:yb,fee:m},requires:g?[]:[{step:"approve",token:i,spender:p,amount:String(a)}],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 A9,D_,Pi,Qc,U_,yb,q_=Y(()=>{De();vo();A9=[100,500,3e3,1e4],D_={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},Pi=e=>BigInt(e).toString(16).padStart(64,"0"),Qc=e=>e.slice(2).toLowerCase().padStart(64,"0"),U_=/^0x[0-9a-fA-F]{40}$/,yb=100});function j_(e){if(!e||e==="0x")return null;try{return BigInt(e)}catch{return null}}function H_(e){if(!e||e==="0x")return null;let t=e.slice(2);if(t.length>=128){let r=Number(BigInt(`0x${t.slice(64,128)}`));if(r>0&&r<=256&&t.length>=128+r*2){let o=t.slice(128,128+r*2),i=Buffer.from(o,"hex").toString("utf8").replace(/\0+$/,"");if(i)return i}}return Buffer.from(t.slice(0,64),"hex").toString("utf8").replace(/\0+$/,"")||null}function _9(e){let{chainId:t}=e;async function n(r,o,i){return ee(t,"eth_call",[{to:r,data:o},"latest"],i)}return{async blockNumber(r={}){let o=await xc(t,r);return{chainId:t,blockNumber:o?.blockNumber??o,evidence:ue.LIVE}},async nativeBalance(r,o={}){let i=await Ei(t,r,o);return{chainId:t,address:r,wei:i?.wei??i?.balance??null,symbol:e.nativeCurrency?.symbol??null,decimals:e.nativeCurrency?.decimals??18,evidence:ue.LIVE}},async tokenBalance({token:r,owner:o},i={}){let s=await kc({chainId:t,token:r,owner:o},i);return{chainId:t,token:r,owner:o,raw:s?.balance??s,evidence:ue.LIVE}},async resolveToken(r,o={}){if(!/^0x[0-9a-fA-F]{40}$/.test(r||""))return{chainId:t,token:r,evidence:ue.UNKNOWN,error:"resolveToken needs a 20-byte address; symbol lookup is a market-data concern"};let[i,s,a,c]=await Promise.all([n(r,Tp.decimals,o).catch(()=>null),n(r,Tp.symbol,o).catch(()=>null),n(r,Tp.name,o).catch(()=>null),n(r,Tp.totalSupply,o).catch(()=>null)]),l=j_(i?.result??i),u=l!==null||s?.result||a?.result,d={chainId:t,address:r,decimals:l===null?null:Number(l),symbol:H_(s?.result??s),name:H_(a?.result??a),totalSupply:(j_(c?.result??c)??null)?.toString()??null,evidence:u?ue.LIVE:ue.UNKNOWN};return u||(d.warning="no ERC-20 metadata returned -- may not be a token contract"),d},async resolvePools(r,o={}){let i=e.dexscreenerSlug;if(!i)return{chainId:t,token:r,pools:[],evidence:ue.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let s=await pr(r,o).catch(()=>null),c=(s?.pairs||s?.data?.pairs||[]).filter(u=>String(u.chainId).toLowerCase()===String(i).toLowerCase()).map(u=>({pair:u.pairAddress,dex:u.dexId,base:u.baseToken?.address,quote:u.quoteToken?.address,liquidityUsd:u.liquidity?.usd??null,priceUsd:u.priceUsd??null,volume24hUsd:u.volume?.h24??null,createdAt:u.pairCreatedAt??null})).sort((u,d)=>(d.liquidityUsd??0)-(u.liquidityUsd??0)),l=Cg(r,c,{stables:e.stableQuoteAssets||[],wrappedNative:e.wrappedNative});return{chainId:t,token:r,pools:l,topPool:l[0]||null,quoteAsset:dA(r,l),evidence:l.length?ue.LIVE:ue.UNKNOWN}},async scanBlocks({fromBlock:r,toBlock:o,address:i,topics:s,chunkSize:a=2e3}={},c={}){if(!Number.isInteger(r)||!Number.isInteger(o))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(o<r)throw new Error("toBlock must be >= fromBlock");let l=[],u=[];for(let p=r;p<=o;p+=a){let f=Math.min(p+a-1,o);u.push([p,f])}let d=await rt(u,4,async([p,f])=>{let m={fromBlock:`0x${p.toString(16)}`,toBlock:`0x${f.toString(16)}`};i&&(m.address=i),s&&(m.topics=s);let h=await ee(t,"eth_getLogs",[m],c).catch(g=>({error:String(g?.message||g)}));return{start:p,end:f,res:h}});for(let{start:p,end:f,res:m}of d){if(m?.error)return{chainId:t,fromBlock:r,toBlock:o,logs:l,complete:!1,failedAt:[p,f],error:m.error,evidence:ue.UNKNOWN};for(let h of m?.result??m??[])l.push(h)}return{chainId:t,fromBlock:r,toBlock:o,logs:l,complete:!0,chunks:u.length,evidence:ue.LIVE}},async scoreRisk(r,o={}){let i=[],s=ie.PASS,a=u=>{let d={[ie.PASS]:0,[ie.CAUTION]:1,[ie.UNKNOWN]:2,[ie.FAIL]:3};d[u]>d[s]&&(s=u)},[c,l]=await Promise.all([this.resolveToken(r,o),this.resolvePools(r,o)]);if(c.evidence!==ue.LIVE?(i.push({check:"erc20-metadata",result:ie.UNKNOWN,detail:c.warning}),a(ie.UNKNOWN)):i.push({check:"erc20-metadata",result:ie.PASS,detail:`${c.symbol} / ${c.decimals}d`}),l.evidence===ue.UNAVAILABLE)i.push({check:"liquidity",result:ie.UNKNOWN,detail:l.reason}),a(ie.UNKNOWN);else if(!l.pools.length)i.push({check:"liquidity",result:ie.FAIL,detail:"no pool with liquidity found"}),a(ie.FAIL);else{let u=l.pools[0],d=u.liquidityUsd??0;d<5e3?(i.push({check:"liquidity",result:ie.CAUTION,detail:`top pool only $${d}`}),a(ie.CAUTION)):i.push({check:"liquidity",result:ie.PASS,detail:`$${d} on ${u.dex}`}),u.createdAt&&Date.now()-u.createdAt<24*3600*1e3&&(i.push({check:"age",result:ie.CAUTION,detail:"pool under 24h old"}),a(ie.CAUTION))}if(typeof this.sellSimulation=="function"){let u=await this.sellSimulation({token:r,amountIn:(10n**16n).toString()},o).catch(d=>({verdict:ie.UNKNOWN,reason:String(d?.message||d)}));i.push({check:"sellability",result:u.verdict,detail:u.retentionBps!=null?`round trip returns ${(u.retentionBps/100).toFixed(2)}% -- ${u.reason}`:u.reason}),a(u.verdict)}else i.push({check:"sellability",result:ie.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."}),a(ie.UNKNOWN);return{chainId:t,token:r,verdict:s,checks:i,note:"Structural checks only. UNKNOWN is not PASS. A token is not tradeable until a sell simulation succeeds."}}}}function bb(e){let n={..._9(e)},r=new Set((e.venues||[]).map(i=>i.kind));e.venueKind==="uniswap-v3"&&r.has("quoter")&&r.has("router")?Object.assign(n,F_({chainId:e.chainId,wrappedNative:e.wrappedNative,stableQuoteAssets:e.stableQuoteAssets||[],resolveQuoteAsset:async(i,s)=>(await n.resolvePools(i,s)).quoteAsset||null})):e.venueKind==="uniswap-v2"&&r.has("router")&&Object.assign(n,M_({chainId:e.chainId,wrappedNative:e.wrappedNative}));let o={};for(let[i,s]of Object.entries(n))o[i]=s.bind(n);return{key:e.key,chainId:e.chainId,name:e.name,rpcEnv:e.rpcEnv,nativeCurrency:e.nativeCurrency,explorer:e.explorer,venues:e.venues||[],capabilities:o}}var Tp,z_=Y(()=>{De();Pr();V();vo();B_();q_();Rg();Tp={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"}});var Oo,V_=Y(()=>{Oo=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 wb={};vt(wb,{CHAIN_CONFIGS:()=>Oo,registerBuiltinScanners:()=>zs,registerCustomChain:()=>O9});function zs(){return Oo.map(e=>ay(bb(e)))}function O9(e){return ay(bb(e))}var Ci=Y(()=>{z_();vo();V_()});import{types as Vs}from"node:util";function an(e){if(!e||typeof e!="object"||Vs.isProxy(e)||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Kt(e,t){if(e==null||(typeof e=="object"||typeof e=="function")&&Vs.isProxy(e)||!Object.hasOwn(Object(e),t))return;let n=Object.getOwnPropertyDescriptor(Object(e),t);return n&&Object.hasOwn(n,"value")?n.value:void 0}function qr(e,t,n="provider response",r=null,o=0){if(typeof t!="string"||t.length===0)return e;if(o>64)throw new Error(`${n} exceeds the credential guard nesting bound`);let i=r??{nodes:0,active:new Set};if(i.nodes+=1,i.nodes>2e5)throw new Error(`${n} exceeds the credential guard node bound`);if(e==null)return e;if(["string","number","boolean"].includes(typeof e)){if(String(e).includes(t))throw new Error(`${n} reflected an attached credential`);return e}if(!e||typeof e!="object"||Vs.isProxy(e)||i.active.has(e))throw new Error(`${n} is not credential-guardable own-data JSON`);i.active.add(e);try{if(Array.isArray(e)){for(let s=0;s<e.length;s+=1){let a=Object.getOwnPropertyDescriptor(e,String(s));if(!a||!Object.hasOwn(a,"value"))throw new Error(`${n} is not credential-guardable own-data JSON`);qr(a.value,t,n,i,o+1)}return e}if(!an(e))throw new Error(`${n} is not credential-guardable own-data JSON`);for(let s of Object.keys(e)){if(s.includes(t))throw new Error(`${n} reflected an attached credential`);let a=Object.getOwnPropertyDescriptor(e,s);if(!a||!Object.hasOwn(a,"value"))throw new Error(`${n} is not credential-guardable own-data JSON`);qr(a.value,t,n,i,o+1)}return e}finally{i.active.delete(e)}}function Xe(e,t="provider response",n=0){if(n>64)throw new Error(`${t} exceeds the JSON nesting bound`);if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e;if(Array.isArray(e)){if(Vs.isProxy(e)||e.length>1e5)throw new Error(`${t} contains an invalid array`);let o=new Array(e.length);for(let i=0;i<e.length;i+=1){let s=Object.getOwnPropertyDescriptor(e,String(i));if(!s||!Object.hasOwn(s,"value"))throw new Error(`${t} arrays must contain dense own data`);o[i]=Xe(s.value,t,n+1)}return o}if(!an(e))throw new Error(`${t} contains a non-JSON value`);let r=Object.create(null);for(let o of Object.keys(e)){let i=Object.getOwnPropertyDescriptor(e,o);if(!i||!Object.hasOwn(i,"value"))throw new Error(`${t} objects must contain own data`);r[o]=Xe(i.value,t,n+1)}return r}function Ws(e,t){let n=t&&typeof t=="object"&&!Vs.isProxy(t)?t:null,r=n?Object.getOwnPropertyDescriptor(n,"status"):null,o=r&&Object.hasOwn(r,"value")&&Number.isInteger(r.value)&&r.value>=400&&r.value<=599?r.value:null,i=a=>{if(!n)return;let c=Object.getOwnPropertyDescriptor(n,a);return c&&Object.hasOwn(c,"value")?c.value:void 0},s=i("oversize")===!0?"provider-response-too-large":i("oracleTimeout")===!0||i("name")==="AbortError"||i("name")==="TimeoutError"?"provider-timeout":null;return(o!==null||s!==null)&&Object.defineProperty(e,J_,{value:Object.freeze({status:o,code:s}),enumerable:!1,configurable:!1,writable:!1}),e}function X_(e){if(!e||typeof e!="object"||Vs.isProxy(e))return null;let t=Object.getOwnPropertyDescriptor(e,J_);if(!t||!Object.hasOwn(t,"value")||!t.value||typeof t.value!="object")return null;let n=Number.isInteger(t.value.status)&&t.value.status>=400&&t.value.status<=599?t.value.status:null,r=M9.has(t.value.code)?t.value.code:null;return n===null&&r===null?null:Object.freeze({status:n,code:r})}var J_,M9,Rn=Y(()=>{J_=Symbol("oracle.provider-failure-metadata"),M9=new Set(["provider-response-too-large","provider-timeout"])});function B9({testnet:e,baseUrl:t}={}){if(t)return t.replace(/\/$/,"").endsWith("/info")?t:`${t.replace(/\/$/,"")}/info`;if(process.env.HL_INFO_URL)return process.env.HL_INFO_URL;if(process.env.HL_API_URL){let n=process.env.HL_API_URL.replace(/\/$/,"");return n.endsWith("/info")?n:`${n}/info`}return e||process.env.HL_TESTNET==="1"?kb:xb}async function _e(e,t={}){if(!e||!e.type)throw new Error("hlInfo requires body.type");let n=B9(t);return Xe(await A(n,{method:"POST",body:e,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs,maxResponseBytes:t.maxResponseBytes,sameOriginRedirectsOnly:t.sameOriginRedirectsOnly,signal:t.signal}),"hyperliquid info response")}async function Q_(e={}){let t=await _e({type:"allMids"},e),n=t&&typeof t=="object"?Object.keys(t).length:0;return{ok:n>0,midCount:n}}async function Gn(e={}){return _e({type:"allMids"},e)}async function Gs(e,t={}){if(!e)throw new Error("hlL2Book requires coin");return _e({type:"l2Book",coin:String(e)},t)}async function el(e={}){return _e({type:"outcomeMeta"},e)}async function Cp(e,t={}){if(!e)throw new Error("hlClearinghouse requires user address");return _e({type:"spotClearinghouseState",user:e},t)}async function Rp(e,t={}){if(!e)throw new Error("hlUserFills requires user address");return _e({type:"userFills",user:e},t)}async function Lp(e={}){return _e({type:"meta"},e)}async function cn(e={}){let t={type:"metaAndAssetCtxs"};return e.dex&&(t.dex=e.dex),_e(t,e)}async function Ks({coin:e,interval:t="1h",startTime:n,endTime:r},o={}){if(!e)throw new Error("hlCandleSnapshot requires coin");let i={type:"candleSnapshot",req:{coin:String(e),interval:t,startTime:n??Date.now()-24*3600*1e3,endTime:r??Date.now()}};return _e(i,o)}async function $p({coin:e,startTime:t,endTime:n},r={}){if(!e)throw new Error("hlFundingHistory requires coin");return _e({type:"fundingHistory",coin:String(e),startTime:t??Date.now()-24*3600*1e3,endTime:n??Date.now()},r)}async function Z_(e,t={}){if(!e)throw new Error("hlOpenOrders requires user");return _e({type:"openOrders",user:e},t)}async function eO(e,t={}){if(!e)throw new Error("hlFrontendOpenOrders requires user");return _e({type:"frontendOpenOrders",user:e},t)}async function Ys(e,t={}){if(!e)throw new Error("hlUserState requires user");return _e({type:"clearinghouseState",user:e},t)}async function Mp(e={}){return _e({type:"spotMeta"},e)}var xb,kb,Ct=Y(()=>{V();Rn();xb="https://api.hyperliquid.xyz/info",kb="https://api.hyperliquid-testnet.xyz/info"});async function cO(e={}){let t=Date.now();if(sl.dexs&&t-sl.at<6e4&&!e.fetchImpl)return sl.dexs;let n=await _e({type:"perpDexs"},e);return sl={at:t,dexs:Array.isArray(n)?n:[]},sl.dexs}async function lO(e="",t={}){let n=e||"",r=Date.now(),o=aO.get(n);if(o&&r-o.at<3e4&&!t.fetchImpl)return o;let i=e?await _e({type:"metaAndAssetCtxs",dex:e},t):await cn(t),s=i?.[0]?.universe??i?.universe??[],a=Array.isArray(i?.[1])?i[1]:[],c={at:r,universe:s,ctxs:a};return aO.set(n,c),c}function K9(e){let t=String(e??"").trim();if(!t)return t;let n=t.toLowerCase().replace(/[\s._-]+/g,"");return G9[n]??t}function Co(e){if(typeof e!="string"||!/^#(?:0|[1-9]\d*)$/.test(e))return null;let t=Number(e.slice(1));if(!Number.isSafeInteger(t)||t<0)return null;let n=t%10;if(n!==0&&n!==1)return null;let r=Math.floor(t/10),o=uO+t;return Number.isSafeInteger(o)?{encoding:t,outcome:r,side:n,coin:`#${t}`,assetId:o}:null}function Po(e,t){let n=Fb(e),r=Fb(t);if(n==null)throw new Error("hl-assets: outcome id must be a non-negative integer");if(r!==0&&r!==1)throw new Error("hl-assets: outcome side must be 0 or 1");let o=10*n+r;if(!Number.isSafeInteger(o))throw new Error("hl-assets: outcome encoding exceeds safe integer range");let i=uO+o;if(!Number.isSafeInteger(i))throw new Error("hl-assets: outcome asset id exceeds safe integer range");return{encoding:o,outcome:n,side:r,coin:`#${o}`,assetId:i}}function Fb(e){if(typeof e=="number")return Number.isSafeInteger(e)&&e>=0?e:null;if(typeof e!="string"||!/^(?:0|[1-9]\d*)$/.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null}async function qb(e={},t={}){if(e.outcome!=null||typeof e.coin=="string"&&e.coin.startsWith("#")){let l=e.coin==null?null:Co(e.coin);if(e.coin!=null&&!l)throw new Error(`hl-assets: invalid outcome coin ${e.coin}`);let u=e.outcome==null?null:Po(e.outcome,0).outcome;if(u!=null&&l&&l.outcome!==u)throw new Error("hl-assets: coin does not match outcome");let d=e.outcomeSide==null?null:Y9(e.outcomeSide,"outcomeSide"),p=u??l?.outcome;if(e.outcome!=null&&e.coin==null&&d==null)throw new Error("hl-assets: outcomeSide required");let f=d??l?.side;if(f==null)throw new Error("hl-assets: outcomeSide required");if(p==null)throw new Error("hl-assets: outcome identity required");let m=Po(p,f);if(l&&(l.outcome!==m.outcome||l.side!==m.side))throw new Error("hl-assets: coin does not match outcome side");let h=e.szDecimals!=null?Number(e.szDecimals):2;return{kind:"outcome",coin:m.coin,assetId:m.assetId,encoding:m.encoding,outcome:m.outcome,side:m.side,szDecimals:h,maxLeverage:1,dex:null,markPx:null}}let n=String(e.coin||e.symbol||e.name||"").trim();if(!n)throw new Error("hl-assets: coin required");if(n.includes(":")){let[l,...u]=n.split(":"),d=u.join(":");if(!l||!d)throw new Error(`hl-assets: bad builder coin ${n}`);let p=K9(l),f=await cO(t),m=f.findIndex(E=>E&&E.name===p);if(m<1)throw new Error(`hl-assets: unknown builder dex "${l}"`);let{universe:h,ctxs:g}=await lO(p,t),y=h.findIndex(E=>E.name===`${p}:${d}`);if(y<0)throw new Error(`hl-assets: ${n} not in dex ${p} meta`);let b=h[y];if(b.isDelisted)throw new Error(`hl-assets: ${n} is delisted`);let S=W9+m*1e4+y,w=g[y]||{};return{kind:"hip3",coin:b.name||n,assetId:S,szDecimals:b.szDecimals??0,maxLeverage:b.maxLeverage??null,dex:p,dexName:f[m]?.fullName||p,dexIndex:m,indexInMeta:y,markPx:w.markPx??null}}let{universe:r,ctxs:o}=await lO("",t),i=n.toUpperCase(),s=r.findIndex(l=>l.name===i);if(s<0){if(t.allowBareBuilderLeaf===!0)try{let l=await cO(t);for(let u=1;u<l.length;u++){let d=l[u];if(!d?.name)continue;let p=`${d.name}:${i}`;try{return await qb({coin:p},t)}catch{}}}catch{}throw new Error(`hl-perps: ${i} is not a listed perp`)}let a=r[s];if(a.isDelisted)throw new Error(`hl-assets: ${i} is delisted`);let c=o[s]||{};return{kind:"main",coin:a.name,assetId:s,szDecimals:a.szDecimals??0,maxLeverage:a.maxLeverage??null,dex:"",markPx:c.markPx??null}}function Y9(e,t){let n=Fb(e);if(n!==0&&n!==1)throw new Error(`hl-assets: ${t} must be 0 or 1`);return n}var uO,W9,sl,aO,G9,jp=Y(()=>{Ct();uO=1e8,W9=1e5,sl={at:0,dexs:null},aO=new Map;G9=Object.freeze({tradexyz:"xyz",ventuals:"vntl",hypernova:"hyna",paradex:"para",entropy:"io",entropyio:"io"})});function kt(e,t="value"){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${t} must be a finite number`);if(Math.abs(e)>Number.MAX_SAFE_INTEGER)throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);if(Number.isInteger(e)&&!Number.isSafeInteger(e))throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);return String(e)}if(typeof e=="string"){if(e!==e.trim())throw new Error(`${t} must be a number or decimal string`);return e}throw new Error(`${t} must be a number or decimal string`)}function Ln(e,t="value"){if(typeof e!="string"||e==="")throw new Error(`${t} must be a string`);return e}function $i(e,t="amount"){if(typeof e=="bigint")return e;if(typeof e=="number"){if(!Number.isInteger(e))throw new Error(`${t} must be an integer`);if(!Number.isSafeInteger(e))throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);return BigInt(e)}let n=kt(e,t);if(n==="")throw new Error(`${t} is required`);if(!/^-?\d+$/.test(n)&&!/^0x[0-9a-fA-F]+$/.test(n))throw new Error(`${t} must be an integer in decimal or 0x-hex form, got ${JSON.stringify(n)}`);try{return BigInt(n)}catch{throw new Error(`${t} must be an integer, got ${JSON.stringify(n)}`)}}function $n(e,t="amount"){let n=$i(e,t);if(n<=0n)throw new Error(`${t} must be positive`);return n}function ht(e,t,n="amount"){let r=kt(e,n);if(!/^-?\d*(\.\d+)?$/.test(r)||r===""||r==="."||r==="-")throw new Error(`${n} must be a decimal number, got ${JSON.stringify(r)}`);let o=r.startsWith("-"),i=o?r.slice(1):r,[s="0",a=""]=i.split(".");if(a.length>t)throw new Error(`${n} has more than ${t} decimal places, which would lose precision`);let c=BigInt((s||"0")+a.padEnd(t,"0"));return o?-c:c}var Js=Y(()=>{});function e8(e,t){let n=e.toString().padStart(t+1,"0");if(t===0)return n;let r=n.slice(0,-t),o=n.slice(-t).replace(/0+$/,"");return o?`${r}.${o}`:r}function dO(e,t){let n=kt(e,`hl: ${t}`);if(!/^\d+(?:\.\d+)?$/.test(n))throw new Error(`hl: ${t} must be a positive decimal`);let[r,o=""]=n.split("."),i=BigInt(r+o);if(i<=0n)throw new Error(`hl: ${t} must be positive`);return{raw:i,decimals:o.length}}function mr(e,t){if(e===null||typeof e=="string"||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`hl: ${t} must be finite JSON`);return JSON.stringify(e)}if(Array.isArray(e))return`[${e.map(r=>mr(r,t)).join(",")}]`;if(!e||typeof e!="object")throw new Error(`hl: ${t} must be structured JSON`);return`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${mr(e[r],t)}`).join(",")}}`}function t8(e){if(typeof e.orderType!="string"||!e.orderType)throw new Error("hl: order type must be a string");let t=e.orderType,n=e.orderWire;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("hl: declared order wire required");if(t==="limit"){let i=n.limit?.tif;if(!["Gtc","Ioc","Alo"].includes(i)||mr(n,"declared order type")!==mr({limit:{tif:i}},"expected order type"))throw new Error("hl: limit order type must match its wire shape");return}if(t==="market"){if(mr(n,"declared order type")!==mr({limit:{tif:"Ioc"}},"expected order type"))throw new Error("hl: market order type must match its IOC wire shape");return}let r={stopMarket:{isMarket:!0,tpsl:"sl"},stopLimit:{isMarket:!1,tpsl:"sl"},takeProfitMarket:{isMarket:!0,tpsl:"tp"},takeProfitLimit:{isMarket:!1,tpsl:"tp"}}[t];if(!r)throw new Error("hl: unsupported declared order type");let o=n.trigger?.triggerPx;if(o==null||mr(n,"declared order type")!==mr({trigger:{isMarket:r.isMarket,triggerPx:o,tpsl:r.tpsl}},"expected order type"))throw new Error("hl: trigger order type must match its wire shape")}function n8(e,t,n){let r=dO(e.s,"signed size"),o=dO(e.p,"signed price"),i=r.decimals+o.decimals,s=r.raw*o.raw,a=ht(t.notionalUsd,i,"hl: notionalUsd");if(a<=0n||s!==a)throw new Error("hl: signed notional must match");let c=ht(n.maxNotionalUsd,i,"hl: maxNotionalUsd");if(s>c)throw new Error("hl: notional exceeds cap")}function r8(e,t){let n=e.action.builder;if(n==null){if(e.builder!=null)throw new Error("hl: declared builder requires a signed builder");return}if(!n||typeof n!="object"||Array.isArray(n))throw new Error("hl: signed order builder must be structured");let r=Ro(n.b,"order builder",42).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(r))throw new Error("hl: order builder address required");if(Ln(e.builder||"","hl: builder").toLowerCase()!==r)throw new Error("hl: signed order builder must match");if(!(Array.isArray(t.hlBuilders)?t.hlBuilders.map(a=>String(a).toLowerCase()):[]).includes(r))throw new Error("hl: order builder not allowed");let i=$i(n.f,"hl: signed order builder fee");if(i<0n)throw new Error("hl: signed order builder fee must be non-negative");let s=ht(t.maxBuilderFeeBps??0,1,"hl: maxBuilderFeeBps");if(i>s)throw new Error("hl: order builder fee exceeds cap")}function pO(e,t,n){if(!Number.isSafeInteger(e.a)||e.a!==n)throw new Error("hl: signed asset must match assetId");if(typeof e.b!="boolean"||e.b!==(t.side==="buy"))throw new Error("hl: signed side must match exactly");if(kt(e.s,"hl: signed size")!==kt(t.size,"hl: size"))throw new Error("hl: signed size must match");if(kt(e.p,"hl: signed price")!==kt(t.price,"hl: price"))throw new Error("hl: signed price must match");if(typeof t.reduceOnly!="boolean"||typeof e.r!="boolean"||e.r!==t.reduceOnly)throw new Error("hl: signed reduceOnly must match exactly");if(mr(e.t,"signed order type")!==mr(t.orderWire,"declared order type"))throw new Error("hl: signed order type must match declared order type");let r=Object.prototype.hasOwnProperty.call(e,"c");if(t.clientOrderId==null){if(r)throw new Error("hl: undeclared signed client order id")}else if(!r||typeof e.c!="string"||e.c!==t.clientOrderId)throw new Error("hl: signed client order id must match")}function fO(e,t,n,r,o){if(!Number.isSafeInteger(e.a)||e.a!==n)throw new Error("hl: bracket protection asset must match");if(typeof e.b!="boolean"||e.b===(t.side==="buy"))throw new Error("hl: bracket protection side must oppose entry");if(kt(e.s,"hl: bracket protection size")!==kt(t.size,"hl: size"))throw new Error("hl: bracket protection size must match");if(kt(e.p,"hl: bracket protection price")!==kt(r,"hl: protection price"))throw new Error("hl: bracket protection price must match");if(e.r!==!0)throw new Error("hl: bracket protection must be reduce-only");let i=e.t?.trigger;if(!i||i.isMarket!==!0||i.tpsl!==o)throw new Error("hl: bracket protection trigger must match");if(kt(i.triggerPx,"hl: triggerPx")!==kt(r,"hl: protection price"))throw new Error("hl: bracket protection trigger must match")}function o8(e){let t=String(e||"").replace(/\/$/,"");if(!J9.has(t))throw new Error("hl: submitTo must be the official Hyperliquid exchange");return t}function jb(e){return Co(e)!=null}function i8(e,t){let n=String(e||""),r=Array.isArray(t.coins)?t.coins.map(String):[];if(jb(n)){if(t.hip4!==!0)throw new Error("hl: HIP-4 outcome orders are disabled without explicit policy enablement");if(r.includes(n)||r.includes("#*")||r.includes("*")||r.length===0)return!0;throw new Error("hl: outcome coin not allowed")}if(r.length&&!r.includes(n)&&!r.includes("*"))throw new Error("hl: coin not allowed");return!0}function s8(e,t,n){let r=Array.isArray(n.hlMarkets)?n.hlMarkets:[];if(r.length){if(!r.some(s=>{if(typeof s=="string"){let[a,c]=String(s).split(":");return a===e&&Number(c)===t}return String(s?.coin)===e&&Number(s?.assetId)===t}))throw new Error("hl: coin/assetId pair not allowed");return!0}if(jb(e)){let i=Array.isArray(n.coins)?n.coins.map(String):[];if(i.includes("#*")||i.includes("*")||i.length===0)return!0;throw new Error("hl: restricted coin policy requires hlMarkets pairs")}let o=Array.isArray(n.coins)?n.coins.map(String):[];if(o.length&&!o.includes("*"))throw new Error("hl: restricted coin policy requires hlMarkets pairs");return!0}function mO(e,t){if(e?.surface!=="hl")throw new Error("hl: surface hl required");let n=e.artifact;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("hl: structured artifact required");let r=Ro(n.kind,"kind",48),o=Q9[r];if(!o)throw new Error("hl: unsupported Hyperliquid kind");if(e.action!==o)throw new Error("hl: surface/action/kind mismatch");if(String(e.destination).toLowerCase()!=="hyperliquid")throw new Error("hl: destination must be hyperliquid");if(!/^0x[0-9a-fA-F]{40}$/.test(String(e.owner||"")))throw new Error("hl: owner required");let i=o8(n.submitTo);if(Object.prototype.hasOwnProperty.call(n,"vaultAddress"))throw new Error("hl: vaultAddress is not public");if(Object.prototype.hasOwnProperty.call(n,"expiresAfter"))throw new Error("hl: expiresAfter is not public");let s=Number(n.nonce);if(!Number.isSafeInteger(s)||s<=0)throw new Error("hl: nonce must be a positive integer");if(!n.action||typeof n.action!="object")throw new Error("hl: signed action required");if(Object.prototype.hasOwnProperty.call(n.action,"vaultAddress"))throw new Error("hl: action vaultAddress is not public");if(Object.prototype.hasOwnProperty.call(n.action,"expiresAfter"))throw new Error("hl: action expiresAfter is not public");if(n.action.type!==Z9[r])throw new Error("hl: action type must match kind");let a=n.notionalUsd??0;if(X9.has(r)||r==="perp-cancel"||r==="perp-leverage"||r==="perp-isolated-margin"){let c=Ro(n.coin,"coin",64),l=n.assetId??n.assetIndex;if(!Number.isSafeInteger(l)||l<0)throw new Error("hl: assetId required");if(r==="hip4-order"||l>=1e8){let u=Co(c);if(!u||u.coin!==c)throw new Error("hl: HIP-4 actions must use a canonical outcome coin");if(u.assetId!==l)throw new Error("hl: HIP-4 coin must bind to its canonical assetId")}if(i8(c,t),s8(c,l,t),r==="hip4-order"&&!jb(c))throw new Error("hl: HIP-4 orders must use an outcome coin");if(r==="perp-order"||r==="hip3-order"||r==="hip4-order"||r==="perp-bracket"){if(n.side!=="buy"&&n.side!=="sell")throw new Error("hl: side must be buy or sell");if(n.action.type!=="order"||!Array.isArray(n.action.orders))throw new Error("hl: signed orders are required");t8(n);let u=n.action.orders;if(r==="perp-bracket"){let d=n.takeProfitPx,p=n.stopLossPx,f=1+(d==null?0:1)+(p==null?0:1);if(f<2||u.length!==f||n.grouping!=="normalTpsl"||n.action.grouping!==n.grouping)throw new Error("hl: bracket must contain exactly the declared entry and protection legs");pO(u[0],n,l);let m=1;d!=null&&fO(u[m++],n,l,d,"tp"),p!=null&&fO(u[m],n,l,p,"sl")}else{if(u.length!==1)throw new Error("hl: exactly one signed order is required");if(n.grouping!=="na"||n.action.grouping!==n.grouping)throw new Error("hl: signed grouping must match declared grouping");pO(u[0],n,l)}n8(u[0],n,t),r8(n,t),a=kt(n.notionalUsd,"hl: notionalUsd")}if(r==="perp-leverage"){let u=n.leverage;if(!Number.isSafeInteger(u)||u<1)throw new Error("hl: leverage must be a positive integer");let d=t.maxLeverage==null?50:t.maxLeverage;if(typeof d!="number"||!Number.isSafeInteger(d)||d<1)throw new Error("hl: maxLeverage must be a positive integer");if(u>d)throw new Error("hl: leverage exceeds cap")}if(r==="perp-cancel"){let u=n.action.cancels;if(!Array.isArray(u)||u.length!==1)throw new Error("hl: exactly one cancel is required");if(!Number.isSafeInteger(u[0].a)||u[0].a!==l)throw new Error("hl: signed cancel asset must match assetId");if(!Number.isSafeInteger(n.orderId)||n.orderId<0)throw new Error("hl: declared order id required");if(!Number.isSafeInteger(u[0].o)||u[0].o!==n.orderId)throw new Error("hl: signed cancel order id must match")}if(r==="perp-leverage"){if(!Number.isSafeInteger(n.action.asset)||n.action.asset!==l)throw new Error("hl: signed leverage asset must match assetId");if(!Number.isSafeInteger(n.action.leverage)||n.action.leverage!==n.leverage)throw new Error("hl: signed leverage must match");if(!["cross","isolated"].includes(n.marginMode))throw new Error("hl: declared margin mode required");let u=n.marginMode==="cross";if(typeof n.action.isCross!="boolean"||n.action.isCross!==u)throw new Error("hl: signed isCross must match declared margin mode")}if(r==="perp-isolated-margin"){if(!Number.isSafeInteger(n.action.asset)||n.action.asset!==l)throw new Error("hl: signed margin asset must match assetId");let u=Ro(n.usd,"margin usd",64),d=ht(u,6,"hl: margin usd");if($i(n.action.ntli,"hl: signed margin ntli")!==d)throw new Error("hl: signed margin amount must match usd");if(typeof n.isBuy!="boolean"||n.action.isBuy!==n.isBuy)throw new Error("hl: signed margin isBuy must match");let f=ht(t.maxNotionalUsd,6,"hl: maxNotionalUsd"),m=d<0n?-d:d;if(m>f)throw new Error("hl: margin notional exceeds cap");a=e8(m,6)}}if(r==="builder-fee-approval"){let c=Ro(n.builder,"builder",42).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(c))throw new Error("hl: builder address required");if(Ro(n.action.builder,"signed builder",42).toLowerCase()!==c)throw new Error("hl: signed builder must match");if(!(Array.isArray(t.hlBuilders)?t.hlBuilders.map(m=>String(m).toLowerCase()):[]).includes(c))throw new Error("hl: builder not allowed");let u=Ro(n.maxFeeRate,"maxFeeRate",32);if(Ro(n.action.maxFeeRate,"signed maxFeeRate",32)!==u)throw new Error("hl: signed builder fee must match");if(!/^\d+(?:\.\d+)?%$/.test(u))throw new Error("hl: builder fee rate must be a percent");let d=ht(u.slice(0,-1),12,"hl: builder fee percent"),p=ht(t.maxBuilderFeeBps,12,"hl: maxBuilderFeeBps");if(p<0n||d*100n>p)throw new Error("hl: builder fee exceeds cap");if(Number(n.action.nonce)!==s)throw new Error("hl: signed builder nonce must match");let f=i.includes("testnet")?"Testnet":"Mainnet";if(n.hyperliquidChain!==f||n.action.hyperliquidChain!==n.hyperliquidChain)throw new Error("hl: signed Hyperliquid chain must match destination");if(n.signatureChainId!=="0x66eee"||n.action.signatureChainId!==n.signatureChainId)throw new Error("hl: signed signature chain id must match")}if(r.startsWith("hype-stake")||r==="hype-delegate"||r==="hype-undelegate"){if(r==="hype-delegate"||r==="hype-undelegate"){let c=r==="hype-undelegate";if(typeof n.action.isUndelegate!="boolean"||n.action.isUndelegate!==c)throw new Error("hl: signed isUndelegate must match delegate kind exactly")}if(t.maxHypeWei!=null&&BigInt(String(n.action.wei??n.caps?.amountHype??"0"))>BigInt(t.maxHypeWei))throw new Error("hl: stake amount exceeds cap")}return Object.freeze({unit:"usd",value:String(a??n.action.wei??0),notional:String(a??0),fee:"0",kind:r,actionType:n.action.type,amount:String(n.action.wei??a??0),coin:n.coin||null,submitTo:i})}var J9,X9,Q9,Z9,Ro,hO=Y(()=>{Js();jp();J9=new Set(["https://api.hyperliquid.xyz/exchange","https://api.hyperliquid-testnet.xyz/exchange"]),X9=new Set(["perp-order","hip3-order","hip4-order","perp-bracket"]),Q9=Object.freeze({"perp-order":"order","hip3-order":"order","hip4-order":"order","perp-bracket":"order","perp-cancel":"cancel","perp-leverage":"leverage","perp-isolated-margin":"margin","builder-fee-approval":"approveBuilder","hype-stake-deposit":"stake","hype-stake-withdraw":"unstake","hype-delegate":"delegate","hype-undelegate":"delegate"}),Z9=Object.freeze({"perp-order":"order","hip3-order":"order","hip4-order":"order","perp-bracket":"order","perp-cancel":"cancel","perp-leverage":"updateLeverage","perp-isolated-margin":"updateIsolatedMargin","builder-fee-approval":"approveBuilderFee","hype-stake-deposit":"cDeposit","hype-stake-withdraw":"cWithdraw","hype-delegate":"tokenDelegate","hype-undelegate":"tokenDelegate"}),Ro=(e,t,n=256)=>{if(typeof e!="string"||!e||e.length>n)throw new Error(`hl: bounded ${t} required`);return e}});function c8(e){let t=e.owner||e.user||e.from||e.recipient;if(!/^0x[0-9a-fA-F]{40}$/.test(String(t||"")))throw new Error("hl: owner/user address required for local-signer envelope");return String(t).toLowerCase()}function Hp(e,t={},n={}){let r=String(e?.kind||""),o=a8[r];if(!o)throw new Error("hl: prepared kind is not a local-signer surface");if(!e?.action||typeof e.action!="object")throw new Error("hl: prepared action required");let i=Number(n.nowMs??Date.now()),s=Math.min(6e4,Math.max(1e3,Number(t.ttlMs??t.expiresInMs??3e4)||3e4)),a=String(e.submitTo||"").replace(/\/$/,""),c={version:1,surface:"hl",action:o,owner:c8(t),destination:"hyperliquid",tradeId:String(t.tradeId||`hl:${r}:${e.nonce}`),expiresAtMs:i+s,slippageBps:Number(t.slippageBps??0),fee:{oracleFeeBps:0},provider:e.provider,artifact:{kind:r,coin:e.coin??null,assetId:e.assetId??e.assetIndex??null,side:e.side??null,size:e.size??null,price:e.price??null,reduceOnly:e.reduceOnly??null,orderType:e.orderType??null,orderWire:e.action?.orders?.[0]?.t??null,clientOrderId:e.action?.orders?.[0]?.c??null,grouping:e.action?.grouping??null,orderId:e.orderId??null,leverage:e.leverage??null,marginMode:e.marginMode??null,notionalUsd:e.notionalUsd??0,usd:e.usd??null,isBuy:e.isBuy??null,takeProfitPx:e.takeProfitPx??null,stopLossPx:e.stopLossPx??null,builder:e.builderFee?.address??e.action?.builder??null,maxFeeRate:e.builderFee?.percent??e.action?.maxFeeRate??null,nonce:e.nonce,hyperliquidChain:e.action?.hyperliquidChain??null,signatureChainId:e.signatureChainId||e.action?.signatureChainId||"0xa4b1",submitTo:a,action:e.action,typedData:e.typedData||null,caps:e.caps||null}};return mO(c,{coins:t.coins||["*"],hip4:!0,maxNotionalUsd:t.maxNotionalUsd??Number.MAX_SAFE_INTEGER,maxLeverage:t.maxLeverage??50,hlBuilders:t.hlBuilders||(e.builderFee?.address?[e.builderFee.address]:[]),maxBuilderFeeBps:t.maxBuilderFeeBps??e.builderFee?.bps}),c}var a8,Hb=Y(()=>{hO();a8=Object.freeze({"perp-order":"order","hip3-order":"order","hip4-order":"order","perp-bracket":"order","perp-cancel":"cancel","perp-leverage":"leverage","perp-isolated-margin":"margin","builder-fee-approval":"approveBuilder","hype-stake-deposit":"stake","hype-stake-withdraw":"unstake","hype-delegate":"delegate","hype-undelegate":"delegate"})});var Zb={};vt(Zb,{HL_BUILDER_ADDRESS_ENV:()=>zp,HL_BUILDER_DEFAULT_FEE_BPS:()=>l8,HL_BUILDER_FEE_ENV:()=>Vb,HL_BUILDER_FEE_TIERS:()=>al,HL_BUILDER_MAX_FEE_BPS:()=>zb,HL_PERP_MAX_SIG_FIGS:()=>gO,HL_PERP_PRICE_DECIMALS:()=>yO,HL_SIGNATURE_CHAIN_ID:()=>Vp,MARGIN_MODE:()=>cl,ORDER_TYPES:()=>ln,TIF:()=>ll,formatPerpPrice:()=>Hr,formatPerpSize:()=>EO,hlBuilderFeeBpsForKind:()=>SO,hlPerpAssetInfo:()=>Lo,hlPrepareApproveAgent:()=>g8,hlPrepareBracketOrder:()=>Qb,hlPrepareBuilderApproval:()=>Yb,hlPrepareCancelOrder:()=>ul,hlPreparePerpOrder:()=>$o,hlPrepareUpdateIsolatedMargin:()=>Xb,hlPrepareUpdateLeverage:()=>Jb,resolveBuilderFee:()=>Gb});function bO(e,t){if(typeof e=="number"){if(Number.isSafeInteger(e)&&e>=0)return e}else if(typeof e=="string"&&/^(?:0|[1-9]\d*)$/.test(e)){let n=Number(e);if(Number.isSafeInteger(n))return n}throw new Error(`hl-perps: ${t} must be a non-negative safe integer`)}function u8(e,t){let n=bO(e,t);if(n<1)throw new Error(`hl-perps: ${t} must be a positive integer`);return n}function d8(e={}){let t={...e};if(t.side==null)return t;if(t.side===0||t.side===1){if(t.outcomeSide!=null&&t.outcomeSide!==t.side)throw new Error("hl-perps: side conflict with outcomeSide");return t.outcomeSide=t.side,delete t.side,t}throw new Error("hl-assets: side must be 0 or 1")}function wO(e,{defaultBuy:t=!1}={}){if(e.side!=null){if(typeof e.side!="string")throw new Error("hl-perps: side must be buy or sell");let n=e.side.toLowerCase();if(n!=="buy"&&n!=="sell")throw new Error("hl-perps: side must be buy or sell");let r=n==="buy";if(e.isBuy!=null&&(typeof e.isBuy!="boolean"||e.isBuy!==r))throw new Error("hl-perps: side and isBuy conflict");return r}if(e.isBuy==null&&t)return!0;if(typeof e.isBuy!="boolean")throw new Error("hl-perps: isBuy must be boolean when side is omitted");return e.isBuy}function SO(e="perp"){if(e==="perp"||e==="main")return al.perp;if(e==="spot")return al.spot;if(e==="hip3")return al.hip3;if(e==="outcome"||e==="hip4")return al.hip4;throw new Error(`hl-perps: unknown builder fee kind ${e}`)}function Gb({env:e=process.env,isHolder:t=!1,kind:n="perp"}={}){if(t)return null;let r=String(e?.[zp]||"").trim().toLowerCase();if(!r)return null;if(!/^0x[a-f0-9]{40}$/.test(r))throw new Error(`hl-perps: ${zp} must be an EVM address`);let o=fy(e);if(!o||o!==r)return null;let i=e?.[Vb],s=SO(n),a=i==null?s:Number(i);if(!Number.isFinite(a)||a<=0||Math.abs(a*10-Math.round(a*10))>1e-9)throw new Error(`hl-perps: ${Vb} must be a positive number in 0.1 bps increments`);if(a>zb)throw new Error(`hl-perps: builder fee ${a} bps exceeds the ${zb} bps cap`);if(a>s)throw new Error(`hl-perps: builder fee ${a} bps exceeds the ${s} bps product tier for ${n}`);let c=Math.round(a*10),l=(c/1e3).toFixed(3).replace(/0+$/,"").replace(/\.$/,"");return{wire:{b:r,f:c},disclosure:{address:r,bps:a,percent:`${l}%`}}}async function p8(e,t={},n={}){if(!e)return{approved:!1,approvedFeeBps:0,status:"not-configured"};let r=String(t.user||n.user||"").trim().toLowerCase();if(!/^0x[a-f0-9]{40}$/.test(r))return{approved:!1,approvedFeeBps:0,status:"wallet-required"};try{let o=Number(await _e({type:"maxBuilderFee",user:r,builder:e.disclosure.address},n));return!Number.isInteger(o)||o<0?{approved:!1,approvedFeeBps:0,status:"invalid-response"}:{approved:o>=e.wire.f,approvedFeeBps:o/10,status:o>=e.wire.f?"approved":"insufficient"}}catch{return{approved:!1,approvedFeeBps:0,status:"unavailable"}}}async function f8(e,t={},n={}){if(!e)return{exempt:!1,status:"not-configured"};let r=String(t.user||n.user||"").trim().toLowerCase();if(!/^0x[a-f0-9]{40}$/.test(r))return{exempt:!1,status:"wallet-required"};try{let o=n.holderBalance||rp;return BigInt(await o(r))>0n?{exempt:!0,status:"holder"}:{exempt:!1,status:"non-holder"}}catch{return{exempt:!1,status:"unavailable"}}}function Kb(e,t,{roundDown:n=null}={}){let r=typeof e=="number"?e.toFixed(Math.min(20,t+8)):e;if(typeof r!="string"||!/^-?\d+(\.\d+)?$/.test(r))throw new Error(`hl-perps: "${e}" is not a decimal number`);let o=r.startsWith("-"),[i,s=""]=r.replace(/^-/,"").split(".");if(s.length<=t){let m=s.replace(/0+$/,"");return(o?"-":"")+(m?`${i}.${m}`:i)}let a=s.slice(0,t),c=Number(s[t]),l=BigInt(i+a),u=s.slice(t).replace(/0+$/,"")!=="";n===!0||(n===!1?u&&(l+=1n):c>=5&&(l+=1n));let d=l.toString().padStart(t+1,"0"),f=(t===0?d:`${d.slice(0,-t)}.${d.slice(-t)}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"");return(o?"-":"")+f}function m8(e,t,n={}){if(typeof e!="number"&&typeof e!="string")throw new Error(`hl-perps: "${e}" is not a decimal number`);let r=typeof e=="number"?String(e):e;if(!r.includes("."))return r;let o=Number(r);if(!Number.isFinite(o)||o===0)return r;let i=Math.floor(Math.log10(Math.abs(o))),s=Math.max(0,t-1-i);return Kb(r,s,n)}function Hr(e,t,n={}){let r=yO-Number(t??0);if(r<0)throw new Error("hl-perps: szDecimals out of range");return Kb(m8(e,gO,n),r,n)}function EO(e,t){let n=Kb(e,Number(t??0));if(BigInt(n.split(".")[0])<0n)throw new Error("hl-perps: size must be positive");if(Number(n)<=0)throw new Error("hl-perps: size rounds to zero at this asset's precision");return n}function h8(e,t){let n=(u,d)=>{let p=String(u).trim();if(!/^\d+(?:\.\d+)?$/.test(p))throw new Error(`hl-perps: ${d} must be a positive decimal`);let[f,m=""]=p.split(".");return{raw:BigInt(f+m),decimals:m.length}},r=n(e,"size"),o=n(t,"price"),i=r.raw*o.raw,s=r.decimals+o.decimals,a=i.toString().padStart(s+1,"0");if(s===0)return a;let c=a.slice(0,-s),l=a.slice(-s).replace(/0+$/,"");return l?`${c}.${l}`:c}async function Lo(e={},t={}){let n=await qb(e,t);return{coin:n.coin,assetId:n.assetId,szDecimals:n.szDecimals,maxLeverage:n.maxLeverage,markPx:n.markPx,kind:n.kind,dex:n.dex??null,dexName:n.dexName??null,outcome:n.outcome??null,side:n.side??null}}function Wb(e,{tif:t=ll.GTC,triggerPx:n,isMarket:r,szDecimals:o}={}){switch(e){case ln.LIMIT:return{limit:{tif:t}};case ln.MARKET:return{limit:{tif:ll.IOC}};case ln.STOP_MARKET:case ln.TAKE_PROFIT_MARKET:return{trigger:{isMarket:!0,triggerPx:Hr(n,o),tpsl:e===ln.STOP_MARKET?"sl":"tp"}};case ln.STOP_LIMIT:case ln.TAKE_PROFIT_LIMIT:return{trigger:{isMarket:!1,triggerPx:Hr(n,o),tpsl:e===ln.STOP_LIMIT?"sl":"tp"}};default:throw new Error(`hl-perps: unknown order type ${e}`)}}function Mi(e,t,n={}){let r=n.testnet||process.env.HL_TESTNET==="1";return{action:e,nonce:t,signatureChainId:Vp,submitTo:r?"https://api.hyperliquid-testnet.xyz/exchange":"https://api.hyperliquid.xyz/exchange",note:"Sign locally via Oracle local-signer or a wallet. Hosted Oracle does not submit."}}function Xs(e,t={},n={}){let r={...e};try{r.localSignerEnvelope=Hp(r,t,n),r.prepared=!0,r.signing="awaiting-hl-signer"}catch(o){r.prepared=!1,r.localSignerEnvelope=null,r.localSignerBlockedReason=String(o?.message||o).slice(0,200),r.signing="blocked"}return r.oraclePrepared=!!r.localSignerEnvelope,q(r,{provider:e.provider||"hl-perps",kind:e.kind})}function Yb(e={},t={}){let n=Gb({env:t.env});if(!n)throw new Error(`hl-perps: ${zp} is required`);let r=Number(e.nonce??t.nonce??Date.now());if(!Number.isSafeInteger(r)||r<=0)throw new Error("hl-perps: nonce must be a positive integer");let o={type:"approveBuilderFee",hyperliquidChain:t.testnet||process.env.HL_TESTNET==="1"?"Testnet":"Mainnet",signatureChainId:Vp,maxFeeRate:n.disclosure.percent,builder:n.disclosure.address,nonce:r};return Xs({provider:"hl-perps",venue:"hyperliquid",kind:"builder-fee-approval",builderFee:n.disclosure,...Mi(o,r,t)},e,t)}function g8(e={},t={}){let n=String(e.agentAddress||e.agent||"").trim();if(!/^0x[0-9a-fA-F]{40}$/.test(n))throw new Error("hl-perps: agentAddress required");let r=Number(e.nonce??t.nonce??Date.now());if(!Number.isSafeInteger(r)||r<=0)throw new Error("hl-perps: nonce must be a positive integer");let o=String(e.agentName||"Oracle").slice(0,16),i={type:"approveAgent",hyperliquidChain:t.testnet||process.env.HL_TESTNET==="1"?"Testnet":"Mainnet",signatureChainId:Vp,agentAddress:n.toLowerCase(),agentName:o,nonce:r};return q({provider:"hl-perps",venue:"hyperliquid",kind:"hl-approve-agent",unsigned:!0,broadcast:!1,agentAddress:n.toLowerCase(),agentName:o,...Mi(i,r,t)},{provider:"hl-perps",kind:"hl-approve-agent",env:t.env})}async function $o(e={},t={}){let n=await Lo(e,t);if(e.type!=null&&(typeof e.type!="string"||!e.type))throw new Error("hl-perps: order type must be a string");let r=e.type??ln.LIMIT;if(typeof r!="string"||!r)throw new Error("hl-perps: order type must be a string");let o=wO(e);if(e.reduceOnly!=null&&typeof e.reduceOnly!="boolean")throw new Error("hl-perps: reduceOnly must be boolean");let i=e.reduceOnly===!0,s=EO(e.size??e.sz,n.szDecimals),a;if(r===ln.MARKET){let b=Number(n.markPx);if(!Number.isFinite(b)){let x=await Gn(t);b=Number(x?.[n.coin]??x?.[String(n.assetId)]??NaN)}if(!Number.isFinite(b))throw new Error("hl-perps: no mark price available for a market order");let S=Number(e.maxSlippageBps??50);if(!Number.isInteger(S)||S<0)throw new Error("hl-perps: maxSlippageBps must be a non-negative integer");if(S>100)throw new Error(`hl-perps: maxSlippageBps ${S} exceeds the hard 100 bps cap`);let w=o?b*(1+S/1e4):b*(1-S/1e4);a=Hr(w,n.szDecimals,{roundDown:o});let E=Math.abs(Number(a)/b-1)*1e4;if(E>S+1e-9)throw new Error(`hl-perps: tick rounding makes the limit ${E.toFixed(2)} bps from mark, above the ${S} bps cap`)}else{if(e.price==null&&e.limitPx==null)throw new Error("hl-perps: a limit order requires an explicit price");a=Hr(e.price??e.limitPx,n.szDecimals)}let c=Wb(r,{tif:e.tif??(r===ln.MARKET?ll.IOC:ll.GTC),triggerPx:e.triggerPx,szDecimals:n.szDecimals}),l={a:n.assetId,b:o,p:a,s,r:i,t:c};if(e.clientOrderId!=null){if(typeof e.clientOrderId!="string"||!e.clientOrderId)throw new Error("hl-perps: clientOrderId must be a string");l.c=e.clientOrderId}if(e.grouping!=null&&(typeof e.grouping!="string"||!e.grouping))throw new Error("hl-perps: grouping must be a string");let u={type:"order",orders:[l],grouping:e.grouping??"na"},d=Gb({env:t.env,kind:n.kind}),p=await f8(d,e,t),f=p.exempt?null:d,m=await p8(f,e,t),h=m.approved?f:null;h&&(u.builder=h.wire);let g=Number(e.nonce??Date.now()),y=h8(s,a);return Xs({provider:"hl-perps",venue:"hyperliquid",kind:n.kind==="outcome"?"hip4-order":n.kind==="hip3"?"hip3-order":"perp-order",coin:n.coin,assetId:n.assetId,assetKind:n.kind,outcome:n.outcome??null,outcomeSide:n.side??null,dex:n.dex??null,dexName:n.dexName??null,side:o?"buy":"sell",orderType:r,price:a,size:s,reduceOnly:i,notionalUsd:y,maxLeverage:n.maxLeverage,markPx:n.markPx,builderFee:h?.disclosure??null,holderExempt:p.exempt,holderVerificationStatus:p.status,builderApprovalRequired:f&&!h?{...d.disclosure,...m}:null,...Mi(u,g,t)},e,t)}async function ul(e={},t={}){let n=await Lo(d8(e),t),r=e.orderId??e.oid;if(r==null)throw new Error("hl-perps: orderId required");let o=bO(r,"orderId"),i={type:"cancel",cancels:[{a:n.assetId,o}]};return Xs({provider:"hl-perps",venue:"hyperliquid",kind:"perp-cancel",coin:n.coin,assetId:n.assetId,orderId:o,...Mi(i,Number(e.nonce??Date.now()),t)},e,t)}async function Jb(e={},t={}){let n=await Lo(e,t),r=u8(e.leverage,"leverage");if(n.maxLeverage!=null&&r>n.maxLeverage)throw new Error(`hl-perps: ${n.coin} allows at most ${n.maxLeverage}x, requested ${r}x`);if(e.marginMode!=null&&typeof e.marginMode!="string")throw new Error("hl-perps: marginMode must be a string");let o=(e.marginMode||cl.CROSS).toLowerCase();if(o!==cl.CROSS&&o!==cl.ISOLATED)throw new Error('hl-perps: marginMode must be "cross" or "isolated"');let i={type:"updateLeverage",asset:n.assetId,isCross:o===cl.CROSS,leverage:r};return Xs({provider:"hl-perps",venue:"hyperliquid",kind:"perp-leverage",coin:n.coin,assetId:n.assetId,leverage:r,marginMode:o,maxLeverage:n.maxLeverage,liquidationWarning:r>=20?`${r}x liquidates on roughly a ${(100/r).toFixed(2)}% adverse move before fees`:null,...Mi(i,Number(e.nonce??Date.now()),t)},e,t)}async function Xb(e={},t={}){let n=await Lo(e,t),r=e.usd??e.amountUsd;if(r==null)throw new Error("hl-perps: usd amount required");if(typeof r!="number"&&typeof r!="string")throw new Error("hl-perps: usd must be a decimal number");let o=typeof r=="number"?String(r):r;if(!/^-?\d+(\.\d+)?$/.test(o))throw new Error("hl-perps: usd must be a decimal number");let i=ht(o,6,"hl-perps: usd"),s=wO(e,{defaultBuy:!0}),a={type:"updateIsolatedMargin",asset:n.assetId,isBuy:s,ntli:i<=BigInt(Number.MAX_SAFE_INTEGER)?Number(i):i.toString()};return Xs({provider:"hl-perps",venue:"hyperliquid",kind:"perp-isolated-margin",coin:n.coin,assetId:n.assetId,isBuy:s,usd:o,...Mi(a,Number(e.nonce??Date.now()),t)},e,t)}async function Qb(e={},t={}){let n=await $o(e,t),r=await Lo(e,t),o=n.side==="buy",i=[n.action.orders[0]];if(e.takeProfitPx!=null&&i.push({a:r.assetId,b:!o,p:Hr(e.takeProfitPx,r.szDecimals),s:n.size,r:!0,t:Wb(ln.TAKE_PROFIT_MARKET,{triggerPx:e.takeProfitPx,szDecimals:r.szDecimals})}),e.stopLossPx!=null&&i.push({a:r.assetId,b:!o,p:Hr(e.stopLossPx,r.szDecimals),s:n.size,r:!0,t:Wb(ln.STOP_MARKET,{triggerPx:e.stopLossPx,szDecimals:r.szDecimals})}),i.length===1)throw new Error("hl-perps: a bracket needs takeProfitPx and/or stopLossPx");let s={type:"order",orders:i,grouping:"normalTpsl",...n.action.builder?{builder:n.action.builder}:{}};return Xs({provider:"hl-perps",venue:"hyperliquid",kind:"perp-bracket",coin:r.coin,assetId:r.assetId,side:n.side,price:n.price,size:n.size,reduceOnly:n.reduceOnly,orderType:n.orderType,notionalUsd:n.notionalUsd,legs:i.length,entry:{side:n.side,price:n.price,size:n.size},takeProfitPx:e.takeProfitPx==null?null:Hr(e.takeProfitPx,r.szDecimals),stopLossPx:e.stopLossPx==null?null:Hr(e.stopLossPx,r.szDecimals),builderFee:n.builderFee,...Mi(s,Number(e.nonce??Date.now()),t)},e,t)}var gO,yO,Vp,l8,zb,zp,Vb,al,ln,ll,cl,dl=Y(()=>{Ct();jp();Js();ae();Hb();dy();Cc();gO=5,yO=6,Vp="0x66eee",l8=2,zb=10,zp="ORACLE_HL_BUILDER_ADDRESS",Vb="ORACLE_HL_BUILDER_FEE_BPS",al=Object.freeze({perp:2,spot:1,hip3:1,hip4:1}),ln=Object.freeze({LIMIT:"limit",MARKET:"market",STOP_MARKET:"stopMarket",STOP_LIMIT:"stopLimit",TAKE_PROFIT_MARKET:"takeProfitMarket",TAKE_PROFIT_LIMIT:"takeProfitLimit"}),ll=Object.freeze({GTC:"Gtc",IOC:"Ioc",ALO:"Alo"}),cl=Object.freeze({CROSS:"cross",ISOLATED:"isolated"})});import{existsSync as kC,readFileSync as AC}from"node:fs";import{dirname as xC,join as Vf}from"node:path";import{fileURLToPath as rK}from"node:url";function IC(e){let t=xC(rK(e));for(let n=0;n<8;n+=1){let r=Vf(t,"package.json");if(kC(r))try{let i=JSON.parse(AC(r,"utf8"));if(i&&typeof i.version=="string")return t}catch{}let o=xC(t);if(o===t)break;t=o}throw new Error(`oracle: could not resolve package root from ${e}`)}function _C(e){return JSON.parse(AC(Vf(IC(e),"package.json"),"utf8"))}function Wf(e,t){let n=IC(t),r=Vf(n,e);return kC(r)?r:Vf(n,"dist","assets",e)}var Gf=Y(()=>{});import{isAddress as oK}from"ethers";function sK(e,t){return Object.freeze({id:e,contractName:t.contractName,source:t.source,dependency:Object.freeze({name:"OpenZeppelin Contracts",version:OC,tag:`v${OC}`}),constructor:Object.freeze([...t.constructor]),authority:Object.freeze([...t.authority]),monitor:Object.freeze([...t.monitor]),fixedSource:!0,proxy:!1,upgradeable:!1,arbitraryDelegatecall:!1,modelEmittedSource:!1})}function Kf(e){let t=Ki[String(e||"")];if(!t)throw new Error(`protocol-templates: unknown template "${e}"`);return t}function Zl(e,t){try{if(BigInt(e)<=0n)throw new Error}catch{throw new Error(`${t} must be > 0`)}}function eu(e,t){let n=String(e||"");if(!oK(n)||/^0x0{40}$/i.test(n))throw new Error(`${t} must be nonzero address`)}function TC(e,t){let n=Kf(e);if(!Array.isArray(t))throw new Error(`${e}: constructor args must be an array`);if(t.length!==n.constructor.length)throw new Error(`${e}: expected ${n.constructor.length} constructor args`);if(e==="safe-erc20"){let[r,o,i,s,a]=t;if(!String(r||"").trim()||!String(o||"").trim())throw new Error("safe-erc20: name/symbol required");Zl(i,"safe-erc20: supply"),eu(s,"safe-erc20: initialHolder"),eu(a,"safe-erc20: initialOwner")}else if(e==="safe-erc721-drop"){let[r,o,i,s,a,c,l]=t;if(!String(r||"").trim()||!String(o||"").trim())throw new Error("safe-erc721-drop: name/symbol required");if(Zl(i,"safe-erc721-drop: cap"),eu(s,"safe-erc721-drop: treasury"),Zl(a,"safe-erc721-drop: mintPrice"),Zl(c,"safe-erc721-drop: perWalletCap"),BigInt(c)>BigInt(i))throw new Error("safe-erc721-drop: perWalletCap exceeds cap");eu(l,"safe-erc721-drop: initialOwner")}else if(e==="safe-vesting"){let[r,o,i]=t;eu(r,"safe-vesting: beneficiary");for(let[s,a]of[[o,"startTimestamp"],[i,"durationSeconds"]])try{let c=BigInt(s);if(c<0n||c>18446744073709551615n)throw new Error}catch{throw new Error(`safe-vesting: ${a} must be uint64`)}Zl(i,"safe-vesting: durationSeconds")}return n}function NC(e){return{authorities:[...e.authority],proxy:!1,upgradeable:!1,arbitraryDelegatecall:!1}}var OC,iK,Ki,Yf=Y(()=>{OC="5.0.2",iK={"safe-erc20":{contractName:"SafeERC20",source:"src/SafeERC20.sol",constructor:["string name","string symbol","uint256 initialSupply","address initialHolder","address initialOwner"],authority:["initialOwner may pause transfers and use Ownable2Step"],monitor:["OwnershipTransferStarted","OwnershipTransferred","Paused","Unpaused","Transfer"]},"safe-erc721-drop":{contractName:"SafeERC721Drop",source:"src/SafeERC721Drop.sol",constructor:["string name","string symbol","uint256 cap","address treasury","uint256 mintPrice","uint256 perWalletCap","address initialOwner"],authority:["initialOwner may withdraw the full balance to immutable treasury","no mint, proxy, upgrade, or delegatecall authority"],monitor:["Transfer","OwnershipTransferred","Withdrawal"]},"safe-vesting":{contractName:"SafeVesting",source:"src/SafeVesting.sol",constructor:["address beneficiary","uint64 startTimestamp","uint64 durationSeconds"],authority:["beneficiary is the immutable OpenZeppelin owner/recipient identity","ownership transfer and renunciation are disabled","no separate administrator, proxy, upgrade, or delegatecall authority"],monitor:["EtherReleased","ERC20Released"]}};Ki=Object.freeze(Object.fromEntries(Object.entries(iK).map(([e,t])=>[e,sK(e,t)])))});import{spawnSync as RC}from"node:child_process";import{existsSync as PC,mkdtempSync as aK,readFileSync as cK,rmSync as lK}from"node:fs";import{tmpdir as uK}from"node:os";import{join as xw}from"node:path";function LC(e){let t=e.HOME||"";return`${t}/.local/bin:${t}/.foundry/bin:${e.PATH||""}`}function mK(e=process.env){return e.SLITHER_BIN?e.SLITHER_BIN:RC("slither",["--version"],{encoding:"utf8",env:{...e,PATH:LC(e)}}).status===0?"slither":null}function CC(e){return String(e||"").split(`
|
|
8
|
+
`)){let n=t.match(/^\s*OPENSEA_API_KEY\s*=\s*(.+)\s*$/);if(n)return n[1].replace(/^["']|["']$/g,"").trim()}}catch{}return""}function fr(e={}){return e.apiKey?e.apiKey:e.allowAmbientCredentials===!1||e.allowDiskCredentials===!1?e.env?.OPENSEA_API_KEY||e.env?.OPEN_SEA_API_KEY||"":e.env?.OPENSEA_API_KEY||process.env.OPENSEA_API_KEY||process.env.OPEN_SEA_API_KEY||XH()}function E_(e={}){return Ue({provider:"opensea",defaultUrl:y_,hosts:["api.opensea.io","testnets-api.opensea.io"],url:e.baseUrl||process.env.OPENSEA_API_URL})}function Ur(e={}){return E_(e).baseUrl}function Fr(e={}){return Je({accept:"application/json"},{"x-api-key":fr(e)},E_(e).trusted)}function v_(e){let t=String(e||"ethereum").trim().toLowerCase();if(!KH.has(t))throw new Error(`opensea: unsupported account chain ${t}`);return t}function pe(e,t="address"){try{return VH(String(e||"").trim().toLowerCase())}catch{throw new Error(`opensea: invalid ${t}`)}}function x_(e,t=null){let n=String(e||"").trim();if(!n)throw new Error("opensea: account address required");if(t&&!S_.has(t)||!t&&/^0x[0-9a-fA-F]{40}$/.test(n))return pe(n,"account address");if(!/^[1-9A-HJ-NP-Za-km-z]{32,64}$/.test(n))throw new Error("opensea: invalid account address");return n}function QH(e,t){let n=String(e??"").trim();if(!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(n)||Number(n)<=0)throw new Error(`opensea: ${t} must be a positive plain decimal`);return n}function ZH(e,t){let n=Number(e);if(!Number.isSafeInteger(n)||n<=0)throw new Error(`opensea: ${t} must be a positive integer`);return n}function p_(e,t){let n=String(e||"").trim(),r=Date.parse(n);if(!n||!Number.isFinite(r))throw new Error(`opensea: ${t} must be an ISO 8601 timestamp`);return{text:new Date(r).toISOString(),ms:r}}function e9(e={},t,n){return{chain:t,owner:n,contract:e.contract||null,tokenId:e.identifier==null?null:String(e.identifier),tokenStandard:e.token_standard||null,quantity:e.quantity==null&&e.balance==null?null:String(e.quantity??e.balance),collection:e.collection||null,name:e.name||null,description:e.description||null,imageUrl:e.display_image_url||e.image_url||e.original_image_url||null,originalImageUrl:e.original_image_url||e.image_url||null,animationUrl:e.display_animation_url||e.original_animation_url||null,metadataUrl:e.metadata_url||null,marketplaceUrl:e.opensea_url||null,estimatedValueUsd:e.estimated_value_usd!=null&&Number.isFinite(Number(e.estimated_value_usd))?Number(e.estimated_value_usd):null,spam:e.is_disabled===!0,disabled:e.is_disabled===!0,nsfw:e.is_nsfw===!0,traits:Array.isArray(e.traits)?e.traits:[],updatedAt:e.updated_at||null,acquisitionCost:null,itemPnl:{status:"unavailable",reason:"OpenSea account inventory does not expose trustworthy per-item acquisition cost"}}}function t9(e={}){return{base:Ur(e),headers:Fr(e),fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs}}async function sb(e={}){if(!fr(e))return{ok:!1,configured:!1,error:"OPENSEA_API_KEY not set"};try{let t=await js("boredapeyachtclub",e);return{ok:!0,configured:!0,name:t.name||t.collection}}catch(t){return{ok:!1,configured:!0,error:String(t.message||t).slice(0,160)}}}async function js(e,t={}){if(!e)throw new Error("collection slug required");if(!fr(t))throw new Error("OPENSEA_API_KEY required");return A(`${Ur(t)}/collections/${encodeURIComponent(e)}`,{headers:Fr(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function k_(e,t={}){if(!e)throw new Error("collection slug required");if(!fr(t))throw new Error("OPENSEA_API_KEY required");return A(`${Ur(t)}/collections/${encodeURIComponent(e)}/stats`,{headers:Fr(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function ab(e,t={}){let n=await js(e,t),r=n.stats||n.total||{},o=n.floor_price??n.floorPrice??r.floor_price??r.floorPrice??null;if(o==null){let d=await k_(e,t);r=d?.total||d?.stats||d||{},o=r.floor_price??r.floorPrice??null}let i=(Array.isArray(n.contracts)?n.contracts:[]).map(d=>({chain:String(d?.chain||d?.chain_identifier||n.chain||"").trim().toLowerCase(),address:String(d?.address||d?.contract_address||d?.contract||"").trim()})).filter(d=>d.chain&&d.address),s=String(t.expectedChain||"").trim().toLowerCase(),a=String(t.expectedContract||"").trim(),c=null;if(s&&a){let d=p=>s==="solana"?p:p.toLowerCase();if(c=i.find(p=>p.chain===s&&d(p.address)===d(a))||null,!c)throw new Error("opensea: collection identity does not match held contract")}let l=c?.chain||String(n.chain||"").trim().toLowerCase()||i[0]?.chain||"",u=String(n.floor_price_symbol||n.floorPriceSymbol||r.floor_price_symbol||r.floorPriceSymbol||"").trim().toUpperCase()||null;return{slug:n.collection||e,name:n.name||null,floor:o,chain:l||null,contracts:i,currency:u,totalSupply:n.total_supply??r.total_supply??null,numOwners:n.num_owners??r.num_owners??null,raw:{contracts:i,fees:n.fees,category:n.category}}}async function Hs(e={},t={}){if(!fr(t))throw new Error("OPENSEA_API_KEY required");let n=v_(e.chain),r=x_(e.address||e.owner,n),o=Math.min(Math.max(Number(e.pageSize??e.limit??200)||200,1),200),i=Math.min(Math.max(Number(e.maxPages??5)||5,1),25),s=[],a=e.next?String(e.next):null,c=0;do{let l=new URL(`${Ur(t)}/chain/${encodeURIComponent(n)}/account/${encodeURIComponent(r)}/nfts`);l.searchParams.set("limit",String(o)),e.collection&&l.searchParams.set("collection",String(e.collection)),a&&l.searchParams.set("next",a);let u=await A(l.toString(),{headers:Fr(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4});for(let d of Array.isArray(u?.nfts)?u.nfts:[])s.push(e9(d,n,r));a=u?.next?String(u.next):null,c+=1}while(a&&c<i);return{provider:"opensea-nft",source:"opensea-account-inventory",chain:n,owner:r,count:s.length,pages:c,complete:!a,next:a,nfts:s,exec:!1,readOnly:!0}}async function zc(e={},t={}){if(!fr(t))throw new Error("OPENSEA_API_KEY required");let n=x_(e.address||e.owner),r=await A(`${Ur(t)}/account/${encodeURIComponent(n)}/pnl`,{headers:Fr(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4});return{provider:"opensea-nft",source:"opensea-indexed-account-pnl",address:n,scope:"OpenSea-indexed account trading PnL across supported currencies, not per-item NFT cost basis",methodology:"provider-indexed",realizedPnlUsd:r?.realized_pnl_usd??null,unrealizedPnlUsd:r?.unrealized_pnl_usd??null,totalPnlUsd:r?.total_pnl_usd??null,netInvestedUsd:r?.net_invested_usd??null,currentValueUsd:r?.current_value_usd??null,returnPercentage:r?.return_percentage??null,itemLevelPnlAvailable:!1,raw:r,exec:!1,readOnly:!0}}function Wc(e){let t=String(e||"").trim().toLowerCase(),n=Vc[t];if(!n)throw new Error(`opensea: unsupported EVM chain ${t||"(missing)"}`);return{chain:t,chainId:n}}function sn(e,t,{positive:n=!1}={}){let r=String(e??"").trim();if(!/^\d+$/.test(r))throw new Error(`opensea: ${t} must be an unsigned integer`);let o=BigInt(r);if(n&&o<=0n)throw new Error(`opensea: ${t} must be positive`);return o}function n9(e,t="transaction value"){let n;try{let r=String(e??"0").trim();if(!/^(?:0x[0-9a-fA-F]+|\d+)$/.test(r))throw new Error("invalid");n=BigInt(r)}catch{throw new Error(`opensea: ${t} must be a non-negative integer quantity`)}if(n<0n)throw new Error(`opensea: ${t} must be non-negative`);return{amount:n,hex:`0x${n.toString(16)}`}}function Hc(e){let t=String(e??"").trim();if(!/^\d+$/.test(t))throw new Error("opensea: tokenId must be an unsigned integer string");return t}function A_(e,t=10){let n=Number(e??1);if(!Number.isSafeInteger(n)||n<1||n>t)throw new Error(`opensea: quantity must be an integer from 1 through ${t}`);return n}function I_(e,t,n="listing expiry"){let r=e==null?"":String(e).trim(),o;if(/^\d+$/.test(r)){let i=Number(r);o=r.length<=10?i*1e3:i}else o=Date.parse(r);if(!r||!Number.isFinite(o))throw new Error(`opensea: ${n} missing or invalid`);if(o<=t)throw new Error(`opensea: ${n} is expired or stale`);return new Date(o).toISOString()}function r9(e){return!!e&&typeof e=="object"&&[0,1].includes(Number(e.itemType))}function o9(e,t){let n=Number(e?.itemType);if(![0,1].includes(n))throw new Error(`opensea: ${t} is not a native or ERC20 payment item`);let r=pe(e?.token,t);if(n===0&&r!==qs)throw new Error(`opensea: ${t} native payment item must use the zero address`);if(n===1&&r===qs)throw new Error(`opensea: ${t} ERC20 payment item must name a non-zero token contract`);return r}function i9(e,t){let n=sn(e?.startAmount,`${t} startAmount`),r=sn(e?.endAmount??e?.startAmount,`${t} endAmount`);if(n!==r)throw new Error(`opensea: ${t} must be a fixed amount, not a decaying range`);return n}function ob(e,t,{required:n=!0}={}){let r=(Array.isArray(e)?e:[]).filter(r9);if(!r.length){if(n)throw new Error(`opensea: ${t} contains no native or ERC20 payment item`);return{paymentToken:null,totalWei:0n,count:0}}let o=null,i=0n;for(let s of r){let a=o9(s,`${t} payment token`);if(o==null)o=a;else if(a!==o)throw new Error(`opensea: ${t} mixes more than one payment token`);i+=i9(s,`${t} payment amount`)}return{paymentToken:o,totalWei:i,count:r.length}}function hn(e,t){let n=String(e??"").trim();if(!/^\d+$/.test(n))throw new Error(`opensea: ${t} must be an unsigned integer`);return n}function f_(e,t){let n=String(e??"").trim().toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(n))throw new Error(`opensea: ${t} must be a 32-byte hex value`);return n}function __(e,t){return{itemType:Number(hn(e?.itemType,`${t} itemType`)),token:pe(e?.token,`${t} token`),identifierOrCriteria:hn(e?.identifierOrCriteria,`${t} identifierOrCriteria`),startAmount:hn(e?.startAmount,`${t} startAmount`),endAmount:hn(e?.endAmount,`${t} endAmount`)}}function a9(e,t){return{...__(e,t),recipient:pe(e?.recipient,`${t} recipient`)}}function c9(e,t){if(!e||typeof e!="object")throw new Error(`opensea: ${t} has no canonical Seaport protocol parameters`);let n=Array.isArray(e.offer)?e.offer:null,r=Array.isArray(e.consideration)?e.consideration:null;if(!n||!n.length)throw new Error(`opensea: ${t} canonical offer array is missing`);if(!r||!r.length)throw new Error(`opensea: ${t} canonical consideration array is missing`);return{offerer:pe(e.offerer,`${t} offerer`),zone:pe(e.zone,`${t} zone`),offer:n.map((o,i)=>__(o,`${t} offer[${i}]`)),consideration:r.map((o,i)=>a9(o,`${t} consideration[${i}]`)),orderType:Number(hn(e.orderType,`${t} orderType`)),startTime:hn(e.startTime,`${t} startTime`),endTime:hn(e.endTime,`${t} endTime`),zoneHash:f_(e.zoneHash,`${t} zoneHash`),salt:hn(e.salt,`${t} salt`),conduitKey:f_(e.conduitKey,`${t} conduitKey`),counter:hn(e.counter,`${t} counter`)}}function O_(e,t,n){let r=String(e?.order_hash??e?.orderHash??"").trim().toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(r))throw new Error(`opensea: invalid ${n} order hash`);let o=c9(t,n);if(ib.hashStruct("OrderComponents",s9,o).toLowerCase()!==r)throw new Error(`opensea: ${n} order hash does not match its canonical Seaport parameters`);return r}function T_(e,t){let n=Number(e?.itemType);if([4,5].includes(n))throw new Error(`opensea: ${t} is a criteria item, not a fixed token`);if(![2,3].includes(n))throw new Error(`opensea: ${t} must be an ERC-721 or ERC-1155 item`);let r=pe(e?.token,`${t} contract`),o=Hc(e?.identifierOrCriteria),i=sn(e?.startAmount,`${t} startAmount`,{positive:!0}),s=sn(e?.endAmount??e?.startAmount,`${t} endAmount`,{positive:!0});if(i!==s)throw new Error(`opensea: ${t} must be a fixed quantity, not a decaying range`);if(n===2&&i!==1n)throw new Error(`opensea: ${t} ERC-721 quantity must be exactly 1`);if(i>BigInt(Number.MAX_SAFE_INTEGER))throw new Error(`opensea: ${t} quantity exceeds safe integer range`);return{itemType:n,contract:r,tokenId:o,quantity:Number(i)}}function l9(e,t){let n=Array.isArray(e?.offer)?e.offer:[];if(n.some(o=>[4,5].includes(Number(o?.itemType))))throw new Error(`opensea: ${t} uses a criteria offer item, not a fixed token`);let r=n.filter(o=>[2,3].includes(Number(o?.itemType)));if(r.length!==1||n.length!==1)throw new Error(`opensea: ${t} must offer exactly one fixed ERC-721 or ERC-1155 item`);return T_(r[0],`${t} offer NFT`)}function u9(e,t,n){let r=Array.isArray(e?.consideration)?e.consideration:[];if(r.some(s=>[4,5].includes(Number(s?.itemType))))throw new Error(`opensea: ${n} uses a criteria consideration item, not a fixed token`);let o=r.filter(s=>[2,3].includes(Number(s?.itemType)));if(o.length!==1)throw new Error(`opensea: ${n} must require exactly one fixed ERC-721 or ERC-1155 consideration item`);let i=T_(o[0],`${n} consideration NFT`);if(i.tokenId!==t)throw new Error(`opensea: ${n} consideration token does not match the requested token`);return i}function d9(e,t,n,r){if(!(!e||typeof e!="object")){if(e.contract!=null&&String(e.contract).trim()!==""&&pe(e.contract,`${r} display contract`)!==t)throw new Error(`opensea: ${r} display asset contract disagrees with the canonical Seaport offer`);if(e.identifier!=null&&String(e.identifier).trim()!==""&&String(e.identifier).trim()!==n)throw new Error(`opensea: ${r} display asset token disagrees with the canonical Seaport offer`)}}function p9(e){let t=String(e??"").trim();return/^\d+$/.test(t)?t.length<=10?Number(t):Math.floor(Number(t)/1e3):Math.floor(Date.parse(t)/1e3)}function N_(e,t,n,r){let o=hn(t?.startTime,`${r} startTime`),i=hn(t?.endTime,`${r} endTime`),s=BigInt(Math.floor(n/1e3));if(BigInt(o)>s)throw new Error(`opensea: ${r} canonical startTime is in the future`);if(BigInt(i)<=s)throw new Error(`opensea: ${r} canonical endTime is expired or stale`);let a=I_(i,n,`${r} expiry`),c=e?.expiration_time??e?.expirationTime;if(c!=null&&String(c).trim()!==""&&p9(c)!==Number(i))throw new Error(`opensea: ${r} display expiry disagrees with the canonical order endTime`);return a}function f9(e,t,n){if(!e||typeof e!="object")throw new Error("opensea: invalid best listing");let r=String(e.chain||"").trim().toLowerCase();if(r!==t.chain)throw new Error("opensea: OpenSea returned a listing for the wrong chain");if(Vc[r]!==t.chainId)throw new Error("opensea: OpenSea listing chain id mismatch");if(String(e.status||"").toUpperCase()!=="ACTIVE")throw new Error("opensea: OpenSea returned a non-active listing");let i=e.protocol_data?.parameters,s=l9(i,"listing"),a=s.contract;if(t.contract&&a!==t.contract)throw new Error("opensea: OpenSea returned a listing for the wrong contract");let c=s.tokenId;d9(e.asset,a,c,"listing");let l=sn(e.price?.current?.value,"listing price",{positive:!0}),u=O_(e,i,"listing"),d=ob(i?.consideration,"listing consideration");if(d.totalWei!==l)throw new Error("opensea: listing consideration total does not equal the quoted listing price");return{orderHash:u,chain:t.chain,chainId:t.chainId,protocolAddress:pe(e.protocol_address,"listing protocol address"),contract:a,tokenId:c,quantity:s.quantity,priceWei:l.toString(),paymentToken:d.paymentToken,currency:String(e.price?.current?.currency||"").trim()||null,decimals:Number(e.price?.current?.decimals??18),expiry:N_(e,i,n,"listing"),counter:hn(i?.counter,"listing counter")}}async function _p(e={},t={}){if(!fr(t))throw new Error("OPENSEA_API_KEY required");let n=Wc(e.chain);n.contract=e.contract?pe(e.contract,"NFT contract"):null;let r=String(e.slug||"").trim();if(!r)throw new Error("opensea: collection slug required");let o=Number(e.limit??12);if(!Number.isSafeInteger(o)||o<1||o>50)throw new Error("opensea: listing limit must be 1 through 50");let i=new URL(`${Ur(t)}/listings/collection/${encodeURIComponent(r)}/best`);i.searchParams.set("limit",String(o)),e.next&&i.searchParams.set("next",String(e.next));let s=await A(i.toString(),{headers:Fr(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),a=Array.isArray(s?.listings)?s.listings:[];if(!a.length)throw new Error("opensea: no active best listings returned");let c=Number.isFinite(Number(t.nowMs))?Number(t.nowMs):Date.now();return{provider:"opensea-nft",source:"opensea-best-listings",chain:n.chain,chainId:n.chainId,slug:r,contract:n.contract,listings:a.map(l=>f9(l,n,c)),next:s?.next?String(s.next):null,exec:!1,readOnly:!0}}async function Gc(e={},t={}){let n=Hc(e.tokenId),r=Math.min(Math.max(Number(e.maxPages??20)||20,1),25),o=e.next?String(e.next):null,i=new Set;for(let s=1;s<=r;s+=1){let a=await _p({...e,tokenId:void 0,limit:50,next:o},t),c=a.listings.find(l=>l.tokenId===n);if(c)return{provider:"opensea-nft",source:"opensea-best-exact-listing",...c,pagesScanned:s,exact:!0,exec:!1,readOnly:!0};if(!a.next||i.has(a.next))break;i.add(a.next),o=a.next}throw new Error("opensea: no active exact NFT listing returned within page bound")}function m9(e,t,n,r){if(!e||typeof e!="object")throw new Error("opensea: invalid best offer");if(String(e.chain||"").trim().toLowerCase()!==t.chain)throw new Error("opensea: OpenSea returned an offer for the wrong chain");if(String(e.status||"").toUpperCase()!=="ACTIVE")throw new Error("opensea: OpenSea returned a non-active offer");let i=e.protocol_data?.parameters||{},a=u9(i,n,"offer").contract;if(t.contract&&a!==t.contract)throw new Error("opensea: OpenSea returned an offer for the wrong contract");let c=sn(e.price?.current?.value??e.price?.value,"offer value",{positive:!0}),l=ob(i.offer,"offer payment"),u=l.paymentToken;if(l.totalWei!==c)throw new Error("opensea: offer payment total does not equal the quoted gross offer");let d=ob(i.consideration,"offer fee",{required:!1});if(d.count&&d.paymentToken!==u)throw new Error("opensea: offer fee consideration uses a different token than the offer payment");if(d.totalWei>c)throw new Error("opensea: offer fee consideration exceeds the gross offer");let p=d.totalWei.toString(),f=(c-d.totalWei).toString();return{provider:"opensea-nft",source:"opensea-best-exact-offer",orderHash:O_(e,i,"offer"),chain:t.chain,chainId:t.chainId,protocolAddress:pe(e.protocol_address,"offer protocol address"),contract:a,tokenId:n,grossOfferWei:c.toString(),sellerNetWei:f,feeWei:p,paymentToken:u,currency:String(e.price?.current?.currency||e.price?.currency||"").trim()||null,decimals:Number(e.price?.current?.decimals??e.price?.decimals??18),expiry:N_(e,i,r,"offer"),counter:hn(i.counter,"offer counter"),exec:!1,readOnly:!0}}async function Kc(e={},t={}){if(!fr(t))throw new Error("OPENSEA_API_KEY required");let n=Wc(e.chain);n.contract=e.contract?pe(e.contract,"NFT contract"):null;let r=String(e.slug||"").trim();if(!r)throw new Error("opensea: collection slug required");let o=Hc(e.tokenId),i=await A(`${Ur(t)}/offers/collection/${encodeURIComponent(r)}/nfts/${encodeURIComponent(o)}/best`,{headers:Fr(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),s=i?.offer||(Array.isArray(i?.offers)?i.offers[0]:i);if(!s)throw new Error("opensea: no active exact NFT offer returned");let a=Number.isFinite(Number(t.nowMs))?Number(t.nowMs):Date.now();return m9(s,n,o,a)}function h9(e){if(e.userConfirmed!==!0)throw new Error("opensea: userConfirmed=true required after buyer, chain, contract, token, quantity, price cap, total cap, and expiry review")}function P_(e){if(!e||typeof e!="object")return!1;let t=String(e.action??e.type??e.method??"");return/approv|setapprovalforall|permit/i.test(t)?!0:Object.values(e).some(n=>n&&typeof n=="object"&&P_(n))}function C_(e){return!e||typeof e!="object"?!1:Object.keys(e).some(t=>/^(?:signed.*|rawtransaction|serializedtransaction|txsigned|r|s|v)$/i.test(t))}function R_(e){return!e||typeof e!="object"?!1:C_(e)?!0:Object.values(e).some(t=>t&&typeof t=="object"&&R_(t))}function L_(e,t=[],n=new Set){if(!e||typeof e!="object"||n.has(e))return t;n.add(e),e.transaction&&typeof e.transaction=="object"?t.push(e.transaction):e.tx&&typeof e.tx=="object"&&t.push(e.tx);for(let[r,o]of Object.entries(e))(r==="transaction"||r==="tx")&&o&&typeof o=="object"||o&&typeof o=="object"&&L_(o,t,n);return t}function m_(e){return e&&typeof e=="object"&&typeof e.value=="string"?e.value:e}function $_(e,{buyer:t,chainId:n,targets:r}){if(!e||typeof e!="object")throw new Error("opensea: transaction object required");if(C_(e))throw new Error("opensea: signed transaction material refused");if((e.from?pe(m_(e.from),"transaction buyer"):t)!==t)throw new Error("opensea: OpenSea returned a transaction for the wrong buyer");let i=pe(m_(e.to??e.target),"transaction target");if(!r.has(i))throw new Error("opensea: OpenSea returned a transaction for the wrong target");let s=e.data??e.calldata,a=e.input_data&&typeof e.input_data=="object"?e.input_data:e.input&&typeof e.input=="object"?e.input:null;if(s==null&&a){if(!String(e.function||"").replace(/^function\s+/,"").startsWith("fulfillAdvancedOrder("))throw new Error("opensea: only exact Seaport fulfillAdvancedOrder preparation is accepted");s=GH.encodeFunctionData("fulfillAdvancedOrder",[a.advancedOrder,a.criteriaResolvers,a.fulfillerConduitKey,a.recipient])}let c=String(s??"").trim().toLowerCase();if(!/^0x(?:[0-9a-f]{2})+$/.test(c))throw new Error("opensea: OpenSea returned invalid transaction calldata");let l=e.calldata_suffix==null?"":String(e.calldata_suffix).trim().toLowerCase();if(l){if(!/^0x[0-9a-f]{8}$/.test(l))throw new Error("opensea: invalid OpenSea calldata suffix");c.endsWith(l.slice(2))||(c+=l.slice(2))}let u=e.chainId??e.chain_id??e.chainIdentifier?.chainId;if(u!=null&&Number(u)!==n)throw new Error("opensea: OpenSea returned a transaction for the wrong chain");let d=n9(e.value_hex??e.valueHex??e.value??0);return{from:t,to:i,data:c,value:d.hex,chainId:n,valueWei:d.amount}}function Op(e){return{from:e.from,to:e.to,data:e.data,value:e.value,chainId:e.chainId,...e.gasLimit==null?{}:{gasLimit:e.gasLimit},...e.maxFeePerGas==null?{}:{maxFeePerGas:e.maxFeePerGas},...e.maxPriorityFeePerGas==null?{}:{maxPriorityFeePerGas:e.maxPriorityFeePerGas},...e.worstCaseFeeWei==null?{}:{worstCaseFeeWei:e.worstCaseFeeWei}}}async function cb(e,t,n){let r=n.provider,o=!!n.rpcUrl;if(!r&&!o)return{simulated:!1,gasEstimates:[]};let i=await rt(e,4,async c=>{let{chainId:l,...u}=Op(c);if(r){if(typeof r.call!="function"||typeof r.estimateGas!="function")throw new Error("opensea: supplied provider must implement call and estimateGas");let[,m]=await Promise.all([r.call(u),r.estimateGas(u)]);return BigInt(m).toString()}let{rpcCall:d}=await Promise.resolve().then(()=>(De(),qd)),p={...n,fetchImpl:n.rpcFetchImpl||n.fetchImpl},[,f]=await Promise.all([d(t,"eth_call",[u,"pending"],p),d(t,"eth_estimateGas",[u],p)]);return BigInt(f).toString()}),s=null,a=null;if(r&&typeof r.getFeeData=="function"){let c=await r.getFeeData();a=c?.maxPriorityFeePerGas==null?0n:BigInt(c.maxPriorityFeePerGas),s=c?.maxFeePerGas==null?c?.gasPrice==null?null:BigInt(c.gasPrice):BigInt(c.maxFeePerGas)}else if(o){let{rpcCall:c}=await Promise.resolve().then(()=>(De(),qd)),l={...n,fetchImpl:n.rpcFetchImpl||n.fetchImpl},u=BigInt(await c(t,"eth_gasPrice",[],l));try{a=BigInt(await c(t,"eth_maxPriorityFeePerGas",[],l))}catch{a=0n}let d=await c(t,"eth_getBlockByNumber",["pending",!1],l),f=(d?.baseFeePerGas==null?0n:BigInt(d.baseFeePerGas))*2n+a;s=u>f?u:f}return s!=null&&a!=null&&e.forEach((c,l)=>{let d=(BigInt(i[l])*120n+99n)/100n;c.gasLimit=d.toString(),c.maxPriorityFeePerGas=a.toString(),c.maxFeePerGas=s.toString(),c.worstCaseFeeWei=(d*s).toString()}),{simulated:!0,gasEstimates:i}}function g9(e,t){if(P_(e))throw new Error("opensea: approval steps are not permitted in NFT buy, sweep, or mint preparation");if(R_(e))throw new Error("opensea: signed transaction material refused");let n=L_(e);if(!n.length&&e&&typeof e=="object"&&(e.to||e.target)&&n.push(e),!n.length)throw new Error("opensea: OpenSea returned no transaction action");return n.map(r=>$_(r,t))}function y9(e,t,n={}){return q({...e,provider:"opensea-nft",kind:t,marketplace:"opensea",prepareReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,executionReady:!1,note:"Unsigned OpenSea EVM NFT transaction preparation only. The private signer must revalidate every bound field before the user signs or broadcasts."},n)}async function lb(e={},t={}){throw new Error("opensea: public buy preparation disabled until canonical Seaport calldata is independently decoded and fully bound")}async function ub(e={},t={}){throw new Error("opensea: public buy preparation disabled until canonical Seaport calldata is independently decoded and fully bound")}function b9(e,t,n){let o=(Array.isArray(e?.contracts)?e.contracts:[]).find(s=>String(s?.chain||t).toLowerCase()===t&&s?.address);if(!o)throw new Error("opensea: collection response contains no contract for requested chain");let i=pe(o.address,"collection NFT contract");if(i!==n)throw new Error("opensea: OpenSea returned the wrong collection contract");return i}async function Yc(e={},t={}){if(!fr(t))throw new Error("OPENSEA_API_KEY required");h9(e);let{chain:n,chainId:r}=Wc(e.chain),o=pe(e.buyer||e.minter||e.address,"buyer"),i=pe(e.contract,"NFT contract"),s=A_(e.quantity),a=sn(e.priceWei,"priceWei"),c=sn(e.maxTotalWei,"maxTotalWei"),l=Number.isFinite(Number(t.nowMs))?Number(t.nowMs):Date.now(),u=I_(e.expiry,l,"mint expiry");if(e.tokenId!=null)throw new Error("opensea: SeaDrop mint tokenId is unknown until the mined receipt and must not be caller supplied");let d=String(e.slug||"").trim();if(!d)throw new Error("opensea: collection slug required");let p=await js(d,t),f=b9(p,n,i),m=a*BigInt(s);if(m>c)throw new Error("opensea: mint total exceeds total cap");let h=await A(`${Ur(t)}/drops/${encodeURIComponent(d)}/mint`,{method:"POST",headers:Fr(t),body:{minter:o,quantity:s},fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??25e3,retries:0,dedupe:!1}),g=t.allowedMintTargets?.[n]??t.allowedMintTargets?.[r]??e.mintTarget,y=Array.isArray(g)?g:g?[g]:[];if(!y.length)throw new Error("opensea: reviewed SeaDrop mintTarget required");let b=new Set(y.map($=>pe($,"SeaDrop mint target"))),S=g9(h,{buyer:o,chainId:r,targets:b});if(S.length!==1)throw new Error("opensea: mint must contain exactly one SeaDrop transaction");let w,E,x=null,v;try{w=Ap.decodeFunctionData("mintPublic",S[0].data),E="public",v=Ap.encodeFunctionData("mintPublic",[w[0],w[1],w[2],w[3]])}catch{try{w=Ap.decodeFunctionData("mintAllowList",S[0].data),E="allowlist";let $=w[4],B=[...w[5]].map(String);if(B.length<1||B.length>64||B.some(z=>!/^0x[0-9a-fA-F]{64}$/.test(z)))throw new Error("opensea: allowlist mint requires a bounded canonical Merkle proof");let N=BigInt($.startTime),C=BigInt($.endTime),j=BigInt(Math.floor(l/1e3));if(N>j||C<=j)throw new Error("opensea: allowlist mint stage is not open");if(BigInt($.mintPrice)!==a)throw new Error("opensea: allowlist stage price does not match exact approved price");if(BigInt($.maxTotalMintableByWallet)<BigInt(s))throw new Error("opensea: allowlist wallet cap is below requested quantity");v=Ap.encodeFunctionData("mintAllowList",[w[0],w[1],w[2],w[3],$,B]),x={mintPrice:BigInt($.mintPrice).toString(),maxTotalMintableByWallet:BigInt($.maxTotalMintableByWallet).toString(),startTime:N.toString(),endTime:C.toString(),dropStageIndex:BigInt($.dropStageIndex).toString(),maxTokenSupplyForStage:BigInt($.maxTokenSupplyForStage).toString(),feeBps:Number($.feeBps),restrictFeeRecipients:!!$.restrictFeeRecipients,proof:B}}catch($){throw/opensea:/.test(String($?.message||""))?$:new Error("opensea: mint transaction must call reviewed SeaDrop mintPublic or mintAllowList")}}let k=pe(w[0],"mint NFT contract"),I=pe(w[1],"mint fee recipient"),_=pe(w[2],"mint recipient");if(k!==f)throw new Error("opensea: mint calldata collection mismatch");if(_!==o)throw new Error("opensea: mint calldata recipient mismatch");if(BigInt(w[3])!==BigInt(s))throw new Error("opensea: mint calldata quantity mismatch");if(v.toLowerCase()!==S[0].data.toLowerCase())throw new Error("opensea: mint calldata must be canonical with no suffix");let P=S.reduce(($,B)=>$+B.valueWei,0n);if(P!==m)throw new Error("opensea: mint transaction total does not match exact approved price and quantity");if(P>c)throw new Error("opensea: mint total exceeds total cap");let O=await cb(S,r,{...t,provider:e.provider||t.provider});if(O.simulated!==!0)throw new Error("opensea: mint RPC simulation required");let F=e.gasPolicy||t.gasPolicy||{maxTotalGasWei:e.maxGasWei,maxFeePerGasWei:e.maxFeePerGasWei,maxPriorityFeePerGasWei:e.maxPriorityFeePerGasWei},M=d_({chainId:r,tx:S[0],policy:F});return y9({action:"mint",mintType:E,...x?{stage:x}:{},chain:n,chainId:r,slug:d,buyer:o,contract:f,quantity:s,priceWei:a.toString(),totalWei:P.toString(),maxTotalWei:c.toString(),mintTarget:S[0].to,feeRecipient:I,expiry:u,transactions:S.map(Op),gasWar:M,...O},"nft-mint",{nowMs:l,expiresAtMs:Math.min(l+_s,Date.parse(u),x?Number(BigInt(x.endTime)*1000n):Number.MAX_SAFE_INTEGER)})}function w9(e={}){let t=v_(e.chain);if(S_.has(t))throw new Error("opensea: listing actions currently require an EVM NFT chain");let n=e.startTime||e.start_time?p_(e.startTime||e.start_time,"startTime"):{text:new Date().toISOString(),ms:Date.now()},r=p_(e.endTime||e.end_time,"endTime");if(r.ms<=n.ms)throw new Error("opensea: endTime must be after startTime");let o=String(e.tokenId??e.token_id??"").trim();if(!/^\d+$/.test(o))throw new Error("opensea: tokenId must be an unsigned integer string");return{chain:t,contract:pe(e.contract,"NFT contract"),token_id:o,quantity:ZH(e.quantity??1,"quantity"),price:{amount:QH(e.price?.amount??e.amount??e.priceAmount,"price amount"),currency:pe(e.price?.currency??e.currency??qs,"price currency")},start_time:n.text,end_time:r.text}}function g_(e,t){return e?.[t]||(e?.action===t?e:null)}function E9(e,{seller:t,item:n,chainId:r}){let o=Array.isArray(e?.steps)?e.steps:[],i=o.map(S=>g_(S,"createListingsAction")).find(Boolean)||o.find(S=>/createListings/i.test(String(S?.action||""))),s=i?.signatureRequest?.message??i?.typedData,a;try{a=typeof s=="string"?JSON.parse(s):s}catch{throw new Error("opensea: invalid listing typed-data JSON")}if(!a||a.primaryType!=="OrderComponents"||!a.domain||!a.message)throw new Error("opensea: exact Seaport OrderComponents action required");let c=a.domain;if(c.name!=="Seaport"||c.version!=="1.6"||Number(c.chainId)!==r)throw new Error("opensea: listing domain mismatch");let l=pe(c.verifyingContract,"listing protocol"),u=a.message;if(pe(u.offerer,"listing seller")!==t)throw new Error("opensea: listing seller mismatch");if(!Array.isArray(u.offer)||u.offer.length!==1)throw new Error("opensea: executable listing requires exactly one NFT offer");let d=u.offer[0];if(![2,3].includes(Number(d.itemType)))throw new Error("opensea: listing offer must be ERC721 or ERC1155");if(pe(d.token,"listing collection")!==n.contract||String(d.identifierOrCriteria)!==n.token_id)throw new Error("opensea: listing NFT mismatch");if(String(d.startAmount)!==String(n.quantity)||String(d.endAmount)!==String(n.quantity))throw new Error("opensea: listing quantity mismatch");if(Number(u.orderType)!==2)throw new Error("opensea: only FULL_RESTRICTED listings are executable");if(!Array.isArray(u.consideration)||!u.consideration.length)throw new Error("opensea: listing consideration required");let p=0n;for(let S of u.consideration){if(Number(S.itemType)!==0||pe(S.token,"listing payment token")!==qs)throw new Error("opensea: executable listings currently require native fixed-price consideration");let w=BigInt(S.startAmount),E=BigInt(S.endAmount);if(w<=0n||w!==E)throw new Error("opensea: listing consideration must be fixed and positive");pe(S.recipient,"listing consideration recipient"),p+=w}let f=WH(n.price.amount,18);if(p!==f)throw new Error("opensea: listing price mismatch");let m=BigInt(Math.floor(Date.parse(n.start_time)/1e3)),h=BigInt(Math.floor(Date.parse(n.end_time)/1e3));if(BigInt(u.startTime)!==m||BigInt(u.endTime)!==h)throw new Error("opensea: listing time bounds mismatch");let g=ib.hashStruct("OrderComponents",Fs,u),y=o.map(S=>g_(S,"itemApprovalAction")).find(Boolean)||o.find(S=>/setApprovalForAll/i.test(String(S?.action||""))),b=null;if(y){let S=y.transaction||y.itemApprovalAction?.transaction,w=$_(S,{buyer:t,chainId:r,targets:new Set([n.contract])}),E;try{E=h_.decodeFunctionData("setApprovalForAll",w.data)}catch{throw new Error("opensea: listing approval must be setApprovalForAll")}let x=pe(E[0],"listing approval operator");if(E[1]!==!0||w.valueWei!==0n)throw new Error("opensea: listing approval must grant one exact operator with zero value");if(h_.encodeFunctionData("setApprovalForAll",[x,!0]).toLowerCase()!==w.data.toLowerCase())throw new Error("opensea: listing approval calldata must be canonical");b={...w,operator:x}}return{protocolAddress:l,typedData:{domain:c,types:Fs,primaryType:"OrderComponents",message:u},orderHash:g,priceWei:p,approval:b}}async function Jc(e={},t={}){if(!fr(t))throw new Error("OPENSEA_API_KEY required");if(e.userConfirmed!==!0)throw new Error("opensea: userConfirmed=true required after NFT, marketplace, price, currency, and expiry review");let n=pe(e.seller||e.address||e.owner,"seller"),r=Array.isArray(e.items)&&e.items.length?e.items:[e];if(r.length!==1)throw new Error("opensea: executable listing preparation supports exactly one NFT per envelope");let o=r.map(w9);if(new Set(o.map(f=>f.chain)).size!==1)throw new Error("opensea: all prepared listing items must be on one chain");let s=e.useCreatorFee!==!1,a={address:n,items:o,use_creator_fee:s};e.taker&&(a.taker=pe(e.taker,"taker"));let c=await A(`${Ur(t)}/listings/actions`,{method:"POST",headers:Fr(t),body:a,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??25e3,retries:0,dedupe:!1}),{chainId:l}=Wc(o[0].chain),u=E9(c,{seller:n,item:o[0],chainId:l}),d=u.approval?[u.approval]:[],p=d.length?await cb(d,l,{...t,provider:e.provider||t.provider}):{simulated:!0};return q({provider:"opensea-nft",marketplace:"opensea",chain:o[0].chain,chainId:l,kind:"nft-list",action:"list",prepareReady:!0,executionReady:p.simulated===!0,signingReady:p.simulated===!0,broadcastReady:p.simulated===!0,requiresUserSignature:!0,requiresSeparateApproval:d.length>0,seller:n,contract:o[0].contract,tokenId:o[0].token_id,quantity:o[0].quantity,priceWei:u.priceWei.toString(),typedData:u.typedData,orderHash:u.orderHash,submission:{chain:o[0].chain,protocol:"seaport",protocolAddress:u.protocolAddress},transactions:d.map(Op),useCreatorFee:s,taker:a.taker||null,feeDisclosure:s?"Creator fees requested and bound into exact Seaport consideration recipients.":"Creator fees disabled by explicit request; every remaining consideration recipient is still bound.",...p})}async function db(e={},t={}){if(e.userConfirmed!==!0)throw new Error("opensea: userConfirmed=true required for listing cancellation");let{chain:n,chainId:r}=Wc(e.chain),o=pe(e.seller||e.address||e.owner,"seller"),i=pe(e.protocolAddress,"reviewed Seaport protocol address"),s=pe(e.contract,"NFT contract"),a=Hc(e.tokenId),c=A_(e.quantity),l=e.typedData;if(!l||l.primaryType!=="OrderComponents"||!l.domain||!l.message)throw new Error("opensea: exact Seaport OrderComponents typedData required for cancellation");for(let[k,I]of Object.entries(Fs)){let _=l.types?.[k];if(!Array.isArray(_)||_.length!==I.length||_.some((P,O)=>P?.name!==I[O].name||P?.type!==I[O].type))throw new Error("opensea: cancellation requires canonical Seaport types")}if(Object.keys(l.types||{}).filter(k=>k!=="EIP712Domain").sort().join(",")!==Object.keys(Fs).sort().join(","))throw new Error("opensea: cancellation requires canonical Seaport types");let d=l.domain;if(d.name!=="Seaport"||d.version!=="1.6"||Number(d.chainId)!==r)throw new Error("opensea: cancellation domain mismatch");let p=pe(d.verifyingContract,"Seaport cancellation target");if(p!==i)throw new Error("opensea: cancellation target mismatch");let f=l.message;if(pe(f.offerer,"listing seller")!==o)throw new Error("opensea: cancellation seller mismatch");if(!Array.isArray(f.offer)||f.offer.length!==1||!Array.isArray(f.consideration)||!f.consideration.length)throw new Error("opensea: cancellation requires one exact previously prepared listing order");if(Number(f.orderType)!==2)throw new Error("opensea: cancellation requires a FULL_RESTRICTED listing order");let m=f.offer[0];if(![2,3].includes(Number(m.itemType)))throw new Error("opensea: cancellation offer must be ERC721 or ERC1155");if(pe(m.token,"cancellation NFT contract")!==s)throw new Error("opensea: cancellation NFT contract mismatch");if(Hc(m.identifierOrCriteria)!==a)throw new Error("opensea: cancellation tokenId mismatch");let h=sn(m.startAmount,"cancellation offer startAmount",{positive:!0}),g=sn(m.endAmount,"cancellation offer endAmount",{positive:!0});if(h!==BigInt(c)||g!==BigInt(c))throw new Error("opensea: cancellation quantity mismatch");for(let k of f.consideration){if(Number(k.itemType)!==0||pe(k.token,"cancellation payment token")!==qs)throw new Error("opensea: cancellation requires native fixed-price consideration");let I=sn(k.startAmount,"cancellation consideration startAmount",{positive:!0}),_=sn(k.endAmount,"cancellation consideration endAmount",{positive:!0});if(I!==_)throw new Error("opensea: cancellation consideration must be fixed and positive");pe(k.recipient,"cancellation consideration recipient")}let y=sn(f.startTime,"cancellation startTime");if(sn(f.endTime,"cancellation endTime",{positive:!0})<=y)throw new Error("opensea: cancellation listing time bounds invalid");let S=ib.hashStruct("OrderComponents",Fs,f),w=String(e.orderHash||"").trim().toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(w)||w!==S.toLowerCase())throw new Error("opensea: cancellation order hash mismatch");let E=S9.encodeFunctionData("cancel",[[f]]),x=[{from:o,to:p,data:E,value:"0x0",valueWei:0n,chainId:r}],v=await cb(x,r,{...t,provider:e.provider||t.provider});if(v.simulated!==!0)throw new Error("opensea: cancellation RPC simulation required");return q({provider:"opensea-nft",marketplace:"opensea",kind:"nft-cancel",action:"cancel-listing",prepareReady:!0,chain:n,chainId:r,seller:o,contract:s,tokenId:a,quantity:c,protocolAddress:p,orderHash:S,typedData:{domain:d,types:Fs,primaryType:"OrderComponents",message:f},transactions:x.map(Op),...v,requiresUserSignature:!0},{provider:"opensea-nft",kind:"nft-cancel"})}var y_,b_,GH,Ap,w_,KH,S_,qs,YH,JH,Vc,s9,Fs,h_,S9,Ni=Y(()=>{V();Pt();ae();rb();y_="https://api.opensea.io/api/v2",b_="fulfillAdvancedOrder(((address offerer,address zone,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount)[] offer,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount,address recipient)[] consideration,uint8 orderType,uint256 startTime,uint256 endTime,bytes32 zoneHash,uint256 salt,bytes32 conduitKey,uint256 totalOriginalConsiderationItems) parameters,uint120 numerator,uint120 denominator,bytes signature,bytes extraData) advancedOrder,(uint256 orderIndex,uint8 side,uint256 index,uint256 identifier,bytes32[] criteriaProof)[] criteriaResolvers,bytes32 fulfillerConduitKey,address recipient)",GH=new Ip([`function ${b_}`]),Ap=new Ip(["function mintPublic(address nftContract,address feeRecipient,address minterIfNotPayer,uint256 quantity) payable","function mintAllowList(address nftContract,address feeRecipient,address minterIfNotPayer,uint256 quantity,(uint80 mintPrice,uint48 maxTotalMintableByWallet,uint48 startTime,uint48 endTime,uint48 dropStageIndex,uint32 maxTokenSupplyForStage,uint16 feeBps,bool restrictFeeRecipients) mintParams,bytes32[] proof) payable"]),w_=Object.freeze(["blast","base","ethereum","zora","arbitrum","sei","avalanche","polygon","optimism","ape_chain","flow","b3","soneium","ronin","bera_chain","solana","shape","unichain","gunzilla","abstract","animechain","hyperevm","somnia","monad","hyperliquid","megaeth","ink","robinhood","stablechain"]),KH=new Set(w_),S_=new Set(["solana","flow"]),qs="0x0000000000000000000000000000000000000000",YH=qs,JH="0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73";Vc=Object.freeze({robinhood:4663,ethereum:1,base:8453,arbitrum:42161,optimism:10,polygon:137,avalanche:43114,zora:7777777,blast:81457,sei:1329,ape_chain:33139,b3:8333,soneium:1868,ronin:2020,bera_chain:80094,shape:360,unichain:130,gunzilla:43419,abstract:2741,animechain:69e3,hyperevm:999,somnia:5031,monad:143,megaeth:4326,ink:57073,stablechain:988});s9=Object.freeze({OrderComponents:[{name:"offerer",type:"address"},{name:"zone",type:"address"},{name:"offer",type:"OfferItem[]"},{name:"consideration",type:"ConsiderationItem[]"},{name:"orderType",type:"uint8"},{name:"startTime",type:"uint256"},{name:"endTime",type:"uint256"},{name:"zoneHash",type:"bytes32"},{name:"salt",type:"uint256"},{name:"conduitKey",type:"bytes32"},{name:"counter",type:"uint256"}],OfferItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"}],ConsiderationItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"},{name:"recipient",type:"address"}]});Fs={OrderComponents:[{name:"offerer",type:"address"},{name:"zone",type:"address"},{name:"offer",type:"OfferItem[]"},{name:"consideration",type:"ConsiderationItem[]"},{name:"orderType",type:"uint8"},{name:"startTime",type:"uint256"},{name:"endTime",type:"uint256"},{name:"zoneHash",type:"bytes32"},{name:"salt",type:"uint256"},{name:"conduitKey",type:"bytes32"},{name:"counter",type:"uint256"}],OfferItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"}],ConsiderationItem:[{name:"itemType",type:"uint8"},{name:"token",type:"address"},{name:"identifierOrCriteria",type:"uint256"},{name:"startAmount",type:"uint256"},{name:"endAmount",type:"uint256"},{name:"recipient",type:"address"}]},h_=new Ip(["function setApprovalForAll(address operator,bool approved)"]),S9=new Ip(["function cancel((address offerer,address zone,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount)[] offer,(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount,address recipient)[] consideration,uint8 orderType,uint256 startTime,uint256 endTime,bytes32 zoneHash,uint256 salt,bytes32 conduitKey,uint256 counter)[] orders) returns (bool cancelled)"])});function v9(e,t){return`0x${mb.getAmountsOut}`+Cn(e)+Cn(64)+Cn(t.length)+t.map(Xc).join("")}function x9(e){if(!e||e==="0x")return null;let t=e.slice(2);if(t.length<128)return null;let n=Number(BigInt(`0x${t.slice(64,128)}`));if(!Number.isFinite(n)||n<1||n>16)return null;let r=[];for(let o=0;o<n;o++){let i=128+o*64;if(t.length<i+64)return null;r.push(BigInt(`0x${t.slice(i,i+64)}`))}return r}function fb(e,t="router"){return(e?.venues||[]).find(r=>r.kind===t)?.address??null}function k9(e,t){let n=Number(t);if(!Number.isFinite(n)||n<0)throw new Error("slippageBps must be a non-negative number");if(n>hb)throw new Error(`slippageBps ${n} exceeds the ${hb} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(e)*BigInt(1e4-Math.floor(n))/10000n}function M_(e){let{chainId:t,wrappedNative:n}=e;async function r(o,i,s,a){let c=await ee(t,"eth_call",[{to:o,data:v9(i,s)},"latest"],a);return x9(c?.result??c)}return{async quote({tokenIn:o,tokenOut:i,amountIn:s,path:a},c={}){let l=fb(c.scanner);if(!l)return{chainId:t,evidence:ue.UNAVAILABLE,reason:"no verified router configured for this chain; quoting stays fail-closed rather than guessing a venue address"};let u=a||[o,i];if(u.some(p=>!/^0x[0-9a-fA-F]{40}$/.test(p||"")))throw new Error("quote requires valid 20-byte addresses");let d=await r(l,s,u,c);return d?{chainId:t,router:l,path:u,amountIn:String(s),amountOut:d[d.length-1].toString(),hops:u.length-1,evidence:ue.LIVE,note:"exact-input quote at current reserves; not a guaranteed fill"}:{chainId:t,router:l,path:u,evidence:ue.UNKNOWN,reason:"router returned no amounts -- no pool for this path, or the call reverted"}},async sellSimulation({token:o,amountIn:i,base:s},a={}){let c=fb(a.scanner),l=s||n;if(l&&String(o).toLowerCase()===String(l).toLowerCase())return{chainId:t,token:o,verdict:ie.UNKNOWN,evidence:ue.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:t,token:o,verdict:ie.UNKNOWN,evidence:ue.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 u=await r(c,i,[l,o],a);if(!u)return{chainId:t,token:o,verdict:ie.FAIL,evidence:ue.LIVE,leg:"buy",reason:"buy leg returned no amounts -- no route in"};let d=u[u.length-1];if(d===0n)return{chainId:t,token:o,verdict:ie.FAIL,evidence:ue.LIVE,leg:"buy",reason:"buy leg quotes zero output"};let p=await r(c,d,[o,l],a);if(!p)return{chainId:t,token:o,verdict:ie.FAIL,evidence:ue.LIVE,leg:"sell",bought:d.toString(),reason:"SELL LEG FAILED while the buy leg quoted fine. This is the honeypot signature: do not trade."};let f=p[p.length-1],m=Number(f*10000n/BigInt(i)),h=ie.PASS,g="round trip completes with expected fee/impact loss";return m<5e3?(h=ie.FAIL,g=`round trip returns only ${(m/100).toFixed(2)}% -- punitive tax or no real liquidity`):m<9e3&&(h=ie.CAUTION,g=`round trip returns ${(m/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,token:o,base:l,router:c,verdict:h,reason:g,amountIn:String(i),bought:d.toString(),returned:f.toString(),retentionBps:m,evidence:ue.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:o,tokenOut:i,amountIn:s,recipient:a,slippageBps:c=50,deadlineSeconds:l=900,path:u},d={}){let p=d.scanner,f=fb(p);if(!f)throw new Error(`chain ${t} 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(a||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let m=u||[o,i],h=await this.quote({tokenIn:o,tokenOut:i,amountIn:s,path:m},d);if(h.evidence!==ue.LIVE)throw new Error(`cannot prepare without a live quote (${h.evidence}: ${h.reason??"no reason given"})`);let g=k9(h.amountOut,c);if(g<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let y=BigInt(Math.floor(Date.now()/1e3)+Number(l)),b=n&&m[0].toLowerCase()===n.toLowerCase()&&d.useNative,S=b?`0x${mb.swapExactETHForTokens}`+Cn(g)+Cn(128)+Xc(a)+Cn(y)+Cn(m.length)+m.map(Xc).join(""):`0x${mb.swapExactTokensForTokens}`+Cn(s)+Cn(g)+Cn(160)+Xc(a)+Cn(y)+Cn(m.length)+m.map(Xc).join("");return{unsigned:!0,signedBy:"user-wallet",chainId:t,tx:{to:f,data:S,value:b?`0x${BigInt(s).toString(16)}`:"0x0"},guard:{quotedOut:h.amountOut,minOut:g.toString(),slippageBps:c,maxSlippageBps:hb,deadline:y.toString()},requires:b?[]:[{step:"approve",token:m[0],spender:f,amount:String(s)}],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 mb,Cn,Xc,hb,B_=Y(()=>{De();vo();mb={getAmountsOut:"d06ca61f",swapExactTokensForTokens:"38ed1739",swapExactETHForTokens:"7ff36ab5"},Cn=e=>BigInt(e).toString(16).padStart(64,"0"),Xc=e=>e.slice(2).toLowerCase().padStart(64,"0");hb=100});function I9(e,t){let n=Number(t);if(!Number.isFinite(n)||n<0)throw new Error("slippageBps must be a non-negative number");if(n>yb)throw new Error(`slippageBps ${n} exceeds the ${yb} bps ceiling. Block and requote or split the order -- do not widen the guard to force a fill.`);return BigInt(e)*BigInt(1e4-Math.floor(n))/10000n}function gb(e,t){return(e?.venues||[]).find(n=>n.kind===t)?.address??null}function F_(e){let{chainId:t,wrappedNative:n}=e;async function r({quoter:i,tokenIn:s,tokenOut:a,amountIn:c,fee:l},u){let d=`0x${D_.quoteExactInputSingle}`+Qc(s)+Qc(a)+Pi(c)+Pi(l)+Pi(0),p=await ee(t,"eth_call",[{to:i,data:d},"latest"],u).catch(()=>null),f=p?.result??p;if(!f||f==="0x"||f.length<66)return null;let m=BigInt(`0x${f.slice(2,66)}`);return m>0n?m:null}async function o({quoter:i,tokenIn:s,tokenOut:a,amountIn:c},l){let u=await Promise.all(A9.map(async p=>{let f=await r({quoter:i,tokenIn:s,tokenOut:a,amountIn:c,fee:p},l);return{fee:p,amountOut:f?f.toString():null,out:f}})),d=null;for(let p of u)p.out&&(!d||p.out>d.amountOut)&&(d={fee:p.fee,amountOut:p.out});return{best:d,tried:u.map(({fee:p,amountOut:f})=>({fee:p,amountOut:f}))}}return{async quote({tokenIn:i,tokenOut:s,amountIn:a},c={}){let l=gb(c.scanner,"quoter");if(!l)return{chainId:t,evidence:ue.UNAVAILABLE,reason:"no verified quoter configured for this chain; quoting stays fail-closed rather than guessing a venue address"};for(let p of[i,s])if(!U_.test(p||""))throw new Error("quote requires valid 20-byte addresses");let{best:u,tried:d}=await o({quoter:l,tokenIn:i,tokenOut:s,amountIn:a},c);return u?{chainId:t,venue:"uniswap-v3",quoter:l,tokenIn:i,tokenOut:s,amountIn:String(a),amountOut:u.amountOut.toString(),fee:u.fee,useNative:!!n&&String(i).toLowerCase()===String(n).toLowerCase(),triedFeeTiers:d,evidence:ue.LIVE,note:"exact-input single-hop quote at current tick; not a guaranteed fill"}:{chainId:t,quoter:l,tokenIn:i,tokenOut:s,triedFeeTiers:d,evidence:ue.UNKNOWN,reason:"no fee tier returned a quote -- no V3 pool for this pair, or no liquidity"}},async sellSimulation({token:i,amountIn:s,base:a},c={}){let l=gb(c.scanner,"quoter"),u=(e.stableQuoteAssets||[]).map(E=>String(E).toLowerCase()),d=null;!a&&typeof e.resolveQuoteAsset=="function"&&(d=await e.resolveQuoteAsset(i,c).catch(()=>null));let p=String(i).toLowerCase(),f=String(n||"").toLowerCase();if(f&&p===f)return{chainId:t,token:i,verdict:ie.UNKNOWN,evidence:ue.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 m=a||d||(u[0]&&p!==u[0]?u[0]:null)||n;if(m&&p===String(m).toLowerCase())return{chainId:t,token:i,verdict:ie.UNKNOWN,evidence:ue.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||!m)return{chainId:t,token:i,verdict:ie.UNKNOWN,evidence:ue.UNAVAILABLE,reason:l?"no wrappedNative configured, so there is no base asset to round-trip against":"no verified quoter configured for this chain"};let h=await o({quoter:l,tokenIn:m,tokenOut:i,amountIn:s},c);if(!h.best){let E=u.find(x=>x&&x!==String(m).toLowerCase()&&x!==String(i).toLowerCase());if(E){let x=await o({quoter:l,tokenIn:E,tokenOut:i,amountIn:s},c);if(x.best){let v=await o({quoter:l,tokenIn:i,tokenOut:E,amountIn:x.best.amountOut},c);if(v.best){let k=v.best.amountOut,I=Number(k*10000n/BigInt(s)),_=ie.PASS,P="round trip vs dollar book completes with expected fee/impact loss";return I<5e3?(_=ie.FAIL,P=`round trip vs dollar book returns only ${(I/100).toFixed(2)}% -- punitive tax or no real liquidity`):I<9e3&&(_=ie.CAUTION,P=`round trip vs dollar book returns ${(I/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:i,base:E,quoteAsset:E,verdict:_,reason:P,amountIn:String(s),bought:x.best.amountOut.toString(),returned:k.toString(),retentionBps:I,buyFee:x.best.fee,sellFee:v.best.fee,evidence:ue.LIVE,note:"Quoted against the dollar book, not wrapped native. A missing WETH pool is not a honeypot."}}}}return{chainId:t,token:i,verdict:ie.FAIL,evidence:ue.LIVE,leg:"buy",reason:"no V3 pool priced the buy leg on any fee tier against wrapped native or the dollar book"}}let g=await o({quoter:l,tokenIn:i,tokenOut:m,amountIn:h.best.amountOut},c);if(!g.best){let E=u.find(x=>x&&x!==String(m).toLowerCase()&&x!==String(i).toLowerCase());if(E){let x=await o({quoter:l,tokenIn:E,tokenOut:i,amountIn:s},c),v=x.best?await o({quoter:l,tokenIn:i,tokenOut:E,amountIn:x.best.amountOut},c):{best:null};if(x.best&&v.best){let k=v.best.amountOut,I=Number(k*10000n/BigInt(s)),_=ie.PASS,P="round trip vs dollar book completes; missing WETH sell pool is not a honeypot";return I<5e3?(_=ie.FAIL,P=`dollar-book round trip returns only ${(I/100).toFixed(2)}%`):I<9e3&&(_=ie.CAUTION,P=`dollar-book round trip returns ${(I/100).toFixed(2)}%`),{chainId:t,venue:"uniswap-v3",token:i,base:E,quoteAsset:E,verdict:_,reason:P,amountIn:String(s),bought:x.best.amountOut.toString(),returned:k.toString(),retentionBps:I,buyFee:x.best.fee,sellFee:v.best.fee,evidence:ue.LIVE,note:"Sell vs wrapped native failed; dollar book succeeded. Not labelled honeypot."}}}return{chainId:t,token:i,verdict:ie.FAIL,evidence:ue.LIVE,leg:"sell",bought:h.best.amountOut.toString(),reason:"SELL LEG FAILED against wrapped native and the dollar book. This is the honeypot signature: do not trade."}}let y=g.best.amountOut,b=Number(y*10000n/BigInt(s)),S=ie.PASS,w="round trip completes with expected fee/impact loss";return b<5e3?(S=ie.FAIL,w=`round trip returns only ${(b/100).toFixed(2)}% -- punitive tax or no real liquidity`):b<9e3&&(S=ie.CAUTION,w=`round trip returns ${(b/100).toFixed(2)}% -- transfer tax or thin liquidity at this size`),{chainId:t,venue:"uniswap-v3",token:i,base:m,verdict:S,reason:w,amountIn:String(s),bought:h.best.amountOut.toString(),returned:y.toString(),retentionBps:b,buyFee:h.best.fee,sellFee:g.best.fee,evidence:ue.LIVE,note:"Quote-level round trip. It does not prove transfer hooks absent at execution time."}},async prepareUnsignedTx({tokenIn:i,tokenOut:s,amountIn:a,recipient:c,slippageBps:l=50,fee:u},d={}){let p=gb(d.scanner,"router");if(!p)throw new Error(`chain ${t} 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(!U_.test(c||""))throw new Error("prepareUnsignedTx requires a valid recipient address");let f=await this.quote({tokenIn:i,tokenOut:s,amountIn:a},d);if(f.evidence!==ue.LIVE)throw new Error(`cannot prepare without a live quote (${f.evidence}: ${f.reason??"no reason given"})`);let m=u??f.fee,h=I9(f.amountOut,l);if(h<=0n)throw new Error("computed minOut is zero -- refusing to prepare");let g=!!(d.useNative||f.useNative)&&n&&String(i).toLowerCase()===String(n).toLowerCase(),y=`0x${D_.exactInputSingle}`+Qc(i)+Qc(s)+Pi(m)+Qc(c)+Pi(a)+Pi(h)+Pi(0);return{unsigned:!0,signedBy:"user-wallet",chainId:t,venue:"uniswap-v3",tx:{to:p,data:y,value:g?String(a):"0x0"},guard:{quotedOut:f.amountOut,minOut:h.toString(),slippageBps:l,maxSlippageBps:yb,fee:m},requires:g?[]:[{step:"approve",token:i,spender:p,amount:String(a)}],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 A9,D_,Pi,Qc,U_,yb,q_=Y(()=>{De();vo();A9=[100,500,3e3,1e4],D_={quoteExactInputSingle:"c6a5026a",exactInputSingle:"04e45aaf"},Pi=e=>BigInt(e).toString(16).padStart(64,"0"),Qc=e=>e.slice(2).toLowerCase().padStart(64,"0"),U_=/^0x[0-9a-fA-F]{40}$/,yb=100});function j_(e){if(!e||e==="0x")return null;try{return BigInt(e)}catch{return null}}function H_(e){if(!e||e==="0x")return null;let t=e.slice(2);if(t.length>=128){let r=Number(BigInt(`0x${t.slice(64,128)}`));if(r>0&&r<=256&&t.length>=128+r*2){let o=t.slice(128,128+r*2),i=Buffer.from(o,"hex").toString("utf8").replace(/\0+$/,"");if(i)return i}}return Buffer.from(t.slice(0,64),"hex").toString("utf8").replace(/\0+$/,"")||null}function _9(e){let{chainId:t}=e;async function n(r,o,i){return ee(t,"eth_call",[{to:r,data:o},"latest"],i)}return{async blockNumber(r={}){let o=await xc(t,r);return{chainId:t,blockNumber:o?.blockNumber??o,evidence:ue.LIVE}},async nativeBalance(r,o={}){let i=await Ei(t,r,o);return{chainId:t,address:r,wei:i?.wei??i?.balance??null,symbol:e.nativeCurrency?.symbol??null,decimals:e.nativeCurrency?.decimals??18,evidence:ue.LIVE}},async tokenBalance({token:r,owner:o},i={}){let s=await kc({chainId:t,token:r,owner:o},i);return{chainId:t,token:r,owner:o,raw:s?.balance??s,evidence:ue.LIVE}},async resolveToken(r,o={}){if(!/^0x[0-9a-fA-F]{40}$/.test(r||""))return{chainId:t,token:r,evidence:ue.UNKNOWN,error:"resolveToken needs a 20-byte address; symbol lookup is a market-data concern"};let[i,s,a,c]=await Promise.all([n(r,Tp.decimals,o).catch(()=>null),n(r,Tp.symbol,o).catch(()=>null),n(r,Tp.name,o).catch(()=>null),n(r,Tp.totalSupply,o).catch(()=>null)]),l=j_(i?.result??i),u=l!==null||s?.result||a?.result,d={chainId:t,address:r,decimals:l===null?null:Number(l),symbol:H_(s?.result??s),name:H_(a?.result??a),totalSupply:(j_(c?.result??c)??null)?.toString()??null,evidence:u?ue.LIVE:ue.UNKNOWN};return u||(d.warning="no ERC-20 metadata returned -- may not be a token contract"),d},async resolvePools(r,o={}){let i=e.dexscreenerSlug;if(!i)return{chainId:t,token:r,pools:[],evidence:ue.UNAVAILABLE,reason:"no dexscreenerSlug configured for this chain; pool discovery is unavailable rather than guessed"};let s=await pr(r,o).catch(()=>null),c=(s?.pairs||s?.data?.pairs||[]).filter(u=>String(u.chainId).toLowerCase()===String(i).toLowerCase()).map(u=>({pair:u.pairAddress,dex:u.dexId,base:u.baseToken?.address,quote:u.quoteToken?.address,liquidityUsd:u.liquidity?.usd??null,priceUsd:u.priceUsd??null,volume24hUsd:u.volume?.h24??null,createdAt:u.pairCreatedAt??null})).sort((u,d)=>(d.liquidityUsd??0)-(u.liquidityUsd??0)),l=Cg(r,c,{stables:e.stableQuoteAssets||[],wrappedNative:e.wrappedNative});return{chainId:t,token:r,pools:l,topPool:l[0]||null,quoteAsset:dA(r,l),evidence:l.length?ue.LIVE:ue.UNKNOWN}},async scanBlocks({fromBlock:r,toBlock:o,address:i,topics:s,chunkSize:a=2e3}={},c={}){if(!Number.isInteger(r)||!Number.isInteger(o))throw new Error("scanBlocks requires integer fromBlock and toBlock");if(o<r)throw new Error("toBlock must be >= fromBlock");let l=[],u=[];for(let p=r;p<=o;p+=a){let f=Math.min(p+a-1,o);u.push([p,f])}let d=await rt(u,4,async([p,f])=>{let m={fromBlock:`0x${p.toString(16)}`,toBlock:`0x${f.toString(16)}`};i&&(m.address=i),s&&(m.topics=s);let h=await ee(t,"eth_getLogs",[m],c).catch(g=>({error:String(g?.message||g)}));return{start:p,end:f,res:h}});for(let{start:p,end:f,res:m}of d){if(m?.error)return{chainId:t,fromBlock:r,toBlock:o,logs:l,complete:!1,failedAt:[p,f],error:m.error,evidence:ue.UNKNOWN};for(let h of m?.result??m??[])l.push(h)}return{chainId:t,fromBlock:r,toBlock:o,logs:l,complete:!0,chunks:u.length,evidence:ue.LIVE}},async scoreRisk(r,o={}){let i=[],s=ie.PASS,a=u=>{let d={[ie.PASS]:0,[ie.CAUTION]:1,[ie.UNKNOWN]:2,[ie.FAIL]:3};d[u]>d[s]&&(s=u)},[c,l]=await Promise.all([this.resolveToken(r,o),this.resolvePools(r,o)]);if(c.evidence!==ue.LIVE?(i.push({check:"erc20-metadata",result:ie.UNKNOWN,detail:c.warning}),a(ie.UNKNOWN)):i.push({check:"erc20-metadata",result:ie.PASS,detail:`${c.symbol} / ${c.decimals}d`}),l.evidence===ue.UNAVAILABLE)i.push({check:"liquidity",result:ie.UNKNOWN,detail:l.reason}),a(ie.UNKNOWN);else if(!l.pools.length)i.push({check:"liquidity",result:ie.FAIL,detail:"no pool with liquidity found"}),a(ie.FAIL);else{let u=l.pools[0],d=u.liquidityUsd??0;d<5e3?(i.push({check:"liquidity",result:ie.CAUTION,detail:`top pool only $${d}`}),a(ie.CAUTION)):i.push({check:"liquidity",result:ie.PASS,detail:`$${d} on ${u.dex}`}),u.createdAt&&Date.now()-u.createdAt<24*3600*1e3&&(i.push({check:"age",result:ie.CAUTION,detail:"pool under 24h old"}),a(ie.CAUTION))}if(typeof this.sellSimulation=="function"){let u=await this.sellSimulation({token:r,amountIn:(10n**16n).toString()},o).catch(d=>({verdict:ie.UNKNOWN,reason:String(d?.message||d)}));i.push({check:"sellability",result:u.verdict,detail:u.retentionBps!=null?`round trip returns ${(u.retentionBps/100).toFixed(2)}% -- ${u.reason}`:u.reason}),a(u.verdict)}else i.push({check:"sellability",result:ie.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."}),a(ie.UNKNOWN);return{chainId:t,token:r,verdict:s,checks:i,note:"Structural checks only. UNKNOWN is not PASS. A token is not tradeable until a sell simulation succeeds."}}}}function bb(e){let n={..._9(e)},r=new Set((e.venues||[]).map(i=>i.kind));e.venueKind==="uniswap-v3"&&r.has("quoter")&&r.has("router")?Object.assign(n,F_({chainId:e.chainId,wrappedNative:e.wrappedNative,stableQuoteAssets:e.stableQuoteAssets||[],resolveQuoteAsset:async(i,s)=>(await n.resolvePools(i,s)).quoteAsset||null})):e.venueKind==="uniswap-v2"&&r.has("router")&&Object.assign(n,M_({chainId:e.chainId,wrappedNative:e.wrappedNative}));let o={};for(let[i,s]of Object.entries(n))o[i]=s.bind(n);return{key:e.key,chainId:e.chainId,name:e.name,rpcEnv:e.rpcEnv,nativeCurrency:e.nativeCurrency,explorer:e.explorer,venues:e.venues||[],capabilities:o}}var Tp,z_=Y(()=>{De();Pr();V();vo();B_();q_();Rg();Tp={decimals:"0x313ce567",symbol:"0x95d89b41",name:"0x06fdde03",totalSupply:"0x18160ddd",owner:"0x8da5cb5b"}});var Oo,V_=Y(()=>{Oo=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 wb={};vt(wb,{CHAIN_CONFIGS:()=>Oo,registerBuiltinScanners:()=>zs,registerCustomChain:()=>O9});function zs(){return Oo.map(e=>ay(bb(e)))}function O9(e){return ay(bb(e))}var Ci=Y(()=>{z_();vo();V_()});import{types as Vs}from"node:util";function an(e){if(!e||typeof e!="object"||Vs.isProxy(e)||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Kt(e,t){if(e==null||(typeof e=="object"||typeof e=="function")&&Vs.isProxy(e)||!Object.hasOwn(Object(e),t))return;let n=Object.getOwnPropertyDescriptor(Object(e),t);return n&&Object.hasOwn(n,"value")?n.value:void 0}function qr(e,t,n="provider response",r=null,o=0){if(typeof t!="string"||t.length===0)return e;if(o>64)throw new Error(`${n} exceeds the credential guard nesting bound`);let i=r??{nodes:0,active:new Set};if(i.nodes+=1,i.nodes>2e5)throw new Error(`${n} exceeds the credential guard node bound`);if(e==null)return e;if(["string","number","boolean"].includes(typeof e)){if(String(e).includes(t))throw new Error(`${n} reflected an attached credential`);return e}if(!e||typeof e!="object"||Vs.isProxy(e)||i.active.has(e))throw new Error(`${n} is not credential-guardable own-data JSON`);i.active.add(e);try{if(Array.isArray(e)){for(let s=0;s<e.length;s+=1){let a=Object.getOwnPropertyDescriptor(e,String(s));if(!a||!Object.hasOwn(a,"value"))throw new Error(`${n} is not credential-guardable own-data JSON`);qr(a.value,t,n,i,o+1)}return e}if(!an(e))throw new Error(`${n} is not credential-guardable own-data JSON`);for(let s of Object.keys(e)){if(s.includes(t))throw new Error(`${n} reflected an attached credential`);let a=Object.getOwnPropertyDescriptor(e,s);if(!a||!Object.hasOwn(a,"value"))throw new Error(`${n} is not credential-guardable own-data JSON`);qr(a.value,t,n,i,o+1)}return e}finally{i.active.delete(e)}}function Xe(e,t="provider response",n=0){if(n>64)throw new Error(`${t} exceeds the JSON nesting bound`);if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return e;if(Array.isArray(e)){if(Vs.isProxy(e)||e.length>1e5)throw new Error(`${t} contains an invalid array`);let o=new Array(e.length);for(let i=0;i<e.length;i+=1){let s=Object.getOwnPropertyDescriptor(e,String(i));if(!s||!Object.hasOwn(s,"value"))throw new Error(`${t} arrays must contain dense own data`);o[i]=Xe(s.value,t,n+1)}return o}if(!an(e))throw new Error(`${t} contains a non-JSON value`);let r=Object.create(null);for(let o of Object.keys(e)){let i=Object.getOwnPropertyDescriptor(e,o);if(!i||!Object.hasOwn(i,"value"))throw new Error(`${t} objects must contain own data`);r[o]=Xe(i.value,t,n+1)}return r}function Ws(e,t){let n=t&&typeof t=="object"&&!Vs.isProxy(t)?t:null,r=n?Object.getOwnPropertyDescriptor(n,"status"):null,o=r&&Object.hasOwn(r,"value")&&Number.isInteger(r.value)&&r.value>=400&&r.value<=599?r.value:null,i=a=>{if(!n)return;let c=Object.getOwnPropertyDescriptor(n,a);return c&&Object.hasOwn(c,"value")?c.value:void 0},s=i("oversize")===!0?"provider-response-too-large":i("oracleTimeout")===!0||i("name")==="AbortError"||i("name")==="TimeoutError"?"provider-timeout":null;return(o!==null||s!==null)&&Object.defineProperty(e,J_,{value:Object.freeze({status:o,code:s}),enumerable:!1,configurable:!1,writable:!1}),e}function X_(e){if(!e||typeof e!="object"||Vs.isProxy(e))return null;let t=Object.getOwnPropertyDescriptor(e,J_);if(!t||!Object.hasOwn(t,"value")||!t.value||typeof t.value!="object")return null;let n=Number.isInteger(t.value.status)&&t.value.status>=400&&t.value.status<=599?t.value.status:null,r=M9.has(t.value.code)?t.value.code:null;return n===null&&r===null?null:Object.freeze({status:n,code:r})}var J_,M9,Rn=Y(()=>{J_=Symbol("oracle.provider-failure-metadata"),M9=new Set(["provider-response-too-large","provider-timeout"])});function B9({testnet:e,baseUrl:t}={}){if(t)return t.replace(/\/$/,"").endsWith("/info")?t:`${t.replace(/\/$/,"")}/info`;if(process.env.HL_INFO_URL)return process.env.HL_INFO_URL;if(process.env.HL_API_URL){let n=process.env.HL_API_URL.replace(/\/$/,"");return n.endsWith("/info")?n:`${n}/info`}return e||process.env.HL_TESTNET==="1"?kb:xb}async function _e(e,t={}){if(!e||!e.type)throw new Error("hlInfo requires body.type");let n=B9(t);return Xe(await A(n,{method:"POST",body:e,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs,maxResponseBytes:t.maxResponseBytes,sameOriginRedirectsOnly:t.sameOriginRedirectsOnly,signal:t.signal}),"hyperliquid info response")}async function Q_(e={}){let t=await _e({type:"allMids"},e),n=t&&typeof t=="object"?Object.keys(t).length:0;return{ok:n>0,midCount:n}}async function Gn(e={}){return _e({type:"allMids"},e)}async function Gs(e,t={}){if(!e)throw new Error("hlL2Book requires coin");return _e({type:"l2Book",coin:String(e)},t)}async function el(e={}){return _e({type:"outcomeMeta"},e)}async function Cp(e,t={}){if(!e)throw new Error("hlClearinghouse requires user address");return _e({type:"spotClearinghouseState",user:e},t)}async function Rp(e,t={}){if(!e)throw new Error("hlUserFills requires user address");return _e({type:"userFills",user:e},t)}async function Lp(e={}){return _e({type:"meta"},e)}async function cn(e={}){let t={type:"metaAndAssetCtxs"};return e.dex&&(t.dex=e.dex),_e(t,e)}async function Ks({coin:e,interval:t="1h",startTime:n,endTime:r},o={}){if(!e)throw new Error("hlCandleSnapshot requires coin");let i={type:"candleSnapshot",req:{coin:String(e),interval:t,startTime:n??Date.now()-24*3600*1e3,endTime:r??Date.now()}};return _e(i,o)}async function $p({coin:e,startTime:t,endTime:n},r={}){if(!e)throw new Error("hlFundingHistory requires coin");return _e({type:"fundingHistory",coin:String(e),startTime:t??Date.now()-24*3600*1e3,endTime:n??Date.now()},r)}async function Z_(e,t={}){if(!e)throw new Error("hlOpenOrders requires user");return _e({type:"openOrders",user:e},t)}async function eO(e,t={}){if(!e)throw new Error("hlFrontendOpenOrders requires user");return _e({type:"frontendOpenOrders",user:e},t)}async function Ys(e,t={}){if(!e)throw new Error("hlUserState requires user");return _e({type:"clearinghouseState",user:e},t)}async function Mp(e={}){return _e({type:"spotMeta"},e)}var xb,kb,Ct=Y(()=>{V();Rn();xb="https://api.hyperliquid.xyz/info",kb="https://api.hyperliquid-testnet.xyz/info"});async function cO(e={}){let t=Date.now();if(sl.dexs&&t-sl.at<6e4&&!e.fetchImpl)return sl.dexs;let n=await _e({type:"perpDexs"},e);return sl={at:t,dexs:Array.isArray(n)?n:[]},sl.dexs}async function lO(e="",t={}){let n=e||"",r=Date.now(),o=aO.get(n);if(o&&r-o.at<3e4&&!t.fetchImpl)return o;let i=e?await _e({type:"metaAndAssetCtxs",dex:e},t):await cn(t),s=i?.[0]?.universe??i?.universe??[],a=Array.isArray(i?.[1])?i[1]:[],c={at:r,universe:s,ctxs:a};return aO.set(n,c),c}function K9(e){let t=String(e??"").trim();if(!t)return t;let n=t.toLowerCase().replace(/[\s._-]+/g,"");return G9[n]??t}function Co(e){if(typeof e!="string"||!/^#(?:0|[1-9]\d*)$/.test(e))return null;let t=Number(e.slice(1));if(!Number.isSafeInteger(t)||t<0)return null;let n=t%10;if(n!==0&&n!==1)return null;let r=Math.floor(t/10),o=uO+t;return Number.isSafeInteger(o)?{encoding:t,outcome:r,side:n,coin:`#${t}`,assetId:o}:null}function Po(e,t){let n=Fb(e),r=Fb(t);if(n==null)throw new Error("hl-assets: outcome id must be a non-negative integer");if(r!==0&&r!==1)throw new Error("hl-assets: outcome side must be 0 or 1");let o=10*n+r;if(!Number.isSafeInteger(o))throw new Error("hl-assets: outcome encoding exceeds safe integer range");let i=uO+o;if(!Number.isSafeInteger(i))throw new Error("hl-assets: outcome asset id exceeds safe integer range");return{encoding:o,outcome:n,side:r,coin:`#${o}`,assetId:i}}function Fb(e){if(typeof e=="number")return Number.isSafeInteger(e)&&e>=0?e:null;if(typeof e!="string"||!/^(?:0|[1-9]\d*)$/.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null}async function qb(e={},t={}){if(e.outcome!=null||typeof e.coin=="string"&&e.coin.startsWith("#")){let l=e.coin==null?null:Co(e.coin);if(e.coin!=null&&!l)throw new Error(`hl-assets: invalid outcome coin ${e.coin}`);let u=e.outcome==null?null:Po(e.outcome,0).outcome;if(u!=null&&l&&l.outcome!==u)throw new Error("hl-assets: coin does not match outcome");let d=e.outcomeSide==null?null:Y9(e.outcomeSide,"outcomeSide"),p=u??l?.outcome;if(e.outcome!=null&&e.coin==null&&d==null)throw new Error("hl-assets: outcomeSide required");let f=d??l?.side;if(f==null)throw new Error("hl-assets: outcomeSide required");if(p==null)throw new Error("hl-assets: outcome identity required");let m=Po(p,f);if(l&&(l.outcome!==m.outcome||l.side!==m.side))throw new Error("hl-assets: coin does not match outcome side");let h=e.szDecimals!=null?Number(e.szDecimals):2;return{kind:"outcome",coin:m.coin,assetId:m.assetId,encoding:m.encoding,outcome:m.outcome,side:m.side,szDecimals:h,maxLeverage:1,dex:null,markPx:null}}let n=String(e.coin||e.symbol||e.name||"").trim();if(!n)throw new Error("hl-assets: coin required");if(n.includes(":")){let[l,...u]=n.split(":"),d=u.join(":");if(!l||!d)throw new Error(`hl-assets: bad builder coin ${n}`);let p=K9(l),f=await cO(t),m=f.findIndex(E=>E&&E.name===p);if(m<1)throw new Error(`hl-assets: unknown builder dex "${l}"`);let{universe:h,ctxs:g}=await lO(p,t),y=h.findIndex(E=>E.name===`${p}:${d}`);if(y<0)throw new Error(`hl-assets: ${n} not in dex ${p} meta`);let b=h[y];if(b.isDelisted)throw new Error(`hl-assets: ${n} is delisted`);let S=W9+m*1e4+y,w=g[y]||{};return{kind:"hip3",coin:b.name||n,assetId:S,szDecimals:b.szDecimals??0,maxLeverage:b.maxLeverage??null,dex:p,dexName:f[m]?.fullName||p,dexIndex:m,indexInMeta:y,markPx:w.markPx??null}}let{universe:r,ctxs:o}=await lO("",t),i=n.toUpperCase(),s=r.findIndex(l=>l.name===i);if(s<0){if(t.allowBareBuilderLeaf===!0)try{let l=await cO(t);for(let u=1;u<l.length;u++){let d=l[u];if(!d?.name)continue;let p=`${d.name}:${i}`;try{return await qb({coin:p},t)}catch{}}}catch{}throw new Error(`hl-perps: ${i} is not a listed perp`)}let a=r[s];if(a.isDelisted)throw new Error(`hl-assets: ${i} is delisted`);let c=o[s]||{};return{kind:"main",coin:a.name,assetId:s,szDecimals:a.szDecimals??0,maxLeverage:a.maxLeverage??null,dex:"",markPx:c.markPx??null}}function Y9(e,t){let n=Fb(e);if(n!==0&&n!==1)throw new Error(`hl-assets: ${t} must be 0 or 1`);return n}var uO,W9,sl,aO,G9,jp=Y(()=>{Ct();uO=1e8,W9=1e5,sl={at:0,dexs:null},aO=new Map;G9=Object.freeze({tradexyz:"xyz",ventuals:"vntl",hypernova:"hyna",paradex:"para",entropy:"io",entropyio:"io"})});function kt(e,t="value"){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${t} must be a finite number`);if(Math.abs(e)>Number.MAX_SAFE_INTEGER)throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);if(Number.isInteger(e)&&!Number.isSafeInteger(e))throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);return String(e)}if(typeof e=="string"){if(e!==e.trim())throw new Error(`${t} must be a number or decimal string`);return e}throw new Error(`${t} must be a number or decimal string`)}function Ln(e,t="value"){if(typeof e!="string"||e==="")throw new Error(`${t} must be a string`);return e}function $i(e,t="amount"){if(typeof e=="bigint")return e;if(typeof e=="number"){if(!Number.isInteger(e))throw new Error(`${t} must be an integer`);if(!Number.isSafeInteger(e))throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);return BigInt(e)}let n=kt(e,t);if(n==="")throw new Error(`${t} is required`);if(!/^-?\d+$/.test(n)&&!/^0x[0-9a-fA-F]+$/.test(n))throw new Error(`${t} must be an integer in decimal or 0x-hex form, got ${JSON.stringify(n)}`);try{return BigInt(n)}catch{throw new Error(`${t} must be an integer, got ${JSON.stringify(n)}`)}}function $n(e,t="amount"){let n=$i(e,t);if(n<=0n)throw new Error(`${t} must be positive`);return n}function ht(e,t,n="amount"){let r=kt(e,n);if(!/^-?\d*(\.\d+)?$/.test(r)||r===""||r==="."||r==="-")throw new Error(`${n} must be a decimal number, got ${JSON.stringify(r)}`);let o=r.startsWith("-"),i=o?r.slice(1):r,[s="0",a=""]=i.split(".");if(a.length>t)throw new Error(`${n} has more than ${t} decimal places, which would lose precision`);let c=BigInt((s||"0")+a.padEnd(t,"0"));return o?-c:c}var Js=Y(()=>{});function e8(e,t){let n=e.toString().padStart(t+1,"0");if(t===0)return n;let r=n.slice(0,-t),o=n.slice(-t).replace(/0+$/,"");return o?`${r}.${o}`:r}function dO(e,t){let n=kt(e,`hl: ${t}`);if(!/^\d+(?:\.\d+)?$/.test(n))throw new Error(`hl: ${t} must be a positive decimal`);let[r,o=""]=n.split("."),i=BigInt(r+o);if(i<=0n)throw new Error(`hl: ${t} must be positive`);return{raw:i,decimals:o.length}}function mr(e,t){if(e===null||typeof e=="string"||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`hl: ${t} must be finite JSON`);return JSON.stringify(e)}if(Array.isArray(e))return`[${e.map(r=>mr(r,t)).join(",")}]`;if(!e||typeof e!="object")throw new Error(`hl: ${t} must be structured JSON`);return`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${mr(e[r],t)}`).join(",")}}`}function t8(e){if(typeof e.orderType!="string"||!e.orderType)throw new Error("hl: order type must be a string");let t=e.orderType,n=e.orderWire;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("hl: declared order wire required");if(t==="limit"){let i=n.limit?.tif;if(!["Gtc","Ioc","Alo"].includes(i)||mr(n,"declared order type")!==mr({limit:{tif:i}},"expected order type"))throw new Error("hl: limit order type must match its wire shape");return}if(t==="market"){if(mr(n,"declared order type")!==mr({limit:{tif:"Ioc"}},"expected order type"))throw new Error("hl: market order type must match its IOC wire shape");return}let r={stopMarket:{isMarket:!0,tpsl:"sl"},stopLimit:{isMarket:!1,tpsl:"sl"},takeProfitMarket:{isMarket:!0,tpsl:"tp"},takeProfitLimit:{isMarket:!1,tpsl:"tp"}}[t];if(!r)throw new Error("hl: unsupported declared order type");let o=n.trigger?.triggerPx;if(o==null||mr(n,"declared order type")!==mr({trigger:{isMarket:r.isMarket,triggerPx:o,tpsl:r.tpsl}},"expected order type"))throw new Error("hl: trigger order type must match its wire shape")}function n8(e,t,n){let r=dO(e.s,"signed size"),o=dO(e.p,"signed price"),i=r.decimals+o.decimals,s=r.raw*o.raw,a=ht(t.notionalUsd,i,"hl: notionalUsd");if(a<=0n||s!==a)throw new Error("hl: signed notional must match");let c=ht(n.maxNotionalUsd,i,"hl: maxNotionalUsd");if(s>c)throw new Error("hl: notional exceeds cap")}function r8(e,t){let n=e.action.builder;if(n==null){if(e.builder!=null)throw new Error("hl: declared builder requires a signed builder");return}if(!n||typeof n!="object"||Array.isArray(n))throw new Error("hl: signed order builder must be structured");let r=Ro(n.b,"order builder",42).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(r))throw new Error("hl: order builder address required");if(Ln(e.builder||"","hl: builder").toLowerCase()!==r)throw new Error("hl: signed order builder must match");if(!(Array.isArray(t.hlBuilders)?t.hlBuilders.map(a=>String(a).toLowerCase()):[]).includes(r))throw new Error("hl: order builder not allowed");let i=$i(n.f,"hl: signed order builder fee");if(i<0n)throw new Error("hl: signed order builder fee must be non-negative");let s=ht(t.maxBuilderFeeBps??0,1,"hl: maxBuilderFeeBps");if(i>s)throw new Error("hl: order builder fee exceeds cap")}function pO(e,t,n){if(!Number.isSafeInteger(e.a)||e.a!==n)throw new Error("hl: signed asset must match assetId");if(typeof e.b!="boolean"||e.b!==(t.side==="buy"))throw new Error("hl: signed side must match exactly");if(kt(e.s,"hl: signed size")!==kt(t.size,"hl: size"))throw new Error("hl: signed size must match");if(kt(e.p,"hl: signed price")!==kt(t.price,"hl: price"))throw new Error("hl: signed price must match");if(typeof t.reduceOnly!="boolean"||typeof e.r!="boolean"||e.r!==t.reduceOnly)throw new Error("hl: signed reduceOnly must match exactly");if(mr(e.t,"signed order type")!==mr(t.orderWire,"declared order type"))throw new Error("hl: signed order type must match declared order type");let r=Object.prototype.hasOwnProperty.call(e,"c");if(t.clientOrderId==null){if(r)throw new Error("hl: undeclared signed client order id")}else if(!r||typeof e.c!="string"||e.c!==t.clientOrderId)throw new Error("hl: signed client order id must match")}function fO(e,t,n,r,o){if(!Number.isSafeInteger(e.a)||e.a!==n)throw new Error("hl: bracket protection asset must match");if(typeof e.b!="boolean"||e.b===(t.side==="buy"))throw new Error("hl: bracket protection side must oppose entry");if(kt(e.s,"hl: bracket protection size")!==kt(t.size,"hl: size"))throw new Error("hl: bracket protection size must match");if(kt(e.p,"hl: bracket protection price")!==kt(r,"hl: protection price"))throw new Error("hl: bracket protection price must match");if(e.r!==!0)throw new Error("hl: bracket protection must be reduce-only");let i=e.t?.trigger;if(!i||i.isMarket!==!0||i.tpsl!==o)throw new Error("hl: bracket protection trigger must match");if(kt(i.triggerPx,"hl: triggerPx")!==kt(r,"hl: protection price"))throw new Error("hl: bracket protection trigger must match")}function o8(e){let t=String(e||"").replace(/\/$/,"");if(!J9.has(t))throw new Error("hl: submitTo must be the official Hyperliquid exchange");return t}function jb(e){return Co(e)!=null}function i8(e,t){let n=String(e||""),r=Array.isArray(t.coins)?t.coins.map(String):[];if(jb(n)){if(t.hip4!==!0)throw new Error("hl: HIP-4 outcome orders are disabled without explicit policy enablement");if(r.includes(n)||r.includes("#*")||r.includes("*")||r.length===0)return!0;throw new Error("hl: outcome coin not allowed")}if(r.length&&!r.includes(n)&&!r.includes("*"))throw new Error("hl: coin not allowed");return!0}function s8(e,t,n){let r=Array.isArray(n.hlMarkets)?n.hlMarkets:[];if(r.length){if(!r.some(s=>{if(typeof s=="string"){let[a,c]=String(s).split(":");return a===e&&Number(c)===t}return String(s?.coin)===e&&Number(s?.assetId)===t}))throw new Error("hl: coin/assetId pair not allowed");return!0}if(jb(e)){let i=Array.isArray(n.coins)?n.coins.map(String):[];if(i.includes("#*")||i.includes("*")||i.length===0)return!0;throw new Error("hl: restricted coin policy requires hlMarkets pairs")}let o=Array.isArray(n.coins)?n.coins.map(String):[];if(o.length&&!o.includes("*"))throw new Error("hl: restricted coin policy requires hlMarkets pairs");return!0}function mO(e,t){if(e?.surface!=="hl")throw new Error("hl: surface hl required");let n=e.artifact;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("hl: structured artifact required");let r=Ro(n.kind,"kind",48),o=Q9[r];if(!o)throw new Error("hl: unsupported Hyperliquid kind");if(e.action!==o)throw new Error("hl: surface/action/kind mismatch");if(String(e.destination).toLowerCase()!=="hyperliquid")throw new Error("hl: destination must be hyperliquid");if(!/^0x[0-9a-fA-F]{40}$/.test(String(e.owner||"")))throw new Error("hl: owner required");let i=o8(n.submitTo);if(Object.prototype.hasOwnProperty.call(n,"vaultAddress"))throw new Error("hl: vaultAddress is not public");if(Object.prototype.hasOwnProperty.call(n,"expiresAfter"))throw new Error("hl: expiresAfter is not public");let s=Number(n.nonce);if(!Number.isSafeInteger(s)||s<=0)throw new Error("hl: nonce must be a positive integer");if(!n.action||typeof n.action!="object")throw new Error("hl: signed action required");if(Object.prototype.hasOwnProperty.call(n.action,"vaultAddress"))throw new Error("hl: action vaultAddress is not public");if(Object.prototype.hasOwnProperty.call(n.action,"expiresAfter"))throw new Error("hl: action expiresAfter is not public");if(n.action.type!==Z9[r])throw new Error("hl: action type must match kind");let a=n.notionalUsd??0;if(X9.has(r)||r==="perp-cancel"||r==="perp-leverage"||r==="perp-isolated-margin"){let c=Ro(n.coin,"coin",64),l=n.assetId??n.assetIndex;if(!Number.isSafeInteger(l)||l<0)throw new Error("hl: assetId required");if(r==="perp-bracket"&&l>=1e8)throw new Error("hl: brackets are not supported on outcome markets");if(r==="hip4-order"||l>=1e8){let u=Co(c);if(!u||u.coin!==c)throw new Error("hl: HIP-4 actions must use a canonical outcome coin");if(u.assetId!==l)throw new Error("hl: HIP-4 coin must bind to its canonical assetId")}if(i8(c,t),s8(c,l,t),r==="hip4-order"&&!jb(c))throw new Error("hl: HIP-4 orders must use an outcome coin");if(r==="perp-order"||r==="hip3-order"||r==="hip4-order"||r==="perp-bracket"){if(n.side!=="buy"&&n.side!=="sell")throw new Error("hl: side must be buy or sell");if(n.action.type!=="order"||!Array.isArray(n.action.orders))throw new Error("hl: signed orders are required");t8(n);let u=n.action.orders;if(r==="perp-bracket"){let d=n.takeProfitPx,p=n.stopLossPx,f=1+(d==null?0:1)+(p==null?0:1);if(f<2||u.length!==f||n.grouping!=="normalTpsl"||n.action.grouping!==n.grouping)throw new Error("hl: bracket must contain exactly the declared entry and protection legs");pO(u[0],n,l);let m=1;d!=null&&fO(u[m++],n,l,d,"tp"),p!=null&&fO(u[m],n,l,p,"sl")}else{if(u.length!==1)throw new Error("hl: exactly one signed order is required");if(n.grouping!=="na"||n.action.grouping!==n.grouping)throw new Error("hl: signed grouping must match declared grouping");pO(u[0],n,l)}n8(u[0],n,t),r8(n,t),a=kt(n.notionalUsd,"hl: notionalUsd")}if(r==="perp-leverage"){let u=n.leverage;if(!Number.isSafeInteger(u)||u<1)throw new Error("hl: leverage must be a positive integer");let d=t.maxLeverage==null?50:t.maxLeverage;if(typeof d!="number"||!Number.isSafeInteger(d)||d<1)throw new Error("hl: maxLeverage must be a positive integer");if(u>d)throw new Error("hl: leverage exceeds cap")}if(r==="perp-cancel"){let u=n.action.cancels;if(!Array.isArray(u)||u.length!==1)throw new Error("hl: exactly one cancel is required");if(!Number.isSafeInteger(u[0].a)||u[0].a!==l)throw new Error("hl: signed cancel asset must match assetId");if(!Number.isSafeInteger(n.orderId)||n.orderId<0)throw new Error("hl: declared order id required");if(!Number.isSafeInteger(u[0].o)||u[0].o!==n.orderId)throw new Error("hl: signed cancel order id must match")}if(r==="perp-leverage"){if(!Number.isSafeInteger(n.action.asset)||n.action.asset!==l)throw new Error("hl: signed leverage asset must match assetId");if(!Number.isSafeInteger(n.action.leverage)||n.action.leverage!==n.leverage)throw new Error("hl: signed leverage must match");if(!["cross","isolated"].includes(n.marginMode))throw new Error("hl: declared margin mode required");let u=n.marginMode==="cross";if(typeof n.action.isCross!="boolean"||n.action.isCross!==u)throw new Error("hl: signed isCross must match declared margin mode")}if(r==="perp-isolated-margin"){if(!Number.isSafeInteger(n.action.asset)||n.action.asset!==l)throw new Error("hl: signed margin asset must match assetId");let u=Ro(n.usd,"margin usd",64),d=ht(u,6,"hl: margin usd");if($i(n.action.ntli,"hl: signed margin ntli")!==d)throw new Error("hl: signed margin amount must match usd");if(typeof n.isBuy!="boolean"||n.action.isBuy!==n.isBuy)throw new Error("hl: signed margin isBuy must match");let f=ht(t.maxNotionalUsd,6,"hl: maxNotionalUsd"),m=d<0n?-d:d;if(m>f)throw new Error("hl: margin notional exceeds cap");a=e8(m,6)}}if(r==="builder-fee-approval"){let c=Ro(n.builder,"builder",42).toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(c))throw new Error("hl: builder address required");if(Ro(n.action.builder,"signed builder",42).toLowerCase()!==c)throw new Error("hl: signed builder must match");if(!(Array.isArray(t.hlBuilders)?t.hlBuilders.map(m=>String(m).toLowerCase()):[]).includes(c))throw new Error("hl: builder not allowed");let u=Ro(n.maxFeeRate,"maxFeeRate",32);if(Ro(n.action.maxFeeRate,"signed maxFeeRate",32)!==u)throw new Error("hl: signed builder fee must match");if(!/^\d+(?:\.\d+)?%$/.test(u))throw new Error("hl: builder fee rate must be a percent");let d=ht(u.slice(0,-1),12,"hl: builder fee percent"),p=ht(t.maxBuilderFeeBps,12,"hl: maxBuilderFeeBps");if(p<0n||d*100n>p)throw new Error("hl: builder fee exceeds cap");if(Number(n.action.nonce)!==s)throw new Error("hl: signed builder nonce must match");let f=i.includes("testnet")?"Testnet":"Mainnet";if(n.hyperliquidChain!==f||n.action.hyperliquidChain!==n.hyperliquidChain)throw new Error("hl: signed Hyperliquid chain must match destination");if(n.signatureChainId!=="0x66eee"||n.action.signatureChainId!==n.signatureChainId)throw new Error("hl: signed signature chain id must match")}if(r.startsWith("hype-stake")||r==="hype-delegate"||r==="hype-undelegate"){if(r==="hype-delegate"||r==="hype-undelegate"){let c=r==="hype-undelegate";if(typeof n.action.isUndelegate!="boolean"||n.action.isUndelegate!==c)throw new Error("hl: signed isUndelegate must match delegate kind exactly")}if(t.maxHypeWei!=null&&BigInt(String(n.action.wei??n.caps?.amountHype??"0"))>BigInt(t.maxHypeWei))throw new Error("hl: stake amount exceeds cap")}return Object.freeze({unit:"usd",value:String(a??n.action.wei??0),notional:String(a??0),fee:"0",kind:r,actionType:n.action.type,amount:String(n.action.wei??a??0),coin:n.coin||null,submitTo:i})}var J9,X9,Q9,Z9,Ro,hO=Y(()=>{Js();jp();J9=new Set(["https://api.hyperliquid.xyz/exchange","https://api.hyperliquid-testnet.xyz/exchange"]),X9=new Set(["perp-order","hip3-order","hip4-order","perp-bracket"]),Q9=Object.freeze({"perp-order":"order","hip3-order":"order","hip4-order":"order","perp-bracket":"order","perp-cancel":"cancel","perp-leverage":"leverage","perp-isolated-margin":"margin","builder-fee-approval":"approveBuilder","hype-stake-deposit":"stake","hype-stake-withdraw":"unstake","hype-delegate":"delegate","hype-undelegate":"delegate"}),Z9=Object.freeze({"perp-order":"order","hip3-order":"order","hip4-order":"order","perp-bracket":"order","perp-cancel":"cancel","perp-leverage":"updateLeverage","perp-isolated-margin":"updateIsolatedMargin","builder-fee-approval":"approveBuilderFee","hype-stake-deposit":"cDeposit","hype-stake-withdraw":"cWithdraw","hype-delegate":"tokenDelegate","hype-undelegate":"tokenDelegate"}),Ro=(e,t,n=256)=>{if(typeof e!="string"||!e||e.length>n)throw new Error(`hl: bounded ${t} required`);return e}});function c8(e){let t=e.owner||e.user||e.from||e.recipient;if(!/^0x[0-9a-fA-F]{40}$/.test(String(t||"")))throw new Error("hl: owner/user address required for local-signer envelope");return String(t).toLowerCase()}function Hp(e,t={},n={}){let r=String(e?.kind||""),o=a8[r];if(!o)throw new Error("hl: prepared kind is not a local-signer surface");if(!e?.action||typeof e.action!="object")throw new Error("hl: prepared action required");let i=Number(n.nowMs??Date.now()),s=Math.min(6e4,Math.max(1e3,Number(t.ttlMs??t.expiresInMs??3e4)||3e4)),a=String(e.submitTo||"").replace(/\/$/,""),c={version:1,surface:"hl",action:o,owner:c8(t),destination:"hyperliquid",tradeId:String(t.tradeId||`hl:${r}:${e.nonce}`),expiresAtMs:i+s,slippageBps:Number(t.slippageBps??0),fee:{oracleFeeBps:0},provider:e.provider,artifact:{kind:r,coin:e.coin??null,assetId:e.assetId??e.assetIndex??null,side:e.side??null,size:e.size??null,price:e.price??null,reduceOnly:e.reduceOnly??null,orderType:e.orderType??null,orderWire:e.action?.orders?.[0]?.t??null,clientOrderId:e.action?.orders?.[0]?.c??null,grouping:e.action?.grouping??null,orderId:e.orderId??null,leverage:e.leverage??null,marginMode:e.marginMode??null,notionalUsd:e.notionalUsd??0,usd:e.usd??null,isBuy:e.isBuy??null,takeProfitPx:e.takeProfitPx??null,stopLossPx:e.stopLossPx??null,builder:e.builderFee?.address??e.action?.builder??null,maxFeeRate:e.builderFee?.percent??e.action?.maxFeeRate??null,nonce:e.nonce,hyperliquidChain:e.action?.hyperliquidChain??null,signatureChainId:e.signatureChainId||e.action?.signatureChainId||"0xa4b1",submitTo:a,action:e.action,typedData:e.typedData||null,caps:e.caps||null}};return mO(c,{coins:t.coins||["*"],hip4:!0,maxNotionalUsd:t.maxNotionalUsd??Number.MAX_SAFE_INTEGER,maxLeverage:t.maxLeverage??50,hlBuilders:t.hlBuilders||(e.builderFee?.address?[e.builderFee.address]:[]),maxBuilderFeeBps:t.maxBuilderFeeBps??e.builderFee?.bps}),c}var a8,Hb=Y(()=>{hO();a8=Object.freeze({"perp-order":"order","hip3-order":"order","hip4-order":"order","perp-bracket":"order","perp-cancel":"cancel","perp-leverage":"leverage","perp-isolated-margin":"margin","builder-fee-approval":"approveBuilder","hype-stake-deposit":"stake","hype-stake-withdraw":"unstake","hype-delegate":"delegate","hype-undelegate":"delegate"})});var Zb={};vt(Zb,{HL_BUILDER_ADDRESS_ENV:()=>zp,HL_BUILDER_DEFAULT_FEE_BPS:()=>l8,HL_BUILDER_FEE_ENV:()=>Vb,HL_BUILDER_FEE_TIERS:()=>al,HL_BUILDER_MAX_FEE_BPS:()=>zb,HL_PERP_MAX_SIG_FIGS:()=>gO,HL_PERP_PRICE_DECIMALS:()=>yO,HL_SIGNATURE_CHAIN_ID:()=>Vp,MARGIN_MODE:()=>cl,ORDER_TYPES:()=>ln,TIF:()=>ll,formatPerpPrice:()=>Hr,formatPerpSize:()=>EO,hlBuilderFeeBpsForKind:()=>SO,hlPerpAssetInfo:()=>Lo,hlPrepareApproveAgent:()=>g8,hlPrepareBracketOrder:()=>Qb,hlPrepareBuilderApproval:()=>Yb,hlPrepareCancelOrder:()=>ul,hlPreparePerpOrder:()=>$o,hlPrepareUpdateIsolatedMargin:()=>Xb,hlPrepareUpdateLeverage:()=>Jb,resolveBuilderFee:()=>Gb});function bO(e,t){if(typeof e=="number"){if(Number.isSafeInteger(e)&&e>=0)return e}else if(typeof e=="string"&&/^(?:0|[1-9]\d*)$/.test(e)){let n=Number(e);if(Number.isSafeInteger(n))return n}throw new Error(`hl-perps: ${t} must be a non-negative safe integer`)}function u8(e,t){let n=bO(e,t);if(n<1)throw new Error(`hl-perps: ${t} must be a positive integer`);return n}function d8(e={}){let t={...e};if(t.side==null)return t;if(t.side===0||t.side===1){if(t.outcomeSide!=null&&t.outcomeSide!==t.side)throw new Error("hl-perps: side conflict with outcomeSide");return t.outcomeSide=t.side,delete t.side,t}throw new Error("hl-assets: side must be 0 or 1")}function wO(e,{defaultBuy:t=!1}={}){if(e.side!=null){if(typeof e.side!="string")throw new Error("hl-perps: side must be buy or sell");let n=e.side.toLowerCase();if(n!=="buy"&&n!=="sell")throw new Error("hl-perps: side must be buy or sell");let r=n==="buy";if(e.isBuy!=null&&(typeof e.isBuy!="boolean"||e.isBuy!==r))throw new Error("hl-perps: side and isBuy conflict");return r}if(e.isBuy==null&&t)return!0;if(typeof e.isBuy!="boolean")throw new Error("hl-perps: isBuy must be boolean when side is omitted");return e.isBuy}function SO(e="perp"){if(e==="perp"||e==="main")return al.perp;if(e==="spot")return al.spot;if(e==="hip3")return al.hip3;if(e==="outcome"||e==="hip4")return al.hip4;throw new Error(`hl-perps: unknown builder fee kind ${e}`)}function Gb({env:e=process.env,isHolder:t=!1,kind:n="perp"}={}){if(t)return null;let r=String(e?.[zp]||"").trim().toLowerCase();if(!r)return null;if(!/^0x[a-f0-9]{40}$/.test(r))throw new Error(`hl-perps: ${zp} must be an EVM address`);let o=fy(e);if(!o||o!==r)return null;let i=e?.[Vb],s=SO(n),a=i==null?s:Number(i);if(!Number.isFinite(a)||a<=0||Math.abs(a*10-Math.round(a*10))>1e-9)throw new Error(`hl-perps: ${Vb} must be a positive number in 0.1 bps increments`);if(a>zb)throw new Error(`hl-perps: builder fee ${a} bps exceeds the ${zb} bps cap`);if(a>s)throw new Error(`hl-perps: builder fee ${a} bps exceeds the ${s} bps product tier for ${n}`);let c=Math.round(a*10),l=(c/1e3).toFixed(3).replace(/0+$/,"").replace(/\.$/,"");return{wire:{b:r,f:c},disclosure:{address:r,bps:a,percent:`${l}%`}}}async function p8(e,t={},n={}){if(!e)return{approved:!1,approvedFeeBps:0,status:"not-configured"};let r=String(t.user||n.user||"").trim().toLowerCase();if(!/^0x[a-f0-9]{40}$/.test(r))return{approved:!1,approvedFeeBps:0,status:"wallet-required"};try{let o=Number(await _e({type:"maxBuilderFee",user:r,builder:e.disclosure.address},n));return!Number.isInteger(o)||o<0?{approved:!1,approvedFeeBps:0,status:"invalid-response"}:{approved:o>=e.wire.f,approvedFeeBps:o/10,status:o>=e.wire.f?"approved":"insufficient"}}catch{return{approved:!1,approvedFeeBps:0,status:"unavailable"}}}async function f8(e,t={},n={}){if(!e)return{exempt:!1,status:"not-configured"};let r=String(t.user||n.user||"").trim().toLowerCase();if(!/^0x[a-f0-9]{40}$/.test(r))return{exempt:!1,status:"wallet-required"};try{let o=n.holderBalance||rp;return BigInt(await o(r))>0n?{exempt:!0,status:"holder"}:{exempt:!1,status:"non-holder"}}catch{return{exempt:!1,status:"unavailable"}}}function Kb(e,t,{roundDown:n=null}={}){let r=typeof e=="number"?e.toFixed(Math.min(20,t+8)):e;if(typeof r!="string"||!/^-?\d+(\.\d+)?$/.test(r))throw new Error(`hl-perps: "${e}" is not a decimal number`);let o=r.startsWith("-"),[i,s=""]=r.replace(/^-/,"").split(".");if(s.length<=t){let m=s.replace(/0+$/,"");return(o?"-":"")+(m?`${i}.${m}`:i)}let a=s.slice(0,t),c=Number(s[t]),l=BigInt(i+a),u=s.slice(t).replace(/0+$/,"")!=="";n===!0||(n===!1?u&&(l+=1n):c>=5&&(l+=1n));let d=l.toString().padStart(t+1,"0"),f=(t===0?d:`${d.slice(0,-t)}.${d.slice(-t)}`).replace(/(\.\d*?)0+$/,"$1").replace(/\.$/,"");return(o?"-":"")+f}function m8(e,t,n={}){if(typeof e!="number"&&typeof e!="string")throw new Error(`hl-perps: "${e}" is not a decimal number`);let r=typeof e=="number"?String(e):e;if(!r.includes("."))return r;let o=Number(r);if(!Number.isFinite(o)||o===0)return r;let i=Math.floor(Math.log10(Math.abs(o))),s=Math.max(0,t-1-i);return Kb(r,s,n)}function Hr(e,t,n={}){let r=yO-Number(t??0);if(r<0)throw new Error("hl-perps: szDecimals out of range");return Kb(m8(e,gO,n),r,n)}function EO(e,t){let n=Kb(e,Number(t??0));if(BigInt(n.split(".")[0])<0n)throw new Error("hl-perps: size must be positive");if(Number(n)<=0)throw new Error("hl-perps: size rounds to zero at this asset's precision");return n}function h8(e,t){let n=(u,d)=>{let p=String(u).trim();if(!/^\d+(?:\.\d+)?$/.test(p))throw new Error(`hl-perps: ${d} must be a positive decimal`);let[f,m=""]=p.split(".");return{raw:BigInt(f+m),decimals:m.length}},r=n(e,"size"),o=n(t,"price"),i=r.raw*o.raw,s=r.decimals+o.decimals,a=i.toString().padStart(s+1,"0");if(s===0)return a;let c=a.slice(0,-s),l=a.slice(-s).replace(/0+$/,"");return l?`${c}.${l}`:c}async function Lo(e={},t={}){let n=await qb(e,t);return{coin:n.coin,assetId:n.assetId,szDecimals:n.szDecimals,maxLeverage:n.maxLeverage,markPx:n.markPx,kind:n.kind,dex:n.dex??null,dexName:n.dexName??null,outcome:n.outcome??null,side:n.side??null}}function Wb(e,{tif:t=ll.GTC,triggerPx:n,isMarket:r,szDecimals:o}={}){switch(e){case ln.LIMIT:return{limit:{tif:t}};case ln.MARKET:return{limit:{tif:ll.IOC}};case ln.STOP_MARKET:case ln.TAKE_PROFIT_MARKET:return{trigger:{isMarket:!0,triggerPx:Hr(n,o),tpsl:e===ln.STOP_MARKET?"sl":"tp"}};case ln.STOP_LIMIT:case ln.TAKE_PROFIT_LIMIT:return{trigger:{isMarket:!1,triggerPx:Hr(n,o),tpsl:e===ln.STOP_LIMIT?"sl":"tp"}};default:throw new Error(`hl-perps: unknown order type ${e}`)}}function Mi(e,t,n={}){let r=n.testnet||process.env.HL_TESTNET==="1";return{action:e,nonce:t,signatureChainId:Vp,submitTo:r?"https://api.hyperliquid-testnet.xyz/exchange":"https://api.hyperliquid.xyz/exchange",note:"Sign locally via Oracle local-signer or a wallet. Hosted Oracle does not submit."}}function Xs(e,t={},n={}){let r={...e};try{r.localSignerEnvelope=Hp(r,t,n),r.prepared=!0,r.signing="awaiting-hl-signer"}catch(o){r.prepared=!1,r.localSignerEnvelope=null,r.localSignerBlockedReason=String(o?.message||o).slice(0,200),r.signing="blocked"}return r.oraclePrepared=!!r.localSignerEnvelope,q(r,{provider:e.provider||"hl-perps",kind:e.kind})}function Yb(e={},t={}){let n=Gb({env:t.env});if(!n)throw new Error(`hl-perps: ${zp} is required`);let r=Number(e.nonce??t.nonce??Date.now());if(!Number.isSafeInteger(r)||r<=0)throw new Error("hl-perps: nonce must be a positive integer");let o={type:"approveBuilderFee",hyperliquidChain:t.testnet||process.env.HL_TESTNET==="1"?"Testnet":"Mainnet",signatureChainId:Vp,maxFeeRate:n.disclosure.percent,builder:n.disclosure.address,nonce:r};return Xs({provider:"hl-perps",venue:"hyperliquid",kind:"builder-fee-approval",builderFee:n.disclosure,...Mi(o,r,t)},e,t)}function g8(e={},t={}){let n=String(e.agentAddress||e.agent||"").trim();if(!/^0x[0-9a-fA-F]{40}$/.test(n))throw new Error("hl-perps: agentAddress required");let r=Number(e.nonce??t.nonce??Date.now());if(!Number.isSafeInteger(r)||r<=0)throw new Error("hl-perps: nonce must be a positive integer");let o=String(e.agentName||"Oracle").slice(0,16),i={type:"approveAgent",hyperliquidChain:t.testnet||process.env.HL_TESTNET==="1"?"Testnet":"Mainnet",signatureChainId:Vp,agentAddress:n.toLowerCase(),agentName:o,nonce:r};return q({provider:"hl-perps",venue:"hyperliquid",kind:"hl-approve-agent",unsigned:!0,broadcast:!1,agentAddress:n.toLowerCase(),agentName:o,...Mi(i,r,t)},{provider:"hl-perps",kind:"hl-approve-agent",env:t.env})}async function $o(e={},t={}){let n=await Lo(e,t);if(e.type!=null&&(typeof e.type!="string"||!e.type))throw new Error("hl-perps: order type must be a string");let r=e.type??ln.LIMIT;if(typeof r!="string"||!r)throw new Error("hl-perps: order type must be a string");let o=wO(e);if(e.reduceOnly!=null&&typeof e.reduceOnly!="boolean")throw new Error("hl-perps: reduceOnly must be boolean");let i=e.reduceOnly===!0,s=EO(e.size??e.sz,n.szDecimals),a;if(r===ln.MARKET){let b=Number(n.markPx);if(!Number.isFinite(b)){let x=await Gn(t);b=Number(x?.[n.coin]??x?.[String(n.assetId)]??NaN)}if(!Number.isFinite(b))throw new Error("hl-perps: no mark price available for a market order");let S=Number(e.maxSlippageBps??50);if(!Number.isInteger(S)||S<0)throw new Error("hl-perps: maxSlippageBps must be a non-negative integer");if(S>100)throw new Error(`hl-perps: maxSlippageBps ${S} exceeds the hard 100 bps cap`);let w=o?b*(1+S/1e4):b*(1-S/1e4);a=Hr(w,n.szDecimals,{roundDown:o});let E=Math.abs(Number(a)/b-1)*1e4;if(E>S+1e-9)throw new Error(`hl-perps: tick rounding makes the limit ${E.toFixed(2)} bps from mark, above the ${S} bps cap`)}else{if(e.price==null&&e.limitPx==null)throw new Error("hl-perps: a limit order requires an explicit price");a=Hr(e.price??e.limitPx,n.szDecimals)}let c=Wb(r,{tif:e.tif??(r===ln.MARKET?ll.IOC:ll.GTC),triggerPx:e.triggerPx,szDecimals:n.szDecimals}),l={a:n.assetId,b:o,p:a,s,r:i,t:c};if(e.clientOrderId!=null){if(typeof e.clientOrderId!="string"||!e.clientOrderId)throw new Error("hl-perps: clientOrderId must be a string");l.c=e.clientOrderId}if(e.grouping!=null&&(typeof e.grouping!="string"||!e.grouping))throw new Error("hl-perps: grouping must be a string");let u={type:"order",orders:[l],grouping:e.grouping??"na"},d=Gb({env:t.env,kind:n.kind}),p=await f8(d,e,t),f=p.exempt?null:d,m=await p8(f,e,t),h=m.approved?f:null;h&&(u.builder=h.wire);let g=Number(e.nonce??Date.now()),y=h8(s,a);return Xs({provider:"hl-perps",venue:"hyperliquid",kind:n.kind==="outcome"?"hip4-order":n.kind==="hip3"?"hip3-order":"perp-order",coin:n.coin,assetId:n.assetId,assetKind:n.kind,outcome:n.outcome??null,outcomeSide:n.side??null,dex:n.dex??null,dexName:n.dexName??null,side:o?"buy":"sell",orderType:r,price:a,size:s,reduceOnly:i,notionalUsd:y,maxLeverage:n.maxLeverage,markPx:n.markPx,builderFee:h?.disclosure??null,holderExempt:p.exempt,holderVerificationStatus:p.status,builderApprovalRequired:f&&!h?{...d.disclosure,...m}:null,...Mi(u,g,t)},e,t)}async function ul(e={},t={}){let n=await Lo(d8(e),t),r=e.orderId??e.oid;if(r==null)throw new Error("hl-perps: orderId required");let o=bO(r,"orderId"),i={type:"cancel",cancels:[{a:n.assetId,o}]};return Xs({provider:"hl-perps",venue:"hyperliquid",kind:"perp-cancel",coin:n.coin,assetId:n.assetId,orderId:o,...Mi(i,Number(e.nonce??Date.now()),t)},e,t)}async function Jb(e={},t={}){let n=await Lo(e,t),r=u8(e.leverage,"leverage");if(n.maxLeverage!=null&&r>n.maxLeverage)throw new Error(`hl-perps: ${n.coin} allows at most ${n.maxLeverage}x, requested ${r}x`);if(e.marginMode!=null&&typeof e.marginMode!="string")throw new Error("hl-perps: marginMode must be a string");let o=(e.marginMode||cl.CROSS).toLowerCase();if(o!==cl.CROSS&&o!==cl.ISOLATED)throw new Error('hl-perps: marginMode must be "cross" or "isolated"');let i={type:"updateLeverage",asset:n.assetId,isCross:o===cl.CROSS,leverage:r};return Xs({provider:"hl-perps",venue:"hyperliquid",kind:"perp-leverage",coin:n.coin,assetId:n.assetId,leverage:r,marginMode:o,maxLeverage:n.maxLeverage,liquidationWarning:r>=20?`${r}x liquidates on roughly a ${(100/r).toFixed(2)}% adverse move before fees`:null,...Mi(i,Number(e.nonce??Date.now()),t)},e,t)}async function Xb(e={},t={}){let n=await Lo(e,t),r=e.usd??e.amountUsd;if(r==null)throw new Error("hl-perps: usd amount required");if(typeof r!="number"&&typeof r!="string")throw new Error("hl-perps: usd must be a decimal number");let o=typeof r=="number"?String(r):r;if(!/^-?\d+(\.\d+)?$/.test(o))throw new Error("hl-perps: usd must be a decimal number");let i=ht(o,6,"hl-perps: usd"),s=wO(e,{defaultBuy:!0}),a={type:"updateIsolatedMargin",asset:n.assetId,isBuy:s,ntli:i<=BigInt(Number.MAX_SAFE_INTEGER)?Number(i):i.toString()};return Xs({provider:"hl-perps",venue:"hyperliquid",kind:"perp-isolated-margin",coin:n.coin,assetId:n.assetId,isBuy:s,usd:o,...Mi(a,Number(e.nonce??Date.now()),t)},e,t)}async function Qb(e={},t={}){let n=await $o(e,t),r=await Lo(e,t),o=n.side==="buy",i=[n.action.orders[0]];if(e.takeProfitPx!=null&&i.push({a:r.assetId,b:!o,p:Hr(e.takeProfitPx,r.szDecimals),s:n.size,r:!0,t:Wb(ln.TAKE_PROFIT_MARKET,{triggerPx:e.takeProfitPx,szDecimals:r.szDecimals})}),e.stopLossPx!=null&&i.push({a:r.assetId,b:!o,p:Hr(e.stopLossPx,r.szDecimals),s:n.size,r:!0,t:Wb(ln.STOP_MARKET,{triggerPx:e.stopLossPx,szDecimals:r.szDecimals})}),i.length===1)throw new Error("hl-perps: a bracket needs takeProfitPx and/or stopLossPx");let s={type:"order",orders:i,grouping:"normalTpsl",...n.action.builder?{builder:n.action.builder}:{}};return Xs({provider:"hl-perps",venue:"hyperliquid",kind:"perp-bracket",coin:r.coin,assetId:r.assetId,side:n.side,price:n.price,size:n.size,reduceOnly:n.reduceOnly,orderType:n.orderType,notionalUsd:n.notionalUsd,legs:i.length,entry:{side:n.side,price:n.price,size:n.size},takeProfitPx:e.takeProfitPx==null?null:Hr(e.takeProfitPx,r.szDecimals),stopLossPx:e.stopLossPx==null?null:Hr(e.stopLossPx,r.szDecimals),builderFee:n.builderFee,...Mi(s,Number(e.nonce??Date.now()),t)},e,t)}var gO,yO,Vp,l8,zb,zp,Vb,al,ln,ll,cl,dl=Y(()=>{Ct();jp();Js();ae();Hb();dy();Cc();gO=5,yO=6,Vp="0x66eee",l8=2,zb=10,zp="ORACLE_HL_BUILDER_ADDRESS",Vb="ORACLE_HL_BUILDER_FEE_BPS",al=Object.freeze({perp:2,spot:1,hip3:1,hip4:1}),ln=Object.freeze({LIMIT:"limit",MARKET:"market",STOP_MARKET:"stopMarket",STOP_LIMIT:"stopLimit",TAKE_PROFIT_MARKET:"takeProfitMarket",TAKE_PROFIT_LIMIT:"takeProfitLimit"}),ll=Object.freeze({GTC:"Gtc",IOC:"Ioc",ALO:"Alo"}),cl=Object.freeze({CROSS:"cross",ISOLATED:"isolated"})});import{existsSync as kC,readFileSync as AC}from"node:fs";import{dirname as xC,join as Vf}from"node:path";import{fileURLToPath as rK}from"node:url";function IC(e){let t=xC(rK(e));for(let n=0;n<8;n+=1){let r=Vf(t,"package.json");if(kC(r))try{let i=JSON.parse(AC(r,"utf8"));if(i&&typeof i.version=="string")return t}catch{}let o=xC(t);if(o===t)break;t=o}throw new Error(`oracle: could not resolve package root from ${e}`)}function _C(e){return JSON.parse(AC(Vf(IC(e),"package.json"),"utf8"))}function Wf(e,t){let n=IC(t),r=Vf(n,e);return kC(r)?r:Vf(n,"dist","assets",e)}var Gf=Y(()=>{});import{isAddress as oK}from"ethers";function sK(e,t){return Object.freeze({id:e,contractName:t.contractName,source:t.source,dependency:Object.freeze({name:"OpenZeppelin Contracts",version:OC,tag:`v${OC}`}),constructor:Object.freeze([...t.constructor]),authority:Object.freeze([...t.authority]),monitor:Object.freeze([...t.monitor]),fixedSource:!0,proxy:!1,upgradeable:!1,arbitraryDelegatecall:!1,modelEmittedSource:!1})}function Kf(e){let t=Ki[String(e||"")];if(!t)throw new Error(`protocol-templates: unknown template "${e}"`);return t}function Zl(e,t){try{if(BigInt(e)<=0n)throw new Error}catch{throw new Error(`${t} must be > 0`)}}function eu(e,t){let n=String(e||"");if(!oK(n)||/^0x0{40}$/i.test(n))throw new Error(`${t} must be nonzero address`)}function TC(e,t){let n=Kf(e);if(!Array.isArray(t))throw new Error(`${e}: constructor args must be an array`);if(t.length!==n.constructor.length)throw new Error(`${e}: expected ${n.constructor.length} constructor args`);if(e==="safe-erc20"){let[r,o,i,s,a]=t;if(!String(r||"").trim()||!String(o||"").trim())throw new Error("safe-erc20: name/symbol required");Zl(i,"safe-erc20: supply"),eu(s,"safe-erc20: initialHolder"),eu(a,"safe-erc20: initialOwner")}else if(e==="safe-erc721-drop"){let[r,o,i,s,a,c,l]=t;if(!String(r||"").trim()||!String(o||"").trim())throw new Error("safe-erc721-drop: name/symbol required");if(Zl(i,"safe-erc721-drop: cap"),eu(s,"safe-erc721-drop: treasury"),Zl(a,"safe-erc721-drop: mintPrice"),Zl(c,"safe-erc721-drop: perWalletCap"),BigInt(c)>BigInt(i))throw new Error("safe-erc721-drop: perWalletCap exceeds cap");eu(l,"safe-erc721-drop: initialOwner")}else if(e==="safe-vesting"){let[r,o,i]=t;eu(r,"safe-vesting: beneficiary");for(let[s,a]of[[o,"startTimestamp"],[i,"durationSeconds"]])try{let c=BigInt(s);if(c<0n||c>18446744073709551615n)throw new Error}catch{throw new Error(`safe-vesting: ${a} must be uint64`)}Zl(i,"safe-vesting: durationSeconds")}return n}function NC(e){return{authorities:[...e.authority],proxy:!1,upgradeable:!1,arbitraryDelegatecall:!1}}var OC,iK,Ki,Yf=Y(()=>{OC="5.0.2",iK={"safe-erc20":{contractName:"SafeERC20",source:"src/SafeERC20.sol",constructor:["string name","string symbol","uint256 initialSupply","address initialHolder","address initialOwner"],authority:["initialOwner may pause transfers and use Ownable2Step"],monitor:["OwnershipTransferStarted","OwnershipTransferred","Paused","Unpaused","Transfer"]},"safe-erc721-drop":{contractName:"SafeERC721Drop",source:"src/SafeERC721Drop.sol",constructor:["string name","string symbol","uint256 cap","address treasury","uint256 mintPrice","uint256 perWalletCap","address initialOwner"],authority:["initialOwner may withdraw the full balance to immutable treasury","no mint, proxy, upgrade, or delegatecall authority"],monitor:["Transfer","OwnershipTransferred","Withdrawal"]},"safe-vesting":{contractName:"SafeVesting",source:"src/SafeVesting.sol",constructor:["address beneficiary","uint64 startTimestamp","uint64 durationSeconds"],authority:["beneficiary is the immutable OpenZeppelin owner/recipient identity","ownership transfer and renunciation are disabled","no separate administrator, proxy, upgrade, or delegatecall authority"],monitor:["EtherReleased","ERC20Released"]}};Ki=Object.freeze(Object.fromEntries(Object.entries(iK).map(([e,t])=>[e,sK(e,t)])))});import{spawnSync as RC}from"node:child_process";import{existsSync as PC,mkdtempSync as aK,readFileSync as cK,rmSync as lK}from"node:fs";import{tmpdir as uK}from"node:os";import{join as xw}from"node:path";function LC(e){let t=e.HOME||"";return`${t}/.local/bin:${t}/.foundry/bin:${e.PATH||""}`}function mK(e=process.env){return e.SLITHER_BIN?e.SLITHER_BIN:RC("slither",["--version"],{encoding:"utf8",env:{...e,PATH:LC(e)}}).status===0?"slither":null}function CC(e){return String(e||"").split(`
|
|
9
9
|
`)[0].slice(0,200)}function $C(e,t={}){let n=t.env||process.env,r=t.bin===void 0?mK(n):t.bin;if(!r)return{tool:null,ok:!0,skipped:!0,reason:"slither not installed",blocking:[],tolerated:[],counts:{},findings:[]};if(!PC(xw(e,"foundry.toml")))return{tool:"slither",ok:!1,skipped:!1,reason:"no foundry.toml",blocking:[],tolerated:[],counts:{},findings:[]};let o=new Set((t.allow||[]).filter(c=>!pK.includes(c))),i=aK(xw(uK(),"oracle-slither-")),s=xw(i,"slither.json"),a;try{if(a=RC(r,[".","--filter-paths",fK,"--exclude-dependencies","--json",s,"--disable-color"],{cwd:e,encoding:"utf8",env:{...n,PATH:LC(n)},timeout:t.timeoutMs||18e4}),!PC(s))return{tool:"slither",ok:!1,skipped:!1,reason:`slither produced no output (compile failed?)
|
|
10
10
|
${(a.stderr||a.stdout||"").slice(-1200)}`,blocking:[],tolerated:[],counts:{},findings:[]};let c=JSON.parse(cK(s,"utf8"));if(!c.success)return{tool:"slither",ok:!1,skipped:!1,reason:String(c.error||"slither error").slice(0,800),blocking:[],tolerated:[],counts:{},findings:[]};let u=(c.results?.detectors||[]).map(g=>({check:g.check,impact:g.impact,confidence:g.confidence,description:CC(g.description)})),d={};for(let g of u)d[g.impact]=(d[g.impact]||0)+1;let p=u.filter(g=>dK.includes(g.impact)),f=p.filter(g=>!o.has(g.check)),m=p.filter(g=>o.has(g.check)),h=CC((a.stderr+a.stdout).split(`
|
|
11
11
|
`).find(g=>g.includes("analyzed"))||"");return{tool:"slither",ok:f.length===0,skipped:!1,blocking:f,tolerated:m,counts:d,findings:u,analyzed:h}}finally{lK(i,{recursive:!0,force:!0})}}function MC(e){let t=e.blocking.map(n=>` ${n.impact}/${n.confidence} ${n.check}: ${n.description}`);return`slither BLOCK (${e.blocking.length} High/Medium)
|