@spicenet-io/spiceflow-ui 2.5.6 → 2.5.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -20,7 +20,7 @@
20
20
  transform: translateX(100%);
21
21
  }
22
22
  }
23
- `})]})},_n={WALLET_DISCONNECTED:"Wallet is not connected.",WALLET_REJECTED:"Transaction was rejected.",SIGNATURE_FAILED:"Signature failed. Please try again.",CONCURRENT_EXECUTION:"A transaction is already in progress.",ABORT:"Transaction was cancelled.",NO_VENUE_FOR_CHAIN:"No swap venue available for this chain.",NO_LIQUIDITY:"No liquidity available for this swap pair.",VENUE_API_ERROR:"Swap service error. Please try again.",ROUTE_TOKEN_NOT_FOUND:"Token not found in the registry.",ROUTE_UNSUPPORTED_INPUT:"This input token is not supported.",ROUTE_STRATEGY_ERROR:"No viable route found for this swap.",INVALID_PARAMS:"Invalid parameters. Please check your inputs.",RELAYER_ERROR:"Relayer error. Please try again.",RELAYER_EXECUTE_ERROR:"Transaction execution failed. Please try again.",RELAYER_STATUS_ERROR:"Failed to check transaction status.",ON_CHAIN_REVERT:"Transaction reverted on-chain. Please verify your inputs.",POLLING_EXHAUSTED:"Transaction status check timed out. It may still complete.",POLLING_CONSECUTIVE_FAILURES:"Lost connection to transaction status. It may still complete.",ALL_ATTEMPTS_FAILED:"All attempts failed. Please try again."},eo=[{test:t=>t.includes("user rejected")||t.includes("user denied")||t.includes("user cancelled")||t.includes("rejected the request")||t.includes("action_rejected"),message:"Transaction was rejected."},{test:t=>t.includes("4001"),message:"Transaction was rejected."},{test:t=>t.includes("insufficient funds")||t.includes("insufficient balance"),message:"Insufficient funds for this transaction."},{test:t=>t.includes("internal json-rpc error")||t.includes("internal error")||t.includes("an internal error was received"),message:"RPC Network error. Try switching your RPC endpoint or try again."},{test:t=>t.includes("network error")||t.includes("failed to fetch")||t.includes("econnrefused")||t.includes("timeout"),message:"Network connection error. Please check your connection."},{test:t=>t.includes("does not match the target chain")||t.includes("current chain of the wallet"),message:"Wrong network detected. Please switch to the correct network and try again."},{test:t=>t.includes("nonce too low")||t.includes("nonce has already been used"),message:"Transaction conflict. Please try again."},{test:t=>t.includes("cannot estimate gas")||t.includes("gas required exceeds"),message:"Unable to estimate gas. The transaction may fail \u2014 please verify your inputs."},{test:t=>t.includes("execution reverted")||t.includes("transaction reverted"),message:"Transaction would fail on-chain. Please verify your inputs and try again."}],jt=(t,s="Something went wrong. Please try again.")=>{if(z.isSpiceflowError(t)){const a=_n[t.code];if(a)return a}const n=Gs(t).toLowerCase();for(const{test:a,message:i}of eo)if(a(n))return i;return s},to=t=>{if(z.isSpiceflowError(t))return t.code==="WALLET_REJECTED";const s=Gs(t).toLowerCase();return s.includes("user rejected")||s.includes("user denied")||s.includes("user cancelled")||s.includes("rejected the request")||s.includes("action_rejected")||s.includes("4001")};function Gs(t){if(!t)return"";if(typeof t=="string")return t;const s=t,n=s.message||s.reason||"",a=s.details||"";return`${n} ${a}`.trim()}var Js="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==",Ts="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=",so="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=";const Wt=K.getChainMeta(1)?.logo??"";K.getChainMeta(42161)?.logo;const cs=K.TOKENS.find(t=>t.symbol==="USDC")?.logo??"";K.TOKENS.find(t=>t.symbol==="WBTC")?.logo;const bt=Object.fromEntries([...K.getMainnetChains(),...K.getTestnetChains()].map(t=>[t.id,t.logo])),vs={metamask:Js,metaMask:Js,rabby:Ts,phantom:so},no=Object.fromEntries(K.TOKENS.map(t=>[t.symbol,t.logo])),Nt=({symbol:t,logoURI:s,size:n=20,theme:a})=>{const i=a||Re.createTheme("dark"),[l,r]=o.useState(!1),c={width:`${n}px`,height:`${n}px`,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:`${n*.4}px`,fontWeight:i.typography.fontWeight.bold,flexShrink:0,overflow:"hidden",backgroundColor:"#ffffff"},d=t.toUpperCase(),p=s||no[d];if(p&&!l)return e.jsx("img",{src:p,alt:t,style:{...c,objectFit:"cover"},onError:()=>r(!0)});const u=oo(t);return e.jsx("div",{style:{...c,...u.style},children:u.icon})},oo=t=>{const s=t.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"}}[s];if(n)return{style:{backgroundColor:n.bg,color:n.text},icon:n.icon||s.charAt(0)};const a=s.split("").reduce((c,d)=>d.charCodeAt(0)+((c<<5)-c),0),i=Math.abs(a)%360,l=`hsl(${i}, 60%, 50%)`,r=i>180?"#FFFFFF":"#000000";return{style:{backgroundColor:l,color:r},icon:s.charAt(0)}};var Ds="data:image/svg+xml,%3csvg width='15' height='15' viewBox='0 0 15 15' fill='none' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M7.5 7.49993V10.4999M7.5 4.96868V4.96784M14.25 7.5C14.25 11.2279 11.2279 14.25 7.5 14.25C3.77208 14.25 0.75 11.2279 0.75 7.5C0.75 3.77208 3.77208 0.75 7.5 0.75C11.2279 0.75 14.25 3.77208 14.25 7.5Z' stroke='%23ED6969' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3e%3c/svg%3e";const ro=({isOpen:t,onClose:s,onComplete:n,title:a="Testnet Airdrop",description:i="Request testnet tokens for your wallet. A small gas fee is required to process the airdrop.",chainId:l,airdropTag:r="default",walletAddress:c,airdropTokens:d,getChainConfig:p,getSupportedTokens:u})=>{const x=Re.createTheme("light"),{primaryColor:g}=z.useSpiceBrand(),[f,h]=o.useState(null),[b,m]=o.useState(null),{chain:I}=Qe.useAccount(),{data:W}=Qe.useWalletClient(),{switchChainAsync:C}=Qe.useSwitchChain(),y=o.useMemo(()=>u(l),[l,u]),B=o.useMemo(()=>y.filter(j=>!K.isNativeToken(j.address)),[y]),{data:D,refetch:R}=Qe.useReadContracts({contracts:B.map(j=>({address:j.address,abi:V.erc20Abi,functionName:"balanceOf",args:[c],chainId:l})),blockTag:"pending"}),S=o.useCallback(()=>{R();const j=setTimeout(R,2e3),E=setTimeout(R,4e3);return()=>{clearTimeout(j),clearTimeout(E)}},[R]);o.useEffect(()=>t?S():void 0,[t,S]),o.useEffect(()=>{let j;const E=()=>{j?.(),j=S()};return window.addEventListener("airdrop-complete",E),()=>{j?.(),window.removeEventListener("airdrop-complete",E)}},[S]);const A=o.useMemo(()=>{const j=[];return B.forEach((E,Q)=>{if(!d.some(ie=>ie.toUpperCase()===E.symbol.toUpperCase()))return;const Y=D?.[Q],U=Y?.status==="success"?Y.result:BigInt(0),G=Number(U)/Math.pow(10,E.decimals);j.push({address:E.address,symbol:E.symbol,name:E.name,decimals:E.decimals,balance:U,balanceFormatted:G})}),j},[B,D,d]),w=p(l),M="0x11126A138f34532D250CCf35531E5A2f398ce7d4",J=o.useCallback(async j=>{if(!c||!l){m({message:"Wallet not connected",type:"error"});return}if(!W){m({message:"Wallet client not available",type:"error"});return}h(j.address);try{I?.id!==l&&await C({chainId:l});const E=O.getClientForChain(l),Q=await E.getGasPrice(),Y=BigInt(21e3)*Q*BigInt(110)/BigInt(100),U=await W.sendTransaction({to:M,value:Y});await E.waitForTransactionReceipt({hash:U,timeout:6e4,pollingInterval:2e3,confirmations:1});const G=await z.relayerService.requestAirdrop({chainId:l,tokenId:j.symbol==="WBTC"?"mWBTC":j.symbol,wallet:c,tag:r});if(G.success){const ie=w?.blockExplorer;m({message:`Successfully airdropped ${j.symbol}!`,type:"success",linkText:G.txHash?"View Transaction":void 0,linkUrl:G.txHash&&ie?`${ie}/tx/${G.txHash}`:void 0}),window.dispatchEvent(new CustomEvent("airdrop-complete",{detail:{token:j.symbol,txHash:G.txHash}})),n&&n()}else m({message:G.errorMessage||"Airdrop failed",type:"error"})}catch(E){m({message:jt(E,"Airdrop request failed"),type:"error"})}finally{h(null)}},[c,l,W,I,C,r,w,n]),T=o.useCallback(()=>{window.dispatchEvent(new CustomEvent("airdrop-skipped"))},[s]);return e.jsxs(Ct,{isOpen:t,onClose:s,title:a,subtitle:e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"5px",backgroundColor:"#f9fafb",border:"1px solid #ed6969",borderRadius:"8px",padding:"10px",margin:"0 0 0 0"},children:[e.jsx("img",{src:Ds,alt:"Info",style:{width:"14px",height:"14px",marginTop:"2px",flexShrink:0}}),e.jsx("p",{style:{fontSize:"13px",color:"#374151",margin:0,lineHeight:"1.5"},children:i})]}),theme:x,maxWidth:"420px",children:[e.jsxs("div",{style:{padding:"0 24px 32px 24px"},children:[e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:A.length===0?e.jsx("p",{style:{textAlign:"center",color:"#6b7280",fontSize:"14px",padding:"20px 0"},children:"No airdrop tokens available for this chain."}):A.map(j=>{const E=f===j.address,Q=E||f!==null;return e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderRadius:"12px",border:"1px solid #e5e7eb",backgroundColor:"white",transition:"all 150ms ease"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[e.jsx(Nt,{symbol:j.symbol,size:36,theme:x}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:"16px",fontWeight:600,color:"#111827"},children:j.symbol}),e.jsxs("div",{style:{fontSize:"12px",color:"#6b7280",fontFamily:'"IBM Plex Mono", monospace'},children:["Balance:"," ",j.balanceFormatted?.toFixed(4)??"0.0000"]})]})]}),e.jsx(Re.Button,{variant:"outline",size:"sm",onClick:()=>J(j),disabled:Q,loading:E,theme:x,styles:{button:{backgroundColor:g}},children:"Get Airdrop"})]},j.address)})}),e.jsx(Re.Button,{variant:"outline",fullWidth:!0,onClick:T,disabled:f!==null,theme:x,styles:{button:{backgroundColor:g}},style:{marginTop:"20px"},children:"NEXT"})]}),b&&e.jsx(Ms,{message:b.message,type:b.type,linkText:b.linkText,linkUrl:b.linkUrl,onClose:()=>m(null)})]})},Ws=15,Ns=({checkStepStatus:t,pollingInterval:s=4e3,retryStep:n,maxRetries:a=3})=>{const[i,l]=o.useState(null),r=o.useRef(null),c=o.useRef(!1),d=o.useRef(!1),p=o.useRef(null),u=o.useRef({}),x=o.useRef(0),g=o.useRef(0),f=o.useCallback(()=>{r.current&&(clearInterval(r.current),r.current=null)},[]),h=o.useCallback(()=>{p.current=null,l(null),u.current={},x.current=0,g.current=0,f()},[f]),b=o.useCallback((m,I)=>{f(),c.current=!1,d.current=!1,u.current={},x.current=0,g.current=0;const W={intentId:m,steps:I.map(y=>({...y,status:"pending"})),overallStatus:"processing"};p.current=W,l(W);const C=async()=>{if(c.current||d.current)return;d.current=!0,g.current+=1;const y=g.current;try{const B=p.current;if(!B)return;const D=B.steps.map(w=>({...w}));let R=!0,S=!1;for(let w=0;w<D.length;w++){const M=D[w];if(M.status!=="success"){if((M.stepId===0||w>0&&D[w-1].status==="success")&&(M.status==="pending"||M.status==="processing"))try{const J=await t(m,M.stepId);if(x.current=0,J.data.status==="success")D[w]={...M,status:"success",transactionHash:J.data.transactionHash},w+1<D.length&&D[w+1].status==="pending"&&(D[w+1]={...D[w+1],status:"processing"});else if(J.data.status==="executing"||J.data.status==="created")D[w]={...M,status:"processing"};else if(J.data.status==="reverted"){const T=u.current[M.stepId]||0;if(n&&T<a){u.current[M.stepId]=T+1;try{await n(m,M.stepId)}catch(j){console.error(`[useStatus] Retry failed for step ${M.stepId}:`,j)}D[w]={...M,status:"processing"}}else D[w]={...M,status:"failed",transactionHash:J.data.transactionHash},S=!0}else D[w]={...M,status:"processing"}}catch(J){x.current+=1,console.error(`[useStatus] Poll #${y}: Error checking step ${M.stepId} (consecutive errors: ${x.current}/${Ws}):`,J),x.current>=Ws&&(console.error(`[useStatus] Too many consecutive polling errors (${Ws}). Marking step ${M.stepId} as failed.`),D[w]={...M,status:"failed"},S=!0)}D[w].status!=="success"&&(R=!1)}}const A={...B,steps:D,overallStatus:S?"failed":R?"success":"processing"};p.current=A,l(A),(R||S)&&(c.current=!0,f())}finally{d.current=!1}};C(),r.current=setInterval(C,s)},[t,s,f,n,a]);return o.useEffect(()=>()=>{f()},[f]),{intentStatus:i,startStatusPolling:b,stopStatusPolling:f,clearStatus:h}},os=({address:t,supportedChains:s,enabled:n=!0,refetchInterval:a})=>{const i=o.useContext(z.SpiceFlowProviderContext)?.apiUrl||z.RELAYER_API_URL,[l,r]=o.useState([]),[c,d]=o.useState(!1),[p,u]=o.useState(null),[x,g]=o.useState(!1),f=o.useRef(!1),h=o.useRef(!1),b=s?JSON.stringify([...s].sort()):"",m=o.useCallback(async(C=!1)=>{if(!t||!n){r([]),g(!1),f.current=!1;return}if(!h.current){h.current=!0,!f.current&&!C&&d(!0),u(null);try{const y=await fetch(`${i}/spicedeposit/${t}`);if(!y.ok)throw new Error(`Failed to fetch balance: ${y.status}`);const B=await y.json();if(B.success&&B.data?.tokens&&Array.isArray(B.data.tokens)){const D=new Map;B.data.tokens.forEach(S=>{const A=S.chainId,w=S.tokenAddress,M=S.amount;if(s&&!s.includes(A))return;const J=BigInt(M||"0");if(J>BigInt(0)){const T=O.getChainConfig(A),j=K.isNativeToken(w),E=j?K.ZERO_ADDRESS:w.toLowerCase();let Q=18,Y="TOKEN",U=w.slice(0,6)+"..."+w.slice(-4),G;if(j)Q=T?.nativeCurrency?.decimals||18,Y=T?.nativeCurrency?.symbol||"ETH",U=T?.nativeCurrency?.name||"Native Token";else{const F=T?.supportedTokens?.find(L=>L.address.toLowerCase()===w.toLowerCase());F&&(Q=F.decimals,Y=F.symbol,U=F.name,G=F.logo)}const ie=parseFloat((Number(J)/Math.pow(10,Q)).toFixed(6));if(ie>0){const F=`${E}-${A}`,L=D.get(F);if(L){const $=L.balance+J,me=parseFloat((Number($)/Math.pow(10,Q)).toFixed(6));D.set(F,{...L,balance:$,balanceFormatted:me})}else D.set(F,{address:E,symbol:Y,name:U,decimals:Q,chainId:A,balance:J,balanceFormatted:ie,balanceUsd:0,isNative:j,logoURI:G})}}});const R=Array.from(D.values());r(R),g(R.length>0),f.current=!0}else r([]),g(!1)}catch(y){const B=y instanceof Error?y.message:"Failed to fetch balance";u(B),console.error("Error fetching Spice assets:",y),f.current||(r([]),g(!1))}finally{d(!1),h.current=!1}}},[t,n,b,i]);o.useEffect(()=>{n&&t&&(f.current=!1,m(!1))},[t,n,b]),o.useEffect(()=>{if(!n||!t||!a)return;const C=setInterval(()=>{m(!0)},a);return()=>clearInterval(C)},[t,n,a,b]);const I=o.useCallback(C=>l.filter(y=>y.chainId===C),[l]),W=o.useCallback(async()=>{await m(!0)},[m]);return{assets:l,loading:c,error:p,hasBalance:x,refetch:W,getAssetsByChain:I}},ks=(t,s=4)=>!isFinite(t)||t===0?"0":t<1e-4?"< 0.0001":t.toFixed(s),rs=t=>isFinite(t)?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}).format(t):"$0.00",ao=(t,s=6,n=4)=>t.length<=s+n?t:`${t.slice(0,s)}...${t.slice(-n)}`,$s=t=>{const s=t.replace(/[^0-9.]/g,""),n=s.split(".");return n.length>2?n[0]+"."+n.slice(1).join(""):s},io=async t=>{try{return await navigator.clipboard.writeText(t),!0}catch(s){return console.error("Failed to copy to clipboard:",s),!1}},us=({chainId:t,name:s,size:n=16})=>{const a=t&&(bt[t]||K.getChainMeta(t)?.logo)||"";return a?e.jsx("img",{src:a,alt:s||`Chain ${t}`,style:{width:`${n}px`,height:`${n}px`,borderRadius:"50%",objectFit:"cover",flexShrink:0}}):null},lo=({selectedAsset:t,assets:s,onAssetSelect:n,showDropdown:a,onToggleDropdown:i,disabled:l=!1,theme:r})=>{const c=r||Re.createTheme("dark"),d=o.useRef(null),p=o.useRef(null),u=o.useRef(null),[x,g]=o.useState(null);o.useEffect(()=>{if(a&&p.current){const S=()=>{if(p.current){const A=p.current.getBoundingClientRect();g({top:A.bottom+6,right:window.innerWidth-A.right})}};return S(),window.addEventListener("scroll",S,!0),window.addEventListener("resize",S),()=>{window.removeEventListener("scroll",S,!0),window.removeEventListener("resize",S)}}else g(null)},[a]),o.useEffect(()=>{const S=A=>{d.current&&!d.current.contains(A.target)&&u.current&&!u.current.contains(A.target)&&a&&i()};return a&&document.addEventListener("mousedown",S),()=>{document.removeEventListener("mousedown",S)}},[a,i]);const[f,h]=o.useState(!1),b={backgroundColor:"transparent",border:`1px solid ${c.mode==="light"?"#aaaaaa":c.colors.border}`,borderRadius:"6px",color:c.colors.text,cursor:l?"not-allowed":"pointer",padding:"8px 12px 8px 8px",width:"100%",display:"flex",flexDirection:"column",gap:"4px",opacity:l?.6:1,transition:"all 0.15s ease",transform:f?"scale(0.98)":"scale(1)"},m={display:"flex",justifyContent:"space-between",alignItems:"center"},I={display:"flex",alignItems:"center",gap:"4px",paddingTop:"4px",borderTop:`1px solid ${c.colors.border}`},W=()=>x?{position:"fixed",top:`${x.top}px`,right:`${x.right}px`,backgroundColor:c.colors.secondary,border:`1px solid ${c.colors.border}`,borderRadius:c.borderRadius.md,boxShadow:c.shadows.lg,zIndex:100,width:"200px",maxHeight:"300px",overflow:"auto"}:{},C={backgroundColor:"transparent",border:"none",color:c.colors.text,cursor:"pointer",padding:c.spacing.sm,width:"100%",display:"flex",alignItems:"center",gap:c.spacing.sm,transition:`background-color ${c.animation.normal}`,":hover":{backgroundColor:c.colors.surfaceHover}},y={display:"flex",flexDirection:"column",alignItems:"flex-start",flex:1},B={fontSize:c.typography.fontSize.sm,fontWeight:c.typography.fontWeight.medium},D={fontSize:c.typography.fontSize.xs,color:c.colors.textMuted},R={transition:`transform ${c.animation.normal}`,transform:a?"rotate(180deg)":"rotate(0deg)"};return e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{position:"relative"},ref:d,children:e.jsxs("div",{ref:p,style:b,onClick:l?void 0:i,onMouseLeave:()=>{h(!1)},onMouseDown:()=>h(!0),onMouseUp:()=>h(!1),children:[e.jsxs("div",{style:m,children:[e.jsx("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:t?.asset?e.jsxs(e.Fragment,{children:[e.jsx(Nt,{symbol:t.asset.symbol,logoURI:t.asset.logoURI,theme:c,size:24}),e.jsx("span",{style:{fontSize:"16px",fontWeight:500,color:c.colors.text,lineHeight:"1.5"},children:t.asset.symbol})]}):e.jsx("span",{style:{fontSize:"14px",color:c.colors.textMuted},children:"Select"})}),e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:c.colors.textMuted,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:R,children:e.jsx("path",{d:"M6 9l6 6 6-6"})})]}),t?.asset&&e.jsxs("div",{style:I,children:[e.jsx(us,{chainId:t.asset.chainId,theme:c}),e.jsx("span",{style:{fontSize:"11px",color:c.colors.textMuted},children:O.getChainName(t.asset.chainId)})]})]})}),a&&x&&Bs.createPortal(e.jsxs("div",{ref:u,style:W(),children:[s.length===0&&e.jsx("div",{style:{padding:"10px 12px",color:c.colors.textMuted,fontSize:c.typography.fontSize.xs},children:"No assets available"}),s.map(S=>e.jsxs("button",{style:C,onClick:()=>{n(S),i()},children:[e.jsx(Nt,{symbol:S.symbol,logoURI:S.logoURI,theme:c},`${S.address}-${S.chainId}`),e.jsxs("div",{style:y,children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:c.spacing.xs},children:[e.jsx("span",{style:B,children:S.symbol}),e.jsx(us,{chainId:S.chainId,theme:c})]}),e.jsxs("span",{style:D,children:[ks(S.balanceFormatted)," \u2022"," ",O.getChainName(S.chainId)]})]})]},`${S.address}-${S.chainId}`))]}),document.body)]})},co=({assets:t,selectedAsset:s,onAssetSelect:n,onAmountChange:a,disabled:i=!1,loading:l=!1,label:r="Select Asset",showBalance:c=!0,showMaxButton:d=!0,placeholder:p="0.0",theme:u,styles:x,maxAmount:g,hideAmountInput:f=!1,displayAmount:h,dark:b})=>{const m=u||Re.createTheme("dark"),{primaryColor:I,dark:W,dk:C}=z.useSpiceBrand(x,b),y=b??W,[B,D]=o.useState(!1),[R,S]=o.useState(null),[A,w]=o.useState(null),[M,J]=o.useState(s?.amount||""),T=o.useRef(null),j=o.useRef("");o.useEffect(()=>{const F=s?.asset?`${s.asset.chainId}-${s.asset.address}`:"";F!==j.current&&(J(s?.amount||""),j.current=F)},[s?.asset?.chainId,s?.asset?.address,s?.amount]);const E=F=>{let L=F;L.startsWith(".")&&(L="0"+L);const $=$s(L);if(!$){J($),T.current&&clearTimeout(T.current),T.current=setTimeout(()=>{a($)},300);return}if(g&&parseFloat($)>parseFloat(g)){J(g),T.current&&clearTimeout(T.current),T.current=setTimeout(()=>{a(g)},300);return}if(s?.asset){const me=parseFloat($),we=s.asset.balanceFormatted;if(!isNaN(me)&&me>we){const re=(Math.floor(we*1e6)/1e6).toString();J(re),T.current&&clearTimeout(T.current),T.current=setTimeout(()=>{a(re)},300);return}}J($),T.current&&clearTimeout(T.current),T.current=setTimeout(()=>{a($)},300)},Q=F=>{if(s?.asset){const L=s.asset.balanceFormatted*F/100;let $=Math.floor(L*1e6)/1e6;g&&$>parseFloat(g)&&($=parseFloat(g));const me=$.toString();J(me),T.current&&clearTimeout(T.current),a(me)}},Y=s?.asset?.balanceFormatted??0,U=parseFloat(M)||0,G=Y>0?U/Y*100:0;o.useEffect(()=>()=>{T.current&&clearTimeout(T.current)},[]);const ie={backgroundColor:x?.assetSelector?.backgroundColor||x?.secondaryBackground||(y?C.cardBg:"#e9e9e9"),border:y?`0.5px solid ${C.cardBorder}`:"0.5px solid #A8A8A7",borderRadius:x?.assetSelector?.borderRadius||"6px",padding:x?.assetSelector?.padding||"16px",height:"auto",minHeight:f?void 0:"144px",display:"flex",flexDirection:"column",gap:"8px",position:"relative",opacity:i?.6:1};return l?e.jsx("div",{style:ie,children:e.jsxs("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[e.jsx("div",{style:{backgroundColor:y?C.hoverBg:"#d1d5db",borderRadius:"4px",height:"16px",width:"60px"}}),e.jsx("div",{style:{backgroundColor:y?C.hoverBg:"#d1d5db",borderRadius:"4px",height:"40px",width:"150px"}})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:"8px"},children:[e.jsx("div",{style:{backgroundColor:y?C.hoverBg:"#d1d5db",borderRadius:"4px",height:"12px",width:"80px"}}),e.jsx("div",{style:{backgroundColor:y?C.hoverBg:"#d1d5db",borderRadius:"6px",height:"46px",width:"128px"}})]})]})}):e.jsxs("div",{style:ie,children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("span",{style:{fontFamily:x?.fontFamily||m.typography.fontFamily,fontSize:"16px",fontWeight:500,color:y?C.textSecondary:"#7d7c7b",lineHeight:"24px"},children:r}),c&&s?.asset&&e.jsxs("span",{style:{fontFamily:x?.fontFamily||m.typography.fontFamily,fontSize:"12px",fontWeight:500,color:y?C.textSecondary:"#71757a",lineHeight:"16px"},children:["Balance: ",ks(s.asset.balanceFormatted)]})]}),e.jsxs("div",{style:{display:"flex",justifyContent:f&&!h?"flex-start":"space-between",alignItems:"center",flex:1},children:[!f&&e.jsx("input",{type:"text",value:M,onChange:F=>E(F.target.value),placeholder:p,disabled:i||!s?.asset,style:{fontFamily:x?.fontFamily||m.typography.fontFamily,fontSize:"40px",fontWeight:700,color:i?y?"rgba(255, 255, 255, 0.16)":"rgba(14, 13, 11, 0.16)":M?y?"#ffffff":"#0e0d0b":y?"#4a5568":"#d1d5db",lineHeight:"1.08",letterSpacing:"-1.2px",backgroundColor:"transparent",border:"none",outline:"none",padding:0,width:"100%",maxWidth:"200px"}}),e.jsx("div",{style:{width:"128px",position:"relative",flexShrink:0},children:e.jsx(lo,{selectedAsset:s,assets:t,onAssetSelect:n,showDropdown:B,onToggleDropdown:()=>D(!B),disabled:i,theme:m})}),f&&h&&e.jsx("span",{style:{fontFamily:x?.fontFamily||m.typography.fontFamily,fontSize:"40px",fontWeight:700,color:y?"#ffffff":"#0e0d0b",lineHeight:"1.08",letterSpacing:"-1.2px",textAlign:"right",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:h})]}),!f&&e.jsx("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",height:"14px"},children:[0,25,50,75,100].map((F,L)=>{const $=Math.abs(G-F)<1,me=L===4,we=F/100,re=R===F,le=A===F;return e.jsx("button",{onClick:()=>Q(F),onMouseEnter:()=>S(F),onMouseLeave:()=>{S(null),w(null)},onMouseDown:()=>w(F),onMouseUp:()=>w(null),disabled:i||!s?.asset,title:`${F}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:i||!s?.asset?"not-allowed":"pointer",opacity:$?1:re?.8:.5,transform:le?"scale(0.85)":re?"scale(1.15)":"scale(1)",transition:"all 0.15s ease"},children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[e.jsx("circle",{cx:"7",cy:"7",r:"6.84375",fill:me?I:"none",stroke:me?I:y?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!me&&we>0&&e.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${we>.5?1:0} 1 ${7+6.84375*Math.sin(we*2*Math.PI)} ${7-6.84375*Math.cos(we*2*Math.PI)} Z`,fill:y?C.textSecondary:"#3C3E42"})]})},F)})})]})},as=co,uo=()=>{const[t,s]=o.useState(!1);let n=null,a=null;try{n=ds.useDynamicContext()}catch(u){a=u instanceof Error?u.message:String(u)}if(o.useEffect(()=>{s(!0)},[]),a)return{isReady:!1,isAuthenticated:!1,isConnected:!1,provider:"dynamic",actions:{signAuthorization:async()=>{throw new Error("Dynamic context not available")},signMessage:async()=>{throw new Error("Dynamic context not available")},getEthereumProvider:async()=>{throw new Error("Dynamic context not available")}}};const{user:i,primaryWallet:l,connectedWallets:r}=n||{},c=Tt.getDynamicEmbeddedWallet({connectedWallets:r,primaryWallet:l})||l,d=!!i,p=c?.address;return{isReady:t&&!!n,isAuthenticated:d,isConnected:d&&!!p,address:p,provider:"dynamic",actions:{signAuthorization:async u=>{if(!c)throw new Error("Dynamic embedded wallet not available");const{isEthereumWallet:x}=await import("@dynamic-labs/ethereum");if(!x(c))throw new Error("Embedded wallet is not an Ethereum wallet");const g=c.connector,f={address:c.address,chainId:u.chainId,contractAddress:u.contractAddress,nonce:u.nonce},h={address:u.contractAddress,chainId:u.chainId,nonce:u.nonce},b=typeof g?.getWaasWalletClient=="function"?await g.getWaasWalletClient():null;if(b&&typeof b.signRawMessage=="function"){const{hashAuthorization:m}=await import("viem/experimental"),{parseSignature:I}=await import("viem"),W={address:u.contractAddress,chainId:u.chainId,nonce:u.nonce},C=g.getSignedSessionId,y=typeof C=="function"?await C.call(g):void 0,B=g.getAuthToken,D=typeof B=="function"?B.call(g):void 0,R=await b.signRawMessage({accountAddress:c.address,authToken:D,context:{eip7702Auth:W},message:m(W).slice(2),signedSessionId:y}),S=I(R);return{address:f.contractAddress,chainId:f.chainId,contractAddress:f.contractAddress,nonce:BigInt(f.nonce),r:S.r,s:S.s,yParity:Number(S.yParity)}}if(typeof g?.signAuthorization=="function"){typeof g.switchNetwork=="function"&&await g.switchNetwork({networkChainId:u.chainId});const m=await g.signAuthorization(h);return Tt.normalizeAuthorization(m,f)}throw new Error("Dynamic embedded wallet does not support EIP-7702 authorization. Ensure @dynamic-labs packages are v4.15+.")},signMessage:async u=>{if(!c)throw new Error("Dynamic embedded wallet not available");const{isEthereumWallet:x}=await import("@dynamic-labs/ethereum");if(!x(c))throw new Error("Embedded wallet is not an Ethereum wallet");const g=typeof u=="object"&&"raw"in u?{raw:u.raw}:u,f=await c.getWalletClient();if(!f)throw new Error("Dynamic wallet client not available");return{signature:await f.signMessage({message:g,account:c.address})}},getEthereumProvider:async()=>{if(!c)throw new Error("Dynamic embedded wallet not available");const{isEthereumWallet:u}=await import("@dynamic-labs/ethereum");if(!u(c))throw new Error("Embedded wallet is not an Ethereum wallet");return Tt.getProviderEthereumProvider(c)}}}},Ut=()=>{const t=o.useContext(z.SpiceFlowProviderContext),s=t?.mode||"7702";let n=null,a=null;try{n=Zt.useWallets(),{user:a}=Zt.usePrivy()}catch{n=null}const i=n?.wallets?.find(d=>d.connectorType==="embedded")?.address,l=a?.wallet?.address;let r=null;try{r=ds.useDynamicContext()}catch{r=null}const c=(Tt.getDynamicEmbeddedWallet(r)||r?.primaryWallet)?.address;if(!(!t||s!=="7702"))return t.provider==="privy"?i??l:t.provider==="dynamic"?c:i??l??c},po=()=>{const t=o.useContext(z.SpiceFlowProviderContext)?.mode,{isConnected:s,address:n}=Qe.useAccount();let a=null,i=null,l=null,r=null,c=null;try{a=Zt.usePrivy(),i=Zt.useSign7702Authorization(),l=Zt.useSignMessage(),r=Zt.useWallets()}catch(g){c=g instanceof Error?g.message:String(g)}if(c)return t==="ondemand"&&s&&n?{isReady:!0,isAuthenticated:!0,isConnected:!0,address:n,provider:"privy",actions:{signAuthorization:async()=>{throw new Error("Not available in ondemand mode")},signMessage:async()=>{throw new Error("Not available in ondemand mode")},getEthereumProvider:async()=>{throw new Error("Not available in ondemand mode")}}}:{isReady:!1,isAuthenticated:!1,isConnected:!1,provider:null,actions:{signAuthorization:async()=>{throw new Error("Privy not available")},signMessage:async()=>{throw new Error("Privy not available")},getEthereumProvider:async()=>{throw new Error("Privy not available")}}};const{ready:d=!1,authenticated:p=!1}=a||{},u=Ut(),x=r?.wallets?.find(g=>g.connectorType==="embedded");return{isReady:t==="ondemand"?!0:d,isAuthenticated:t==="ondemand"?!0:p,isConnected:t==="ondemand"&&s&&!!n||d&&p&&!!u,address:t==="ondemand"&&!u&&s?n:u,provider:"privy",actions:{signAuthorization:async g=>{if(!i)throw new Error("Privy sign authorization not available");try{const f=await i.signAuthorization({contractAddress:g.contractAddress,chainId:g.chainId,nonce:g.nonce},{address:u});return delete f.v,f}catch(f){const h=f?.message||String(f);throw h.includes("not configured")||h.includes("chain")?new Error(`Chain ${g.chainId} is not configured in PrivyProvider. Add this chain to your Privy dashboard or supportedChainIds.`):f}},signMessage:async g=>{if(typeof g=="object"&&"raw"in g){if(!x)throw new Error("Embedded wallet not available for raw signing");const f=await x.getEthereumProvider();return{signature:await V.createWalletClient({account:x.address,transport:V.custom(f)}).signMessage({account:x.address,message:{raw:g.raw}})}}if(!l)throw new Error("Privy sign message not available");return{signature:(await l.signMessage({message:g})).signature}},getEthereumProvider:async()=>{if(!x)throw new Error("Embedded wallet not available");return x.getEthereumProvider()}}}},zt=()=>{const t=o.useContext(z.SpiceFlowProviderContext)?.provider,s=po(),n=uo();return t==="privy"?s:t==="dynamic"?n:{isReady:!1,isAuthenticated:!1,isConnected:!1,provider:null,actions:{signAuthorization:async()=>{throw new Error("No wallet provider available")},signMessage:async()=>{throw new Error("No wallet provider available")},getEthereumProvider:async()=>{throw new Error("No wallet provider available")}}}};async function Us(t,s=3,n=1e3){let a;for(let i=0;i<=s;i++)try{return await t()}catch(l){a=l instanceof Error?l:new Error(String(l)),i<s&&(console.warn(`[withRetry] Attempt ${i+1}/${s} failed: ${a.message}. Retrying in ${n}ms...`),await new Promise(r=>setTimeout(r,n)))}throw a}const _s=({isSuccess:t,type:s,chainName:n,explorerUrl:a,txHash:i,dark:l=!1,successBg:r="#d1fae5",successBorder:c="#6ee7b7",successText:d="#065f46",errorBg:p="#fee2e2",errorBorder:u="#fca5a5",errorText:x="#dc2626",textSecondary:g="#6b7280"})=>e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px",borderRadius:"8px",backgroundColor:t?r:p,border:t?`1px solid ${c}`:`1px solid ${u}`},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[e.jsx("div",{style:{width:"28px",height:"28px",borderRadius:"50%",backgroundColor:t?"#10b981":"#ef4444",display:"flex",alignItems:"center",justifyContent:"center"},children:t?e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:e.jsx("path",{d:"M11.6667 3.5L5.25 9.91667L2.33333 7",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}):e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:e.jsx("path",{d:"M10.5 3.5L3.5 10.5M3.5 3.5L10.5 10.5",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),e.jsxs("div",{children:[e.jsx("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:'"IBM Plex Mono", monospace',letterSpacing:"0.5px",color:t?d:x},children:t?`${s.toUpperCase()} CONFIRMED`:`${s.toUpperCase()} FAILED`}),e.jsxs("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:g},children:["on ",n]})]})]}),a&&i&&e.jsxs("a",{href:`${a}/tx/${i}`,target:"_blank",rel:"noopener noreferrer",style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"13px",color:g,textDecoration:"none",whiteSpace:"nowrap"},children:["View on explorer",e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:[e.jsx("path",{d:"M9 6.5V9.5C9 9.76522 8.89464 10.0196 8.70711 10.2071C8.51957 10.3946 8.26522 10.5 8 10.5H2.5C2.23478 10.5 1.98043 10.3946 1.79289 10.2071C1.60536 10.0196 1.5 9.76522 1.5 9.5V4C1.5 3.73478 1.60536 3.48043 1.79289 3.29289C1.98043 3.10536 2.23478 3 2.5 3H5.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M7.5 1.5H10.5V4.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M5 7L10.5 1.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})]})]})]}),ps=({isOpen:t,onClose:s,onComplete:n,closeOnComplete:a=!1,type:i,results:l,chainName:r="Network",explorerUrl:c,theme:d,styles:p,dark:u,intentStatus:x,onRetry:g,onNewTx:f,onRetryTx:h,asOverlay:b=!1,isProcessing:m=!1})=>{const I=d||Re.createTheme("light"),{primaryColor:W,dark:C,dk:y}=z.useSpiceBrand(p,u),[B,D]=o.useState(!1),R=C?y.cardBg:"#ffffff",S=C?"0 4px 20px rgba(0, 0, 0, 0.4)":"0 4px 20px rgba(0, 0, 0, 0.1)",A=C?"0 -4px 8px -2px rgba(0, 0, 0, 0.4)":"0 -4px 8px -2px rgba(0, 0, 0, 0.15)",w=C?y.textSecondary:"#6b7280",M=C?y.textPrimary:"#374151",J=C?y.inputBg:"#f9fafb",T=C?y.inputBorder:"#e5e7eb",j=C?y.inputBg:"#f3f4f6",E=C?y.inputBorder:"#e5e7eb",[Q,Y]=o.useState(!0),[U,G]=o.useState(null),[ie,F]=o.useState(null);o.useEffect(()=>{!t&&!x&&D(!1)},[t,x]);const L=()=>{D(!0),setTimeout(()=>{window.dispatchEvent(new CustomEvent("tx-complete",{detail:{type:i,results:l}})),window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:{type:i,status:"success",results:l}})),n?.(),a&&s()},300)},$=()=>{Y(!Q)};if(x){const{steps:re,overallStatus:le}=x,ce=le==="processing",Be=le==="success",ye=le==="failed",Te=re.filter(P=>P.transactionHash)[0],ue=re.length>1?re.map(P=>P.chainName).filter(Boolean).join(" and "):r!=="Network"?r:re[0]?.chainName||r,He=c||(Te?O.getExplorerUrl(Te.chainId,Te.transactionHash||"").replace(/\/tx\/.*$/,""):void 0),De=e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"16px"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:"pointer"},onClick:$,children:[e.jsxs("span",{style:{fontSize:"13px",fontWeight:500,color:w,fontFamily:p?.fontFamily||I.typography.fontFamily},children:[ce?`Processing ${i.charAt(0).toUpperCase()+i.slice(1)}`:`${i.charAt(0).toUpperCase()+i.slice(1)} results`," "]}),e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",style:{transform:Q?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.3s ease"},children:e.jsx("path",{d:"M4 6L8 10L12 6",stroke:w,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),!ce&&e.jsx("button",{onClick:s,onMouseEnter:()=>G("close"),onMouseLeave:()=>{G(null),F(null)},onMouseDown:()=>F("close"),onMouseUp:()=>F(null),style:{background:ie==="close"?C?y.hoverBg:"#f3f4f6":U==="close"?C?y.inputBg:"#f9fafb":"none",border:"none",borderRadius:"4px",cursor:"pointer",padding:"4px",display:"flex",alignItems:"center",justifyContent:"center",color:U==="close"||ie==="close"?M:w,transform:ie==="close"?"scale(0.9)":U==="close"?"scale(1.1)":"scale(1)",transition:"all 0.15s ease"},children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:e.jsx("path",{d:"M12 4L4 12M4 4L12 12",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),e.jsx("div",{style:{marginBottom:"16px"},children:ce?e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"20px 16px",borderRadius:"8px",backgroundColor:j,border:`1px solid ${E}`,gap:"12px"},children:[e.jsx(Re.Spinner,{size:24,borderWidth:3,color:W}),e.jsxs("div",{children:[e.jsx("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:'"IBM Plex Mono", monospace',letterSpacing:"0.5px",color:M},children:"PROCESSING TRANSACTION"}),e.jsxs("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:w},children:["on ",ue]})]})]}):e.jsx(_s,{isSuccess:Be,type:i,chainName:ue,explorerUrl:He,txHash:Te?.transactionHash,dark:C,...C?{successBg:y.successBg,successBorder:y.successBorder,successText:y.successText,errorBg:y.errorBg,errorBorder:y.errorBorder,errorText:y.errorText}:{},textSecondary:w})}),e.jsx("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:e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:re.map((P,Ie)=>{const Ee=P.transactionHash?O.getExplorerUrl(P.chainId,P.transactionHash):null;return e.jsxs("div",{style:{padding:"10px 12px",borderRadius:"6px",backgroundColor:J,border:`1px solid ${T}`,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("span",{style:{fontSize:"13px",color:M},children:P.chainName?`On ${P.chainName}`:P.description||`Step ${Ie+1}`}),e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:P.status==="success"?"#10b981":P.status==="failed"?"#ef4444":w,fontWeight:500},children:[Ee&&e.jsx("a",{href:Ee,target:"_blank",rel:"noopener noreferrer",style:{color:C?y.infoText:"#2563eb",textDecoration:"none"},onClick:ne=>ne.stopPropagation(),children:"View"}),P.status==="success"?"\u2713":P.status==="failed"?"\u2717":"\u25CB"]})]},Ie)})})}),!ce&&e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[ye&&g&&e.jsx(Re.Button,{variant:"outline",fullWidth:!0,onClick:g,theme:I,styles:{button:{backgroundColor:W}},children:"TRY AGAIN"}),f&&e.jsxs(Re.Button,{variant:"outline",fullWidth:!0,onClick:f,theme:I,styles:{button:{backgroundColor:W}},children:["NEW ",i.toUpperCase()," \u2192"]})]})]});return b?e.jsxs("div",{style:{position:"absolute",bottom:0,left:0,right:0,zIndex:10,animation:B?"slideDown 0.3s ease-in forwards":"slideUp 0.3s ease-out forwards",pointerEvents:"auto"},children:[e.jsx("div",{style:{backgroundColor:R,borderRadius:"12px 12px 0 0",width:"100%",padding:"18px 24px 24px",boxShadow:A},children:De}),e.jsx("style",{children:`
23
+ `})]})},_n={WALLET_DISCONNECTED:"Wallet is not connected.",WALLET_REJECTED:"Transaction was rejected.",SIGNATURE_FAILED:"Signature failed. Please try again.",CONCURRENT_EXECUTION:"A transaction is already in progress.",ABORT:"Transaction was cancelled.",NO_VENUE_FOR_CHAIN:"No swap venue available for this chain.",NO_LIQUIDITY:"No liquidity available for this swap pair.",VENUE_API_ERROR:"Swap service error. Please try again.",ROUTE_TOKEN_NOT_FOUND:"Token not found in the registry.",ROUTE_UNSUPPORTED_INPUT:"This input token is not supported.",ROUTE_STRATEGY_ERROR:"No viable route found for this swap.",INVALID_PARAMS:"Invalid parameters. Please check your inputs.",RELAYER_ERROR:"Relayer error. Please try again.",RELAYER_EXECUTE_ERROR:"Transaction execution failed. Please try again.",RELAYER_STATUS_ERROR:"Failed to check transaction status.",ON_CHAIN_REVERT:"Transaction reverted on-chain. Please verify your inputs.",POLLING_EXHAUSTED:"Transaction status check timed out. It may still complete.",POLLING_CONSECUTIVE_FAILURES:"Lost connection to transaction status. It may still complete.",ALL_ATTEMPTS_FAILED:"All attempts failed. Please try again."},eo=[{test:t=>t.includes("user rejected")||t.includes("user denied")||t.includes("user cancelled")||t.includes("rejected the request")||t.includes("action_rejected"),message:"Transaction was rejected."},{test:t=>t.includes("4001"),message:"Transaction was rejected."},{test:t=>t.includes("insufficient funds")||t.includes("insufficient balance"),message:"Insufficient funds for this transaction."},{test:t=>t.includes("internal json-rpc error")||t.includes("internal error")||t.includes("an internal error was received"),message:"RPC Network error. Try switching your RPC endpoint or try again."},{test:t=>t.includes("network error")||t.includes("failed to fetch")||t.includes("econnrefused")||t.includes("timeout"),message:"Network connection error. Please check your connection."},{test:t=>t.includes("does not match the target chain")||t.includes("current chain of the wallet"),message:"Wrong network detected. Please switch to the correct network and try again."},{test:t=>t.includes("nonce too low")||t.includes("nonce has already been used"),message:"Transaction conflict. Please try again."},{test:t=>t.includes("cannot estimate gas")||t.includes("gas required exceeds"),message:"Unable to estimate gas. The transaction may fail \u2014 please verify your inputs."},{test:t=>t.includes("execution reverted")||t.includes("transaction reverted"),message:"Transaction would fail on-chain. Please verify your inputs and try again."}],jt=(t,s="Something went wrong. Please try again.")=>{if(z.isSpiceflowError(t)){const a=_n[t.code];if(a)return a}const n=Gs(t).toLowerCase();for(const{test:a,message:i}of eo)if(a(n))return i;return s},to=t=>{if(z.isSpiceflowError(t))return t.code==="WALLET_REJECTED";const s=Gs(t).toLowerCase();return s.includes("user rejected")||s.includes("user denied")||s.includes("user cancelled")||s.includes("rejected the request")||s.includes("action_rejected")||s.includes("4001")};function Gs(t){if(!t)return"";if(typeof t=="string")return t;const s=t,n=s.message||s.reason||"",a=s.details||"";return`${n} ${a}`.trim()}var Js="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==",Ts="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=",so="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=";const Wt=K.getChainMeta(1)?.logo??"";K.getChainMeta(42161)?.logo;const cs=K.TOKENS.find(t=>t.symbol==="USDC")?.logo??"";K.TOKENS.find(t=>t.symbol==="WBTC")?.logo;const bt=Object.fromEntries([...K.getMainnetChains(),...K.getTestnetChains()].map(t=>[t.id,t.logo])),vs={metamask:Js,metaMask:Js,rabby:Ts,phantom:so},no=Object.fromEntries(K.TOKENS.map(t=>[t.symbol,t.logo])),Nt=({symbol:t,logoURI:s,size:n=20,theme:a})=>{const i=a||Re.createTheme("dark"),[l,r]=o.useState(!1),c={width:`${n}px`,height:`${n}px`,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:`${n*.4}px`,fontWeight:i.typography.fontWeight.bold,flexShrink:0,overflow:"hidden",backgroundColor:"#ffffff"},d=t.toUpperCase(),p=s||no[d];if(p&&!l)return e.jsx("img",{src:p,alt:t,style:{...c,objectFit:"cover"},onError:()=>r(!0)});const u=oo(t);return e.jsx("div",{style:{...c,...u.style},children:u.icon})},oo=t=>{const s=t.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"}}[s];if(n)return{style:{backgroundColor:n.bg,color:n.text},icon:n.icon||s.charAt(0)};const a=s.split("").reduce((c,d)=>d.charCodeAt(0)+((c<<5)-c),0),i=Math.abs(a)%360,l=`hsl(${i}, 60%, 50%)`,r=i>180?"#FFFFFF":"#000000";return{style:{backgroundColor:l,color:r},icon:s.charAt(0)}};var Ds="data:image/svg+xml,%3csvg width='15' height='15' viewBox='0 0 15 15' fill='none' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M7.5 7.49993V10.4999M7.5 4.96868V4.96784M14.25 7.5C14.25 11.2279 11.2279 14.25 7.5 14.25C3.77208 14.25 0.75 11.2279 0.75 7.5C0.75 3.77208 3.77208 0.75 7.5 0.75C11.2279 0.75 14.25 3.77208 14.25 7.5Z' stroke='%23ED6969' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3e%3c/svg%3e";const ro=({isOpen:t,onClose:s,onComplete:n,title:a="Testnet Airdrop",description:i="Request testnet tokens for your wallet. A small gas fee is required to process the airdrop.",chainId:l,airdropTag:r="default",walletAddress:c,airdropTokens:d,getChainConfig:p,getSupportedTokens:u})=>{const x=Re.createTheme("light"),{primaryColor:g}=z.useSpiceBrand(),[f,h]=o.useState(null),[b,m]=o.useState(null),{chain:I}=Qe.useAccount(),{data:W}=Qe.useWalletClient(),{switchChainAsync:C}=Qe.useSwitchChain(),y=o.useMemo(()=>u(l),[l,u]),B=o.useMemo(()=>y.filter(j=>!K.isNativeToken(j.address)),[y]),{data:D,refetch:R}=Qe.useReadContracts({contracts:B.map(j=>({address:j.address,abi:V.erc20Abi,functionName:"balanceOf",args:[c],chainId:l})),blockTag:"pending"}),S=o.useCallback(()=>{R();const j=setTimeout(R,2e3),E=setTimeout(R,4e3);return()=>{clearTimeout(j),clearTimeout(E)}},[R]);o.useEffect(()=>t?S():void 0,[t,S]),o.useEffect(()=>{let j;const E=()=>{j?.(),j=S()};return window.addEventListener("airdrop-complete",E),()=>{j?.(),window.removeEventListener("airdrop-complete",E)}},[S]);const A=o.useMemo(()=>{const j=[];return B.forEach((E,Q)=>{if(!d.some(ie=>ie.toUpperCase()===E.symbol.toUpperCase()))return;const Y=D?.[Q],U=Y?.status==="success"?Y.result:BigInt(0),G=Number(U)/Math.pow(10,E.decimals);j.push({address:E.address,symbol:E.symbol,name:E.name,decimals:E.decimals,balance:U,balanceFormatted:G})}),j},[B,D,d]),w=p(l),M="0x11126A138f34532D250CCf35531E5A2f398ce7d4",J=o.useCallback(async j=>{if(!c||!l){m({message:"Wallet not connected",type:"error"});return}if(!W){m({message:"Wallet client not available",type:"error"});return}h(j.address);try{I?.id!==l&&await C({chainId:l});const E=O.getClientForChain(l),Q=await E.getGasPrice(),Y=BigInt(21e3)*Q*BigInt(110)/BigInt(100),U=await W.sendTransaction({to:M,value:Y});await E.waitForTransactionReceipt({hash:U,timeout:6e4,pollingInterval:2e3,confirmations:1});const G=await z.relayerService.requestAirdrop({chainId:l,tokenId:j.symbol==="WBTC"?"mWBTC":j.symbol,wallet:c,tag:r});if(G.success){const ie=w?.blockExplorer;m({message:`Successfully airdropped ${j.symbol}!`,type:"success",linkText:G.txHash?"View Transaction":void 0,linkUrl:G.txHash&&ie?`${ie}/tx/${G.txHash}`:void 0}),window.dispatchEvent(new CustomEvent("airdrop-complete",{detail:{token:j.symbol,txHash:G.txHash}})),n&&n()}else m({message:G.errorMessage||"Airdrop failed",type:"error"})}catch(E){m({message:jt(E,"Airdrop request failed"),type:"error"})}finally{h(null)}},[c,l,W,I,C,r,w,n]),T=o.useCallback(()=>{window.dispatchEvent(new CustomEvent("airdrop-skipped"))},[s]);return e.jsxs(Ct,{isOpen:t,onClose:s,title:a,subtitle:e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"5px",backgroundColor:"#f9fafb",border:"1px solid #ed6969",borderRadius:"8px",padding:"10px",margin:"0 0 0 0"},children:[e.jsx("img",{src:Ds,alt:"Info",style:{width:"14px",height:"14px",marginTop:"2px",flexShrink:0}}),e.jsx("p",{style:{fontSize:"13px",color:"#374151",margin:0,lineHeight:"1.5"},children:i})]}),theme:x,maxWidth:"420px",children:[e.jsxs("div",{style:{padding:"0 24px 32px 24px"},children:[e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:A.length===0?e.jsx("p",{style:{textAlign:"center",color:"#6b7280",fontSize:"14px",padding:"20px 0"},children:"No airdrop tokens available for this chain."}):A.map(j=>{const E=f===j.address,Q=E||f!==null;return e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderRadius:"12px",border:"1px solid #e5e7eb",backgroundColor:"white",transition:"all 150ms ease"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[e.jsx(Nt,{symbol:j.symbol,size:36,theme:x}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:"16px",fontWeight:600,color:"#111827"},children:j.symbol}),e.jsxs("div",{style:{fontSize:"12px",color:"#6b7280",fontFamily:'"IBM Plex Mono", monospace'},children:["Balance:"," ",j.balanceFormatted?.toFixed(4)??"0.0000"]})]})]}),e.jsx(Re.Button,{variant:"outline",size:"sm",onClick:()=>J(j),disabled:Q,loading:E,theme:x,styles:{button:{backgroundColor:g}},children:"Get Airdrop"})]},j.address)})}),e.jsx(Re.Button,{variant:"outline",fullWidth:!0,onClick:T,disabled:f!==null,theme:x,styles:{button:{backgroundColor:g}},style:{marginTop:"20px"},children:"NEXT"})]}),b&&e.jsx(Ms,{message:b.message,type:b.type,linkText:b.linkText,linkUrl:b.linkUrl,onClose:()=>m(null)})]})},Ws=15,Ns=({checkStepStatus:t,pollingInterval:s=4e3,retryStep:n,maxRetries:a=3})=>{const[i,l]=o.useState(null),r=o.useRef(null),c=o.useRef(!1),d=o.useRef(!1),p=o.useRef(null),u=o.useRef({}),x=o.useRef(0),g=o.useRef(0),f=o.useCallback(()=>{r.current&&(clearInterval(r.current),r.current=null)},[]),h=o.useCallback(()=>{p.current=null,l(null),u.current={},x.current=0,g.current=0,f()},[f]),b=o.useCallback((m,I)=>{f(),c.current=!1,d.current=!1,u.current={},x.current=0,g.current=0;const W={intentId:m,steps:I.map(y=>({...y,status:"pending"})),overallStatus:"processing"};p.current=W,l(W);const C=async()=>{if(c.current||d.current)return;d.current=!0,g.current+=1;const y=g.current;try{const B=p.current;if(!B)return;const D=B.steps.map(w=>({...w}));let R=!0,S=!1;for(let w=0;w<D.length;w++){const M=D[w];if(M.status!=="success"){if((M.stepId===0||w>0&&D[w-1].status==="success")&&(M.status==="pending"||M.status==="processing"))try{const J=await t(m,M.stepId);if(x.current=0,J.data.status==="success")D[w]={...M,status:"success",transactionHash:J.data.transactionHash},w+1<D.length&&D[w+1].status==="pending"&&(D[w+1]={...D[w+1],status:"processing"});else if(J.data.status==="executing"||J.data.status==="created")D[w]={...M,status:"processing"};else if(J.data.status==="reverted"){const T=u.current[M.stepId]||0;if(n&&T<a){u.current[M.stepId]=T+1;try{await n(m,M.stepId)}catch(j){console.error(`[useStatus] Retry failed for step ${M.stepId}:`,j)}D[w]={...M,status:"processing"}}else D[w]={...M,status:"failed",transactionHash:J.data.transactionHash},S=!0}else D[w]={...M,status:"processing"}}catch(J){x.current+=1,console.error(`[useStatus] Poll #${y}: Error checking step ${M.stepId} (consecutive errors: ${x.current}/${Ws}):`,J),x.current>=Ws&&(console.error(`[useStatus] Too many consecutive polling errors (${Ws}). Marking step ${M.stepId} as failed.`),D[w]={...M,status:"failed"},S=!0)}D[w].status!=="success"&&(R=!1)}}const A={...B,steps:D,overallStatus:S?"failed":R?"success":"processing"};p.current=A,l(A),(R||S)&&(c.current=!0,f())}finally{d.current=!1}};C(),r.current=setInterval(C,s)},[t,s,f,n,a]);return o.useEffect(()=>()=>{f()},[f]),{intentStatus:i,startStatusPolling:b,stopStatusPolling:f,clearStatus:h}},os=({address:t,supportedChains:s,enabled:n=!0,refetchInterval:a})=>{const i=o.useContext(z.SpiceFlowProviderContext)?.apiUrl||z.RELAYER_API_URL,[l,r]=o.useState([]),[c,d]=o.useState(!1),[p,u]=o.useState(null),[x,g]=o.useState(!1),f=o.useRef(!1),h=o.useRef(!1),b=s?JSON.stringify([...s].sort()):"",m=o.useCallback(async(C=!1)=>{if(!t||!n){r([]),g(!1),f.current=!1;return}if(!h.current){h.current=!0,!f.current&&!C&&d(!0),u(null);try{const y=await fetch(`${i}/spicedeposit/${t}`);if(!y.ok)throw new Error(`Failed to fetch balance: ${y.status}`);const B=await y.json();if(B.success&&B.data?.tokens&&Array.isArray(B.data.tokens)){const D=new Map;B.data.tokens.forEach(S=>{const A=S.chainId,w=S.tokenAddress,M=S.amount;if(s&&!s.includes(A))return;const J=BigInt(M||"0");if(J>BigInt(0)){const T=O.getChainConfig(A),j=K.isNativeToken(w),E=j?K.ZERO_ADDRESS:w.toLowerCase();let Q=18,Y="TOKEN",U=w.slice(0,6)+"..."+w.slice(-4),G;if(j)Q=T?.nativeCurrency?.decimals||18,Y=T?.nativeCurrency?.symbol||"ETH",U=T?.nativeCurrency?.name||"Native Token";else{const F=T?.supportedTokens?.find(L=>L.address.toLowerCase()===w.toLowerCase());F&&(Q=F.decimals,Y=F.symbol,U=F.name,G=F.logo)}const ie=parseFloat((Number(J)/Math.pow(10,Q)).toFixed(6));if(ie>0){const F=`${E}-${A}`,L=D.get(F);if(L){const $=L.balance+J,me=parseFloat((Number($)/Math.pow(10,Q)).toFixed(6));D.set(F,{...L,balance:$,balanceFormatted:me})}else D.set(F,{address:E,symbol:Y,name:U,decimals:Q,chainId:A,balance:J,balanceFormatted:ie,balanceUsd:0,isNative:j,logoURI:G})}}});const R=Array.from(D.values());r(R),g(R.length>0),f.current=!0}else r([]),g(!1)}catch(y){const B=y instanceof Error?y.message:"Failed to fetch balance";u(B),console.error("Error fetching Spice assets:",y),f.current||(r([]),g(!1))}finally{d(!1),h.current=!1}}},[t,n,b,i]);o.useEffect(()=>{n&&t&&(f.current=!1,m(!1))},[t,n,b]),o.useEffect(()=>{if(!n||!t||!a)return;const C=setInterval(()=>{m(!0)},a);return()=>clearInterval(C)},[t,n,a,b]);const I=o.useCallback(C=>l.filter(y=>y.chainId===C),[l]),W=o.useCallback(async()=>{await m(!0)},[m]);return{assets:l,loading:c,error:p,hasBalance:x,refetch:W,getAssetsByChain:I}},ks=(t,s=4)=>!isFinite(t)||t===0?"0":t<1e-4?"< 0.0001":t.toFixed(s),rs=t=>isFinite(t)?t>0&&t<.01?"<$0.01":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}).format(t):"$0.00",ao=(t,s=6,n=4)=>t.length<=s+n?t:`${t.slice(0,s)}...${t.slice(-n)}`,$s=t=>{const s=t.replace(/[^0-9.]/g,""),n=s.split(".");return n.length>2?n[0]+"."+n.slice(1).join(""):s},io=async t=>{try{return await navigator.clipboard.writeText(t),!0}catch(s){return console.error("Failed to copy to clipboard:",s),!1}},us=({chainId:t,name:s,size:n=16})=>{const a=t&&(bt[t]||K.getChainMeta(t)?.logo)||"";return a?e.jsx("img",{src:a,alt:s||`Chain ${t}`,style:{width:`${n}px`,height:`${n}px`,borderRadius:"50%",objectFit:"cover",flexShrink:0}}):null},lo=({selectedAsset:t,assets:s,onAssetSelect:n,showDropdown:a,onToggleDropdown:i,disabled:l=!1,theme:r})=>{const c=r||Re.createTheme("dark"),d=o.useRef(null),p=o.useRef(null),u=o.useRef(null),[x,g]=o.useState(null);o.useEffect(()=>{if(a&&p.current){const S=()=>{if(p.current){const A=p.current.getBoundingClientRect();g({top:A.bottom+6,right:window.innerWidth-A.right})}};return S(),window.addEventListener("scroll",S,!0),window.addEventListener("resize",S),()=>{window.removeEventListener("scroll",S,!0),window.removeEventListener("resize",S)}}else g(null)},[a]),o.useEffect(()=>{const S=A=>{d.current&&!d.current.contains(A.target)&&u.current&&!u.current.contains(A.target)&&a&&i()};return a&&document.addEventListener("mousedown",S),()=>{document.removeEventListener("mousedown",S)}},[a,i]);const[f,h]=o.useState(!1),b={backgroundColor:"transparent",border:`1px solid ${c.mode==="light"?"#aaaaaa":c.colors.border}`,borderRadius:"6px",color:c.colors.text,cursor:l?"not-allowed":"pointer",padding:"8px 12px 8px 8px",width:"100%",display:"flex",flexDirection:"column",gap:"4px",opacity:l?.6:1,transition:"all 0.15s ease",transform:f?"scale(0.98)":"scale(1)"},m={display:"flex",justifyContent:"space-between",alignItems:"center"},I={display:"flex",alignItems:"center",gap:"4px",paddingTop:"4px",borderTop:`1px solid ${c.colors.border}`},W=()=>x?{position:"fixed",top:`${x.top}px`,right:`${x.right}px`,backgroundColor:c.colors.secondary,border:`1px solid ${c.colors.border}`,borderRadius:c.borderRadius.md,boxShadow:c.shadows.lg,zIndex:100,width:"200px",maxHeight:"300px",overflow:"auto"}:{},C={backgroundColor:"transparent",border:"none",color:c.colors.text,cursor:"pointer",padding:c.spacing.sm,width:"100%",display:"flex",alignItems:"center",gap:c.spacing.sm,transition:`background-color ${c.animation.normal}`,":hover":{backgroundColor:c.colors.surfaceHover}},y={display:"flex",flexDirection:"column",alignItems:"flex-start",flex:1},B={fontSize:c.typography.fontSize.sm,fontWeight:c.typography.fontWeight.medium},D={fontSize:c.typography.fontSize.xs,color:c.colors.textMuted},R={transition:`transform ${c.animation.normal}`,transform:a?"rotate(180deg)":"rotate(0deg)"};return e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{position:"relative"},ref:d,children:e.jsxs("div",{ref:p,style:b,onClick:l?void 0:i,onMouseLeave:()=>{h(!1)},onMouseDown:()=>h(!0),onMouseUp:()=>h(!1),children:[e.jsxs("div",{style:m,children:[e.jsx("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:t?.asset?e.jsxs(e.Fragment,{children:[e.jsx(Nt,{symbol:t.asset.symbol,logoURI:t.asset.logoURI,theme:c,size:24}),e.jsx("span",{style:{fontSize:"16px",fontWeight:500,color:c.colors.text,lineHeight:"1.5"},children:t.asset.symbol})]}):e.jsx("span",{style:{fontSize:"14px",color:c.colors.textMuted},children:"Select"})}),e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:c.colors.textMuted,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:R,children:e.jsx("path",{d:"M6 9l6 6 6-6"})})]}),t?.asset&&e.jsxs("div",{style:I,children:[e.jsx(us,{chainId:t.asset.chainId,theme:c}),e.jsx("span",{style:{fontSize:"11px",color:c.colors.textMuted},children:O.getChainName(t.asset.chainId)})]})]})}),a&&x&&Bs.createPortal(e.jsxs("div",{ref:u,style:W(),children:[s.length===0&&e.jsx("div",{style:{padding:"10px 12px",color:c.colors.textMuted,fontSize:c.typography.fontSize.xs},children:"No assets available"}),s.map(S=>e.jsxs("button",{style:C,onClick:()=>{n(S),i()},children:[e.jsx(Nt,{symbol:S.symbol,logoURI:S.logoURI,theme:c},`${S.address}-${S.chainId}`),e.jsxs("div",{style:y,children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:c.spacing.xs},children:[e.jsx("span",{style:B,children:S.symbol}),e.jsx(us,{chainId:S.chainId,theme:c})]}),e.jsxs("span",{style:D,children:[ks(S.balanceFormatted)," \u2022"," ",O.getChainName(S.chainId)]})]})]},`${S.address}-${S.chainId}`))]}),document.body)]})},co=({assets:t,selectedAsset:s,onAssetSelect:n,onAmountChange:a,disabled:i=!1,loading:l=!1,label:r="Select Asset",showBalance:c=!0,showMaxButton:d=!0,placeholder:p="0.0",theme:u,styles:x,maxAmount:g,hideAmountInput:f=!1,displayAmount:h,dark:b})=>{const m=u||Re.createTheme("dark"),{primaryColor:I,dark:W,dk:C}=z.useSpiceBrand(x,b),y=b??W,[B,D]=o.useState(!1),[R,S]=o.useState(null),[A,w]=o.useState(null),[M,J]=o.useState(s?.amount||""),T=o.useRef(null),j=o.useRef("");o.useEffect(()=>{const F=s?.asset?`${s.asset.chainId}-${s.asset.address}`:"";F!==j.current&&(J(s?.amount||""),j.current=F)},[s?.asset?.chainId,s?.asset?.address,s?.amount]);const E=F=>{let L=F;L.startsWith(".")&&(L="0"+L);const $=$s(L);if(!$){J($),T.current&&clearTimeout(T.current),T.current=setTimeout(()=>{a($)},300);return}if(g&&parseFloat($)>parseFloat(g)){J(g),T.current&&clearTimeout(T.current),T.current=setTimeout(()=>{a(g)},300);return}if(s?.asset){const me=parseFloat($),we=s.asset.balanceFormatted;if(!isNaN(me)&&me>we){const re=(Math.floor(we*1e6)/1e6).toString();J(re),T.current&&clearTimeout(T.current),T.current=setTimeout(()=>{a(re)},300);return}}J($),T.current&&clearTimeout(T.current),T.current=setTimeout(()=>{a($)},300)},Q=F=>{if(s?.asset){const L=s.asset.balanceFormatted*F/100;let $=Math.floor(L*1e6)/1e6;g&&$>parseFloat(g)&&($=parseFloat(g));const me=$.toString();J(me),T.current&&clearTimeout(T.current),a(me)}},Y=s?.asset?.balanceFormatted??0,U=parseFloat(M)||0,G=Y>0?U/Y*100:0;o.useEffect(()=>()=>{T.current&&clearTimeout(T.current)},[]);const ie={backgroundColor:x?.assetSelector?.backgroundColor||x?.secondaryBackground||(y?C.cardBg:"#e9e9e9"),border:y?`0.5px solid ${C.cardBorder}`:"0.5px solid #A8A8A7",borderRadius:x?.assetSelector?.borderRadius||"6px",padding:x?.assetSelector?.padding||"16px",height:"auto",minHeight:f?void 0:"144px",display:"flex",flexDirection:"column",gap:"8px",position:"relative",opacity:i?.6:1};return l?e.jsx("div",{style:ie,children:e.jsxs("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[e.jsx("div",{style:{backgroundColor:y?C.hoverBg:"#d1d5db",borderRadius:"4px",height:"16px",width:"60px"}}),e.jsx("div",{style:{backgroundColor:y?C.hoverBg:"#d1d5db",borderRadius:"4px",height:"40px",width:"150px"}})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:"8px"},children:[e.jsx("div",{style:{backgroundColor:y?C.hoverBg:"#d1d5db",borderRadius:"4px",height:"12px",width:"80px"}}),e.jsx("div",{style:{backgroundColor:y?C.hoverBg:"#d1d5db",borderRadius:"6px",height:"46px",width:"128px"}})]})]})}):e.jsxs("div",{style:ie,children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("span",{style:{fontFamily:x?.fontFamily||m.typography.fontFamily,fontSize:"16px",fontWeight:500,color:y?C.textSecondary:"#7d7c7b",lineHeight:"24px"},children:r}),c&&s?.asset&&e.jsxs("span",{style:{fontFamily:x?.fontFamily||m.typography.fontFamily,fontSize:"12px",fontWeight:500,color:y?C.textSecondary:"#71757a",lineHeight:"16px"},children:["Balance: ",ks(s.asset.balanceFormatted)]})]}),e.jsxs("div",{style:{display:"flex",justifyContent:f&&!h?"flex-start":"space-between",alignItems:"center",flex:1},children:[!f&&e.jsx("input",{type:"text",value:M,onChange:F=>E(F.target.value),placeholder:p,disabled:i||!s?.asset,style:{fontFamily:x?.fontFamily||m.typography.fontFamily,fontSize:"40px",fontWeight:700,color:i?y?"rgba(255, 255, 255, 0.16)":"rgba(14, 13, 11, 0.16)":M?y?"#ffffff":"#0e0d0b":y?"#4a5568":"#d1d5db",lineHeight:"1.08",letterSpacing:"-1.2px",backgroundColor:"transparent",border:"none",outline:"none",padding:0,width:"100%",maxWidth:"200px"}}),e.jsx("div",{style:{width:"128px",position:"relative",flexShrink:0},children:e.jsx(lo,{selectedAsset:s,assets:t,onAssetSelect:n,showDropdown:B,onToggleDropdown:()=>D(!B),disabled:i,theme:m})}),f&&h&&e.jsx("span",{style:{fontFamily:x?.fontFamily||m.typography.fontFamily,fontSize:"40px",fontWeight:700,color:y?"#ffffff":"#0e0d0b",lineHeight:"1.08",letterSpacing:"-1.2px",textAlign:"right",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:h})]}),!f&&e.jsx("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",height:"14px"},children:[0,25,50,75,100].map((F,L)=>{const $=Math.abs(G-F)<1,me=L===4,we=F/100,re=R===F,le=A===F;return e.jsx("button",{onClick:()=>Q(F),onMouseEnter:()=>S(F),onMouseLeave:()=>{S(null),w(null)},onMouseDown:()=>w(F),onMouseUp:()=>w(null),disabled:i||!s?.asset,title:`${F}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:i||!s?.asset?"not-allowed":"pointer",opacity:$?1:re?.8:.5,transform:le?"scale(0.85)":re?"scale(1.15)":"scale(1)",transition:"all 0.15s ease"},children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[e.jsx("circle",{cx:"7",cy:"7",r:"6.84375",fill:me?I:"none",stroke:me?I:y?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!me&&we>0&&e.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${we>.5?1:0} 1 ${7+6.84375*Math.sin(we*2*Math.PI)} ${7-6.84375*Math.cos(we*2*Math.PI)} Z`,fill:y?C.textSecondary:"#3C3E42"})]})},F)})})]})},as=co,uo=()=>{const[t,s]=o.useState(!1);let n=null,a=null;try{n=ds.useDynamicContext()}catch(u){a=u instanceof Error?u.message:String(u)}if(o.useEffect(()=>{s(!0)},[]),a)return{isReady:!1,isAuthenticated:!1,isConnected:!1,provider:"dynamic",actions:{signAuthorization:async()=>{throw new Error("Dynamic context not available")},signMessage:async()=>{throw new Error("Dynamic context not available")},getEthereumProvider:async()=>{throw new Error("Dynamic context not available")}}};const{user:i,primaryWallet:l,connectedWallets:r}=n||{},c=Tt.getDynamicEmbeddedWallet({connectedWallets:r,primaryWallet:l})||l,d=!!i,p=c?.address;return{isReady:t&&!!n,isAuthenticated:d,isConnected:d&&!!p,address:p,provider:"dynamic",actions:{signAuthorization:async u=>{if(!c)throw new Error("Dynamic embedded wallet not available");const{isEthereumWallet:x}=await import("@dynamic-labs/ethereum");if(!x(c))throw new Error("Embedded wallet is not an Ethereum wallet");const g=c.connector,f={address:c.address,chainId:u.chainId,contractAddress:u.contractAddress,nonce:u.nonce},h={address:u.contractAddress,chainId:u.chainId,nonce:u.nonce},b=typeof g?.getWaasWalletClient=="function"?await g.getWaasWalletClient():null;if(b&&typeof b.signRawMessage=="function"){const{hashAuthorization:m}=await import("viem/experimental"),{parseSignature:I}=await import("viem"),W={address:u.contractAddress,chainId:u.chainId,nonce:u.nonce},C=g.getSignedSessionId,y=typeof C=="function"?await C.call(g):void 0,B=g.getAuthToken,D=typeof B=="function"?B.call(g):void 0,R=await b.signRawMessage({accountAddress:c.address,authToken:D,context:{eip7702Auth:W},message:m(W).slice(2),signedSessionId:y}),S=I(R);return{address:f.contractAddress,chainId:f.chainId,contractAddress:f.contractAddress,nonce:BigInt(f.nonce),r:S.r,s:S.s,yParity:Number(S.yParity)}}if(typeof g?.signAuthorization=="function"){typeof g.switchNetwork=="function"&&await g.switchNetwork({networkChainId:u.chainId});const m=await g.signAuthorization(h);return Tt.normalizeAuthorization(m,f)}throw new Error("Dynamic embedded wallet does not support EIP-7702 authorization. Ensure @dynamic-labs packages are v4.15+.")},signMessage:async u=>{if(!c)throw new Error("Dynamic embedded wallet not available");const{isEthereumWallet:x}=await import("@dynamic-labs/ethereum");if(!x(c))throw new Error("Embedded wallet is not an Ethereum wallet");const g=typeof u=="object"&&"raw"in u?{raw:u.raw}:u,f=await c.getWalletClient();if(!f)throw new Error("Dynamic wallet client not available");return{signature:await f.signMessage({message:g,account:c.address})}},getEthereumProvider:async()=>{if(!c)throw new Error("Dynamic embedded wallet not available");const{isEthereumWallet:u}=await import("@dynamic-labs/ethereum");if(!u(c))throw new Error("Embedded wallet is not an Ethereum wallet");return Tt.getProviderEthereumProvider(c)}}}},Ut=()=>{const t=o.useContext(z.SpiceFlowProviderContext),s=t?.mode||"7702";let n=null,a=null;try{n=Zt.useWallets(),{user:a}=Zt.usePrivy()}catch{n=null}const i=n?.wallets?.find(d=>d.connectorType==="embedded")?.address,l=a?.wallet?.address;let r=null;try{r=ds.useDynamicContext()}catch{r=null}const c=(Tt.getDynamicEmbeddedWallet(r)||r?.primaryWallet)?.address;if(!(!t||s!=="7702"))return t.provider==="privy"?i??l:t.provider==="dynamic"?c:i??l??c},po=()=>{const t=o.useContext(z.SpiceFlowProviderContext)?.mode,{isConnected:s,address:n}=Qe.useAccount();let a=null,i=null,l=null,r=null,c=null;try{a=Zt.usePrivy(),i=Zt.useSign7702Authorization(),l=Zt.useSignMessage(),r=Zt.useWallets()}catch(g){c=g instanceof Error?g.message:String(g)}if(c)return t==="ondemand"&&s&&n?{isReady:!0,isAuthenticated:!0,isConnected:!0,address:n,provider:"privy",actions:{signAuthorization:async()=>{throw new Error("Not available in ondemand mode")},signMessage:async()=>{throw new Error("Not available in ondemand mode")},getEthereumProvider:async()=>{throw new Error("Not available in ondemand mode")}}}:{isReady:!1,isAuthenticated:!1,isConnected:!1,provider:null,actions:{signAuthorization:async()=>{throw new Error("Privy not available")},signMessage:async()=>{throw new Error("Privy not available")},getEthereumProvider:async()=>{throw new Error("Privy not available")}}};const{ready:d=!1,authenticated:p=!1}=a||{},u=Ut(),x=r?.wallets?.find(g=>g.connectorType==="embedded");return{isReady:t==="ondemand"?!0:d,isAuthenticated:t==="ondemand"?!0:p,isConnected:t==="ondemand"&&s&&!!n||d&&p&&!!u,address:t==="ondemand"&&!u&&s?n:u,provider:"privy",actions:{signAuthorization:async g=>{if(!i)throw new Error("Privy sign authorization not available");try{const f=await i.signAuthorization({contractAddress:g.contractAddress,chainId:g.chainId,nonce:g.nonce},{address:u});return delete f.v,f}catch(f){const h=f?.message||String(f);throw h.includes("not configured")||h.includes("chain")?new Error(`Chain ${g.chainId} is not configured in PrivyProvider. Add this chain to your Privy dashboard or supportedChainIds.`):f}},signMessage:async g=>{if(typeof g=="object"&&"raw"in g){if(!x)throw new Error("Embedded wallet not available for raw signing");const f=await x.getEthereumProvider();return{signature:await V.createWalletClient({account:x.address,transport:V.custom(f)}).signMessage({account:x.address,message:{raw:g.raw}})}}if(!l)throw new Error("Privy sign message not available");return{signature:(await l.signMessage({message:g})).signature}},getEthereumProvider:async()=>{if(!x)throw new Error("Embedded wallet not available");return x.getEthereumProvider()}}}},zt=()=>{const t=o.useContext(z.SpiceFlowProviderContext)?.provider,s=po(),n=uo();return t==="privy"?s:t==="dynamic"?n:{isReady:!1,isAuthenticated:!1,isConnected:!1,provider:null,actions:{signAuthorization:async()=>{throw new Error("No wallet provider available")},signMessage:async()=>{throw new Error("No wallet provider available")},getEthereumProvider:async()=>{throw new Error("No wallet provider available")}}}};async function Us(t,s=3,n=1e3){let a;for(let i=0;i<=s;i++)try{return await t()}catch(l){a=l instanceof Error?l:new Error(String(l)),i<s&&(console.warn(`[withRetry] Attempt ${i+1}/${s} failed: ${a.message}. Retrying in ${n}ms...`),await new Promise(r=>setTimeout(r,n)))}throw a}const _s=({isSuccess:t,type:s,chainName:n,explorerUrl:a,txHash:i,dark:l=!1,successBg:r="#d1fae5",successBorder:c="#6ee7b7",successText:d="#065f46",errorBg:p="#fee2e2",errorBorder:u="#fca5a5",errorText:x="#dc2626",textSecondary:g="#6b7280"})=>e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px",borderRadius:"8px",backgroundColor:t?r:p,border:t?`1px solid ${c}`:`1px solid ${u}`},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[e.jsx("div",{style:{width:"28px",height:"28px",borderRadius:"50%",backgroundColor:t?"#10b981":"#ef4444",display:"flex",alignItems:"center",justifyContent:"center"},children:t?e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:e.jsx("path",{d:"M11.6667 3.5L5.25 9.91667L2.33333 7",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}):e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:e.jsx("path",{d:"M10.5 3.5L3.5 10.5M3.5 3.5L10.5 10.5",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),e.jsxs("div",{children:[e.jsx("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:'"IBM Plex Mono", monospace',letterSpacing:"0.5px",color:t?d:x},children:t?`${s.toUpperCase()} CONFIRMED`:`${s.toUpperCase()} FAILED`}),e.jsxs("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:g},children:["on ",n]})]})]}),a&&i&&e.jsxs("a",{href:`${a}/tx/${i}`,target:"_blank",rel:"noopener noreferrer",style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"13px",color:g,textDecoration:"none",whiteSpace:"nowrap"},children:["View on explorer",e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:[e.jsx("path",{d:"M9 6.5V9.5C9 9.76522 8.89464 10.0196 8.70711 10.2071C8.51957 10.3946 8.26522 10.5 8 10.5H2.5C2.23478 10.5 1.98043 10.3946 1.79289 10.2071C1.60536 10.0196 1.5 9.76522 1.5 9.5V4C1.5 3.73478 1.60536 3.48043 1.79289 3.29289C1.98043 3.10536 2.23478 3 2.5 3H5.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M7.5 1.5H10.5V4.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M5 7L10.5 1.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})]})]})]}),ps=({isOpen:t,onClose:s,onComplete:n,closeOnComplete:a=!1,type:i,results:l,chainName:r="Network",explorerUrl:c,theme:d,styles:p,dark:u,intentStatus:x,onRetry:g,onNewTx:f,onRetryTx:h,asOverlay:b=!1,isProcessing:m=!1})=>{const I=d||Re.createTheme("light"),{primaryColor:W,dark:C,dk:y}=z.useSpiceBrand(p,u),[B,D]=o.useState(!1),R=C?y.cardBg:"#ffffff",S=C?"0 4px 20px rgba(0, 0, 0, 0.4)":"0 4px 20px rgba(0, 0, 0, 0.1)",A=C?"0 -4px 8px -2px rgba(0, 0, 0, 0.4)":"0 -4px 8px -2px rgba(0, 0, 0, 0.15)",w=C?y.textSecondary:"#6b7280",M=C?y.textPrimary:"#374151",J=C?y.inputBg:"#f9fafb",T=C?y.inputBorder:"#e5e7eb",j=C?y.inputBg:"#f3f4f6",E=C?y.inputBorder:"#e5e7eb",[Q,Y]=o.useState(!0),[U,G]=o.useState(null),[ie,F]=o.useState(null);o.useEffect(()=>{!t&&!x&&D(!1)},[t,x]);const L=()=>{D(!0),setTimeout(()=>{window.dispatchEvent(new CustomEvent("tx-complete",{detail:{type:i,results:l}})),window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:{type:i,status:"success",results:l}})),n?.(),a&&s()},300)},$=()=>{Y(!Q)};if(x){const{steps:re,overallStatus:le}=x,ce=le==="processing",Be=le==="success",ye=le==="failed",Te=re.filter(P=>P.transactionHash)[0],ue=re.length>1?re.map(P=>P.chainName).filter(Boolean).join(" and "):r!=="Network"?r:re[0]?.chainName||r,He=c||(Te?O.getExplorerUrl(Te.chainId,Te.transactionHash||"").replace(/\/tx\/.*$/,""):void 0),De=e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"16px"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:"pointer"},onClick:$,children:[e.jsxs("span",{style:{fontSize:"13px",fontWeight:500,color:w,fontFamily:p?.fontFamily||I.typography.fontFamily},children:[ce?`Processing ${i.charAt(0).toUpperCase()+i.slice(1)}`:`${i.charAt(0).toUpperCase()+i.slice(1)} results`," "]}),e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",style:{transform:Q?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.3s ease"},children:e.jsx("path",{d:"M4 6L8 10L12 6",stroke:w,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),!ce&&e.jsx("button",{onClick:s,onMouseEnter:()=>G("close"),onMouseLeave:()=>{G(null),F(null)},onMouseDown:()=>F("close"),onMouseUp:()=>F(null),style:{background:ie==="close"?C?y.hoverBg:"#f3f4f6":U==="close"?C?y.inputBg:"#f9fafb":"none",border:"none",borderRadius:"4px",cursor:"pointer",padding:"4px",display:"flex",alignItems:"center",justifyContent:"center",color:U==="close"||ie==="close"?M:w,transform:ie==="close"?"scale(0.9)":U==="close"?"scale(1.1)":"scale(1)",transition:"all 0.15s ease"},children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:e.jsx("path",{d:"M12 4L4 12M4 4L12 12",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),e.jsx("div",{style:{marginBottom:"16px"},children:ce?e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"20px 16px",borderRadius:"8px",backgroundColor:j,border:`1px solid ${E}`,gap:"12px"},children:[e.jsx(Re.Spinner,{size:24,borderWidth:3,color:W}),e.jsxs("div",{children:[e.jsx("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:'"IBM Plex Mono", monospace',letterSpacing:"0.5px",color:M},children:"PROCESSING TRANSACTION"}),e.jsxs("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:w},children:["on ",ue]})]})]}):e.jsx(_s,{isSuccess:Be,type:i,chainName:ue,explorerUrl:He,txHash:Te?.transactionHash,dark:C,...C?{successBg:y.successBg,successBorder:y.successBorder,successText:y.successText,errorBg:y.errorBg,errorBorder:y.errorBorder,errorText:y.errorText}:{},textSecondary:w})}),e.jsx("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:e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:re.map((P,Ie)=>{const Ee=P.transactionHash?O.getExplorerUrl(P.chainId,P.transactionHash):null;return e.jsxs("div",{style:{padding:"10px 12px",borderRadius:"6px",backgroundColor:J,border:`1px solid ${T}`,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("span",{style:{fontSize:"13px",color:M},children:P.chainName?`On ${P.chainName}`:P.description||`Step ${Ie+1}`}),e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:P.status==="success"?"#10b981":P.status==="failed"?"#ef4444":w,fontWeight:500},children:[Ee&&e.jsx("a",{href:Ee,target:"_blank",rel:"noopener noreferrer",style:{color:C?y.infoText:"#2563eb",textDecoration:"none"},onClick:ne=>ne.stopPropagation(),children:"View"}),P.status==="success"?"\u2713":P.status==="failed"?"\u2717":"\u25CB"]})]},Ie)})})}),!ce&&e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[ye&&g&&e.jsx(Re.Button,{variant:"outline",fullWidth:!0,onClick:g,theme:I,styles:{button:{backgroundColor:W}},children:"TRY AGAIN"}),f&&e.jsxs(Re.Button,{variant:"outline",fullWidth:!0,onClick:f,theme:I,styles:{button:{backgroundColor:W}},children:["NEW ",i.toUpperCase()," \u2192"]})]})]});return b?e.jsxs("div",{style:{position:"absolute",bottom:0,left:0,right:0,zIndex:10,animation:B?"slideDown 0.3s ease-in forwards":"slideUp 0.3s ease-out forwards",pointerEvents:"auto"},children:[e.jsx("div",{style:{backgroundColor:R,borderRadius:"12px 12px 0 0",width:"100%",padding:"18px 24px 24px",boxShadow:A},children:De}),e.jsx("style",{children:`
24
24
  @keyframes slideUp {
25
25
  from { transform: translateY(100%); }
26
26
  to { transform: translateY(0); }
@@ -111,7 +111,7 @@
111
111
  from { transform: rotate(0deg); }
112
112
  to { transform: rotate(360deg); }
113
113
  }
