@oracle-agent/oracle 0.35.24 → 0.35.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -0
- package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
- package/dist/bin/desk-server.mjs +1 -1
- package/dist/bin/oracle.mjs +13 -12
- package/dist/cli/commands/chat.mjs +222 -222
- package/dist/cli/commands/eval.mjs +1 -1
- package/dist/cli/commands/farm.mjs +1 -1
- package/dist/cli/commands/model.mjs +225 -225
- package/dist/cli/commands/session-vault.mjs +15 -0
- package/dist/cli/commands/setup.mjs +4 -4
- package/dist/data/desk-data.mjs +1 -1
- package/dist/index.mjs +49 -49
- package/package.json +1 -1
- package/public/eval-report.json +1 -1
- package/server.json +2 -2
package/dist/data/desk-data.mjs
CHANGED
|
@@ -142,7 +142,7 @@ anchor-lang = "0.31.1"
|
|
|
142
142
|
- This is a policy scaffold, not a funded address, PSBT, signature, or broadcast
|
|
143
143
|
- Compile and satisfy on regtest/signet with a reviewed Miniscript implementation before mainnet
|
|
144
144
|
`)];return{family:"bitcoin",network:n,projectName:t,protocolModel:nl["bitcoin-tapscript-vault"].protocolModel,policy:{descriptorType:"tr",miniscript:l,cooperativeMiniscript:s,recoveryMiniscript:c,descriptor:f,address:m.address,scriptPubKey:m.scriptPubKey,threshold:o,signerCount:r.length,recoveryDelayBlocks:a.toString()},authorityReport:{cooperativeSigners:r,threshold:o,recoveryPubkey:i,recoveryDelayBlocks:a.toString()},files:g,gate:{sourceChecks:{ok:o<=r.length&&a>0n&&new Set([...r,i]).size===r.length+1,checks:["bounded threshold","unique keys","positive BIP68 delay","separate recovery key"]},compiler:{tool:"rust-miniscript or equivalent",requiredBeforeFunding:!0,run:!1},tests:{tool:"regtest/signet policy satisfaction",requiredBeforeFunding:!0,run:!1},simulation:{network:n==="mainnet"?"signet or regtest required first":n,requiredBeforeFunding:!0,run:!1},firmAudit:!1,disclaimer:Ym},psbtPrepared:!1,fundingPrepared:!1}}function pa(){return Object.values(nl).map(e=>({...e,disclaimer:Ym}))}async function ma(e={}){let t=String(e.templateId||"").trim(),n=nl[t];n||yt("protocol-templates",`unknown native template "${t}"`);let r=t==="solana-safe-vault"?RU(e):LU(e),o=OU(r.files);return N({provider:"protocol-templates",kind:"native-protocol-build",templateId:t,supportStatus:n.supportStatus,prepareOnly:!0,firmAudit:!1,artifactHash:o,...r,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,note:"Deterministic native protocol source bundle only. Compile, test, simulate, and separately prepare deployment/funding before user signature."},{provider:"protocol-templates",kind:"native-protocol-build"})}var Ym,kS,nl,Xm=G(()=>{Y();Ym="Reviewed scaffold and source checks only; NOT a paid security audit. Testnet simulation and independent review are required before mainnet use.",kS="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",nl=Object.freeze({"solana-safe-vault":Object.freeze({id:"solana-safe-vault",family:"solana",language:"Rust / Anchor",supportStatus:"GUIDED_BUILD",protocolModel:"Solana program with PDA-owned vault state",prepareOnly:!0,firmAudit:!1}),"bitcoin-tapscript-vault":Object.freeze({id:"bitcoin-tapscript-vault",family:"bitcoin",language:"Miniscript / Tapscript policy",supportStatus:"GUIDED_BUILD",protocolModel:"UTXO policy; not a general-purpose smart contract",prepareOnly:!0,firmAudit:!1})})});var DC={};Ze(DC,{CONTRACTS_EVAL_HERE:()=>xH,runContractsEval:()=>vH});import Ql from"node:fs";import Hn from"node:path";import{spawnSync as sH}from"node:child_process";import{fileURLToPath as cH}from"node:url";function gH(){let e=process.env.HOME||"";for(let t of["forge",Hn.join(e,".foundry/bin/forge")])if(sH(t,["--version"],{encoding:"utf8"}).status===0)return!0;return!1}function FC(e,t=[]){if(!Ql.existsSync(e))return t;for(let n of Ql.readdirSync(e)){let r=Hn.join(e,n);if(Ql.statSync(r).isDirectory()){if(["lib","out","cache","node_modules"].includes(n))continue;FC(r,t)}else n.endsWith(".sol")&&!r.includes(`${Hn.sep}lib${Hn.sep}`)&&t.push(r)}return t}function yH(){let e=[];for(let t of Object.keys(mr)){let n=Hn.join(lH,t),r=FC(Hn.join(n,"src")),o=[];for(let i of r){let a=Ql.readFileSync(i,"utf8");for(let s of uH)s.test(a)&&o.push(`${Hn.basename(i)}:${s}`)}e.push({language:"Solidity",templateId:t,ok:r.length>0&&o.length===0,files:r.length,hits:o})}return e}function bH(){return gH()?Object.keys(mr).map(e=>{try{let t=ua(e,{allowSkipStatic:!0});return{language:"Solidity",templateId:e,ok:t.ok===!0&&t.forgeTests?.ok===!0,forge:t.forgeTests,firmAudit:t.firmAudit===!1}}catch(t){return{language:"Solidity",templateId:e,ok:!1,error:String(t?.message||t).slice(0,240)}}}):Object.keys(mr).map(e=>({language:"Solidity",templateId:e,ok:!0,skipped:!0,reason:"forge-not-installed"}))}async function wH(){let e=[],t=pa();e.push({language:"catalog",ok:t.some(o=>o.family==="solana")&&t.some(o=>o.family==="bitcoin"),templates:t.map(o=>o.id)});let n=await ma({templateId:"solana-safe-vault",projectName:"eval_vault",network:"devnet",authority:dH,programId:pH,unlockDelaySlots:1200});e.push({language:"Rust / Anchor",templateId:"solana-safe-vault",ok:n.oraclePrepared===!0&&n.signingReady===!1&&n.broadcastReady===!1&&n.firmAudit===!1,artifactHash:n.artifactHash});let r=await ma({templateId:"bitcoin-tapscript-vault",projectName:"eval_treasury",network:"signet",threshold:2,signerPubkeys:[mH,fH],recoveryPubkey:hH,recoveryDelayBlocks:144});return e.push({language:"Miniscript / Tapscript",templateId:"bitcoin-tapscript-vault",ok:r.oraclePrepared===!0&&r.psbtPrepared===!1&&r.broadcastReady===!1&&r.firmAudit===!1,artifactHash:r.artifactHash}),e}async function vH(){let e=yH(),t=bH(),n=await wH(),r=[...e,...t,...n],o=r.filter(a=>a.ok!==!0&&a.skipped!==!0).length,i=r.filter(a=>a.skipped===!0).length;return{ok:o===0,total:r.length,pass:r.length-o-i,fail:o,skipped:i,languages:["Solidity","Rust / Anchor","Miniscript / Tapscript"],firmAudit:!1,cases:r}}var lH,uH,dH,pH,mH,fH,hH,xH,qC=G(()=>{Jc();el();Xm();Vm();lH=Kc("protocols/templates",import.meta.url),uH=[/\bselfdestruct\s*\(/i,/\bdelegatecall\s*\(/i,/\btx\.origin\b/,/\bassembly\s*\{/],dH="4wBqpZM9xaSheZzJSMawUKKwhdpChKbZ5eu5ky4Vigw",pH="6Ckm2BrZsQhcNZ6AcXjB9UbcK1jTn1nao3HSBKv5qvWY",mH="031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f",fH="024d4b6cd1361032ca9bd2aeb9d900aa4d45d9ead80ac9423374c451a7254d0766",hH="02531fe6068134503d2723133227c867ac8fa6c83c537e9a44c3c5bdbdcb1fe337";xH=Hn.dirname(cH(import.meta.url))});_r();Cr();pe();import{Interface as py,getAddress as hn,id as EO,isAddress as AO}from"ethers";pe();var QT="08c379a0",ZT="4e487b71",eN=Object.freeze({1:"assertion failed",17:"arithmetic overflow or underflow",18:"division or modulo by zero",33:"invalid enum value",34:"invalid storage byte array encoding",49:"pop() on an empty array",50:"array index out of bounds",65:"out of memory",81:"call to an uninitialized function pointer"});function tN(e){if(!e||e==="0x")return{kind:"empty",reason:"reverted without a reason (often a require with no message, or out of gas)"};let t=String(e).slice(2),n=t.slice(0,8);if(n===QT)try{let r=parseInt(t.slice(72,136),16),o=t.slice(136,136+r*2);return{kind:"revert",reason:Buffer.from(o,"hex").toString("utf8"),selector:`0x${n}`}}catch{return{kind:"revert",reason:"Error(string) payload could not be decoded",selector:`0x${n}`}}if(n===ZT){let r=parseInt(t.slice(8,72),16);return{kind:"panic",code:r,reason:eN[r]||`panic code 0x${r.toString(16)}`,selector:`0x${n}`}}return{kind:"custom",reason:`custom error ${`0x${n}`} (decoding needs the contract ABI)`,selector:`0x${n}`}}function nN(e){let t=[e?.data,e?.error?.data,e?.data?.data,e?.cause?.data,e?.body?.error?.data];for(let o of t){if(typeof o=="string"&&o.startsWith("0x")&&o.length>2)return o;if(typeof o?.data=="string"&&o.data.startsWith("0x")&&o.data.length>2)return o.data}let r=String(e?.message||"").match(/0x[0-9a-fA-F]{72,}/);return r?r[0]:null}function rN(e,t){if(t)return!0;let n=String(e?.message||"").toLowerCase();return!!/execution reverted|revert|invalid opcode|out of gas|stack underflow|insufficient funds for/.test(n)}function oN(e={}){let t={};return e.from&&(t.from=String(e.from).toLowerCase()),e.to&&(t.to=String(e.to).toLowerCase()),e.data&&e.data!=="0x"&&(t.data=e.data),e.value!=null&&String(e.value)!=="0"&&(t.value=`0x${BigInt(e.value).toString(16)}`),t}async function Wn(e={},t={}){let n=t.rpcCall||D,r=Number(e.chainId),o=e.tx||{};if(!Number.isInteger(r))return{status:"error",willRevert:null,error:"chainId is required"};if(!o.to||!/^0x[a-fA-F0-9]{40}$/.test(String(o.to)))return{status:"error",willRevert:null,error:"tx.to must be a valid address"};if(o.from&&!/^0x[a-fA-F0-9]{40}$/.test(String(o.from)))return{status:"error",willRevert:null,error:"tx.from must be a valid address"};let i=oN(o),a=[],s=null,c=!1,l=null;try{s=await n(r,"eth_call",[i,"pending"],t)}catch(f){let h=nN(f);if(!rN(f,!!h))return{status:"unavailable",willRevert:null,chainId:r,error:f?.message||"simulation unavailable",notes:["could not reach the node; this is NOT evidence the transaction would fail"]};c=!0,l=tN(h),h||(l.reason="execution reverted (node did not return a reason payload)",l.kind="revert-no-data")}if(c)return{status:"ok",willRevert:!0,chainId:r,revert:l,summary:`would REVERT: ${l.reason}`,notes:["simulated against current chain state; signing this now would burn gas and fail"]};let u=null,d=null;if(e.estimateGas!==!1)try{let f=await n(r,"eth_estimateGas",[i,"pending"],t);u=BigInt(f);let h=BigInt(Math.max(0,Math.floor(e.gasBufferPercent??20)));d=u+u*h/100n,a.push(`gasLimit includes a ${h}% buffer over the ${u} estimate`)}catch(f){a.push(`gas estimation failed: ${f?.message||"unknown"}`)}a.push("a pass reflects CURRENT chain state \u2014 it is not a guarantee the transaction lands, and in a contested mint the state changes between blocks");let p=`0x${"0".repeat(64)}`,m=s===p;return m&&a.push("call did not revert but returned boolean false \u2014 some ERC-20s (e.g. USDC) signal failure this way instead of reverting"),{status:"ok",willRevert:!1,returnsFalse:m,chainId:r,returnData:s,gasEstimate:u==null?null:u.toString(),gasLimit:d==null?null:d.toString(),summary:m?"executes but returns FALSE \u2014 the contract is rejecting this operation":u?`would succeed, ~${u} gas`:"would succeed",notes:a}}async function pg(e={}){let t=Date.now();try{let n=await Wn({chainId:1,tx:{to:"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",data:`0x70a08231${"0".repeat(64)}`},estimateGas:!1},e),r=n.status==="ok";return{provider:"evm-simulate",status:r?"ok":"degraded",latencyMs:Date.now()-t,detail:r?"eth_call reachable":n.error||"probe failed"}}catch(n){return{provider:"evm-simulate",status:"down",latencyMs:Date.now()-t,detail:n?.message||"probe failed"}}}Cd();Y();var fn=Object.freeze({TRANSACTION:"unsigned-transaction",TYPED_DATA_ORDER:"typed-data-order"}),xO=100,Td={"uniswap-v3":async({chainId:e,tokenIn:t,tokenOut:n,amountIn:r,taker:o},i)=>{let{uniV3PrepareExactIn:a}=await Promise.resolve().then(()=>(_r(),Tu)),s=await a({chainId:e,tokenIn:t,tokenOut:n,amountIn:r,recipient:o},i);return{artifactKind:fn.TRANSACTION,transaction:s.transaction,requiresApproval:s.requiresApproval??null,amountOut:s.quote?.amountOut??null,minOut:s.quote?.amountOutMinimum??null}},"uniswap-v4":async({chainId:e,tokenIn:t,tokenOut:n,amountIn:r,taker:o,slippageBps:i,deadlineSeconds:a,fee:s,tickSpacing:c,hooks:l},u)=>{let{uniV4PrepareExactIn:d}=await Promise.resolve().then(()=>(Cr(),Hu)),p=await d({chainId:e,tokenIn:t,tokenOut:n,amountIn:r,recipient:o,slippageBps:i,deadlineSeconds:a,fee:s,tickSpacing:c,hooks:l},u);return{artifactKind:fn.TRANSACTION,transaction:p.transaction,requiresApproval:p.requiresApproval,amountOut:p.quote?.amountOut??null,minOut:p.quote?.amountOutMinimum??null,prepareReady:!0,executionReady:!1}},lifi:async({chainId:e,tokenIn:t,tokenOut:n,amountIn:r,taker:o},i)=>{let{lifiPrepare:a}=await Promise.resolve().then(()=>(Yo(),nd)),s=await a({fromChain:e,toChain:e,fromToken:t,toToken:n,fromAmount:r,fromAddress:o},i);return{artifactKind:fn.TRANSACTION,transaction:s.transaction,requiresApproval:s.requiresApproval??null,amountOut:s.quote?.estimate?.toAmount??null,minOut:s.quote?.estimate?.toAmountMin??null}},paraswap:async({chainId:e,tokenIn:t,tokenOut:n,amountIn:r,taker:o,decimalsIn:i,decimalsOut:a},s)=>{let{paraswapPrepare:c}=await Promise.resolve().then(()=>(Jo(),ad)),l=await c({chainId:e,srcToken:t,destToken:n,amount:r,srcDecimals:i,destDecimals:a,userAddress:o,side:"SELL"},s);return{artifactKind:fn.TRANSACTION,transaction:l.transaction,requiresApproval:l.requiresApproval??null,amountOut:l.quote?.priceRoute?.destAmount??null,minOut:l.quote?.amountOutMinimum??null}},"0x":async({chainId:e,tokenIn:t,tokenOut:n,amountIn:r,taker:o},i)=>{let{zeroxPrepare:a}=await Promise.resolve().then(()=>(Xo(),ld)),s=await a({chainId:e,sellToken:t,buyToken:n,sellAmount:r,taker:o},i);return{artifactKind:fn.TRANSACTION,transaction:s.transaction,requiresApproval:s.requiresApproval??null,amountOut:s.quote?.buyAmount??null,minOut:s.quote?.minBuyAmount??null}},cow:async({chainId:e,tokenIn:t,tokenOut:n,amountIn:r,taker:o},i)=>{let{cowPrepareOrder:a}=await Promise.resolve().then(()=>(ti(),kd)),s=await a({chainId:e,sellToken:t,buyToken:n,sellAmountBeforeFee:String(r),from:o},i);return{artifactKind:fn.TYPED_DATA_ORDER,typedData:s.typedData,requiresApproval:{token:t,spender:s.vaultRelayer,amount:String(r),note:"CoW pulls funds via the vault relayer, not the settlement contract"},settlement:s.settlement,amountOut:s.quote?.quote?.buyAmount??null,minOut:null,submission:"sign the typed data, then submit the order to the CoW API"}}};var kO=new Set(["0x0000000000000000000000000000000000000000","0x000000000000000000000000000000000000dead","0x0000000000000000000000000000000000000001","0x00000000000000000000000000000000000a1ce5"].map(e=>e.toLowerCase())),SO=/^0x[0-9a-fA-F]{40}$/,IO=Object.freeze(["operation","exactOutput","amountOut","multihop","path","positionManager","modifyLiquidities","commands","actions"]);async function cy(e,t={}){if(IO.some(g=>Object.hasOwn(e,g)))throw new Error("unsupported operation shape is inspect/quote-only");if(e.hookData!=null&&String(e.hookData).toLowerCase()!=="0x")throw new Error("opaque hookData is inspect/quote-only");let{taker:n}=e;if(!n)throw new Error("prepareBestRoute requires taker: a prepared transaction is built FOR an address, and the quote-only placeholder must never end up in one");if(!SO.test(n))throw new Error(`taker must be a valid 20-byte address, got "${n}"`);if(kO.has(n.toLowerCase()))throw new Error(`taker "${n}" is a placeholder/burn address. It is valid for quoting but not for preparing -- that would build a transaction for an address nobody controls. Pass the real wallet that will sign.`);let r=await Pd(e,t);if(!r.best){let g=r.impactRejected??[];return{ok:!1,reason:g.length?g[0].reason:"no source returned a usable route",priceImpactBlocked:g.length>0,impactRejected:g,comparison:r}}let o=e.source||r.best.source,i=r.routes.find(g=>g.source===o);if(!i)return{ok:!1,reason:`source "${o}" did not return a usable route`,comparison:r};let a=Td[o];if(!a){let g=r.routes.find(w=>Td[w.source]&&w.source!==o);return{ok:!1,reason:`${o} won the comparison but has no prepare path in this build. `+(g?`Next preparable route is ${g.source}; pass source:"${g.source}" to use it.`:"No route in this comparison can be prepared."),comparison:r,winner:o}}let s;try{s=await a(e,t)}catch(g){let w=typeof g?.body=="string"?g.body:g?.body?JSON.stringify(g.body):"",x=[String(g?.message||g),w].filter(Boolean).join(" :: "),b=/allowance/i.test(x),y=!b&&/not enough|insufficient|balance/i.test(x),k,E;b?(E="approval-required-first",k=`${o} will not build swap calldata until the token approval exists on-chain. Approve the spender first, then prepare again. Underlying: ${x}`):y?(E="taker-not-funded",k=`${o} refused to build the transaction: ${x}. This venue verifies the taker holds the input token. Quoting works for any address; preparing needs the real funded wallet.`):(E="provider-error",k=`${o} prepare failed: ${x}`);let I=r.routes.find(v=>Td[v.source]&&v.source!==o);return{ok:!1,reason:k,failureKind:E,...I?{alternative:I.source}:{},comparison:r}}let c=e.driftToleranceBps??xO,l=null,u=null;if(s.amountOut!=null&&i.grossOut!=null)try{let g=BigInt(i.grossOut),w=BigInt(s.amountOut);g>0n&&(l=Number((w-g)*10000n/g),l<-c&&(u=`route moved ${(l/100).toFixed(2)}% against you between the comparison and this prepare (tolerance ${(c/100).toFixed(2)}%). The ranking may no longer hold -- re-run the comparison before signing.`))}catch{}let d=r.routes.filter(g=>g.source!==o).map(g=>({source:g.source,netOut:g.netOut,gasUsd:g.gasUsd})),m=r.routes.map(g=>({source:g.source,liquidityUsd:g.liquidityUsd??null})).reduce((g,w)=>Math.max(g,w.liquidityUsd??0),0)||null,f=i.liquidityUsd??null,h=f!=null&&m>0?Math.round(f/m*100):null;return N({ok:!0,chosen:{source:o,wasWinner:o===r.best.source,netOut:i.netOut,grossOut:i.grossOut,gasUsd:i.gasUsd,liquidityUsd:i.liquidityUsd??null},liquidity:{chosenUsd:f,maxUsd:m,sharePct:h},priceImpact:r.priceImpact??null,impactUnmeasured:r.impactUnmeasured??[],...s,unsigned:!0,signedBy:"user-wallet",destination:s.artifactKind===fn.TRANSACTION?s.transaction?.to??null:s.settlement??null,driftBps:l,warnings:[...u?[u]:[],...r.warnings||[],...s.artifactKind===fn.TYPED_DATA_ORDER?["This is an ORDER to sign, not a transaction to broadcast. Signing it authorizes a solver to settle on your behalf."]:[]],runnersUp:d,comparison:{rankedOn:r.rankedOn,sourcesAnswered:r.sourcesAnswered,sourcesTried:r.sourcesTried,improvementBps:r.improvementBps},note:"UNSIGNED. Verify the destination address and minOut against a fresh quote immediately before signing -- a quote-time minimum is not a minimum at broadcast time."},{provider:"router",kind:"best-route"})}Y();var Lr=Object.freeze({1:Object.freeze({name:"ethereum",positionManager:"0xC36442b4a4522E871399CD717aBDD847Ab11FE88",wrappedNative:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",venue:"uniswap-v3",source:"https://docs.uniswap.org/contracts/v3/reference/deployments/ethereum-deployments"}),8453:Object.freeze({name:"base",positionManager:"0x03a520b32C04BF3bEEf7BEb72E919cf822Ed34f1",wrappedNative:"0x4200000000000000000000000000000000000006",venue:"uniswap-v3",source:"https://docs.uniswap.org/contracts/v3/reference/deployments/base-deployments"})}),zt=new py(["function ownerOf(uint256 tokenId) view returns (address)","function positions(uint256 tokenId) view returns (uint96 nonce,address operator,address token0,address token1,uint24 fee,int24 tickLower,int24 tickUpper,uint128 liquidity,uint256 feeGrowthInside0LastX128,uint256 feeGrowthInside1LastX128,uint128 tokensOwed0,uint128 tokensOwed1)","function decreaseLiquidity((uint256 tokenId,uint128 liquidity,uint256 amount0Min,uint256 amount1Min,uint256 deadline) params) payable returns (uint256 amount0,uint256 amount1)","function collect((uint256 tokenId,address recipient,uint128 amount0Max,uint128 amount1Max) params) payable returns (uint256 amount0,uint256 amount1)","function multicall(bytes[] data) payable returns (bytes[] results)"]),_O=new py(["function withdraw(uint256 wad)"]),ly=(1n<<128n)-1n,PO=/^0x[0-9a-fA-F]{64}$/,CO=EO("Transfer(address,address,uint256)").toLowerCase();function $r(e){let t=Number(e),n=Lr[t];if(!n)throw new Error(`lp-exit: unsupported chain ${e}; supported: ${Object.keys(Lr).join(", ")}`);return{chainId:t,...n}}function Jn(e,t){if(!AO(String(e||"")))throw new Error(`lp-exit: ${t} must be a valid address`);return hn(String(e))}function my(e,t){let n;try{n=BigInt(e)}catch{throw new Error(`lp-exit: ${t} must be an unsigned integer`)}if(n<=0n)throw new Error(`lp-exit: ${t} must be positive`);return n}function TO(e){let t=Number(e??50);if(!Number.isInteger(t)||t<1||t>100)throw new Error("lp-exit: slippageBps must be an integer from 1 to 100");return t}function NO(e,t){let n=Number(e.deadlineSeconds??300);if(!Number.isInteger(n)||n<30||n>600)throw new Error("lp-exit: deadlineSeconds must be an integer from 30 to 600");let r=Number(t.nowSeconds??Math.floor(Date.now()/1e3));if(!Number.isInteger(r)||r<=0)throw new Error("lp-exit: invalid current time");return r+n}function uy(e,t){if(e===0n)return 0n;let n=e*BigInt(1e4-t)/10000n;return n>0n?n:1n}function fy(e,t){if(!PO.test(String(e||"")))throw new Error(`lp-exit: valid ${t} transaction hash required`);return String(e).toLowerCase()}async function Nd(e,t,n,r){return(r.rpcCall||D)(e,t,n,r)}function Yn(e,t){return String(e||"").toLowerCase()===String(t||"").toLowerCase()}async function hy(e,t,n,r,o){let[i,a]=await Promise.all([Nd(e,"eth_getTransactionReceipt",[t],r),Nd(e,"eth_getTransactionByHash",[t],r)]),s=i?.status===1||i?.status==="1"||i?.status==="0x1";if(!i||!a||!s||!Yn(i.transactionHash,t)||!Yn(a.hash,t))throw new Error(`lp-exit: live confirmed successful ${o} receipt and transaction required`);if(!Yn(a.from,n.from)||!Yn(a.to,n.to)||!Yn(a.input??a.data,n.data))throw new Error(`lp-exit: ${o} transaction does not match prepared from/to/input`);return{receipt:i,txHash:t}}function gy(e,t,n){let r=new Set(t.map(a=>a.toLowerCase())),o=`0x${n.slice(2).toLowerCase().padStart(64,"0")}`,i=new Map(t.map(a=>[a.toLowerCase(),0n]));for(let a of e.logs||[]){let s=String(a.address||"").toLowerCase();if(!r.has(s)||!Yn(a.topics?.[0],CO)||!Yn(a.topics?.[2],o))continue;let c;try{c=BigInt(a.data)}catch{throw new Error("lp-exit: malformed ERC20 Transfer amount in receipt")}c>0n&&i.set(s,i.get(s)+c)}return i}function yy(e,t,n){if(Su(e,{providers:["lp-exit"],label:"lp-exit continuation",nowMs:n.nowMs??(n.nowSeconds==null?Date.now():Number(n.nowSeconds)*1e3)}),e.phase!==t)throw new Error(`lp-exit: ${t} prepared artifact required`)}async function dy(e,t,n,r){return(r.rpcCall||D)(e,"eth_call",[{to:t,data:n},"latest"],r)}async function Od(e,t,n,r){let i=await(n.simulateTransaction||Wn)({chainId:e,tx:t},n);if(i?.status==="unavailable"||i?.willRevert==null)throw new Error(`lp-exit: ${r} simulation unavailable; refusing unsigned transaction`);if(i?.status!=="ok"||i?.willRevert){let a=i?.revert?.reason||i?.error||"would revert";throw new Error(`lp-exit: ${r} simulation failed: ${a}`)}return i}async function Rd(e={},t={}){if(Object.hasOwn(e,"positionManager"))throw new Error("lp-exit: positionManager is not accepted from callers; the reviewed registry is authoritative");let n=$r(e.chainId),r=Jn(e.owner,"owner"),o=my(e.tokenId,"tokenId"),i=hn(n.positionManager),[a,s]=await Promise.all([dy(n.chainId,i,zt.encodeFunctionData("ownerOf",[o]),t),dy(n.chainId,i,zt.encodeFunctionData("positions",[o]),t)]),c=hn(zt.decodeFunctionResult("ownerOf",a)[0]);if(c!==r)throw new Error(`lp-exit: owner mismatch; position ${o} belongs to ${c}`);let l=zt.decodeFunctionResult("positions",s);return Object.freeze({chainId:n.chainId,chain:n.name,venue:n.venue,positionManager:i,registrySource:n.source,tokenId:o.toString(),owner:r,operator:hn(l[1]),token0:hn(l[2]),token1:hn(l[3]),fee:Number(l[4]),tickLower:Number(l[5]),tickUpper:Number(l[6]),liquidity:l[7].toString(),tokensOwed0:l[10].toString(),tokensOwed1:l[11].toString()})}async function by(e={},t={}){if(Object.hasOwn(e,"positionManager"))throw new Error("lp-exit: positionManager is not accepted from callers; the reviewed registry is authoritative");let n=await Rd(e,t),r=$r(n.chainId),o=BigInt(n.liquidity);if(o<=0n)throw new Error("lp-exit: position has no active liquidity; collect-only exits are not yet supported");let i=e.liquidity==null?o:my(e.liquidity,"liquidity");if(i>o)throw new Error("lp-exit: requested liquidity exceeds live position liquidity");let a=TO(e.slippageBps),s=NO(e,t),c=zt.encodeFunctionData("decreaseLiquidity",[{tokenId:BigInt(n.tokenId),liquidity:i,amount0Min:0n,amount1Min:0n,deadline:s}]),l={chainId:n.chainId,from:n.owner,to:n.positionManager,data:c,value:"0"},u=await Od(n.chainId,l,t,"amount probe");if(!u.returnData||u.returnData==="0x")throw new Error("lp-exit: amount probe simulation returned no amounts");let d,p;try{[d,p]=zt.decodeFunctionResult("decreaseLiquidity",u.returnData)}catch{throw new Error("lp-exit: amount probe simulation returned malformed amounts")}if(d===0n&&p===0n)throw new Error("lp-exit: live removal currently returns zero assets");let m=uy(d,a),f=uy(p,a),h=zt.encodeFunctionData("decreaseLiquidity",[{tokenId:BigInt(n.tokenId),liquidity:i,amount0Min:m,amount1Min:f,deadline:s}]),g=zt.encodeFunctionData("collect",[{tokenId:BigInt(n.tokenId),recipient:n.owner,amount0Max:ly,amount1Max:ly}]),w=zt.encodeFunctionData("multicall",[[h,g]]),x={chainId:n.chainId,from:n.owner,to:n.positionManager,data:w,value:"0"},b=await Od(n.chainId,x,t,"guarded remove-and-collect");return N({provider:"lp-exit",phase:"remove-and-collect",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:n.chainId,deadline:s,position:n,liquidity:i.toString(),slippageBps:a,expected:{amount0:d.toString(),amount1:p.toString()},minimums:{amount0Min:m.toString(),amount1Min:f.toString()},transaction:x,simulation:b,continuation:{operation:"prepareLpSettlementToWrappedNative",requiresConfirmedReceipt:!0,requiresTransferProofFor:[n.token0,n.token1],note:"Re-read the mined transaction and receipt; only token Transfer logs to the bound owner are settlement evidence."}},{provider:"lp-exit",kind:"univ3-remove-and-collect",nowMs:t.nowMs??Number(t.nowSeconds??Math.floor(Date.now()/1e3))*1e3,expiresAtMs:s*1e3})}async function wy(e={},t={}){let n=e.removalPrepared;yy(n,"remove-and-collect",t);let r=$r(n.chainId),o=Jn(n.position?.owner,"prepared owner");if(e.chainId!=null&&Number(e.chainId)!==r.chainId)throw new Error("lp-exit: chainId does not match prepared removal");if(e.owner!=null&&Jn(e.owner,"owner")!==o)throw new Error("lp-exit: owner does not match prepared removal");let i=fy(e.removalTxHash,"removal"),{receipt:a}=await hy(r.chainId,i,n.transaction,t,"removal"),s=hn(r.wrappedNative),c=[Jn(n.position.token0,"prepared token0"),Jn(n.position.token1,"prepared token1")],l=gy(a,c,o),u=c.map(f=>({token:f,amount:l.get(f.toLowerCase()).toString()})).filter(f=>BigInt(f.amount)>0n);if(u.length===0)throw new Error("lp-exit: removal receipt proves no token transfers to prepared owner");let d=0n,p=[],m=t.prepareBestRoute||cy;for(let f of u){if(f.token===s){d+=BigInt(f.amount);continue}let h=await m({chainId:r.chainId,tokenIn:f.token,tokenOut:s,amountIn:f.amount,taker:o,maxSlippageBps:e.maxSlippageBps??100},t);if(!h?.ok||!h?.transaction)throw new Error(`lp-exit: no preparable net route for ${f.token}: ${h?.reason||"unknown failure"}`);p.push(Object.freeze({tokenIn:f.token,amountIn:f.amount,...h}))}return N({provider:"lp-exit",phase:"settle-to-wrapped-native",chainId:r.chainId,owner:o,removalTxHash:i,removalPrepareHash:n.prepareHash,position:n.position,wrappedNative:s,alreadyWrappedNative:d.toString(),routes:Object.freeze(p),warnings:Object.freeze(p.filter(f=>f.comparison?.rankedOn==="gross").map(f=>`${f.tokenIn} route ranked on gross output; gas was not accounted for`)),continuation:Object.freeze({operation:"prepareLpUnwrapNative",requiresConfirmedSwapReceipts:p.length>0,requiresWrappedNativeTransferProof:p.length>0,note:"Match every mined swap to its prepared route and derive wrapped-native received from Transfer logs before unwrapping."})},{provider:"lp-exit",kind:"univ3-settlement-routes",nowMs:t.nowMs??Date.now(),expiresAtMs:n.expiresAt})}async function vy(e={},t={}){let n=e.settlementPrepared;yy(n,"settle-to-wrapped-native",t);let r=$r(n.chainId),o=Jn(n.owner,"prepared owner");if(e.chainId!=null&&Number(e.chainId)!==r.chainId)throw new Error("lp-exit: chainId does not match prepared settlement");if(e.owner!=null&&Jn(e.owner,"owner")!==o)throw new Error("lp-exit: owner does not match prepared settlement");let i=e.swapTxHashes??[];if(!Array.isArray(i)||i.length!==n.routes.length)throw new Error("lp-exit: one live swap transaction hash required for every prepared route");let a=hn(r.wrappedNative),s=BigInt(n.alreadyWrappedNative),c=[];for(let p=0;p<n.routes.length;p+=1){let m=fy(i[p],"swap"),{receipt:f}=await hy(r.chainId,m,n.routes[p].transaction,t,`swap ${p+1}`),h=gy(f,[a],o).get(a.toLowerCase());if(h<=0n)throw new Error(`lp-exit: swap ${p+1} receipt proves no wrapped-native transfer to owner`);s+=h,c.push(m)}if(s<=0n)throw new Error("lp-exit: no receipt-proven wrapped-native amount to unwrap");let l=_O.encodeFunctionData("withdraw",[s]),u={chainId:r.chainId,from:o,to:a,data:l,value:"0"},d=await Od(r.chainId,u,t,"wrapped-native unwrap");return N({provider:"lp-exit",phase:"unwrap-native",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:r.chainId,owner:o,swapTxHashes:c,settlementPrepareHash:n.prepareHash,nativeAmount:s.toString(),transaction:u,simulation:d,note:"UNSIGNED. The user's wallet must sign; Oracle does not broadcast or custody the native asset."},{provider:"lp-exit",kind:"wrapped-native-withdraw",nowMs:t.nowMs??Date.now(),expiresAtMs:n.expiresAt})}async function xy(){return Object.entries(Lr).map(([e,t])=>({chainId:Number(e),...t}))}async function ky(e={},t={}){let n=e.chainId==null?Object.keys(Lr).map(o=>$r(o)):[$r(e.chainId)],r=await Promise.all(n.map(async o=>{try{let i=await Nd(o.chainId,"eth_getCode",[o.positionManager,"latest"],t),a=typeof i=="string"&&/^0x[0-9a-fA-F]+$/.test(i)&&i!=="0x";return{chainId:o.chainId,positionManager:o.positionManager,ok:a}}catch(i){return{chainId:o.chainId,positionManager:o.positionManager,ok:!1,error:String(i?.message||i)}}}));return{ok:r.every(o=>o.ok),chains:r}}R();vt();Y();import{readFileSync as BO,existsSync as MO}from"node:fs";import{getAddress as UO,Interface as Ps,TypedDataEncoder as Md,parseUnits as FO}from"ethers";var RO=/^(0|[1-9][0-9]*)$/,Ld=class extends Error{constructor(t){super(`nft gas-war limit: ${t.reason}`),this.name="NftGasWarLimitError",this.verdict=t}};function Xn(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(!RO.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 LO(e){let t=Number(e);if(!Number.isSafeInteger(t)||t<=0)throw new Error("chainId must be a positive integer");return t}function $O(e={}){return e.maxFeePerGas!=null?Xn(e.maxFeePerGas,"maxFeePerGas"):e.gasPrice!=null?Xn(e.gasPrice,"gasPrice"):null}function $d(e={}){try{let t=LO(e.chainId??e.tx?.chainId),n=e.tx||e,r=e.policy||e,o=r.grant?.maxGasWei??e.grant?.maxGasWei,i=Xn(r.maxTotalGasWei??r.maxGasWei??o,"maxTotalGasWei"),a=Xn(n.gasLimit??n.gas,"gasLimit"),s=$O(n);if(s==null)throw new Error("maxFeePerGas or gasPrice required");let c=Xn(r.maxFeePerGasWei,"maxFeePerGasWei",{required:!1}),l=Xn(r.maxPriorityFeePerGasWei,"maxPriorityFeePerGasWei",{required:!1}),u=n.maxPriorityFeePerGas==null?null:Xn(n.maxPriorityFeePerGas,"maxPriorityFeePerGas"),d=a*s;return d>i?{ok:!1,status:"BLOCK",reason:`total gas ${d} exceeds cap ${i}`,chainId:t,totalGasWei:d.toString(),maxTotalGasWei:i.toString()}:c!=null&&s>c?{ok:!1,status:"BLOCK",reason:`unit fee ${s} exceeds cap ${c}`,chainId:t,unitFeeWei:s.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:s.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 Sy(e={}){let t=$d(e);if(!t.ok)throw new Ld(t);return t}var DO="https://api.opensea.io/api/v2",qO="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)",HO=new Ps([`function ${qO}`]),_s=new Ps(["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"]),jO=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"]),zO=new Set(jO),Cy=new Set(["solana","flow"]),ri="0x0000000000000000000000000000000000000000";function VO(){let e=process.env.OPENSEA_ENV_FILE||`${process.env.HOME||""}/.config/locals-only/opensea.env`;if(!MO(e))return"";try{for(let t of BO(e,"utf8").split(`
|
|
145
|
-
`)){let n=t.match(/^\s*OPENSEA_API_KEY\s*=\s*(.+)\s*$/);if(n)return n[1].replace(/^["']|["']$/g,"").trim()}}catch{}return""}function Vt(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||VO()}function Ty(e={}){return Ae({provider:"opensea",defaultUrl:DO,hosts:["api.opensea.io","testnets-api.opensea.io"],url:e.baseUrl||process.env.OPENSEA_API_URL})}function Qn(e={}){return Ty(e).baseUrl}function Zn(e={}){return Ie({accept:"application/json"},{"x-api-key":Vt(e)},Ty(e).trusted)}function Ny(e){let t=String(e||"ethereum").trim().toLowerCase();if(!zO.has(t))throw new Error(`opensea: unsupported account chain ${t}`);return t}function Z(e,t="address"){try{return UO(String(e||"").trim().toLowerCase())}catch{throw new Error(`opensea: invalid ${t}`)}}function Oy(e,t=null){let n=String(e||"").trim();if(!n)throw new Error("opensea: account address required");if(t&&!Cy.has(t)||!t&&/^0x[0-9a-fA-F]{40}$/.test(n))return Z(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 WO(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 GO(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 Iy(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 KO(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,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"}}}async function Ry(e={}){if(!Vt(e))return{ok:!1,configured:!1,error:"OPENSEA_API_KEY not set"};try{let t=await ii("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 ii(e,t={}){if(!e)throw new Error("collection slug required");if(!Vt(t))throw new Error("OPENSEA_API_KEY required");return S(`${Qn(t)}/collections/${encodeURIComponent(e)}`,{headers:Zn(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function Ly(e,t={}){let n=await ii(e,t),r=n.stats||n.total||{},o=n.floor_price??n.floorPrice??r.floor_price??r.floorPrice??null;return{slug:n.collection||e,name:n.name||null,floor:o,totalSupply:n.total_supply??r.total_supply??null,numOwners:n.num_owners??r.num_owners??null,raw:{contracts:n.contracts,fees:n.fees,category:n.category}}}async function ai(e={},t={}){if(!Vt(t))throw new Error("OPENSEA_API_KEY required");let n=Ny(e.chain),r=Oy(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),a=[],s=e.next?String(e.next):null,c=0;do{let l=new URL(`${Qn(t)}/chain/${encodeURIComponent(n)}/account/${encodeURIComponent(r)}/nfts`);l.searchParams.set("limit",String(o)),e.collection&&l.searchParams.set("collection",String(e.collection)),s&&l.searchParams.set("next",s);let u=await S(l.toString(),{headers:Zn(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4});for(let d of Array.isArray(u?.nfts)?u.nfts:[])a.push(KO(d,n,r));s=u?.next?String(u.next):null,c+=1}while(s&&c<i);return{provider:"opensea-nft",source:"opensea-account-inventory",chain:n,owner:r,count:a.length,pages:c,complete:!s,next:s,nfts:a,exec:!1,readOnly:!0}}async function Cs(e={},t={}){if(!Vt(t))throw new Error("OPENSEA_API_KEY required");let n=Oy(e.address||e.owner),r=await S(`${Qn(t)}/account/${encodeURIComponent(n)}/pnl`,{headers:Zn(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}}var Ts=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});function si(e){let t=String(e||"").trim().toLowerCase(),n=Ts[t];if(!n)throw new Error(`opensea: unsupported EVM chain ${t||"(missing)"}`);return{chain:t,chainId:n}}function Ge(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 YO(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 oi(e){let t=String(e??"").trim();if(!/^\d+$/.test(t))throw new Error("opensea: tokenId must be an unsigned integer string");return t}function $y(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 By(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 JO(e){return!!e&&typeof e=="object"&&[0,1].includes(Number(e.itemType))}function XO(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=Z(e?.token,t);if(n===0&&r!==ri)throw new Error(`opensea: ${t} native payment item must use the zero address`);if(n===1&&r===ri)throw new Error(`opensea: ${t} ERC20 payment item must name a non-zero token contract`);return r}function QO(e,t){let n=Ge(e?.startAmount,`${t} startAmount`),r=Ge(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 Bd(e,t,{required:n=!0}={}){let r=(Array.isArray(e)?e:[]).filter(JO);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 a of r){let s=XO(a,`${t} payment token`);if(o==null)o=s;else if(s!==o)throw new Error(`opensea: ${t} mixes more than one payment token`);i+=QO(a,`${t} payment amount`)}return{paymentToken:o,totalWei:i,count:r.length}}var ZO=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"}]});function nt(e,t){let n=String(e??"").trim();if(!/^\d+$/.test(n))throw new Error(`opensea: ${t} must be an unsigned integer`);return n}function Ey(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 My(e,t){return{itemType:Number(nt(e?.itemType,`${t} itemType`)),token:Z(e?.token,`${t} token`),identifierOrCriteria:nt(e?.identifierOrCriteria,`${t} identifierOrCriteria`),startAmount:nt(e?.startAmount,`${t} startAmount`),endAmount:nt(e?.endAmount,`${t} endAmount`)}}function eR(e,t){return{...My(e,t),recipient:Z(e?.recipient,`${t} recipient`)}}function tR(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:Z(e.offerer,`${t} offerer`),zone:Z(e.zone,`${t} zone`),offer:n.map((o,i)=>My(o,`${t} offer[${i}]`)),consideration:r.map((o,i)=>eR(o,`${t} consideration[${i}]`)),orderType:Number(nt(e.orderType,`${t} orderType`)),startTime:nt(e.startTime,`${t} startTime`),endTime:nt(e.endTime,`${t} endTime`),zoneHash:Ey(e.zoneHash,`${t} zoneHash`),salt:nt(e.salt,`${t} salt`),conduitKey:Ey(e.conduitKey,`${t} conduitKey`),counter:nt(e.counter,`${t} counter`)}}function Uy(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=tR(t,n);if(Md.hashStruct("OrderComponents",ZO,o).toLowerCase()!==r)throw new Error(`opensea: ${n} order hash does not match its canonical Seaport parameters`);return r}function Fy(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=Z(e?.token,`${t} contract`),o=oi(e?.identifierOrCriteria),i=Ge(e?.startAmount,`${t} startAmount`,{positive:!0}),a=Ge(e?.endAmount??e?.startAmount,`${t} endAmount`,{positive:!0});if(i!==a)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 nR(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 Fy(r[0],`${t} offer NFT`)}function rR(e,t,n){let r=Array.isArray(e?.consideration)?e.consideration:[];if(r.some(a=>[4,5].includes(Number(a?.itemType))))throw new Error(`opensea: ${n} uses a criteria consideration item, not a fixed token`);let o=r.filter(a=>[2,3].includes(Number(a?.itemType)));if(o.length!==1)throw new Error(`opensea: ${n} must require exactly one fixed ERC-721 or ERC-1155 consideration item`);let i=Fy(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 oR(e,t,n,r){if(!(!e||typeof e!="object")){if(e.contract!=null&&String(e.contract).trim()!==""&&Z(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 iR(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 Dy(e,t,n,r){let o=nt(t?.startTime,`${r} startTime`),i=nt(t?.endTime,`${r} endTime`),a=BigInt(Math.floor(n/1e3));if(BigInt(o)>a)throw new Error(`opensea: ${r} canonical startTime is in the future`);if(BigInt(i)<=a)throw new Error(`opensea: ${r} canonical endTime is expired or stale`);let s=By(i,n,`${r} expiry`),c=e?.expiration_time??e?.expirationTime;if(c!=null&&String(c).trim()!==""&&iR(c)!==Number(i))throw new Error(`opensea: ${r} display expiry disagrees with the canonical order endTime`);return s}function aR(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(Ts[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,a=nR(i,"listing"),s=a.contract;if(t.contract&&s!==t.contract)throw new Error("opensea: OpenSea returned a listing for the wrong contract");let c=a.tokenId;oR(e.asset,s,c,"listing");let l=Ge(e.price?.current?.value,"listing price",{positive:!0}),u=Uy(e,i,"listing"),d=Bd(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:Z(e.protocol_address,"listing protocol address"),contract:s,tokenId:c,quantity:a.quantity,priceWei:l.toString(),paymentToken:d.paymentToken,currency:String(e.price?.current?.currency||"").trim()||null,decimals:Number(e.price?.current?.decimals??18),expiry:Dy(e,i,n,"listing"),counter:nt(i?.counter,"listing counter")}}async function Ud(e={},t={}){if(!Vt(t))throw new Error("OPENSEA_API_KEY required");let n=si(e.chain);n.contract=e.contract?Z(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(`${Qn(t)}/listings/collection/${encodeURIComponent(r)}/best`);i.searchParams.set("limit",String(o)),e.next&&i.searchParams.set("next",String(e.next));let a=await S(i.toString(),{headers:Zn(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),s=Array.isArray(a?.listings)?a.listings:[];if(!s.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:s.map(l=>aR(l,n,c)),next:a?.next?String(a.next):null,exec:!1,readOnly:!0}}async function Ns(e={},t={}){let n=oi(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 a=1;a<=r;a+=1){let s=await Ud({...e,tokenId:void 0,limit:50,next:o},t),c=s.listings.find(l=>l.tokenId===n);if(c)return{provider:"opensea-nft",source:"opensea-best-exact-listing",...c,pagesScanned:a,exact:!0,exec:!1,readOnly:!0};if(!s.next||i.has(s.next))break;i.add(s.next),o=s.next}throw new Error("opensea: no active exact NFT listing returned within page bound")}function sR(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||{},s=rR(i,n,"offer").contract;if(t.contract&&s!==t.contract)throw new Error("opensea: OpenSea returned an offer for the wrong contract");let c=Ge(e.price?.current?.value??e.price?.value,"offer value",{positive:!0}),l=Bd(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=Bd(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(),m=(c-d.totalWei).toString();return{provider:"opensea-nft",source:"opensea-best-exact-offer",orderHash:Uy(e,i,"offer"),chain:t.chain,chainId:t.chainId,protocolAddress:Z(e.protocol_address,"offer protocol address"),contract:s,tokenId:n,grossOfferWei:c.toString(),sellerNetWei:m,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:Dy(e,i,r,"offer"),counter:nt(i.counter,"offer counter"),exec:!1,readOnly:!0}}async function Os(e={},t={}){if(!Vt(t))throw new Error("OPENSEA_API_KEY required");let n=si(e.chain);n.contract=e.contract?Z(e.contract,"NFT contract"):null;let r=String(e.slug||"").trim();if(!r)throw new Error("opensea: collection slug required");let o=oi(e.tokenId),i=await S(`${Qn(t)}/offers/collection/${encodeURIComponent(r)}/nfts/${encodeURIComponent(o)}/best`,{headers:Zn(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),a=i?.offer||(Array.isArray(i?.offers)?i.offers[0]:i);if(!a)throw new Error("opensea: no active exact NFT offer returned");let s=Number.isFinite(Number(t.nowMs))?Number(t.nowMs):Date.now();return sR(a,n,o,s)}function cR(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 qy(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"&&qy(n))}function Hy(e){return!e||typeof e!="object"?!1:Object.keys(e).some(t=>/^(?:signed.*|rawtransaction|serializedtransaction|txsigned|r|s|v)$/i.test(t))}function jy(e){return!e||typeof e!="object"?!1:Hy(e)?!0:Object.values(e).some(t=>t&&typeof t=="object"&&jy(t))}function zy(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"&&zy(o,t,n);return t}function Ay(e){return e&&typeof e=="object"&&typeof e.value=="string"?e.value:e}function Vy(e,{buyer:t,chainId:n,targets:r}){if(!e||typeof e!="object")throw new Error("opensea: transaction object required");if(Hy(e))throw new Error("opensea: signed transaction material refused");if((e.from?Z(Ay(e.from),"transaction buyer"):t)!==t)throw new Error("opensea: OpenSea returned a transaction for the wrong buyer");let i=Z(Ay(e.to??e.target),"transaction target");if(!r.has(i))throw new Error("opensea: OpenSea returned a transaction for the wrong target");let a=e.data??e.calldata,s=e.input_data&&typeof e.input_data=="object"?e.input_data:e.input&&typeof e.input=="object"?e.input:null;if(a==null&&s){if(!String(e.function||"").replace(/^function\s+/,"").startsWith("fulfillAdvancedOrder("))throw new Error("opensea: only exact Seaport fulfillAdvancedOrder preparation is accepted");a=HO.encodeFunctionData("fulfillAdvancedOrder",[s.advancedOrder,s.criteriaResolvers,s.fulfillerConduitKey,s.recipient])}let c=String(a??"").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=YO(e.value_hex??e.valueHex??e.value??0);return{from:t,to:i,data:c,value:d.hex,chainId:n,valueWei:d.amount}}function Rs(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 Fd(e,t,n){let r=n.provider,o=!!n.rpcUrl;if(!r&&!o)return{simulated:!1,gasEstimates:[]};let i=await ve(e,4,async c=>{let{chainId:l,...u}=Rs(c);if(r){if(typeof r.call!="function"||typeof r.estimateGas!="function")throw new Error("opensea: supplied provider must implement call and estimateGas");let[,f]=await Promise.all([r.call(u),r.estimateGas(u)]);return BigInt(f).toString()}let{rpcCall:d}=await Promise.resolve().then(()=>(pe(),za)),p={...n,fetchImpl:n.rpcFetchImpl||n.fetchImpl},[,m]=await Promise.all([d(t,"eth_call",[u,"pending"],p),d(t,"eth_estimateGas",[u],p)]);return BigInt(m).toString()}),a=null,s=null;if(r&&typeof r.getFeeData=="function"){let c=await r.getFeeData();s=c?.maxPriorityFeePerGas==null?0n:BigInt(c.maxPriorityFeePerGas),a=c?.maxFeePerGas==null?c?.gasPrice==null?null:BigInt(c.gasPrice):BigInt(c.maxFeePerGas)}else if(o){let{rpcCall:c}=await Promise.resolve().then(()=>(pe(),za)),l={...n,fetchImpl:n.rpcFetchImpl||n.fetchImpl},u=BigInt(await c(t,"eth_gasPrice",[],l));try{s=BigInt(await c(t,"eth_maxPriorityFeePerGas",[],l))}catch{s=0n}let d=await c(t,"eth_getBlockByNumber",["pending",!1],l),m=(d?.baseFeePerGas==null?0n:BigInt(d.baseFeePerGas))*2n+s;a=u>m?u:m}return a!=null&&s!=null&&e.forEach((c,l)=>{let d=(BigInt(i[l])*120n+99n)/100n;c.gasLimit=d.toString(),c.maxPriorityFeePerGas=s.toString(),c.maxFeePerGas=a.toString(),c.worstCaseFeeWei=(d*a).toString()}),{simulated:!0,gasEstimates:i}}function lR(e,t){if(qy(e))throw new Error("opensea: approval steps are not permitted in NFT buy, sweep, or mint preparation");if(jy(e))throw new Error("opensea: signed transaction material refused");let n=zy(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=>Vy(r,t))}function uR(e,t,n={}){return N({...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 Wy(e={},t={}){throw new Error("opensea: public buy preparation disabled until canonical Seaport calldata is independently decoded and fully bound")}async function Gy(e={},t={}){throw new Error("opensea: public buy preparation disabled until canonical Seaport calldata is independently decoded and fully bound")}function dR(e,t,n){let o=(Array.isArray(e?.contracts)?e.contracts:[]).find(a=>String(a?.chain||t).toLowerCase()===t&&a?.address);if(!o)throw new Error("opensea: collection response contains no contract for requested chain");let i=Z(o.address,"collection NFT contract");if(i!==n)throw new Error("opensea: OpenSea returned the wrong collection contract");return i}async function Ls(e={},t={}){if(!Vt(t))throw new Error("OPENSEA_API_KEY required");cR(e);let{chain:n,chainId:r}=si(e.chain),o=Z(e.buyer||e.minter||e.address,"buyer"),i=Z(e.contract,"NFT contract"),a=$y(e.quantity),s=Ge(e.priceWei,"priceWei"),c=Ge(e.maxTotalWei,"maxTotalWei"),l=Number.isFinite(Number(t.nowMs))?Number(t.nowMs):Date.now(),u=By(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 ii(d,t),m=dR(p,n,i),f=s*BigInt(a);if(f>c)throw new Error("opensea: mint total exceeds total cap");let h=await S(`${Qn(t)}/drops/${encodeURIComponent(d)}/mint`,{method:"POST",headers:Zn(t),body:{minter:o,quantity:a},fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??25e3,retries:0,dedupe:!1}),g=t.allowedMintTargets?.[n]??t.allowedMintTargets?.[r]??e.mintTarget,w=Array.isArray(g)?g:g?[g]:[];if(!w.length)throw new Error("opensea: reviewed SeaDrop mintTarget required");let x=new Set(w.map(O=>Z(O,"SeaDrop mint target"))),b=lR(h,{buyer:o,chainId:r,targets:x});if(b.length!==1)throw new Error("opensea: mint must contain exactly one SeaDrop transaction");let y,k,E=null,I;try{y=_s.decodeFunctionData("mintPublic",b[0].data),k="public",I=_s.encodeFunctionData("mintPublic",[y[0],y[1],y[2],y[3]])}catch{try{y=_s.decodeFunctionData("mintAllowList",b[0].data),k="allowlist";let O=y[4],H=[...y[5]].map(String);if(H.length<1||H.length>64||H.some(ue=>!/^0x[0-9a-fA-F]{64}$/.test(ue)))throw new Error("opensea: allowlist mint requires a bounded canonical Merkle proof");let B=BigInt(O.startTime),z=BigInt(O.endTime),le=BigInt(Math.floor(l/1e3));if(B>le||z<=le)throw new Error("opensea: allowlist mint stage is not open");if(BigInt(O.mintPrice)!==s)throw new Error("opensea: allowlist stage price does not match exact approved price");if(BigInt(O.maxTotalMintableByWallet)<BigInt(a))throw new Error("opensea: allowlist wallet cap is below requested quantity");I=_s.encodeFunctionData("mintAllowList",[y[0],y[1],y[2],y[3],O,H]),E={mintPrice:BigInt(O.mintPrice).toString(),maxTotalMintableByWallet:BigInt(O.maxTotalMintableByWallet).toString(),startTime:B.toString(),endTime:z.toString(),dropStageIndex:BigInt(O.dropStageIndex).toString(),maxTokenSupplyForStage:BigInt(O.maxTokenSupplyForStage).toString(),feeBps:Number(O.feeBps),restrictFeeRecipients:!!O.restrictFeeRecipients,proof:H}}catch(O){throw/opensea:/.test(String(O?.message||""))?O:new Error("opensea: mint transaction must call reviewed SeaDrop mintPublic or mintAllowList")}}let v=Z(y[0],"mint NFT contract"),A=Z(y[1],"mint fee recipient"),P=Z(y[2],"mint recipient");if(v!==m)throw new Error("opensea: mint calldata collection mismatch");if(P!==o)throw new Error("opensea: mint calldata recipient mismatch");if(BigInt(y[3])!==BigInt(a))throw new Error("opensea: mint calldata quantity mismatch");if(I.toLowerCase()!==b[0].data.toLowerCase())throw new Error("opensea: mint calldata must be canonical with no suffix");let T=b.reduce((O,H)=>O+H.valueWei,0n);if(T!==f)throw new Error("opensea: mint transaction total does not match exact approved price and quantity");if(T>c)throw new Error("opensea: mint total exceeds total cap");let L=await Fd(b,r,{...t,provider:e.provider||t.provider});if(L.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},q=Sy({chainId:r,tx:b[0],policy:F});return uR({action:"mint",mintType:k,...E?{stage:E}:{},chain:n,chainId:r,slug:d,buyer:o,contract:m,quantity:a,priceWei:s.toString(),totalWei:T.toString(),maxTotalWei:c.toString(),mintTarget:b[0].to,feeRecipient:A,expiry:u,transactions:b.map(Rs),gasWar:q,...L},"nft-mint",{nowMs:l,expiresAtMs:Math.min(l+Ar,Date.parse(u),E?Number(BigInt(E.endTime)*1000n):Number.MAX_SAFE_INTEGER)})}function pR(e={}){let t=Ny(e.chain);if(Cy.has(t))throw new Error("opensea: listing actions currently require an EVM NFT chain");let n=e.startTime||e.start_time?Iy(e.startTime||e.start_time,"startTime"):{text:new Date().toISOString(),ms:Date.now()},r=Iy(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:Z(e.contract,"NFT contract"),token_id:o,quantity:GO(e.quantity??1,"quantity"),price:{amount:WO(e.price?.amount??e.amount??e.priceAmount,"price amount"),currency:Z(e.price?.currency??e.currency??ri,"price currency")},start_time:n.text,end_time:r.text}}var Br={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"}]},_y=new Ps(["function setApprovalForAll(address operator,bool approved)"]),mR=new Ps(["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 Py(e,t){return e?.[t]||(e?.action===t?e:null)}function fR(e,{seller:t,item:n,chainId:r}){let o=Array.isArray(e?.steps)?e.steps:[],i=o.map(b=>Py(b,"createListingsAction")).find(Boolean)||o.find(b=>/createListings/i.test(String(b?.action||""))),a=i?.signatureRequest?.message??i?.typedData,s;try{s=typeof a=="string"?JSON.parse(a):a}catch{throw new Error("opensea: invalid listing typed-data JSON")}if(!s||s.primaryType!=="OrderComponents"||!s.domain||!s.message)throw new Error("opensea: exact Seaport OrderComponents action required");let c=s.domain;if(c.name!=="Seaport"||c.version!=="1.6"||Number(c.chainId)!==r)throw new Error("opensea: listing domain mismatch");let l=Z(c.verifyingContract,"listing protocol"),u=s.message;if(Z(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(Z(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 b of u.consideration){if(Number(b.itemType)!==0||Z(b.token,"listing payment token")!==ri)throw new Error("opensea: executable listings currently require native fixed-price consideration");let y=BigInt(b.startAmount),k=BigInt(b.endAmount);if(y<=0n||y!==k)throw new Error("opensea: listing consideration must be fixed and positive");Z(b.recipient,"listing consideration recipient"),p+=y}let m=FO(n.price.amount,18);if(p!==m)throw new Error("opensea: listing price mismatch");let f=BigInt(Math.floor(Date.parse(n.start_time)/1e3)),h=BigInt(Math.floor(Date.parse(n.end_time)/1e3));if(BigInt(u.startTime)!==f||BigInt(u.endTime)!==h)throw new Error("opensea: listing time bounds mismatch");let g=Md.hashStruct("OrderComponents",Br,u),w=o.map(b=>Py(b,"itemApprovalAction")).find(Boolean)||o.find(b=>/setApprovalForAll/i.test(String(b?.action||""))),x=null;if(w){let b=w.transaction||w.itemApprovalAction?.transaction,y=Vy(b,{buyer:t,chainId:r,targets:new Set([n.contract])}),k;try{k=_y.decodeFunctionData("setApprovalForAll",y.data)}catch{throw new Error("opensea: listing approval must be setApprovalForAll")}let E=Z(k[0],"listing approval operator");if(k[1]!==!0||y.valueWei!==0n)throw new Error("opensea: listing approval must grant one exact operator with zero value");if(_y.encodeFunctionData("setApprovalForAll",[E,!0]).toLowerCase()!==y.data.toLowerCase())throw new Error("opensea: listing approval calldata must be canonical");x={...y,operator:E}}return{protocolAddress:l,typedData:{domain:c,types:Br,primaryType:"OrderComponents",message:u},orderHash:g,priceWei:p,approval:x}}async function $s(e={},t={}){if(!Vt(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=Z(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(pR);if(new Set(o.map(m=>m.chain)).size!==1)throw new Error("opensea: all prepared listing items must be on one chain");let a=e.useCreatorFee!==!1,s={address:n,items:o,use_creator_fee:a};e.taker&&(s.taker=Z(e.taker,"taker"));let c=await S(`${Qn(t)}/listings/actions`,{method:"POST",headers:Zn(t),body:s,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??25e3,retries:0,dedupe:!1}),{chainId:l}=si(o[0].chain),u=fR(c,{seller:n,item:o[0],chainId:l}),d=u.approval?[u.approval]:[],p=d.length?await Fd(d,l,{...t,provider:e.provider||t.provider}):{simulated:!0};return N({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(Rs),useCreatorFee:a,taker:s.taker||null,feeDisclosure:a?"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 Ky(e={},t={}){if(e.userConfirmed!==!0)throw new Error("opensea: userConfirmed=true required for listing cancellation");let{chain:n,chainId:r}=si(e.chain),o=Z(e.seller||e.address||e.owner,"seller"),i=Z(e.protocolAddress,"reviewed Seaport protocol address"),a=Z(e.contract,"NFT contract"),s=oi(e.tokenId),c=$y(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[v,A]of Object.entries(Br)){let P=l.types?.[v];if(!Array.isArray(P)||P.length!==A.length||P.some((T,L)=>T?.name!==A[L].name||T?.type!==A[L].type))throw new Error("opensea: cancellation requires canonical Seaport types")}if(Object.keys(l.types||{}).filter(v=>v!=="EIP712Domain").sort().join(",")!==Object.keys(Br).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=Z(d.verifyingContract,"Seaport cancellation target");if(p!==i)throw new Error("opensea: cancellation target mismatch");let m=l.message;if(Z(m.offerer,"listing seller")!==o)throw new Error("opensea: cancellation seller mismatch");if(!Array.isArray(m.offer)||m.offer.length!==1||!Array.isArray(m.consideration)||!m.consideration.length)throw new Error("opensea: cancellation requires one exact previously prepared listing order");if(Number(m.orderType)!==2)throw new Error("opensea: cancellation requires a FULL_RESTRICTED listing order");let f=m.offer[0];if(![2,3].includes(Number(f.itemType)))throw new Error("opensea: cancellation offer must be ERC721 or ERC1155");if(Z(f.token,"cancellation NFT contract")!==a)throw new Error("opensea: cancellation NFT contract mismatch");if(oi(f.identifierOrCriteria)!==s)throw new Error("opensea: cancellation tokenId mismatch");let h=Ge(f.startAmount,"cancellation offer startAmount",{positive:!0}),g=Ge(f.endAmount,"cancellation offer endAmount",{positive:!0});if(h!==BigInt(c)||g!==BigInt(c))throw new Error("opensea: cancellation quantity mismatch");for(let v of m.consideration){if(Number(v.itemType)!==0||Z(v.token,"cancellation payment token")!==ri)throw new Error("opensea: cancellation requires native fixed-price consideration");let A=Ge(v.startAmount,"cancellation consideration startAmount",{positive:!0}),P=Ge(v.endAmount,"cancellation consideration endAmount",{positive:!0});if(A!==P)throw new Error("opensea: cancellation consideration must be fixed and positive");Z(v.recipient,"cancellation consideration recipient")}let w=Ge(m.startTime,"cancellation startTime");if(Ge(m.endTime,"cancellation endTime",{positive:!0})<=w)throw new Error("opensea: cancellation listing time bounds invalid");let b=Md.hashStruct("OrderComponents",Br,m),y=String(e.orderHash||"").trim().toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(y)||y!==b.toLowerCase())throw new Error("opensea: cancellation order hash mismatch");let k=mR.encodeFunctionData("cancel",[[m]]),E=[{from:o,to:p,data:k,value:"0x0",valueWei:0n,chainId:r}],I=await Fd(E,r,{...t,provider:e.provider||t.provider});if(I.simulated!==!0)throw new Error("opensea: cancellation RPC simulation required");return N({provider:"opensea-nft",marketplace:"opensea",kind:"nft-cancel",action:"cancel-listing",prepareReady:!0,chain:n,chainId:r,seller:o,contract:a,tokenId:s,quantity:c,protocolAddress:p,orderHash:b,typedData:{domain:d,types:Br,primaryType:"OrderComponents",message:m},transactions:E.map(Rs),...I,requiresUserSignature:!0},{provider:"opensea-nft",kind:"nft-cancel"})}Mr();var ui=new Map,SR=Object.keys($e).map(Number),IR=Object.keys(et).map(Number),ER=Object.keys(Lr).map(Number),Kd=tr.map(e=>e.chainId),AR=[...new Set(Object.values(Ts))],Gd=new Set,ob=!1;function ib(e){if(!e||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Object.values(e))ib(t);return Object.freeze(e)}function C(e){if(!e?.id)throw new Error("registerProvider requires id");if(!e.venue)throw new Error("registerProvider requires venue");if(!Array.isArray(e.ops))throw new Error("registerProvider requires ops[]");let t=String(e.id);if(ob&&Gd.has(t))throw new Error(`registerProvider refuses to overwrite built-in provider: ${t}`);return ui.set(t,{chainIds:e.chainIds||[],auth:e.auth||"none",description:e.description||"",baseEnv:e.baseEnv||[],...e,id:t}),ui.get(t)}function Us(e){return ui.get(e)||null}function Fs({venue:e,op:t}={}){let n=[...ui.values()];return e&&(n=n.filter(r=>r.venue===e)),t&&(n=n.filter(r=>r.ops.includes(t))),n}function _R(){Gd.clear();for(let[e,t]of ui)Gd.add(e),ib(t);ob=!0}C({id:"hl-info",venue:"hl",chainIds:[],auth:"none",ops:["health","allMids","l2Book","outcomeMeta","clearinghouse","userFills","meta","metaAndAssetCtxs","candleSnapshot","openOrders","frontendOpenOrders","userState","spotMeta"],baseEnv:["HL_INFO_URL","HL_API_URL"],description:"Hyperliquid public /info"});C({id:"hl-vaults",venue:"hyperliquid-vaults",chainIds:[],auth:"none",ops:["health","summaries","details","userEquities","tracker"],execution:"read-only",baseEnv:["HL_INFO_URL","HL_API_URL"],description:"Read-only Hyperliquid vault summaries, vault details, user vault equities, and HLP tracking."});C({id:"hl-precompiles",venue:"hyperliquid",chainIds:[999],auth:"none",ops:["health","read","l1BlockNumber","markPx","oraclePx","spotPx","position","spotBalance","vaultEquity","withdrawable"],execution:"read-only",baseEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],description:"HyperEVM L1Read precompiles (0x800-0x809). eth_call only. Includes HLP vault equity. No CoreWriter."});C({id:"protocol-templates",venue:"protocol-builder",chainIds:[],auth:"none",ops:["health","list","listNative","gate","prepareDeploy","buildNative","eval"],description:"Gated EVM templates plus deterministic Solana program and Bitcoin policy scaffolds. Native bundles require chain-specific compile, tests, and simulation before any unsigned deploy/funding prepare. NOT a firm audit."});C({id:"poly-public",venue:"poly",chainIds:[137],auth:"none",ops:["health","time","markets","book","midpoint","spread","price","events"],execution:"read-only",baseEnv:["POLY_CLOB_URL","POLY_GAMMA_URL"],description:"Polymarket CLOB + Gamma public REST"});C({id:"poly-clob",venue:"poly",chainIds:[137],auth:"none",ops:["health","prepareOrder"],execution:"prepare",localSignerSurfaces:["poly"],description:"Polymarket CLOB unsigned EIP-712 order prepare plus owner-operated local-signer submit. Hosted/keyless remains prepare-only."});C({id:"hl-delta-neutral",venue:"hyperliquid",chainIds:[],auth:"none",ops:["health","scan","quote","prepare","loop"],execution:"prepare",localSignerSurfaces:["hl"],description:"Hyperliquid funding carry. Armed through the existing hl signer. Hosted/keyless remains prepare-only. Not automated."});C({id:"lighter-delta-neutral",venue:"lighter",chainIds:[],auth:"none",ops:["health","scan","quote","prepare","loop"],execution:"prepare",localSignerSurfaces:["lighter"],description:"Lighter.xyz funding carry. Armed through the official sendTx local-signer. Hosted/keyless remains prepare-only. Not automated."});C({id:"portfolio",venue:"multichain-wallet",chainIds:[1,10,56,137,988,999,2741,4663,8453,42161,43114],auth:"none",ops:["health","balances","snapshot","history","valueGraph"],execution:"read-only",description:"Read-only balance aggregation across configured EVM chains, Solana, Bitcoin, and Hyperliquid, plus profile-local observation snapshots, history, and value graphs with explicit partial coverage."});C({id:"nft-portfolio",venue:"multichain-nft-wallet",chainIds:[1,10,137,988,999,2741,4663,8453,42161,43114],auth:"optionalApiKey",ops:["health","inventory","gallery","pnl","prepareList","traitSnipe"],execution:"prepare",baseEnv:["OPENSEA_API_KEY","MAGICEDEN_API_KEY","SATFLOW_API_KEY"],description:"Normalized EVM, Solana, and Bitcoin NFT inventory, static contact-sheet galleries, explicit PnL coverage, user-confirmed unsigned listing preparation, and evidence-gated trait-snipe buy intents."});C({id:"evm-simulate",venue:"onchain-simulation",chainIds:[1,10,56,137,988,999,2741,4663,8453,42161,43114],auth:"none",ops:["health","simulate"],execution:"read",baseEnv:[],description:"Pre-sign EVM transaction simulation: eth_call at pending state to catch reverts, decoded revert reasons (Error(string), Panic codes, custom-error selectors), and a buffered gas estimate. Distinguishes a genuine revert from an unreachable node \u2014 an infra failure is never reported as 'would fail'. A pass reflects current chain state and is explicitly not a guarantee."});C({id:"nft-mint",venue:"onchain-mint",chainIds:[1,10,56,137,988,999,2741,4663,8453,42161,43114],auth:"none",ops:["health","discover","prepare","priceGas","createTrigger","checkOpen"],execution:"prepare",localSignerSurfaces:["evm-nft"],baseEnv:[],description:"EVM NFT mints: discover the collection's mint entrypoint from bytecode, price a competitive EIP-1559 bid from fee-history percentiles, enforce gas-war caps, surface contract risk, and hand execution to the local signer after explicit arming and bounded grant."});C({id:"universal-mint-router",venue:"universal-nft-mint",chainIds:[],auth:"optionalApiKey",ops:["health","capabilities","prepare"],execution:"prepare",baseEnv:["OPENSEA_API_KEY"],description:"Prepare-only exact universal mint routing across reviewed EVM and Ordinals adapters. Universal Solana mint is RESEARCH_ONLY and disabled until canonical serialized-message decoding ships; the separate Magic Eden marketplace provider is unchanged. It never signs or broadcasts."});C({id:"universal-nft-lifecycle",venue:"universal-nft-lifecycle",chainIds:[],auth:"optionalApiKey",ops:["health","capabilities","route"],execution:"read",baseEnv:["OPENSEA_API_KEY","MAGICEDEN_API_KEY","SATFLOW_API_KEY"],description:"Read-only NFT lifecycle route discovery. It does not prepare, sign, or broadcast artifacts; callers must invoke and review the selected provider operation separately."});for(let[e,t,n]of[["universal-evm-nft-transfer","evm-nft-transfer","Exact unsigned ERC-721/ERC-1155 safeTransferFrom preparation."],["universal-solana-nft-transfer","solana-nft-transfer","Exact unsigned verified Metaplex NFT/Core transfer preparation."],["universal-ordinals-transfer","bitcoin-nft-transfer","Exact unsigned Ordinals PSBT transfer-plan preparation."]])C({id:e,venue:t,chainIds:[],auth:"none",ops:["health","prepare"],execution:"prepare",description:n});C({id:"contract-risk",venue:"onchain-bytecode",chainIds:[1,10,56,137,988,999,2741,4663,8453,42161,43114],auth:"none",ops:["health","scan"],execution:"read",baseEnv:[],description:"Structural contract risk from on-chain bytecode: retained owner powers (mint, blacklist, pause, fee changes) and upgradeability across EIP-1967, legacy zeppelinos, and EIP-1822 proxy slots. Complements behavioural sell simulation. Never reports 'safe' \u2014 a clean scan is weak evidence, not a guarantee."});C({id:"evm-token-sniper",venue:"evm-token-launches",chainIds:Kd,auth:"none",ops:["health","scan"],execution:"prepare",localSignerSurfaces:["evm-swap"],baseEnv:tr.flatMap(e=>e.rpcEnv),description:"One generic EVM token-sniping path across every configured EVM chain: live identity, pools, structural risk, sell simulation, quote, guarded transaction preparation, and local-signer execution handoff. Robinhood Chain is the default, not a special implementation."});C({id:"evm-rpc",venue:"evm",chainIds:[1,137,42161,8453,10,4663,999],auth:"none",ops:["health","healthAll","blockNumber","chainId","getBalance","call","erc20Allowance","erc20Balance","transactionReceipt"],baseEnv:["ETH_RPC_URL","POLYGON_RPC_URL","RH_CHAIN_RPC","BASE_RPC_URL","ARBITRUM_RPC_URL"],description:"EVM JSON-RPC multi-chain (env RPC or public fallbacks)"});C({id:"solana-rpc",venue:"solana",chainIds:[],auth:"none",ops:["health","latestBlockhash","getBalance","tokenAccounts","simulate"],baseEnv:["SOLANA_RPC_URL"],description:"Solana mainnet JSON-RPC read/prepare surface (no key, no signing, no broadcast)"});C({id:"bitcoin-esplora",venue:"bitcoin",chainIds:[],auth:"none",ops:["health","tipHeight","fees","address","utxos","tx","decode"],execution:"read-only",baseEnv:["BTC_ESPLORA_URL","BTC_NETWORK"],description:"Bitcoin L1 via Esplora (mempool.space/Blockstream). Reads only on data plane. User-signed broadcast is bitcoin_send on exec MCP. No Core RPC, no house keys. Wallets: Xverse/UniSat/Leather/OKX/Phantom"});C({id:"bitcoin-meta",venue:"bitcoin-metaprotocol",chainIds:[],auth:"optionalApiKey",ops:["health","runeBalances","inscriptions","inscriptionInfo","inscriptionChildren","ordBlockInfo"],execution:"read-only",baseEnv:["BTC_META_API_URL","UNISAT_API_KEY","BESTINSLOT_API_KEY"],description:"Bitcoin ordinals/runes reads. Keyless tier via ordinals.com recursive (inscriptionInfo/children/blockInfo); address-indexed ops (inscriptions, runeBalances) need a keyed indexer. Hiro is deprecated (410) and Magic Eden BTC is dead \u2014 use satflow for market."});C({id:"satflow",venue:"bitcoin-marketplace",chainIds:[],auth:"apiKey",ops:["health","collectionFloors","collectionStats","item","walletContents","floorListings","preparePurchase","prepareList"],execution:"prepare",localSignerSurfaces:["btc"],baseEnv:["SATFLOW_API_KEY","SATFLOW_API_URL"],description:"Satflow ordinals+runes marketplace (api.satflow.com). Primary BTC NFT market after Magic Eden BTC sunset. PSBT intents for buy/list; key via x-api-key."});C({id:"jupiter",venue:"solana-dex",chainIds:[],auth:"none",ops:["health","venues","quote","prepare"],execution:"prepare",localSignerSurfaces:["sol"],baseEnv:["JUPITER_SWAP_API_URL","SOLANA_RPC_URL"],description:"Jupiter Swap API v1 quote + local-signer Solana swap handoff"});C({id:"hl-perps",venue:"hyperliquid",chainIds:[],auth:"none",ops:["health","assetInfo","prepareOrder","prepareCancel","prepareLeverage","prepareIsolatedMargin","prepareBracket","prepareBuilderApproval"],execution:"prepare",localSignerSurfaces:["hl"],notes:"Hyperliquid perp, HIP-3, and HIP-4 outcome orders through local-signer L1 action handoff."});C({id:"hl-markets",venue:"hyperliquid",chainIds:[],auth:"none",ops:["health","markets","leaderboards","coin","spot"],notes:"Joined Hyperliquid market datapoints for the Hyperliquid agent. Read-only."});C({id:"hl-entry-state",venue:"hyperliquid",chainIds:[],auth:"none",ops:["health","see","qualify","lock","list","watch"],execution:"read-only",description:"SEE/ENTER/MANAGE for discretionary HL perps: compose sourced /info fields, qualify a side, lock the state only after a fill receipt, and alert_only-diff live vs that lock. Never signs."});C({id:"hl-staking",venue:"hypercore-staking",chainIds:[],auth:"none",ops:["health","validators","delegatorSummary","delegations","rewards","history","preflight","prepareStakeDeposit","prepareStakeWithdraw","prepareDelegate"],execution:"prepare",localSignerSurfaces:["hl"],baseEnv:["HL_INFO_URL","HL_EXCHANGE_URL","HL_TESTNET"],description:"Hyperliquid HyperCore HYPE staking. Public reads plus local-signer EIP-712 execution for cDeposit / cWithdraw / tokenDelegate after arming. Hosted/keyless remains prepare-only."});C({id:"magiceden-sol",venue:"solana-nft",chainIds:[],auth:"optionalApiKey",ops:["health","stats","listings","tokenListings","prepareBuy","prepareList","prepareMint"],execution:"prepare",baseEnv:["MAGICEDEN_API_KEY","MAGICEDEN_API_URL"],description:"Magic Eden Solana NFT market. Reads (stats/listings) are keyless; buy/list/mint instruction builders need MAGICEDEN_API_KEY and return an unsigned base64 transaction for the user's Solana wallet. Never signs or broadcasts."});C({id:"defillama",venue:"prices",chainIds:[],auth:"none",ops:["health","prices","pricesBySymbol","protocols","yields","stablecoins","dexVolumes"],baseEnv:["DEFILLAMA_COINS_URL","DEFILLAMA_API_URL"],description:"DeFiLlama public prices + protocols TVL"});C({id:"lifi",venue:"dex",chainIds:[1,10,56,137,988,999,2741,4663,8453,42161,43114],auth:"none",ops:["health","quote","prepare","chains"],execution:"prepare",baseEnv:["LIFI_API_URL"],description:"LI.FI public cross-chain / DEX aggregator quotes (no key)"});C({id:"dexscreener",venue:"dex",chainIds:[],auth:"none",ops:["health","token","search","pair"],baseEnv:["DEXSCREENER_API_URL"],description:"DexScreener public token/pair discovery"});C({id:"uniswap-v3",venue:"dex",chainIds:SR,auth:"none",ops:["health","quote","prepare","quotePath","ethUsdc","chains"],execution:"prepare",localSignerSurfaces:["evm-swap"],baseEnv:["ETH_RPC_URL","BASE_RPC_URL","ARBITRUM_RPC_URL","OPTIMISM_RPC_URL","BSC_RPC_URL","POLYGON_RPC_URL","AVALANCHE_RPC_URL","RH_CHAIN_RPC"],description:"Uniswap V3 QuoterV2 exact-in quotes via eth_call across official deployments plus Robinhood Chain, no key"});C({id:"lp-exit",venue:"dex",chainIds:ER,auth:"none",ops:["health","inspect","prepareRemove","prepareSettlement","prepareUnwrap","chains"],execution:"prepare",baseEnv:["ETH_RPC_URL","BASE_RPC_URL"],description:"Receipt-gated Uniswap V3 LP exit into native asset: remove/collect, net-route token legs, then unwrap. Unsigned only."});C({id:"lp-liquidity-ranker",venue:"dex",chainIds:Kd,auth:"none",ops:["health","rank"],execution:"read-only",description:"Cross-chain LP destination analysis: deepest liquidity and net-best migration are separate, exact canonical mappings required."});C({id:"lp-destination-discovery",venue:"dex",chainIds:Kd,auth:"none",ops:["health","discover"],execution:"read-only",description:"Live exact-address LP pool discovery across configured chains; reports deepest liquidity separately from cost-qualified migration evidence."});C({id:"uniswap-v4",venue:"dex",chainIds:IR,auth:"none",ops:["health","quote","inspectHook","prepare","chains"],execution:"prepare",baseEnv:["ETH_RPC_URL","BASE_RPC_URL","ARBITRUM_RPC_URL","OPTIMISM_RPC_URL","BSC_RPC_URL","POLYGON_RPC_URL","AVALANCHE_RPC_URL","RH_CHAIN_RPC"],description:"Uniswap V4 quotes, hook permission/code/pool-state inspection, and guarded unsigned Universal Router preparation across official deployments plus Robinhood Chain."});C({id:"x402",venue:"payments",chainIds:[],auth:"none",ops:["health","inspect","prepare"],execution:"prepare",description:"x402 v2 PAYMENT-REQUIRED inspection and explicit-cap exact-payment templates. Never signs, calls a facilitator, or retries a paid request."});C({id:"bankr",venue:"wallet-data",chainIds:[],auth:"apiKey",ops:["health","wallet","portfolio","swapQuote"],execution:"read-only",baseEnv:["BANKR_API_KEY","BANKR_API_URL"],description:"Bankr Wallet API read-only identity, portfolio, and swap quotes. Oracle excludes Bankr swap, transfer, sign, submit, agent, and LLM endpoints."});C({id:"aerodrome",venue:"dex",chainIds:[8453],auth:"none",ops:["health","quote","prepare","chains"],execution:"prepare",localSignerSurfaces:["evm-swap"],baseEnv:["BASE_RPC_URL"],description:"Aerodrome Slipstream CL on Base \u2014 QuoterV2 + SwapRouter exact-input via eth_call (tickSpacing, no key)"});C({id:"zerox",venue:"dex",chainIds:[1,10,137,8453,42161],auth:"apiKey",ops:["health","price","quote","prepare"],execution:"prepare",baseEnv:["ZEROX_API_KEY","ZEROX_API_URL"],description:"0x Swap API v2 price/quote/prepare \u2014 requires ZEROX_API_KEY (unconfigured without key; no Oracle key shipped)"});C({id:"across",venue:"bridge",chainIds:[1,10,137,42161,8453],auth:"none",ops:["health","suggestedFees"],baseEnv:["ACROSS_API_URL"],description:"Across bridge suggested-fees (public)"});C({id:"hop",venue:"bridge",chainIds:[1,10,137,42161],auth:"none",ops:["health","quote"],baseEnv:["HOP_API_URL"],description:"Hop Protocol bridge quotes (public)"});C({id:"relay",venue:"bridge",chainIds:[1,10,137,8453,42161],auth:"none",ops:["health","quote","prepare"],execution:"prepare",baseEnv:["RELAY_API_URL"],description:"Relay.link bridge/swap quotes (public)"});C({id:"cowswap",venue:"dex",chainIds:[1,100,42161,8453],auth:"none",ops:["health","quote","prepareOrder","order","status","chains","arm"],execution:"armed-local",localSignerSurfaces:["evm-order"],baseEnv:[],description:"CowSwap batch auction. Quote is public; Allow posts official api.cow.fi orders."});C({id:"oneinch",venue:"dex",chainIds:[1,10,137,8453,42161],auth:"apiKey",ops:["health","quote","prepare","approveSpender"],execution:"prepare",baseEnv:["ONEINCH_API_KEY","ONEINCH_API_URL"],description:"1inch Swap API v6 quote/prepare \u2014 requires ONEINCH_API_KEY (unconfigured without key; no Oracle key shipped)"});C({id:"hl-ws",venue:"hl",chainIds:[],auth:"none",ops:["health","allMids","l2Book","snapshot"],baseEnv:["HL_WS_URL"],description:"Hyperliquid short-lived WS snapshots (allMids/l2Book)"});C({id:"poly-ws",venue:"poly",chainIds:[137],auth:"none",ops:["health","book","snapshot"],baseEnv:["POLY_WS_URL"],description:"Polymarket CLOB short-lived WS market snapshots"});C({id:"anvil-nft",venue:"robinhood-nft",chainIds:[4663],auth:"optionalApiKey",ops:["health","markets","quoteSpecificBuy","quoteSell","scanCollection","scanAllMarkets","scanCrossVenueArb","scanAllMarketsArb","prepareSpecificBuy","prepareSell"],execution:"prepare",localSignerSurfaces:["evm-nft"],baseEnv:["RH_CHAIN_RPC","OPENSEA_API_KEY","OPENSEA_ENV_FILE"],description:"All-market Anvil discovery and exact-token arbitrage, with exact buy and sell execution through the armed owner-local signer after human confirmation"});C({id:"stonkbrokers",venue:"robinhood-nft",chainIds:[4663],auth:"optionalApiKey",ops:["health","quoteBrokerBuy","scanBrokerLoot","prepareBrokerBuy","brokerDesk","clockInStatus","prepareClockIn"],execution:"prepare",baseEnv:["RH_CHAIN_RPC"],description:"Unsigned StonkBrokers Broker Desk discovery, nested-loot verification, and bounded local-only preparations"});C({id:"opensea-nft",venue:"nft",chainIds:AR,auth:"apiKey",ops:["health","collection","floor","bestListings","bestListing","bestOffer","accountNfts","accountPnl","prepareMint","prepareList","prepareCancel"],execution:"prepare",baseEnv:["OPENSEA_API_KEY","OPENSEA_ENV_FILE"],description:"OpenSea multichain NFT inventory, floors, and unsigned bounded mint, listing, and listing-cancellation preparations; opaque buy/sweep fulfillment is disabled"});C({id:"local-marketplace",venue:"local-p2",chainIds:[],auth:"none",ops:["health","createListing","listListings","cancelListing","createOffer","armFill"],execution:"prepare",localSignerSurfaces:["evm-nft"],description:"Owner-local P2 catalog stored under ~/.config/oracle. Additive and isolated from OpenSea, Magic Eden, Satflow, Bisq, Anvil, and Polymarket. Listings are armed for the owner-local signer; sign-and-broadcast is an explicit createLocalMarketplace().instructFill instruction. Generic signHash is refused."});C({id:"local-x402",venue:"local-x402",chainIds:[],auth:"none",ops:["health","createIntent","listIntents","cancelIntent","armPayment"],execution:"prepare",localSignerSurfaces:["evm-swap"],description:"Owner-local x402 payment budgets under ~/.config/oracle. Additive and isolated from OpenSea and Telegram. Intents are armed; sign-and-broadcast is an explicit createLocalX402().instructPay instruction. Generic signHash is refused."});C({id:"local-pack-registry",venue:"local-packs",chainIds:[],auth:"none",ops:["health","registerPack","listPacks","revokePack"],execution:"read-only",description:"Owner-local third-party pack REGISTRY under ~/.config/oracle. Catalog only: packs are never loaded or executed. Isolated from OpenSea and Telegram."});C({id:"erc8004-identity",venue:"agent-identity",chainIds:[],auth:"none",ops:["health","prepareIdentityRegistration","prepareAgentURIUpdate","inspectIdentity","arm"],execution:"armed-local",localSignerSurfaces:["evm"],baseEnv:["ORACLE_ERC8004_CHAIN_ID","ORACLE_ERC8004_IDENTITY_REGISTRY"],description:"Draft ERC-8004 identity. Public prepare is keyless; Allow broadcasts type-2 register/setAgentURI."});C({id:"hyperevm-dex",venue:"hyperevm",chainIds:[999],auth:"none",ops:["health","search","token"],baseEnv:["HYPEREVM_RPC_URL"],description:"HyperEVM pair discovery via DexScreener + optional RPC"});C({id:"geckoterminal",venue:"dex-data",chainIds:[],auth:"none",ops:["health","networks","pool","token","ohlcv"],baseEnv:["GECKOTERMINAL_API_URL"],description:"GeckoTerminal public networks, pools, tokens, and OHLCV"});C({id:"curve",venue:"dex",chainIds:[1,10,56,137,988,999,4663,8453,42161,43114],auth:"none",ops:["health","openapi","pools","quote","prepare"],execution:"prepare",baseEnv:["CURVE_API_URL"],description:"Curve public pool registry API + RouterNG validated single-hop prepare"});C({id:"gmx",venue:"perps-data",chainIds:[42161,43114],auth:"none",ops:["health","tickers","markets","marketsInfo","tokens","prepareOrder","positions","orderStatus","verifyOrder"],execution:"intent",baseEnv:[],description:"GMX v2 public oracle/markets plus guarded async order intents on Arbitrum and Avalanche"});C({id:"morpho",venue:"lending-data",chainIds:[1,10,137,2741,8453,42161,4663,999,988],auth:"none",ops:["health","markets","vaults","prepareVault"],execution:"intent",baseEnv:["MORPHO_API_URL"],description:"Morpho public GraphQL markets/vaults + guarded ERC-4626 vault intents"});C({id:"balancer",venue:"dex",chainIds:[1,10,137,42161,43114,8453],auth:"none",ops:["health","pools","quote","prepare"],execution:"prepare",baseEnv:["BALANCER_API_URL"],description:"Balancer public GraphQL pool data + v3 Router exact-input prepare (Polygon read-only)"});C({id:"pendle",venue:"yield",chainIds:[1,10,56,8453,42161,999],auth:"none",ops:["health","markets","quote","prepare"],execution:"prepare",baseEnv:["PENDLE_API_URL"],description:"Pendle public yield-market API + Hosted SDK direct Convert prepare"});C({id:"odos",venue:"dex",chainIds:[1,10,56,137,8453,42161,43114,4663],auth:"none",ops:["health"],execution:"unavailable",deprecated:{since:"2026-07-30",reason:"Odos sunset the public SOR API; /sor/quote/v2 and v3 both return 410 Gone",evidence:"sunset: Thu, 30 Jul 2026 12:00:00 GMT response header"},baseEnv:["ODOS_API_URL"],description:"Odos public SOR (DEPRECATED upstream 2026-07-30 -- endpoint returns 410)"});C({id:"blockscout",venue:"explorer",chainIds:[1,10,137,8453,42161],auth:"none",ops:["health","stats","address","token"],baseEnv:[],description:"Verified public Blockscout REST v2 instances"});C({id:"paraswap",venue:"dex",chainIds:[1,10,56,137,8453,42161,43114,4663],auth:"none",ops:["health","tokens","price","quote","prepare"],execution:"prepare",baseEnv:["PARASWAP_API_URL"],description:"ParaSwap/Velora public price routes + validated transaction builder"});C({id:"rfq",venue:"intent-rfq",chainIds:[1,10,56,137,8453,42161,43114,4663],auth:"none",ops:["health","intent","quote"],execution:"prepare",baseEnv:["ZEROX_API_KEY","ONEINCH_API_KEY"],description:"Cross-chain RFQ intent normalizer and firm-quote fanout over reviewed venues. Prepares artifacts only, never signs or broadcasts."});C({id:"execution-strategies",venue:"oracle-native",chainIds:[],auth:"none",ops:["health","plan"],execution:"plan-only",baseEnv:[],description:"Oracle-native TWAP, VWAP, POV, iceberg, and implementation-shortfall planners. No Tread.fi/API dependency. Plans never sign or broadcast; every slice requires a fresh best-execution quote, policy check, simulation, confirmation, wallet signature, and receipt."});C({id:"polygon-staking",venue:"polygon-staking",chainIds:[137],auth:"none",ops:["health","validators","validatorDetail"],baseEnv:["POLYGON_STAKING_API_URL"],description:"Polygon POS staking validators"});C({id:"babylon-staking",venue:"btc-staking",chainIds:[],auth:"none",ops:["health","stats","finalityProviders","delegations"],execution:"read-only",baseEnv:["BABYLON_STAKING_API_URL"],description:"Babylon native BTC staking (staking-api.babylonlabs.io v2). Keyless per-staker positions from a PUBLIC key alone \u2014 APR, TVL, finality-provider roster, and delegations. Read-only; staking/unbonding is user-wallet."});C({id:"mempool-mining",venue:"btc-mining",chainIds:[],auth:"none",ops:["health","difficulty","poolShare","hashrate","rewardStats"],execution:"read-only",baseEnv:["MEMPOOL_API_URL"],description:"Bitcoin mining + network security telemetry via mempool.space /api/v1/mining. Difficulty retarget, pool concentration (top-1/top-3 share), hashrate trend, subsidy-vs-fee split."});C({id:"liquid-esplora",venue:"liquid",chainIds:[],auth:"none",ops:["health","tipHeight","addressInfo","assetInfo"],execution:"read-only",baseEnv:["LIQUID_ESPLORA_URL"],description:"Liquid Network (Blockstream sidechain) via Esplora. Same schema as bitcoin-esplora plus multi-asset issuance/peg stats. Confidential addresses return TXO counts only \u2014 amounts are blinded on chain and reported as such."});C({id:"hiro-stacks",venue:"stacks",chainIds:[],auth:"none",ops:["health","networkInfo","stackingInfo","poxCycles","blocks"],execution:"read-only",baseEnv:["HIRO_API_URL","HIRO_API_KEY"],description:"Stacks (Bitcoin L2) via Hiro public API. Network tip, PoX stacking state (the BTC-yield mechanism), and historical reward cycles. Keyless tier is ~20 rps; HIRO_API_KEY is optional and never required."});C({id:"tron-public",venue:"tron",chainIds:[],auth:"none",ops:["health","account","trc20Balances","trc20Transfers","chainParameters"],execution:"read-only",localSignerSurfaces:[],baseEnv:["TRON_API_URL","TRONGRID_API_KEY"],description:"Tron mainnet via public TronGrid. TRX balance, TRC20 token balances, USDT-TRC20 transfer history, chain parameters. Tron carries the largest USDT float of any chain. Keyless; TRONGRID_API_KEY only raises the rate ceiling and never travels to a non-TronGrid host."});C({id:"ton-public",venue:"ton",chainIds:[],auth:"none",ops:["health","accountState","jettonBalances","transactions"],execution:"read-only",localSignerSurfaces:[],baseEnv:["TON_API_URL","TONCENTER_API_KEY"],description:"TON via public toncenter. Account state + nanoton balance, jetton (TON's ERC20) balances, transaction history. The settlement layer for Telegram-native assets. Keyless; TONCENTER_API_KEY only raises the rate ceiling."});C({id:"cosmos-lcd",venue:"cosmos",chainIds:[],auth:"none",ops:["health","chains","balances","delegations","denomTrace"],execution:"read-only",localSignerSurfaces:[],baseEnv:["COSMOS_LCD_URL","COSMOS_CHAIN"],description:"Cosmos SDK chains via keyless LCD/REST \u2014 one provider, many chains (cosmoshub default, plus osmosis/celestia/injective/neutron/dydx/noble/kava, or any LCD via COSMOS_LCD_URL_<CHAIN>). Bank balances, staking delegations + unbondings + rewards, and IBC denom-trace resolution for ibc/<hash> denoms."});C({id:"sui-public",venue:"sui",chainIds:[],auth:"none",ops:["health"],execution:"unavailable",deprecated:{since:"2026-08-25",reason:"Sui public fullnodes return JSON-RPC -32601 because the JSON-RPC surface is deprecated",evidence:"Migrate the provider to Sui GraphQL or gRPC before restoring it to the live roster"},localSignerSurfaces:[],baseEnv:["SUI_RPC_URL"],description:"QUARANTINED: Sui public JSON-RPC is deprecated. A GraphQL or gRPC replacement has not shipped."});C({id:"aptos-public",venue:"aptos",chainIds:[],auth:"none",ops:["health","account","resources","coinBalances"],execution:"read-only",localSignerSurfaces:[],baseEnv:["APTOS_FULLNODE_URL","APTOS_API_KEY"],description:"Aptos mainnet via the public fullnode REST API. Ledger info, account sequence/auth key, Move resources, and coin balances (0x1::coin::balance view with a CoinStore resource fallback). Read-only; the transaction submit door is never called."});C({id:"ordinals-runes",venue:"btc-runes",chainIds:[],auth:"none",ops:["health","blockHeight","blockInfo","satInfo","runeInfo"],execution:"read-only",baseEnv:["ORDINALS_BASE_URL"],description:"Runes + sat/block index via a public ord server (ordinals.com). /r/blockheight is PLAIN TEXT; the /runes listing is 406 'JSON API disabled' so only per-rune lookup exists; rune names must drop the bullet spacer (UNCOMMONGOODS)."});C({id:"mempool-lightning",venue:"btc-lightning",chainIds:[],auth:"none",ops:["health","statistics","nodeRankings","nodeCountries"],execution:"read-only",baseEnv:["MEMPOOL_API_URL"],description:"Lightning Network topology via mempool.space. Capacity/channel/node aggregates, node rankings, country distribution. STALE-PRONE: the crawler snapshot has been observed weeks behind, so every response carries ageDays + a stale flag."});C({id:"bob-rootstock",venue:"btc-l2",chainIds:[60808,30],auth:"none",ops:["health","stats","addressInfo","tokenBalances"],execution:"read-only",baseEnv:["BOB_EXPLORER_URL","ROOTSTOCK_EXPLORER_URL"],description:"BOB (60808) and Rootstock (30) \u2014 the EVM Bitcoin L2s \u2014 via their Blockscout v2 instances (identical schema, one code path). Chain stats, gas prices, native balances, token holdings. Pass chainId 'all' to fan out."});C({id:"bisq-markets",venue:"bisq",chainIds:[],auth:"none",ops:["health","markets","ticker","trades"],execution:"read-only",baseEnv:["BISQ_MARKETS_URL"],description:"Bisq non-KYC P2P BTC price discovery (markets.bisq.network). Value is the BASIS against centralized spot, not the absolute print: volume is thin and the last trade can be hours old, so trade age is always reported."});C({id:"social-intel",venue:"oracle-social",chainIds:[],auth:"none",ops:["health","trendingTokens","trendingCas","keywordMentions","smartAccounts","narratives"],execution:"read-only",localSignerSurfaces:[],baseEnv:["ORACLE_SOCIAL_INTEL_STORE","ORACLE_SOCIAL_INTEL_STALE_MIN"],description:"Local curated-account crypto social intelligence. Sample = graded caller list, NOT a firehose; every response reports sample size and snapshot age."});C({id:"magiceden-ordinals",venue:"btc-ordinals-market",chainIds:[],auth:"none",ops:["health","collectionStat"],execution:"read-only",baseEnv:["MAGICEDEN_ORD_API_URL","MAGICEDEN_API_KEY","MAGICEDEN_PROBE_COLLECTION"],description:"Magic Eden ordinals collection stats. DEGRADED UPSTREAM: /v2/ord/btc/* returned 503 'no healthy upstream' on every verification attempt. health() reports ok:false while it is down and collectionStat() returns upstreamDown:true with fallback 'satflow' instead of throwing. Only /stat is wired; 600 req/min documented."});C({id:"braiins-insights",venue:"btc-mining",chainIds:[],auth:"none",ops:["health","priceStats","poolStats"],execution:"read-only",baseEnv:["BRAIINS_INSIGHTS_URL"],description:"Braiins mining insights \u2014 BTC price tick + per-pool block/hashrate distribution. Use insights.braiins.com (302s to learn.braiins.com, followed transparently); pool.braiins.com/api is 403 and is NOT the public API."});C({id:"pyth-price-feeds",venue:"solana-oracle",chainIds:[],auth:"none",ops:["health","latestPrice","latestPrices","feedDirectory"],baseEnv:["PYTH_HERMES_URL"],description:"Pyth Network: Solana price feeds with confidence intervals, real-time updates, zero auth"});C({id:"solend-lending",venue:"solana-lending",chainIds:[],auth:"none",ops:["health","markets","reserves"],baseEnv:["SAVE_API_URL"],description:"Solend/Save lending: markets + per-reserve supply/borrow APY, Solana's Aave equivalent (keyless)"});C({id:"jito-mev",venue:"solana-mev",chainIds:[],auth:"none",ops:["health","recentBundles","tipFloor"],baseEnv:["JITO_API_URL"],description:"Jito MEV: recent bundles, tippers, tip floor \u2014 real-time Solana MEV data (keyless)"});C({id:"sanctum-lst",venue:"solana-staking",chainIds:[],auth:"none",ops:["health","lstList","apyAll","apyIndividual"],baseEnv:["SANCTUM_API_URL"],description:"Sanctum LST: liquid staking tokens with per-token APY \u2014 JitoSOL, mSOL, bSOL, compSOL, pathSOL, etc. (keyless)"});C({id:"kamino-strategies",venue:"solana-yield",chainIds:[],auth:"none",ops:["health","strategies","strategyMetrics"],baseEnv:["KAMINO_API_URL"],description:"Kamino: live yield strategies with APY, TVL, vault balances (keyless)"});C({id:"meteora-dlmm",venue:"solana-dex",chainIds:[],auth:"none",ops:["health","pools","poolSearch"],baseEnv:["METEORA_API_URL"],description:"Meteora DLMM: concentrated liquidity pools via amm-v2 API, distinct from Jupiter DEX routes (keyless)"});C({id:"aave-v3",venue:"evm-lending",chainIds:[1,10,56,137,59144,1088,534352,8453,42161,43114,5e3,1868],auth:"none",ops:["health","markets","marketReserves","chains"],baseEnv:["AAVE_V3_API_URL"],description:"Aave V3 GraphQL: multi-chain lending, full market + reserve schema with supplyInfo/borrowInfo (keyless)"});C({id:"cow-protocol",venue:"evm-intent",chainIds:[1,100,42161],auth:"none",ops:["health","auction","openOrders","recentTrades"],baseEnv:["COW_API_URL"],description:"CoW Protocol: intent/solver auction data, open orders, trades \u2014 intent-based DEX not covered by existing providers (keyless)"});C({id:"relayscan-mev",venue:"evm-mev",chainIds:[1],auth:"none",ops:["health","overview","builderProfit","dailyStats"],baseEnv:["RELAYSCAN_API_URL"],description:"Relayscan: MEV relay overview, builder profit rankings, daily block stats (keyless)"});C({id:"birdeye-tokens",venue:"solana-tokens",chainIds:[],auth:"none",ops:["health","tokenList"],baseEnv:["BIRDEYE_API_URL"],description:"Birdeye public token list: Solana tokens ranked by 24h volume, market cap (keyless)"});C({id:"das-assets",venue:"solana-nft",chainIds:[],auth:"none",ops:["health","assetsByOwner","searchAssets","assetProof"],baseEnv:["SOLANA_RPC_URL"],description:"Digital Asset Standard (DAS): compressed NFT reads via public Solana RPC \u2014 getAssetsByOwner, searchAssets, assetProof. No Helius key needed."});C({id:"symbiotic-restaking",venue:"evm-restaking",chainIds:[1],auth:"none",ops:["health","vaults","vaultDetail"],baseEnv:["SYMBIOTIC_API_URL"],description:"Symbiotic restaking: vaults with collateral data, approved status, operator metadata (keyless)"});C({id:"beefy-yields",venue:"evm-yield",chainIds:[1,10,56,137,8453,42161,43114,250,1088],auth:"none",ops:["health","apy","apyBreakdown"],baseEnv:["BEEFY_API_URL"],description:"Beefy Finance: cross-chain yield aggregator vaults with APY breakdowns (keyless)"});C({id:"across-bridge",venue:"evm-bridge",chainIds:[1,10,42161,8453,324,59144],auth:"none",ops:["health","pools","suggestedFees"],baseEnv:["ACROSS_API_URL"],description:"Across bridge: pool liquidity + APY per bridge pool with suggested fees (keyless)"});C({id:"spark-lend",venue:"evm-lending",chainIds:[1],auth:"none",ops:["health","markets"],baseEnv:["SPARK_API_URL"],description:"Spark Lend / Sky Savings: ERC-4626 vault APY + TVL + user count (keyless)"});C({id:"l2beat-tvl",venue:"evm-l2",chainIds:[],auth:"none",ops:["health","tvl","activity"],baseEnv:["L2BEAT_API_URL"],description:"L2Beat: L2 scaling TVL, project-level breakdowns, activity metrics (keyless)"});C({id:"celestia-da",venue:"evm-da",chainIds:[],auth:"none",ops:["health","stats","blockStats"],baseEnv:["CELENIUM_API_URL"],description:"Celestia DA via Celenium: blob stats, block-level blob counts, network metrics (keyless)"});C({id:"limit-order",venue:"1inch-lop",chainIds:[1,10,56,137,8453,42161],auth:"none",ops:["health","prepare","arm"],execution:"armed-local",localSignerSurfaces:["evm-order"],description:"1inch Limit Order Protocol v4. Queues on the local signer; Allow posts the order."});C({id:"jupiter-dca",venue:"jupiter",chainIds:[],auth:"none",ops:["health","prepare","arm"],execution:"armed-local",localSignerSurfaces:["sol"],description:"Jupiter limit/DCA. Unsigned tx queues on the sol signer; Allow submits."});C({id:"protective-monitors",venue:"oracle-intel",chainIds:[],auth:"none",ops:["health","depeg","oracleDeviation","exploitFeed","goplus","liquidationLadder"],execution:"read-only",description:"Alert-only depeg, oracle deviation, exploit feed, GoPlus second opinion, liquidation ladder."});C({id:"funding-scanner",venue:"perps",chainIds:[],auth:"none",ops:["health","scan"],execution:"read-only",description:"Cross-venue funding carry ranked net of fee drag. Failed venues stay FAILED."});C({id:"perp-universal",venue:"perps",chainIds:[],auth:"none",ops:["health","fundingAll","prepareOrder"],execution:"prepare-only",description:"Live fundingAll across HL/GMX/dYdX + honest FAILED Drift/Vertex. prepareOrder unsigned."});C({id:"onchain-options",venue:"options",chainIds:[],auth:"none",ops:["health","rank"],execution:"read-only",description:"Local Black-Scholes ranking. No arm until official Derive/Lyra domain is pinned."});C({id:"holder-clusters",venue:"oracle-intel",chainIds:[],auth:"none",ops:["health","score"],execution:"read-only",description:"Heuristic holder HHI + common-funding clusters. Not identity."});C({id:"kalshi",venue:"prediction",chainIds:[],auth:"none",ops:["health","markets"],execution:"read-only",description:"Kalshi market catalog read-only. Trading may be US-restricted. Prepare refused."});C({id:"derive-options",venue:"options",chainIds:[],auth:"none",ops:["health"],execution:"unavailable",deprecated:{since:"2026-08-25",reason:"No official Derive EIP-712 domain or contract is pinned, so prepare remains unavailable",evidence:"prepareOption() in onchain-options.mjs refuses unconditionally"},description:"UNAVAILABLE: Derive execution has no pinned official domain. Use onchain-options for local ranking."});C({id:"limitless",venue:"prediction",chainIds:[],auth:"none",ops:["health","markets"],execution:"read-only",description:"Limitless market catalog. Prepare refused \u2014 no grant-bound decoder."});C({id:"dov-vaults",venue:"options",chainIds:[],auth:"none",ops:["health"],execution:"unavailable",deprecated:{since:"2026-08-25",reason:"The reviewed DOV vault registry is empty, so every vault read refuses",evidence:"REVIEWED_DOV_VAULTS.length is zero and no reviewed code hash is pinned"},description:"UNAVAILABLE: the reviewed DOV vault registry is empty and every read fails closed."});C({id:"prediction-match",venue:"prediction",chainIds:[],auth:"none",ops:["health","match"],execution:"read-only",description:"Cross-venue event match. Same title is not a match."});C({id:"tee-attestation",venue:"identity",chainIds:[],auth:"none",ops:["health","verify"],execution:"read-only",description:"TEE schema stub. Hardware unavailable. Unknown root unverified."});C({id:"keeper-mirror",venue:"oracle-intel",chainIds:[],auth:"none",ops:["health"],execution:"read-only",description:"Keeper alert-mirror. Off by default. No execute path."});C({id:"erc7715-permissions",venue:"aa",chainIds:[],auth:"none",ops:["health","normalize"],execution:"read-only",description:"ERC-7715 permission normalize. Wildcards refused. aa allowlist empty."});C({id:"erc7710-delegation",venue:"aa",chainIds:[],auth:"none",ops:["health","inspect"],execution:"read-only",description:"ERC-7710 delegation inspect. Missing revocation/expiry fails closed."});C({id:"binance-public",venue:"cex",chainIds:[],auth:"none",ops:["health","ticker","orderbook","funding","markPrice","openInterest","fundingHistory"],execution:"read-only",localSignerSurfaces:[],baseEnv:["BINANCE_API_URL","BINANCE_FAPI_URL"],description:"Binance public spot + USD-M perp market data (ticker, depth, premiumIndex funding, open interest). Keyless reads only; no trading endpoints."});C({id:"okx-public",venue:"cex",chainIds:[],auth:"none",ops:["health","ticker","orderbook","funding","markPrice","openInterest"],execution:"read-only",localSignerSurfaces:[],baseEnv:["OKX_API_URL"],description:"OKX public v5 market data (ticker, books, swap funding-rate, mark-price, open-interest). Keyless reads only; no trading endpoints."});C({id:"bybit-public",venue:"cex",chainIds:[],auth:"none",ops:["health","ticker","orderbook","funding","markPrice","openInterest","fundingHistory"],execution:"read-only",localSignerSurfaces:[],baseEnv:["BYBIT_API_URL"],description:"Bybit public v5 market data (spot/linear tickers, orderbook, funding, open interest). Keyless reads only; no trading endpoints."});C({id:"cex-basis",venue:"cex",chainIds:[],auth:"none",ops:["health","basis","fundingSpread","legs"],execution:"read-only",localSignerSurfaces:[],baseEnv:["BINANCE_API_URL","OKX_API_URL","BYBIT_API_URL","HL_INFO_URL"],description:"Cross-venue perp basis and annualized funding spreads across Binance, OKX, Bybit and Hyperliquid public data. Analysis only, no sizing and no prepare."});C({id:"snapshot-governance",venue:"governance",chainIds:[],auth:"none",ops:["health","spaces","proposals","activeProposals","proposal","votes","votingPower"],execution:"read-only",localSignerSurfaces:[],baseEnv:["SNAPSHOT_API_URL"],description:"Snapshot.org off-chain governance reads: spaces, proposals, proposal detail, an address's votes and voting power. Never signs a vote."});C({id:"tally-governance",venue:"governance",chainIds:[1,10,42161],auth:"none",ops:["health","governors","info","proposals","proposal","voterStatus","tallyProposals"],execution:"read-only",localSignerSurfaces:[],baseEnv:["TALLY_API_URL","TALLY_API_KEY"],description:"Governor Bravo / OZ Governor on-chain proposal state and vote tallies for major DAOs, plus optional keyed Tally metadata. Read-only ABI has no vote/queue/execute selector."});C({id:"stablecoin-peg",venue:"oracle-intel",chainIds:[],auth:"none",ops:["health","scan"],execution:"read-only",localSignerSurfaces:[],baseEnv:[],description:"Peg-deviation scan across major and Hyperliquid-native stables. Ranks by absolute bps from $1 and classifies normal/watch/warn/depeg. Unpriced is unknown, never on-peg. Read-only composition of DefiLlama/Pyth/DexScreener."});_R();R();var m7=Object.freeze(["live","needs_key","deprecated","soft_fail","hard_down"]);function Ds(e={}){return e.execution==="unavailable"||!!e.deprecated}dt();dt();var OR=/^0x[0-9a-fA-F]{40}$/,pi="0xdfc24b077bc1425ad1dea75bcb6f8158e10df303";function Yd(e,t){let n=String(e||"").trim();if(!OR.test(n))throw new Error(`hl-vaults: ${t} must be a 0x EVM address`);return n.toLowerCase()}function pb(e){if(e==null||e==="")return null;let t=Number(e);return Number.isFinite(t)?t:null}function mb(e={}){let t=Array.isArray(e.portfolio)?e.portfolio:[],n=t.find(([i])=>i==="day")?.[1]||null,r=Array.isArray(n?.accountValueHistory)?n.accountValueHistory:[],o=Array.isArray(n?.pnlHistory)?n.pnlHistory:[];return{name:e.name??null,vaultAddress:e.vaultAddress??e.address??null,leader:e.leader??null,description:e.description??null,tvl:e.tvl??r.at(-1)?.[1]??null,apr:e.apr??null,pnl:e.pnl??o.at(-1)?.[1]??null,isClosed:e.isClosed??null,allowDeposits:e.allowDeposits??null,maxDistributable:e.maxDistributable??null,followers:e.followers??null,portfolio:t}}function RR(e){return[...e].sort((t,n)=>(pb(n.tvl)??-1)-(pb(t.tvl)??-1))}function Jd(e){return e.hlInfo||de}function Xd(e){return{...e,exec:!1,execution:"read-only",armed:!1}}async function Qd(e={},t={}){let n=await Jd(t)({type:"vaultSummaries"},t),r=RR((Array.isArray(n)?n:[]).map(mb));return Xd({provider:"hl-vaults",count:r.length,vaults:r,raw:n})}async function zs(e={},t={}){let r={type:"vaultDetails",vaultAddress:Yd(e.vaultAddress||e.address,"vaultAddress")};e.user&&(r.user=Yd(e.user,"user"));let o=await Jd(t)(r,t);return Xd({provider:"hl-vaults",vault:mb(o||{}),raw:o})}async function Zd(e={},t={}){let n=Yd(e.user||e.address,"user"),r=await Jd(t)({type:"userVaultEquities",user:n},t),o=(Array.isArray(r)?r:[]).map(i=>({vaultAddress:i.vaultAddress??i.address??null,equity:i.equity??i.vaultEquity??null}));return Xd({provider:"hl-vaults",user:n,count:o.length,positions:o,raw:r})}async function ep(e={},t={}){let n=String(e.mode||"hlp").toLowerCase();if(n==="hlp")return zs({...e,vaultAddress:pi},t);if(n==="summaries")return Qd(e,t);if(n==="details")return zs(e,t);if(n==="mine")return Zd(e,t);throw new Error("hl-vaults: mode must be hlp, summaries, details, or mine")}async function fb(e={}){try{let t=await ep({mode:"hlp"},e);return{ok:t.vault.vaultAddress===pi&&!!t.vault.name,provider:"hl-vaults",hlp:{name:t.vault.name,vaultAddress:t.vault.vaultAddress,tvl:t.vault.tvl,apr:t.vault.apr,allowDeposits:t.vault.allowDeposits},exec:!1,execution:"read-only",armed:!1}}catch(t){return{ok:!1,provider:"hl-vaults",error:String(t?.message||t).slice(0,160),exec:!1,execution:"read-only",armed:!1}}}pe();import{AbiCoder as $R}from"ethers";var tp=999;var Oe=Object.freeze({position:"0x0000000000000000000000000000000000000800",spotBalance:"0x0000000000000000000000000000000000000801",vaultEquity:"0x0000000000000000000000000000000000000802",withdrawable:"0x0000000000000000000000000000000000000803",delegations:"0x0000000000000000000000000000000000000804",delegatorSummary:"0x0000000000000000000000000000000000000805",markPx:"0x0000000000000000000000000000000000000806",oraclePx:"0x0000000000000000000000000000000000000807",spotPx:"0x0000000000000000000000000000000000000808",l1BlockNumber:"0x0000000000000000000000000000000000000809"}),np=Object.freeze({exec:!1,execution:"read-only",armed:!1,signing:!1,broadcasting:!1}),BR=$R.defaultAbiCoder();function mi(e,t){let n=String(e||"").trim();if(!/^0x[0-9a-fA-F]{40}$/.test(n))throw new Error(`hl-precompiles: ${t} must be a 0x EVM address`);return n.toLowerCase()}function fi(e,t,n){let r=Number(e);if(!Number.isInteger(r)||r<0||r>=2**n)throw new Error(`hl-precompiles: ${t} must fit uint${n}`);return r}function nr(e,t){return e.length?BR.encode(e,t):"0x"}function Wt(e,t=0){let r=String(e||"").replace(/^0x/i,"").slice(t*64,t*64+64);if(r.length!==64)throw new Error("hl-precompiles: malformed precompile result");return BigInt(`0x${r}`)}function MR(e,t=0){let n=Wt(e,t);return(n>=2n**255n?n-2n**256n:n).toString()}async function gn(e,t,n={}){if(typeof n.ethCall=="function")return n.ethCall({to:e,data:t,chainId:tp});let r=await D(tp,"eth_call",[{to:e,data:t},"latest"],n);if(typeof r!="string"||!/^0x[0-9a-fA-F]*$/.test(r))throw new Error("hl-precompiles: eth_call did not return hex");return r}function yn(e){return{provider:"hl-precompiles",chainId:tp,...np,...e}}async function Vs(e={}){let t=await gn(Oe.l1BlockNumber,"0x",e);return yn({op:"l1BlockNumber",precompile:Oe.l1BlockNumber,l1BlockNumber:Wt(t).toString(),raw:t})}async function rp(e={},t={}){let n=fi(e.index??e.assetId??0,"index",32),r=await gn(Oe.markPx,nr(["uint32"],[n]),t);return yn({op:"markPx",precompile:Oe.markPx,index:n,markPx:Wt(r).toString(),raw:r})}async function op(e={},t={}){let n=fi(e.index??e.assetId??0,"index",32),r=await gn(Oe.oraclePx,nr(["uint32"],[n]),t);return yn({op:"oraclePx",precompile:Oe.oraclePx,index:n,oraclePx:Wt(r).toString(),raw:r})}async function ip(e={},t={}){let n=fi(e.index??e.assetId??0,"index",32),r=await gn(Oe.spotPx,nr(["uint32"],[n]),t);return yn({op:"spotPx",precompile:Oe.spotPx,index:n,spotPx:Wt(r).toString(),raw:r})}async function ap(e={},t={}){let n=mi(e.user,"user"),r=fi(e.perp??e.assetId??0,"perp",16),o=await gn(Oe.position,nr(["address","uint16"],[n,r]),t);return yn({op:"position",precompile:Oe.position,user:n,perp:r,szi:MR(o,0),raw:o})}async function sp(e={},t={}){let n=mi(e.user,"user"),r=fi(e.token??0,"token",64),o=await gn(Oe.spotBalance,nr(["address","uint64"],[n,r]),t);return yn({op:"spotBalance",precompile:Oe.spotBalance,user:n,token:r,total:Wt(o,0).toString(),hold:Wt(o,1).toString(),raw:o})}async function cp(e={},t={}){let n=mi(e.user,"user"),r=mi(e.vaultAddress??e.vault??pi,"vault"),o=await gn(Oe.vaultEquity,nr(["address","address"],[n,r]),t);return yn({op:"vaultEquity",precompile:Oe.vaultEquity,user:n,vaultAddress:r,hlp:r===pi,equity:Wt(o,0).toString(),raw:o})}async function lp(e={},t={}){let n=mi(e.user,"user"),r=await gn(Oe.withdrawable,nr(["address"],[n]),t);return yn({op:"withdrawable",precompile:Oe.withdrawable,user:n,withdrawable:Wt(r).toString(),raw:r})}async function hb(e={},t={}){let n=String(e.op||e.mode||"l1BlockNumber");if(n==="l1BlockNumber")return Vs(t);if(n==="markPx")return rp(e,t);if(n==="oraclePx")return op(e,t);if(n==="spotPx")return ip(e,t);if(n==="position")return ap(e,t);if(n==="spotBalance")return sp(e,t);if(n==="vaultEquity"||n==="hlp")return cp(e,t);if(n==="withdrawable")return lp(e,t);throw new Error("hl-precompiles: op must be l1BlockNumber, markPx, oraclePx, spotPx, position, spotBalance, vaultEquity, or withdrawable")}async function gb(e={}){try{let t=await Vs(e);return{ok:BigInt(t.l1BlockNumber)>0n,provider:"hl-precompiles",...np,l1BlockNumber:t.l1BlockNumber,precompiles:Oe}}catch(t){return{ok:!1,provider:"hl-precompiles",...np,error:String(t?.message||t).slice(0,160)}}}dt();Y();function yb(e={}){let t=e.spotSizes??e.spotHeldSizes;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Gs(e={},t,n){let r=String(t||""),o=yb(e);if(o){let a=hi(o[r]);if(a==null)throw new Error(`${n}: held spot required for ${r}`);return a}let i=hi(e.spotSize??e.spotHeldSize);if(i==null)throw new Error(`${n}: prepare requires spotSize of held spot`);return i}function Ks(e={},t=[],n){let r=yb(e);if(t.length>1){if(!r)throw new Error(`${n}: multi-coin live loop requires spotSizes map`);for(let o of t)if(hi(r[o])==null)throw new Error(`${n}: held spot required for ${o}`);return}if(r){let o=t[0];if(o&&hi(r[o])==null)throw new Error(`${n}: held spot required for ${o}`);return}if(hi(e.spotSize??e.spotHeldSize)==null)throw new Error(`${n}: live loop requires spotSize of held spot`)}var up=Number.MAX_SAFE_INTEGER,Ws=String(up);function hi(e){if(typeof e=="number")return Number.isFinite(e)&&e>0&&e<=up?e:null;if(typeof e!="string"||!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(e))return null;let[t,n=""]=e.split(".");if(t.length>Ws.length||t.length===Ws.length&&t>Ws||t===Ws&&/[1-9]/.test(n))return null;let r=Number(e);return Number.isFinite(r)&&r>0&&r<=up?r:null}function Rb(){return{ok:!0,provider:"hl-delta-neutral",exec:!1,execution:"armed-local",signing:"local-signer",broadcasting:"local-signer",armed:!1,signed:!1,broadcast:!1,note:"capability only. Scan/quote/prepare are public. Sign/submit stay on the owner-operated hl signer. Not automated."}}function Kt(e){let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}function Lb(e){let t=Kt(e);if(t==null)throw new Error("hl-delta-neutral: funding rate required");return t*24*365*100}function c2(e,t,n=4){let r=Kt(e),o=Kt(t),i=Number.isInteger(Number(n))?Number(n):4;if(!(r>0))throw new Error("hl-delta-neutral: notionalUsd must be > 0");if(!(o>0))throw new Error("hl-delta-neutral: markPx must be > 0");let a=10**i;return String(Math.floor(r/o*a+1e-12)/a)}function $b(e){let t=Array.isArray(e?.[0]?.universe)?e[0].universe:[],n=Array.isArray(e?.[1])?e[1]:[],r=[];for(let o=0;o<t.length;o+=1){let i=t[o]||{},a=n[o]||{},s=String(i.name||"").trim(),c=Kt(a.funding),l=Kt(a.markPx??a.oraclePx),u=Kt(a.openInterest)??0;!s||c==null||!(l>0)||r.push({coin:s,szDecimals:Number.isInteger(Number(i.szDecimals))?Number(i.szDecimals):4,funding:c,markPx:l,oraclePx:Kt(a.oraclePx),openInterest:u,fundingAprPct:Lb(c)})}return r}function Bb(e,t){if(!e?.coin)throw new Error("hl-delta-neutral: coin required");let n=Kt(e.funding);if(n==null)throw new Error("hl-delta-neutral: funding required");let r=Lb(n),o=n>0,i={coin:e.coin,notionalUsd:Kt(t),markPx:e.markPx,fundingHourly:n,fundingAprPct:r,targetDelta:0,spot:o?"hold-existing":"short-spot-not-in-light-path",perpSide:o?"sell":"buy",perpSize:o?c2(t,e.markPx,e.szDecimals):"0",verdict:o?r>=5?"carry":"watch":"skip",posture:"light hold-spot / short-perp carry. A farm tick may prepare the perp hedge unsigned. Hosted stays prepare-only."};if(!(i.notionalUsd>0))throw new Error("hl-delta-neutral: notionalUsd must be > 0");return i}async function Ep(e={},t={}){let n=Math.min(24,Math.max(1,Number(e.limit??8)||8)),r=Number(e.minOpenInterest??0),o=await Ke(t),i=$b(o).filter(a=>a.funding>0&&a.openInterest>=r).sort((a,s)=>s.funding-a.funding||s.openInterest-a.openInterest).slice(0,n);return{live:!0,source:"Hyperliquid metaAndAssetCtxs",considered:Array.isArray(o?.[0]?.universe)?o[0].universe.length:0,candidates:i,posture:"read-only funding scan. Positive funding only. No signing."}}async function Ap(e={},t={}){let n=String(e.coin||"").trim();if(!n)throw new Error("hl-delta-neutral: coin required");let r=Number(e.notionalUsd??e.notional??1e3),o=await Ke(t),i=$b(o).find(a=>a.coin===n);if(!i)throw new Error(`hl-delta-neutral: ${n} not in Hyperliquid meta`);return Bb(i,r)}async function _p(e={},t={}){Ub(e,t,"hl-delta-neutral");let n=Fb(e.maxNotionalUsd??25e3,"hl-delta-neutral"),r=await Ap(e,t);if(r.verdict==="skip")return N({...r,prepared:!1,oraclePrepared:!1,surface:"hl",reason:"negative funding is outside the light hold-spot path"},{provider:"hl-delta-neutral",kind:"hl-carry-hedge"});let o=Gs(e,r.coin,"hl-delta-neutral");if(!Mb.test(String(e.owner||"")))throw new Error("hl-delta-neutral: prepare requires owner");if(Number(r.perpSize)-o>1e-12)throw new Error("hl-delta-neutral: hedge cannot exceed held spot");let{hlPreparePerpOrder:i}=await Promise.resolve().then(()=>(xi(),Ip)),a=await i({coin:r.coin,side:r.perpSide,size:r.perpSize,type:e.orderType||"limit",price:e.price??r.markPx,owner:e.owner,maxNotionalUsd:n},{fetchImpl:t.fetchImpl,nowMs:t.nowMs});if(a?.signed===!0||a?.broadcast===!0)throw new Error("hl-delta-neutral: prepare cannot sign or broadcast");let s=a?.localSignerEnvelope||null,c=a?.localSignerBlockedReason||null;return N({...r,prepared:!!s,surface:"hl",hedge:a,localSignerEnvelope:s,localSignerBlockedReason:c,signed:!1,broadcast:!1,signing:s?"awaiting-hl-signer":"blocked",oraclePrepared:!!s},{provider:"hl-delta-neutral",kind:"hl-carry-hedge"})}var Mb=/^0x[0-9a-fA-F]{40}$/;function Ub(e,t,n){if((t.hosted===!0||t.keyless===!0)&&(e.farming===!0||typeof t.signImpl=="function"))throw new Error(`${n}: hosted/keyless cannot sign`);if(e.farming===!0||typeof t.signImpl=="function"||typeof t.prepareImpl=="function")throw new Error(`${n}: farm cannot sign; use oracle signer`)}function l2(e,t,n){Ub(e,t,n)}function u2(e={}){if(e.halted===!0)throw new Error("hl-delta-neutral: loop is halted");let t=e.mode==="live"?"live":"shadow",n=Array.isArray(e.coins||e.allowlist)?(e.coins||e.allowlist).map(String):[],r=e.maxCoins??1;if(typeof r!="number"&&!(typeof r=="string"&&/^(?:0|[1-9]\d*)$/.test(r)))throw new Error("hl-delta-neutral: maxCoins must be an integer");let o=Number(r);if(!Number.isSafeInteger(o))throw new Error("hl-delta-neutral: maxCoins must be an integer");if(o<1||o>8)throw new Error("hl-delta-neutral: maxCoins must be between 1 and 8");let i=Fb(e.maxNotionalUsd??e.notionalUsd??e.notional??1e3,"hl-delta-neutral");if(t==="live"&&n.length===0)throw new Error("hl-delta-neutral: live loop requires a coin allowlist");if(t==="live"&&Ks(e,n,"hl-delta-neutral"),t==="live"&&!Mb.test(String(e.owner||"")))throw new Error("hl-delta-neutral: live loop requires owner");return{mode:t,allowlist:n,maxCoins:o,maxNotionalUsd:i,intervalMs:Math.max(3e4,Number(e.intervalMs??3e5)||3e5)}}function Fb(e,t){let n=typeof e=="string"&&e===e.trim()&&/^(?:0\.\d+|[1-9]\d*(?:\.\d+)?)$/.test(e);if(typeof e!="number"&&!n)throw new Error(`${t}: maxNotionalUsd out of bounds`);let r=Number(e);if(!(r>0)||r>25e3)throw new Error(`${t}: maxNotionalUsd out of bounds`);return r}async function Db(e={},t={}){l2(e,t,"hl-delta-neutral");let n=u2(e),r=await Ep({limit:e.limit??16,minOpenInterest:e.minOpenInterest},t),o=new Set(n.allowlist),i=[],a=Math.floor(n.maxNotionalUsd/n.maxCoins);for(let s of r.candidates){if(o.size&&!o.has(s.coin))continue;let c=Bb(s,a);if(c.verdict!=="carry")continue;if(i.length>=n.maxCoins)break;if(n.mode==="shadow"){i.push({...c,mode:"shadow",surface:"hl",prepared:!1,signed:!1,broadcast:!1});continue}let l=await _p({coin:c.coin,notionalUsd:c.notionalUsd,owner:e.owner,orderType:e.orderType,price:e.price,maxNotionalUsd:a,spotSize:e.spotSize??e.spotHeldSize,spotSizes:e.spotSizes??e.spotHeldSizes},{fetchImpl:t.fetchImpl,nowMs:t.nowMs});i.push({...l,mode:"live",surface:"hl"})}return{loop:!0,mode:n.mode,surface:"hl",signer:"hl",considered:r.considered,actions:i,nextWaitMs:n.intervalMs,signed:i.some(s=>s.signed===!0),broadcast:i.some(s=>s.broadcast===!0),posture:"one tick. Prepares an unsigned hedge for oracle signer. Armed, not automated. Farm loop never signs or broadcasts."}}R();Y();Dr();var p2=new Set(["https://mainnet.zklighter.elliot.ai/api/v1/sendTx","https://testnet.zklighter.elliot.ai/api/v1/sendTx"]),ki=14,qb=(e,t,n=256)=>{if(typeof e!="string"||!e||e.length>n)throw new Error(`lighter: bounded ${t} required`);return e};function Hr(e,t,n){if(!Number.isSafeInteger(e)||e!==t)throw new Error(`lighter: ${n} must be exact numeric ${t}`)}function Pp(e){let t=String(e||"").replace(/\/$/,"");if(!p2.has(t))throw new Error("lighter: submitTo must be the official Lighter sendTx");return t}function Hb(e,t={}){if(e?.surface!=="lighter")throw new Error("lighter: surface lighter required");let n=e.artifact;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("lighter: structured artifact required");let r=qb(n.kind,"kind",48);if(r!=="lighter-order")throw new Error("lighter: unsupported Lighter kind");if(e.action!=="order")throw new Error("lighter: surface/action/kind mismatch");if(String(e.destination).toLowerCase()!=="lighter")throw new Error("lighter: destination must be lighter");let o=Pp(n.submitTo),i=n.marketIndex;if(typeof i!="number"||!Number.isSafeInteger(i)||i<0)throw new Error("lighter: marketIndex required");let a=Number(rr(n.accountIndex,"lighter: accountIndex"));if(!Number.isSafeInteger(a)||a<0)throw new Error("lighter: accountIndex required");let s=Number(rr(n.clientOrderIndex,"lighter: clientOrderIndex"));if(!Number.isSafeInteger(s)||s<0)throw new Error("lighter: clientOrderIndex required");Hr(n.orderType,0,"orderType"),Hr(n.timeInForce,1,"timeInForce"),Hr(n.reduceOnly,0,"reduceOnly"),Hr(n.triggerPrice,0,"triggerPrice"),Hr(n.orderExpiry,-1,"orderExpiry");let c=qb(n.symbol||n.coin,"symbol",32),l=Array.isArray(t.lighterMarkets)?t.lighterMarkets.map(String):[];if(l.length&&!l.includes(c)&&!l.includes(String(i))&&!l.includes("*"))throw new Error("lighter: market not allowed");if(n.side!=="buy"&&n.side!=="sell")throw new Error("lighter: side must be buy or sell");let u=mt(n.baseAmount,"lighter: baseAmount"),d=mt(n.price,"lighter: price");if(u>BigInt(Number.MAX_SAFE_INTEGER)||d>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("lighter: baseAmount and price must be safe integers");let p=Number(u),m=Number(d),f=Number(n.sizeDecimals??0),h=Number(n.priceDecimals??0);if(!Number.isInteger(f)||f<0||f>12)throw new Error("lighter: sizeDecimals required");if(!Number.isInteger(h)||h<0||h>12)throw new Error("lighter: priceDecimals required");let g=f+h,w=u*d,x=_e(n.notionalUsd,g,"lighter: notionalUsd");if(x<=0n)throw new Error("lighter: notionalUsd required");if(w!==x)throw new Error("lighter: notionalUsd must match size and price");let b=_e(t.maxNotionalUsd??Number.MAX_SAFE_INTEGER,g,"lighter: maxNotionalUsd");if(w>b)throw new Error("lighter: notional exceeds cap");let y=Ce(n.notionalUsd,"lighter: notionalUsd");return Hr(n.txType,ki,"txType"),Object.freeze({unit:"usd",value:String(y),notional:String(y),fee:"0",kind:r,symbol:c,marketIndex:i,side:n.side,baseAmount:p,price:m,submitTo:o,actionType:"create-order",amount:String(y)})}function m2(e){let t=e.owner||e.user||e.from;if(!/^0x[0-9a-fA-F]{40}$/.test(String(t||"")))throw new Error("lighter: owner address required for local-signer envelope");return String(t).toLowerCase()}function jb(e,t={},n={}){if(String(e?.kind)!=="lighter-order")throw new Error("lighter: prepared kind is not a local-signer surface");let r=Number(n.nowMs??Date.now()),o=Math.min(6e4,Math.max(1e3,Number(t.ttlMs??t.expiresInMs??3e4)||3e4)),i=Pp(e.submitTo),a={version:1,surface:"lighter",action:"order",owner:m2(t),destination:"lighter",tradeId:String(t.tradeId||`lighter:${e.symbol}:${e.marketIndex}:${e.clientOrderIndex}`),expiresAtMs:r+o,slippageBps:Number(t.slippageBps??0),fee:{oracleFeeBps:0},provider:"lighter-delta-neutral",artifact:{kind:"lighter-order",symbol:e.symbol,marketIndex:e.marketIndex,side:e.side,baseAmount:e.baseAmount,price:e.price,notionalUsd:e.notionalUsd,sizeDecimals:e.sizeDecimals??0,priceDecimals:e.priceDecimals??0,clientOrderIndex:e.clientOrderIndex,txType:e.txType??ki,submitTo:i,accountIndex:e.accountIndex??t.accountIndex??null,orderType:e.orderType,timeInForce:e.timeInForce,reduceOnly:e.reduceOnly,triggerPrice:e.triggerPrice,orderExpiry:e.orderExpiry}};return Hb(a,{lighterMarkets:t.lighterMarkets||["*"],maxNotionalUsd:t.maxNotionalUsd??Number.MAX_SAFE_INTEGER}),a}var Vb="https://mainnet.zklighter.elliot.ai",Wb="https://testnet.zklighter.elliot.ai";function f2(e={}){return e.testnet||process.env.LIGHTER_TESTNET==="1"?Wb:Vb}function Gb(){return{ok:!0,provider:"lighter-delta-neutral",exec:!1,execution:"armed-local",signing:"local-signer",broadcasting:"local-signer",armed:!1,signed:!1,broadcast:!1,note:"capability only. Scan/quote/prepare are public. Sign/submit stay on the owner-operated lighter signer. Not automated."}}function Sn(e){let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}function h2(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 Kb(e){let t=Sn(e);if(t==null)throw new Error("lighter: funding rate required");return t*24*365*100}function g2(e,t,n=4){let r=Sn(e),o=Sn(t),i=Number.isInteger(Number(n))?Number(n):4;if(!(r>0))throw new Error("lighter: notionalUsd must be > 0");if(!(o>0))throw new Error("lighter: markPx must be > 0");let a=10**i;return Math.floor(r/o*a+1e-12)}function zb(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?e:null}function Cp(e,t){let n=Array.isArray(e?.funding_rates)?e.funding_rates:[],r=Array.isArray(t?.order_book_details)?t.order_book_details:[],o=new Map;for(let a of r){let s=zb(a.market_id);s!=null&&o.set(s,a)}let i=[];for(let a of n){if(String(a.exchange||"")!=="lighter")continue;let s=zb(a.market_id);if(s==null)continue;let c=o.get(s),l=Sn(c?.mark_price??c?.index_price),u=Sn(a.rate),d=String(a.symbol||c?.symbol||"").trim();!d||u==null||!(l>0)||i.push({coin:d,symbol:d,marketIndex:s,funding:u,markPx:l,openInterest:Sn(c?.open_interest)??0,sizeDecimals:Number(c?.supported_size_decimals??c?.size_decimals??4),priceDecimals:Number(c?.supported_price_decimals??c?.price_decimals??2),fundingAprPct:Kb(u)})}return i}function Yb(e,t){if(!e?.symbol&&!e?.coin)throw new Error("lighter: symbol required");let n=Sn(e.funding);if(n==null)throw new Error("lighter: funding required");let r=Kb(n),o=n>0,i={coin:e.symbol||e.coin,symbol:e.symbol||e.coin,marketIndex:e.marketIndex,notionalUsd:Sn(t),markPx:e.markPx,fundingHourly:n,fundingAprPct:r,targetDelta:0,spot:o?"hold-existing":"short-spot-not-in-light-path",perpSide:o?"sell":"buy",baseAmount:o?g2(t,e.markPx,e.sizeDecimals):0,price:Math.round(Number(e.markPx)*10**Number(e.priceDecimals||0)),sizeDecimals:e.sizeDecimals,priceDecimals:e.priceDecimals,verdict:o?r>=5?"carry":"watch":"skip",posture:"light hold-spot / short-perp carry on Lighter. Armed via official sendTx. Not automated."};if(!(i.notionalUsd>0))throw new Error("lighter: notionalUsd must be > 0");return i}async function Tp(e={}){let t=f2(e),n=e.fetchImpl,r=await S(`${t}/api/v1/funding-rates`,{fetchImpl:n,retries:0}),o=await S(`${t}/api/v1/orderBookDetails`,{fetchImpl:n,retries:0});return{funding:r,books:o}}async function Jb(e={}){let{funding:t,books:n}=await Tp(e);return{live:!0,source:"Lighter funding-rates + orderBookDetails",markets:Cp(t,n)}}async function Np(e={},t={}){let n=Math.min(24,Math.max(1,Number(e.limit??8)||8)),{funding:r,books:o}=await Tp(t),i=Cp(r,o).filter(a=>a.funding>0).sort((a,s)=>s.funding-a.funding||s.openInterest-a.openInterest).slice(0,n);return{live:!0,source:"Lighter funding-rates + orderBookDetails",considered:Array.isArray(r?.funding_rates)?r.funding_rates.filter(a=>a.exchange==="lighter").length:0,candidates:i,posture:"read-only Lighter funding scan. Positive funding only. No signing."}}async function Op(e={},t={}){let n=String(e.coin||e.symbol||"").trim();if(!n)throw new Error("lighter: coin required");let r=Number(e.notionalUsd??e.notional??1e3),{funding:o,books:i}=await Tp(t),a=Cp(o,i).find(s=>s.symbol===n);if(!a)throw new Error(`lighter: ${n} not in Lighter funding`);return Yb(a,r)}async function Rp(e={},t={}){Qb(e,t,"lighter");let n=Zb(e.maxNotionalUsd??25e3,"lighter");if(typeof e.accountIndex!="number"||!Number.isSafeInteger(e.accountIndex)||e.accountIndex<0)throw new Error("lighter: accountIndex required");let r=e.accountIndex,o=await Op(e,t);if(o.verdict==="skip")return N({...o,prepared:!1,oraclePrepared:!1,surface:"lighter",reason:"negative funding is outside the light hold-spot path"},{provider:"lighter-delta-neutral",kind:"lighter-order"});let i=Gs(e,o.coin,"lighter");if(!Xb.test(String(e.owner||"")))throw new Error("lighter: prepare requires owner");if(o.baseAmount/10**Number(o.sizeDecimals||0)-i>1e-12)throw new Error("lighter: hedge cannot exceed held spot");let s=!!(t.testnet||process.env.LIGHTER_TESTNET==="1"),c=Number(o.sizeDecimals||0)+Number(o.priceDecimals||0),l=h2(BigInt(o.baseAmount)*BigInt(o.price),c);if(e.clientOrderIndex!=null&&(typeof e.clientOrderIndex!="number"||!Number.isSafeInteger(e.clientOrderIndex)||e.clientOrderIndex<0))throw new Error("lighter: clientOrderIndex must be a safe integer");let u={...o,targetNotionalUsd:o.notionalUsd,notionalUsd:l,kind:"lighter-order",surface:"lighter",side:o.perpSide,clientOrderIndex:e.clientOrderIndex??Date.now()%1e9,accountIndex:r,orderType:0,timeInForce:1,reduceOnly:0,triggerPrice:0,orderExpiry:-1,txType:ki,submitTo:`${s?Wb:Vb}/api/v1/sendTx`,signed:!1,broadcast:!1},d=null,p=null;try{d=jb(u,{...e,maxNotionalUsd:n},t)}catch(f){p=String(f?.message||f).slice(0,200)}return N({...u,prepared:!!d,signing:d?"awaiting-lighter-signer":"blocked",localSignerEnvelope:d,localSignerBlockedReason:p,oraclePrepared:!!d},{provider:"lighter-delta-neutral",kind:"lighter-order"})}var Xb=/^0x[0-9a-fA-F]{40}$/;function Qb(e,t,n){if((t.hosted===!0||t.keyless===!0)&&(e.farming===!0||typeof t.signImpl=="function"))throw new Error(`${n}: hosted/keyless cannot sign`);if(e.farming===!0||typeof t.signImpl=="function"||typeof t.prepareImpl=="function")throw new Error(`${n}: farm cannot sign; use oracle signer`)}function y2(e,t,n){Qb(e,t,n)}function b2(e={}){if(e.halted===!0)throw new Error("lighter: loop is halted");let t=e.mode==="live"?"live":"shadow",n=Array.isArray(e.coins||e.allowlist)?(e.coins||e.allowlist).map(String):[],r=e.maxCoins??1;if(typeof r!="number"&&!(typeof r=="string"&&/^(?:0|[1-9]\d*)$/.test(r)))throw new Error("lighter: maxCoins must be an integer");let o=Number(r);if(!Number.isSafeInteger(o))throw new Error("lighter: maxCoins must be an integer");if(o<1||o>8)throw new Error("lighter: maxCoins must be between 1 and 8");let i=Zb(e.maxNotionalUsd??e.notionalUsd??e.notional??1e3,"lighter");if(t==="live"&&n.length===0)throw new Error("lighter: live loop requires a coin allowlist");if(t==="live"&&Ks(e,n,"lighter"),t==="live"&&!Xb.test(String(e.owner||"")))throw new Error("lighter: live loop requires owner");let a=e.accountIndex;if(t==="live"&&(typeof a!="number"||!Number.isSafeInteger(a)||a<0))throw new Error("lighter: live loop requires accountIndex");return{mode:t,allowlist:n,maxCoins:o,maxNotionalUsd:i,accountIndex:a}}function Zb(e,t){let n=typeof e=="string"&&e===e.trim()&&/^(?:0\.\d+|[1-9]\d*(?:\.\d+)?)$/.test(e);if(typeof e!="number"&&!n)throw new Error(`${t}: maxNotionalUsd out of bounds`);let r=Number(e);if(!(r>0)||r>25e3)throw new Error(`${t}: maxNotionalUsd out of bounds`);return r}async function ew(e={},t={}){y2(e,t,"lighter");let n=b2(e),r=await Np({limit:e.limit??16},t),o=new Set(n.allowlist),i=[],a=Math.floor(n.maxNotionalUsd/n.maxCoins);for(let s of r.candidates){if(o.size&&!o.has(s.symbol)&&!o.has(s.coin))continue;let c=Yb(s,a);if(c.verdict!=="carry")continue;if(i.length>=n.maxCoins)break;if(n.mode==="shadow"){i.push({...c,mode:"shadow",surface:"lighter",prepared:!1,signed:!1,broadcast:!1});continue}let l=await Rp({coin:c.symbol,notionalUsd:c.notionalUsd,maxNotionalUsd:a,owner:e.owner,accountIndex:n.accountIndex,spotSize:e.spotSize??e.spotHeldSize,spotSizes:e.spotSizes??e.spotHeldSizes},{fetchImpl:t.fetchImpl,nowMs:t.nowMs,testnet:t.testnet});i.push({...l,mode:"live",surface:"lighter"})}return{loop:!0,mode:n.mode,surface:"lighter",signer:"lighter",considered:r.considered,actions:i,signed:i.some(s=>s.signed===!0),broadcast:i.some(s=>s.broadcast===!0),posture:"one tick. Prepares an unsigned official sendTx for oracle signer. Armed, not automated. Farm loop never signs or broadcasts."}}R();var v2="https://clob.polymarket.com",x2="https://gamma-api.polymarket.com";function Si(e={}){return(e.clobUrl||process.env.POLY_CLOB_URL||v2).replace(/\/$/,"")}function tw(e={}){return(e.gammaUrl||process.env.POLY_GAMMA_URL||x2).replace(/\/$/,"")}async function Lp(e={}){return S(`${Si(e)}/time`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs})}async function nw(e={}){let t=await Lp(e);return{ok:t!=null&&t!=="",time:t}}async function rw({limit:e=5,offset:t=0,...n}={},r={}){let o=new URLSearchParams({limit:String(e),offset:String(t),...Object.fromEntries(Object.entries(n).filter(([,i])=>i!=null).map(([i,a])=>[i,String(a)]))});return S(`${tw(r)}/markets?${o}`,{fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs})}async function ow(e,t={}){if(!e)throw new Error("polyBook requires tokenId");let n=new URLSearchParams({token_id:String(e)});return S(`${Si(t)}/book?${n}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function iw(e,t={}){if(!e)throw new Error("polyMidpoint requires tokenId");let n=new URLSearchParams({token_id:String(e)});return S(`${Si(t)}/midpoint?${n}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function aw(e,t={}){if(!e)throw new Error("polySpread requires tokenId");let n=new URLSearchParams({token_id:String(e)});return S(`${Si(t)}/spread?${n}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function sw(e,{side:t="buy"}={},n={}){if(!e)throw new Error("polyPrice requires tokenId");let r=new URLSearchParams({token_id:String(e),side:String(t)});return S(`${Si(n)}/price?${r}`,{fetchImpl:n.fetchImpl,timeoutMs:n.timeoutMs})}async function cw({limit:e=5,offset:t=0,...n}={},r={}){let o=new URLSearchParams({limit:String(e),offset:String(t),...Object.fromEntries(Object.entries(n).filter(([,i])=>i!=null).map(([i,a])=>[i,String(a)]))});return S(`${tw(r)}/events?${o}`,{fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs})}pe();R();import{createHash as lw}from"node:crypto";var jr="mainnet-beta",S2="https://api.mainnet-beta.solana.com",$p="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";function I2(e={}){return String(e.rpcUrl||process.env.SOLANA_RPC_URL||S2).trim()}function he(e,t="address"){let n=String(e||"").trim();if(!/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(n))throw new Error(`solana-rpc: ${t} must be a base58 public key`);return n}function E2(e,t){return t?[...e,{commitment:t}]:e}async function Ii(e,t=[],n={}){let r=String(e||"");if(r==="sendTransaction"||r==="sendRawTransaction"||r==="requestAirdrop"||r==="requestAirDrop"||/airdrop/i.test(r)||/^send/i.test(r))throw new Error(`solana-rpc: ${r} refused \u2014 @oracle-agent/oracle is prepare-only (no broadcast/airdrop)`);let o=await S(I2(n),{method:"POST",body:{jsonrpc:"2.0",id:n.id||1,method:e,params:t},fetchImpl:n.fetchImpl,timeoutMs:n.timeoutMs??12e3});if(o?.error)throw new Error(`solana-rpc ${e}: ${o.error.message||JSON.stringify(o.error)}`);return o?.result}async function Bp(e={},t={}){let n=e.commitment?[{commitment:e.commitment}]:[],r=await Ii("getLatestBlockhash",n,t);return{provider:"solana-rpc",cluster:jr,blockhash:r?.value?.blockhash||null,lastValidBlockHeight:r?.value?.lastValidBlockHeight??null,slot:r?.context?.slot??null,raw:r}}async function uw(e={}){try{let[t,n]=await Promise.all([Ii("getHealth",[],e),Bp({},e)]);return{ok:t==="ok",provider:"solana-rpc",cluster:jr,health:t,latestBlockhash:n,exec:!1}}catch(t){return{ok:!1,provider:"solana-rpc",cluster:jr,error:String(t?.message||t),exec:!1}}}async function Zs(e={},t={}){let n=he(e.address||e.owner,"address"),r=await Ii("getBalance",E2([n],e.commitment),t);return{provider:"solana-rpc",cluster:jr,address:n,lamports:String(r?.value??0),slot:r?.context?.slot??null,raw:r}}function A2(e={}){let t=e.account?.data?.parsed?.info||{},n=t.tokenAmount||{};return{pubkey:e.pubkey,mint:t.mint||null,owner:t.owner||null,amount:String(n.amount??"0"),decimals:n.decimals??null,uiAmount:n.uiAmount??null,uiAmountString:n.uiAmountString??null,raw:e}}async function Ei(e={},t={}){let n=he(e.owner||e.address,"owner"),r=e.mint?{mint:he(e.mint,"mint")}:{programId:he(e.programId||$p,"token program")},o={encoding:"jsonParsed"};e.commitment&&(o.commitment=e.commitment);let i=await Ii("getTokenAccountsByOwner",[n,r,o],t),a=Array.isArray(i?.value)?i.value.map(A2):[];return{provider:"solana-rpc",cluster:jr,owner:n,filter:r,slot:i?.context?.slot??null,accounts:a,raw:i}}function _2(e){let t=String(e||"").trim();if(!/^[A-Za-z0-9+/]+={0,2}$/.test(t)||t.length%4!==0)throw new Error("solana-rpc: transaction must be base64");return t}function P2(e,t){let n=0,r=0,o=t;for(let i=0;i<3;i++){if(o>=e.length)throw new Error("solana-rpc: transaction shortvec truncated");let a=e[o++];if(n|=(a&127)<<r,(a&128)===0)return{value:n,offset:o};r+=7}throw new Error("solana-rpc: transaction shortvec too long")}function C2(e){let t=Buffer.from(e,"base64");try{let n=P2(t,0),r=n.offset+n.value*64;if(r>=t.length)throw new Error("missing message");return lw("sha256").update(t.subarray(r)).digest("hex")}catch{return lw("sha256").update(t).digest("hex")}}async function dw(e={},t={}){let n=_2(e.transaction||e.swapTransaction),r={encoding:"base64",sigVerify:!!e.sigVerify,replaceRecentBlockhash:e.replaceRecentBlockhash!==!1};e.commitment&&(r.commitment=e.commitment);let o=await Ii("simulateTransaction",[n,r],t),i=o?.value||{};return{provider:"solana-rpc",cluster:jr,ok:i.err==null,transactionHash:C2(n),err:i.err??null,logs:i.logs||[],unitsConsumed:i.unitsConsumed??null,replacementBlockhash:i.replacementBlockhash||null,slot:o?.context?.slot??null,raw:o}}R();var N2="mainnet",O2="https://mempool.space/api",R2="https://mempool.space/testnet/api";function Lt(e={}){return String(e.network||process.env.BTC_NETWORK||N2).trim().toLowerCase()==="testnet"?"testnet":"mainnet"}function Up(e={}){return e.baseUrl?String(e.baseUrl).replace(/\/$/,""):process.env.BTC_ESPLORA_URL?String(process.env.BTC_ESPLORA_URL).replace(/\/$/,""):Lt(e)==="testnet"?R2:O2}function Mp(e){let t=String(e||"");try{let n=new URL(t);(n.username||n.password)&&(n.username="[REDACTED]",n.password="");for(let r of[...n.searchParams.keys()])/^(key|api[_-]?key|token|secret|password|auth|bearer)$/i.test(r)&&n.searchParams.set(r,"[REDACTED]");t=n.toString().replace(/\/$/,"")}catch{}return t.replace(/(https?:\/\/)([^\s/:@]+):([^\s@/]+)@/gi,"$1[REDACTED]@").replace(/([?&](?:key|api[_-]?key|token|secret|password|auth|bearer)=)[^&\s]+/gi,"$1[REDACTED]")}function kt(e,t="address"){let n=String(e||"").trim();if(!/^(bc1|tb1|bcrt1)[a-z0-9]{20,90}$/i.test(n)&&!/^[13mn2][a-km-zA-HJ-NP-Z1-9]{25,34}$/.test(n))throw new Error(`bitcoin-esplora: ${t} must look like a Bitcoin address`);return n}function L2(e,t="txHex"){let n=String(e||"").trim().toLowerCase().replace(/^0x/,"");if(!/^[0-9a-f]+$/.test(n)||n.length<20||n.length%2!==0)throw new Error(`bitcoin-esplora: ${t} must be even-length hex`);return n}async function Fp(e,t={}){let n=`${Up(t)}${e.startsWith("/")?e:`/${e}`}`,o=await(t.fetchImpl||fetch)(n,{method:"GET",headers:{accept:"application/json,text/plain;q=0.9,*/*;q=0.8"},signal:AbortSignal.timeout(t.timeoutMs??12e3)}),i=await o.text();if(!o.ok)throw new Error(`bitcoin-esplora GET ${e}: HTTP ${o.status} ${i.slice(0,160)}`);return i}async function ec(e,t={}){let n=await Fp(e,t);try{return JSON.parse(n)}catch{return n}}async function pw(e={}){try{let t=await Fp("/blocks/tip/height",e),n=Number(t);return{ok:Number.isFinite(n)&&n>0,provider:"bitcoin-esplora",network:Lt(e),baseUrl:Mp(Up(e)),tipHeight:n,exec:!1,signing:"user-wallet"}}catch(t){return{ok:!1,provider:"bitcoin-esplora",network:Lt(e),baseUrl:Mp(Up(e)),error:Mp(t?.message||t),exec:!1}}}async function mw(e={}){let t=await Fp("/blocks/tip/height",e);return{provider:"bitcoin-esplora",network:Lt(e),tipHeight:Number(t)}}async function fw(e={}){try{let t=await ec("/v1/fees/recommended",e);return{provider:"bitcoin-esplora",network:Lt(e),fastestFee:t.fastestFee??null,halfHourFee:t.halfHourFee??null,hourFee:t.hourFee??null,economyFee:t.economyFee??null,minimumFee:t.minimumFee??null,raw:t}}catch{return{provider:"bitcoin-esplora",network:Lt(e),fastestFee:null,halfHourFee:null,hourFee:null,note:"fee endpoint unavailable on this Esplora host"}}}async function tc(e={},t={}){let n=kt(e.address||e.addr,"address"),r=await ec(`/address/${n}`,t),o=r.chain_stats||{},i=r.mempool_stats||{},a=Number(o.funded_txo_sum||0)+Number(i.funded_txo_sum||0),s=Number(o.spent_txo_sum||0)+Number(i.spent_txo_sum||0);return{provider:"bitcoin-esplora",network:Lt(t),address:n,balanceSats:String(a-s),chainStats:o,mempoolStats:i,raw:r}}async function hw(e={},t={}){let n=kt(e.address||e.addr,"address"),r=await ec(`/address/${n}/utxo`,t),o=Array.isArray(r)?r:[];return{provider:"bitcoin-esplora",network:Lt(t),address:n,count:o.length,totalSats:String(o.reduce((i,a)=>i+Number(a.value||0),0)),utxos:o.map(i=>({txid:i.txid,vout:i.vout,value:Number(i.value||0),status:i.status||null}))}}async function gw(e={},t={}){let n=String(e.txid||e.txId||"").trim().toLowerCase();if(!/^[0-9a-f]{64}$/.test(n))throw new Error("bitcoin-esplora: txid must be 64-char hex");let r=await ec(`/tx/${n}`,t);return{provider:"bitcoin-esplora",network:Lt(t),txid:n,confirmed:!!r.status?.confirmed,fee:r.fee??null,size:r.size??null,weight:r.weight??null,vinCount:Array.isArray(r.vin)?r.vin.length:null,voutCount:Array.isArray(r.vout)?r.vout.length:null,raw:r}}async function yw(e={},t={}){let n=L2(e.txHex||e.hex||e.transaction,"txHex");return{provider:"bitcoin-esplora",network:Lt(t),encoding:"hex",txHex:n,byteLength:n.length/2,note:"full decode is wallet/client-side or via bitcoinjs; Esplora returns broadcast acceptance only"}}vt();var Dp="https://ordinals.com";function nc(e={}){return String(e.baseUrl||process.env.BTC_META_API_URL||process.env.UNISAT_API_URL||"").trim().replace(/\/$/,"")}var B2=["open-api.unisat.io","open-api-testnet.unisat.io","api.bestinslot.xyz","api.hiro.so"];function bw(e={}){let t=e.apiKey||process.env.UNISAT_API_KEY||process.env.BESTINSLOT_API_KEY||process.env.BTC_META_API_KEY||"",n=!1;try{let r=nc(e);if(r){let o=new URL(r).host,i=new URL(r).protocol,a=/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(o);n=B2.includes(o)&&(i==="https:"||a)}}catch{n=!1}return Ie({accept:"application/json","user-agent":"oracle-btc-meta/0.1"},{authorization:t?`Bearer ${t}`:"","x-api-key":t},n)}async function zr(e,t={}){let r=await(t.fetchImpl||fetch)(e,{method:"GET",headers:bw(t),signal:AbortSignal.timeout(t.timeoutMs??12e3)}),o=await r.text(),i;try{i=JSON.parse(o)}catch{i=o}if(!r.ok)throw new Error(`bitcoin-meta GET ${e}: HTTP ${r.status} ${String(o).slice(0,160)}`);return i}async function ww(e={}){let t=nc(e),n=null;try{let i=await(e.fetchImpl||fetch)("https://ordinals.com/r/blockheight",{signal:AbortSignal.timeout(8e3)});n=Number(await i.text())}catch{n=null}if(!t)return{ok:n!=null,provider:"bitcoin-meta",indexerConfigured:!1,ordinalsComTip:n,note:"Set BTC_META_API_URL and/or UNISAT_API_KEY / BESTINSLOT_API_KEY for balances. Marketplace = Satflow (SATFLOW_API_KEY). Magic Eden BTC is dead.",capabilities:{tip:n!=null,runeBalances:!1,inscriptions:!1,marketplace:!1}};let r={ok:!1,path:null,status:null};for(let o of["/v1/indexer/brc20/best-height","/v1/health","/health","/"])try{let a=await(e.fetchImpl||fetch)(`${t}${o}`,{headers:bw(e),signal:AbortSignal.timeout(8e3)});if(r={ok:a.status>0&&a.status<500,path:o,status:a.status},a.ok)break}catch{}return{ok:r.ok||n!=null,provider:"bitcoin-meta",indexerConfigured:!0,baseUrl:t,probe:r,ordinalsComTip:n,apiKeyPresent:!!(process.env.UNISAT_API_KEY||process.env.BESTINSLOT_API_KEY||process.env.BTC_META_API_KEY),capabilities:{tip:n!=null,runeBalances:!0,inscriptions:!0,marketplace:!!process.env.SATFLOW_API_KEY}}}async function rc(e={},t={}){let n=kt(e.address||e.addr,"address"),r=nc(t);if(!r)return{provider:"bitcoin-meta",address:n,ok:!1,balances:[],error:"no indexer configured (set BTC_META_API_URL or vendor API key env)"};let o=[`${r}/v1/indexer/address/${n}/runes/balance-list?start=0&limit=100`,`${r}/v1/runes/address/${n}`,`${r}/runes/balance/${n}`,`${r}/address/${n}/runes`],i=null;for(let a of o)try{let s=await zr(a,t),c=M2(s);return{provider:"bitcoin-meta",address:n,ok:!0,count:c.length,balances:c,source:a}}catch(s){i=s}return{provider:"bitcoin-meta",address:n,ok:!1,balances:[],error:String(i?.message||i||"all indexer paths failed")}}function M2(e){let t=e?.data?.detail||e?.data?.list||e?.data||e?.balances||e?.results||e?.runes||(Array.isArray(e)?e:[]);return(Array.isArray(t)?t:[]).map(r=>({rune:r.rune||r.runeid||r.runeId||r.spacedRune||r.name||r.ticker||null,runeId:r.runeid||r.runeId||r.id||null,amount:String(r.amount??r.balance??r.total??r.qty??"0"),symbol:r.symbol||null,divisibility:r.divisibility??r.div??null,raw:r}))}async function Vr(e={},t={}){let n=kt(e.address||e.addr,"address"),r=nc(t);if(!r)return{provider:"bitcoin-meta",address:n,ok:!1,inscriptions:[],error:"no indexer configured \u2014 address-indexed lookups need a keyed indexer (BTC_META_API_URL + UNISAT_API_KEY / BESTINSLOT_API_KEY). ordinals.com recursive is keyless but has no address index.",unknownNotEmpty:!0,keylessAlternatives:["btc_inscription_info (by inscription id)","btc_meta_health"]};let o=Math.min(Number(e.limit||50),200),i=[`${r}/v1/indexer/address/${n}/inscription-data?cursor=0&size=${o}`,`${r}/v1/inscriptions/address/${n}?limit=${o}`,`${r}/address/${n}/inscriptions?limit=${o}`],a=null;for(let s of i)try{let c=await zr(s,t),l=U2(c);return{provider:"bitcoin-meta",address:n,ok:!0,count:l.length,inscriptions:l,source:s}}catch(c){a=c}return{provider:"bitcoin-meta",address:n,ok:!1,inscriptions:[],error:String(a?.message||a||"all indexer paths failed")}}async function vw(e={},t={}){let n=String(e.inscriptionId||e.id||"").trim();if(!/^[0-9a-f]{64}i\d+$/i.test(n))throw new Error("bitcoin-meta: inscriptionId must look like <64-hex-txid>i<index>");let r=t.ordinalsBase||Dp,o=await zr(`${r}/r/inscription/${n}`,t);return{provider:"bitcoin-meta",source:"ordinals.com/r",keyless:!0,inscriptionId:n,info:o}}async function xw(e={},t={}){let n=String(e.inscriptionId||e.id||"").trim();if(!/^[0-9a-f]{64}i\d+$/i.test(n))throw new Error("bitcoin-meta: inscriptionId must look like <64-hex-txid>i<index>");let r=t.ordinalsBase||Dp,o=Number(e.page||0),i=await zr(`${r}/r/children/${n}${o?`/${o}`:""}`,t);return{provider:"bitcoin-meta",source:"ordinals.com/r",keyless:!0,inscriptionId:n,page:o,children:Array.isArray(i?.ids)?i.ids:[],more:!!i?.more}}async function kw(e={},t={}){let n=t.ordinalsBase||Dp,r=e.height??await zr(`${n}/r/blockheight`,t),o=await zr(`${n}/r/blockinfo/${Number(r)}`,t);return{provider:"bitcoin-meta",source:"ordinals.com/r",keyless:!0,height:Number(r),info:o}}function U2(e){let t=e?.data?.inscription||e?.data?.detail||e?.data?.list||e?.data||e?.inscriptions||e?.results||(Array.isArray(e)?e:[]);return(Array.isArray(t)?t:[]).map(r=>({id:r.inscriptionId||r.id||r.inscription_id||null,number:r.inscriptionNumber??r.number??null,sat:r.sat||r.satoshi||null,contentType:r.contentType||r.content_type||null,utxo:r.utxo||r.output||(r.txid!=null?`${r.txid}:${r.vout??r.n}`:null),raw:r}))}vt();Y();var D2=["unsigned","notsigned","tosign","signable"],q2=new Set(["requiresusersignature","requiressignature","needssignature","signaturerequired","signaturesrequired","signingready","signaturecount","signaturethreshold","requiredsignatures","signatureneeded","hassignature","allowsignatures","requestsignature","multisig","cosig","msig"]),H2=new Set(["sig","sigs","scriptsig","witness","psbt","finalizedpsbt","completepsbt","finalpsbt","psbtfinalized","serializedtransaction"]);function qp(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function j2(e){return D2.some(t=>e.startsWith(t))||q2.has(e)}function z2(e){let t=String(e);if(!/^[\x20-\x7e]+$/.test(t))return!0;let n=qp(t);return j2(n)?!1:H2.has(n)?!0:n.includes("signed")||n.includes("signature")||n.endsWith("sig")||n.endsWith("sigs")}function V2(e){let t=Number(e?.v),n=String(e?.r||""),r=String(e?.s||"");return[0,1,27,28].includes(t)&&/^0x[0-9a-f]{2,64}$/i.test(n)&&/^0x[0-9a-f]{2,64}$/i.test(r)}function Hp(e,t=0,n=new Set,r={nodes:0}){if(e==null||typeof e!="object")return[];if(t>16)return["<max-depth>"];if(n.has(e))return[];if(r.nodes+=1,r.nodes>2048)return["<max-nodes>"];if(n.add(e),Array.isArray(e))return e.flatMap(c=>Hp(c,t+1,n,r));let o=[];for(let[c,l]of Object.entries(e)){if(z2(c)){o.push(c);continue}o.push(...Hp(l,t+1,n,r))}let a=Object.keys(e).map(qp).some(c=>c.endsWith("psbt")||c.endsWith("psbtbase64")),s=Object.entries(e).some(([c,l])=>/complete|finalized|isfinal/.test(qp(c))&&l===!0);return a&&s&&o.push("psbt(complete)"),V2(e)&&o.push("v/r/s"),o}function Yt(e,t){let n=Hp(t);if(n.length)throw new Error(`${e}: refused a pre-signed transaction payload from the API (fields: ${[...new Set(n)].join(", ")}) \u2014 @oracle-agent/oracle is prepare-only and will not bind signed material into a prepared envelope`)}var W2="https://api.satflow.com/v1";function Sw(e={}){return Ae({provider:"satflow",defaultUrl:W2,hosts:["api.satflow.com"],url:e.baseUrl||process.env.SATFLOW_API_URL})}function oc(e={}){return Sw(e).baseUrl}function zp(e={}){return String(e.apiKey||process.env.SATFLOW_API_KEY||process.env.BTC_SATFLOW_API_KEY||"").trim()}function G2(e={}){return Ie({accept:"application/json","content-type":"application/json","user-agent":"oracle-btc-satflow/0.1"},{"x-api-key":zp(e)},Sw(e).trusted)}async function In(e,{method:t="GET",body:n,opts:r={}}={}){if(!zp(r))throw new Error("satflow: SATFLOW_API_KEY not set (request key via Satflow docs form)");let i=`${oc(r)}${e.startsWith("/")?e:`/${e}`}`,s=await(r.fetchImpl||fetch)(i,{method:t,headers:G2(r),body:n!=null?JSON.stringify(n):void 0,signal:AbortSignal.timeout(r.timeoutMs??2e4)}),c=await s.text(),l;try{l=JSON.parse(c)}catch{l=c}if(!s.ok)throw new Error(`satflow ${t} ${e}: HTTP ${s.status} ${String(c).slice(0,200)}`);return l}async function Iw(e={}){if(!!!zp(e))return{ok:!1,provider:"satflow",baseUrl:oc(e),apiKeyPresent:!1,marketplace:"satflow",magicEdenOrdinals:"deprecated-dead",note:"Set SATFLOW_API_KEY. Magic Eden BTC ordinals marketplace is shut down \u2014 do not use ME."};try{return await In("/collection/stats/floors?type=ordinals",{opts:e}),{ok:!0,provider:"satflow",baseUrl:oc(e),apiKeyPresent:!0,marketplace:"satflow",magicEdenOrdinals:"deprecated-dead",capabilities:{floors:!0,walletContents:!0,purchaseIntent:!0,listIntent:!0,bidIntent:!0}}}catch(n){return{ok:!1,provider:"satflow",baseUrl:oc(e),apiKeyPresent:!0,error:String(n?.message||n).slice(0,200),magicEdenOrdinals:"deprecated-dead"}}}async function Ew(e={},t={}){let n=String(e.type||"ordinals").toLowerCase();if(!["ordinals","runes"].includes(n))throw new Error("satflow: type must be ordinals|runes");let r=new URLSearchParams({type:n});e.ids&&r.set("ids",Array.isArray(e.ids)?e.ids.join(","):String(e.ids));let o=await In(`/collection/stats/floors?${r}`,{opts:t});return{provider:"satflow",type:n,floors:o,magicEdenOrdinals:"deprecated-dead"}}async function Aw(e={},t={}){let n=String(e.collectionId||e.id||e.slug||"").trim();if(!n)throw new Error("satflow: collectionId required");let r=new URLSearchParams({id:n});e.type&&r.set("type",e.type);let o=await In(`/collection/stats?${r}`,{opts:t});return{provider:"satflow",collectionId:n,stats:o}}async function _w(e={},t={}){let n=String(e.inscriptionId||e.id||"").trim();if(!n)throw new Error("satflow: inscriptionId required");let r=new URLSearchParams({id:n});return{provider:"satflow",item:await In(`/item?${r}`,{opts:t})}}async function ic(e={},t={}){let n=kt(e.address||e.addr,"address"),r=new URLSearchParams({address:n});e.type&&r.set("type",e.type),e.limit!=null&&r.set("limit",String(e.limit)),e.offset!=null&&r.set("offset",String(e.offset));let o=await In(`/address/wallet-contents?${r}`,{opts:t});return{provider:"satflow",address:n,contents:o}}async function Pw(e={},t={}){let n=e.collectionIds||e.ids||e.collectionId;if(!n)throw new Error("satflow: collectionIds required");let r=new URLSearchParams({ids:Array.isArray(n)?n.join(","):String(n)});return e.limit!=null&&r.set("limit",String(e.limit)),{provider:"satflow",listings:await In(`/orders/floor?${r}`,{opts:t})}}var K2=new Set(["body","execute","fetchImpl","opts","apiKey","baseUrl","timeoutMs","maxSats","operator"]);function Cw(e={},t=null){let n=e.body&&typeof e.body=="object"?e.body:e,r={};for(let[o,i]of Object.entries(n))K2.has(o)||t&&!t.has(o)||i!==void 0&&(r[o]=i);return r}var Y2=new Set(["listing_id","listingId","inscription_id","inscriptionId","runes_output","runesOutput","buyer_address","buyerAddress","ord_address","receive_address","payment_address","pay_address","tap_key","public_key","publicKey","fee_rate","feeRate","price","quantity","slug","collection_slug"]),J2=new Set(["inscription_id","inscriptionId","runes_output","runesOutput","ord_address","receive_address","price","tap_key","collection_slug","expires_at"]);function jp(e){if(!e||typeof e!="object")return null;let t=[e.price,e.priceSats,e.price_sats,e.totalSats,e.total_sats,e.amount,e.satoshis];for(let n of t){if(n==null)continue;let r=String(n).trim();if(/^\d+$/.test(r))return BigInt(r)}return null}function X2(e={},{psbt:t,priceSats:n,nowMs:r=Date.now()}={}){if(!t)throw new Error("satflow: local signer envelope requires unsigned PSBT");let o=kt(e.owner||e.buyer_address||e.buyerAddress||e.payment_address||e.pay_address,"owner"),i=kt(e.destination||e.seller_address||e.sellerAddress||e.payment_destination,"destination"),a=String(e.network||"bitcoin").toLowerCase();if(!["bitcoin","mainnet","testnet","signet","regtest"].includes(a))throw new Error("satflow: unsupported Bitcoin network");return{version:1,surface:"btc",action:"transfer",owner:o,destination:i,tradeId:e.tradeId||`satflow-${e.listing_id||e.listingId||e.inscription_id||e.inscriptionId||"purchase"}`,slippageBps:0,expiresAtMs:Number(r)+Math.min(Math.max(Number(e.ttlMs??e.expiresInMs??3e4)||3e4,1e3),6e4),fee:{oracleFeeBps:0},artifact:{network:a,psbt:t},meta:{provider:"satflow",kind:"purchase-intent",priceSats:String(n)}}}async function Tw(e={},t={}){let n=Cw(e,Y2);if(!n||Object.keys(n).length===0)throw new Error("satflow: purchase body required (see docs.satflow.com intent/satflow-purchase)");let r=e.maxSats??e.body?.maxSats;if(r==null)throw new Error("satflow: maxSats is required to prepare a purchase \u2014 an uncapped buy has no spend ceiling");let o=BigInt(String(r).trim());if(o<=0n)throw new Error("satflow: maxSats must be a positive integer sat amount");let i=jp(n);if(i!=null&&i>o)throw new Error(`satflow: requested price ${i} sats exceeds maxSats cap ${o}`);let a=await In("/intent/satflow-purchase",{method:"POST",body:n,opts:t}),s=jp(a)??jp(a?.intent);if(s==null)throw new Error("satflow: purchase intent did not report a price \u2014 refusing to return an unverifiable PSBT");if(s>o)throw new Error(`satflow: purchase price ${s} sats exceeds maxSats cap ${o} \u2014 PSBT withheld`);Yt("satflow",a);let c=a?.unsignedPSBTBase64||a?.unsignedPsbtBase64||a?.unsigned_psbt||null,l=null,u=null;try{l=X2(e,{psbt:c,priceSats:s,nowMs:t.nowMs})}catch(d){u=String(d?.message||d).slice(0,200)}return N({provider:"satflow",kind:"purchase-intent",executionReady:!1,signingReady:!1,broadcastReady:!1,requiresUserSignature:!0,marketplace:"satflow",magicEdenOrdinals:"deprecated-dead",priceSats:s.toString(),maxSats:o.toString(),intent:a,unsignedPsbt:c,localSignerEnvelope:l,localSignerBlockedReason:u,note:"Sign PSBT in a Bitcoin wallet. Broadcast only through the user's wallet or an explicitly armed Bitcoin execution plane."})}async function ac(e={},t={}){let n=Cw(e,J2);if(!n.inscription_id&&!n.runes_output&&!n.inscriptionId&&!n.runesOutput)throw new Error("satflow: list requires inscription_id or runes_output");let r=await In("/intent/sell",{method:"POST",body:n,opts:t});return Yt("satflow",r),N({provider:"satflow",kind:"list-intent",requiresUserSignature:!0,marketplace:"satflow",listingRequest:n,intent:r,unsignedPsbt:r?.unsignedListingPSBTBase64||r?.unsigned_psbt||null,note:"Sign listing PSBTs in a Bitcoin wallet; listing broadcast is outside the data plane."})}R();Y();var cc="https://lite-api.jup.ag/swap/v1",Vp="So11111111111111111111111111111111111111112",Rw="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",Z2=100,Nw=2e4;function Lw(e={}){return String(e.baseUrl||process.env.JUPITER_SWAP_API_URL||cc).replace(/\/$/,"")}function Ai(e,t="amount"){try{let n=BigInt(String(e));if(n<=0n)throw new Error("nonpositive");return n.toString()}catch{throw new Error(`jupiter: ${t} must be a positive integer string`)}}function $w(e){let t=e==null?50:Number(e);if(!Number.isInteger(t)||t<0)throw new Error("jupiter: slippageBps must be a non-negative integer");if(t>Z2)throw new Error("jupiter: slippage exceeds hard 100 bps cap");return t}function sc(e,t){return e==null?t:!!e}function eL(e){let t=String(e||"").trim();if(!/^[A-Za-z0-9+/]+={0,2}$/.test(t)||t.length%4!==0)throw new Error("jupiter: swapTransaction must be base64");return t}function tL(e,t=0){let n=0,r=0,o=t;for(;o<e.length&&o-t<3;){let i=e[o++];if(n|=(i&127)<<r,(i&128)===0)return{value:n,offset:o};r+=7}return null}function Bw(e){let t=Buffer.from(e,"base64"),n=tL(t,0);if(!n||n.value!==1)throw new Error("jupiter: unsigned swapTransaction must declare exactly one signature slot");let r=n.offset+n.value*64;if(r>=t.length)throw new Error("jupiter: Solana transaction missing message bytes");if(t.subarray(n.offset,r).some(i=>i!==0))throw new Error("jupiter: swapTransaction already contains signature material");return t.subarray(r).toString("base64")}function _i(e={},{quotedAtMs:t=Date.now(),ttlMs:n=Nw}={}){let r=he(e.inputMint,"inputMint"),o=he(e.outputMint,"outputMint"),i=Ai(e.inAmount,"inAmount"),a=Ai(e.outAmount,"outAmount"),s=Ai(e.otherAmountThreshold??e.outAmount,"otherAmountThreshold"),c=$w(e.slippageBps??50),l=(BigInt(a)-BigInt(a)*BigInt(c)/10000n).toString();if(s!==l)throw new Error("jupiter: otherAmountThreshold does not match serialized min-out");return{mode:"solana-jupiter-quote",provider:"jupiter",venue:"jupiter-swap-v1",inputMint:r,outputMint:o,inAmount:i,outAmount:a,otherAmountThreshold:s,slippageBps:c,contextSlot:e.contextSlot??null,quotedAtMs:t,expiresAtMs:t+Math.min(Math.max(Number(n)||Nw,1e3),3e4)}}function Wp({userPublicKey:e,guard:t,swapTransaction:n,args:r={},response:o={}}){if(t.inputMint!==Vp)throw new Error("jupiter: local signer supports native SOL input only");if(BigInt(o?.prioritizationFeeLamports??0)!==0n)throw new Error("jupiter: local signer requires zero priority fee until exact fee accounting is supplied");let i=Bw(n),a=Ai(r.exactFeeLamports??o.exactFeeLamports??"5000","exactFeeLamports");return{version:1,surface:"sol",action:"swap",owner:e,destination:t.outputMint,tradeId:r.tradeId||`jupiter-${t.inputMint.slice(0,6)}-${t.outputMint.slice(0,6)}-${t.inAmount}`,slippageBps:t.slippageBps,expiresAtMs:t.expiresAtMs,fee:{oracleFeeBps:5},artifact:{cluster:r.cluster||"mainnet",provider:"jupiter",inputMint:t.inputMint,outputMint:t.outputMint,inAmount:t.inAmount,outAmount:t.outAmount,otherAmountThreshold:t.otherAmountThreshold,slippageBps:t.slippageBps,jupiterProgram:r.jupiterProgram||o.jupiterProgram||"JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4",messageBase64:i,exactFeeLamports:a}}}var nL=new Set(["BPFLoaderUpgradeab1e11111111111111111111111","BPFLoader2111111111111111111111111111111111","BPFLoader1111111111111111111111111111111111"]),rL="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function Ow(e){if(typeof e!="string"||!e.length)return!1;let t=0n;for(let o of e){let i=rL.indexOf(o);if(i<0)return!1;t=t*58n+BigInt(i)}let n=t.toString(16);n.length%2&&(n="0"+n);let r=n.length/2;for(let o of e)if(o==="1")r++;else break;return r===32}async function Mw(e={},t={}){let n=e.rpc||t.solanaRpc||process.env.SOLANA_RPC||"https://api.mainnet-beta.solana.com",r=t.fetchImpl||fetch,o=await r(`${cc}/program-id-to-label`,{signal:AbortSignal.timeout(Number(t.timeoutMs)||15e3)});if(!o.ok)throw new Error(`jupiter venue map failed: HTTP ${o.status}`);let i=await o.json(),a=Object.entries(i),s=a.filter(([p])=>Ow(p)),c=[],l=a.filter(([p])=>!Ow(p)).map(([p,m])=>({programId:p,label:m,reason:"malformed program id"}));if(e.verify===!1)return{source:`${cc}/program-id-to-label`,verified:s.map(([p,m])=>({programId:p,label:m})),unresolved:l,verifiedOnChain:!1,totals:{fromRouterMap:a.length,verified:s.length}};let u=async p=>{let f=await(await r(n,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(p),signal:AbortSignal.timeout(Number(t.timeoutMs)||2e4)})).json();if(f.error)throw new Error(f.error.message);return f.result};for(let p=0;p<s.length;p+=90){let m=s.slice(p,p+90),f=null;for(let h=0;h<3&&!f;h++)try{f=await u({jsonrpc:"2.0",id:1,method:"getMultipleAccounts",params:[m.map(([g])=>g),{encoding:"base64",dataSlice:{offset:0,length:0}}]})}catch{await new Promise(g=>setTimeout(g,2e3*(h+1)))}if(!f){for(let[h,g]of m)l.push({programId:h,label:g,reason:"rpc batch failed after 3 attempts"});continue}f.value.forEach((h,g)=>{let[w,x]=m[g];h&&h.executable===!0&&nL.has(h.owner)?c.push({programId:w,label:x,owner:h.owner}):l.push({programId:w,label:x,reason:h?h.executable!==!0?"not executable":`unknown owner ${h.owner}`:"account not found"})}),p+90<s.length&&await new Promise(h=>setTimeout(h,700))}let d=new Set(c.map(p=>p.label.replace(/\s+(CLMM|CP|V\d+|Launchlab|DLMM|Pools?)$/i,"").trim()));return{source:`${cc}/program-id-to-label`,verifiedOnChain:!0,verifiedAt:new Date().toISOString(),totals:{fromRouterMap:a.length,verified:c.length,unresolved:l.length,distinctLabels:new Set(c.map(p=>p.label)).size,distinctBrands:d.size},verified:c.sort((p,m)=>p.label.localeCompare(m.label)),unresolved:l}}async function Uw(e={}){try{return{ok:!0,provider:"jupiter",outAmount:(await lc({inputMint:Vp,outputMint:Rw,amount:"1000000",slippageBps:50},e)).quote.outAmount,exec:!1}}catch(t){return{ok:!1,provider:"jupiter",error:String(t?.message||t),exec:!1}}}async function lc(e={},t={}){let n=he(e.inputMint||e.fromMint||Vp,"inputMint"),r=he(e.outputMint||e.toMint||Rw,"outputMint"),o=Ai(e.amount||e.inAmount,"amount"),i=$w(e.slippageBps??e.maxSlippageBps??50),a=new URL(`${Lw(t)}/quote`);a.searchParams.set("inputMint",n),a.searchParams.set("outputMint",r),a.searchParams.set("amount",o),a.searchParams.set("slippageBps",String(i)),a.searchParams.set("swapMode",e.swapMode||"ExactIn"),e.onlyDirectRoutes!=null&&a.searchParams.set("onlyDirectRoutes",String(!!e.onlyDirectRoutes)),e.platformFeeBps!=null&&a.searchParams.set("platformFeeBps",String(e.platformFeeBps));let s=await S(a.toString(),{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),c=_i({...s,slippageBps:i},t);return{provider:"jupiter",chain:"solana-mainnet-beta",quoteReady:!0,executionReady:!1,inputMint:n,outputMint:r,amount:o,quote:s,solanaGuard:c}}function oL(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}async function Fw(e={},t={}){let n=he(e.userPublicKey||e.owner||e.wallet,"userPublicKey"),r=e.quoteResponse?{quote:e.quoteResponse,solanaGuard:_i(e.quoteResponse,t)}:await lc(e,t),o=r.quote,i=r.solanaGuard||_i(o,t);if(sc(e.dynamicSlippage,!1)===!0)throw new Error("jupiter: dynamicSlippage would override the enforced slippage ceiling \u2014 pass an explicit slippageBps instead");let a=await S(`${Lw(t)}/swap`,{method:"POST",body:oL({quoteResponse:o,userPublicKey:n,wrapAndUnwrapSol:sc(e.wrapAndUnwrapSol,!0),dynamicComputeUnitLimit:sc(e.dynamicComputeUnitLimit,!0),dynamicSlippage:!1,asLegacyTransaction:sc(e.asLegacyTransaction,!0),prioritizationFeeLamports:e.prioritizationFeeLamports??0}),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),s=eL(a?.swapTransaction);Bw(s),Yt("jupiter",a);let c=a?.quoteResponse??a?.quote??null,l=["inAmount","outAmount","otherAmountThreshold","inputMint","outputMint"],u=!1;if(c&&typeof c=="object"){for(let m of l){let f=o?.[m],h=c?.[m];if(f==null||h==null)throw new Error(`jupiter: echoed quote is incomplete \u2014 missing ${m}`);if(String(f)!==String(h))throw new Error(`jupiter: swap response ${m} (${h}) does not match the quoted ${m} (${f}) \u2014 refusing to prepare`)}u=!0}let d=null,p=null;try{d=Wp({userPublicKey:n,guard:i,swapTransaction:s,args:e,response:a})}catch(m){p=String(m?.message||m).slice(0,200)}return N({provider:"jupiter",chain:"solana-mainnet-beta",prepareReady:!0,executionReady:!1,signingReady:!1,broadcastReady:!1,requiresUserSignature:!0,verifiedAgainstQuote:u,userPublicKey:n,quote:o,solanaGuard:i,swapTransaction:s,localSignerEnvelope:d,localSignerBlockedReason:p,swapTransactionEncoding:"base64",lastValidBlockHeight:a?.lastValidBlockHeight??null,prioritizationFeeLamports:a?.prioritizationFeeLamports??null,computeUnitLimit:a?.computeUnitLimit??null,raw:a},{provider:"jupiter",kind:"jupiter-swap"})}Kn();Yo();cn();_r();Cr();import{getAddress as aL}from"ethers";var Kp=Object.freeze(["uniswap-v2","uniswap-v3","uniswap-v4","aerodrome","curve","balancer","meteora-dlmm","pancakeswap","sushiswap"]),qw="0x0000000000000000000000000000000000000000",Hw=/^0x[0-9a-fA-F]{40}$/,sL=25,uc=Object.freeze([["removalGasUsd","estimateRemovalGasUsd"],["swapCostUsd","estimateSwapCostUsd"],["bridgeCostUsd","estimateBridgeCostUsd"],["addLiquidityGasUsd","estimateAddLiquidityGasUsd"],["priceImpactUsd","estimatePriceImpactUsd"]]);function Pi(e,t){let n=String(e??"").trim();if(!n)throw new Error(`${t} is required`);if(Hw.test(n))try{return aL(n)}catch{throw new Error(`${t} is not a valid EVM address`)}return n}function dc(e,t){let n=e?.[t];if(typeof n!="function")throw new Error(`lp-liquidity-ranker: opts.${t} must be a function`);return n}function cL(e){if(!e||typeof e!="object")throw new Error("candidate must be an object");let t=Number(e.chainId);if(!Number.isInteger(t)||t<=0)throw new Error("chainId must be a positive integer");let n=String(e.venue??"").trim().toLowerCase();if(!n)throw new Error("venue is required");let r=Pi(e.poolAddress,"poolAddress"),o=e.token;if(!o||typeof o!="object")throw new Error("token is required");let i=String(o.symbol??"").trim();if(!i)throw new Error("token.symbol is required");let a=Pi(o.address,"token.address"),s=null;if(o.decimals!=null&&(s=Number(o.decimals),!Number.isInteger(s)||s<0||s>255))throw new Error("token.decimals must be a uint8 when provided");let c=Number(e.liquidityUsd);if(!Number.isFinite(c)||c<0)throw new Error("liquidityUsd must be a non-negative finite number");let l=n==="uniswap-v4"||e.isV4===!0,u=null;if(e.hook!=null){if(typeof e.hook!="object")throw new Error("hook must be an object when provided");u=Object.freeze({address:e.hook.address!=null?Pi(e.hook.address,"hook.address"):qw,dynamicFee:e.hook.dynamicFee===!0,reviewed:e.hook.reviewed===!0})}let d=e.id!=null?String(e.id):`${n}:${t}:${r}`;return Object.freeze({id:d,chainId:t,venue:n,poolAddress:r,token:Object.freeze({symbol:i,address:a,decimals:s}),liquidityUsd:c,isV4:l,hook:u})}function lL(e){if(!Kp.includes(e.venue))return`unsupported venue "${e.venue}"; supported: ${Kp.join(", ")}`;if(e.isV4){if(!e.hook)return"uniswap-v4 candidate is missing hook disclosure; failing closed";if(e.hook.dynamicFee)return"uniswap-v4 pool uses a dynamic fee; fee is not knowable in advance, failing closed";if(e.hook.address!==qw&&!e.hook.reviewed)return`uniswap-v4 pool has an unreviewed hook (${e.hook.address}); failing closed`}return null}async function uL(e,t,n){let r=dc(n,"resolveTokenIdentity"),o;try{o=await r({chainId:e.chainId,address:e.token.address,symbol:e.token.symbol})}catch(l){return{ok:!1,reason:`identity resolution failed: ${l?.message??l}`}}if(!o||typeof o!="object")return{ok:!1,reason:"identity unresolved"};if(o.ambiguous)return{ok:!1,reason:o.reason??"ambiguous token identity"};if(!o.canonicalId)return{ok:!1,reason:"identity resolver returned no canonicalId"};if(o.canonicalId!==t.canonicalId)return{ok:!1,reason:`token resolves to canonical id "${o.canonicalId}", expected "${t.canonicalId}"`};let i=Number(o.homeChainId);if(!Number.isInteger(i)||i<=0)return{ok:!1,reason:"identity resolver returned no homeChainId"};let a;try{a=Pi(o.canonicalAddress,"identity resolver canonicalAddress")}catch(l){return{ok:!1,reason:l.message}}let s=e.token.address;return(Hw.test(a)?a===s:a.toLowerCase()===String(s).toLowerCase())?{ok:!0,canonicalId:o.canonicalId,homeChainId:i,canonicalAddress:a,decimals:o.decimals??e.token.decimals??null}:{ok:!1,reason:`token address ${e.token.address} on chain ${e.chainId} does not match the canonical address ${a}; possible wrapped variant or spoof`}}async function dL(e,t,n){let r={},o=[];for(let[s,c]of uc){let l=dc(n,c),u;try{u=await l(e,t)}catch(p){return{ok:!1,reason:`${c} failed for ${e.id}: ${p?.message??p}`}}if(u==null||!Number.isFinite(Number(u))){r[s]=null,o.push(s);continue}let d=Number(u);if(d<0)return{ok:!1,reason:`${c} returned a negative cost for ${e.id}`};r[s]=d}let i=uc.reduce((s,[c])=>s+(r[c]??0),0),a=o.length===0;return{ok:!0,costs:Object.freeze(r),missingLegs:Object.freeze(o),grossOnly:!a,measuredCostUsd:i,totalCostUsd:a?i:null,netUsd:a?t.amountUsd-i:null}}function Gp(e){return Object.freeze({id:e.id,chainId:e.chainId,venue:e.venue,poolAddress:e.poolAddress,token:e.token,liquidityUsd:e.liquidityUsd,canonicalId:e.identity.canonicalId,homeChainId:e.identity.homeChainId})}function Dw(e,t){let n=null;for(let r of e){if(!n){n=r;continue}let o=t(r),i=t(n);(o>i||o===i&&r.id<n.id)&&(n=r)}return n}async function pL(e={},t={}){let n=String(e.canonicalId??"").trim();if(!n)throw new Error("lp-liquidity-ranker: canonicalId is required");let r=Number(e.amountUsd);if(!Number.isFinite(r)||r<=0)throw new Error("lp-liquidity-ranker: amountUsd must be a positive finite number");if(!Array.isArray(e.candidates)||e.candidates.length===0)throw new Error("lp-liquidity-ranker: candidates must be a non-empty array");let o=e.materialityThresholdBps??sL;if(!Number.isInteger(o)||o<0)throw new Error("lp-liquidity-ranker: materialityThresholdBps must be a non-negative integer");dc(t,"resolveTokenIdentity");for(let[,h]of uc)dc(t,h);let i=Object.freeze({canonicalId:n,amountUsd:r,materialityThresholdBps:o}),a=[],s=[],c=new Set,l=null;for(let h=0;h<e.candidates.length;h+=1){let g=e.candidates[h],w=g?.id!=null?String(g.id):`candidates[${h}]`,x;try{x=cL(g)}catch(E){a.push({id:w,reason:E.message});continue}if(c.has(x.id)){a.push({id:x.id,reason:"duplicate candidate id"});continue}c.add(x.id);let b=lL(x);if(b){a.push({id:x.id,reason:b});continue}let y=await uL(x,i,t);if(!y.ok){a.push({id:x.id,reason:y.reason});continue}if(l==null)l=y.homeChainId;else if(y.homeChainId!==l){a.push({id:x.id,reason:`ambiguous home chain for canonical token "${n}": got ${y.homeChainId}, expected ${l}`});continue}let k=await dL(x,i,t);if(!k.ok){a.push({id:x.id,reason:k.reason});continue}s.push({...x,identity:y,...k})}let u=[];if(s.length===0)return Object.freeze({ok:!0,canonicalId:n,homeChainId:l,amountUsd:r,evaluated:e.candidates.length,accepted:0,rejected:Object.freeze(a),deepestLiquidity:null,netBest:null,netRankingComplete:!1,preparationEligible:!1,runnersUp:Object.freeze([]),warnings:Object.freeze(["no candidate passed identity, venue, or cost validation"])});let d=Dw(s,h=>h.liquidityUsd),p=s.filter(h=>!h.grossOnly&&h.netUsd!=null),m=Dw(p,h=>h.netUsd);for(let h of s)h.grossOnly&&u.push(`${h.id}: gas/fees not fully accounted (missing: ${h.missingLegs.join(", ")}); missing costs were not treated as zero`);m?d.id!==m.id&&u.push(`${d.id} has the deepest liquidity ($${d.liquidityUsd}) but ${m.id} nets more after costs; these are intentionally different answers`):u.push("net-best migration is unavailable until every ranking cost leg is measured; missing gas is never treated as zero and deepest liquidity is not claimed as net-best"),p.length<s.length&&u.push("partial-cost candidates were excluded from net ranking; missing gas was not treated as zero");let f=s.filter(h=>h.id!==m?.id).sort((h,g)=>h.netUsd==null&&g.netUsd==null?h.id<g.id?-1:1:h.netUsd==null?1:g.netUsd==null?-1:g.netUsd-h.netUsd||(h.id<g.id?-1:1)).map(h=>{let g=m!=null&&h.netUsd!=null,w=g?m.netUsd-h.netUsd:null,x=g?Math.round(w/r*1e4):null;return Object.freeze({...Gp(h),netUsd:h.netUsd,totalCostUsd:h.totalCostUsd,grossOnly:h.grossOnly,missingLegs:h.missingLegs,marginUsd:w,marginBps:x,material:x!=null&&x>o})});return Object.freeze({ok:!0,canonicalId:n,homeChainId:l,amountUsd:r,evaluated:e.candidates.length,accepted:s.length,rejected:Object.freeze(a),deepestLiquidity:Gp(d),netBest:m?Object.freeze({...Gp(m),netUsd:m.netUsd,totalCostUsd:m.totalCostUsd,costs:m.costs,grossOnly:!1,missingLegs:m.missingLegs}):null,netRankingComplete:!!m&&p.length===s.length,preparationEligible:!1,runnersUp:Object.freeze(f),warnings:Object.freeze(u)})}async function jw(e={}){let t=String(e.canonicalId??"").trim(),n=Number(e.homeChainId);if(!t)throw new Error("lp-liquidity-ranker: canonicalId is required");if(!Number.isInteger(n)||n<=0)throw new Error("lp-liquidity-ranker: homeChainId must be a positive integer");if(!Array.isArray(e.canonicalAssets)||e.canonicalAssets.length===0)throw new Error("lp-liquidity-ranker: canonicalAssets must be a non-empty array");let r=new Map;for(let c of e.canonicalAssets){let l=Number(c?.chainId);if(!Number.isInteger(l)||l<=0)throw new Error("lp-liquidity-ranker: canonical asset chainId must be positive");if(r.has(l))throw new Error(`lp-liquidity-ranker: duplicate canonical asset for chain ${l}`);let u=Pi(c?.address,"canonical asset address"),d=c?.decimals==null?null:Number(c.decimals);if(d!=null&&(!Number.isInteger(d)||d<0||d>255))throw new Error("lp-liquidity-ranker: canonical asset decimals must be a uint8");r.set(l,Object.freeze({canonicalAddress:u,decimals:d}))}let o={resolveTokenIdentity:async({chainId:c})=>{let l=r.get(Number(c));return l?{canonicalId:t,homeChainId:n,...l}:{ambiguous:!0,reason:`no exact canonical asset mapping for chain ${c}`}}},i=(e.candidates??[]).map(c=>({...c,costs:c?.costs&&typeof c.costs=="object"?{...c.costs}:{}})),a=new Map(i.map(c=>[String(c?.id??`${String(c?.venue??"").toLowerCase()}:${Number(c?.chainId)}:${String(c?.poolAddress??"")}`),c.costs]));for(let[c,l]of uc)o[l]=async u=>a.get(u.id)?.[c]??null;let s=await pL({...e,canonicalId:t,candidates:i},o);return Object.freeze({...s,evidenceMode:"caller-supplied",warnings:Object.freeze(["canonical mappings, pool liquidity, and migration costs were caller-supplied and not independently live-verified",...s.warnings])})}async function zw(){return Object.freeze({ok:!0,execution:"analysis-only",supportedVenues:Kp,note:"Deepest liquidity and net-best migration are reported separately; no signing or broadcasting."})}cn();var fL=Object.freeze([/(?:^|\s)Bearer\s+\S+/i,/-----BEGIN [A-Z ]*PRIVATE KEY-----/i,/\b(?:sk-|xprv|gh[pousr]_|github_pat_|AKIA|ASIA)[A-Za-z0-9_/-]{12,}\b/i,/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/,/\b(?:0x)?[0-9a-f]{64}\b/i,/(?<![1-9A-HJ-NP-Za-km-z])[59KLc][1-9A-HJ-NP-Za-km-z]{50,51}(?![1-9A-HJ-NP-Za-km-z])/,/(?<![1-9A-HJ-NP-Za-km-z])[1-9A-HJ-NP-Za-km-z]{64,88}(?![1-9A-HJ-NP-Za-km-z])/]),hL=new Set(["apikey","key","token","accesstoken","secret","password","passwd","auth","authorization","bearer","signertoken","credential","credentials","clientsecret","privatekey","xapikey","accesskey","refreshtoken"]),gL=Object.freeze(["apikey","accesskey","privatekey","clientsecret","accesstoken","refreshtoken","signertoken","credential","password","passwd","authorization","bearer","secret","token"]);function yL(e){return String(e??"").replace(/[^a-z0-9]/gi,"").toLowerCase()}function bL(e){let t;try{t=new URL(e)}catch{return!1}if(t.username||t.password)return!0;for(let n of t.searchParams.keys()){let r=yL(n);if(hL.has(r)||gL.some(o=>r.includes(o)))return!0}return!1}function Vw(e){try{let t=decodeURIComponent(e);return t===e?null:t}catch{return null}}var wL=/[a-z][a-z0-9+.-]{1,15}(?::\/\/|%3a%2f%2f)\S+/gi;function vL(e){return e.replace(/[),.;:!?'"\]}]+$/,"")}function xL(e){let t=e.match(wL)||[];for(let n of t){let r=vL(n),o=Vw(r),i=o?Vw(o):null;for(let a of[r,o,i])if(a&&bL(a))return!0}return!1}function Ww(e){return typeof e!="string"||e.length===0?!1:fL.some(t=>t.test(e))?!0:xL(e)}var Gw=/^0x[0-9a-fA-F]{40}$/,kL=new Set(["source","reviewedAt","evidenceHash","txHash"]),SL=1e4,Jt=e=>String(e??"").trim().toLowerCase();function IL(e,t){if(!e||typeof e!="object"||!String(e.source??"").trim())throw new Error(`lp-destination-discovery: ${t}.provenance.source is required`);if(Object.keys(e).filter(s=>!kL.has(s)).length)throw new Error(`lp-destination-discovery: ${t}.provenance contains unsupported fields`);let r=String(e.source).trim();if(r.length>512||Ww(r))throw new Error(`lp-destination-discovery: ${t}.provenance.source is unsafe`);let o=e.evidenceHash==null?null:String(e.evidenceHash).trim();if(o!=null&&!/^[0-9a-f]{64}$/i.test(o))throw new Error(`lp-destination-discovery: ${t}.provenance.evidenceHash must be a sha256 digest`);let i=e.txHash==null?null:String(e.txHash).trim();if(i!=null&&!/^0x[0-9a-f]{64}$/i.test(i))throw new Error(`lp-destination-discovery: ${t}.provenance.txHash must be an EVM transaction hash`);let a=e.reviewedAt==null?null:String(e.reviewedAt).trim();if(a!=null&&!Number.isFinite(Date.parse(a)))throw new Error(`lp-destination-discovery: ${t}.provenance.reviewedAt must be ISO time`);return Object.freeze({source:r,reviewedAt:a,evidenceHash:o,txHash:i})}function Kw(e,t){if(!e||typeof e!="object")throw new Error(`lp-destination-discovery: ${t} is required`);let n=Number(e.chainId),r=String(e.token0??"").trim(),o=String(e.token1??"").trim();if(!Number.isInteger(n)||n<=0)throw new Error(`lp-destination-discovery: ${t}.chainId must be positive`);if(!Gw.test(r)||!Gw.test(o)||Jt(r)===Jt(o))throw new Error(`lp-destination-discovery: ${t} requires distinct exact token0/token1 addresses`);return Object.freeze({...e,chainId:n,token0:r,token1:o,provenance:IL(e.provenance,t)})}function EL(e,t){if(!String(e.dexId??"").toLowerCase().includes("v4"))return{eligible:!0,reason:null};let n=t.v4;if(!n)return{eligible:!1,reason:"Uniswap V4 metadata is unreviewed"};if(n.dynamicFee===!0)return{eligible:!1,reason:"Uniswap V4 dynamic fee is not preparation-eligible"};let r=Jt(n.hook);return r&&r!=="0x0000000000000000000000000000000000000000"&&n.reviewed!==!0?{eligible:!1,reason:"Uniswap V4 hook is unreviewed"}:{eligible:!0,reason:null}}function AL(e){let t=e?.best;if(!t||t.quality!=="FULL")return null;let n=Number(t.gasUsd),r=Number(t.feeUsd);return t.gasUsd==null||t.feeUsd==null||!Number.isFinite(n)||!Number.isFinite(r)?null:n+r}async function Yw({source:e,destination:t,amountIn:n,index:r},o,i){if(n==null)return{requested:!1,measured:!1,costUsd:null,quote:null};let a=e[`token${r}`],s=t[`token${r}`];if(e.chainId===t.chainId&&Jt(a)===Jt(s))return{requested:!0,measured:!0,costUsd:0,quote:null,kind:"none",amountIn:String(n)};let c=e.chainId===t.chainId?{chainId:e.chainId,tokenIn:a,tokenOut:s,amountIn:String(n)}:{fromChainId:e.chainId,toChainId:t.chainId,tokenIn:a,tokenOut:s,amountIn:String(n)},l=e.chainId===t.chainId?"swap":"bridge";try{let u=l==="swap"?await o.bestSwapRoute(c,i):await o.bestBridgeRoute(c,i),d=AL(u);return{requested:!0,measured:d!=null,costUsd:d,quote:u,kind:l,amountIn:String(n)}}catch(u){return{requested:!0,measured:!1,costUsd:null,quote:null,kind:l,amountIn:String(n),error:u?.message??String(u)}}}function _L(e){let t=e.minLiquidityBpsOfDeepest??SL;if(!Number.isInteger(t)||t<1||t>1e4)throw new Error("lp-destination-discovery: minLiquidityBpsOfDeepest must be an integer from 1 to 10000");if(e.minLiquidityUsd==null)return{bps:t,minLiquidityUsd:null};let n=Number(e.minLiquidityUsd);if(!Number.isFinite(n)||n<0)throw new Error("lp-destination-discovery: minLiquidityUsd must be a non-negative number");return{bps:t,minLiquidityUsd:n}}function PL(e,t,n){if(e.venueReviewEligible===!1)return{destinationEligible:!1,destinationIneligibleReason:e.ineligibleReason};if(e.liquidityUsd==null)return{destinationEligible:!1,destinationIneligibleReason:"reported USD liquidity is unknown"};let r=Number(e.liquidityUsd);if(!Number.isFinite(r)||r<=0)return{destinationEligible:!1,destinationIneligibleReason:"reported USD liquidity is not positive"};if(n.minLiquidityUsd!=null&&r<n.minLiquidityUsd)return{destinationEligible:!1,destinationIneligibleReason:`liquidity $${r} is below the $${n.minLiquidityUsd} floor`};if(!t||t.liquidityUsd==null)return{destinationEligible:!1,destinationIneligibleReason:"no eligible deepest pool"};let o=Number(t.liquidityUsd)*n.bps/1e4;return r<o?{destinationEligible:!1,destinationIneligibleReason:`shallower than the deepest eligible pool ($${r} < $${o} required)`}:{destinationEligible:!0,destinationIneligibleReason:null}}function Jw(e,t,n="max"){return[...e].sort((r,o)=>(n==="max"?t(o)-t(r):t(r)-t(o))||String(r.poolAddress).localeCompare(String(o.poolAddress)))[0]??null}async function Xw(e={},t={}){let n=Kw(e.sourcePair,"sourcePair");if(!Array.isArray(e.destinationPairs))throw new Error("lp-destination-discovery: destinationPairs must be an array");let r=e.destinationPairs.map((v,A)=>Kw(v,`destinationPairs[${A}]`)),o=new Map;for(let v of r){if(o.has(v.chainId))throw new Error(`lp-destination-discovery: duplicate destination mapping for chain ${v.chainId}`);o.set(v.chainId,v)}let i=_L(e),a=t.chainConfigs??(await Promise.resolve().then(()=>(Mr(),Wd))).CHAIN_CONFIGS,s=e.amounts?.token0!=null||e.amounts?.token1!=null,c=s&&r.some(v=>v.chainId===n.chainId&&(Jt(v.token0)!==Jt(n.token0)||Jt(v.token1)!==Jt(n.token1))),l=s&&r.some(v=>v.chainId!==n.chainId),u=c&&!t.bestSwapRoute||l&&!t.bestBridgeRoute?await Promise.resolve().then(()=>(Cd(),sy)):null,d={discoverExactPairPools:t.discoverExactPairPools??W0,bestSwapRoute:t.bestSwapRoute??u?.bestSwapRoute,bestBridgeRoute:t.bestBridgeRoute??u?.bestBridgeRoute},p=e.limit??10,m=await Promise.all(a.map(async v=>{let A=o.get(Number(v.chainId));if(!v.dexscreenerSlug)return{chainId:v.chainId,chain:v.name??v.key??null,status:"unavailable",reason:"DexScreener coverage slug is not configured",pools:[]};if(!A)return{chainId:v.chainId,chain:v.name??v.key??null,chainSlug:v.dexscreenerSlug,status:"unavailable",reason:"no explicit provenanced destination token0/token1 mapping",pools:[]};try{let P=await d.discoverExactPairPools({chainSlug:v.dexscreenerSlug,token0:A.token0,token1:A.token1,limit:p,dexIds:A.dexIds},t);return{chainId:v.chainId,chain:v.name??v.key??null,chainSlug:v.dexscreenerSlug,status:"available",mapping:A,pools:P}}catch(P){return{chainId:v.chainId,chain:v.name??v.key??null,chainSlug:v.dexscreenerSlug,status:"unavailable",reason:P?.message??String(P),mapping:A,pools:[]}}})),f=m.flatMap(v=>v.pools.map(A=>({...A,chainId:Number(v.chainId),mapping:v.mapping}))),h=e.amounts??{},g=await Promise.all(f.map(async v=>{let[A,P]=await Promise.all([Yw({source:n,destination:v.mapping,amountIn:h.token0,index:0},d,t),Yw({source:n,destination:v.mapping,amountIn:h.token1,index:1},d,t)]),L=!(A.requested||P.requested)||[A,P].filter(O=>O.requested).every(O=>O.measured),F=L?[A,P].reduce((O,H)=>O+(H.costUsd??0),0):null,q=EL(v,v.mapping);return Object.freeze({...v,mappingProvenance:v.mapping.provenance,legs:Object.freeze([A,P]),fullyMeasured:L,costUsd:F,preparationEligible:!1,venueReviewEligible:q.eligible,ineligibleReason:q.reason})})),w=Jw(g.filter(v=>v.liquidityUsd!=null),v=>Number(v.liquidityUsd)),x=g.map(v=>Object.freeze({...v,...PL(v,w,i)})),b=x.find(v=>v.destinationEligible&&w&&v.poolAddress===w.poolAddress&&v.chainId===w.chainId)??null,y=x.filter(v=>v.fullyMeasured&&v.destinationEligible),k=Jw(y,v=>v.costUsd,"min"),E=x.filter(v=>v.destinationEligible===!1&&v.destinationIneligibleReason?.includes("shallower")),I=w&&x.some(v=>v.poolAddress===w.poolAddress&&v.chainId===w.chainId&&v.destinationEligible===!1);return Object.freeze({ok:!0,analysisOnly:!0,sourcePair:n,coverage:Object.freeze(m),routes:Object.freeze(x),deepestLiquidity:w,recommendedDestination:b,migrationCostBest:k,netBest:null,rankedOn:"liquidity",netRankingComplete:!1,preparationEligible:!1,liquidityFloor:Object.freeze(i),warnings:Object.freeze([...y.length<x.filter(v=>v.fullyMeasured).length?["partial-cost or thin-book routes were excluded from migration-cost comparison; missing gas was not treated as zero and thinner pools are not destinations"]:[],...E.length?[`${E.length} shallower pool(s) are not destination-eligible; a thinner V3 book is never recommended over a deeper V4 book`]:[],...I?["deepest book is not destination-eligible (unreviewed/dynamic-fee V4 or liquidity floor); thinner pools are still not recommended"]:[],"net-best migration is unavailable until destination token values and final add-liquidity gas/impact are measured; deepest liquidity is not claimed as net-best"])})}async function Qw(){let{CHAIN_CONFIGS:e}=await Promise.resolve().then(()=>(Mr(),Wd));return{ok:!0,execution:"analysis-only",configuredChains:e.length}}pe();Fe();Y();import{Interface as tv,getAddress as Ci,isAddress as TL}from"ethers";var En={8453:{name:"base",quoter:"0x254cF9E1E6e233aa1AC962CB9B05b2cfeAaE15b0",router:"0xBE6D8f0d05cC4be24d5167a3eF062215bE6D18a5",factory:"0x5e7BB104d84c7CB9B682AaC2F3d509f5F406809A",weth:"0x4200000000000000000000000000000000000006",usdc:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"}},NL=[1,50,100,200,2e3],Zw=new tv(["function quoteExactInputSingle((address tokenIn, address tokenOut, uint256 amountIn, int24 tickSpacing, uint160 sqrtPriceLimitX96) params) returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)"]),OL=new tv(["function exactInputSingle((address tokenIn, address tokenOut, int24 tickSpacing, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)"]),nv="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",rv="0x0000000000000000000000000000000000000000";function ov(e){let t=Number(e),n=En[t];if(!n)throw new Error(`aerodrome: unsupported chainId ${e} (supported: ${Object.keys(En).join(", ")})`);return{chainId:t,...n}}function ev(e,t){let n=En[Number(t)];if(!e||e===nv||e===rv||/^eth$/i.test(String(e)))return Ci(n.weth);let r=String(e);if(/^weth$/i.test(r))return Ci(n.weth);if(/^usdc$/i.test(r))return Ci(n.usdc);if(!TL(r))throw new Error(`invalid token address: ${e}`);return Ci(r)}async function pc(e={},t={}){let{chainId:n,quoter:r,router:o}=ov(e.chainId??8453),i=ev(e.tokenIn||"WETH",n),a=ev(e.tokenOut||En[n].usdc,n),s=BigInt(e.amountIn??0);if(s<=0n)throw new Error("amountIn required (raw base units)");let c=e.tickSpacing!=null?[Number(e.tickSpacing)]:e.tryTickSpacings===!1?[100]:[...NL],u=await Promise.all(c.map(async p=>{let m=Zw.encodeFunctionData("quoteExactInputSingle",[{tokenIn:i,tokenOut:a,amountIn:s,tickSpacing:p,sqrtPriceLimitX96:0n}]);try{let f=await D(n,"eth_call",[{to:r,data:m},"latest"],t);if(!f||f==="0x")return{tickSpacing:p,ok:!1,error:"empty result"};let h=Zw.decodeFunctionResult("quoteExactInputSingle",f);return{tickSpacing:p,ok:!0,amountOut:h[0].toString(),sqrtPriceX96After:h[1].toString(),initializedTicksCrossed:Number(h[2]),gasEstimate:h[3].toString()}}catch(f){return{tickSpacing:p,ok:!1,error:String(f.message||f).slice(0,160)}}})),d=null;for(let p of u)p.ok&&(!d||BigInt(p.amountOut)>BigInt(d.amountOut))&&(d=p);if(!d){let p=u.map(m=>`${m.tickSpacing}:${m.error||"fail"}`).join("; ");throw new Error(`aerodrome quote failed chain=${n}: ${p}`)}return oe({venue:"aerodrome",chainId:n,chain:En[n].name,quoter:r,router:o,tokenIn:i,tokenOut:a,amountIn:s.toString(),tickSpacing:d.tickSpacing,amountOut:d.amountOut,gasEstimate:d.gasEstimate,sqrtPriceX96After:d.sqrtPriceX96After,initializedTicksCrossed:d.initializedTicksCrossed,triedTickSpacings:u,best:!0},{chainId:n,venue:o,amountOut:d.amountOut,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function iv(e={},t={}){let n=Number(e.chainId??8453),r=ov(n),o=Ci(e.recipient||e.from||e.userAddress),i=String(e.tokenIn||"WETH"),a=!e.tokenIn||i===nv||i===rv||/^eth$/i.test(i),s=await pc(e,t),c=Math.min(600,Math.max(30,Number(e.deadlineSeconds??300))),u=Number(t.nowSeconds??Math.floor(Date.now()/1e3))+c,d=OL.encodeFunctionData("exactInputSingle",[{tokenIn:s.tokenIn,tokenOut:s.tokenOut,tickSpacing:s.tickSpacing,recipient:o,deadline:u,amountIn:BigInt(s.amountIn),amountOutMinimum:BigInt(s.amountOutMinimum),sqrtPriceLimitX96:0n}]);return N({provider:"aerodrome",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:n,deadline:u,quote:s,autoSlippage:s.autoSlippage,requiresApproval:a?null:{token:s.tokenIn,spender:r.router,amount:s.amountIn},transaction:{chainId:n,from:o,to:r.router,data:d,value:a?s.amountIn:"0",slippageGuard:ye(s.autoSlippage,{chainId:n,venue:r.router,data:d})}},{provider:"aerodrome",kind:"aerodrome-exact-in"})}async function av(e={}){let t=Number(e.chainId??8453);try{let n=await pc({chainId:t,tokenIn:"WETH",tokenOut:"USDC",amountIn:"1000000000000000"},e),r=Number(n.amountOut)/1e6;return{ok:!0,chainId:t,tickSpacing:n.tickSpacing,amountOutUsdc:r,midPxHint:r/.001,router:En[t]?.router,quoter:En[t]?.quoter}}catch(n){return{ok:!1,chainId:t,error:String(n.message||n).slice(0,200)}}}async function sv(){return Object.entries(En).map(([e,t])=>({chainId:Number(e),name:t.name,quoter:t.quoter,router:t.router,factory:t.factory,weth:t.weth,usdc:t.usdc}))}Xo();Is();ti();md();Y();var LL=96*1024,cv=50;function $L(e){if(e&&typeof e=="object"&&!Array.isArray(e))return e;let t=String(e||"").trim();if(!t||t.length>LL)throw new Error("x402: invalid PAYMENT-REQUIRED payload");if(t.startsWith("{"))try{return JSON.parse(t)}catch{throw new Error("x402: invalid PAYMENT-REQUIRED JSON")}if(!/^[A-Za-z0-9+/_-]+={0,2}$/.test(t)||t.length%4===1)throw new Error("x402: invalid PAYMENT-REQUIRED Base64");let n=t.replace(/-/g,"+").replace(/_/g,"/"),r=n+"=".repeat((4-n.length%4)%4);try{let o=Buffer.from(r,"base64").toString("utf8");if(!o.trim().startsWith("{"))throw new Error("shape");return JSON.parse(o)}catch{throw new Error("x402: invalid PAYMENT-REQUIRED Base64 JSON")}}function Xt(e,t){let n=String(e||"").trim();if(!n)throw new Error(`x402: ${t} required`);return n}function uv(e,t){let n=Xt(e,t);if(!/^\d+$/.test(n))throw new Error(`x402: ${t} must be atomic units`);let r=BigInt(n);if(r<=0n)throw new Error(`x402: ${t} must be positive`);return r.toString()}function BL(e){if(!e||typeof e!="object"||Array.isArray(e))return Object.freeze({});let t={};for(let n of["name","version"])typeof e[n]=="string"&&e[n].trim()&&(t[n]=e[n].trim());return Object.freeze(t)}function ML(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`x402: accepts[${t}] must be an object`);let n=Xt(e.scheme,`accepts[${t}].scheme`).toLowerCase();return Object.freeze({scheme:n,network:Xt(e.network,`accepts[${t}].network`),amount:uv(e.amount,`accepts[${t}].amount`),asset:Xt(e.asset,`accepts[${t}].asset`),payTo:Xt(e.payTo,`accepts[${t}].payTo`),maxTimeoutSeconds:Number(e.maxTimeoutSeconds),extra:BL(e.extra)})}function Yp(e){let t=$L(e);if(t.x402Version!==2)throw new Error("x402: only x402Version 2 is supported");if(!Array.isArray(t.accepts)||t.accepts.length===0||t.accepts.length>cv)throw new Error(`x402: accepts must contain 1-${cv} requirements`);let n=t.resource&&typeof t.resource=="object"&&!Array.isArray(t.resource)?Object.freeze({url:Xt(t.resource.url,"resource.url"),description:String(t.resource.description||""),mimeType:String(t.resource.mimeType||"")}):null;if(!n)throw new Error("x402: resource required");let r=Object.freeze(t.accepts.map(ML));for(let o of r)if(!Number.isInteger(o.maxTimeoutSeconds)||o.maxTimeoutSeconds<=0)throw new Error("x402: maxTimeoutSeconds must be a positive integer");return Object.freeze({x402Version:2,resource:n,accepts:r})}function lv(e,t){return String(e)===String(t)}function UL(e,t={}){let n=Yp(e),r=Xt(t.network,"network"),o=Xt(t.asset,"asset"),i=Xt(t.payTo,"payTo"),a=BigInt(uv(t.maxAmount,"maxAmount")),s=n.accepts.filter(l=>l.scheme==="exact"&&l.network===r&&lv(l.asset,o)&&lv(l.payTo,i));if(s.length===0)throw new Error("x402: no exact requirement matches network, asset, and payTo");let c=s.sort((l,u)=>{let d=BigInt(l.amount),p=BigInt(u.amount);return d<p?-1:d>p?1:0})[0];if(BigInt(c.amount)>a)throw new Error(`x402: amount ${c.amount} exceeds maxAmount ${a}`);return c}function dv(e={}){return e.paymentRequired??e.header??e.body}function pv(e={}){return Yp(dv(e))}function mv(e={},t={}){let n=Yp(dv(e)),r=UL(n,e);return N({provider:"x402",x402Version:2,resource:n.resource,accepted:r,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,executionReady:!1,paymentReady:!1,requestTemplate:{x402Version:2,resource:n.resource,accepted:r,payload:null},nextStep:"A user-controlled wallet must create the scheme-specific payload. Oracle does not sign, call a facilitator, or retry the paid request."},{provider:"x402",kind:"x402-payment-template",nowMs:t.nowMs})}function fv(){return{ok:!0,configured:!0,x402Version:2,schemes:["exact"],custody:"prepare-only",signingReady:!1,broadcastReady:!1}}R();vt();var DL="https://api.bankr.bot";function Jp(e={}){return Ae({provider:"bankr",defaultUrl:DL,hosts:["api.bankr.bot"],url:e.baseUrl||process.env.BANKR_API_URL})}function hv(e={}){return e.apiKey||process.env.BANKR_API_KEY||""}function qL(e={}){let t=hv(e);if(!t)throw new Error("BANKR_API_KEY required for Bankr");return t}function gv(e={},t=!1){let n=qL(e),r=Jp(e);return Ie({accept:"application/json",...t?{"content-type":"application/json"}:{}},{"X-API-Key":n},r.trusted)}async function yv(e,t={}){return S(`${Jp(t).baseUrl}${e}`,{headers:gv(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3,retries:0})}async function Xp(e={}){return yv("/wallet/me",e)}async function bv(e={}){return yv("/wallet/portfolio",e)}function Ti(e,t){let n=String(e||"").trim();if(!n)throw new Error(`bankr: ${t} required`);return n}function HL(e){let t=Ti(e,"amount");if(!/^\d+(?:\.\d+)?$/.test(t)||Number(t)<=0)throw new Error("bankr: amount must be a positive decimal string");return t}async function wv(e={},t={}){let n={fromChain:Ti(e.fromChain,"fromChain"),fromToken:Ti(e.fromToken,"fromToken"),toChain:Ti(e.toChain,"toChain"),toToken:Ti(e.toToken,"toToken"),amount:HL(e.amount)};if(e.slippageBps!=null){let r=Number(e.slippageBps);if(!Number.isInteger(r)||r<10||r>2e3)throw new Error("bankr: slippageBps must be an integer from 10 through 2000");n.slippageBps=r}return S(`${Jp(t).baseUrl}/wallet/swap-quote`,{method:"POST",headers:gv(t,!0),body:JSON.stringify(n),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4,retries:0})}async function vv(e={}){if(!hv(e))return{ok:!1,configured:!1,error:"BANKR_API_KEY not set"};try{return{ok:!0,configured:!0,walletConfigured:!!await Xp(e),custody:"vendor-wallet-read-only",execution:!1}}catch(t){return{ok:!1,configured:!0,error:String(t?.message||t).slice(0,160)}}}var zL=process.env.HL_WS_URL||"wss://api.hyperliquid.xyz/ws";async function Ni(e,t={}){if(!e?.type)throw new Error("hlWsSnapshot requires subscription.type");let n=t.timeoutMs??8e3,r=t.maxMessages??1,o=t.WebSocket||globalThis.WebSocket;if(!o)throw new Error("WebSocket not available in this runtime");let i=t.url||zL,a=Date.now();return new Promise((s,c)=>{let l=!1,u=[],d=0,p=new o(i),m=setTimeout(()=>{f(),l||(l=!0,u.length?s({ok:!0,partial:!0,ms:Date.now()-a,messages:u}):c(new Error(`hl ws timeout after ${n}ms`)))},n);function f(){clearTimeout(m);try{p.close()}catch{}}p.addEventListener("open",()=>{p.send(JSON.stringify({method:"subscribe",subscription:e}))}),p.addEventListener("message",h=>{let g;try{g=JSON.parse(typeof h.data=="string"?h.data:String(h.data))}catch{g={raw:String(h.data).slice(0,200)}}u.push(g),g.channel&&g.channel!=="subscriptionResponse"?d+=1:g.data&&g.channel==="subscriptionResponse"||g.channel||(d+=1),d>=r&&(f(),l||(l=!0,s({ok:!0,ms:Date.now()-a,subscription:e,messages:u,last:u[u.length-1]})))}),p.addEventListener("error",()=>{f(),l||(l=!0,c(new Error("hl ws error")))})})}async function xv(e={}){try{let t=await Ni({type:"allMids"},{...e,maxMessages:1}),n=t.last||{},r=n.data?.mids||n.data||{},o=typeof r=="object"?Object.keys(r).length:0;return{ok:!0,ms:t.ms,midCount:o,channel:n.channel||null}}catch(t){return{ok:!1,error:String(t.message||t).slice(0,160)}}}async function kv(e={}){let t=await Ni({type:"allMids"},e),n=t.last||{};return{ms:t.ms,mids:n.data?.mids||n.data||{},channel:n.channel}}async function Sv(e,t={}){if(!e)throw new Error("coin required");let n=await Ni({type:"l2Book",coin:String(e)},t);return{ms:n.ms,book:n.last?.data||n.last,channel:n.last?.channel}}var WL=process.env.POLY_WS_URL||"wss://ws-subscriptions-clob.polymarket.com/ws/market";async function mc(e=[],t={}){let n=Array.isArray(e)?e.map(String):[String(e)];if(!n.length||!n[0])throw new Error("polyWsSnapshot requires assetIds");let r=t.timeoutMs??8e3,o=t.maxMessages??1,i=t.WebSocket||globalThis.WebSocket;if(!i)throw new Error("WebSocket not available");let a=t.url||WL,s=Date.now();return new Promise((c,l)=>{let u=!1,d=[],p=0,m=new i(a),f=setTimeout(()=>{h(),u||(u=!0,d.length?c({ok:!0,partial:!0,ms:Date.now()-s,messages:d}):l(new Error(`poly ws timeout after ${r}ms`)))},r);function h(){clearTimeout(f);try{m.close()}catch{}}m.addEventListener("open",()=>{m.send(JSON.stringify({assets_ids:n,type:"market"}))}),m.addEventListener("message",g=>{let w;try{w=JSON.parse(typeof g.data=="string"?g.data:String(g.data))}catch{w={raw:String(g.data).slice(0,300)}}d.push(w),p+=1,p>=o&&(h(),u||(u=!0,c({ok:!0,ms:Date.now()-s,assetIds:n,messages:d,last:d[d.length-1]})))}),m.addEventListener("error",()=>{h(),u||(u=!0,l(new Error("poly ws error")))})})}async function Iv(e={}){let t=e.assetId||"98022490269692409998126496127597032490334070080325855126491859374983463996227";try{let n=await mc([t],{...e,maxMessages:1});return{ok:!0,ms:n.ms,got:!!n.last,partial:n.partial||!1}}catch(n){return{ok:!1,error:String(n.message||n).slice(0,160)}}}async function Ev(e,t={}){if(!e)throw new Error("assetId required");let n=await mc([e],t);return{ms:n.ms,assetId:String(e),data:n.last,messages:n.messages}}R();var KL="https://api.binance.com",YL="https://fapi.binance.com",JL=8;function Qp(e={}){return(e.spotBaseUrl||e.baseUrl||process.env.BINANCE_API_URL||KL).replace(/\/$/,"")}function fc(e={}){return(e.futuresBaseUrl||process.env.BINANCE_FAPI_URL||YL).replace(/\/$/,"")}function Oi(e){return{error:String(e.message||e).slice(0,200)}}function rt(e){let t=Number(e);return Number.isFinite(t)?t:null}function Ri(e,t="USDT"){let n=String(e||"").trim().toUpperCase().replace(/[-_/]/g,"");return n?n.endsWith(t)?n:`${n}${t}`:""}async function hc(e={}){try{let t=await S(`${Qp(e)}/api/v3/ping`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??1e4});return{ok:t&&typeof t=="object",provider:"binance-public",execution:"read-only",exec:!1}}catch(t){return{ok:!1,provider:"binance-public",error:String(t.message||t).slice(0,160)}}}async function gc(e={},t={}){let n=Ri(e.symbol||e.coin,e.quote||"USDT");if(!n)return{error:"binanceTicker requires symbol or coin"};try{let r=e.full?"/api/v3/ticker/24hr":"/api/v3/ticker/price",o=await S(`${Qp(t)}${r}?symbol=${encodeURIComponent(n)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3});return{venue:"binance",market:"spot",symbol:n,price:rt(o?.price??o?.lastPrice),volume24h:rt(o?.volume),quoteVolume24h:rt(o?.quoteVolume),raw:o}}catch(r){return Oi(r)}}async function Av(e={},t={}){let n=Ri(e.symbol||e.coin,e.quote||"USDT");if(!n)return{error:"binanceOrderbook requires symbol or coin"};let r=Math.min(Math.max(Number(e.limit)||20,1),1e3),o=String(e.market||"spot").toLowerCase()==="perp";try{let i=o?`${fc(t)}/fapi/v1/depth?symbol=${encodeURIComponent(n)}&limit=${r}`:`${Qp(t)}/api/v3/depth?symbol=${encodeURIComponent(n)}&limit=${r}`,a=await S(i,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3});return $i({venue:"binance",market:o?"perp":"spot",symbol:n,bids:a?.bids,asks:a?.asks,raw:a})}catch(i){return Oi(i)}}async function Li(e={},t={}){let n=Ri(e.symbol||e.coin,e.quote||"USDT");if(!n)return{error:"binanceFunding requires symbol or coin"};try{let r=await S(`${fc(t)}/fapi/v1/premiumIndex?symbol=${encodeURIComponent(n)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),o=Array.isArray(r)?r[0]:r,i=Number(e.fundingIntervalHours)||JL,a=rt(o?.lastFundingRate);return{venue:"binance",market:"perp",symbol:n,markPrice:rt(o?.markPrice),indexPrice:rt(o?.indexPrice),fundingRate:a,fundingIntervalHours:i,fundingAprPct:a==null?null:a*(8760/i)*100,nextFundingTime:rt(o?.nextFundingTime),raw:o??null}}catch(r){return Oi(r)}}async function _v(e={},t={}){let n=await Li(e,t);return n?.error?n:{venue:"binance",market:"perp",symbol:n.symbol,markPrice:n.markPrice,indexPrice:n.indexPrice}}async function Pv(e={},t={}){let n=Ri(e.symbol||e.coin,e.quote||"USDT");if(!n)return{error:"binanceOpenInterest requires symbol or coin"};try{let r=await S(`${fc(t)}/fapi/v1/openInterest?symbol=${encodeURIComponent(n)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3});return{venue:"binance",market:"perp",symbol:n,openInterest:rt(r?.openInterest),time:rt(r?.time),raw:r??null}}catch(r){return Oi(r)}}async function Cv(e={},t={}){let n=Ri(e.symbol||e.coin,e.quote||"USDT");if(!n)return{error:"binanceFundingHistory requires symbol or coin"};let r=Math.min(Math.max(Number(e.limit)||10,1),1e3);try{let o=await S(`${fc(t)}/fapi/v1/fundingRate?symbol=${encodeURIComponent(n)}&limit=${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),i=Array.isArray(o)?o:[];return{venue:"binance",symbol:n,count:i.length,history:i.map(a=>({fundingTime:rt(a?.fundingTime),fundingRate:rt(a?.fundingRate)}))}}catch(o){return Oi(o)}}function $i({venue:e,market:t,symbol:n,bids:r,asks:o,raw:i}){let a=m=>(Array.isArray(m)?m:[]).map(f=>{let h=rt(Array.isArray(f)?f[0]:f?.price),g=rt(Array.isArray(f)?f[1]:f?.size);return h==null||g==null?null:{price:h,size:g}}).filter(Boolean),s=a(r),c=a(o),l=s[0]?.price??null,u=c[0]?.price??null,d=l!=null&&u!=null?(l+u)/2:null,p=d?(u-l)/d*1e4:null;return{venue:e,market:t,symbol:n,bids:s,asks:c,bestBid:l,bestAsk:u,mid:d,spreadBps:p,raw:i??null}}R();var XL="https://www.okx.com",QL=8;function Wr(e={}){return(e.baseUrl||process.env.OKX_API_URL||XL).replace(/\/$/,"")}function Bi(e){return{error:String(e.message||e).slice(0,200)}}function Je(e){if(e===""||e==null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function Mi(e,{market:t="spot",quote:n="USDT"}={}){let r=String(e||"").trim().toUpperCase();if(!r)return"";if(r.includes("-"))return r;let o=`${r}-${n}`;return t==="perp"?`${o}-SWAP`:o}function Gr(e){if(e&&String(e.code)!=="0"&&e.code!==void 0)throw new Error(`okx error ${e.code}: ${e.msg||"unknown"}`);let t=e?.data;return Array.isArray(t)?t:[]}async function yc(e={}){try{let t=await S(`${Wr(e)}/api/v5/public/time`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??1e4});return{ok:Gr(t).length>0,provider:"okx-public",execution:"read-only",exec:!1}}catch(t){return{ok:!1,provider:"okx-public",error:String(t.message||t).slice(0,160)}}}async function bc(e={},t={}){let n=String(e.market||"spot").toLowerCase(),r=Mi(e.instId||e.symbol||e.coin,{market:n,quote:e.quote||"USDT"});if(!r)return{error:"okxTicker requires instId, symbol or coin"};try{let o=await S(`${Wr(t)}/api/v5/market/ticker?instId=${encodeURIComponent(r)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),i=Gr(o)[0];return i?{venue:"okx",market:r.endsWith("-SWAP")?"perp":"spot",symbol:r,price:Je(i.last),bestBid:Je(i.bidPx),bestAsk:Je(i.askPx),volume24h:Je(i.vol24h),quoteVolume24h:Je(i.volCcy24h),raw:i}:{error:`okx ticker empty for ${r}`}}catch(o){return Bi(o)}}async function Nv(e={},t={}){let n=String(e.market||"spot").toLowerCase(),r=Mi(e.instId||e.symbol||e.coin,{market:n,quote:e.quote||"USDT"});if(!r)return{error:"okxOrderbook requires instId, symbol or coin"};let o=Math.min(Math.max(Number(e.limit)||20,1),400);try{let i=await S(`${Wr(t)}/api/v5/market/books?instId=${encodeURIComponent(r)}&sz=${o}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),a=Gr(i)[0];return a?$i({venue:"okx",market:r.endsWith("-SWAP")?"perp":"spot",symbol:r,bids:a.bids,asks:a.asks,raw:a}):{error:`okx books empty for ${r}`}}catch(i){return Bi(i)}}async function wc(e={},t={}){let n=Mi(e.instId||e.symbol||e.coin,{market:"perp",quote:e.quote||"USDT"});if(!n)return{error:"okxFunding requires instId, symbol or coin"};try{let r=await S(`${Wr(t)}/api/v5/public/funding-rate?instId=${encodeURIComponent(n)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),o=Gr(r)[0];if(!o)return{error:`okx funding-rate empty for ${n}`};let i=Number(e.fundingIntervalHours)||QL,a=Je(o.fundingRate);return{venue:"okx",market:"perp",symbol:n,fundingRate:a,nextFundingRate:Je(o.nextFundingRate),fundingIntervalHours:i,fundingAprPct:a==null?null:a*(8760/i)*100,nextFundingTime:Je(o.nextFundingTime??o.fundingTime),raw:o}}catch(r){return Bi(r)}}async function vc(e={},t={}){let n=Mi(e.instId||e.symbol||e.coin,{market:"perp",quote:e.quote||"USDT"});if(!n)return{error:"okxMarkPrice requires instId, symbol or coin"};let r=String(e.instType||"SWAP").toUpperCase();try{let o=await S(`${Wr(t)}/api/v5/public/mark-price?instType=${encodeURIComponent(r)}&instId=${encodeURIComponent(n)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),i=Gr(o)[0];return i?{venue:"okx",market:"perp",symbol:n,markPrice:Je(i.markPx),time:Je(i.ts),raw:i}:{error:`okx mark-price empty for ${n}`}}catch(o){return Bi(o)}}async function Ov(e={},t={}){let n=Mi(e.instId||e.symbol||e.coin,{market:"perp",quote:e.quote||"USDT"});if(!n)return{error:"okxOpenInterest requires instId, symbol or coin"};let r=String(e.instType||"SWAP").toUpperCase();try{let o=await S(`${Wr(t)}/api/v5/public/open-interest?instType=${encodeURIComponent(r)}&instId=${encodeURIComponent(n)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),i=Gr(o)[0];return i?{venue:"okx",market:"perp",symbol:n,openInterest:Je(i.oiCcy??i.oi),openInterestContracts:Je(i.oi),openInterestUsd:Je(i.oiUsd),time:Je(i.ts),raw:i}:{error:`okx open-interest empty for ${n}`}}catch(o){return Bi(o)}}R();var ZL="https://api.bybit.com",e$=8;function Ui(e={}){return(e.baseUrl||process.env.BYBIT_API_URL||ZL).replace(/\/$/,"")}function Fi(e){return{error:String(e.message||e).slice(0,200)}}function Te(e){if(e===""||e==null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function xc(e,t="USDT"){let n=String(e||"").trim().toUpperCase().replace(/[-_/]/g,"");return n?n.endsWith(t)?n:`${n}${t}`:""}function Zp(e){let t=String(e||"spot").toLowerCase();return t==="perp"||t==="linear"||t==="swap"?"linear":t==="inverse"?"inverse":"spot"}function Di(e){if(e&&e.retCode!==void 0&&Number(e.retCode)!==0)throw new Error(`bybit error ${e.retCode}: ${e.retMsg||"unknown"}`);return e?.result??null}async function kc(e={}){try{let t=await S(`${Ui(e)}/v5/market/time`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??1e4});return{ok:!!Di(t),provider:"bybit-public",execution:"read-only",exec:!1}}catch(t){return{ok:!1,provider:"bybit-public",error:String(t.message||t).slice(0,160)}}}async function Lv(e,t){let n=Zp(e.market),r=xc(e.symbol||e.coin,e.quote||"USDT");if(!r)return{error:"bybit requires symbol or coin"};let o=await S(`${Ui(t)}/v5/market/tickers?category=${encodeURIComponent(n)}&symbol=${encodeURIComponent(r)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),i=Di(o)?.list?.[0];return i?{row:i,symbol:r,category:n}:{error:`bybit tickers empty for ${r}`}}async function Sc(e={},t={}){try{let n=await Lv(e,t);if(n.error)return n;let{row:r,symbol:o,category:i}=n;return{venue:"bybit",market:i==="spot"?"spot":"perp",symbol:o,price:Te(r.lastPrice),bestBid:Te(r.bid1Price),bestAsk:Te(r.ask1Price),markPrice:Te(r.markPrice),indexPrice:Te(r.indexPrice),volume24h:Te(r.volume24h),quoteVolume24h:Te(r.turnover24h),raw:r}}catch(n){return Fi(n)}}async function $v(e={},t={}){let n=Zp(e.market),r=xc(e.symbol||e.coin,e.quote||"USDT");if(!r)return{error:"bybitOrderbook requires symbol or coin"};let o=Math.min(Math.max(Number(e.limit)||25,1),200);try{let i=await S(`${Ui(t)}/v5/market/orderbook?category=${encodeURIComponent(n)}&symbol=${encodeURIComponent(r)}&limit=${o}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),a=Di(i);return a?$i({venue:"bybit",market:n==="spot"?"spot":"perp",symbol:r,bids:a.b,asks:a.a,raw:a}):{error:`bybit orderbook empty for ${r}`}}catch(i){return Fi(i)}}async function qi(e={},t={}){try{let n=await Lv({...e,market:e.market||"perp"},t);if(n.error)return n;let{row:r,symbol:o}=n,i=Number(e.fundingIntervalHours)||e$,a=Te(r.fundingRate);return{venue:"bybit",market:"perp",symbol:o,markPrice:Te(r.markPrice),indexPrice:Te(r.indexPrice),fundingRate:a,fundingIntervalHours:i,fundingAprPct:a==null?null:a*(8760/i)*100,nextFundingTime:Te(r.nextFundingTime),openInterest:Te(r.openInterest),raw:r}}catch(n){return Fi(n)}}async function Bv(e={},t={}){let n=await qi(e,t);return n?.error?n:{venue:"bybit",market:"perp",symbol:n.symbol,markPrice:n.markPrice,indexPrice:n.indexPrice}}async function Mv(e={},t={}){let n=xc(e.symbol||e.coin,e.quote||"USDT");if(!n)return{error:"bybitOpenInterest requires symbol or coin"};let r=Zp(e.market||"perp"),o=String(e.intervalTime||"1h"),i=Math.min(Math.max(Number(e.limit)||1,1),200);try{let a=await S(`${Ui(t)}/v5/market/open-interest?category=${encodeURIComponent(r)}&symbol=${encodeURIComponent(n)}&intervalTime=${encodeURIComponent(o)}&limit=${i}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),s=Di(a)?.list,c=Array.isArray(s)?s[0]:null;return c?{venue:"bybit",market:"perp",symbol:n,openInterest:Te(c.openInterest),time:Te(c.timestamp),history:(Array.isArray(s)?s:[]).map(l=>({openInterest:Te(l?.openInterest),timestamp:Te(l?.timestamp)}))}:{error:`bybit open-interest empty for ${n}`}}catch(a){return Fi(a)}}async function Uv(e={},t={}){let n=xc(e.symbol||e.coin,e.quote||"USDT");if(!n)return{error:"bybitFundingHistory requires symbol or coin"};let r=Math.min(Math.max(Number(e.limit)||10,1),200);try{let o=await S(`${Ui(t)}/v5/market/funding/history?category=linear&symbol=${encodeURIComponent(n)}&limit=${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),i=Di(o)?.list,a=Array.isArray(i)?i:[];return{venue:"bybit",symbol:n,count:a.length,history:a.map(s=>({fundingRate:Te(s?.fundingRate),fundingTime:Te(s?.fundingRateTimestamp)}))}}catch(o){return Fi(o)}}dt();var em=["binance","okx","bybit","hyperliquid"],Dv=1;function Hi(e){return{error:String(e.message||e).slice(0,200)}}function Be(e){if(e===""||e==null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function t$(e,t){return e==null||!t?null:e*(8760/t)*100}function tm(e={}){return String(e.coin||e.symbol||"").trim().toUpperCase().replace(/[-_/]/g,"").replace(/USDT?$/,"")||""}function n$(e={}){let t=e.venues,n=Array.isArray(t)?t:typeof t=="string"&&t.trim()&&t.trim().toLowerCase()!=="all"?t.split(","):em,r=new Set(n.map(i=>String(i).trim().toLowerCase()).filter(Boolean)),o=em.filter(i=>r.has(i));return o.length?o:em}async function r$(e={},t={}){let n=tm(e);if(!n)return{error:"hyperliquidPerpLeg requires coin"};try{let r=await Ke(t),o=r?.[0]?.universe,i=r?.[1];if(!Array.isArray(o)||!Array.isArray(i))return{error:"hyperliquid metaAndAssetCtxs returned an unexpected shape"};let a=o.findIndex(l=>String(l?.name||"").toUpperCase()===n);if(a<0)return{error:`hyperliquid has no perp for ${n}`};let s=i[a]||{},c=Be(s.funding);return{venue:"hyperliquid",market:"perp",symbol:n,markPrice:Be(s.markPx),indexPrice:Be(s.oraclePx),midPrice:Be(s.midPx),fundingRate:c,fundingIntervalHours:Dv,fundingAprPct:t$(c,Dv),openInterest:Be(s.openInterest)}}catch(r){return Hi(r)}}async function o$(e={},t={}){let n=tm(e);if(!n)return{error:"hyperliquidSpotLeg requires coin"};try{let r=await xt(t),o=Be(r?.[n]);return o==null?{error:`hyperliquid allMids has no entry for ${n}`}:{venue:"hyperliquid",market:"spot",symbol:n,price:o}}catch(r){return Hi(r)}}async function i$(e={},t={}){let[n,r]=await Promise.all([wc(e,t).catch(Hi),vc(e,t).catch(Hi)]);return n?.error&&r?.error?n:{...n?.error?{venue:"okx",market:"perp",fundingError:n.error}:n,markPrice:r?.error?null:Be(r.markPrice),...r?.error?{markError:r.error}:{}}}async function An(e,t){try{let n=await t;return[e,n&&typeof n=="object"?n:{error:"empty response"}]}catch(n){return[e,Hi(n)]}}async function nm(e={},t={}){let n=tm(e);if(!n)return{error:"cexVenueLegs requires coin"};let r=e.quote||"USDT",o=n$(e),i=[];o.includes("binance")&&(i.push(An("binance:perp",Li({coin:n,quote:r},t))),i.push(An("binance:spot",gc({coin:n,quote:r},t)))),o.includes("okx")&&(i.push(An("okx:perp",i$({coin:n,quote:r},t))),i.push(An("okx:spot",bc({coin:n,quote:r,market:"spot"},t)))),o.includes("bybit")&&(i.push(An("bybit:perp",qi({coin:n,quote:r},t))),i.push(An("bybit:spot",Sc({coin:n,quote:r,market:"spot"},t)))),o.includes("hyperliquid")&&(i.push(An("hyperliquid:perp",r$({coin:n},t))),i.push(An("hyperliquid:spot",o$({coin:n},t))));let a=await Promise.all(i),s={};for(let[c,l]of a){let[u,d]=c.split(":");s[u]=s[u]||{},s[u][d]=l}return{coin:n,quote:r,venues:o,legs:s}}function qv(e){return!e||e.error?null:Be(e.price)??Be(e.mid)??null}function a$(e){return!e||e.error?null:Be(e.markPrice)??Be(e.midPrice)??null}async function rm(e={},t={}){let n=await nm(e,t);if(n.error)return n;let{coin:r,quote:o,venues:i,legs:a}=n,s=[];for(let f of i){let h=qv(a[f]?.spot);h!=null&&h>0&&s.push(h)}let c=[...s].sort((f,h)=>f-h),l=c.length?c.length%2?c[(c.length-1)/2]:(c[c.length/2-1]+c[c.length/2])/2:null,u=[];for(let f of i){let h=a[f]?.perp,g=a[f]?.spot,w=a$(h),x=qv(g),b=x??l,y=w!=null&&b?(w-b)/b*1e4:null;u.push({venue:f,symbol:h?.symbol??g?.symbol??r,markPrice:w,spotPrice:x,spotSource:x!=null?f:l!=null?"cross-venue-median":null,basisBps:y,fundingRate:h&&!h.error?Be(h.fundingRate):null,fundingIntervalHours:h&&!h.error?Be(h.fundingIntervalHours):null,fundingAprPct:h&&!h.error?Be(h.fundingAprPct):null,openInterest:h&&!h.error?Be(h.openInterest):null,errors:[h?.error,g?.error].filter(Boolean)})}let d=s$(u),p=u.filter(f=>f.markPrice!=null),m=u.filter(f=>f.basisBps!=null);return{coin:r,quote:o,referenceSpot:l,asOf:new Date().toISOString(),venues:u,fundingSpreads:d,widestFundingSpread:d[0]??null,richestBasis:m.length?m.reduce((f,h)=>h.basisBps>f.basisBps?h:f):null,cheapestBasis:m.length?m.reduce((f,h)=>h.basisBps<f.basisBps?h:f):null,venuesPriced:p.length,venuesRequested:i.length,execution:"read-only",exec:!1,note:"Public market data only. Funding compared on an annualized basis (HL settles hourly, CEXes 8h). Not advice."}}function s$(e=[]){let t=e.filter(r=>Be(r?.fundingAprPct)!=null),n=[];for(let r=0;r<t.length;r++)for(let o=r+1;o<t.length;o++){let i=t[r],a=t[o],s=i.fundingAprPct-a.fundingAprPct,c=s>0?a.venue:i.venue,l=s>0?i.venue:a.venue;n.push({pair:`${i.venue}/${a.venue}`,aprSpreadPct:Math.abs(s),signedAprSpreadPct:s,longVenue:c,shortVenue:l})}return n.sort((r,o)=>o.aprSpreadPct-r.aprSpreadPct)}async function Hv(e={},t={}){let n=await rm(e,t);return n.error?n:{coin:n.coin,asOf:n.asOf,venues:n.venues.map(r=>({venue:r.venue,symbol:r.symbol,fundingRate:r.fundingRate,fundingIntervalHours:r.fundingIntervalHours,fundingAprPct:r.fundingAprPct,errors:r.errors})),fundingSpreads:n.fundingSpreads,widestFundingSpread:n.widestFundingSpread,execution:"read-only",exec:!1}}async function jv(e={}){try{let t=await Promise.all([hc(e).catch(()=>({ok:!1})),yc(e).catch(()=>({ok:!1})),kc(e).catch(()=>({ok:!1}))]),n={binance:!!t[0]?.ok,okx:!!t[1]?.ok,bybit:!!t[2]?.ok};return{ok:Object.values(n).some(Boolean),provider:"cex-basis",upstream:n,execution:"read-only",exec:!1}}catch(t){return{ok:!1,provider:"cex-basis",error:String(t.message||t).slice(0,160)}}}import Kv from"node:path";import{homedir as x$}from"node:os";import{createHash as k$,randomUUID as S$}from"node:crypto";import se from"node:fs";import Ic from"node:path";import{createHash as l$,randomUUID as zv}from"node:crypto";var om=1,St=class extends Error{constructor(t,n="DURABLE_STORE_ERROR"){super(t),this.name="DurableStoreError",this.code=n}};function _n(e){if(e===null)return"null";if(typeof e=="string"||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError("durable store values must contain finite numbers");return JSON.stringify(e)}if(Array.isArray(e))return`[${e.map(_n).join(",")}]`;if(e&&typeof e=="object")return`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${_n(e[n])}`).join(",")}}`;throw new TypeError(`durable store values must be JSON-safe, got ${typeof e}`)}function Vv(e){return l$("sha256").update(_n(e)).digest("hex")}function Ec(e){let t=e(),n=t instanceof Date?t.getTime():typeof t=="string"?Date.parse(t):Number(t);if(!Number.isFinite(n))throw new TypeError("clock must return epoch milliseconds, an ISO string, or a Date");return Math.trunc(n)}function Ac(e){return e===void 0?void 0:JSON.parse(JSON.stringify(e))}function Wv(e){se.mkdirSync(e,{recursive:!0,mode:448});try{se.chmodSync(e,448)}catch{}}function im(e){try{let t=se.statSync(e);return{...JSON.parse(se.readFileSync(e,"utf8")),mtimeMs:t.mtimeMs}}catch{return null}}function Kr({filePath:e,kind:t,initialData:n,validateData:r,clock:o=()=>Date.now(),maxBytes:i=4*1024*1024,lockStaleMs:a=3e4,lockWaitMs:s=2e3,lockIdFactory:c=()=>zv()}={}){if(typeof e!="string"||e==="")throw new TypeError("filePath is required");if(!/^[a-z][a-z0-9._-]{0,63}$/i.test(String(t)))throw new TypeError("a bounded store kind is required");if(typeof n!="function"||typeof r!="function")throw new TypeError("initialData and validateData are required");if(!Number.isSafeInteger(i)||i<1024)throw new TypeError("maxBytes must be at least 1024");if(!Number.isSafeInteger(a)||a<1e3)throw new TypeError("lockStaleMs must be at least 1000");if(!Number.isSafeInteger(s)||s<0||s>3e4)throw new TypeError("lockWaitMs must be between 0 and 30000");let l=`${e}.lock`;function u(){let b=n();return r(b),{schemaVersion:om,kind:t,generation:0,data:b}}function d(b){let y;try{y=JSON.parse(b)}catch(I){throw new St(`corrupt ${t} snapshot: invalid JSON (${I.message})`,"STORE_CORRUPT")}if(!y||typeof y!="object"||Array.isArray(y))throw new St(`corrupt ${t} snapshot: root must be an object`,"STORE_CORRUPT");if(y.schemaVersion!==om)throw new St(`unsupported ${t} schemaVersion ${String(y.schemaVersion)}`,"STORE_SCHEMA");if(y.kind!==t||!Number.isSafeInteger(y.generation)||y.generation<0)throw new St(`corrupt ${t} snapshot metadata`,"STORE_CORRUPT");let{integrity:k,...E}=y;if(typeof k!="string"||!/^[a-f0-9]{64}$/.test(k)||Vv(E)!==k)throw new St(`corrupt ${t} snapshot: checksum mismatch`,"STORE_CORRUPT");try{r(y.data)}catch(I){throw new St(`corrupt ${t} snapshot: ${I.message}`,"STORE_CORRUPT")}return E}function p(){if(!se.existsSync(e))return u();let b=se.statSync(e);if(!b.isFile()||b.size>i)throw new St(`${t} snapshot is not a bounded regular file`,"STORE_BOUNDS");try{se.chmodSync(e,384)}catch{}return d(se.readFileSync(e,"utf8"))}function m(){Wv(Ic.dirname(e));let b=Ec(o),y=String(c()),k=`${JSON.stringify({schemaVersion:1,lockId:y,pid:process.pid,acquiredAt:b})}
|
|
145
|
+
`)){let n=t.match(/^\s*OPENSEA_API_KEY\s*=\s*(.+)\s*$/);if(n)return n[1].replace(/^["']|["']$/g,"").trim()}}catch{}return""}function Vt(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||VO()}function Ty(e={}){return Ae({provider:"opensea",defaultUrl:DO,hosts:["api.opensea.io","testnets-api.opensea.io"],url:e.baseUrl||process.env.OPENSEA_API_URL})}function Qn(e={}){return Ty(e).baseUrl}function Zn(e={}){return Ie({accept:"application/json"},{"x-api-key":Vt(e)},Ty(e).trusted)}function Ny(e){let t=String(e||"ethereum").trim().toLowerCase();if(!zO.has(t))throw new Error(`opensea: unsupported account chain ${t}`);return t}function Z(e,t="address"){try{return UO(String(e||"").trim().toLowerCase())}catch{throw new Error(`opensea: invalid ${t}`)}}function Oy(e,t=null){let n=String(e||"").trim();if(!n)throw new Error("opensea: account address required");if(t&&!Cy.has(t)||!t&&/^0x[0-9a-fA-F]{40}$/.test(n))return Z(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 WO(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 GO(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 Iy(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 KO(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,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"}}}async function Ry(e={}){if(!Vt(e))return{ok:!1,configured:!1,error:"OPENSEA_API_KEY not set"};try{let t=await ii("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 ii(e,t={}){if(!e)throw new Error("collection slug required");if(!Vt(t))throw new Error("OPENSEA_API_KEY required");return S(`${Qn(t)}/collections/${encodeURIComponent(e)}`,{headers:Zn(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3})}async function Ly(e,t={}){let n=await ii(e,t),r=n.stats||n.total||{},o=n.floor_price??n.floorPrice??r.floor_price??r.floorPrice??null;return{slug:n.collection||e,name:n.name||null,floor:o,totalSupply:n.total_supply??r.total_supply??null,numOwners:n.num_owners??r.num_owners??null,raw:{contracts:n.contracts,fees:n.fees,category:n.category}}}async function ai(e={},t={}){if(!Vt(t))throw new Error("OPENSEA_API_KEY required");let n=Ny(e.chain),r=Oy(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),a=[],s=e.next?String(e.next):null,c=0;do{let l=new URL(`${Qn(t)}/chain/${encodeURIComponent(n)}/account/${encodeURIComponent(r)}/nfts`);l.searchParams.set("limit",String(o)),e.collection&&l.searchParams.set("collection",String(e.collection)),s&&l.searchParams.set("next",s);let u=await S(l.toString(),{headers:Zn(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4});for(let d of Array.isArray(u?.nfts)?u.nfts:[])a.push(KO(d,n,r));s=u?.next?String(u.next):null,c+=1}while(s&&c<i);return{provider:"opensea-nft",source:"opensea-account-inventory",chain:n,owner:r,count:a.length,pages:c,complete:!s,next:s,nfts:a,exec:!1,readOnly:!0}}async function Cs(e={},t={}){if(!Vt(t))throw new Error("OPENSEA_API_KEY required");let n=Oy(e.address||e.owner),r=await S(`${Qn(t)}/account/${encodeURIComponent(n)}/pnl`,{headers:Zn(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}}var Ts=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});function si(e){let t=String(e||"").trim().toLowerCase(),n=Ts[t];if(!n)throw new Error(`opensea: unsupported EVM chain ${t||"(missing)"}`);return{chain:t,chainId:n}}function Ge(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 YO(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 oi(e){let t=String(e??"").trim();if(!/^\d+$/.test(t))throw new Error("opensea: tokenId must be an unsigned integer string");return t}function $y(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 By(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 JO(e){return!!e&&typeof e=="object"&&[0,1].includes(Number(e.itemType))}function XO(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=Z(e?.token,t);if(n===0&&r!==ri)throw new Error(`opensea: ${t} native payment item must use the zero address`);if(n===1&&r===ri)throw new Error(`opensea: ${t} ERC20 payment item must name a non-zero token contract`);return r}function QO(e,t){let n=Ge(e?.startAmount,`${t} startAmount`),r=Ge(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 Bd(e,t,{required:n=!0}={}){let r=(Array.isArray(e)?e:[]).filter(JO);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 a of r){let s=XO(a,`${t} payment token`);if(o==null)o=s;else if(s!==o)throw new Error(`opensea: ${t} mixes more than one payment token`);i+=QO(a,`${t} payment amount`)}return{paymentToken:o,totalWei:i,count:r.length}}var ZO=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"}]});function nt(e,t){let n=String(e??"").trim();if(!/^\d+$/.test(n))throw new Error(`opensea: ${t} must be an unsigned integer`);return n}function Ey(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 My(e,t){return{itemType:Number(nt(e?.itemType,`${t} itemType`)),token:Z(e?.token,`${t} token`),identifierOrCriteria:nt(e?.identifierOrCriteria,`${t} identifierOrCriteria`),startAmount:nt(e?.startAmount,`${t} startAmount`),endAmount:nt(e?.endAmount,`${t} endAmount`)}}function eR(e,t){return{...My(e,t),recipient:Z(e?.recipient,`${t} recipient`)}}function tR(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:Z(e.offerer,`${t} offerer`),zone:Z(e.zone,`${t} zone`),offer:n.map((o,i)=>My(o,`${t} offer[${i}]`)),consideration:r.map((o,i)=>eR(o,`${t} consideration[${i}]`)),orderType:Number(nt(e.orderType,`${t} orderType`)),startTime:nt(e.startTime,`${t} startTime`),endTime:nt(e.endTime,`${t} endTime`),zoneHash:Ey(e.zoneHash,`${t} zoneHash`),salt:nt(e.salt,`${t} salt`),conduitKey:Ey(e.conduitKey,`${t} conduitKey`),counter:nt(e.counter,`${t} counter`)}}function Uy(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=tR(t,n);if(Md.hashStruct("OrderComponents",ZO,o).toLowerCase()!==r)throw new Error(`opensea: ${n} order hash does not match its canonical Seaport parameters`);return r}function Fy(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=Z(e?.token,`${t} contract`),o=oi(e?.identifierOrCriteria),i=Ge(e?.startAmount,`${t} startAmount`,{positive:!0}),a=Ge(e?.endAmount??e?.startAmount,`${t} endAmount`,{positive:!0});if(i!==a)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 nR(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 Fy(r[0],`${t} offer NFT`)}function rR(e,t,n){let r=Array.isArray(e?.consideration)?e.consideration:[];if(r.some(a=>[4,5].includes(Number(a?.itemType))))throw new Error(`opensea: ${n} uses a criteria consideration item, not a fixed token`);let o=r.filter(a=>[2,3].includes(Number(a?.itemType)));if(o.length!==1)throw new Error(`opensea: ${n} must require exactly one fixed ERC-721 or ERC-1155 consideration item`);let i=Fy(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 oR(e,t,n,r){if(!(!e||typeof e!="object")){if(e.contract!=null&&String(e.contract).trim()!==""&&Z(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 iR(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 Dy(e,t,n,r){let o=nt(t?.startTime,`${r} startTime`),i=nt(t?.endTime,`${r} endTime`),a=BigInt(Math.floor(n/1e3));if(BigInt(o)>a)throw new Error(`opensea: ${r} canonical startTime is in the future`);if(BigInt(i)<=a)throw new Error(`opensea: ${r} canonical endTime is expired or stale`);let s=By(i,n,`${r} expiry`),c=e?.expiration_time??e?.expirationTime;if(c!=null&&String(c).trim()!==""&&iR(c)!==Number(i))throw new Error(`opensea: ${r} display expiry disagrees with the canonical order endTime`);return s}function aR(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(Ts[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,a=nR(i,"listing"),s=a.contract;if(t.contract&&s!==t.contract)throw new Error("opensea: OpenSea returned a listing for the wrong contract");let c=a.tokenId;oR(e.asset,s,c,"listing");let l=Ge(e.price?.current?.value,"listing price",{positive:!0}),u=Uy(e,i,"listing"),d=Bd(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:Z(e.protocol_address,"listing protocol address"),contract:s,tokenId:c,quantity:a.quantity,priceWei:l.toString(),paymentToken:d.paymentToken,currency:String(e.price?.current?.currency||"").trim()||null,decimals:Number(e.price?.current?.decimals??18),expiry:Dy(e,i,n,"listing"),counter:nt(i?.counter,"listing counter")}}async function Ud(e={},t={}){if(!Vt(t))throw new Error("OPENSEA_API_KEY required");let n=si(e.chain);n.contract=e.contract?Z(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(`${Qn(t)}/listings/collection/${encodeURIComponent(r)}/best`);i.searchParams.set("limit",String(o)),e.next&&i.searchParams.set("next",String(e.next));let a=await S(i.toString(),{headers:Zn(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),s=Array.isArray(a?.listings)?a.listings:[];if(!s.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:s.map(l=>aR(l,n,c)),next:a?.next?String(a.next):null,exec:!1,readOnly:!0}}async function Ns(e={},t={}){let n=oi(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 a=1;a<=r;a+=1){let s=await Ud({...e,tokenId:void 0,limit:50,next:o},t),c=s.listings.find(l=>l.tokenId===n);if(c)return{provider:"opensea-nft",source:"opensea-best-exact-listing",...c,pagesScanned:a,exact:!0,exec:!1,readOnly:!0};if(!s.next||i.has(s.next))break;i.add(s.next),o=s.next}throw new Error("opensea: no active exact NFT listing returned within page bound")}function sR(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||{},s=rR(i,n,"offer").contract;if(t.contract&&s!==t.contract)throw new Error("opensea: OpenSea returned an offer for the wrong contract");let c=Ge(e.price?.current?.value??e.price?.value,"offer value",{positive:!0}),l=Bd(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=Bd(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(),m=(c-d.totalWei).toString();return{provider:"opensea-nft",source:"opensea-best-exact-offer",orderHash:Uy(e,i,"offer"),chain:t.chain,chainId:t.chainId,protocolAddress:Z(e.protocol_address,"offer protocol address"),contract:s,tokenId:n,grossOfferWei:c.toString(),sellerNetWei:m,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:Dy(e,i,r,"offer"),counter:nt(i.counter,"offer counter"),exec:!1,readOnly:!0}}async function Os(e={},t={}){if(!Vt(t))throw new Error("OPENSEA_API_KEY required");let n=si(e.chain);n.contract=e.contract?Z(e.contract,"NFT contract"):null;let r=String(e.slug||"").trim();if(!r)throw new Error("opensea: collection slug required");let o=oi(e.tokenId),i=await S(`${Qn(t)}/offers/collection/${encodeURIComponent(r)}/nfts/${encodeURIComponent(o)}/best`,{headers:Zn(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4}),a=i?.offer||(Array.isArray(i?.offers)?i.offers[0]:i);if(!a)throw new Error("opensea: no active exact NFT offer returned");let s=Number.isFinite(Number(t.nowMs))?Number(t.nowMs):Date.now();return sR(a,n,o,s)}function cR(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 qy(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"&&qy(n))}function Hy(e){return!e||typeof e!="object"?!1:Object.keys(e).some(t=>/^(?:signed.*|rawtransaction|serializedtransaction|txsigned|r|s|v)$/i.test(t))}function jy(e){return!e||typeof e!="object"?!1:Hy(e)?!0:Object.values(e).some(t=>t&&typeof t=="object"&&jy(t))}function zy(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"&&zy(o,t,n);return t}function Ay(e){return e&&typeof e=="object"&&typeof e.value=="string"?e.value:e}function Vy(e,{buyer:t,chainId:n,targets:r}){if(!e||typeof e!="object")throw new Error("opensea: transaction object required");if(Hy(e))throw new Error("opensea: signed transaction material refused");if((e.from?Z(Ay(e.from),"transaction buyer"):t)!==t)throw new Error("opensea: OpenSea returned a transaction for the wrong buyer");let i=Z(Ay(e.to??e.target),"transaction target");if(!r.has(i))throw new Error("opensea: OpenSea returned a transaction for the wrong target");let a=e.data??e.calldata,s=e.input_data&&typeof e.input_data=="object"?e.input_data:e.input&&typeof e.input=="object"?e.input:null;if(a==null&&s){if(!String(e.function||"").replace(/^function\s+/,"").startsWith("fulfillAdvancedOrder("))throw new Error("opensea: only exact Seaport fulfillAdvancedOrder preparation is accepted");a=HO.encodeFunctionData("fulfillAdvancedOrder",[s.advancedOrder,s.criteriaResolvers,s.fulfillerConduitKey,s.recipient])}let c=String(a??"").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=YO(e.value_hex??e.valueHex??e.value??0);return{from:t,to:i,data:c,value:d.hex,chainId:n,valueWei:d.amount}}function Rs(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 Fd(e,t,n){let r=n.provider,o=!!n.rpcUrl;if(!r&&!o)return{simulated:!1,gasEstimates:[]};let i=await ve(e,4,async c=>{let{chainId:l,...u}=Rs(c);if(r){if(typeof r.call!="function"||typeof r.estimateGas!="function")throw new Error("opensea: supplied provider must implement call and estimateGas");let[,f]=await Promise.all([r.call(u),r.estimateGas(u)]);return BigInt(f).toString()}let{rpcCall:d}=await Promise.resolve().then(()=>(pe(),za)),p={...n,fetchImpl:n.rpcFetchImpl||n.fetchImpl},[,m]=await Promise.all([d(t,"eth_call",[u,"pending"],p),d(t,"eth_estimateGas",[u],p)]);return BigInt(m).toString()}),a=null,s=null;if(r&&typeof r.getFeeData=="function"){let c=await r.getFeeData();s=c?.maxPriorityFeePerGas==null?0n:BigInt(c.maxPriorityFeePerGas),a=c?.maxFeePerGas==null?c?.gasPrice==null?null:BigInt(c.gasPrice):BigInt(c.maxFeePerGas)}else if(o){let{rpcCall:c}=await Promise.resolve().then(()=>(pe(),za)),l={...n,fetchImpl:n.rpcFetchImpl||n.fetchImpl},u=BigInt(await c(t,"eth_gasPrice",[],l));try{s=BigInt(await c(t,"eth_maxPriorityFeePerGas",[],l))}catch{s=0n}let d=await c(t,"eth_getBlockByNumber",["pending",!1],l),m=(d?.baseFeePerGas==null?0n:BigInt(d.baseFeePerGas))*2n+s;a=u>m?u:m}return a!=null&&s!=null&&e.forEach((c,l)=>{let d=(BigInt(i[l])*120n+99n)/100n;c.gasLimit=d.toString(),c.maxPriorityFeePerGas=s.toString(),c.maxFeePerGas=a.toString(),c.worstCaseFeeWei=(d*a).toString()}),{simulated:!0,gasEstimates:i}}function lR(e,t){if(qy(e))throw new Error("opensea: approval steps are not permitted in NFT buy, sweep, or mint preparation");if(jy(e))throw new Error("opensea: signed transaction material refused");let n=zy(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=>Vy(r,t))}function uR(e,t,n={}){return N({...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 Wy(e={},t={}){throw new Error("opensea: public buy preparation disabled until canonical Seaport calldata is independently decoded and fully bound")}async function Gy(e={},t={}){throw new Error("opensea: public buy preparation disabled until canonical Seaport calldata is independently decoded and fully bound")}function dR(e,t,n){let o=(Array.isArray(e?.contracts)?e.contracts:[]).find(a=>String(a?.chain||t).toLowerCase()===t&&a?.address);if(!o)throw new Error("opensea: collection response contains no contract for requested chain");let i=Z(o.address,"collection NFT contract");if(i!==n)throw new Error("opensea: OpenSea returned the wrong collection contract");return i}async function Ls(e={},t={}){if(!Vt(t))throw new Error("OPENSEA_API_KEY required");cR(e);let{chain:n,chainId:r}=si(e.chain),o=Z(e.buyer||e.minter||e.address,"buyer"),i=Z(e.contract,"NFT contract"),a=$y(e.quantity),s=Ge(e.priceWei,"priceWei"),c=Ge(e.maxTotalWei,"maxTotalWei"),l=Number.isFinite(Number(t.nowMs))?Number(t.nowMs):Date.now(),u=By(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 ii(d,t),m=dR(p,n,i),f=s*BigInt(a);if(f>c)throw new Error("opensea: mint total exceeds total cap");let h=await S(`${Qn(t)}/drops/${encodeURIComponent(d)}/mint`,{method:"POST",headers:Zn(t),body:{minter:o,quantity:a},fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??25e3,retries:0,dedupe:!1}),g=t.allowedMintTargets?.[n]??t.allowedMintTargets?.[r]??e.mintTarget,w=Array.isArray(g)?g:g?[g]:[];if(!w.length)throw new Error("opensea: reviewed SeaDrop mintTarget required");let x=new Set(w.map(O=>Z(O,"SeaDrop mint target"))),b=lR(h,{buyer:o,chainId:r,targets:x});if(b.length!==1)throw new Error("opensea: mint must contain exactly one SeaDrop transaction");let y,k,E=null,I;try{y=_s.decodeFunctionData("mintPublic",b[0].data),k="public",I=_s.encodeFunctionData("mintPublic",[y[0],y[1],y[2],y[3]])}catch{try{y=_s.decodeFunctionData("mintAllowList",b[0].data),k="allowlist";let O=y[4],H=[...y[5]].map(String);if(H.length<1||H.length>64||H.some(ue=>!/^0x[0-9a-fA-F]{64}$/.test(ue)))throw new Error("opensea: allowlist mint requires a bounded canonical Merkle proof");let B=BigInt(O.startTime),z=BigInt(O.endTime),le=BigInt(Math.floor(l/1e3));if(B>le||z<=le)throw new Error("opensea: allowlist mint stage is not open");if(BigInt(O.mintPrice)!==s)throw new Error("opensea: allowlist stage price does not match exact approved price");if(BigInt(O.maxTotalMintableByWallet)<BigInt(a))throw new Error("opensea: allowlist wallet cap is below requested quantity");I=_s.encodeFunctionData("mintAllowList",[y[0],y[1],y[2],y[3],O,H]),E={mintPrice:BigInt(O.mintPrice).toString(),maxTotalMintableByWallet:BigInt(O.maxTotalMintableByWallet).toString(),startTime:B.toString(),endTime:z.toString(),dropStageIndex:BigInt(O.dropStageIndex).toString(),maxTokenSupplyForStage:BigInt(O.maxTokenSupplyForStage).toString(),feeBps:Number(O.feeBps),restrictFeeRecipients:!!O.restrictFeeRecipients,proof:H}}catch(O){throw/opensea:/.test(String(O?.message||""))?O:new Error("opensea: mint transaction must call reviewed SeaDrop mintPublic or mintAllowList")}}let v=Z(y[0],"mint NFT contract"),A=Z(y[1],"mint fee recipient"),P=Z(y[2],"mint recipient");if(v!==m)throw new Error("opensea: mint calldata collection mismatch");if(P!==o)throw new Error("opensea: mint calldata recipient mismatch");if(BigInt(y[3])!==BigInt(a))throw new Error("opensea: mint calldata quantity mismatch");if(I.toLowerCase()!==b[0].data.toLowerCase())throw new Error("opensea: mint calldata must be canonical with no suffix");let T=b.reduce((O,H)=>O+H.valueWei,0n);if(T!==f)throw new Error("opensea: mint transaction total does not match exact approved price and quantity");if(T>c)throw new Error("opensea: mint total exceeds total cap");let L=await Fd(b,r,{...t,provider:e.provider||t.provider});if(L.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},q=Sy({chainId:r,tx:b[0],policy:F});return uR({action:"mint",mintType:k,...E?{stage:E}:{},chain:n,chainId:r,slug:d,buyer:o,contract:m,quantity:a,priceWei:s.toString(),totalWei:T.toString(),maxTotalWei:c.toString(),mintTarget:b[0].to,feeRecipient:A,expiry:u,transactions:b.map(Rs),gasWar:q,...L},"nft-mint",{nowMs:l,expiresAtMs:Math.min(l+Ar,Date.parse(u),E?Number(BigInt(E.endTime)*1000n):Number.MAX_SAFE_INTEGER)})}function pR(e={}){let t=Ny(e.chain);if(Cy.has(t))throw new Error("opensea: listing actions currently require an EVM NFT chain");let n=e.startTime||e.start_time?Iy(e.startTime||e.start_time,"startTime"):{text:new Date().toISOString(),ms:Date.now()},r=Iy(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:Z(e.contract,"NFT contract"),token_id:o,quantity:GO(e.quantity??1,"quantity"),price:{amount:WO(e.price?.amount??e.amount??e.priceAmount,"price amount"),currency:Z(e.price?.currency??e.currency??ri,"price currency")},start_time:n.text,end_time:r.text}}var Br={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"}]},_y=new Ps(["function setApprovalForAll(address operator,bool approved)"]),mR=new Ps(["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 Py(e,t){return e?.[t]||(e?.action===t?e:null)}function fR(e,{seller:t,item:n,chainId:r}){let o=Array.isArray(e?.steps)?e.steps:[],i=o.map(b=>Py(b,"createListingsAction")).find(Boolean)||o.find(b=>/createListings/i.test(String(b?.action||""))),a=i?.signatureRequest?.message??i?.typedData,s;try{s=typeof a=="string"?JSON.parse(a):a}catch{throw new Error("opensea: invalid listing typed-data JSON")}if(!s||s.primaryType!=="OrderComponents"||!s.domain||!s.message)throw new Error("opensea: exact Seaport OrderComponents action required");let c=s.domain;if(c.name!=="Seaport"||c.version!=="1.6"||Number(c.chainId)!==r)throw new Error("opensea: listing domain mismatch");let l=Z(c.verifyingContract,"listing protocol"),u=s.message;if(Z(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(Z(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 b of u.consideration){if(Number(b.itemType)!==0||Z(b.token,"listing payment token")!==ri)throw new Error("opensea: executable listings currently require native fixed-price consideration");let y=BigInt(b.startAmount),k=BigInt(b.endAmount);if(y<=0n||y!==k)throw new Error("opensea: listing consideration must be fixed and positive");Z(b.recipient,"listing consideration recipient"),p+=y}let m=FO(n.price.amount,18);if(p!==m)throw new Error("opensea: listing price mismatch");let f=BigInt(Math.floor(Date.parse(n.start_time)/1e3)),h=BigInt(Math.floor(Date.parse(n.end_time)/1e3));if(BigInt(u.startTime)!==f||BigInt(u.endTime)!==h)throw new Error("opensea: listing time bounds mismatch");let g=Md.hashStruct("OrderComponents",Br,u),w=o.map(b=>Py(b,"itemApprovalAction")).find(Boolean)||o.find(b=>/setApprovalForAll/i.test(String(b?.action||""))),x=null;if(w){let b=w.transaction||w.itemApprovalAction?.transaction,y=Vy(b,{buyer:t,chainId:r,targets:new Set([n.contract])}),k;try{k=_y.decodeFunctionData("setApprovalForAll",y.data)}catch{throw new Error("opensea: listing approval must be setApprovalForAll")}let E=Z(k[0],"listing approval operator");if(k[1]!==!0||y.valueWei!==0n)throw new Error("opensea: listing approval must grant one exact operator with zero value");if(_y.encodeFunctionData("setApprovalForAll",[E,!0]).toLowerCase()!==y.data.toLowerCase())throw new Error("opensea: listing approval calldata must be canonical");x={...y,operator:E}}return{protocolAddress:l,typedData:{domain:c,types:Br,primaryType:"OrderComponents",message:u},orderHash:g,priceWei:p,approval:x}}async function $s(e={},t={}){if(!Vt(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=Z(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(pR);if(new Set(o.map(m=>m.chain)).size!==1)throw new Error("opensea: all prepared listing items must be on one chain");let a=e.useCreatorFee!==!1,s={address:n,items:o,use_creator_fee:a};e.taker&&(s.taker=Z(e.taker,"taker"));let c=await S(`${Qn(t)}/listings/actions`,{method:"POST",headers:Zn(t),body:s,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??25e3,retries:0,dedupe:!1}),{chainId:l}=si(o[0].chain),u=fR(c,{seller:n,item:o[0],chainId:l}),d=u.approval?[u.approval]:[],p=d.length?await Fd(d,l,{...t,provider:e.provider||t.provider}):{simulated:!0};return N({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(Rs),useCreatorFee:a,taker:s.taker||null,feeDisclosure:a?"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 Ky(e={},t={}){if(e.userConfirmed!==!0)throw new Error("opensea: userConfirmed=true required for listing cancellation");let{chain:n,chainId:r}=si(e.chain),o=Z(e.seller||e.address||e.owner,"seller"),i=Z(e.protocolAddress,"reviewed Seaport protocol address"),a=Z(e.contract,"NFT contract"),s=oi(e.tokenId),c=$y(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[v,A]of Object.entries(Br)){let P=l.types?.[v];if(!Array.isArray(P)||P.length!==A.length||P.some((T,L)=>T?.name!==A[L].name||T?.type!==A[L].type))throw new Error("opensea: cancellation requires canonical Seaport types")}if(Object.keys(l.types||{}).filter(v=>v!=="EIP712Domain").sort().join(",")!==Object.keys(Br).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=Z(d.verifyingContract,"Seaport cancellation target");if(p!==i)throw new Error("opensea: cancellation target mismatch");let m=l.message;if(Z(m.offerer,"listing seller")!==o)throw new Error("opensea: cancellation seller mismatch");if(!Array.isArray(m.offer)||m.offer.length!==1||!Array.isArray(m.consideration)||!m.consideration.length)throw new Error("opensea: cancellation requires one exact previously prepared listing order");if(Number(m.orderType)!==2)throw new Error("opensea: cancellation requires a FULL_RESTRICTED listing order");let f=m.offer[0];if(![2,3].includes(Number(f.itemType)))throw new Error("opensea: cancellation offer must be ERC721 or ERC1155");if(Z(f.token,"cancellation NFT contract")!==a)throw new Error("opensea: cancellation NFT contract mismatch");if(oi(f.identifierOrCriteria)!==s)throw new Error("opensea: cancellation tokenId mismatch");let h=Ge(f.startAmount,"cancellation offer startAmount",{positive:!0}),g=Ge(f.endAmount,"cancellation offer endAmount",{positive:!0});if(h!==BigInt(c)||g!==BigInt(c))throw new Error("opensea: cancellation quantity mismatch");for(let v of m.consideration){if(Number(v.itemType)!==0||Z(v.token,"cancellation payment token")!==ri)throw new Error("opensea: cancellation requires native fixed-price consideration");let A=Ge(v.startAmount,"cancellation consideration startAmount",{positive:!0}),P=Ge(v.endAmount,"cancellation consideration endAmount",{positive:!0});if(A!==P)throw new Error("opensea: cancellation consideration must be fixed and positive");Z(v.recipient,"cancellation consideration recipient")}let w=Ge(m.startTime,"cancellation startTime");if(Ge(m.endTime,"cancellation endTime",{positive:!0})<=w)throw new Error("opensea: cancellation listing time bounds invalid");let b=Md.hashStruct("OrderComponents",Br,m),y=String(e.orderHash||"").trim().toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(y)||y!==b.toLowerCase())throw new Error("opensea: cancellation order hash mismatch");let k=mR.encodeFunctionData("cancel",[[m]]),E=[{from:o,to:p,data:k,value:"0x0",valueWei:0n,chainId:r}],I=await Fd(E,r,{...t,provider:e.provider||t.provider});if(I.simulated!==!0)throw new Error("opensea: cancellation RPC simulation required");return N({provider:"opensea-nft",marketplace:"opensea",kind:"nft-cancel",action:"cancel-listing",prepareReady:!0,chain:n,chainId:r,seller:o,contract:a,tokenId:s,quantity:c,protocolAddress:p,orderHash:b,typedData:{domain:d,types:Br,primaryType:"OrderComponents",message:m},transactions:E.map(Rs),...I,requiresUserSignature:!0},{provider:"opensea-nft",kind:"nft-cancel"})}Mr();var ui=new Map,SR=Object.keys($e).map(Number),IR=Object.keys(et).map(Number),ER=Object.keys(Lr).map(Number),Kd=tr.map(e=>e.chainId),AR=[...new Set(Object.values(Ts))],Gd=new Set,ob=!1;function ib(e){if(!e||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Object.values(e))ib(t);return Object.freeze(e)}function C(e){if(!e?.id)throw new Error("registerProvider requires id");if(!e.venue)throw new Error("registerProvider requires venue");if(!Array.isArray(e.ops))throw new Error("registerProvider requires ops[]");let t=String(e.id);if(ob&&Gd.has(t))throw new Error(`registerProvider refuses to overwrite built-in provider: ${t}`);return ui.set(t,{chainIds:e.chainIds||[],auth:e.auth||"none",description:e.description||"",baseEnv:e.baseEnv||[],...e,id:t}),ui.get(t)}function Us(e){return ui.get(e)||null}function Fs({venue:e,op:t}={}){let n=[...ui.values()];return e&&(n=n.filter(r=>r.venue===e)),t&&(n=n.filter(r=>r.ops.includes(t))),n}function _R(){Gd.clear();for(let[e,t]of ui)Gd.add(e),ib(t);ob=!0}C({id:"hl-info",venue:"hl",chainIds:[],auth:"none",ops:["health","allMids","l2Book","outcomeMeta","clearinghouse","userFills","meta","metaAndAssetCtxs","candleSnapshot","openOrders","frontendOpenOrders","userState","spotMeta"],baseEnv:["HL_INFO_URL","HL_API_URL"],description:"Hyperliquid public /info"});C({id:"hl-vaults",venue:"hyperliquid-vaults",chainIds:[],auth:"none",ops:["health","summaries","details","userEquities","tracker"],execution:"read-only",baseEnv:["HL_INFO_URL","HL_API_URL"],description:"Read-only Hyperliquid vault summaries, vault details, user vault equities, and HLP tracking."});C({id:"hl-precompiles",venue:"hyperliquid",chainIds:[999],auth:"none",ops:["health","read","l1BlockNumber","markPx","oraclePx","spotPx","position","spotBalance","vaultEquity","withdrawable"],execution:"read-only",baseEnv:["HYPEREVM_RPC_URL","HYPER_EVM_RPC"],description:"HyperEVM L1Read precompiles (0x800-0x809). eth_call only. Includes HLP vault equity. No CoreWriter."});C({id:"protocol-templates",venue:"protocol-builder",chainIds:[],auth:"none",ops:["health","list","listNative","gate","prepareDeploy","buildNative","eval"],description:"Gated EVM templates plus deterministic Solana program and Bitcoin policy scaffolds. Native bundles require chain-specific compile, tests, and simulation before any unsigned deploy/funding prepare. NOT a firm audit."});C({id:"poly-public",venue:"poly",chainIds:[137],auth:"none",ops:["health","time","markets","book","midpoint","spread","price","events"],execution:"read-only",baseEnv:["POLY_CLOB_URL","POLY_GAMMA_URL"],description:"Polymarket CLOB + Gamma public REST"});C({id:"poly-clob",venue:"poly",chainIds:[137],auth:"none",ops:["health","prepareOrder"],execution:"prepare",localSignerSurfaces:["poly"],description:"Polymarket CLOB unsigned EIP-712 order prepare plus owner-operated local-signer submit. Hosted/keyless remains prepare-only."});C({id:"hl-delta-neutral",venue:"hyperliquid",chainIds:[],auth:"none",ops:["health","scan","quote","prepare","loop"],execution:"prepare",localSignerSurfaces:["hl"],description:"Hyperliquid funding carry. Armed through the existing hl signer. Hosted/keyless remains prepare-only. Not automated."});C({id:"lighter-delta-neutral",venue:"lighter",chainIds:[],auth:"none",ops:["health","scan","quote","prepare","loop"],execution:"prepare",localSignerSurfaces:["lighter"],description:"Lighter.xyz funding carry. Armed through the official sendTx local-signer. Hosted/keyless remains prepare-only. Not automated."});C({id:"portfolio",venue:"multichain-wallet",chainIds:[1,10,56,137,988,999,2741,4663,8453,42161,43114],auth:"none",ops:["health","balances","snapshot","history","valueGraph"],execution:"read-only",description:"Read-only balance aggregation across configured EVM chains, Solana, Bitcoin, and Hyperliquid, plus profile-local observation snapshots, history, and value graphs with explicit partial coverage."});C({id:"nft-portfolio",venue:"multichain-nft-wallet",chainIds:[1,10,137,988,999,2741,4663,8453,42161,43114],auth:"optionalApiKey",ops:["health","inventory","gallery","pnl","prepareList","traitSnipe"],execution:"prepare",baseEnv:["OPENSEA_API_KEY","MAGICEDEN_API_KEY","SATFLOW_API_KEY"],description:"Normalized EVM, Solana, and Bitcoin NFT inventory, static contact-sheet galleries, explicit PnL coverage, user-confirmed unsigned listing preparation, and evidence-gated trait-snipe buy intents."});C({id:"evm-simulate",venue:"onchain-simulation",chainIds:[1,10,56,137,988,999,2741,4663,8453,42161,43114],auth:"none",ops:["health","simulate"],execution:"read",baseEnv:[],description:"Pre-sign EVM transaction simulation: eth_call at pending state to catch reverts, decoded revert reasons (Error(string), Panic codes, custom-error selectors), and a buffered gas estimate. Distinguishes a genuine revert from an unreachable node \u2014 an infra failure is never reported as 'would fail'. A pass reflects current chain state and is explicitly not a guarantee."});C({id:"nft-mint",venue:"onchain-mint",chainIds:[1,10,56,137,988,999,2741,4663,8453,42161,43114],auth:"none",ops:["health","discover","prepare","priceGas","createTrigger","checkOpen"],execution:"prepare",localSignerSurfaces:["evm-nft"],baseEnv:[],description:"EVM NFT mints: discover the collection's mint entrypoint from bytecode, price a competitive EIP-1559 bid from fee-history percentiles, enforce gas-war caps, surface contract risk, and hand execution to the local signer after explicit arming and bounded grant."});C({id:"universal-mint-router",venue:"universal-nft-mint",chainIds:[],auth:"optionalApiKey",ops:["health","capabilities","prepare"],execution:"prepare",baseEnv:["OPENSEA_API_KEY"],description:"Prepare-only exact universal mint routing across reviewed EVM and Ordinals adapters. Universal Solana mint is RESEARCH_ONLY and disabled until canonical serialized-message decoding ships; the separate Magic Eden marketplace provider is unchanged. It never signs or broadcasts."});C({id:"universal-nft-lifecycle",venue:"universal-nft-lifecycle",chainIds:[],auth:"optionalApiKey",ops:["health","capabilities","route"],execution:"read",baseEnv:["OPENSEA_API_KEY","MAGICEDEN_API_KEY","SATFLOW_API_KEY"],description:"Read-only NFT lifecycle route discovery. It does not prepare, sign, or broadcast artifacts; callers must invoke and review the selected provider operation separately."});for(let[e,t,n]of[["universal-evm-nft-transfer","evm-nft-transfer","Exact unsigned ERC-721/ERC-1155 safeTransferFrom preparation."],["universal-solana-nft-transfer","solana-nft-transfer","Exact unsigned verified Metaplex NFT/Core transfer preparation."],["universal-ordinals-transfer","bitcoin-nft-transfer","Exact unsigned Ordinals PSBT transfer-plan preparation."]])C({id:e,venue:t,chainIds:[],auth:"none",ops:["health","prepare"],execution:"prepare",description:n});C({id:"contract-risk",venue:"onchain-bytecode",chainIds:[1,10,56,137,988,999,2741,4663,8453,42161,43114],auth:"none",ops:["health","scan"],execution:"read",baseEnv:[],description:"Structural contract risk from on-chain bytecode: retained owner powers (mint, blacklist, pause, fee changes) and upgradeability across EIP-1967, legacy zeppelinos, and EIP-1822 proxy slots. Complements behavioural sell simulation. Never reports 'safe' \u2014 a clean scan is weak evidence, not a guarantee."});C({id:"evm-token-sniper",venue:"evm-token-launches",chainIds:Kd,auth:"none",ops:["health","scan"],execution:"prepare",localSignerSurfaces:["evm-swap"],baseEnv:tr.flatMap(e=>e.rpcEnv),description:"One generic EVM token-sniping path across every configured EVM chain: live identity, pools, structural risk, sell simulation, quote, guarded transaction preparation, and local-signer execution handoff. Robinhood Chain is the default, not a special implementation."});C({id:"evm-rpc",venue:"evm",chainIds:[1,137,42161,8453,10,4663,999],auth:"none",ops:["health","healthAll","blockNumber","chainId","getBalance","call","erc20Allowance","erc20Balance","transactionReceipt"],baseEnv:["ETH_RPC_URL","POLYGON_RPC_URL","RH_CHAIN_RPC","BASE_RPC_URL","ARBITRUM_RPC_URL"],description:"EVM JSON-RPC multi-chain (env RPC or public fallbacks)"});C({id:"solana-rpc",venue:"solana",chainIds:[],auth:"none",ops:["health","latestBlockhash","getBalance","tokenAccounts","simulate"],baseEnv:["SOLANA_RPC_URL"],description:"Solana mainnet JSON-RPC read/prepare surface (no key, no signing, no broadcast)"});C({id:"bitcoin-esplora",venue:"bitcoin",chainIds:[],auth:"none",ops:["health","tipHeight","fees","address","utxos","tx","decode"],execution:"read-only",baseEnv:["BTC_ESPLORA_URL","BTC_NETWORK"],description:"Bitcoin L1 via Esplora (mempool.space/Blockstream). Reads only on data plane. User-signed broadcast is bitcoin_send on exec MCP. No Core RPC, no house keys. Wallets: Xverse/UniSat/Leather/OKX/Phantom"});C({id:"bitcoin-meta",venue:"bitcoin-metaprotocol",chainIds:[],auth:"optionalApiKey",ops:["health","runeBalances","inscriptions","inscriptionInfo","inscriptionChildren","ordBlockInfo"],execution:"read-only",baseEnv:["BTC_META_API_URL","UNISAT_API_KEY","BESTINSLOT_API_KEY"],description:"Bitcoin ordinals/runes reads. Keyless tier via ordinals.com recursive (inscriptionInfo/children/blockInfo); address-indexed ops (inscriptions, runeBalances) need a keyed indexer. Hiro is deprecated (410) and Magic Eden BTC is dead \u2014 use satflow for market."});C({id:"satflow",venue:"bitcoin-marketplace",chainIds:[],auth:"apiKey",ops:["health","collectionFloors","collectionStats","item","walletContents","floorListings","preparePurchase","prepareList"],execution:"prepare",localSignerSurfaces:["btc"],baseEnv:["SATFLOW_API_KEY","SATFLOW_API_URL"],description:"Satflow ordinals+runes marketplace (api.satflow.com). Primary BTC NFT market after Magic Eden BTC sunset. PSBT intents for buy/list; key via x-api-key."});C({id:"jupiter",venue:"solana-dex",chainIds:[],auth:"none",ops:["health","venues","quote","prepare"],execution:"prepare",localSignerSurfaces:["sol"],baseEnv:["JUPITER_SWAP_API_URL","SOLANA_RPC_URL"],description:"Jupiter Swap API v1 quote + local-signer Solana swap handoff"});C({id:"hl-perps",venue:"hyperliquid",chainIds:[],auth:"none",ops:["health","assetInfo","prepareOrder","prepareCancel","prepareLeverage","prepareIsolatedMargin","prepareBracket","prepareBuilderApproval"],execution:"prepare",localSignerSurfaces:["hl"],notes:"Hyperliquid perp, HIP-3, and HIP-4 outcome orders through local-signer L1 action handoff."});C({id:"hl-markets",venue:"hyperliquid",chainIds:[],auth:"none",ops:["health","markets","leaderboards","coin","spot"],notes:"Joined Hyperliquid market datapoints for the Hyperliquid agent. Read-only."});C({id:"hl-entry-state",venue:"hyperliquid",chainIds:[],auth:"none",ops:["health","see","qualify","lock","list","watch"],execution:"read-only",description:"SEE/ENTER/MANAGE for discretionary HL perps: compose sourced /info fields, qualify a side, lock the state only after a fill receipt, and alert_only-diff live vs that lock. Never signs."});C({id:"hl-staking",venue:"hypercore-staking",chainIds:[],auth:"none",ops:["health","validators","delegatorSummary","delegations","rewards","history","preflight","prepareStakeDeposit","prepareStakeWithdraw","prepareDelegate"],execution:"prepare",localSignerSurfaces:["hl"],baseEnv:["HL_INFO_URL","HL_EXCHANGE_URL","HL_TESTNET"],description:"Hyperliquid HyperCore HYPE staking. Public reads plus local-signer EIP-712 execution for cDeposit / cWithdraw / tokenDelegate after arming. Hosted/keyless remains prepare-only."});C({id:"magiceden-sol",venue:"solana-nft",chainIds:[],auth:"optionalApiKey",ops:["health","stats","listings","tokenListings","prepareBuy","prepareList","prepareMint"],execution:"prepare",baseEnv:["MAGICEDEN_API_KEY","MAGICEDEN_API_URL"],description:"Magic Eden Solana NFT market. Reads (stats/listings) are keyless; buy/list/mint instruction builders need MAGICEDEN_API_KEY and return an unsigned base64 transaction for the user's Solana wallet. Never signs or broadcasts."});C({id:"defillama",venue:"prices",chainIds:[],auth:"none",ops:["health","prices","pricesBySymbol","protocols","yields","stablecoins","dexVolumes"],baseEnv:["DEFILLAMA_COINS_URL","DEFILLAMA_API_URL"],description:"DeFiLlama public prices + protocols TVL"});C({id:"lifi",venue:"dex",chainIds:[1,10,56,137,988,999,2741,4663,8453,42161,43114],auth:"none",ops:["health","quote","prepare","chains"],execution:"prepare",baseEnv:["LIFI_API_URL"],description:"LI.FI public cross-chain / DEX aggregator quotes (no key)"});C({id:"dexscreener",venue:"dex",chainIds:[],auth:"none",ops:["health","token","search","pair"],baseEnv:["DEXSCREENER_API_URL"],description:"DexScreener public token/pair discovery"});C({id:"uniswap-v3",venue:"dex",chainIds:SR,auth:"none",ops:["health","quote","prepare","quotePath","ethUsdc","chains"],execution:"prepare",localSignerSurfaces:["evm-swap"],baseEnv:["ETH_RPC_URL","BASE_RPC_URL","ARBITRUM_RPC_URL","OPTIMISM_RPC_URL","BSC_RPC_URL","POLYGON_RPC_URL","AVALANCHE_RPC_URL","RH_CHAIN_RPC"],description:"Uniswap V3 QuoterV2 exact-in quotes via eth_call across official deployments plus Robinhood Chain, no key"});C({id:"lp-exit",venue:"dex",chainIds:ER,auth:"none",ops:["health","inspect","prepareRemove","prepareSettlement","prepareUnwrap","chains"],execution:"prepare",baseEnv:["ETH_RPC_URL","BASE_RPC_URL"],description:"Receipt-gated Uniswap V3 LP exit into native asset: remove/collect, net-route token legs, then unwrap. Unsigned only."});C({id:"lp-liquidity-ranker",venue:"dex",chainIds:Kd,auth:"none",ops:["health","rank"],execution:"read-only",description:"Cross-chain LP destination analysis: deepest liquidity and net-best migration are separate, exact canonical mappings required."});C({id:"lp-destination-discovery",venue:"dex",chainIds:Kd,auth:"none",ops:["health","discover"],execution:"read-only",description:"Live exact-address LP pool discovery across configured chains; reports deepest liquidity separately from cost-qualified migration evidence."});C({id:"uniswap-v4",venue:"dex",chainIds:IR,auth:"none",ops:["health","quote","inspectHook","prepare","chains"],execution:"prepare",baseEnv:["ETH_RPC_URL","BASE_RPC_URL","ARBITRUM_RPC_URL","OPTIMISM_RPC_URL","BSC_RPC_URL","POLYGON_RPC_URL","AVALANCHE_RPC_URL","RH_CHAIN_RPC"],description:"Uniswap V4 quotes, hook permission/code/pool-state inspection, and guarded unsigned Universal Router preparation across official deployments plus Robinhood Chain."});C({id:"x402",venue:"payments",chainIds:[],auth:"none",ops:["health","inspect","prepare"],execution:"prepare",description:"x402 v2 PAYMENT-REQUIRED inspection and explicit-cap exact-payment templates. Never signs, calls a facilitator, or retries a paid request."});C({id:"bankr",venue:"wallet-data",chainIds:[],auth:"apiKey",ops:["health","wallet","portfolio","swapQuote"],execution:"read-only",baseEnv:["BANKR_API_KEY","BANKR_API_URL"],description:"Bankr Wallet API read-only identity, portfolio, and swap quotes. Oracle excludes Bankr swap, transfer, sign, submit, agent, and LLM endpoints."});C({id:"aerodrome",venue:"dex",chainIds:[8453],auth:"none",ops:["health","quote","prepare","chains"],execution:"prepare",localSignerSurfaces:["evm-swap"],baseEnv:["BASE_RPC_URL"],description:"Aerodrome Slipstream CL on Base \u2014 QuoterV2 + SwapRouter exact-input via eth_call (tickSpacing, no key)"});C({id:"zerox",venue:"dex",chainIds:[1,10,137,8453,42161],auth:"apiKey",ops:["health","price","quote","prepare"],execution:"prepare",baseEnv:["ZEROX_API_KEY","ZEROX_API_URL"],description:"0x Swap API v2 price/quote/prepare \u2014 requires ZEROX_API_KEY (unconfigured without key; no Oracle key shipped)"});C({id:"across",venue:"bridge",chainIds:[1,10,137,42161,8453],auth:"none",ops:["health","suggestedFees"],baseEnv:["ACROSS_API_URL"],description:"Across bridge suggested-fees (public)"});C({id:"hop",venue:"bridge",chainIds:[1,10,137,42161],auth:"none",ops:["health","quote"],baseEnv:["HOP_API_URL"],description:"Hop Protocol bridge quotes (public)"});C({id:"relay",venue:"bridge",chainIds:[1,10,137,8453,42161],auth:"none",ops:["health","quote","prepare"],execution:"prepare",baseEnv:["RELAY_API_URL"],description:"Relay.link bridge/swap quotes (public)"});C({id:"cowswap",venue:"dex",chainIds:[1,100,42161,8453],auth:"none",ops:["health","quote","prepareOrder","order","status","chains","arm"],execution:"armed-local",localSignerSurfaces:["evm-order"],baseEnv:[],description:"CowSwap batch auction. Quote is public; Allow posts official api.cow.fi orders."});C({id:"oneinch",venue:"dex",chainIds:[1,10,137,8453,42161],auth:"apiKey",ops:["health","quote","prepare","approveSpender"],execution:"prepare",baseEnv:["ONEINCH_API_KEY","ONEINCH_API_URL"],description:"1inch Swap API v6 quote/prepare \u2014 requires ONEINCH_API_KEY (unconfigured without key; no Oracle key shipped)"});C({id:"hl-ws",venue:"hl",chainIds:[],auth:"none",ops:["health","allMids","l2Book","snapshot"],baseEnv:["HL_WS_URL"],description:"Hyperliquid short-lived WS snapshots (allMids/l2Book)"});C({id:"poly-ws",venue:"poly",chainIds:[137],auth:"none",ops:["health","book","snapshot"],baseEnv:["POLY_WS_URL"],description:"Polymarket CLOB short-lived WS market snapshots"});C({id:"anvil-nft",venue:"robinhood-nft",chainIds:[4663],auth:"optionalApiKey",ops:["health","markets","quoteSpecificBuy","quoteSell","scanCollection","scanAllMarkets","scanCrossVenueArb","scanAllMarketsArb","prepareSpecificBuy","prepareSell"],execution:"prepare",localSignerSurfaces:["evm-nft"],baseEnv:["RH_CHAIN_RPC","OPENSEA_API_KEY","OPENSEA_ENV_FILE"],description:"All-market Anvil discovery and exact-token arbitrage, with exact buy and sell execution through the armed owner-local signer after human confirmation"});C({id:"stonkbrokers",venue:"robinhood-nft",chainIds:[4663],auth:"optionalApiKey",ops:["health","quoteBrokerBuy","scanBrokerLoot","prepareBrokerBuy","brokerDesk","clockInStatus","prepareClockIn"],execution:"prepare",baseEnv:["RH_CHAIN_RPC"],description:"Unsigned StonkBrokers Broker Desk discovery, nested-loot verification, and bounded local-only preparations"});C({id:"opensea-nft",venue:"nft",chainIds:AR,auth:"apiKey",ops:["health","collection","floor","bestListings","bestListing","bestOffer","accountNfts","accountPnl","prepareMint","prepareList","prepareCancel"],execution:"prepare",baseEnv:["OPENSEA_API_KEY","OPENSEA_ENV_FILE"],description:"OpenSea multichain NFT inventory, floors, and unsigned bounded mint, listing, and listing-cancellation preparations; opaque buy/sweep fulfillment is disabled"});C({id:"local-marketplace",venue:"local-p2",chainIds:[],auth:"none",ops:["health","createListing","listListings","cancelListing","createOffer","armFill"],execution:"prepare",localSignerSurfaces:["evm-nft"],description:"Owner-local P2 catalog stored under ~/.config/oracle. Additive and isolated from OpenSea, Magic Eden, Satflow, Bisq, Anvil, and Polymarket. Listings are armed for the owner-local signer; sign-and-broadcast is an explicit createLocalMarketplace().instructFill instruction. Generic signHash is refused."});C({id:"local-x402",venue:"local-x402",chainIds:[],auth:"none",ops:["health","createIntent","listIntents","cancelIntent","armPayment"],execution:"prepare",localSignerSurfaces:["evm-swap"],description:"Owner-local x402 payment budgets under ~/.config/oracle. Additive and isolated from OpenSea and Telegram. Intents are armed; sign-and-broadcast is an explicit createLocalX402().instructPay instruction. Generic signHash is refused."});C({id:"local-pack-registry",venue:"local-packs",chainIds:[],auth:"none",ops:["health","registerPack","listPacks","revokePack"],execution:"read-only",description:"Owner-local third-party pack REGISTRY under ~/.config/oracle. Catalog only: packs are never loaded or executed. Isolated from OpenSea and Telegram."});C({id:"erc8004-identity",venue:"agent-identity",chainIds:[],auth:"none",ops:["health","prepareIdentityRegistration","prepareAgentURIUpdate","inspectIdentity","arm"],execution:"armed-local",localSignerSurfaces:["evm"],baseEnv:["ORACLE_ERC8004_CHAIN_ID","ORACLE_ERC8004_IDENTITY_REGISTRY"],description:"Draft ERC-8004 identity. Public prepare is keyless; Allow broadcasts type-2 register/setAgentURI."});C({id:"hyperevm-dex",venue:"hyperevm",chainIds:[999],auth:"none",ops:["health","search","token"],baseEnv:["HYPEREVM_RPC_URL"],description:"HyperEVM pair discovery via DexScreener + optional RPC"});C({id:"geckoterminal",venue:"dex-data",chainIds:[],auth:"none",ops:["health","networks","pool","token","ohlcv"],baseEnv:["GECKOTERMINAL_API_URL"],description:"GeckoTerminal public networks, pools, tokens, and OHLCV"});C({id:"curve",venue:"dex",chainIds:[1,10,56,137,988,999,4663,8453,42161,43114],auth:"none",ops:["health","openapi","pools","quote","prepare"],execution:"prepare",baseEnv:["CURVE_API_URL"],description:"Curve public pool registry API + RouterNG validated single-hop prepare"});C({id:"gmx",venue:"perps-data",chainIds:[42161,43114],auth:"none",ops:["health","tickers","markets","marketsInfo","tokens","prepareOrder","positions","orderStatus","verifyOrder"],execution:"intent",baseEnv:[],description:"GMX v2 public oracle/markets plus guarded async order intents on Arbitrum and Avalanche"});C({id:"morpho",venue:"lending-data",chainIds:[1,10,137,2741,8453,42161,4663,999,988],auth:"none",ops:["health","markets","vaults","prepareVault"],execution:"intent",baseEnv:["MORPHO_API_URL"],description:"Morpho public GraphQL markets/vaults + guarded ERC-4626 vault intents"});C({id:"balancer",venue:"dex",chainIds:[1,10,137,42161,43114,8453],auth:"none",ops:["health","pools","quote","prepare"],execution:"prepare",baseEnv:["BALANCER_API_URL"],description:"Balancer public GraphQL pool data + v3 Router exact-input prepare (Polygon read-only)"});C({id:"pendle",venue:"yield",chainIds:[1,10,56,8453,42161,999],auth:"none",ops:["health","markets","quote","prepare"],execution:"prepare",baseEnv:["PENDLE_API_URL"],description:"Pendle public yield-market API + Hosted SDK direct Convert prepare"});C({id:"odos",venue:"dex",chainIds:[1,10,56,137,8453,42161,43114,4663],auth:"none",ops:["health"],execution:"unavailable",deprecated:{since:"2026-07-30",reason:"Odos sunset the public SOR API; /sor/quote/v2 and v3 both return 410 Gone",evidence:"sunset: Thu, 30 Jul 2026 12:00:00 GMT response header"},baseEnv:["ODOS_API_URL"],description:"Odos public SOR (DEPRECATED upstream 2026-07-30 -- endpoint returns 410)"});C({id:"blockscout",venue:"explorer",chainIds:[1,10,137,8453,42161],auth:"none",ops:["health","stats","address","token"],baseEnv:[],description:"Verified public Blockscout REST v2 instances"});C({id:"paraswap",venue:"dex",chainIds:[1,10,56,137,8453,42161,43114,4663],auth:"none",ops:["health","tokens","price","quote","prepare"],execution:"prepare",baseEnv:["PARASWAP_API_URL"],description:"ParaSwap/Velora public price routes + validated transaction builder"});C({id:"rfq",venue:"intent-rfq",chainIds:[1,10,56,137,8453,42161,43114,4663],auth:"none",ops:["health","intent","quote"],execution:"prepare",baseEnv:["ZEROX_API_KEY","ONEINCH_API_KEY"],description:"Cross-chain RFQ intent normalizer and firm-quote fanout over reviewed venues. Prepares artifacts only, never signs or broadcasts."});C({id:"execution-strategies",venue:"oracle-native",chainIds:[],auth:"none",ops:["health","plan"],execution:"plan-only",baseEnv:[],description:"Oracle-native TWAP, VWAP, POV, iceberg, and implementation-shortfall planners. No Tread.fi/API dependency. Plans never sign or broadcast; every slice requires a fresh best-execution quote, policy check, simulation, confirmation, wallet signature, and receipt."});C({id:"polygon-staking",venue:"polygon-staking",chainIds:[137],auth:"none",ops:["health","validators","validatorDetail"],baseEnv:["POLYGON_STAKING_API_URL"],description:"Polygon POS staking validators"});C({id:"babylon-staking",venue:"btc-staking",chainIds:[],auth:"none",ops:["health","stats","finalityProviders","delegations"],execution:"read-only",baseEnv:["BABYLON_STAKING_API_URL"],description:"Babylon native BTC staking (staking-api.babylonlabs.io v2). Keyless per-staker positions from a PUBLIC key alone \u2014 APR, TVL, finality-provider roster, and delegations. Read-only; staking/unbonding is user-wallet."});C({id:"mempool-mining",venue:"btc-mining",chainIds:[],auth:"none",ops:["health","difficulty","poolShare","hashrate","rewardStats"],execution:"read-only",baseEnv:["MEMPOOL_API_URL"],description:"Bitcoin mining + network security telemetry via mempool.space /api/v1/mining. Difficulty retarget, pool concentration (top-1/top-3 share), hashrate trend, subsidy-vs-fee split."});C({id:"liquid-esplora",venue:"liquid",chainIds:[],auth:"none",ops:["health","tipHeight","addressInfo","assetInfo"],execution:"read-only",baseEnv:["LIQUID_ESPLORA_URL"],description:"Liquid Network (Blockstream sidechain) via Esplora. Same schema as bitcoin-esplora plus multi-asset issuance/peg stats. Confidential addresses return TXO counts only \u2014 amounts are blinded on chain and reported as such."});C({id:"hiro-stacks",venue:"stacks",chainIds:[],auth:"none",ops:["health","networkInfo","stackingInfo","poxCycles","blocks"],execution:"read-only",baseEnv:["HIRO_API_URL","HIRO_API_KEY"],description:"Stacks (Bitcoin L2) via Hiro public API. Network tip, PoX stacking state (the BTC-yield mechanism), and historical reward cycles. Keyless tier is ~20 rps; HIRO_API_KEY is optional and never required."});C({id:"tron-public",venue:"tron",chainIds:[],auth:"none",ops:["health","account","trc20Balances","trc20Transfers","chainParameters"],execution:"read-only",localSignerSurfaces:[],baseEnv:["TRON_API_URL","TRONGRID_API_KEY"],description:"Tron mainnet via public TronGrid. TRX balance, TRC20 token balances, USDT-TRC20 transfer history, chain parameters. Tron carries the largest USDT float of any chain. Keyless; TRONGRID_API_KEY only raises the rate ceiling and never travels to a non-TronGrid host."});C({id:"ton-public",venue:"ton",chainIds:[],auth:"none",ops:["health","accountState","jettonBalances","transactions"],execution:"read-only",localSignerSurfaces:[],baseEnv:["TON_API_URL","TONCENTER_API_KEY"],description:"TON via public toncenter. Account state + nanoton balance, jetton (TON's ERC20) balances, transaction history. The settlement layer for Telegram-native assets. Keyless; TONCENTER_API_KEY only raises the rate ceiling."});C({id:"cosmos-lcd",venue:"cosmos",chainIds:[],auth:"none",ops:["health","chains","balances","delegations","denomTrace"],execution:"read-only",localSignerSurfaces:[],baseEnv:["COSMOS_LCD_URL","COSMOS_CHAIN"],description:"Cosmos SDK chains via keyless LCD/REST \u2014 one provider, many chains (cosmoshub default, plus osmosis/celestia/injective/neutron/dydx/noble/kava, or any LCD via COSMOS_LCD_URL_<CHAIN>). Bank balances, staking delegations + unbondings + rewards, and IBC denom-trace resolution for ibc/<hash> denoms."});C({id:"sui-public",venue:"sui",chainIds:[],auth:"none",ops:["health"],execution:"unavailable",deprecated:{since:"2026-08-25",reason:"Sui public fullnodes return JSON-RPC -32601 because the JSON-RPC surface is deprecated",evidence:"Migrate the provider to Sui GraphQL or gRPC before restoring it to the live roster"},localSignerSurfaces:[],baseEnv:["SUI_RPC_URL"],description:"QUARANTINED: Sui public JSON-RPC is deprecated. A GraphQL or gRPC replacement has not shipped."});C({id:"aptos-public",venue:"aptos",chainIds:[],auth:"none",ops:["health","account","resources","coinBalances"],execution:"read-only",localSignerSurfaces:[],baseEnv:["APTOS_FULLNODE_URL","APTOS_API_KEY"],description:"Aptos mainnet via the public fullnode REST API. Ledger info, account sequence/auth key, Move resources, and coin balances (0x1::coin::balance view with a CoinStore resource fallback). Read-only; the transaction submit door is never called."});C({id:"ordinals-runes",venue:"btc-runes",chainIds:[],auth:"none",ops:["health","blockHeight","blockInfo","satInfo","runeInfo"],execution:"read-only",baseEnv:["ORDINALS_BASE_URL"],description:"Runes + sat/block index via a public ord server (ordinals.com). /r/blockheight is PLAIN TEXT; the /runes listing is 406 'JSON API disabled' so only per-rune lookup exists; rune names must drop the bullet spacer (UNCOMMONGOODS)."});C({id:"mempool-lightning",venue:"btc-lightning",chainIds:[],auth:"none",ops:["health","statistics","nodeRankings","nodeCountries"],execution:"read-only",baseEnv:["MEMPOOL_API_URL"],description:"Lightning Network topology via mempool.space. Capacity/channel/node aggregates, node rankings, country distribution. STALE-PRONE: the crawler snapshot has been observed weeks behind, so every response carries ageDays + a stale flag."});C({id:"bob-rootstock",venue:"btc-l2",chainIds:[60808,30],auth:"none",ops:["health","stats","addressInfo","tokenBalances"],execution:"read-only",baseEnv:["BOB_EXPLORER_URL","ROOTSTOCK_EXPLORER_URL"],description:"BOB (60808) and Rootstock (30) \u2014 the EVM Bitcoin L2s \u2014 via their Blockscout v2 instances (identical schema, one code path). Chain stats, gas prices, native balances, token holdings. Pass chainId 'all' to fan out."});C({id:"bisq-markets",venue:"bisq",chainIds:[],auth:"none",ops:["health","markets","ticker","trades"],execution:"read-only",baseEnv:["BISQ_MARKETS_URL"],description:"Bisq non-KYC P2P BTC price discovery (markets.bisq.network). Value is the BASIS against centralized spot, not the absolute print: volume is thin and the last trade can be hours old, so trade age is always reported."});C({id:"social-intel",venue:"oracle-social",chainIds:[],auth:"none",ops:["health","trendingTokens","trendingCas","keywordMentions","smartAccounts","narratives"],execution:"read-only",localSignerSurfaces:[],baseEnv:["ORACLE_SOCIAL_INTEL_STORE","ORACLE_SOCIAL_INTEL_STALE_MIN"],description:"Local curated-account crypto social intelligence. Sample = graded caller list, NOT a firehose; every response reports sample size and snapshot age."});C({id:"magiceden-ordinals",venue:"btc-ordinals-market",chainIds:[],auth:"none",ops:["health","collectionStat"],execution:"read-only",baseEnv:["MAGICEDEN_ORD_API_URL","MAGICEDEN_API_KEY","MAGICEDEN_PROBE_COLLECTION"],description:"Magic Eden ordinals collection stats. DEGRADED UPSTREAM: /v2/ord/btc/* returned 503 'no healthy upstream' on every verification attempt. health() reports ok:false while it is down and collectionStat() returns upstreamDown:true with fallback 'satflow' instead of throwing. Only /stat is wired; 600 req/min documented."});C({id:"braiins-insights",venue:"btc-mining",chainIds:[],auth:"none",ops:["health","priceStats","poolStats"],execution:"read-only",baseEnv:["BRAIINS_INSIGHTS_URL"],description:"Braiins mining insights \u2014 BTC price tick + per-pool block/hashrate distribution. Use insights.braiins.com (302s to learn.braiins.com, followed transparently); pool.braiins.com/api is 403 and is NOT the public API."});C({id:"pyth-price-feeds",venue:"solana-oracle",chainIds:[],auth:"none",ops:["health","latestPrice","latestPrices","feedDirectory"],baseEnv:["PYTH_HERMES_URL"],description:"Pyth Network: Solana price feeds with confidence intervals, real-time updates, zero auth"});C({id:"solend-lending",venue:"solana-lending",chainIds:[],auth:"none",ops:["health","markets","reserves"],baseEnv:["SAVE_API_URL"],description:"Solend/Save lending: markets + per-reserve supply/borrow APY, Solana's Aave equivalent (keyless)"});C({id:"jito-mev",venue:"solana-mev",chainIds:[],auth:"none",ops:["health","recentBundles","tipFloor"],baseEnv:["JITO_API_URL"],description:"Jito MEV: recent bundles, tippers, tip floor \u2014 real-time Solana MEV data (keyless)"});C({id:"sanctum-lst",venue:"solana-staking",chainIds:[],auth:"none",ops:["health","lstList","apyAll","apyIndividual"],baseEnv:["SANCTUM_API_URL"],description:"Sanctum LST: liquid staking tokens with per-token APY \u2014 JitoSOL, mSOL, bSOL, compSOL, pathSOL, etc. (keyless)"});C({id:"kamino-strategies",venue:"solana-yield",chainIds:[],auth:"none",ops:["health","strategies","strategyMetrics"],baseEnv:["KAMINO_API_URL"],description:"Kamino: live yield strategies with APY, TVL, vault balances (keyless)"});C({id:"meteora-dlmm",venue:"solana-dex",chainIds:[],auth:"none",ops:["health","pools","poolSearch"],baseEnv:["METEORA_API_URL"],description:"Meteora DLMM: concentrated liquidity pools via amm-v2 API, distinct from Jupiter DEX routes (keyless)"});C({id:"aave-v3",venue:"evm-lending",chainIds:[1,10,56,137,59144,1088,534352,8453,42161,43114,5e3,1868],auth:"none",ops:["health","markets","marketReserves","chains"],baseEnv:["AAVE_V3_API_URL"],description:"Aave V3 GraphQL: multi-chain lending, full market + reserve schema with supplyInfo/borrowInfo (keyless)"});C({id:"cow-protocol",venue:"evm-intent",chainIds:[1,100,42161],auth:"none",ops:["health","auction","openOrders","recentTrades"],baseEnv:["COW_API_URL"],description:"CoW Protocol: intent/solver auction data, open orders, trades \u2014 intent-based DEX not covered by existing providers (keyless)"});C({id:"relayscan-mev",venue:"evm-mev",chainIds:[1],auth:"none",ops:["health","overview","builderProfit","dailyStats"],baseEnv:["RELAYSCAN_API_URL"],description:"Relayscan: MEV relay overview, builder profit rankings, daily block stats (keyless)"});C({id:"birdeye-tokens",venue:"solana-tokens",chainIds:[],auth:"none",ops:["health","tokenList"],baseEnv:["BIRDEYE_API_URL"],description:"Birdeye public token list: Solana tokens ranked by 24h volume, market cap (keyless)"});C({id:"das-assets",venue:"solana-nft",chainIds:[],auth:"none",ops:["health","assetsByOwner","searchAssets","assetProof"],baseEnv:["SOLANA_RPC_URL"],description:"Digital Asset Standard (DAS): compressed NFT reads via public Solana RPC \u2014 getAssetsByOwner, searchAssets, assetProof. No Helius key needed."});C({id:"symbiotic-restaking",venue:"evm-restaking",chainIds:[1],auth:"none",ops:["health","vaults","vaultDetail"],baseEnv:["SYMBIOTIC_API_URL"],description:"Symbiotic restaking: vaults with collateral data, approved status, operator metadata (keyless)"});C({id:"beefy-yields",venue:"evm-yield",chainIds:[1,10,56,137,8453,42161,43114,250,1088],auth:"none",ops:["health","apy","apyBreakdown"],baseEnv:["BEEFY_API_URL"],description:"Beefy Finance: cross-chain yield aggregator vaults with APY breakdowns (keyless)"});C({id:"across-bridge",venue:"evm-bridge",chainIds:[1,10,42161,8453,324,59144],auth:"none",ops:["health","pools","suggestedFees"],baseEnv:["ACROSS_API_URL"],description:"Across bridge: pool liquidity + APY per bridge pool with suggested fees (keyless)"});C({id:"spark-lend",venue:"evm-lending",chainIds:[1],auth:"none",ops:["health","markets"],baseEnv:["SPARK_API_URL"],description:"Spark Lend / Sky Savings: ERC-4626 vault APY + TVL + user count (keyless)"});C({id:"l2beat-tvl",venue:"evm-l2",chainIds:[],auth:"none",ops:["health","tvl","activity"],baseEnv:["L2BEAT_API_URL"],description:"L2Beat: L2 scaling TVL, project-level breakdowns, activity metrics (keyless)"});C({id:"celestia-da",venue:"evm-da",chainIds:[],auth:"none",ops:["health","stats","blockStats"],baseEnv:["CELENIUM_API_URL"],description:"Celestia DA via Celenium: blob stats, block-level blob counts, network metrics (keyless)"});C({id:"limit-order",venue:"1inch-lop",chainIds:[1,10,56,137,8453,42161],auth:"none",ops:["health","prepare","arm"],execution:"armed-local",localSignerSurfaces:["evm-order"],description:"1inch Limit Order Protocol v4. Queues on the local signer; Allow posts the order."});C({id:"jupiter-dca",venue:"jupiter",chainIds:[],auth:"none",ops:["health","prepare","arm"],execution:"armed-local",localSignerSurfaces:["sol"],description:"Jupiter limit/DCA. Unsigned tx queues on the sol signer; Allow submits."});C({id:"protective-monitors",venue:"oracle-intel",chainIds:[],auth:"none",ops:["health","depeg","oracleDeviation","exploitFeed","goplus","liquidationLadder"],execution:"read-only",description:"Alert-only depeg, oracle deviation, exploit feed, GoPlus second opinion, liquidation ladder."});C({id:"funding-scanner",venue:"perps",chainIds:[],auth:"none",ops:["health","scan"],execution:"read-only",description:"Cross-venue funding carry ranked net of fee drag. Failed venues stay FAILED."});C({id:"perp-universal",venue:"perps",chainIds:[],auth:"none",ops:["health","fundingAll","prepareOrder"],execution:"prepare-only",description:"Live fundingAll across HL/GMX/dYdX + honest FAILED Drift/Vertex. prepareOrder unsigned."});C({id:"onchain-options",venue:"options",chainIds:[],auth:"none",ops:["health","rank"],execution:"read-only",description:"Local Black-Scholes ranking. No arm until official Derive/Lyra domain is pinned."});C({id:"holder-clusters",venue:"oracle-intel",chainIds:[],auth:"none",ops:["health","score"],execution:"read-only",description:"Heuristic holder HHI + common-funding clusters. Not identity."});C({id:"kalshi",venue:"prediction",chainIds:[],auth:"none",ops:["health","markets"],execution:"read-only",description:"Kalshi market catalog read-only. Trading may be US-restricted. Prepare refused."});C({id:"derive-options",venue:"options",chainIds:[],auth:"none",ops:["health"],execution:"unavailable",deprecated:{since:"2026-08-25",reason:"No official Derive EIP-712 domain or contract is pinned, so prepare remains unavailable",evidence:"prepareOption() in onchain-options.mjs refuses unconditionally"},description:"UNAVAILABLE: Derive execution has no pinned official domain. Use onchain-options for local ranking."});C({id:"limitless",venue:"prediction",chainIds:[],auth:"none",ops:["health","markets"],execution:"read-only",description:"Limitless market catalog. Prepare refused \u2014 no grant-bound decoder."});C({id:"dov-vaults",venue:"options",chainIds:[],auth:"none",ops:["health"],execution:"unavailable",deprecated:{since:"2026-08-25",reason:"The reviewed DOV vault registry is empty, so every vault read refuses",evidence:"REVIEWED_DOV_VAULTS.length is zero and no reviewed code hash is pinned"},description:"UNAVAILABLE: the reviewed DOV vault registry is empty and every read fails closed."});C({id:"prediction-match",venue:"prediction",chainIds:[],auth:"none",ops:["health","match"],execution:"read-only",description:"Cross-venue event match. Same title is not a match."});C({id:"tee-attestation",venue:"identity",chainIds:[],auth:"none",ops:["health","verify"],execution:"read-only",description:"TEE schema stub. Hardware unavailable. Unknown root unverified."});C({id:"keeper-mirror",venue:"oracle-intel",chainIds:[],auth:"none",ops:["health"],execution:"read-only",description:"Keeper alert-mirror. Off by default. No execute path."});C({id:"erc7715-permissions",venue:"aa",chainIds:[],auth:"none",ops:["health","normalize"],execution:"read-only",description:"ERC-7715 permission normalize. Wildcards refused. aa allowlist empty."});C({id:"erc7710-delegation",venue:"aa",chainIds:[],auth:"none",ops:["health","inspect"],execution:"read-only",description:"ERC-7710 delegation inspect. Missing revocation/expiry fails closed."});C({id:"binance-public",venue:"cex",chainIds:[],auth:"none",ops:["health","ticker","orderbook","funding","markPrice","openInterest","fundingHistory"],execution:"read-only",localSignerSurfaces:[],baseEnv:["BINANCE_API_URL","BINANCE_FAPI_URL"],description:"Binance public spot + USD-M perp market data (ticker, depth, premiumIndex funding, open interest). Keyless reads only; no trading endpoints."});C({id:"okx-public",venue:"cex",chainIds:[],auth:"none",ops:["health","ticker","orderbook","funding","markPrice","openInterest"],execution:"read-only",localSignerSurfaces:[],baseEnv:["OKX_API_URL"],description:"OKX public v5 market data (ticker, books, swap funding-rate, mark-price, open-interest). Keyless reads only; no trading endpoints."});C({id:"bybit-public",venue:"cex",chainIds:[],auth:"none",ops:["health","ticker","orderbook","funding","markPrice","openInterest","fundingHistory"],execution:"read-only",localSignerSurfaces:[],baseEnv:["BYBIT_API_URL"],description:"Bybit public v5 market data (spot/linear tickers, orderbook, funding, open interest). Keyless reads only; no trading endpoints."});C({id:"cex-basis",venue:"cex",chainIds:[],auth:"none",ops:["health","basis","fundingSpread","legs"],execution:"read-only",localSignerSurfaces:[],baseEnv:["BINANCE_API_URL","OKX_API_URL","BYBIT_API_URL","HL_INFO_URL"],description:"Cross-venue perp basis and annualized funding spreads across Binance, OKX, Bybit and Hyperliquid public data. Analysis only, no sizing and no prepare."});C({id:"snapshot-governance",venue:"governance",chainIds:[],auth:"none",ops:["health","spaces","proposals","activeProposals","proposal","votes","votingPower"],execution:"read-only",localSignerSurfaces:[],baseEnv:["SNAPSHOT_API_URL"],description:"Snapshot.org off-chain governance reads: spaces, proposals, proposal detail, an address's votes and voting power. Never signs a vote."});C({id:"tally-governance",venue:"governance",chainIds:[1,10,42161],auth:"none",ops:["health","governors","info","proposals","proposal","voterStatus","tallyProposals"],execution:"read-only",localSignerSurfaces:[],baseEnv:["TALLY_API_URL","TALLY_API_KEY"],description:"Governor Bravo / OZ Governor on-chain proposal state and vote tallies for major DAOs, plus optional keyed Tally metadata. Read-only ABI has no vote/queue/execute selector."});C({id:"stablecoin-peg",venue:"oracle-intel",chainIds:[],auth:"none",ops:["health","scan"],execution:"read-only",localSignerSurfaces:[],baseEnv:[],description:"Peg-deviation scan across major and Hyperliquid-native stables. Ranks by absolute bps from $1 and classifies normal/watch/warn/depeg. Unpriced is unknown, never on-peg. Read-only composition of DefiLlama/Pyth/DexScreener."});_R();R();var m7=Object.freeze(["live","needs_key","deprecated","soft_fail","hard_down"]);function Ds(e={}){return e.execution==="unavailable"||!!e.deprecated}dt();dt();var OR=/^0x[0-9a-fA-F]{40}$/,pi="0xdfc24b077bc1425ad1dea75bcb6f8158e10df303";function Yd(e,t){let n=String(e||"").trim();if(!OR.test(n))throw new Error(`hl-vaults: ${t} must be a 0x EVM address`);return n.toLowerCase()}function pb(e){if(e==null||e==="")return null;let t=Number(e);return Number.isFinite(t)?t:null}function mb(e={}){let t=Array.isArray(e.portfolio)?e.portfolio:[],n=t.find(([i])=>i==="day")?.[1]||null,r=Array.isArray(n?.accountValueHistory)?n.accountValueHistory:[],o=Array.isArray(n?.pnlHistory)?n.pnlHistory:[];return{name:e.name??null,vaultAddress:e.vaultAddress??e.address??null,leader:e.leader??null,description:e.description??null,tvl:e.tvl??r.at(-1)?.[1]??null,apr:e.apr??null,pnl:e.pnl??o.at(-1)?.[1]??null,isClosed:e.isClosed??null,allowDeposits:e.allowDeposits??null,maxDistributable:e.maxDistributable??null,followers:e.followers??null,portfolio:t}}function RR(e){return[...e].sort((t,n)=>(pb(n.tvl)??-1)-(pb(t.tvl)??-1))}function Jd(e){return e.hlInfo||de}function Xd(e){return{...e,exec:!1,execution:"read-only",armed:!1}}async function Qd(e={},t={}){let n=await Jd(t)({type:"vaultSummaries"},t),r=RR((Array.isArray(n)?n:[]).map(mb));return Xd({provider:"hl-vaults",count:r.length,vaults:r,raw:n})}async function zs(e={},t={}){let r={type:"vaultDetails",vaultAddress:Yd(e.vaultAddress||e.address,"vaultAddress")};e.user&&(r.user=Yd(e.user,"user"));let o=await Jd(t)(r,t);return Xd({provider:"hl-vaults",vault:mb(o||{}),raw:o})}async function Zd(e={},t={}){let n=Yd(e.user||e.address,"user"),r=await Jd(t)({type:"userVaultEquities",user:n},t),o=(Array.isArray(r)?r:[]).map(i=>({vaultAddress:i.vaultAddress??i.address??null,equity:i.equity??i.vaultEquity??null}));return Xd({provider:"hl-vaults",user:n,count:o.length,positions:o,raw:r})}async function ep(e={},t={}){let n=String(e.mode||"hlp").toLowerCase();if(n==="hlp")return zs({...e,vaultAddress:pi},t);if(n==="summaries")return Qd(e,t);if(n==="details")return zs(e,t);if(n==="mine")return Zd(e,t);throw new Error("hl-vaults: mode must be hlp, summaries, details, or mine")}async function fb(e={}){try{let t=await ep({mode:"hlp"},e);return{ok:t.vault.vaultAddress===pi&&!!t.vault.name,provider:"hl-vaults",hlp:{name:t.vault.name,vaultAddress:t.vault.vaultAddress,tvl:t.vault.tvl,apr:t.vault.apr,allowDeposits:t.vault.allowDeposits},exec:!1,execution:"read-only",armed:!1}}catch(t){return{ok:!1,provider:"hl-vaults",error:String(t?.message||t).slice(0,160),exec:!1,execution:"read-only",armed:!1}}}pe();import{AbiCoder as $R}from"ethers";var tp=999;var Oe=Object.freeze({position:"0x0000000000000000000000000000000000000800",spotBalance:"0x0000000000000000000000000000000000000801",vaultEquity:"0x0000000000000000000000000000000000000802",withdrawable:"0x0000000000000000000000000000000000000803",delegations:"0x0000000000000000000000000000000000000804",delegatorSummary:"0x0000000000000000000000000000000000000805",markPx:"0x0000000000000000000000000000000000000806",oraclePx:"0x0000000000000000000000000000000000000807",spotPx:"0x0000000000000000000000000000000000000808",l1BlockNumber:"0x0000000000000000000000000000000000000809"}),np=Object.freeze({exec:!1,execution:"read-only",armed:!1,signing:!1,broadcasting:!1}),BR=$R.defaultAbiCoder();function mi(e,t){let n=String(e||"").trim();if(!/^0x[0-9a-fA-F]{40}$/.test(n))throw new Error(`hl-precompiles: ${t} must be a 0x EVM address`);return n.toLowerCase()}function fi(e,t,n){let r=Number(e);if(!Number.isInteger(r)||r<0||r>=2**n)throw new Error(`hl-precompiles: ${t} must fit uint${n}`);return r}function nr(e,t){return e.length?BR.encode(e,t):"0x"}function Wt(e,t=0){let r=String(e||"").replace(/^0x/i,"").slice(t*64,t*64+64);if(r.length!==64)throw new Error("hl-precompiles: malformed precompile result");return BigInt(`0x${r}`)}function MR(e,t=0){let n=Wt(e,t);return(n>=2n**255n?n-2n**256n:n).toString()}async function gn(e,t,n={}){if(typeof n.ethCall=="function")return n.ethCall({to:e,data:t,chainId:tp});let r=await D(tp,"eth_call",[{to:e,data:t},"latest"],n);if(typeof r!="string"||!/^0x[0-9a-fA-F]*$/.test(r))throw new Error("hl-precompiles: eth_call did not return hex");return r}function yn(e){return{provider:"hl-precompiles",chainId:tp,...np,...e}}async function Vs(e={}){let t=await gn(Oe.l1BlockNumber,"0x",e);return yn({op:"l1BlockNumber",precompile:Oe.l1BlockNumber,l1BlockNumber:Wt(t).toString(),raw:t})}async function rp(e={},t={}){let n=fi(e.index??e.assetId??0,"index",32),r=await gn(Oe.markPx,nr(["uint32"],[n]),t);return yn({op:"markPx",precompile:Oe.markPx,index:n,markPx:Wt(r).toString(),raw:r})}async function op(e={},t={}){let n=fi(e.index??e.assetId??0,"index",32),r=await gn(Oe.oraclePx,nr(["uint32"],[n]),t);return yn({op:"oraclePx",precompile:Oe.oraclePx,index:n,oraclePx:Wt(r).toString(),raw:r})}async function ip(e={},t={}){let n=fi(e.index??e.assetId??0,"index",32),r=await gn(Oe.spotPx,nr(["uint32"],[n]),t);return yn({op:"spotPx",precompile:Oe.spotPx,index:n,spotPx:Wt(r).toString(),raw:r})}async function ap(e={},t={}){let n=mi(e.user,"user"),r=fi(e.perp??e.assetId??0,"perp",16),o=await gn(Oe.position,nr(["address","uint16"],[n,r]),t);return yn({op:"position",precompile:Oe.position,user:n,perp:r,szi:MR(o,0),raw:o})}async function sp(e={},t={}){let n=mi(e.user,"user"),r=fi(e.token??0,"token",64),o=await gn(Oe.spotBalance,nr(["address","uint64"],[n,r]),t);return yn({op:"spotBalance",precompile:Oe.spotBalance,user:n,token:r,total:Wt(o,0).toString(),hold:Wt(o,1).toString(),raw:o})}async function cp(e={},t={}){let n=mi(e.user,"user"),r=mi(e.vaultAddress??e.vault??pi,"vault"),o=await gn(Oe.vaultEquity,nr(["address","address"],[n,r]),t);return yn({op:"vaultEquity",precompile:Oe.vaultEquity,user:n,vaultAddress:r,hlp:r===pi,equity:Wt(o,0).toString(),raw:o})}async function lp(e={},t={}){let n=mi(e.user,"user"),r=await gn(Oe.withdrawable,nr(["address"],[n]),t);return yn({op:"withdrawable",precompile:Oe.withdrawable,user:n,withdrawable:Wt(r).toString(),raw:r})}async function hb(e={},t={}){let n=String(e.op||e.mode||"l1BlockNumber");if(n==="l1BlockNumber")return Vs(t);if(n==="markPx")return rp(e,t);if(n==="oraclePx")return op(e,t);if(n==="spotPx")return ip(e,t);if(n==="position")return ap(e,t);if(n==="spotBalance")return sp(e,t);if(n==="vaultEquity"||n==="hlp")return cp(e,t);if(n==="withdrawable")return lp(e,t);throw new Error("hl-precompiles: op must be l1BlockNumber, markPx, oraclePx, spotPx, position, spotBalance, vaultEquity, or withdrawable")}async function gb(e={}){try{let t=await Vs(e);return{ok:BigInt(t.l1BlockNumber)>0n,provider:"hl-precompiles",...np,l1BlockNumber:t.l1BlockNumber,precompiles:Oe}}catch(t){return{ok:!1,provider:"hl-precompiles",...np,error:String(t?.message||t).slice(0,160)}}}dt();Y();function yb(e={}){let t=e.spotSizes??e.spotHeldSizes;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Gs(e={},t,n){let r=String(t||""),o=yb(e);if(o){let a=hi(o[r]);if(a==null)throw new Error(`${n}: held spot required for ${r}`);return a}let i=hi(e.spotSize??e.spotHeldSize);if(i==null)throw new Error(`${n}: prepare requires spotSize of held spot`);return i}function Ks(e={},t=[],n){let r=yb(e);if(t.length>1){if(!r)throw new Error(`${n}: multi-coin live loop requires spotSizes map`);for(let o of t)if(hi(r[o])==null)throw new Error(`${n}: held spot required for ${o}`);return}if(r){let o=t[0];if(o&&hi(r[o])==null)throw new Error(`${n}: held spot required for ${o}`);return}if(hi(e.spotSize??e.spotHeldSize)==null)throw new Error(`${n}: live loop requires spotSize of held spot`)}var up=Number.MAX_SAFE_INTEGER,Ws=String(up);function hi(e){if(typeof e=="number")return Number.isFinite(e)&&e>0&&e<=up?e:null;if(typeof e!="string"||!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(e))return null;let[t,n=""]=e.split(".");if(t.length>Ws.length||t.length===Ws.length&&t>Ws||t===Ws&&/[1-9]/.test(n))return null;let r=Number(e);return Number.isFinite(r)&&r>0&&r<=up?r:null}function Rb(){return{ok:!0,provider:"hl-delta-neutral",exec:!1,execution:"armed-local",signing:"local-signer",broadcasting:"local-signer",armed:!1,signed:!1,broadcast:!1,note:"capability only. Scan/quote/prepare are public. Sign/submit stay on the owner-operated hl signer. Not automated."}}function Kt(e){let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}function Lb(e){let t=Kt(e);if(t==null)throw new Error("hl-delta-neutral: funding rate required");return t*24*365*100}function c2(e,t,n=4){let r=Kt(e),o=Kt(t),i=Number.isInteger(Number(n))?Number(n):4;if(!(r>0))throw new Error("hl-delta-neutral: notionalUsd must be > 0");if(!(o>0))throw new Error("hl-delta-neutral: markPx must be > 0");let a=10**i;return String(Math.floor(r/o*a+1e-12)/a)}function $b(e){let t=Array.isArray(e?.[0]?.universe)?e[0].universe:[],n=Array.isArray(e?.[1])?e[1]:[],r=[];for(let o=0;o<t.length;o+=1){let i=t[o]||{},a=n[o]||{},s=String(i.name||"").trim(),c=Kt(a.funding),l=Kt(a.markPx??a.oraclePx),u=Kt(a.openInterest)??0;!s||c==null||!(l>0)||r.push({coin:s,szDecimals:Number.isInteger(Number(i.szDecimals))?Number(i.szDecimals):4,funding:c,markPx:l,oraclePx:Kt(a.oraclePx),openInterest:u,fundingAprPct:Lb(c)})}return r}function Bb(e,t){if(!e?.coin)throw new Error("hl-delta-neutral: coin required");let n=Kt(e.funding);if(n==null)throw new Error("hl-delta-neutral: funding required");let r=Lb(n),o=n>0,i={coin:e.coin,notionalUsd:Kt(t),markPx:e.markPx,fundingHourly:n,fundingAprPct:r,targetDelta:0,spot:o?"hold-existing":"short-spot-not-in-light-path",perpSide:o?"sell":"buy",perpSize:o?c2(t,e.markPx,e.szDecimals):"0",verdict:o?r>=5?"carry":"watch":"skip",posture:"light hold-spot / short-perp carry. A farm tick may prepare the perp hedge unsigned. Hosted stays prepare-only."};if(!(i.notionalUsd>0))throw new Error("hl-delta-neutral: notionalUsd must be > 0");return i}async function Ep(e={},t={}){let n=Math.min(24,Math.max(1,Number(e.limit??8)||8)),r=Number(e.minOpenInterest??0),o=await Ke(t),i=$b(o).filter(a=>a.funding>0&&a.openInterest>=r).sort((a,s)=>s.funding-a.funding||s.openInterest-a.openInterest).slice(0,n);return{live:!0,source:"Hyperliquid metaAndAssetCtxs",considered:Array.isArray(o?.[0]?.universe)?o[0].universe.length:0,candidates:i,posture:"read-only funding scan. Positive funding only. No signing."}}async function Ap(e={},t={}){let n=String(e.coin||"").trim();if(!n)throw new Error("hl-delta-neutral: coin required");let r=Number(e.notionalUsd??e.notional??1e3),o=await Ke(t),i=$b(o).find(a=>a.coin===n);if(!i)throw new Error(`hl-delta-neutral: ${n} not in Hyperliquid meta`);return Bb(i,r)}async function _p(e={},t={}){Ub(e,t,"hl-delta-neutral");let n=Fb(e.maxNotionalUsd??25e3,"hl-delta-neutral"),r=await Ap(e,t);if(r.verdict==="skip")return N({...r,prepared:!1,oraclePrepared:!1,surface:"hl",reason:"negative funding is outside the light hold-spot path"},{provider:"hl-delta-neutral",kind:"hl-carry-hedge"});let o=Gs(e,r.coin,"hl-delta-neutral");if(!Mb.test(String(e.owner||"")))throw new Error("hl-delta-neutral: prepare requires owner");if(Number(r.perpSize)-o>1e-12)throw new Error("hl-delta-neutral: hedge cannot exceed held spot");let{hlPreparePerpOrder:i}=await Promise.resolve().then(()=>(xi(),Ip)),a=await i({coin:r.coin,side:r.perpSide,size:r.perpSize,type:e.orderType||"limit",price:e.price??r.markPx,owner:e.owner,maxNotionalUsd:n},{fetchImpl:t.fetchImpl,nowMs:t.nowMs});if(a?.signed===!0||a?.broadcast===!0)throw new Error("hl-delta-neutral: prepare cannot sign or broadcast");let s=a?.localSignerEnvelope||null,c=a?.localSignerBlockedReason||null;return N({...r,prepared:!!s,surface:"hl",hedge:a,localSignerEnvelope:s,localSignerBlockedReason:c,signed:!1,broadcast:!1,signing:s?"awaiting-hl-signer":"blocked",oraclePrepared:!!s},{provider:"hl-delta-neutral",kind:"hl-carry-hedge"})}var Mb=/^0x[0-9a-fA-F]{40}$/;function Ub(e,t,n){if((t.hosted===!0||t.keyless===!0)&&(e.farming===!0||typeof t.signImpl=="function"))throw new Error(`${n}: hosted/keyless cannot sign`);if(e.farming===!0||typeof t.signImpl=="function"||typeof t.prepareImpl=="function")throw new Error(`${n}: farm cannot sign; use oracle signer`)}function l2(e,t,n){Ub(e,t,n)}function u2(e={}){if(e.halted===!0)throw new Error("hl-delta-neutral: loop is halted");let t=e.mode==="live"?"live":"shadow",n=Array.isArray(e.coins||e.allowlist)?(e.coins||e.allowlist).map(String):[],r=e.maxCoins??1;if(typeof r!="number"&&!(typeof r=="string"&&/^(?:0|[1-9]\d*)$/.test(r)))throw new Error("hl-delta-neutral: maxCoins must be an integer");let o=Number(r);if(!Number.isSafeInteger(o))throw new Error("hl-delta-neutral: maxCoins must be an integer");if(o<1||o>8)throw new Error("hl-delta-neutral: maxCoins must be between 1 and 8");let i=Fb(e.maxNotionalUsd??e.notionalUsd??e.notional??1e3,"hl-delta-neutral");if(t==="live"&&n.length===0)throw new Error("hl-delta-neutral: live loop requires a coin allowlist");if(t==="live"&&Ks(e,n,"hl-delta-neutral"),t==="live"&&!Mb.test(String(e.owner||"")))throw new Error("hl-delta-neutral: live loop requires owner");return{mode:t,allowlist:n,maxCoins:o,maxNotionalUsd:i,intervalMs:Math.max(3e4,Number(e.intervalMs??3e5)||3e5)}}function Fb(e,t){let n=typeof e=="string"&&e===e.trim()&&/^(?:0\.\d+|[1-9]\d*(?:\.\d+)?)$/.test(e);if(typeof e!="number"&&!n)throw new Error(`${t}: maxNotionalUsd out of bounds`);let r=Number(e);if(!(r>0)||r>25e3)throw new Error(`${t}: maxNotionalUsd out of bounds`);return r}async function Db(e={},t={}){l2(e,t,"hl-delta-neutral");let n=u2(e),r=await Ep({limit:e.limit??16,minOpenInterest:e.minOpenInterest},t),o=new Set(n.allowlist),i=[],a=Math.floor(n.maxNotionalUsd/n.maxCoins);for(let s of r.candidates){if(o.size&&!o.has(s.coin))continue;let c=Bb(s,a);if(c.verdict!=="carry")continue;if(i.length>=n.maxCoins)break;if(n.mode==="shadow"){i.push({...c,mode:"shadow",surface:"hl",prepared:!1,signed:!1,broadcast:!1});continue}let l=await _p({coin:c.coin,notionalUsd:c.notionalUsd,owner:e.owner,orderType:e.orderType,price:e.price,maxNotionalUsd:a,spotSize:e.spotSize??e.spotHeldSize,spotSizes:e.spotSizes??e.spotHeldSizes},{fetchImpl:t.fetchImpl,nowMs:t.nowMs});i.push({...l,mode:"live",surface:"hl"})}return{loop:!0,mode:n.mode,surface:"hl",signer:"hl",considered:r.considered,actions:i,nextWaitMs:n.intervalMs,signed:i.some(s=>s.signed===!0),broadcast:i.some(s=>s.broadcast===!0),posture:"one tick. Prepares an unsigned hedge for oracle signer. Armed, not automated. Farm loop never signs or broadcasts."}}R();Y();Dr();var p2=new Set(["https://mainnet.zklighter.elliot.ai/api/v1/sendTx","https://testnet.zklighter.elliot.ai/api/v1/sendTx"]),ki=14,qb=(e,t,n=256)=>{if(typeof e!="string"||!e||e.length>n)throw new Error(`lighter: bounded ${t} required`);return e};function Hr(e,t,n){if(!Number.isSafeInteger(e)||e!==t)throw new Error(`lighter: ${n} must be exact numeric ${t}`)}function Pp(e){let t=String(e||"").replace(/\/$/,"");if(!p2.has(t))throw new Error("lighter: submitTo must be the official Lighter sendTx");return t}function Hb(e,t={}){if(e?.surface!=="lighter")throw new Error("lighter: surface lighter required");let n=e.artifact;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("lighter: structured artifact required");let r=qb(n.kind,"kind",48);if(r!=="lighter-order")throw new Error("lighter: unsupported Lighter kind");if(e.action!=="order")throw new Error("lighter: surface/action/kind mismatch");if(String(e.destination).toLowerCase()!=="lighter")throw new Error("lighter: destination must be lighter");let o=Pp(n.submitTo),i=n.marketIndex;if(typeof i!="number"||!Number.isSafeInteger(i)||i<0)throw new Error("lighter: marketIndex required");let a=Number(rr(n.accountIndex,"lighter: accountIndex"));if(!Number.isSafeInteger(a)||a<0)throw new Error("lighter: accountIndex required");let s=Number(rr(n.clientOrderIndex,"lighter: clientOrderIndex"));if(!Number.isSafeInteger(s)||s<0)throw new Error("lighter: clientOrderIndex required");Hr(n.orderType,0,"orderType"),Hr(n.timeInForce,1,"timeInForce"),Hr(n.reduceOnly,0,"reduceOnly"),Hr(n.triggerPrice,0,"triggerPrice"),Hr(n.orderExpiry,-1,"orderExpiry");let c=qb(n.symbol||n.coin,"symbol",32),l=Array.isArray(t.lighterMarkets)?t.lighterMarkets.map(String):[];if(l.length&&!l.includes(c)&&!l.includes(String(i))&&!l.includes("*"))throw new Error("lighter: market not allowed");if(n.side!=="buy"&&n.side!=="sell")throw new Error("lighter: side must be buy or sell");let u=mt(n.baseAmount,"lighter: baseAmount"),d=mt(n.price,"lighter: price");if(u>BigInt(Number.MAX_SAFE_INTEGER)||d>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("lighter: baseAmount and price must be safe integers");let p=Number(u),m=Number(d),f=Number(n.sizeDecimals??0),h=Number(n.priceDecimals??0);if(!Number.isInteger(f)||f<0||f>12)throw new Error("lighter: sizeDecimals required");if(!Number.isInteger(h)||h<0||h>12)throw new Error("lighter: priceDecimals required");let g=f+h,w=u*d,x=_e(n.notionalUsd,g,"lighter: notionalUsd");if(x<=0n)throw new Error("lighter: notionalUsd required");if(w!==x)throw new Error("lighter: notionalUsd must match size and price");let b=_e(t.maxNotionalUsd??Number.MAX_SAFE_INTEGER,g,"lighter: maxNotionalUsd");if(w>b)throw new Error("lighter: notional exceeds cap");let y=Ce(n.notionalUsd,"lighter: notionalUsd");return Hr(n.txType,ki,"txType"),Object.freeze({unit:"usd",value:String(y),notional:String(y),fee:"0",kind:r,symbol:c,marketIndex:i,side:n.side,baseAmount:p,price:m,submitTo:o,actionType:"create-order",amount:String(y)})}function m2(e){let t=e.owner||e.user||e.from;if(!/^0x[0-9a-fA-F]{40}$/.test(String(t||"")))throw new Error("lighter: owner address required for local-signer envelope");return String(t).toLowerCase()}function jb(e,t={},n={}){if(String(e?.kind)!=="lighter-order")throw new Error("lighter: prepared kind is not a local-signer surface");let r=Number(n.nowMs??Date.now()),o=Math.min(6e4,Math.max(1e3,Number(t.ttlMs??t.expiresInMs??3e4)||3e4)),i=Pp(e.submitTo),a={version:1,surface:"lighter",action:"order",owner:m2(t),destination:"lighter",tradeId:String(t.tradeId||`lighter:${e.symbol}:${e.marketIndex}:${e.clientOrderIndex}`),expiresAtMs:r+o,slippageBps:Number(t.slippageBps??0),fee:{oracleFeeBps:0},provider:"lighter-delta-neutral",artifact:{kind:"lighter-order",symbol:e.symbol,marketIndex:e.marketIndex,side:e.side,baseAmount:e.baseAmount,price:e.price,notionalUsd:e.notionalUsd,sizeDecimals:e.sizeDecimals??0,priceDecimals:e.priceDecimals??0,clientOrderIndex:e.clientOrderIndex,txType:e.txType??ki,submitTo:i,accountIndex:e.accountIndex??t.accountIndex??null,orderType:e.orderType,timeInForce:e.timeInForce,reduceOnly:e.reduceOnly,triggerPrice:e.triggerPrice,orderExpiry:e.orderExpiry}};return Hb(a,{lighterMarkets:t.lighterMarkets||["*"],maxNotionalUsd:t.maxNotionalUsd??Number.MAX_SAFE_INTEGER}),a}var Vb="https://mainnet.zklighter.elliot.ai",Wb="https://testnet.zklighter.elliot.ai";function f2(e={}){return e.testnet||process.env.LIGHTER_TESTNET==="1"?Wb:Vb}function Gb(){return{ok:!0,provider:"lighter-delta-neutral",exec:!1,execution:"armed-local",signing:"local-signer",broadcasting:"local-signer",armed:!1,signed:!1,broadcast:!1,note:"capability only. Scan/quote/prepare are public. Sign/submit stay on the owner-operated lighter signer. Not automated."}}function Sn(e){let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}function h2(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 Kb(e){let t=Sn(e);if(t==null)throw new Error("lighter: funding rate required");return t*24*365*100}function g2(e,t,n=4){let r=Sn(e),o=Sn(t),i=Number.isInteger(Number(n))?Number(n):4;if(!(r>0))throw new Error("lighter: notionalUsd must be > 0");if(!(o>0))throw new Error("lighter: markPx must be > 0");let a=10**i;return Math.floor(r/o*a+1e-12)}function zb(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?e:null}function Cp(e,t){let n=Array.isArray(e?.funding_rates)?e.funding_rates:[],r=Array.isArray(t?.order_book_details)?t.order_book_details:[],o=new Map;for(let a of r){let s=zb(a.market_id);s!=null&&o.set(s,a)}let i=[];for(let a of n){if(String(a.exchange||"")!=="lighter")continue;let s=zb(a.market_id);if(s==null)continue;let c=o.get(s),l=Sn(c?.mark_price??c?.index_price),u=Sn(a.rate),d=String(a.symbol||c?.symbol||"").trim();!d||u==null||!(l>0)||i.push({coin:d,symbol:d,marketIndex:s,funding:u,markPx:l,openInterest:Sn(c?.open_interest)??0,sizeDecimals:Number(c?.supported_size_decimals??c?.size_decimals??4),priceDecimals:Number(c?.supported_price_decimals??c?.price_decimals??2),fundingAprPct:Kb(u)})}return i}function Yb(e,t){if(!e?.symbol&&!e?.coin)throw new Error("lighter: symbol required");let n=Sn(e.funding);if(n==null)throw new Error("lighter: funding required");let r=Kb(n),o=n>0,i={coin:e.symbol||e.coin,symbol:e.symbol||e.coin,marketIndex:e.marketIndex,notionalUsd:Sn(t),markPx:e.markPx,fundingHourly:n,fundingAprPct:r,targetDelta:0,spot:o?"hold-existing":"short-spot-not-in-light-path",perpSide:o?"sell":"buy",baseAmount:o?g2(t,e.markPx,e.sizeDecimals):0,price:Math.round(Number(e.markPx)*10**Number(e.priceDecimals||0)),sizeDecimals:e.sizeDecimals,priceDecimals:e.priceDecimals,verdict:o?r>=5?"carry":"watch":"skip",posture:"light hold-spot / short-perp carry on Lighter. Armed via official sendTx. Not automated."};if(!(i.notionalUsd>0))throw new Error("lighter: notionalUsd must be > 0");return i}async function Tp(e={}){let t=f2(e),n=new AbortController,r={fetchImpl:e.fetchImpl,retries:0,signal:n.signal};try{let[o,i]=await Promise.all([S(`${t}/api/v1/funding-rates`,r),S(`${t}/api/v1/orderBookDetails`,r)]);return{funding:o,books:i}}catch(o){throw n.abort(o),o}}async function Jb(e={}){let{funding:t,books:n}=await Tp(e);return{live:!0,source:"Lighter funding-rates + orderBookDetails",markets:Cp(t,n)}}async function Np(e={},t={}){let n=Math.min(24,Math.max(1,Number(e.limit??8)||8)),{funding:r,books:o}=await Tp(t),i=Cp(r,o).filter(a=>a.funding>0).sort((a,s)=>s.funding-a.funding||s.openInterest-a.openInterest).slice(0,n);return{live:!0,source:"Lighter funding-rates + orderBookDetails",considered:Array.isArray(r?.funding_rates)?r.funding_rates.filter(a=>a.exchange==="lighter").length:0,candidates:i,posture:"read-only Lighter funding scan. Positive funding only. No signing."}}async function Op(e={},t={}){let n=String(e.coin||e.symbol||"").trim();if(!n)throw new Error("lighter: coin required");let r=Number(e.notionalUsd??e.notional??1e3),{funding:o,books:i}=await Tp(t),a=Cp(o,i).find(s=>s.symbol===n);if(!a)throw new Error(`lighter: ${n} not in Lighter funding`);return Yb(a,r)}async function Rp(e={},t={}){Qb(e,t,"lighter");let n=Zb(e.maxNotionalUsd??25e3,"lighter");if(typeof e.accountIndex!="number"||!Number.isSafeInteger(e.accountIndex)||e.accountIndex<0)throw new Error("lighter: accountIndex required");let r=e.accountIndex,o=await Op(e,t);if(o.verdict==="skip")return N({...o,prepared:!1,oraclePrepared:!1,surface:"lighter",reason:"negative funding is outside the light hold-spot path"},{provider:"lighter-delta-neutral",kind:"lighter-order"});let i=Gs(e,o.coin,"lighter");if(!Xb.test(String(e.owner||"")))throw new Error("lighter: prepare requires owner");if(o.baseAmount/10**Number(o.sizeDecimals||0)-i>1e-12)throw new Error("lighter: hedge cannot exceed held spot");let s=!!(t.testnet||process.env.LIGHTER_TESTNET==="1"),c=Number(o.sizeDecimals||0)+Number(o.priceDecimals||0),l=h2(BigInt(o.baseAmount)*BigInt(o.price),c);if(e.clientOrderIndex!=null&&(typeof e.clientOrderIndex!="number"||!Number.isSafeInteger(e.clientOrderIndex)||e.clientOrderIndex<0))throw new Error("lighter: clientOrderIndex must be a safe integer");let u={...o,targetNotionalUsd:o.notionalUsd,notionalUsd:l,kind:"lighter-order",surface:"lighter",side:o.perpSide,clientOrderIndex:e.clientOrderIndex??Date.now()%1e9,accountIndex:r,orderType:0,timeInForce:1,reduceOnly:0,triggerPrice:0,orderExpiry:-1,txType:ki,submitTo:`${s?Wb:Vb}/api/v1/sendTx`,signed:!1,broadcast:!1},d=null,p=null;try{d=jb(u,{...e,maxNotionalUsd:n},t)}catch(f){p=String(f?.message||f).slice(0,200)}return N({...u,prepared:!!d,signing:d?"awaiting-lighter-signer":"blocked",localSignerEnvelope:d,localSignerBlockedReason:p,oraclePrepared:!!d},{provider:"lighter-delta-neutral",kind:"lighter-order"})}var Xb=/^0x[0-9a-fA-F]{40}$/;function Qb(e,t,n){if((t.hosted===!0||t.keyless===!0)&&(e.farming===!0||typeof t.signImpl=="function"))throw new Error(`${n}: hosted/keyless cannot sign`);if(e.farming===!0||typeof t.signImpl=="function"||typeof t.prepareImpl=="function")throw new Error(`${n}: farm cannot sign; use oracle signer`)}function y2(e,t,n){Qb(e,t,n)}function b2(e={}){if(e.halted===!0)throw new Error("lighter: loop is halted");let t=e.mode==="live"?"live":"shadow",n=Array.isArray(e.coins||e.allowlist)?(e.coins||e.allowlist).map(String):[],r=e.maxCoins??1;if(typeof r!="number"&&!(typeof r=="string"&&/^(?:0|[1-9]\d*)$/.test(r)))throw new Error("lighter: maxCoins must be an integer");let o=Number(r);if(!Number.isSafeInteger(o))throw new Error("lighter: maxCoins must be an integer");if(o<1||o>8)throw new Error("lighter: maxCoins must be between 1 and 8");let i=Zb(e.maxNotionalUsd??e.notionalUsd??e.notional??1e3,"lighter");if(t==="live"&&n.length===0)throw new Error("lighter: live loop requires a coin allowlist");if(t==="live"&&Ks(e,n,"lighter"),t==="live"&&!Xb.test(String(e.owner||"")))throw new Error("lighter: live loop requires owner");let a=e.accountIndex;if(t==="live"&&(typeof a!="number"||!Number.isSafeInteger(a)||a<0))throw new Error("lighter: live loop requires accountIndex");return{mode:t,allowlist:n,maxCoins:o,maxNotionalUsd:i,accountIndex:a}}function Zb(e,t){let n=typeof e=="string"&&e===e.trim()&&/^(?:0\.\d+|[1-9]\d*(?:\.\d+)?)$/.test(e);if(typeof e!="number"&&!n)throw new Error(`${t}: maxNotionalUsd out of bounds`);let r=Number(e);if(!(r>0)||r>25e3)throw new Error(`${t}: maxNotionalUsd out of bounds`);return r}async function ew(e={},t={}){y2(e,t,"lighter");let n=b2(e),r=await Np({limit:e.limit??16},t),o=new Set(n.allowlist),i=[],a=Math.floor(n.maxNotionalUsd/n.maxCoins);for(let s of r.candidates){if(o.size&&!o.has(s.symbol)&&!o.has(s.coin))continue;let c=Yb(s,a);if(c.verdict!=="carry")continue;if(i.length>=n.maxCoins)break;if(n.mode==="shadow"){i.push({...c,mode:"shadow",surface:"lighter",prepared:!1,signed:!1,broadcast:!1});continue}let l=await Rp({coin:c.symbol,notionalUsd:c.notionalUsd,maxNotionalUsd:a,owner:e.owner,accountIndex:n.accountIndex,spotSize:e.spotSize??e.spotHeldSize,spotSizes:e.spotSizes??e.spotHeldSizes},{fetchImpl:t.fetchImpl,nowMs:t.nowMs,testnet:t.testnet});i.push({...l,mode:"live",surface:"lighter"})}return{loop:!0,mode:n.mode,surface:"lighter",signer:"lighter",considered:r.considered,actions:i,signed:i.some(s=>s.signed===!0),broadcast:i.some(s=>s.broadcast===!0),posture:"one tick. Prepares an unsigned official sendTx for oracle signer. Armed, not automated. Farm loop never signs or broadcasts."}}R();var v2="https://clob.polymarket.com",x2="https://gamma-api.polymarket.com";function Si(e={}){return(e.clobUrl||process.env.POLY_CLOB_URL||v2).replace(/\/$/,"")}function tw(e={}){return(e.gammaUrl||process.env.POLY_GAMMA_URL||x2).replace(/\/$/,"")}async function Lp(e={}){return S(`${Si(e)}/time`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs})}async function nw(e={}){let t=await Lp(e);return{ok:t!=null&&t!=="",time:t}}async function rw({limit:e=5,offset:t=0,...n}={},r={}){let o=new URLSearchParams({limit:String(e),offset:String(t),...Object.fromEntries(Object.entries(n).filter(([,i])=>i!=null).map(([i,a])=>[i,String(a)]))});return S(`${tw(r)}/markets?${o}`,{fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs})}async function ow(e,t={}){if(!e)throw new Error("polyBook requires tokenId");let n=new URLSearchParams({token_id:String(e)});return S(`${Si(t)}/book?${n}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function iw(e,t={}){if(!e)throw new Error("polyMidpoint requires tokenId");let n=new URLSearchParams({token_id:String(e)});return S(`${Si(t)}/midpoint?${n}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function aw(e,t={}){if(!e)throw new Error("polySpread requires tokenId");let n=new URLSearchParams({token_id:String(e)});return S(`${Si(t)}/spread?${n}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function sw(e,{side:t="buy"}={},n={}){if(!e)throw new Error("polyPrice requires tokenId");let r=new URLSearchParams({token_id:String(e),side:String(t)});return S(`${Si(n)}/price?${r}`,{fetchImpl:n.fetchImpl,timeoutMs:n.timeoutMs})}async function cw({limit:e=5,offset:t=0,...n}={},r={}){let o=new URLSearchParams({limit:String(e),offset:String(t),...Object.fromEntries(Object.entries(n).filter(([,i])=>i!=null).map(([i,a])=>[i,String(a)]))});return S(`${tw(r)}/events?${o}`,{fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs})}pe();R();import{createHash as lw}from"node:crypto";var jr="mainnet-beta",S2="https://api.mainnet-beta.solana.com",$p="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";function I2(e={}){return String(e.rpcUrl||process.env.SOLANA_RPC_URL||S2).trim()}function he(e,t="address"){let n=String(e||"").trim();if(!/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(n))throw new Error(`solana-rpc: ${t} must be a base58 public key`);return n}function E2(e,t){return t?[...e,{commitment:t}]:e}async function Ii(e,t=[],n={}){let r=String(e||"");if(r==="sendTransaction"||r==="sendRawTransaction"||r==="requestAirdrop"||r==="requestAirDrop"||/airdrop/i.test(r)||/^send/i.test(r))throw new Error(`solana-rpc: ${r} refused \u2014 @oracle-agent/oracle is prepare-only (no broadcast/airdrop)`);let o=await S(I2(n),{method:"POST",body:{jsonrpc:"2.0",id:n.id||1,method:e,params:t},fetchImpl:n.fetchImpl,timeoutMs:n.timeoutMs??12e3});if(o?.error)throw new Error(`solana-rpc ${e}: ${o.error.message||JSON.stringify(o.error)}`);return o?.result}async function Bp(e={},t={}){let n=e.commitment?[{commitment:e.commitment}]:[],r=await Ii("getLatestBlockhash",n,t);return{provider:"solana-rpc",cluster:jr,blockhash:r?.value?.blockhash||null,lastValidBlockHeight:r?.value?.lastValidBlockHeight??null,slot:r?.context?.slot??null,raw:r}}async function uw(e={}){try{let[t,n]=await Promise.all([Ii("getHealth",[],e),Bp({},e)]);return{ok:t==="ok",provider:"solana-rpc",cluster:jr,health:t,latestBlockhash:n,exec:!1}}catch(t){return{ok:!1,provider:"solana-rpc",cluster:jr,error:String(t?.message||t),exec:!1}}}async function Zs(e={},t={}){let n=he(e.address||e.owner,"address"),r=await Ii("getBalance",E2([n],e.commitment),t);return{provider:"solana-rpc",cluster:jr,address:n,lamports:String(r?.value??0),slot:r?.context?.slot??null,raw:r}}function A2(e={}){let t=e.account?.data?.parsed?.info||{},n=t.tokenAmount||{};return{pubkey:e.pubkey,mint:t.mint||null,owner:t.owner||null,amount:String(n.amount??"0"),decimals:n.decimals??null,uiAmount:n.uiAmount??null,uiAmountString:n.uiAmountString??null,raw:e}}async function Ei(e={},t={}){let n=he(e.owner||e.address,"owner"),r=e.mint?{mint:he(e.mint,"mint")}:{programId:he(e.programId||$p,"token program")},o={encoding:"jsonParsed"};e.commitment&&(o.commitment=e.commitment);let i=await Ii("getTokenAccountsByOwner",[n,r,o],t),a=Array.isArray(i?.value)?i.value.map(A2):[];return{provider:"solana-rpc",cluster:jr,owner:n,filter:r,slot:i?.context?.slot??null,accounts:a,raw:i}}function _2(e){let t=String(e||"").trim();if(!/^[A-Za-z0-9+/]+={0,2}$/.test(t)||t.length%4!==0)throw new Error("solana-rpc: transaction must be base64");return t}function P2(e,t){let n=0,r=0,o=t;for(let i=0;i<3;i++){if(o>=e.length)throw new Error("solana-rpc: transaction shortvec truncated");let a=e[o++];if(n|=(a&127)<<r,(a&128)===0)return{value:n,offset:o};r+=7}throw new Error("solana-rpc: transaction shortvec too long")}function C2(e){let t=Buffer.from(e,"base64");try{let n=P2(t,0),r=n.offset+n.value*64;if(r>=t.length)throw new Error("missing message");return lw("sha256").update(t.subarray(r)).digest("hex")}catch{return lw("sha256").update(t).digest("hex")}}async function dw(e={},t={}){let n=_2(e.transaction||e.swapTransaction),r={encoding:"base64",sigVerify:!!e.sigVerify,replaceRecentBlockhash:e.replaceRecentBlockhash!==!1};e.commitment&&(r.commitment=e.commitment);let o=await Ii("simulateTransaction",[n,r],t),i=o?.value||{};return{provider:"solana-rpc",cluster:jr,ok:i.err==null,transactionHash:C2(n),err:i.err??null,logs:i.logs||[],unitsConsumed:i.unitsConsumed??null,replacementBlockhash:i.replacementBlockhash||null,slot:o?.context?.slot??null,raw:o}}R();var N2="mainnet",O2="https://mempool.space/api",R2="https://mempool.space/testnet/api";function Lt(e={}){return String(e.network||process.env.BTC_NETWORK||N2).trim().toLowerCase()==="testnet"?"testnet":"mainnet"}function Up(e={}){return e.baseUrl?String(e.baseUrl).replace(/\/$/,""):process.env.BTC_ESPLORA_URL?String(process.env.BTC_ESPLORA_URL).replace(/\/$/,""):Lt(e)==="testnet"?R2:O2}function Mp(e){let t=String(e||"");try{let n=new URL(t);(n.username||n.password)&&(n.username="[REDACTED]",n.password="");for(let r of[...n.searchParams.keys()])/^(key|api[_-]?key|token|secret|password|auth|bearer)$/i.test(r)&&n.searchParams.set(r,"[REDACTED]");t=n.toString().replace(/\/$/,"")}catch{}return t.replace(/(https?:\/\/)([^\s/:@]+):([^\s@/]+)@/gi,"$1[REDACTED]@").replace(/([?&](?:key|api[_-]?key|token|secret|password|auth|bearer)=)[^&\s]+/gi,"$1[REDACTED]")}function kt(e,t="address"){let n=String(e||"").trim();if(!/^(bc1|tb1|bcrt1)[a-z0-9]{20,90}$/i.test(n)&&!/^[13mn2][a-km-zA-HJ-NP-Z1-9]{25,34}$/.test(n))throw new Error(`bitcoin-esplora: ${t} must look like a Bitcoin address`);return n}function L2(e,t="txHex"){let n=String(e||"").trim().toLowerCase().replace(/^0x/,"");if(!/^[0-9a-f]+$/.test(n)||n.length<20||n.length%2!==0)throw new Error(`bitcoin-esplora: ${t} must be even-length hex`);return n}async function Fp(e,t={}){let n=`${Up(t)}${e.startsWith("/")?e:`/${e}`}`,o=await(t.fetchImpl||fetch)(n,{method:"GET",headers:{accept:"application/json,text/plain;q=0.9,*/*;q=0.8"},signal:AbortSignal.timeout(t.timeoutMs??12e3)}),i=await o.text();if(!o.ok)throw new Error(`bitcoin-esplora GET ${e}: HTTP ${o.status} ${i.slice(0,160)}`);return i}async function ec(e,t={}){let n=await Fp(e,t);try{return JSON.parse(n)}catch{return n}}async function pw(e={}){try{let t=await Fp("/blocks/tip/height",e),n=Number(t);return{ok:Number.isFinite(n)&&n>0,provider:"bitcoin-esplora",network:Lt(e),baseUrl:Mp(Up(e)),tipHeight:n,exec:!1,signing:"user-wallet"}}catch(t){return{ok:!1,provider:"bitcoin-esplora",network:Lt(e),baseUrl:Mp(Up(e)),error:Mp(t?.message||t),exec:!1}}}async function mw(e={}){let t=await Fp("/blocks/tip/height",e);return{provider:"bitcoin-esplora",network:Lt(e),tipHeight:Number(t)}}async function fw(e={}){try{let t=await ec("/v1/fees/recommended",e);return{provider:"bitcoin-esplora",network:Lt(e),fastestFee:t.fastestFee??null,halfHourFee:t.halfHourFee??null,hourFee:t.hourFee??null,economyFee:t.economyFee??null,minimumFee:t.minimumFee??null,raw:t}}catch{return{provider:"bitcoin-esplora",network:Lt(e),fastestFee:null,halfHourFee:null,hourFee:null,note:"fee endpoint unavailable on this Esplora host"}}}async function tc(e={},t={}){let n=kt(e.address||e.addr,"address"),r=await ec(`/address/${n}`,t),o=r.chain_stats||{},i=r.mempool_stats||{},a=Number(o.funded_txo_sum||0)+Number(i.funded_txo_sum||0),s=Number(o.spent_txo_sum||0)+Number(i.spent_txo_sum||0);return{provider:"bitcoin-esplora",network:Lt(t),address:n,balanceSats:String(a-s),chainStats:o,mempoolStats:i,raw:r}}async function hw(e={},t={}){let n=kt(e.address||e.addr,"address"),r=await ec(`/address/${n}/utxo`,t),o=Array.isArray(r)?r:[];return{provider:"bitcoin-esplora",network:Lt(t),address:n,count:o.length,totalSats:String(o.reduce((i,a)=>i+Number(a.value||0),0)),utxos:o.map(i=>({txid:i.txid,vout:i.vout,value:Number(i.value||0),status:i.status||null}))}}async function gw(e={},t={}){let n=String(e.txid||e.txId||"").trim().toLowerCase();if(!/^[0-9a-f]{64}$/.test(n))throw new Error("bitcoin-esplora: txid must be 64-char hex");let r=await ec(`/tx/${n}`,t);return{provider:"bitcoin-esplora",network:Lt(t),txid:n,confirmed:!!r.status?.confirmed,fee:r.fee??null,size:r.size??null,weight:r.weight??null,vinCount:Array.isArray(r.vin)?r.vin.length:null,voutCount:Array.isArray(r.vout)?r.vout.length:null,raw:r}}async function yw(e={},t={}){let n=L2(e.txHex||e.hex||e.transaction,"txHex");return{provider:"bitcoin-esplora",network:Lt(t),encoding:"hex",txHex:n,byteLength:n.length/2,note:"full decode is wallet/client-side or via bitcoinjs; Esplora returns broadcast acceptance only"}}vt();var Dp="https://ordinals.com";function nc(e={}){return String(e.baseUrl||process.env.BTC_META_API_URL||process.env.UNISAT_API_URL||"").trim().replace(/\/$/,"")}var B2=["open-api.unisat.io","open-api-testnet.unisat.io","api.bestinslot.xyz","api.hiro.so"];function bw(e={}){let t=e.apiKey||process.env.UNISAT_API_KEY||process.env.BESTINSLOT_API_KEY||process.env.BTC_META_API_KEY||"",n=!1;try{let r=nc(e);if(r){let o=new URL(r).host,i=new URL(r).protocol,a=/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(o);n=B2.includes(o)&&(i==="https:"||a)}}catch{n=!1}return Ie({accept:"application/json","user-agent":"oracle-btc-meta/0.1"},{authorization:t?`Bearer ${t}`:"","x-api-key":t},n)}async function zr(e,t={}){let r=await(t.fetchImpl||fetch)(e,{method:"GET",headers:bw(t),signal:AbortSignal.timeout(t.timeoutMs??12e3)}),o=await r.text(),i;try{i=JSON.parse(o)}catch{i=o}if(!r.ok)throw new Error(`bitcoin-meta GET ${e}: HTTP ${r.status} ${String(o).slice(0,160)}`);return i}async function ww(e={}){let t=nc(e),n=null;try{let i=await(e.fetchImpl||fetch)("https://ordinals.com/r/blockheight",{signal:AbortSignal.timeout(8e3)});n=Number(await i.text())}catch{n=null}if(!t)return{ok:n!=null,provider:"bitcoin-meta",indexerConfigured:!1,ordinalsComTip:n,note:"Set BTC_META_API_URL and/or UNISAT_API_KEY / BESTINSLOT_API_KEY for balances. Marketplace = Satflow (SATFLOW_API_KEY). Magic Eden BTC is dead.",capabilities:{tip:n!=null,runeBalances:!1,inscriptions:!1,marketplace:!1}};let r={ok:!1,path:null,status:null};for(let o of["/v1/indexer/brc20/best-height","/v1/health","/health","/"])try{let a=await(e.fetchImpl||fetch)(`${t}${o}`,{headers:bw(e),signal:AbortSignal.timeout(8e3)});if(r={ok:a.status>0&&a.status<500,path:o,status:a.status},a.ok)break}catch{}return{ok:r.ok||n!=null,provider:"bitcoin-meta",indexerConfigured:!0,baseUrl:t,probe:r,ordinalsComTip:n,apiKeyPresent:!!(process.env.UNISAT_API_KEY||process.env.BESTINSLOT_API_KEY||process.env.BTC_META_API_KEY),capabilities:{tip:n!=null,runeBalances:!0,inscriptions:!0,marketplace:!!process.env.SATFLOW_API_KEY}}}async function rc(e={},t={}){let n=kt(e.address||e.addr,"address"),r=nc(t);if(!r)return{provider:"bitcoin-meta",address:n,ok:!1,balances:[],error:"no indexer configured (set BTC_META_API_URL or vendor API key env)"};let o=[`${r}/v1/indexer/address/${n}/runes/balance-list?start=0&limit=100`,`${r}/v1/runes/address/${n}`,`${r}/runes/balance/${n}`,`${r}/address/${n}/runes`],i=null;for(let a of o)try{let s=await zr(a,t),c=M2(s);return{provider:"bitcoin-meta",address:n,ok:!0,count:c.length,balances:c,source:a}}catch(s){i=s}return{provider:"bitcoin-meta",address:n,ok:!1,balances:[],error:String(i?.message||i||"all indexer paths failed")}}function M2(e){let t=e?.data?.detail||e?.data?.list||e?.data||e?.balances||e?.results||e?.runes||(Array.isArray(e)?e:[]);return(Array.isArray(t)?t:[]).map(r=>({rune:r.rune||r.runeid||r.runeId||r.spacedRune||r.name||r.ticker||null,runeId:r.runeid||r.runeId||r.id||null,amount:String(r.amount??r.balance??r.total??r.qty??"0"),symbol:r.symbol||null,divisibility:r.divisibility??r.div??null,raw:r}))}async function Vr(e={},t={}){let n=kt(e.address||e.addr,"address"),r=nc(t);if(!r)return{provider:"bitcoin-meta",address:n,ok:!1,inscriptions:[],error:"no indexer configured \u2014 address-indexed lookups need a keyed indexer (BTC_META_API_URL + UNISAT_API_KEY / BESTINSLOT_API_KEY). ordinals.com recursive is keyless but has no address index.",unknownNotEmpty:!0,keylessAlternatives:["btc_inscription_info (by inscription id)","btc_meta_health"]};let o=Math.min(Number(e.limit||50),200),i=[`${r}/v1/indexer/address/${n}/inscription-data?cursor=0&size=${o}`,`${r}/v1/inscriptions/address/${n}?limit=${o}`,`${r}/address/${n}/inscriptions?limit=${o}`],a=null;for(let s of i)try{let c=await zr(s,t),l=U2(c);return{provider:"bitcoin-meta",address:n,ok:!0,count:l.length,inscriptions:l,source:s}}catch(c){a=c}return{provider:"bitcoin-meta",address:n,ok:!1,inscriptions:[],error:String(a?.message||a||"all indexer paths failed")}}async function vw(e={},t={}){let n=String(e.inscriptionId||e.id||"").trim();if(!/^[0-9a-f]{64}i\d+$/i.test(n))throw new Error("bitcoin-meta: inscriptionId must look like <64-hex-txid>i<index>");let r=t.ordinalsBase||Dp,o=await zr(`${r}/r/inscription/${n}`,t);return{provider:"bitcoin-meta",source:"ordinals.com/r",keyless:!0,inscriptionId:n,info:o}}async function xw(e={},t={}){let n=String(e.inscriptionId||e.id||"").trim();if(!/^[0-9a-f]{64}i\d+$/i.test(n))throw new Error("bitcoin-meta: inscriptionId must look like <64-hex-txid>i<index>");let r=t.ordinalsBase||Dp,o=Number(e.page||0),i=await zr(`${r}/r/children/${n}${o?`/${o}`:""}`,t);return{provider:"bitcoin-meta",source:"ordinals.com/r",keyless:!0,inscriptionId:n,page:o,children:Array.isArray(i?.ids)?i.ids:[],more:!!i?.more}}async function kw(e={},t={}){let n=t.ordinalsBase||Dp,r=e.height??await zr(`${n}/r/blockheight`,t),o=await zr(`${n}/r/blockinfo/${Number(r)}`,t);return{provider:"bitcoin-meta",source:"ordinals.com/r",keyless:!0,height:Number(r),info:o}}function U2(e){let t=e?.data?.inscription||e?.data?.detail||e?.data?.list||e?.data||e?.inscriptions||e?.results||(Array.isArray(e)?e:[]);return(Array.isArray(t)?t:[]).map(r=>({id:r.inscriptionId||r.id||r.inscription_id||null,number:r.inscriptionNumber??r.number??null,sat:r.sat||r.satoshi||null,contentType:r.contentType||r.content_type||null,utxo:r.utxo||r.output||(r.txid!=null?`${r.txid}:${r.vout??r.n}`:null),raw:r}))}vt();Y();var D2=["unsigned","notsigned","tosign","signable"],q2=new Set(["requiresusersignature","requiressignature","needssignature","signaturerequired","signaturesrequired","signingready","signaturecount","signaturethreshold","requiredsignatures","signatureneeded","hassignature","allowsignatures","requestsignature","multisig","cosig","msig"]),H2=new Set(["sig","sigs","scriptsig","witness","psbt","finalizedpsbt","completepsbt","finalpsbt","psbtfinalized","serializedtransaction"]);function qp(e){return String(e).toLowerCase().replace(/[^a-z0-9]/g,"")}function j2(e){return D2.some(t=>e.startsWith(t))||q2.has(e)}function z2(e){let t=String(e);if(!/^[\x20-\x7e]+$/.test(t))return!0;let n=qp(t);return j2(n)?!1:H2.has(n)?!0:n.includes("signed")||n.includes("signature")||n.endsWith("sig")||n.endsWith("sigs")}function V2(e){let t=Number(e?.v),n=String(e?.r||""),r=String(e?.s||"");return[0,1,27,28].includes(t)&&/^0x[0-9a-f]{2,64}$/i.test(n)&&/^0x[0-9a-f]{2,64}$/i.test(r)}function Hp(e,t=0,n=new Set,r={nodes:0}){if(e==null||typeof e!="object")return[];if(t>16)return["<max-depth>"];if(n.has(e))return[];if(r.nodes+=1,r.nodes>2048)return["<max-nodes>"];if(n.add(e),Array.isArray(e))return e.flatMap(c=>Hp(c,t+1,n,r));let o=[];for(let[c,l]of Object.entries(e)){if(z2(c)){o.push(c);continue}o.push(...Hp(l,t+1,n,r))}let a=Object.keys(e).map(qp).some(c=>c.endsWith("psbt")||c.endsWith("psbtbase64")),s=Object.entries(e).some(([c,l])=>/complete|finalized|isfinal/.test(qp(c))&&l===!0);return a&&s&&o.push("psbt(complete)"),V2(e)&&o.push("v/r/s"),o}function Yt(e,t){let n=Hp(t);if(n.length)throw new Error(`${e}: refused a pre-signed transaction payload from the API (fields: ${[...new Set(n)].join(", ")}) \u2014 @oracle-agent/oracle is prepare-only and will not bind signed material into a prepared envelope`)}var W2="https://api.satflow.com/v1";function Sw(e={}){return Ae({provider:"satflow",defaultUrl:W2,hosts:["api.satflow.com"],url:e.baseUrl||process.env.SATFLOW_API_URL})}function oc(e={}){return Sw(e).baseUrl}function zp(e={}){return String(e.apiKey||process.env.SATFLOW_API_KEY||process.env.BTC_SATFLOW_API_KEY||"").trim()}function G2(e={}){return Ie({accept:"application/json","content-type":"application/json","user-agent":"oracle-btc-satflow/0.1"},{"x-api-key":zp(e)},Sw(e).trusted)}async function In(e,{method:t="GET",body:n,opts:r={}}={}){if(!zp(r))throw new Error("satflow: SATFLOW_API_KEY not set (request key via Satflow docs form)");let i=`${oc(r)}${e.startsWith("/")?e:`/${e}`}`,s=await(r.fetchImpl||fetch)(i,{method:t,headers:G2(r),body:n!=null?JSON.stringify(n):void 0,signal:AbortSignal.timeout(r.timeoutMs??2e4)}),c=await s.text(),l;try{l=JSON.parse(c)}catch{l=c}if(!s.ok)throw new Error(`satflow ${t} ${e}: HTTP ${s.status} ${String(c).slice(0,200)}`);return l}async function Iw(e={}){if(!!!zp(e))return{ok:!1,provider:"satflow",baseUrl:oc(e),apiKeyPresent:!1,marketplace:"satflow",magicEdenOrdinals:"deprecated-dead",note:"Set SATFLOW_API_KEY. Magic Eden BTC ordinals marketplace is shut down \u2014 do not use ME."};try{return await In("/collection/stats/floors?type=ordinals",{opts:e}),{ok:!0,provider:"satflow",baseUrl:oc(e),apiKeyPresent:!0,marketplace:"satflow",magicEdenOrdinals:"deprecated-dead",capabilities:{floors:!0,walletContents:!0,purchaseIntent:!0,listIntent:!0,bidIntent:!0}}}catch(n){return{ok:!1,provider:"satflow",baseUrl:oc(e),apiKeyPresent:!0,error:String(n?.message||n).slice(0,200),magicEdenOrdinals:"deprecated-dead"}}}async function Ew(e={},t={}){let n=String(e.type||"ordinals").toLowerCase();if(!["ordinals","runes"].includes(n))throw new Error("satflow: type must be ordinals|runes");let r=new URLSearchParams({type:n});e.ids&&r.set("ids",Array.isArray(e.ids)?e.ids.join(","):String(e.ids));let o=await In(`/collection/stats/floors?${r}`,{opts:t});return{provider:"satflow",type:n,floors:o,magicEdenOrdinals:"deprecated-dead"}}async function Aw(e={},t={}){let n=String(e.collectionId||e.id||e.slug||"").trim();if(!n)throw new Error("satflow: collectionId required");let r=new URLSearchParams({id:n});e.type&&r.set("type",e.type);let o=await In(`/collection/stats?${r}`,{opts:t});return{provider:"satflow",collectionId:n,stats:o}}async function _w(e={},t={}){let n=String(e.inscriptionId||e.id||"").trim();if(!n)throw new Error("satflow: inscriptionId required");let r=new URLSearchParams({id:n});return{provider:"satflow",item:await In(`/item?${r}`,{opts:t})}}async function ic(e={},t={}){let n=kt(e.address||e.addr,"address"),r=new URLSearchParams({address:n});e.type&&r.set("type",e.type),e.limit!=null&&r.set("limit",String(e.limit)),e.offset!=null&&r.set("offset",String(e.offset));let o=await In(`/address/wallet-contents?${r}`,{opts:t});return{provider:"satflow",address:n,contents:o}}async function Pw(e={},t={}){let n=e.collectionIds||e.ids||e.collectionId;if(!n)throw new Error("satflow: collectionIds required");let r=new URLSearchParams({ids:Array.isArray(n)?n.join(","):String(n)});return e.limit!=null&&r.set("limit",String(e.limit)),{provider:"satflow",listings:await In(`/orders/floor?${r}`,{opts:t})}}var K2=new Set(["body","execute","fetchImpl","opts","apiKey","baseUrl","timeoutMs","maxSats","operator"]);function Cw(e={},t=null){let n=e.body&&typeof e.body=="object"?e.body:e,r={};for(let[o,i]of Object.entries(n))K2.has(o)||t&&!t.has(o)||i!==void 0&&(r[o]=i);return r}var Y2=new Set(["listing_id","listingId","inscription_id","inscriptionId","runes_output","runesOutput","buyer_address","buyerAddress","ord_address","receive_address","payment_address","pay_address","tap_key","public_key","publicKey","fee_rate","feeRate","price","quantity","slug","collection_slug"]),J2=new Set(["inscription_id","inscriptionId","runes_output","runesOutput","ord_address","receive_address","price","tap_key","collection_slug","expires_at"]);function jp(e){if(!e||typeof e!="object")return null;let t=[e.price,e.priceSats,e.price_sats,e.totalSats,e.total_sats,e.amount,e.satoshis];for(let n of t){if(n==null)continue;let r=String(n).trim();if(/^\d+$/.test(r))return BigInt(r)}return null}function X2(e={},{psbt:t,priceSats:n,nowMs:r=Date.now()}={}){if(!t)throw new Error("satflow: local signer envelope requires unsigned PSBT");let o=kt(e.owner||e.buyer_address||e.buyerAddress||e.payment_address||e.pay_address,"owner"),i=kt(e.destination||e.seller_address||e.sellerAddress||e.payment_destination,"destination"),a=String(e.network||"bitcoin").toLowerCase();if(!["bitcoin","mainnet","testnet","signet","regtest"].includes(a))throw new Error("satflow: unsupported Bitcoin network");return{version:1,surface:"btc",action:"transfer",owner:o,destination:i,tradeId:e.tradeId||`satflow-${e.listing_id||e.listingId||e.inscription_id||e.inscriptionId||"purchase"}`,slippageBps:0,expiresAtMs:Number(r)+Math.min(Math.max(Number(e.ttlMs??e.expiresInMs??3e4)||3e4,1e3),6e4),fee:{oracleFeeBps:0},artifact:{network:a,psbt:t},meta:{provider:"satflow",kind:"purchase-intent",priceSats:String(n)}}}async function Tw(e={},t={}){let n=Cw(e,Y2);if(!n||Object.keys(n).length===0)throw new Error("satflow: purchase body required (see docs.satflow.com intent/satflow-purchase)");let r=e.maxSats??e.body?.maxSats;if(r==null)throw new Error("satflow: maxSats is required to prepare a purchase \u2014 an uncapped buy has no spend ceiling");let o=BigInt(String(r).trim());if(o<=0n)throw new Error("satflow: maxSats must be a positive integer sat amount");let i=jp(n);if(i!=null&&i>o)throw new Error(`satflow: requested price ${i} sats exceeds maxSats cap ${o}`);let a=await In("/intent/satflow-purchase",{method:"POST",body:n,opts:t}),s=jp(a)??jp(a?.intent);if(s==null)throw new Error("satflow: purchase intent did not report a price \u2014 refusing to return an unverifiable PSBT");if(s>o)throw new Error(`satflow: purchase price ${s} sats exceeds maxSats cap ${o} \u2014 PSBT withheld`);Yt("satflow",a);let c=a?.unsignedPSBTBase64||a?.unsignedPsbtBase64||a?.unsigned_psbt||null,l=null,u=null;try{l=X2(e,{psbt:c,priceSats:s,nowMs:t.nowMs})}catch(d){u=String(d?.message||d).slice(0,200)}return N({provider:"satflow",kind:"purchase-intent",executionReady:!1,signingReady:!1,broadcastReady:!1,requiresUserSignature:!0,marketplace:"satflow",magicEdenOrdinals:"deprecated-dead",priceSats:s.toString(),maxSats:o.toString(),intent:a,unsignedPsbt:c,localSignerEnvelope:l,localSignerBlockedReason:u,note:"Sign PSBT in a Bitcoin wallet. Broadcast only through the user's wallet or an explicitly armed Bitcoin execution plane."})}async function ac(e={},t={}){let n=Cw(e,J2);if(!n.inscription_id&&!n.runes_output&&!n.inscriptionId&&!n.runesOutput)throw new Error("satflow: list requires inscription_id or runes_output");let r=await In("/intent/sell",{method:"POST",body:n,opts:t});return Yt("satflow",r),N({provider:"satflow",kind:"list-intent",requiresUserSignature:!0,marketplace:"satflow",listingRequest:n,intent:r,unsignedPsbt:r?.unsignedListingPSBTBase64||r?.unsigned_psbt||null,note:"Sign listing PSBTs in a Bitcoin wallet; listing broadcast is outside the data plane."})}R();Y();var cc="https://lite-api.jup.ag/swap/v1",Vp="So11111111111111111111111111111111111111112",Rw="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",Z2=100,Nw=2e4;function Lw(e={}){return String(e.baseUrl||process.env.JUPITER_SWAP_API_URL||cc).replace(/\/$/,"")}function Ai(e,t="amount"){try{let n=BigInt(String(e));if(n<=0n)throw new Error("nonpositive");return n.toString()}catch{throw new Error(`jupiter: ${t} must be a positive integer string`)}}function $w(e){let t=e==null?50:Number(e);if(!Number.isInteger(t)||t<0)throw new Error("jupiter: slippageBps must be a non-negative integer");if(t>Z2)throw new Error("jupiter: slippage exceeds hard 100 bps cap");return t}function sc(e,t){return e==null?t:!!e}function eL(e){let t=String(e||"").trim();if(!/^[A-Za-z0-9+/]+={0,2}$/.test(t)||t.length%4!==0)throw new Error("jupiter: swapTransaction must be base64");return t}function tL(e,t=0){let n=0,r=0,o=t;for(;o<e.length&&o-t<3;){let i=e[o++];if(n|=(i&127)<<r,(i&128)===0)return{value:n,offset:o};r+=7}return null}function Bw(e){let t=Buffer.from(e,"base64"),n=tL(t,0);if(!n||n.value!==1)throw new Error("jupiter: unsigned swapTransaction must declare exactly one signature slot");let r=n.offset+n.value*64;if(r>=t.length)throw new Error("jupiter: Solana transaction missing message bytes");if(t.subarray(n.offset,r).some(i=>i!==0))throw new Error("jupiter: swapTransaction already contains signature material");return t.subarray(r).toString("base64")}function _i(e={},{quotedAtMs:t=Date.now(),ttlMs:n=Nw}={}){let r=he(e.inputMint,"inputMint"),o=he(e.outputMint,"outputMint"),i=Ai(e.inAmount,"inAmount"),a=Ai(e.outAmount,"outAmount"),s=Ai(e.otherAmountThreshold??e.outAmount,"otherAmountThreshold"),c=$w(e.slippageBps??50),l=(BigInt(a)-BigInt(a)*BigInt(c)/10000n).toString();if(s!==l)throw new Error("jupiter: otherAmountThreshold does not match serialized min-out");return{mode:"solana-jupiter-quote",provider:"jupiter",venue:"jupiter-swap-v1",inputMint:r,outputMint:o,inAmount:i,outAmount:a,otherAmountThreshold:s,slippageBps:c,contextSlot:e.contextSlot??null,quotedAtMs:t,expiresAtMs:t+Math.min(Math.max(Number(n)||Nw,1e3),3e4)}}function Wp({userPublicKey:e,guard:t,swapTransaction:n,args:r={},response:o={}}){if(t.inputMint!==Vp)throw new Error("jupiter: local signer supports native SOL input only");if(BigInt(o?.prioritizationFeeLamports??0)!==0n)throw new Error("jupiter: local signer requires zero priority fee until exact fee accounting is supplied");let i=Bw(n),a=Ai(r.exactFeeLamports??o.exactFeeLamports??"5000","exactFeeLamports");return{version:1,surface:"sol",action:"swap",owner:e,destination:t.outputMint,tradeId:r.tradeId||`jupiter-${t.inputMint.slice(0,6)}-${t.outputMint.slice(0,6)}-${t.inAmount}`,slippageBps:t.slippageBps,expiresAtMs:t.expiresAtMs,fee:{oracleFeeBps:5},artifact:{cluster:r.cluster||"mainnet",provider:"jupiter",inputMint:t.inputMint,outputMint:t.outputMint,inAmount:t.inAmount,outAmount:t.outAmount,otherAmountThreshold:t.otherAmountThreshold,slippageBps:t.slippageBps,jupiterProgram:r.jupiterProgram||o.jupiterProgram||"JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4",messageBase64:i,exactFeeLamports:a}}}var nL=new Set(["BPFLoaderUpgradeab1e11111111111111111111111","BPFLoader2111111111111111111111111111111111","BPFLoader1111111111111111111111111111111111"]),rL="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function Ow(e){if(typeof e!="string"||!e.length)return!1;let t=0n;for(let o of e){let i=rL.indexOf(o);if(i<0)return!1;t=t*58n+BigInt(i)}let n=t.toString(16);n.length%2&&(n="0"+n);let r=n.length/2;for(let o of e)if(o==="1")r++;else break;return r===32}async function Mw(e={},t={}){let n=e.rpc||t.solanaRpc||process.env.SOLANA_RPC||"https://api.mainnet-beta.solana.com",r=t.fetchImpl||fetch,o=await r(`${cc}/program-id-to-label`,{signal:AbortSignal.timeout(Number(t.timeoutMs)||15e3)});if(!o.ok)throw new Error(`jupiter venue map failed: HTTP ${o.status}`);let i=await o.json(),a=Object.entries(i),s=a.filter(([p])=>Ow(p)),c=[],l=a.filter(([p])=>!Ow(p)).map(([p,m])=>({programId:p,label:m,reason:"malformed program id"}));if(e.verify===!1)return{source:`${cc}/program-id-to-label`,verified:s.map(([p,m])=>({programId:p,label:m})),unresolved:l,verifiedOnChain:!1,totals:{fromRouterMap:a.length,verified:s.length}};let u=async p=>{let f=await(await r(n,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(p),signal:AbortSignal.timeout(Number(t.timeoutMs)||2e4)})).json();if(f.error)throw new Error(f.error.message);return f.result};for(let p=0;p<s.length;p+=90){let m=s.slice(p,p+90),f=null;for(let h=0;h<3&&!f;h++)try{f=await u({jsonrpc:"2.0",id:1,method:"getMultipleAccounts",params:[m.map(([g])=>g),{encoding:"base64",dataSlice:{offset:0,length:0}}]})}catch{await new Promise(g=>setTimeout(g,2e3*(h+1)))}if(!f){for(let[h,g]of m)l.push({programId:h,label:g,reason:"rpc batch failed after 3 attempts"});continue}f.value.forEach((h,g)=>{let[w,x]=m[g];h&&h.executable===!0&&nL.has(h.owner)?c.push({programId:w,label:x,owner:h.owner}):l.push({programId:w,label:x,reason:h?h.executable!==!0?"not executable":`unknown owner ${h.owner}`:"account not found"})}),p+90<s.length&&await new Promise(h=>setTimeout(h,700))}let d=new Set(c.map(p=>p.label.replace(/\s+(CLMM|CP|V\d+|Launchlab|DLMM|Pools?)$/i,"").trim()));return{source:`${cc}/program-id-to-label`,verifiedOnChain:!0,verifiedAt:new Date().toISOString(),totals:{fromRouterMap:a.length,verified:c.length,unresolved:l.length,distinctLabels:new Set(c.map(p=>p.label)).size,distinctBrands:d.size},verified:c.sort((p,m)=>p.label.localeCompare(m.label)),unresolved:l}}async function Uw(e={}){try{return{ok:!0,provider:"jupiter",outAmount:(await lc({inputMint:Vp,outputMint:Rw,amount:"1000000",slippageBps:50},e)).quote.outAmount,exec:!1}}catch(t){return{ok:!1,provider:"jupiter",error:String(t?.message||t),exec:!1}}}async function lc(e={},t={}){let n=he(e.inputMint||e.fromMint||Vp,"inputMint"),r=he(e.outputMint||e.toMint||Rw,"outputMint"),o=Ai(e.amount||e.inAmount,"amount"),i=$w(e.slippageBps??e.maxSlippageBps??50),a=new URL(`${Lw(t)}/quote`);a.searchParams.set("inputMint",n),a.searchParams.set("outputMint",r),a.searchParams.set("amount",o),a.searchParams.set("slippageBps",String(i)),a.searchParams.set("swapMode",e.swapMode||"ExactIn"),e.onlyDirectRoutes!=null&&a.searchParams.set("onlyDirectRoutes",String(!!e.onlyDirectRoutes)),e.platformFeeBps!=null&&a.searchParams.set("platformFeeBps",String(e.platformFeeBps));let s=await S(a.toString(),{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),c=_i({...s,slippageBps:i},t);return{provider:"jupiter",chain:"solana-mainnet-beta",quoteReady:!0,executionReady:!1,inputMint:n,outputMint:r,amount:o,quote:s,solanaGuard:c}}function oL(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}async function Fw(e={},t={}){let n=he(e.userPublicKey||e.owner||e.wallet,"userPublicKey"),r=e.quoteResponse?{quote:e.quoteResponse,solanaGuard:_i(e.quoteResponse,t)}:await lc(e,t),o=r.quote,i=r.solanaGuard||_i(o,t);if(sc(e.dynamicSlippage,!1)===!0)throw new Error("jupiter: dynamicSlippage would override the enforced slippage ceiling \u2014 pass an explicit slippageBps instead");let a=await S(`${Lw(t)}/swap`,{method:"POST",body:oL({quoteResponse:o,userPublicKey:n,wrapAndUnwrapSol:sc(e.wrapAndUnwrapSol,!0),dynamicComputeUnitLimit:sc(e.dynamicComputeUnitLimit,!0),dynamicSlippage:!1,asLegacyTransaction:sc(e.asLegacyTransaction,!0),prioritizationFeeLamports:e.prioritizationFeeLamports??0}),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),s=eL(a?.swapTransaction);Bw(s),Yt("jupiter",a);let c=a?.quoteResponse??a?.quote??null,l=["inAmount","outAmount","otherAmountThreshold","inputMint","outputMint"],u=!1;if(c&&typeof c=="object"){for(let m of l){let f=o?.[m],h=c?.[m];if(f==null||h==null)throw new Error(`jupiter: echoed quote is incomplete \u2014 missing ${m}`);if(String(f)!==String(h))throw new Error(`jupiter: swap response ${m} (${h}) does not match the quoted ${m} (${f}) \u2014 refusing to prepare`)}u=!0}let d=null,p=null;try{d=Wp({userPublicKey:n,guard:i,swapTransaction:s,args:e,response:a})}catch(m){p=String(m?.message||m).slice(0,200)}return N({provider:"jupiter",chain:"solana-mainnet-beta",prepareReady:!0,executionReady:!1,signingReady:!1,broadcastReady:!1,requiresUserSignature:!0,verifiedAgainstQuote:u,userPublicKey:n,quote:o,solanaGuard:i,swapTransaction:s,localSignerEnvelope:d,localSignerBlockedReason:p,swapTransactionEncoding:"base64",lastValidBlockHeight:a?.lastValidBlockHeight??null,prioritizationFeeLamports:a?.prioritizationFeeLamports??null,computeUnitLimit:a?.computeUnitLimit??null,raw:a},{provider:"jupiter",kind:"jupiter-swap"})}Kn();Yo();cn();_r();Cr();import{getAddress as aL}from"ethers";var Kp=Object.freeze(["uniswap-v2","uniswap-v3","uniswap-v4","aerodrome","curve","balancer","meteora-dlmm","pancakeswap","sushiswap"]),qw="0x0000000000000000000000000000000000000000",Hw=/^0x[0-9a-fA-F]{40}$/,sL=25,uc=Object.freeze([["removalGasUsd","estimateRemovalGasUsd"],["swapCostUsd","estimateSwapCostUsd"],["bridgeCostUsd","estimateBridgeCostUsd"],["addLiquidityGasUsd","estimateAddLiquidityGasUsd"],["priceImpactUsd","estimatePriceImpactUsd"]]);function Pi(e,t){let n=String(e??"").trim();if(!n)throw new Error(`${t} is required`);if(Hw.test(n))try{return aL(n)}catch{throw new Error(`${t} is not a valid EVM address`)}return n}function dc(e,t){let n=e?.[t];if(typeof n!="function")throw new Error(`lp-liquidity-ranker: opts.${t} must be a function`);return n}function cL(e){if(!e||typeof e!="object")throw new Error("candidate must be an object");let t=Number(e.chainId);if(!Number.isInteger(t)||t<=0)throw new Error("chainId must be a positive integer");let n=String(e.venue??"").trim().toLowerCase();if(!n)throw new Error("venue is required");let r=Pi(e.poolAddress,"poolAddress"),o=e.token;if(!o||typeof o!="object")throw new Error("token is required");let i=String(o.symbol??"").trim();if(!i)throw new Error("token.symbol is required");let a=Pi(o.address,"token.address"),s=null;if(o.decimals!=null&&(s=Number(o.decimals),!Number.isInteger(s)||s<0||s>255))throw new Error("token.decimals must be a uint8 when provided");let c=Number(e.liquidityUsd);if(!Number.isFinite(c)||c<0)throw new Error("liquidityUsd must be a non-negative finite number");let l=n==="uniswap-v4"||e.isV4===!0,u=null;if(e.hook!=null){if(typeof e.hook!="object")throw new Error("hook must be an object when provided");u=Object.freeze({address:e.hook.address!=null?Pi(e.hook.address,"hook.address"):qw,dynamicFee:e.hook.dynamicFee===!0,reviewed:e.hook.reviewed===!0})}let d=e.id!=null?String(e.id):`${n}:${t}:${r}`;return Object.freeze({id:d,chainId:t,venue:n,poolAddress:r,token:Object.freeze({symbol:i,address:a,decimals:s}),liquidityUsd:c,isV4:l,hook:u})}function lL(e){if(!Kp.includes(e.venue))return`unsupported venue "${e.venue}"; supported: ${Kp.join(", ")}`;if(e.isV4){if(!e.hook)return"uniswap-v4 candidate is missing hook disclosure; failing closed";if(e.hook.dynamicFee)return"uniswap-v4 pool uses a dynamic fee; fee is not knowable in advance, failing closed";if(e.hook.address!==qw&&!e.hook.reviewed)return`uniswap-v4 pool has an unreviewed hook (${e.hook.address}); failing closed`}return null}async function uL(e,t,n){let r=dc(n,"resolveTokenIdentity"),o;try{o=await r({chainId:e.chainId,address:e.token.address,symbol:e.token.symbol})}catch(l){return{ok:!1,reason:`identity resolution failed: ${l?.message??l}`}}if(!o||typeof o!="object")return{ok:!1,reason:"identity unresolved"};if(o.ambiguous)return{ok:!1,reason:o.reason??"ambiguous token identity"};if(!o.canonicalId)return{ok:!1,reason:"identity resolver returned no canonicalId"};if(o.canonicalId!==t.canonicalId)return{ok:!1,reason:`token resolves to canonical id "${o.canonicalId}", expected "${t.canonicalId}"`};let i=Number(o.homeChainId);if(!Number.isInteger(i)||i<=0)return{ok:!1,reason:"identity resolver returned no homeChainId"};let a;try{a=Pi(o.canonicalAddress,"identity resolver canonicalAddress")}catch(l){return{ok:!1,reason:l.message}}let s=e.token.address;return(Hw.test(a)?a===s:a.toLowerCase()===String(s).toLowerCase())?{ok:!0,canonicalId:o.canonicalId,homeChainId:i,canonicalAddress:a,decimals:o.decimals??e.token.decimals??null}:{ok:!1,reason:`token address ${e.token.address} on chain ${e.chainId} does not match the canonical address ${a}; possible wrapped variant or spoof`}}async function dL(e,t,n){let r={},o=[];for(let[s,c]of uc){let l=dc(n,c),u;try{u=await l(e,t)}catch(p){return{ok:!1,reason:`${c} failed for ${e.id}: ${p?.message??p}`}}if(u==null||!Number.isFinite(Number(u))){r[s]=null,o.push(s);continue}let d=Number(u);if(d<0)return{ok:!1,reason:`${c} returned a negative cost for ${e.id}`};r[s]=d}let i=uc.reduce((s,[c])=>s+(r[c]??0),0),a=o.length===0;return{ok:!0,costs:Object.freeze(r),missingLegs:Object.freeze(o),grossOnly:!a,measuredCostUsd:i,totalCostUsd:a?i:null,netUsd:a?t.amountUsd-i:null}}function Gp(e){return Object.freeze({id:e.id,chainId:e.chainId,venue:e.venue,poolAddress:e.poolAddress,token:e.token,liquidityUsd:e.liquidityUsd,canonicalId:e.identity.canonicalId,homeChainId:e.identity.homeChainId})}function Dw(e,t){let n=null;for(let r of e){if(!n){n=r;continue}let o=t(r),i=t(n);(o>i||o===i&&r.id<n.id)&&(n=r)}return n}async function pL(e={},t={}){let n=String(e.canonicalId??"").trim();if(!n)throw new Error("lp-liquidity-ranker: canonicalId is required");let r=Number(e.amountUsd);if(!Number.isFinite(r)||r<=0)throw new Error("lp-liquidity-ranker: amountUsd must be a positive finite number");if(!Array.isArray(e.candidates)||e.candidates.length===0)throw new Error("lp-liquidity-ranker: candidates must be a non-empty array");let o=e.materialityThresholdBps??sL;if(!Number.isInteger(o)||o<0)throw new Error("lp-liquidity-ranker: materialityThresholdBps must be a non-negative integer");dc(t,"resolveTokenIdentity");for(let[,h]of uc)dc(t,h);let i=Object.freeze({canonicalId:n,amountUsd:r,materialityThresholdBps:o}),a=[],s=[],c=new Set,l=null;for(let h=0;h<e.candidates.length;h+=1){let g=e.candidates[h],w=g?.id!=null?String(g.id):`candidates[${h}]`,x;try{x=cL(g)}catch(E){a.push({id:w,reason:E.message});continue}if(c.has(x.id)){a.push({id:x.id,reason:"duplicate candidate id"});continue}c.add(x.id);let b=lL(x);if(b){a.push({id:x.id,reason:b});continue}let y=await uL(x,i,t);if(!y.ok){a.push({id:x.id,reason:y.reason});continue}if(l==null)l=y.homeChainId;else if(y.homeChainId!==l){a.push({id:x.id,reason:`ambiguous home chain for canonical token "${n}": got ${y.homeChainId}, expected ${l}`});continue}let k=await dL(x,i,t);if(!k.ok){a.push({id:x.id,reason:k.reason});continue}s.push({...x,identity:y,...k})}let u=[];if(s.length===0)return Object.freeze({ok:!0,canonicalId:n,homeChainId:l,amountUsd:r,evaluated:e.candidates.length,accepted:0,rejected:Object.freeze(a),deepestLiquidity:null,netBest:null,netRankingComplete:!1,preparationEligible:!1,runnersUp:Object.freeze([]),warnings:Object.freeze(["no candidate passed identity, venue, or cost validation"])});let d=Dw(s,h=>h.liquidityUsd),p=s.filter(h=>!h.grossOnly&&h.netUsd!=null),m=Dw(p,h=>h.netUsd);for(let h of s)h.grossOnly&&u.push(`${h.id}: gas/fees not fully accounted (missing: ${h.missingLegs.join(", ")}); missing costs were not treated as zero`);m?d.id!==m.id&&u.push(`${d.id} has the deepest liquidity ($${d.liquidityUsd}) but ${m.id} nets more after costs; these are intentionally different answers`):u.push("net-best migration is unavailable until every ranking cost leg is measured; missing gas is never treated as zero and deepest liquidity is not claimed as net-best"),p.length<s.length&&u.push("partial-cost candidates were excluded from net ranking; missing gas was not treated as zero");let f=s.filter(h=>h.id!==m?.id).sort((h,g)=>h.netUsd==null&&g.netUsd==null?h.id<g.id?-1:1:h.netUsd==null?1:g.netUsd==null?-1:g.netUsd-h.netUsd||(h.id<g.id?-1:1)).map(h=>{let g=m!=null&&h.netUsd!=null,w=g?m.netUsd-h.netUsd:null,x=g?Math.round(w/r*1e4):null;return Object.freeze({...Gp(h),netUsd:h.netUsd,totalCostUsd:h.totalCostUsd,grossOnly:h.grossOnly,missingLegs:h.missingLegs,marginUsd:w,marginBps:x,material:x!=null&&x>o})});return Object.freeze({ok:!0,canonicalId:n,homeChainId:l,amountUsd:r,evaluated:e.candidates.length,accepted:s.length,rejected:Object.freeze(a),deepestLiquidity:Gp(d),netBest:m?Object.freeze({...Gp(m),netUsd:m.netUsd,totalCostUsd:m.totalCostUsd,costs:m.costs,grossOnly:!1,missingLegs:m.missingLegs}):null,netRankingComplete:!!m&&p.length===s.length,preparationEligible:!1,runnersUp:Object.freeze(f),warnings:Object.freeze(u)})}async function jw(e={}){let t=String(e.canonicalId??"").trim(),n=Number(e.homeChainId);if(!t)throw new Error("lp-liquidity-ranker: canonicalId is required");if(!Number.isInteger(n)||n<=0)throw new Error("lp-liquidity-ranker: homeChainId must be a positive integer");if(!Array.isArray(e.canonicalAssets)||e.canonicalAssets.length===0)throw new Error("lp-liquidity-ranker: canonicalAssets must be a non-empty array");let r=new Map;for(let c of e.canonicalAssets){let l=Number(c?.chainId);if(!Number.isInteger(l)||l<=0)throw new Error("lp-liquidity-ranker: canonical asset chainId must be positive");if(r.has(l))throw new Error(`lp-liquidity-ranker: duplicate canonical asset for chain ${l}`);let u=Pi(c?.address,"canonical asset address"),d=c?.decimals==null?null:Number(c.decimals);if(d!=null&&(!Number.isInteger(d)||d<0||d>255))throw new Error("lp-liquidity-ranker: canonical asset decimals must be a uint8");r.set(l,Object.freeze({canonicalAddress:u,decimals:d}))}let o={resolveTokenIdentity:async({chainId:c})=>{let l=r.get(Number(c));return l?{canonicalId:t,homeChainId:n,...l}:{ambiguous:!0,reason:`no exact canonical asset mapping for chain ${c}`}}},i=(e.candidates??[]).map(c=>({...c,costs:c?.costs&&typeof c.costs=="object"?{...c.costs}:{}})),a=new Map(i.map(c=>[String(c?.id??`${String(c?.venue??"").toLowerCase()}:${Number(c?.chainId)}:${String(c?.poolAddress??"")}`),c.costs]));for(let[c,l]of uc)o[l]=async u=>a.get(u.id)?.[c]??null;let s=await pL({...e,canonicalId:t,candidates:i},o);return Object.freeze({...s,evidenceMode:"caller-supplied",warnings:Object.freeze(["canonical mappings, pool liquidity, and migration costs were caller-supplied and not independently live-verified",...s.warnings])})}async function zw(){return Object.freeze({ok:!0,execution:"analysis-only",supportedVenues:Kp,note:"Deepest liquidity and net-best migration are reported separately; no signing or broadcasting."})}cn();var fL=Object.freeze([/(?:^|\s)Bearer\s+\S+/i,/-----BEGIN [A-Z ]*PRIVATE KEY-----/i,/\b(?:sk-|xprv|gh[pousr]_|github_pat_|AKIA|ASIA)[A-Za-z0-9_/-]{12,}\b/i,/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/,/\b(?:0x)?[0-9a-f]{64}\b/i,/(?<![1-9A-HJ-NP-Za-km-z])[59KLc][1-9A-HJ-NP-Za-km-z]{50,51}(?![1-9A-HJ-NP-Za-km-z])/,/(?<![1-9A-HJ-NP-Za-km-z])[1-9A-HJ-NP-Za-km-z]{64,88}(?![1-9A-HJ-NP-Za-km-z])/]),hL=new Set(["apikey","key","token","accesstoken","secret","password","passwd","auth","authorization","bearer","signertoken","credential","credentials","clientsecret","privatekey","xapikey","accesskey","refreshtoken"]),gL=Object.freeze(["apikey","accesskey","privatekey","clientsecret","accesstoken","refreshtoken","signertoken","credential","password","passwd","authorization","bearer","secret","token"]);function yL(e){return String(e??"").replace(/[^a-z0-9]/gi,"").toLowerCase()}function bL(e){let t;try{t=new URL(e)}catch{return!1}if(t.username||t.password)return!0;for(let n of t.searchParams.keys()){let r=yL(n);if(hL.has(r)||gL.some(o=>r.includes(o)))return!0}return!1}function Vw(e){try{let t=decodeURIComponent(e);return t===e?null:t}catch{return null}}var wL=/[a-z][a-z0-9+.-]{1,15}(?::\/\/|%3a%2f%2f)\S+/gi;function vL(e){return e.replace(/[),.;:!?'"\]}]+$/,"")}function xL(e){let t=e.match(wL)||[];for(let n of t){let r=vL(n),o=Vw(r),i=o?Vw(o):null;for(let a of[r,o,i])if(a&&bL(a))return!0}return!1}function Ww(e){return typeof e!="string"||e.length===0?!1:fL.some(t=>t.test(e))?!0:xL(e)}var Gw=/^0x[0-9a-fA-F]{40}$/,kL=new Set(["source","reviewedAt","evidenceHash","txHash"]),SL=1e4,Jt=e=>String(e??"").trim().toLowerCase();function IL(e,t){if(!e||typeof e!="object"||!String(e.source??"").trim())throw new Error(`lp-destination-discovery: ${t}.provenance.source is required`);if(Object.keys(e).filter(s=>!kL.has(s)).length)throw new Error(`lp-destination-discovery: ${t}.provenance contains unsupported fields`);let r=String(e.source).trim();if(r.length>512||Ww(r))throw new Error(`lp-destination-discovery: ${t}.provenance.source is unsafe`);let o=e.evidenceHash==null?null:String(e.evidenceHash).trim();if(o!=null&&!/^[0-9a-f]{64}$/i.test(o))throw new Error(`lp-destination-discovery: ${t}.provenance.evidenceHash must be a sha256 digest`);let i=e.txHash==null?null:String(e.txHash).trim();if(i!=null&&!/^0x[0-9a-f]{64}$/i.test(i))throw new Error(`lp-destination-discovery: ${t}.provenance.txHash must be an EVM transaction hash`);let a=e.reviewedAt==null?null:String(e.reviewedAt).trim();if(a!=null&&!Number.isFinite(Date.parse(a)))throw new Error(`lp-destination-discovery: ${t}.provenance.reviewedAt must be ISO time`);return Object.freeze({source:r,reviewedAt:a,evidenceHash:o,txHash:i})}function Kw(e,t){if(!e||typeof e!="object")throw new Error(`lp-destination-discovery: ${t} is required`);let n=Number(e.chainId),r=String(e.token0??"").trim(),o=String(e.token1??"").trim();if(!Number.isInteger(n)||n<=0)throw new Error(`lp-destination-discovery: ${t}.chainId must be positive`);if(!Gw.test(r)||!Gw.test(o)||Jt(r)===Jt(o))throw new Error(`lp-destination-discovery: ${t} requires distinct exact token0/token1 addresses`);return Object.freeze({...e,chainId:n,token0:r,token1:o,provenance:IL(e.provenance,t)})}function EL(e,t){if(!String(e.dexId??"").toLowerCase().includes("v4"))return{eligible:!0,reason:null};let n=t.v4;if(!n)return{eligible:!1,reason:"Uniswap V4 metadata is unreviewed"};if(n.dynamicFee===!0)return{eligible:!1,reason:"Uniswap V4 dynamic fee is not preparation-eligible"};let r=Jt(n.hook);return r&&r!=="0x0000000000000000000000000000000000000000"&&n.reviewed!==!0?{eligible:!1,reason:"Uniswap V4 hook is unreviewed"}:{eligible:!0,reason:null}}function AL(e){let t=e?.best;if(!t||t.quality!=="FULL")return null;let n=Number(t.gasUsd),r=Number(t.feeUsd);return t.gasUsd==null||t.feeUsd==null||!Number.isFinite(n)||!Number.isFinite(r)?null:n+r}async function Yw({source:e,destination:t,amountIn:n,index:r},o,i){if(n==null)return{requested:!1,measured:!1,costUsd:null,quote:null};let a=e[`token${r}`],s=t[`token${r}`];if(e.chainId===t.chainId&&Jt(a)===Jt(s))return{requested:!0,measured:!0,costUsd:0,quote:null,kind:"none",amountIn:String(n)};let c=e.chainId===t.chainId?{chainId:e.chainId,tokenIn:a,tokenOut:s,amountIn:String(n)}:{fromChainId:e.chainId,toChainId:t.chainId,tokenIn:a,tokenOut:s,amountIn:String(n)},l=e.chainId===t.chainId?"swap":"bridge";try{let u=l==="swap"?await o.bestSwapRoute(c,i):await o.bestBridgeRoute(c,i),d=AL(u);return{requested:!0,measured:d!=null,costUsd:d,quote:u,kind:l,amountIn:String(n)}}catch(u){return{requested:!0,measured:!1,costUsd:null,quote:null,kind:l,amountIn:String(n),error:u?.message??String(u)}}}function _L(e){let t=e.minLiquidityBpsOfDeepest??SL;if(!Number.isInteger(t)||t<1||t>1e4)throw new Error("lp-destination-discovery: minLiquidityBpsOfDeepest must be an integer from 1 to 10000");if(e.minLiquidityUsd==null)return{bps:t,minLiquidityUsd:null};let n=Number(e.minLiquidityUsd);if(!Number.isFinite(n)||n<0)throw new Error("lp-destination-discovery: minLiquidityUsd must be a non-negative number");return{bps:t,minLiquidityUsd:n}}function PL(e,t,n){if(e.venueReviewEligible===!1)return{destinationEligible:!1,destinationIneligibleReason:e.ineligibleReason};if(e.liquidityUsd==null)return{destinationEligible:!1,destinationIneligibleReason:"reported USD liquidity is unknown"};let r=Number(e.liquidityUsd);if(!Number.isFinite(r)||r<=0)return{destinationEligible:!1,destinationIneligibleReason:"reported USD liquidity is not positive"};if(n.minLiquidityUsd!=null&&r<n.minLiquidityUsd)return{destinationEligible:!1,destinationIneligibleReason:`liquidity $${r} is below the $${n.minLiquidityUsd} floor`};if(!t||t.liquidityUsd==null)return{destinationEligible:!1,destinationIneligibleReason:"no eligible deepest pool"};let o=Number(t.liquidityUsd)*n.bps/1e4;return r<o?{destinationEligible:!1,destinationIneligibleReason:`shallower than the deepest eligible pool ($${r} < $${o} required)`}:{destinationEligible:!0,destinationIneligibleReason:null}}function Jw(e,t,n="max"){return[...e].sort((r,o)=>(n==="max"?t(o)-t(r):t(r)-t(o))||String(r.poolAddress).localeCompare(String(o.poolAddress)))[0]??null}async function Xw(e={},t={}){let n=Kw(e.sourcePair,"sourcePair");if(!Array.isArray(e.destinationPairs))throw new Error("lp-destination-discovery: destinationPairs must be an array");let r=e.destinationPairs.map((v,A)=>Kw(v,`destinationPairs[${A}]`)),o=new Map;for(let v of r){if(o.has(v.chainId))throw new Error(`lp-destination-discovery: duplicate destination mapping for chain ${v.chainId}`);o.set(v.chainId,v)}let i=_L(e),a=t.chainConfigs??(await Promise.resolve().then(()=>(Mr(),Wd))).CHAIN_CONFIGS,s=e.amounts?.token0!=null||e.amounts?.token1!=null,c=s&&r.some(v=>v.chainId===n.chainId&&(Jt(v.token0)!==Jt(n.token0)||Jt(v.token1)!==Jt(n.token1))),l=s&&r.some(v=>v.chainId!==n.chainId),u=c&&!t.bestSwapRoute||l&&!t.bestBridgeRoute?await Promise.resolve().then(()=>(Cd(),sy)):null,d={discoverExactPairPools:t.discoverExactPairPools??W0,bestSwapRoute:t.bestSwapRoute??u?.bestSwapRoute,bestBridgeRoute:t.bestBridgeRoute??u?.bestBridgeRoute},p=e.limit??10,m=await Promise.all(a.map(async v=>{let A=o.get(Number(v.chainId));if(!v.dexscreenerSlug)return{chainId:v.chainId,chain:v.name??v.key??null,status:"unavailable",reason:"DexScreener coverage slug is not configured",pools:[]};if(!A)return{chainId:v.chainId,chain:v.name??v.key??null,chainSlug:v.dexscreenerSlug,status:"unavailable",reason:"no explicit provenanced destination token0/token1 mapping",pools:[]};try{let P=await d.discoverExactPairPools({chainSlug:v.dexscreenerSlug,token0:A.token0,token1:A.token1,limit:p,dexIds:A.dexIds},t);return{chainId:v.chainId,chain:v.name??v.key??null,chainSlug:v.dexscreenerSlug,status:"available",mapping:A,pools:P}}catch(P){return{chainId:v.chainId,chain:v.name??v.key??null,chainSlug:v.dexscreenerSlug,status:"unavailable",reason:P?.message??String(P),mapping:A,pools:[]}}})),f=m.flatMap(v=>v.pools.map(A=>({...A,chainId:Number(v.chainId),mapping:v.mapping}))),h=e.amounts??{},g=await Promise.all(f.map(async v=>{let[A,P]=await Promise.all([Yw({source:n,destination:v.mapping,amountIn:h.token0,index:0},d,t),Yw({source:n,destination:v.mapping,amountIn:h.token1,index:1},d,t)]),L=!(A.requested||P.requested)||[A,P].filter(O=>O.requested).every(O=>O.measured),F=L?[A,P].reduce((O,H)=>O+(H.costUsd??0),0):null,q=EL(v,v.mapping);return Object.freeze({...v,mappingProvenance:v.mapping.provenance,legs:Object.freeze([A,P]),fullyMeasured:L,costUsd:F,preparationEligible:!1,venueReviewEligible:q.eligible,ineligibleReason:q.reason})})),w=Jw(g.filter(v=>v.liquidityUsd!=null),v=>Number(v.liquidityUsd)),x=g.map(v=>Object.freeze({...v,...PL(v,w,i)})),b=x.find(v=>v.destinationEligible&&w&&v.poolAddress===w.poolAddress&&v.chainId===w.chainId)??null,y=x.filter(v=>v.fullyMeasured&&v.destinationEligible),k=Jw(y,v=>v.costUsd,"min"),E=x.filter(v=>v.destinationEligible===!1&&v.destinationIneligibleReason?.includes("shallower")),I=w&&x.some(v=>v.poolAddress===w.poolAddress&&v.chainId===w.chainId&&v.destinationEligible===!1);return Object.freeze({ok:!0,analysisOnly:!0,sourcePair:n,coverage:Object.freeze(m),routes:Object.freeze(x),deepestLiquidity:w,recommendedDestination:b,migrationCostBest:k,netBest:null,rankedOn:"liquidity",netRankingComplete:!1,preparationEligible:!1,liquidityFloor:Object.freeze(i),warnings:Object.freeze([...y.length<x.filter(v=>v.fullyMeasured).length?["partial-cost or thin-book routes were excluded from migration-cost comparison; missing gas was not treated as zero and thinner pools are not destinations"]:[],...E.length?[`${E.length} shallower pool(s) are not destination-eligible; a thinner V3 book is never recommended over a deeper V4 book`]:[],...I?["deepest book is not destination-eligible (unreviewed/dynamic-fee V4 or liquidity floor); thinner pools are still not recommended"]:[],"net-best migration is unavailable until destination token values and final add-liquidity gas/impact are measured; deepest liquidity is not claimed as net-best"])})}async function Qw(){let{CHAIN_CONFIGS:e}=await Promise.resolve().then(()=>(Mr(),Wd));return{ok:!0,execution:"analysis-only",configuredChains:e.length}}pe();Fe();Y();import{Interface as tv,getAddress as Ci,isAddress as TL}from"ethers";var En={8453:{name:"base",quoter:"0x254cF9E1E6e233aa1AC962CB9B05b2cfeAaE15b0",router:"0xBE6D8f0d05cC4be24d5167a3eF062215bE6D18a5",factory:"0x5e7BB104d84c7CB9B682AaC2F3d509f5F406809A",weth:"0x4200000000000000000000000000000000000006",usdc:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"}},NL=[1,50,100,200,2e3],Zw=new tv(["function quoteExactInputSingle((address tokenIn, address tokenOut, uint256 amountIn, int24 tickSpacing, uint160 sqrtPriceLimitX96) params) returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)"]),OL=new tv(["function exactInputSingle((address tokenIn, address tokenOut, int24 tickSpacing, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)"]),nv="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",rv="0x0000000000000000000000000000000000000000";function ov(e){let t=Number(e),n=En[t];if(!n)throw new Error(`aerodrome: unsupported chainId ${e} (supported: ${Object.keys(En).join(", ")})`);return{chainId:t,...n}}function ev(e,t){let n=En[Number(t)];if(!e||e===nv||e===rv||/^eth$/i.test(String(e)))return Ci(n.weth);let r=String(e);if(/^weth$/i.test(r))return Ci(n.weth);if(/^usdc$/i.test(r))return Ci(n.usdc);if(!TL(r))throw new Error(`invalid token address: ${e}`);return Ci(r)}async function pc(e={},t={}){let{chainId:n,quoter:r,router:o}=ov(e.chainId??8453),i=ev(e.tokenIn||"WETH",n),a=ev(e.tokenOut||En[n].usdc,n),s=BigInt(e.amountIn??0);if(s<=0n)throw new Error("amountIn required (raw base units)");let c=e.tickSpacing!=null?[Number(e.tickSpacing)]:e.tryTickSpacings===!1?[100]:[...NL],u=await Promise.all(c.map(async p=>{let m=Zw.encodeFunctionData("quoteExactInputSingle",[{tokenIn:i,tokenOut:a,amountIn:s,tickSpacing:p,sqrtPriceLimitX96:0n}]);try{let f=await D(n,"eth_call",[{to:r,data:m},"latest"],t);if(!f||f==="0x")return{tickSpacing:p,ok:!1,error:"empty result"};let h=Zw.decodeFunctionResult("quoteExactInputSingle",f);return{tickSpacing:p,ok:!0,amountOut:h[0].toString(),sqrtPriceX96After:h[1].toString(),initializedTicksCrossed:Number(h[2]),gasEstimate:h[3].toString()}}catch(f){return{tickSpacing:p,ok:!1,error:String(f.message||f).slice(0,160)}}})),d=null;for(let p of u)p.ok&&(!d||BigInt(p.amountOut)>BigInt(d.amountOut))&&(d=p);if(!d){let p=u.map(m=>`${m.tickSpacing}:${m.error||"fail"}`).join("; ");throw new Error(`aerodrome quote failed chain=${n}: ${p}`)}return oe({venue:"aerodrome",chainId:n,chain:En[n].name,quoter:r,router:o,tokenIn:i,tokenOut:a,amountIn:s.toString(),tickSpacing:d.tickSpacing,amountOut:d.amountOut,gasEstimate:d.gasEstimate,sqrtPriceX96After:d.sqrtPriceX96After,initializedTicksCrossed:d.initializedTicksCrossed,triedTickSpacings:u,best:!0},{chainId:n,venue:o,amountOut:d.amountOut,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function iv(e={},t={}){let n=Number(e.chainId??8453),r=ov(n),o=Ci(e.recipient||e.from||e.userAddress),i=String(e.tokenIn||"WETH"),a=!e.tokenIn||i===nv||i===rv||/^eth$/i.test(i),s=await pc(e,t),c=Math.min(600,Math.max(30,Number(e.deadlineSeconds??300))),u=Number(t.nowSeconds??Math.floor(Date.now()/1e3))+c,d=OL.encodeFunctionData("exactInputSingle",[{tokenIn:s.tokenIn,tokenOut:s.tokenOut,tickSpacing:s.tickSpacing,recipient:o,deadline:u,amountIn:BigInt(s.amountIn),amountOutMinimum:BigInt(s.amountOutMinimum),sqrtPriceLimitX96:0n}]);return N({provider:"aerodrome",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:n,deadline:u,quote:s,autoSlippage:s.autoSlippage,requiresApproval:a?null:{token:s.tokenIn,spender:r.router,amount:s.amountIn},transaction:{chainId:n,from:o,to:r.router,data:d,value:a?s.amountIn:"0",slippageGuard:ye(s.autoSlippage,{chainId:n,venue:r.router,data:d})}},{provider:"aerodrome",kind:"aerodrome-exact-in"})}async function av(e={}){let t=Number(e.chainId??8453);try{let n=await pc({chainId:t,tokenIn:"WETH",tokenOut:"USDC",amountIn:"1000000000000000"},e),r=Number(n.amountOut)/1e6;return{ok:!0,chainId:t,tickSpacing:n.tickSpacing,amountOutUsdc:r,midPxHint:r/.001,router:En[t]?.router,quoter:En[t]?.quoter}}catch(n){return{ok:!1,chainId:t,error:String(n.message||n).slice(0,200)}}}async function sv(){return Object.entries(En).map(([e,t])=>({chainId:Number(e),name:t.name,quoter:t.quoter,router:t.router,factory:t.factory,weth:t.weth,usdc:t.usdc}))}Xo();Is();ti();md();Y();var LL=96*1024,cv=50;function $L(e){if(e&&typeof e=="object"&&!Array.isArray(e))return e;let t=String(e||"").trim();if(!t||t.length>LL)throw new Error("x402: invalid PAYMENT-REQUIRED payload");if(t.startsWith("{"))try{return JSON.parse(t)}catch{throw new Error("x402: invalid PAYMENT-REQUIRED JSON")}if(!/^[A-Za-z0-9+/_-]+={0,2}$/.test(t)||t.length%4===1)throw new Error("x402: invalid PAYMENT-REQUIRED Base64");let n=t.replace(/-/g,"+").replace(/_/g,"/"),r=n+"=".repeat((4-n.length%4)%4);try{let o=Buffer.from(r,"base64").toString("utf8");if(!o.trim().startsWith("{"))throw new Error("shape");return JSON.parse(o)}catch{throw new Error("x402: invalid PAYMENT-REQUIRED Base64 JSON")}}function Xt(e,t){let n=String(e||"").trim();if(!n)throw new Error(`x402: ${t} required`);return n}function uv(e,t){let n=Xt(e,t);if(!/^\d+$/.test(n))throw new Error(`x402: ${t} must be atomic units`);let r=BigInt(n);if(r<=0n)throw new Error(`x402: ${t} must be positive`);return r.toString()}function BL(e){if(!e||typeof e!="object"||Array.isArray(e))return Object.freeze({});let t={};for(let n of["name","version"])typeof e[n]=="string"&&e[n].trim()&&(t[n]=e[n].trim());return Object.freeze(t)}function ML(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`x402: accepts[${t}] must be an object`);let n=Xt(e.scheme,`accepts[${t}].scheme`).toLowerCase();return Object.freeze({scheme:n,network:Xt(e.network,`accepts[${t}].network`),amount:uv(e.amount,`accepts[${t}].amount`),asset:Xt(e.asset,`accepts[${t}].asset`),payTo:Xt(e.payTo,`accepts[${t}].payTo`),maxTimeoutSeconds:Number(e.maxTimeoutSeconds),extra:BL(e.extra)})}function Yp(e){let t=$L(e);if(t.x402Version!==2)throw new Error("x402: only x402Version 2 is supported");if(!Array.isArray(t.accepts)||t.accepts.length===0||t.accepts.length>cv)throw new Error(`x402: accepts must contain 1-${cv} requirements`);let n=t.resource&&typeof t.resource=="object"&&!Array.isArray(t.resource)?Object.freeze({url:Xt(t.resource.url,"resource.url"),description:String(t.resource.description||""),mimeType:String(t.resource.mimeType||"")}):null;if(!n)throw new Error("x402: resource required");let r=Object.freeze(t.accepts.map(ML));for(let o of r)if(!Number.isInteger(o.maxTimeoutSeconds)||o.maxTimeoutSeconds<=0)throw new Error("x402: maxTimeoutSeconds must be a positive integer");return Object.freeze({x402Version:2,resource:n,accepts:r})}function lv(e,t){return String(e)===String(t)}function UL(e,t={}){let n=Yp(e),r=Xt(t.network,"network"),o=Xt(t.asset,"asset"),i=Xt(t.payTo,"payTo"),a=BigInt(uv(t.maxAmount,"maxAmount")),s=n.accepts.filter(l=>l.scheme==="exact"&&l.network===r&&lv(l.asset,o)&&lv(l.payTo,i));if(s.length===0)throw new Error("x402: no exact requirement matches network, asset, and payTo");let c=s.sort((l,u)=>{let d=BigInt(l.amount),p=BigInt(u.amount);return d<p?-1:d>p?1:0})[0];if(BigInt(c.amount)>a)throw new Error(`x402: amount ${c.amount} exceeds maxAmount ${a}`);return c}function dv(e={}){return e.paymentRequired??e.header??e.body}function pv(e={}){return Yp(dv(e))}function mv(e={},t={}){let n=Yp(dv(e)),r=UL(n,e);return N({provider:"x402",x402Version:2,resource:n.resource,accepted:r,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,executionReady:!1,paymentReady:!1,requestTemplate:{x402Version:2,resource:n.resource,accepted:r,payload:null},nextStep:"A user-controlled wallet must create the scheme-specific payload. Oracle does not sign, call a facilitator, or retry the paid request."},{provider:"x402",kind:"x402-payment-template",nowMs:t.nowMs})}function fv(){return{ok:!0,configured:!0,x402Version:2,schemes:["exact"],custody:"prepare-only",signingReady:!1,broadcastReady:!1}}R();vt();var DL="https://api.bankr.bot";function Jp(e={}){return Ae({provider:"bankr",defaultUrl:DL,hosts:["api.bankr.bot"],url:e.baseUrl||process.env.BANKR_API_URL})}function hv(e={}){return e.apiKey||process.env.BANKR_API_KEY||""}function qL(e={}){let t=hv(e);if(!t)throw new Error("BANKR_API_KEY required for Bankr");return t}function gv(e={},t=!1){let n=qL(e),r=Jp(e);return Ie({accept:"application/json",...t?{"content-type":"application/json"}:{}},{"X-API-Key":n},r.trusted)}async function yv(e,t={}){return S(`${Jp(t).baseUrl}${e}`,{headers:gv(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3,retries:0})}async function Xp(e={}){return yv("/wallet/me",e)}async function bv(e={}){return yv("/wallet/portfolio",e)}function Ti(e,t){let n=String(e||"").trim();if(!n)throw new Error(`bankr: ${t} required`);return n}function HL(e){let t=Ti(e,"amount");if(!/^\d+(?:\.\d+)?$/.test(t)||Number(t)<=0)throw new Error("bankr: amount must be a positive decimal string");return t}async function wv(e={},t={}){let n={fromChain:Ti(e.fromChain,"fromChain"),fromToken:Ti(e.fromToken,"fromToken"),toChain:Ti(e.toChain,"toChain"),toToken:Ti(e.toToken,"toToken"),amount:HL(e.amount)};if(e.slippageBps!=null){let r=Number(e.slippageBps);if(!Number.isInteger(r)||r<10||r>2e3)throw new Error("bankr: slippageBps must be an integer from 10 through 2000");n.slippageBps=r}return S(`${Jp(t).baseUrl}/wallet/swap-quote`,{method:"POST",headers:gv(t,!0),body:JSON.stringify(n),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4,retries:0})}async function vv(e={}){if(!hv(e))return{ok:!1,configured:!1,error:"BANKR_API_KEY not set"};try{return{ok:!0,configured:!0,walletConfigured:!!await Xp(e),custody:"vendor-wallet-read-only",execution:!1}}catch(t){return{ok:!1,configured:!0,error:String(t?.message||t).slice(0,160)}}}var zL=process.env.HL_WS_URL||"wss://api.hyperliquid.xyz/ws";async function Ni(e,t={}){if(!e?.type)throw new Error("hlWsSnapshot requires subscription.type");let n=t.timeoutMs??8e3,r=t.maxMessages??1,o=t.WebSocket||globalThis.WebSocket;if(!o)throw new Error("WebSocket not available in this runtime");let i=t.url||zL,a=Date.now();return new Promise((s,c)=>{let l=!1,u=[],d=0,p=new o(i),m=setTimeout(()=>{f(),l||(l=!0,u.length?s({ok:!0,partial:!0,ms:Date.now()-a,messages:u}):c(new Error(`hl ws timeout after ${n}ms`)))},n);function f(){clearTimeout(m);try{p.close()}catch{}}p.addEventListener("open",()=>{p.send(JSON.stringify({method:"subscribe",subscription:e}))}),p.addEventListener("message",h=>{let g;try{g=JSON.parse(typeof h.data=="string"?h.data:String(h.data))}catch{g={raw:String(h.data).slice(0,200)}}u.push(g),g.channel&&g.channel!=="subscriptionResponse"?d+=1:g.data&&g.channel==="subscriptionResponse"||g.channel||(d+=1),d>=r&&(f(),l||(l=!0,s({ok:!0,ms:Date.now()-a,subscription:e,messages:u,last:u[u.length-1]})))}),p.addEventListener("error",()=>{f(),l||(l=!0,c(new Error("hl ws error")))})})}async function xv(e={}){try{let t=await Ni({type:"allMids"},{...e,maxMessages:1}),n=t.last||{},r=n.data?.mids||n.data||{},o=typeof r=="object"?Object.keys(r).length:0;return{ok:!0,ms:t.ms,midCount:o,channel:n.channel||null}}catch(t){return{ok:!1,error:String(t.message||t).slice(0,160)}}}async function kv(e={}){let t=await Ni({type:"allMids"},e),n=t.last||{};return{ms:t.ms,mids:n.data?.mids||n.data||{},channel:n.channel}}async function Sv(e,t={}){if(!e)throw new Error("coin required");let n=await Ni({type:"l2Book",coin:String(e)},t);return{ms:n.ms,book:n.last?.data||n.last,channel:n.last?.channel}}var WL=process.env.POLY_WS_URL||"wss://ws-subscriptions-clob.polymarket.com/ws/market";async function mc(e=[],t={}){let n=Array.isArray(e)?e.map(String):[String(e)];if(!n.length||!n[0])throw new Error("polyWsSnapshot requires assetIds");let r=t.timeoutMs??8e3,o=t.maxMessages??1,i=t.WebSocket||globalThis.WebSocket;if(!i)throw new Error("WebSocket not available");let a=t.url||WL,s=Date.now();return new Promise((c,l)=>{let u=!1,d=[],p=0,m=new i(a),f=setTimeout(()=>{h(),u||(u=!0,d.length?c({ok:!0,partial:!0,ms:Date.now()-s,messages:d}):l(new Error(`poly ws timeout after ${r}ms`)))},r);function h(){clearTimeout(f);try{m.close()}catch{}}m.addEventListener("open",()=>{m.send(JSON.stringify({assets_ids:n,type:"market"}))}),m.addEventListener("message",g=>{let w;try{w=JSON.parse(typeof g.data=="string"?g.data:String(g.data))}catch{w={raw:String(g.data).slice(0,300)}}d.push(w),p+=1,p>=o&&(h(),u||(u=!0,c({ok:!0,ms:Date.now()-s,assetIds:n,messages:d,last:d[d.length-1]})))}),m.addEventListener("error",()=>{h(),u||(u=!0,l(new Error("poly ws error")))})})}async function Iv(e={}){let t=e.assetId||"98022490269692409998126496127597032490334070080325855126491859374983463996227";try{let n=await mc([t],{...e,maxMessages:1});return{ok:!0,ms:n.ms,got:!!n.last,partial:n.partial||!1}}catch(n){return{ok:!1,error:String(n.message||n).slice(0,160)}}}async function Ev(e,t={}){if(!e)throw new Error("assetId required");let n=await mc([e],t);return{ms:n.ms,assetId:String(e),data:n.last,messages:n.messages}}R();var KL="https://api.binance.com",YL="https://fapi.binance.com",JL=8;function Qp(e={}){return(e.spotBaseUrl||e.baseUrl||process.env.BINANCE_API_URL||KL).replace(/\/$/,"")}function fc(e={}){return(e.futuresBaseUrl||process.env.BINANCE_FAPI_URL||YL).replace(/\/$/,"")}function Oi(e){return{error:String(e.message||e).slice(0,200)}}function rt(e){let t=Number(e);return Number.isFinite(t)?t:null}function Ri(e,t="USDT"){let n=String(e||"").trim().toUpperCase().replace(/[-_/]/g,"");return n?n.endsWith(t)?n:`${n}${t}`:""}async function hc(e={}){try{let t=await S(`${Qp(e)}/api/v3/ping`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??1e4});return{ok:t&&typeof t=="object",provider:"binance-public",execution:"read-only",exec:!1}}catch(t){return{ok:!1,provider:"binance-public",error:String(t.message||t).slice(0,160)}}}async function gc(e={},t={}){let n=Ri(e.symbol||e.coin,e.quote||"USDT");if(!n)return{error:"binanceTicker requires symbol or coin"};try{let r=e.full?"/api/v3/ticker/24hr":"/api/v3/ticker/price",o=await S(`${Qp(t)}${r}?symbol=${encodeURIComponent(n)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3});return{venue:"binance",market:"spot",symbol:n,price:rt(o?.price??o?.lastPrice),volume24h:rt(o?.volume),quoteVolume24h:rt(o?.quoteVolume),raw:o}}catch(r){return Oi(r)}}async function Av(e={},t={}){let n=Ri(e.symbol||e.coin,e.quote||"USDT");if(!n)return{error:"binanceOrderbook requires symbol or coin"};let r=Math.min(Math.max(Number(e.limit)||20,1),1e3),o=String(e.market||"spot").toLowerCase()==="perp";try{let i=o?`${fc(t)}/fapi/v1/depth?symbol=${encodeURIComponent(n)}&limit=${r}`:`${Qp(t)}/api/v3/depth?symbol=${encodeURIComponent(n)}&limit=${r}`,a=await S(i,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3});return $i({venue:"binance",market:o?"perp":"spot",symbol:n,bids:a?.bids,asks:a?.asks,raw:a})}catch(i){return Oi(i)}}async function Li(e={},t={}){let n=Ri(e.symbol||e.coin,e.quote||"USDT");if(!n)return{error:"binanceFunding requires symbol or coin"};try{let r=await S(`${fc(t)}/fapi/v1/premiumIndex?symbol=${encodeURIComponent(n)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),o=Array.isArray(r)?r[0]:r,i=Number(e.fundingIntervalHours)||JL,a=rt(o?.lastFundingRate);return{venue:"binance",market:"perp",symbol:n,markPrice:rt(o?.markPrice),indexPrice:rt(o?.indexPrice),fundingRate:a,fundingIntervalHours:i,fundingAprPct:a==null?null:a*(8760/i)*100,nextFundingTime:rt(o?.nextFundingTime),raw:o??null}}catch(r){return Oi(r)}}async function _v(e={},t={}){let n=await Li(e,t);return n?.error?n:{venue:"binance",market:"perp",symbol:n.symbol,markPrice:n.markPrice,indexPrice:n.indexPrice}}async function Pv(e={},t={}){let n=Ri(e.symbol||e.coin,e.quote||"USDT");if(!n)return{error:"binanceOpenInterest requires symbol or coin"};try{let r=await S(`${fc(t)}/fapi/v1/openInterest?symbol=${encodeURIComponent(n)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3});return{venue:"binance",market:"perp",symbol:n,openInterest:rt(r?.openInterest),time:rt(r?.time),raw:r??null}}catch(r){return Oi(r)}}async function Cv(e={},t={}){let n=Ri(e.symbol||e.coin,e.quote||"USDT");if(!n)return{error:"binanceFundingHistory requires symbol or coin"};let r=Math.min(Math.max(Number(e.limit)||10,1),1e3);try{let o=await S(`${fc(t)}/fapi/v1/fundingRate?symbol=${encodeURIComponent(n)}&limit=${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),i=Array.isArray(o)?o:[];return{venue:"binance",symbol:n,count:i.length,history:i.map(a=>({fundingTime:rt(a?.fundingTime),fundingRate:rt(a?.fundingRate)}))}}catch(o){return Oi(o)}}function $i({venue:e,market:t,symbol:n,bids:r,asks:o,raw:i}){let a=m=>(Array.isArray(m)?m:[]).map(f=>{let h=rt(Array.isArray(f)?f[0]:f?.price),g=rt(Array.isArray(f)?f[1]:f?.size);return h==null||g==null?null:{price:h,size:g}}).filter(Boolean),s=a(r),c=a(o),l=s[0]?.price??null,u=c[0]?.price??null,d=l!=null&&u!=null?(l+u)/2:null,p=d?(u-l)/d*1e4:null;return{venue:e,market:t,symbol:n,bids:s,asks:c,bestBid:l,bestAsk:u,mid:d,spreadBps:p,raw:i??null}}R();var XL="https://www.okx.com",QL=8;function Wr(e={}){return(e.baseUrl||process.env.OKX_API_URL||XL).replace(/\/$/,"")}function Bi(e){return{error:String(e.message||e).slice(0,200)}}function Je(e){if(e===""||e==null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function Mi(e,{market:t="spot",quote:n="USDT"}={}){let r=String(e||"").trim().toUpperCase();if(!r)return"";if(r.includes("-"))return r;let o=`${r}-${n}`;return t==="perp"?`${o}-SWAP`:o}function Gr(e){if(e&&String(e.code)!=="0"&&e.code!==void 0)throw new Error(`okx error ${e.code}: ${e.msg||"unknown"}`);let t=e?.data;return Array.isArray(t)?t:[]}async function yc(e={}){try{let t=await S(`${Wr(e)}/api/v5/public/time`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??1e4});return{ok:Gr(t).length>0,provider:"okx-public",execution:"read-only",exec:!1}}catch(t){return{ok:!1,provider:"okx-public",error:String(t.message||t).slice(0,160)}}}async function bc(e={},t={}){let n=String(e.market||"spot").toLowerCase(),r=Mi(e.instId||e.symbol||e.coin,{market:n,quote:e.quote||"USDT"});if(!r)return{error:"okxTicker requires instId, symbol or coin"};try{let o=await S(`${Wr(t)}/api/v5/market/ticker?instId=${encodeURIComponent(r)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),i=Gr(o)[0];return i?{venue:"okx",market:r.endsWith("-SWAP")?"perp":"spot",symbol:r,price:Je(i.last),bestBid:Je(i.bidPx),bestAsk:Je(i.askPx),volume24h:Je(i.vol24h),quoteVolume24h:Je(i.volCcy24h),raw:i}:{error:`okx ticker empty for ${r}`}}catch(o){return Bi(o)}}async function Nv(e={},t={}){let n=String(e.market||"spot").toLowerCase(),r=Mi(e.instId||e.symbol||e.coin,{market:n,quote:e.quote||"USDT"});if(!r)return{error:"okxOrderbook requires instId, symbol or coin"};let o=Math.min(Math.max(Number(e.limit)||20,1),400);try{let i=await S(`${Wr(t)}/api/v5/market/books?instId=${encodeURIComponent(r)}&sz=${o}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),a=Gr(i)[0];return a?$i({venue:"okx",market:r.endsWith("-SWAP")?"perp":"spot",symbol:r,bids:a.bids,asks:a.asks,raw:a}):{error:`okx books empty for ${r}`}}catch(i){return Bi(i)}}async function wc(e={},t={}){let n=Mi(e.instId||e.symbol||e.coin,{market:"perp",quote:e.quote||"USDT"});if(!n)return{error:"okxFunding requires instId, symbol or coin"};try{let r=await S(`${Wr(t)}/api/v5/public/funding-rate?instId=${encodeURIComponent(n)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),o=Gr(r)[0];if(!o)return{error:`okx funding-rate empty for ${n}`};let i=Number(e.fundingIntervalHours)||QL,a=Je(o.fundingRate);return{venue:"okx",market:"perp",symbol:n,fundingRate:a,nextFundingRate:Je(o.nextFundingRate),fundingIntervalHours:i,fundingAprPct:a==null?null:a*(8760/i)*100,nextFundingTime:Je(o.nextFundingTime??o.fundingTime),raw:o}}catch(r){return Bi(r)}}async function vc(e={},t={}){let n=Mi(e.instId||e.symbol||e.coin,{market:"perp",quote:e.quote||"USDT"});if(!n)return{error:"okxMarkPrice requires instId, symbol or coin"};let r=String(e.instType||"SWAP").toUpperCase();try{let o=await S(`${Wr(t)}/api/v5/public/mark-price?instType=${encodeURIComponent(r)}&instId=${encodeURIComponent(n)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),i=Gr(o)[0];return i?{venue:"okx",market:"perp",symbol:n,markPrice:Je(i.markPx),time:Je(i.ts),raw:i}:{error:`okx mark-price empty for ${n}`}}catch(o){return Bi(o)}}async function Ov(e={},t={}){let n=Mi(e.instId||e.symbol||e.coin,{market:"perp",quote:e.quote||"USDT"});if(!n)return{error:"okxOpenInterest requires instId, symbol or coin"};let r=String(e.instType||"SWAP").toUpperCase();try{let o=await S(`${Wr(t)}/api/v5/public/open-interest?instType=${encodeURIComponent(r)}&instId=${encodeURIComponent(n)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),i=Gr(o)[0];return i?{venue:"okx",market:"perp",symbol:n,openInterest:Je(i.oiCcy??i.oi),openInterestContracts:Je(i.oi),openInterestUsd:Je(i.oiUsd),time:Je(i.ts),raw:i}:{error:`okx open-interest empty for ${n}`}}catch(o){return Bi(o)}}R();var ZL="https://api.bybit.com",e$=8;function Ui(e={}){return(e.baseUrl||process.env.BYBIT_API_URL||ZL).replace(/\/$/,"")}function Fi(e){return{error:String(e.message||e).slice(0,200)}}function Te(e){if(e===""||e==null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function xc(e,t="USDT"){let n=String(e||"").trim().toUpperCase().replace(/[-_/]/g,"");return n?n.endsWith(t)?n:`${n}${t}`:""}function Zp(e){let t=String(e||"spot").toLowerCase();return t==="perp"||t==="linear"||t==="swap"?"linear":t==="inverse"?"inverse":"spot"}function Di(e){if(e&&e.retCode!==void 0&&Number(e.retCode)!==0)throw new Error(`bybit error ${e.retCode}: ${e.retMsg||"unknown"}`);return e?.result??null}async function kc(e={}){try{let t=await S(`${Ui(e)}/v5/market/time`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs??1e4});return{ok:!!Di(t),provider:"bybit-public",execution:"read-only",exec:!1}}catch(t){return{ok:!1,provider:"bybit-public",error:String(t.message||t).slice(0,160)}}}async function Lv(e,t){let n=Zp(e.market),r=xc(e.symbol||e.coin,e.quote||"USDT");if(!r)return{error:"bybit requires symbol or coin"};let o=await S(`${Ui(t)}/v5/market/tickers?category=${encodeURIComponent(n)}&symbol=${encodeURIComponent(r)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),i=Di(o)?.list?.[0];return i?{row:i,symbol:r,category:n}:{error:`bybit tickers empty for ${r}`}}async function Sc(e={},t={}){try{let n=await Lv(e,t);if(n.error)return n;let{row:r,symbol:o,category:i}=n;return{venue:"bybit",market:i==="spot"?"spot":"perp",symbol:o,price:Te(r.lastPrice),bestBid:Te(r.bid1Price),bestAsk:Te(r.ask1Price),markPrice:Te(r.markPrice),indexPrice:Te(r.indexPrice),volume24h:Te(r.volume24h),quoteVolume24h:Te(r.turnover24h),raw:r}}catch(n){return Fi(n)}}async function $v(e={},t={}){let n=Zp(e.market),r=xc(e.symbol||e.coin,e.quote||"USDT");if(!r)return{error:"bybitOrderbook requires symbol or coin"};let o=Math.min(Math.max(Number(e.limit)||25,1),200);try{let i=await S(`${Ui(t)}/v5/market/orderbook?category=${encodeURIComponent(n)}&symbol=${encodeURIComponent(r)}&limit=${o}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),a=Di(i);return a?$i({venue:"bybit",market:n==="spot"?"spot":"perp",symbol:r,bids:a.b,asks:a.a,raw:a}):{error:`bybit orderbook empty for ${r}`}}catch(i){return Fi(i)}}async function qi(e={},t={}){try{let n=await Lv({...e,market:e.market||"perp"},t);if(n.error)return n;let{row:r,symbol:o}=n,i=Number(e.fundingIntervalHours)||e$,a=Te(r.fundingRate);return{venue:"bybit",market:"perp",symbol:o,markPrice:Te(r.markPrice),indexPrice:Te(r.indexPrice),fundingRate:a,fundingIntervalHours:i,fundingAprPct:a==null?null:a*(8760/i)*100,nextFundingTime:Te(r.nextFundingTime),openInterest:Te(r.openInterest),raw:r}}catch(n){return Fi(n)}}async function Bv(e={},t={}){let n=await qi(e,t);return n?.error?n:{venue:"bybit",market:"perp",symbol:n.symbol,markPrice:n.markPrice,indexPrice:n.indexPrice}}async function Mv(e={},t={}){let n=xc(e.symbol||e.coin,e.quote||"USDT");if(!n)return{error:"bybitOpenInterest requires symbol or coin"};let r=Zp(e.market||"perp"),o=String(e.intervalTime||"1h"),i=Math.min(Math.max(Number(e.limit)||1,1),200);try{let a=await S(`${Ui(t)}/v5/market/open-interest?category=${encodeURIComponent(r)}&symbol=${encodeURIComponent(n)}&intervalTime=${encodeURIComponent(o)}&limit=${i}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),s=Di(a)?.list,c=Array.isArray(s)?s[0]:null;return c?{venue:"bybit",market:"perp",symbol:n,openInterest:Te(c.openInterest),time:Te(c.timestamp),history:(Array.isArray(s)?s:[]).map(l=>({openInterest:Te(l?.openInterest),timestamp:Te(l?.timestamp)}))}:{error:`bybit open-interest empty for ${n}`}}catch(a){return Fi(a)}}async function Uv(e={},t={}){let n=xc(e.symbol||e.coin,e.quote||"USDT");if(!n)return{error:"bybitFundingHistory requires symbol or coin"};let r=Math.min(Math.max(Number(e.limit)||10,1),200);try{let o=await S(`${Ui(t)}/v5/market/funding/history?category=linear&symbol=${encodeURIComponent(n)}&limit=${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),i=Di(o)?.list,a=Array.isArray(i)?i:[];return{venue:"bybit",symbol:n,count:a.length,history:a.map(s=>({fundingRate:Te(s?.fundingRate),fundingTime:Te(s?.fundingRateTimestamp)}))}}catch(o){return Fi(o)}}dt();var em=["binance","okx","bybit","hyperliquid"],Dv=1;function Hi(e){return{error:String(e.message||e).slice(0,200)}}function Be(e){if(e===""||e==null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function t$(e,t){return e==null||!t?null:e*(8760/t)*100}function tm(e={}){return String(e.coin||e.symbol||"").trim().toUpperCase().replace(/[-_/]/g,"").replace(/USDT?$/,"")||""}function n$(e={}){let t=e.venues,n=Array.isArray(t)?t:typeof t=="string"&&t.trim()&&t.trim().toLowerCase()!=="all"?t.split(","):em,r=new Set(n.map(i=>String(i).trim().toLowerCase()).filter(Boolean)),o=em.filter(i=>r.has(i));return o.length?o:em}async function r$(e={},t={}){let n=tm(e);if(!n)return{error:"hyperliquidPerpLeg requires coin"};try{let r=await Ke(t),o=r?.[0]?.universe,i=r?.[1];if(!Array.isArray(o)||!Array.isArray(i))return{error:"hyperliquid metaAndAssetCtxs returned an unexpected shape"};let a=o.findIndex(l=>String(l?.name||"").toUpperCase()===n);if(a<0)return{error:`hyperliquid has no perp for ${n}`};let s=i[a]||{},c=Be(s.funding);return{venue:"hyperliquid",market:"perp",symbol:n,markPrice:Be(s.markPx),indexPrice:Be(s.oraclePx),midPrice:Be(s.midPx),fundingRate:c,fundingIntervalHours:Dv,fundingAprPct:t$(c,Dv),openInterest:Be(s.openInterest)}}catch(r){return Hi(r)}}async function o$(e={},t={}){let n=tm(e);if(!n)return{error:"hyperliquidSpotLeg requires coin"};try{let r=await xt(t),o=Be(r?.[n]);return o==null?{error:`hyperliquid allMids has no entry for ${n}`}:{venue:"hyperliquid",market:"spot",symbol:n,price:o}}catch(r){return Hi(r)}}async function i$(e={},t={}){let[n,r]=await Promise.all([wc(e,t).catch(Hi),vc(e,t).catch(Hi)]);return n?.error&&r?.error?n:{...n?.error?{venue:"okx",market:"perp",fundingError:n.error}:n,markPrice:r?.error?null:Be(r.markPrice),...r?.error?{markError:r.error}:{}}}async function An(e,t){try{let n=await t;return[e,n&&typeof n=="object"?n:{error:"empty response"}]}catch(n){return[e,Hi(n)]}}async function nm(e={},t={}){let n=tm(e);if(!n)return{error:"cexVenueLegs requires coin"};let r=e.quote||"USDT",o=n$(e),i=[];o.includes("binance")&&(i.push(An("binance:perp",Li({coin:n,quote:r},t))),i.push(An("binance:spot",gc({coin:n,quote:r},t)))),o.includes("okx")&&(i.push(An("okx:perp",i$({coin:n,quote:r},t))),i.push(An("okx:spot",bc({coin:n,quote:r,market:"spot"},t)))),o.includes("bybit")&&(i.push(An("bybit:perp",qi({coin:n,quote:r},t))),i.push(An("bybit:spot",Sc({coin:n,quote:r,market:"spot"},t)))),o.includes("hyperliquid")&&(i.push(An("hyperliquid:perp",r$({coin:n},t))),i.push(An("hyperliquid:spot",o$({coin:n},t))));let a=await Promise.all(i),s={};for(let[c,l]of a){let[u,d]=c.split(":");s[u]=s[u]||{},s[u][d]=l}return{coin:n,quote:r,venues:o,legs:s}}function qv(e){return!e||e.error?null:Be(e.price)??Be(e.mid)??null}function a$(e){return!e||e.error?null:Be(e.markPrice)??Be(e.midPrice)??null}async function rm(e={},t={}){let n=await nm(e,t);if(n.error)return n;let{coin:r,quote:o,venues:i,legs:a}=n,s=[];for(let f of i){let h=qv(a[f]?.spot);h!=null&&h>0&&s.push(h)}let c=[...s].sort((f,h)=>f-h),l=c.length?c.length%2?c[(c.length-1)/2]:(c[c.length/2-1]+c[c.length/2])/2:null,u=[];for(let f of i){let h=a[f]?.perp,g=a[f]?.spot,w=a$(h),x=qv(g),b=x??l,y=w!=null&&b?(w-b)/b*1e4:null;u.push({venue:f,symbol:h?.symbol??g?.symbol??r,markPrice:w,spotPrice:x,spotSource:x!=null?f:l!=null?"cross-venue-median":null,basisBps:y,fundingRate:h&&!h.error?Be(h.fundingRate):null,fundingIntervalHours:h&&!h.error?Be(h.fundingIntervalHours):null,fundingAprPct:h&&!h.error?Be(h.fundingAprPct):null,openInterest:h&&!h.error?Be(h.openInterest):null,errors:[h?.error,g?.error].filter(Boolean)})}let d=s$(u),p=u.filter(f=>f.markPrice!=null),m=u.filter(f=>f.basisBps!=null);return{coin:r,quote:o,referenceSpot:l,asOf:new Date().toISOString(),venues:u,fundingSpreads:d,widestFundingSpread:d[0]??null,richestBasis:m.length?m.reduce((f,h)=>h.basisBps>f.basisBps?h:f):null,cheapestBasis:m.length?m.reduce((f,h)=>h.basisBps<f.basisBps?h:f):null,venuesPriced:p.length,venuesRequested:i.length,execution:"read-only",exec:!1,note:"Public market data only. Funding compared on an annualized basis (HL settles hourly, CEXes 8h). Not advice."}}function s$(e=[]){let t=e.filter(r=>Be(r?.fundingAprPct)!=null),n=[];for(let r=0;r<t.length;r++)for(let o=r+1;o<t.length;o++){let i=t[r],a=t[o],s=i.fundingAprPct-a.fundingAprPct,c=s>0?a.venue:i.venue,l=s>0?i.venue:a.venue;n.push({pair:`${i.venue}/${a.venue}`,aprSpreadPct:Math.abs(s),signedAprSpreadPct:s,longVenue:c,shortVenue:l})}return n.sort((r,o)=>o.aprSpreadPct-r.aprSpreadPct)}async function Hv(e={},t={}){let n=await rm(e,t);return n.error?n:{coin:n.coin,asOf:n.asOf,venues:n.venues.map(r=>({venue:r.venue,symbol:r.symbol,fundingRate:r.fundingRate,fundingIntervalHours:r.fundingIntervalHours,fundingAprPct:r.fundingAprPct,errors:r.errors})),fundingSpreads:n.fundingSpreads,widestFundingSpread:n.widestFundingSpread,execution:"read-only",exec:!1}}async function jv(e={}){try{let t=await Promise.all([hc(e).catch(()=>({ok:!1})),yc(e).catch(()=>({ok:!1})),kc(e).catch(()=>({ok:!1}))]),n={binance:!!t[0]?.ok,okx:!!t[1]?.ok,bybit:!!t[2]?.ok};return{ok:Object.values(n).some(Boolean),provider:"cex-basis",upstream:n,execution:"read-only",exec:!1}}catch(t){return{ok:!1,provider:"cex-basis",error:String(t.message||t).slice(0,160)}}}import Kv from"node:path";import{homedir as x$}from"node:os";import{createHash as k$,randomUUID as S$}from"node:crypto";import se from"node:fs";import Ic from"node:path";import{createHash as l$,randomUUID as zv}from"node:crypto";var om=1,St=class extends Error{constructor(t,n="DURABLE_STORE_ERROR"){super(t),this.name="DurableStoreError",this.code=n}};function _n(e){if(e===null)return"null";if(typeof e=="string"||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError("durable store values must contain finite numbers");return JSON.stringify(e)}if(Array.isArray(e))return`[${e.map(_n).join(",")}]`;if(e&&typeof e=="object")return`{${Object.keys(e).sort().map(n=>`${JSON.stringify(n)}:${_n(e[n])}`).join(",")}}`;throw new TypeError(`durable store values must be JSON-safe, got ${typeof e}`)}function Vv(e){return l$("sha256").update(_n(e)).digest("hex")}function Ec(e){let t=e(),n=t instanceof Date?t.getTime():typeof t=="string"?Date.parse(t):Number(t);if(!Number.isFinite(n))throw new TypeError("clock must return epoch milliseconds, an ISO string, or a Date");return Math.trunc(n)}function Ac(e){return e===void 0?void 0:JSON.parse(JSON.stringify(e))}function Wv(e){se.mkdirSync(e,{recursive:!0,mode:448});try{se.chmodSync(e,448)}catch{}}function im(e){try{let t=se.statSync(e);return{...JSON.parse(se.readFileSync(e,"utf8")),mtimeMs:t.mtimeMs}}catch{return null}}function Kr({filePath:e,kind:t,initialData:n,validateData:r,clock:o=()=>Date.now(),maxBytes:i=4*1024*1024,lockStaleMs:a=3e4,lockWaitMs:s=2e3,lockIdFactory:c=()=>zv()}={}){if(typeof e!="string"||e==="")throw new TypeError("filePath is required");if(!/^[a-z][a-z0-9._-]{0,63}$/i.test(String(t)))throw new TypeError("a bounded store kind is required");if(typeof n!="function"||typeof r!="function")throw new TypeError("initialData and validateData are required");if(!Number.isSafeInteger(i)||i<1024)throw new TypeError("maxBytes must be at least 1024");if(!Number.isSafeInteger(a)||a<1e3)throw new TypeError("lockStaleMs must be at least 1000");if(!Number.isSafeInteger(s)||s<0||s>3e4)throw new TypeError("lockWaitMs must be between 0 and 30000");let l=`${e}.lock`;function u(){let b=n();return r(b),{schemaVersion:om,kind:t,generation:0,data:b}}function d(b){let y;try{y=JSON.parse(b)}catch(I){throw new St(`corrupt ${t} snapshot: invalid JSON (${I.message})`,"STORE_CORRUPT")}if(!y||typeof y!="object"||Array.isArray(y))throw new St(`corrupt ${t} snapshot: root must be an object`,"STORE_CORRUPT");if(y.schemaVersion!==om)throw new St(`unsupported ${t} schemaVersion ${String(y.schemaVersion)}`,"STORE_SCHEMA");if(y.kind!==t||!Number.isSafeInteger(y.generation)||y.generation<0)throw new St(`corrupt ${t} snapshot metadata`,"STORE_CORRUPT");let{integrity:k,...E}=y;if(typeof k!="string"||!/^[a-f0-9]{64}$/.test(k)||Vv(E)!==k)throw new St(`corrupt ${t} snapshot: checksum mismatch`,"STORE_CORRUPT");try{r(y.data)}catch(I){throw new St(`corrupt ${t} snapshot: ${I.message}`,"STORE_CORRUPT")}return E}function p(){if(!se.existsSync(e))return u();let b=se.statSync(e);if(!b.isFile()||b.size>i)throw new St(`${t} snapshot is not a bounded regular file`,"STORE_BOUNDS");try{se.chmodSync(e,384)}catch{}return d(se.readFileSync(e,"utf8"))}function m(){Wv(Ic.dirname(e));let b=Ec(o),y=String(c()),k=`${JSON.stringify({schemaVersion:1,lockId:y,pid:process.pid,acquiredAt:b})}
|
|
146
146
|
`,E=()=>{let P;try{return P=se.openSync(l,"wx",384),se.writeFileSync(P,k,"utf8"),se.fsyncSync(P),se.closeSync(P),{lockId:y}}catch(T){let L=P!==void 0;if(L)try{se.closeSync(P)}catch{}if(L)try{se.unlinkSync(l)}catch{}if(T?.code!=="EEXIST")throw T;return null}},v=Ec(o)+s,A=new Int32Array(new SharedArrayBuffer(4));for(;;){let P=E();if(P)return P;let T=Ec(o),L=im(l),F=!1;if(L){let O=T-Number(L.acquiredAt??L.mtimeMs);F=Number.isFinite(O)&&O>=a}else try{F=T-se.statSync(l).mtimeMs>=a}catch{F=!1}if(F){let O=im(l);if(L?O?.lockId===L.lockId:O===null){try{se.unlinkSync(l)}catch(B){if(B?.code!=="ENOENT")throw B}continue}}let q=v-T;if(q<=0)throw new St(`${t} store is busy`,"STORE_BUSY");Atomics.wait(A,0,0,Math.min(10,q))}}function f(b){if(im(l)?.lockId===b.lockId)try{se.unlinkSync(l)}catch(k){if(k?.code!=="ENOENT")throw k}}function h(b){r(b.data);let y={...b,integrity:Vv(b)},k=`${_n(y)}
|
|
147
147
|
`;if(Buffer.byteLength(k)>i)throw new St(`${t} snapshot exceeds ${i} bytes`,"STORE_BOUNDS");let E=Ic.dirname(e);Wv(E);let I=Ic.join(E,`.${Ic.basename(e)}.${process.pid}.${zv()}.tmp`),v;try{v=se.openSync(I,"wx",384),se.writeFileSync(v,k,"utf8"),se.fsyncSync(v),se.closeSync(v),v=void 0,se.renameSync(I,e);try{se.chmodSync(e,384)}catch{}try{let A=se.openSync(E,"r");try{se.fsyncSync(A)}finally{se.closeSync(A)}}catch{}}finally{if(v!==void 0)try{se.closeSync(v)}catch{}try{se.unlinkSync(I)}catch(A){if(A?.code!=="ENOENT")throw A}}}function g(){return Ac(p().data)}function w(){let b=p();return{schemaVersion:b.schemaVersion,kind:b.kind,generation:b.generation,data:Ac(b.data)}}function x(b){if(typeof b!="function")throw new TypeError("mutator must be a function");let y=m();try{let k=p(),E=Ac(k.data),I=b(E,{generation:k.generation,now:Ec(o)});return r(E),h({schemaVersion:om,kind:t,generation:k.generation+1,data:E}),Ac(I)}finally{f(y)}}return Object.freeze({filePath:e,read:g,inspect:w,mutate:x})}import{wordlists as u$}from"ethers";var d$=new Set(["privatekey","privkey","secretkey","seedphrase","seed","mnemonic","passphrase","password","keystore","keymaterial","wif","xprv","xpriv","bearer","authorization","signature","apikey","credential"]),p$=[/\b[5KL][1-9A-HJ-NP-Za-km-z]{50,51}\b/,/\bxprv[0-9A-Za-z]{50,}\b/],m$=new Set([12,15,18,21,24]);function f$(e){let t=String(e).trim().toLowerCase().split(/\s+/).filter(Boolean);return m$.has(t.length)&&t.every(n=>u$.en.getWordIndex(n)>=0)}var h$=/^\s*(?:0x)?[0-9a-fA-F]{64}\s*$/,g$=/(hash|digest|root|salt|nonce|proof|commitment|sig|id)(?:e?s)?$/i,y$=new Set(["calldata","data","publickey","pubkey","message","payload","input","extradata"]);function b$(e){let t=Gv(e);return y$.has(t)||g$.test(t)}var ji=class extends Error{constructor(t){super(`action receipt refused: secret-bearing field at ${t}`),this.name="ActionReceiptSecretError",this.code="ACTION_RECEIPT_SECRET"}};function Gv(e){return String(e).replace(/[^a-z0-9]/gi,"").toLowerCase()}function w$(e){let t=Gv(e);return[...d$].some(n=>t.includes(n))}function v$(e,t,n){if(typeof t=="string"){if(p$.some(r=>r.test(t))||f$(t))throw new ji(n);if(h$.test(t)&&!b$(e))throw new ji(n)}}function am(e,t="$",n=""){if(e==null||typeof e=="boolean")return e;if(typeof e=="string")return v$(n,e,t),e;if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError(`action receipt: non-finite number at ${t}`);return e}if(typeof e=="bigint")return e.toString();if(Array.isArray(e))return e.map((o,i)=>am(o,`${t}[${i}]`,n));if(typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype)throw new TypeError(`action receipt: JSON-like value required at ${t}`);let r={};for(let o of Object.keys(e).sort()){let i=`${t}.${o}`;if(w$(o))throw new ji(i);e[o]!==void 0&&(r[o]=am(e[o],i,o))}return r}function Qt(e){return am(e)}var Pc=1,Yv="Local catalog only; existing marketplace providers are unchanged. Armed for the owner-local signer. Sign/broadcast require an explicit instruction.",Uz=Object.freeze(["listing","offer","arm","instruct"]),I$=Object.freeze(["open","cancelled","expired","armed","submitted"]),Fz=Object.freeze(["arm","sign-and-broadcast"]),E$=Object.freeze({protocol:"oracle-a2a/1",name:"oracle-local-marketplace",brand:"Oracle",publisher:"Oracle",product:"Oracle",role:"Oracle owner-local P2 catalog",consultOnly:!0,remoteDelegation:!1,pluginExecution:!1,refusesSignHash:!0,skills:Object.freeze(["list-local-listings"]),note:"Oracle consult-only local Agent Card. Untrusted A2A text cannot create, fill, cancel, sign, or broadcast listings. Existing marketplace providers are unchanged. No plugin pack loader."}),A$=/^(?:0|[1-9][0-9]*)$/,_$=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,P$=/^0x[a-fA-F0-9]{40}$/,C$=/^0x[a-fA-F0-9]{64}$/,T$=/[\u0000-\u001f\u007f]/,N$=new Set(I$),lm=class extends Error{constructor(t,n="LOCAL_MARKETPLACE_INVALID"){super(`local-marketplace: ${t}`),this.name="LocalMarketplaceError",this.code=n}};function K(e,t){throw new lm(e,t)}function sr(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))sr(t);Object.freeze(e)}return e}function Vi(e,t,{max:n=256,lower:r=!1}={}){typeof e!="string"&&K(`${t} must be a string`);let o=e.trim();return(!o||o.length>n||T$.test(o))&&K(`${t} is invalid`),r?o.toLowerCase():o}function qe(e,t){let n=Vi(e,t,{max:128});return _$.test(n)||K(`${t} must be a bounded id`),n}function zi(e,t,{positive:n=!1}={}){typeof e=="number"&&K(`${t} must be an exact integer string`);let r=typeof e=="bigint"?e.toString():String(e??"");return A$.test(r)||K(`${t} must be a canonical integer string`),n&&r==="0"&&K(`${t} must be positive`),r}function ar(e,t){let n=Vi(e,t,{max:42,lower:!0});return P$.test(n)||K(`${t} must be a 20-byte EVM address`),n}function Jv(e,t){return(!e||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&K(`${t} must be a plain object`),e}function ir(e){let t=e(),n=t instanceof Date?t.getTime():typeof t=="string"?Date.parse(t):Number(t);return(!Number.isSafeInteger(n)||n<0)&&K("clock must return a safe integer millisecond timestamp","CLOCK_INVALID"),n}function sm(e){return new Date(e).toISOString()}function O$(e){return k$("sha256").update(_n(e),"utf8").digest("hex")}function R$(e=process.env){let t=e.ORACLE_CONFIG_DIR||Kv.join(x$(),".config","oracle");return Kv.join(t,"local-marketplace.v1.json")}function _c(e){let t=e.status==="submitted";return sr({schemaVersion:Pc,listingId:e.listingId,tenantId:e.tenantId,seller:e.seller,asset:e.asset,amount:e.amount,price:e.price,chainId:e.chainId,status:N$.has(e.status)?e.status:K("invalid listing status","STORE_INVALID"),createdAt:e.createdAt,expiresAt:e.expiresAt,listingHash:e.listingHash,offers:(e.offers||[]).map(n=>sr({offerId:n.offerId,buyer:n.buyer,amount:n.amount,status:n.status,createdAt:n.createdAt})),transactionHash:e.transactionHash||null,label:Yv,custody:"none",execution:t?"local-signer-instructed":"armed-local",armed:!t,signed:t,broadcast:t})}function L$(e){(!e||e.schemaVersion!==Pc||!Array.isArray(e.listings))&&K("invalid marketplace snapshot","STORE_INVALID"),e.listings.length>1e4&&K("marketplace capacity exceeded","STORE_LIMIT")}function cm(e,t){return sr({schemaVersion:Pc,recordType:"local-marketplace-armed",listingId:e.listingId,offerId:t.offerId,tenantId:e.tenantId,seller:e.seller,buyer:t.buyer,asset:e.asset,amount:t.amount,price:e.price,chainId:e.chainId,listingHash:e.listingHash,unsigned:{kind:"local-p2-fill",from:e.seller,to:t.buyer,asset:e.asset,amount:t.amount,price:e.price,chainId:e.chainId},review:`Local P2 fill ${e.listingId} is armed for the owner-local signer: seller ${e.seller} transfers ${t.amount} ${e.asset} to ${t.buyer} at ${e.price} on chain ${e.chainId}. Sign and broadcast still require an explicit instruction.`,label:Yv,custody:"none",execution:"armed-local",armed:!0,signed:!1,broadcast:!1,requiresWalletSignature:!0,backendSigner:!1,refusesSignHash:!0})}function $$(e,t,n){typeof e=="string"&&K("raw hash artifacts are refused; pass a typed local-signer artifact","SIGNHASH_REFUSED");let r=Jv(e,"instruction.artifact");(Object.prototype.hasOwnProperty.call(r,"signHash")||Object.prototype.hasOwnProperty.call(r,"hashToSign"))&&K("generic signHash is refused","SIGNHASH_REFUSED");let o=ar(r.from??r.offerer??t.seller,"artifact.from"),i=ar(r.to??r.recipient??n.buyer,"artifact.to"),a=zi(r.chainId??t.chainId,"artifact.chainId",{positive:!0});return o!==t.seller&&K("artifact.from must match the seller","ARTIFACT_MISMATCH"),i!==n.buyer&&K("artifact.to must match the buyer","ARTIFACT_MISMATCH"),a!==t.chainId&&K("artifact.chainId must match the listing","ARTIFACT_MISMATCH"),r.listingHash&&r.listingHash!==t.listingHash&&K("artifact.listingHash must match the listing","ARTIFACT_MISMATCH"),r}function B$(e,t){if(e==null)return{action:"arm"};let n=Jv(e,"instruction");Object.prototype.hasOwnProperty.call(n,"signHash")&&n.signHash!==!1&&K("generic signHash is refused","SIGNHASH_REFUSED");let r=Vi(n.action??"arm","instruction.action",{max:64});return r==="arm"?{action:"arm"}:(r==="prepare"&&K("prepare is refused; arm the listing, then instruct sign-and-broadcast","INSTRUCTION_INVALID"),r!=="sign-and-broadcast"&&K("instruction.action must be arm or sign-and-broadcast","INSTRUCTION_INVALID"),n.confirm!==!0&&K("sign-and-broadcast requires confirm: true","INSTRUCTION_INVALID"),n.sign!==!0&&K("sign-and-broadcast requires sign: true","INSTRUCTION_INVALID"),n.broadcast!==!0&&K("sign-and-broadcast requires broadcast: true","INSTRUCTION_INVALID"),n.listingHash&&n.listingHash!==t.listingHash&&K("instruction.listingHash must match the listing","ARTIFACT_MISMATCH"),n)}function Xv({filePath:e=R$(),clock:t=()=>Date.now(),idFactory:n=()=>S$()}={}){let r=Kr({filePath:e,kind:"oracle-local-marketplace",clock:t,maxBytes:4194304,initialData:()=>({schemaVersion:Pc,listings:[]}),validateData:L$});function o(h,g){return h.tenantId===g}function i(h,g){return h.status==="open"&&Date.parse(h.expiresAt)<=g&&(h.status="expired"),h}function a(h={}){Qt(h);let g=qe(h.tenantId,"tenantId"),w=ar(h.seller,"seller"),x=Vi(h.asset,"asset",{max:128}),b=zi(h.amount,"amount",{positive:!0}),y=zi(h.price,"price",{positive:!0}),k=zi(h.chainId,"chainId",{positive:!0}),E=ir(t),I=sm(E),v=h.expiresAt==null?sm(E+864e5):Vi(h.expiresAt,"expiresAt",{max:64});(!Number.isFinite(Date.parse(v))||Date.parse(v)<=E)&&K("expiresAt must be after now");let A=qe(String(h.listingId??`listing-${n()}`),"listingId");return r.mutate(P=>{P.listings.some(F=>F.listingId===A)&&K("listingId already exists","DUPLICATE");let T={listingId:A,tenantId:g,seller:w,asset:x,amount:b,price:y,chainId:k,status:"open",createdAt:I,expiresAt:v,offers:[],custody:"none",execution:"armed-local"},L={...T,listingHash:O$(T)};return P.listings.push(L),_c(L)})}function s({tenantId:h}={}){let g=qe(h,"tenantId"),w=ir(t);return sr(r.read().listings.filter(x=>o(x,g)).map(x=>_c(i({...x,offers:x.offers.map(b=>({...b}))},w))))}function c({tenantId:h,listingId:g,actor:w}={}){let x=qe(h,"tenantId"),b=qe(g,"listingId"),y=ar(w,"actor"),k=ir(t);return r.mutate(E=>{let I=E.listings.find(v=>o(v,x)&&v.listingId===b);return I||K("listing not found","NOT_FOUND"),i(I,k),I.seller!==y&&K("only the seller can cancel","FORBIDDEN"),I.status!=="open"&&K("listing is not open","NOT_OPEN"),I.status="cancelled",_c(I)})}function l(h={}){Qt(h);let g=qe(h.tenantId,"tenantId"),w=qe(h.listingId,"listingId"),x=ar(h.buyer,"buyer"),b=zi(h.amount,"amount",{positive:!0}),y=ir(t),k=qe(String(h.offerId??`offer-${n()}`),"offerId");return r.mutate(E=>{let I=E.listings.find(v=>o(v,g)&&v.listingId===w);return I||K("listing not found","NOT_FOUND"),i(I,y),I.status!=="open"&&K("listing is not open","NOT_OPEN"),I.seller===x&&K("seller cannot offer on their own listing","FORBIDDEN"),I.offers.some(v=>v.offerId===k)&&K("offerId already exists","DUPLICATE"),I.offers.push({offerId:k,buyer:x,amount:b,status:"open",createdAt:sm(y)}),_c(I)})}function u(h,{tenantId:g,listingId:w,offerId:x,actor:b,now:y,allowed:k=["open","armed"]}){let E=h.listings.find(v=>o(v,g)&&v.listingId===w);E||K("listing not found","NOT_FOUND"),i(E,y),k.includes(E.status)||K("listing is not open","NOT_OPEN"),E.seller!==b&&K("only the seller can arm a fill","FORBIDDEN");let I=E.offers.find(v=>v.offerId===x);return(!I||!["open","armed"].includes(I.status))&&K("offer not found","NOT_FOUND"),{row:E,offer:I}}function d({tenantId:h,listingId:g,offerId:w,actor:x}={}){let b=qe(h,"tenantId"),y=qe(g,"listingId"),k=qe(w,"offerId"),E=ar(x,"actor"),I=ir(t);return r.mutate(v=>{let{row:A,offer:P}=u(v,{tenantId:b,listingId:y,offerId:k,actor:E,now:I});return A.status="armed",P.status="armed",cm(A,P)})}async function p({tenantId:h,listingId:g,offerId:w,actor:x,instruction:b,executor:y}={}){let k=qe(h,"tenantId"),E=qe(g,"listingId"),I=qe(w,"offerId"),v=ar(x,"actor"),A=ir(t),P=r.mutate(B=>{let{row:z,offer:le}=u(B,{tenantId:k,listingId:E,offerId:I,actor:v,now:A,allowed:["open","armed"]}),ue=B$(b,z);return z.status="armed",le.status="armed",{armed:cm(z,le),instruction:ue,listingHash:z.listingHash}});if(P.instruction.action==="arm")return P.armed;let T=r.read().listings.find(B=>B.listingId===E&&B.tenantId===k),L=T?.offers.find(B=>B.offerId===I),F=$$(P.instruction.artifact,T,L);(!y||typeof y.executeConfirmedArtifact!="function")&&K("sign-and-broadcast requires an injected local-signer executor","EXECUTOR_REQUIRED"),typeof y.signHash=="function"&&K("generic signHash executors are refused","SIGNHASH_REFUSED");let q=await y.executeConfirmedArtifact(F,P.instruction.nonce,y),O=q?.receipt?.transactionHash??q?.transactionHash;(typeof O!="string"||!C$.test(O))&&K("local-signer receipt must include a 32-byte transaction hash","RECEIPT_INVALID");let H=q?.receipt?.status??q?.status;return H!==1&&H!=="0x1"&&K("local-signer broadcast did not return a successful receipt","RECEIPT_INVALID"),r.mutate(B=>{let{row:z,offer:le}=u(B,{tenantId:k,listingId:E,offerId:I,actor:v,now:ir(t),allowed:["armed"]});return z.status="submitted",le.status="submitted",z.transactionHash=O.toLowerCase(),sr({...cm(z,le),recordType:"local-marketplace-submitted",execution:"local-signer-instructed",armed:!1,signed:!0,broadcast:!0,backendSigner:!0,requiresWalletSignature:!1,refusesSignHash:!0,transactionHash:z.transactionHash,review:`Local P2 fill ${z.listingId} signed and broadcast through the instructed local signer. transactionHash=${z.transactionHash}`})})}function m({tenantId:h,text:g}={}){return qe(h,"tenantId"),(typeof g!="string"||g.trim()==="")&&K("consult text required"),sr({accepted:!1,reason:"untrusted consult text cannot create, fill, or cancel listings",custody:"none",execution:"armed-local",armed:!0,signed:!1,broadcast:!1})}function f(){return E$}return Object.freeze({createListing:a,listListings:s,cancelListing:c,createOffer:l,armFill:d,instructFill:p,ingestUntrustedConsult:m,agentCard:f})}import Qv from"node:path";import{homedir as M$}from"node:os";import{createHash as U$,randomUUID as F$}from"node:crypto";var Tc=1,Zv="Oracle local x402 budget. Armed for the owner-local signer. Pay requires an explicit instruction. Not Telegram A2A.",Wz=Object.freeze(["open","cancelled","armed","submitted"]),D$=/^(?:0|[1-9][0-9]*)$/,q$=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,H$=/^0x[a-fA-F0-9]{40}$/,j$=/^0x[a-fA-F0-9]{64}$/,z$=/[\u0000-\u001f\u007f]/,pm=class extends Error{constructor(t,n="LOCAL_X402_INVALID"){super(`local-x402: ${t}`),this.name="LocalX402Error",this.code=n}};function Q(e,t){throw new pm(e,t)}function Wi(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))Wi(t);Object.freeze(e)}return e}function Gi(e,t,{max:n=256}={}){typeof e!="string"&&Q(`${t} must be a string`);let r=e.trim();return(!r||r.length>n||z$.test(r))&&Q(`${t} is invalid`),r}function Zt(e,t){let n=Gi(e,t,{max:128});return q$.test(n)||Q(`${t} must be a bounded id`),n}function Cc(e,t,{positive:n=!1}={}){typeof e=="number"&&Q(`${t} must be an exact integer string`);let r=typeof e=="bigint"?e.toString():String(e??"");return D$.test(r)||Q(`${t} must be a canonical integer string`),n&&r==="0"&&Q(`${t} must be positive`),r}function cr(e,t){let n=Gi(e,t,{max:42}).toLowerCase();return H$.test(n)||Q(`${t} must be a 20-byte EVM address`),n}function V$(e){let t=Gi(e,"resource",{max:2048}),n;try{n=new URL(t)}catch{Q("resource must be an https URL")}return n.protocol!=="https:"&&Q("resource must be https"),(n.username||n.password)&&Q("resource must not contain credentials"),n.toString()}function ex(e,t){return(!e||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&Q(`${t} must be a plain object`),e}function W$(e){let t=e(),n=t instanceof Date?t.getTime():typeof t=="string"?Date.parse(t):Number(t);return(!Number.isSafeInteger(n)||n<0)&&Q("clock must return a safe integer millisecond timestamp","CLOCK_INVALID"),n}function G$(e){return new Date(e).toISOString()}function K$(e=process.env){let t=e.ORACLE_CONFIG_DIR||Qv.join(M$(),".config","oracle");return Qv.join(t,"local-x402.v1.json")}function um(e){let t=e.status==="submitted";return Wi({schemaVersion:Tc,intentId:e.intentId,tenantId:e.tenantId,payer:e.payer,payTo:e.payTo,resource:e.resource,amount:e.amount,maxBudget:e.maxBudget,asset:e.asset,chainId:e.chainId,status:e.status,createdAt:e.createdAt,intentHash:e.intentHash,transactionHash:e.transactionHash||null,label:Zv,custody:"none",execution:t?"local-signer-instructed":"armed-local",armed:!t,signed:t,broadcast:t,telegram:!1,pluginExecution:!1})}function Y$(e){(!e||e.schemaVersion!==Tc||!Array.isArray(e.intents))&&Q("invalid x402 snapshot","STORE_INVALID"),e.intents.length>1e4&&Q("x402 capacity exceeded","STORE_LIMIT")}function dm(e){return Wi({schemaVersion:Tc,recordType:"local-x402-armed",intentId:e.intentId,tenantId:e.tenantId,payer:e.payer,payTo:e.payTo,resource:e.resource,amount:e.amount,asset:e.asset,chainId:e.chainId,intentHash:e.intentHash,unsigned:{kind:"local-x402-pay",from:e.payer,to:e.payTo,amount:e.amount,asset:e.asset,chainId:e.chainId,resource:e.resource},review:`Oracle local x402 ${e.intentId} is armed: pay ${e.amount} ${e.asset} to ${e.payTo} for ${e.resource}. Sign and broadcast still require an explicit instruction.`,label:Zv,custody:"none",execution:"armed-local",armed:!0,signed:!1,broadcast:!1,requiresWalletSignature:!0,backendSigner:!1,refusesSignHash:!0,telegram:!1})}function J$(e,t){typeof e=="string"&&Q("raw hash artifacts are refused; pass a typed local-signer artifact","SIGNHASH_REFUSED");let n=ex(e,"instruction.artifact");(Object.prototype.hasOwnProperty.call(n,"signHash")||Object.prototype.hasOwnProperty.call(n,"hashToSign"))&&Q("generic signHash is refused","SIGNHASH_REFUSED");let r=cr(n.from??t.payer,"artifact.from"),o=cr(n.to??t.payTo,"artifact.to"),i=Cc(n.amount??t.amount,"artifact.amount",{positive:!0});r!==t.payer&&Q("artifact.from must match payer","ARTIFACT_MISMATCH"),o!==t.payTo&&Q("artifact.to must match payTo","ARTIFACT_MISMATCH"),i!==t.amount&&Q("artifact.amount must match the armed intent","ARTIFACT_MISMATCH");let a=BigInt(t.maxBudget);return BigInt(i)>a&&Q("amount exceeds maxBudget","BUDGET"),n}function X$(e,t){if(e==null)return{action:"arm"};let n=ex(e,"instruction");Object.prototype.hasOwnProperty.call(n,"signHash")&&n.signHash!==!1&&Q("generic signHash is refused","SIGNHASH_REFUSED");let r=Gi(n.action??"arm","instruction.action",{max:64});return r==="arm"?{action:"arm"}:(r==="prepare"&&Q("prepare is refused; arm the payment, then instruct sign-and-broadcast","INSTRUCTION_INVALID"),r!=="sign-and-broadcast"&&Q("instruction.action must be arm or sign-and-broadcast","INSTRUCTION_INVALID"),(n.confirm!==!0||n.sign!==!0||n.broadcast!==!0)&&Q("sign-and-broadcast requires confirm, sign, and broadcast all true","INSTRUCTION_INVALID"),n.intentHash&&n.intentHash!==t.intentHash&&Q("instruction.intentHash must match","ARTIFACT_MISMATCH"),n)}function tx({filePath:e=K$(),clock:t=()=>Date.now(),idFactory:n=()=>F$()}={}){let r=Kr({filePath:e,kind:"oracle-local-x402",clock:t,maxBytes:4194304,initialData:()=>({schemaVersion:Tc,intents:[]}),validateData:Y$});function o(l={}){Qt(l);let u=Zt(l.tenantId,"tenantId"),d=cr(l.payer,"payer"),p=cr(l.payTo,"payTo"),m=V$(l.resource),f=Cc(l.amount,"amount",{positive:!0}),h=Cc(l.maxBudget??f,"maxBudget",{positive:!0});BigInt(f)>BigInt(h)&&Q("amount exceeds maxBudget","BUDGET");let g=Gi(l.asset??"USDC","asset",{max:32}),w=Cc(l.chainId,"chainId",{positive:!0}),x=W$(t),b=Zt(String(l.intentId??`x402-${n()}`),"intentId");return r.mutate(y=>{y.intents.some(I=>I.intentId===b)&&Q("intentId already exists","DUPLICATE");let k={intentId:b,tenantId:u,payer:d,payTo:p,resource:m,amount:f,maxBudget:h,asset:g,chainId:w,status:"open",createdAt:G$(x),custody:"none",execution:"armed-local"},E={...k,intentHash:U$("sha256").update(_n(k),"utf8").digest("hex")};return y.intents.push(E),um(E)})}function i({tenantId:l}={}){let u=Zt(l,"tenantId");return Wi(r.read().intents.filter(d=>d.tenantId===u).map(um))}function a({tenantId:l,intentId:u,actor:d}={}){let p=Zt(l,"tenantId"),m=Zt(u,"intentId"),f=cr(d,"actor");return r.mutate(h=>{let g=h.intents.find(w=>w.tenantId===p&&w.intentId===m);return g||Q("intent not found","NOT_FOUND"),g.payer!==f&&Q("only the payer can cancel","FORBIDDEN"),g.status!=="open"&&Q("intent is not open","NOT_OPEN"),g.status="cancelled",um(g)})}function s({tenantId:l,intentId:u,actor:d}={}){let p=Zt(l,"tenantId"),m=Zt(u,"intentId"),f=cr(d,"actor");return r.mutate(h=>{let g=h.intents.find(w=>w.tenantId===p&&w.intentId===m);return g||Q("intent not found","NOT_FOUND"),g.payer!==f&&Q("only the payer can arm","FORBIDDEN"),["open","armed"].includes(g.status)||Q("intent is not open","NOT_OPEN"),g.status="armed",dm(g)})}async function c({tenantId:l,intentId:u,actor:d,instruction:p,executor:m}={}){let f=Zt(l,"tenantId"),h=Zt(u,"intentId"),g=cr(d,"actor"),w=r.mutate(I=>{let v=I.intents.find(P=>P.tenantId===f&&P.intentId===h);v||Q("intent not found","NOT_FOUND"),v.payer!==g&&Q("only the payer can instruct pay","FORBIDDEN"),["open","armed"].includes(v.status)||Q("intent is not open","NOT_OPEN");let A=X$(p,v);return v.status="armed",{armed:dm(v),instruction:A}});if(w.instruction.action==="arm")return w.armed;let x=r.read().intents.find(I=>I.tenantId===f&&I.intentId===h),b=J$(w.instruction.artifact,x);(!m||typeof m.executeConfirmedArtifact!="function")&&Q("sign-and-broadcast requires an injected local-signer executor","EXECUTOR_REQUIRED"),typeof m.signHash=="function"&&Q("generic signHash executors are refused","SIGNHASH_REFUSED");let y=await m.executeConfirmedArtifact(b,w.instruction.nonce,m),k=y?.receipt?.transactionHash??y?.transactionHash;(typeof k!="string"||!j$.test(k))&&Q("local-signer receipt must include a 32-byte transaction hash","RECEIPT_INVALID");let E=y?.receipt?.status??y?.status;return E!==1&&E!=="0x1"&&Q("local-signer broadcast did not return a successful receipt","RECEIPT_INVALID"),r.mutate(I=>{let v=I.intents.find(A=>A.tenantId===f&&A.intentId===h);return(!v||v.status!=="armed")&&Q("intent is not armed","NOT_OPEN"),v.status="submitted",v.transactionHash=k.toLowerCase(),Wi({...dm(v),recordType:"local-x402-submitted",execution:"local-signer-instructed",armed:!1,signed:!0,broadcast:!0,backendSigner:!0,requiresWalletSignature:!1,transactionHash:v.transactionHash,review:`Oracle local x402 ${v.intentId} signed and broadcast. transactionHash=${v.transactionHash}`})})}return Object.freeze({createIntent:o,listIntents:i,cancelIntent:a,armPayment:s,instructPay:c})}import nx from"node:path";import{homedir as Q$}from"node:os";import{randomUUID as Z$}from"node:crypto";var hm=1,eB="Oracle local pack registry. Catalog only. Packs are never executed. Not Telegram A2A.",tV=Object.freeze(["listed","revoked"]),tB=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,nB=/[\u0000-\u001f\u007f]/,rB=/^[a-f0-9]{64}$/,oB=/^(?:localhost|(?:\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}|(?:\d{1,3}\.){3}\d{1,3})$/i,iB=new Set(["read","prepare","none"]),fm=class extends Error{constructor(t,n="LOCAL_PACK_INVALID"){super(`local-pack-registry: ${t}`),this.name="LocalPackRegistryError",this.code=n}};function Pe(e,t){throw new fm(e,t)}function gm(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){for(let t of Object.values(e))gm(t);Object.freeze(e)}return e}function Pn(e,t,{max:n=256}={}){typeof e!="string"&&Pe(`${t} must be a string`);let r=e.trim();return(!r||r.length>n||nB.test(r))&&Pe(`${t} is invalid`),r}function Ki(e,t){let n=Pn(e,t,{max:128});return tB.test(n)||Pe(`${t} must be a bounded id`),n}function rx(e,t){let n=Pn(e,t,{max:64}).toLowerCase();return rB.test(n)||Pe(`${t} must be 64 lowercase hex`),n}function aB(e,t){let n=Pn(e,t,{max:2048}),r;try{r=new URL(n)}catch{Pe(`${t} must be an https URL`)}return r.protocol!=="https:"&&Pe(`${t} must be https`),(r.username||r.password)&&Pe(`${t} must not contain credentials`),r.toString()}function sB(e){return e==null?[]:((!Array.isArray(e)||e.length>16)&&Pe("outboundHosts must be a bounded array"),e.map((t,n)=>{let r=Pn(t,`outboundHosts[${n}]`,{max:253}).toLowerCase();return(!oB.test(r)||r==="0.0.0.0")&&Pe(`outboundHosts[${n}] is not an allowlisted host`),r}))}function ox(e){let t=e(),n=t instanceof Date?t.getTime():typeof t=="string"?Date.parse(t):Number(t);return(!Number.isSafeInteger(n)||n<0)&&Pe("clock invalid","CLOCK_INVALID"),n}function ix(e){return new Date(e).toISOString()}function cB(e=process.env){let t=e.ORACLE_CONFIG_DIR||nx.join(Q$(),".config","oracle");return nx.join(t,"local-pack-registry.v1.json")}function mm(e){return gm({schemaVersion:hm,packId:e.packId,tenantId:e.tenantId,name:e.name,version:e.version,publisher:e.publisher,manifestDigest:e.manifestDigest,sbomDigest:e.sbomDigest,homepage:e.homepage,outboundHosts:e.outboundHosts,spendScope:e.spendScope,status:e.status,createdAt:e.createdAt,revokedAt:e.revokedAt,label:eB,custody:"none",execution:"none",pluginExecution:!1,loaded:!1,spawned:!1,telegram:!1})}function lB(e){(!e||e.schemaVersion!==hm||!Array.isArray(e.packs))&&Pe("invalid pack registry snapshot","STORE_INVALID"),e.packs.length>1e3&&Pe("pack registry capacity exceeded","STORE_LIMIT")}function ax({filePath:e=cB(),clock:t=()=>Date.now(),idFactory:n=()=>Z$()}={}){let r=Kr({filePath:e,kind:"oracle-local-pack-registry",clock:t,maxBytes:2097152,initialData:()=>({schemaVersion:hm,packs:[]}),validateData:lB});function o(l={}){Qt(l);let u=Ki(l.tenantId,"tenantId"),d=Pn(l.name,"name",{max:128}),p=Pn(l.version,"version",{max:64}),m=Pn(l.publisher,"publisher",{max:128}),f=rx(l.manifestDigest,"manifestDigest"),h=l.sbomDigest==null?null:rx(l.sbomDigest,"sbomDigest"),g=l.homepage==null?null:aB(l.homepage,"homepage"),w=sB(l.outboundHosts),x=Pn(l.spendScope??"none","spendScope",{max:16});iB.has(x)||Pe("spendScope must be read, prepare, or none"),x!=="none"&&x!=="read"&&Pe("write/spend pack scopes are refused; registry is catalog-only","SCOPE_REFUSED");let b=ox(t),y=Ki(String(l.packId??`pack-${n()}`),"packId");return r.mutate(k=>{k.packs.some(I=>I.packId===y||I.tenantId===u&&I.name===d&&I.version===p&&I.status==="listed")&&Pe("pack already listed","DUPLICATE");let E={packId:y,tenantId:u,name:d,version:p,publisher:m,manifestDigest:f,sbomDigest:h,homepage:g,outboundHosts:w,spendScope:x,status:"listed",createdAt:ix(b),revokedAt:null,execution:"none",pluginExecution:!1};return k.packs.push(E),mm(E)})}function i({tenantId:l}={}){let u=Ki(l,"tenantId");return gm(r.read().packs.filter(d=>d.tenantId===u).map(mm))}function a({tenantId:l,packId:u}={}){let d=Ki(l,"tenantId"),p=Ki(u,"packId"),m=ox(t);return r.mutate(f=>{let h=f.packs.find(g=>g.tenantId===d&&g.packId===p);return h||Pe("pack not found","NOT_FOUND"),h.status!=="listed"&&Pe("pack is not listed","NOT_OPEN"),h.status="revoked",h.revokedAt=ix(m),mm(h)})}function s(){Pe("pack execution is refused; this registry is catalog-only","EXECUTION_REFUSED")}function c(){Pe("pack execution is refused; this registry is catalog-only","EXECUTION_REFUSED")}return Object.freeze({registerPack:o,listPacks:i,revokePack:a,loadPack:s,executePack:c})}R();import{getAddress as gB,Interface as Jr,keccak256 as wm}from"ethers";import{createHash as vm,createHmac as yB,timingSafeEqual as xx}from"node:crypto";Cr();pe();import{Interface as lx,getAddress as ym,isAddress as uB}from"ethers";var dB="0x0000000000000000000000000000000000000000",ux=Object.freeze({4663:Object.freeze({name:"robinhood",factory:"0x1ac9dB4a2608ba45D6127B1737949b51Bb54B7F3",quoter:"0x03983AB2C057a2eac211ff01738a1e49ff325B49",router:"0xC062b870E813fcA720f1e002c234369Ab3aB9415",weth:"0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73"})}),pB=new lx(["function getPool(address tokenA,address tokenB,int24 tickSpacing) view returns (address pool)"]),mB=new lx(["function quoteExactInputSingle((address tokenIn,address tokenOut,uint256 amountIn,int24 tickSpacing,uint160 sqrtPriceLimitX96) params) returns (uint256 amountOut,uint160 sqrtPriceX96After,uint32 initializedTicksCrossed,uint256 gasEstimate)","function quoteExactOutputSingle((address tokenIn,address tokenOut,uint256 amount,int24 tickSpacing,uint160 sqrtPriceLimitX96) params) returns (uint256 amountIn,uint160 sqrtPriceX96After,uint32 initializedTicksCrossed,uint256 gasEstimate)"]);function fB(e){let t=Number(e??4663),n=ux[t];if(!n)throw new Error(`up33: unsupported chainId ${e}`);return{chainId:t,...n}}function sx(e,t){if(/^weth$/i.test(String(e||"")))return ym(ux[t].weth);if(!uB(String(e||"")))throw new Error(`up33: invalid token ${e}`);return ym(e)}function hB(e,t){let n=BigInt(e??0);if(n<=0n)throw new Error(`up33: ${t} must be positive`);return n}async function cx(e,t,n,r,o,i){let a=r.encodeFunctionData(o,i),s=await e(t,"eth_call",[{to:n,data:a},"latest"]);if(!s||s==="0x")throw new Error(`up33: empty ${o} result`);return r.decodeFunctionResult(o,s)}async function dx(e,t={},n={}){try{let r=fB(t.chainId),o=sx(t.tokenIn,r.chainId),i=sx(t.tokenOut,r.chainId);if(o.toLowerCase()===i.toLowerCase())throw new Error("up33: tokens must differ");let a=hB(e==="exact-input"?t.amountIn:t.amountOut,e==="exact-input"?"amountIn":"amountOut"),s=Number(t.tickSpacing??2e3);if(!Number.isInteger(s)||s<=0)throw new Error("up33: invalid tickSpacing");let c=n.rpcCall||D,l=await cx(c,r.chainId,r.factory,pB,"getPool",[o,i,s]),u=ym(l[0]);if(u.toLowerCase()===dB)throw new Error("up33: exact pool unavailable");let d=e==="exact-input"?"quoteExactInputSingle":"quoteExactOutputSingle",p=e==="exact-input"?{tokenIn:o,tokenOut:i,amountIn:a,tickSpacing:s,sqrtPriceLimitX96:0n}:{tokenIn:o,tokenOut:i,amount:a,tickSpacing:s,sqrtPriceLimitX96:0n},m=await cx(c,r.chainId,r.quoter,mB,d,[p]),f={provider:"up33",venue:"up33-v3",chainId:r.chainId,chain:r.name,factory:r.factory,quoter:r.quoter,router:r.router,pool:u.toLowerCase(),tokenIn:o.toLowerCase(),tokenOut:i.toLowerCase(),tickSpacing:s,sqrtPriceX96After:m[1].toString(),initializedTicksCrossed:Number(m[2]),gasEstimate:m[3].toString(),executionReady:!1,preparable:!1,readOnly:!0};return e==="exact-input"?{...f,amountIn:a.toString(),amountOut:m[0].toString()}:{...f,amountIn:m[0].toString(),amountOut:a.toString()}}catch(r){return{error:String(r.message||r).slice(0,200)}}}async function px(e={},t={}){return dx("exact-input",e,t)}async function mx(e={},t={}){return dx("exact-output",e,t)}Y();var W=4663,Nc="https://anvil.clutch.market",bB=`${Nc}/api/markets/snapshot?chainId=${W}`,wB=`${Nc}/api/rpc?chainId=${W}`,vB=new Set(["eth_call","eth_chainId","eth_blockNumber","eth_getBlockByNumber","eth_getCode"]),ot="0x0bd7d308f8e1639fab988df18a8011f41eacad73",xm="0x0000000000000000000000000000000000000000",lr=1e5,xB=256e3,fx=256,kB=3e4,SB=Object.freeze({"0x25482a6e453646f518c6194def85b0d477134f27":"0xdb1cb50fd93395644993895a2d1ee784973287453c16b1aa92716284fd265265","0x2554cad3d851381ec1a16b7bf7b4737ed46b40fe":"0x3a7563ef4a79e56aeab6e11b3fea2e319964a962379cb31beeedc4eaadf87cc1","0xd9206764cbc81c326ee6cace76c80089f6a0b360":"0x93cee896d680d2a0fb068413f39cf5b684dd70799dd9379f9ec35a2492d28b75","0x4e07aa3e0228cfe099462bc25f4789adb6038451":"0x04078324b6c9b861b6b59308c9327d73250992e1dd76546feccdf18e5e4d5fbc","0x714a07a5accc26a2799c50f3781612b4675129a1":"0x83ef76324d1c19aa59c76e5376814c0ed1071354d0c850110a94e91f35b4db28","0xfe0b24a3b4052ad78f10fa75a27118c3e54a00e6":"0x965e384f236132ec25d88662665408e49a443014a7fc58af92c03833df957f2f","0x2079c001b1a1e1be53b7463387510ddac2b45da2":"0x6c9c976c7cbd34e17e14189ccd487be9b541107885b86e28aa7ef1a033b7bb9f","0x147ef077bfbe4bbec3f267c358073c449cbb4b32":"0x5064f645f51ece3be2e5a6624c9cc6d508ba1544fef45455bbc7a906d07e6a4f","0xe6fa04e189ea271f0311162afc839443c51fe920":"0x467b919a9109c34d63ce40f8fcb4c9f33bccb45e7f6a027685a22228882553e1","0x492d80f0009cd250ceabcfcfb1c5c1de40f98ef6":"0x5da29cfd5f8f686998564a8ef0b89156c9f75d381c80ee5886b617385346e928","0x5bdf7bd9b20bb7c50061e4f4748725cd341d1f45":"0x94c052d894b557ac5b20295d74ee82c2a34b127cf148ba93e7596dc0cab549eb","0xdd59536f394c4b589e695f5921723b89ea479379":"0xa2c5533b1f8a41d863fa787dec42e51d57d8d77343555e5b0a9ce18fb51361ef","0xf29aa29804033d5fc9a16ad6f864e495d950acb4":"0xec8d77482cbd2f550345d67fc7f0f317e349ffd148a06b05237c9efb82b61900","0x26c41f7c732cf27b9c687f88ae4c9dbfed4f9ac4":"0xce7a9041ec2808643506b6327fed3d46b07dca344ff7b32e110d28a8fe6c712a","0x6109ed398827f06ba2ccd763a597ae2e0586b349":"0x625695c20dccfca1c2db898d09b4f56bde23b6ae0b9d76adc05573d280f320b0","0x95aa9e2130016e7ffe8828a4e1e2047441704cfd":"0xded628a34f602a70f5dc4d34974a2107ad5539be3428a34083aeddce8b2f46c4"}),ft=Object.freeze({chainId:W,nft:"0x539cdd042c2f3d93ebc5be7dfff0c79f3b4fabf0",token:"0xe934e36a439c94017b64a3fece66af12099abf50",activationManager:"0xacd5ae3c060c1137fe2ee86b0ab2ef697456f664",stockBooster:"0x038a7f4e4e89448ad74e044337c9ac25c11e726b",overtimeBooster:"0xf9ca5f6d8622c82758914681a12674e2d489259a",ammVault:"0xe302733accf4800146e55fc45b46b4e4ffc032d2",loanVault:"0xa7b9ac696b252b79568a5a01b2fd02177ef23664",registry:"0x28c154cbdeaecbf5f72b6ae48535ab9a431a4161",accountImpl:"0xe946075125843aadb5e40e59f513d929af507c4b",slug:"stonkbrokers-434284142"}),Me=new Jr(["function quoteSpecificBuy(uint256 tokenId) view returns (uint256 totalCost,uint256 baseCost,uint256 fee,uint256 protocolFee,bool available)","function quoteSellNFT() view returns (uint256 netPayout,uint256 grossPayout,uint256 fee,uint256 protocolFee)","function inventory(uint256 tokenId) view returns (bool)","function inventoryLength() view returns (uint256)","function oldestTokenId() view returns (uint256)","function getNextTokenId(uint256 tokenId) view returns (uint256)","function collection() view returns (address)","function token() view returns (address)","function robinhoodSwapFeeWei() view returns (uint256)","function buySpecificNFT(uint256 tokenId,uint256 maxCost) payable","function sellNFT(uint256 tokenId,uint256 minPayout) payable"]),IB=new Jr(["function allowance(address owner,address spender) view returns (uint256)"]),kx=new Jr(["function decimals() view returns (uint8)"]),hx=new Jr(["function quoteSpecificBuy(uint256 tokenId) view returns (uint256 tokenCost,uint256 ethFee,bool available)","function inventory(uint256 tokenId) view returns (bool)"]),ht=new Jr(["function ownerOf(uint256 tokenId) view returns (address)","function getApproved(uint256 tokenId) view returns (address)","function isApprovedForAll(address owner,address operator) view returns (bool)","function tokenURI(uint256 tokenId) view returns (string)","function rarityOf(uint256 tokenId) view returns (uint8)","function tokenWallet(uint256 tokenId) view returns (address)","function predictWallet(uint256 tokenId) view returns (address)"]),Cn=new Jr(["function pendingEth() view returns (uint256)","function minDropWei() view returns (uint256)","function roundActive() view returns (bool)","function currentRound() view returns (uint256)","function roundState() view returns (uint256 roundId,bool active,uint256 cursor,uint256 remaining,uint256[3] amounts,uint256[3] paid)","function getStockTokens() view returns (address[3])","function startDropPublic(uint256 minOutBps)","function continueDrop(uint256 batchSize)"]);function j(e,t){try{return gB(String(e||"").trim().toLowerCase()).toLowerCase()}catch{throw new Error(`stonkbrokers: invalid ${t}`)}}function tn(e,t="tokenId"){let n=String(e??"").trim();if(!/^\d+$/.test(n))throw new Error(`stonkbrokers: ${t} must be an unsigned integer`);return n}function it(e,t,n=null){let r=e==null&&n!=null?n:e,o=String(r??"").trim();if(!/^\d+$/.test(o))throw new Error(`stonkbrokers: ${t} must be an unsigned integer`);return BigInt(o)}async function te(e,t,n,r,o=[],i="latest"){let a=n.encodeFunctionData(r,o),s=await e(W,"eth_call",[{to:j(t,"contract"),data:a},i]);return n.decodeFunctionResult(r,s)}function Sx(e,t){let n=BigInt(e).toString(),r=BigInt(t).toString(),o=(BigInt(e)+BigInt(t)).toString();return{anvilFeeRaw:n,protocolFeeRaw:r,totalFeeRaw:o}}function gx(e={}){let t;if(Array.isArray(e))t=e;else if(e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.data))t=e.data;else if(e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.markets))t=e.markets;else throw new Error("stonkbrokers: Anvil snapshot shape requires a data array");if(t.length>fx)throw new Error(`stonkbrokers: Anvil snapshot row limit is ${fx}`);return t.map(n=>{if(!n||typeof n!="object"||Array.isArray(n))throw new Error("stonkbrokers: Anvil snapshot rows must be objects");if(Number(n.chainId)!==W)throw new Error(`stonkbrokers: Anvil snapshot rows must use chain ${W}`);return{name:n.name||n.collectionName||null,chainId:W,collection:j(n.collection||n.collectionAddress,"Anvil collection"),market:j(n.address||n.market||n.ammVaultAddress,"Anvil market"),tokenAddress:n.tokenAddress?j(n.tokenAddress,"Anvil payment token"):null,floorPrice:n.floorPrice??null,buyPrice:n.buyPrice??null,tokensPerNFT:n.tokensPerNFT??null,inventoryCount:Number(n.inventoryCount??n.inventoryLength??0),specificFeeBps:Number(n.specificFeeBps??0),source:"anvil-snapshot"}})}async function EB(e,t,n=[],r={}){if(Number(e)!==W)throw new Error(`stonkbrokers: Anvil supports chain ${W} only`);if(!vB.has(String(t)))throw new Error("stonkbrokers: Anvil RPC proxy is read-only");let o=await S(wB,{method:"POST",headers:{origin:Nc,referer:`${Nc}/`,"user-agent":"Mozilla/5.0"},body:{jsonrpc:"2.0",id:1,method:t,params:n},fetchImpl:r.fetchImpl,timeoutMs:r.timeoutMs??2e4,retries:0});if(o?.error)throw new Error(`stonkbrokers: Anvil RPC ${o.error.message||"failed"}`);if(o?.result==null)throw new Error("stonkbrokers: Anvil RPC returned no result");return o.result}function It(e={}){return e.rpcCall||((t,n,r)=>EB(t,n,r,e))}async function Xr(e={},t={}){if(e.snapshot){let s=gx(e.snapshot),c={kind:"anvil-markets",chainId:W,total:s.length,contentHash:vm("sha256").update(Yr(s)).digest("hex")},l=km(e.snapshotCompletenessEvidence,c,Number(t.nowMs??Date.now()),t.completenessEvidenceSecret||t.gasEvidenceSecret||process.env.ORACLE_ROUTE_ATTESTATION_SECRET);return Object.defineProperty(s,"snapshotCoverage",{value:{complete:l.valid,evidence:l.evidence,error:l.error},enumerable:!1}),s}let n=s=>{let c=String(s?.headers?.get?.("content-type")||"").split(";",1)[0].trim().toLowerCase();if(c!=="application/json"&&!c.endsWith("+json"))throw new Error("stonkbrokers: Anvil snapshot content-type must be JSON")},r=await S(bB,{...t.fetchImpl?{fetchImpl:t.fetchImpl}:{},...t.lookupFn?{lookupFn:t.lookupFn}:{},...t.importUndici?{importUndici:t.importUndici}:{},untrustedUrl:!0,validateResponse:n,timeoutMs:t.timeoutMs??2e4,maxResponseBytes:xB,retries:0});if(!r||typeof r!="object"||Array.isArray(r)||!Array.isArray(r.data))throw new Error("stonkbrokers: Anvil snapshot must be a JSON object with a data array");let o=gx(r),i={kind:"anvil-markets",chainId:W,total:o.length,contentHash:vm("sha256").update(Yr(o)).digest("hex")},a=km(e.snapshotCompletenessEvidence??r.completenessEvidence,i,Number(t.nowMs??Date.now()),t.completenessEvidenceSecret||t.gasEvidenceSecret||process.env.ORACLE_ROUTE_ATTESTATION_SECRET);return Object.defineProperty(o,"snapshotCoverage",{value:{complete:a.valid,evidence:a.evidence,error:a.error},enumerable:!1}),o}function Oc(e){let t=String(e||"").toLowerCase();if(!/^0x(?:0|[1-9a-f][0-9a-f]*)$/.test(t))throw new Error("stonkbrokers: Anvil RPC returned an invalid block number");return t}async function Ix({market:e,collection:t},n={}){let r=Number(n.nowMs??Date.now());if(!Number.isFinite(r))throw new Error("stonkbrokers: opts.nowMs must be finite");let i=(await Xr({},n)).find(f=>f.market===e);if(!i)throw new Error("stonkbrokers: market is missing from the trusted Anvil snapshot");if(i.collection!==t)throw new Error("stonkbrokers: trusted Anvil snapshot collection mismatch");if(!i.tokenAddress)throw new Error("stonkbrokers: trusted Anvil snapshot payment token is missing");let a=SB[e];if(!a)throw new Error("stonkbrokers: Anvil market has no reviewed runtime identity");let s=It(n),c=Oc(await s(W,"eth_blockNumber",[])),l=await s(W,"eth_getBlockByNumber",[c,!1]),u=String(l?.hash||"").toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(u)||Oc(l?.number)!==c)throw new Error("stonkbrokers: Anvil RPC returned an invalid block attestation");let d=Object.freeze({blockHash:u,requireCanonical:!0}),p=String(await s(W,"eth_getCode",[e,d])).toLowerCase();if(!/^0x[0-9a-f]+$/.test(p)||p==="0x")throw new Error("stonkbrokers: Anvil market runtime is empty");let m=wm(p).toLowerCase();if(m!==a)throw new Error("stonkbrokers: Anvil market runtime identity is not reviewed");return{rpc:s,record:i,blockNumber:c,blockHash:u,blockRef:d,runtimeCodeHash:m,snapshotFetchedAtMs:r,snapshotExpiresAtMs:r+kB}}function Ex(e,{paymentToken:t,paymentTokenDecimals:n,nativeSwapFeeWei:r}){return Object.freeze({version:1,source:"anvil-snapshot-rpc-reviewed-runtime",chainId:W,market:e.record.market,collection:e.record.collection,paymentToken:t,paymentTokenDecimals:n,nativeSwapFeeWei:r,snapshotFetchedAtMs:e.snapshotFetchedAtMs,snapshotExpiresAtMs:e.snapshotExpiresAtMs,blockNumber:BigInt(e.blockNumber).toString(),blockHash:e.blockHash,runtimeCodeHash:e.runtimeCodeHash})}async function Ji(e={},t={}){let n=j(e.market,"Anvil market"),r=j(e.collection,"NFT collection"),o=tn(e.tokenId),i=await Ix({market:n,collection:r},t),{rpc:a,blockRef:s}=i,[c,l,u,d,p,m]=await Promise.all([te(a,n,Me,"quoteSpecificBuy",[BigInt(o)],s),te(a,n,Me,"inventory",[BigInt(o)],s),te(a,r,ht,"ownerOf",[BigInt(o)],s),te(a,n,Me,"collection",[],s),te(a,n,Me,"token",[],s),te(a,n,Me,"robinhoodSwapFeeWei",[],s)]),f=j(d[0],"Anvil market collection");if(f!==r)throw new Error("stonkbrokers: Anvil market collection mismatch");let h=j(p[0],"Anvil payment token");if(h!==i.record.tokenAddress)throw new Error("stonkbrokers: Anvil snapshot payment token mismatch");let g=Number((await te(a,h,kx,"decimals",[],s))[0]);if(!Number.isSafeInteger(g)||g<0||g>255)throw new Error("stonkbrokers: invalid payment token decimals");let w=BigInt(m[0]).toString(),x=Ex(i,{paymentToken:h,paymentTokenDecimals:g,nativeSwapFeeWei:w}),b=!!c[4],y=!!l[0],k=j(u[0],"NFT owner")===n,E=b&&y&&k;return{provider:"stonkbrokers",source:"anvil-exact-buy-quote",chainId:W,market:n,collection:r,tokenId:o,paymentToken:h,paymentTokenDecimals:g,amountUnits:"payment-token-raw",totalCostRaw:BigInt(c[0]).toString(),baseCostRaw:BigInt(c[1]).toString(),nativeSwapFeeWei:w,fees:Sx(c[2],c[3]),available:E,evidence:{quoteAvailable:b,inventory:y,ownerIsMarket:k,marketCollection:f,attestation:x},reason:E?null:"nft-not-provably-in-anvil-inventory",exec:!1,readOnly:!0}}async function Rc(e={},t={}){let n=j(e.market,"Anvil market"),r=j(e.collection,"NFT collection"),o=await Ix({market:n,collection:r},t),{rpc:i,blockRef:a}=o,[s,c,l,u]=await Promise.all([te(i,n,Me,"quoteSellNFT",[],a),te(i,n,Me,"collection",[],a),te(i,n,Me,"token",[],a),te(i,n,Me,"robinhoodSwapFeeWei",[],a)]),d=j(c[0],"Anvil market collection");if(d!==r)throw new Error("stonkbrokers: Anvil market collection mismatch");let p=j(l[0],"Anvil payment token");if(p!==o.record.tokenAddress)throw new Error("stonkbrokers: Anvil snapshot payment token mismatch");let m=Number((await te(i,p,kx,"decimals",[],a))[0]);if(!Number.isSafeInteger(m)||m<0||m>255)throw new Error("stonkbrokers: invalid payment token decimals");let f=BigInt(u[0]).toString(),h=Ex(o,{paymentToken:p,paymentTokenDecimals:m,nativeSwapFeeWei:f});return{provider:"stonkbrokers",source:"anvil-sell-quote",chainId:W,market:n,collection:r,paymentToken:p,paymentTokenDecimals:m,amountUnits:"payment-token-raw",netPayoutRaw:BigInt(s[0]).toString(),grossPayoutRaw:BigInt(s[1]).toString(),nativeSwapFeeWei:f,fees:Sx(s[2],s[3]),evidence:{marketCollection:d,attestation:h},exec:!1,readOnly:!0}}function Ax(e){let t=String(e||"").trim();if(!/^[A-Za-z0-9._:-]{1,128}$/.test(t))throw new Error("stonkbrokers: bounded tradeId required");return t}function en(e,t){let n=it(e,t);if(n<=0n)throw new Error(`stonkbrokers: ${t} must be positive`);return n}function _x({from:e,to:t,data:n,value:r,gasLimit:o,maxFeePerGas:i,maxPriorityFeePerGas:a,nonce:s}){let c={chainId:W,from:e,to:t,data:n,value:BigInt(r).toString(),gasLimit:en(o,"gasLimit").toString(),maxFeePerGas:en(i,"maxFeePerGasWei").toString(),nonce:Number(s),type:2};if(!Number.isSafeInteger(c.nonce)||c.nonce<0)throw new Error("stonkbrokers: explicit non-negative nonce required");return a!=null&&a!==""&&(c.maxPriorityFeePerGas=en(a,"maxPriorityFeePerGasWei").toString()),c}function Px(e,t){return N({provider:"anvil-nft",kind:"anvil-nft-execution",execution:"armed-local",armed:!1,signing:"local-signer",broadcasting:"local-signer",signed:"pending-local-signer",broadcast:"pending-local-signer",simulation:"required-again-at-local-signer",localSignerEnvelope:e,quote:t},{provider:"anvil-nft",kind:"anvil-nft-execution"})}async function Cx(e={},t={}){if(e.userConfirmed!==!0)throw new Error("stonkbrokers: userConfirmed=true required");let n=j(e.buyer,"buyer"),r=j(e.market,"Anvil market"),o=j(e.collection,"NFT collection"),i=tn(e.tokenId),a=en(e.maxTotalCostRaw,"maxTotalCostRaw"),s=it(e.maxNativeSwapFeeWei,"maxNativeSwapFeeWei"),c=Number(e.actionNonce);if(!Number.isSafeInteger(c)||c<0)throw new Error("stonkbrokers: explicit non-negative actionNonce required");let l=await Ji({market:r,collection:o,tokenId:i},t);if(!l.available)throw new Error("stonkbrokers: NFT is not provably available");if(BigInt(l.totalCostRaw)>a||BigInt(l.nativeSwapFeeWei)>s)throw new Error("stonkbrokers: live quote exceeds reviewed cap");let u=BigInt(l.totalCostRaw),d=en(e.confirmedTotalCostRaw,"confirmedTotalCostRaw");if(d!==u)throw new Error("stonkbrokers: confirmed buy economics do not match the exact fresh quote");let p=Number(t.nowMs??Date.now()),m=Math.min(6e4,Math.max(1e3,Number(e.ttlMs??3e4)||3e4)),f=j(l.paymentToken,"Anvil payment token"),h=Number(l.paymentTokenDecimals),g=l.evidence.attestation,w={blockHash:g.blockHash,requireCanonical:!0},x=BigInt((await te(It(t),f,IB,"allowance",[n,r],w))[0]);if(x<u)throw new Error("stonkbrokers: pre-existing payment-token allowance is insufficient");let b={from:n,maxFeePerGas:e.maxFeePerGasWei,maxPriorityFeePerGas:e.maxPriorityFeePerGasWei},y=[_x({...b,to:r,data:Me.encodeFunctionData("buySpecificNFT",[BigInt(i),u]),value:l.nativeSwapFeeWei,gasLimit:e.actionGasLimit,nonce:c})],k={totalCostRaw:l.totalCostRaw,baseCostRaw:l.baseCostRaw,feeRaw:l.fees.anvilFeeRaw,protocolFeeRaw:l.fees.protocolFeeRaw,available:l.available},E={version:1,surface:"evm-nft",action:"nft",nftAction:"buy",provider:"anvil-nft",owner:n,destination:r,contract:o,tokenId:i,paymentToken:f,paymentTokenDecimals:h,nativeSwapFeeWei:l.nativeSwapFeeWei,exactQuoteTotalCostRaw:u.toString(),maxPaymentTokenAmountRaw:u.toString(),marketCollection:l.evidence.marketCollection,anvilAttestation:g,anvilQuote:k,preconditions:{allowanceVerified:!0,allowanceRaw:x.toString(),exactQuoteConfirmed:!0,confirmedTotalCostRaw:d.toString()},tradeId:Ax(e.tradeId),slippageBps:0,expiresAtMs:p+m,fee:{oracleFeeBps:0},artifact:{chainId:W,owner:n,contract:o,marketCollection:l.evidence.marketCollection,tokenId:i,paymentToken:f,paymentTokenDecimals:h,nativeSwapFeeWei:l.nativeSwapFeeWei,anvilAttestation:g,anvilQuote:k,exactQuoteTotalCostRaw:u.toString(),maxPaymentTokenAmountRaw:u.toString(),transactions:y}};return Px(E,l)}async function Tx(e={},t={}){if(e.userConfirmed!==!0)throw new Error("stonkbrokers: userConfirmed=true required");let n=It(t),r=j(e.seller,"seller"),o=j(e.market,"Anvil market"),i=j(e.collection,"NFT collection"),a=tn(e.tokenId),s=en(e.minPayoutRaw,"minPayoutRaw"),c=it(e.maxNativeSwapFeeWei,"maxNativeSwapFeeWei"),l=Number(e.actionNonce);if(!Number.isSafeInteger(l)||l<0)throw new Error("stonkbrokers: explicit non-negative actionNonce required");let u=await Rc({market:o,collection:i},t),d=u.evidence.attestation,p={blockHash:d.blockHash,requireCanonical:!0},[m,f,h]=await Promise.all([te(n,i,ht,"ownerOf",[BigInt(a)],p).then(P=>j(P[0],"NFT owner")),te(n,i,ht,"getApproved",[BigInt(a)],p).then(P=>j(P[0],"NFT approval")),te(n,i,ht,"isApprovedForAll",[r,o],p).then(P=>!!P[0])]);if(m!==r)throw new Error("stonkbrokers: seller does not own exact NFT");if(f!==o&&!h)throw new Error("stonkbrokers: pre-existing NFT approval is required");if(BigInt(u.netPayoutRaw)<s||BigInt(u.nativeSwapFeeWei)>c)throw new Error("stonkbrokers: live quote violates reviewed limit");let g=BigInt(u.netPayoutRaw),w=en(e.confirmedNetPayoutRaw,"confirmedNetPayoutRaw");if(w!==g)throw new Error("stonkbrokers: confirmed sell economics do not match the exact fresh quote");let x=Number(t.nowMs??Date.now()),b=Math.min(6e4,Math.max(1e3,Number(e.ttlMs??3e4)||3e4)),y=j(u.paymentToken,"Anvil payment token"),k=Number(u.paymentTokenDecimals),E={from:r,maxFeePerGas:e.maxFeePerGasWei,maxPriorityFeePerGas:e.maxPriorityFeePerGasWei},I=[_x({...E,to:o,data:Me.encodeFunctionData("sellNFT",[BigInt(a),g]),value:u.nativeSwapFeeWei,gasLimit:e.actionGasLimit,nonce:l})],v={netPayoutRaw:u.netPayoutRaw,grossPayoutRaw:u.grossPayoutRaw,feeRaw:u.fees.anvilFeeRaw,protocolFeeRaw:u.fees.protocolFeeRaw},A={version:1,surface:"evm-nft",action:"nft",nftAction:"sell",provider:"anvil-nft",owner:r,destination:o,contract:i,tokenId:a,paymentToken:y,paymentTokenDecimals:k,nativeSwapFeeWei:u.nativeSwapFeeWei,exactQuoteNetPayoutRaw:g.toString(),minPayoutRaw:g.toString(),marketCollection:u.evidence.marketCollection,anvilAttestation:d,anvilQuote:v,preconditions:{nftApprovalVerified:!0,approvedForAll:h,approvedAddress:f,exactQuoteConfirmed:!0,confirmedNetPayoutRaw:w.toString()},tradeId:Ax(e.tradeId),slippageBps:0,expiresAtMs:x+b,fee:{oracleFeeBps:0},artifact:{chainId:W,owner:r,contract:i,marketCollection:u.evidence.marketCollection,tokenId:a,paymentToken:y,paymentTokenDecimals:k,nativeSwapFeeWei:u.nativeSwapFeeWei,anvilAttestation:d,anvilQuote:v,exactQuoteNetPayoutRaw:g.toString(),minPayoutRaw:g.toString(),transactions:I}};return Px(A,u)}async function AB(e={},t={}){if(Array.isArray(e.tokenIds)){let x=e.tokenIds.map(k=>tn(k)),b={kind:"anvil-inventory",chainId:W,market:j(e.market,"Anvil market"),collection:j(e.collection,"NFT collection"),total:x.length,contentHash:vm("sha256").update(Yr(x)).digest("hex")},y=km(e.inventoryCompletenessEvidence,b,Number(t.nowMs??Date.now()),t.completenessEvidenceSecret||t.gasEvidenceSecret||process.env.ORACLE_ROUTE_ATTESTATION_SECRET);return{ids:x,total:x.length,scanned:x.length,complete:y.valid,continuation:y.valid?null:{offset:x.length,evidenceRequired:!0},completenessEvidence:y.evidence,completenessError:y.error}}let n=It(t),r=j(e.market,"Anvil market"),o=Oc(await n(W,"eth_blockNumber",[])),i=await n(W,"eth_getBlockByNumber",[o,!1]),a=String(i?.hash||"").toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(a)||Oc(i?.number)!==o)throw new Error("stonkbrokers: Anvil inventory block attestation is invalid");let s={blockHash:a,requireCanonical:!0},c=await te(n,r,Me,"inventoryLength",[],s),l=Number(c[0]);if(!Number.isSafeInteger(l)||l<0||l>lr)throw new Error(`stonkbrokers: Anvil inventory length exceeds safety maximum ${lr}`);let u=Object.hasOwn(e,"maxItems")&&e.maxItems!=null,d=Number(e.maxItems);if(u&&(!Number.isSafeInteger(d)||d<1||d>lr))throw new Error(`stonkbrokers: maxItems must be an integer from 1 through ${lr}`);let p=u?Math.min(d,l):l,m={source:"anvil-inventoryLength-linked-list",market:r,blockNumber:BigInt(o).toString(),blockHash:a,boundedMaximum:lr};if(l===0)return{ids:[],total:0,scanned:0,complete:!0,continuation:null,completenessEvidence:m};let f=BigInt((await te(n,r,Me,"oldestTokenId",[],s))[0]),h=[],g=new Set;for(;h.length<l&&h.length<p&&!g.has(f.toString());){let x=f.toString();g.add(x),h.push(x),f=BigInt((await te(n,r,Me,"getNextTokenId",[f],s))[0])}let w=h.length===l;return{ids:h,total:l,scanned:h.length,complete:w,continuation:w?null:{offset:h.length,tokenId:f.toString()},completenessEvidence:m}}function _B(e){if(!String(e).startsWith("data:application/json"))return null;let t=String(e).indexOf(",");if(t<0)throw new Error("stonkbrokers: malformed metadata data URI");let n=String(e).slice(0,t),r=String(e).slice(t+1),o=/;base64/i.test(n)?Buffer.from(r,"base64").toString("utf8"):decodeURIComponent(r);if(Buffer.byteLength(o)>256e3)throw new Error("stonkbrokers: metadata exceeds 256KB");return JSON.parse(o)}async function PB(e,t,n){let r=It(n);try{let o=String((await te(r,e,ht,"tokenURI",[BigInt(t)]))[0]),i=_B(o);if(i)return i;let a=o.startsWith("ipfs://")?`https://ipfs.io/ipfs/${o.slice(7)}`:o;return await S(a,{fetchImpl:n.fetchImpl,timeoutMs:n.timeoutMs??15e3,lookupFn:n.lookupFn,untrustedUrl:!0,maxResponseBytes:256e3})}catch(o){if(n.allowRarityOfFallback===!1)throw o;let i=await te(r,e,ht,"rarityOf",[BigInt(t)]);return{attributes:[{trait_type:"Stars",value:Number(i[0])+1}],metadataFallback:"rarityOf"}}}function Nx(e,t){let n=String(t||"Stars").trim().toLowerCase(),r=(Array.isArray(e?.attributes)?e.attributes:[]).find(i=>String(i?.trait_type??i?.traitType??"").trim().toLowerCase()===n),o=Number(r?.value);return Number.isFinite(o)?o:null}function CB(e,t=[]){let n=Array.isArray(e?.attributes)?e.attributes:[];return t.every(r=>{let o=String(r?.traitType??r?.trait_type??"").trim().toLowerCase();if(!o)throw new Error("stonkbrokers: trait filter requires traitType");let i=n.find(u=>String(u?.trait_type??u?.traitType??"").trim().toLowerCase()===o),a=String(r?.op||"eq").trim().toLowerCase();if(a==="exists")return i!=null;if(i==null)return!1;let s=i.value;if(a==="eq")return String(s).toLowerCase()===String(r.value).toLowerCase();if(a==="in")return Array.isArray(r.values)&&r.values.some(u=>String(s).toLowerCase()===String(u).toLowerCase());let c=Number(s),l=Number(r.value);if(!Number.isFinite(c)||!Number.isFinite(l))return!1;if(a==="gte")return c>=l;if(a==="lte")return c<=l;throw new Error(`stonkbrokers: unsupported trait filter op ${a}`)})}async function Lc(e={},t={}){let n=j(e.market,"Anvil market"),r=j(e.collection,"NFT collection"),o=await AB({...e,market:n},t),i=o.ids,a=Math.min(Math.max(Number(e.minStars??4)||4,1),5),s=Math.min(Math.max(Number(e.concurrency??8)||8,1),16);if(e.raritySource==="rarityOf"){let u=It(t),p=(await ve(i,s,async h=>{try{let g=await te(u,r,ht,"rarityOf",[BigInt(h)]);return{tokenId:h,stars:Number(g[0])+1}}catch(g){return e.includeErrors?{tokenId:h,stars:null,error:String(g.message||g)}:null}})).filter(h=>h&&h.stars>=a),f=(await ve(p,s,async h=>{try{let g=await Ji({market:n,collection:r,tokenId:h.tokenId},t);return{tokenId:h.tokenId,stars:h.stars,traits:[{trait_type:"Stars",value:h.stars}],available:g.available,quote:g,decision:"WATCH",reason:"rarity is ranking-only until exact exit liquidity clears net-profit gates"}}catch(g){return e.includeErrors?{tokenId:h.tokenId,stars:h.stars,available:!1,error:String(g.message||g)}:null}})).filter(Boolean).sort((h,g)=>Number(g.stars||0)-Number(h.stars||0)||(BigInt(h.tokenId)<BigInt(g.tokenId)?-1:1));return{provider:"stonkbrokers",source:"anvil-live-inventory-rarityOf",chainId:W,market:n,collection:r,scanned:i.length,inventoryTotal:o.total,inventoryScanned:o.scanned,complete:o.complete,truncated:!o.complete,continuation:o.continuation,completenessEvidence:o.completenessEvidence,completenessError:o.completenessError,count:f.length,candidates:f,exec:!1,readOnly:!0}}let l=(await ve(i,s,async u=>{try{let[d,p]=await Promise.all([PB(r,u,t),Ji({market:n,collection:r,tokenId:u},t)]),m=Nx(d,e.traitType||"Stars"),f=Array.isArray(e.traitFilters)?e.traitFilters:[];return(f.length?CB(d,f):e.includeAll===!0?!0:m!=null&&m>=a)?{tokenId:u,stars:m,traits:d.attributes||[],available:p.available,quote:p,decision:"WATCH",reason:"trait evidence is ranking-only until exact exit liquidity clears net-profit gates"}:null}catch(d){return e.includeErrors?{tokenId:u,available:!1,error:String(d.message||d)}:null}})).filter(Boolean).sort((u,d)=>Number(d.stars||0)-Number(u.stars||0)||(BigInt(u.tokenId)<BigInt(d.tokenId)?-1:1));return{provider:"stonkbrokers",source:"anvil-live-inventory-traits",chainId:W,market:n,collection:r,scanned:i.length,inventoryTotal:o.total,inventoryScanned:o.scanned,complete:o.complete,truncated:!o.complete,continuation:o.continuation,completenessEvidence:o.completenessEvidence,completenessError:o.completenessError,count:l.length,candidates:l,exec:!1,readOnly:!0}}function Ox(e,t){let n=e.collectionProfiles&&typeof e.collectionProfiles=="object"?e.collectionProfiles:{};return n[t]||n[t.toLowerCase()]||{}}function yx(e,t,n){if(!Object.hasOwn(e,t)||e[t]==null)return null;let r=Number(e[t]);if(!Number.isSafeInteger(r)||r<1||r>n)throw new Error(`stonkbrokers: ${t} must be an integer from 1 through ${n}`);return r}function Rx(e={}){return{maxMarkets:yx(e,"maxMarkets",lr),maxItemsPerMarket:yx(e,"maxItemsPerMarket",lr)}}function Lx(e,t,n){let r=t.includeEmpty===!1?e.filter(o=>o.inventoryCount>0):e;return n==null?r:r.slice(0,n)}function Yi(e,t){let n=Number(t?.inventoryTotal??e.inventoryCount??0),r=Number(e.inventoryCount??0),o=Number(t?.inventoryScanned??t?.scanned??0),i=Number.isFinite(o)?Math.min(Math.max(o,0),n):0,a=Number.isSafeInteger(n)&&n>=0&&n===r,s=!!(a&&t?.complete===!0&&t?.completenessEvidence&&i===n);return{inventoryTotal:n,inventoryScanned:i,inventoryTotalMatchesSnapshot:a,complete:s,truncated:!s,continuation:s?null:t?.continuation??{offset:i}}}function $x(e,t){let n=t.length,r=n===e.length,o=e.snapshotCoverage?.complete===!0,i=o&&r&&t.every(s=>s.complete===!0),a=t.filter(s=>s.complete!==!0).map(s=>({market:s.market,continuation:s.continuation}));return{marketTotal:e.length,marketScanned:n,complete:i,truncated:!i,snapshotCompletenessEvidence:e.snapshotCoverage?.evidence||null,continuation:r?o?a.length?{markets:a}:null:{snapshotEvidenceRequired:!0,...a.length?{markets:a}:{}}:{marketOffset:n}}}async function Bx(e={},t={}){let{maxMarkets:n,maxItemsPerMarket:r}=Rx(e),o=await Xr(e,t),i=Lx(o,e,n),a=t.scanCollection||Lc,s=Math.min(Math.max(Number(e.marketConcurrency??2)||2,1),4),c=await ve(i,s,async l=>{let u=Ox(e,l.collection);try{let d={...e,...u,market:l.market,collection:l.collection,includeAll:u.includeAll??!u.raritySource};r!=null&&(d.maxItems=r);let p=await a(d,t);return{...l,status:"ok",scan:p,...Yi(l,p)}}catch(d){return{...l,status:"error",error:String(d.message||d).slice(0,240),...Yi(l,null)}}});return{provider:"anvil-nft",source:"anvil-all-markets-live-scan",chainId:W,marketCount:i.length,...$x(o,c),collectionCount:new Set(i.map(l=>l.collection)).size,scannedMarketCount:c.filter(l=>l.status==="ok").length,candidateCount:c.reduce((l,u)=>l+Number(u.scan?.count||0),0),markets:c,exec:!1,readOnly:!0}}async function Mx(e={},t={}){let{maxMarkets:n,maxItemsPerMarket:r}=Rx(e),o=await Xr(e,t),i=o.snapshotCoverage?.complete===!0,a=Lx(o,e,n),s=e.openseaSlugs&&typeof e.openseaSlugs=="object"?e.openseaSlugs:{},c=t.scanCrossVenue||Sm,l=Math.min(Math.max(Number(e.marketConcurrency??2)||2,1),4),u=await ve(a,l,async d=>{let p=Ox(e,d.collection),m=String(p.slug||s[d.collection]||s[d.collection.toLowerCase()]||"").trim();if(!m)return{...d,decision:"WATCH",reason:"exact OpenSea collection slug is required",...Yi(d,null)};try{let f={...e,...p,market:d.market,collection:d.collection,slug:m,includeAll:p.includeAll??!p.raritySource};r!=null&&(f.maxItems=r);let h=await c(f,t),g=Yi(d,h);return{...d,decision:i&&g.complete&&h.arbCount>0?"ARB":"WATCH",slug:m,scan:h,...g}}catch(f){return{...d,decision:"WATCH",slug:m,reason:String(f.message||f).slice(0,240),...Yi(d,null)}}});return{provider:"anvil-nft",source:"anvil-all-markets-opensea-exact-nft-arb",chainId:W,marketCount:a.length,...$x(o,u),scannedMarketCount:u.filter(d=>d.scan).length,arbCount:i?u.reduce((d,p)=>d+(p.complete?Number(p.scan?.arbCount||0):0),0):0,markets:u,exec:!1,readOnly:!0}}function bx(e,t){return e>t?"ARB":"PASS"}async function TB(e={},t={}){let n=String(e.direction||""),r=it(e.amountRaw,"conversion amountRaw");if(r<=0n)throw new Error("stonkbrokers: conversion amountRaw must be positive");let o=j(e.paymentToken,"Anvil payment token"),i={chainId:W,fee:e.fee,tickSpacing:e.tickSpacing,hooks:e.hooks,tryTiers:e.tryTiers,liquidityUsd:e.liquidityUsd},a={...t,rpcCall:It(t)};if(n==="acquire-exact-output"){let l=await(t.up33QuoteExactOut||mx)({chainId:W,tokenIn:ot,tokenOut:o,amountOut:r.toString(),tickSpacing:e.up33TickSpacing??2e3},a);if(!l?.error&&l?.amountIn!=null)return{direction:n,paymentToken:o,quoteToken:ot,amountOutRaw:r.toString(),amountInWei:String(l.amountIn),source:`up33:${l.pool}`,venue:l.venue||"up33-v3",tickSpacing:l.tickSpacing,pool:l.pool,quoter:l.quoter,gasEstimate:l.gasEstimate};let u=await(t.uniV4QuoteExactOut||Uu)({...i,tokenIn:ot,tokenOut:o,amountOut:r.toString()},a);return{direction:n,paymentToken:o,quoteToken:ot,amountOutRaw:r.toString(),amountInWei:String(u.amountIn),source:`uniswap-v4:${u.poolId}`,venue:u.venue||"uniswap-v4",fee:u.fee,tickSpacing:u.tickSpacing,hooks:u.hooks||null,poolId:u.poolId,gasEstimate:u.gasEstimate}}if(n!=="liquidate-exact-input")throw new Error("stonkbrokers: unsupported conversion direction");let s=await(t.up33QuoteExactIn||px)({chainId:W,tokenIn:o,tokenOut:ot,amountIn:r.toString(),tickSpacing:e.up33TickSpacing??2e3},a);if(!s?.error&&s?.amountOut!=null)return{direction:n,paymentToken:o,quoteToken:ot,amountInRaw:r.toString(),amountOutWei:String(s.amountOut),source:`up33:${s.pool}`,venue:s.venue||"up33-v3",tickSpacing:s.tickSpacing,pool:s.pool,quoter:s.quoter,gasEstimate:s.gasEstimate};let c=await(t.uniV4QuoteExactIn||un)({...i,tokenIn:o,tokenOut:ot,amountIn:r.toString()},a);return{direction:n,paymentToken:o,quoteToken:ot,amountInRaw:r.toString(),amountOutWei:String(c.amountOut),source:`uniswap-v4:${c.poolId}`,venue:c.venue||"uniswap-v4",fee:c.fee,tickSpacing:c.tickSpacing,hooks:c.hooks||null,poolId:c.poolId,gasEstimate:c.gasEstimate}}function wx(e,t){if(!e||typeof e!="object")throw new Error("exact payment-token conversion quote unavailable");let n=j(e.quoteToken,"conversion quote token");if(n!==ot)throw new Error("conversion quote token must be Robinhood WETH");if(!String(e.source||"").trim())throw new Error("conversion quote source required");if(t.direction==="acquire-exact-output"){if(String(e.amountOutRaw)!==t.amountRaw)throw new Error("conversion exact-output amount mismatch");let o=it(e.amountInWei,"conversion amountInWei");if(o<=0n)throw new Error("conversion amountInWei must be positive");return{...e,quoteToken:n,amountInWei:o.toString()}}if(String(e.amountInRaw)!==t.amountRaw)throw new Error("conversion exact-input amount mismatch");let r=it(e.amountOutWei,"conversion amountOutWei");if(r<=0n)throw new Error("conversion amountOutWei must be positive");return{...e,quoteToken:n,amountOutWei:r.toString()}}function NB(e,t){return Array.isArray(e)?e.find(n=>n?.route===t)||null:!e||typeof e!="object"?null:Object.hasOwn(e,"route")||Object.hasOwn(e,"chainId")?e:e[t]||e.routes?.[t]||null}function Yr(e){return Array.isArray(e)?`[${e.map(Yr).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Yr(e[t])}`).join(",")}}`:JSON.stringify(e)}function Ux(e,t){let n=String(t||"");if(n.length<16)throw new Error("stonkbrokers: gas evidence secret must be at least 16 characters");let r={...e};return delete r.mac,{...r,mac:yB("sha256",n).update(Yr(r)).digest("hex")}}function OB(e,t){return Ux(e,t)}function km(e,t,n,r){try{if(!e||typeof e!="object"||Array.isArray(e))throw new Error("completeness evidence is required");if(!r||String(r).length<16)throw new Error("trusted completeness attestation secret is unavailable");let o=String(e.mac||"").toLowerCase(),i=OB(e,r).mac,a=Buffer.from(o,"hex"),s=Buffer.from(i,"hex");if(!/^[0-9a-f]{64}$/.test(o)||a.length!==s.length||!xx(a,s))throw new Error("completeness evidence authentication failed");for(let[u,d]of Object.entries(t))if(String(e[u])!==String(d))throw new Error(`completeness evidence ${u} mismatch`);let c=Number(e.quotedAtMs),l=Number(e.expiresAtMs);if(!Number.isFinite(c)||!Number.isFinite(l)||c>n||l<=n||l<=c)throw new Error("completeness evidence is stale or has invalid freshness bounds");if(!String(e.source||"").trim())throw new Error("completeness evidence source is required");return{valid:!0,evidence:e,error:null}}catch(o){return{valid:!1,evidence:null,error:String(o.message||o)}}}function RB(e,t,n,r){return Array.isArray(e)?e.find(o=>o?.route===t&&o?.leg===r&&(n==null||String(o?.calldataHash||"").toLowerCase()===n))||null:NB(e,t)}function bm(e,t,n,r,o,i){let a=RB(e,t,o.calldataHash,o.leg);try{if(!a||typeof a!="object")throw new Error(`${r} evidence is required`);if(Number(a.chainId)!==W)throw new Error(`${r} evidence chainId mismatch`);if(String(a.route||"")!==t)throw new Error(`${r} evidence route mismatch`);if(String(a.leg||"")!==o.leg)throw new Error(`${r} evidence leg mismatch`);if(!String(a.source||"").trim())throw new Error(`${r} evidence source is required`);if(!i||String(i).length<16)throw new Error(`${r} trusted attestation secret is unavailable`);let s=String(a.mac||"").toLowerCase(),c=Ux(a,i).mac,l=Buffer.from(s,"hex"),u=Buffer.from(c,"hex");if(!/^[0-9a-f]{64}$/.test(s)||l.length!==u.length||!xx(l,u))throw new Error(`${r} evidence authentication failed`);if(!/^0x[0-9a-f]{64}$/.test(String(a.calldataHash||"").toLowerCase()))throw new Error(`${r} evidence calldata hash is invalid`);if(o.calldataHash!=null&&String(a.calldataHash||"").toLowerCase()!==o.calldataHash)throw new Error(`${r} evidence calldata mismatch`);if(String(a.blockHash||"").toLowerCase()!==o.blockHash||String(a.blockNumber)!==o.blockNumber)throw new Error(`${r} evidence block mismatch`);if(o.orderHash!=null&&String(a.orderHash||"").toLowerCase()!==o.orderHash)throw new Error(`${r} evidence order mismatch`);if(o.protocolAddress!=null&&j(a.protocolAddress,`${r} protocol address`)!==o.protocolAddress)throw new Error(`${r} evidence protocol mismatch`);let d=Number(a.quotedAtMs),p=Number(a.expiresAtMs);if(!Number.isFinite(d)||!Number.isFinite(p)||d>n||p<=n||p<=d)throw new Error(`${r} evidence is stale or has invalid freshness bounds`);let m=a.amountWei??a.amount??a.gasCostWei??a.gasPriceWei,f=it(m,`${r} evidence amountWei`);if(f<=0n)throw new Error(`${r} evidence amountWei must be positive`);let h=en(a.gasLimit,`${r} evidence gasLimit`),g=en(a.gasPriceWei,`${r} evidence gasPriceWei`);if(h*g!==f)throw new Error(`${r} evidence amount does not match gasLimit times gasPriceWei`);let w=a.simulation;if(!w||typeof w!="object"||Array.isArray(w))throw new Error(`${r} simulation evidence is required`);if(Number(w.chainId)!==W)throw new Error(`${r} simulation chainId mismatch`);if(String(w.route||"")!==t||String(w.leg||"")!==o.leg)throw new Error(`${r} simulation route or leg mismatch`);if(!String(w.source||"").trim())throw new Error(`${r} simulation source is required`);if(String(w.blockHash||"").toLowerCase()!==o.blockHash||String(w.blockNumber)!==o.blockNumber)throw new Error(`${r} simulation block mismatch`);if(String(w.calldataHash||"").toLowerCase()!==o.calldataHash)throw new Error(`${r} simulation calldata mismatch`);if(j(w.target,`${r} simulation target`)!==o.target)throw new Error(`${r} simulation target mismatch`);let b=j(w.sender,`${r} simulation sender`),y=j(w.owner,`${r} simulation owner`);if(!o.owner||b!==o.owner||y!==o.owner)throw new Error(`${r} simulation sender or owner mismatch`);if(String(it(w.valueWei,`${r} simulation valueWei`))!==String(it(o.valueWei,`${r} expected simulation valueWei`)))throw new Error(`${r} simulation value mismatch`);if(o.orderHash!=null&&String(w.orderHash||"").toLowerCase()!==o.orderHash)throw new Error(`${r} simulation order mismatch`);if(o.protocolAddress!=null&&j(w.protocolAddress,`${r} simulation protocol address`)!==o.protocolAddress)throw new Error(`${r} simulation protocol mismatch`);if(w.success!==!0||w.reverted!==!1||!/^0x(?:[0-9a-f]{2})*$/i.test(String(w.result??"")))throw new Error(`${r} simulation did not return a successful result`);let k=Number(w.quotedAtMs),E=Number(w.expiresAtMs);if(!Number.isFinite(k)||!Number.isFinite(E)||k>n||E<=n||E<=k)throw new Error(`${r} simulation is stale or has invalid freshness bounds`);return{amount:f,evidence:{...a,amountWei:f.toString()},error:null}}catch(s){return{amount:null,evidence:null,error:String(s.message||s)}}}function vx(e){let t=j(e,"OpenSea payment token");if(t!==xm&&t!==ot)throw new Error("OpenSea payment token is not Robinhood native or canonical WETH");return t}async function Sm(e={},t={}){let n=await Lc(e,t),r=Number(t.nowMs??Date.now());if(!Number.isFinite(r))throw new Error("stonkbrokers: opts.nowMs must be finite");let o=t.gasEvidenceSecret||process.env.ORACLE_ROUTE_ATTESTATION_SECRET,i=null;try{i=j(e.owner,"execution owner")}catch{}let a=(w,x,b,y={})=>({calldataHash:w==null?null:String(w).toLowerCase(),blockNumber:String(x?.blockNumber??""),blockHash:String(x?.blockHash||"").toLowerCase(),leg:b,owner:i,...y}),s=(w,x,b,y,k)=>bm(e.gasEvidence??e.gasCostEvidence,w,r,`${x} gas`,a(b,y,x,k),o),c=(w,x)=>{let b=null;try{b=j(w?.target,"conversion target")}catch{}let y=a(w?.calldataHash,w,"conversion",{target:b,valueWei:String(w?.valueWei??"0")});if(!/^0x[0-9a-f]{64}$/.test(y.calldataHash)||!/^0x[0-9a-f]{64}$/.test(y.blockHash)||!/^\d+$/.test(y.blockNumber))return{amount:null,evidence:null,error:"conversion quote lacks route/calldata/block binding"};let k=bm(e.conversionGasEvidence??e.conversionGasCostEvidence,x,r,"conversion gas",y,o);if(k.amount!=null||w?.gasEstimate==null)return k;let E=bm(e.gasPriceEvidence,x,r,"gas price",{...y,leg:"conversion-gas-price"},o);if(E.amount==null)return{amount:null,evidence:null,error:E.error};let I=it(w.gasEstimate,"conversion gasEstimate");return{amount:I*E.amount,evidence:{source:"quote-gas-estimate-times-bound-gas-price",route:x,leg:"conversion",gasEstimate:I.toString(),gasPriceEvidence:E.evidence},error:null}},l=(w,x,b,y,k)=>{try{let E=String(x?.orderHash||"").toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(E))throw new Error("exact Seaport order hash is required");let I=j(x?.protocolAddress,"Seaport protocol address"),v=String(x?.executionCalldataHash||"").toLowerCase(),A=/^0x[0-9a-f]{64}$/.test(v)?v:null,P=y==="seaport-fulfillment"&&k===xm?String(x?.priceWei??""):"0",T={orderHash:E,protocolAddress:I,target:I,valueWei:P},L=s(w,y,A,b,T);if(L.amount==null)throw new Error(L.error);if(L.evidence?.approvalChecked!==!0)throw new Error("fresh exact Seaport approval-state check is required");let F=L.evidence?.approvalRequired;if(typeof F!="boolean")throw new Error("exact Seaport approval requirement evidence is required");if(typeof x?.approvalRequired=="boolean"&&x.approvalRequired!==F)throw new Error("Seaport approval requirement evidence mismatch");let q=[L];if(F){let H=String(x?.approvalCalldataHash||"").toLowerCase(),B=/^0x[0-9a-f]{64}$/.test(H)?H:null,z=y==="seaport-offer-acceptance"?n.collection:k;q.push(s(w,"seaport-approval",B,b,{...T,target:z,valueWei:"0"}))}if(k===xm){let H=w==="anvil-to-opensea"?"wrap-native-to-weth":"unwrap-weth-to-native",B=String(x?.prerequisiteCalldataHash||"").toLowerCase(),z=/^0x[0-9a-f]{64}$/.test(B)?B:null,le=H==="wrap-native-to-weth"?String(x?.sellerNetWei??""):"0";q.push(s(w,H,z,b,{...T,target:ot,valueWei:le}))}let O=q.find(H=>H.amount==null);if(O)throw new Error(O.error);return{amount:q.reduce((H,B)=>H+B.amount,0n),evidence:q.map(H=>H.evidence),error:null}}catch(E){return{amount:null,evidence:null,error:String(E.message||E)}}},u=it(e.minNetWei,"minNetWei","0"),d=t.openSeaBestListing||Ns,p=t.openSeaBestOffer||Os,m=t.paymentTokenConversion||(w=>TB({...w,fee:e.conversionFee,tickSpacing:e.conversionTickSpacing,hooks:e.conversionHooks,tryTiers:e.conversionTryTiers,liquidityUsd:e.conversionLiquidityUsd},t)),f=await Rc({market:n.market,collection:n.collection},t),h=[];for(let w of n.candidates){let x=null;try{x=await p({chain:"robinhood",slug:e.slug,contract:n.collection,tokenId:w.tokenId},t)}catch{}let b=w.quote,y=wm(Me.encodeFunctionData("buySpecificNFT",[BigInt(w.tokenId),BigInt(b.totalCostRaw)])).toLowerCase(),k=s("anvil-to-opensea","anvil-call",y,b.evidence.attestation,{target:n.market,valueWei:b.nativeSwapFeeWei}),E=null,I=null;if(x)try{E=vx(x.paymentToken)}catch(B){I=String(B.message||B)}let v=I||!x?{amount:null,evidence:null,error:I||"exact OpenSea offer is unavailable"}:l("anvil-to-opensea",x,b.evidence.attestation,"seaport-offer-acceptance",E),A={route:"anvil-to-opensea",tokenId:w.tokenId,stars:w.stars,paymentToken:b.paymentToken,amountUnits:b.amountUnits,anvilTotalCostRaw:b.totalCostRaw,anvilBaseCostRaw:b.baseCostRaw,anvilFeeRaw:b.fees.totalFeeRaw,paymentTokenDecimals:b.paymentTokenDecimals,nativeSwapFeeWei:b.nativeSwapFeeWei,openSeaGrossOfferWei:x?.grossOfferWei==null?null:String(x.grossOfferWei),openSeaSellingValueWei:x?.sellerNetWei==null?null:String(x.sellerNetWei),openSeaFeeWei:x?.feeWei==null?null:String(x.feeWei),openSeaPaymentToken:E,gasCostWei:k.amount==null?null:k.amount.toString(),gasEvidence:k.evidence,marketplaceGasCostWei:v.amount==null?null:v.amount.toString(),marketplaceGasEvidence:v.evidence,conversionGasCostWei:null};if(x?.sellerNetWei==null||!b.available)h.push({...A,netWei:null,decision:"WATCH",reason:"exact OpenSea seller net is unavailable or Anvil inventory is not executable"});else if(I)h.push({...A,netWei:null,decision:"WATCH",reason:`exact OpenSea payment token binding failed: ${I}`});else if(k.amount==null)h.push({...A,netWei:null,decision:"WATCH",reason:`fresh exact gas evidence is required before net arbitrage can be calculated: ${k.error}`});else if(v.amount==null)h.push({...A,netWei:null,decision:"WATCH",reason:`fresh exact Seaport and prerequisite gas evidence is required before net arbitrage can be calculated: ${v.error}`});else if(typeof m!="function")h.push({...A,netWei:null,decision:"WATCH",reason:"exact payment-token to WETH conversion quote is required before unlike currency values can be compared"});else try{let B=wx(await m({chainId:W,direction:"acquire-exact-output",amountRaw:b.totalCostRaw,paymentToken:b.paymentToken,quoteToken:ot}),{direction:"acquire-exact-output",amountRaw:b.totalCostRaw}),z=c(B,"anvil-to-opensea");if(z.amount==null)h.push({...A,conversion:B,netWei:null,decision:"WATCH",reason:`fresh exact conversion gas evidence is required before net arbitrage can be calculated: ${z.error}`});else{let le=k.amount+v.amount+z.amount,ue=BigInt(x.sellerNetWei)-BigInt(B.amountInWei)-BigInt(b.nativeSwapFeeWei)-le;h.push({...A,conversionGasCostWei:z.amount.toString(),conversionGasEvidence:z.evidence,totalExecutionGasWei:le.toString(),anvilCostInWethWei:B.amountInWei,conversion:B,netWei:ue.toString(),decision:bx(ue,u),reason:ue>u?"exact inventory, exact conversion, native fee, gas, and exact OpenSea seller net clear the configured net-profit gate":"net does not clear configured minimum"})}}catch(B){h.push({...A,netWei:null,decision:"WATCH",reason:`exact payment-token conversion failed: ${String(B.message||B)}`})}let P=null;try{P=await d({chain:"robinhood",slug:e.slug,contract:n.collection,tokenId:w.tokenId,maxPages:e.openSeaListingMaxPages},t)}catch{}if(!P)continue;let T=wm(Me.encodeFunctionData("sellNFT",[BigInt(w.tokenId),BigInt(f.netPayoutRaw)])).toLowerCase(),L=s("opensea-to-anvil","anvil-call",T,f.evidence.attestation,{target:n.market,valueWei:f.nativeSwapFeeWei}),F=null,q=null;try{F=vx(P.paymentToken)}catch(B){q=String(B.message||B)}let O=q?{amount:null,evidence:null,error:q}:l("opensea-to-anvil",P,f.evidence.attestation,"seaport-fulfillment",F),H={route:"opensea-to-anvil",tokenId:w.tokenId,stars:w.stars,paymentToken:f.paymentToken,amountUnits:f.amountUnits,openSeaBuyPriceWei:String(P.priceWei),anvilGrossPayoutRaw:f.grossPayoutRaw,anvilNetPayoutRaw:f.netPayoutRaw,anvilFeeRaw:f.fees.totalFeeRaw,paymentTokenDecimals:f.paymentTokenDecimals,nativeSwapFeeWei:f.nativeSwapFeeWei,openSeaPaymentToken:F,gasCostWei:L.amount==null?null:L.amount.toString(),gasEvidence:L.evidence,marketplaceGasCostWei:O.amount==null?null:O.amount.toString(),marketplaceGasEvidence:O.evidence,conversionGasCostWei:null};if(q){h.push({...H,netWei:null,decision:"WATCH",reason:`exact OpenSea payment token binding failed: ${q}`});continue}if(L.amount==null){h.push({...H,netWei:null,decision:"WATCH",reason:`fresh exact gas evidence is required before net arbitrage can be calculated: ${L.error}`});continue}if(O.amount==null){h.push({...H,netWei:null,decision:"WATCH",reason:`fresh exact Seaport and prerequisite gas evidence is required before net arbitrage can be calculated: ${O.error}`});continue}if(typeof m!="function"){h.push({...H,netWei:null,decision:"WATCH",reason:"exact payment-token to WETH conversion quote is required before unlike currency values can be compared"});continue}try{let B=wx(await m({chainId:W,direction:"liquidate-exact-input",amountRaw:f.netPayoutRaw,paymentToken:f.paymentToken,quoteToken:ot}),{direction:"liquidate-exact-input",amountRaw:f.netPayoutRaw}),z=c(B,"opensea-to-anvil");if(z.amount==null)h.push({...H,conversion:B,netWei:null,decision:"WATCH",reason:`fresh exact conversion gas evidence is required before net arbitrage can be calculated: ${z.error}`});else{let le=L.amount+O.amount+z.amount,ue=BigInt(B.amountOutWei)-BigInt(P.priceWei)-BigInt(f.nativeSwapFeeWei)-le;h.push({...H,conversionGasCostWei:z.amount.toString(),conversionGasEvidence:z.evidence,totalExecutionGasWei:le.toString(),anvilPayoutInWethWei:B.amountOutWei,conversion:B,netWei:ue.toString(),decision:bx(ue,u),reason:ue>u?"exact OpenSea listing, exact conversion, native fee, gas, and current Anvil payout clear the configured net-profit gate":"net does not clear configured minimum"})}}catch(B){h.push({...H,netWei:null,decision:"WATCH",reason:`exact payment-token conversion failed: ${String(B.message||B)}`})}}let g=n.complete===!0?h:h.map(w=>w.decision==="ARB"?{...w,netWei:null,decision:"WATCH",reason:"complete inventory coverage evidence is required before arbitrage classification"}:w);return{provider:"stonkbrokers",source:"anvil-opensea-exact-nft-arb",chainId:W,collection:n.collection,market:n.market,slug:String(e.slug||""),gasCostWei:null,conversionGasCostWei:null,gasPriceWei:null,inventoryTotal:n.inventoryTotal,inventoryScanned:n.inventoryScanned,complete:n.complete,truncated:n.truncated,continuation:n.continuation,minNetWei:u.toString(),opportunities:g.sort((w,x)=>{let b=BigInt(w.netWei??"-1"),y=BigInt(x.netWei??"-1");return y>b?1:y<b?-1:0}),arbCount:g.filter(w=>w.decision==="ARB").length,exec:!1,readOnly:!0}}async function $c(e={},t={}){let n=It(t),r=tn(e.brokerTokenId,"brokerTokenId"),[o,i,a]=await Promise.all([te(n,ft.ammVault,hx,"quoteSpecificBuy",[BigInt(r)]),te(n,ft.ammVault,hx,"inventory",[BigInt(r)]),te(n,ft.nft,ht,"ownerOf",[BigInt(r)])]),s={quoteAvailable:!!o[2],inventory:!!i[0],ownerIsAmm:j(a[0],"broker owner")===ft.ammVault},c=s.quoteAvailable&&s.inventory&&s.ownerIsAmm;return{provider:"stonkbrokers",chainId:W,brokerTokenId:r,tokenCostWei:BigInt(o[0]).toString(),ethFeeWei:BigInt(o[1]).toString(),available:c,evidence:s,reason:c?null:"broker-not-provably-in-inventory",exec:!1,readOnly:!0}}async function Fx(e,t){try{return j((await te(t,ft.nft,ht,"tokenWallet",[BigInt(e)]))[0],"broker TBA")}catch{return j((await te(t,ft.nft,ht,"predictWallet",[BigInt(e)]))[0],"broker TBA")}}async function Dx(e={},t={}){let n=It(t),r=Math.min(Math.max(Number(e.minStars??4)||4,1),5),i=(await ve(Array.isArray(e.candidates)?e.candidates:[],8,async a=>{let s=tn(a.brokerTokenId,"brokerTokenId"),c=tn(a.nestedTokenId,"nestedTokenId"),l=j(a.tba,"TBA"),u=j(a.nestedCollection,"nested collection"),d=Nx({attributes:a.traits},e.traitType||"Stars");if(d==null||d<r)return null;let[p,m,f]=await Promise.all([Fx(s,n),te(n,u,ht,"ownerOf",[BigInt(c)]).then(g=>j(g[0],"nested owner")),$c({brokerTokenId:s},t)]),h=p===l&&m===l&&f.available;return{brokerTokenId:s,tba:l,nestedCollection:u,nestedTokenId:c,stars:d,traits:a.traits||[],available:h,quote:f,decision:"WATCH",reason:h?"rarity is ranking-only until exit-liquidity evidence clears profit gates":"nested custody or parent availability is stale"}})).filter(Boolean).sort((a,s)=>s.stars-a.stars);return{provider:"stonkbrokers",chainId:W,count:i.length,candidates:i,exec:!1,readOnly:!0}}async function qx(e={},t={}){if(e.userConfirmed!==!0)throw new Error("stonkbrokers: userConfirmed=true required");let n=j(e.buyer,"buyer"),r=tn(e.brokerTokenId,"brokerTokenId"),o=it(e.maxTokenCostWei,"maxTokenCostWei"),i=it(e.maxEthFeeWei,"maxEthFeeWei"),a=await $c({brokerTokenId:r},t);if(!a.available)throw new Error("stonkbrokers: broker is not provably available");if(BigInt(a.tokenCostWei)>o||BigInt(a.ethFeeWei)>i)throw new Error("stonkbrokers: live quote exceeds reviewed cap");return N({provider:"stonkbrokers",kind:"stonkbroker-specific-buy-intent",action:"buy-specific-broker",chainId:W,buyer:n,localOnly:!0,requiresLocalVault:!0,transaction:null,intent:{brokerTokenId:r,market:ft.ammVault,maxTokenCostWei:o.toString(),maxEthFeeWei:i.toString(),quotedTokenCostWei:a.tokenCostWei,quotedEthFeeWei:a.ethFeeWei}},{provider:"stonkbrokers",kind:"stonkbroker-specific-buy-intent",env:t.env})}async function Xi(e={},t={}){let n=It(t),r=e.which==="overtime"?"overtime":"stock",o=r==="overtime"?ft.overtimeBooster:ft.stockBooster,[i,a,s,c,l,u]=await Promise.all([te(n,o,Cn,"pendingEth"),te(n,o,Cn,"minDropWei"),te(n,o,Cn,"roundActive"),te(n,o,Cn,"currentRound"),te(n,o,Cn,"roundState").catch(()=>null),te(n,o,Cn,"getStockTokens").catch(()=>null)]),d=BigInt(i[0]),p=BigInt(a[0]),m=!!s[0],f=!m&&d>=p,h=m;return{provider:"stonkbrokers",chainId:W,which:r,booster:o,pendingWei:d.toString(),minDropWei:p.toString(),roundActive:m,roundId:BigInt(c[0]).toString(),cursor:l?BigInt(l[2]).toString():null,remaining:l?BigInt(l[3]).toString():null,stockTokens:u?Array.from(u[0]).map(g=>j(g,"stock token")):[],canStart:f,canContinue:h,action:h?"continueDrop":f?"startDropPublic":"wait",exec:!1,readOnly:!0}}function Hx(e={},t={}){let r=(e.which==="overtime"?"overtime":"stock")==="overtime"?ft.overtimeBooster:ft.stockBooster,o=e.mode==="continue"||e.mode==="continueDrop"?"continue":"start",i=o==="continue"?Cn.encodeFunctionData("continueDrop",[BigInt(Math.min(Math.max(Number(e.batchSize??50)||50,1),200))]):Cn.encodeFunctionData("startDropPublic",[BigInt(Math.min(Math.max(Number(e.minOutBps??0)||0,0),1e4))]);return N({provider:"stonkbrokers",kind:"stonkbrokers-clock-in",action:o==="continue"?"continueDrop":"startDropPublic",chainId:W,localOnly:!0,requiresLocalVault:!0,transaction:{chainId:W,to:r,data:i,value:"0"}},{provider:"stonkbrokers",kind:"stonkbrokers-clock-in",env:t.env})}async function jx(e={},t={}){let n=Array.isArray(e.brokerTokenIds)?e.brokerTokenIds.map(s=>tn(s,"brokerTokenId")):[],r=It(t),o=await ve(n,8,async s=>{let[c,l]=await Promise.all([te(r,ft.nft,ht,"ownerOf",[BigInt(s)]).then(u=>j(u[0],"broker owner")),Fx(s,r)]);return{brokerTokenId:s,owner:c,tba:l}}),[i,a]=await Promise.all([Xi({which:"stock"},t),Xi({which:"overtime"},t).catch(s=>({error:String(s.message||s)}))]);return{provider:"stonkbrokers",chainId:W,owner:e.owner?j(e.owner,"owner"):null,brokers:o,clockIn:{stock:i,overtime:a},exec:!1,readOnly:!0}}async function zx(e={},t={}){try{let n=await Xr(e,t);return{ok:!0,chainId:W,marketCount:n.length,activeMarketCount:n.filter(r=>r.inventoryCount>0).length,readOnly:!0}}catch(n){return{ok:!1,chainId:W,error:String(n.message||n).slice(0,180),readOnly:!0}}}async function Vx(e={},t={}){try{let n=await Xi({which:"stock"},t);return{ok:!0,chainId:W,blockRead:!0,action:n.action}}catch(n){return{ok:!1,chainId:W,error:String(n.message||n).slice(0,180)}}}Y();import{createHash as $B}from"node:crypto";var Bc="https://eips.ethereum.org/EIPS/eip-8004#registration-v1",BB=Object.freeze([{name:"register",signature:"register(string)",selector:"0xf2c298be"},{name:"setAgentURI",signature:"setAgentURI(uint256,string)",selector:"0x0af28bd3"},{name:"ownerOf",signature:"ownerOf(uint256)",selector:"0x6352211e"},{name:"tokenURI",signature:"tokenURI(uint256)",selector:"0xc87b56dd"},{name:"getAgentWallet",signature:"getAgentWallet(uint256)",selector:"0x00339509"}]),ur=Object.freeze(Object.fromEntries(BB.map(e=>[e.name,e.selector]))),MB=new Set(["type","name","description","image","services","x402Support","active","registrations","supportedTrust"]),UB=new Set(["name","endpoint","version","skills","domains"]),FB=new Set(["agentId","agentRegistry"]),Wx=new Set(["reputation","crypto-economic","tee-attestation"]),DB=/(private.?key|secret|seed|mnemonic|password|signature|api.?key|bearer|authorization)/i,qB=64*1024;function Qi(e,t){if(!e||typeof e!="object"||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)throw new Error(`erc8004: ${t} must be a plain object`);return e}function Im(e,t,n){for(let r of Object.keys(e)){if(DB.test(r))throw new Error(`erc8004: secret-looking field ${n}.${r} forbidden`);if(!t.has(r))throw new Error(`erc8004: unknown field ${n}.${r}`)}}function Qr(e,t,n,{empty:r=!1}={}){if(typeof e!="string"||!r&&e.length===0||e.length>n||/[\u0000-\u001f\u007f]/u.test(e))throw new Error(`erc8004: malformed or oversized ${t}`);return e}function Gx(e,t,{service:n=!1}={}){let r=Qr(e,t,2048);if(/^(?:javascript|file):/i.test(r))throw new Error(`erc8004: unsafe ${t} URI`);if(n&&(/^[^\s@]+@[^\s@]+$/.test(r)||/^[\w-]+(?:\.[\w-]+)*\.eth$/i.test(r))||n&&/^did:[a-z0-9]+:[^\s]+$/i.test(r)||/^(?:https|ipfs):\/\/[^\s]+$/i.test(r)||/^data:image\/(?:png|jpeg|gif|webp|svg\+xml);base64,[a-z0-9+/]+=*$/i.test(r)&&r.length<=16384)return r;throw new Error(`erc8004: ${t} must use a safe URI scheme`)}function Em(e,t){let n=String(e||"");if(!/^0x[0-9a-fA-F]{40}$/.test(n))throw new Error(`erc8004: ${t} must be a 20-byte address`);return n.toLowerCase()}function Mc(e){let t=Number(e);if(!Number.isSafeInteger(t)||t<=0)throw new Error("erc8004: positive integer chainId required");return t}function Am(e){if(typeof e!="number"&&typeof e!="bigint"||e<0||!Number.isSafeInteger(Number(e)))throw new Error("erc8004: agentId must be a non-negative safe integer");return BigInt(e)}function _m(e){let t=Mc(process.env.ORACLE_ERC8004_CHAIN_ID);if(e!==t)throw new Error(`erc8004: chainId ${e} is not in registry allowlist`);return Em(process.env.ORACLE_ERC8004_IDENTITY_REGISTRY,"allowlisted registry")}function Yx(){let e=[];try{let t=Mc(process.env.ORACLE_ERC8004_CHAIN_ID);_m(t),e=[t]}catch{}return{provider:"erc8004-identity",status:e.length>0?"configured":"unconfigured",standardStatus:"draft",custody:"public-keyless",signingReady:!1,broadcastReady:!1,configuredChainIds:e}}function HB(e){return JSON.parse(JSON.stringify(e))}function Uc(e){let t=Qi(e,"registration file");if(Im(t,MB,"registration"),t.type!==Bc)throw new Error("erc8004: registration-v1 type required");let n={type:Bc,name:Qr(t.name,"name",128),description:Qr(t.description,"description",4096),image:Gx(t.image,"image")};if(!Array.isArray(t.services)||t.services.length>32)throw new Error("erc8004: services must be a bounded array");let r=new Set;if(n.services=t.services.map((a,s)=>{let c=Qi(a,`services[${s}]`);Im(c,UB,`services[${s}]`);let l=Qr(c.name,`services[${s}].name`,64);if(/^(?:x|twitter)$/i.test(l)||/(?:^|\.)x\.com(?:\/|$)|twitter\.com/i.test(String(c.endpoint)))throw new Error("erc8004: X/Twitter services are excluded");let u=l.toLowerCase();if(r.has(u))throw new Error(`erc8004: duplicate service ${l}`);r.add(u);let d={name:l,endpoint:Gx(c.endpoint,`services[${s}].endpoint`,{service:!0})};c.version!=null&&(d.version=Qr(c.version,`services[${s}].version`,64));for(let p of["skills","domains"])if(c[p]!=null){if(!Array.isArray(c[p])||c[p].length>64||c[p].some(m=>typeof m!="string"||m.length>128))throw new Error(`erc8004: malformed services[${s}].${p}`);d[p]=[...c[p]]}return d}),typeof t.x402Support!="boolean"||typeof t.active!="boolean")throw new Error("erc8004: x402Support and active must be boolean");if(n.x402Support=t.x402Support,n.active=t.active,!Array.isArray(t.registrations)||t.registrations.length>32)throw new Error("erc8004: registrations must be a bounded array");let o=new Set;if(n.registrations=t.registrations.map((a,s)=>{let c=Qi(a,`registrations[${s}]`);Im(c,FB,`registrations[${s}]`);let l=Am(c.agentId),u=/^eip155:([1-9][0-9]*):(0x[0-9a-fA-F]{40})$/.exec(String(c.agentRegistry||""));if(!u)throw new Error(`erc8004: malformed registrations[${s}].agentRegistry`);let d=`eip155:${Number(u[1])}:${u[2].toLowerCase()}`,p=`${d}:${l}`;if(o.has(p))throw new Error("erc8004: duplicate registration");return o.add(p),{agentId:Number(l),agentRegistry:d}}),t.supportedTrust!=null){if(!Array.isArray(t.supportedTrust)||t.supportedTrust.length>Wx.size||new Set(t.supportedTrust).size!==t.supportedTrust.length||t.supportedTrust.some(a=>!Wx.has(a)))throw new Error("erc8004: malformed supportedTrust");n.supportedTrust=[...t.supportedTrust]}let i=JSON.stringify(n);if(Buffer.byteLength(i)>qB)throw new Error("erc8004: registration metadata oversized");return HB(n)}function jB(e){if(Qi(e,"registration input"),Object.prototype.hasOwnProperty.call(e,"type")&&e.type!==Bc)throw new Error("erc8004: registration-v1 type required");return Uc({type:Bc,...e})}function zB(e){let t=Uc(e);return`data:application/json;base64,${Buffer.from(JSON.stringify(t),"utf8").toString("base64")}`}function Zi(e){return BigInt(e).toString(16).padStart(64,"0")}function Jx(e){let t=Buffer.from(e,"utf8").toString("hex");return`${Zi(t.length/2)}${t.padEnd(Math.ceil(t.length/64)*64,"0")}`}function VB(e){return`${ur.register}${Zi(32)}${Jx(e)}`}function WB(e,t){return`${ur.setAgentURI}${Zi(e)}${Zi(64)}${Jx(t)}`}function GB(e,t){return`${e}${Zi(t)}`}function KB(e){return $B("sha256").update(e,"utf8").digest("hex")}function Pm(e,t){Qi(e,"arguments");for(let n of Object.keys(e))if(!t.has(n))throw new Error(`erc8004: caller field ${n} is forbidden or unknown`)}function Xx(e,t,{kind:n,uri:r,selector:o,data:i,id:a}){let s=Mc(e.chainId),c=Em(e.owner,"owner"),l=_m(s),u=Number(t?.nowMs??Date.now());return N({chainId:s,registry:l,owner:c,taker:c,...a==null?{}:{agentId:Number(a)},agentURI:r,agentURIHash:KB(r),selector:o,custody:"public-keyless",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,executionReady:!1,transaction:{chainId:s,from:c,to:l,data:i,value:"0x0"}},{provider:"erc8004-identity",kind:n,nowMs:u,expiresAtMs:t?.expiresAtMs})}function Qx(e={},t={}){Pm(e,new Set(["chainId","owner","registration"]));let n=zB(jB(e.registration));return Xx(e,t,{kind:"erc8004-register",uri:n,selector:ur.register,data:VB(n)})}function Zx(e={},t={}){Pm(e,new Set(["chainId","owner","agentId","agentURI"]));let n=Am(e.agentId),r=ek(e.agentURI);return Xx(e,t,{kind:"erc8004-set-agent-uri",uri:r,selector:ur.setAgentURI,data:WB(n,r),id:n})}function ek(e){let t=Qr(e,"agentURI",9e4);if(/^(?:javascript|file):/i.test(t))throw new Error("erc8004: unsafe agentURI");if(/^(?:https|ipfs):\/\/[^\s]+$/i.test(t))return t;let n="data:application/json;base64,";if(!t.startsWith(n)||t.length>9e4)throw new Error("erc8004: agentURI must use https, ipfs, or base64 JSON data URI");let r=t.slice(n.length);if(!/^[A-Za-z0-9+/]+={0,2}$/.test(r)||r.length%4!==0)throw new Error("erc8004: malformed agentURI base64");let o;try{o=JSON.parse(Buffer.from(r,"base64").toString("utf8"))}catch{throw new Error("erc8004: malformed agentURI JSON")}return Uc(o),t}function Kx(e,t){if(!/^0x[0-9a-fA-F]{64}$/.test(e)||!/^0{24}/.test(e.slice(2)))throw new Error(`erc8004: malformed ${t} RPC result`);return Em(`0x${e.slice(-40)}`,t)}function YB(e,t){if(!/^0x[0-9a-fA-F]*$/.test(e)||e.length<130)throw new Error(`erc8004: malformed ${t} RPC result`);let n=e.slice(2),r=Number.parseInt(n.slice(0,64),16)*2,o=Number.parseInt(n.slice(r,r+64),16)*2;if(!Number.isSafeInteger(r)||!Number.isSafeInteger(o)||r+64+o>n.length)throw new Error(`erc8004: malformed ${t} RPC bounds`);return Buffer.from(n.slice(r+64,r+64+o),"hex").toString("utf8")}async function tk(e={},t={}){Pm(e,new Set(["chainId","agentId"]));let n=Mc(e.chainId),r=Am(e.agentId),o=_m(n);if(typeof t.rpcCall!="function")throw new Error("erc8004: reviewed rpcCall function required");let i=async d=>t.rpcCall("eth_call",[{to:o,data:GB(d,r)},"latest"]),[a,s,c]=await Promise.all([i(ur.ownerOf),i(ur.tokenURI),i(ur.getAgentWallet)]),l=ek(YB(s,"tokenURI")),u=null;return l.startsWith("data:application/json;base64,")&&(u=Uc(JSON.parse(Buffer.from(l.split(",")[1],"base64").toString("utf8")))),{chainId:n,registry:o,agentId:Number(r),owner:Kx(a,"owner"),tokenURI:l,agentURI:l,agentWallet:Kx(c,"agentWallet"),registration:u,readOnly:!0,custody:"public-keyless"}}cn();pe();var nk=999;async function rk(e={}){let t={chainId:nk,rpc:null,dex:null};try{t.rpc=await Er(nk,e)}catch(n){t.rpc={ok:!1,error:String(n.message||n).slice(0,120)}}try{let n=await Do("HYPE",e),r=(n.pairs||[]).filter(o=>/hyper|hl|hyperevm/i.test(String(o.chainId||o.chain||"")));t.dex={ok:!0,hypePairs:r.length||(n.pairs||[]).length,sample:(r[0]||n.pairs?.[0])?.pairAddress||null}}catch(n){t.dex={ok:!1,error:String(n.message||n).slice(0,120)}}return{ok:!!(t.rpc?.ok||t.dex?.ok),...t}}async function ok(e="HYPE",t={}){let r=(await Do(e,t)).pairs||[],o=r.filter(i=>/hyper|hl|hyperevm/i.test(String(i.chainId||"")));return{query:e,hyperPairs:o,allPairs:r.slice(0,20),count:o.length||r.length}}async function ik(e,t={}){return Tt(e,t)}R();vt();Y();var QB="https://api-mainnet.magiceden.dev/v2",ea=1e9;function ak(e={}){return Ae({provider:"magiceden",defaultUrl:QB,hosts:["api-mainnet.magiceden.dev","api-devnet.magiceden.dev"],url:e.baseUrl||process.env.MAGICEDEN_API_URL})}function eo(e={}){return ak(e).baseUrl}function dr(e={}){return e.apiKey||process.env.MAGICEDEN_API_KEY||""}function to(e={}){let t=dr(e);return Ie({accept:"application/json"},{Authorization:t?`Bearer ${t}`:""},ak(e).trusted)}function Cm(e){let t=String(e||"").trim();if(!/^[a-z0-9_]{1,64}$/i.test(t))throw new Error("magiceden: symbol must be a collection slug");return t}function Zr(e,t){if(typeof e=="number"){if(!Number.isFinite(e)||e<=0)throw new Error(`magiceden: ${t} must be a positive number`);return e}let n=String(e??"").trim();if(!/^\d+(\.\d+)?$/.test(n))throw new Error(`magiceden: ${t} must be a plain decimal number (no hex, exponent, or sign)`);let r=Number(n);if(!Number.isFinite(r)||r<=0)throw new Error(`magiceden: ${t} must be a positive number`);return r}function ZB(e){let t=[e?.price,e?.mintPrice,e?.priceSol,e?.v0?.price,e?.launchStageInfo?.price,e?.stage?.price];for(let n of t){if(n==null)continue;let r=Number(n);if(Number.isFinite(r)&&r>=0)return r}return e?.isFree===!0?0:null}function eM(e){return Math.round(Zr(e,"priceSol")*ea)}function tM(e){if(e==null||e==="")throw new Error("magiceden: listing expiry is required and must be in the future");let t=Number(e);if(!Number.isSafeInteger(t)||t<=0)throw new Error("magiceden: expiry must be a future Unix timestamp in seconds");if(t<=Math.floor(Date.now()/1e3))throw new Error("magiceden: expiry must be in the future");return t}function nM({tokenMint:e,priceSol:t,expiry:n}){return`list ${e} on magiceden-sol for ${t} SOL until ${n}`}function rM(e,t){if(e.userConfirmed!==!0)throw new Error("magiceden: listing requires userConfirmed=true after reviewing tokenMint, priceSol, and expiry");let n=nM(t);if(String(e.confirmation||e.confirmationPhrase||"").trim()!==n)throw new Error(`magiceden: confirmation must equal ${JSON.stringify(n)}`);return n}async function sk(e={}){try{let t=await Tm({symbol:"mad_lads"},e);return{ok:!0,provider:"magiceden-sol",keyed:!!dr(e),readTier:"keyless",prepareTier:dr(e)?"keyed":"requires MAGICEDEN_API_KEY",floorPriceSol:t.floorPriceSol,exec:!1}}catch(t){return{ok:!1,provider:"magiceden-sol",keyed:!!dr(e),error:String(t?.message||t).slice(0,160),exec:!1}}}async function Tm(e={},t={}){let n=Cm(e.symbol||e.collection),r=await S(`${eo(t)}/collections/${encodeURIComponent(n)}/stats`,{headers:to(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),o=Number(r?.floorPrice??0);return{provider:"magiceden-sol",chain:"solana-mainnet-beta",symbol:n,floorPriceLamports:o||null,floorPriceSol:o?o/ea:null,listedCount:r?.listedCount??null,volume24hrSol:r?.volume24hr!=null?Number(r.volume24hr)/ea:null,avgPrice24hrSol:r?.avgPrice24hr!=null?Number(r.avgPrice24hr)/ea:null,exec:!1,raw:r}}function ck(e={}){let t=Number(e.price??0);return{tokenMint:e.tokenMint??null,tokenATA:e.tokenAddress??null,seller:e.seller??null,sellerReferral:e.sellerReferral??null,auctionHouse:e.auctionHouse??null,pdaAddress:e.pdaAddress??null,priceSol:t||null,priceLamports:t?Math.round(t*ea):null,tokenSize:e.tokenSize??1}}async function lk(e={},t={}){let n=Cm(e.symbol||e.collection),r=Math.min(Math.max(Number(e.limit??20)||20,1),100),o=Math.max(Number(e.offset??0)||0,0),i=new URL(`${eo(t)}/collections/${encodeURIComponent(n)}/listings`);i.searchParams.set("offset",String(o)),i.searchParams.set("limit",String(r)),e.sort&&i.searchParams.set("sort",String(e.sort));let a=await S(i.toString(),{headers:to(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),s=(Array.isArray(a)?a:[]).map(ck);return{provider:"magiceden-sol",chain:"solana-mainnet-beta",symbol:n,count:s.length,listings:s,exec:!1}}async function uk(e={},t={}){let n=he(e.tokenMint||e.mint,"tokenMint"),r=await S(`${eo(t)}/tokens/${encodeURIComponent(n)}/listings`,{headers:to(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3}),o=(Array.isArray(r)?r:[]).map(ck);return{provider:"magiceden-sol",chain:"solana-mainnet-beta",tokenMint:n,listings:o,exec:!1}}async function dk(e={},t={}){if(!dr(t))throw new Error("magiceden: MAGICEDEN_API_KEY required to build a buy instruction");let n=he(e.buyer||e.userPublicKey,"buyer"),r=he(e.seller,"seller"),o=he(e.tokenMint,"tokenMint"),i=he(e.tokenATA||e.tokenAddress,"tokenATA"),a=he(e.auctionHouse,"auctionHouse"),s=Zr(e.priceSol??e.price,"priceSol"),c=e.maxPriceSol==null?s:Zr(e.maxPriceSol,"maxPriceSol");if(s>c)throw new Error(`magiceden: listing price ${s} SOL exceeds maxPriceSol cap ${c} SOL`);let l=new URL(`${eo(t)}/instructions/buy_now`);l.searchParams.set("buyer",n),l.searchParams.set("seller",r),l.searchParams.set("auctionHouseAddress",a),l.searchParams.set("tokenMint",o),l.searchParams.set("tokenATA",i),l.searchParams.set("price",String(s)),e.sellerReferral&&l.searchParams.set("sellerReferral",String(e.sellerReferral)),e.buyerReferral&&l.searchParams.set("buyerReferral",String(e.buyerReferral));let u=await S(l.toString(),{headers:to(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3});Yt("magiceden",u);let d=u?.v0?.tx?.data??u?.tx?.data??null;if(!Array.isArray(d))throw u?.txSigned?new Error("magiceden: refused a pre-signed transaction payload from the API"):new Error("magiceden: buy_now returned no unsigned transaction payload");let p=Buffer.from(d).toString("base64");return N({provider:"magiceden-sol",chain:"solana-mainnet-beta",kind:"nft-buy",prepareReady:!0,executionReady:!1,signingReady:!1,broadcastReady:!1,requiresUserSignature:!0,buyer:n,seller:r,tokenMint:o,priceSol:s,maxPriceSol:c,lamports:eM(s),transaction:p,transactionEncoding:"base64",raw:u})}async function Fc(e={},t={}){if(!dr(t))throw new Error("magiceden: MAGICEDEN_API_KEY required to build a list instruction");let n=he(e.seller||e.userPublicKey,"seller"),r=he(e.tokenMint,"tokenMint"),o=he(e.tokenATA||e.tokenAddress,"tokenATA"),i=he(e.auctionHouse,"auctionHouse"),a=Zr(e.priceSol??e.price,"priceSol"),s=tM(e.expiry),c=rM(e,{tokenMint:r,priceSol:a,expiry:s}),l=new URL(`${eo(t)}/instructions/sell`);l.searchParams.set("seller",n),l.searchParams.set("auctionHouseAddress",i),l.searchParams.set("tokenMint",r),l.searchParams.set("tokenAccount",o),l.searchParams.set("price",String(a)),e.sellerReferral&&l.searchParams.set("sellerReferral",he(e.sellerReferral,"sellerReferral")),s!=null&&l.searchParams.set("expiry",String(s));let u=await S(l.toString(),{headers:to(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3});Yt("magiceden",u);let d=u?.v0?.tx?.data??u?.tx?.data??null;if(!Array.isArray(d))throw u?.txSigned?new Error("magiceden: refused a pre-signed transaction payload from the API"):new Error("magiceden: sell returned no unsigned transaction payload");let p=Buffer.from(d).toString("base64");return N({provider:"magiceden-sol",chain:"solana-mainnet-beta",kind:"nft-list",prepareReady:!0,executionReady:!1,signingReady:!1,broadcastReady:!1,requiresUserSignature:!0,seller:n,tokenMint:r,priceSol:a,expiry:s,confirmation:c,transaction:p,transactionEncoding:"base64",raw:u})}async function pk(e={},t={}){if(!dr(t))throw new Error("magiceden: MAGICEDEN_API_KEY required to build a mint instruction");let n=he(e.buyer||e.userPublicKey,"buyer"),r=Cm(e.symbol||e.collection);if(e.maxPriceSol==null)throw new Error("magiceden: maxPriceSol is required to prepare a mint \u2014 an uncapped mint has no spend ceiling");let o=Zr(e.maxPriceSol,"maxPriceSol"),i=e.nftAmount==null?1:Zr(e.nftAmount,"nftAmount");if(!Number.isInteger(i))throw new Error("magiceden: nftAmount must be a whole number");let a=new URL(`${eo(t)}/instructions/mint`);a.searchParams.set("symbol",r),a.searchParams.set("wallet",n),a.searchParams.set("nftAmount",String(i));let s=await S(a.toString(),{headers:to(t),fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??15e3}),c=ZB(s);if(c==null)throw new Error("magiceden: mint price not present in the API response \u2014 refusing to prepare an unverifiable spend");let l=c*i;if(l>o)throw new Error(`magiceden: mint cost ${l} SOL exceeds maxPriceSol cap ${o} SOL`);Yt("magiceden",s);let u=s?.v0?.tx?.data??s?.tx?.data??null;if(!Array.isArray(u))throw s?.txSigned?new Error("magiceden: refused a pre-signed transaction payload from the API"):new Error("magiceden: mint returned no unsigned transaction payload");let d=Buffer.from(u).toString("base64");return N({provider:"magiceden-sol",chain:"solana-mainnet-beta",kind:"nft-mint",prepareReady:!0,executionReady:!1,signingReady:!1,broadcastReady:!1,requiresUserSignature:!0,buyer:n,symbol:r,nftAmount:i,priceSol:c,totalSol:l,maxPriceSol:o,transaction:d,transactionEncoding:"base64",raw:s})}Y();fp();R();dt();var no=8,Nm=10n**BigInt(no),iM="0xa4b1",mk=7,Om=1,aM=2n**64n-1n;function sM(e={}){return e.exchangeUrl?e.exchangeUrl:process.env.HL_EXCHANGE_URL?process.env.HL_EXCHANGE_URL:e.testnet||process.env.HL_TESTNET==="1"?"https://api.hyperliquid-testnet.xyz/exchange":"https://api.hyperliquid.xyz/exchange"}function na(e={}){return e.testnet||process.env.HL_TESTNET==="1"?"Testnet":"Mainnet"}function oo(e,t){let n=String(e||"").trim();if(!/^0x[0-9a-fA-F]{40}$/.test(n))throw new Error(`hl-staking: ${t} must be a 0x EVM address`);return n.toLowerCase()}function ta(e,t="amount"){let n=String(e??"").trim();if(!/^\d+(\.\d+)?$/.test(n))throw new Error(`hl-staking: ${t} must be a positive decimal HYPE amount`);let[r,o=""]=n.split(".");if(o.length>no)throw new Error(`hl-staking: ${t} has more than ${no} decimals`);let i=BigInt(r)*Nm+BigInt((o+"0".repeat(no)).slice(0,no)||"0");if(i<=0n)throw new Error(`hl-staking: ${t} must be greater than zero`);if(i>aM)throw new Error(`hl-staking: ${t} exceeds the uint64 range the signed action encodes`);return i.toString()}function ro(e){let t=BigInt(e);return t<=BigInt(Number.MAX_SAFE_INTEGER)?Number(t):e}function nn(e){let t=BigInt(String(e||"0")),n=t/Nm,r=(t%Nm).toString().padStart(no,"0").replace(/0+$/,"");return r?`${n}.${r}`:String(n)}async function fk(e={}){try{let t=await Rm(e);return{ok:t.count>0,provider:"hl-staking",chain:na(e),validators:t.count,exec:!1}}catch(t){return{ok:!1,provider:"hl-staking",error:String(t?.message||t).slice(0,160),exec:!1}}}async function Rm(e={}){let t=await de({type:"validatorSummaries"},e),r=(Array.isArray(t)?t:[]).map(o=>({validator:o.validator??null,name:o.name??null,isActive:o.isActive??null,isJailed:o.isJailed??null,commission:o.commission??null,stake:o.stake??null,nRecentBlocks:o.nRecentBlocks??null}));return{provider:"hl-staking",count:r.length,validators:r,exec:!1,raw:t}}async function Lm(e={},t={}){let n=oo(e.user||e.address,"user"),r=await de({type:"delegatorSummary",user:n},t);return{provider:"hl-staking",user:n,delegatedWei:r?.delegated??null,undelegatedWei:r?.undelegated??null,totalPendingWithdrawalWei:r?.totalPendingWithdrawal??null,nPendingWithdrawals:r?.nPendingWithdrawals??null,delegatedHype:r?.delegated!=null?String(r.delegated):null,undelegatedHype:r?.undelegated!=null?String(r.undelegated):null,exec:!1,raw:r}}async function $m(e={},t={}){let n=oo(e.user||e.address,"user"),r=await de({type:"delegations",user:n},t),o=Array.isArray(r)?r:[];return{provider:"hl-staking",user:n,count:o.length,delegations:o.map(i=>({validator:i.validator??null,amount:i.amount??null,lockedUntilTimestamp:i.lockedUntilTimestamp??null})),exec:!1,raw:r}}async function hk(e={},t={}){let n=oo(e.user||e.address,"user"),r=await de({type:"delegatorRewards",user:n},t);return{provider:"hl-staking",user:n,rewards:Array.isArray(r)?r:[],exec:!1}}async function gk(e={},t={}){let n=oo(e.user||e.address,"user"),r=await de({type:"delegatorHistory",user:n},t);return{provider:"hl-staking",user:n,history:Array.isArray(r)?r:[],exec:!1}}function Bm(e={}){let t=e.nonce==null?Date.now():Number(e.nonce);if(!Number.isInteger(t)||t<=0)throw new Error("hl-staking: nonce must be a positive integer ms timestamp");return t}function Dc(e={}){return String(e.signatureChainId||process.env.HL_SIGNATURE_CHAIN_ID||iM)}function cM(e={}){return{name:"HyperliquidSignTransaction",version:"1",chainId:Number(BigInt(Dc(e))),verifyingContract:"0x0000000000000000000000000000000000000000"}}function Mm({kind:e,action:t,types:n,primaryType:r,message:o,opts:i,notes:a,caps:s,args:c={}}){let l={provider:"hl-staking",venue:"hypercore",chain:na(i),kind:e,prepareReady:!0,executionReady:!1,signingReady:!1,broadcastReady:!1,requiresUserSignature:!0,signWith:"user wallet (EIP-712 typed data)",submitTo:sM(i),nonce:t.nonce,submitShape:{action:t,nonce:t.nonce,signature:"<user 65-byte signature>"},action:t,typedData:{domain:cM(i),types:n,primaryType:r,message:o},caps:s||null,notes:a,exec:!1};try{l.localSignerEnvelope=Js(l,c,i)}catch(u){l.localSignerBlockedReason=String(u?.message||u).slice(0,200)}return l.oraclePrepared=!!l.localSignerEnvelope,N(l,{provider:"hl-staking",kind:e})}function yk(e={},t={}){let n=ta(e.amountHype??e.amount,"amountHype"),r=e.maxHype==null?null:ta(e.maxHype,"maxHype");if(r&&BigInt(n)>BigInt(r))throw new Error(`hl-staking: amount ${nn(n)} HYPE exceeds maxHype cap ${nn(r)} HYPE`);let o=Bm(e),i=na(t),a={type:"cDeposit",hyperliquidChain:i,signatureChainId:Dc(t),wei:ro(n),nonce:o};return Mm({kind:"hype-stake-deposit",action:a,primaryType:"HyperliquidTransaction:CDeposit",types:{"HyperliquidTransaction:CDeposit":[{name:"hyperliquidChain",type:"string"},{name:"wei",type:"uint64"},{name:"nonce",type:"uint64"}]},message:{hyperliquidChain:i,wei:ro(n),nonce:o},opts:t,args:e,caps:{amountHype:nn(n),maxHype:r?nn(r):null},notes:["Moves HYPE from your Hyperliquid spot balance into your staking balance.","Staking balance still earns nothing until it is delegated to a validator.","Oracle prepared this. Your wallet signs it. Nothing was submitted."]})}function bk(e={},t={}){let n=ta(e.amountHype??e.amount,"amountHype"),r=Bm(e),o=na(t),i={type:"cWithdraw",hyperliquidChain:o,signatureChainId:Dc(t),wei:ro(n),nonce:r};return Mm({kind:"hype-stake-withdraw",action:i,primaryType:"HyperliquidTransaction:CWithdraw",types:{"HyperliquidTransaction:CWithdraw":[{name:"hyperliquidChain",type:"string"},{name:"wei",type:"uint64"},{name:"nonce",type:"uint64"}]},message:{hyperliquidChain:o,wei:ro(n),nonce:r},opts:t,args:e,caps:{amountHype:nn(n)},notes:[`Starts the ${mk} day unstaking queue back to spot. The HYPE is not liquid during the queue.`,"Undelegate from the validator first: only undelegated staking balance can be withdrawn.","Oracle prepared this. Your wallet signs it. Nothing was submitted."]})}function wk(e={},t={}){let n=oo(e.validator,"validator"),r=ta(e.amountHype??e.amount,"amountHype"),o=Object.prototype.hasOwnProperty.call(e,"isUndelegate"),i=Object.prototype.hasOwnProperty.call(e,"undelegate");if(o&&typeof e.isUndelegate!="boolean")throw new Error("hl-staking: isUndelegate must be a boolean");if(i&&typeof e.undelegate!="boolean")throw new Error("hl-staking: undelegate must be a boolean");if(o&&i&&e.isUndelegate!==e.undelegate)throw new Error("hl-staking: isUndelegate and undelegate must match");let a=o?e.isUndelegate:i?e.undelegate:!1,s=e.maxHype==null?null:ta(e.maxHype,"maxHype");if(!a&&s&&BigInt(r)>BigInt(s))throw new Error(`hl-staking: delegate amount ${nn(r)} HYPE exceeds maxHype cap ${nn(s)} HYPE`);let c=Bm(e),l=na(t),u={type:"tokenDelegate",hyperliquidChain:l,signatureChainId:Dc(t),validator:n,wei:ro(r),isUndelegate:a,nonce:c};return Mm({kind:a?"hype-undelegate":"hype-delegate",action:u,primaryType:"HyperliquidTransaction:TokenDelegate",types:{"HyperliquidTransaction:TokenDelegate":[{name:"hyperliquidChain",type:"string"},{name:"validator",type:"address"},{name:"wei",type:"uint64"},{name:"isUndelegate",type:"bool"},{name:"nonce",type:"uint64"}]},message:{hyperliquidChain:l,validator:n,wei:ro(r),isUndelegate:a,nonce:c},opts:t,args:e,caps:{amountHype:nn(r),maxHype:s?nn(s):null,validator:n},notes:a?["Returns stake from the validator to your staking balance.",`Delegations carry a ${Om} day validator lockup before they can be undelegated.`,"Oracle prepared this. Your wallet signs it. Nothing was submitted."]:["Delegates staking balance to the chosen validator so it starts earning.",`Once delegated, the stake is locked with that validator for ${Om} day.`,"Check the validator's commission and jail status before delegating.","Oracle prepared this. Your wallet signs it. Nothing was submitted."]})}async function vk(e={},t={}){let n=oo(e.user||e.address,"user"),r=await Lm({user:n},t),o=await $m({user:n},t);return{provider:"hl-staking",user:n,stakingBalanceUndelegated:r.undelegatedWei,stakingBalanceDelegated:r.delegatedWei,pendingWithdrawals:r.nPendingWithdrawals,delegations:o.delegations,unstakingQueueDays:mk,validatorLockupDays:Om,exec:!1}}dt();async function Um(e={}){let t=Date.now();try{let n=await xt(e);return{provider:"hl-markets",ok:!0,venue:"hyperliquid",symbols:Object.keys(n||{}).length,latencyMs:Date.now()-t}}catch(n){return{provider:"hl-markets",ok:!1,error:String(n?.message||n),latencyMs:Date.now()-t}}}var uM=24*365,dM=8;function Ue(e){if(e==null)return null;let t=Number(e);return Number.isFinite(t)?t:null}function pM(e,t){return e==null||t==null||t===0?null:(e-t)/t*100}async function io(e={},t={}){let[n,r]=await Promise.all([Ke(t),xt(t).catch(()=>({}))]),o=n?.[0]?.universe??n?.universe??[],i=Array.isArray(n?.[1])?n[1]:[],s=o.map((c,l)=>{let u=i[l]||{},d=Ue(u.markPx),p=Ue(u.prevDayPx),m=Ue(u.openInterest),f=Ue(u.funding);return{coin:c.name,index:l,markPx:d,oraclePx:Ue(u.oraclePx),midPx:Ue(u.midPx)??Ue(r?.[c.name]),prevDayPx:p,change24hPct:pM(d,p),dayNtlVolumeUsd:Ue(u.dayNtlVlm),premium:Ue(u.premium),fundingRate:f,fundingRateAprPct:f==null?null:f*(uM/dM)*100,openInterestCoin:m,openInterestUsd:m==null||d==null?null:m*d,maxLeverage:c.maxLeverage??null,szDecimals:c.szDecimals??null,isDelisted:!!c.isDelisted}}).filter(c=>!c.isDelisted);return{provider:"hl-info",venue:"hyperliquid",kind:"market-datapoints",asOfMs:Date.now(),count:s.length,markets:s,totals:{openInterestUsd:s.reduce((c,l)=>c+(l.openInterestUsd||0),0),dayNtlVolumeUsd:s.reduce((c,l)=>c+(l.dayNtlVolumeUsd||0),0)}}}async function xk(e={},t={}){let n=Math.max(1,Math.min(Number(e.limit)||10,50)),{markets:r,asOfMs:o,totals:i}=await io(e,t),a=(s,c=-1)=>r.filter(l=>l[s]!=null).sort((l,u)=>(l[s]-u[s])*c).slice(0,n);return{provider:"hl-info",venue:"hyperliquid",kind:"leaderboards",asOfMs:o,totals:i,gainers:a("change24hPct"),losers:a("change24hPct",1),byVolume:a("dayNtlVolumeUsd"),byOpenInterest:a("openInterestUsd"),fundingHighest:a("fundingRateAprPct"),fundingLowest:a("fundingRateAprPct",1)}}async function kk(e={},t={}){let n=String(e.coin||e.symbol||"").trim().toUpperCase();if(!n)throw new Error("hl-markets: coin required");let r=String(e.interval||"1h"),o=Number(e.lookbackMs)||1440*60*1e3,i=Date.now(),a=i-o,[s,c,l]=await Promise.all([io({},t),Hs({coin:n,interval:r,startTime:a,endTime:i},t).catch(()=>[]),Ur(n,t).catch(()=>null)]),u=s.markets.find(h=>h.coin===n)||null;if(!u)throw new Error(`hl-markets: ${n} is not a listed perp`);let d=(Array.isArray(c)?c:[]).map(h=>({t:Number(h.t),open:Ue(h.o),high:Ue(h.h),low:Ue(h.l),close:Ue(h.c),volume:Ue(h.v)})),p=l?.levels??[],m=Ue(p?.[0]?.[0]?.px),f=Ue(p?.[1]?.[0]?.px);return{provider:"hl-info",venue:"hyperliquid",kind:"coin-datapoints",asOfMs:Date.now(),coin:n,market:u,book:{bestBid:m,bestAsk:f,spread:m==null||f==null?null:f-m,spreadBps:m==null||f==null||f===0?null:(f-m)/f*1e4},candles:{interval:r,count:d.length,series:d}}}async function Sk(e={},t={}){let n=await js(t),r=n?.tokens??[],o=n?.universe??[];return{provider:"hl-info",venue:"hyperliquid",kind:"spot-datapoints",asOfMs:Date.now(),tokenCount:r.length,pairCount:o.length,tokens:r.map(i=>({name:i.name,index:i.index,szDecimals:i.szDecimals??null,weiDecimals:i.weiDecimals??null,tokenId:i.tokenId??null,isCanonical:!!i.isCanonical})),pairs:o.map(i=>({name:i.name,index:i.index,tokens:i.tokens,isCanonical:!!i.isCanonical}))}}import{mkdirSync as NM,readFileSync as OM,readdirSync as RM,renameSync as LM,writeFileSync as $M}from"node:fs";import{homedir as BM}from"node:os";import{join as Vc}from"node:path";var ra=Object.freeze({ALERT_ONLY:"alert_only",EXECUTE:"execute"});Kn();R();pe();Y();import{Interface as Fm,getAddress as Tk,isAddress as fM}from"ethers";var Ik=Object.freeze({42161:"https://arbitrum-api.gmxinfra.io",43114:"https://avalanche-api.gmxinfra.io"}),Ek=Object.freeze({42161:{name:"arbitrum",api:Ik[42161],exchangeRouter:"0x1C3fa76e6E1088bCE750f23a5BFcffa1efEF6A41",router:"0x7452c558d45f8afC8c83dAe62C3f8A5BE19c71f6",orderVault:"0x31eF83a530Fde1B38EE9A18093A333D8Bbbc40D5",dataStore:"0xFD70de6b91282D8017aA4E741e9Ae325CAb992d8",reader:"0x470fbC46bcC0f16532691Df360A07d8Bf5ee0789",eventEmitter:"0xC8ee91A54287DB53897056e12D9819156D3822Fb",wnt:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",usdc:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"},43114:{name:"avalanche",api:Ik[43114],exchangeRouter:"0x8f550E53DFe96C055D5Bdb267c21F268fCAF63B2",router:"0x820F5FfC5b525cD4d88Cd91aCf2c28F16530Cc68",orderVault:"0xD3D60D22d415aD43b7e64b510D86A30f19B1B12C",dataStore:"0x2F0b22339414ADeD7D5F06f9D604c7fF5b2fe3f6",reader:"0x62Cb8740E6986B29dC671B2EB596676f60590A5B",eventEmitter:"0xDb17B211c34240B014ab6d61d4A31FA0C0e20c26",wnt:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",usdc:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"}}),Ak="0x0000000000000000000000000000000000000000",hM=`0x${"0".repeat(64)}`,_k=Object.freeze({marketSwap:0,limitSwap:1,marketIncrease:2,limitIncrease:3,marketDecrease:4,limitDecrease:5,stopLossDecrease:6,stopIncrease:8}),Pk=Object.freeze({noSwap:0,swapPnlTokenToCollateralToken:1,swapCollateralTokenToPnlToken:2}),qc=new Fm(["function multicall(bytes[] data) payable returns (bytes[] results)","function sendTokens(address token,address receiver,uint256 amount) payable","function sendWnt(address receiver,uint256 amount) payable","function createOrder(((address receiver,address cancellationReceiver,address callbackContract,address uiFeeReceiver,address market,address initialCollateralToken,address[] swapPath) addresses,(uint256 sizeDeltaUsd,uint256 initialCollateralDeltaAmount,uint256 triggerPrice,uint256 acceptablePrice,uint256 executionFee,uint256 callbackGasLimit,uint256 minOutputAmount,uint256 validFromTime) numbers,uint8 orderType,uint8 decreasePositionSwapType,bool isLong,bool shouldUnwrapNativeToken,bool autoCancel,bytes32 referralCode,bytes32[] dataList) params) payable returns (bytes32)","function cancelOrder(bytes32 key) payable"]),Nk=new Fm(["function getAccountPositions(address dataStore,address account,uint256 start,uint256 end) view returns (bytes)","function getAccountOrders(address dataStore,address account,uint256 start,uint256 end) view returns (bytes)","function getOrder(address dataStore,bytes32 key) view returns (bytes)"]),gM=new Fm(["event EventLog1(address msgSender,string eventName,string indexed eventNameHash,bytes32 indexed topic1,((tuple(string key,address value)[] items,tuple(string key,address[] value)[] arrayItems),(tuple(string key,uint256 value)[] items,tuple(string key,uint256[] value)[] arrayItems),(tuple(string key,int256 value)[] items,tuple(string key,int256[] value)[] arrayItems),(tuple(string key,bool value)[] items,tuple(string key,bool[] value)[] arrayItems),(tuple(string key,bytes32 value)[] items,tuple(string key,bytes32[] value)[] arrayItems),(tuple(string key,bytes value)[] items,tuple(string key,bytes[] value)[] arrayItems),(tuple(string key,string value)[] items,tuple(string key,string[] value)[] arrayItems)) eventData)","event EventLog2(address msgSender,string eventName,string indexed eventNameHash,bytes32 indexed topic1,bytes32 indexed topic2,((tuple(string key,address value)[] items,tuple(string key,address[] value)[] arrayItems),(tuple(string key,uint256 value)[] items,tuple(string key,uint256[] value)[] arrayItems),(tuple(string key,int256 value)[] items,tuple(string key,int256[] value)[] arrayItems),(tuple(string key,bool value)[] items,tuple(string key,bool[] value)[] arrayItems),(tuple(string key,bytes32 value)[] items,tuple(string key,bytes32[] value)[] arrayItems),(tuple(string key,bytes value)[] items,tuple(string key,bytes[] value)[] arrayItems),(tuple(string key,string value)[] items,tuple(string key,string[] value)[] arrayItems)) eventData)"]),yM=Object.freeze({OrderCreated:"created",OrderUpdated:"updated",OrderExecuted:"executed",OrderCancelled:"cancelled",OrderFrozen:"frozen"});function so(e){let t=Number(e??42161),n=Ek[t];if(!n)throw new Error(`gmx: unsupported chainId ${e} (supported: ${Object.keys(Ek).join(", ")})`);return{chainId:t,...n}}function Hc(e,t={}){let n=so(e);return(t.baseUrl||n.api).replace(/\/$/,"")}function gt(e,t){if(!fM(e))throw new Error(`${t} must be a valid EVM address`);return Tk(e)}function re(e){return Tk(e).toLowerCase()}function ao(e,t){let n;try{n=BigInt(String(e))}catch{throw new Error(`${t} must be an integer string`)}if(n<=0n)throw new Error(`${t} must be positive`);return n}function pr(e,t){let n;try{n=BigInt(String(e??"0"))}catch{throw new Error(`${t} must be an integer string`)}if(n<0n)throw new Error(`${t} must be non-negative`);return n}function bM(e,t=50){let n=Number(e??t);if(!Number.isFinite(n)||n<0||n>100)throw new Error("gmx maxSlippageBps must be 0..100");return Math.floor(n)}function wM(e){let t=String(e||"marketIncrease").trim();if(!(t in _k))throw new Error(`gmx unsupported orderType ${t}`);if(!["marketIncrease","marketDecrease"].includes(t))throw new Error("gmx prepare currently supports marketIncrease and marketDecrease only");return{key:t,code:_k[t]}}function vM(e){let t=String(e||"noSwap").trim();if(!(t in Pk))throw new Error(`gmx unsupported decreasePositionSwapType ${t}`);return{key:t,code:Pk[t]}}function xM(e,t){return Array.isArray(e)?e:Array.isArray(e?.[t])?e[t]:[]}function kM(e,t){let n=re(t);return e.find(r=>re(r.marketToken||r.market||r.address)===n)||null}function SM(e,t){let n=re(t);return e.find(r=>re(r.tokenAddress||r.address)===n)||null}function IM({ticker:e,isLong:t,typeKey:n,maxSlippageBps:r}){let o=ao(e?.minPrice,"gmx minPrice"),i=ao(e?.maxPrice,"gmx maxPrice"),a=BigInt(r),s=10000n;return n==="marketIncrease"?(t?i*(s+a)/s:o*(s-a)/s).toString():(t?o*(s-a)/s:i*(s+a)/s).toString()}function EM(e,t){let n=t?e.availableLiquidityLong:e.availableLiquidityShort;try{return BigInt(String(n??"0"))}catch{return 0n}}function AM(e){let t=String(e||"").toLowerCase();return/^0x[0-9a-f]{64}$/.test(t)?`0x${t.slice(-40)}`:null}function $t(e,t,n=r=>r){let o=Array.from(e?.items||e?.[0]||[]).find(i=>String(i?.key??i?.[0]??"")===t);return o?n(o.value??o[1]):null}function _M(e={}){let t=e.addressItems||e[0],n=e.uintItems||e[1],r=e.boolItems||e[3],o=e.bytes32Items||e[4],i=e.stringItems||e[6];return{account:$t(t,"account",a=>re(a)),market:$t(t,"market",a=>re(a)),initialCollateralToken:$t(t,"initialCollateralToken",a=>re(a)),key:$t(o,"key",a=>String(a).toLowerCase()),reason:$t(i,"reason",a=>String(a)),sizeDeltaUsd:$t(n,"sizeDeltaUsd",a=>BigInt(a).toString()),initialCollateralDeltaAmount:$t(n,"initialCollateralDeltaAmount",a=>BigInt(a).toString()),executionFee:$t(n,"executionFee",a=>BigInt(a).toString()),acceptablePrice:$t(n,"acceptablePrice",a=>BigInt(a).toString()),isLong:$t(r,"isLong",a=>!!a)}}function PM(e={},t){if(re(e.address)!==re(t.eventEmitter))return null;let n;try{n=gM.parseLog({topics:e.topics,data:e.data})}catch{return null}let r=String(n?.args?.eventName||""),o=yM[r];if(!o)return null;let i=_M(n.args.eventData||{}),a=(i.key||String(n.args.topic1||"")).toLowerCase(),s=i.account||AM(n.args.topic2);return{eventName:r,status:o,orderKey:a,account:s?re(s):null,market:i.market,initialCollateralToken:i.initialCollateralToken,sizeDeltaUsd:i.sizeDeltaUsd,initialCollateralDeltaAmount:i.initialCollateralDeltaAmount,executionFee:i.executionFee,acceptablePrice:i.acceptablePrice,isLong:i.isLong,reason:i.reason,logIndex:e.logIndex==null?null:Number.parseInt(String(e.logIndex),16)}}function Ck(e){return{executed:5,cancelled:4,frozen:3,created:2,updated:1}[e]||0}function CM(e=[],{chainId:t}={}){let n=so(t);return(Array.isArray(e)?e:[]).map(r=>PM(r,n)).filter(Boolean).sort((r,o)=>(r.logIndex??0)-(o.logIndex??0))}async function Ok(e={},t={}){return S(`${Hc(e.chainId??42161,t)}/markets`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4})}async function Dm(e={},t={}){return S(`${Hc(e.chainId??42161,t)}/markets/info`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4})}async function Rk(e={},t={}){return S(`${Hc(e.chainId??42161,t)}/tokens`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4})}async function Tn(e={},t={}){return S(`${Hc(e.chainId??42161,t)}/prices/tickers`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4})}async function Lk(e={}){let t=await Tn({chainId:42161},e);return{ok:Array.isArray(t)&&t.length>0,tickerSample:Array.isArray(t)?t.length:0}}async function $k(e={},t={}){let n=so(e.chainId??42161),r=gt(e.account||e.owner||e.user,"gmx account"),o=pr(e.start??0,"gmx start"),i=pr(e.end??e.limit??20,"gmx end"),a=Nk.encodeFunctionData("getAccountPositions",[n.dataStore,r,o,i]),c=await(t.rpcCall||D)(n.chainId,"eth_call",[{to:n.reader,data:a},e.blockTag||"latest"],t);return{provider:"gmx",chainId:n.chainId,reader:re(n.reader),dataStore:re(n.dataStore),account:re(r),raw:c}}async function Bk(e={},t={}){let n=so(e.chainId??42161),r=String(e.key||e.orderKey||"").trim();if(!/^0x[0-9a-fA-F]{64}$/.test(r))throw new Error("gmx order key must be bytes32 hex");let o=Nk.encodeFunctionData("getOrder",[n.dataStore,r]),a=await(t.rpcCall||D)(n.chainId,"eth_call",[{to:n.reader,data:o},e.blockTag||"latest"],t);return{provider:"gmx",chainId:n.chainId,reader:re(n.reader),dataStore:re(n.dataStore),key:r,raw:a}}async function Mk(e={},t={}){let n=so(e.chainId??42161),r=t.receipt||await Fo({chainId:n.chainId,txHash:e.txHash,expectedTo:e.expectedTo||n.exchangeRouter},t),o=String(e.txHash||r.txHash||"").toLowerCase();if(r.ok!==!0)return{ok:!1,provider:"gmx",chainId:n.chainId,txHash:o,status:r.status||"unknown",reason:r.reason||"receipt not successful",receipt:r};let i=CM(r.logs||[],{chainId:n.chainId}),a=e.expectedOrderKey||e.orderKey?String(e.expectedOrderKey||e.orderKey).toLowerCase():null,s=a?i.filter(u=>u.orderKey===a):i;if(s.length===0)return{ok:!1,provider:"gmx",chainId:n.chainId,txHash:o,status:"unknown",reason:a?"order key not found in GMX EventEmitter logs":"no GMX order lifecycle event found",events:i,receipt:r};let c=s.reduce((u,d)=>Ck(d.status)>=Ck(u.status)?d:u,s[0]),l=e.expectedAccount||e.account?re(e.expectedAccount||e.account):null;return l&&c.account!==l?{ok:!1,provider:"gmx",chainId:n.chainId,txHash:o,status:c.status,reason:`account mismatch: expected ${l}, got ${c.account||"null"}`,orderKey:c.orderKey,account:c.account,events:i,receipt:r}:{ok:!0,provider:"gmx",chainId:n.chainId,txHash:o,status:c.status,orderKey:c.orderKey,account:c.account,market:c.market,eventEmitter:re(n.eventEmitter),events:s,receipt:r}}async function jc(e={},t={}){let n=so(e.chainId??42161),r=wM(e.orderType||e.type),o=vM(e.decreasePositionSwapType),i=gt(e.account||e.owner||e.from||e.sender||e.receiver,"gmx account"),a=gt(e.receiver||i,"gmx receiver"),s=gt(e.cancellationReceiver||a,"gmx cancellationReceiver"),c=e.callbackContract?gt(e.callbackContract,"gmx callbackContract"):Ak,l=e.uiFeeReceiver?gt(e.uiFeeReceiver,"gmx uiFeeReceiver"):Ak,u=gt(e.market||e.marketToken,"gmx market"),d=gt(e.initialCollateralToken||e.collateralToken||n.usdc,"gmx initialCollateralToken"),p=r.key==="marketIncrease"?ao(e.initialCollateralDeltaAmount??e.collateralAmount??e.amountIn,"gmx initialCollateralDeltaAmount"):pr(e.initialCollateralDeltaAmount??e.collateralAmount??"0","gmx initialCollateralDeltaAmount"),m=ao(e.sizeDeltaUsd,"gmx sizeDeltaUsd"),f=ao(e.executionFee,"gmx executionFee"),h=BigInt(String(e.maxExecutionFeeWei??"10000000000000000"));if(f>h)throw new Error("gmx executionFee exceeds maxExecutionFeeWei");let g=BigInt(String(e.maxSizeDeltaUsd??"50000000000000000000000000000000000"));if(m>g)throw new Error("gmx sizeDeltaUsd exceeds maxSizeDeltaUsd");let w=bM(e.maxSlippageBps??e.slippageBps,50),x=e.isLong==null?!0:!!e.isLong,[b,y]=await Promise.all([Dm({chainId:n.chainId},t),Tn({chainId:n.chainId},t)]),k=kM(xM(b,"markets"),u);if(!k)throw new Error("gmx market not found in public registry");if(k.isListed===!1)throw new Error("gmx market is not listed");let E=gt(k.indexToken,"gmx market indexToken"),I=gt(k.longToken,"gmx market longToken"),v=gt(k.shortToken,"gmx market shortToken"),A=re(d);if(![re(I),re(v)].includes(A))throw new Error("gmx collateral token must match market longToken or shortToken for this guarded slice");let P=EM(k,x);if(P>0n&&m>P)throw new Error("gmx sizeDeltaUsd exceeds available market liquidity");let T=SM(y,E);if(!T)throw new Error("gmx index ticker not found");let L=e.acceptablePrice?ao(e.acceptablePrice,"gmx acceptablePrice").toString():IM({ticker:T,isLong:x,typeKey:r.key,maxSlippageBps:w}),F=(e.swapPath||[]).map(ge=>gt(ge,"gmx swapPath market"));if(F.length>3)throw new Error("gmx swapPath too long for guarded slice");let q=pr(e.triggerPrice??"0","gmx triggerPrice"),O=pr(e.callbackGasLimit??"0","gmx callbackGasLimit"),H=pr(e.minOutputAmount??"0","gmx minOutputAmount"),B=pr(e.validFromTime??"0","gmx validFromTime"),z=!!e.shouldUnwrapNativeToken,le=e.autoCancel==null?!0:!!e.autoCancel,ue=String(e.referralCode||hM);if(!/^0x[0-9a-fA-F]{64}$/.test(ue))throw new Error("gmx referralCode must be bytes32 hex");let Ut=Array.isArray(e.dataList)?e.dataList:[];for(let ge of Ut)if(!/^0x[0-9a-fA-F]{64}$/.test(String(ge)))throw new Error("gmx dataList entries must be bytes32 hex");let an={addresses:{receiver:a,cancellationReceiver:s,callbackContract:c,uiFeeReceiver:l,market:u,initialCollateralToken:d,swapPath:F},numbers:{sizeDeltaUsd:m,initialCollateralDeltaAmount:p,triggerPrice:q,acceptablePrice:BigInt(L),executionFee:f,callbackGasLimit:O,minOutputAmount:H,validFromTime:B},orderType:r.code,decreasePositionSwapType:o.code,isLong:x,shouldUnwrapNativeToken:z,autoCancel:le,referralCode:ue,dataList:Ut},$=[];r.key==="marketIncrease"&&p>0n&&$.push(qc.encodeFunctionData("sendTokens",[d,n.orderVault,p])),$.push(qc.encodeFunctionData("sendWnt",[n.orderVault,f])),$.push(qc.encodeFunctionData("createOrder",[an]));let U=qc.encodeFunctionData("multicall",[$]),ee={mode:"gmx-order",provider:"gmx",chainId:n.chainId,chain:n.name,orderType:r.key,orderTypeCode:r.code,decreasePositionSwapType:o.key,account:re(i),receiver:re(a),exchangeRouter:re(n.exchangeRouter),router:re(n.router),orderVault:re(n.orderVault),market:re(u),indexToken:re(E),initialCollateralToken:re(d),initialCollateralDeltaAmount:p.toString(),sizeDeltaUsd:m.toString(),executionFee:f.toString(),acceptablePrice:L,maxSlippageBps:w,isLong:x,asyncExecution:!0,issuedAtMs:Number(t.nowMs??Date.now())};return N({provider:"gmx",chainId:n.chainId,chain:n.name,orderReady:!0,executionReady:!1,asyncExecution:!0,orderType:r.key,market:re(u),requiresApproval:r.key==="marketIncrease"&&p>0n?{token:re(d),spender:re(n.router),amount:p.toString()}:null,gmxGuard:ee,transaction:{chainId:n.chainId,from:re(i),to:re(n.exchangeRouter),data:U,value:f.toString(),gmxGuard:ee}},{provider:"gmx",kind:"gmx-order"})}dt();var Nn="oracle.hl.entry-state.v1",MM=8,UM=24*365;function me(e){if(e==null||e==="")return null;let t=Number(e);return Number.isFinite(t)?t:null}function co(e){return e==null||e===0?0:e>0?1:-1}function oa(e,t){return e==null||t==null||t===0?null:(e-t)/t*1e4}function FM(e={}){return e.configDir||process.env.ORACLE_CONFIG_DIR||Vc(BM(),".config","oracle")}function Dk(e={}){return Vc(FM(e),"hl-entry-states")}function zc(e,t,n){return n==null&&e.push(t),n}function DM(e,t){let n=String(t||"").toUpperCase(),r=e?.[0]?.universe??e?.universe??[],o=Array.isArray(e?.[1])?e[1]:[],i=r.findIndex(a=>String(a?.name||"").toUpperCase()===n);return i<0?null:{asset:r[i],ctx:o[i]||{},index:i}}function rn(e,t){return{source:e,asOfMs:null,unknown:!0,reason:t||"unavailable"}}function qM(e,{coin:t,asOfMs:n}={}){let o=(Array.isArray(e)?e:[]).map(a=>({t:me(a.time),rate:me(a.fundingRate)})).filter(a=>a.t!=null&&a.rate!=null).sort((a,s)=>a.t-s.t);if(!o.length)return rn("hl-info.fundingHistory","empty");let i=0;for(let a=1;a<o.length;a+=1)co(o[a].rate)!==co(o[a-1].rate)&&(i+=1);return{source:"hl-info.fundingHistory",asOfMs:n??o[o.length-1].t,unknown:!1,coin:t||null,samples:o.length,firstRate:o[0].rate,lastRate:o[o.length-1].rate,signFlips:i,windowMs:o[o.length-1].t-o[0].t}}function HM(e,t=Date.now()){let n=e?.peggedAssets;if(!Array.isArray(n)||!n.length)return rn("defillama.stablecoins","empty");let r=0,o=0;for(let i of n){let a=i.circulating||{},s=me(a.peggedUSD??a.usd??i.circulatingPrevDay?.peggedUSD);s!=null&&(r+=s,o+=1)}return o?{source:"defillama.stablecoins",asOfMs:t,unknown:!1,assets:o,mcapUsd:r}:rn("defillama.stablecoins","no peggedUSD")}function Uk(e,t){let n=me(e);if(n==null)return null;if(t!=null&&t>0){for(let r of[1,1e12,1e22,1e30]){let o=n/r;if(o>t*.5&&o<t*1.5)return o}return null}return n>1e20?n/1e22:n>1e12?n/1e30:n}function jM(e,{coin:t,hlMark:n,asOfMs:r}={}){let o=Array.isArray(e)?e:[],i=String(t||"").toUpperCase(),a=i==="BTC"?["BTC","WBTC","BTC.B"]:i==="ETH"?["ETH","WETH"]:[i],s=o.find(p=>a.includes(String(p.tokenSymbol||p.symbol||"").toUpperCase()));if(!s)return rn("gmx.tickers","no matching symbol");let c=Uk(s.minPrice,n),l=Uk(s.maxPrice,n),u=c==null||l==null?null:(c+l)/2;if(u==null||u<=0)return rn("gmx.tickers","unreadable price");let d=n!=null&&n>0?oa(u,n):null;return n!=null&&(u<n*.5||u>n*1.5)?rn("gmx.tickers","price scale mismatch"):{source:"gmx.tickers",asOfMs:r??Date.now(),unknown:!1,chainId:42161,symbol:String(s.tokenSymbol||s.symbol),minPx:c,maxPx:l,midPx:u,hlMark:n??null,basisBps:d}}function zM({coin:e,hlMark:t,asOfMs:n,fundingHistory:r=null,llamaStables:o=null,gmxTickers:i=null}={}){return{fundingPath:r==null?rn("hl-info.fundingHistory","not fetched"):qM(r,{coin:e,asOfMs:n}),llamaStables:o==null?rn("defillama.stablecoins","not fetched"):HM(o,n),gmxTicker:i==null?rn("gmx.tickers","not fetched"):jM(i,{coin:e,hlMark:t,asOfMs:n})}}function Fk(e,t,n){let r=Array.isArray(e)?e:[],o=0,i=0;for(let s of r){let c=me(s?.px),l=me(s?.sz);if(c==null||l==null||c<=0||l<=0)continue;let u=c*l,d=Math.min(u,Math.max(0,t-o));if(d<=0||(i+=d/c,o+=d,o>=t))break}let a=i>0?o/i:null;return{side:n,requestedNotionalUsd:t,fillableUsd:o,fillable:o+1e-9>=t,avgFillPx:a}}function VM(e,t){if(!e)return{present:!1,unknown:["userState"]};let n=String(t).toUpperCase(),i=(e.assetPositions||e.clearinghouseState?.assetPositions||[]).find(f=>String(f?.position?.coin||"").toUpperCase()===n)?.position;if(!i)return{present:!1,unknown:[]};let a=me(i.szi),s=me(i.positionValue)!=null&&a?Math.abs(me(i.positionValue)/a):null,c=me(i.entryPx),l=me(i.liquidationPx),u=a==null?null:a>0?"long":a<0?"short":null,d=null,p=s??c;l!=null&&p!=null&&p!==0&&u==="long"?d=(p-l)/p*100:l!=null&&p!=null&&p!==0&&u==="short"&&(d=(l-p)/p*100);let m=[];return a==null&&m.push("position.szi"),c==null&&m.push("position.entryPx"),l==null&&m.push("position.liquidationPx"),d==null&&m.push("position.liqDistancePct"),{present:!0,side:u,szi:a,entryPx:c,liquidationPx:l,leverage:me(i.leverage?.value??i.leverage),liqDistancePct:d,unknown:m}}function WM({coin:e,notionalUsd:t=1e4,meta:n,book:r,userState:o=null,priorOiCoin:i=null,asOfMs:a=Date.now(),fundingHistory:s=null,llamaStables:c=null,gmxTickers:l=null}={}){let u=[];if(!e)return{schema:Nn,venue:"hyperliquid",coin:null,asOfMs:a,unknown:["coin"],verdict:"no"};let d=DM(n,e);if(!d)return{schema:Nn,venue:"hyperliquid",coin:String(e).toUpperCase(),asOfMs:a,unknown:["market"],verdict:"no"};let{asset:p,ctx:m}=d,f=zc(u,"markPx",me(m.markPx)),h=zc(u,"oraclePx",me(m.oraclePx)),g=me(m.midPx),w=me(m.premium),x=zc(u,"fundingRate",me(m.funding)),b=zc(u,"openInterestCoin",me(m.openInterest)),y=me(m.dayNtlVlm),k=Array.isArray(m.impactPxs)?m.impactPxs:[],E=me(k[0]),I=me(k[1]),v=x==null?null:x*(UM/MM)*100,A=b==null||f==null?null:b*f,P=i==null||i===0||b==null?null:(b-i)/i*100;P==null&&u.push("oiDeltaPct");let T=r?.levels,L=Array.isArray(T)?T[0]:[],F=Array.isArray(T)?T[1]:[],q=me(L?.[0]?.px),O=me(F?.[0]?.px);q==null&&u.push("book.bidPx"),O==null&&u.push("book.askPx");let H=Fk(F,Number(t)||0,"buy"),B=Fk(L,Number(t)||0,"sell");H.fillable||u.push("book.buyFillable"),B.fillable||u.push("book.sellFillable");let z=g??f,le=H.avgFillPx==null||z==null?null:oa(H.avgFillPx,z),ue=B.avgFillPx==null||z==null?null:oa(z,B.avgFillPx),Ut=VM(o,e);for(let ee of Ut.unknown||[])u.push(ee);let an=me(m.prevDayPx),$=f==null||an==null||an===0?null:(f-an)/an*100;$==null&&u.push("change24hPct");let U=zM({coin:String(p.name),hlMark:f,asOfMs:a,fundingHistory:s,llamaStables:c,gmxTickers:l});return U.fundingPath.unknown&&u.push("overlays.fundingPath"),U.llamaStables.unknown&&u.push("overlays.llamaStables"),U.gmxTicker.unknown&&u.push("overlays.gmxTicker"),{schema:Nn,venue:"hyperliquid",coin:String(p.name),asOfMs:a,markPx:f,oraclePx:h,midPx:g,premium:w,markOracleBps:oa(f,h),fundingRate:x,fundingAprPct:v,openInterestCoin:b,openInterestUsd:A,oiDeltaPct:P,dayNtlVolumeUsd:y,change24hPct:$,impactBidPx:E,impactAskPx:I,maxLeverage:p.maxLeverage??null,book:{bidPx:q,askPx:O,spreadBps:q==null||O==null?null:oa(O,q),notionalUsd:Number(t)||0,buy:H,sell:B,buySlipBps:le,sellSlipBps:ue},position:Ut,overlays:U,unknown:u,verdict:u.includes("market")?"no":u.length?"wait":"go"}}function qk(e,t){let n=String(t||"").toLowerCase();if(n!=="long"&&n!=="short")return{side:null,verdict:"no",factors:[{key:"side",status:"unverifiable",note:"side must be long or short"}]};if(!e?.coin||e.verdict==="no")return{side:n,verdict:"no",factors:[{key:"market",status:"unverifiable",note:"no live market"}]};let r=[],o=e.fundingRate;o==null?r.push({key:"funding",status:"unverifiable",note:"fundingRate unknown"}):n==="long"?r.push({key:"funding",status:o>0?"counter":(o<0,"aligned"),note:o>0?"longs pay":"shorts pay / flat",fundingAprPct:e.fundingAprPct}):r.push({key:"funding",status:o<0?"counter":"aligned",note:o<0?"shorts pay":"longs pay / flat",fundingAprPct:e.fundingAprPct});let i=e.premium??(e.markOracleBps==null?null:e.markOracleBps/1e4);i==null?r.push({key:"premium",status:"unverifiable",note:"mark vs oracle unknown"}):n==="long"?r.push({key:"premium",status:i>0?"counter":"aligned",note:i>0?"mark rich to oracle":"mark cheap / flat"}):r.push({key:"premium",status:i<0?"counter":"aligned",note:i<0?"mark cheap to oracle":"mark rich / flat"});let a=n==="long"?e.book?.buy:e.book?.sell;if(!a)r.push({key:"book",status:"unverifiable",note:"no book walk"});else if(!a.fillable)r.push({key:"book",status:"counter",note:`cannot fill ${a.requestedNotionalUsd} usd`});else{let f=n==="long"?e.book.buySlipBps:e.book.sellSlipBps;r.push({key:"book",status:f!=null&&f>20?"counter":"aligned",note:f==null?"fillable, slip unknown":`slip ${f.toFixed(1)} bps`})}let s=e.position?.liqDistancePct;e.position?.present?s==null?r.push({key:"liqDistancePct",status:"unverifiable",note:"liquidationPx unknown"}):r.push({key:"liqDistancePct",status:s<5?"counter":"aligned",note:`${s.toFixed(2)}% to liq`}):r.push({key:"liqDistancePct",status:"unverifiable",note:"no position / no user"}),e.oiDeltaPct==null&&r.push({key:"oiDeltaPct",status:"unverifiable",note:"no prior OI \u2014 HL /info has no 24h OI"});let c=e.overlays?.fundingPath;!c||c.unknown?r.push({key:"fundingPath",status:"unverifiable",note:c?.reason||"funding history unknown"}):r.push({key:"fundingPath",status:c.signFlips>0?"unverifiable":"aligned",note:c.signFlips>0?`${c.signFlips} funding sign flip(s) in window`:`carry stable n=${c.samples}`});let l=e.overlays?.gmxTicker;!l||l.unknown?r.push({key:"gmxBasis",status:"unverifiable",note:l?.reason||"gmx ticker unknown"}):l.basisBps!=null&&Math.abs(l.basisBps)>80?r.push({key:"gmxBasis",status:"counter",note:`HL vs GMX ${l.basisBps.toFixed(1)} bps`}):r.push({key:"gmxBasis",status:"aligned",note:l.basisBps==null?"gmx print, no HL mark":`HL vs GMX ${l.basisBps.toFixed(1)} bps`});let u=r.some(f=>f.key==="book"&&f.status==="counter"&&/cannot fill/.test(f.note)),d=r.some(f=>f.status==="counter"),p=r.some(f=>f.status==="unverifiable");return{side:n,verdict:u?"no":d||p?"wait":"go",factors:r,seeUnknown:e.unknown||[]}}function GM(e){let t=String(e?.hash||e?.txHash||"").trim(),n=e?.oid,r=e?.tid;if(t)return{kind:e.kind||"hl-fill",hash:t};if(n!=null&&r!=null)return{kind:e.kind||"hl-fill",oid:n,tid:r,time:e.time??null};throw new Error("entry snapshot refused: no receipt (need hash or oid+tid)")}function KM({see:e,side:t,receipt:n,configDir:r}={},o={}){if(!e||e.schema!==Nn||!e.coin)throw new Error("entry snapshot refused: SEE object missing");let i=GM(n),a=qk(e,t);if(!a.side)throw new Error("entry snapshot refused: side must be long or short");let s={schema:Nn,id:`${e.coin}-${i.hash||`${i.oid}-${i.tid}`}`,lockedAtMs:Date.now(),side:a.side,receipt:i,see:e,qualify:a,actionMode:ra.ALERT_ONLY},c=Dk({...o,configDir:r||o.configDir});NM(c,{recursive:!0,mode:448});let l=Vc(c,`${s.id}.json`),u=`${l}.${process.pid}.tmp`;return $M(u,`${JSON.stringify(s,null,2)}
|
|
148
148
|
`,{mode:384}),LM(u,l),s}function qm(e={}){let t=Dk(e),n=[];try{n=RM(t).filter(r=>r.endsWith(".json"))}catch{return[]}return n.map(r=>JSON.parse(OM(Vc(t,r),"utf8")))}function YM(e,t){let n=[];if(!e?.see||!t)return{alerts:n,actionMode:ra.ALERT_ONLY};let r=e.see,o=t;co(r.fundingRate)!==co(o.fundingRate)&&r.fundingRate!=null&&o.fundingRate!=null&&n.push({key:"fundingSign",level:"thesis-broke",from:r.fundingRate,to:o.fundingRate}),co(r.premium)!==co(o.premium)&&r.premium!=null&&o.premium!=null&&n.push({key:"premiumSign",level:"hold",from:r.premium,to:o.premium});let i=r.position?.liqDistancePct,a=o.position?.liqDistancePct;i!=null&&a!=null&&(a<5||a<i*.7)&&n.push({key:"liqDistancePct",level:"thesis-broke",from:i,to:a});let s=e.side,c=s==="long"?r.book?.buy:r.book?.sell,l=s==="long"?o.book?.buy:o.book?.sell;c?.fillable&&l&&!l.fillable&&n.push({key:"bookFillable",level:"thesis-broke",from:!0,to:!1});let u=o.oiDeltaPct;return u!=null&&Math.abs(u)>=15&&n.push({key:"oiDeltaPct",level:"hold",from:0,to:u}),{schema:Nn,id:e.id,coin:e.see.coin,side:e.side,actionMode:ra.ALERT_ONLY,alerts:n,verdict:n.some(d=>d.level==="thesis-broke")?"thesis-broke":n.length?"hold":"hold-ok",live:t}}async function Hk(e={}){let t=Date.now();try{return{provider:"hl-entry-state",ok:!!(await Ke(e))?.[0]?.universe?.length,venue:"hyperliquid",latencyMs:Date.now()-t}}catch(n){return{provider:"hl-entry-state",ok:!1,error:String(n?.message||n),latencyMs:Date.now()-t}}}async function ia(e={},t={}){let n=e.coin,r=me(e.notionalUsd)??1e4,o=Date.now(),[i,a,s,c,l,u]=await Promise.all([Ke(t),n?Ur(n,t).catch(()=>null):Promise.resolve(null),e.user?Fr(e.user,t).catch(()=>null):Promise.resolve(null),n?lb({coin:n,startTime:o-24*3600*1e3,endTime:o},t).catch(()=>null):Promise.resolve(null),vs({},t).catch(()=>null),Tn({chainId:42161},t).catch(()=>null)]);return WM({coin:n,notionalUsd:r,meta:i,book:a,userState:s,priorOiCoin:me(e.priorOiCoin),asOfMs:o,fundingHistory:c,llamaStables:l,gmxTickers:u})}async function jk(e={},t={}){let n=e.see&&e.see.schema===Nn?e.see:await ia(e,t);return{see:n,...qk(n,e.side)}}async function zk(e={},t={}){let n=e.see&&e.see.schema===Nn?e.see:await ia(e,t);return KM({see:n,side:e.side,receipt:e.receipt,configDir:t.configDir},t)}async function Vk(e={},t={}){let n=e.locked||qm(t).find(o=>o.id===e.id||o.see?.coin===e.coin);if(!n)return{ok:!1,error:"no locked entry",actionMode:ra.ALERT_ONLY};let r=await ia({coin:n.see.coin,notionalUsd:n.see.book?.notionalUsd,user:e.user,priorOiCoin:n.see.openInterestCoin},t);return YM(n,r)}dt();Ys();xi();async function Wk(e={}){let t=await di(e);return{provider:"hl-outcome",kind:"outcome-meta",outcomes:t?.outcomes||[],questions:t?.questions||[]}}async function Gk(e={},t={}){let n=e.coin,r=e.outcome==null?null:bn(e.outcome,0).outcome,o=typeof e.side=="string"&&["buy","sell"].includes(e.side.toLowerCase())?e.side.toLowerCase():null,i;e.outcomeSide!=null?i=Yk(e.outcomeSide):(i=o?null:e.side,i!=null&&(i=Hm(i)));let a=n==null?null:wn(n);if(n!=null&&!a)throw new Error(`hl-outcome: invalid outcome coin ${n}`);if(e.sideName){let l=r??a?.outcome;if(l==null)throw new Error("hl-outcome: sideName requires outcome identity");let d=((await di(t))?.outcomes||[]).find(f=>{try{return bn(f.outcome,0).outcome===l}catch{return!1}}),p=Array.isArray(d?.sideSpecs)?d.sideSpecs.findIndex(f=>f?.name===e.sideName):-1;if(p<0)throw new Error("hl-outcome: unknown sideName for outcome");let m=Hm(p);if(i!=null&&i!==m)throw new Error("hl-outcome: sideName does not match outcome side");if(a&&a.side!==m)throw new Error("hl-outcome: sideName does not match outcome coin side");i=m}if(!n){if(r==null||i==null)throw new Error("hl-outcome: provide coin (#N) or outcome + side (0/1 or yes/no)");n=bn(r,i).coin}if(a=wn(n),!a)throw new Error(`hl-outcome: invalid outcome coin ${n}`);if(r!=null&&a.outcome!==r)throw new Error("hl-outcome: coin does not match outcome");if(i!=null&&a.side!==i)throw new Error("hl-outcome: coin does not match outcome side");let s=e.orderSide??o??(typeof e.isBuy=="boolean"?null:"buy"),c={...e,coin:n,outcome:void 0,outcomeSide:i};return delete c.orderSide,delete c.sideName,s==null?delete c.side:c.side=s,kn(c,t)}async function Kk(e={},t={}){let n=e.coin,r=e.outcome==null?null:bn(e.outcome,0).outcome,o;if(e.outcomeSide!=null?o=Yk(e.outcomeSide):(o=e.side,o!=null&&(o=Hm(o))),!n&&r!=null){if(o==null)throw new Error("hl-outcome: cancel requires explicit side when coin is omitted");n=bn(r,o).coin}let i=wn(n);if(!i)throw new Error(`hl-outcome: invalid outcome coin ${n}`);if(r!=null&&i.outcome!==r)throw new Error("hl-outcome: coin does not match outcome");if(o!=null&&i.side!==o)throw new Error("hl-outcome: coin does not match outcome side");let a={...e,coin:n,outcome:void 0,outcomeSide:i.side};return delete a.side,vi(a,t)}function Yk(e){if(e===0||e===1)return e;throw new Error("hl-outcome: outcome side must be 0 or 1")}function Hm(e){if(e===0||e===1)return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="0"||t==="yes")return 0;if(t==="1"||t==="no")return 1}throw new Error("hl-outcome: outcome side must be 0, 1, yes, or no")}Y();Dr();var zV="0x"+"00".repeat(32);function QM(e){let t=typeof e=="bigint"?e:mt(e,"poly: atomicUsdc");if(t<=0n)throw new Error("poly: order amounts must be positive integer micro-units");let n=t/1000000n,r=(t%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return r?`${n.toString()}.${r}`:n.toString()}function Jk(e,t){let n=mt(e.makerAmount,"poly: makerAmount"),r=mt(e.takerAmount,"poly: takerAmount");return QM(t==="BUY"?n:r)}Dr();var ZM=new Set(["https://clob.polymarket.com/order"]),aa=Object.freeze([["salt","uint256"],["maker","address"],["signer","address"],["tokenId","uint256"],["makerAmount","uint256"],["takerAmount","uint256"],["side","uint8"],["signatureType","uint8"],["timestamp","uint256"],["metadata","bytes32"],["builder","bytes32"]]),KV=Object.freeze(aa.map(e=>e[0])),eU=new Set(["0xe111180000d2663c0091e4f400237545b87b996b","0xe2222d279d744050d28e00520010520000310f59"]),tU="0xe111180000d2663c0091e4f400237545b87b996b",nU="0xe2222d279d744050d28e00520010520000310f59",Xk=(e,t,n=256)=>{if(typeof e!="string"||!e||e.length>n)throw new Error(`poly: bounded ${t} required`);return e};function Qk(e){let t=String(e||"").replace(/\/$/,"");if(!ZM.has(t))throw new Error("poly: submitTo must be the official Polymarket CLOB");return t}function Zk(e){let t=pt(e,"poly: exchange").toLowerCase();if(!eU.has(t))throw new Error("poly: verifyingContract must be an official CTF Exchange");return t}function eS(e,t){if(e?.surface!=="poly")throw new Error("poly: surface poly required");let n=e.artifact;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("poly: structured artifact required");let r=Xk(n.kind,"kind",48);if(r!=="poly-order")throw new Error("poly: unsupported Polymarket kind");if(e.action!=="order")throw new Error("poly: surface/action/kind mismatch");if(pt(e.destination,"poly: destination").toLowerCase()!=="polymarket")throw new Error("poly: destination must be polymarket");if(Qk(n.submitTo),n.chainId!==137)throw new Error("poly: chainId must be Polygon 137");let o=n.domain;if(!o||typeof o!="object")throw new Error("poly: EIP-712 domain required");if(o.name!=="Polymarket CTF Exchange"||o.version!=="2"||o.chainId!==137)throw new Error("poly: EIP-712 domain must be official CTF Exchange v2 on Polygon");if(Zk(o.verifyingContract),Zk(n.exchange),pt(o.verifyingContract,"poly: verifyingContract").toLowerCase()!==pt(n.exchange,"poly: exchange").toLowerCase())throw new Error("poly: exchange/domain mismatch");if(typeof n.negRisk!="boolean")throw new Error("poly: negRisk must be a boolean");let i=n.negRisk?nU:tU;if(pt(n.exchange,"poly: exchange").toLowerCase()!==i)throw new Error("poly: negRisk/exchange mismatch");let a=n.message||n.value;if(!a||typeof a!="object")throw new Error("poly: signed order message required");let s=n.types?.Order;if(!Array.isArray(s)||s.length!==aa.length)throw new Error("poly: EIP-712 Order type must be official CLOB v2");for(let I=0;I<aa.length;I+=1)if(s[I]?.name!==aa[I][0]||s[I]?.type!==aa[I][1])throw new Error("poly: EIP-712 Order type must be official CLOB v2");if((n.orderType||"GTC")!=="GTC")throw new Error("poly: only GTC is public");let c=String(e.owner||"").toLowerCase();if(pt(a.maker,"poly: maker").toLowerCase()!==c)throw new Error("poly: maker must equal owner");if(pt(a.signer,"poly: signer").toLowerCase()!==c)throw new Error("poly: signer must equal owner");if(a.signatureType!==0)throw new Error("poly: only EOA signatureType 0 is public");if(typeof a.builder!="string"||a.builder.toLowerCase()!==`0x${"00".repeat(32)}`)throw new Error("poly: builder must be zero");if(a.side!==0&&a.side!==1)throw new Error("poly: side must be BUY or SELL");let l=Xk(n.tokenId,"tokenId",80);if(pt(a.tokenId,"poly: tokenId")!==l)throw new Error("poly: tokenId mismatch");let u=Array.isArray(t.polyTokens)?t.polyTokens.map(String):[];if(u.length&&!u.includes(l)&&!u.includes("*"))throw new Error("poly: tokenId not allowed");let d=Number(a.side)===0?"BUY":"SELL";if(n.side&&n.side!==d)throw new Error("poly: side mismatch");let p=mt(a.makerAmount,"poly: makerAmount"),m=mt(a.takerAmount,"poly: takerAmount"),f=mt(n.makerAmount,"poly: prepared makerAmount"),h=mt(n.takerAmount,"poly: prepared takerAmount");if(p!==f)throw new Error("poly: signed makerAmount differs from prepared envelope");if(m!==h)throw new Error("poly: signed takerAmount differs from prepared envelope");let g=d==="BUY"?p:m,w=d==="BUY"?m:p,x=_e(n.quantity,6,"poly: quantity");if(x<=0n||x!==w)throw new Error("poly: quantity must match CLOB v2 amounts");let b=_e(n.price,6,"poly: price");if(b<=0n||b>=1000000n)throw new Error("poly: price must be within (0,1)");if(w*b!==g*1000000n)throw new Error("poly: price must match CLOB v2 amounts");if(_e(n.notionalUsdc,6,"poly: notionalUsdc")!==g)throw new Error("poly: notionalUsdc must match CLOB v2 amounts");let k=Jk(a,d);if(_e(k,6,"poly: displayed notionalUsdc")!==g)throw new Error("poly: displayed notionalUsdc must match CLOB v2 amounts");let E=t.maxNotionalUsd??t.maxNotionalUsdc;if(E!=null){let I=_e(E,6,"poly: maxNotionalUsd");if(g>I)throw new Error("poly: notional exceeds cap")}return Object.freeze({unit:"usdc",value:g.toString(),notional:g.toString(),fee:"0",kind:r,tokenId:l,side:d,makerAmount:p.toString(),takerAmount:m.toString(),price:String(n.price),quantity:String(n.quantity),notionalUsdc:k,submitTo:Qk(n.submitTo)})}function rU(e){let t=e.owner||e.maker||e.signer||e.user||e.from;if(!/^0x[0-9a-fA-F]{40}$/.test(String(t||"")))throw new Error("poly: owner/maker address required for local-signer envelope");return String(t).toLowerCase()}function tS(e,t={},n={}){if(String(e?.kind)!=="poly-order")throw new Error("poly: prepared kind is not a local-signer surface");if(!e?.domain||!e?.types||!e?.value)throw new Error("poly: prepared EIP-712 order required");let r=Number(n.nowMs??Date.now()),o=Math.min(6e4,Math.max(1e3,Number(t.ttlMs??t.expiresInMs??3e4)||3e4)),a={version:1,surface:"poly",action:"order",owner:rU({...t,maker:e.value?.maker,signer:e.value?.signer}),destination:"polymarket",tradeId:String(t.tradeId||`poly:${e.value?.tokenId}:${e.value?.salt}`),expiresAtMs:r+o,slippageBps:Number(t.slippageBps??0),fee:{oracleFeeBps:0},provider:"poly-clob",artifact:{kind:"poly-order",tokenId:String(e.tokenId||e.value.tokenId),side:e.side,makerAmount:String(e.value.makerAmount),takerAmount:String(e.value.takerAmount),price:e.price,quantity:e.quantity,notionalUsdc:e.notionalUsdc,exchange:e.exchange,negRisk:e.negRisk,chainId:137,submitTo:"https://clob.polymarket.com/order",orderType:e.orderType||"GTC",signatureType:e.signatureType??0,domain:e.domain,types:e.types,message:e.value}};return eS(a,{polyTokens:t.polyTokens||["*"],maxNotionalUsd:t.maxNotionalUsd??t.maxNotionalUsdc??Number.MAX_SAFE_INTEGER}),a}import{createHmac as tW,randomInt as oU}from"node:crypto";import{keccak256 as rW,concat as oW,zeroPadValue as iW,getCreate2Address as aW,AbiCoder as sW}from"ethers";var aS=137;var iU="0xE111180000d2663C0091e4f400237545B87B996B",aU="0xe2222d279d744050d28e00520010520000310F59",nS="0x0000000000000000000000000000000000000000000000000000000000000000",jm=6;var sU={name:"Polymarket CTF Exchange",version:"2",chainId:aS},cU={Order:[{name:"salt",type:"uint256"},{name:"maker",type:"address"},{name:"signer",type:"address"},{name:"tokenId",type:"uint256"},{name:"makerAmount",type:"uint256"},{name:"takerAmount",type:"uint256"},{name:"side",type:"uint8"},{name:"signatureType",type:"uint8"},{name:"timestamp",type:"uint256"},{name:"metadata",type:"bytes32"},{name:"builder",type:"bytes32"}]},rS={"0.1":{price:1,size:2,amount:3},"0.01":{price:2,size:2,amount:4},"0.001":{price:3,size:2,amount:5},"0.0001":{price:4,size:2,amount:6}};function Wc(e){let t=String(e);return t.includes(".")?t.split(".")[1].replace(/0+$/,"").length:0}function Gc(e,t){let n=10**t;return Math.floor(e*n+1e-12)/n}function oS(e,t){let n=10**t;return Math.ceil(e*n-1e-12)/n}function sS(e,t){let n=10**t;return Math.round(e*n+Number.EPSILON)/n}function lU(e,t,n,r){let o=sS(Number(n),r.price);if(e==="BUY"){let c=Gc(Number(t),r.size),l=c*o;return Wc(l)>r.amount&&(l=oS(l,r.amount+4),Wc(l)>r.amount&&(l=Gc(l,r.amount))),{rawMakerAmt:l,rawTakerAmt:c}}let a=Gc(Number(t),r.size),s=a*o;return Wc(s)>r.amount&&(s=oS(s,r.amount+4),Wc(s)>r.amount&&(s=Gc(s,r.amount))),{rawMakerAmt:a,rawTakerAmt:s}}function iS(e){let t=Number(e).toFixed(jm),[n,r=""]=t.split(".");return(n+r.padEnd(jm,"0").slice(0,jm)).replace(/^0+/,"")||"0"}function uU(e={}){if(Object.prototype.hasOwnProperty.call(e,"negRisk")&&typeof e.negRisk!="boolean")throw new Error("negRisk must be a boolean");let{tokenId:t,side:n,price:r,size:o,maker:i,signer:a,negRisk:s=!1,tickSize:c="0.01",orderType:l="GTC",signatureType:u=0,metadata:d=nS,builder:p=nS}=e;if(!t)throw new Error("tokenId required");if(n!=="BUY"&&n!=="SELL")throw new Error("side must be BUY or SELL");if(!i||!a)throw new Error("maker and signer required");let m=Number(r),f=Number(o);if(!(m>0&&m<1))throw new Error(`price out of (0,1): ${r}`);if(!(f>0))throw new Error(`size must be > 0: ${o}`);if(u!==0&&u!==3)throw new Error(`Desk poly supports signatureType 0 (EOA) or 3 (deposit wallet), got ${u}`);if(typeof p!="string"||!/^0x[0-9a-fA-F]{64}$/.test(p))throw new Error("poly: builder must be a 32-byte hex string");if(typeof d!="string"||!/^0x[0-9a-fA-F]{64}$/.test(d))throw new Error("poly: metadata must be a 32-byte hex string");let h=rS[String(c)]||rS["0.01"],g=sS(m,h.price),{rawMakerAmt:w,rawTakerAmt:x}=lU(n,f,g,h),b=iS(w),y=iS(x),k=String(oU(1,2**31-1)),E=Date.now().toString(),I=n==="BUY"?0:1,v=s?aU:iU,A={salt:k,maker:i,signer:a,tokenId:String(t),makerAmount:b,takerAmount:y,side:I,signatureType:u,timestamp:E,metadata:d,builder:p},P={...sU,verifyingContract:v},T=n==="BUY"?w:x;return{domain:P,types:cU,value:A,orderType:l,side:n,price:String(g),quantity:String(n==="BUY"?x:w),notionalUsdc:T,exchange:v,negRisk:s}}function cS(){return{ok:!0,provider:"poly-clob",exec:!1,execution:"armed-local",signing:"local-signer",broadcasting:"local-signer",armed:!1,signed:!1,broadcast:!1,note:"capability only. Hosted/keyless remains prepare-only."}}function lS(e={},t={}){let n=uU(e),r={provider:"poly-clob",kind:"poly-order",chainId:aS,tokenId:String(e.tokenId),side:n.side,orderType:n.orderType,price:n.price,quantity:n.quantity,notionalUsdc:n.notionalUsdc,exchange:n.exchange,domain:n.domain,types:n.types,value:n.value,tickSize:e.tickSize||"0.01",negRisk:n.negRisk,signatureType:e.signatureType??0,maxNotionalUsdc:e.maxNotionalUsdc??null};try{r.localSignerEnvelope=tS(r,e,t)}catch{r.oraclePrepared=!1}return N(r,{provider:"poly-clob",kind:"poly-order"})}import{ContractFactory as xU,keccak256 as wS}from"ethers";Y();el();Jc();var kU=new Set(["status","chainId","forkBlockNumber","gasUsed","transactionHash","contractAddress","revertReason"]);function SU(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("prepareTemplateDeploy: localForkSimulationReceipt must be an object");let n=Qt(e);for(let o of Object.keys(n))if(!kU.has(o))throw new Error(`prepareTemplateDeploy: unsupported field "${o}" in localForkSimulationReceipt`);if(n.status!=="success"&&n.status!=="reverted")throw new Error('prepareTemplateDeploy: simulation status must be "success" or "reverted"');let r={status:n.status};if(n.chainId!==void 0){let o=Number(n.chainId);if(!Number.isSafeInteger(o)||o!==t)throw new Error("prepareTemplateDeploy: simulation chainId must match deployment chainId");r.chainId=o}if(n.forkBlockNumber!==void 0){let o=Number(n.forkBlockNumber);if(!Number.isSafeInteger(o)||o<0)throw new Error("prepareTemplateDeploy: simulation forkBlockNumber must be a nonnegative safe integer");r.forkBlockNumber=o}if(n.gasUsed!==void 0){let o=String(n.gasUsed);if(!/^(0|[1-9][0-9]*)$/.test(o))throw new Error("prepareTemplateDeploy: simulation gasUsed must be a nonnegative integer");r.gasUsed=o}if(n.transactionHash!==void 0){if(!/^0x[0-9a-fA-F]{64}$/.test(n.transactionHash))throw new Error("prepareTemplateDeploy: simulation transactionHash must be bytes32 hex");r.transactionHash=n.transactionHash}if(n.contractAddress!==void 0){if(!/^0x[0-9a-fA-F]{40}$/.test(n.contractAddress))throw new Error("prepareTemplateDeploy: simulation contractAddress must be an EVM address");r.contractAddress=n.contractAddress}if(n.revertReason!==void 0){if(typeof n.revertReason!="string"||n.revertReason.length>500)throw new Error("prepareTemplateDeploy: simulation revertReason must be at most 500 characters");r.revertReason=n.revertReason}return r}async function vS(e={},t={}){let n=String(e.templateId||"").trim();if(!n)throw new Error("prepareTemplateDeploy: templateId required");let r=Number(e.chainId);if(!Number.isInteger(r)||r<=0)throw new Error("prepareTemplateDeploy: chainId required");let o=e.args??e.constructorArgs??[],i=mS(n,o),a=bS(n,{contractName:e.contractName,allowSkipStatic:t.allowSkipStatic!==!1,allowStaticFail:t.allowStaticFail===!0});if(!a.bytecode||a.bytecode==="0x")throw new Error("prepareTemplateDeploy: empty bytecode");let s=a.bytecode.startsWith("0x")?a.bytecode:`0x${a.bytecode}`,u=(await new xU(a.abi,s).getDeployTransaction(...o)).data,d=t.localForkSimulationReceipt??e.localForkSimulationReceipt??null,p=d===null?{status:"not-run",injected:!1,trusted:!1,gateDecision:!1,networkSideEffects:!1}:{...SU(d,r),kind:"local-fork",injected:!0,trusted:!1,gateDecision:!1,networkSideEffects:!1},m={chainId:r,to:null,data:u,value:"0x0"};return N({provider:"protocol-templates",kind:"template-deploy",templateId:n,contractName:a.contractName,template:i,chainId:r,transaction:m,unsignedDeployEnvelope:{transaction:m,signed:!1,broadcast:!1},abi:a.abi,sourceHash:a.gate.sourceHash,bytecodeHash:wS(s),authorityReport:fS(i),simulationReceipt:p,verificationManifest:{contractName:a.contractName,source:i.source,compiler:"0.8.24",optimizer:{enabled:!0,runs:200},openZeppelin:i.dependency,sourceHash:a.gate.sourceHash,creationBytecodeHash:wS(s),constructorData:`0x${u.slice(s.length)}`},addressBookRecord:{status:"pending-deployment",address:null,chainId:r,label:`${n}:${a.contractName}`},monitoringPlan:{activation:"after user-signed deployment confirmation",enabled:!1,events:[...i.monitor],checks:["deployment bytecode matches verification manifest","authority changes","contract balance and release/withdraw events"]},gate:{forgeBuild:a.gate.forgeBuild,forgeTests:a.gate.forgeTests,staticAnalysis:{tool:a.gate.staticAnalysis.tool,ok:a.gate.staticAnalysis.ok,skipped:a.gate.staticAnalysis.skipped},firmAudit:!1,disclaimer:Qc},requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,deploymentActivated:!1,note:"Unsigned deploy. User wallet signs. Template tests passed; not a firm audit."},{provider:"protocol-templates",kind:"template-deploy"})}el();Xm();xi();R();var $U="https://api.geckoterminal.com/api/v2",rl=(e={})=>(e.baseUrl||process.env.GECKOTERMINAL_API_URL||$U).replace(/\/$/,""),uo=e=>encodeURIComponent(String(e));async function Qm(e={},t={}){let n=Math.max(1,Number(e.page||1));return S(`${rl(t)}/networks?page=${n}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function PS(e={},t={}){if(!e.network||!e.poolAddress)throw new Error("network and poolAddress required");return S(`${rl(t)}/networks/${uo(e.network)}/pools/${uo(e.poolAddress)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function CS(e={},t={}){if(!e.network||!(e.address||e.tokenAddress))throw new Error("network and token address required");return S(`${rl(t)}/networks/${uo(e.network)}/tokens/${uo(e.address||e.tokenAddress)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function TS(e={},t={}){if(!e.network||!e.poolAddress)throw new Error("network and poolAddress required");let n=["minute","hour","day"].includes(e.timeframe)?e.timeframe:"hour",r=new URLSearchParams;return r.set("aggregate",String(Math.max(1,Number(e.aggregate||1)))),r.set("limit",String(Math.min(1e3,Math.max(1,Number(e.limit||168))))),e.beforeTimestamp!=null&&r.set("before_timestamp",String(e.beforeTimestamp)),e.currency&&r.set("currency",String(e.currency)),e.token&&r.set("token",String(e.token)),S(`${rl(t)}/networks/${uo(e.network)}/pools/${uo(e.poolAddress)}/ohlcv/${n}?${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function NS(e={}){let t=await Qm({page:1},e);return{ok:Array.isArray(t?.data)&&t.data.length>0,networkSample:t?.data?.length||0}}R();pe();Fe();Y();import{Interface as $S,getAddress as BS,isAddress as MU}from"ethers";var UU="https://api.curve.finance/v1",MS=(e={})=>(e.baseUrl||process.env.CURVE_API_URL||UU).replace(/\/$/,""),FU=Object.freeze({1:"0x45312ea0eFf7E09C83CBE249fa1d7598c4C8cd4e",10:"0x0DCDED3545D565bA3B19E683431381007245d983",56:"0xA72C85C258A81761433B4e8da60505Fe3Dd551CC",137:"0x0DCDED3545D565bA3B19E683431381007245d983",988:"0xFF5Cb29241F002fFeD2eAa224e3e996D24A6E8d1",999:"0xd2002373543Ce3527023C75e7518C274A51ce712",4663:"0xFF5Cb29241F002fFeD2eAa224e3e996D24A6E8d1",8453:"0x4f37A9d177470499A2dD084621020b023fcffc1F",42161:"0x2191718CD32d02B8E60BAdFFeA33E4B5DD9A0A0D",43114:"0x0DCDED3545D565bA3B19E683431381007245d983"}),US="0x0000000000000000000000000000000000000000",Zm=new $S(["function get_dy(address[11] route,uint256[5][5] swap_params,uint256 amount,address[5] pools) view returns (uint256)","function exchange(address[11] route,uint256[5][5] swap_params,uint256 amount,uint256 expected,address[5] pools,address receiver) payable returns (uint256)"]),OS=new $S(["function coins(uint256) view returns (address)"]);function FS(e){let t=FU[Number(e)];if(!t)throw new Error(`curve-router-ng: unsupported chainId ${e}`);return t}function fa(e,t){if(!MU(e))throw new Error(`${t} must be a valid EVM address`);return BS(e)}function DU(e,t){let n;try{n=BigInt(String(e))}catch{throw new Error(`${t} must be an integer string`)}if(n<=0n)throw new Error(`${t} must be positive`);return n}function RS(e,t,n,r){let o=Number(e);if(!Number.isInteger(o)||o<n||o>r)throw new Error(`${t} must be an integer ${n}..${r}`);return o}function DS(e,t,n){return[e,t,n,...Array(8).fill(US)]}function qS(e,t,n,r){return[[BigInt(e),BigInt(t),1n,BigInt(n),BigInt(r)],...Array.from({length:4},()=>[0n,0n,0n,0n,0n])]}function HS(e){return[e,...Array(4).fill(US)]}async function qU({chainId:e,pool:t,nCoins:n,rpcCall:r,opts:o}){return(await Promise.all(Array.from({length:n},(a,s)=>{let c=OS.encodeFunctionData("coins",[s]);return r(e,"eth_call",[{to:t,data:c},o.blockTag||"latest"],o)}))).map(a=>BS(OS.decodeFunctionResult("coins",a)[0]))}function LS(e,t,n){let r=t.toLowerCase(),o=e.findIndex(i=>i.toLowerCase()===r);if(o<0)throw new Error(`Curve pool does not contain ${n}`);return o}async function jS(e={}){return S(`${MS(e)}/openapi.json`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs})}async function ef(e={},t={}){let n=String(e.chain||e.network||"ethereum").toLowerCase(),r=String(e.registry||"main").toLowerCase();if(!/^[a-z0-9-]+$/.test(n)||!/^[a-z0-9-]+$/.test(r))throw new Error("invalid Curve chain or registry");return S(`${MS(t)}/getPools/${n}/${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??2e4})}async function zS(e={}){let t=await ef({chain:"ethereum",registry:"main"},e),n=t?.data?.poolData?.length||0;return{ok:t?.success===!0&&n>0,poolSample:n}}async function tf(e={},t={}){let n=Number(e.chainId??8453),r=FS(n),o=fa(e.pool,"curve pool"),i=fa(e.tokenIn,"curve tokenIn"),a=fa(e.tokenOut,"curve tokenOut"),s=DU(e.amountIn,"curve amountIn"),c=RS(e.nCoins??2,"curve nCoins",2,8),l=RS(e.poolType,"curve poolType",1,4),u=t.rpcCall||D,d=await qU({chainId:n,pool:o,nCoins:c,rpcCall:u,opts:t}),p=LS(d,i,"tokenIn"),m=LS(d,a,"tokenOut");if(p===m)throw new Error("Curve token indexes must differ");let f=DS(i,o,a),h=qS(p,m,l,c),g=HS(o),w=Zm.encodeFunctionData("get_dy",[f,h,s,g]),x=await u(n,"eth_call",[{to:r,data:w},e.blockTag||"latest"],t),b=Zm.decodeFunctionResult("get_dy",x),y=BigInt(b[0]);if(y<=0n)throw new Error("curve quote returned zero output");return oe({venue:"curve",router:r,chainId:n,pool:o,tokenIn:i,tokenOut:a,amountIn:s.toString(),amountOut:y.toString(),nCoins:c,poolType:l,swapType:1,i:p,j:m,route:f,swapParams:h.map(k=>k.map(E=>E.toString())),pools:g},{chainId:n,venue:r,amountOut:y.toString(),liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function VS(e={},t={}){let n=Number(e.chainId??8453),r=FS(n),o=fa(e.sender||e.from||e.fromAddress||e.receiver,"curve sender"),i=fa(e.receiver||e.recipient||o,"curve receiver"),a=await tf({...e,sender:o},t),s=DS(a.tokenIn,a.pool,a.tokenOut),c=qS(a.i,a.j,a.poolType,a.nCoins),l=HS(a.pool),u=Zm.encodeFunctionData("exchange",[s,c,BigInt(a.amountIn),BigInt(a.amountOutMinimum),l,i]);return N({provider:"curve",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:n,quote:a,autoSlippage:a.autoSlippage,requiresApproval:{token:a.tokenIn,spender:r,amount:a.amountIn},transaction:{chainId:n,from:o,to:r,data:u,value:"0",slippageGuard:ye(a.autoSlippage,{chainId:n,venue:r,data:u})}},{provider:"curve",kind:"curve-tx"})}R();pe();Y();import{Interface as jU,getAddress as zU,isAddress as VU,keccak256 as WS,toUtf8Bytes as GS}from"ethers";var WU="https://api.morpho.org/graphql",ol=new jU(["function asset() view returns (address)","function maxDeposit(address owner) view returns (uint256)","function previewDeposit(uint256 assets) view returns (uint256)","function deposit(uint256 assets,address receiver) returns (uint256)","function maxWithdraw(address owner) view returns (uint256)","function previewWithdraw(uint256 assets) view returns (uint256)","function withdraw(uint256 assets,address receiver,address owner) returns (uint256)"]),GU=(e={})=>e.baseUrl||process.env.MORPHO_API_URL||WU;async function rf(e,t,n={}){return S(GU(n),{method:"POST",body:{query:e,variables:t},fetchImpl:n.fetchImpl,timeoutMs:n.timeoutMs??2e4})}var KU="query Markets($first: Int, $where: MarketFilters) { markets(first: $first, where: $where) { items { marketId lltv listed loanAsset { address symbol decimals } collateralAsset { address symbol decimals } state { supplyAssetsUsd borrowAssetsUsd } } } }",YU="query Vaults($first: Int, $where: VaultFilters) { vaults(first: $first, where: $where) { items { address name symbol listed asset { address symbol decimals } state { totalAssets totalAssetsUsd apy } } } }";function ha(e,t){let n=String(e||"").trim();if(!VU(n))throw new Error(`morpho: ${t} must be an address`);return zU(n).toLowerCase()}function JU(e,t="amount"){try{let n=BigInt(String(e));if(n<=0n)throw new Error("nonpositive");return n.toString()}catch{throw new Error(`morpho: ${t} must be a positive integer string`)}}function nf(e){return Array.isArray(e)?`[${e.map(nf).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${nf(e[t])}`).join(",")}}`:JSON.stringify(e)}async function ga(e,t,n,r,o={}){let i=ol.encodeFunctionData(n,r),s=await(o.rpcCall||D)(Number(e),"eth_call",[{to:t,data:i},"latest"],o);return ol.decodeFunctionResult(n,s)}function XU(e,t){let n=t.toLowerCase();return(e||[]).find(r=>String(r?.address||"").toLowerCase()===n)||null}async function KS(e={},t={}){let n=Math.min(100,Math.max(1,Number(e.first||20))),r=(e.chainIds||[e.chainId||1]).map(Number);return rf(KU,{first:n,chainIds:r,where:{chainId_in:r}},t)}async function of(e={},t={}){let n=Math.min(100,Math.max(1,Number(e.first||20))),r=(e.chainIds||[e.chainId||1]).map(Number);return rf(YU,{first:n,chainIds:r,where:{chainId_in:r}},t)}async function YS(e={}){return{ok:(await rf("query { __typename }",{},e))?.data?.__typename==="Query"}}async function JS(e={},t={}){let n=Number(e.chainId??8453),r=String(e.action||"deposit").toLowerCase();if(!["deposit","withdraw"].includes(r))throw new Error("morpho: action must be deposit or withdraw");let o=ha(e.vault||e.vaultAddress,"vault"),i=ha(e.owner||e.from||e.sender,"owner"),a=ha(e.receiver||i,"receiver"),s=JU(e.amount||e.assets,"amount"),c=Number(e.minTotalAssetsUsd??1e5),[l,[u]]=await Promise.all([of({chainId:n,first:100},t),ga(n,o,"asset",[],t)]),d=XU(l?.data?.vaults?.items,o);if(!d)throw new Error("morpho: vault not found in public Morpho vault registry");if(d.listed===!1)throw new Error("morpho: vault is not listed");let p=Number(d?.state?.totalAssetsUsd??0);if(Number.isFinite(c)&&p<c)throw new Error(`morpho: vault totalAssetsUsd ${p} below minimum ${c}`);let m=ha(u,"vault asset");if((d?.asset?.address?ha(d.asset.address,"api vault asset"):m)!==m)throw new Error("morpho: API asset and on-chain asset mismatch");let h,g;if(r==="deposit"){let[[x],[b]]=await Promise.all([ga(n,o,"maxDeposit",[i],t),ga(n,o,"previewDeposit",[s],t)]);if(BigInt(s)>BigInt(x.toString()))throw new Error("morpho: amount exceeds maxDeposit");if(BigInt(b.toString())<=0n)throw new Error("morpho: previewDeposit returned zero shares");g={minSharesOut:b.toString()},h=ol.encodeFunctionData("deposit",[s,a])}else{let[[x],[b]]=await Promise.all([ga(n,o,"maxWithdraw",[i],t),ga(n,o,"previewWithdraw",[s],t)]);if(BigInt(s)>BigInt(x.toString()))throw new Error("morpho: amount exceeds maxWithdraw");if(BigInt(b.toString())<=0n)throw new Error("morpho: previewWithdraw returned zero shares");g={maxSharesIn:b.toString()},h=ol.encodeFunctionData("withdraw",[s,a,i])}let w={mode:"erc4626-vault",version:1,provider:"morpho",chainId:n,action:r,vault:o,asset:m,owner:i,receiver:a,amount:s,totalAssetsUsd:p,...g,calldataHash:WS(GS(h)),issuedAtMs:Date.now(),expiresAtMs:Date.now()+2e4};return w.guardHash=WS(GS(nf(w))),N({provider:"morpho",protocol:"erc4626-vault",vaultReady:!0,executionReady:!1,signingReady:!1,broadcastReady:!1,requiresUserSignature:!0,chainId:n,action:r,vault:o,asset:m,owner:i,receiver:a,amount:s,vaultInfo:d,vaultGuard:w,requiresApproval:r==="deposit"?{token:m,spender:o,amount:s}:null,transaction:{chainId:n,from:i,to:o,data:h,value:"0x0",madVault:w}},{provider:"morpho",kind:"erc4626-vault"})}R();pe();Fe();Y();import{Interface as ZU,getAddress as af,isAddress as eF}from"ethers";var tF="https://api-v3.balancer.fi/",nF=(e={})=>e.baseUrl||process.env.BALANCER_API_URL||tF;async function ZS(e,t,n={}){return S(nF(n),{method:"POST",body:{query:e,variables:t},fetchImpl:n.fetchImpl,timeoutMs:n.timeoutMs??2e4})}var rF="query Pools($first: Int, $where: GqlPoolFilter) { poolGetPools(first: $first, where: $where) { id address chain type protocolVersion dynamicData { totalLiquidity volume24h fees24h } } }",XS=Object.freeze({1:{name:"ethereum",router:"0xAE563E3f8219521950555F5962419C8919758Ea2",weth:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",usdc:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},10:{name:"optimism",router:"0xe2fa4e1d17725e72dcdAfe943Ecf45dF4B9E285b",weth:"0x4200000000000000000000000000000000000006",usdc:"0x0b2c639c533813f4aa9d7837caf62653d097ff85"},8453:{name:"base",router:"0x3f170631ed9821Ca51A59D996aB095162438DC10",weth:"0x4200000000000000000000000000000000000006",usdc:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"},42161:{name:"arbitrum",router:"0xEAedc32a51c510d35ebC11088fD5fF2b47aACF2E",weth:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",usdc:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"},43114:{name:"avalanche",router:"0xF39CA6ede9BF7820a952b52f3c94af526bAB9015",weth:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",usdc:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"}}),oF="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",iF="0x0000000000000000000000000000000000000000",sf=new ZU(["function querySwapSingleTokenExactIn(address pool,address tokenIn,address tokenOut,uint256 exactAmountIn,address sender,bytes userData) returns (uint256 amountOut)","function swapSingleTokenExactIn(address pool,address tokenIn,address tokenOut,uint256 exactAmountIn,uint256 minAmountOut,uint256 deadline,bool wethIsEth,bytes userData) payable returns (uint256 amountOut)"]);function eI(e){let t=Number(e??8453),n=XS[t];if(!n)throw new Error(`balancer-v3: unsupported chainId ${e} (supported: ${Object.keys(XS).join(", ")})`);return{chainId:t,...n}}function tI(e){let t=String(e||"").toLowerCase();return!t||t==="eth"||t==="native"||t===iF||t===oF.toLowerCase()}function il(e,t){if(!eF(e))throw new Error(`${t} must be a valid EVM address`);return af(e)}function QS(e,t,n){let r=String(e||"");return tI(r)||/^weth$/i.test(r)?af(t.weth):/^usdc$/i.test(r)?af(t.usdc):il(r,n)}function aF(e,t){let n;try{n=BigInt(String(e))}catch{throw new Error(`${t} must be an integer string`)}if(n<=0n)throw new Error(`${t} must be positive`);return n}function nI(e){if(e==null||e==="")return"0x";let t=String(e);if(!/^0x[0-9a-fA-F]*$/.test(t))throw new Error("balancer userData must be hex");return t}async function rI(e={},t={}){let n=Math.min(100,Math.max(1,Number(e.first||20))),r=(e.chains||[e.chain||"ETHEREUM"]).map(o=>String(o).toUpperCase());return ZS(rF,{first:n,chains:r,where:{chainIn:r}},t)}async function oI(e={}){return{ok:(await ZS("query { __typename }",{},e))?.data?.__typename==="Query"}}async function cf(e={},t={}){let n=eI(e.chainId),r=il(e.pool,"balancer pool"),o=e.tokenIn||"WETH",i=QS(o,n,"balancer tokenIn"),a=QS(e.tokenOut||"USDC",n,"balancer tokenOut"),s=aF(e.amountIn,"balancer amountIn"),c=il(e.sender||e.from||e.fromAddress||e.recipient,"balancer sender"),l=sf.encodeFunctionData("querySwapSingleTokenExactIn",[r,i,a,s,c,nI(e.userData)]),d=await(t.rpcCall||D)(n.chainId,"eth_call",[{to:n.router,data:l},e.blockTag||"latest"],t),p=sf.decodeFunctionResult("querySwapSingleTokenExactIn",d),m=BigInt(p[0]);if(m<=0n)throw new Error("balancer quote returned zero output");return oe({venue:"balancer",protocolVersion:3,chainId:n.chainId,chain:n.name,router:n.router,pool:r,tokenIn:i,tokenOut:a,amountIn:s.toString(),amountOut:m.toString()},{chainId:n.chainId,venue:n.router,amountOut:m.toString(),liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps})}async function iI(e={},t={}){let n=eI(e.chainId),r=il(e.sender||e.from||e.fromAddress||e.recipient,"balancer sender"),o=e.tokenIn||"WETH",i=tI(o),a=await cf({...e,sender:r},t),s=Math.min(600,Math.max(30,Number(e.deadlineSeconds??300))),c=Number(t.nowSeconds??Math.floor(Date.now()/1e3)),l=BigInt(c+s),u=e.wethIsEth!=null?!!e.wethIsEth:i,d=sf.encodeFunctionData("swapSingleTokenExactIn",[a.pool,a.tokenIn,a.tokenOut,BigInt(a.amountIn),BigInt(a.amountOutMinimum),l,u,nI(e.userData)]);return N({provider:"balancer",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:n.chainId,deadline:l.toString(),quote:a,autoSlippage:a.autoSlippage,requiresApproval:i?null:{token:a.tokenIn,spender:n.router,amount:a.amountIn},transaction:{chainId:n.chainId,from:r,to:n.router,data:d,value:i?a.amountIn:"0",slippageGuard:ye(a.autoSlippage,{chainId:n.chainId,venue:n.router,data:d})}},{provider:"balancer",kind:"balancer-tx"})}R();Fe();Y();import{getAddress as cF}from"ethers";var lF="https://api-v2.pendle.finance/core",uF=Object.freeze({42161:"0x888888888889758F76e7103c6CbF23ABbF58F946",8453:"0x888888888889758F76e7103c6CbF23ABbF58F946"}),dF="0x0000000000000000000000000000000000000000",pF="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",aI=(e={})=>(e.baseUrl||process.env.PENDLE_API_URL||lF).replace(/\/$/,"");function al(e,t){try{return cF(e)}catch{throw new Error(`${t} must be a valid EVM address`)}}function po(e,t){return al(e,t).toLowerCase()}function mF(e){let t=String(e||"").toLowerCase();return t==="native"||t==="eth"||t===pF||t===dF}function lf(e,t){let n;try{n=BigInt(String(e))}catch{throw new Error(`${t} must be an integer string`)}if(n<=0n)throw new Error(`${t} must be positive`);return n.toString()}function fF(e){if(!Array.isArray(e)||e.length===0)throw new Error("pendle convert requires inputs[]");return e.map((t,n)=>({token:al(t.token,`pendle input ${n} token`),amount:lf(t.amount,`pendle input ${n} amount`)}))}function hF(e){if(!Array.isArray(e)||e.length===0)throw new Error("pendle convert requires outputs[]");return e.map((t,n)=>al(t,`pendle output ${n} token`))}function gF(e){let t=uF[Number(e)];if(!t)throw new Error(`Pendle prepare not enabled for chainId ${e}`);return t}function yF(e){let t=e?.routes?.[0]?.outputs?.[0]?.amount||e?.outputs?.[0]?.amount;if(!t)throw new Error("Pendle convert response missing output amount");return lf(t,"pendle output amount")}function bF(e,t){let n=(Array.isArray(e)?e:[]).filter(r=>r?.token&&r?.amount&&!mF(r.token)).map(r=>({token:po(r.token,"pendle approval token"),spender:po(t,"pendle approval spender"),amount:lf(r.amount,"pendle approval amount")}));return n.length?n.length===1?n[0]:n:null}async function uf(e={},t={}){let n=Number(e.chainId||42161),r=new URLSearchParams({limit:String(Math.min(100,Math.max(1,Number(e.limit||20)))),skip:String(Math.max(0,Number(e.skip||0)))});return e.isExpired!=null&&r.set("isExpired",String(!!e.isExpired)),S(`${aI(t)}/v1/${n}/markets?${r}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs})}async function sI(e={}){let t=await uf({chainId:42161,limit:1},e);return{ok:Array.isArray(t?.results),marketSample:t?.results?.length||0}}async function df(e={},t={}){let n=Number(e.chainId??42161),r=gF(n),o=e.from||e.fromAddress||e.userAddress||e.taker||e.receiver;if(!o)throw new Error("pendlePrepare requires from/receiver");let i=al(e.receiver||o,"pendle receiver"),a=fF(e.inputs),s=hF(e.outputs);if(e.enableAggregator===!0||Array.isArray(e.aggregators)&&e.aggregators.length)throw new Error("Pendle aggregator paths are disabled by policy; use direct convert only");let c=We({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!c.executable)throw new Error(`Pendle: route requires ${c.requiredBps} bps above cap ${c.capBps}`);let l={receiver:i,slippage:c.selectedBps/1e4,enableAggregator:!1,useLimitOrder:!1,inputs:a,outputs:s,...e.redeemRewards!=null?{redeemRewards:!!e.redeemRewards}:{},...e.needScale!=null?{needScale:!!e.needScale}:{},...e.additionalData?{additionalData:String(e.additionalData)}:{}},u=await S(`${aI(t)}/v3/sdk/${n}/convert`,{method:"POST",body:l,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??25e3}),p=u?.routes?.[0]?.tx;if(!p?.to||!p?.data)throw new Error("Pendle convert returned no executable tx");if(po(p.to,"pendle tx target")!==po(r,"pendle router"))throw new Error("Pendle convert returned unexpected router target");if(p.from&&po(p.from,"pendle tx sender")!==po(o,"pendle sender"))throw new Error("Pendle convert transaction sender mismatch");let m=yF(u),f=oe(u,{chainId:n,venue:p.to,amountOut:m,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps});return N({provider:"pendle",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:n,action:u.action||null,quote:f,autoSlippage:f.autoSlippage,requiresApproval:bF(u.requiredApprovals,p.to),transaction:{chainId:n,from:p.from||o,to:p.to,data:p.data,value:p.value??"0x0",slippageGuard:ye(f.autoSlippage,{chainId:n,venue:p.to,data:p.data})}},{provider:"pendle",kind:"pendle-swap"})}async function cI(e={},t={}){let n=await df(e,t),{transaction:r,...o}=n;return o}R();Fe();Y();import{isAddress as vF}from"ethers";var xF="https://api.odos.xyz",pf=(e={})=>(e.baseUrl||process.env.ODOS_API_URL||xF).replace(/\/$/,"");async function mf(e={}){return S(`${pf(e)}/info/chains`,{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs})}function kF(e={}){let t=Number(e.chainId);if(!Number.isInteger(t))throw new Error("odos: chainId required");if(!Array.isArray(e.inputTokens)||e.inputTokens.length<1)throw new Error("odos: inputTokens[] required");if(!Array.isArray(e.outputTokens)||e.outputTokens.length!==1)throw new Error("odos: agentic execution currently requires exactly one output token");if(!vF(String(e.userAddr||"")))throw new Error("odos: valid userAddr required");return t}async function lI(e={},t={}){let n=kF(e),r=We({liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps});if(!r.executable)throw new Error(`odos: route requires ${r.requiredBps} bps above cap ${r.capBps}`);let o={chainId:n,inputTokens:e.inputTokens,outputTokens:e.outputTokens,userAddr:e.userAddr,slippageLimitPercent:r.selectedBps/100,disableRFQs:e.disableRFQs??!0,compact:e.compact??!0,simple:e.simple??!1},i=await S(`${pf(t)}/sor/quote/v3`,{method:"POST",body:o,fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??25e3}),a=i?.outAmounts?.[0];if(!i?.pathId||!a)throw new Error("odos: quote missing pathId or outAmounts[0]");return{chainId:n,selected:r,quote:i,amountOut:a}}async function uI(e={},t={}){let{chainId:n,quote:r,amountOut:o}=await lI(e,t);return{...oe(r,{chainId:n,venue:"odos-quote",amountOut:o,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}),executionReady:!1,executionBlocker:"call prepare to assemble and simulate the path"}}async function dI(e={},t={}){let{chainId:n,quote:r,amountOut:o}=await lI(e,t),i=await S(`${pf(t)}/sor/assemble`,{method:"POST",body:{userAddr:e.userAddr,pathId:r.pathId,simulate:!0,...e.receiver?{receiver:e.receiver}:{}},fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??3e4}),a=i?.transaction;if(!a?.to||!a?.data)throw new Error("odos: assemble returned no executable transaction");if(Number(a.chainId??n)!==n)throw new Error("odos: transaction chain mismatch");if(a.from&&String(a.from).toLowerCase()!==String(e.userAddr).toLowerCase())throw new Error("odos: transaction sender mismatch");if(i?.simulation?.isSuccess!==!0)throw new Error(`odos: assembled transaction simulation failed: ${i?.simulation?.simulationError||"unknown"}`);let s=oe(r,{chainId:n,venue:a.to,amountOut:o,liquidityUsd:e.liquidityUsd,priceChange5m:e.priceChange5m,requestedCapBps:e.maxSlippageBps??e.slippageBps}),c=i?.simulation?.amountsOut?.[0];if(c!=null&&BigInt(c)<BigInt(s.amountOutMinimum))throw new Error("odos: simulation output is below the bounded automatic floor");let l="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",u="0x0000000000000000000000000000000000000000",d=e.inputTokens.filter(p=>![l,u].includes(String(p.tokenAddress).toLowerCase())).map(p=>({token:p.tokenAddress,spender:a.to,amount:String(p.amount)}));return N({provider:"odos",calldataReady:!0,requiresUserSignature:!0,signingReady:!1,broadcastReady:!1,chainId:n,quote:s,simulation:i.simulation,requiresApproval:d,autoSlippage:s.autoSlippage,transaction:{chainId:n,from:a.from||e.userAddr,to:a.to,data:a.data,value:a.value??"0x0",...a.gas!=null?{gasLimit:a.gas}:{},...a.nonce!=null?{nonce:a.nonce}:{},slippageGuard:ye(s.autoSlippage,{chainId:n,venue:a.to,data:a.data})}},{provider:"odos",kind:"odos-tx"})}async function pI(e={}){let t=await mf(e);return{ok:Array.isArray(t?.chains)&&t.chains.length>0,chainCount:t?.chains?.length||0}}R();var mI=/[\u200B-\u200F\u202A-\u202E\u2060-\u2064\uFEFF]/g,IF=/[<>&`*_~[\]()|\\]/g,EF=/[\u0000-\u001F\u007F]/g;function ff(e,{max:t=32,fallback:n=""}={}){return e==null?n:String(e).normalize("NFKC").replace(mI,"").replace(EF,"").replace(IF,"").replace(/\s+/g," ").trim().slice(0,t).trim()||n}function hf(e){if(e==null)return!1;let t=String(e);return mI.test(t)?!0:/[\u0400-\u04FF\u0370-\u03FF]/.test(t)&&/[A-Za-z]/.test(t)}var fI=Object.freeze({1:"https://eth.blockscout.com",10:"https://explorer.optimism.io",137:"https://polygon.blockscout.com",324:"https://zksync.blockscout.com",8453:"https://base.blockscout.com",42161:"https://arbitrum.blockscout.com",534352:"https://scrollscan.com"});function sl(e,t={}){let n=Number(e),r=t.baseUrl||fI[n];if(!r)throw new Error(`Blockscout not configured for chainId ${n}`);return r.replace(/\/$/,"")}function hI(e){return!!fI[Number(e)]}async function gf(e={},t={}){return S(`${sl(e.chainId||1,t)}/api/v2/stats`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3})}async function gI(e={},t={}){if(!e.address)throw new Error("address required");return S(`${sl(e.chainId||1,t)}/api/v2/addresses/${encodeURIComponent(e.address)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3})}async function yI(e={},t={}){if(!e.address&&!e.tokenAddress)throw new Error("token address required");return S(`${sl(e.chainId||1,t)}/api/v2/tokens/${encodeURIComponent(e.address||e.tokenAddress)}`,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??12e3})}async function bI(e={},t={}){if(!e.address)throw new Error("address required");let n=Number(e.chainId||1),r=`${sl(n,t)}/api/v2/addresses/${encodeURIComponent(e.address)}/token-balances`,o=await S(r,{fetchImpl:t.fetchImpl,timeoutMs:t.timeoutMs??18e3,headers:{accept:"application/json","user-agent":"OraclePortfolio/1.0"}});return Array.isArray(o)?o:[]}function wI(e=[],{fungibleOnly:t=!0}={}){let n=[];for(let r of e){if(!r||typeof r!="object")continue;let o=r.token&&typeof r.token=="object"?r.token:{},i=String(o.type||r.token_type||"").toUpperCase();if(t&&i&&!i.includes("ERC-20")&&i!=="ERC20")continue;let a=o.address_hash||o.address||r.token_address||r.tokenAddress||null;if(!a||typeof a!="string")continue;let s=String(r.value??r.balance??"0").replace(/^0x/i,"");if(!/^\d+$/.test(s)||s==="0")continue;let c=o.decimals??r.decimals;typeof c=="string"&&/^\d+$/.test(c)&&(c=Number(c)),(typeof c!="number"||!Number.isInteger(c)||c<0||c>36)&&(c=18);let l=ff(o.symbol||o.name,{max:32,fallback:"TOKEN"}),u=ff(o.name,{max:80,fallback:""})||null;n.push({address:a.toLowerCase().startsWith("0x")?a:`0x${a}`,symbol:l,name:u,decimals:c,amountRaw:s,tokenType:i||"ERC-20",source:"blockscout",verification:"indexer-reported",displaySuspicious:hf(o.symbol)||hf(o.name)||void 0})}return n}async function vI(e={}){let t=await gf({chainId:8453},e);return{ok:t?.total_blocks!=null||t?.total_transactions!=null,chainId:8453}}Mr();R();pe();import{getAddress as _F}from"ethers";dt();Kn();var PF="TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb",kI=Object.freeze({ETH:"coingecko:ethereum",POL:"coingecko:polygon-ecosystem-token",BNB:"coingecko:binancecoin",AVAX:"coingecko:avalanche-2",HYPE:"coingecko:hyperliquid",USDT0:"coingecko:tether",SOL:"coingecko:solana",BTC:"coingecko:bitcoin"});function On(e={},t){return{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs,env:e.env,...e[t]||{}}}function cl(e,...t){for(let n of t){let r=String(e?.[n]||"").trim();if(r)return r}return null}function xI(e){if(!e)return null;try{return _F(String(e).trim().toLowerCase())}catch{throw new Error("portfolio: EVM address must be a valid 20-byte address")}}function hr(e={},t=process.env){let n=e.addresses||{},r=xI(n.evm||e.evmAddress||cl(t,"ORACLE_EVM_ADDRESS","ORACLE_DEFAULT_ADDRESS","MAD_OPERATOR_ADDRESS")),o=n.solana||e.solanaAddress||cl(t,"ORACLE_SOLANA_ADDRESS"),i=n.bitcoin||e.bitcoinAddress||cl(t,"ORACLE_BITCOIN_ADDRESS"),a=xI(n.hyperliquid||e.hyperliquidAddress||cl(t,"ORACLE_HYPERLIQUID_ADDRESS")||r);return{evm:r,solana:o?he(o,"portfolio Solana address"):null,bitcoin:i?kt(i,"portfolio Bitcoin address"):null,hyperliquid:a}}function ya(e,t){let n=BigInt(String(e||"0")),r=Number(t);if(!Number.isInteger(r)||r<0||r>36)throw new Error("portfolio: decimals must be an integer from 0 to 36");if(r===0)return n.toString();let o=n<0n,i=o?-n:n,a=10n**BigInt(r),s=i/a,c=String(i%a).padStart(r,"0").replace(/0+$/,"");return`${o?"-":""}${s}${c?`.${c}`:""}`}function mo(e){let t=Number(e);return Number.isFinite(t)?t:null}function ll(e){return Number.isFinite(e)?Number(e.toFixed(2)):null}function Rn(e){let t=Number(e);return Number.isFinite(t)&&t!==0}function SI(e,t){let n=kI[t],r=n?e?.coins?.[n]:null,o=Number(r?.price);return{key:n||null,priceUsd:Number.isFinite(o)?o:null,timestamp:r?.timestamp??null,confidence:r?.confidence??null}}function CF(e){let t=new Map;for(let n of e)if(n?.ok)for(let r of n.data?.accounts||[]){let o=BigInt(String(r.amount||"0"));if(o===0n||!r.mint)continue;let i=`${r.mint}:${r.decimals??"unknown"}`,a=t.get(i)||{mint:r.mint,amountRaw:0n,decimals:r.decimals??null,programs:new Set,accounts:0};a.amountRaw+=o,a.accounts+=1,n.program&&a.programs.add(n.program),t.set(i,a)}return[...t.values()].map(n=>{let r=n.amountRaw.toString(),o=n.decimals==null?null:ya(r,n.decimals),i=n.decimals===0&&n.amountRaw===1n;return{mint:n.mint,amountRaw:r,amount:o,decimals:n.decimals,tokenPrograms:[...n.programs],accountCount:n.accounts,verification:"unverified",classification:i?"collectible-candidate":"fungible-or-unclassified",priceUsd:null,usdValue:null}})}function yf(e,t){return{family:e,status:"unsupported",reason:t}}function bf(e,t){if(!e||e.status!=="ok")return e;let n=SI(t,e.symbol),r=mo(e.amount),o=r!=null&&n.priceUsd!=null?ll(r*n.priceUsd):null;return{...e,price:n,usdValue:o}}async function II(e={}){let t=hr({},e.env||process.env);return{ok:!0,provider:"portfolio",readOnly:!0,configuredFamilies:Object.entries(t).filter(([,n])=>!!n).map(([n])=>n)}}async function ul(e={},t={}){let n=new Date().toISOString(),r=hr(e,t.env||process.env),o=e.includePrices!==!1,i=e.includeTokens!==!1,a=e.includeCollectibles!==!1,s=new Map(tr.map($=>[$.chainId,$])),c=Array.isArray(e.evmChainIds)&&e.evmChainIds.length?[...new Set(e.evmChainIds.map(Number))]:[...s.keys()],l=[...new Set(Object.values(kI))],u=o?Se(()=>tt(l,On(t,"prices"))):Promise.resolve({ok:!1,ms:0,error:"price lookup disabled"}),d=ve(c,e.concurrency||5,async $=>{let U=s.get($);if(!U)return{family:"evm",chainId:$,name:null,address:r.evm,status:"unsupported",error:"chainId is not in Oracle's configured EVM registry"};if(!r.evm)return{family:"evm",chainId:$,name:U.name,address:null,status:"not-configured",error:"set ORACLE_EVM_ADDRESS or pass addresses.evm"};let ee={...On(t,"evm"),rpcUrl:e.rpcUrls?.[$]||t.evm?.rpcUrls?.[$]},ge=await Se(()=>Vn($,r.evm,ee));if(!ge.ok)return{family:"evm",chainId:$,name:U.name,address:r.evm,status:"unavailable",latencyMs:ge.ms,error:ge.error};let Le=U.nativeCurrency?.decimals??18,Qe=U.nativeCurrency?.symbol||"NATIVE",J=ge.data.balanceWei,xe={status:i?"unavailable":"not-requested",assets:[],reason:i?"EVM JSON-RPC cannot enumerate wallet tokens without an address indexer":"token discovery disabled"};if(i&&hI($)){let jn=await Se(()=>bI({chainId:$,address:r.evm},{...On(t,"blockscout"),timeoutMs:t.timeoutMs??18e3}));jn.ok?xe={status:"ok",assets:wI(jn.data,{fungibleOnly:!0}).map(Oo=>{let Ro=ya(Oo.amountRaw,Oo.decimals);return{...Oo,amount:Ro,priceUsd:null,usdValue:null}}),reason:null,source:"blockscout",latencyMs:jn.ms}:xe={status:"unavailable",assets:[],reason:jn.error||"blockscout token-balances failed",source:"blockscout",latencyMs:jn.ms}}return{family:"evm",chainId:$,name:U.name,address:r.evm,status:"ok",latencyMs:ge.ms,native:{status:"ok",symbol:Qe,amountRaw:J,decimals:Le,amount:ya(J,Le)},fungibleTokens:xe,collectibles:{status:a?"unavailable":"not-requested",assets:[],reason:a?"EVM JSON-RPC cannot enumerate wallet NFTs without an address indexer":"collectible discovery disabled"},source:xe.source==="blockscout"?"evm-rpc+blockscout":"evm-rpc"}}),p=(async()=>{if(!r.solana)return{family:"solana",name:"Solana Mainnet",address:null,status:"not-configured",error:"set ORACLE_SOLANA_ADDRESS or pass addresses.solana"};let $=On(t,"solana"),U=await Se(()=>Zs({address:r.solana},$)),ee=i||a?await Promise.all([Se(()=>Ei({owner:r.solana,programId:$p},$)).then(xe=>({...xe,program:"spl-token"})),Se(()=>Ei({owner:r.solana,programId:PF},$)).then(xe=>({...xe,program:"token-2022"}))]):[],ge=CF(ee),Le=ge.filter(xe=>xe.classification==="collectible-candidate"),Qe=ge.filter(xe=>xe.classification!=="collectible-candidate"),J=ee.filter(xe=>!xe.ok).map(xe=>xe.error);return{family:"solana",name:"Solana Mainnet",address:r.solana,status:U.ok||ee.some(xe=>xe.ok)?"ok":"unavailable",native:U.ok?{status:"ok",symbol:"SOL",amountRaw:U.data.lamports,decimals:9,amount:ya(U.data.lamports,9),slot:U.data.slot}:{status:"unavailable",symbol:"SOL",error:U.error},fungibleTokens:{status:i?J.length===ee.length?"unavailable":J.length?"partial":"ok":"not-requested",assets:i?Qe:[],errors:J,note:"SPL accounts are unverified until a metadata/indexer source confirms symbol and spam status"},collectibles:{status:a?J.length===ee.length?"unavailable":"partial":"not-requested",assets:a?Le:[],errors:J,note:"decimals=0 and amount=1 is only a collectible candidate, not verified NFT metadata"},source:"solana-rpc"}})(),m=(async()=>{if(!r.bitcoin)return{family:"bitcoin",name:"Bitcoin Mainnet",address:null,status:"not-configured",error:"set ORACLE_BITCOIN_ADDRESS or pass addresses.bitcoin"};let $=On(t,"bitcoin"),U=On(t,"bitcoinMeta"),[ee,ge,Le]=await Promise.all([Se(()=>tc({address:r.bitcoin},$)),i?Se(()=>rc({address:r.bitcoin},U)):Promise.resolve({ok:!1,ms:0,error:"token discovery disabled"}),a?Se(()=>Vr({address:r.bitcoin},U)):Promise.resolve({ok:!1,ms:0,error:"collectible discovery disabled"})]),Qe=ge.ok?ge.data:null,J=Le.ok?Le.data:null;return{family:"bitcoin",name:"Bitcoin Mainnet",address:r.bitcoin,status:ee.ok||Qe?.ok||J?.ok?"ok":"unavailable",native:ee.ok?{status:"ok",symbol:"BTC",amountRaw:ee.data.balanceSats,decimals:8,amount:ya(ee.data.balanceSats,8)}:{status:"unavailable",symbol:"BTC",error:ee.error},fungibleTokens:{status:i?Qe?.ok?"ok":"unavailable":"not-requested",assets:Qe?.balances||[],error:Qe?.ok?null:Qe?.error||ge.error,verification:"indexer-reported"},collectibles:{status:a?J?.ok?"ok":"unavailable":"not-requested",assets:J?.inscriptions||[],error:J?.ok?null:J?.error||Le.error,unknownNotEmpty:!!J?.unknownNotEmpty,verification:"indexer-reported"},source:"bitcoin-esplora+bitcoin-meta"}})(),f=(async()=>{if(!r.hyperliquid)return{family:"hyperliquid",name:"Hyperliquid HyperCore",address:null,status:"not-configured",error:"set ORACLE_HYPERLIQUID_ADDRESS or pass addresses.hyperliquid"};let $=On(t,"hyperliquid"),[U,ee,ge]=await Promise.all([Se(()=>qs(r.hyperliquid,$)),Se(()=>Fr(r.hyperliquid,$)),Se(()=>xt($))]),Le=(U.ok&&Array.isArray(U.data?.balances)?U.data.balances:[]).filter(J=>Rn(J.total)||Rn(J.hold)).map(J=>({coin:J.coin||null,total:String(J.total??"0"),hold:String(J.hold??"0"),priceUsd:null,usdValue:null})),Qe=(ee.ok&&Array.isArray(ee.data?.assetPositions)?ee.data.assetPositions:[]).map(J=>J.position||J).filter(J=>Rn(J.szi)).map(J=>({coin:J.coin||null,size:String(J.szi??"0"),entryPrice:J.entryPx??null,positionValueUsd:J.positionValue??null,unrealizedPnlUsd:J.unrealizedPnl??null,liquidationPrice:J.liquidationPx??null}));return{family:"hyperliquid",name:"Hyperliquid HyperCore",address:r.hyperliquid,status:U.ok||ee.ok?"ok":"unavailable",spot:{status:U.ok?"ok":"unavailable",balances:Le,error:U.ok?null:U.error},perps:{status:ee.ok?"ok":"unavailable",accountValueUsd:ee.data?.marginSummary?.accountValue??null,withdrawableUsd:ee.data?.withdrawable??null,positions:Qe,error:ee.ok?null:ee.error},mids:ge.ok?ge.data:{},source:"hyperliquid-info"}})(),[h,g,w,x,b]=await Promise.all([d,p,m,f,u]),y=b.ok?b.data:null,k=Object.freeze({1:"ethereum",10:"optimism",56:"bsc",137:"polygon",8453:"base",42161:"arbitrum",43114:"avax",81457:"blast",534352:"scroll",59144:"linea",324:"era"}),E=[];for(let $ of h){if($.family!=="evm"||$.fungibleTokens?.status!=="ok")continue;let U=k[$.chainId];if(U)for(let ee of $.fungibleTokens.assets||[])ee.address&&E.push(`${U}:${String(ee.address).toLowerCase()}`)}let I=null;if(o&&E.length){let $=[...new Set(E)],U=await Se(()=>tt($,On(t,"prices")));U.ok&&(I=U.data)}let v=h.map($=>{let U=$.native?{...$,native:bf($.native,y)}:$;if(U.fungibleTokens?.status==="ok"&&Array.isArray(U.fungibleTokens.assets)){let ee=k[U.chainId],ge=U.fungibleTokens.assets.map(Le=>{let Qe=String(Le.symbol||"").toUpperCase(),J=null;if(["USDC","USDT","USDT0","DAI","USDBC","USDE","USDCE"].includes(Qe)&&(J=1),J==null&&ee&&Le.address&&I?.coins){let g0=`${ee}:${String(Le.address).toLowerCase()}`,Oo=I.coins[g0],Ro=Number(Oo?.price);Number.isFinite(Ro)&&Ro>0&&(J=Ro)}let xe=mo(Le.amount),jn=xe!=null&&J!=null?ll(xe*J):null;return{...Le,priceUsd:J,usdValue:jn}});U={...U,fungibleTokens:{...U.fungibleTokens,assets:ge}}}return U});g.native&&(g.native=bf(g.native,y)),w.native&&(w.native=bf(w.native,y));let A=0,P=0,T=0;for(let $ of[...v,g,w]){$.native?.status==="ok"&&Rn($.native.amount)&&($.native.usdValue!=null?(A+=$.native.usdValue,P+=1):T+=1);for(let U of $.fungibleTokens?.assets||[])!Rn(U.amount)&&!Rn(U.amountRaw)||(U.usdValue!=null?(A+=U.usdValue,P+=1):T+=1)}let L=SI(y,"HYPE");for(let $ of x.spot?.balances||[]){let U=String($.coin||"").toUpperCase(),ee=U==="USDC"||U==="USDT"||U==="USDT0"?1:U==="HYPE"?L.priceUsd||mo(x.mids?.HYPE):mo(x.mids?.[$.coin]),ge=mo($.total);$.priceUsd=ee,$.usdValue=ge!=null&&ee!=null?ll(ge*ee):null,Rn($.total)&&($.usdValue!=null?(A+=$.usdValue,P+=1):T+=1)}let F=mo(x.perps?.accountValueUsd);F!=null&&F!==0&&(A+=F,P+=1);let q=[...g.fungibleTokens?.assets||[],...g.collectibles?.assets||[]].filter($=>Rn($.amount)).length,O=(w.fungibleTokens?.assets||[]).length+(w.collectibles?.assets||[]).length;T+=q+O;let H=[...v,g,w,x],B=$=>H.filter(U=>U.status===$).length,z=[],le=v.filter($=>$.fungibleTokens?.status==="unavailable"),ue=v.filter($=>$.fungibleTokens?.status==="ok");le.length&&!ue.length?z.push("EVM token discovery is unavailable without a working address indexer; native balances are still live."):le.length&&z.push(`EVM token discovery partial: Blockscout covered ${ue.length} chain(s); ${le.length} chain(s) still native-only.`),(g.fungibleTokens?.assets?.length||g.collectibles?.assets?.length)&&z.push("Solana token accounts are unverified and may include spam; collectible candidates are not confirmed NFTs."),w.collectibles?.unknownNotEmpty&&z.push("Bitcoin inscription holdings are unknown, not zero, because no address indexer is configured."),b.ok||z.push(`Price provider unavailable: ${b.error}`);let Ut=[yf("cosmos","requires a chain-specific bech32 address and LCD/RPC adapter"),yf("sui","Sui balance adapter is not installed"),yf("aptos","Aptos balance adapter is not installed")],an=H.some($=>["unavailable","partial","not-configured"].includes($.fungibleTokens?.status)||["unavailable","partial","not-configured"].includes($.collectibles?.status));return{provider:"portfolio",operation:"balances",readOnly:!0,queriedAt:n,addresses:r,coverage:{requestedSurfaces:H.length,ok:B("ok"),unavailable:B("unavailable"),notConfigured:B("not-configured"),unsupported:B("unsupported")+Ut.length,evmChainsRequested:c.length,evmChainsOk:v.filter($=>$.status==="ok").length},valuation:{knownUsd:ll(A),label:"known priced value, not a complete portfolio total",pricedItems:P,unpricedNonzeroItems:T,complete:T===0&&!an&&B("unavailable")===0&&B("not-configured")===0&&Ut.length===0,priceSource:o?"DefiLlama":null,priceStatus:b.ok?"ok":"unavailable",priceQueriedAt:n},chains:[...v,g,w,x],unsupportedFamilies:Ut,warnings:z}}import{constants as pl}from"node:fs";import{chmod as eD,mkdir as tD,open as nD,readFile as rD}from"node:fs/promises";import{createHash as oD,randomUUID as iD}from"node:crypto";import aD from"node:os";import ho from"node:path";R();R();var NF=Object.freeze(["i.seadn.io","openseauserdata.com","arweave.net","ipfs.io","nftstorage.link","dweb.link","cloudflare-ipfs.com","ordinals.com","ordinals.g.com","cdn.helius-rpc.com","shdw-drive.genesysgo.net"]),OF=new Set(["image/jpeg","image/png","image/webp"]);function RF(e){let t=String(e||"").toLowerCase();return NF.some(n=>t===n||t.endsWith(`.${n}`))}function LF(e){let t=String(e||"").trim();return t.startsWith("ipfs://")?`https://ipfs.io/ipfs/${t.slice(7).replace(/^ipfs\//,"")}`:t.startsWith("ar://")?`https://arweave.net/${t.slice(5)}`:t}function EI(e){let t=LF(e),n;try{n=new URL(t)}catch{return null}return n.protocol!=="https:"||n.username||n.password||!RF(n.hostname)?null:n}async function $F(e,t={}){let n=t.fetchImpl||globalThis.fetch;if(typeof n!="function")throw new Error("gallery fetch unavailable");let r=EI(e);if(!r)throw new Error("image host is not on the raster gallery allowlist");let o=Math.min(Math.max(Number(t.maxImageBytes??15e5),5e4),4e6);for(let i=0;i<=3;i+=1){let a=await Se(()=>n(r.toString(),{method:"GET",redirect:"manual",headers:{accept:"image/jpeg,image/png,image/webp"},signal:AbortSignal.timeout(t.timeoutMs??12e3)}));if(!a.ok)throw new Error(a.error);let s=a.data;if(s.status>=300&&s.status<400){let d=s.headers?.get?.("location");if(!d)throw new Error("image redirect missing location");let p=EI(new URL(d,r).toString());if(!p)throw new Error("image redirect left the host allowlist");r=p;continue}if(!s.ok)throw new Error(`image HTTP ${s.status}`);let c=String(s.headers?.get?.("content-type")||"").split(";",1)[0].toLowerCase();if(!OF.has(c))throw new Error(`unsafe or unsupported image type ${c||"unknown"}`);if(Number(s.headers?.get?.("content-length")||0)>o)throw new Error("image exceeds gallery byte cap");let u=Buffer.from(await s.arrayBuffer());if(!u.length||u.length>o)throw new Error("image exceeds gallery byte cap");return{mimeType:c,data:u.toString("base64"),sourceUrl:r.toString(),bytes:u.length}}throw new Error("too many image redirects")}function wf(e){return String(e??"").replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function BF(e,t){return e.name||e.collection||e.tokenId||`NFT ${t+1}`}async function AI(e={},t={}){let n=Array.isArray(e.items)?e.items:[];if(!n.length)throw new Error("nft gallery requires inventory items");let r=Math.min(Math.max(Number(e.pageSize??12)||12,1),12),o=Math.max(Number(e.page??1)||1,1),i=Math.max(Math.ceil(n.length/r),1);if(o>i)throw new Error(`nft gallery page ${o} exceeds ${i}`);let a=n.slice((o-1)*r,o*r),s=[],c=0,l=Math.min(Math.max(Number(e.maxTotalBytes??8e6),25e4),12e6);for(let b of a){if(c>=l){s.push({item:b,image:null,error:"gallery page byte cap reached"});continue}try{let y=await $F(b.imageUrl||b.originalImageUrl,{...t,maxImageBytes:Math.min(Number(e.maxImageBytes??15e5),l-c)});c+=y.bytes,s.push({item:b,image:y,error:null})}catch(y){s.push({item:b,image:null,error:String(y?.message||y).slice(0,180)})}}let u=3,d=340,p=400,m=76,f=Math.ceil(a.length/u),h=u*d,g=m+f*p,w=s.map(({item:b,image:y,error:k},E)=>{let I=E%u,v=Math.floor(E/u),A=I*d,P=m+v*p,T=y?`<image x="${A+14}" y="${P+14}" width="312" height="312" preserveAspectRatio="xMidYMid slice" href="data:${y.mimeType};base64,${y.data}"/>`:`<rect x="${A+14}" y="${P+14}" width="312" height="312" rx="14" fill="#151820"/><text x="${A+170}" y="${P+165}" text-anchor="middle" fill="#76808f" font-size="16">image unavailable</text>`,L=wf(BF(b,E).slice(0,34)),F=wf(b.chain||"unknown chain");return`${T}<text x="${A+16}" y="${P+350}" fill="#f3f5f7" font-size="17" font-weight="600">${L}</text><text x="${A+16}" y="${P+376}" fill="#8d98a8" font-size="13">${F}${k?" \xB7 placeholder":""}</text>`}).join(""),x=`<svg xmlns="http://www.w3.org/2000/svg" width="${h}" height="${g}" viewBox="0 0 ${h} ${g}"><rect width="100%" height="100%" fill="#090b10"/><text x="24" y="34" fill="#ffffff" font-size="24" font-weight="700">NFT INVENTORY</text><text x="24" y="58" fill="#8d98a8" font-size="14">page ${o} of ${i} \xB7 ${n.length} assets \xB7 generated ${wf(new Date().toISOString())}</text>${w}</svg>`;return{provider:"nft-portfolio",operation:"gallery",mimeType:"image/svg+xml",dataBase64:Buffer.from(x).toString("base64"),page:o,pageSize:r,totalPages:i,totalItems:n.length,renderedItems:s.filter(b=>b.image).length,placeholders:s.filter(b=>!b.image).map(b=>({assetKey:b.item.assetKey||null,name:b.item.name||null,sourceUrl:b.item.imageUrl||null,error:b.error})),rasterOnly:!0,externalScripts:!1}}var MF=[/\bclaim\b/i,/\breward\b/i,/\bairdrop\b/i,/\bvoucher\b/i,/\bwinner\b/i,/\bfree\s*mint\b/i,/\bactivate\b/i,/\bunlock\b/i,/\bverify\b/i,/\bconnect\s+wallet\b/i],UF=/(https?:\/\/|www\.|[a-z0-9-]+\.(?:com|net|io|xyz|org|app|finance|gift|claims?|site|link|live|vip|top|cc))/i,FF=/(\$\s?\d|\d[\d,.]*\s*(?:usd|usdc|usdt|eth|weth|btc|sol)\b)/i;function DF(e={}){let t=[],n=String(e.name||""),r=String(e.description||""),o=`${n} ${r}`;UF.test(n)&&t.push("url-in-name");let i=MF.filter(l=>l.test(o)).length;i>0&&t.push(`lure-language:${i}`),FF.test(n)&&t.push("value-claim-in-name"),/[\u200B-\u200F\u202A-\u202E\uFEFF]/.test(n)&&t.push("invisible-characters"),e.disabled===!0&&t.push("marketplace-disabled");let a=e.estimatedValueUsd==null&&e.estimatedValueSats==null,s=!Array.isArray(e.traits)||e.traits.length===0;a&&s&&i>0&&t.push("valueless-airdrop-with-lure");let c=t.includes("url-in-name")||t.includes("invisible-characters")||t.includes("valueless-airdrop-with-lure")||t.length>=2;return{spam:c,risk:c?"high":t.length>0?"low":"none",reasons:t}}function _I(e={}){let t=DF(e);return{...e,spam:e.spam===!0||t.spam,riskLevel:t.risk,riskReasons:t.reasons.length?t.reasons:void 0}}Y();var qF=Object.freeze([{chain:"ethereum",chainId:1,family:"evm"},{chain:"optimism",chainId:10,family:"evm"},{chain:"polygon",chainId:137,family:"evm"},{chain:"stablechain",chainId:988,family:"evm"},{chain:"hyperevm",chainId:999,family:"evm"},{chain:"abstract",chainId:2741,family:"evm"},{chain:"robinhood",chainId:4663,family:"evm"},{chain:"base",chainId:8453,family:"evm"},{chain:"arbitrum",chainId:42161,family:"evm"},{chain:"avalanche",chainId:43114,family:"evm"},{chain:"hyperliquid",chainId:null,family:"hyperliquid"}]),HF=Object.freeze([{family:"evm",chain:"bsc",chainId:56,reason:"OpenSea account inventory does not support BSC"},{family:"cosmos",reason:"requires a chain-specific bech32 address and NFT indexer"},{family:"sui",reason:"owner inventory adapter not installed"},{family:"aptos",reason:"owner inventory adapter not installed"}]);function gr(e={},t){return{fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs,env:e.env,allowDiskCredentials:e.allowDiskCredentials,allowAmbientCredentials:e.allowAmbientCredentials,...e[t]||{}}}async function ba(e,t){let n=await Se(t);return n.ok?{ok:!0,data:n.data}:{ok:!1,error:`${e}: ${n.error}`.slice(0,300)}}function jF(e){if(Array.isArray(e))return e;for(let t of["items","results","ordinals","inscriptions","data"])if(Array.isArray(e?.[t]))return e[t];return[]}function zF(e={},t){let n=e.inscription_id||e.inscriptionId||e.id||e.inscription||null;return{chain:"bitcoin",family:"bitcoin",owner:t,contract:null,tokenId:n==null?null:String(n),tokenStandard:"ordinal",collection:e.collection_slug||e.collectionSlug||e.collection?.slug||e.collection||null,name:e.name||e.meta?.name||(n?`Inscription ${n}`:"Bitcoin inscription"),description:e.description||e.meta?.description||null,imageUrl:e.image_url||e.imageUrl||e.content_url||e.contentUrl||e.thumbnail||null,originalImageUrl:e.content_url||e.contentUrl||e.image_url||e.imageUrl||null,animationUrl:null,metadataUrl:e.metadata_url||e.metadataUrl||null,marketplaceUrl:e.marketplace_url||e.marketplaceUrl||null,estimatedValueUsd:e.estimated_value_usd!=null&&Number.isFinite(Number(e.estimated_value_usd))?Number(e.estimated_value_usd):null,estimatedValueSats:(e.floor_price_sats??e.price_sats)!=null&&Number.isFinite(Number(e.floor_price_sats??e.price_sats))?Number(e.floor_price_sats??e.price_sats):null,spam:!1,disabled:!1,nsfw:!1,listed:e.listed===!0||e.is_listed===!0,listingId:e.listing_id||e.listingId||null,traits:Array.isArray(e.traits)?e.traits:[],updatedAt:e.updated_at||e.updatedAt||null,acquisitionCost:null,itemPnl:{status:"unavailable",reason:"Satflow wallet inventory does not expose trustworthy acquisition cost"},listingAdapter:"satflow",source:"satflow-wallet-contents"}}function VF(e,t){return{chain:"bitcoin",family:"bitcoin",owner:t,contract:null,tokenId:String(e),tokenStandard:"ordinal",collection:null,name:`Inscription ${e}`,description:null,imageUrl:null,originalImageUrl:null,animationUrl:null,metadataUrl:null,marketplaceUrl:null,estimatedValueUsd:null,spam:!1,disabled:!1,nsfw:!1,traits:[],updatedAt:null,acquisitionCost:null,itemPnl:{status:"unavailable",reason:"address indexer returned no acquisition or valuation data"},listingAdapter:"satflow",source:"bitcoin-meta-address-indexer"}}function TI(e={}){return[e.chain||"unknown",e.contract||"native",e.tokenId||"unknown"].join(":").toLowerCase()}function WF(e){let t=new Map;if(Array.isArray(e)){for(let n of e)n?.assetKey&&t.set(String(n.assetKey).toLowerCase(),n);return t}if(e&&typeof e=="object")for(let[n,r]of Object.entries(e))t.set(n.toLowerCase(),r);return t}function GF(e,t){let n=TI(e),r=t.get(n),o=e.estimatedValueUsd==null?null:Number(e.estimatedValueUsd);if(!r)return{...e,assetKey:n};let i=Number(r.costUsd),a=Number(r.feesUsd??0);if(!Number.isFinite(i)||i<0||!Number.isFinite(a)||a<0)return{...e,assetKey:n,acquisitionCost:null,itemPnl:{status:"unavailable",reason:"invalid user-supplied cost basis"}};let s=Math.round((i+a)*100)/100;return Number.isFinite(o)?{...e,assetKey:n,acquisitionCost:{costUsd:i,feesUsd:a,totalCostUsd:s,acquiredAt:r.acquiredAt||null,source:r.source||"user-supplied"},itemPnl:{status:"estimated",methodology:"provider estimated current value minus supplied USD acquisition cost and fees",unrealizedUsd:Math.round((o-s)*100)/100,currentValueUsd:o,totalCostUsd:s,realizedUsd:null}}:{...e,assetKey:n,acquisitionCost:{costUsd:i,feesUsd:a,totalCostUsd:s,acquiredAt:r.acquiredAt||null,source:r.source||"user-supplied"},itemPnl:{status:"unavailable",reason:"current NFT valuation is unavailable"}}}function KF(e){let t=new Map;for(let n of e){let r=TI(n);t.has(r)||t.set(r,n)}return[...t.values()]}function YF(e,t){let n=e.filter(i=>i.itemPnl?.status==="estimated"),r=e.length-n.length,o=Math.round(n.reduce((i,a)=>i+Number(a.itemPnl.unrealizedUsd||0),0)*100)/100;return{nftItemPnl:{status:r===0&&e.length?"estimated-complete-for-held-items":n.length?"partial":"unavailable",methodology:"Only items with explicit acquisition cost and provider estimated current value are included",knownUnrealizedUsd:o,knownItems:n.length,unknownItems:r,realizedUsd:null,warning:"Transfers, gifts, airdrops, mints, bridges, gas, royalties, and off-market sales can make cost basis unavailable or incomplete."},providerAccountPnl:t}}async function NI(){return{ok:!0,provider:"nft-portfolio",readOnly:!0,marketplaces:["opensea","magiceden-sol","satflow"],listingExecution:"prepare-only"}}async function fo(e={},t={}){let n=new Date().toISOString(),r=hr(e,t.env||process.env),o=Array.isArray(e.chains)&&e.chains.length?new Set(e.chains.map(y=>String(y).toLowerCase())):null,i=qF.filter(y=>!o||o.has(y.chain)),a=[],s=[],c=gr(t,"opensea"),l=r.evm?i.filter(y=>y.family!=="solana"):[],u=await ve(l,4,async y=>({row:y,result:await ba(`opensea-${y.chain}`,()=>ai({chain:y.chain,address:r.evm,pageSize:e.pageSize,maxPages:e.maxPages},c),t.timeoutMs??35e3)}));for(let{row:y,result:k}of u)if(k.ok){let E=k.data.nfts.map(I=>({...I,family:y.family,chainId:y.chainId,listingAdapter:"opensea",source:"opensea-account-inventory"}));s.push(...E),a.push({family:y.family,chain:y.chain,chainId:y.chainId,status:k.data.complete?"ok":"partial",count:E.length,complete:k.data.complete,next:k.data.next,source:"opensea"})}else a.push({family:y.family,chain:y.chain,chainId:y.chainId,status:"unavailable",error:k.error,source:"opensea"});if(!r.evm)for(let y of i.filter(k=>k.family!=="solana"))a.push({family:y.family,chain:y.chain,chainId:y.chainId,status:"not-configured",reason:"EVM address missing"});if(r.solana&&(!o||o.has("solana"))){let y=await ba("opensea-solana",()=>ai({chain:"solana",address:r.solana,pageSize:e.pageSize,maxPages:e.maxPages},c),t.timeoutMs??35e3);if(y.ok){let k=y.data.nfts.map(E=>({...E,family:"solana",chainId:null,listingAdapter:null,source:"opensea-account-inventory"}));s.push(...k),a.push({family:"solana",chain:"solana",status:y.data.complete?"ok":"partial",count:k.length,complete:y.data.complete,next:y.data.next,source:"opensea"})}else a.push({family:"solana",chain:"solana",status:"unavailable",error:y.error,source:"opensea"})}else(!o||o.has("solana"))&&a.push({family:"solana",chain:"solana",status:"not-configured",reason:"Solana address missing"});if(r.bitcoin&&(!o||o.has("bitcoin"))){let y=await ba("satflow-wallet-contents",()=>ic({address:r.bitcoin,type:"ordinals",limit:e.bitcoinLimit??100,offset:0},gr(t,"satflow")),t.timeoutMs??35e3);if(y.ok){let k=jF(y.data.contents).map(I=>zF(I,r.bitcoin));s.push(...k);let E=k.length<Number(e.bitcoinLimit??100);a.push({family:"bitcoin",chain:"bitcoin",status:E?"ok":"partial",count:k.length,complete:E,source:"satflow"})}else{let k=await ba("bitcoin-meta-inscriptions",()=>Vr({address:r.bitcoin},gr(t,"bitcoinMeta")),t.timeoutMs??35e3),E=k.ok&&k.data?.ok&&Array.isArray(k.data.inscriptions)?k.data.inscriptions:[];s.push(...E.map(I=>VF(I,r.bitcoin))),a.push({family:"bitcoin",chain:"bitcoin",status:E.length?"partial":"unavailable",count:E.length,complete:!1,source:E.length?"bitcoin-meta":"satflow",error:E.length?"Satflow unavailable; fallback has IDs only":y.error})}}else(!o||o.has("bitcoin"))&&a.push({family:"bitcoin",chain:"bitcoin",status:"not-configured",reason:"Bitcoin address missing"});let d=[];if(e.includePnl!==!1)for(let y of[...new Set([r.evm,r.solana].filter(Boolean))]){let k=await ba(`opensea-pnl-${y}`,()=>Cs({address:y},c),t.timeoutMs??35e3);d.push(k.ok?{status:"ok",...k.data}:{status:"unavailable",address:y,source:"opensea-indexed-account-pnl",error:k.error})}let p=WF(e.costBasis),m=KF(s).map(y=>GF(y,p)).map(y=>_I(y)),f=m.filter(y=>!y.spam),h=m.filter(y=>y.spam),g=f.filter(y=>y.estimatedValueUsd!=null&&Number.isFinite(Number(y.estimatedValueUsd))),w=Math.round(g.reduce((y,k)=>y+Number(k.estimatedValueUsd),0)*100)/100,x=f.length-g.length,b=a.filter(y=>y.status!=="ok"||y.complete===!1);return{provider:"nft-portfolio",operation:"inventory",readOnly:!0,generatedAt:n,addresses:r,coverage:a,unsupported:HF,inventory:{count:m.length,visibleCount:f.length,flaggedCount:h.length,items:m,visibleItems:f,flaggedItems:h},valuation:{estimatedCurrentValueUsd:w,valuedItems:g.length,unvaluedItems:x,complete:x===0&&b.length===0,methodology:"Sum of provider estimated_value_usd for non-flagged items. It is not an executable bid."},pnl:YF(f,d),listingCoverage:{opensea:"EVM listing actions available with OPENSEA_API_KEY, explicit price/currency/expiry, and user confirmation",satflow:"Bitcoin unsigned listing PSBT available with SATFLOW_API_KEY, explicit price/expiry, and user confirmation",solana:"Magic Eden unsigned list transaction available with MAGICEDEN_API_KEY, explicit SOL price/expiry, and user confirmation",unsupported:"Sui, Aptos, Cosmos, BSC, and unknown marketplaces fail closed"},traitSniperCoverage:{opensea:"Evaluates reveal/trait-floor mispricing only with recent trait sales and volume evidence. Buy intents require local vault signing.",execution:"prepare-only on hosted surfaces; local vault required for purchase"},metadataSafety:{imagesAreUntrusted:!0,animationAndHtmlNotRendered:!0,galleryRasterOnly:!0,missingImagesUsePlaceholders:!0}}}function PI(e,t){let n=typeof e=="number"?e*1e3:Date.parse(String(e||""));if(!Number.isFinite(n))throw new Error(`${t} must be an ISO 8601 timestamp or Unix seconds`);let r=Math.floor(n/1e3);if(r<=Math.floor(Date.now()/1e3))throw new Error(`${t} must be in the future`);return r}function JF(e){let t=String(e??"").trim();if(!/^[1-9]\d*$/.test(t))throw new Error("Bitcoin NFT list priceSats must be a positive integer");return t}async function OI(e={},t={}){if(e.userConfirmed!==!0)throw new Error("NFT listing preparation requires userConfirmed=true after reviewing asset, marketplace, price, currency, fees, royalties, and expiry");let n=String(e.marketplace||"").trim().toLowerCase();if(n==="opensea")return $s(e,gr(t,"opensea"));if(n==="magiceden"||n==="magiceden-sol"){let r=PI(e.expiry??e.endTime,"Solana NFT listing expiry");return Fc({...e,expiry:r},gr(t,"magiceden"))}if(n==="satflow"){let r=PI(e.expiry??e.endTime??e.expiresAt,"Bitcoin NFT listing expiry");return ac({inscription_id:e.inscriptionId||e.tokenId,runes_output:e.runesOutput,ord_address:e.ordAddress||e.seller,receive_address:e.receiveAddress,price:JF(e.priceSats??e.price),tap_key:e.tapKey,collection_slug:e.collectionSlug||e.collection,expires_at:r},gr(t,"satflow"))}throw new Error(`unsupported NFT marketplace: ${n||"<missing>"}`)}function vf(e,t){let n=Number(e);if(!Number.isFinite(n)||n<0)throw new Error(`${t} must be a non-negative ETH number`);return n}function xf(e){if(e==null||e==="")return null;let t=Number(e);return Number.isFinite(t)&&t>0?t:null}function dl(e){return String(e??"").trim().toLowerCase()}function XF(e={},t,n){let r=Array.isArray(e.traits)?e.traits:[],o=dl(t),i=dl(n);return!o||!i?!1:r.some(a=>dl(a.trait_type??a.traitType??a.type)===o&&dl(a.value??a.trait_value??a.traitValue)===i)}function QF(e={},t){if(!t)return!0;let n=String(e.contract||e.tokenContract||e.assetContract||"").toLowerCase();return!n||n===String(t).toLowerCase()}function CI(e={},t=["timestamp","listedAt","createdAt"]){for(let n of t){let r=e[n]??e[n.replace(/[A-Z]/g,i=>`_${i.toLowerCase()}`)];if(r==null)continue;let o=typeof r=="number"?r:Date.parse(String(r));if(Number.isFinite(o))return o}return null}function kf(e){return Math.round(Number(e)*1e6)/1e6}function Ln(e,t,n={}){return{provider:"nft-portfolio",operation:"traitSnipe",marketplace:String(e.marketplace||"").toLowerCase(),collectionSlug:e.collectionSlug||e.collection||null,contract:e.contract||null,decision:"PASS",reason:t,executionReady:!1,signingReady:!1,broadcastReady:!1,requiresLocalVault:!0,best:null,evidence:n,prepareIntent:null}}async function RI(e={},t={}){let n=String(e.marketplace||"").trim().toLowerCase();if(n!=="opensea")return Ln(e,`unsupported NFT marketplace: ${n||"<missing>"}`);let o=["traitType","traitValue","maxPriceEth","minDiscountBps","minTraitSales","minTraitVolumeEth","traitFloorEth"].filter(I=>e[I]==null||e[I]==="");if(o.length)return Ln(e,`trait-risk-params-required: ${o.join(",")}`);let i=Number.isFinite(Number(e.nowMs))?Number(e.nowMs):Date.now(),a=vf(e.maxPriceEth,"maxPriceEth"),s=Number(e.minDiscountBps),c=Number(e.minTraitSales),l=vf(e.minTraitVolumeEth,"minTraitVolumeEth"),u=vf(e.traitFloorEth,"traitFloorEth"),d=xf(e.collectionFloorEth),p=xf(e.maxListingAgeMs),m=xf(e.maxSaleAgeMs??e.salesWindowMs);if(!Number.isFinite(s)||s<0)return Ln(e,"invalid-min-discount-bps");if(!Number.isFinite(c)||c<1)return Ln(e,"invalid-min-trait-sales");if(u<=0)return Ln(e,"trait-floor-unavailable");let f=I=>XF(I,e.traitType,e.traitValue)&&QF(I,e.contract),h=(Array.isArray(e.sales)?e.sales:[]).filter(f).filter(I=>{if(!m)return!0;let v=CI(I,["timestamp","soldAt","createdAt"]);return v!=null&&i-v<=m}),g=kf(h.reduce((I,v)=>I+Number(v.priceEth??v.price??0),0)),w={count:h.length,volumeEth:g,minSales:c,minVolumeEth:l};if(h.length<c||g<l)return Ln(e,"trait-liquidity-insufficient",{traitSales:w});let x=(Array.isArray(e.listings)?e.listings:[]).filter(f).filter(I=>{let v=Number(I.priceEth??I.price);if(!Number.isFinite(v)||v<=0||v>a)return!1;if(!p)return!0;let A=CI(I,["listedAt","createdAt","timestamp"]);return A!=null&&i-A<=p}).map(I=>{let v=Number(I.priceEth??I.price),A=Math.round((u-v)/u*1e4);return{...I,priceEth:v,discountBps:A}}).filter(I=>I.discountBps>=s).sort((I,v)=>I.priceEth-v.priceEth||v.discountBps-I.discountBps),b={traitSales:w,collectionFloorEth:d,traitFloorEth:u,listingDepth:{count:x.length,minFreshListings:e.minTraitListings==null?null:Number(e.minTraitListings)},methodology:"Trait buy intent requires caller-supplied fresh listings, real trait sales, volume, max price, and min discount gates. Rarity metadata alone is ignored."},y=e.minTraitListings==null?1:Number(e.minTraitListings);if(!Number.isFinite(y)||y<1)return Ln(e,"invalid-min-trait-listings",b);if(x.length<y)return Ln(e,"trait-listing-depth-insufficient",b);let k=x[0],E=N({provider:"nft-portfolio",kind:"nft-trait-buy-intent",marketplace:n,chain:e.chain||null,collectionSlug:e.collectionSlug||e.collection||null,contract:e.contract||null,tokenId:k.tokenId==null?null:String(k.tokenId),listingId:k.listingId||null,orderHash:k.orderHash||null,priceEth:kf(k.priceEth),maxPriceEth:a,traitType:e.traitType,traitValue:e.traitValue,evidence:b,localOnly:!0,requiresLocalVault:!0},{provider:"nft-portfolio",kind:"nft-trait-buy-intent",env:t.env||process.env});return{provider:"nft-portfolio",operation:"traitSnipe",marketplace:n,collectionSlug:e.collectionSlug||e.collection||null,contract:e.contract||null,decision:"BUY",reason:"trait-mispricing-evidence-met",executionReady:!1,signingReady:!1,broadcastReady:!1,requiresLocalVault:!0,best:{tokenId:k.tokenId==null?null:String(k.tokenId),listingId:k.listingId||null,orderHash:k.orderHash||null,priceEth:kf(k.priceEth),discountBps:k.discountBps},evidence:b,prepareIntent:E}}async function LI(e={},t={}){let n=await fo({...e,includePnl:!0},t);return{provider:"nft-portfolio",operation:"pnl",readOnly:!0,generatedAt:n.generatedAt,addresses:n.addresses,coverage:n.coverage,unsupported:n.unsupported,valuation:n.valuation,pnl:n.pnl}}async function $I(e={},t={}){let n=Array.isArray(e.items)?e.items:null,r=null;return n||(r=await fo({...e,includePnl:!1},t),n=r.inventory.visibleItems),{...await AI({...e,items:n},gr(t,"gallery")),inventorySummary:r?{visibleCount:r.inventory.visibleCount,flaggedCount:r.inventory.flaggedCount,coverage:r.coverage}:null}}var BI=10*1024*1024,FI=1e3;function $n(e){if(e==null||e==="")return null;let t=Number(e);return Number.isFinite(t)?t:null}function go(e){return Number.isFinite(e)?Number(e.toFixed(2)):null}function MI(e,t){if(e==null||e==="")return null;let n=Date.parse(String(e));if(!Number.isFinite(n))throw new Error(`${t} must be an ISO 8601 timestamp`);return new Date(n).toISOString()}function DI(e,t,n,r,o){if(e==null||e==="")return t;let i=Number(e);if(!Number.isInteger(i)||i<n||i>r)throw new Error(`${o} must be an integer from ${n} to ${r}`);return i}function sD(e={}){return["evm","solana","bitcoin","hyperliquid"].map(t=>`${t}:${String(e[t]||"").trim().toLowerCase()}`).join("|")}function qI(e={}){return`portfolio_${oD("sha256").update(sD(e)).digest("hex").slice(0,20)}`}function HI(e={}){if(e.historyFile)return ho.resolve(String(e.historyFile));let t=e.env||process.env;if(t.ORACLE_PORTFOLIO_HISTORY_FILE)return ho.resolve(String(t.ORACLE_PORTFOLIO_HISTORY_FILE));let n=String(t.HERMES_HOME||"").trim()||ho.join(aD.homedir(),".hermes");return ho.join(ho.resolve(n),"state","oracle","portfolio-history.jsonl")}function cD(e){let t=$n(e?.valuation?.knownUsd);return t==null?null:Number(e?.valuation?.pricedItems||0)>0||e?.valuation?.complete===!0?go(t):null}function lD(e){if(!e||e.status==="unavailable"||e.status==="not-requested")return null;let t=$n(e?.valuation?.estimatedCurrentValueUsd);return t==null?null:Number(e?.valuation?.valuedItems||0)>0||e?.valuation?.complete===!0?go(t):null}function uD(e){let t=[];for(let n of e?.chains||[]){if(n.family==="hyperliquid"){let o=(n.spot?.balances||[]).reduce((s,c)=>{let l=$n(c.usdValue);return l==null?s:s+l},0),i=$n(n.perps?.accountValueUsd),a=go(o+(i??0));(a!==0||i!=null||(n.spot?.balances||[]).some(s=>$n(s.usdValue)!=null))&&t.push({family:"hyperliquid",chainId:null,name:n.name||"Hyperliquid",knownUsd:a});continue}let r=$n(n.native?.usdValue);r!=null&&t.push({family:n.family||"evm",chainId:n.chainId??null,name:n.name||n.native?.symbol||"Unknown",knownUsd:go(r)})}return t}function dD(e,t,n){let r=Array.isArray(t?.coverage)?t.coverage:[];return{balances:e?.coverage||null,nfts:{requested:n,ok:r.filter(o=>o.status==="ok").length,partial:r.filter(o=>o.status==="partial").length,unavailable:r.filter(o=>o.status==="unavailable").length,notConfigured:r.filter(o=>o.status==="not-configured").length,status:n?t?.status==="unavailable"?"unavailable":t?.valuation?.complete?"ok":"partial":"not-requested"}}}async function pD(e,t){let n=HI(t),r=`${JSON.stringify(e)}
|