@spicenet-io/spiceflow-ui 4.21.1 → 4.21.2-rpc-fallback.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  (function(){if(typeof document==="undefined"||document.getElementById("spiceflow-styles"))return;var s=document.createElement("style");s.id="spiceflow-styles";s.textContent="@keyframes spiceflow-spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}@keyframes spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}@media (prefers-reduced-motion:reduce){*,:after,:before{animation-duration:.001ms!important;animation-iteration-count:1!important;scroll-behavior:auto!important;transition-duration:.001ms!important}}.spiceflow-focus-ring:focus-visible,[data-spiceflow-focus]:focus-visible{border-radius:4px;outline:2px solid currentColor;outline-offset:2px}@media (forced-colors:active){.spiceflow-focus-ring:focus-visible,[data-spiceflow-focus]:focus-visible{outline:2px solid Highlight}}.ibm-plex-mono-thin{font-weight:100}.ibm-plex-mono-extralight,.ibm-plex-mono-thin{font-family:IBM Plex Mono,monospace!important;font-style:normal}.ibm-plex-mono-extralight{font-weight:200}.ibm-plex-mono-light{font-weight:300}.ibm-plex-mono-light,.ibm-plex-mono-regular{font-family:IBM Plex Mono,monospace!important;font-style:normal}.ibm-plex-mono-regular{font-weight:400}.ibm-plex-mono-medium{font-weight:500}.ibm-plex-mono-medium,.ibm-plex-mono-semibold{font-family:IBM Plex Mono,monospace!important;font-style:normal}.ibm-plex-mono-semibold{font-weight:600}.ibm-plex-mono-bold{font-family:IBM Plex Mono,monospace!important;font-style:normal;font-weight:700}#privy-modal-content button{border-radius:6px;font-family:IBM Plex Mono,monospace!important;font-size:small;letter-spacing:-.5px;text-transform:uppercase}#privy-modal-content input{background:#fff;border-radius:6px;padding-top:5px!important}#privy-dialog-title{display:none!important;font-size:18px;padding-bottom:10px;padding-top:10px}.AppLogoContainer-sc-a206bd44-0{display:none}#privy-modal-content{background:var(--Neutral-0,#fafafa);border:6px solid var(--Neutral-1,#e9e9e9);box-shadow:inset 0 0 0 1px rgba(0,0,0,.15),0 330px 92px transparent,0 211px 84px rgba(0,0,0,.01),0 119px 71px rgba(0,0,0,.05),0 53px 53px rgba(0,0,0,.09),0 13px 29px rgba(0,0,0,.1);height:auto!important;padding-bottom:10px}.Subtitle-sc-ddbf22b4-4{font-size:12px;margin-top:-14px;opacity:.5}.StyledLink-sc-1c6127e5-0{background:none!important}.StyledLink-sc-c8577138-0,.login-method-button{font-family:IBM Plex Mono,monospace!important}.StyledLink-sc-c8577138-0{font-style:uppercase}#protected-by-privy{color:#000!important}";document.head.appendChild(s)})();
2
- "use strict";var Nd=Object.create;var Ci=Object.defineProperty;var Md=Object.getOwnPropertyDescriptor;var Pd=Object.getOwnPropertyNames;var Ud=Object.getPrototypeOf,Wd=Object.prototype.hasOwnProperty;var qd=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Pd(t))!Wd.call(e,r)&&r!==n&&Ci(e,r,{get:()=>t[r],enumerable:!(s=Md(t,r))||s.enumerable});return e};var Ld=(e,t,n)=>(n=e!=null?Nd(Ud(e)):{},qd(t||!e||!e.__esModule?Ci(n,"default",{value:e,enumerable:!0}):n,e));const c=require("react/jsx-runtime"),d=require("./privy-dPSWODmJ.cjs"),p=require("react"),R=require("@spicenet-io/spiceflow-core"),ns=require("wagmi"),N=require("viem"),Vn=require("viem/actions"),pr=require("@privy-io/react-auth"),fr=require("react-dom");require("@tanstack/react-query");const zd="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@100;200;300;400;500;600;700&display=swap",Hd="spiceflow-ibm-plex-mono",Vd="spiceflow-preconnect-googleapis",Qd="spiceflow-preconnect-gstatic";function qo(e,t){if(document.getElementById(e))return;const n=t();n.id=e,document.head.appendChild(n)}function Gd(){typeof document>"u"||(qo(Vd,()=>{const e=document.createElement("link");return e.rel="preconnect",e.href="https://fonts.googleapis.com",e}),qo(Qd,()=>{const e=document.createElement("link");return e.rel="preconnect",e.href="https://fonts.gstatic.com",e.crossOrigin="",e}),qo(Hd,()=>{const e=document.createElement("link");return e.rel="stylesheet",e.href=zd,e}))}const Kd={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",8453:"0x4200000000000000000000000000000000000006",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",84532:"0x4200000000000000000000000000000000000006"},ki=N.parseAbi(["function deposit() payable","function withdraw(uint256 wad)"]);function Lo(e){return d.getChainConfig(e)?.wrappedNativeTokenAddress??Kd[e]}const zo=(e,t)=>({to:e,value:t,data:N.encodeFunctionData({abi:ki,functionName:"deposit"})}),Ho=(e,t)=>({to:e,value:0n,data:N.encodeFunctionData({abi:ki,functionName:"withdraw",args:[t]})});function Vo(e,t,n){const s=R.isNativeToken(t),r=R.isNativeToken(n);if(!s&&!r)return null;const o=Lo(e);return o?{weth:o,wrapIn:s,unwrapOut:r}:null}function Si(e,t,n,s){const r=Vo(e,t,n);return!r||s<=0n?null:r.wrapIn&&!r.unwrapOut&&n.toLowerCase()===r.weth.toLowerCase()?[zo(r.weth,s)]:r.unwrapOut&&!r.wrapIn&&t.toLowerCase()===r.weth.toLowerCase()?[Ho(r.weth,s)]:null}function Yd(e){return{...e,resolve:async(t,n,s,r)=>{const o=Si(n,t.tokenIn,t.tokenOut,t.amountIn);if(o)return{venue:"native-wrap",amountOut:t.amountIn,amountOutMinimum:t.amountIn,calls:o};const a=await e.resolve(t,n,s,r);if(a)return a;const i=Vo(n,t.tokenIn,t.tokenOut);if(!i)return null;const l=await e.resolve({...t,tokenIn:i.wrapIn?i.weth:t.tokenIn,tokenOut:i.unwrapOut?i.weth:t.tokenOut},n,s,r);return l?{...l,calls:[...i.wrapIn?[zo(i.weth,t.amountIn)]:[],...l.calls,...i.unwrapOut?[Ho(i.weth,l.amountOutMinimum)]:[]]}:null}}}function Zd(e){return{...e,resolve:async(t,n,s)=>{const r=Si(n,t.tokenIn,t.tokenOut,t.amountOut);if(r)return{venue:"native-wrap",amountIn:t.amountOut,amountInMax:t.amountOut,amountOut:t.amountOut,calls:r};const o=await e.resolve(t,n,s);if(o)return o;const a=Vo(n,t.tokenIn,t.tokenOut);if(!a)return null;const i=await e.resolve({...t,tokenIn:a.wrapIn?a.weth:t.tokenIn,tokenOut:a.unwrapOut?a.weth:t.tokenOut},n,s);return i?{...i,calls:[...a.wrapIn?[zo(a.weth,i.amountInMax)]:[],...i.calls,...a.unwrapOut?[Ho(a.weth,i.amountOut)]:[]]}:null}}}const Ii=[100,500,3e3,1e4];function Zr(e,t,n,s,r){const o=[];for(const a of n){const i=typeof a=="object"&&!Array.isArray(a)?a:void 0,l=i?i.tokens:Array.isArray(a)?a:[a];if(!l.length||l.length>2)throw new Error("A v3 route must have one or two intermediate tokens");const u=[e,...l,t];if(i&&(i.feeTiers.length!==u.length-1||i.feeTiers.some(f=>!f.length)))throw new Error("A v3 route needs fee tiers for every pool");if(new Set(u.map(f=>f.toLowerCase())).size!==u.length)continue;const m=(f,h)=>{if(f===u.length){o.push(r==="in"?h:Ai(h));return}for(const y of i?.feeTiers[f-1]??s)m(f+1,N.concatHex([h,N.encodePacked(["uint24","address"],[y,u[f]])]))};m(1,u[0])}return[...new Set(o)]}function Ai(e){const t=e.slice(2),n=[];for(let s=0;s<t.length;){const r=n.length%2===0?40:6;n.push(t.slice(s,s+r)),s+=r}return`0x${n.reverse().join("")}`}const Xd=N.parseAbi(["function exactOutputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 amountOut, uint256 amountInMaximum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountIn)","function exactOutput((bytes path, address recipient, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),Jd=N.parseAbi(["function exactOutputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountIn)","function exactOutput((bytes path, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),$d=1800;function Ei(e){const{config:t,route:n,tokenIn:s,tokenOut:r,recipient:o,amountOut:a}=e,i=e.amountInMaximum,l=e.routerHasDeadline?Jd:Xd,u=e.routerHasDeadline?{deadline:BigInt(Math.floor(Date.now()/1e3)+$d)}:{},m=n.path?N.encodeFunctionData({abi:l,functionName:"exactOutput",args:[{path:n.path,recipient:o,...u,amountOut:a,amountInMaximum:i}]}):N.encodeFunctionData({abi:l,functionName:"exactOutputSingle",args:[{tokenIn:s,tokenOut:r,fee:n.fee,recipient:o,...u,amountOut:a,amountInMaximum:i,sqrtPriceLimitX96:0n}]});return{to:t.swapRouter,value:0n,data:m}}const _d=N.parseAbi(["function quoteExactInput(bytes path, uint256 amountIn) returns (uint256 amountOut, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate)","function quoteExactOutput(bytes path, uint256 amountOut) returns (uint256 amountIn, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate)"]);async function mr(e,t,n,s,r){const o=d.getClientForChain(e),{result:a}=await o.simulateContract({address:t.quoterV2,abi:_d,functionName:r==="in"?"quoteExactInput":"quoteExactOutput",args:[n,s]}),[i,,,l]=a;if(i<=0n)throw new Error("No liquidity along this path.");return{amount:i,gasEstimate:l}}async function eu(e){const{tokenIn:t,tokenOut:n,amountIn:s,fee:r,chainId:o,config:a}=e;if(s<=0n)throw new Error("amountIn must be greater than 0");const i=(await d.getClientForChain(o).simulateContract({address:a.quoterV2,abi:R.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:s,fee:r,sqrtPriceLimitX96:0n}]})).result;if(i[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:i[0],sqrtPriceX96After:i[1],gasEstimate:i[3]}}async function Fi(e){const t=e.feeTiers??Ii,n=Zr(e.tokenIn,e.tokenOut,e.hubs??[],t,"in"),s=await Promise.allSettled([...t.map(async o=>({...await eu({...e,fee:o}),fee:o})),...n.map(async o=>{const a=await mr(e.chainId,e.config,o,e.amountIn,"in");return{amountOut:a.amount,sqrtPriceX96After:0n,gasEstimate:a.gasEstimate,fee:0,path:o}})]);let r=null;for(const o of s)o.status==="fulfilled"&&(!r||o.value.amountOut>r.amountOut)&&(r=o.value);if(!r)throw new Error("No liquidity found for this pair on any fee tier.");return r}const tu=[{inputs:[{components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"amount",type:"uint256"},{name:"fee",type:"uint24"},{name:"sqrtPriceLimitX96",type:"uint160"}],name:"params",type:"tuple"}],name:"quoteExactOutputSingle",outputs:[{name:"amountIn",type:"uint256"},{name:"sqrtPriceX96After",type:"uint160"},{name:"initializedTicksCrossed",type:"uint32"},{name:"gasEstimate",type:"uint256"}],stateMutability:"nonpayable",type:"function"}];async function nu(e){const{tokenIn:t,tokenOut:n,amountOut:s,fee:r,chainId:o,config:a}=e;if(s<=0n)throw new Error("amountOut must be greater than 0");const i=(await d.getClientForChain(o).simulateContract({address:a.quoterV2,abi:tu,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:s,fee:r,sqrtPriceLimitX96:0n}]})).result;if(i[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:i[0],sqrtPriceX96After:i[1],gasEstimate:i[3]}}async function Ti(e){const t=e.feeTiers??Ii,n=Zr(e.tokenIn,e.tokenOut,e.hubs??[],t,"out"),s=await Promise.allSettled([...t.map(async o=>({...await nu({...e,fee:o}),fee:o})),...n.map(async o=>{const a=await mr(e.chainId,e.config,o,e.amountOut,"out");return{amountIn:a.amount,sqrtPriceX96After:0n,gasEstimate:a.gasEstimate,fee:0,path:o}})]);let r=null;for(const o of s)o.status==="fulfilled"&&(!r||o.value.amountIn<r.amountIn)&&(r=o.value);if(!r)throw new Error("No liquidity found for this pair on any fee tier.");return r}function su(e){return e.type==="swap"}const hr=.02,ru=[1,8453,42161,10,137,43114,56],ou="https://api.1inch.dev/swap/v6.0";function Qo(e,t){return R.applySlippage(e,t)}function au(e){const t=e?.baseUrl??ou;return{name:"1inch",chainIds:e?.chainIds??ru,resolve:async(n,s,r)=>{const o=n.maxSlippage??hr,a=o*100,i=R.isNativeToken(n.tokenIn)?R.NATIVE_TOKEN_ADDRESS:n.tokenIn,l=R.isNativeToken(n.tokenOut)?R.NATIVE_TOKEN_ADDRESS:n.tokenOut,u=R.isNativeToken(n.tokenIn);try{const m=new URL(`${t}/${s}/swap`);m.searchParams.set("src",i),m.searchParams.set("dst",l),m.searchParams.set("amount",n.amountIn.toString()),m.searchParams.set("from",r),m.searchParams.set("slippage",a.toString()),m.searchParams.set("disableEstimate","true"),m.searchParams.set("allowPartialFill","false");const f={Accept:"application/json"};e?.apiKey&&(f.Authorization=`Bearer ${e.apiKey}`);const h=await fetch(m.toString(),{headers:f});if(!h.ok)throw new d.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${h.status} for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:`HTTP ${h.status}`});const y=await h.json();if(!y.dstAmount||!y.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const g=BigInt(y.dstAmount);if(g<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const x=Qo(g,o),w=[];return y.tx.to&&!u&&w.push({to:n.tokenIn,value:0n,data:N.encodeFunctionData({abi:N.erc20Abi,functionName:"approve",args:[y.tx.to,n.amountIn]})}),w.push({to:y.tx.to,value:BigInt(y.tx.value||"0"),data:y.tx.data}),{venue:"1inch",amountOut:g,amountOutMinimum:x,calls:w}}catch(m){if(m instanceof d.SpiceflowError)throw m;const f=m instanceof Error?m.message:String(m);throw new d.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}: ${f}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:f})}}}}const Ri=[4114,5115],Go={name:"Satsuma",swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},Bi={name:"Uniswap v3",swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x4200000000000000000000000000000000000006","0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]},Oi={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[1],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2","0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"]},ji={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[42161],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x82aF49447D8a07e3bd95BD0d56f35241523fBab1","0xaf88d065e77c8cC2239327C5EDb3A432268e5831"]},iu={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[137],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270","0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"]},cu={name:"Uniswap v3",swapRouter:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",quoterV2:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",chainIds:[56],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c","0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d"]},lu={name:"Uniswap v3",swapRouter:"0xfe31f71c1b106eac32f1a19239c9a9a72ddfb900",quoterV2:"0x661e93cca42afacb172121ef892830ca3b70f08d",chainIds:[143],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A","0x754704Bc059F8C67012fEd69BC8A327a5aafb603"]},Di={name:"Uniswap v3",swapRouter:"0xcaf681a66d020601342297493863e78c959e5cb2",quoterV2:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",chainIds:[4663],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73","0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"]},Ni={name:"SushiSwap",swapRouter:"0x1e406484F1F204b23cE84B9901C0171a738fd406",quoterV2:"0x3E290e5E01818002A0b672148BdC7514D861C7B3",chainIds:[4663],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73","0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"],routerHasDeadline:!0},Mi=N.parseAbi(["function exactInput((bytes path, address recipient, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),Pi=N.parseAbi(["function exactInputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)","function exactInput((bytes path, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),du=N.parseAbi(["function exactInput((bytes path, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),uu=N.parseAbi(["function exactOutput((bytes path, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),Ko=1800,Ui=[1,50,100,200,2e3],Xr={name:"Aerodrome",swapRouter:"0xcbBb8035cAc7D4B3Ca7aBb74cF7BdF900215Ce0D",quoterV2:"0x3d4C22254F86f64B7eC90ab8F7aeC1FBFD271c6C",chainIds:[8453],hubCurrencies:["0x4200000000000000000000000000000000000006","0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]};function gr(e){const t=e.name??"Aerodrome",n=e.chainIds??[8453],s=e.tickSpacings??Ui;return{name:t,chainIds:n,resolve:async(r,o,a)=>{if(R.isNativeToken(r.tokenIn)||R.isNativeToken(r.tokenOut))return null;const i=r.maxSlippage??hr,l=[...s.map(w=>N.encodePacked(["address","uint24","address"],[r.tokenIn,w,r.tokenOut])),...Zr(r.tokenIn,r.tokenOut,e.hubCurrencies??[],s,"in")],u={quoterV2:e.quoterV2},m=await Promise.allSettled(l.map(async w=>({path:w,amountOut:(await mr(o,u,w,r.amountIn,"in")).amount})));let f=null;for(const w of m)w.status==="fulfilled"&&(!f||w.value.amountOut>f.amountOut)&&(f=w.value);if(!f)return console.warn(`[AerodromeVenue] No viable route for ${r.tokenIn} \u2192 ${r.tokenOut} on chain ${o}.`),null;const h=Qo(f.amountOut,i),y=e.deadline??BigInt(Math.floor(Date.now()/1e3)+Ko),g=N.encodeFunctionData({abi:du,functionName:"exactInput",args:[{path:f.path,recipient:a,deadline:y,amountIn:r.amountIn,amountOutMinimum:h}]}),x=[{to:r.tokenIn,value:0n,data:N.encodeFunctionData({abi:N.erc20Abi,functionName:"approve",args:[e.swapRouter,r.amountIn]})},{to:e.swapRouter,value:0n,data:g}];return{venue:t,amountOut:f.amountOut,amountOutMinimum:h,calls:x}}}}function Wi(e){const t=e.name??"Aerodrome",n=e.chainIds??[8453],s=e.tickSpacings??Ui;return{name:t,chainIds:n,resolve:async(r,o,a)=>{if(R.isNativeToken(r.tokenIn)||R.isNativeToken(r.tokenOut))return null;const i=r.maxSlippage??hr,l=[...s.map(x=>N.encodePacked(["address","uint24","address"],[r.tokenOut,x,r.tokenIn])),...Zr(r.tokenIn,r.tokenOut,e.hubCurrencies??[],s,"out")],u={quoterV2:e.quoterV2},m=await Promise.allSettled(l.map(async x=>({path:x,amountIn:(await mr(o,u,x,r.amountOut,"out")).amount})));let f=null;for(const x of m)x.status==="fulfilled"&&(!f||x.value.amountIn<f.amountIn)&&(f=x.value);if(!f)return console.warn(`[AerodromeExactOutputVenue] No viable route for ${r.tokenIn} \u2192 ${r.tokenOut} on chain ${o}.`),null;const h=BigInt(Math.round(i*1e4)),y=f.amountIn+f.amountIn*h/10000n,g=e.deadline??BigInt(Math.floor(Date.now()/1e3)+Ko);return{venue:t,amountIn:f.amountIn,amountInMax:y,amountOut:r.amountOut,calls:[{to:e.swapRouter,value:0n,data:N.encodeFunctionData({abi:uu,functionName:"exactOutput",args:[{path:f.path,recipient:a,deadline:g,amountOut:r.amountOut,amountInMaximum:y}]})}]}}}}function wr(e){const t=e.name??"Uniswap v3",n=e.chainIds??Ri;return{name:t,chainIds:n,resolve:async(s,r,o,a)=>{if(R.isNativeToken(s.tokenIn)||R.isNativeToken(s.tokenOut))return null;const i=s.maxSlippage??hr;let l;try{let g;if(a){if(a.venue!==t)return null;const x=a.calls.find(b=>b.to.toLowerCase()===e.swapRouter.toLowerCase());if(!x)return null;const w=N.decodeFunctionData({abi:e.routerHasDeadline?Pi:[...Mi,...R.uniV3SwapRouterAbi],data:x.data});if(w.functionName==="exactInput"){const{path:b}=w.args[0];if(b.slice(0,42).toLowerCase()!==s.tokenIn.toLowerCase()||`0x${b.slice(-40)}`.toLowerCase()!==s.tokenOut.toLowerCase())return null;g={path:b,fee:0}}else if(w.functionName==="exactInputSingle"){const{tokenIn:b,tokenOut:k,fee:A}=w.args[0];if(b.toLowerCase()!==s.tokenIn.toLowerCase()||k.toLowerCase()!==s.tokenOut.toLowerCase())return null;g={fee:A}}else return null}l=g?.path?{...g,amountOut:(await mr(r,e,g.path,s.amountIn,"in")).amount}:await Fi({tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn,chainId:r,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:g?[g.fee]:e.feeTiers,hubs:g?[]:[...e.hubCurrencies??[],...e.hubPaths??[]]})}catch{return console.warn(`[UniV3Venue] No viable route for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${r}.`),null}const u=Qo(l.amountOut,i),m=e.routerHasDeadline?{deadline:BigInt(Math.floor(Date.now()/1e3)+Ko)}:{},f=e.routerHasDeadline?Pi:l.path?Mi:R.uniV3SwapRouterAbi,h=l.path?N.encodeFunctionData({abi:f,functionName:"exactInput",args:[{path:l.path,recipient:o,...m,amountIn:s.amountIn,amountOutMinimum:u}]}):N.encodeFunctionData({abi:f,functionName:"exactInputSingle",args:[{tokenIn:s.tokenIn,tokenOut:s.tokenOut,fee:l.fee,recipient:o,...m,amountIn:s.amountIn,amountOutMinimum:u,sqrtPriceLimitX96:0n}]}),y=[{to:s.tokenIn,value:0n,data:N.encodeFunctionData({abi:N.erc20Abi,functionName:"approve",args:[e.swapRouter,s.amountIn]})},{to:e.swapRouter,value:0n,data:h}];return{venue:t,amountOut:l.amountOut,amountOutMinimum:u,calls:y}}}}function Yo(e){const t=e.name??"Uniswap v3",n=e.chainIds??Ri;return{name:t,chainIds:n,resolve:async(s,r,o)=>{if(R.isNativeToken(s.tokenIn)||R.isNativeToken(s.tokenOut))return null;const a=s.maxSlippage??hr;let i;try{i=await Ti({tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountOut:s.amountOut,chainId:r,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers,hubs:[...e.hubCurrencies??[],...e.hubPaths??[]]})}catch{return null}const l=BigInt(Math.round(a*1e4)),u=i.amountIn+i.amountIn*l/10000n;return{venue:t,amountIn:i.amountIn,amountInMax:u,amountOut:s.amountOut,calls:[Ei({config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},routerHasDeadline:e.routerHasDeadline,route:i,tokenIn:s.tokenIn,tokenOut:s.tokenOut,recipient:o,amountOut:s.amountOut,amountInMaximum:u})]}}}}function qi(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(wr(e.satsuma)),e?.aerodrome!==!1&&t.push(gr(e?.aerodrome??Xr)),t.push(au(e?.oneInch));const n=t.map(Yd);function s(a){return n.find(i=>i.chainIds.includes(a))}async function r(a,i,l,u){const m=n.filter(g=>g.chainIds.includes(i));if(m.length===0)throw new d.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${i}. Cannot resolve swap ${a.tokenIn} \u2192 ${a.tokenOut}.`,{chainId:i,tokenIn:a.tokenIn,tokenOut:a.tokenOut,amountIn:a.amountIn.toString()});const f=await Promise.allSettled(m.map(g=>g.resolve(a,i,l,u)));let h=null;for(const g of f)u&&g.status==="fulfilled"&&g.value&&(g.value.venue!==u.venue||g.value.calls.length!==u.calls.length||g.value.calls.some((x,w)=>x.to.toLowerCase()!==u.calls[w].to.toLowerCase()||x.data.slice(0,10)!==u.calls[w].data.slice(0,10)))||g.status==="fulfilled"&&g.value&&(!h||g.value.amountOut>h.amountOut)&&(h=g.value);if(h)return h;const y=f.find(g=>g.status==="rejected");if(y)throw y.reason;return null}async function o(a,i,l){const u=[],m=[];for(const f of a){if(!su(f)){u.push(f);continue}const h=await r(f,i,l);if(!h)throw new d.SpiceflowError("NO_LIQUIDITY",`No venue returned a quote for ${f.tokenIn} \u2192 ${f.tokenOut} on chain ${i}.`,{chainId:i,tokenIn:f.tokenIn,tokenOut:f.tokenOut,amountIn:f.amountIn.toString()});u.push(...h.calls),m.push(h)}return{calls:u,resolvedSwaps:m}}return{resolveSwapIntents:o,resolveSwap:r,getVenueForChain:s,venues:t}}const Xn="0x0000000000000000000000000000000000000000",Zo=[{fee:100,tickSpacing:1},{fee:500,tickSpacing:10},{fee:3e3,tickSpacing:60},{fee:1e4,tickSpacing:200}],Li=Xn,zi=.02,pu=1800,Hi={name:"Uniswap v4",quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",universalRouter:"0x6ff5693b99212da76ad316178a184ab56d299b43",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",chainIds:[8453],hubCurrencies:["0x4200000000000000000000000000000000000006",Xn,"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]},Vi={name:"Uniswap v4",quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",universalRouter:"0x8876789976decbfcbbbe364623c63652db8c0904",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",routerHasHopPrice:!0,chainIds:[4663],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73",Xn,"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"]},Qi=N.parseAbi(["struct PoolKey { address currency0; address currency1; uint24 fee; int24 tickSpacing; address hooks; }","struct PathKey { address intermediateCurrency; uint24 fee; int24 tickSpacing; address hooks; bytes hookData; }","struct QuoteExactSingleParams { PoolKey poolKey; bool zeroForOne; uint128 exactAmount; bytes hookData; }","struct QuoteExactParams { address exactCurrency; PathKey[] path; uint128 exactAmount; }","function quoteExactInputSingle(QuoteExactSingleParams params) returns (uint256 amountOut, uint256 gasEstimate)","function quoteExactInput(QuoteExactParams params) returns (uint256 amountOut, uint256 gasEstimate)","function quoteExactOutputSingle(QuoteExactSingleParams params) returns (uint256 amountIn, uint256 gasEstimate)","function quoteExactOutput(QuoteExactParams params) returns (uint256 amountIn, uint256 gasEstimate)"]),fu=N.parseAbi(["function approve(address token, address spender, uint160 amount, uint48 expiration)"]),mu=N.parseAbi(["function execute(bytes commands, bytes[] inputs, uint256 deadline) payable"]),Gi="0x10",hu="04",gu="06",wu="07",xu="08",yu="09",Jr="0c",$r="0e",bu=[{name:"currency0",type:"address"},{name:"currency1",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"}],vu=[{name:"intermediateCurrency",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"},{name:"hookData",type:"bytes"}],ss=(e,t)=>e.toLowerCase()===t.toLowerCase();function _r(e){return R.isNativeToken(e)?Xn:e}function Cu(e,t){return e.toLowerCase()<t.toLowerCase()?[e,t]:[t,e]}function Ki(e,t,n,s,r){const o=[],[a,i]=Cu(e,t);for(const{fee:u,tickSpacing:m}of Zo)o.push({kind:"single",poolKey:{currency0:a,currency1:i,fee:u,tickSpacing:m,hooks:Li},zeroForOne:ss(e,a)});const l=(u,m)=>!!r&&(ss(u,Xn)&&ss(m,r)||ss(u,r)&&ss(m,Xn));for(const u of n)if(!(ss(u,e)||ss(u,t))&&!(l(u,e)||l(u,t)))for(const m of Zo)for(const f of Zo){const h=(y,g)=>({intermediateCurrency:y,fee:g.fee,tickSpacing:g.tickSpacing,hooks:Li,hookData:"0x"});o.push({kind:"multi",path:s==="in"?[h(u,m),h(t,f)]:[h(e,m),h(u,f)]})}return o}async function Yi(e,t,n,s,r,o){const a=d.getClientForChain(e),i=(await Promise.allSettled(n.map(async l=>{const{result:u}=l.kind==="single"?await a.simulateContract({address:t.quoter,abi:Qi,functionName:o==="in"?"quoteExactInputSingle":"quoteExactOutputSingle",args:[{poolKey:l.poolKey,zeroForOne:l.zeroForOne,exactAmount:r,hookData:"0x"}]}):await a.simulateContract({address:t.quoter,abi:Qi,functionName:o==="in"?"quoteExactInput":"quoteExactOutput",args:[{exactCurrency:s,path:l.path,exactAmount:r}]}),m=u[0];if(m<=0n)throw new Error("zero quote");return{candidate:l,amount:m}}))).filter(l=>l.status==="fulfilled").map(l=>l.value);return i.length===0?null:(i.sort((l,u)=>l.amount<u.amount?-1:l.amount>u.amount?1:0),o==="in"?i[i.length-1]:i[0])}function Zi(e){const{candidate:t,direction:n,currencyIn:s,currencyOut:r,recipient:o,exactAmount:a,limitAmount:i,deadline:l,routerHasHopPrice:u,sweepNativeTo:m}=e;let f,h;t.kind==="single"?(f=n==="in"?`0x${gu}${Jr}${$r}`:`0x${xu}${Jr}${$r}`,h=N.encodeAbiParameters([{type:"tuple",components:[{name:"poolKey",type:"tuple",components:bu},{name:"zeroForOne",type:"bool"},{name:n==="in"?"amountIn":"amountOut",type:"uint128"},{name:n==="in"?"amountOutMinimum":"amountInMaximum",type:"uint128"},...u?[{name:"minHopPriceX36",type:"uint256"}]:[],{name:"hookData",type:"bytes"}]}],[{poolKey:t.poolKey,zeroForOne:t.zeroForOne,[n==="in"?"amountIn":"amountOut"]:a,[n==="in"?"amountOutMinimum":"amountInMaximum"]:i,...u?{minHopPriceX36:0n}:{},hookData:"0x"}])):(f=n==="in"?`0x${wu}${Jr}${$r}`:`0x${yu}${Jr}${$r}`,h=N.encodeAbiParameters([{type:"tuple",components:[{name:n==="in"?"currencyIn":"currencyOut",type:"address"},{name:"path",type:"tuple[]",components:vu},...u?[{name:"minHopPriceX36",type:"uint256[]"}]:[],{name:n==="in"?"amountIn":"amountOut",type:"uint128"},{name:n==="in"?"amountOutMinimum":"amountInMaximum",type:"uint128"}]}],[{[n==="in"?"currencyIn":"currencyOut"]:n==="in"?s:r,path:t.path,...u?{minHopPriceX36:[]}:{},[n==="in"?"amountIn":"amountOut"]:a,[n==="in"?"amountOutMinimum":"amountInMaximum"]:i}]));const y=N.encodeAbiParameters([{type:"address"},{type:"uint256"}],[s,n==="in"?a:i]),g=N.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"}],[r,o,0n]),x=N.encodeAbiParameters([{type:"bytes"},{type:"bytes[]"}],[f,[h,y,g]]),w=m?`${Gi}${hu}`:Gi,b=m?[x,N.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"}],[Xn,m,0n])]:[x];return N.encodeFunctionData({abi:mu,functionName:"execute",args:[w,b,l]})}function Xi(){return BigInt(Math.floor(Date.now()/1e3)+pu)}function Ji(e,t,n,s){return{to:e.permit2,value:0n,data:N.encodeFunctionData({abi:fu,functionName:"approve",args:[t,e.universalRouter,n,Number(s)]})}}function $i(e){const t=e.name??"Uniswap v4",n=e.v3?wr({...e.v3,chainIds:e.chainIds}):null;return{name:t,chainIds:e.chainIds,resolve:async(s,r,o)=>{const a=s.maxSlippage??zi,i=_r(s.tokenIn),l=_r(s.tokenOut),u=R.isNativeToken(s.tokenIn),m=e.hubCurrencies??[Xn];let f=null;if(!ss(i,l)&&s.amountIn>0n){const h=await Yi(r,e,Ki(i,l,m,"in",Lo(r)),i,s.amountIn,"in").catch(()=>null);if(h){const y=R.applySlippage(h.amount,a),g=Xi(),x=[];u||(x.push({to:s.tokenIn,value:0n,data:N.encodeFunctionData({abi:N.erc20Abi,functionName:"approve",args:[e.permit2,s.amountIn]})}),x.push(Ji(e,s.tokenIn,s.amountIn,g))),x.push({to:e.universalRouter,value:u?s.amountIn:0n,data:Zi({candidate:h.candidate,direction:"in",currencyIn:i,currencyOut:l,recipient:o,exactAmount:s.amountIn,limitAmount:y,deadline:g,routerHasHopPrice:e.routerHasHopPrice})}),f={venue:t,amountOut:h.amount,amountOutMinimum:y,calls:x}}}return!f&&n?n.resolve(s,r,o):f}}}function _i(e){const t=e.name??"Uniswap v4";return{name:t,chainIds:e.chainIds,resolve:async(n,s,r)=>{const o=R.isNativeToken(n.tokenIn),a=_r(n.tokenIn),i=_r(n.tokenOut);if(ss(a,i)||n.amountOut<=0n)return null;const l=n.maxSlippage??zi,u=e.hubCurrencies??[Xn],m=await Yi(s,e,Ki(a,i,u,"out",Lo(s)),i,n.amountOut,"out").catch(()=>null);if(!m)return null;const f=BigInt(Math.round(l*1e4)),h=m.amount+m.amount*f/10000n,y=Xi();return{venue:t,amountIn:m.amount,amountInMax:h,amountOut:n.amountOut,calls:[...o?[]:[Ji(e,n.tokenIn,h,y)],{to:e.universalRouter,value:o?h:0n,data:Zi({candidate:m.candidate,direction:"out",currencyIn:a,currencyOut:i,recipient:r,exactAmount:n.amountOut,limitAmount:h,deadline:y,routerHasHopPrice:e.routerHasHopPrice,sweepNativeTo:o?r:void 0})}]}}}}const Xo=[{...Go,protocol:"uniswap-v3",chainId:4114},{...Go,protocol:"uniswap-v3",chainId:5115},{...Bi,protocol:"uniswap-v3",chainId:8453},{...Oi,protocol:"uniswap-v3",chainId:1},{...ji,protocol:"uniswap-v3",chainId:42161},{...iu,protocol:"uniswap-v3",chainId:137},{...cu,protocol:"uniswap-v3",chainId:56},{...lu,protocol:"uniswap-v3",chainId:143},{...Di,protocol:"uniswap-v3",chainId:4663},{...Ni,protocol:"uniswap-v3",chainId:4663},{...Hi,protocol:"uniswap-v4",chainId:8453},{...Vi,protocol:"uniswap-v4",chainId:4663},{...Xr,protocol:"aerodrome-slipstream",chainId:8453}];function Fs(e){const t=e?.includeDefaults===!1?e.venues??[]:[...Xo,...e?.venues??[]],n=[],s=[];for(const r of t){const o=[r.chainId];switch(r.protocol){case"uniswap-v3":{const a={...r,chainIds:o};n.push(wr(a)),s.push(Yo(a));break}case"uniswap-v4":{const a={...r,chainIds:o};n.push($i(a)),s.push(_i(a));break}case"aerodrome-slipstream":{const a={...r,chainIds:o};n.push(gr(a)),s.push(Wi(a));break}default:{const a=r;throw new d.SpiceflowError("INVALID_PARAMS",`Unsupported liquidity venue protocol: ${a.protocol}`,{protocol:a.protocol})}}}return{input:n,output:s}}const Jo=new Set(["WBTC","CBTC"]),ec=new Set(["btc","wbtc","wcbtc","cbtc"]);function tc(e,t){return!e||!t?!1:e===t?!0:Jo.has(e)&&Jo.has(t)}function kn(e){const[t,n,s]=e.split(":");if(t!=="evm"||!n||!s)return null;const r=Number(n);if(!Number.isFinite(r))return null;const o=s.startsWith("0x")?s.toLowerCase():`0x${s.toLowerCase()}`;return{chainId:r,address:o}}function eo(e){return(e??"").trim().replace(/^test\s+/i,"").replace(/^spice/i,"").toLowerCase().replace(/[^a-z0-9]/g,"")}function ku(e){return new Set([e.receiptTokenName,e.displaySymbol,e.symbol,e.displayName,e.name].map(eo).filter(Boolean))}function Su(e,t){const n=ku(e),s=[t.symbol,t.name,t.equivalenceGroup].map(eo);if(s.some(a=>a&&n.has(a)))return!0;const r=[...n].some(a=>ec.has(a)),o=s.some(a=>ec.has(a))||Jo.has(t.equivalenceGroup??"");return r&&o}function nc(e,t,n){const s=new Set(t.map(eo).filter(Boolean)),r=o=>{if(n&&d.addressesEqual(o.address,n))return 0;const a=[o.symbol,o.name,o.equivalenceGroup].map(eo).findIndex(i=>i&&s.has(i));return a===-1?4:a+1};return[...e].sort((o,a)=>{const i=r(o)-r(a);return i!==0?i:o.address.toLowerCase().localeCompare(a.address.toLowerCase())})}function Vs(e,t){const n=e.chainTokens?Object.keys(e.chainTokens):[],s=[];for(const r of n){const o=kn(r);if(!o||o.chainId!==t)continue;const a=o.address,i=R.isNativeToken(a)?d.getChainConfig(t)?.nativeCurrency:void 0,l=R.getTokenByAddress(a,t)??(i?{...i}:void 0);l&&(!$o(e,a,t)&&!(e.isUniversal&&Su(e,l))||s.some(u=>d.addressesEqual(u,a))||s.push(a))}return nc(s.map(r=>{const o=R.getTokenByAddress(r,t);return{address:r,symbol:o?.symbol,name:o?.name,equivalenceGroup:o?.equivalenceGroup}}),[e.receiptTokenName,e.displaySymbol,e.symbol,e.displayName,e.name],e.chainId===t&&!e.isUniversal?e.address:void 0).map(r=>r.address)}function $o(e,t,n){return e.chainId===n&&d.addressesEqual(e.address,t)?!0:xr(e.address,e.chainId,t,n)}async function Iu(e,t){const n=d.getClientForChain(e),s=R.getEscrowContractAddress(e);return R.isNativeToken(t)?n.getBalance({address:s}):await n.readContract({address:t,abi:N.erc20Abi,functionName:"balanceOf",args:[s]})}function _o(e,t,n){const s=R.getTokensForChain(n),r=s.find(a=>d.addressesEqual(a.address,e));if(r&&(t===n||!R.isNativeToken(e)))return r;const o=R.getTokenByAddress(e,t);if(o)return nc(s.filter(a=>tc(a.equivalenceGroup,o.equivalenceGroup)),[o.symbol,o.name,o.equivalenceGroup])[0]}function to(e){return e.equivalenceGroup==="USDC"&&e.symbol.toUpperCase()!=="USDT"}function Ts(e){const t=R.getEscrowContract(e);if(!t||t===R.ZERO_ADDRESS)return;const n=R.getTokensForChain(e).filter(to);return n.find(s=>s.symbol.toUpperCase()==="USDC")??n[0]}function ea(e,t){if(e.chainId===t)return null;const n=R.getEscrowContract(e.chainId),s=R.getEscrowContract(t);if(!n||n===R.ZERO_ADDRESS||!s||s===R.ZERO_ADDRESS)return null;const r=!e.isNative&&!R.isNativeToken(e.address)?R.getTokenByAddress(e.address,e.chainId):void 0,o=r&&to(r)?_o(e.address,e.chainId,t):void 0,a=o?r:Ts(e.chainId),i=o??Ts(t);if(!a||!i)return null;const l=u=>({address:u.address,symbol:u.symbol,decimals:u.decimals,chainId:u.chainId});return{source:l(a),destination:l(i)}}function Au(e,t){return!!ea(e,t)}function Nn(e,t){if(e.chainId===t)return e.address;const n=_o(e.address,e.chainId,t);return n?n.address:null}async function Jn(e,t,n,s){const r=R.getTokenByAddress(t,n);return r?r.decimals:e?.chainId===n&&d.addressesEqual(e.address,t)&&!e.isUniversal?e.decimals:s?.chainId===n&&d.addressesEqual(s.address,t)?s.decimals:d.getTokenDecimals(n,t)}async function sc(e,t,n={}){const s=Nn(e,t),r=Vs(e,t);if(r.length===0)return s;if(r.length===1)return r[0];const o=n.requiredAmount??0n,a=i=>{const l=r.map(u=>({candidate:u,balance:i.get(R.isNativeToken(u)?"native":u.toLowerCase())??0n})).filter(u=>u.balance>0n).sort((u,m)=>u.balance===m.balance?0:u.balance>m.balance?-1:1);return l.length===0?null:((o>0n?l.find(u=>u.balance>=o):l[0])??l[0]).candidate};try{const i=await Promise.all(r.map(async m=>({key:R.isNativeToken(m)?"native":m.toLowerCase(),value:await Iu(t,m)}))),l=new Map(i.map(({key:m,value:f})=>[m,f])),u=a(l);if(u)return u}catch{}return s}function xr(e,t,n,s){const r=R.getTokenByAddress(e,t),o=R.getTokenByAddress(n,s);return r&&o?tc(r.equivalenceGroup,o.equivalenceGroup):R.areEquivalent(e,n)}function no(e,t){return xr(e.address,e.chainId,t.address,t.chainId)}const rc=.01;function oc(e,t=!1){const n=Number.isFinite(e.balanceUsd)&&e.balanceUsd>0;return e.isDiscovered?n&&e.balanceUsd>=rc:!t||!n||e.balanceUsd>=rc}function Qs(e,t=!1){return!!e&&e._source==="wallet"&&(e.location==="external"||e._fundingWallet==="external"||!e.location&&!e._fundingWallet&&t)}function he(e){return e.positionId??`${e.owner?.toLowerCase()??""}:${e.location??e._source??""}:${e.chainId}:${e.receiptTokenId??R.normalizeNativeTokenAddress(e.address).toLowerCase()}`}function ac(e,t){if(!t?.length||e.symbol!==void 0&&d.isAssetAllowed({...e,symbol:e.symbol},t))return!0;const n=s=>t.some(r=>d.addressesEqual(R.normalizeNativeTokenAddress(r),R.normalizeNativeTokenAddress(s)));return n(e.address)||Object.keys(e.chainTokens??{}).some(s=>{const r=kn(s);return r?n(r.address):!1})}function Qn(e,t,n,s,r,o){const a=(x,w=!1)=>({eligible:!1,reason:x,policyExcluded:w}),i=e._source==="wallet"||e.location==="external"||e.location==="embedded",l=t==="spend-source"&&i&&!!s&&e.chainId===s.chainId&&d.addressesEqual(R.normalizeNativeTokenAddress(e.address),R.normalizeNativeTokenAddress(s.address));if(n.isWhitelistGateActive||!l&&!d.isAssetAllowed(e,n.allowedTokens))return a("Asset excluded by client policy",!0);if(t!=="withdraw-destination"&&!l&&!oc(e))return a("Asset is unpriced or below the minimum value",!0);if(t==="holding")return{eligible:!0,reason:null};if(e.balanceError)return a(e.balanceError);if(!l&&!ac(e,r))return a("Asset excluded by action policy",!0);const u=new Set(s?[s.chainId]:[]);e._source!=="spice"&&e.location!=="rollup"&&u.add(e.chainId);for(const x of u)if(!d.getRpcUrlForChain(x,n.rpcOverrides)?.trim())return a(`Configure SpiceFlowProvider rpcOverrides[${x}] before using this asset.`);if(o?.requiresEscrow){const x=R.getTokenByAddress(e.address,e.chainId);if(!x||!to(x))return a("This asset has no supported escrow mapping")}if(!s)return{eligible:!0,reason:null};const m=n.liquidityVenues?.includeDefaults===!1?n.liquidityVenues.venues??[]:[...Xo,...n.liquidityVenues?.venues??[]],f=x=>m.some(w=>w.chainId===x),h=i&&e.chainId!==s.chainId,y=h?ea(e,s.chainId):null;if(h&&!y)return a("No supported source route");if(y&&!d.addressesEqual(R.normalizeNativeTokenAddress(e.address),R.normalizeNativeTokenAddress(y.source.address))&&!f(e.chainId))return a("No conversion venue configured on the source chain");const g=y?.destination.address??Nn(e,s.chainId);return t==="withdraw-destination"?(e.chainTokens||e.receiptTokenId?Vs(e,s.chainId):g?[g]:[]).some(x=>d.addressesEqual(R.normalizeNativeTokenAddress(x),R.normalizeNativeTokenAddress(s.address)))?{eligible:!0,reason:null}:a("No supported withdrawal mapping"):g&&d.addressesEqual(R.normalizeNativeTokenAddress(g),R.normalizeNativeTokenAddress(s.address))?{eligible:!0,reason:null}:!g&&!Au(e,s.chainId)?a("No supported destination route"):f(s.chainId)?{eligible:!0,reason:null}:a("No conversion venue configured on the destination chain")}function so(){const e=p.useContext(d.SpiceFlowProviderContext),[t]=p.useState(d.createInventoryStore);return e?.inventory??t}function ta(e,t,n,s,r){const o=so(),a=r??o,i=p.useMemo(()=>a.entry(e),[a,e]),[,l]=p.useState(0);p.useEffect(()=>{if(n)return i.subscribe(()=>l(m=>m+1),t,s)},[i,n,t,s]);const u=p.useCallback(()=>i.refresh(),[i]);return{...n?i.snapshot():d.EMPTY_INVENTORY,refresh:u}}var ic="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAA6lBMVEXc3NzX/v/1hRvZ2dnd3dzb29va7fpMaXHa1tPc3N35/v/c3Nzc3NzCrp/c3Nza2tp1PRbLsJzlr33uhSj0kTHcnWnUva7jdhuNX0B6Qhrsk0LOxMCFVDJ+RyGhfGTkeiGYVSHjdx3lij7khDPEsaPfoW/jgjLQuKXmgzB2PRb2hRvldhvjdRv4hhvpeRtwORb/ihryghvabhnsehrUaRjLXxXtfRt7PxXwexricRbRYhURFBeSTBe0XBrEZxmDRxiiVRrlgCbfzMAvLCmrWBgbMEh9UjBbOBe2pJi9byekk4nkgDHkgDJLNB7jlKArAAAAKXRSTlMzJv0TNSYsADUxKBwK/QUZ/URTx650/vqJ5YpMosxj3ezwkqa6/q3KrihQ98kAAAAJcEhZcwAACxMAAAsTAQCanBgAAATxSURBVHjapVeJcuI4EJXBdiRuw4JzDAFyzeIT22BsNgTIJNnM7Pz/90xLsmV5ChJm6SqqZOR+7teXWujsgLSqdU0jBCFCNK1ebR16D+39t1HXiKqqGDHBsCRavXEsQKutIVWln0aZ0BX8o7VbRwC06gS+LHQLIWAJqbc+A6iC+h7t3BCVVD8EaGgqOqSemaFqjcMA8PkP1RnEb0bIAPXD1peNqO8H0NQj1LkR2j6Ao/XLCOh/6JcQkOD/B/oUoV4GqGb6+HNdnCFUZYBG9nmsE/whBsZE5y9g0pAAcgcQQ1V0fAgDNnRFNQiW3cAA2lwfI3wxvunqyl4z4OOK3r0ZX2CUIbRzgFZOoHY9nW7NXt9QdFTGgCddMfq9cDudXteyLdLKAPII4NqXZcffzIPJQx8zDCFgev9hksw3fmf5pYalSCDJAGAw7Uz9zkuU2CNKRQiYPrIT76Xjwws5B/BjiwG0hQHAgIr/GHpeYvb+EtIzI88LH32+fy1MaDMAKOGCAUdYPnmmE82ERI7pPS25fsEB0UCgs4ZwVO08AwB5sT0zrmQSm7b94mff7yzPa8LBDQAQSSwo5DRsKxO7MF+mwNyIBAPwjHEhIQCNgOsHwnwmF4aeWwAcUEMO97DgABAvkUv13WgrqXeWQ7moGqiqFtkivJjTCADBDWTzZR9SE6pIquOSF6msGYdgPS0BSD4EJ6CikUB+DKcd2QkRB4hkF3SmQyyqHioKaViicF4AQEp7DqfgRJDCSwFxLlPQ5GMAAHJ9n4bRyQEcGkZ/HwColwBYHH3fXz6uHc+xnZgCxLDwnPXj0mcgUhRpOZSblTEE9c32ybMi27ELAHiILO9puwGIoXG48YEJ43UYzGYumG/LADbQcGezIFyPjRr+7aCREfTezLUqFtMB4QB87cSw4c56uqyPSz4A/S6UDuikqzkTmwLYfL1K4aFiVbolBCKHEWHlclahyRvMF4vFarWgOm5KV4vFnIbEqswuFUmD5oF0olAGFZ7+88VqvV05FMBZbderxZwXRqXEgSaSfCTp3cDiAIETvr2+riP64K1fX99ClhMA4AIH+YAqFVPGgGnFu+9v44Quk/Hb913suXyjzAGKSS7nnAEtgBg6WeAxLIjrLM56A+NQKueioVAGruW67OdWrCCwYqoS01XgZmLJHGhDkVqa3oXeSyUESaktvBrBJ5WU/sd3IxFI3tKKpkrwCDIQcjCkUfPAnIAJ+NSjcQ1tuuuNMCk11TORCVh5SEyWdXP2dmzxpk4TEzDnbMtM/lakligfLADQj3gOOysASNPd5l+QzS5NAWCVbUV9RTBol442cIIxsVnlwPthurtv/sOkeb9LQ2oS25qIcs6PNtmNvch0HBOKN/15P3h+5wDvz4P7/1IocNhzop7swvLxTjMpMm0viSa9m6/Pg+cf35j8gOXXm94kSjzbjIo8Esd7cbxCIBNzdNs3dAXdDQbN9ybIe3MwuEOKbvRvR2YigigNGNKMh28vu0ihswGp9ZuDJpNBs0+HFjjuUffyFpcnvfKQhbgym06wcnXHAe6umNWYjSlKkcXlMa8YpIrEIldMCMHyrLNvzDs0aBImxwyap4+6pw/bp4/71A/opAvH6Vee0y9dn1z70OfXvuziudcMSKdjLp786quecPWVL99Zfqt/ePkuX/8Jv/43Dl3/fwH9bPJ09nq7MQAAAABJRU5ErkJggg==",Eu="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAQlBMVEVMaXGGl/+Elf+HmP+Hmf+Hl/+Gl/+Flv+Glv+Gl/+Gl/+Gl/////+On/+Akv/4+f/v8f/i5v+9x//S2P+tuP+erP+W3PvUAAAAC3RSTlMArBlx7Isy/vvOXbb4wDYAAAAJcEhZcwAACxMAAAsTAQCanBgAAALuSURBVHjarVfbtqsgDOxu0UBpkOv//+pJRC0i2HZ58uTeqzOEyYXkduvY/Tn8KSEBpFB/w3O8/WTjoCSS6dn4S6rha477QxFGS0nHM56ckJL/ox73b+CDQAQJujKiQxTDR4qH4LN109gP8Ti/uyI46K4BUagTLZ4Cz+CZAsWzhx/oeP3RyImhjf/7ePzmxF8Hr7+zNsP3eL7GkWH4Bc8MlQ7P3/DMsIvFKHRLPzBsTWVBizIfVNMBg9H7mLQxTRdUkb9tfJxebNZjywuJW1bf2xcw4WXtzDF5bVqXuJ9HwETHNnPYeHRii0THgcwQyBxTBDQ9Fx7dEBr0TOCDYyeS6aigsFsCQIFgBh9YiVgxQA7EqM9KiCiS95nh5WsGPZ4k8ZZFRqfoY4shy9i8AaExxRgTMgcApuSODPMdRtn02wc7Z9HkPMsPa1ZVOsiRygga4udfZ5vTKKx/7GIBVFJHCUy0r705DNu3LQ9kEQ6NxMTXwWzhUTD7xlJr2MLvrZCBVazy2OD0iaC4BGh1k4cSLOSbbIuujKW4wT76aYefrGswuBJSEoBeUnaFk7nQcKEIJZRXMPsfM95O3p3KKAoRa/cJTh0pHKMybSqyiO8wMsG0wzODi7UK9u0Ah7FIJAj1+UyQcl4Gqi2uax+L/siJVKQyi+j251sbMoHTZrUqlctiojDGRX27WpivYNtdi4upKme0c/gXBmdzY7ZoOi/cWDeU7MJy+oKn3hzbT9/cFKt6pmKe9udnCoTeG103VW7EjrGZJMOD863GNzfVQ0EDP6aJUH61wBRHGZa23npYDDpuh8EnpPBRS6UUQOg9r8enzaDdmhmsPkH/da3bokkr/i0dwMmYU7lg0pRrwiVzNrW+n/dKhVzVVIbGnE9Jj86IA8glk87h+xGnGrJyzXwYNvdD1uUx7/qgeX3UvT5sXx/3ry8c11ee60vX9bXvvXjWfsC3i+d79YV19+WPH1bf/7B8Lxy8/isBINTp+v8Ph4CTcAywkiYAAAAASUVORK5CYII=",Fu="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAPFBMVEVMaXGZhueZh+eYhuWXheWYh+eYhuaXheCYhuaah+j//fmhjvOSf+Sdi+q8sOzNxO/m4fT08fapmuja0/Jb/wGxAAAACnRSTlMArEz/IYtsA87sGIEBYwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAmJJREFUeNqtV4uSgyAMRIECGhTk///1otTKG3s2Mzdz03aXbEJIQkhuYv9jIx+komhKDnxk4v1F1wT+SoxcUj3PWu8Ex39U8lH4bzt4QthL6tlDA8OP5Iv1vMADGFc5+uRQnDWdEES81EwbNquXqDuBx8va6ZcXktUYBOkc/3GixsBvwA8neFGGGO7hdyeGAsMXeM/wBJ8ziLv6LwYeisD4f4lHhiAXmH9FvzYV3AchOw6At9gFKW4KANDbsttGoSyCKd1Ab4uxkzezhBQaRfQygHB3oj2FhjwT9QgifErM6jiOrQgAXe2UmcuiIKSuHG+mki2XCH0kYqzgF1vETyYszLFaxLBMNdsgDGNFAazRoUcwrDMlDYz28RS0newGcCRlDa8TK4YgxuORGj9x8NYVEsxjKQSp/pNAw5YRcJI/JP5nYeqxjAxeIfCeRQQDyWOos/y5xR2V4NIgYhRJVkjgpralBPcvQH4PsBxIX0DjJqKRdgYLtsYPUyqh60CsACXEQew7ECvAICZp7DqwQEIQXaR+CkzaoeKr3FewQdqg4mIy36VgLyZWz4G96N5vs8sKj0UPSlJGy4fAbWX88SgGQYgJVjDXi7JaaxYo9Oj4UQ0lrHCGdN25ceiEfNoZSfIomjhcKN26DarT0q4gaiyfe2C9u9hWNUBvRghbG+yd1AZNFFrjmu+ucXMF2j60OObE7f0m+mrv/5qQkimpO+IU8fKXQ9bDMe/5oPl81P3BsP183EeGu3GoLBw/WHnuLF20sXQ9X/ueL57PV99w+Z7P5Vvj8j3fXr7j9X/f/5Vsrv9/K3NM7mGXOq0AAAAASUVORK5CYII=",yr="data:image/svg+xml,%3csvg width='8' height='11' viewBox='57 6 8 11' fill='none' xmlns='http://www.w3.org/2000/svg'%3e %3cpath d='M62.7081 13.27C62.742 13.27 62.7642 13.3057 62.7491 13.3362V13.336L61.1229 16.6083C61.0892 16.6761 60.9926 16.6759 60.959 16.6083L59.3382 13.336C59.3232 13.3057 59.3453 13.27 59.3792 13.27H62.7081Z' fill='%23EA4B4B'/%3e %3cpath d='M61.0026 9.71913C61.0194 9.68524 61.0678 9.68524 61.0845 9.71913L62.747 13.0897C62.762 13.12 62.7399 13.1557 62.706 13.1557H59.3763C59.3424 13.1557 59.3203 13.12 59.3353 13.0897L61.0026 9.71913Z' fill='%23EA4B4B'/%3e %3cpath d='M60.8426 9.63827C60.8766 9.63827 60.8987 9.6741 60.8835 9.70444L59.2164 13.0594C59.1995 13.0932 59.1513 13.0932 59.1345 13.0594L57.5001 9.77047C57.47 9.70962 57.5142 9.63827 57.5821 9.63827H60.8426Z' fill='%23EA4B4B'/%3e %3cpath d='M64.5036 9.63617C64.5715 9.63618 64.6157 9.70753 64.5855 9.76838H64.5854L62.9512 13.0573C62.9344 13.0911 62.8862 13.0912 62.8692 13.0573L61.2021 9.70235C61.187 9.672 61.2091 9.63617 61.2431 9.63617H64.5036Z' fill='%23EA4B4B'/%3e %3cpath d='M62.8284 6.18281C62.862 6.11518 62.9586 6.11518 62.9922 6.18281L64.5855 9.38969C64.6157 9.45054 64.5715 9.52189 64.5036 9.52189H61.2431C61.2091 9.52189 61.187 9.48605 61.2021 9.45571L62.8283 6.18265L62.8284 6.18281Z' fill='%23EA4B4B'/%3e %3cpath d='M62.3131 6.13196C62.381 6.13196 62.4252 6.20331 62.3951 6.26416C62.154 6.74935 61.9128 7.23455 61.6718 7.71975H61.6716C61.4225 8.22125 61.1733 8.72259 60.9242 9.22409C60.9074 9.25799 60.859 9.25799 60.8422 9.22409L60.6305 8.79587C60.6275 8.78957 60.6259 8.78263 60.6259 8.77553V6.22349C60.6259 6.17297 60.6668 6.13196 60.7173 6.13196H62.3131Z' fill='%23EA4B4B'/%3e%3c/svg%3e";const br=R.getChainMeta(1)?.logo??"",Tu=R.TOKENS.find(e=>e.symbol==="USDC")?.logo??"",xs=Object.fromEntries([...R.getMainnetChains(),...R.getTestnetChains()].map(e=>[e.id,e.logo])),vr={metamask:ic,metaMask:ic,rabby:Eu,phantom:Fu},na=Object.fromEntries(R.TOKENS.map(e=>[e.symbol.toUpperCase(),e.logo])),Ru={usdc:[8453,1,42161,5115,4114],usdt:[1],btc:[4114,42161,1,5115],wbtc:[1],weth:[8453,1],eth:[8453,1,42161,4663,84532,46630],ctusd:[5115,4114],wcbtc:[5115,4114]},Bu={btc:["wcbtc","cbtc","wbtc"]};function ro(e){return e.replace(/^test\s*/i,"").replace(/^spice/i,"").trim()}function rs(e){return ro(e).toLowerCase()}function cc(e){return rs(e??"").replace(/[^a-z0-9]/g,"")}function sa(e){const t=rs(e);return[t,...Bu[t]??[]].filter(Boolean)}function Ou(e){try{return BigInt(e.balanceAvailable||"0")}catch{return 0n}}function lc(e){return Array.isArray(e.chainTokens)?e.chainTokens:Object.keys(e.chainTokens??{})}function dc(e,t){const n=d.getChainConfig(e),s=t.toLowerCase();return s===R.ZERO_ADDRESS.toLowerCase()?n?.nativeCurrency.decimals??18:n?.supportedTokens?.find(r=>r.address.toLowerCase()===s)?.decimals??18}function ju(e,t,n,s=[]){const r=dc(t,n),o=e.filter(i=>uc(i,t,n,s));if(o.length===0)return null;const a=o.reduce((i,l)=>Math.min(i,l.decimals??r),r);return{chainDecimals:r,receiptDecimals:a}}function uc(e,t,n,s){if(lc(e).some(o=>{const a=kn(o);return a&&xr(a.address,a.chainId,n,t)}))return!0;const r=new Set(s.map(cc).filter(Boolean));return r.size===0?!1:r.has(cc(e.tokenName||e.receiptToken))}function pc(e,t,n,s=[]){const r=dc(t,n);return e.reduce((o,a)=>uc(a,t,n,s)?o+R.convertAmountBetweenDecimals(Ou(a),a.decimals??r,r):o,0n)}function fc(e,t){const n=new Set([...sa(t),...sa(ro(t))]);return[...e].sort((s,r)=>{const o=rs(s.symbol),a=rs(r.symbol),i=rs(s.name),l=rs(r.name),u=n.has(o)?0:n.has(i)?1:2,m=n.has(a)?0:n.has(l)?1:2;return u!==m?u-m:s.address.toLowerCase().localeCompare(r.address.toLowerCase())})[0]}function Du(e){const t=e&&e.length>0?e:Object.keys(d.CHAIN_CONFIGS).map(Number).filter(Number.isFinite),n=new Map;for(const s of t){const r=d.getChainConfig(s);if(!r)continue;const o=`${s}:${R.ZERO_ADDRESS.toLowerCase()}`;n.has(o)||n.set(o,{address:R.ZERO_ADDRESS,chainId:s,symbol:r.nativeCurrency.symbol,name:r.nativeCurrency.name,decimals:r.nativeCurrency.decimals,isNative:!0,logoURI:na[r.nativeCurrency.symbol.toUpperCase()]??r.logo});for(const a of r.supportedTokens??[]){const i=a.address.toLowerCase(),l=`${s}:${i}`;n.has(l)||n.set(l,{address:i,chainId:s,symbol:a.symbol,name:a.name,decimals:a.decimals,isNative:R.isNativeToken(i),logoURI:a.logo})}}return n}function Nu(e,t){const n=Du(t),s=ro(e.tokenName),r=rs(e.tokenName),o=sa(e.tokenName),a=Array.isArray(e.chainTokens)?e.chainTokens.map(g=>[g,void 0]):Object.entries(e.chainTokens??{}),i=a.map(([g])=>kn(g)).filter(g=>g!==null),l=new Map;for(const[g,x]of a){const w=kn(g);if(!w||!Number.isSafeInteger(w.chainId)||w.chainId<0||!/^evm:[0-9]+:(?:0x)?[0-9a-fA-F]{40}$/.test(g)){if(!Array.isArray(e.chainTokens))throw new Error("Invalid chain token metadata identity");continue}if(x!==void 0&&(!x||typeof x!="object"||Array.isArray(x)||x.name!==void 0&&typeof x.name!="string"||x.decimals!==void 0&&(!Number.isInteger(x.decimals)||x.decimals<0||x.decimals>255)))throw new Error("Invalid chain token metadata");const b=`${w.chainId}:${w.address.toLowerCase()}`;if(l.has(b)){const k=l.get(b);if(k?.name!==x?.name||k?.decimals!==x?.decimals)throw new Error("Conflicting chain token metadata")}l.set(b,x)}const u=(g,x)=>{const w=l.get(`${x.chainId}:${x.address.toLowerCase()}`);return{...g,name:typeof w?.name=="string"&&w.name.length>0?w.name:g.name,decimals:typeof w?.decimals=="number"?w.decimals:g.decimals}},m=i.map(g=>{const x=n.get(`${g.chainId}:${g.address.toLowerCase()}`);return x?u(x,g):void 0}).filter(g=>g!==void 0),f=Ru[r]??[];if(f.length>0)for(const g of f){const x=m.filter(w=>w.chainId===g);if(x.length>0)return fc(x,e.tokenName)}if(m.length>0)return fc(m,e.tokenName);const h=Array.from(n.values()).filter(g=>o.includes(rs(g.symbol))||o.includes(rs(g.name)));if(f.length>0)for(const g of f){const x=h.find(w=>w.chainId===g);if(x)return x}if(h.length>0)return h[0];const y=i[0];if(y){const g=l.get(`${y.chainId}:${y.address.toLowerCase()}`);return{address:y.address,chainId:y.chainId,symbol:s||e.tokenName,name:typeof g?.name=="string"&&g.name.length>0?g.name:s||e.tokenName,decimals:typeof g?.decimals=="number"?g.decimals:e.decimals??18,isNative:R.isNativeToken(y.address),logoURI:void 0}}}function Mu(e,t){let n;try{n=BigInt(e.balanceAvailable||"0")}catch{return null}if(n<=0n)return null;if(t?.length){const g=lc(e).map(kn).filter(x=>x!==null);if(g.length>0&&!g.some(x=>t.includes(x.chainId)))return null}let s;try{s=Nu(e,t)}catch{return null}const r=s?.decimals??e.decimals??18,o=e.decimals??r,a=R.convertAmountBetweenDecimals(n,o,r),i=s?.address??R.ZERO_ADDRESS,l=s?.chainId??0,u=ro(e.tokenName),m=s?.symbol??u,f=s?.name??u,h=parseFloat(N.formatUnits(a,r)),y=typeof e.balanceUsd=="number"?e.balanceUsd:typeof e.balanceUsd=="string"&&Number(e.balanceUsd)||0;return{address:i,symbol:m,name:f,decimals:r,chainId:l,balance:a,balanceFormatted:h,balanceUsd:y,isNative:s?.isNative??R.isNativeToken(i),logoURI:s?.logoURI,displaySymbol:u||m,displayName:u||f,displayChainName:"Spicenet",receiptTokenId:e.receiptToken,receiptTokenName:e.tokenName||f,receiptTokenDecimals:o,chainTokens:e.chainTokens&&!Array.isArray(e.chainTokens)?e.chainTokens:void 0,isUniversal:!0}}const ra=6e4,Pu=3e5,mc="https://api.g.alchemy.com/prices/v1",Gs=new Map;function oo(e,t){try{const n=t??d.getClientForChain(e).transport.url;if(typeof n!="string")return null;const{hostname:s,pathname:r}=new URL(n);if(!s.endsWith(".g.alchemy.com"))return null;const o=r.split("/").filter(Boolean).pop();return o?{network:s.slice(0,-14),key:o}:null}catch{return null}}const Cr=(e,t)=>`${e.network}:${e.key}:${t.toLowerCase()}`;function Rs(e,t){const n=Gs.get(Cr(e,t));if(!n?.price||n.updatedAt===void 0)return;const s=Date.now()-n.updatedAt;if(!(s>=Pu))return{price:n.price,stale:s>=ra}}function hc(e){const t=Number(e.prices?.find(n=>n.currency==="usd")?.value);return Number.isFinite(t)&&t>0?t:0}async function gc(e,t,n){const s=[],r=new Set,o=Date.now();for(const a of new Set(t.map(i=>i.toLowerCase()))){const i=Gs.get(Cr(e,a));i?.pending?r.add(i.pending):(!i||o-i.attemptedAt>=ra&&(i.updatedAt===void 0||o-i.updatedAt>=ra))&&s.push(a)}for(let a=0;a<s.length;a+=25){const i=s.slice(a,a+25),l=Promise.resolve().then(async()=>{try{const u=await n(i);for(const m of i){const f=u.get(m);if(!f)continue;const h=Gs.get(Cr(e,m));h.price=f,h.updatedAt=Date.now()}}catch{}finally{for(const u of i)Gs.get(Cr(e,u)).pending=void 0}});for(const u of i){const m=Cr(e,u);Gs.set(m,{...Gs.get(m),attemptedAt:o,pending:l})}r.add(l)}await Promise.all(r)}async function oa(e,t){return await gc(e,t,async n=>{const s=await fetch(`${mc}/${e.key}/tokens/by-address`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({addresses:n.map(a=>({network:e.network,address:a}))}),signal:AbortSignal.timeout(1e4)});if(!s.ok)throw new Error("Provider price request failed");const r=await s.json(),o=new Map;for(const a of r?.data??[]){if(a.network&&a.network!==e.network)continue;const i=String(a.address).toLowerCase();n.includes(i)&&o.set(i,hc(a))}return o}),new Map(t.map(n=>[n.toLowerCase(),Rs(e,n)?.price??0]))}async function aa(e,t){const n=`native:${t}`;return await gc(e,[n],async()=>{const s=await fetch(`${mc}/${e.key}/tokens/by-symbol?symbols=${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(1e4)});if(!s.ok)throw new Error("Provider native price request failed");const r=(await s.json())?.data?.find(o=>o.symbol?.toUpperCase()===t.toUpperCase());return new Map([[n.toLowerCase(),r?hc(r):0]])}),Rs(e,n)?.price??0}async function Uu(e,t){const n=t.supportedChains,s=e.map(r=>{const o=Object.keys(r.chainTokens??{}).map(kn).filter(a=>!!a&&N.isAddress(a.address)&&!!n?.includes(a.chainId));return o.sort((a,i)=>{const l=u=>u===t.nativeChainId?-1:n.indexOf(u);return l(a.chainId)-l(i.chainId)||+!d.addressesEqual(a.address,r.address)-+!d.addressesEqual(i.address,r.address)}),o.flatMap(a=>{const i=t.rpcOverrides?.[a.chainId];if(!i)return[];const l=oo(a.chainId,i);if(!l)return[];const u=R.isNativeToken(a.address)?d.getChainConfig(a.chainId)?.nativeCurrency.symbol:void 0,m=u?`native:${u}`:a.address;return[{rpc:l,token:m,address:a.address,nativeSymbol:u}]})});return(typeof document>"u"||!document.hidden)&&await Promise.all(s.map(async r=>{for(const o of r)if(o.nativeSymbol?await aa(o.rpc,o.nativeSymbol).catch(()=>0):await oa(o.rpc,[o.address]).catch(()=>new Map),Rs(o.rpc,o.token)?.stale===!1)break})),e.map((r,o)=>{const a=s[o].map(l=>Rs(l.rpc,l.token)),i=a.find(l=>l&&!l.stale)??a.find(Boolean);return{...r,balanceUsd:i?r.balanceFormatted*i.price:Number.isFinite(r.balanceUsd)&&r.balanceUsd>0?r.balanceUsd:0,priceStatus:i?i.stale?"stale":"fresh":"unavailable"}})}function Wu(e,t,n){const s=p.useContext(d.SpiceFlowProviderContext),[r,o]=p.useState(()=>typeof document>"u"||!document.hidden);p.useEffect(()=>{const m=()=>o(!document.hidden);return document.addEventListener("visibilitychange",m),()=>document.removeEventListener("visibilitychange",m)},[]);const a={supportedChains:n??s?.supportedChainIds,nativeChainId:s?.nativeChainId,rpcOverrides:s?.rpcOverrides},i=JSON.stringify([e,a],(m,f)=>typeof f=="bigint"?f.toString():f),l=p.useCallback(()=>Uu(e,a),[i]),u=ta(`prices:${i}`,l,t&&r&&e.length>0,6e4);return u.updatedAt?u.assets:e}function qu(e){const t=e.chainTokens??e.chainTokenConfig;if(Array.isArray(t))return t.filter(n=>typeof n=="string");if(t&&typeof t=="object")return t}const wc=({address:e,supportedChains:t,enabled:n=!0,refetchInterval:s,priceEnabled:r=!1})=>{const o=p.useContext(d.SpiceFlowProviderContext),a=o?.apiUrl||d.RELAYER_API_URL,i=so(),l=o?.supportedChainIds??t,u=JSON.stringify([...l??[]].sort((D,S)=>D-S)),m=e?.toLowerCase(),f=p.useCallback(async()=>{const D=`${a}/wallets/${m}/balance`;let S,v;try{const F=await d.relayerFetch(D,{cache:"no-store"});if(S=F.status,v=F.requestId,!F.ok)throw new Error(`Failed to fetch balance: ${F.status}`);const O=await F.json();if(!Array.isArray(O.balances))throw new Error("Invalid balance response");return O.balances.map(j=>{const q=Mu({receiptToken:typeof j.receiptToken=="string"?j.receiptToken:void 0,tokenName:String(j.tokenName??""),balanceAvailable:String(j.balanceAvailable??"0"),chainTokens:qu(j),decimals:typeof j.decimals=="number"?j.decimals:void 0,balanceUsd:typeof j.balanceUsd=="number"||typeof j.balanceUsd=="string"?j.balanceUsd:null},l);return q?{...q,owner:m,location:"rollup",_source:"spice",positionId:`${m}:rollup:${q.receiptTokenId??q.address}`}:null}).filter(j=>j!==null)}catch(F){const O=F instanceof Error?F.name:void 0,j=S===429?"Balance refresh is temporarily busy. Wait a moment and try again.":S===408||S===504||O==="TimeoutError"?"Balance refresh timed out. Try again.":O==="AbortError"?"Balance refresh was interrupted. Try again.":"Balances are unavailable. Check your connection and try again.",q=new d.SpiceflowError("RELAYER_STATUS_ERROR",j,{endpoint:D,httpStatus:S,requestId:v,cause:F});throw d.sanitizeError(q),q}},[m,a,u,o?.nativeChainId,o?.rpcOverrides]),{assets:h,loading:y,refreshing:g,error:x,updatedAt:w}=ta(`rollup:${m}:${a}:${u}`,f,n&&!!m,s??0,i),b=JSON.stringify(t??[]),k=p.useMemo(()=>x?h.map(D=>({...D,balanceError:x,balanceStatus:"stale"})):h,[h,x]),A=Wu(k,n&&r,l),C=p.useMemo(()=>A.filter(D=>!t?.length||t.includes(D.chainId)||Object.keys(D.chainTokens??{}).some(S=>t.some(v=>S.startsWith(`evm:${v}:`)))),[A,b]),E=p.useCallback(D=>C.filter(S=>S.chainId===D),[C]);return{assets:C,loading:y,error:x,hasBalance:C.some(D=>D.balance>0n),refreshing:g,updatedAt:w,refetch:i.invalidate,getAssetsByChain:E}};async function Lu(e,t,n){if(n)return{decimals:n.decimals,symbol:n.symbol,name:n.name,logoURI:n.logo};const[s,r,o]=await Promise.all([Vn.readContract(e,{address:t,abi:N.erc20Abi,functionName:"decimals"}),Vn.readContract(e,{address:t,abi:N.erc20Abi,functionName:"symbol"}).catch(()=>"TOKEN"),Vn.readContract(e,{address:t,abi:N.erc20Abi,functionName:"name"}).catch(()=>"TOKEN")]);if(!Number.isInteger(Number(s))||Number(s)<0||Number(s)>255)throw new Error("Invalid token decimals");return{decimals:Number(s),symbol:r,name:o,logoURI:void 0}}const xc=async(e,t,n)=>{const s=d.getClientForChain(t,n),r=d.getChainConfig(t),o=await Vn.getBalance(s,{address:e}),a=r.nativeCurrency,i=r.supportedTokens?.find(l=>R.isNativeToken(l.address));return{address:R.ZERO_ADDRESS,name:a.name,symbol:a.symbol,decimals:a.decimals,balance:o,balanceFormatted:Number(N.formatUnits(o,a.decimals)),balanceUsd:0,priceStatus:"unavailable",logoURI:i?.logo||r.logo,isNative:!0,chainId:t}},zu=async(e,t,n,s,r,o,a)=>{try{if(!N.isAddress(n))return null;const i=N.getAddress(n),l=N.isAddress(e)?N.getAddress(e):e,u=d.getClientForChain(t,a),m=await Vn.readContract(u,{address:i,abi:N.erc20Abi,functionName:"balanceOf",args:[l]}),f=Number(N.formatUnits(m,o));return m>0n?{address:i,name:s,symbol:r,decimals:o,balance:m,balanceFormatted:f,balanceUsd:0,priceStatus:"unavailable",logoURI:void 0,isNative:!1,chainId:t}:null}catch(i){throw i}},yc=(e,t)=>{const n=d.getChainConfig(t);if(!n)return e;const s=new Set(e.map(o=>o.address.toLowerCase())),r=e.some(o=>o.isNative);for(const o of n.supportedTokens||[])R.isNativeToken(o.address)&&r||s.has(o.address.toLowerCase())||e.push({address:o.address,name:o.name,symbol:o.symbol,decimals:o.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,priceStatus:"unavailable",logoURI:o.logo,isNative:R.isNativeToken(o.address),chainId:t});if(!e.find(o=>o.isNative)){const o=n.supportedTokens?.find(a=>R.isNativeToken(a.address));e.push({address:R.ZERO_ADDRESS,name:n.nativeCurrency.name,symbol:n.nativeCurrency.symbol,decimals:n.nativeCurrency.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,priceStatus:"unavailable",logoURI:o?.logo||n.logo,isNative:!0,chainId:t})}return e},Hu=async(e,t,n)=>{const s=[],r=async i=>{for(const l of i){const u=await zu(e,t,l.address,l.name,l.symbol,l.decimals,n);u&&(u.logoURI=l.logo,s.push(u))}},o=await xc(e,t,n);o.balance>0n&&s.push(o);const a=(d.getChainConfig(t)?.supportedTokens||[]).filter(i=>!R.isNativeToken(i.address));if(a.length>0)try{const i=d.getClientForChain(t,n),l=N.getAddress(e),u=a.filter(y=>N.isAddress(y.address)).map(y=>({address:N.getAddress(y.address),abi:N.erc20Abi,functionName:"balanceOf",args:[l]})),m=await i.multicall({contracts:u}),f=a.filter(y=>N.isAddress(y.address)),h=[];m.forEach((y,g)=>{if(y.status==="success"){const x=y.result;if(x&&x>0n){const w=f[g],b=Number(N.formatUnits(x,w.decimals));x>0n&&s.push({address:N.getAddress(w.address),name:w.name,symbol:w.symbol,decimals:w.decimals,balance:x,balanceFormatted:b,balanceUsd:0,priceStatus:"unavailable",logoURI:w.logo,isNative:!1,chainId:t})}}else h.push(f[g])}),await r(h)}catch{await r(a)}return{tokens:yc(s,t),chainId:t}},Vu=async(e,t,n)=>{const s=new Map,r=oo(e,n?n[e]??"":void 0);if(!r)return s;const o=t.filter(u=>R.isNativeToken(u)),a=t.filter(u=>!R.isNativeToken(u)),[i,l]=await Promise.all([a.length?oa(r,a).catch(()=>new Map):new Map,o.length?aa(r,d.getChainConfig(e)?.nativeCurrency?.symbol??"ETH").catch(()=>0):0]);for(const[u,m]of i)m>0&&s.set(u,m);if(l>0)for(const u of o)s.set(u.toLowerCase(),l);return s},Qu=async(e,t,n,s=!0,r)=>{const o=d.getClientForChain(t,r),a=N.getAddress(e),i=[];let l;do{const x=await o.request({method:"alchemy_getTokenBalances",params:[a,"erc20",l?{pageKey:l}:{}]});i.push(...x.tokenBalances),l=x.pageKey||void 0}while(l);const u=i.filter(x=>N.isAddress(x.contractAddress)&&!!x.tokenBalance&&BigInt(x.tokenBalance)>0n),m=d.getChainConfig(t)?.supportedTokens||[],f=x=>m.find(w=>w.address.toLowerCase()===x.toLowerCase()),h=[],y=await xc(e,t,r),[g]=await Promise.all([Promise.all(u.map(async x=>{const w=f(x.contractAddress);return w?{name:w.name,symbol:w.symbol,decimals:w.decimals,logo:w.logo??null}:await o.request({method:"alchemy_getTokenMetadata",params:[x.contractAddress]})})),s?oa(n,u.map(x=>x.contractAddress)):void 0,s&&y.balanceFormatted>0?aa(n,y.symbol):void 0]);if(y.balance>0n){const x=Rs(n,`native:${y.symbol}`);h.push({...y,balanceUsd:(x?.price??0)*y.balanceFormatted,priceStatus:x?x.stale?"stale":"fresh":"unavailable"})}return u.forEach((x,w)=>{const b=g[w];if(!Number.isInteger(b.decimals)||b.decimals===null||b.decimals<0||b.decimals>255)throw new Error(`Invalid token metadata on chain ${t}`);const k=BigInt(x.tokenBalance),A=Number(N.formatUnits(k,b.decimals));if(k<=0n)return;const C=Rs(n,x.contractAddress),E=(C?.price??0)*A;h.push({address:N.getAddress(x.contractAddress),name:b.name||"Unknown",symbol:b.symbol||"UNKNOWN",decimals:b.decimals,balance:k,balanceFormatted:A,balanceUsd:E,priceStatus:C?C.stale?"stale":"fresh":"unavailable",isDiscovered:!f(x.contractAddress),logoURI:b.logo||void 0,isNative:!1,chainId:t})}),{tokens:yc(h,t),chainId:t}},bc=new Set,Gu=async(e,t,n=!0,s)=>{try{const r=oo(t,s?s[t]??"":void 0);if(r)try{return await Qu(e,t,r,n&&(typeof document>"u"||!document.hidden),s)}catch(o){bc.has(t)||(bc.add(t),console.warn(`Token discovery unavailable on chain ${t}; listing configured tokens only.`,o))}return await Hu(e,t,s)}catch(r){throw r}},Ks=async(e,t,n=[],s)=>{if(!e)throw new Error("Wallet address is required");const r=d.getChainsForAssets(s),o=t?.length?[...new Set(t)]:Object.keys(r).map(Number),a=await Promise.allSettled(o.map(l=>Gu(e,l,!0,s))),i={};return a.forEach((l,u)=>{const m=o[u];i[m]=l.status==="fulfilled"?l.value:{chainId:m,tokens:[],error:`Unable to refresh balances on chain ${m}`}}),(await Promise.allSettled(n.map(async l=>{const u=i[l.chainId];if(!u||u.error||u.tokens.some(w=>R.normalizeNativeTokenAddress(w.address).toLowerCase()===R.normalizeNativeTokenAddress(l.address).toLowerCase()))return;const m=d.getClientForChain(l.chainId,s),f=await Lu(m,l.address,l.decimals!==void 0&&l.symbol?{decimals:l.decimals,symbol:l.symbol,name:l.name||l.symbol,logo:l.logoURI}:void 0),h=await Vn.readContract(m,{address:l.address,abi:N.erc20Abi,functionName:"balanceOf",args:[e]});await Vu(l.chainId,[l.address],s);const y=Number(N.formatUnits(h,f.decimals)),g=oo(l.chainId,s?s[l.chainId]??"":void 0),x=g?Rs(g,l.address):void 0;u.tokens.push({...f,...l,name:f.name,symbol:f.symbol,decimals:f.decimals,balance:h,balanceFormatted:y,balanceUsd:(x?.price??0)*y,priceStatus:x?x.stale?"stale":"fresh":"unavailable",isNative:!1})}))).forEach((l,u)=>{if(l.status==="rejected"){const m=i[n[u].chainId];m&&(m.error=`Unable to refresh token balances on chain ${m.chainId}`)}}),i},kr=({address:e,supportedChains:t,fetchBalances:n=Ks,additionalTokens:s=[],enabled:r=!0,refreshInterval:o=0,priceEnabled:a=!0})=>{const i=p.useContext(d.SpiceFlowProviderContext),l=so(),u=e?.toLowerCase(),m=JSON.stringify([...i?.supportedChainIds??t??[]].sort((k,A)=>k-A)),f=JSON.stringify(s);p.useEffect(()=>l.registerTokens(s),[l,f]);const h=u&&u===i?.embeddedWalletAddress?.toLowerCase()?"embedded":"external",y=`wallet:${JSON.stringify([i?.network,i?.apiUrl,i?.rpcOverrides])}:${u}:${h}:${m}:${l.fetcherId(n)}`,g=p.useCallback(async()=>{let k;try{k=await n(u,JSON.parse(m),l.tokens(),i?.rpcOverrides)}catch(D){const S=D instanceof Error?D.message:"Unable to refresh balances";k=Object.fromEntries(JSON.parse(m).map(v=>[v,{chainId:v,tokens:[],error:S}]))}const A=l.entry(y).snapshot().assets,C=JSON.parse(m).map(D=>k[D]??{chainId:D,tokens:[],error:`Unable to refresh balances on chain ${D}`}),E=C.flatMap(D=>D.error?[D.error]:[]);return{assets:C.flatMap(D=>D.error?A.filter(S=>S.chainId===D.chainId).map(S=>({...S,balanceError:D.error,balanceStatus:"stale"})):D.tokens.map(S=>({...S,owner:u,location:h,_fundingWallet:h,_source:"wallet",positionId:`${u}:${h}:${D.chainId}:${R.normalizeNativeTokenAddress(S.address).toLowerCase()}`}))),error:E.length?E.join("; "):null}},[l,u,m,n,h,y]),x=ta(y,g,r&&!!u,o,l),w=JSON.stringify(t&&[...t].sort((k,A)=>k-A)),b=p.useMemo(()=>t?x.assets.filter(k=>t.includes(k.chainId)):x.assets,[x.assets,w]);return p.useEffect(()=>{a&&r&&u&&x.refresh()},[a]),{...x,assets:b,refreshAssets:l.invalidate,getAssetsByChain:p.useCallback(k=>b.filter(A=>A.chainId===k),[b]),getNativeAssets:p.useCallback(()=>b.filter(k=>k.isNative),[b])}};function Bs(e){const t=p.useContext(d.SpiceFlowProviderContext),n=so(),s=e.owner??((t?.mode||"7702")!=="7702"?t?.externalWalletAddress:t?.embeddedWalletAddress),r=s?.toLowerCase()!==t?.embeddedWalletAddress?.toLowerCase(),o=e.sourceChains??t?.supportedChainIds??[],a=(e.enabled??!0)&&!t?.isWhitelistGateActive,i=p.useMemo(()=>{const h=[...t?.additionalSourceTokens??[],...e.additionalSourceTokens??[],...e.destination?[e.destination]:[]];for(const y of e.supportedSourceAssets??[])for(const g of o){const x=d.getChainConfig(g)?.supportedTokens?.find(w=>d.isAssetAllowed(w,[y]));x&&h.push({...x,address:x.address,chainId:g,logoURI:x.logo})}return h},[e.destination,JSON.stringify(t?.additionalSourceTokens),JSON.stringify(e.additionalSourceTokens),JSON.stringify(e.supportedSourceAssets),JSON.stringify(o)]),l=kr({address:s,supportedChains:o,fetchBalances:Ks,additionalTokens:i,enabled:a&&e.includeWalletAssets!==!1,refreshInterval:3e4}),u=wc({address:s,supportedChains:o,enabled:a&&e.includeRollupAssets!==!1&&!!s&&s.toLowerCase()===t?.embeddedWalletAddress?.toLowerCase(),priceEnabled:a,refetchInterval:3e4}),m=p.useMemo(()=>a?[...(e.includeWalletAssets===!1?[]:l.assets).map(h=>({...h,owner:h.owner??s,location:h.location??(r?"external":"embedded"),_source:"wallet"})),...(e.includeRollupAssets===!1||s?.toLowerCase()!==t?.embeddedWalletAddress?.toLowerCase()?[]:u.assets).map(h=>({...h,owner:h.owner??s,location:"rollup",_source:"spice"}))]:[],[a,l.assets,u.assets,e.includeWalletAssets,e.includeRollupAssets,s,r,t?.embeddedWalletAddress]),f=p.useMemo(()=>m.map(h=>({asset:h,...Qn(h,e.role??"holding",{allowedTokens:t?.allowedTokens,rpcOverrides:t?.rpcOverrides,liquidityVenues:t?.liquidityVenues,isWhitelistGateActive:!!t?.isWhitelistGateActive},e.destination,e.supportedSourceAssets,{requiresEscrow:e.requiresEscrow})})),[m,t?.allowedTokens,t?.rpcOverrides,t?.liquidityVenues,t?.isWhitelistGateActive,e.role,e.destination,e.supportedSourceAssets,e.requiresEscrow]);return{positions:f,assets:p.useMemo(()=>f.filter(h=>h.eligible&&h.asset.balance>0n).map(h=>h.asset),[f]),walletAssets:p.useMemo(()=>m.filter(h=>h._source==="wallet"),[m]),rollupAssets:p.useMemo(()=>m.filter(h=>h._source==="spice"),[m]),loading:l.loading||u.loading,refreshing:l.refreshing||u.refreshing,error:l.error||u.error,refresh:n.invalidate}}function ao(e,t=!0,n){const s=n?.pendingOnly===!0,r=d.relayerService.getBaseUrl(),o=`${r}:${e?.toLowerCase()??""}:${s}`,[a,i]=p.useState({scope:o,actions:[],error:null,loading:t&&!!e,updatedAt:null,revision:0}),[l,u]=p.useState(0),m=p.useCallback(()=>u(h=>h+1),[]);p.useEffect(()=>{if(!t||!e){i(w=>w.scope===o&&w.actions.length===0&&!w.error&&!w.loading&&!w.updatedAt&&w.revision===0?w:{scope:o,actions:[],error:null,loading:!1,updatedAt:null,revision:0});return}const h=new AbortController,y=new d.RelayerService;y.setBaseUrl(r);let g;i(w=>({scope:o,actions:w.scope===o?w.actions:[],error:w.scope===o?w.error:null,loading:!0,updatedAt:w.scope===o?w.updatedAt:null,revision:w.scope===o?w.revision:0}));const x=async()=>{try{const w=await y.getWalletActions(e,{pendingOnly:s,signal:h.signal});h.signal.aborted||i(b=>({scope:o,actions:w,error:null,loading:!1,updatedAt:new Date().toISOString(),revision:b.scope===o?b.revision+1:1}))}catch(w){if(h.signal.aborted)return;const b=w instanceof d.SpiceflowError&&w.context.httpStatus===404;i(b&&!s?k=>({scope:o,actions:[],error:null,loading:!1,updatedAt:new Date().toISOString(),revision:k.scope===o?k.revision+1:1}):k=>({scope:o,actions:k.scope===o?k.actions:[],error:"Activity is temporarily unavailable. Refresh to check again.",loading:!1,updatedAt:k.scope===o?k.updatedAt:null,revision:k.scope===o?k.revision:0}))}h.signal.aborted||(g=setTimeout(x,5e3))};return x(),window.addEventListener("online",m),()=>{h.abort(),g&&clearTimeout(g),window.removeEventListener("online",m)}},[r,e,t,o,s,l,m]);const f=a.scope===o;return{actions:t&&e&&f?a.actions:[],error:f?a.error:null,loading:t&&!!e&&(!f||a.loading),updatedAt:f?a.updatedAt:null,revision:f?a.revision:0,refresh:m}}function ia(e){const t=p.useRef(0),n=p.useRef(null),s=p.useRef(e.run);s.current=e.run;const r=p.useRef(e.onSkip);r.current=e.onSkip;const o=p.useRef(e.onCleanup);o.current=e.onCleanup,p.useEffect(()=>{if(!e.shouldRun){t.current+=1,n.current?.abort(),r.current?.();return}let a=!1,i=!1;const l=async h=>{if(h&&i)return;n.current?.abort();const y=new AbortController;n.current=y;const g=++t.current;i=!0;try{await s.current({isBackground:h,isCurrent:()=>!a&&t.current===g,signal:y.signal})}finally{i=!1}},u=window.setTimeout(()=>void l(!1),e.delayMs??250),m=()=>{document.hidden||l(!0)},f=e.backgroundIntervalMs?window.setInterval(m,e.backgroundIntervalMs):void 0;return f!==void 0&&document.addEventListener("visibilitychange",m),()=>{a=!0,n.current?.abort(),clearTimeout(u),f!==void 0&&(window.clearInterval(f),document.removeEventListener("visibilitychange",m)),o.current?.()}},[e.shouldRun,e.delayMs,e.backgroundIntervalMs,...e.deps])}function vc(e,t){if(e.length!==t.length)return!1;const n=R.hashChainBatches(e),s=R.hashChainBatches(t);return n.every((r,o)=>r.hash===s[o]?.hash)}const Wn=e=>new Promise(t=>setTimeout(t,e)),Ku="0xa9059cbb";function Cc(e){const t=e.findIndex(r=>R.isSpicenetChainId(r.chainId));if(t<=0)return[];const n=new Map,s=(r,o,a)=>{if(a<=0n)return;const i=`${r}:${o.toLowerCase()}`,l=n.get(i);l?l.amount+=a:n.set(i,{chainId:r,token:o,amount:a})};for(const r of e.slice(0,t)){const o=R.getEscrowContract(r.chainId);if(!(!o||o===R.ZERO_ADDRESS)){for(const a of r.calls)if(a.value&&a.value>0n&&d.addressesEqual(a.to,o)&&s(r.chainId,R.ZERO_ADDRESS,a.value),!!a.data?.startsWith(Ku))try{const i=N.decodeFunctionData({abi:N.erc20Abi,data:a.data});if(i.functionName!=="transfer")continue;const[l,u]=i.args;d.addressesEqual(l,o)&&s(r.chainId,a.to,u)}catch{}}}return[...n.values()]}function kc(e){const t=R.getTokenByAddress(e.token,e.chainId);return[t?.equivalenceGroup,t?.symbol,t?.name]}function Sc(e,t){return pc(e,t.chainId,t.token,kc(t))}function Yu(e,t){const n=ju(e,t.chainId,t.token,kc(t));return!n||n.receiptDecimals>=n.chainDecimals?t.amount:R.convertAmountBetweenDecimals(R.convertAmountBetweenDecimals(t.amount,n.chainDecimals,n.receiptDecimals),n.receiptDecimals,n.chainDecimals)}async function Ic(e){const{deposits:t,baseline:n,fetchEntries:s,timeoutMs:r=12e4,intervalMs:o,signal:a,wait:i=Wn}=e;if(t.length===0)return!0;const l=new Map(t.map(f=>[f,Sc(n,f)])),u=Date.now(),m=u+r;for(;!a?.aborted;){try{const g=await s();if(t.every(x=>Sc(g,x)-l.get(x)>=Yu(g,x)))return!0}catch{}const f=Date.now();if(f>=m)return!1;const h=f-u,y=o??(h<5e3?250:h<15e3?1e3:3e3);await i(Math.min(y,m-f))}return!1}function ca(e,t){const n=R.hashChainBatches(e).map(s=>s.hash);return N.keccak256(N.encodeAbiParameters([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,t,n]))}async function la(e,t,n,s,r){if(s?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");const o={raw:ca(t,n)},a=r?await e.signMessage(o,r):await e.signMessage(o);console.debug("[SpiceFlow:execution]",{phase:"signature-returned",at:Date.now()});const i=typeof a=="string"?a:a.signature;if(!i)throw new d.SpiceflowError("SIGNATURE_FAILED","Failed to sign intent authorization. The wallet returned an empty signature.");return i}function Zu(e){return e.domain==="spicenet"||R.isSpicenetChainId(e.chainId)}const Ac=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;async function Xu(e,t,n){const s=(m,f)=>new d.SpiceflowError("SIGNATURE_FAILED","The wallet returned an invalid authorization. Review the action and try again.",{chainId:t.chainId,reason:m,...f?{cause:f}:{}});if(!e||typeof e!="object")throw s("missing-authorization");const r=e;for(const m of["address","contractAddress"])if(r[m]!==void 0&&(typeof r[m]!="string"||r[m].toLowerCase()!==t.address.toLowerCase()))throw s("authorization-target-mismatch");for(const m of["chainId","nonce"]){const f=r[m];if(f!==void 0&&(typeof f=="bigint"?f!==BigInt(t[m]):typeof f!="number"||!Number.isSafeInteger(f)||f!==t[m]))throw s(`authorization-${m}-mismatch`)}const{r:o,s:a,yParity:i}=r;if(typeof o!="string"||typeof a!="string"||!/^0x[0-9a-fA-F]{64}$/.test(o)||!/^0x[0-9a-fA-F]{64}$/.test(a)||i!==0&&i!==1||BigInt(o)===0n||BigInt(o)>=Ac||BigInt(a)===0n||BigInt(a)>Ac/2n)throw s("invalid-signature");const l={...t,r:o,s:a,yParity:i};let u;try{u=await N.recoverAddress({hash:N.keccak256(N.concatHex(["0x05",N.toRlp([N.toHex(t.chainId),t.address,t.nonce===0?"0x":N.toHex(t.nonce)])])),signature:l})}catch(m){throw s("invalid-signature",m)}if(u.toLowerCase()!==n.toLowerCase())throw s("authorization-signer-mismatch");return l}async function da(e){const{chainBatches:t,signingAddress:n,actions:s,cache:r,signal:o,onSignatureRequested:a,beforeSign:i}=e;if(o?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");if(typeof n!="string"||!N.isAddress(n,{strict:!1})||n.toLowerCase()===N.zeroAddress)throw new d.SpiceflowError("INVALID_PARAMS","A valid signing address is required.");for(const h of t)if(!Number.isSafeInteger(h.chainId)||h.chainId<=0)throw new d.SpiceflowError("INVALID_PARAMS","A valid authorization chain is required.");const l=[...new Set(t.filter(h=>!Zu(h)).map(h=>h.chainId))].map(h=>{const y=d.getDelegateContractAddress(h);if(!N.isAddress(y,{strict:!1})||y.toLowerCase()===N.zeroAddress)throw new d.SpiceflowError("INVALID_PARAMS","A valid delegation target is required.");return{chainId:h,client:d.getClientForChain(h),delegateContract:y}}),[u]=await Promise.all([Promise.all(l.map(async({chainId:h,client:y,delegateContract:g})=>{const x=Number(await R.getAccountNonce(n,y));if(!Number.isSafeInteger(x)||x<0)throw new d.SpiceflowError("INVALID_PARAMS","The authorization nonce is invalid.");const w=[n.toLowerCase(),h,g.toLowerCase(),x].join(":");return{chainId:h,delegateContract:g,nonce:x,cacheKey:w,cached:r?.get(w)}})),l.length?s.prepareSigning?.():void 0]);if(await i?.(),o?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");const m=[];let f=!1;for(const{chainId:h,delegateContract:y,nonce:g,cacheKey:x,cached:w}of u){if(w===void 0&&f&&await i?.(),o?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");const b=w===void 0?await s.signAuthorization({contractAddress:y,chainId:h,nonce:g},a):w;let k;try{k=await Xu(b,{address:y,chainId:h,nonce:g},n)}catch(A){throw r?.delete(x),A}if(o?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");f=!0,r?.set(x,k),m.push(k)}return m}const Ec=15;function Ju(e){return e.now-e.lastProgressAt>=e.pollTimeoutMs}function Fc(e,t){return{intentId:e,steps:t.map(n=>({...n,status:"pending"})),overallStatus:"processing"}}function io(e,t,n){const s=e.steps.map(i=>({...i})),r=s[t];if(!r)return e;n.status==="success"||n.status==="completed"?(s[t]={...r,status:"success",transactionHash:n.transactionHash},t+1<s.length&&s[t+1].status==="pending"&&(s[t+1]={...s[t+1],status:"processing"})):n.status==="reverted"||n.status==="error"?s[t]={...r,status:"failed",transactionHash:n.transactionHash,error:n.error}:s[t]={...r,status:"processing"};const o=s.some(i=>i.status==="failed"),a=s.every(i=>i.status==="success");return{...e,steps:s,overallStatus:o?"failed":a?"success":"processing"}}function $u({checkStepStatus:e,retryStep:t,maxRetries:n=3,pollingInterval:s=2500,pollTimeoutMs:r=3e5}){const[o,a]=p.useState(null),i=p.useRef(null),l=p.useRef(null),u=p.useRef(!1),m=p.useRef(!1),f=p.useRef(0),h=p.useRef({}),y=p.useRef(0),g=p.useCallback(C=>{i.current=C,a(C)},[]),x=p.useCallback(()=>{l.current&&(clearInterval(l.current),l.current=null)},[]),w=p.useCallback(()=>{f.current=0,h.current={},y.current=0,u.current=!0,x(),g(null)},[x,g]),b=p.useCallback((C,E)=>{x(),u.current=!1,g(Fc(C,E))},[x,g]),k=p.useCallback((C,E)=>{const D=i.current;D&&g(io(D,C,E))},[g]),A=p.useCallback((C,E)=>{x(),u.current=!1,m.current=!1,f.current=0,h.current={},y.current=Date.now(),g(Fc(C,E));const D=async()=>{if(!(u.current||m.current||!e)){m.current=!0;try{if(Ju({now:Date.now(),lastProgressAt:y.current,pollTimeoutMs:r})){const F=i.current;F&&g({...F,steps:F.steps.map(O=>O.status==="success"?O:{...O,status:"failed",error:"Taking longer than expected. It may still complete - check the explorer, then refresh."}),overallStatus:"failed"}),u.current=!0,x();return}const S=i.current;if(!S)return;const v=S.steps.findIndex(F=>F.status!=="success");if(v===-1){u.current=!0,x();return}if(!(v===0||S.steps[v-1].status==="success"))return;try{const F=S.steps[v].stepId,{data:O}=await e(C,F);if(f.current=0,O.status==="success"&&(y.current=Date.now()),O.status==="reverted"){const q=h.current[F]||0;if(t&&q<n){h.current[F]=q+1;try{await t(C,F)}catch(I){console.error(`[intentStatus] retry failed for step ${F}:`,I)}g(io(i.current,v,{status:"executing"}));return}}const j=io(i.current,v,O);g(j),j.overallStatus!=="processing"&&(u.current=!0,x())}catch(F){f.current+=1,console.error(`[intentStatus] poll error (${f.current}/${Ec}):`,F),f.current>=Ec&&(g(io(i.current,v,{status:"error"})),u.current=!0,x())}}finally{m.current=!1}}};D(),l.current=setInterval(D,s)},[e,t,n,s,r,x,g]);return p.useEffect(()=>()=>x(),[x]),{intentStatus:o,startStatusPolling:A,beginStatusTracking:b,applyStepUpdate:k,stopStatusPolling:x,clearStatus:w}}function _u(e,t){return(t||"").trim()||`Transaction ${e}. The transaction was rejected on-chain. This may be due to insufficient balance, price changes, or health factor constraints. Please verify your positions and try again.`}const ep=350,tp=2500;async function Tc(e){const{actionId:t,intentIndex:n,intentId:s,stepIndex:r,maxPolls:o=48,maxExecuteAttempts:a=3,pollsBeforeRetry:i=5,maxConsecutiveStatusErrors:l=15,onStatusMessage:u,onStepUpdate:m,signal:f,chainId:h,startWithExecute:y=!0,observeOnly:g=!1,relayer:x=d.relayerService,completeOnExecution:w=!1}=e;if(f?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");let b="pending",k,A,C=e.initialExecuteAttempts??0,E=0,D,S;const v=new Promise((O,j)=>{D=O,S=()=>j(new d.SpiceflowError("ABORT","Execution transaction aborted"))}),F=()=>{C++,e.onExecuteAttempt?.(C),x.executeStep(t,n,r,{action:"execute"}).then(O=>{O.transactionHash&&(k=O.transactionHash),O.status==="success"&&D({status:O.status,transactionHash:O.transactionHash})}).catch(O=>{const j=O instanceof Error?O.message:String(O);console.warn(`[execution] executeStep ${r} attempt ${C} error (will poll):`,j)})};f?.addEventListener("abort",S,{once:!0});try{y&&!g&&C<a&&F();for(let O=0;O<o;O++){const j=O===0?ep:tp;try{const I=await Promise.race([Wn(j).then(()=>{}),v]);if(f?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");const B=I??await Promise.race([x.checkStepStatus(s,r,w).then(M=>M.data),v]);if(f?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");E=0,b=B.status,A=B.error;const T=B.transactionHash;T&&(k=T),w&&/^0x[0-9a-f]{64}$/i.test(T??"")&&(B.executionStatus==="success"||B.executionStatus==="reverted")&&(b=B.executionStatus,A=void 0),m?.({status:b,transactionHash:k,error:A})}catch(I){if(I instanceof Error&&(I.name==="AbortError"||I instanceof d.SpiceflowError&&I.code==="ABORT"))throw I;if(E++,E>=l){if(!g)throw I;u?.("Status is temporarily unavailable. The backend continues this action.",k)}continue}if(!g&&b==="created"&&O>=C*i&&C<a&&F(),b==="reverted"||b==="error")throw new d.SpiceflowError("ON_CHAIN_REVERT",_u(b,A),{status:b,txHash:k,actionId:t,intentId:s,stepId:r,chainId:h});if(b==="success"||b==="completed")return k;let q="Waiting for solver...";b==="executing"?q="Transaction executing...":b==="submitted"?q="Transaction submitted...":b==="created"&&(q="Waiting for relayer..."),u?.(q,k)}throw new d.SpiceflowError("POLLING_EXHAUSTED",`Transaction is still processing (status: ${b}). This doesn't mean it failed \u2014 the solver may still complete it. Check your positions in a few minutes, or try refreshing the page.`,{actionId:t,intentId:s,stepId:r,lastStatus:b,pollAttempts:o,maxPolls:o,txHash:k})}finally{f?.removeEventListener("abort",S)}}async function np(e){const{actionId:t,intentIndex:n,intentId:s,totalSteps:r,observeOnly:o,delayBeforeSpicenetStepMs:a=5e3,isSpicenetStep:i,beforeStep:l,maxExecuteAttemptsForStep:u,maxPolls:m=48,onStatusMessage:f,onStepUpdate:h,signal:y}=e;let g;for(let x=e.startStep??0;x<r;x++){if(!o&&x>0&&i?.(x)&&a>0&&await Wn(a),o||await l?.(x),y?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");const w=u?.(x)??3,b=await Tc({actionId:t,intentIndex:n,intentId:s,stepIndex:x,observeOnly:o,startWithExecute:e.startWithExecute,relayer:e.relayer,maxPolls:m,maxExecuteAttempts:w,initialExecuteAttempts:e.executeAttempts?.get(x),onExecuteAttempt:k=>e.executeAttempts?.set(x,k),maxConsecutiveStatusErrors:w===6?5:15,onStatusMessage:f,onStepUpdate:h?k=>h(x,k):void 0,signal:y,completeOnExecution:x===r-1&&i?.(x)===!1});b&&(g=b)}return g}const sp="0xa9059cbb",rp=[R.SPICE_COMBINED_FEE_RECIPIENT,R.SPICE_GAS_FEE_RECIPIENT,R.SPICE_PLATFORM_FEE_RECIPIENT];function Rc(e){return rp.some(t=>d.addressesEqual(e,t))}function co(e,t){return e.map(n=>{if(n.domain==="spicenet"||R.isSpicenetChainId(n.chainId)||n.calls.length===0)return n;const s=new Set((n.tokenTransfers??[]).filter(a=>(a.from==="escrow"||a.from==="solver")&&d.addressesEqual(a.to,t)).map(a=>a.token.toLowerCase()));if(s.size===0)return n;const r=[...s].some(R.isNativeToken);let o=0;for(const a of n.calls){if(r&&a.value>0n&&a.data==="0x"&&Rc(a.to)){o+=1;continue}if(!a.data?.startsWith(sp))break;try{const i=N.decodeFunctionData({abi:N.erc20Abi,data:a.data});if(i.functionName!=="transfer")break;const[l]=i.args;if(!Rc(l)||!s.has(a.to.toLowerCase()))break;o+=1}catch{break}}return o===0?n:{...n,calls:n.calls.slice(o)}})}async function ua(e,t,n){if(!t||!/^0x[0-9a-f]{64}$/i.test(t))throw new Error("The destination receipt is not available yet; reconcile the existing action before retrying.");const s=()=>new d.SpiceflowError("ABORT","Execution observation retired");if(n?.aborted)throw s();const r=await new Promise((o,a)=>{const i=()=>a(s());n?.addEventListener("abort",i,{once:!0}),Promise.resolve().then(()=>e.waitForTransactionReceipt({hash:t,timeout:12e4,pollingInterval:2e3,confirmations:1})).then(o,a).finally(()=>n?.removeEventListener("abort",i))});if(n?.aborted)throw s();if(r.transactionHash?.toLowerCase()===t.toLowerCase()&&r.status==="reverted")throw new d.SpiceflowError("ON_CHAIN_REVERT","The destination transaction reverted.",{status:"reverted",txHash:t});if(r.transactionHash?.toLowerCase()!==t.toLowerCase()||r.status!=="success")throw new Error("The destination transaction has not been confirmed successfully. Reconcile the existing action before retrying.");return t}async function lo(e){let t=e.hash,n=!1;const s=Date.now()+12e4,r=a=>a.transactionHash&&a.transactionHash.toLowerCase()!==t.toLowerCase();let o=await e.client.waitForTransactionReceipt({hash:t,timeout:12e4,pollingInterval:2e3,confirmations:1,onReplaced:a=>{const i=a.transaction,l=a.replacedTransaction;if(!(a.reason==="repriced"&&l?.hash?.toLowerCase()===t.toLowerCase()&&l?.to?.toLowerCase()===e.call.to.toLowerCase()&&(l.input??"0x").toLowerCase()===e.call.data.toLowerCase()&&BigInt(l.value??0)===e.call.value&&l?.from&&l.nonce!==void 0&&/^0x[0-9a-f]{64}$/i.test(i?.hash??"")&&i?.to?.toLowerCase()===e.call.to.toLowerCase()&&(i.input??"0x").toLowerCase()===e.call.data.toLowerCase()&&BigInt(i.value??0)===e.call.value&&i.from?.toLowerCase()===l?.from?.toLowerCase()&&i.nonce===l?.nonce)){n=!0,e.onCancelled?.();return}t=i.hash,e.onRepriced?.(t)}});if(n)throw new Error("Transaction was cancelled or replaced with a different action; retry the unfinished action");if((e.confirmations??1)>1&&!r(o)&&o.status==="success"&&(o=await e.client.waitForTransactionReceipt({hash:t,timeout:Math.max(s-Date.now(),1),pollingInterval:2e3,confirmations:e.confirmations})),r(o))throw new Error("Unexpected transaction receipt; recover the submitted transaction before retrying");return{receipt:o,hash:t}}const pa=10n,op=5;function uo(e,t,n){return n?.calls.length&&n.amountOutMinimum>0n?[{chainId:e,token:t,amount:n.amountOutMinimum}]:[]}function fa(e){return e.map(t=>({...t,calls:[...t.calls],tokenTransfers:t.tokenTransfers?[...t.tokenTransfers]:void 0}))}function po({token:e,recipient:t,amount:n}){return{to:e,value:0n,data:N.encodeFunctionData({abi:N.erc20Abi,functionName:"transfer",args:[t,n]})}}function ap({chainBatches:e,token:t,amount:n}){const s=fa(e),r=s[s.length-1];if(!r)return s;const o=R.getEscrowContractAddress(r.chainId);return r.calls=[...r.calls,po({token:t,recipient:o,amount:n})],s}function Bc({chainBatches:e,user:t,token:n,grossAmount:s,gasFee:r,policy:o}){const a=fa(e),i=a[a.length-1];if(!i)throw new d.SpiceflowError("INVALID_PARAMS","Action-output escrow funding requires at least one chain batch.");const l=d.calculateBpsFee(s,BigInt(o?.platformBps??pa)),u=r+l;if(u>=s)throw new d.SpiceflowError("INVALID_PARAMS","Borrow amount is too small after gas and Spicenet fees.",{grossAmount:s.toString(),gasFee:r.toString(),spicenetFee:l.toString()});const m=s-u,f=R.getEscrowContractAddress(i.chainId),h=[];return r>0n&&h.push(po({token:n,recipient:o?.gasRecipient??R.SPICE_GAS_FEE_RECIPIENT,amount:r})),l>0n&&h.push(po({token:n,recipient:o?.platformRecipient??R.SPICE_PLATFORM_FEE_RECIPIENT,amount:l})),i.calls=[...i.calls,...h,po({token:n,recipient:f,amount:m})],i.tokenTransfers=[...i.tokenTransfers??[],...r>0n?[{from:t,to:R.SPICE_GAS_FEE_RECIPIENT,token:n,amount:r}]:[],...l>0n?[{from:t,to:R.SPICE_PLATFORM_FEE_RECIPIENT,token:n,amount:l}]:[],{from:t,to:f,token:n,amount:m}],{chainBatches:a,gasFee:r,spicenetFee:l,netEscrowAmount:m,outputCredit:{chainId:i.chainId,token:n,amount:s}}}async function Oc({chainBatches:e,user:t,token:n,grossAmount:s,chainAuthorizations:r}){let o=0n,a,i=Bc({chainBatches:e,user:t,token:n,grossAmount:s,gasFee:o});for(let l=0;l<op;l+=1){const u=R.hashChainBatches(i.chainBatches),m=await d.relayerService.estimateBatchGas({user:t,outputToken:n,chainBatches:i.chainBatches.map((h,y)=>({...h,hash:u[y].hash})),chainAuthorizations:r}),f=m.gasFee;if(f===o&&JSON.stringify(m.policy)===JSON.stringify(a))return i;a=m.policy,o=f,i=Bc({chainBatches:e,user:t,token:n,grossAmount:s,gasFee:o,policy:a})}throw new d.SpiceflowError("INVALID_PARAMS","Action-output fee estimate did not converge. Please retry.")}function $n(e){return R.isSpicenetChainId(e.chainId)}const ip="0xa9059cbb";function Sr(e,t){return`${e}:${R.normalizeNativeTokenAddress(t).toLowerCase()}`}function jc(e,t){return t===R.ZERO_ADDRESS.toLowerCase()?{symbol:d.getChainName(e),decimals:18}:R.getTokenByAddress(t,e)??{symbol:"tokens",decimals:18}}function cp(e,t){const n=R.getTokenByAddress(t,e);return[n?.equivalenceGroup,n?.symbol,n?.name]}async function ma(e){return d.getWalletBalanceEntries(e)}async function ha(e,t,n){const s=new Map,r=new Map,o=[...n?.walletFundingRequirement?[n.walletFundingRequirement]:[],...n?.walletFundingRequirements??[]];for(const f of o){if(f.amount<0n)throw new Error("Accepted wallet funding must not be negative");const h=Sr(f.chainId,f.token);r.set(h,(r.get(h)??0n)+f.amount),s.set(h,0n)}const a=new Map,i=new Map,l=new Map,u=new Map;for(const f of n?.actionOutputCredits??[]){const h=Sr(f.chainId,f.token);u.set(h,(u.get(h)??0n)+f.amount)}for(const f of e){if($n(f))continue;for(const g of f.tokenTransfers??[]){if(g.from!=="escrow"&&g.from!=="solver"||!d.addressesEqual(g.to,t))continue;const x=BigInt(g.amount??0);if(x<=0n)continue;const w=Sr(f.chainId,g.token);a.set(w,(a.get(w)??0n)+x),g.from==="escrow"&&i.set(w,(i.get(w)??0n)+x)}const h=R.getEscrowContract(f.chainId),y=g=>!!h&&h!==R.ZERO_ADDRESS&&d.addressesEqual(g,h);for(const g of f.calls){if(g.value&&g.value>0n){const x=Sr(f.chainId,R.ZERO_ADDRESS);s.set(x,(s.get(x)??0n)+g.value),y(g.to)&&l.set(x,(l.get(x)??0n)+g.value)}if(g.data?.startsWith(ip))try{const x=N.decodeFunctionData({abi:N.erc20Abi,data:g.data});if(x.functionName!=="transfer")continue;const[w,b]=x.args,k=g.to.toLowerCase(),A=Sr(f.chainId,k);s.set(A,(s.get(A)??0n)+b),y(w)&&l.set(A,(l.get(A)??0n)+b)}catch{}}}let m=null;for(const[f,h]of i){const y=h-(l.get(f)??0n);if(y<=0n)continue;const[g,x]=f.split(":"),w=Number(g),b=jc(w,x);m??(m=await ma(t));const k=pc(m,w,x,cp(w,x));if(!(k>=y))throw new d.SpiceflowError("INVALID_PARAMS",`Insufficient Spice ${b.symbol}: needs ${N.formatUnits(y,b.decimals)}, has ${N.formatUnits(k,b.decimals)}.`,{chainId:w,token:x,userAddress:t,requiredAmount:y.toString(),balance:k.toString(),balanceSource:"spice"})}for(const[f,h]of s){const[y,g]=f.split(":"),x=Number(y);let w=h-(a.get(f)??0n)-(u.get(f)??0n);const b=r.get(f)??0n;if(b>w&&(w=b),w<=0n)continue;const k=d.getClientForChain(x),A=g===R.ZERO_ADDRESS.toLowerCase()?await k.getBalance({address:t}):await k.readContract({address:g,abi:N.erc20Abi,functionName:"balanceOf",args:[t]});if(A>=w)continue;const C=jc(x,g);throw new d.SpiceflowError("INVALID_PARAMS",`Insufficient ${C.symbol} on ${d.getChainName(x)}: needs ${N.formatUnits(w,C.decimals)}, has ${N.formatUnits(A,C.decimals)}.`,{chainId:x,token:g,userAddress:t,requiredAmount:w.toString(),balance:A.toString(),balanceSource:"wallet"})}}function lp({chainBatches:e,tokenAddress:t,tokenTransferAmount:n,useCustomTransfers:s}){if(!(e.some($n)||!(s?e.some(r=>$n(r)?!1:(r.tokenTransfers??[]).some(o=>o.from==="escrow"&&BigInt(o.amount??0)>0n)):n>0n)))throw new d.SpiceflowError("INVALID_PARAMS","Payouts funded from Spice balance require a Spicenet funding batch before the destination chain batch. Deposits into Spice balance and gas-only actions do not need one.",{tokenAddress:t,tokenTransferAmount:n.toString(),useCustomTransfers:!!s})}function dp(e,t,n,s){t.forEach((r,o)=>{if(!r.to||!r.from||!r.token||r.amount===void 0)throw new d.SpiceflowError("INVALID_TOKEN_TRANSFER",`tokenTransfers[${o}] on chain ${e} is missing required fields (to/from/token/amount). This usually means the embedded wallet wasn't ready when the intent was built \u2014 please retry.`,{chainId:e,transferIndex:o,transfer:{from:r.from,to:r.to,token:r.token,amount:r.amount?.toString()},signingAddress:n,useCustomTransfers:s})})}function fo({user:e,chainBatches:t,tokenAddress:n,tokenTransferAmount:s,exp:r,signature:o,chainAuthorizations:a,useCustomTransfers:i}){const l=t,u=R.hashChainBatches(l),m=l.filter(f=>!$n(f)).length;if(lp({chainBatches:l,tokenAddress:n,tokenTransferAmount:s,useCustomTransfers:i}),!i&&s>0n&&m>1)throw new d.SpiceflowError("INVALID_PARAMS","Multiple non-Spicenet batches require explicit tokenTransfers. Pass useCustomTransfers with per-batch transfers instead of relying on the default escrow payout injection.",{nonSpicenetBatchCount:m,tokenAddress:n,tokenTransferAmount:s.toString()});return{user:e,...a?{chainAuthorizations:a}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:o,nbf:0,exp:r,chainBatches:u.map((f,h)=>{const y=l[h],g=$n(y)?[]:i?y.tokenTransfers??[]:s>0n?[{from:"escrow",to:e,token:n,amount:s}]:[];return dp(Number(f.chainId),g,e,i),{hash:f.hash,chainId:Number(f.chainId),tokenTransfers:g,calls:f.calls}})}]}}function Dc(e,t){const n=t?.depositToEscrow?.gasFundingSource==="action-output"?t.depositToEscrow:null,s=t?.depositToEscrow&&!n?ap({chainBatches:e,token:t.depositToEscrow.token,amount:t.depositToEscrow.amount}):fa(e);return{actionOutputDeposit:n,batches:s}}let ga=!1;function Ys(){const{address:e,isConnected:t,isAuthenticated:n,actions:s}=d.useWallet(),r=p.useRef(null),o=p.useRef(0),a=p.useRef(null),{intentStatus:i,startStatusPolling:l,beginStatusTracking:u,applyStepUpdate:m,clearStatus:f}=$u({checkStepStatus:(A,C)=>d.relayerService.checkStepStatus(A,C),retryStep:async(A,C)=>{const[E,D]=A.split("/"),S=parseInt(D||"0",10);await d.relayerService.executeStep(E,S,C,{action:"execute"})}}),h=p.useCallback(()=>{o.current++,a.current=null,f()},[f]),y=p.useRef(s),g=p.useRef(new Map);y.current=s;const x=p.useCallback((A,C,E,D,S)=>da({chainBatches:A,signingAddress:C,actions:y.current,cache:g.current,signal:E,onSignatureRequested:D,beforeSign:S}),[]),w=p.useCallback((A,C,E,D)=>la(y.current,A,C,E,D),[]),b=p.useCallback(async(A,C,E,D,S,v)=>{let F={},O={};const j=(I,B,T)=>{T?.actionId&&(F={actionId:T.actionId,intentId:T.intentId,intentIndex:T.intentIndex,totalSteps:T.totalSteps,autoContinue:T.autoContinue,user:v?.userOverride||e}),D?.({step:I,message:B,...O,...F,...T})};if(ga)throw new d.SpiceflowError("CONCURRENT_EXECUTION","A execution transaction is already in progress. Please wait.");ga=!0;const q=o.current;try{if(!e)throw new d.SpiceflowError("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const I=v?.userOverride||e,B=d.relayerService.getBaseUrl(),T=a.current;if(T&&d.addressesEqual(T.user,I)&&T.apiUrl===B){if(T.resume)return await T.resume(A,C,E,S,D,v);throw T.error}a.current=null;const M=Ce=>R.hashConditionalExecutionPlan(Ce.map(Re=>({...Re,tokenTransfers:Re.tokenTransfers??[]})),[]),P=M(A),z=Ce=>new Map(Object.entries(Ce??{}).filter(([Re,ke])=>Re!=="signal"&&(typeof ke!="function"||["prepareForSigning","adjustBatchesForEstimate","resolveActionOutputCredits"].includes(Re))).map(([Re,ke])=>[Re,typeof ke=="function"?ke:JSON.stringify(ke,(qe,xe)=>typeof xe=="bigint"?xe.toString():xe)])),Q=z(v),Z=await d.relayerService.supportsAutomaticContinuation({signal:S}),{actionOutputDeposit:se,batches:X}=Dc(A,v);let K=X,re=[],$=v?.useCustomTransfers,pe=Cc(K),we=null;const ge=async()=>{(v?.walletFundingRequirement||v?.walletFundingRequirements?.length)&&await ha([],I,{walletFundingRequirement:v?.walletFundingRequirement,walletFundingRequirements:v?.walletFundingRequirements});for(let Ce=0;pe.length>0&&Ce<3;Ce++)try{we=await ma(I);break}catch(Re){if(S?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");if(Ce===2)throw new d.SpiceflowError("RELAYER_ERROR","Unable to read your Spice balance. Please try again before submitting the transaction.",{cause:Re});await Wn(1e3)}await v?.validateBeforeSubmit?.(K)};j("building","Preparing your wallet and transaction...");const be=await x(K,I,S,()=>j("signing-delegation","Confirm the authorization in your wallet..."),ge);if(j("building","Checking transaction fees and balances..."),S?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");const _=BigInt(Math.floor(Date.now()/1e3)+3600);if(se){const Ce=await Oc({chainBatches:A,user:I,token:se.token,grossAmount:se.amount,chainAuthorizations:be});K=Ce.chainBatches,re=[Ce.outputCredit],$=!0}if(!v?.skipPreSubmitFeeEstimate){let Ce=!1;if(v?.feeExecutionMode==="user-transfer"&&v.adjustBatchesForEstimate&&d.relayerService.canValidateActionFees()){const Re=await d.relayerService.validateActionFees(fo({user:I,chainBatches:K,tokenAddress:C,tokenTransferAmount:E,exp:Number(_),signature:"0x00",chainAuthorizations:be,useCustomTransfers:$}),{signal:S});r.current=Re;const ke=await v.adjustBatchesForEstimate({feeEstimate:Re,chainBatches:K});Ce=!ke||vc(K,ke),ke&&(K=ke)}for(let Re=0;!Ce&&Re<10;Re++){const ke=v?.feeExecutionMode==="user-transfer"?co(K,I):K,qe=fo({user:I,chainBatches:ke,tokenAddress:C,tokenTransferAmount:E,exp:Number(_),signature:"0x00",chainAuthorizations:be,useCustomTransfers:$}),xe=await d.relayerService.estimateActionFees(qe,{signal:S});r.current=xe;const Pe=await v?.adjustBatchesForEstimate?.({feeEstimate:xe,chainBatches:K}),lt=!!Pe&&vc(K,Pe);if(!Pe||lt){Ce=!0;break}K=Pe}if(!Ce)throw new d.SpiceflowError("INVALID_PARAMS","Fee estimate did not converge. Please retry.")}if(v?.prepareForSigning){const Ce=await v.prepareForSigning(K);if(Ce.length!==K.length||Ce.some((Re,ke)=>Re.chainId!==K[ke].chainId||Re.domain!==K[ke].domain))throw new Error("The funded route changed before signing");K=Ce}v?.resolveActionOutputCredits&&(re=await v.resolveActionOutputCredits()),(!v?.skipUserFundingPreflight||v.walletFundingRequirement||v.walletFundingRequirements?.length)&&await ha(v?.skipUserFundingPreflight?[]:K,I,{actionOutputCredits:re,walletFundingRequirement:v?.walletFundingRequirement,walletFundingRequirements:v?.walletFundingRequirements}),pe=Cc(K),pe.length&&!we&&(we=await d.getWalletBalanceEntries(I)),await v?.validateBeforeSubmit?.(K),j("building","Preparing the signing request...");const G=await w(K,_,S,()=>j("signing-intent","Confirm the transaction in your wallet..."));if(S?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");if(B!==d.relayerService.getBaseUrl())throw new d.SpiceflowError("RELAYER_ERROR","The network changed before submission. Review your balances before trying again.");const ae=fo({user:I,chainBatches:K,tokenAddress:C,tokenTransferAmount:E,exp:Number(_),signature:G,chainAuthorizations:be,useCustomTransfers:$});let W=K.length-1;for(;W>=0&&$n(K[W]);)W--;O={totalSteps:K.length},W>=0&&(O={...O,destinationChainId:Number(K[W].chainId),destinationStepIndex:W});const De=Date.now();if(j("submitting","Submitting to relayer..."),await v?.validateBeforeSubmit?.(K),S?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");if(B!==d.relayerService.getBaseUrl())throw new d.SpiceflowError("RELAYER_ERROR","The network changed before submission. Review your balances before trying again.");console.debug("[SpiceFlow:execution]",{phase:"submit-check-complete",at:Date.now(),durationMs:Date.now()-De});const Te=K.length;let L;try{L=await d.relayerService.createAction({...ae,...v?.externalExecution?{externalExecution:v.externalExecution}:{}},{autoContinue:Z,idempotencyKey:v?.idempotencyKey,signal:S,onAccepted:Ce=>{const[Re,ke="0"]=Ce.intentIds[0].split("/"),qe=parseInt(ke,10);j("executing","Executing on chain...",{actionId:Re,intentId:`${Re}/${qe}`,intentIndex:qe,totalSteps:Te,autoContinue:Ce.autoContinue===!0})}})}catch(Ce){throw q===o.current&&Ce instanceof d.SpiceflowError&&Ce.context.submissionStatus==="unknown"&&(a.current={user:I,apiUrl:B,error:Ce}),Ce}const[H,te]=L.intentIds[0].split("/"),ie=parseInt(te||"0",10),J=`${H}/${ie}`;j("executing","Executing on chain..."),j("executing","Executing on chain...",{actionId:H,intentId:J,intentIndex:ie,totalSteps:K.length,autoContinue:L.autoContinue===!0});const ce=new d.RelayerService;ce.setBaseUrl(B);let Be,Ie=0;const ve=new Map,Ze=async(Ce,Re=D,ke=!1)=>{const qe=(xe,Pe,lt)=>Re?.({step:xe,message:Pe,...lt});try{if((!ke||!Be)&&(Be=await np({actionId:H,intentIndex:ie,intentId:J,totalSteps:Te,signal:Ce,observeOnly:L.autoContinue===!0,startWithExecute:!ke,startStep:ke?Ie:0,executeAttempts:ve,onStepUpdate:(xe,Pe)=>{(Pe.status==="success"||Pe.status==="completed")&&(Ie=Math.max(Ie,xe+1))},relayer:L.autoContinue||ke?ce:d.relayerService,...we?{delayBeforeSpicenetStepMs:0}:{},isSpicenetStep:xe=>$n(K[xe]),beforeStep:async xe=>{if(L.autoContinue===!0||!we||!$n(K[xe]))return;const Pe=await Ic({deposits:pe,baseline:we,fetchEntries:()=>ma(I),signal:Ce});if(Ce?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");if(!Pe)throw new d.SpiceflowError("POLLING_EXHAUSTED","Your deposit is still waiting for Spice credit. Check this transaction's status before trying again.",{actionId:H,intentId:J,stepId:xe})},maxExecuteAttemptsForStep:xe=>$n(K[xe])?6:3,maxPolls:L.autoContinue?Number.POSITIVE_INFINITY:180,onStatusMessage:(xe,Pe)=>{qe("executing",xe,{txHash:Pe,actionId:H,intentId:J,intentIndex:ie,totalSteps:Te,autoContinue:L.autoContinue===!0})}})),v?.requireDestinationReceipt){const xe=[...K].reverse().find(Pe=>!$n(Pe));if(!xe)throw new Error("The action has no destination transaction to verify.");await ua(d.getClientForChain(xe.chainId),Be,Ce)}return qe("success","Transaction successful!",{txHash:Be,actionId:H,intentId:J,intentIndex:ie,totalSteps:Te,autoContinue:L.autoContinue===!0}),a.current?.resume===Ne&&(a.current=null),Be||H}catch(xe){if(xe instanceof d.SpiceflowError&&xe.code==="ON_CHAIN_REVERT"&&xe.context.status==="reverted"&&(xe.context.stepId===0||Te===1))throw a.current?.resume===Ne&&(a.current=null),xe;const Pe=new d.SpiceflowError(xe instanceof d.SpiceflowError?xe.code:"RELAYER_STATUS_ERROR",xe instanceof d.SpiceflowError&&xe.code==="ON_CHAIN_REVERT"?xe.message:`Your action was accepted, but its completion could not be confirmed. Check the original action before trying again. ${xe instanceof Error?xe.message:""}`.trim(),{...xe instanceof d.SpiceflowError?xe.context:{},submissionStatus:"accepted",actionId:H,intentId:J,txHash:Be,cause:xe});throw q===o.current&&(a.current={user:I,apiUrl:B,error:Pe,resume:Ne}),Pe}},Ne=async(Ce,Re,ke,qe,xe,Pe)=>{const lt=z(Pe);if(P!==M(Ce)||Q.size!==lt.size||[...Q].some(([Qe,Xe])=>lt.get(Qe)!==Xe)||!d.addressesEqual(C,Re)||E!==ke)throw a.current.error;return Ze(qe,xe,!0)};return await Ze(S,D)}catch(I){throw console.error("[Execution] Error:",I),j("error",I.message||"Transaction failed",{error:I.message,...I?.context?.submissionStatus==="unknown"?{submissionStatus:"unknown",...typeof I.context.idempotencyKey=="string"&&/^0x[0-9a-f]{64}$/i.test(I.context.idempotencyKey)?{idempotencyKey:I.context.idempotencyKey}:{},...typeof I.context.user=="string"&&/^0x[0-9a-f]{40}$/i.test(I.context.user)?{user:I.context.user}:{}}:{}}),I}finally{ga=!1}},[e,n,x,w]),k=p.useCallback(async(A,C,E,D)=>{if(!e&&(!D?.userOverride||D.signAuthorizationsForEstimate))throw new d.SpiceflowError("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const S=D?.userOverride||e,v=D?.validateFeeCalls===!0&&D.feeExecutionMode==="user-transfer"&&d.relayerService.canValidateActionFees(),{actionOutputDeposit:F,batches:O}=Dc(A,D);let j=O;const q=D?.feeExecutionMode==="user-transfer"&&!v?co(j,S):j,I=D?.signAuthorizationsForEstimate?await x(q,S):void 0;let B=D?.useCustomTransfers;F&&(j=(await Oc({chainBatches:A,user:S,token:F.token,grossAmount:F.amount,chainAuthorizations:I})).chainBatches,B=!0);const T=D?.feeExecutionMode==="user-transfer"&&!v?co(j,S):j,M=fo({user:S,chainBatches:T,tokenAddress:C,tokenTransferAmount:E,exp:Math.floor(Date.now()/1e3)+3600,signature:"0x00",chainAuthorizations:I,useCustomTransfers:B}),P=await(v?d.relayerService.validateActionFees(M,{signal:D?.signal}):d.relayerService.estimateActionFees(M,{signal:D?.signal}));return r.current=P,P},[e,x]);return{execute:b,estimate:k,lastFeeEstimate:r.current,hasEmbeddedWallet:t&&n,intentStatus:i,startStatusPolling:l,beginStatusTracking:u,applyStepUpdate:m,clearStatus:h}}function Zt(e,t,n,s){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const r=10n**BigInt(t-n);return s==="ceil"?(e+r-1n)/r:e/r}function dn(e,t){if(!Number.isInteger(t)||t<0||t>255)throw new Error("Invalid token decimals");if(!/^\d+(?:\.\d*)?$/.test(e))throw new Error("Enter a valid amount.");if((e.split(".")[1]?.replace(/0+$/,"")??"").length>t)throw new Error(`Use at most ${t} decimal places for this source.`);return N.parseUnits(e,t)}function on(e,t,n){const s=Zt(e,t,n,"floor");if(Zt(s,n,t,"floor")!==e)throw new Error(`Use at most ${n} decimal places for this delivered token.`);return s}function up(e){return`0x77${e.slice(4)}`}function Ir({userAddress:e,destinationChainId:t,deliveryToken:n,deliveryAmount:s,withdrawalAmount:r,deliveryRecipient:o,deliveryTransfers:a,requestTimestampMs:i,expiresAt:l,metadata:u,requestNonce:m}){if(l!==void 0&&(!Number.isSafeInteger(l)||l<=0))throw new Error("Withdrawal expiry must be a positive Unix timestamp in seconds");const f=a?.length?a:[{token:n,recipient:o,amount:r??s}],h=f.reduce((b,k)=>b+k.amount,0n);if(h<=0n)return null;const y=i??Date.now(),g=BigInt(Math.floor(y/1e3)),x=e??o,w=up(N.keccak256(N.encodeAbiParameters([{type:"address"},{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"},...m?[{type:"bytes32"}]:[]],[x,n,o,h,BigInt(t),BigInt(y),...m?[m]:[]])));return{chainId:R.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:[{to:R.ZERO_ADDRESS,value:0n,data:N.encodeFunctionData({abi:R.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${t}`,idempotenceKey:w,nbf:0n,exp:l===void 0?g+3600n:BigInt(l),metadata:u??"{}",transfers:f.map(b=>({token:N.getAddress(b.token).toLowerCase(),to:N.getAddress(b.recipient).toLowerCase(),amount:b.amount}))}]})}]}}const wa=e=>{const[t,n]=p.useState(!1),s=p.useContext(d.SpiceFlowProviderContext),{dark:r,dk:o}=d.useSpiceBrand();if(p.useEffect(()=>{n(!0)},[]),!t)return c.jsx("div",{className:e.className,children:c.jsx("button",{disabled:!0,style:{padding:"12px 24px",fontSize:"16px",backgroundColor:r?o.hoverBg:"#ccc",color:r?o.textSecondary:"white",border:r?`1px solid ${o.buttonBorder}`:"none",borderRadius:"4px",cursor:"not-allowed"},children:"Loading..."})});if(!s){const a='ProviderLogin must be used within SpiceFlowProvider. Please wrap your app with <SpiceFlowProvider provider="privy">.';return c.jsx("div",{className:e.className,children:c.jsx("button",{onClick:()=>{e.onAuthError&&e.onAuthError(a)},style:{padding:"12px 24px",fontSize:"16px",backgroundColor:r?o.errorBg:"#dc2626",color:r?o.errorText:"white",border:r?`1px solid ${o.errorBorder}`:"none",borderRadius:"4px",cursor:"pointer"},children:"Provider Not Found"})})}return c.jsx(d.PrivyLogin,{...e})},Ar=({size:e=20,strokeWidth:t=2,color:n="currentColor",style:s})=>c.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:s,children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),Er=(e,t,n,s)=>({width:e,height:e,fill:"none",className:t,"aria-hidden":n??!0,style:s}),Zs=({size:e=16,color:t="currentColor",strokeWidth:n=2,direction:s="down",className:r,style:o,"aria-hidden":a})=>c.jsx("svg",{...Er(e,r,a,{transform:s==="up"?"rotate(180deg)":void 0,transition:"transform 0.3s ease",...o}),viewBox:"0 0 16 16",children:c.jsx("path",{d:"M4 6L8 10L12 6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),pp=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:s,style:r,"aria-hidden":o})=>c.jsxs("svg",{...Er(e,s,o,r),viewBox:"0 0 24 24",children:[c.jsx("circle",{cx:"11",cy:"11",r:"8",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"}),c.jsx("path",{d:"m21 21-4.3-4.3",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})]}),fp=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:s,style:r,"aria-hidden":o})=>c.jsx("svg",{...Er(e,s,o,r),viewBox:"0 0 24 24",children:c.jsx("path",{d:"m6 9 6 6 6-6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),mp=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:s,style:r,"aria-hidden":o})=>c.jsx("svg",{...Er(e,s,o,r),viewBox:"0 0 24 24",children:c.jsx("path",{d:"m9 18 6-6-6-6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),Nc=({size:e=14,color:t="currentColor",strokeWidth:n=2,className:s,style:r,"aria-hidden":o})=>c.jsx("svg",{...Er(e,s,o,r),viewBox:"0 0 16 16",children:c.jsx("path",{d:"M3 8L6.5 11.5L13 5",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),Mc=({isSuccess:e,type:t,chainName:n,explorerUrl:s,txHash:r,dark:o=!1,successBg:a="#d1fae5",successBorder:i="#6ee7b7",successText:l="#065f46",errorBg:u="#fee2e2",errorBorder:m="#fca5a5",errorText:f="#dc2626",textSecondary:h="#6b7280"})=>c.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px",borderRadius:"8px",backgroundColor:e?a:u,border:e?`1px solid ${i}`:`1px solid ${m}`},children:[c.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[c.jsx("div",{style:{width:"28px",height:"28px",borderRadius:"50%",backgroundColor:e?"#10b981":"#ef4444",display:"flex",alignItems:"center",justifyContent:"center"},children:e?c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:c.jsx("path",{d:"M11.6667 3.5L5.25 9.91667L2.33333 7",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}):c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:c.jsx("path",{d:"M10.5 3.5L3.5 10.5M3.5 3.5L10.5 10.5",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),c.jsxs("div",{children:[c.jsx("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:d.font.mono,letterSpacing:"0.5px",color:e?l:f},children:e?`${t.toUpperCase()} CONFIRMED`:`${t.toUpperCase()} FAILED`}),c.jsxs("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:h},children:["on ",n]})]})]}),s&&r&&c.jsxs("a",{href:`${s}/tx/${r}`,target:"_blank",rel:"noopener noreferrer",style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"13px",color:h,textDecoration:"none",whiteSpace:"nowrap"},children:["View on explorer",c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:[c.jsx("path",{d:"M9 6.5V9.5C9 9.76522 8.89464 10.0196 8.70711 10.2071C8.51957 10.3946 8.26522 10.5 8 10.5H2.5C2.23478 10.5 1.98043 10.3946 1.79289 10.2071C1.60536 10.0196 1.5 9.76522 1.5 9.5V4C1.5 3.73478 1.60536 3.48043 1.79289 3.29289C1.98043 3.10536 2.23478 3 2.5 3H5.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),c.jsx("path",{d:"M7.5 1.5H10.5V4.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),c.jsx("path",{d:"M5 7L10.5 1.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})]})]})]}),Pc=`
2
+ "use strict";var Nd=Object.create;var Ci=Object.defineProperty;var Md=Object.getOwnPropertyDescriptor;var Pd=Object.getOwnPropertyNames;var Ud=Object.getPrototypeOf,Wd=Object.prototype.hasOwnProperty;var qd=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Pd(t))!Wd.call(e,r)&&r!==n&&Ci(e,r,{get:()=>t[r],enumerable:!(s=Md(t,r))||s.enumerable});return e};var Ld=(e,t,n)=>(n=e!=null?Nd(Ud(e)):{},qd(t||!e||!e.__esModule?Ci(n,"default",{value:e,enumerable:!0}):n,e));const c=require("react/jsx-runtime"),d=require("./privy-B9_DLG_6.cjs"),p=require("react"),R=require("@spicenet-io/spiceflow-core"),ns=require("wagmi"),N=require("viem"),Vn=require("viem/actions"),pr=require("@privy-io/react-auth"),fr=require("react-dom");require("@tanstack/react-query");const zd="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@100;200;300;400;500;600;700&display=swap",Hd="spiceflow-ibm-plex-mono",Vd="spiceflow-preconnect-googleapis",Qd="spiceflow-preconnect-gstatic";function qo(e,t){if(document.getElementById(e))return;const n=t();n.id=e,document.head.appendChild(n)}function Gd(){typeof document>"u"||(qo(Vd,()=>{const e=document.createElement("link");return e.rel="preconnect",e.href="https://fonts.googleapis.com",e}),qo(Qd,()=>{const e=document.createElement("link");return e.rel="preconnect",e.href="https://fonts.gstatic.com",e.crossOrigin="",e}),qo(Hd,()=>{const e=document.createElement("link");return e.rel="stylesheet",e.href=zd,e}))}const Kd={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",8453:"0x4200000000000000000000000000000000000006",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",84532:"0x4200000000000000000000000000000000000006"},ki=N.parseAbi(["function deposit() payable","function withdraw(uint256 wad)"]);function Lo(e){return d.getChainConfig(e)?.wrappedNativeTokenAddress??Kd[e]}const zo=(e,t)=>({to:e,value:t,data:N.encodeFunctionData({abi:ki,functionName:"deposit"})}),Ho=(e,t)=>({to:e,value:0n,data:N.encodeFunctionData({abi:ki,functionName:"withdraw",args:[t]})});function Vo(e,t,n){const s=R.isNativeToken(t),r=R.isNativeToken(n);if(!s&&!r)return null;const o=Lo(e);return o?{weth:o,wrapIn:s,unwrapOut:r}:null}function Si(e,t,n,s){const r=Vo(e,t,n);return!r||s<=0n?null:r.wrapIn&&!r.unwrapOut&&n.toLowerCase()===r.weth.toLowerCase()?[zo(r.weth,s)]:r.unwrapOut&&!r.wrapIn&&t.toLowerCase()===r.weth.toLowerCase()?[Ho(r.weth,s)]:null}function Yd(e){return{...e,resolve:async(t,n,s,r)=>{const o=Si(n,t.tokenIn,t.tokenOut,t.amountIn);if(o)return{venue:"native-wrap",amountOut:t.amountIn,amountOutMinimum:t.amountIn,calls:o};const a=await e.resolve(t,n,s,r);if(a)return a;const i=Vo(n,t.tokenIn,t.tokenOut);if(!i)return null;const l=await e.resolve({...t,tokenIn:i.wrapIn?i.weth:t.tokenIn,tokenOut:i.unwrapOut?i.weth:t.tokenOut},n,s,r);return l?{...l,calls:[...i.wrapIn?[zo(i.weth,t.amountIn)]:[],...l.calls,...i.unwrapOut?[Ho(i.weth,l.amountOutMinimum)]:[]]}:null}}}function Zd(e){return{...e,resolve:async(t,n,s)=>{const r=Si(n,t.tokenIn,t.tokenOut,t.amountOut);if(r)return{venue:"native-wrap",amountIn:t.amountOut,amountInMax:t.amountOut,amountOut:t.amountOut,calls:r};const o=await e.resolve(t,n,s);if(o)return o;const a=Vo(n,t.tokenIn,t.tokenOut);if(!a)return null;const i=await e.resolve({...t,tokenIn:a.wrapIn?a.weth:t.tokenIn,tokenOut:a.unwrapOut?a.weth:t.tokenOut},n,s);return i?{...i,calls:[...a.wrapIn?[zo(a.weth,i.amountInMax)]:[],...i.calls,...a.unwrapOut?[Ho(a.weth,i.amountOut)]:[]]}:null}}}const Ii=[100,500,3e3,1e4];function Zr(e,t,n,s,r){const o=[];for(const a of n){const i=typeof a=="object"&&!Array.isArray(a)?a:void 0,l=i?i.tokens:Array.isArray(a)?a:[a];if(!l.length||l.length>2)throw new Error("A v3 route must have one or two intermediate tokens");const u=[e,...l,t];if(i&&(i.feeTiers.length!==u.length-1||i.feeTiers.some(f=>!f.length)))throw new Error("A v3 route needs fee tiers for every pool");if(new Set(u.map(f=>f.toLowerCase())).size!==u.length)continue;const m=(f,h)=>{if(f===u.length){o.push(r==="in"?h:Ai(h));return}for(const y of i?.feeTiers[f-1]??s)m(f+1,N.concatHex([h,N.encodePacked(["uint24","address"],[y,u[f]])]))};m(1,u[0])}return[...new Set(o)]}function Ai(e){const t=e.slice(2),n=[];for(let s=0;s<t.length;){const r=n.length%2===0?40:6;n.push(t.slice(s,s+r)),s+=r}return`0x${n.reverse().join("")}`}const Xd=N.parseAbi(["function exactOutputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 amountOut, uint256 amountInMaximum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountIn)","function exactOutput((bytes path, address recipient, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),Jd=N.parseAbi(["function exactOutputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountIn)","function exactOutput((bytes path, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),$d=1800;function Ei(e){const{config:t,route:n,tokenIn:s,tokenOut:r,recipient:o,amountOut:a}=e,i=e.amountInMaximum,l=e.routerHasDeadline?Jd:Xd,u=e.routerHasDeadline?{deadline:BigInt(Math.floor(Date.now()/1e3)+$d)}:{},m=n.path?N.encodeFunctionData({abi:l,functionName:"exactOutput",args:[{path:n.path,recipient:o,...u,amountOut:a,amountInMaximum:i}]}):N.encodeFunctionData({abi:l,functionName:"exactOutputSingle",args:[{tokenIn:s,tokenOut:r,fee:n.fee,recipient:o,...u,amountOut:a,amountInMaximum:i,sqrtPriceLimitX96:0n}]});return{to:t.swapRouter,value:0n,data:m}}const _d=N.parseAbi(["function quoteExactInput(bytes path, uint256 amountIn) returns (uint256 amountOut, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate)","function quoteExactOutput(bytes path, uint256 amountOut) returns (uint256 amountIn, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate)"]);async function mr(e,t,n,s,r){const o=d.getClientForChain(e),{result:a}=await o.simulateContract({address:t.quoterV2,abi:_d,functionName:r==="in"?"quoteExactInput":"quoteExactOutput",args:[n,s]}),[i,,,l]=a;if(i<=0n)throw new Error("No liquidity along this path.");return{amount:i,gasEstimate:l}}async function eu(e){const{tokenIn:t,tokenOut:n,amountIn:s,fee:r,chainId:o,config:a}=e;if(s<=0n)throw new Error("amountIn must be greater than 0");const i=(await d.getClientForChain(o).simulateContract({address:a.quoterV2,abi:R.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:s,fee:r,sqrtPriceLimitX96:0n}]})).result;if(i[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:i[0],sqrtPriceX96After:i[1],gasEstimate:i[3]}}async function Fi(e){const t=e.feeTiers??Ii,n=Zr(e.tokenIn,e.tokenOut,e.hubs??[],t,"in"),s=await Promise.allSettled([...t.map(async o=>({...await eu({...e,fee:o}),fee:o})),...n.map(async o=>{const a=await mr(e.chainId,e.config,o,e.amountIn,"in");return{amountOut:a.amount,sqrtPriceX96After:0n,gasEstimate:a.gasEstimate,fee:0,path:o}})]);let r=null;for(const o of s)o.status==="fulfilled"&&(!r||o.value.amountOut>r.amountOut)&&(r=o.value);if(!r)throw new Error("No liquidity found for this pair on any fee tier.");return r}const tu=[{inputs:[{components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"amount",type:"uint256"},{name:"fee",type:"uint24"},{name:"sqrtPriceLimitX96",type:"uint160"}],name:"params",type:"tuple"}],name:"quoteExactOutputSingle",outputs:[{name:"amountIn",type:"uint256"},{name:"sqrtPriceX96After",type:"uint160"},{name:"initializedTicksCrossed",type:"uint32"},{name:"gasEstimate",type:"uint256"}],stateMutability:"nonpayable",type:"function"}];async function nu(e){const{tokenIn:t,tokenOut:n,amountOut:s,fee:r,chainId:o,config:a}=e;if(s<=0n)throw new Error("amountOut must be greater than 0");const i=(await d.getClientForChain(o).simulateContract({address:a.quoterV2,abi:tu,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:s,fee:r,sqrtPriceLimitX96:0n}]})).result;if(i[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:i[0],sqrtPriceX96After:i[1],gasEstimate:i[3]}}async function Ti(e){const t=e.feeTiers??Ii,n=Zr(e.tokenIn,e.tokenOut,e.hubs??[],t,"out"),s=await Promise.allSettled([...t.map(async o=>({...await nu({...e,fee:o}),fee:o})),...n.map(async o=>{const a=await mr(e.chainId,e.config,o,e.amountOut,"out");return{amountIn:a.amount,sqrtPriceX96After:0n,gasEstimate:a.gasEstimate,fee:0,path:o}})]);let r=null;for(const o of s)o.status==="fulfilled"&&(!r||o.value.amountIn<r.amountIn)&&(r=o.value);if(!r)throw new Error("No liquidity found for this pair on any fee tier.");return r}function su(e){return e.type==="swap"}const hr=.02,ru=[1,8453,42161,10,137,43114,56],ou="https://api.1inch.dev/swap/v6.0";function Qo(e,t){return R.applySlippage(e,t)}function au(e){const t=e?.baseUrl??ou;return{name:"1inch",chainIds:e?.chainIds??ru,resolve:async(n,s,r)=>{const o=n.maxSlippage??hr,a=o*100,i=R.isNativeToken(n.tokenIn)?R.NATIVE_TOKEN_ADDRESS:n.tokenIn,l=R.isNativeToken(n.tokenOut)?R.NATIVE_TOKEN_ADDRESS:n.tokenOut,u=R.isNativeToken(n.tokenIn);try{const m=new URL(`${t}/${s}/swap`);m.searchParams.set("src",i),m.searchParams.set("dst",l),m.searchParams.set("amount",n.amountIn.toString()),m.searchParams.set("from",r),m.searchParams.set("slippage",a.toString()),m.searchParams.set("disableEstimate","true"),m.searchParams.set("allowPartialFill","false");const f={Accept:"application/json"};e?.apiKey&&(f.Authorization=`Bearer ${e.apiKey}`);const h=await fetch(m.toString(),{headers:f});if(!h.ok)throw new d.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${h.status} for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:`HTTP ${h.status}`});const y=await h.json();if(!y.dstAmount||!y.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const g=BigInt(y.dstAmount);if(g<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const x=Qo(g,o),w=[];return y.tx.to&&!u&&w.push({to:n.tokenIn,value:0n,data:N.encodeFunctionData({abi:N.erc20Abi,functionName:"approve",args:[y.tx.to,n.amountIn]})}),w.push({to:y.tx.to,value:BigInt(y.tx.value||"0"),data:y.tx.data}),{venue:"1inch",amountOut:g,amountOutMinimum:x,calls:w}}catch(m){if(m instanceof d.SpiceflowError)throw m;const f=m instanceof Error?m.message:String(m);throw new d.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}: ${f}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:f})}}}}const Ri=[4114,5115],Go={name:"Satsuma",swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},Bi={name:"Uniswap v3",swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x4200000000000000000000000000000000000006","0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]},Oi={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[1],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2","0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"]},ji={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[42161],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x82aF49447D8a07e3bd95BD0d56f35241523fBab1","0xaf88d065e77c8cC2239327C5EDb3A432268e5831"]},iu={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[137],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270","0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"]},cu={name:"Uniswap v3",swapRouter:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",quoterV2:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",chainIds:[56],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c","0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d"]},lu={name:"Uniswap v3",swapRouter:"0xfe31f71c1b106eac32f1a19239c9a9a72ddfb900",quoterV2:"0x661e93cca42afacb172121ef892830ca3b70f08d",chainIds:[143],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A","0x754704Bc059F8C67012fEd69BC8A327a5aafb603"]},Di={name:"Uniswap v3",swapRouter:"0xcaf681a66d020601342297493863e78c959e5cb2",quoterV2:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",chainIds:[4663],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73","0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"]},Ni={name:"SushiSwap",swapRouter:"0x1e406484F1F204b23cE84B9901C0171a738fd406",quoterV2:"0x3E290e5E01818002A0b672148BdC7514D861C7B3",chainIds:[4663],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73","0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"],routerHasDeadline:!0},Mi=N.parseAbi(["function exactInput((bytes path, address recipient, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),Pi=N.parseAbi(["function exactInputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)","function exactInput((bytes path, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),du=N.parseAbi(["function exactInput((bytes path, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),uu=N.parseAbi(["function exactOutput((bytes path, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),Ko=1800,Ui=[1,50,100,200,2e3],Xr={name:"Aerodrome",swapRouter:"0xcbBb8035cAc7D4B3Ca7aBb74cF7BdF900215Ce0D",quoterV2:"0x3d4C22254F86f64B7eC90ab8F7aeC1FBFD271c6C",chainIds:[8453],hubCurrencies:["0x4200000000000000000000000000000000000006","0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]};function gr(e){const t=e.name??"Aerodrome",n=e.chainIds??[8453],s=e.tickSpacings??Ui;return{name:t,chainIds:n,resolve:async(r,o,a)=>{if(R.isNativeToken(r.tokenIn)||R.isNativeToken(r.tokenOut))return null;const i=r.maxSlippage??hr,l=[...s.map(w=>N.encodePacked(["address","uint24","address"],[r.tokenIn,w,r.tokenOut])),...Zr(r.tokenIn,r.tokenOut,e.hubCurrencies??[],s,"in")],u={quoterV2:e.quoterV2},m=await Promise.allSettled(l.map(async w=>({path:w,amountOut:(await mr(o,u,w,r.amountIn,"in")).amount})));let f=null;for(const w of m)w.status==="fulfilled"&&(!f||w.value.amountOut>f.amountOut)&&(f=w.value);if(!f)return console.warn(`[AerodromeVenue] No viable route for ${r.tokenIn} \u2192 ${r.tokenOut} on chain ${o}.`),null;const h=Qo(f.amountOut,i),y=e.deadline??BigInt(Math.floor(Date.now()/1e3)+Ko),g=N.encodeFunctionData({abi:du,functionName:"exactInput",args:[{path:f.path,recipient:a,deadline:y,amountIn:r.amountIn,amountOutMinimum:h}]}),x=[{to:r.tokenIn,value:0n,data:N.encodeFunctionData({abi:N.erc20Abi,functionName:"approve",args:[e.swapRouter,r.amountIn]})},{to:e.swapRouter,value:0n,data:g}];return{venue:t,amountOut:f.amountOut,amountOutMinimum:h,calls:x}}}}function Wi(e){const t=e.name??"Aerodrome",n=e.chainIds??[8453],s=e.tickSpacings??Ui;return{name:t,chainIds:n,resolve:async(r,o,a)=>{if(R.isNativeToken(r.tokenIn)||R.isNativeToken(r.tokenOut))return null;const i=r.maxSlippage??hr,l=[...s.map(x=>N.encodePacked(["address","uint24","address"],[r.tokenOut,x,r.tokenIn])),...Zr(r.tokenIn,r.tokenOut,e.hubCurrencies??[],s,"out")],u={quoterV2:e.quoterV2},m=await Promise.allSettled(l.map(async x=>({path:x,amountIn:(await mr(o,u,x,r.amountOut,"out")).amount})));let f=null;for(const x of m)x.status==="fulfilled"&&(!f||x.value.amountIn<f.amountIn)&&(f=x.value);if(!f)return console.warn(`[AerodromeExactOutputVenue] No viable route for ${r.tokenIn} \u2192 ${r.tokenOut} on chain ${o}.`),null;const h=BigInt(Math.round(i*1e4)),y=f.amountIn+f.amountIn*h/10000n,g=e.deadline??BigInt(Math.floor(Date.now()/1e3)+Ko);return{venue:t,amountIn:f.amountIn,amountInMax:y,amountOut:r.amountOut,calls:[{to:e.swapRouter,value:0n,data:N.encodeFunctionData({abi:uu,functionName:"exactOutput",args:[{path:f.path,recipient:a,deadline:g,amountOut:r.amountOut,amountInMaximum:y}]})}]}}}}function wr(e){const t=e.name??"Uniswap v3",n=e.chainIds??Ri;return{name:t,chainIds:n,resolve:async(s,r,o,a)=>{if(R.isNativeToken(s.tokenIn)||R.isNativeToken(s.tokenOut))return null;const i=s.maxSlippage??hr;let l;try{let g;if(a){if(a.venue!==t)return null;const x=a.calls.find(b=>b.to.toLowerCase()===e.swapRouter.toLowerCase());if(!x)return null;const w=N.decodeFunctionData({abi:e.routerHasDeadline?Pi:[...Mi,...R.uniV3SwapRouterAbi],data:x.data});if(w.functionName==="exactInput"){const{path:b}=w.args[0];if(b.slice(0,42).toLowerCase()!==s.tokenIn.toLowerCase()||`0x${b.slice(-40)}`.toLowerCase()!==s.tokenOut.toLowerCase())return null;g={path:b,fee:0}}else if(w.functionName==="exactInputSingle"){const{tokenIn:b,tokenOut:k,fee:A}=w.args[0];if(b.toLowerCase()!==s.tokenIn.toLowerCase()||k.toLowerCase()!==s.tokenOut.toLowerCase())return null;g={fee:A}}else return null}l=g?.path?{...g,amountOut:(await mr(r,e,g.path,s.amountIn,"in")).amount}:await Fi({tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn,chainId:r,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:g?[g.fee]:e.feeTiers,hubs:g?[]:[...e.hubCurrencies??[],...e.hubPaths??[]]})}catch{return console.warn(`[UniV3Venue] No viable route for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${r}.`),null}const u=Qo(l.amountOut,i),m=e.routerHasDeadline?{deadline:BigInt(Math.floor(Date.now()/1e3)+Ko)}:{},f=e.routerHasDeadline?Pi:l.path?Mi:R.uniV3SwapRouterAbi,h=l.path?N.encodeFunctionData({abi:f,functionName:"exactInput",args:[{path:l.path,recipient:o,...m,amountIn:s.amountIn,amountOutMinimum:u}]}):N.encodeFunctionData({abi:f,functionName:"exactInputSingle",args:[{tokenIn:s.tokenIn,tokenOut:s.tokenOut,fee:l.fee,recipient:o,...m,amountIn:s.amountIn,amountOutMinimum:u,sqrtPriceLimitX96:0n}]}),y=[{to:s.tokenIn,value:0n,data:N.encodeFunctionData({abi:N.erc20Abi,functionName:"approve",args:[e.swapRouter,s.amountIn]})},{to:e.swapRouter,value:0n,data:h}];return{venue:t,amountOut:l.amountOut,amountOutMinimum:u,calls:y}}}}function Yo(e){const t=e.name??"Uniswap v3",n=e.chainIds??Ri;return{name:t,chainIds:n,resolve:async(s,r,o)=>{if(R.isNativeToken(s.tokenIn)||R.isNativeToken(s.tokenOut))return null;const a=s.maxSlippage??hr;let i;try{i=await Ti({tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountOut:s.amountOut,chainId:r,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers,hubs:[...e.hubCurrencies??[],...e.hubPaths??[]]})}catch{return null}const l=BigInt(Math.round(a*1e4)),u=i.amountIn+i.amountIn*l/10000n;return{venue:t,amountIn:i.amountIn,amountInMax:u,amountOut:s.amountOut,calls:[Ei({config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},routerHasDeadline:e.routerHasDeadline,route:i,tokenIn:s.tokenIn,tokenOut:s.tokenOut,recipient:o,amountOut:s.amountOut,amountInMaximum:u})]}}}}function qi(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(wr(e.satsuma)),e?.aerodrome!==!1&&t.push(gr(e?.aerodrome??Xr)),t.push(au(e?.oneInch));const n=t.map(Yd);function s(a){return n.find(i=>i.chainIds.includes(a))}async function r(a,i,l,u){const m=n.filter(g=>g.chainIds.includes(i));if(m.length===0)throw new d.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${i}. Cannot resolve swap ${a.tokenIn} \u2192 ${a.tokenOut}.`,{chainId:i,tokenIn:a.tokenIn,tokenOut:a.tokenOut,amountIn:a.amountIn.toString()});const f=await Promise.allSettled(m.map(g=>g.resolve(a,i,l,u)));let h=null;for(const g of f)u&&g.status==="fulfilled"&&g.value&&(g.value.venue!==u.venue||g.value.calls.length!==u.calls.length||g.value.calls.some((x,w)=>x.to.toLowerCase()!==u.calls[w].to.toLowerCase()||x.data.slice(0,10)!==u.calls[w].data.slice(0,10)))||g.status==="fulfilled"&&g.value&&(!h||g.value.amountOut>h.amountOut)&&(h=g.value);if(h)return h;const y=f.find(g=>g.status==="rejected");if(y)throw y.reason;return null}async function o(a,i,l){const u=[],m=[];for(const f of a){if(!su(f)){u.push(f);continue}const h=await r(f,i,l);if(!h)throw new d.SpiceflowError("NO_LIQUIDITY",`No venue returned a quote for ${f.tokenIn} \u2192 ${f.tokenOut} on chain ${i}.`,{chainId:i,tokenIn:f.tokenIn,tokenOut:f.tokenOut,amountIn:f.amountIn.toString()});u.push(...h.calls),m.push(h)}return{calls:u,resolvedSwaps:m}}return{resolveSwapIntents:o,resolveSwap:r,getVenueForChain:s,venues:t}}const Xn="0x0000000000000000000000000000000000000000",Zo=[{fee:100,tickSpacing:1},{fee:500,tickSpacing:10},{fee:3e3,tickSpacing:60},{fee:1e4,tickSpacing:200}],Li=Xn,zi=.02,pu=1800,Hi={name:"Uniswap v4",quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",universalRouter:"0x6ff5693b99212da76ad316178a184ab56d299b43",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",chainIds:[8453],hubCurrencies:["0x4200000000000000000000000000000000000006",Xn,"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]},Vi={name:"Uniswap v4",quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",universalRouter:"0x8876789976decbfcbbbe364623c63652db8c0904",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",routerHasHopPrice:!0,chainIds:[4663],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73",Xn,"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"]},Qi=N.parseAbi(["struct PoolKey { address currency0; address currency1; uint24 fee; int24 tickSpacing; address hooks; }","struct PathKey { address intermediateCurrency; uint24 fee; int24 tickSpacing; address hooks; bytes hookData; }","struct QuoteExactSingleParams { PoolKey poolKey; bool zeroForOne; uint128 exactAmount; bytes hookData; }","struct QuoteExactParams { address exactCurrency; PathKey[] path; uint128 exactAmount; }","function quoteExactInputSingle(QuoteExactSingleParams params) returns (uint256 amountOut, uint256 gasEstimate)","function quoteExactInput(QuoteExactParams params) returns (uint256 amountOut, uint256 gasEstimate)","function quoteExactOutputSingle(QuoteExactSingleParams params) returns (uint256 amountIn, uint256 gasEstimate)","function quoteExactOutput(QuoteExactParams params) returns (uint256 amountIn, uint256 gasEstimate)"]),fu=N.parseAbi(["function approve(address token, address spender, uint160 amount, uint48 expiration)"]),mu=N.parseAbi(["function execute(bytes commands, bytes[] inputs, uint256 deadline) payable"]),Gi="0x10",hu="04",gu="06",wu="07",xu="08",yu="09",Jr="0c",$r="0e",bu=[{name:"currency0",type:"address"},{name:"currency1",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"}],vu=[{name:"intermediateCurrency",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"},{name:"hookData",type:"bytes"}],ss=(e,t)=>e.toLowerCase()===t.toLowerCase();function _r(e){return R.isNativeToken(e)?Xn:e}function Cu(e,t){return e.toLowerCase()<t.toLowerCase()?[e,t]:[t,e]}function Ki(e,t,n,s,r){const o=[],[a,i]=Cu(e,t);for(const{fee:u,tickSpacing:m}of Zo)o.push({kind:"single",poolKey:{currency0:a,currency1:i,fee:u,tickSpacing:m,hooks:Li},zeroForOne:ss(e,a)});const l=(u,m)=>!!r&&(ss(u,Xn)&&ss(m,r)||ss(u,r)&&ss(m,Xn));for(const u of n)if(!(ss(u,e)||ss(u,t))&&!(l(u,e)||l(u,t)))for(const m of Zo)for(const f of Zo){const h=(y,g)=>({intermediateCurrency:y,fee:g.fee,tickSpacing:g.tickSpacing,hooks:Li,hookData:"0x"});o.push({kind:"multi",path:s==="in"?[h(u,m),h(t,f)]:[h(e,m),h(u,f)]})}return o}async function Yi(e,t,n,s,r,o){const a=d.getClientForChain(e),i=(await Promise.allSettled(n.map(async l=>{const{result:u}=l.kind==="single"?await a.simulateContract({address:t.quoter,abi:Qi,functionName:o==="in"?"quoteExactInputSingle":"quoteExactOutputSingle",args:[{poolKey:l.poolKey,zeroForOne:l.zeroForOne,exactAmount:r,hookData:"0x"}]}):await a.simulateContract({address:t.quoter,abi:Qi,functionName:o==="in"?"quoteExactInput":"quoteExactOutput",args:[{exactCurrency:s,path:l.path,exactAmount:r}]}),m=u[0];if(m<=0n)throw new Error("zero quote");return{candidate:l,amount:m}}))).filter(l=>l.status==="fulfilled").map(l=>l.value);return i.length===0?null:(i.sort((l,u)=>l.amount<u.amount?-1:l.amount>u.amount?1:0),o==="in"?i[i.length-1]:i[0])}function Zi(e){const{candidate:t,direction:n,currencyIn:s,currencyOut:r,recipient:o,exactAmount:a,limitAmount:i,deadline:l,routerHasHopPrice:u,sweepNativeTo:m}=e;let f,h;t.kind==="single"?(f=n==="in"?`0x${gu}${Jr}${$r}`:`0x${xu}${Jr}${$r}`,h=N.encodeAbiParameters([{type:"tuple",components:[{name:"poolKey",type:"tuple",components:bu},{name:"zeroForOne",type:"bool"},{name:n==="in"?"amountIn":"amountOut",type:"uint128"},{name:n==="in"?"amountOutMinimum":"amountInMaximum",type:"uint128"},...u?[{name:"minHopPriceX36",type:"uint256"}]:[],{name:"hookData",type:"bytes"}]}],[{poolKey:t.poolKey,zeroForOne:t.zeroForOne,[n==="in"?"amountIn":"amountOut"]:a,[n==="in"?"amountOutMinimum":"amountInMaximum"]:i,...u?{minHopPriceX36:0n}:{},hookData:"0x"}])):(f=n==="in"?`0x${wu}${Jr}${$r}`:`0x${yu}${Jr}${$r}`,h=N.encodeAbiParameters([{type:"tuple",components:[{name:n==="in"?"currencyIn":"currencyOut",type:"address"},{name:"path",type:"tuple[]",components:vu},...u?[{name:"minHopPriceX36",type:"uint256[]"}]:[],{name:n==="in"?"amountIn":"amountOut",type:"uint128"},{name:n==="in"?"amountOutMinimum":"amountInMaximum",type:"uint128"}]}],[{[n==="in"?"currencyIn":"currencyOut"]:n==="in"?s:r,path:t.path,...u?{minHopPriceX36:[]}:{},[n==="in"?"amountIn":"amountOut"]:a,[n==="in"?"amountOutMinimum":"amountInMaximum"]:i}]));const y=N.encodeAbiParameters([{type:"address"},{type:"uint256"}],[s,n==="in"?a:i]),g=N.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"}],[r,o,0n]),x=N.encodeAbiParameters([{type:"bytes"},{type:"bytes[]"}],[f,[h,y,g]]),w=m?`${Gi}${hu}`:Gi,b=m?[x,N.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"}],[Xn,m,0n])]:[x];return N.encodeFunctionData({abi:mu,functionName:"execute",args:[w,b,l]})}function Xi(){return BigInt(Math.floor(Date.now()/1e3)+pu)}function Ji(e,t,n,s){return{to:e.permit2,value:0n,data:N.encodeFunctionData({abi:fu,functionName:"approve",args:[t,e.universalRouter,n,Number(s)]})}}function $i(e){const t=e.name??"Uniswap v4",n=e.v3?wr({...e.v3,chainIds:e.chainIds}):null;return{name:t,chainIds:e.chainIds,resolve:async(s,r,o)=>{const a=s.maxSlippage??zi,i=_r(s.tokenIn),l=_r(s.tokenOut),u=R.isNativeToken(s.tokenIn),m=e.hubCurrencies??[Xn];let f=null;if(!ss(i,l)&&s.amountIn>0n){const h=await Yi(r,e,Ki(i,l,m,"in",Lo(r)),i,s.amountIn,"in").catch(()=>null);if(h){const y=R.applySlippage(h.amount,a),g=Xi(),x=[];u||(x.push({to:s.tokenIn,value:0n,data:N.encodeFunctionData({abi:N.erc20Abi,functionName:"approve",args:[e.permit2,s.amountIn]})}),x.push(Ji(e,s.tokenIn,s.amountIn,g))),x.push({to:e.universalRouter,value:u?s.amountIn:0n,data:Zi({candidate:h.candidate,direction:"in",currencyIn:i,currencyOut:l,recipient:o,exactAmount:s.amountIn,limitAmount:y,deadline:g,routerHasHopPrice:e.routerHasHopPrice})}),f={venue:t,amountOut:h.amount,amountOutMinimum:y,calls:x}}}return!f&&n?n.resolve(s,r,o):f}}}function _i(e){const t=e.name??"Uniswap v4";return{name:t,chainIds:e.chainIds,resolve:async(n,s,r)=>{const o=R.isNativeToken(n.tokenIn),a=_r(n.tokenIn),i=_r(n.tokenOut);if(ss(a,i)||n.amountOut<=0n)return null;const l=n.maxSlippage??zi,u=e.hubCurrencies??[Xn],m=await Yi(s,e,Ki(a,i,u,"out",Lo(s)),i,n.amountOut,"out").catch(()=>null);if(!m)return null;const f=BigInt(Math.round(l*1e4)),h=m.amount+m.amount*f/10000n,y=Xi();return{venue:t,amountIn:m.amount,amountInMax:h,amountOut:n.amountOut,calls:[...o?[]:[Ji(e,n.tokenIn,h,y)],{to:e.universalRouter,value:o?h:0n,data:Zi({candidate:m.candidate,direction:"out",currencyIn:a,currencyOut:i,recipient:r,exactAmount:n.amountOut,limitAmount:h,deadline:y,routerHasHopPrice:e.routerHasHopPrice,sweepNativeTo:o?r:void 0})}]}}}}const Xo=[{...Go,protocol:"uniswap-v3",chainId:4114},{...Go,protocol:"uniswap-v3",chainId:5115},{...Bi,protocol:"uniswap-v3",chainId:8453},{...Oi,protocol:"uniswap-v3",chainId:1},{...ji,protocol:"uniswap-v3",chainId:42161},{...iu,protocol:"uniswap-v3",chainId:137},{...cu,protocol:"uniswap-v3",chainId:56},{...lu,protocol:"uniswap-v3",chainId:143},{...Di,protocol:"uniswap-v3",chainId:4663},{...Ni,protocol:"uniswap-v3",chainId:4663},{...Hi,protocol:"uniswap-v4",chainId:8453},{...Vi,protocol:"uniswap-v4",chainId:4663},{...Xr,protocol:"aerodrome-slipstream",chainId:8453}];function Fs(e){const t=e?.includeDefaults===!1?e.venues??[]:[...Xo,...e?.venues??[]],n=[],s=[];for(const r of t){const o=[r.chainId];switch(r.protocol){case"uniswap-v3":{const a={...r,chainIds:o};n.push(wr(a)),s.push(Yo(a));break}case"uniswap-v4":{const a={...r,chainIds:o};n.push($i(a)),s.push(_i(a));break}case"aerodrome-slipstream":{const a={...r,chainIds:o};n.push(gr(a)),s.push(Wi(a));break}default:{const a=r;throw new d.SpiceflowError("INVALID_PARAMS",`Unsupported liquidity venue protocol: ${a.protocol}`,{protocol:a.protocol})}}}return{input:n,output:s}}const Jo=new Set(["WBTC","CBTC"]),ec=new Set(["btc","wbtc","wcbtc","cbtc"]);function tc(e,t){return!e||!t?!1:e===t?!0:Jo.has(e)&&Jo.has(t)}function kn(e){const[t,n,s]=e.split(":");if(t!=="evm"||!n||!s)return null;const r=Number(n);if(!Number.isFinite(r))return null;const o=s.startsWith("0x")?s.toLowerCase():`0x${s.toLowerCase()}`;return{chainId:r,address:o}}function eo(e){return(e??"").trim().replace(/^test\s+/i,"").replace(/^spice/i,"").toLowerCase().replace(/[^a-z0-9]/g,"")}function ku(e){return new Set([e.receiptTokenName,e.displaySymbol,e.symbol,e.displayName,e.name].map(eo).filter(Boolean))}function Su(e,t){const n=ku(e),s=[t.symbol,t.name,t.equivalenceGroup].map(eo);if(s.some(a=>a&&n.has(a)))return!0;const r=[...n].some(a=>ec.has(a)),o=s.some(a=>ec.has(a))||Jo.has(t.equivalenceGroup??"");return r&&o}function nc(e,t,n){const s=new Set(t.map(eo).filter(Boolean)),r=o=>{if(n&&d.addressesEqual(o.address,n))return 0;const a=[o.symbol,o.name,o.equivalenceGroup].map(eo).findIndex(i=>i&&s.has(i));return a===-1?4:a+1};return[...e].sort((o,a)=>{const i=r(o)-r(a);return i!==0?i:o.address.toLowerCase().localeCompare(a.address.toLowerCase())})}function Vs(e,t){const n=e.chainTokens?Object.keys(e.chainTokens):[],s=[];for(const r of n){const o=kn(r);if(!o||o.chainId!==t)continue;const a=o.address,i=R.isNativeToken(a)?d.getChainConfig(t)?.nativeCurrency:void 0,l=R.getTokenByAddress(a,t)??(i?{...i}:void 0);l&&(!$o(e,a,t)&&!(e.isUniversal&&Su(e,l))||s.some(u=>d.addressesEqual(u,a))||s.push(a))}return nc(s.map(r=>{const o=R.getTokenByAddress(r,t);return{address:r,symbol:o?.symbol,name:o?.name,equivalenceGroup:o?.equivalenceGroup}}),[e.receiptTokenName,e.displaySymbol,e.symbol,e.displayName,e.name],e.chainId===t&&!e.isUniversal?e.address:void 0).map(r=>r.address)}function $o(e,t,n){return e.chainId===n&&d.addressesEqual(e.address,t)?!0:xr(e.address,e.chainId,t,n)}async function Iu(e,t){const n=d.getClientForChain(e),s=R.getEscrowContractAddress(e);return R.isNativeToken(t)?n.getBalance({address:s}):await n.readContract({address:t,abi:N.erc20Abi,functionName:"balanceOf",args:[s]})}function _o(e,t,n){const s=R.getTokensForChain(n),r=s.find(a=>d.addressesEqual(a.address,e));if(r&&(t===n||!R.isNativeToken(e)))return r;const o=R.getTokenByAddress(e,t);if(o)return nc(s.filter(a=>tc(a.equivalenceGroup,o.equivalenceGroup)),[o.symbol,o.name,o.equivalenceGroup])[0]}function to(e){return e.equivalenceGroup==="USDC"&&e.symbol.toUpperCase()!=="USDT"}function Ts(e){const t=R.getEscrowContract(e);if(!t||t===R.ZERO_ADDRESS)return;const n=R.getTokensForChain(e).filter(to);return n.find(s=>s.symbol.toUpperCase()==="USDC")??n[0]}function ea(e,t){if(e.chainId===t)return null;const n=R.getEscrowContract(e.chainId),s=R.getEscrowContract(t);if(!n||n===R.ZERO_ADDRESS||!s||s===R.ZERO_ADDRESS)return null;const r=!e.isNative&&!R.isNativeToken(e.address)?R.getTokenByAddress(e.address,e.chainId):void 0,o=r&&to(r)?_o(e.address,e.chainId,t):void 0,a=o?r:Ts(e.chainId),i=o??Ts(t);if(!a||!i)return null;const l=u=>({address:u.address,symbol:u.symbol,decimals:u.decimals,chainId:u.chainId});return{source:l(a),destination:l(i)}}function Au(e,t){return!!ea(e,t)}function Nn(e,t){if(e.chainId===t)return e.address;const n=_o(e.address,e.chainId,t);return n?n.address:null}async function Jn(e,t,n,s){const r=R.getTokenByAddress(t,n);return r?r.decimals:e?.chainId===n&&d.addressesEqual(e.address,t)&&!e.isUniversal?e.decimals:s?.chainId===n&&d.addressesEqual(s.address,t)?s.decimals:d.getTokenDecimals(n,t)}async function sc(e,t,n={}){const s=Nn(e,t),r=Vs(e,t);if(r.length===0)return s;if(r.length===1)return r[0];const o=n.requiredAmount??0n,a=i=>{const l=r.map(u=>({candidate:u,balance:i.get(R.isNativeToken(u)?"native":u.toLowerCase())??0n})).filter(u=>u.balance>0n).sort((u,m)=>u.balance===m.balance?0:u.balance>m.balance?-1:1);return l.length===0?null:((o>0n?l.find(u=>u.balance>=o):l[0])??l[0]).candidate};try{const i=await Promise.all(r.map(async m=>({key:R.isNativeToken(m)?"native":m.toLowerCase(),value:await Iu(t,m)}))),l=new Map(i.map(({key:m,value:f})=>[m,f])),u=a(l);if(u)return u}catch{}return s}function xr(e,t,n,s){const r=R.getTokenByAddress(e,t),o=R.getTokenByAddress(n,s);return r&&o?tc(r.equivalenceGroup,o.equivalenceGroup):R.areEquivalent(e,n)}function no(e,t){return xr(e.address,e.chainId,t.address,t.chainId)}const rc=.01;function oc(e,t=!1){const n=Number.isFinite(e.balanceUsd)&&e.balanceUsd>0;return e.isDiscovered?n&&e.balanceUsd>=rc:!t||!n||e.balanceUsd>=rc}function Qs(e,t=!1){return!!e&&e._source==="wallet"&&(e.location==="external"||e._fundingWallet==="external"||!e.location&&!e._fundingWallet&&t)}function he(e){return e.positionId??`${e.owner?.toLowerCase()??""}:${e.location??e._source??""}:${e.chainId}:${e.receiptTokenId??R.normalizeNativeTokenAddress(e.address).toLowerCase()}`}function ac(e,t){if(!t?.length||e.symbol!==void 0&&d.isAssetAllowed({...e,symbol:e.symbol},t))return!0;const n=s=>t.some(r=>d.addressesEqual(R.normalizeNativeTokenAddress(r),R.normalizeNativeTokenAddress(s)));return n(e.address)||Object.keys(e.chainTokens??{}).some(s=>{const r=kn(s);return r?n(r.address):!1})}function Qn(e,t,n,s,r,o){const a=(x,w=!1)=>({eligible:!1,reason:x,policyExcluded:w}),i=e._source==="wallet"||e.location==="external"||e.location==="embedded",l=t==="spend-source"&&i&&!!s&&e.chainId===s.chainId&&d.addressesEqual(R.normalizeNativeTokenAddress(e.address),R.normalizeNativeTokenAddress(s.address));if(n.isWhitelistGateActive||!l&&!d.isAssetAllowed(e,n.allowedTokens))return a("Asset excluded by client policy",!0);if(t!=="withdraw-destination"&&!l&&!oc(e))return a("Asset is unpriced or below the minimum value",!0);if(t==="holding")return{eligible:!0,reason:null};if(e.balanceError)return a(e.balanceError);if(!l&&!ac(e,r))return a("Asset excluded by action policy",!0);const u=new Set(s?[s.chainId]:[]);e._source!=="spice"&&e.location!=="rollup"&&u.add(e.chainId);for(const x of u)if(!d.getRpcUrlForChain(x,n.rpcOverrides)?.trim())return a(`Configure SpiceFlowProvider rpcOverrides[${x}] before using this asset.`);if(o?.requiresEscrow){const x=R.getTokenByAddress(e.address,e.chainId);if(!x||!to(x))return a("This asset has no supported escrow mapping")}if(!s)return{eligible:!0,reason:null};const m=n.liquidityVenues?.includeDefaults===!1?n.liquidityVenues.venues??[]:[...Xo,...n.liquidityVenues?.venues??[]],f=x=>m.some(w=>w.chainId===x),h=i&&e.chainId!==s.chainId,y=h?ea(e,s.chainId):null;if(h&&!y)return a("No supported source route");if(y&&!d.addressesEqual(R.normalizeNativeTokenAddress(e.address),R.normalizeNativeTokenAddress(y.source.address))&&!f(e.chainId))return a("No conversion venue configured on the source chain");const g=y?.destination.address??Nn(e,s.chainId);return t==="withdraw-destination"?(e.chainTokens||e.receiptTokenId?Vs(e,s.chainId):g?[g]:[]).some(x=>d.addressesEqual(R.normalizeNativeTokenAddress(x),R.normalizeNativeTokenAddress(s.address)))?{eligible:!0,reason:null}:a("No supported withdrawal mapping"):g&&d.addressesEqual(R.normalizeNativeTokenAddress(g),R.normalizeNativeTokenAddress(s.address))?{eligible:!0,reason:null}:!g&&!Au(e,s.chainId)?a("No supported destination route"):f(s.chainId)?{eligible:!0,reason:null}:a("No conversion venue configured on the destination chain")}function so(){const e=p.useContext(d.SpiceFlowProviderContext),[t]=p.useState(d.createInventoryStore);return e?.inventory??t}function ta(e,t,n,s,r){const o=so(),a=r??o,i=p.useMemo(()=>a.entry(e),[a,e]),[,l]=p.useState(0);p.useEffect(()=>{if(n)return i.subscribe(()=>l(m=>m+1),t,s)},[i,n,t,s]);const u=p.useCallback(()=>i.refresh(),[i]);return{...n?i.snapshot():d.EMPTY_INVENTORY,refresh:u}}var ic="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAA6lBMVEXc3NzX/v/1hRvZ2dnd3dzb29va7fpMaXHa1tPc3N35/v/c3Nzc3NzCrp/c3Nza2tp1PRbLsJzlr33uhSj0kTHcnWnUva7jdhuNX0B6Qhrsk0LOxMCFVDJ+RyGhfGTkeiGYVSHjdx3lij7khDPEsaPfoW/jgjLQuKXmgzB2PRb2hRvldhvjdRv4hhvpeRtwORb/ihryghvabhnsehrUaRjLXxXtfRt7PxXwexricRbRYhURFBeSTBe0XBrEZxmDRxiiVRrlgCbfzMAvLCmrWBgbMEh9UjBbOBe2pJi9byekk4nkgDHkgDJLNB7jlKArAAAAKXRSTlMzJv0TNSYsADUxKBwK/QUZ/URTx650/vqJ5YpMosxj3ezwkqa6/q3KrihQ98kAAAAJcEhZcwAACxMAAAsTAQCanBgAAATxSURBVHjapVeJcuI4EJXBdiRuw4JzDAFyzeIT22BsNgTIJNnM7Pz/90xLsmV5ChJm6SqqZOR+7teXWujsgLSqdU0jBCFCNK1ebR16D+39t1HXiKqqGDHBsCRavXEsQKutIVWln0aZ0BX8o7VbRwC06gS+LHQLIWAJqbc+A6iC+h7t3BCVVD8EaGgqOqSemaFqjcMA8PkP1RnEb0bIAPXD1peNqO8H0NQj1LkR2j6Ao/XLCOh/6JcQkOD/B/oUoV4GqGb6+HNdnCFUZYBG9nmsE/whBsZE5y9g0pAAcgcQQ1V0fAgDNnRFNQiW3cAA2lwfI3wxvunqyl4z4OOK3r0ZX2CUIbRzgFZOoHY9nW7NXt9QdFTGgCddMfq9cDudXteyLdLKAPII4NqXZcffzIPJQx8zDCFgev9hksw3fmf5pYalSCDJAGAw7Uz9zkuU2CNKRQiYPrIT76Xjwws5B/BjiwG0hQHAgIr/GHpeYvb+EtIzI88LH32+fy1MaDMAKOGCAUdYPnmmE82ERI7pPS25fsEB0UCgs4ZwVO08AwB5sT0zrmQSm7b94mff7yzPa8LBDQAQSSwo5DRsKxO7MF+mwNyIBAPwjHEhIQCNgOsHwnwmF4aeWwAcUEMO97DgABAvkUv13WgrqXeWQ7moGqiqFtkivJjTCADBDWTzZR9SE6pIquOSF6msGYdgPS0BSD4EJ6CikUB+DKcd2QkRB4hkF3SmQyyqHioKaViicF4AQEp7DqfgRJDCSwFxLlPQ5GMAAHJ9n4bRyQEcGkZ/HwColwBYHH3fXz6uHc+xnZgCxLDwnPXj0mcgUhRpOZSblTEE9c32ybMi27ELAHiILO9puwGIoXG48YEJ43UYzGYumG/LADbQcGezIFyPjRr+7aCREfTezLUqFtMB4QB87cSw4c56uqyPSz4A/S6UDuikqzkTmwLYfL1K4aFiVbolBCKHEWHlclahyRvMF4vFarWgOm5KV4vFnIbEqswuFUmD5oF0olAGFZ7+88VqvV05FMBZbderxZwXRqXEgSaSfCTp3cDiAIETvr2+riP64K1fX99ClhMA4AIH+YAqFVPGgGnFu+9v44Quk/Hb913suXyjzAGKSS7nnAEtgBg6WeAxLIjrLM56A+NQKueioVAGruW67OdWrCCwYqoS01XgZmLJHGhDkVqa3oXeSyUESaktvBrBJ5WU/sd3IxFI3tKKpkrwCDIQcjCkUfPAnIAJ+NSjcQ1tuuuNMCk11TORCVh5SEyWdXP2dmzxpk4TEzDnbMtM/lakligfLADQj3gOOysASNPd5l+QzS5NAWCVbUV9RTBol442cIIxsVnlwPthurtv/sOkeb9LQ2oS25qIcs6PNtmNvch0HBOKN/15P3h+5wDvz4P7/1IocNhzop7swvLxTjMpMm0viSa9m6/Pg+cf35j8gOXXm94kSjzbjIo8Esd7cbxCIBNzdNs3dAXdDQbN9ybIe3MwuEOKbvRvR2YigigNGNKMh28vu0ihswGp9ZuDJpNBs0+HFjjuUffyFpcnvfKQhbgym06wcnXHAe6umNWYjSlKkcXlMa8YpIrEIldMCMHyrLNvzDs0aBImxwyap4+6pw/bp4/71A/opAvH6Vee0y9dn1z70OfXvuziudcMSKdjLp786quecPWVL99Zfqt/ePkuX/8Jv/43Dl3/fwH9bPJ09nq7MQAAAABJRU5ErkJggg==",Eu="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAQlBMVEVMaXGGl/+Elf+HmP+Hmf+Hl/+Gl/+Flv+Glv+Gl/+Gl/+Gl/////+On/+Akv/4+f/v8f/i5v+9x//S2P+tuP+erP+W3PvUAAAAC3RSTlMArBlx7Isy/vvOXbb4wDYAAAAJcEhZcwAACxMAAAsTAQCanBgAAALuSURBVHjarVfbtqsgDOxu0UBpkOv//+pJRC0i2HZ58uTeqzOEyYXkduvY/Tn8KSEBpFB/w3O8/WTjoCSS6dn4S6rha477QxFGS0nHM56ckJL/ox73b+CDQAQJujKiQxTDR4qH4LN109gP8Ti/uyI46K4BUagTLZ4Cz+CZAsWzhx/oeP3RyImhjf/7ePzmxF8Hr7+zNsP3eL7GkWH4Bc8MlQ7P3/DMsIvFKHRLPzBsTWVBizIfVNMBg9H7mLQxTRdUkb9tfJxebNZjywuJW1bf2xcw4WXtzDF5bVqXuJ9HwETHNnPYeHRii0THgcwQyBxTBDQ9Fx7dEBr0TOCDYyeS6aigsFsCQIFgBh9YiVgxQA7EqM9KiCiS95nh5WsGPZ4k8ZZFRqfoY4shy9i8AaExxRgTMgcApuSODPMdRtn02wc7Z9HkPMsPa1ZVOsiRygga4udfZ5vTKKx/7GIBVFJHCUy0r705DNu3LQ9kEQ6NxMTXwWzhUTD7xlJr2MLvrZCBVazy2OD0iaC4BGh1k4cSLOSbbIuujKW4wT76aYefrGswuBJSEoBeUnaFk7nQcKEIJZRXMPsfM95O3p3KKAoRa/cJTh0pHKMybSqyiO8wMsG0wzODi7UK9u0Ah7FIJAj1+UyQcl4Gqi2uax+L/siJVKQyi+j251sbMoHTZrUqlctiojDGRX27WpivYNtdi4upKme0c/gXBmdzY7ZoOi/cWDeU7MJy+oKn3hzbT9/cFKt6pmKe9udnCoTeG103VW7EjrGZJMOD863GNzfVQ0EDP6aJUH61wBRHGZa23npYDDpuh8EnpPBRS6UUQOg9r8enzaDdmhmsPkH/da3bokkr/i0dwMmYU7lg0pRrwiVzNrW+n/dKhVzVVIbGnE9Jj86IA8glk87h+xGnGrJyzXwYNvdD1uUx7/qgeX3UvT5sXx/3ry8c11ee60vX9bXvvXjWfsC3i+d79YV19+WPH1bf/7B8Lxy8/isBINTp+v8Ph4CTcAywkiYAAAAASUVORK5CYII=",Fu="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAPFBMVEVMaXGZhueZh+eYhuWXheWYh+eYhuaXheCYhuaah+j//fmhjvOSf+Sdi+q8sOzNxO/m4fT08fapmuja0/Jb/wGxAAAACnRSTlMArEz/IYtsA87sGIEBYwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAmJJREFUeNqtV4uSgyAMRIECGhTk///1otTKG3s2Mzdz03aXbEJIQkhuYv9jIx+komhKDnxk4v1F1wT+SoxcUj3PWu8Ex39U8lH4bzt4QthL6tlDA8OP5Iv1vMADGFc5+uRQnDWdEES81EwbNquXqDuBx8va6ZcXktUYBOkc/3GixsBvwA8neFGGGO7hdyeGAsMXeM/wBJ8ziLv6LwYeisD4f4lHhiAXmH9FvzYV3AchOw6At9gFKW4KANDbsttGoSyCKd1Ab4uxkzezhBQaRfQygHB3oj2FhjwT9QgifErM6jiOrQgAXe2UmcuiIKSuHG+mki2XCH0kYqzgF1vETyYszLFaxLBMNdsgDGNFAazRoUcwrDMlDYz28RS0newGcCRlDa8TK4YgxuORGj9x8NYVEsxjKQSp/pNAw5YRcJI/JP5nYeqxjAxeIfCeRQQDyWOos/y5xR2V4NIgYhRJVkjgpralBPcvQH4PsBxIX0DjJqKRdgYLtsYPUyqh60CsACXEQew7ECvAICZp7DqwQEIQXaR+CkzaoeKr3FewQdqg4mIy36VgLyZWz4G96N5vs8sKj0UPSlJGy4fAbWX88SgGQYgJVjDXi7JaaxYo9Oj4UQ0lrHCGdN25ceiEfNoZSfIomjhcKN26DarT0q4gaiyfe2C9u9hWNUBvRghbG+yd1AZNFFrjmu+ucXMF2j60OObE7f0m+mrv/5qQkimpO+IU8fKXQ9bDMe/5oPl81P3BsP183EeGu3GoLBw/WHnuLF20sXQ9X/ueL57PV99w+Z7P5Vvj8j3fXr7j9X/f/5Vsrv9/K3NM7mGXOq0AAAAASUVORK5CYII=",yr="data:image/svg+xml,%3csvg width='8' height='11' viewBox='57 6 8 11' fill='none' xmlns='http://www.w3.org/2000/svg'%3e %3cpath d='M62.7081 13.27C62.742 13.27 62.7642 13.3057 62.7491 13.3362V13.336L61.1229 16.6083C61.0892 16.6761 60.9926 16.6759 60.959 16.6083L59.3382 13.336C59.3232 13.3057 59.3453 13.27 59.3792 13.27H62.7081Z' fill='%23EA4B4B'/%3e %3cpath d='M61.0026 9.71913C61.0194 9.68524 61.0678 9.68524 61.0845 9.71913L62.747 13.0897C62.762 13.12 62.7399 13.1557 62.706 13.1557H59.3763C59.3424 13.1557 59.3203 13.12 59.3353 13.0897L61.0026 9.71913Z' fill='%23EA4B4B'/%3e %3cpath d='M60.8426 9.63827C60.8766 9.63827 60.8987 9.6741 60.8835 9.70444L59.2164 13.0594C59.1995 13.0932 59.1513 13.0932 59.1345 13.0594L57.5001 9.77047C57.47 9.70962 57.5142 9.63827 57.5821 9.63827H60.8426Z' fill='%23EA4B4B'/%3e %3cpath d='M64.5036 9.63617C64.5715 9.63618 64.6157 9.70753 64.5855 9.76838H64.5854L62.9512 13.0573C62.9344 13.0911 62.8862 13.0912 62.8692 13.0573L61.2021 9.70235C61.187 9.672 61.2091 9.63617 61.2431 9.63617H64.5036Z' fill='%23EA4B4B'/%3e %3cpath d='M62.8284 6.18281C62.862 6.11518 62.9586 6.11518 62.9922 6.18281L64.5855 9.38969C64.6157 9.45054 64.5715 9.52189 64.5036 9.52189H61.2431C61.2091 9.52189 61.187 9.48605 61.2021 9.45571L62.8283 6.18265L62.8284 6.18281Z' fill='%23EA4B4B'/%3e %3cpath d='M62.3131 6.13196C62.381 6.13196 62.4252 6.20331 62.3951 6.26416C62.154 6.74935 61.9128 7.23455 61.6718 7.71975H61.6716C61.4225 8.22125 61.1733 8.72259 60.9242 9.22409C60.9074 9.25799 60.859 9.25799 60.8422 9.22409L60.6305 8.79587C60.6275 8.78957 60.6259 8.78263 60.6259 8.77553V6.22349C60.6259 6.17297 60.6668 6.13196 60.7173 6.13196H62.3131Z' fill='%23EA4B4B'/%3e%3c/svg%3e";const br=R.getChainMeta(1)?.logo??"",Tu=R.TOKENS.find(e=>e.symbol==="USDC")?.logo??"",xs=Object.fromEntries([...R.getMainnetChains(),...R.getTestnetChains()].map(e=>[e.id,e.logo])),vr={metamask:ic,metaMask:ic,rabby:Eu,phantom:Fu},na=Object.fromEntries(R.TOKENS.map(e=>[e.symbol.toUpperCase(),e.logo])),Ru={usdc:[8453,1,42161,5115,4114],usdt:[1],btc:[4114,42161,1,5115],wbtc:[1],weth:[8453,1],eth:[8453,1,42161,4663,84532,46630],ctusd:[5115,4114],wcbtc:[5115,4114]},Bu={btc:["wcbtc","cbtc","wbtc"]};function ro(e){return e.replace(/^test\s*/i,"").replace(/^spice/i,"").trim()}function rs(e){return ro(e).toLowerCase()}function cc(e){return rs(e??"").replace(/[^a-z0-9]/g,"")}function sa(e){const t=rs(e);return[t,...Bu[t]??[]].filter(Boolean)}function Ou(e){try{return BigInt(e.balanceAvailable||"0")}catch{return 0n}}function lc(e){return Array.isArray(e.chainTokens)?e.chainTokens:Object.keys(e.chainTokens??{})}function dc(e,t){const n=d.getChainConfig(e),s=t.toLowerCase();return s===R.ZERO_ADDRESS.toLowerCase()?n?.nativeCurrency.decimals??18:n?.supportedTokens?.find(r=>r.address.toLowerCase()===s)?.decimals??18}function ju(e,t,n,s=[]){const r=dc(t,n),o=e.filter(i=>uc(i,t,n,s));if(o.length===0)return null;const a=o.reduce((i,l)=>Math.min(i,l.decimals??r),r);return{chainDecimals:r,receiptDecimals:a}}function uc(e,t,n,s){if(lc(e).some(o=>{const a=kn(o);return a&&xr(a.address,a.chainId,n,t)}))return!0;const r=new Set(s.map(cc).filter(Boolean));return r.size===0?!1:r.has(cc(e.tokenName||e.receiptToken))}function pc(e,t,n,s=[]){const r=dc(t,n);return e.reduce((o,a)=>uc(a,t,n,s)?o+R.convertAmountBetweenDecimals(Ou(a),a.decimals??r,r):o,0n)}function fc(e,t){const n=new Set([...sa(t),...sa(ro(t))]);return[...e].sort((s,r)=>{const o=rs(s.symbol),a=rs(r.symbol),i=rs(s.name),l=rs(r.name),u=n.has(o)?0:n.has(i)?1:2,m=n.has(a)?0:n.has(l)?1:2;return u!==m?u-m:s.address.toLowerCase().localeCompare(r.address.toLowerCase())})[0]}function Du(e){const t=e&&e.length>0?e:Object.keys(d.CHAIN_CONFIGS).map(Number).filter(Number.isFinite),n=new Map;for(const s of t){const r=d.getChainConfig(s);if(!r)continue;const o=`${s}:${R.ZERO_ADDRESS.toLowerCase()}`;n.has(o)||n.set(o,{address:R.ZERO_ADDRESS,chainId:s,symbol:r.nativeCurrency.symbol,name:r.nativeCurrency.name,decimals:r.nativeCurrency.decimals,isNative:!0,logoURI:na[r.nativeCurrency.symbol.toUpperCase()]??r.logo});for(const a of r.supportedTokens??[]){const i=a.address.toLowerCase(),l=`${s}:${i}`;n.has(l)||n.set(l,{address:i,chainId:s,symbol:a.symbol,name:a.name,decimals:a.decimals,isNative:R.isNativeToken(i),logoURI:a.logo})}}return n}function Nu(e,t){const n=Du(t),s=ro(e.tokenName),r=rs(e.tokenName),o=sa(e.tokenName),a=Array.isArray(e.chainTokens)?e.chainTokens.map(g=>[g,void 0]):Object.entries(e.chainTokens??{}),i=a.map(([g])=>kn(g)).filter(g=>g!==null),l=new Map;for(const[g,x]of a){const w=kn(g);if(!w||!Number.isSafeInteger(w.chainId)||w.chainId<0||!/^evm:[0-9]+:(?:0x)?[0-9a-fA-F]{40}$/.test(g)){if(!Array.isArray(e.chainTokens))throw new Error("Invalid chain token metadata identity");continue}if(x!==void 0&&(!x||typeof x!="object"||Array.isArray(x)||x.name!==void 0&&typeof x.name!="string"||x.decimals!==void 0&&(!Number.isInteger(x.decimals)||x.decimals<0||x.decimals>255)))throw new Error("Invalid chain token metadata");const b=`${w.chainId}:${w.address.toLowerCase()}`;if(l.has(b)){const k=l.get(b);if(k?.name!==x?.name||k?.decimals!==x?.decimals)throw new Error("Conflicting chain token metadata")}l.set(b,x)}const u=(g,x)=>{const w=l.get(`${x.chainId}:${x.address.toLowerCase()}`);return{...g,name:typeof w?.name=="string"&&w.name.length>0?w.name:g.name,decimals:typeof w?.decimals=="number"?w.decimals:g.decimals}},m=i.map(g=>{const x=n.get(`${g.chainId}:${g.address.toLowerCase()}`);return x?u(x,g):void 0}).filter(g=>g!==void 0),f=Ru[r]??[];if(f.length>0)for(const g of f){const x=m.filter(w=>w.chainId===g);if(x.length>0)return fc(x,e.tokenName)}if(m.length>0)return fc(m,e.tokenName);const h=Array.from(n.values()).filter(g=>o.includes(rs(g.symbol))||o.includes(rs(g.name)));if(f.length>0)for(const g of f){const x=h.find(w=>w.chainId===g);if(x)return x}if(h.length>0)return h[0];const y=i[0];if(y){const g=l.get(`${y.chainId}:${y.address.toLowerCase()}`);return{address:y.address,chainId:y.chainId,symbol:s||e.tokenName,name:typeof g?.name=="string"&&g.name.length>0?g.name:s||e.tokenName,decimals:typeof g?.decimals=="number"?g.decimals:e.decimals??18,isNative:R.isNativeToken(y.address),logoURI:void 0}}}function Mu(e,t){let n;try{n=BigInt(e.balanceAvailable||"0")}catch{return null}if(n<=0n)return null;if(t?.length){const g=lc(e).map(kn).filter(x=>x!==null);if(g.length>0&&!g.some(x=>t.includes(x.chainId)))return null}let s;try{s=Nu(e,t)}catch{return null}const r=s?.decimals??e.decimals??18,o=e.decimals??r,a=R.convertAmountBetweenDecimals(n,o,r),i=s?.address??R.ZERO_ADDRESS,l=s?.chainId??0,u=ro(e.tokenName),m=s?.symbol??u,f=s?.name??u,h=parseFloat(N.formatUnits(a,r)),y=typeof e.balanceUsd=="number"?e.balanceUsd:typeof e.balanceUsd=="string"&&Number(e.balanceUsd)||0;return{address:i,symbol:m,name:f,decimals:r,chainId:l,balance:a,balanceFormatted:h,balanceUsd:y,isNative:s?.isNative??R.isNativeToken(i),logoURI:s?.logoURI,displaySymbol:u||m,displayName:u||f,displayChainName:"Spicenet",receiptTokenId:e.receiptToken,receiptTokenName:e.tokenName||f,receiptTokenDecimals:o,chainTokens:e.chainTokens&&!Array.isArray(e.chainTokens)?e.chainTokens:void 0,isUniversal:!0}}const ra=6e4,Pu=3e5,mc="https://api.g.alchemy.com/prices/v1",Gs=new Map;function oo(e,t){try{const n=t??d.getRpcUrlForChain(e);if(typeof n!="string")return null;const{hostname:s,pathname:r}=new URL(n);if(!s.endsWith(".g.alchemy.com"))return null;const o=r.split("/").filter(Boolean).pop();return o?{network:s.slice(0,-14),key:o}:null}catch{return null}}const Cr=(e,t)=>`${e.network}:${e.key}:${t.toLowerCase()}`;function Rs(e,t){const n=Gs.get(Cr(e,t));if(!n?.price||n.updatedAt===void 0)return;const s=Date.now()-n.updatedAt;if(!(s>=Pu))return{price:n.price,stale:s>=ra}}function hc(e){const t=Number(e.prices?.find(n=>n.currency==="usd")?.value);return Number.isFinite(t)&&t>0?t:0}async function gc(e,t,n){const s=[],r=new Set,o=Date.now();for(const a of new Set(t.map(i=>i.toLowerCase()))){const i=Gs.get(Cr(e,a));i?.pending?r.add(i.pending):(!i||o-i.attemptedAt>=ra&&(i.updatedAt===void 0||o-i.updatedAt>=ra))&&s.push(a)}for(let a=0;a<s.length;a+=25){const i=s.slice(a,a+25),l=Promise.resolve().then(async()=>{try{const u=await n(i);for(const m of i){const f=u.get(m);if(!f)continue;const h=Gs.get(Cr(e,m));h.price=f,h.updatedAt=Date.now()}}catch{}finally{for(const u of i)Gs.get(Cr(e,u)).pending=void 0}});for(const u of i){const m=Cr(e,u);Gs.set(m,{...Gs.get(m),attemptedAt:o,pending:l})}r.add(l)}await Promise.all(r)}async function oa(e,t){return await gc(e,t,async n=>{const s=await fetch(`${mc}/${e.key}/tokens/by-address`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({addresses:n.map(a=>({network:e.network,address:a}))}),signal:AbortSignal.timeout(1e4)});if(!s.ok)throw new Error("Provider price request failed");const r=await s.json(),o=new Map;for(const a of r?.data??[]){if(a.network&&a.network!==e.network)continue;const i=String(a.address).toLowerCase();n.includes(i)&&o.set(i,hc(a))}return o}),new Map(t.map(n=>[n.toLowerCase(),Rs(e,n)?.price??0]))}async function aa(e,t){const n=`native:${t}`;return await gc(e,[n],async()=>{const s=await fetch(`${mc}/${e.key}/tokens/by-symbol?symbols=${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(1e4)});if(!s.ok)throw new Error("Provider native price request failed");const r=(await s.json())?.data?.find(o=>o.symbol?.toUpperCase()===t.toUpperCase());return new Map([[n.toLowerCase(),r?hc(r):0]])}),Rs(e,n)?.price??0}async function Uu(e,t){const n=t.supportedChains,s=e.map(r=>{const o=Object.keys(r.chainTokens??{}).map(kn).filter(a=>!!a&&N.isAddress(a.address)&&!!n?.includes(a.chainId));return o.sort((a,i)=>{const l=u=>u===t.nativeChainId?-1:n.indexOf(u);return l(a.chainId)-l(i.chainId)||+!d.addressesEqual(a.address,r.address)-+!d.addressesEqual(i.address,r.address)}),o.flatMap(a=>{const i=t.rpcOverrides?.[a.chainId];if(!i)return[];const l=oo(a.chainId,i);if(!l)return[];const u=R.isNativeToken(a.address)?d.getChainConfig(a.chainId)?.nativeCurrency.symbol:void 0,m=u?`native:${u}`:a.address;return[{rpc:l,token:m,address:a.address,nativeSymbol:u}]})});return(typeof document>"u"||!document.hidden)&&await Promise.all(s.map(async r=>{for(const o of r)if(o.nativeSymbol?await aa(o.rpc,o.nativeSymbol).catch(()=>0):await oa(o.rpc,[o.address]).catch(()=>new Map),Rs(o.rpc,o.token)?.stale===!1)break})),e.map((r,o)=>{const a=s[o].map(l=>Rs(l.rpc,l.token)),i=a.find(l=>l&&!l.stale)??a.find(Boolean);return{...r,balanceUsd:i?r.balanceFormatted*i.price:Number.isFinite(r.balanceUsd)&&r.balanceUsd>0?r.balanceUsd:0,priceStatus:i?i.stale?"stale":"fresh":"unavailable"}})}function Wu(e,t,n){const s=p.useContext(d.SpiceFlowProviderContext),[r,o]=p.useState(()=>typeof document>"u"||!document.hidden);p.useEffect(()=>{const m=()=>o(!document.hidden);return document.addEventListener("visibilitychange",m),()=>document.removeEventListener("visibilitychange",m)},[]);const a={supportedChains:n??s?.supportedChainIds,nativeChainId:s?.nativeChainId,rpcOverrides:s?.rpcOverrides},i=JSON.stringify([e,a],(m,f)=>typeof f=="bigint"?f.toString():f),l=p.useCallback(()=>Uu(e,a),[i]),u=ta(`prices:${i}`,l,t&&r&&e.length>0,6e4);return u.updatedAt?u.assets:e}function qu(e){const t=e.chainTokens??e.chainTokenConfig;if(Array.isArray(t))return t.filter(n=>typeof n=="string");if(t&&typeof t=="object")return t}const wc=({address:e,supportedChains:t,enabled:n=!0,refetchInterval:s,priceEnabled:r=!1})=>{const o=p.useContext(d.SpiceFlowProviderContext),a=o?.apiUrl||d.RELAYER_API_URL,i=so(),l=o?.supportedChainIds??t,u=JSON.stringify([...l??[]].sort((D,S)=>D-S)),m=e?.toLowerCase(),f=p.useCallback(async()=>{const D=`${a}/wallets/${m}/balance`;let S,v;try{const F=await d.relayerFetch(D,{cache:"no-store"});if(S=F.status,v=F.requestId,!F.ok)throw new Error(`Failed to fetch balance: ${F.status}`);const O=await F.json();if(!Array.isArray(O.balances))throw new Error("Invalid balance response");return O.balances.map(j=>{const q=Mu({receiptToken:typeof j.receiptToken=="string"?j.receiptToken:void 0,tokenName:String(j.tokenName??""),balanceAvailable:String(j.balanceAvailable??"0"),chainTokens:qu(j),decimals:typeof j.decimals=="number"?j.decimals:void 0,balanceUsd:typeof j.balanceUsd=="number"||typeof j.balanceUsd=="string"?j.balanceUsd:null},l);return q?{...q,owner:m,location:"rollup",_source:"spice",positionId:`${m}:rollup:${q.receiptTokenId??q.address}`}:null}).filter(j=>j!==null)}catch(F){const O=F instanceof Error?F.name:void 0,j=S===429?"Balance refresh is temporarily busy. Wait a moment and try again.":S===408||S===504||O==="TimeoutError"?"Balance refresh timed out. Try again.":O==="AbortError"?"Balance refresh was interrupted. Try again.":"Balances are unavailable. Check your connection and try again.",q=new d.SpiceflowError("RELAYER_STATUS_ERROR",j,{endpoint:D,httpStatus:S,requestId:v,cause:F});throw d.sanitizeError(q),q}},[m,a,u,o?.nativeChainId,o?.rpcOverrides]),{assets:h,loading:y,refreshing:g,error:x,updatedAt:w}=ta(`rollup:${m}:${a}:${u}`,f,n&&!!m,s??0,i),b=JSON.stringify(t??[]),k=p.useMemo(()=>x?h.map(D=>({...D,balanceError:x,balanceStatus:"stale"})):h,[h,x]),A=Wu(k,n&&r,l),C=p.useMemo(()=>A.filter(D=>!t?.length||t.includes(D.chainId)||Object.keys(D.chainTokens??{}).some(S=>t.some(v=>S.startsWith(`evm:${v}:`)))),[A,b]),E=p.useCallback(D=>C.filter(S=>S.chainId===D),[C]);return{assets:C,loading:y,error:x,hasBalance:C.some(D=>D.balance>0n),refreshing:g,updatedAt:w,refetch:i.invalidate,getAssetsByChain:E}};async function Lu(e,t,n){if(n)return{decimals:n.decimals,symbol:n.symbol,name:n.name,logoURI:n.logo};const[s,r,o]=await Promise.all([Vn.readContract(e,{address:t,abi:N.erc20Abi,functionName:"decimals"}),Vn.readContract(e,{address:t,abi:N.erc20Abi,functionName:"symbol"}).catch(()=>"TOKEN"),Vn.readContract(e,{address:t,abi:N.erc20Abi,functionName:"name"}).catch(()=>"TOKEN")]);if(!Number.isInteger(Number(s))||Number(s)<0||Number(s)>255)throw new Error("Invalid token decimals");return{decimals:Number(s),symbol:r,name:o,logoURI:void 0}}const xc=async(e,t,n)=>{const s=d.getClientForChain(t,n),r=d.getChainConfig(t),o=await Vn.getBalance(s,{address:e}),a=r.nativeCurrency,i=r.supportedTokens?.find(l=>R.isNativeToken(l.address));return{address:R.ZERO_ADDRESS,name:a.name,symbol:a.symbol,decimals:a.decimals,balance:o,balanceFormatted:Number(N.formatUnits(o,a.decimals)),balanceUsd:0,priceStatus:"unavailable",logoURI:i?.logo||r.logo,isNative:!0,chainId:t}},zu=async(e,t,n,s,r,o,a)=>{try{if(!N.isAddress(n))return null;const i=N.getAddress(n),l=N.isAddress(e)?N.getAddress(e):e,u=d.getClientForChain(t,a),m=await Vn.readContract(u,{address:i,abi:N.erc20Abi,functionName:"balanceOf",args:[l]}),f=Number(N.formatUnits(m,o));return m>0n?{address:i,name:s,symbol:r,decimals:o,balance:m,balanceFormatted:f,balanceUsd:0,priceStatus:"unavailable",logoURI:void 0,isNative:!1,chainId:t}:null}catch(i){throw i}},yc=(e,t)=>{const n=d.getChainConfig(t);if(!n)return e;const s=new Set(e.map(o=>o.address.toLowerCase())),r=e.some(o=>o.isNative);for(const o of n.supportedTokens||[])R.isNativeToken(o.address)&&r||s.has(o.address.toLowerCase())||e.push({address:o.address,name:o.name,symbol:o.symbol,decimals:o.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,priceStatus:"unavailable",logoURI:o.logo,isNative:R.isNativeToken(o.address),chainId:t});if(!e.find(o=>o.isNative)){const o=n.supportedTokens?.find(a=>R.isNativeToken(a.address));e.push({address:R.ZERO_ADDRESS,name:n.nativeCurrency.name,symbol:n.nativeCurrency.symbol,decimals:n.nativeCurrency.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,priceStatus:"unavailable",logoURI:o?.logo||n.logo,isNative:!0,chainId:t})}return e},Hu=async(e,t,n)=>{const s=[],r=async i=>{for(const l of i){const u=await zu(e,t,l.address,l.name,l.symbol,l.decimals,n);u&&(u.logoURI=l.logo,s.push(u))}},o=await xc(e,t,n);o.balance>0n&&s.push(o);const a=(d.getChainConfig(t)?.supportedTokens||[]).filter(i=>!R.isNativeToken(i.address));if(a.length>0)try{const i=d.getClientForChain(t,n),l=N.getAddress(e),u=a.filter(y=>N.isAddress(y.address)).map(y=>({address:N.getAddress(y.address),abi:N.erc20Abi,functionName:"balanceOf",args:[l]})),m=await i.multicall({contracts:u}),f=a.filter(y=>N.isAddress(y.address)),h=[];m.forEach((y,g)=>{if(y.status==="success"){const x=y.result;if(x&&x>0n){const w=f[g],b=Number(N.formatUnits(x,w.decimals));x>0n&&s.push({address:N.getAddress(w.address),name:w.name,symbol:w.symbol,decimals:w.decimals,balance:x,balanceFormatted:b,balanceUsd:0,priceStatus:"unavailable",logoURI:w.logo,isNative:!1,chainId:t})}}else h.push(f[g])}),await r(h)}catch{await r(a)}return{tokens:yc(s,t),chainId:t}},Vu=async(e,t,n)=>{const s=new Map,r=oo(e,n?n[e]??"":void 0);if(!r)return s;const o=t.filter(u=>R.isNativeToken(u)),a=t.filter(u=>!R.isNativeToken(u)),[i,l]=await Promise.all([a.length?oa(r,a).catch(()=>new Map):new Map,o.length?aa(r,d.getChainConfig(e)?.nativeCurrency?.symbol??"ETH").catch(()=>0):0]);for(const[u,m]of i)m>0&&s.set(u,m);if(l>0)for(const u of o)s.set(u.toLowerCase(),l);return s},Qu=async(e,t,n,s=!0,r)=>{const o=d.getClientForChain(t,r),a=N.getAddress(e),i=[];let l;do{const x=await o.request({method:"alchemy_getTokenBalances",params:[a,"erc20",l?{pageKey:l}:{}]});i.push(...x.tokenBalances),l=x.pageKey||void 0}while(l);const u=i.filter(x=>N.isAddress(x.contractAddress)&&!!x.tokenBalance&&BigInt(x.tokenBalance)>0n),m=d.getChainConfig(t)?.supportedTokens||[],f=x=>m.find(w=>w.address.toLowerCase()===x.toLowerCase()),h=[],y=await xc(e,t,r),[g]=await Promise.all([Promise.all(u.map(async x=>{const w=f(x.contractAddress);return w?{name:w.name,symbol:w.symbol,decimals:w.decimals,logo:w.logo??null}:await o.request({method:"alchemy_getTokenMetadata",params:[x.contractAddress]})})),s?oa(n,u.map(x=>x.contractAddress)):void 0,s&&y.balanceFormatted>0?aa(n,y.symbol):void 0]);if(y.balance>0n){const x=Rs(n,`native:${y.symbol}`);h.push({...y,balanceUsd:(x?.price??0)*y.balanceFormatted,priceStatus:x?x.stale?"stale":"fresh":"unavailable"})}return u.forEach((x,w)=>{const b=g[w];if(!Number.isInteger(b.decimals)||b.decimals===null||b.decimals<0||b.decimals>255)throw new Error(`Invalid token metadata on chain ${t}`);const k=BigInt(x.tokenBalance),A=Number(N.formatUnits(k,b.decimals));if(k<=0n)return;const C=Rs(n,x.contractAddress),E=(C?.price??0)*A;h.push({address:N.getAddress(x.contractAddress),name:b.name||"Unknown",symbol:b.symbol||"UNKNOWN",decimals:b.decimals,balance:k,balanceFormatted:A,balanceUsd:E,priceStatus:C?C.stale?"stale":"fresh":"unavailable",isDiscovered:!f(x.contractAddress),logoURI:b.logo||void 0,isNative:!1,chainId:t})}),{tokens:yc(h,t),chainId:t}},bc=new Set,Gu=async(e,t,n=!0,s)=>{try{const r=oo(t,s?s[t]??"":void 0);if(r)try{return await Qu(e,t,r,n&&(typeof document>"u"||!document.hidden),s)}catch(o){bc.has(t)||(bc.add(t),console.warn(`Token discovery unavailable on chain ${t}; listing configured tokens only.`,o))}return await Hu(e,t,s)}catch(r){throw r}},Ks=async(e,t,n=[],s)=>{if(!e)throw new Error("Wallet address is required");const r=d.getChainsForAssets(s),o=t?.length?[...new Set(t)]:Object.keys(r).map(Number),a=await Promise.allSettled(o.map(l=>Gu(e,l,!0,s))),i={};return a.forEach((l,u)=>{const m=o[u];i[m]=l.status==="fulfilled"?l.value:{chainId:m,tokens:[],error:`Unable to refresh balances on chain ${m}`}}),(await Promise.allSettled(n.map(async l=>{const u=i[l.chainId];if(!u||u.error||u.tokens.some(w=>R.normalizeNativeTokenAddress(w.address).toLowerCase()===R.normalizeNativeTokenAddress(l.address).toLowerCase()))return;const m=d.getClientForChain(l.chainId,s),f=await Lu(m,l.address,l.decimals!==void 0&&l.symbol?{decimals:l.decimals,symbol:l.symbol,name:l.name||l.symbol,logo:l.logoURI}:void 0),h=await Vn.readContract(m,{address:l.address,abi:N.erc20Abi,functionName:"balanceOf",args:[e]});await Vu(l.chainId,[l.address],s);const y=Number(N.formatUnits(h,f.decimals)),g=oo(l.chainId,s?s[l.chainId]??"":void 0),x=g?Rs(g,l.address):void 0;u.tokens.push({...f,...l,name:f.name,symbol:f.symbol,decimals:f.decimals,balance:h,balanceFormatted:y,balanceUsd:(x?.price??0)*y,priceStatus:x?x.stale?"stale":"fresh":"unavailable",isNative:!1})}))).forEach((l,u)=>{if(l.status==="rejected"){const m=i[n[u].chainId];m&&(m.error=`Unable to refresh token balances on chain ${m.chainId}`)}}),i},kr=({address:e,supportedChains:t,fetchBalances:n=Ks,additionalTokens:s=[],enabled:r=!0,refreshInterval:o=0,priceEnabled:a=!0})=>{const i=p.useContext(d.SpiceFlowProviderContext),l=so(),u=e?.toLowerCase(),m=JSON.stringify([...i?.supportedChainIds??t??[]].sort((k,A)=>k-A)),f=JSON.stringify(s);p.useEffect(()=>l.registerTokens(s),[l,f]);const h=u&&u===i?.embeddedWalletAddress?.toLowerCase()?"embedded":"external",y=`wallet:${JSON.stringify([i?.network,i?.apiUrl,i?.rpcOverrides])}:${u}:${h}:${m}:${l.fetcherId(n)}`,g=p.useCallback(async()=>{let k;try{k=await n(u,JSON.parse(m),l.tokens(),i?.rpcOverrides)}catch(D){const S=D instanceof Error?D.message:"Unable to refresh balances";k=Object.fromEntries(JSON.parse(m).map(v=>[v,{chainId:v,tokens:[],error:S}]))}const A=l.entry(y).snapshot().assets,C=JSON.parse(m).map(D=>k[D]??{chainId:D,tokens:[],error:`Unable to refresh balances on chain ${D}`}),E=C.flatMap(D=>D.error?[D.error]:[]);return{assets:C.flatMap(D=>D.error?A.filter(S=>S.chainId===D.chainId).map(S=>({...S,balanceError:D.error,balanceStatus:"stale"})):D.tokens.map(S=>({...S,owner:u,location:h,_fundingWallet:h,_source:"wallet",positionId:`${u}:${h}:${D.chainId}:${R.normalizeNativeTokenAddress(S.address).toLowerCase()}`}))),error:E.length?E.join("; "):null}},[l,u,m,n,h,y]),x=ta(y,g,r&&!!u,o,l),w=JSON.stringify(t&&[...t].sort((k,A)=>k-A)),b=p.useMemo(()=>t?x.assets.filter(k=>t.includes(k.chainId)):x.assets,[x.assets,w]);return p.useEffect(()=>{a&&r&&u&&x.refresh()},[a]),{...x,assets:b,refreshAssets:l.invalidate,getAssetsByChain:p.useCallback(k=>b.filter(A=>A.chainId===k),[b]),getNativeAssets:p.useCallback(()=>b.filter(k=>k.isNative),[b])}};function Bs(e){const t=p.useContext(d.SpiceFlowProviderContext),n=so(),s=e.owner??((t?.mode||"7702")!=="7702"?t?.externalWalletAddress:t?.embeddedWalletAddress),r=s?.toLowerCase()!==t?.embeddedWalletAddress?.toLowerCase(),o=e.sourceChains??t?.supportedChainIds??[],a=(e.enabled??!0)&&!t?.isWhitelistGateActive,i=p.useMemo(()=>{const h=[...t?.additionalSourceTokens??[],...e.additionalSourceTokens??[],...e.destination?[e.destination]:[]];for(const y of e.supportedSourceAssets??[])for(const g of o){const x=d.getChainConfig(g)?.supportedTokens?.find(w=>d.isAssetAllowed(w,[y]));x&&h.push({...x,address:x.address,chainId:g,logoURI:x.logo})}return h},[e.destination,JSON.stringify(t?.additionalSourceTokens),JSON.stringify(e.additionalSourceTokens),JSON.stringify(e.supportedSourceAssets),JSON.stringify(o)]),l=kr({address:s,supportedChains:o,fetchBalances:Ks,additionalTokens:i,enabled:a&&e.includeWalletAssets!==!1,refreshInterval:3e4}),u=wc({address:s,supportedChains:o,enabled:a&&e.includeRollupAssets!==!1&&!!s&&s.toLowerCase()===t?.embeddedWalletAddress?.toLowerCase(),priceEnabled:a,refetchInterval:3e4}),m=p.useMemo(()=>a?[...(e.includeWalletAssets===!1?[]:l.assets).map(h=>({...h,owner:h.owner??s,location:h.location??(r?"external":"embedded"),_source:"wallet"})),...(e.includeRollupAssets===!1||s?.toLowerCase()!==t?.embeddedWalletAddress?.toLowerCase()?[]:u.assets).map(h=>({...h,owner:h.owner??s,location:"rollup",_source:"spice"}))]:[],[a,l.assets,u.assets,e.includeWalletAssets,e.includeRollupAssets,s,r,t?.embeddedWalletAddress]),f=p.useMemo(()=>m.map(h=>({asset:h,...Qn(h,e.role??"holding",{allowedTokens:t?.allowedTokens,rpcOverrides:t?.rpcOverrides,liquidityVenues:t?.liquidityVenues,isWhitelistGateActive:!!t?.isWhitelistGateActive},e.destination,e.supportedSourceAssets,{requiresEscrow:e.requiresEscrow})})),[m,t?.allowedTokens,t?.rpcOverrides,t?.liquidityVenues,t?.isWhitelistGateActive,e.role,e.destination,e.supportedSourceAssets,e.requiresEscrow]);return{positions:f,assets:p.useMemo(()=>f.filter(h=>h.eligible&&h.asset.balance>0n).map(h=>h.asset),[f]),walletAssets:p.useMemo(()=>m.filter(h=>h._source==="wallet"),[m]),rollupAssets:p.useMemo(()=>m.filter(h=>h._source==="spice"),[m]),loading:l.loading||u.loading,refreshing:l.refreshing||u.refreshing,error:l.error||u.error,refresh:n.invalidate}}function ao(e,t=!0,n){const s=n?.pendingOnly===!0,r=d.relayerService.getBaseUrl(),o=`${r}:${e?.toLowerCase()??""}:${s}`,[a,i]=p.useState({scope:o,actions:[],error:null,loading:t&&!!e,updatedAt:null,revision:0}),[l,u]=p.useState(0),m=p.useCallback(()=>u(h=>h+1),[]);p.useEffect(()=>{if(!t||!e){i(w=>w.scope===o&&w.actions.length===0&&!w.error&&!w.loading&&!w.updatedAt&&w.revision===0?w:{scope:o,actions:[],error:null,loading:!1,updatedAt:null,revision:0});return}const h=new AbortController,y=new d.RelayerService;y.setBaseUrl(r);let g;i(w=>({scope:o,actions:w.scope===o?w.actions:[],error:w.scope===o?w.error:null,loading:!0,updatedAt:w.scope===o?w.updatedAt:null,revision:w.scope===o?w.revision:0}));const x=async()=>{try{const w=await y.getWalletActions(e,{pendingOnly:s,signal:h.signal});h.signal.aborted||i(b=>({scope:o,actions:w,error:null,loading:!1,updatedAt:new Date().toISOString(),revision:b.scope===o?b.revision+1:1}))}catch(w){if(h.signal.aborted)return;const b=w instanceof d.SpiceflowError&&w.context.httpStatus===404;i(b&&!s?k=>({scope:o,actions:[],error:null,loading:!1,updatedAt:new Date().toISOString(),revision:k.scope===o?k.revision+1:1}):k=>({scope:o,actions:k.scope===o?k.actions:[],error:"Activity is temporarily unavailable. Refresh to check again.",loading:!1,updatedAt:k.scope===o?k.updatedAt:null,revision:k.scope===o?k.revision:0}))}h.signal.aborted||(g=setTimeout(x,5e3))};return x(),window.addEventListener("online",m),()=>{h.abort(),g&&clearTimeout(g),window.removeEventListener("online",m)}},[r,e,t,o,s,l,m]);const f=a.scope===o;return{actions:t&&e&&f?a.actions:[],error:f?a.error:null,loading:t&&!!e&&(!f||a.loading),updatedAt:f?a.updatedAt:null,revision:f?a.revision:0,refresh:m}}function ia(e){const t=p.useRef(0),n=p.useRef(null),s=p.useRef(e.run);s.current=e.run;const r=p.useRef(e.onSkip);r.current=e.onSkip;const o=p.useRef(e.onCleanup);o.current=e.onCleanup,p.useEffect(()=>{if(!e.shouldRun){t.current+=1,n.current?.abort(),r.current?.();return}let a=!1,i=!1;const l=async h=>{if(h&&i)return;n.current?.abort();const y=new AbortController;n.current=y;const g=++t.current;i=!0;try{await s.current({isBackground:h,isCurrent:()=>!a&&t.current===g,signal:y.signal})}finally{i=!1}},u=window.setTimeout(()=>void l(!1),e.delayMs??250),m=()=>{document.hidden||l(!0)},f=e.backgroundIntervalMs?window.setInterval(m,e.backgroundIntervalMs):void 0;return f!==void 0&&document.addEventListener("visibilitychange",m),()=>{a=!0,n.current?.abort(),clearTimeout(u),f!==void 0&&(window.clearInterval(f),document.removeEventListener("visibilitychange",m)),o.current?.()}},[e.shouldRun,e.delayMs,e.backgroundIntervalMs,...e.deps])}function vc(e,t){if(e.length!==t.length)return!1;const n=R.hashChainBatches(e),s=R.hashChainBatches(t);return n.every((r,o)=>r.hash===s[o]?.hash)}const Wn=e=>new Promise(t=>setTimeout(t,e)),Ku="0xa9059cbb";function Cc(e){const t=e.findIndex(r=>R.isSpicenetChainId(r.chainId));if(t<=0)return[];const n=new Map,s=(r,o,a)=>{if(a<=0n)return;const i=`${r}:${o.toLowerCase()}`,l=n.get(i);l?l.amount+=a:n.set(i,{chainId:r,token:o,amount:a})};for(const r of e.slice(0,t)){const o=R.getEscrowContract(r.chainId);if(!(!o||o===R.ZERO_ADDRESS)){for(const a of r.calls)if(a.value&&a.value>0n&&d.addressesEqual(a.to,o)&&s(r.chainId,R.ZERO_ADDRESS,a.value),!!a.data?.startsWith(Ku))try{const i=N.decodeFunctionData({abi:N.erc20Abi,data:a.data});if(i.functionName!=="transfer")continue;const[l,u]=i.args;d.addressesEqual(l,o)&&s(r.chainId,a.to,u)}catch{}}}return[...n.values()]}function kc(e){const t=R.getTokenByAddress(e.token,e.chainId);return[t?.equivalenceGroup,t?.symbol,t?.name]}function Sc(e,t){return pc(e,t.chainId,t.token,kc(t))}function Yu(e,t){const n=ju(e,t.chainId,t.token,kc(t));return!n||n.receiptDecimals>=n.chainDecimals?t.amount:R.convertAmountBetweenDecimals(R.convertAmountBetweenDecimals(t.amount,n.chainDecimals,n.receiptDecimals),n.receiptDecimals,n.chainDecimals)}async function Ic(e){const{deposits:t,baseline:n,fetchEntries:s,timeoutMs:r=12e4,intervalMs:o,signal:a,wait:i=Wn}=e;if(t.length===0)return!0;const l=new Map(t.map(f=>[f,Sc(n,f)])),u=Date.now(),m=u+r;for(;!a?.aborted;){try{const g=await s();if(t.every(x=>Sc(g,x)-l.get(x)>=Yu(g,x)))return!0}catch{}const f=Date.now();if(f>=m)return!1;const h=f-u,y=o??(h<5e3?250:h<15e3?1e3:3e3);await i(Math.min(y,m-f))}return!1}function ca(e,t){const n=R.hashChainBatches(e).map(s=>s.hash);return N.keccak256(N.encodeAbiParameters([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,t,n]))}async function la(e,t,n,s,r){if(s?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");const o={raw:ca(t,n)},a=r?await e.signMessage(o,r):await e.signMessage(o);console.debug("[SpiceFlow:execution]",{phase:"signature-returned",at:Date.now()});const i=typeof a=="string"?a:a.signature;if(!i)throw new d.SpiceflowError("SIGNATURE_FAILED","Failed to sign intent authorization. The wallet returned an empty signature.");return i}function Zu(e){return e.domain==="spicenet"||R.isSpicenetChainId(e.chainId)}const Ac=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;async function Xu(e,t,n){const s=(m,f)=>new d.SpiceflowError("SIGNATURE_FAILED","The wallet returned an invalid authorization. Review the action and try again.",{chainId:t.chainId,reason:m,...f?{cause:f}:{}});if(!e||typeof e!="object")throw s("missing-authorization");const r=e;for(const m of["address","contractAddress"])if(r[m]!==void 0&&(typeof r[m]!="string"||r[m].toLowerCase()!==t.address.toLowerCase()))throw s("authorization-target-mismatch");for(const m of["chainId","nonce"]){const f=r[m];if(f!==void 0&&(typeof f=="bigint"?f!==BigInt(t[m]):typeof f!="number"||!Number.isSafeInteger(f)||f!==t[m]))throw s(`authorization-${m}-mismatch`)}const{r:o,s:a,yParity:i}=r;if(typeof o!="string"||typeof a!="string"||!/^0x[0-9a-fA-F]{64}$/.test(o)||!/^0x[0-9a-fA-F]{64}$/.test(a)||i!==0&&i!==1||BigInt(o)===0n||BigInt(o)>=Ac||BigInt(a)===0n||BigInt(a)>Ac/2n)throw s("invalid-signature");const l={...t,r:o,s:a,yParity:i};let u;try{u=await N.recoverAddress({hash:N.keccak256(N.concatHex(["0x05",N.toRlp([N.toHex(t.chainId),t.address,t.nonce===0?"0x":N.toHex(t.nonce)])])),signature:l})}catch(m){throw s("invalid-signature",m)}if(u.toLowerCase()!==n.toLowerCase())throw s("authorization-signer-mismatch");return l}async function da(e){const{chainBatches:t,signingAddress:n,actions:s,cache:r,signal:o,onSignatureRequested:a,beforeSign:i}=e;if(o?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");if(typeof n!="string"||!N.isAddress(n,{strict:!1})||n.toLowerCase()===N.zeroAddress)throw new d.SpiceflowError("INVALID_PARAMS","A valid signing address is required.");for(const h of t)if(!Number.isSafeInteger(h.chainId)||h.chainId<=0)throw new d.SpiceflowError("INVALID_PARAMS","A valid authorization chain is required.");const l=[...new Set(t.filter(h=>!Zu(h)).map(h=>h.chainId))].map(h=>{const y=d.getDelegateContractAddress(h);if(!N.isAddress(y,{strict:!1})||y.toLowerCase()===N.zeroAddress)throw new d.SpiceflowError("INVALID_PARAMS","A valid delegation target is required.");return{chainId:h,client:d.getClientForChain(h),delegateContract:y}}),[u]=await Promise.all([Promise.all(l.map(async({chainId:h,client:y,delegateContract:g})=>{const x=Number(await R.getAccountNonce(n,y));if(!Number.isSafeInteger(x)||x<0)throw new d.SpiceflowError("INVALID_PARAMS","The authorization nonce is invalid.");const w=[n.toLowerCase(),h,g.toLowerCase(),x].join(":");return{chainId:h,delegateContract:g,nonce:x,cacheKey:w,cached:r?.get(w)}})),l.length?s.prepareSigning?.():void 0]);if(await i?.(),o?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");const m=[];let f=!1;for(const{chainId:h,delegateContract:y,nonce:g,cacheKey:x,cached:w}of u){if(w===void 0&&f&&await i?.(),o?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");const b=w===void 0?await s.signAuthorization({contractAddress:y,chainId:h,nonce:g},a):w;let k;try{k=await Xu(b,{address:y,chainId:h,nonce:g},n)}catch(A){throw r?.delete(x),A}if(o?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");f=!0,r?.set(x,k),m.push(k)}return m}const Ec=15;function Ju(e){return e.now-e.lastProgressAt>=e.pollTimeoutMs}function Fc(e,t){return{intentId:e,steps:t.map(n=>({...n,status:"pending"})),overallStatus:"processing"}}function io(e,t,n){const s=e.steps.map(i=>({...i})),r=s[t];if(!r)return e;n.status==="success"||n.status==="completed"?(s[t]={...r,status:"success",transactionHash:n.transactionHash},t+1<s.length&&s[t+1].status==="pending"&&(s[t+1]={...s[t+1],status:"processing"})):n.status==="reverted"||n.status==="error"?s[t]={...r,status:"failed",transactionHash:n.transactionHash,error:n.error}:s[t]={...r,status:"processing"};const o=s.some(i=>i.status==="failed"),a=s.every(i=>i.status==="success");return{...e,steps:s,overallStatus:o?"failed":a?"success":"processing"}}function $u({checkStepStatus:e,retryStep:t,maxRetries:n=3,pollingInterval:s=2500,pollTimeoutMs:r=3e5}){const[o,a]=p.useState(null),i=p.useRef(null),l=p.useRef(null),u=p.useRef(!1),m=p.useRef(!1),f=p.useRef(0),h=p.useRef({}),y=p.useRef(0),g=p.useCallback(C=>{i.current=C,a(C)},[]),x=p.useCallback(()=>{l.current&&(clearInterval(l.current),l.current=null)},[]),w=p.useCallback(()=>{f.current=0,h.current={},y.current=0,u.current=!0,x(),g(null)},[x,g]),b=p.useCallback((C,E)=>{x(),u.current=!1,g(Fc(C,E))},[x,g]),k=p.useCallback((C,E)=>{const D=i.current;D&&g(io(D,C,E))},[g]),A=p.useCallback((C,E)=>{x(),u.current=!1,m.current=!1,f.current=0,h.current={},y.current=Date.now(),g(Fc(C,E));const D=async()=>{if(!(u.current||m.current||!e)){m.current=!0;try{if(Ju({now:Date.now(),lastProgressAt:y.current,pollTimeoutMs:r})){const F=i.current;F&&g({...F,steps:F.steps.map(O=>O.status==="success"?O:{...O,status:"failed",error:"Taking longer than expected. It may still complete - check the explorer, then refresh."}),overallStatus:"failed"}),u.current=!0,x();return}const S=i.current;if(!S)return;const v=S.steps.findIndex(F=>F.status!=="success");if(v===-1){u.current=!0,x();return}if(!(v===0||S.steps[v-1].status==="success"))return;try{const F=S.steps[v].stepId,{data:O}=await e(C,F);if(f.current=0,O.status==="success"&&(y.current=Date.now()),O.status==="reverted"){const q=h.current[F]||0;if(t&&q<n){h.current[F]=q+1;try{await t(C,F)}catch(I){console.error(`[intentStatus] retry failed for step ${F}:`,I)}g(io(i.current,v,{status:"executing"}));return}}const j=io(i.current,v,O);g(j),j.overallStatus!=="processing"&&(u.current=!0,x())}catch(F){f.current+=1,console.error(`[intentStatus] poll error (${f.current}/${Ec}):`,F),f.current>=Ec&&(g(io(i.current,v,{status:"error"})),u.current=!0,x())}}finally{m.current=!1}}};D(),l.current=setInterval(D,s)},[e,t,n,s,r,x,g]);return p.useEffect(()=>()=>x(),[x]),{intentStatus:o,startStatusPolling:A,beginStatusTracking:b,applyStepUpdate:k,stopStatusPolling:x,clearStatus:w}}function _u(e,t){return(t||"").trim()||`Transaction ${e}. The transaction was rejected on-chain. This may be due to insufficient balance, price changes, or health factor constraints. Please verify your positions and try again.`}const ep=350,tp=2500;async function Tc(e){const{actionId:t,intentIndex:n,intentId:s,stepIndex:r,maxPolls:o=48,maxExecuteAttempts:a=3,pollsBeforeRetry:i=5,maxConsecutiveStatusErrors:l=15,onStatusMessage:u,onStepUpdate:m,signal:f,chainId:h,startWithExecute:y=!0,observeOnly:g=!1,relayer:x=d.relayerService,completeOnExecution:w=!1}=e;if(f?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");let b="pending",k,A,C=e.initialExecuteAttempts??0,E=0,D,S;const v=new Promise((O,j)=>{D=O,S=()=>j(new d.SpiceflowError("ABORT","Execution transaction aborted"))}),F=()=>{C++,e.onExecuteAttempt?.(C),x.executeStep(t,n,r,{action:"execute"}).then(O=>{O.transactionHash&&(k=O.transactionHash),O.status==="success"&&D({status:O.status,transactionHash:O.transactionHash})}).catch(O=>{const j=O instanceof Error?O.message:String(O);console.warn(`[execution] executeStep ${r} attempt ${C} error (will poll):`,j)})};f?.addEventListener("abort",S,{once:!0});try{y&&!g&&C<a&&F();for(let O=0;O<o;O++){const j=O===0?ep:tp;try{const I=await Promise.race([Wn(j).then(()=>{}),v]);if(f?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");const B=I??await Promise.race([x.checkStepStatus(s,r,w).then(M=>M.data),v]);if(f?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");E=0,b=B.status,A=B.error;const T=B.transactionHash;T&&(k=T),w&&/^0x[0-9a-f]{64}$/i.test(T??"")&&(B.executionStatus==="success"||B.executionStatus==="reverted")&&(b=B.executionStatus,A=void 0),m?.({status:b,transactionHash:k,error:A})}catch(I){if(I instanceof Error&&(I.name==="AbortError"||I instanceof d.SpiceflowError&&I.code==="ABORT"))throw I;if(E++,E>=l){if(!g)throw I;u?.("Status is temporarily unavailable. The backend continues this action.",k)}continue}if(!g&&b==="created"&&O>=C*i&&C<a&&F(),b==="reverted"||b==="error")throw new d.SpiceflowError("ON_CHAIN_REVERT",_u(b,A),{status:b,txHash:k,actionId:t,intentId:s,stepId:r,chainId:h});if(b==="success"||b==="completed")return k;let q="Waiting for solver...";b==="executing"?q="Transaction executing...":b==="submitted"?q="Transaction submitted...":b==="created"&&(q="Waiting for relayer..."),u?.(q,k)}throw new d.SpiceflowError("POLLING_EXHAUSTED",`Transaction is still processing (status: ${b}). This doesn't mean it failed \u2014 the solver may still complete it. Check your positions in a few minutes, or try refreshing the page.`,{actionId:t,intentId:s,stepId:r,lastStatus:b,pollAttempts:o,maxPolls:o,txHash:k})}finally{f?.removeEventListener("abort",S)}}async function np(e){const{actionId:t,intentIndex:n,intentId:s,totalSteps:r,observeOnly:o,delayBeforeSpicenetStepMs:a=5e3,isSpicenetStep:i,beforeStep:l,maxExecuteAttemptsForStep:u,maxPolls:m=48,onStatusMessage:f,onStepUpdate:h,signal:y}=e;let g;for(let x=e.startStep??0;x<r;x++){if(!o&&x>0&&i?.(x)&&a>0&&await Wn(a),o||await l?.(x),y?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");const w=u?.(x)??3,b=await Tc({actionId:t,intentIndex:n,intentId:s,stepIndex:x,observeOnly:o,startWithExecute:e.startWithExecute,relayer:e.relayer,maxPolls:m,maxExecuteAttempts:w,initialExecuteAttempts:e.executeAttempts?.get(x),onExecuteAttempt:k=>e.executeAttempts?.set(x,k),maxConsecutiveStatusErrors:w===6?5:15,onStatusMessage:f,onStepUpdate:h?k=>h(x,k):void 0,signal:y,completeOnExecution:x===r-1&&i?.(x)===!1});b&&(g=b)}return g}const sp="0xa9059cbb",rp=[R.SPICE_COMBINED_FEE_RECIPIENT,R.SPICE_GAS_FEE_RECIPIENT,R.SPICE_PLATFORM_FEE_RECIPIENT];function Rc(e){return rp.some(t=>d.addressesEqual(e,t))}function co(e,t){return e.map(n=>{if(n.domain==="spicenet"||R.isSpicenetChainId(n.chainId)||n.calls.length===0)return n;const s=new Set((n.tokenTransfers??[]).filter(a=>(a.from==="escrow"||a.from==="solver")&&d.addressesEqual(a.to,t)).map(a=>a.token.toLowerCase()));if(s.size===0)return n;const r=[...s].some(R.isNativeToken);let o=0;for(const a of n.calls){if(r&&a.value>0n&&a.data==="0x"&&Rc(a.to)){o+=1;continue}if(!a.data?.startsWith(sp))break;try{const i=N.decodeFunctionData({abi:N.erc20Abi,data:a.data});if(i.functionName!=="transfer")break;const[l]=i.args;if(!Rc(l)||!s.has(a.to.toLowerCase()))break;o+=1}catch{break}}return o===0?n:{...n,calls:n.calls.slice(o)}})}async function ua(e,t,n){if(!t||!/^0x[0-9a-f]{64}$/i.test(t))throw new Error("The destination receipt is not available yet; reconcile the existing action before retrying.");const s=()=>new d.SpiceflowError("ABORT","Execution observation retired");if(n?.aborted)throw s();const r=await new Promise((o,a)=>{const i=()=>a(s());n?.addEventListener("abort",i,{once:!0}),Promise.resolve().then(()=>e.waitForTransactionReceipt({hash:t,timeout:12e4,pollingInterval:2e3,confirmations:1})).then(o,a).finally(()=>n?.removeEventListener("abort",i))});if(n?.aborted)throw s();if(r.transactionHash?.toLowerCase()===t.toLowerCase()&&r.status==="reverted")throw new d.SpiceflowError("ON_CHAIN_REVERT","The destination transaction reverted.",{status:"reverted",txHash:t});if(r.transactionHash?.toLowerCase()!==t.toLowerCase()||r.status!=="success")throw new Error("The destination transaction has not been confirmed successfully. Reconcile the existing action before retrying.");return t}async function lo(e){let t=e.hash,n=!1;const s=Date.now()+12e4,r=a=>a.transactionHash&&a.transactionHash.toLowerCase()!==t.toLowerCase();let o=await e.client.waitForTransactionReceipt({hash:t,timeout:12e4,pollingInterval:2e3,confirmations:1,onReplaced:a=>{const i=a.transaction,l=a.replacedTransaction;if(!(a.reason==="repriced"&&l?.hash?.toLowerCase()===t.toLowerCase()&&l?.to?.toLowerCase()===e.call.to.toLowerCase()&&(l.input??"0x").toLowerCase()===e.call.data.toLowerCase()&&BigInt(l.value??0)===e.call.value&&l?.from&&l.nonce!==void 0&&/^0x[0-9a-f]{64}$/i.test(i?.hash??"")&&i?.to?.toLowerCase()===e.call.to.toLowerCase()&&(i.input??"0x").toLowerCase()===e.call.data.toLowerCase()&&BigInt(i.value??0)===e.call.value&&i.from?.toLowerCase()===l?.from?.toLowerCase()&&i.nonce===l?.nonce)){n=!0,e.onCancelled?.();return}t=i.hash,e.onRepriced?.(t)}});if(n)throw new Error("Transaction was cancelled or replaced with a different action; retry the unfinished action");if((e.confirmations??1)>1&&!r(o)&&o.status==="success"&&(o=await e.client.waitForTransactionReceipt({hash:t,timeout:Math.max(s-Date.now(),1),pollingInterval:2e3,confirmations:e.confirmations})),r(o))throw new Error("Unexpected transaction receipt; recover the submitted transaction before retrying");return{receipt:o,hash:t}}const pa=10n,op=5;function uo(e,t,n){return n?.calls.length&&n.amountOutMinimum>0n?[{chainId:e,token:t,amount:n.amountOutMinimum}]:[]}function fa(e){return e.map(t=>({...t,calls:[...t.calls],tokenTransfers:t.tokenTransfers?[...t.tokenTransfers]:void 0}))}function po({token:e,recipient:t,amount:n}){return{to:e,value:0n,data:N.encodeFunctionData({abi:N.erc20Abi,functionName:"transfer",args:[t,n]})}}function ap({chainBatches:e,token:t,amount:n}){const s=fa(e),r=s[s.length-1];if(!r)return s;const o=R.getEscrowContractAddress(r.chainId);return r.calls=[...r.calls,po({token:t,recipient:o,amount:n})],s}function Bc({chainBatches:e,user:t,token:n,grossAmount:s,gasFee:r,policy:o}){const a=fa(e),i=a[a.length-1];if(!i)throw new d.SpiceflowError("INVALID_PARAMS","Action-output escrow funding requires at least one chain batch.");const l=d.calculateBpsFee(s,BigInt(o?.platformBps??pa)),u=r+l;if(u>=s)throw new d.SpiceflowError("INVALID_PARAMS","Borrow amount is too small after gas and Spicenet fees.",{grossAmount:s.toString(),gasFee:r.toString(),spicenetFee:l.toString()});const m=s-u,f=R.getEscrowContractAddress(i.chainId),h=[];return r>0n&&h.push(po({token:n,recipient:o?.gasRecipient??R.SPICE_GAS_FEE_RECIPIENT,amount:r})),l>0n&&h.push(po({token:n,recipient:o?.platformRecipient??R.SPICE_PLATFORM_FEE_RECIPIENT,amount:l})),i.calls=[...i.calls,...h,po({token:n,recipient:f,amount:m})],i.tokenTransfers=[...i.tokenTransfers??[],...r>0n?[{from:t,to:R.SPICE_GAS_FEE_RECIPIENT,token:n,amount:r}]:[],...l>0n?[{from:t,to:R.SPICE_PLATFORM_FEE_RECIPIENT,token:n,amount:l}]:[],{from:t,to:f,token:n,amount:m}],{chainBatches:a,gasFee:r,spicenetFee:l,netEscrowAmount:m,outputCredit:{chainId:i.chainId,token:n,amount:s}}}async function Oc({chainBatches:e,user:t,token:n,grossAmount:s,chainAuthorizations:r}){let o=0n,a,i=Bc({chainBatches:e,user:t,token:n,grossAmount:s,gasFee:o});for(let l=0;l<op;l+=1){const u=R.hashChainBatches(i.chainBatches),m=await d.relayerService.estimateBatchGas({user:t,outputToken:n,chainBatches:i.chainBatches.map((h,y)=>({...h,hash:u[y].hash})),chainAuthorizations:r}),f=m.gasFee;if(f===o&&JSON.stringify(m.policy)===JSON.stringify(a))return i;a=m.policy,o=f,i=Bc({chainBatches:e,user:t,token:n,grossAmount:s,gasFee:o,policy:a})}throw new d.SpiceflowError("INVALID_PARAMS","Action-output fee estimate did not converge. Please retry.")}function $n(e){return R.isSpicenetChainId(e.chainId)}const ip="0xa9059cbb";function Sr(e,t){return`${e}:${R.normalizeNativeTokenAddress(t).toLowerCase()}`}function jc(e,t){return t===R.ZERO_ADDRESS.toLowerCase()?{symbol:d.getChainName(e),decimals:18}:R.getTokenByAddress(t,e)??{symbol:"tokens",decimals:18}}function cp(e,t){const n=R.getTokenByAddress(t,e);return[n?.equivalenceGroup,n?.symbol,n?.name]}async function ma(e){return d.getWalletBalanceEntries(e)}async function ha(e,t,n){const s=new Map,r=new Map,o=[...n?.walletFundingRequirement?[n.walletFundingRequirement]:[],...n?.walletFundingRequirements??[]];for(const f of o){if(f.amount<0n)throw new Error("Accepted wallet funding must not be negative");const h=Sr(f.chainId,f.token);r.set(h,(r.get(h)??0n)+f.amount),s.set(h,0n)}const a=new Map,i=new Map,l=new Map,u=new Map;for(const f of n?.actionOutputCredits??[]){const h=Sr(f.chainId,f.token);u.set(h,(u.get(h)??0n)+f.amount)}for(const f of e){if($n(f))continue;for(const g of f.tokenTransfers??[]){if(g.from!=="escrow"&&g.from!=="solver"||!d.addressesEqual(g.to,t))continue;const x=BigInt(g.amount??0);if(x<=0n)continue;const w=Sr(f.chainId,g.token);a.set(w,(a.get(w)??0n)+x),g.from==="escrow"&&i.set(w,(i.get(w)??0n)+x)}const h=R.getEscrowContract(f.chainId),y=g=>!!h&&h!==R.ZERO_ADDRESS&&d.addressesEqual(g,h);for(const g of f.calls){if(g.value&&g.value>0n){const x=Sr(f.chainId,R.ZERO_ADDRESS);s.set(x,(s.get(x)??0n)+g.value),y(g.to)&&l.set(x,(l.get(x)??0n)+g.value)}if(g.data?.startsWith(ip))try{const x=N.decodeFunctionData({abi:N.erc20Abi,data:g.data});if(x.functionName!=="transfer")continue;const[w,b]=x.args,k=g.to.toLowerCase(),A=Sr(f.chainId,k);s.set(A,(s.get(A)??0n)+b),y(w)&&l.set(A,(l.get(A)??0n)+b)}catch{}}}let m=null;for(const[f,h]of i){const y=h-(l.get(f)??0n);if(y<=0n)continue;const[g,x]=f.split(":"),w=Number(g),b=jc(w,x);m??(m=await ma(t));const k=pc(m,w,x,cp(w,x));if(!(k>=y))throw new d.SpiceflowError("INVALID_PARAMS",`Insufficient Spice ${b.symbol}: needs ${N.formatUnits(y,b.decimals)}, has ${N.formatUnits(k,b.decimals)}.`,{chainId:w,token:x,userAddress:t,requiredAmount:y.toString(),balance:k.toString(),balanceSource:"spice"})}for(const[f,h]of s){const[y,g]=f.split(":"),x=Number(y);let w=h-(a.get(f)??0n)-(u.get(f)??0n);const b=r.get(f)??0n;if(b>w&&(w=b),w<=0n)continue;const k=d.getClientForChain(x),A=g===R.ZERO_ADDRESS.toLowerCase()?await k.getBalance({address:t}):await k.readContract({address:g,abi:N.erc20Abi,functionName:"balanceOf",args:[t]});if(A>=w)continue;const C=jc(x,g);throw new d.SpiceflowError("INVALID_PARAMS",`Insufficient ${C.symbol} on ${d.getChainName(x)}: needs ${N.formatUnits(w,C.decimals)}, has ${N.formatUnits(A,C.decimals)}.`,{chainId:x,token:g,userAddress:t,requiredAmount:w.toString(),balance:A.toString(),balanceSource:"wallet"})}}function lp({chainBatches:e,tokenAddress:t,tokenTransferAmount:n,useCustomTransfers:s}){if(!(e.some($n)||!(s?e.some(r=>$n(r)?!1:(r.tokenTransfers??[]).some(o=>o.from==="escrow"&&BigInt(o.amount??0)>0n)):n>0n)))throw new d.SpiceflowError("INVALID_PARAMS","Payouts funded from Spice balance require a Spicenet funding batch before the destination chain batch. Deposits into Spice balance and gas-only actions do not need one.",{tokenAddress:t,tokenTransferAmount:n.toString(),useCustomTransfers:!!s})}function dp(e,t,n,s){t.forEach((r,o)=>{if(!r.to||!r.from||!r.token||r.amount===void 0)throw new d.SpiceflowError("INVALID_TOKEN_TRANSFER",`tokenTransfers[${o}] on chain ${e} is missing required fields (to/from/token/amount). This usually means the embedded wallet wasn't ready when the intent was built \u2014 please retry.`,{chainId:e,transferIndex:o,transfer:{from:r.from,to:r.to,token:r.token,amount:r.amount?.toString()},signingAddress:n,useCustomTransfers:s})})}function fo({user:e,chainBatches:t,tokenAddress:n,tokenTransferAmount:s,exp:r,signature:o,chainAuthorizations:a,useCustomTransfers:i}){const l=t,u=R.hashChainBatches(l),m=l.filter(f=>!$n(f)).length;if(lp({chainBatches:l,tokenAddress:n,tokenTransferAmount:s,useCustomTransfers:i}),!i&&s>0n&&m>1)throw new d.SpiceflowError("INVALID_PARAMS","Multiple non-Spicenet batches require explicit tokenTransfers. Pass useCustomTransfers with per-batch transfers instead of relying on the default escrow payout injection.",{nonSpicenetBatchCount:m,tokenAddress:n,tokenTransferAmount:s.toString()});return{user:e,...a?{chainAuthorizations:a}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:o,nbf:0,exp:r,chainBatches:u.map((f,h)=>{const y=l[h],g=$n(y)?[]:i?y.tokenTransfers??[]:s>0n?[{from:"escrow",to:e,token:n,amount:s}]:[];return dp(Number(f.chainId),g,e,i),{hash:f.hash,chainId:Number(f.chainId),tokenTransfers:g,calls:f.calls}})}]}}function Dc(e,t){const n=t?.depositToEscrow?.gasFundingSource==="action-output"?t.depositToEscrow:null,s=t?.depositToEscrow&&!n?ap({chainBatches:e,token:t.depositToEscrow.token,amount:t.depositToEscrow.amount}):fa(e);return{actionOutputDeposit:n,batches:s}}let ga=!1;function Ys(){const{address:e,isConnected:t,isAuthenticated:n,actions:s}=d.useWallet(),r=p.useRef(null),o=p.useRef(0),a=p.useRef(null),{intentStatus:i,startStatusPolling:l,beginStatusTracking:u,applyStepUpdate:m,clearStatus:f}=$u({checkStepStatus:(A,C)=>d.relayerService.checkStepStatus(A,C),retryStep:async(A,C)=>{const[E,D]=A.split("/"),S=parseInt(D||"0",10);await d.relayerService.executeStep(E,S,C,{action:"execute"})}}),h=p.useCallback(()=>{o.current++,a.current=null,f()},[f]),y=p.useRef(s),g=p.useRef(new Map);y.current=s;const x=p.useCallback((A,C,E,D,S)=>da({chainBatches:A,signingAddress:C,actions:y.current,cache:g.current,signal:E,onSignatureRequested:D,beforeSign:S}),[]),w=p.useCallback((A,C,E,D)=>la(y.current,A,C,E,D),[]),b=p.useCallback(async(A,C,E,D,S,v)=>{let F={},O={};const j=(I,B,T)=>{T?.actionId&&(F={actionId:T.actionId,intentId:T.intentId,intentIndex:T.intentIndex,totalSteps:T.totalSteps,autoContinue:T.autoContinue,user:v?.userOverride||e}),D?.({step:I,message:B,...O,...F,...T})};if(ga)throw new d.SpiceflowError("CONCURRENT_EXECUTION","A execution transaction is already in progress. Please wait.");ga=!0;const q=o.current;try{if(!e)throw new d.SpiceflowError("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const I=v?.userOverride||e,B=d.relayerService.getBaseUrl(),T=a.current;if(T&&d.addressesEqual(T.user,I)&&T.apiUrl===B){if(T.resume)return await T.resume(A,C,E,S,D,v);throw T.error}a.current=null;const M=Ce=>R.hashConditionalExecutionPlan(Ce.map(Re=>({...Re,tokenTransfers:Re.tokenTransfers??[]})),[]),P=M(A),z=Ce=>new Map(Object.entries(Ce??{}).filter(([Re,ke])=>Re!=="signal"&&(typeof ke!="function"||["prepareForSigning","adjustBatchesForEstimate","resolveActionOutputCredits"].includes(Re))).map(([Re,ke])=>[Re,typeof ke=="function"?ke:JSON.stringify(ke,(qe,xe)=>typeof xe=="bigint"?xe.toString():xe)])),Q=z(v),Z=await d.relayerService.supportsAutomaticContinuation({signal:S}),{actionOutputDeposit:se,batches:X}=Dc(A,v);let K=X,re=[],$=v?.useCustomTransfers,pe=Cc(K),we=null;const ge=async()=>{(v?.walletFundingRequirement||v?.walletFundingRequirements?.length)&&await ha([],I,{walletFundingRequirement:v?.walletFundingRequirement,walletFundingRequirements:v?.walletFundingRequirements});for(let Ce=0;pe.length>0&&Ce<3;Ce++)try{we=await ma(I);break}catch(Re){if(S?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");if(Ce===2)throw new d.SpiceflowError("RELAYER_ERROR","Unable to read your Spice balance. Please try again before submitting the transaction.",{cause:Re});await Wn(1e3)}await v?.validateBeforeSubmit?.(K)};j("building","Preparing your wallet and transaction...");const be=await x(K,I,S,()=>j("signing-delegation","Confirm the authorization in your wallet..."),ge);if(j("building","Checking transaction fees and balances..."),S?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");const _=BigInt(Math.floor(Date.now()/1e3)+3600);if(se){const Ce=await Oc({chainBatches:A,user:I,token:se.token,grossAmount:se.amount,chainAuthorizations:be});K=Ce.chainBatches,re=[Ce.outputCredit],$=!0}if(!v?.skipPreSubmitFeeEstimate){let Ce=!1;if(v?.feeExecutionMode==="user-transfer"&&v.adjustBatchesForEstimate&&d.relayerService.canValidateActionFees()){const Re=await d.relayerService.validateActionFees(fo({user:I,chainBatches:K,tokenAddress:C,tokenTransferAmount:E,exp:Number(_),signature:"0x00",chainAuthorizations:be,useCustomTransfers:$}),{signal:S});r.current=Re;const ke=await v.adjustBatchesForEstimate({feeEstimate:Re,chainBatches:K});Ce=!ke||vc(K,ke),ke&&(K=ke)}for(let Re=0;!Ce&&Re<10;Re++){const ke=v?.feeExecutionMode==="user-transfer"?co(K,I):K,qe=fo({user:I,chainBatches:ke,tokenAddress:C,tokenTransferAmount:E,exp:Number(_),signature:"0x00",chainAuthorizations:be,useCustomTransfers:$}),xe=await d.relayerService.estimateActionFees(qe,{signal:S});r.current=xe;const Pe=await v?.adjustBatchesForEstimate?.({feeEstimate:xe,chainBatches:K}),lt=!!Pe&&vc(K,Pe);if(!Pe||lt){Ce=!0;break}K=Pe}if(!Ce)throw new d.SpiceflowError("INVALID_PARAMS","Fee estimate did not converge. Please retry.")}if(v?.prepareForSigning){const Ce=await v.prepareForSigning(K);if(Ce.length!==K.length||Ce.some((Re,ke)=>Re.chainId!==K[ke].chainId||Re.domain!==K[ke].domain))throw new Error("The funded route changed before signing");K=Ce}v?.resolveActionOutputCredits&&(re=await v.resolveActionOutputCredits()),(!v?.skipUserFundingPreflight||v.walletFundingRequirement||v.walletFundingRequirements?.length)&&await ha(v?.skipUserFundingPreflight?[]:K,I,{actionOutputCredits:re,walletFundingRequirement:v?.walletFundingRequirement,walletFundingRequirements:v?.walletFundingRequirements}),pe=Cc(K),pe.length&&!we&&(we=await d.getWalletBalanceEntries(I)),await v?.validateBeforeSubmit?.(K),j("building","Preparing the signing request...");const G=await w(K,_,S,()=>j("signing-intent","Confirm the transaction in your wallet..."));if(S?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");if(B!==d.relayerService.getBaseUrl())throw new d.SpiceflowError("RELAYER_ERROR","The network changed before submission. Review your balances before trying again.");const ae=fo({user:I,chainBatches:K,tokenAddress:C,tokenTransferAmount:E,exp:Number(_),signature:G,chainAuthorizations:be,useCustomTransfers:$});let W=K.length-1;for(;W>=0&&$n(K[W]);)W--;O={totalSteps:K.length},W>=0&&(O={...O,destinationChainId:Number(K[W].chainId),destinationStepIndex:W});const De=Date.now();if(j("submitting","Submitting to relayer..."),await v?.validateBeforeSubmit?.(K),S?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");if(B!==d.relayerService.getBaseUrl())throw new d.SpiceflowError("RELAYER_ERROR","The network changed before submission. Review your balances before trying again.");console.debug("[SpiceFlow:execution]",{phase:"submit-check-complete",at:Date.now(),durationMs:Date.now()-De});const Te=K.length;let L;try{L=await d.relayerService.createAction({...ae,...v?.externalExecution?{externalExecution:v.externalExecution}:{}},{autoContinue:Z,idempotencyKey:v?.idempotencyKey,signal:S,onAccepted:Ce=>{const[Re,ke="0"]=Ce.intentIds[0].split("/"),qe=parseInt(ke,10);j("executing","Executing on chain...",{actionId:Re,intentId:`${Re}/${qe}`,intentIndex:qe,totalSteps:Te,autoContinue:Ce.autoContinue===!0})}})}catch(Ce){throw q===o.current&&Ce instanceof d.SpiceflowError&&Ce.context.submissionStatus==="unknown"&&(a.current={user:I,apiUrl:B,error:Ce}),Ce}const[H,te]=L.intentIds[0].split("/"),ie=parseInt(te||"0",10),J=`${H}/${ie}`;j("executing","Executing on chain..."),j("executing","Executing on chain...",{actionId:H,intentId:J,intentIndex:ie,totalSteps:K.length,autoContinue:L.autoContinue===!0});const ce=new d.RelayerService;ce.setBaseUrl(B);let Be,Ie=0;const ve=new Map,Ze=async(Ce,Re=D,ke=!1)=>{const qe=(xe,Pe,lt)=>Re?.({step:xe,message:Pe,...lt});try{if((!ke||!Be)&&(Be=await np({actionId:H,intentIndex:ie,intentId:J,totalSteps:Te,signal:Ce,observeOnly:L.autoContinue===!0,startWithExecute:!ke,startStep:ke?Ie:0,executeAttempts:ve,onStepUpdate:(xe,Pe)=>{(Pe.status==="success"||Pe.status==="completed")&&(Ie=Math.max(Ie,xe+1))},relayer:L.autoContinue||ke?ce:d.relayerService,...we?{delayBeforeSpicenetStepMs:0}:{},isSpicenetStep:xe=>$n(K[xe]),beforeStep:async xe=>{if(L.autoContinue===!0||!we||!$n(K[xe]))return;const Pe=await Ic({deposits:pe,baseline:we,fetchEntries:()=>ma(I),signal:Ce});if(Ce?.aborted)throw new d.SpiceflowError("ABORT","Execution transaction aborted");if(!Pe)throw new d.SpiceflowError("POLLING_EXHAUSTED","Your deposit is still waiting for Spice credit. Check this transaction's status before trying again.",{actionId:H,intentId:J,stepId:xe})},maxExecuteAttemptsForStep:xe=>$n(K[xe])?6:3,maxPolls:L.autoContinue?Number.POSITIVE_INFINITY:180,onStatusMessage:(xe,Pe)=>{qe("executing",xe,{txHash:Pe,actionId:H,intentId:J,intentIndex:ie,totalSteps:Te,autoContinue:L.autoContinue===!0})}})),v?.requireDestinationReceipt){const xe=[...K].reverse().find(Pe=>!$n(Pe));if(!xe)throw new Error("The action has no destination transaction to verify.");await ua(d.getClientForChain(xe.chainId),Be,Ce)}return qe("success","Transaction successful!",{txHash:Be,actionId:H,intentId:J,intentIndex:ie,totalSteps:Te,autoContinue:L.autoContinue===!0}),a.current?.resume===Ne&&(a.current=null),Be||H}catch(xe){if(xe instanceof d.SpiceflowError&&xe.code==="ON_CHAIN_REVERT"&&xe.context.status==="reverted"&&(xe.context.stepId===0||Te===1))throw a.current?.resume===Ne&&(a.current=null),xe;const Pe=new d.SpiceflowError(xe instanceof d.SpiceflowError?xe.code:"RELAYER_STATUS_ERROR",xe instanceof d.SpiceflowError&&xe.code==="ON_CHAIN_REVERT"?xe.message:`Your action was accepted, but its completion could not be confirmed. Check the original action before trying again. ${xe instanceof Error?xe.message:""}`.trim(),{...xe instanceof d.SpiceflowError?xe.context:{},submissionStatus:"accepted",actionId:H,intentId:J,txHash:Be,cause:xe});throw q===o.current&&(a.current={user:I,apiUrl:B,error:Pe,resume:Ne}),Pe}},Ne=async(Ce,Re,ke,qe,xe,Pe)=>{const lt=z(Pe);if(P!==M(Ce)||Q.size!==lt.size||[...Q].some(([Qe,Xe])=>lt.get(Qe)!==Xe)||!d.addressesEqual(C,Re)||E!==ke)throw a.current.error;return Ze(qe,xe,!0)};return await Ze(S,D)}catch(I){throw console.error("[Execution] Error:",I),j("error",I.message||"Transaction failed",{error:I.message,...I?.context?.submissionStatus==="unknown"?{submissionStatus:"unknown",...typeof I.context.idempotencyKey=="string"&&/^0x[0-9a-f]{64}$/i.test(I.context.idempotencyKey)?{idempotencyKey:I.context.idempotencyKey}:{},...typeof I.context.user=="string"&&/^0x[0-9a-f]{40}$/i.test(I.context.user)?{user:I.context.user}:{}}:{}}),I}finally{ga=!1}},[e,n,x,w]),k=p.useCallback(async(A,C,E,D)=>{if(!e&&(!D?.userOverride||D.signAuthorizationsForEstimate))throw new d.SpiceflowError("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const S=D?.userOverride||e,v=D?.validateFeeCalls===!0&&D.feeExecutionMode==="user-transfer"&&d.relayerService.canValidateActionFees(),{actionOutputDeposit:F,batches:O}=Dc(A,D);let j=O;const q=D?.feeExecutionMode==="user-transfer"&&!v?co(j,S):j,I=D?.signAuthorizationsForEstimate?await x(q,S):void 0;let B=D?.useCustomTransfers;F&&(j=(await Oc({chainBatches:A,user:S,token:F.token,grossAmount:F.amount,chainAuthorizations:I})).chainBatches,B=!0);const T=D?.feeExecutionMode==="user-transfer"&&!v?co(j,S):j,M=fo({user:S,chainBatches:T,tokenAddress:C,tokenTransferAmount:E,exp:Math.floor(Date.now()/1e3)+3600,signature:"0x00",chainAuthorizations:I,useCustomTransfers:B}),P=await(v?d.relayerService.validateActionFees(M,{signal:D?.signal}):d.relayerService.estimateActionFees(M,{signal:D?.signal}));return r.current=P,P},[e,x]);return{execute:b,estimate:k,lastFeeEstimate:r.current,hasEmbeddedWallet:t&&n,intentStatus:i,startStatusPolling:l,beginStatusTracking:u,applyStepUpdate:m,clearStatus:h}}function Zt(e,t,n,s){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const r=10n**BigInt(t-n);return s==="ceil"?(e+r-1n)/r:e/r}function dn(e,t){if(!Number.isInteger(t)||t<0||t>255)throw new Error("Invalid token decimals");if(!/^\d+(?:\.\d*)?$/.test(e))throw new Error("Enter a valid amount.");if((e.split(".")[1]?.replace(/0+$/,"")??"").length>t)throw new Error(`Use at most ${t} decimal places for this source.`);return N.parseUnits(e,t)}function on(e,t,n){const s=Zt(e,t,n,"floor");if(Zt(s,n,t,"floor")!==e)throw new Error(`Use at most ${n} decimal places for this delivered token.`);return s}function up(e){return`0x77${e.slice(4)}`}function Ir({userAddress:e,destinationChainId:t,deliveryToken:n,deliveryAmount:s,withdrawalAmount:r,deliveryRecipient:o,deliveryTransfers:a,requestTimestampMs:i,expiresAt:l,metadata:u,requestNonce:m}){if(l!==void 0&&(!Number.isSafeInteger(l)||l<=0))throw new Error("Withdrawal expiry must be a positive Unix timestamp in seconds");const f=a?.length?a:[{token:n,recipient:o,amount:r??s}],h=f.reduce((b,k)=>b+k.amount,0n);if(h<=0n)return null;const y=i??Date.now(),g=BigInt(Math.floor(y/1e3)),x=e??o,w=up(N.keccak256(N.encodeAbiParameters([{type:"address"},{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"},...m?[{type:"bytes32"}]:[]],[x,n,o,h,BigInt(t),BigInt(y),...m?[m]:[]])));return{chainId:R.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:[{to:R.ZERO_ADDRESS,value:0n,data:N.encodeFunctionData({abi:R.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${t}`,idempotenceKey:w,nbf:0n,exp:l===void 0?g+3600n:BigInt(l),metadata:u??"{}",transfers:f.map(b=>({token:N.getAddress(b.token).toLowerCase(),to:N.getAddress(b.recipient).toLowerCase(),amount:b.amount}))}]})}]}}const wa=e=>{const[t,n]=p.useState(!1),s=p.useContext(d.SpiceFlowProviderContext),{dark:r,dk:o}=d.useSpiceBrand();if(p.useEffect(()=>{n(!0)},[]),!t)return c.jsx("div",{className:e.className,children:c.jsx("button",{disabled:!0,style:{padding:"12px 24px",fontSize:"16px",backgroundColor:r?o.hoverBg:"#ccc",color:r?o.textSecondary:"white",border:r?`1px solid ${o.buttonBorder}`:"none",borderRadius:"4px",cursor:"not-allowed"},children:"Loading..."})});if(!s){const a='ProviderLogin must be used within SpiceFlowProvider. Please wrap your app with <SpiceFlowProvider provider="privy">.';return c.jsx("div",{className:e.className,children:c.jsx("button",{onClick:()=>{e.onAuthError&&e.onAuthError(a)},style:{padding:"12px 24px",fontSize:"16px",backgroundColor:r?o.errorBg:"#dc2626",color:r?o.errorText:"white",border:r?`1px solid ${o.errorBorder}`:"none",borderRadius:"4px",cursor:"pointer"},children:"Provider Not Found"})})}return c.jsx(d.PrivyLogin,{...e})},Ar=({size:e=20,strokeWidth:t=2,color:n="currentColor",style:s})=>c.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:s,children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),Er=(e,t,n,s)=>({width:e,height:e,fill:"none",className:t,"aria-hidden":n??!0,style:s}),Zs=({size:e=16,color:t="currentColor",strokeWidth:n=2,direction:s="down",className:r,style:o,"aria-hidden":a})=>c.jsx("svg",{...Er(e,r,a,{transform:s==="up"?"rotate(180deg)":void 0,transition:"transform 0.3s ease",...o}),viewBox:"0 0 16 16",children:c.jsx("path",{d:"M4 6L8 10L12 6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),pp=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:s,style:r,"aria-hidden":o})=>c.jsxs("svg",{...Er(e,s,o,r),viewBox:"0 0 24 24",children:[c.jsx("circle",{cx:"11",cy:"11",r:"8",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"}),c.jsx("path",{d:"m21 21-4.3-4.3",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})]}),fp=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:s,style:r,"aria-hidden":o})=>c.jsx("svg",{...Er(e,s,o,r),viewBox:"0 0 24 24",children:c.jsx("path",{d:"m6 9 6 6 6-6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),mp=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:s,style:r,"aria-hidden":o})=>c.jsx("svg",{...Er(e,s,o,r),viewBox:"0 0 24 24",children:c.jsx("path",{d:"m9 18 6-6-6-6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),Nc=({size:e=14,color:t="currentColor",strokeWidth:n=2,className:s,style:r,"aria-hidden":o})=>c.jsx("svg",{...Er(e,s,o,r),viewBox:"0 0 16 16",children:c.jsx("path",{d:"M3 8L6.5 11.5L13 5",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),Mc=({isSuccess:e,type:t,chainName:n,explorerUrl:s,txHash:r,dark:o=!1,successBg:a="#d1fae5",successBorder:i="#6ee7b7",successText:l="#065f46",errorBg:u="#fee2e2",errorBorder:m="#fca5a5",errorText:f="#dc2626",textSecondary:h="#6b7280"})=>c.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px",borderRadius:"8px",backgroundColor:e?a:u,border:e?`1px solid ${i}`:`1px solid ${m}`},children:[c.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[c.jsx("div",{style:{width:"28px",height:"28px",borderRadius:"50%",backgroundColor:e?"#10b981":"#ef4444",display:"flex",alignItems:"center",justifyContent:"center"},children:e?c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:c.jsx("path",{d:"M11.6667 3.5L5.25 9.91667L2.33333 7",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}):c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:c.jsx("path",{d:"M10.5 3.5L3.5 10.5M3.5 3.5L10.5 10.5",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),c.jsxs("div",{children:[c.jsx("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:d.font.mono,letterSpacing:"0.5px",color:e?l:f},children:e?`${t.toUpperCase()} CONFIRMED`:`${t.toUpperCase()} FAILED`}),c.jsxs("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:h},children:["on ",n]})]})]}),s&&r&&c.jsxs("a",{href:`${s}/tx/${r}`,target:"_blank",rel:"noopener noreferrer",style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"13px",color:h,textDecoration:"none",whiteSpace:"nowrap"},children:["View on explorer",c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:[c.jsx("path",{d:"M9 6.5V9.5C9 9.76522 8.89464 10.0196 8.70711 10.2071C8.51957 10.3946 8.26522 10.5 8 10.5H2.5C2.23478 10.5 1.98043 10.3946 1.79289 10.2071C1.60536 10.0196 1.5 9.76522 1.5 9.5V4C1.5 3.73478 1.60536 3.48043 1.79289 3.29289C1.98043 3.10536 2.23478 3 2.5 3H5.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),c.jsx("path",{d:"M7.5 1.5H10.5V4.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),c.jsx("path",{d:"M5 7L10.5 1.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})]})]})]}),Pc=`
3
3
  @keyframes slideUp {
4
4
  from { transform: translateY(100%); }
5
5
  to { transform: translateY(0); }