114
- `})]})},nr=({color:t})=>e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",style:{marginTop:"1px",flexShrink:0},children:[e.jsx("circle",{cx:"7",cy:"7",r:"6.5",stroke:t,strokeWidth:"1.2"}),e.jsx("path",{d:"M7 6v4",stroke:t,strokeWidth:"1.2",strokeLinecap:"round"}),e.jsx("circle",{cx:"7",cy:"4.5",r:"0.7",fill:t})]}),or=({isOpen:t,onClose:s,lockBatches:n,lockTokenSymbol:a,lockTokenLogoURI:i,destinationInputHook:l,sourceAssetInputHook:r,lockDurationHook:c,lockChainId:d,durationOptions:p,votingPowerEstimate:u,sourceChains:x,sourceAssets:g=[],escrowAddress:f,includeWalletAssets:h=!1,destinationTokenAddress:b,onLockSuccess:m,onLockExecute:I,sourceToDestinationConversionRate:W,estimatedOutputAmount:C,onAddFunds:y,styles:B,dark:D=!1})=>{const{theme:R,dark:S,primaryColor:A,dk:w}=z.useSpiceBrand(B,D),M=R.typography.fontFamily,J=o.useContext(z.SpiceFlowProviderContext),T=(J?.mode||"7702")!=="7702",j=S?w.cardBg:B?.assetSelector?.backgroundColor||B?.secondaryBackground||"#e9e9e9",E=S?`1px solid ${w.cardBorder}`:"0.5px solid #A8A8A7",Q=S?"12px":"6px",Y=S?w.textPrimary:"#111827",U=S?w.textSecondary:"#6b7280",G=o.useMemo(()=>({...B,assetSelector:{...B?.assetSelector,backgroundColor:S?w.cardBg:B?.assetSelector?.backgroundColor,borderRadius:S?"12px":B?.assetSelector?.borderRadius},secondaryBackground:S?w.cardBg:B?.secondaryBackground}),[B,S]),ie=o.useMemo(()=>S?{...R,colors:{...R.colors,secondary:w.cardBg,surfaceHover:w.hoverBg,border:w.cardBorder,borderHover:w.inputBorder}}:R,[S,R]),[F,L]=o.useState(null),[$,me]=o.useState(0),we=c?.selectedDurationIdx??$,re=c?.setSelectedDurationIdx??me,[le,ce]=o.useState(!1),[Be,ye]=o.useState(null),[Te,ue]=o.useState(!1),[He,De]=o.useState(!1),[P,Ie]=o.useState(null);Qe.useWalletClient(),Qe.useSwitchChain();const{chain:Ee,address:ne}=Qe.useAccount();Qe.useConfig();const We=o.useRef(Ee);o.useEffect(()=>{We.current=Ee},[Ee]);const ze=zt(),{isReady:Z,isAuthenticated:ee,isConnected:v,address:k,provider:se,actions:ae}=ze,{intentStatus:N,startStatusPolling:X,clearStatus:de}=Ns({checkStepStatus:(te,xe)=>z.relayerService.checkStepStatus(te,xe),retryStep:async(te,xe)=>{const[Ge,tt]=te.split("/"),lt=parseInt(tt||"0",10);await z.relayerService.executeStep(Ge,lt,xe,{action:"execute"})},maxRetries:3}),{assets:pe,refetch:ke}=os({address:k,supportedChains:x,enabled:v&&!T,refetchInterval:3e4}),ot=o.useMemo(()=>{if(g.length===0)return pe;const te=new Set(g.map(xe=>xe.toLowerCase()));return pe.filter(xe=>te.has(xe.address.toLowerCase()))},[pe,g]),fe=Ut(),Ce=T?ne:fe,be=o.useMemo(()=>{if(!h)return[];const te=new Set,xe=[],Ge=tt=>{if(!tt)return;const lt=tt.toLowerCase();te.has(lt)||(te.add(lt),xe.push(V.getAddress(tt)))};if(b&&Ge(b),T)for(const tt of g)Ge(tt);return xe},[h,T,b,g]),Ye=o.useMemo(()=>be.map(te=>te.toLowerCase()).sort().join(","),[be]),ht=o.useMemo(()=>JSON.stringify([...x||[]].sort()),[x]),[ut,rt]=o.useState([]),wt=o.useRef(0),xt=o.useCallback(async()=>{if(!h||!Ce||be.length===0){wt.current++,rt([]);return}const te=++wt.current,xe=V.getAddress(Ce),Ge=x&&x.length>0?x:[d],tt=be.map(Me=>{const je=Me.toLowerCase();for(const st of Ge){const Ve=O.getChainConfig(st)?.supportedTokens?.find(Ke=>Ke.address.toLowerCase()===je);if(Ve)return{address:Me,chainId:st,configToken:{decimals:Ve.decimals,symbol:Ve.symbol,name:Ve.name,logo:Ve.logo}}}return{address:Me,chainId:d}}),lt=new Map;for(const Me of tt){const je=lt.get(Me.chainId)||[];je.push(Me),lt.set(Me.chainId,je)}const Se=async(Me,je)=>{try{const st=await Dt.readContract(Me,{address:je.address,abi:O._,functionName:"balanceOf",args:[xe]});let Ve,Ke,Ae,Le;if(je.configToken)Ve=je.configToken.decimals,Ke=je.configToken.symbol,Ae=je.configToken.name,Le=je.configToken.logo;else{const[St,H,_]=await Promise.all([Dt.readContract(Me,{address:je.address,abi:O._,functionName:"decimals",args:[]}).catch(()=>18),Dt.readContract(Me,{address:je.address,abi:O._,functionName:"symbol",args:[]}).catch(()=>"TOKEN"),Dt.readContract(Me,{address:je.address,abi:O._,functionName:"name",args:[]}).catch(()=>"TOKEN")]);Ve=Number(St),Ke=H,Ae=_}const Xe=!!b&&je.address.toLowerCase()===b.toLowerCase()&&je.chainId===d;Xe&&i&&(Le=i),Xe&&a&&!je.configToken&&(Ke==="TOKEN"&&(Ke=a),Ae==="TOKEN"&&(Ae=a));const kt=parseFloat((Number(st)/Math.pow(10,Ve)).toFixed(6));return{address:je.address,name:Ae,symbol:Ke,decimals:Ve,balance:st,balanceFormatted:kt,balanceUsd:0,logoURI:Le,isNative:!1,chainId:je.chainId}}catch{return null}},Fe=await Promise.all(Array.from(lt.entries()).map(async([Me,je])=>{let st;try{st=O.getClientForChain(Me)}catch{return[]}const Ve=[],Ke=[];for(const Le of je){const Xe=Ve.length;Ve.push({address:Le.address,abi:O._,functionName:"balanceOf",args:[xe]}),Le.configToken||Ve.push({address:Le.address,abi:O._,functionName:"decimals",args:[]},{address:Le.address,abi:O._,functionName:"symbol",args:[]},{address:Le.address,abi:O._,functionName:"name",args:[]}),Ke.push({start:Xe,item:Le})}let Ae=null;try{Ae=await st.multicall({contracts:Ve})}catch{Ae=null}return Ae?Ke.map(({start:Le,item:Xe})=>{const kt=Ae[Le],St=kt?.status==="success"?kt.result:0n;let H,_,q,oe;if(Xe.configToken)H=Xe.configToken.decimals,_=Xe.configToken.symbol,q=Xe.configToken.name,oe=Xe.configToken.logo;else{const nt=Ae[Le+1],Ne=Ae[Le+2],Je=Ae[Le+3];H=nt?.status==="success"?Number(nt.result):18,_=Ne?.status==="success"?Ne.result:"TOKEN",q=Je?.status==="success"?Je.result:_}const Pe=!!b&&Xe.address.toLowerCase()===b.toLowerCase()&&Xe.chainId===d;Pe&&i&&(oe=i),Pe&&a&&!Xe.configToken&&(_==="TOKEN"&&(_=a),q==="TOKEN"&&(q=a));const pt=parseFloat((Number(St)/Math.pow(10,H)).toFixed(6));return{address:Xe.address,name:q,symbol:_,decimals:H,balance:St,balanceFormatted:pt,balanceUsd:0,logoURI:oe,isNative:!1,chainId:Xe.chainId}}):(await Promise.all(je.map(Le=>Se(st,Le)))).filter(Le=>Le!==null)}));te===wt.current&&rt(Fe.flat())},[h,Ce,Ye,ht,d,b,i,a]);o.useEffect(()=>{if(!h){rt([]);return}xt();const te=setInterval(()=>{xt()},15e3);return()=>clearInterval(te)},[xt,h]);const _e=o.useCallback(()=>{xt()},[xt]),vt=o.useMemo(()=>ut.filter(te=>te.balance>0n),[ut]),Bt=o.useMemo(()=>{if(T)return vt.map(xe=>({...xe,_source:"wallet"}));if(!h)return ot;const te=[];for(const xe of vt)te.push({...xe,_source:"wallet"});for(const xe of ot)te.push({...xe,_source:"spice"});return te},[T,h,vt,ot]),he=o.useRef(null),ge=o.useRef(null);o.useEffect(()=>{ge.current=F},[F]),o.useEffect(()=>{t||(L(null),ye(null),ce(!1),De(!1),Ie(null),ue(!1),de())},[t,de]),o.useEffect(()=>{l&&l.assetAmount!==(F?.amount||"")&&L(te=>te&&{...te,amount:l.assetAmount})},[l?.assetAmount]),o.useEffect(()=>{r&&r.assetAmount!==(F?.amount||"")&&L(te=>te&&{...te,amount:r.assetAmount})},[r?.assetAmount]),o.useEffect(()=>{if(N?.overallStatus==="success"&&N.intentId&&he.current!==N.intentId&&k){const te=N.steps.find(xe=>xe.transactionHash);if(te?.transactionHash){he.current=N.intentId;const xe=ge.current;if(!xe?.asset||!xe.amount||xe.asset._source==="wallet")return;const Ge=V.parseUnits(xe.amount,xe.asset.decimals);if(Ge===0n)return;z.relayerService.submitSpiceDeposit({user:k,txHash:te.transactionHash,sender:k,tokenAddress:xe.asset.address,chainId:xe.asset.chainId??d,amount:Ge.toString(),isDeposit:!1}).then(()=>ke()).catch(()=>{he.current=null})}}},[N,k,d,ke]);const ve=parseFloat(F?.amount||"")||0,Ze=o.useMemo(()=>F?.asset?F.asset._source==="wallet"?F.asset.balanceFormatted??0:ot.find(te=>te.address.toLowerCase()===F.asset.address.toLowerCase()&&te.chainId===F.asset.chainId)?.balanceFormatted??0:0,[F?.asset,ot]),at=ve>0&&ve>Ze,qe=c?.selectedDuration??p[we]??p[0],et=o.useMemo(()=>!F?.asset||!b?!1:F.asset.address.toLowerCase()===b.toLowerCase()&&F.asset.chainId===d,[F?.asset,b,d]),gt=o.useMemo(()=>ve<=0?0:et?ve:!W||W<=0?0:ve/W,[ve,W,et]),Pt=o.useMemo(()=>gt<=0?null:gt.toLocaleString(void 0,{maximumFractionDigits:2}),[gt]),Lt=u&&gt>0&&qe?u(gt,qe.months):void 0,Xt=o.useMemo(()=>ve<=0?"$0.00":et&&W?(ve*W).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!W||W<=0?"$0.00":ve.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[ve,W,et]),qt=o.useMemo(()=>{if(!Pt)return null;const te=parseFloat(Pt.replace(/,/g,""));return et&&W?(te*W).toLocaleString(void 0,{maximumFractionDigits:2}):W?(te*W).toLocaleString(void 0,{maximumFractionDigits:2}):null},[Pt,W,et]),ts=o.useCallback(te=>{L(xe=>({asset:te,amount:xe?.asset?.address===te.address&&xe?.asset?.chainId===te.chainId&&xe.amount||""})),ye(null),r?.setSelectedAsset&&r.setSelectedAsset({symbol:te.symbol,address:te.address,decimals:te.decimals,chainId:te.chainId})},[r?.setSelectedAsset]),Ft=o.useCallback(te=>{L(xe=>xe&&{...xe,amount:te}),ye(null),l&&l.setAssetAmount(te),r&&r.setAssetAmount(te)},[l,r]),Et=o.useCallback(()=>{if(typeof n=="function"){if(!F?.asset||!F.amount)throw new Error("Select an asset and enter an amount");return n({asset:F.asset,amount:F.amount,amountWei:V.parseUnits(F.amount,F.asset.decimals)})}return n},[n,F]),Rt=o.useCallback(async()=>{if(!v||!k)throw new Error("Please connect your wallet to continue");const te=Et();if(te.length===0)throw new Error("No lock batches configured");if(!Z||!ee)throw new Error(`Please authenticate with ${se||"wallet provider"} to continue`);const xe=[...te],Ge=[...new Set(xe.map(Ae=>Ae.chainId))],tt=[];for(const Ae of Ge){const Le=O.getClientForChain(Ae),Xe=O.getDelegateContractAddress(Ae),kt=await K.getAccountNonce(k,Le),St=await ae.signAuthorization({contractAddress:Xe,chainId:Ae,nonce:Number(kt)});tt.push(St)}const lt=K.hashChainBatches(xe),Se=Math.floor(Date.now()/1e3)+60*10,Fe=lt.map(Ae=>Ae.hash),Me=V.keccak256(V.encodeAbiParameters([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,BigInt(Se),Fe])),je=await ae.signMessage({raw:Me}),st=typeof je=="string"?je:je.signature;if(!st)throw new Error("Failed to sign intent authorization");const Ve={mode:"7702",signatureType:"ecdsa",signature:st,nbf:0,exp:Se,chainBatches:lt.map((Ae,Le)=>({hash:Ae.hash,chainId:Ae.chainId,tokenTransfers:xe[Le].tokenTransfers??[],calls:Ae.calls}))},Ke=await z.relayerService.createAction({user:k,chainAuthorizations:tt.map(Ae=>({r:Ae.r,s:Ae.s,yParity:Ae.yParity,address:Ae.address,chainId:Number(Ae.chainId),nonce:Number(Ae.nonce)})),intents:[Ve]});if(Ke){const Ae=z.createInitialSteps(xe,O.getChainName),[Le,Xe]=Ke.intentIds[0].split("/"),kt=parseInt(Xe||"0",10);X(Ke.intentIds[0],Ae);for(let St=0;St<xe.length;St++)await Us(()=>z.relayerService.executeStep(Le,kt,St,{action:"execute"}))}},[Et,ze,X]),Ht=o.useCallback(async()=>{if(!F?.asset||!F.amount)throw new Error("Select an asset and enter an amount");if(!k||!fe)throw new Error("Embedded wallet not connected");const te=F.asset,xe=V.parseUnits(F.amount,te.decimals),Ge=f||O.getDelegateContractAddress(d),tt=await ae.getEthereumProvider();await tt.request({method:"wallet_switchEthereumChain",params:[{chainId:`0x${d.toString(16)}`}]});const lt=O.getChainConfig(d),Se=V.createWalletClient({account:fe,transport:V.custom(tt),chain:lt?.viemChain});let Fe;if(te.isNative||K.isNativeToken(te.address))Fe=await Se.sendTransaction({to:Ge,value:xe,chain:lt?.viemChain});else{const Me=V.encodeFunctionData({abi:O._,functionName:"transfer",args:[Ge,xe]});Fe=await Se.sendTransaction({to:te.address,data:Me,chain:lt?.viemChain})}if((await O.getClientForChain(d).waitForTransactionReceipt({hash:Fe,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to escrow failed");await Us(()=>z.relayerService.submitSpiceDeposit({txHash:Fe,sender:fe,tokenAddress:te.address,chainId:d,amount:xe.toString(),user:fe,isDeposit:!0})),await ke(),_e(),await Rt()},[F,k,fe,ae,f,d,Rt,ke,_e]),ft=o.useCallback(async()=>{if(!F?.asset||!F.amount)throw new Error("Select an asset and enter an amount");if(!ne)throw new Error("Please connect your wallet to continue");if(!I)throw new Error("onLockExecute callback is required for non-7702 mode");const te=Et();if(te.length===0)throw new Error("No lock batches configured");const xe=F.asset,Ge=V.parseUnits(F.amount,xe.decimals),tt=await I({asset:xe,amount:F.amount,amountWei:Ge,lockDurationMonths:qe?.months??0,chainBatches:te});tt&&m?.(tt)},[F,ne,I,Et,qe,m]);o.useEffect(()=>{if(N?.overallStatus==="success"){const te=N.steps.find(xe=>xe.transactionHash);m?.(te?.transactionHash)}},[N?.overallStatus,m]);const Ot=h&&F?.asset?._source==="wallet"&&F?.asset?.chainId===d,Vt=o.useCallback(async()=>{if(!F?.asset||ve<=0){ye("Select an asset and enter an amount");return}if(at){ye("Insufficient balance. Add more assets.");return}if(ce(!0),ye(null),T){try{await ft()}catch(te){ye(jt(te,"Transaction failed. Please try again."))}finally{ce(!1)}return}ue(!0);try{Ot&&!et?await Ht():await Rt()}catch(te){ye(jt(te,"Transaction failed. Please try again."))}finally{ce(!1)}},[F,ve,at,T,ft,Ot,et,Ht,Rt]),Gt=!!F?.asset&&ve>0&&!at&&!le,Mt=e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[e.jsx(nr,{color:U}),e.jsxs("p",{style:{fontSize:"13px",color:U,margin:0,lineHeight:"1.5"},children:["Add ",a," by converting assets from your account"]})]});if(!t)return null;const Jt={backgroundColor:j,border:E,borderRadius:Q,padding:"16px",marginBottom:"16px"};return e.jsx(Ct,{isOpen:t,onClose:s,title:`Add ${a} to your account`,subtitle:Mt,styles:B,dark:S,footerLinkText:"Spicenet accounts \u2192",overlayContent:He?e.jsx("div",{}):void 0,children:e.jsxs("div",{style:{padding:"0 24px 8px 24px",position:"relative"},children:[e.jsxs("div",{style:{marginBottom:"12px"},children:[y&&e.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:e.jsxs("button",{onClick:y,style:{background:"none",border:"none",cursor:"pointer",padding:0,display:"flex",alignItems:"center",gap:"4px",color:A,fontSize:"12px",fontWeight:500,fontFamily:M,textDecoration:"underline",textUnderlineOffset:"2px"},children:["Add Funds",e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:A,strokeWidth:"1.8",children:[e.jsx("circle",{cx:"6",cy:"6",r:"5"}),e.jsx("path",{d:"M6 4v4M4 6h4",strokeLinecap:"round"})]})]})}),e.jsx(as,{assets:Bt,selectedAsset:F??void 0,onAssetSelect:ts,onAmountChange:Ft,label:"Amount",showBalance:!0,showMaxButton:!0,theme:ie,styles:G}),e.jsx("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:U,fontFamily:M},children:Xt})]}),e.jsxs("div",{style:Jt,children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:S?`1px solid ${w.cardBorder}`:"1px solid #e5e7eb"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[i?e.jsx("img",{src:i,alt:a,style:{width:"32px",height:"32px",borderRadius:"50%",objectFit:"cover"}}):e.jsx("div",{style:{width:"32px",height:"32px",borderRadius:"50%",backgroundColor:S?w.inputBg:"#d1d5db",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:700,color:Y},children:a.slice(0,2)}),e.jsx("span",{style:{fontSize:"16px",fontWeight:600,color:Y,fontFamily:M},children:a})]}),e.jsxs("div",{style:{textAlign:"right"},children:[e.jsx("div",{style:{fontSize:"22px",fontWeight:700,color:Y,fontFamily:M,lineHeight:1.1},children:Pt??"0.00"}),e.jsxs("div",{style:{fontSize:"12px",color:U,fontFamily:M,marginTop:"2px"},children:["~$",qt??"0.00"]})]})]}),e.jsxs("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:S?`1px solid ${w.cardBorder}`:"1px solid #e5e7eb"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[e.jsx("span",{style:{fontSize:"15px",fontWeight:500,color:U,fontFamily:M},children:"Lock Duration"}),e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:e.jsx("path",{d:"M4 6L8 10L12 6",stroke:U,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),e.jsx($o,{options:p,selectedIndex:we,onSelect:re,primaryColor:A,dark:S,textPrimary:Y,textSecondary:U})]}),e.jsxs("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[e.jsx(er,{durationMonths:qe?.months,fontFamily:M,dark:S,textPrimary:Y,textSecondary:U}),u&&e.jsx(tr,{votes:Lt,fontFamily:M,dark:S,textPrimary:Y,textSecondary:U})]})]}),Be&&e.jsx("div",{style:{marginBottom:"12px",padding:"10px 14px",backgroundColor:S?"rgba(239,68,68,0.12)":"#fef2f2",border:`1px solid ${S?"rgba(239,68,68,0.3)":"#fecaca"}`,borderRadius:"6px"},children:e.jsx("p",{style:{color:"#ef4444",fontSize:"13px",margin:0,fontFamily:M},children:Be})}),e.jsx(Re.Button,{variant:"outline",fullWidth:!0,onClick:Vt,disabled:!Gt,loading:le,dark:S,styles:{button:{backgroundColor:A}},children:le?Ot&&!et?"DEPOSITING...":et?"LOCKING...":"CONVERTING...":Ot&&!et?`DEPOSIT ${a}`:et?`LOCK ${a}`:`CONVERT TO ${a}`}),e.jsx(sr,{isOpen:He,data:P,isLocking:le,lockError:Be,onContinue:Vt,onClose:()=>De(!1),primaryColor:A,fontFamily:M,dark:S}),N&&Te&&e.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:S?w.shell:"white",borderRadius:Q,padding:"16px 0"},children:e.jsx(ps,{type:"deposit",isOpen:!!N&&N.overallStatus!=="processing",isProcessing:le||N?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{de(),ue(!1),Vt()},onNewTx:()=>{de(),ue(!1),L(null),he.current=null,ke(),_e()},onClose:()=>{de(),ue(!1)},onComplete:()=>{de(),ue(!1),L(null),he.current=null,ke(),_e()},results:N?.overallStatus==="success"||N?.overallStatus==="failed"?N.steps.map(te=>({asset:{symbol:F?.asset?.symbol||a,address:F?.asset?.address||""},txHash:te.transactionHash||"",success:te.status==="success",amount:F?.amount})):void 0,chainName:O.getChainName(d),explorerUrl:O.getExplorerUrl(d,"").replace(/\/tx\/.*$/,"")||void 0,theme:R,styles:B,dark:S})})]})})},Sn=({variant:t,destinationSymbol:s,destinationLogoURI:n,destinationDecimals:a,primaryColor:i,fontFamily:l,textPrimary:r,textSecondary:c,cardBg:d,cardBorder:p,dk:u,dark:x,isQuoting:g,quoteError:f,estimatedOutput:h,paymentAmount:b,needsSwap:m,exactOutputSwap:I,adjustable:W=!1,maxAmount:C,onAmountChange:y})=>t==="supply"?e.jsx("div",{style:{backgroundColor:d,border:`1px solid ${p}`,borderRadius:"12px",padding:"14px 16px",marginBottom:"16px"},children:e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[e.jsx(In,{symbol:s,logoURI:n,primaryColor:i,size:28}),e.jsxs("span",{style:{fontSize:"13px",fontWeight:500,color:c,fontFamily:l},children:["Estimated ",s]})]}),e.jsx("div",{style:{textAlign:"right"},children:g?e.jsx("span",{style:{fontSize:"14px",color:c,fontFamily:l},children:"Quoting..."}):f?e.jsx("span",{style:{fontSize:"13px",color:"#ef4444",fontFamily:l},children:"Quote failed"}):h?e.jsxs("span",{style:{fontSize:"16px",fontWeight:600,color:r,fontFamily:l},children:["\u2248 ",h]}):e.jsx("span",{style:{fontSize:"14px",color:c,fontFamily:l},children:"\u2014"})})]})}):e.jsx(rr,{destinationSymbol:s,destinationLogoURI:n,destinationDecimals:a,primaryColor:i,fontFamily:l,textPrimary:r,textSecondary:c,cardBg:d,cardBorder:p,dk:u,dark:x,paymentAmount:b||"0",needsSwap:m,exactOutputSwap:I,isQuoting:g,adjustable:W,maxAmount:C,onAmountChange:y}),In=({symbol:t,logoURI:s,primaryColor:n,size:a})=>s?e.jsx("img",{src:s,alt:t,style:{width:a,height:a,borderRadius:"50%",objectFit:"cover"}}):e.jsx("div",{style:{width:a,height:a,borderRadius:"50%",backgroundColor:`${n}22`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:a<30?"11px":"12px",fontWeight:700,color:n},children:t.slice(0,2)}),rr=({destinationSymbol:t,destinationLogoURI:s,destinationDecimals:n,primaryColor:a,fontFamily:i,textPrimary:l,textSecondary:r,cardBg:c,cardBorder:d,dk:p,dark:u,paymentAmount:x,needsSwap:g,exactOutputSwap:f,isQuoting:h,adjustable:b,maxAmount:m,onAmountChange:I})=>{const W='"IBM Plex Mono", monospace',C=parseFloat(x||"0"),y=m?parseFloat(m):0,[B,D]=o.useState(x||""),R=o.useRef(null),[S,A]=o.useState(null),[w,M]=o.useState(null);o.useEffect(()=>{b||D(x||"")},[x,b]);const J=E=>{let Q=E;Q.startsWith(".")&&(Q="0"+Q);const Y=$s(Q);let U=Y;m&&parseFloat(Y)>parseFloat(m)&&(U=m),D(U),R.current&&clearTimeout(R.current),R.current=setTimeout(()=>I?.(U),300)},T=E=>{if(!y)return;if(E===100){D(m||y.toString()),R.current&&clearTimeout(R.current),I?.(m||y.toString());return}const Q=10**n,Y=(Math.floor(y*E/100*Q)/Q).toString();D(Y),R.current&&clearTimeout(R.current),I?.(Y)},j=y>0?parseFloat(B||"0")/y*100:0;return o.useEffect(()=>()=>{R.current&&clearTimeout(R.current)},[]),e.jsxs("div",{style:{backgroundColor:c,border:`1px solid ${d}`,borderRadius:u?"12px":"6px",padding:"16px",marginBottom:"16px"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[e.jsx(In,{symbol:t,logoURI:s,primaryColor:a,size:32}),e.jsxs("div",{children:[e.jsx("span",{style:{fontSize:"14px",fontWeight:600,color:l,fontFamily:i},children:"Payment"}),e.jsx("div",{style:{fontSize:"12px",color:r,fontFamily:i,marginTop:"2px"},children:t})]})]}),e.jsxs("div",{style:{textAlign:"right"},children:[b?e.jsx("input",{type:"text",value:B,onChange:E=>J(E.target.value),placeholder:"0.0",style:{fontSize:"20px",fontWeight:700,color:l,fontFamily:W,lineHeight:1.1,backgroundColor:"transparent",border:"none",outline:"none",padding:0,width:"120px",textAlign:"right"}}):e.jsx("div",{style:{fontSize:"20px",fontWeight:700,color:l,fontFamily:W,lineHeight:1.1},children:C>0?x:"0.00"}),e.jsx("div",{style:{fontSize:"12px",color:r,fontFamily:W,marginTop:"2px"},children:t}),b&&y>0&&e.jsx("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((E,Q)=>{const Y=Math.abs(j-E)<1,U=Q===4,G=E/100,ie=S===E,F=w===E;return e.jsx("button",{onClick:()=>T(E),onMouseEnter:()=>A(E),onMouseLeave:()=>{A(null),M(null)},onMouseDown:()=>M(E),onMouseUp:()=>M(null),title:`${E}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:Y?1:ie?.8:.5,transform:F?"scale(0.85)":ie?"scale(1.15)":"scale(1)",transition:"all 0.15s ease"},children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[e.jsx("circle",{cx:"7",cy:"7",r:"6.84375",fill:U?a:"none",stroke:U?a:u?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!U&&G>0&&e.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${G>.5?1:0} 1 ${7+6.84375*Math.sin(G*2*Math.PI)} ${7-6.84375*Math.cos(G*2*Math.PI)} Z`,fill:u?p?.textSecondary||"#9ca3af":"#3C3E42"})]})},E)})})]})]}),g&&f&&!h&&e.jsx("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:u?`1px solid ${p?.cardBorder||d}`:"1px solid #e5e7eb",display:"flex",justifyContent:"flex-end"},children:e.jsxs("span",{style:{fontSize:"11px",color:r,fontFamily:i,opacity:.7},children:["via ",f.venue]})})]})};function jn(t,s,n){const a=t.address.toLowerCase()===s,i=t.chainId===n,l=t._source==="wallet";return l&&a&&i?0:l&&i?1:!l&&a?2:!l&&i?3:4}function ar(t){const{address:s,destinationToken:n,supportedSourceAssets:a,sourceChains:i,enabled:l}=t,r=Ut(),{assets:c,refetch:d}=os({address:s,supportedChains:i,enabled:l,refetchInterval:3e4}),p=o.useMemo(()=>{if(!a||a.length===0)return c;const f=a.map(h=>h.toLowerCase());return c.filter(h=>f.includes(h.address.toLowerCase()))},[c,a]),[u,x]=o.useState(null);o.useEffect(()=>{if(!n.address||!r||!l){x(null);return}let f=!1;const h=V.getAddress(n.address),b=V.getAddress(r),m=O.getClientForChain(n.chainId),I=async()=>{try{const C=await m.multicall({contracts:[{address:h,abi:V.erc20Abi,functionName:"balanceOf",args:[b]},{address:h,abi:V.erc20Abi,functionName:"decimals",args:[]},{address:h,abi:V.erc20Abi,functionName:"symbol",args:[]},{address:h,abi:V.erc20Abi,functionName:"name",args:[]}]});if(f)return;const y=C[0].status==="success"?C[0].result:0n,B=C[1].status==="success"?Number(C[1].result):n.decimals,D=C[2].status==="success"?C[2].result:n.symbol,R=C[3].status==="success"?C[3].result:n.symbol;y>0n?x({address:h,name:R,symbol:D,decimals:B,balance:y,balanceFormatted:parseFloat((Number(y)/Math.pow(10,B)).toFixed(6)),balanceUsd:0,logoURI:n.logoURI,isNative:!1,chainId:n.chainId}):x(null)}catch{f||x(null)}};I();const W=setInterval(I,15e3);return()=>{f=!0,clearInterval(W)}},[n.address,n.chainId,n.decimals,n.symbol,n.logoURI,r,l]);const g=o.useCallback(()=>{if(!n.address||!r)return;const f=O.getClientForChain(n.chainId),h=V.getAddress(n.address),b=V.getAddress(r);f.multicall({contracts:[{address:h,abi:V.erc20Abi,functionName:"balanceOf",args:[b]},{address:h,abi:V.erc20Abi,functionName:"decimals",args:[]}]}).then(m=>{const I=m[0].status==="success"?m[0].result:0n,W=m[1].status==="success"?Number(m[1].result):18;I>0n?x(C=>C?{...C,balance:I,balanceFormatted:parseFloat((Number(I)/Math.pow(10,W)).toFixed(6))}:null):x(null)}).catch(()=>{})},[n.address,n.chainId,r]);return{displayAssets:o.useMemo(()=>{const f=[];u&&f.push({...u,_source:"wallet"});for(const b of p)f.push({...b,_source:"spice"});const h=n.address.toLowerCase();return f.sort((b,m)=>jn(b,h,n.chainId)-jn(m,h,n.chainId)),f},[u,p,n.address,n.chainId]),filteredSpiceAssets:p,embeddedWalletAddress:r,refreshSpiceAssets:d,refreshWalletAssets:g}}function xs(t){const s=new Set(K.getEquivalentAddresses(t).map(n=>n.toLowerCase()));return s.add(t.toLowerCase()),s}const ir=["USDC","USDT","WETH","WBTC"];function Qs(t,s){const n=O.getChainConfig(s);if(!n)return;if(n.nativeCurrency.symbol.toUpperCase()===t.toUpperCase())return{address:K.ZERO_ADDRESS,symbol:n.nativeCurrency.symbol,decimals:n.nativeCurrency.decimals,chainId:s};const a=n.supportedTokens?.find(i=>i.symbol.toUpperCase()===t.toUpperCase());if(a)return{address:a.address.toLowerCase(),symbol:a.symbol,decimals:a.decimals,chainId:s}}function $t(t,s){const n=O.getChainConfig(s);if(!n)return;const a=xs(t);if([...a].some(l=>K.isNativeToken(l)))return{address:K.ZERO_ADDRESS,symbol:n.nativeCurrency.symbol,decimals:n.nativeCurrency.decimals,chainId:s};const i=n.supportedTokens?.find(l=>a.has(l.address.toLowerCase()));if(i)return{address:i.address.toLowerCase(),symbol:i.symbol,decimals:i.decimals,chainId:s}}function En(t){const{sourceAsset:s,outputAsset:n,sourceChainId:a,destinationChainId:i,intermediaryCandidates:l=ir}=t,r=xs(s.address);if(r.has(n.address.toLowerCase()))return{strategy:"direct",sourceAsset:s,outputAsset:n,sourceChainId:a,destinationChainId:i,summary:`${s.symbol} fronted directly`};if($t(s.address,i))return{strategy:"direct",sourceAsset:s,outputAsset:n,sourceChainId:a,destinationChainId:i,summary:`${s.symbol} fronted on destination, swapped to ${n.symbol}`};if($t(n.address,a))return{strategy:"source-swap",sourceAsset:s,outputAsset:n,sourceChainId:a,destinationChainId:i,summary:`${s.symbol} \u2192 ${n.symbol} on source chain, then fronted`};const c=xs(n.address);for(const d of l){const p=Qs(d,a);if(!p||r.has(p.address.toLowerCase())||c.has(p.address.toLowerCase()))continue;const u=Qs(d,i);if(!(!u||!xs(p.address).has(u.address.toLowerCase())))return{strategy:"intermediary",sourceAsset:s,outputAsset:n,intermediaryAsset:u,sourceChainId:a,destinationChainId:i,summary:`${s.symbol} \u2192 ${d} on source, fronted, then ${d} \u2192 ${n.symbol} on destination`}}throw new z.SpiceflowError("ROUTE_STRATEGY_ERROR",`No viable cross-chain route found from ${s.symbol} (chain ${a}) to ${n.symbol} (chain ${i}). No intermediary asset is available on both chains.`,{sourceAsset:s.symbol,outputAsset:n.symbol,sourceChainId:a,destinationChainId:i,candidatesChecked:l})}async function An(t){const{route:s,sourceAmount:n,userAddress:a,registry:i,actionCalls:l,slippage:r}=t;async function c(d,p,u,x){const g=i.getVenueForChain(d);if(!g)throw new z.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${d}. Cannot resolve swap ${p} \u2192 ${u}.`,{chainId:d,tokenIn:p,tokenOut:u,amountIn:x.toString()});const f=await g.resolve({type:"swap",tokenIn:p,tokenOut:u,amountIn:x,maxSlippage:r},d,a);if(!f)throw new z.SpiceflowError("NO_LIQUIDITY",`${g.name} returned no quote for ${p} \u2192 ${u} on chain ${d}. No liquidity available for this pair.`,{venue:g.name,chainId:d,tokenIn:p,tokenOut:u,amountIn:x.toString()});return f}switch(s.strategy){case"direct":{const d=$t(s.sourceAsset.address,s.destinationChainId)||s.sourceAsset;if(xs(d.address).has(s.outputAsset.address.toLowerCase()))return{chainBatches:[{chainId:s.destinationChainId,calls:l}],solverFrontToken:d,solverFrontAmount:n,resolvedSwaps:{}};const p=await c(s.destinationChainId,d.address,s.outputAsset.address,n);return{chainBatches:[{chainId:s.destinationChainId,calls:[...p.calls,...l]}],solverFrontToken:d,solverFrontAmount:n,resolvedSwaps:{destinationSwap:p}}}case"source-swap":{const d=$t(s.outputAsset.address,s.sourceChainId);if(!d)throw new z.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Output asset ${s.outputAsset.symbol} (${s.outputAsset.address}) not found on source chain ${s.sourceChainId}`,{token:s.outputAsset.symbol,address:s.outputAsset.address,chainId:s.sourceChainId,side:"source"});const p=$t(s.outputAsset.address,s.destinationChainId);if(!p)throw new z.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Output asset ${s.outputAsset.symbol} (${s.outputAsset.address}) not found on destination chain ${s.destinationChainId}`,{token:s.outputAsset.symbol,address:s.outputAsset.address,chainId:s.destinationChainId,side:"destination"});const u=await c(s.sourceChainId,s.sourceAsset.address,d.address,n);return{chainBatches:[{chainId:s.sourceChainId,calls:u.calls},{chainId:s.destinationChainId,calls:l}],solverFrontToken:p,solverFrontAmount:u.amountOutMinimum,resolvedSwaps:{sourceSwap:u}}}case"intermediary":{if(!s.intermediaryAsset)throw new z.SpiceflowError("ROUTE_STRATEGY_ERROR","Intermediary strategy requires an intermediary asset but none was provided in the route plan.",{strategy:s.strategy});const d=$t(s.intermediaryAsset.address,s.sourceChainId);if(!d)throw new z.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Intermediary ${s.intermediaryAsset.symbol} (${s.intermediaryAsset.address}) not found on source chain ${s.sourceChainId}`,{token:s.intermediaryAsset.symbol,address:s.intermediaryAsset.address,chainId:s.sourceChainId,side:"source"});const p=await c(s.sourceChainId,s.sourceAsset.address,d.address,n),u=await c(s.destinationChainId,s.intermediaryAsset.address,s.outputAsset.address,p.amountOutMinimum);return{chainBatches:[{chainId:s.sourceChainId,calls:p.calls},{chainId:s.destinationChainId,calls:[...u.calls,...l]}],solverFrontToken:s.intermediaryAsset,solverFrontAmount:p.amountOutMinimum,resolvedSwaps:{sourceSwap:p,destinationSwap:u}}}default:throw new z.SpiceflowError("ROUTE_STRATEGY_ERROR",`Unknown route strategy: ${s.strategy}`,{strategy:s.strategy})}}async function Bn(t){const{tokenIn:s,tokenOut:n,amountIn:a,fee:i,chainId:l,config:r}=t;if(a<=0n)throw new Error("amountIn must be greater than 0");const c=(await O.getClientForChain(l).simulateContract({address:r.quoterV2,abi:K.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:s,tokenOut:n,amountIn:a,fee:i,sqrtPriceLimitX96:0n}]})).result;if(c[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:c[0],sqrtPriceX96After:c[1],gasEstimate:c[3]}}async function Fn(t){const s=t.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(s.map(i=>Bn({...t,fee:i})));let a=null;for(let i=0;i<n.length;i++){const l=n[i];l.status==="fulfilled"&&(!a||l.value.amountOut>a.amountOut)&&(a={...l.value,fee:s[i]})}if(!a)throw new Error("No liquidity found for this pair on any fee tier.");return a}const lr=[{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 dr(t){const{tokenIn:s,tokenOut:n,amountOut:a,fee:i,chainId:l,config:r}=t;if(a<=0n)throw new Error("amountOut must be greater than 0");const c=(await O.getClientForChain(l).simulateContract({address:r.quoterV2,abi:lr,functionName:"quoteExactOutputSingle",args:[{tokenIn:s,tokenOut:n,amount:a,fee:i,sqrtPriceLimitX96:0n}]})).result;if(c[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:c[0],sqrtPriceX96After:c[1],gasEstimate:c[3]}}async function cr(t){const s=t.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(s.map(i=>dr({...t,fee:i})));let a=null;for(let i=0;i<n.length;i++){const l=n[i];l.status==="fulfilled"&&(!a||l.value.amountIn<a.amountIn)&&(a={...l.value,fee:s[i]})}if(!a)throw new Error("No liquidity found for this pair on any fee tier.");return a}function Rn(t){return t.type==="swap"}const Ys=.02,ur=[1,8453,42161,10,137,43114,56],pr="https://api.1inch.dev/swap/v6.0";function Mn(t,s){return K.applySlippage(t,s)}function Tn(t){const s=t?.baseUrl??pr;return{name:"1inch",chainIds:t?.chainIds??ur,resolve:async(n,a,i)=>{const l=n.maxSlippage??Ys,r=l*100,c=K.isNativeToken(n.tokenIn)?K.NATIVE_TOKEN_ADDRESS:n.tokenIn,d=K.isNativeToken(n.tokenOut)?K.NATIVE_TOKEN_ADDRESS:n.tokenOut,p=K.isNativeToken(n.tokenIn);try{const u=new URL(`${s}/${a}/swap`);u.searchParams.set("src",c),u.searchParams.set("dst",d),u.searchParams.set("amount",n.amountIn.toString()),u.searchParams.set("from",i),u.searchParams.set("slippage",r.toString()),u.searchParams.set("disableEstimate","true"),u.searchParams.set("allowPartialFill","false");const x={Accept:"application/json"};t?.apiKey&&(x.Authorization=`Bearer ${t.apiKey}`);const g=await fetch(u.toString(),{headers:x});if(!g.ok)throw new z.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${g.status} for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${a}`,{venue:"1inch",chainId:a,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:`HTTP ${g.status}`});const f=await g.json();if(!f.dstAmount||!f.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${a}`),null;const h=BigInt(f.dstAmount);if(h<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${a}`),null;const b=Mn(h,l),m=[];return f.tx.to&&!p&&m.push({to:n.tokenIn,value:0n,data:V.encodeFunctionData({abi:V.erc20Abi,functionName:"approve",args:[f.tx.to,n.amountIn]})}),m.push({to:f.tx.to,value:BigInt(f.tx.value||"0"),data:f.tx.data}),{venue:"1inch",amountOut:h,amountOutMinimum:b,calls:m}}catch(u){if(u instanceof z.SpiceflowError)throw u;const x=u instanceof Error?u.message:String(u);throw new z.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${a}: ${x}`,{venue:"1inch",chainId:a,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:x})}}}}const Dn=[4114,5115],Ks={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425"},Wn={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453]};function Nn(t){return{name:"satsuma",chainIds:t.chainIds??Dn,resolve:async(s,n,a)=>{const i=s.maxSlippage??Ys,l=K.isNativeToken(s.tokenIn);let r;try{r=await Fn({tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn,chainId:n,config:{swapRouter:t.swapRouter,quoterV2:t.quoterV2},feeTiers:t.feeTiers})}catch{return console.warn(`[SatsumaVenue] No viable fee tier for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${n}.`),null}const c=Mn(r.amountOut,i),d=[];return l||d.push({to:s.tokenIn,value:0n,data:V.encodeFunctionData({abi:V.erc20Abi,functionName:"approve",args:[t.swapRouter,s.amountIn]})}),d.push({to:t.swapRouter,value:l?s.amountIn:0n,data:V.encodeFunctionData({abi:K.uniV3SwapRouterAbi,functionName:"exactInputSingle",args:[{tokenIn:s.tokenIn,tokenOut:s.tokenOut,fee:r.fee,recipient:a,amountIn:s.amountIn,amountOutMinimum:c,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:r.amountOut,amountOutMinimum:c,calls:d}}}}function Un(t){return{name:"satsuma",chainIds:t.chainIds??Dn,resolve:async(s,n,a)=>{const i=s.maxSlippage??Ys,l=K.isNativeToken(s.tokenIn);let r;try{r=await cr({tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountOut:s.amountOut,chainId:n,config:{swapRouter:t.swapRouter,quoterV2:t.quoterV2},feeTiers:t.feeTiers})}catch{return null}const c=BigInt(Math.round(i*1e4)),d=r.amountIn+r.amountIn*c/10000n,p=[];return p.push({to:t.swapRouter,value:l?d:0n,data:V.encodeFunctionData({abi:hr,functionName:"exactOutputSingle",args:[{tokenIn:s.tokenIn,tokenOut:s.tokenOut,fee:r.fee,recipient:a,amountOut:s.amountOut,amountInMaximum:d,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:r.amountIn,amountInMax:d,amountOut:s.amountOut,calls:p}}}}const hr=[{inputs:[{components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"fee",type:"uint24"},{name:"recipient",type:"address"},{name:"amountOut",type:"uint256"},{name:"amountInMaximum",type:"uint256"},{name:"sqrtPriceLimitX96",type:"uint160"}],name:"params",type:"tuple"}],name:"exactOutputSingle",outputs:[{name:"amountIn",type:"uint256"}],stateMutability:"payable",type:"function"}];function zn(t){const s=[];t?.customVenues&&s.push(...t.customVenues),t?.satsuma&&s.push(Nn(t.satsuma)),s.push(Tn(t?.oneInch));function n(i){return s.find(l=>l.chainIds.includes(i))}async function a(i,l,r){const c=[],d=[];for(const p of i){if(!Rn(p)){c.push(p);continue}const u=n(l);if(!u)throw new z.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${l}. Cannot resolve swap ${p.tokenIn} \u2192 ${p.tokenOut}.`,{chainId:l,tokenIn:p.tokenIn,tokenOut:p.tokenOut,amountIn:p.amountIn.toString()});const x=await u.resolve(p,l,r);if(!x)throw new z.SpiceflowError("NO_LIQUIDITY",`${u.name} returned no quote for ${p.tokenIn} \u2192 ${p.tokenOut} on chain ${l}.`,{venue:u.name,chainId:l,tokenIn:p.tokenIn,tokenOut:p.tokenOut,amountIn:p.amountIn.toString()});c.push(...x.calls),d.push(x)}return{calls:c,resolvedSwaps:d}}return{resolveSwapIntents:a,getVenueForChain:n,venues:s}}function xr(t){const s=t?.customVenues??[];async function n(a,i,l){const r=s.filter(d=>d.chainIds.includes(i));if(r.length===0)throw new z.SpiceflowError("NO_SWAP_ROUTE",`No exact-output venue supports chain ${i}`,{chainId:i,tokenIn:a.tokenIn,tokenOut:a.tokenOut});const c=(await Promise.allSettled(r.map(d=>d.resolve(a,i,l)))).filter(d=>d.status==="fulfilled").map(d=>d.value).filter(d=>d!==null);if(c.length===0)throw new z.SpiceflowError("NO_SWAP_ROUTE",`All aggregators failed for ${a.tokenIn} \u2192 ${a.tokenOut} on chain ${i}`,{chainId:i,tokenIn:a.tokenIn,tokenOut:a.tokenOut,amountOut:a.amountOut.toString()});return c.sort((d,p)=>d.amountIn<p.amountIn?-1:d.amountIn>p.amountIn?1:0),c[0]}return{getQuote:n,venues:s}}function fr(t){const{direction:s,selectedAsset:n,destinationToken:a,chainId:i,recipient:l,paymentAmount:r}=t,[c,d]=o.useState(!1),[p,u]=o.useState(null),[x,g]=o.useState(null),[f,h]=o.useState(null),[b,m]=o.useState(null),[I,W]=o.useState(null),[C,y]=o.useState(null),B=o.useRef(null),D=o.useMemo(()=>zn({satsuma:Ks}),[]),R=o.useMemo(()=>xr({customVenues:[Un(Ks),Un(Wn)]}),[]),S=o.useMemo(()=>{if(!n?.asset)return null;if(n.asset.chainId===i)return n.asset.address;const T=$t(n.asset.address,i);return T?T.address:null},[n?.asset?.address,n?.asset?.chainId,i]),A=o.useMemo(()=>n?.asset?n.asset.address.toLowerCase()===a.address.toLowerCase()&&n.asset.chainId===i?!0:K.areEquivalent(n.asset.address,a.address):!1,[n,a.address,i]),w=S?S.toLowerCase()===a.address.toLowerCase():!1,M=s==="output"&&parseFloat(r||"0")===0,J=!!n?.asset&&!A&&!w&&!M;return o.useEffect(()=>{B.current&&clearTimeout(B.current);const T=s==="input"?n?.amount:r,j=parseFloat(T||"0");if(!J||j<=0||!n?.asset||!l||!S){g(null),h(null),m(null),W(null),y(null),u(null),d(!1);return}return d(!0),B.current=setTimeout(async()=>{try{if(s==="input"){const E=V.parseUnits(n.amount,n.asset.decimals),Q=D.getVenueForChain(i);if(!Q)throw new Error("No swap venue for this chain");const Y=await Q.resolve({type:"swap",tokenIn:S,tokenOut:a.address,amountIn:E},i,l);if(!Y)throw new Error("No liquidity for this pair");y(Y.amountOut),m(Y),W(null);const U=V.formatUnits(Y.amountOut,a.decimals),G=parseFloat(U);g(G<.01?G.toPrecision(4):G.toLocaleString(void 0,{maximumFractionDigits:6})),h(null),u(null)}else{const E=V.parseUnits(r||"0",a.decimals),Q=await R.getQuote({tokenIn:S,tokenOut:a.address,amountOut:E},i,l);W(Q),m(null),y(null),h(parseFloat(V.formatUnits(Q.amountIn,n.asset.decimals)).toFixed(6)),g(null),u(null)}}catch(E){const Q=E instanceof Error?E.message:"Failed to get quote";u(Q),g(null),h(null),m(null),W(null),y(null)}finally{d(!1)}},500),()=>{B.current&&clearTimeout(B.current)}},[s,J,n?.amount,n?.asset?.address,n?.asset?.decimals,r,S,i,a.address,a.decimals,l,D,R]),{isQuoting:c,quoteError:p,estimatedOutput:x,estimatedInput:f,resolvedSwap:b,exactOutputSwap:I,quoteAmountOut:C,resolvedTokenIn:S,isDirect:w,needsSwap:J,selectedIsEquivalent:A}}const gr=[0n,1n,30n],mr=new Set(["ABORT","CONCURRENT_EXECUTION","WALLET_DISCONNECTED","WALLET_REJECTED","NO_VENUE_FOR_CHAIN"]);function Pn(t,s){return s===0n?t:t*(1000n-s)/1000n}async function Ln(t,s){const{chainId:n,swapCalls:a,quoteAmountOut:i,buildActionCalls:l,tokenAddress:r,tokenTransferAmount:c,onProgress:d,signal:p,options:u,buffers:x=gr}=s;for(let g=0;g<x.length;g++){const f=x[g],h=Pn(i,f),b=l(h),m=[{chainId:n,calls:[...a,...b]}];try{return await t(m,r,c,d,p,u)}catch(I){if(z.isSpiceflowError(I)&&mr.has(I.code)||I.name==="AbortError"||p?.aborted||I.message?.includes("User rejected")||I.message?.includes("User denied")||I.code===4001||g>=x.length-1)throw I;const W=Number(x[g+1])/10;console.warn(`[SwapThenAction] Action attempt ${g+1} failed (buffer ${Number(f)/10}%), retrying with ${W}% buffer...`,I.message),d?.({step:"signing-delegation",message:`Adjusting action amount, retrying (${W}% buffer)...`})}}throw new z.SpiceflowError("ALL_ATTEMPTS_FAILED","All action attempts failed after exhausting buffer progression.",{attempts:x.length,chainId:n})}const Hn={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Transaction successful!",error:"Transaction failed"},On=["signing-delegation","signing-intent","submitting","executing"],yr=({color:t})=>e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",style:{marginTop:"1px",flexShrink:0},children:[e.jsx("circle",{cx:"7",cy:"7",r:"6.5",stroke:t,strokeWidth:"1.2"}),e.jsx("path",{d:"M7 6v4",stroke:t,strokeWidth:"1.2",strokeLinecap:"round"}),e.jsx("circle",{cx:"7",cy:"4.5",r:"0.7",fill:t})]}),Vn=({isOpen:t,onClose:s,destinationToken:n,buildActionCalls:a,actionLabel:i,amountDirection:l="input",swapDescription:r,directDescription:c,supportedSourceAssets:d,sourceChains:p,paymentAmount:u,amountInputMode:x="fixed",minPaymentAmount:g,maxPaymentAmount:f,onAmountChange:h,styles:b,dark:m,title:I,subtitle:W,onAddFunds:C,onSuccess:y,onError:B})=>{const D=l==="output",{theme:R,dark:S,primaryColor:A,dk:w,palette:M}=z.useSpiceBrand(b,m),J=R.typography.fontFamily,T=b?.inputVariant?b.inputVariant==="dark":S,j=M.textPrimary,E=M.textSecondary,Q=T?w.cardBg:"#f9fafb",Y=T?w.cardBorder:"#e5e7eb",U=b?.button?.backgroundColor??A,G=b?.button?.color??"#0e0d0b",ie=T?{...R,colors:{...R.colors,secondary:w.cardBg,surfaceHover:w.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:R,F=n.chainId,L=zt(),{address:$,isConnected:me,isReady:we,isAuthenticated:re,provider:le}=L,{executeGasless:ce}=js(),{displayAssets:Be,filteredSpiceAssets:ye,embeddedWalletAddress:Te,refreshSpiceAssets:ue,refreshWalletAssets:He}=ar({address:$,destinationToken:n,supportedSourceAssets:d,sourceChains:p,enabled:t&&!!$}),De=D?Be:ye,[P,Ie]=o.useState(null),[Ee,ne]=o.useState(u||""),[We,ze]=o.useState(!1),[Z,ee]=o.useState(null),[v,k]=o.useState("idle"),[se,ae]=o.useState(""),[N,X]=o.useState(null),[de,pe]=o.useState(!1),[ke,ot]=o.useState(null),fe=o.useRef(P),Ce=o.useRef(!1),be=o.useRef(null);o.useEffect(()=>{fe.current=P},[P]);const Ye=x==="adjustable"?Ee:u||"0",ht=Te||$,{isQuoting:ut,quoteError:rt,estimatedOutput:wt,resolvedSwap:xt,exactOutputSwap:_e,quoteAmountOut:vt,resolvedTokenIn:Bt,isDirect:he,needsSwap:ge,selectedIsEquivalent:ve}=fr({direction:l,selectedAsset:P,destinationToken:n,chainId:F,recipient:ht,paymentAmount:Ye}),Ze=D?parseFloat(Ye||"0"):parseFloat(P?.amount||"")||0,at=o.useMemo(()=>P?.asset?ye.find(Se=>Se.address.toLowerCase()===P.asset.address.toLowerCase())?.balanceFormatted??0:0,[P,ye]),qe=o.useMemo(()=>P?.asset?D?ve?Ze>P.asset.balanceFormatted:_e?parseFloat(V.formatUnits(_e.amountInMax,P.asset.decimals))>P.asset.balanceFormatted:!1:Ze>at:!1,[P,D,ve,Ze,_e,at]);o.useEffect(()=>{t||(Ie(null),ee(null),ze(!1),k("idle"),ae(""),X(null),pe(!1),ot(null),Ce.current=!1,x==="adjustable"&&ne(u||""),be.current&&(be.current.abort(),be.current=null))},[t]);const et=o.useCallback(Se=>{Ie(Fe=>({asset:Se,amount:Fe?.asset?.address===Se.address&&Fe?.asset?.chainId===Se.chainId&&Fe.amount||""})),ee(null)},[]),gt=o.useCallback(Se=>{Ie(Fe=>Fe&&{...Fe,amount:Se}),ee(null)},[]),Pt=o.useCallback(Se=>{let Fe=Se;f&&parseFloat(Fe)>parseFloat(f)&&(Fe=f),ne(Fe),h?.(Fe),ee(null)},[f,h]),Lt=o.useCallback(Se=>{k({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[Se.step]||"executing"),ae(Se.message),Se.txHash&&X(Se.txHash)},[]),Xt=o.useCallback(()=>{const Se=V.parseUnits(Ye,n.decimals),Fe={userAddress:Te,chainId:F,destinationToken:n.address},Me=a(Se,Fe),je={chainId:F,calls:Me},st=P?.asset?._source==="spice",Ve=(Ke,Ae)=>({token:Ke,from:"solver",to:Te,amount:Ae});if(Se===0n)return[je];if(ge&&_e){let Ke=P.asset.address;if(P.asset.chainId!==F){const Xe=K.getTokenDefinition(P.asset.address)?.deployments.find(kt=>kt.chainId===F);Xe&&(Ke=Xe.address)}const Ae=st?[Ve(Ke,_e.amountInMax)]:[],Le={to:Ke,value:0n,data:V.encodeFunctionData({abi:V.erc20Abi,functionName:"approve",args:[_e.calls[0]?.to,_e.amountInMax]})};return[{chainId:F,calls:[Le,..._e.calls,...Me],tokenTransfers:[...Ae,...je.tokenTransfers??[]]}]}if(st){let Ke=n.address;if(P.asset.chainId!==F){const Ae=K.getTokenDefinition(P.asset.address)?.deployments.find(Le=>Le.chainId===F);Ae&&(Ke=Ae.address)}return[{...je,tokenTransfers:[Ve(Ke,Se),...je.tokenTransfers??[]]}]}return[je]},[Ye,n,Te,F,a,P,ge,_e]),qt=o.useCallback(async()=>{if(!P?.asset||Ze<=0){ee("Select an asset and enter an amount");return}if(qe){ee("Insufficient balance");return}if(!Te){ee("Wallet not ready");return}ze(!0),ee(null),k("signing-delegation"),ae("Building transaction..."),X(null),Ce.current=!1;const Se=new AbortController;be.current=Se;try{const Fe={userAddress:Te,chainId:F,destinationToken:n.address};if(he){const Me=V.parseUnits(P.amount,P.asset.decimals),je=a(Me,Fe);await ce([{chainId:F,calls:je}],Bt??P.asset.address,Me,Lt,Se.signal)}else{if(!xt||!vt)throw new Error("Please wait for the swap quote");const Me=V.parseUnits(P.amount,P.asset.decimals);await Ln(ce,{chainId:F,swapCalls:xt.calls,quoteAmountOut:vt,buildActionCalls:je=>a(je,Fe),tokenAddress:Bt,tokenTransferAmount:Me,onProgress:Lt,signal:Se.signal})}k("success"),ae("Transaction successful!")}catch(Fe){const Me=Fe instanceof Error?Fe:new Error(String(Fe));if(Me.name==="AbortError"||Se.signal.aborted){k("idle");return}const je=Me.message||"Transaction failed";k("error"),ae(je),ee(je),B?.(Me)}finally{ze(!1)}},[P,Ze,qe,Te,he,F,xt,vt,Bt,a,ce,Lt,B]),ts=o.useCallback(async()=>{if(Ze<0){ee("Enter a valid payment amount");return}if(!P?.asset){ee("Select a payment source");return}if(qe){ee("Insufficient balance");return}if(ge&&!_e){ee("Swap quote not available. Try a different asset.");return}if(!me||!$){ee("Please connect your wallet to continue");return}if(!we||!re){ee(`Please authenticate with ${le||"wallet provider"} to continue`);return}ze(!0),ee(null),pe(!0),ot({status:"processing"});try{const Se=Xt(),Fe=Se.some(Ve=>Ve.tokenTransfers?.length),Me=V.parseUnits(Ye,n.decimals),je=P?.asset?.address||n.address,st=await ce(Se,je,Me,Ve=>{Ve.txHash&&(ot(Ke=>({...Ke,txHash:Ve.txHash})),X(Ve.txHash))},void 0,Fe?{useCustomTransfers:!0}:void 0);ot(Ve=>({status:"success",txHash:Ve?.txHash||st}))}catch(Se){const Fe=jt(Se,"Payment failed. Please try again.");ee(Fe),ot({status:"failed",error:Fe}),B?.(Se instanceof Error?Se:new Error(Fe))}finally{ze(!1)}},[Ze,P,qe,ge,_e,me,$,we,re,le,Xt,Ye,n,ce,B]);o.useEffect(()=>{!D&&v==="success"&&N&&(ue(),y?.(N))},[D,v,N,ue,y]),o.useEffect(()=>{if(!D||ke?.status!=="success"||Ce.current||!$)return;Ce.current=!0;const Se=fe.current;!Se?.asset||Se.asset?._source==="wallet"||ue()},[D,ke?.status,$,ue]);const Ft=o.useRef(y),Et=o.useRef(B);o.useEffect(()=>{Ft.current=y},[y]),o.useEffect(()=>{Et.current=B},[B]),o.useEffect(()=>{D&&(ke?.status==="success"&&Ft.current?.(ke.txHash||""),ke?.status==="failed"&&Et.current?.(new Error("Payment execution failed")))},[D,ke?.status]);const Rt=o.useCallback(()=>{pe(!1),ot(null),Ie(null),Ce.current=!1,ue(),He()},[ue,He]),Ht=D?!!P?.asset&&Ze>=0&&!qe&&!We&&(!ge||!!_e):!!P?.asset&&Ze>0&&!qe&&!We&&(he||!!xt&&!ut),ft=he?c||`Your ${n.symbol} will be used directly.`:r||"Your assets will be swapped and used in a single atomic transaction.",Ot=S?w.shell:"white",Vt=S?w.buttonBorder:"#0e0d0b",Gt=(F?O.getChainConfig(F):void 0)?.viemChain?.blockExplorers?.default?.url??"",Mt=On.indexOf(v),Jt=We?(Hn[v]||"EXECUTING...").toUpperCase():v==="success"?"DONE":qe?"INSUFFICIENT BALANCE":i.toUpperCase(),te=o.useMemo(()=>{if(We)return"PAYING...";if(qe&&P?.asset)return`INSUFFICIENT ${P.asset.symbol}`;const Se=Ze>0?` ${Ye} ${n.symbol}`:"";return ge?`SWAP & PAY${Se}`:`PAY${Se}`},[We,qe,P,Ze,Ye,n.symbol,ge]),xe=v==="success"?()=>{k("idle"),Ie(null),X(null),ue()}:qt,Ge=v==="success"?!1:!Ht;if(!t)return null;const tt=D?I||`Pay ${n.symbol}`:i,lt=D?W:e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[e.jsx(yr,{color:E}),e.jsx("p",{style:{fontSize:"13px",color:E,margin:0,lineHeight:"1.5"},children:ft})]});if(D){const Se=ke&&(ke.status==="success"||ke.status==="failed")?[{asset:{symbol:P?.asset?.symbol||n.symbol,address:P?.asset?.address||""},amount:Ye,txHash:ke.txHash||"",success:ke.status==="success",error:ke.status==="failed"?ke.error:void 0}]:void 0;return e.jsx(Ct,{isOpen:t,onClose:s,title:tt,subtitle:lt,styles:b,dark:S,footerLinkText:"Spicenet accounts \u2192",children:e.jsxs("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[C&&e.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:e.jsxs("button",{onClick:C,style:{background:"none",border:"none",cursor:"pointer",padding:0,display:"flex",alignItems:"center",gap:"4px",color:A,fontSize:"12px",fontWeight:500,fontFamily:J,textDecoration:"underline",textUnderlineOffset:"2px"},children:["Add Funds",e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:A,strokeWidth:"1.8",children:[e.jsx("circle",{cx:"6",cy:"6",r:"5"}),e.jsx("path",{d:"M6 4v4M4 6h4",strokeLinecap:"round"})]})]})}),e.jsx("div",{style:{marginBottom:"12px"},children:e.jsx(as,{assets:De,selectedAsset:P??void 0,onAssetSelect:et,onAmountChange:()=>{},label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:P?.asset?ge?ut?"...":_e?`~${parseFloat(V.formatUnits(_e.amountIn,P.asset.decimals)).toFixed(6)}`:void 0:Ye??void 0:void 0,dark:S,theme:ie,styles:b})}),e.jsx(Sn,{variant:"pay",destinationSymbol:n.symbol,destinationLogoURI:n.logoURI,destinationDecimals:n.decimals,primaryColor:A,fontFamily:J,textPrimary:j,textSecondary:E,cardBg:Q,cardBorder:Y,dk:w,dark:S,isQuoting:ut,quoteError:rt,estimatedOutput:wt,paymentAmount:Ye,needsSwap:ge,exactOutputSwap:_e,adjustable:x==="adjustable",maxAmount:f,onAmountChange:Pt}),Z&&e.jsx("div",{style:{marginBottom:"12px",padding:"10px 14px",backgroundColor:M.errorBg,border:`1px solid ${M.errorBorder}`,borderRadius:"6px"},children:e.jsx("p",{style:{color:M.errorText,fontSize:"13px",margin:0,fontFamily:J},children:Z})}),e.jsx(Re.Button,{variant:"outline",fullWidth:!0,onClick:ts,disabled:!Ht,loading:We,dark:S,styles:{button:{backgroundColor:A}},children:te}),ke&&de&&e.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:S?w.shell:"white",borderRadius:S?"12px":"6px",padding:"16px 0"},children:e.jsx(ps,{type:"payment",isOpen:ke.status!=="processing",isProcessing:We||ke.status==="processing",closeOnComplete:!1,chainName:O.getChainName(F),explorerUrl:O.getExplorerUrl(F,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{pe(!1),ot(null),ts()},onNewTx:Rt,onClose:()=>{pe(!1),ot(null)},onComplete:Rt,results:Se,styles:b,dark:S})})]})})}return e.jsxs(Ct,{isOpen:t,onClose:s,title:tt,subtitle:lt,dark:S,styles:b,theme:R,children:[e.jsx("div",{style:{marginBottom:"16px"},children:e.jsx(as,{assets:De,selectedAsset:P||void 0,onAssetSelect:et,onAmountChange:gt,disabled:We||v==="success",showBalance:!0,showMaxButton:!0,label:"From Spice Balance",placeholder:"0.00",theme:ie,styles:b,dark:T,maxAmount:at>0?at.toString():void 0})}),P?.asset&&!he&&e.jsx(Sn,{variant:"supply",destinationSymbol:n.symbol,destinationLogoURI:n.logoURI,destinationDecimals:n.decimals,primaryColor:A,fontFamily:J,textPrimary:j,textSecondary:E,cardBg:Q,cardBorder:Y,dark:S,isQuoting:ut,quoteError:rt,estimatedOutput:wt}),v!=="idle"&&e.jsxs("div",{style:{padding:"10px 14px",borderRadius:"10px",marginBottom:"16px",backgroundColor:v==="success"?M.successBg:v==="error"?M.errorBg:Q,border:`1px solid ${v==="success"?M.successBorder:v==="error"?M.errorBorder:Y}`},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[v==="success"?e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:e.jsx("path",{d:"M5 13l4 4L19 7",stroke:M.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):v==="error"?e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:e.jsx("path",{d:"M18 6L6 18M6 6l12 12",stroke:M.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):e.jsx(Re.Spinner,{size:14,color:A}),e.jsx("span",{style:{fontSize:"13px",fontWeight:500,color:v==="success"?M.successText:v==="error"?M.errorText:j,fontFamily:J,flex:1},children:v==="success"?"Transaction successful!":v==="error"?se||"Transaction failed":Hn[v]||se}),v==="success"&&N&&e.jsx("a",{href:`${Gt}/tx/${N}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:A,fontFamily:J,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),v==="error"&&e.jsx("button",{onClick:()=>{k("idle"),ee(null),setTimeout(qt,50)},style:{background:"none",border:"none",fontSize:"12px",color:A,fontFamily:J,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),Mt>=0&&v!=="success"&&v!=="error"&&e.jsx("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${E}22`,overflow:"hidden"},children:e.jsx("div",{style:{height:"100%",borderRadius:"2px",backgroundColor:A,width:`${(Mt+1)/On.length*100}%`,transition:"width 400ms ease"}})})]}),Z&&v==="idle"&&e.jsx("div",{style:{padding:"10px 14px",borderRadius:"10px",backgroundColor:M.errorBg,border:`1px solid ${M.errorBorder}`,marginBottom:"16px"},children:e.jsx("p",{style:{fontSize:"13px",color:M.errorText,margin:0,fontFamily:J},children:Z})}),e.jsx(Re.Button,{variant:"outline",fullWidth:!0,disabled:Ge,onClick:xe,style:{height:"56px",backgroundColor:Ge?`${U}66`:v==="success"?M.successBg:U,color:v==="success"?M.successText:G,border:`1px solid ${v==="success"?M.successBorder:Vt}`,fontSize:"14px",fontWeight:700,letterSpacing:"2px",fontFamily:'"IBM Plex Mono", monospace',boxShadow:Ge?"none":`3px 3px 0px ${Ot}, 4px 4px 0px ${Vt}`,cursor:Ge?"not-allowed":"pointer",opacity:Ge?.6:1},children:Jt})]})},Cr=t=>e.jsx(Vn,{isOpen:t.isOpen,onClose:t.onClose,amountDirection:"output",destinationToken:{address:t.paymentTokenAddress,symbol:t.paymentTokenSymbol,decimals:t.paymentTokenDecimals,chainId:t.paymentChainId,logoURI:t.paymentTokenLogoURI},buildActionCalls:t.buildActionCalls,actionLabel:t.ctaLabel||"PAY",paymentAmount:t.paymentAmount,amountInputMode:t.amountInputMode,minPaymentAmount:t.minPaymentAmount,maxPaymentAmount:t.maxPaymentAmount,onAmountChange:t.onAmountChange,sourceChains:t.sourceChains,title:t.title,subtitle:t.subtitle,onAddFunds:t.onAddFunds,styles:t.styles,dark:t.dark,onSuccess:t.onPaymentSuccess,onError:t.onPaymentError}),br=({label:t="Export Wallet",style:s,className:n,onExport:a,onError:i})=>{const[l,r]=o.useState(!1),[c,d]=o.useState(!1),{primaryColor:p}=z.useSpiceBrand(),u=o.useContext(z.SpiceFlowProviderContext),{isAuthenticated:x}=zt();let g=null;try{g=Zt.usePrivy()}catch{}let f=null,h=null;try{f=ds.useEmbeddedReveal(),h=ds.useDynamicContext()}catch{f=null,h=null}const b=Tt.getDynamicEmbeddedWallet(h),m=o.useCallback(async()=>{if(!x){i?.("User is not authenticated. Please log in first.");return}try{if(u?.provider==="dynamic"){if(!f||!b){i?.("Dynamic is not available. Ensure the app is wrapped in a DynamicContextProvider.");return}await f.initExportProcess(!1),a?.();return}if(!g){i?.("Privy is not available. Ensure the app is wrapped in a PrivyProvider.");return}await g.exportWallet(),a?.()}catch(C){const y=C instanceof Error?C.message:"Failed to export wallet";console.error("Export wallet error:",C),i?.(y)}},[b,f,x,i,a,g,u?.provider]),I=!x,W={padding:"10px 20px",borderRadius:"8px",fontFamily:'"IBM Plex Mono", monospace',fontSize:"14px",fontWeight:500,letterSpacing:"0.4px",textTransform:"uppercase",cursor:I?"not-allowed":"pointer",opacity:I?.5:1,border:"1px solid #0e0d0b",color:"#0e0d0b",backgroundColor:c?`${p}cc`:l?`${p}ee`:p,transition:"all 150ms ease",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"8px",...s};return e.jsxs("button",{onClick:m,onMouseEnter:()=>r(!0),onMouseLeave:()=>{r(!1),d(!1)},onMouseDown:()=>d(!0),onMouseUp:()=>d(!1),disabled:I,className:n,style:W,children:[e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),e.jsx("polyline",{points:"17 8 12 3 7 8"}),e.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]}),t]})};function Qn(t){const s=o.useContext(z.SpiceFlowProviderContext),n=Ut(),a=t?.enabled===!1?void 0:n,i=s?.network?{network:s.network,pollIntervalMs:t?.pollIntervalMs,chainIds:t?.chainIds??s.supportedChainIds}:void 0;return{...mn(a,i),embeddedWalletAddress:n}}const wr=({appName:t,status:s,statusLabel:n,totalUsdValue:a,breakdownSubtitle:i,address:l,dk:r,dark:c=!1,showModeToggle:d,isEmbeddedMode:p=!0,onModeToggle:u})=>{const[x,g]=o.useState(!1),f=async()=>{l&&await io(l)&&(g(!0),setTimeout(()=>g(!1),2e3))},h=s==="active",b=n||(h?"Active":"Inactive"),m=h?"#10b981":"#9ca3af";return e.jsxs("div",{children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[e.jsxs("div",{style:{fontSize:"13px",fontWeight:600,color:c?r.textPrimary:"#111827"},children:[t," Account"]}),d?e.jsxs("button",{onClick:u,style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:c?r.hoverBg:"#f3f4f6",border:c?`1px solid ${r.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"11px",fontWeight:600,fontFamily:'"IBM Plex Mono", monospace',color:c?r.textSecondary:"#6b7280",transition:"all 150ms ease",letterSpacing:"0.02em"},children:[e.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:p?"#22c55e":"#f59e0b"}}),e.jsx("span",{children:p?"Embedded":"External"})]}):e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:c?r.hoverBg:h?"#ecfdf5":"#f3f4f6",border:c?`1px solid ${r.cardBorder}`:h?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[e.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:m}}),e.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:c?r.textSecondary:h?"#065f46":"#6b7280"},children:b})]})]}),e.jsx("div",{style:{fontSize:"28px",fontWeight:700,color:c?r.textPrimary:"#111827",lineHeight:1.2,marginBottom:"2px"},children:rs(a)}),i&&e.jsx("div",{style:{fontSize:"12px",color:c?r.textSecondary:"#6b7280",marginBottom:"8px"},children:i}),l&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[e.jsx("span",{style:{fontSize:"12px",fontFamily:'"IBM Plex Mono", monospace',color:c?r.textSecondary:"#9ca3af"},children:ao(l)}),e.jsx("button",{onClick:f,style:{padding:"2px 6px",fontSize:"10px",fontWeight:500,backgroundColor:"transparent",color:c?r.textSecondary:"#9ca3af",border:"none",cursor:"pointer",borderRadius:"4px",transition:"all 150ms ease"},title:"Copy address",children:x?"Copied":"Copy"})]})]})},vr=({pendingDeposits:t,onCompleteDeposit:s,dk:n,dark:a=!1})=>t.length===0?null:e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:a?n.textSecondary:"#6b7280",marginBottom:"8px",textTransform:"uppercase"},children:"Pending Deposits"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:t.map((i,l)=>{const r=O.getChainConfig(i.chainId)?.displayName||`Chain ${i.chainId}`;return e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:a?n.warningBg:"#fffbeb",border:a?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"8px"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:a?n.hoverBg:"#fde68a",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:a?n.warningText:"#92400e"},children:i.tokenSymbol.charAt(0)}),e.jsxs("div",{children:[e.jsxs("div",{style:{fontSize:"13px",fontWeight:500,color:a?n.textPrimary:"#111827"},children:[i.amount," ",i.tokenSymbol]}),e.jsxs("div",{style:{fontSize:"11px",color:a?n.warningText:"#92400e"},children:["on ",r]})]})]}),e.jsx("button",{onClick:()=>s?.(i),style:{padding:"4px 12px",fontSize:"11px",fontWeight:600,backgroundColor:a?n.hoverBg:"#fef3c7",color:a?n.textPrimary:"#92400e",border:a?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"9999px",cursor:"pointer",transition:"all 150ms ease"},children:"Complete"})]},`${i.tokenAddress}-${i.chainId}-${l}`)})})]}),kr=({spiceAssets:t,loading:s,dk:n,dark:a=!1})=>{const i={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:a?n.textSecondary:"#6b7280",marginBottom:"8px",textTransform:"uppercase"},l={backgroundColor:a?n.cardBg:"#f9fafb",border:a?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return s?e.jsxs("div",{children:[e.jsx("div",{style:i,children:"Idle Balances"}),[1,2].map(r=>e.jsx("div",{style:{...l,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},r))]}):t.length===0?e.jsxs("div",{children:[e.jsx("div",{style:i,children:"Idle Balances"}),e.jsx("div",{style:{...l,padding:"16px",textAlign:"center",fontSize:"13px",color:a?n.textSecondary:"#9ca3af"},children:"No assets yet. Deposit to get started."})]}):e.jsxs("div",{children:[e.jsx("div",{style:i,children:"Idle Balances"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:t.map((r,c)=>{const d=O.getChainConfig(r.chainId)?.displayName||`Chain ${r.chainId}`;return e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...l},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[r.logoURI?e.jsx("img",{src:r.logoURI,alt:r.tokenSymbol,style:{width:"24px",height:"24px",borderRadius:"50%"}}):e.jsx("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:a?n.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:a?n.textSecondary:"#6b7280"},children:r.tokenSymbol.charAt(0)}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:a?n.textPrimary:"#111827"},children:r.tokenSymbol}),e.jsx("div",{style:{fontSize:"11px",color:a?n.textSecondary:"#9ca3af"},children:d})]})]}),e.jsxs("div",{style:{textAlign:"right"},children:[e.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:a?n.textPrimary:"#111827"},children:ks(r.balanceFormatted)}),e.jsx("div",{style:{fontSize:"11px",color:a?n.textSecondary:"#9ca3af"},children:rs(r.usdValue)})]})]},`${r.tokenAddress}-${r.chainId}-${c}`)})})]})},Sr=({section:t,dk:s,dark:n=!1})=>{const a=i=>{switch(i){case"green":return"#10b981";case"red":return"#ef4444";default:return n?s.textPrimary:"#111827"}};return e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n?s.textSecondary:"#6b7280",marginBottom:"8px",textTransform:"uppercase"},children:t.title}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:t.items.map((i,l)=>e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:n?s.cardBg:"#f9fafb",border:n?`1px solid ${s.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[i.tokenLogoURI?e.jsx("img",{src:i.tokenLogoURI,alt:i.tokenSymbol,style:{width:"20px",height:"20px",borderRadius:"50%"}}):e.jsx("div",{style:{width:"20px",height:"20px",borderRadius:"50%",backgroundColor:n?s.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",fontWeight:600,color:n?s.textSecondary:"#6b7280"},children:i.tokenSymbol.charAt(0)}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:n?s.textPrimary:"#111827"},children:i.tokenSymbol}),e.jsx("div",{style:{fontSize:"11px",color:n?s.textSecondary:"#6b7280"},children:i.label})]})]}),e.jsx("div",{style:{fontSize:"13px",fontWeight:600,color:a(i.valueColor)},children:i.displayValue})]},l))})]})},Ir=({onDepositClick:t,onWithdrawClick:s,depositDisabled:n=!1,withdrawDisabled:a=!1,primaryColor:i="#EA4B4B",dark:l=!1})=>e.jsxs("div",{style:{display:"flex",gap:"8px"},children:[e.jsx(Re.Button,{variant:"outline",onClick:t,disabled:n,dark:l,styles:{button:{backgroundColor:i}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),e.jsx(Re.Button,{variant:"outline",onClick:s,disabled:a,dark:l,styles:{button:{backgroundColor:i}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),jr=({appName:t,status:s,statusLabel:n,totalUsdValue:a,breakdownSubtitle:i,address:l,spiceAssets:r,spiceAssetsLoading:c,pendingDeposits:d,customSections:p,onDepositClick:u,onWithdrawClick:x,onCompleteDeposit:g,primaryColor:f,dk:h,dark:b=!1,showModeToggle:m,isEmbeddedMode:I,onModeToggle:W})=>{const[C,y]=o.useState(!1);return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[e.jsx(wr,{appName:t,status:s,statusLabel:n,totalUsdValue:a,breakdownSubtitle:i,address:l,dk:h,dark:b,showModeToggle:m,isEmbeddedMode:I,onModeToggle:W}),e.jsx("div",{style:{height:"1px",backgroundColor:b?"#2d2d2d":"#e5e7eb"}}),e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>y(!C),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:b?h.cardBg:"#f9fafb",border:b?`1px solid ${h.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:b?h.textSecondary:"#6b7280",fontSize:"12px",fontWeight:500},children:[e.jsx("span",{children:"How It Works"}),e.jsx("span",{style:{transform:C?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),C&&e.jsxs("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:b?h.cardBg:"#f0fdf4",border:b?`1px solid ${h.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:b?h.textSecondary:"#374151"},children:["Fund your ",t," Account from any supported chain (10+ EVM chains). Once funded, transact gas-free and asset-abstracted on"," ",t,"."]})]}),e.jsx(vr,{pendingDeposits:d,onCompleteDeposit:g,dk:h,dark:b}),e.jsx(kr,{spiceAssets:r,loading:c,dk:h,dark:b}),p.map((B,D)=>e.jsx(Sr,{section:B,dk:h,dark:b},D)),e.jsx(Ir,{onDepositClick:u,onWithdrawClick:x,primaryColor:f,dark:b})]})},Zs=380,is=8,Er=({appName:t="Spice",status:s="active",statusLabel:n,customSections:a=[],extraAssets:i=[],tokenPrices:l={},breakdownLabels:r=[],supportedChains:c,styles:d,dark:p=!1,onDepositSuccess:u,onDepositClick:x,onWithdrawClick:g,onCompleteDeposit:f,showModeToggle:h=!1,defaultMode:b})=>{const m=o.useContext(z.SpiceFlowProviderContext),I=m?.mode!=="7702";o.useEffect(()=>{b&&m?.setMode&&m.setMode(b==="non7702"?"ondemand":"7702")},[]);const[W,C]=o.useState(!1),[y,B]=o.useState(null),[D,R]=o.useState({top:0,left:0,placement:"below"}),S=o.useRef(null),A=o.useRef(null),{address:w,isConnected:M}=zt(),J=Ut(),{address:T}=Qe.useAccount(),{dark:j,primaryColor:E,dk:Q}=z.useSpiceBrand(d,p),Y=o.useMemo(()=>c||K.getChainIdsByNetwork("mainnet"),[c]),{assets:U,loading:G}=os({address:w,supportedChains:Y,enabled:!!w&&!I,refetchInterval:3e4}),ie=o.useMemo(()=>[...I?[]:U.map(P=>{const Ie=P.balanceUsd||0,Ee=Number(P.balance)/Math.pow(10,P.decimals),ne=Ie>0?Ie:(l[P.symbol]||0)*Ee;return{tokenAddress:P.address,tokenSymbol:P.symbol,tokenDecimals:P.decimals,chainId:P.chainId,balance:P.balance.toString(),balanceFormatted:P.balanceFormatted,usdValue:ne,logoURI:P.logoURI}}),...i].filter(P=>P.usdValue>=.01),[I,U,l,i]),F=o.useMemo(()=>ie.reduce((P,Ie)=>P+Ie.usdValue,0),[ie]),{pendingDeposits:L}=Qn({chainIds:Y,enabled:!!w}),$=o.useMemo(()=>a.reduce((P,Ie)=>P+Ie.totalValue,0),[a]),me=F+$,we=o.useMemo(()=>{const P=[];F>0&&P.push(`${rs(F)} idle`);for(const Ie of a){const Ee=r.find(ne=>ne.sectionTitle===Ie.title)?.label||Ie.title.toLowerCase();P.push(`${rs(Ie.totalValue)} ${Ee}`)}return P.join(" \xB7 ")},[F,a,r]),re=o.useCallback(P=>{f?f(P):B(P)},[f]),le=o.useCallback(()=>{B(null)},[]),ce=o.useCallback(()=>{B(null),u?.()},[u]),Be=o.useCallback(()=>{if(!S.current)return;const P=S.current.getBoundingClientRect(),Ie=window.innerHeight-P.bottom-is,Ee=P.top-is,ne=Ie>=400||Ie>=Ee?"below":"above",We=Math.max(is,Math.min(P.right-Zs,window.innerWidth-Zs-is)),ze=ne==="below"?P.bottom+is:P.top-is;R({top:ze,left:We,placement:ne})},[]);o.useLayoutEffect(()=>{W&&Be()},[W,Be]),o.useEffect(()=>{if(!W)return;const P=ne=>{S.current&&!S.current.contains(ne.target)&&A.current&&!A.current.contains(ne.target)&&C(!1)},Ie=ne=>{ne.key==="Escape"&&C(!1)},Ee=()=>Be();return document.addEventListener("mousedown",P),document.addEventListener("keydown",Ie),window.addEventListener("scroll",Ee,{passive:!0}),window.addEventListener("resize",Be),()=>{document.removeEventListener("mousedown",P),document.removeEventListener("keydown",Ie),window.removeEventListener("scroll",Ee),window.removeEventListener("resize",Be)}},[W,Be]);const ye=m?.mode==="7702",Te=ye?J||w:T||w,ue=o.useCallback(()=>{m?.setMode&&m.setMode(ye?"ondemand":"7702")},[m,ye]);if(typeof window>"u")return null;const He=e.jsxs("button",{ref:S,onClick:()=>C(!W),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:j?Q.hoverBg:"#ffffff",border:j?`1px solid ${Q.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:'"Helvetica Neue", sans-serif',color:j?Q.textPrimary:"#111827",transition:"all 150ms ease",boxShadow:j?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[e.jsx("span",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:E,flexShrink:0}}),e.jsxs("span",{children:[t," Account"]}),M&&e.jsxs("span",{style:{color:j?Q.textSecondary:"#6b7280"},children:["\xB7 ",rs(me)]}),e.jsx("span",{style:{fontSize:"10px",color:j?Q.textSecondary:"#9ca3af",transform:W?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),De=W?Bs.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:9998},onClick:()=>C(!1)}),e.jsx("div",{ref:A,style:{position:"fixed",top:D.placement==="below"?`${D.top}px`:"auto",bottom:D.placement==="above"?`${window.innerHeight-D.top}px`:"auto",left:`${D.left}px`,width:`${Zs}px`,maxHeight:"80vh",backgroundColor:j?Q.shell:"#ffffff",border:j?`1px solid ${Q.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:9999,overflow:"hidden",animation:"accountDisplayFadeIn 150ms ease-out"},children:e.jsx(jr,{appName:t,status:s,statusLabel:n,totalUsdValue:me,breakdownSubtitle:we,address:h?Te:w,spiceAssets:ie,spiceAssetsLoading:G,pendingDeposits:L,customSections:a,onDepositClick:x,onWithdrawClick:g,onCompleteDeposit:re,primaryColor:E,dk:Q,dark:j,showModeToggle:h,isEmbeddedMode:ye,onModeToggle:ue})}),e.jsx("style",{children:`
114
+ `})]})},nr=({color:t})=>e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",style:{marginTop:"1px",flexShrink:0},children:[e.jsx("circle",{cx:"7",cy:"7",r:"6.5",stroke:t,strokeWidth:"1.2"}),e.jsx("path",{d:"M7 6v4",stroke:t,strokeWidth:"1.2",strokeLinecap:"round"}),e.jsx("circle",{cx:"7",cy:"4.5",r:"0.7",fill:t})]}),or=({isOpen:t,onClose:s,lockBatches:n,lockTokenSymbol:a,lockTokenLogoURI:i,destinationInputHook:l,sourceAssetInputHook:r,lockDurationHook:c,lockChainId:d,durationOptions:p,votingPowerEstimate:u,sourceChains:x,sourceAssets:g=[],escrowAddress:f,includeWalletAssets:h=!1,destinationTokenAddress:b,onLockSuccess:m,onLockExecute:I,sourceToDestinationConversionRate:W,estimatedOutputAmount:C,onAddFunds:y,styles:B,dark:D=!1})=>{const{theme:R,dark:S,primaryColor:A,dk:w}=z.useSpiceBrand(B,D),M=R.typography.fontFamily,J=o.useContext(z.SpiceFlowProviderContext),T=(J?.mode||"7702")!=="7702",j=S?w.cardBg:B?.assetSelector?.backgroundColor||B?.secondaryBackground||"#e9e9e9",E=S?`1px solid ${w.cardBorder}`:"0.5px solid #A8A8A7",Q=S?"12px":"6px",Y=S?w.textPrimary:"#111827",U=S?w.textSecondary:"#6b7280",G=o.useMemo(()=>({...B,assetSelector:{...B?.assetSelector,backgroundColor:S?w.cardBg:B?.assetSelector?.backgroundColor,borderRadius:S?"12px":B?.assetSelector?.borderRadius},secondaryBackground:S?w.cardBg:B?.secondaryBackground}),[B,S]),ie=o.useMemo(()=>S?{...R,colors:{...R.colors,secondary:w.cardBg,surfaceHover:w.hoverBg,border:w.cardBorder,borderHover:w.inputBorder}}:R,[S,R]),[F,L]=o.useState(null),[$,me]=o.useState(0),we=c?.selectedDurationIdx??$,re=c?.setSelectedDurationIdx??me,[le,ce]=o.useState(!1),[Be,ye]=o.useState(null),[Te,ue]=o.useState(!1),[He,De]=o.useState(!1),[P,Ie]=o.useState(null);Qe.useWalletClient(),Qe.useSwitchChain();const{chain:Ee,address:ne}=Qe.useAccount();Qe.useConfig();const We=o.useRef(Ee);o.useEffect(()=>{We.current=Ee},[Ee]);const ze=zt(),{isReady:Z,isAuthenticated:ee,isConnected:v,address:k,provider:se,actions:ae}=ze,{intentStatus:N,startStatusPolling:X,clearStatus:de}=Ns({checkStepStatus:(te,xe)=>z.relayerService.checkStepStatus(te,xe),retryStep:async(te,xe)=>{const[Ge,tt]=te.split("/"),lt=parseInt(tt||"0",10);await z.relayerService.executeStep(Ge,lt,xe,{action:"execute"})},maxRetries:3}),{assets:pe,refetch:ke}=os({address:k,supportedChains:x,enabled:v&&!T,refetchInterval:3e4}),ot=o.useMemo(()=>{if(g.length===0)return pe;const te=new Set(g.map(xe=>xe.toLowerCase()));return pe.filter(xe=>te.has(xe.address.toLowerCase()))},[pe,g]),fe=Ut(),Ce=T?ne:fe,be=o.useMemo(()=>{if(!h)return[];const te=new Set,xe=[],Ge=tt=>{if(!tt)return;const lt=tt.toLowerCase();te.has(lt)||(te.add(lt),xe.push(V.getAddress(tt)))};if(b&&Ge(b),T)for(const tt of g)Ge(tt);return xe},[h,T,b,g]),Ye=o.useMemo(()=>be.map(te=>te.toLowerCase()).sort().join(","),[be]),ht=o.useMemo(()=>JSON.stringify([...x||[]].sort()),[x]),[ut,rt]=o.useState([]),wt=o.useRef(0),xt=o.useCallback(async()=>{if(!h||!Ce||be.length===0){wt.current++,rt([]);return}const te=++wt.current,xe=V.getAddress(Ce),Ge=x&&x.length>0?x:[d],tt=be.map(Me=>{const je=Me.toLowerCase();for(const st of Ge){const Ve=O.getChainConfig(st)?.supportedTokens?.find(Ke=>Ke.address.toLowerCase()===je);if(Ve)return{address:Me,chainId:st,configToken:{decimals:Ve.decimals,symbol:Ve.symbol,name:Ve.name,logo:Ve.logo}}}return{address:Me,chainId:d}}),lt=new Map;for(const Me of tt){const je=lt.get(Me.chainId)||[];je.push(Me),lt.set(Me.chainId,je)}const Se=async(Me,je)=>{try{const st=await Dt.readContract(Me,{address:je.address,abi:O._,functionName:"balanceOf",args:[xe]});let Ve,Ke,Ae,Le;if(je.configToken)Ve=je.configToken.decimals,Ke=je.configToken.symbol,Ae=je.configToken.name,Le=je.configToken.logo;else{const[St,H,_]=await Promise.all([Dt.readContract(Me,{address:je.address,abi:O._,functionName:"decimals",args:[]}).catch(()=>18),Dt.readContract(Me,{address:je.address,abi:O._,functionName:"symbol",args:[]}).catch(()=>"TOKEN"),Dt.readContract(Me,{address:je.address,abi:O._,functionName:"name",args:[]}).catch(()=>"TOKEN")]);Ve=Number(St),Ke=H,Ae=_}const Xe=!!b&&je.address.toLowerCase()===b.toLowerCase()&&je.chainId===d;Xe&&i&&(Le=i),Xe&&a&&!je.configToken&&(Ke==="TOKEN"&&(Ke=a),Ae==="TOKEN"&&(Ae=a));const kt=parseFloat((Number(st)/Math.pow(10,Ve)).toFixed(6));return{address:je.address,name:Ae,symbol:Ke,decimals:Ve,balance:st,balanceFormatted:kt,balanceUsd:0,logoURI:Le,isNative:!1,chainId:je.chainId}}catch{return null}},Fe=await Promise.all(Array.from(lt.entries()).map(async([Me,je])=>{let st;try{st=O.getClientForChain(Me)}catch{return[]}const Ve=[],Ke=[];for(const Le of je){const Xe=Ve.length;Ve.push({address:Le.address,abi:O._,functionName:"balanceOf",args:[xe]}),Le.configToken||Ve.push({address:Le.address,abi:O._,functionName:"decimals",args:[]},{address:Le.address,abi:O._,functionName:"symbol",args:[]},{address:Le.address,abi:O._,functionName:"name",args:[]}),Ke.push({start:Xe,item:Le})}let Ae=null;try{Ae=await st.multicall({contracts:Ve})}catch{Ae=null}return Ae?Ke.map(({start:Le,item:Xe})=>{const kt=Ae[Le],St=kt?.status==="success"?kt.result:0n;let H,_,q,oe;if(Xe.configToken)H=Xe.configToken.decimals,_=Xe.configToken.symbol,q=Xe.configToken.name,oe=Xe.configToken.logo;else{const nt=Ae[Le+1],Ne=Ae[Le+2],Je=Ae[Le+3];H=nt?.status==="success"?Number(nt.result):18,_=Ne?.status==="success"?Ne.result:"TOKEN",q=Je?.status==="success"?Je.result:_}const Pe=!!b&&Xe.address.toLowerCase()===b.toLowerCase()&&Xe.chainId===d;Pe&&i&&(oe=i),Pe&&a&&!Xe.configToken&&(_==="TOKEN"&&(_=a),q==="TOKEN"&&(q=a));const pt=parseFloat((Number(St)/Math.pow(10,H)).toFixed(6));return{address:Xe.address,name:q,symbol:_,decimals:H,balance:St,balanceFormatted:pt,balanceUsd:0,logoURI:oe,isNative:!1,chainId:Xe.chainId}}):(await Promise.all(je.map(Le=>Se(st,Le)))).filter(Le=>Le!==null)}));te===wt.current&&rt(Fe.flat())},[h,Ce,Ye,ht,d,b,i,a]);o.useEffect(()=>{if(!h){rt([]);return}xt();const te=setInterval(()=>{xt()},15e3);return()=>clearInterval(te)},[xt,h]);const _e=o.useCallback(()=>{xt()},[xt]),vt=o.useMemo(()=>ut.filter(te=>te.balance>0n),[ut]),Bt=o.useMemo(()=>{if(T)return vt.map(xe=>({...xe,_source:"wallet"}));if(!h)return ot;const te=[];for(const xe of vt)te.push({...xe,_source:"wallet"});for(const xe of ot)te.push({...xe,_source:"spice"});return te},[T,h,vt,ot]),he=o.useRef(null),ge=o.useRef(null);o.useEffect(()=>{ge.current=F},[F]),o.useEffect(()=>{t||(L(null),ye(null),ce(!1),De(!1),Ie(null),ue(!1),de())},[t,de]),o.useEffect(()=>{l&&l.assetAmount!==(F?.amount||"")&&L(te=>te&&{...te,amount:l.assetAmount})},[l?.assetAmount]),o.useEffect(()=>{r&&r.assetAmount!==(F?.amount||"")&&L(te=>te&&{...te,amount:r.assetAmount})},[r?.assetAmount]),o.useEffect(()=>{if(N?.overallStatus==="success"&&N.intentId&&he.current!==N.intentId&&k){const te=N.steps.find(xe=>xe.transactionHash);if(te?.transactionHash){he.current=N.intentId;const xe=ge.current;if(!xe?.asset||!xe.amount||xe.asset._source==="wallet")return;const Ge=V.parseUnits(xe.amount,xe.asset.decimals);if(Ge===0n)return;z.relayerService.submitSpiceDeposit({user:k,txHash:te.transactionHash,sender:k,tokenAddress:xe.asset.address,chainId:xe.asset.chainId??d,amount:Ge.toString(),isDeposit:!1}).then(()=>ke()).catch(()=>{he.current=null})}}},[N,k,d,ke]);const ve=parseFloat(F?.amount||"")||0,Ze=o.useMemo(()=>F?.asset?F.asset._source==="wallet"?F.asset.balanceFormatted??0:ot.find(te=>te.address.toLowerCase()===F.asset.address.toLowerCase()&&te.chainId===F.asset.chainId)?.balanceFormatted??0:0,[F?.asset,ot]),at=ve>0&&ve>Ze,qe=c?.selectedDuration??p[we]??p[0],et=o.useMemo(()=>!F?.asset||!b?!1:F.asset.address.toLowerCase()===b.toLowerCase()&&F.asset.chainId===d,[F?.asset,b,d]),gt=o.useMemo(()=>ve<=0?0:et?ve:!W||W<=0?0:ve/W,[ve,W,et]),Pt=o.useMemo(()=>gt<=0?null:gt.toLocaleString(void 0,{maximumFractionDigits:2}),[gt]),Lt=u&&gt>0&&qe?u(gt,qe.months):void 0,Xt=o.useMemo(()=>ve<=0?"$0.00":et&&W?(ve*W).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!W||W<=0?"$0.00":ve.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[ve,W,et]),qt=o.useMemo(()=>{if(!Pt)return null;const te=parseFloat(Pt.replace(/,/g,""));return et&&W?(te*W).toLocaleString(void 0,{maximumFractionDigits:2}):W?(te*W).toLocaleString(void 0,{maximumFractionDigits:2}):null},[Pt,W,et]),ts=o.useCallback(te=>{L(xe=>({asset:te,amount:xe?.asset?.address===te.address&&xe?.asset?.chainId===te.chainId&&xe.amount||""})),ye(null),r?.setSelectedAsset&&r.setSelectedAsset({symbol:te.symbol,address:te.address,decimals:te.decimals,chainId:te.chainId})},[r?.setSelectedAsset]),Ft=o.useCallback(te=>{L(xe=>xe&&{...xe,amount:te}),ye(null),l&&l.setAssetAmount(te),r&&r.setAssetAmount(te)},[l,r]),Et=o.useCallback(()=>{if(typeof n=="function"){if(!F?.asset||!F.amount)throw new Error("Select an asset and enter an amount");return n({asset:F.asset,amount:F.amount,amountWei:V.parseUnits(F.amount,F.asset.decimals)})}return n},[n,F]),Rt=o.useCallback(async()=>{if(!v||!k)throw new Error("Please connect your wallet to continue");const te=Et();if(te.length===0)throw new Error("No lock batches configured");if(!Z||!ee)throw new Error(`Please authenticate with ${se||"wallet provider"} to continue`);const xe=[...te],Ge=[...new Set(xe.map(Ae=>Ae.chainId))],tt=[];for(const Ae of Ge){const Le=O.getClientForChain(Ae),Xe=O.getDelegateContractAddress(Ae),kt=await K.getAccountNonce(k,Le),St=await ae.signAuthorization({contractAddress:Xe,chainId:Ae,nonce:Number(kt)});tt.push(St)}const lt=K.hashChainBatches(xe),Se=Math.floor(Date.now()/1e3)+60*10,Fe=lt.map(Ae=>Ae.hash),Me=V.keccak256(V.encodeAbiParameters([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,BigInt(Se),Fe])),je=await ae.signMessage({raw:Me}),st=typeof je=="string"?je:je.signature;if(!st)throw new Error("Failed to sign intent authorization");const Ve={mode:"7702",signatureType:"ecdsa",signature:st,nbf:0,exp:Se,chainBatches:lt.map((Ae,Le)=>({hash:Ae.hash,chainId:Ae.chainId,tokenTransfers:xe[Le].tokenTransfers??[],calls:Ae.calls}))},Ke=await z.relayerService.createAction({user:k,chainAuthorizations:tt.map(Ae=>({r:Ae.r,s:Ae.s,yParity:Ae.yParity,address:Ae.address,chainId:Number(Ae.chainId),nonce:Number(Ae.nonce)})),intents:[Ve]});if(Ke){const Ae=z.createInitialSteps(xe,O.getChainName),[Le,Xe]=Ke.intentIds[0].split("/"),kt=parseInt(Xe||"0",10);X(Ke.intentIds[0],Ae);for(let St=0;St<xe.length;St++)await Us(()=>z.relayerService.executeStep(Le,kt,St,{action:"execute"}))}},[Et,ze,X]),Ht=o.useCallback(async()=>{if(!F?.asset||!F.amount)throw new Error("Select an asset and enter an amount");if(!k||!fe)throw new Error("Embedded wallet not connected");const te=F.asset,xe=V.parseUnits(F.amount,te.decimals),Ge=f||O.getDelegateContractAddress(d),tt=await ae.getEthereumProvider();await tt.request({method:"wallet_switchEthereumChain",params:[{chainId:`0x${d.toString(16)}`}]});const lt=O.getChainConfig(d),Se=V.createWalletClient({account:fe,transport:V.custom(tt),chain:lt?.viemChain});let Fe;if(te.isNative||K.isNativeToken(te.address))Fe=await Se.sendTransaction({to:Ge,value:xe,chain:lt?.viemChain});else{const Me=V.encodeFunctionData({abi:O._,functionName:"transfer",args:[Ge,xe]});Fe=await Se.sendTransaction({to:te.address,data:Me,chain:lt?.viemChain})}if((await O.getClientForChain(d).waitForTransactionReceipt({hash:Fe,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to escrow failed");await Us(()=>z.relayerService.submitSpiceDeposit({txHash:Fe,sender:fe,tokenAddress:te.address,chainId:d,amount:xe.toString(),user:fe,isDeposit:!0})),await ke(),_e(),await Rt()},[F,k,fe,ae,f,d,Rt,ke,_e]),ft=o.useCallback(async()=>{if(!F?.asset||!F.amount)throw new Error("Select an asset and enter an amount");if(!ne)throw new Error("Please connect your wallet to continue");if(!I)throw new Error("onLockExecute callback is required for non-7702 mode");const te=Et();if(te.length===0)throw new Error("No lock batches configured");const xe=F.asset,Ge=V.parseUnits(F.amount,xe.decimals),tt=await I({asset:xe,amount:F.amount,amountWei:Ge,lockDurationMonths:qe?.months??0,chainBatches:te});tt&&m?.(tt)},[F,ne,I,Et,qe,m]);o.useEffect(()=>{if(N?.overallStatus==="success"){const te=N.steps.find(xe=>xe.transactionHash);m?.(te?.transactionHash)}},[N?.overallStatus,m]);const Ot=h&&F?.asset?._source==="wallet"&&F?.asset?.chainId===d,Vt=o.useCallback(async()=>{if(!F?.asset||ve<=0){ye("Select an asset and enter an amount");return}if(at){ye("Insufficient balance. Add more assets.");return}if(ce(!0),ye(null),T){try{await ft()}catch(te){ye(jt(te,"Transaction failed. Please try again."))}finally{ce(!1)}return}ue(!0);try{Ot&&!et?await Ht():await Rt()}catch(te){ye(jt(te,"Transaction failed. Please try again."))}finally{ce(!1)}},[F,ve,at,T,ft,Ot,et,Ht,Rt]),Gt=!!F?.asset&&ve>0&&!at&&!le,Mt=e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[e.jsx(nr,{color:U}),e.jsxs("p",{style:{fontSize:"13px",color:U,margin:0,lineHeight:"1.5"},children:["Add ",a," by converting assets from your account"]})]});if(!t)return null;const Jt={backgroundColor:j,border:E,borderRadius:Q,padding:"16px",marginBottom:"16px"};return e.jsx(Ct,{isOpen:t,onClose:s,title:`Add ${a} to your account`,subtitle:Mt,styles:B,dark:S,footerLinkText:"Spicenet accounts \u2192",overlayContent:He?e.jsx("div",{}):void 0,children:e.jsxs("div",{style:{padding:"0 24px 8px 24px",position:"relative"},children:[e.jsxs("div",{style:{marginBottom:"12px"},children:[y&&e.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:e.jsxs("button",{onClick:y,style:{background:"none",border:"none",cursor:"pointer",padding:0,display:"flex",alignItems:"center",gap:"4px",color:A,fontSize:"12px",fontWeight:500,fontFamily:M,textDecoration:"underline",textUnderlineOffset:"2px"},children:["Add Funds",e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:A,strokeWidth:"1.8",children:[e.jsx("circle",{cx:"6",cy:"6",r:"5"}),e.jsx("path",{d:"M6 4v4M4 6h4",strokeLinecap:"round"})]})]})}),e.jsx(as,{assets:Bt,selectedAsset:F??void 0,onAssetSelect:ts,onAmountChange:Ft,label:"Amount",showBalance:!0,showMaxButton:!0,theme:ie,styles:G}),e.jsx("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:U,fontFamily:M},children:Xt})]}),e.jsxs("div",{style:Jt,children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:S?`1px solid ${w.cardBorder}`:"1px solid #e5e7eb"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[i?e.jsx("img",{src:i,alt:a,style:{width:"32px",height:"32px",borderRadius:"50%",objectFit:"cover"}}):e.jsx("div",{style:{width:"32px",height:"32px",borderRadius:"50%",backgroundColor:S?w.inputBg:"#d1d5db",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:700,color:Y},children:a.slice(0,2)}),e.jsx("span",{style:{fontSize:"16px",fontWeight:600,color:Y,fontFamily:M},children:a})]}),e.jsxs("div",{style:{textAlign:"right"},children:[e.jsx("div",{style:{fontSize:"22px",fontWeight:700,color:Y,fontFamily:M,lineHeight:1.1},children:Pt??"0.00"}),e.jsxs("div",{style:{fontSize:"12px",color:U,fontFamily:M,marginTop:"2px"},children:["~$",qt??"0.00"]})]})]}),e.jsxs("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:S?`1px solid ${w.cardBorder}`:"1px solid #e5e7eb"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[e.jsx("span",{style:{fontSize:"15px",fontWeight:500,color:U,fontFamily:M},children:"Lock Duration"}),e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:e.jsx("path",{d:"M4 6L8 10L12 6",stroke:U,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),e.jsx($o,{options:p,selectedIndex:we,onSelect:re,primaryColor:A,dark:S,textPrimary:Y,textSecondary:U})]}),e.jsxs("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[e.jsx(er,{durationMonths:qe?.months,fontFamily:M,dark:S,textPrimary:Y,textSecondary:U}),u&&e.jsx(tr,{votes:Lt,fontFamily:M,dark:S,textPrimary:Y,textSecondary:U})]})]}),Be&&e.jsx("div",{style:{marginBottom:"12px",padding:"10px 14px",backgroundColor:S?"rgba(239,68,68,0.12)":"#fef2f2",border:`1px solid ${S?"rgba(239,68,68,0.3)":"#fecaca"}`,borderRadius:"6px"},children:e.jsx("p",{style:{color:"#ef4444",fontSize:"13px",margin:0,fontFamily:M},children:Be})}),e.jsx(Re.Button,{variant:"outline",fullWidth:!0,onClick:Vt,disabled:!Gt,loading:le,dark:S,styles:{button:{backgroundColor:A}},children:le?Ot&&!et?"DEPOSITING...":et?"LOCKING...":"CONVERTING...":Ot&&!et?`DEPOSIT ${a}`:et?`LOCK ${a}`:`CONVERT TO ${a}`}),e.jsx(sr,{isOpen:He,data:P,isLocking:le,lockError:Be,onContinue:Vt,onClose:()=>De(!1),primaryColor:A,fontFamily:M,dark:S}),N&&Te&&e.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:S?w.shell:"white",borderRadius:Q,padding:"16px 0"},children:e.jsx(ps,{type:"deposit",isOpen:!!N&&N.overallStatus!=="processing",isProcessing:le||N?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{de(),ue(!1),Vt()},onNewTx:()=>{de(),ue(!1),L(null),he.current=null,ke(),_e()},onClose:()=>{de(),ue(!1)},onComplete:()=>{de(),ue(!1),L(null),he.current=null,ke(),_e()},results:N?.overallStatus==="success"||N?.overallStatus==="failed"?N.steps.map(te=>({asset:{symbol:F?.asset?.symbol||a,address:F?.asset?.address||""},txHash:te.transactionHash||"",success:te.status==="success",amount:F?.amount})):void 0,chainName:O.getChainName(d),explorerUrl:O.getExplorerUrl(d,"").replace(/\/tx\/.*$/,"")||void 0,theme:R,styles:B,dark:S})})]})})},Sn=({variant:t,destinationSymbol:s,destinationLogoURI:n,destinationDecimals:a,primaryColor:i,fontFamily:l,textPrimary:r,textSecondary:c,cardBg:d,cardBorder:p,dk:u,dark:x,isQuoting:g,quoteError:f,estimatedOutput:h,paymentAmount:b,needsSwap:m,exactOutputSwap:I,adjustable:W=!1,maxAmount:C,onAmountChange:y})=>t==="supply"?e.jsx("div",{style:{backgroundColor:d,border:`1px solid ${p}`,borderRadius:"12px",padding:"14px 16px",marginBottom:"16px"},children:e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[e.jsx(In,{symbol:s,logoURI:n,primaryColor:i,size:28}),e.jsxs("span",{style:{fontSize:"13px",fontWeight:500,color:c,fontFamily:l},children:["Estimated ",s]})]}),e.jsx("div",{style:{textAlign:"right"},children:g?e.jsx("span",{style:{fontSize:"14px",color:c,fontFamily:l},children:"Quoting..."}):f?e.jsx("span",{style:{fontSize:"13px",color:"#ef4444",fontFamily:l},children:"Quote failed"}):h?e.jsxs("span",{style:{fontSize:"16px",fontWeight:600,color:r,fontFamily:l},children:["\u2248 ",h]}):e.jsx("span",{style:{fontSize:"14px",color:c,fontFamily:l},children:"\u2014"})})]})}):e.jsx(rr,{destinationSymbol:s,destinationLogoURI:n,destinationDecimals:a,primaryColor:i,fontFamily:l,textPrimary:r,textSecondary:c,cardBg:d,cardBorder:p,dk:u,dark:x,paymentAmount:b||"0",needsSwap:m,exactOutputSwap:I,isQuoting:g,adjustable:W,maxAmount:C,onAmountChange:y}),In=({symbol:t,logoURI:s,primaryColor:n,size:a})=>s?e.jsx("img",{src:s,alt:t,style:{width:a,height:a,borderRadius:"50%",objectFit:"cover"}}):e.jsx("div",{style:{width:a,height:a,borderRadius:"50%",backgroundColor:`${n}22`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:a<30?"11px":"12px",fontWeight:700,color:n},children:t.slice(0,2)}),rr=({destinationSymbol:t,destinationLogoURI:s,destinationDecimals:n,primaryColor:a,fontFamily:i,textPrimary:l,textSecondary:r,cardBg:c,cardBorder:d,dk:p,dark:u,paymentAmount:x,needsSwap:g,exactOutputSwap:f,isQuoting:h,adjustable:b,maxAmount:m,onAmountChange:I})=>{const W='"IBM Plex Mono", monospace',C=parseFloat(x||"0"),y=m?parseFloat(m):0,[B,D]=o.useState(x||""),R=o.useRef(null),[S,A]=o.useState(null),[w,M]=o.useState(null);o.useEffect(()=>{b||D(x||"")},[x,b]);const J=E=>{let Q=E;Q.startsWith(".")&&(Q="0"+Q);const Y=$s(Q);let U=Y;m&&parseFloat(Y)>parseFloat(m)&&(U=m),D(U),R.current&&clearTimeout(R.current),R.current=setTimeout(()=>I?.(U),300)},T=E=>{if(!y)return;if(E===100){D(m||y.toString()),R.current&&clearTimeout(R.current),I?.(m||y.toString());return}const Q=10**n,Y=(Math.floor(y*E/100*Q)/Q).toString();D(Y),R.current&&clearTimeout(R.current),I?.(Y)},j=y>0?parseFloat(B||"0")/y*100:0;return o.useEffect(()=>()=>{R.current&&clearTimeout(R.current)},[]),e.jsxs("div",{style:{backgroundColor:c,border:`1px solid ${d}`,borderRadius:u?"12px":"6px",padding:"16px",marginBottom:"16px"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[e.jsx(In,{symbol:t,logoURI:s,primaryColor:a,size:32}),e.jsxs("div",{children:[e.jsx("span",{style:{fontSize:"14px",fontWeight:600,color:l,fontFamily:i},children:"Payment"}),e.jsx("div",{style:{fontSize:"12px",color:r,fontFamily:i,marginTop:"2px"},children:t})]})]}),e.jsxs("div",{style:{textAlign:"right"},children:[b?e.jsx("input",{type:"text",value:B,onChange:E=>J(E.target.value),placeholder:"0.0",style:{fontSize:"20px",fontWeight:700,color:l,fontFamily:W,lineHeight:1.1,backgroundColor:"transparent",border:"none",outline:"none",padding:0,width:"120px",textAlign:"right"}}):e.jsx("div",{style:{fontSize:"20px",fontWeight:700,color:l,fontFamily:W,lineHeight:1.1},children:C>0?x:"0.00"}),e.jsx("div",{style:{fontSize:"12px",color:r,fontFamily:W,marginTop:"2px"},children:t}),b&&y>0&&e.jsx("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((E,Q)=>{const Y=Math.abs(j-E)<1,U=Q===4,G=E/100,ie=S===E,F=w===E;return e.jsx("button",{onClick:()=>T(E),onMouseEnter:()=>A(E),onMouseLeave:()=>{A(null),M(null)},onMouseDown:()=>M(E),onMouseUp:()=>M(null),title:`${E}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:Y?1:ie?.8:.5,transform:F?"scale(0.85)":ie?"scale(1.15)":"scale(1)",transition:"all 0.15s ease"},children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[e.jsx("circle",{cx:"7",cy:"7",r:"6.84375",fill:U?a:"none",stroke:U?a:u?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!U&&G>0&&e.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${G>.5?1:0} 1 ${7+6.84375*Math.sin(G*2*Math.PI)} ${7-6.84375*Math.cos(G*2*Math.PI)} Z`,fill:u?p?.textSecondary||"#9ca3af":"#3C3E42"})]})},E)})})]})]}),g&&f&&!h&&e.jsx("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:u?`1px solid ${p?.cardBorder||d}`:"1px solid #e5e7eb",display:"flex",justifyContent:"flex-end"},children:e.jsxs("span",{style:{fontSize:"11px",color:r,fontFamily:i,opacity:.7},children:["via ",f.venue]})})]})};function jn(t,s,n){const a=t.address.toLowerCase()===s,i=t.chainId===n,l=t._source==="wallet";return l&&a&&i?0:l&&i?1:!l&&a?2:!l&&i?3:4}function ar(t){const{address:s,destinationToken:n,supportedSourceAssets:a,sourceChains:i,enabled:l}=t,r=Ut(),{assets:c,refetch:d}=os({address:s,supportedChains:i,enabled:l,refetchInterval:3e4}),p=o.useMemo(()=>{if(!a||a.length===0)return c;const f=a.map(h=>h.toLowerCase());return c.filter(h=>f.includes(h.address.toLowerCase()))},[c,a]),[u,x]=o.useState(null);o.useEffect(()=>{if(!n.address||!r||!l){x(null);return}let f=!1;const h=V.getAddress(n.address),b=V.getAddress(r),m=O.getClientForChain(n.chainId),I=async()=>{try{const C=await m.multicall({contracts:[{address:h,abi:V.erc20Abi,functionName:"balanceOf",args:[b]},{address:h,abi:V.erc20Abi,functionName:"decimals",args:[]},{address:h,abi:V.erc20Abi,functionName:"symbol",args:[]},{address:h,abi:V.erc20Abi,functionName:"name",args:[]}]});if(f)return;const y=C[0].status==="success"?C[0].result:0n,B=C[1].status==="success"?Number(C[1].result):n.decimals,D=C[2].status==="success"?C[2].result:n.symbol,R=C[3].status==="success"?C[3].result:n.symbol;y>0n?x({address:h,name:R,symbol:D,decimals:B,balance:y,balanceFormatted:parseFloat((Number(y)/Math.pow(10,B)).toFixed(6)),balanceUsd:0,logoURI:n.logoURI,isNative:!1,chainId:n.chainId}):x(null)}catch{f||x(null)}};I();const W=setInterval(I,15e3);return()=>{f=!0,clearInterval(W)}},[n.address,n.chainId,n.decimals,n.symbol,n.logoURI,r,l]);const g=o.useCallback(()=>{if(!n.address||!r)return;const f=O.getClientForChain(n.chainId),h=V.getAddress(n.address),b=V.getAddress(r);f.multicall({contracts:[{address:h,abi:V.erc20Abi,functionName:"balanceOf",args:[b]},{address:h,abi:V.erc20Abi,functionName:"decimals",args:[]}]}).then(m=>{const I=m[0].status==="success"?m[0].result:0n,W=m[1].status==="success"?Number(m[1].result):18;I>0n?x(C=>C?{...C,balance:I,balanceFormatted:parseFloat((Number(I)/Math.pow(10,W)).toFixed(6))}:null):x(null)}).catch(()=>{})},[n.address,n.chainId,r]);return{displayAssets:o.useMemo(()=>{const f=[];u&&f.push({...u,_source:"wallet"});for(const b of p)f.push({...b,_source:"spice"});const h=n.address.toLowerCase();return f.sort((b,m)=>jn(b,h,n.chainId)-jn(m,h,n.chainId)),f},[u,p,n.address,n.chainId]),filteredSpiceAssets:p,embeddedWalletAddress:r,refreshSpiceAssets:d,refreshWalletAssets:g}}function xs(t){const s=new Set(K.getEquivalentAddresses(t).map(n=>n.toLowerCase()));return s.add(t.toLowerCase()),s}const ir=["USDC","USDT","WETH","WBTC"];function Qs(t,s){const n=O.getChainConfig(s);if(!n)return;if(n.nativeCurrency.symbol.toUpperCase()===t.toUpperCase())return{address:K.ZERO_ADDRESS,symbol:n.nativeCurrency.symbol,decimals:n.nativeCurrency.decimals,chainId:s};const a=n.supportedTokens?.find(i=>i.symbol.toUpperCase()===t.toUpperCase());if(a)return{address:a.address.toLowerCase(),symbol:a.symbol,decimals:a.decimals,chainId:s}}function $t(t,s){const n=O.getChainConfig(s);if(!n)return;const a=xs(t);if([...a].some(l=>K.isNativeToken(l)))return{address:K.ZERO_ADDRESS,symbol:n.nativeCurrency.symbol,decimals:n.nativeCurrency.decimals,chainId:s};const i=n.supportedTokens?.find(l=>a.has(l.address.toLowerCase()));if(i)return{address:i.address.toLowerCase(),symbol:i.symbol,decimals:i.decimals,chainId:s}}function En(t){const{sourceAsset:s,outputAsset:n,sourceChainId:a,destinationChainId:i,intermediaryCandidates:l=ir}=t,r=xs(s.address);if(r.has(n.address.toLowerCase()))return{strategy:"direct",sourceAsset:s,outputAsset:n,sourceChainId:a,destinationChainId:i,summary:`${s.symbol} fronted directly`};if($t(s.address,i))return{strategy:"direct",sourceAsset:s,outputAsset:n,sourceChainId:a,destinationChainId:i,summary:`${s.symbol} fronted on destination, swapped to ${n.symbol}`};if($t(n.address,a))return{strategy:"source-swap",sourceAsset:s,outputAsset:n,sourceChainId:a,destinationChainId:i,summary:`${s.symbol} \u2192 ${n.symbol} on source chain, then fronted`};const c=xs(n.address);for(const d of l){const p=Qs(d,a);if(!p||r.has(p.address.toLowerCase())||c.has(p.address.toLowerCase()))continue;const u=Qs(d,i);if(!(!u||!xs(p.address).has(u.address.toLowerCase())))return{strategy:"intermediary",sourceAsset:s,outputAsset:n,intermediaryAsset:u,sourceChainId:a,destinationChainId:i,summary:`${s.symbol} \u2192 ${d} on source, fronted, then ${d} \u2192 ${n.symbol} on destination`}}throw new z.SpiceflowError("ROUTE_STRATEGY_ERROR",`No viable cross-chain route found from ${s.symbol} (chain ${a}) to ${n.symbol} (chain ${i}). No intermediary asset is available on both chains.`,{sourceAsset:s.symbol,outputAsset:n.symbol,sourceChainId:a,destinationChainId:i,candidatesChecked:l})}async function An(t){const{route:s,sourceAmount:n,userAddress:a,registry:i,actionCalls:l,slippage:r}=t;async function c(d,p,u,x){const g=i.getVenueForChain(d);if(!g)throw new z.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${d}. Cannot resolve swap ${p} \u2192 ${u}.`,{chainId:d,tokenIn:p,tokenOut:u,amountIn:x.toString()});const f=await g.resolve({type:"swap",tokenIn:p,tokenOut:u,amountIn:x,maxSlippage:r},d,a);if(!f)throw new z.SpiceflowError("NO_LIQUIDITY",`${g.name} returned no quote for ${p} \u2192 ${u} on chain ${d}. No liquidity available for this pair.`,{venue:g.name,chainId:d,tokenIn:p,tokenOut:u,amountIn:x.toString()});return f}switch(s.strategy){case"direct":{const d=$t(s.sourceAsset.address,s.destinationChainId)||s.sourceAsset;if(xs(d.address).has(s.outputAsset.address.toLowerCase()))return{chainBatches:[{chainId:s.destinationChainId,calls:l}],solverFrontToken:d,solverFrontAmount:n,resolvedSwaps:{}};const p=await c(s.destinationChainId,d.address,s.outputAsset.address,n);return{chainBatches:[{chainId:s.destinationChainId,calls:[...p.calls,...l]}],solverFrontToken:d,solverFrontAmount:n,resolvedSwaps:{destinationSwap:p}}}case"source-swap":{const d=$t(s.outputAsset.address,s.sourceChainId);if(!d)throw new z.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Output asset ${s.outputAsset.symbol} (${s.outputAsset.address}) not found on source chain ${s.sourceChainId}`,{token:s.outputAsset.symbol,address:s.outputAsset.address,chainId:s.sourceChainId,side:"source"});const p=$t(s.outputAsset.address,s.destinationChainId);if(!p)throw new z.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Output asset ${s.outputAsset.symbol} (${s.outputAsset.address}) not found on destination chain ${s.destinationChainId}`,{token:s.outputAsset.symbol,address:s.outputAsset.address,chainId:s.destinationChainId,side:"destination"});const u=await c(s.sourceChainId,s.sourceAsset.address,d.address,n);return{chainBatches:[{chainId:s.sourceChainId,calls:u.calls},{chainId:s.destinationChainId,calls:l}],solverFrontToken:p,solverFrontAmount:u.amountOutMinimum,resolvedSwaps:{sourceSwap:u}}}case"intermediary":{if(!s.intermediaryAsset)throw new z.SpiceflowError("ROUTE_STRATEGY_ERROR","Intermediary strategy requires an intermediary asset but none was provided in the route plan.",{strategy:s.strategy});const d=$t(s.intermediaryAsset.address,s.sourceChainId);if(!d)throw new z.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Intermediary ${s.intermediaryAsset.symbol} (${s.intermediaryAsset.address}) not found on source chain ${s.sourceChainId}`,{token:s.intermediaryAsset.symbol,address:s.intermediaryAsset.address,chainId:s.sourceChainId,side:"source"});const p=await c(s.sourceChainId,s.sourceAsset.address,d.address,n),u=await c(s.destinationChainId,s.intermediaryAsset.address,s.outputAsset.address,p.amountOutMinimum);return{chainBatches:[{chainId:s.sourceChainId,calls:p.calls},{chainId:s.destinationChainId,calls:[...u.calls,...l]}],solverFrontToken:s.intermediaryAsset,solverFrontAmount:p.amountOutMinimum,resolvedSwaps:{sourceSwap:p,destinationSwap:u}}}default:throw new z.SpiceflowError("ROUTE_STRATEGY_ERROR",`Unknown route strategy: ${s.strategy}`,{strategy:s.strategy})}}async function Bn(t){const{tokenIn:s,tokenOut:n,amountIn:a,fee:i,chainId:l,config:r}=t;if(a<=0n)throw new Error("amountIn must be greater than 0");const c=(await O.getClientForChain(l).simulateContract({address:r.quoterV2,abi:K.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:s,tokenOut:n,amountIn:a,fee:i,sqrtPriceLimitX96:0n}]})).result;if(c[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:c[0],sqrtPriceX96After:c[1],gasEstimate:c[3]}}async function Fn(t){const s=t.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(s.map(i=>Bn({...t,fee:i})));let a=null;for(let i=0;i<n.length;i++){const l=n[i];l.status==="fulfilled"&&(!a||l.value.amountOut>a.amountOut)&&(a={...l.value,fee:s[i]})}if(!a)throw new Error("No liquidity found for this pair on any fee tier.");return a}const lr=[{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 dr(t){const{tokenIn:s,tokenOut:n,amountOut:a,fee:i,chainId:l,config:r}=t;if(a<=0n)throw new Error("amountOut must be greater than 0");const c=(await O.getClientForChain(l).simulateContract({address:r.quoterV2,abi:lr,functionName:"quoteExactOutputSingle",args:[{tokenIn:s,tokenOut:n,amount:a,fee:i,sqrtPriceLimitX96:0n}]})).result;if(c[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:c[0],sqrtPriceX96After:c[1],gasEstimate:c[3]}}async function cr(t){const s=t.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(s.map(i=>dr({...t,fee:i})));let a=null;for(let i=0;i<n.length;i++){const l=n[i];l.status==="fulfilled"&&(!a||l.value.amountIn<a.amountIn)&&(a={...l.value,fee:s[i]})}if(!a)throw new Error("No liquidity found for this pair on any fee tier.");return a}function Rn(t){return t.type==="swap"}const Ys=.02,ur=[1,8453,42161,10,137,43114,56],pr="https://api.1inch.dev/swap/v6.0";function Mn(t,s){return K.applySlippage(t,s)}function Tn(t){const s=t?.baseUrl??pr;return{name:"1inch",chainIds:t?.chainIds??ur,resolve:async(n,a,i)=>{const l=n.maxSlippage??Ys,r=l*100,c=K.isNativeToken(n.tokenIn)?K.NATIVE_TOKEN_ADDRESS:n.tokenIn,d=K.isNativeToken(n.tokenOut)?K.NATIVE_TOKEN_ADDRESS:n.tokenOut,p=K.isNativeToken(n.tokenIn);try{const u=new URL(`${s}/${a}/swap`);u.searchParams.set("src",c),u.searchParams.set("dst",d),u.searchParams.set("amount",n.amountIn.toString()),u.searchParams.set("from",i),u.searchParams.set("slippage",r.toString()),u.searchParams.set("disableEstimate","true"),u.searchParams.set("allowPartialFill","false");const x={Accept:"application/json"};t?.apiKey&&(x.Authorization=`Bearer ${t.apiKey}`);const g=await fetch(u.toString(),{headers:x});if(!g.ok)throw new z.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${g.status} for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${a}`,{venue:"1inch",chainId:a,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:`HTTP ${g.status}`});const f=await g.json();if(!f.dstAmount||!f.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${a}`),null;const h=BigInt(f.dstAmount);if(h<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${a}`),null;const b=Mn(h,l),m=[];return f.tx.to&&!p&&m.push({to:n.tokenIn,value:0n,data:V.encodeFunctionData({abi:V.erc20Abi,functionName:"approve",args:[f.tx.to,n.amountIn]})}),m.push({to:f.tx.to,value:BigInt(f.tx.value||"0"),data:f.tx.data}),{venue:"1inch",amountOut:h,amountOutMinimum:b,calls:m}}catch(u){if(u instanceof z.SpiceflowError)throw u;const x=u instanceof Error?u.message:String(u);throw new z.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${a}: ${x}`,{venue:"1inch",chainId:a,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:x})}}}}const Dn=[4114,5115],Ks={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425"},Wn={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453]};function Nn(t){return{name:"satsuma",chainIds:t.chainIds??Dn,resolve:async(s,n,a)=>{const i=s.maxSlippage??Ys,l=K.isNativeToken(s.tokenIn);let r;try{r=await Fn({tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn,chainId:n,config:{swapRouter:t.swapRouter,quoterV2:t.quoterV2},feeTiers:t.feeTiers})}catch{return console.warn(`[SatsumaVenue] No viable fee tier for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${n}.`),null}const c=Mn(r.amountOut,i),d=[];return l||d.push({to:s.tokenIn,value:0n,data:V.encodeFunctionData({abi:V.erc20Abi,functionName:"approve",args:[t.swapRouter,s.amountIn]})}),d.push({to:t.swapRouter,value:l?s.amountIn:0n,data:V.encodeFunctionData({abi:K.uniV3SwapRouterAbi,functionName:"exactInputSingle",args:[{tokenIn:s.tokenIn,tokenOut:s.tokenOut,fee:r.fee,recipient:a,amountIn:s.amountIn,amountOutMinimum:c,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:r.amountOut,amountOutMinimum:c,calls:d}}}}function Un(t){return{name:"satsuma",chainIds:t.chainIds??Dn,resolve:async(s,n,a)=>{const i=s.maxSlippage??Ys,l=K.isNativeToken(s.tokenIn);let r;try{r=await cr({tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountOut:s.amountOut,chainId:n,config:{swapRouter:t.swapRouter,quoterV2:t.quoterV2},feeTiers:t.feeTiers})}catch{return null}const c=BigInt(Math.round(i*1e4)),d=r.amountIn+r.amountIn*c/10000n,p=[];return p.push({to:t.swapRouter,value:l?d:0n,data:V.encodeFunctionData({abi:hr,functionName:"exactOutputSingle",args:[{tokenIn:s.tokenIn,tokenOut:s.tokenOut,fee:r.fee,recipient:a,amountOut:s.amountOut,amountInMaximum:d,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:r.amountIn,amountInMax:d,amountOut:s.amountOut,calls:p}}}}const hr=[{inputs:[{components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"fee",type:"uint24"},{name:"recipient",type:"address"},{name:"amountOut",type:"uint256"},{name:"amountInMaximum",type:"uint256"},{name:"sqrtPriceLimitX96",type:"uint160"}],name:"params",type:"tuple"}],name:"exactOutputSingle",outputs:[{name:"amountIn",type:"uint256"}],stateMutability:"payable",type:"function"}];function zn(t){const s=[];t?.customVenues&&s.push(...t.customVenues),t?.satsuma&&s.push(Nn(t.satsuma)),s.push(Tn(t?.oneInch));function n(i){return s.find(l=>l.chainIds.includes(i))}async function a(i,l,r){const c=[],d=[];for(const p of i){if(!Rn(p)){c.push(p);continue}const u=n(l);if(!u)throw new z.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${l}. Cannot resolve swap ${p.tokenIn} \u2192 ${p.tokenOut}.`,{chainId:l,tokenIn:p.tokenIn,tokenOut:p.tokenOut,amountIn:p.amountIn.toString()});const x=await u.resolve(p,l,r);if(!x)throw new z.SpiceflowError("NO_LIQUIDITY",`${u.name} returned no quote for ${p.tokenIn} \u2192 ${p.tokenOut} on chain ${l}.`,{venue:u.name,chainId:l,tokenIn:p.tokenIn,tokenOut:p.tokenOut,amountIn:p.amountIn.toString()});c.push(...x.calls),d.push(x)}return{calls:c,resolvedSwaps:d}}return{resolveSwapIntents:a,getVenueForChain:n,venues:s}}function xr(t){const s=t?.customVenues??[];async function n(a,i,l){const r=s.filter(d=>d.chainIds.includes(i));if(r.length===0)throw new z.SpiceflowError("NO_SWAP_ROUTE",`No exact-output venue supports chain ${i}`,{chainId:i,tokenIn:a.tokenIn,tokenOut:a.tokenOut});const c=(await Promise.allSettled(r.map(d=>d.resolve(a,i,l)))).filter(d=>d.status==="fulfilled").map(d=>d.value).filter(d=>d!==null);if(c.length===0)throw new z.SpiceflowError("NO_SWAP_ROUTE",`All aggregators failed for ${a.tokenIn} \u2192 ${a.tokenOut} on chain ${i}`,{chainId:i,tokenIn:a.tokenIn,tokenOut:a.tokenOut,amountOut:a.amountOut.toString()});return c.sort((d,p)=>d.amountIn<p.amountIn?-1:d.amountIn>p.amountIn?1:0),c[0]}return{getQuote:n,venues:s}}function fr(t){const{direction:s,selectedAsset:n,destinationToken:a,chainId:i,recipient:l,paymentAmount:r}=t,[c,d]=o.useState(!1),[p,u]=o.useState(null),[x,g]=o.useState(null),[f,h]=o.useState(null),[b,m]=o.useState(null),[I,W]=o.useState(null),[C,y]=o.useState(null),B=o.useRef(null),D=o.useMemo(()=>zn({satsuma:Ks}),[]),R=o.useMemo(()=>xr({customVenues:[Un(Ks),Un(Wn)]}),[]),S=o.useMemo(()=>{if(!n?.asset)return null;if(n.asset.chainId===i)return n.asset.address;const T=$t(n.asset.address,i);return T?T.address:null},[n?.asset?.address,n?.asset?.chainId,i]),A=o.useMemo(()=>n?.asset?n.asset.address.toLowerCase()===a.address.toLowerCase()&&n.asset.chainId===i?!0:K.areEquivalent(n.asset.address,a.address):!1,[n,a.address,i]),w=S?S.toLowerCase()===a.address.toLowerCase():!1,M=s==="output"&&parseFloat(r||"0")===0,J=!!n?.asset&&!A&&!w&&!M;return o.useEffect(()=>{B.current&&clearTimeout(B.current);const T=s==="input"?n?.amount:r,j=parseFloat(T||"0");if(!J||j<=0||!n?.asset||!l||!S){g(null),h(null),m(null),W(null),y(null),u(null),d(!1);return}return d(!0),B.current=setTimeout(async()=>{try{if(s==="input"){const E=V.parseUnits(n.amount,n.asset.decimals),Q=D.getVenueForChain(i);if(!Q)throw new Error("No swap venue for this chain");const Y=await Q.resolve({type:"swap",tokenIn:S,tokenOut:a.address,amountIn:E},i,l);if(!Y)throw new Error("No liquidity for this pair");y(Y.amountOut),m(Y),W(null);const U=V.formatUnits(Y.amountOut,a.decimals),G=parseFloat(U);g(G<.01?G.toPrecision(4):G.toLocaleString(void 0,{maximumFractionDigits:6})),h(null),u(null)}else{const E=V.parseUnits(r||"0",a.decimals),Q=await R.getQuote({tokenIn:S,tokenOut:a.address,amountOut:E},i,l);W(Q),m(null),y(null),h(parseFloat(V.formatUnits(Q.amountIn,n.asset.decimals)).toFixed(6)),g(null),u(null)}}catch(E){const Q=E instanceof Error?E.message:"Failed to get quote";u(Q),g(null),h(null),m(null),W(null),y(null)}finally{d(!1)}},500),()=>{B.current&&clearTimeout(B.current)}},[s,J,n?.amount,n?.asset?.address,n?.asset?.decimals,r,S,i,a.address,a.decimals,l,D,R]),{isQuoting:c,quoteError:p,estimatedOutput:x,estimatedInput:f,resolvedSwap:b,exactOutputSwap:I,quoteAmountOut:C,resolvedTokenIn:S,isDirect:w,needsSwap:J,selectedIsEquivalent:A}}const gr=[0n,1n,30n],mr=new Set(["ABORT","CONCURRENT_EXECUTION","WALLET_DISCONNECTED","WALLET_REJECTED","NO_VENUE_FOR_CHAIN"]);function Pn(t,s){return s===0n?t:t*(1000n-s)/1000n}async function Ln(t,s){const{chainId:n,swapCalls:a,quoteAmountOut:i,buildActionCalls:l,tokenAddress:r,tokenTransferAmount:c,onProgress:d,signal:p,options:u,buffers:x=gr}=s;for(let g=0;g<x.length;g++){const f=x[g],h=Pn(i,f),b=l(h),m=[{chainId:n,calls:[...a,...b]}];try{return await t(m,r,c,d,p,u)}catch(I){if(z.isSpiceflowError(I)&&mr.has(I.code)||I.name==="AbortError"||p?.aborted||I.message?.includes("User rejected")||I.message?.includes("User denied")||I.code===4001||g>=x.length-1)throw I;const W=Number(x[g+1])/10;console.warn(`[SwapThenAction] Action attempt ${g+1} failed (buffer ${Number(f)/10}%), retrying with ${W}% buffer...`,I.message),d?.({step:"signing-delegation",message:`Adjusting action amount, retrying (${W}% buffer)...`})}}throw new z.SpiceflowError("ALL_ATTEMPTS_FAILED","All action attempts failed after exhausting buffer progression.",{attempts:x.length,chainId:n})}const Hn={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Transaction successful!",error:"Transaction failed"},On=["signing-delegation","signing-intent","submitting","executing"],yr=({color:t})=>e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",style:{marginTop:"1px",flexShrink:0},children:[e.jsx("circle",{cx:"7",cy:"7",r:"6.5",stroke:t,strokeWidth:"1.2"}),e.jsx("path",{d:"M7 6v4",stroke:t,strokeWidth:"1.2",strokeLinecap:"round"}),e.jsx("circle",{cx:"7",cy:"4.5",r:"0.7",fill:t})]}),Vn=({isOpen:t,onClose:s,destinationToken:n,buildActionCalls:a,actionLabel:i,amountDirection:l="input",swapDescription:r,directDescription:c,supportedSourceAssets:d,sourceChains:p,paymentAmount:u,amountInputMode:x="fixed",minPaymentAmount:g,maxPaymentAmount:f,onAmountChange:h,styles:b,dark:m,title:I,subtitle:W,onAddFunds:C,onSuccess:y,onError:B})=>{const D=l==="output",{theme:R,dark:S,primaryColor:A,dk:w,palette:M}=z.useSpiceBrand(b,m),J=R.typography.fontFamily,T=b?.inputVariant?b.inputVariant==="dark":S,j=M.textPrimary,E=M.textSecondary,Q=T?w.cardBg:"#f9fafb",Y=T?w.cardBorder:"#e5e7eb",U=b?.button?.backgroundColor??A,G=b?.button?.color??"#0e0d0b",ie=T?{...R,colors:{...R.colors,secondary:w.cardBg,surfaceHover:w.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:R,F=n.chainId,L=zt(),{address:$,isConnected:me,isReady:we,isAuthenticated:re,provider:le}=L,{executeGasless:ce}=js(),{displayAssets:Be,filteredSpiceAssets:ye,embeddedWalletAddress:Te,refreshSpiceAssets:ue,refreshWalletAssets:He}=ar({address:$,destinationToken:n,supportedSourceAssets:d,sourceChains:p,enabled:t&&!!$}),De=D?Be:ye,[P,Ie]=o.useState(null),[Ee,ne]=o.useState(u||""),[We,ze]=o.useState(!1),[Z,ee]=o.useState(null),[v,k]=o.useState("idle"),[se,ae]=o.useState(""),[N,X]=o.useState(null),[de,pe]=o.useState(!1),[ke,ot]=o.useState(null),fe=o.useRef(P),Ce=o.useRef(!1),be=o.useRef(null);o.useEffect(()=>{fe.current=P},[P]);const Ye=x==="adjustable"?Ee:u||"0",ht=Te||$,{isQuoting:ut,quoteError:rt,estimatedOutput:wt,resolvedSwap:xt,exactOutputSwap:_e,quoteAmountOut:vt,resolvedTokenIn:Bt,isDirect:he,needsSwap:ge,selectedIsEquivalent:ve}=fr({direction:l,selectedAsset:P,destinationToken:n,chainId:F,recipient:ht,paymentAmount:Ye}),Ze=D?parseFloat(Ye||"0"):parseFloat(P?.amount||"")||0,at=o.useMemo(()=>P?.asset?ye.find(Se=>Se.address.toLowerCase()===P.asset.address.toLowerCase())?.balanceFormatted??0:0,[P,ye]),qe=o.useMemo(()=>P?.asset?D?ve?Ze>P.asset.balanceFormatted:_e?parseFloat(V.formatUnits(_e.amountInMax,P.asset.decimals))>P.asset.balanceFormatted:!1:Ze>at:!1,[P,D,ve,Ze,_e,at]);o.useEffect(()=>{t||(Ie(null),ee(null),ze(!1),k("idle"),ae(""),X(null),pe(!1),ot(null),Ce.current=!1,x==="adjustable"&&ne(u||""),be.current&&(be.current.abort(),be.current=null))},[t]);const et=o.useCallback(Se=>{Ie(Fe=>({asset:Se,amount:Fe?.asset?.address===Se.address&&Fe?.asset?.chainId===Se.chainId&&Fe.amount||""})),ee(null)},[]),gt=o.useCallback(Se=>{Ie(Fe=>Fe&&{...Fe,amount:Se}),ee(null)},[]),Pt=o.useCallback(Se=>{let Fe=Se;f&&parseFloat(Fe)>parseFloat(f)&&(Fe=f),ne(Fe),h?.(Fe),ee(null)},[f,h]),Lt=o.useCallback(Se=>{k({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[Se.step]||"executing"),ae(Se.message),Se.txHash&&X(Se.txHash)},[]),Xt=o.useCallback(()=>{const Se=V.parseUnits(Ye,n.decimals),Fe={userAddress:Te,chainId:F,destinationToken:n.address},Me=a(Se,Fe),je={chainId:F,calls:Me},st=P?.asset?._source==="spice",Ve=(Ke,Ae)=>({token:Ke,from:"solver",to:Te,amount:Ae});if(Se===0n)return[je];if(ge&&_e){let Ke=P.asset.address;if(P.asset.chainId!==F){const Xe=K.getTokenDefinition(P.asset.address)?.deployments.find(kt=>kt.chainId===F);Xe&&(Ke=Xe.address)}const Ae=st?[Ve(Ke,_e.amountInMax)]:[],Le={to:Ke,value:0n,data:V.encodeFunctionData({abi:V.erc20Abi,functionName:"approve",args:[_e.calls[0]?.to,_e.amountInMax]})};return[{chainId:F,calls:[Le,..._e.calls,...Me],tokenTransfers:[...Ae,...je.tokenTransfers??[]]}]}if(st){let Ke=n.address;if(P.asset.chainId!==F){const Ae=K.getTokenDefinition(P.asset.address)?.deployments.find(Le=>Le.chainId===F);Ae&&(Ke=Ae.address)}return[{...je,tokenTransfers:[Ve(Ke,Se),...je.tokenTransfers??[]]}]}return[je]},[Ye,n,Te,F,a,P,ge,_e]),qt=o.useCallback(async()=>{if(!P?.asset||Ze<=0){ee("Select an asset and enter an amount");return}if(qe){ee("Insufficient balance");return}if(!Te){ee("Wallet not ready");return}ze(!0),ee(null),k("signing-delegation"),ae("Building transaction..."),X(null),Ce.current=!1;const Se=new AbortController;be.current=Se;try{const Fe={userAddress:Te,chainId:F,destinationToken:n.address};if(he){const Me=V.parseUnits(P.amount,P.asset.decimals),je=a(Me,Fe);await ce([{chainId:F,calls:je}],Bt??P.asset.address,Me,Lt,Se.signal)}else{if(!xt||!vt)throw new Error("Please wait for the swap quote");const Me=V.parseUnits(P.amount,P.asset.decimals);await Ln(ce,{chainId:F,swapCalls:xt.calls,quoteAmountOut:vt,buildActionCalls:je=>a(je,Fe),tokenAddress:Bt,tokenTransferAmount:Me,onProgress:Lt,signal:Se.signal})}k("success"),ae("Transaction successful!")}catch(Fe){const Me=Fe instanceof Error?Fe:new Error(String(Fe));if(Me.name==="AbortError"||Se.signal.aborted){k("idle");return}const je=Me.message||"Transaction failed";k("error"),ae(je),ee(je),B?.(Me)}finally{ze(!1)}},[P,Ze,qe,Te,he,F,xt,vt,Bt,a,ce,Lt,B]),ts=o.useCallback(async()=>{if(Ze<0){ee("Enter a valid payment amount");return}if(!P?.asset){ee("Select a payment source");return}if(qe){ee("Insufficient balance");return}if(ge&&!_e){ee("Swap quote not available. Try a different asset.");return}if(!me||!$){ee("Please connect your wallet to continue");return}if(!we||!re){ee(`Please authenticate with ${le||"wallet provider"} to continue`);return}ze(!0),ee(null),pe(!0),ot({status:"processing"});try{const Se=Xt(),Fe=Se.some(Ve=>Ve.tokenTransfers?.length),Me=V.parseUnits(Ye,n.decimals),je=P?.asset?.address||n.address,st=await ce(Se,je,Me,Ve=>{Ve.txHash&&(ot(Ke=>({...Ke,txHash:Ve.txHash})),X(Ve.txHash))},void 0,Fe?{useCustomTransfers:!0}:void 0);ot(Ve=>({status:"success",txHash:Ve?.txHash||st}))}catch(Se){const Fe=jt(Se,"Payment failed. Please try again.");ee(Fe),ot({status:"failed",error:Fe}),B?.(Se instanceof Error?Se:new Error(Fe))}finally{ze(!1)}},[Ze,P,qe,ge,_e,me,$,we,re,le,Xt,Ye,n,ce,B]);o.useEffect(()=>{!D&&v==="success"&&N&&(ue(),y?.(N))},[D,v,N,ue,y]),o.useEffect(()=>{if(!D||ke?.status!=="success"||Ce.current||!$)return;Ce.current=!0;const Se=fe.current;!Se?.asset||Se.asset?._source==="wallet"||ue()},[D,ke?.status,$,ue]);const Ft=o.useRef(y),Et=o.useRef(B);o.useEffect(()=>{Ft.current=y},[y]),o.useEffect(()=>{Et.current=B},[B]),o.useEffect(()=>{D&&(ke?.status==="success"&&Ft.current?.(ke.txHash||""),ke?.status==="failed"&&Et.current?.(new Error("Payment execution failed")))},[D,ke?.status]);const Rt=o.useCallback(()=>{pe(!1),ot(null),Ie(null),Ce.current=!1,ue(),He()},[ue,He]),Ht=D?!!P?.asset&&Ze>=0&&!qe&&!We&&(!ge||!!_e):!!P?.asset&&Ze>0&&!qe&&!We&&(he||!!xt&&!ut),ft=he?c||`Your ${n.symbol} will be used directly.`:r||"Your assets will be swapped and used in a single atomic transaction.",Ot=S?w.shell:"white",Vt=S?w.buttonBorder:"#0e0d0b",Gt=(F?O.getChainConfig(F):void 0)?.viemChain?.blockExplorers?.default?.url??"",Mt=On.indexOf(v),Jt=We?(Hn[v]||"EXECUTING...").toUpperCase():v==="success"?"DONE":qe?"INSUFFICIENT BALANCE":i.toUpperCase(),te=o.useMemo(()=>{if(We)return"PAYING...";if(qe&&P?.asset)return`INSUFFICIENT ${P.asset.symbol}`;const Se=Ze>0?` ${Ye} ${n.symbol}`:"";return ge?`SWAP & PAY${Se}`:`PAY${Se}`},[We,qe,P,Ze,Ye,n.symbol,ge]),xe=v==="success"?()=>{k("idle"),Ie(null),X(null),ue()}:qt,Ge=v==="success"?!1:!Ht;if(!t)return null;const tt=D?I||`Pay ${n.symbol}`:i,lt=D?W:e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[e.jsx(yr,{color:E}),e.jsx("p",{style:{fontSize:"13px",color:E,margin:0,lineHeight:"1.5"},children:ft})]});if(D){const Se=ke&&(ke.status==="success"||ke.status==="failed")?[{asset:{symbol:P?.asset?.symbol||n.symbol,address:P?.asset?.address||""},amount:Ye,txHash:ke.txHash||"",success:ke.status==="success",error:ke.status==="failed"?ke.error:void 0}]:void 0;return e.jsx(Ct,{isOpen:t,onClose:s,title:tt,subtitle:lt,styles:b,dark:S,footerLinkText:"Spicenet accounts \u2192",children:e.jsxs("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[C&&e.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:e.jsxs("button",{onClick:C,style:{background:"none",border:"none",cursor:"pointer",padding:0,display:"flex",alignItems:"center",gap:"4px",color:A,fontSize:"12px",fontWeight:500,fontFamily:J,textDecoration:"underline",textUnderlineOffset:"2px"},children:["Add Funds",e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:A,strokeWidth:"1.8",children:[e.jsx("circle",{cx:"6",cy:"6",r:"5"}),e.jsx("path",{d:"M6 4v4M4 6h4",strokeLinecap:"round"})]})]})}),e.jsx("div",{style:{marginBottom:"12px"},children:e.jsx(as,{assets:De,selectedAsset:P??void 0,onAssetSelect:et,onAmountChange:()=>{},label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:P?.asset?ge?ut?"...":_e?`~${parseFloat(V.formatUnits(_e.amountIn,P.asset.decimals)).toFixed(6)}`:void 0:Ye??void 0:void 0,dark:S,theme:ie,styles:b})}),e.jsx(Sn,{variant:"pay",destinationSymbol:n.symbol,destinationLogoURI:n.logoURI,destinationDecimals:n.decimals,primaryColor:A,fontFamily:J,textPrimary:j,textSecondary:E,cardBg:Q,cardBorder:Y,dk:w,dark:S,isQuoting:ut,quoteError:rt,estimatedOutput:wt,paymentAmount:Ye,needsSwap:ge,exactOutputSwap:_e,adjustable:x==="adjustable",maxAmount:f,onAmountChange:Pt}),Z&&e.jsx("div",{style:{marginBottom:"12px",padding:"10px 14px",backgroundColor:M.errorBg,border:`1px solid ${M.errorBorder}`,borderRadius:"6px"},children:e.jsx("p",{style:{color:M.errorText,fontSize:"13px",margin:0,fontFamily:J},children:Z})}),e.jsx(Re.Button,{variant:"outline",fullWidth:!0,onClick:ts,disabled:!Ht,loading:We,dark:S,styles:{button:{backgroundColor:A}},children:te}),ke&&de&&e.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:S?w.shell:"white",borderRadius:S?"12px":"6px",padding:"16px 0"},children:e.jsx(ps,{type:"payment",isOpen:ke.status!=="processing",isProcessing:We||ke.status==="processing",closeOnComplete:!1,chainName:O.getChainName(F),explorerUrl:O.getExplorerUrl(F,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{pe(!1),ot(null),ts()},onNewTx:Rt,onClose:()=>{pe(!1),ot(null)},onComplete:Rt,results:Se,styles:b,dark:S})})]})})}return e.jsxs(Ct,{isOpen:t,onClose:s,title:tt,subtitle:lt,dark:S,styles:b,theme:R,children:[e.jsx("div",{style:{marginBottom:"16px"},children:e.jsx(as,{assets:De,selectedAsset:P||void 0,onAssetSelect:et,onAmountChange:gt,disabled:We||v==="success",showBalance:!0,showMaxButton:!0,label:"From Spice Balance",placeholder:"0.00",theme:ie,styles:b,dark:T,maxAmount:at>0?at.toString():void 0})}),P?.asset&&!he&&e.jsx(Sn,{variant:"supply",destinationSymbol:n.symbol,destinationLogoURI:n.logoURI,destinationDecimals:n.decimals,primaryColor:A,fontFamily:J,textPrimary:j,textSecondary:E,cardBg:Q,cardBorder:Y,dark:S,isQuoting:ut,quoteError:rt,estimatedOutput:wt}),v!=="idle"&&e.jsxs("div",{style:{padding:"10px 14px",borderRadius:"10px",marginBottom:"16px",backgroundColor:v==="success"?M.successBg:v==="error"?M.errorBg:Q,border:`1px solid ${v==="success"?M.successBorder:v==="error"?M.errorBorder:Y}`},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[v==="success"?e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:e.jsx("path",{d:"M5 13l4 4L19 7",stroke:M.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):v==="error"?e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:e.jsx("path",{d:"M18 6L6 18M6 6l12 12",stroke:M.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):e.jsx(Re.Spinner,{size:14,color:A}),e.jsx("span",{style:{fontSize:"13px",fontWeight:500,color:v==="success"?M.successText:v==="error"?M.errorText:j,fontFamily:J,flex:1},children:v==="success"?"Transaction successful!":v==="error"?se||"Transaction failed":Hn[v]||se}),v==="success"&&N&&e.jsx("a",{href:`${Gt}/tx/${N}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:A,fontFamily:J,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),v==="error"&&e.jsx("button",{onClick:()=>{k("idle"),ee(null),setTimeout(qt,50)},style:{background:"none",border:"none",fontSize:"12px",color:A,fontFamily:J,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),Mt>=0&&v!=="success"&&v!=="error"&&e.jsx("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${E}22`,overflow:"hidden"},children:e.jsx("div",{style:{height:"100%",borderRadius:"2px",backgroundColor:A,width:`${(Mt+1)/On.length*100}%`,transition:"width 400ms ease"}})})]}),Z&&v==="idle"&&e.jsx("div",{style:{padding:"10px 14px",borderRadius:"10px",backgroundColor:M.errorBg,border:`1px solid ${M.errorBorder}`,marginBottom:"16px"},children:e.jsx("p",{style:{fontSize:"13px",color:M.errorText,margin:0,fontFamily:J},children:Z})}),e.jsx(Re.Button,{variant:"outline",fullWidth:!0,disabled:Ge,onClick:xe,style:{height:"56px",backgroundColor:Ge?`${U}66`:v==="success"?M.successBg:U,color:v==="success"?M.successText:G,border:`1px solid ${v==="success"?M.successBorder:Vt}`,fontSize:"14px",fontWeight:700,letterSpacing:"2px",fontFamily:'"IBM Plex Mono", monospace',boxShadow:Ge?"none":`3px 3px 0px ${Ot}, 4px 4px 0px ${Vt}`,cursor:Ge?"not-allowed":"pointer",opacity:Ge?.6:1},children:Jt})]})},Cr=t=>e.jsx(Vn,{isOpen:t.isOpen,onClose:t.onClose,amountDirection:"output",destinationToken:{address:t.paymentTokenAddress,symbol:t.paymentTokenSymbol,decimals:t.paymentTokenDecimals,chainId:t.paymentChainId,logoURI:t.paymentTokenLogoURI},buildActionCalls:t.buildActionCalls,actionLabel:t.ctaLabel||"PAY",paymentAmount:t.paymentAmount,amountInputMode:t.amountInputMode,minPaymentAmount:t.minPaymentAmount,maxPaymentAmount:t.maxPaymentAmount,onAmountChange:t.onAmountChange,sourceChains:t.sourceChains,title:t.title,subtitle:t.subtitle,onAddFunds:t.onAddFunds,styles:t.styles,dark:t.dark,onSuccess:t.onPaymentSuccess,onError:t.onPaymentError}),br=({label:t="Export Wallet",style:s,className:n,onExport:a,onError:i})=>{const[l,r]=o.useState(!1),[c,d]=o.useState(!1),{primaryColor:p}=z.useSpiceBrand(),u=o.useContext(z.SpiceFlowProviderContext),{isAuthenticated:x}=zt();let g=null;try{g=Zt.usePrivy()}catch{}let f=null,h=null;try{f=ds.useEmbeddedReveal(),h=ds.useDynamicContext()}catch{f=null,h=null}const b=Tt.getDynamicEmbeddedWallet(h),m=o.useCallback(async()=>{if(!x){i?.("User is not authenticated. Please log in first.");return}try{if(u?.provider==="dynamic"){if(!f||!b){i?.("Dynamic is not available. Ensure the app is wrapped in a DynamicContextProvider.");return}await f.initExportProcess(!1),a?.();return}if(!g){i?.("Privy is not available. Ensure the app is wrapped in a PrivyProvider.");return}await g.exportWallet(),a?.()}catch(C){const y=C instanceof Error?C.message:"Failed to export wallet";console.error("Export wallet error:",C),i?.(y)}},[b,f,x,i,a,g,u?.provider]),I=!x,W={padding:"10px 20px",borderRadius:"8px",fontFamily:'"IBM Plex Mono", monospace',fontSize:"14px",fontWeight:500,letterSpacing:"0.4px",textTransform:"uppercase",cursor:I?"not-allowed":"pointer",opacity:I?.5:1,border:"1px solid #0e0d0b",color:"#0e0d0b",backgroundColor:c?`${p}cc`:l?`${p}ee`:p,transition:"all 150ms ease",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"8px",...s};return e.jsxs("button",{onClick:m,onMouseEnter:()=>r(!0),onMouseLeave:()=>{r(!1),d(!1)},onMouseDown:()=>d(!0),onMouseUp:()=>d(!1),disabled:I,className:n,style:W,children:[e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),e.jsx("polyline",{points:"17 8 12 3 7 8"}),e.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]}),t]})};function Qn(t){const s=o.useContext(z.SpiceFlowProviderContext),n=Ut(),a=t?.enabled===!1?void 0:n,i=s?.network?{network:s.network,pollIntervalMs:t?.pollIntervalMs,chainIds:t?.chainIds??s.supportedChainIds}:void 0;return{...mn(a,i),embeddedWalletAddress:n}}const wr=({appName:t,status:s,statusLabel:n,totalUsdValue:a,breakdownSubtitle:i,address:l,dk:r,dark:c=!1,showModeToggle:d,isEmbeddedMode:p=!0,onModeToggle:u})=>{const[x,g]=o.useState(!1),f=async()=>{l&&await io(l)&&(g(!0),setTimeout(()=>g(!1),2e3))},h=s==="active",b=n||(h?"Active":"Inactive"),m=h?"#10b981":"#9ca3af";return e.jsxs("div",{children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[e.jsxs("div",{style:{fontSize:"13px",fontWeight:600,color:c?r.textPrimary:"#111827"},children:[t," Account"]}),d?e.jsxs("button",{onClick:u,style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:c?r.hoverBg:"#f3f4f6",border:c?`1px solid ${r.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"11px",fontWeight:600,fontFamily:'"IBM Plex Mono", monospace',color:c?r.textSecondary:"#6b7280",transition:"all 150ms ease",letterSpacing:"0.02em"},children:[e.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:p?"#22c55e":"#f59e0b"}}),e.jsx("span",{children:p?"Embedded":"External"})]}):e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:c?r.hoverBg:h?"#ecfdf5":"#f3f4f6",border:c?`1px solid ${r.cardBorder}`:h?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[e.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:m}}),e.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:c?r.textSecondary:h?"#065f46":"#6b7280"},children:b})]})]}),e.jsx("div",{style:{fontSize:"28px",fontWeight:700,color:c?r.textPrimary:"#111827",lineHeight:1.2,marginBottom:"2px"},children:rs(a)}),i&&e.jsx("div",{style:{fontSize:"12px",color:c?r.textSecondary:"#6b7280",marginBottom:"8px"},children:i}),l&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[e.jsx("span",{style:{fontSize:"12px",fontFamily:'"IBM Plex Mono", monospace',color:c?r.textSecondary:"#9ca3af"},children:ao(l)}),e.jsx("button",{onClick:f,style:{padding:"2px 6px",fontSize:"10px",fontWeight:500,backgroundColor:"transparent",color:c?r.textSecondary:"#9ca3af",border:"none",cursor:"pointer",borderRadius:"4px",transition:"all 150ms ease"},title:"Copy address",children:x?"Copied":"Copy"})]})]})},vr=({pendingDeposits:t,onCompleteDeposit:s,dk:n,dark:a=!1})=>t.length===0?null:e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:a?n.textSecondary:"#6b7280",marginBottom:"8px",textTransform:"uppercase"},children:"Pending Deposits"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:t.map((i,l)=>{const r=O.getChainConfig(i.chainId)?.displayName||`Chain ${i.chainId}`;return e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:a?n.warningBg:"#fffbeb",border:a?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"8px"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:a?n.hoverBg:"#fde68a",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:a?n.warningText:"#92400e"},children:i.tokenSymbol.charAt(0)}),e.jsxs("div",{children:[e.jsxs("div",{style:{fontSize:"13px",fontWeight:500,color:a?n.textPrimary:"#111827"},children:[i.amount," ",i.tokenSymbol]}),e.jsxs("div",{style:{fontSize:"11px",color:a?n.warningText:"#92400e"},children:["on ",r]})]})]}),e.jsx("button",{onClick:()=>s?.(i),style:{padding:"4px 12px",fontSize:"11px",fontWeight:600,backgroundColor:a?n.hoverBg:"#fef3c7",color:a?n.textPrimary:"#92400e",border:a?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"9999px",cursor:"pointer",transition:"all 150ms ease"},children:"Complete"})]},`${i.tokenAddress}-${i.chainId}-${l}`)})})]}),kr=({spiceAssets:t,loading:s,dk:n,dark:a=!1})=>{const i={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:a?n.textSecondary:"#6b7280",marginBottom:"8px",textTransform:"uppercase"},l={backgroundColor:a?n.cardBg:"#f9fafb",border:a?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return s?e.jsxs("div",{children:[e.jsx("div",{style:i,children:"Idle Balances"}),[1,2].map(r=>e.jsx("div",{style:{...l,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},r))]}):t.length===0?e.jsxs("div",{children:[e.jsx("div",{style:i,children:"Idle Balances"}),e.jsx("div",{style:{...l,padding:"16px",textAlign:"center",fontSize:"13px",color:a?n.textSecondary:"#9ca3af"},children:"No assets yet. Deposit to get started."})]}):e.jsxs("div",{children:[e.jsx("div",{style:i,children:"Idle Balances"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:t.map((r,c)=>{const d=O.getChainConfig(r.chainId)?.displayName||`Chain ${r.chainId}`;return e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...l},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[r.logoURI?e.jsx("img",{src:r.logoURI,alt:r.tokenSymbol,style:{width:"24px",height:"24px",borderRadius:"50%"}}):e.jsx("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:a?n.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:a?n.textSecondary:"#6b7280"},children:r.tokenSymbol.charAt(0)}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:a?n.textPrimary:"#111827"},children:r.tokenSymbol}),e.jsx("div",{style:{fontSize:"11px",color:a?n.textSecondary:"#9ca3af"},children:d})]})]}),e.jsxs("div",{style:{textAlign:"right"},children:[e.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:a?n.textPrimary:"#111827"},children:ks(r.balanceFormatted)}),e.jsx("div",{style:{fontSize:"11px",color:a?n.textSecondary:"#9ca3af"},children:rs(r.usdValue)})]})]},`${r.tokenAddress}-${r.chainId}-${c}`)})})]})},Sr=({section:t,dk:s,dark:n=!1})=>{const a=i=>{switch(i){case"green":return"#10b981";case"red":return"#ef4444";default:return n?s.textPrimary:"#111827"}};return e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n?s.textSecondary:"#6b7280",marginBottom:"8px",textTransform:"uppercase"},children:t.title}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:t.items.map((i,l)=>e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:n?s.cardBg:"#f9fafb",border:n?`1px solid ${s.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[i.tokenLogoURI?e.jsx("img",{src:i.tokenLogoURI,alt:i.tokenSymbol,style:{width:"20px",height:"20px",borderRadius:"50%"}}):e.jsx("div",{style:{width:"20px",height:"20px",borderRadius:"50%",backgroundColor:n?s.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",fontWeight:600,color:n?s.textSecondary:"#6b7280"},children:i.tokenSymbol.charAt(0)}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:n?s.textPrimary:"#111827"},children:i.tokenSymbol}),e.jsx("div",{style:{fontSize:"11px",color:n?s.textSecondary:"#6b7280"},children:i.label})]})]}),e.jsx("div",{style:{fontSize:"13px",fontWeight:600,color:a(i.valueColor)},children:i.displayValue})]},l))})]})},Ir=({onDepositClick:t,onWithdrawClick:s,depositDisabled:n=!1,withdrawDisabled:a=!1,primaryColor:i="#EA4B4B",dark:l=!1})=>e.jsxs("div",{style:{display:"flex",gap:"8px"},children:[e.jsx(Re.Button,{variant:"outline",onClick:t,disabled:n,dark:l,styles:{button:{backgroundColor:i}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),e.jsx(Re.Button,{variant:"outline",onClick:s,disabled:a,dark:l,styles:{button:{backgroundColor:i}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),jr=({appName:t,status:s,statusLabel:n,totalUsdValue:a,breakdownSubtitle:i,address:l,spiceAssets:r,spiceAssetsLoading:c,pendingDeposits:d,customSections:p,onDepositClick:u,onWithdrawClick:x,onCompleteDeposit:g,primaryColor:f,dk:h,dark:b=!1,showModeToggle:m,isEmbeddedMode:I,onModeToggle:W})=>{const[C,y]=o.useState(!1);return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[e.jsx(wr,{appName:t,status:s,statusLabel:n,totalUsdValue:a,breakdownSubtitle:i,address:l,dk:h,dark:b,showModeToggle:m,isEmbeddedMode:I,onModeToggle:W}),e.jsx("div",{style:{height:"1px",backgroundColor:b?"#2d2d2d":"#e5e7eb"}}),e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>y(!C),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:b?h.cardBg:"#f9fafb",border:b?`1px solid ${h.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:b?h.textSecondary:"#6b7280",fontSize:"12px",fontWeight:500},children:[e.jsx("span",{children:"How It Works"}),e.jsx("span",{style:{transform:C?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),C&&e.jsxs("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:b?h.cardBg:"#f0fdf4",border:b?`1px solid ${h.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:b?h.textSecondary:"#374151"},children:["Fund your ",t," Account from any supported chain (10+ EVM chains). Once funded, transact gas-free and asset-abstracted on"," ",t,"."]})]}),e.jsx(vr,{pendingDeposits:d,onCompleteDeposit:g,dk:h,dark:b}),e.jsx(kr,{spiceAssets:r,loading:c,dk:h,dark:b}),p.map((B,D)=>e.jsx(Sr,{section:B,dk:h,dark:b},D)),e.jsx(Ir,{onDepositClick:u,onWithdrawClick:x,primaryColor:f,dark:b})]})},Zs=380,is=8,Er=({appName:t="Spice",status:s="active",statusLabel:n,customSections:a=[],extraAssets:i=[],tokenPrices:l={},breakdownLabels:r=[],supportedChains:c,styles:d,dark:p=!1,onDepositSuccess:u,onDepositClick:x,onWithdrawClick:g,onCompleteDeposit:f,showModeToggle:h=!1,defaultMode:b})=>{const m=o.useContext(z.SpiceFlowProviderContext),I=m?.mode!=="7702";o.useEffect(()=>{b&&m?.setMode&&m.setMode(b==="non7702"?"ondemand":"7702")},[]);const[W,C]=o.useState(!1),[y,B]=o.useState(null),[D,R]=o.useState({top:0,left:0,placement:"below"}),S=o.useRef(null),A=o.useRef(null),{address:w,isConnected:M}=zt(),J=Ut(),{address:T}=Qe.useAccount(),{dark:j,primaryColor:E,dk:Q}=z.useSpiceBrand(d,p),Y=o.useMemo(()=>c||K.getChainIdsByNetwork("mainnet"),[c]),{assets:U,loading:G}=os({address:w,supportedChains:Y,enabled:!!w&&!I,refetchInterval:3e4}),ie=o.useMemo(()=>[...I?[]:U.map(P=>{const Ie=P.balanceUsd||0,Ee=Number(P.balance)/Math.pow(10,P.decimals),ne=Ie>0?Ie:(l[P.symbol]||0)*Ee;return{tokenAddress:P.address,tokenSymbol:P.symbol,tokenDecimals:P.decimals,chainId:P.chainId,balance:P.balance.toString(),balanceFormatted:P.balanceFormatted,usdValue:ne,logoURI:P.logoURI}}),...i].filter(P=>P.balanceFormatted>0),[I,U,l,i]),F=o.useMemo(()=>ie.reduce((P,Ie)=>P+Ie.usdValue,0),[ie]),{pendingDeposits:L}=Qn({chainIds:Y,enabled:!!w}),$=o.useMemo(()=>a.reduce((P,Ie)=>P+Ie.totalValue,0),[a]),me=F+$,we=o.useMemo(()=>{const P=[];F>0&&P.push(`${rs(F)} idle`);for(const Ie of a){const Ee=r.find(ne=>ne.sectionTitle===Ie.title)?.label||Ie.title.toLowerCase();P.push(`${rs(Ie.totalValue)} ${Ee}`)}return P.join(" \xB7 ")},[F,a,r]),re=o.useCallback(P=>{f?f(P):B(P)},[f]),le=o.useCallback(()=>{B(null)},[]),ce=o.useCallback(()=>{B(null),u?.()},[u]),Be=o.useCallback(()=>{if(!S.current)return;const P=S.current.getBoundingClientRect(),Ie=window.innerHeight-P.bottom-is,Ee=P.top-is,ne=Ie>=400||Ie>=Ee?"below":"above",We=Math.max(is,Math.min(P.right-Zs,window.innerWidth-Zs-is)),ze=ne==="below"?P.bottom+is:P.top-is;R({top:ze,left:We,placement:ne})},[]);o.useLayoutEffect(()=>{W&&Be()},[W,Be]),o.useEffect(()=>{if(!W)return;const P=ne=>{S.current&&!S.current.contains(ne.target)&&A.current&&!A.current.contains(ne.target)&&C(!1)},Ie=ne=>{ne.key==="Escape"&&C(!1)},Ee=()=>Be();return document.addEventListener("mousedown",P),document.addEventListener("keydown",Ie),window.addEventListener("scroll",Ee,{passive:!0}),window.addEventListener("resize",Be),()=>{document.removeEventListener("mousedown",P),document.removeEventListener("keydown",Ie),window.removeEventListener("scroll",Ee),window.removeEventListener("resize",Be)}},[W,Be]);const ye=m?.mode==="7702",Te=ye?J||w:T||w,ue=o.useCallback(()=>{m?.setMode&&m.setMode(ye?"ondemand":"7702")},[m,ye]);if(typeof window>"u")return null;const He=e.jsxs("button",{ref:S,onClick:()=>C(!W),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:j?Q.hoverBg:"#ffffff",border:j?`1px solid ${Q.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:'"Helvetica Neue", sans-serif',color:j?Q.textPrimary:"#111827",transition:"all 150ms ease",boxShadow:j?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[e.jsx("span",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:E,flexShrink:0}}),e.jsxs("span",{children:[t," Account"]}),M&&e.jsxs("span",{style:{color:j?Q.textSecondary:"#6b7280"},children:["\xB7 ",rs(me)]}),e.jsx("span",{style:{fontSize:"10px",color:j?Q.textSecondary:"#9ca3af",transform:W?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),De=W?Bs.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:9998},onClick:()=>C(!1)}),e.jsx("div",{ref:A,style:{position:"fixed",top:D.placement==="below"?`${D.top}px`:"auto",bottom:D.placement==="above"?`${window.innerHeight-D.top}px`:"auto",left:`${D.left}px`,width:`${Zs}px`,maxHeight:"80vh",backgroundColor:j?Q.shell:"#ffffff",border:j?`1px solid ${Q.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:9999,overflow:"hidden",animation:"accountDisplayFadeIn 150ms ease-out"},children:e.jsx(jr,{appName:t,status:s,statusLabel:n,totalUsdValue:me,breakdownSubtitle:we,address:h?Te:w,spiceAssets:ie,spiceAssetsLoading:G,pendingDeposits:L,customSections:a,onDepositClick:x,onWithdrawClick:g,onCompleteDeposit:re,primaryColor:E,dk:Q,dark:j,showModeToggle:h,isEmbeddedMode:ye,onModeToggle:ue})}),e.jsx("style",{children:`
115
115
  @keyframes accountDisplayFadeIn {
116
116
  from { opacity: 0; transform: translateY(-4px); }
117
117
  to { opacity: 1; transform: translateY(0); }