@spicenet-io/spiceflow-ui 4.14.1 → 4.14.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{jsxs as C,jsx as u,Fragment as an}from"react/jsx-runtime";import{g as Ge,a as yt,S as Ne,b as ge,c as as,i as is,d as ba,e as Mt,f as Rc,E as Mc,C as ls,r as Wc,R as Nc,h as Pc,j as va,k as Lt,l as tr,u as Zn,m as Ca,n as gn,z as ao,o as Rn,p as Oe,q as Bt,s as nr,t as wo,v as ka,w as Ia,x as Mn,y as No,A as In,B as or,D as cs,F as ds,G as sr,H as Ln,I as us,J as Et,K as ps,L as fs,M as Uc,P as Lc,N as io,O as Sa,Q as Xn,T as zc,U as ms,V as hs,W as Aa,X as Hc,Y as Po,Z as qc,_ as Ea,$ as rr,a0 as Fa,a1 as lo,a2 as Vc,a3 as Qc,a4 as jc,a5 as Gc,a6 as Ta,a7 as Yc}from"./privy-CTIfxFeM.js";import{a8 as Qm,aa as jm,ab as Gm,ad as Ym,ac as Km,a9 as Zm}from"./privy-CTIfxFeM.js";import En,{useContext as Qt,useState as O,useMemo as ue,useEffect as ae,useCallback as te,useRef as _,useId as Ba,useLayoutEffect as Da,memo as yn}from"react";import{isNativeToken as be,uniV3QuoterV2Abi as Kc,uniV3SwapRouterAbi as Oa,applySlippage as Ra,NATIVE_TOKEN_ADDRESS as Ma,getTokenByAddress as Ft,areEquivalent as Zc,getTokensForChain as gs,getEscrowContractAddress as Jn,getEscrowContract as Uo,ZERO_ADDRESS as Tt,normalizeNativeTokenAddress as Ye,getChainMeta as Wa,getMainnetChains as Xc,getTestnetChains as Jc,TOKENS as Na,convertAmountBetweenDecimals as co,getChainIdsByNetwork as ys,hashChainBatches as $n,isSpicenetChainId as bo,getAccountNonce as $c,SPICE_GAS_FEE_RECIPIENT as nn,SPICE_PLATFORM_FEE_RECIPIENT as Fn,getEquivalenceGroup as _c,SPICENET_NATIVE_CHAIN_ID as Pa,spicenetAbi as ar,getEquivalentAddresses as ed,getTokenBySymbol as Ua}from"@spicenet-io/spiceflow-core";import{ZERO_ADDRESS as Jm,SPICENET_NATIVE_CHAIN_ID as $m,SPICE_COMBINED_FEE_RECIPIENT as _m,SPICE_GAS_FEE_RECIPIENT as eh,SPICE_PLATFORM_FEE_RECIPIENT as th,SPICE_SOLVER_ADDRESS as nh,applySlippage as oh,buildUniV3SwapCalls as sh,getChainIdsByNetwork as rh,getEscrowContractAddress as ah,isNativeToken as ih,isSpicenetChainId as lh,normalizeNativeTokenAddress as ch,spicenetAbi as dh,spicenetAbi as uh}from"@spicenet-io/spiceflow-core";import{useWalletClient as td,useAccount as ir,useDisconnect as La,useConnect as nd,useSwitchChain as za,useReconnect as od}from"wagmi";import{encodeFunctionData as xt,parseAbi as Tn,concatHex as sd,encodePacked as lr,erc20Abi as tt,decodeFunctionData as uo,encodeAbiParameters as zn,formatUnits as Fe,isAddress as fn,getAddress as zt,keccak256 as vo,createWalletClient as cr,custom as dr,parseUnits as mn,toHex as Ha,stringToHex as rd}from"viem";import{readContract as _n,getBalance as ur}from"viem/actions";import{useConnectWallet as qa,usePrivy as ad}from"@privy-io/react-auth";import pr,{createPortal as fr}from"react-dom";import"@tanstack/react-query";const id="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@100;200;300;400;500;600;700&display=swap",ld="spiceflow-ibm-plex-mono",cd="spiceflow-preconnect-googleapis",dd="spiceflow-preconnect-gstatic";function mr(e,t){if(document.getElementById(e))return;const n=t();n.id=e,document.head.appendChild(n)}function ud(){typeof document>"u"||(mr(cd,()=>{const e=document.createElement("link");return e.rel="preconnect",e.href="https://fonts.googleapis.com",e}),mr(dd,()=>{const e=document.createElement("link");return e.rel="preconnect",e.href="https://fonts.gstatic.com",e.crossOrigin="",e}),mr(ld,()=>{const e=document.createElement("link");return e.rel="stylesheet",e.href=id,e}))}const pd={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",8453:"0x4200000000000000000000000000000000000006",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",84532:"0x4200000000000000000000000000000000000006"},Va=Tn(["function deposit() payable","function withdraw(uint256 wad)"]);function hr(e){return Ge(e)?.wrappedNativeTokenAddress??pd[e]}const gr=(e,t)=>({to:e,value:t,data:xt({abi:Va,functionName:"deposit"})}),yr=(e,t)=>({to:e,value:0n,data:xt({abi:Va,functionName:"withdraw",args:[t]})});function xr(e,t,n){const o=be(t),s=be(n);if(!o&&!s)return null;const r=hr(e);return r?{weth:r,wrapIn:o,unwrapOut:s}:null}function Qa(e,t,n,o){const s=xr(e,t,n);return!s||o<=0n?null:s.wrapIn&&!s.unwrapOut&&n.toLowerCase()===s.weth.toLowerCase()?[gr(s.weth,o)]:s.unwrapOut&&!s.wrapIn&&t.toLowerCase()===s.weth.toLowerCase()?[yr(s.weth,o)]:null}function fd(e){return{...e,resolve:async(t,n,o,s)=>{const r=Qa(n,t.tokenIn,t.tokenOut,t.amountIn);if(r)return{venue:"native-wrap",amountOut:t.amountIn,amountOutMinimum:t.amountIn,calls:r};const a=await e.resolve(t,n,o,s);if(a)return a;const i=xr(n,t.tokenIn,t.tokenOut);if(!i)return null;const l=await e.resolve({...t,tokenIn:i.wrapIn?i.weth:t.tokenIn,tokenOut:i.unwrapOut?i.weth:t.tokenOut},n,o,s);return l?{...l,calls:[...i.wrapIn?[gr(i.weth,t.amountIn)]:[],...l.calls,...i.unwrapOut?[yr(i.weth,l.amountOutMinimum)]:[]]}:null}}}function md(e){return{...e,resolve:async(t,n,o)=>{const s=Qa(n,t.tokenIn,t.tokenOut,t.amountOut);if(s)return{venue:"native-wrap",amountIn:t.amountOut,amountInMax:t.amountOut,amountOut:t.amountOut,calls:s};const r=await e.resolve(t,n,o);if(r)return r;const a=xr(n,t.tokenIn,t.tokenOut);if(!a)return null;const i=await e.resolve({...t,tokenIn:a.wrapIn?a.weth:t.tokenIn,tokenOut:a.unwrapOut?a.weth:t.tokenOut},n,o);return i?{...i,calls:[...a.wrapIn?[gr(a.weth,i.amountInMax)]:[],...i.calls,...a.unwrapOut?[yr(a.weth,i.amountOut)]:[]]}:null}}}const ja=[100,500,3e3,1e4];function xs(e,t,n,o,s){const r=[];for(const a of n){const i=typeof a=="object"&&!Array.isArray(a)?a:void 0,l=i?i.tokens:Array.isArray(a)?a:[a];if(!l.length||l.length>2)throw new Error("A v3 route must have one or two intermediate tokens");const c=[e,...l,t];if(i&&(i.feeTiers.length!==c.length-1||i.feeTiers.some(p=>!p.length)))throw new Error("A v3 route needs fee tiers for every pool");if(new Set(c.map(p=>p.toLowerCase())).size!==c.length)continue;const d=(p,f)=>{if(p===c.length){r.push(s==="in"?f:Ga(f));return}for(const h of i?.feeTiers[p-1]??o)d(p+1,sd([f,lr(["uint24","address"],[h,c[p]])]))};d(1,c[0])}return[...new Set(r)]}function Ga(e){const t=e.slice(2),n=[];for(let o=0;o<t.length;){const s=n.length%2===0?40:6;n.push(t.slice(o,o+s)),o+=s}return`0x${n.reverse().join("")}`}const hd=Tn(["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)"]),gd=Tn(["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)"]),yd=1800;function Ya(e){const{config:t,route:n,tokenIn:o,tokenOut:s,recipient:r,amountOut:a}=e,i=e.amountInMaximum,l=e.routerHasDeadline?gd:hd,c=e.routerHasDeadline?{deadline:BigInt(Math.floor(Date.now()/1e3)+yd)}:{},d=n.path?xt({abi:l,functionName:"exactOutput",args:[{path:n.path,recipient:r,...c,amountOut:a,amountInMaximum:i}]}):xt({abi:l,functionName:"exactOutputSingle",args:[{tokenIn:o,tokenOut:s,fee:n.fee,recipient:r,...c,amountOut:a,amountInMaximum:i,sqrtPriceLimitX96:0n}]});return{to:t.swapRouter,value:0n,data:d}}const xd=Tn(["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 Lo(e,t,n,o,s){const r=yt(e),{result:a}=await r.simulateContract({address:t.quoterV2,abi:xd,functionName:s==="in"?"quoteExactInput":"quoteExactOutput",args:[n,o]}),[i,,,l]=a;if(i<=0n)throw new Error("No liquidity along this path.");return{amount:i,gasEstimate:l}}async function wd(e){const{tokenIn:t,tokenOut:n,amountIn:o,fee:s,chainId:r,config:a}=e;if(o<=0n)throw new Error("amountIn must be greater than 0");const i=(await yt(r).simulateContract({address:a.quoterV2,abi:Kc,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:o,fee:s,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 Ka(e){const t=e.feeTiers??ja,n=xs(e.tokenIn,e.tokenOut,e.hubs??[],t,"in"),o=await Promise.allSettled([...t.map(async r=>({...await wd({...e,fee:r}),fee:r})),...n.map(async r=>{const a=await Lo(e.chainId,e.config,r,e.amountIn,"in");return{amountOut:a.amount,sqrtPriceX96After:0n,gasEstimate:a.gasEstimate,fee:0,path:r}})]);let s=null;for(const r of o)r.status==="fulfilled"&&(!s||r.value.amountOut>s.amountOut)&&(s=r.value);if(!s)throw new Error("No liquidity found for this pair on any fee tier.");return s}const bd=[{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 vd(e){const{tokenIn:t,tokenOut:n,amountOut:o,fee:s,chainId:r,config:a}=e;if(o<=0n)throw new Error("amountOut must be greater than 0");const i=(await yt(r).simulateContract({address:a.quoterV2,abi:bd,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:o,fee:s,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 Za(e){const t=e.feeTiers??ja,n=xs(e.tokenIn,e.tokenOut,e.hubs??[],t,"out"),o=await Promise.allSettled([...t.map(async r=>({...await vd({...e,fee:r}),fee:r})),...n.map(async r=>{const a=await Lo(e.chainId,e.config,r,e.amountOut,"out");return{amountIn:a.amount,sqrtPriceX96After:0n,gasEstimate:a.gasEstimate,fee:0,path:r}})]);let s=null;for(const r of o)r.status==="fulfilled"&&(!s||r.value.amountIn<s.amountIn)&&(s=r.value);if(!s)throw new Error("No liquidity found for this pair on any fee tier.");return s}function Cd(e){return e.type==="swap"}const zo=.02,kd=[1,8453,42161,10,137,43114,56],Id="https://api.1inch.dev/swap/v6.0";function wr(e,t){return Ra(e,t)}function Sd(e){const t=e?.baseUrl??Id;return{name:"1inch",chainIds:e?.chainIds??kd,resolve:async(n,o,s)=>{const r=n.maxSlippage??zo,a=r*100,i=be(n.tokenIn)?Ma:n.tokenIn,l=be(n.tokenOut)?Ma:n.tokenOut,c=be(n.tokenIn);try{const d=new URL(`${t}/${o}/swap`);d.searchParams.set("src",i),d.searchParams.set("dst",l),d.searchParams.set("amount",n.amountIn.toString()),d.searchParams.set("from",s),d.searchParams.set("slippage",a.toString()),d.searchParams.set("disableEstimate","true"),d.searchParams.set("allowPartialFill","false");const p={Accept:"application/json"};e?.apiKey&&(p.Authorization=`Bearer ${e.apiKey}`);const f=await fetch(d.toString(),{headers:p});if(!f.ok)throw new Ne("VENUE_API_ERROR",`[1inchVenue] API returned ${f.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 ${f.status}`});const h=await f.json();if(!h.dstAmount||!h.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const m=BigInt(h.dstAmount);if(m<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const g=wr(m,r),y=[];return h.tx.to&&!c&&y.push({to:n.tokenIn,value:0n,data:xt({abi:tt,functionName:"approve",args:[h.tx.to,n.amountIn]})}),y.push({to:h.tx.to,value:BigInt(h.tx.value||"0"),data:h.tx.data}),{venue:"1inch",amountOut:m,amountOutMinimum:g,calls:y}}catch(d){if(d instanceof Ne)throw d;const p=d instanceof Error?d.message:String(d);throw new Ne("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}: ${p}`,{venue:"1inch",chainId:o,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:p})}}}}const Xa=[4114,5115],br={name:"Satsuma",swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},Ja={name:"Uniswap v3",swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x4200000000000000000000000000000000000006","0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]},$a={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[1],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2","0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"]},_a={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[42161],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x82aF49447D8a07e3bd95BD0d56f35241523fBab1","0xaf88d065e77c8cC2239327C5EDb3A432268e5831"]},Ad={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[137],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270","0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"]},Ed={name:"Uniswap v3",swapRouter:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",quoterV2:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",chainIds:[56],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c","0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d"]},Fd={name:"Uniswap v3",swapRouter:"0xfe31f71c1b106eac32f1a19239c9a9a72ddfb900",quoterV2:"0x661e93cca42afacb172121ef892830ca3b70f08d",chainIds:[143],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A","0x754704Bc059F8C67012fEd69BC8A327a5aafb603"]},ei={name:"Uniswap v3",swapRouter:"0xcaf681a66d020601342297493863e78c959e5cb2",quoterV2:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",chainIds:[4663],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73","0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"]},ti={name:"SushiSwap",swapRouter:"0x1e406484F1F204b23cE84B9901C0171a738fd406",quoterV2:"0x3E290e5E01818002A0b672148BdC7514D861C7B3",chainIds:[4663],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73","0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"],routerHasDeadline:!0},ni=Tn(["function exactInput((bytes path, address recipient, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),oi=Tn(["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)"]),Td=Tn(["function exactInput((bytes path, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),Bd=Tn(["function exactOutput((bytes path, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),vr=1800,si=[1,50,100,200,2e3],Cr={name:"Aerodrome",swapRouter:"0xcbBb8035cAc7D4B3Ca7aBb74cF7BdF900215Ce0D",quoterV2:"0x3d4C22254F86f64B7eC90ab8F7aeC1FBFD271c6C",chainIds:[8453],hubCurrencies:["0x4200000000000000000000000000000000000006","0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]};function kr(e){const t=e.name??"Aerodrome",n=e.chainIds??[8453],o=e.tickSpacings??si;return{name:t,chainIds:n,resolve:async(s,r,a)=>{if(be(s.tokenIn)||be(s.tokenOut))return null;const i=s.maxSlippage??zo,l=[...o.map(y=>lr(["address","uint24","address"],[s.tokenIn,y,s.tokenOut])),...xs(s.tokenIn,s.tokenOut,e.hubCurrencies??[],o,"in")],c={quoterV2:e.quoterV2},d=await Promise.allSettled(l.map(async y=>({path:y,amountOut:(await Lo(r,c,y,s.amountIn,"in")).amount})));let p=null;for(const y of d)y.status==="fulfilled"&&(!p||y.value.amountOut>p.amountOut)&&(p=y.value);if(!p)return console.warn(`[AerodromeVenue] No viable route for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${r}.`),null;const f=wr(p.amountOut,i),h=BigInt(Math.floor(Date.now()/1e3)+vr),m=xt({abi:Td,functionName:"exactInput",args:[{path:p.path,recipient:a,deadline:h,amountIn:s.amountIn,amountOutMinimum:f}]}),g=[{to:s.tokenIn,value:0n,data:xt({abi:tt,functionName:"approve",args:[e.swapRouter,s.amountIn]})},{to:e.swapRouter,value:0n,data:m}];return{venue:t,amountOut:p.amountOut,amountOutMinimum:f,calls:g}}}}function ri(e){const t=e.name??"Aerodrome",n=e.chainIds??[8453],o=e.tickSpacings??si;return{name:t,chainIds:n,resolve:async(s,r,a)=>{if(be(s.tokenIn)||be(s.tokenOut))return null;const i=s.maxSlippage??zo,l=[...o.map(g=>lr(["address","uint24","address"],[s.tokenOut,g,s.tokenIn])),...xs(s.tokenIn,s.tokenOut,e.hubCurrencies??[],o,"out")],c={quoterV2:e.quoterV2},d=await Promise.allSettled(l.map(async g=>({path:g,amountIn:(await Lo(r,c,g,s.amountOut,"out")).amount})));let p=null;for(const g of d)g.status==="fulfilled"&&(!p||g.value.amountIn<p.amountIn)&&(p=g.value);if(!p)return console.warn(`[AerodromeExactOutputVenue] No viable route for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${r}.`),null;const f=BigInt(Math.round(i*1e4)),h=p.amountIn+p.amountIn*f/10000n,m=BigInt(Math.floor(Date.now()/1e3)+vr);return{venue:t,amountIn:p.amountIn,amountInMax:h,amountOut:s.amountOut,calls:[{to:e.swapRouter,value:0n,data:xt({abi:Bd,functionName:"exactOutput",args:[{path:p.path,recipient:a,deadline:m,amountOut:s.amountOut,amountInMaximum:h}]})}]}}}}function Ho(e){const t=e.name??"Uniswap v3",n=e.chainIds??Xa;return{name:t,chainIds:n,resolve:async(o,s,r,a)=>{if(be(o.tokenIn)||be(o.tokenOut))return null;const i=o.maxSlippage??zo;let l;try{let m;if(a){if(a.venue!==t)return null;const g=a.calls.find(w=>w.to.toLowerCase()===e.swapRouter.toLowerCase());if(!g)return null;const y=uo({abi:e.routerHasDeadline?oi:[...ni,...Oa],data:g.data});if(y.functionName==="exactInput"){const{path:w}=y.args[0];if(w.slice(0,42).toLowerCase()!==o.tokenIn.toLowerCase()||`0x${w.slice(-40)}`.toLowerCase()!==o.tokenOut.toLowerCase())return null;m={path:w,fee:0}}else if(y.functionName==="exactInputSingle"){const{tokenIn:w,tokenOut:x,fee:v}=y.args[0];if(w.toLowerCase()!==o.tokenIn.toLowerCase()||x.toLowerCase()!==o.tokenOut.toLowerCase())return null;m={fee:v}}else return null}l=m?.path?{...m,amountOut:(await Lo(s,e,m.path,o.amountIn,"in")).amount}:await Ka({tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountIn:o.amountIn,chainId:s,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:m?[m.fee]:e.feeTiers,hubs:m?[]:[...e.hubCurrencies??[],...e.hubPaths??[]]})}catch{return console.warn(`[UniV3Venue] No viable route for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${s}.`),null}const c=wr(l.amountOut,i),d=e.routerHasDeadline?{deadline:BigInt(Math.floor(Date.now()/1e3)+vr)}:{},p=e.routerHasDeadline?oi:l.path?ni:Oa,f=l.path?xt({abi:p,functionName:"exactInput",args:[{path:l.path,recipient:r,...d,amountIn:o.amountIn,amountOutMinimum:c}]}):xt({abi:p,functionName:"exactInputSingle",args:[{tokenIn:o.tokenIn,tokenOut:o.tokenOut,fee:l.fee,recipient:r,...d,amountIn:o.amountIn,amountOutMinimum:c,sqrtPriceLimitX96:0n}]}),h=[{to:o.tokenIn,value:0n,data:xt({abi:tt,functionName:"approve",args:[e.swapRouter,o.amountIn]})},{to:e.swapRouter,value:0n,data:f}];return{venue:t,amountOut:l.amountOut,amountOutMinimum:c,calls:h}}}}function Ir(e){const t=e.name??"Uniswap v3",n=e.chainIds??Xa;return{name:t,chainIds:n,resolve:async(o,s,r)=>{if(be(o.tokenIn)||be(o.tokenOut))return null;const a=o.maxSlippage??zo;let i;try{i=await Za({tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountOut:o.amountOut,chainId:s,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers,hubs:[...e.hubCurrencies??[],...e.hubPaths??[]]})}catch{return null}const l=BigInt(Math.round(a*1e4)),c=i.amountIn+i.amountIn*l/10000n;return{venue:t,amountIn:i.amountIn,amountInMax:c,amountOut:o.amountOut,calls:[Ya({config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},routerHasDeadline:e.routerHasDeadline,route:i,tokenIn:o.tokenIn,tokenOut:o.tokenOut,recipient:r,amountOut:o.amountOut,amountInMaximum:c})]}}}}function ai(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(Ho(e.satsuma)),e?.aerodrome!==!1&&t.push(kr(e?.aerodrome??Cr)),t.push(Sd(e?.oneInch));const n=t.map(fd);function o(a){return n.find(i=>i.chainIds.includes(a))}async function s(a,i,l,c){const d=n.filter(m=>m.chainIds.includes(i));if(d.length===0)throw new Ne("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${i}. Cannot resolve swap ${a.tokenIn} \u2192 ${a.tokenOut}.`,{chainId:i,tokenIn:a.tokenIn,tokenOut:a.tokenOut,amountIn:a.amountIn.toString()});const p=await Promise.allSettled(d.map(m=>m.resolve(a,i,l,c)));let f=null;for(const m of p)c&&m.status==="fulfilled"&&m.value&&(m.value.venue!==c.venue||m.value.calls.length!==c.calls.length||m.value.calls.some((g,y)=>g.to.toLowerCase()!==c.calls[y].to.toLowerCase()||g.data.slice(0,10)!==c.calls[y].data.slice(0,10)))||m.status==="fulfilled"&&m.value&&(!f||m.value.amountOut>f.amountOut)&&(f=m.value);if(f)return f;const h=p.find(m=>m.status==="rejected");if(h)throw h.reason;return null}async function r(a,i,l){const c=[],d=[];for(const p of a){if(!Cd(p)){c.push(p);continue}const f=await s(p,i,l);if(!f)throw new Ne("NO_LIQUIDITY",`No venue returned a quote for ${p.tokenIn} \u2192 ${p.tokenOut} on chain ${i}.`,{chainId:i,tokenIn:p.tokenIn,tokenOut:p.tokenOut,amountIn:p.amountIn.toString()});c.push(...f.calls),d.push(f)}return{calls:c,resolvedSwaps:d}}return{resolveSwapIntents:r,resolveSwap:s,getVenueForChain:o,venues:t}}const Wn="0x0000000000000000000000000000000000000000",Sr=[{fee:100,tickSpacing:1},{fee:500,tickSpacing:10},{fee:3e3,tickSpacing:60},{fee:1e4,tickSpacing:200}],ii=Wn,li=.02,Dd=1800,ci={name:"Uniswap v4",quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",universalRouter:"0x6ff5693b99212da76ad316178a184ab56d299b43",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",chainIds:[8453],hubCurrencies:["0x4200000000000000000000000000000000000006",Wn,"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]},di={name:"Uniswap v4",quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",universalRouter:"0x8876789976decbfcbbbe364623c63652db8c0904",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",routerHasHopPrice:!0,chainIds:[4663],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73",Wn,"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"]},ui=Tn(["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)"]),Od=Tn(["function approve(address token, address spender, uint160 amount, uint48 expiration)"]),Rd=Tn(["function execute(bytes commands, bytes[] inputs, uint256 deadline) payable"]),pi="0x10",Md="04",Wd="06",Nd="07",Pd="08",Ud="09",ws="0c",bs="0e",Ld=[{name:"currency0",type:"address"},{name:"currency1",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"}],zd=[{name:"intermediateCurrency",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"},{name:"hookData",type:"bytes"}],Hn=(e,t)=>e.toLowerCase()===t.toLowerCase();function vs(e){return be(e)?Wn:e}function Hd(e,t){return e.toLowerCase()<t.toLowerCase()?[e,t]:[t,e]}function fi(e,t,n,o,s){const r=[],[a,i]=Hd(e,t);for(const{fee:c,tickSpacing:d}of Sr)r.push({kind:"single",poolKey:{currency0:a,currency1:i,fee:c,tickSpacing:d,hooks:ii},zeroForOne:Hn(e,a)});const l=(c,d)=>!!s&&(Hn(c,Wn)&&Hn(d,s)||Hn(c,s)&&Hn(d,Wn));for(const c of n)if(!(Hn(c,e)||Hn(c,t))&&!(l(c,e)||l(c,t)))for(const d of Sr)for(const p of Sr){const f=(h,m)=>({intermediateCurrency:h,fee:m.fee,tickSpacing:m.tickSpacing,hooks:ii,hookData:"0x"});r.push({kind:"multi",path:o==="in"?[f(c,d),f(t,p)]:[f(e,d),f(c,p)]})}return r}async function mi(e,t,n,o,s,r){const a=yt(e),i=(await Promise.allSettled(n.map(async l=>{const{result:c}=l.kind==="single"?await a.simulateContract({address:t.quoter,abi:ui,functionName:r==="in"?"quoteExactInputSingle":"quoteExactOutputSingle",args:[{poolKey:l.poolKey,zeroForOne:l.zeroForOne,exactAmount:s,hookData:"0x"}]}):await a.simulateContract({address:t.quoter,abi:ui,functionName:r==="in"?"quoteExactInput":"quoteExactOutput",args:[{exactCurrency:o,path:l.path,exactAmount:s}]}),d=c[0];if(d<=0n)throw new Error("zero quote");return{candidate:l,amount:d}}))).filter(l=>l.status==="fulfilled").map(l=>l.value);return i.length===0?null:(i.sort((l,c)=>l.amount<c.amount?-1:l.amount>c.amount?1:0),r==="in"?i[i.length-1]:i[0])}function hi(e){const{candidate:t,direction:n,currencyIn:o,currencyOut:s,recipient:r,exactAmount:a,limitAmount:i,deadline:l,routerHasHopPrice:c,sweepNativeTo:d}=e;let p,f;t.kind==="single"?(p=n==="in"?`0x${Wd}${ws}${bs}`:`0x${Pd}${ws}${bs}`,f=zn([{type:"tuple",components:[{name:"poolKey",type:"tuple",components:Ld},{name:"zeroForOne",type:"bool"},{name:n==="in"?"amountIn":"amountOut",type:"uint128"},{name:n==="in"?"amountOutMinimum":"amountInMaximum",type:"uint128"},...c?[{name:"minHopPriceX36",type:"uint256"}]:[],{name:"hookData",type:"bytes"}]}],[{poolKey:t.poolKey,zeroForOne:t.zeroForOne,[n==="in"?"amountIn":"amountOut"]:a,[n==="in"?"amountOutMinimum":"amountInMaximum"]:i,...c?{minHopPriceX36:0n}:{},hookData:"0x"}])):(p=n==="in"?`0x${Nd}${ws}${bs}`:`0x${Ud}${ws}${bs}`,f=zn([{type:"tuple",components:[{name:n==="in"?"currencyIn":"currencyOut",type:"address"},{name:"path",type:"tuple[]",components:zd},...c?[{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:s,path:t.path,...c?{minHopPriceX36:[]}:{},[n==="in"?"amountIn":"amountOut"]:a,[n==="in"?"amountOutMinimum":"amountInMaximum"]:i}]));const h=zn([{type:"address"},{type:"uint256"}],[o,n==="in"?a:i]),m=zn([{type:"address"},{type:"address"},{type:"uint256"}],[s,r,0n]),g=zn([{type:"bytes"},{type:"bytes[]"}],[p,[f,h,m]]),y=d?`${pi}${Md}`:pi,w=d?[g,zn([{type:"address"},{type:"address"},{type:"uint256"}],[Wn,d,0n])]:[g];return xt({abi:Rd,functionName:"execute",args:[y,w,l]})}function gi(){return BigInt(Math.floor(Date.now()/1e3)+Dd)}function yi(e,t,n,o){return{to:e.permit2,value:0n,data:xt({abi:Od,functionName:"approve",args:[t,e.universalRouter,n,Number(o)]})}}function xi(e){const t=e.name??"Uniswap v4",n=e.v3?Ho({...e.v3,chainIds:e.chainIds}):null;return{name:t,chainIds:e.chainIds,resolve:async(o,s,r)=>{const a=o.maxSlippage??li,i=vs(o.tokenIn),l=vs(o.tokenOut),c=be(o.tokenIn),d=e.hubCurrencies??[Wn];let p=null;if(!Hn(i,l)&&o.amountIn>0n){const f=await mi(s,e,fi(i,l,d,"in",hr(s)),i,o.amountIn,"in").catch(()=>null);if(f){const h=Ra(f.amount,a),m=gi(),g=[];c||(g.push({to:o.tokenIn,value:0n,data:xt({abi:tt,functionName:"approve",args:[e.permit2,o.amountIn]})}),g.push(yi(e,o.tokenIn,o.amountIn,m))),g.push({to:e.universalRouter,value:c?o.amountIn:0n,data:hi({candidate:f.candidate,direction:"in",currencyIn:i,currencyOut:l,recipient:r,exactAmount:o.amountIn,limitAmount:h,deadline:m,routerHasHopPrice:e.routerHasHopPrice})}),p={venue:t,amountOut:f.amount,amountOutMinimum:h,calls:g}}}return!p&&n?n.resolve(o,s,r):p}}}function wi(e){const t=e.name??"Uniswap v4";return{name:t,chainIds:e.chainIds,resolve:async(n,o,s)=>{const r=be(n.tokenIn),a=vs(n.tokenIn),i=vs(n.tokenOut);if(Hn(a,i)||n.amountOut<=0n)return null;const l=n.maxSlippage??li,c=e.hubCurrencies??[Wn],d=await mi(o,e,fi(a,i,c,"out",hr(o)),i,n.amountOut,"out").catch(()=>null);if(!d)return null;const p=BigInt(Math.round(l*1e4)),f=d.amount+d.amount*p/10000n,h=gi();return{venue:t,amountIn:d.amount,amountInMax:f,amountOut:n.amountOut,calls:[...r?[]:[yi(e,n.tokenIn,f,h)],{to:e.universalRouter,value:r?f:0n,data:hi({candidate:d.candidate,direction:"out",currencyIn:a,currencyOut:i,recipient:s,exactAmount:n.amountOut,limitAmount:f,deadline:h,routerHasHopPrice:e.routerHasHopPrice,sweepNativeTo:r?s:void 0})}]}}}}const Ar=[{...br,protocol:"uniswap-v3",chainId:4114},{...br,protocol:"uniswap-v3",chainId:5115},{...Ja,protocol:"uniswap-v3",chainId:8453},{...$a,protocol:"uniswap-v3",chainId:1},{..._a,protocol:"uniswap-v3",chainId:42161},{...Ad,protocol:"uniswap-v3",chainId:137},{...Ed,protocol:"uniswap-v3",chainId:56},{...Fd,protocol:"uniswap-v3",chainId:143},{...ei,protocol:"uniswap-v3",chainId:4663},{...ti,protocol:"uniswap-v3",chainId:4663},{...ci,protocol:"uniswap-v4",chainId:8453},{...di,protocol:"uniswap-v4",chainId:4663},{...Cr,protocol:"aerodrome-slipstream",chainId:8453}];function Co(e){const t=e?.includeDefaults===!1?e.venues??[]:[...Ar,...e?.venues??[]],n=[],o=[];for(const s of t){const r=[s.chainId];switch(s.protocol){case"uniswap-v3":{const a={...s,chainIds:r};n.push(Ho(a)),o.push(Ir(a));break}case"uniswap-v4":{const a={...s,chainIds:r};n.push(xi(a)),o.push(wi(a));break}case"aerodrome-slipstream":{const a={...s,chainIds:r};n.push(kr(a)),o.push(ri(a));break}default:{const a=s;throw new Ne("INVALID_PARAMS",`Unsupported liquidity venue protocol: ${a.protocol}`,{protocol:a.protocol})}}}return{input:n,output:o}}const Er=new Set(["WBTC","CBTC"]),bi=new Set(["btc","wbtc","wcbtc","cbtc"]);function vi(e,t){return!e||!t?!1:e===t?!0:Er.has(e)&&Er.has(t)}function qn(e){const[t,n,o]=e.split(":");if(t!=="evm"||!n||!o)return null;const s=Number(n);if(!Number.isFinite(s))return null;const r=o.startsWith("0x")?o.toLowerCase():`0x${o.toLowerCase()}`;return{chainId:s,address:r}}function Cs(e){return(e??"").trim().replace(/^test\s+/i,"").replace(/^spice/i,"").toLowerCase().replace(/[^a-z0-9]/g,"")}function qd(e){return new Set([e.receiptTokenName,e.displaySymbol,e.symbol,e.displayName,e.name].map(Cs).filter(Boolean))}function Vd(e,t){const n=qd(e),o=[t.symbol,t.name,t.equivalenceGroup].map(Cs);if(o.some(a=>a&&n.has(a)))return!0;const s=[...n].some(a=>bi.has(a)),r=o.some(a=>bi.has(a))||Er.has(t.equivalenceGroup??"");return s&&r}function Ci(e,t,n){const o=new Set(t.map(Cs).filter(Boolean)),s=r=>{if(n&&ge(r.address,n))return 0;const a=[r.symbol,r.name,r.equivalenceGroup].map(Cs).findIndex(i=>i&&o.has(i));return a===-1?4:a+1};return[...e].sort((r,a)=>{const i=s(r)-s(a);return i!==0?i:r.address.toLowerCase().localeCompare(a.address.toLowerCase())})}function ko(e,t){const n=e.chainTokens?Object.keys(e.chainTokens):[],o=[];for(const s of n){const r=qn(s);if(!r||r.chainId!==t)continue;const a=r.address,i=be(a)?Ge(t)?.nativeCurrency:void 0,l=Ft(a,t)??(i?{...i}:void 0);l&&(!Fr(e,a,t)&&!(e.isUniversal&&Vd(e,l))||o.some(c=>ge(c,a))||o.push(a))}return Ci(o.map(s=>{const r=Ft(s,t);return{address:s,symbol:r?.symbol,name:r?.name,equivalenceGroup:r?.equivalenceGroup}}),[e.receiptTokenName,e.displaySymbol,e.symbol,e.displayName,e.name],e.chainId===t&&!e.isUniversal?e.address:void 0).map(s=>s.address)}function Fr(e,t,n){return e.chainId===n&&ge(e.address,t)?!0:qo(e.address,e.chainId,t,n)}async function Qd(e,t){const n=yt(e),o=Jn(e);return be(t)?n.getBalance({address:o}):await n.readContract({address:t,abi:tt,functionName:"balanceOf",args:[o]})}function Tr(e,t,n){const o=gs(n),s=o.find(a=>ge(a.address,e));if(s&&(t===n||!be(e)))return s;const r=Ft(e,t);if(r)return Ci(o.filter(a=>vi(a.equivalenceGroup,r.equivalenceGroup)),[r.symbol,r.name,r.equivalenceGroup])[0]}function ks(e){return e.equivalenceGroup==="USDC"&&e.symbol.toUpperCase()!=="USDT"}function ki(e){const t=Uo(e);if(!t||t===Tt)return;const n=gs(e).filter(ks);return n.find(o=>o.symbol.toUpperCase()==="USDC")??n[0]}function Br(e,t){if(e.chainId===t)return null;const n=Uo(e.chainId),o=Uo(t);if(!n||n===Tt||!o||o===Tt)return null;const s=!e.isNative&&!be(e.address)?Ft(e.address,e.chainId):void 0,r=s&&ks(s)?Tr(e.address,e.chainId,t):void 0,a=r?s:ki(e.chainId),i=r??ki(t);if(!a||!i)return null;const l=c=>({address:c.address,symbol:c.symbol,decimals:c.decimals,chainId:c.chainId});return{source:l(a),destination:l(i)}}function jd(e,t){return!!Br(e,t)}function Sn(e,t){if(e.chainId===t)return e.address;const n=Tr(e.address,e.chainId,t);return n?n.address:null}async function eo(e,t,n,o){const s=Ft(t,n);return s?s.decimals:e?.chainId===n&&ge(e.address,t)&&!e.isUniversal?e.decimals:o?.chainId===n&&ge(o.address,t)?o.decimals:as(n,t)}async function Ii(e,t,n={}){const o=Sn(e,t),s=ko(e,t);if(s.length===0)return o;if(s.length===1)return s[0];const r=n.requiredAmount??0n,a=i=>{const l=s.map(c=>({candidate:c,balance:i.get(be(c)?"native":c.toLowerCase())??0n})).filter(c=>c.balance>0n).sort((c,d)=>c.balance===d.balance?0:c.balance>d.balance?-1:1);return l.length===0?null:((r>0n?l.find(c=>c.balance>=r):l[0])??l[0]).candidate};try{const i=await Promise.all(s.map(async d=>({key:be(d)?"native":d.toLowerCase(),value:await Qd(t,d)}))),l=new Map(i.map(({key:d,value:p})=>[d,p])),c=a(l);if(c)return c}catch{}return o}function qo(e,t,n,o){const s=Ft(e,t),r=Ft(n,o);return s&&r?vi(s.equivalenceGroup,r.equivalenceGroup):Zc(e,n)}function Is(e,t){return qo(e.address,e.chainId,t.address,t.chainId)}const Si=.01;function Ai(e,t=!1){const n=Number.isFinite(e.balanceUsd)&&e.balanceUsd>0;return e.isDiscovered?n&&e.balanceUsd>=Si:!t||!n||e.balanceUsd>=Si}function Ss(e,t=!1){return!!e&&e._source==="wallet"&&(e.location==="external"||e._fundingWallet==="external"||!e.location&&!e._fundingWallet&&t)}function nt(e){return e.positionId??`${e.owner?.toLowerCase()??""}:${e.location??e._source??""}:${e.chainId}:${e.receiptTokenId??Ye(e.address).toLowerCase()}`}function Ei(e,t){if(!t?.length||e.symbol!==void 0&&is({...e,symbol:e.symbol},t))return!0;const n=o=>t.some(s=>ge(Ye(s),Ye(o)));return n(e.address)||Object.keys(e.chainTokens??{}).some(o=>{const s=qn(o);return s?n(s.address):!1})}function po(e,t,n,o,s,r){const a=(g,y=!1)=>({eligible:!1,reason:g,policyExcluded:y}),i=e._source==="wallet"||e.location==="external"||e.location==="embedded",l=t==="spend-source"&&i&&!!o&&e.chainId===o.chainId&&ge(Ye(e.address),Ye(o.address));if(n.isWhitelistGateActive||!l&&!is(e,n.allowedTokens))return a("Asset excluded by client policy",!0);if(t!=="withdraw-destination"&&!l&&!Ai(e))return a("Asset is unpriced or below the minimum value",!0);if(t==="holding")return{eligible:!0,reason:null};if(e.balanceError)return a(e.balanceError);if(!l&&!Ei(e,s))return a("Asset excluded by action policy",!0);const c=new Set(o?[o.chainId]:[]);e._source!=="spice"&&e.location!=="rollup"&&c.add(e.chainId);for(const g of c)if(!ba(g,n.rpcOverrides)?.trim())return a(`Configure SpiceFlowProvider rpcOverrides[${g}] before using this asset.`);if(r?.requiresEscrow){const g=Ft(e.address,e.chainId);if(!g||!ks(g))return a("This asset has no supported escrow mapping")}if(!o)return{eligible:!0,reason:null};const d=n.liquidityVenues?.includeDefaults===!1?n.liquidityVenues.venues??[]:[...Ar,...n.liquidityVenues?.venues??[]],p=g=>d.some(y=>y.chainId===g),f=i&&e.chainId!==o.chainId,h=f?Br(e,o.chainId):null;if(f&&!h)return a("No supported source route");if(h&&!ge(Ye(e.address),Ye(h.source.address))&&!p(e.chainId))return a("No conversion venue configured on the source chain");const m=h?.destination.address??Sn(e,o.chainId);return t==="withdraw-destination"?(e.chainTokens||e.receiptTokenId?ko(e,o.chainId):m?[m]:[]).some(g=>ge(Ye(g),Ye(o.address)))?{eligible:!0,reason:null}:a("No supported withdrawal mapping"):m&&ge(Ye(m),Ye(o.address))?{eligible:!0,reason:null}:!m&&!jd(e,o.chainId)?a("No supported destination route"):p(o.chainId)?{eligible:!0,reason:null}:a("No conversion venue configured on the destination chain")}function As(){const e=Qt(Mt),[t]=O(Rc);return e?.inventory??t}function Dr(e,t,n,o,s){const r=As(),a=s??r,i=ue(()=>a.entry(e),[a,e]),[,l]=O(0);ae(()=>{if(n)return i.subscribe(()=>l(d=>d+1),t,o)},[i,n,t,o]);const c=te(()=>i.refresh(),[i]);return{...n?i.snapshot():Mc,refresh:c}}var Fi="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==",Gd="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=",Yd="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=",Vo="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 Qo=Wa(1)?.logo??"",Kd=Na.find(e=>e.symbol==="USDC")?.logo??"",to=Object.fromEntries([...Xc(),...Jc()].map(e=>[e.id,e.logo])),jo={metamask:Fi,metaMask:Fi,rabby:Gd,phantom:Yd},Or=Object.fromEntries(Na.map(e=>[e.symbol.toUpperCase(),e.logo])),Zd={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]},Xd={btc:["wcbtc","cbtc","wbtc"]};function Es(e){return e.replace(/^test\s*/i,"").replace(/^spice/i,"").trim()}function Vn(e){return Es(e).toLowerCase()}function Ti(e){return Vn(e??"").replace(/[^a-z0-9]/g,"")}function Rr(e){const t=Vn(e);return[t,...Xd[t]??[]].filter(Boolean)}function Jd(e){try{return BigInt(e.balanceAvailable||"0")}catch{return 0n}}function Bi(e){return Array.isArray(e.chainTokens)?e.chainTokens:Object.keys(e.chainTokens??{})}function Di(e,t){const n=Ge(e),o=t.toLowerCase();return o===Tt.toLowerCase()?n?.nativeCurrency.decimals??18:n?.supportedTokens?.find(s=>s.address.toLowerCase()===o)?.decimals??18}function $d(e,t,n,o=[]){const s=Di(t,n),r=e.filter(i=>Oi(i,t,n,o));if(r.length===0)return null;const a=r.reduce((i,l)=>Math.min(i,l.decimals??s),s);return{chainDecimals:s,receiptDecimals:a}}function Oi(e,t,n,o){if(Bi(e).some(r=>{const a=qn(r);return a&&qo(a.address,a.chainId,n,t)}))return!0;const s=new Set(o.map(Ti).filter(Boolean));return s.size===0?!1:s.has(Ti(e.tokenName||e.receiptToken))}function Ri(e,t,n,o=[]){const s=Di(t,n);return e.reduce((r,a)=>Oi(a,t,n,o)?r+co(Jd(a),a.decimals??s,s):r,0n)}function Mi(e,t){const n=new Set([...Rr(t),...Rr(Es(t))]);return[...e].sort((o,s)=>{const r=Vn(o.symbol),a=Vn(s.symbol),i=Vn(o.name),l=Vn(s.name),c=n.has(r)?0:n.has(i)?1:2,d=n.has(a)?0:n.has(l)?1:2;return c!==d?c-d:o.address.toLowerCase().localeCompare(s.address.toLowerCase())})[0]}function _d(e){const t=e&&e.length>0?e:Object.keys(ls).map(Number).filter(Number.isFinite),n=new Map;for(const o of t){const s=Ge(o);if(!s)continue;const r=`${o}:${Tt.toLowerCase()}`;n.has(r)||n.set(r,{address:Tt,chainId:o,symbol:s.nativeCurrency.symbol,name:s.nativeCurrency.name,decimals:s.nativeCurrency.decimals,isNative:!0,logoURI:Or[s.nativeCurrency.symbol.toUpperCase()]??s.logo});for(const a of s.supportedTokens??[]){const i=a.address.toLowerCase(),l=`${o}:${i}`;n.has(l)||n.set(l,{address:i,chainId:o,symbol:a.symbol,name:a.name,decimals:a.decimals,isNative:be(i),logoURI:a.logo})}}return n}function eu(e,t){const n=_d(t),o=Es(e.tokenName),s=Vn(e.tokenName),r=Rr(e.tokenName),a=Array.isArray(e.chainTokens)?e.chainTokens.map(m=>[m,void 0]):Object.entries(e.chainTokens??{}),i=a.map(([m])=>qn(m)).filter(m=>m!==null),l=new Map;for(const[m,g]of a){const y=qn(m);if(!y||!Number.isSafeInteger(y.chainId)||y.chainId<0||!/^evm:[0-9]+:(?:0x)?[0-9a-fA-F]{40}$/.test(m)){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 w=`${y.chainId}:${y.address.toLowerCase()}`;if(l.has(w)){const x=l.get(w);if(x?.name!==g?.name||x?.decimals!==g?.decimals)throw new Error("Conflicting chain token metadata")}l.set(w,g)}const c=(m,g)=>{const y=l.get(`${g.chainId}:${g.address.toLowerCase()}`);return{...m,name:typeof y?.name=="string"&&y.name.length>0?y.name:m.name,decimals:typeof y?.decimals=="number"?y.decimals:m.decimals}},d=i.map(m=>{const g=n.get(`${m.chainId}:${m.address.toLowerCase()}`);return g?c(g,m):void 0}).filter(m=>m!==void 0),p=Zd[s]??[];if(p.length>0)for(const m of p){const g=d.filter(y=>y.chainId===m);if(g.length>0)return Mi(g,e.tokenName)}if(d.length>0)return Mi(d,e.tokenName);const f=Array.from(n.values()).filter(m=>r.includes(Vn(m.symbol))||r.includes(Vn(m.name)));if(p.length>0)for(const m of p){const g=f.find(y=>y.chainId===m);if(g)return g}if(f.length>0)return f[0];const h=i[0];if(h){const m=l.get(`${h.chainId}:${h.address.toLowerCase()}`);return{address:h.address,chainId:h.chainId,symbol:o||e.tokenName,name:typeof m?.name=="string"&&m.name.length>0?m.name:o||e.tokenName,decimals:typeof m?.decimals=="number"?m.decimals:e.decimals??18,isNative:be(h.address),logoURI:void 0}}}function tu(e,t){let n;try{n=BigInt(e.balanceAvailable||"0")}catch{return null}if(n<=0n)return null;if(t?.length){const m=Bi(e).map(qn).filter(g=>g!==null);if(m.length>0&&!m.some(g=>t.includes(g.chainId)))return null}let o;try{o=eu(e,t)}catch{return null}const s=o?.decimals??e.decimals??18,r=e.decimals??s,a=co(n,r,s),i=o?.address??Tt,l=o?.chainId??0,c=Es(e.tokenName),d=o?.symbol??c,p=o?.name??c,f=parseFloat(Fe(a,s)),h=typeof e.balanceUsd=="number"?e.balanceUsd:typeof e.balanceUsd=="string"&&Number(e.balanceUsd)||0;return{address:i,symbol:d,name:p,decimals:s,chainId:l,balance:a,balanceFormatted:f,balanceUsd:h,isNative:o?.isNative??be(i),logoURI:o?.logoURI,displaySymbol:c||d,displayName:c||p,displayChainName:"Spicenet",receiptTokenId:e.receiptToken,receiptTokenName:e.tokenName||p,receiptTokenDecimals:r,chainTokens:e.chainTokens&&!Array.isArray(e.chainTokens)?e.chainTokens:void 0,isUniversal:!0}}const Mr=6e4,nu=3e5,Wi="https://api.g.alchemy.com/prices/v1",Io=new Map;function Wr(e,t){try{const n=t??yt(e).transport.url;if(typeof n!="string")return null;const{hostname:o,pathname:s}=new URL(n);if(!o.endsWith(".g.alchemy.com"))return null;const r=s.split("/").filter(Boolean).pop();return r?{network:o.slice(0,-14),key:r}:null}catch{return null}}const Go=(e,t)=>`${e.network}:${e.key}:${t.toLowerCase()}`;function Yo(e,t){const n=Io.get(Go(e,t));if(!n?.price||n.updatedAt===void 0)return;const o=Date.now()-n.updatedAt;if(!(o>=nu))return{price:n.price,stale:o>=Mr}}function Ni(e){const t=Number(e.prices?.find(n=>n.currency==="usd")?.value);return Number.isFinite(t)&&t>0?t:0}async function Pi(e,t,n){const o=[],s=new Set,r=Date.now();for(const a of new Set(t.map(i=>i.toLowerCase()))){const i=Io.get(Go(e,a));i?.pending?s.add(i.pending):(!i||r-i.attemptedAt>=Mr&&(i.updatedAt===void 0||r-i.updatedAt>=Mr))&&o.push(a)}for(let a=0;a<o.length;a+=25){const i=o.slice(a,a+25),l=Promise.resolve().then(async()=>{try{const c=await n(i);for(const d of i){const p=c.get(d);if(!p)continue;const f=Io.get(Go(e,d));f.price=p,f.updatedAt=Date.now()}}catch{}finally{for(const c of i)Io.get(Go(e,c)).pending=void 0}});for(const c of i){const d=Go(e,c);Io.set(d,{...Io.get(d),attemptedAt:r,pending:l})}s.add(l)}await Promise.all(s)}async function Nr(e,t){return await Pi(e,t,async n=>{const o=await fetch(`${Wi}/${e.key}/tokens/by-address`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({addresses:n.map(a=>({network:e.network,address:a}))}),signal:AbortSignal.timeout(1e4)});if(!o.ok)throw new Error("Provider price request failed");const s=await o.json(),r=new Map;for(const a of s?.data??[]){if(a.network&&a.network!==e.network)continue;const i=String(a.address).toLowerCase();n.includes(i)&&r.set(i,Ni(a))}return r}),new Map(t.map(n=>[n.toLowerCase(),Yo(e,n)?.price??0]))}async function Pr(e,t){const n=`native:${t}`;return await Pi(e,[n],async()=>{const o=await fetch(`${Wi}/${e.key}/tokens/by-symbol?symbols=${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(1e4)});if(!o.ok)throw new Error("Provider native price request failed");const s=(await o.json())?.data?.find(r=>r.symbol?.toUpperCase()===t.toUpperCase());return new Map([[n.toLowerCase(),s?Ni(s):0]])}),Yo(e,n)?.price??0}async function ou(e,t){const n=t.supportedChains,o=e.map(s=>{if(Number.isFinite(s.balanceUsd)&&s.balanceUsd>0)return[];const r=Object.keys(s.chainTokens??{}).map(qn).filter(a=>!!a&&fn(a.address)&&!!n?.includes(a.chainId));return r.sort((a,i)=>{const l=c=>c===t.nativeChainId?-1:n.indexOf(c);return l(a.chainId)-l(i.chainId)||+!ge(a.address,s.address)-+!ge(i.address,s.address)}),r.flatMap(a=>{const i=t.rpcOverrides?.[a.chainId];if(!i)return[];const l=Wr(a.chainId,i);if(!l)return[];const c=be(a.address)?Ge(a.chainId)?.nativeCurrency.symbol:void 0,d=c?`native:${c}`:a.address;return[{rpc:l,token:d,address:a.address,nativeSymbol:c}]})});return(typeof document>"u"||!document.hidden)&&await Promise.all(o.map(async s=>{for(const r of s)if(r.nativeSymbol?await Pr(r.rpc,r.nativeSymbol).catch(()=>0):(await Nr(r.rpc,[r.address]).catch(()=>new Map)).get(r.address.toLowerCase()))break})),e.map((s,r)=>{if(Number.isFinite(s.balanceUsd)&&s.balanceUsd>0)return s;const a=o[r].map(i=>Yo(i.rpc,i.token)).find(Boolean);return{...s,balanceUsd:a?s.balanceFormatted*a.price:0,priceStatus:a?a.stale?"stale":"fresh":"unavailable"}})}function su(e,t,n){const o=Qt(Mt),[s,r]=O(()=>typeof document>"u"||!document.hidden);ae(()=>{const d=()=>r(!document.hidden);return document.addEventListener("visibilitychange",d),()=>document.removeEventListener("visibilitychange",d)},[]);const a={supportedChains:n??o?.supportedChainIds,nativeChainId:o?.nativeChainId,rpcOverrides:o?.rpcOverrides},i=JSON.stringify([e,a],(d,p)=>typeof p=="bigint"?p.toString():p),l=te(()=>ou(e,a),[i]),c=Dr(`prices:${i}`,l,t&&s&&e.length>0,6e4);return c.updatedAt?c.assets:e}function ru(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 Ui=({address:e,supportedChains:t,enabled:n=!0,refetchInterval:o,priceEnabled:s=!1})=>{const r=Qt(Mt),a=r?.apiUrl||Nc,i=As(),l=r?.supportedChainIds??t,c=JSON.stringify([...l??[]].sort((b,S)=>b-S)),d=e?.toLowerCase(),p=te(async()=>{const b=await Wc(`${a}/wallets/${d}/balance`,{cache:"no-store"});if(!b.ok)throw new Error(`Failed to fetch balance: ${b.status}`);const S=await b.json();if(!Array.isArray(S.balances))throw new Error("Invalid balance response");return S.balances.map(T=>{const E=tu({receiptToken:typeof T.receiptToken=="string"?T.receiptToken:void 0,tokenName:String(T.tokenName??""),balanceAvailable:String(T.balanceAvailable??"0"),chainTokens:ru(T),decimals:typeof T.decimals=="number"?T.decimals:void 0,balanceUsd:typeof T.balanceUsd=="number"||typeof T.balanceUsd=="string"?T.balanceUsd:null},l);return E?{...E,owner:d,location:"rollup",_source:"spice",positionId:`${d}:rollup:${E.receiptTokenId??E.address}`}:null}).filter(T=>T!==null)},[d,a,c,r?.nativeChainId,r?.rpcOverrides]),{assets:f,loading:h,refreshing:m,error:g,updatedAt:y}=Dr(`rollup:${d}:${a}:${c}`,p,n&&!!d,o??0,i),w=JSON.stringify(t??[]),x=ue(()=>g?f.map(b=>({...b,balanceError:g,balanceStatus:"stale"})):f,[f,g]),v=su(x,n&&s,l),k=ue(()=>v.filter(b=>!t?.length||t.includes(b.chainId)||Object.keys(b.chainTokens??{}).some(S=>t.some(T=>S.startsWith(`evm:${T}:`)))),[v,w]),A=te(b=>k.filter(S=>S.chainId===b),[k]);return{assets:k,loading:h,error:g,hasBalance:k.some(b=>b.balance>0n),refreshing:m,updatedAt:y,refetch:i.invalidate,getAssetsByChain:A}};async function au(e,t,n){if(n)return{decimals:n.decimals,symbol:n.symbol,name:n.name,logoURI:n.logo};const[o,s,r]=await Promise.all([_n(e,{address:t,abi:tt,functionName:"decimals"}),_n(e,{address:t,abi:tt,functionName:"symbol"}).catch(()=>"TOKEN"),_n(e,{address:t,abi:tt,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:s,name:r,logoURI:void 0}}const Li=async(e,t,n)=>{const o=yt(t,n),s=Ge(t),r=await ur(o,{address:e}),a=s.nativeCurrency,i=s.supportedTokens?.find(l=>be(l.address));return{address:Tt,name:a.name,symbol:a.symbol,decimals:a.decimals,balance:r,balanceFormatted:Number(Fe(r,a.decimals)),balanceUsd:0,logoURI:i?.logo||s.logo,isNative:!0,chainId:t}},iu=async(e,t,n,o,s,r,a)=>{try{if(!fn(n))return null;const i=zt(n),l=fn(e)?zt(e):e,c=yt(t,a),d=await _n(c,{address:i,abi:tt,functionName:"balanceOf",args:[l]}),p=Number(Fe(d,r));return d>0n?{address:i,name:o,symbol:s,decimals:r,balance:d,balanceFormatted:p,balanceUsd:0,logoURI:void 0,isNative:!1,chainId:t}:null}catch(i){throw i}},zi=(e,t)=>{const n=Ge(t);if(!n)return e;const o=new Set(e.map(r=>r.address.toLowerCase())),s=e.some(r=>r.isNative);for(const r of n.supportedTokens||[])be(r.address)&&s||o.has(r.address.toLowerCase())||e.push({address:r.address,name:r.name,symbol:r.symbol,decimals:r.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:r.logo,isNative:be(r.address),chainId:t});if(!e.find(r=>r.isNative)){const r=n.supportedTokens?.find(a=>be(a.address));e.push({address:Tt,name:n.nativeCurrency.name,symbol:n.nativeCurrency.symbol,decimals:n.nativeCurrency.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:r?.logo||n.logo,isNative:!0,chainId:t})}return e},lu=async(e,t,n)=>{const o=[],s=async i=>{for(const l of i){const c=await iu(e,t,l.address,l.name,l.symbol,l.decimals,n);c&&(c.logoURI=l.logo,o.push(c))}},r=await Li(e,t,n);r.balance>0n&&o.push(r);const a=(Ge(t)?.supportedTokens||[]).filter(i=>!be(i.address));if(a.length>0)try{const i=yt(t,n),l=zt(e),c=a.filter(h=>fn(h.address)).map(h=>({address:zt(h.address),abi:tt,functionName:"balanceOf",args:[l]})),d=await i.multicall({contracts:c}),p=a.filter(h=>fn(h.address)),f=[];d.forEach((h,m)=>{if(h.status==="success"){const g=h.result;if(g&&g>0n){const y=p[m],w=Number(Fe(g,y.decimals));g>0n&&o.push({address:zt(y.address),name:y.name,symbol:y.symbol,decimals:y.decimals,balance:g,balanceFormatted:w,balanceUsd:0,logoURI:y.logo,isNative:!1,chainId:t})}}else f.push(p[m])}),await s(f)}catch{await s(a)}return{tokens:zi(o,t),chainId:t}},cu=async(e,t,n)=>{const o=new Map,s=Wr(e,n?n[e]??"":void 0);if(!s)return o;const r=t.filter(c=>be(c)),a=t.filter(c=>!be(c)),[i,l]=await Promise.all([a.length?Nr(s,a).catch(()=>new Map):new Map,r.length?Pr(s,Ge(e)?.nativeCurrency?.symbol??"ETH").catch(()=>0):0]);for(const[c,d]of i)d>0&&o.set(c,d);if(l>0)for(const c of r)o.set(c.toLowerCase(),l);return o},du=async(e,t,n,o=!0,s)=>{const r=yt(t,s),a=zt(e),i=[];let l;do{const w=await r.request({method:"alchemy_getTokenBalances",params:[a,"erc20",l?{pageKey:l}:{}]});i.push(...w.tokenBalances),l=w.pageKey||void 0}while(l);const c=i.filter(w=>fn(w.contractAddress)&&!!w.tokenBalance&&BigInt(w.tokenBalance)>0n),d=Ge(t)?.supportedTokens||[],p=w=>d.find(x=>x.address.toLowerCase()===w.toLowerCase()),f=[],h=await Li(e,t,s),[m,g,y]=await Promise.all([Promise.all(c.map(async w=>{const x=p(w.contractAddress);return x?{name:x.name,symbol:x.symbol,decimals:x.decimals,logo:x.logo??null}:await r.request({method:"alchemy_getTokenMetadata",params:[w.contractAddress]})})),o?Nr(n,c.map(w=>w.contractAddress)):new Map(c.map(w=>[w.contractAddress.toLowerCase(),Yo(n,w.contractAddress)?.price??0])),o&&h.balanceFormatted>0?Pr(n,h.symbol):Yo(n,`native:${h.symbol}`)?.price??0]);return h.balance>0n&&f.push({...h,balanceUsd:y*h.balanceFormatted}),c.forEach((w,x)=>{const v=m[x];if(!Number.isInteger(v.decimals)||v.decimals===null||v.decimals<0||v.decimals>255)throw new Error(`Invalid token metadata on chain ${t}`);const k=BigInt(w.tokenBalance),A=Number(Fe(k,v.decimals));if(k<=0n)return;const b=g.get(w.contractAddress.toLowerCase()),S=b?b*A:0;f.push({address:zt(w.contractAddress),name:v.name||"Unknown",symbol:v.symbol||"UNKNOWN",decimals:v.decimals,balance:k,balanceFormatted:A,balanceUsd:S,isDiscovered:!p(w.contractAddress),logoURI:v.logo||void 0,isNative:!1,chainId:t})}),{tokens:zi(f,t),chainId:t}},Hi=new Set,uu=async(e,t,n=!0,o)=>{try{const s=Wr(t,o?o[t]??"":void 0);if(s)try{return await du(e,t,s,n&&(typeof document>"u"||!document.hidden),o)}catch(r){Hi.has(t)||(Hi.add(t),console.warn(`Token discovery unavailable on chain ${t}; listing configured tokens only.`,r))}return await lu(e,t,o)}catch(s){throw s}},So=async(e,t,n=[],o)=>{if(!e)throw new Error("Wallet address is required");const s=Pc(o),r=t?.length?[...new Set(t)]:Object.keys(s).map(Number),a=await Promise.allSettled(r.map(l=>uu(e,l,!0,o))),i={};return a.forEach((l,c)=>{const d=r[c];i[d]=l.status==="fulfilled"?l.value:{chainId:d,tokens:[],error:`Unable to refresh balances on chain ${d}`}}),(await Promise.allSettled(n.map(async l=>{const c=i[l.chainId];if(!c||c.error||c.tokens.some(g=>Ye(g.address).toLowerCase()===Ye(l.address).toLowerCase()))return;const d=yt(l.chainId,o),p=await au(d,l.address,l.decimals!==void 0&&l.symbol?{decimals:l.decimals,symbol:l.symbol,name:l.name||l.symbol,logo:l.logoURI}:void 0),f=await _n(d,{address:l.address,abi:tt,functionName:"balanceOf",args:[e]}),h=await cu(l.chainId,[l.address],o),m=Number(Fe(f,p.decimals));c.tokens.push({...p,...l,name:p.name,symbol:p.symbol,decimals:p.decimals,balance:f,balanceFormatted:m,balanceUsd:(h.get(l.address.toLowerCase())||0)*m,isNative:!1})}))).forEach((l,c)=>{if(l.status==="rejected"){const d=i[n[c].chainId];d&&(d.error=`Unable to refresh token balances on chain ${d.chainId}`)}}),i},Ko=({address:e,supportedChains:t,fetchBalances:n=So,additionalTokens:o=[],enabled:s=!0,refreshInterval:r=0,priceEnabled:a=!0})=>{const i=Qt(Mt),l=As(),c=e?.toLowerCase(),d=JSON.stringify([...i?.supportedChainIds??t??[]].sort((x,v)=>x-v)),p=JSON.stringify(o);ae(()=>l.registerTokens(o),[l,p]);const f=c&&c===i?.embeddedWalletAddress?.toLowerCase()?"embedded":"external",h=`wallet:${JSON.stringify([i?.network,i?.apiUrl,i?.rpcOverrides])}:${c}:${f}:${d}:${l.fetcherId(n)}`,m=te(async()=>{let x;try{x=await n(c,JSON.parse(d),l.tokens(),i?.rpcOverrides)}catch(b){const S=b instanceof Error?b.message:"Unable to refresh balances";x=Object.fromEntries(JSON.parse(d).map(T=>[T,{chainId:T,tokens:[],error:S}]))}const v=l.entry(h).snapshot().assets,k=JSON.parse(d).map(b=>x[b]??{chainId:b,tokens:[],error:`Unable to refresh balances on chain ${b}`}),A=k.flatMap(b=>b.error?[b.error]:[]);return{assets:k.flatMap(b=>b.error?v.filter(S=>S.chainId===b.chainId).map(S=>({...S,balanceError:b.error,balanceStatus:"stale"})):b.tokens.map(S=>({...S,owner:c,location:f,_fundingWallet:f,_source:"wallet",positionId:`${c}:${f}:${b.chainId}:${Ye(S.address).toLowerCase()}`}))),error:A.length?A.join("; "):null}},[l,c,d,n,f,h]),g=Dr(h,m,s&&!!c,r,l),y=JSON.stringify(t&&[...t].sort((x,v)=>x-v)),w=ue(()=>t?g.assets.filter(x=>t.includes(x.chainId)):g.assets,[g.assets,y]);return ae(()=>{a&&s&&c&&g.refresh()},[a]),{...g,assets:w,refreshAssets:l.invalidate,getAssetsByChain:te(x=>w.filter(v=>v.chainId===x),[w]),getNativeAssets:te(()=>w.filter(x=>x.isNative),[w])}};function Ao(e){const t=Qt(Mt),n=As(),o=e.owner??((t?.mode||"7702")!=="7702"?t?.externalWalletAddress:t?.embeddedWalletAddress),s=o?.toLowerCase()!==t?.embeddedWalletAddress?.toLowerCase(),r=e.sourceChains??t?.supportedChainIds??[],a=(e.enabled??!0)&&!t?.isWhitelistGateActive,i=ue(()=>{const f=[...t?.additionalSourceTokens??[],...e.additionalSourceTokens??[],...e.destination?[e.destination]:[]];for(const h of e.supportedSourceAssets??[])for(const m of r){const g=Ge(m)?.supportedTokens?.find(y=>is(y,[h]));g&&f.push({...g,address:g.address,chainId:m,logoURI:g.logo})}return f},[e.destination,JSON.stringify(t?.additionalSourceTokens),JSON.stringify(e.additionalSourceTokens),JSON.stringify(e.supportedSourceAssets),JSON.stringify(r)]),l=Ko({address:o,supportedChains:r,fetchBalances:So,additionalTokens:i,enabled:a&&e.includeWalletAssets!==!1,refreshInterval:3e4}),c=Ui({address:o,supportedChains:r,enabled:a&&e.includeRollupAssets!==!1&&!!o&&o.toLowerCase()===t?.embeddedWalletAddress?.toLowerCase(),priceEnabled:a,refetchInterval:3e4}),d=ue(()=>a?[...(e.includeWalletAssets===!1?[]:l.assets).map(f=>({...f,owner:f.owner??o,location:f.location??(s?"external":"embedded"),_source:"wallet"})),...(e.includeRollupAssets===!1||o?.toLowerCase()!==t?.embeddedWalletAddress?.toLowerCase()?[]:c.assets).map(f=>({...f,owner:f.owner??o,location:"rollup",_source:"spice"}))]:[],[a,l.assets,c.assets,e.includeWalletAssets,e.includeRollupAssets,o,s,t?.embeddedWalletAddress]),p=ue(()=>d.map(f=>({asset:f,...po(f,e.role??"holding",{allowedTokens:t?.allowedTokens,rpcOverrides:t?.rpcOverrides,liquidityVenues:t?.liquidityVenues,isWhitelistGateActive:!!t?.isWhitelistGateActive},e.destination,e.supportedSourceAssets,{requiresEscrow:e.requiresEscrow})})),[d,t?.allowedTokens,t?.rpcOverrides,t?.liquidityVenues,t?.isWhitelistGateActive,e.role,e.destination,e.supportedSourceAssets,e.requiresEscrow]);return{positions:p,assets:ue(()=>p.filter(f=>f.eligible&&f.asset.balance>0n).map(f=>f.asset),[p]),walletAssets:ue(()=>d.filter(f=>f._source==="wallet"),[d]),rollupAssets:ue(()=>d.filter(f=>f._source==="spice"),[d]),loading:l.loading||c.loading,refreshing:l.refreshing||c.refreshing,error:l.error||c.error,refresh:n.invalidate}}function no(e){const t=Ye(e.address);if(e.isNative||be(t))return!1;const n=Ge(e.chainId)?.supportedTokens?.some(s=>ge(s.address,t)),o=Ft(t,e.chainId);return!!n&&!!o&&ks(o)}const qi="spiceflow:pendingDeposit",Fs="spiceflow:pendingDepositChanged";function Vi(e,t,n){return`${qi}:${e.toLowerCase()}:${t}:${n.toLowerCase()}`}function Ur(){try{const e="__spiceflow_storage_test__";return localStorage.setItem(e,"1"),localStorage.removeItem(e),!0}catch{return!1}}function pu(e){if(!Ur())return;const t=Vi(e.embeddedWalletAddress,e.chainId,e.tokenAddress);try{localStorage.setItem(t,JSON.stringify(e)),window.dispatchEvent(new Event(Fs))}catch(n){console.error("[pendingDeposit] Failed to save:",n)}}function fu(e){if(!Ur())return[];const t=`${qi}:${e.toLowerCase()}:`,n=[],o=Date.now();for(let s=0;s<localStorage.length;s++){const r=localStorage.key(s);if(!(!r||!r.startsWith(t)))try{const a=localStorage.getItem(r);if(!a)continue;const i=JSON.parse(a);if(o-i.timestamp>6048e5){localStorage.removeItem(r);continue}n.push(i)}catch{localStorage.removeItem(r)}}return n}function Lr(e,t,n){if(!Ur())return;const o=Vi(e,t,n);localStorage.removeItem(o),window.dispatchEvent(new Event(Fs))}const mu=new Set(["USDC","SUSD","USD","NUSD","USDT","DAI","ENUSD","USDG"]),Qi={ETH:"ethereum",WETH:"ethereum",BTC:"bitcoin",WBTC:"bitcoin",WCBTC:"bitcoin",CBTC:"bitcoin",ECBTC:"bitcoin",ARB:"arbitrum",MATIC:"matic-network",POL:"matic-network"};let Ts=null;const hu=6e4;async function ji(e){const t={},n=new Set,o={};for(const r of e){const a=r.toUpperCase();if(mu.has(a))t[a]=1;else if(Qi[a]){const i=Qi[a];n.add(i),o[a]=i}else t[a]=0}if(n.size===0)return t;const s=Date.now();if(Ts&&s-Ts.timestamp<hu){for(const[r,a]of Object.entries(o))t[r]=Ts.prices[a]??0;return t}try{const r=Array.from(n).join(","),a=await fetch(`https://api.coingecko.com/api/v3/simple/price?ids=${r}&vs_currencies=usd`);if(!a.ok)throw new Error(`CoinGecko ${a.status}`);const i=await a.json(),l={};for(const c of n)l[c]=i[c]?.usd??0;Ts={prices:l,timestamp:s};for(const[c,d]of Object.entries(o))t[c]=l[d]??0}catch(r){console.warn("[fetchTokenPrices] CoinGecko fetch failed:",r);for(const a of Object.keys(o))t[a]=t[a]??0}return t}const gu=new Set(["cbtc","btc","wbtc","wcbtc","tbtc"]),yu=new Set(["usdc","usdt","dai","usdc.e","usdbc","usdg"]);async function xu(){const e=(await ji(["BTC"])).BTC;if(!e||e<=0)throw new Error("Failed to fetch BTC/USD price");return e}function wu(e){return gu.has(e.toLowerCase())}function bu(e){return yu.has(e.toLowerCase())}function vu(e,t,n,o){const s=10n**12n,r=BigInt(Math.round(o*Number(s))),a=t-n,i=10n**BigInt(Math.abs(a));let l=e*r/s;return a>0?l=l/i:a<0&&(l=l*i),l}const Cu=.01,ku=5*60*1e3;function Iu(e){const t=Number(Fe(e.verifiedBalance,e.tokenDecimals));return Number.isFinite(t)?t:0}async function Su(e){const t=Au(e);let n;try{n=await ji(t.map(o=>o.tokenSymbol))}catch{return t}return t.filter(o=>{const s=Iu(o);if(s<=0)return!0;const r=n[o.tokenSymbol.toUpperCase()]??0;return!Number.isFinite(r)||r<=0?!0:s*r>=Cu})}function Au(e){const t=new Map;for(const n of e){const o=`${n.chainId}:${n.tokenAddress.toLowerCase()}`;t.get(o)||t.set(o,{...n,amount:n.timestamp===0?Fe(n.verifiedBalance,n.tokenDecimals):n.amount,rawAmount:n.timestamp===0?n.verifiedBalance.toString():n.rawAmount,hasFullBalance:n.timestamp===0?!0:n.hasFullBalance})}return Array.from(t.values())}function Gi(e,t){const[n,o]=O([]),[s,r]=O(!1),a=_(t);a.current=t;const i=_(0),l=_(0),c=te(async({forceDiscovery:d=!1}={})=>{if(!e){o([]),r(!1);return}const p=++l.current,f=()=>p!==l.current;r(!0);try{const h=[],m=fu(e);for(const x of m){if(f())return;if(no({address:x.tokenAddress,chainId:x.chainId,isNative:x.isNative}))try{const v=yt(x.chainId);let k;if(x.isNative||be(x.tokenAddress)?k=await ur(v,{address:e}):k=await _n(v,{address:zt(x.tokenAddress),abi:tt,functionName:"balanceOf",args:[e]}),f())return;k>0n?h.push({...x,verifiedBalance:k,hasFullBalance:k>=BigInt(x.rawAmount)}):Date.now()-x.timestamp>15*60*1e3&&Lr(e,x.chainId,x.tokenAddress)}catch(v){console.warn(`[usePendingDeposit] Failed to verify balance for ${x.tokenSymbol} on chain ${x.chainId}:`,v),h.push({...x,verifiedBalance:0n,hasFullBalance:!1})}}if(f())return;const g=a.current,y=Date.now(),w=(g?.discoverWalletBalances??!0)&&(d||y-i.current>=ku);if(g?.network&&w){i.current=y;const x=g.chainIds??ys(g.network),v=new Set(h.map(A=>`${A.chainId}:${A.tokenAddress.toLowerCase()}`)),k=[];for(const A of x){const b=Ge(A);if(b?.supportedTokens)for(const S of b.supportedTokens){if(!no({address:S.address,chainId:A,isNative:!1}))continue;const T=`${A}:${S.address.toLowerCase()}`;v.has(T)||k.push((async()=>{try{const E=yt(A),I=await _n(E,{address:zt(S.address),abi:tt,functionName:"balanceOf",args:[e]});return I>0n?{chainId:A,tokenAddress:S.address,tokenSymbol:S.symbol,tokenDecimals:S.decimals,amount:Fe(I,S.decimals),rawAmount:I.toString(),embeddedWalletAddress:e,externalWalletAddress:"",timestamp:0,isNative:!1,verifiedBalance:I,hasFullBalance:!0}:null}catch{return null}})())}}if(k.length>0){const A=await Promise.allSettled(k);if(f())return;for(const b of A)b.status==="fulfilled"&&b.value&&h.push(b.value)}}if(!f()){const x=await Su(h);if(f())return;o(x)}}catch(h){console.error("[usePendingDeposit] Verification error:",h),f()||o([])}finally{f()||r(!1)}},[e]);return ae(()=>{if(!a.current?.enabled){l.current++,o([]),r(!1);return}c({forceDiscovery:!0});const d=a.current?.pollIntervalMs??3e4;if(d<=0||!e)return()=>{l.current++};const p=setInterval(()=>{c({forceDiscovery:!1})},d),f=()=>c({forceDiscovery:!0});return window.addEventListener(Fs,f),()=>{l.current++,window.removeEventListener(Fs,f),clearInterval(p)}},[c,e]),{pendingDeposits:n,loading:s,refresh:()=>c({forceDiscovery:!0})}}function Yi(e){const t=Qt(Mt),n=t?.embeddedWalletAddress,o=e?.enabled===!1?void 0:n,s=t?.network?{network:t.network,pollIntervalMs:e?.pollIntervalMs,chainIds:e?.chainIds??t.supportedChainIds,discoverWalletBalances:e?.discoverWalletBalances}:void 0;return{...Gi(o,s),embeddedWalletAddress:n}}var zr="data:image/svg+xml,%3csvg width='10' height='10' viewBox='0 0 10 10' fill='none' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M5 4.99995V6.99995M5 3.31245V3.31189M9.5 5C9.5 7.48528 7.48528 9.5 5 9.5C2.51472 9.5 0.5 7.48528 0.5 5C0.5 2.51472 2.51472 0.5 5 0.5C7.48528 0.5 9.5 2.51472 9.5 5Z' stroke='black' stroke-opacity='0.4' stroke-linecap='round' stroke-linejoin='round'/%3e%3c/svg%3e";function Hr(e){const t=_(0),n=_(null),o=_(e.run);o.current=e.run;const s=_(e.onSkip);s.current=e.onSkip;const r=_(e.onCleanup);r.current=e.onCleanup,ae(()=>{if(!e.shouldRun){t.current+=1,n.current?.abort(),s.current?.();return}let a=!1,i=!1;const l=async p=>{if(p&&i)return;n.current?.abort();const f=new AbortController;n.current=f;const h=++t.current;i=!0;try{await o.current({isBackground:p,isCurrent:()=>!a&&t.current===h,signal:f.signal})}finally{i=!1}},c=window.setTimeout(()=>void l(!1),e.delayMs??250),d=e.backgroundIntervalMs?window.setInterval(()=>void l(!0),e.backgroundIntervalMs):void 0;return()=>{a=!0,n.current?.abort(),clearTimeout(c),d!==void 0&&window.clearInterval(d),r.current?.()}},[e.shouldRun,e.delayMs,e.backgroundIntervalMs,...e.deps])}function Ki(e,t){if(e.length!==t.length)return!1;const n=$n(e),o=$n(t);return n.every((s,r)=>s.hash===o[r]?.hash)}const Bn=e=>new Promise(t=>setTimeout(t,e)),Eu="0xa9059cbb";function Zi(e){const t=e.findIndex(s=>bo(s.chainId));if(t<=0)return[];const n=new Map,o=(s,r,a)=>{if(a<=0n)return;const i=`${s}:${r.toLowerCase()}`,l=n.get(i);l?l.amount+=a:n.set(i,{chainId:s,token:r,amount:a})};for(const s of e.slice(0,t)){const r=Uo(s.chainId);if(!(!r||r===Tt)){for(const a of s.calls)if(a.value&&a.value>0n&&ge(a.to,r)&&o(s.chainId,Tt,a.value),!!a.data?.startsWith(Eu))try{const i=uo({abi:tt,data:a.data});if(i.functionName!=="transfer")continue;const[l,c]=i.args;ge(l,r)&&o(s.chainId,a.to,c)}catch{}}}return[...n.values()]}function Xi(e){const t=Ft(e.token,e.chainId);return[t?.equivalenceGroup,t?.symbol,t?.name]}function Ji(e,t){return Ri(e,t.chainId,t.token,Xi(t))}function Fu(e,t){const n=$d(e,t.chainId,t.token,Xi(t));return!n||n.receiptDecimals>=n.chainDecimals?t.amount:co(co(t.amount,n.chainDecimals,n.receiptDecimals),n.receiptDecimals,n.chainDecimals)}async function Tu(e){const{deposits:t,baseline:n,fetchEntries:o,timeoutMs:s=12e4,intervalMs:r,signal:a,wait:i=Bn}=e;if(t.length===0)return!0;const l=new Map(t.map(p=>[p,Ji(n,p)])),c=Date.now(),d=c+s;for(;!a?.aborted;){try{const m=await o();if(t.every(g=>Ji(m,g)-l.get(g)>=Fu(m,g)))return!0}catch{}const p=Date.now();if(p>=d)return!1;const f=p-c,h=r??(f<5e3?250:f<15e3?1e3:3e3);await i(Math.min(h,d-p))}return!1}function Bu(e,t){const n=$n(e).map(o=>o.hash);return vo(zn([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,t,n]))}async function Du(e,t,n,o,s){if(o?.aborted)throw new Ne("ABORT","Execution transaction aborted");const r={raw:Bu(t,n)},a=s?await e.signMessage(r,s):await e.signMessage(r);console.debug("[SpiceFlow:execution]",{phase:"signature-returned",at:Date.now()});const i=typeof a=="string"?a:a.signature;if(!i)throw new Ne("SIGNATURE_FAILED","Failed to sign intent authorization. The wallet returned an empty signature.");return i}function Ou(e){return e.domain==="spicenet"||bo(e.chainId)}async function Ru(e){const{chainBatches:t,signingAddress:n,actions:o,cache:s,signal:r,onSignatureRequested:a,beforeSign:i}=e;if(r?.aborted)throw new Ne("ABORT","Execution transaction aborted");const l=[...new Set(t.filter(p=>!Ou(p)).map(p=>p.chainId))].map(p=>({chainId:p,client:yt(p),delegateContract:va(p)})),[c]=await Promise.all([Promise.all(l.map(async({chainId:p,client:f,delegateContract:h})=>{const m=Number(await $c(n,f)),g=[n.toLowerCase(),p,h.toLowerCase(),m].join(":");return{chainId:p,delegateContract:h,nonce:m,cacheKey:g,cached:s?.get(g)}})),l.length?o.prepareSigning?.():void 0,i?.()]),d=[];for(const{chainId:p,delegateContract:f,nonce:h,cacheKey:m,cached:g}of c){if(g){d.push(g);continue}if(r?.aborted)throw new Ne("ABORT","Execution transaction aborted");const y=await o.signAuthorization({contractAddress:f,chainId:p,nonce:h},a),w={r:y.r,s:y.s,yParity:y.yParity,address:y.address??f,chainId:Number(y.chainId??p),nonce:Number(y.nonce??h)};s?.set(m,w),d.push(w)}return d}const $i=15;function Mu(e){return e.now-e.lastProgressAt>=e.pollTimeoutMs}function _i(e,t){return{intentId:e,steps:t.map(n=>({...n,status:"pending"})),overallStatus:"processing"}}function Bs(e,t,n){const o=e.steps.map(i=>({...i})),s=o[t];if(!s)return e;n.status==="success"||n.status==="completed"?(o[t]={...s,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]={...s,status:"failed",transactionHash:n.transactionHash,error:n.error}:o[t]={...s,status:"processing"};const r=o.some(i=>i.status==="failed"),a=o.every(i=>i.status==="success");return{...e,steps:o,overallStatus:r?"failed":a?"success":"processing"}}function Wu({checkStepStatus:e,retryStep:t,maxRetries:n=3,pollingInterval:o=2500,pollTimeoutMs:s=3e5}){const[r,a]=O(null),i=_(null),l=_(null),c=_(!1),d=_(!1),p=_(0),f=_({}),h=_(0),m=te(k=>{i.current=k,a(k)},[]),g=te(()=>{l.current&&(clearInterval(l.current),l.current=null)},[]),y=te(()=>{p.current=0,f.current={},h.current=0,c.current=!0,g(),m(null)},[g,m]),w=te((k,A)=>{g(),c.current=!1,m(_i(k,A))},[g,m]),x=te((k,A)=>{const b=i.current;b&&m(Bs(b,k,A))},[m]),v=te((k,A)=>{g(),c.current=!1,d.current=!1,p.current=0,f.current={},h.current=Date.now(),m(_i(k,A));const b=async()=>{if(!(c.current||d.current||!e)){d.current=!0;try{if(Mu({now:Date.now(),lastProgressAt:h.current,pollTimeoutMs:s})){const E=i.current;E&&m({...E,steps:E.steps.map(I=>I.status==="success"?I:{...I,status:"failed",error:"Taking longer than expected. It may still complete - check the explorer, then refresh."}),overallStatus:"failed"}),c.current=!0,g();return}const S=i.current;if(!S)return;const T=S.steps.findIndex(E=>E.status!=="success");if(T===-1){c.current=!0,g();return}if(!(T===0||S.steps[T-1].status==="success"))return;try{const E=S.steps[T].stepId,{data:I}=await e(k,E);if(p.current=0,I.status==="success"&&(h.current=Date.now()),I.status==="reverted"){const W=f.current[E]||0;if(t&&W<n){f.current[E]=W+1;try{await t(k,E)}catch(R){console.error(`[intentStatus] retry failed for step ${E}:`,R)}m(Bs(i.current,T,{status:"executing"}));return}}const M=Bs(i.current,T,I);m(M),M.overallStatus!=="processing"&&(c.current=!0,g())}catch(E){p.current+=1,console.error(`[intentStatus] poll error (${p.current}/${$i}):`,E),p.current>=$i&&(m(Bs(i.current,T,{status:"error"})),c.current=!0,g())}}finally{d.current=!1}}};b(),l.current=setInterval(b,o)},[e,t,n,o,s,g,m]);return ae(()=>()=>g(),[g]),{intentStatus:r,startStatusPolling:v,beginStatusTracking:w,applyStepUpdate:x,stopStatusPolling:g,clearStatus:y}}function Nu(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 Pu=350,Uu=2500;async function el(e){const{actionId:t,intentIndex:n,intentId:o,stepIndex:s,maxPolls:r=48,maxExecuteAttempts:a=3,pollsBeforeRetry:i=5,maxConsecutiveStatusErrors:l=15,onStatusMessage:c,onStepUpdate:d,signal:p,chainId:f}=e;if(p?.aborted)throw new Ne("ABORT","Execution transaction aborted");let h="pending",m,g,y=0,w=0,x,v;const k=new Promise((b,S)=>{x=b,v=()=>S(new Ne("ABORT","Execution transaction aborted"))}),A=()=>{y++,Lt.executeStep(t,n,s,{action:"execute"}).then(b=>{b.transactionHash&&(m=b.transactionHash),b.status==="success"&&x({status:b.status,transactionHash:b.transactionHash})}).catch(b=>{const S=b instanceof Error?b.message:String(b);console.warn(`[execution] executeStep ${s} attempt ${y} error (will poll):`,S)})};p?.addEventListener("abort",v,{once:!0});try{A();for(let b=0;b<r;b++){const S=b===0?Pu:Uu;try{const E=await Promise.race([Bn(S).then(()=>{}),k]);if(p?.aborted)throw new Ne("ABORT","Execution transaction aborted");const I=E??await Promise.race([Lt.checkStepStatus(o,s).then(W=>W.data),k]);if(p?.aborted)throw new Ne("ABORT","Execution transaction aborted");w=0,h=I.status,g=I.error;const M=I.transactionHash;M&&(m=M),d?.({status:h,transactionHash:m,error:g})}catch(E){if(E instanceof Error&&(E.name==="AbortError"||E instanceof Ne&&E.code==="ABORT")||(w++,w>=l))throw E;continue}if(h==="created"&&b>=y*i&&y<a&&A(),h==="reverted"||h==="error")throw new Ne("ON_CHAIN_REVERT",Nu(h,g),{status:h,txHash:m,actionId:t,intentId:o,stepId:s,chainId:f});if(h==="success"||h==="completed")return m;let T="Waiting for solver...";h==="executing"?T="Transaction executing...":h==="submitted"?T="Transaction submitted...":h==="created"&&(T="Waiting for relayer..."),c?.(T,m)}throw new Ne("POLLING_EXHAUSTED",`Transaction is still processing (status: ${h}). 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:s,lastStatus:h,pollAttempts:r,maxPolls:r,txHash:m})}finally{p?.removeEventListener("abort",v)}}async function Lu(e){const{actionId:t,intentIndex:n,intentId:o,totalSteps:s,delayBeforeSpicenetStepMs:r=5e3,isSpicenetStep:a,beforeStep:i,maxExecuteAttemptsForStep:l,maxPolls:c=48,onStatusMessage:d,onStepUpdate:p,signal:f}=e;let h;for(let m=0;m<s;m++){if(m>0&&a?.(m)&&r>0&&await Bn(r),await i?.(m),f?.aborted)throw new Ne("ABORT","Execution transaction aborted");const g=l?.(m)??3,y=await el({actionId:t,intentIndex:n,intentId:o,stepIndex:m,maxPolls:c,maxExecuteAttempts:g,maxConsecutiveStatusErrors:g===6?5:15,onStatusMessage:d,onStepUpdate:p?w=>p(m,w):void 0,signal:f});y&&(h=y)}return h}const zu="0xa9059cbb";function qr(e,t){return e.map(n=>{if(n.domain==="spicenet"||bo(n.chainId)||n.calls.length===0)return n;const o=new Set((n.tokenTransfers??[]).filter(a=>(a.from==="escrow"||a.from==="solver")&&ge(a.to,t)).map(a=>a.token.toLowerCase()));if(o.size===0)return n;const s=[...o].some(be);let r=0;for(const a of n.calls){if(s&&a.value>0n&&a.data==="0x"&&!ge(a.to,t)){r+=1;continue}if(!a.data?.startsWith(zu))break;try{const i=uo({abi:tt,data:a.data});if(i.functionName!=="transfer")break;const[l]=i.args;if(ge(l,t)||!o.has(a.to.toLowerCase()))break;r+=1}catch{break}}return r===0?n:{...n,calls:n.calls.slice(r)}})}async function Hu(e,t){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 n=await e.waitForTransactionReceipt({hash:t,timeout:12e4,pollingInterval:2e3,confirmations:1});if(n.transactionHash?.toLowerCase()!==t.toLowerCase()||n.status!=="success")throw new Error("The destination transaction has not been confirmed successfully. Reconcile the existing action before retrying.");return t}async function Ds(e){let t=e.hash,n=!1;const o=Date.now()+12e4,s=a=>a.transactionHash&&a.transactionHash.toLowerCase()!==t.toLowerCase();let r=await e.client.waitForTransactionReceipt({hash:t,timeout:12e4,pollingInterval:2e3,confirmations:1,onReplaced:a=>{const i=a.transaction,l=a.replacedTransaction;if(!(a.reason==="repriced"&&l?.from&&l.nonce!==void 0&&/^0x[0-9a-f]{64}$/i.test(i?.hash??"")&&i?.to?.toLowerCase()===e.call.to.toLowerCase()&&(i.input??"0x").toLowerCase()===e.call.data.toLowerCase()&&BigInt(i.value??0)===e.call.value&&i.from?.toLowerCase()===l?.from?.toLowerCase()&&i.nonce===l?.nonce)){n=!0,e.onCancelled?.();return}t=i.hash,e.onRepriced?.(t)}});if(n)throw new Error("Transaction was cancelled or replaced with a different action; retry the unfinished action");if((e.confirmations??1)>1&&!s(r)&&r.status==="success"&&(r=await e.client.waitForTransactionReceipt({hash:t,timeout:Math.max(o-Date.now(),1),pollingInterval:2e3,confirmations:e.confirmations})),s(r))throw new Error("Unexpected transaction receipt; recover the submitted transaction before retrying");return{receipt:r,hash:t}}const qu=10n,Vu=10n,Qu=5;function Vr(e){return e.map(t=>({...t,calls:[...t.calls],tokenTransfers:t.tokenTransfers?[...t.tokenTransfers]:void 0}))}function Os({token:e,recipient:t,amount:n}){return{to:e,value:0n,data:xt({abi:tt,functionName:"transfer",args:[t,n]})}}function ju({chainBatches:e,token:t,amount:n}){const o=Vr(e),s=o[o.length-1];if(!s)return o;const r=Jn(s.chainId);return s.calls=[...s.calls,Os({token:t,recipient:r,amount:n})],o}function tl({chainBatches:e,user:t,token:n,grossAmount:o,gasFee:s}){const r=Vr(e),a=r[r.length-1];if(!a)throw new Ne("INVALID_PARAMS","Action-output escrow funding requires at least one chain batch.");const i=tr(o,Vu),l=s+i;if(l>=o)throw new Ne("INVALID_PARAMS","Borrow amount is too small after gas and Spicenet fees.",{grossAmount:o.toString(),gasFee:s.toString(),spicenetFee:i.toString()});const c=o-l,d=Jn(a.chainId),p=[];return s>0n&&p.push(Os({token:n,recipient:nn,amount:s})),i>0n&&p.push(Os({token:n,recipient:Fn,amount:i})),a.calls=[...a.calls,...p,Os({token:n,recipient:d,amount:c})],a.tokenTransfers=[...a.tokenTransfers??[],...s>0n?[{from:t,to:nn,token:n,amount:s}]:[],...i>0n?[{from:t,to:Fn,token:n,amount:i}]:[],{from:t,to:d,token:n,amount:c}],{chainBatches:r,gasFee:s,spicenetFee:i,netEscrowAmount:c,outputCredit:{chainId:a.chainId,token:n,amount:o}}}async function nl({chainBatches:e,user:t,token:n,grossAmount:o,chainAuthorizations:s}){let r=0n,a=tl({chainBatches:e,user:t,token:n,grossAmount:o,gasFee:r});for(let i=0;i<Qu;i+=1){const l=$n(a.chainBatches),c=(await Lt.estimateBatchGas({user:t,outputToken:n,chainBatches:a.chainBatches.map((d,p)=>({...d,hash:l[p].hash})),chainAuthorizations:s})).gasFee;if(c===r)return a;r=c,a=tl({chainBatches:e,user:t,token:n,grossAmount:o,gasFee:r})}throw new Ne("INVALID_PARAMS","Action-output fee estimate did not converge. Please retry.")}function Qn(e){return bo(e.chainId)}const Gu="0xa9059cbb";function Zo(e,t){return`${e}:${Ye(t).toLowerCase()}`}function ol(e,t){return t===Tt.toLowerCase()?{symbol:gn(e),decimals:18}:Ft(t,e)??{symbol:"tokens",decimals:18}}function Yu(e,t){const n=Ft(t,e);return[n?.equivalenceGroup,n?.symbol,n?.name]}async function Qr(e){return Ca(e)}async function Ku(e,t,n){const o=new Map,s=n?.walletFundingRequirement,r=s&&Zo(s.chainId,s.token);r&&o.set(r,0n);const a=new Map,i=new Map,l=new Map,c=new Map;for(const p of n?.actionOutputCredits??[]){const f=Zo(p.chainId,p.token);c.set(f,(c.get(f)??0n)+p.amount)}for(const p of e){if(Qn(p))continue;for(const m of p.tokenTransfers??[]){if(m.from!=="escrow"&&m.from!=="solver"||!ge(m.to,t))continue;const g=BigInt(m.amount??0);if(g<=0n)continue;const y=Zo(p.chainId,m.token);a.set(y,(a.get(y)??0n)+g),m.from==="escrow"&&i.set(y,(i.get(y)??0n)+g)}const f=Uo(p.chainId),h=m=>!!f&&f!==Tt&&ge(m,f);for(const m of p.calls){if(m.value&&m.value>0n){const g=Zo(p.chainId,Tt);o.set(g,(o.get(g)??0n)+m.value),h(m.to)&&l.set(g,(l.get(g)??0n)+m.value)}if(m.data?.startsWith(Gu))try{const g=uo({abi:tt,data:m.data});if(g.functionName!=="transfer")continue;const[y,w]=g.args,x=m.to.toLowerCase(),v=Zo(p.chainId,x);o.set(v,(o.get(v)??0n)+w),h(y)&&l.set(v,(l.get(v)??0n)+w)}catch{}}}let d=null;for(const[p,f]of i){const h=f-(l.get(p)??0n);if(h<=0n)continue;const[m,g]=p.split(":"),y=Number(m),w=ol(y,g);d??(d=await Qr(t));const x=Ri(d,y,g,Yu(y,g));if(!(x>=h))throw new Ne("INVALID_PARAMS",`Insufficient Spice ${w.symbol}: needs ${Fe(h,w.decimals)}, has ${Fe(x,w.decimals)}.`,{chainId:y,token:g,userAddress:t,requiredAmount:h.toString(),balance:x.toString(),balanceSource:"spice"})}for(const[p,f]of o){const[h,m]=p.split(":"),g=Number(h);let y=f-(a.get(p)??0n)-(c.get(p)??0n);if(s&&p===r&&s.amount>y&&(y=s.amount),y<=0n)continue;const w=yt(g),x=m===Tt.toLowerCase()?await w.getBalance({address:t}):await w.readContract({address:m,abi:tt,functionName:"balanceOf",args:[t]});if(x>=y)continue;const v=ol(g,m);throw new Ne("INVALID_PARAMS",`Insufficient ${v.symbol} on ${gn(g)}: needs ${Fe(y,v.decimals)}, has ${Fe(x,v.decimals)}.`,{chainId:g,token:m,userAddress:t,requiredAmount:y.toString(),balance:x.toString(),balanceSource:"wallet"})}}function Zu({chainBatches:e,tokenAddress:t,tokenTransferAmount:n,useCustomTransfers:o}){if(!(e.some(Qn)||!(o?e.some(s=>Qn(s)?!1:(s.tokenTransfers??[]).some(r=>r.from==="escrow"&&BigInt(r.amount??0)>0n)):n>0n)))throw new Ne("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 Xu(e,t,n,o){t.forEach((s,r)=>{if(!s.to||!s.from||!s.token||s.amount===void 0)throw new Ne("INVALID_TOKEN_TRANSFER",`tokenTransfers[${r}] 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:r,transfer:{from:s.from,to:s.to,token:s.token,amount:s.amount?.toString()},signingAddress:n,useCustomTransfers:o})})}function Rs({user:e,chainBatches:t,tokenAddress:n,tokenTransferAmount:o,exp:s,signature:r,chainAuthorizations:a,useCustomTransfers:i}){const l=t,c=$n(l),d=l.filter(p=>!Qn(p)).length;if(Zu({chainBatches:l,tokenAddress:n,tokenTransferAmount:o,useCustomTransfers:i}),!i&&o>0n&&d>1)throw new Ne("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:d,tokenAddress:n,tokenTransferAmount:o.toString()});return{user:e,...a?{chainAuthorizations:a}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:r,nbf:0,exp:s,chainBatches:c.map((p,f)=>{const h=l[f],m=Qn(h)?[]:i?h.tokenTransfers??[]:o>0n?[{from:"escrow",to:e,token:n,amount:o}]:[];return Xu(Number(p.chainId),m,e,i),{hash:p.hash,chainId:Number(p.chainId),tokenTransfers:m,calls:p.calls}})}]}}function sl(e,t){const n=t?.depositToEscrow?.gasFundingSource==="action-output"?t.depositToEscrow:null,o=t?.depositToEscrow&&!n?ju({chainBatches:e,token:t.depositToEscrow.token,amount:t.depositToEscrow.amount}):Vr(e);return{actionOutputDeposit:n,batches:o}}let jr=!1;function Ms(){const{address:e,isConnected:t,isAuthenticated:n,actions:o}=Zn(),s=_(null),{intentStatus:r,startStatusPolling:a,beginStatusTracking:i,applyStepUpdate:l,clearStatus:c}=Wu({checkStepStatus:(y,w)=>Lt.checkStepStatus(y,w),retryStep:async(y,w)=>{const[x,v]=y.split("/"),k=parseInt(v||"0",10);await Lt.executeStep(x,k,w,{action:"execute"})}}),d=_(o),p=_(new Map);d.current=o;const f=te((y,w,x,v,k)=>Ru({chainBatches:y,signingAddress:w,actions:d.current,cache:p.current,signal:x,onSignatureRequested:v,beforeSign:k}),[]),h=te((y,w,x,v)=>Du(d.current,y,w,x,v),[]),m=te(async(y,w,x,v,k,A)=>{const b=(S,T,E)=>{v?.({step:S,message:T,...E})};if(jr)throw new Ne("CONCURRENT_EXECUTION","A execution transaction is already in progress. Please wait.");jr=!0;try{if(!e)throw new Ne("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const S=A?.userOverride||e,{actionOutputDeposit:T,batches:E}=sl(y,A);let I=E,M=[],W=A?.useCustomTransfers,R=Zi(I),F=null;const N=async()=>{for(let B=0;R.length>0&&B<3;B++)try{F=await Qr(S);break}catch(U){if(k?.aborted)throw new Ne("ABORT","Execution transaction aborted");if(B===2)throw new Ne("RELAYER_ERROR","Unable to read your Spice balance. Please try again before submitting the transaction.",{cause:U});await Bn(1e3)}await A?.validateBeforeSubmit?.(I)};b("building","Preparing your wallet and transaction...");const D=await f(I,S,k,()=>b("signing-delegation","Confirm the authorization in your wallet..."),N);if(b("building","Checking transaction fees and balances..."),k?.aborted)throw new Ne("ABORT","Execution transaction aborted");const L=BigInt(Math.floor(Date.now()/1e3)+3600);if(T){const B=await nl({chainBatches:y,user:S,token:T.token,grossAmount:T.amount,chainAuthorizations:D});I=B.chainBatches,M=[B.outputCredit],W=!0}if(!A?.skipPreSubmitFeeEstimate){let B=!1;if(A?.feeExecutionMode==="user-transfer"&&A.adjustBatchesForEstimate&&Lt.canValidateActionFees()){const U=await Lt.validateActionFees(Rs({user:S,chainBatches:I,tokenAddress:w,tokenTransferAmount:x,exp:Number(L),signature:"0x00",chainAuthorizations:D,useCustomTransfers:W}),{signal:k});s.current=U;const X=await A.adjustBatchesForEstimate({feeEstimate:U,chainBatches:I});B=!X||Ki(I,X),X&&(I=X)}for(let U=0;!B&&U<10;U++){const X=A?.feeExecutionMode==="user-transfer"?qr(I,S):I,pe=Rs({user:S,chainBatches:X,tokenAddress:w,tokenTransferAmount:x,exp:Number(L),signature:"0x00",chainAuthorizations:D,useCustomTransfers:W}),de=await Lt.estimateActionFees(pe,{signal:k});s.current=de;const xe=await A?.adjustBatchesForEstimate?.({feeEstimate:de,chainBatches:I}),K=!!xe&&Ki(I,xe);if(!xe||K){B=!0;break}I=xe}if(!B)throw new Ne("INVALID_PARAMS","Fee estimate did not converge. Please retry.")}if(A?.prepareForSigning){const B=await A.prepareForSigning(I);if(B.length!==I.length||B.some((U,X)=>U.chainId!==I[X].chainId||U.domain!==I[X].domain))throw new Error("The funded route changed before signing");I=B}A?.resolveActionOutputCredits&&(M=await A.resolveActionOutputCredits()),(!A?.skipUserFundingPreflight||A.walletFundingRequirement)&&await Ku(A?.skipUserFundingPreflight?[]:I,S,{actionOutputCredits:M,walletFundingRequirement:A?.walletFundingRequirement}),R=Zi(I),R.length&&!F&&(F=await Ca(S)),await A?.validateBeforeSubmit?.(I),b("building","Preparing the signing request...");const z=await h(I,L,k,()=>b("signing-intent","Confirm the transaction in your wallet..."));if(k?.aborted)throw new Ne("ABORT","Execution transaction aborted");b("submitting","Submitting to relayer...");const fe=Rs({user:S,chainBatches:I,tokenAddress:w,tokenTransferAmount:x,exp:Number(L),signature:z,chainAuthorizations:D,useCustomTransfers:W}),ce=Date.now();await A?.validateBeforeSubmit?.(I),console.debug("[SpiceFlow:execution]",{phase:"submit-check-complete",at:Date.now(),durationMs:Date.now()-ce});const Q=await Lt.createAction(fe),[ne,re]=Q.intentIds[0].split("/"),j=parseInt(re||"0",10),J=`${ne}/${j}`;b("executing","Executing on chain..."),b("executing","Executing on chain...",{actionId:ne,intentId:J,intentIndex:j,totalSteps:I.length});const Y=I.length,me=await Lu({actionId:ne,intentIndex:j,intentId:J,totalSteps:Y,signal:k,...F?{delayBeforeSpicenetStepMs:0}:{},isSpicenetStep:B=>Qn(I[B]),beforeStep:async B=>{if(!F||!Qn(I[B]))return;const U=await Tu({deposits:R,baseline:F,fetchEntries:()=>Qr(S),signal:k});if(k?.aborted)throw new Ne("ABORT","Execution transaction aborted");if(!U)throw new Ne("POLLING_EXHAUSTED","Your deposit is still waiting for Spice credit. Check this transaction's status before trying again.",{actionId:ne,intentId:J,stepId:B})},maxExecuteAttemptsForStep:B=>Qn(I[B])?6:3,maxPolls:180,onStatusMessage:(B,U)=>{b("executing",B,{txHash:U,actionId:ne,intentId:J,intentIndex:j,totalSteps:Y})}});if(A?.requireDestinationReceipt){const B=[...I].reverse().find(U=>!Qn(U));if(!B)throw new Error("The action has no destination transaction to verify.");await Hu(yt(B.chainId),me)}return b("success","Transaction successful!",{txHash:me,actionId:ne,intentId:J,intentIndex:j,totalSteps:Y}),me||ne}catch(S){throw console.error("[Execution] Error:",S),b("error",S.message||"Transaction failed",{error:S.message}),S}finally{jr=!1}},[e,n,f,h]),g=te(async(y,w,x,v)=>{if(!e)throw new Ne("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const k=v?.userOverride||e,A=v?.validateFeeCalls===!0&&v.feeExecutionMode==="user-transfer"&&Lt.canValidateActionFees(),{actionOutputDeposit:b,batches:S}=sl(y,v);let T=S;const E=v?.feeExecutionMode==="user-transfer"&&!A?qr(T,k):T,I=v?.signAuthorizationsForEstimate?await f(E,k):void 0;let M=v?.useCustomTransfers;b&&(T=(await nl({chainBatches:y,user:k,token:b.token,grossAmount:b.amount,chainAuthorizations:I})).chainBatches,M=!0);const W=v?.feeExecutionMode==="user-transfer"&&!A?qr(T,k):T,R=Rs({user:k,chainBatches:W,tokenAddress:w,tokenTransferAmount:x,exp:Math.floor(Date.now()/1e3)+3600,signature:"0x00",chainAuthorizations:I,useCustomTransfers:M}),F=await(A?Lt.validateActionFees(R,{signal:v?.signal}):Lt.estimateActionFees(R,{signal:v?.signal}));return s.current=F,F},[e,f]);return{execute:m,estimate:g,lastFeeEstimate:s.current,hasEmbeddedWallet:t&&n,intentStatus:r,startStatusPolling:a,beginStatusTracking:i,applyStepUpdate:l,clearStatus:c}}const Gr=({color:e})=>C("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:[u("circle",{cx:"7",cy:"7",r:"6.5",stroke:e,strokeWidth:"1.2"}),u("path",{d:"M7 6v4",stroke:e,strokeWidth:"1.2",strokeLinecap:"round"}),u("circle",{cx:"7",cy:"4.5",r:"0.7",fill:e})]}),rl=({content:e,label:t="More info",textColor:n="#f9fafb",backgroundColor:o="#111827",borderColor:s="rgba(255,255,255,0.08)",accentColor:r="#9ca3af",children:a})=>{const i=Ba(),[l,c]=O(!1),d=_(null),[p,f]=O(!1),[h,m]=O(null);ae(()=>{f(!0)},[]),Da(()=>{if(!l||!d.current)return;const y=()=>{if(!d.current)return;const w=d.current.getBoundingClientRect(),x=Math.min(220,window.innerWidth-48),v=Math.min(Math.max(w.left+w.width/2,24+x/2),window.innerWidth-24-x/2),k=w.top>84;m({top:k?w.top-10:w.bottom+10,left:v,placement:k?"top":"bottom"})};return y(),window.addEventListener("scroll",y,!0),window.addEventListener("resize",y),()=>{window.removeEventListener("scroll",y,!0),window.removeEventListener("resize",y)}},[l]);const g=l&&p&&h?fr(C("span",{id:i,role:"tooltip",style:{position:"fixed",left:h.left,top:h.top,transform:h.placement==="top"?"translate(-50%, -100%)":"translate(-50%, 0)",width:"220px",maxWidth:"min(220px, calc(100vw - 48px))",padding:"10px 12px",borderRadius:"10px",backgroundColor:o,color:n,border:`1px solid ${s}`,boxShadow:"0 18px 45px rgba(0,0,0,0.28)",fontSize:"11px",lineHeight:"1.45",fontWeight:500,textAlign:"left",zIndex:ao.tooltip,pointerEvents:"none"},children:[e,u("span",{"aria-hidden":"true",style:{position:"absolute",left:"50%",width:"10px",height:"10px",transform:"translateX(-50%) rotate(45deg)",backgroundColor:o,...h.placement==="top"?{bottom:"-6px",borderRight:`1px solid ${s}`,borderBottom:`1px solid ${s}`}:{top:"-6px",borderTop:`1px solid ${s}`,borderLeft:`1px solid ${s}`}}})]}),document.body):null;return C(an,{children:[u("span",{ref:d,style:{position:"relative",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),children:u("button",{type:"button","aria-label":t,"aria-describedby":l?i:void 0,onFocus:()=>c(!0),onBlur:()=>c(!1),style:{width:"18px",height:"18px",borderRadius:"999px",display:"inline-flex",alignItems:"center",justifyContent:"center",border:`1px solid ${s}`,backgroundColor:"transparent",color:r,cursor:"help",padding:0,outline:"none",boxShadow:l?`0 0 0 2px ${r}26`:"none",transition:"border-color 120ms ease, box-shadow 120ms ease, color 120ms ease"},children:a||u(Gr,{color:r})})}),g]})},Xo=(e,t,n,o)=>({width:e,height:e,fill:"none",className:t,"aria-hidden":n??!0,style:o}),Eo=({size:e=16,color:t="currentColor",strokeWidth:n=2,direction:o="down",className:s,style:r,"aria-hidden":a})=>u("svg",{...Xo(e,s,a,{transform:o==="up"?"rotate(180deg)":void 0,transition:"transform 0.3s ease",...r}),viewBox:"0 0 16 16",children:u("path",{d:"M4 6L8 10L12 6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),Ju=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:o,style:s,"aria-hidden":r})=>C("svg",{...Xo(e,o,r,s),viewBox:"0 0 24 24",children:[u("circle",{cx:"11",cy:"11",r:"8",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"}),u("path",{d:"m21 21-4.3-4.3",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})]}),$u=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:o,style:s,"aria-hidden":r})=>u("svg",{...Xo(e,o,r,s),viewBox:"0 0 24 24",children:u("path",{d:"m6 9 6 6 6-6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),_u=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:o,style:s,"aria-hidden":r})=>u("svg",{...Xo(e,o,r,s),viewBox:"0 0 24 24",children:u("path",{d:"m9 18 6-6-6-6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),al=({size:e=14,color:t="currentColor",strokeWidth:n=2,className:o,style:s,"aria-hidden":r})=>u("svg",{...Xo(e,o,r,s),viewBox:"0 0 16 16",children:u("path",{d:"M3 8L6.5 11.5L13 5",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})});function Ws(e,t){if(e===0n)return"0";const n=10n**BigInt(t),o=e/n,s=(e%n).toString().padStart(t,"0").replace(/0+$/,"");return s?`${o.toString()}.${s}`:o.toString()}function Yr(e,t,n){const o=`${Ws(e,t)} ${n}`;return e===0n?o:`-${o}`}const ep=({fontFamily:e,textPrimary:t,textSecondary:n,cardBg:o,cardBorder:s,resolvedDark:r,darkCardBorder:a,primaryColor:i,feePreview:l,asset:c,isLoading:d,errorText:p,directExecutionFeeNote:f=!1})=>{const h=Rn(),m=c&&l&&[c.symbol,c.displaySymbol,c.receiptTokenName].includes(l.symbol)?h(c).symbol:l?.symbol,g=r?a??s:"#e5e7eb",y=r?"#111214":"#111827",w=r?"rgba(255,255,255,0.08)":"rgba(17,24,39,0.12)",x="#f87171",v=r?"#d1d5db":"#4b5563",k=r?"#f3f4f6":t,[A,b]=O(!1),S=!!p,T=S?null:l,E=T?[{label:"Total Required",help:"Total amount required to fund this action.",value:`${Ws(T.grossAmount,T.decimals)} ${m}`,tone:"default"},{label:"Spicenet Fee",help:"Fees paid to Spicenet for intent processing and execution.",value:Yr(T.spicenetFee,T.decimals,m),tone:"fee"},{label:"Network Fee",help:"Network fee shown in the same token you are using for this action.",value:Yr(T.gasFee,T.decimals,m),tone:"fee"},...T.bridgeFee&&T.bridgeFee>0n?[{label:"Bridge Fee",help:"Estimated cost to rebalance liquidity for this action.",value:Yr(T.bridgeFee,T.decimals,m),tone:"fee"}]:[],{label:"Used in TX",help:"Resulting amount of funds used in the transaction.",value:`${Ws(T.netAmount,T.decimals)} ${m}`,tone:"default"}]:[],I=T?`${Ws(T.grossAmount,T.decimals)} ${m}`:null;return S?u("div",{style:{backgroundColor:o,border:`1px solid ${s}`,borderRadius:r?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",boxShadow:r?"inset 0 1px 0 rgba(255,255,255,0.03)":"none"},children:C("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:[u("span",{style:{fontSize:"17px",fontWeight:500,color:v,fontFamily:e,lineHeight:"24px"},children:"Fee"}),u("div",{style:{color:x,fontSize:"12px",lineHeight:"1.55",fontFamily:e},children:p})]})}):C("div",{style:{backgroundColor:o,border:`1px solid ${s}`,borderRadius:r?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",boxShadow:r?"inset 0 1px 0 rgba(255,255,255,0.03)":"none"},children:[C("button",{type:"button",onClick:()=>b(M=>!M),style:{display:"flex",justifyContent:"space-between",alignItems:"center",width:"100%",gap:"12px",marginBottom:A?"14px":0,background:"none",border:"none",padding:0,cursor:"pointer",textAlign:"left"},children:[C("div",{style:{display:"flex",flexDirection:"column",gap:"4px"},children:[u("span",{style:{fontSize:"17px",fontWeight:500,color:v,fontFamily:e,lineHeight:"24px"},children:"Fee"}),A&&u("span",{style:{fontSize:"12px",color:n,fontFamily:e,lineHeight:"1.45"},children:"What is funded, spent, and taken as fees"})]}),C("div",{style:{display:"flex",alignItems:"center",gap:"8px",flexShrink:0},children:[I&&C("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:"2px",minWidth:0},children:[u("span",{style:{fontSize:"10px",fontWeight:700,color:n,fontFamily:e,letterSpacing:"0.08em",textTransform:"uppercase"},children:"Total required"}),u("span",{style:{fontSize:"14px",fontWeight:700,color:k,fontFamily:e,whiteSpace:"nowrap"},children:I})]}),d&&!f&&u("span",{style:{fontSize:"11px",fontWeight:600,color:i,fontFamily:e,padding:"6px 9px",borderRadius:"999px",backgroundColor:r?"rgba(255,255,255,0.04)":"rgba(0,0,0,0.035)",border:`1px solid ${r?g:"rgba(0,0,0,0.06)"}`,whiteSpace:"nowrap"},children:"Recalculating"}),u(Eo,{color:n,direction:A?"up":"down",style:{flexShrink:0}})]})]}),u("div",{style:{overflow:"hidden",maxHeight:A?"480px":"0px",opacity:A?1:0,transition:"max-height 0.24s ease, opacity 0.18s ease"},children:f?u("p",{style:{margin:0,color:n,fontSize:"12px",lineHeight:"1.55",fontFamily:e},children:"This path executes directly from the external wallet. Network gas is shown and paid in your wallet. No Spicenet fee is charged."}):E.length>0?C(an,{children:[u("div",{style:{display:"grid",gap:"10px"},children:E.map((M,W)=>C("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) auto",alignItems:"center",gap:"12px",paddingTop:W===0?0:"10px",borderTop:W===0?"none":`1px solid ${g}`,opacity:d?.74:1,transition:"opacity 120ms ease"},children:[C("div",{style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0},children:[u("span",{style:{fontSize:"12px",color:n,fontFamily:e,fontWeight:500},children:M.label}),u(rl,{content:M.help,label:`${M.label} info`,textColor:"#f9fafb",backgroundColor:y,borderColor:w,accentColor:r?"#8f96a3":"#6b7280"})]}),u("span",{style:{fontSize:"12px",color:M.tone==="fee"?x:k,fontFamily:Oe.mono,textAlign:"right",fontWeight:M.label==="Used in TX"?600:500,letterSpacing:"-0.01em"},children:M.value})]},M.label))}),u("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:`1px solid ${g}`,fontSize:"11px",color:n,fontFamily:e,lineHeight:"1.45"},children:T?.gasQuoteSource==="estimated"?"Gas quote uses a live estimate.":T?.gasQuoteSource==="configured_fallback"?"Gas quote uses a configured fallback.":"Gas quote is currently zero."})]}):u("div",{style:{fontSize:"12px",color:p?x:n,fontFamily:e,opacity:p?1:.8,lineHeight:"1.5"},children:p||"Waiting for fee estimate..."})})]})},Kr=yn(ep),Jo=({size:e=20,strokeWidth:t=2,color:n="currentColor",style:o})=>C("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:[u("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),u("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]});var il="data:image/svg+xml,%3csvg width='108' height='22' viewBox='0 0 108 22' fill='none' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M1.9916 11.9854V11.2041H3.98379C4.48835 11.2041 4.87897 11.0739 5.15566 10.8135C5.43236 10.5498 5.5707 10.1868 5.5707 9.72461V9.71484C5.5707 9.24935 5.43236 8.88639 5.15566 8.62598C4.87897 8.36556 4.48835 8.23535 3.98379 8.23535H1.9916V7.4541H4.2084C4.65111 7.4541 5.04173 7.5485 5.38027 7.7373C5.71882 7.92611 5.98411 8.18978 6.17617 8.52832C6.37148 8.86686 6.46914 9.25911 6.46914 9.70508V9.71484C6.46914 10.1608 6.37148 10.5547 6.17617 10.8965C5.98411 11.2383 5.71882 11.5052 5.38027 11.6973C5.04173 11.8893 4.65111 11.9854 4.2084 11.9854H1.9916ZM1.55215 14.5V7.4541H2.43106V14.5H1.55215ZM9.51875 14.5928C9.0207 14.5928 8.58939 14.4837 8.2248 14.2656C7.86348 14.0443 7.58353 13.7301 7.38496 13.3232C7.18965 12.9163 7.09199 12.4329 7.09199 11.873V11.8633C7.09199 11.3001 7.18965 10.8151 7.38496 10.4082C7.58353 10.0013 7.86348 9.6888 8.2248 9.4707C8.58939 9.2526 9.0207 9.14355 9.51875 9.14355C10.0201 9.14355 10.4514 9.2526 10.8127 9.4707C11.174 9.6888 11.4523 10.0013 11.6477 10.4082C11.8462 10.8151 11.9455 11.3001 11.9455 11.8633V11.873C11.9455 12.4329 11.8462 12.9163 11.6477 13.3232C11.4523 13.7301 11.174 14.0443 10.8127 14.2656C10.4514 14.4837 10.0201 14.5928 9.51875 14.5928ZM9.51875 13.8408C9.85078 13.8408 10.1324 13.7627 10.3635 13.6064C10.5946 13.4502 10.7704 13.2256 10.8908 12.9326C11.0145 12.6396 11.0764 12.2865 11.0764 11.873V11.8633C11.0764 11.4466 11.0145 11.0918 10.8908 10.7988C10.7704 10.5059 10.5946 10.2829 10.3635 10.1299C10.1324 9.97363 9.85078 9.89551 9.51875 9.89551C9.18672 9.89551 8.90514 9.97363 8.67402 10.1299C8.4429 10.2829 8.26549 10.5059 8.1418 10.7988C8.02135 11.0918 7.96113 11.4466 7.96113 11.8633V11.873C7.96113 12.2865 8.02135 12.6396 8.1418 12.9326C8.26549 13.2256 8.4429 13.4502 8.67402 13.6064C8.90514 13.7627 9.18672 13.8408 9.51875 13.8408ZM13.7842 14.5L12.3096 9.23633H13.1592L14.1943 13.4453H14.2725L15.4492 9.23633H16.2549L17.4316 13.4453H17.5098L18.5449 9.23633H19.3896L17.915 14.5H17.0605L15.8838 10.4277H15.8057L14.6338 14.5H13.7842ZM22.1658 14.5928C21.6645 14.5928 21.2332 14.4821 20.8719 14.2607C20.5138 14.0394 20.2371 13.7269 20.0418 13.3232C19.8497 12.9163 19.7537 12.4378 19.7537 11.8877V11.8828C19.7537 11.3392 19.8497 10.8623 20.0418 10.4521C20.2371 10.042 20.5122 9.72135 20.867 9.49023C21.2218 9.25911 21.6368 9.14355 22.1121 9.14355C22.5906 9.14355 23.0008 9.25423 23.3426 9.47559C23.6876 9.69694 23.9513 10.0062 24.1336 10.4033C24.3191 10.7972 24.4119 11.2562 24.4119 11.7803V12.1123H20.1932V11.4336H23.9773L23.5574 12.0537V11.7168C23.5574 11.3034 23.4956 10.9632 23.3719 10.6963C23.2482 10.4294 23.0773 10.2308 22.8592 10.1006C22.6411 9.96712 22.3904 9.90039 22.1072 9.90039C21.824 9.90039 21.5701 9.97038 21.3455 10.1104C21.1242 10.2471 20.9484 10.4505 20.8182 10.7207C20.688 10.9909 20.6229 11.3229 20.6229 11.7168V12.0537C20.6229 12.4281 20.6863 12.7487 20.8133 13.0156C20.9402 13.2793 21.1209 13.4827 21.3553 13.626C21.5896 13.766 21.8663 13.8359 22.1854 13.8359C22.423 13.8359 22.6297 13.8034 22.8055 13.7383C22.9813 13.6732 23.1261 13.5902 23.24 13.4893C23.354 13.3883 23.4337 13.2858 23.4793 13.1816L23.4988 13.1377H24.3484L24.3387 13.1768C24.2931 13.3558 24.2117 13.5299 24.0945 13.6992C23.9806 13.8652 23.8325 14.0166 23.6502 14.1533C23.4679 14.2868 23.2514 14.3942 23.0008 14.4756C22.7534 14.5537 22.4751 14.5928 22.1658 14.5928ZM25.4303 14.5V9.23633H26.2799V10.0176H26.358C26.4589 9.74089 26.6298 9.52604 26.8707 9.37305C27.1116 9.22005 27.4094 9.14355 27.7643 9.14355C27.8456 9.14355 27.9254 9.14844 28.0035 9.1582C28.0849 9.16471 28.1467 9.17122 28.1891 9.17773V10.0029C28.1012 9.98665 28.0149 9.97526 27.9303 9.96875C27.8489 9.95898 27.761 9.9541 27.6666 9.9541C27.3964 9.9541 27.1572 10.0078 26.9488 10.1152C26.7405 10.2227 26.5761 10.3724 26.4557 10.5645C26.3385 10.7565 26.2799 10.9811 26.2799 11.2383V14.5H25.4303ZM30.9408 14.5928C30.4395 14.5928 30.0082 14.4821 29.6469 14.2607C29.2888 14.0394 29.0121 13.7269 28.8168 13.3232C28.6247 12.9163 28.5287 12.4378 28.5287 11.8877V11.8828C28.5287 11.3392 28.6247 10.8623 28.8168 10.4521C29.0121 10.042 29.2872 9.72135 29.642 9.49023C29.9968 9.25911 30.4118 9.14355 30.8871 9.14355C31.3656 9.14355 31.7758 9.25423 32.1176 9.47559C32.4626 9.69694 32.7263 10.0062 32.9086 10.4033C33.0941 10.7972 33.1869 11.2562 33.1869 11.7803V12.1123H28.9682V11.4336H32.7523L32.3324 12.0537V11.7168C32.3324 11.3034 32.2706 10.9632 32.1469 10.6963C32.0232 10.4294 31.8523 10.2308 31.6342 10.1006C31.4161 9.96712 31.1654 9.90039 30.8822 9.90039C30.599 9.90039 30.3451 9.97038 30.1205 10.1104C29.8992 10.2471 29.7234 10.4505 29.5932 10.7207C29.463 10.9909 29.3979 11.3229 29.3979 11.7168V12.0537C29.3979 12.4281 29.4613 12.7487 29.5883 13.0156C29.7152 13.2793 29.8959 13.4827 30.1303 13.626C30.3646 13.766 30.6413 13.8359 30.9604 13.8359C31.198 13.8359 31.4047 13.8034 31.5805 13.7383C31.7563 13.6732 31.9011 13.5902 32.015 13.4893C32.129 13.3883 32.2087 13.2858 32.2543 13.1816L32.2738 13.1377H33.1234L33.1137 13.1768C33.0681 13.3558 32.9867 13.5299 32.8695 13.6992C32.7556 13.8652 32.6075 14.0166 32.4252 14.1533C32.2429 14.2868 32.0264 14.3942 31.7758 14.4756C31.5284 14.5537 31.2501 14.5928 30.9408 14.5928ZM36.1486 14.5928C35.7059 14.5928 35.3186 14.4805 34.9865 14.2559C34.6545 14.0312 34.3973 13.7155 34.215 13.3086C34.0328 12.8984 33.9416 12.4199 33.9416 11.873V11.8633C33.9416 11.3132 34.0328 10.8346 34.215 10.4277C34.3973 10.0208 34.6529 9.70508 34.9816 9.48047C35.3137 9.25586 35.7027 9.14355 36.1486 9.14355C36.3895 9.14355 36.6158 9.18262 36.8273 9.26074C37.0422 9.33561 37.2326 9.44141 37.3986 9.57812C37.5647 9.71484 37.6949 9.8776 37.7893 10.0664H37.8674V7.14648H38.717V14.5H37.8674V13.6602H37.7893C37.6818 13.8555 37.5467 14.0231 37.384 14.1631C37.2212 14.2998 37.0357 14.4056 36.8273 14.4805C36.619 14.5553 36.3928 14.5928 36.1486 14.5928ZM36.3439 13.8408C36.663 13.8408 36.938 13.7611 37.1691 13.6016C37.4003 13.4421 37.5777 13.2158 37.7014 12.9229C37.8251 12.6266 37.8869 12.2767 37.8869 11.873V11.8633C37.8869 11.4564 37.8251 11.1064 37.7014 10.8135C37.5777 10.5205 37.4003 10.2943 37.1691 10.1348C36.938 9.97526 36.663 9.89551 36.3439 9.89551C36.0249 9.89551 35.7499 9.97526 35.5188 10.1348C35.2909 10.291 35.1151 10.5156 34.9914 10.8086C34.871 11.1016 34.8107 11.4531 34.8107 11.8633V11.873C34.8107 12.2799 34.871 12.6315 34.9914 12.9277C35.1151 13.2207 35.2909 13.4469 35.5188 13.6064C35.7499 13.7627 36.0249 13.8408 36.3439 13.8408ZM45.1775 14.5928C44.9334 14.5928 44.7072 14.5553 44.4988 14.4805C44.2905 14.4056 44.1049 14.2998 43.9422 14.1631C43.7794 14.0231 43.6443 13.8555 43.5369 13.6602H43.4588V14.5H42.6092V7.14648H43.4588V10.0664H43.5369C43.6346 9.8776 43.7648 9.71484 43.9275 9.57812C44.0936 9.44141 44.2824 9.33561 44.4939 9.26074C44.7088 9.18262 44.9367 9.14355 45.1775 9.14355C45.6235 9.14355 46.0109 9.25586 46.3396 9.48047C46.6717 9.70508 46.9288 10.0208 47.1111 10.4277C47.2934 10.8346 47.3846 11.3132 47.3846 11.8633V11.873C47.3846 12.4199 47.2934 12.8984 47.1111 13.3086C46.9288 13.7155 46.6717 14.0312 46.3396 14.2559C46.0109 14.4805 45.6235 14.5928 45.1775 14.5928ZM44.9822 13.8408C45.3045 13.8408 45.5796 13.7627 45.8074 13.6064C46.0353 13.4469 46.2094 13.2207 46.3299 12.9277C46.4536 12.6315 46.5154 12.2799 46.5154 11.873V11.8633C46.5154 11.4531 46.4536 11.1016 46.3299 10.8086C46.2094 10.5156 46.0353 10.291 45.8074 10.1348C45.5796 9.97526 45.3045 9.89551 44.9822 9.89551C44.6632 9.89551 44.3881 9.97526 44.157 10.1348C43.9259 10.2943 43.7485 10.5205 43.6248 10.8135C43.5011 11.1064 43.4393 11.4564 43.4393 11.8633V11.873C43.4393 12.2767 43.5011 12.6266 43.6248 12.9229C43.7485 13.2158 43.9259 13.4421 44.157 13.6016C44.3881 13.7611 44.6632 13.8408 44.9822 13.8408ZM48.6568 16.3457C48.6015 16.3457 48.5396 16.3424 48.4713 16.3359C48.4029 16.3327 48.3395 16.3262 48.2809 16.3164V15.6182C48.3329 15.6279 48.3899 15.6344 48.4518 15.6377C48.5136 15.641 48.5738 15.6426 48.6324 15.6426C48.8733 15.6426 49.0702 15.5807 49.2232 15.457C49.3795 15.3333 49.5048 15.1201 49.5992 14.8174L49.6969 14.5049L47.7486 9.23633H48.6568L50.2779 14.0996L49.941 13.5674H50.3414L50.0045 14.0996L51.6207 9.23633H52.5143L50.4586 14.8223C50.3154 15.2161 50.164 15.5238 50.0045 15.7451C49.845 15.9665 49.6578 16.1211 49.443 16.209C49.2314 16.3001 48.9693 16.3457 48.6568 16.3457Z' fill='%230E0D0B'/%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%3cpath fill-rule='evenodd' clip-rule='evenodd' d='M74.8537 10.0096C75.2721 10.0096 75.654 10.1125 75.9993 10.3184C76.3513 10.5177 76.6303 10.8032 76.8361 11.1751C77.0487 11.547 77.1549 11.9953 77.1549 12.52V12.6495C77.1549 13.1675 77.052 13.6158 76.8461 13.9943C76.6402 14.3729 76.3613 14.6618 76.0093 14.861C75.664 15.0603 75.2788 15.1599 74.8537 15.1599C74.515 15.1599 74.2261 15.1134 73.9871 15.0204C73.7546 14.9341 73.5653 14.8212 73.4192 14.6817C73.2731 14.5423 73.1602 14.3995 73.0805 14.2534H72.941V16.9659L72.1541 16.0013V10.1491H72.9211V10.956H73.0352C73.2729 10.6733 73.3893 10.4911 73.6683 10.2985C73.9538 10.1059 74.349 10.0096 74.8537 10.0096ZM74.6445 10.7069C74.1464 10.7069 73.7347 10.8696 73.4092 11.195C73.0905 11.5138 72.9311 11.9621 72.9311 12.5399V12.6296C72.9311 13.2074 73.0905 13.659 73.4092 13.9844C73.7347 14.3032 74.1464 14.4626 74.6445 14.4626C75.1492 14.4626 75.5577 14.3032 75.8698 13.9844C76.1886 13.659 76.348 13.2074 76.348 12.6296V12.5399C76.348 11.9621 76.1886 11.5138 75.8698 11.195C75.5577 10.8696 75.1492 10.7069 74.6445 10.7069Z' fill='%230E0D0B'/%3e%3cpath d='M78.5848 11.9583L78.5555 15.4596L77.7681 14.4846V10.9583L78.5848 11.9583Z' fill='%230E0D0B'/%3e%3cpath d='M101.588 10.2986H102.444L103 10.986H101.588V10.9867H100.802L101.588 11.9623V14.1937C101.588 14.3929 101.685 14.4926 101.877 14.4926H102.379L102.928 15.17H101.668C101.389 15.17 101.173 15.0936 101.021 14.9409C100.874 14.7881 100.801 14.5789 100.801 14.3133V10.986H99.8799L99.3217 10.2986H100.801V9.13501H101.588V10.2986Z' fill='%230E0D0B'/%3e%3cpath d='M69.0133 7.90764C69.4848 7.90764 69.9065 7.99068 70.2784 8.15671C70.6569 8.3161 70.9525 8.55517 71.165 8.87395C71.3842 9.18609 71.4938 9.58126 71.4938 10.0594V10.4778H70.667V10.0594C70.667 9.72072 70.5939 9.44842 70.4477 9.24254C70.3083 9.03666 70.1124 8.88392 69.86 8.7843C69.6143 8.68469 69.332 8.63487 69.0133 8.63487C68.555 8.63487 68.1864 8.7378 67.9075 8.94367C67.6286 9.14291 67.4891 9.4285 67.4891 9.80041C67.4891 10.0461 67.5488 10.2453 67.6684 10.3981C67.7879 10.5508 67.9573 10.677 68.1764 10.7767C68.3956 10.8696 68.658 10.9527 68.9635 11.0257L69.4815 11.1552C69.8866 11.2416 70.2485 11.3611 70.5673 11.5138C70.8927 11.6599 71.1517 11.8625 71.3443 12.1215C71.5369 12.3739 71.6332 12.706 71.6332 13.1177C71.6332 13.5295 71.5303 13.8881 71.3244 14.1936C71.1185 14.4991 70.8263 14.7382 70.4477 14.9109C70.0758 15.0769 69.6375 15.1599 69.1328 15.1599C68.6281 15.1599 68.1765 15.0702 67.778 14.8909C67.3795 14.7116 67.0641 14.4426 66.8316 14.084C66.6058 13.7187 66.4929 13.2638 66.4929 12.7192V12.51H67.3197V12.7192C67.3197 13.297 67.4891 13.7287 67.8278 14.0143C68.1665 14.2932 68.6015 14.4327 69.1328 14.4327C69.6774 14.4327 70.0924 14.3098 70.378 14.0641C70.6636 13.8183 70.8064 13.5095 70.8064 13.1376C70.8064 12.8786 70.74 12.6727 70.6072 12.52C70.481 12.3673 70.3017 12.2444 70.0692 12.1514C69.8368 12.0518 69.5645 11.9655 69.2523 11.8924L68.7343 11.7629C68.3292 11.6566 67.9706 11.5271 67.6584 11.3744C67.3463 11.2216 67.1006 11.0224 66.9213 10.7767C66.7486 10.5243 66.6623 10.2022 66.6623 9.81035C66.6623 9.41852 66.7585 9.07981 66.9511 8.79424C67.1504 8.50866 67.426 8.28953 67.778 8.13678C68.1366 7.98404 68.5484 7.90764 69.0133 7.90764Z' fill='%230E0D0B'/%3e%3cpath d='M81.6544 10.0096C82.1193 10.0096 82.5145 10.0959 82.8399 10.2686C83.1719 10.4412 83.431 10.6704 83.6169 10.956C83.8095 11.2415 83.9324 11.5471 83.9855 11.8725L83.2185 12.0318C83.1853 11.7928 83.1056 11.5736 82.9794 11.3744C82.8598 11.1752 82.6905 11.0158 82.4713 10.8962C82.2521 10.7767 81.9832 10.7169 81.6644 10.7169C81.339 10.7169 81.0468 10.7899 80.7877 10.936C80.5354 11.0821 80.3328 11.2914 80.1801 11.5637C80.034 11.836 79.9609 12.1614 79.9609 12.5399V12.6296C79.9609 13.0081 80.034 13.3335 80.1801 13.6058C80.3328 13.8781 80.5354 14.0873 80.7877 14.2334C81.0468 14.3795 81.339 14.4526 81.6644 14.4526C82.1492 14.4526 82.5178 14.3264 82.7702 14.0741C83.0292 13.8217 83.1886 13.5095 83.2483 13.1376L84.0254 13.307C83.9523 13.6257 83.8195 13.9279 83.6269 14.2135C83.4343 14.4991 83.172 14.7282 82.8399 14.9009C82.5145 15.0735 82.1193 15.1599 81.6544 15.1599C81.1829 15.1599 80.7579 15.0603 80.3793 14.861C80.0074 14.6551 79.7119 14.363 79.4927 13.9844C79.2802 13.6059 79.1739 13.1575 79.1739 12.6395V12.5299C79.1739 12.0053 79.2802 11.557 79.4927 11.1851C79.7119 10.8066 80.0074 10.5177 80.3793 10.3184C80.7579 10.1126 81.1829 10.0096 81.6544 10.0096Z' fill='%230E0D0B'/%3e%3cpath fill-rule='evenodd' clip-rule='evenodd' d='M86.7515 10.0096C87.2097 10.0096 87.6149 10.1092 87.9668 10.3084C88.3188 10.501 88.5944 10.78 88.7937 11.1452C88.9929 11.5105 89.0925 11.9389 89.0925 12.4304V12.7889H85.1177C85.1377 13.3136 85.3071 13.7254 85.6258 14.0243C85.9446 14.3165 86.3431 14.4626 86.8212 14.4626C87.2396 14.4626 87.5617 14.3663 87.7875 14.1737C88.0133 13.9811 88.186 13.752 88.3056 13.4863L88.983 13.815C88.8833 14.0209 88.7439 14.2268 88.5646 14.4327C88.3919 14.6386 88.1628 14.8113 87.8772 14.9507C87.5983 15.0902 87.2396 15.1599 86.8013 15.1599C86.3099 15.1599 85.8782 15.057 85.5063 14.8511C85.1344 14.6386 84.8455 14.343 84.6396 13.9645C84.4337 13.5859 84.3307 13.1476 84.3307 12.6495V12.5299C84.3307 12.0252 84.4337 11.5836 84.6396 11.205C84.8455 10.8265 85.1311 10.5342 85.4963 10.3284C85.8616 10.1159 86.28 10.0096 86.7515 10.0096ZM86.7515 10.7069C86.3066 10.7069 85.9413 10.8331 85.6557 11.0855C85.3701 11.3378 85.1941 11.6898 85.1277 12.1414H88.2956C88.269 11.6898 88.113 11.3378 87.8274 11.0855C87.5485 10.8331 87.1898 10.7069 86.7515 10.7069Z' fill='%230E0D0B'/%3e%3cpath fill-rule='evenodd' clip-rule='evenodd' d='M97.1624 10.0096C97.6207 10.0096 98.0258 10.1092 98.3778 10.3084C98.7298 10.501 99.0054 10.78 99.2046 11.1452C99.4039 11.5105 99.5035 11.9389 99.5035 12.4304V12.7889H95.5287C95.5487 13.3136 95.718 13.7254 96.0368 14.0243C96.3555 14.3165 96.754 14.4626 97.2322 14.4626C97.6505 14.4626 97.9727 14.3663 98.1985 14.1737C98.4243 13.9811 98.5969 13.752 98.7165 13.4863L99.3939 13.815C99.2943 14.0209 99.1548 14.2268 98.9755 14.4327C98.8028 14.6386 98.5737 14.8113 98.2881 14.9507C98.0092 15.0902 97.6506 15.1599 97.2123 15.1599C96.7208 15.1599 96.2892 15.057 95.9172 14.8511C95.5453 14.6386 95.2564 14.343 95.0505 13.9645C94.8446 13.5859 94.7417 13.1476 94.7417 12.6495V12.5299C94.7417 12.0252 94.8446 11.5836 95.0505 11.205C95.2564 10.8265 95.542 10.5342 95.9073 10.3284C96.2725 10.1158 96.6909 10.0096 97.1624 10.0096ZM97.1624 10.7069C96.7175 10.7069 96.3522 10.8331 96.0666 11.0855C95.7811 11.3378 95.6051 11.6898 95.5387 12.1414H98.7066C98.68 11.6898 98.5239 11.3378 98.2383 11.0855C97.9594 10.8331 97.6008 10.7069 97.1624 10.7069Z' fill='%230E0D0B'/%3e%3cpath d='M92.2484 10.0594C92.6137 10.0594 92.9391 10.1358 93.2247 10.2885C93.5169 10.4413 93.7494 10.6671 93.9221 10.966C94.0947 11.2648 94.1811 11.6334 94.1811 12.0717V15.1458H93.394V12.1315C93.394 11.6467 93.2712 11.2947 93.0255 11.0755C92.7864 10.8564 92.461 10.7468 92.0492 10.7468C91.5777 10.7468 91.1925 10.8995 90.8936 11.205C90.6014 11.5105 90.4553 11.9655 90.4553 12.5698V15.1458H89.6683V10.1491H90.4354V10.9582H90.5361C90.7355 10.7018 90.8604 10.5342 91.1128 10.3483C91.3718 10.1557 91.7503 10.0594 92.2484 10.0594Z' fill='%230E0D0B'/%3e%3cpath d='M78.5932 10.9581H77.7681V10.1514H78.6L78.5932 10.9581Z' fill='%230E0D0B'/%3e%3c/svg%3e";const ll=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(","),Dn=({isOpen:e,onClose:t,title:n,subtitle:o,children:s,overlayContent:r,overlayDimmed:a=!0,styles:i,theme:l,maxWidth:c="522px",dark:d,footerLinkText:p,bannerSrc:f,bannerAlt:h,closeOnBackdropClick:m=!1})=>{const{theme:g,dark:y,dk:w,palette:x}=Bt(i,d),v=d??y,k=l||g,A=i?.fontFamily||k.typography.fontFamily||Oe.ui,b=i?.primaryColor||k.colors.primary,S=_(null),T=_(null),E=_(null),I=Ba(),[M,W]=O(!1),[R,F]=O(!1),N=_(t);if(ae(()=>{N.current=t},[t]),ae(()=>{if(!e){F(!1);return}T.current=document.activeElement;const z=document.body.style.overflow;document.body.style.overflow="hidden";const fe=requestAnimationFrame(()=>{const re=requestAnimationFrame(()=>F(!0));E.current=re}),ce=()=>{const re=S.current;re&&(re.querySelectorAll(ll)[0]??re).focus({preventScroll:!0})},Q=re=>{if(re.key==="Escape"){re.stopPropagation(),N.current();return}if(re.key!=="Tab")return;const j=S.current;if(!j)return;const J=Array.from(j.querySelectorAll(ll)).filter(U=>!U.hasAttribute("aria-hidden"));if(J.length===0){re.preventDefault(),j.focus();return}const Y=J[0],me=J[J.length-1],B=document.activeElement;re.shiftKey&&B===Y?(re.preventDefault(),me.focus()):!re.shiftKey&&B===me&&(re.preventDefault(),Y.focus())},ne=requestAnimationFrame(ce);return document.addEventListener("keydown",Q),()=>{cancelAnimationFrame(ne),cancelAnimationFrame(fe),E.current&&cancelAnimationFrame(E.current),document.removeEventListener("keydown",Q),document.body.style.overflow=z;const re=T.current;re&&typeof re.focus=="function"&&re.focus({preventScroll:!0})}},[e]),!e)return null;const D=!!f&&!M,L=h??"";return u("div",{onMouseDown:z=>{m&&z.target===z.currentTarget&&N.current()},style:{position:"fixed",inset:0,backgroundColor:v?"rgba(0,0,0,0.72)":"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",padding:"clamp(16px, 4vw, 48px)",zIndex:ao.modal,opacity:R?1:0,transition:`opacity ${nr.normal} ${wo.out}`},children:u("div",{ref:S,role:"dialog","aria-modal":"true","aria-labelledby":I,tabIndex:-1,style:{backgroundColor:x.shellBorder,borderRadius:"12px",padding:"5px",width:"100%",maxWidth:c,boxSizing:"border-box",boxShadow:"0 16px 48px rgba(0, 0, 0, 0.4)",outline:"none",transform:R?"scale(1)":"scale(0.96)",transition:`transform ${nr.slow} ${wo.out}`,display:"flex",flexDirection:"column",maxHeight:"100%"},children:C("div",{style:{backgroundColor:x.shell,border:`1px solid ${x.shellInnerBorder}`,borderRadius:"9px",width:"100%",padding:"0",display:"flex",flexDirection:"column",position:"relative",flex:"0 1 auto",minHeight:0,overflowY:"auto",overflowX:"hidden"},children:[r&&a&&u("div",{style:{position:"absolute",inset:0,backgroundColor:"rgba(0, 0, 0, 0.4)",zIndex:5,pointerEvents:"none",borderRadius:"12px"},"aria-hidden":"true"}),D&&C("div",{style:{position:"relative",width:"100%"},children:[u("img",{src:f,style:{width:"100%",height:"auto",display:"block",borderRadius:"6px 6px 0 0"},alt:L,"aria-hidden":L===""?"true":void 0,onError:()=>W(!0)}),u("button",{type:"button",onClick:t,"aria-label":"Close dialog",style:{position:"absolute",top:"8px",right:"8px",minWidth:"44px",minHeight:"44px",color:x.textPrimary,padding:"8px",backgroundColor:"transparent",borderRadius:"9999px",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1},children:u(Jo,{size:28,strokeWidth:2.5})})]}),C("div",{style:{padding:"28px 28px 0 28px",position:"relative"},children:[!D&&u("button",{type:"button",onClick:t,"aria-label":"Close dialog",style:{position:"absolute",top:"10px",right:"10px",minWidth:"44px",minHeight:"44px",color:x.textSecondary,padding:"10px",backgroundColor:"transparent",borderRadius:"50%",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.2s",fontSize:"18px",fontWeight:"600"},onMouseEnter:z=>{z.currentTarget.style.backgroundColor=v?`${b}1a`:"#f3f4f6"},onMouseLeave:z=>{z.currentTarget.style.backgroundColor="transparent"},children:u(Jo,{size:24,strokeWidth:2.4})}),u("h2",{id:I,style:{fontSize:"22px",fontWeight:"700",color:x.textPrimary,margin:"0",fontFamily:A,lineHeight:"1.12"},children:n})]}),o&&u("div",{style:{padding:"11px 28px 13px 28px",fontSize:"12px",color:x.textSecondary,margin:"0",lineHeight:"1.35",fontFamily:A,borderBottom:v?`1px solid ${w.cardBorder}`:"1px solid #cdcfd1"},children:o}),s,C("div",{style:{padding:"12px 28px",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[u("img",{src:il,alt:"","aria-hidden":"true",width:108,height:22,decoding:"async",style:{width:"108px",height:"22px",opacity:v?.85:1,filter:v?"brightness(0) invert(1)":"none",margin:0,display:"block"}}),u("a",{href:"https://spiceflow-docs.spicenet.io",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"10px",color:x.textSecondary,textDecoration:"none",display:"flex",alignItems:"center",gap:"4px",fontFamily:A,lineHeight:"1"},children:u("span",{style:{color:b,textDecoration:"underline",fontWeight:"500"},children:p??"Learn more \u2192"})})]}),r]})})})},cl=({dk:e,dark:t,message:n,buttonLabel:o,onAction:s,disabled:r=!1})=>C("div",{style:{padding:"12px",backgroundColor:e.warningBg,borderRadius:"8px",border:`1px solid ${e.warningBorder}`},children:[u("p",{style:{margin:"0 0 10px 0",color:e.warningText,fontSize:"14px"},children:n}),u("button",{onClick:s,disabled:r,style:{width:"100%",padding:"8px 12px",borderRadius:"6px",border:`1px solid ${t?e.warningBorder:"#fbbf24"}`,backgroundColor:t?e.cardBg:"white",cursor:r?"not-allowed":"pointer",fontWeight:600,fontSize:"13px",color:e.warningText,opacity:r?.6:1},children:o})]}),dl=({dk:e,dark:t,borderRadius:n,children:o})=>u("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:t?e.warningBg:"#fffbeb",border:`1px solid ${e.warningBorder}`,borderRadius:n,fontSize:"12px",color:e.warningText,lineHeight:"1.4"},children:o});async function tp(e,t,n){let o=null;try{const s=await e.request({method:"eth_chainId"});o=parseInt(s,16)}catch{o=null}o!==t&&(n?.(),await ka(e,t))}function ul(e){let t=e;const n=new Set;for(;t&&typeof t=="object"&&!n.has(t);){if(n.add(t),t.code===4001)return!0;t=t.cause}return!1}async function Zr(e){const t=e.provider??await e.wallet?.getEthereumProvider();if(!t)throw new Error("External wallet provider not available");await tp(t,e.chainId,e.onSwitch);const n=await t.request({method:"eth_accounts"});if(!Array.isArray(n)||!n.some(s=>typeof s=="string"&&s.toLowerCase()===e.account.toLowerCase()))throw new Error("The connected source wallet changed. Reconnect the selected account before funding.");const o=Ge(e.chainId)?.viemChain;return{extWc:cr({account:e.account,chain:o,transport:dr(t)}),viemChain:o}}async function pl(e,t,n){const o=Date.now()+1e4;for(;Date.now()<o;){let s;try{s=await Promise.all([t.getBlockNumber({cacheTime:0}),e.request({method:"eth_blockNumber"}).then(BigInt)])}catch{return}if(s.every(r=>r>=n))return;await new Promise(r=>setTimeout(r,250))}}async function np(e){let t;for(const[n,o]of e.calls.entries()){await e.observer?.onSending?.(n);let s;try{s=await e.extWc.sendTransaction({to:o.to,data:o.data,value:o.value,chain:e.viemChain})}catch(i){throw ul(i)&&e.observer?.onRejected?.(n),i}e.observer?.onSubmitted?.(n,s);const r=await Ds({client:e.client,hash:s,call:o,onRepriced:i=>e.observer?.onSubmitted?.(n,i),onCancelled:()=>e.observer?.onReverted?.(n,s)});s=r.hash;const a=r.receipt;if(a.status!=="success")throw e.observer?.onReverted?.(n,s),new Error(e.errorMessage);await pl(e.extWc,e.client,a.blockNumber),e.observer?.onConfirmed?.(n,s),t=s}return t}async function fl(e){const t=await e.client.estimateFeesPerGas(),n=t.maxFeePerGas??t.gasPrice;if(typeof n!="bigint"||n<=0n)throw new Error("Network gas could not be priced.");let o=0n;for(const s of e.calls){const r=await e.client.estimateGas({account:e.account,...s});o+=(r*n*120n+99n)/100n}return o}function Ns(e,t,n,o){return n?{to:e,value:o,data:"0x"}:{to:t,value:0n,data:xt({abi:tt,functionName:"transfer",args:[e,o]})}}async function ml(e){const t=Ns(e.recipient,e.token,e.isNative,e.amount),[n,o]=await Promise.all([e.client.estimateGas({account:e.account,...t}),e.client.estimateFeesPerGas()]),s=o.maxFeePerGas??o.gasPrice;if(typeof s!="bigint"||s<=0n)throw new Error("Source transaction gas could not be priced.");return(n*s*120n+99n)/100n}function Xr(e,t){return t.isNative?e.sendTransaction({to:t.recipient,value:t.amount,chain:t.viemChain}):e.sendTransaction({to:t.tokenAddr,data:xt({abi:tt,functionName:"transfer",args:[t.recipient,t.amount]}),chain:t.viemChain})}async function op(e){const{extWc:t,sourceClient:n,recipient:o,tokenAddr:s,isNative:r,amount:a}=e;if(a<=0n)return;await e.observer?.onSending?.(0);let i;try{i=await Xr(t,{recipient:o,tokenAddr:s,isNative:r,amount:a,viemChain:e.viemChain})}catch(d){throw ul(d)&&e.observer?.onRejected?.(0),d}e.observer?.onSubmitted?.(0,i);const l=await Ds({client:n,hash:i,call:Ns(o,s,r,a),onRepriced:d=>e.observer?.onSubmitted?.(0,d),onCancelled:()=>e.observer?.onReverted?.(0,i)});i=l.hash;const c=l.receipt;if(c.status!=="success")throw e.observer?.onReverted?.(0,i),new Error("Embedded wallet funding failed");await pl(t,n,c.blockNumber),e.observer?.onConfirmed?.(0,i)}function sp({sourceChainId:e,selectedAsset:t,destinationChainId:n,destinationTokenAddress:o,isCrossDenomination:s,convertedUsdAmount:r}){const a=Ye(t.asset.address),i=o;let l,c;if(i&&n)if(l=ls[n]?.supportedTokens?.find(d=>ge(d.address,i))?.decimals??t.asset.decimals,s){if(!r)throw new Error("Destination amount is still being calculated. Please retry in a moment.");c=r}else{const d=mn(t.amount,t.asset.decimals);c=co(d,t.asset.decimals,l)}return{sourceChainId:e,depositTokenAddress:a,depositAmount:t.amount,depositTokenDecimals:t.asset.decimals,destinationChainId:n,destinationTokenAddress:i,destinationAmount:c,destinationTokenDecimals:l}}async function rp(e,t){if(!e)return[];if(Array.isArray(e))return e;const n=e;return e.length>=2?n(t.depositAmount,t.depositTokenAddress):n(t)}function hl(e,t){return!!e&&e.quotedAmount===t.amount&&e.chainId===t.chainId&&ge(e.token,t.token)}async function Ps(e,t){const n=await Xr(e,{recipient:t.recipient,tokenAddr:t.tokenAddr,isNative:t.isNative,amount:t.amount});t.afterSend?.(n);const o=yt(t.chainId),{receipt:s,hash:r}=await Ds({client:o,hash:n,call:Ns(t.recipient,t.tokenAddr,t.isNative,t.amount),confirmations:2});if(s.status!=="success")throw new Error(t.failureMessage);return t.settle&&await o.getBlockNumber()-s.blockNumber<2n&&await Bn(3e3),r}async function ap(e){const t=e.selectedDepositAssets.filter(s=>s.asset&&s.amount&&parseFloat(s.amount)>0);if(t.length===0){console.error("[DepositModal] No valid assets for deposit"),e.setError("Please select an asset and enter an amount");return}const n=t[0];if(!e.escrowOnly&&!e.sourceAddress){e.setError("External wallet not connected. Please connect your wallet in the previous step.");return}if(!e.isNon7702){if(!e.address||!e.embeddedWalletAddress){e.setError("Couldn't find your account wallet. Try reconnecting.");return}if(!e.isReady||!e.isAuthenticated){e.setError("Sign in to continue.");return}}if(e.zeroCreditError){e.setError(e.zeroCreditError);return}if(e.depositBalanceError){e.setError(e.depositBalanceError);return}if(e.isNon7702&&e.sponsorGas&&e.nativeChainId&&n.asset.chainId!==e.nativeChainId&&e.destinationTokenAddress){e.setError("Gas sponsorship is not supported for this deposit route. Disable sponsorGas to continue.");return}e.setIsExecuting(!0),e.setError(null);let o=!1;try{const s=n.asset.chainId,r=Jn(s),a=mn(n.amount,n.asset.decimals),i=t.length===1&&hl(e.effectiveDepositFee,{amount:a,token:Ye(n.asset.address),chainId:s}),l=!e.isNon7702&&!e.escrowOnly&&!no(n.asset);if(!e.isNon7702&&t.length===1&&!l&&!i)throw new Error("Fee quote is out of date. Please wait for it to refresh.");let c=e.externalWalletClient;if(!e.escrowOnly){if(!c)throw new Error("External wallet not connected");if(e.externalProvider){const d=await Zr({provider:e.externalProvider,account:e.sourceAddress,chainId:s});d.viemChain&&(c=d.extWc)}}if(e.isNon7702){if(!c)throw new Error("External wallet not connected");if(!e.sourceAddress)throw new Error("External wallet address not available");if(e.nativeChainId&&s===e.nativeChainId){const d=Ge(s),p=t.map(h=>`${h.amount} ${h.asset.symbol}`).join(", ");e.setConfirmationData({network:d?.displayName||`Chain ${s}`,amount:p,symbol:"",chainId:s}),e.setShowConfirmation(!0);let f=null;e.setDirectDepositStatus("processing"),e.setDirectDepositChainId(s);for(const h of t){const m=mn(h.amount,h.asset.decimals),g=Ye(h.asset.address),y=h.asset.isNative||be(g),w=await Ps(c,{chainId:s,recipient:r,tokenAddr:g,isNative:y,amount:m,failureMessage:`Escrow deposit failed for ${h.asset.symbol}`});f=w,e.setDirectDepositTxHash(w)}if(t[0]?.amount){const h=t[0].amount;if(e.onDepositExecute){e.setPostDepositStatus("executing");try{await e.onDepositExecute(h),e.setPostDepositStatus("success")}catch(g){console.error("ctx.onDepositExecute failed:",g),e.setPostDepositStatus("error"),e.setPostDepositError(g?.message||"Post-deposit instruction failed")}}else e.setPostDepositStatus("success");e.setDirectDepositStatus("success"),e.setPostDepositAmount(h),e.setPostDepositSuccess(!0);const m={type:"deposit",status:"success",amount:h,asset:t[0].asset.symbol,sourceChain:d?.displayName||`Chain ${s}`,txHash:f??void 0};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:m})),e.onDepositSuccess?.(m)}e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset)}else{const d=e.destinationChainId||e.nativeChainId;if(!d)throw new Error("Destination chain ID is required for non-7702 mode. Either pass ctx.destinationChainId to <SpiceDeposit> or set ctx.nativeChainId on <SpiceFlowProvider>.");const p=va(s),f=r,h=[];let m=null;for(const g of t){const y=mn(g.amount,g.asset.decimals),w=Ye(g.asset.address),x=g.asset.isNative||be(w),v=await Ps(c,{chainId:s,recipient:f,tokenAddr:w,isNative:x,amount:y,failureMessage:`Transfer failed for ${g.asset.symbol}`,settle:!0});m||(m=v),e.depositDataRef.current||(e.depositDataRef.current=[]),e.depositDataRef.current.push({txHash:v,sender:e.sourceAddress,tokenAddress:w,chainId:s,amount:y.toString(),user:e.spiceBalanceUser}),h.push({tokenAddress:w,tokenAmount:y.toString(),sender:e.sourceAddress,receiver:f})}if(!m)throw new Error("No transaction hash generated");if(!e.destinationTokenAddress){const g={type:"deposit",status:"success",amount:t[0]?.amount,asset:t[0]?.asset?.symbol,sourceChain:gn(s),txHash:m};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:g})),e.onDepositSuccess?.(g),e.depositDataRef.current=null,e.bridgedAmountRef.current=t[0]?.amount||null,e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset),e.setShowConfirmation(!1);return}if(e.mode==="ondemand"){const g={to:p,value:BigInt(0),data:"0x"},y=await as(d,e.destinationTokenAddress);let w=BigInt(0);for(const I of h){const M=BigInt(I.tokenAmount),W=Ye(I.tokenAddress),R=t.find(N=>{const D=Ye(N.asset.address);return ge(D,W)}),F=R?R.asset.decimals:await as(s,Tt);w+=co(M,F,y)}e.isCrossDenomination&&e.convertedUsdAmount&&(w=e.convertedUsdAmount);const x={chainId:s,tokenTransfers:h.map(I=>({from:I.sender,to:I.receiver,token:I.tokenAddress,amount:BigInt(I.tokenAmount)})),call:g},v=e.isCrossDenomination&&e.convertedUsdAmount?[{from:e.sourceAddress,to:r,token:Ye(t[0].asset.address),amount:mn(t[0].amount,t[0].asset.decimals)}]:[],k={chainId:d,tokenTransfers:[...v,{from:"escrow",to:e.sourceAddress,token:e.destinationTokenAddress,amount:w}],call:{to:e.destinationTokenAddress,value:BigInt(0),data:"0x"}},A={mode:"non-7702:on-demand",chainBatches:[x,k]},b={user:e.sourceAddress,intents:[A]},S=await Lt.createAction(b),T=S.actionId,E=S.intentIds[0];if(!m)throw new Error("No transaction hash available");e.startStatusPolling(E,Ia([{chainId:s,calls:[g]},{chainId:d,calls:[k.call]}],I=>gn(I))),await Lt.executeStep(T,0,0,{action:"execute",hash:m}),t[0]?.amount&&(e.bridgedAmountRef.current=t[0].amount),e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset),e.setShowConfirmation(!1)}else throw new Error("Presign mode not yet fully supported for cross-chain deposits")}}else{const d=[];let p=0,f;const h=i&&e.effectiveDepositFee?Fe(e.effectiveDepositFee.net,n.asset.decimals):n?.amount;for(const I of t){const M=mn(I.amount,I.asset.decimals),W=i&&I===n,R=W?e.effectiveDepositFee.fee:0n,F=W?e.effectiveDepositFee.net:M,N=e.escrowOnly?M:M+R,D=Ye(I.asset.address),L=I.asset.isNative||be(D);if(!e.escrowOnly&&!no(I.asset)){e.setDirectDepositStatus("processing"),e.setDirectDepositChainId(s);const z=await Ps(c,{chainId:s,recipient:e.address,tokenAddr:D,isNative:L,amount:M,failureMessage:`Transfer to embedded wallet failed for ${I.asset.symbol}`});p+=1,I===n&&(f=z);continue}e.escrowOnly||await Ps(c,{chainId:s,recipient:e.address,tokenAddr:D,isNative:L,amount:N,failureMessage:`Transfer to embedded wallet failed for ${I.asset.symbol}`,afterSend:()=>pu({chainId:s,tokenAddress:Ye(I.asset.address),tokenSymbol:I.asset.symbol,tokenDecimals:I.asset.decimals,amount:I.amount,rawAmount:M.toString(),embeddedWalletAddress:e.address,externalWalletAddress:e.sourceAddress,timestamp:Date.now(),isNative:L}),settle:!0}),d.push(L?{to:r,value:F,data:"0x"}:{to:D,value:BigInt(0),data:xt({abi:tt,functionName:"transfer",args:[r,F]})}),R>0n&&d.push(L?{to:nn,value:R,data:"0x"}:{to:D,value:BigInt(0),data:xt({abi:tt,functionName:"transfer",args:[nn,R]})})}if(d.length===0){e.setDirectDepositTxHash(f??null),e.setDirectDepositStatus("success");const I={type:"deposit",status:"success",amount:n.amount,asset:n.asset.symbol,sourceChain:gn(s),txHash:f};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:I})),e.onDepositSuccess?.(I),e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(n.asset);return}p>0&&e.setDirectDepositStatus("idle");const m=t.find(I=>e.escrowOnly||no(I.asset))??n,g=await yt(s).getBlockNumber(),y=d.map(I=>({...I,to:zt(I.to)})),w={chainId:s,recentBlock:g,calls:y,tokenTransfers:[]},x=sp({sourceChainId:s,selectedAsset:m===n&&h?{...n,amount:h}:m,destinationChainId:e.destinationChainId,destinationTokenAddress:e.destinationTokenAddress,isCrossDenomination:e.isCrossDenomination,convertedUsdAmount:e.convertedUsdAmount}),v=await rp(e.depositBatches,x),k=[w,...v];if(!e.address)throw new Error("Address not available");const A=[];if(e.isCrossDenomination&&e.convertedUsdAmount&&e.destinationTokenAddress){const I=e.selectedDepositAssets[0]?.asset;if(I){const M=mn(e.selectedDepositAssets[0].amount,I.decimals);A.push({from:e.address,to:r,token:Ye(I.address),amount:M}),A.push({from:"escrow",to:e.address,token:e.destinationTokenAddress,amount:e.convertedUsdAmount})}}A.length>0&&k[1]&&(k[1].tokenTransfers=A);const b=Ia(k,I=>gn(I));let S=!1;const T=await e.execution.execute(k,Tt,0n,I=>{if(I.intentId&&!S){S=!0;for(const M of t)Lr(e.address,s,Ye(M.asset.address));e.startStatusPolling(I.intentId,b)}},void 0,{userOverride:e.address,useCustomTransfers:!0,skipPreSubmitFeeEstimate:!0,skipUserFundingPreflight:!0});if(e.refreshAssets(),e.onDepositExecute&&m.amount)try{e.setPostDepositStatus("executing"),await e.onDepositExecute(h||m.amount),e.setPostDepositStatus("success"),e.setPostDepositAmount(h||m.amount),e.setPostDepositSuccess(!0)}catch(I){console.error("ctx.onDepositExecute failed (7702):",I),e.setPostDepositStatus("error"),e.setPostDepositError(I?.message||"Post-deposit instruction failed");return}const E={type:"deposit",status:"success",amount:m===n&&h||m.amount,asset:m.asset.symbol,sourceChain:gn(s),txHash:/^0x[0-9a-f]{64}$/i.test(T??"")?T:void 0};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:E})),e.onDepositSuccess?.(E),e.onDepositSelect&&e.onDepositSelect(m.asset)}}catch(s){o=!0,console.error("[DepositModal] executeDeposit CAUGHT ERROR:",s),console.error("[DepositModal] Error details:",{message:s?.message,code:s?.code,name:s?.name,stack:s?.stack?.slice(0,500)}),e.setError(Mn(s,"Deposit failed")),e.clearStatus()}finally{e.setIsExecuting(!1),o&&e.setDirectDepositStatus("idle"),o||!e.getCurrentIntentStatus()&&e.getCurrentPostDepositStatus()!=="idle"||e.setShowConfirmation(!1)}}async function ip(e){const{asset:t,assetIndex:n,selectedAssetCount:o,address:s,escrowOnly:r,isNon7702:a}=e;if(n!==0||a||o>1||!s||t.balance<=0n)return null;if(!r&&!no(t))return No(t.balance,t.decimals);const i=await gl({address:s,depositQuote:{asset:t,amount:t.balance,token:Ye(t.address),chainId:t.chainId},escrowOnly:r}),l=r?t.balance:t.balance>i.fee?t.balance-i.fee:0n;return No(l,t.decimals)}async function gl(e){const{address:t,depositQuote:n,escrowOnly:o}=e,{asset:s,amount:r,token:a,chainId:i}=n,l=Jn(i),c=s.isNative||be(a),d=r>1n?1n:0n,p=[c?{to:l,value:r,data:"0x"}:{to:a,value:0n,data:xt({abi:tt,functionName:"transfer",args:[l,r]})}];d>0n&&p.push(c?{to:nn,value:d,data:"0x"}:{to:a,value:0n,data:xt({abi:tt,functionName:"transfer",args:[nn,d]})});const f={chainId:i,tokenTransfers:[],calls:p},h=(await Lt.estimateBatchGas({user:t,outputToken:a,chainBatches:[{...f,hash:$n([f])[0].hash}],signal:e.signal})).gasFee,m=o&&h<r?r-h:r;return{fee:h,net:m,quotedAmount:r,token:a,chainId:i}}function lp(e,t=40,n=18){const o=e.length,s=[{maxLength:7,shrink:0},{maxLength:10,shrink:6},{maxLength:13,shrink:12},{maxLength:16,shrink:16},{maxLength:20,shrink:19}].find(r=>o<=r.maxLength);return Math.max(n,t-(s?.shrink??22))}const fo=({value:e,element:t="span",placeholder:n,ariaLabel:o,ariaInvalid:s,disabled:r,onChange:a,inputMode:i="decimal",autoComplete:l="off",dataSpiceflowFocus:c,fontFamily:d,fontWeight:p=700,color:f,textAlign:h,lineHeight:m=1,maxFontSize:g=40,minFontSize:y=18,overflow:w="ellipsis",title:x,style:v})=>{const k=lp(e||n||"",g,y),A=w==="wrap"?{overflowWrap:"anywhere",wordBreak:"break-word",whiteSpace:"normal"}:w==="ellipsis"?{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}:{},b={fontFamily:d,fontSize:`${k}px`,fontWeight:p,color:f,lineHeight:m,letterSpacing:0,textAlign:h,minWidth:0,maxWidth:"100%",...A,...v};return t==="input"?u("input",{type:"text",inputMode:i,autoComplete:l,"aria-label":o,"aria-invalid":s||void 0,"data-spiceflow-focus":c||void 0,value:e,onChange:a,placeholder:n,disabled:r,title:x,style:{backgroundColor:"transparent",border:"none",outline:"none",padding:0,width:"100%",...b}}):u(t,{title:x,style:b,children:e})},Jr=({pct:e,isMax:t,primaryColor:n,dark:o,fillColor:s})=>{const r=e/100;return C("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[u("circle",{cx:"7",cy:"7",r:"6.84375",fill:t?n:"none",stroke:t?n:o?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!t&&r>0&&u("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${r>.5?1:0} 1 ${7+6.84375*Math.sin(r*2*Math.PI)} ${7-6.84375*Math.cos(r*2*Math.PI)} Z`,fill:s})]})},yl=({chainId:e,name:t,size:n=16})=>{const o=e&&(to[e]||Wa(e)?.logo)||"";return o?u("img",{src:o,alt:t||`Chain ${e}`,loading:"lazy",decoding:"async",width:n,height:n,style:{width:`${n}px`,height:`${n}px`,borderRadius:"50%",objectFit:"cover",flexShrink:0}}):null},cp={1:"ethereum",56:"binance-smart-chain",137:"polygon-pos",143:"monad",4114:"citrea",4663:"robinhood",8453:"base",42161:"arbitrum-one"},dp=6e4,$o=new Map;function xl(e,t){return $o.get(e)?.logos?.get(t.toLowerCase())}function up(e,t){const n=cp[e];if(!n||be(t))return;const o=$o.get(e);if(o?.logos||o?.pending)return o.pending;if(o?.failedAt!==void 0&&Date.now()-o.failedAt<dp)return;const s=Promise.resolve().then(async()=>{try{const r=await fetch(`https://tokens.coingecko.com/${n}/all.json`,{signal:AbortSignal.timeout(1e4)});if(!r.ok)throw new Error("Token list request failed");const a=await r.json(),i=new Map;for(const l of a?.tokens??[])l?.address&&l?.logoURI&&i.set(String(l.address).toLowerCase(),l.logoURI);$o.set(e,{logos:i})}catch(r){console.warn(`[tokenLogos] Token list unavailable for chain ${e}`,r),$o.set(e,{failedAt:Date.now()})}});return $o.set(e,{...o,pending:s}),s}function wl(e,t,n){const[o,s]=O(),r=e||e===null||t===void 0||!n?void 0:`${t}:${n.toLowerCase()}`,a=r?xl(t,n):void 0;return ae(()=>{if(!r||a||t===void 0||!n)return;let i=!0;const l=()=>{const d=xl(t,n);i&&d&&s({token:r,logo:d})},c=up(t,n);return c?c.then(l):l(),()=>{i=!1}},[r,a,t,n]),e||a||(o&&o.token===r?o.logo:void 0)}const Us=({symbol:e,label:t,logoURI:n,chainId:o,address:s,size:r=20,theme:a})=>{const{theme:i}=Bt(),l=a||i,[c,d]=O(),p={width:`${r}px`,height:`${r}px`,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:`${r*.4}px`,fontWeight:l.typography.fontWeight.bold,flexShrink:0,overflow:"hidden",backgroundColor:"#ffffff"},f=wl(n===null?null:n||Or[e.toUpperCase()],o,s);if(n===null)return null;if(f&&f!==c)return u("img",{src:f,alt:t??e,loading:"lazy",decoding:"async",style:{...p,objectFit:"cover"},onError:()=>d(f)});const h=pp(e);return u("div",{style:{...p,...h.style},children:h.icon})},pp=e=>{const t=e.toUpperCase(),n={ETH:{bg:"#627EEA",text:"#FFFFFF",icon:"\u039E"},BTC:{bg:"#F7931A",text:"#FFFFFF",icon:"\u20BF"},USDC:{bg:"#2775CA",text:"#FFFFFF"},USDT:{bg:"#26A17B",text:"#FFFFFF"},DAI:{bg:"#F5AC37",text:"#FFFFFF"},WETH:{bg:"#627EEA",text:"#FFFFFF",icon:"\u039E"},WBTC:{bg:"#F09242",text:"#FFFFFF",icon:"\u20BF"},CBTC:{bg:"#F7931A",text:"#FFFFFF",icon:"\u20BF"},USD:{bg:"#26A17B",text:"#FFFFFF",icon:"$"},MATIC:{bg:"#8247E5",text:"#FFFFFF"},AVAX:{bg:"#E84142",text:"#FFFFFF"},SOL:{bg:"#9945FF",text:"#FFFFFF"},DOT:{bg:"#E6007A",text:"#FFFFFF"},ADA:{bg:"#0033AD",text:"#FFFFFF"},LINK:{bg:"#375BD2",text:"#FFFFFF"},UNI:{bg:"#FF007A",text:"#FFFFFF"},AAVE:{bg:"#B6509E",text:"#FFFFFF"},CRV:{bg:"#40E0D0",text:"#000000"}}[t];if(n)return{style:{backgroundColor:n.bg,color:n.text},icon:n.icon||t.charAt(0)};const o=t.split("").reduce((i,l)=>l.charCodeAt(0)+((i<<5)-i),0),s=Math.abs(o)%360,r=`hsl(${s}, 60%, 50%)`,a=s>180?"#FFFFFF":"#000000";return{style:{backgroundColor:r,color:a},icon:t.charAt(0)}},fp=({selectedAsset:e,assets:t,onAssetSelect:n,showDropdown:o,onToggleDropdown:s,disabled:r=!1,theme:a,onViewAllAssets:i})=>{const l=Rn(),{theme:c}=Bt(),d=a||c,p=_(null),f=_(null),h=_(null),[m,g]=O(null);ae(()=>{if(o&&f.current){const R=()=>{if(f.current){const F=f.current.getBoundingClientRect();g({top:F.bottom+6,right:window.innerWidth-F.right})}};return R(),window.addEventListener("scroll",R,!0),window.addEventListener("resize",R),()=>{window.removeEventListener("scroll",R,!0),window.removeEventListener("resize",R)}}else g(null)},[o]),ae(()=>{const R=F=>{p.current&&!p.current.contains(F.target)&&h.current&&!h.current.contains(F.target)&&o&&s()};return o&&document.addEventListener("mousedown",R),()=>{document.removeEventListener("mousedown",R)}},[o,s]);const[y,w]=O(!1),x=d.mode==="light",v={backgroundColor:"transparent",border:`1px solid ${x?"#aaaaaa":d.colors.border}`,borderRadius:"6px",color:d.colors.text,cursor:r?"not-allowed":"pointer",padding:"8px 14px 8px 10px",width:"100%",display:"flex",flexDirection:"column",gap:"4px",opacity:r?.6:1,transition:In.interactive,transform:y?"scale(0.98)":"scale(1)"},k={display:"flex",justifyContent:"space-between",alignItems:"center",gap:"10px",minWidth:0},A={display:"flex",alignItems:"center",gap:"4px",paddingTop:"4px",borderTop:`1px solid ${d.colors.border}`},b=()=>m?{position:"fixed",top:`${m.top}px`,right:`${m.right}px`,backgroundColor:d.colors.secondary,border:`1px solid ${d.colors.border}`,borderRadius:d.borderRadius.md,boxShadow:d.shadows.lg,zIndex:ao.dropdown,width:"200px",maxHeight:"300px",overflow:"auto"}:{},S={backgroundColor:"transparent",border:"none",color:d.colors.text,cursor:"pointer",padding:d.spacing.sm,width:"100%",display:"flex",alignItems:"center",gap:d.spacing.sm,transition:`background-color ${d.animation.normal}`,":hover":{backgroundColor:d.colors.surfaceHover}},T={display:"flex",flexDirection:"column",alignItems:"flex-start",flex:1},E={fontSize:d.typography.fontSize.sm,fontWeight:d.typography.fontWeight.medium},I={fontSize:d.typography.fontSize.xs,color:d.colors.textMuted},M={backgroundColor:"transparent",border:"none",borderTop:`1px solid ${d.colors.border}`,color:d.colors.primary,cursor:"pointer",padding:"10px 12px",width:"100%",display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",fontFamily:d.typography.fontFamily,fontSize:d.typography.fontSize.xs,fontWeight:d.typography.fontWeight.medium,textDecoration:"underline",textUnderlineOffset:"2px"},W={transition:`transform ${d.animation.normal}`,transform:o?"rotate(180deg)":"rotate(0deg)",flexShrink:0};return C(an,{children:[u("div",{style:{position:"relative"},ref:p,children:C("div",{ref:f,style:v,onClick:r?void 0:s,onMouseLeave:()=>{w(!1)},onMouseDown:()=>w(!0),onMouseUp:()=>w(!1),children:[C("div",{style:k,children:[u("div",{style:{display:"flex",alignItems:"center",gap:"8px",flex:1,minWidth:0},children:e?.asset?C(an,{children:[u(Us,{symbol:e.asset.symbol,label:l(e.asset).symbol,logoURI:l(e.asset).logoURI,chainId:e.asset.chainId,address:e.asset.address,theme:d,size:24}),u("span",{style:{fontSize:"15px",fontWeight:500,color:d.colors.text,lineHeight:"1.5",flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:l(e.asset).symbol})]}):u("span",{style:{fontSize:"14px",color:d.colors.textMuted},children:"Select"})}),u("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:x?d.colors.textMuted:"#c7ccd4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:W,children:u("path",{d:"M6 9l6 6 6-6"})})]}),e?.asset&&C("div",{style:A,children:[!e.asset.displayChainName&&u(yl,{chainId:e.asset.chainId,theme:d}),u("span",{style:{fontSize:"11px",color:d.colors.textMuted},children:or(e.asset)})]})]})}),o&&m&&fr(C("div",{ref:h,style:b(),children:[t.length===0&&u("div",{style:{padding:"10px 12px",color:d.colors.textMuted,fontSize:d.typography.fontSize.xs},children:"No assets available"}),t.map(R=>C("button",{style:S,onClick:()=>{n(R),s()},children:[u(Us,{symbol:R.symbol,label:l(R).symbol,logoURI:l(R).logoURI,chainId:R.chainId,address:R.address,theme:d},nt(R)),C("div",{style:T,children:[C("div",{style:{display:"flex",alignItems:"center",gap:d.spacing.xs},children:[u("span",{style:E,children:l(R).symbol}),!R.displayChainName&&u(yl,{chainId:R.chainId,theme:d})]}),C("span",{style:I,children:[cs(R)," \u2022"," ",or(R)]})]})]},nt(R))),i&&C("button",{type:"button",style:M,onClick:()=>{s(),i()},children:[u("span",{children:"View all assets"}),C("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[u("path",{d:"M5 12h14"}),u("path",{d:"M13 5l7 7-7 7"})]})]})]}),document.body)]})},mp=({assets:e,selectedAsset:t,onAssetSelect:n,onAmountChange:o,disabled:s=!1,loading:r=!1,label:a="Select Asset",showBalance:i=!0,showMaxButton:l=!0,placeholder:c="0.0",theme:d,styles:p,maxAmount:f,resolveMaxAmount:h,hideAmountInput:m=!1,displayAmount:g,dark:y,onViewAllAssets:w})=>{const x=Rn(),{theme:v,primaryColor:k,dark:A,dk:b}=Bt(p,y),S=d||v,T=y??A,[E,I]=O(!1),[M,W]=O(null),[R,F]=O(null),[N,D]=O(!1),[L,z]=O(null),[fe,ce]=O(t?.amount||""),Q=_(h),ne=t?.asset?nt(t.asset):"",re=_(ne);re.current=ne;const j=!!h,J=L??f;ae(()=>{Q.current=h},[h]),ae(()=>{ce(t?.amount||"")},[ne,t?.amount]),ae(()=>{z(null),D(!1)},[ne,j,t?.asset?.balance]);const Y=()=>{const G=t?.asset;if(!G)return 0n;if(!J)return G.balance;const P=mn(J,G.decimals);return P<G.balance?P:G.balance},me=G=>{ce(G),o?.(G)},B=G=>{const P=t?.asset,V=ds(G.startsWith(".")?`0${G}`:G,P?.decimals);if(!P||!V)return me(V);const ie=mn(V,P.decimals),ke=Y();me(ie>ke?Fe(ke,P.decimals):V)},U=async()=>{const G=t?.asset;if(!G||s)return;const P=ne,V=Q.current;if(L)return me(L);if(V){D(!0);try{const ie=await V(G);if(re.current!==P)return;if(ie!==null){const ke=ds(ie,G.decimals);z(ke),me(ke);return}return}catch(ie){console.warn("[AssetSelector] Failed to resolve max amount:",ie);return}finally{re.current===P&&D(!1)}}re.current===P&&me(Fe(Y(),G.decimals))},X=async G=>{if(!(!t||s)){if(G===100)return U();me(Fe(Y()*BigInt(G)/100n,t.asset.decimals))}},pe=t?.asset?.balanceFormatted??0,de=parseFloat(fe)||0,xe=pe>0?de/pe*100:0,K={backgroundColor:p?.assetSelector?.backgroundColor||p?.secondaryBackground||(T?b.cardBg:"#e9e9e9"),border:T?`0.5px solid ${b.cardBorder}`:"0.5px solid #A8A8A7",borderRadius:p?.assetSelector?.borderRadius||"6px",padding:p?.assetSelector?.padding||"16px",height:"auto",minHeight:m?void 0:"144px",display:"flex",flexDirection:"column",gap:"8px",position:"relative",opacity:s?.6:1};return r?u("div",{style:K,children:C("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"space-between"},children:[C("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[u("div",{style:{backgroundColor:T?b.hoverBg:"#d1d5db",borderRadius:"4px",height:"16px",width:"60px"}}),u("div",{style:{backgroundColor:T?b.hoverBg:"#d1d5db",borderRadius:"4px",height:"40px",width:"150px"}})]}),C("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:"8px"},children:[u("div",{style:{backgroundColor:T?b.hoverBg:"#d1d5db",borderRadius:"4px",height:"12px",width:"80px"}}),u("div",{style:{backgroundColor:T?b.hoverBg:"#d1d5db",borderRadius:"6px",height:"46px",width:"128px"}})]})]})}):C("div",{style:K,children:[C("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[u("span",{style:{fontFamily:p?.fontFamily||S.typography.fontFamily,fontSize:"16px",fontWeight:500,color:T?b.textSecondary:"#7d7c7b",lineHeight:"24px"},children:a}),i&&t?.asset&&C("span",{style:{fontFamily:p?.fontFamily||S.typography.fontFamily,fontSize:"12px",fontWeight:500,color:T?b.textSecondary:"#71757a",lineHeight:"16px"},children:["Balance: ",cs(t.asset)]})]}),C("div",{style:{display:"flex",justifyContent:m&&!g?"flex-start":"space-between",alignItems:"center",flex:1},children:[!m&&u(fo,{element:"input",ariaLabel:t?.asset?`${x(t.asset).symbol} amount`:"Amount",dataSpiceflowFocus:!0,value:fe,onChange:G=>B(G.target.value),placeholder:c,disabled:s||!t?.asset,fontFamily:p?.fontFamily||S.typography.fontFamily,color:s?T?"rgba(255, 255, 255, 0.16)":"rgba(14, 13, 11, 0.16)":fe?T?"#ffffff":"#0e0d0b":T?"#4a5568":"#d1d5db",lineHeight:"1.08",maxFontSize:40,minFontSize:22,style:{width:"100%",maxWidth:"200px"}}),u("div",{style:{width:"176px",position:"relative",flexShrink:0},children:u(fp,{selectedAsset:t,assets:e,onAssetSelect:n,showDropdown:E,onToggleDropdown:()=>I(!E),disabled:s,theme:S,onViewAllAssets:w})}),m&&g&&u(fo,{element:"span",value:g,title:g,fontFamily:p?.fontFamily||S.typography.fontFamily,color:T?"#ffffff":"#0e0d0b",lineHeight:"1.08",textAlign:"right",maxFontSize:40,minFontSize:22,style:{flex:1}})]}),!m&&u("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",height:"14px"},children:[0,25,50,75,100].filter(G=>l||G!==100).map((G,P)=>{const V=Math.abs(xe-G)<1,ie=P===4,ke=M===G,Ee=R===G;return u("button",{onClick:()=>X(G),onMouseEnter:()=>W(G),onMouseLeave:()=>{W(null),F(null)},onMouseDown:()=>F(G),onMouseUp:()=>F(null),disabled:s||!t?.asset||G===100&&N,title:`${G}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:s||!t?.asset||G===100&&N?"not-allowed":"pointer",opacity:V?1:ke?.8:.5,transform:Ee?"scale(0.85)":ke?"scale(1.15)":"scale(1)",transition:In.interactive},children:u(Jr,{pct:G,isMax:ie,primaryColor:k,dark:T,fillColor:T?b.textSecondary:"#3C3E42"})},G)})})]})},Fo=yn(mp),hp=({selectedDepositAssets:e,depositAssets:t,secondAssetOptions:n,loadingAssets:o,allowSecondAsset:s,theme:r,styles:a,dark:i,dk:l,onSelect:c,onAmountChange:d,onAdd:p,onRemove:f,resolveMaxAmount:h,onViewAllAssets:m})=>C(an,{children:[e.map((g,y)=>{const w=e.length===1?"Deposit":`Asset ${y+1}`;return C("div",{style:{marginBottom:r.spacing.md,position:"relative"},children:[u(Fo,{assets:y===0?t:n,selectedAsset:g||void 0,onAssetSelect:x=>c(x,y),onAmountChange:x=>d(x,y),loading:o,label:w,showBalance:!0,theme:r,styles:a,allowSecondAsset:s&&y===0,onAddAsset:p,canAddAsset:e.length===1&&!!e[0]?.asset,resolveMaxAmount:h?x=>h(x,y):void 0,onViewAllAssets:y===0?m:void 0}),y===1&&u("button",{onClick:()=>f(y),style:{position:"absolute",top:"-2px",right:"-2px",background:i?`${l.cardBg}ee`:"rgba(255, 255, 255, 0.9)",border:`1px solid ${l.cardBorder}`,borderRadius:"50%",cursor:"pointer",color:r.colors.textMuted,fontSize:"16px",padding:"2px",width:"22px",height:"22px",display:"flex",alignItems:"center",justifyContent:"center",transition:In.interactive,boxShadow:"0 1px 3px rgba(0, 0, 0, 0.1)"},onMouseEnter:x=>{x.currentTarget.style.color=i?l.errorText:"#ef4444",x.currentTarget.style.background=i?l.cardBg:"#fff",x.currentTarget.style.borderColor=i?l.errorBorder:"#fecaca"},onMouseLeave:x=>{x.currentTarget.style.color=r.colors.textMuted,x.currentTarget.style.background=i?`${l.cardBg}ee`:"rgba(255, 255, 255, 0.9)",x.currentTarget.style.borderColor=i?l.cardBorder:"#e5e7eb"},title:"Remove asset",children:"\xD7"})]},`asset-${y}`)}),e.length===0&&u("div",{style:{marginBottom:r.spacing.md},children:u(Fo,{assets:t,selectedAsset:void 0,onAssetSelect:g=>c(g,0),onAmountChange:g=>d(g,0),loading:o,label:"Deposit",showBalance:!0,theme:r,styles:a,allowSecondAsset:s,onAddAsset:p,canAddAsset:!1,resolveMaxAmount:h?g=>h(g,0):void 0},"initial-selector")})]}),gp=yn(hp);function yp(e,t){switch(e){case"success":return{bg:t.successBg,border:t.successBorder,text:t.successText};case"warning":return{bg:t.warningBg,border:t.warningBorder,text:t.warningText};case"error":return{bg:t.errorBg,border:t.errorBorder,text:t.errorText};case"info":return{bg:t.infoBg,border:t.infoBorder,text:t.infoText}}}const Nn=({variant:e,palette:t,children:n,icon:o,style:s,fontFamily:r,size:a="default"})=>{const i=yp(e,t),l=a==="compact";return C("div",{role:e==="error"?"alert":"status",style:{backgroundColor:i.bg,border:`1px solid ${i.border}`,borderRadius:l?"7px":"8px",padding:l?"8px 10px":"12px 16px",color:i.text,fontSize:l?"12px":"13px",lineHeight:l?1.4:1.5,display:"flex",alignItems:"flex-start",gap:l?"6px":"8px",fontFamily:r,...s},children:[o&&u("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:o}),u("span",{style:{minWidth:0,overflowWrap:"anywhere"},children:n})]})},bl=Oe.mono,oo=({label:e,value:t,palette:n,valueColor:o,labelColor:s,style:r})=>C("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",...r},children:[u("span",{style:{fontSize:"12px",color:s??n.textSecondary,fontFamily:bl,fontWeight:500,letterSpacing:"0.03em",flexShrink:0,whiteSpace:"nowrap"},children:e}),u("span",{style:{fontSize:"13px",color:o??n.textPrimary,fontWeight:500,fontFamily:bl,minWidth:0,textAlign:"right",overflowWrap:"anywhere"},children:t})]}),$r=({onClick:e,label:t="Add Funds",color:n,fontFamily:o,style:s})=>{const[r,a]=O(!1);return C("button",{type:"button",onClick:e,"data-spiceflow-focus":!0,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),style:{background:"none",border:"none",cursor:"pointer",padding:0,display:"inline-flex",alignItems:"center",gap:"4px",color:n,fontSize:"12px",fontWeight:500,fontFamily:o,textDecoration:"underline",textUnderlineOffset:"2px",whiteSpace:"nowrap",opacity:r?.75:1,transition:"opacity 150ms ease",...s},children:[t,C("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.8","aria-hidden":"true",children:[u("circle",{cx:"6",cy:"6",r:"5"}),u("path",{d:"M6 4v4M4 6h4",strokeLinecap:"round"})]})]})},_r=({value:e,onChange:t,ariaLabel:n,placeholder:o,endAdornment:s,size:r="lg",dark:a,styles:i,inputRef:l,autoFocus:c})=>{const{dark:d,dk:p}=Bt(i,a),f=a??d,h=r==="lg",m=h?"15px":"14px",g=h?"7px":"10px",y=h?sr.input:sr.sm,w=i?.fontFamily||Oe.ui,x=f?p.inputBg:"#FAFAFA",v=f?p.inputBorder:"#e5e7eb",k=f?p.textPrimary:"#374151",A=f?p.textSecondary:"#9ca3af";return C("div",{style:{display:"flex",alignItems:"center",gap:"8px",backgroundColor:x,borderRadius:y,boxShadow:f?"0 2px 4px rgba(0, 0, 0, 0.3)":"0 2px 4px rgba(0, 0, 0, 0.1)",padding:`${g} 5px`,border:`1px solid ${v}`},children:[u(Ju,{style:{color:A},size:24}),u("input",{ref:l,type:"text",role:"searchbox","aria-label":n,autoComplete:"off",spellCheck:!1,autoFocus:c,"data-spiceflow-focus":!0,placeholder:o,value:e,onChange:b=>t(b.target.value),style:{flex:1,backgroundColor:x,outline:"none",border:"none",color:k,fontSize:m,fontWeight:400,fontFamily:w}}),s]})},xp="This deposit didn't confirm in time. It may still have gone through, so check the explorer and refresh your balance before retrying.";function wp(e){return e?.overallStatus!=="failed"?{isFailed:!1,failureMessage:null}:{isFailed:!0,failureMessage:e.steps?.find(t=>t.status==="failed"&&!!t.error)?.error||xp}}const Ls=C("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",style:{flexShrink:0},children:[u("circle",{cx:"10",cy:"10",r:"10",fill:"#10b981"}),u("path",{d:"M6 10l3 3 5-6",stroke:"#ffffff",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),bp=({isOpen:e,onClose:t,onConfirm:n,data:o,isExecuting:s=!1,error:r=null,theme:a,styles:i,intentStatus:l,postDepositStatus:c="idle",hasPostDepositInstruction:d=!1})=>{const{dark:p,dk:f,theme:h}=Bt(i),[m,g]=O(!1),[y,w]=O(!0);ae(()=>{e||g(!1)},[e]);const x=()=>{g(!0),setTimeout(()=>{t()},300)},v=()=>{w(!y)};if(!e||!o)return null;const k=l?.overallStatus==="processing",A=l?.overallStatus==="success",b=!!l,{isFailed:S,failureMessage:T}=wp(l),E=!b&&d,I=E&&c==="executing",M=E&&c==="success",W=A&&d&&(c==="idle"||c==="executing")||I,R=A&&(!d||c==="success"||c==="error")||M||E&&c==="error",F=p?f.cardBg:"#ffffff",N=p?"0 -4px 20px rgba(0, 0, 0, 0.4)":"0 -4px 20px rgba(0, 0, 0, 0.15)",D=f.textSecondary,L=p?f.textPrimary:"#1f2937",z=p?f.textPrimary:"#1f2937",fe=ne=>u("div",{style:{marginBottom:a.spacing.md,padding:a.spacing.md,backgroundColor:i?.errorMessage?.backgroundColor||(a.mode==="light"?"#fef2f2":`${a.colors.error}20`),border:`1px solid ${i?.errorMessage?.borderColor||(a.mode==="light"?"#fecaca":a.colors.error)}`,borderRadius:i?.errorMessage?.borderRadius||a.borderRadius.md},children:u("p",{style:{color:i?.errorMessage?.color||a.colors.error,fontSize:i?.errorMessage?.fontSize||a.typography.fontSize.sm,margin:0,fontFamily:i?.errorMessage?.fontFamily||i?.fontFamily||a.typography.fontFamily},children:ne})}),ce={fontSize:a.typography.fontSize.sm,fontWeight:500,color:D,fontFamily:Oe.mono,letterSpacing:"0.5px"},Q=(ne,re,j=L)=>C("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[u("span",{style:ce,children:ne}),u("span",{style:{fontSize:a.typography.fontSize.sm,fontWeight:500,color:j,fontFamily:Oe.mono},children:re})]});return C("div",{style:{position:"absolute",bottom:0,left:0,right:0,zIndex:10,animation:m?"slideDown 0.3s ease-in":"slideUp 0.3s ease-out",pointerEvents:"auto"},children:[C("div",{style:{backgroundColor:F,borderRadius:"0",width:"100%",maxWidth:"522px",margin:"0 auto",padding:"18px 24px",boxShadow:N},children:[!A&&!M&&C(an,{children:[C("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:a.spacing.md},children:[C("div",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:"pointer"},onClick:v,children:[u("span",{style:{fontSize:"13px",fontWeight:a.typography.fontWeight.medium,color:D,fontFamily:i?.fontFamily||a.typography.fontFamily},children:"Transaction Details"}),u(Eo,{color:D,direction:y?"up":"down"})]}),u("button",{onClick:ne=>{ne.stopPropagation(),t()},style:{background:"none",border:"none",cursor:"pointer",padding:"4px",display:"flex",alignItems:"center",justifyContent:"center",color:D,transition:"color 0.2s ease"},onMouseEnter:ne=>{ne.currentTarget.style.color=z},onMouseLeave:ne=>{ne.currentTarget.style.color=D},children:u(Jo,{size:16})})]}),C("div",{style:{marginBottom:a.spacing.lg,display:"flex",flexDirection:"column",gap:a.spacing.md,overflow:"hidden",maxHeight:y?"200px":"0px",opacity:y?1:0,transition:"max-height 0.3s ease, opacity 0.3s ease"},children:[Q("NETWORK",o.network),Q("DEPOSITED AMOUNT",o.amount,a.colors.success),o.creditedAmount&&Q("CREDITED AMOUNT",o.creditedAmount),o.spicenetFee&&Q("SPICENET FEE",o.spicenetFee),o.networkFee&&Q("EST. NETWORK FEE",o.networkFee)]})]}),r&&!b&&fe(r),S&&T&&fe(T),u(Et,{onClick:R||S?x:n,variant:"outline",fullWidth:!0,disabled:s||k||W||I,styles:i,theme:h,children:s||k||I||W?"PROCESSING...":R?"CONTINUE \u2192":S?"CLOSE":"CONFIRM DEPOSIT"}),R&&u("p",{style:{marginTop:a.spacing.md,marginBottom:0,fontSize:"14px",color:D,textAlign:"center",fontFamily:i?.fontFamily||a.typography.fontFamily},children:"Your funds are now available in your Account"}),u("div",{style:{marginTop:a.spacing.md,display:"flex",justifyContent:"center",alignItems:"center"},children:u("img",{src:il,alt:"Powered by SpiceNet",style:{height:"auto",width:"130px",opacity:1,filter:p?"brightness(0) invert(1) opacity(0.7)":"none"}})})]}),u("style",{children:`
3
+ import{jsxs as C,jsx as u,Fragment as an}from"react/jsx-runtime";import{g as Ge,a as yt,S as Ne,b as ge,c as as,i as is,d as ba,e as Mt,f as Rc,E as Mc,C as ls,r as Wc,R as Nc,h as Pc,j as va,k as Lt,l as tr,u as Zn,m as Ca,n as gn,z as ao,o as Rn,p as Oe,q as Bt,s as nr,t as wo,v as ka,w as Ia,x as Mn,y as No,A as In,B as or,D as cs,F as ds,G as sr,H as Ln,I as us,J as Et,K as ps,L as fs,M as Uc,P as Lc,N as io,O as Sa,Q as Xn,T as zc,U as ms,V as hs,W as Aa,X as Hc,Y as Po,Z as qc,_ as Ea,$ as rr,a0 as Fa,a1 as lo,a2 as Vc,a3 as Qc,a4 as jc,a5 as Gc,a6 as Ta,a7 as Yc}from"./privy-B7TjILWd.js";import{a8 as Qm,aa as jm,ab as Gm,ad as Ym,ac as Km,a9 as Zm}from"./privy-B7TjILWd.js";import En,{useContext as Qt,useState as O,useMemo as ue,useEffect as ae,useCallback as te,useRef as _,useId as Ba,useLayoutEffect as Da,memo as yn}from"react";import{isNativeToken as be,uniV3QuoterV2Abi as Kc,uniV3SwapRouterAbi as Oa,applySlippage as Ra,NATIVE_TOKEN_ADDRESS as Ma,getTokenByAddress as Ft,areEquivalent as Zc,getTokensForChain as gs,getEscrowContractAddress as Jn,getEscrowContract as Uo,ZERO_ADDRESS as Tt,normalizeNativeTokenAddress as Ye,getChainMeta as Wa,getMainnetChains as Xc,getTestnetChains as Jc,TOKENS as Na,convertAmountBetweenDecimals as co,getChainIdsByNetwork as ys,hashChainBatches as $n,isSpicenetChainId as bo,getAccountNonce as $c,SPICE_GAS_FEE_RECIPIENT as nn,SPICE_PLATFORM_FEE_RECIPIENT as Fn,getEquivalenceGroup as _c,SPICENET_NATIVE_CHAIN_ID as Pa,spicenetAbi as ar,getEquivalentAddresses as ed,getTokenBySymbol as Ua}from"@spicenet-io/spiceflow-core";import{ZERO_ADDRESS as Jm,SPICENET_NATIVE_CHAIN_ID as $m,SPICE_COMBINED_FEE_RECIPIENT as _m,SPICE_GAS_FEE_RECIPIENT as eh,SPICE_PLATFORM_FEE_RECIPIENT as th,SPICE_SOLVER_ADDRESS as nh,applySlippage as oh,buildUniV3SwapCalls as sh,getChainIdsByNetwork as rh,getEscrowContractAddress as ah,isNativeToken as ih,isSpicenetChainId as lh,normalizeNativeTokenAddress as ch,spicenetAbi as dh,spicenetAbi as uh}from"@spicenet-io/spiceflow-core";import{useWalletClient as td,useAccount as ir,useDisconnect as La,useConnect as nd,useSwitchChain as za,useReconnect as od}from"wagmi";import{encodeFunctionData as xt,parseAbi as Tn,concatHex as sd,encodePacked as lr,erc20Abi as tt,decodeFunctionData as uo,encodeAbiParameters as zn,formatUnits as Fe,isAddress as fn,getAddress as zt,keccak256 as vo,createWalletClient as cr,custom as dr,parseUnits as mn,toHex as Ha,stringToHex as rd}from"viem";import{readContract as _n,getBalance as ur}from"viem/actions";import{useConnectWallet as qa,usePrivy as ad}from"@privy-io/react-auth";import pr,{createPortal as fr}from"react-dom";import"@tanstack/react-query";const id="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@100;200;300;400;500;600;700&display=swap",ld="spiceflow-ibm-plex-mono",cd="spiceflow-preconnect-googleapis",dd="spiceflow-preconnect-gstatic";function mr(e,t){if(document.getElementById(e))return;const n=t();n.id=e,document.head.appendChild(n)}function ud(){typeof document>"u"||(mr(cd,()=>{const e=document.createElement("link");return e.rel="preconnect",e.href="https://fonts.googleapis.com",e}),mr(dd,()=>{const e=document.createElement("link");return e.rel="preconnect",e.href="https://fonts.gstatic.com",e.crossOrigin="",e}),mr(ld,()=>{const e=document.createElement("link");return e.rel="stylesheet",e.href=id,e}))}const pd={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",8453:"0x4200000000000000000000000000000000000006",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",84532:"0x4200000000000000000000000000000000000006"},Va=Tn(["function deposit() payable","function withdraw(uint256 wad)"]);function hr(e){return Ge(e)?.wrappedNativeTokenAddress??pd[e]}const gr=(e,t)=>({to:e,value:t,data:xt({abi:Va,functionName:"deposit"})}),yr=(e,t)=>({to:e,value:0n,data:xt({abi:Va,functionName:"withdraw",args:[t]})});function xr(e,t,n){const o=be(t),s=be(n);if(!o&&!s)return null;const r=hr(e);return r?{weth:r,wrapIn:o,unwrapOut:s}:null}function Qa(e,t,n,o){const s=xr(e,t,n);return!s||o<=0n?null:s.wrapIn&&!s.unwrapOut&&n.toLowerCase()===s.weth.toLowerCase()?[gr(s.weth,o)]:s.unwrapOut&&!s.wrapIn&&t.toLowerCase()===s.weth.toLowerCase()?[yr(s.weth,o)]:null}function fd(e){return{...e,resolve:async(t,n,o,s)=>{const r=Qa(n,t.tokenIn,t.tokenOut,t.amountIn);if(r)return{venue:"native-wrap",amountOut:t.amountIn,amountOutMinimum:t.amountIn,calls:r};const a=await e.resolve(t,n,o,s);if(a)return a;const i=xr(n,t.tokenIn,t.tokenOut);if(!i)return null;const l=await e.resolve({...t,tokenIn:i.wrapIn?i.weth:t.tokenIn,tokenOut:i.unwrapOut?i.weth:t.tokenOut},n,o,s);return l?{...l,calls:[...i.wrapIn?[gr(i.weth,t.amountIn)]:[],...l.calls,...i.unwrapOut?[yr(i.weth,l.amountOutMinimum)]:[]]}:null}}}function md(e){return{...e,resolve:async(t,n,o)=>{const s=Qa(n,t.tokenIn,t.tokenOut,t.amountOut);if(s)return{venue:"native-wrap",amountIn:t.amountOut,amountInMax:t.amountOut,amountOut:t.amountOut,calls:s};const r=await e.resolve(t,n,o);if(r)return r;const a=xr(n,t.tokenIn,t.tokenOut);if(!a)return null;const i=await e.resolve({...t,tokenIn:a.wrapIn?a.weth:t.tokenIn,tokenOut:a.unwrapOut?a.weth:t.tokenOut},n,o);return i?{...i,calls:[...a.wrapIn?[gr(a.weth,i.amountInMax)]:[],...i.calls,...a.unwrapOut?[yr(a.weth,i.amountOut)]:[]]}:null}}}const ja=[100,500,3e3,1e4];function xs(e,t,n,o,s){const r=[];for(const a of n){const i=typeof a=="object"&&!Array.isArray(a)?a:void 0,l=i?i.tokens:Array.isArray(a)?a:[a];if(!l.length||l.length>2)throw new Error("A v3 route must have one or two intermediate tokens");const c=[e,...l,t];if(i&&(i.feeTiers.length!==c.length-1||i.feeTiers.some(p=>!p.length)))throw new Error("A v3 route needs fee tiers for every pool");if(new Set(c.map(p=>p.toLowerCase())).size!==c.length)continue;const d=(p,f)=>{if(p===c.length){r.push(s==="in"?f:Ga(f));return}for(const h of i?.feeTiers[p-1]??o)d(p+1,sd([f,lr(["uint24","address"],[h,c[p]])]))};d(1,c[0])}return[...new Set(r)]}function Ga(e){const t=e.slice(2),n=[];for(let o=0;o<t.length;){const s=n.length%2===0?40:6;n.push(t.slice(o,o+s)),o+=s}return`0x${n.reverse().join("")}`}const hd=Tn(["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)"]),gd=Tn(["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)"]),yd=1800;function Ya(e){const{config:t,route:n,tokenIn:o,tokenOut:s,recipient:r,amountOut:a}=e,i=e.amountInMaximum,l=e.routerHasDeadline?gd:hd,c=e.routerHasDeadline?{deadline:BigInt(Math.floor(Date.now()/1e3)+yd)}:{},d=n.path?xt({abi:l,functionName:"exactOutput",args:[{path:n.path,recipient:r,...c,amountOut:a,amountInMaximum:i}]}):xt({abi:l,functionName:"exactOutputSingle",args:[{tokenIn:o,tokenOut:s,fee:n.fee,recipient:r,...c,amountOut:a,amountInMaximum:i,sqrtPriceLimitX96:0n}]});return{to:t.swapRouter,value:0n,data:d}}const xd=Tn(["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 Lo(e,t,n,o,s){const r=yt(e),{result:a}=await r.simulateContract({address:t.quoterV2,abi:xd,functionName:s==="in"?"quoteExactInput":"quoteExactOutput",args:[n,o]}),[i,,,l]=a;if(i<=0n)throw new Error("No liquidity along this path.");return{amount:i,gasEstimate:l}}async function wd(e){const{tokenIn:t,tokenOut:n,amountIn:o,fee:s,chainId:r,config:a}=e;if(o<=0n)throw new Error("amountIn must be greater than 0");const i=(await yt(r).simulateContract({address:a.quoterV2,abi:Kc,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:o,fee:s,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 Ka(e){const t=e.feeTiers??ja,n=xs(e.tokenIn,e.tokenOut,e.hubs??[],t,"in"),o=await Promise.allSettled([...t.map(async r=>({...await wd({...e,fee:r}),fee:r})),...n.map(async r=>{const a=await Lo(e.chainId,e.config,r,e.amountIn,"in");return{amountOut:a.amount,sqrtPriceX96After:0n,gasEstimate:a.gasEstimate,fee:0,path:r}})]);let s=null;for(const r of o)r.status==="fulfilled"&&(!s||r.value.amountOut>s.amountOut)&&(s=r.value);if(!s)throw new Error("No liquidity found for this pair on any fee tier.");return s}const bd=[{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 vd(e){const{tokenIn:t,tokenOut:n,amountOut:o,fee:s,chainId:r,config:a}=e;if(o<=0n)throw new Error("amountOut must be greater than 0");const i=(await yt(r).simulateContract({address:a.quoterV2,abi:bd,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:o,fee:s,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 Za(e){const t=e.feeTiers??ja,n=xs(e.tokenIn,e.tokenOut,e.hubs??[],t,"out"),o=await Promise.allSettled([...t.map(async r=>({...await vd({...e,fee:r}),fee:r})),...n.map(async r=>{const a=await Lo(e.chainId,e.config,r,e.amountOut,"out");return{amountIn:a.amount,sqrtPriceX96After:0n,gasEstimate:a.gasEstimate,fee:0,path:r}})]);let s=null;for(const r of o)r.status==="fulfilled"&&(!s||r.value.amountIn<s.amountIn)&&(s=r.value);if(!s)throw new Error("No liquidity found for this pair on any fee tier.");return s}function Cd(e){return e.type==="swap"}const zo=.02,kd=[1,8453,42161,10,137,43114,56],Id="https://api.1inch.dev/swap/v6.0";function wr(e,t){return Ra(e,t)}function Sd(e){const t=e?.baseUrl??Id;return{name:"1inch",chainIds:e?.chainIds??kd,resolve:async(n,o,s)=>{const r=n.maxSlippage??zo,a=r*100,i=be(n.tokenIn)?Ma:n.tokenIn,l=be(n.tokenOut)?Ma:n.tokenOut,c=be(n.tokenIn);try{const d=new URL(`${t}/${o}/swap`);d.searchParams.set("src",i),d.searchParams.set("dst",l),d.searchParams.set("amount",n.amountIn.toString()),d.searchParams.set("from",s),d.searchParams.set("slippage",a.toString()),d.searchParams.set("disableEstimate","true"),d.searchParams.set("allowPartialFill","false");const p={Accept:"application/json"};e?.apiKey&&(p.Authorization=`Bearer ${e.apiKey}`);const f=await fetch(d.toString(),{headers:p});if(!f.ok)throw new Ne("VENUE_API_ERROR",`[1inchVenue] API returned ${f.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 ${f.status}`});const h=await f.json();if(!h.dstAmount||!h.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const m=BigInt(h.dstAmount);if(m<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const g=wr(m,r),y=[];return h.tx.to&&!c&&y.push({to:n.tokenIn,value:0n,data:xt({abi:tt,functionName:"approve",args:[h.tx.to,n.amountIn]})}),y.push({to:h.tx.to,value:BigInt(h.tx.value||"0"),data:h.tx.data}),{venue:"1inch",amountOut:m,amountOutMinimum:g,calls:y}}catch(d){if(d instanceof Ne)throw d;const p=d instanceof Error?d.message:String(d);throw new Ne("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}: ${p}`,{venue:"1inch",chainId:o,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:p})}}}}const Xa=[4114,5115],br={name:"Satsuma",swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},Ja={name:"Uniswap v3",swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x4200000000000000000000000000000000000006","0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]},$a={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[1],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2","0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"]},_a={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[42161],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x82aF49447D8a07e3bd95BD0d56f35241523fBab1","0xaf88d065e77c8cC2239327C5EDb3A432268e5831"]},Ad={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[137],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270","0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"]},Ed={name:"Uniswap v3",swapRouter:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",quoterV2:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",chainIds:[56],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c","0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d"]},Fd={name:"Uniswap v3",swapRouter:"0xfe31f71c1b106eac32f1a19239c9a9a72ddfb900",quoterV2:"0x661e93cca42afacb172121ef892830ca3b70f08d",chainIds:[143],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A","0x754704Bc059F8C67012fEd69BC8A327a5aafb603"]},ei={name:"Uniswap v3",swapRouter:"0xcaf681a66d020601342297493863e78c959e5cb2",quoterV2:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",chainIds:[4663],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73","0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"]},ti={name:"SushiSwap",swapRouter:"0x1e406484F1F204b23cE84B9901C0171a738fd406",quoterV2:"0x3E290e5E01818002A0b672148BdC7514D861C7B3",chainIds:[4663],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73","0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"],routerHasDeadline:!0},ni=Tn(["function exactInput((bytes path, address recipient, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),oi=Tn(["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)"]),Td=Tn(["function exactInput((bytes path, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),Bd=Tn(["function exactOutput((bytes path, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),vr=1800,si=[1,50,100,200,2e3],Cr={name:"Aerodrome",swapRouter:"0xcbBb8035cAc7D4B3Ca7aBb74cF7BdF900215Ce0D",quoterV2:"0x3d4C22254F86f64B7eC90ab8F7aeC1FBFD271c6C",chainIds:[8453],hubCurrencies:["0x4200000000000000000000000000000000000006","0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]};function kr(e){const t=e.name??"Aerodrome",n=e.chainIds??[8453],o=e.tickSpacings??si;return{name:t,chainIds:n,resolve:async(s,r,a)=>{if(be(s.tokenIn)||be(s.tokenOut))return null;const i=s.maxSlippage??zo,l=[...o.map(y=>lr(["address","uint24","address"],[s.tokenIn,y,s.tokenOut])),...xs(s.tokenIn,s.tokenOut,e.hubCurrencies??[],o,"in")],c={quoterV2:e.quoterV2},d=await Promise.allSettled(l.map(async y=>({path:y,amountOut:(await Lo(r,c,y,s.amountIn,"in")).amount})));let p=null;for(const y of d)y.status==="fulfilled"&&(!p||y.value.amountOut>p.amountOut)&&(p=y.value);if(!p)return console.warn(`[AerodromeVenue] No viable route for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${r}.`),null;const f=wr(p.amountOut,i),h=BigInt(Math.floor(Date.now()/1e3)+vr),m=xt({abi:Td,functionName:"exactInput",args:[{path:p.path,recipient:a,deadline:h,amountIn:s.amountIn,amountOutMinimum:f}]}),g=[{to:s.tokenIn,value:0n,data:xt({abi:tt,functionName:"approve",args:[e.swapRouter,s.amountIn]})},{to:e.swapRouter,value:0n,data:m}];return{venue:t,amountOut:p.amountOut,amountOutMinimum:f,calls:g}}}}function ri(e){const t=e.name??"Aerodrome",n=e.chainIds??[8453],o=e.tickSpacings??si;return{name:t,chainIds:n,resolve:async(s,r,a)=>{if(be(s.tokenIn)||be(s.tokenOut))return null;const i=s.maxSlippage??zo,l=[...o.map(g=>lr(["address","uint24","address"],[s.tokenOut,g,s.tokenIn])),...xs(s.tokenIn,s.tokenOut,e.hubCurrencies??[],o,"out")],c={quoterV2:e.quoterV2},d=await Promise.allSettled(l.map(async g=>({path:g,amountIn:(await Lo(r,c,g,s.amountOut,"out")).amount})));let p=null;for(const g of d)g.status==="fulfilled"&&(!p||g.value.amountIn<p.amountIn)&&(p=g.value);if(!p)return console.warn(`[AerodromeExactOutputVenue] No viable route for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${r}.`),null;const f=BigInt(Math.round(i*1e4)),h=p.amountIn+p.amountIn*f/10000n,m=BigInt(Math.floor(Date.now()/1e3)+vr);return{venue:t,amountIn:p.amountIn,amountInMax:h,amountOut:s.amountOut,calls:[{to:e.swapRouter,value:0n,data:xt({abi:Bd,functionName:"exactOutput",args:[{path:p.path,recipient:a,deadline:m,amountOut:s.amountOut,amountInMaximum:h}]})}]}}}}function Ho(e){const t=e.name??"Uniswap v3",n=e.chainIds??Xa;return{name:t,chainIds:n,resolve:async(o,s,r,a)=>{if(be(o.tokenIn)||be(o.tokenOut))return null;const i=o.maxSlippage??zo;let l;try{let m;if(a){if(a.venue!==t)return null;const g=a.calls.find(w=>w.to.toLowerCase()===e.swapRouter.toLowerCase());if(!g)return null;const y=uo({abi:e.routerHasDeadline?oi:[...ni,...Oa],data:g.data});if(y.functionName==="exactInput"){const{path:w}=y.args[0];if(w.slice(0,42).toLowerCase()!==o.tokenIn.toLowerCase()||`0x${w.slice(-40)}`.toLowerCase()!==o.tokenOut.toLowerCase())return null;m={path:w,fee:0}}else if(y.functionName==="exactInputSingle"){const{tokenIn:w,tokenOut:x,fee:v}=y.args[0];if(w.toLowerCase()!==o.tokenIn.toLowerCase()||x.toLowerCase()!==o.tokenOut.toLowerCase())return null;m={fee:v}}else return null}l=m?.path?{...m,amountOut:(await Lo(s,e,m.path,o.amountIn,"in")).amount}:await Ka({tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountIn:o.amountIn,chainId:s,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:m?[m.fee]:e.feeTiers,hubs:m?[]:[...e.hubCurrencies??[],...e.hubPaths??[]]})}catch{return console.warn(`[UniV3Venue] No viable route for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${s}.`),null}const c=wr(l.amountOut,i),d=e.routerHasDeadline?{deadline:BigInt(Math.floor(Date.now()/1e3)+vr)}:{},p=e.routerHasDeadline?oi:l.path?ni:Oa,f=l.path?xt({abi:p,functionName:"exactInput",args:[{path:l.path,recipient:r,...d,amountIn:o.amountIn,amountOutMinimum:c}]}):xt({abi:p,functionName:"exactInputSingle",args:[{tokenIn:o.tokenIn,tokenOut:o.tokenOut,fee:l.fee,recipient:r,...d,amountIn:o.amountIn,amountOutMinimum:c,sqrtPriceLimitX96:0n}]}),h=[{to:o.tokenIn,value:0n,data:xt({abi:tt,functionName:"approve",args:[e.swapRouter,o.amountIn]})},{to:e.swapRouter,value:0n,data:f}];return{venue:t,amountOut:l.amountOut,amountOutMinimum:c,calls:h}}}}function Ir(e){const t=e.name??"Uniswap v3",n=e.chainIds??Xa;return{name:t,chainIds:n,resolve:async(o,s,r)=>{if(be(o.tokenIn)||be(o.tokenOut))return null;const a=o.maxSlippage??zo;let i;try{i=await Za({tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountOut:o.amountOut,chainId:s,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers,hubs:[...e.hubCurrencies??[],...e.hubPaths??[]]})}catch{return null}const l=BigInt(Math.round(a*1e4)),c=i.amountIn+i.amountIn*l/10000n;return{venue:t,amountIn:i.amountIn,amountInMax:c,amountOut:o.amountOut,calls:[Ya({config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},routerHasDeadline:e.routerHasDeadline,route:i,tokenIn:o.tokenIn,tokenOut:o.tokenOut,recipient:r,amountOut:o.amountOut,amountInMaximum:c})]}}}}function ai(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(Ho(e.satsuma)),e?.aerodrome!==!1&&t.push(kr(e?.aerodrome??Cr)),t.push(Sd(e?.oneInch));const n=t.map(fd);function o(a){return n.find(i=>i.chainIds.includes(a))}async function s(a,i,l,c){const d=n.filter(m=>m.chainIds.includes(i));if(d.length===0)throw new Ne("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${i}. Cannot resolve swap ${a.tokenIn} \u2192 ${a.tokenOut}.`,{chainId:i,tokenIn:a.tokenIn,tokenOut:a.tokenOut,amountIn:a.amountIn.toString()});const p=await Promise.allSettled(d.map(m=>m.resolve(a,i,l,c)));let f=null;for(const m of p)c&&m.status==="fulfilled"&&m.value&&(m.value.venue!==c.venue||m.value.calls.length!==c.calls.length||m.value.calls.some((g,y)=>g.to.toLowerCase()!==c.calls[y].to.toLowerCase()||g.data.slice(0,10)!==c.calls[y].data.slice(0,10)))||m.status==="fulfilled"&&m.value&&(!f||m.value.amountOut>f.amountOut)&&(f=m.value);if(f)return f;const h=p.find(m=>m.status==="rejected");if(h)throw h.reason;return null}async function r(a,i,l){const c=[],d=[];for(const p of a){if(!Cd(p)){c.push(p);continue}const f=await s(p,i,l);if(!f)throw new Ne("NO_LIQUIDITY",`No venue returned a quote for ${p.tokenIn} \u2192 ${p.tokenOut} on chain ${i}.`,{chainId:i,tokenIn:p.tokenIn,tokenOut:p.tokenOut,amountIn:p.amountIn.toString()});c.push(...f.calls),d.push(f)}return{calls:c,resolvedSwaps:d}}return{resolveSwapIntents:r,resolveSwap:s,getVenueForChain:o,venues:t}}const Wn="0x0000000000000000000000000000000000000000",Sr=[{fee:100,tickSpacing:1},{fee:500,tickSpacing:10},{fee:3e3,tickSpacing:60},{fee:1e4,tickSpacing:200}],ii=Wn,li=.02,Dd=1800,ci={name:"Uniswap v4",quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",universalRouter:"0x6ff5693b99212da76ad316178a184ab56d299b43",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",chainIds:[8453],hubCurrencies:["0x4200000000000000000000000000000000000006",Wn,"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]},di={name:"Uniswap v4",quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",universalRouter:"0x8876789976decbfcbbbe364623c63652db8c0904",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",routerHasHopPrice:!0,chainIds:[4663],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73",Wn,"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"]},ui=Tn(["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)"]),Od=Tn(["function approve(address token, address spender, uint160 amount, uint48 expiration)"]),Rd=Tn(["function execute(bytes commands, bytes[] inputs, uint256 deadline) payable"]),pi="0x10",Md="04",Wd="06",Nd="07",Pd="08",Ud="09",ws="0c",bs="0e",Ld=[{name:"currency0",type:"address"},{name:"currency1",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"}],zd=[{name:"intermediateCurrency",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"},{name:"hookData",type:"bytes"}],Hn=(e,t)=>e.toLowerCase()===t.toLowerCase();function vs(e){return be(e)?Wn:e}function Hd(e,t){return e.toLowerCase()<t.toLowerCase()?[e,t]:[t,e]}function fi(e,t,n,o,s){const r=[],[a,i]=Hd(e,t);for(const{fee:c,tickSpacing:d}of Sr)r.push({kind:"single",poolKey:{currency0:a,currency1:i,fee:c,tickSpacing:d,hooks:ii},zeroForOne:Hn(e,a)});const l=(c,d)=>!!s&&(Hn(c,Wn)&&Hn(d,s)||Hn(c,s)&&Hn(d,Wn));for(const c of n)if(!(Hn(c,e)||Hn(c,t))&&!(l(c,e)||l(c,t)))for(const d of Sr)for(const p of Sr){const f=(h,m)=>({intermediateCurrency:h,fee:m.fee,tickSpacing:m.tickSpacing,hooks:ii,hookData:"0x"});r.push({kind:"multi",path:o==="in"?[f(c,d),f(t,p)]:[f(e,d),f(c,p)]})}return r}async function mi(e,t,n,o,s,r){const a=yt(e),i=(await Promise.allSettled(n.map(async l=>{const{result:c}=l.kind==="single"?await a.simulateContract({address:t.quoter,abi:ui,functionName:r==="in"?"quoteExactInputSingle":"quoteExactOutputSingle",args:[{poolKey:l.poolKey,zeroForOne:l.zeroForOne,exactAmount:s,hookData:"0x"}]}):await a.simulateContract({address:t.quoter,abi:ui,functionName:r==="in"?"quoteExactInput":"quoteExactOutput",args:[{exactCurrency:o,path:l.path,exactAmount:s}]}),d=c[0];if(d<=0n)throw new Error("zero quote");return{candidate:l,amount:d}}))).filter(l=>l.status==="fulfilled").map(l=>l.value);return i.length===0?null:(i.sort((l,c)=>l.amount<c.amount?-1:l.amount>c.amount?1:0),r==="in"?i[i.length-1]:i[0])}function hi(e){const{candidate:t,direction:n,currencyIn:o,currencyOut:s,recipient:r,exactAmount:a,limitAmount:i,deadline:l,routerHasHopPrice:c,sweepNativeTo:d}=e;let p,f;t.kind==="single"?(p=n==="in"?`0x${Wd}${ws}${bs}`:`0x${Pd}${ws}${bs}`,f=zn([{type:"tuple",components:[{name:"poolKey",type:"tuple",components:Ld},{name:"zeroForOne",type:"bool"},{name:n==="in"?"amountIn":"amountOut",type:"uint128"},{name:n==="in"?"amountOutMinimum":"amountInMaximum",type:"uint128"},...c?[{name:"minHopPriceX36",type:"uint256"}]:[],{name:"hookData",type:"bytes"}]}],[{poolKey:t.poolKey,zeroForOne:t.zeroForOne,[n==="in"?"amountIn":"amountOut"]:a,[n==="in"?"amountOutMinimum":"amountInMaximum"]:i,...c?{minHopPriceX36:0n}:{},hookData:"0x"}])):(p=n==="in"?`0x${Nd}${ws}${bs}`:`0x${Ud}${ws}${bs}`,f=zn([{type:"tuple",components:[{name:n==="in"?"currencyIn":"currencyOut",type:"address"},{name:"path",type:"tuple[]",components:zd},...c?[{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:s,path:t.path,...c?{minHopPriceX36:[]}:{},[n==="in"?"amountIn":"amountOut"]:a,[n==="in"?"amountOutMinimum":"amountInMaximum"]:i}]));const h=zn([{type:"address"},{type:"uint256"}],[o,n==="in"?a:i]),m=zn([{type:"address"},{type:"address"},{type:"uint256"}],[s,r,0n]),g=zn([{type:"bytes"},{type:"bytes[]"}],[p,[f,h,m]]),y=d?`${pi}${Md}`:pi,w=d?[g,zn([{type:"address"},{type:"address"},{type:"uint256"}],[Wn,d,0n])]:[g];return xt({abi:Rd,functionName:"execute",args:[y,w,l]})}function gi(){return BigInt(Math.floor(Date.now()/1e3)+Dd)}function yi(e,t,n,o){return{to:e.permit2,value:0n,data:xt({abi:Od,functionName:"approve",args:[t,e.universalRouter,n,Number(o)]})}}function xi(e){const t=e.name??"Uniswap v4",n=e.v3?Ho({...e.v3,chainIds:e.chainIds}):null;return{name:t,chainIds:e.chainIds,resolve:async(o,s,r)=>{const a=o.maxSlippage??li,i=vs(o.tokenIn),l=vs(o.tokenOut),c=be(o.tokenIn),d=e.hubCurrencies??[Wn];let p=null;if(!Hn(i,l)&&o.amountIn>0n){const f=await mi(s,e,fi(i,l,d,"in",hr(s)),i,o.amountIn,"in").catch(()=>null);if(f){const h=Ra(f.amount,a),m=gi(),g=[];c||(g.push({to:o.tokenIn,value:0n,data:xt({abi:tt,functionName:"approve",args:[e.permit2,o.amountIn]})}),g.push(yi(e,o.tokenIn,o.amountIn,m))),g.push({to:e.universalRouter,value:c?o.amountIn:0n,data:hi({candidate:f.candidate,direction:"in",currencyIn:i,currencyOut:l,recipient:r,exactAmount:o.amountIn,limitAmount:h,deadline:m,routerHasHopPrice:e.routerHasHopPrice})}),p={venue:t,amountOut:f.amount,amountOutMinimum:h,calls:g}}}return!p&&n?n.resolve(o,s,r):p}}}function wi(e){const t=e.name??"Uniswap v4";return{name:t,chainIds:e.chainIds,resolve:async(n,o,s)=>{const r=be(n.tokenIn),a=vs(n.tokenIn),i=vs(n.tokenOut);if(Hn(a,i)||n.amountOut<=0n)return null;const l=n.maxSlippage??li,c=e.hubCurrencies??[Wn],d=await mi(o,e,fi(a,i,c,"out",hr(o)),i,n.amountOut,"out").catch(()=>null);if(!d)return null;const p=BigInt(Math.round(l*1e4)),f=d.amount+d.amount*p/10000n,h=gi();return{venue:t,amountIn:d.amount,amountInMax:f,amountOut:n.amountOut,calls:[...r?[]:[yi(e,n.tokenIn,f,h)],{to:e.universalRouter,value:r?f:0n,data:hi({candidate:d.candidate,direction:"out",currencyIn:a,currencyOut:i,recipient:s,exactAmount:n.amountOut,limitAmount:f,deadline:h,routerHasHopPrice:e.routerHasHopPrice,sweepNativeTo:r?s:void 0})}]}}}}const Ar=[{...br,protocol:"uniswap-v3",chainId:4114},{...br,protocol:"uniswap-v3",chainId:5115},{...Ja,protocol:"uniswap-v3",chainId:8453},{...$a,protocol:"uniswap-v3",chainId:1},{..._a,protocol:"uniswap-v3",chainId:42161},{...Ad,protocol:"uniswap-v3",chainId:137},{...Ed,protocol:"uniswap-v3",chainId:56},{...Fd,protocol:"uniswap-v3",chainId:143},{...ei,protocol:"uniswap-v3",chainId:4663},{...ti,protocol:"uniswap-v3",chainId:4663},{...ci,protocol:"uniswap-v4",chainId:8453},{...di,protocol:"uniswap-v4",chainId:4663},{...Cr,protocol:"aerodrome-slipstream",chainId:8453}];function Co(e){const t=e?.includeDefaults===!1?e.venues??[]:[...Ar,...e?.venues??[]],n=[],o=[];for(const s of t){const r=[s.chainId];switch(s.protocol){case"uniswap-v3":{const a={...s,chainIds:r};n.push(Ho(a)),o.push(Ir(a));break}case"uniswap-v4":{const a={...s,chainIds:r};n.push(xi(a)),o.push(wi(a));break}case"aerodrome-slipstream":{const a={...s,chainIds:r};n.push(kr(a)),o.push(ri(a));break}default:{const a=s;throw new Ne("INVALID_PARAMS",`Unsupported liquidity venue protocol: ${a.protocol}`,{protocol:a.protocol})}}}return{input:n,output:o}}const Er=new Set(["WBTC","CBTC"]),bi=new Set(["btc","wbtc","wcbtc","cbtc"]);function vi(e,t){return!e||!t?!1:e===t?!0:Er.has(e)&&Er.has(t)}function qn(e){const[t,n,o]=e.split(":");if(t!=="evm"||!n||!o)return null;const s=Number(n);if(!Number.isFinite(s))return null;const r=o.startsWith("0x")?o.toLowerCase():`0x${o.toLowerCase()}`;return{chainId:s,address:r}}function Cs(e){return(e??"").trim().replace(/^test\s+/i,"").replace(/^spice/i,"").toLowerCase().replace(/[^a-z0-9]/g,"")}function qd(e){return new Set([e.receiptTokenName,e.displaySymbol,e.symbol,e.displayName,e.name].map(Cs).filter(Boolean))}function Vd(e,t){const n=qd(e),o=[t.symbol,t.name,t.equivalenceGroup].map(Cs);if(o.some(a=>a&&n.has(a)))return!0;const s=[...n].some(a=>bi.has(a)),r=o.some(a=>bi.has(a))||Er.has(t.equivalenceGroup??"");return s&&r}function Ci(e,t,n){const o=new Set(t.map(Cs).filter(Boolean)),s=r=>{if(n&&ge(r.address,n))return 0;const a=[r.symbol,r.name,r.equivalenceGroup].map(Cs).findIndex(i=>i&&o.has(i));return a===-1?4:a+1};return[...e].sort((r,a)=>{const i=s(r)-s(a);return i!==0?i:r.address.toLowerCase().localeCompare(a.address.toLowerCase())})}function ko(e,t){const n=e.chainTokens?Object.keys(e.chainTokens):[],o=[];for(const s of n){const r=qn(s);if(!r||r.chainId!==t)continue;const a=r.address,i=be(a)?Ge(t)?.nativeCurrency:void 0,l=Ft(a,t)??(i?{...i}:void 0);l&&(!Fr(e,a,t)&&!(e.isUniversal&&Vd(e,l))||o.some(c=>ge(c,a))||o.push(a))}return Ci(o.map(s=>{const r=Ft(s,t);return{address:s,symbol:r?.symbol,name:r?.name,equivalenceGroup:r?.equivalenceGroup}}),[e.receiptTokenName,e.displaySymbol,e.symbol,e.displayName,e.name],e.chainId===t&&!e.isUniversal?e.address:void 0).map(s=>s.address)}function Fr(e,t,n){return e.chainId===n&&ge(e.address,t)?!0:qo(e.address,e.chainId,t,n)}async function Qd(e,t){const n=yt(e),o=Jn(e);return be(t)?n.getBalance({address:o}):await n.readContract({address:t,abi:tt,functionName:"balanceOf",args:[o]})}function Tr(e,t,n){const o=gs(n),s=o.find(a=>ge(a.address,e));if(s&&(t===n||!be(e)))return s;const r=Ft(e,t);if(r)return Ci(o.filter(a=>vi(a.equivalenceGroup,r.equivalenceGroup)),[r.symbol,r.name,r.equivalenceGroup])[0]}function ks(e){return e.equivalenceGroup==="USDC"&&e.symbol.toUpperCase()!=="USDT"}function ki(e){const t=Uo(e);if(!t||t===Tt)return;const n=gs(e).filter(ks);return n.find(o=>o.symbol.toUpperCase()==="USDC")??n[0]}function Br(e,t){if(e.chainId===t)return null;const n=Uo(e.chainId),o=Uo(t);if(!n||n===Tt||!o||o===Tt)return null;const s=!e.isNative&&!be(e.address)?Ft(e.address,e.chainId):void 0,r=s&&ks(s)?Tr(e.address,e.chainId,t):void 0,a=r?s:ki(e.chainId),i=r??ki(t);if(!a||!i)return null;const l=c=>({address:c.address,symbol:c.symbol,decimals:c.decimals,chainId:c.chainId});return{source:l(a),destination:l(i)}}function jd(e,t){return!!Br(e,t)}function Sn(e,t){if(e.chainId===t)return e.address;const n=Tr(e.address,e.chainId,t);return n?n.address:null}async function eo(e,t,n,o){const s=Ft(t,n);return s?s.decimals:e?.chainId===n&&ge(e.address,t)&&!e.isUniversal?e.decimals:o?.chainId===n&&ge(o.address,t)?o.decimals:as(n,t)}async function Ii(e,t,n={}){const o=Sn(e,t),s=ko(e,t);if(s.length===0)return o;if(s.length===1)return s[0];const r=n.requiredAmount??0n,a=i=>{const l=s.map(c=>({candidate:c,balance:i.get(be(c)?"native":c.toLowerCase())??0n})).filter(c=>c.balance>0n).sort((c,d)=>c.balance===d.balance?0:c.balance>d.balance?-1:1);return l.length===0?null:((r>0n?l.find(c=>c.balance>=r):l[0])??l[0]).candidate};try{const i=await Promise.all(s.map(async d=>({key:be(d)?"native":d.toLowerCase(),value:await Qd(t,d)}))),l=new Map(i.map(({key:d,value:p})=>[d,p])),c=a(l);if(c)return c}catch{}return o}function qo(e,t,n,o){const s=Ft(e,t),r=Ft(n,o);return s&&r?vi(s.equivalenceGroup,r.equivalenceGroup):Zc(e,n)}function Is(e,t){return qo(e.address,e.chainId,t.address,t.chainId)}const Si=.01;function Ai(e,t=!1){const n=Number.isFinite(e.balanceUsd)&&e.balanceUsd>0;return e.isDiscovered?n&&e.balanceUsd>=Si:!t||!n||e.balanceUsd>=Si}function Ss(e,t=!1){return!!e&&e._source==="wallet"&&(e.location==="external"||e._fundingWallet==="external"||!e.location&&!e._fundingWallet&&t)}function nt(e){return e.positionId??`${e.owner?.toLowerCase()??""}:${e.location??e._source??""}:${e.chainId}:${e.receiptTokenId??Ye(e.address).toLowerCase()}`}function Ei(e,t){if(!t?.length||e.symbol!==void 0&&is({...e,symbol:e.symbol},t))return!0;const n=o=>t.some(s=>ge(Ye(s),Ye(o)));return n(e.address)||Object.keys(e.chainTokens??{}).some(o=>{const s=qn(o);return s?n(s.address):!1})}function po(e,t,n,o,s,r){const a=(g,y=!1)=>({eligible:!1,reason:g,policyExcluded:y}),i=e._source==="wallet"||e.location==="external"||e.location==="embedded",l=t==="spend-source"&&i&&!!o&&e.chainId===o.chainId&&ge(Ye(e.address),Ye(o.address));if(n.isWhitelistGateActive||!l&&!is(e,n.allowedTokens))return a("Asset excluded by client policy",!0);if(t!=="withdraw-destination"&&!l&&!Ai(e))return a("Asset is unpriced or below the minimum value",!0);if(t==="holding")return{eligible:!0,reason:null};if(e.balanceError)return a(e.balanceError);if(!l&&!Ei(e,s))return a("Asset excluded by action policy",!0);const c=new Set(o?[o.chainId]:[]);e._source!=="spice"&&e.location!=="rollup"&&c.add(e.chainId);for(const g of c)if(!ba(g,n.rpcOverrides)?.trim())return a(`Configure SpiceFlowProvider rpcOverrides[${g}] before using this asset.`);if(r?.requiresEscrow){const g=Ft(e.address,e.chainId);if(!g||!ks(g))return a("This asset has no supported escrow mapping")}if(!o)return{eligible:!0,reason:null};const d=n.liquidityVenues?.includeDefaults===!1?n.liquidityVenues.venues??[]:[...Ar,...n.liquidityVenues?.venues??[]],p=g=>d.some(y=>y.chainId===g),f=i&&e.chainId!==o.chainId,h=f?Br(e,o.chainId):null;if(f&&!h)return a("No supported source route");if(h&&!ge(Ye(e.address),Ye(h.source.address))&&!p(e.chainId))return a("No conversion venue configured on the source chain");const m=h?.destination.address??Sn(e,o.chainId);return t==="withdraw-destination"?(e.chainTokens||e.receiptTokenId?ko(e,o.chainId):m?[m]:[]).some(g=>ge(Ye(g),Ye(o.address)))?{eligible:!0,reason:null}:a("No supported withdrawal mapping"):m&&ge(Ye(m),Ye(o.address))?{eligible:!0,reason:null}:!m&&!jd(e,o.chainId)?a("No supported destination route"):p(o.chainId)?{eligible:!0,reason:null}:a("No conversion venue configured on the destination chain")}function As(){const e=Qt(Mt),[t]=O(Rc);return e?.inventory??t}function Dr(e,t,n,o,s){const r=As(),a=s??r,i=ue(()=>a.entry(e),[a,e]),[,l]=O(0);ae(()=>{if(n)return i.subscribe(()=>l(d=>d+1),t,o)},[i,n,t,o]);const c=te(()=>i.refresh(),[i]);return{...n?i.snapshot():Mc,refresh:c}}var Fi="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==",Gd="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=",Yd="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=",Vo="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 Qo=Wa(1)?.logo??"",Kd=Na.find(e=>e.symbol==="USDC")?.logo??"",to=Object.fromEntries([...Xc(),...Jc()].map(e=>[e.id,e.logo])),jo={metamask:Fi,metaMask:Fi,rabby:Gd,phantom:Yd},Or=Object.fromEntries(Na.map(e=>[e.symbol.toUpperCase(),e.logo])),Zd={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]},Xd={btc:["wcbtc","cbtc","wbtc"]};function Es(e){return e.replace(/^test\s*/i,"").replace(/^spice/i,"").trim()}function Vn(e){return Es(e).toLowerCase()}function Ti(e){return Vn(e??"").replace(/[^a-z0-9]/g,"")}function Rr(e){const t=Vn(e);return[t,...Xd[t]??[]].filter(Boolean)}function Jd(e){try{return BigInt(e.balanceAvailable||"0")}catch{return 0n}}function Bi(e){return Array.isArray(e.chainTokens)?e.chainTokens:Object.keys(e.chainTokens??{})}function Di(e,t){const n=Ge(e),o=t.toLowerCase();return o===Tt.toLowerCase()?n?.nativeCurrency.decimals??18:n?.supportedTokens?.find(s=>s.address.toLowerCase()===o)?.decimals??18}function $d(e,t,n,o=[]){const s=Di(t,n),r=e.filter(i=>Oi(i,t,n,o));if(r.length===0)return null;const a=r.reduce((i,l)=>Math.min(i,l.decimals??s),s);return{chainDecimals:s,receiptDecimals:a}}function Oi(e,t,n,o){if(Bi(e).some(r=>{const a=qn(r);return a&&qo(a.address,a.chainId,n,t)}))return!0;const s=new Set(o.map(Ti).filter(Boolean));return s.size===0?!1:s.has(Ti(e.tokenName||e.receiptToken))}function Ri(e,t,n,o=[]){const s=Di(t,n);return e.reduce((r,a)=>Oi(a,t,n,o)?r+co(Jd(a),a.decimals??s,s):r,0n)}function Mi(e,t){const n=new Set([...Rr(t),...Rr(Es(t))]);return[...e].sort((o,s)=>{const r=Vn(o.symbol),a=Vn(s.symbol),i=Vn(o.name),l=Vn(s.name),c=n.has(r)?0:n.has(i)?1:2,d=n.has(a)?0:n.has(l)?1:2;return c!==d?c-d:o.address.toLowerCase().localeCompare(s.address.toLowerCase())})[0]}function _d(e){const t=e&&e.length>0?e:Object.keys(ls).map(Number).filter(Number.isFinite),n=new Map;for(const o of t){const s=Ge(o);if(!s)continue;const r=`${o}:${Tt.toLowerCase()}`;n.has(r)||n.set(r,{address:Tt,chainId:o,symbol:s.nativeCurrency.symbol,name:s.nativeCurrency.name,decimals:s.nativeCurrency.decimals,isNative:!0,logoURI:Or[s.nativeCurrency.symbol.toUpperCase()]??s.logo});for(const a of s.supportedTokens??[]){const i=a.address.toLowerCase(),l=`${o}:${i}`;n.has(l)||n.set(l,{address:i,chainId:o,symbol:a.symbol,name:a.name,decimals:a.decimals,isNative:be(i),logoURI:a.logo})}}return n}function eu(e,t){const n=_d(t),o=Es(e.tokenName),s=Vn(e.tokenName),r=Rr(e.tokenName),a=Array.isArray(e.chainTokens)?e.chainTokens.map(m=>[m,void 0]):Object.entries(e.chainTokens??{}),i=a.map(([m])=>qn(m)).filter(m=>m!==null),l=new Map;for(const[m,g]of a){const y=qn(m);if(!y||!Number.isSafeInteger(y.chainId)||y.chainId<0||!/^evm:[0-9]+:(?:0x)?[0-9a-fA-F]{40}$/.test(m)){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 w=`${y.chainId}:${y.address.toLowerCase()}`;if(l.has(w)){const x=l.get(w);if(x?.name!==g?.name||x?.decimals!==g?.decimals)throw new Error("Conflicting chain token metadata")}l.set(w,g)}const c=(m,g)=>{const y=l.get(`${g.chainId}:${g.address.toLowerCase()}`);return{...m,name:typeof y?.name=="string"&&y.name.length>0?y.name:m.name,decimals:typeof y?.decimals=="number"?y.decimals:m.decimals}},d=i.map(m=>{const g=n.get(`${m.chainId}:${m.address.toLowerCase()}`);return g?c(g,m):void 0}).filter(m=>m!==void 0),p=Zd[s]??[];if(p.length>0)for(const m of p){const g=d.filter(y=>y.chainId===m);if(g.length>0)return Mi(g,e.tokenName)}if(d.length>0)return Mi(d,e.tokenName);const f=Array.from(n.values()).filter(m=>r.includes(Vn(m.symbol))||r.includes(Vn(m.name)));if(p.length>0)for(const m of p){const g=f.find(y=>y.chainId===m);if(g)return g}if(f.length>0)return f[0];const h=i[0];if(h){const m=l.get(`${h.chainId}:${h.address.toLowerCase()}`);return{address:h.address,chainId:h.chainId,symbol:o||e.tokenName,name:typeof m?.name=="string"&&m.name.length>0?m.name:o||e.tokenName,decimals:typeof m?.decimals=="number"?m.decimals:e.decimals??18,isNative:be(h.address),logoURI:void 0}}}function tu(e,t){let n;try{n=BigInt(e.balanceAvailable||"0")}catch{return null}if(n<=0n)return null;if(t?.length){const m=Bi(e).map(qn).filter(g=>g!==null);if(m.length>0&&!m.some(g=>t.includes(g.chainId)))return null}let o;try{o=eu(e,t)}catch{return null}const s=o?.decimals??e.decimals??18,r=e.decimals??s,a=co(n,r,s),i=o?.address??Tt,l=o?.chainId??0,c=Es(e.tokenName),d=o?.symbol??c,p=o?.name??c,f=parseFloat(Fe(a,s)),h=typeof e.balanceUsd=="number"?e.balanceUsd:typeof e.balanceUsd=="string"&&Number(e.balanceUsd)||0;return{address:i,symbol:d,name:p,decimals:s,chainId:l,balance:a,balanceFormatted:f,balanceUsd:h,isNative:o?.isNative??be(i),logoURI:o?.logoURI,displaySymbol:c||d,displayName:c||p,displayChainName:"Spicenet",receiptTokenId:e.receiptToken,receiptTokenName:e.tokenName||p,receiptTokenDecimals:r,chainTokens:e.chainTokens&&!Array.isArray(e.chainTokens)?e.chainTokens:void 0,isUniversal:!0}}const Mr=6e4,nu=3e5,Wi="https://api.g.alchemy.com/prices/v1",Io=new Map;function Wr(e,t){try{const n=t??yt(e).transport.url;if(typeof n!="string")return null;const{hostname:o,pathname:s}=new URL(n);if(!o.endsWith(".g.alchemy.com"))return null;const r=s.split("/").filter(Boolean).pop();return r?{network:o.slice(0,-14),key:r}:null}catch{return null}}const Go=(e,t)=>`${e.network}:${e.key}:${t.toLowerCase()}`;function Yo(e,t){const n=Io.get(Go(e,t));if(!n?.price||n.updatedAt===void 0)return;const o=Date.now()-n.updatedAt;if(!(o>=nu))return{price:n.price,stale:o>=Mr}}function Ni(e){const t=Number(e.prices?.find(n=>n.currency==="usd")?.value);return Number.isFinite(t)&&t>0?t:0}async function Pi(e,t,n){const o=[],s=new Set,r=Date.now();for(const a of new Set(t.map(i=>i.toLowerCase()))){const i=Io.get(Go(e,a));i?.pending?s.add(i.pending):(!i||r-i.attemptedAt>=Mr&&(i.updatedAt===void 0||r-i.updatedAt>=Mr))&&o.push(a)}for(let a=0;a<o.length;a+=25){const i=o.slice(a,a+25),l=Promise.resolve().then(async()=>{try{const c=await n(i);for(const d of i){const p=c.get(d);if(!p)continue;const f=Io.get(Go(e,d));f.price=p,f.updatedAt=Date.now()}}catch{}finally{for(const c of i)Io.get(Go(e,c)).pending=void 0}});for(const c of i){const d=Go(e,c);Io.set(d,{...Io.get(d),attemptedAt:r,pending:l})}s.add(l)}await Promise.all(s)}async function Nr(e,t){return await Pi(e,t,async n=>{const o=await fetch(`${Wi}/${e.key}/tokens/by-address`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({addresses:n.map(a=>({network:e.network,address:a}))}),signal:AbortSignal.timeout(1e4)});if(!o.ok)throw new Error("Provider price request failed");const s=await o.json(),r=new Map;for(const a of s?.data??[]){if(a.network&&a.network!==e.network)continue;const i=String(a.address).toLowerCase();n.includes(i)&&r.set(i,Ni(a))}return r}),new Map(t.map(n=>[n.toLowerCase(),Yo(e,n)?.price??0]))}async function Pr(e,t){const n=`native:${t}`;return await Pi(e,[n],async()=>{const o=await fetch(`${Wi}/${e.key}/tokens/by-symbol?symbols=${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(1e4)});if(!o.ok)throw new Error("Provider native price request failed");const s=(await o.json())?.data?.find(r=>r.symbol?.toUpperCase()===t.toUpperCase());return new Map([[n.toLowerCase(),s?Ni(s):0]])}),Yo(e,n)?.price??0}async function ou(e,t){const n=t.supportedChains,o=e.map(s=>{if(Number.isFinite(s.balanceUsd)&&s.balanceUsd>0)return[];const r=Object.keys(s.chainTokens??{}).map(qn).filter(a=>!!a&&fn(a.address)&&!!n?.includes(a.chainId));return r.sort((a,i)=>{const l=c=>c===t.nativeChainId?-1:n.indexOf(c);return l(a.chainId)-l(i.chainId)||+!ge(a.address,s.address)-+!ge(i.address,s.address)}),r.flatMap(a=>{const i=t.rpcOverrides?.[a.chainId];if(!i)return[];const l=Wr(a.chainId,i);if(!l)return[];const c=be(a.address)?Ge(a.chainId)?.nativeCurrency.symbol:void 0,d=c?`native:${c}`:a.address;return[{rpc:l,token:d,address:a.address,nativeSymbol:c}]})});return(typeof document>"u"||!document.hidden)&&await Promise.all(o.map(async s=>{for(const r of s)if(r.nativeSymbol?await Pr(r.rpc,r.nativeSymbol).catch(()=>0):(await Nr(r.rpc,[r.address]).catch(()=>new Map)).get(r.address.toLowerCase()))break})),e.map((s,r)=>{if(Number.isFinite(s.balanceUsd)&&s.balanceUsd>0)return s;const a=o[r].map(i=>Yo(i.rpc,i.token)).find(Boolean);return{...s,balanceUsd:a?s.balanceFormatted*a.price:0,priceStatus:a?a.stale?"stale":"fresh":"unavailable"}})}function su(e,t,n){const o=Qt(Mt),[s,r]=O(()=>typeof document>"u"||!document.hidden);ae(()=>{const d=()=>r(!document.hidden);return document.addEventListener("visibilitychange",d),()=>document.removeEventListener("visibilitychange",d)},[]);const a={supportedChains:n??o?.supportedChainIds,nativeChainId:o?.nativeChainId,rpcOverrides:o?.rpcOverrides},i=JSON.stringify([e,a],(d,p)=>typeof p=="bigint"?p.toString():p),l=te(()=>ou(e,a),[i]),c=Dr(`prices:${i}`,l,t&&s&&e.length>0,6e4);return c.updatedAt?c.assets:e}function ru(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 Ui=({address:e,supportedChains:t,enabled:n=!0,refetchInterval:o,priceEnabled:s=!1})=>{const r=Qt(Mt),a=r?.apiUrl||Nc,i=As(),l=r?.supportedChainIds??t,c=JSON.stringify([...l??[]].sort((b,S)=>b-S)),d=e?.toLowerCase(),p=te(async()=>{const b=await Wc(`${a}/wallets/${d}/balance`,{cache:"no-store"});if(!b.ok)throw new Error(`Failed to fetch balance: ${b.status}`);const S=await b.json();if(!Array.isArray(S.balances))throw new Error("Invalid balance response");return S.balances.map(T=>{const E=tu({receiptToken:typeof T.receiptToken=="string"?T.receiptToken:void 0,tokenName:String(T.tokenName??""),balanceAvailable:String(T.balanceAvailable??"0"),chainTokens:ru(T),decimals:typeof T.decimals=="number"?T.decimals:void 0,balanceUsd:typeof T.balanceUsd=="number"||typeof T.balanceUsd=="string"?T.balanceUsd:null},l);return E?{...E,owner:d,location:"rollup",_source:"spice",positionId:`${d}:rollup:${E.receiptTokenId??E.address}`}:null}).filter(T=>T!==null)},[d,a,c,r?.nativeChainId,r?.rpcOverrides]),{assets:f,loading:h,refreshing:m,error:g,updatedAt:y}=Dr(`rollup:${d}:${a}:${c}`,p,n&&!!d,o??0,i),w=JSON.stringify(t??[]),x=ue(()=>g?f.map(b=>({...b,balanceError:g,balanceStatus:"stale"})):f,[f,g]),v=su(x,n&&s,l),k=ue(()=>v.filter(b=>!t?.length||t.includes(b.chainId)||Object.keys(b.chainTokens??{}).some(S=>t.some(T=>S.startsWith(`evm:${T}:`)))),[v,w]),A=te(b=>k.filter(S=>S.chainId===b),[k]);return{assets:k,loading:h,error:g,hasBalance:k.some(b=>b.balance>0n),refreshing:m,updatedAt:y,refetch:i.invalidate,getAssetsByChain:A}};async function au(e,t,n){if(n)return{decimals:n.decimals,symbol:n.symbol,name:n.name,logoURI:n.logo};const[o,s,r]=await Promise.all([_n(e,{address:t,abi:tt,functionName:"decimals"}),_n(e,{address:t,abi:tt,functionName:"symbol"}).catch(()=>"TOKEN"),_n(e,{address:t,abi:tt,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:s,name:r,logoURI:void 0}}const Li=async(e,t,n)=>{const o=yt(t,n),s=Ge(t),r=await ur(o,{address:e}),a=s.nativeCurrency,i=s.supportedTokens?.find(l=>be(l.address));return{address:Tt,name:a.name,symbol:a.symbol,decimals:a.decimals,balance:r,balanceFormatted:Number(Fe(r,a.decimals)),balanceUsd:0,logoURI:i?.logo||s.logo,isNative:!0,chainId:t}},iu=async(e,t,n,o,s,r,a)=>{try{if(!fn(n))return null;const i=zt(n),l=fn(e)?zt(e):e,c=yt(t,a),d=await _n(c,{address:i,abi:tt,functionName:"balanceOf",args:[l]}),p=Number(Fe(d,r));return d>0n?{address:i,name:o,symbol:s,decimals:r,balance:d,balanceFormatted:p,balanceUsd:0,logoURI:void 0,isNative:!1,chainId:t}:null}catch(i){throw i}},zi=(e,t)=>{const n=Ge(t);if(!n)return e;const o=new Set(e.map(r=>r.address.toLowerCase())),s=e.some(r=>r.isNative);for(const r of n.supportedTokens||[])be(r.address)&&s||o.has(r.address.toLowerCase())||e.push({address:r.address,name:r.name,symbol:r.symbol,decimals:r.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:r.logo,isNative:be(r.address),chainId:t});if(!e.find(r=>r.isNative)){const r=n.supportedTokens?.find(a=>be(a.address));e.push({address:Tt,name:n.nativeCurrency.name,symbol:n.nativeCurrency.symbol,decimals:n.nativeCurrency.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:r?.logo||n.logo,isNative:!0,chainId:t})}return e},lu=async(e,t,n)=>{const o=[],s=async i=>{for(const l of i){const c=await iu(e,t,l.address,l.name,l.symbol,l.decimals,n);c&&(c.logoURI=l.logo,o.push(c))}},r=await Li(e,t,n);r.balance>0n&&o.push(r);const a=(Ge(t)?.supportedTokens||[]).filter(i=>!be(i.address));if(a.length>0)try{const i=yt(t,n),l=zt(e),c=a.filter(h=>fn(h.address)).map(h=>({address:zt(h.address),abi:tt,functionName:"balanceOf",args:[l]})),d=await i.multicall({contracts:c}),p=a.filter(h=>fn(h.address)),f=[];d.forEach((h,m)=>{if(h.status==="success"){const g=h.result;if(g&&g>0n){const y=p[m],w=Number(Fe(g,y.decimals));g>0n&&o.push({address:zt(y.address),name:y.name,symbol:y.symbol,decimals:y.decimals,balance:g,balanceFormatted:w,balanceUsd:0,logoURI:y.logo,isNative:!1,chainId:t})}}else f.push(p[m])}),await s(f)}catch{await s(a)}return{tokens:zi(o,t),chainId:t}},cu=async(e,t,n)=>{const o=new Map,s=Wr(e,n?n[e]??"":void 0);if(!s)return o;const r=t.filter(c=>be(c)),a=t.filter(c=>!be(c)),[i,l]=await Promise.all([a.length?Nr(s,a).catch(()=>new Map):new Map,r.length?Pr(s,Ge(e)?.nativeCurrency?.symbol??"ETH").catch(()=>0):0]);for(const[c,d]of i)d>0&&o.set(c,d);if(l>0)for(const c of r)o.set(c.toLowerCase(),l);return o},du=async(e,t,n,o=!0,s)=>{const r=yt(t,s),a=zt(e),i=[];let l;do{const w=await r.request({method:"alchemy_getTokenBalances",params:[a,"erc20",l?{pageKey:l}:{}]});i.push(...w.tokenBalances),l=w.pageKey||void 0}while(l);const c=i.filter(w=>fn(w.contractAddress)&&!!w.tokenBalance&&BigInt(w.tokenBalance)>0n),d=Ge(t)?.supportedTokens||[],p=w=>d.find(x=>x.address.toLowerCase()===w.toLowerCase()),f=[],h=await Li(e,t,s),[m,g,y]=await Promise.all([Promise.all(c.map(async w=>{const x=p(w.contractAddress);return x?{name:x.name,symbol:x.symbol,decimals:x.decimals,logo:x.logo??null}:await r.request({method:"alchemy_getTokenMetadata",params:[w.contractAddress]})})),o?Nr(n,c.map(w=>w.contractAddress)):new Map(c.map(w=>[w.contractAddress.toLowerCase(),Yo(n,w.contractAddress)?.price??0])),o&&h.balanceFormatted>0?Pr(n,h.symbol):Yo(n,`native:${h.symbol}`)?.price??0]);return h.balance>0n&&f.push({...h,balanceUsd:y*h.balanceFormatted}),c.forEach((w,x)=>{const v=m[x];if(!Number.isInteger(v.decimals)||v.decimals===null||v.decimals<0||v.decimals>255)throw new Error(`Invalid token metadata on chain ${t}`);const k=BigInt(w.tokenBalance),A=Number(Fe(k,v.decimals));if(k<=0n)return;const b=g.get(w.contractAddress.toLowerCase()),S=b?b*A:0;f.push({address:zt(w.contractAddress),name:v.name||"Unknown",symbol:v.symbol||"UNKNOWN",decimals:v.decimals,balance:k,balanceFormatted:A,balanceUsd:S,isDiscovered:!p(w.contractAddress),logoURI:v.logo||void 0,isNative:!1,chainId:t})}),{tokens:zi(f,t),chainId:t}},Hi=new Set,uu=async(e,t,n=!0,o)=>{try{const s=Wr(t,o?o[t]??"":void 0);if(s)try{return await du(e,t,s,n&&(typeof document>"u"||!document.hidden),o)}catch(r){Hi.has(t)||(Hi.add(t),console.warn(`Token discovery unavailable on chain ${t}; listing configured tokens only.`,r))}return await lu(e,t,o)}catch(s){throw s}},So=async(e,t,n=[],o)=>{if(!e)throw new Error("Wallet address is required");const s=Pc(o),r=t?.length?[...new Set(t)]:Object.keys(s).map(Number),a=await Promise.allSettled(r.map(l=>uu(e,l,!0,o))),i={};return a.forEach((l,c)=>{const d=r[c];i[d]=l.status==="fulfilled"?l.value:{chainId:d,tokens:[],error:`Unable to refresh balances on chain ${d}`}}),(await Promise.allSettled(n.map(async l=>{const c=i[l.chainId];if(!c||c.error||c.tokens.some(g=>Ye(g.address).toLowerCase()===Ye(l.address).toLowerCase()))return;const d=yt(l.chainId,o),p=await au(d,l.address,l.decimals!==void 0&&l.symbol?{decimals:l.decimals,symbol:l.symbol,name:l.name||l.symbol,logo:l.logoURI}:void 0),f=await _n(d,{address:l.address,abi:tt,functionName:"balanceOf",args:[e]}),h=await cu(l.chainId,[l.address],o),m=Number(Fe(f,p.decimals));c.tokens.push({...p,...l,name:p.name,symbol:p.symbol,decimals:p.decimals,balance:f,balanceFormatted:m,balanceUsd:(h.get(l.address.toLowerCase())||0)*m,isNative:!1})}))).forEach((l,c)=>{if(l.status==="rejected"){const d=i[n[c].chainId];d&&(d.error=`Unable to refresh token balances on chain ${d.chainId}`)}}),i},Ko=({address:e,supportedChains:t,fetchBalances:n=So,additionalTokens:o=[],enabled:s=!0,refreshInterval:r=0,priceEnabled:a=!0})=>{const i=Qt(Mt),l=As(),c=e?.toLowerCase(),d=JSON.stringify([...i?.supportedChainIds??t??[]].sort((x,v)=>x-v)),p=JSON.stringify(o);ae(()=>l.registerTokens(o),[l,p]);const f=c&&c===i?.embeddedWalletAddress?.toLowerCase()?"embedded":"external",h=`wallet:${JSON.stringify([i?.network,i?.apiUrl,i?.rpcOverrides])}:${c}:${f}:${d}:${l.fetcherId(n)}`,m=te(async()=>{let x;try{x=await n(c,JSON.parse(d),l.tokens(),i?.rpcOverrides)}catch(b){const S=b instanceof Error?b.message:"Unable to refresh balances";x=Object.fromEntries(JSON.parse(d).map(T=>[T,{chainId:T,tokens:[],error:S}]))}const v=l.entry(h).snapshot().assets,k=JSON.parse(d).map(b=>x[b]??{chainId:b,tokens:[],error:`Unable to refresh balances on chain ${b}`}),A=k.flatMap(b=>b.error?[b.error]:[]);return{assets:k.flatMap(b=>b.error?v.filter(S=>S.chainId===b.chainId).map(S=>({...S,balanceError:b.error,balanceStatus:"stale"})):b.tokens.map(S=>({...S,owner:c,location:f,_fundingWallet:f,_source:"wallet",positionId:`${c}:${f}:${b.chainId}:${Ye(S.address).toLowerCase()}`}))),error:A.length?A.join("; "):null}},[l,c,d,n,f,h]),g=Dr(h,m,s&&!!c,r,l),y=JSON.stringify(t&&[...t].sort((x,v)=>x-v)),w=ue(()=>t?g.assets.filter(x=>t.includes(x.chainId)):g.assets,[g.assets,y]);return ae(()=>{a&&s&&c&&g.refresh()},[a]),{...g,assets:w,refreshAssets:l.invalidate,getAssetsByChain:te(x=>w.filter(v=>v.chainId===x),[w]),getNativeAssets:te(()=>w.filter(x=>x.isNative),[w])}};function Ao(e){const t=Qt(Mt),n=As(),o=e.owner??((t?.mode||"7702")!=="7702"?t?.externalWalletAddress:t?.embeddedWalletAddress),s=o?.toLowerCase()!==t?.embeddedWalletAddress?.toLowerCase(),r=e.sourceChains??t?.supportedChainIds??[],a=(e.enabled??!0)&&!t?.isWhitelistGateActive,i=ue(()=>{const f=[...t?.additionalSourceTokens??[],...e.additionalSourceTokens??[],...e.destination?[e.destination]:[]];for(const h of e.supportedSourceAssets??[])for(const m of r){const g=Ge(m)?.supportedTokens?.find(y=>is(y,[h]));g&&f.push({...g,address:g.address,chainId:m,logoURI:g.logo})}return f},[e.destination,JSON.stringify(t?.additionalSourceTokens),JSON.stringify(e.additionalSourceTokens),JSON.stringify(e.supportedSourceAssets),JSON.stringify(r)]),l=Ko({address:o,supportedChains:r,fetchBalances:So,additionalTokens:i,enabled:a&&e.includeWalletAssets!==!1,refreshInterval:3e4}),c=Ui({address:o,supportedChains:r,enabled:a&&e.includeRollupAssets!==!1&&!!o&&o.toLowerCase()===t?.embeddedWalletAddress?.toLowerCase(),priceEnabled:a,refetchInterval:3e4}),d=ue(()=>a?[...(e.includeWalletAssets===!1?[]:l.assets).map(f=>({...f,owner:f.owner??o,location:f.location??(s?"external":"embedded"),_source:"wallet"})),...(e.includeRollupAssets===!1||o?.toLowerCase()!==t?.embeddedWalletAddress?.toLowerCase()?[]:c.assets).map(f=>({...f,owner:f.owner??o,location:"rollup",_source:"spice"}))]:[],[a,l.assets,c.assets,e.includeWalletAssets,e.includeRollupAssets,o,s,t?.embeddedWalletAddress]),p=ue(()=>d.map(f=>({asset:f,...po(f,e.role??"holding",{allowedTokens:t?.allowedTokens,rpcOverrides:t?.rpcOverrides,liquidityVenues:t?.liquidityVenues,isWhitelistGateActive:!!t?.isWhitelistGateActive},e.destination,e.supportedSourceAssets,{requiresEscrow:e.requiresEscrow})})),[d,t?.allowedTokens,t?.rpcOverrides,t?.liquidityVenues,t?.isWhitelistGateActive,e.role,e.destination,e.supportedSourceAssets,e.requiresEscrow]);return{positions:p,assets:ue(()=>p.filter(f=>f.eligible&&f.asset.balance>0n).map(f=>f.asset),[p]),walletAssets:ue(()=>d.filter(f=>f._source==="wallet"),[d]),rollupAssets:ue(()=>d.filter(f=>f._source==="spice"),[d]),loading:l.loading||c.loading,refreshing:l.refreshing||c.refreshing,error:l.error||c.error,refresh:n.invalidate}}function no(e){const t=Ye(e.address);if(e.isNative||be(t))return!1;const n=Ge(e.chainId)?.supportedTokens?.some(s=>ge(s.address,t)),o=Ft(t,e.chainId);return!!n&&!!o&&ks(o)}const qi="spiceflow:pendingDeposit",Fs="spiceflow:pendingDepositChanged";function Vi(e,t,n){return`${qi}:${e.toLowerCase()}:${t}:${n.toLowerCase()}`}function Ur(){try{const e="__spiceflow_storage_test__";return localStorage.setItem(e,"1"),localStorage.removeItem(e),!0}catch{return!1}}function pu(e){if(!Ur())return;const t=Vi(e.embeddedWalletAddress,e.chainId,e.tokenAddress);try{localStorage.setItem(t,JSON.stringify(e)),window.dispatchEvent(new Event(Fs))}catch(n){console.error("[pendingDeposit] Failed to save:",n)}}function fu(e){if(!Ur())return[];const t=`${qi}:${e.toLowerCase()}:`,n=[],o=Date.now();for(let s=0;s<localStorage.length;s++){const r=localStorage.key(s);if(!(!r||!r.startsWith(t)))try{const a=localStorage.getItem(r);if(!a)continue;const i=JSON.parse(a);if(o-i.timestamp>6048e5){localStorage.removeItem(r);continue}n.push(i)}catch{localStorage.removeItem(r)}}return n}function Lr(e,t,n){if(!Ur())return;const o=Vi(e,t,n);localStorage.removeItem(o),window.dispatchEvent(new Event(Fs))}const mu=new Set(["USDC","SUSD","USD","NUSD","USDT","DAI","ENUSD","USDG"]),Qi={ETH:"ethereum",WETH:"ethereum",BTC:"bitcoin",WBTC:"bitcoin",WCBTC:"bitcoin",CBTC:"bitcoin",ECBTC:"bitcoin",ARB:"arbitrum",MATIC:"matic-network",POL:"matic-network"};let Ts=null;const hu=6e4;async function ji(e){const t={},n=new Set,o={};for(const r of e){const a=r.toUpperCase();if(mu.has(a))t[a]=1;else if(Qi[a]){const i=Qi[a];n.add(i),o[a]=i}else t[a]=0}if(n.size===0)return t;const s=Date.now();if(Ts&&s-Ts.timestamp<hu){for(const[r,a]of Object.entries(o))t[r]=Ts.prices[a]??0;return t}try{const r=Array.from(n).join(","),a=await fetch(`https://api.coingecko.com/api/v3/simple/price?ids=${r}&vs_currencies=usd`);if(!a.ok)throw new Error(`CoinGecko ${a.status}`);const i=await a.json(),l={};for(const c of n)l[c]=i[c]?.usd??0;Ts={prices:l,timestamp:s};for(const[c,d]of Object.entries(o))t[c]=l[d]??0}catch(r){console.warn("[fetchTokenPrices] CoinGecko fetch failed:",r);for(const a of Object.keys(o))t[a]=t[a]??0}return t}const gu=new Set(["cbtc","btc","wbtc","wcbtc","tbtc"]),yu=new Set(["usdc","usdt","dai","usdc.e","usdbc","usdg"]);async function xu(){const e=(await ji(["BTC"])).BTC;if(!e||e<=0)throw new Error("Failed to fetch BTC/USD price");return e}function wu(e){return gu.has(e.toLowerCase())}function bu(e){return yu.has(e.toLowerCase())}function vu(e,t,n,o){const s=10n**12n,r=BigInt(Math.round(o*Number(s))),a=t-n,i=10n**BigInt(Math.abs(a));let l=e*r/s;return a>0?l=l/i:a<0&&(l=l*i),l}const Cu=.01,ku=5*60*1e3;function Iu(e){const t=Number(Fe(e.verifiedBalance,e.tokenDecimals));return Number.isFinite(t)?t:0}async function Su(e){const t=Au(e);let n;try{n=await ji(t.map(o=>o.tokenSymbol))}catch{return t}return t.filter(o=>{const s=Iu(o);if(s<=0)return!0;const r=n[o.tokenSymbol.toUpperCase()]??0;return!Number.isFinite(r)||r<=0?!0:s*r>=Cu})}function Au(e){const t=new Map;for(const n of e){const o=`${n.chainId}:${n.tokenAddress.toLowerCase()}`;t.get(o)||t.set(o,{...n,amount:n.timestamp===0?Fe(n.verifiedBalance,n.tokenDecimals):n.amount,rawAmount:n.timestamp===0?n.verifiedBalance.toString():n.rawAmount,hasFullBalance:n.timestamp===0?!0:n.hasFullBalance})}return Array.from(t.values())}function Gi(e,t){const[n,o]=O([]),[s,r]=O(!1),a=_(t);a.current=t;const i=_(0),l=_(0),c=te(async({forceDiscovery:d=!1}={})=>{if(!e){o([]),r(!1);return}const p=++l.current,f=()=>p!==l.current;r(!0);try{const h=[],m=fu(e);for(const x of m){if(f())return;if(no({address:x.tokenAddress,chainId:x.chainId,isNative:x.isNative}))try{const v=yt(x.chainId);let k;if(x.isNative||be(x.tokenAddress)?k=await ur(v,{address:e}):k=await _n(v,{address:zt(x.tokenAddress),abi:tt,functionName:"balanceOf",args:[e]}),f())return;k>0n?h.push({...x,verifiedBalance:k,hasFullBalance:k>=BigInt(x.rawAmount)}):Date.now()-x.timestamp>15*60*1e3&&Lr(e,x.chainId,x.tokenAddress)}catch(v){console.warn(`[usePendingDeposit] Failed to verify balance for ${x.tokenSymbol} on chain ${x.chainId}:`,v),h.push({...x,verifiedBalance:0n,hasFullBalance:!1})}}if(f())return;const g=a.current,y=Date.now(),w=(g?.discoverWalletBalances??!0)&&(d||y-i.current>=ku);if(g?.network&&w){i.current=y;const x=g.chainIds??ys(g.network),v=new Set(h.map(A=>`${A.chainId}:${A.tokenAddress.toLowerCase()}`)),k=[];for(const A of x){const b=Ge(A);if(b?.supportedTokens)for(const S of b.supportedTokens){if(!no({address:S.address,chainId:A,isNative:!1}))continue;const T=`${A}:${S.address.toLowerCase()}`;v.has(T)||k.push((async()=>{try{const E=yt(A),I=await _n(E,{address:zt(S.address),abi:tt,functionName:"balanceOf",args:[e]});return I>0n?{chainId:A,tokenAddress:S.address,tokenSymbol:S.symbol,tokenDecimals:S.decimals,amount:Fe(I,S.decimals),rawAmount:I.toString(),embeddedWalletAddress:e,externalWalletAddress:"",timestamp:0,isNative:!1,verifiedBalance:I,hasFullBalance:!0}:null}catch{return null}})())}}if(k.length>0){const A=await Promise.allSettled(k);if(f())return;for(const b of A)b.status==="fulfilled"&&b.value&&h.push(b.value)}}if(!f()){const x=await Su(h);if(f())return;o(x)}}catch(h){console.error("[usePendingDeposit] Verification error:",h),f()||o([])}finally{f()||r(!1)}},[e]);return ae(()=>{if(!a.current?.enabled){l.current++,o([]),r(!1);return}c({forceDiscovery:!0});const d=a.current?.pollIntervalMs??3e4;if(d<=0||!e)return()=>{l.current++};const p=setInterval(()=>{c({forceDiscovery:!1})},d),f=()=>c({forceDiscovery:!0});return window.addEventListener(Fs,f),()=>{l.current++,window.removeEventListener(Fs,f),clearInterval(p)}},[c,e]),{pendingDeposits:n,loading:s,refresh:()=>c({forceDiscovery:!0})}}function Yi(e){const t=Qt(Mt),n=t?.embeddedWalletAddress,o=e?.enabled===!1?void 0:n,s=t?.network?{network:t.network,pollIntervalMs:e?.pollIntervalMs,chainIds:e?.chainIds??t.supportedChainIds,discoverWalletBalances:e?.discoverWalletBalances}:void 0;return{...Gi(o,s),embeddedWalletAddress:n}}var zr="data:image/svg+xml,%3csvg width='10' height='10' viewBox='0 0 10 10' fill='none' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M5 4.99995V6.99995M5 3.31245V3.31189M9.5 5C9.5 7.48528 7.48528 9.5 5 9.5C2.51472 9.5 0.5 7.48528 0.5 5C0.5 2.51472 2.51472 0.5 5 0.5C7.48528 0.5 9.5 2.51472 9.5 5Z' stroke='black' stroke-opacity='0.4' stroke-linecap='round' stroke-linejoin='round'/%3e%3c/svg%3e";function Hr(e){const t=_(0),n=_(null),o=_(e.run);o.current=e.run;const s=_(e.onSkip);s.current=e.onSkip;const r=_(e.onCleanup);r.current=e.onCleanup,ae(()=>{if(!e.shouldRun){t.current+=1,n.current?.abort(),s.current?.();return}let a=!1,i=!1;const l=async f=>{if(f&&i)return;n.current?.abort();const h=new AbortController;n.current=h;const m=++t.current;i=!0;try{await o.current({isBackground:f,isCurrent:()=>!a&&t.current===m,signal:h.signal})}finally{i=!1}},c=window.setTimeout(()=>void l(!1),e.delayMs??250),d=()=>{document.hidden||l(!0)},p=e.backgroundIntervalMs?window.setInterval(d,e.backgroundIntervalMs):void 0;return p!==void 0&&document.addEventListener("visibilitychange",d),()=>{a=!0,n.current?.abort(),clearTimeout(c),p!==void 0&&(window.clearInterval(p),document.removeEventListener("visibilitychange",d)),r.current?.()}},[e.shouldRun,e.delayMs,e.backgroundIntervalMs,...e.deps])}function Ki(e,t){if(e.length!==t.length)return!1;const n=$n(e),o=$n(t);return n.every((s,r)=>s.hash===o[r]?.hash)}const Bn=e=>new Promise(t=>setTimeout(t,e)),Eu="0xa9059cbb";function Zi(e){const t=e.findIndex(s=>bo(s.chainId));if(t<=0)return[];const n=new Map,o=(s,r,a)=>{if(a<=0n)return;const i=`${s}:${r.toLowerCase()}`,l=n.get(i);l?l.amount+=a:n.set(i,{chainId:s,token:r,amount:a})};for(const s of e.slice(0,t)){const r=Uo(s.chainId);if(!(!r||r===Tt)){for(const a of s.calls)if(a.value&&a.value>0n&&ge(a.to,r)&&o(s.chainId,Tt,a.value),!!a.data?.startsWith(Eu))try{const i=uo({abi:tt,data:a.data});if(i.functionName!=="transfer")continue;const[l,c]=i.args;ge(l,r)&&o(s.chainId,a.to,c)}catch{}}}return[...n.values()]}function Xi(e){const t=Ft(e.token,e.chainId);return[t?.equivalenceGroup,t?.symbol,t?.name]}function Ji(e,t){return Ri(e,t.chainId,t.token,Xi(t))}function Fu(e,t){const n=$d(e,t.chainId,t.token,Xi(t));return!n||n.receiptDecimals>=n.chainDecimals?t.amount:co(co(t.amount,n.chainDecimals,n.receiptDecimals),n.receiptDecimals,n.chainDecimals)}async function Tu(e){const{deposits:t,baseline:n,fetchEntries:o,timeoutMs:s=12e4,intervalMs:r,signal:a,wait:i=Bn}=e;if(t.length===0)return!0;const l=new Map(t.map(p=>[p,Ji(n,p)])),c=Date.now(),d=c+s;for(;!a?.aborted;){try{const m=await o();if(t.every(g=>Ji(m,g)-l.get(g)>=Fu(m,g)))return!0}catch{}const p=Date.now();if(p>=d)return!1;const f=p-c,h=r??(f<5e3?250:f<15e3?1e3:3e3);await i(Math.min(h,d-p))}return!1}function Bu(e,t){const n=$n(e).map(o=>o.hash);return vo(zn([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,t,n]))}async function Du(e,t,n,o,s){if(o?.aborted)throw new Ne("ABORT","Execution transaction aborted");const r={raw:Bu(t,n)},a=s?await e.signMessage(r,s):await e.signMessage(r);console.debug("[SpiceFlow:execution]",{phase:"signature-returned",at:Date.now()});const i=typeof a=="string"?a:a.signature;if(!i)throw new Ne("SIGNATURE_FAILED","Failed to sign intent authorization. The wallet returned an empty signature.");return i}function Ou(e){return e.domain==="spicenet"||bo(e.chainId)}async function Ru(e){const{chainBatches:t,signingAddress:n,actions:o,cache:s,signal:r,onSignatureRequested:a,beforeSign:i}=e;if(r?.aborted)throw new Ne("ABORT","Execution transaction aborted");const l=[...new Set(t.filter(p=>!Ou(p)).map(p=>p.chainId))].map(p=>({chainId:p,client:yt(p),delegateContract:va(p)})),[c]=await Promise.all([Promise.all(l.map(async({chainId:p,client:f,delegateContract:h})=>{const m=Number(await $c(n,f)),g=[n.toLowerCase(),p,h.toLowerCase(),m].join(":");return{chainId:p,delegateContract:h,nonce:m,cacheKey:g,cached:s?.get(g)}})),l.length?o.prepareSigning?.():void 0,i?.()]),d=[];for(const{chainId:p,delegateContract:f,nonce:h,cacheKey:m,cached:g}of c){if(g){d.push(g);continue}if(r?.aborted)throw new Ne("ABORT","Execution transaction aborted");const y=await o.signAuthorization({contractAddress:f,chainId:p,nonce:h},a),w={r:y.r,s:y.s,yParity:y.yParity,address:y.address??f,chainId:Number(y.chainId??p),nonce:Number(y.nonce??h)};s?.set(m,w),d.push(w)}return d}const $i=15;function Mu(e){return e.now-e.lastProgressAt>=e.pollTimeoutMs}function _i(e,t){return{intentId:e,steps:t.map(n=>({...n,status:"pending"})),overallStatus:"processing"}}function Bs(e,t,n){const o=e.steps.map(i=>({...i})),s=o[t];if(!s)return e;n.status==="success"||n.status==="completed"?(o[t]={...s,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]={...s,status:"failed",transactionHash:n.transactionHash,error:n.error}:o[t]={...s,status:"processing"};const r=o.some(i=>i.status==="failed"),a=o.every(i=>i.status==="success");return{...e,steps:o,overallStatus:r?"failed":a?"success":"processing"}}function Wu({checkStepStatus:e,retryStep:t,maxRetries:n=3,pollingInterval:o=2500,pollTimeoutMs:s=3e5}){const[r,a]=O(null),i=_(null),l=_(null),c=_(!1),d=_(!1),p=_(0),f=_({}),h=_(0),m=te(k=>{i.current=k,a(k)},[]),g=te(()=>{l.current&&(clearInterval(l.current),l.current=null)},[]),y=te(()=>{p.current=0,f.current={},h.current=0,c.current=!0,g(),m(null)},[g,m]),w=te((k,A)=>{g(),c.current=!1,m(_i(k,A))},[g,m]),x=te((k,A)=>{const b=i.current;b&&m(Bs(b,k,A))},[m]),v=te((k,A)=>{g(),c.current=!1,d.current=!1,p.current=0,f.current={},h.current=Date.now(),m(_i(k,A));const b=async()=>{if(!(c.current||d.current||!e)){d.current=!0;try{if(Mu({now:Date.now(),lastProgressAt:h.current,pollTimeoutMs:s})){const E=i.current;E&&m({...E,steps:E.steps.map(I=>I.status==="success"?I:{...I,status:"failed",error:"Taking longer than expected. It may still complete - check the explorer, then refresh."}),overallStatus:"failed"}),c.current=!0,g();return}const S=i.current;if(!S)return;const T=S.steps.findIndex(E=>E.status!=="success");if(T===-1){c.current=!0,g();return}if(!(T===0||S.steps[T-1].status==="success"))return;try{const E=S.steps[T].stepId,{data:I}=await e(k,E);if(p.current=0,I.status==="success"&&(h.current=Date.now()),I.status==="reverted"){const W=f.current[E]||0;if(t&&W<n){f.current[E]=W+1;try{await t(k,E)}catch(R){console.error(`[intentStatus] retry failed for step ${E}:`,R)}m(Bs(i.current,T,{status:"executing"}));return}}const M=Bs(i.current,T,I);m(M),M.overallStatus!=="processing"&&(c.current=!0,g())}catch(E){p.current+=1,console.error(`[intentStatus] poll error (${p.current}/${$i}):`,E),p.current>=$i&&(m(Bs(i.current,T,{status:"error"})),c.current=!0,g())}}finally{d.current=!1}}};b(),l.current=setInterval(b,o)},[e,t,n,o,s,g,m]);return ae(()=>()=>g(),[g]),{intentStatus:r,startStatusPolling:v,beginStatusTracking:w,applyStepUpdate:x,stopStatusPolling:g,clearStatus:y}}function Nu(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 Pu=350,Uu=2500;async function el(e){const{actionId:t,intentIndex:n,intentId:o,stepIndex:s,maxPolls:r=48,maxExecuteAttempts:a=3,pollsBeforeRetry:i=5,maxConsecutiveStatusErrors:l=15,onStatusMessage:c,onStepUpdate:d,signal:p,chainId:f}=e;if(p?.aborted)throw new Ne("ABORT","Execution transaction aborted");let h="pending",m,g,y=0,w=0,x,v;const k=new Promise((b,S)=>{x=b,v=()=>S(new Ne("ABORT","Execution transaction aborted"))}),A=()=>{y++,Lt.executeStep(t,n,s,{action:"execute"}).then(b=>{b.transactionHash&&(m=b.transactionHash),b.status==="success"&&x({status:b.status,transactionHash:b.transactionHash})}).catch(b=>{const S=b instanceof Error?b.message:String(b);console.warn(`[execution] executeStep ${s} attempt ${y} error (will poll):`,S)})};p?.addEventListener("abort",v,{once:!0});try{A();for(let b=0;b<r;b++){const S=b===0?Pu:Uu;try{const E=await Promise.race([Bn(S).then(()=>{}),k]);if(p?.aborted)throw new Ne("ABORT","Execution transaction aborted");const I=E??await Promise.race([Lt.checkStepStatus(o,s).then(W=>W.data),k]);if(p?.aborted)throw new Ne("ABORT","Execution transaction aborted");w=0,h=I.status,g=I.error;const M=I.transactionHash;M&&(m=M),d?.({status:h,transactionHash:m,error:g})}catch(E){if(E instanceof Error&&(E.name==="AbortError"||E instanceof Ne&&E.code==="ABORT")||(w++,w>=l))throw E;continue}if(h==="created"&&b>=y*i&&y<a&&A(),h==="reverted"||h==="error")throw new Ne("ON_CHAIN_REVERT",Nu(h,g),{status:h,txHash:m,actionId:t,intentId:o,stepId:s,chainId:f});if(h==="success"||h==="completed")return m;let T="Waiting for solver...";h==="executing"?T="Transaction executing...":h==="submitted"?T="Transaction submitted...":h==="created"&&(T="Waiting for relayer..."),c?.(T,m)}throw new Ne("POLLING_EXHAUSTED",`Transaction is still processing (status: ${h}). 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:s,lastStatus:h,pollAttempts:r,maxPolls:r,txHash:m})}finally{p?.removeEventListener("abort",v)}}async function Lu(e){const{actionId:t,intentIndex:n,intentId:o,totalSteps:s,delayBeforeSpicenetStepMs:r=5e3,isSpicenetStep:a,beforeStep:i,maxExecuteAttemptsForStep:l,maxPolls:c=48,onStatusMessage:d,onStepUpdate:p,signal:f}=e;let h;for(let m=0;m<s;m++){if(m>0&&a?.(m)&&r>0&&await Bn(r),await i?.(m),f?.aborted)throw new Ne("ABORT","Execution transaction aborted");const g=l?.(m)??3,y=await el({actionId:t,intentIndex:n,intentId:o,stepIndex:m,maxPolls:c,maxExecuteAttempts:g,maxConsecutiveStatusErrors:g===6?5:15,onStatusMessage:d,onStepUpdate:p?w=>p(m,w):void 0,signal:f});y&&(h=y)}return h}const zu="0xa9059cbb";function qr(e,t){return e.map(n=>{if(n.domain==="spicenet"||bo(n.chainId)||n.calls.length===0)return n;const o=new Set((n.tokenTransfers??[]).filter(a=>(a.from==="escrow"||a.from==="solver")&&ge(a.to,t)).map(a=>a.token.toLowerCase()));if(o.size===0)return n;const s=[...o].some(be);let r=0;for(const a of n.calls){if(s&&a.value>0n&&a.data==="0x"&&!ge(a.to,t)){r+=1;continue}if(!a.data?.startsWith(zu))break;try{const i=uo({abi:tt,data:a.data});if(i.functionName!=="transfer")break;const[l]=i.args;if(ge(l,t)||!o.has(a.to.toLowerCase()))break;r+=1}catch{break}}return r===0?n:{...n,calls:n.calls.slice(r)}})}async function Hu(e,t){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 n=await e.waitForTransactionReceipt({hash:t,timeout:12e4,pollingInterval:2e3,confirmations:1});if(n.transactionHash?.toLowerCase()!==t.toLowerCase()||n.status!=="success")throw new Error("The destination transaction has not been confirmed successfully. Reconcile the existing action before retrying.");return t}async function Ds(e){let t=e.hash,n=!1;const o=Date.now()+12e4,s=a=>a.transactionHash&&a.transactionHash.toLowerCase()!==t.toLowerCase();let r=await e.client.waitForTransactionReceipt({hash:t,timeout:12e4,pollingInterval:2e3,confirmations:1,onReplaced:a=>{const i=a.transaction,l=a.replacedTransaction;if(!(a.reason==="repriced"&&l?.from&&l.nonce!==void 0&&/^0x[0-9a-f]{64}$/i.test(i?.hash??"")&&i?.to?.toLowerCase()===e.call.to.toLowerCase()&&(i.input??"0x").toLowerCase()===e.call.data.toLowerCase()&&BigInt(i.value??0)===e.call.value&&i.from?.toLowerCase()===l?.from?.toLowerCase()&&i.nonce===l?.nonce)){n=!0,e.onCancelled?.();return}t=i.hash,e.onRepriced?.(t)}});if(n)throw new Error("Transaction was cancelled or replaced with a different action; retry the unfinished action");if((e.confirmations??1)>1&&!s(r)&&r.status==="success"&&(r=await e.client.waitForTransactionReceipt({hash:t,timeout:Math.max(o-Date.now(),1),pollingInterval:2e3,confirmations:e.confirmations})),s(r))throw new Error("Unexpected transaction receipt; recover the submitted transaction before retrying");return{receipt:r,hash:t}}const qu=10n,Vu=10n,Qu=5;function Vr(e){return e.map(t=>({...t,calls:[...t.calls],tokenTransfers:t.tokenTransfers?[...t.tokenTransfers]:void 0}))}function Os({token:e,recipient:t,amount:n}){return{to:e,value:0n,data:xt({abi:tt,functionName:"transfer",args:[t,n]})}}function ju({chainBatches:e,token:t,amount:n}){const o=Vr(e),s=o[o.length-1];if(!s)return o;const r=Jn(s.chainId);return s.calls=[...s.calls,Os({token:t,recipient:r,amount:n})],o}function tl({chainBatches:e,user:t,token:n,grossAmount:o,gasFee:s}){const r=Vr(e),a=r[r.length-1];if(!a)throw new Ne("INVALID_PARAMS","Action-output escrow funding requires at least one chain batch.");const i=tr(o,Vu),l=s+i;if(l>=o)throw new Ne("INVALID_PARAMS","Borrow amount is too small after gas and Spicenet fees.",{grossAmount:o.toString(),gasFee:s.toString(),spicenetFee:i.toString()});const c=o-l,d=Jn(a.chainId),p=[];return s>0n&&p.push(Os({token:n,recipient:nn,amount:s})),i>0n&&p.push(Os({token:n,recipient:Fn,amount:i})),a.calls=[...a.calls,...p,Os({token:n,recipient:d,amount:c})],a.tokenTransfers=[...a.tokenTransfers??[],...s>0n?[{from:t,to:nn,token:n,amount:s}]:[],...i>0n?[{from:t,to:Fn,token:n,amount:i}]:[],{from:t,to:d,token:n,amount:c}],{chainBatches:r,gasFee:s,spicenetFee:i,netEscrowAmount:c,outputCredit:{chainId:a.chainId,token:n,amount:o}}}async function nl({chainBatches:e,user:t,token:n,grossAmount:o,chainAuthorizations:s}){let r=0n,a=tl({chainBatches:e,user:t,token:n,grossAmount:o,gasFee:r});for(let i=0;i<Qu;i+=1){const l=$n(a.chainBatches),c=(await Lt.estimateBatchGas({user:t,outputToken:n,chainBatches:a.chainBatches.map((d,p)=>({...d,hash:l[p].hash})),chainAuthorizations:s})).gasFee;if(c===r)return a;r=c,a=tl({chainBatches:e,user:t,token:n,grossAmount:o,gasFee:r})}throw new Ne("INVALID_PARAMS","Action-output fee estimate did not converge. Please retry.")}function Qn(e){return bo(e.chainId)}const Gu="0xa9059cbb";function Zo(e,t){return`${e}:${Ye(t).toLowerCase()}`}function ol(e,t){return t===Tt.toLowerCase()?{symbol:gn(e),decimals:18}:Ft(t,e)??{symbol:"tokens",decimals:18}}function Yu(e,t){const n=Ft(t,e);return[n?.equivalenceGroup,n?.symbol,n?.name]}async function Qr(e){return Ca(e)}async function Ku(e,t,n){const o=new Map,s=n?.walletFundingRequirement,r=s&&Zo(s.chainId,s.token);r&&o.set(r,0n);const a=new Map,i=new Map,l=new Map,c=new Map;for(const p of n?.actionOutputCredits??[]){const f=Zo(p.chainId,p.token);c.set(f,(c.get(f)??0n)+p.amount)}for(const p of e){if(Qn(p))continue;for(const m of p.tokenTransfers??[]){if(m.from!=="escrow"&&m.from!=="solver"||!ge(m.to,t))continue;const g=BigInt(m.amount??0);if(g<=0n)continue;const y=Zo(p.chainId,m.token);a.set(y,(a.get(y)??0n)+g),m.from==="escrow"&&i.set(y,(i.get(y)??0n)+g)}const f=Uo(p.chainId),h=m=>!!f&&f!==Tt&&ge(m,f);for(const m of p.calls){if(m.value&&m.value>0n){const g=Zo(p.chainId,Tt);o.set(g,(o.get(g)??0n)+m.value),h(m.to)&&l.set(g,(l.get(g)??0n)+m.value)}if(m.data?.startsWith(Gu))try{const g=uo({abi:tt,data:m.data});if(g.functionName!=="transfer")continue;const[y,w]=g.args,x=m.to.toLowerCase(),v=Zo(p.chainId,x);o.set(v,(o.get(v)??0n)+w),h(y)&&l.set(v,(l.get(v)??0n)+w)}catch{}}}let d=null;for(const[p,f]of i){const h=f-(l.get(p)??0n);if(h<=0n)continue;const[m,g]=p.split(":"),y=Number(m),w=ol(y,g);d??(d=await Qr(t));const x=Ri(d,y,g,Yu(y,g));if(!(x>=h))throw new Ne("INVALID_PARAMS",`Insufficient Spice ${w.symbol}: needs ${Fe(h,w.decimals)}, has ${Fe(x,w.decimals)}.`,{chainId:y,token:g,userAddress:t,requiredAmount:h.toString(),balance:x.toString(),balanceSource:"spice"})}for(const[p,f]of o){const[h,m]=p.split(":"),g=Number(h);let y=f-(a.get(p)??0n)-(c.get(p)??0n);if(s&&p===r&&s.amount>y&&(y=s.amount),y<=0n)continue;const w=yt(g),x=m===Tt.toLowerCase()?await w.getBalance({address:t}):await w.readContract({address:m,abi:tt,functionName:"balanceOf",args:[t]});if(x>=y)continue;const v=ol(g,m);throw new Ne("INVALID_PARAMS",`Insufficient ${v.symbol} on ${gn(g)}: needs ${Fe(y,v.decimals)}, has ${Fe(x,v.decimals)}.`,{chainId:g,token:m,userAddress:t,requiredAmount:y.toString(),balance:x.toString(),balanceSource:"wallet"})}}function Zu({chainBatches:e,tokenAddress:t,tokenTransferAmount:n,useCustomTransfers:o}){if(!(e.some(Qn)||!(o?e.some(s=>Qn(s)?!1:(s.tokenTransfers??[]).some(r=>r.from==="escrow"&&BigInt(r.amount??0)>0n)):n>0n)))throw new Ne("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 Xu(e,t,n,o){t.forEach((s,r)=>{if(!s.to||!s.from||!s.token||s.amount===void 0)throw new Ne("INVALID_TOKEN_TRANSFER",`tokenTransfers[${r}] 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:r,transfer:{from:s.from,to:s.to,token:s.token,amount:s.amount?.toString()},signingAddress:n,useCustomTransfers:o})})}function Rs({user:e,chainBatches:t,tokenAddress:n,tokenTransferAmount:o,exp:s,signature:r,chainAuthorizations:a,useCustomTransfers:i}){const l=t,c=$n(l),d=l.filter(p=>!Qn(p)).length;if(Zu({chainBatches:l,tokenAddress:n,tokenTransferAmount:o,useCustomTransfers:i}),!i&&o>0n&&d>1)throw new Ne("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:d,tokenAddress:n,tokenTransferAmount:o.toString()});return{user:e,...a?{chainAuthorizations:a}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:r,nbf:0,exp:s,chainBatches:c.map((p,f)=>{const h=l[f],m=Qn(h)?[]:i?h.tokenTransfers??[]:o>0n?[{from:"escrow",to:e,token:n,amount:o}]:[];return Xu(Number(p.chainId),m,e,i),{hash:p.hash,chainId:Number(p.chainId),tokenTransfers:m,calls:p.calls}})}]}}function sl(e,t){const n=t?.depositToEscrow?.gasFundingSource==="action-output"?t.depositToEscrow:null,o=t?.depositToEscrow&&!n?ju({chainBatches:e,token:t.depositToEscrow.token,amount:t.depositToEscrow.amount}):Vr(e);return{actionOutputDeposit:n,batches:o}}let jr=!1;function Ms(){const{address:e,isConnected:t,isAuthenticated:n,actions:o}=Zn(),s=_(null),{intentStatus:r,startStatusPolling:a,beginStatusTracking:i,applyStepUpdate:l,clearStatus:c}=Wu({checkStepStatus:(y,w)=>Lt.checkStepStatus(y,w),retryStep:async(y,w)=>{const[x,v]=y.split("/"),k=parseInt(v||"0",10);await Lt.executeStep(x,k,w,{action:"execute"})}}),d=_(o),p=_(new Map);d.current=o;const f=te((y,w,x,v,k)=>Ru({chainBatches:y,signingAddress:w,actions:d.current,cache:p.current,signal:x,onSignatureRequested:v,beforeSign:k}),[]),h=te((y,w,x,v)=>Du(d.current,y,w,x,v),[]),m=te(async(y,w,x,v,k,A)=>{const b=(S,T,E)=>{v?.({step:S,message:T,...E})};if(jr)throw new Ne("CONCURRENT_EXECUTION","A execution transaction is already in progress. Please wait.");jr=!0;try{if(!e)throw new Ne("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const S=A?.userOverride||e,{actionOutputDeposit:T,batches:E}=sl(y,A);let I=E,M=[],W=A?.useCustomTransfers,R=Zi(I),F=null;const N=async()=>{for(let B=0;R.length>0&&B<3;B++)try{F=await Qr(S);break}catch(U){if(k?.aborted)throw new Ne("ABORT","Execution transaction aborted");if(B===2)throw new Ne("RELAYER_ERROR","Unable to read your Spice balance. Please try again before submitting the transaction.",{cause:U});await Bn(1e3)}await A?.validateBeforeSubmit?.(I)};b("building","Preparing your wallet and transaction...");const D=await f(I,S,k,()=>b("signing-delegation","Confirm the authorization in your wallet..."),N);if(b("building","Checking transaction fees and balances..."),k?.aborted)throw new Ne("ABORT","Execution transaction aborted");const L=BigInt(Math.floor(Date.now()/1e3)+3600);if(T){const B=await nl({chainBatches:y,user:S,token:T.token,grossAmount:T.amount,chainAuthorizations:D});I=B.chainBatches,M=[B.outputCredit],W=!0}if(!A?.skipPreSubmitFeeEstimate){let B=!1;if(A?.feeExecutionMode==="user-transfer"&&A.adjustBatchesForEstimate&&Lt.canValidateActionFees()){const U=await Lt.validateActionFees(Rs({user:S,chainBatches:I,tokenAddress:w,tokenTransferAmount:x,exp:Number(L),signature:"0x00",chainAuthorizations:D,useCustomTransfers:W}),{signal:k});s.current=U;const X=await A.adjustBatchesForEstimate({feeEstimate:U,chainBatches:I});B=!X||Ki(I,X),X&&(I=X)}for(let U=0;!B&&U<10;U++){const X=A?.feeExecutionMode==="user-transfer"?qr(I,S):I,pe=Rs({user:S,chainBatches:X,tokenAddress:w,tokenTransferAmount:x,exp:Number(L),signature:"0x00",chainAuthorizations:D,useCustomTransfers:W}),de=await Lt.estimateActionFees(pe,{signal:k});s.current=de;const xe=await A?.adjustBatchesForEstimate?.({feeEstimate:de,chainBatches:I}),K=!!xe&&Ki(I,xe);if(!xe||K){B=!0;break}I=xe}if(!B)throw new Ne("INVALID_PARAMS","Fee estimate did not converge. Please retry.")}if(A?.prepareForSigning){const B=await A.prepareForSigning(I);if(B.length!==I.length||B.some((U,X)=>U.chainId!==I[X].chainId||U.domain!==I[X].domain))throw new Error("The funded route changed before signing");I=B}A?.resolveActionOutputCredits&&(M=await A.resolveActionOutputCredits()),(!A?.skipUserFundingPreflight||A.walletFundingRequirement)&&await Ku(A?.skipUserFundingPreflight?[]:I,S,{actionOutputCredits:M,walletFundingRequirement:A?.walletFundingRequirement}),R=Zi(I),R.length&&!F&&(F=await Ca(S)),await A?.validateBeforeSubmit?.(I),b("building","Preparing the signing request...");const z=await h(I,L,k,()=>b("signing-intent","Confirm the transaction in your wallet..."));if(k?.aborted)throw new Ne("ABORT","Execution transaction aborted");b("submitting","Submitting to relayer...");const fe=Rs({user:S,chainBatches:I,tokenAddress:w,tokenTransferAmount:x,exp:Number(L),signature:z,chainAuthorizations:D,useCustomTransfers:W}),ce=Date.now();await A?.validateBeforeSubmit?.(I),console.debug("[SpiceFlow:execution]",{phase:"submit-check-complete",at:Date.now(),durationMs:Date.now()-ce});const Q=await Lt.createAction(fe),[ne,re]=Q.intentIds[0].split("/"),j=parseInt(re||"0",10),J=`${ne}/${j}`;b("executing","Executing on chain..."),b("executing","Executing on chain...",{actionId:ne,intentId:J,intentIndex:j,totalSteps:I.length});const Y=I.length,me=await Lu({actionId:ne,intentIndex:j,intentId:J,totalSteps:Y,signal:k,...F?{delayBeforeSpicenetStepMs:0}:{},isSpicenetStep:B=>Qn(I[B]),beforeStep:async B=>{if(!F||!Qn(I[B]))return;const U=await Tu({deposits:R,baseline:F,fetchEntries:()=>Qr(S),signal:k});if(k?.aborted)throw new Ne("ABORT","Execution transaction aborted");if(!U)throw new Ne("POLLING_EXHAUSTED","Your deposit is still waiting for Spice credit. Check this transaction's status before trying again.",{actionId:ne,intentId:J,stepId:B})},maxExecuteAttemptsForStep:B=>Qn(I[B])?6:3,maxPolls:180,onStatusMessage:(B,U)=>{b("executing",B,{txHash:U,actionId:ne,intentId:J,intentIndex:j,totalSteps:Y})}});if(A?.requireDestinationReceipt){const B=[...I].reverse().find(U=>!Qn(U));if(!B)throw new Error("The action has no destination transaction to verify.");await Hu(yt(B.chainId),me)}return b("success","Transaction successful!",{txHash:me,actionId:ne,intentId:J,intentIndex:j,totalSteps:Y}),me||ne}catch(S){throw console.error("[Execution] Error:",S),b("error",S.message||"Transaction failed",{error:S.message}),S}finally{jr=!1}},[e,n,f,h]),g=te(async(y,w,x,v)=>{if(!e)throw new Ne("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const k=v?.userOverride||e,A=v?.validateFeeCalls===!0&&v.feeExecutionMode==="user-transfer"&&Lt.canValidateActionFees(),{actionOutputDeposit:b,batches:S}=sl(y,v);let T=S;const E=v?.feeExecutionMode==="user-transfer"&&!A?qr(T,k):T,I=v?.signAuthorizationsForEstimate?await f(E,k):void 0;let M=v?.useCustomTransfers;b&&(T=(await nl({chainBatches:y,user:k,token:b.token,grossAmount:b.amount,chainAuthorizations:I})).chainBatches,M=!0);const W=v?.feeExecutionMode==="user-transfer"&&!A?qr(T,k):T,R=Rs({user:k,chainBatches:W,tokenAddress:w,tokenTransferAmount:x,exp:Math.floor(Date.now()/1e3)+3600,signature:"0x00",chainAuthorizations:I,useCustomTransfers:M}),F=await(A?Lt.validateActionFees(R,{signal:v?.signal}):Lt.estimateActionFees(R,{signal:v?.signal}));return s.current=F,F},[e,f]);return{execute:m,estimate:g,lastFeeEstimate:s.current,hasEmbeddedWallet:t&&n,intentStatus:r,startStatusPolling:a,beginStatusTracking:i,applyStepUpdate:l,clearStatus:c}}const Gr=({color:e})=>C("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:[u("circle",{cx:"7",cy:"7",r:"6.5",stroke:e,strokeWidth:"1.2"}),u("path",{d:"M7 6v4",stroke:e,strokeWidth:"1.2",strokeLinecap:"round"}),u("circle",{cx:"7",cy:"4.5",r:"0.7",fill:e})]}),rl=({content:e,label:t="More info",textColor:n="#f9fafb",backgroundColor:o="#111827",borderColor:s="rgba(255,255,255,0.08)",accentColor:r="#9ca3af",children:a})=>{const i=Ba(),[l,c]=O(!1),d=_(null),[p,f]=O(!1),[h,m]=O(null);ae(()=>{f(!0)},[]),Da(()=>{if(!l||!d.current)return;const y=()=>{if(!d.current)return;const w=d.current.getBoundingClientRect(),x=Math.min(220,window.innerWidth-48),v=Math.min(Math.max(w.left+w.width/2,24+x/2),window.innerWidth-24-x/2),k=w.top>84;m({top:k?w.top-10:w.bottom+10,left:v,placement:k?"top":"bottom"})};return y(),window.addEventListener("scroll",y,!0),window.addEventListener("resize",y),()=>{window.removeEventListener("scroll",y,!0),window.removeEventListener("resize",y)}},[l]);const g=l&&p&&h?fr(C("span",{id:i,role:"tooltip",style:{position:"fixed",left:h.left,top:h.top,transform:h.placement==="top"?"translate(-50%, -100%)":"translate(-50%, 0)",width:"220px",maxWidth:"min(220px, calc(100vw - 48px))",padding:"10px 12px",borderRadius:"10px",backgroundColor:o,color:n,border:`1px solid ${s}`,boxShadow:"0 18px 45px rgba(0,0,0,0.28)",fontSize:"11px",lineHeight:"1.45",fontWeight:500,textAlign:"left",zIndex:ao.tooltip,pointerEvents:"none"},children:[e,u("span",{"aria-hidden":"true",style:{position:"absolute",left:"50%",width:"10px",height:"10px",transform:"translateX(-50%) rotate(45deg)",backgroundColor:o,...h.placement==="top"?{bottom:"-6px",borderRight:`1px solid ${s}`,borderBottom:`1px solid ${s}`}:{top:"-6px",borderTop:`1px solid ${s}`,borderLeft:`1px solid ${s}`}}})]}),document.body):null;return C(an,{children:[u("span",{ref:d,style:{position:"relative",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),children:u("button",{type:"button","aria-label":t,"aria-describedby":l?i:void 0,onFocus:()=>c(!0),onBlur:()=>c(!1),style:{width:"18px",height:"18px",borderRadius:"999px",display:"inline-flex",alignItems:"center",justifyContent:"center",border:`1px solid ${s}`,backgroundColor:"transparent",color:r,cursor:"help",padding:0,outline:"none",boxShadow:l?`0 0 0 2px ${r}26`:"none",transition:"border-color 120ms ease, box-shadow 120ms ease, color 120ms ease"},children:a||u(Gr,{color:r})})}),g]})},Xo=(e,t,n,o)=>({width:e,height:e,fill:"none",className:t,"aria-hidden":n??!0,style:o}),Eo=({size:e=16,color:t="currentColor",strokeWidth:n=2,direction:o="down",className:s,style:r,"aria-hidden":a})=>u("svg",{...Xo(e,s,a,{transform:o==="up"?"rotate(180deg)":void 0,transition:"transform 0.3s ease",...r}),viewBox:"0 0 16 16",children:u("path",{d:"M4 6L8 10L12 6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),Ju=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:o,style:s,"aria-hidden":r})=>C("svg",{...Xo(e,o,r,s),viewBox:"0 0 24 24",children:[u("circle",{cx:"11",cy:"11",r:"8",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"}),u("path",{d:"m21 21-4.3-4.3",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})]}),$u=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:o,style:s,"aria-hidden":r})=>u("svg",{...Xo(e,o,r,s),viewBox:"0 0 24 24",children:u("path",{d:"m6 9 6 6 6-6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),_u=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:o,style:s,"aria-hidden":r})=>u("svg",{...Xo(e,o,r,s),viewBox:"0 0 24 24",children:u("path",{d:"m9 18 6-6-6-6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),al=({size:e=14,color:t="currentColor",strokeWidth:n=2,className:o,style:s,"aria-hidden":r})=>u("svg",{...Xo(e,o,r,s),viewBox:"0 0 16 16",children:u("path",{d:"M3 8L6.5 11.5L13 5",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})});function Ws(e,t){if(e===0n)return"0";const n=10n**BigInt(t),o=e/n,s=(e%n).toString().padStart(t,"0").replace(/0+$/,"");return s?`${o.toString()}.${s}`:o.toString()}function Yr(e,t,n){const o=`${Ws(e,t)} ${n}`;return e===0n?o:`-${o}`}const ep=({fontFamily:e,textPrimary:t,textSecondary:n,cardBg:o,cardBorder:s,resolvedDark:r,darkCardBorder:a,primaryColor:i,feePreview:l,asset:c,isLoading:d,errorText:p,directExecutionFeeNote:f=!1})=>{const h=Rn(),m=c&&l&&[c.symbol,c.displaySymbol,c.receiptTokenName].includes(l.symbol)?h(c).symbol:l?.symbol,g=r?a??s:"#e5e7eb",y=r?"#111214":"#111827",w=r?"rgba(255,255,255,0.08)":"rgba(17,24,39,0.12)",x="#f87171",v=r?"#d1d5db":"#4b5563",k=r?"#f3f4f6":t,[A,b]=O(!1),S=!!p,T=S?null:l,E=T?[{label:"Total Required",help:"Total amount required to fund this action.",value:`${Ws(T.grossAmount,T.decimals)} ${m}`,tone:"default"},{label:"Spicenet Fee",help:"Fees paid to Spicenet for intent processing and execution.",value:Yr(T.spicenetFee,T.decimals,m),tone:"fee"},{label:"Network Fee",help:"Network fee shown in the same token you are using for this action.",value:Yr(T.gasFee,T.decimals,m),tone:"fee"},...T.bridgeFee&&T.bridgeFee>0n?[{label:"Bridge Fee",help:"Estimated cost to rebalance liquidity for this action.",value:Yr(T.bridgeFee,T.decimals,m),tone:"fee"}]:[],{label:"Used in TX",help:"Resulting amount of funds used in the transaction.",value:`${Ws(T.netAmount,T.decimals)} ${m}`,tone:"default"}]:[],I=T?`${Ws(T.grossAmount,T.decimals)} ${m}`:null;return S?u("div",{style:{backgroundColor:o,border:`1px solid ${s}`,borderRadius:r?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",boxShadow:r?"inset 0 1px 0 rgba(255,255,255,0.03)":"none"},children:C("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:[u("span",{style:{fontSize:"17px",fontWeight:500,color:v,fontFamily:e,lineHeight:"24px"},children:"Fee"}),u("div",{style:{color:x,fontSize:"12px",lineHeight:"1.55",fontFamily:e},children:p})]})}):C("div",{style:{backgroundColor:o,border:`1px solid ${s}`,borderRadius:r?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",boxShadow:r?"inset 0 1px 0 rgba(255,255,255,0.03)":"none"},children:[C("button",{type:"button",onClick:()=>b(M=>!M),style:{display:"flex",justifyContent:"space-between",alignItems:"center",width:"100%",gap:"12px",marginBottom:A?"14px":0,background:"none",border:"none",padding:0,cursor:"pointer",textAlign:"left"},children:[C("div",{style:{display:"flex",flexDirection:"column",gap:"4px"},children:[u("span",{style:{fontSize:"17px",fontWeight:500,color:v,fontFamily:e,lineHeight:"24px"},children:"Fee"}),A&&u("span",{style:{fontSize:"12px",color:n,fontFamily:e,lineHeight:"1.45"},children:"What is funded, spent, and taken as fees"})]}),C("div",{style:{display:"flex",alignItems:"center",gap:"8px",flexShrink:0},children:[I&&C("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:"2px",minWidth:0},children:[u("span",{style:{fontSize:"10px",fontWeight:700,color:n,fontFamily:e,letterSpacing:"0.08em",textTransform:"uppercase"},children:"Total required"}),u("span",{style:{fontSize:"14px",fontWeight:700,color:k,fontFamily:e,whiteSpace:"nowrap"},children:I})]}),d&&!f&&u("span",{style:{fontSize:"11px",fontWeight:600,color:i,fontFamily:e,padding:"6px 9px",borderRadius:"999px",backgroundColor:r?"rgba(255,255,255,0.04)":"rgba(0,0,0,0.035)",border:`1px solid ${r?g:"rgba(0,0,0,0.06)"}`,whiteSpace:"nowrap"},children:"Recalculating"}),u(Eo,{color:n,direction:A?"up":"down",style:{flexShrink:0}})]})]}),u("div",{style:{overflow:"hidden",maxHeight:A?"480px":"0px",opacity:A?1:0,transition:"max-height 0.24s ease, opacity 0.18s ease"},children:f?u("p",{style:{margin:0,color:n,fontSize:"12px",lineHeight:"1.55",fontFamily:e},children:"This path executes directly from the external wallet. Network gas is shown and paid in your wallet. No Spicenet fee is charged."}):E.length>0?C(an,{children:[u("div",{style:{display:"grid",gap:"10px"},children:E.map((M,W)=>C("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) auto",alignItems:"center",gap:"12px",paddingTop:W===0?0:"10px",borderTop:W===0?"none":`1px solid ${g}`,opacity:d?.74:1,transition:"opacity 120ms ease"},children:[C("div",{style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0},children:[u("span",{style:{fontSize:"12px",color:n,fontFamily:e,fontWeight:500},children:M.label}),u(rl,{content:M.help,label:`${M.label} info`,textColor:"#f9fafb",backgroundColor:y,borderColor:w,accentColor:r?"#8f96a3":"#6b7280"})]}),u("span",{style:{fontSize:"12px",color:M.tone==="fee"?x:k,fontFamily:Oe.mono,textAlign:"right",fontWeight:M.label==="Used in TX"?600:500,letterSpacing:"-0.01em"},children:M.value})]},M.label))}),u("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:`1px solid ${g}`,fontSize:"11px",color:n,fontFamily:e,lineHeight:"1.45"},children:T?.gasQuoteSource==="estimated"?"Gas quote uses a live estimate.":T?.gasQuoteSource==="configured_fallback"?"Gas quote uses a configured fallback.":"Gas quote is currently zero."})]}):u("div",{style:{fontSize:"12px",color:p?x:n,fontFamily:e,opacity:p?1:.8,lineHeight:"1.5"},children:p||"Waiting for fee estimate..."})})]})},Kr=yn(ep),Jo=({size:e=20,strokeWidth:t=2,color:n="currentColor",style:o})=>C("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:[u("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),u("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]});var il="data:image/svg+xml,%3csvg width='108' height='22' viewBox='0 0 108 22' fill='none' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M1.9916 11.9854V11.2041H3.98379C4.48835 11.2041 4.87897 11.0739 5.15566 10.8135C5.43236 10.5498 5.5707 10.1868 5.5707 9.72461V9.71484C5.5707 9.24935 5.43236 8.88639 5.15566 8.62598C4.87897 8.36556 4.48835 8.23535 3.98379 8.23535H1.9916V7.4541H4.2084C4.65111 7.4541 5.04173 7.5485 5.38027 7.7373C5.71882 7.92611 5.98411 8.18978 6.17617 8.52832C6.37148 8.86686 6.46914 9.25911 6.46914 9.70508V9.71484C6.46914 10.1608 6.37148 10.5547 6.17617 10.8965C5.98411 11.2383 5.71882 11.5052 5.38027 11.6973C5.04173 11.8893 4.65111 11.9854 4.2084 11.9854H1.9916ZM1.55215 14.5V7.4541H2.43106V14.5H1.55215ZM9.51875 14.5928C9.0207 14.5928 8.58939 14.4837 8.2248 14.2656C7.86348 14.0443 7.58353 13.7301 7.38496 13.3232C7.18965 12.9163 7.09199 12.4329 7.09199 11.873V11.8633C7.09199 11.3001 7.18965 10.8151 7.38496 10.4082C7.58353 10.0013 7.86348 9.6888 8.2248 9.4707C8.58939 9.2526 9.0207 9.14355 9.51875 9.14355C10.0201 9.14355 10.4514 9.2526 10.8127 9.4707C11.174 9.6888 11.4523 10.0013 11.6477 10.4082C11.8462 10.8151 11.9455 11.3001 11.9455 11.8633V11.873C11.9455 12.4329 11.8462 12.9163 11.6477 13.3232C11.4523 13.7301 11.174 14.0443 10.8127 14.2656C10.4514 14.4837 10.0201 14.5928 9.51875 14.5928ZM9.51875 13.8408C9.85078 13.8408 10.1324 13.7627 10.3635 13.6064C10.5946 13.4502 10.7704 13.2256 10.8908 12.9326C11.0145 12.6396 11.0764 12.2865 11.0764 11.873V11.8633C11.0764 11.4466 11.0145 11.0918 10.8908 10.7988C10.7704 10.5059 10.5946 10.2829 10.3635 10.1299C10.1324 9.97363 9.85078 9.89551 9.51875 9.89551C9.18672 9.89551 8.90514 9.97363 8.67402 10.1299C8.4429 10.2829 8.26549 10.5059 8.1418 10.7988C8.02135 11.0918 7.96113 11.4466 7.96113 11.8633V11.873C7.96113 12.2865 8.02135 12.6396 8.1418 12.9326C8.26549 13.2256 8.4429 13.4502 8.67402 13.6064C8.90514 13.7627 9.18672 13.8408 9.51875 13.8408ZM13.7842 14.5L12.3096 9.23633H13.1592L14.1943 13.4453H14.2725L15.4492 9.23633H16.2549L17.4316 13.4453H17.5098L18.5449 9.23633H19.3896L17.915 14.5H17.0605L15.8838 10.4277H15.8057L14.6338 14.5H13.7842ZM22.1658 14.5928C21.6645 14.5928 21.2332 14.4821 20.8719 14.2607C20.5138 14.0394 20.2371 13.7269 20.0418 13.3232C19.8497 12.9163 19.7537 12.4378 19.7537 11.8877V11.8828C19.7537 11.3392 19.8497 10.8623 20.0418 10.4521C20.2371 10.042 20.5122 9.72135 20.867 9.49023C21.2218 9.25911 21.6368 9.14355 22.1121 9.14355C22.5906 9.14355 23.0008 9.25423 23.3426 9.47559C23.6876 9.69694 23.9513 10.0062 24.1336 10.4033C24.3191 10.7972 24.4119 11.2562 24.4119 11.7803V12.1123H20.1932V11.4336H23.9773L23.5574 12.0537V11.7168C23.5574 11.3034 23.4956 10.9632 23.3719 10.6963C23.2482 10.4294 23.0773 10.2308 22.8592 10.1006C22.6411 9.96712 22.3904 9.90039 22.1072 9.90039C21.824 9.90039 21.5701 9.97038 21.3455 10.1104C21.1242 10.2471 20.9484 10.4505 20.8182 10.7207C20.688 10.9909 20.6229 11.3229 20.6229 11.7168V12.0537C20.6229 12.4281 20.6863 12.7487 20.8133 13.0156C20.9402 13.2793 21.1209 13.4827 21.3553 13.626C21.5896 13.766 21.8663 13.8359 22.1854 13.8359C22.423 13.8359 22.6297 13.8034 22.8055 13.7383C22.9813 13.6732 23.1261 13.5902 23.24 13.4893C23.354 13.3883 23.4337 13.2858 23.4793 13.1816L23.4988 13.1377H24.3484L24.3387 13.1768C24.2931 13.3558 24.2117 13.5299 24.0945 13.6992C23.9806 13.8652 23.8325 14.0166 23.6502 14.1533C23.4679 14.2868 23.2514 14.3942 23.0008 14.4756C22.7534 14.5537 22.4751 14.5928 22.1658 14.5928ZM25.4303 14.5V9.23633H26.2799V10.0176H26.358C26.4589 9.74089 26.6298 9.52604 26.8707 9.37305C27.1116 9.22005 27.4094 9.14355 27.7643 9.14355C27.8456 9.14355 27.9254 9.14844 28.0035 9.1582C28.0849 9.16471 28.1467 9.17122 28.1891 9.17773V10.0029C28.1012 9.98665 28.0149 9.97526 27.9303 9.96875C27.8489 9.95898 27.761 9.9541 27.6666 9.9541C27.3964 9.9541 27.1572 10.0078 26.9488 10.1152C26.7405 10.2227 26.5761 10.3724 26.4557 10.5645C26.3385 10.7565 26.2799 10.9811 26.2799 11.2383V14.5H25.4303ZM30.9408 14.5928C30.4395 14.5928 30.0082 14.4821 29.6469 14.2607C29.2888 14.0394 29.0121 13.7269 28.8168 13.3232C28.6247 12.9163 28.5287 12.4378 28.5287 11.8877V11.8828C28.5287 11.3392 28.6247 10.8623 28.8168 10.4521C29.0121 10.042 29.2872 9.72135 29.642 9.49023C29.9968 9.25911 30.4118 9.14355 30.8871 9.14355C31.3656 9.14355 31.7758 9.25423 32.1176 9.47559C32.4626 9.69694 32.7263 10.0062 32.9086 10.4033C33.0941 10.7972 33.1869 11.2562 33.1869 11.7803V12.1123H28.9682V11.4336H32.7523L32.3324 12.0537V11.7168C32.3324 11.3034 32.2706 10.9632 32.1469 10.6963C32.0232 10.4294 31.8523 10.2308 31.6342 10.1006C31.4161 9.96712 31.1654 9.90039 30.8822 9.90039C30.599 9.90039 30.3451 9.97038 30.1205 10.1104C29.8992 10.2471 29.7234 10.4505 29.5932 10.7207C29.463 10.9909 29.3979 11.3229 29.3979 11.7168V12.0537C29.3979 12.4281 29.4613 12.7487 29.5883 13.0156C29.7152 13.2793 29.8959 13.4827 30.1303 13.626C30.3646 13.766 30.6413 13.8359 30.9604 13.8359C31.198 13.8359 31.4047 13.8034 31.5805 13.7383C31.7563 13.6732 31.9011 13.5902 32.015 13.4893C32.129 13.3883 32.2087 13.2858 32.2543 13.1816L32.2738 13.1377H33.1234L33.1137 13.1768C33.0681 13.3558 32.9867 13.5299 32.8695 13.6992C32.7556 13.8652 32.6075 14.0166 32.4252 14.1533C32.2429 14.2868 32.0264 14.3942 31.7758 14.4756C31.5284 14.5537 31.2501 14.5928 30.9408 14.5928ZM36.1486 14.5928C35.7059 14.5928 35.3186 14.4805 34.9865 14.2559C34.6545 14.0312 34.3973 13.7155 34.215 13.3086C34.0328 12.8984 33.9416 12.4199 33.9416 11.873V11.8633C33.9416 11.3132 34.0328 10.8346 34.215 10.4277C34.3973 10.0208 34.6529 9.70508 34.9816 9.48047C35.3137 9.25586 35.7027 9.14355 36.1486 9.14355C36.3895 9.14355 36.6158 9.18262 36.8273 9.26074C37.0422 9.33561 37.2326 9.44141 37.3986 9.57812C37.5647 9.71484 37.6949 9.8776 37.7893 10.0664H37.8674V7.14648H38.717V14.5H37.8674V13.6602H37.7893C37.6818 13.8555 37.5467 14.0231 37.384 14.1631C37.2212 14.2998 37.0357 14.4056 36.8273 14.4805C36.619 14.5553 36.3928 14.5928 36.1486 14.5928ZM36.3439 13.8408C36.663 13.8408 36.938 13.7611 37.1691 13.6016C37.4003 13.4421 37.5777 13.2158 37.7014 12.9229C37.8251 12.6266 37.8869 12.2767 37.8869 11.873V11.8633C37.8869 11.4564 37.8251 11.1064 37.7014 10.8135C37.5777 10.5205 37.4003 10.2943 37.1691 10.1348C36.938 9.97526 36.663 9.89551 36.3439 9.89551C36.0249 9.89551 35.7499 9.97526 35.5188 10.1348C35.2909 10.291 35.1151 10.5156 34.9914 10.8086C34.871 11.1016 34.8107 11.4531 34.8107 11.8633V11.873C34.8107 12.2799 34.871 12.6315 34.9914 12.9277C35.1151 13.2207 35.2909 13.4469 35.5188 13.6064C35.7499 13.7627 36.0249 13.8408 36.3439 13.8408ZM45.1775 14.5928C44.9334 14.5928 44.7072 14.5553 44.4988 14.4805C44.2905 14.4056 44.1049 14.2998 43.9422 14.1631C43.7794 14.0231 43.6443 13.8555 43.5369 13.6602H43.4588V14.5H42.6092V7.14648H43.4588V10.0664H43.5369C43.6346 9.8776 43.7648 9.71484 43.9275 9.57812C44.0936 9.44141 44.2824 9.33561 44.4939 9.26074C44.7088 9.18262 44.9367 9.14355 45.1775 9.14355C45.6235 9.14355 46.0109 9.25586 46.3396 9.48047C46.6717 9.70508 46.9288 10.0208 47.1111 10.4277C47.2934 10.8346 47.3846 11.3132 47.3846 11.8633V11.873C47.3846 12.4199 47.2934 12.8984 47.1111 13.3086C46.9288 13.7155 46.6717 14.0312 46.3396 14.2559C46.0109 14.4805 45.6235 14.5928 45.1775 14.5928ZM44.9822 13.8408C45.3045 13.8408 45.5796 13.7627 45.8074 13.6064C46.0353 13.4469 46.2094 13.2207 46.3299 12.9277C46.4536 12.6315 46.5154 12.2799 46.5154 11.873V11.8633C46.5154 11.4531 46.4536 11.1016 46.3299 10.8086C46.2094 10.5156 46.0353 10.291 45.8074 10.1348C45.5796 9.97526 45.3045 9.89551 44.9822 9.89551C44.6632 9.89551 44.3881 9.97526 44.157 10.1348C43.9259 10.2943 43.7485 10.5205 43.6248 10.8135C43.5011 11.1064 43.4393 11.4564 43.4393 11.8633V11.873C43.4393 12.2767 43.5011 12.6266 43.6248 12.9229C43.7485 13.2158 43.9259 13.4421 44.157 13.6016C44.3881 13.7611 44.6632 13.8408 44.9822 13.8408ZM48.6568 16.3457C48.6015 16.3457 48.5396 16.3424 48.4713 16.3359C48.4029 16.3327 48.3395 16.3262 48.2809 16.3164V15.6182C48.3329 15.6279 48.3899 15.6344 48.4518 15.6377C48.5136 15.641 48.5738 15.6426 48.6324 15.6426C48.8733 15.6426 49.0702 15.5807 49.2232 15.457C49.3795 15.3333 49.5048 15.1201 49.5992 14.8174L49.6969 14.5049L47.7486 9.23633H48.6568L50.2779 14.0996L49.941 13.5674H50.3414L50.0045 14.0996L51.6207 9.23633H52.5143L50.4586 14.8223C50.3154 15.2161 50.164 15.5238 50.0045 15.7451C49.845 15.9665 49.6578 16.1211 49.443 16.209C49.2314 16.3001 48.9693 16.3457 48.6568 16.3457Z' fill='%230E0D0B'/%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%3cpath fill-rule='evenodd' clip-rule='evenodd' d='M74.8537 10.0096C75.2721 10.0096 75.654 10.1125 75.9993 10.3184C76.3513 10.5177 76.6303 10.8032 76.8361 11.1751C77.0487 11.547 77.1549 11.9953 77.1549 12.52V12.6495C77.1549 13.1675 77.052 13.6158 76.8461 13.9943C76.6402 14.3729 76.3613 14.6618 76.0093 14.861C75.664 15.0603 75.2788 15.1599 74.8537 15.1599C74.515 15.1599 74.2261 15.1134 73.9871 15.0204C73.7546 14.9341 73.5653 14.8212 73.4192 14.6817C73.2731 14.5423 73.1602 14.3995 73.0805 14.2534H72.941V16.9659L72.1541 16.0013V10.1491H72.9211V10.956H73.0352C73.2729 10.6733 73.3893 10.4911 73.6683 10.2985C73.9538 10.1059 74.349 10.0096 74.8537 10.0096ZM74.6445 10.7069C74.1464 10.7069 73.7347 10.8696 73.4092 11.195C73.0905 11.5138 72.9311 11.9621 72.9311 12.5399V12.6296C72.9311 13.2074 73.0905 13.659 73.4092 13.9844C73.7347 14.3032 74.1464 14.4626 74.6445 14.4626C75.1492 14.4626 75.5577 14.3032 75.8698 13.9844C76.1886 13.659 76.348 13.2074 76.348 12.6296V12.5399C76.348 11.9621 76.1886 11.5138 75.8698 11.195C75.5577 10.8696 75.1492 10.7069 74.6445 10.7069Z' fill='%230E0D0B'/%3e%3cpath d='M78.5848 11.9583L78.5555 15.4596L77.7681 14.4846V10.9583L78.5848 11.9583Z' fill='%230E0D0B'/%3e%3cpath d='M101.588 10.2986H102.444L103 10.986H101.588V10.9867H100.802L101.588 11.9623V14.1937C101.588 14.3929 101.685 14.4926 101.877 14.4926H102.379L102.928 15.17H101.668C101.389 15.17 101.173 15.0936 101.021 14.9409C100.874 14.7881 100.801 14.5789 100.801 14.3133V10.986H99.8799L99.3217 10.2986H100.801V9.13501H101.588V10.2986Z' fill='%230E0D0B'/%3e%3cpath d='M69.0133 7.90764C69.4848 7.90764 69.9065 7.99068 70.2784 8.15671C70.6569 8.3161 70.9525 8.55517 71.165 8.87395C71.3842 9.18609 71.4938 9.58126 71.4938 10.0594V10.4778H70.667V10.0594C70.667 9.72072 70.5939 9.44842 70.4477 9.24254C70.3083 9.03666 70.1124 8.88392 69.86 8.7843C69.6143 8.68469 69.332 8.63487 69.0133 8.63487C68.555 8.63487 68.1864 8.7378 67.9075 8.94367C67.6286 9.14291 67.4891 9.4285 67.4891 9.80041C67.4891 10.0461 67.5488 10.2453 67.6684 10.3981C67.7879 10.5508 67.9573 10.677 68.1764 10.7767C68.3956 10.8696 68.658 10.9527 68.9635 11.0257L69.4815 11.1552C69.8866 11.2416 70.2485 11.3611 70.5673 11.5138C70.8927 11.6599 71.1517 11.8625 71.3443 12.1215C71.5369 12.3739 71.6332 12.706 71.6332 13.1177C71.6332 13.5295 71.5303 13.8881 71.3244 14.1936C71.1185 14.4991 70.8263 14.7382 70.4477 14.9109C70.0758 15.0769 69.6375 15.1599 69.1328 15.1599C68.6281 15.1599 68.1765 15.0702 67.778 14.8909C67.3795 14.7116 67.0641 14.4426 66.8316 14.084C66.6058 13.7187 66.4929 13.2638 66.4929 12.7192V12.51H67.3197V12.7192C67.3197 13.297 67.4891 13.7287 67.8278 14.0143C68.1665 14.2932 68.6015 14.4327 69.1328 14.4327C69.6774 14.4327 70.0924 14.3098 70.378 14.0641C70.6636 13.8183 70.8064 13.5095 70.8064 13.1376C70.8064 12.8786 70.74 12.6727 70.6072 12.52C70.481 12.3673 70.3017 12.2444 70.0692 12.1514C69.8368 12.0518 69.5645 11.9655 69.2523 11.8924L68.7343 11.7629C68.3292 11.6566 67.9706 11.5271 67.6584 11.3744C67.3463 11.2216 67.1006 11.0224 66.9213 10.7767C66.7486 10.5243 66.6623 10.2022 66.6623 9.81035C66.6623 9.41852 66.7585 9.07981 66.9511 8.79424C67.1504 8.50866 67.426 8.28953 67.778 8.13678C68.1366 7.98404 68.5484 7.90764 69.0133 7.90764Z' fill='%230E0D0B'/%3e%3cpath d='M81.6544 10.0096C82.1193 10.0096 82.5145 10.0959 82.8399 10.2686C83.1719 10.4412 83.431 10.6704 83.6169 10.956C83.8095 11.2415 83.9324 11.5471 83.9855 11.8725L83.2185 12.0318C83.1853 11.7928 83.1056 11.5736 82.9794 11.3744C82.8598 11.1752 82.6905 11.0158 82.4713 10.8962C82.2521 10.7767 81.9832 10.7169 81.6644 10.7169C81.339 10.7169 81.0468 10.7899 80.7877 10.936C80.5354 11.0821 80.3328 11.2914 80.1801 11.5637C80.034 11.836 79.9609 12.1614 79.9609 12.5399V12.6296C79.9609 13.0081 80.034 13.3335 80.1801 13.6058C80.3328 13.8781 80.5354 14.0873 80.7877 14.2334C81.0468 14.3795 81.339 14.4526 81.6644 14.4526C82.1492 14.4526 82.5178 14.3264 82.7702 14.0741C83.0292 13.8217 83.1886 13.5095 83.2483 13.1376L84.0254 13.307C83.9523 13.6257 83.8195 13.9279 83.6269 14.2135C83.4343 14.4991 83.172 14.7282 82.8399 14.9009C82.5145 15.0735 82.1193 15.1599 81.6544 15.1599C81.1829 15.1599 80.7579 15.0603 80.3793 14.861C80.0074 14.6551 79.7119 14.363 79.4927 13.9844C79.2802 13.6059 79.1739 13.1575 79.1739 12.6395V12.5299C79.1739 12.0053 79.2802 11.557 79.4927 11.1851C79.7119 10.8066 80.0074 10.5177 80.3793 10.3184C80.7579 10.1126 81.1829 10.0096 81.6544 10.0096Z' fill='%230E0D0B'/%3e%3cpath fill-rule='evenodd' clip-rule='evenodd' d='M86.7515 10.0096C87.2097 10.0096 87.6149 10.1092 87.9668 10.3084C88.3188 10.501 88.5944 10.78 88.7937 11.1452C88.9929 11.5105 89.0925 11.9389 89.0925 12.4304V12.7889H85.1177C85.1377 13.3136 85.3071 13.7254 85.6258 14.0243C85.9446 14.3165 86.3431 14.4626 86.8212 14.4626C87.2396 14.4626 87.5617 14.3663 87.7875 14.1737C88.0133 13.9811 88.186 13.752 88.3056 13.4863L88.983 13.815C88.8833 14.0209 88.7439 14.2268 88.5646 14.4327C88.3919 14.6386 88.1628 14.8113 87.8772 14.9507C87.5983 15.0902 87.2396 15.1599 86.8013 15.1599C86.3099 15.1599 85.8782 15.057 85.5063 14.8511C85.1344 14.6386 84.8455 14.343 84.6396 13.9645C84.4337 13.5859 84.3307 13.1476 84.3307 12.6495V12.5299C84.3307 12.0252 84.4337 11.5836 84.6396 11.205C84.8455 10.8265 85.1311 10.5342 85.4963 10.3284C85.8616 10.1159 86.28 10.0096 86.7515 10.0096ZM86.7515 10.7069C86.3066 10.7069 85.9413 10.8331 85.6557 11.0855C85.3701 11.3378 85.1941 11.6898 85.1277 12.1414H88.2956C88.269 11.6898 88.113 11.3378 87.8274 11.0855C87.5485 10.8331 87.1898 10.7069 86.7515 10.7069Z' fill='%230E0D0B'/%3e%3cpath fill-rule='evenodd' clip-rule='evenodd' d='M97.1624 10.0096C97.6207 10.0096 98.0258 10.1092 98.3778 10.3084C98.7298 10.501 99.0054 10.78 99.2046 11.1452C99.4039 11.5105 99.5035 11.9389 99.5035 12.4304V12.7889H95.5287C95.5487 13.3136 95.718 13.7254 96.0368 14.0243C96.3555 14.3165 96.754 14.4626 97.2322 14.4626C97.6505 14.4626 97.9727 14.3663 98.1985 14.1737C98.4243 13.9811 98.5969 13.752 98.7165 13.4863L99.3939 13.815C99.2943 14.0209 99.1548 14.2268 98.9755 14.4327C98.8028 14.6386 98.5737 14.8113 98.2881 14.9507C98.0092 15.0902 97.6506 15.1599 97.2123 15.1599C96.7208 15.1599 96.2892 15.057 95.9172 14.8511C95.5453 14.6386 95.2564 14.343 95.0505 13.9645C94.8446 13.5859 94.7417 13.1476 94.7417 12.6495V12.5299C94.7417 12.0252 94.8446 11.5836 95.0505 11.205C95.2564 10.8265 95.542 10.5342 95.9073 10.3284C96.2725 10.1158 96.6909 10.0096 97.1624 10.0096ZM97.1624 10.7069C96.7175 10.7069 96.3522 10.8331 96.0666 11.0855C95.7811 11.3378 95.6051 11.6898 95.5387 12.1414H98.7066C98.68 11.6898 98.5239 11.3378 98.2383 11.0855C97.9594 10.8331 97.6008 10.7069 97.1624 10.7069Z' fill='%230E0D0B'/%3e%3cpath d='M92.2484 10.0594C92.6137 10.0594 92.9391 10.1358 93.2247 10.2885C93.5169 10.4413 93.7494 10.6671 93.9221 10.966C94.0947 11.2648 94.1811 11.6334 94.1811 12.0717V15.1458H93.394V12.1315C93.394 11.6467 93.2712 11.2947 93.0255 11.0755C92.7864 10.8564 92.461 10.7468 92.0492 10.7468C91.5777 10.7468 91.1925 10.8995 90.8936 11.205C90.6014 11.5105 90.4553 11.9655 90.4553 12.5698V15.1458H89.6683V10.1491H90.4354V10.9582H90.5361C90.7355 10.7018 90.8604 10.5342 91.1128 10.3483C91.3718 10.1557 91.7503 10.0594 92.2484 10.0594Z' fill='%230E0D0B'/%3e%3cpath d='M78.5932 10.9581H77.7681V10.1514H78.6L78.5932 10.9581Z' fill='%230E0D0B'/%3e%3c/svg%3e";const ll=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(","),Dn=({isOpen:e,onClose:t,title:n,subtitle:o,children:s,overlayContent:r,overlayDimmed:a=!0,styles:i,theme:l,maxWidth:c="522px",dark:d,footerLinkText:p,bannerSrc:f,bannerAlt:h,closeOnBackdropClick:m=!1})=>{const{theme:g,dark:y,dk:w,palette:x}=Bt(i,d),v=d??y,k=l||g,A=i?.fontFamily||k.typography.fontFamily||Oe.ui,b=i?.primaryColor||k.colors.primary,S=_(null),T=_(null),E=_(null),I=Ba(),[M,W]=O(!1),[R,F]=O(!1),N=_(t);if(ae(()=>{N.current=t},[t]),ae(()=>{if(!e){F(!1);return}T.current=document.activeElement;const z=document.body.style.overflow;document.body.style.overflow="hidden";const fe=requestAnimationFrame(()=>{const re=requestAnimationFrame(()=>F(!0));E.current=re}),ce=()=>{const re=S.current;re&&(re.querySelectorAll(ll)[0]??re).focus({preventScroll:!0})},Q=re=>{if(re.key==="Escape"){re.stopPropagation(),N.current();return}if(re.key!=="Tab")return;const j=S.current;if(!j)return;const J=Array.from(j.querySelectorAll(ll)).filter(U=>!U.hasAttribute("aria-hidden"));if(J.length===0){re.preventDefault(),j.focus();return}const Y=J[0],me=J[J.length-1],B=document.activeElement;re.shiftKey&&B===Y?(re.preventDefault(),me.focus()):!re.shiftKey&&B===me&&(re.preventDefault(),Y.focus())},ne=requestAnimationFrame(ce);return document.addEventListener("keydown",Q),()=>{cancelAnimationFrame(ne),cancelAnimationFrame(fe),E.current&&cancelAnimationFrame(E.current),document.removeEventListener("keydown",Q),document.body.style.overflow=z;const re=T.current;re&&typeof re.focus=="function"&&re.focus({preventScroll:!0})}},[e]),!e)return null;const D=!!f&&!M,L=h??"";return u("div",{onMouseDown:z=>{m&&z.target===z.currentTarget&&N.current()},style:{position:"fixed",inset:0,backgroundColor:v?"rgba(0,0,0,0.72)":"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",padding:"clamp(16px, 4vw, 48px)",zIndex:ao.modal,opacity:R?1:0,transition:`opacity ${nr.normal} ${wo.out}`},children:u("div",{ref:S,role:"dialog","aria-modal":"true","aria-labelledby":I,tabIndex:-1,style:{backgroundColor:x.shellBorder,borderRadius:"12px",padding:"5px",width:"100%",maxWidth:c,boxSizing:"border-box",boxShadow:"0 16px 48px rgba(0, 0, 0, 0.4)",outline:"none",transform:R?"scale(1)":"scale(0.96)",transition:`transform ${nr.slow} ${wo.out}`,display:"flex",flexDirection:"column",maxHeight:"100%"},children:C("div",{style:{backgroundColor:x.shell,border:`1px solid ${x.shellInnerBorder}`,borderRadius:"9px",width:"100%",padding:"0",display:"flex",flexDirection:"column",position:"relative",flex:"0 1 auto",minHeight:0,overflowY:"auto",overflowX:"hidden"},children:[r&&a&&u("div",{style:{position:"absolute",inset:0,backgroundColor:"rgba(0, 0, 0, 0.4)",zIndex:5,pointerEvents:"none",borderRadius:"12px"},"aria-hidden":"true"}),D&&C("div",{style:{position:"relative",width:"100%"},children:[u("img",{src:f,style:{width:"100%",height:"auto",display:"block",borderRadius:"6px 6px 0 0"},alt:L,"aria-hidden":L===""?"true":void 0,onError:()=>W(!0)}),u("button",{type:"button",onClick:t,"aria-label":"Close dialog",style:{position:"absolute",top:"8px",right:"8px",minWidth:"44px",minHeight:"44px",color:x.textPrimary,padding:"8px",backgroundColor:"transparent",borderRadius:"9999px",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1},children:u(Jo,{size:28,strokeWidth:2.5})})]}),C("div",{style:{padding:"28px 28px 0 28px",position:"relative"},children:[!D&&u("button",{type:"button",onClick:t,"aria-label":"Close dialog",style:{position:"absolute",top:"10px",right:"10px",minWidth:"44px",minHeight:"44px",color:x.textSecondary,padding:"10px",backgroundColor:"transparent",borderRadius:"50%",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.2s",fontSize:"18px",fontWeight:"600"},onMouseEnter:z=>{z.currentTarget.style.backgroundColor=v?`${b}1a`:"#f3f4f6"},onMouseLeave:z=>{z.currentTarget.style.backgroundColor="transparent"},children:u(Jo,{size:24,strokeWidth:2.4})}),u("h2",{id:I,style:{fontSize:"22px",fontWeight:"700",color:x.textPrimary,margin:"0",fontFamily:A,lineHeight:"1.12"},children:n})]}),o&&u("div",{style:{padding:"11px 28px 13px 28px",fontSize:"12px",color:x.textSecondary,margin:"0",lineHeight:"1.35",fontFamily:A,borderBottom:v?`1px solid ${w.cardBorder}`:"1px solid #cdcfd1"},children:o}),s,C("div",{style:{padding:"12px 28px",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[u("img",{src:il,alt:"","aria-hidden":"true",width:108,height:22,decoding:"async",style:{width:"108px",height:"22px",opacity:v?.85:1,filter:v?"brightness(0) invert(1)":"none",margin:0,display:"block"}}),u("a",{href:"https://spiceflow-docs.spicenet.io",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"10px",color:x.textSecondary,textDecoration:"none",display:"flex",alignItems:"center",gap:"4px",fontFamily:A,lineHeight:"1"},children:u("span",{style:{color:b,textDecoration:"underline",fontWeight:"500"},children:p??"Learn more \u2192"})})]}),r]})})})},cl=({dk:e,dark:t,message:n,buttonLabel:o,onAction:s,disabled:r=!1})=>C("div",{style:{padding:"12px",backgroundColor:e.warningBg,borderRadius:"8px",border:`1px solid ${e.warningBorder}`},children:[u("p",{style:{margin:"0 0 10px 0",color:e.warningText,fontSize:"14px"},children:n}),u("button",{onClick:s,disabled:r,style:{width:"100%",padding:"8px 12px",borderRadius:"6px",border:`1px solid ${t?e.warningBorder:"#fbbf24"}`,backgroundColor:t?e.cardBg:"white",cursor:r?"not-allowed":"pointer",fontWeight:600,fontSize:"13px",color:e.warningText,opacity:r?.6:1},children:o})]}),dl=({dk:e,dark:t,borderRadius:n,children:o})=>u("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:t?e.warningBg:"#fffbeb",border:`1px solid ${e.warningBorder}`,borderRadius:n,fontSize:"12px",color:e.warningText,lineHeight:"1.4"},children:o});async function tp(e,t,n){let o=null;try{const s=await e.request({method:"eth_chainId"});o=parseInt(s,16)}catch{o=null}o!==t&&(n?.(),await ka(e,t))}function ul(e){let t=e;const n=new Set;for(;t&&typeof t=="object"&&!n.has(t);){if(n.add(t),t.code===4001)return!0;t=t.cause}return!1}async function Zr(e){const t=e.provider??await e.wallet?.getEthereumProvider();if(!t)throw new Error("External wallet provider not available");await tp(t,e.chainId,e.onSwitch);const n=await t.request({method:"eth_accounts"});if(!Array.isArray(n)||!n.some(s=>typeof s=="string"&&s.toLowerCase()===e.account.toLowerCase()))throw new Error("The connected source wallet changed. Reconnect the selected account before funding.");const o=Ge(e.chainId)?.viemChain;return{extWc:cr({account:e.account,chain:o,transport:dr(t)}),viemChain:o}}async function pl(e,t,n){const o=Date.now()+1e4;for(;Date.now()<o;){let s;try{s=await Promise.all([t.getBlockNumber({cacheTime:0}),e.request({method:"eth_blockNumber"}).then(BigInt)])}catch{return}if(s.every(r=>r>=n))return;await new Promise(r=>setTimeout(r,250))}}async function np(e){let t;for(const[n,o]of e.calls.entries()){await e.observer?.onSending?.(n);let s;try{s=await e.extWc.sendTransaction({to:o.to,data:o.data,value:o.value,chain:e.viemChain})}catch(i){throw ul(i)&&e.observer?.onRejected?.(n),i}e.observer?.onSubmitted?.(n,s);const r=await Ds({client:e.client,hash:s,call:o,onRepriced:i=>e.observer?.onSubmitted?.(n,i),onCancelled:()=>e.observer?.onReverted?.(n,s)});s=r.hash;const a=r.receipt;if(a.status!=="success")throw e.observer?.onReverted?.(n,s),new Error(e.errorMessage);await pl(e.extWc,e.client,a.blockNumber),e.observer?.onConfirmed?.(n,s),t=s}return t}async function fl(e){const t=await e.client.estimateFeesPerGas(),n=t.maxFeePerGas??t.gasPrice;if(typeof n!="bigint"||n<=0n)throw new Error("Network gas could not be priced.");let o=0n;for(const s of e.calls){const r=await e.client.estimateGas({account:e.account,...s});o+=(r*n*120n+99n)/100n}return o}function Ns(e,t,n,o){return n?{to:e,value:o,data:"0x"}:{to:t,value:0n,data:xt({abi:tt,functionName:"transfer",args:[e,o]})}}async function ml(e){const t=Ns(e.recipient,e.token,e.isNative,e.amount),[n,o]=await Promise.all([e.client.estimateGas({account:e.account,...t}),e.client.estimateFeesPerGas()]),s=o.maxFeePerGas??o.gasPrice;if(typeof s!="bigint"||s<=0n)throw new Error("Source transaction gas could not be priced.");return(n*s*120n+99n)/100n}function Xr(e,t){return t.isNative?e.sendTransaction({to:t.recipient,value:t.amount,chain:t.viemChain}):e.sendTransaction({to:t.tokenAddr,data:xt({abi:tt,functionName:"transfer",args:[t.recipient,t.amount]}),chain:t.viemChain})}async function op(e){const{extWc:t,sourceClient:n,recipient:o,tokenAddr:s,isNative:r,amount:a}=e;if(a<=0n)return;await e.observer?.onSending?.(0);let i;try{i=await Xr(t,{recipient:o,tokenAddr:s,isNative:r,amount:a,viemChain:e.viemChain})}catch(d){throw ul(d)&&e.observer?.onRejected?.(0),d}e.observer?.onSubmitted?.(0,i);const l=await Ds({client:n,hash:i,call:Ns(o,s,r,a),onRepriced:d=>e.observer?.onSubmitted?.(0,d),onCancelled:()=>e.observer?.onReverted?.(0,i)});i=l.hash;const c=l.receipt;if(c.status!=="success")throw e.observer?.onReverted?.(0,i),new Error("Embedded wallet funding failed");await pl(t,n,c.blockNumber),e.observer?.onConfirmed?.(0,i)}function sp({sourceChainId:e,selectedAsset:t,destinationChainId:n,destinationTokenAddress:o,isCrossDenomination:s,convertedUsdAmount:r}){const a=Ye(t.asset.address),i=o;let l,c;if(i&&n)if(l=ls[n]?.supportedTokens?.find(d=>ge(d.address,i))?.decimals??t.asset.decimals,s){if(!r)throw new Error("Destination amount is still being calculated. Please retry in a moment.");c=r}else{const d=mn(t.amount,t.asset.decimals);c=co(d,t.asset.decimals,l)}return{sourceChainId:e,depositTokenAddress:a,depositAmount:t.amount,depositTokenDecimals:t.asset.decimals,destinationChainId:n,destinationTokenAddress:i,destinationAmount:c,destinationTokenDecimals:l}}async function rp(e,t){if(!e)return[];if(Array.isArray(e))return e;const n=e;return e.length>=2?n(t.depositAmount,t.depositTokenAddress):n(t)}function hl(e,t){return!!e&&e.quotedAmount===t.amount&&e.chainId===t.chainId&&ge(e.token,t.token)}async function Ps(e,t){const n=await Xr(e,{recipient:t.recipient,tokenAddr:t.tokenAddr,isNative:t.isNative,amount:t.amount});t.afterSend?.(n);const o=yt(t.chainId),{receipt:s,hash:r}=await Ds({client:o,hash:n,call:Ns(t.recipient,t.tokenAddr,t.isNative,t.amount),confirmations:2});if(s.status!=="success")throw new Error(t.failureMessage);return t.settle&&await o.getBlockNumber()-s.blockNumber<2n&&await Bn(3e3),r}async function ap(e){const t=e.selectedDepositAssets.filter(s=>s.asset&&s.amount&&parseFloat(s.amount)>0);if(t.length===0){console.error("[DepositModal] No valid assets for deposit"),e.setError("Please select an asset and enter an amount");return}const n=t[0];if(!e.escrowOnly&&!e.sourceAddress){e.setError("External wallet not connected. Please connect your wallet in the previous step.");return}if(!e.isNon7702){if(!e.address||!e.embeddedWalletAddress){e.setError("Couldn't find your account wallet. Try reconnecting.");return}if(!e.isReady||!e.isAuthenticated){e.setError("Sign in to continue.");return}}if(e.zeroCreditError){e.setError(e.zeroCreditError);return}if(e.depositBalanceError){e.setError(e.depositBalanceError);return}if(e.isNon7702&&e.sponsorGas&&e.nativeChainId&&n.asset.chainId!==e.nativeChainId&&e.destinationTokenAddress){e.setError("Gas sponsorship is not supported for this deposit route. Disable sponsorGas to continue.");return}e.setIsExecuting(!0),e.setError(null);let o=!1;try{const s=n.asset.chainId,r=Jn(s),a=mn(n.amount,n.asset.decimals),i=t.length===1&&hl(e.effectiveDepositFee,{amount:a,token:Ye(n.asset.address),chainId:s}),l=!e.isNon7702&&!e.escrowOnly&&!no(n.asset);if(!e.isNon7702&&t.length===1&&!l&&!i)throw new Error("Fee quote is out of date. Please wait for it to refresh.");let c=e.externalWalletClient;if(!e.escrowOnly){if(!c)throw new Error("External wallet not connected");if(e.externalProvider){const d=await Zr({provider:e.externalProvider,account:e.sourceAddress,chainId:s});d.viemChain&&(c=d.extWc)}}if(e.isNon7702){if(!c)throw new Error("External wallet not connected");if(!e.sourceAddress)throw new Error("External wallet address not available");if(e.nativeChainId&&s===e.nativeChainId){const d=Ge(s),p=t.map(h=>`${h.amount} ${h.asset.symbol}`).join(", ");e.setConfirmationData({network:d?.displayName||`Chain ${s}`,amount:p,symbol:"",chainId:s}),e.setShowConfirmation(!0);let f=null;e.setDirectDepositStatus("processing"),e.setDirectDepositChainId(s);for(const h of t){const m=mn(h.amount,h.asset.decimals),g=Ye(h.asset.address),y=h.asset.isNative||be(g),w=await Ps(c,{chainId:s,recipient:r,tokenAddr:g,isNative:y,amount:m,failureMessage:`Escrow deposit failed for ${h.asset.symbol}`});f=w,e.setDirectDepositTxHash(w)}if(t[0]?.amount){const h=t[0].amount;if(e.onDepositExecute){e.setPostDepositStatus("executing");try{await e.onDepositExecute(h),e.setPostDepositStatus("success")}catch(g){console.error("ctx.onDepositExecute failed:",g),e.setPostDepositStatus("error"),e.setPostDepositError(g?.message||"Post-deposit instruction failed")}}else e.setPostDepositStatus("success");e.setDirectDepositStatus("success"),e.setPostDepositAmount(h),e.setPostDepositSuccess(!0);const m={type:"deposit",status:"success",amount:h,asset:t[0].asset.symbol,sourceChain:d?.displayName||`Chain ${s}`,txHash:f??void 0};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:m})),e.onDepositSuccess?.(m)}e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset)}else{const d=e.destinationChainId||e.nativeChainId;if(!d)throw new Error("Destination chain ID is required for non-7702 mode. Either pass ctx.destinationChainId to <SpiceDeposit> or set ctx.nativeChainId on <SpiceFlowProvider>.");const p=va(s),f=r,h=[];let m=null;for(const g of t){const y=mn(g.amount,g.asset.decimals),w=Ye(g.asset.address),x=g.asset.isNative||be(w),v=await Ps(c,{chainId:s,recipient:f,tokenAddr:w,isNative:x,amount:y,failureMessage:`Transfer failed for ${g.asset.symbol}`,settle:!0});m||(m=v),e.depositDataRef.current||(e.depositDataRef.current=[]),e.depositDataRef.current.push({txHash:v,sender:e.sourceAddress,tokenAddress:w,chainId:s,amount:y.toString(),user:e.spiceBalanceUser}),h.push({tokenAddress:w,tokenAmount:y.toString(),sender:e.sourceAddress,receiver:f})}if(!m)throw new Error("No transaction hash generated");if(!e.destinationTokenAddress){const g={type:"deposit",status:"success",amount:t[0]?.amount,asset:t[0]?.asset?.symbol,sourceChain:gn(s),txHash:m};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:g})),e.onDepositSuccess?.(g),e.depositDataRef.current=null,e.bridgedAmountRef.current=t[0]?.amount||null,e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset),e.setShowConfirmation(!1);return}if(e.mode==="ondemand"){const g={to:p,value:BigInt(0),data:"0x"},y=await as(d,e.destinationTokenAddress);let w=BigInt(0);for(const I of h){const M=BigInt(I.tokenAmount),W=Ye(I.tokenAddress),R=t.find(N=>{const D=Ye(N.asset.address);return ge(D,W)}),F=R?R.asset.decimals:await as(s,Tt);w+=co(M,F,y)}e.isCrossDenomination&&e.convertedUsdAmount&&(w=e.convertedUsdAmount);const x={chainId:s,tokenTransfers:h.map(I=>({from:I.sender,to:I.receiver,token:I.tokenAddress,amount:BigInt(I.tokenAmount)})),call:g},v=e.isCrossDenomination&&e.convertedUsdAmount?[{from:e.sourceAddress,to:r,token:Ye(t[0].asset.address),amount:mn(t[0].amount,t[0].asset.decimals)}]:[],k={chainId:d,tokenTransfers:[...v,{from:"escrow",to:e.sourceAddress,token:e.destinationTokenAddress,amount:w}],call:{to:e.destinationTokenAddress,value:BigInt(0),data:"0x"}},A={mode:"non-7702:on-demand",chainBatches:[x,k]},b={user:e.sourceAddress,intents:[A]},S=await Lt.createAction(b),T=S.actionId,E=S.intentIds[0];if(!m)throw new Error("No transaction hash available");e.startStatusPolling(E,Ia([{chainId:s,calls:[g]},{chainId:d,calls:[k.call]}],I=>gn(I))),await Lt.executeStep(T,0,0,{action:"execute",hash:m}),t[0]?.amount&&(e.bridgedAmountRef.current=t[0].amount),e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset),e.setShowConfirmation(!1)}else throw new Error("Presign mode not yet fully supported for cross-chain deposits")}}else{const d=[];let p=0,f;const h=i&&e.effectiveDepositFee?Fe(e.effectiveDepositFee.net,n.asset.decimals):n?.amount;for(const I of t){const M=mn(I.amount,I.asset.decimals),W=i&&I===n,R=W?e.effectiveDepositFee.fee:0n,F=W?e.effectiveDepositFee.net:M,N=e.escrowOnly?M:M+R,D=Ye(I.asset.address),L=I.asset.isNative||be(D);if(!e.escrowOnly&&!no(I.asset)){e.setDirectDepositStatus("processing"),e.setDirectDepositChainId(s);const z=await Ps(c,{chainId:s,recipient:e.address,tokenAddr:D,isNative:L,amount:M,failureMessage:`Transfer to embedded wallet failed for ${I.asset.symbol}`});p+=1,I===n&&(f=z);continue}e.escrowOnly||await Ps(c,{chainId:s,recipient:e.address,tokenAddr:D,isNative:L,amount:N,failureMessage:`Transfer to embedded wallet failed for ${I.asset.symbol}`,afterSend:()=>pu({chainId:s,tokenAddress:Ye(I.asset.address),tokenSymbol:I.asset.symbol,tokenDecimals:I.asset.decimals,amount:I.amount,rawAmount:M.toString(),embeddedWalletAddress:e.address,externalWalletAddress:e.sourceAddress,timestamp:Date.now(),isNative:L}),settle:!0}),d.push(L?{to:r,value:F,data:"0x"}:{to:D,value:BigInt(0),data:xt({abi:tt,functionName:"transfer",args:[r,F]})}),R>0n&&d.push(L?{to:nn,value:R,data:"0x"}:{to:D,value:BigInt(0),data:xt({abi:tt,functionName:"transfer",args:[nn,R]})})}if(d.length===0){e.setDirectDepositTxHash(f??null),e.setDirectDepositStatus("success");const I={type:"deposit",status:"success",amount:n.amount,asset:n.asset.symbol,sourceChain:gn(s),txHash:f};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:I})),e.onDepositSuccess?.(I),e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(n.asset);return}p>0&&e.setDirectDepositStatus("idle");const m=t.find(I=>e.escrowOnly||no(I.asset))??n,g=await yt(s).getBlockNumber(),y=d.map(I=>({...I,to:zt(I.to)})),w={chainId:s,recentBlock:g,calls:y,tokenTransfers:[]},x=sp({sourceChainId:s,selectedAsset:m===n&&h?{...n,amount:h}:m,destinationChainId:e.destinationChainId,destinationTokenAddress:e.destinationTokenAddress,isCrossDenomination:e.isCrossDenomination,convertedUsdAmount:e.convertedUsdAmount}),v=await rp(e.depositBatches,x),k=[w,...v];if(!e.address)throw new Error("Address not available");const A=[];if(e.isCrossDenomination&&e.convertedUsdAmount&&e.destinationTokenAddress){const I=e.selectedDepositAssets[0]?.asset;if(I){const M=mn(e.selectedDepositAssets[0].amount,I.decimals);A.push({from:e.address,to:r,token:Ye(I.address),amount:M}),A.push({from:"escrow",to:e.address,token:e.destinationTokenAddress,amount:e.convertedUsdAmount})}}A.length>0&&k[1]&&(k[1].tokenTransfers=A);const b=Ia(k,I=>gn(I));let S=!1;const T=await e.execution.execute(k,Tt,0n,I=>{if(I.intentId&&!S){S=!0;for(const M of t)Lr(e.address,s,Ye(M.asset.address));e.startStatusPolling(I.intentId,b)}},void 0,{userOverride:e.address,useCustomTransfers:!0,skipPreSubmitFeeEstimate:!0,skipUserFundingPreflight:!0});if(e.refreshAssets(),e.onDepositExecute&&m.amount)try{e.setPostDepositStatus("executing"),await e.onDepositExecute(h||m.amount),e.setPostDepositStatus("success"),e.setPostDepositAmount(h||m.amount),e.setPostDepositSuccess(!0)}catch(I){console.error("ctx.onDepositExecute failed (7702):",I),e.setPostDepositStatus("error"),e.setPostDepositError(I?.message||"Post-deposit instruction failed");return}const E={type:"deposit",status:"success",amount:m===n&&h||m.amount,asset:m.asset.symbol,sourceChain:gn(s),txHash:/^0x[0-9a-f]{64}$/i.test(T??"")?T:void 0};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:E})),e.onDepositSuccess?.(E),e.onDepositSelect&&e.onDepositSelect(m.asset)}}catch(s){o=!0,console.error("[DepositModal] executeDeposit CAUGHT ERROR:",s),console.error("[DepositModal] Error details:",{message:s?.message,code:s?.code,name:s?.name,stack:s?.stack?.slice(0,500)}),e.setError(Mn(s,"Deposit failed")),e.clearStatus()}finally{e.setIsExecuting(!1),o&&e.setDirectDepositStatus("idle"),o||!e.getCurrentIntentStatus()&&e.getCurrentPostDepositStatus()!=="idle"||e.setShowConfirmation(!1)}}async function ip(e){const{asset:t,assetIndex:n,selectedAssetCount:o,address:s,escrowOnly:r,isNon7702:a}=e;if(n!==0||a||o>1||!s||t.balance<=0n)return null;if(!r&&!no(t))return No(t.balance,t.decimals);const i=await gl({address:s,depositQuote:{asset:t,amount:t.balance,token:Ye(t.address),chainId:t.chainId},escrowOnly:r}),l=r?t.balance:t.balance>i.fee?t.balance-i.fee:0n;return No(l,t.decimals)}async function gl(e){const{address:t,depositQuote:n,escrowOnly:o}=e,{asset:s,amount:r,token:a,chainId:i}=n,l=Jn(i),c=s.isNative||be(a),d=r>1n?1n:0n,p=[c?{to:l,value:r,data:"0x"}:{to:a,value:0n,data:xt({abi:tt,functionName:"transfer",args:[l,r]})}];d>0n&&p.push(c?{to:nn,value:d,data:"0x"}:{to:a,value:0n,data:xt({abi:tt,functionName:"transfer",args:[nn,d]})});const f={chainId:i,tokenTransfers:[],calls:p},h=(await Lt.estimateBatchGas({user:t,outputToken:a,chainBatches:[{...f,hash:$n([f])[0].hash}],signal:e.signal})).gasFee,m=o&&h<r?r-h:r;return{fee:h,net:m,quotedAmount:r,token:a,chainId:i}}function lp(e,t=40,n=18){const o=e.length,s=[{maxLength:7,shrink:0},{maxLength:10,shrink:6},{maxLength:13,shrink:12},{maxLength:16,shrink:16},{maxLength:20,shrink:19}].find(r=>o<=r.maxLength);return Math.max(n,t-(s?.shrink??22))}const fo=({value:e,element:t="span",placeholder:n,ariaLabel:o,ariaInvalid:s,disabled:r,onChange:a,inputMode:i="decimal",autoComplete:l="off",dataSpiceflowFocus:c,fontFamily:d,fontWeight:p=700,color:f,textAlign:h,lineHeight:m=1,maxFontSize:g=40,minFontSize:y=18,overflow:w="ellipsis",title:x,style:v})=>{const k=lp(e||n||"",g,y),A=w==="wrap"?{overflowWrap:"anywhere",wordBreak:"break-word",whiteSpace:"normal"}:w==="ellipsis"?{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}:{},b={fontFamily:d,fontSize:`${k}px`,fontWeight:p,color:f,lineHeight:m,letterSpacing:0,textAlign:h,minWidth:0,maxWidth:"100%",...A,...v};return t==="input"?u("input",{type:"text",inputMode:i,autoComplete:l,"aria-label":o,"aria-invalid":s||void 0,"data-spiceflow-focus":c||void 0,value:e,onChange:a,placeholder:n,disabled:r,title:x,style:{backgroundColor:"transparent",border:"none",outline:"none",padding:0,width:"100%",...b}}):u(t,{title:x,style:b,children:e})},Jr=({pct:e,isMax:t,primaryColor:n,dark:o,fillColor:s})=>{const r=e/100;return C("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[u("circle",{cx:"7",cy:"7",r:"6.84375",fill:t?n:"none",stroke:t?n:o?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!t&&r>0&&u("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${r>.5?1:0} 1 ${7+6.84375*Math.sin(r*2*Math.PI)} ${7-6.84375*Math.cos(r*2*Math.PI)} Z`,fill:s})]})},yl=({chainId:e,name:t,size:n=16})=>{const o=e&&(to[e]||Wa(e)?.logo)||"";return o?u("img",{src:o,alt:t||`Chain ${e}`,loading:"lazy",decoding:"async",width:n,height:n,style:{width:`${n}px`,height:`${n}px`,borderRadius:"50%",objectFit:"cover",flexShrink:0}}):null},cp={1:"ethereum",56:"binance-smart-chain",137:"polygon-pos",143:"monad",4114:"citrea",4663:"robinhood",8453:"base",42161:"arbitrum-one"},dp=6e4,$o=new Map;function xl(e,t){return $o.get(e)?.logos?.get(t.toLowerCase())}function up(e,t){const n=cp[e];if(!n||be(t))return;const o=$o.get(e);if(o?.logos||o?.pending)return o.pending;if(o?.failedAt!==void 0&&Date.now()-o.failedAt<dp)return;const s=Promise.resolve().then(async()=>{try{const r=await fetch(`https://tokens.coingecko.com/${n}/all.json`,{signal:AbortSignal.timeout(1e4)});if(!r.ok)throw new Error("Token list request failed");const a=await r.json(),i=new Map;for(const l of a?.tokens??[])l?.address&&l?.logoURI&&i.set(String(l.address).toLowerCase(),l.logoURI);$o.set(e,{logos:i})}catch(r){console.warn(`[tokenLogos] Token list unavailable for chain ${e}`,r),$o.set(e,{failedAt:Date.now()})}});return $o.set(e,{...o,pending:s}),s}function wl(e,t,n){const[o,s]=O(),r=e||e===null||t===void 0||!n?void 0:`${t}:${n.toLowerCase()}`,a=r?xl(t,n):void 0;return ae(()=>{if(!r||a||t===void 0||!n)return;let i=!0;const l=()=>{const d=xl(t,n);i&&d&&s({token:r,logo:d})},c=up(t,n);return c?c.then(l):l(),()=>{i=!1}},[r,a,t,n]),e||a||(o&&o.token===r?o.logo:void 0)}const Us=({symbol:e,label:t,logoURI:n,chainId:o,address:s,size:r=20,theme:a})=>{const{theme:i}=Bt(),l=a||i,[c,d]=O(),p={width:`${r}px`,height:`${r}px`,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:`${r*.4}px`,fontWeight:l.typography.fontWeight.bold,flexShrink:0,overflow:"hidden",backgroundColor:"#ffffff"},f=wl(n===null?null:n||Or[e.toUpperCase()],o,s);if(n===null)return null;if(f&&f!==c)return u("img",{src:f,alt:t??e,loading:"lazy",decoding:"async",style:{...p,objectFit:"cover"},onError:()=>d(f)});const h=pp(e);return u("div",{style:{...p,...h.style},children:h.icon})},pp=e=>{const t=e.toUpperCase(),n={ETH:{bg:"#627EEA",text:"#FFFFFF",icon:"\u039E"},BTC:{bg:"#F7931A",text:"#FFFFFF",icon:"\u20BF"},USDC:{bg:"#2775CA",text:"#FFFFFF"},USDT:{bg:"#26A17B",text:"#FFFFFF"},DAI:{bg:"#F5AC37",text:"#FFFFFF"},WETH:{bg:"#627EEA",text:"#FFFFFF",icon:"\u039E"},WBTC:{bg:"#F09242",text:"#FFFFFF",icon:"\u20BF"},CBTC:{bg:"#F7931A",text:"#FFFFFF",icon:"\u20BF"},USD:{bg:"#26A17B",text:"#FFFFFF",icon:"$"},MATIC:{bg:"#8247E5",text:"#FFFFFF"},AVAX:{bg:"#E84142",text:"#FFFFFF"},SOL:{bg:"#9945FF",text:"#FFFFFF"},DOT:{bg:"#E6007A",text:"#FFFFFF"},ADA:{bg:"#0033AD",text:"#FFFFFF"},LINK:{bg:"#375BD2",text:"#FFFFFF"},UNI:{bg:"#FF007A",text:"#FFFFFF"},AAVE:{bg:"#B6509E",text:"#FFFFFF"},CRV:{bg:"#40E0D0",text:"#000000"}}[t];if(n)return{style:{backgroundColor:n.bg,color:n.text},icon:n.icon||t.charAt(0)};const o=t.split("").reduce((i,l)=>l.charCodeAt(0)+((i<<5)-i),0),s=Math.abs(o)%360,r=`hsl(${s}, 60%, 50%)`,a=s>180?"#FFFFFF":"#000000";return{style:{backgroundColor:r,color:a},icon:t.charAt(0)}},fp=({selectedAsset:e,assets:t,onAssetSelect:n,showDropdown:o,onToggleDropdown:s,disabled:r=!1,theme:a,onViewAllAssets:i})=>{const l=Rn(),{theme:c}=Bt(),d=a||c,p=_(null),f=_(null),h=_(null),[m,g]=O(null);ae(()=>{if(o&&f.current){const R=()=>{if(f.current){const F=f.current.getBoundingClientRect();g({top:F.bottom+6,right:window.innerWidth-F.right})}};return R(),window.addEventListener("scroll",R,!0),window.addEventListener("resize",R),()=>{window.removeEventListener("scroll",R,!0),window.removeEventListener("resize",R)}}else g(null)},[o]),ae(()=>{const R=F=>{p.current&&!p.current.contains(F.target)&&h.current&&!h.current.contains(F.target)&&o&&s()};return o&&document.addEventListener("mousedown",R),()=>{document.removeEventListener("mousedown",R)}},[o,s]);const[y,w]=O(!1),x=d.mode==="light",v={backgroundColor:"transparent",border:`1px solid ${x?"#aaaaaa":d.colors.border}`,borderRadius:"6px",color:d.colors.text,cursor:r?"not-allowed":"pointer",padding:"8px 14px 8px 10px",width:"100%",display:"flex",flexDirection:"column",gap:"4px",opacity:r?.6:1,transition:In.interactive,transform:y?"scale(0.98)":"scale(1)"},k={display:"flex",justifyContent:"space-between",alignItems:"center",gap:"10px",minWidth:0},A={display:"flex",alignItems:"center",gap:"4px",paddingTop:"4px",borderTop:`1px solid ${d.colors.border}`},b=()=>m?{position:"fixed",top:`${m.top}px`,right:`${m.right}px`,backgroundColor:d.colors.secondary,border:`1px solid ${d.colors.border}`,borderRadius:d.borderRadius.md,boxShadow:d.shadows.lg,zIndex:ao.dropdown,width:"200px",maxHeight:"300px",overflow:"auto"}:{},S={backgroundColor:"transparent",border:"none",color:d.colors.text,cursor:"pointer",padding:d.spacing.sm,width:"100%",display:"flex",alignItems:"center",gap:d.spacing.sm,transition:`background-color ${d.animation.normal}`,":hover":{backgroundColor:d.colors.surfaceHover}},T={display:"flex",flexDirection:"column",alignItems:"flex-start",flex:1},E={fontSize:d.typography.fontSize.sm,fontWeight:d.typography.fontWeight.medium},I={fontSize:d.typography.fontSize.xs,color:d.colors.textMuted},M={backgroundColor:"transparent",border:"none",borderTop:`1px solid ${d.colors.border}`,color:d.colors.primary,cursor:"pointer",padding:"10px 12px",width:"100%",display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",fontFamily:d.typography.fontFamily,fontSize:d.typography.fontSize.xs,fontWeight:d.typography.fontWeight.medium,textDecoration:"underline",textUnderlineOffset:"2px"},W={transition:`transform ${d.animation.normal}`,transform:o?"rotate(180deg)":"rotate(0deg)",flexShrink:0};return C(an,{children:[u("div",{style:{position:"relative"},ref:p,children:C("div",{ref:f,style:v,onClick:r?void 0:s,onMouseLeave:()=>{w(!1)},onMouseDown:()=>w(!0),onMouseUp:()=>w(!1),children:[C("div",{style:k,children:[u("div",{style:{display:"flex",alignItems:"center",gap:"8px",flex:1,minWidth:0},children:e?.asset?C(an,{children:[u(Us,{symbol:e.asset.symbol,label:l(e.asset).symbol,logoURI:l(e.asset).logoURI,chainId:e.asset.chainId,address:e.asset.address,theme:d,size:24}),u("span",{style:{fontSize:"15px",fontWeight:500,color:d.colors.text,lineHeight:"1.5",flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:l(e.asset).symbol})]}):u("span",{style:{fontSize:"14px",color:d.colors.textMuted},children:"Select"})}),u("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:x?d.colors.textMuted:"#c7ccd4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:W,children:u("path",{d:"M6 9l6 6 6-6"})})]}),e?.asset&&C("div",{style:A,children:[!e.asset.displayChainName&&u(yl,{chainId:e.asset.chainId,theme:d}),u("span",{style:{fontSize:"11px",color:d.colors.textMuted},children:or(e.asset)})]})]})}),o&&m&&fr(C("div",{ref:h,style:b(),children:[t.length===0&&u("div",{style:{padding:"10px 12px",color:d.colors.textMuted,fontSize:d.typography.fontSize.xs},children:"No assets available"}),t.map(R=>C("button",{style:S,onClick:()=>{n(R),s()},children:[u(Us,{symbol:R.symbol,label:l(R).symbol,logoURI:l(R).logoURI,chainId:R.chainId,address:R.address,theme:d},nt(R)),C("div",{style:T,children:[C("div",{style:{display:"flex",alignItems:"center",gap:d.spacing.xs},children:[u("span",{style:E,children:l(R).symbol}),!R.displayChainName&&u(yl,{chainId:R.chainId,theme:d})]}),C("span",{style:I,children:[cs(R)," \u2022"," ",or(R)]})]})]},nt(R))),i&&C("button",{type:"button",style:M,onClick:()=>{s(),i()},children:[u("span",{children:"View all assets"}),C("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[u("path",{d:"M5 12h14"}),u("path",{d:"M13 5l7 7-7 7"})]})]})]}),document.body)]})},mp=({assets:e,selectedAsset:t,onAssetSelect:n,onAmountChange:o,disabled:s=!1,loading:r=!1,label:a="Select Asset",showBalance:i=!0,showMaxButton:l=!0,placeholder:c="0.0",theme:d,styles:p,maxAmount:f,resolveMaxAmount:h,hideAmountInput:m=!1,displayAmount:g,dark:y,onViewAllAssets:w})=>{const x=Rn(),{theme:v,primaryColor:k,dark:A,dk:b}=Bt(p,y),S=d||v,T=y??A,[E,I]=O(!1),[M,W]=O(null),[R,F]=O(null),[N,D]=O(!1),[L,z]=O(null),[fe,ce]=O(t?.amount||""),Q=_(h),ne=t?.asset?nt(t.asset):"",re=_(ne);re.current=ne;const j=!!h,J=L??f;ae(()=>{Q.current=h},[h]),ae(()=>{ce(t?.amount||"")},[ne,t?.amount]),ae(()=>{z(null),D(!1)},[ne,j,t?.asset?.balance]);const Y=()=>{const G=t?.asset;if(!G)return 0n;if(!J)return G.balance;const P=mn(J,G.decimals);return P<G.balance?P:G.balance},me=G=>{ce(G),o?.(G)},B=G=>{const P=t?.asset,V=ds(G.startsWith(".")?`0${G}`:G,P?.decimals);if(!P||!V)return me(V);const ie=mn(V,P.decimals),ke=Y();me(ie>ke?Fe(ke,P.decimals):V)},U=async()=>{const G=t?.asset;if(!G||s)return;const P=ne,V=Q.current;if(L)return me(L);if(V){D(!0);try{const ie=await V(G);if(re.current!==P)return;if(ie!==null){const ke=ds(ie,G.decimals);z(ke),me(ke);return}return}catch(ie){console.warn("[AssetSelector] Failed to resolve max amount:",ie);return}finally{re.current===P&&D(!1)}}re.current===P&&me(Fe(Y(),G.decimals))},X=async G=>{if(!(!t||s)){if(G===100)return U();me(Fe(Y()*BigInt(G)/100n,t.asset.decimals))}},pe=t?.asset?.balanceFormatted??0,de=parseFloat(fe)||0,xe=pe>0?de/pe*100:0,K={backgroundColor:p?.assetSelector?.backgroundColor||p?.secondaryBackground||(T?b.cardBg:"#e9e9e9"),border:T?`0.5px solid ${b.cardBorder}`:"0.5px solid #A8A8A7",borderRadius:p?.assetSelector?.borderRadius||"6px",padding:p?.assetSelector?.padding||"16px",height:"auto",minHeight:m?void 0:"144px",display:"flex",flexDirection:"column",gap:"8px",position:"relative",opacity:s?.6:1};return r?u("div",{style:K,children:C("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"space-between"},children:[C("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[u("div",{style:{backgroundColor:T?b.hoverBg:"#d1d5db",borderRadius:"4px",height:"16px",width:"60px"}}),u("div",{style:{backgroundColor:T?b.hoverBg:"#d1d5db",borderRadius:"4px",height:"40px",width:"150px"}})]}),C("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:"8px"},children:[u("div",{style:{backgroundColor:T?b.hoverBg:"#d1d5db",borderRadius:"4px",height:"12px",width:"80px"}}),u("div",{style:{backgroundColor:T?b.hoverBg:"#d1d5db",borderRadius:"6px",height:"46px",width:"128px"}})]})]})}):C("div",{style:K,children:[C("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[u("span",{style:{fontFamily:p?.fontFamily||S.typography.fontFamily,fontSize:"16px",fontWeight:500,color:T?b.textSecondary:"#7d7c7b",lineHeight:"24px"},children:a}),i&&t?.asset&&C("span",{style:{fontFamily:p?.fontFamily||S.typography.fontFamily,fontSize:"12px",fontWeight:500,color:T?b.textSecondary:"#71757a",lineHeight:"16px"},children:["Balance: ",cs(t.asset)]})]}),C("div",{style:{display:"flex",justifyContent:m&&!g?"flex-start":"space-between",alignItems:"center",flex:1},children:[!m&&u(fo,{element:"input",ariaLabel:t?.asset?`${x(t.asset).symbol} amount`:"Amount",dataSpiceflowFocus:!0,value:fe,onChange:G=>B(G.target.value),placeholder:c,disabled:s||!t?.asset,fontFamily:p?.fontFamily||S.typography.fontFamily,color:s?T?"rgba(255, 255, 255, 0.16)":"rgba(14, 13, 11, 0.16)":fe?T?"#ffffff":"#0e0d0b":T?"#4a5568":"#d1d5db",lineHeight:"1.08",maxFontSize:40,minFontSize:22,style:{width:"100%",maxWidth:"200px"}}),u("div",{style:{width:"176px",position:"relative",flexShrink:0},children:u(fp,{selectedAsset:t,assets:e,onAssetSelect:n,showDropdown:E,onToggleDropdown:()=>I(!E),disabled:s,theme:S,onViewAllAssets:w})}),m&&g&&u(fo,{element:"span",value:g,title:g,fontFamily:p?.fontFamily||S.typography.fontFamily,color:T?"#ffffff":"#0e0d0b",lineHeight:"1.08",textAlign:"right",maxFontSize:40,minFontSize:22,style:{flex:1}})]}),!m&&u("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",height:"14px"},children:[0,25,50,75,100].filter(G=>l||G!==100).map((G,P)=>{const V=Math.abs(xe-G)<1,ie=P===4,ke=M===G,Ee=R===G;return u("button",{onClick:()=>X(G),onMouseEnter:()=>W(G),onMouseLeave:()=>{W(null),F(null)},onMouseDown:()=>F(G),onMouseUp:()=>F(null),disabled:s||!t?.asset||G===100&&N,title:`${G}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:s||!t?.asset||G===100&&N?"not-allowed":"pointer",opacity:V?1:ke?.8:.5,transform:Ee?"scale(0.85)":ke?"scale(1.15)":"scale(1)",transition:In.interactive},children:u(Jr,{pct:G,isMax:ie,primaryColor:k,dark:T,fillColor:T?b.textSecondary:"#3C3E42"})},G)})})]})},Fo=yn(mp),hp=({selectedDepositAssets:e,depositAssets:t,secondAssetOptions:n,loadingAssets:o,allowSecondAsset:s,theme:r,styles:a,dark:i,dk:l,onSelect:c,onAmountChange:d,onAdd:p,onRemove:f,resolveMaxAmount:h,onViewAllAssets:m})=>C(an,{children:[e.map((g,y)=>{const w=e.length===1?"Deposit":`Asset ${y+1}`;return C("div",{style:{marginBottom:r.spacing.md,position:"relative"},children:[u(Fo,{assets:y===0?t:n,selectedAsset:g||void 0,onAssetSelect:x=>c(x,y),onAmountChange:x=>d(x,y),loading:o,label:w,showBalance:!0,theme:r,styles:a,allowSecondAsset:s&&y===0,onAddAsset:p,canAddAsset:e.length===1&&!!e[0]?.asset,resolveMaxAmount:h?x=>h(x,y):void 0,onViewAllAssets:y===0?m:void 0}),y===1&&u("button",{onClick:()=>f(y),style:{position:"absolute",top:"-2px",right:"-2px",background:i?`${l.cardBg}ee`:"rgba(255, 255, 255, 0.9)",border:`1px solid ${l.cardBorder}`,borderRadius:"50%",cursor:"pointer",color:r.colors.textMuted,fontSize:"16px",padding:"2px",width:"22px",height:"22px",display:"flex",alignItems:"center",justifyContent:"center",transition:In.interactive,boxShadow:"0 1px 3px rgba(0, 0, 0, 0.1)"},onMouseEnter:x=>{x.currentTarget.style.color=i?l.errorText:"#ef4444",x.currentTarget.style.background=i?l.cardBg:"#fff",x.currentTarget.style.borderColor=i?l.errorBorder:"#fecaca"},onMouseLeave:x=>{x.currentTarget.style.color=r.colors.textMuted,x.currentTarget.style.background=i?`${l.cardBg}ee`:"rgba(255, 255, 255, 0.9)",x.currentTarget.style.borderColor=i?l.cardBorder:"#e5e7eb"},title:"Remove asset",children:"\xD7"})]},`asset-${y}`)}),e.length===0&&u("div",{style:{marginBottom:r.spacing.md},children:u(Fo,{assets:t,selectedAsset:void 0,onAssetSelect:g=>c(g,0),onAmountChange:g=>d(g,0),loading:o,label:"Deposit",showBalance:!0,theme:r,styles:a,allowSecondAsset:s,onAddAsset:p,canAddAsset:!1,resolveMaxAmount:h?g=>h(g,0):void 0},"initial-selector")})]}),gp=yn(hp);function yp(e,t){switch(e){case"success":return{bg:t.successBg,border:t.successBorder,text:t.successText};case"warning":return{bg:t.warningBg,border:t.warningBorder,text:t.warningText};case"error":return{bg:t.errorBg,border:t.errorBorder,text:t.errorText};case"info":return{bg:t.infoBg,border:t.infoBorder,text:t.infoText}}}const Nn=({variant:e,palette:t,children:n,icon:o,style:s,fontFamily:r,size:a="default"})=>{const i=yp(e,t),l=a==="compact";return C("div",{role:e==="error"?"alert":"status",style:{backgroundColor:i.bg,border:`1px solid ${i.border}`,borderRadius:l?"7px":"8px",padding:l?"8px 10px":"12px 16px",color:i.text,fontSize:l?"12px":"13px",lineHeight:l?1.4:1.5,display:"flex",alignItems:"flex-start",gap:l?"6px":"8px",fontFamily:r,...s},children:[o&&u("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:o}),u("span",{style:{minWidth:0,overflowWrap:"anywhere"},children:n})]})},bl=Oe.mono,oo=({label:e,value:t,palette:n,valueColor:o,labelColor:s,style:r})=>C("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",...r},children:[u("span",{style:{fontSize:"12px",color:s??n.textSecondary,fontFamily:bl,fontWeight:500,letterSpacing:"0.03em",flexShrink:0,whiteSpace:"nowrap"},children:e}),u("span",{style:{fontSize:"13px",color:o??n.textPrimary,fontWeight:500,fontFamily:bl,minWidth:0,textAlign:"right",overflowWrap:"anywhere"},children:t})]}),$r=({onClick:e,label:t="Add Funds",color:n,fontFamily:o,style:s})=>{const[r,a]=O(!1);return C("button",{type:"button",onClick:e,"data-spiceflow-focus":!0,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),style:{background:"none",border:"none",cursor:"pointer",padding:0,display:"inline-flex",alignItems:"center",gap:"4px",color:n,fontSize:"12px",fontWeight:500,fontFamily:o,textDecoration:"underline",textUnderlineOffset:"2px",whiteSpace:"nowrap",opacity:r?.75:1,transition:"opacity 150ms ease",...s},children:[t,C("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.8","aria-hidden":"true",children:[u("circle",{cx:"6",cy:"6",r:"5"}),u("path",{d:"M6 4v4M4 6h4",strokeLinecap:"round"})]})]})},_r=({value:e,onChange:t,ariaLabel:n,placeholder:o,endAdornment:s,size:r="lg",dark:a,styles:i,inputRef:l,autoFocus:c})=>{const{dark:d,dk:p}=Bt(i,a),f=a??d,h=r==="lg",m=h?"15px":"14px",g=h?"7px":"10px",y=h?sr.input:sr.sm,w=i?.fontFamily||Oe.ui,x=f?p.inputBg:"#FAFAFA",v=f?p.inputBorder:"#e5e7eb",k=f?p.textPrimary:"#374151",A=f?p.textSecondary:"#9ca3af";return C("div",{style:{display:"flex",alignItems:"center",gap:"8px",backgroundColor:x,borderRadius:y,boxShadow:f?"0 2px 4px rgba(0, 0, 0, 0.3)":"0 2px 4px rgba(0, 0, 0, 0.1)",padding:`${g} 5px`,border:`1px solid ${v}`},children:[u(Ju,{style:{color:A},size:24}),u("input",{ref:l,type:"text",role:"searchbox","aria-label":n,autoComplete:"off",spellCheck:!1,autoFocus:c,"data-spiceflow-focus":!0,placeholder:o,value:e,onChange:b=>t(b.target.value),style:{flex:1,backgroundColor:x,outline:"none",border:"none",color:k,fontSize:m,fontWeight:400,fontFamily:w}}),s]})},xp="This deposit didn't confirm in time. It may still have gone through, so check the explorer and refresh your balance before retrying.";function wp(e){return e?.overallStatus!=="failed"?{isFailed:!1,failureMessage:null}:{isFailed:!0,failureMessage:e.steps?.find(t=>t.status==="failed"&&!!t.error)?.error||xp}}const Ls=C("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",style:{flexShrink:0},children:[u("circle",{cx:"10",cy:"10",r:"10",fill:"#10b981"}),u("path",{d:"M6 10l3 3 5-6",stroke:"#ffffff",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),bp=({isOpen:e,onClose:t,onConfirm:n,data:o,isExecuting:s=!1,error:r=null,theme:a,styles:i,intentStatus:l,postDepositStatus:c="idle",hasPostDepositInstruction:d=!1})=>{const{dark:p,dk:f,theme:h}=Bt(i),[m,g]=O(!1),[y,w]=O(!0);ae(()=>{e||g(!1)},[e]);const x=()=>{g(!0),setTimeout(()=>{t()},300)},v=()=>{w(!y)};if(!e||!o)return null;const k=l?.overallStatus==="processing",A=l?.overallStatus==="success",b=!!l,{isFailed:S,failureMessage:T}=wp(l),E=!b&&d,I=E&&c==="executing",M=E&&c==="success",W=A&&d&&(c==="idle"||c==="executing")||I,R=A&&(!d||c==="success"||c==="error")||M||E&&c==="error",F=p?f.cardBg:"#ffffff",N=p?"0 -4px 20px rgba(0, 0, 0, 0.4)":"0 -4px 20px rgba(0, 0, 0, 0.15)",D=f.textSecondary,L=p?f.textPrimary:"#1f2937",z=p?f.textPrimary:"#1f2937",fe=ne=>u("div",{style:{marginBottom:a.spacing.md,padding:a.spacing.md,backgroundColor:i?.errorMessage?.backgroundColor||(a.mode==="light"?"#fef2f2":`${a.colors.error}20`),border:`1px solid ${i?.errorMessage?.borderColor||(a.mode==="light"?"#fecaca":a.colors.error)}`,borderRadius:i?.errorMessage?.borderRadius||a.borderRadius.md},children:u("p",{style:{color:i?.errorMessage?.color||a.colors.error,fontSize:i?.errorMessage?.fontSize||a.typography.fontSize.sm,margin:0,fontFamily:i?.errorMessage?.fontFamily||i?.fontFamily||a.typography.fontFamily},children:ne})}),ce={fontSize:a.typography.fontSize.sm,fontWeight:500,color:D,fontFamily:Oe.mono,letterSpacing:"0.5px"},Q=(ne,re,j=L)=>C("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[u("span",{style:ce,children:ne}),u("span",{style:{fontSize:a.typography.fontSize.sm,fontWeight:500,color:j,fontFamily:Oe.mono},children:re})]});return C("div",{style:{position:"absolute",bottom:0,left:0,right:0,zIndex:10,animation:m?"slideDown 0.3s ease-in":"slideUp 0.3s ease-out",pointerEvents:"auto"},children:[C("div",{style:{backgroundColor:F,borderRadius:"0",width:"100%",maxWidth:"522px",margin:"0 auto",padding:"18px 24px",boxShadow:N},children:[!A&&!M&&C(an,{children:[C("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:a.spacing.md},children:[C("div",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:"pointer"},onClick:v,children:[u("span",{style:{fontSize:"13px",fontWeight:a.typography.fontWeight.medium,color:D,fontFamily:i?.fontFamily||a.typography.fontFamily},children:"Transaction Details"}),u(Eo,{color:D,direction:y?"up":"down"})]}),u("button",{onClick:ne=>{ne.stopPropagation(),t()},style:{background:"none",border:"none",cursor:"pointer",padding:"4px",display:"flex",alignItems:"center",justifyContent:"center",color:D,transition:"color 0.2s ease"},onMouseEnter:ne=>{ne.currentTarget.style.color=z},onMouseLeave:ne=>{ne.currentTarget.style.color=D},children:u(Jo,{size:16})})]}),C("div",{style:{marginBottom:a.spacing.lg,display:"flex",flexDirection:"column",gap:a.spacing.md,overflow:"hidden",maxHeight:y?"200px":"0px",opacity:y?1:0,transition:"max-height 0.3s ease, opacity 0.3s ease"},children:[Q("NETWORK",o.network),Q("DEPOSITED AMOUNT",o.amount,a.colors.success),o.creditedAmount&&Q("CREDITED AMOUNT",o.creditedAmount),o.spicenetFee&&Q("SPICENET FEE",o.spicenetFee),o.networkFee&&Q("EST. NETWORK FEE",o.networkFee)]})]}),r&&!b&&fe(r),S&&T&&fe(T),u(Et,{onClick:R||S?x:n,variant:"outline",fullWidth:!0,disabled:s||k||W||I,styles:i,theme:h,children:s||k||I||W?"PROCESSING...":R?"CONTINUE \u2192":S?"CLOSE":"CONFIRM DEPOSIT"}),R&&u("p",{style:{marginTop:a.spacing.md,marginBottom:0,fontSize:"14px",color:D,textAlign:"center",fontFamily:i?.fontFamily||a.typography.fontFamily},children:"Your funds are now available in your Account"}),u("div",{style:{marginTop:a.spacing.md,display:"flex",justifyContent:"center",alignItems:"center"},children:u("img",{src:il,alt:"Powered by SpiceNet",style:{height:"auto",width:"130px",opacity:1,filter:p?"brightness(0) invert(1) opacity(0.7)":"none"}})})]}),u("style",{children:`
4
4
  @keyframes slideUp {
5
5
  from {
6
6
  transform: translateY(100%);
@@ -28,7 +28,7 @@ import{jsxs as C,jsx as u,Fragment as an}from"react/jsx-runtime";import{g as Ge,
28
28
  transform: translateY(0);
29
29
  }
30
30
  }
31
- `})]})},vl=En.memo(({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,onDepositSelect:o,depositBatches:s,supportedChains:r,title:a,styles:i,onDepositAssetChange:l,assetInputHook:c,externalWalletAddress:d,onDepositAmountChange:p,allowSecondAsset:f=!1,destinationChainId:h,destinationTokenAddress:m,onDepositExecute:g,depositActionLabel:y,nativeChainId:w,sponsorGas:x=!1,preSelectedAsset:v,escrowOnly:k=!1,escrowTokenAddress:A,escrowAmount:b,escrowTokenDecimals:S,escrowTokenSymbol:T,onSubmit:E,onDepositSuccess:I,onDepositError:M,embeddedWalletAddress:W,onViewAllAssets:R})=>{const F=Qt(Mt),N=F?.mode||"7702",D=F?.allowedTokens,L=!!F?.isWhitelistGateActive,z=!k&&!!F?.isWhitelistConfigured&&F?.isUserWhitelisted!==!0,fe=c?.assetAmount||"",{theme:ce,dark:Q,appName:ne,primaryColor:re,dk:j}=Bt(i),J=Zn(),{isReady:Y,isAuthenticated:me}=J,{externalWallet:B}=ps(),U=F?.embeddedWalletAddress||W,X=N!="7702",pe=X?!!d:Y&&me&&!!U,de=U,xe=d,K=de??xe,G=Rn(),{data:P}=td(),[V,ie]=En.useState(P),ke=En.useRef(null),Ee=En.useRef(B);Ee.current=B;const Be=B?.address;En.useEffect(()=>{const H=Ee.current;if(!H||!xe){ke.current=null,ie(P);return}if(H.address?.toLowerCase()!==xe?.toLowerCase()){ke.current=null,ie(P);return}H.getEthereumProvider().then(async we=>{ke.current=we;const He=await we.request({method:"eth_chainId"}),Se=parseInt(He,16),mt=Ge(Se),rt=await H.getWalletClient(Se);ie(mt?cr({account:xe,chain:mt.viemChain,transport:dr(we)}):rt)}).catch(()=>{ke.current=null,ie(P)})},[Be,xe,P]);const Ie=En.useRef(null),[Z,ot]=O([]),{assets:qe,loading:Ct,error:ht,refreshAssets:Ve}=Ko({address:k?de:xe||de,supportedChains:r,fetchBalances:So,enabled:e,refreshInterval:e?5e3:0}),Qe=ue(()=>qe.filter(H=>H.balance>0n&&po(H,"deposit-source",{allowedTokens:D,rpcOverrides:F?.rpcOverrides,liquidityVenues:F?.liquidityVenues,isWhitelistGateActive:L},void 0,void 0,{requiresEscrow:X||k}).eligible).sort((H,we)=>we.balanceUsd-H.balanceUsd),[qe,D,F?.rpcOverrides,L,X,k]),at=ue(()=>{if(!Z[0]?.asset)return[];const H=Z[0].asset.chainId;return Qe.filter(we=>we.chainId===H)},[Qe,Z]),[je,Dt]=O(!1),[Ke,gt]=O(null),De=_(M);De.current=M;const et=te(H=>{gt(H),typeof H=="string"&&H&&De.current?.(H,fs(H))},[]),[Le,ct]=O("idle"),$e=te(H=>{typeof H=="string"&&H&&De.current?.(H,fs(H))},[]),[dt,kt]=O(!1),[ut,Re]=O(null),[ft,Ot]=O("idle"),[Me,$]=O(null),[ee,ze]=O(null),[Ce,le]=O(null),[Pe,Ae]=O(null),[q,Ze]=O(null),{intentStatus:ye,startStatusPolling:Xe,clearStatus:Ht,execute:qt}=Ms(),Te=te((H,we)=>{const He=ls[we];return He?He.supportedTokens?.find(Se=>ge(Se.address,H))?.symbol??null:null},[]),Wt=ue(()=>{const H=Z[0]?.asset;if(!H||!m||!h)return!1;const we=Te(m,h);return wu(H.symbol)&&!!we&&bu(we)},[Z,m,h,Te]);ae(()=>{Z.length>0&&fe!==Z[0]?.amount&&ot(H=>{if(H.length===0)return H;const we=[...H];return we[0]={...we[0],amount:fe||""},we})},[fe]),ae(()=>{Z.length!==0&&ot(H=>{let we=!1;const He=H.map(Se=>{if(!Se.asset)return Se;const mt=Qe.find(rt=>rt.chainId===Se.asset.chainId&&ge(rt.address,Se.asset.address));return mt?mt===Se.asset||mt.balance===Se.asset.balance?Se:(we=!0,{...Se,asset:mt,amount:Se.amount}):Se});return we?He:H})},[Qe,Z.length]),ae(()=>{if(!v||Z.length>0||Qe.length===0)return;const H=Qe.find(we=>we.chainId===v.chainId&&ge(we.address,v.address));H&&(ot([{asset:H,amount:""}]),l?.(H))},[v,Qe,Z.length]);const Nt=En.useRef(null);ae(()=>{if(X&&ye?.overallStatus==="success"&&g&&Le==="idle"){const H=Nt.current,we=Ie.current;H&&(async()=>{try{ct("executing"),await g(H),ct("success"),Re(H),kt(!0);const He=Array.isArray(we)?we[0]:void 0,Se={type:"deposit",status:"success",amount:H,asset:He?.tokenAddress,sourceChain:He?String(He.chainId):void 0,txHash:He?.txHash};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:Se})),I?.(Se)}catch(He){console.error("onDepositExecute failed:",He),ct("error"),$e(Mn(He,"Post-deposit instruction failed"))}finally{Nt.current=null,Ie.current=null}})()}},[ye?.overallStatus,X,Le]);const wt=te(()=>{et(null)},[]);ae(()=>{e||(kt(!1),Re(null),Ot("idle"),$(null),ze(null))},[e]);const On=te((H,we)=>{ot(He=>{const Se=[...He];return Se[we]={asset:H,amount:Se[we]?.amount||""},Se}),we===0&&l?.(H),wt()},[l,wt]),Gn=te(async(H,we)=>{if(ot(He=>{const Se=[...He];return Se[we]&&(Se[we]={...Se[we],amount:H}),Se}),wt(),we===0)if(c?.setAssetAmount(H),Wt&&H&&parseFloat(H)>0)try{const He=Ce??await xu();Ce||le(He);const Se=Z[0]?.asset;if(!Se)return;const mt=mn(H,Se.decimals),rt=m?Te(m,h):null,Kn=ls[h]?.supportedTokens?.find(Xs=>ge(Xs.address,m))?.decimals??6,Ro=vu(mt,Se.decimals,Kn,He);Ae(Ro);const Mo=Fe(Ro,Kn),Zs=He.toLocaleString("en-US",{maximumFractionDigits:0});Ze(`${H} ${Se.symbol} \u2248 $${parseFloat(Mo).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})} ${rt??"USD"} (rate: $${Zs}/BTC)`),p?.(Mo)}catch(He){console.error("Failed to fetch BTC/USD price:",He),Ze(null),Ae(null),p?.(H)}else Ze(null),Ae(null),p?.(H)},[wt,c,p,Wt,Ce,Z,m,h,Te]),wn=te(()=>{Z.length<2&&ot(H=>[...H,{asset:null,amount:""}])},[Z.length]),Pn=te(H=>{ot(we=>we.filter((He,Se)=>Se!==H)),wt()},[wt]),bn=_(!1),jt=_(!1);ae(()=>{e||(bn.current=!1,jt.current=!1,st(null),$t(null))},[e]);const[Kt,ln]=O(!1),[Jt,Zt]=O(null),[on,st]=O(null),[Je,$t]=O(null),[vn,_t]=O(!1),[Ue,cn]=O(null),We=ue(()=>{const H=Z[0];if(Z.length!==1||!H?.asset||!H.amount||parseFloat(H.amount)<=0)return null;try{return{asset:H.asset,amount:mn(H.amount,H.asset.decimals),token:Ye(H.asset.address),chainId:H.asset.chainId}}catch{return null}},[Z]),en=!X&&!k&&!!We&&!no(We.asset),It=ue(()=>We?[We.chainId,We.token.toLowerCase(),We.amount.toString(),k?"escrow":"normal"].join("|"):null,[We,k]),pt=te(async(H,we)=>de?gl({address:de,depositQuote:H,escrowOnly:k,signal:we}):null,[de,k]),Un=te(async H=>We?pt(We,H):null,[We,pt]),hn=_(Un);hn.current=Un,Hr({shouldRun:e&&!X&&!en&&!!It&&!Kt&&!je,deps:[e,X,en,It,Kt,je],delayMs:500,backgroundIntervalMs:1e4,onSkip:()=>{st(null),cn(null),_t(!1)},onCleanup:()=>_t(!1),run:async({isBackground:H,isCurrent:we,signal:He})=>{H||(cn(null),_t(!0));try{const Se=await hn.current(He);we()&&st(Se)}catch(Se){if(!we())return;st(null),cn(Se instanceof Error?Se.message:"Failed to estimate gas fee")}finally{we()&&_t(!1)}}}),ae(()=>{Kt||je||$t(null)},[Kt,je,It]);const Oo=async()=>{if(Z.length===0||!Z[0]?.asset)return;const H=Z.filter(rt=>rt.asset&&rt.amount&&parseFloat(rt.amount)>0);if(H.length===0)return;const we=H[0],He=Ge(we.asset.chainId),Se=H.map(rt=>{const Kn=parseFloat(rt.amount);return`${isNaN(Kn)?rt.amount:Kn.toPrecision(6).replace(/\.?0+$/,"")} ${rt.asset.symbol}`}).join(", "),mt={network:He?.displayName||`Chain ${we.asset.chainId}`,amount:Se,symbol:"",chainId:we.asset.chainId};if(!X&&H.length===1&&on){$t(on);const rt=H[0];mt.creditedAmount=`${Fe(on.net,rt.asset.decimals)} ${no(rt.asset)?G({...rt.asset,location:"rollup",_source:"spice",receiptTokenName:"spiceUSDC"}).symbol:rt.asset.symbol}`,mt.networkFee=`${Fe(on.fee,rt.asset.decimals)} ${rt.asset.symbol}`}Zt(mt),ln(!0)},se=_(ye);se.current=ye;const he=_(Le);he.current=Le;const ve=async()=>{await ap({selectedDepositAssets:Z,escrowOnly:k,sourceAddress:xe,isNon7702:X,address:de,embeddedWalletAddress:U,isReady:Y,isAuthenticated:me,zeroCreditError:_e,depositBalanceError:rn,externalWalletClient:V,externalProvider:ke.current,effectiveDepositFee:St,depositBatches:s,destinationChainId:h,destinationTokenAddress:m,isCrossDenomination:Wt,convertedUsdAmount:Pe,mode:N,sponsorGas:x,nativeChainId:w,spiceBalanceUser:K,depositDataRef:Ie,bridgedAmountRef:Nt,setIsExecuting:Dt,setError:et,setConfirmationData:Zt,setShowConfirmation:ln,setDirectDepositStatus:Ot,setDirectDepositChainId:ze,setDirectDepositTxHash:$,setPostDepositStatus:ct,setPostDepositError:$e,setPostDepositAmount:Re,setPostDepositSuccess:kt,startStatusPolling:Xe,clearStatus:Ht,refreshAssets:Ve,onDepositExecute:g,onDepositSelect:o,onDepositSuccess:I,execution:{execute:qt},getCurrentIntentStatus:()=>se.current,getCurrentPostDepositStatus:()=>he.current})},_e=ue(()=>{for(const H of Z)if(!(!H?.asset||!H.amount||parseFloat(H.amount)<=0))try{const we=H.asset.decimals,He=mn(H.amount,we);if(He<=0n)continue;const Se=Ye(H.asset.address),mt=be(Se)?Ft(Se,H.asset.chainId)?.equivalenceGroup:_c(Se),rt=H.asset.receiptTokenDecimals??(mt==="ETH"||mt==="ARB"?18:mt==="USDC"||mt==="SUSD"||mt==="WBTC"||mt==="CBTC"?6:void 0);if(rt===void 0||we<=rt||co(He,we,rt)>0n)continue;return`Amount too small. Minimum deposit for this asset is ${Fe(10n**BigInt(we-rt),we)} ${H.asset.symbol}.`}catch{continue}return null},[Z]),Vt=!X&&!!We&&!en,St=Je??on,sn=!!We&&hl(St,We),rn=ue(()=>{if(!We)return null;if(en)return We.asset.balance>=We.amount?null:`Insufficient ${We.asset.symbol}. Need ${Fe(We.amount,We.asset.decimals)} ${We.asset.symbol}.`;if(!Vt||!sn)return null;const H=k?We.amount:We.amount+St.fee;return We.asset.balance>=H?null:`Insufficient ${We.asset.symbol}. Need ${Fe(H,We.asset.decimals)} ${We.asset.symbol} including gas.`},[Vt,en,We,sn,St,k]),[un,Gt]=O(!1),tn=Z[0]?.asset?.chainId,Pt=qe.find(H=>H.isNative&&H.chainId===tn)?.balance??0n;ae(()=>{if(!e||!tn){Gt(!1);return}let H=!1;return(async()=>{try{const we=await yt(tn).getGasPrice()*150000n;H||Gt(Pt<we)}catch{H||Gt(!1)}})(),()=>{H=!0}},[e,tn,Pt]);const ro=!Vt||sn&&!vn&&!Ue&&!rn,Yt=te((H,we)=>ip({asset:H,assetIndex:we,selectedAssetCount:Z.length,address:de,escrowOnly:k,isNon7702:X}),[X,Z.length,de,k]),Cn=ue(()=>{if(!We||!St||!sn)return null;const H=k?We.amount:We.amount+St.fee;return{symbol:We.asset.symbol,decimals:We.asset.decimals,grossAmount:H,netAmount:St.net,totalFee:St.fee,gasFee:St.fee,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"estimated"}},[We,St,sn,k]),An=parseFloat(Z[0]?.amount||"")||0,kn=Z.length>0&&Z[0]?.asset&&Z[0]?.amount&&An>0&&pe&&!je&&!_e&&!rn&&ro&&!z;ae(()=>{if(!k||!A||!b||bn.current||!pe)return;const H=r[0];if(!H)return;const we=Uc(H,[]).find(Se=>ge(Se.address,A));let He;if(we)He=we;else if(S!==void 0&&T)He={address:A,symbol:T,name:T,decimals:S,chainId:H,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,isNative:be(A)};else{console.warn("[DepositModal] escrowOnly: no matching asset and missing escrowTokenDecimals/escrowTokenSymbol for",A);return}bn.current=!0,ot([{asset:He,amount:b}])},[k,A,b,S,T,pe,r]),ae(()=>{!k||!kn||jt.current||je||(jt.current=!0,ve())},[k,kn,je]);const Yn=ht||Ke||_e||rn,yo=()=>{if(je)return"Executing Deposit...";if(!pe)return"Wallet Not Connected";if(N==="7702"){if(!Y)return"Loading...";if(!me)return"Authentication Required"}return Z[0]?.asset?Z[0]?.amount?_e?"AMOUNT TOO SMALL":rn?"INSUFFICIENT BALANCE":Vt&&!ro?Ue?"GAS UNAVAILABLE":"ESTIMATING GAS":"DEPOSIT":"ENTER AMOUNT":"SELECT TOKEN"};return e?u(Dn,{isOpen:e,onClose:t,closeOnBackdropClick:n,title:a||`Deposit to your ${ne} account`,subtitle:C("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[u("img",{src:zr,alt:"","aria-hidden":"true",style:{width:"13px",height:"13px",flexShrink:0,...Q?{filter:"invert(0.6)"}:{}}}),u("p",{style:{fontSize:"12px",color:j.textSecondary,margin:"0",lineHeight:"1.4",fontFamily:Oe.ui},children:`Deposit collateral to your ${ne} Account from any supported network.`})]}),dark:Q,overlayContent:Kt||ye||Le!=="idle"&&g?u("div",{}):void 0,styles:i,theme:ce,children:C("div",{style:{padding:"24px 24px 5px 24px"},children:[u(gp,{selectedDepositAssets:Z,depositAssets:Qe,secondAssetOptions:at,loadingAssets:Ct,allowSecondAsset:f,theme:ce,styles:i,dark:Q,dk:j,onSelect:On,onAmountChange:Gn,onAdd:wn,onRemove:Pn,resolveMaxAmount:Yt,onViewAllAssets:R}),Vt&&We&&u(Kr,{fontFamily:i?.fontFamily||ce.typography.fontFamily,textPrimary:j.textPrimary,textSecondary:j.textSecondary,cardBg:Q?j.inputBg:"#ffffff",cardBorder:j.cardBorder,resolvedDark:Q,darkCardBorder:j.cardBorder,primaryColor:re,feePreview:Cn,isLoading:vn||Vt&&!sn,errorText:Ue}),u(vp,{intentStatus:ye,postDepositSuccess:dt,postDepositAmount:ut,postDepositStatus:Le,depositActionLabel:y,sourceChainName:Z[0]?.asset?.chainId?gn(Z[0].asset.chainId):"Destination Chain",directDepositStatus:ft,directDepositTxHash:Me,directDepositChainId:ee,styles:i}),u(bp,{isOpen:Kt||!!ye||Le!=="idle"&&!!g,onClose:()=>{ln(!1),ye&&Ht();const H=Le==="success"&&!ye,we=ye?.overallStatus==="success"&&(g?Le==="success":!0);(H||we)&&t()},onConfirm:()=>{if(!je)return E?.(),ve()},data:Jt,isExecuting:je,error:Ke,theme:ce,styles:i,intentStatus:ye,postDepositStatus:Le,hasPostDepositInstruction:!!g}),q&&C(dl,{dk:j,dark:Q,borderRadius:ce.borderRadius.md,children:["\u26A1 ",q]}),un&&u(dl,{dk:j,dark:Q,borderRadius:ce.borderRadius.md,children:"Low native balance in the external wallet. The deposit to spicenet account might fail."}),C("div",{style:{display:"flex",flexDirection:"column",gap:0,marginBottom:0,margin:0,padding:0},children:[Yn?u("div",{style:{marginBottom:"10px",fontSize:"12px",lineHeight:"1.45",color:j.errorText,fontFamily:i?.fontFamily||ce.typography.fontFamily},children:Yn}):null,u(Et,{variant:"outline",fullWidth:!0,onClick:Oo,disabled:!kn||!pe||je,theme:ce,dark:Q,styles:i,children:yo()})]})]})}):null});function xn(e,t,n,o){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const s=10n**BigInt(t-n);return o==="ceil"?(e+s-1n)/s:e/s}function dn(e,t){if(!Number.isInteger(t)||t<0||t>255)throw new Error("Invalid token decimals");if(!/^\d+(?:\.\d*)?$/.test(e))throw new Error("Enter a valid amount.");if((e.split(".")[1]?.replace(/0+$/,"")??"").length>t)throw new Error(`Use at most ${t} decimal places for this source.`);return mn(e,t)}function zs(e,t,n){const o=xn(e,t,n,"floor");if(xn(o,n,t,"floor")!==e)throw new Error(`Use at most ${n} decimal places for this delivered token.`);return o}function Cp(e){return`0x77${e.slice(4)}`}function Hs({userAddress:e,destinationChainId:t,deliveryToken:n,deliveryAmount:o,withdrawalAmount:s,deliveryRecipient:r,deliveryTransfers:a,requestTimestampMs:i}){const l=a?.length?a:[{token:n,recipient:r,amount:s??o}],c=l.reduce((h,m)=>h+m.amount,0n);if(c<=0n)return null;const d=i??Date.now(),p=BigInt(Math.floor(d/1e3)),f=Cp(vo(zn([{type:"address"},{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[e??r,n,r,c,BigInt(t),BigInt(d)])));return{chainId:Pa,domain:"spicenet",tokenTransfers:[],calls:[{to:Tt,value:0n,data:xt({abi:ar,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${t}`,idempotenceKey:f,nbf:0n,exp:p+3600n,metadata:"{}",transfers:l.map(h=>({token:zt(h.token).toLowerCase(),to:zt(h.recipient).toLowerCase(),amount:h.amount}))}]})}]}}const ea=e=>{const[t,n]=O(!1),o=Qt(Mt),{dark:s,dk:r}=Bt();if(ae(()=>{n(!0)},[]),!t)return u("div",{className:e.className,children:u("button",{disabled:!0,style:{padding:"12px 24px",fontSize:"16px",backgroundColor:s?r.hoverBg:"#ccc",color:s?r.textSecondary:"white",border:s?`1px solid ${r.buttonBorder}`:"none",borderRadius:"4px",cursor:"not-allowed"},children:"Loading..."})});if(!o){const a='ProviderLogin must be used within SpiceFlowProvider. Please wrap your app with <SpiceFlowProvider provider="privy">.';return u("div",{className:e.className,children:u("button",{onClick:()=>{e.onAuthError&&e.onAuthError(a)},style:{padding:"12px 24px",fontSize:"16px",backgroundColor:s?r.errorBg:"#dc2626",color:s?r.errorText:"white",border:s?`1px solid ${r.errorBorder}`:"none",borderRadius:"4px",cursor:"pointer"},children:"Provider Not Found"})})}return u(Lc,{...e})},Cl=({isSuccess:e,type:t,chainName:n,explorerUrl:o,txHash:s,dark:r=!1,successBg:a="#d1fae5",successBorder:i="#6ee7b7",successText:l="#065f46",errorBg:c="#fee2e2",errorBorder:d="#fca5a5",errorText:p="#dc2626",textSecondary:f="#6b7280"})=>C("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px",borderRadius:"8px",backgroundColor:e?a:c,border:e?`1px solid ${i}`:`1px solid ${d}`},children:[C("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[u("div",{style:{width:"28px",height:"28px",borderRadius:"50%",backgroundColor:e?"#10b981":"#ef4444",display:"flex",alignItems:"center",justifyContent:"center"},children:e?u("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:u("path",{d:"M11.6667 3.5L5.25 9.91667L2.33333 7",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}):u("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:u("path",{d:"M10.5 3.5L3.5 10.5M3.5 3.5L10.5 10.5",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),C("div",{children:[u("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:Oe.mono,letterSpacing:"0.5px",color:e?l:p},children:e?`${t.toUpperCase()} CONFIRMED`:`${t.toUpperCase()} FAILED`}),C("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:f},children:["on ",n]})]})]}),o&&s&&C("a",{href:`${o}/tx/${s}`,target:"_blank",rel:"noopener noreferrer",style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"13px",color:f,textDecoration:"none",whiteSpace:"nowrap"},children:["View on explorer",C("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:[u("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"}),u("path",{d:"M7.5 1.5H10.5V4.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),u("path",{d:"M5 7L10.5 1.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})]})]})]}),kl=`
31
+ `})]})},vl=En.memo(({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,onDepositSelect:o,depositBatches:s,supportedChains:r,title:a,styles:i,onDepositAssetChange:l,assetInputHook:c,externalWalletAddress:d,onDepositAmountChange:p,allowSecondAsset:f=!1,destinationChainId:h,destinationTokenAddress:m,onDepositExecute:g,depositActionLabel:y,nativeChainId:w,sponsorGas:x=!1,preSelectedAsset:v,escrowOnly:k=!1,escrowTokenAddress:A,escrowAmount:b,escrowTokenDecimals:S,escrowTokenSymbol:T,onSubmit:E,onDepositSuccess:I,onDepositError:M,embeddedWalletAddress:W,onViewAllAssets:R})=>{const F=Qt(Mt),N=F?.mode||"7702",D=F?.allowedTokens,L=!!F?.isWhitelistGateActive,z=!k&&!!F?.isWhitelistConfigured&&F?.isUserWhitelisted!==!0,fe=c?.assetAmount||"",{theme:ce,dark:Q,appName:ne,primaryColor:re,dk:j}=Bt(i),J=Zn(),{isReady:Y,isAuthenticated:me}=J,{externalWallet:B}=ps(),U=F?.embeddedWalletAddress||W,X=N!="7702",pe=X?!!d:Y&&me&&!!U,de=U,xe=d,K=de??xe,G=Rn(),{data:P}=td(),[V,ie]=En.useState(P),ke=En.useRef(null),Ee=En.useRef(B);Ee.current=B;const Be=B?.address;En.useEffect(()=>{const H=Ee.current;if(!H||!xe){ke.current=null,ie(P);return}if(H.address?.toLowerCase()!==xe?.toLowerCase()){ke.current=null,ie(P);return}H.getEthereumProvider().then(async we=>{ke.current=we;const He=await we.request({method:"eth_chainId"}),Se=parseInt(He,16),mt=Ge(Se),rt=await H.getWalletClient(Se);ie(mt?cr({account:xe,chain:mt.viemChain,transport:dr(we)}):rt)}).catch(()=>{ke.current=null,ie(P)})},[Be,xe,P]);const Ie=En.useRef(null),[Z,ot]=O([]),{assets:qe,loading:Ct,error:ht,refreshAssets:Ve}=Ko({address:k?de:xe||de,supportedChains:r,fetchBalances:So,enabled:e,refreshInterval:e?5e3:0}),Qe=ue(()=>qe.filter(H=>H.balance>0n&&po(H,"deposit-source",{allowedTokens:D,rpcOverrides:F?.rpcOverrides,liquidityVenues:F?.liquidityVenues,isWhitelistGateActive:L},void 0,void 0,{requiresEscrow:X||k}).eligible).sort((H,we)=>we.balanceUsd-H.balanceUsd),[qe,D,F?.rpcOverrides,L,X,k]),at=ue(()=>{if(!Z[0]?.asset)return[];const H=Z[0].asset.chainId;return Qe.filter(we=>we.chainId===H)},[Qe,Z]),[je,Dt]=O(!1),[Ke,gt]=O(null),De=_(M);De.current=M;const et=te(H=>{gt(H),typeof H=="string"&&H&&De.current?.(H,fs(H))},[]),[Le,ct]=O("idle"),$e=te(H=>{typeof H=="string"&&H&&De.current?.(H,fs(H))},[]),[dt,kt]=O(!1),[ut,Re]=O(null),[ft,Ot]=O("idle"),[Me,$]=O(null),[ee,ze]=O(null),[Ce,le]=O(null),[Pe,Ae]=O(null),[q,Ze]=O(null),{intentStatus:ye,startStatusPolling:Xe,clearStatus:Ht,execute:qt}=Ms(),Te=te((H,we)=>{const He=ls[we];return He?He.supportedTokens?.find(Se=>ge(Se.address,H))?.symbol??null:null},[]),Wt=ue(()=>{const H=Z[0]?.asset;if(!H||!m||!h)return!1;const we=Te(m,h);return wu(H.symbol)&&!!we&&bu(we)},[Z,m,h,Te]);ae(()=>{Z.length>0&&fe!==Z[0]?.amount&&ot(H=>{if(H.length===0)return H;const we=[...H];return we[0]={...we[0],amount:fe||""},we})},[fe]),ae(()=>{Z.length!==0&&ot(H=>{let we=!1;const He=H.map(Se=>{if(!Se.asset)return Se;const mt=Qe.find(rt=>rt.chainId===Se.asset.chainId&&ge(rt.address,Se.asset.address));return mt?mt===Se.asset||mt.balance===Se.asset.balance?Se:(we=!0,{...Se,asset:mt,amount:Se.amount}):Se});return we?He:H})},[Qe,Z.length]),ae(()=>{if(!v||Z.length>0||Qe.length===0)return;const H=Qe.find(we=>we.chainId===v.chainId&&ge(we.address,v.address));H&&(ot([{asset:H,amount:""}]),l?.(H))},[v,Qe,Z.length]);const Nt=En.useRef(null);ae(()=>{if(X&&ye?.overallStatus==="success"&&g&&Le==="idle"){const H=Nt.current,we=Ie.current;H&&(async()=>{try{ct("executing"),await g(H),ct("success"),Re(H),kt(!0);const He=Array.isArray(we)?we[0]:void 0,Se={type:"deposit",status:"success",amount:H,asset:He?.tokenAddress,sourceChain:He?String(He.chainId):void 0,txHash:He?.txHash};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:Se})),I?.(Se)}catch(He){console.error("onDepositExecute failed:",He),ct("error"),$e(Mn(He,"Post-deposit instruction failed"))}finally{Nt.current=null,Ie.current=null}})()}},[ye?.overallStatus,X,Le]);const wt=te(()=>{et(null)},[]);ae(()=>{e||(kt(!1),Re(null),Ot("idle"),$(null),ze(null))},[e]);const On=te((H,we)=>{ot(He=>{const Se=[...He];return Se[we]={asset:H,amount:Se[we]?.amount||""},Se}),we===0&&l?.(H),wt()},[l,wt]),Gn=te(async(H,we)=>{if(ot(He=>{const Se=[...He];return Se[we]&&(Se[we]={...Se[we],amount:H}),Se}),wt(),we===0)if(c?.setAssetAmount(H),Wt&&H&&parseFloat(H)>0)try{const He=Ce??await xu();Ce||le(He);const Se=Z[0]?.asset;if(!Se)return;const mt=mn(H,Se.decimals),rt=m?Te(m,h):null,Kn=ls[h]?.supportedTokens?.find(Xs=>ge(Xs.address,m))?.decimals??6,Ro=vu(mt,Se.decimals,Kn,He);Ae(Ro);const Mo=Fe(Ro,Kn),Zs=He.toLocaleString("en-US",{maximumFractionDigits:0});Ze(`${H} ${Se.symbol} \u2248 $${parseFloat(Mo).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})} ${rt??"USD"} (rate: $${Zs}/BTC)`),p?.(Mo)}catch(He){console.error("Failed to fetch BTC/USD price:",He),Ze(null),Ae(null),p?.(H)}else Ze(null),Ae(null),p?.(H)},[wt,c,p,Wt,Ce,Z,m,h,Te]),wn=te(()=>{Z.length<2&&ot(H=>[...H,{asset:null,amount:""}])},[Z.length]),Pn=te(H=>{ot(we=>we.filter((He,Se)=>Se!==H)),wt()},[wt]),bn=_(!1),jt=_(!1);ae(()=>{e||(bn.current=!1,jt.current=!1,st(null),$t(null))},[e]);const[Kt,ln]=O(!1),[Jt,Zt]=O(null),[on,st]=O(null),[Je,$t]=O(null),[vn,_t]=O(!1),[Ue,cn]=O(null),We=ue(()=>{const H=Z[0];if(Z.length!==1||!H?.asset||!H.amount||parseFloat(H.amount)<=0)return null;try{return{asset:H.asset,amount:mn(H.amount,H.asset.decimals),token:Ye(H.asset.address),chainId:H.asset.chainId}}catch{return null}},[Z]),en=!X&&!k&&!!We&&!no(We.asset),It=ue(()=>We?[We.chainId,We.token.toLowerCase(),We.amount.toString(),k?"escrow":"normal"].join("|"):null,[We,k]),pt=te(async(H,we)=>de?gl({address:de,depositQuote:H,escrowOnly:k,signal:we}):null,[de,k]),Un=te(async H=>We?pt(We,H):null,[We,pt]),hn=_(Un);hn.current=Un,Hr({shouldRun:e&&!X&&!en&&!!It&&!Kt&&!je,deps:[e,X,en,It,Kt,je],delayMs:500,backgroundIntervalMs:3e4,onSkip:()=>{st(null),cn(null),_t(!1)},onCleanup:()=>_t(!1),run:async({isBackground:H,isCurrent:we,signal:He})=>{H||(cn(null),_t(!0));try{const Se=await hn.current(He);we()&&st(Se)}catch(Se){if(!we())return;st(null),cn(Se instanceof Error?Se.message:"Failed to estimate gas fee")}finally{we()&&_t(!1)}}}),ae(()=>{Kt||je||$t(null)},[Kt,je,It]);const Oo=async()=>{if(Z.length===0||!Z[0]?.asset)return;const H=Z.filter(rt=>rt.asset&&rt.amount&&parseFloat(rt.amount)>0);if(H.length===0)return;const we=H[0],He=Ge(we.asset.chainId),Se=H.map(rt=>{const Kn=parseFloat(rt.amount);return`${isNaN(Kn)?rt.amount:Kn.toPrecision(6).replace(/\.?0+$/,"")} ${rt.asset.symbol}`}).join(", "),mt={network:He?.displayName||`Chain ${we.asset.chainId}`,amount:Se,symbol:"",chainId:we.asset.chainId};if(!X&&H.length===1&&on){$t(on);const rt=H[0];mt.creditedAmount=`${Fe(on.net,rt.asset.decimals)} ${no(rt.asset)?G({...rt.asset,location:"rollup",_source:"spice",receiptTokenName:"spiceUSDC"}).symbol:rt.asset.symbol}`,mt.networkFee=`${Fe(on.fee,rt.asset.decimals)} ${rt.asset.symbol}`}Zt(mt),ln(!0)},se=_(ye);se.current=ye;const he=_(Le);he.current=Le;const ve=async()=>{await ap({selectedDepositAssets:Z,escrowOnly:k,sourceAddress:xe,isNon7702:X,address:de,embeddedWalletAddress:U,isReady:Y,isAuthenticated:me,zeroCreditError:_e,depositBalanceError:rn,externalWalletClient:V,externalProvider:ke.current,effectiveDepositFee:St,depositBatches:s,destinationChainId:h,destinationTokenAddress:m,isCrossDenomination:Wt,convertedUsdAmount:Pe,mode:N,sponsorGas:x,nativeChainId:w,spiceBalanceUser:K,depositDataRef:Ie,bridgedAmountRef:Nt,setIsExecuting:Dt,setError:et,setConfirmationData:Zt,setShowConfirmation:ln,setDirectDepositStatus:Ot,setDirectDepositChainId:ze,setDirectDepositTxHash:$,setPostDepositStatus:ct,setPostDepositError:$e,setPostDepositAmount:Re,setPostDepositSuccess:kt,startStatusPolling:Xe,clearStatus:Ht,refreshAssets:Ve,onDepositExecute:g,onDepositSelect:o,onDepositSuccess:I,execution:{execute:qt},getCurrentIntentStatus:()=>se.current,getCurrentPostDepositStatus:()=>he.current})},_e=ue(()=>{for(const H of Z)if(!(!H?.asset||!H.amount||parseFloat(H.amount)<=0))try{const we=H.asset.decimals,He=mn(H.amount,we);if(He<=0n)continue;const Se=Ye(H.asset.address),mt=be(Se)?Ft(Se,H.asset.chainId)?.equivalenceGroup:_c(Se),rt=H.asset.receiptTokenDecimals??(mt==="ETH"||mt==="ARB"?18:mt==="USDC"||mt==="SUSD"||mt==="WBTC"||mt==="CBTC"?6:void 0);if(rt===void 0||we<=rt||co(He,we,rt)>0n)continue;return`Amount too small. Minimum deposit for this asset is ${Fe(10n**BigInt(we-rt),we)} ${H.asset.symbol}.`}catch{continue}return null},[Z]),Vt=!X&&!!We&&!en,St=Je??on,sn=!!We&&hl(St,We),rn=ue(()=>{if(!We)return null;if(en)return We.asset.balance>=We.amount?null:`Insufficient ${We.asset.symbol}. Need ${Fe(We.amount,We.asset.decimals)} ${We.asset.symbol}.`;if(!Vt||!sn)return null;const H=k?We.amount:We.amount+St.fee;return We.asset.balance>=H?null:`Insufficient ${We.asset.symbol}. Need ${Fe(H,We.asset.decimals)} ${We.asset.symbol} including gas.`},[Vt,en,We,sn,St,k]),[un,Gt]=O(!1),tn=Z[0]?.asset?.chainId,Pt=qe.find(H=>H.isNative&&H.chainId===tn)?.balance??0n;ae(()=>{if(!e||!tn){Gt(!1);return}let H=!1;return(async()=>{try{const we=await yt(tn).getGasPrice()*150000n;H||Gt(Pt<we)}catch{H||Gt(!1)}})(),()=>{H=!0}},[e,tn,Pt]);const ro=!Vt||sn&&!vn&&!Ue&&!rn,Yt=te((H,we)=>ip({asset:H,assetIndex:we,selectedAssetCount:Z.length,address:de,escrowOnly:k,isNon7702:X}),[X,Z.length,de,k]),Cn=ue(()=>{if(!We||!St||!sn)return null;const H=k?We.amount:We.amount+St.fee;return{symbol:We.asset.symbol,decimals:We.asset.decimals,grossAmount:H,netAmount:St.net,totalFee:St.fee,gasFee:St.fee,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"estimated"}},[We,St,sn,k]),An=parseFloat(Z[0]?.amount||"")||0,kn=Z.length>0&&Z[0]?.asset&&Z[0]?.amount&&An>0&&pe&&!je&&!_e&&!rn&&ro&&!z;ae(()=>{if(!k||!A||!b||bn.current||!pe)return;const H=r[0];if(!H)return;const we=Uc(H,[]).find(Se=>ge(Se.address,A));let He;if(we)He=we;else if(S!==void 0&&T)He={address:A,symbol:T,name:T,decimals:S,chainId:H,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,isNative:be(A)};else{console.warn("[DepositModal] escrowOnly: no matching asset and missing escrowTokenDecimals/escrowTokenSymbol for",A);return}bn.current=!0,ot([{asset:He,amount:b}])},[k,A,b,S,T,pe,r]),ae(()=>{!k||!kn||jt.current||je||(jt.current=!0,ve())},[k,kn,je]);const Yn=ht||Ke||_e||rn,yo=()=>{if(je)return"Executing Deposit...";if(!pe)return"Wallet Not Connected";if(N==="7702"){if(!Y)return"Loading...";if(!me)return"Authentication Required"}return Z[0]?.asset?Z[0]?.amount?_e?"AMOUNT TOO SMALL":rn?"INSUFFICIENT BALANCE":Vt&&!ro?Ue?"GAS UNAVAILABLE":"ESTIMATING GAS":"DEPOSIT":"ENTER AMOUNT":"SELECT TOKEN"};return e?u(Dn,{isOpen:e,onClose:t,closeOnBackdropClick:n,title:a||`Deposit to your ${ne} account`,subtitle:C("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[u("img",{src:zr,alt:"","aria-hidden":"true",style:{width:"13px",height:"13px",flexShrink:0,...Q?{filter:"invert(0.6)"}:{}}}),u("p",{style:{fontSize:"12px",color:j.textSecondary,margin:"0",lineHeight:"1.4",fontFamily:Oe.ui},children:`Deposit collateral to your ${ne} Account from any supported network.`})]}),dark:Q,overlayContent:Kt||ye||Le!=="idle"&&g?u("div",{}):void 0,styles:i,theme:ce,children:C("div",{style:{padding:"24px 24px 5px 24px"},children:[u(gp,{selectedDepositAssets:Z,depositAssets:Qe,secondAssetOptions:at,loadingAssets:Ct,allowSecondAsset:f,theme:ce,styles:i,dark:Q,dk:j,onSelect:On,onAmountChange:Gn,onAdd:wn,onRemove:Pn,resolveMaxAmount:Yt,onViewAllAssets:R}),Vt&&We&&u(Kr,{fontFamily:i?.fontFamily||ce.typography.fontFamily,textPrimary:j.textPrimary,textSecondary:j.textSecondary,cardBg:Q?j.inputBg:"#ffffff",cardBorder:j.cardBorder,resolvedDark:Q,darkCardBorder:j.cardBorder,primaryColor:re,feePreview:Cn,isLoading:vn||Vt&&!sn,errorText:Ue}),u(vp,{intentStatus:ye,postDepositSuccess:dt,postDepositAmount:ut,postDepositStatus:Le,depositActionLabel:y,sourceChainName:Z[0]?.asset?.chainId?gn(Z[0].asset.chainId):"Destination Chain",directDepositStatus:ft,directDepositTxHash:Me,directDepositChainId:ee,styles:i}),u(bp,{isOpen:Kt||!!ye||Le!=="idle"&&!!g,onClose:()=>{ln(!1),ye&&Ht();const H=Le==="success"&&!ye,we=ye?.overallStatus==="success"&&(g?Le==="success":!0);(H||we)&&t()},onConfirm:()=>{if(!je)return E?.(),ve()},data:Jt,isExecuting:je,error:Ke,theme:ce,styles:i,intentStatus:ye,postDepositStatus:Le,hasPostDepositInstruction:!!g}),q&&C(dl,{dk:j,dark:Q,borderRadius:ce.borderRadius.md,children:["\u26A1 ",q]}),un&&u(dl,{dk:j,dark:Q,borderRadius:ce.borderRadius.md,children:"Low native balance in the external wallet. The deposit to spicenet account might fail."}),C("div",{style:{display:"flex",flexDirection:"column",gap:0,marginBottom:0,margin:0,padding:0},children:[Yn?u("div",{style:{marginBottom:"10px",fontSize:"12px",lineHeight:"1.45",color:j.errorText,fontFamily:i?.fontFamily||ce.typography.fontFamily},children:Yn}):null,u(Et,{variant:"outline",fullWidth:!0,onClick:Oo,disabled:!kn||!pe||je,theme:ce,dark:Q,styles:i,children:yo()})]})]})}):null});function xn(e,t,n,o){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const s=10n**BigInt(t-n);return o==="ceil"?(e+s-1n)/s:e/s}function dn(e,t){if(!Number.isInteger(t)||t<0||t>255)throw new Error("Invalid token decimals");if(!/^\d+(?:\.\d*)?$/.test(e))throw new Error("Enter a valid amount.");if((e.split(".")[1]?.replace(/0+$/,"")??"").length>t)throw new Error(`Use at most ${t} decimal places for this source.`);return mn(e,t)}function zs(e,t,n){const o=xn(e,t,n,"floor");if(xn(o,n,t,"floor")!==e)throw new Error(`Use at most ${n} decimal places for this delivered token.`);return o}function Cp(e){return`0x77${e.slice(4)}`}function Hs({userAddress:e,destinationChainId:t,deliveryToken:n,deliveryAmount:o,withdrawalAmount:s,deliveryRecipient:r,deliveryTransfers:a,requestTimestampMs:i}){const l=a?.length?a:[{token:n,recipient:r,amount:s??o}],c=l.reduce((h,m)=>h+m.amount,0n);if(c<=0n)return null;const d=i??Date.now(),p=BigInt(Math.floor(d/1e3)),f=Cp(vo(zn([{type:"address"},{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[e??r,n,r,c,BigInt(t),BigInt(d)])));return{chainId:Pa,domain:"spicenet",tokenTransfers:[],calls:[{to:Tt,value:0n,data:xt({abi:ar,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${t}`,idempotenceKey:f,nbf:0n,exp:p+3600n,metadata:"{}",transfers:l.map(h=>({token:zt(h.token).toLowerCase(),to:zt(h.recipient).toLowerCase(),amount:h.amount}))}]})}]}}const ea=e=>{const[t,n]=O(!1),o=Qt(Mt),{dark:s,dk:r}=Bt();if(ae(()=>{n(!0)},[]),!t)return u("div",{className:e.className,children:u("button",{disabled:!0,style:{padding:"12px 24px",fontSize:"16px",backgroundColor:s?r.hoverBg:"#ccc",color:s?r.textSecondary:"white",border:s?`1px solid ${r.buttonBorder}`:"none",borderRadius:"4px",cursor:"not-allowed"},children:"Loading..."})});if(!o){const a='ProviderLogin must be used within SpiceFlowProvider. Please wrap your app with <SpiceFlowProvider provider="privy">.';return u("div",{className:e.className,children:u("button",{onClick:()=>{e.onAuthError&&e.onAuthError(a)},style:{padding:"12px 24px",fontSize:"16px",backgroundColor:s?r.errorBg:"#dc2626",color:s?r.errorText:"white",border:s?`1px solid ${r.errorBorder}`:"none",borderRadius:"4px",cursor:"pointer"},children:"Provider Not Found"})})}return u(Lc,{...e})},Cl=({isSuccess:e,type:t,chainName:n,explorerUrl:o,txHash:s,dark:r=!1,successBg:a="#d1fae5",successBorder:i="#6ee7b7",successText:l="#065f46",errorBg:c="#fee2e2",errorBorder:d="#fca5a5",errorText:p="#dc2626",textSecondary:f="#6b7280"})=>C("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px",borderRadius:"8px",backgroundColor:e?a:c,border:e?`1px solid ${i}`:`1px solid ${d}`},children:[C("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[u("div",{style:{width:"28px",height:"28px",borderRadius:"50%",backgroundColor:e?"#10b981":"#ef4444",display:"flex",alignItems:"center",justifyContent:"center"},children:e?u("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:u("path",{d:"M11.6667 3.5L5.25 9.91667L2.33333 7",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}):u("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:u("path",{d:"M10.5 3.5L3.5 10.5M3.5 3.5L10.5 10.5",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),C("div",{children:[u("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:Oe.mono,letterSpacing:"0.5px",color:e?l:p},children:e?`${t.toUpperCase()} CONFIRMED`:`${t.toUpperCase()} FAILED`}),C("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:f},children:["on ",n]})]})]}),o&&s&&C("a",{href:`${o}/tx/${s}`,target:"_blank",rel:"noopener noreferrer",style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"13px",color:f,textDecoration:"none",whiteSpace:"nowrap"},children:["View on explorer",C("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:[u("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"}),u("path",{d:"M7.5 1.5H10.5V4.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),u("path",{d:"M5 7L10.5 1.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})]})]})]}),kl=`
32
32
  @keyframes slideUp {
33
33
  from { transform: translateY(100%); }
34
34
  to { transform: translateY(0); }
@@ -41,7 +41,7 @@ import{jsxs as C,jsx as u,Fragment as an}from"react/jsx-runtime";import{g as Ge,
41
41
  from { opacity: 0; transform: translateY(4px); }
42
42
  to { opacity: 1; transform: translateY(0); }
43
43
  }
44
- `,Il=({title:e,showChevron:t,expanded:n,onToggleDetails:o,showClose:s,onClose:r,fontFamily:a,labelColor:i,textPrimary:l,closeHoverBg:c,closePressedBg:d})=>{const[p,f]=O(!1),[h,m]=O(!1);return C("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"16px"},children:[C("div",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:o?"pointer":"default"},onClick:o,children:[C("span",{style:{fontSize:"13px",fontWeight:500,color:i,fontFamily:a},children:[e," "]}),t&&u(Eo,{color:i,direction:n?"up":"down"})]}),s&&u("button",{onClick:r,onMouseEnter:()=>f(!0),onMouseLeave:()=>{f(!1),m(!1)},onMouseDown:()=>m(!0),onMouseUp:()=>m(!1),style:{background:h?d:p?c:"none",border:"none",borderRadius:"4px",cursor:"pointer",padding:"4px",display:"flex",alignItems:"center",justifyContent:"center",color:p||h?l:i,transform:h?"scale(0.9)":p?"scale(1.1)":"scale(1)",transition:In.interactive},children:u(Jo,{size:16})})]})},Sl=({chainName:e,bg:t,border:n,textPrimary:o,labelColor:s,primaryColor:r})=>C("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"20px 16px",borderRadius:"8px",backgroundColor:t,border:`1px solid ${n}`,gap:"12px"},children:[u(Ln,{size:24,borderWidth:3,color:r}),C("div",{children:[u("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:Oe.mono,letterSpacing:"0.5px",color:o},children:"PROCESSING TRANSACTION"}),C("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:s},children:["on ",e]})]})]}),Al=({bg:e,border:t,left:n,right:o})=>C("div",{style:{padding:"10px 12px",borderRadius:"6px",backgroundColor:e,border:`1px solid ${t}`,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[n,o]}),ta=({isOpen:e,onClose:t,onComplete:n,closeOnComplete:o=!1,type:s,results:r,chainId:a,chainName:i,explorerUrl:l,theme:c,styles:d,dark:p,intentStatus:f,onRetry:h,onNewTx:m,onRetryTx:g,asOverlay:y=!0,isProcessing:w=!1,showStepBreakdown:x=!0})=>{const{theme:v,primaryColor:k,dark:A,dk:b}=Bt(d,p),S=c||v,[T,E]=O(!1),I=i??(a?gn(a):"Network"),M=l??(a&&us(a,"").replace(/\/tx\/.*$/,"")||void 0),W=A?b.cardBg:"#ffffff",R=A?"0 4px 20px rgba(0, 0, 0, 0.4)":"0 4px 20px rgba(0, 0, 0, 0.1)",F=A?"0 -4px 8px -2px rgba(0, 0, 0, 0.4)":"0 -4px 8px -2px rgba(0, 0, 0, 0.15)",N=b.textSecondary,D=A?b.textPrimary:"#374151",L=A?b.inputBg:"#f9fafb",z=A?b.inputBorder:"#e5e7eb",fe=A?b.inputBg:"#f3f4f6",ce=A?b.inputBorder:"#e5e7eb",[Q,ne]=O(!0),re=A?b.inputBg:"#f9fafb",j=A?b.hoverBg:"#f3f4f6",J=A?{successBg:b.successBg,successBorder:b.successBorder,successText:b.successText,errorBg:b.errorBg,errorBorder:b.errorBorder,errorText:b.errorText}:{},Y=f?.steps.find(de=>de.status==="failed")?.error;ae(()=>{!e&&!f&&E(!1)},[e,f]);const me=()=>{E(!0),setTimeout(()=>{window.dispatchEvent(new CustomEvent("tx-complete",{detail:{type:s,results:r}})),window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:{type:s,status:"success",results:r}})),n?.(),o&&t()},300)},B=()=>{ne(!Q)};if(f){const{steps:de,overallStatus:xe}=f,K=xe==="processing",G=xe==="success",P=xe==="failed",V=de.filter(Be=>Be.transactionHash)[0],ie=de.length>1?de.map(Be=>Be.chainName).filter(Boolean).join(" and "):I!=="Network"?I:de[0]?.chainName||I,ke=M||(V?us(V.chainId,V.transactionHash||"").replace(/\/tx\/.*$/,""):void 0),Ee=C(an,{children:[u(Il,{title:K?`Processing ${s.charAt(0).toUpperCase()+s.slice(1)}`:`${s.charAt(0).toUpperCase()+s.slice(1)} results`,showChevron:x,expanded:Q,onToggleDetails:B,showClose:!K,onClose:t,fontFamily:d?.fontFamily||S.typography.fontFamily,labelColor:N,textPrimary:D,closeHoverBg:re,closePressedBg:j}),u("div",{style:{marginBottom:"16px"},children:K?u(Sl,{chainName:ie,bg:fe,border:ce,textPrimary:D,labelColor:N,primaryColor:k}):u(Cl,{isSuccess:G,type:s,chainName:ie,explorerUrl:ke,txHash:V?.transactionHash,dark:A,...J,textSecondary:N})}),x&&u("div",{style:{overflow:"hidden",maxHeight:Q?"300px":"0px",opacity:Q?1:0,transition:"max-height 0.3s ease, opacity 0.3s ease",marginBottom:Q?"16px":"0"},children:u("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:de.map((Be,Ie)=>{const Z=Be.transactionHash?us(Be.chainId,Be.transactionHash):null;return u(Al,{bg:L,border:z,left:u("span",{style:{fontSize:"13px",color:D},children:Be.chainName?`On ${Be.chainName}`:Be.description||`Step ${Ie+1}`}),right:C("span",{style:{display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:Be.status==="success"?"#10b981":Be.status==="failed"?"#ef4444":N,fontWeight:500},children:[Z&&u("a",{href:Z,target:"_blank",rel:"noopener noreferrer",style:{color:A?b.infoText:"#2563eb",textDecoration:"none"},onClick:ot=>ot.stopPropagation(),children:"View"}),Be.status==="success"?"\u2713":Be.status==="failed"?"\u2717":"\u25CB"]})},Ie)})})}),!K&&C("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[P&&h&&u(Et,{variant:"outline",fullWidth:!0,onClick:h,theme:S,styles:d,dark:A,children:"TRY AGAIN"}),m&&C(Et,{variant:"outline",fullWidth:!0,onClick:m,theme:S,styles:d,dark:A,children:["NEW ",s.toUpperCase()," \u2192"]})]})]});return y?C("div",{style:{position:"absolute",bottom:0,left:0,right:0,zIndex:10,animation:T?"slideDown 0.3s ease-in forwards":"slideUp 0.3s ease-out forwards",pointerEvents:"auto"},children:[u("div",{style:{backgroundColor:W,borderRadius:"12px 12px 0 0",width:"100%",padding:"18px 24px 24px",boxShadow:F},children:Ee}),u("style",{children:kl})]}):u("div",{style:{backgroundColor:W,borderRadius:"12px",padding:"24px",width:"100%",boxShadow:R},children:Ee})}if(!e&&!w||!w&&(!r||r.length===0))return null;const U=r?r.every(de=>de.success):!1,X=r?.[0],pe=[...r??[]].reverse().find(de=>de.txHash)?.txHash||X?.txHash;return C("div",{style:{position:y?"absolute":"relative",bottom:y?0:void 0,left:y?0:void 0,right:y?0:void 0,zIndex:y?10:void 0,animation:y?T?"slideDown 0.3s ease-in forwards":"slideUp 0.3s ease-out forwards":void 0,pointerEvents:"auto",width:"100%"},children:[u("div",{style:{backgroundColor:W,borderRadius:y?"12px 12px 0 0":"12px",width:"100%",padding:"18px 0 24px",boxShadow:y?F:R},children:C("div",{style:{width:"100%",boxSizing:"border-box",padding:"0 24px"},children:[u(Il,{title:w?`Processing ${s.charAt(0).toUpperCase()+s.slice(1)}`:`${s.charAt(0).toUpperCase()+s.slice(1)} results`,showChevron:!w&&x,expanded:Q,onToggleDetails:w?void 0:B,showClose:!w,onClose:t,fontFamily:d?.fontFamily||S.typography.fontFamily,labelColor:N,textPrimary:D,closeHoverBg:re,closePressedBg:j}),u("div",{style:{marginBottom:"16px",animation:"statusFadeIn 220ms cubic-bezier(0.22, 1, 0.36, 1) both"},children:w?u(Sl,{chainName:I,bg:fe,border:ce,textPrimary:D,labelColor:N,primaryColor:k}):u(Cl,{isSuccess:U,type:s,chainName:I,explorerUrl:M,txHash:pe,dark:A,...J,textSecondary:N})},w?"processing":U?"success":"error"),!w&&x&&r&&r.length>1&&u("div",{style:{overflow:"hidden",maxHeight:Q?"200px":"0px",opacity:Q?1:0,transition:"max-height 0.3s ease, opacity 0.3s ease",marginBottom:Q?"16px":"0"},children:u("div",{style:{maxHeight:"180px",overflowY:"auto",display:"flex",flexDirection:"column",gap:"8px"},children:r.map((de,xe)=>u(Al,{bg:L,border:z,left:C("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[u("span",{style:{fontWeight:600,fontSize:"13px",color:b.textPrimary,fontFamily:Oe.mono},children:de.asset.symbol}),de.amount&&u("span",{style:{fontSize:"12px",color:N},children:de.amount})]}),right:u("span",{style:{fontSize:"12px",color:de.success?"#10b981":"#ef4444",fontWeight:500},children:de.success?"\u2713":"\u2717"})},xe))})}),!w&&!U&&r&&u("div",{style:{padding:"12px",backgroundColor:b.errorBg,border:`1px solid ${b.errorBorder}`,borderRadius:"8px",marginBottom:"16px"},children:u("p",{style:{fontSize:"13px",color:b.errorText,margin:0,lineHeight:1.5},children:Y||r.find(de=>!de.success)?.error||`${s.charAt(0).toUpperCase()+s.slice(1)} failed. Please try again.`})}),!w&&C("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[!U&&g&&C(Et,{variant:"outline",fullWidth:!0,onClick:g,theme:S,styles:d,dark:A,children:["TRY AGAIN ",s.toUpperCase()]}),U&&u(Et,{variant:"outline",fullWidth:!0,onClick:me,theme:S,styles:d,dark:A,children:"DONE"})]})]})}),u("style",{children:kl})]})};function El(e){const t=new Set(ed(e).map(n=>n.toLowerCase()));return t.add(e.toLowerCase()),t}const kp=["USDC","USDT","WETH","WBTC"];function Fl(e,t){const n=Ge(t);if(!n)return;if(n.nativeCurrency.symbol.toUpperCase()===e.toUpperCase())return{address:Tt,symbol:n.nativeCurrency.symbol,decimals:n.nativeCurrency.decimals,chainId:t};const o=n.supportedTokens?.find(s=>s.symbol.toUpperCase()===e.toUpperCase());if(o)return{address:o.address.toLowerCase(),symbol:o.symbol,decimals:o.decimals,chainId:t}}function jn(e,t,n){const o=Ge(t);if(!o)return;if(n!==void 0){if(be(e)&&!Ft(e,n))return;const a=Tr(e,n,t);return a?{address:a.address.toLowerCase(),symbol:a.symbol,decimals:a.decimals,chainId:t}:void 0}if(be(e))return;const s=El(e),r=o.supportedTokens?.find(a=>s.has(a.address.toLowerCase()));if(r)return{address:r.address.toLowerCase(),symbol:r.symbol,decimals:r.decimals,chainId:t}}function Ip(e){const{sourceAsset:t,outputAsset:n,sourceChainId:o,destinationChainId:s,intermediaryCandidates:r=kp}=e;if(Is(t,n))return{strategy:"direct",sourceAsset:t,outputAsset:n,sourceChainId:o,destinationChainId:s,summary:`${t.symbol} fronted directly`};if(o===s&&(be(t.address)||!Ft(t.address,o)))return{strategy:"direct-swap",sourceAsset:t,outputAsset:n,sourceChainId:o,destinationChainId:s,summary:`${t.symbol} \u2192 ${n.symbol} on chain ${o}, no escrow`};if(jn(t.address,s,o))return{strategy:"direct",sourceAsset:t,outputAsset:n,sourceChainId:o,destinationChainId:s,summary:`${t.symbol} fronted on destination, swapped to ${n.symbol}`};if(jn(n.address,o,s))return{strategy:"source-swap",sourceAsset:t,outputAsset:n,sourceChainId:o,destinationChainId:s,summary:`${t.symbol} \u2192 ${n.symbol} on source chain, then fronted`};for(const a of r){const i=Fl(a,o);if(!i||Is(t,i)||Is(n,i))continue;const l=Fl(a,s);if(l&&Is(i,l))return{strategy:"intermediary",sourceAsset:t,outputAsset:n,intermediaryAsset:l,sourceChainId:o,destinationChainId:s,summary:`${t.symbol} \u2192 ${a} on source, fronted, then ${a} \u2192 ${n.symbol} on destination`}}throw new Ne("ROUTE_STRATEGY_ERROR",`No viable cross-chain route found from ${t.symbol} (chain ${o}) to ${n.symbol} (chain ${s}). No intermediary asset is available on both chains.`,{sourceAsset:t.symbol,outputAsset:n.symbol,sourceChainId:o,destinationChainId:s,candidatesChecked:r})}async function Sp(e){const{route:t,sourceAmount:n,userAddress:o,registry:s,actionCalls:r,slippage:a}=e;async function i(l,c,d,p){const f=await s.resolveSwap({type:"swap",tokenIn:c,tokenOut:d,amountIn:p,maxSlippage:a},l,o);if(!f)throw new Ne("NO_LIQUIDITY",`No venue returned a quote for ${c} \u2192 ${d} on chain ${l}. No liquidity available for this pair.`,{chainId:l,tokenIn:c,tokenOut:d,amountIn:p.toString()});return f}switch(t.strategy){case"direct-swap":{const l=await i(t.destinationChainId,t.sourceAsset.address,t.outputAsset.address,n);return{chainBatches:[{chainId:t.destinationChainId,calls:[...l.calls,...r]}],solverFrontToken:t.outputAsset,solverFrontAmount:0n,resolvedSwaps:{sourceSwap:l}}}case"direct":{const l=jn(t.sourceAsset.address,t.destinationChainId,t.sourceChainId)||t.sourceAsset;if(El(l.address).has(t.outputAsset.address.toLowerCase()))return{chainBatches:[{chainId:t.destinationChainId,calls:r}],solverFrontToken:l,solverFrontAmount:n,resolvedSwaps:{}};const c=await i(t.destinationChainId,l.address,t.outputAsset.address,n);return{chainBatches:[{chainId:t.destinationChainId,calls:[...c.calls,...r]}],solverFrontToken:l,solverFrontAmount:n,resolvedSwaps:{destinationSwap:c}}}case"source-swap":{const l=jn(t.outputAsset.address,t.sourceChainId,t.destinationChainId);if(!l)throw new Ne("ROUTE_TOKEN_NOT_FOUND",`Output asset ${t.outputAsset.symbol} (${t.outputAsset.address}) not found on source chain ${t.sourceChainId}`,{token:t.outputAsset.symbol,address:t.outputAsset.address,chainId:t.sourceChainId,side:"source"});const c=jn(t.outputAsset.address,t.destinationChainId,t.destinationChainId);if(!c)throw new Ne("ROUTE_TOKEN_NOT_FOUND",`Output asset ${t.outputAsset.symbol} (${t.outputAsset.address}) not found on destination chain ${t.destinationChainId}`,{token:t.outputAsset.symbol,address:t.outputAsset.address,chainId:t.destinationChainId,side:"destination"});const d=await i(t.sourceChainId,t.sourceAsset.address,l.address,n);return{chainBatches:[{chainId:t.sourceChainId,calls:d.calls},{chainId:t.destinationChainId,calls:r}],solverFrontToken:c,solverFrontAmount:d.amountOutMinimum,resolvedSwaps:{sourceSwap:d}}}case"intermediary":{if(!t.intermediaryAsset)throw new Ne("ROUTE_STRATEGY_ERROR","Intermediary strategy requires an intermediary asset but none was provided in the route plan.",{strategy:t.strategy});const l=jn(t.intermediaryAsset.address,t.sourceChainId,t.destinationChainId);if(!l)throw new Ne("ROUTE_TOKEN_NOT_FOUND",`Intermediary ${t.intermediaryAsset.symbol} (${t.intermediaryAsset.address}) not found on source chain ${t.sourceChainId}`,{token:t.intermediaryAsset.symbol,address:t.intermediaryAsset.address,chainId:t.sourceChainId,side:"source"});const c=await i(t.sourceChainId,t.sourceAsset.address,l.address,n),d=await i(t.destinationChainId,t.intermediaryAsset.address,t.outputAsset.address,c.amountOutMinimum);return{chainBatches:[{chainId:t.sourceChainId,calls:c.calls},{chainId:t.destinationChainId,calls:[...d.calls,...r]}],solverFrontToken:t.intermediaryAsset,solverFrontAmount:c.amountOutMinimum,resolvedSwaps:{sourceSwap:c,destinationSwap:d}}}default:throw new Ne("ROUTE_STRATEGY_ERROR",`Unknown route strategy: ${t.strategy}`,{strategy:t.strategy})}}function Ap(e,t,n){if(!e||!t)return null;const o=ko(e,t),s=Object.entries(e.chainTokens??{}).flatMap(([p,f])=>{const h=qn(p);return h?.chainId===t?[{parsed:h,detail:f}]:[]}),r=p=>n.find(f=>ge(f.address,p))??null,a=p=>{const f=s.find(({parsed:g})=>ge(g.address,p));if(!f)return null;const h=Ge(t);if(be(p))return h?{address:Tt,symbol:h.nativeCurrency.symbol,name:h.nativeCurrency.name,decimals:h.nativeCurrency.decimals,logoURI:e.logoURI}:null;const m=h?.supportedTokens?.find(g=>ge(g.address,p));return!m||!Fr(e,p,t)?null:{address:f.parsed.address,symbol:m.symbol,name:m.name||f.detail?.name||e.displayName||e.name||e.symbol,decimals:m.decimals,logoURI:m.logo||e.logoURI}},i=s.map(({parsed:p})=>p.address).filter(be);for(const p of[...o,...i]){if(be(p)){const m=a(p);if(m)return m}const f=r(p);if(f)return f;const h=a(p);if(h)return h}if(e.chainTokens||e.receiptTokenId)return null;const l=Sn(e,t);if(l){const p=r(l);if(p)return p}const c=jn(e.address,t,e.chainId);return c?r(c.address)||(n.length>0?null:{address:c.address,symbol:c.symbol||e.symbol,name:e.displayName||e.name||e.symbol,decimals:c.decimals??e.decimals,logoURI:e.logoURI}):null}function Ep(e){const t=e.find(n=>bo(n.chainId))?.calls?.[0]?.data;if(!t)return null;try{const n=uo({abi:ar,data:t});return n.functionName!=="createWithdrawalRequest"?null:n.args[0].transfers.map(o=>({token:o.token,recipient:o.to,amount:o.amount}))}catch{return null}}function Fp(e,t){if(!e||e.length!==t.length)return!1;const n=o=>o.reduce((s,r)=>s+r.amount,0n);return n(e)!==n(t)?!1:e.every((o,s)=>{const r=t[s];return o.token.toLowerCase()!==r.token.toLowerCase()||o.recipient.toLowerCase()!==r.recipient.toLowerCase()?!1:o.recipient.toLowerCase()===nn.toLowerCase()?Sa(o.amount,r.amount,100n):o.recipient.toLowerCase()!==Fn.toLowerCase()||o.amount===r.amount})}function Tp(e,t){const n=e.intents.flatMap(r=>r.batches).filter(r=>{const a=io(r);return BigInt(r.quotedAmount)>0n||BigInt(r.totalDebit)>0n||a.totalFee>0n}),o=n.filter(r=>r.chainId===t),s=o.length>0?o:n;return s.length===1?s[0]:null}function Bp(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const o=n.token.toLowerCase(),s=n.recipient.toLowerCase(),r=`${o}:${s}`,a=t.get(r);a?a.amount+=n.amount:t.set(r,{...n})}return[...t.values()]}function Tl(e,t){if(!e.token||!e.recipient||e.chainId===null)return null;const n=Tp(t,e.chainId);if(!n)return null;const{gasFee:o,bridgeFee:s,spicenetFee:r}=io(n),a=o+s,i=e.grossAmountRaw-a-r;if(i<=0n)throw new Error("Withdrawal amount does not cover the network fee.");const l=[{token:e.token.address,recipient:e.recipient,amount:i}];return a>0n&&l.push({token:e.token.address,recipient:nn,amount:a}),r>0n&&l.push({token:e.token.address,recipient:Fn,amount:r}),Bp(l)}function Dp(e,t,n){const o=Tl(e,t);return!o||Fp(Ep(n),o)?null:e.buildWithdrawBatches(o)}async function Bl(e){if(!(!e.batches.length||!e.walletAddress||!e.recipient)){e.ui.setIsExecuting(!0),e.ui.setExecutionError(null),e.ui.setExecutionProgress(null),e.executionContextRef.current=null,e.ui.setLockedGasFee(e.gasFee);try{let t=e.batches;if(e.isNon7702&&e.onWithdrawExecute)await e.onWithdrawExecute(e.amount);else{if(!e.isNon7702&&!t.some(s=>bo(s.chainId)))throw new Error("Spice withdrawals must include a Spicenet funding batch before the destination chain batch.");const n=e.token?.address||"",o={useCustomTransfers:!0};if(e.buildSpicenetBatch){const s=e.feeEstimate??await e.execution.estimate(t,n,0n,o),r=Tl(e,s);r&&(t=e.buildWithdrawBatches(r));const a=s.intents[0]?.batches.find(i=>i.chainId===e.chainId)??s.intents[0]?.batches[0]??null;a&&e.ui.setLockedGasFee(io(a).totalFee)}else{const s=(e.feeEstimate??await e.execution.estimate(t,n,0n,o)).intents[0]?.batches[0]??null;s&&e.ui.setLockedGasFee(io(s).totalFee)}await e.execution.execute(t,n,0n,s=>{s.actionId&&s.intentId&&typeof s.intentIndex=="number"&&typeof s.totalSteps=="number"&&(e.executionContextRef.current={actionId:s.actionId,intentId:s.intentId,intentIndex:s.intentIndex,totalSteps:s.totalSteps}),e.ui.setExecutionProgress(s)},void 0,e.buildSpicenetBatch?{...o,adjustBatchesForEstimate:({feeEstimate:s,chainBatches:r})=>Dp(e,s,r)}:{...o,skipPreSubmitFeeEstimate:!0})}Dl(e)}catch(t){const n=t instanceof Error?t.message:"Withdraw failed";e.ui.setExecutionError(n)}finally{e.ui.setIsExecuting(!1)}}}function Dl(e){window.dispatchEvent(new CustomEvent("withdraw-completed")),e.onWithdrawSuccess?.({token:e.token?.symbol||"",amount:e.amount,chainId:e.chainId})}async function Op(e){const t=e.executionContextRef.current;if(!t){e.ui.setExecutionProgress(null),await Bl(e);return}e.ui.setIsExecuting(!0),e.ui.setExecutionError(null),e.ui.setExecutionProgress({step:"executing",message:"Resuming existing action...",actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps});try{let n=t.totalSteps;for(let o=0;o<t.totalSteps;o++)if((await Lt.checkStepStatus(t.intentId,o)).data.status!=="success"){n=o;break}if(n>=t.totalSteps)e.ui.setExecutionProgress(o=>({...o||{step:"success",message:"Transaction successful!",actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps},step:"success",message:"Transaction successful!"}));else for(let o=n;o<t.totalSteps;o++){const s=await el({actionId:t.actionId,intentIndex:t.intentIndex,intentId:t.intentId,stepIndex:o,chainId:e.chainId??void 0,onStatusMessage:(r,a)=>{e.isMountedRef.current&&e.ui.setExecutionProgress({step:"executing",message:r,txHash:a,actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps})}});if(!e.isMountedRef.current)return;e.ui.setExecutionProgress({step:o===t.totalSteps-1?"success":"executing",message:o===t.totalSteps-1?"Transaction successful!":"Executing remaining steps...",txHash:s,actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps})}Dl(e)}catch(n){const o=n instanceof Error?n.message:"Withdraw failed";e.ui.setExecutionError(o)}finally{e.ui.setIsExecuting(!1)}}async function Rp(e){const t=await e.estimate(e.batches,e.tokenAddress,0n,{useCustomTransfers:!0,signal:e.signal}),n=t.intents.flatMap(s=>s.batches).filter(s=>io(s).totalFee>0n),o=n.filter(s=>s.chainId===e.chainId)[0]??n[0]??t.intents[0]?.batches[0];if(!o)throw new Error("No gas fee estimate was returned for this withdraw.");return{gasFee:io(o).totalFee,feeEstimate:t}}function na(e,t){return Fe(e,t).replace(/(\.\d*?[1-9])0+$|\.0+$/,"$1")}function Mp(e,t,n){return xn(e,t,n,"floor")}function Ol(e,t,n=!1){if(e<=0)return"$0";if(!t||!Number.isFinite(t)||t<=0)return"\u2014";const o=e*t;return`$${o>=1?o.toFixed(3).replace(/0+$/,"").replace(/\.$/,""):o.toFixed(4).replace(/0+$/,"").replace(/\.$/,"")}${n?" (stale)":""}`}function Wp(e,t){return t?JSON.stringify({tokenAddress:t.toLowerCase(),batches:e.map(n=>({chainId:n.chainId,calls:n.calls.map(o=>({to:o.to.toLowerCase(),value:o.value.toString(),data:o.data})),tokenTransfers:(n.tokenTransfers??[]).map(o=>({from:o.from,to:o.to.toLowerCase(),token:o.token.toLowerCase(),amount:o.amount.toString()}))}))}):null}function Rl(e,t,n){const o=n.filter(s=>s.amount>0n);return{chainId:e,domain:"evm",tokenTransfers:[],calls:be(t)?o.map(s=>({to:s.recipient,value:s.amount,data:"0x"})):o.map(s=>({to:t,value:0n,data:xt({abi:tt,functionName:"transfer",args:[s.recipient,s.amount]})}))}}new Set([nn,Fn].map(e=>e.toLowerCase()));function Np(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const o=zt(n.token),s=zt(n.to),r=`${o.toLowerCase()}:${s.toLowerCase()}`,a=t.get(r);a?a.amount+=n.amount:t.set(r,{token:o,to:s,amount:n.amount})}return[...t.values()]}function Pp(e,t){return`0x${t}${e.slice(4)}`}function Ml(e,t,n,o){if(e.some(d=>d.domain==="spicenet"))return e;const s=n?.intents.flatMap(d=>d.batches),r=d=>d.from==="escrow",a=e.map(d=>{const p=s?.find(S=>S.chainId===d.chainId);if(!p)return d;const f=io(p),h=f.totalFee;if(h<=0n)return d;const m=(d.tokenTransfers??[]).filter(S=>r(S)&&zt(S.to).toLowerCase()===t.toLowerCase()),g=m.find(S=>!be(zt(S.token)))??m[0];if(!g)return d;const y=zt(g.token),w=be(y);let x=!1;const v=(d.tokenTransfers??[]).map(S=>x||!r(S)||zt(S.to).toLowerCase()!==t.toLowerCase()||zt(S.token).toLowerCase()!==y.toLowerCase()?S:(x=!0,{...S,amount:o?.payoutAlreadyGross?BigInt(S.amount):BigInt(S.amount)+h}));if(!x)return d;const k=(S,T)=>w?{to:S,value:T,data:"0x"}:{to:y,value:0n,data:xt({abi:tt,functionName:"transfer",args:[S,T]})},A=[];f.spicenetFee>0n&&A.push(k(Fn,f.spicenetFee));const b=f.gasFee+f.bridgeFee;return b>0n&&A.push(k(nn,b)),{...d,tokenTransfers:v,calls:[...A,...d.calls]}}),i=a.flatMap(d=>(d.tokenTransfers??[]).filter(r).map(p=>{const f=zt(p.token),h=zt(p.to),m=[{token:f,to:h,amount:BigInt(p.amount)}];return{chainId:d.chainId,transfers:Np(m)}}));if(i.length===0)return e;const l=o?.requestTimestampMs??Date.now(),c=BigInt(Math.floor(l/1e3))+3600n;return[{chainId:Pa,domain:"spicenet",tokenTransfers:[],calls:i.map((d,p)=>{const f=vo(zn([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,d.transfers[0].token,d.transfers.reduce((m,g)=>m+g.amount,0n),BigInt(d.chainId),BigInt(l+p)])),h=Pp(f,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:xt({abi:ar,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${d.chainId}`,idempotenceKey:h,nbf:0n,exp:c,metadata:"{}",transfers:d.transfers.map(m=>({token:m.token.toLowerCase(),to:m.to,amount:m.amount}))}]})}})},...a]}function mo(e,t,n,o){const s=e.filter(a=>a.domain!=="spicenet"),r=a=>(a.tokenTransfers??[]).some(i=>i.from==="escrow");return[...s.filter(a=>!r(a)),...Ml(s.filter(r),t,n,o)]}class To extends Error{constructor(t,n){super("The selected balance cannot cover the fee funding amount"),this.requiredAmount=t,this.balance=n,this.name="InsufficientFeeFundingBalanceError"}}function oa(e,t,n,o,s){const r=e[e.length-1];if(!r?.calls.length||r.domain==="spicenet")throw new Error("Proceeds fees require a final destination action");const a=[{to:Fn,amount:s},{to:nn,amount:o}].filter(i=>i.amount>0n);return e.map(i=>i===r?{...i,calls:[...i.calls,...a.map(l=>({to:n,value:0n,data:xt({abi:tt,functionName:"transfer",args:[l.to,l.amount]})}))],tokenTransfers:[...i.tokenTransfers??[],...a.map(l=>({from:t,to:l.to,token:n,amount:l.amount}))]}:i)}async function Wl(e,t,n,o,s){const r=$n(e),a=await Lt.estimateBatchGas({user:t,outputToken:n,signal:o,requireSimulation:!0,includePlatformFee:s!==void 0,chainBatches:e.map((i,l)=>({...i,hash:r[l].hash}))});if(a.gasQuoteSource!=="estimated"||!a.simulationVerified)throw new Error("Action proceeds require a successful live batch simulation; fallback gas pricing is not sufficient");if(s!==void 0&&(a.platformFee===void 0||a.platformFee>s))throw new Error("Fee conversion platform price changed; refresh before retrying");return a.gasFee}async function Nl(e){if(e.proceeds.token.toLowerCase()!==e.token.toLowerCase())throw new Error("Action proceeds must use the destination fee token");const t=await e.proceeds.resolve(e.signal);if(e.signal?.aborted)throw new Error("Action proceeds quote was cancelled");if(t<0n)throw new Error("Action proceeds cannot be negative");const n=await e.baseline();if(!n?.preview)throw new Error("Action fee quote is unavailable");let o=n.preview.gasFee;const s=n.preview.spicenetFee,r=n.preview.bridgeFee??0n;for(let a=0;a<5;a++){const i=o+s+r,l=t<i?t:i,c=i-l;if(c>0n&&e.fundShortfall===!1)throw new To(i,t);const d=c>0n?(c*110n+99n)/100n+2n:0n;let p=d,f;const h=mo(await e.buildBatches(d,{actionAmountOverride:e.actionAmountFor?.(i),onSourceSpend:y=>{p=y},onActionCalls:y=>{f=y}}),e.owner),m=oa(h,e.owner,e.token,o+r,s),g=await Wl(m,e.owner,e.token,e.signal);if(g<=o&&(o-g)*100n<=g*15n)return{preview:{...n.preview,grossAmount:d,netAmount:0n,gasFee:o,totalFee:i,gasQuoteSource:"estimated"},feeEstimate:n.feeEstimate,grossFundingAmount:d,proceedsAvailable:t,proceedsUsed:l,fundingBatches:m,sourceSpendCap:p,destinationAmount:0n,actionDefinition:f};o=g}throw new Error("Action proceeds fee estimate did not converge")}function Pl(e,t){let n,o;if(be(t)){if(e.data!=="0x")return null;n=e.to,o=e.value}else{if(!ge(e.to,t))return null;try{const s=uo({abi:tt,data:e.data});if(s.functionName!=="transfer")return null;[n,o]=s.args}catch{return null}}return ge(n,nn)?{gas:o,platform:0n}:ge(n,Fn)?{gas:0n,platform:o}:null}async function Up(e,t,n){const o=yt(e);return be(n)?o.getBalance({address:t}):o.readContract({address:n,abi:tt,functionName:"balanceOf",args:[t]})}function qs(e,t,n){return e.map(o=>o.chainId===t?{...o,calls:o.calls.filter(s=>!Pl(s,n))}:o)}function Ul(e,t,n){if(!e.feeOnlyAction)return{};const o=e.embeddedWalletAddress??e.providerEmbeddedAddress,s=e.feeQuote?.fundingSource,r=s&&s.kind!=="proceeds"?void 0:e.actionProceeds,a=s&&(s.kind==="input"||s.kind==="balance"&&s.asset?._source==="wallet")?s:void 0;if(r||e.feeQuote?.fundingConversion||a){const d=e.feeQuote?.fundingConversion,p=r??{token:t,resolve:async()=>0n},f=e.feeQuote?.preview,h=e.feeQuote?.proceedsUsed,m=d?.fromProceeds?d.tokenIn:t;if(!f||h===void 0||!a&&p.token.toLowerCase()!==m.toLowerCase())throw new Error("Refresh the action proceeds quote");const g=f.gasFee+(f.bridgeFee??0n),y=f.spicenetFee,w=a?async()=>{e.validateFeeQuote?.();const v=await Up(e.resolvedChainId,o,a.token);e.validateFeeQuote?.();const k=a.kind==="input"?a.amount:(d?.amountInMax??h)+(a.reservedAmount??0n);if(e.signal?.aborted||v<k||d&&d.amountOut<g+y)throw new Error("The fee funding balance changed; refresh before retrying");return d?[{chainId:e.resolvedChainId,token:t,amount:d.amountOut}]:[]}:async()=>{e.validateFeeQuote?.();const v=await p.resolve(e.signal);if(e.validateFeeQuote?.(),e.signal?.aborted||(d?.fromProceeds?v<d.amountInMax||d.amountOut<g+y:v<h||v+(d?.amountOut??n)<g+y))throw new Error("Action proceeds changed; refresh before retrying");return d?.fromProceeds?[{chainId:e.resolvedChainId,token:d.tokenIn,amount:d.amountInMax},{chainId:e.resolvedChainId,token:t,amount:d.amountOut}]:[{chainId:e.resolvedChainId,token:t,amount:h+(d?.amountOut??0n)}]},x=async v=>{await w();const k=await Wl(v,o,t,e.signal,d?y:void 0);if(await w(),(k>f.gasFee?k-f.gasFee:f.gasFee-k)*100n>k*15n)throw new Error("Action gas quote changed; refresh before retrying")};return{resolveActionOutputCredits:w,prepareForSigning:async v=>{const k=qs(v,e.resolvedChainId,t).map(b=>({...b,tokenTransfers:b.tokenTransfers?.filter(S=>!(typeof S.from=="string"&&ge(S.from,o)&&(ge(S.to,nn)||ge(S.to,Fn))))})),A=oa(k,o,t,g,y);return await x(A),A},validateBeforeSubmit:x}}const i=Ft(t,e.resolvedChainId),l={chainId:e.resolvedChainId,tokenAddress:t,symbol:i?.symbol??e.destinationToken.symbol,decimals:e.executionTokenDecimals??i?.decimals??e.destinationToken.decimals},c=async d=>{e.validateFeeQuote?.();const p=qs(d,e.resolvedChainId,t),f=await e.execution.estimate(p,t,n,{userOverride:o,useCustomTransfers:!0,feeExecutionMode:"backend-transfer"});e.validateFeeQuote?.();const h=Xn(f,l);if(!h||h.chainId!==e.resolvedChainId)throw new Error("The fee service did not return the destination action's fee quote");if(h.gasFee+h.spicenetFee+(h.bridgeFee??0n)+2n>n)throw new Error("Fees exceed the displayed maximum funding; refresh the quote before retrying");return{raw:p,feeEstimate:f,fees:h}};return{prepareForSigning:async d=>{const{raw:p,feeEstimate:f}=await c(d);return mo(p,o,f,{payoutAlreadyGross:!0})},validateBeforeSubmit:async d=>{const{fees:p}=await c(d);let f=0n,h=0n;for(const g of d)if(g.chainId===e.resolvedChainId)for(const y of g.calls){const w=Pl(y,t);w&&(f+=w.gas,h+=w.platform)}if(f+h+2n>n)throw new Error("Signed fees exceed the displayed maximum funding");const m=p.gasFee+(p.bridgeFee??0n);if((f>m?f-m:m-f)*100n>m*15n||h!==p.spicenetFee)throw new Error("The signed gas quote changed materially; refresh before retrying")}}}const Lp="0xa9059cbb";function _o(e,t,n){return be(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:xt({abi:tt,functionName:"transfer",args:[n,t]})}}function Ll(e,t,n){return{chainId:n,calls:[_o(e,t,Jn(n))]}}function zp(e,t,n,o){const s=t.source.chainId;return{chainId:s,calls:[...e.calls,_o(t.source.address,n,Jn(s)),...o>0n?[_o(t.source.address,o,nn)]:[]]}}function zl(e,t){const n=e.amountOutMinimum-t;if(n<=0n)throw new Error("Amount is too small to cover fees. Increase the amount and retry.");return n}function Hl(e,t,n){return e?.asset?._source==="wallet"&&e?.asset.chainId===n}function ql(e){return e.isNative||be(e.address)?!0:!Ft(e.address,e.chainId)}function Vl(e,t,n,o){return t!=="user-transfer"||!n||e.length===0||e[0]?.to.toLowerCase()!==o.toLowerCase()||!e[0]?.data.startsWith(Lp)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function es(e,t,n,o){const s=await(t??Hs)({...n,requestTimestampMs:o});return s?[s,e]:[e]}function Hp(e){return e.filter(t=>t.domain!=="spicenet")}function ts(e,t){const n=(e.tokenTransfers??[]).filter(o=>o.from==="escrow").map(o=>({token:Ye(o.token),recipient:o.to,amount:BigInt(o.amount)})).filter(o=>o.amount>0n);return t!==void 0&&n.length===1&&(n[0]={...n[0],amount:t}),n.length>0?n:void 0}function Bo(e,t,n){return xn(e,t,n,"ceil")}function Ql(e){const t=e.selectedAsset?.asset;return e.isPayMode&&!!t&&t._source==="wallet"&&t.chainId!==e.resolvedChainId&&!!e.pivot}function sa(e){const t=e.selectedAsset?.asset;return!e.isPayMode&&!!t&&t._source==="wallet"&&t.chainId!==e.resolvedChainId&&!!e.sourceSwap&&!!e.pivot}function Vs(e,t){if(t?.sourceSpendCap!==void 0&&e>t.sourceSpendCap)throw new Error("The source amount increased. Review the updated quote before submitting.");t?.onSourceSpend?.(e)}async function jl(e,t,n){let o;const s=await e({...t,buildActionCalls:async(r,a)=>{o=r;const i=await t.buildActionCalls(r,a);return n?.onActionCalls?.({amount:r,context:a,calls:i}),i}},n);if(o!==void 0){if(n?.minimumDestinationAmount!==void 0&&o<n.minimumDestinationAmount)throw new Error("The destination amount decreased. Review the refreshed quote before submitting.");n?.onDestinationAmount?.(o)}return s}const Qs=(e,t)=>jl(qp,e,t),js=async(e,t)=>{const n=await jl(Vp,e,t),o=t?.actionContextOverride?.feeBreakdown,s=n[n.length-1];if(e.feeExecutionMode!=="user-transfer"||!o||!s)return n;const r=e.needsSwap&&e.resolvedTokenIn?e.resolvedTokenIn:e.destinationToken.address,[a]=qs([s],e.resolvedChainId,r),i=Rl(e.resolvedChainId,r,[{recipient:Fn,amount:o.spicenetFee},{recipient:nn,amount:o.gasFee+(o.bridgeFee??0n)}]).calls,l=s.calls.filter(c=>!a.calls.includes(c));return l.length===i.length&&i.every(c=>l.some(d=>d.to.toLowerCase()===c.to.toLowerCase()&&d.value===c.value&&d.data===c.data))?n:[...n.slice(0,-1),{...a,calls:[...i,...a.calls]}]};async function qp(e,t){const{currentPaymentAmount:n,destinationToken:o,embeddedWalletAddress:s,providerEmbeddedAddress:r,address:a,isNon7702:i,resolvedChainId:l,buildActionCalls:c,feeExecutionMode:d,buildSpicenetBatch:p,needsSwap:f,exactOutputSwap:h,resolvedTokenIn:m,requestTimestampMs:g}=e,y=t?.sourceAssetOverride?{asset:t.sourceAssetOverride}:e.selectedAsset,w=t?.fundingTokenOverride??m,x=dn(n,o.decimals),v=t?.actionAmountOverride??(e.feeOnlyAction?0n:x),k=!!e.feeOnlyAction&&(t?.fundingAmountOverride??0n)>0n,A=s||r||a;if(!A)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const b={userAddress:e.recipient??A,executorAddress:A,beneficiary:e.recipient??A,outputRecipient:f?A:void 0,chainId:l,destinationToken:o.address,grossAmount:t?.fundingAmountOverride??x,netAmount:v,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:d,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},S=await c(v,b),T={chainId:l,calls:S},E=!!y&&y.asset._source!=="wallet",I=Hl(y??null,i,l),M=E||I&&!!y&&!ql(y.asset),W=(F,N)=>({token:Ye(F),from:"escrow",to:A,amount:N}),R=(F,N,D)=>I?[Ll(F,N,l),...D]:D;if(x===0n&&!k)return[T];if(y?.asset._source==="wallet"&&y.asset.chainId!==l&&!e.pivot)throw new Error("A current source-to-destination funding route is required");if(e.feeOnlyAction&&t?.fundingTokenOverride&&I)return Vs(t.fundingAmountOverride??0n,t),[T];if(Ql(e)){if(f&&!h)throw new Error("Swap quote not available yet");const F=t?.fundingAmountOverride??(h?h.amountInMax:x),N=t?.sourceGasSkimOverride??0n,D=xn(F,e.pivot.destination.decimals,e.pivot.source.decimals,"ceil"),L=D+N,z=e.sourceExactOutputSwap,fe=z&&(t?.reuseQuotedSourceSwap||z.amountOut>=L)?z:e.resolveSourceExactOutputSwap?await e.resolveSourceExactOutputSwap(L):null;if(!fe)throw new Error("Swap quote not available yet");Vs(fe.amountInMax,t);const ce=y.asset;if(fe.amountInMax>ce.balance)throw new Error(`Insufficient ${ce.symbol} for this payment. Required ${Fe(fe.amountInMax,ce.decimals)} ${ce.symbol}; available ${Fe(ce.balance,ce.decimals)} ${ce.symbol}.`);const Q=fe.amountOut>=L?D:fe.amountOut-N;if(Q<=0n)throw new Error("Amount is too small to cover fees. Increase the amount and retry.");const ne={chainId:e.pivot.source.chainId,calls:[...fe.calls,_o(e.pivot.source.address,Q,Jn(e.pivot.source.chainId)),...N>0n?[_o(e.pivot.source.address,N,nn)]:[]]},re={chainId:l,calls:[...h?.calls??[],...S],tokenTransfers:[W(e.pivot.destination.address,F),...T.tokenTransfers??[]]},j=await es(re,p,{userAddress:A,destinationChainId:l,deliveryToken:e.pivot.destination.address,deliveryAmount:F,deliveryRecipient:A,deliveryTransfers:ts(re),sourceAsset:y.asset},g);return[ne,...j]}if(y){const F=t?.fundingAmountOverride??h?.amountInMax??x;Vs(Bo(F,await eo(y.asset,w??y.asset.address,l,o),y.asset.decimals),t)}if(f&&h){const F=w??Sn(y.asset,l)??y.asset.address,N=t?.fundingAmountOverride??h.amountInMax,D=M?[W(F,N)]:[],L={chainId:l,calls:[...h.calls,...S],tokenTransfers:[...D,...T.tokenTransfers??[]]};if(!M)return[L];const z=await es(L,p,{userAddress:A,destinationChainId:l,deliveryToken:F,deliveryAmount:N,deliveryRecipient:A,deliveryTransfers:ts(L),sourceAsset:y.asset},g);return R(F,N,z)}if(M){const F=w??Sn(y.asset,l)??o.address;if(I&&!e.feeOnlyAction&&F.toLowerCase()===o.address.toLowerCase())return[T];const N=t?.fundingAmountOverride??x,D={...T,tokenTransfers:[W(F,N),...T.tokenTransfers??[]]},L=await es(D,p,{userAddress:A,destinationChainId:l,deliveryToken:F,deliveryAmount:N,deliveryRecipient:A,deliveryTransfers:ts(D),sourceAsset:y.asset},g);return R(F,N,L)}return[T]}async function Vp(e,t){const{selectedAsset:n,embeddedWalletAddress:o,recipient:s,resolvedChainId:r,destinationToken:a,buildActionCalls:i,feeExecutionMode:l,buildSpicenetBatch:c,isPayMode:d,isNon7702:p,needsSwap:f,resolvedSwap:h,quoteAmountOut:m,resolvedTokenIn:g,requestTimestampMs:y}=e;if(!n?.asset||!o)return[];const w=s??o;if(!w)return[];const x=sa(e);let v=e.sourceSwap,k=dn(n.amount,n.asset.decimals),A=x?e.sourceSwap.amountOutMinimum:null;if(x&&e.isFeeInclusiveInput&&(A=zl(e.sourceSwap,t?.sourceGasSkimOverride??0n)),x&&!e.isFeeInclusiveInput&&(t?.fundingAmountOverride!==void 0||(t?.sourceGasSkimOverride??0n)>0n)){A=t?.fundingAmountOverride!==void 0?Bo(t.fundingAmountOverride,e.pivot.destination.decimals,e.pivot.source.decimals):e.sourceSwap.amountOutMinimum;const Y=A+(t?.sourceGasSkimOverride??0n);if(!e.resolveSourceExactOutputSwap)throw new Error("The source quote cannot include fees yet.");const me=await e.resolveSourceExactOutputSwap(Y);if(me.amountOut<Y)throw new Error("The source quote does not cover the accepted funding amount.");k=me.amountInMax,v={...me,amountOutMinimum:me.amountOut}}const b=x?e.pivot.destination.address:g??Sn(n.asset,r)??a.address,S=x?e.pivot.destination.decimals:await eo(n.asset,b,r,a),T=t?.fundingAmountOverride??t?.actionAmountOverride??(x?xn(A,e.pivot.source.decimals,S,"floor"):zs(dn(n.amount,n.asset.decimals),n.asset.decimals,S)),E=t?.fundingAmountOverride??T,I=t?.sourceFundingAmountOverride??Bo(T,S,n.asset.decimals);Vs(x?k:I,t);const M=t?.deliveryAmountOverride??(l==="user-transfer"?E:t?.actionContextOverride?.netAmount??E),W=t?.withdrawalAmountOverride??M,R=t?.actionAmountOverride??t?.actionContextOverride?.netAmount??T;let F=h;if(f&&!d&&(t?.actionContextOverride?.netAmount!==void 0||x&&(t?.sourceGasSkimOverride??0n)>0n&&!t?.reuseQuotedSourceSwap)){if(!e.resolveInputSwap)throw new Error("Swap quote cannot be refreshed for the amount after fees.");const Y=t?.actionContextOverride?.netAmount??R;(!F||e.swapInputAmount!==Y)&&(F=await e.resolveInputSwap(Y,h??void 0))}F&&t?.onSwap?.(F,t?.actionContextOverride?.netAmount??e.swapInputAmount??R);const N=F?.amountOutMinimum??m,D={userAddress:w,executorAddress:o,beneficiary:w,outputRecipient:f?o:void 0,chainId:r,destinationToken:a.address,feeToken:l==="user-transfer"&&f&&g?g:a.address,grossAmount:E,netAmount:R,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:l,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},L=()=>i(R,D),z=n.asset?._source==="wallet";if(!d&&z&&n.asset.chainId===r&&ql(n.asset)){if(f){if(!g)throw new Error("Swap input token could not be resolved");if(!F||N===null)throw new Error("Swap quote not available yet")}if(f&&F&&N){const Y=await i(t?.actionAmountOverride??N,{...D,netAmount:t?.actionAmountOverride??N}),{feeCall:me,remainingCalls:B}=Vl(Y,l,f,D.feeToken);return[{chainId:r,calls:[...me?[me]:[],...F.calls,...B]}]}return[{chainId:r,calls:await L()}]}if(!d&&z&&n.asset.chainId!==r&&!x)throw new Error("A current source-to-destination funding route is required");const fe=n.asset._source!=="wallet",ce=Hl(n,p,r);if(!(fe||ce||x))return[{chainId:r,calls:await L()}];const Q=x?zp(v,e.pivot,A,t?.sourceGasSkimOverride??0n):ce?Ll(g??Ye(n.asset.address),I,r):null,ne=(Y,me)=>({token:Ye(Y),from:"escrow",to:o,amount:me});if(f){if(!g)throw new Error("Swap input token could not be resolved");if(!F||N===null)throw new Error("Swap quote not available yet")}if(f&&F&&N&&g){const Y=await i(t?.actionAmountOverride??N,{...D,netAmount:t?.actionAmountOverride??N}),{feeCall:me,remainingCalls:B}=Vl(Y,l,f,D.feeToken),U={chainId:r,calls:[...me?[me]:[],...F.calls,...B],tokenTransfers:[ne(g,M)]},X=await es(U,c,{userAddress:o,destinationChainId:r,deliveryToken:g,deliveryAmount:M,withdrawalAmount:W,deliveryRecipient:o,deliveryTransfers:ts(U,W),sourceAsset:n.asset},y);return Q?[Q,...X]:X}const re=g??Sn(n.asset,r)??a.address,j={chainId:r,calls:await L(),tokenTransfers:[ne(re,M)]},J=await es(j,c,{userAddress:o,destinationChainId:r,deliveryToken:re,deliveryAmount:M,withdrawalAmount:W,deliveryRecipient:o,deliveryTransfers:ts(j,W),sourceAsset:n.asset},y);return Q?[Q,...J]:J}async function Qp(e,t,n,o,s){let r=e;for(let a=0;a<4;a++){const i=await t(r),l=await o(i,n,r,s),c=zc(l);if(c===null||c>=e)return r;const d=r-c,p=e+d;if(p<=r)return r;r=p}return r}function jp(e){return{...e,resolve:async(t,n,o)=>{const s=await e.resolve(t,n,o),r=s?.calls[0]?.to;return!s||!r||be(t.tokenIn)?s:{...s,calls:[{to:t.tokenIn,value:0n,data:xt({abi:tt,functionName:"approve",args:[r,s.amountInMax]})},...s.calls]}}}}function Gs(e){const t=(e?.customVenues??[]).map(o=>md(jp(o)));async function n(o,s,r){const a=t.filter(c=>c.chainIds.includes(s));if(a.length===0)throw new Ne("NO_SWAP_ROUTE",`No exact-output venue supports chain ${s}`,{chainId:s,tokenIn:o.tokenIn,tokenOut:o.tokenOut});const i=(await Promise.allSettled(a.map(async c=>({venue:c,quote:await c.resolve(o,s,r)})))).filter(c=>c.status==="fulfilled").map(c=>c.value).filter(c=>c.quote!==null);if(i.length===0)throw new Ne("NO_SWAP_ROUTE",`All aggregators failed for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${s}`,{chainId:s,tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountOut:o.amountOut.toString()});const l=i.find(c=>c.venue.preferred);return l?l.quote:(i.sort((c,d)=>c.quote.amountIn<d.quote.amountIn?-1:c.quote.amountIn>d.quote.amountIn?1:0),i[0].quote)}return{getQuote:n,venues:t}}function Gl(e,t,n){if(e._source==="wallet")return e.chainId===t?e.address:null;const o=ko(e,t);return o.find(s=>s.toLowerCase()===n.toLowerCase())??o[0]??null}async function Yl(e,t,n,o){const s=$n(o),r=await Lt.estimateBatchGas({user:t,outputToken:n,requireSimulation:!0,includePlatformFee:!0,signal:e.signal,chainBatches:o.map((a,i)=>({...a,hash:s[i].hash}))});if(!r.simulationVerified||r.gasQuoteSource!=="estimated"||r.platformFee===void 0||r.gasFee<=0n)throw new Error("Fee funding requires verified gas and platform pricing");return r}async function ns(e,t){const n=e.selectedAsset?.asset,o=!t&&!!e.actionProceeds&&e.actionProceeds.token.toLowerCase()!==e.destinationToken.address.toLowerCase(),s=!!t||o,r=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!r||!s&&(!n||n._source!=="spice"&&!(n._source==="wallet"&&n.chainId===e.resolvedChainId)))throw new Error("A local embedded or Spice balance is required for fee conversion");const a=t?t.token:o?e.actionProceeds.token:Gl(n,e.resolvedChainId,e.destinationToken.address);if(!a)throw new Error("This receipt has no registered destination withdrawal token");const i=Ft(a,e.resolvedChainId)?.decimals??(be(a)?18:s?await yt(e.resolvedChainId).readContract({address:a,abi:tt,functionName:"decimals"}):n?._source==="wallet"?n.decimals:void 0);if(i===void 0)throw new Error("Fee funding token metadata is unavailable");const l=e.destinationToken.address;if(e.actionProceeds&&!o&&e.actionProceeds.token.toLowerCase()!==l.toLowerCase())throw new Error("Action proceeds must use the destination fee token");const c=t?t.amount:e.actionProceeds?await e.actionProceeds.resolve(e.signal):0n;if(c<0n||e.signal?.aborted)throw new Error("Action proceeds quote was cancelled or invalid");const d=Gs({customVenues:[...e.resolveExactOutputSwap?[{name:"consumer-exact-output",chainIds:[e.resolvedChainId],preferred:!0,resolve:e.resolveExactOutputSwap}]:[],...Co(e.liquidityVenues).output]}),p=h=>Yl(e,r,l,h);let f=await p(await e.buildPayChainBatches({fundingAmountOverride:0n}));for(let h=0;h<8;h++){const m=f.gasFee+f.platformFee,g=s?0n:c<m?c:m,y=m-g,w=y>0n?(y*110n+99n)/100n+2n:0n,x=w>0n?await d.getQuote({tokenIn:a,tokenOut:l,amountOut:w,maxSlippage:e.maxSlippage},e.resolvedChainId,r):null;if(e.signal?.aborted)throw new Error("Fee conversion quote was cancelled");if(x&&(x.amountOut!==w||x.amountInMax<=0n||x.amountInMax<x.amountIn||!x.calls.length))throw new Error("Invalid exact-output fee conversion quote");const v=x?.amountInMax??0n,k=s?0n:Bo(v,i,n.decimals);if(s&&v>c)throw new To(v,c);if(!s&&k>n.balance)throw new To(k,n.balance);let A,b=mo(await e.buildPayChainBatches({fundingAmountOverride:s?0n:v,...s?{}:{fundingTokenOverride:a},...t?{actionAmountOverride:t.amount-v}:{},onActionCalls:T=>{A=T}}),r);if(x){const T=b.length-1;b=b.map((E,I)=>I===T?{...E,calls:[...E.calls,...x.calls]}:E)}b=oa(b,r,l,f.gasFee,f.platformFee);const S=await p(b);if(S.gasFee<=f.gasFee&&(f.gasFee-S.gasFee)*100n<=S.gasFee*15n&&S.platformFee===f.platformFee){const T={tokenIn:a,tokenOut:l,amountInMax:v,amountOut:w,sourceAmountMax:k,...o?{fromProceeds:!0}:{},...t?{fromInput:!0}:{}};return{feeEstimate:null,preview:{symbol:e.destinationToken.symbol,decimals:e.destinationToken.decimals,grossAmount:s?0n:w,netAmount:0n,gasFee:f.gasFee,spicenetFee:f.platformFee,totalFee:m,gasQuoteSource:"estimated"},grossFundingAmount:s?0n:v,proceedsAvailable:c,proceedsUsed:s?m:g,fundingConversion:T,fundingBatches:b,sourceSpendCap:k,destinationAmount:0n,actionDefinition:A}}f=S}throw new Error("Fee conversion pricing did not converge")}const ra=["input","proceeds","balance"];function Gp(e){if(e.reserve&&e.reserve.amount<0n)throw new Error("Fee funding reserve cannot be negative");const t=i=>ge(i,e.feeToken),n=(i,l)=>Number(i.swap)-Number(l.swap),o={input:[],proceeds:[],balance:[]};for(const i of e.inputs??[])i.amount>0n&&o.input.push({kind:"input",...i,swap:!t(i.token)});o.input.sort(n),e.proceeds&&e.proceeds.amount>0n&&o.proceeds.push({kind:"proceeds",...e.proceeds,swap:!t(e.proceeds.token)});const s=e.balances.filter(i=>i._source==="wallet"&&i.chainId===e.chainId&&i.location!=="external"),r=e.balances.filter(i=>i._source==="spice"),a=i=>{const l=[];for(const c of i){const d=e.reserve&&nt(c)===nt(e.reserve.asset)?e.reserve.amount:0n,p=c.balance-d;if(p<=0n)continue;const f=d>0n?{...c,balance:p,balanceFormatted:Number(Fe(p,c.decimals)),balanceUsd:c.balanceUsd*Number(p)/Number(c.balance)}:c,h=Gl(f,e.chainId,e.feeToken);h&&(e.inputs?.some(m=>ge(m.token,h)&&!(e.reserve&&ge(e.reserve.asset.address,m.token)))||l.push({kind:"balance",token:h,amount:f.balance,asset:f,...d>0n?{reservedAmount:d}:{},swap:!t(h)}))}return l.sort((c,d)=>n(c,d)||d.asset.balanceUsd-c.asset.balanceUsd)};return o.balance=[...a(s),...a(r)],(e.order??ra).flatMap(i=>o[i])}function Yp(e){return e instanceof To||e instanceof Ne&&e.code==="NO_SWAP_ROUTE"}async function Kl(e,t){const n=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!n||!e.ready||!e.authenticated)return null;const o=e.destinationToken.address;let s;const r=()=>s??(s=(async()=>{const c=await Yl(e,n,o,await e.buildPayChainBatches({fundingAmountOverride:0n}));return{feeEstimate:null,preview:{symbol:e.destinationToken.symbol,decimals:e.destinationToken.decimals,gasFee:c.gasFee,spicenetFee:c.platformFee,bridgeFee:0n,totalFee:c.gasFee+c.platformFee,grossAmount:0n,netAmount:0n,gasQuoteSource:"estimated"}}})()),a=(c,d)=>e.buildPayChainBatches({...d,fundingAmountOverride:c}),i=(c,d)=>Nl({proceeds:{token:o,resolve:async()=>c},owner:n,token:o,signal:e.signal,baseline:r,buildBatches:a,fundShortfall:!1,actionAmountFor:d}),l=async c=>{if(c.kind==="input")return c.swap?ns({...e,actionProceeds:void 0},c):i(c.amount,h=>c.amount-h);if(c.kind==="proceeds"){const h={...e.actionProceeds,resolve:async()=>c.amount};return c.swap?ns({...e,actionProceeds:h}):i(c.amount)}const d=c.asset;if(d._source==="wallet"&&!c.swap)return i(d.balance);const p={...e,selectedAsset:{asset:d,amount:"0"},resolvedTokenIn:c.token,actionInput:void 0,actionProceeds:void 0,buildPayChainBatches:h=>e.buildPayChainBatches({...h,sourceAssetOverride:d,fundingTokenOverride:h?.fundingTokenOverride??c.token})};if(c.swap)return ns(p);const f=await t(p);if(f&&(f.sourceSpendCap??0n)>d.balance)throw new To(f.sourceSpendCap,d.balance);return f};for(const c of e.feeFunding??ra){const d=c==="proceeds"&&e.actionProceeds?{token:e.actionProceeds.token,amount:await e.actionProceeds.resolve(e.signal)}:void 0;if(e.signal?.aborted)throw new Error("Fee funding quote was cancelled");if(d&&d.amount<0n)throw new Error("Action proceeds cannot be negative");const p=Gp({feeToken:o,chainId:e.resolvedChainId,inputs:e.actionInput,proceeds:d,balances:e.feeFundingBalances??[],order:[c],reserve:e.feeFundingReserve});for(const f of p)try{const h=await l(f);if(!h)continue;const{swap:m,...g}=f;return{...h,fundingSource:g}}catch(h){if(e.signal?.aborted||!Yp(h))throw h}}throw new Error(`No available balance can cover this action's ${e.destinationToken.symbol} execution cost`)}async function Kp(e,t,n,o=!1){const s=e.selectedAsset,r=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!s||!r||!e.ready||!e.authenticated||e.isQuoting)return null;if(s.asset._source!=="wallet"||s.asset.chainId!==e.resolvedChainId||!Ss(s.asset)&&s.asset.owner&&!ge(s.asset.owner,r))throw new Error("Funded fee hierarchy requires principal on the action chain in the executing wallet.");if(o&&(e.isPayMode||!e.isFeeInclusiveInput||t.recipient&&!ge(t.recipient,r)))throw new Error("Output-funded actions require an input-inclusive amount left in the executing wallet.");if(e.isPayMode&&e.needsSwap&&!e.exactOutputSwap)return null;const a=e.isPayMode?dn(e.currentPaymentAmount,e.destinationToken.decimals):void 0;if(e.isPayMode&&e.needsSwap&&e.exactOutputSwap.amountOut!==a)throw new Error("Wait for the payment quote for the current amount.");const i=gs(e.resolvedChainId).find(y=>y.equivalenceGroup==="USDC");if(!i)throw new Error("Configure the execution fee token for this chain.");const l={...i,address:i.address,chainId:e.resolvedChainId},c=a!==void 0?e.needsSwap?e.exactOutputSwap.amountInMax:a:dn(s.amount,s.asset.decimals);if(c<=0n||c>s.asset.balance)throw new Error("Enter an amount within the available balance.");if(!e.isPayMode&&e.needsSwap&&t.swapInputAmount!=null&&t.swapInputAmount!==c)throw new Error("Wait for the action quote for the current amount.");const d=a??(e.needsSwap?t.resolvedSwap?.amountOutMinimum??0n:c);let p=t.resolvedSwap??void 0,f=c,h=d;const m={...e,feeOnlyAction:!0,selectedAsset:null,isPayMode:!0,isFeeInclusiveInput:!1,parsedAmount:0,currentPaymentAmount:"0",destinationToken:l,resolvedTokenIn:l.address,executionTokenAddress:l.address,needsSwap:!1,resolvedSwap:null,isDirect:!0,actionInput:!e.isPayMode&&e.isFeeInclusiveInput?[{token:s.asset.address,amount:c}]:void 0,actionProceeds:o?{token:e.destinationToken.address,resolve:async()=>d>0n?d-1n:0n}:e.actionProceeds,feeFundingBalances:e.feeFundingBalances?.filter(y=>!y.balanceError&&!(e.feeFundingReserve&&nt(e.feeFundingReserve.asset)!==nt(s.asset)&&nt(y)===nt(e.feeFundingReserve.asset))&&!Ss(y)&&(!y.owner||ge(y.owner,r))),feeFundingReserve:{asset:s.asset,amount:e.feeFundingReserve&&nt(e.feeFundingReserve.asset)===nt(s.asset)&&e.feeFundingReserve.amount>c?e.feeFundingReserve.amount:c},buildPayChainBatches:async y=>{const w=y?.actionAmountOverride??c;if(w<=0n)throw new To(c+1n,c);const x=!e.isPayMode&&e.needsSwap?w===c?t.resolvedSwap:await t.resolveInputSwap?.(w,t.resolvedSwap??void 0):null,v=e.needsSwap?e.isPayMode?e.exactOutputSwap:x:null;if(e.needsSwap&&!v)throw new Error("The action quote is unavailable.");p=x??void 0,f=w,h=a??p?.amountOutMinimum??w;const k={userAddress:t.recipient??r,executorAddress:r,beneficiary:t.recipient??r,outputRecipient:r,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address,grossAmount:d,netAmount:h,feeToken:l.address,feeExecutionMode:"backend-transfer"},A=await t.buildActionCalls(h,k),b={amount:h,context:k,calls:A},S=[...v?.calls??[],...A];return Qs({...t,selectedAsset:null,feeOnlyAction:!0,isPayMode:!0,isFeeInclusiveInput:!1,currentPaymentAmount:"0",destinationToken:l,resolvedTokenIn:l.address,needsSwap:!1,resolvedSwap:null,exactOutputSwap:null,quoteAmountOut:null,feeExecutionMode:"backend-transfer",buildActionCalls:()=>S},{...y,onActionCalls:()=>y?.onActionCalls?.(b)})}},g=await Kl(m,n);if(!g)return null;if(o&&g.fundingSource?.kind==="proceeds"&&(h-=g.fundingConversion?.amountInMax??g.proceedsUsed??0n),h<=0n)throw new Error("Not enough action output remains after execution costs.");return{...g,fundedFeeToken:l,batches:g.fundingBatches??g.batches,destinationSwap:p,swapInputAmount:f,destinationAmount:h,sourceSpendCap:c+(g.fundingSource?.kind==="balance"&&g.fundingSource.asset&&nt(g.fundingSource.asset)===nt(s.asset)?g.fundingConversion?.amountInMax??g.proceedsUsed??0n:0n)}}async function Zp(e){const t=e.selectedAsset.asset;if(t.chainId!==e.destinationToken.chainId||!ge(Ye(t.address),Ye(e.destinationToken.address)))throw new Error("Direct execution requires the destination token on its own chain.");if(t.decimals!==e.destinationToken.decimals)throw new Error("Source and destination token decimals do not match.");const n=dn(e.paymentAmount??e.selectedAsset.amount,t.decimals);if(n<=0n)throw new Error("Enter a positive action amount.");const o={userAddress:e.beneficiary??e.account,executorAddress:e.account,beneficiary:e.beneficiary??e.account,chainId:e.destinationToken.chainId,destinationToken:e.destinationToken.address,feeToken:t.address,grossAmount:n,netAmount:n,combinedFeeAmount:0n,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:0n,gasFee:0n,bridgeFee:0n}},s=await e.buildActionCalls(n,o);if(!s.length)throw new Error("No action calls configured.");if(be(t.address)&&s.reduce((r,a)=>r+a.value,0n)>n)throw new Error("The native action exceeds the accepted source amount.");return{actionDefinition:{amount:n,context:o,calls:s},actionContext:o,batches:[{chainId:o.chainId,calls:s}],fundingAmount:n,sourceSpendCap:n,destinationAmount:n,feeEstimate:null,preview:{symbol:t.symbol,decimals:t.decimals,grossAmount:n,netAmount:n,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}}}async function Zl(e){const[t]=await e.buildSupplyChainBatches({sourceGasSkimOverride:1n,reuseQuotedSourceSwap:!0});if(!t)throw new Error("Swap quote not available yet");const{gasFee:n}=await Lt.estimateBatchGas({user:e.user,outputToken:e.pivot.source.address,stepIndex:0,chainBatches:[t],signal:e.signal});return n}const Xl=(e,t)=>(e+t-1n)/t;function aa(e,t){return e.intents.length===0?t:{...e,intents:e.intents.map(n=>({...n,batches:n.batches.map(o=>{const s=t.intents.find(i=>i.intentIndex===n.intentIndex)?.batches.find(i=>i.chainId===o.chainId);if(!s)return o;const r={...o.feeBreakdown};let a=0n;for(const i of["gasFee","bridgeFee"]){const l=BigInt(r[i]??"0"),c=BigInt(s.feeBreakdown[i]??"0");c>l&&(r[i]=c.toString(),a+=c-l)}return{...o,feeBreakdown:r,totalDebit:(BigInt(o.totalDebit)+a).toString()}})}))}}function Xp(e,t){const n=e.spicenetFee+(e.bridgeFee??0n);return e.grossAmount<=n?t+e.gasFee+n:Xl((t+e.gasFee)*e.grossAmount,e.grossAmount-n)+2n}async function Jl(e){const{requiredNetFunding:t}=e;if(e.feeOnlyAction){const c=e.executionOptions?.userOverride;if(!c||t!==0n)throw new Error("Fee-only estimates require a zero action amount and its embedded executor");let d=1n,p;for(let f=0;f<8;f++){const h=mo(await e.buildBatches(d),c,p,{payoutAlreadyGross:!0}),m=await e.estimate(qs(h,e.tokenDescriptor.chainId,e.fundingToken),e.fundingToken,d,{...e.executionOptions,feeExecutionMode:"backend-transfer"}),g=Xn(m,e.tokenDescriptor);if(!g)throw new Error("The fee service did not return a fee quote for this action");const y=g.gasFee+g.spicenetFee+(g.bridgeFee??0n);if(p&&y+2n<=d)return{preview:{...g,grossAmount:d,netAmount:0n},feeEstimate:m,grossFundingAmount:d};d=(y*110n+99n)/100n+2n,p=m}throw new Error("Fee-only funding did not converge; refresh the fee quote before retrying")}const n=await e.buildBatches(t),o=await e.estimate(n,e.fundingToken,t,e.executionOptions),s=Xn(o,e.tokenDescriptor);if(!s)return{preview:ms(n,e.tokenDescriptor,t),feeEstimate:o,grossFundingAmount:t};const r=Xp(s,t),a=c=>s.grossAmount>0n?Xl(c*r,s.grossAmount):c,i=a(s.spicenetFee),l=a(s.bridgeFee??0n);return{preview:{...s,grossAmount:r,netAmount:t,spicenetFee:i,bridgeFee:l,totalFee:s.gasFee+i+l},feeEstimate:o,grossFundingAmount:r}}async function $l(e){if(e.balance<=0n)throw new Error("No spendable balance remains after source gas.");let t=e.balance;for(let n=0;n<8;n++){const o=await e.planForAmount(t);if(!o||o.sourceSpendCap===void 0||o.sourceSpendCap<=0n)throw new Error("Max requires a current route and fee estimate.");if(o.sourceSpendCap<=e.balance)return No(t,e.decimals);const s=t*e.balance/o.sourceSpendCap;if(s<=0n||s>=t)throw new Error("The balance cannot cover this action and its fees.");t=s}throw new Error("Max fees did not converge. Refresh the quote before retrying.")}async function Jp(e){if(e.isPayMode||e.needsSwap||e.isQuoting||e.pivot||!e.embeddedWalletAddress)return null;const t=e.asset,n=Ft(e.executionTokenAddress,t.chainId);return!n||t.balance<=0n?null:$l({balance:t.balance,decimals:t.decimals,planForAmount:o=>ho({selectedAsset:{asset:t,amount:No(o,t.decimals)},isPayMode:!1,isNon7702:!1,isFeeInclusiveInput:!1,parsedAmount:Number(No(o,t.decimals)),currentPaymentAmount:"0",destinationToken:{...n,address:e.executionTokenAddress,chainId:t.chainId},resolvedChainId:t.chainId,resolvedTokenIn:e.executionTokenAddress,executionTokenAddress:e.executionTokenAddress,embeddedWalletAddress:e.embeddedWalletAddress,providerEmbeddedAddress:e.embeddedWalletAddress,address:e.embeddedWalletAddress,isConnected:!0,ready:!0,authenticated:!0,isDirect:!0,isSourceDestToken:!0,needsSwap:!1,isQuoting:!1,resolvedSwap:null,exactOutputSwap:null,buildPayChainBatches:async()=>[],buildSupplyChainBatches:s=>e.buildSupplyChainBatches({...s,actionAmountOverride:o}),estimate:e.estimate,feeExecutionMode:e.feeExecutionMode})})}async function ho(e){const{signal:t,selectedAsset:n,isPayMode:o,isFeeInclusiveInput:s=!1,parsedAmount:r,needsSwap:a,exactOutputSwap:i,isNon7702:l,currentPaymentAmount:c,destinationToken:d,feeExecutionMode:p,resolvedTokenIn:f,embeddedWalletAddress:h,providerEmbeddedAddress:m,resolvedChainId:g,isConnected:y,address:w,ready:x,authenticated:v,isDirect:k,resolvedSwap:A,sourceSwap:b,pivot:S,isQuoting:T,executionTokenAddress:E,buildPayChainBatches:I,buildSupplyChainBatches:M,estimate:W}=e;if(e.feeOnlyAction&&!n&&e.feeFunding?.length!==0)return Kl(e,ho);if(e.feeOnlyAction&&e.actionProceeds&&e.actionProceeds.token.toLowerCase()!==d.address.toLowerCase()||e.feeOnlyAction&&n&&(n.asset._source==="spice"||n.asset._source==="wallet"&&n.asset.chainId===g)&&(f?f.toLowerCase()!==d.address.toLowerCase():n.asset.receiptTokenId||n.asset.chainTokens))return ns(e);if(e.actionProceeds&&e.feeOnlyAction){const re=h||m;if(!re||!x||!v)return null;if(f&&f.toLowerCase()!==d.address.toLowerCase())throw new Error("Action proceeds require a matching fee-token source");return Nl({proceeds:e.actionProceeds,owner:re,token:d.address,signal:t,buildBatches:(j,J)=>I({...J,fundingAmountOverride:j}),baseline:()=>ho({...e,actionProceeds:void 0,selectedAsset:n??{amount:"0",asset:{...d,name:d.symbol,balance:0n,balanceFormatted:0,balanceUsd:0,isNative:!1,_source:"spice"}}})})}if(!n?.asset)return null;if(o){if(!h&&!m||r<=0&&!e.feeOnlyAction||a&&!i&&!e.feeOnlyAction)return null;const re=dn(c,d.decimals),j=f||Sn(n.asset,g)||n.asset.address||d.address,J={chainId:g,tokenAddress:j,symbol:Ft(j,g)?.symbol??n.asset.symbol,decimals:await eo(n.asset,j,g,d)};if(!y||!w||!x||!v)return null;const Y=h||m||w,me=a?i?.amountInMax??0n:re;if(me===0n&&!e.feeOnlyAction)return null;const B=S?await Zl({user:Y,pivot:S,buildSupplyChainBatches:P=>I({...P,sourceGasSkimOverride:1n}),signal:t}):0n,U=Date.now();let X=await Jl({requiredNetFunding:me,feeOnlyAction:e.feeOnlyAction,buildBatches:P=>I({fundingAmountOverride:P,sourceGasSkimOverride:B}).then(V=>Ml(Hp(V),Y,void 0,{requestTimestampMs:U})),fundingToken:j,estimate:W,executionOptions:{userOverride:Y,useCustomTransfers:!0,feeExecutionMode:p,signal:t},tokenDescriptor:J});if(!X.preview)return null;let pe=0n,de,xe=[],K=!1;for(let P=0;P<8;P++){if(t?.aborted)throw new Error("Fee estimation cancelled");if(xe=mo(await I({fundingAmountOverride:X.grossFundingAmount,sourceGasSkimOverride:B,onSourceSpend:ot=>{pe=ot},onActionCalls:ot=>{de=ot}}),Y,X.feeEstimate,{payoutAlreadyGross:!0,requestTimestampMs:U}),e.feeOnlyAction){K=!0;break}const V=await W(xe,j,X.grossFundingAmount,{userOverride:Y,useCustomTransfers:!0,feeExecutionMode:p,signal:t}),ie=p==="user-transfer"?aa(V,X.feeEstimate):V,ke=Xn(ie,J)??ms(xe,J,me);if(!ke)return null;const Ee=me+ke.gasFee+ke.spicenetFee+(ke.bridgeFee??0n),Be=Xn(X.feeEstimate,J),Ie=(Be?.gasFee??0n)===ke.gasFee&&(Be?.spicenetFee??0n)===ke.spicenetFee&&(Be?.bridgeFee??0n)===(ke.bridgeFee??0n),Z=X.grossFundingAmount===Ee&&Ie;if(X={feeEstimate:ie,grossFundingAmount:Ee,preview:{...ke,grossAmount:Ee,netAmount:me}},Z){K=!0;break}}if(!K)throw new Error("Payment fees did not converge. Refresh the quote before submitting.");if(!X.preview)return null;const G=S?xn(B,S.source.decimals,S.destination.decimals,"ceil"):0n;return{...X,batches:xe,sourceSpendCap:pe,actionDefinition:de,destinationAmount:re,preview:{...X.preview,grossAmount:X.preview.grossAmount+G,gasFee:X.preview.gasFee+G,totalFee:(X.preview.totalFee??0n)+G},...S?{sourceGasSkim:B}:{}}}if(r<=0||!h)return null;const R=h||m;if(S&&!b)return null;const F=sa({isPayMode:o,selectedAsset:n,resolvedChainId:g,sourceSwap:b,pivot:S});if(!(!o&&!l&&n.asset?._source==="wallet"&&n.asset.chainId!==g)&&!k&&!A&&!T||T)return null;let N=await M();if(N.length===0)return null;const D={chainId:g,tokenAddress:E,symbol:Ft(E,g)?.symbol??(n.asset.chainId===g&&ge(n.asset.address,E)?n.asset.symbol:d.symbol),decimals:await eo(n.asset,E,g,d)},L=F&&e.initialFeeEstimate!==void 0&&e.initialSourceGasSkim!==void 0,z=F?L?e.initialSourceGasSkim:await Zl({user:R,pivot:S,buildSupplyChainBatches:M,signal:t}):0n;F&&z>0n&&(N=await M({sourceGasSkimOverride:z}));const fe=F?xn(s?zl(b,z):b.amountOutMinimum,S.source.decimals,S.destination.decimals,"floor"):xn(dn(n.amount,n.asset.decimals),n.asset.decimals,D.decimals,"floor"),ce={userOverride:R,useCustomTransfers:!0,feeExecutionMode:p,signal:t,...F?{skipUserFundingPreflight:!0}:{}};let Q=fe,ne=e.initialFeeEstimate??await W(N,E,Q,ce);for(let re=0;re<8;re++){if(t?.aborted)throw new Error("Fee estimation cancelled");const j=Xn(ne,D)??ms(N,D,Q);if(!j)return null;const J=ia(j,fe,s,p);Q=J.grossAmount;let Y,me,B,U,X;const pe=await M({fundingAmountOverride:Q,sourceGasSkimOverride:z,actionContextOverride:J,onDestinationAmount:V=>{Y=V},onSourceSpend:V=>{me=V},onSwap:(V,ie)=>{B=V,U=ie},onActionCalls:V=>{X=V}}),[de,xe]=await Promise.all([W(pe,E,Q,{...ce,validateFeeCalls:e.initialFeeEstimate!==void 0}),L?Lt.estimateBatchGas({user:R,outputToken:S.source.address,stepIndex:0,chainBatches:[pe[0]],signal:t}):void 0]);if(xe&&!(p==="user-transfer"?hs(z,xe.gasFee,e.feeToleranceBps):xe.gasFee===z))throw new Error("Source gas changed. Prepare a fresh fee quote.");const K=p==="user-transfer"?aa(de,ne):de,G=Xn(K,D)??ms(pe,D,Q);if(!G)return null;const P=ia(G,fe,s,p);if(JSON.stringify(J,(V,ie)=>typeof ie=="bigint"?ie.toString():ie)===JSON.stringify(P,(V,ie)=>typeof ie=="bigint"?ie.toString():ie)||p==="user-transfer"&&Aa(J.feeBreakdown,P.feeBreakdown,e.feeToleranceBps)){const V=p==="user-transfer"?j:G,ie=F?xn(z,S.source.decimals,S.destination.decimals,"ceil"):0n;return{batches:pe,fundingAmount:Q,actionContext:J,sourceSpendCap:me,destinationAmount:Y,destinationSwap:B,swapInputAmount:U,actionDefinition:X,feeEstimate:p==="user-transfer"?ne:K,sourceGasSkim:z,preview:{...V,grossAmount:Q+ie,netAmount:J.netAmount,gasFee:V.gasFee+ie,spicenetFee:J.feeBreakdown.spicenetFee,totalFee:J.combinedFeeAmount+ie}}}ne=K,N=pe}throw new Error("Fees did not converge. Refresh the quote before submitting.")}class _l extends Error{constructor(t){super("Amount is too small to cover fees. Increase the amount and retry."),this.preview=t,this.name="FeeShortfallError"}}function ia(e,t,n,o){const s=e.gasFee+(e.bridgeFee??0n);if(e.gasQuoteSource==="static_zero")return{grossAmount:t,netAmount:t,combinedFeeAmount:0n,feeExecutionMode:o??"backend-transfer",feeBreakdown:{gasFee:0n,bridgeFee:0n,spicenetFee:0n}};const r=n?Hc(t,s,10n):null;if(r&&!r.coversFees)throw new _l({...e,grossAmount:t,netAmount:0n,spicenetFee:0n,totalFee:s});const a=r?.spicenetFee??(o==="user-transfer"?tr(t,10n):e.spicenetFee);return{grossAmount:r?.grossAmount??t+a+s,netAmount:r?.netAmount??t,combinedFeeAmount:a+s,feeExecutionMode:o??"backend-transfer",feeBreakdown:{gasFee:e.gasFee,bridgeFee:e.bridgeFee??0n,spicenetFee:a}}}function $p(e,t){const n=e.selectedAsset?.asset;if(!n||n?._source!=="wallet")return;const o=Sn(n,e.resolvedChainId);if(!o||!ge(o,e.executionTokenAddress))return;const s=Ft(e.executionTokenAddress,e.resolvedChainId),r=Bo(t,s?.decimals??e.destinationToken.decimals,n.decimals);if(r<=n.balance)return;const a=Fe(r,n.decimals),i=Fe(n.balance,n.decimals);throw new Error(`Insufficient ${n.symbol} for this total amount. Required ${a} ${n.symbol}; available ${i} ${n.symbol}.`)}function _p(e){const t=Ft(e.executionTokenAddress,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:t?.symbol??e.destinationToken.symbol,decimals:t?.decimals??e.destinationToken.decimals}}function ef(e){const t=e.selectedAsset.asset,n=dn(e.selectedAsset.amount,t.decimals);if(n<=t.balance)return n;throw new Error(`Insufficient ${t.symbol} for this total amount. Required ${Fe(n,t.decimals)} ${t.symbol}; available ${Fe(t.balance,t.decimals)} ${t.symbol}.`)}function tf(e,t,n){const o=Xn(e,_p(t));if(o)return ia(o,n,!!t.isFeeInclusiveInput,t.feeExecutionMode)}function nf(e,t,n){let o=0n,s=0n;const r=n.toLowerCase();for(const a of e)if(a.chainId===t){for(const i of a.calls??[])if(i.to.toLowerCase()===r)try{const l=uo({abi:tt,data:i.data});if(l.functionName!=="transfer")continue;const c=l.args[0].toLowerCase(),d=l.args[1];c===Fn.toLowerCase()?o+=d:c===nn.toLowerCase()&&(s+=d)}catch{continue}}return{spicenetFee:o,gasFee:s}}function of(e,t,n,o){const s=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,r=nf(e,t.resolvedChainId,s);return r.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||r.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:hs(r.spicenetFee,n.feeBreakdown.spicenetFee,t.feeToleranceBps)&&hs(r.gasFee,n.feeBreakdown.gasFee,t.feeToleranceBps)&&hs(o.feeBreakdown.bridgeFee,n.feeBreakdown.bridgeFee,t.feeToleranceBps)}function sf(e,t,n){return e?Sa(e.grossAmount,t.grossAmount,100n)&&Aa(e.feeBreakdown,t.feeBreakdown,n):!1}function rf(e,t){const n=Ft(t,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:t,symbol:n?.symbol??e.selectedAsset?.asset.symbol??"",decimals:n?.decimals??e.selectedAsset?.asset.decimals??e.destinationToken.decimals}}async function af(e,t){const n=e.feeQuote;return n?.feeEstimate&&n.grossFundingAmount!==void 0?{grossFundingAmount:n.grossFundingAmount,feeEstimate:n.feeEstimate}:Jl({...t,feeOnlyAction:e.feeOnlyAction,estimate:e.execution.estimate,tokenDescriptor:rf(e,t.fundingToken)})}function ec(e,t,n){const o=t instanceof Error?t:new Error(String(t));if(o.name==="AbortError"||n){e.ui.setStep("idle");return}const s=o.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(s),e.ui.setError(s)}function tc(e,t){const n=Mn(t,"Payment failed. Please try again.");e.ui.setError(n),e.ui.setPaymentResult({status:"failed",error:n})}async function nc(e){e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setStep("executing"),e.ui.setStatusMsg("Confirm the transaction in your external wallet..."),e.ui.setTxHash(null),e.isPayMode&&(e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"}));try{if(e.validateFeeQuote?.(),!e.feeQuote?.batches||!e.feeQuote.actionDefinition)throw new Error("Review the direct action plan before submitting.");const t=await e.execution.execute(e.feeQuote.batches,e.destinationToken.address,0n,e.execution.onProgress);e.ui.setTxHash(t),e.ui.setStep("success"),e.ui.setStatusMsg("Transaction confirmed"),e.isPayMode&&e.ui.setPaymentResult({status:"success",txHash:t})}catch(t){e.isPayMode?tc(e,t):ec(e,t,!1)}finally{e.ui.setIsExecuting(!1)}}async function oc(e,t,n){e.validateFeeQuote?.();const o=e.feeQuote;if(!o.batches||o.sourceSpendCap===void 0||!o.fundingSource)throw new Error("Refresh the action before submitting.");const s=o.fundedFeeToken,r=o.grossFundingAmount??0n,a=Ul({...e,signal:n,feeOnlyAction:!0,destinationToken:s,actionProceeds:e.actionProceeds??{token:o.fundingSource.token,resolve:async()=>o.proceedsAvailable??0n}},s.address,r);return e.execution.execute(o.batches,o.fundingConversion?.tokenIn??o.fundingSource.token,r,t,n,{...a,userOverride:e.embeddedWalletAddress||e.providerEmbeddedAddress,useCustomTransfers:!0,feeExecutionMode:"backend-transfer",skipPreSubmitFeeEstimate:!0})}async function sc(e){if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.directExternalAction)return nc(e);if(!e.embeddedWalletAddress){e.ui.setError("Wallet not ready");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.ui.setTxHash(null),e.refs.spiceDepositSubmittedRef.current=!1;const t=new AbortController;e.refs.abortControllerRef.current=t;try{const n=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(e.feeQuote?.fundedFeeToken){const h=await oc(e,e.execution.onProgress,t.signal);e.ui.setTxHash(h),e.ui.setStep("success"),e.ui.setStatusMsg("Transaction confirmed");return}const o=sa(e);o&&ef(e);const s=e.feeQuote?.batches?e.feeQuote:await ho({...e,feeExecutionMode:e.feeExecutionMode,isDirect:!e.needsSwap,isQuoting:!1,resolvedSwap:null,buildPayChainBatches:e.execution.buildPayChainBatches,buildSupplyChainBatches:e.execution.buildSupplyChainBatches,estimate:e.execution.estimate});if(!s?.batches||s.fundingAmount===void 0||!s.actionContext)throw new Error("A current action plan is required. Refresh the quote before submitting.");const r=e.isFeeInclusiveInput?s.actionContext.grossAmount:s.actionContext.netAmount;let a=s.batches;const i=a.some(h=>h.tokenTransfers?.length),l={userOverride:n,useCustomTransfers:i,feeExecutionMode:e.feeExecutionMode,...o?{skipUserFundingPreflight:!0}:{}},c=s.fundingAmount,d=s.actionContext;$p(e,c);const p=d,f=await e.execution.execute(a,e.executionTokenAddress,i?c:0n,e.execution.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...l,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:h,chainBatches:m})=>{const g=tf(s.feeEstimate?aa(h,s.feeEstimate):h,e,r);if(!g)throw new Error("Unable to validate the accepted fees. Refresh the quote before submitting.");const y=sf(p,g,e.feeToleranceBps),w=of(m,e,g,p);if(y||w)return null;throw new Error("Transaction fees changed. Refresh the quote before submitting.")}}:{...l,skipPreSubmitFeeEstimate:!0});e.ui.setTxHash(f),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){ec(e,n,t.signal.aborted)}finally{e.ui.setIsExecuting(!1)}}async function rc(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}const t=e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t){e.ui.setError("Select a payment source");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.parsedAmount>0&&e.needsSwap&&!e.exactOutputSwap){e.ui.setError("Swap quote not available. Try a different asset.");return}if(e.directExternalAction)return nc(e);const n=Ql(e)&&!t,o=n?e.feeQuote?.sourceGasSkim??0n:0n,s=r=>e.execution.buildPayChainBatches(n?{...r,sourceGasSkimOverride:o}:r);if(!e.isConnected||!e.address){e.ui.setError("Please connect your wallet to continue");return}if(!e.ready||!e.authenticated){e.ui.setError(`Please authenticate with ${e.provider||"wallet provider"} to continue`);return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{if(e.feeQuote?.fundedFeeToken){const v=await oc(e,k=>{k.txHash&&(e.ui.setTxHash(k.txHash),e.ui.setPaymentResult({status:"processing",txHash:k.txHash}))});e.ui.setPaymentResult(k=>({status:"success",txHash:k?.txHash||v}));return}const r=dn(e.currentPaymentAmount,e.destinationToken.decimals),a={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,...n?{skipUserFundingPreflight:!0}:{}};if(t&&!e.feeOnlyAction){const v=await s(),k=await e.execution.execute(v,e.executionTokenAddress,0n,A=>{A.txHash&&(e.ui.setPaymentResult(b=>({...b??{status:"processing"},txHash:A.txHash})),e.ui.setTxHash(A.txHash))},void 0,a);e.ui.setPaymentResult(A=>({status:"success",txHash:A?.txHash||k}));return}const i=e.selectedAsset?.asset,l=e.feeQuote?.fundingSource;if(!i&&!e.actionProceeds&&!l)throw new Error("Select a payment source");const c=e.feeQuote?.fundingConversion?.tokenIn||l?.token||e.resolvedTokenIn||i?.address||e.destinationToken.address,d=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:r,p=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,f=!!e.feeQuote?.fundingConversion||!!l&&(l.kind!=="balance"||l.asset?._source==="wallet"),{grossFundingAmount:h,feeEstimate:m}=f?{grossFundingAmount:e.feeQuote.grossFundingAmount??0n,feeEstimate:void 0}:await af(e,{requiredNetFunding:d,buildBatches:v=>e.execution.buildPayChainBatches({fundingAmountOverride:v}).then(k=>mo(k,p)),fundingToken:c,executionOptions:a});let g=e.feeQuote?.fundingBatches??e.feeQuote?.batches??mo(await s({fundingAmountOverride:h}),p,e.actionProceeds?void 0:m,{payoutAlreadyGross:!0});const y=Ul(e,e.feeQuote?.fundingConversion?.tokenOut??c,h);y.prepareForSigning&&(g=await y.prepareForSigning(g));const w=g.some(v=>v.tokenTransfers?.length),x=await e.execution.execute(g,c,w?h:0n,v=>{v.txHash&&(e.ui.setPaymentResult(k=>({...k,txHash:v.txHash})),e.ui.setTxHash(v.txHash))},void 0,{...a,...y,skipPreSubmitFeeEstimate:!0});e.ui.setPaymentResult(v=>({status:"success",txHash:v?.txHash||x}))}catch(r){tc(e,r)}finally{e.ui.setIsExecuting(!1)}}async function lf(e){const{definition:t,account:n,chainId:o}=e,{calls:s}=t;if(!ge(t.context.executorAddress,n)||t.context.chainId!==o||!s.length)throw new Error("The direct action no longer matches its wallet or chain.");const r=yt(o);let a;for(const i of s){await e.assertCurrent();const[l,c]=await Promise.all([fl({client:r,account:n,calls:[i]}),r.getBalance({address:n})]);if(c<i.value+l)throw new Error("The external wallet has insufficient native balance for this transaction and network gas.");const{extWc:d,viemChain:p}=await Zr({wallet:e.wallet,account:n,chainId:o});a=await np({extWc:d,viemChain:p,client:r,calls:[i],errorMessage:"The external transaction reverted. Retry the unfinished action when ready."})}if(!a)throw new Error("The direct action has no confirmed receipt.");return a}async function ac(e){const{asset:t,embedded:n,external:o,amount:s}=e;if(!o||!e.externalWallet)throw new Error("Connect the source wallet before funding.");if(s<=0n)return;const r=yt(t.chainId),a=t.isNative||be(t.address),[i,l]=await Promise.all([ml({client:r,account:o,recipient:n,token:t.address,isNative:a,amount:s}),r.getBalance({address:o})]);if(l<i+(a?s:0n))throw new Error("The source wallet has insufficient native balance for funding and gas.");const{extWc:c,viemChain:d}=await Zr({wallet:e.externalWallet,account:o,chainId:t.chainId});await op({extWc:c,sourceClient:r,recipient:n,tokenAddr:t.address,isNative:a,amount:s,viemChain:d,observer:{onSending:()=>e.assertCurrent()}})}function ic(e){const t=Qt(Mt),n=Ge(e.chainId),o=e.address??n?.supportedTokens?.find(m=>m.symbol.toLowerCase()===e.symbol?.toLowerCase())?.address,s=e.symbol??(o&&be(o)?n?.nativeCurrency?.symbol:n?.supportedTokens?.find(m=>!!o&&ge(m.address,o))?.symbol),r=ba(e.chainId,t?.rpcOverrides),[a,i]=O(0),l=`${e.chainId}:${o?.toLowerCase()}:${r}:${e.decimals??""}:${s??""}:${a}`,[c,d]=O(null);ae(()=>{let m=!1;if(!(!e.enabled||!o||!r?.trim()))return Promise.all([e.decimals??as(e.chainId,o,t?.rpcOverrides),s??_n(yt(e.chainId,t?.rpcOverrides),{address:o,abi:tt,functionName:"symbol"}).catch(()=>{})]).then(([g,y])=>{if(!Number.isInteger(g)||g<0||g>255)throw new Error("Invalid destination token decimals");m||d({key:l,decimals:g,symbol:y})}).catch(g=>{m||d({key:l,error:g.message})}),()=>{m=!0}},[e.enabled,l]);const p=c?.key===l?c:null,f=ue(()=>({address:o??Tt,chainId:e.chainId,decimals:p?.decimals??0,symbol:s??p?.symbol??(o?Po(o):""),logoURI:e.logoURI}),[o,e.chainId,p?.decimals,p?.symbol,s,e.logoURI]),h=e.enabled?o?r?.trim()?p?.error??null:`Configure SpiceFlowProvider rpcOverrides[${e.chainId}] before continuing.`:"Configure the destination token address before continuing.":null;return{token:f,error:h,ready:e.enabled&&!!o&&!!r?.trim()&&p?.decimals!==void 0,refresh:te(()=>i(m=>m+1),[])}}function lc(e,t){const n=!!e&&e.symbol!==void 0&&e.decimals!==void 0,o=ic({enabled:t&&!!e&&!n,chainId:e?.chainId??0,address:e?.address,decimals:e?.decimals,symbol:e?.symbol,logoURI:e?.logoURI});return{token:e?n?e:o.ready?o.token:void 0:void 0,error:o.error}}const la={address:Tt,symbol:"",decimals:18,chainId:0};function cc(e,t,n){return ge(e.address,t)&&e.chainId===n?e._source==="wallet"?0:1:2}function cf(e,t,n,o){const s=cc(e,n,o)-cc(t,n,o);return s!==0?s:(t.balanceUsd||0)-(e.balanceUsd||0)}const df=Ei;function dc(e){const t=Qt(Mt),n=ps(),o=t?.embeddedWalletAddress||n.embeddedAddress,s=t?.externalWalletAddress||n.externalAddress,r=(t?.mode||"7702")!=="7702",a=e.destinationToken??la,i=e.enabled&&!!e.destinationToken,l=Ao({...e,owner:o,enabled:i&&!!o&&(!r||e.includeCrossChainEmbeddedAssets!==!1),role:"spend-source",destination:e.destinationToken}),c=Ao({...e,owner:s,enabled:i&&!!s&&(r||e.includeExternalWalletAssets!==!1),role:"spend-source",destination:e.destinationToken});return{displayAssets:ue(()=>[...l.assets,...c.assets].sort((d,p)=>cf(d,p,a.address,a.chainId)),[l.assets,c.assets,a.address,a.chainId]),filteredSpiceAssets:l.rollupAssets,walletAssets:[...l.walletAssets,...c.walletAssets],embeddedWalletAddress:o,externalAddress:s,isNon7702:r,refreshSpiceAssets:l.refresh,refreshWalletAssets:l.refresh,loading:l.loading||c.loading,refreshing:l.refreshing||c.refreshing,error:l.error||c.error}}function uf(e,t){return!e||e._source!=="wallet"?null:Br(e,t)}function ca(e){return ai({aerodrome:!1,oneInch:{chainIds:[]},customVenues:e})}const da=Co(),pf=ca(da.input);function uc(e){return{venue:"mapped-transfer",amountOut:e,amountOutMinimum:e,calls:[]}}function pc(e){return{venue:"mapped-transfer",amountIn:e,amountInMax:e,amountOut:e,calls:[]}}async function ua(e){if(ge(e.tokenIn,e.tokenOut))return uc(e.amountIn);if(e.resolveInputSwap){const n=await e.resolveInputSwap({type:"swap",tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:e.amountIn,maxSlippage:e.maxSlippage},e.chainId,e.recipient);if(n)return n}const t=await(e.liquidityVenues?ca(Co(e.liquidityVenues).input):pf).resolveSwap({type:"swap",tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:e.amountIn,maxSlippage:e.maxSlippage},e.chainId,e.recipient,e.selectedSwap);if(!t)throw new Error("No liquidity for this pair.");return t}async function ff(e){return ge(e.tokenIn,e.tokenOut)?pc(e.amountOut):Gs({customVenues:e.liquidityVenues?Co(e.liquidityVenues).output:da.output}).getQuote({tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountOut:e.amountOut,maxSlippage:e.maxSlippage},e.chainId,e.recipient)}function fc(e){const{enabled:t=!0,direction:n,selectedAsset:o,destinationToken:s,chainId:r=s.chainId,recipient:a,paymentAmount:i,maxSlippage:l,refreshIntervalMs:c,resolveInputSwap:d,resolveExactOutputSwap:p}=e,f=Qt(Mt),h=f?.liquidityVenues,m=JSON.stringify([f?.network,f?.apiUrl,f?.rpcOverrides]),[g,y]=O(!1),[w,x]=O(null),[v,k]=O(null),[A,b]=O(null),[S,T]=O(null),[E,I]=O(null),[M,W]=O(null),[R,F]=O(null),[N,D]=O(null),[L,z]=O(null),[fe,ce]=O(null),[Q,ne]=O(null),[re,j]=O(null),[J,Y]=O(null),[me,B]=O(0),[U,X]=O(null),[pe,de]=O(null),xe=_(null),K=_(null),G=_(0),P=_(new Map),V=te(()=>{G.current++,P.current.clear(),de(null),B(Le=>Le+1)},[]),ie=c&&c>0?c:null,ke=h?JSON.stringify(h):"",Ee=ue(()=>h?Co(h):da,[ke]),Be=ue(()=>ca(Ee.input),[Ee]),Ie=ue(()=>Gs({customVenues:[...p?[{name:"consumer-exact-output",chainIds:[r],preferred:!0,resolve:p}]:[],...Ee.output]}),[p,r,Ee]);ae(()=>{P.current.clear()},[Ie]);const Z=ue(()=>t?uf(o?.asset,r):null,[t,o?.asset,r]),ot=ue(()=>{if(!t||!o?.asset)return null;if(Z)return Z.destination.address;const Le=Sn(o.asset,r);if(Le)return Le;const ct=jn(o.asset.address,r,o.asset.chainId);return ct?ct.address:null},[t,o?.asset,r,Z]),qe=ue(()=>t&&o?.asset?ko(o.asset,r):[],[t,o?.asset,r]),Ct=ue(()=>qe.map(Le=>Le.toLowerCase()).join(","),[qe]),ht=JSON.stringify([t,m,o?.asset.owner,o?.asset.location,o?.asset.receiptTokenId,o?.asset.address,o?.asset.chainId,o?.asset.decimals,o?.amount,r,Ct,n,i]);ae(()=>{let Le=!1;if(K.current&&(clearTimeout(K.current),K.current=null),!t||!o?.asset||Z||qe.length<=1){j(null),Y(null);return}return K.current=setTimeout(async()=>{const ct=n==="input"?o.amount:i||"0";let $e=0n;try{$e=n==="input"?dn(ct,o.asset.decimals):0n}catch{$e=0n}try{const dt=await Ii(o.asset,r,{requiredAmount:$e});Le||(j(dt),Y(ht))}catch{Le||j(null)}},400),()=>{Le=!0,K.current&&(clearTimeout(K.current),K.current=null)}},[ht]);const Ve=ue(()=>(J===ht?re:null)??ot,[re,J,ht,ot]),Qe=ue(()=>!o?.asset||!Ve?[]:[Ve,...qe.filter(Le=>Le.toLowerCase()!==Ve.toLowerCase())],[o?.asset,Ve,qe]),at=ue(()=>!o?.asset||!qo(o.asset.address,o.asset.chainId,s.address,s.chainId)||!Ve?!1:ge(Ve,s.address),[o,s.address,s.chainId,Ve]),je=Ve?ge(Ve,s.address):!1,Dt=n==="output"&&parseFloat(i||"0")===0,Ke=t&&!!o?.asset&&!at&&!je&&!Dt,gt=JSON.stringify([t,ke,n,Ke,m,o?.asset.owner,o?.asset.location,o?.asset.receiptTokenId,o?.asset.address,o?.asset.chainId,o?.asset.decimals,n==="input"?o?.amount:i,Qe.map(Le=>Le.toLowerCase()),r,s.address.toLowerCase(),s.chainId,s.decimals,a?.toLowerCase(),l,ie,Z?.source.address.toLowerCase()??""]),De=ue(()=>({}),[gt,Be,Ie,d,me]),et=pe?.request===De&&(!ie||pe.expiresAt>Date.now());return ae(()=>{if(!ie||pe?.request!==De)return;const Le=setTimeout(V,Math.max(0,pe.expiresAt-Date.now()));return()=>clearTimeout(Le)},[ie,pe,De,V]),ae(()=>{xe.current&&clearTimeout(xe.current),X(De),de(null),x(null);const Le=n==="input"?o?.amount:i,ct=parseFloat(Le||"0");if(!t||!Number.isFinite(ct)||ct<=0||!o?.asset||!a||Qe.length===0){G.current++,k(null),b(null),T(null),I(null),W(null),F(null),D(null),ne(null),x(null),y(!1);return}const $e=o.asset.decimals;let dt;try{dt=n==="input"?dn(o.amount,$e):dn(i||"0",s.decimals)}catch(Me){G.current++,x(Me instanceof Error?Me.message:"Invalid amount or token precision"),y(!1);return}const kt=++G.current,ut=()=>kt!==G.current;y(!0);const Re=n==="output"?150:100,ft=async(Me,$,ee,ze={chainId:r,tokenOut:s.address,amountIn:dt},Ce=Qe)=>{for(const le of Ce){const Pe=`${m}:${ke}:${n}:${ze.chainId}:${le.toLowerCase()}:${ze.tokenOut.toLowerCase()}:${ze.amountIn.toString()}:${a.toLowerCase()}:${l??"default"}:${ie??"default"}`,Ae=P.current.get(Pe),q=Ae&&Ae.expiresAt>Date.now()?Me(Ae):void 0;if(q)return{quote:q,tokenIn:le,expiresAt:Ae.expiresAt};const Ze=await ee(le);if(ut())return"stale";if(!Ze)continue;const ye=Date.now()+Math.min(ie??3e4,3e4);return P.current.set(Pe,{expiresAt:ye,direction:n,...$(Ze)}),{quote:Ze,tokenIn:le,expiresAt:ye}}return null},Ot=Me=>ft($=>$.resolvedSwap,$=>({resolvedSwap:$}),async $=>{const ee=!Z&&Me.chainId===r&&o.asset._source!=="wallet",ze=ee?await eo(o.asset,$,Me.chainId,s):$e;if(ut())return null;const Ce=ee?zs(Me.amountIn,$e,ze):Me.amountIn;if(ge($,Me.tokenOut))return uc(Ce);const le={type:"swap",tokenIn:$,tokenOut:Me.tokenOut,amountIn:Ce,maxSlippage:l};if(d){const Pe=await d(le,Me.chainId,a);if(Pe)return Pe}return Be.resolveSwap(le,Me.chainId,a)},Me,Me.candidates);return xe.current=setTimeout(async()=>{try{if(n==="input"){let Me=null,$=dt;if(Z){if(Me=await Ot({chainId:Z.source.chainId,tokenOut:Z.source.address,amountIn:dt,candidates:[o.asset.address]}),Me==="stale"||ut())return;if(!Me)throw new Error("No liquidity for this pair");$=xn(Me.quote.amountOutMinimum,Z.source.decimals,Z.destination.decimals,"floor")}const ee=Ke||!Z?await Ot({chainId:r,tokenOut:s.address,amountIn:$,candidates:Qe}):null;if(ee==="stale"||ut())return;if(Ke&&!ee)throw new Error("No liquidity for this pair");const ze=ee?ee.quote.amountOut:$,Ce=Math.min(ee?.expiresAt??1/0,Me?.expiresAt??1/0),le=Z?.destination.decimals??await eo(o.asset,ee.tokenIn,r,s),Pe=!Z&&o.asset._source!=="wallet"?zs($,$e,le):$;if(ut())return;ne(ee?.tokenIn??Z?.destination.address??null),de({request:De,key:`${vo(Ha(gt))}:${kt}`,expiresAt:Ce}),D(ze),z(Pe),ce(le),T(Ke?ee?.quote??null:null),I(Me?.quote??null),W(null),F(null);const Ae=parseFloat(Fe(ze,s.decimals));k(Ae<.01?Ae.toPrecision(4):Ae.toLocaleString(void 0,{maximumFractionDigits:6})),b(null),x(null)}else{const Me=Pe=>ft(Ae=>Ae.exactOutputSwap,Ae=>({exactOutputSwap:Ae}),async Ae=>{try{return ge(Ae,Pe.tokenOut)?pc(Pe.amountOut):await Ie.getQuote({tokenIn:Ae,tokenOut:Pe.tokenOut,amountOut:Pe.amountOut,maxSlippage:l},Pe.chainId,a)}catch{return null}},{chainId:Pe.chainId,tokenOut:Pe.tokenOut,amountIn:Pe.amountOut},Pe.candidates),$=!Z||Ke,ee=$?await Me({chainId:r,tokenOut:s.address,amountOut:dt,candidates:Qe}):null;if(ee==="stale"||ut())return;if($&&!ee)throw new Error("No liquidity for this pair");let ze=null;if(Z){const Pe=ee?ee.quote.amountInMax:dt;if(ze=await Me({chainId:Z.source.chainId,tokenOut:Z.source.address,amountOut:xn(Pe,Z.destination.decimals,Z.source.decimals,"ceil"),candidates:[o.asset.address]}),ze==="stale"||ut())return;if(!ze)throw new Error("No liquidity for this pair")}const Ce=ze?$e:await eo(o.asset,ee.tokenIn,r,s);if(ut())return;ne(ee?.tokenIn??Z?.destination.address??null),de({request:De,key:`${vo(Ha(gt))}:${kt}`,expiresAt:Math.min(ee?.expiresAt??1/0,ze?.expiresAt??1/0)}),F(ee?.quote??null),W(ze?.quote??null),T(null),I(null),D(null);const le=ze?.quote.amountIn??ee.quote.amountIn;b(Fe(le,Ce)),k(null),x(null)}}catch(Me){if(ut())return;const $=Me instanceof Error?Me.message:"Failed to get quote";x($),k(null),b(null),T(null),I(null),W(null),F(null),D(null),ne(null)}finally{ut()||y(!1)}},Ke||Z?Re:0),()=>{G.current++,xe.current&&clearTimeout(xe.current)}},[De]),{inputAmount:et&&n==="input"?L:null,inputDecimals:et&&n==="input"?fe:null,quoteKey:et?pe.key:null,quoteExpiresAt:et?pe.expiresAt:null,refreshQuote:V,isQuoting:U===De?g:Ke||!!Z,quoteError:U===De?w:null,estimatedOutput:et?v:null,estimatedInput:et?A:null,resolvedSwap:et?S:null,exactOutputSwap:et?R:null,quoteAmountOut:et?N:null,resolvedTokenIn:Ke&&et?Q??Ve:Ve,isDirect:je,needsSwap:Ke,selectedIsEquivalent:at,sourceSwap:et?E:null,sourceExactOutputSwap:et?M:null,pivot:Z}}function os(e){const{enabled:t=!0,destinationToken:n,selectedAsset:o,paymentAmount:s="0",sourceChains:r,supportedSourceAssets:a,buildActionCalls:i,feeExecutionMode:l="user-transfer",buildSpicenetBatch:c,onPayExecute:d,resolveExactOutputSwap:p,amountDirection:f=e.feeOnlyAction?"output":"input",onSuccess:h,onError:m}=e,g=lc(n,t),y=g.token??la,w=t&&!!g.token,x=f==="output",v=f==="input-inclusive",k=e.feeFunding?.length!==0&&(e.actionProceeds==="output"||!!e.feeFunding?.length),A=x?"output":"input",b=y.chainId,S=Qt(Mt),T=qc(S?.feeToleranceBps),E=S?.mode||"7702",I=!1,M=!!S?.isWhitelistGateActive,W=!!S?.isWhitelistConfigured&&S?.isUserWhitelisted!==!0,R=ue(()=>r??S?.supportedChainIds??[],[r,S?.supportedChainIds]),F=a,{address:N,isConnected:D,isReady:L,isAuthenticated:z,provider:fe}=Zn(),{execute:ce,estimate:Q}=Ms(),{externalWallet:ne,embeddedAddress:re,activeWallet:j,activeAddress:J}=ps(),Y=S?.externalWalletAddress,me=S?.embeddedWalletAddress||re,B=o,U=Ss(B?.asset,E!=="7702"),X=!!B&&B.asset.chainId===y.chainId&&ge(Ye(B.asset.address),Ye(y.address)),pe=E!=="7702"&&U&&X&&(!x||Number(s)>0)&&!e.feeOnlyAction&&!e.actionProceeds,de=U&&!pe,xe=g.error?g.error:d?"Move onPayExecute protocol calls to buildActionCalls and application updates to onSuccess before continuing.":e.actionExecution?.wallet==="external"&&!pe?"This action requires the external wallet as its caller. Select its destination token on the destination chain for direct execution, or configure a beneficiary-capable embedded action for routing.":null,{displayAssets:K,filteredSpiceAssets:G,walletAssets:P,embeddedWalletAddress:V,refreshSpiceAssets:ie,refreshWalletAssets:ke,loading:Ee,refreshing:Be,error:Ie}=dc({address:N,destinationToken:y,supportedSourceAssets:F,sourceChains:R,additionalSourceTokens:[...e.additionalSourceTokens??[],...B?.asset._source==="wallet"?[{address:B.asset.address,chainId:B.asset.chainId,decimals:B.asset.decimals,symbol:B.asset.symbol,name:B.asset.name,logoURI:B.asset.logoURI}]:[]],includeExternalWalletAssets:e.includeExternalWalletAssets,includeCrossChainEmbeddedAssets:e.includeCrossChainEmbeddedAssets,enabled:w&&(E!=="7702"?!!Y:!!me)}),Z=K,ot=ue(()=>e.feeOnlyAction||k?Z.filter(oe=>oe.balance>0n&&oe.location!=="external"&&(oe._source==="spice"||oe._source==="wallet"&&oe.chainId===b)):[],[Z,e.feeOnlyAction,k,b]),qe=B?[...P,...G].find(oe=>nt(oe)===nt(B.asset)):void 0,Ct=ue(()=>B&&qe?{...B,asset:qe}:B,[B,qe]),ht=B?po(qe??B.asset,"spend-source",{allowedTokens:S?.allowedTokens,rpcOverrides:S?.rpcOverrides,liquidityVenues:S?.liquidityVenues,isWhitelistGateActive:M},y,F):null,Ve=qe?qe.balance<(B?.asset.balance??0n)?qe.balance:B.asset.balance:0n,[Qe,at]=O(!1),[je,Dt]=O(null),Ke=_(m);Ke.current=m;const gt=te(oe=>{Dt(oe),typeof oe=="string"&&oe&&Ke.current?.(new Error(oe),fs(oe))},[]),[De,et]=O("idle"),[Le,ct]=O(""),[$e,dt]=O(null),[kt,ut]=O(!1),[Re,ft]=O(null),[Ot,Me]=O(null),[$,ee]=O(!1),[ze,Ce]=O(!1),[le,Pe]=O(null),Ae=_(B),q=_(!1),Ze=_(null),ye=_(null),Xe=_(null),Ht=_(null),qt=_(null),Te=_(null),Wt=_(h),Nt=_(null),wt=_(!1),[On,Gn]=O(null),[wn,Pn]=O(null),[bn,jt]=O(!1),[Kt,ln]=O(0),Jt=Re?.status==="success"?Re.txHash:De==="success"?$e:null,Zt=!!Jt&&On!==Jt,on=_(Zt);on.current=Zt,ae(()=>{Ae.current=B},[B]);const st=pe?Y:V||re||N,Je=w&&!Qe&&De==="idle"&&!xe&&!W&&!!st&&!pe&&!x&&v&&l==="user-transfer"&&!e.feeOnlyAction&&!e.actionInput&&!e.actionProceeds&&!!B&&Number(B.amount||"0")===0&&!!ht?.eligible&&Ve>0n,$t=ue(()=>{if(!Je||!B)return B;const oe=10n**BigInt(B.asset.decimals);return{...B,amount:Fe(Ve<oe?Ve:oe,B.asset.decimals)}},[Je,B,Ve]),vn=fc({enabled:w&&!W&&!pe,direction:A,selectedAsset:$t,destinationToken:y,chainId:b,recipient:st,paymentAmount:s,resolveExactOutputSwap:p,resolveInputSwap:e.resolveInputSwap,maxSlippage:e.maxSlippage}),_t=pe?{...vn,quoteKey:"direct-external",quoteExpiresAt:null,quoteAmountOut:null,inputAmount:null,inputDecimals:B?.asset.decimals??null,isQuoting:!1,quoteError:null,isDirect:!0,needsSwap:!1,selectedIsEquivalent:!0,resolvedTokenIn:y.address,resolvedSwap:null,exactOutputSwap:null,sourceSwap:null,sourceExactOutputSwap:null,pivot:null,estimatedInput:x?s:B?.amount??null,estimatedOutput:x?s:B?.amount??null}:vn,Ue=_t,{isQuoting:cn,resolvedSwap:We,exactOutputSwap:en,quoteAmountOut:It,resolvedTokenIn:pt,isDirect:Un,needsSwap:hn,selectedIsEquivalent:Oo,sourceSwap:se,sourceExactOutputSwap:he,pivot:ve}=_t,_e=x?parseFloat(s||"0"):parseFloat(B?.amount||"")||0,Vt=B?.asset?._source==="wallet",St=!!B?.asset&&Vt&&B.asset.chainId!==b,sn=B?Number(Fe(Ve,B.asset.decimals)):0,rn=ue(()=>{if(!B||x)return!1;try{return dn(B.amount||"0",B.asset.decimals)>Ve}catch{return!0}},[B,x,Ve]);ae(()=>{w||(gt(null),at(!1),Zt||(et("idle"),ct(""),dt(null),ut(!1),ft(null)),Me(null),ee(!1),Ce(!1),Pe(null),q.current=!1,Ze.current&&(Ze.current.abort(),Ze.current=null))},[w,Zt]);const un=te(oe=>{et({building:"building","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[oe.step]||"executing"),ct(oe.message),oe.txHash&&dt(oe.txHash)},[]),Gt=ue(()=>({currentPaymentAmount:s,isFeeInclusiveInput:v,feeOnlyAction:e.feeOnlyAction,swapInputAmount:_t.inputAmount,destinationToken:y,embeddedWalletAddress:V,providerEmbeddedAddress:re,externalWalletAddress:Y,address:N,recipient:e.recipient??(E!=="7702"?Y:void 0),isNon7702:I,isPayMode:x,resolvedChainId:b,buildActionCalls:i,feeExecutionMode:l,buildSpicenetBatch:c,selectedAsset:B,needsSwap:hn,resolvedSwap:We,exactOutputSwap:en,quoteAmountOut:It,resolvedTokenIn:pt,sourceSwap:se,sourceExactOutputSwap:he,pivot:ve,resolveSourceExactOutputSwap:async oe=>{if(!ve||!st)throw new Error("Swap route is not ready.");const lt=await ff({chainId:ve.source.chainId,recipient:st,tokenIn:B.asset.address,tokenOut:ve.source.address,amountOut:oe,liquidityVenues:S?.liquidityVenues,maxSlippage:e.maxSlippage}).catch(()=>null);if(!lt)throw new Error("No liquidity for this pair.");return lt},resolveInputSwap:async(oe,lt)=>{if(!pt||!st)throw new Error("Swap route is not ready.");return ua({chainId:b,recipient:st,tokenIn:pt,tokenOut:y.address,amountIn:oe,selectedSwap:lt,liquidityVenues:S?.liquidityVenues,maxSlippage:e.maxSlippage,resolveInputSwap:e.resolveInputSwap})}}),[s,y,V,re,Y,N,e.recipient,e.feeOnlyAction,e.maxSlippage,e.resolveInputSwap,_t.inputAmount,v,E,I,x,b,i,l,c,B,hn,We,en,It,pt,se,he,ve,st,S?.liquidityVenues]),tn=ue(()=>B?.asset?ve?ve.destination.address:hn&&pt?pt:B.asset.chainId===b?B.asset.address:pt??Sn(B.asset,b)??y.address:y.address,[B,y.address,hn,b,pt,ve]),Pt=JSON.stringify([B&&nt(B.asset),f,y.address,y.chainId,y.decimals,e.recipient,E,Y,pe?Y:V,S?.apiUrl,S?.rpcOverrides,e.maxSlippage,l,T,e.feeOnlyAction,e.actionProceeds==="output"?"output":e.actionProceeds?.token,e.feeFunding,e.actionInput?.map(oe=>[oe.token,oe.amount.toString()]),e.feeFundingReserve&&nt(e.feeFundingReserve.asset),e.feeFundingReserve?.amount.toString(),S?.liquidityVenues,S?.allowedTokens,M,F,R,e.actionInput,e.actionProceeds,e.feeFunding,b,tn,Ue.pivot?.source.address,Ue.pivot?.destination.address],(oe,lt)=>typeof lt=="bigint"?lt.toString():lt),ro=_(null);ro.current=w&&!Qe&&!xe&&!W?Pt:null,ae(()=>()=>{qt.current?.controller.abort(),qt.current=null},[Pt,w,Qe,xe,W]);const Yt=vo(rd(JSON.stringify([Pt,B?.amount,s]))),Cn=_({key:Yt,enabled:w,sourceBalance:Ve,sourceEligible:ht?.eligible});Cn.current={key:Yt,enabled:w,sourceBalance:Ve,sourceEligible:ht?.eligible};const An=_(null),kn=_(!1),Yn=_(e.onSubmit);Yn.current=e.onSubmit;const yo=te(()=>kn.current?(kn.current=!1,Yn.current?.(),Wt.current=Te.current.onSuccess,An.current={key:Cn.current.key,quote:Te.current.feeQuote},sc(Te.current)):Promise.resolve(),[]),H=pe,we=W,He=!Xe.current?.quote.fundedFeeToken&&(v||!!ve)&&!!Ot&&Ot.netAmount===0n,Se=ue(()=>!!e.feeOnlyAction||(!!B?.asset||!!e.actionProceeds)&&_e>0,[B,_e,e.actionProceeds,e.feeOnlyAction]),mt=ue(()=>!w||!Se||!B?.asset&&!e.actionProceeds&&!e.feeOnlyAction?null:[Yt,x?"pay":"supply",f,B?nt(B.asset):"sdk-funded",e.actionInput?.map(oe=>`${oe.token.toLowerCase()}:${oe.amount}`).join(",")??"",e.feeFunding?.join(",")??"",JSON.stringify(S?.rpcOverrides),S?.apiUrl,e.recipient,B?.asset.address.toLowerCase(),B?.asset.chainId,B?.amount,s,y.address.toLowerCase(),y.chainId,b,Ue.resolvedTokenIn?.toLowerCase()??"",Ue.quoteKey,Ue.needsSwap?"swap":"direct",Ue.isDirect?"direct-token":"routed-token","7702",X?"source-dest":"cross-chain",Ue.isQuoting?"quoting":"quoted",Ue.exactOutputSwap?.amountIn?.toString()??"",Ue.exactOutputSwap?.amountInMax?.toString()??"",Ue.exactOutputSwap?.venue??"",Ue.resolvedSwap?.amountOut?.toString()??"",Ue.quoteAmountOut?.toString()??"",Ue.sourceSwap?.amountOutMinimum?.toString()??"",Ue.sourceExactOutputSwap?.amountInMax?.toString()??"",Ue.pivot?.source.address.toLowerCase()??"",V??"",re??"",N??""].join("|"),[w,Yt,e.actionProceeds,e.feeOnlyAction,e.actionInput,e.feeFunding,Qe,De,Se,H,B,x,f,s,y,b,Ue,I,X,V,re,N]),rt=te(async(oe,lt,Ut)=>{if(pe){if(!Y||!B)throw new Error("Connect the external wallet before continuing.");return Zp({selectedAsset:lt?.selectedAsset??B,destinationToken:y,paymentAmount:x?s:void 0,account:Y,beneficiary:e.recipient,buildActionCalls:i,feeExecutionMode:l})}const bt={...Ut??{...Gt,selectedAsset:$t},requestTimestampMs:Date.now()},it={signal:oe,feeToleranceBps:T,feeOnlyAction:e.feeOnlyAction,actionInput:e.actionInput,actionProceeds:e.actionProceeds==="output"?void 0:e.actionProceeds,feeFunding:e.feeFunding,feeFundingBalances:ot,feeFundingReserve:e.feeFundingReserve,liquidityVenues:S?.liquidityVenues,maxSlippage:e.maxSlippage,resolveExactOutputSwap:p,selectedAsset:$t,isPayMode:x,isFeeInclusiveInput:v,parsedAmount:Je?Number($t.amount):_e,needsSwap:Ue.needsSwap,exactOutputSwap:Ue.exactOutputSwap,isNon7702:I,isSourceDestToken:X,currentPaymentAmount:s,destinationToken:y,feeExecutionMode:l,resolvedTokenIn:Ue.resolvedTokenIn,embeddedWalletAddress:V,providerEmbeddedAddress:re,resolvedChainId:b,isConnected:D,address:N,ready:L,authenticated:z,isDirect:Ue.isDirect,resolvedSwap:Ue.resolvedSwap,sourceSwap:Ue.sourceSwap,sourceExactOutputSwap:Ue.sourceExactOutputSwap,pivot:Ue.pivot,isQuoting:Ue.isQuoting,executionTokenAddress:tn,buildPayChainBatches:vt=>Qs(bt,vt),buildSupplyChainBatches:vt=>js(bt,vt),estimate:Q,...lt},At=!it.feeOnlyAction&&it.selectedAsset&&k&&it.selectedAsset.asset._source==="wallet"&&it.selectedAsset.asset.chainId===b;if(k&&!it.feeOnlyAction&&it.selectedAsset&&!At&&e.feeFunding&&e.feeFunding.join(",")!==ra.join(","))throw new Error("Fee-source overrides require a wallet source on the action chain.");return At||k&&e.actionProceeds==="output"?Kp(it,bt,ho,e.actionProceeds==="output"):ho(it)},[B,k,$t,Je,pe,Y,e.recipient,i,e.feeOnlyAction,e.actionInput,e.actionProceeds,e.feeFunding,ot,e.feeFundingReserve,e.maxSlippage,p,T,S?.liquidityVenues,x,v,_e,Ue,I,X,s,y,l,V,re,Gt,Q,b,D,N,L,z,tn]);ae(()=>{ye.current=rt},[rt]);const Kn=te(async oe=>{if(x)return null;if(!B||nt(oe)!==nt(B.asset)||!st||!pt)throw new Error("Select a source before calculating Max.");let lt=oe.balance;if(pe){if(!oe.isNative&&!be(oe.address))return Fe(lt,oe.decimals);const Ut=yt(oe.chainId),bt=Y;let it=lt;for(let At=0;At<8;At++){const vt=await rt(void 0,{selectedAsset:{asset:oe,amount:Fe(At===0?1n:it,oe.decimals)}});if(!vt?.actionDefinition)throw new Error("The direct action could not be sized.");const pn=await fl({client:Ut,account:bt,calls:vt.actionDefinition.calls}),er=lt>pn?lt-pn:0n;if(er===0n)return"0";if(At>0&&it<=er)return Fe(it,oe.decimals);it=er}throw new Error("Network gas could not be reserved for Max. Enter a smaller amount.")}if(de&&(oe.isNative||be(oe.address))){if(!Y)throw new Error("Connect the source wallet before calculating Max.");const Ut=await ml({client:yt(oe.chainId),account:Y,recipient:st,token:oe.address,isNative:!0,amount:1n});lt-=Ut}return k&&v&&oe._source==="wallet"&&oe.chainId===b?Fe(lt>0n?lt:0n,oe.decimals):$l({balance:lt,decimals:oe.decimals,planForAmount:async Ut=>{const bt={...Gt,requestTimestampMs:Date.now(),selectedAsset:{asset:oe,amount:Fe(Ut,oe.decimals)}};let it=Ut;ve?(bt.sourceSwap=await ua({chainId:oe.chainId,recipient:st,tokenIn:oe.address,tokenOut:ve.source.address,amountIn:Ut,maxSlippage:e.maxSlippage,liquidityVenues:S?.liquidityVenues,resolveInputSwap:e.resolveInputSwap}),it=xn(bt.sourceSwap.amountOutMinimum,ve.source.decimals,ve.destination.decimals,"floor")):it=zs(Ut,oe.decimals,await eo(oe,pt,b,y)),bt.resolvedSwap=hn?await bt.resolveInputSwap(it):null,bt.swapInputAmount=it,bt.quoteAmountOut=bt.resolvedSwap?.amountOut??it;const At=k&&oe._source==="wallet"&&oe.chainId===b,vt=await rt(void 0,{selectedAsset:bt.selectedAsset,...At?{isFeeInclusiveInput:!0}:{},parsedAmount:Number(bt.selectedAsset.amount),sourceSwap:bt.sourceSwap,resolvedSwap:bt.resolvedSwap,isQuoting:!1,buildSupplyChainBatches:pn=>js(bt,pn)},bt);return At&&vt?.fundingSource?.kind==="input"&&!v?{...vt,sourceSpendCap:Ut+(Ut-vt.swapInputAmount)}:vt}})},[B,k,Gt,x,pe,st,pt,b,y,de,Y,ve,hn,rt,e.maxSlippage,e.resolveInputSwap,e.actionProceeds,e.feeFunding,v,S?.liquidityVenues]);Hr({shouldRun:w&&!Qe&&De==="idle"&&(Se||Je)&&!Ue.isQuoting&&(!!mt||Je),deps:[w,Qe,De,Se,H,Ue.isQuoting,mt,Je,Pt],onSkip:()=>{if(!w){Ht.current=null,ee(!1),Ce(!1),Pe(null),Me(null);return}if(Qe||De!=="idle"){ee(!1);return}if(!Se){Me(null),ee(!1),Ce(!1),Pe(null);return}Ue.isQuoting&&(ee(!1),Ce(!1))},onCleanup:()=>ee(!1),delayMs:Ue.needsSwap||Ue.pivot?0:100,backgroundIntervalMs:5e3,run:async({isBackground:oe,isCurrent:lt,signal:Ut})=>{if(Je){const it=Ht.current;if(it?.scope===Pt&&Date.now()-it.at<3e4||qt.current?.scope===Pt&&Date.now()-qt.current.at<3e4)return;qt.current?.controller.abort();const At=new AbortController,vt=ye.current?.(At.signal).then(pn=>{At.signal.aborted||ro.current!==Pt||!pn?.feeEstimate||(Ht.current={scope:Pt,at:Date.now(),feeEstimate:pn.feeEstimate,sourceGasSkim:pn.sourceGasSkim})}).catch(pn=>{At.signal.aborted||console.debug("[SpiceSupply] fee prewarm unavailable:",pn)})??Promise.resolve();qt.current={scope:Pt,at:Date.now(),controller:At,promise:vt},await vt;return}const bt=mt;oe||(Pe(null),ee(!0));try{if(qt.current?.scope===Pt&&await qt.current.promise,Ut.aborted||!lt())return;const it=Ht.current,At=!x&&it?.scope===Pt&&Date.now()-it.at<3e4?it:void 0;let vt;try{vt=await ye.current?.(Ut,At?{initialFeeEstimate:At.feeEstimate,initialSourceGasSkim:At.sourceGasSkim}:void 0)}catch(pn){if(!At||Ut.aborted||!lt())throw pn;vt=await ye.current?.(Ut)}if(!lt())return;vt&&bt?(Xe.current={key:bt,quote:vt},vt.feeEstimate&&(Ht.current={scope:Pt,at:Date.now(),feeEstimate:vt.feeEstimate,sourceGasSkim:vt.sourceGasSkim}),Me(vt.preview),Ce(!0)):(Xe.current=null,Me(null),Ce(!1)),Pe(null)}catch(it){if(!lt())return;if(oe&&Xe.current?.key===bt){console.warn("[SpiceSupply] fee refresh failed:",it);return}const At=Mn(it,"Unable to calculate fees for this action.");Xe.current=null,Me(it instanceof _l?it.preview:null),Ce(!1),Pe(At)}finally{lt()&&ee(!1)}}});const Ro=te(()=>kn.current?(kn.current=!1,Yn.current?.(),Wt.current=Te.current.onSuccess,An.current={key:Cn.current.key,quote:Te.current.feeQuote},rc(Te.current)):Promise.resolve(),[]);ae(()=>{if(!Jt||Nt.current===Jt)return;Nt.current=Jt;const oe=Wt.current;wt.current=!0,jt(!0),Pn(null),Promise.resolve().then(()=>oe?.(Jt)).then(()=>{Gn(Jt),ie(),ke()}).catch(lt=>{Pn(`Transaction confirmed; application update needs retry: ${Mn(lt,"Unable to finalize the action")}`)}).finally(()=>{wt.current=!1,jt(!1)})},[Jt,Kt]);const Mo=Zt&&!wn,Zs=te(()=>{!on.current||wt.current||(Nt.current=null,ln(oe=>oe+1))},[]),Xs=te(()=>{on.current||(ut(!1),ft(null),q.current=!1,ie(),ke())},[ie,ke]),Xt=mt&&Xe.current?.key===mt?Xe.current.quote:null,Js=(oe=!0)=>{if(xe)throw new Error(xe);if(!Cn.current.enabled||Cn.current.key!==Yt)throw new Error("The source, amount, beneficiary or configuration changed. Review the form before continuing.");if((B||e.feeOnlyAction)&&!Xt)throw new Error("A current action plan is required. Refresh the quote before submitting.");if(pe&&B?.asset.owner&&!ge(B.asset.owner,Y))throw new Error("Reconnect the external wallet that owns the selected asset.");if(oe&&B&&(Xt?.sourceSpendCap??0n)>Cn.current.sourceBalance)throw new Error("The source balance changed. Review the available amount before continuing.");if(oe&&B&&!Cn.current.sourceEligible)throw new Error(ht?.reason??"This source is unavailable.")},Wo=async()=>Js(),ga=oe=>({...oe,sourceSpendCap:Xt?.sourceSpendCap,minimumDestinationAmount:Xt?.destinationAmount}),rs=B&&Xt?.sourceSpendCap!==void 0?Xt.sourceSpendCap>Ve:rn,ya={...Gt,resolvedSwap:Xt?.destinationSwap??Gt.resolvedSwap,swapInputAmount:Xt?.swapInputAmount??Gt.swapInputAmount};let $s=!1;Te.current={selectedAsset:B,parsedAmount:_e,currentPaymentAmount:s,isInsufficientBalance:rs,isPayMode:x,isFeeInclusiveInput:v,feeOnlyAction:e.feeOnlyAction,actionProceeds:e.actionProceeds==="output"?void 0:e.actionProceeds,validateFeeQuote:()=>Js(!$s),isNon7702:I,directExternalAction:pe,isSourceDestToken:X,needsSwap:hn,exactOutputSwap:en,selectedIsEquivalent:Oo,resolvedTokenIn:pt,sourceSwap:se,sourceExactOutputSwap:he,pivot:ve,embeddedWalletAddress:V,providerEmbeddedAddress:re,externalWallet:ne,externalWalletAddress:Y,activeSignerWallet:j,activeSignerAddress:J,address:N,isConnected:D,ready:L,authenticated:z,provider:fe,resolvedChainId:b,executionTokenAddress:tn,destinationToken:y,buildActionCalls:i,feeExecutionMode:l,feeToleranceBps:T,buildSpicenetBatch:c,onPayExecute:d,onSuccess:h,feeQuote:Xt,execution:{estimate:(oe,lt,Ut,bt)=>Q(oe,lt,Ut,{...bt,userOverride:st}),execute:async(oe,lt,Ut,bt,it,At)=>{const vt=async()=>Js(!$s);if(await Wo(),pe){if(!Xt?.actionDefinition)throw new Error("The direct action plan is unavailable.");return lf({definition:Xt.actionDefinition,account:Y,chainId:y.chainId,wallet:ne,assertCurrent:Wo})}return de&&B&&(ct("Transfer the selected source to your embedded wallet"),await ac({asset:B.asset,embedded:st,external:Y,externalWallet:ne,amount:Xt?.sourceSpendCap??0n,assertCurrent:Wo}),$s=!0,await vt()),ce(oe,lt,Ut,bt,it,{...At,userOverride:st,requireDestinationReceipt:!0,walletFundingRequirement:B?.asset._source==="wallet"&&Xt?.sourceSpendCap!==void 0?{chainId:B.asset.chainId,token:B.asset.address,amount:Xt.sourceSpendCap}:void 0,validateBeforeSubmit:async pn=>{await vt(),await At?.validateBeforeSubmit?.(pn)}})},buildPayChainBatches:oe=>Qs(ya,ga(oe)),buildSupplyChainBatches:oe=>js(ya,ga(oe)),onProgress:un},ui:{setError:gt,setStep:et,setStatusMsg:ct,setTxHash:dt,setIsExecuting:at,setShowStatusPanel:ut,setPaymentResult:ft},refs:{spiceDepositSubmittedRef:q,abortControllerRef:Ze}};const xo=!!e.isZeroAmountPay&&!e.feeOnlyAction&&x&&_e===0,Tc=x?(xo||!!B?.asset||!!e.actionProceeds||!!e.feeOnlyAction)&&_e>=0&&!rs&&!Qe&&(xo||H||ze)&&!le&&(xo||e.feeOnlyAction||!hn||!!en)&&(xo||e.feeOnlyAction||!ve||!!he)&&!we:!!B?.asset&&_e>0&&!rs&&!Qe&&(pe||ze)&&!le&&!He&&(ve?!!se&&!cn&&(Un||!!We):St||Un||!!We&&!cn)&&!we,xa=!xe&&!!st&&(!pe||!!ne&&(!B?.asset.owner||ge(B.asset.owner,Y)))&&(E==="7702"||!!Y)&&!Zt&&!bn&&!wn&&w&&Tc&&(xo||!B&&(!!e.actionProceeds||!!e.feeOnlyAction)||!!ht?.eligible)&&De!=="success"&&Re?.status!=="success"&&!_t.quoteError&&(xo||!!mt&&Xe.current?.key===mt);kn.current=xa;const _s=te(()=>{on.current||(kn.current=!1,Xe.current=null,Ce(!1),vn.refreshQuote(),et("idle"),gt(null),ct(""),ft(null),ut(!1))},[vn.refreshQuote,gt]),wa=_(Yt);ae(()=>{const oe=wa.current!==Yt;wa.current=Yt,(oe||Ea(je))&&De==="error"&&!Qe&&An.current&&An.current.key!==Yt&&_s()},[Yt,De,Qe,je,_s]);const Bc=te(()=>{ut(!1)},[]),Dc=te(()=>{on.current||(et("idle"),dt(null),ie())},[ie]),Rt=Xt??(Xe.current?.key.startsWith(`${Yt}|`)?Xe.current.quote:null)??(An.current?.key===Yt?An.current.quote:null),Oc=async oe=>{if(pe)throw new Error("This source executes directly from the external wallet; submit the action without embedded funding.");if(!(!de||!B)){if(!Xt||oe!==Xt.sourceSpendCap)throw new Error("Use the displayed source funding maximum before preparing this action.");await Wo(),await ac({asset:B.asset,embedded:st,external:Y,externalWallet:ne,amount:oe,assertCurrent:Wo})}};return{selectedAsset:Ct,capability:ht,assets:{selectable:Z,displayAssets:Z,filteredSpiceAssets:G,embeddedWalletAddress:V,externalAddress:Y,isNon7702:E!=="7702",refreshSpiceAssets:ie,refreshWalletAssets:ke,loading:Ee,refreshing:Be,error:Ie},quote:{..._t,...Je?{quoteKey:null,quoteExpiresAt:null,quoteError:null,isQuoting:!1,estimatedInput:null,estimatedOutput:null,quoteAmountOut:null,inputAmount:null,resolvedSwap:null,sourceSwap:null,exactOutputSwap:null,sourceExactOutputSwap:null}:{},hasSourceConversion:!!ve,executionInput:ve&&Rt?{address:ve.destination.address,chainId:ve.destination.chainId,decimals:ve.destination.decimals,amount:Rt.preview.netAmount}:null,...Rt?.destinationSwap?{resolvedSwap:Rt.destinationSwap,inputAmount:Rt.swapInputAmount,estimatedOutput:Fe(Rt.destinationSwap.amountOut,y.decimals)}:{},...Rt?.fundedFeeToken&&Rt.destinationAmount!==void 0?{estimatedOutput:Fe(Rt.destinationAmount+(Rt.destinationSwap?Rt.destinationSwap.amountOut-Rt.destinationSwap.amountOutMinimum:0n),y.decimals)}:{}},fees:{fundingConversion:Rt?.fundingConversion,fundingSource:Rt?.fundingSource,proceedsUsed:Rt?.proceedsUsed,fundingShortfall:Rt?.grossFundingAmount,source:ve&&Rt?{address:ve.source.address,chainId:ve.source.chainId,symbol:ve.source.symbol,decimals:ve.source.decimals,gasFee:Rt.sourceGasSkim??0n,spicenetFee:0n}:null,destinationAmount:Rt?.destinationAmount,sourceSpendCap:Rt?.sourceSpendCap,preview:Je?null:Rt?.preview??Ot,isLoading:!Je&&$,ready:!Je&&!!Xt,error:Je?null:le},amount:{sourceRequiredAmount:Rt?.sourceSpendCap??null,parsed:_e,isInsufficientBalance:rs,sourceBalance:sn,feesExceedAmount:He},status:{finalizing:bn||Mo,finalizationError:wn,step:Zt&&De==="success"?"executing":De,statusMsg:Zt?wn??"Transaction confirmed. Updating application...":Le,txHash:$e,isExecuting:Qe||Mo,error:xe||wn||je||ht?.reason||null,showStatusPanel:kt,paymentResult:Zt&&Re?.status==="success"?{...Re,status:"processing"}:Re},flags:{directExecutionFeeNote:H},retryFinalization:Zs,fundEmbeddedSource:Oc,canExecute:xa,submit:x?Ro:yo,submitSupply:yo,submitPay:Ro,retrySupply:_s,dismissPaymentStatus:Bc,resolveMaxAmount:Kn,max:()=>B?Kn(B.asset):Promise.resolve(null),resetAfterSuccess:Dc,resetPaymentState:Xs}}function mf(e){const{asset:t,amount:n,recipient:o,owner:s,onSuccess:r}=e,a=t?.chainId??e.sourceChains?.[0]??0,i=ue(()=>gs(a).find(y=>y.equivalenceGroup==="USDC"),[a]),l=te((y,w)=>{if(!t||n<=0n||n>t.balance||!o||!s||ge(s,o))throw new Error("Enter a valid withdrawal amount and recipient.");if(w.chainId!==t.chainId||!ge(w.executorAddress??w.userAddress,s))throw new Error("The withdrawal wallet or network changed. Review the withdrawal again.");return Rl(t.chainId,t.address,[{recipient:o,amount:n}]).calls},[t?.address,t?.chainId,t?.balance,n,o,s]),c=ue(()=>t?{asset:t,amount:n}:void 0,[t,n]),d=ue(()=>t?[{address:t.address,chainId:t.chainId,symbol:t.symbol,decimals:t.decimals,logoURI:t.logoURI}]:void 0,[t?.address,t?.chainId,t?.symbol,t?.decimals,t?.logoURI]),p=os({enabled:e.enabled&&!!i&&!!t&&n>0n&&!!o&&!!s&&!ge(s,o),feeOnlyAction:!0,isZeroAmountPay:!0,amountDirection:"output",paymentAmount:"0",destinationToken:{address:i?.address??Tt,symbol:i?.symbol??"USDC",decimals:i?.decimals??6,chainId:a},recipient:o,selectedAsset:null,feeFundingReserve:c,additionalSourceTokens:d,sourceChains:e.sourceChains,includeCrossChainEmbeddedAssets:!0,includeExternalWalletAssets:!1,feeExecutionMode:"backend-transfer",buildActionCalls:l,buildSpicenetBatch:Hs,onError:(y,w)=>e.onError?.(y.message,w),onSuccess:async()=>{t&&(window.dispatchEvent(new CustomEvent("withdraw-completed")),await r?.({token:t.symbol,amount:Fe(n,t.decimals),chainId:a}))}}),f=`${e.enabled}:${t?.chainId}:${t?.address}:${n}:${o}`,h=_(f);ae(()=>{h.current===f||p.status.isExecuting||(h.current=f,(p.status.step==="success"||p.status.paymentResult?.status==="success")&&p.resetAfterSuccess())},[f,p.status.isExecuting,p.status.step,p.status.paymentResult?.status,p.resetAfterSuccess]);const m=p.fees.fundingSource?.asset,g=m?m._source==="wallet"?p.fees.fundingConversion?.amountInMax??p.fees.proceedsUsed:p.amount.sourceRequiredAmount:null;return{supply:p,source:m,maximumFeeFunding:g}}const mc=Oe.ui,hf=({label:e,loading:t,balance:n,dark:o,dk:s})=>{const r=o?s.textSecondary:"#7D7C7B",a=o?s.textSecondary:"#71757A";return C("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[u("span",{style:{fontFamily:mc,fontSize:"17px",fontWeight:500,color:r,lineHeight:"24px"},children:e}),C("div",{style:{display:"flex",alignItems:"center",gap:"6px",fontFamily:mc,fontSize:"13px",fontWeight:500,color:a,lineHeight:"16px"},children:["Balance:"," ",t?"...":n===null?"\u2014":rr(n)]})]})},hc=({isOpen:e,position:t,title:n,items:o,selectedId:s,onSelect:r,portalAttribute:a})=>{const{dark:i,dk:l,primaryColor:c}=Bt(),[d,p]=O(null),[f,h]=O(!1);return ae(()=>{if(!e){h(!1);return}const m=requestAnimationFrame(()=>{requestAnimationFrame(()=>h(!0))});return()=>cancelAnimationFrame(m)},[e]),!e||!t||o.length===0?null:fr(C("div",{[`data-${a}-popover`]:"true",style:{position:"fixed",top:`${t.top}px`,left:`${t.left}px`,opacity:f?1:0,transform:f?"scale(1) translateY(0)":"scale(0.96) translateY(-6px)",transition:`opacity 200ms ${wo.out}, transform 200ms ${wo.out}`,backgroundColor:i?l.shell:"#ffffff",borderRadius:"10px",padding:"10px 12px",boxShadow:i?"0 16px 48px rgba(0,0,0,0.45)":"0 12px 32px rgba(0,0,0,0.12)",border:`1px solid ${l.cardBorder}`,minWidth:"220px",zIndex:ao.dropdown,fontFamily:Oe.mono},children:[u("div",{style:{marginBottom:"6px"},children:u("span",{style:{fontSize:"11px",fontWeight:500,color:i?l.textPrimary:"#0e0d0b",textTransform:"uppercase",letterSpacing:"1px"},children:n})}),u("div",{style:{borderBottom:`1px solid ${l.cardBorder}`,marginBottom:"6px"}}),u("div",{style:{display:"flex",flexDirection:"column",gap:"2px"},children:o.map(m=>{const g=s===m.id,y=d===m.id;return C("button",{onClick:w=>{w.stopPropagation(),r(m.id)},onMouseEnter:()=>p(m.id),onMouseLeave:()=>p(null),style:{display:"flex",alignItems:"center",gap:"8px",padding:"6px 4px",borderRadius:"8px",border:"none",cursor:"pointer",backgroundColor:g?i?l.hoverBg:"#f3f4f6":y?i?l.cardBg:"#f9fafb":"transparent",transition:"background-color 0.15s",width:"100%",fontFamily:Oe.mono},children:[m.icon&&u("img",{src:m.icon,alt:m.label,style:{width:"22px",height:"22px",borderRadius:"50%"}}),u("span",{style:{fontSize:"13px",fontWeight:g?700:500,textTransform:"uppercase",color:i?l.textPrimary:"#0e0d0b",letterSpacing:"0.5px",flex:1,textAlign:"left"},children:m.label}),m.detail&&u("span",{style:{fontSize:"11px",fontWeight:500,color:l.textSecondary},children:m.detail}),g&&u(al,{color:c,style:{flexShrink:0}})]},m.id)})})]}),document.body)},Ys=Oe.ui,gf=Oe.mono,yf=170,xf=({header:e,amount:t,receiveAmountDisplay:n,receiveUsdEstimate:o,selectedDestToken:s,destTokenSymbol:r,destChainName:a,destChainLogo:i,compatibleDestinationChains:l,networkSwitchRef:c,onOpenNetworkPopover:d,showNetworkPopover:p,setShowNetworkPopover:f,networkPopoverPos:h,selectedChainId:m,setSelectedChainId:g,dark:y,dk:w})=>{const x=y?w.cardBg:"#E9E9E9",v=y?w.cardBorder:"#C6C6C6",k=y?w.textSecondary:"#71757A",A=y?w.textPrimary:"#0E0D0B",b=y?w.cardBorder:"#C5C5C4",S=y?"rgba(255,255,255,0.08)":"#D4D3D3",T=r.length>8?"14px":r.length>6?"16px":"18px";return C("div",{style:{backgroundColor:x,border:`1px solid ${v}`,borderRadius:"7px",padding:"14px 16px 12px 16px",minHeight:"138px",display:"flex",flexDirection:"column",gap:"6px"},children:[e,C("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[C("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[u(fo,{element:"div",value:n,title:n,fontFamily:Ys,color:t?A:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,overflow:"wrap"}),u("div",{style:{fontSize:"12px",fontWeight:500,color:k,fontFamily:Ys,marginTop:"10px"},children:o})]}),C("div",{style:{width:`${yf}px`,flexShrink:0,display:"flex",flexDirection:"column",alignItems:"stretch",gap:"8px"},children:[C("div",{style:{backgroundColor:"transparent",border:`1px solid ${b}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[C("div",{style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px"},children:[u("img",{src:s?.logoURI||Kd,alt:r,style:{width:"24px",height:"24px",borderRadius:"50%"}}),u("span",{style:{fontSize:T,fontWeight:500,color:A,lineHeight:"1.3",fontFamily:Ys,flex:1,minWidth:0,letterSpacing:0},children:r})]}),C("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:S,borderTop:`1px solid ${b}`},children:[C("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[i&&u("img",{src:i,alt:a,style:{width:"13px",height:"13px",borderRadius:"50%",flexShrink:0}}),u("span",{style:{fontSize:"11px",fontWeight:400,color:A,fontFamily:Ys,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:a})]}),u("button",{ref:c,onClick:E=>{E.stopPropagation(),d(c.current)},style:{background:"none",border:"none",cursor:l.length>1?"pointer":"not-allowed",padding:"0 0 0 8px",fontSize:"9.5px",fontFamily:gf,color:k,textDecoration:"underline",fontWeight:600,opacity:l.length>1?1:.45},children:"Switch"}),u(hc,{isOpen:p,position:h,title:"SELECT NETWORK",portalAttribute:"network",items:l.map(E=>{const I=Ge(E);return{id:String(E),label:I?.displayName||String(E),icon:to[E]||Qo}}),selectedId:m!==null?String(m):null,onSelect:E=>{g(Number(E)),f(!1)}})]})]}),u("div",{style:{minHeight:"14px"}})]})]})]})},wf=Oe.ui,so=Oe.mono,bf=({show:e,onToggle:t,showCustomAddress:n,setShowCustomAddress:o,customRecipient:s,setCustomRecipient:r,externalAddress:a,recipientAddress:i,destChainName:l,destChainLogo:c,compatibleDestinationChains:d,txDetailsChainSwitchRef:p,onOpenNetworkPopover:f,sourceChainLabel:h,sourceDetailsLogo:m,sourceTokenLabel:g,amount:y,totalSourceDebitDisplay:w,receiveAmountDisplay:x,destTokenSymbol:v,shouldQuoteWithdrawGas:k,estimatingFee:A,feeError:b,displayedGasFee:S,selectedDestToken:T,theme:E,styles:I,dark:M,dk:W})=>{const R=M?W.textSecondary:"#71757A",F=M?W.textPrimary:"#0E0D0B",N=d.length>1,D=n&&s?fn(s)?Po(s):s:i?Po(i):"\u2014";return C(an,{children:[C("div",{onClick:t,style:{display:"flex",alignItems:"center",gap:"6px",marginBottom:e?"10px":"0",cursor:"pointer",userSelect:"none"},children:[u("span",{style:{fontSize:"13px",color:R,fontFamily:wf,fontWeight:600},children:"Transaction Details"}),u($u,{size:12,color:R,style:{transform:e?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s"}})]}),e&&C("div",{style:{display:"flex",flexDirection:"column",gap:"7px"},children:[C("div",{children:[C("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[u("span",{style:{fontSize:"12px",color:R,fontFamily:so,fontWeight:500,letterSpacing:"0.03em"},children:"TO"}),C("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[u("span",{style:{fontSize:"13px",color:F,fontFamily:so,fontWeight:500},children:D}),u("button",{onClick:()=>{o(L=>!L),!n&&a&&r(a)},style:{background:"none",border:"none",cursor:"pointer",padding:"0",fontSize:"9.5px",fontFamily:so,color:R,textDecoration:"underline",fontWeight:600},children:n?"Reset":"Switch"})]})]}),n&&C("div",{style:{marginTop:"6px"},children:[u("div",{style:{marginBottom:"6px",padding:"7px 9px",borderRadius:"6px",border:"1px solid rgba(239, 68, 68, 0.55)",backgroundColor:"rgba(239, 68, 68, 0.12)",color:"#ef4444",fontSize:"10px",lineHeight:1.35,fontFamily:so,fontWeight:700,letterSpacing:0,textTransform:"uppercase"},children:"CAUTION: ENTERING AN INCORRECT ADDRESS WILL RESULT IN LOSS OF FUNDS"}),u("input",{type:"text",autoComplete:"off",spellCheck:!1,"aria-label":"Recipient address","aria-invalid":s&&!fn(s)?!0:void 0,"data-spiceflow-focus":!0,value:s,onChange:L=>r(L.target.value),placeholder:"0x...",style:{width:"100%",padding:"8px 10px",borderRadius:"6px",border:`1px solid ${s&&!fn(s)?M?W.errorBorder:"#fca5a5":M?W.inputBorder:"#d1d5db"}`,backgroundColor:M?W.inputBg:"#f9fafb",color:M?W.inputText:"#111827",fontSize:"12px",fontFamily:so,outline:"none",boxSizing:"border-box"}}),s&&!fn(s)&&u("span",{style:{fontSize:"11px",color:W.errorText,marginTop:"3px",display:"block"},children:"Invalid address"})]})]}),u(oo,{palette:W,labelColor:R,valueColor:F,label:"RECEIVING CHAIN",value:C("div",{style:{display:"flex",alignItems:"center",gap:"7px"},children:[c&&u("img",{src:c,alt:l,style:{width:"14px",height:"14px",borderRadius:"50%"}}),u("span",{style:{fontSize:"13px",color:F,fontWeight:500,fontFamily:so,textTransform:"uppercase"},children:l}),u("button",{ref:p,onClick:L=>{L.stopPropagation(),f(p.current)},style:{background:"none",border:"none",cursor:N?"pointer":"not-allowed",padding:"0",fontSize:"9.5px",fontFamily:so,color:R,textDecoration:"underline",fontWeight:600,opacity:N?1:.45},children:"Switch"})]})}),u(oo,{palette:W,labelColor:R,valueColor:F,label:"REQUESTED WITHDRAWAL",value:C(pa,{logo:m||null,alt:h,primaryText:F,children:[y||"0"," ",g]})}),k&&u(oo,{palette:W,labelColor:R,valueColor:F,label:"TOTAL SOURCE DEBIT",value:C(pa,{logo:m||null,alt:h,primaryText:F,children:[w," ",g]})}),u(oo,{palette:W,labelColor:R,valueColor:F,label:"YOU RECEIVE",value:C(pa,{logo:c,alt:l,primaryText:F,gap:"4px",children:[x," ",v]})}),k&&C(an,{children:[u(oo,{palette:W,labelColor:R,label:"EST. NETWORK FEE",valueColor:b?"#f87171":F,value:A?"Estimating...":b?"Unavailable":S!==null&&T?`${na(S,T.decimals)} ${T.symbol}`:"Estimating..."}),b&&u(Nn,{variant:"error",size:"compact",palette:W,fontFamily:I?.fontFamily||E.typography.fontFamily,children:b})]})]})]})},vf=yn(bf),pa=({logo:e,alt:t,primaryText:n,gap:o="6px",children:s})=>C("div",{style:{display:"flex",alignItems:"center",gap:o},children:[e&&u("img",{src:e,alt:t,style:{width:"13px",height:"13px",borderRadius:"50%"}}),u("span",{style:{fontSize:"13px",color:n,fontWeight:500,fontFamily:so},children:s})]}),ss=Oe.ui,Cf=170,kf=({header:e,amount:t,setAmount:n,isInsufficient:o,sourceAmountDecimals:s,selectedSourceAsset:r,resolvedSelectedSourceAsset:a,spiceAssets:i,setSelectedSourceAsset:l,sourceUsdEstimate:c,sourceTokenLabel:d,sourceChainLabel:p,totalSelectedBalance:f,showSourceTokenPopover:h,setShowSourceTokenPopover:m,tokenPopoverPos:g,setTokenPopoverPos:y,tokenTriggerRef:w,primaryColor:x,dark:v,dk:k})=>{const A=Rn(),b=a?A({...a,logoURI:Vo}).logoURI:Vo,S=v?k.cardBg:"#E9E9E9",T=v?k.cardBorder:"#C6C6C6",E=v?k.textSecondary:"#71757A",I=v?k.textPrimary:"#0E0D0B",M=v?k.cardBorder:"#C5C5C4",W=v?"rgba(255,255,255,0.08)":"#D4D3D3",R=d.length>8?"14px":d.length>6?"16px":"18px";return C("div",{style:{backgroundColor:S,border:`1px solid ${T}`,borderRadius:"7px",padding:"14px 16px 12px 16px",minHeight:"138px",display:"flex",flexDirection:"column",gap:"6px",position:"relative"},children:[e,C("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[C("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[u(fo,{element:"input",ariaLabel:"Withdraw amount",ariaInvalid:o,dataSpiceflowFocus:!0,value:t,onChange:F=>{const N=F.target.value;if(N===""){n("");return}/^\d*\.?\d*$/.test(N)&&n(ds(N.startsWith(".")?`0${N}`:N,s??r?.decimals))},placeholder:"0.0",fontFamily:ss,color:o?"#ef4444":t?I:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,style:{width:"100%"}}),u("div",{style:{fontSize:"12px",fontWeight:500,color:E,fontFamily:ss,marginTop:"10px"},children:c})]}),u("div",{style:{width:`${Cf}px`,flexShrink:0},children:C("div",{style:{backgroundColor:"transparent",border:`1px solid ${M}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[C("div",{ref:w,onClick:F=>{if(F.stopPropagation(),!h&&w.current){const N=w.current.getBoundingClientRect(),D=220,L=16;y({top:N.bottom+8,left:Math.min(Math.max(L,N.right-D),window.innerWidth-D-L)})}m(N=>!N)},style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px",cursor:"pointer"},children:[b&&u("img",{src:b,alt:d,style:{width:"24px",height:"24px",borderRadius:"50%"}}),u("span",{style:{fontSize:R,fontWeight:500,color:I,lineHeight:"1.3",fontFamily:ss,flex:1,minWidth:0,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",letterSpacing:0},children:d}),u(Eo,{size:15,color:I,strokeWidth:2.25})]}),u(hc,{isOpen:h,position:g,title:"SELECT TOKEN",portalAttribute:"token",items:(i||[]).map(F=>({id:F.receiptTokenId||F.address,label:A({...F,displaySymbol:F.displaySymbol||F.receiptTokenName}).symbol,icon:A({...F,logoURI:Vo}).logoURI||void 0,detail:rr(F.balanceFormatted)})),selectedId:a?.receiptTokenId||a?.address||null,onSelect:F=>{const N=(i||[]).find(D=>(D.receiptTokenId||D.address)===F);N&&(l(N),n("")),m(!1)}}),u("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:W,borderTop:`1px solid ${M}`},children:u("span",{style:{fontSize:"11px",fontWeight:400,color:I,fontFamily:ss,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:p})})]})})]}),C("div",{style:{minHeight:"18px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[o?u("span",{style:{fontSize:"12px",color:k.errorText,fontFamily:ss,fontWeight:500},children:"Insufficient Balance"}):u("span",{}),u("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0px",minHeight:"32px",marginRight:"-9px"},children:[0,25,50,75,100].map((F,N)=>{const D=N===4,L=parseFloat(t)||0,z=f>0&&Math.abs(L/f*100-F)<1;return u("button",{type:"button","aria-label":`Set amount to ${F}%`,"aria-pressed":z,onClick:()=>{const fe=f*F/100,ce=r?.decimals??6,Q=Math.floor(fe*10**ce)/10**ce;n(F===0?"":Q>0?Fa(Q,ce):"")},title:`${F}%`,disabled:f===0,"data-spiceflow-focus":!0,style:{width:"32px",height:"32px",padding:"9px",border:"none",backgroundColor:"transparent",cursor:f===0?"not-allowed":"pointer",opacity:z?1:.5,transition:"opacity 0.15s ease",display:"flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box"},children:u(Jr,{pct:F,isMax:D,primaryColor:x,dark:v,fillColor:v?k.textSecondary:"#3C3E42"})},F)})})]})]})},If=({dark:e,dk:t})=>C("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[u("img",{src:zr,alt:"","aria-hidden":"true",style:{width:"13px",height:"13px",flexShrink:0,...e?{filter:"invert(0.6)"}:{}}}),u("p",{style:{fontSize:"13px",color:e?t.textSecondary:"#979AA0",margin:"0",lineHeight:"1.4",fontFamily:Oe.ui},children:"Withdraw collateral from your account to 10+ EVM blockchains."})]}),Sf=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,styles:o,onWithdrawExecute:s,onWithdrawSuccess:r,onWithdrawError:a,availableTokens:i,initialSourceAssetId:l,walletAssets:c,buildSpicenetBatch:d=Hs})=>{const p=Qt(Mt);if(!p)return u("div",{children:"Error: SpiceWithdraw must be used within SpiceFlowProvider"});const f=p.mode||"7702",h=f==="presign"||f==="ondemand",m=p.supportedChainIds,g=p.allowedTokens,y=!!c,w=c?.initialAsset,x=ue(()=>[...c?.extraAssets??[],...w?[w]:[]].map(se=>({address:se.address,chainId:se.chainId,symbol:se.symbol,decimals:se.decimals})),[c?.extraAssets,w]),v=p.isWhitelistGateActive,{theme:k,dark:A,dk:b}=Bt(o),S=Rn(),T=p.network,E=()=>h?"select":"provider-login",[I,M]=O(E()),[W,R]=O(!1),[F,N]=O(null),[D,L]=O(null),[z,fe]=O(""),[ce,Q]=O(!1),[ne,re]=O(!1),[j,J]=O(!1),[Y,me]=O(""),[B,U]=O(!0),X=_(null),pe=_(null),de=_(null),[xe,K]=O(null),[G,P]=O(null),V=Zn(),{isReady:ie,isAuthenticated:ke,address:Ee}=V,Be=p?.embeddedWalletAddress,{address:Ie,chainId:Z}=ir(),ot=p.externalWalletAddress||Ie,[qe,Ct]=O(!1),[ht,Ve]=O(null),Qe=_(a);Qe.current=a;const at=te(se=>{Ve(se),typeof se=="string"&&se&&Qe.current?.(se,fs(se))},[]),[je,Dt]=O(null),Ke=_(null),gt=_(!0),De=_(null);ae(()=>(gt.current=!0,()=>{gt.current=!1}),[]);const{execute:et,estimate:Le}=Ms(),[ct,$e]=O(null),[dt,kt]=O(null),[ut,Re]=O(!1),[ft,Ot]=O(null),{assets:Me,loading:$,error:ee,refresh:ze}=Ao({owner:Be,role:"holding",includeWalletAssets:y,additionalSourceTokens:x,enabled:e&&!!Be}),Ce=ue(()=>{if(v)return[];const se=(he,ve)=>(ve.balanceUsd||0)-(he.balanceUsd||0);return(Me??[]).filter(he=>he.balance>0n&&po(he,"holding",{allowedTokens:g,isWhitelistGateActive:v}).eligible).sort(se)},[Me,g,v]),le=ue(()=>[...new Set([...m??[],...Object.keys(i??{}).map(Number),...(Ce||[]).map(se=>se.chainId),...(Ce||[]).flatMap(se=>Object.keys(se.chainTokens??{}).map(he=>{const[,ve]=he.split(":"),_e=Number(ve);return Number.isFinite(_e)?_e:null}).filter(he=>he!==null))])].filter(se=>Ge(se)?.network===T),[m,i,Ce,T]),Pe=ue(()=>{if(i)return i;const se={};for(const he of Ce||[]){const ve=Object.entries(he.chainTokens??{});if(ve.length>0){for(const[_e,Vt]of ve){const[St,sn,rn]=_e.split(":");if(St!=="evm"||!sn||!rn)continue;const un=Number(sn);if(!Number.isFinite(un))continue;const Gt=rn.startsWith("0x")?rn.toLowerCase():`0x${rn.toLowerCase()}`,tn=Ge(un)?.supportedTokens?.find(Pt=>ge(Pt.address,Gt));tn&&Fr(he,Gt,un)&&(se[un]||(se[un]=[]),se[un].find(Pt=>ge(Pt.address,Gt))||se[un].push({address:Gt,symbol:tn?.symbol||Vt?.name||he.symbol,name:tn?.name||Vt?.name||he.displayName||he.name||he.symbol,decimals:tn?.decimals??Vt?.decimals??he.decimals,logoURI:tn?.logo||he.logoURI}))}continue}se[he.chainId]||(se[he.chainId]=[]),se[he.chainId].find(_e=>ge(_e.address,he.address))||se[he.chainId].push({address:he.address,symbol:he.symbol,name:he.displayName||he.name||he.symbol,decimals:he.decimals,logoURI:he.logoURI})}return se},[i,Ce]),Ae=te((se,he)=>{const ve=Ap(se,he,he?Pe[he]??[]:[]);return!se||!ve||!he||se._source==="wallet"&&he!==se.chainId?null:po(se,"withdraw-destination",p,{...ve,chainId:he}).eligible?ve:null},[Pe,p.allowedTokens,p.rpcOverrides,p.isWhitelistGateActive]),q=ue(()=>F?Ce.find(se=>nt(se)===nt(F))??null:null,[F,Ce]),Ze=q?q.balanceError:ee,ye=q?._source==="wallet",Xe=ue(()=>{if(!q)return[];const se=Object.keys(q.chainTokens??{}).map(he=>qn(he)?.chainId??null).filter(he=>he!==null);return Array.from(new Set([...se,q.chainId,...le].filter(Number.isFinite))).filter(he=>Ge(he)?.network===T&&Ae(q,he)!==null)},[q,le,Ae,T]),Ht=ue(()=>{if(!q||typeof window>"u")return null;const se=`spiceflow:withdraw-chain:${q.receiptTokenId||q.address.toLowerCase()}`,he=window.localStorage.getItem(se),ve=he?Number(he):null;return ve!==null&&Number.isFinite(ve)&&Xe.includes(ve)?ve:null},[q,Xe]),qt=ue(()=>q?Ht!==null?Ht:Z&&Xe.includes(Z)?Z:q.chainId&&Xe.includes(q.chainId)?q.chainId:Xe[0]??null:le[0]??null,[q,Ht,Z,Xe,le]),Te=ue(()=>Ae(q,D),[Ae,q,D]);ae(()=>{e&&(N(null),fe(""))},[e,l,w?.address,w?.chainId]),ae(()=>{if(!e||!Ce.length||F)return;const se=w?Ce.find(he=>he.chainId===w.chainId&&ge(he.address,w.address)&&he._source==="wallet"):l?Ce.find(he=>he.receiptTokenId===l):Ce[0];N(se??null),fe("")},[e,Ce,F,l,w]),ae(()=>{q&&(D===null||!Xe.includes(D))&&L(qt)},[q,D,qt,Xe]),ae(()=>{if(!ce&&!ne)return;const se=he=>{const ve=he.target;ce&&!X.current?.contains(ve)&&!pe.current?.contains(ve)&&!ve?.closest?.("[data-network-popover]")&&Q(!1),ne&&!de.current?.contains(ve)&&!ve?.closest?.("[data-token-popover]")&&re(!1)};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[ce,ne]);const Wt=te(se=>{if(!se||Xe.length<=1)return;const he=se.getBoundingClientRect(),ve=220,_e=16;K({top:he.bottom+8,left:Math.min(Math.max(_e,he.right-ve),window.innerWidth-ve-_e)}),Q(Vt=>!Vt)},[Xe.length]),Nt=te(()=>U(se=>!se),[]);ae(()=>{if(!q||D===null||typeof window>"u")return;const se=`spiceflow:withdraw-chain:${q.receiptTokenId||q.address.toLowerCase()}`;window.localStorage.setItem(se,String(D))},[q,D]);const wt=j?fn(Y)?Y:void 0:ot||(ye?void 0:Be),On=Ao({owner:wt,role:"holding",includeRollupAssets:!1,sourceChains:D?[D]:[],additionalSourceTokens:Te&&D?[{...Te,chainId:D}]:[],enabled:e&&!!wt&&!!Te&&!!D}),Gn=On.walletAssets.find(se=>ge(se.owner,wt)&&se.chainId===D&&ge(se.address,Te?.address)),wn=q?.balanceFormatted??0,Pn=q?S({...q,displaySymbol:q.displaySymbol||q.receiptTokenName}).symbol:"Select token",bn=q?.displayChainName||(ye?Ge(q.chainId)?.displayName:"Spicenet")||"Network",jt=q?.receiptTokenDecimals??q?.decimals,Kt=ue(()=>{if(!Te||jt===void 0)return 0n;try{return dn(z||"0",jt)}catch{return 0n}},[z,Te,jt]),ln=ue(()=>!Te||jt===void 0?0n:Mp(Kt,jt,Te.decimals),[Te,jt,Kt]),Jt=dt??ct,Zt=ue(()=>{const se=ye?0n:Jt??0n;return ln>se?ln-se:0n},[ye,Jt,ln]),on=Kt,st=mf({enabled:e&&ye,asset:ye?q:null,amount:Kt,recipient:wt,owner:Be,sourceChains:m,onSuccess:r,onError:a}),Je=st.supply,$t=qe||ye&&(Je.status.isExecuting||Je.status.finalizing),vn=Je.status.step==="success"||Je.status.paymentResult?.status==="success",_t=te(se=>{if(ye||!D||!Te)return[];if(Kt===0n||ln===0n||!wt)return[];const he=Array.isArray(se)?se.filter(St=>St.amount>0n):[{token:Te.address,recipient:wt,amount:se??ln}],ve=he.reduce((St,sn)=>St+sn.amount,0n);if(ve<=0n)return[];const _e={chainId:D,calls:[],tokenTransfers:he.map(St=>({from:"escrow",to:St.recipient,token:St.token,amount:St.amount}))},Vt=d({destinationChainId:D,deliveryToken:Te.address,deliveryAmount:ve,deliveryRecipient:wt,deliveryTransfers:he,requestTimestampMs:De.current??Date.now()});return Vt?[Vt,_e]:[_e]},[ye,D,Te,Kt,ln,wt,d]),Ue=ue(()=>_t(),[_t]),cn=ue(()=>Wp(Ue,Te?.address),[Ue,Te?.address]),We=_(null),en=!ye&&e&&!h&&!qe&&!!Te&&!!D&&Kt!==0n;Hr({shouldRun:en&&Ue.length>0&&!!cn,deps:[en,Ue.length>0,cn],delayMs:500,onSkip:()=>{We.current=null,$e(null),Ot(null),Re(en&&Ue.length===0)},onCleanup:()=>Re(!1),run:async({isCurrent:se,signal:he})=>{const ve=cn;Re(!0),Ot(null);try{const _e=await Rp({batches:Ue,tokenAddress:Te.address,chainId:D,estimate:Le,signal:he});if(!se())return;We.current={key:ve,quote:_e},$e(_e.gasFee)}catch(_e){if(!se())return;We.current=null,$e(null),Ot(_e instanceof Error?_e.message:"Failed to estimate gas fee")}finally{se()&&Re(!1)}}}),ae(()=>{qe||kt(null)},[qe,z,D,Te?.address]);const It=te(()=>{R(!0),M("select")},[]),pt=te(()=>{$t||t()},[t,$t]),Un=_(null);Un.current={batches:Ue,walletAddress:Ee,recipient:wt,token:Te,chainId:D,amount:z,grossAmountRaw:ln,gasFee:ct,feeEstimate:cn&&We.current?.key===cn?We.current.quote.feeEstimate:null,isNon7702:h,buildWithdrawBatches:_t,execution:{estimate:Le,execute:et},ui:{setIsExecuting:Ct,setExecutionError:at,setExecutionProgress:Dt,setLockedGasFee:kt},executionContextRef:Ke,isMountedRef:gt,onWithdrawExecute:s,onWithdrawSuccess:r,buildSpicenetBatch:d};const hn=te(()=>(De.current=Date.now(),Bl(Un.current)),[]),Oo=te(()=>(De.current=Date.now(),Op(Un.current)),[]);if(ae(()=>{if(!e){const se=setTimeout(()=>{M(E()),R(!1),N(null),L(null),fe(""),Q(!1),re(!1),J(!1),me(""),Ct(!1),at(null),Dt(null),Ke.current=null},300);return()=>clearTimeout(se)}},[e,h]),ae(()=>{if(!h&&e&&I==="provider-login"&&ie&&ke&&Be&&!W){const se=setTimeout(()=>{R(!0),M("select")},100);return()=>clearTimeout(se)}},[h,e,I,ie,ke,Be,W]),!e)return null;if(I==="provider-login"&&!h)return u(ea,{onAuthSuccess:It,autoTrigger:!0});if(I==="select"){const se=parseFloat(z)||0,he=jt?na(on,jt):z||"0",ve=!!q&&on>q.balance,_e=(D?Ge(D):null)?.displayName||"Network",Vt=D?to[D]||Qo:null,St=Te?.symbol||"\u2014",sn=Pn,rn=Te?na(Zt,Te.decimals):"0",un=q&&q.balanceFormatted>0?q.balanceUsd/q.balanceFormatted:void 0,Gt=q?.priceStatus==="stale",tn=Ol(se,un,Gt),Pt=Ol(parseFloat(rn)||0,un,Gt),ro=(!j||fn(Y))&&(!ye||!ge(wt,Be)),Yt=!h&&!ye&&se>0&&Te!==null,Cn=!Yt||ct!==null&&!ut&&!ft,An=se>0&&!ve&&!$&&!Ze&&q!==null&&D!==null&&Te!==null&&wt&&ro&&Cn&&Zt>0n&&(!ye||Je.canExecute&&!vn),kn=!An,Yn=$?"LOADING BALANCES":Ze?"BALANCES UNAVAILABLE":q===null?"NO BALANCE":se===0?"ENTER AMOUNT":ve?"INSUFFICIENT BALANCE":Yt&&!Cn?ft?"GAS UNAVAILABLE":"ESTIMATING GAS":Yt&&Zt===0n?"AMOUNT TOO SMALL":ye&&!Je.canExecute?"REVIEW FEES":"WITHDRAW",yo=!!je&&(je.step==="success"||je.step==="error"),H=o?.primaryColor||k.colors.primary,we=402,He=(Se,mt,rt)=>u(hf,{label:Se,loading:rt,balance:mt,dark:A,dk:b});return u(Dn,{isOpen:!0,onClose:pt,title:"Withdraw",subtitle:u(If,{dark:A,dk:b}),styles:o,theme:k,dark:A,maxWidth:"486px",footerLinkText:"Spicenet accounts \u2192",overlayDimmed:!1,closeOnBackdropClick:n,overlayContent:yo?u("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,display:"flex",flexDirection:"column",justifyContent:"flex-end",pointerEvents:"none",zIndex:20},children:u("div",{style:{pointerEvents:"auto"},children:u(ta,{type:"withdraw",isOpen:!0,isProcessing:qe,onRetryTx:()=>{Oo()},onNewTx:()=>{Dt(null),fe(""),at(null),Ke.current=null},onClose:()=>{Dt(null),at(null),Ct(!1),Ke.current=null},onComplete:()=>{Dt(null),at(null),Ct(!1),Ke.current=null},results:[{asset:{symbol:Te?.symbol||"Token",address:Te?.address||""},txHash:je?.txHash||"",success:je?.step==="success",error:je?.error,amount:z}],chainId:D??void 0,theme:k})})}):null,children:C("fieldset",{disabled:$t,style:{border:0,minWidth:0,width:"calc(100% - 32px)",maxWidth:`${we}px`,margin:"0 auto",padding:"0 0 4px 0",position:"relative"},children:[C("div",{style:{marginTop:"16px",marginBottom:"16px",display:"flex",flexDirection:"column",gap:"16px"},children:[u(kf,{header:He("Source",wn,$),amount:z,setAmount:fe,isInsufficient:ve,sourceAmountDecimals:jt,selectedSourceAsset:q,resolvedSelectedSourceAsset:q,spiceAssets:Ce,setSelectedSourceAsset:N,sourceUsdEstimate:tn,sourceTokenLabel:sn,sourceChainLabel:bn,totalSelectedBalance:wn,showSourceTokenPopover:ne,setShowSourceTokenPopover:re,tokenPopoverPos:G,setTokenPopoverPos:P,tokenTriggerRef:de,primaryColor:H,dark:A,dk:b}),u(xf,{header:He("Destination",Gn?.balanceFormatted??null,On.loading),amount:z,receiveAmountDisplay:rn,receiveUsdEstimate:Pt,selectedDestToken:Te,destTokenSymbol:St,destChainName:_e,destChainLogo:Vt,compatibleDestinationChains:Xe,networkSwitchRef:X,onOpenNetworkPopover:Wt,showNetworkPopover:ce,setShowNetworkPopover:Q,networkPopoverPos:xe,selectedChainId:D,setSelectedChainId:L,dark:A,dk:b})]}),C("div",{style:{marginBottom:k.spacing.sm},children:[u(vf,{show:B,onToggle:Nt,showCustomAddress:j,setShowCustomAddress:J,customRecipient:Y,setCustomRecipient:me,externalAddress:ot,recipientAddress:wt,destChainName:_e,destChainLogo:Vt,compatibleDestinationChains:Xe,txDetailsChainSwitchRef:pe,onOpenNetworkPopover:Wt,sourceChainLabel:bn,sourceDetailsLogo:q?S({...q,logoURI:Vo}).logoURI:Vo,sourceTokenLabel:sn,amount:z,totalSourceDebitDisplay:he,receiveAmountDisplay:rn,destTokenSymbol:St,shouldQuoteWithdrawGas:Yt,estimatingFee:ut,feeError:ft,displayedGasFee:Jt,selectedDestToken:Te,theme:k,styles:o,dark:A,dk:b}),ye&&C("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[u(oo,{palette:b,label:"FEE ASSET",value:Je.fees.isLoading?"Estimating...":st.source?`${S(st.source).symbol} \xB7 ${st.source._source==="spice"?"Spicenet":Ge(st.source.chainId)?.displayName}`:"Unavailable"}),u(oo,{palette:b,label:"MAXIMUM FEE FUNDING",value:Je.fees.isLoading?"Estimating...":Je.fees.ready&&st.source&&st.maximumFeeFunding!=null?`${Fe(st.maximumFeeFunding,st.source.decimals)} ${S(st.source).symbol}`:"Unavailable"}),(Je.status.error||Je.fees.error)&&u(Nn,{variant:"error",size:"compact",palette:b,children:Je.status.error||Je.fees.error}),Je.status.finalizationError&&u(Et,{variant:"outline",dark:A,disabled:Je.status.finalizing,onClick:()=>void Je.retryFinalization(),children:"Retry application update"}),Je.status.statusMsg&&u("span",{role:"status",children:Je.status.statusMsg})]}),q&&!$&&Xe.length===0&&u(Nn,{variant:"warning",size:"compact",palette:b,children:"No withdrawal networks are available for this asset."}),ht&&u(Nn,{variant:"error",size:"compact",palette:b,fontFamily:o?.fontFamily||k.typography.fontFamily,style:{marginBottom:"12px"},children:ht}),ee&&C(Nn,{variant:Ze?"error":"warning",size:"compact",palette:b,children:[Ze?"Unable to load this balance. Please try again.":"Some other balances could not be refreshed."," ",u("button",{type:"button",onClick:()=>void ze(),children:"Retry"})]}),u(Et,{variant:"outline",fullWidth:!0,onClick:()=>{An&&(ye?Je.submitPay():hn())},disabled:kn||$t,theme:k,dark:A,styles:o,style:{marginTop:"8px"},children:$t?"EXECUTING...":ye&&vn?"WITHDRAWN":Yn})]})]})})}return null},fa=Sf,Af=({onDepositClick:e,onWithdrawClick:t,depositDisabled:n=!1,withdrawDisabled:o=!1,primaryColor:s="#EA4B4B",buttonStyles:r,dark:a=!1})=>{if(!e&&!t)return null;const i={button:{backgroundColor:s,...r}};return C("div",{style:{display:"flex",gap:"8px"},children:[e&&u(Et,{variant:"outline",onClick:e,disabled:n,dark:a,styles:i,style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&u(Et,{variant:"outline",onClick:()=>t(),disabled:o,dark:a,styles:i,style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]})},Ef=yn(Af),Ff=({section:e,dk:t,dark:n=!1})=>{const o=s=>{switch(s){case"green":return"#10b981";case"red":return"#ef4444";default:return t.textPrimary}};return C("div",{children:[u("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:t.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:e.title}),u("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.items.map((s,r)=>C("div",{role:s.onClick?"button":void 0,tabIndex:s.onClick?0:void 0,onClick:s.onClick,onKeyDown:s.onClick?a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),s.onClick?.())}:void 0,style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:t.cardBg,border:n?`1px solid ${t.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"},children:[C("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.tokenLogoURI?u("img",{src:s.tokenLogoURI,alt:s.tokenSymbol,style:{width:"20px",height:"20px",borderRadius:"50%"}}):u("div",{style:{width:"20px",height:"20px",borderRadius:"50%",backgroundColor:n?t.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",fontWeight:600,color:t.textSecondary},children:s.tokenSymbol.charAt(0)}),C("div",{children:[u("div",{style:{fontSize:"13px",fontWeight:500,color:t.textPrimary},children:s.tokenSymbol}),u("div",{style:{fontSize:"11px",color:t.textSecondary},children:s.label})]})]}),u("div",{style:{fontSize:"13px",fontWeight:600,color:o(s.valueColor)},children:s.displayValue})]},r))})]})},Tf=yn(Ff);var Bf="data:image/svg+xml,%3csvg width='11' height='11' viewBox='0 0 24 24' fill='none' stroke='black' stroke-opacity='0.5' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' xmlns='http://www.w3.org/2000/svg'%3e%3cpolyline points='17 1 21 5 17 9' /%3e%3cpath d='M3 11V9a4 4 0 0 1 4-4h14' /%3e%3cpolyline points='7 23 3 19 7 15' /%3e%3cpath d='M21 13v2a4 4 0 0 1-4 4H3' /%3e%3c/svg%3e";const Df=({appName:e,status:t,statusLabel:n,totalUsdValue:o,breakdownSubtitle:s,showUsdSummary:r=!0,address:a,dk:i,dark:l=!1,showModeToggle:c,isEmbeddedMode:d=!0,onModeToggle:p})=>{const[f,h]=O(!1),m=async()=>{a&&await Vc(a)&&(h(!0),setTimeout(()=>h(!1),2e3))},g=t==="active",y=n||(g?"Active":"Inactive"),w=g?"#10b981":"#9ca3af",x=C("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[C("div",{children:[u("strong",{children:"Embedded:"})," Deposit assets into ",e," account and use them here."]}),C("div",{children:[u("strong",{children:"External:"})," Use assets from your connected wallet here."]})]});return C("div",{children:[C("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[C("div",{style:{fontSize:"13px",fontWeight:600,color:i.textPrimary},children:[e," Account"]}),c?C("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[C("button",{onClick:p,style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:l?i.hoverBg:"#f3f4f6",border:l?`1px solid ${i.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"11px",fontWeight:600,fontFamily:Oe.mono,color:i.textSecondary,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease",letterSpacing:"0.02em"},children:[u("span",{children:d?"Embedded":"External"}),u("img",{src:Bf,alt:"","aria-hidden":"true",style:{width:"11px",height:"11px",display:"block",...l?{filter:"invert(0.65)"}:{}}})]}),u(rl,{content:x,label:"Account mode info",textColor:l?i.textPrimary:"#f9fafb",backgroundColor:l?i.cardBg:"#111827",borderColor:l?i.cardBorder:"rgba(255,255,255,0.08)",accentColor:l?i.textSecondary:"#6b7280",children:u("img",{src:zr,alt:"","aria-hidden":"true",style:{width:"12px",height:"12px",display:"block",...l?{filter:"invert(0.65)"}:{}}})})]}):C("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:l?i.hoverBg:g?"#ecfdf5":"#f3f4f6",border:l?`1px solid ${i.cardBorder}`:g?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[u("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:w}}),u("span",{style:{fontSize:"11px",fontWeight:500,color:l?i.textSecondary:g?"#065f46":"#6b7280"},children:y})]})]}),r&&u("div",{style:{fontSize:"28px",fontWeight:700,color:i.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:lo(o)}),r&&s&&u("div",{style:{fontSize:"12px",color:i.textSecondary,marginBottom:"8px"},children:s}),a&&C("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[u("span",{style:{fontSize:"12px",fontFamily:Oe.mono,color:l?i.textSecondary:"#9ca3af"},children:Po(a)}),u("button",{onClick:m,style:{padding:"2px 6px",fontSize:"10px",fontWeight:500,backgroundColor:"transparent",color:l?i.textSecondary:"#9ca3af",border:"none",cursor:"pointer",borderRadius:"4px",transition:"background-color 150ms ease, color 150ms ease"},title:"Copy address",children:f?"Copied":"Copy"})]})]})},Of=yn(Df),Rf=({asset:e,label:t,logo:n,dk:o,dark:s})=>{const r=wl(n,e.chainId,e.tokenAddress),[a,i]=En.useState();return n===null?null:r&&r!==a?u("img",{src:r,alt:t,onError:()=>i(r),style:{width:"24px",height:"24px",borderRadius:"50%"}}):u("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:s?o.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:o.textSecondary},children:t.charAt(0)})},Mf=e=>`${e.tokenAddress}-${e.chainId}`,Wf=({spiceAssets:e,loading:t,dk:n,dark:o=!1,canDirectWithdraw:s=!1,onDirectWithdraw:r,directWithdrawState:a,onWithdrawClick:i,limit:l})=>{const c=Rn(),[d,p]=O(!1),f=l!==void 0&&!d?Math.max(e.length-l,0):0,h=f>0?e.slice(0,l):e,m={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},g={backgroundColor:n.cardBg,border:o?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return t?C("div",{children:[u("div",{style:m,children:"Idle Balances"}),[1,2].map(y=>u("div",{style:{...g,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},y))]}):e.length===0?C("div",{children:[u("div",{style:m,children:"Idle Balances"}),u("div",{style:{...g,padding:"16px",textAlign:"center",fontSize:"13px",color:o?n.textSecondary:"#9ca3af"},children:"No assets yet. Deposit to get started."})]}):C("div",{children:[u("div",{style:m,children:"Idle Balances"}),C("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[h.map(y=>{const w=Ge(y.chainId),x=y.chainDisplayName||w?.displayName||`Chain ${y.chainId}`,v=c({symbol:y.tokenSymbol,displaySymbol:y.tokenDisplaySymbol||y.tokenDisplayName,displayName:y.tokenDisplayName,receiptTokenId:y.receiptTokenId,receiptTokenName:y.receiptTokenName,location:y.location,logoURI:y.logoURI}),k=v.symbol,A=Mf(y),b=y.receiptTokenId&&i,S=b||s&&y.directWithdraw&&!!r,T=!b&&a?.key===A?a:null,E=T?.step==="pending";return C("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...g},children:[C("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[u(Rf,{asset:y,label:k,logo:v.logoURI,dk:n,dark:o}),C("div",{children:[u("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:k}),u("div",{style:{fontSize:"11px",color:o?n.textSecondary:"#9ca3af"},children:x})]})]}),C("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[C("div",{style:{textAlign:"right"},children:[u("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:cs({balance:BigInt(y.balance),decimals:y.tokenDecimals})}),u("div",{style:{fontSize:"11px",color:T?.step==="error"?n.errorText:o?n.textSecondary:"#9ca3af"},children:T?.step==="error"?T.message||"Withdraw failed":!Number.isFinite(y.usdValue)||y.usdValue<=0?"\u2014":`${lo(y.usdValue)}${y.priceStatus==="stale"?" (stale)":""}`})]}),S&&u("button",{onClick:()=>{E||(b?b(y.receiptTokenId):r(y))},disabled:E,title:b?"Choose withdrawal network":"Withdraw to external wallet",style:{padding:"6px 10px",borderRadius:"6px",border:o?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",backgroundColor:o?n.hoverBg:"#ffffff",color:n.textPrimary,fontSize:"11px",fontWeight:600,cursor:E?"default":"pointer",opacity:E?.6:1,whiteSpace:"nowrap"},children:E?"Withdrawing\u2026":"Withdraw"})]})]},y.positionId??`${y.owner??""}:${y.location??""}:${y.receiptTokenId??`${y.tokenAddress}-${y.chainId}`}`)}),l!==void 0&&e.length>l&&C("button",{onClick:()=>p(!d),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:"6px",width:"100%",padding:"8px 12px",...g,cursor:"pointer",color:n.textSecondary,fontSize:"12px",fontWeight:500},children:[u("span",{children:d?"Show less":`Show ${f} more`}),u("span",{style:{transform:d?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]})]})]})},Nf=yn(Wf),Pf=({pendingDeposits:e,onCompleteDeposit:t,dk:n,dark:o=!1})=>e.length===0?null:C("div",{children:[u("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:"Pending Deposits"}),u("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((s,r)=>{const a=Ge(s.chainId)?.displayName||`Chain ${s.chainId}`;return C("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:o?n.warningBg:"#fffbeb",border:o?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"8px"},children:[C("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[u("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:o?n.hoverBg:"#fde68a",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:n.warningText},children:s.tokenSymbol.charAt(0)}),C("div",{children:[C("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:[s.amount," ",s.tokenSymbol]}),C("div",{style:{fontSize:"11px",color:n.warningText},children:["on ",a]})]})]}),u("button",{onClick:()=>t?.(s),style:{padding:"4px 12px",fontSize:"11px",fontWeight:600,backgroundColor:o?n.hoverBg:"#fef3c7",color:o?n.textPrimary:"#92400e",border:o?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"9999px",cursor:"pointer",transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease"},children:"Complete"})]},`${s.tokenAddress}-${s.chainId}-${r}`)})})]}),Uf=yn(Pf),Lf=({appName:e,status:t,statusLabel:n,totalUsdValue:o,breakdownSubtitle:s,showUsdSummary:r,address:a,spiceAssets:i,spiceAssetsLoading:l,pendingDeposits:c,customSections:d,notice:p,onDepositClick:f,onWithdrawClick:h,depositDisabled:m,onCompleteDeposit:g,primaryColor:y,buttonStyles:w,dk:x,dark:v=!1,showModeToggle:k,isEmbeddedMode:A,onModeToggle:b,showConnectExternalCta:S,onConnectExternalWallet:T,connectExternalError:E,showHowItWorks:I=!0,canDirectWithdraw:M,onDirectWithdraw:W,directWithdrawState:R,idleBalancesLimit:F})=>{const[N,D]=O(!1);return C("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[u(Of,{appName:e,status:t,statusLabel:n,totalUsdValue:o,breakdownSubtitle:s,showUsdSummary:r,address:a,dk:x,dark:v,showModeToggle:k,isEmbeddedMode:A,onModeToggle:b}),p&&u("div",{style:{padding:"10px 12px",borderRadius:"8px",backgroundColor:p.tone==="warning"?v?"rgba(245, 158, 11, 0.12)":"#fffbeb":p.tone==="success"?v?"rgba(16, 185, 129, 0.12)":"#ecfdf5":x.cardBg,border:p.tone==="warning"?v?"1px solid rgba(245, 158, 11, 0.35)":"1px solid #fde68a":p.tone==="success"?v?"1px solid rgba(16, 185, 129, 0.35)":"1px solid #a7f3d0":v?`1px solid ${x.cardBorder}`:"1px solid #e5e7eb",color:p.tone==="warning"?v?"#fbbf24":"#92400e":p.tone==="success"?v?"#34d399":"#047857":x.textSecondary,fontSize:"12px",lineHeight:1.45,fontWeight:500},children:p.message}),S&&C("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[u("button",{onClick:T,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:y||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:Oe.ui,transition:"opacity 150ms ease"},children:"Connect External Wallet"}),E&&u("span",{style:{fontSize:"11px",color:v?x.errorText:"#b91c1c",lineHeight:1.4},children:E})]}),u("div",{style:{height:"1px",backgroundColor:v?"#2d2d2d":"#e5e7eb"}}),u(Ef,{onDepositClick:f,onWithdrawClick:h,depositDisabled:m,primaryColor:y,buttonStyles:w,dark:v}),I&&C("div",{children:[C("button",{onClick:()=>D(!N),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:x.cardBg,border:v?`1px solid ${x.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:x.textSecondary,fontSize:"12px",fontWeight:500},children:[u("span",{children:"How It Works"}),u("span",{style:{transform:N?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),N&&C("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:v?x.cardBg:"#f0fdf4",border:v?`1px solid ${x.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:v?x.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),u(Uf,{pendingDeposits:c,onCompleteDeposit:g,dk:x,dark:v}),u(Nf,{spiceAssets:i,loading:l,dk:x,dark:v,canDirectWithdraw:M,onDirectWithdraw:W,directWithdrawState:R,onWithdrawClick:h,limit:F}),d.map((L,z)=>u(Tf,{section:L,dk:x,dark:v},z))]})},zf=yn(Lf);function Hf({dark:e,onSuccess:t,onError:n}){const{disconnect:o}=La(),{logout:s}=ad(),[r,a]=O(!1);return u(Et,{variant:"ghost",fullWidth:!0,dark:e,loading:r,onClick:async()=>{a(!0);try{o(),await s(),t()}catch(i){n(Mn(i,"Unable to disconnect. Please try again."))}finally{a(!1)}},children:"Disconnect"})}const ma=380,go=8,qf=[],Vf={};function gc(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function Qf(e,t){const n=new Map;Object.entries(t).forEach(([s,r])=>{if(!Number.isFinite(r)||r<=0)return;n.set(s,r),n.set(s.toUpperCase(),r);const a=gc(s);a&&n.set(a,r)});const o=[e.symbol,e.displaySymbol,e.receiptTokenName,e.name,e.displayName];for(const s of o){if(!s)continue;const r=n.get(s)??n.get(s.toUpperCase());if(r!==void 0)return r;const a=gc(s);if(!a)continue;const i=n.get(a);if(i!==void 0)return i}return 0}const yc=({appName:e,status:t="active",statusLabel:n,customSections:o=qf,extraAssets:s=[],tokenPrices:r={},tokenLogos:a=Vf,breakdownLabels:i=[],notice:l,styles:c,dark:d,onDepositSuccess:p,onDepositClick:f,onWithdrawClick:h,onCompleteDeposit:m,showModeToggle:g=!1,defaultMode:y,showUsdSummary:w=!0,alwaysShowEmbeddedIdle:x=!1,idleBalancesLimit:v,showDisconnect:k=!1})=>{const A=Qt(Mt),b=A?.mode!=="7702",S=!!A?.isWhitelistGateActive,T=!!A?.isWhitelistConfigured&&A?.isUserWhitelisted!==!0,E=_(!1);ae(()=>{if(!E.current){if(Qc()){E.current=!0;return}y&&A?.setMode&&(A.setMode(y==="non7702"?"ondemand":"7702"),E.current=!0)}},[A,y]);const[I,M]=O(!1),[W,R]=O(null),[F,N]=O({top:0,bottom:0,left:0,placement:"below"}),D=_(null),L=_(null),{address:z,isConnected:fe}=Zn(),ce=A?.embeddedWalletAddress,Q=A?.externalWalletAddress,{embeddedAddress:ne}=ps(),{brand:re,dark:j,primaryColor:J,dk:Y}=Bt(c,d),me=e??re?.appName??"Spice",B=b&&!Q,U=!b||x,X=U?ce||ne:z,pe=ue(()=>A?.supportedChainIds??ys("mainnet"),[A?.supportedChainIds]),de=Ao({owner:U?X:Q,role:"holding",sourceChains:pe,additionalSourceTokens:s.filter($=>!$.receiptTokenId&&(!$.owner||ge($.owner,U?X:Q))).map($=>({address:$.tokenAddress,chainId:$.chainId,decimals:$.tokenDecimals,symbol:$.tokenSymbol,logoURI:$.logoURI})),includeRollupAssets:U,enabled:U?!!X:!!Q}),xe=de.assets.filter($=>$._source==="spice"),K=de.walletAssets,G=de.loading,P=de.refresh,V=U?X:Q,ie=ue(()=>s.filter($=>!$.owner||$.owner.toLowerCase()===V?.toLowerCase()).map($=>({...$,owner:$.owner??V,location:$.location??($.receiptTokenId?"rollup":U?"embedded":"external")})),[s,V,U]),ke=ue(()=>{const $=new Map(Object.entries(r).filter(([,ee])=>Number.isFinite(ee)&&ee>0).map(([ee,ze])=>[ee.toLowerCase(),ze]));return K.map(ee=>({owner:ee.owner,location:ee.location,positionId:nt(ee),tokenAddress:ee.address,tokenSymbol:ee.symbol,tokenDecimals:ee.decimals,chainId:ee.chainId,chainDisplayName:gn(ee.chainId),balance:ee.balance.toString(),balanceFormatted:ee.balanceFormatted,usdValue:ee.balanceUsd||($.get(`${ee.chainId}:${ee.address.toLowerCase()}`)??0)*ee.balanceFormatted,logoURI:ee.logoURI||a[ee.symbol],directWithdraw:U}))},[K,ie,a,r,U]),Ee=ue(()=>{const $=U?xe.map(le=>{const Pe=le.balanceUsd||0,Ae=Number.isFinite(le.balanceFormatted)?le.balanceFormatted:0,q=Qf(le,r),Ze=le.priceStatus&&q>0?q*Ae:Pe>0?Pe:q*Ae;return{owner:le.owner,location:le.location,positionId:nt(le),tokenAddress:le.address,tokenSymbol:le.symbol,tokenDisplaySymbol:Gc(le),tokenDisplayName:jc(le),tokenDecimals:le.decimals,chainId:le.chainId,chainDisplayName:or(le),balance:le.balance.toString(),balanceFormatted:le.balanceFormatted,usdValue:Ze,priceStatus:q>0?void 0:le.priceStatus,logoURI:le.logoURI,receiptTokenId:le.receiptTokenId,receiptTokenName:le.receiptTokenName}}):[],ee=le=>`${le.owner?.toLowerCase()}:${le.location}:${le.chainId}:${le.receiptTokenId??Ye(le.tokenAddress).toLowerCase()}`,ze=new Map([...de.rollupAssets,...K].map(le=>[ee({...le,tokenAddress:le.address}),le])),Ce=new Map([...$,...ke].map(le=>[ee(le),le]));for(const le of B?[]:ie){const Pe=ee(le),Ae=Ce.get(Pe);Ce.set(Pe,Ae?{...le,...Ae,logoURI:le.logoURI??Ae.logoURI,tokenDisplayName:le.tokenDisplayName??Ae.tokenDisplayName,tokenDisplaySymbol:le.tokenDisplaySymbol??Ae.tokenDisplaySymbol}:le)}return[...Ce.values()].filter(le=>BigInt(le.balance)>0n&&Ai({isDiscovered:ze.get(ee(le))?.isDiscovered,balanceUsd:le.usdValue},!0)&&is(ze.get(ee(le))??{address:le.tokenAddress,symbol:le.tokenSymbol,displaySymbol:le.tokenDisplaySymbol},A?.allowedTokens)).sort((le,Pe)=>Pe.usdValue-le.usdValue)},[U,B,xe,de.rollupAssets,r,ke,ie,A?.allowedTokens]),Be=ue(()=>Ee.reduce(($,ee)=>$+ee.usdValue,0),[Ee]),{pendingDeposits:Ie,refresh:Z}=Yi({chainIds:pe,enabled:!!z,discoverWalletBalances:!0}),ot=ue(()=>o.reduce(($,ee)=>$+(ee.totalValue??0),0),[o]),qe=Be+ot,Ct=ue(()=>{const $=[];Be>0&&$.push(`${lo(Be)} idle`);for(const ee of o){const ze=i.find(Ce=>Ce.sectionTitle===ee.title)?.label||ee.title.toLowerCase();$.push(`${lo(ee.totalValue??0)} ${ze}`)}return $.join(" \xB7 ")},[Be,o,i]),ht=te($=>{m?m($):R($)},[m]),Ve=te(()=>{R(null)},[]),Qe=te(()=>{R(null),p?.()},[p]),at=te(()=>{if(!D.current)return;const $=D.current.getBoundingClientRect(),ee=window.innerHeight-$.bottom-go,ze=$.top-go,Ce=ee>=400||ee>=ze?"below":"above",le=Math.max(go,Math.min($.right-ma,window.innerWidth-ma-go)),Pe=Ce==="below"?$.bottom+go:$.top-go,Ae=Ce==="above"?window.innerHeight-Pe:0;N({top:Pe,bottom:Ae,left:le,placement:Ce})},[]);Da(()=>{I&&at()},[I,at]),ae(()=>{if(!I)return;const $=Ce=>{D.current&&!D.current.contains(Ce.target)&&L.current&&!L.current.contains(Ce.target)&&M(!1)},ee=Ce=>{Ce.key==="Escape"&&M(!1)},ze=()=>at();return document.addEventListener("mousedown",$),document.addEventListener("keydown",ee),window.addEventListener("scroll",ze,{passive:!0}),window.addEventListener("resize",at),()=>{document.removeEventListener("mousedown",$),document.removeEventListener("keydown",ee),window.removeEventListener("scroll",ze),window.removeEventListener("resize",at)}},[I,at]);const je=U?ce||ne||z:Q||z,Dt=te(()=>{A?.setMode&&A.setMode(b?"7702":"ondemand")},[A,b]),[Ke,gt]=O(null);let De=null;try{De=qa({onSuccess:()=>gt(null),onError:$=>gt(Mn($,"Failed to connect wallet."))}).connectWallet}catch{De=null}const et=te(()=>{De&&(M(!1),gt(null),De({walletChainType:"ethereum-only"}))},[De]),Le=!Q&&!!De,ct=te(()=>{M(!1),f?.()},[f]),$e=te($=>{M(!1),h?.($)},[h]),dt=te($=>{M(!1),ht($)},[ht]),[kt,ut]=O(null),Re=U&&!!Q&&!ge(V,Q),ft=te($=>{const ee=K.find(ze=>ze.chainId===$.chainId&&ge(ze.address,$.tokenAddress));ee&&(M(!1),ut(ee))},[K]);if(typeof window>"u")return null;const Ot=C("button",{ref:D,onClick:()=>M(!I),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:j?Y.hoverBg:"#ffffff",border:j?`1px solid ${Y.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:Oe.ui,color:j?Y.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:j?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[C("span",{children:[me," Account"]}),fe&&w&&C("span",{style:{color:j?Y.textSecondary:"#6b7280"},children:["\xB7 ",lo(qe)]}),u("span",{style:{fontSize:"10px",color:j?Y.textSecondary:"#9ca3af",transform:I?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),Me=I?pr.createPortal(C(an,{children:[u("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:ao.popover},onClick:()=>M(!1)}),C("div",{ref:L,style:{position:"fixed",top:F.placement==="below"?`${F.top}px`:"auto",bottom:F.placement==="above"?`${F.bottom}px`:"auto",left:`${F.left}px`,width:`${ma}px`,maxWidth:`calc(100vw - ${go*2}px)`,maxHeight:"80vh",backgroundColor:j?Y.shell:"#ffffff",border:j?`1px solid ${Y.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:j?"0 10px 40px rgba(0, 0, 0, 0.5)":"0 10px 40px rgba(0, 0, 0, 0.12)",zIndex:ao.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${wo.out}`},children:[u(zf,{appName:me,status:t,statusLabel:n,totalUsdValue:qe,breakdownSubtitle:Ct,showUsdSummary:w,address:U?je:z,spiceAssets:Ee,spiceAssetsLoading:G,pendingDeposits:Ie,customSections:o,notice:l,onDepositClick:f?ct:void 0,onWithdrawClick:h?$e:void 0,depositDisabled:T,onCompleteDeposit:dt,primaryColor:J,buttonStyles:c?.button,dk:Y,dark:j,showModeToggle:g,isEmbeddedMode:!b,onModeToggle:Dt,showConnectExternalCta:Le,onConnectExternalWallet:et,connectExternalError:Ke,showHowItWorks:!S,canDirectWithdraw:Re,onDirectWithdraw:ft,idleBalancesLimit:v}),k&&fe&&u("div",{style:{padding:"0 16px 16px"},children:u(Hf,{dark:j,onSuccess:()=>M(!1),onError:gt})})]}),u("style",{children:`
44
+ `,Il=({title:e,showChevron:t,expanded:n,onToggleDetails:o,showClose:s,onClose:r,fontFamily:a,labelColor:i,textPrimary:l,closeHoverBg:c,closePressedBg:d})=>{const[p,f]=O(!1),[h,m]=O(!1);return C("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"16px"},children:[C("div",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:o?"pointer":"default"},onClick:o,children:[C("span",{style:{fontSize:"13px",fontWeight:500,color:i,fontFamily:a},children:[e," "]}),t&&u(Eo,{color:i,direction:n?"up":"down"})]}),s&&u("button",{onClick:r,onMouseEnter:()=>f(!0),onMouseLeave:()=>{f(!1),m(!1)},onMouseDown:()=>m(!0),onMouseUp:()=>m(!1),style:{background:h?d:p?c:"none",border:"none",borderRadius:"4px",cursor:"pointer",padding:"4px",display:"flex",alignItems:"center",justifyContent:"center",color:p||h?l:i,transform:h?"scale(0.9)":p?"scale(1.1)":"scale(1)",transition:In.interactive},children:u(Jo,{size:16})})]})},Sl=({chainName:e,bg:t,border:n,textPrimary:o,labelColor:s,primaryColor:r})=>C("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"20px 16px",borderRadius:"8px",backgroundColor:t,border:`1px solid ${n}`,gap:"12px"},children:[u(Ln,{size:24,borderWidth:3,color:r}),C("div",{children:[u("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:Oe.mono,letterSpacing:"0.5px",color:o},children:"PROCESSING TRANSACTION"}),C("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:s},children:["on ",e]})]})]}),Al=({bg:e,border:t,left:n,right:o})=>C("div",{style:{padding:"10px 12px",borderRadius:"6px",backgroundColor:e,border:`1px solid ${t}`,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[n,o]}),ta=({isOpen:e,onClose:t,onComplete:n,closeOnComplete:o=!1,type:s,results:r,chainId:a,chainName:i,explorerUrl:l,theme:c,styles:d,dark:p,intentStatus:f,onRetry:h,onNewTx:m,onRetryTx:g,asOverlay:y=!0,isProcessing:w=!1,showStepBreakdown:x=!0})=>{const{theme:v,primaryColor:k,dark:A,dk:b}=Bt(d,p),S=c||v,[T,E]=O(!1),I=i??(a?gn(a):"Network"),M=l??(a&&us(a,"").replace(/\/tx\/.*$/,"")||void 0),W=A?b.cardBg:"#ffffff",R=A?"0 4px 20px rgba(0, 0, 0, 0.4)":"0 4px 20px rgba(0, 0, 0, 0.1)",F=A?"0 -4px 8px -2px rgba(0, 0, 0, 0.4)":"0 -4px 8px -2px rgba(0, 0, 0, 0.15)",N=b.textSecondary,D=A?b.textPrimary:"#374151",L=A?b.inputBg:"#f9fafb",z=A?b.inputBorder:"#e5e7eb",fe=A?b.inputBg:"#f3f4f6",ce=A?b.inputBorder:"#e5e7eb",[Q,ne]=O(!0),re=A?b.inputBg:"#f9fafb",j=A?b.hoverBg:"#f3f4f6",J=A?{successBg:b.successBg,successBorder:b.successBorder,successText:b.successText,errorBg:b.errorBg,errorBorder:b.errorBorder,errorText:b.errorText}:{},Y=f?.steps.find(de=>de.status==="failed")?.error;ae(()=>{!e&&!f&&E(!1)},[e,f]);const me=()=>{E(!0),setTimeout(()=>{window.dispatchEvent(new CustomEvent("tx-complete",{detail:{type:s,results:r}})),window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:{type:s,status:"success",results:r}})),n?.(),o&&t()},300)},B=()=>{ne(!Q)};if(f){const{steps:de,overallStatus:xe}=f,K=xe==="processing",G=xe==="success",P=xe==="failed",V=de.filter(Be=>Be.transactionHash)[0],ie=de.length>1?de.map(Be=>Be.chainName).filter(Boolean).join(" and "):I!=="Network"?I:de[0]?.chainName||I,ke=M||(V?us(V.chainId,V.transactionHash||"").replace(/\/tx\/.*$/,""):void 0),Ee=C(an,{children:[u(Il,{title:K?`Processing ${s.charAt(0).toUpperCase()+s.slice(1)}`:`${s.charAt(0).toUpperCase()+s.slice(1)} results`,showChevron:x,expanded:Q,onToggleDetails:B,showClose:!K,onClose:t,fontFamily:d?.fontFamily||S.typography.fontFamily,labelColor:N,textPrimary:D,closeHoverBg:re,closePressedBg:j}),u("div",{style:{marginBottom:"16px"},children:K?u(Sl,{chainName:ie,bg:fe,border:ce,textPrimary:D,labelColor:N,primaryColor:k}):u(Cl,{isSuccess:G,type:s,chainName:ie,explorerUrl:ke,txHash:V?.transactionHash,dark:A,...J,textSecondary:N})}),x&&u("div",{style:{overflow:"hidden",maxHeight:Q?"300px":"0px",opacity:Q?1:0,transition:"max-height 0.3s ease, opacity 0.3s ease",marginBottom:Q?"16px":"0"},children:u("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:de.map((Be,Ie)=>{const Z=Be.transactionHash?us(Be.chainId,Be.transactionHash):null;return u(Al,{bg:L,border:z,left:u("span",{style:{fontSize:"13px",color:D},children:Be.chainName?`On ${Be.chainName}`:Be.description||`Step ${Ie+1}`}),right:C("span",{style:{display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:Be.status==="success"?"#10b981":Be.status==="failed"?"#ef4444":N,fontWeight:500},children:[Z&&u("a",{href:Z,target:"_blank",rel:"noopener noreferrer",style:{color:A?b.infoText:"#2563eb",textDecoration:"none"},onClick:ot=>ot.stopPropagation(),children:"View"}),Be.status==="success"?"\u2713":Be.status==="failed"?"\u2717":"\u25CB"]})},Ie)})})}),!K&&C("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[P&&h&&u(Et,{variant:"outline",fullWidth:!0,onClick:h,theme:S,styles:d,dark:A,children:"TRY AGAIN"}),m&&C(Et,{variant:"outline",fullWidth:!0,onClick:m,theme:S,styles:d,dark:A,children:["NEW ",s.toUpperCase()," \u2192"]})]})]});return y?C("div",{style:{position:"absolute",bottom:0,left:0,right:0,zIndex:10,animation:T?"slideDown 0.3s ease-in forwards":"slideUp 0.3s ease-out forwards",pointerEvents:"auto"},children:[u("div",{style:{backgroundColor:W,borderRadius:"12px 12px 0 0",width:"100%",padding:"18px 24px 24px",boxShadow:F},children:Ee}),u("style",{children:kl})]}):u("div",{style:{backgroundColor:W,borderRadius:"12px",padding:"24px",width:"100%",boxShadow:R},children:Ee})}if(!e&&!w||!w&&(!r||r.length===0))return null;const U=r?r.every(de=>de.success):!1,X=r?.[0],pe=[...r??[]].reverse().find(de=>de.txHash)?.txHash||X?.txHash;return C("div",{style:{position:y?"absolute":"relative",bottom:y?0:void 0,left:y?0:void 0,right:y?0:void 0,zIndex:y?10:void 0,animation:y?T?"slideDown 0.3s ease-in forwards":"slideUp 0.3s ease-out forwards":void 0,pointerEvents:"auto",width:"100%"},children:[u("div",{style:{backgroundColor:W,borderRadius:y?"12px 12px 0 0":"12px",width:"100%",padding:"18px 0 24px",boxShadow:y?F:R},children:C("div",{style:{width:"100%",boxSizing:"border-box",padding:"0 24px"},children:[u(Il,{title:w?`Processing ${s.charAt(0).toUpperCase()+s.slice(1)}`:`${s.charAt(0).toUpperCase()+s.slice(1)} results`,showChevron:!w&&x,expanded:Q,onToggleDetails:w?void 0:B,showClose:!w,onClose:t,fontFamily:d?.fontFamily||S.typography.fontFamily,labelColor:N,textPrimary:D,closeHoverBg:re,closePressedBg:j}),u("div",{style:{marginBottom:"16px",animation:"statusFadeIn 220ms cubic-bezier(0.22, 1, 0.36, 1) both"},children:w?u(Sl,{chainName:I,bg:fe,border:ce,textPrimary:D,labelColor:N,primaryColor:k}):u(Cl,{isSuccess:U,type:s,chainName:I,explorerUrl:M,txHash:pe,dark:A,...J,textSecondary:N})},w?"processing":U?"success":"error"),!w&&x&&r&&r.length>1&&u("div",{style:{overflow:"hidden",maxHeight:Q?"200px":"0px",opacity:Q?1:0,transition:"max-height 0.3s ease, opacity 0.3s ease",marginBottom:Q?"16px":"0"},children:u("div",{style:{maxHeight:"180px",overflowY:"auto",display:"flex",flexDirection:"column",gap:"8px"},children:r.map((de,xe)=>u(Al,{bg:L,border:z,left:C("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[u("span",{style:{fontWeight:600,fontSize:"13px",color:b.textPrimary,fontFamily:Oe.mono},children:de.asset.symbol}),de.amount&&u("span",{style:{fontSize:"12px",color:N},children:de.amount})]}),right:u("span",{style:{fontSize:"12px",color:de.success?"#10b981":"#ef4444",fontWeight:500},children:de.success?"\u2713":"\u2717"})},xe))})}),!w&&!U&&r&&u("div",{style:{padding:"12px",backgroundColor:b.errorBg,border:`1px solid ${b.errorBorder}`,borderRadius:"8px",marginBottom:"16px"},children:u("p",{style:{fontSize:"13px",color:b.errorText,margin:0,lineHeight:1.5},children:Y||r.find(de=>!de.success)?.error||`${s.charAt(0).toUpperCase()+s.slice(1)} failed. Please try again.`})}),!w&&C("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[!U&&g&&C(Et,{variant:"outline",fullWidth:!0,onClick:g,theme:S,styles:d,dark:A,children:["TRY AGAIN ",s.toUpperCase()]}),U&&u(Et,{variant:"outline",fullWidth:!0,onClick:me,theme:S,styles:d,dark:A,children:"DONE"})]})]})}),u("style",{children:kl})]})};function El(e){const t=new Set(ed(e).map(n=>n.toLowerCase()));return t.add(e.toLowerCase()),t}const kp=["USDC","USDT","WETH","WBTC"];function Fl(e,t){const n=Ge(t);if(!n)return;if(n.nativeCurrency.symbol.toUpperCase()===e.toUpperCase())return{address:Tt,symbol:n.nativeCurrency.symbol,decimals:n.nativeCurrency.decimals,chainId:t};const o=n.supportedTokens?.find(s=>s.symbol.toUpperCase()===e.toUpperCase());if(o)return{address:o.address.toLowerCase(),symbol:o.symbol,decimals:o.decimals,chainId:t}}function jn(e,t,n){const o=Ge(t);if(!o)return;if(n!==void 0){if(be(e)&&!Ft(e,n))return;const a=Tr(e,n,t);return a?{address:a.address.toLowerCase(),symbol:a.symbol,decimals:a.decimals,chainId:t}:void 0}if(be(e))return;const s=El(e),r=o.supportedTokens?.find(a=>s.has(a.address.toLowerCase()));if(r)return{address:r.address.toLowerCase(),symbol:r.symbol,decimals:r.decimals,chainId:t}}function Ip(e){const{sourceAsset:t,outputAsset:n,sourceChainId:o,destinationChainId:s,intermediaryCandidates:r=kp}=e;if(Is(t,n))return{strategy:"direct",sourceAsset:t,outputAsset:n,sourceChainId:o,destinationChainId:s,summary:`${t.symbol} fronted directly`};if(o===s&&(be(t.address)||!Ft(t.address,o)))return{strategy:"direct-swap",sourceAsset:t,outputAsset:n,sourceChainId:o,destinationChainId:s,summary:`${t.symbol} \u2192 ${n.symbol} on chain ${o}, no escrow`};if(jn(t.address,s,o))return{strategy:"direct",sourceAsset:t,outputAsset:n,sourceChainId:o,destinationChainId:s,summary:`${t.symbol} fronted on destination, swapped to ${n.symbol}`};if(jn(n.address,o,s))return{strategy:"source-swap",sourceAsset:t,outputAsset:n,sourceChainId:o,destinationChainId:s,summary:`${t.symbol} \u2192 ${n.symbol} on source chain, then fronted`};for(const a of r){const i=Fl(a,o);if(!i||Is(t,i)||Is(n,i))continue;const l=Fl(a,s);if(l&&Is(i,l))return{strategy:"intermediary",sourceAsset:t,outputAsset:n,intermediaryAsset:l,sourceChainId:o,destinationChainId:s,summary:`${t.symbol} \u2192 ${a} on source, fronted, then ${a} \u2192 ${n.symbol} on destination`}}throw new Ne("ROUTE_STRATEGY_ERROR",`No viable cross-chain route found from ${t.symbol} (chain ${o}) to ${n.symbol} (chain ${s}). No intermediary asset is available on both chains.`,{sourceAsset:t.symbol,outputAsset:n.symbol,sourceChainId:o,destinationChainId:s,candidatesChecked:r})}async function Sp(e){const{route:t,sourceAmount:n,userAddress:o,registry:s,actionCalls:r,slippage:a}=e;async function i(l,c,d,p){const f=await s.resolveSwap({type:"swap",tokenIn:c,tokenOut:d,amountIn:p,maxSlippage:a},l,o);if(!f)throw new Ne("NO_LIQUIDITY",`No venue returned a quote for ${c} \u2192 ${d} on chain ${l}. No liquidity available for this pair.`,{chainId:l,tokenIn:c,tokenOut:d,amountIn:p.toString()});return f}switch(t.strategy){case"direct-swap":{const l=await i(t.destinationChainId,t.sourceAsset.address,t.outputAsset.address,n);return{chainBatches:[{chainId:t.destinationChainId,calls:[...l.calls,...r]}],solverFrontToken:t.outputAsset,solverFrontAmount:0n,resolvedSwaps:{sourceSwap:l}}}case"direct":{const l=jn(t.sourceAsset.address,t.destinationChainId,t.sourceChainId)||t.sourceAsset;if(El(l.address).has(t.outputAsset.address.toLowerCase()))return{chainBatches:[{chainId:t.destinationChainId,calls:r}],solverFrontToken:l,solverFrontAmount:n,resolvedSwaps:{}};const c=await i(t.destinationChainId,l.address,t.outputAsset.address,n);return{chainBatches:[{chainId:t.destinationChainId,calls:[...c.calls,...r]}],solverFrontToken:l,solverFrontAmount:n,resolvedSwaps:{destinationSwap:c}}}case"source-swap":{const l=jn(t.outputAsset.address,t.sourceChainId,t.destinationChainId);if(!l)throw new Ne("ROUTE_TOKEN_NOT_FOUND",`Output asset ${t.outputAsset.symbol} (${t.outputAsset.address}) not found on source chain ${t.sourceChainId}`,{token:t.outputAsset.symbol,address:t.outputAsset.address,chainId:t.sourceChainId,side:"source"});const c=jn(t.outputAsset.address,t.destinationChainId,t.destinationChainId);if(!c)throw new Ne("ROUTE_TOKEN_NOT_FOUND",`Output asset ${t.outputAsset.symbol} (${t.outputAsset.address}) not found on destination chain ${t.destinationChainId}`,{token:t.outputAsset.symbol,address:t.outputAsset.address,chainId:t.destinationChainId,side:"destination"});const d=await i(t.sourceChainId,t.sourceAsset.address,l.address,n);return{chainBatches:[{chainId:t.sourceChainId,calls:d.calls},{chainId:t.destinationChainId,calls:r}],solverFrontToken:c,solverFrontAmount:d.amountOutMinimum,resolvedSwaps:{sourceSwap:d}}}case"intermediary":{if(!t.intermediaryAsset)throw new Ne("ROUTE_STRATEGY_ERROR","Intermediary strategy requires an intermediary asset but none was provided in the route plan.",{strategy:t.strategy});const l=jn(t.intermediaryAsset.address,t.sourceChainId,t.destinationChainId);if(!l)throw new Ne("ROUTE_TOKEN_NOT_FOUND",`Intermediary ${t.intermediaryAsset.symbol} (${t.intermediaryAsset.address}) not found on source chain ${t.sourceChainId}`,{token:t.intermediaryAsset.symbol,address:t.intermediaryAsset.address,chainId:t.sourceChainId,side:"source"});const c=await i(t.sourceChainId,t.sourceAsset.address,l.address,n),d=await i(t.destinationChainId,t.intermediaryAsset.address,t.outputAsset.address,c.amountOutMinimum);return{chainBatches:[{chainId:t.sourceChainId,calls:c.calls},{chainId:t.destinationChainId,calls:[...d.calls,...r]}],solverFrontToken:t.intermediaryAsset,solverFrontAmount:c.amountOutMinimum,resolvedSwaps:{sourceSwap:c,destinationSwap:d}}}default:throw new Ne("ROUTE_STRATEGY_ERROR",`Unknown route strategy: ${t.strategy}`,{strategy:t.strategy})}}function Ap(e,t,n){if(!e||!t)return null;const o=ko(e,t),s=Object.entries(e.chainTokens??{}).flatMap(([p,f])=>{const h=qn(p);return h?.chainId===t?[{parsed:h,detail:f}]:[]}),r=p=>n.find(f=>ge(f.address,p))??null,a=p=>{const f=s.find(({parsed:g})=>ge(g.address,p));if(!f)return null;const h=Ge(t);if(be(p))return h?{address:Tt,symbol:h.nativeCurrency.symbol,name:h.nativeCurrency.name,decimals:h.nativeCurrency.decimals,logoURI:e.logoURI}:null;const m=h?.supportedTokens?.find(g=>ge(g.address,p));return!m||!Fr(e,p,t)?null:{address:f.parsed.address,symbol:m.symbol,name:m.name||f.detail?.name||e.displayName||e.name||e.symbol,decimals:m.decimals,logoURI:m.logo||e.logoURI}},i=s.map(({parsed:p})=>p.address).filter(be);for(const p of[...o,...i]){if(be(p)){const m=a(p);if(m)return m}const f=r(p);if(f)return f;const h=a(p);if(h)return h}if(e.chainTokens||e.receiptTokenId)return null;const l=Sn(e,t);if(l){const p=r(l);if(p)return p}const c=jn(e.address,t,e.chainId);return c?r(c.address)||(n.length>0?null:{address:c.address,symbol:c.symbol||e.symbol,name:e.displayName||e.name||e.symbol,decimals:c.decimals??e.decimals,logoURI:e.logoURI}):null}function Ep(e){const t=e.find(n=>bo(n.chainId))?.calls?.[0]?.data;if(!t)return null;try{const n=uo({abi:ar,data:t});return n.functionName!=="createWithdrawalRequest"?null:n.args[0].transfers.map(o=>({token:o.token,recipient:o.to,amount:o.amount}))}catch{return null}}function Fp(e,t){if(!e||e.length!==t.length)return!1;const n=o=>o.reduce((s,r)=>s+r.amount,0n);return n(e)!==n(t)?!1:e.every((o,s)=>{const r=t[s];return o.token.toLowerCase()!==r.token.toLowerCase()||o.recipient.toLowerCase()!==r.recipient.toLowerCase()?!1:o.recipient.toLowerCase()===nn.toLowerCase()?Sa(o.amount,r.amount,100n):o.recipient.toLowerCase()!==Fn.toLowerCase()||o.amount===r.amount})}function Tp(e,t){const n=e.intents.flatMap(r=>r.batches).filter(r=>{const a=io(r);return BigInt(r.quotedAmount)>0n||BigInt(r.totalDebit)>0n||a.totalFee>0n}),o=n.filter(r=>r.chainId===t),s=o.length>0?o:n;return s.length===1?s[0]:null}function Bp(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const o=n.token.toLowerCase(),s=n.recipient.toLowerCase(),r=`${o}:${s}`,a=t.get(r);a?a.amount+=n.amount:t.set(r,{...n})}return[...t.values()]}function Tl(e,t){if(!e.token||!e.recipient||e.chainId===null)return null;const n=Tp(t,e.chainId);if(!n)return null;const{gasFee:o,bridgeFee:s,spicenetFee:r}=io(n),a=o+s,i=e.grossAmountRaw-a-r;if(i<=0n)throw new Error("Withdrawal amount does not cover the network fee.");const l=[{token:e.token.address,recipient:e.recipient,amount:i}];return a>0n&&l.push({token:e.token.address,recipient:nn,amount:a}),r>0n&&l.push({token:e.token.address,recipient:Fn,amount:r}),Bp(l)}function Dp(e,t,n){const o=Tl(e,t);return!o||Fp(Ep(n),o)?null:e.buildWithdrawBatches(o)}async function Bl(e){if(!(!e.batches.length||!e.walletAddress||!e.recipient)){e.ui.setIsExecuting(!0),e.ui.setExecutionError(null),e.ui.setExecutionProgress(null),e.executionContextRef.current=null,e.ui.setLockedGasFee(e.gasFee);try{let t=e.batches;if(e.isNon7702&&e.onWithdrawExecute)await e.onWithdrawExecute(e.amount);else{if(!e.isNon7702&&!t.some(s=>bo(s.chainId)))throw new Error("Spice withdrawals must include a Spicenet funding batch before the destination chain batch.");const n=e.token?.address||"",o={useCustomTransfers:!0};if(e.buildSpicenetBatch){const s=e.feeEstimate??await e.execution.estimate(t,n,0n,o),r=Tl(e,s);r&&(t=e.buildWithdrawBatches(r));const a=s.intents[0]?.batches.find(i=>i.chainId===e.chainId)??s.intents[0]?.batches[0]??null;a&&e.ui.setLockedGasFee(io(a).totalFee)}else{const s=(e.feeEstimate??await e.execution.estimate(t,n,0n,o)).intents[0]?.batches[0]??null;s&&e.ui.setLockedGasFee(io(s).totalFee)}await e.execution.execute(t,n,0n,s=>{s.actionId&&s.intentId&&typeof s.intentIndex=="number"&&typeof s.totalSteps=="number"&&(e.executionContextRef.current={actionId:s.actionId,intentId:s.intentId,intentIndex:s.intentIndex,totalSteps:s.totalSteps}),e.ui.setExecutionProgress(s)},void 0,e.buildSpicenetBatch?{...o,adjustBatchesForEstimate:({feeEstimate:s,chainBatches:r})=>Dp(e,s,r)}:{...o,skipPreSubmitFeeEstimate:!0})}Dl(e)}catch(t){const n=t instanceof Error?t.message:"Withdraw failed";e.ui.setExecutionError(n)}finally{e.ui.setIsExecuting(!1)}}}function Dl(e){window.dispatchEvent(new CustomEvent("withdraw-completed")),e.onWithdrawSuccess?.({token:e.token?.symbol||"",amount:e.amount,chainId:e.chainId})}async function Op(e){const t=e.executionContextRef.current;if(!t){e.ui.setExecutionProgress(null),await Bl(e);return}e.ui.setIsExecuting(!0),e.ui.setExecutionError(null),e.ui.setExecutionProgress({step:"executing",message:"Resuming existing action...",actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps});try{let n=t.totalSteps;for(let o=0;o<t.totalSteps;o++)if((await Lt.checkStepStatus(t.intentId,o)).data.status!=="success"){n=o;break}if(n>=t.totalSteps)e.ui.setExecutionProgress(o=>({...o||{step:"success",message:"Transaction successful!",actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps},step:"success",message:"Transaction successful!"}));else for(let o=n;o<t.totalSteps;o++){const s=await el({actionId:t.actionId,intentIndex:t.intentIndex,intentId:t.intentId,stepIndex:o,chainId:e.chainId??void 0,onStatusMessage:(r,a)=>{e.isMountedRef.current&&e.ui.setExecutionProgress({step:"executing",message:r,txHash:a,actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps})}});if(!e.isMountedRef.current)return;e.ui.setExecutionProgress({step:o===t.totalSteps-1?"success":"executing",message:o===t.totalSteps-1?"Transaction successful!":"Executing remaining steps...",txHash:s,actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps})}Dl(e)}catch(n){const o=n instanceof Error?n.message:"Withdraw failed";e.ui.setExecutionError(o)}finally{e.ui.setIsExecuting(!1)}}async function Rp(e){const t=await e.estimate(e.batches,e.tokenAddress,0n,{useCustomTransfers:!0,signal:e.signal}),n=t.intents.flatMap(s=>s.batches).filter(s=>io(s).totalFee>0n),o=n.filter(s=>s.chainId===e.chainId)[0]??n[0]??t.intents[0]?.batches[0];if(!o)throw new Error("No gas fee estimate was returned for this withdraw.");return{gasFee:io(o).totalFee,feeEstimate:t}}function na(e,t){return Fe(e,t).replace(/(\.\d*?[1-9])0+$|\.0+$/,"$1")}function Mp(e,t,n){return xn(e,t,n,"floor")}function Ol(e,t,n=!1){if(e<=0)return"$0";if(!t||!Number.isFinite(t)||t<=0)return"\u2014";const o=e*t;return`$${o>=1?o.toFixed(3).replace(/0+$/,"").replace(/\.$/,""):o.toFixed(4).replace(/0+$/,"").replace(/\.$/,"")}${n?" (stale)":""}`}function Wp(e,t){return t?JSON.stringify({tokenAddress:t.toLowerCase(),batches:e.map(n=>({chainId:n.chainId,calls:n.calls.map(o=>({to:o.to.toLowerCase(),value:o.value.toString(),data:o.data})),tokenTransfers:(n.tokenTransfers??[]).map(o=>({from:o.from,to:o.to.toLowerCase(),token:o.token.toLowerCase(),amount:o.amount.toString()}))}))}):null}function Rl(e,t,n){const o=n.filter(s=>s.amount>0n);return{chainId:e,domain:"evm",tokenTransfers:[],calls:be(t)?o.map(s=>({to:s.recipient,value:s.amount,data:"0x"})):o.map(s=>({to:t,value:0n,data:xt({abi:tt,functionName:"transfer",args:[s.recipient,s.amount]})}))}}new Set([nn,Fn].map(e=>e.toLowerCase()));function Np(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const o=zt(n.token),s=zt(n.to),r=`${o.toLowerCase()}:${s.toLowerCase()}`,a=t.get(r);a?a.amount+=n.amount:t.set(r,{token:o,to:s,amount:n.amount})}return[...t.values()]}function Pp(e,t){return`0x${t}${e.slice(4)}`}function Ml(e,t,n,o){if(e.some(d=>d.domain==="spicenet"))return e;const s=n?.intents.flatMap(d=>d.batches),r=d=>d.from==="escrow",a=e.map(d=>{const p=s?.find(S=>S.chainId===d.chainId);if(!p)return d;const f=io(p),h=f.totalFee;if(h<=0n)return d;const m=(d.tokenTransfers??[]).filter(S=>r(S)&&zt(S.to).toLowerCase()===t.toLowerCase()),g=m.find(S=>!be(zt(S.token)))??m[0];if(!g)return d;const y=zt(g.token),w=be(y);let x=!1;const v=(d.tokenTransfers??[]).map(S=>x||!r(S)||zt(S.to).toLowerCase()!==t.toLowerCase()||zt(S.token).toLowerCase()!==y.toLowerCase()?S:(x=!0,{...S,amount:o?.payoutAlreadyGross?BigInt(S.amount):BigInt(S.amount)+h}));if(!x)return d;const k=(S,T)=>w?{to:S,value:T,data:"0x"}:{to:y,value:0n,data:xt({abi:tt,functionName:"transfer",args:[S,T]})},A=[];f.spicenetFee>0n&&A.push(k(Fn,f.spicenetFee));const b=f.gasFee+f.bridgeFee;return b>0n&&A.push(k(nn,b)),{...d,tokenTransfers:v,calls:[...A,...d.calls]}}),i=a.flatMap(d=>(d.tokenTransfers??[]).filter(r).map(p=>{const f=zt(p.token),h=zt(p.to),m=[{token:f,to:h,amount:BigInt(p.amount)}];return{chainId:d.chainId,transfers:Np(m)}}));if(i.length===0)return e;const l=o?.requestTimestampMs??Date.now(),c=BigInt(Math.floor(l/1e3))+3600n;return[{chainId:Pa,domain:"spicenet",tokenTransfers:[],calls:i.map((d,p)=>{const f=vo(zn([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,d.transfers[0].token,d.transfers.reduce((m,g)=>m+g.amount,0n),BigInt(d.chainId),BigInt(l+p)])),h=Pp(f,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:xt({abi:ar,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${d.chainId}`,idempotenceKey:h,nbf:0n,exp:c,metadata:"{}",transfers:d.transfers.map(m=>({token:m.token.toLowerCase(),to:m.to,amount:m.amount}))}]})}})},...a]}function mo(e,t,n,o){const s=e.filter(a=>a.domain!=="spicenet"),r=a=>(a.tokenTransfers??[]).some(i=>i.from==="escrow");return[...s.filter(a=>!r(a)),...Ml(s.filter(r),t,n,o)]}class To extends Error{constructor(t,n){super("The selected balance cannot cover the fee funding amount"),this.requiredAmount=t,this.balance=n,this.name="InsufficientFeeFundingBalanceError"}}function oa(e,t,n,o,s){const r=e[e.length-1];if(!r?.calls.length||r.domain==="spicenet")throw new Error("Proceeds fees require a final destination action");const a=[{to:Fn,amount:s},{to:nn,amount:o}].filter(i=>i.amount>0n);return e.map(i=>i===r?{...i,calls:[...i.calls,...a.map(l=>({to:n,value:0n,data:xt({abi:tt,functionName:"transfer",args:[l.to,l.amount]})}))],tokenTransfers:[...i.tokenTransfers??[],...a.map(l=>({from:t,to:l.to,token:n,amount:l.amount}))]}:i)}async function Wl(e,t,n,o,s){const r=$n(e),a=await Lt.estimateBatchGas({user:t,outputToken:n,signal:o,requireSimulation:!0,includePlatformFee:s!==void 0,chainBatches:e.map((i,l)=>({...i,hash:r[l].hash}))});if(a.gasQuoteSource!=="estimated"||!a.simulationVerified)throw new Error("Action proceeds require a successful live batch simulation; fallback gas pricing is not sufficient");if(s!==void 0&&(a.platformFee===void 0||a.platformFee>s))throw new Error("Fee conversion platform price changed; refresh before retrying");return a.gasFee}async function Nl(e){if(e.proceeds.token.toLowerCase()!==e.token.toLowerCase())throw new Error("Action proceeds must use the destination fee token");const t=await e.proceeds.resolve(e.signal);if(e.signal?.aborted)throw new Error("Action proceeds quote was cancelled");if(t<0n)throw new Error("Action proceeds cannot be negative");const n=await e.baseline();if(!n?.preview)throw new Error("Action fee quote is unavailable");let o=n.preview.gasFee;const s=n.preview.spicenetFee,r=n.preview.bridgeFee??0n;for(let a=0;a<5;a++){const i=o+s+r,l=t<i?t:i,c=i-l;if(c>0n&&e.fundShortfall===!1)throw new To(i,t);const d=c>0n?(c*110n+99n)/100n+2n:0n;let p=d,f;const h=mo(await e.buildBatches(d,{actionAmountOverride:e.actionAmountFor?.(i),onSourceSpend:y=>{p=y},onActionCalls:y=>{f=y}}),e.owner),m=oa(h,e.owner,e.token,o+r,s),g=await Wl(m,e.owner,e.token,e.signal);if(g<=o&&(o-g)*100n<=g*15n)return{preview:{...n.preview,grossAmount:d,netAmount:0n,gasFee:o,totalFee:i,gasQuoteSource:"estimated"},feeEstimate:n.feeEstimate,grossFundingAmount:d,proceedsAvailable:t,proceedsUsed:l,fundingBatches:m,sourceSpendCap:p,destinationAmount:0n,actionDefinition:f};o=g}throw new Error("Action proceeds fee estimate did not converge")}function Pl(e,t){let n,o;if(be(t)){if(e.data!=="0x")return null;n=e.to,o=e.value}else{if(!ge(e.to,t))return null;try{const s=uo({abi:tt,data:e.data});if(s.functionName!=="transfer")return null;[n,o]=s.args}catch{return null}}return ge(n,nn)?{gas:o,platform:0n}:ge(n,Fn)?{gas:0n,platform:o}:null}async function Up(e,t,n){const o=yt(e);return be(n)?o.getBalance({address:t}):o.readContract({address:n,abi:tt,functionName:"balanceOf",args:[t]})}function qs(e,t,n){return e.map(o=>o.chainId===t?{...o,calls:o.calls.filter(s=>!Pl(s,n))}:o)}function Ul(e,t,n){if(!e.feeOnlyAction)return{};const o=e.embeddedWalletAddress??e.providerEmbeddedAddress,s=e.feeQuote?.fundingSource,r=s&&s.kind!=="proceeds"?void 0:e.actionProceeds,a=s&&(s.kind==="input"||s.kind==="balance"&&s.asset?._source==="wallet")?s:void 0;if(r||e.feeQuote?.fundingConversion||a){const d=e.feeQuote?.fundingConversion,p=r??{token:t,resolve:async()=>0n},f=e.feeQuote?.preview,h=e.feeQuote?.proceedsUsed,m=d?.fromProceeds?d.tokenIn:t;if(!f||h===void 0||!a&&p.token.toLowerCase()!==m.toLowerCase())throw new Error("Refresh the action proceeds quote");const g=f.gasFee+(f.bridgeFee??0n),y=f.spicenetFee,w=a?async()=>{e.validateFeeQuote?.();const v=await Up(e.resolvedChainId,o,a.token);e.validateFeeQuote?.();const k=a.kind==="input"?a.amount:(d?.amountInMax??h)+(a.reservedAmount??0n);if(e.signal?.aborted||v<k||d&&d.amountOut<g+y)throw new Error("The fee funding balance changed; refresh before retrying");return d?[{chainId:e.resolvedChainId,token:t,amount:d.amountOut}]:[]}:async()=>{e.validateFeeQuote?.();const v=await p.resolve(e.signal);if(e.validateFeeQuote?.(),e.signal?.aborted||(d?.fromProceeds?v<d.amountInMax||d.amountOut<g+y:v<h||v+(d?.amountOut??n)<g+y))throw new Error("Action proceeds changed; refresh before retrying");return d?.fromProceeds?[{chainId:e.resolvedChainId,token:d.tokenIn,amount:d.amountInMax},{chainId:e.resolvedChainId,token:t,amount:d.amountOut}]:[{chainId:e.resolvedChainId,token:t,amount:h+(d?.amountOut??0n)}]},x=async v=>{await w();const k=await Wl(v,o,t,e.signal,d?y:void 0);if(await w(),(k>f.gasFee?k-f.gasFee:f.gasFee-k)*100n>k*15n)throw new Error("Action gas quote changed; refresh before retrying")};return{resolveActionOutputCredits:w,prepareForSigning:async v=>{const k=qs(v,e.resolvedChainId,t).map(b=>({...b,tokenTransfers:b.tokenTransfers?.filter(S=>!(typeof S.from=="string"&&ge(S.from,o)&&(ge(S.to,nn)||ge(S.to,Fn))))})),A=oa(k,o,t,g,y);return await x(A),A},validateBeforeSubmit:x}}const i=Ft(t,e.resolvedChainId),l={chainId:e.resolvedChainId,tokenAddress:t,symbol:i?.symbol??e.destinationToken.symbol,decimals:e.executionTokenDecimals??i?.decimals??e.destinationToken.decimals},c=async d=>{e.validateFeeQuote?.();const p=qs(d,e.resolvedChainId,t),f=await e.execution.estimate(p,t,n,{userOverride:o,useCustomTransfers:!0,feeExecutionMode:"backend-transfer"});e.validateFeeQuote?.();const h=Xn(f,l);if(!h||h.chainId!==e.resolvedChainId)throw new Error("The fee service did not return the destination action's fee quote");if(h.gasFee+h.spicenetFee+(h.bridgeFee??0n)+2n>n)throw new Error("Fees exceed the displayed maximum funding; refresh the quote before retrying");return{raw:p,feeEstimate:f,fees:h}};return{prepareForSigning:async d=>{const{raw:p,feeEstimate:f}=await c(d);return mo(p,o,f,{payoutAlreadyGross:!0})},validateBeforeSubmit:async d=>{const{fees:p}=await c(d);let f=0n,h=0n;for(const g of d)if(g.chainId===e.resolvedChainId)for(const y of g.calls){const w=Pl(y,t);w&&(f+=w.gas,h+=w.platform)}if(f+h+2n>n)throw new Error("Signed fees exceed the displayed maximum funding");const m=p.gasFee+(p.bridgeFee??0n);if((f>m?f-m:m-f)*100n>m*15n||h!==p.spicenetFee)throw new Error("The signed gas quote changed materially; refresh before retrying")}}}const Lp="0xa9059cbb";function _o(e,t,n){return be(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:xt({abi:tt,functionName:"transfer",args:[n,t]})}}function Ll(e,t,n){return{chainId:n,calls:[_o(e,t,Jn(n))]}}function zp(e,t,n,o){const s=t.source.chainId;return{chainId:s,calls:[...e.calls,_o(t.source.address,n,Jn(s)),...o>0n?[_o(t.source.address,o,nn)]:[]]}}function zl(e,t){const n=e.amountOutMinimum-t;if(n<=0n)throw new Error("Amount is too small to cover fees. Increase the amount and retry.");return n}function Hl(e,t,n){return e?.asset?._source==="wallet"&&e?.asset.chainId===n}function ql(e){return e.isNative||be(e.address)?!0:!Ft(e.address,e.chainId)}function Vl(e,t,n,o){return t!=="user-transfer"||!n||e.length===0||e[0]?.to.toLowerCase()!==o.toLowerCase()||!e[0]?.data.startsWith(Lp)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function es(e,t,n,o){const s=await(t??Hs)({...n,requestTimestampMs:o});return s?[s,e]:[e]}function Hp(e){return e.filter(t=>t.domain!=="spicenet")}function ts(e,t){const n=(e.tokenTransfers??[]).filter(o=>o.from==="escrow").map(o=>({token:Ye(o.token),recipient:o.to,amount:BigInt(o.amount)})).filter(o=>o.amount>0n);return t!==void 0&&n.length===1&&(n[0]={...n[0],amount:t}),n.length>0?n:void 0}function Bo(e,t,n){return xn(e,t,n,"ceil")}function Ql(e){const t=e.selectedAsset?.asset;return e.isPayMode&&!!t&&t._source==="wallet"&&t.chainId!==e.resolvedChainId&&!!e.pivot}function sa(e){const t=e.selectedAsset?.asset;return!e.isPayMode&&!!t&&t._source==="wallet"&&t.chainId!==e.resolvedChainId&&!!e.sourceSwap&&!!e.pivot}function Vs(e,t){if(t?.sourceSpendCap!==void 0&&e>t.sourceSpendCap)throw new Error("The source amount increased. Review the updated quote before submitting.");t?.onSourceSpend?.(e)}async function jl(e,t,n){let o;const s=await e({...t,buildActionCalls:async(r,a)=>{o=r;const i=await t.buildActionCalls(r,a);return n?.onActionCalls?.({amount:r,context:a,calls:i}),i}},n);if(o!==void 0){if(n?.minimumDestinationAmount!==void 0&&o<n.minimumDestinationAmount)throw new Error("The destination amount decreased. Review the refreshed quote before submitting.");n?.onDestinationAmount?.(o)}return s}const Qs=(e,t)=>jl(qp,e,t),js=async(e,t)=>{const n=await jl(Vp,e,t),o=t?.actionContextOverride?.feeBreakdown,s=n[n.length-1];if(e.feeExecutionMode!=="user-transfer"||!o||!s)return n;const r=e.needsSwap&&e.resolvedTokenIn?e.resolvedTokenIn:e.destinationToken.address,[a]=qs([s],e.resolvedChainId,r),i=Rl(e.resolvedChainId,r,[{recipient:Fn,amount:o.spicenetFee},{recipient:nn,amount:o.gasFee+(o.bridgeFee??0n)}]).calls,l=s.calls.filter(c=>!a.calls.includes(c));return l.length===i.length&&i.every(c=>l.some(d=>d.to.toLowerCase()===c.to.toLowerCase()&&d.value===c.value&&d.data===c.data))?n:[...n.slice(0,-1),{...a,calls:[...i,...a.calls]}]};async function qp(e,t){const{currentPaymentAmount:n,destinationToken:o,embeddedWalletAddress:s,providerEmbeddedAddress:r,address:a,isNon7702:i,resolvedChainId:l,buildActionCalls:c,feeExecutionMode:d,buildSpicenetBatch:p,needsSwap:f,exactOutputSwap:h,resolvedTokenIn:m,requestTimestampMs:g}=e,y=t?.sourceAssetOverride?{asset:t.sourceAssetOverride}:e.selectedAsset,w=t?.fundingTokenOverride??m,x=dn(n,o.decimals),v=t?.actionAmountOverride??(e.feeOnlyAction?0n:x),k=!!e.feeOnlyAction&&(t?.fundingAmountOverride??0n)>0n,A=s||r||a;if(!A)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const b={userAddress:e.recipient??A,executorAddress:A,beneficiary:e.recipient??A,outputRecipient:f?A:void 0,chainId:l,destinationToken:o.address,grossAmount:t?.fundingAmountOverride??x,netAmount:v,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:d,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},S=await c(v,b),T={chainId:l,calls:S},E=!!y&&y.asset._source!=="wallet",I=Hl(y??null,i,l),M=E||I&&!!y&&!ql(y.asset),W=(F,N)=>({token:Ye(F),from:"escrow",to:A,amount:N}),R=(F,N,D)=>I?[Ll(F,N,l),...D]:D;if(x===0n&&!k)return[T];if(y?.asset._source==="wallet"&&y.asset.chainId!==l&&!e.pivot)throw new Error("A current source-to-destination funding route is required");if(e.feeOnlyAction&&t?.fundingTokenOverride&&I)return Vs(t.fundingAmountOverride??0n,t),[T];if(Ql(e)){if(f&&!h)throw new Error("Swap quote not available yet");const F=t?.fundingAmountOverride??(h?h.amountInMax:x),N=t?.sourceGasSkimOverride??0n,D=xn(F,e.pivot.destination.decimals,e.pivot.source.decimals,"ceil"),L=D+N,z=e.sourceExactOutputSwap,fe=z&&(t?.reuseQuotedSourceSwap||z.amountOut>=L)?z:e.resolveSourceExactOutputSwap?await e.resolveSourceExactOutputSwap(L):null;if(!fe)throw new Error("Swap quote not available yet");Vs(fe.amountInMax,t);const ce=y.asset;if(fe.amountInMax>ce.balance)throw new Error(`Insufficient ${ce.symbol} for this payment. Required ${Fe(fe.amountInMax,ce.decimals)} ${ce.symbol}; available ${Fe(ce.balance,ce.decimals)} ${ce.symbol}.`);const Q=fe.amountOut>=L?D:fe.amountOut-N;if(Q<=0n)throw new Error("Amount is too small to cover fees. Increase the amount and retry.");const ne={chainId:e.pivot.source.chainId,calls:[...fe.calls,_o(e.pivot.source.address,Q,Jn(e.pivot.source.chainId)),...N>0n?[_o(e.pivot.source.address,N,nn)]:[]]},re={chainId:l,calls:[...h?.calls??[],...S],tokenTransfers:[W(e.pivot.destination.address,F),...T.tokenTransfers??[]]},j=await es(re,p,{userAddress:A,destinationChainId:l,deliveryToken:e.pivot.destination.address,deliveryAmount:F,deliveryRecipient:A,deliveryTransfers:ts(re),sourceAsset:y.asset},g);return[ne,...j]}if(y){const F=t?.fundingAmountOverride??h?.amountInMax??x;Vs(Bo(F,await eo(y.asset,w??y.asset.address,l,o),y.asset.decimals),t)}if(f&&h){const F=w??Sn(y.asset,l)??y.asset.address,N=t?.fundingAmountOverride??h.amountInMax,D=M?[W(F,N)]:[],L={chainId:l,calls:[...h.calls,...S],tokenTransfers:[...D,...T.tokenTransfers??[]]};if(!M)return[L];const z=await es(L,p,{userAddress:A,destinationChainId:l,deliveryToken:F,deliveryAmount:N,deliveryRecipient:A,deliveryTransfers:ts(L),sourceAsset:y.asset},g);return R(F,N,z)}if(M){const F=w??Sn(y.asset,l)??o.address;if(I&&!e.feeOnlyAction&&F.toLowerCase()===o.address.toLowerCase())return[T];const N=t?.fundingAmountOverride??x,D={...T,tokenTransfers:[W(F,N),...T.tokenTransfers??[]]},L=await es(D,p,{userAddress:A,destinationChainId:l,deliveryToken:F,deliveryAmount:N,deliveryRecipient:A,deliveryTransfers:ts(D),sourceAsset:y.asset},g);return R(F,N,L)}return[T]}async function Vp(e,t){const{selectedAsset:n,embeddedWalletAddress:o,recipient:s,resolvedChainId:r,destinationToken:a,buildActionCalls:i,feeExecutionMode:l,buildSpicenetBatch:c,isPayMode:d,isNon7702:p,needsSwap:f,resolvedSwap:h,quoteAmountOut:m,resolvedTokenIn:g,requestTimestampMs:y}=e;if(!n?.asset||!o)return[];const w=s??o;if(!w)return[];const x=sa(e);let v=e.sourceSwap,k=dn(n.amount,n.asset.decimals),A=x?e.sourceSwap.amountOutMinimum:null;if(x&&e.isFeeInclusiveInput&&(A=zl(e.sourceSwap,t?.sourceGasSkimOverride??0n)),x&&!e.isFeeInclusiveInput&&(t?.fundingAmountOverride!==void 0||(t?.sourceGasSkimOverride??0n)>0n)){A=t?.fundingAmountOverride!==void 0?Bo(t.fundingAmountOverride,e.pivot.destination.decimals,e.pivot.source.decimals):e.sourceSwap.amountOutMinimum;const Y=A+(t?.sourceGasSkimOverride??0n);if(!e.resolveSourceExactOutputSwap)throw new Error("The source quote cannot include fees yet.");const me=await e.resolveSourceExactOutputSwap(Y);if(me.amountOut<Y)throw new Error("The source quote does not cover the accepted funding amount.");k=me.amountInMax,v={...me,amountOutMinimum:me.amountOut}}const b=x?e.pivot.destination.address:g??Sn(n.asset,r)??a.address,S=x?e.pivot.destination.decimals:await eo(n.asset,b,r,a),T=t?.fundingAmountOverride??t?.actionAmountOverride??(x?xn(A,e.pivot.source.decimals,S,"floor"):zs(dn(n.amount,n.asset.decimals),n.asset.decimals,S)),E=t?.fundingAmountOverride??T,I=t?.sourceFundingAmountOverride??Bo(T,S,n.asset.decimals);Vs(x?k:I,t);const M=t?.deliveryAmountOverride??(l==="user-transfer"?E:t?.actionContextOverride?.netAmount??E),W=t?.withdrawalAmountOverride??M,R=t?.actionAmountOverride??t?.actionContextOverride?.netAmount??T;let F=h;if(f&&!d&&(t?.actionContextOverride?.netAmount!==void 0||x&&(t?.sourceGasSkimOverride??0n)>0n&&!t?.reuseQuotedSourceSwap)){if(!e.resolveInputSwap)throw new Error("Swap quote cannot be refreshed for the amount after fees.");const Y=t?.actionContextOverride?.netAmount??R;(!F||e.swapInputAmount!==Y)&&(F=await e.resolveInputSwap(Y,h??void 0))}F&&t?.onSwap?.(F,t?.actionContextOverride?.netAmount??e.swapInputAmount??R);const N=F?.amountOutMinimum??m,D={userAddress:w,executorAddress:o,beneficiary:w,outputRecipient:f?o:void 0,chainId:r,destinationToken:a.address,feeToken:l==="user-transfer"&&f&&g?g:a.address,grossAmount:E,netAmount:R,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:l,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},L=()=>i(R,D),z=n.asset?._source==="wallet";if(!d&&z&&n.asset.chainId===r&&ql(n.asset)){if(f){if(!g)throw new Error("Swap input token could not be resolved");if(!F||N===null)throw new Error("Swap quote not available yet")}if(f&&F&&N){const Y=await i(t?.actionAmountOverride??N,{...D,netAmount:t?.actionAmountOverride??N}),{feeCall:me,remainingCalls:B}=Vl(Y,l,f,D.feeToken);return[{chainId:r,calls:[...me?[me]:[],...F.calls,...B]}]}return[{chainId:r,calls:await L()}]}if(!d&&z&&n.asset.chainId!==r&&!x)throw new Error("A current source-to-destination funding route is required");const fe=n.asset._source!=="wallet",ce=Hl(n,p,r);if(!(fe||ce||x))return[{chainId:r,calls:await L()}];const Q=x?zp(v,e.pivot,A,t?.sourceGasSkimOverride??0n):ce?Ll(g??Ye(n.asset.address),I,r):null,ne=(Y,me)=>({token:Ye(Y),from:"escrow",to:o,amount:me});if(f){if(!g)throw new Error("Swap input token could not be resolved");if(!F||N===null)throw new Error("Swap quote not available yet")}if(f&&F&&N&&g){const Y=await i(t?.actionAmountOverride??N,{...D,netAmount:t?.actionAmountOverride??N}),{feeCall:me,remainingCalls:B}=Vl(Y,l,f,D.feeToken),U={chainId:r,calls:[...me?[me]:[],...F.calls,...B],tokenTransfers:[ne(g,M)]},X=await es(U,c,{userAddress:o,destinationChainId:r,deliveryToken:g,deliveryAmount:M,withdrawalAmount:W,deliveryRecipient:o,deliveryTransfers:ts(U,W),sourceAsset:n.asset},y);return Q?[Q,...X]:X}const re=g??Sn(n.asset,r)??a.address,j={chainId:r,calls:await L(),tokenTransfers:[ne(re,M)]},J=await es(j,c,{userAddress:o,destinationChainId:r,deliveryToken:re,deliveryAmount:M,withdrawalAmount:W,deliveryRecipient:o,deliveryTransfers:ts(j,W),sourceAsset:n.asset},y);return Q?[Q,...J]:J}async function Qp(e,t,n,o,s){let r=e;for(let a=0;a<4;a++){const i=await t(r),l=await o(i,n,r,s),c=zc(l);if(c===null||c>=e)return r;const d=r-c,p=e+d;if(p<=r)return r;r=p}return r}function jp(e){return{...e,resolve:async(t,n,o)=>{const s=await e.resolve(t,n,o),r=s?.calls[0]?.to;return!s||!r||be(t.tokenIn)?s:{...s,calls:[{to:t.tokenIn,value:0n,data:xt({abi:tt,functionName:"approve",args:[r,s.amountInMax]})},...s.calls]}}}}function Gs(e){const t=(e?.customVenues??[]).map(o=>md(jp(o)));async function n(o,s,r){const a=t.filter(c=>c.chainIds.includes(s));if(a.length===0)throw new Ne("NO_SWAP_ROUTE",`No exact-output venue supports chain ${s}`,{chainId:s,tokenIn:o.tokenIn,tokenOut:o.tokenOut});const i=(await Promise.allSettled(a.map(async c=>({venue:c,quote:await c.resolve(o,s,r)})))).filter(c=>c.status==="fulfilled").map(c=>c.value).filter(c=>c.quote!==null);if(i.length===0)throw new Ne("NO_SWAP_ROUTE",`All aggregators failed for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${s}`,{chainId:s,tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountOut:o.amountOut.toString()});const l=i.find(c=>c.venue.preferred);return l?l.quote:(i.sort((c,d)=>c.quote.amountIn<d.quote.amountIn?-1:c.quote.amountIn>d.quote.amountIn?1:0),i[0].quote)}return{getQuote:n,venues:t}}function Gl(e,t,n){if(e._source==="wallet")return e.chainId===t?e.address:null;const o=ko(e,t);return o.find(s=>s.toLowerCase()===n.toLowerCase())??o[0]??null}async function Yl(e,t,n,o){const s=$n(o),r=await Lt.estimateBatchGas({user:t,outputToken:n,requireSimulation:!0,includePlatformFee:!0,signal:e.signal,chainBatches:o.map((a,i)=>({...a,hash:s[i].hash}))});if(!r.simulationVerified||r.gasQuoteSource!=="estimated"||r.platformFee===void 0||r.gasFee<=0n)throw new Error("Fee funding requires verified gas and platform pricing");return r}async function ns(e,t){const n=e.selectedAsset?.asset,o=!t&&!!e.actionProceeds&&e.actionProceeds.token.toLowerCase()!==e.destinationToken.address.toLowerCase(),s=!!t||o,r=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!r||!s&&(!n||n._source!=="spice"&&!(n._source==="wallet"&&n.chainId===e.resolvedChainId)))throw new Error("A local embedded or Spice balance is required for fee conversion");const a=t?t.token:o?e.actionProceeds.token:Gl(n,e.resolvedChainId,e.destinationToken.address);if(!a)throw new Error("This receipt has no registered destination withdrawal token");const i=Ft(a,e.resolvedChainId)?.decimals??(be(a)?18:s?await yt(e.resolvedChainId).readContract({address:a,abi:tt,functionName:"decimals"}):n?._source==="wallet"?n.decimals:void 0);if(i===void 0)throw new Error("Fee funding token metadata is unavailable");const l=e.destinationToken.address;if(e.actionProceeds&&!o&&e.actionProceeds.token.toLowerCase()!==l.toLowerCase())throw new Error("Action proceeds must use the destination fee token");const c=t?t.amount:e.actionProceeds?await e.actionProceeds.resolve(e.signal):0n;if(c<0n||e.signal?.aborted)throw new Error("Action proceeds quote was cancelled or invalid");const d=Gs({customVenues:[...e.resolveExactOutputSwap?[{name:"consumer-exact-output",chainIds:[e.resolvedChainId],preferred:!0,resolve:e.resolveExactOutputSwap}]:[],...Co(e.liquidityVenues).output]}),p=h=>Yl(e,r,l,h);let f=await p(await e.buildPayChainBatches({fundingAmountOverride:0n}));for(let h=0;h<8;h++){const m=f.gasFee+f.platformFee,g=s?0n:c<m?c:m,y=m-g,w=y>0n?(y*110n+99n)/100n+2n:0n,x=w>0n?await d.getQuote({tokenIn:a,tokenOut:l,amountOut:w,maxSlippage:e.maxSlippage},e.resolvedChainId,r):null;if(e.signal?.aborted)throw new Error("Fee conversion quote was cancelled");if(x&&(x.amountOut!==w||x.amountInMax<=0n||x.amountInMax<x.amountIn||!x.calls.length))throw new Error("Invalid exact-output fee conversion quote");const v=x?.amountInMax??0n,k=s?0n:Bo(v,i,n.decimals);if(s&&v>c)throw new To(v,c);if(!s&&k>n.balance)throw new To(k,n.balance);let A,b=mo(await e.buildPayChainBatches({fundingAmountOverride:s?0n:v,...s?{}:{fundingTokenOverride:a},...t?{actionAmountOverride:t.amount-v}:{},onActionCalls:T=>{A=T}}),r);if(x){const T=b.length-1;b=b.map((E,I)=>I===T?{...E,calls:[...E.calls,...x.calls]}:E)}b=oa(b,r,l,f.gasFee,f.platformFee);const S=await p(b);if(S.gasFee<=f.gasFee&&(f.gasFee-S.gasFee)*100n<=S.gasFee*15n&&S.platformFee===f.platformFee){const T={tokenIn:a,tokenOut:l,amountInMax:v,amountOut:w,sourceAmountMax:k,...o?{fromProceeds:!0}:{},...t?{fromInput:!0}:{}};return{feeEstimate:null,preview:{symbol:e.destinationToken.symbol,decimals:e.destinationToken.decimals,grossAmount:s?0n:w,netAmount:0n,gasFee:f.gasFee,spicenetFee:f.platformFee,totalFee:m,gasQuoteSource:"estimated"},grossFundingAmount:s?0n:v,proceedsAvailable:c,proceedsUsed:s?m:g,fundingConversion:T,fundingBatches:b,sourceSpendCap:k,destinationAmount:0n,actionDefinition:A}}f=S}throw new Error("Fee conversion pricing did not converge")}const ra=["input","proceeds","balance"];function Gp(e){if(e.reserve&&e.reserve.amount<0n)throw new Error("Fee funding reserve cannot be negative");const t=i=>ge(i,e.feeToken),n=(i,l)=>Number(i.swap)-Number(l.swap),o={input:[],proceeds:[],balance:[]};for(const i of e.inputs??[])i.amount>0n&&o.input.push({kind:"input",...i,swap:!t(i.token)});o.input.sort(n),e.proceeds&&e.proceeds.amount>0n&&o.proceeds.push({kind:"proceeds",...e.proceeds,swap:!t(e.proceeds.token)});const s=e.balances.filter(i=>i._source==="wallet"&&i.chainId===e.chainId&&i.location!=="external"),r=e.balances.filter(i=>i._source==="spice"),a=i=>{const l=[];for(const c of i){const d=e.reserve&&nt(c)===nt(e.reserve.asset)?e.reserve.amount:0n,p=c.balance-d;if(p<=0n)continue;const f=d>0n?{...c,balance:p,balanceFormatted:Number(Fe(p,c.decimals)),balanceUsd:c.balanceUsd*Number(p)/Number(c.balance)}:c,h=Gl(f,e.chainId,e.feeToken);h&&(e.inputs?.some(m=>ge(m.token,h)&&!(e.reserve&&ge(e.reserve.asset.address,m.token)))||l.push({kind:"balance",token:h,amount:f.balance,asset:f,...d>0n?{reservedAmount:d}:{},swap:!t(h)}))}return l.sort((c,d)=>n(c,d)||d.asset.balanceUsd-c.asset.balanceUsd)};return o.balance=[...a(s),...a(r)],(e.order??ra).flatMap(i=>o[i])}function Yp(e){return e instanceof To||e instanceof Ne&&e.code==="NO_SWAP_ROUTE"}async function Kl(e,t){const n=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!n||!e.ready||!e.authenticated)return null;const o=e.destinationToken.address;let s;const r=()=>s??(s=(async()=>{const c=await Yl(e,n,o,await e.buildPayChainBatches({fundingAmountOverride:0n}));return{feeEstimate:null,preview:{symbol:e.destinationToken.symbol,decimals:e.destinationToken.decimals,gasFee:c.gasFee,spicenetFee:c.platformFee,bridgeFee:0n,totalFee:c.gasFee+c.platformFee,grossAmount:0n,netAmount:0n,gasQuoteSource:"estimated"}}})()),a=(c,d)=>e.buildPayChainBatches({...d,fundingAmountOverride:c}),i=(c,d)=>Nl({proceeds:{token:o,resolve:async()=>c},owner:n,token:o,signal:e.signal,baseline:r,buildBatches:a,fundShortfall:!1,actionAmountFor:d}),l=async c=>{if(c.kind==="input")return c.swap?ns({...e,actionProceeds:void 0},c):i(c.amount,h=>c.amount-h);if(c.kind==="proceeds"){const h={...e.actionProceeds,resolve:async()=>c.amount};return c.swap?ns({...e,actionProceeds:h}):i(c.amount)}const d=c.asset;if(d._source==="wallet"&&!c.swap)return i(d.balance);const p={...e,selectedAsset:{asset:d,amount:"0"},resolvedTokenIn:c.token,actionInput:void 0,actionProceeds:void 0,buildPayChainBatches:h=>e.buildPayChainBatches({...h,sourceAssetOverride:d,fundingTokenOverride:h?.fundingTokenOverride??c.token})};if(c.swap)return ns(p);const f=await t(p);if(f&&(f.sourceSpendCap??0n)>d.balance)throw new To(f.sourceSpendCap,d.balance);return f};for(const c of e.feeFunding??ra){const d=c==="proceeds"&&e.actionProceeds?{token:e.actionProceeds.token,amount:await e.actionProceeds.resolve(e.signal)}:void 0;if(e.signal?.aborted)throw new Error("Fee funding quote was cancelled");if(d&&d.amount<0n)throw new Error("Action proceeds cannot be negative");const p=Gp({feeToken:o,chainId:e.resolvedChainId,inputs:e.actionInput,proceeds:d,balances:e.feeFundingBalances??[],order:[c],reserve:e.feeFundingReserve});for(const f of p)try{const h=await l(f);if(!h)continue;const{swap:m,...g}=f;return{...h,fundingSource:g}}catch(h){if(e.signal?.aborted||!Yp(h))throw h}}throw new Error(`No available balance can cover this action's ${e.destinationToken.symbol} execution cost`)}async function Kp(e,t,n,o=!1){const s=e.selectedAsset,r=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!s||!r||!e.ready||!e.authenticated||e.isQuoting)return null;if(s.asset._source!=="wallet"||s.asset.chainId!==e.resolvedChainId||!Ss(s.asset)&&s.asset.owner&&!ge(s.asset.owner,r))throw new Error("Funded fee hierarchy requires principal on the action chain in the executing wallet.");if(o&&(e.isPayMode||!e.isFeeInclusiveInput||t.recipient&&!ge(t.recipient,r)))throw new Error("Output-funded actions require an input-inclusive amount left in the executing wallet.");if(e.isPayMode&&e.needsSwap&&!e.exactOutputSwap)return null;const a=e.isPayMode?dn(e.currentPaymentAmount,e.destinationToken.decimals):void 0;if(e.isPayMode&&e.needsSwap&&e.exactOutputSwap.amountOut!==a)throw new Error("Wait for the payment quote for the current amount.");const i=gs(e.resolvedChainId).find(y=>y.equivalenceGroup==="USDC");if(!i)throw new Error("Configure the execution fee token for this chain.");const l={...i,address:i.address,chainId:e.resolvedChainId},c=a!==void 0?e.needsSwap?e.exactOutputSwap.amountInMax:a:dn(s.amount,s.asset.decimals);if(c<=0n||c>s.asset.balance)throw new Error("Enter an amount within the available balance.");if(!e.isPayMode&&e.needsSwap&&t.swapInputAmount!=null&&t.swapInputAmount!==c)throw new Error("Wait for the action quote for the current amount.");const d=a??(e.needsSwap?t.resolvedSwap?.amountOutMinimum??0n:c);let p=t.resolvedSwap??void 0,f=c,h=d;const m={...e,feeOnlyAction:!0,selectedAsset:null,isPayMode:!0,isFeeInclusiveInput:!1,parsedAmount:0,currentPaymentAmount:"0",destinationToken:l,resolvedTokenIn:l.address,executionTokenAddress:l.address,needsSwap:!1,resolvedSwap:null,isDirect:!0,actionInput:!e.isPayMode&&e.isFeeInclusiveInput?[{token:s.asset.address,amount:c}]:void 0,actionProceeds:o?{token:e.destinationToken.address,resolve:async()=>d>0n?d-1n:0n}:e.actionProceeds,feeFundingBalances:e.feeFundingBalances?.filter(y=>!y.balanceError&&!(e.feeFundingReserve&&nt(e.feeFundingReserve.asset)!==nt(s.asset)&&nt(y)===nt(e.feeFundingReserve.asset))&&!Ss(y)&&(!y.owner||ge(y.owner,r))),feeFundingReserve:{asset:s.asset,amount:e.feeFundingReserve&&nt(e.feeFundingReserve.asset)===nt(s.asset)&&e.feeFundingReserve.amount>c?e.feeFundingReserve.amount:c},buildPayChainBatches:async y=>{const w=y?.actionAmountOverride??c;if(w<=0n)throw new To(c+1n,c);const x=!e.isPayMode&&e.needsSwap?w===c?t.resolvedSwap:await t.resolveInputSwap?.(w,t.resolvedSwap??void 0):null,v=e.needsSwap?e.isPayMode?e.exactOutputSwap:x:null;if(e.needsSwap&&!v)throw new Error("The action quote is unavailable.");p=x??void 0,f=w,h=a??p?.amountOutMinimum??w;const k={userAddress:t.recipient??r,executorAddress:r,beneficiary:t.recipient??r,outputRecipient:r,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address,grossAmount:d,netAmount:h,feeToken:l.address,feeExecutionMode:"backend-transfer"},A=await t.buildActionCalls(h,k),b={amount:h,context:k,calls:A},S=[...v?.calls??[],...A];return Qs({...t,selectedAsset:null,feeOnlyAction:!0,isPayMode:!0,isFeeInclusiveInput:!1,currentPaymentAmount:"0",destinationToken:l,resolvedTokenIn:l.address,needsSwap:!1,resolvedSwap:null,exactOutputSwap:null,quoteAmountOut:null,feeExecutionMode:"backend-transfer",buildActionCalls:()=>S},{...y,onActionCalls:()=>y?.onActionCalls?.(b)})}},g=await Kl(m,n);if(!g)return null;if(o&&g.fundingSource?.kind==="proceeds"&&(h-=g.fundingConversion?.amountInMax??g.proceedsUsed??0n),h<=0n)throw new Error("Not enough action output remains after execution costs.");return{...g,fundedFeeToken:l,batches:g.fundingBatches??g.batches,destinationSwap:p,swapInputAmount:f,destinationAmount:h,sourceSpendCap:c+(g.fundingSource?.kind==="balance"&&g.fundingSource.asset&&nt(g.fundingSource.asset)===nt(s.asset)?g.fundingConversion?.amountInMax??g.proceedsUsed??0n:0n)}}async function Zp(e){const t=e.selectedAsset.asset;if(t.chainId!==e.destinationToken.chainId||!ge(Ye(t.address),Ye(e.destinationToken.address)))throw new Error("Direct execution requires the destination token on its own chain.");if(t.decimals!==e.destinationToken.decimals)throw new Error("Source and destination token decimals do not match.");const n=dn(e.paymentAmount??e.selectedAsset.amount,t.decimals);if(n<=0n)throw new Error("Enter a positive action amount.");const o={userAddress:e.beneficiary??e.account,executorAddress:e.account,beneficiary:e.beneficiary??e.account,chainId:e.destinationToken.chainId,destinationToken:e.destinationToken.address,feeToken:t.address,grossAmount:n,netAmount:n,combinedFeeAmount:0n,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:0n,gasFee:0n,bridgeFee:0n}},s=await e.buildActionCalls(n,o);if(!s.length)throw new Error("No action calls configured.");if(be(t.address)&&s.reduce((r,a)=>r+a.value,0n)>n)throw new Error("The native action exceeds the accepted source amount.");return{actionDefinition:{amount:n,context:o,calls:s},actionContext:o,batches:[{chainId:o.chainId,calls:s}],fundingAmount:n,sourceSpendCap:n,destinationAmount:n,feeEstimate:null,preview:{symbol:t.symbol,decimals:t.decimals,grossAmount:n,netAmount:n,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}}}async function Zl(e){const[t]=await e.buildSupplyChainBatches({sourceGasSkimOverride:1n,reuseQuotedSourceSwap:!0});if(!t)throw new Error("Swap quote not available yet");const{gasFee:n}=await Lt.estimateBatchGas({user:e.user,outputToken:e.pivot.source.address,stepIndex:0,chainBatches:[t],signal:e.signal});return n}const Xl=(e,t)=>(e+t-1n)/t;function aa(e,t){return e.intents.length===0?t:{...e,intents:e.intents.map(n=>({...n,batches:n.batches.map(o=>{const s=t.intents.find(i=>i.intentIndex===n.intentIndex)?.batches.find(i=>i.chainId===o.chainId);if(!s)return o;const r={...o.feeBreakdown};let a=0n;for(const i of["gasFee","bridgeFee"]){const l=BigInt(r[i]??"0"),c=BigInt(s.feeBreakdown[i]??"0");c>l&&(r[i]=c.toString(),a+=c-l)}return{...o,feeBreakdown:r,totalDebit:(BigInt(o.totalDebit)+a).toString()}})}))}}function Xp(e,t){const n=e.spicenetFee+(e.bridgeFee??0n);return e.grossAmount<=n?t+e.gasFee+n:Xl((t+e.gasFee)*e.grossAmount,e.grossAmount-n)+2n}async function Jl(e){const{requiredNetFunding:t}=e;if(e.feeOnlyAction){const c=e.executionOptions?.userOverride;if(!c||t!==0n)throw new Error("Fee-only estimates require a zero action amount and its embedded executor");let d=1n,p;for(let f=0;f<8;f++){const h=mo(await e.buildBatches(d),c,p,{payoutAlreadyGross:!0}),m=await e.estimate(qs(h,e.tokenDescriptor.chainId,e.fundingToken),e.fundingToken,d,{...e.executionOptions,feeExecutionMode:"backend-transfer"}),g=Xn(m,e.tokenDescriptor);if(!g)throw new Error("The fee service did not return a fee quote for this action");const y=g.gasFee+g.spicenetFee+(g.bridgeFee??0n);if(p&&y+2n<=d)return{preview:{...g,grossAmount:d,netAmount:0n},feeEstimate:m,grossFundingAmount:d};d=(y*110n+99n)/100n+2n,p=m}throw new Error("Fee-only funding did not converge; refresh the fee quote before retrying")}const n=await e.buildBatches(t),o=await e.estimate(n,e.fundingToken,t,e.executionOptions),s=Xn(o,e.tokenDescriptor);if(!s)return{preview:ms(n,e.tokenDescriptor,t),feeEstimate:o,grossFundingAmount:t};const r=Xp(s,t),a=c=>s.grossAmount>0n?Xl(c*r,s.grossAmount):c,i=a(s.spicenetFee),l=a(s.bridgeFee??0n);return{preview:{...s,grossAmount:r,netAmount:t,spicenetFee:i,bridgeFee:l,totalFee:s.gasFee+i+l},feeEstimate:o,grossFundingAmount:r}}async function $l(e){if(e.balance<=0n)throw new Error("No spendable balance remains after source gas.");let t=e.balance;for(let n=0;n<8;n++){const o=await e.planForAmount(t);if(!o||o.sourceSpendCap===void 0||o.sourceSpendCap<=0n)throw new Error("Max requires a current route and fee estimate.");if(o.sourceSpendCap<=e.balance)return No(t,e.decimals);const s=t*e.balance/o.sourceSpendCap;if(s<=0n||s>=t)throw new Error("The balance cannot cover this action and its fees.");t=s}throw new Error("Max fees did not converge. Refresh the quote before retrying.")}async function Jp(e){if(e.isPayMode||e.needsSwap||e.isQuoting||e.pivot||!e.embeddedWalletAddress)return null;const t=e.asset,n=Ft(e.executionTokenAddress,t.chainId);return!n||t.balance<=0n?null:$l({balance:t.balance,decimals:t.decimals,planForAmount:o=>ho({selectedAsset:{asset:t,amount:No(o,t.decimals)},isPayMode:!1,isNon7702:!1,isFeeInclusiveInput:!1,parsedAmount:Number(No(o,t.decimals)),currentPaymentAmount:"0",destinationToken:{...n,address:e.executionTokenAddress,chainId:t.chainId},resolvedChainId:t.chainId,resolvedTokenIn:e.executionTokenAddress,executionTokenAddress:e.executionTokenAddress,embeddedWalletAddress:e.embeddedWalletAddress,providerEmbeddedAddress:e.embeddedWalletAddress,address:e.embeddedWalletAddress,isConnected:!0,ready:!0,authenticated:!0,isDirect:!0,isSourceDestToken:!0,needsSwap:!1,isQuoting:!1,resolvedSwap:null,exactOutputSwap:null,buildPayChainBatches:async()=>[],buildSupplyChainBatches:s=>e.buildSupplyChainBatches({...s,actionAmountOverride:o}),estimate:e.estimate,feeExecutionMode:e.feeExecutionMode})})}async function ho(e){const{signal:t,selectedAsset:n,isPayMode:o,isFeeInclusiveInput:s=!1,parsedAmount:r,needsSwap:a,exactOutputSwap:i,isNon7702:l,currentPaymentAmount:c,destinationToken:d,feeExecutionMode:p,resolvedTokenIn:f,embeddedWalletAddress:h,providerEmbeddedAddress:m,resolvedChainId:g,isConnected:y,address:w,ready:x,authenticated:v,isDirect:k,resolvedSwap:A,sourceSwap:b,pivot:S,isQuoting:T,executionTokenAddress:E,buildPayChainBatches:I,buildSupplyChainBatches:M,estimate:W}=e;if(e.feeOnlyAction&&!n&&e.feeFunding?.length!==0)return Kl(e,ho);if(e.feeOnlyAction&&e.actionProceeds&&e.actionProceeds.token.toLowerCase()!==d.address.toLowerCase()||e.feeOnlyAction&&n&&(n.asset._source==="spice"||n.asset._source==="wallet"&&n.asset.chainId===g)&&(f?f.toLowerCase()!==d.address.toLowerCase():n.asset.receiptTokenId||n.asset.chainTokens))return ns(e);if(e.actionProceeds&&e.feeOnlyAction){const re=h||m;if(!re||!x||!v)return null;if(f&&f.toLowerCase()!==d.address.toLowerCase())throw new Error("Action proceeds require a matching fee-token source");return Nl({proceeds:e.actionProceeds,owner:re,token:d.address,signal:t,buildBatches:(j,J)=>I({...J,fundingAmountOverride:j}),baseline:()=>ho({...e,actionProceeds:void 0,selectedAsset:n??{amount:"0",asset:{...d,name:d.symbol,balance:0n,balanceFormatted:0,balanceUsd:0,isNative:!1,_source:"spice"}}})})}if(!n?.asset)return null;if(o){if(!h&&!m||r<=0&&!e.feeOnlyAction||a&&!i&&!e.feeOnlyAction)return null;const re=dn(c,d.decimals),j=f||Sn(n.asset,g)||n.asset.address||d.address,J={chainId:g,tokenAddress:j,symbol:Ft(j,g)?.symbol??n.asset.symbol,decimals:await eo(n.asset,j,g,d)};if(!y||!w||!x||!v)return null;const Y=h||m||w,me=a?i?.amountInMax??0n:re;if(me===0n&&!e.feeOnlyAction)return null;const B=S?await Zl({user:Y,pivot:S,buildSupplyChainBatches:P=>I({...P,sourceGasSkimOverride:1n}),signal:t}):0n,U=Date.now();let X=await Jl({requiredNetFunding:me,feeOnlyAction:e.feeOnlyAction,buildBatches:P=>I({fundingAmountOverride:P,sourceGasSkimOverride:B}).then(V=>Ml(Hp(V),Y,void 0,{requestTimestampMs:U})),fundingToken:j,estimate:W,executionOptions:{userOverride:Y,useCustomTransfers:!0,feeExecutionMode:p,signal:t},tokenDescriptor:J});if(!X.preview)return null;let pe=0n,de,xe=[],K=!1;for(let P=0;P<8;P++){if(t?.aborted)throw new Error("Fee estimation cancelled");if(xe=mo(await I({fundingAmountOverride:X.grossFundingAmount,sourceGasSkimOverride:B,onSourceSpend:ot=>{pe=ot},onActionCalls:ot=>{de=ot}}),Y,X.feeEstimate,{payoutAlreadyGross:!0,requestTimestampMs:U}),e.feeOnlyAction){K=!0;break}const V=await W(xe,j,X.grossFundingAmount,{userOverride:Y,useCustomTransfers:!0,feeExecutionMode:p,signal:t}),ie=p==="user-transfer"?aa(V,X.feeEstimate):V,ke=Xn(ie,J)??ms(xe,J,me);if(!ke)return null;const Ee=me+ke.gasFee+ke.spicenetFee+(ke.bridgeFee??0n),Be=Xn(X.feeEstimate,J),Ie=(Be?.gasFee??0n)===ke.gasFee&&(Be?.spicenetFee??0n)===ke.spicenetFee&&(Be?.bridgeFee??0n)===(ke.bridgeFee??0n),Z=X.grossFundingAmount===Ee&&Ie;if(X={feeEstimate:ie,grossFundingAmount:Ee,preview:{...ke,grossAmount:Ee,netAmount:me}},Z){K=!0;break}}if(!K)throw new Error("Payment fees did not converge. Refresh the quote before submitting.");if(!X.preview)return null;const G=S?xn(B,S.source.decimals,S.destination.decimals,"ceil"):0n;return{...X,batches:xe,sourceSpendCap:pe,actionDefinition:de,destinationAmount:re,preview:{...X.preview,grossAmount:X.preview.grossAmount+G,gasFee:X.preview.gasFee+G,totalFee:(X.preview.totalFee??0n)+G},...S?{sourceGasSkim:B}:{}}}if(r<=0||!h)return null;const R=h||m;if(S&&!b)return null;const F=sa({isPayMode:o,selectedAsset:n,resolvedChainId:g,sourceSwap:b,pivot:S});if(!(!o&&!l&&n.asset?._source==="wallet"&&n.asset.chainId!==g)&&!k&&!A&&!T||T)return null;let N=await M();if(N.length===0)return null;const D={chainId:g,tokenAddress:E,symbol:Ft(E,g)?.symbol??(n.asset.chainId===g&&ge(n.asset.address,E)?n.asset.symbol:d.symbol),decimals:await eo(n.asset,E,g,d)},L=F&&e.initialFeeEstimate!==void 0&&e.initialSourceGasSkim!==void 0,z=F?L?e.initialSourceGasSkim:await Zl({user:R,pivot:S,buildSupplyChainBatches:M,signal:t}):0n;F&&z>0n&&(N=await M({sourceGasSkimOverride:z}));const fe=F?xn(s?zl(b,z):b.amountOutMinimum,S.source.decimals,S.destination.decimals,"floor"):xn(dn(n.amount,n.asset.decimals),n.asset.decimals,D.decimals,"floor"),ce={userOverride:R,useCustomTransfers:!0,feeExecutionMode:p,signal:t,...F?{skipUserFundingPreflight:!0}:{}};let Q=fe,ne=e.initialFeeEstimate??await W(N,E,Q,ce);for(let re=0;re<8;re++){if(t?.aborted)throw new Error("Fee estimation cancelled");const j=Xn(ne,D)??ms(N,D,Q);if(!j)return null;const J=ia(j,fe,s,p);Q=J.grossAmount;let Y,me,B,U,X;const pe=await M({fundingAmountOverride:Q,sourceGasSkimOverride:z,actionContextOverride:J,onDestinationAmount:V=>{Y=V},onSourceSpend:V=>{me=V},onSwap:(V,ie)=>{B=V,U=ie},onActionCalls:V=>{X=V}}),[de,xe]=await Promise.all([W(pe,E,Q,{...ce,validateFeeCalls:e.initialFeeEstimate!==void 0}),L?Lt.estimateBatchGas({user:R,outputToken:S.source.address,stepIndex:0,chainBatches:[pe[0]],signal:t}):void 0]);if(xe&&!(p==="user-transfer"?hs(z,xe.gasFee,e.feeToleranceBps):xe.gasFee===z))throw new Error("Source gas changed. Prepare a fresh fee quote.");const K=p==="user-transfer"?aa(de,ne):de,G=Xn(K,D)??ms(pe,D,Q);if(!G)return null;const P=ia(G,fe,s,p);if(JSON.stringify(J,(V,ie)=>typeof ie=="bigint"?ie.toString():ie)===JSON.stringify(P,(V,ie)=>typeof ie=="bigint"?ie.toString():ie)||p==="user-transfer"&&Aa(J.feeBreakdown,P.feeBreakdown,e.feeToleranceBps)){const V=p==="user-transfer"?j:G,ie=F?xn(z,S.source.decimals,S.destination.decimals,"ceil"):0n;return{batches:pe,fundingAmount:Q,actionContext:J,sourceSpendCap:me,destinationAmount:Y,destinationSwap:B,swapInputAmount:U,actionDefinition:X,feeEstimate:p==="user-transfer"?ne:K,sourceGasSkim:z,preview:{...V,grossAmount:Q+ie,netAmount:J.netAmount,gasFee:V.gasFee+ie,spicenetFee:J.feeBreakdown.spicenetFee,totalFee:J.combinedFeeAmount+ie}}}ne=K,N=pe}throw new Error("Fees did not converge. Refresh the quote before submitting.")}class _l extends Error{constructor(t){super("Amount is too small to cover fees. Increase the amount and retry."),this.preview=t,this.name="FeeShortfallError"}}function ia(e,t,n,o){const s=e.gasFee+(e.bridgeFee??0n);if(e.gasQuoteSource==="static_zero")return{grossAmount:t,netAmount:t,combinedFeeAmount:0n,feeExecutionMode:o??"backend-transfer",feeBreakdown:{gasFee:0n,bridgeFee:0n,spicenetFee:0n}};const r=n?Hc(t,s,10n):null;if(r&&!r.coversFees)throw new _l({...e,grossAmount:t,netAmount:0n,spicenetFee:0n,totalFee:s});const a=r?.spicenetFee??(o==="user-transfer"?tr(t,10n):e.spicenetFee);return{grossAmount:r?.grossAmount??t+a+s,netAmount:r?.netAmount??t,combinedFeeAmount:a+s,feeExecutionMode:o??"backend-transfer",feeBreakdown:{gasFee:e.gasFee,bridgeFee:e.bridgeFee??0n,spicenetFee:a}}}function $p(e,t){const n=e.selectedAsset?.asset;if(!n||n?._source!=="wallet")return;const o=Sn(n,e.resolvedChainId);if(!o||!ge(o,e.executionTokenAddress))return;const s=Ft(e.executionTokenAddress,e.resolvedChainId),r=Bo(t,s?.decimals??e.destinationToken.decimals,n.decimals);if(r<=n.balance)return;const a=Fe(r,n.decimals),i=Fe(n.balance,n.decimals);throw new Error(`Insufficient ${n.symbol} for this total amount. Required ${a} ${n.symbol}; available ${i} ${n.symbol}.`)}function _p(e){const t=Ft(e.executionTokenAddress,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:t?.symbol??e.destinationToken.symbol,decimals:t?.decimals??e.destinationToken.decimals}}function ef(e){const t=e.selectedAsset.asset,n=dn(e.selectedAsset.amount,t.decimals);if(n<=t.balance)return n;throw new Error(`Insufficient ${t.symbol} for this total amount. Required ${Fe(n,t.decimals)} ${t.symbol}; available ${Fe(t.balance,t.decimals)} ${t.symbol}.`)}function tf(e,t,n){const o=Xn(e,_p(t));if(o)return ia(o,n,!!t.isFeeInclusiveInput,t.feeExecutionMode)}function nf(e,t,n){let o=0n,s=0n;const r=n.toLowerCase();for(const a of e)if(a.chainId===t){for(const i of a.calls??[])if(i.to.toLowerCase()===r)try{const l=uo({abi:tt,data:i.data});if(l.functionName!=="transfer")continue;const c=l.args[0].toLowerCase(),d=l.args[1];c===Fn.toLowerCase()?o+=d:c===nn.toLowerCase()&&(s+=d)}catch{continue}}return{spicenetFee:o,gasFee:s}}function of(e,t,n,o){const s=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,r=nf(e,t.resolvedChainId,s);return r.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||r.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:hs(r.spicenetFee,n.feeBreakdown.spicenetFee,t.feeToleranceBps)&&hs(r.gasFee,n.feeBreakdown.gasFee,t.feeToleranceBps)&&hs(o.feeBreakdown.bridgeFee,n.feeBreakdown.bridgeFee,t.feeToleranceBps)}function sf(e,t,n){return e?Sa(e.grossAmount,t.grossAmount,100n)&&Aa(e.feeBreakdown,t.feeBreakdown,n):!1}function rf(e,t){const n=Ft(t,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:t,symbol:n?.symbol??e.selectedAsset?.asset.symbol??"",decimals:n?.decimals??e.selectedAsset?.asset.decimals??e.destinationToken.decimals}}async function af(e,t){const n=e.feeQuote;return n?.feeEstimate&&n.grossFundingAmount!==void 0?{grossFundingAmount:n.grossFundingAmount,feeEstimate:n.feeEstimate}:Jl({...t,feeOnlyAction:e.feeOnlyAction,estimate:e.execution.estimate,tokenDescriptor:rf(e,t.fundingToken)})}function ec(e,t,n){const o=t instanceof Error?t:new Error(String(t));if(o.name==="AbortError"||n){e.ui.setStep("idle");return}const s=o.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(s),e.ui.setError(s)}function tc(e,t){const n=Mn(t,"Payment failed. Please try again.");e.ui.setError(n),e.ui.setPaymentResult({status:"failed",error:n})}async function nc(e){e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setStep("executing"),e.ui.setStatusMsg("Confirm the transaction in your external wallet..."),e.ui.setTxHash(null),e.isPayMode&&(e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"}));try{if(e.validateFeeQuote?.(),!e.feeQuote?.batches||!e.feeQuote.actionDefinition)throw new Error("Review the direct action plan before submitting.");const t=await e.execution.execute(e.feeQuote.batches,e.destinationToken.address,0n,e.execution.onProgress);e.ui.setTxHash(t),e.ui.setStep("success"),e.ui.setStatusMsg("Transaction confirmed"),e.isPayMode&&e.ui.setPaymentResult({status:"success",txHash:t})}catch(t){e.isPayMode?tc(e,t):ec(e,t,!1)}finally{e.ui.setIsExecuting(!1)}}async function oc(e,t,n){e.validateFeeQuote?.();const o=e.feeQuote;if(!o.batches||o.sourceSpendCap===void 0||!o.fundingSource)throw new Error("Refresh the action before submitting.");const s=o.fundedFeeToken,r=o.grossFundingAmount??0n,a=Ul({...e,signal:n,feeOnlyAction:!0,destinationToken:s,actionProceeds:e.actionProceeds??{token:o.fundingSource.token,resolve:async()=>o.proceedsAvailable??0n}},s.address,r);return e.execution.execute(o.batches,o.fundingConversion?.tokenIn??o.fundingSource.token,r,t,n,{...a,userOverride:e.embeddedWalletAddress||e.providerEmbeddedAddress,useCustomTransfers:!0,feeExecutionMode:"backend-transfer",skipPreSubmitFeeEstimate:!0})}async function sc(e){if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.directExternalAction)return nc(e);if(!e.embeddedWalletAddress){e.ui.setError("Wallet not ready");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.ui.setTxHash(null),e.refs.spiceDepositSubmittedRef.current=!1;const t=new AbortController;e.refs.abortControllerRef.current=t;try{const n=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(e.feeQuote?.fundedFeeToken){const h=await oc(e,e.execution.onProgress,t.signal);e.ui.setTxHash(h),e.ui.setStep("success"),e.ui.setStatusMsg("Transaction confirmed");return}const o=sa(e);o&&ef(e);const s=e.feeQuote?.batches?e.feeQuote:await ho({...e,feeExecutionMode:e.feeExecutionMode,isDirect:!e.needsSwap,isQuoting:!1,resolvedSwap:null,buildPayChainBatches:e.execution.buildPayChainBatches,buildSupplyChainBatches:e.execution.buildSupplyChainBatches,estimate:e.execution.estimate});if(!s?.batches||s.fundingAmount===void 0||!s.actionContext)throw new Error("A current action plan is required. Refresh the quote before submitting.");const r=e.isFeeInclusiveInput?s.actionContext.grossAmount:s.actionContext.netAmount;let a=s.batches;const i=a.some(h=>h.tokenTransfers?.length),l={userOverride:n,useCustomTransfers:i,feeExecutionMode:e.feeExecutionMode,...o?{skipUserFundingPreflight:!0}:{}},c=s.fundingAmount,d=s.actionContext;$p(e,c);const p=d,f=await e.execution.execute(a,e.executionTokenAddress,i?c:0n,e.execution.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...l,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:h,chainBatches:m})=>{const g=tf(s.feeEstimate?aa(h,s.feeEstimate):h,e,r);if(!g)throw new Error("Unable to validate the accepted fees. Refresh the quote before submitting.");const y=sf(p,g,e.feeToleranceBps),w=of(m,e,g,p);if(y||w)return null;throw new Error("Transaction fees changed. Refresh the quote before submitting.")}}:{...l,skipPreSubmitFeeEstimate:!0});e.ui.setTxHash(f),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){ec(e,n,t.signal.aborted)}finally{e.ui.setIsExecuting(!1)}}async function rc(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}const t=e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t){e.ui.setError("Select a payment source");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.parsedAmount>0&&e.needsSwap&&!e.exactOutputSwap){e.ui.setError("Swap quote not available. Try a different asset.");return}if(e.directExternalAction)return nc(e);const n=Ql(e)&&!t,o=n?e.feeQuote?.sourceGasSkim??0n:0n,s=r=>e.execution.buildPayChainBatches(n?{...r,sourceGasSkimOverride:o}:r);if(!e.isConnected||!e.address){e.ui.setError("Please connect your wallet to continue");return}if(!e.ready||!e.authenticated){e.ui.setError(`Please authenticate with ${e.provider||"wallet provider"} to continue`);return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{if(e.feeQuote?.fundedFeeToken){const v=await oc(e,k=>{k.txHash&&(e.ui.setTxHash(k.txHash),e.ui.setPaymentResult({status:"processing",txHash:k.txHash}))});e.ui.setPaymentResult(k=>({status:"success",txHash:k?.txHash||v}));return}const r=dn(e.currentPaymentAmount,e.destinationToken.decimals),a={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,...n?{skipUserFundingPreflight:!0}:{}};if(t&&!e.feeOnlyAction){const v=await s(),k=await e.execution.execute(v,e.executionTokenAddress,0n,A=>{A.txHash&&(e.ui.setPaymentResult(b=>({...b??{status:"processing"},txHash:A.txHash})),e.ui.setTxHash(A.txHash))},void 0,a);e.ui.setPaymentResult(A=>({status:"success",txHash:A?.txHash||k}));return}const i=e.selectedAsset?.asset,l=e.feeQuote?.fundingSource;if(!i&&!e.actionProceeds&&!l)throw new Error("Select a payment source");const c=e.feeQuote?.fundingConversion?.tokenIn||l?.token||e.resolvedTokenIn||i?.address||e.destinationToken.address,d=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:r,p=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,f=!!e.feeQuote?.fundingConversion||!!l&&(l.kind!=="balance"||l.asset?._source==="wallet"),{grossFundingAmount:h,feeEstimate:m}=f?{grossFundingAmount:e.feeQuote.grossFundingAmount??0n,feeEstimate:void 0}:await af(e,{requiredNetFunding:d,buildBatches:v=>e.execution.buildPayChainBatches({fundingAmountOverride:v}).then(k=>mo(k,p)),fundingToken:c,executionOptions:a});let g=e.feeQuote?.fundingBatches??e.feeQuote?.batches??mo(await s({fundingAmountOverride:h}),p,e.actionProceeds?void 0:m,{payoutAlreadyGross:!0});const y=Ul(e,e.feeQuote?.fundingConversion?.tokenOut??c,h);y.prepareForSigning&&(g=await y.prepareForSigning(g));const w=g.some(v=>v.tokenTransfers?.length),x=await e.execution.execute(g,c,w?h:0n,v=>{v.txHash&&(e.ui.setPaymentResult(k=>({...k,txHash:v.txHash})),e.ui.setTxHash(v.txHash))},void 0,{...a,...y,skipPreSubmitFeeEstimate:!0});e.ui.setPaymentResult(v=>({status:"success",txHash:v?.txHash||x}))}catch(r){tc(e,r)}finally{e.ui.setIsExecuting(!1)}}async function lf(e){const{definition:t,account:n,chainId:o}=e,{calls:s}=t;if(!ge(t.context.executorAddress,n)||t.context.chainId!==o||!s.length)throw new Error("The direct action no longer matches its wallet or chain.");const r=yt(o);let a;for(const i of s){await e.assertCurrent();const[l,c]=await Promise.all([fl({client:r,account:n,calls:[i]}),r.getBalance({address:n})]);if(c<i.value+l)throw new Error("The external wallet has insufficient native balance for this transaction and network gas.");const{extWc:d,viemChain:p}=await Zr({wallet:e.wallet,account:n,chainId:o});a=await np({extWc:d,viemChain:p,client:r,calls:[i],errorMessage:"The external transaction reverted. Retry the unfinished action when ready."})}if(!a)throw new Error("The direct action has no confirmed receipt.");return a}async function ac(e){const{asset:t,embedded:n,external:o,amount:s}=e;if(!o||!e.externalWallet)throw new Error("Connect the source wallet before funding.");if(s<=0n)return;const r=yt(t.chainId),a=t.isNative||be(t.address),[i,l]=await Promise.all([ml({client:r,account:o,recipient:n,token:t.address,isNative:a,amount:s}),r.getBalance({address:o})]);if(l<i+(a?s:0n))throw new Error("The source wallet has insufficient native balance for funding and gas.");const{extWc:c,viemChain:d}=await Zr({wallet:e.externalWallet,account:o,chainId:t.chainId});await op({extWc:c,sourceClient:r,recipient:n,tokenAddr:t.address,isNative:a,amount:s,viemChain:d,observer:{onSending:()=>e.assertCurrent()}})}function ic(e){const t=Qt(Mt),n=Ge(e.chainId),o=e.address??n?.supportedTokens?.find(m=>m.symbol.toLowerCase()===e.symbol?.toLowerCase())?.address,s=e.symbol??(o&&be(o)?n?.nativeCurrency?.symbol:n?.supportedTokens?.find(m=>!!o&&ge(m.address,o))?.symbol),r=ba(e.chainId,t?.rpcOverrides),[a,i]=O(0),l=`${e.chainId}:${o?.toLowerCase()}:${r}:${e.decimals??""}:${s??""}:${a}`,[c,d]=O(null);ae(()=>{let m=!1;if(!(!e.enabled||!o||!r?.trim()))return Promise.all([e.decimals??as(e.chainId,o,t?.rpcOverrides),s??_n(yt(e.chainId,t?.rpcOverrides),{address:o,abi:tt,functionName:"symbol"}).catch(()=>{})]).then(([g,y])=>{if(!Number.isInteger(g)||g<0||g>255)throw new Error("Invalid destination token decimals");m||d({key:l,decimals:g,symbol:y})}).catch(g=>{m||d({key:l,error:g.message})}),()=>{m=!0}},[e.enabled,l]);const p=c?.key===l?c:null,f=ue(()=>({address:o??Tt,chainId:e.chainId,decimals:p?.decimals??0,symbol:s??p?.symbol??(o?Po(o):""),logoURI:e.logoURI}),[o,e.chainId,p?.decimals,p?.symbol,s,e.logoURI]),h=e.enabled?o?r?.trim()?p?.error??null:`Configure SpiceFlowProvider rpcOverrides[${e.chainId}] before continuing.`:"Configure the destination token address before continuing.":null;return{token:f,error:h,ready:e.enabled&&!!o&&!!r?.trim()&&p?.decimals!==void 0,refresh:te(()=>i(m=>m+1),[])}}function lc(e,t){const n=!!e&&e.symbol!==void 0&&e.decimals!==void 0,o=ic({enabled:t&&!!e&&!n,chainId:e?.chainId??0,address:e?.address,decimals:e?.decimals,symbol:e?.symbol,logoURI:e?.logoURI});return{token:e?n?e:o.ready?o.token:void 0:void 0,error:o.error}}const la={address:Tt,symbol:"",decimals:18,chainId:0};function cc(e,t,n){return ge(e.address,t)&&e.chainId===n?e._source==="wallet"?0:1:2}function cf(e,t,n,o){const s=cc(e,n,o)-cc(t,n,o);return s!==0?s:(t.balanceUsd||0)-(e.balanceUsd||0)}const df=Ei;function dc(e){const t=Qt(Mt),n=ps(),o=t?.embeddedWalletAddress||n.embeddedAddress,s=t?.externalWalletAddress||n.externalAddress,r=(t?.mode||"7702")!=="7702",a=e.destinationToken??la,i=e.enabled&&!!e.destinationToken,l=Ao({...e,owner:o,enabled:i&&!!o&&(!r||e.includeCrossChainEmbeddedAssets!==!1),role:"spend-source",destination:e.destinationToken}),c=Ao({...e,owner:s,enabled:i&&!!s&&(r||e.includeExternalWalletAssets!==!1),role:"spend-source",destination:e.destinationToken});return{displayAssets:ue(()=>[...l.assets,...c.assets].sort((d,p)=>cf(d,p,a.address,a.chainId)),[l.assets,c.assets,a.address,a.chainId]),filteredSpiceAssets:l.rollupAssets,walletAssets:[...l.walletAssets,...c.walletAssets],embeddedWalletAddress:o,externalAddress:s,isNon7702:r,refreshSpiceAssets:l.refresh,refreshWalletAssets:l.refresh,loading:l.loading||c.loading,refreshing:l.refreshing||c.refreshing,error:l.error||c.error}}function uf(e,t){return!e||e._source!=="wallet"?null:Br(e,t)}function ca(e){return ai({aerodrome:!1,oneInch:{chainIds:[]},customVenues:e})}const da=Co(),pf=ca(da.input);function uc(e){return{venue:"mapped-transfer",amountOut:e,amountOutMinimum:e,calls:[]}}function pc(e){return{venue:"mapped-transfer",amountIn:e,amountInMax:e,amountOut:e,calls:[]}}async function ua(e){if(ge(e.tokenIn,e.tokenOut))return uc(e.amountIn);if(e.resolveInputSwap){const n=await e.resolveInputSwap({type:"swap",tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:e.amountIn,maxSlippage:e.maxSlippage},e.chainId,e.recipient);if(n)return n}const t=await(e.liquidityVenues?ca(Co(e.liquidityVenues).input):pf).resolveSwap({type:"swap",tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:e.amountIn,maxSlippage:e.maxSlippage},e.chainId,e.recipient,e.selectedSwap);if(!t)throw new Error("No liquidity for this pair.");return t}async function ff(e){return ge(e.tokenIn,e.tokenOut)?pc(e.amountOut):Gs({customVenues:e.liquidityVenues?Co(e.liquidityVenues).output:da.output}).getQuote({tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountOut:e.amountOut,maxSlippage:e.maxSlippage},e.chainId,e.recipient)}function fc(e){const{enabled:t=!0,direction:n,selectedAsset:o,destinationToken:s,chainId:r=s.chainId,recipient:a,paymentAmount:i,maxSlippage:l,refreshIntervalMs:c,resolveInputSwap:d,resolveExactOutputSwap:p}=e,f=Qt(Mt),h=f?.liquidityVenues,m=JSON.stringify([f?.network,f?.apiUrl,f?.rpcOverrides]),[g,y]=O(!1),[w,x]=O(null),[v,k]=O(null),[A,b]=O(null),[S,T]=O(null),[E,I]=O(null),[M,W]=O(null),[R,F]=O(null),[N,D]=O(null),[L,z]=O(null),[fe,ce]=O(null),[Q,ne]=O(null),[re,j]=O(null),[J,Y]=O(null),[me,B]=O(0),[U,X]=O(null),[pe,de]=O(null),xe=_(null),K=_(null),G=_(0),P=_(new Map),V=te(()=>{G.current++,P.current.clear(),de(null),B(Le=>Le+1)},[]),ie=c&&c>0?c:null,ke=h?JSON.stringify(h):"",Ee=ue(()=>h?Co(h):da,[ke]),Be=ue(()=>ca(Ee.input),[Ee]),Ie=ue(()=>Gs({customVenues:[...p?[{name:"consumer-exact-output",chainIds:[r],preferred:!0,resolve:p}]:[],...Ee.output]}),[p,r,Ee]);ae(()=>{P.current.clear()},[Ie]);const Z=ue(()=>t?uf(o?.asset,r):null,[t,o?.asset,r]),ot=ue(()=>{if(!t||!o?.asset)return null;if(Z)return Z.destination.address;const Le=Sn(o.asset,r);if(Le)return Le;const ct=jn(o.asset.address,r,o.asset.chainId);return ct?ct.address:null},[t,o?.asset,r,Z]),qe=ue(()=>t&&o?.asset?ko(o.asset,r):[],[t,o?.asset,r]),Ct=ue(()=>qe.map(Le=>Le.toLowerCase()).join(","),[qe]),ht=JSON.stringify([t,m,o?.asset.owner,o?.asset.location,o?.asset.receiptTokenId,o?.asset.address,o?.asset.chainId,o?.asset.decimals,o?.amount,r,Ct,n,i]);ae(()=>{let Le=!1;if(K.current&&(clearTimeout(K.current),K.current=null),!t||!o?.asset||Z||qe.length<=1){j(null),Y(null);return}return K.current=setTimeout(async()=>{const ct=n==="input"?o.amount:i||"0";let $e=0n;try{$e=n==="input"?dn(ct,o.asset.decimals):0n}catch{$e=0n}try{const dt=await Ii(o.asset,r,{requiredAmount:$e});Le||(j(dt),Y(ht))}catch{Le||j(null)}},400),()=>{Le=!0,K.current&&(clearTimeout(K.current),K.current=null)}},[ht]);const Ve=ue(()=>(J===ht?re:null)??ot,[re,J,ht,ot]),Qe=ue(()=>!o?.asset||!Ve?[]:[Ve,...qe.filter(Le=>Le.toLowerCase()!==Ve.toLowerCase())],[o?.asset,Ve,qe]),at=ue(()=>!o?.asset||!qo(o.asset.address,o.asset.chainId,s.address,s.chainId)||!Ve?!1:ge(Ve,s.address),[o,s.address,s.chainId,Ve]),je=Ve?ge(Ve,s.address):!1,Dt=n==="output"&&parseFloat(i||"0")===0,Ke=t&&!!o?.asset&&!at&&!je&&!Dt,gt=JSON.stringify([t,ke,n,Ke,m,o?.asset.owner,o?.asset.location,o?.asset.receiptTokenId,o?.asset.address,o?.asset.chainId,o?.asset.decimals,n==="input"?o?.amount:i,Qe.map(Le=>Le.toLowerCase()),r,s.address.toLowerCase(),s.chainId,s.decimals,a?.toLowerCase(),l,ie,Z?.source.address.toLowerCase()??""]),De=ue(()=>({}),[gt,Be,Ie,d,me]),et=pe?.request===De&&(!ie||pe.expiresAt>Date.now());return ae(()=>{if(!ie||pe?.request!==De)return;const Le=setTimeout(V,Math.max(0,pe.expiresAt-Date.now()));return()=>clearTimeout(Le)},[ie,pe,De,V]),ae(()=>{xe.current&&clearTimeout(xe.current),X(De),de(null),x(null);const Le=n==="input"?o?.amount:i,ct=parseFloat(Le||"0");if(!t||!Number.isFinite(ct)||ct<=0||!o?.asset||!a||Qe.length===0){G.current++,k(null),b(null),T(null),I(null),W(null),F(null),D(null),ne(null),x(null),y(!1);return}const $e=o.asset.decimals;let dt;try{dt=n==="input"?dn(o.amount,$e):dn(i||"0",s.decimals)}catch(Me){G.current++,x(Me instanceof Error?Me.message:"Invalid amount or token precision"),y(!1);return}const kt=++G.current,ut=()=>kt!==G.current;y(!0);const Re=n==="output"?150:100,ft=async(Me,$,ee,ze={chainId:r,tokenOut:s.address,amountIn:dt},Ce=Qe)=>{for(const le of Ce){const Pe=`${m}:${ke}:${n}:${ze.chainId}:${le.toLowerCase()}:${ze.tokenOut.toLowerCase()}:${ze.amountIn.toString()}:${a.toLowerCase()}:${l??"default"}:${ie??"default"}`,Ae=P.current.get(Pe),q=Ae&&Ae.expiresAt>Date.now()?Me(Ae):void 0;if(q)return{quote:q,tokenIn:le,expiresAt:Ae.expiresAt};const Ze=await ee(le);if(ut())return"stale";if(!Ze)continue;const ye=Date.now()+Math.min(ie??3e4,3e4);return P.current.set(Pe,{expiresAt:ye,direction:n,...$(Ze)}),{quote:Ze,tokenIn:le,expiresAt:ye}}return null},Ot=Me=>ft($=>$.resolvedSwap,$=>({resolvedSwap:$}),async $=>{const ee=!Z&&Me.chainId===r&&o.asset._source!=="wallet",ze=ee?await eo(o.asset,$,Me.chainId,s):$e;if(ut())return null;const Ce=ee?zs(Me.amountIn,$e,ze):Me.amountIn;if(ge($,Me.tokenOut))return uc(Ce);const le={type:"swap",tokenIn:$,tokenOut:Me.tokenOut,amountIn:Ce,maxSlippage:l};if(d){const Pe=await d(le,Me.chainId,a);if(Pe)return Pe}return Be.resolveSwap(le,Me.chainId,a)},Me,Me.candidates);return xe.current=setTimeout(async()=>{try{if(n==="input"){let Me=null,$=dt;if(Z){if(Me=await Ot({chainId:Z.source.chainId,tokenOut:Z.source.address,amountIn:dt,candidates:[o.asset.address]}),Me==="stale"||ut())return;if(!Me)throw new Error("No liquidity for this pair");$=xn(Me.quote.amountOutMinimum,Z.source.decimals,Z.destination.decimals,"floor")}const ee=Ke||!Z?await Ot({chainId:r,tokenOut:s.address,amountIn:$,candidates:Qe}):null;if(ee==="stale"||ut())return;if(Ke&&!ee)throw new Error("No liquidity for this pair");const ze=ee?ee.quote.amountOut:$,Ce=Math.min(ee?.expiresAt??1/0,Me?.expiresAt??1/0),le=Z?.destination.decimals??await eo(o.asset,ee.tokenIn,r,s),Pe=!Z&&o.asset._source!=="wallet"?zs($,$e,le):$;if(ut())return;ne(ee?.tokenIn??Z?.destination.address??null),de({request:De,key:`${vo(Ha(gt))}:${kt}`,expiresAt:Ce}),D(ze),z(Pe),ce(le),T(Ke?ee?.quote??null:null),I(Me?.quote??null),W(null),F(null);const Ae=parseFloat(Fe(ze,s.decimals));k(Ae<.01?Ae.toPrecision(4):Ae.toLocaleString(void 0,{maximumFractionDigits:6})),b(null),x(null)}else{const Me=Pe=>ft(Ae=>Ae.exactOutputSwap,Ae=>({exactOutputSwap:Ae}),async Ae=>{try{return ge(Ae,Pe.tokenOut)?pc(Pe.amountOut):await Ie.getQuote({tokenIn:Ae,tokenOut:Pe.tokenOut,amountOut:Pe.amountOut,maxSlippage:l},Pe.chainId,a)}catch{return null}},{chainId:Pe.chainId,tokenOut:Pe.tokenOut,amountIn:Pe.amountOut},Pe.candidates),$=!Z||Ke,ee=$?await Me({chainId:r,tokenOut:s.address,amountOut:dt,candidates:Qe}):null;if(ee==="stale"||ut())return;if($&&!ee)throw new Error("No liquidity for this pair");let ze=null;if(Z){const Pe=ee?ee.quote.amountInMax:dt;if(ze=await Me({chainId:Z.source.chainId,tokenOut:Z.source.address,amountOut:xn(Pe,Z.destination.decimals,Z.source.decimals,"ceil"),candidates:[o.asset.address]}),ze==="stale"||ut())return;if(!ze)throw new Error("No liquidity for this pair")}const Ce=ze?$e:await eo(o.asset,ee.tokenIn,r,s);if(ut())return;ne(ee?.tokenIn??Z?.destination.address??null),de({request:De,key:`${vo(Ha(gt))}:${kt}`,expiresAt:Math.min(ee?.expiresAt??1/0,ze?.expiresAt??1/0)}),F(ee?.quote??null),W(ze?.quote??null),T(null),I(null),D(null);const le=ze?.quote.amountIn??ee.quote.amountIn;b(Fe(le,Ce)),k(null),x(null)}}catch(Me){if(ut())return;const $=Me instanceof Error?Me.message:"Failed to get quote";x($),k(null),b(null),T(null),I(null),W(null),F(null),D(null),ne(null)}finally{ut()||y(!1)}},Ke||Z?Re:0),()=>{G.current++,xe.current&&clearTimeout(xe.current)}},[De]),{inputAmount:et&&n==="input"?L:null,inputDecimals:et&&n==="input"?fe:null,quoteKey:et?pe.key:null,quoteExpiresAt:et?pe.expiresAt:null,refreshQuote:V,isQuoting:U===De?g:Ke||!!Z,quoteError:U===De?w:null,estimatedOutput:et?v:null,estimatedInput:et?A:null,resolvedSwap:et?S:null,exactOutputSwap:et?R:null,quoteAmountOut:et?N:null,resolvedTokenIn:Ke&&et?Q??Ve:Ve,isDirect:je,needsSwap:Ke,selectedIsEquivalent:at,sourceSwap:et?E:null,sourceExactOutputSwap:et?M:null,pivot:Z}}function os(e){const{enabled:t=!0,destinationToken:n,selectedAsset:o,paymentAmount:s="0",sourceChains:r,supportedSourceAssets:a,buildActionCalls:i,feeExecutionMode:l="user-transfer",buildSpicenetBatch:c,onPayExecute:d,resolveExactOutputSwap:p,amountDirection:f=e.feeOnlyAction?"output":"input",onSuccess:h,onError:m}=e,g=lc(n,t),y=g.token??la,w=t&&!!g.token,x=f==="output",v=f==="input-inclusive",k=e.feeFunding?.length!==0&&(e.actionProceeds==="output"||!!e.feeFunding?.length),A=x?"output":"input",b=y.chainId,S=Qt(Mt),T=qc(S?.feeToleranceBps),E=S?.mode||"7702",I=!1,M=!!S?.isWhitelistGateActive,W=!!S?.isWhitelistConfigured&&S?.isUserWhitelisted!==!0,R=ue(()=>r??S?.supportedChainIds??[],[r,S?.supportedChainIds]),F=a,{address:N,isConnected:D,isReady:L,isAuthenticated:z,provider:fe}=Zn(),{execute:ce,estimate:Q}=Ms(),{externalWallet:ne,embeddedAddress:re,activeWallet:j,activeAddress:J}=ps(),Y=S?.externalWalletAddress,me=S?.embeddedWalletAddress||re,B=o,U=Ss(B?.asset,E!=="7702"),X=!!B&&B.asset.chainId===y.chainId&&ge(Ye(B.asset.address),Ye(y.address)),pe=E!=="7702"&&U&&X&&(!x||Number(s)>0)&&!e.feeOnlyAction&&!e.actionProceeds,de=U&&!pe,xe=g.error?g.error:d?"Move onPayExecute protocol calls to buildActionCalls and application updates to onSuccess before continuing.":e.actionExecution?.wallet==="external"&&!pe?"This action requires the external wallet as its caller. Select its destination token on the destination chain for direct execution, or configure a beneficiary-capable embedded action for routing.":null,{displayAssets:K,filteredSpiceAssets:G,walletAssets:P,embeddedWalletAddress:V,refreshSpiceAssets:ie,refreshWalletAssets:ke,loading:Ee,refreshing:Be,error:Ie}=dc({address:N,destinationToken:y,supportedSourceAssets:F,sourceChains:R,additionalSourceTokens:[...e.additionalSourceTokens??[],...B?.asset._source==="wallet"?[{address:B.asset.address,chainId:B.asset.chainId,decimals:B.asset.decimals,symbol:B.asset.symbol,name:B.asset.name,logoURI:B.asset.logoURI}]:[]],includeExternalWalletAssets:e.includeExternalWalletAssets,includeCrossChainEmbeddedAssets:e.includeCrossChainEmbeddedAssets,enabled:w&&(E!=="7702"?!!Y:!!me)}),Z=K,ot=ue(()=>e.feeOnlyAction||k?Z.filter(oe=>oe.balance>0n&&oe.location!=="external"&&(oe._source==="spice"||oe._source==="wallet"&&oe.chainId===b)):[],[Z,e.feeOnlyAction,k,b]),qe=B?[...P,...G].find(oe=>nt(oe)===nt(B.asset)):void 0,Ct=ue(()=>B&&qe?{...B,asset:qe}:B,[B,qe]),ht=B?po(qe??B.asset,"spend-source",{allowedTokens:S?.allowedTokens,rpcOverrides:S?.rpcOverrides,liquidityVenues:S?.liquidityVenues,isWhitelistGateActive:M},y,F):null,Ve=qe?qe.balance<(B?.asset.balance??0n)?qe.balance:B.asset.balance:0n,[Qe,at]=O(!1),[je,Dt]=O(null),Ke=_(m);Ke.current=m;const gt=te(oe=>{Dt(oe),typeof oe=="string"&&oe&&Ke.current?.(new Error(oe),fs(oe))},[]),[De,et]=O("idle"),[Le,ct]=O(""),[$e,dt]=O(null),[kt,ut]=O(!1),[Re,ft]=O(null),[Ot,Me]=O(null),[$,ee]=O(!1),[ze,Ce]=O(!1),[le,Pe]=O(null),Ae=_(B),q=_(!1),Ze=_(null),ye=_(null),Xe=_(null),Ht=_(null),qt=_(null),Te=_(null),Wt=_(h),Nt=_(null),wt=_(!1),[On,Gn]=O(null),[wn,Pn]=O(null),[bn,jt]=O(!1),[Kt,ln]=O(0),Jt=Re?.status==="success"?Re.txHash:De==="success"?$e:null,Zt=!!Jt&&On!==Jt,on=_(Zt);on.current=Zt,ae(()=>{Ae.current=B},[B]);const st=pe?Y:V||re||N,Je=w&&!Qe&&De==="idle"&&!xe&&!W&&!!st&&!pe&&!x&&v&&l==="user-transfer"&&!e.feeOnlyAction&&!e.actionInput&&!e.actionProceeds&&!!B&&Number(B.amount||"0")===0&&!!ht?.eligible&&Ve>0n,$t=ue(()=>{if(!Je||!B)return B;const oe=10n**BigInt(B.asset.decimals);return{...B,amount:Fe(Ve<oe?Ve:oe,B.asset.decimals)}},[Je,B,Ve]),vn=fc({enabled:w&&!W&&!pe,direction:A,selectedAsset:$t,destinationToken:y,chainId:b,recipient:st,paymentAmount:s,resolveExactOutputSwap:p,resolveInputSwap:e.resolveInputSwap,maxSlippage:e.maxSlippage}),_t=pe?{...vn,quoteKey:"direct-external",quoteExpiresAt:null,quoteAmountOut:null,inputAmount:null,inputDecimals:B?.asset.decimals??null,isQuoting:!1,quoteError:null,isDirect:!0,needsSwap:!1,selectedIsEquivalent:!0,resolvedTokenIn:y.address,resolvedSwap:null,exactOutputSwap:null,sourceSwap:null,sourceExactOutputSwap:null,pivot:null,estimatedInput:x?s:B?.amount??null,estimatedOutput:x?s:B?.amount??null}:vn,Ue=_t,{isQuoting:cn,resolvedSwap:We,exactOutputSwap:en,quoteAmountOut:It,resolvedTokenIn:pt,isDirect:Un,needsSwap:hn,selectedIsEquivalent:Oo,sourceSwap:se,sourceExactOutputSwap:he,pivot:ve}=_t,_e=x?parseFloat(s||"0"):parseFloat(B?.amount||"")||0,Vt=B?.asset?._source==="wallet",St=!!B?.asset&&Vt&&B.asset.chainId!==b,sn=B?Number(Fe(Ve,B.asset.decimals)):0,rn=ue(()=>{if(!B||x)return!1;try{return dn(B.amount||"0",B.asset.decimals)>Ve}catch{return!0}},[B,x,Ve]);ae(()=>{w||(gt(null),at(!1),Zt||(et("idle"),ct(""),dt(null),ut(!1),ft(null)),Me(null),ee(!1),Ce(!1),Pe(null),q.current=!1,Ze.current&&(Ze.current.abort(),Ze.current=null))},[w,Zt]);const un=te(oe=>{et({building:"building","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[oe.step]||"executing"),ct(oe.message),oe.txHash&&dt(oe.txHash)},[]),Gt=ue(()=>({currentPaymentAmount:s,isFeeInclusiveInput:v,feeOnlyAction:e.feeOnlyAction,swapInputAmount:_t.inputAmount,destinationToken:y,embeddedWalletAddress:V,providerEmbeddedAddress:re,externalWalletAddress:Y,address:N,recipient:e.recipient??(E!=="7702"?Y:void 0),isNon7702:I,isPayMode:x,resolvedChainId:b,buildActionCalls:i,feeExecutionMode:l,buildSpicenetBatch:c,selectedAsset:B,needsSwap:hn,resolvedSwap:We,exactOutputSwap:en,quoteAmountOut:It,resolvedTokenIn:pt,sourceSwap:se,sourceExactOutputSwap:he,pivot:ve,resolveSourceExactOutputSwap:async oe=>{if(!ve||!st)throw new Error("Swap route is not ready.");const lt=await ff({chainId:ve.source.chainId,recipient:st,tokenIn:B.asset.address,tokenOut:ve.source.address,amountOut:oe,liquidityVenues:S?.liquidityVenues,maxSlippage:e.maxSlippage}).catch(()=>null);if(!lt)throw new Error("No liquidity for this pair.");return lt},resolveInputSwap:async(oe,lt)=>{if(!pt||!st)throw new Error("Swap route is not ready.");return ua({chainId:b,recipient:st,tokenIn:pt,tokenOut:y.address,amountIn:oe,selectedSwap:lt,liquidityVenues:S?.liquidityVenues,maxSlippage:e.maxSlippage,resolveInputSwap:e.resolveInputSwap})}}),[s,y,V,re,Y,N,e.recipient,e.feeOnlyAction,e.maxSlippage,e.resolveInputSwap,_t.inputAmount,v,E,I,x,b,i,l,c,B,hn,We,en,It,pt,se,he,ve,st,S?.liquidityVenues]),tn=ue(()=>B?.asset?ve?ve.destination.address:hn&&pt?pt:B.asset.chainId===b?B.asset.address:pt??Sn(B.asset,b)??y.address:y.address,[B,y.address,hn,b,pt,ve]),Pt=JSON.stringify([B&&nt(B.asset),f,y.address,y.chainId,y.decimals,e.recipient,E,Y,pe?Y:V,S?.apiUrl,S?.rpcOverrides,e.maxSlippage,l,T,e.feeOnlyAction,e.actionProceeds==="output"?"output":e.actionProceeds?.token,e.feeFunding,e.actionInput?.map(oe=>[oe.token,oe.amount.toString()]),e.feeFundingReserve&&nt(e.feeFundingReserve.asset),e.feeFundingReserve?.amount.toString(),S?.liquidityVenues,S?.allowedTokens,M,F,R,e.actionInput,e.actionProceeds,e.feeFunding,b,tn,Ue.pivot?.source.address,Ue.pivot?.destination.address],(oe,lt)=>typeof lt=="bigint"?lt.toString():lt),ro=_(null);ro.current=w&&!Qe&&!xe&&!W?Pt:null,ae(()=>()=>{qt.current?.controller.abort(),qt.current=null},[Pt,w,Qe,xe,W]);const Yt=vo(rd(JSON.stringify([Pt,B?.amount,s]))),Cn=_({key:Yt,enabled:w,sourceBalance:Ve,sourceEligible:ht?.eligible});Cn.current={key:Yt,enabled:w,sourceBalance:Ve,sourceEligible:ht?.eligible};const An=_(null),kn=_(!1),Yn=_(e.onSubmit);Yn.current=e.onSubmit;const yo=te(()=>kn.current?(kn.current=!1,Yn.current?.(),Wt.current=Te.current.onSuccess,An.current={key:Cn.current.key,quote:Te.current.feeQuote},sc(Te.current)):Promise.resolve(),[]),H=pe,we=W,He=!Xe.current?.quote.fundedFeeToken&&(v||!!ve)&&!!Ot&&Ot.netAmount===0n,Se=ue(()=>!!e.feeOnlyAction||(!!B?.asset||!!e.actionProceeds)&&_e>0,[B,_e,e.actionProceeds,e.feeOnlyAction]),mt=ue(()=>!w||!Se||!B?.asset&&!e.actionProceeds&&!e.feeOnlyAction?null:[Yt,x?"pay":"supply",f,B?nt(B.asset):"sdk-funded",e.actionInput?.map(oe=>`${oe.token.toLowerCase()}:${oe.amount}`).join(",")??"",e.feeFunding?.join(",")??"",JSON.stringify(S?.rpcOverrides),S?.apiUrl,e.recipient,B?.asset.address.toLowerCase(),B?.asset.chainId,B?.amount,s,y.address.toLowerCase(),y.chainId,b,Ue.resolvedTokenIn?.toLowerCase()??"",Ue.quoteKey,Ue.needsSwap?"swap":"direct",Ue.isDirect?"direct-token":"routed-token","7702",X?"source-dest":"cross-chain",Ue.isQuoting?"quoting":"quoted",Ue.exactOutputSwap?.amountIn?.toString()??"",Ue.exactOutputSwap?.amountInMax?.toString()??"",Ue.exactOutputSwap?.venue??"",Ue.resolvedSwap?.amountOut?.toString()??"",Ue.quoteAmountOut?.toString()??"",Ue.sourceSwap?.amountOutMinimum?.toString()??"",Ue.sourceExactOutputSwap?.amountInMax?.toString()??"",Ue.pivot?.source.address.toLowerCase()??"",V??"",re??"",N??""].join("|"),[w,Yt,e.actionProceeds,e.feeOnlyAction,e.actionInput,e.feeFunding,Qe,De,Se,H,B,x,f,s,y,b,Ue,I,X,V,re,N]),rt=te(async(oe,lt,Ut)=>{if(pe){if(!Y||!B)throw new Error("Connect the external wallet before continuing.");return Zp({selectedAsset:lt?.selectedAsset??B,destinationToken:y,paymentAmount:x?s:void 0,account:Y,beneficiary:e.recipient,buildActionCalls:i,feeExecutionMode:l})}const bt={...Ut??{...Gt,selectedAsset:$t},requestTimestampMs:Date.now()},it={signal:oe,feeToleranceBps:T,feeOnlyAction:e.feeOnlyAction,actionInput:e.actionInput,actionProceeds:e.actionProceeds==="output"?void 0:e.actionProceeds,feeFunding:e.feeFunding,feeFundingBalances:ot,feeFundingReserve:e.feeFundingReserve,liquidityVenues:S?.liquidityVenues,maxSlippage:e.maxSlippage,resolveExactOutputSwap:p,selectedAsset:$t,isPayMode:x,isFeeInclusiveInput:v,parsedAmount:Je?Number($t.amount):_e,needsSwap:Ue.needsSwap,exactOutputSwap:Ue.exactOutputSwap,isNon7702:I,isSourceDestToken:X,currentPaymentAmount:s,destinationToken:y,feeExecutionMode:l,resolvedTokenIn:Ue.resolvedTokenIn,embeddedWalletAddress:V,providerEmbeddedAddress:re,resolvedChainId:b,isConnected:D,address:N,ready:L,authenticated:z,isDirect:Ue.isDirect,resolvedSwap:Ue.resolvedSwap,sourceSwap:Ue.sourceSwap,sourceExactOutputSwap:Ue.sourceExactOutputSwap,pivot:Ue.pivot,isQuoting:Ue.isQuoting,executionTokenAddress:tn,buildPayChainBatches:vt=>Qs(bt,vt),buildSupplyChainBatches:vt=>js(bt,vt),estimate:Q,...lt},At=!it.feeOnlyAction&&it.selectedAsset&&k&&it.selectedAsset.asset._source==="wallet"&&it.selectedAsset.asset.chainId===b;if(k&&!it.feeOnlyAction&&it.selectedAsset&&!At&&e.feeFunding&&e.feeFunding.join(",")!==ra.join(","))throw new Error("Fee-source overrides require a wallet source on the action chain.");return At||k&&e.actionProceeds==="output"?Kp(it,bt,ho,e.actionProceeds==="output"):ho(it)},[B,k,$t,Je,pe,Y,e.recipient,i,e.feeOnlyAction,e.actionInput,e.actionProceeds,e.feeFunding,ot,e.feeFundingReserve,e.maxSlippage,p,T,S?.liquidityVenues,x,v,_e,Ue,I,X,s,y,l,V,re,Gt,Q,b,D,N,L,z,tn]);ae(()=>{ye.current=rt},[rt]);const Kn=te(async oe=>{if(x)return null;if(!B||nt(oe)!==nt(B.asset)||!st||!pt)throw new Error("Select a source before calculating Max.");let lt=oe.balance;if(pe){if(!oe.isNative&&!be(oe.address))return Fe(lt,oe.decimals);const Ut=yt(oe.chainId),bt=Y;let it=lt;for(let At=0;At<8;At++){const vt=await rt(void 0,{selectedAsset:{asset:oe,amount:Fe(At===0?1n:it,oe.decimals)}});if(!vt?.actionDefinition)throw new Error("The direct action could not be sized.");const pn=await fl({client:Ut,account:bt,calls:vt.actionDefinition.calls}),er=lt>pn?lt-pn:0n;if(er===0n)return"0";if(At>0&&it<=er)return Fe(it,oe.decimals);it=er}throw new Error("Network gas could not be reserved for Max. Enter a smaller amount.")}if(de&&(oe.isNative||be(oe.address))){if(!Y)throw new Error("Connect the source wallet before calculating Max.");const Ut=await ml({client:yt(oe.chainId),account:Y,recipient:st,token:oe.address,isNative:!0,amount:1n});lt-=Ut}return k&&v&&oe._source==="wallet"&&oe.chainId===b?Fe(lt>0n?lt:0n,oe.decimals):$l({balance:lt,decimals:oe.decimals,planForAmount:async Ut=>{const bt={...Gt,requestTimestampMs:Date.now(),selectedAsset:{asset:oe,amount:Fe(Ut,oe.decimals)}};let it=Ut;ve?(bt.sourceSwap=await ua({chainId:oe.chainId,recipient:st,tokenIn:oe.address,tokenOut:ve.source.address,amountIn:Ut,maxSlippage:e.maxSlippage,liquidityVenues:S?.liquidityVenues,resolveInputSwap:e.resolveInputSwap}),it=xn(bt.sourceSwap.amountOutMinimum,ve.source.decimals,ve.destination.decimals,"floor")):it=zs(Ut,oe.decimals,await eo(oe,pt,b,y)),bt.resolvedSwap=hn?await bt.resolveInputSwap(it):null,bt.swapInputAmount=it,bt.quoteAmountOut=bt.resolvedSwap?.amountOut??it;const At=k&&oe._source==="wallet"&&oe.chainId===b,vt=await rt(void 0,{selectedAsset:bt.selectedAsset,...At?{isFeeInclusiveInput:!0}:{},parsedAmount:Number(bt.selectedAsset.amount),sourceSwap:bt.sourceSwap,resolvedSwap:bt.resolvedSwap,isQuoting:!1,buildSupplyChainBatches:pn=>js(bt,pn)},bt);return At&&vt?.fundingSource?.kind==="input"&&!v?{...vt,sourceSpendCap:Ut+(Ut-vt.swapInputAmount)}:vt}})},[B,k,Gt,x,pe,st,pt,b,y,de,Y,ve,hn,rt,e.maxSlippage,e.resolveInputSwap,e.actionProceeds,e.feeFunding,v,S?.liquidityVenues]);Hr({shouldRun:w&&!Qe&&De==="idle"&&(Se||Je)&&!Ue.isQuoting&&(!!mt||Je),deps:[w,Qe,De,Se,H,Ue.isQuoting,mt,Je,Pt],onSkip:()=>{if(!w){Ht.current=null,ee(!1),Ce(!1),Pe(null),Me(null);return}if(Qe||De!=="idle"){ee(!1);return}if(!Se){Me(null),ee(!1),Ce(!1),Pe(null);return}Ue.isQuoting&&(ee(!1),Ce(!1))},onCleanup:()=>ee(!1),delayMs:Ue.needsSwap||Ue.pivot?0:100,backgroundIntervalMs:3e4,run:async({isBackground:oe,isCurrent:lt,signal:Ut})=>{if(Je){const it=Ht.current;if(it?.scope===Pt&&Date.now()-it.at<3e4||qt.current?.scope===Pt&&Date.now()-qt.current.at<3e4)return;qt.current?.controller.abort();const At=new AbortController,vt=ye.current?.(At.signal).then(pn=>{At.signal.aborted||ro.current!==Pt||!pn?.feeEstimate||(Ht.current={scope:Pt,at:Date.now(),feeEstimate:pn.feeEstimate,sourceGasSkim:pn.sourceGasSkim})}).catch(pn=>{At.signal.aborted||console.debug("[SpiceSupply] fee prewarm unavailable:",pn)})??Promise.resolve();qt.current={scope:Pt,at:Date.now(),controller:At,promise:vt},await vt;return}const bt=mt;oe||(Pe(null),ee(!0));try{if(qt.current?.scope===Pt&&await qt.current.promise,Ut.aborted||!lt())return;const it=Ht.current,At=!x&&it?.scope===Pt&&Date.now()-it.at<3e4?it:void 0;let vt;try{vt=await ye.current?.(Ut,At?{initialFeeEstimate:At.feeEstimate,initialSourceGasSkim:At.sourceGasSkim}:void 0)}catch(pn){if(!At||Ut.aborted||!lt())throw pn;vt=await ye.current?.(Ut)}if(!lt())return;vt&&bt?(Xe.current={key:bt,quote:vt},vt.feeEstimate&&(Ht.current={scope:Pt,at:Date.now(),feeEstimate:vt.feeEstimate,sourceGasSkim:vt.sourceGasSkim}),Me(vt.preview),Ce(!0)):(Xe.current=null,Me(null),Ce(!1)),Pe(null)}catch(it){if(!lt())return;if(oe&&Xe.current?.key===bt){console.warn("[SpiceSupply] fee refresh failed:",it);return}const At=Mn(it,"Unable to calculate fees for this action.");Xe.current=null,Me(it instanceof _l?it.preview:null),Ce(!1),Pe(At)}finally{lt()&&ee(!1)}}});const Ro=te(()=>kn.current?(kn.current=!1,Yn.current?.(),Wt.current=Te.current.onSuccess,An.current={key:Cn.current.key,quote:Te.current.feeQuote},rc(Te.current)):Promise.resolve(),[]);ae(()=>{if(!Jt||Nt.current===Jt)return;Nt.current=Jt;const oe=Wt.current;wt.current=!0,jt(!0),Pn(null),Promise.resolve().then(()=>oe?.(Jt)).then(()=>{Gn(Jt),ie(),ke()}).catch(lt=>{Pn(`Transaction confirmed; application update needs retry: ${Mn(lt,"Unable to finalize the action")}`)}).finally(()=>{wt.current=!1,jt(!1)})},[Jt,Kt]);const Mo=Zt&&!wn,Zs=te(()=>{!on.current||wt.current||(Nt.current=null,ln(oe=>oe+1))},[]),Xs=te(()=>{on.current||(ut(!1),ft(null),q.current=!1,ie(),ke())},[ie,ke]),Xt=mt&&Xe.current?.key===mt?Xe.current.quote:null,Js=(oe=!0)=>{if(xe)throw new Error(xe);if(!Cn.current.enabled||Cn.current.key!==Yt)throw new Error("The source, amount, beneficiary or configuration changed. Review the form before continuing.");if((B||e.feeOnlyAction)&&!Xt)throw new Error("A current action plan is required. Refresh the quote before submitting.");if(pe&&B?.asset.owner&&!ge(B.asset.owner,Y))throw new Error("Reconnect the external wallet that owns the selected asset.");if(oe&&B&&(Xt?.sourceSpendCap??0n)>Cn.current.sourceBalance)throw new Error("The source balance changed. Review the available amount before continuing.");if(oe&&B&&!Cn.current.sourceEligible)throw new Error(ht?.reason??"This source is unavailable.")},Wo=async()=>Js(),ga=oe=>({...oe,sourceSpendCap:Xt?.sourceSpendCap,minimumDestinationAmount:Xt?.destinationAmount}),rs=B&&Xt?.sourceSpendCap!==void 0?Xt.sourceSpendCap>Ve:rn,ya={...Gt,resolvedSwap:Xt?.destinationSwap??Gt.resolvedSwap,swapInputAmount:Xt?.swapInputAmount??Gt.swapInputAmount};let $s=!1;Te.current={selectedAsset:B,parsedAmount:_e,currentPaymentAmount:s,isInsufficientBalance:rs,isPayMode:x,isFeeInclusiveInput:v,feeOnlyAction:e.feeOnlyAction,actionProceeds:e.actionProceeds==="output"?void 0:e.actionProceeds,validateFeeQuote:()=>Js(!$s),isNon7702:I,directExternalAction:pe,isSourceDestToken:X,needsSwap:hn,exactOutputSwap:en,selectedIsEquivalent:Oo,resolvedTokenIn:pt,sourceSwap:se,sourceExactOutputSwap:he,pivot:ve,embeddedWalletAddress:V,providerEmbeddedAddress:re,externalWallet:ne,externalWalletAddress:Y,activeSignerWallet:j,activeSignerAddress:J,address:N,isConnected:D,ready:L,authenticated:z,provider:fe,resolvedChainId:b,executionTokenAddress:tn,destinationToken:y,buildActionCalls:i,feeExecutionMode:l,feeToleranceBps:T,buildSpicenetBatch:c,onPayExecute:d,onSuccess:h,feeQuote:Xt,execution:{estimate:(oe,lt,Ut,bt)=>Q(oe,lt,Ut,{...bt,userOverride:st}),execute:async(oe,lt,Ut,bt,it,At)=>{const vt=async()=>Js(!$s);if(await Wo(),pe){if(!Xt?.actionDefinition)throw new Error("The direct action plan is unavailable.");return lf({definition:Xt.actionDefinition,account:Y,chainId:y.chainId,wallet:ne,assertCurrent:Wo})}return de&&B&&(ct("Transfer the selected source to your embedded wallet"),await ac({asset:B.asset,embedded:st,external:Y,externalWallet:ne,amount:Xt?.sourceSpendCap??0n,assertCurrent:Wo}),$s=!0,await vt()),ce(oe,lt,Ut,bt,it,{...At,userOverride:st,requireDestinationReceipt:!0,walletFundingRequirement:B?.asset._source==="wallet"&&Xt?.sourceSpendCap!==void 0?{chainId:B.asset.chainId,token:B.asset.address,amount:Xt.sourceSpendCap}:void 0,validateBeforeSubmit:async pn=>{await vt(),await At?.validateBeforeSubmit?.(pn)}})},buildPayChainBatches:oe=>Qs(ya,ga(oe)),buildSupplyChainBatches:oe=>js(ya,ga(oe)),onProgress:un},ui:{setError:gt,setStep:et,setStatusMsg:ct,setTxHash:dt,setIsExecuting:at,setShowStatusPanel:ut,setPaymentResult:ft},refs:{spiceDepositSubmittedRef:q,abortControllerRef:Ze}};const xo=!!e.isZeroAmountPay&&!e.feeOnlyAction&&x&&_e===0,Tc=x?(xo||!!B?.asset||!!e.actionProceeds||!!e.feeOnlyAction)&&_e>=0&&!rs&&!Qe&&(xo||H||ze)&&!le&&(xo||e.feeOnlyAction||!hn||!!en)&&(xo||e.feeOnlyAction||!ve||!!he)&&!we:!!B?.asset&&_e>0&&!rs&&!Qe&&(pe||ze)&&!le&&!He&&(ve?!!se&&!cn&&(Un||!!We):St||Un||!!We&&!cn)&&!we,xa=!xe&&!!st&&(!pe||!!ne&&(!B?.asset.owner||ge(B.asset.owner,Y)))&&(E==="7702"||!!Y)&&!Zt&&!bn&&!wn&&w&&Tc&&(xo||!B&&(!!e.actionProceeds||!!e.feeOnlyAction)||!!ht?.eligible)&&De!=="success"&&Re?.status!=="success"&&!_t.quoteError&&(xo||!!mt&&Xe.current?.key===mt);kn.current=xa;const _s=te(()=>{on.current||(kn.current=!1,Xe.current=null,Ce(!1),vn.refreshQuote(),et("idle"),gt(null),ct(""),ft(null),ut(!1))},[vn.refreshQuote,gt]),wa=_(Yt);ae(()=>{const oe=wa.current!==Yt;wa.current=Yt,(oe||Ea(je))&&De==="error"&&!Qe&&An.current&&An.current.key!==Yt&&_s()},[Yt,De,Qe,je,_s]);const Bc=te(()=>{ut(!1)},[]),Dc=te(()=>{on.current||(et("idle"),dt(null),ie())},[ie]),Rt=Xt??(Xe.current?.key.startsWith(`${Yt}|`)?Xe.current.quote:null)??(An.current?.key===Yt?An.current.quote:null),Oc=async oe=>{if(pe)throw new Error("This source executes directly from the external wallet; submit the action without embedded funding.");if(!(!de||!B)){if(!Xt||oe!==Xt.sourceSpendCap)throw new Error("Use the displayed source funding maximum before preparing this action.");await Wo(),await ac({asset:B.asset,embedded:st,external:Y,externalWallet:ne,amount:oe,assertCurrent:Wo})}};return{selectedAsset:Ct,capability:ht,assets:{selectable:Z,displayAssets:Z,filteredSpiceAssets:G,embeddedWalletAddress:V,externalAddress:Y,isNon7702:E!=="7702",refreshSpiceAssets:ie,refreshWalletAssets:ke,loading:Ee,refreshing:Be,error:Ie},quote:{..._t,...Je?{quoteKey:null,quoteExpiresAt:null,quoteError:null,isQuoting:!1,estimatedInput:null,estimatedOutput:null,quoteAmountOut:null,inputAmount:null,resolvedSwap:null,sourceSwap:null,exactOutputSwap:null,sourceExactOutputSwap:null}:{},hasSourceConversion:!!ve,executionInput:ve&&Rt?{address:ve.destination.address,chainId:ve.destination.chainId,decimals:ve.destination.decimals,amount:Rt.preview.netAmount}:null,...Rt?.destinationSwap?{resolvedSwap:Rt.destinationSwap,inputAmount:Rt.swapInputAmount,estimatedOutput:Fe(Rt.destinationSwap.amountOut,y.decimals)}:{},...Rt?.fundedFeeToken&&Rt.destinationAmount!==void 0?{estimatedOutput:Fe(Rt.destinationAmount+(Rt.destinationSwap?Rt.destinationSwap.amountOut-Rt.destinationSwap.amountOutMinimum:0n),y.decimals)}:{}},fees:{fundingConversion:Rt?.fundingConversion,fundingSource:Rt?.fundingSource,proceedsUsed:Rt?.proceedsUsed,fundingShortfall:Rt?.grossFundingAmount,source:ve&&Rt?{address:ve.source.address,chainId:ve.source.chainId,symbol:ve.source.symbol,decimals:ve.source.decimals,gasFee:Rt.sourceGasSkim??0n,spicenetFee:0n}:null,destinationAmount:Rt?.destinationAmount,sourceSpendCap:Rt?.sourceSpendCap,preview:Je?null:Rt?.preview??Ot,isLoading:!Je&&$,ready:!Je&&!!Xt,error:Je?null:le},amount:{sourceRequiredAmount:Rt?.sourceSpendCap??null,parsed:_e,isInsufficientBalance:rs,sourceBalance:sn,feesExceedAmount:He},status:{finalizing:bn||Mo,finalizationError:wn,step:Zt&&De==="success"?"executing":De,statusMsg:Zt?wn??"Transaction confirmed. Updating application...":Le,txHash:$e,isExecuting:Qe||Mo,error:xe||wn||je||ht?.reason||null,showStatusPanel:kt,paymentResult:Zt&&Re?.status==="success"?{...Re,status:"processing"}:Re},flags:{directExecutionFeeNote:H},retryFinalization:Zs,fundEmbeddedSource:Oc,canExecute:xa,submit:x?Ro:yo,submitSupply:yo,submitPay:Ro,retrySupply:_s,dismissPaymentStatus:Bc,resolveMaxAmount:Kn,max:()=>B?Kn(B.asset):Promise.resolve(null),resetAfterSuccess:Dc,resetPaymentState:Xs}}function mf(e){const{asset:t,amount:n,recipient:o,owner:s,onSuccess:r}=e,a=t?.chainId??e.sourceChains?.[0]??0,i=ue(()=>gs(a).find(y=>y.equivalenceGroup==="USDC"),[a]),l=te((y,w)=>{if(!t||n<=0n||n>t.balance||!o||!s||ge(s,o))throw new Error("Enter a valid withdrawal amount and recipient.");if(w.chainId!==t.chainId||!ge(w.executorAddress??w.userAddress,s))throw new Error("The withdrawal wallet or network changed. Review the withdrawal again.");return Rl(t.chainId,t.address,[{recipient:o,amount:n}]).calls},[t?.address,t?.chainId,t?.balance,n,o,s]),c=ue(()=>t?{asset:t,amount:n}:void 0,[t,n]),d=ue(()=>t?[{address:t.address,chainId:t.chainId,symbol:t.symbol,decimals:t.decimals,logoURI:t.logoURI}]:void 0,[t?.address,t?.chainId,t?.symbol,t?.decimals,t?.logoURI]),p=os({enabled:e.enabled&&!!i&&!!t&&n>0n&&!!o&&!!s&&!ge(s,o),feeOnlyAction:!0,isZeroAmountPay:!0,amountDirection:"output",paymentAmount:"0",destinationToken:{address:i?.address??Tt,symbol:i?.symbol??"USDC",decimals:i?.decimals??6,chainId:a},recipient:o,selectedAsset:null,feeFundingReserve:c,additionalSourceTokens:d,sourceChains:e.sourceChains,includeCrossChainEmbeddedAssets:!0,includeExternalWalletAssets:!1,feeExecutionMode:"backend-transfer",buildActionCalls:l,buildSpicenetBatch:Hs,onError:(y,w)=>e.onError?.(y.message,w),onSuccess:async()=>{t&&(window.dispatchEvent(new CustomEvent("withdraw-completed")),await r?.({token:t.symbol,amount:Fe(n,t.decimals),chainId:a}))}}),f=`${e.enabled}:${t?.chainId}:${t?.address}:${n}:${o}`,h=_(f);ae(()=>{h.current===f||p.status.isExecuting||(h.current=f,(p.status.step==="success"||p.status.paymentResult?.status==="success")&&p.resetAfterSuccess())},[f,p.status.isExecuting,p.status.step,p.status.paymentResult?.status,p.resetAfterSuccess]);const m=p.fees.fundingSource?.asset,g=m?m._source==="wallet"?p.fees.fundingConversion?.amountInMax??p.fees.proceedsUsed:p.amount.sourceRequiredAmount:null;return{supply:p,source:m,maximumFeeFunding:g}}const mc=Oe.ui,hf=({label:e,loading:t,balance:n,dark:o,dk:s})=>{const r=o?s.textSecondary:"#7D7C7B",a=o?s.textSecondary:"#71757A";return C("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[u("span",{style:{fontFamily:mc,fontSize:"17px",fontWeight:500,color:r,lineHeight:"24px"},children:e}),C("div",{style:{display:"flex",alignItems:"center",gap:"6px",fontFamily:mc,fontSize:"13px",fontWeight:500,color:a,lineHeight:"16px"},children:["Balance:"," ",t?"...":n===null?"\u2014":rr(n)]})]})},hc=({isOpen:e,position:t,title:n,items:o,selectedId:s,onSelect:r,portalAttribute:a})=>{const{dark:i,dk:l,primaryColor:c}=Bt(),[d,p]=O(null),[f,h]=O(!1);return ae(()=>{if(!e){h(!1);return}const m=requestAnimationFrame(()=>{requestAnimationFrame(()=>h(!0))});return()=>cancelAnimationFrame(m)},[e]),!e||!t||o.length===0?null:fr(C("div",{[`data-${a}-popover`]:"true",style:{position:"fixed",top:`${t.top}px`,left:`${t.left}px`,opacity:f?1:0,transform:f?"scale(1) translateY(0)":"scale(0.96) translateY(-6px)",transition:`opacity 200ms ${wo.out}, transform 200ms ${wo.out}`,backgroundColor:i?l.shell:"#ffffff",borderRadius:"10px",padding:"10px 12px",boxShadow:i?"0 16px 48px rgba(0,0,0,0.45)":"0 12px 32px rgba(0,0,0,0.12)",border:`1px solid ${l.cardBorder}`,minWidth:"220px",zIndex:ao.dropdown,fontFamily:Oe.mono},children:[u("div",{style:{marginBottom:"6px"},children:u("span",{style:{fontSize:"11px",fontWeight:500,color:i?l.textPrimary:"#0e0d0b",textTransform:"uppercase",letterSpacing:"1px"},children:n})}),u("div",{style:{borderBottom:`1px solid ${l.cardBorder}`,marginBottom:"6px"}}),u("div",{style:{display:"flex",flexDirection:"column",gap:"2px"},children:o.map(m=>{const g=s===m.id,y=d===m.id;return C("button",{onClick:w=>{w.stopPropagation(),r(m.id)},onMouseEnter:()=>p(m.id),onMouseLeave:()=>p(null),style:{display:"flex",alignItems:"center",gap:"8px",padding:"6px 4px",borderRadius:"8px",border:"none",cursor:"pointer",backgroundColor:g?i?l.hoverBg:"#f3f4f6":y?i?l.cardBg:"#f9fafb":"transparent",transition:"background-color 0.15s",width:"100%",fontFamily:Oe.mono},children:[m.icon&&u("img",{src:m.icon,alt:m.label,style:{width:"22px",height:"22px",borderRadius:"50%"}}),u("span",{style:{fontSize:"13px",fontWeight:g?700:500,textTransform:"uppercase",color:i?l.textPrimary:"#0e0d0b",letterSpacing:"0.5px",flex:1,textAlign:"left"},children:m.label}),m.detail&&u("span",{style:{fontSize:"11px",fontWeight:500,color:l.textSecondary},children:m.detail}),g&&u(al,{color:c,style:{flexShrink:0}})]},m.id)})})]}),document.body)},Ys=Oe.ui,gf=Oe.mono,yf=170,xf=({header:e,amount:t,receiveAmountDisplay:n,receiveUsdEstimate:o,selectedDestToken:s,destTokenSymbol:r,destChainName:a,destChainLogo:i,compatibleDestinationChains:l,networkSwitchRef:c,onOpenNetworkPopover:d,showNetworkPopover:p,setShowNetworkPopover:f,networkPopoverPos:h,selectedChainId:m,setSelectedChainId:g,dark:y,dk:w})=>{const x=y?w.cardBg:"#E9E9E9",v=y?w.cardBorder:"#C6C6C6",k=y?w.textSecondary:"#71757A",A=y?w.textPrimary:"#0E0D0B",b=y?w.cardBorder:"#C5C5C4",S=y?"rgba(255,255,255,0.08)":"#D4D3D3",T=r.length>8?"14px":r.length>6?"16px":"18px";return C("div",{style:{backgroundColor:x,border:`1px solid ${v}`,borderRadius:"7px",padding:"14px 16px 12px 16px",minHeight:"138px",display:"flex",flexDirection:"column",gap:"6px"},children:[e,C("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[C("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[u(fo,{element:"div",value:n,title:n,fontFamily:Ys,color:t?A:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,overflow:"wrap"}),u("div",{style:{fontSize:"12px",fontWeight:500,color:k,fontFamily:Ys,marginTop:"10px"},children:o})]}),C("div",{style:{width:`${yf}px`,flexShrink:0,display:"flex",flexDirection:"column",alignItems:"stretch",gap:"8px"},children:[C("div",{style:{backgroundColor:"transparent",border:`1px solid ${b}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[C("div",{style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px"},children:[u("img",{src:s?.logoURI||Kd,alt:r,style:{width:"24px",height:"24px",borderRadius:"50%"}}),u("span",{style:{fontSize:T,fontWeight:500,color:A,lineHeight:"1.3",fontFamily:Ys,flex:1,minWidth:0,letterSpacing:0},children:r})]}),C("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:S,borderTop:`1px solid ${b}`},children:[C("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[i&&u("img",{src:i,alt:a,style:{width:"13px",height:"13px",borderRadius:"50%",flexShrink:0}}),u("span",{style:{fontSize:"11px",fontWeight:400,color:A,fontFamily:Ys,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:a})]}),u("button",{ref:c,onClick:E=>{E.stopPropagation(),d(c.current)},style:{background:"none",border:"none",cursor:l.length>1?"pointer":"not-allowed",padding:"0 0 0 8px",fontSize:"9.5px",fontFamily:gf,color:k,textDecoration:"underline",fontWeight:600,opacity:l.length>1?1:.45},children:"Switch"}),u(hc,{isOpen:p,position:h,title:"SELECT NETWORK",portalAttribute:"network",items:l.map(E=>{const I=Ge(E);return{id:String(E),label:I?.displayName||String(E),icon:to[E]||Qo}}),selectedId:m!==null?String(m):null,onSelect:E=>{g(Number(E)),f(!1)}})]})]}),u("div",{style:{minHeight:"14px"}})]})]})]})},wf=Oe.ui,so=Oe.mono,bf=({show:e,onToggle:t,showCustomAddress:n,setShowCustomAddress:o,customRecipient:s,setCustomRecipient:r,externalAddress:a,recipientAddress:i,destChainName:l,destChainLogo:c,compatibleDestinationChains:d,txDetailsChainSwitchRef:p,onOpenNetworkPopover:f,sourceChainLabel:h,sourceDetailsLogo:m,sourceTokenLabel:g,amount:y,totalSourceDebitDisplay:w,receiveAmountDisplay:x,destTokenSymbol:v,shouldQuoteWithdrawGas:k,estimatingFee:A,feeError:b,displayedGasFee:S,selectedDestToken:T,theme:E,styles:I,dark:M,dk:W})=>{const R=M?W.textSecondary:"#71757A",F=M?W.textPrimary:"#0E0D0B",N=d.length>1,D=n&&s?fn(s)?Po(s):s:i?Po(i):"\u2014";return C(an,{children:[C("div",{onClick:t,style:{display:"flex",alignItems:"center",gap:"6px",marginBottom:e?"10px":"0",cursor:"pointer",userSelect:"none"},children:[u("span",{style:{fontSize:"13px",color:R,fontFamily:wf,fontWeight:600},children:"Transaction Details"}),u($u,{size:12,color:R,style:{transform:e?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s"}})]}),e&&C("div",{style:{display:"flex",flexDirection:"column",gap:"7px"},children:[C("div",{children:[C("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[u("span",{style:{fontSize:"12px",color:R,fontFamily:so,fontWeight:500,letterSpacing:"0.03em"},children:"TO"}),C("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[u("span",{style:{fontSize:"13px",color:F,fontFamily:so,fontWeight:500},children:D}),u("button",{onClick:()=>{o(L=>!L),!n&&a&&r(a)},style:{background:"none",border:"none",cursor:"pointer",padding:"0",fontSize:"9.5px",fontFamily:so,color:R,textDecoration:"underline",fontWeight:600},children:n?"Reset":"Switch"})]})]}),n&&C("div",{style:{marginTop:"6px"},children:[u("div",{style:{marginBottom:"6px",padding:"7px 9px",borderRadius:"6px",border:"1px solid rgba(239, 68, 68, 0.55)",backgroundColor:"rgba(239, 68, 68, 0.12)",color:"#ef4444",fontSize:"10px",lineHeight:1.35,fontFamily:so,fontWeight:700,letterSpacing:0,textTransform:"uppercase"},children:"CAUTION: ENTERING AN INCORRECT ADDRESS WILL RESULT IN LOSS OF FUNDS"}),u("input",{type:"text",autoComplete:"off",spellCheck:!1,"aria-label":"Recipient address","aria-invalid":s&&!fn(s)?!0:void 0,"data-spiceflow-focus":!0,value:s,onChange:L=>r(L.target.value),placeholder:"0x...",style:{width:"100%",padding:"8px 10px",borderRadius:"6px",border:`1px solid ${s&&!fn(s)?M?W.errorBorder:"#fca5a5":M?W.inputBorder:"#d1d5db"}`,backgroundColor:M?W.inputBg:"#f9fafb",color:M?W.inputText:"#111827",fontSize:"12px",fontFamily:so,outline:"none",boxSizing:"border-box"}}),s&&!fn(s)&&u("span",{style:{fontSize:"11px",color:W.errorText,marginTop:"3px",display:"block"},children:"Invalid address"})]})]}),u(oo,{palette:W,labelColor:R,valueColor:F,label:"RECEIVING CHAIN",value:C("div",{style:{display:"flex",alignItems:"center",gap:"7px"},children:[c&&u("img",{src:c,alt:l,style:{width:"14px",height:"14px",borderRadius:"50%"}}),u("span",{style:{fontSize:"13px",color:F,fontWeight:500,fontFamily:so,textTransform:"uppercase"},children:l}),u("button",{ref:p,onClick:L=>{L.stopPropagation(),f(p.current)},style:{background:"none",border:"none",cursor:N?"pointer":"not-allowed",padding:"0",fontSize:"9.5px",fontFamily:so,color:R,textDecoration:"underline",fontWeight:600,opacity:N?1:.45},children:"Switch"})]})}),u(oo,{palette:W,labelColor:R,valueColor:F,label:"REQUESTED WITHDRAWAL",value:C(pa,{logo:m||null,alt:h,primaryText:F,children:[y||"0"," ",g]})}),k&&u(oo,{palette:W,labelColor:R,valueColor:F,label:"TOTAL SOURCE DEBIT",value:C(pa,{logo:m||null,alt:h,primaryText:F,children:[w," ",g]})}),u(oo,{palette:W,labelColor:R,valueColor:F,label:"YOU RECEIVE",value:C(pa,{logo:c,alt:l,primaryText:F,gap:"4px",children:[x," ",v]})}),k&&C(an,{children:[u(oo,{palette:W,labelColor:R,label:"EST. NETWORK FEE",valueColor:b?"#f87171":F,value:A?"Estimating...":b?"Unavailable":S!==null&&T?`${na(S,T.decimals)} ${T.symbol}`:"Estimating..."}),b&&u(Nn,{variant:"error",size:"compact",palette:W,fontFamily:I?.fontFamily||E.typography.fontFamily,children:b})]})]})]})},vf=yn(bf),pa=({logo:e,alt:t,primaryText:n,gap:o="6px",children:s})=>C("div",{style:{display:"flex",alignItems:"center",gap:o},children:[e&&u("img",{src:e,alt:t,style:{width:"13px",height:"13px",borderRadius:"50%"}}),u("span",{style:{fontSize:"13px",color:n,fontWeight:500,fontFamily:so},children:s})]}),ss=Oe.ui,Cf=170,kf=({header:e,amount:t,setAmount:n,isInsufficient:o,sourceAmountDecimals:s,selectedSourceAsset:r,resolvedSelectedSourceAsset:a,spiceAssets:i,setSelectedSourceAsset:l,sourceUsdEstimate:c,sourceTokenLabel:d,sourceChainLabel:p,totalSelectedBalance:f,showSourceTokenPopover:h,setShowSourceTokenPopover:m,tokenPopoverPos:g,setTokenPopoverPos:y,tokenTriggerRef:w,primaryColor:x,dark:v,dk:k})=>{const A=Rn(),b=a?A({...a,logoURI:Vo}).logoURI:Vo,S=v?k.cardBg:"#E9E9E9",T=v?k.cardBorder:"#C6C6C6",E=v?k.textSecondary:"#71757A",I=v?k.textPrimary:"#0E0D0B",M=v?k.cardBorder:"#C5C5C4",W=v?"rgba(255,255,255,0.08)":"#D4D3D3",R=d.length>8?"14px":d.length>6?"16px":"18px";return C("div",{style:{backgroundColor:S,border:`1px solid ${T}`,borderRadius:"7px",padding:"14px 16px 12px 16px",minHeight:"138px",display:"flex",flexDirection:"column",gap:"6px",position:"relative"},children:[e,C("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[C("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[u(fo,{element:"input",ariaLabel:"Withdraw amount",ariaInvalid:o,dataSpiceflowFocus:!0,value:t,onChange:F=>{const N=F.target.value;if(N===""){n("");return}/^\d*\.?\d*$/.test(N)&&n(ds(N.startsWith(".")?`0${N}`:N,s??r?.decimals))},placeholder:"0.0",fontFamily:ss,color:o?"#ef4444":t?I:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,style:{width:"100%"}}),u("div",{style:{fontSize:"12px",fontWeight:500,color:E,fontFamily:ss,marginTop:"10px"},children:c})]}),u("div",{style:{width:`${Cf}px`,flexShrink:0},children:C("div",{style:{backgroundColor:"transparent",border:`1px solid ${M}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[C("div",{ref:w,onClick:F=>{if(F.stopPropagation(),!h&&w.current){const N=w.current.getBoundingClientRect(),D=220,L=16;y({top:N.bottom+8,left:Math.min(Math.max(L,N.right-D),window.innerWidth-D-L)})}m(N=>!N)},style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px",cursor:"pointer"},children:[b&&u("img",{src:b,alt:d,style:{width:"24px",height:"24px",borderRadius:"50%"}}),u("span",{style:{fontSize:R,fontWeight:500,color:I,lineHeight:"1.3",fontFamily:ss,flex:1,minWidth:0,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",letterSpacing:0},children:d}),u(Eo,{size:15,color:I,strokeWidth:2.25})]}),u(hc,{isOpen:h,position:g,title:"SELECT TOKEN",portalAttribute:"token",items:(i||[]).map(F=>({id:F.receiptTokenId||F.address,label:A({...F,displaySymbol:F.displaySymbol||F.receiptTokenName}).symbol,icon:A({...F,logoURI:Vo}).logoURI||void 0,detail:rr(F.balanceFormatted)})),selectedId:a?.receiptTokenId||a?.address||null,onSelect:F=>{const N=(i||[]).find(D=>(D.receiptTokenId||D.address)===F);N&&(l(N),n("")),m(!1)}}),u("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:W,borderTop:`1px solid ${M}`},children:u("span",{style:{fontSize:"11px",fontWeight:400,color:I,fontFamily:ss,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:p})})]})})]}),C("div",{style:{minHeight:"18px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[o?u("span",{style:{fontSize:"12px",color:k.errorText,fontFamily:ss,fontWeight:500},children:"Insufficient Balance"}):u("span",{}),u("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0px",minHeight:"32px",marginRight:"-9px"},children:[0,25,50,75,100].map((F,N)=>{const D=N===4,L=parseFloat(t)||0,z=f>0&&Math.abs(L/f*100-F)<1;return u("button",{type:"button","aria-label":`Set amount to ${F}%`,"aria-pressed":z,onClick:()=>{const fe=f*F/100,ce=r?.decimals??6,Q=Math.floor(fe*10**ce)/10**ce;n(F===0?"":Q>0?Fa(Q,ce):"")},title:`${F}%`,disabled:f===0,"data-spiceflow-focus":!0,style:{width:"32px",height:"32px",padding:"9px",border:"none",backgroundColor:"transparent",cursor:f===0?"not-allowed":"pointer",opacity:z?1:.5,transition:"opacity 0.15s ease",display:"flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box"},children:u(Jr,{pct:F,isMax:D,primaryColor:x,dark:v,fillColor:v?k.textSecondary:"#3C3E42"})},F)})})]})]})},If=({dark:e,dk:t})=>C("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[u("img",{src:zr,alt:"","aria-hidden":"true",style:{width:"13px",height:"13px",flexShrink:0,...e?{filter:"invert(0.6)"}:{}}}),u("p",{style:{fontSize:"13px",color:e?t.textSecondary:"#979AA0",margin:"0",lineHeight:"1.4",fontFamily:Oe.ui},children:"Withdraw collateral from your account to 10+ EVM blockchains."})]}),Sf=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,styles:o,onWithdrawExecute:s,onWithdrawSuccess:r,onWithdrawError:a,availableTokens:i,initialSourceAssetId:l,walletAssets:c,buildSpicenetBatch:d=Hs})=>{const p=Qt(Mt);if(!p)return u("div",{children:"Error: SpiceWithdraw must be used within SpiceFlowProvider"});const f=p.mode||"7702",h=f==="presign"||f==="ondemand",m=p.supportedChainIds,g=p.allowedTokens,y=!!c,w=c?.initialAsset,x=ue(()=>[...c?.extraAssets??[],...w?[w]:[]].map(se=>({address:se.address,chainId:se.chainId,symbol:se.symbol,decimals:se.decimals})),[c?.extraAssets,w]),v=p.isWhitelistGateActive,{theme:k,dark:A,dk:b}=Bt(o),S=Rn(),T=p.network,E=()=>h?"select":"provider-login",[I,M]=O(E()),[W,R]=O(!1),[F,N]=O(null),[D,L]=O(null),[z,fe]=O(""),[ce,Q]=O(!1),[ne,re]=O(!1),[j,J]=O(!1),[Y,me]=O(""),[B,U]=O(!0),X=_(null),pe=_(null),de=_(null),[xe,K]=O(null),[G,P]=O(null),V=Zn(),{isReady:ie,isAuthenticated:ke,address:Ee}=V,Be=p?.embeddedWalletAddress,{address:Ie,chainId:Z}=ir(),ot=p.externalWalletAddress||Ie,[qe,Ct]=O(!1),[ht,Ve]=O(null),Qe=_(a);Qe.current=a;const at=te(se=>{Ve(se),typeof se=="string"&&se&&Qe.current?.(se,fs(se))},[]),[je,Dt]=O(null),Ke=_(null),gt=_(!0),De=_(null);ae(()=>(gt.current=!0,()=>{gt.current=!1}),[]);const{execute:et,estimate:Le}=Ms(),[ct,$e]=O(null),[dt,kt]=O(null),[ut,Re]=O(!1),[ft,Ot]=O(null),{assets:Me,loading:$,error:ee,refresh:ze}=Ao({owner:Be,role:"holding",includeWalletAssets:y,additionalSourceTokens:x,enabled:e&&!!Be}),Ce=ue(()=>{if(v)return[];const se=(he,ve)=>(ve.balanceUsd||0)-(he.balanceUsd||0);return(Me??[]).filter(he=>he.balance>0n&&po(he,"holding",{allowedTokens:g,isWhitelistGateActive:v}).eligible).sort(se)},[Me,g,v]),le=ue(()=>[...new Set([...m??[],...Object.keys(i??{}).map(Number),...(Ce||[]).map(se=>se.chainId),...(Ce||[]).flatMap(se=>Object.keys(se.chainTokens??{}).map(he=>{const[,ve]=he.split(":"),_e=Number(ve);return Number.isFinite(_e)?_e:null}).filter(he=>he!==null))])].filter(se=>Ge(se)?.network===T),[m,i,Ce,T]),Pe=ue(()=>{if(i)return i;const se={};for(const he of Ce||[]){const ve=Object.entries(he.chainTokens??{});if(ve.length>0){for(const[_e,Vt]of ve){const[St,sn,rn]=_e.split(":");if(St!=="evm"||!sn||!rn)continue;const un=Number(sn);if(!Number.isFinite(un))continue;const Gt=rn.startsWith("0x")?rn.toLowerCase():`0x${rn.toLowerCase()}`,tn=Ge(un)?.supportedTokens?.find(Pt=>ge(Pt.address,Gt));tn&&Fr(he,Gt,un)&&(se[un]||(se[un]=[]),se[un].find(Pt=>ge(Pt.address,Gt))||se[un].push({address:Gt,symbol:tn?.symbol||Vt?.name||he.symbol,name:tn?.name||Vt?.name||he.displayName||he.name||he.symbol,decimals:tn?.decimals??Vt?.decimals??he.decimals,logoURI:tn?.logo||he.logoURI}))}continue}se[he.chainId]||(se[he.chainId]=[]),se[he.chainId].find(_e=>ge(_e.address,he.address))||se[he.chainId].push({address:he.address,symbol:he.symbol,name:he.displayName||he.name||he.symbol,decimals:he.decimals,logoURI:he.logoURI})}return se},[i,Ce]),Ae=te((se,he)=>{const ve=Ap(se,he,he?Pe[he]??[]:[]);return!se||!ve||!he||se._source==="wallet"&&he!==se.chainId?null:po(se,"withdraw-destination",p,{...ve,chainId:he}).eligible?ve:null},[Pe,p.allowedTokens,p.rpcOverrides,p.isWhitelistGateActive]),q=ue(()=>F?Ce.find(se=>nt(se)===nt(F))??null:null,[F,Ce]),Ze=q?q.balanceError:ee,ye=q?._source==="wallet",Xe=ue(()=>{if(!q)return[];const se=Object.keys(q.chainTokens??{}).map(he=>qn(he)?.chainId??null).filter(he=>he!==null);return Array.from(new Set([...se,q.chainId,...le].filter(Number.isFinite))).filter(he=>Ge(he)?.network===T&&Ae(q,he)!==null)},[q,le,Ae,T]),Ht=ue(()=>{if(!q||typeof window>"u")return null;const se=`spiceflow:withdraw-chain:${q.receiptTokenId||q.address.toLowerCase()}`,he=window.localStorage.getItem(se),ve=he?Number(he):null;return ve!==null&&Number.isFinite(ve)&&Xe.includes(ve)?ve:null},[q,Xe]),qt=ue(()=>q?Ht!==null?Ht:Z&&Xe.includes(Z)?Z:q.chainId&&Xe.includes(q.chainId)?q.chainId:Xe[0]??null:le[0]??null,[q,Ht,Z,Xe,le]),Te=ue(()=>Ae(q,D),[Ae,q,D]);ae(()=>{e&&(N(null),fe(""))},[e,l,w?.address,w?.chainId]),ae(()=>{if(!e||!Ce.length||F)return;const se=w?Ce.find(he=>he.chainId===w.chainId&&ge(he.address,w.address)&&he._source==="wallet"):l?Ce.find(he=>he.receiptTokenId===l):Ce[0];N(se??null),fe("")},[e,Ce,F,l,w]),ae(()=>{q&&(D===null||!Xe.includes(D))&&L(qt)},[q,D,qt,Xe]),ae(()=>{if(!ce&&!ne)return;const se=he=>{const ve=he.target;ce&&!X.current?.contains(ve)&&!pe.current?.contains(ve)&&!ve?.closest?.("[data-network-popover]")&&Q(!1),ne&&!de.current?.contains(ve)&&!ve?.closest?.("[data-token-popover]")&&re(!1)};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[ce,ne]);const Wt=te(se=>{if(!se||Xe.length<=1)return;const he=se.getBoundingClientRect(),ve=220,_e=16;K({top:he.bottom+8,left:Math.min(Math.max(_e,he.right-ve),window.innerWidth-ve-_e)}),Q(Vt=>!Vt)},[Xe.length]),Nt=te(()=>U(se=>!se),[]);ae(()=>{if(!q||D===null||typeof window>"u")return;const se=`spiceflow:withdraw-chain:${q.receiptTokenId||q.address.toLowerCase()}`;window.localStorage.setItem(se,String(D))},[q,D]);const wt=j?fn(Y)?Y:void 0:ot||(ye?void 0:Be),On=Ao({owner:wt,role:"holding",includeRollupAssets:!1,sourceChains:D?[D]:[],additionalSourceTokens:Te&&D?[{...Te,chainId:D}]:[],enabled:e&&!!wt&&!!Te&&!!D}),Gn=On.walletAssets.find(se=>ge(se.owner,wt)&&se.chainId===D&&ge(se.address,Te?.address)),wn=q?.balanceFormatted??0,Pn=q?S({...q,displaySymbol:q.displaySymbol||q.receiptTokenName}).symbol:"Select token",bn=q?.displayChainName||(ye?Ge(q.chainId)?.displayName:"Spicenet")||"Network",jt=q?.receiptTokenDecimals??q?.decimals,Kt=ue(()=>{if(!Te||jt===void 0)return 0n;try{return dn(z||"0",jt)}catch{return 0n}},[z,Te,jt]),ln=ue(()=>!Te||jt===void 0?0n:Mp(Kt,jt,Te.decimals),[Te,jt,Kt]),Jt=dt??ct,Zt=ue(()=>{const se=ye?0n:Jt??0n;return ln>se?ln-se:0n},[ye,Jt,ln]),on=Kt,st=mf({enabled:e&&ye,asset:ye?q:null,amount:Kt,recipient:wt,owner:Be,sourceChains:m,onSuccess:r,onError:a}),Je=st.supply,$t=qe||ye&&(Je.status.isExecuting||Je.status.finalizing),vn=Je.status.step==="success"||Je.status.paymentResult?.status==="success",_t=te(se=>{if(ye||!D||!Te)return[];if(Kt===0n||ln===0n||!wt)return[];const he=Array.isArray(se)?se.filter(St=>St.amount>0n):[{token:Te.address,recipient:wt,amount:se??ln}],ve=he.reduce((St,sn)=>St+sn.amount,0n);if(ve<=0n)return[];const _e={chainId:D,calls:[],tokenTransfers:he.map(St=>({from:"escrow",to:St.recipient,token:St.token,amount:St.amount}))},Vt=d({destinationChainId:D,deliveryToken:Te.address,deliveryAmount:ve,deliveryRecipient:wt,deliveryTransfers:he,requestTimestampMs:De.current??Date.now()});return Vt?[Vt,_e]:[_e]},[ye,D,Te,Kt,ln,wt,d]),Ue=ue(()=>_t(),[_t]),cn=ue(()=>Wp(Ue,Te?.address),[Ue,Te?.address]),We=_(null),en=!ye&&e&&!h&&!qe&&!!Te&&!!D&&Kt!==0n;Hr({shouldRun:en&&Ue.length>0&&!!cn,deps:[en,Ue.length>0,cn],delayMs:500,onSkip:()=>{We.current=null,$e(null),Ot(null),Re(en&&Ue.length===0)},onCleanup:()=>Re(!1),run:async({isCurrent:se,signal:he})=>{const ve=cn;Re(!0),Ot(null);try{const _e=await Rp({batches:Ue,tokenAddress:Te.address,chainId:D,estimate:Le,signal:he});if(!se())return;We.current={key:ve,quote:_e},$e(_e.gasFee)}catch(_e){if(!se())return;We.current=null,$e(null),Ot(_e instanceof Error?_e.message:"Failed to estimate gas fee")}finally{se()&&Re(!1)}}}),ae(()=>{qe||kt(null)},[qe,z,D,Te?.address]);const It=te(()=>{R(!0),M("select")},[]),pt=te(()=>{$t||t()},[t,$t]),Un=_(null);Un.current={batches:Ue,walletAddress:Ee,recipient:wt,token:Te,chainId:D,amount:z,grossAmountRaw:ln,gasFee:ct,feeEstimate:cn&&We.current?.key===cn?We.current.quote.feeEstimate:null,isNon7702:h,buildWithdrawBatches:_t,execution:{estimate:Le,execute:et},ui:{setIsExecuting:Ct,setExecutionError:at,setExecutionProgress:Dt,setLockedGasFee:kt},executionContextRef:Ke,isMountedRef:gt,onWithdrawExecute:s,onWithdrawSuccess:r,buildSpicenetBatch:d};const hn=te(()=>(De.current=Date.now(),Bl(Un.current)),[]),Oo=te(()=>(De.current=Date.now(),Op(Un.current)),[]);if(ae(()=>{if(!e){const se=setTimeout(()=>{M(E()),R(!1),N(null),L(null),fe(""),Q(!1),re(!1),J(!1),me(""),Ct(!1),at(null),Dt(null),Ke.current=null},300);return()=>clearTimeout(se)}},[e,h]),ae(()=>{if(!h&&e&&I==="provider-login"&&ie&&ke&&Be&&!W){const se=setTimeout(()=>{R(!0),M("select")},100);return()=>clearTimeout(se)}},[h,e,I,ie,ke,Be,W]),!e)return null;if(I==="provider-login"&&!h)return u(ea,{onAuthSuccess:It,autoTrigger:!0});if(I==="select"){const se=parseFloat(z)||0,he=jt?na(on,jt):z||"0",ve=!!q&&on>q.balance,_e=(D?Ge(D):null)?.displayName||"Network",Vt=D?to[D]||Qo:null,St=Te?.symbol||"\u2014",sn=Pn,rn=Te?na(Zt,Te.decimals):"0",un=q&&q.balanceFormatted>0?q.balanceUsd/q.balanceFormatted:void 0,Gt=q?.priceStatus==="stale",tn=Ol(se,un,Gt),Pt=Ol(parseFloat(rn)||0,un,Gt),ro=(!j||fn(Y))&&(!ye||!ge(wt,Be)),Yt=!h&&!ye&&se>0&&Te!==null,Cn=!Yt||ct!==null&&!ut&&!ft,An=se>0&&!ve&&!$&&!Ze&&q!==null&&D!==null&&Te!==null&&wt&&ro&&Cn&&Zt>0n&&(!ye||Je.canExecute&&!vn),kn=!An,Yn=$?"LOADING BALANCES":Ze?"BALANCES UNAVAILABLE":q===null?"NO BALANCE":se===0?"ENTER AMOUNT":ve?"INSUFFICIENT BALANCE":Yt&&!Cn?ft?"GAS UNAVAILABLE":"ESTIMATING GAS":Yt&&Zt===0n?"AMOUNT TOO SMALL":ye&&!Je.canExecute?"REVIEW FEES":"WITHDRAW",yo=!!je&&(je.step==="success"||je.step==="error"),H=o?.primaryColor||k.colors.primary,we=402,He=(Se,mt,rt)=>u(hf,{label:Se,loading:rt,balance:mt,dark:A,dk:b});return u(Dn,{isOpen:!0,onClose:pt,title:"Withdraw",subtitle:u(If,{dark:A,dk:b}),styles:o,theme:k,dark:A,maxWidth:"486px",footerLinkText:"Spicenet accounts \u2192",overlayDimmed:!1,closeOnBackdropClick:n,overlayContent:yo?u("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,display:"flex",flexDirection:"column",justifyContent:"flex-end",pointerEvents:"none",zIndex:20},children:u("div",{style:{pointerEvents:"auto"},children:u(ta,{type:"withdraw",isOpen:!0,isProcessing:qe,onRetryTx:()=>{Oo()},onNewTx:()=>{Dt(null),fe(""),at(null),Ke.current=null},onClose:()=>{Dt(null),at(null),Ct(!1),Ke.current=null},onComplete:()=>{Dt(null),at(null),Ct(!1),Ke.current=null},results:[{asset:{symbol:Te?.symbol||"Token",address:Te?.address||""},txHash:je?.txHash||"",success:je?.step==="success",error:je?.error,amount:z}],chainId:D??void 0,theme:k})})}):null,children:C("fieldset",{disabled:$t,style:{border:0,minWidth:0,width:"calc(100% - 32px)",maxWidth:`${we}px`,margin:"0 auto",padding:"0 0 4px 0",position:"relative"},children:[C("div",{style:{marginTop:"16px",marginBottom:"16px",display:"flex",flexDirection:"column",gap:"16px"},children:[u(kf,{header:He("Source",wn,$),amount:z,setAmount:fe,isInsufficient:ve,sourceAmountDecimals:jt,selectedSourceAsset:q,resolvedSelectedSourceAsset:q,spiceAssets:Ce,setSelectedSourceAsset:N,sourceUsdEstimate:tn,sourceTokenLabel:sn,sourceChainLabel:bn,totalSelectedBalance:wn,showSourceTokenPopover:ne,setShowSourceTokenPopover:re,tokenPopoverPos:G,setTokenPopoverPos:P,tokenTriggerRef:de,primaryColor:H,dark:A,dk:b}),u(xf,{header:He("Destination",Gn?.balanceFormatted??null,On.loading),amount:z,receiveAmountDisplay:rn,receiveUsdEstimate:Pt,selectedDestToken:Te,destTokenSymbol:St,destChainName:_e,destChainLogo:Vt,compatibleDestinationChains:Xe,networkSwitchRef:X,onOpenNetworkPopover:Wt,showNetworkPopover:ce,setShowNetworkPopover:Q,networkPopoverPos:xe,selectedChainId:D,setSelectedChainId:L,dark:A,dk:b})]}),C("div",{style:{marginBottom:k.spacing.sm},children:[u(vf,{show:B,onToggle:Nt,showCustomAddress:j,setShowCustomAddress:J,customRecipient:Y,setCustomRecipient:me,externalAddress:ot,recipientAddress:wt,destChainName:_e,destChainLogo:Vt,compatibleDestinationChains:Xe,txDetailsChainSwitchRef:pe,onOpenNetworkPopover:Wt,sourceChainLabel:bn,sourceDetailsLogo:q?S({...q,logoURI:Vo}).logoURI:Vo,sourceTokenLabel:sn,amount:z,totalSourceDebitDisplay:he,receiveAmountDisplay:rn,destTokenSymbol:St,shouldQuoteWithdrawGas:Yt,estimatingFee:ut,feeError:ft,displayedGasFee:Jt,selectedDestToken:Te,theme:k,styles:o,dark:A,dk:b}),ye&&C("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[u(oo,{palette:b,label:"FEE ASSET",value:Je.fees.isLoading?"Estimating...":st.source?`${S(st.source).symbol} \xB7 ${st.source._source==="spice"?"Spicenet":Ge(st.source.chainId)?.displayName}`:"Unavailable"}),u(oo,{palette:b,label:"MAXIMUM FEE FUNDING",value:Je.fees.isLoading?"Estimating...":Je.fees.ready&&st.source&&st.maximumFeeFunding!=null?`${Fe(st.maximumFeeFunding,st.source.decimals)} ${S(st.source).symbol}`:"Unavailable"}),(Je.status.error||Je.fees.error)&&u(Nn,{variant:"error",size:"compact",palette:b,children:Je.status.error||Je.fees.error}),Je.status.finalizationError&&u(Et,{variant:"outline",dark:A,disabled:Je.status.finalizing,onClick:()=>void Je.retryFinalization(),children:"Retry application update"}),Je.status.statusMsg&&u("span",{role:"status",children:Je.status.statusMsg})]}),q&&!$&&Xe.length===0&&u(Nn,{variant:"warning",size:"compact",palette:b,children:"No withdrawal networks are available for this asset."}),ht&&u(Nn,{variant:"error",size:"compact",palette:b,fontFamily:o?.fontFamily||k.typography.fontFamily,style:{marginBottom:"12px"},children:ht}),ee&&C(Nn,{variant:Ze?"error":"warning",size:"compact",palette:b,children:[Ze?"Unable to load this balance. Please try again.":"Some other balances could not be refreshed."," ",u("button",{type:"button",onClick:()=>void ze(),children:"Retry"})]}),u(Et,{variant:"outline",fullWidth:!0,onClick:()=>{An&&(ye?Je.submitPay():hn())},disabled:kn||$t,theme:k,dark:A,styles:o,style:{marginTop:"8px"},children:$t?"EXECUTING...":ye&&vn?"WITHDRAWN":Yn})]})]})})}return null},fa=Sf,Af=({onDepositClick:e,onWithdrawClick:t,depositDisabled:n=!1,withdrawDisabled:o=!1,primaryColor:s="#EA4B4B",buttonStyles:r,dark:a=!1})=>{if(!e&&!t)return null;const i={button:{backgroundColor:s,...r}};return C("div",{style:{display:"flex",gap:"8px"},children:[e&&u(Et,{variant:"outline",onClick:e,disabled:n,dark:a,styles:i,style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&u(Et,{variant:"outline",onClick:()=>t(),disabled:o,dark:a,styles:i,style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]})},Ef=yn(Af),Ff=({section:e,dk:t,dark:n=!1})=>{const o=s=>{switch(s){case"green":return"#10b981";case"red":return"#ef4444";default:return t.textPrimary}};return C("div",{children:[u("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:t.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:e.title}),u("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.items.map((s,r)=>C("div",{role:s.onClick?"button":void 0,tabIndex:s.onClick?0:void 0,onClick:s.onClick,onKeyDown:s.onClick?a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),s.onClick?.())}:void 0,style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:t.cardBg,border:n?`1px solid ${t.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"},children:[C("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.tokenLogoURI?u("img",{src:s.tokenLogoURI,alt:s.tokenSymbol,style:{width:"20px",height:"20px",borderRadius:"50%"}}):u("div",{style:{width:"20px",height:"20px",borderRadius:"50%",backgroundColor:n?t.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",fontWeight:600,color:t.textSecondary},children:s.tokenSymbol.charAt(0)}),C("div",{children:[u("div",{style:{fontSize:"13px",fontWeight:500,color:t.textPrimary},children:s.tokenSymbol}),u("div",{style:{fontSize:"11px",color:t.textSecondary},children:s.label})]})]}),u("div",{style:{fontSize:"13px",fontWeight:600,color:o(s.valueColor)},children:s.displayValue})]},r))})]})},Tf=yn(Ff);var Bf="data:image/svg+xml,%3csvg width='11' height='11' viewBox='0 0 24 24' fill='none' stroke='black' stroke-opacity='0.5' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' xmlns='http://www.w3.org/2000/svg'%3e%3cpolyline points='17 1 21 5 17 9' /%3e%3cpath d='M3 11V9a4 4 0 0 1 4-4h14' /%3e%3cpolyline points='7 23 3 19 7 15' /%3e%3cpath d='M21 13v2a4 4 0 0 1-4 4H3' /%3e%3c/svg%3e";const Df=({appName:e,status:t,statusLabel:n,totalUsdValue:o,breakdownSubtitle:s,showUsdSummary:r=!0,address:a,dk:i,dark:l=!1,showModeToggle:c,isEmbeddedMode:d=!0,onModeToggle:p})=>{const[f,h]=O(!1),m=async()=>{a&&await Vc(a)&&(h(!0),setTimeout(()=>h(!1),2e3))},g=t==="active",y=n||(g?"Active":"Inactive"),w=g?"#10b981":"#9ca3af",x=C("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[C("div",{children:[u("strong",{children:"Embedded:"})," Deposit assets into ",e," account and use them here."]}),C("div",{children:[u("strong",{children:"External:"})," Use assets from your connected wallet here."]})]});return C("div",{children:[C("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[C("div",{style:{fontSize:"13px",fontWeight:600,color:i.textPrimary},children:[e," Account"]}),c?C("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[C("button",{onClick:p,style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:l?i.hoverBg:"#f3f4f6",border:l?`1px solid ${i.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"11px",fontWeight:600,fontFamily:Oe.mono,color:i.textSecondary,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease",letterSpacing:"0.02em"},children:[u("span",{children:d?"Embedded":"External"}),u("img",{src:Bf,alt:"","aria-hidden":"true",style:{width:"11px",height:"11px",display:"block",...l?{filter:"invert(0.65)"}:{}}})]}),u(rl,{content:x,label:"Account mode info",textColor:l?i.textPrimary:"#f9fafb",backgroundColor:l?i.cardBg:"#111827",borderColor:l?i.cardBorder:"rgba(255,255,255,0.08)",accentColor:l?i.textSecondary:"#6b7280",children:u("img",{src:zr,alt:"","aria-hidden":"true",style:{width:"12px",height:"12px",display:"block",...l?{filter:"invert(0.65)"}:{}}})})]}):C("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:l?i.hoverBg:g?"#ecfdf5":"#f3f4f6",border:l?`1px solid ${i.cardBorder}`:g?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[u("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:w}}),u("span",{style:{fontSize:"11px",fontWeight:500,color:l?i.textSecondary:g?"#065f46":"#6b7280"},children:y})]})]}),r&&u("div",{style:{fontSize:"28px",fontWeight:700,color:i.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:lo(o)}),r&&s&&u("div",{style:{fontSize:"12px",color:i.textSecondary,marginBottom:"8px"},children:s}),a&&C("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[u("span",{style:{fontSize:"12px",fontFamily:Oe.mono,color:l?i.textSecondary:"#9ca3af"},children:Po(a)}),u("button",{onClick:m,style:{padding:"2px 6px",fontSize:"10px",fontWeight:500,backgroundColor:"transparent",color:l?i.textSecondary:"#9ca3af",border:"none",cursor:"pointer",borderRadius:"4px",transition:"background-color 150ms ease, color 150ms ease"},title:"Copy address",children:f?"Copied":"Copy"})]})]})},Of=yn(Df),Rf=({asset:e,label:t,logo:n,dk:o,dark:s})=>{const r=wl(n,e.chainId,e.tokenAddress),[a,i]=En.useState();return n===null?null:r&&r!==a?u("img",{src:r,alt:t,onError:()=>i(r),style:{width:"24px",height:"24px",borderRadius:"50%"}}):u("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:s?o.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:o.textSecondary},children:t.charAt(0)})},Mf=e=>`${e.tokenAddress}-${e.chainId}`,Wf=({spiceAssets:e,loading:t,dk:n,dark:o=!1,canDirectWithdraw:s=!1,onDirectWithdraw:r,directWithdrawState:a,onWithdrawClick:i,limit:l})=>{const c=Rn(),[d,p]=O(!1),f=l!==void 0&&!d?Math.max(e.length-l,0):0,h=f>0?e.slice(0,l):e,m={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},g={backgroundColor:n.cardBg,border:o?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return t?C("div",{children:[u("div",{style:m,children:"Idle Balances"}),[1,2].map(y=>u("div",{style:{...g,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},y))]}):e.length===0?C("div",{children:[u("div",{style:m,children:"Idle Balances"}),u("div",{style:{...g,padding:"16px",textAlign:"center",fontSize:"13px",color:o?n.textSecondary:"#9ca3af"},children:"No assets yet. Deposit to get started."})]}):C("div",{children:[u("div",{style:m,children:"Idle Balances"}),C("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[h.map(y=>{const w=Ge(y.chainId),x=y.chainDisplayName||w?.displayName||`Chain ${y.chainId}`,v=c({symbol:y.tokenSymbol,displaySymbol:y.tokenDisplaySymbol||y.tokenDisplayName,displayName:y.tokenDisplayName,receiptTokenId:y.receiptTokenId,receiptTokenName:y.receiptTokenName,location:y.location,logoURI:y.logoURI}),k=v.symbol,A=Mf(y),b=y.receiptTokenId&&i,S=b||s&&y.directWithdraw&&!!r,T=!b&&a?.key===A?a:null,E=T?.step==="pending";return C("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...g},children:[C("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[u(Rf,{asset:y,label:k,logo:v.logoURI,dk:n,dark:o}),C("div",{children:[u("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:k}),u("div",{style:{fontSize:"11px",color:o?n.textSecondary:"#9ca3af"},children:x})]})]}),C("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[C("div",{style:{textAlign:"right"},children:[u("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:cs({balance:BigInt(y.balance),decimals:y.tokenDecimals})}),u("div",{style:{fontSize:"11px",color:T?.step==="error"?n.errorText:o?n.textSecondary:"#9ca3af"},children:T?.step==="error"?T.message||"Withdraw failed":!Number.isFinite(y.usdValue)||y.usdValue<=0?"\u2014":`${lo(y.usdValue)}${y.priceStatus==="stale"?" (stale)":""}`})]}),S&&u("button",{onClick:()=>{E||(b?b(y.receiptTokenId):r(y))},disabled:E,title:b?"Choose withdrawal network":"Withdraw to external wallet",style:{padding:"6px 10px",borderRadius:"6px",border:o?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",backgroundColor:o?n.hoverBg:"#ffffff",color:n.textPrimary,fontSize:"11px",fontWeight:600,cursor:E?"default":"pointer",opacity:E?.6:1,whiteSpace:"nowrap"},children:E?"Withdrawing\u2026":"Withdraw"})]})]},y.positionId??`${y.owner??""}:${y.location??""}:${y.receiptTokenId??`${y.tokenAddress}-${y.chainId}`}`)}),l!==void 0&&e.length>l&&C("button",{onClick:()=>p(!d),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:"6px",width:"100%",padding:"8px 12px",...g,cursor:"pointer",color:n.textSecondary,fontSize:"12px",fontWeight:500},children:[u("span",{children:d?"Show less":`Show ${f} more`}),u("span",{style:{transform:d?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]})]})]})},Nf=yn(Wf),Pf=({pendingDeposits:e,onCompleteDeposit:t,dk:n,dark:o=!1})=>e.length===0?null:C("div",{children:[u("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:"Pending Deposits"}),u("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((s,r)=>{const a=Ge(s.chainId)?.displayName||`Chain ${s.chainId}`;return C("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:o?n.warningBg:"#fffbeb",border:o?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"8px"},children:[C("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[u("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:o?n.hoverBg:"#fde68a",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:n.warningText},children:s.tokenSymbol.charAt(0)}),C("div",{children:[C("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:[s.amount," ",s.tokenSymbol]}),C("div",{style:{fontSize:"11px",color:n.warningText},children:["on ",a]})]})]}),u("button",{onClick:()=>t?.(s),style:{padding:"4px 12px",fontSize:"11px",fontWeight:600,backgroundColor:o?n.hoverBg:"#fef3c7",color:o?n.textPrimary:"#92400e",border:o?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"9999px",cursor:"pointer",transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease"},children:"Complete"})]},`${s.tokenAddress}-${s.chainId}-${r}`)})})]}),Uf=yn(Pf),Lf=({appName:e,status:t,statusLabel:n,totalUsdValue:o,breakdownSubtitle:s,showUsdSummary:r,address:a,spiceAssets:i,spiceAssetsLoading:l,pendingDeposits:c,customSections:d,notice:p,onDepositClick:f,onWithdrawClick:h,depositDisabled:m,onCompleteDeposit:g,primaryColor:y,buttonStyles:w,dk:x,dark:v=!1,showModeToggle:k,isEmbeddedMode:A,onModeToggle:b,showConnectExternalCta:S,onConnectExternalWallet:T,connectExternalError:E,showHowItWorks:I=!0,canDirectWithdraw:M,onDirectWithdraw:W,directWithdrawState:R,idleBalancesLimit:F})=>{const[N,D]=O(!1);return C("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[u(Of,{appName:e,status:t,statusLabel:n,totalUsdValue:o,breakdownSubtitle:s,showUsdSummary:r,address:a,dk:x,dark:v,showModeToggle:k,isEmbeddedMode:A,onModeToggle:b}),p&&u("div",{style:{padding:"10px 12px",borderRadius:"8px",backgroundColor:p.tone==="warning"?v?"rgba(245, 158, 11, 0.12)":"#fffbeb":p.tone==="success"?v?"rgba(16, 185, 129, 0.12)":"#ecfdf5":x.cardBg,border:p.tone==="warning"?v?"1px solid rgba(245, 158, 11, 0.35)":"1px solid #fde68a":p.tone==="success"?v?"1px solid rgba(16, 185, 129, 0.35)":"1px solid #a7f3d0":v?`1px solid ${x.cardBorder}`:"1px solid #e5e7eb",color:p.tone==="warning"?v?"#fbbf24":"#92400e":p.tone==="success"?v?"#34d399":"#047857":x.textSecondary,fontSize:"12px",lineHeight:1.45,fontWeight:500},children:p.message}),S&&C("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[u("button",{onClick:T,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:y||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:Oe.ui,transition:"opacity 150ms ease"},children:"Connect External Wallet"}),E&&u("span",{style:{fontSize:"11px",color:v?x.errorText:"#b91c1c",lineHeight:1.4},children:E})]}),u("div",{style:{height:"1px",backgroundColor:v?"#2d2d2d":"#e5e7eb"}}),u(Ef,{onDepositClick:f,onWithdrawClick:h,depositDisabled:m,primaryColor:y,buttonStyles:w,dark:v}),I&&C("div",{children:[C("button",{onClick:()=>D(!N),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:x.cardBg,border:v?`1px solid ${x.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:x.textSecondary,fontSize:"12px",fontWeight:500},children:[u("span",{children:"How It Works"}),u("span",{style:{transform:N?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),N&&C("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:v?x.cardBg:"#f0fdf4",border:v?`1px solid ${x.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:v?x.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),u(Uf,{pendingDeposits:c,onCompleteDeposit:g,dk:x,dark:v}),u(Nf,{spiceAssets:i,loading:l,dk:x,dark:v,canDirectWithdraw:M,onDirectWithdraw:W,directWithdrawState:R,onWithdrawClick:h,limit:F}),d.map((L,z)=>u(Tf,{section:L,dk:x,dark:v},z))]})},zf=yn(Lf);function Hf({dark:e,onSuccess:t,onError:n}){const{disconnect:o}=La(),{logout:s}=ad(),[r,a]=O(!1);return u(Et,{variant:"ghost",fullWidth:!0,dark:e,loading:r,onClick:async()=>{a(!0);try{o(),await s(),t()}catch(i){n(Mn(i,"Unable to disconnect. Please try again."))}finally{a(!1)}},children:"Disconnect"})}const ma=380,go=8,qf=[],Vf={};function gc(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function Qf(e,t){const n=new Map;Object.entries(t).forEach(([s,r])=>{if(!Number.isFinite(r)||r<=0)return;n.set(s,r),n.set(s.toUpperCase(),r);const a=gc(s);a&&n.set(a,r)});const o=[e.symbol,e.displaySymbol,e.receiptTokenName,e.name,e.displayName];for(const s of o){if(!s)continue;const r=n.get(s)??n.get(s.toUpperCase());if(r!==void 0)return r;const a=gc(s);if(!a)continue;const i=n.get(a);if(i!==void 0)return i}return 0}const yc=({appName:e,status:t="active",statusLabel:n,customSections:o=qf,extraAssets:s=[],tokenPrices:r={},tokenLogos:a=Vf,breakdownLabels:i=[],notice:l,styles:c,dark:d,onDepositSuccess:p,onDepositClick:f,onWithdrawClick:h,onCompleteDeposit:m,showModeToggle:g=!1,defaultMode:y,showUsdSummary:w=!0,alwaysShowEmbeddedIdle:x=!1,idleBalancesLimit:v,showDisconnect:k=!1})=>{const A=Qt(Mt),b=A?.mode!=="7702",S=!!A?.isWhitelistGateActive,T=!!A?.isWhitelistConfigured&&A?.isUserWhitelisted!==!0,E=_(!1);ae(()=>{if(!E.current){if(Qc()){E.current=!0;return}y&&A?.setMode&&(A.setMode(y==="non7702"?"ondemand":"7702"),E.current=!0)}},[A,y]);const[I,M]=O(!1),[W,R]=O(null),[F,N]=O({top:0,bottom:0,left:0,placement:"below"}),D=_(null),L=_(null),{address:z,isConnected:fe}=Zn(),ce=A?.embeddedWalletAddress,Q=A?.externalWalletAddress,{embeddedAddress:ne}=ps(),{brand:re,dark:j,primaryColor:J,dk:Y}=Bt(c,d),me=e??re?.appName??"Spice",B=b&&!Q,U=!b||x,X=U?ce||ne:z,pe=ue(()=>A?.supportedChainIds??ys("mainnet"),[A?.supportedChainIds]),de=Ao({owner:U?X:Q,role:"holding",sourceChains:pe,additionalSourceTokens:s.filter($=>!$.receiptTokenId&&(!$.owner||ge($.owner,U?X:Q))).map($=>({address:$.tokenAddress,chainId:$.chainId,decimals:$.tokenDecimals,symbol:$.tokenSymbol,logoURI:$.logoURI})),includeRollupAssets:U,enabled:U?!!X:!!Q}),xe=de.assets.filter($=>$._source==="spice"),K=de.walletAssets,G=de.loading,P=de.refresh,V=U?X:Q,ie=ue(()=>s.filter($=>!$.owner||$.owner.toLowerCase()===V?.toLowerCase()).map($=>({...$,owner:$.owner??V,location:$.location??($.receiptTokenId?"rollup":U?"embedded":"external")})),[s,V,U]),ke=ue(()=>{const $=new Map(Object.entries(r).filter(([,ee])=>Number.isFinite(ee)&&ee>0).map(([ee,ze])=>[ee.toLowerCase(),ze]));return K.map(ee=>({owner:ee.owner,location:ee.location,positionId:nt(ee),tokenAddress:ee.address,tokenSymbol:ee.symbol,tokenDecimals:ee.decimals,chainId:ee.chainId,chainDisplayName:gn(ee.chainId),balance:ee.balance.toString(),balanceFormatted:ee.balanceFormatted,usdValue:ee.balanceUsd||($.get(`${ee.chainId}:${ee.address.toLowerCase()}`)??0)*ee.balanceFormatted,logoURI:ee.logoURI||a[ee.symbol],directWithdraw:U}))},[K,ie,a,r,U]),Ee=ue(()=>{const $=U?xe.map(le=>{const Pe=le.balanceUsd||0,Ae=Number.isFinite(le.balanceFormatted)?le.balanceFormatted:0,q=Qf(le,r),Ze=le.priceStatus&&q>0?q*Ae:Pe>0?Pe:q*Ae;return{owner:le.owner,location:le.location,positionId:nt(le),tokenAddress:le.address,tokenSymbol:le.symbol,tokenDisplaySymbol:Gc(le),tokenDisplayName:jc(le),tokenDecimals:le.decimals,chainId:le.chainId,chainDisplayName:or(le),balance:le.balance.toString(),balanceFormatted:le.balanceFormatted,usdValue:Ze,priceStatus:q>0?void 0:le.priceStatus,logoURI:le.logoURI,receiptTokenId:le.receiptTokenId,receiptTokenName:le.receiptTokenName}}):[],ee=le=>`${le.owner?.toLowerCase()}:${le.location}:${le.chainId}:${le.receiptTokenId??Ye(le.tokenAddress).toLowerCase()}`,ze=new Map([...de.rollupAssets,...K].map(le=>[ee({...le,tokenAddress:le.address}),le])),Ce=new Map([...$,...ke].map(le=>[ee(le),le]));for(const le of B?[]:ie){const Pe=ee(le),Ae=Ce.get(Pe);Ce.set(Pe,Ae?{...le,...Ae,logoURI:le.logoURI??Ae.logoURI,tokenDisplayName:le.tokenDisplayName??Ae.tokenDisplayName,tokenDisplaySymbol:le.tokenDisplaySymbol??Ae.tokenDisplaySymbol}:le)}return[...Ce.values()].filter(le=>BigInt(le.balance)>0n&&Ai({isDiscovered:ze.get(ee(le))?.isDiscovered,balanceUsd:le.usdValue},!0)&&is(ze.get(ee(le))??{address:le.tokenAddress,symbol:le.tokenSymbol,displaySymbol:le.tokenDisplaySymbol},A?.allowedTokens)).sort((le,Pe)=>Pe.usdValue-le.usdValue)},[U,B,xe,de.rollupAssets,r,ke,ie,A?.allowedTokens]),Be=ue(()=>Ee.reduce(($,ee)=>$+ee.usdValue,0),[Ee]),{pendingDeposits:Ie,refresh:Z}=Yi({chainIds:pe,enabled:!!z,discoverWalletBalances:!0}),ot=ue(()=>o.reduce(($,ee)=>$+(ee.totalValue??0),0),[o]),qe=Be+ot,Ct=ue(()=>{const $=[];Be>0&&$.push(`${lo(Be)} idle`);for(const ee of o){const ze=i.find(Ce=>Ce.sectionTitle===ee.title)?.label||ee.title.toLowerCase();$.push(`${lo(ee.totalValue??0)} ${ze}`)}return $.join(" \xB7 ")},[Be,o,i]),ht=te($=>{m?m($):R($)},[m]),Ve=te(()=>{R(null)},[]),Qe=te(()=>{R(null),p?.()},[p]),at=te(()=>{if(!D.current)return;const $=D.current.getBoundingClientRect(),ee=window.innerHeight-$.bottom-go,ze=$.top-go,Ce=ee>=400||ee>=ze?"below":"above",le=Math.max(go,Math.min($.right-ma,window.innerWidth-ma-go)),Pe=Ce==="below"?$.bottom+go:$.top-go,Ae=Ce==="above"?window.innerHeight-Pe:0;N({top:Pe,bottom:Ae,left:le,placement:Ce})},[]);Da(()=>{I&&at()},[I,at]),ae(()=>{if(!I)return;const $=Ce=>{D.current&&!D.current.contains(Ce.target)&&L.current&&!L.current.contains(Ce.target)&&M(!1)},ee=Ce=>{Ce.key==="Escape"&&M(!1)},ze=()=>at();return document.addEventListener("mousedown",$),document.addEventListener("keydown",ee),window.addEventListener("scroll",ze,{passive:!0}),window.addEventListener("resize",at),()=>{document.removeEventListener("mousedown",$),document.removeEventListener("keydown",ee),window.removeEventListener("scroll",ze),window.removeEventListener("resize",at)}},[I,at]);const je=U?ce||ne||z:Q||z,Dt=te(()=>{A?.setMode&&A.setMode(b?"7702":"ondemand")},[A,b]),[Ke,gt]=O(null);let De=null;try{De=qa({onSuccess:()=>gt(null),onError:$=>gt(Mn($,"Failed to connect wallet."))}).connectWallet}catch{De=null}const et=te(()=>{De&&(M(!1),gt(null),De({walletChainType:"ethereum-only"}))},[De]),Le=!Q&&!!De,ct=te(()=>{M(!1),f?.()},[f]),$e=te($=>{M(!1),h?.($)},[h]),dt=te($=>{M(!1),ht($)},[ht]),[kt,ut]=O(null),Re=U&&!!Q&&!ge(V,Q),ft=te($=>{const ee=K.find(ze=>ze.chainId===$.chainId&&ge(ze.address,$.tokenAddress));ee&&(M(!1),ut(ee))},[K]);if(typeof window>"u")return null;const Ot=C("button",{ref:D,onClick:()=>M(!I),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:j?Y.hoverBg:"#ffffff",border:j?`1px solid ${Y.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:Oe.ui,color:j?Y.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:j?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[C("span",{children:[me," Account"]}),fe&&w&&C("span",{style:{color:j?Y.textSecondary:"#6b7280"},children:["\xB7 ",lo(qe)]}),u("span",{style:{fontSize:"10px",color:j?Y.textSecondary:"#9ca3af",transform:I?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),Me=I?pr.createPortal(C(an,{children:[u("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:ao.popover},onClick:()=>M(!1)}),C("div",{ref:L,style:{position:"fixed",top:F.placement==="below"?`${F.top}px`:"auto",bottom:F.placement==="above"?`${F.bottom}px`:"auto",left:`${F.left}px`,width:`${ma}px`,maxWidth:`calc(100vw - ${go*2}px)`,maxHeight:"80vh",backgroundColor:j?Y.shell:"#ffffff",border:j?`1px solid ${Y.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:j?"0 10px 40px rgba(0, 0, 0, 0.5)":"0 10px 40px rgba(0, 0, 0, 0.12)",zIndex:ao.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${wo.out}`},children:[u(zf,{appName:me,status:t,statusLabel:n,totalUsdValue:qe,breakdownSubtitle:Ct,showUsdSummary:w,address:U?je:z,spiceAssets:Ee,spiceAssetsLoading:G,pendingDeposits:Ie,customSections:o,notice:l,onDepositClick:f?ct:void 0,onWithdrawClick:h?$e:void 0,depositDisabled:T,onCompleteDeposit:dt,primaryColor:J,buttonStyles:c?.button,dk:Y,dark:j,showModeToggle:g,isEmbeddedMode:!b,onModeToggle:Dt,showConnectExternalCta:Le,onConnectExternalWallet:et,connectExternalError:Ke,showHowItWorks:!S,canDirectWithdraw:Re,onDirectWithdraw:ft,idleBalancesLimit:v}),k&&fe&&u("div",{style:{padding:"0 16px 16px"},children:u(Hf,{dark:j,onSuccess:()=>M(!1),onError:gt})})]}),u("style",{children:`
45
45
  @keyframes accountDisplayFadeIn {
46
46
  from { opacity: 0; transform: translateY(-4px); }
47
47
  to { opacity: 1; transform: translateY(0); }