@spicenet-io/spiceflow-ui 4.22.1 → 4.22.2

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.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use client";
2
2
  (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)})();
3
- import{jsx as m,jsxs as D,Fragment as In}from"react/jsx-runtime";import{g as xt,a as Ot,S as ke,b as Q,c as Xa,i as Ja,d as $a,e as on,f as Ap,E as Ep,C as _a,r as Fp,R as Tp,s as Ln,h as Bp,j as qe,k as Ir,l as Op,m as es,u as Oo,n as ts,o as io,p as cn,P as Rp,q as ns,B as Kt,t as ot,v as go,w as Vo,x as Xs,y as Ur,z as kr,A as Qo,D as Kc,F as wo,G as Dp,H as la,I as da,J as os,K as Js,L as Mp,M as Yc,N as ua,O as Lr,Q as Np,T as qr,U as $s,V as _s,W as Ro,X as rs,Y as Cr,Z as Pp,_ as as,$ as Wp,a0 as ei,a1 as Up,a2 as Lp,a3 as ti,a4 as qp,a5 as Zc,a6 as zp,a7 as Hp,a8 as Vp}from"./privy-Cm5z8eSR.js";import{a9 as q0,ab as z0,ac as H0,ae as V0,ad as Q0,aa as j0}from"./privy-Cm5z8eSR.js";import Eo,{useContext as pn,useState as q,useMemo as Ie,useEffect as me,useCallback as ae,useRef as G,useId as Xc,useLayoutEffect as Do,memo as yo}from"react";import{isNativeToken as Oe,uniV3QuoterV2Abi as Qp,uniV3SwapRouterAbi as Jc,applySlippage as $c,NATIVE_TOKEN_ADDRESS as _c,getTokenByAddress as en,areEquivalent as jp,getTokensForChain as ir,getEscrowContractAddress as Mo,getEscrowContract as pa,ZERO_ADDRESS as Yt,normalizeNativeTokenAddress as ut,getChainMeta as ni,getMainnetChains as Gp,getTestnetChains as Kp,TOKENS as el,convertAmountBetweenDecimals as bo,hashChainBatches as Fo,isSpicenetChainId as No,getAccountNonce as Yp,SPICE_COMBINED_FEE_RECIPIENT as Zp,SPICE_GAS_FEE_RECIPIENT as kn,SPICE_PLATFORM_FEE_RECIPIENT as Kn,hashConditionalExecutionPlan as tl,SPICENET_NATIVE_CHAIN_ID as nl,spicenetAbi as ss,getEquivalentAddresses as Xp,getChainIdsByNetwork as is,getEquivalenceGroup as Jp,getTokenBySymbol as ol,hashConditionalIntentAuthorization as $p,getConditionalIntentId as _p,hashConditionalReadAuthorization as ef,hashConditionalCancellation as tf}from"@spicenet-io/spiceflow-core";import{ZERO_ADDRESS as K0,SPICENET_NATIVE_CHAIN_ID as Y0,SPICE_COMBINED_FEE_RECIPIENT as Z0,SPICE_GAS_FEE_RECIPIENT as X0,SPICE_PLATFORM_FEE_RECIPIENT as J0,SPICE_SOLVER_ADDRESS as $0,applySlippage as _0,buildUniV3SwapCalls as e1,getChainIdsByNetwork as t1,getEscrowContractAddress as n1,isNativeToken as o1,isSpicenetChainId as r1,normalizeNativeTokenAddress as a1,spicenetAbi as s1,spicenetAbi as i1}from"@spicenet-io/spiceflow-core";import{useAccount as oi,useDisconnect as ri,useConnect as nf,useWalletClient as of,useSwitchChain as rf}from"wagmi";import{encodeFunctionData as Wt,parseAbi as xo,concatHex as rl,encodePacked as ai,erc20Abi as pt,decodeFunctionData as Jn,encodeAbiParameters as jo,formatUnits as Ne,isAddress as Qn,getAddress as gn,zeroAddress as al,keccak256 as cr,recoverAddress as af,toRlp as sf,toHex as cs,parseUnits as $n,decodeEventLog as cf,createWalletClient as si,custom as ii,stringToHex as lf,bytesToHex as sl}from"viem";import{readContract as lr,getBalance as ci}from"viem/actions";import{useConnectWallet as il,usePrivy as cl,useActiveWallet as df}from"@privy-io/react-auth";import ll,{createPortal as li}from"react-dom";import"@tanstack/react-query";const uf="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@100;200;300;400;500;600;700&display=swap",pf="spiceflow-ibm-plex-mono",ff="spiceflow-preconnect-googleapis",mf="spiceflow-preconnect-gstatic";function di(e,t){if(document.getElementById(e))return;const n=t();n.id=e,document.head.appendChild(n)}function hf(){typeof document>"u"||(di(ff,()=>{const e=document.createElement("link");return e.rel="preconnect",e.href="https://fonts.googleapis.com",e}),di(mf,()=>{const e=document.createElement("link");return e.rel="preconnect",e.href="https://fonts.gstatic.com",e.crossOrigin="",e}),di(pf,()=>{const e=document.createElement("link");return e.rel="stylesheet",e.href=uf,e}))}const gf={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",8453:"0x4200000000000000000000000000000000000006",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",84532:"0x4200000000000000000000000000000000000006"},dl=xo(["function deposit() payable","function withdraw(uint256 wad)"]);function ui(e){return xt(e)?.wrappedNativeTokenAddress??gf[e]}const pi=(e,t)=>({to:e,value:t,data:Wt({abi:dl,functionName:"deposit"})}),fi=(e,t)=>({to:e,value:0n,data:Wt({abi:dl,functionName:"withdraw",args:[t]})});function mi(e,t,n){const o=Oe(t),r=Oe(n);if(!o&&!r)return null;const a=ui(e);return a?{weth:a,wrapIn:o,unwrapOut:r}:null}function ul(e,t,n,o){const r=mi(e,t,n);return!r||o<=0n?null:r.wrapIn&&!r.unwrapOut&&n.toLowerCase()===r.weth.toLowerCase()?[pi(r.weth,o)]:r.unwrapOut&&!r.wrapIn&&t.toLowerCase()===r.weth.toLowerCase()?[fi(r.weth,o)]:null}function wf(e){return{...e,resolve:async(t,n,o,r)=>{const a=ul(n,t.tokenIn,t.tokenOut,t.amountIn);if(a)return{venue:"native-wrap",amountOut:t.amountIn,amountOutMinimum:t.amountIn,calls:a};const s=await e.resolve(t,n,o,r);if(s)return s;const i=mi(n,t.tokenIn,t.tokenOut);if(!i)return null;const c=await e.resolve({...t,tokenIn:i.wrapIn?i.weth:t.tokenIn,tokenOut:i.unwrapOut?i.weth:t.tokenOut},n,o,r);return c?{...c,calls:[...i.wrapIn?[pi(i.weth,t.amountIn)]:[],...c.calls,...i.unwrapOut?[fi(i.weth,c.amountOutMinimum)]:[]]}:null}}}function yf(e){return{...e,resolve:async(t,n,o)=>{const r=ul(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 a=await e.resolve(t,n,o);if(a)return a;const s=mi(n,t.tokenIn,t.tokenOut);if(!s)return null;const i=await e.resolve({...t,tokenIn:s.wrapIn?s.weth:t.tokenIn,tokenOut:s.unwrapOut?s.weth:t.tokenOut},n,o);return i?{...i,calls:[...s.wrapIn?[pi(s.weth,i.amountInMax)]:[],...i.calls,...s.unwrapOut?[fi(s.weth,i.amountOut)]:[]]}:null}}}const pl=[100,500,3e3,1e4];function ls(e,t,n,o,r){const a=[];for(const s of n){const i=typeof s=="object"&&!Array.isArray(s)?s:void 0,c=i?i.tokens:Array.isArray(s)?s:[s];if(!c.length||c.length>2)throw new Error("A v3 route must have one or two intermediate tokens");const l=[e,...c,t];if(i&&(i.feeTiers.length!==l.length-1||i.feeTiers.some(d=>!d.length)))throw new Error("A v3 route needs fee tiers for every pool");if(new Set(l.map(d=>d.toLowerCase())).size!==l.length)continue;const u=(d,p)=>{if(d===l.length){a.push(r==="in"?p:fl(p));return}for(const w of i?.feeTiers[d-1]??o)u(d+1,rl([p,ai(["uint24","address"],[w,l[d]])]))};u(1,l[0])}return[...new Set(a)]}function fl(e){const t=e.slice(2),n=[];for(let o=0;o<t.length;){const r=n.length%2===0?40:6;n.push(t.slice(o,o+r)),o+=r}return`0x${n.reverse().join("")}`}const bf=xo(["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)"]),xf=xo(["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)"]),vf=1800;function ml(e){const{config:t,route:n,tokenIn:o,tokenOut:r,recipient:a,amountOut:s}=e,i=e.amountInMaximum,c=e.routerHasDeadline?xf:bf,l=e.routerHasDeadline?{deadline:BigInt(Math.floor(Date.now()/1e3)+vf)}:{},u=n.path?Wt({abi:c,functionName:"exactOutput",args:[{path:n.path,recipient:a,...l,amountOut:s,amountInMaximum:i}]}):Wt({abi:c,functionName:"exactOutputSingle",args:[{tokenIn:o,tokenOut:r,fee:n.fee,recipient:a,...l,amountOut:s,amountInMaximum:i,sqrtPriceLimitX96:0n}]});return{to:t.swapRouter,value:0n,data:u}}const If=xo(["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 fa(e,t,n,o,r){const a=Ot(e),{result:s}=await a.simulateContract({address:t.quoterV2,abi:If,functionName:r==="in"?"quoteExactInput":"quoteExactOutput",args:[n,o]}),[i,,,c]=s;if(i<=0n)throw new Error("No liquidity along this path.");return{amount:i,gasEstimate:c}}async function kf(e){const{tokenIn:t,tokenOut:n,amountIn:o,fee:r,chainId:a,config:s}=e;if(o<=0n)throw new Error("amountIn must be greater than 0");const i=(await Ot(a).simulateContract({address:s.quoterV2,abi:Qp,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:o,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 hl(e){const t=e.feeTiers??pl,n=ls(e.tokenIn,e.tokenOut,e.hubs??[],t,"in"),o=await Promise.allSettled([...t.map(async a=>({...await kf({...e,fee:a}),fee:a})),...n.map(async a=>{const s=await fa(e.chainId,e.config,a,e.amountIn,"in");return{amountOut:s.amount,sqrtPriceX96After:0n,gasEstimate:s.gasEstimate,fee:0,path:a}})]);let r=null;for(const a of o)a.status==="fulfilled"&&(!r||a.value.amountOut>r.amountOut)&&(r=a.value);if(!r)throw new Error("No liquidity found for this pair on any fee tier.");return r}const Cf=[{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 Sf(e){const{tokenIn:t,tokenOut:n,amountOut:o,fee:r,chainId:a,config:s}=e;if(o<=0n)throw new Error("amountOut must be greater than 0");const i=(await Ot(a).simulateContract({address:s.quoterV2,abi:Cf,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:o,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 gl(e){const t=e.feeTiers??pl,n=ls(e.tokenIn,e.tokenOut,e.hubs??[],t,"out"),o=await Promise.allSettled([...t.map(async a=>({...await Sf({...e,fee:a}),fee:a})),...n.map(async a=>{const s=await fa(e.chainId,e.config,a,e.amountOut,"out");return{amountIn:s.amount,sqrtPriceX96After:0n,gasEstimate:s.gasEstimate,fee:0,path:a}})]);let r=null;for(const a of o)a.status==="fulfilled"&&(!r||a.value.amountIn<r.amountIn)&&(r=a.value);if(!r)throw new Error("No liquidity found for this pair on any fee tier.");return r}function Af(e){return e.type==="swap"}const ma=.02,Ef=[1,8453,42161,10,137,43114,56],Ff="https://api.1inch.dev/swap/v6.0";function hi(e,t){return $c(e,t)}function Tf(e){const t=e?.baseUrl??Ff;return{name:"1inch",chainIds:e?.chainIds??Ef,resolve:async(n,o,r)=>{const a=n.maxSlippage??ma,s=a*100,i=Oe(n.tokenIn)?_c:n.tokenIn,c=Oe(n.tokenOut)?_c:n.tokenOut,l=Oe(n.tokenIn);try{const u=new URL(`${t}/${o}/swap`);u.searchParams.set("src",i),u.searchParams.set("dst",c),u.searchParams.set("amount",n.amountIn.toString()),u.searchParams.set("from",r),u.searchParams.set("slippage",s.toString()),u.searchParams.set("disableEstimate","true"),u.searchParams.set("allowPartialFill","false");const d={Accept:"application/json"};e?.apiKey&&(d.Authorization=`Bearer ${e.apiKey}`);const p=await fetch(u.toString(),{headers:d});if(!p.ok)throw new ke("VENUE_API_ERROR",`[1inchVenue] API returned ${p.status} for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`,{venue:"1inch",chainId:o,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:`HTTP ${p.status}`});const w=await p.json();if(!w.dstAmount||!w.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const f=BigInt(w.dstAmount);if(f<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const g=hi(f,a),h=[];return w.tx.to&&!l&&h.push({to:n.tokenIn,value:0n,data:Wt({abi:pt,functionName:"approve",args:[w.tx.to,n.amountIn]})}),h.push({to:w.tx.to,value:BigInt(w.tx.value||"0"),data:w.tx.data}),{venue:"1inch",amountOut:f,amountOutMinimum:g,calls:h}}catch(u){if(u instanceof ke)throw u;const d=u instanceof Error?u.message:String(u);throw new ke("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}: ${d}`,{venue:"1inch",chainId:o,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:d})}}}}const wl=[4114,5115],gi={name:"Satsuma",swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},yl={name:"Uniswap v3",swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x4200000000000000000000000000000000000006","0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]},bl={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[1],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2","0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"]},xl={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[42161],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x82aF49447D8a07e3bd95BD0d56f35241523fBab1","0xaf88d065e77c8cC2239327C5EDb3A432268e5831"]},Bf={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[137],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270","0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"]},Of={name:"Uniswap v3",swapRouter:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",quoterV2:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",chainIds:[56],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c","0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d"]},Rf={name:"Uniswap v3",swapRouter:"0xfe31f71c1b106eac32f1a19239c9a9a72ddfb900",quoterV2:"0x661e93cca42afacb172121ef892830ca3b70f08d",chainIds:[143],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A","0x754704Bc059F8C67012fEd69BC8A327a5aafb603"]},vl={name:"Uniswap v3",swapRouter:"0xcaf681a66d020601342297493863e78c959e5cb2",quoterV2:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",chainIds:[4663],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73","0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"]},Il={name:"SushiSwap",swapRouter:"0x1e406484F1F204b23cE84B9901C0171a738fd406",quoterV2:"0x3E290e5E01818002A0b672148BdC7514D861C7B3",chainIds:[4663],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73","0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"],routerHasDeadline:!0},kl=xo(["function exactInput((bytes path, address recipient, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),Cl=xo(["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)"]),Df=xo(["function exactInput((bytes path, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),Mf=xo(["function exactOutput((bytes path, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),wi=1800,Sl=[1,50,100,200,2e3],ds={name:"Aerodrome",swapRouter:"0xcbBb8035cAc7D4B3Ca7aBb74cF7BdF900215Ce0D",quoterV2:"0x3d4C22254F86f64B7eC90ab8F7aeC1FBFD271c6C",chainIds:[8453],hubCurrencies:["0x4200000000000000000000000000000000000006","0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]};function ha(e){const t=e.name??"Aerodrome",n=e.chainIds??[8453],o=e.tickSpacings??Sl;return{name:t,chainIds:n,resolve:async(r,a,s)=>{if(Oe(r.tokenIn)||Oe(r.tokenOut))return null;const i=r.maxSlippage??ma,c=[...o.map(h=>ai(["address","uint24","address"],[r.tokenIn,h,r.tokenOut])),...ls(r.tokenIn,r.tokenOut,e.hubCurrencies??[],o,"in")],l={quoterV2:e.quoterV2},u=await Promise.allSettled(c.map(async h=>({path:h,amountOut:(await fa(a,l,h,r.amountIn,"in")).amount})));let d=null;for(const h of u)h.status==="fulfilled"&&(!d||h.value.amountOut>d.amountOut)&&(d=h.value);if(!d)return console.warn(`[AerodromeVenue] No viable route for ${r.tokenIn} \u2192 ${r.tokenOut} on chain ${a}.`),null;const p=hi(d.amountOut,i),w=e.deadline??BigInt(Math.floor(Date.now()/1e3)+wi),f=Wt({abi:Df,functionName:"exactInput",args:[{path:d.path,recipient:s,deadline:w,amountIn:r.amountIn,amountOutMinimum:p}]}),g=[{to:r.tokenIn,value:0n,data:Wt({abi:pt,functionName:"approve",args:[e.swapRouter,r.amountIn]})},{to:e.swapRouter,value:0n,data:f}];return{venue:t,amountOut:d.amountOut,amountOutMinimum:p,calls:g}}}}function Al(e){const t=e.name??"Aerodrome",n=e.chainIds??[8453],o=e.tickSpacings??Sl;return{name:t,chainIds:n,resolve:async(r,a,s)=>{if(Oe(r.tokenIn)||Oe(r.tokenOut))return null;const i=r.maxSlippage??ma,c=[...o.map(g=>ai(["address","uint24","address"],[r.tokenOut,g,r.tokenIn])),...ls(r.tokenIn,r.tokenOut,e.hubCurrencies??[],o,"out")],l={quoterV2:e.quoterV2},u=await Promise.allSettled(c.map(async g=>({path:g,amountIn:(await fa(a,l,g,r.amountOut,"out")).amount})));let d=null;for(const g of u)g.status==="fulfilled"&&(!d||g.value.amountIn<d.amountIn)&&(d=g.value);if(!d)return console.warn(`[AerodromeExactOutputVenue] No viable route for ${r.tokenIn} \u2192 ${r.tokenOut} on chain ${a}.`),null;const p=BigInt(Math.round(i*1e4)),w=d.amountIn+d.amountIn*p/10000n,f=e.deadline??BigInt(Math.floor(Date.now()/1e3)+wi);return{venue:t,amountIn:d.amountIn,amountInMax:w,amountOut:r.amountOut,calls:[{to:e.swapRouter,value:0n,data:Wt({abi:Mf,functionName:"exactOutput",args:[{path:d.path,recipient:s,deadline:f,amountOut:r.amountOut,amountInMaximum:w}]})}]}}}}function ga(e){const t=e.name??"Uniswap v3",n=e.chainIds??wl;return{name:t,chainIds:n,resolve:async(o,r,a,s)=>{if(Oe(o.tokenIn)||Oe(o.tokenOut))return null;const i=o.maxSlippage??ma;let c;try{let f;if(s){if(s.venue!==t)return null;const g=s.calls.find(y=>y.to.toLowerCase()===e.swapRouter.toLowerCase());if(!g)return null;const h=Jn({abi:e.routerHasDeadline?Cl:[...kl,...Jc],data:g.data});if(h.functionName==="exactInput"){const{path:y}=h.args[0];if(y.slice(0,42).toLowerCase()!==o.tokenIn.toLowerCase()||`0x${y.slice(-40)}`.toLowerCase()!==o.tokenOut.toLowerCase())return null;f={path:y,fee:0}}else if(h.functionName==="exactInputSingle"){const{tokenIn:y,tokenOut:I,fee:A}=h.args[0];if(y.toLowerCase()!==o.tokenIn.toLowerCase()||I.toLowerCase()!==o.tokenOut.toLowerCase())return null;f={fee:A}}else return null}c=f?.path?{...f,amountOut:(await fa(r,e,f.path,o.amountIn,"in")).amount}:await hl({tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountIn:o.amountIn,chainId:r,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:f?[f.fee]:e.feeTiers,hubs:f?[]:[...e.hubCurrencies??[],...e.hubPaths??[]]})}catch{return console.warn(`[UniV3Venue] No viable route for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${r}.`),null}const l=hi(c.amountOut,i),u=e.routerHasDeadline?{deadline:BigInt(Math.floor(Date.now()/1e3)+wi)}:{},d=e.routerHasDeadline?Cl:c.path?kl:Jc,p=c.path?Wt({abi:d,functionName:"exactInput",args:[{path:c.path,recipient:a,...u,amountIn:o.amountIn,amountOutMinimum:l}]}):Wt({abi:d,functionName:"exactInputSingle",args:[{tokenIn:o.tokenIn,tokenOut:o.tokenOut,fee:c.fee,recipient:a,...u,amountIn:o.amountIn,amountOutMinimum:l,sqrtPriceLimitX96:0n}]}),w=[{to:o.tokenIn,value:0n,data:Wt({abi:pt,functionName:"approve",args:[e.swapRouter,o.amountIn]})},{to:e.swapRouter,value:0n,data:p}];return{venue:t,amountOut:c.amountOut,amountOutMinimum:l,calls:w}}}}function yi(e){const t=e.name??"Uniswap v3",n=e.chainIds??wl;return{name:t,chainIds:n,resolve:async(o,r,a)=>{if(Oe(o.tokenIn)||Oe(o.tokenOut))return null;const s=o.maxSlippage??ma;let i;try{i=await gl({tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountOut:o.amountOut,chainId:r,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers,hubs:[...e.hubCurrencies??[],...e.hubPaths??[]]})}catch{return null}const c=BigInt(Math.round(s*1e4)),l=i.amountIn+i.amountIn*c/10000n;return{venue:t,amountIn:i.amountIn,amountInMax:l,amountOut:o.amountOut,calls:[ml({config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},routerHasDeadline:e.routerHasDeadline,route:i,tokenIn:o.tokenIn,tokenOut:o.tokenOut,recipient:a,amountOut:o.amountOut,amountInMaximum:l})]}}}}function El(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(ga(e.satsuma)),e?.aerodrome!==!1&&t.push(ha(e?.aerodrome??ds)),t.push(Tf(e?.oneInch));const n=t.map(wf);function o(s){return n.find(i=>i.chainIds.includes(s))}async function r(s,i,c,l){const u=n.filter(f=>f.chainIds.includes(i));if(u.length===0)throw new ke("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${i}. Cannot resolve swap ${s.tokenIn} \u2192 ${s.tokenOut}.`,{chainId:i,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn.toString()});const d=await Promise.allSettled(u.map(f=>f.resolve(s,i,c,l)));let p=null;for(const f of d)l&&f.status==="fulfilled"&&f.value&&(f.value.venue!==l.venue||f.value.calls.length!==l.calls.length||f.value.calls.some((g,h)=>g.to.toLowerCase()!==l.calls[h].to.toLowerCase()||g.data.slice(0,10)!==l.calls[h].data.slice(0,10)))||f.status==="fulfilled"&&f.value&&(!p||f.value.amountOut>p.amountOut)&&(p=f.value);if(p)return p;const w=d.find(f=>f.status==="rejected");if(w)throw w.reason;return null}async function a(s,i,c){const l=[],u=[];for(const d of s){if(!Af(d)){l.push(d);continue}const p=await r(d,i,c);if(!p)throw new ke("NO_LIQUIDITY",`No venue returned a quote for ${d.tokenIn} \u2192 ${d.tokenOut} on chain ${i}.`,{chainId:i,tokenIn:d.tokenIn,tokenOut:d.tokenOut,amountIn:d.amountIn.toString()});l.push(...p.calls),u.push(p)}return{calls:l,resolvedSwaps:u}}return{resolveSwapIntents:a,resolveSwap:r,getVenueForChain:o,venues:t}}const Po="0x0000000000000000000000000000000000000000",bi=[{fee:100,tickSpacing:1},{fee:500,tickSpacing:10},{fee:3e3,tickSpacing:60},{fee:1e4,tickSpacing:200}],Fl=Po,Tl=.02,Nf=1800,Bl={name:"Uniswap v4",quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",universalRouter:"0x6ff5693b99212da76ad316178a184ab56d299b43",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",chainIds:[8453],hubCurrencies:["0x4200000000000000000000000000000000000006",Po,"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]},Ol={name:"Uniswap v4",quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",universalRouter:"0x8876789976decbfcbbbe364623c63652db8c0904",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",routerHasHopPrice:!0,chainIds:[4663],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73",Po,"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"]},Rl=xo(["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)"]),Pf=xo(["function approve(address token, address spender, uint160 amount, uint48 expiration)"]),Wf=xo(["function execute(bytes commands, bytes[] inputs, uint256 deadline) payable"]),Dl="0x10",Uf="04",Lf="06",qf="07",zf="08",Hf="09",us="0c",ps="0e",Vf=[{name:"currency0",type:"address"},{name:"currency1",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"}],Qf=[{name:"intermediateCurrency",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"},{name:"hookData",type:"bytes"}],Go=(e,t)=>e.toLowerCase()===t.toLowerCase();function fs(e){return Oe(e)?Po:e}function jf(e,t){return e.toLowerCase()<t.toLowerCase()?[e,t]:[t,e]}function Ml(e,t,n,o,r){const a=[],[s,i]=jf(e,t);for(const{fee:l,tickSpacing:u}of bi)a.push({kind:"single",poolKey:{currency0:s,currency1:i,fee:l,tickSpacing:u,hooks:Fl},zeroForOne:Go(e,s)});const c=(l,u)=>!!r&&(Go(l,Po)&&Go(u,r)||Go(l,r)&&Go(u,Po));for(const l of n)if(!(Go(l,e)||Go(l,t))&&!(c(l,e)||c(l,t)))for(const u of bi)for(const d of bi){const p=(w,f)=>({intermediateCurrency:w,fee:f.fee,tickSpacing:f.tickSpacing,hooks:Fl,hookData:"0x"});a.push({kind:"multi",path:o==="in"?[p(l,u),p(t,d)]:[p(e,u),p(l,d)]})}return a}async function Nl(e,t,n,o,r,a){const s=Ot(e),i=(await Promise.allSettled(n.map(async c=>{const{result:l}=c.kind==="single"?await s.simulateContract({address:t.quoter,abi:Rl,functionName:a==="in"?"quoteExactInputSingle":"quoteExactOutputSingle",args:[{poolKey:c.poolKey,zeroForOne:c.zeroForOne,exactAmount:r,hookData:"0x"}]}):await s.simulateContract({address:t.quoter,abi:Rl,functionName:a==="in"?"quoteExactInput":"quoteExactOutput",args:[{exactCurrency:o,path:c.path,exactAmount:r}]}),u=l[0];if(u<=0n)throw new Error("zero quote");return{candidate:c,amount:u}}))).filter(c=>c.status==="fulfilled").map(c=>c.value);return i.length===0?null:(i.sort((c,l)=>c.amount<l.amount?-1:c.amount>l.amount?1:0),a==="in"?i[i.length-1]:i[0])}function Pl(e){const{candidate:t,direction:n,currencyIn:o,currencyOut:r,recipient:a,exactAmount:s,limitAmount:i,deadline:c,routerHasHopPrice:l,sweepNativeTo:u}=e;let d,p;t.kind==="single"?(d=n==="in"?`0x${Lf}${us}${ps}`:`0x${zf}${us}${ps}`,p=jo([{type:"tuple",components:[{name:"poolKey",type:"tuple",components:Vf},{name:"zeroForOne",type:"bool"},{name:n==="in"?"amountIn":"amountOut",type:"uint128"},{name:n==="in"?"amountOutMinimum":"amountInMaximum",type:"uint128"},...l?[{name:"minHopPriceX36",type:"uint256"}]:[],{name:"hookData",type:"bytes"}]}],[{poolKey:t.poolKey,zeroForOne:t.zeroForOne,[n==="in"?"amountIn":"amountOut"]:s,[n==="in"?"amountOutMinimum":"amountInMaximum"]:i,...l?{minHopPriceX36:0n}:{},hookData:"0x"}])):(d=n==="in"?`0x${qf}${us}${ps}`:`0x${Hf}${us}${ps}`,p=jo([{type:"tuple",components:[{name:n==="in"?"currencyIn":"currencyOut",type:"address"},{name:"path",type:"tuple[]",components:Qf},...l?[{name:"minHopPriceX36",type:"uint256[]"}]:[],{name:n==="in"?"amountIn":"amountOut",type:"uint128"},{name:n==="in"?"amountOutMinimum":"amountInMaximum",type:"uint128"}]}],[{[n==="in"?"currencyIn":"currencyOut"]:n==="in"?o:r,path:t.path,...l?{minHopPriceX36:[]}:{},[n==="in"?"amountIn":"amountOut"]:s,[n==="in"?"amountOutMinimum":"amountInMaximum"]:i}]));const w=jo([{type:"address"},{type:"uint256"}],[o,n==="in"?s:i]),f=jo([{type:"address"},{type:"address"},{type:"uint256"}],[r,a,0n]),g=jo([{type:"bytes"},{type:"bytes[]"}],[d,[p,w,f]]),h=u?`${Dl}${Uf}`:Dl,y=u?[g,jo([{type:"address"},{type:"address"},{type:"uint256"}],[Po,u,0n])]:[g];return Wt({abi:Wf,functionName:"execute",args:[h,y,c]})}function Wl(){return BigInt(Math.floor(Date.now()/1e3)+Nf)}function Ul(e,t,n,o){return{to:e.permit2,value:0n,data:Wt({abi:Pf,functionName:"approve",args:[t,e.universalRouter,n,Number(o)]})}}function Ll(e){const t=e.name??"Uniswap v4",n=e.v3?ga({...e.v3,chainIds:e.chainIds}):null;return{name:t,chainIds:e.chainIds,resolve:async(o,r,a)=>{const s=o.maxSlippage??Tl,i=fs(o.tokenIn),c=fs(o.tokenOut),l=Oe(o.tokenIn),u=e.hubCurrencies??[Po];let d=null;if(!Go(i,c)&&o.amountIn>0n){const p=await Nl(r,e,Ml(i,c,u,"in",ui(r)),i,o.amountIn,"in").catch(()=>null);if(p){const w=$c(p.amount,s),f=Wl(),g=[];l||(g.push({to:o.tokenIn,value:0n,data:Wt({abi:pt,functionName:"approve",args:[e.permit2,o.amountIn]})}),g.push(Ul(e,o.tokenIn,o.amountIn,f))),g.push({to:e.universalRouter,value:l?o.amountIn:0n,data:Pl({candidate:p.candidate,direction:"in",currencyIn:i,currencyOut:c,recipient:a,exactAmount:o.amountIn,limitAmount:w,deadline:f,routerHasHopPrice:e.routerHasHopPrice})}),d={venue:t,amountOut:p.amount,amountOutMinimum:w,calls:g}}}return!d&&n?n.resolve(o,r,a):d}}}function ql(e){const t=e.name??"Uniswap v4";return{name:t,chainIds:e.chainIds,resolve:async(n,o,r)=>{const a=Oe(n.tokenIn),s=fs(n.tokenIn),i=fs(n.tokenOut);if(Go(s,i)||n.amountOut<=0n)return null;const c=n.maxSlippage??Tl,l=e.hubCurrencies??[Po],u=await Nl(o,e,Ml(s,i,l,"out",ui(o)),i,n.amountOut,"out").catch(()=>null);if(!u)return null;const d=BigInt(Math.round(c*1e4)),p=u.amount+u.amount*d/10000n,w=Wl();return{venue:t,amountIn:u.amount,amountInMax:p,amountOut:n.amountOut,calls:[...a?[]:[Ul(e,n.tokenIn,p,w)],{to:e.universalRouter,value:a?p:0n,data:Pl({candidate:u.candidate,direction:"out",currencyIn:s,currencyOut:i,recipient:r,exactAmount:n.amountOut,limitAmount:p,deadline:w,routerHasHopPrice:e.routerHasHopPrice,sweepNativeTo:a?r:void 0})}]}}}}const xi=[{...gi,protocol:"uniswap-v3",chainId:4114},{...gi,protocol:"uniswap-v3",chainId:5115},{...yl,protocol:"uniswap-v3",chainId:8453},{...bl,protocol:"uniswap-v3",chainId:1},{...xl,protocol:"uniswap-v3",chainId:42161},{...Bf,protocol:"uniswap-v3",chainId:137},{...Of,protocol:"uniswap-v3",chainId:56},{...Rf,protocol:"uniswap-v3",chainId:143},{...vl,protocol:"uniswap-v3",chainId:4663},{...Il,protocol:"uniswap-v3",chainId:4663},{...Bl,protocol:"uniswap-v4",chainId:8453},{...Ol,protocol:"uniswap-v4",chainId:4663},{...ds,protocol:"aerodrome-slipstream",chainId:8453}];function Sr(e){const t=e?.includeDefaults===!1?e.venues??[]:[...xi,...e?.venues??[]],n=[],o=[];for(const r of t){const a=[r.chainId];switch(r.protocol){case"uniswap-v3":{const s={...r,chainIds:a};n.push(ga(s)),o.push(yi(s));break}case"uniswap-v4":{const s={...r,chainIds:a};n.push(Ll(s)),o.push(ql(s));break}case"aerodrome-slipstream":{const s={...r,chainIds:a};n.push(ha(s)),o.push(Al(s));break}default:{const s=r;throw new ke("INVALID_PARAMS",`Unsupported liquidity venue protocol: ${s.protocol}`,{protocol:s.protocol})}}}return{input:n,output:o}}const vi=new Set(["WBTC","CBTC"]),zl=new Set(["btc","wbtc","wcbtc","cbtc"]);function Hl(e,t){return!e||!t?!1:e===t?!0:vi.has(e)&&vi.has(t)}function _n(e){const[t,n,o]=e.split(":");if(t!=="evm"||!n||!o)return null;const r=Number(n);if(!Number.isFinite(r))return null;const a=o.startsWith("0x")?o.toLowerCase():`0x${o.toLowerCase()}`;return{chainId:r,address:a}}function ms(e){return(e??"").trim().replace(/^test\s+/i,"").replace(/^spice/i,"").toLowerCase().replace(/[^a-z0-9]/g,"")}function Gf(e){return new Set([e.receiptTokenName,e.displaySymbol,e.symbol,e.displayName,e.name].map(ms).filter(Boolean))}function Kf(e,t){const n=Gf(e),o=[t.symbol,t.name,t.equivalenceGroup].map(ms);if(o.some(s=>s&&n.has(s)))return!0;const r=[...n].some(s=>zl.has(s)),a=o.some(s=>zl.has(s))||vi.has(t.equivalenceGroup??"");return r&&a}function Vl(e,t,n){const o=new Set(t.map(ms).filter(Boolean)),r=a=>{if(n&&Q(a.address,n))return 0;const s=[a.symbol,a.name,a.equivalenceGroup].map(ms).findIndex(i=>i&&o.has(i));return s===-1?4:s+1};return[...e].sort((a,s)=>{const i=r(a)-r(s);return i!==0?i:a.address.toLowerCase().localeCompare(s.address.toLowerCase())})}function zr(e,t){const n=e.chainTokens?Object.keys(e.chainTokens):[],o=[];for(const r of n){const a=_n(r);if(!a||a.chainId!==t)continue;const s=a.address,i=Oe(s)?xt(t)?.nativeCurrency:void 0,c=en(s,t)??(i?{...i}:void 0);c&&(!Ii(e,s,t)&&!(e.isUniversal&&Kf(e,c))||o.some(l=>Q(l,s))||o.push(s))}return Vl(o.map(r=>{const a=en(r,t);return{address:r,symbol:a?.symbol,name:a?.name,equivalenceGroup:a?.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 Ii(e,t,n){return e.chainId===n&&Q(e.address,t)?!0:ya(e.address,e.chainId,t,n)}async function Ql(e,t){const n=Ot(e),o=Mo(e);return Oe(t)?n.getBalance({address:o}):await n.readContract({address:t,abi:pt,functionName:"balanceOf",args:[o]})}function ki(e,t,n){const o=ir(n),r=o.find(s=>Q(s.address,e));if(r&&(t===n||!Oe(e)))return r;const a=en(e,t);if(a)return Vl(o.filter(s=>Hl(s.equivalenceGroup,a.equivalenceGroup)),[a.symbol,a.name,a.equivalenceGroup])[0]}function wa(e){return e.equivalenceGroup==="USDC"&&e.symbol.toUpperCase()!=="USDT"}function Ar(e){const t=pa(e);if(!t||t===Yt)return;const n=ir(e).filter(wa);return n.find(o=>o.symbol.toUpperCase()==="USDC")??n[0]}function Ci(e,t){if(e.chainId===t)return null;const n=pa(e.chainId),o=pa(t);if(!n||n===Yt||!o||o===Yt)return null;const r=!e.isNative&&!Oe(e.address)?en(e.address,e.chainId):void 0,a=r&&wa(r)?ki(e.address,e.chainId,t):void 0,s=a?r:Ar(e.chainId),i=a??Ar(t);if(!s||!i)return null;const c=l=>({address:l.address,symbol:l.symbol,decimals:l.decimals,chainId:l.chainId});return{source:c(s),destination:c(i)}}async function jl(e,t,n){const o=ir(e.chainId).filter(wa),r=[o.find(i=>Q(i.address,t.address)),e,...o].filter((i,c,l)=>!!i&&l.findIndex(u=>u&&Q(u.address,i.address))===c);let a;for(const i of r){let c;try{c=await Ql(e.chainId,i.address)}catch{continue}if(c<=0n)continue;const l={...i,address:i.address};let u;try{u=await n(l)}catch{u=null}if(Q(l.address,e.address)&&(a=u),u&&u.amount<=c)return{token:l,...u}}const s=a===void 0?await n(e):a;return s?{token:e,...s}:null}function Yf(e,t){return!!Ci(e,t)}function co(e,t){if(e.chainId===t)return e.address;const n=ki(e.address,e.chainId,t);return n?n.address:null}async function Wo(e,t,n,o){const r=en(t,n);return r?r.decimals:e?.chainId===n&&Q(e.address,t)&&!e.isUniversal?e.decimals:o?.chainId===n&&Q(o.address,t)?o.decimals:Xa(n,t)}async function Gl(e,t,n={}){const o=co(e,t),r=zr(e,t);if(r.length===0)return o;if(r.length===1)return r[0];const a=n.requiredAmount??0n,s=i=>{const c=r.map(l=>({candidate:l,balance:i.get(Oe(l)?"native":l.toLowerCase())??0n})).filter(l=>l.balance>0n).sort((l,u)=>l.balance===u.balance?0:l.balance>u.balance?-1:1);return c.length===0?null:((a>0n?c.find(l=>l.balance>=a):c[0])??c[0]).candidate};try{const i=await Promise.all(r.map(async u=>({key:Oe(u)?"native":u.toLowerCase(),value:await Ql(t,u)}))),c=new Map(i.map(({key:u,value:d})=>[u,d])),l=s(c);if(l)return l}catch{}return o}function ya(e,t,n,o){const r=en(e,t),a=en(n,o);return r&&a?Hl(r.equivalenceGroup,a.equivalenceGroup):jp(e,n)}function hs(e,t){return ya(e.address,e.chainId,t.address,t.chainId)}const Kl=.01;function Yl(e,t=!1){const n=Number.isFinite(e.balanceUsd)&&e.balanceUsd>0;return e.isDiscovered?n&&e.balanceUsd>=Kl:!t||!n||e.balanceUsd>=Kl}function Hr(e,t=!1){return!!e&&e._source==="wallet"&&(e.location==="external"||e._fundingWallet==="external"||!e.location&&!e._fundingWallet&&t)}function be(e){return e.positionId??`${e.owner?.toLowerCase()??""}:${e.location??e._source??""}:${e.chainId}:${e.receiptTokenId??ut(e.address).toLowerCase()}`}function Zl(e,t){if(!t?.length||e.symbol!==void 0&&Ja({...e,symbol:e.symbol},t))return!0;const n=o=>t.some(r=>Q(ut(r),ut(o)));return n(e.address)||Object.keys(e.chainTokens??{}).some(o=>{const r=_n(o);return r?n(r.address):!1})}function To(e,t,n,o,r,a){const s=(g,h=!1)=>({eligible:!1,reason:g,policyExcluded:h}),i=e._source==="wallet"||e.location==="external"||e.location==="embedded",c=t==="spend-source"&&i&&!!o&&e.chainId===o.chainId&&Q(ut(e.address),ut(o.address));if(n.isWhitelistGateActive||!c&&!Ja(e,n.allowedTokens))return s("Asset excluded by client policy",!0);if(t!=="withdraw-destination"&&!c&&!Yl(e))return s("Asset is unpriced or below the minimum value",!0);if(t==="holding")return{eligible:!0,reason:null};if(e.balanceError)return s(e.balanceError);if(!c&&!Zl(e,r))return s("Asset excluded by action policy",!0);const l=new Set(o?[o.chainId]:[]);e._source!=="spice"&&e.location!=="rollup"&&l.add(e.chainId);for(const g of l)if(!$a(g,n.rpcOverrides)?.trim())return s(`Configure SpiceFlowProvider rpcOverrides[${g}] before using this asset.`);if(a?.requiresEscrow){const g=en(e.address,e.chainId);if(!g||!wa(g))return s("This asset has no supported escrow mapping")}if(!o)return{eligible:!0,reason:null};const u=n.liquidityVenues?.includeDefaults===!1?n.liquidityVenues.venues??[]:[...xi,...n.liquidityVenues?.venues??[]],d=g=>u.some(h=>h.chainId===g),p=i&&e.chainId!==o.chainId,w=p?Ci(e,o.chainId):null;if(p&&!w)return s("No supported source route");if(w&&!Q(ut(e.address),ut(w.source.address))&&!d(e.chainId))return s("No conversion venue configured on the source chain");const f=w?.destination.address??co(e,o.chainId);return t==="withdraw-destination"?(e.chainTokens||e.receiptTokenId?zr(e,o.chainId):f?[f]:[]).some(g=>Q(ut(g),ut(o.address)))?{eligible:!0,reason:null}:s("No supported withdrawal mapping"):f&&Q(ut(f),ut(o.address))?{eligible:!0,reason:null}:!f&&!Yf(e,o.chainId)?s("No supported destination route"):d(o.chainId)?{eligible:!0,reason:null}:s("No conversion venue configured on the destination chain")}function gs(){const e=pn(on),[t]=q(Ap);return e?.inventory??t}function Si(e,t,n,o,r){const a=gs(),s=r??a,i=Ie(()=>s.entry(e),[s,e]),[,c]=q(0);me(()=>{if(n)return i.subscribe(()=>c(u=>u+1),t,o)},[i,n,t,o]);const l=ae(()=>i.refresh(),[i]);return{...n?i.snapshot():Ep,refresh:l}}var Xl="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==",Zf="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=",Xf="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=",ba="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 xa=ni(1)?.logo??"",Jf=el.find(e=>e.symbol==="USDC")?.logo??"",dr=Object.fromEntries([...Gp(),...Kp()].map(e=>[e.id,e.logo])),va={metamask:Xl,metaMask:Xl,rabby:Zf,phantom:Xf},Ai=Object.fromEntries(el.map(e=>[e.symbol.toUpperCase(),e.logo])),$f={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]},_f={btc:["wcbtc","cbtc","wbtc"]};function ws(e){return e.replace(/^test\s*/i,"").replace(/^spice/i,"").trim()}function Ko(e){return ws(e).toLowerCase()}function Jl(e){return Ko(e??"").replace(/[^a-z0-9]/g,"")}function Ei(e){const t=Ko(e);return[t,..._f[t]??[]].filter(Boolean)}function em(e){try{return BigInt(e.balanceAvailable||"0")}catch{return 0n}}function $l(e){return Array.isArray(e.chainTokens)?e.chainTokens:Object.keys(e.chainTokens??{})}function _l(e,t){const n=xt(e),o=t.toLowerCase();return o===Yt.toLowerCase()?n?.nativeCurrency.decimals??18:n?.supportedTokens?.find(r=>r.address.toLowerCase()===o)?.decimals??18}function tm(e,t,n,o=[]){const r=_l(t,n),a=e.filter(i=>ed(i,t,n,o));if(a.length===0)return null;const s=a.reduce((i,c)=>Math.min(i,c.decimals??r),r);return{chainDecimals:r,receiptDecimals:s}}function ed(e,t,n,o){if($l(e).some(a=>{const s=_n(a);return s&&ya(s.address,s.chainId,n,t)}))return!0;const r=new Set(o.map(Jl).filter(Boolean));return r.size===0?!1:r.has(Jl(e.tokenName||e.receiptToken))}function td(e,t,n,o=[]){const r=_l(t,n);return e.reduce((a,s)=>ed(s,t,n,o)?a+bo(em(s),s.decimals??r,r):a,0n)}function nd(e,t){const n=new Set([...Ei(t),...Ei(ws(t))]);return[...e].sort((o,r)=>{const a=Ko(o.symbol),s=Ko(r.symbol),i=Ko(o.name),c=Ko(r.name),l=n.has(a)?0:n.has(i)?1:2,u=n.has(s)?0:n.has(c)?1:2;return l!==u?l-u:o.address.toLowerCase().localeCompare(r.address.toLowerCase())})[0]}function nm(e){const t=e&&e.length>0?e:Object.keys(_a).map(Number).filter(Number.isFinite),n=new Map;for(const o of t){const r=xt(o);if(!r)continue;const a=`${o}:${Yt.toLowerCase()}`;n.has(a)||n.set(a,{address:Yt,chainId:o,symbol:r.nativeCurrency.symbol,name:r.nativeCurrency.name,decimals:r.nativeCurrency.decimals,isNative:!0,logoURI:Ai[r.nativeCurrency.symbol.toUpperCase()]??r.logo});for(const s of r.supportedTokens??[]){const i=s.address.toLowerCase(),c=`${o}:${i}`;n.has(c)||n.set(c,{address:i,chainId:o,symbol:s.symbol,name:s.name,decimals:s.decimals,isNative:Oe(i),logoURI:s.logo})}}return n}function om(e,t){const n=nm(t),o=ws(e.tokenName),r=Ko(e.tokenName),a=Ei(e.tokenName),s=Array.isArray(e.chainTokens)?e.chainTokens.map(f=>[f,void 0]):Object.entries(e.chainTokens??{}),i=s.map(([f])=>_n(f)).filter(f=>f!==null),c=new Map;for(const[f,g]of s){const h=_n(f);if(!h||!Number.isSafeInteger(h.chainId)||h.chainId<0||!/^evm:[0-9]+:(?:0x)?[0-9a-fA-F]{40}$/.test(f)){if(!Array.isArray(e.chainTokens))throw new Error("Invalid chain token metadata identity");continue}if(g!==void 0&&(!g||typeof g!="object"||Array.isArray(g)||g.name!==void 0&&typeof g.name!="string"||g.decimals!==void 0&&(!Number.isInteger(g.decimals)||g.decimals<0||g.decimals>255)))throw new Error("Invalid chain token metadata");const y=`${h.chainId}:${h.address.toLowerCase()}`;if(c.has(y)){const I=c.get(y);if(I?.name!==g?.name||I?.decimals!==g?.decimals)throw new Error("Conflicting chain token metadata")}c.set(y,g)}const l=(f,g)=>{const h=c.get(`${g.chainId}:${g.address.toLowerCase()}`);return{...f,name:typeof h?.name=="string"&&h.name.length>0?h.name:f.name,decimals:typeof h?.decimals=="number"?h.decimals:f.decimals}},u=i.map(f=>{const g=n.get(`${f.chainId}:${f.address.toLowerCase()}`);return g?l(g,f):void 0}).filter(f=>f!==void 0),d=$f[r]??[];if(d.length>0)for(const f of d){const g=u.filter(h=>h.chainId===f);if(g.length>0)return nd(g,e.tokenName)}if(u.length>0)return nd(u,e.tokenName);const p=Array.from(n.values()).filter(f=>a.includes(Ko(f.symbol))||a.includes(Ko(f.name)));if(d.length>0)for(const f of d){const g=p.find(h=>h.chainId===f);if(g)return g}if(p.length>0)return p[0];const w=i[0];if(w){const f=c.get(`${w.chainId}:${w.address.toLowerCase()}`);return{address:w.address,chainId:w.chainId,symbol:o||e.tokenName,name:typeof f?.name=="string"&&f.name.length>0?f.name:o||e.tokenName,decimals:typeof f?.decimals=="number"?f.decimals:e.decimals??18,isNative:Oe(w.address),logoURI:void 0}}}function rm(e,t){let n;try{n=BigInt(e.balanceAvailable||"0")}catch{return null}if(n<=0n)return null;if(t?.length){const f=$l(e).map(_n).filter(g=>g!==null);if(f.length>0&&!f.some(g=>t.includes(g.chainId)))return null}let o;try{o=om(e,t)}catch{return null}const r=o?.decimals??e.decimals??18,a=e.decimals??r,s=bo(n,a,r),i=o?.address??Yt,c=o?.chainId??0,l=ws(e.tokenName),u=o?.symbol??l,d=o?.name??l,p=parseFloat(Ne(s,r)),w=typeof e.balanceUsd=="number"?e.balanceUsd:typeof e.balanceUsd=="string"&&Number(e.balanceUsd)||0;return{address:i,symbol:u,name:d,decimals:r,chainId:c,balance:s,balanceFormatted:p,balanceUsd:w,isNative:o?.isNative??Oe(i),logoURI:o?.logoURI,displaySymbol:l||u,displayName:l||d,displayChainName:"Spicenet",receiptTokenId:e.receiptToken,receiptTokenName:e.tokenName||d,receiptTokenDecimals:a,chainTokens:e.chainTokens&&!Array.isArray(e.chainTokens)?e.chainTokens:void 0,isUniversal:!0}}const Fi=6e4,am=3e5,od="https://api.g.alchemy.com/prices/v1",Vr=new Map;function ys(e,t){try{const n=t??$a(e);if(typeof n!="string")return null;const{hostname:o,pathname:r}=new URL(n);if(!o.endsWith(".g.alchemy.com"))return null;const a=r.split("/").filter(Boolean).pop();return a?{network:o.slice(0,-14),key:a}:null}catch{return null}}const Ia=(e,t)=>`${e.network}:${e.key}:${t.toLowerCase()}`;function Er(e,t){const n=Vr.get(Ia(e,t));if(!n?.price||n.updatedAt===void 0)return;const o=Date.now()-n.updatedAt;if(!(o>=am))return{price:n.price,stale:o>=Fi}}function rd(e){const t=Number(e.prices?.find(n=>n.currency==="usd")?.value);return Number.isFinite(t)&&t>0?t:0}async function ad(e,t,n){const o=[],r=new Set,a=Date.now();for(const s of new Set(t.map(i=>i.toLowerCase()))){const i=Vr.get(Ia(e,s));i?.pending?r.add(i.pending):(!i||a-i.attemptedAt>=Fi&&(i.updatedAt===void 0||a-i.updatedAt>=Fi))&&o.push(s)}for(let s=0;s<o.length;s+=25){const i=o.slice(s,s+25),c=Promise.resolve().then(async()=>{try{const l=await n(i);for(const u of i){const d=l.get(u);if(!d)continue;const p=Vr.get(Ia(e,u));p.price=d,p.updatedAt=Date.now()}}catch{}finally{for(const l of i)Vr.get(Ia(e,l)).pending=void 0}});for(const l of i){const u=Ia(e,l);Vr.set(u,{...Vr.get(u),attemptedAt:a,pending:c})}r.add(c)}await Promise.all(r)}async function Ti(e,t){return await ad(e,t,async n=>{const o=await fetch(`${od}/${e.key}/tokens/by-address`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({addresses:n.map(s=>({network:e.network,address:s}))}),signal:AbortSignal.timeout(1e4)});if(!o.ok)throw new Error("Provider price request failed");const r=await o.json(),a=new Map;for(const s of r?.data??[]){if(s.network&&s.network!==e.network)continue;const i=String(s.address).toLowerCase();n.includes(i)&&a.set(i,rd(s))}return a}),new Map(t.map(n=>[n.toLowerCase(),Er(e,n)?.price??0]))}async function Bi(e,t){const n=`native:${t}`;return await ad(e,[n],async()=>{const o=await fetch(`${od}/${e.key}/tokens/by-symbol?symbols=${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(1e4)});if(!o.ok)throw new Error("Provider native price request failed");const r=(await o.json())?.data?.find(a=>a.symbol?.toUpperCase()===t.toUpperCase());return new Map([[n.toLowerCase(),r?rd(r):0]])}),Er(e,n)?.price??0}async function sm(e,t){const n=t.supportedChains,o=e.map(r=>{const a=Object.keys(r.chainTokens??{}).map(_n).filter(s=>!!s&&Qn(s.address)&&!!n?.includes(s.chainId));return a.sort((s,i)=>{const c=l=>l===t.nativeChainId?-1:n.indexOf(l);return c(s.chainId)-c(i.chainId)||+!Q(s.address,r.address)-+!Q(i.address,r.address)}),a.flatMap(s=>{const i=t.rpcOverrides?.[s.chainId];if(!i)return[];const c=ys(s.chainId,i);if(!c)return[];const l=Oe(s.address)?xt(s.chainId)?.nativeCurrency.symbol:void 0,u=l?`native:${l}`:s.address;return[{rpc:c,token:u,address:s.address,nativeSymbol:l}]})});return(typeof document>"u"||!document.hidden)&&await Promise.all(o.map(async r=>{for(const a of r)if(a.nativeSymbol?await Bi(a.rpc,a.nativeSymbol).catch(()=>0):await Ti(a.rpc,[a.address]).catch(()=>new Map),Er(a.rpc,a.token)?.stale===!1)break})),e.map((r,a)=>{const s=o[a].map(c=>Er(c.rpc,c.token)),i=s.find(c=>c&&!c.stale)??s.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 im(e,t,n){const o=pn(on),[r,a]=q(()=>typeof document>"u"||!document.hidden);me(()=>{const u=()=>a(!document.hidden);return document.addEventListener("visibilitychange",u),()=>document.removeEventListener("visibilitychange",u)},[]);const s={supportedChains:n??o?.supportedChainIds,nativeChainId:o?.nativeChainId,rpcOverrides:o?.rpcOverrides},i=JSON.stringify([e,s],(u,d)=>typeof d=="bigint"?d.toString():d),c=ae(()=>sm(e,s),[i]),l=Si(`prices:${i}`,c,t&&r&&e.length>0,6e4);return l.updatedAt?l.assets:e}function cm(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 sd=({address:e,supportedChains:t,enabled:n=!0,refetchInterval:o,priceEnabled:r=!1})=>{const a=pn(on),s=a?.apiUrl||Tp,i=gs(),c=a?.supportedChainIds??t,l=JSON.stringify([...c??[]].sort((T,k)=>T-k)),u=e?.toLowerCase(),d=ae(async()=>{const T=`${s}/wallets/${u}/balance`;let k,b;try{const S=await Fp(T,{cache:"no-store"});if(k=S.status,b=S.requestId,!S.ok)throw new Error(`Failed to fetch balance: ${S.status}`);const E=await S.json();if(!Array.isArray(E.balances))throw new Error("Invalid balance response");return E.balances.map(F=>{const P=rm({receiptToken:typeof F.receiptToken=="string"?F.receiptToken:void 0,tokenName:String(F.tokenName??""),balanceAvailable:String(F.balanceAvailable??"0"),chainTokens:cm(F),decimals:typeof F.decimals=="number"?F.decimals:void 0,balanceUsd:typeof F.balanceUsd=="number"||typeof F.balanceUsd=="string"?F.balanceUsd:null},c);return P?{...P,owner:u,location:"rollup",_source:"spice",positionId:`${u}:rollup:${P.receiptTokenId??P.address}`}:null}).filter(F=>F!==null)}catch(S){const E=S instanceof Error?S.name:void 0,F=k===429?"Balance refresh is temporarily busy. Wait a moment and try again.":k===408||k===504||E==="TimeoutError"?"Balance refresh timed out. Try again.":E==="AbortError"?"Balance refresh was interrupted. Try again.":"Balances are unavailable. Check your connection and try again.",P=new ke("RELAYER_STATUS_ERROR",F,{endpoint:T,httpStatus:k,requestId:b,cause:S});throw Ln(P),P}},[u,s,l,a?.nativeChainId,a?.rpcOverrides]),{assets:p,loading:w,refreshing:f,error:g,updatedAt:h}=Si(`rollup:${u}:${s}:${l}`,d,n&&!!u,o??0,i),y=JSON.stringify(t??[]),I=Ie(()=>g?p.map(T=>({...T,balanceError:g,balanceStatus:"stale"})):p,[p,g]),A=im(I,n&&r,c),v=Ie(()=>A.filter(T=>!t?.length||t.includes(T.chainId)||Object.keys(T.chainTokens??{}).some(k=>t.some(b=>k.startsWith(`evm:${b}:`)))),[A,y]),C=ae(T=>v.filter(k=>k.chainId===T),[v]);return{assets:v,loading:w,error:g,hasBalance:v.some(T=>T.balance>0n),refreshing:f,updatedAt:h,refetch:i.invalidate,getAssetsByChain:C}};async function lm(e,t,n){if(n)return{decimals:n.decimals,symbol:n.symbol,name:n.name,logoURI:n.logo};const[o,r,a]=await Promise.all([lr(e,{address:t,abi:pt,functionName:"decimals"}),lr(e,{address:t,abi:pt,functionName:"symbol"}).catch(()=>"TOKEN"),lr(e,{address:t,abi:pt,functionName:"name"}).catch(()=>"TOKEN")]);if(!Number.isInteger(Number(o))||Number(o)<0||Number(o)>255)throw new Error("Invalid token decimals");return{decimals:Number(o),symbol:r,name:a,logoURI:void 0}}const id=async(e,t,n)=>{const o=Ot(t,n),r=xt(t),a=await ci(o,{address:e}),s=r.nativeCurrency,i=r.supportedTokens?.find(c=>Oe(c.address));return{address:Yt,name:s.name,symbol:s.symbol,decimals:s.decimals,balance:a,balanceFormatted:Number(Ne(a,s.decimals)),balanceUsd:0,priceStatus:"unavailable",logoURI:i?.logo||r.logo,isNative:!0,chainId:t}},dm=async(e,t,n,o,r,a,s)=>{try{if(!Qn(n))return null;const i=gn(n),c=Qn(e)?gn(e):e,l=Ot(t,s),u=await lr(l,{address:i,abi:pt,functionName:"balanceOf",args:[c]}),d=Number(Ne(u,a));return u>0n?{address:i,name:o,symbol:r,decimals:a,balance:u,balanceFormatted:d,balanceUsd:0,priceStatus:"unavailable",logoURI:void 0,isNative:!1,chainId:t}:null}catch(i){throw i}},cd=(e,t)=>{const n=xt(t);if(!n)return e;const o=new Set(e.map(a=>a.address.toLowerCase())),r=e.some(a=>a.isNative);for(const a of n.supportedTokens||[])Oe(a.address)&&r||o.has(a.address.toLowerCase())||e.push({address:a.address,name:a.name,symbol:a.symbol,decimals:a.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,priceStatus:"unavailable",logoURI:a.logo,isNative:Oe(a.address),chainId:t});if(!e.find(a=>a.isNative)){const a=n.supportedTokens?.find(s=>Oe(s.address));e.push({address:Yt,name:n.nativeCurrency.name,symbol:n.nativeCurrency.symbol,decimals:n.nativeCurrency.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,priceStatus:"unavailable",logoURI:a?.logo||n.logo,isNative:!0,chainId:t})}return e},um=async(e,t,n)=>{const o=[],r=async i=>{for(const c of i){const l=await dm(e,t,c.address,c.name,c.symbol,c.decimals,n);l&&(l.logoURI=c.logo,o.push(l))}},a=await id(e,t,n);a.balance>0n&&o.push(a);const s=(xt(t)?.supportedTokens||[]).filter(i=>!Oe(i.address));if(s.length>0)try{const i=Ot(t,n),c=gn(e),l=s.filter(w=>Qn(w.address)).map(w=>({address:gn(w.address),abi:pt,functionName:"balanceOf",args:[c]})),u=await i.multicall({contracts:l}),d=s.filter(w=>Qn(w.address)),p=[];u.forEach((w,f)=>{if(w.status==="success"){const g=w.result;if(g&&g>0n){const h=d[f],y=Number(Ne(g,h.decimals));g>0n&&o.push({address:gn(h.address),name:h.name,symbol:h.symbol,decimals:h.decimals,balance:g,balanceFormatted:y,balanceUsd:0,priceStatus:"unavailable",logoURI:h.logo,isNative:!1,chainId:t})}}else p.push(d[f])}),await r(p)}catch{await r(s)}return{tokens:cd(o,t),chainId:t}},pm=async(e,t,n)=>{const o=new Map,r=ys(e,n?n[e]??"":void 0);if(!r)return o;const a=t.filter(l=>Oe(l)),s=t.filter(l=>!Oe(l)),[i,c]=await Promise.all([s.length?Ti(r,s).catch(()=>new Map):new Map,a.length?Bi(r,xt(e)?.nativeCurrency?.symbol??"ETH").catch(()=>0):0]);for(const[l,u]of i)u>0&&o.set(l,u);if(c>0)for(const l of a)o.set(l.toLowerCase(),c);return o},fm=async(e,t,n,o=!0,r)=>{const a=Ot(t,r),s=gn(e),i=[];let c;do{const g=await a.request({method:"alchemy_getTokenBalances",params:[s,"erc20",c?{pageKey:c}:{}]});i.push(...g.tokenBalances),c=g.pageKey||void 0}while(c);const l=i.filter(g=>Qn(g.contractAddress)&&!!g.tokenBalance&&BigInt(g.tokenBalance)>0n),u=xt(t)?.supportedTokens||[],d=g=>u.find(h=>h.address.toLowerCase()===g.toLowerCase()),p=[],w=await id(e,t,r),[f]=await Promise.all([Promise.all(l.map(async g=>{const h=d(g.contractAddress);return h?{name:h.name,symbol:h.symbol,decimals:h.decimals,logo:h.logo??null}:await a.request({method:"alchemy_getTokenMetadata",params:[g.contractAddress]})})),o?Ti(n,l.map(g=>g.contractAddress)):void 0,o&&w.balanceFormatted>0?Bi(n,w.symbol):void 0]);if(w.balance>0n){const g=Er(n,`native:${w.symbol}`);p.push({...w,balanceUsd:(g?.price??0)*w.balanceFormatted,priceStatus:g?g.stale?"stale":"fresh":"unavailable"})}return l.forEach((g,h)=>{const y=f[h];if(!Number.isInteger(y.decimals)||y.decimals===null||y.decimals<0||y.decimals>255)throw new Error(`Invalid token metadata on chain ${t}`);const I=BigInt(g.tokenBalance),A=Number(Ne(I,y.decimals));if(I<=0n)return;const v=Er(n,g.contractAddress),C=(v?.price??0)*A;p.push({address:gn(g.contractAddress),name:y.name||"Unknown",symbol:y.symbol||"UNKNOWN",decimals:y.decimals,balance:I,balanceFormatted:A,balanceUsd:C,priceStatus:v?v.stale?"stale":"fresh":"unavailable",isDiscovered:!d(g.contractAddress),logoURI:y.logo||void 0,isNative:!1,chainId:t})}),{tokens:cd(p,t),chainId:t}},ld=new Set,mm=async(e,t,n=!0,o)=>{try{const r=ys(t,o?o[t]??"":void 0);if(r)try{return await fm(e,t,r,n&&(typeof document>"u"||!document.hidden),o)}catch(a){ld.has(t)||(ld.add(t),console.warn(`Token discovery unavailable on chain ${t}; listing configured tokens only.`,a))}return await um(e,t,o)}catch(r){throw r}},Qr=async(e,t,n=[],o)=>{if(!e)throw new Error("Wallet address is required");const r=Bp(o),a=t?.length?[...new Set(t)]:Object.keys(r).map(Number),s=await Promise.allSettled(a.map(c=>mm(e,c,!0,o))),i={};return s.forEach((c,l)=>{const u=a[l];i[u]=c.status==="fulfilled"?c.value:{chainId:u,tokens:[],error:`Unable to refresh balances on chain ${u}`}}),(await Promise.allSettled(n.map(async c=>{const l=i[c.chainId];if(!l||l.error||l.tokens.some(h=>ut(h.address).toLowerCase()===ut(c.address).toLowerCase()))return;const u=Ot(c.chainId,o),d=await lm(u,c.address,c.decimals!==void 0&&c.symbol?{decimals:c.decimals,symbol:c.symbol,name:c.name||c.symbol,logo:c.logoURI}:void 0),p=await lr(u,{address:c.address,abi:pt,functionName:"balanceOf",args:[e]});await pm(c.chainId,[c.address],o);const w=Number(Ne(p,d.decimals)),f=ys(c.chainId,o?o[c.chainId]??"":void 0),g=f?Er(f,c.address):void 0;l.tokens.push({...d,...c,name:d.name,symbol:d.symbol,decimals:d.decimals,balance:p,balanceFormatted:w,balanceUsd:(g?.price??0)*w,priceStatus:g?g.stale?"stale":"fresh":"unavailable",isNative:!1})}))).forEach((c,l)=>{if(c.status==="rejected"){const u=i[n[l].chainId];u&&(u.error=`Unable to refresh token balances on chain ${u.chainId}`)}}),i},ka=({address:e,supportedChains:t,fetchBalances:n=Qr,additionalTokens:o=[],enabled:r=!0,refreshInterval:a=0,priceEnabled:s=!0})=>{const i=pn(on),c=gs(),l=e?.toLowerCase(),u=JSON.stringify([...i?.supportedChainIds??t??[]].sort((I,A)=>I-A)),d=JSON.stringify(o);me(()=>c.registerTokens(o),[c,d]);const p=l&&l===i?.embeddedWalletAddress?.toLowerCase()?"embedded":"external",w=`wallet:${JSON.stringify([i?.network,i?.apiUrl,i?.rpcOverrides])}:${l}:${p}:${u}:${c.fetcherId(n)}`,f=ae(async()=>{let I;try{I=await n(l,JSON.parse(u),c.tokens(),i?.rpcOverrides)}catch(T){const k=T instanceof Error?T.message:"Unable to refresh balances";I=Object.fromEntries(JSON.parse(u).map(b=>[b,{chainId:b,tokens:[],error:k}]))}const A=c.entry(w).snapshot().assets,v=JSON.parse(u).map(T=>I[T]??{chainId:T,tokens:[],error:`Unable to refresh balances on chain ${T}`}),C=v.flatMap(T=>T.error?[T.error]:[]);return{assets:v.flatMap(T=>T.error?A.filter(k=>k.chainId===T.chainId).map(k=>({...k,balanceError:T.error,balanceStatus:"stale"})):T.tokens.map(k=>({...k,owner:l,location:p,_fundingWallet:p,_source:"wallet",positionId:`${l}:${p}:${T.chainId}:${ut(k.address).toLowerCase()}`}))),error:C.length?C.join("; "):null}},[c,l,u,n,p,w]),g=Si(w,f,r&&!!l,a,c),h=JSON.stringify(t&&[...t].sort((I,A)=>I-A)),y=Ie(()=>t?g.assets.filter(I=>t.includes(I.chainId)):g.assets,[g.assets,h]);return me(()=>{s&&r&&l&&g.refresh()},[s]),{...g,assets:y,refreshAssets:c.invalidate,getAssetsByChain:ae(I=>y.filter(A=>A.chainId===I),[y]),getNativeAssets:ae(()=>y.filter(I=>I.isNative),[y])}};function Fr(e){const t=pn(on),n=gs(),o=e.owner??((t?.mode||"7702")!=="7702"?t?.externalWalletAddress:t?.embeddedWalletAddress),r=o?.toLowerCase()!==t?.embeddedWalletAddress?.toLowerCase(),a=e.sourceChains??t?.supportedChainIds??[],s=(e.enabled??!0)&&!t?.isWhitelistGateActive,i=Ie(()=>{const p=[...t?.additionalSourceTokens??[],...e.additionalSourceTokens??[],...e.destination?[e.destination]:[]];for(const w of e.supportedSourceAssets??[])for(const f of a){const g=xt(f)?.supportedTokens?.find(h=>Ja(h,[w]));g&&p.push({...g,address:g.address,chainId:f,logoURI:g.logo})}return p},[e.destination,JSON.stringify(t?.additionalSourceTokens),JSON.stringify(e.additionalSourceTokens),JSON.stringify(e.supportedSourceAssets),JSON.stringify(a)]),c=ka({address:o,supportedChains:a,fetchBalances:Qr,additionalTokens:i,enabled:s&&e.includeWalletAssets!==!1,refreshInterval:3e4}),l=sd({address:o,supportedChains:a,enabled:s&&e.includeRollupAssets!==!1&&!!o&&o.toLowerCase()===t?.embeddedWalletAddress?.toLowerCase(),priceEnabled:s,refetchInterval:3e4}),u=Ie(()=>s?[...(e.includeWalletAssets===!1?[]:c.assets).map(p=>({...p,owner:p.owner??o,location:p.location??(r?"external":"embedded"),_source:"wallet"})),...(e.includeRollupAssets===!1||o?.toLowerCase()!==t?.embeddedWalletAddress?.toLowerCase()?[]:l.assets).map(p=>({...p,owner:p.owner??o,location:"rollup",_source:"spice"}))]:[],[s,c.assets,l.assets,e.includeWalletAssets,e.includeRollupAssets,o,r,t?.embeddedWalletAddress]),d=Ie(()=>u.map(p=>({asset:p,...To(p,e.role??"holding",{allowedTokens:t?.allowedTokens,rpcOverrides:t?.rpcOverrides,liquidityVenues:t?.liquidityVenues,isWhitelistGateActive:!!t?.isWhitelistGateActive},e.destination,e.supportedSourceAssets,{requiresEscrow:e.requiresEscrow})})),[u,t?.allowedTokens,t?.rpcOverrides,t?.liquidityVenues,t?.isWhitelistGateActive,e.role,e.destination,e.supportedSourceAssets,e.requiresEscrow]);return{positions:d,assets:Ie(()=>d.filter(p=>p.eligible&&p.asset.balance>0n).map(p=>p.asset),[d]),walletAssets:Ie(()=>u.filter(p=>p._source==="wallet"),[u]),rollupAssets:Ie(()=>u.filter(p=>p._source==="spice"),[u]),loading:c.loading||l.loading,refreshing:c.refreshing||l.refreshing,error:c.error||l.error,refresh:n.invalidate}}function bs(e,t=!0,n){const o=n?.pendingOnly===!0,r=qe.getBaseUrl(),a=`${r}:${e?.toLowerCase()??""}:${o}`,[s,i]=q({scope:a,actions:[],error:null,loading:t&&!!e,updatedAt:null,revision:0}),[c,l]=q(0),u=ae(()=>l(p=>p+1),[]);me(()=>{if(!t||!e){i(h=>h.scope===a&&h.actions.length===0&&!h.error&&!h.loading&&!h.updatedAt&&h.revision===0?h:{scope:a,actions:[],error:null,loading:!1,updatedAt:null,revision:0});return}const p=new AbortController,w=new Ir;w.setBaseUrl(r);let f;i(h=>({scope:a,actions:h.scope===a?h.actions:[],error:h.scope===a?h.error:null,loading:!0,updatedAt:h.scope===a?h.updatedAt:null,revision:h.scope===a?h.revision:0}));const g=async()=>{try{const h=await w.getWalletActions(e,{pendingOnly:o,signal:p.signal});p.signal.aborted||i(y=>({scope:a,actions:h,error:null,loading:!1,updatedAt:new Date().toISOString(),revision:y.scope===a?y.revision+1:1}))}catch(h){if(p.signal.aborted)return;const y=h instanceof ke&&h.context.httpStatus===404;i(y&&!o?I=>({scope:a,actions:[],error:null,loading:!1,updatedAt:new Date().toISOString(),revision:I.scope===a?I.revision+1:1}):I=>({scope:a,actions:I.scope===a?I.actions:[],error:"Activity is temporarily unavailable. Refresh to check again.",loading:!1,updatedAt:I.scope===a?I.updatedAt:null,revision:I.scope===a?I.revision:0}))}p.signal.aborted||(f=setTimeout(g,5e3))};return g(),window.addEventListener("online",u),()=>{p.abort(),f&&clearTimeout(f),window.removeEventListener("online",u)}},[r,e,t,a,o,c,u]);const d=s.scope===a;return{actions:t&&e&&d?s.actions:[],error:d?s.error:null,loading:t&&!!e&&(!d||s.loading),updatedAt:d?s.updatedAt:null,revision:d?s.revision:0,refresh:u}}function Oi(e){const t=G(0),n=G(null),o=G(e.run);o.current=e.run;const r=G(e.onSkip);r.current=e.onSkip;const a=G(e.onCleanup);a.current=e.onCleanup,me(()=>{if(!e.shouldRun){t.current+=1,n.current?.abort(),r.current?.();return}let s=!1,i=!1;const c=async p=>{if(p&&i)return;n.current?.abort();const w=new AbortController;n.current=w;const f=++t.current;i=!0;try{await o.current({isBackground:p,isCurrent:()=>!s&&t.current===f,signal:w.signal})}finally{i=!1}},l=window.setTimeout(()=>void c(!1),e.delayMs??250),u=()=>{document.hidden||c(!0)},d=e.backgroundIntervalMs?window.setInterval(u,e.backgroundIntervalMs):void 0;return d!==void 0&&document.addEventListener("visibilitychange",u),()=>{s=!0,n.current?.abort(),clearTimeout(l),d!==void 0&&(window.clearInterval(d),document.removeEventListener("visibilitychange",u)),a.current?.()}},[e.shouldRun,e.delayMs,e.backgroundIntervalMs,...e.deps])}function dd(e,t){if(e.length!==t.length)return!1;const n=Fo(e),o=Fo(t);return n.every((r,a)=>r.hash===o[a]?.hash)}const vo=e=>new Promise(t=>setTimeout(t,e)),hm="0xa9059cbb";function ud(e){const t=e.findIndex(r=>No(r.chainId));if(t<=0)return[];const n=new Map,o=(r,a,s)=>{if(s<=0n)return;const i=`${r}:${a.toLowerCase()}`,c=n.get(i);c?c.amount+=s:n.set(i,{chainId:r,token:a,amount:s})};for(const r of e.slice(0,t)){const a=pa(r.chainId);if(!(!a||a===Yt)){for(const s of r.calls)if(s.value&&s.value>0n&&Q(s.to,a)&&o(r.chainId,Yt,s.value),!!s.data?.startsWith(hm))try{const i=Jn({abi:pt,data:s.data});if(i.functionName!=="transfer")continue;const[c,l]=i.args;Q(c,a)&&o(r.chainId,s.to,l)}catch{}}}return[...n.values()]}function pd(e){const t=en(e.token,e.chainId);return[t?.equivalenceGroup,t?.symbol,t?.name]}function fd(e,t){return td(e,t.chainId,t.token,pd(t))}function gm(e,t){const n=tm(e,t.chainId,t.token,pd(t));return!n||n.receiptDecimals>=n.chainDecimals?t.amount:bo(bo(t.amount,n.chainDecimals,n.receiptDecimals),n.receiptDecimals,n.chainDecimals)}async function md(e){const{deposits:t,baseline:n,fetchEntries:o,timeoutMs:r=12e4,intervalMs:a,signal:s,wait:i=vo}=e;if(t.length===0)return!0;const c=new Map(t.map(d=>[d,fd(n,d)])),l=Date.now(),u=l+r;for(;!s?.aborted;){try{const f=await o();if(t.every(g=>fd(f,g)-c.get(g)>=gm(f,g)))return!0}catch{}const d=Date.now();if(d>=u)return!1;const p=d-l,w=a??(p<5e3?250:p<15e3?1e3:3e3);await i(Math.min(w,u-d))}return!1}function Ri(e,t){const n=Fo(e).map(o=>o.hash);return cr(jo([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,t,n]))}async function Di(e,t,n,o,r){if(o?.aborted)throw new ke("ABORT","Execution transaction aborted");const a={raw:Ri(t,n)},s=r?await e.signMessage(a,r):await e.signMessage(a);console.debug("[SpiceFlow:execution]",{phase:"signature-returned",at:Date.now()});const i=typeof s=="string"?s:s.signature;if(!i)throw new ke("SIGNATURE_FAILED","Failed to sign intent authorization. The wallet returned an empty signature.");return i}function wm(e){return e.domain==="spicenet"||No(e.chainId)}const hd=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;async function ym(e,t,n){const o=(u,d)=>new ke("SIGNATURE_FAILED","The wallet returned an invalid authorization. Review the action and try again.",{chainId:t.chainId,reason:u,...d?{cause:d}:{}});if(!e||typeof e!="object")throw o("missing-authorization");const r=e;for(const u of["address","contractAddress"])if(r[u]!==void 0&&(typeof r[u]!="string"||r[u].toLowerCase()!==t.address.toLowerCase()))throw o("authorization-target-mismatch");for(const u of["chainId","nonce"]){const d=r[u];if(d!==void 0&&(typeof d=="bigint"?d!==BigInt(t[u]):typeof d!="number"||!Number.isSafeInteger(d)||d!==t[u]))throw o(`authorization-${u}-mismatch`)}const{r:a,s,yParity:i}=r;if(typeof a!="string"||typeof s!="string"||!/^0x[0-9a-fA-F]{64}$/.test(a)||!/^0x[0-9a-fA-F]{64}$/.test(s)||i!==0&&i!==1||BigInt(a)===0n||BigInt(a)>=hd||BigInt(s)===0n||BigInt(s)>hd/2n)throw o("invalid-signature");const c={...t,r:a,s,yParity:i};let l;try{l=await af({hash:cr(rl(["0x05",sf([cs(t.chainId),t.address,t.nonce===0?"0x":cs(t.nonce)])])),signature:c})}catch(u){throw o("invalid-signature",u)}if(l.toLowerCase()!==n.toLowerCase())throw o("authorization-signer-mismatch");return c}async function Mi(e){const{chainBatches:t,signingAddress:n,actions:o,cache:r,signal:a,onSignatureRequested:s,beforeSign:i}=e;if(a?.aborted)throw new ke("ABORT","Execution transaction aborted");if(typeof n!="string"||!Qn(n,{strict:!1})||n.toLowerCase()===al)throw new ke("INVALID_PARAMS","A valid signing address is required.");for(const p of t)if(!Number.isSafeInteger(p.chainId)||p.chainId<=0)throw new ke("INVALID_PARAMS","A valid authorization chain is required.");const c=[...new Set(t.filter(p=>!wm(p)).map(p=>p.chainId))].map(p=>{const w=Op(p);if(!Qn(w,{strict:!1})||w.toLowerCase()===al)throw new ke("INVALID_PARAMS","A valid delegation target is required.");return{chainId:p,client:Ot(p),delegateContract:w}}),[l]=await Promise.all([Promise.all(c.map(async({chainId:p,client:w,delegateContract:f})=>{const g=Number(await Yp(n,w));if(!Number.isSafeInteger(g)||g<0)throw new ke("INVALID_PARAMS","The authorization nonce is invalid.");const h=[n.toLowerCase(),p,f.toLowerCase(),g].join(":");return{chainId:p,delegateContract:f,nonce:g,cacheKey:h,cached:r?.get(h)}})),c.length?o.prepareSigning?.():void 0]);if(await i?.(),a?.aborted)throw new ke("ABORT","Execution transaction aborted");const u=[];let d=!1;for(const{chainId:p,delegateContract:w,nonce:f,cacheKey:g,cached:h}of l){if(h===void 0&&d&&await i?.(),a?.aborted)throw new ke("ABORT","Execution transaction aborted");const y=h===void 0?await o.signAuthorization({contractAddress:w,chainId:p,nonce:f},s):h;let I;try{I=await ym(y,{address:w,chainId:p,nonce:f},n)}catch(A){throw r?.delete(g),A}if(a?.aborted)throw new ke("ABORT","Execution transaction aborted");d=!0,r?.set(g,I),u.push(I)}return u}const gd=15;function bm(e){return e.now-e.lastProgressAt>=e.pollTimeoutMs}function wd(e,t){return{intentId:e,steps:t.map(n=>({...n,status:"pending"})),overallStatus:"processing"}}function xs(e,t,n){const o=e.steps.map(i=>({...i})),r=o[t];if(!r)return e;n.status==="success"||n.status==="completed"?(o[t]={...r,status:"success",transactionHash:n.transactionHash},t+1<o.length&&o[t+1].status==="pending"&&(o[t+1]={...o[t+1],status:"processing"})):n.status==="reverted"||n.status==="error"?o[t]={...r,status:"failed",transactionHash:n.transactionHash,error:n.error}:o[t]={...r,status:"processing"};const a=o.some(i=>i.status==="failed"),s=o.every(i=>i.status==="success");return{...e,steps:o,overallStatus:a?"failed":s?"success":"processing"}}function xm({checkStepStatus:e,retryStep:t,maxRetries:n=3,pollingInterval:o=2500,pollTimeoutMs:r=3e5}){const[a,s]=q(null),i=G(null),c=G(null),l=G(!1),u=G(!1),d=G(0),p=G({}),w=G(0),f=ae(v=>{i.current=v,s(v)},[]),g=ae(()=>{c.current&&(clearInterval(c.current),c.current=null)},[]),h=ae(()=>{d.current=0,p.current={},w.current=0,l.current=!0,g(),f(null)},[g,f]),y=ae((v,C)=>{g(),l.current=!1,f(wd(v,C))},[g,f]),I=ae((v,C)=>{const T=i.current;T&&f(xs(T,v,C))},[f]),A=ae((v,C)=>{g(),l.current=!1,u.current=!1,d.current=0,p.current={},w.current=Date.now(),f(wd(v,C));const T=async()=>{if(!(l.current||u.current||!e)){u.current=!0;try{if(bm({now:Date.now(),lastProgressAt:w.current,pollTimeoutMs:r})){const S=i.current;S&&f({...S,steps:S.steps.map(E=>E.status==="success"?E:{...E,status:"failed",error:"Taking longer than expected. It may still complete - check the explorer, then refresh."}),overallStatus:"failed"}),l.current=!0,g();return}const k=i.current;if(!k)return;const b=k.steps.findIndex(S=>S.status!=="success");if(b===-1){l.current=!0,g();return}if(!(b===0||k.steps[b-1].status==="success"))return;try{const S=k.steps[b].stepId,{data:E}=await e(v,S);if(d.current=0,E.status==="success"&&(w.current=Date.now()),E.status==="reverted"){const P=p.current[S]||0;if(t&&P<n){p.current[S]=P+1;try{await t(v,S)}catch(B){console.error(`[intentStatus] retry failed for step ${S}:`,B)}f(xs(i.current,b,{status:"executing"}));return}}const F=xs(i.current,b,E);f(F),F.overallStatus!=="processing"&&(l.current=!0,g())}catch(S){d.current+=1,console.error(`[intentStatus] poll error (${d.current}/${gd}):`,S),d.current>=gd&&(f(xs(i.current,b,{status:"error"})),l.current=!0,g())}}finally{u.current=!1}}};T(),c.current=setInterval(T,o)},[e,t,n,o,r,g,f]);return me(()=>()=>g(),[g]),{intentStatus:a,startStatusPolling:A,beginStatusTracking:y,applyStepUpdate:I,stopStatusPolling:g,clearStatus:h}}function vm(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 Im=350,km=2500;async function yd(e){const{actionId:t,intentIndex:n,intentId:o,stepIndex:r,maxPolls:a=48,maxExecuteAttempts:s=3,pollsBeforeRetry:i=5,maxConsecutiveStatusErrors:c=15,onStatusMessage:l,onStepUpdate:u,signal:d,chainId:p,startWithExecute:w=!0,observeOnly:f=!1,relayer:g=qe,completeOnExecution:h=!1}=e;if(d?.aborted)throw new ke("ABORT","Execution transaction aborted");let y="pending",I,A,v=e.initialExecuteAttempts??0,C=0,T,k;const b=new Promise((E,F)=>{T=E,k=()=>F(new ke("ABORT","Execution transaction aborted"))}),S=()=>{v++,e.onExecuteAttempt?.(v),g.executeStep(t,n,r,{action:"execute"}).then(E=>{E.transactionHash&&(I=E.transactionHash),E.status==="success"&&T({status:E.status,transactionHash:E.transactionHash})}).catch(E=>{const F=E instanceof Error?E.message:String(E);console.warn(`[execution] executeStep ${r} attempt ${v} error (will poll):`,F)})};d?.addEventListener("abort",k,{once:!0});try{w&&!f&&v<s&&S();for(let E=0;E<a;E++){const F=E===0?Im:km;try{const B=await Promise.race([vo(F).then(()=>{}),b]);if(d?.aborted)throw new ke("ABORT","Execution transaction aborted");const R=B??await Promise.race([g.checkStepStatus(o,r,h).then(O=>O.data),b]);if(d?.aborted)throw new ke("ABORT","Execution transaction aborted");C=0,y=R.status,A=R.error;const x=R.transactionHash;x&&(I=x),h&&/^0x[0-9a-f]{64}$/i.test(x??"")&&(R.executionStatus==="success"||R.executionStatus==="reverted")&&(y=R.executionStatus,A=void 0),u?.({status:y,transactionHash:I,error:A})}catch(B){if(B instanceof Error&&(B.name==="AbortError"||B instanceof ke&&B.code==="ABORT"))throw B;if(C++,C>=c){if(!f)throw B;l?.("Status is temporarily unavailable. The backend continues this action.",I)}continue}if(!f&&y==="created"&&E>=v*i&&v<s&&S(),y==="reverted"||y==="error")throw new ke("ON_CHAIN_REVERT",vm(y,A),{status:y,txHash:I,actionId:t,intentId:o,stepId:r,chainId:p});if(y==="success"||y==="completed")return I;let P="Waiting for solver...";y==="executing"?P="Transaction executing...":y==="submitted"?P="Transaction submitted...":y==="created"&&(P="Waiting for relayer..."),l?.(P,I)}throw new ke("POLLING_EXHAUSTED",`Transaction is still processing (status: ${y}). 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:o,stepId:r,lastStatus:y,pollAttempts:a,maxPolls:a,txHash:I})}finally{d?.removeEventListener("abort",k)}}async function Cm(e){const{actionId:t,intentIndex:n,intentId:o,totalSteps:r,observeOnly:a,delayBeforeSpicenetStepMs:s=5e3,isSpicenetStep:i,beforeStep:c,maxExecuteAttemptsForStep:l,maxPolls:u=48,onStatusMessage:d,onStepUpdate:p,signal:w}=e;let f;for(let g=e.startStep??0;g<r;g++){if(!a&&g>0&&i?.(g)&&s>0&&await vo(s),a||await c?.(g),w?.aborted)throw new ke("ABORT","Execution transaction aborted");const h=l?.(g)??3,y=await yd({actionId:t,intentIndex:n,intentId:o,stepIndex:g,observeOnly:a,startWithExecute:e.startWithExecute,relayer:e.relayer,maxPolls:u,maxExecuteAttempts:h,initialExecuteAttempts:e.executeAttempts?.get(g),onExecuteAttempt:I=>e.executeAttempts?.set(g,I),maxConsecutiveStatusErrors:h===6?5:15,onStatusMessage:d,onStepUpdate:p?I=>p(g,I):void 0,signal:w,completeOnExecution:g===r-1&&i?.(g)===!1});y&&(f=y)}return f}const Sm="0xa9059cbb",Am=[Zp,kn,Kn];function bd(e){return Am.some(t=>Q(e,t))}function vs(e,t){return e.map(n=>{if(n.domain==="spicenet"||No(n.chainId)||n.calls.length===0)return n;const o=new Set((n.tokenTransfers??[]).filter(s=>(s.from==="escrow"||s.from==="solver")&&Q(s.to,t)).map(s=>s.token.toLowerCase()));if(o.size===0)return n;const r=[...o].some(Oe);let a=0;for(const s of n.calls){if(r&&s.value>0n&&s.data==="0x"&&bd(s.to)){a+=1;continue}if(!s.data?.startsWith(Sm))break;try{const i=Jn({abi:pt,data:s.data});if(i.functionName!=="transfer")break;const[c]=i.args;if(!bd(c)||!o.has(s.to.toLowerCase()))break;a+=1}catch{break}}return a===0?n:{...n,calls:n.calls.slice(a)}})}async function Ni(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 o=()=>new ke("ABORT","Execution observation retired");if(n?.aborted)throw o();const r=await new Promise((a,s)=>{const i=()=>s(o());n?.addEventListener("abort",i,{once:!0}),Promise.resolve().then(()=>e.waitForTransactionReceipt({hash:t,timeout:12e4,pollingInterval:2e3,confirmations:1})).then(a,s).finally(()=>n?.removeEventListener("abort",i))});if(n?.aborted)throw o();if(r.transactionHash?.toLowerCase()===t.toLowerCase()&&r.status==="reverted")throw new ke("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 Is(e){let t=e.hash,n=!1;const o=Date.now()+12e4,r=s=>s.transactionHash&&s.transactionHash.toLowerCase()!==t.toLowerCase();let a=await e.client.waitForTransactionReceipt({hash:t,timeout:12e4,pollingInterval:2e3,confirmations:1,onReplaced:s=>{const i=s.transaction,c=s.replacedTransaction;if(!(s.reason==="repriced"&&c?.hash?.toLowerCase()===t.toLowerCase()&&c?.to?.toLowerCase()===e.call.to.toLowerCase()&&(c.input??"0x").toLowerCase()===e.call.data.toLowerCase()&&BigInt(c.value??0)===e.call.value&&c?.from&&c.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()===c?.from?.toLowerCase()&&i.nonce===c?.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(a)&&a.status==="success"&&(a=await e.client.waitForTransactionReceipt({hash:t,timeout:Math.max(o-Date.now(),1),pollingInterval:2e3,confirmations:e.confirmations})),r(a))throw new Error("Unexpected transaction receipt; recover the submitted transaction before retrying");return{receipt:a,hash:t}}const Pi=10n,Em=5;function ks(e,t,n){return n?.calls.length&&n.amountOutMinimum>0n?[{chainId:e,token:t,amount:n.amountOutMinimum}]:[]}function Wi(e){return e.map(t=>({...t,calls:[...t.calls],tokenTransfers:t.tokenTransfers?[...t.tokenTransfers]:void 0}))}function Cs({token:e,recipient:t,amount:n}){return{to:e,value:0n,data:Wt({abi:pt,functionName:"transfer",args:[t,n]})}}function Fm({chainBatches:e,token:t,amount:n}){const o=Wi(e),r=o[o.length-1];if(!r)return o;const a=Mo(r.chainId);return r.calls=[...r.calls,Cs({token:t,recipient:a,amount:n})],o}function xd({chainBatches:e,user:t,token:n,grossAmount:o,gasFee:r,policy:a}){const s=Wi(e),i=s[s.length-1];if(!i)throw new ke("INVALID_PARAMS","Action-output escrow funding requires at least one chain batch.");const c=es(o,BigInt(a?.platformBps??Pi)),l=r+c;if(l>=o)throw new ke("INVALID_PARAMS","Borrow amount is too small after gas and Spicenet fees.",{grossAmount:o.toString(),gasFee:r.toString(),spicenetFee:c.toString()});const u=o-l,d=Mo(i.chainId),p=[];return r>0n&&p.push(Cs({token:n,recipient:a?.gasRecipient??kn,amount:r})),c>0n&&p.push(Cs({token:n,recipient:a?.platformRecipient??Kn,amount:c})),i.calls=[...i.calls,...p,Cs({token:n,recipient:d,amount:u})],i.tokenTransfers=[...i.tokenTransfers??[],...r>0n?[{from:t,to:kn,token:n,amount:r}]:[],...c>0n?[{from:t,to:Kn,token:n,amount:c}]:[],{from:t,to:d,token:n,amount:u}],{chainBatches:s,gasFee:r,spicenetFee:c,netEscrowAmount:u,outputCredit:{chainId:i.chainId,token:n,amount:o}}}async function vd({chainBatches:e,user:t,token:n,grossAmount:o,chainAuthorizations:r}){let a=0n,s,i=xd({chainBatches:e,user:t,token:n,grossAmount:o,gasFee:a});for(let c=0;c<Em;c+=1){const l=Fo(i.chainBatches),u=await qe.estimateBatchGas({user:t,outputToken:n,chainBatches:i.chainBatches.map((p,w)=>({...p,hash:l[w].hash})),chainAuthorizations:r}),d=u.gasFee;if(d===a&&JSON.stringify(u.policy)===JSON.stringify(s))return i;s=u.policy,a=d,i=xd({chainBatches:e,user:t,token:n,grossAmount:o,gasFee:a,policy:s})}throw new ke("INVALID_PARAMS","Action-output fee estimate did not converge. Please retry.")}function Uo(e){return No(e.chainId)}const Tm="0xa9059cbb";function Ca(e,t){return`${e}:${ut(t).toLowerCase()}`}function Id(e,t){return t===Yt.toLowerCase()?{symbol:io(e),decimals:18}:en(t,e)??{symbol:"tokens",decimals:18}}function Bm(e,t){const n=en(t,e);return[n?.equivalenceGroup,n?.symbol,n?.name]}async function Ui(e){return ts(e)}async function Li(e,t,n){const o=new Map,r=new Map,a=[...n?.walletFundingRequirement?[n.walletFundingRequirement]:[],...n?.walletFundingRequirements??[]];for(const d of a){if(d.amount<0n)throw new Error("Accepted wallet funding must not be negative");const p=Ca(d.chainId,d.token);r.set(p,(r.get(p)??0n)+d.amount),o.set(p,0n)}const s=new Map,i=new Map,c=new Map,l=new Map;for(const d of n?.actionOutputCredits??[]){const p=Ca(d.chainId,d.token);l.set(p,(l.get(p)??0n)+d.amount)}for(const d of e){if(Uo(d))continue;for(const f of d.tokenTransfers??[]){if(f.from!=="escrow"&&f.from!=="solver"||!Q(f.to,t))continue;const g=BigInt(f.amount??0);if(g<=0n)continue;const h=Ca(d.chainId,f.token);s.set(h,(s.get(h)??0n)+g),f.from==="escrow"&&i.set(h,(i.get(h)??0n)+g)}const p=pa(d.chainId),w=f=>!!p&&p!==Yt&&Q(f,p);for(const f of d.calls){if(f.value&&f.value>0n){const g=Ca(d.chainId,Yt);o.set(g,(o.get(g)??0n)+f.value),w(f.to)&&c.set(g,(c.get(g)??0n)+f.value)}if(f.data?.startsWith(Tm))try{const g=Jn({abi:pt,data:f.data});if(g.functionName!=="transfer")continue;const[h,y]=g.args,I=f.to.toLowerCase(),A=Ca(d.chainId,I);o.set(A,(o.get(A)??0n)+y),w(h)&&c.set(A,(c.get(A)??0n)+y)}catch{}}}let u=null;for(const[d,p]of i){const w=p-(c.get(d)??0n);if(w<=0n)continue;const[f,g]=d.split(":"),h=Number(f),y=Id(h,g);u??(u=await Ui(t));const I=td(u,h,g,Bm(h,g));if(!(I>=w))throw new ke("INVALID_PARAMS",`Insufficient Spice ${y.symbol}: needs ${Ne(w,y.decimals)}, has ${Ne(I,y.decimals)}.`,{chainId:h,token:g,userAddress:t,requiredAmount:w.toString(),balance:I.toString(),balanceSource:"spice"})}for(const[d,p]of o){const[w,f]=d.split(":"),g=Number(w);let h=p-(s.get(d)??0n)-(l.get(d)??0n);const y=r.get(d)??0n;if(y>h&&(h=y),h<=0n)continue;const I=Ot(g),A=f===Yt.toLowerCase()?await I.getBalance({address:t}):await I.readContract({address:f,abi:pt,functionName:"balanceOf",args:[t]});if(A>=h)continue;const v=Id(g,f);throw new ke("INVALID_PARAMS",`Insufficient ${v.symbol} on ${io(g)}: needs ${Ne(h,v.decimals)}, has ${Ne(A,v.decimals)}.`,{chainId:g,token:f,userAddress:t,requiredAmount:h.toString(),balance:A.toString(),balanceSource:"wallet"})}}function Om({chainBatches:e,tokenAddress:t,tokenTransferAmount:n,useCustomTransfers:o}){if(!(e.some(Uo)||!(o?e.some(r=>Uo(r)?!1:(r.tokenTransfers??[]).some(a=>a.from==="escrow"&&BigInt(a.amount??0)>0n)):n>0n)))throw new ke("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:!!o})}function Rm(e,t,n,o){t.forEach((r,a)=>{if(!r.to||!r.from||!r.token||r.amount===void 0)throw new ke("INVALID_TOKEN_TRANSFER",`tokenTransfers[${a}] 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:a,transfer:{from:r.from,to:r.to,token:r.token,amount:r.amount?.toString()},signingAddress:n,useCustomTransfers:o})})}function Ss({user:e,chainBatches:t,tokenAddress:n,tokenTransferAmount:o,exp:r,signature:a,chainAuthorizations:s,useCustomTransfers:i}){const c=t,l=Fo(c),u=c.filter(d=>!Uo(d)).length;if(Om({chainBatches:c,tokenAddress:n,tokenTransferAmount:o,useCustomTransfers:i}),!i&&o>0n&&u>1)throw new ke("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:u,tokenAddress:n,tokenTransferAmount:o.toString()});return{user:e,...s?{chainAuthorizations:s}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:a,nbf:0,exp:r,chainBatches:l.map((d,p)=>{const w=c[p],f=Uo(w)?[]:i?w.tokenTransfers??[]:o>0n?[{from:"escrow",to:e,token:n,amount:o}]:[];return Rm(Number(d.chainId),f,e,i),{hash:d.hash,chainId:Number(d.chainId),tokenTransfers:f,calls:d.calls}})}]}}function kd(e,t){const n=t?.depositToEscrow?.gasFundingSource==="action-output"?t.depositToEscrow:null,o=t?.depositToEscrow&&!n?Fm({chainBatches:e,token:t.depositToEscrow.token,amount:t.depositToEscrow.amount}):Wi(e);return{actionOutputDeposit:n,batches:o}}let qi=!1;function jr(){const{address:e,isConnected:t,isAuthenticated:n,actions:o}=Oo(),r=G(null),a=G(0),s=G(null),{intentStatus:i,startStatusPolling:c,beginStatusTracking:l,applyStepUpdate:u,clearStatus:d}=xm({checkStepStatus:(A,v)=>qe.checkStepStatus(A,v),retryStep:async(A,v)=>{const[C,T]=A.split("/"),k=parseInt(T||"0",10);await qe.executeStep(C,k,v,{action:"execute"})}}),p=ae(()=>{a.current++,s.current=null,d()},[d]),w=G(o),f=G(new Map);w.current=o;const g=ae((A,v,C,T,k)=>Mi({chainBatches:A,signingAddress:v,actions:w.current,cache:f.current,signal:C,onSignatureRequested:T,beforeSign:k}),[]),h=ae((A,v,C,T)=>Di(w.current,A,v,C,T),[]),y=ae(async(A,v,C,T,k,b)=>{let S={},E={};const F=(B,R,x)=>{x?.actionId&&(S={actionId:x.actionId,intentId:x.intentId,intentIndex:x.intentIndex,totalSteps:x.totalSteps,autoContinue:x.autoContinue,user:b?.userOverride||e}),T?.({step:B,message:R,...E,...S,...x})};if(qi)throw new ke("CONCURRENT_EXECUTION","A execution transaction is already in progress. Please wait.");qi=!0;const P=a.current;try{if(!e)throw new ke("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const B=b?.userOverride||e,R=qe.getBaseUrl(),x=s.current;if(x&&Q(x.user,B)&&x.apiUrl===R){if(x.resume)return await x.resume(A,v,C,k,T,b);throw x.error}s.current=null;const O=Se=>tl(Se.map(Ze=>({...Ze,tokenTransfers:Ze.tokenTransfers??[]})),[]),M=O(A),U=Se=>new Map(Object.entries(Se??{}).filter(([Ze,xe])=>Ze!=="signal"&&(typeof xe!="function"||["prepareForSigning","adjustBatchesForEstimate","resolveActionOutputCredits"].includes(Ze))).map(([Ze,xe])=>[Ze,typeof xe=="function"?xe:JSON.stringify(xe,(Ke,ue)=>typeof ue=="bigint"?ue.toString():ue)])),V=U(b),j=await qe.supportsAutomaticContinuation({signal:k}),{actionOutputDeposit:_,batches:J}=kd(A,b);let K=J,ee=[],te=b?.useCustomTransfers,ge=ud(K),we=null;const ve=async()=>{(b?.walletFundingRequirement||b?.walletFundingRequirements?.length)&&await Li([],B,{walletFundingRequirement:b?.walletFundingRequirement,walletFundingRequirements:b?.walletFundingRequirements});for(let Se=0;ge.length>0&&Se<3;Se++)try{we=await Ui(B);break}catch(Ze){if(k?.aborted)throw new ke("ABORT","Execution transaction aborted");if(Se===2)throw new ke("RELAYER_ERROR","Unable to read your Spice balance. Please try again before submitting the transaction.",{cause:Ze});await vo(1e3)}await b?.validateBeforeSubmit?.(K)};F("building","Preparing your wallet and transaction...");const Ce=await g(K,B,k,()=>F("signing-delegation","Confirm the authorization in your wallet..."),ve);if(F("building","Checking transaction fees and balances..."),k?.aborted)throw new ke("ABORT","Execution transaction aborted");const ne=BigInt(Math.floor(Date.now()/1e3)+3600);if(_){const Se=await vd({chainBatches:A,user:B,token:_.token,grossAmount:_.amount,chainAuthorizations:Ce});K=Se.chainBatches,ee=[Se.outputCredit],te=!0}if(!b?.skipPreSubmitFeeEstimate){let Se=!1;if(b?.feeExecutionMode==="user-transfer"&&b.adjustBatchesForEstimate&&qe.canValidateActionFees()){const Ze=await qe.validateActionFees(Ss({user:B,chainBatches:K,tokenAddress:v,tokenTransferAmount:C,exp:Number(ne),signature:"0x00",chainAuthorizations:Ce,useCustomTransfers:te}),{signal:k});r.current=Ze;const xe=await b.adjustBatchesForEstimate({feeEstimate:Ze,chainBatches:K});Se=!xe||dd(K,xe),xe&&(K=xe)}for(let Ze=0;!Se&&Ze<10;Ze++){const xe=b?.feeExecutionMode==="user-transfer"?vs(K,B):K,Ke=Ss({user:B,chainBatches:xe,tokenAddress:v,tokenTransferAmount:C,exp:Number(ne),signature:"0x00",chainAuthorizations:Ce,useCustomTransfers:te}),ue=await qe.estimateActionFees(Ke,{signal:k});r.current=ue;const tt=await b?.adjustBatchesForEstimate?.({feeEstimate:ue,chainBatches:K}),vt=!!tt&&dd(K,tt);if(!tt||vt){Se=!0;break}K=tt}if(!Se)throw new ke("INVALID_PARAMS","Fee estimate did not converge. Please retry.")}if(b?.prepareForSigning){const Se=await b.prepareForSigning(K);if(Se.length!==K.length||Se.some((Ze,xe)=>Ze.chainId!==K[xe].chainId||Ze.domain!==K[xe].domain))throw new Error("The funded route changed before signing");K=Se}b?.resolveActionOutputCredits&&(ee=await b.resolveActionOutputCredits()),(!b?.skipUserFundingPreflight||b.walletFundingRequirement||b.walletFundingRequirements?.length)&&await Li(b?.skipUserFundingPreflight?[]:K,B,{actionOutputCredits:ee,walletFundingRequirement:b?.walletFundingRequirement,walletFundingRequirements:b?.walletFundingRequirements}),ge=ud(K),ge.length&&!we&&(we=await ts(B)),await b?.validateBeforeSubmit?.(K),F("building","Preparing the signing request...");const Y=await h(K,ne,k,()=>F("signing-intent","Confirm the transaction in your wallet..."));if(k?.aborted)throw new ke("ABORT","Execution transaction aborted");if(R!==qe.getBaseUrl())throw new ke("RELAYER_ERROR","The network changed before submission. Review your balances before trying again.");const ce=Ss({user:B,chainBatches:K,tokenAddress:v,tokenTransferAmount:C,exp:Number(ne),signature:Y,chainAuthorizations:Ce,useCustomTransfers:te});let W=K.length-1;for(;W>=0&&Uo(K[W]);)W--;E={totalSteps:K.length},W>=0&&(E={...E,destinationChainId:Number(K[W].chainId),destinationStepIndex:W});const Le=Date.now();if(F("submitting","Submitting to relayer..."),await b?.validateBeforeSubmit?.(K),k?.aborted)throw new ke("ABORT","Execution transaction aborted");if(R!==qe.getBaseUrl())throw new ke("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()-Le});const Te=K.length;let L;try{L=await qe.createAction({...ce,...b?.externalExecution?{externalExecution:b.externalExecution}:{}},{autoContinue:j,idempotencyKey:b?.idempotencyKey,signal:k,onAccepted:Se=>{const[Ze,xe="0"]=Se.intentIds[0].split("/"),Ke=parseInt(xe,10);F("executing","Executing on chain...",{actionId:Ze,intentId:`${Ze}/${Ke}`,intentIndex:Ke,totalSteps:Te,autoContinue:Se.autoContinue===!0})}})}catch(Se){throw P===a.current&&Se instanceof ke&&Se.context.submissionStatus==="unknown"&&(s.current={user:B,apiUrl:R,error:Se}),Se}const[z,oe]=L.intentIds[0].split("/"),de=parseInt(oe||"0",10),X=`${z}/${de}`;F("executing","Executing on chain..."),F("executing","Executing on chain...",{actionId:z,intentId:X,intentIndex:de,totalSteps:K.length,autoContinue:L.autoContinue===!0});const se=new Ir;se.setBaseUrl(R);let Pe,Ge=0;const Ee=new Map,De=async(Se,Ze=T,xe=!1)=>{const Ke=(ue,tt,vt)=>Ze?.({step:ue,message:tt,...vt});try{if((!xe||!Pe)&&(Pe=await Cm({actionId:z,intentIndex:de,intentId:X,totalSteps:Te,signal:Se,observeOnly:L.autoContinue===!0,startWithExecute:!xe,startStep:xe?Ge:0,executeAttempts:Ee,onStepUpdate:(ue,tt)=>{(tt.status==="success"||tt.status==="completed")&&(Ge=Math.max(Ge,ue+1))},relayer:L.autoContinue||xe?se:qe,...we?{delayBeforeSpicenetStepMs:0}:{},isSpicenetStep:ue=>Uo(K[ue]),beforeStep:async ue=>{if(L.autoContinue===!0||!we||!Uo(K[ue]))return;const tt=await md({deposits:ge,baseline:we,fetchEntries:()=>Ui(B),signal:Se});if(Se?.aborted)throw new ke("ABORT","Execution transaction aborted");if(!tt)throw new ke("POLLING_EXHAUSTED","Your deposit is still waiting for Spice credit. Check this transaction's status before trying again.",{actionId:z,intentId:X,stepId:ue})},maxExecuteAttemptsForStep:ue=>Uo(K[ue])?6:3,maxPolls:L.autoContinue?Number.POSITIVE_INFINITY:180,onStatusMessage:(ue,tt)=>{Ke("executing",ue,{txHash:tt,actionId:z,intentId:X,intentIndex:de,totalSteps:Te,autoContinue:L.autoContinue===!0})}})),b?.requireDestinationReceipt){const ue=[...K].reverse().find(tt=>!Uo(tt));if(!ue)throw new Error("The action has no destination transaction to verify.");await Ni(Ot(ue.chainId),Pe,Se)}return Ke("success","Transaction successful!",{txHash:Pe,actionId:z,intentId:X,intentIndex:de,totalSteps:Te,autoContinue:L.autoContinue===!0}),s.current?.resume===He&&(s.current=null),Pe||z}catch(ue){if(ue instanceof ke&&ue.code==="ON_CHAIN_REVERT"&&ue.context.status==="reverted"&&(ue.context.stepId===0||Te===1))throw s.current?.resume===He&&(s.current=null),ue;const tt=new ke(ue instanceof ke?ue.code:"RELAYER_STATUS_ERROR",ue instanceof ke&&ue.code==="ON_CHAIN_REVERT"?ue.message:`Your action was accepted, but its completion could not be confirmed. Check the original action before trying again. ${ue instanceof Error?ue.message:""}`.trim(),{...ue instanceof ke?ue.context:{},submissionStatus:"accepted",actionId:z,intentId:X,txHash:Pe,cause:ue});throw P===a.current&&(s.current={user:B,apiUrl:R,error:tt,resume:He}),tt}},He=async(Se,Ze,xe,Ke,ue,tt)=>{const vt=U(tt);if(M!==O(Se)||V.size!==vt.size||[...V].some(([it,st])=>vt.get(it)!==st)||!Q(v,Ze)||C!==xe)throw s.current.error;return De(Ke,ue,!0)};return await De(k,T)}catch(B){throw console.error("[Execution] Error:",B),F("error",B.message||"Transaction failed",{error:B.message,...B?.context?.submissionStatus==="unknown"?{submissionStatus:"unknown",...typeof B.context.idempotencyKey=="string"&&/^0x[0-9a-f]{64}$/i.test(B.context.idempotencyKey)?{idempotencyKey:B.context.idempotencyKey}:{},...typeof B.context.user=="string"&&/^0x[0-9a-f]{40}$/i.test(B.context.user)?{user:B.context.user}:{}}:{}}),B}finally{qi=!1}},[e,n,g,h]),I=ae(async(A,v,C,T)=>{if(!e&&(!T?.userOverride||T.signAuthorizationsForEstimate))throw new ke("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const k=T?.userOverride||e,b=T?.validateFeeCalls===!0&&T.feeExecutionMode==="user-transfer"&&qe.canValidateActionFees(),{actionOutputDeposit:S,batches:E}=kd(A,T);let F=E;const P=T?.feeExecutionMode==="user-transfer"&&!b?vs(F,k):F,B=T?.signAuthorizationsForEstimate?await g(P,k):void 0;let R=T?.useCustomTransfers;S&&(F=(await vd({chainBatches:A,user:k,token:S.token,grossAmount:S.amount,chainAuthorizations:B})).chainBatches,R=!0);const x=T?.feeExecutionMode==="user-transfer"&&!b?vs(F,k):F,O=Ss({user:k,chainBatches:x,tokenAddress:v,tokenTransferAmount:C,exp:Math.floor(Date.now()/1e3)+3600,signature:"0x00",chainAuthorizations:B,useCustomTransfers:R}),M=await(b?qe.validateActionFees(O,{signal:T?.signal}):qe.estimateActionFees(O,{signal:T?.signal}));return r.current=M,M},[e,g]);return{execute:y,estimate:I,lastFeeEstimate:r.current,hasEmbeddedWallet:t&&n,intentStatus:i,startStatusPolling:c,beginStatusTracking:l,applyStepUpdate:u,clearStatus:p}}function fn(e,t,n,o){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const r=10n**BigInt(t-n);return o==="ceil"?(e+r-1n)/r:e/r}function On(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(e,t)}function An(e,t,n){const o=fn(e,t,n,"floor");if(fn(o,n,t,"floor")!==e)throw new Error(`Use at most ${n} decimal places for this delivered token.`);return o}function Dm(e){return`0x77${e.slice(4)}`}function Sa({userAddress:e,destinationChainId:t,deliveryToken:n,deliveryAmount:o,withdrawalAmount:r,deliveryRecipient:a,deliveryTransfers:s,requestTimestampMs:i,expiresAt:c,metadata:l,requestNonce:u}){if(c!==void 0&&(!Number.isSafeInteger(c)||c<=0))throw new Error("Withdrawal expiry must be a positive Unix timestamp in seconds");const d=s?.length?s:[{token:n,recipient:a,amount:r??o}],p=d.reduce((y,I)=>y+I.amount,0n);if(p<=0n)return null;const w=i??Date.now(),f=BigInt(Math.floor(w/1e3)),g=e??a,h=Dm(cr(jo([{type:"address"},{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"},...u?[{type:"bytes32"}]:[]],[g,n,a,p,BigInt(t),BigInt(w),...u?[u]:[]])));return{chainId:nl,domain:"spicenet",tokenTransfers:[],calls:[{to:Yt,value:0n,data:Wt({abi:ss,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${t}`,idempotenceKey:h,nbf:0n,exp:c===void 0?f+3600n:BigInt(c),metadata:l??"{}",transfers:d.map(y=>({token:gn(y.token).toLowerCase(),to:gn(y.recipient).toLowerCase(),amount:y.amount}))}]})}]}}const zi=e=>{const[t,n]=q(!1),o=pn(on),{dark:r,dk:a}=cn();if(me(()=>{n(!0)},[]),!t)return m("div",{className:e.className,children:m("button",{disabled:!0,style:{padding:"12px 24px",fontSize:"16px",backgroundColor:r?a.hoverBg:"#ccc",color:r?a.textSecondary:"white",border:r?`1px solid ${a.buttonBorder}`:"none",borderRadius:"4px",cursor:"not-allowed"},children:"Loading..."})});if(!o){const s='ProviderLogin must be used within SpiceFlowProvider. Please wrap your app with <SpiceFlowProvider provider="privy">.';return m("div",{className:e.className,children:m("button",{onClick:()=>{e.onAuthError&&e.onAuthError(s)},style:{padding:"12px 24px",fontSize:"16px",backgroundColor:r?a.errorBg:"#dc2626",color:r?a.errorText:"white",border:r?`1px solid ${a.errorBorder}`:"none",borderRadius:"4px",cursor:"pointer"},children:"Provider Not Found"})})}return m(Rp,{...e})},Aa=({size:e=20,strokeWidth:t=2,color:n="currentColor",style:o})=>D("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:o,children:[m("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),m("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),Ea=(e,t,n,o)=>({width:e,height:e,fill:"none",className:t,"aria-hidden":n??!0,style:o}),Gr=({size:e=16,color:t="currentColor",strokeWidth:n=2,direction:o="down",className:r,style:a,"aria-hidden":s})=>m("svg",{...Ea(e,r,s,{transform:o==="up"?"rotate(180deg)":void 0,transition:"transform 0.3s ease",...a}),viewBox:"0 0 16 16",children:m("path",{d:"M4 6L8 10L12 6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),Mm=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:o,style:r,"aria-hidden":a})=>D("svg",{...Ea(e,o,a,r),viewBox:"0 0 24 24",children:[m("circle",{cx:"11",cy:"11",r:"8",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"}),m("path",{d:"m21 21-4.3-4.3",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})]}),Nm=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:o,style:r,"aria-hidden":a})=>m("svg",{...Ea(e,o,a,r),viewBox:"0 0 24 24",children:m("path",{d:"m6 9 6 6 6-6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),Pm=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:o,style:r,"aria-hidden":a})=>m("svg",{...Ea(e,o,a,r),viewBox:"0 0 24 24",children:m("path",{d:"m9 18 6-6-6-6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),Cd=({size:e=14,color:t="currentColor",strokeWidth:n=2,className:o,style:r,"aria-hidden":a})=>m("svg",{...Ea(e,o,a,r),viewBox:"0 0 16 16",children:m("path",{d:"M3 8L6.5 11.5L13 5",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),Sd=({isSuccess:e,type:t,chainName:n,explorerUrl:o,txHash:r,dark:a=!1,successBg:s="#d1fae5",successBorder:i="#6ee7b7",successText:c="#065f46",errorBg:l="#fee2e2",errorBorder:u="#fca5a5",errorText:d="#dc2626",textSecondary:p="#6b7280"})=>D("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px",borderRadius:"8px",backgroundColor:e?s:l,border:e?`1px solid ${i}`:`1px solid ${u}`},children:[D("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[m("div",{style:{width:"28px",height:"28px",borderRadius:"50%",backgroundColor:e?"#10b981":"#ef4444",display:"flex",alignItems:"center",justifyContent:"center"},children:e?m("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:m("path",{d:"M11.6667 3.5L5.25 9.91667L2.33333 7",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}):m("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:m("path",{d:"M10.5 3.5L3.5 10.5M3.5 3.5L10.5 10.5",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),D("div",{children:[m("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:ot.mono,letterSpacing:"0.5px",color:e?c:d},children:e?`${t.toUpperCase()} CONFIRMED`:`${t.toUpperCase()} FAILED`}),D("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:p},children:["on ",n]})]})]}),o&&r&&D("a",{href:`${o}/tx/${r}`,target:"_blank",rel:"noopener noreferrer",style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"13px",color:p,textDecoration:"none",whiteSpace:"nowrap"},children:["View on explorer",D("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:[m("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"}),m("path",{d:"M7.5 1.5H10.5V4.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),m("path",{d:"M5 7L10.5 1.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})]})]})]}),Ad=`
3
+ import{jsx as m,jsxs as D,Fragment as In}from"react/jsx-runtime";import{g as xt,a as Ot,S as ke,b as Q,c as Xa,i as Ja,d as $a,e as on,f as Ap,E as Ep,C as _a,r as Fp,R as Tp,s as Ln,h as Bp,j as qe,k as Ir,l as Op,m as es,u as Oo,n as ts,o as io,p as cn,P as Rp,q as ns,B as Kt,t as ot,v as go,w as Vo,x as Xs,y as Ur,z as kr,A as Qo,D as Kc,F as wo,G as Dp,H as la,I as da,J as os,K as Js,L as Mp,M as Yc,N as ua,O as Lr,Q as Np,T as qr,U as $s,V as _s,W as Ro,X as rs,Y as Cr,Z as Pp,_ as as,$ as Wp,a0 as ei,a1 as Up,a2 as Lp,a3 as ti,a4 as qp,a5 as Zc,a6 as zp,a7 as Hp,a8 as Vp}from"./privy-zcougfEy.js";import{a9 as q0,ab as z0,ac as H0,ae as V0,ad as Q0,aa as j0}from"./privy-zcougfEy.js";import Eo,{useContext as pn,useState as q,useMemo as Ie,useEffect as me,useCallback as ae,useRef as G,useId as Xc,useLayoutEffect as Do,memo as yo}from"react";import{isNativeToken as Oe,uniV3QuoterV2Abi as Qp,uniV3SwapRouterAbi as Jc,applySlippage as $c,NATIVE_TOKEN_ADDRESS as _c,getTokenByAddress as en,areEquivalent as jp,getTokensForChain as ir,getEscrowContractAddress as Mo,getEscrowContract as pa,ZERO_ADDRESS as Yt,normalizeNativeTokenAddress as ut,getChainMeta as ni,getMainnetChains as Gp,getTestnetChains as Kp,TOKENS as el,convertAmountBetweenDecimals as bo,hashChainBatches as Fo,isSpicenetChainId as No,getAccountNonce as Yp,SPICE_COMBINED_FEE_RECIPIENT as Zp,SPICE_GAS_FEE_RECIPIENT as kn,SPICE_PLATFORM_FEE_RECIPIENT as Kn,hashConditionalExecutionPlan as tl,SPICENET_NATIVE_CHAIN_ID as nl,spicenetAbi as ss,getEquivalentAddresses as Xp,getChainIdsByNetwork as is,getEquivalenceGroup as Jp,getTokenBySymbol as ol,hashConditionalIntentAuthorization as $p,getConditionalIntentId as _p,hashConditionalReadAuthorization as ef,hashConditionalCancellation as tf}from"@spicenet-io/spiceflow-core";import{ZERO_ADDRESS as K0,SPICENET_NATIVE_CHAIN_ID as Y0,SPICE_COMBINED_FEE_RECIPIENT as Z0,SPICE_GAS_FEE_RECIPIENT as X0,SPICE_PLATFORM_FEE_RECIPIENT as J0,SPICE_SOLVER_ADDRESS as $0,applySlippage as _0,buildUniV3SwapCalls as e1,getChainIdsByNetwork as t1,getEscrowContractAddress as n1,isNativeToken as o1,isSpicenetChainId as r1,normalizeNativeTokenAddress as a1,spicenetAbi as s1,spicenetAbi as i1}from"@spicenet-io/spiceflow-core";import{useAccount as oi,useDisconnect as ri,useConnect as nf,useWalletClient as of,useSwitchChain as rf}from"wagmi";import{encodeFunctionData as Wt,parseAbi as xo,concatHex as rl,encodePacked as ai,erc20Abi as pt,decodeFunctionData as Jn,encodeAbiParameters as jo,formatUnits as Ne,isAddress as Qn,getAddress as gn,zeroAddress as al,keccak256 as cr,recoverAddress as af,toRlp as sf,toHex as cs,parseUnits as $n,decodeEventLog as cf,createWalletClient as si,custom as ii,stringToHex as lf,bytesToHex as sl}from"viem";import{readContract as lr,getBalance as ci}from"viem/actions";import{useConnectWallet as il,usePrivy as cl,useActiveWallet as df}from"@privy-io/react-auth";import ll,{createPortal as li}from"react-dom";import"@tanstack/react-query";const uf="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@100;200;300;400;500;600;700&display=swap",pf="spiceflow-ibm-plex-mono",ff="spiceflow-preconnect-googleapis",mf="spiceflow-preconnect-gstatic";function di(e,t){if(document.getElementById(e))return;const n=t();n.id=e,document.head.appendChild(n)}function hf(){typeof document>"u"||(di(ff,()=>{const e=document.createElement("link");return e.rel="preconnect",e.href="https://fonts.googleapis.com",e}),di(mf,()=>{const e=document.createElement("link");return e.rel="preconnect",e.href="https://fonts.gstatic.com",e.crossOrigin="",e}),di(pf,()=>{const e=document.createElement("link");return e.rel="stylesheet",e.href=uf,e}))}const gf={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",8453:"0x4200000000000000000000000000000000000006",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",84532:"0x4200000000000000000000000000000000000006"},dl=xo(["function deposit() payable","function withdraw(uint256 wad)"]);function ui(e){return xt(e)?.wrappedNativeTokenAddress??gf[e]}const pi=(e,t)=>({to:e,value:t,data:Wt({abi:dl,functionName:"deposit"})}),fi=(e,t)=>({to:e,value:0n,data:Wt({abi:dl,functionName:"withdraw",args:[t]})});function mi(e,t,n){const o=Oe(t),r=Oe(n);if(!o&&!r)return null;const a=ui(e);return a?{weth:a,wrapIn:o,unwrapOut:r}:null}function ul(e,t,n,o){const r=mi(e,t,n);return!r||o<=0n?null:r.wrapIn&&!r.unwrapOut&&n.toLowerCase()===r.weth.toLowerCase()?[pi(r.weth,o)]:r.unwrapOut&&!r.wrapIn&&t.toLowerCase()===r.weth.toLowerCase()?[fi(r.weth,o)]:null}function wf(e){return{...e,resolve:async(t,n,o,r)=>{const a=ul(n,t.tokenIn,t.tokenOut,t.amountIn);if(a)return{venue:"native-wrap",amountOut:t.amountIn,amountOutMinimum:t.amountIn,calls:a};const s=await e.resolve(t,n,o,r);if(s)return s;const i=mi(n,t.tokenIn,t.tokenOut);if(!i)return null;const c=await e.resolve({...t,tokenIn:i.wrapIn?i.weth:t.tokenIn,tokenOut:i.unwrapOut?i.weth:t.tokenOut},n,o,r);return c?{...c,calls:[...i.wrapIn?[pi(i.weth,t.amountIn)]:[],...c.calls,...i.unwrapOut?[fi(i.weth,c.amountOutMinimum)]:[]]}:null}}}function yf(e){return{...e,resolve:async(t,n,o)=>{const r=ul(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 a=await e.resolve(t,n,o);if(a)return a;const s=mi(n,t.tokenIn,t.tokenOut);if(!s)return null;const i=await e.resolve({...t,tokenIn:s.wrapIn?s.weth:t.tokenIn,tokenOut:s.unwrapOut?s.weth:t.tokenOut},n,o);return i?{...i,calls:[...s.wrapIn?[pi(s.weth,i.amountInMax)]:[],...i.calls,...s.unwrapOut?[fi(s.weth,i.amountOut)]:[]]}:null}}}const pl=[100,500,3e3,1e4];function ls(e,t,n,o,r){const a=[];for(const s of n){const i=typeof s=="object"&&!Array.isArray(s)?s:void 0,c=i?i.tokens:Array.isArray(s)?s:[s];if(!c.length||c.length>2)throw new Error("A v3 route must have one or two intermediate tokens");const l=[e,...c,t];if(i&&(i.feeTiers.length!==l.length-1||i.feeTiers.some(d=>!d.length)))throw new Error("A v3 route needs fee tiers for every pool");if(new Set(l.map(d=>d.toLowerCase())).size!==l.length)continue;const u=(d,p)=>{if(d===l.length){a.push(r==="in"?p:fl(p));return}for(const w of i?.feeTiers[d-1]??o)u(d+1,rl([p,ai(["uint24","address"],[w,l[d]])]))};u(1,l[0])}return[...new Set(a)]}function fl(e){const t=e.slice(2),n=[];for(let o=0;o<t.length;){const r=n.length%2===0?40:6;n.push(t.slice(o,o+r)),o+=r}return`0x${n.reverse().join("")}`}const bf=xo(["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)"]),xf=xo(["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)"]),vf=1800;function ml(e){const{config:t,route:n,tokenIn:o,tokenOut:r,recipient:a,amountOut:s}=e,i=e.amountInMaximum,c=e.routerHasDeadline?xf:bf,l=e.routerHasDeadline?{deadline:BigInt(Math.floor(Date.now()/1e3)+vf)}:{},u=n.path?Wt({abi:c,functionName:"exactOutput",args:[{path:n.path,recipient:a,...l,amountOut:s,amountInMaximum:i}]}):Wt({abi:c,functionName:"exactOutputSingle",args:[{tokenIn:o,tokenOut:r,fee:n.fee,recipient:a,...l,amountOut:s,amountInMaximum:i,sqrtPriceLimitX96:0n}]});return{to:t.swapRouter,value:0n,data:u}}const If=xo(["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 fa(e,t,n,o,r){const a=Ot(e),{result:s}=await a.simulateContract({address:t.quoterV2,abi:If,functionName:r==="in"?"quoteExactInput":"quoteExactOutput",args:[n,o]}),[i,,,c]=s;if(i<=0n)throw new Error("No liquidity along this path.");return{amount:i,gasEstimate:c}}async function kf(e){const{tokenIn:t,tokenOut:n,amountIn:o,fee:r,chainId:a,config:s}=e;if(o<=0n)throw new Error("amountIn must be greater than 0");const i=(await Ot(a).simulateContract({address:s.quoterV2,abi:Qp,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:o,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 hl(e){const t=e.feeTiers??pl,n=ls(e.tokenIn,e.tokenOut,e.hubs??[],t,"in"),o=await Promise.allSettled([...t.map(async a=>({...await kf({...e,fee:a}),fee:a})),...n.map(async a=>{const s=await fa(e.chainId,e.config,a,e.amountIn,"in");return{amountOut:s.amount,sqrtPriceX96After:0n,gasEstimate:s.gasEstimate,fee:0,path:a}})]);let r=null;for(const a of o)a.status==="fulfilled"&&(!r||a.value.amountOut>r.amountOut)&&(r=a.value);if(!r)throw new Error("No liquidity found for this pair on any fee tier.");return r}const Cf=[{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 Sf(e){const{tokenIn:t,tokenOut:n,amountOut:o,fee:r,chainId:a,config:s}=e;if(o<=0n)throw new Error("amountOut must be greater than 0");const i=(await Ot(a).simulateContract({address:s.quoterV2,abi:Cf,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:o,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 gl(e){const t=e.feeTiers??pl,n=ls(e.tokenIn,e.tokenOut,e.hubs??[],t,"out"),o=await Promise.allSettled([...t.map(async a=>({...await Sf({...e,fee:a}),fee:a})),...n.map(async a=>{const s=await fa(e.chainId,e.config,a,e.amountOut,"out");return{amountIn:s.amount,sqrtPriceX96After:0n,gasEstimate:s.gasEstimate,fee:0,path:a}})]);let r=null;for(const a of o)a.status==="fulfilled"&&(!r||a.value.amountIn<r.amountIn)&&(r=a.value);if(!r)throw new Error("No liquidity found for this pair on any fee tier.");return r}function Af(e){return e.type==="swap"}const ma=.02,Ef=[1,8453,42161,10,137,43114,56],Ff="https://api.1inch.dev/swap/v6.0";function hi(e,t){return $c(e,t)}function Tf(e){const t=e?.baseUrl??Ff;return{name:"1inch",chainIds:e?.chainIds??Ef,resolve:async(n,o,r)=>{const a=n.maxSlippage??ma,s=a*100,i=Oe(n.tokenIn)?_c:n.tokenIn,c=Oe(n.tokenOut)?_c:n.tokenOut,l=Oe(n.tokenIn);try{const u=new URL(`${t}/${o}/swap`);u.searchParams.set("src",i),u.searchParams.set("dst",c),u.searchParams.set("amount",n.amountIn.toString()),u.searchParams.set("from",r),u.searchParams.set("slippage",s.toString()),u.searchParams.set("disableEstimate","true"),u.searchParams.set("allowPartialFill","false");const d={Accept:"application/json"};e?.apiKey&&(d.Authorization=`Bearer ${e.apiKey}`);const p=await fetch(u.toString(),{headers:d});if(!p.ok)throw new ke("VENUE_API_ERROR",`[1inchVenue] API returned ${p.status} for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`,{venue:"1inch",chainId:o,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:`HTTP ${p.status}`});const w=await p.json();if(!w.dstAmount||!w.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const f=BigInt(w.dstAmount);if(f<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const g=hi(f,a),h=[];return w.tx.to&&!l&&h.push({to:n.tokenIn,value:0n,data:Wt({abi:pt,functionName:"approve",args:[w.tx.to,n.amountIn]})}),h.push({to:w.tx.to,value:BigInt(w.tx.value||"0"),data:w.tx.data}),{venue:"1inch",amountOut:f,amountOutMinimum:g,calls:h}}catch(u){if(u instanceof ke)throw u;const d=u instanceof Error?u.message:String(u);throw new ke("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}: ${d}`,{venue:"1inch",chainId:o,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:d})}}}}const wl=[4114,5115],gi={name:"Satsuma",swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},yl={name:"Uniswap v3",swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x4200000000000000000000000000000000000006","0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]},bl={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[1],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2","0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"]},xl={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[42161],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x82aF49447D8a07e3bd95BD0d56f35241523fBab1","0xaf88d065e77c8cC2239327C5EDb3A432268e5831"]},Bf={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[137],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270","0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"]},Of={name:"Uniswap v3",swapRouter:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",quoterV2:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",chainIds:[56],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c","0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d"]},Rf={name:"Uniswap v3",swapRouter:"0xfe31f71c1b106eac32f1a19239c9a9a72ddfb900",quoterV2:"0x661e93cca42afacb172121ef892830ca3b70f08d",chainIds:[143],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A","0x754704Bc059F8C67012fEd69BC8A327a5aafb603"]},vl={name:"Uniswap v3",swapRouter:"0xcaf681a66d020601342297493863e78c959e5cb2",quoterV2:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",chainIds:[4663],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73","0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"]},Il={name:"SushiSwap",swapRouter:"0x1e406484F1F204b23cE84B9901C0171a738fd406",quoterV2:"0x3E290e5E01818002A0b672148BdC7514D861C7B3",chainIds:[4663],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73","0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"],routerHasDeadline:!0},kl=xo(["function exactInput((bytes path, address recipient, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),Cl=xo(["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)"]),Df=xo(["function exactInput((bytes path, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),Mf=xo(["function exactOutput((bytes path, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),wi=1800,Sl=[1,50,100,200,2e3],ds={name:"Aerodrome",swapRouter:"0xcbBb8035cAc7D4B3Ca7aBb74cF7BdF900215Ce0D",quoterV2:"0x3d4C22254F86f64B7eC90ab8F7aeC1FBFD271c6C",chainIds:[8453],hubCurrencies:["0x4200000000000000000000000000000000000006","0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]};function ha(e){const t=e.name??"Aerodrome",n=e.chainIds??[8453],o=e.tickSpacings??Sl;return{name:t,chainIds:n,resolve:async(r,a,s)=>{if(Oe(r.tokenIn)||Oe(r.tokenOut))return null;const i=r.maxSlippage??ma,c=[...o.map(h=>ai(["address","uint24","address"],[r.tokenIn,h,r.tokenOut])),...ls(r.tokenIn,r.tokenOut,e.hubCurrencies??[],o,"in")],l={quoterV2:e.quoterV2},u=await Promise.allSettled(c.map(async h=>({path:h,amountOut:(await fa(a,l,h,r.amountIn,"in")).amount})));let d=null;for(const h of u)h.status==="fulfilled"&&(!d||h.value.amountOut>d.amountOut)&&(d=h.value);if(!d)return console.warn(`[AerodromeVenue] No viable route for ${r.tokenIn} \u2192 ${r.tokenOut} on chain ${a}.`),null;const p=hi(d.amountOut,i),w=e.deadline??BigInt(Math.floor(Date.now()/1e3)+wi),f=Wt({abi:Df,functionName:"exactInput",args:[{path:d.path,recipient:s,deadline:w,amountIn:r.amountIn,amountOutMinimum:p}]}),g=[{to:r.tokenIn,value:0n,data:Wt({abi:pt,functionName:"approve",args:[e.swapRouter,r.amountIn]})},{to:e.swapRouter,value:0n,data:f}];return{venue:t,amountOut:d.amountOut,amountOutMinimum:p,calls:g}}}}function Al(e){const t=e.name??"Aerodrome",n=e.chainIds??[8453],o=e.tickSpacings??Sl;return{name:t,chainIds:n,resolve:async(r,a,s)=>{if(Oe(r.tokenIn)||Oe(r.tokenOut))return null;const i=r.maxSlippage??ma,c=[...o.map(g=>ai(["address","uint24","address"],[r.tokenOut,g,r.tokenIn])),...ls(r.tokenIn,r.tokenOut,e.hubCurrencies??[],o,"out")],l={quoterV2:e.quoterV2},u=await Promise.allSettled(c.map(async g=>({path:g,amountIn:(await fa(a,l,g,r.amountOut,"out")).amount})));let d=null;for(const g of u)g.status==="fulfilled"&&(!d||g.value.amountIn<d.amountIn)&&(d=g.value);if(!d)return console.warn(`[AerodromeExactOutputVenue] No viable route for ${r.tokenIn} \u2192 ${r.tokenOut} on chain ${a}.`),null;const p=BigInt(Math.round(i*1e4)),w=d.amountIn+d.amountIn*p/10000n,f=e.deadline??BigInt(Math.floor(Date.now()/1e3)+wi);return{venue:t,amountIn:d.amountIn,amountInMax:w,amountOut:r.amountOut,calls:[{to:e.swapRouter,value:0n,data:Wt({abi:Mf,functionName:"exactOutput",args:[{path:d.path,recipient:s,deadline:f,amountOut:r.amountOut,amountInMaximum:w}]})}]}}}}function ga(e){const t=e.name??"Uniswap v3",n=e.chainIds??wl;return{name:t,chainIds:n,resolve:async(o,r,a,s)=>{if(Oe(o.tokenIn)||Oe(o.tokenOut))return null;const i=o.maxSlippage??ma;let c;try{let f;if(s){if(s.venue!==t)return null;const g=s.calls.find(y=>y.to.toLowerCase()===e.swapRouter.toLowerCase());if(!g)return null;const h=Jn({abi:e.routerHasDeadline?Cl:[...kl,...Jc],data:g.data});if(h.functionName==="exactInput"){const{path:y}=h.args[0];if(y.slice(0,42).toLowerCase()!==o.tokenIn.toLowerCase()||`0x${y.slice(-40)}`.toLowerCase()!==o.tokenOut.toLowerCase())return null;f={path:y,fee:0}}else if(h.functionName==="exactInputSingle"){const{tokenIn:y,tokenOut:I,fee:A}=h.args[0];if(y.toLowerCase()!==o.tokenIn.toLowerCase()||I.toLowerCase()!==o.tokenOut.toLowerCase())return null;f={fee:A}}else return null}c=f?.path?{...f,amountOut:(await fa(r,e,f.path,o.amountIn,"in")).amount}:await hl({tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountIn:o.amountIn,chainId:r,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:f?[f.fee]:e.feeTiers,hubs:f?[]:[...e.hubCurrencies??[],...e.hubPaths??[]]})}catch{return console.warn(`[UniV3Venue] No viable route for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${r}.`),null}const l=hi(c.amountOut,i),u=e.routerHasDeadline?{deadline:BigInt(Math.floor(Date.now()/1e3)+wi)}:{},d=e.routerHasDeadline?Cl:c.path?kl:Jc,p=c.path?Wt({abi:d,functionName:"exactInput",args:[{path:c.path,recipient:a,...u,amountIn:o.amountIn,amountOutMinimum:l}]}):Wt({abi:d,functionName:"exactInputSingle",args:[{tokenIn:o.tokenIn,tokenOut:o.tokenOut,fee:c.fee,recipient:a,...u,amountIn:o.amountIn,amountOutMinimum:l,sqrtPriceLimitX96:0n}]}),w=[{to:o.tokenIn,value:0n,data:Wt({abi:pt,functionName:"approve",args:[e.swapRouter,o.amountIn]})},{to:e.swapRouter,value:0n,data:p}];return{venue:t,amountOut:c.amountOut,amountOutMinimum:l,calls:w}}}}function yi(e){const t=e.name??"Uniswap v3",n=e.chainIds??wl;return{name:t,chainIds:n,resolve:async(o,r,a)=>{if(Oe(o.tokenIn)||Oe(o.tokenOut))return null;const s=o.maxSlippage??ma;let i;try{i=await gl({tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountOut:o.amountOut,chainId:r,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers,hubs:[...e.hubCurrencies??[],...e.hubPaths??[]]})}catch{return null}const c=BigInt(Math.round(s*1e4)),l=i.amountIn+i.amountIn*c/10000n;return{venue:t,amountIn:i.amountIn,amountInMax:l,amountOut:o.amountOut,calls:[ml({config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},routerHasDeadline:e.routerHasDeadline,route:i,tokenIn:o.tokenIn,tokenOut:o.tokenOut,recipient:a,amountOut:o.amountOut,amountInMaximum:l})]}}}}function El(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(ga(e.satsuma)),e?.aerodrome!==!1&&t.push(ha(e?.aerodrome??ds)),t.push(Tf(e?.oneInch));const n=t.map(wf);function o(s){return n.find(i=>i.chainIds.includes(s))}async function r(s,i,c,l){const u=n.filter(f=>f.chainIds.includes(i));if(u.length===0)throw new ke("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${i}. Cannot resolve swap ${s.tokenIn} \u2192 ${s.tokenOut}.`,{chainId:i,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn.toString()});const d=await Promise.allSettled(u.map(f=>f.resolve(s,i,c,l)));let p=null;for(const f of d)l&&f.status==="fulfilled"&&f.value&&(f.value.venue!==l.venue||f.value.calls.length!==l.calls.length||f.value.calls.some((g,h)=>g.to.toLowerCase()!==l.calls[h].to.toLowerCase()||g.data.slice(0,10)!==l.calls[h].data.slice(0,10)))||f.status==="fulfilled"&&f.value&&(!p||f.value.amountOut>p.amountOut)&&(p=f.value);if(p)return p;const w=d.find(f=>f.status==="rejected");if(w)throw w.reason;return null}async function a(s,i,c){const l=[],u=[];for(const d of s){if(!Af(d)){l.push(d);continue}const p=await r(d,i,c);if(!p)throw new ke("NO_LIQUIDITY",`No venue returned a quote for ${d.tokenIn} \u2192 ${d.tokenOut} on chain ${i}.`,{chainId:i,tokenIn:d.tokenIn,tokenOut:d.tokenOut,amountIn:d.amountIn.toString()});l.push(...p.calls),u.push(p)}return{calls:l,resolvedSwaps:u}}return{resolveSwapIntents:a,resolveSwap:r,getVenueForChain:o,venues:t}}const Po="0x0000000000000000000000000000000000000000",bi=[{fee:100,tickSpacing:1},{fee:500,tickSpacing:10},{fee:3e3,tickSpacing:60},{fee:1e4,tickSpacing:200}],Fl=Po,Tl=.02,Nf=1800,Bl={name:"Uniswap v4",quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",universalRouter:"0x6ff5693b99212da76ad316178a184ab56d299b43",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",chainIds:[8453],hubCurrencies:["0x4200000000000000000000000000000000000006",Po,"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]},Ol={name:"Uniswap v4",quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",universalRouter:"0x8876789976decbfcbbbe364623c63652db8c0904",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",routerHasHopPrice:!0,chainIds:[4663],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73",Po,"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"]},Rl=xo(["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)"]),Pf=xo(["function approve(address token, address spender, uint160 amount, uint48 expiration)"]),Wf=xo(["function execute(bytes commands, bytes[] inputs, uint256 deadline) payable"]),Dl="0x10",Uf="04",Lf="06",qf="07",zf="08",Hf="09",us="0c",ps="0e",Vf=[{name:"currency0",type:"address"},{name:"currency1",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"}],Qf=[{name:"intermediateCurrency",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"},{name:"hookData",type:"bytes"}],Go=(e,t)=>e.toLowerCase()===t.toLowerCase();function fs(e){return Oe(e)?Po:e}function jf(e,t){return e.toLowerCase()<t.toLowerCase()?[e,t]:[t,e]}function Ml(e,t,n,o,r){const a=[],[s,i]=jf(e,t);for(const{fee:l,tickSpacing:u}of bi)a.push({kind:"single",poolKey:{currency0:s,currency1:i,fee:l,tickSpacing:u,hooks:Fl},zeroForOne:Go(e,s)});const c=(l,u)=>!!r&&(Go(l,Po)&&Go(u,r)||Go(l,r)&&Go(u,Po));for(const l of n)if(!(Go(l,e)||Go(l,t))&&!(c(l,e)||c(l,t)))for(const u of bi)for(const d of bi){const p=(w,f)=>({intermediateCurrency:w,fee:f.fee,tickSpacing:f.tickSpacing,hooks:Fl,hookData:"0x"});a.push({kind:"multi",path:o==="in"?[p(l,u),p(t,d)]:[p(e,u),p(l,d)]})}return a}async function Nl(e,t,n,o,r,a){const s=Ot(e),i=(await Promise.allSettled(n.map(async c=>{const{result:l}=c.kind==="single"?await s.simulateContract({address:t.quoter,abi:Rl,functionName:a==="in"?"quoteExactInputSingle":"quoteExactOutputSingle",args:[{poolKey:c.poolKey,zeroForOne:c.zeroForOne,exactAmount:r,hookData:"0x"}]}):await s.simulateContract({address:t.quoter,abi:Rl,functionName:a==="in"?"quoteExactInput":"quoteExactOutput",args:[{exactCurrency:o,path:c.path,exactAmount:r}]}),u=l[0];if(u<=0n)throw new Error("zero quote");return{candidate:c,amount:u}}))).filter(c=>c.status==="fulfilled").map(c=>c.value);return i.length===0?null:(i.sort((c,l)=>c.amount<l.amount?-1:c.amount>l.amount?1:0),a==="in"?i[i.length-1]:i[0])}function Pl(e){const{candidate:t,direction:n,currencyIn:o,currencyOut:r,recipient:a,exactAmount:s,limitAmount:i,deadline:c,routerHasHopPrice:l,sweepNativeTo:u}=e;let d,p;t.kind==="single"?(d=n==="in"?`0x${Lf}${us}${ps}`:`0x${zf}${us}${ps}`,p=jo([{type:"tuple",components:[{name:"poolKey",type:"tuple",components:Vf},{name:"zeroForOne",type:"bool"},{name:n==="in"?"amountIn":"amountOut",type:"uint128"},{name:n==="in"?"amountOutMinimum":"amountInMaximum",type:"uint128"},...l?[{name:"minHopPriceX36",type:"uint256"}]:[],{name:"hookData",type:"bytes"}]}],[{poolKey:t.poolKey,zeroForOne:t.zeroForOne,[n==="in"?"amountIn":"amountOut"]:s,[n==="in"?"amountOutMinimum":"amountInMaximum"]:i,...l?{minHopPriceX36:0n}:{},hookData:"0x"}])):(d=n==="in"?`0x${qf}${us}${ps}`:`0x${Hf}${us}${ps}`,p=jo([{type:"tuple",components:[{name:n==="in"?"currencyIn":"currencyOut",type:"address"},{name:"path",type:"tuple[]",components:Qf},...l?[{name:"minHopPriceX36",type:"uint256[]"}]:[],{name:n==="in"?"amountIn":"amountOut",type:"uint128"},{name:n==="in"?"amountOutMinimum":"amountInMaximum",type:"uint128"}]}],[{[n==="in"?"currencyIn":"currencyOut"]:n==="in"?o:r,path:t.path,...l?{minHopPriceX36:[]}:{},[n==="in"?"amountIn":"amountOut"]:s,[n==="in"?"amountOutMinimum":"amountInMaximum"]:i}]));const w=jo([{type:"address"},{type:"uint256"}],[o,n==="in"?s:i]),f=jo([{type:"address"},{type:"address"},{type:"uint256"}],[r,a,0n]),g=jo([{type:"bytes"},{type:"bytes[]"}],[d,[p,w,f]]),h=u?`${Dl}${Uf}`:Dl,y=u?[g,jo([{type:"address"},{type:"address"},{type:"uint256"}],[Po,u,0n])]:[g];return Wt({abi:Wf,functionName:"execute",args:[h,y,c]})}function Wl(){return BigInt(Math.floor(Date.now()/1e3)+Nf)}function Ul(e,t,n,o){return{to:e.permit2,value:0n,data:Wt({abi:Pf,functionName:"approve",args:[t,e.universalRouter,n,Number(o)]})}}function Ll(e){const t=e.name??"Uniswap v4",n=e.v3?ga({...e.v3,chainIds:e.chainIds}):null;return{name:t,chainIds:e.chainIds,resolve:async(o,r,a)=>{const s=o.maxSlippage??Tl,i=fs(o.tokenIn),c=fs(o.tokenOut),l=Oe(o.tokenIn),u=e.hubCurrencies??[Po];let d=null;if(!Go(i,c)&&o.amountIn>0n){const p=await Nl(r,e,Ml(i,c,u,"in",ui(r)),i,o.amountIn,"in").catch(()=>null);if(p){const w=$c(p.amount,s),f=Wl(),g=[];l||(g.push({to:o.tokenIn,value:0n,data:Wt({abi:pt,functionName:"approve",args:[e.permit2,o.amountIn]})}),g.push(Ul(e,o.tokenIn,o.amountIn,f))),g.push({to:e.universalRouter,value:l?o.amountIn:0n,data:Pl({candidate:p.candidate,direction:"in",currencyIn:i,currencyOut:c,recipient:a,exactAmount:o.amountIn,limitAmount:w,deadline:f,routerHasHopPrice:e.routerHasHopPrice})}),d={venue:t,amountOut:p.amount,amountOutMinimum:w,calls:g}}}return!d&&n?n.resolve(o,r,a):d}}}function ql(e){const t=e.name??"Uniswap v4";return{name:t,chainIds:e.chainIds,resolve:async(n,o,r)=>{const a=Oe(n.tokenIn),s=fs(n.tokenIn),i=fs(n.tokenOut);if(Go(s,i)||n.amountOut<=0n)return null;const c=n.maxSlippage??Tl,l=e.hubCurrencies??[Po],u=await Nl(o,e,Ml(s,i,l,"out",ui(o)),i,n.amountOut,"out").catch(()=>null);if(!u)return null;const d=BigInt(Math.round(c*1e4)),p=u.amount+u.amount*d/10000n,w=Wl();return{venue:t,amountIn:u.amount,amountInMax:p,amountOut:n.amountOut,calls:[...a?[]:[Ul(e,n.tokenIn,p,w)],{to:e.universalRouter,value:a?p:0n,data:Pl({candidate:u.candidate,direction:"out",currencyIn:s,currencyOut:i,recipient:r,exactAmount:n.amountOut,limitAmount:p,deadline:w,routerHasHopPrice:e.routerHasHopPrice,sweepNativeTo:a?r:void 0})}]}}}}const xi=[{...gi,protocol:"uniswap-v3",chainId:4114},{...gi,protocol:"uniswap-v3",chainId:5115},{...yl,protocol:"uniswap-v3",chainId:8453},{...bl,protocol:"uniswap-v3",chainId:1},{...xl,protocol:"uniswap-v3",chainId:42161},{...Bf,protocol:"uniswap-v3",chainId:137},{...Of,protocol:"uniswap-v3",chainId:56},{...Rf,protocol:"uniswap-v3",chainId:143},{...vl,protocol:"uniswap-v3",chainId:4663},{...Il,protocol:"uniswap-v3",chainId:4663},{...Bl,protocol:"uniswap-v4",chainId:8453},{...Ol,protocol:"uniswap-v4",chainId:4663},{...ds,protocol:"aerodrome-slipstream",chainId:8453}];function Sr(e){const t=e?.includeDefaults===!1?e.venues??[]:[...xi,...e?.venues??[]],n=[],o=[];for(const r of t){const a=[r.chainId];switch(r.protocol){case"uniswap-v3":{const s={...r,chainIds:a};n.push(ga(s)),o.push(yi(s));break}case"uniswap-v4":{const s={...r,chainIds:a};n.push(Ll(s)),o.push(ql(s));break}case"aerodrome-slipstream":{const s={...r,chainIds:a};n.push(ha(s)),o.push(Al(s));break}default:{const s=r;throw new ke("INVALID_PARAMS",`Unsupported liquidity venue protocol: ${s.protocol}`,{protocol:s.protocol})}}}return{input:n,output:o}}const vi=new Set(["WBTC","CBTC"]),zl=new Set(["btc","wbtc","wcbtc","cbtc"]);function Hl(e,t){return!e||!t?!1:e===t?!0:vi.has(e)&&vi.has(t)}function _n(e){const[t,n,o]=e.split(":");if(t!=="evm"||!n||!o)return null;const r=Number(n);if(!Number.isFinite(r))return null;const a=o.startsWith("0x")?o.toLowerCase():`0x${o.toLowerCase()}`;return{chainId:r,address:a}}function ms(e){return(e??"").trim().replace(/^test\s+/i,"").replace(/^spice/i,"").toLowerCase().replace(/[^a-z0-9]/g,"")}function Gf(e){return new Set([e.receiptTokenName,e.displaySymbol,e.symbol,e.displayName,e.name].map(ms).filter(Boolean))}function Kf(e,t){const n=Gf(e),o=[t.symbol,t.name,t.equivalenceGroup].map(ms);if(o.some(s=>s&&n.has(s)))return!0;const r=[...n].some(s=>zl.has(s)),a=o.some(s=>zl.has(s))||vi.has(t.equivalenceGroup??"");return r&&a}function Vl(e,t,n){const o=new Set(t.map(ms).filter(Boolean)),r=a=>{if(n&&Q(a.address,n))return 0;const s=[a.symbol,a.name,a.equivalenceGroup].map(ms).findIndex(i=>i&&o.has(i));return s===-1?4:s+1};return[...e].sort((a,s)=>{const i=r(a)-r(s);return i!==0?i:a.address.toLowerCase().localeCompare(s.address.toLowerCase())})}function zr(e,t){const n=e.chainTokens?Object.keys(e.chainTokens):[],o=[];for(const r of n){const a=_n(r);if(!a||a.chainId!==t)continue;const s=a.address,i=Oe(s)?xt(t)?.nativeCurrency:void 0,c=en(s,t)??(i?{...i}:void 0);c&&(!Ii(e,s,t)&&!(e.isUniversal&&Kf(e,c))||o.some(l=>Q(l,s))||o.push(s))}return Vl(o.map(r=>{const a=en(r,t);return{address:r,symbol:a?.symbol,name:a?.name,equivalenceGroup:a?.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 Ii(e,t,n){return e.chainId===n&&Q(e.address,t)?!0:ya(e.address,e.chainId,t,n)}async function Ql(e,t){const n=Ot(e),o=Mo(e);return Oe(t)?n.getBalance({address:o}):await n.readContract({address:t,abi:pt,functionName:"balanceOf",args:[o]})}function ki(e,t,n){const o=ir(n),r=o.find(s=>Q(s.address,e));if(r&&(t===n||!Oe(e)))return r;const a=en(e,t);if(a)return Vl(o.filter(s=>Hl(s.equivalenceGroup,a.equivalenceGroup)),[a.symbol,a.name,a.equivalenceGroup])[0]}function wa(e){return e.equivalenceGroup==="USDC"&&e.symbol.toUpperCase()!=="USDT"}function Ar(e){const t=pa(e);if(!t||t===Yt)return;const n=ir(e).filter(wa);return n.find(o=>o.symbol.toUpperCase()==="USDC")??n[0]}function Ci(e,t){if(e.chainId===t)return null;const n=pa(e.chainId),o=pa(t);if(!n||n===Yt||!o||o===Yt)return null;const r=!e.isNative&&!Oe(e.address)?en(e.address,e.chainId):void 0,a=r&&wa(r)?ki(e.address,e.chainId,t):void 0,s=a?r:Ar(e.chainId),i=a??Ar(t);if(!s||!i)return null;const c=l=>({address:l.address,symbol:l.symbol,decimals:l.decimals,chainId:l.chainId});return{source:c(s),destination:c(i)}}async function jl(e,t,n){const o=ir(e.chainId).filter(wa),r=[o.find(i=>Q(i.address,t.address)),e,...o].filter((i,c,l)=>!!i&&l.findIndex(u=>u&&Q(u.address,i.address))===c);let a;for(const i of r){let c;try{c=await Ql(e.chainId,i.address)}catch{continue}if(c<=0n)continue;const l={...i,address:i.address};let u;try{u=await n(l)}catch{u=null}if(Q(l.address,e.address)&&(a=u),u&&u.amount<=c)return{token:l,...u}}const s=a===void 0?await n(e):a;return s?{token:e,...s}:null}function Yf(e,t){return!!Ci(e,t)}function co(e,t){if(e.chainId===t)return e.address;const n=ki(e.address,e.chainId,t);return n?n.address:null}async function Wo(e,t,n,o){const r=en(t,n);return r?r.decimals:e?.chainId===n&&Q(e.address,t)&&!e.isUniversal?e.decimals:o?.chainId===n&&Q(o.address,t)?o.decimals:Xa(n,t)}async function Gl(e,t,n={}){const o=co(e,t),r=zr(e,t);if(r.length===0)return o;if(r.length===1)return r[0];const a=n.requiredAmount??0n,s=i=>{const c=r.map(l=>({candidate:l,balance:i.get(Oe(l)?"native":l.toLowerCase())??0n})).filter(l=>l.balance>0n).sort((l,u)=>l.balance===u.balance?0:l.balance>u.balance?-1:1);return c.length===0?null:((a>0n?c.find(l=>l.balance>=a):c[0])??c[0]).candidate};try{const i=await Promise.all(r.map(async u=>({key:Oe(u)?"native":u.toLowerCase(),value:await Ql(t,u)}))),c=new Map(i.map(({key:u,value:d})=>[u,d])),l=s(c);if(l)return l}catch{}return o}function ya(e,t,n,o){const r=en(e,t),a=en(n,o);return r&&a?Hl(r.equivalenceGroup,a.equivalenceGroup):jp(e,n)}function hs(e,t){return ya(e.address,e.chainId,t.address,t.chainId)}const Kl=.01;function Yl(e,t=!1){const n=Number.isFinite(e.balanceUsd)&&e.balanceUsd>0;return e.isDiscovered?n&&e.balanceUsd>=Kl:!t||!n||e.balanceUsd>=Kl}function Hr(e,t=!1){return!!e&&e._source==="wallet"&&(e.location==="external"||e._fundingWallet==="external"||!e.location&&!e._fundingWallet&&t)}function be(e){return e.positionId??`${e.owner?.toLowerCase()??""}:${e.location??e._source??""}:${e.chainId}:${e.receiptTokenId??ut(e.address).toLowerCase()}`}function Zl(e,t){if(!t?.length||e.symbol!==void 0&&Ja({...e,symbol:e.symbol},t))return!0;const n=o=>t.some(r=>Q(ut(r),ut(o)));return n(e.address)||Object.keys(e.chainTokens??{}).some(o=>{const r=_n(o);return r?n(r.address):!1})}function To(e,t,n,o,r,a){const s=(g,h=!1)=>({eligible:!1,reason:g,policyExcluded:h}),i=e._source==="wallet"||e.location==="external"||e.location==="embedded",c=t==="spend-source"&&i&&!!o&&e.chainId===o.chainId&&Q(ut(e.address),ut(o.address));if(n.isWhitelistGateActive||!c&&!Ja(e,n.allowedTokens))return s("Asset excluded by client policy",!0);if(t!=="withdraw-destination"&&!c&&!Yl(e))return s("Asset is unpriced or below the minimum value",!0);if(t==="holding")return{eligible:!0,reason:null};if(e.balanceError)return s(e.balanceError);if(!c&&!Zl(e,r))return s("Asset excluded by action policy",!0);const l=new Set(o?[o.chainId]:[]);e._source!=="spice"&&e.location!=="rollup"&&l.add(e.chainId);for(const g of l)if(!$a(g,n.rpcOverrides)?.trim())return s(`Configure SpiceFlowProvider rpcOverrides[${g}] before using this asset.`);if(a?.requiresEscrow){const g=en(e.address,e.chainId);if(!g||!wa(g))return s("This asset has no supported escrow mapping")}if(!o)return{eligible:!0,reason:null};const u=n.liquidityVenues?.includeDefaults===!1?n.liquidityVenues.venues??[]:[...xi,...n.liquidityVenues?.venues??[]],d=g=>u.some(h=>h.chainId===g),p=i&&e.chainId!==o.chainId,w=p?Ci(e,o.chainId):null;if(p&&!w)return s("No supported source route");if(w&&!Q(ut(e.address),ut(w.source.address))&&!d(e.chainId))return s("No conversion venue configured on the source chain");const f=w?.destination.address??co(e,o.chainId);return t==="withdraw-destination"?(e.chainTokens||e.receiptTokenId?zr(e,o.chainId):f?[f]:[]).some(g=>Q(ut(g),ut(o.address)))?{eligible:!0,reason:null}:s("No supported withdrawal mapping"):f&&Q(ut(f),ut(o.address))?{eligible:!0,reason:null}:!f&&!Yf(e,o.chainId)?s("No supported destination route"):d(o.chainId)?{eligible:!0,reason:null}:s("No conversion venue configured on the destination chain")}function gs(){const e=pn(on),[t]=q(Ap);return e?.inventory??t}function Si(e,t,n,o,r){const a=gs(),s=r??a,i=Ie(()=>s.entry(e),[s,e]),[,c]=q(0);me(()=>{if(n)return i.subscribe(()=>c(u=>u+1),t,o)},[i,n,t,o]);const l=ae(()=>i.refresh(),[i]);return{...n?i.snapshot():Ep,refresh:l}}var Xl="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==",Zf="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=",Xf="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=",ba="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 xa=ni(1)?.logo??"",Jf=el.find(e=>e.symbol==="USDC")?.logo??"",dr=Object.fromEntries([...Gp(),...Kp()].map(e=>[e.id,e.logo])),va={metamask:Xl,metaMask:Xl,rabby:Zf,phantom:Xf},Ai=Object.fromEntries(el.map(e=>[e.symbol.toUpperCase(),e.logo])),$f={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]},_f={btc:["wcbtc","cbtc","wbtc"]};function ws(e){return e.replace(/^test\s*/i,"").replace(/^spice/i,"").trim()}function Ko(e){return ws(e).toLowerCase()}function Jl(e){return Ko(e??"").replace(/[^a-z0-9]/g,"")}function Ei(e){const t=Ko(e);return[t,..._f[t]??[]].filter(Boolean)}function em(e){try{return BigInt(e.balanceAvailable||"0")}catch{return 0n}}function $l(e){return Array.isArray(e.chainTokens)?e.chainTokens:Object.keys(e.chainTokens??{})}function _l(e,t){const n=xt(e),o=t.toLowerCase();return o===Yt.toLowerCase()?n?.nativeCurrency.decimals??18:n?.supportedTokens?.find(r=>r.address.toLowerCase()===o)?.decimals??18}function tm(e,t,n,o=[]){const r=_l(t,n),a=e.filter(i=>ed(i,t,n,o));if(a.length===0)return null;const s=a.reduce((i,c)=>Math.min(i,c.decimals??r),r);return{chainDecimals:r,receiptDecimals:s}}function ed(e,t,n,o){if($l(e).some(a=>{const s=_n(a);return s&&ya(s.address,s.chainId,n,t)}))return!0;const r=new Set(o.map(Jl).filter(Boolean));return r.size===0?!1:r.has(Jl(e.tokenName||e.receiptToken))}function td(e,t,n,o=[]){const r=_l(t,n);return e.reduce((a,s)=>ed(s,t,n,o)?a+bo(em(s),s.decimals??r,r):a,0n)}function nd(e,t){const n=new Set([...Ei(t),...Ei(ws(t))]);return[...e].sort((o,r)=>{const a=Ko(o.symbol),s=Ko(r.symbol),i=Ko(o.name),c=Ko(r.name),l=n.has(a)?0:n.has(i)?1:2,u=n.has(s)?0:n.has(c)?1:2;return l!==u?l-u:o.address.toLowerCase().localeCompare(r.address.toLowerCase())})[0]}function nm(e){const t=e&&e.length>0?e:Object.keys(_a).map(Number).filter(Number.isFinite),n=new Map;for(const o of t){const r=xt(o);if(!r)continue;const a=`${o}:${Yt.toLowerCase()}`;n.has(a)||n.set(a,{address:Yt,chainId:o,symbol:r.nativeCurrency.symbol,name:r.nativeCurrency.name,decimals:r.nativeCurrency.decimals,isNative:!0,logoURI:Ai[r.nativeCurrency.symbol.toUpperCase()]??r.logo});for(const s of r.supportedTokens??[]){const i=s.address.toLowerCase(),c=`${o}:${i}`;n.has(c)||n.set(c,{address:i,chainId:o,symbol:s.symbol,name:s.name,decimals:s.decimals,isNative:Oe(i),logoURI:s.logo})}}return n}function om(e,t){const n=nm(t),o=ws(e.tokenName),r=Ko(e.tokenName),a=Ei(e.tokenName),s=Array.isArray(e.chainTokens)?e.chainTokens.map(f=>[f,void 0]):Object.entries(e.chainTokens??{}),i=s.map(([f])=>_n(f)).filter(f=>f!==null),c=new Map;for(const[f,g]of s){const h=_n(f);if(!h||!Number.isSafeInteger(h.chainId)||h.chainId<0||!/^evm:[0-9]+:(?:0x)?[0-9a-fA-F]{40}$/.test(f)){if(!Array.isArray(e.chainTokens))throw new Error("Invalid chain token metadata identity");continue}if(g!==void 0&&(!g||typeof g!="object"||Array.isArray(g)||g.name!==void 0&&typeof g.name!="string"||g.decimals!==void 0&&(!Number.isInteger(g.decimals)||g.decimals<0||g.decimals>255)))throw new Error("Invalid chain token metadata");const y=`${h.chainId}:${h.address.toLowerCase()}`;if(c.has(y)){const I=c.get(y);if(I?.name!==g?.name||I?.decimals!==g?.decimals)throw new Error("Conflicting chain token metadata")}c.set(y,g)}const l=(f,g)=>{const h=c.get(`${g.chainId}:${g.address.toLowerCase()}`);return{...f,name:typeof h?.name=="string"&&h.name.length>0?h.name:f.name,decimals:typeof h?.decimals=="number"?h.decimals:f.decimals}},u=i.map(f=>{const g=n.get(`${f.chainId}:${f.address.toLowerCase()}`);return g?l(g,f):void 0}).filter(f=>f!==void 0),d=$f[r]??[];if(d.length>0)for(const f of d){const g=u.filter(h=>h.chainId===f);if(g.length>0)return nd(g,e.tokenName)}if(u.length>0)return nd(u,e.tokenName);const p=Array.from(n.values()).filter(f=>a.includes(Ko(f.symbol))||a.includes(Ko(f.name)));if(d.length>0)for(const f of d){const g=p.find(h=>h.chainId===f);if(g)return g}if(p.length>0)return p[0];const w=i[0];if(w){const f=c.get(`${w.chainId}:${w.address.toLowerCase()}`);return{address:w.address,chainId:w.chainId,symbol:o||e.tokenName,name:typeof f?.name=="string"&&f.name.length>0?f.name:o||e.tokenName,decimals:typeof f?.decimals=="number"?f.decimals:e.decimals??18,isNative:Oe(w.address),logoURI:void 0}}}function rm(e,t){let n;try{n=BigInt(e.balanceAvailable||"0")}catch{return null}if(n<=0n)return null;if(t?.length){const f=$l(e).map(_n).filter(g=>g!==null);if(f.length>0&&!f.some(g=>t.includes(g.chainId)))return null}let o;try{o=om(e,t)}catch{return null}const r=o?.decimals??e.decimals??18,a=e.decimals??r,s=bo(n,a,r),i=o?.address??Yt,c=o?.chainId??0,l=ws(e.tokenName),u=o?.symbol??l,d=o?.name??l,p=parseFloat(Ne(s,r)),w=e.tokenName==="spiceUSDC"?p:typeof e.balanceUsd=="number"?e.balanceUsd:typeof e.balanceUsd=="string"&&Number(e.balanceUsd)||0;return{address:i,symbol:u,name:d,decimals:r,chainId:c,balance:s,balanceFormatted:p,balanceUsd:w,isNative:o?.isNative??Oe(i),logoURI:o?.logoURI,displaySymbol:l||u,displayName:l||d,displayChainName:"Spicenet",receiptTokenId:e.receiptToken,receiptTokenName:e.tokenName||d,receiptTokenDecimals:a,chainTokens:e.chainTokens&&!Array.isArray(e.chainTokens)?e.chainTokens:void 0,isUniversal:!0}}const Fi=6e4,am=3e5,od="https://api.g.alchemy.com/prices/v1",Vr=new Map;function ys(e,t){try{const n=t??$a(e);if(typeof n!="string")return null;const{hostname:o,pathname:r}=new URL(n);if(!o.endsWith(".g.alchemy.com"))return null;const a=r.split("/").filter(Boolean).pop();return a?{network:o.slice(0,-14),key:a}:null}catch{return null}}const Ia=(e,t)=>`${e.network}:${e.key}:${t.toLowerCase()}`;function Er(e,t){const n=Vr.get(Ia(e,t));if(!n?.price||n.updatedAt===void 0)return;const o=Date.now()-n.updatedAt;if(!(o>=am))return{price:n.price,stale:o>=Fi}}function rd(e){const t=Number(e.prices?.find(n=>n.currency==="usd")?.value);return Number.isFinite(t)&&t>0?t:0}async function ad(e,t,n){const o=[],r=new Set,a=Date.now();for(const s of new Set(t.map(i=>i.toLowerCase()))){const i=Vr.get(Ia(e,s));i?.pending?r.add(i.pending):(!i||a-i.attemptedAt>=Fi&&(i.updatedAt===void 0||a-i.updatedAt>=Fi))&&o.push(s)}for(let s=0;s<o.length;s+=25){const i=o.slice(s,s+25),c=Promise.resolve().then(async()=>{try{const l=await n(i);for(const u of i){const d=l.get(u);if(!d)continue;const p=Vr.get(Ia(e,u));p.price=d,p.updatedAt=Date.now()}}catch{}finally{for(const l of i)Vr.get(Ia(e,l)).pending=void 0}});for(const l of i){const u=Ia(e,l);Vr.set(u,{...Vr.get(u),attemptedAt:a,pending:c})}r.add(c)}await Promise.all(r)}async function Ti(e,t){return await ad(e,t,async n=>{const o=await fetch(`${od}/${e.key}/tokens/by-address`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({addresses:n.map(s=>({network:e.network,address:s}))}),signal:AbortSignal.timeout(1e4)});if(!o.ok)throw new Error("Provider price request failed");const r=await o.json(),a=new Map;for(const s of r?.data??[]){if(s.network&&s.network!==e.network)continue;const i=String(s.address).toLowerCase();n.includes(i)&&a.set(i,rd(s))}return a}),new Map(t.map(n=>[n.toLowerCase(),Er(e,n)?.price??0]))}async function Bi(e,t){const n=`native:${t}`;return await ad(e,[n],async()=>{const o=await fetch(`${od}/${e.key}/tokens/by-symbol?symbols=${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(1e4)});if(!o.ok)throw new Error("Provider native price request failed");const r=(await o.json())?.data?.find(a=>a.symbol?.toUpperCase()===t.toUpperCase());return new Map([[n.toLowerCase(),r?rd(r):0]])}),Er(e,n)?.price??0}async function sm(e,t){const n=t.supportedChains,o=e.map(r=>{if(r.receiptTokenName==="spiceUSDC")return[];const a=Object.keys(r.chainTokens??{}).map(_n).filter(s=>!!s&&Qn(s.address)&&!!n?.includes(s.chainId));return a.sort((s,i)=>{const c=l=>l===t.nativeChainId?-1:n.indexOf(l);return c(s.chainId)-c(i.chainId)||+!Q(s.address,r.address)-+!Q(i.address,r.address)}),a.flatMap(s=>{const i=t.rpcOverrides?.[s.chainId];if(!i)return[];const c=ys(s.chainId,i);if(!c)return[];const l=Oe(s.address)?xt(s.chainId)?.nativeCurrency.symbol:void 0,u=l?`native:${l}`:s.address;return[{rpc:c,token:u,address:s.address,nativeSymbol:l}]})});return(typeof document>"u"||!document.hidden)&&await Promise.all(o.map(async r=>{for(const a of r)if(a.nativeSymbol?await Bi(a.rpc,a.nativeSymbol).catch(()=>0):await Ti(a.rpc,[a.address]).catch(()=>new Map),Er(a.rpc,a.token)?.stale===!1)break})),e.map((r,a)=>{if(r.receiptTokenName==="spiceUSDC")return{...r,balanceUsd:r.balanceFormatted,priceStatus:"fresh"};const s=o[a].map(c=>Er(c.rpc,c.token)),i=s.find(c=>c&&!c.stale)??s.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 im(e,t,n){const o=pn(on),[r,a]=q(()=>typeof document>"u"||!document.hidden);me(()=>{const u=()=>a(!document.hidden);return document.addEventListener("visibilitychange",u),()=>document.removeEventListener("visibilitychange",u)},[]);const s={supportedChains:n??o?.supportedChainIds,nativeChainId:o?.nativeChainId,rpcOverrides:o?.rpcOverrides},i=JSON.stringify([e,s],(u,d)=>typeof d=="bigint"?d.toString():d),c=ae(()=>sm(e,s),[i]),l=Si(`prices:${i}`,c,t&&r&&e.length>0,6e4);return l.updatedAt?l.assets:e}function cm(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 sd=({address:e,supportedChains:t,enabled:n=!0,refetchInterval:o,priceEnabled:r=!1})=>{const a=pn(on),s=a?.apiUrl||Tp,i=gs(),c=a?.supportedChainIds??t,l=JSON.stringify([...c??[]].sort((T,k)=>T-k)),u=e?.toLowerCase(),d=ae(async()=>{const T=`${s}/wallets/${u}/balance`;let k,b;try{const S=await Fp(T,{cache:"no-store"});if(k=S.status,b=S.requestId,!S.ok)throw new Error(`Failed to fetch balance: ${S.status}`);const E=await S.json();if(!Array.isArray(E.balances))throw new Error("Invalid balance response");return E.balances.map(F=>{const P=rm({receiptToken:typeof F.receiptToken=="string"?F.receiptToken:void 0,tokenName:String(F.tokenName??""),balanceAvailable:String(F.balanceAvailable??"0"),chainTokens:cm(F),decimals:typeof F.decimals=="number"?F.decimals:void 0,balanceUsd:typeof F.balanceUsd=="number"||typeof F.balanceUsd=="string"?F.balanceUsd:null},c);return P?{...P,owner:u,location:"rollup",_source:"spice",positionId:`${u}:rollup:${P.receiptTokenId??P.address}`}:null}).filter(F=>F!==null)}catch(S){const E=S instanceof Error?S.name:void 0,F=k===429?"Balance refresh is temporarily busy. Wait a moment and try again.":k===408||k===504||E==="TimeoutError"?"Balance refresh timed out. Try again.":E==="AbortError"?"Balance refresh was interrupted. Try again.":"Balances are unavailable. Check your connection and try again.",P=new ke("RELAYER_STATUS_ERROR",F,{endpoint:T,httpStatus:k,requestId:b,cause:S});throw Ln(P),P}},[u,s,l,a?.nativeChainId,a?.rpcOverrides]),{assets:p,loading:w,refreshing:f,error:g,updatedAt:h}=Si(`rollup:${u}:${s}:${l}`,d,n&&!!u,o??0,i),y=JSON.stringify(t??[]),I=Ie(()=>g?p.map(T=>({...T,balanceError:g,balanceStatus:"stale"})):p,[p,g]),A=im(I,n&&r,c),v=Ie(()=>A.filter(T=>!t?.length||t.includes(T.chainId)||Object.keys(T.chainTokens??{}).some(k=>t.some(b=>k.startsWith(`evm:${b}:`)))),[A,y]),C=ae(T=>v.filter(k=>k.chainId===T),[v]);return{assets:v,loading:w,error:g,hasBalance:v.some(T=>T.balance>0n),refreshing:f,updatedAt:h,refetch:i.invalidate,getAssetsByChain:C}};async function lm(e,t,n){if(n)return{decimals:n.decimals,symbol:n.symbol,name:n.name,logoURI:n.logo};const[o,r,a]=await Promise.all([lr(e,{address:t,abi:pt,functionName:"decimals"}),lr(e,{address:t,abi:pt,functionName:"symbol"}).catch(()=>"TOKEN"),lr(e,{address:t,abi:pt,functionName:"name"}).catch(()=>"TOKEN")]);if(!Number.isInteger(Number(o))||Number(o)<0||Number(o)>255)throw new Error("Invalid token decimals");return{decimals:Number(o),symbol:r,name:a,logoURI:void 0}}const id=async(e,t,n)=>{const o=Ot(t,n),r=xt(t),a=await ci(o,{address:e}),s=r.nativeCurrency,i=r.supportedTokens?.find(c=>Oe(c.address));return{address:Yt,name:s.name,symbol:s.symbol,decimals:s.decimals,balance:a,balanceFormatted:Number(Ne(a,s.decimals)),balanceUsd:0,priceStatus:"unavailable",logoURI:i?.logo||r.logo,isNative:!0,chainId:t}},dm=async(e,t,n,o,r,a,s)=>{try{if(!Qn(n))return null;const i=gn(n),c=Qn(e)?gn(e):e,l=Ot(t,s),u=await lr(l,{address:i,abi:pt,functionName:"balanceOf",args:[c]}),d=Number(Ne(u,a));return u>0n?{address:i,name:o,symbol:r,decimals:a,balance:u,balanceFormatted:d,balanceUsd:0,priceStatus:"unavailable",logoURI:void 0,isNative:!1,chainId:t}:null}catch(i){throw i}},cd=(e,t)=>{const n=xt(t);if(!n)return e;const o=new Set(e.map(a=>a.address.toLowerCase())),r=e.some(a=>a.isNative);for(const a of n.supportedTokens||[])Oe(a.address)&&r||o.has(a.address.toLowerCase())||e.push({address:a.address,name:a.name,symbol:a.symbol,decimals:a.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,priceStatus:"unavailable",logoURI:a.logo,isNative:Oe(a.address),chainId:t});if(!e.find(a=>a.isNative)){const a=n.supportedTokens?.find(s=>Oe(s.address));e.push({address:Yt,name:n.nativeCurrency.name,symbol:n.nativeCurrency.symbol,decimals:n.nativeCurrency.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,priceStatus:"unavailable",logoURI:a?.logo||n.logo,isNative:!0,chainId:t})}return e},um=async(e,t,n)=>{const o=[],r=async i=>{for(const c of i){const l=await dm(e,t,c.address,c.name,c.symbol,c.decimals,n);l&&(l.logoURI=c.logo,o.push(l))}},a=await id(e,t,n);a.balance>0n&&o.push(a);const s=(xt(t)?.supportedTokens||[]).filter(i=>!Oe(i.address));if(s.length>0)try{const i=Ot(t,n),c=gn(e),l=s.filter(w=>Qn(w.address)).map(w=>({address:gn(w.address),abi:pt,functionName:"balanceOf",args:[c]})),u=await i.multicall({contracts:l}),d=s.filter(w=>Qn(w.address)),p=[];u.forEach((w,f)=>{if(w.status==="success"){const g=w.result;if(g&&g>0n){const h=d[f],y=Number(Ne(g,h.decimals));g>0n&&o.push({address:gn(h.address),name:h.name,symbol:h.symbol,decimals:h.decimals,balance:g,balanceFormatted:y,balanceUsd:0,priceStatus:"unavailable",logoURI:h.logo,isNative:!1,chainId:t})}}else p.push(d[f])}),await r(p)}catch{await r(s)}return{tokens:cd(o,t),chainId:t}},pm=async(e,t,n)=>{const o=new Map,r=ys(e,n?n[e]??"":void 0);if(!r)return o;const a=t.filter(l=>Oe(l)),s=t.filter(l=>!Oe(l)),[i,c]=await Promise.all([s.length?Ti(r,s).catch(()=>new Map):new Map,a.length?Bi(r,xt(e)?.nativeCurrency?.symbol??"ETH").catch(()=>0):0]);for(const[l,u]of i)u>0&&o.set(l,u);if(c>0)for(const l of a)o.set(l.toLowerCase(),c);return o},fm=async(e,t,n,o=!0,r)=>{const a=Ot(t,r),s=gn(e),i=[];let c;do{const g=await a.request({method:"alchemy_getTokenBalances",params:[s,"erc20",c?{pageKey:c}:{}]});i.push(...g.tokenBalances),c=g.pageKey||void 0}while(c);const l=i.filter(g=>Qn(g.contractAddress)&&!!g.tokenBalance&&BigInt(g.tokenBalance)>0n),u=xt(t)?.supportedTokens||[],d=g=>u.find(h=>h.address.toLowerCase()===g.toLowerCase()),p=[],w=await id(e,t,r),[f]=await Promise.all([Promise.all(l.map(async g=>{const h=d(g.contractAddress);return h?{name:h.name,symbol:h.symbol,decimals:h.decimals,logo:h.logo??null}:await a.request({method:"alchemy_getTokenMetadata",params:[g.contractAddress]})})),o?Ti(n,l.map(g=>g.contractAddress)):void 0,o&&w.balanceFormatted>0?Bi(n,w.symbol):void 0]);if(w.balance>0n){const g=Er(n,`native:${w.symbol}`);p.push({...w,balanceUsd:(g?.price??0)*w.balanceFormatted,priceStatus:g?g.stale?"stale":"fresh":"unavailable"})}return l.forEach((g,h)=>{const y=f[h];if(!Number.isInteger(y.decimals)||y.decimals===null||y.decimals<0||y.decimals>255)throw new Error(`Invalid token metadata on chain ${t}`);const I=BigInt(g.tokenBalance),A=Number(Ne(I,y.decimals));if(I<=0n)return;const v=Er(n,g.contractAddress),C=(v?.price??0)*A;p.push({address:gn(g.contractAddress),name:y.name||"Unknown",symbol:y.symbol||"UNKNOWN",decimals:y.decimals,balance:I,balanceFormatted:A,balanceUsd:C,priceStatus:v?v.stale?"stale":"fresh":"unavailable",isDiscovered:!d(g.contractAddress),logoURI:y.logo||void 0,isNative:!1,chainId:t})}),{tokens:cd(p,t),chainId:t}},ld=new Set,mm=async(e,t,n=!0,o)=>{try{const r=ys(t,o?o[t]??"":void 0);if(r)try{return await fm(e,t,r,n&&(typeof document>"u"||!document.hidden),o)}catch(a){ld.has(t)||(ld.add(t),console.warn(`Token discovery unavailable on chain ${t}; listing configured tokens only.`,a))}return await um(e,t,o)}catch(r){throw r}},Qr=async(e,t,n=[],o)=>{if(!e)throw new Error("Wallet address is required");const r=Bp(o),a=t?.length?[...new Set(t)]:Object.keys(r).map(Number),s=await Promise.allSettled(a.map(c=>mm(e,c,!0,o))),i={};return s.forEach((c,l)=>{const u=a[l];i[u]=c.status==="fulfilled"?c.value:{chainId:u,tokens:[],error:`Unable to refresh balances on chain ${u}`}}),(await Promise.allSettled(n.map(async c=>{const l=i[c.chainId];if(!l||l.error||l.tokens.some(h=>ut(h.address).toLowerCase()===ut(c.address).toLowerCase()))return;const u=Ot(c.chainId,o),d=await lm(u,c.address,c.decimals!==void 0&&c.symbol?{decimals:c.decimals,symbol:c.symbol,name:c.name||c.symbol,logo:c.logoURI}:void 0),p=await lr(u,{address:c.address,abi:pt,functionName:"balanceOf",args:[e]});await pm(c.chainId,[c.address],o);const w=Number(Ne(p,d.decimals)),f=ys(c.chainId,o?o[c.chainId]??"":void 0),g=f?Er(f,c.address):void 0;l.tokens.push({...d,...c,name:d.name,symbol:d.symbol,decimals:d.decimals,balance:p,balanceFormatted:w,balanceUsd:(g?.price??0)*w,priceStatus:g?g.stale?"stale":"fresh":"unavailable",isNative:!1})}))).forEach((c,l)=>{if(c.status==="rejected"){const u=i[n[l].chainId];u&&(u.error=`Unable to refresh token balances on chain ${u.chainId}`)}}),i},ka=({address:e,supportedChains:t,fetchBalances:n=Qr,additionalTokens:o=[],enabled:r=!0,refreshInterval:a=0,priceEnabled:s=!0})=>{const i=pn(on),c=gs(),l=e?.toLowerCase(),u=JSON.stringify([...i?.supportedChainIds??t??[]].sort((I,A)=>I-A)),d=JSON.stringify(o);me(()=>c.registerTokens(o),[c,d]);const p=l&&l===i?.embeddedWalletAddress?.toLowerCase()?"embedded":"external",w=`wallet:${JSON.stringify([i?.network,i?.apiUrl,i?.rpcOverrides])}:${l}:${p}:${u}:${c.fetcherId(n)}`,f=ae(async()=>{let I;try{I=await n(l,JSON.parse(u),c.tokens(),i?.rpcOverrides)}catch(T){const k=T instanceof Error?T.message:"Unable to refresh balances";I=Object.fromEntries(JSON.parse(u).map(b=>[b,{chainId:b,tokens:[],error:k}]))}const A=c.entry(w).snapshot().assets,v=JSON.parse(u).map(T=>I[T]??{chainId:T,tokens:[],error:`Unable to refresh balances on chain ${T}`}),C=v.flatMap(T=>T.error?[T.error]:[]);return{assets:v.flatMap(T=>T.error?A.filter(k=>k.chainId===T.chainId).map(k=>({...k,balanceError:T.error,balanceStatus:"stale"})):T.tokens.map(k=>({...k,owner:l,location:p,_fundingWallet:p,_source:"wallet",positionId:`${l}:${p}:${T.chainId}:${ut(k.address).toLowerCase()}`}))),error:C.length?C.join("; "):null}},[c,l,u,n,p,w]),g=Si(w,f,r&&!!l,a,c),h=JSON.stringify(t&&[...t].sort((I,A)=>I-A)),y=Ie(()=>t?g.assets.filter(I=>t.includes(I.chainId)):g.assets,[g.assets,h]);return me(()=>{s&&r&&l&&g.refresh()},[s]),{...g,assets:y,refreshAssets:c.invalidate,getAssetsByChain:ae(I=>y.filter(A=>A.chainId===I),[y]),getNativeAssets:ae(()=>y.filter(I=>I.isNative),[y])}};function Fr(e){const t=pn(on),n=gs(),o=e.owner??((t?.mode||"7702")!=="7702"?t?.externalWalletAddress:t?.embeddedWalletAddress),r=o?.toLowerCase()!==t?.embeddedWalletAddress?.toLowerCase(),a=e.sourceChains??t?.supportedChainIds??[],s=(e.enabled??!0)&&!t?.isWhitelistGateActive,i=Ie(()=>{const p=[...t?.additionalSourceTokens??[],...e.additionalSourceTokens??[],...e.destination?[e.destination]:[]];for(const w of e.supportedSourceAssets??[])for(const f of a){const g=xt(f)?.supportedTokens?.find(h=>Ja(h,[w]));g&&p.push({...g,address:g.address,chainId:f,logoURI:g.logo})}return p},[e.destination,JSON.stringify(t?.additionalSourceTokens),JSON.stringify(e.additionalSourceTokens),JSON.stringify(e.supportedSourceAssets),JSON.stringify(a)]),c=ka({address:o,supportedChains:a,fetchBalances:Qr,additionalTokens:i,enabled:s&&e.includeWalletAssets!==!1,refreshInterval:3e4}),l=sd({address:o,supportedChains:a,enabled:s&&e.includeRollupAssets!==!1&&!!o&&o.toLowerCase()===t?.embeddedWalletAddress?.toLowerCase(),priceEnabled:s,refetchInterval:3e4}),u=Ie(()=>s?[...(e.includeWalletAssets===!1?[]:c.assets).map(p=>({...p,owner:p.owner??o,location:p.location??(r?"external":"embedded"),_source:"wallet"})),...(e.includeRollupAssets===!1||o?.toLowerCase()!==t?.embeddedWalletAddress?.toLowerCase()?[]:l.assets).map(p=>({...p,owner:p.owner??o,location:"rollup",_source:"spice"}))]:[],[s,c.assets,l.assets,e.includeWalletAssets,e.includeRollupAssets,o,r,t?.embeddedWalletAddress]),d=Ie(()=>u.map(p=>({asset:p,...To(p,e.role??"holding",{allowedTokens:t?.allowedTokens,rpcOverrides:t?.rpcOverrides,liquidityVenues:t?.liquidityVenues,isWhitelistGateActive:!!t?.isWhitelistGateActive},e.destination,e.supportedSourceAssets,{requiresEscrow:e.requiresEscrow})})),[u,t?.allowedTokens,t?.rpcOverrides,t?.liquidityVenues,t?.isWhitelistGateActive,e.role,e.destination,e.supportedSourceAssets,e.requiresEscrow]);return{positions:d,assets:Ie(()=>d.filter(p=>p.eligible&&p.asset.balance>0n).map(p=>p.asset),[d]),walletAssets:Ie(()=>u.filter(p=>p._source==="wallet"),[u]),rollupAssets:Ie(()=>u.filter(p=>p._source==="spice"),[u]),loading:c.loading||l.loading,refreshing:c.refreshing||l.refreshing,error:c.error||l.error,refresh:n.invalidate}}function bs(e,t=!0,n){const o=n?.pendingOnly===!0,r=qe.getBaseUrl(),a=`${r}:${e?.toLowerCase()??""}:${o}`,[s,i]=q({scope:a,actions:[],error:null,loading:t&&!!e,updatedAt:null,revision:0}),[c,l]=q(0),u=ae(()=>l(p=>p+1),[]);me(()=>{if(!t||!e){i(h=>h.scope===a&&h.actions.length===0&&!h.error&&!h.loading&&!h.updatedAt&&h.revision===0?h:{scope:a,actions:[],error:null,loading:!1,updatedAt:null,revision:0});return}const p=new AbortController,w=new Ir;w.setBaseUrl(r);let f;i(h=>({scope:a,actions:h.scope===a?h.actions:[],error:h.scope===a?h.error:null,loading:!0,updatedAt:h.scope===a?h.updatedAt:null,revision:h.scope===a?h.revision:0}));const g=async()=>{try{const h=await w.getWalletActions(e,{pendingOnly:o,signal:p.signal});p.signal.aborted||i(y=>({scope:a,actions:h,error:null,loading:!1,updatedAt:new Date().toISOString(),revision:y.scope===a?y.revision+1:1}))}catch(h){if(p.signal.aborted)return;const y=h instanceof ke&&h.context.httpStatus===404;i(y&&!o?I=>({scope:a,actions:[],error:null,loading:!1,updatedAt:new Date().toISOString(),revision:I.scope===a?I.revision+1:1}):I=>({scope:a,actions:I.scope===a?I.actions:[],error:"Activity is temporarily unavailable. Refresh to check again.",loading:!1,updatedAt:I.scope===a?I.updatedAt:null,revision:I.scope===a?I.revision:0}))}p.signal.aborted||(f=setTimeout(g,5e3))};return g(),window.addEventListener("online",u),()=>{p.abort(),f&&clearTimeout(f),window.removeEventListener("online",u)}},[r,e,t,a,o,c,u]);const d=s.scope===a;return{actions:t&&e&&d?s.actions:[],error:d?s.error:null,loading:t&&!!e&&(!d||s.loading),updatedAt:d?s.updatedAt:null,revision:d?s.revision:0,refresh:u}}function Oi(e){const t=G(0),n=G(null),o=G(e.run);o.current=e.run;const r=G(e.onSkip);r.current=e.onSkip;const a=G(e.onCleanup);a.current=e.onCleanup,me(()=>{if(!e.shouldRun){t.current+=1,n.current?.abort(),r.current?.();return}let s=!1,i=!1;const c=async p=>{if(p&&i)return;n.current?.abort();const w=new AbortController;n.current=w;const f=++t.current;i=!0;try{await o.current({isBackground:p,isCurrent:()=>!s&&t.current===f,signal:w.signal})}finally{i=!1}},l=window.setTimeout(()=>void c(!1),e.delayMs??250),u=()=>{document.hidden||c(!0)},d=e.backgroundIntervalMs?window.setInterval(u,e.backgroundIntervalMs):void 0;return d!==void 0&&document.addEventListener("visibilitychange",u),()=>{s=!0,n.current?.abort(),clearTimeout(l),d!==void 0&&(window.clearInterval(d),document.removeEventListener("visibilitychange",u)),a.current?.()}},[e.shouldRun,e.delayMs,e.backgroundIntervalMs,...e.deps])}function dd(e,t){if(e.length!==t.length)return!1;const n=Fo(e),o=Fo(t);return n.every((r,a)=>r.hash===o[a]?.hash)}const vo=e=>new Promise(t=>setTimeout(t,e)),hm="0xa9059cbb";function ud(e){const t=e.findIndex(r=>No(r.chainId));if(t<=0)return[];const n=new Map,o=(r,a,s)=>{if(s<=0n)return;const i=`${r}:${a.toLowerCase()}`,c=n.get(i);c?c.amount+=s:n.set(i,{chainId:r,token:a,amount:s})};for(const r of e.slice(0,t)){const a=pa(r.chainId);if(!(!a||a===Yt)){for(const s of r.calls)if(s.value&&s.value>0n&&Q(s.to,a)&&o(r.chainId,Yt,s.value),!!s.data?.startsWith(hm))try{const i=Jn({abi:pt,data:s.data});if(i.functionName!=="transfer")continue;const[c,l]=i.args;Q(c,a)&&o(r.chainId,s.to,l)}catch{}}}return[...n.values()]}function pd(e){const t=en(e.token,e.chainId);return[t?.equivalenceGroup,t?.symbol,t?.name]}function fd(e,t){return td(e,t.chainId,t.token,pd(t))}function gm(e,t){const n=tm(e,t.chainId,t.token,pd(t));return!n||n.receiptDecimals>=n.chainDecimals?t.amount:bo(bo(t.amount,n.chainDecimals,n.receiptDecimals),n.receiptDecimals,n.chainDecimals)}async function md(e){const{deposits:t,baseline:n,fetchEntries:o,timeoutMs:r=12e4,intervalMs:a,signal:s,wait:i=vo}=e;if(t.length===0)return!0;const c=new Map(t.map(d=>[d,fd(n,d)])),l=Date.now(),u=l+r;for(;!s?.aborted;){try{const f=await o();if(t.every(g=>fd(f,g)-c.get(g)>=gm(f,g)))return!0}catch{}const d=Date.now();if(d>=u)return!1;const p=d-l,w=a??(p<5e3?250:p<15e3?1e3:3e3);await i(Math.min(w,u-d))}return!1}function Ri(e,t){const n=Fo(e).map(o=>o.hash);return cr(jo([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,t,n]))}async function Di(e,t,n,o,r){if(o?.aborted)throw new ke("ABORT","Execution transaction aborted");const a={raw:Ri(t,n)},s=r?await e.signMessage(a,r):await e.signMessage(a);console.debug("[SpiceFlow:execution]",{phase:"signature-returned",at:Date.now()});const i=typeof s=="string"?s:s.signature;if(!i)throw new ke("SIGNATURE_FAILED","Failed to sign intent authorization. The wallet returned an empty signature.");return i}function wm(e){return e.domain==="spicenet"||No(e.chainId)}const hd=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;async function ym(e,t,n){const o=(u,d)=>new ke("SIGNATURE_FAILED","The wallet returned an invalid authorization. Review the action and try again.",{chainId:t.chainId,reason:u,...d?{cause:d}:{}});if(!e||typeof e!="object")throw o("missing-authorization");const r=e;for(const u of["address","contractAddress"])if(r[u]!==void 0&&(typeof r[u]!="string"||r[u].toLowerCase()!==t.address.toLowerCase()))throw o("authorization-target-mismatch");for(const u of["chainId","nonce"]){const d=r[u];if(d!==void 0&&(typeof d=="bigint"?d!==BigInt(t[u]):typeof d!="number"||!Number.isSafeInteger(d)||d!==t[u]))throw o(`authorization-${u}-mismatch`)}const{r:a,s,yParity:i}=r;if(typeof a!="string"||typeof s!="string"||!/^0x[0-9a-fA-F]{64}$/.test(a)||!/^0x[0-9a-fA-F]{64}$/.test(s)||i!==0&&i!==1||BigInt(a)===0n||BigInt(a)>=hd||BigInt(s)===0n||BigInt(s)>hd/2n)throw o("invalid-signature");const c={...t,r:a,s,yParity:i};let l;try{l=await af({hash:cr(rl(["0x05",sf([cs(t.chainId),t.address,t.nonce===0?"0x":cs(t.nonce)])])),signature:c})}catch(u){throw o("invalid-signature",u)}if(l.toLowerCase()!==n.toLowerCase())throw o("authorization-signer-mismatch");return c}async function Mi(e){const{chainBatches:t,signingAddress:n,actions:o,cache:r,signal:a,onSignatureRequested:s,beforeSign:i}=e;if(a?.aborted)throw new ke("ABORT","Execution transaction aborted");if(typeof n!="string"||!Qn(n,{strict:!1})||n.toLowerCase()===al)throw new ke("INVALID_PARAMS","A valid signing address is required.");for(const p of t)if(!Number.isSafeInteger(p.chainId)||p.chainId<=0)throw new ke("INVALID_PARAMS","A valid authorization chain is required.");const c=[...new Set(t.filter(p=>!wm(p)).map(p=>p.chainId))].map(p=>{const w=Op(p);if(!Qn(w,{strict:!1})||w.toLowerCase()===al)throw new ke("INVALID_PARAMS","A valid delegation target is required.");return{chainId:p,client:Ot(p),delegateContract:w}}),[l]=await Promise.all([Promise.all(c.map(async({chainId:p,client:w,delegateContract:f})=>{const g=Number(await Yp(n,w));if(!Number.isSafeInteger(g)||g<0)throw new ke("INVALID_PARAMS","The authorization nonce is invalid.");const h=[n.toLowerCase(),p,f.toLowerCase(),g].join(":");return{chainId:p,delegateContract:f,nonce:g,cacheKey:h,cached:r?.get(h)}})),c.length?o.prepareSigning?.():void 0]);if(await i?.(),a?.aborted)throw new ke("ABORT","Execution transaction aborted");const u=[];let d=!1;for(const{chainId:p,delegateContract:w,nonce:f,cacheKey:g,cached:h}of l){if(h===void 0&&d&&await i?.(),a?.aborted)throw new ke("ABORT","Execution transaction aborted");const y=h===void 0?await o.signAuthorization({contractAddress:w,chainId:p,nonce:f},s):h;let I;try{I=await ym(y,{address:w,chainId:p,nonce:f},n)}catch(A){throw r?.delete(g),A}if(a?.aborted)throw new ke("ABORT","Execution transaction aborted");d=!0,r?.set(g,I),u.push(I)}return u}const gd=15;function bm(e){return e.now-e.lastProgressAt>=e.pollTimeoutMs}function wd(e,t){return{intentId:e,steps:t.map(n=>({...n,status:"pending"})),overallStatus:"processing"}}function xs(e,t,n){const o=e.steps.map(i=>({...i})),r=o[t];if(!r)return e;n.status==="success"||n.status==="completed"?(o[t]={...r,status:"success",transactionHash:n.transactionHash},t+1<o.length&&o[t+1].status==="pending"&&(o[t+1]={...o[t+1],status:"processing"})):n.status==="reverted"||n.status==="error"?o[t]={...r,status:"failed",transactionHash:n.transactionHash,error:n.error}:o[t]={...r,status:"processing"};const a=o.some(i=>i.status==="failed"),s=o.every(i=>i.status==="success");return{...e,steps:o,overallStatus:a?"failed":s?"success":"processing"}}function xm({checkStepStatus:e,retryStep:t,maxRetries:n=3,pollingInterval:o=2500,pollTimeoutMs:r=3e5}){const[a,s]=q(null),i=G(null),c=G(null),l=G(!1),u=G(!1),d=G(0),p=G({}),w=G(0),f=ae(v=>{i.current=v,s(v)},[]),g=ae(()=>{c.current&&(clearInterval(c.current),c.current=null)},[]),h=ae(()=>{d.current=0,p.current={},w.current=0,l.current=!0,g(),f(null)},[g,f]),y=ae((v,C)=>{g(),l.current=!1,f(wd(v,C))},[g,f]),I=ae((v,C)=>{const T=i.current;T&&f(xs(T,v,C))},[f]),A=ae((v,C)=>{g(),l.current=!1,u.current=!1,d.current=0,p.current={},w.current=Date.now(),f(wd(v,C));const T=async()=>{if(!(l.current||u.current||!e)){u.current=!0;try{if(bm({now:Date.now(),lastProgressAt:w.current,pollTimeoutMs:r})){const S=i.current;S&&f({...S,steps:S.steps.map(E=>E.status==="success"?E:{...E,status:"failed",error:"Taking longer than expected. It may still complete - check the explorer, then refresh."}),overallStatus:"failed"}),l.current=!0,g();return}const k=i.current;if(!k)return;const b=k.steps.findIndex(S=>S.status!=="success");if(b===-1){l.current=!0,g();return}if(!(b===0||k.steps[b-1].status==="success"))return;try{const S=k.steps[b].stepId,{data:E}=await e(v,S);if(d.current=0,E.status==="success"&&(w.current=Date.now()),E.status==="reverted"){const P=p.current[S]||0;if(t&&P<n){p.current[S]=P+1;try{await t(v,S)}catch(B){console.error(`[intentStatus] retry failed for step ${S}:`,B)}f(xs(i.current,b,{status:"executing"}));return}}const F=xs(i.current,b,E);f(F),F.overallStatus!=="processing"&&(l.current=!0,g())}catch(S){d.current+=1,console.error(`[intentStatus] poll error (${d.current}/${gd}):`,S),d.current>=gd&&(f(xs(i.current,b,{status:"error"})),l.current=!0,g())}}finally{u.current=!1}}};T(),c.current=setInterval(T,o)},[e,t,n,o,r,g,f]);return me(()=>()=>g(),[g]),{intentStatus:a,startStatusPolling:A,beginStatusTracking:y,applyStepUpdate:I,stopStatusPolling:g,clearStatus:h}}function vm(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 Im=350,km=2500;async function yd(e){const{actionId:t,intentIndex:n,intentId:o,stepIndex:r,maxPolls:a=48,maxExecuteAttempts:s=3,pollsBeforeRetry:i=5,maxConsecutiveStatusErrors:c=15,onStatusMessage:l,onStepUpdate:u,signal:d,chainId:p,startWithExecute:w=!0,observeOnly:f=!1,relayer:g=qe,completeOnExecution:h=!1}=e;if(d?.aborted)throw new ke("ABORT","Execution transaction aborted");let y="pending",I,A,v=e.initialExecuteAttempts??0,C=0,T,k;const b=new Promise((E,F)=>{T=E,k=()=>F(new ke("ABORT","Execution transaction aborted"))}),S=()=>{v++,e.onExecuteAttempt?.(v),g.executeStep(t,n,r,{action:"execute"}).then(E=>{E.transactionHash&&(I=E.transactionHash),E.status==="success"&&T({status:E.status,transactionHash:E.transactionHash})}).catch(E=>{const F=E instanceof Error?E.message:String(E);console.warn(`[execution] executeStep ${r} attempt ${v} error (will poll):`,F)})};d?.addEventListener("abort",k,{once:!0});try{w&&!f&&v<s&&S();for(let E=0;E<a;E++){const F=E===0?Im:km;try{const B=await Promise.race([vo(F).then(()=>{}),b]);if(d?.aborted)throw new ke("ABORT","Execution transaction aborted");const R=B??await Promise.race([g.checkStepStatus(o,r,h).then(O=>O.data),b]);if(d?.aborted)throw new ke("ABORT","Execution transaction aborted");C=0,y=R.status,A=R.error;const x=R.transactionHash;x&&(I=x),h&&/^0x[0-9a-f]{64}$/i.test(x??"")&&(R.executionStatus==="success"||R.executionStatus==="reverted")&&(y=R.executionStatus,A=void 0),u?.({status:y,transactionHash:I,error:A})}catch(B){if(B instanceof Error&&(B.name==="AbortError"||B instanceof ke&&B.code==="ABORT"))throw B;if(C++,C>=c){if(!f)throw B;l?.("Status is temporarily unavailable. The backend continues this action.",I)}continue}if(!f&&y==="created"&&E>=v*i&&v<s&&S(),y==="reverted"||y==="error")throw new ke("ON_CHAIN_REVERT",vm(y,A),{status:y,txHash:I,actionId:t,intentId:o,stepId:r,chainId:p});if(y==="success"||y==="completed")return I;let P="Waiting for solver...";y==="executing"?P="Transaction executing...":y==="submitted"?P="Transaction submitted...":y==="created"&&(P="Waiting for relayer..."),l?.(P,I)}throw new ke("POLLING_EXHAUSTED",`Transaction is still processing (status: ${y}). 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:o,stepId:r,lastStatus:y,pollAttempts:a,maxPolls:a,txHash:I})}finally{d?.removeEventListener("abort",k)}}async function Cm(e){const{actionId:t,intentIndex:n,intentId:o,totalSteps:r,observeOnly:a,delayBeforeSpicenetStepMs:s=5e3,isSpicenetStep:i,beforeStep:c,maxExecuteAttemptsForStep:l,maxPolls:u=48,onStatusMessage:d,onStepUpdate:p,signal:w}=e;let f;for(let g=e.startStep??0;g<r;g++){if(!a&&g>0&&i?.(g)&&s>0&&await vo(s),a||await c?.(g),w?.aborted)throw new ke("ABORT","Execution transaction aborted");const h=l?.(g)??3,y=await yd({actionId:t,intentIndex:n,intentId:o,stepIndex:g,observeOnly:a,startWithExecute:e.startWithExecute,relayer:e.relayer,maxPolls:u,maxExecuteAttempts:h,initialExecuteAttempts:e.executeAttempts?.get(g),onExecuteAttempt:I=>e.executeAttempts?.set(g,I),maxConsecutiveStatusErrors:h===6?5:15,onStatusMessage:d,onStepUpdate:p?I=>p(g,I):void 0,signal:w,completeOnExecution:g===r-1&&i?.(g)===!1});y&&(f=y)}return f}const Sm="0xa9059cbb",Am=[Zp,kn,Kn];function bd(e){return Am.some(t=>Q(e,t))}function vs(e,t){return e.map(n=>{if(n.domain==="spicenet"||No(n.chainId)||n.calls.length===0)return n;const o=new Set((n.tokenTransfers??[]).filter(s=>(s.from==="escrow"||s.from==="solver")&&Q(s.to,t)).map(s=>s.token.toLowerCase()));if(o.size===0)return n;const r=[...o].some(Oe);let a=0;for(const s of n.calls){if(r&&s.value>0n&&s.data==="0x"&&bd(s.to)){a+=1;continue}if(!s.data?.startsWith(Sm))break;try{const i=Jn({abi:pt,data:s.data});if(i.functionName!=="transfer")break;const[c]=i.args;if(!bd(c)||!o.has(s.to.toLowerCase()))break;a+=1}catch{break}}return a===0?n:{...n,calls:n.calls.slice(a)}})}async function Ni(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 o=()=>new ke("ABORT","Execution observation retired");if(n?.aborted)throw o();const r=await new Promise((a,s)=>{const i=()=>s(o());n?.addEventListener("abort",i,{once:!0}),Promise.resolve().then(()=>e.waitForTransactionReceipt({hash:t,timeout:12e4,pollingInterval:2e3,confirmations:1})).then(a,s).finally(()=>n?.removeEventListener("abort",i))});if(n?.aborted)throw o();if(r.transactionHash?.toLowerCase()===t.toLowerCase()&&r.status==="reverted")throw new ke("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 Is(e){let t=e.hash,n=!1;const o=Date.now()+12e4,r=s=>s.transactionHash&&s.transactionHash.toLowerCase()!==t.toLowerCase();let a=await e.client.waitForTransactionReceipt({hash:t,timeout:12e4,pollingInterval:2e3,confirmations:1,onReplaced:s=>{const i=s.transaction,c=s.replacedTransaction;if(!(s.reason==="repriced"&&c?.hash?.toLowerCase()===t.toLowerCase()&&c?.to?.toLowerCase()===e.call.to.toLowerCase()&&(c.input??"0x").toLowerCase()===e.call.data.toLowerCase()&&BigInt(c.value??0)===e.call.value&&c?.from&&c.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()===c?.from?.toLowerCase()&&i.nonce===c?.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(a)&&a.status==="success"&&(a=await e.client.waitForTransactionReceipt({hash:t,timeout:Math.max(o-Date.now(),1),pollingInterval:2e3,confirmations:e.confirmations})),r(a))throw new Error("Unexpected transaction receipt; recover the submitted transaction before retrying");return{receipt:a,hash:t}}const Pi=10n,Em=5;function ks(e,t,n){return n?.calls.length&&n.amountOutMinimum>0n?[{chainId:e,token:t,amount:n.amountOutMinimum}]:[]}function Wi(e){return e.map(t=>({...t,calls:[...t.calls],tokenTransfers:t.tokenTransfers?[...t.tokenTransfers]:void 0}))}function Cs({token:e,recipient:t,amount:n}){return{to:e,value:0n,data:Wt({abi:pt,functionName:"transfer",args:[t,n]})}}function Fm({chainBatches:e,token:t,amount:n}){const o=Wi(e),r=o[o.length-1];if(!r)return o;const a=Mo(r.chainId);return r.calls=[...r.calls,Cs({token:t,recipient:a,amount:n})],o}function xd({chainBatches:e,user:t,token:n,grossAmount:o,gasFee:r,policy:a}){const s=Wi(e),i=s[s.length-1];if(!i)throw new ke("INVALID_PARAMS","Action-output escrow funding requires at least one chain batch.");const c=es(o,BigInt(a?.platformBps??Pi)),l=r+c;if(l>=o)throw new ke("INVALID_PARAMS","Borrow amount is too small after gas and Spicenet fees.",{grossAmount:o.toString(),gasFee:r.toString(),spicenetFee:c.toString()});const u=o-l,d=Mo(i.chainId),p=[];return r>0n&&p.push(Cs({token:n,recipient:a?.gasRecipient??kn,amount:r})),c>0n&&p.push(Cs({token:n,recipient:a?.platformRecipient??Kn,amount:c})),i.calls=[...i.calls,...p,Cs({token:n,recipient:d,amount:u})],i.tokenTransfers=[...i.tokenTransfers??[],...r>0n?[{from:t,to:kn,token:n,amount:r}]:[],...c>0n?[{from:t,to:Kn,token:n,amount:c}]:[],{from:t,to:d,token:n,amount:u}],{chainBatches:s,gasFee:r,spicenetFee:c,netEscrowAmount:u,outputCredit:{chainId:i.chainId,token:n,amount:o}}}async function vd({chainBatches:e,user:t,token:n,grossAmount:o,chainAuthorizations:r}){let a=0n,s,i=xd({chainBatches:e,user:t,token:n,grossAmount:o,gasFee:a});for(let c=0;c<Em;c+=1){const l=Fo(i.chainBatches),u=await qe.estimateBatchGas({user:t,outputToken:n,chainBatches:i.chainBatches.map((p,w)=>({...p,hash:l[w].hash})),chainAuthorizations:r}),d=u.gasFee;if(d===a&&JSON.stringify(u.policy)===JSON.stringify(s))return i;s=u.policy,a=d,i=xd({chainBatches:e,user:t,token:n,grossAmount:o,gasFee:a,policy:s})}throw new ke("INVALID_PARAMS","Action-output fee estimate did not converge. Please retry.")}function Uo(e){return No(e.chainId)}const Tm="0xa9059cbb";function Ca(e,t){return`${e}:${ut(t).toLowerCase()}`}function Id(e,t){return t===Yt.toLowerCase()?{symbol:io(e),decimals:18}:en(t,e)??{symbol:"tokens",decimals:18}}function Bm(e,t){const n=en(t,e);return[n?.equivalenceGroup,n?.symbol,n?.name]}async function Ui(e){return ts(e)}async function Li(e,t,n){const o=new Map,r=new Map,a=[...n?.walletFundingRequirement?[n.walletFundingRequirement]:[],...n?.walletFundingRequirements??[]];for(const d of a){if(d.amount<0n)throw new Error("Accepted wallet funding must not be negative");const p=Ca(d.chainId,d.token);r.set(p,(r.get(p)??0n)+d.amount),o.set(p,0n)}const s=new Map,i=new Map,c=new Map,l=new Map;for(const d of n?.actionOutputCredits??[]){const p=Ca(d.chainId,d.token);l.set(p,(l.get(p)??0n)+d.amount)}for(const d of e){if(Uo(d))continue;for(const f of d.tokenTransfers??[]){if(f.from!=="escrow"&&f.from!=="solver"||!Q(f.to,t))continue;const g=BigInt(f.amount??0);if(g<=0n)continue;const h=Ca(d.chainId,f.token);s.set(h,(s.get(h)??0n)+g),f.from==="escrow"&&i.set(h,(i.get(h)??0n)+g)}const p=pa(d.chainId),w=f=>!!p&&p!==Yt&&Q(f,p);for(const f of d.calls){if(f.value&&f.value>0n){const g=Ca(d.chainId,Yt);o.set(g,(o.get(g)??0n)+f.value),w(f.to)&&c.set(g,(c.get(g)??0n)+f.value)}if(f.data?.startsWith(Tm))try{const g=Jn({abi:pt,data:f.data});if(g.functionName!=="transfer")continue;const[h,y]=g.args,I=f.to.toLowerCase(),A=Ca(d.chainId,I);o.set(A,(o.get(A)??0n)+y),w(h)&&c.set(A,(c.get(A)??0n)+y)}catch{}}}let u=null;for(const[d,p]of i){const w=p-(c.get(d)??0n);if(w<=0n)continue;const[f,g]=d.split(":"),h=Number(f),y=Id(h,g);u??(u=await Ui(t));const I=td(u,h,g,Bm(h,g));if(!(I>=w))throw new ke("INVALID_PARAMS",`Insufficient Spice ${y.symbol}: needs ${Ne(w,y.decimals)}, has ${Ne(I,y.decimals)}.`,{chainId:h,token:g,userAddress:t,requiredAmount:w.toString(),balance:I.toString(),balanceSource:"spice"})}for(const[d,p]of o){const[w,f]=d.split(":"),g=Number(w);let h=p-(s.get(d)??0n)-(l.get(d)??0n);const y=r.get(d)??0n;if(y>h&&(h=y),h<=0n)continue;const I=Ot(g),A=f===Yt.toLowerCase()?await I.getBalance({address:t}):await I.readContract({address:f,abi:pt,functionName:"balanceOf",args:[t]});if(A>=h)continue;const v=Id(g,f);throw new ke("INVALID_PARAMS",`Insufficient ${v.symbol} on ${io(g)}: needs ${Ne(h,v.decimals)}, has ${Ne(A,v.decimals)}.`,{chainId:g,token:f,userAddress:t,requiredAmount:h.toString(),balance:A.toString(),balanceSource:"wallet"})}}function Om({chainBatches:e,tokenAddress:t,tokenTransferAmount:n,useCustomTransfers:o}){if(!(e.some(Uo)||!(o?e.some(r=>Uo(r)?!1:(r.tokenTransfers??[]).some(a=>a.from==="escrow"&&BigInt(a.amount??0)>0n)):n>0n)))throw new ke("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:!!o})}function Rm(e,t,n,o){t.forEach((r,a)=>{if(!r.to||!r.from||!r.token||r.amount===void 0)throw new ke("INVALID_TOKEN_TRANSFER",`tokenTransfers[${a}] 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:a,transfer:{from:r.from,to:r.to,token:r.token,amount:r.amount?.toString()},signingAddress:n,useCustomTransfers:o})})}function Ss({user:e,chainBatches:t,tokenAddress:n,tokenTransferAmount:o,exp:r,signature:a,chainAuthorizations:s,useCustomTransfers:i}){const c=t,l=Fo(c),u=c.filter(d=>!Uo(d)).length;if(Om({chainBatches:c,tokenAddress:n,tokenTransferAmount:o,useCustomTransfers:i}),!i&&o>0n&&u>1)throw new ke("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:u,tokenAddress:n,tokenTransferAmount:o.toString()});return{user:e,...s?{chainAuthorizations:s}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:a,nbf:0,exp:r,chainBatches:l.map((d,p)=>{const w=c[p],f=Uo(w)?[]:i?w.tokenTransfers??[]:o>0n?[{from:"escrow",to:e,token:n,amount:o}]:[];return Rm(Number(d.chainId),f,e,i),{hash:d.hash,chainId:Number(d.chainId),tokenTransfers:f,calls:d.calls}})}]}}function kd(e,t){const n=t?.depositToEscrow?.gasFundingSource==="action-output"?t.depositToEscrow:null,o=t?.depositToEscrow&&!n?Fm({chainBatches:e,token:t.depositToEscrow.token,amount:t.depositToEscrow.amount}):Wi(e);return{actionOutputDeposit:n,batches:o}}let qi=!1;function jr(){const{address:e,isConnected:t,isAuthenticated:n,actions:o}=Oo(),r=G(null),a=G(0),s=G(null),{intentStatus:i,startStatusPolling:c,beginStatusTracking:l,applyStepUpdate:u,clearStatus:d}=xm({checkStepStatus:(A,v)=>qe.checkStepStatus(A,v),retryStep:async(A,v)=>{const[C,T]=A.split("/"),k=parseInt(T||"0",10);await qe.executeStep(C,k,v,{action:"execute"})}}),p=ae(()=>{a.current++,s.current=null,d()},[d]),w=G(o),f=G(new Map);w.current=o;const g=ae((A,v,C,T,k)=>Mi({chainBatches:A,signingAddress:v,actions:w.current,cache:f.current,signal:C,onSignatureRequested:T,beforeSign:k}),[]),h=ae((A,v,C,T)=>Di(w.current,A,v,C,T),[]),y=ae(async(A,v,C,T,k,b)=>{let S={},E={};const F=(B,R,x)=>{x?.actionId&&(S={actionId:x.actionId,intentId:x.intentId,intentIndex:x.intentIndex,totalSteps:x.totalSteps,autoContinue:x.autoContinue,user:b?.userOverride||e}),T?.({step:B,message:R,...E,...S,...x})};if(qi)throw new ke("CONCURRENT_EXECUTION","A execution transaction is already in progress. Please wait.");qi=!0;const P=a.current;try{if(!e)throw new ke("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const B=b?.userOverride||e,R=qe.getBaseUrl(),x=s.current;if(x&&Q(x.user,B)&&x.apiUrl===R){if(x.resume)return await x.resume(A,v,C,k,T,b);throw x.error}s.current=null;const O=Se=>tl(Se.map(Ze=>({...Ze,tokenTransfers:Ze.tokenTransfers??[]})),[]),M=O(A),U=Se=>new Map(Object.entries(Se??{}).filter(([Ze,xe])=>Ze!=="signal"&&(typeof xe!="function"||["prepareForSigning","adjustBatchesForEstimate","resolveActionOutputCredits"].includes(Ze))).map(([Ze,xe])=>[Ze,typeof xe=="function"?xe:JSON.stringify(xe,(Ke,ue)=>typeof ue=="bigint"?ue.toString():ue)])),V=U(b),j=await qe.supportsAutomaticContinuation({signal:k}),{actionOutputDeposit:_,batches:J}=kd(A,b);let K=J,ee=[],te=b?.useCustomTransfers,ge=ud(K),we=null;const ve=async()=>{(b?.walletFundingRequirement||b?.walletFundingRequirements?.length)&&await Li([],B,{walletFundingRequirement:b?.walletFundingRequirement,walletFundingRequirements:b?.walletFundingRequirements});for(let Se=0;ge.length>0&&Se<3;Se++)try{we=await Ui(B);break}catch(Ze){if(k?.aborted)throw new ke("ABORT","Execution transaction aborted");if(Se===2)throw new ke("RELAYER_ERROR","Unable to read your Spice balance. Please try again before submitting the transaction.",{cause:Ze});await vo(1e3)}await b?.validateBeforeSubmit?.(K)};F("building","Preparing your wallet and transaction...");const Ce=await g(K,B,k,()=>F("signing-delegation","Confirm the authorization in your wallet..."),ve);if(F("building","Checking transaction fees and balances..."),k?.aborted)throw new ke("ABORT","Execution transaction aborted");const ne=BigInt(Math.floor(Date.now()/1e3)+3600);if(_){const Se=await vd({chainBatches:A,user:B,token:_.token,grossAmount:_.amount,chainAuthorizations:Ce});K=Se.chainBatches,ee=[Se.outputCredit],te=!0}if(!b?.skipPreSubmitFeeEstimate){let Se=!1;if(b?.feeExecutionMode==="user-transfer"&&b.adjustBatchesForEstimate&&qe.canValidateActionFees()){const Ze=await qe.validateActionFees(Ss({user:B,chainBatches:K,tokenAddress:v,tokenTransferAmount:C,exp:Number(ne),signature:"0x00",chainAuthorizations:Ce,useCustomTransfers:te}),{signal:k});r.current=Ze;const xe=await b.adjustBatchesForEstimate({feeEstimate:Ze,chainBatches:K});Se=!xe||dd(K,xe),xe&&(K=xe)}for(let Ze=0;!Se&&Ze<10;Ze++){const xe=b?.feeExecutionMode==="user-transfer"?vs(K,B):K,Ke=Ss({user:B,chainBatches:xe,tokenAddress:v,tokenTransferAmount:C,exp:Number(ne),signature:"0x00",chainAuthorizations:Ce,useCustomTransfers:te}),ue=await qe.estimateActionFees(Ke,{signal:k});r.current=ue;const tt=await b?.adjustBatchesForEstimate?.({feeEstimate:ue,chainBatches:K}),vt=!!tt&&dd(K,tt);if(!tt||vt){Se=!0;break}K=tt}if(!Se)throw new ke("INVALID_PARAMS","Fee estimate did not converge. Please retry.")}if(b?.prepareForSigning){const Se=await b.prepareForSigning(K);if(Se.length!==K.length||Se.some((Ze,xe)=>Ze.chainId!==K[xe].chainId||Ze.domain!==K[xe].domain))throw new Error("The funded route changed before signing");K=Se}b?.resolveActionOutputCredits&&(ee=await b.resolveActionOutputCredits()),(!b?.skipUserFundingPreflight||b.walletFundingRequirement||b.walletFundingRequirements?.length)&&await Li(b?.skipUserFundingPreflight?[]:K,B,{actionOutputCredits:ee,walletFundingRequirement:b?.walletFundingRequirement,walletFundingRequirements:b?.walletFundingRequirements}),ge=ud(K),ge.length&&!we&&(we=await ts(B)),await b?.validateBeforeSubmit?.(K),F("building","Preparing the signing request...");const Y=await h(K,ne,k,()=>F("signing-intent","Confirm the transaction in your wallet..."));if(k?.aborted)throw new ke("ABORT","Execution transaction aborted");if(R!==qe.getBaseUrl())throw new ke("RELAYER_ERROR","The network changed before submission. Review your balances before trying again.");const ce=Ss({user:B,chainBatches:K,tokenAddress:v,tokenTransferAmount:C,exp:Number(ne),signature:Y,chainAuthorizations:Ce,useCustomTransfers:te});let W=K.length-1;for(;W>=0&&Uo(K[W]);)W--;E={totalSteps:K.length},W>=0&&(E={...E,destinationChainId:Number(K[W].chainId),destinationStepIndex:W});const Le=Date.now();if(F("submitting","Submitting to relayer..."),await b?.validateBeforeSubmit?.(K),k?.aborted)throw new ke("ABORT","Execution transaction aborted");if(R!==qe.getBaseUrl())throw new ke("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()-Le});const Te=K.length;let L;try{L=await qe.createAction({...ce,...b?.externalExecution?{externalExecution:b.externalExecution}:{}},{autoContinue:j,idempotencyKey:b?.idempotencyKey,signal:k,onAccepted:Se=>{const[Ze,xe="0"]=Se.intentIds[0].split("/"),Ke=parseInt(xe,10);F("executing","Executing on chain...",{actionId:Ze,intentId:`${Ze}/${Ke}`,intentIndex:Ke,totalSteps:Te,autoContinue:Se.autoContinue===!0})}})}catch(Se){throw P===a.current&&Se instanceof ke&&Se.context.submissionStatus==="unknown"&&(s.current={user:B,apiUrl:R,error:Se}),Se}const[z,oe]=L.intentIds[0].split("/"),de=parseInt(oe||"0",10),X=`${z}/${de}`;F("executing","Executing on chain..."),F("executing","Executing on chain...",{actionId:z,intentId:X,intentIndex:de,totalSteps:K.length,autoContinue:L.autoContinue===!0});const se=new Ir;se.setBaseUrl(R);let Pe,Ge=0;const Ee=new Map,De=async(Se,Ze=T,xe=!1)=>{const Ke=(ue,tt,vt)=>Ze?.({step:ue,message:tt,...vt});try{if((!xe||!Pe)&&(Pe=await Cm({actionId:z,intentIndex:de,intentId:X,totalSteps:Te,signal:Se,observeOnly:L.autoContinue===!0,startWithExecute:!xe,startStep:xe?Ge:0,executeAttempts:Ee,onStepUpdate:(ue,tt)=>{(tt.status==="success"||tt.status==="completed")&&(Ge=Math.max(Ge,ue+1))},relayer:L.autoContinue||xe?se:qe,...we?{delayBeforeSpicenetStepMs:0}:{},isSpicenetStep:ue=>Uo(K[ue]),beforeStep:async ue=>{if(L.autoContinue===!0||!we||!Uo(K[ue]))return;const tt=await md({deposits:ge,baseline:we,fetchEntries:()=>Ui(B),signal:Se});if(Se?.aborted)throw new ke("ABORT","Execution transaction aborted");if(!tt)throw new ke("POLLING_EXHAUSTED","Your deposit is still waiting for Spice credit. Check this transaction's status before trying again.",{actionId:z,intentId:X,stepId:ue})},maxExecuteAttemptsForStep:ue=>Uo(K[ue])?6:3,maxPolls:L.autoContinue?Number.POSITIVE_INFINITY:180,onStatusMessage:(ue,tt)=>{Ke("executing",ue,{txHash:tt,actionId:z,intentId:X,intentIndex:de,totalSteps:Te,autoContinue:L.autoContinue===!0})}})),b?.requireDestinationReceipt){const ue=[...K].reverse().find(tt=>!Uo(tt));if(!ue)throw new Error("The action has no destination transaction to verify.");await Ni(Ot(ue.chainId),Pe,Se)}return Ke("success","Transaction successful!",{txHash:Pe,actionId:z,intentId:X,intentIndex:de,totalSteps:Te,autoContinue:L.autoContinue===!0}),s.current?.resume===He&&(s.current=null),Pe||z}catch(ue){if(ue instanceof ke&&ue.code==="ON_CHAIN_REVERT"&&ue.context.status==="reverted"&&(ue.context.stepId===0||Te===1))throw s.current?.resume===He&&(s.current=null),ue;const tt=new ke(ue instanceof ke?ue.code:"RELAYER_STATUS_ERROR",ue instanceof ke&&ue.code==="ON_CHAIN_REVERT"?ue.message:`Your action was accepted, but its completion could not be confirmed. Check the original action before trying again. ${ue instanceof Error?ue.message:""}`.trim(),{...ue instanceof ke?ue.context:{},submissionStatus:"accepted",actionId:z,intentId:X,txHash:Pe,cause:ue});throw P===a.current&&(s.current={user:B,apiUrl:R,error:tt,resume:He}),tt}},He=async(Se,Ze,xe,Ke,ue,tt)=>{const vt=U(tt);if(M!==O(Se)||V.size!==vt.size||[...V].some(([it,st])=>vt.get(it)!==st)||!Q(v,Ze)||C!==xe)throw s.current.error;return De(Ke,ue,!0)};return await De(k,T)}catch(B){throw console.error("[Execution] Error:",B),F("error",B.message||"Transaction failed",{error:B.message,...B?.context?.submissionStatus==="unknown"?{submissionStatus:"unknown",...typeof B.context.idempotencyKey=="string"&&/^0x[0-9a-f]{64}$/i.test(B.context.idempotencyKey)?{idempotencyKey:B.context.idempotencyKey}:{},...typeof B.context.user=="string"&&/^0x[0-9a-f]{40}$/i.test(B.context.user)?{user:B.context.user}:{}}:{}}),B}finally{qi=!1}},[e,n,g,h]),I=ae(async(A,v,C,T)=>{if(!e&&(!T?.userOverride||T.signAuthorizationsForEstimate))throw new ke("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const k=T?.userOverride||e,b=T?.validateFeeCalls===!0&&T.feeExecutionMode==="user-transfer"&&qe.canValidateActionFees(),{actionOutputDeposit:S,batches:E}=kd(A,T);let F=E;const P=T?.feeExecutionMode==="user-transfer"&&!b?vs(F,k):F,B=T?.signAuthorizationsForEstimate?await g(P,k):void 0;let R=T?.useCustomTransfers;S&&(F=(await vd({chainBatches:A,user:k,token:S.token,grossAmount:S.amount,chainAuthorizations:B})).chainBatches,R=!0);const x=T?.feeExecutionMode==="user-transfer"&&!b?vs(F,k):F,O=Ss({user:k,chainBatches:x,tokenAddress:v,tokenTransferAmount:C,exp:Math.floor(Date.now()/1e3)+3600,signature:"0x00",chainAuthorizations:B,useCustomTransfers:R}),M=await(b?qe.validateActionFees(O,{signal:T?.signal}):qe.estimateActionFees(O,{signal:T?.signal}));return r.current=M,M},[e,g]);return{execute:y,estimate:I,lastFeeEstimate:r.current,hasEmbeddedWallet:t&&n,intentStatus:i,startStatusPolling:c,beginStatusTracking:l,applyStepUpdate:u,clearStatus:p}}function fn(e,t,n,o){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const r=10n**BigInt(t-n);return o==="ceil"?(e+r-1n)/r:e/r}function On(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(e,t)}function An(e,t,n){const o=fn(e,t,n,"floor");if(fn(o,n,t,"floor")!==e)throw new Error(`Use at most ${n} decimal places for this delivered token.`);return o}function Dm(e){return`0x77${e.slice(4)}`}function Sa({userAddress:e,destinationChainId:t,deliveryToken:n,deliveryAmount:o,withdrawalAmount:r,deliveryRecipient:a,deliveryTransfers:s,requestTimestampMs:i,expiresAt:c,metadata:l,requestNonce:u}){if(c!==void 0&&(!Number.isSafeInteger(c)||c<=0))throw new Error("Withdrawal expiry must be a positive Unix timestamp in seconds");const d=s?.length?s:[{token:n,recipient:a,amount:r??o}],p=d.reduce((y,I)=>y+I.amount,0n);if(p<=0n)return null;const w=i??Date.now(),f=BigInt(Math.floor(w/1e3)),g=e??a,h=Dm(cr(jo([{type:"address"},{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"},...u?[{type:"bytes32"}]:[]],[g,n,a,p,BigInt(t),BigInt(w),...u?[u]:[]])));return{chainId:nl,domain:"spicenet",tokenTransfers:[],calls:[{to:Yt,value:0n,data:Wt({abi:ss,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${t}`,idempotenceKey:h,nbf:0n,exp:c===void 0?f+3600n:BigInt(c),metadata:l??"{}",transfers:d.map(y=>({token:gn(y.token).toLowerCase(),to:gn(y.recipient).toLowerCase(),amount:y.amount}))}]})}]}}const zi=e=>{const[t,n]=q(!1),o=pn(on),{dark:r,dk:a}=cn();if(me(()=>{n(!0)},[]),!t)return m("div",{className:e.className,children:m("button",{disabled:!0,style:{padding:"12px 24px",fontSize:"16px",backgroundColor:r?a.hoverBg:"#ccc",color:r?a.textSecondary:"white",border:r?`1px solid ${a.buttonBorder}`:"none",borderRadius:"4px",cursor:"not-allowed"},children:"Loading..."})});if(!o){const s='ProviderLogin must be used within SpiceFlowProvider. Please wrap your app with <SpiceFlowProvider provider="privy">.';return m("div",{className:e.className,children:m("button",{onClick:()=>{e.onAuthError&&e.onAuthError(s)},style:{padding:"12px 24px",fontSize:"16px",backgroundColor:r?a.errorBg:"#dc2626",color:r?a.errorText:"white",border:r?`1px solid ${a.errorBorder}`:"none",borderRadius:"4px",cursor:"pointer"},children:"Provider Not Found"})})}return m(Rp,{...e})},Aa=({size:e=20,strokeWidth:t=2,color:n="currentColor",style:o})=>D("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:o,children:[m("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),m("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),Ea=(e,t,n,o)=>({width:e,height:e,fill:"none",className:t,"aria-hidden":n??!0,style:o}),Gr=({size:e=16,color:t="currentColor",strokeWidth:n=2,direction:o="down",className:r,style:a,"aria-hidden":s})=>m("svg",{...Ea(e,r,s,{transform:o==="up"?"rotate(180deg)":void 0,transition:"transform 0.3s ease",...a}),viewBox:"0 0 16 16",children:m("path",{d:"M4 6L8 10L12 6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),Mm=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:o,style:r,"aria-hidden":a})=>D("svg",{...Ea(e,o,a,r),viewBox:"0 0 24 24",children:[m("circle",{cx:"11",cy:"11",r:"8",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"}),m("path",{d:"m21 21-4.3-4.3",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})]}),Nm=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:o,style:r,"aria-hidden":a})=>m("svg",{...Ea(e,o,a,r),viewBox:"0 0 24 24",children:m("path",{d:"m6 9 6 6 6-6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),Pm=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:o,style:r,"aria-hidden":a})=>m("svg",{...Ea(e,o,a,r),viewBox:"0 0 24 24",children:m("path",{d:"m9 18 6-6-6-6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),Cd=({size:e=14,color:t="currentColor",strokeWidth:n=2,className:o,style:r,"aria-hidden":a})=>m("svg",{...Ea(e,o,a,r),viewBox:"0 0 16 16",children:m("path",{d:"M3 8L6.5 11.5L13 5",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),Sd=({isSuccess:e,type:t,chainName:n,explorerUrl:o,txHash:r,dark:a=!1,successBg:s="#d1fae5",successBorder:i="#6ee7b7",successText:c="#065f46",errorBg:l="#fee2e2",errorBorder:u="#fca5a5",errorText:d="#dc2626",textSecondary:p="#6b7280"})=>D("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px",borderRadius:"8px",backgroundColor:e?s:l,border:e?`1px solid ${i}`:`1px solid ${u}`},children:[D("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[m("div",{style:{width:"28px",height:"28px",borderRadius:"50%",backgroundColor:e?"#10b981":"#ef4444",display:"flex",alignItems:"center",justifyContent:"center"},children:e?m("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:m("path",{d:"M11.6667 3.5L5.25 9.91667L2.33333 7",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}):m("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:m("path",{d:"M10.5 3.5L3.5 10.5M3.5 3.5L10.5 10.5",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),D("div",{children:[m("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:ot.mono,letterSpacing:"0.5px",color:e?c:d},children:e?`${t.toUpperCase()} CONFIRMED`:`${t.toUpperCase()} FAILED`}),D("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:p},children:["on ",n]})]})]}),o&&r&&D("a",{href:`${o}/tx/${r}`,target:"_blank",rel:"noopener noreferrer",style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"13px",color:p,textDecoration:"none",whiteSpace:"nowrap"},children:["View on explorer",D("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:[m("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"}),m("path",{d:"M7.5 1.5H10.5V4.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),m("path",{d:"M5 7L10.5 1.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})]})]})]}),Ad=`
4
4
  @keyframes slideUp {
5
5
  from { transform: translateY(100%); }
6
6
  to { transform: translateY(0); }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spicenet-io/spiceflow-ui",
3
- "version": "4.22.1",
3
+ "version": "4.22.2",
4
4
  "description": "Spiceflow UI SDK",
5
5
  "type": "module",
6
6
  "workspaces": [
File without changes