@spicenet-io/spiceflow-ui 3.0.0 → 3.0.1
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 +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -111,7 +111,7 @@
|
|
|
111
111
|
from { transform: rotate(0deg); }
|
|
112
112
|
to { transform: rotate(360deg); }
|
|
113
113
|
}
|
|
114
|
-
`})]})},Sr=({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})]}),Ir=({isOpen:t,onClose:n,lockBatches:s,lockTokenSymbol:a,lockTokenLogoURI:i,destinationInputHook:l,sourceAssetInputHook:r,lockDurationHook:c,lockChainId:d,durationOptions:h,votingPowerEstimate:u,sourceChains:x,sourceAssets:y=[],escrowAddress:p,includeWalletAssets:f=!1,destinationTokenAddress:w,onLockSuccess:g,onLockExecute:S,sourceToDestinationConversionRate:D,estimatedOutputAmount:b,onAddFunds:m,styles:B,dark:U=!1})=>{const{theme:I,dark:v,primaryColor:z,dk:C}=V.useSpiceBrand(B,U),k=I.typography.fontFamily,P=o.useContext(V.SpiceFlowProviderContext),T=(P?.mode||"7702")!=="7702",F=v?C.cardBg:B?.assetSelector?.backgroundColor||B?.secondaryBackground||"#e9e9e9",M=v?`1px solid ${C.cardBorder}`:"0.5px solid #A8A8A7",ee=v?"12px":"6px",$=v?C.textPrimary:"#111827",L=v?C.textSecondary:"#6b7280",Z=o.useMemo(()=>({...B,assetSelector:{...B?.assetSelector,backgroundColor:v?C.cardBg:B?.assetSelector?.backgroundColor,borderRadius:v?"12px":B?.assetSelector?.borderRadius},secondaryBackground:v?C.cardBg:B?.secondaryBackground}),[B,v]),te=o.useMemo(()=>v?{...I,colors:{...I.colors,secondary:C.cardBg,surfaceHover:C.hoverBg,border:C.cardBorder,borderHover:C.inputBorder}}:I,[v,I]),[O,R]=o.useState(null),[ae,ye]=o.useState(0),ke=c?.selectedDurationIdx??ae,he=c?.setSelectedDurationIdx??ye,[ge,be]=o.useState(!1),[Me,Se]=o.useState(null),[Ve,me]=o.useState(!1),[Ne,Le]=o.useState(!1),[oe,Ee]=o.useState(null);qe.useWalletClient(),qe.useSwitchChain();const{chain:ne,address:le}=qe.useAccount();qe.useConfig();const Je=o.useRef(ne);o.useEffect(()=>{Je.current=ne},[ne]);const Ye=Ht(),{isReady:G,isAuthenticated:xe,isConnected:E,address:N,provider:_,actions:fe}=Ye,{externalWallet:A,embeddedAddress:q}=Yn(),{intentStatus:re,startStatusPolling:ue,clearStatus:Ze}=Un({checkStepStatus:(K,de)=>V.relayerService.checkStepStatus(K,de),retryStep:async(K,de)=>{const[Te,Ue]=K.split("/"),Oe=parseInt(Ue||"0",10);await V.relayerService.executeStep(Te,Oe,de,{action:"execute"})},maxRetries:3}),{assets:lt,refetch:Be}=an({address:N,supportedChains:x,enabled:E&&!T,refetchInterval:3e4}),Xe=o.useMemo(()=>{if(y.length===0)return lt;const K=new Set(y.map(de=>de.toLowerCase()));return lt.filter(de=>K.has(de.address.toLowerCase()))},[lt,y]),ve=Pt(),rt=T?le:ve,ht=o.useMemo(()=>{if(!f)return[];const K=new Set,de=[],Te=Ue=>{if(!Ue)return;const Oe=Ue.toLowerCase();K.has(Oe)||(K.add(Oe),de.push(Q.getAddress(Ue)))};if(w&&Te(w),T)for(const Ue of y)Te(Ue);return de},[f,T,w,y]),Fe=o.useMemo(()=>ht.map(K=>K.toLowerCase()).sort().join(","),[ht]),Ct=o.useMemo(()=>JSON.stringify([...x||[]].sort()),[x]),[xt,vt]=o.useState([]),zt=o.useRef(0),It=o.useCallback(async()=>{if(!f||!rt||ht.length===0){zt.current++,vt([]);return}const K=++zt.current,de=Q.getAddress(rt),Te=x&&x.length>0?x:[d],Ue=ht.map(ce=>{const Ce=ce.toLowerCase();for(const Ie of Te){const Re=H.getChainConfig(Ie)?.supportedTokens?.find(Ae=>Ae.address.toLowerCase()===Ce);if(Re)return{address:ce,chainId:Ie,configToken:{decimals:Re.decimals,symbol:Re.symbol,name:Re.name,logo:Re.logo}}}return{address:ce,chainId:d}}),Oe=new Map;for(const ce of Ue){const Ce=Oe.get(ce.chainId)||[];Ce.push(ce),Oe.set(ce.chainId,Ce)}const pt=async(ce,Ce)=>{try{const Ie=await Qt.readContract(ce,{address:Ce.address,abi:H.T,functionName:"balanceOf",args:[de]});let Re,Ae,We,we;if(Ce.configToken)Re=Ce.configToken.decimals,Ae=Ce.configToken.symbol,We=Ce.configToken.name,we=Ce.configToken.logo;else{const[j,J,je]=await Promise.all([Qt.readContract(ce,{address:Ce.address,abi:H.T,functionName:"decimals",args:[]}).catch(()=>18),Qt.readContract(ce,{address:Ce.address,abi:H.T,functionName:"symbol",args:[]}).catch(()=>"TOKEN"),Qt.readContract(ce,{address:Ce.address,abi:H.T,functionName:"name",args:[]}).catch(()=>"TOKEN")]);Re=Number(j),Ae=J,We=je}const W=!!w&&Ce.address.toLowerCase()===w.toLowerCase()&&Ce.chainId===d;W&&i&&(we=i),W&&a&&!Ce.configToken&&(Ae==="TOKEN"&&(Ae=a),We==="TOKEN"&&(We=a));const X=parseFloat((Number(Ie)/Math.pow(10,Re)).toFixed(6));return{address:Ce.address,name:We,symbol:Ae,decimals:Re,balance:Ie,balanceFormatted:X,balanceUsd:0,logoURI:we,isNative:!1,chainId:Ce.chainId}}catch{return null}},se=await Promise.all(Array.from(Oe.entries()).map(async([ce,Ce])=>{let Ie;try{Ie=H.getClientForChain(ce)}catch{return[]}const Re=[],Ae=[];for(const we of Ce){const W=Re.length;Re.push({address:we.address,abi:H.T,functionName:"balanceOf",args:[de]}),we.configToken||Re.push({address:we.address,abi:H.T,functionName:"decimals",args:[]},{address:we.address,abi:H.T,functionName:"symbol",args:[]},{address:we.address,abi:H.T,functionName:"name",args:[]}),Ae.push({start:W,item:we})}let We=null;try{We=await Ie.multicall({contracts:Re})}catch{We=null}return We?Ae.map(({start:we,item:W})=>{const X=We[we],j=X?.status==="success"?X.result:0n;let J,je,et,tt;if(W.configToken)J=W.configToken.decimals,je=W.configToken.symbol,et=W.configToken.name,tt=W.configToken.logo;else{const Qe=We[we+1],st=We[we+2],ot=We[we+3];J=Qe?.status==="success"?Number(Qe.result):18,je=st?.status==="success"?st.result:"TOKEN",et=ot?.status==="success"?ot.result:je}const ze=!!w&&W.address.toLowerCase()===w.toLowerCase()&&W.chainId===d;ze&&i&&(tt=i),ze&&a&&!W.configToken&&(je==="TOKEN"&&(je=a),et==="TOKEN"&&(et=a));const it=parseFloat((Number(j)/Math.pow(10,J)).toFixed(6));return{address:W.address,name:et,symbol:je,decimals:J,balance:j,balanceFormatted:it,balanceUsd:0,logoURI:tt,isNative:!1,chainId:W.chainId}}):(await Promise.all(Ce.map(we=>pt(Ie,we)))).filter(we=>we!==null)}));K===zt.current&&vt(se.flat())},[f,rt,Fe,Ct,d,w,i,a]);o.useEffect(()=>{if(!f){vt([]);return}It();const K=setInterval(()=>{It()},15e3);return()=>clearInterval(K)},[It,f]);const nt=o.useCallback(()=>{It()},[It]),At=o.useMemo(()=>xt.filter(K=>K.balance>0n),[xt]),kt=o.useMemo(()=>{if(T)return At.map(de=>({...de,_source:"wallet"}));if(!f)return Xe;const K=[];for(const de of At)K.push({...de,_source:"wallet"});for(const de of Xe)K.push({...de,_source:"spice"});return K},[T,f,At,Xe]),ut=o.useRef(null),mt=o.useRef(null);o.useEffect(()=>{mt.current=O},[O]),o.useEffect(()=>{t||(R(null),Se(null),be(!1),Le(!1),Ee(null),me(!1),Ze())},[t,Ze]),o.useEffect(()=>{l&&l.assetAmount!==(O?.amount||"")&&R(K=>K&&{...K,amount:l.assetAmount})},[l?.assetAmount]),o.useEffect(()=>{r&&r.assetAmount!==(O?.amount||"")&&R(K=>K&&{...K,amount:r.assetAmount})},[r?.assetAmount]),o.useEffect(()=>{if(!T&&re?.overallStatus==="success"&&re.intentId&&ut.current!==re.intentId&&N&&re.steps.find(K=>K.transactionHash)?.transactionHash){ut.current=re.intentId;const K=mt.current;if(!K?.asset||!K.amount||K.asset._source==="wallet"||Q.parseUnits(K.amount,K.asset.decimals)===0n)return;Be()}},[re,N,d,Be,T]);const Ge=parseFloat(O?.amount||"")||0,dt=o.useMemo(()=>O?.asset?O.asset._source==="wallet"?O.asset.balanceFormatted??0:Xe.find(K=>K.address.toLowerCase()===O.asset.address.toLowerCase()&&K.chainId===O.asset.chainId)?.balanceFormatted??0:0,[O?.asset,Xe]),bt=Ge>0&&Ge>dt,ft=c?.selectedDuration??h[ke]??h[0],gt=o.useMemo(()=>!O?.asset||!w?!1:O.asset.address.toLowerCase()===w.toLowerCase()&&O.asset.chainId===d,[O?.asset,w,d]),Bt=o.useMemo(()=>Ge<=0?0:gt?Ge:!D||D<=0?0:Ge/D,[Ge,D,gt]),ie=o.useMemo(()=>Bt<=0?null:Bt.toLocaleString(void 0,{maximumFractionDigits:2}),[Bt]),pe=u&&Bt>0&&ft?u(Bt,ft.months):void 0,Pe=o.useMemo(()=>Ge<=0?"$0.00":gt&&D?(Ge*D).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!D||D<=0?"$0.00":Ge.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[Ge,D,gt]),$e=o.useMemo(()=>{if(!ie)return null;const K=parseFloat(ie.replace(/,/g,""));return gt&&D?(K*D).toLocaleString(void 0,{maximumFractionDigits:2}):D?(K*D).toLocaleString(void 0,{maximumFractionDigits:2}):null},[ie,D,gt]),at=o.useCallback(K=>{R(de=>({asset:K,amount:de?.asset?.address===K.address&&de?.asset?.chainId===K.chainId&&de.amount||""})),Se(null),r?.setSelectedAsset&&r.setSelectedAsset({symbol:K.symbol,address:K.address,decimals:K.decimals,chainId:K.chainId})},[r?.setSelectedAsset]),ct=o.useCallback(K=>{R(de=>de&&{...de,amount:K}),Se(null),l&&l.setAssetAmount(K),r&&r.setAssetAmount(K)},[l,r]),_e=o.useCallback(()=>{if(typeof s=="function"){if(!O?.asset||!O.amount)throw new Error("Select an asset and enter an amount");return s({asset:O.asset,amount:O.amount,amountWei:Q.parseUnits(O.amount,O.asset.decimals)})}return s},[s,O]),Ke=o.useCallback(async()=>{const K=T&&q||N;if(!E||!K)throw new Error("Please connect your wallet to continue");const de=_e();if(de.length===0)throw new Error("No lock batches configured");if(!G||!xe)throw new Error(`Please authenticate with ${_||"wallet provider"} to continue`);const Te=[...de],Ue=[...new Set(Te.map(we=>we.chainId))],Oe=[];for(const we of Ue){const W=H.getClientForChain(we),X=H.getDelegateContractAddress(we),j=await Y.getAccountNonce(K,W),J=await fe.signAuthorization({contractAddress:X,chainId:we,nonce:Number(j)});Oe.push(J)}const pt=Y.hashChainBatches(Te),se=Math.floor(Date.now()/1e3)+60*10,ce=pt.map(we=>we.hash),Ce=Q.keccak256(Q.encodeAbiParameters([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,BigInt(se),ce])),Ie=await fe.signMessage({raw:Ce}),Re=typeof Ie=="string"?Ie:Ie.signature;if(!Re)throw new Error("Failed to sign intent authorization");const Ae={mode:"7702",signatureType:"ecdsa",signature:Re,nbf:0,exp:se,chainBatches:pt.map((we,W)=>({hash:we.hash,chainId:we.chainId,tokenTransfers:Te[W].tokenTransfers??[],calls:we.calls}))},We=await V.relayerService.createAction({user:K,chainAuthorizations:Oe.map(we=>({r:we.r,s:we.s,yParity:we.yParity,address:we.address,chainId:Number(we.chainId),nonce:Number(we.nonce)})),intents:[Ae]});if(We){const we=V.createInitialSteps(Te,H.getChainName),[W,X]=We.intentIds[0].split("/"),j=parseInt(X||"0",10);ue(We.intentIds[0],we);for(let J=0;J<Te.length;J++)await ls(()=>V.relayerService.executeStep(W,j,J,{action:"execute"}))}},[_e,Ye,ue,T,q]),St=o.useCallback(async()=>{if(!O?.asset||!O.amount)throw new Error("Select an asset and enter an amount");if(!N||!ve)throw new Error("Embedded wallet not connected");const K=O.asset,de=Q.parseUnits(O.amount,K.decimals),Te=p||H.getDelegateContractAddress(d),Ue=await fe.getEthereumProvider();await Ue.request({method:"wallet_switchEthereumChain",params:[{chainId:`0x${d.toString(16)}`}]});const Oe=H.getChainConfig(d),pt=Q.createWalletClient({account:ve,transport:Q.custom(Ue),chain:Oe?.viemChain});let se;if(K.isNative||Y.isNativeToken(K.address))se=await pt.sendTransaction({to:Te,value:de,chain:Oe?.viemChain});else{const ce=Q.encodeFunctionData({abi:H.T,functionName:"transfer",args:[Te,de]});se=await pt.sendTransaction({to:K.address,data:ce,chain:Oe?.viemChain})}if((await H.getClientForChain(d).waitForTransactionReceipt({hash:se,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to escrow failed");await Be(),nt(),await Ke()},[O,N,ve,fe,p,d,Ke,Be,nt]),jt=o.useCallback(async()=>{if(!O?.asset||!O.amount)throw new Error("Select an asset and enter an amount");if(!le||!A)throw new Error("Please connect your external wallet to continue");if(!(ve||q))throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");if(S){const Re=_e();if(Re.length===0)throw new Error("No lock batches configured");const Ae=O.asset,We=Q.parseUnits(O.amount,Ae.decimals),we=await S({asset:Ae,amount:O.amount,amountWei:We,lockDurationMonths:ft?.months??0,chainBatches:Re});we&&g?.(we);return}const K=O.asset,de=Q.parseUnits(O.amount,K.decimals),Te=K.chainId,Ue=p||Y.ESCROW_ADDRESS,Oe=await A.getEthereumProvider();let pt=null;try{const Re=await Oe.request({method:"eth_chainId"});pt=parseInt(Re,16)}catch{pt=null}if(pt!==Te)try{await Oe.request({method:"wallet_switchEthereumChain",params:[{chainId:`0x${Te.toString(16)}`}]})}catch(Re){if(Re?.code===4902||Re?.message?.includes("Unrecognized chain ID")){const Ae=H.getChainConfig(Te);Ae&&await Oe.request({method:"wallet_addEthereumChain",params:[{chainId:`0x${Te.toString(16)}`,chainName:Ae.name||`Chain ${Te}`,nativeCurrency:Ae.nativeCurrency||{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:[Ae.rpcUrl],blockExplorerUrls:Ae.blockExplorer?[Ae.blockExplorer]:void 0}]})}else throw Re}const se=H.getChainConfig(Te),ce=Q.createWalletClient({account:le,chain:se?.viemChain,transport:Q.custom(Oe)}),Ce=Y.normalizeNativeTokenAddress(K.address),Ie=K.isNative||Y.isNativeToken(Ce)?await ce.sendTransaction({to:Ue,value:de,chain:se?.viemChain}):await ce.sendTransaction({to:Ce,data:Q.encodeFunctionData({abi:H.T,functionName:"transfer",args:[Ue,de]}),chain:se?.viemChain});if((await H.getClientForChain(Te).waitForTransactionReceipt({hash:Ie,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Escrow deposit failed");await Ke()},[O,A,le,ve,q,p,S,_e,ft,g,Ke]),Ft=o.useCallback(async()=>{if(!O?.asset||!O.amount)throw new Error("Select an asset and enter an amount");if(!le||!A)throw new Error("Please connect your external wallet to continue");const K=_e();if(K.length===0)throw new Error("No lock batches configured");const de=K.find(Ce=>Ce.chainId===d)||K[0];if(!de)throw new Error("No lock batch for lock chain");const Te=await A.getEthereumProvider();let Ue=null;try{const Ce=await Te.request({method:"eth_chainId"});Ue=parseInt(Ce,16)}catch{Ue=null}if(Ue!==d)try{await Te.request({method:"wallet_switchEthereumChain",params:[{chainId:`0x${d.toString(16)}`}]})}catch(Ce){if(Ce?.code===4902||Ce?.message?.includes("Unrecognized chain ID")){const Ie=H.getChainConfig(d);Ie&&await Te.request({method:"wallet_addEthereumChain",params:[{chainId:`0x${d.toString(16)}`,chainName:Ie.name||`Chain ${d}`,nativeCurrency:Ie.nativeCurrency||{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:[Ie.rpcUrl],blockExplorerUrls:Ie.blockExplorer?[Ie.blockExplorer]:void 0}]})}else throw Ce}const Oe=H.getChainConfig(d),pt=Q.createWalletClient({account:le,chain:Oe?.viemChain,transport:Q.custom(Te)}),se=H.getClientForChain(d);let ce;for(const Ce of de.calls){const Ie=await pt.sendTransaction({to:Ce.to,data:Ce.data,value:Ce.value,chain:Oe?.viemChain});if((await se.waitForTransactionReceipt({hash:Ie,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Lock transaction failed");ce=Ie}ce&&g?.(ce)},[O,A,le,_e,d,g]);o.useEffect(()=>{if(re?.overallStatus==="success"){const K=re.steps.find(de=>de.transactionHash);g?.(K?.transactionHash)}},[re?.overallStatus,g]);const Et=f&&O?.asset?._source==="wallet"&&O?.asset?.chainId===d,Rt=o.useCallback(async()=>{if(!O?.asset||Ge<=0){Se("Select an asset and enter an amount");return}if(bt){Se("Insufficient balance. Add more assets.");return}be(!0),Se(null);const K=de=>{console.error("[SpiceLockModal] lock failed:",de);const Te=Lt(de,""),Ue=typeof de?.shortMessage=="string"?de.shortMessage:typeof de?.message=="string"?de.message:"";Se(Te||Ue||"Transaction failed. Please try again.")};if(T){if(gt){try{await Ft()}catch(de){K(de)}finally{be(!1)}return}me(!0);try{await jt()}catch(de){K(de)}finally{be(!1)}return}me(!0);try{Et&&!gt?await St():await Ke()}catch(de){K(de)}finally{be(!1)}},[O,Ge,bt,T,jt,Ft,Et,gt,St,Ke]),Dt=!!O?.asset&&Ge>0&&!bt&&!ge,Gt=e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[e.jsx(Sr,{color:L}),e.jsxs("p",{style:{fontSize:"13px",color:L,margin:0,lineHeight:"1.5"},children:["Add ",a," by converting assets from your account"]})]});if(!t)return null;const Zt={backgroundColor:F,border:M,borderRadius:ee,padding:"16px",marginBottom:"16px"};return e.jsx(Mt,{isOpen:t,onClose:n,title:`Add ${a} to your account`,subtitle:Gt,styles:B,dark:v,footerLinkText:"Spicenet accounts \u2192",overlayContent:Ne?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:[m&&e.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:e.jsxs("button",{onClick:m,style:{background:"none",border:"none",cursor:"pointer",padding:0,display:"flex",alignItems:"center",gap:"4px",color:z,fontSize:"12px",fontWeight:500,fontFamily:k,textDecoration:"underline",textUnderlineOffset:"2px"},children:["Add Funds",e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:z,strokeWidth:"1.8",children:[e.jsx("circle",{cx:"6",cy:"6",r:"5"}),e.jsx("path",{d:"M6 4v4M4 6h4",strokeLinecap:"round"})]})]})}),e.jsx(dn,{assets:kt,selectedAsset:O??void 0,onAssetSelect:at,onAmountChange:ct,label:"Amount",showBalance:!0,showMaxButton:!0,theme:te,styles:Z}),e.jsx("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:L,fontFamily:k},children:Pe})]}),e.jsxs("div",{style:Zt,children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:v?`1px solid ${C.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:v?C.inputBg:"#d1d5db",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:700,color:$},children:a.slice(0,2)}),e.jsx("span",{style:{fontSize:"16px",fontWeight:600,color:$,fontFamily:k},children:a})]}),e.jsxs("div",{style:{textAlign:"right"},children:[e.jsx("div",{style:{fontSize:"22px",fontWeight:700,color:$,fontFamily:k,lineHeight:1.1},children:ie??"0.00"}),e.jsxs("div",{style:{fontSize:"12px",color:L,fontFamily:k,marginTop:"2px"},children:["~$",$e??"0.00"]})]})]}),e.jsxs("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:v?`1px solid ${C.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:L,fontFamily:k},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:L,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),e.jsx(Cr,{options:h,selectedIndex:ke,onSelect:he,primaryColor:z,dark:v,textPrimary:$,textSecondary:L})]}),e.jsxs("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[e.jsx(wr,{durationMonths:ft?.months,fontFamily:k,dark:v,textPrimary:$,textSecondary:L}),u&&e.jsx(vr,{votes:pe,fontFamily:k,dark:v,textPrimary:$,textSecondary:L})]})]}),Me&&e.jsx("div",{style:{marginBottom:"12px",padding:"10px 14px",backgroundColor:v?"rgba(239,68,68,0.12)":"#fef2f2",border:`1px solid ${v?"rgba(239,68,68,0.3)":"#fecaca"}`,borderRadius:"6px"},children:e.jsx("p",{style:{color:"#ef4444",fontSize:"13px",margin:0,fontFamily:k},children:Me})}),e.jsx(De.Button,{variant:"outline",fullWidth:!0,onClick:Rt,disabled:!Dt,loading:ge,dark:v,styles:{button:{backgroundColor:z}},children:ge?Et&&!gt?"DEPOSITING...":gt?"LOCKING...":"CONVERTING...":Et&&!gt?`DEPOSIT ${a}`:gt?`LOCK ${a}`:`CONVERT TO ${a}`}),e.jsx(kr,{isOpen:Ne,data:oe,isLocking:ge,lockError:Me,onContinue:Rt,onClose:()=>Le(!1),primaryColor:z,fontFamily:k,dark:v}),re&&Ve&&e.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:v?C.shell:"white",borderRadius:ee,padding:"16px 0"},children:e.jsx(gn,{type:"deposit",isOpen:!!re&&re.overallStatus!=="processing",isProcessing:ge||re?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{Ze(),me(!1),Rt()},onNewTx:()=>{Ze(),me(!1),R(null),ut.current=null,Be(),nt()},onClose:()=>{Ze(),me(!1)},onComplete:()=>{Ze(),me(!1),R(null),ut.current=null,Be(),nt()},results:re?.overallStatus==="success"||re?.overallStatus==="failed"?re.steps.map(K=>({asset:{symbol:O?.asset?.symbol||a,address:O?.asset?.address||""},txHash:K.transactionHash||"",success:K.status==="success",amount:O?.amount})):void 0,chainName:H.getChainName(d),explorerUrl:H.getExplorerUrl(d,"").replace(/\/tx\/.*$/,"")||void 0,theme:I,styles:B,dark:v})})]})})},Ws=({variant:t,destinationSymbol:n,destinationLogoURI:s,destinationDecimals:a,primaryColor:i,fontFamily:l,textPrimary:r,textSecondary:c,cardBg:d,cardBorder:h,dk:u,dark:x,isQuoting:y,quoteError:p,estimatedOutput:f,paymentAmount:w,needsSwap:g,exactOutputSwap:S,adjustable:D=!1,maxAmount:b,onAmountChange:m})=>t==="supply"?e.jsx("div",{style:{backgroundColor:d,border:`1px solid ${h}`,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(Ns,{symbol:n,logoURI:s,primaryColor:i,size:28}),e.jsxs("span",{style:{fontSize:"13px",fontWeight:500,color:c,fontFamily:l},children:["Estimated ",n]})]}),e.jsx("div",{style:{textAlign:"right"},children:y?e.jsx("span",{style:{fontSize:"14px",color:c,fontFamily:l},children:"Quoting..."}):p?e.jsx("span",{style:{fontSize:"13px",color:"#ef4444",fontFamily:l},children:"Quote failed"}):f?e.jsxs("span",{style:{fontSize:"16px",fontWeight:600,color:r,fontFamily:l},children:["\u2248 ",f]}):e.jsx("span",{style:{fontSize:"14px",color:c,fontFamily:l},children:"\u2014"})})]})}):e.jsx(jr,{destinationSymbol:n,destinationLogoURI:s,destinationDecimals:a,primaryColor:i,fontFamily:l,textPrimary:r,textSecondary:c,cardBg:d,cardBorder:h,dk:u,dark:x,paymentAmount:w||"0",needsSwap:g,exactOutputSwap:S,isQuoting:y,adjustable:D,maxAmount:b,onAmountChange:m}),Ns=({symbol:t,logoURI:n,primaryColor:s,size:a})=>n?e.jsx("img",{src:n,alt:t,style:{width:a,height:a,borderRadius:"50%",objectFit:"cover"}}):e.jsx("div",{style:{width:a,height:a,borderRadius:"50%",backgroundColor:`${s}22`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:a<30?"11px":"12px",fontWeight:700,color:s},children:t.slice(0,2)}),jr=({destinationSymbol:t,destinationLogoURI:n,destinationDecimals:s,primaryColor:a,fontFamily:i,textPrimary:l,textSecondary:r,cardBg:c,cardBorder:d,dk:h,dark:u,paymentAmount:x,needsSwap:y,exactOutputSwap:p,isQuoting:f,adjustable:w,maxAmount:g,onAmountChange:S})=>{const D='"IBM Plex Mono", monospace',b=parseFloat(x||"0"),m=g?parseFloat(g):0,[B,U]=o.useState(x||""),I=o.useRef(null),[v,z]=o.useState(null),[C,k]=o.useState(null);o.useEffect(()=>{w||U(x||"")},[x,w]);const P=M=>{let ee=M;ee.startsWith(".")&&(ee="0"+ee);const $=is(ee);let L=$;g&&parseFloat($)>parseFloat(g)&&(L=g),U(L),I.current&&clearTimeout(I.current),I.current=setTimeout(()=>S?.(L),300)},T=M=>{if(!m)return;if(M===100){U(g||m.toString()),I.current&&clearTimeout(I.current),S?.(g||m.toString());return}const ee=10**s,$=(Math.floor(m*M/100*ee)/ee).toString();U($),I.current&&clearTimeout(I.current),S?.($)},F=m>0?parseFloat(B||"0")/m*100:0;return o.useEffect(()=>()=>{I.current&&clearTimeout(I.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(Ns,{symbol:t,logoURI:n,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:[w?e.jsx("input",{type:"text",value:B,onChange:M=>P(M.target.value),placeholder:"0.0",style:{fontSize:"20px",fontWeight:700,color:l,fontFamily:D,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:D,lineHeight:1.1},children:b>0?x:"0.00"}),e.jsx("div",{style:{fontSize:"12px",color:r,fontFamily:D,marginTop:"2px"},children:t}),w&&m>0&&e.jsx("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((M,ee)=>{const $=Math.abs(F-M)<1,L=ee===4,Z=M/100,te=v===M,O=C===M;return e.jsx("button",{onClick:()=>T(M),onMouseEnter:()=>z(M),onMouseLeave:()=>{z(null),k(null)},onMouseDown:()=>k(M),onMouseUp:()=>k(null),title:`${M}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:$?1:te?.8:.5,transform:O?"scale(0.85)":te?"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:L?a:"none",stroke:L?a:u?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!L&&Z>0&&e.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${Z>.5?1:0} 1 ${7+6.84375*Math.sin(Z*2*Math.PI)} ${7-6.84375*Math.cos(Z*2*Math.PI)} Z`,fill:u?h?.textSecondary||"#9ca3af":"#3C3E42"})]})},M)})})]})]}),y&&p&&!f&&e.jsx("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:u?`1px solid ${h?.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 ",p.venue]})})]})};function Us(t,n,s){const a=t.address.toLowerCase()===n,i=t.chainId===s,l=t._source==="wallet";return l&&a&&i?0:l&&i?1:!l&&a?2:!l&&i?3:4}function Er(t){const{address:n,destinationToken:s,supportedSourceAssets:a,sourceChains:i,enabled:l}=t,r=Pt(),{assets:c,refetch:d}=an({address:n,supportedChains:i,enabled:l,refetchInterval:3e4}),h=o.useMemo(()=>{if(!a||a.length===0)return c;const p=a.map(f=>f.toLowerCase());return c.filter(f=>p.includes(f.address.toLowerCase()))},[c,a]),[u,x]=o.useState(null);o.useEffect(()=>{if(!s.address||!r||!l){x(null);return}let p=!1;const f=Q.getAddress(s.address),w=Q.getAddress(r),g=H.getClientForChain(s.chainId),S=async()=>{try{const b=await g.multicall({contracts:[{address:f,abi:Q.erc20Abi,functionName:"balanceOf",args:[w]},{address:f,abi:Q.erc20Abi,functionName:"decimals",args:[]},{address:f,abi:Q.erc20Abi,functionName:"symbol",args:[]},{address:f,abi:Q.erc20Abi,functionName:"name",args:[]}]});if(p)return;const m=b[0].status==="success"?b[0].result:0n,B=b[1].status==="success"?Number(b[1].result):s.decimals,U=b[2].status==="success"?b[2].result:s.symbol,I=b[3].status==="success"?b[3].result:s.symbol;m>0n?x({address:f,name:I,symbol:U,decimals:B,balance:m,balanceFormatted:parseFloat((Number(m)/Math.pow(10,B)).toFixed(6)),balanceUsd:0,logoURI:s.logoURI,isNative:!1,chainId:s.chainId}):x(null)}catch{p||x(null)}};S();const D=setInterval(S,15e3);return()=>{p=!0,clearInterval(D)}},[s.address,s.chainId,s.decimals,s.symbol,s.logoURI,r,l]);const y=o.useCallback(()=>{if(!s.address||!r)return;const p=H.getClientForChain(s.chainId),f=Q.getAddress(s.address),w=Q.getAddress(r);p.multicall({contracts:[{address:f,abi:Q.erc20Abi,functionName:"balanceOf",args:[w]},{address:f,abi:Q.erc20Abi,functionName:"decimals",args:[]}]}).then(g=>{const S=g[0].status==="success"?g[0].result:0n,D=g[1].status==="success"?Number(g[1].result):18;S>0n?x(b=>b?{...b,balance:S,balanceFormatted:parseFloat((Number(S)/Math.pow(10,D)).toFixed(6))}:null):x(null)}).catch(()=>{})},[s.address,s.chainId,r]);return{displayAssets:o.useMemo(()=>{const p=[];u&&p.push({...u,_source:"wallet"});for(const w of h)p.push({...w,_source:"spice"});const f=s.address.toLowerCase();return p.sort((w,g)=>Us(w,f,s.chainId)-Us(g,f,s.chainId)),p},[u,h,s.address,s.chainId]),filteredSpiceAssets:h,embeddedWalletAddress:r,refreshSpiceAssets:d,refreshWalletAssets:y}}async function zs(t){const{tokenIn:n,tokenOut:s,amountIn:a,fee:i,chainId:l,config:r}=t;if(a<=0n)throw new Error("amountIn must be greater than 0");const c=(await H.getClientForChain(l).simulateContract({address:r.quoterV2,abi:Y.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:n,tokenOut:s,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 Ls(t){const n=t.feeTiers??[100,500,3e3,1e4],s=await Promise.allSettled(n.map(i=>zs({...t,fee:i})));let a=null;for(let i=0;i<s.length;i++){const l=s[i];l.status==="fulfilled"&&(!a||l.value.amountOut>a.amountOut)&&(a={...l.value,fee:n[i]})}if(!a)throw new Error("No liquidity found for this pair on any fee tier.");return a}const Ar=[{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 Br(t){const{tokenIn:n,tokenOut:s,amountOut:a,fee:i,chainId:l,config:r}=t;if(a<=0n)throw new Error("amountOut must be greater than 0");const c=(await H.getClientForChain(l).simulateContract({address:r.quoterV2,abi:Ar,functionName:"quoteExactOutputSingle",args:[{tokenIn:n,tokenOut:s,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 Fr(t){const n=t.feeTiers??[100,500,3e3,1e4],s=await Promise.allSettled(n.map(i=>Br({...t,fee:i})));let a=null;for(let i=0;i<s.length;i++){const l=s[i];l.status==="fulfilled"&&(!a||l.value.amountIn<a.amountIn)&&(a={...l.value,fee:n[i]})}if(!a)throw new Error("No liquidity found for this pair on any fee tier.");return a}function Ps(t){return t.type==="swap"}const $n=.02,Rr=[1,8453,42161,10,137,43114,56],Tr="https://api.1inch.dev/swap/v6.0";function Hs(t,n){return Y.applySlippage(t,n)}function Os(t){const n=t?.baseUrl??Tr;return{name:"1inch",chainIds:t?.chainIds??Rr,resolve:async(s,a,i)=>{const l=s.maxSlippage??$n,r=l*100,c=Y.isNativeToken(s.tokenIn)?Y.NATIVE_TOKEN_ADDRESS:s.tokenIn,d=Y.isNativeToken(s.tokenOut)?Y.NATIVE_TOKEN_ADDRESS:s.tokenOut,h=Y.isNativeToken(s.tokenIn);try{const u=new URL(`${n}/${a}/swap`);u.searchParams.set("src",c),u.searchParams.set("dst",d),u.searchParams.set("amount",s.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 y=await fetch(u.toString(),{headers:x});if(!y.ok)throw new V.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${y.status} for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${a}`,{venue:"1inch",chainId:a,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn.toString(),cause:`HTTP ${y.status}`});const p=await y.json();if(!p.dstAmount||!p.tx)return console.warn(`[1inchVenue] No route data for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${a}`),null;const f=BigInt(p.dstAmount);if(f<=0n)return console.warn(`[1inchVenue] Zero output for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${a}`),null;const w=Hs(f,l),g=[];return p.tx.to&&!h&&g.push({to:s.tokenIn,value:0n,data:Q.encodeFunctionData({abi:Q.erc20Abi,functionName:"approve",args:[p.tx.to,s.amountIn]})}),g.push({to:p.tx.to,value:BigInt(p.tx.value||"0"),data:p.tx.data}),{venue:"1inch",amountOut:f,amountOutMinimum:w,calls:g}}catch(u){if(u instanceof V.SpiceflowError)throw u;const x=u instanceof Error?u.message:String(u);throw new V.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] Exception for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${a}: ${x}`,{venue:"1inch",chainId:a,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn.toString(),cause:x})}}}}const Vs=[4114,5115],_n={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425"},Qs={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453]};function Ys(t){return{name:"satsuma",chainIds:t.chainIds??Vs,resolve:async(n,s,a)=>{const i=n.maxSlippage??$n,l=Y.isNativeToken(n.tokenIn);let r;try{r=await Ls({tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn,chainId:s,config:{swapRouter:t.swapRouter,quoterV2:t.quoterV2},feeTiers:t.feeTiers})}catch{return console.warn(`[SatsumaVenue] No viable fee tier for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}.`),null}const c=Hs(r.amountOut,i),d=[];return l||d.push({to:n.tokenIn,value:0n,data:Q.encodeFunctionData({abi:Q.erc20Abi,functionName:"approve",args:[t.swapRouter,n.amountIn]})}),d.push({to:t.swapRouter,value:l?n.amountIn:0n,data:Q.encodeFunctionData({abi:Y.uniV3SwapRouterAbi,functionName:"exactInputSingle",args:[{tokenIn:n.tokenIn,tokenOut:n.tokenOut,fee:r.fee,recipient:a,amountIn:n.amountIn,amountOutMinimum:c,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:r.amountOut,amountOutMinimum:c,calls:d}}}}function Zs(t){return{name:"satsuma",chainIds:t.chainIds??Vs,resolve:async(n,s,a)=>{const i=n.maxSlippage??$n,l=Y.isNativeToken(n.tokenIn);let r;try{r=await Fr({tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountOut:n.amountOut,chainId:s,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,h=[];return h.push({to:t.swapRouter,value:l?d:0n,data:Q.encodeFunctionData({abi:Mr,functionName:"exactOutputSingle",args:[{tokenIn:n.tokenIn,tokenOut:n.tokenOut,fee:r.fee,recipient:a,amountOut:n.amountOut,amountInMaximum:d,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:r.amountIn,amountInMax:d,amountOut:n.amountOut,calls:h}}}}const Mr=[{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 Ks(t){const n=[];t?.customVenues&&n.push(...t.customVenues),t?.satsuma&&n.push(Ys(t.satsuma)),n.push(Os(t?.oneInch));function s(i){return n.find(l=>l.chainIds.includes(i))}async function a(i,l,r){const c=[],d=[];for(const h of i){if(!Ps(h)){c.push(h);continue}const u=s(l);if(!u)throw new V.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${l}. Cannot resolve swap ${h.tokenIn} \u2192 ${h.tokenOut}.`,{chainId:l,tokenIn:h.tokenIn,tokenOut:h.tokenOut,amountIn:h.amountIn.toString()});const x=await u.resolve(h,l,r);if(!x)throw new V.SpiceflowError("NO_LIQUIDITY",`${u.name} returned no quote for ${h.tokenIn} \u2192 ${h.tokenOut} on chain ${l}.`,{venue:u.name,chainId:l,tokenIn:h.tokenIn,tokenOut:h.tokenOut,amountIn:h.amountIn.toString()});c.push(...x.calls),d.push(x)}return{calls:c,resolvedSwaps:d}}return{resolveSwapIntents:a,getVenueForChain:s,venues:n}}function Dr(t){const n=t?.customVenues??[];async function s(a,i,l){const r=n.filter(d=>d.chainIds.includes(i));if(r.length===0)throw new V.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 V.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,h)=>d.amountIn<h.amountIn?-1:d.amountIn>h.amountIn?1:0),c[0]}return{getQuote:s,venues:n}}function Wr(t){const{direction:n,selectedAsset:s,destinationToken:a,chainId:i,recipient:l,paymentAmount:r}=t,[c,d]=o.useState(!1),[h,u]=o.useState(null),[x,y]=o.useState(null),[p,f]=o.useState(null),[w,g]=o.useState(null),[S,D]=o.useState(null),[b,m]=o.useState(null),B=o.useRef(null),U=o.useMemo(()=>Ks({satsuma:_n}),[]),I=o.useMemo(()=>Dr({customVenues:[Zs(_n),Zs(Qs)]}),[]),v=o.useMemo(()=>{if(!s?.asset)return null;if(s.asset.chainId===i)return s.asset.address;const T=Xt(s.asset.address,i);return T?T.address:null},[s?.asset?.address,s?.asset?.chainId,i]),z=o.useMemo(()=>s?.asset?s.asset.address.toLowerCase()===a.address.toLowerCase()&&s.asset.chainId===i?!0:v?v.toLowerCase()===a.address.toLowerCase():!1:!1,[s,a.address,i,v]),C=v?v.toLowerCase()===a.address.toLowerCase():!1,k=n==="output"&&parseFloat(r||"0")===0,P=!!s?.asset&&!z&&!C&&!k;return o.useEffect(()=>{B.current&&clearTimeout(B.current);const T=n==="input"?s?.amount:r,F=parseFloat(T||"0");if(!P||F<=0||!s?.asset||!l||!v){y(null),f(null),g(null),D(null),m(null),u(null),d(!1);return}return d(!0),B.current=setTimeout(async()=>{try{if(n==="input"){const M=Q.parseUnits(s.amount,s.asset.decimals),ee=U.getVenueForChain(i);if(!ee)throw new Error("No swap venue for this chain");const $=await ee.resolve({type:"swap",tokenIn:v,tokenOut:a.address,amountIn:M},i,l);if(!$)throw new Error("No liquidity for this pair");m($.amountOut),g($),D(null);const L=Q.formatUnits($.amountOut,a.decimals),Z=parseFloat(L);y(Z<.01?Z.toPrecision(4):Z.toLocaleString(void 0,{maximumFractionDigits:6})),f(null),u(null)}else{const M=Q.parseUnits(r||"0",a.decimals),ee=await I.getQuote({tokenIn:v,tokenOut:a.address,amountOut:M},i,l);D(ee),g(null),m(null),f(parseFloat(Q.formatUnits(ee.amountIn,s.asset.decimals)).toFixed(6)),y(null),u(null)}}catch(M){const ee=M instanceof Error?M.message:"Failed to get quote";u(ee),y(null),f(null),g(null),D(null),m(null)}finally{d(!1)}},500),()=>{B.current&&clearTimeout(B.current)}},[n,P,s?.amount,s?.asset?.address,s?.asset?.decimals,r,v,i,a.address,a.decimals,l,U,I]),{isQuoting:c,quoteError:h,estimatedOutput:x,estimatedInput:p,resolvedSwap:w,exactOutputSwap:S,quoteAmountOut:b,resolvedTokenIn:v,isDirect:C,needsSwap:P,selectedIsEquivalent:z}}const qs={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Transaction successful!",error:"Transaction failed"},Xs=["signing-delegation","signing-intent","submitting","executing"],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})]}),Gs=({isOpen:t,onClose:n,destinationToken:s,buildActionCalls:a,buildSpicenetBatch:i,actionLabel:l,amountDirection:r="input",swapDescription:c,directDescription:d,supportedSourceAssets:h,sourceChains:u,paymentAmount:x,amountInputMode:y="fixed",minPaymentAmount:p,maxPaymentAmount:f,onAmountChange:w,styles:g,dark:S,title:D,subtitle:b,onAddFunds:m,onSuccess:B,onError:U})=>{const I=r==="output",{theme:v,dark:z,primaryColor:C,dk:k,palette:P}=V.useSpiceBrand(g,S),T=v.typography.fontFamily,F=g?.inputVariant?g.inputVariant==="dark":z,M=P.textPrimary,ee=P.textSecondary,$=F?k.cardBg:"#f9fafb",L=F?k.cardBorder:"#e5e7eb",Z=g?.button?.backgroundColor??C,te=g?.button?.color??"#0e0d0b",O=F?{...v,colors:{...v.colors,secondary:k.cardBg,surfaceHover:k.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:v,R=s.chainId,ae=Ht(),{address:ye,isConnected:ke,isReady:he,isAuthenticated:ge,provider:be}=ae,{executeGasless:Me}=jn(),{displayAssets:Se,filteredSpiceAssets:Ve,embeddedWalletAddress:me,refreshSpiceAssets:Ne,refreshWalletAssets:Le}=Er({address:ye,destinationToken:s,supportedSourceAssets:h,sourceChains:u,enabled:t&&!!ye}),oe=o.useMemo(()=>Ve.map(se=>({...se,_source:"spice"})),[Ve]),Ee=I?Se:oe,[ne,le]=o.useState(null),[Je,Ye]=o.useState(x||""),[G,xe]=o.useState(!1),[E,N]=o.useState(null),[_,fe]=o.useState("idle"),[A,q]=o.useState(""),[re,ue]=o.useState(null),[Ze,lt]=o.useState(!1),[Be,Xe]=o.useState(null),ve=o.useRef(ne),rt=o.useRef(!1),ht=o.useRef(null);o.useEffect(()=>{ve.current=ne},[ne]);const Fe=y==="adjustable"?Je:x||"0",Ct=me||ye,{isQuoting:xt,quoteError:vt,estimatedOutput:zt,resolvedSwap:It,exactOutputSwap:nt,quoteAmountOut:At,resolvedTokenIn:kt,isDirect:ut,needsSwap:mt,selectedIsEquivalent:Ge}=Wr({direction:r,selectedAsset:ne,destinationToken:s,chainId:R,recipient:Ct,paymentAmount:Fe}),dt=I?parseFloat(Fe||"0"):parseFloat(ne?.amount||"")||0,bt=o.useMemo(()=>ne?.asset?Ve.find(se=>se.address.toLowerCase()===ne.asset.address.toLowerCase())?.balanceFormatted??0:0,[ne,Ve]),ft=o.useMemo(()=>ne?.asset?I?Ge?dt>ne.asset.balanceFormatted:nt?parseFloat(Q.formatUnits(nt.amountInMax,ne.asset.decimals))>ne.asset.balanceFormatted:!1:dt>bt:!1,[ne,I,Ge,dt,nt,bt]);o.useEffect(()=>{t||(le(null),N(null),xe(!1),fe("idle"),q(""),ue(null),lt(!1),Xe(null),rt.current=!1,y==="adjustable"&&Ye(x||""),ht.current&&(ht.current.abort(),ht.current=null))},[t]);const gt=o.useCallback(se=>{le(ce=>({asset:se,amount:ce?.asset?.address===se.address&&ce?.asset?.chainId===se.chainId&&ce.amount||""})),N(null)},[]),Bt=o.useCallback(se=>{le(ce=>ce&&{...ce,amount:se}),N(null)},[]),ie=o.useCallback(se=>{let ce=se;f&&parseFloat(ce)>parseFloat(f)&&(ce=f),Ye(ce),w?.(ce),N(null)},[f,w]);o.useCallback(se=>{if(rt.current||!ye)return;const ce=ve.current;!ce?.asset||!ce.amount||ce.asset?._source==="wallet"||Q.parseUnits(I?Fe:ce.amount,ce.asset.decimals)===0n||(rt.current=!0,Ne())},[ye,R,Ne,I,Fe]);const pe=o.useCallback(se=>{fe({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[se.step]||"executing"),q(se.message),se.txHash&&ue(se.txHash)},[]),Pe=o.useCallback(()=>{const se=Q.parseUnits(Fe,s.decimals),ce={userAddress:me,chainId:R,destinationToken:s.address},Ce=a(se,ce),Ie={chainId:R,calls:Ce},Re=ne?.asset?._source==="spice",Ae=(We,we)=>({token:We,from:"solver",to:me,amount:we});if(se===0n)return[Ie];if(mt&&nt){let We=ne.asset.address;if(ne.asset.chainId!==R){const X=Y.getTokenDefinition(ne.asset.address)?.deployments.find(j=>j.chainId===R);X&&(We=X.address)}const we=Re?[Ae(We,nt.amountInMax)]:[],W={to:We,value:0n,data:Q.encodeFunctionData({abi:Q.erc20Abi,functionName:"approve",args:[nt.calls[0]?.to,nt.amountInMax]})};return[{chainId:R,calls:[W,...nt.calls,...Ce],tokenTransfers:[...we,...Ie.tokenTransfers??[]]}]}if(Re){let We=s.address;if(ne.asset.chainId!==R){const we=Y.getTokenDefinition(ne.asset.address)?.deployments.find(W=>W.chainId===R);we&&(We=we.address)}return[{...Ie,tokenTransfers:[Ae(We,se),...Ie.tokenTransfers??[]]}]}return[Ie]},[Fe,s,me,R,a,ne,mt,nt]),$e=o.useCallback(()=>{if(!ne?.asset||!me)return[];const se=Q.parseUnits(ne.amount,ne.asset.decimals),ce={userAddress:me,chainId:R,destinationToken:s.address},Ce=a(se,ce),Ie=ne.asset?._source==="spice";if(!Ie)return[{chainId:R,calls:Ce}];const Re=(W,X)=>({token:W,from:"solver",to:me,amount:X});if(mt&&It&&At&&kt){const W=a(At,ce),X={chainId:R,calls:[...It.calls,...W],tokenTransfers:[Re(kt,se)]};if(!i)return[X];const j=i({userAddress:me,destinationChainId:R,deliveryToken:kt,deliveryAmount:se});return console.log("[SpiceSupply] buildSupplyChainBatches:swap",{isSpiceSourced:Ie,hasBuildSpicenetBatch:!!i,amountIn:se.toString(),resolvedTokenIn:kt,spicenetBatch:j}),j?[j,X]:[X]}let Ae=s.address;if(ne.asset.chainId!==R){const W=Y.getTokenDefinition(ne.asset.address)?.deployments.find(X=>X.chainId===R);W&&(Ae=W.address)}const We={chainId:R,calls:Ce,tokenTransfers:[Re(Ae,se)]};if(!i)return[We];const we=i({userAddress:me,destinationChainId:R,deliveryToken:Ae,deliveryAmount:se});return console.log("[SpiceSupply] buildSupplyChainBatches:direct",{isSpiceSourced:Ie,hasBuildSpicenetBatch:!!i,amountIn:se.toString(),deliveryToken:Ae,spicenetBatch:we}),we?[we,We]:[We]},[ne,me,R,s,a,mt,It,At,kt,i]),at=o.useMemo(()=>{if(!ne?.asset)return s.address;if(ne.asset.chainId===R)return ne.asset.address;const se=Y.getTokenDefinition(ne.asset.address)?.deployments.find(ce=>ce.chainId===R);return se?se.address:s.address},[ne,s.address,R]),ct=o.useCallback(async()=>{if(!ne?.asset||dt<=0){N("Select an asset and enter an amount");return}if(ft){N("Insufficient balance");return}if(!me){N("Wallet not ready");return}xe(!0),N(null),fe("signing-delegation"),q("Building transaction..."),ue(null),rt.current=!1;const se=new AbortController;ht.current=se;try{const ce=Q.parseUnits(ne.amount,ne.asset.decimals),Ce=$e(),Ie=Ce.some(Re=>Re.tokenTransfers?.length);await Me(Ce,at,ce,pe,se.signal,Ie?{useCustomTransfers:!0}:void 0),fe("success"),q("Transaction successful!")}catch(ce){const Ce=ce instanceof Error?ce:new Error(String(ce));if(Ce.name==="AbortError"||se.signal.aborted){fe("idle");return}const Ie=Ce.message||"Transaction failed";fe("error"),q(Ie),N(Ie),U?.(Ce)}finally{xe(!1)}},[ne,dt,ft,me,at,$e,Me,pe,U]),_e=o.useCallback(async()=>{if(dt<0){N("Enter a valid payment amount");return}if(!ne?.asset){N("Select a payment source");return}if(ft){N("Insufficient balance");return}if(mt&&!nt){N("Swap quote not available. Try a different asset.");return}if(!ke||!ye){N("Please connect your wallet to continue");return}if(!he||!ge){N(`Please authenticate with ${be||"wallet provider"} to continue`);return}xe(!0),N(null),lt(!0),Xe({status:"processing"});try{const se=Pe(),ce=se.some(Ae=>Ae.tokenTransfers?.length),Ce=Q.parseUnits(Fe,s.decimals),Ie=ne?.asset?.address||s.address,Re=await Me(se,Ie,Ce,Ae=>{Ae.txHash&&(Xe(We=>({...We,txHash:Ae.txHash})),ue(Ae.txHash))},void 0,ce?{useCustomTransfers:!0}:void 0);Xe(Ae=>({status:"success",txHash:Ae?.txHash||Re}))}catch(se){const ce=Lt(se,"Payment failed. Please try again.");N(ce),Xe({status:"failed",error:ce}),U?.(se instanceof Error?se:new Error(ce))}finally{xe(!1)}},[dt,ne,ft,mt,nt,ke,ye,he,ge,be,Pe,Fe,s,Me,U]);o.useEffect(()=>{!I&&_==="success"&&re&&(Ne(),B?.(re))},[I,_,re,Ne,B]),o.useEffect(()=>{if(!I||Be?.status!=="success"||rt.current||!ye)return;rt.current=!0;const se=ve.current;!se?.asset||se.asset?._source==="wallet"||Ne()},[I,Be?.status,ye,Ne]);const Ke=o.useRef(B),St=o.useRef(U);o.useEffect(()=>{Ke.current=B},[B]),o.useEffect(()=>{St.current=U},[U]),o.useEffect(()=>{I&&(Be?.status==="success"&&Ke.current?.(Be.txHash||""),Be?.status==="failed"&&St.current?.(new Error("Payment execution failed")))},[I,Be?.status]);const jt=o.useCallback(()=>{lt(!1),Xe(null),le(null),rt.current=!1,Ne(),Le()},[Ne,Le]),Ft=I?!!ne?.asset&&dt>=0&&!ft&&!G&&(!mt||!!nt):!!ne?.asset&&dt>0&&!ft&&!G&&(ut||!!It&&!xt),Et=ut?d||`Your ${s.symbol} will be used directly.`:c||"Your assets will be swapped and used in a single atomic transaction.",Rt=z?k.shell:"white",Dt=z?k.buttonBorder:"#0e0d0b",Gt=(R?H.getChainConfig(R):void 0)?.viemChain?.blockExplorers?.default?.url??"",Zt=Xs.indexOf(_),K=G?(qs[_]||"EXECUTING...").toUpperCase():_==="success"?"DONE":ft?"INSUFFICIENT BALANCE":l.toUpperCase(),de=o.useMemo(()=>{if(G)return"PAYING...";if(ft&&ne?.asset)return`INSUFFICIENT ${ne.asset.symbol}`;const se=dt>0?` ${Fe} ${s.symbol}`:"";return mt?`SWAP & PAY${se}`:`PAY${se}`},[G,ft,ne,dt,Fe,s.symbol,mt]),Te=_==="success"?()=>{fe("idle"),le(null),ue(null),Ne()}:ct,Ue=_==="success"?!1:!Ft;if(!t)return null;const Oe=I?D||`Pay ${s.symbol}`:l,pt=I?b:e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[e.jsx(Nr,{color:ee}),e.jsx("p",{style:{fontSize:"13px",color:ee,margin:0,lineHeight:"1.5"},children:Et})]});if(I){const se=Be&&(Be.status==="success"||Be.status==="failed")?[{asset:{symbol:ne?.asset?.symbol||s.symbol,address:ne?.asset?.address||""},amount:Fe,txHash:Be.txHash||"",success:Be.status==="success",error:Be.status==="failed"?Be.error:void 0}]:void 0;return e.jsx(Mt,{isOpen:t,onClose:n,title:Oe,subtitle:pt,styles:g,dark:z,footerLinkText:"Spicenet accounts \u2192",children:e.jsxs("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[m&&e.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:e.jsxs("button",{onClick:m,style:{background:"none",border:"none",cursor:"pointer",padding:0,display:"flex",alignItems:"center",gap:"4px",color:C,fontSize:"12px",fontWeight:500,fontFamily:T,textDecoration:"underline",textUnderlineOffset:"2px"},children:["Add Funds",e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:C,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(dn,{assets:Ee,selectedAsset:ne??void 0,onAssetSelect:gt,onAmountChange:()=>{},label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:ne?.asset?mt?xt?"...":nt?`~${parseFloat(Q.formatUnits(nt.amountIn,ne.asset.decimals)).toFixed(6)}`:void 0:Fe??void 0:void 0,dark:z,theme:O,styles:g})}),e.jsx(Ws,{variant:"pay",destinationSymbol:s.symbol,destinationLogoURI:s.logoURI,destinationDecimals:s.decimals,primaryColor:C,fontFamily:T,textPrimary:M,textSecondary:ee,cardBg:$,cardBorder:L,dk:k,dark:z,isQuoting:xt,quoteError:vt,estimatedOutput:zt,paymentAmount:Fe,needsSwap:mt,exactOutputSwap:nt,adjustable:y==="adjustable",maxAmount:f,onAmountChange:ie}),E&&e.jsx("div",{style:{marginBottom:"12px",padding:"10px 14px",backgroundColor:P.errorBg,border:`1px solid ${P.errorBorder}`,borderRadius:"6px"},children:e.jsx("p",{style:{color:P.errorText,fontSize:"13px",margin:0,fontFamily:T},children:E})}),e.jsx(De.Button,{variant:"outline",fullWidth:!0,onClick:_e,disabled:!Ft,loading:G,dark:z,styles:{button:{backgroundColor:C}},children:de}),Be&&Ze&&e.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:z?k.shell:"white",borderRadius:z?"12px":"6px",padding:"16px 0"},children:e.jsx(gn,{type:"payment",isOpen:Be.status!=="processing",isProcessing:G||Be.status==="processing",closeOnComplete:!1,chainName:H.getChainName(R),explorerUrl:H.getExplorerUrl(R,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{lt(!1),Xe(null),_e()},onNewTx:jt,onClose:()=>{lt(!1),Xe(null)},onComplete:jt,results:se,styles:g,dark:z})})]})})}return e.jsxs(Mt,{isOpen:t,onClose:n,title:Oe,subtitle:pt,dark:z,styles:g,theme:v,children:[e.jsx("div",{style:{marginBottom:"16px"},children:e.jsx(dn,{assets:Ee,selectedAsset:ne||void 0,onAssetSelect:gt,onAmountChange:Bt,disabled:G||_==="success",showBalance:!0,showMaxButton:!0,label:"From Spice Balance",placeholder:"0.00",theme:O,styles:g,dark:F,maxAmount:bt>0?bt.toString():void 0})}),ne?.asset&&!ut&&e.jsx(Ws,{variant:"supply",destinationSymbol:s.symbol,destinationLogoURI:s.logoURI,destinationDecimals:s.decimals,primaryColor:C,fontFamily:T,textPrimary:M,textSecondary:ee,cardBg:$,cardBorder:L,dark:z,isQuoting:xt,quoteError:vt,estimatedOutput:zt}),_!=="idle"&&e.jsxs("div",{style:{padding:"10px 14px",borderRadius:"10px",marginBottom:"16px",backgroundColor:_==="success"?P.successBg:_==="error"?P.errorBg:$,border:`1px solid ${_==="success"?P.successBorder:_==="error"?P.errorBorder:L}`},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[_==="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:P.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):_==="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:P.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):e.jsx(De.Spinner,{size:14,color:C}),e.jsx("span",{style:{fontSize:"13px",fontWeight:500,color:_==="success"?P.successText:_==="error"?P.errorText:M,fontFamily:T,flex:1},children:_==="success"?"Transaction successful!":_==="error"?A||"Transaction failed":qs[_]||A}),_==="success"&&re&&e.jsx("a",{href:`${Gt}/tx/${re}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:C,fontFamily:T,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),_==="error"&&e.jsx("button",{onClick:()=>{fe("idle"),N(null),setTimeout(ct,50)},style:{background:"none",border:"none",fontSize:"12px",color:C,fontFamily:T,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),Zt>=0&&_!=="success"&&_!=="error"&&e.jsx("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${ee}22`,overflow:"hidden"},children:e.jsx("div",{style:{height:"100%",borderRadius:"2px",backgroundColor:C,width:`${(Zt+1)/Xs.length*100}%`,transition:"width 400ms ease"}})})]}),E&&_==="idle"&&e.jsx("div",{style:{padding:"10px 14px",borderRadius:"10px",backgroundColor:P.errorBg,border:`1px solid ${P.errorBorder}`,marginBottom:"16px"},children:e.jsx("p",{style:{fontSize:"13px",color:P.errorText,margin:0,fontFamily:T},children:E})}),e.jsx(De.Button,{variant:"outline",fullWidth:!0,disabled:Ue,onClick:Te,style:{height:"56px",backgroundColor:Ue?`${Z}66`:_==="success"?P.successBg:Z,color:_==="success"?P.successText:te,border:`1px solid ${_==="success"?P.successBorder:Dt}`,fontSize:"14px",fontWeight:700,letterSpacing:"2px",fontFamily:'"IBM Plex Mono", monospace',boxShadow:Ue?"none":`3px 3px 0px ${Rt}, 4px 4px 0px ${Dt}`,cursor:Ue?"not-allowed":"pointer",opacity:Ue?.6:1},children:K})]})},Ur=t=>e.jsx(Gs,{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}),zr=({label:t="Export Wallet",style:n,className:s,onExport:a,onError:i})=>{const[l,r]=o.useState(!1),[c,d]=o.useState(!1),{primaryColor:h}=V.useSpiceBrand(),u=o.useContext(V.SpiceFlowProviderContext),{isAuthenticated:x}=Ht();let y=null;try{y=Nt.usePrivy()}catch{}let p=null,f=null;try{p=hn.useEmbeddedReveal(),f=hn.useDynamicContext()}catch{p=null,f=null}const w=Vt.getDynamicEmbeddedWallet(f),g=o.useCallback(async()=>{if(!x){i?.("User is not authenticated. Please log in first.");return}try{if(u?.provider==="dynamic"){if(!p||!w){i?.("Dynamic is not available. Ensure the app is wrapped in a DynamicContextProvider.");return}await p.initExportProcess(!1),a?.();return}if(!y){i?.("Privy is not available. Ensure the app is wrapped in a PrivyProvider.");return}await y.exportWallet(),a?.()}catch(b){const m=b instanceof Error?b.message:"Failed to export wallet";console.error("Export wallet error:",b),i?.(m)}},[w,p,x,i,a,y,u?.provider]),S=!x,D={padding:"10px 20px",borderRadius:"8px",fontFamily:'"IBM Plex Mono", monospace',fontSize:"14px",fontWeight:500,letterSpacing:"0.4px",textTransform:"uppercase",cursor:S?"not-allowed":"pointer",opacity:S?.5:1,border:"1px solid #0e0d0b",color:"#0e0d0b",backgroundColor:c?`${h}cc`:l?`${h}ee`:h,transition:"all 150ms ease",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"8px",...n};return e.jsxs("button",{onClick:g,onMouseEnter:()=>r(!0),onMouseLeave:()=>{r(!1),d(!1)},onMouseDown:()=>d(!0),onMouseUp:()=>d(!1),disabled:S,className:s,style:D,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 Js(t){const n=o.useContext(V.SpiceFlowProviderContext),s=Pt(),a=t?.enabled===!1?void 0:s,i=n?.network?{network:n.network,pollIntervalMs:t?.pollIntervalMs,chainIds:t?.chainIds??n.supportedChainIds}:void 0;return{...ks(a,i),embeddedWalletAddress:s}}const Lr=({appName:t,status:n,statusLabel:s,totalUsdValue:a,breakdownSubtitle:i,address:l,dk:r,dark:c=!1,showModeToggle:d,isEmbeddedMode:h=!0,onModeToggle:u})=>{const[x,y]=o.useState(!1),p=async()=>{l&&await vo(l)&&(y(!0),setTimeout(()=>y(!1),2e3))},f=n==="active",w=s||(f?"Active":"Inactive"),g=f?"#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:h?"#22c55e":"#f59e0b"}}),e.jsx("span",{children:h?"Embedded":"External"})]}):e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:c?r.hoverBg:f?"#ecfdf5":"#f3f4f6",border:c?`1px solid ${r.cardBorder}`:f?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[e.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:g}}),e.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:c?r.textSecondary:f?"#065f46":"#6b7280"},children:w})]})]}),e.jsx("div",{style:{fontSize:"28px",fontWeight:700,color:c?r.textPrimary:"#111827",lineHeight:1.2,marginBottom:"2px"},children:ln(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:wo(l)}),e.jsx("button",{onClick:p,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"})]})]})},Pr=({pendingDeposits:t,onCompleteDeposit:n,dk:s,dark:a=!1})=>t.length===0?null:e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:a?s.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=H.getChainConfig(i.chainId)?.displayName||`Chain ${i.chainId}`;return e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:a?s.warningBg:"#fffbeb",border:a?`1px solid ${s.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?s.hoverBg:"#fde68a",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:a?s.warningText:"#92400e"},children:i.tokenSymbol.charAt(0)}),e.jsxs("div",{children:[e.jsxs("div",{style:{fontSize:"13px",fontWeight:500,color:a?s.textPrimary:"#111827"},children:[i.amount," ",i.tokenSymbol]}),e.jsxs("div",{style:{fontSize:"11px",color:a?s.warningText:"#92400e"},children:["on ",r]})]})]}),e.jsx("button",{onClick:()=>n?.(i),style:{padding:"4px 12px",fontSize:"11px",fontWeight:600,backgroundColor:a?s.hoverBg:"#fef3c7",color:a?s.textPrimary:"#92400e",border:a?`1px solid ${s.warningBorder}`:"1px solid #fde68a",borderRadius:"9999px",cursor:"pointer",transition:"all 150ms ease"},children:"Complete"})]},`${i.tokenAddress}-${i.chainId}-${l}`)})})]}),Hr=({spiceAssets:t,loading:n,dk:s,dark:a=!1})=>{const i={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:a?s.textSecondary:"#6b7280",marginBottom:"8px",textTransform:"uppercase"},l={backgroundColor:a?s.cardBg:"#f9fafb",border:a?`1px solid ${s.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return n?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?s.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=H.getChainConfig(r.chainId),h=r.chainDisplayName||d?.displayName||`Chain ${r.chainId}`,u=r.tokenDisplaySymbol||r.tokenDisplayName||r.tokenSymbol;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?s.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:a?s.textSecondary:"#6b7280"},children:u.charAt(0)}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:a?s.textPrimary:"#111827"},children:u}),e.jsx("div",{style:{fontSize:"11px",color:a?s.textSecondary:"#9ca3af"},children:h})]})]}),e.jsxs("div",{style:{textAlign:"right"},children:[e.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:a?s.textPrimary:"#111827"},children:$t(r.balanceFormatted)}),e.jsx("div",{style:{fontSize:"11px",color:a?s.textSecondary:"#9ca3af"},children:ln(r.usdValue)})]})]},`${r.tokenAddress}-${r.chainId}-${c}`)})})]})},Or=({section:t,dk:n,dark:s=!1})=>{const a=i=>{switch(i){case"green":return"#10b981";case"red":return"#ef4444";default:return s?n.textPrimary:"#111827"}};return e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:s?n.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:s?n.cardBg:"#f9fafb",border:s?`1px solid ${n.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:s?n.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",fontWeight:600,color:s?n.textSecondary:"#6b7280"},children:i.tokenSymbol.charAt(0)}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:s?n.textPrimary:"#111827"},children:i.tokenSymbol}),e.jsx("div",{style:{fontSize:"11px",color:s?n.textSecondary:"#6b7280"},children:i.label})]})]}),e.jsx("div",{style:{fontSize:"13px",fontWeight:600,color:a(i.valueColor)},children:i.displayValue})]},l))})]})},Vr=({onDepositClick:t,onWithdrawClick:n,depositDisabled:s=!1,withdrawDisabled:a=!1,primaryColor:i="#EA4B4B",dark:l=!1})=>!t&&!n?null:e.jsxs("div",{style:{display:"flex",gap:"8px"},children:[t&&e.jsx(De.Button,{variant:"outline",onClick:t,disabled:s,dark:l,styles:{button:{backgroundColor:i}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),n&&e.jsx(De.Button,{variant:"outline",onClick:n,disabled:a,dark:l,styles:{button:{backgroundColor:i}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),Qr=({appName:t,status:n,statusLabel:s,totalUsdValue:a,breakdownSubtitle:i,address:l,spiceAssets:r,spiceAssetsLoading:c,pendingDeposits:d,customSections:h,onDepositClick:u,onWithdrawClick:x,onCompleteDeposit:y,primaryColor:p,dk:f,dark:w=!1,showModeToggle:g,isEmbeddedMode:S,onModeToggle:D})=>{const[b,m]=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(Lr,{appName:t,status:n,statusLabel:s,totalUsdValue:a,breakdownSubtitle:i,address:l,dk:f,dark:w,showModeToggle:g,isEmbeddedMode:S,onModeToggle:D}),e.jsx("div",{style:{height:"1px",backgroundColor:w?"#2d2d2d":"#e5e7eb"}}),e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>m(!b),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:w?f.cardBg:"#f9fafb",border:w?`1px solid ${f.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:w?f.textSecondary:"#6b7280",fontSize:"12px",fontWeight:500},children:[e.jsx("span",{children:"How It Works"}),e.jsx("span",{style:{transform:b?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),b&&e.jsxs("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:w?f.cardBg:"#f0fdf4",border:w?`1px solid ${f.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:w?f.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(Pr,{pendingDeposits:d,onCompleteDeposit:y,dk:f,dark:w}),e.jsx(Hr,{spiceAssets:r,loading:c,dk:f,dark:w}),h.map((B,U)=>e.jsx(Or,{section:B,dk:f,dark:w},U)),e.jsx(Vr,{onDepositClick:u,onWithdrawClick:x,primaryColor:p,dark:w})]})},es=380,un=8,Yr=({appName:t="Spice",status:n="active",statusLabel:s,customSections:a=[],extraAssets:i=[],tokenPrices:l={},breakdownLabels:r=[],supportedChains:c,styles:d,dark:h=!1,onDepositSuccess:u,onDepositClick:x,onWithdrawClick:y,onCompleteDeposit:p,showModeToggle:f=!1,defaultMode:w})=>{const g=o.useContext(V.SpiceFlowProviderContext),S=g?.mode!=="7702";o.useEffect(()=>{w&&g?.setMode&&g.setMode(w==="non7702"?"ondemand":"7702")},[g,w]);const[D,b]=o.useState(!1),[m,B]=o.useState(null),[U,I]=o.useState({top:0,left:0,placement:"below"}),v=o.useRef(null),z=o.useRef(null),{address:C,isConnected:k}=Ht(),P=Pt(),{address:T}=qe.useAccount(),{dark:F,primaryColor:M,dk:ee}=V.useSpiceBrand(d,h),$=o.useMemo(()=>c||Y.getChainIdsByNetwork("mainnet"),[c]),{assets:L,loading:Z}=an({address:C,supportedChains:$,enabled:!!C&&!S,refetchInterval:3e4}),te=o.useMemo(()=>[...S?[]:L.map(oe=>{const Ee=oe.balanceUsd||0,ne=Number(oe.balance)/Math.pow(10,oe.decimals),le=Ee>0?Ee:(l[oe.symbol]||0)*ne;return{tokenAddress:oe.address,tokenSymbol:oe.symbol,tokenDisplaySymbol:Pn(oe),tokenDisplayName:ko(oe),tokenDecimals:oe.decimals,chainId:oe.chainId,chainDisplayName:Hn(oe),balance:oe.balance.toString(),balanceFormatted:oe.balanceFormatted,usdValue:le,logoURI:oe.logoURI}}),...i].filter(oe=>oe.balanceFormatted>0),[S,L,l,i]),O=o.useMemo(()=>te.reduce((oe,Ee)=>oe+Ee.usdValue,0),[te]),{pendingDeposits:R}=Js({chainIds:$,enabled:!!C}),ae=o.useMemo(()=>a.reduce((oe,Ee)=>oe+Ee.totalValue,0),[a]),ye=O+ae,ke=o.useMemo(()=>{const oe=[];O>0&&oe.push(`${ln(O)} idle`);for(const Ee of a){const ne=r.find(le=>le.sectionTitle===Ee.title)?.label||Ee.title.toLowerCase();oe.push(`${ln(Ee.totalValue)} ${ne}`)}return oe.join(" \xB7 ")},[O,a,r]),he=o.useCallback(oe=>{p?p(oe):B(oe)},[p]),ge=o.useCallback(()=>{B(null)},[]),be=o.useCallback(()=>{B(null),u?.()},[u]),Me=o.useCallback(()=>{if(!v.current)return;const oe=v.current.getBoundingClientRect(),Ee=window.innerHeight-oe.bottom-un,ne=oe.top-un,le=Ee>=400||Ee>=ne?"below":"above",Je=Math.max(un,Math.min(oe.right-es,window.innerWidth-es-un)),Ye=le==="below"?oe.bottom+un:oe.top-un;I({top:Ye,left:Je,placement:le})},[]);o.useLayoutEffect(()=>{D&&Me()},[D,Me]),o.useEffect(()=>{if(!D)return;const oe=le=>{v.current&&!v.current.contains(le.target)&&z.current&&!z.current.contains(le.target)&&b(!1)},Ee=le=>{le.key==="Escape"&&b(!1)},ne=()=>Me();return document.addEventListener("mousedown",oe),document.addEventListener("keydown",Ee),window.addEventListener("scroll",ne,{passive:!0}),window.addEventListener("resize",Me),()=>{document.removeEventListener("mousedown",oe),document.removeEventListener("keydown",Ee),window.removeEventListener("scroll",ne),window.removeEventListener("resize",Me)}},[D,Me]);const Se=g?.mode==="7702",Ve=Se?P||C:T||C,me=o.useCallback(()=>{g?.setMode&&g.setMode(Se?"ondemand":"7702")},[g,Se]);if(typeof window>"u")return null;const Ne=e.jsxs("button",{ref:v,onClick:()=>b(!D),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:F?ee.hoverBg:"#ffffff",border:F?`1px solid ${ee.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:'"Helvetica Neue", sans-serif',color:F?ee.textPrimary:"#111827",transition:"all 150ms ease",boxShadow:F?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[e.jsx("span",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:M,flexShrink:0}}),e.jsxs("span",{children:[t," Account"]}),k&&e.jsxs("span",{style:{color:F?ee.textSecondary:"#6b7280"},children:["\xB7 ",ln(ye)]}),e.jsx("span",{style:{fontSize:"10px",color:F?ee.textSecondary:"#9ca3af",transform:D?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),Le=D?Bn.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:9998},onClick:()=>b(!1)}),e.jsx("div",{ref:z,style:{position:"fixed",top:U.placement==="below"?`${U.top}px`:"auto",bottom:U.placement==="above"?`${window.innerHeight-U.top}px`:"auto",left:`${U.left}px`,width:`${es}px`,maxHeight:"80vh",backgroundColor:F?ee.shell:"#ffffff",border:F?`1px solid ${ee.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:F?"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(Qr,{appName:t,status:n,statusLabel:s,totalUsdValue:ye,breakdownSubtitle:ke,address:f?Ve:C,spiceAssets:te,spiceAssetsLoading:Z,pendingDeposits:R,customSections:a,onDepositClick:x,onWithdrawClick:y,onCompleteDeposit:he,primaryColor:M,dk:ee,dark:F,showModeToggle:f,isEmbeddedMode:Se,onModeToggle:me})}),e.jsx("style",{children:`
|
|
114
|
+
`})]})},Sr=({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})]}),Ir=({isOpen:t,onClose:n,lockBatches:s,lockTokenSymbol:a,lockTokenLogoURI:i,destinationInputHook:l,sourceAssetInputHook:r,lockDurationHook:c,lockChainId:d,durationOptions:h,votingPowerEstimate:u,sourceChains:x,sourceAssets:y=[],escrowAddress:p,includeWalletAssets:f=!1,destinationTokenAddress:w,onLockSuccess:g,onLockExecute:S,sourceToDestinationConversionRate:D,estimatedOutputAmount:b,onAddFunds:m,styles:B,dark:U=!1})=>{const{theme:I,dark:v,primaryColor:z,dk:C}=V.useSpiceBrand(B,U),k=I.typography.fontFamily,P=o.useContext(V.SpiceFlowProviderContext),T=(P?.mode||"7702")!=="7702",F=v?C.cardBg:B?.assetSelector?.backgroundColor||B?.secondaryBackground||"#e9e9e9",M=v?`1px solid ${C.cardBorder}`:"0.5px solid #A8A8A7",ee=v?"12px":"6px",$=v?C.textPrimary:"#111827",L=v?C.textSecondary:"#6b7280",Z=o.useMemo(()=>({...B,assetSelector:{...B?.assetSelector,backgroundColor:v?C.cardBg:B?.assetSelector?.backgroundColor,borderRadius:v?"12px":B?.assetSelector?.borderRadius},secondaryBackground:v?C.cardBg:B?.secondaryBackground}),[B,v]),te=o.useMemo(()=>v?{...I,colors:{...I.colors,secondary:C.cardBg,surfaceHover:C.hoverBg,border:C.cardBorder,borderHover:C.inputBorder}}:I,[v,I]),[O,R]=o.useState(null),[ae,ye]=o.useState(0),ke=c?.selectedDurationIdx??ae,he=c?.setSelectedDurationIdx??ye,[ge,be]=o.useState(!1),[Me,Se]=o.useState(null),[Ve,me]=o.useState(!1),[Ne,Le]=o.useState(!1),[oe,Ee]=o.useState(null);qe.useWalletClient(),qe.useSwitchChain();const{chain:ne,address:le}=qe.useAccount();qe.useConfig();const Je=o.useRef(ne);o.useEffect(()=>{Je.current=ne},[ne]);const Ye=Ht(),{isReady:G,isAuthenticated:xe,isConnected:E,address:N,provider:_,actions:fe}=Ye,{externalWallet:A,embeddedAddress:q}=Yn(),{intentStatus:re,startStatusPolling:ue,clearStatus:Ze}=Un({checkStepStatus:(K,de)=>V.relayerService.checkStepStatus(K,de),retryStep:async(K,de)=>{const[Te,Ue]=K.split("/"),Oe=parseInt(Ue||"0",10);await V.relayerService.executeStep(Te,Oe,de,{action:"execute"})},maxRetries:3}),{assets:lt,refetch:Be}=an({address:N,supportedChains:x,enabled:E&&!T,refetchInterval:3e4}),Xe=o.useMemo(()=>{if(y.length===0)return lt;const K=new Set(y.map(de=>de.toLowerCase()));return lt.filter(de=>K.has(de.address.toLowerCase()))},[lt,y]),ve=Pt(),rt=T?le:ve,ht=o.useMemo(()=>{if(!f)return[];const K=new Set,de=[],Te=Ue=>{if(!Ue)return;const Oe=Ue.toLowerCase();K.has(Oe)||(K.add(Oe),de.push(Q.getAddress(Ue)))};if(w&&Te(w),T)for(const Ue of y)Te(Ue);return de},[f,T,w,y]),Fe=o.useMemo(()=>ht.map(K=>K.toLowerCase()).sort().join(","),[ht]),Ct=o.useMemo(()=>JSON.stringify([...x||[]].sort()),[x]),[xt,vt]=o.useState([]),zt=o.useRef(0),It=o.useCallback(async()=>{if(!f||!rt||ht.length===0){zt.current++,vt([]);return}const K=++zt.current,de=Q.getAddress(rt),Te=x&&x.length>0?x:[d],Ue=ht.map(ce=>{const Ce=ce.toLowerCase();for(const Ie of Te){const Re=H.getChainConfig(Ie)?.supportedTokens?.find(Ae=>Ae.address.toLowerCase()===Ce);if(Re)return{address:ce,chainId:Ie,configToken:{decimals:Re.decimals,symbol:Re.symbol,name:Re.name,logo:Re.logo}}}return{address:ce,chainId:d}}),Oe=new Map;for(const ce of Ue){const Ce=Oe.get(ce.chainId)||[];Ce.push(ce),Oe.set(ce.chainId,Ce)}const pt=async(ce,Ce)=>{try{const Ie=await Qt.readContract(ce,{address:Ce.address,abi:H.T,functionName:"balanceOf",args:[de]});let Re,Ae,We,we;if(Ce.configToken)Re=Ce.configToken.decimals,Ae=Ce.configToken.symbol,We=Ce.configToken.name,we=Ce.configToken.logo;else{const[j,J,je]=await Promise.all([Qt.readContract(ce,{address:Ce.address,abi:H.T,functionName:"decimals",args:[]}).catch(()=>18),Qt.readContract(ce,{address:Ce.address,abi:H.T,functionName:"symbol",args:[]}).catch(()=>"TOKEN"),Qt.readContract(ce,{address:Ce.address,abi:H.T,functionName:"name",args:[]}).catch(()=>"TOKEN")]);Re=Number(j),Ae=J,We=je}const W=!!w&&Ce.address.toLowerCase()===w.toLowerCase()&&Ce.chainId===d;W&&i&&(we=i),W&&a&&!Ce.configToken&&(Ae==="TOKEN"&&(Ae=a),We==="TOKEN"&&(We=a));const X=parseFloat((Number(Ie)/Math.pow(10,Re)).toFixed(6));return{address:Ce.address,name:We,symbol:Ae,decimals:Re,balance:Ie,balanceFormatted:X,balanceUsd:0,logoURI:we,isNative:!1,chainId:Ce.chainId}}catch{return null}},se=await Promise.all(Array.from(Oe.entries()).map(async([ce,Ce])=>{let Ie;try{Ie=H.getClientForChain(ce)}catch{return[]}const Re=[],Ae=[];for(const we of Ce){const W=Re.length;Re.push({address:we.address,abi:H.T,functionName:"balanceOf",args:[de]}),we.configToken||Re.push({address:we.address,abi:H.T,functionName:"decimals",args:[]},{address:we.address,abi:H.T,functionName:"symbol",args:[]},{address:we.address,abi:H.T,functionName:"name",args:[]}),Ae.push({start:W,item:we})}let We=null;try{We=await Ie.multicall({contracts:Re})}catch{We=null}return We?Ae.map(({start:we,item:W})=>{const X=We[we],j=X?.status==="success"?X.result:0n;let J,je,et,tt;if(W.configToken)J=W.configToken.decimals,je=W.configToken.symbol,et=W.configToken.name,tt=W.configToken.logo;else{const Qe=We[we+1],st=We[we+2],ot=We[we+3];J=Qe?.status==="success"?Number(Qe.result):18,je=st?.status==="success"?st.result:"TOKEN",et=ot?.status==="success"?ot.result:je}const ze=!!w&&W.address.toLowerCase()===w.toLowerCase()&&W.chainId===d;ze&&i&&(tt=i),ze&&a&&!W.configToken&&(je==="TOKEN"&&(je=a),et==="TOKEN"&&(et=a));const it=parseFloat((Number(j)/Math.pow(10,J)).toFixed(6));return{address:W.address,name:et,symbol:je,decimals:J,balance:j,balanceFormatted:it,balanceUsd:0,logoURI:tt,isNative:!1,chainId:W.chainId}}):(await Promise.all(Ce.map(we=>pt(Ie,we)))).filter(we=>we!==null)}));K===zt.current&&vt(se.flat())},[f,rt,Fe,Ct,d,w,i,a]);o.useEffect(()=>{if(!f){vt([]);return}It();const K=setInterval(()=>{It()},15e3);return()=>clearInterval(K)},[It,f]);const nt=o.useCallback(()=>{It()},[It]),At=o.useMemo(()=>xt.filter(K=>K.balance>0n),[xt]),kt=o.useMemo(()=>{if(T)return At.map(de=>({...de,_source:"wallet"}));if(!f)return Xe;const K=[];for(const de of At)K.push({...de,_source:"wallet"});for(const de of Xe)K.push({...de,_source:"spice"});return K},[T,f,At,Xe]),ut=o.useRef(null),mt=o.useRef(null);o.useEffect(()=>{mt.current=O},[O]),o.useEffect(()=>{t||(R(null),Se(null),be(!1),Le(!1),Ee(null),me(!1),Ze())},[t,Ze]),o.useEffect(()=>{l&&l.assetAmount!==(O?.amount||"")&&R(K=>K&&{...K,amount:l.assetAmount})},[l?.assetAmount]),o.useEffect(()=>{r&&r.assetAmount!==(O?.amount||"")&&R(K=>K&&{...K,amount:r.assetAmount})},[r?.assetAmount]),o.useEffect(()=>{if(!T&&re?.overallStatus==="success"&&re.intentId&&ut.current!==re.intentId&&N&&re.steps.find(K=>K.transactionHash)?.transactionHash){ut.current=re.intentId;const K=mt.current;if(!K?.asset||!K.amount||K.asset._source==="wallet"||Q.parseUnits(K.amount,K.asset.decimals)===0n)return;Be()}},[re,N,d,Be,T]);const Ge=parseFloat(O?.amount||"")||0,dt=o.useMemo(()=>O?.asset?O.asset._source==="wallet"?O.asset.balanceFormatted??0:Xe.find(K=>K.address.toLowerCase()===O.asset.address.toLowerCase()&&K.chainId===O.asset.chainId)?.balanceFormatted??0:0,[O?.asset,Xe]),bt=Ge>0&&Ge>dt,ft=c?.selectedDuration??h[ke]??h[0],gt=o.useMemo(()=>!O?.asset||!w?!1:O.asset.address.toLowerCase()===w.toLowerCase()&&O.asset.chainId===d,[O?.asset,w,d]),Bt=o.useMemo(()=>Ge<=0?0:gt?Ge:!D||D<=0?0:Ge/D,[Ge,D,gt]),ie=o.useMemo(()=>Bt<=0?null:Bt.toLocaleString(void 0,{maximumFractionDigits:2}),[Bt]),pe=u&&Bt>0&&ft?u(Bt,ft.months):void 0,Pe=o.useMemo(()=>Ge<=0?"$0.00":gt&&D?(Ge*D).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!D||D<=0?"$0.00":Ge.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[Ge,D,gt]),$e=o.useMemo(()=>{if(!ie)return null;const K=parseFloat(ie.replace(/,/g,""));return gt&&D?(K*D).toLocaleString(void 0,{maximumFractionDigits:2}):D?(K*D).toLocaleString(void 0,{maximumFractionDigits:2}):null},[ie,D,gt]),at=o.useCallback(K=>{R(de=>({asset:K,amount:de?.asset?.address===K.address&&de?.asset?.chainId===K.chainId&&de.amount||""})),Se(null),r?.setSelectedAsset&&r.setSelectedAsset({symbol:K.symbol,address:K.address,decimals:K.decimals,chainId:K.chainId})},[r?.setSelectedAsset]),ct=o.useCallback(K=>{R(de=>de&&{...de,amount:K}),Se(null),l&&l.setAssetAmount(K),r&&r.setAssetAmount(K)},[l,r]),_e=o.useCallback(()=>{if(typeof s=="function"){if(!O?.asset||!O.amount)throw new Error("Select an asset and enter an amount");return s({asset:O.asset,amount:O.amount,amountWei:Q.parseUnits(O.amount,O.asset.decimals)})}return s},[s,O]),Ke=o.useCallback(async()=>{const K=T&&q||N;if(!E||!K)throw new Error("Please connect your wallet to continue");const de=_e();if(de.length===0)throw new Error("No lock batches configured");if(!G||!xe)throw new Error(`Please authenticate with ${_||"wallet provider"} to continue`);const Te=[...de],Ue=[...new Set(Te.map(we=>we.chainId))],Oe=[];for(const we of Ue){const W=H.getClientForChain(we),X=H.getDelegateContractAddress(we),j=await Y.getAccountNonce(K,W),J=await fe.signAuthorization({contractAddress:X,chainId:we,nonce:Number(j)});Oe.push(J)}const pt=Y.hashChainBatches(Te),se=Math.floor(Date.now()/1e3)+60*10,ce=pt.map(we=>we.hash),Ce=Q.keccak256(Q.encodeAbiParameters([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,BigInt(se),ce])),Ie=await fe.signMessage({raw:Ce}),Re=typeof Ie=="string"?Ie:Ie.signature;if(!Re)throw new Error("Failed to sign intent authorization");const Ae={mode:"7702",signatureType:"ecdsa",signature:Re,nbf:0,exp:se,chainBatches:pt.map((we,W)=>({hash:we.hash,chainId:we.chainId,tokenTransfers:Te[W].tokenTransfers??[],calls:we.calls}))},We=await V.relayerService.createAction({user:K,chainAuthorizations:Oe.map(we=>({r:we.r,s:we.s,yParity:we.yParity,address:we.address,chainId:Number(we.chainId),nonce:Number(we.nonce)})),intents:[Ae]});if(We){const we=V.createInitialSteps(Te,H.getChainName),[W,X]=We.intentIds[0].split("/"),j=parseInt(X||"0",10);ue(We.intentIds[0],we);for(let J=0;J<Te.length;J++)await ls(()=>V.relayerService.executeStep(W,j,J,{action:"execute"}))}},[_e,Ye,ue,T,q]),St=o.useCallback(async()=>{if(!O?.asset||!O.amount)throw new Error("Select an asset and enter an amount");if(!N||!ve)throw new Error("Embedded wallet not connected");const K=O.asset,de=Q.parseUnits(O.amount,K.decimals),Te=p||H.getDelegateContractAddress(d),Ue=await fe.getEthereumProvider();await Ue.request({method:"wallet_switchEthereumChain",params:[{chainId:`0x${d.toString(16)}`}]});const Oe=H.getChainConfig(d),pt=Q.createWalletClient({account:ve,transport:Q.custom(Ue),chain:Oe?.viemChain});let se;if(K.isNative||Y.isNativeToken(K.address))se=await pt.sendTransaction({to:Te,value:de,chain:Oe?.viemChain});else{const ce=Q.encodeFunctionData({abi:H.T,functionName:"transfer",args:[Te,de]});se=await pt.sendTransaction({to:K.address,data:ce,chain:Oe?.viemChain})}if((await H.getClientForChain(d).waitForTransactionReceipt({hash:se,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to escrow failed");await Be(),nt(),await Ke()},[O,N,ve,fe,p,d,Ke,Be,nt]),jt=o.useCallback(async()=>{if(!O?.asset||!O.amount)throw new Error("Select an asset and enter an amount");if(!le||!A)throw new Error("Please connect your external wallet to continue");if(!(ve||q))throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");if(S){const Re=_e();if(Re.length===0)throw new Error("No lock batches configured");const Ae=O.asset,We=Q.parseUnits(O.amount,Ae.decimals),we=await S({asset:Ae,amount:O.amount,amountWei:We,lockDurationMonths:ft?.months??0,chainBatches:Re});we&&g?.(we);return}const K=O.asset,de=Q.parseUnits(O.amount,K.decimals),Te=K.chainId,Ue=p||Y.ESCROW_ADDRESS,Oe=await A.getEthereumProvider();let pt=null;try{const Re=await Oe.request({method:"eth_chainId"});pt=parseInt(Re,16)}catch{pt=null}if(pt!==Te)try{await Oe.request({method:"wallet_switchEthereumChain",params:[{chainId:`0x${Te.toString(16)}`}]})}catch(Re){if(Re?.code===4902||Re?.message?.includes("Unrecognized chain ID")){const Ae=H.getChainConfig(Te);Ae&&await Oe.request({method:"wallet_addEthereumChain",params:[{chainId:`0x${Te.toString(16)}`,chainName:Ae.name||`Chain ${Te}`,nativeCurrency:Ae.nativeCurrency||{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:[Ae.rpcUrl],blockExplorerUrls:Ae.blockExplorer?[Ae.blockExplorer]:void 0}]})}else throw Re}const se=H.getChainConfig(Te),ce=Q.createWalletClient({account:le,chain:se?.viemChain,transport:Q.custom(Oe)}),Ce=Y.normalizeNativeTokenAddress(K.address),Ie=K.isNative||Y.isNativeToken(Ce)?await ce.sendTransaction({to:Ue,value:de,chain:se?.viemChain}):await ce.sendTransaction({to:Ce,data:Q.encodeFunctionData({abi:H.T,functionName:"transfer",args:[Ue,de]}),chain:se?.viemChain});if((await H.getClientForChain(Te).waitForTransactionReceipt({hash:Ie,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Escrow deposit failed");await Ke()},[O,A,le,ve,q,p,S,_e,ft,g,Ke]),Ft=o.useCallback(async()=>{if(!O?.asset||!O.amount)throw new Error("Select an asset and enter an amount");if(!le||!A)throw new Error("Please connect your external wallet to continue");const K=_e();if(K.length===0)throw new Error("No lock batches configured");const de=K.find(Ce=>Ce.chainId===d)||K[0];if(!de)throw new Error("No lock batch for lock chain");const Te=await A.getEthereumProvider();let Ue=null;try{const Ce=await Te.request({method:"eth_chainId"});Ue=parseInt(Ce,16)}catch{Ue=null}if(Ue!==d)try{await Te.request({method:"wallet_switchEthereumChain",params:[{chainId:`0x${d.toString(16)}`}]})}catch(Ce){if(Ce?.code===4902||Ce?.message?.includes("Unrecognized chain ID")){const Ie=H.getChainConfig(d);Ie&&await Te.request({method:"wallet_addEthereumChain",params:[{chainId:`0x${d.toString(16)}`,chainName:Ie.name||`Chain ${d}`,nativeCurrency:Ie.nativeCurrency||{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:[Ie.rpcUrl],blockExplorerUrls:Ie.blockExplorer?[Ie.blockExplorer]:void 0}]})}else throw Ce}const Oe=H.getChainConfig(d),pt=Q.createWalletClient({account:le,chain:Oe?.viemChain,transport:Q.custom(Te)}),se=H.getClientForChain(d);let ce;for(const Ce of de.calls){const Ie=await pt.sendTransaction({to:Ce.to,data:Ce.data,value:Ce.value,chain:Oe?.viemChain});if((await se.waitForTransactionReceipt({hash:Ie,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Lock transaction failed");ce=Ie}ce&&g?.(ce)},[O,A,le,_e,d,g]);o.useEffect(()=>{if(re?.overallStatus==="success"){const K=re.steps.find(de=>de.transactionHash);g?.(K?.transactionHash)}},[re?.overallStatus,g]);const Et=f&&O?.asset?._source==="wallet"&&O?.asset?.chainId===d,Rt=o.useCallback(async()=>{if(!O?.asset||Ge<=0){Se("Select an asset and enter an amount");return}if(bt){Se("Insufficient balance. Add more assets.");return}be(!0),Se(null);const K=de=>{console.error("[SpiceLockModal] lock failed:",de);const Te=Lt(de,""),Ue=typeof de?.shortMessage=="string"?de.shortMessage:typeof de?.message=="string"?de.message:"";Se(Te||Ue||"Transaction failed. Please try again.")};if(T){if(gt){try{await Ft()}catch(de){K(de)}finally{be(!1)}return}me(!0);try{await jt()}catch(de){K(de)}finally{be(!1)}return}me(!0);try{Et&&!gt?await St():await Ke()}catch(de){K(de)}finally{be(!1)}},[O,Ge,bt,T,jt,Ft,Et,gt,St,Ke]),Dt=!!O?.asset&&Ge>0&&!bt&&!ge,Gt=e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[e.jsx(Sr,{color:L}),e.jsxs("p",{style:{fontSize:"13px",color:L,margin:0,lineHeight:"1.5"},children:["Add ",a," by converting assets from your account"]})]});if(!t)return null;const Zt={backgroundColor:F,border:M,borderRadius:ee,padding:"16px",marginBottom:"16px"};return e.jsx(Mt,{isOpen:t,onClose:n,title:`Add ${a} to your account`,subtitle:Gt,styles:B,dark:v,footerLinkText:"Spicenet accounts \u2192",overlayContent:Ne?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:[m&&e.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:e.jsxs("button",{onClick:m,style:{background:"none",border:"none",cursor:"pointer",padding:0,display:"flex",alignItems:"center",gap:"4px",color:z,fontSize:"12px",fontWeight:500,fontFamily:k,textDecoration:"underline",textUnderlineOffset:"2px"},children:["Add Funds",e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:z,strokeWidth:"1.8",children:[e.jsx("circle",{cx:"6",cy:"6",r:"5"}),e.jsx("path",{d:"M6 4v4M4 6h4",strokeLinecap:"round"})]})]})}),e.jsx(dn,{assets:kt,selectedAsset:O??void 0,onAssetSelect:at,onAmountChange:ct,label:"Amount",showBalance:!0,showMaxButton:!0,theme:te,styles:Z}),e.jsx("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:L,fontFamily:k},children:Pe})]}),e.jsxs("div",{style:Zt,children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:v?`1px solid ${C.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:v?C.inputBg:"#d1d5db",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:700,color:$},children:a.slice(0,2)}),e.jsx("span",{style:{fontSize:"16px",fontWeight:600,color:$,fontFamily:k},children:a})]}),e.jsxs("div",{style:{textAlign:"right"},children:[e.jsx("div",{style:{fontSize:"22px",fontWeight:700,color:$,fontFamily:k,lineHeight:1.1},children:ie??"0.00"}),e.jsxs("div",{style:{fontSize:"12px",color:L,fontFamily:k,marginTop:"2px"},children:["~$",$e??"0.00"]})]})]}),e.jsxs("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:v?`1px solid ${C.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:L,fontFamily:k},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:L,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),e.jsx(Cr,{options:h,selectedIndex:ke,onSelect:he,primaryColor:z,dark:v,textPrimary:$,textSecondary:L})]}),e.jsxs("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[e.jsx(wr,{durationMonths:ft?.months,fontFamily:k,dark:v,textPrimary:$,textSecondary:L}),u&&e.jsx(vr,{votes:pe,fontFamily:k,dark:v,textPrimary:$,textSecondary:L})]})]}),Me&&e.jsx("div",{style:{marginBottom:"12px",padding:"10px 14px",backgroundColor:v?"rgba(239,68,68,0.12)":"#fef2f2",border:`1px solid ${v?"rgba(239,68,68,0.3)":"#fecaca"}`,borderRadius:"6px"},children:e.jsx("p",{style:{color:"#ef4444",fontSize:"13px",margin:0,fontFamily:k},children:Me})}),e.jsx(De.Button,{variant:"outline",fullWidth:!0,onClick:Rt,disabled:!Dt,loading:ge,dark:v,styles:{button:{backgroundColor:z}},children:ge?Et&&!gt?"DEPOSITING...":gt?"LOCKING...":"CONVERTING...":Et&&!gt?`DEPOSIT ${a}`:gt?`LOCK ${a}`:`CONVERT TO ${a}`}),e.jsx(kr,{isOpen:Ne,data:oe,isLocking:ge,lockError:Me,onContinue:Rt,onClose:()=>Le(!1),primaryColor:z,fontFamily:k,dark:v}),re&&Ve&&e.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:v?C.shell:"white",borderRadius:ee,padding:"16px 0"},children:e.jsx(gn,{type:"deposit",isOpen:!!re&&re.overallStatus!=="processing",isProcessing:ge||re?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{Ze(),me(!1),Rt()},onNewTx:()=>{Ze(),me(!1),R(null),ut.current=null,Be(),nt()},onClose:()=>{Ze(),me(!1)},onComplete:()=>{Ze(),me(!1),R(null),ut.current=null,Be(),nt()},results:re?.overallStatus==="success"||re?.overallStatus==="failed"?re.steps.map(K=>({asset:{symbol:O?.asset?.symbol||a,address:O?.asset?.address||""},txHash:K.transactionHash||"",success:K.status==="success",amount:O?.amount})):void 0,chainName:H.getChainName(d),explorerUrl:H.getExplorerUrl(d,"").replace(/\/tx\/.*$/,"")||void 0,theme:I,styles:B,dark:v})})]})})},Ws=({variant:t,destinationSymbol:n,destinationLogoURI:s,destinationDecimals:a,primaryColor:i,fontFamily:l,textPrimary:r,textSecondary:c,cardBg:d,cardBorder:h,dk:u,dark:x,isQuoting:y,quoteError:p,estimatedOutput:f,paymentAmount:w,needsSwap:g,exactOutputSwap:S,adjustable:D=!1,maxAmount:b,onAmountChange:m})=>t==="supply"?e.jsx("div",{style:{backgroundColor:d,border:`1px solid ${h}`,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(Ns,{symbol:n,logoURI:s,primaryColor:i,size:28}),e.jsxs("span",{style:{fontSize:"13px",fontWeight:500,color:c,fontFamily:l},children:["Estimated ",n]})]}),e.jsx("div",{style:{textAlign:"right"},children:y?e.jsx("span",{style:{fontSize:"14px",color:c,fontFamily:l},children:"Quoting..."}):p?e.jsx("span",{style:{fontSize:"13px",color:"#ef4444",fontFamily:l},children:"Quote failed"}):f?e.jsxs("span",{style:{fontSize:"16px",fontWeight:600,color:r,fontFamily:l},children:["\u2248 ",f]}):e.jsx("span",{style:{fontSize:"14px",color:c,fontFamily:l},children:"\u2014"})})]})}):e.jsx(jr,{destinationSymbol:n,destinationLogoURI:s,destinationDecimals:a,primaryColor:i,fontFamily:l,textPrimary:r,textSecondary:c,cardBg:d,cardBorder:h,dk:u,dark:x,paymentAmount:w||"0",needsSwap:g,exactOutputSwap:S,isQuoting:y,adjustable:D,maxAmount:b,onAmountChange:m}),Ns=({symbol:t,logoURI:n,primaryColor:s,size:a})=>n?e.jsx("img",{src:n,alt:t,style:{width:a,height:a,borderRadius:"50%",objectFit:"cover"}}):e.jsx("div",{style:{width:a,height:a,borderRadius:"50%",backgroundColor:`${s}22`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:a<30?"11px":"12px",fontWeight:700,color:s},children:t.slice(0,2)}),jr=({destinationSymbol:t,destinationLogoURI:n,destinationDecimals:s,primaryColor:a,fontFamily:i,textPrimary:l,textSecondary:r,cardBg:c,cardBorder:d,dk:h,dark:u,paymentAmount:x,needsSwap:y,exactOutputSwap:p,isQuoting:f,adjustable:w,maxAmount:g,onAmountChange:S})=>{const D='"IBM Plex Mono", monospace',b=parseFloat(x||"0"),m=g?parseFloat(g):0,[B,U]=o.useState(x||""),I=o.useRef(null),[v,z]=o.useState(null),[C,k]=o.useState(null);o.useEffect(()=>{w||U(x||"")},[x,w]);const P=M=>{let ee=M;ee.startsWith(".")&&(ee="0"+ee);const $=is(ee);let L=$;g&&parseFloat($)>parseFloat(g)&&(L=g),U(L),I.current&&clearTimeout(I.current),I.current=setTimeout(()=>S?.(L),300)},T=M=>{if(!m)return;if(M===100){U(g||m.toString()),I.current&&clearTimeout(I.current),S?.(g||m.toString());return}const ee=10**s,$=(Math.floor(m*M/100*ee)/ee).toString();U($),I.current&&clearTimeout(I.current),S?.($)},F=m>0?parseFloat(B||"0")/m*100:0;return o.useEffect(()=>()=>{I.current&&clearTimeout(I.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(Ns,{symbol:t,logoURI:n,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:[w?e.jsx("input",{type:"text",value:B,onChange:M=>P(M.target.value),placeholder:"0.0",style:{fontSize:"20px",fontWeight:700,color:l,fontFamily:D,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:D,lineHeight:1.1},children:b>0?x:"0.00"}),e.jsx("div",{style:{fontSize:"12px",color:r,fontFamily:D,marginTop:"2px"},children:t}),w&&m>0&&e.jsx("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((M,ee)=>{const $=Math.abs(F-M)<1,L=ee===4,Z=M/100,te=v===M,O=C===M;return e.jsx("button",{onClick:()=>T(M),onMouseEnter:()=>z(M),onMouseLeave:()=>{z(null),k(null)},onMouseDown:()=>k(M),onMouseUp:()=>k(null),title:`${M}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:$?1:te?.8:.5,transform:O?"scale(0.85)":te?"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:L?a:"none",stroke:L?a:u?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!L&&Z>0&&e.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${Z>.5?1:0} 1 ${7+6.84375*Math.sin(Z*2*Math.PI)} ${7-6.84375*Math.cos(Z*2*Math.PI)} Z`,fill:u?h?.textSecondary||"#9ca3af":"#3C3E42"})]})},M)})})]})]}),y&&p&&!f&&e.jsx("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:u?`1px solid ${h?.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 ",p.venue]})})]})};function Us(t,n,s){const a=t.address.toLowerCase()===n,i=t.chainId===s,l=t._source==="wallet";return l&&a&&i?0:l&&i?1:!l&&a?2:!l&&i?3:4}function Er(t){const{address:n,destinationToken:s,supportedSourceAssets:a,sourceChains:i,enabled:l}=t,r=Pt(),{assets:c,refetch:d}=an({address:n,supportedChains:i,enabled:l,refetchInterval:3e4}),h=o.useMemo(()=>{if(!a||a.length===0)return c;const p=a.map(f=>f.toLowerCase());return c.filter(f=>p.includes(f.address.toLowerCase()))},[c,a]),[u,x]=o.useState(null);o.useEffect(()=>{if(!s.address||!r||!l){x(null);return}let p=!1;const f=Q.getAddress(s.address),w=Q.getAddress(r),g=H.getClientForChain(s.chainId),S=async()=>{try{const b=await g.multicall({contracts:[{address:f,abi:Q.erc20Abi,functionName:"balanceOf",args:[w]},{address:f,abi:Q.erc20Abi,functionName:"decimals",args:[]},{address:f,abi:Q.erc20Abi,functionName:"symbol",args:[]},{address:f,abi:Q.erc20Abi,functionName:"name",args:[]}]});if(p)return;const m=b[0].status==="success"?b[0].result:0n,B=b[1].status==="success"?Number(b[1].result):s.decimals,U=b[2].status==="success"?b[2].result:s.symbol,I=b[3].status==="success"?b[3].result:s.symbol;m>0n?x({address:f,name:I,symbol:U,decimals:B,balance:m,balanceFormatted:parseFloat((Number(m)/Math.pow(10,B)).toFixed(6)),balanceUsd:0,logoURI:s.logoURI,isNative:!1,chainId:s.chainId}):x(null)}catch{p||x(null)}};S();const D=setInterval(S,15e3);return()=>{p=!0,clearInterval(D)}},[s.address,s.chainId,s.decimals,s.symbol,s.logoURI,r,l]);const y=o.useCallback(()=>{if(!s.address||!r)return;const p=H.getClientForChain(s.chainId),f=Q.getAddress(s.address),w=Q.getAddress(r);p.multicall({contracts:[{address:f,abi:Q.erc20Abi,functionName:"balanceOf",args:[w]},{address:f,abi:Q.erc20Abi,functionName:"decimals",args:[]}]}).then(g=>{const S=g[0].status==="success"?g[0].result:0n,D=g[1].status==="success"?Number(g[1].result):18;S>0n?x(b=>b?{...b,balance:S,balanceFormatted:parseFloat((Number(S)/Math.pow(10,D)).toFixed(6))}:null):x(null)}).catch(()=>{})},[s.address,s.chainId,r]);return{displayAssets:o.useMemo(()=>{const p=[];u&&p.push({...u,_source:"wallet"});for(const w of h)p.push({...w,_source:"spice"});const f=s.address.toLowerCase();return p.sort((w,g)=>Us(w,f,s.chainId)-Us(g,f,s.chainId)),p},[u,h,s.address,s.chainId]),filteredSpiceAssets:h,embeddedWalletAddress:r,refreshSpiceAssets:d,refreshWalletAssets:y}}async function zs(t){const{tokenIn:n,tokenOut:s,amountIn:a,fee:i,chainId:l,config:r}=t;if(a<=0n)throw new Error("amountIn must be greater than 0");const c=(await H.getClientForChain(l).simulateContract({address:r.quoterV2,abi:Y.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:n,tokenOut:s,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 Ls(t){const n=t.feeTiers??[100,500,3e3,1e4],s=await Promise.allSettled(n.map(i=>zs({...t,fee:i})));let a=null;for(let i=0;i<s.length;i++){const l=s[i];l.status==="fulfilled"&&(!a||l.value.amountOut>a.amountOut)&&(a={...l.value,fee:n[i]})}if(!a)throw new Error("No liquidity found for this pair on any fee tier.");return a}const Ar=[{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 Br(t){const{tokenIn:n,tokenOut:s,amountOut:a,fee:i,chainId:l,config:r}=t;if(a<=0n)throw new Error("amountOut must be greater than 0");const c=(await H.getClientForChain(l).simulateContract({address:r.quoterV2,abi:Ar,functionName:"quoteExactOutputSingle",args:[{tokenIn:n,tokenOut:s,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 Fr(t){const n=t.feeTiers??[100,500,3e3,1e4],s=await Promise.allSettled(n.map(i=>Br({...t,fee:i})));let a=null;for(let i=0;i<s.length;i++){const l=s[i];l.status==="fulfilled"&&(!a||l.value.amountIn<a.amountIn)&&(a={...l.value,fee:n[i]})}if(!a)throw new Error("No liquidity found for this pair on any fee tier.");return a}function Ps(t){return t.type==="swap"}const $n=.02,Rr=[1,8453,42161,10,137,43114,56],Tr="https://api.1inch.dev/swap/v6.0";function Hs(t,n){return Y.applySlippage(t,n)}function Os(t){const n=t?.baseUrl??Tr;return{name:"1inch",chainIds:t?.chainIds??Rr,resolve:async(s,a,i)=>{const l=s.maxSlippage??$n,r=l*100,c=Y.isNativeToken(s.tokenIn)?Y.NATIVE_TOKEN_ADDRESS:s.tokenIn,d=Y.isNativeToken(s.tokenOut)?Y.NATIVE_TOKEN_ADDRESS:s.tokenOut,h=Y.isNativeToken(s.tokenIn);try{const u=new URL(`${n}/${a}/swap`);u.searchParams.set("src",c),u.searchParams.set("dst",d),u.searchParams.set("amount",s.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 y=await fetch(u.toString(),{headers:x});if(!y.ok)throw new V.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${y.status} for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${a}`,{venue:"1inch",chainId:a,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn.toString(),cause:`HTTP ${y.status}`});const p=await y.json();if(!p.dstAmount||!p.tx)return console.warn(`[1inchVenue] No route data for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${a}`),null;const f=BigInt(p.dstAmount);if(f<=0n)return console.warn(`[1inchVenue] Zero output for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${a}`),null;const w=Hs(f,l),g=[];return p.tx.to&&!h&&g.push({to:s.tokenIn,value:0n,data:Q.encodeFunctionData({abi:Q.erc20Abi,functionName:"approve",args:[p.tx.to,s.amountIn]})}),g.push({to:p.tx.to,value:BigInt(p.tx.value||"0"),data:p.tx.data}),{venue:"1inch",amountOut:f,amountOutMinimum:w,calls:g}}catch(u){if(u instanceof V.SpiceflowError)throw u;const x=u instanceof Error?u.message:String(u);throw new V.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] Exception for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${a}: ${x}`,{venue:"1inch",chainId:a,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn.toString(),cause:x})}}}}const Vs=[4114,5115],_n={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425"},Qs={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453]};function Ys(t){return{name:"satsuma",chainIds:t.chainIds??Vs,resolve:async(n,s,a)=>{const i=n.maxSlippage??$n,l=Y.isNativeToken(n.tokenIn);let r;try{r=await Ls({tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn,chainId:s,config:{swapRouter:t.swapRouter,quoterV2:t.quoterV2},feeTiers:t.feeTiers})}catch{return console.warn(`[SatsumaVenue] No viable fee tier for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}.`),null}const c=Hs(r.amountOut,i),d=[];return l||d.push({to:n.tokenIn,value:0n,data:Q.encodeFunctionData({abi:Q.erc20Abi,functionName:"approve",args:[t.swapRouter,n.amountIn]})}),d.push({to:t.swapRouter,value:l?n.amountIn:0n,data:Q.encodeFunctionData({abi:Y.uniV3SwapRouterAbi,functionName:"exactInputSingle",args:[{tokenIn:n.tokenIn,tokenOut:n.tokenOut,fee:r.fee,recipient:a,amountIn:n.amountIn,amountOutMinimum:c,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:r.amountOut,amountOutMinimum:c,calls:d}}}}function Zs(t){return{name:"satsuma",chainIds:t.chainIds??Vs,resolve:async(n,s,a)=>{const i=n.maxSlippage??$n,l=Y.isNativeToken(n.tokenIn);let r;try{r=await Fr({tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountOut:n.amountOut,chainId:s,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,h=[];return h.push({to:t.swapRouter,value:l?d:0n,data:Q.encodeFunctionData({abi:Mr,functionName:"exactOutputSingle",args:[{tokenIn:n.tokenIn,tokenOut:n.tokenOut,fee:r.fee,recipient:a,amountOut:n.amountOut,amountInMaximum:d,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:r.amountIn,amountInMax:d,amountOut:n.amountOut,calls:h}}}}const Mr=[{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 Ks(t){const n=[];t?.customVenues&&n.push(...t.customVenues),t?.satsuma&&n.push(Ys(t.satsuma)),n.push(Os(t?.oneInch));function s(i){return n.find(l=>l.chainIds.includes(i))}async function a(i,l,r){const c=[],d=[];for(const h of i){if(!Ps(h)){c.push(h);continue}const u=s(l);if(!u)throw new V.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${l}. Cannot resolve swap ${h.tokenIn} \u2192 ${h.tokenOut}.`,{chainId:l,tokenIn:h.tokenIn,tokenOut:h.tokenOut,amountIn:h.amountIn.toString()});const x=await u.resolve(h,l,r);if(!x)throw new V.SpiceflowError("NO_LIQUIDITY",`${u.name} returned no quote for ${h.tokenIn} \u2192 ${h.tokenOut} on chain ${l}.`,{venue:u.name,chainId:l,tokenIn:h.tokenIn,tokenOut:h.tokenOut,amountIn:h.amountIn.toString()});c.push(...x.calls),d.push(x)}return{calls:c,resolvedSwaps:d}}return{resolveSwapIntents:a,getVenueForChain:s,venues:n}}function Dr(t){const n=t?.customVenues??[];async function s(a,i,l){const r=n.filter(d=>d.chainIds.includes(i));if(r.length===0)throw new V.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 V.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,h)=>d.amountIn<h.amountIn?-1:d.amountIn>h.amountIn?1:0),c[0]}return{getQuote:s,venues:n}}function Wr(t){const{direction:n,selectedAsset:s,destinationToken:a,chainId:i,recipient:l,paymentAmount:r}=t,[c,d]=o.useState(!1),[h,u]=o.useState(null),[x,y]=o.useState(null),[p,f]=o.useState(null),[w,g]=o.useState(null),[S,D]=o.useState(null),[b,m]=o.useState(null),B=o.useRef(null),U=o.useMemo(()=>Ks({satsuma:_n}),[]),I=o.useMemo(()=>Dr({customVenues:[Zs(_n),Zs(Qs)]}),[]),v=o.useMemo(()=>{if(!s?.asset)return null;if(s.asset.chainId===i)return s.asset.address;const T=Xt(s.asset.address,i);return T?T.address:null},[s?.asset?.address,s?.asset?.chainId,i]),z=o.useMemo(()=>s?.asset?s.asset.address.toLowerCase()===a.address.toLowerCase()&&s.asset.chainId===i?!0:v?v.toLowerCase()===a.address.toLowerCase():!1:!1,[s,a.address,i,v]),C=v?v.toLowerCase()===a.address.toLowerCase():!1,k=n==="output"&&parseFloat(r||"0")===0,P=!!s?.asset&&!z&&!C&&!k;return o.useEffect(()=>{B.current&&clearTimeout(B.current);const T=n==="input"?s?.amount:r,F=parseFloat(T||"0");if(!P||F<=0||!s?.asset||!l||!v){y(null),f(null),g(null),D(null),m(null),u(null),d(!1);return}return d(!0),B.current=setTimeout(async()=>{try{if(n==="input"){const M=Q.parseUnits(s.amount,s.asset.decimals),ee=U.getVenueForChain(i);if(!ee)throw new Error("No swap venue for this chain");const $=await ee.resolve({type:"swap",tokenIn:v,tokenOut:a.address,amountIn:M},i,l);if(!$)throw new Error("No liquidity for this pair");m($.amountOut),g($),D(null);const L=Q.formatUnits($.amountOut,a.decimals),Z=parseFloat(L);y(Z<.01?Z.toPrecision(4):Z.toLocaleString(void 0,{maximumFractionDigits:6})),f(null),u(null)}else{const M=Q.parseUnits(r||"0",a.decimals),ee=await I.getQuote({tokenIn:v,tokenOut:a.address,amountOut:M},i,l);D(ee),g(null),m(null),f(parseFloat(Q.formatUnits(ee.amountIn,s.asset.decimals)).toFixed(6)),y(null),u(null)}}catch(M){const ee=M instanceof Error?M.message:"Failed to get quote";u(ee),y(null),f(null),g(null),D(null),m(null)}finally{d(!1)}},500),()=>{B.current&&clearTimeout(B.current)}},[n,P,s?.amount,s?.asset?.address,s?.asset?.decimals,r,v,i,a.address,a.decimals,l,U,I]),{isQuoting:c,quoteError:h,estimatedOutput:x,estimatedInput:p,resolvedSwap:w,exactOutputSwap:S,quoteAmountOut:b,resolvedTokenIn:v,isDirect:C,needsSwap:P,selectedIsEquivalent:z}}const qs={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Transaction successful!",error:"Transaction failed"},Xs=["signing-delegation","signing-intent","submitting","executing"],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})]}),Gs=({isOpen:t,onClose:n,destinationToken:s,buildActionCalls:a,buildSpicenetBatch:i,actionLabel:l,amountDirection:r="input",swapDescription:c,directDescription:d,supportedSourceAssets:h,sourceChains:u,paymentAmount:x,amountInputMode:y="fixed",minPaymentAmount:p,maxPaymentAmount:f,onAmountChange:w,styles:g,dark:S,title:D,subtitle:b,onAddFunds:m,onSuccess:B,onError:U})=>{const I=r==="output",{theme:v,dark:z,primaryColor:C,dk:k,palette:P}=V.useSpiceBrand(g,S),T=v.typography.fontFamily,F=g?.inputVariant?g.inputVariant==="dark":z,M=P.textPrimary,ee=P.textSecondary,$=F?k.cardBg:"#f9fafb",L=F?k.cardBorder:"#e5e7eb",Z=g?.button?.backgroundColor??C,te=g?.button?.color??"#0e0d0b",O=F?{...v,colors:{...v.colors,secondary:k.cardBg,surfaceHover:k.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:v,R=s.chainId,ae=Ht(),{address:ye,isConnected:ke,isReady:he,isAuthenticated:ge,provider:be}=ae,{executeGasless:Me}=jn(),{displayAssets:Se,filteredSpiceAssets:Ve,embeddedWalletAddress:me,refreshSpiceAssets:Ne,refreshWalletAssets:Le}=Er({address:ye,destinationToken:s,supportedSourceAssets:h,sourceChains:u,enabled:t&&!!ye}),oe=o.useMemo(()=>Ve.map(se=>({...se,_source:"spice"})),[Ve]),Ee=I?Se:oe,[ne,le]=o.useState(null),[Je,Ye]=o.useState(x||""),[G,xe]=o.useState(!1),[E,N]=o.useState(null),[_,fe]=o.useState("idle"),[A,q]=o.useState(""),[re,ue]=o.useState(null),[Ze,lt]=o.useState(!1),[Be,Xe]=o.useState(null),ve=o.useRef(ne),rt=o.useRef(!1),ht=o.useRef(null);o.useEffect(()=>{ve.current=ne},[ne]);const Fe=y==="adjustable"?Je:x||"0",Ct=me||ye,{isQuoting:xt,quoteError:vt,estimatedOutput:zt,resolvedSwap:It,exactOutputSwap:nt,quoteAmountOut:At,resolvedTokenIn:kt,isDirect:ut,needsSwap:mt,selectedIsEquivalent:Ge}=Wr({direction:r,selectedAsset:ne,destinationToken:s,chainId:R,recipient:Ct,paymentAmount:Fe}),dt=I?parseFloat(Fe||"0"):parseFloat(ne?.amount||"")||0,bt=o.useMemo(()=>ne?.asset?Ve.find(se=>se.address.toLowerCase()===ne.asset.address.toLowerCase())?.balanceFormatted??0:0,[ne,Ve]),ft=o.useMemo(()=>ne?.asset?I?Ge?dt>ne.asset.balanceFormatted:nt?parseFloat(Q.formatUnits(nt.amountInMax,ne.asset.decimals))>ne.asset.balanceFormatted:!1:dt>bt:!1,[ne,I,Ge,dt,nt,bt]);o.useEffect(()=>{t||(le(null),N(null),xe(!1),fe("idle"),q(""),ue(null),lt(!1),Xe(null),rt.current=!1,y==="adjustable"&&Ye(x||""),ht.current&&(ht.current.abort(),ht.current=null))},[t]);const gt=o.useCallback(se=>{le(ce=>({asset:se,amount:ce?.asset?.address===se.address&&ce?.asset?.chainId===se.chainId&&ce.amount||""})),N(null)},[]),Bt=o.useCallback(se=>{le(ce=>ce&&{...ce,amount:se}),N(null)},[]),ie=o.useCallback(se=>{let ce=se;f&&parseFloat(ce)>parseFloat(f)&&(ce=f),Ye(ce),w?.(ce),N(null)},[f,w]);o.useCallback(se=>{if(rt.current||!ye)return;const ce=ve.current;!ce?.asset||!ce.amount||ce.asset?._source==="wallet"||Q.parseUnits(I?Fe:ce.amount,ce.asset.decimals)===0n||(rt.current=!0,Ne())},[ye,R,Ne,I,Fe]);const pe=o.useCallback(se=>{fe({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[se.step]||"executing"),q(se.message),se.txHash&&ue(se.txHash)},[]),Pe=o.useCallback(()=>{const se=Q.parseUnits(Fe,s.decimals),ce={userAddress:me,chainId:R,destinationToken:s.address},Ce=a(se,ce),Ie={chainId:R,calls:Ce},Re=ne?.asset?._source==="spice",Ae=(We,we)=>({token:We,from:"solver",to:me,amount:we});if(se===0n)return[Ie];if(mt&&nt){let We=ne.asset.address;if(ne.asset.chainId!==R){const X=Y.getTokenDefinition(ne.asset.address)?.deployments.find(j=>j.chainId===R);X&&(We=X.address)}const we=Re?[Ae(We,nt.amountInMax)]:[],W={to:We,value:0n,data:Q.encodeFunctionData({abi:Q.erc20Abi,functionName:"approve",args:[nt.calls[0]?.to,nt.amountInMax]})};return[{chainId:R,calls:[W,...nt.calls,...Ce],tokenTransfers:[...we,...Ie.tokenTransfers??[]]}]}if(Re){let We=s.address;if(ne.asset.chainId!==R){const we=Y.getTokenDefinition(ne.asset.address)?.deployments.find(W=>W.chainId===R);we&&(We=we.address)}return[{...Ie,tokenTransfers:[Ae(We,se),...Ie.tokenTransfers??[]]}]}return[Ie]},[Fe,s,me,R,a,ne,mt,nt]),$e=o.useCallback(()=>{if(!ne?.asset||!me)return[];const se=Q.parseUnits(ne.amount,ne.asset.decimals),ce={userAddress:me,chainId:R,destinationToken:s.address},Ce=a(se,ce),Ie=ne.asset?._source==="spice";if(!Ie)return[{chainId:R,calls:Ce}];const Re=(W,X)=>({token:W,from:"solver",to:me,amount:X});if(mt&&It&&At&&kt){const W=a(At,ce),X={chainId:R,calls:[...It.calls,...W],tokenTransfers:[Re(kt,se)]};if(!i)return[X];const j=i({userAddress:me,destinationChainId:R,deliveryToken:kt,deliveryAmount:se});return console.log("[SpiceSupply] buildSupplyChainBatches:swap",{isSpiceSourced:Ie,hasBuildSpicenetBatch:!!i,amountIn:se.toString(),resolvedTokenIn:kt,spicenetBatch:j}),j?[j,X]:[X]}let Ae=s.address;if(ne.asset.chainId!==R){const W=Y.getTokenDefinition(ne.asset.address)?.deployments.find(X=>X.chainId===R);W&&(Ae=W.address)}const We={chainId:R,calls:Ce,tokenTransfers:[Re(Ae,se)]};if(!i)return[We];const we=i({userAddress:me,destinationChainId:R,deliveryToken:Ae,deliveryAmount:se});return console.log("[SpiceSupply] buildSupplyChainBatches:direct",{isSpiceSourced:Ie,hasBuildSpicenetBatch:!!i,amountIn:se.toString(),deliveryToken:Ae,spicenetBatch:we}),we?[we,We]:[We]},[ne,me,R,s,a,mt,It,At,kt,i]),at=o.useMemo(()=>{if(!ne?.asset)return s.address;if(ne.asset.chainId===R)return ne.asset.address;const se=Y.getTokenDefinition(ne.asset.address)?.deployments.find(ce=>ce.chainId===R);return se?se.address:s.address},[ne,s.address,R]),ct=o.useCallback(async()=>{if(!ne?.asset||dt<=0){N("Select an asset and enter an amount");return}if(ft){N("Insufficient balance");return}if(!me){N("Wallet not ready");return}xe(!0),N(null),fe("signing-delegation"),q("Building transaction..."),ue(null),rt.current=!1;const se=new AbortController;ht.current=se;try{const ce=Q.parseUnits(ne.amount,ne.asset.decimals),Ce=$e(),Ie=Ce.some(Re=>Re.tokenTransfers?.length);await Me(Ce,at,ce,pe,se.signal,Ie?{useCustomTransfers:!0}:void 0),fe("success"),q("Transaction successful!")}catch(ce){const Ce=ce instanceof Error?ce:new Error(String(ce));if(Ce.name==="AbortError"||se.signal.aborted){fe("idle");return}const Ie=Ce.message||"Transaction failed";fe("error"),q(Ie),N(Ie),U?.(Ce)}finally{xe(!1)}},[ne,dt,ft,me,at,$e,Me,pe,U]),_e=o.useCallback(async()=>{if(dt<0){N("Enter a valid payment amount");return}if(!ne?.asset){N("Select a payment source");return}if(ft){N("Insufficient balance");return}if(mt&&!nt){N("Swap quote not available. Try a different asset.");return}if(!ke||!ye){N("Please connect your wallet to continue");return}if(!he||!ge){N(`Please authenticate with ${be||"wallet provider"} to continue`);return}xe(!0),N(null),lt(!0),Xe({status:"processing"});try{const se=Pe(),ce=se.some(Ae=>Ae.tokenTransfers?.length),Ce=Q.parseUnits(Fe,s.decimals),Ie=ne?.asset?.address||s.address,Re=await Me(se,Ie,Ce,Ae=>{Ae.txHash&&(Xe(We=>({...We,txHash:Ae.txHash})),ue(Ae.txHash))},void 0,ce?{useCustomTransfers:!0}:void 0);Xe(Ae=>({status:"success",txHash:Ae?.txHash||Re}))}catch(se){const ce=Lt(se,"Payment failed. Please try again.");N(ce),Xe({status:"failed",error:ce}),U?.(se instanceof Error?se:new Error(ce))}finally{xe(!1)}},[dt,ne,ft,mt,nt,ke,ye,he,ge,be,Pe,Fe,s,Me,U]);o.useEffect(()=>{!I&&_==="success"&&re&&(Ne(),B?.(re))},[I,_,re,Ne,B]),o.useEffect(()=>{if(!I||Be?.status!=="success"||rt.current||!ye)return;rt.current=!0;const se=ve.current;!se?.asset||se.asset?._source==="wallet"||Ne()},[I,Be?.status,ye,Ne]);const Ke=o.useRef(B),St=o.useRef(U);o.useEffect(()=>{Ke.current=B},[B]),o.useEffect(()=>{St.current=U},[U]),o.useEffect(()=>{I&&(Be?.status==="success"&&Ke.current?.(Be.txHash||""),Be?.status==="failed"&&St.current?.(new Error("Payment execution failed")))},[I,Be?.status]);const jt=o.useCallback(()=>{lt(!1),Xe(null),le(null),rt.current=!1,Ne(),Le()},[Ne,Le]),Ft=I?!!ne?.asset&&dt>=0&&!ft&&!G&&(!mt||!!nt):!!ne?.asset&&dt>0&&!ft&&!G&&(ut||!!It&&!xt),Et=ut?d||`Your ${s.symbol} will be used directly.`:c||"Your assets will be swapped and used in a single atomic transaction.",Rt=z?k.shell:"white",Dt=z?k.buttonBorder:"#0e0d0b",Gt=(R?H.getChainConfig(R):void 0)?.viemChain?.blockExplorers?.default?.url??"",Zt=Xs.indexOf(_),K=G?(qs[_]||"EXECUTING...").toUpperCase():_==="success"?"DONE":ft?"INSUFFICIENT BALANCE":l.toUpperCase(),de=o.useMemo(()=>{if(G)return"PAYING...";if(ft&&ne?.asset)return`INSUFFICIENT ${ne.asset.symbol}`;const se=dt>0?` ${Fe} ${s.symbol}`:"";return mt?`SWAP & PAY${se}`:`PAY${se}`},[G,ft,ne,dt,Fe,s.symbol,mt]),Te=_==="success"?()=>{fe("idle"),le(null),ue(null),Ne()}:ct,Ue=_==="success"?!1:!Ft;if(!t)return null;const Oe=I?D||`Pay ${s.symbol}`:l,pt=I?b:e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[e.jsx(Nr,{color:ee}),e.jsx("p",{style:{fontSize:"13px",color:ee,margin:0,lineHeight:"1.5"},children:Et})]});if(I){const se=Be&&(Be.status==="success"||Be.status==="failed")?[{asset:{symbol:ne?.asset?.symbol||s.symbol,address:ne?.asset?.address||""},amount:Fe,txHash:Be.txHash||"",success:Be.status==="success",error:Be.status==="failed"?Be.error:void 0}]:void 0;return e.jsx(Mt,{isOpen:t,onClose:n,title:Oe,subtitle:pt,styles:g,dark:z,footerLinkText:"Spicenet accounts \u2192",children:e.jsxs("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[m&&e.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:e.jsxs("button",{onClick:m,style:{background:"none",border:"none",cursor:"pointer",padding:0,display:"flex",alignItems:"center",gap:"4px",color:C,fontSize:"12px",fontWeight:500,fontFamily:T,textDecoration:"underline",textUnderlineOffset:"2px"},children:["Add Funds",e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:C,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(dn,{assets:Ee,selectedAsset:ne??void 0,onAssetSelect:gt,onAmountChange:()=>{},label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:ne?.asset?mt?xt?"...":nt?`~${parseFloat(Q.formatUnits(nt.amountIn,ne.asset.decimals)).toFixed(6)}`:void 0:Fe??void 0:void 0,dark:z,theme:O,styles:g})}),e.jsx(Ws,{variant:"pay",destinationSymbol:s.symbol,destinationLogoURI:s.logoURI,destinationDecimals:s.decimals,primaryColor:C,fontFamily:T,textPrimary:M,textSecondary:ee,cardBg:$,cardBorder:L,dk:k,dark:z,isQuoting:xt,quoteError:vt,estimatedOutput:zt,paymentAmount:Fe,needsSwap:mt,exactOutputSwap:nt,adjustable:y==="adjustable",maxAmount:f,onAmountChange:ie}),E&&e.jsx("div",{style:{marginBottom:"12px",padding:"10px 14px",backgroundColor:P.errorBg,border:`1px solid ${P.errorBorder}`,borderRadius:"6px"},children:e.jsx("p",{style:{color:P.errorText,fontSize:"13px",margin:0,fontFamily:T},children:E})}),e.jsx(De.Button,{variant:"outline",fullWidth:!0,onClick:_e,disabled:!Ft,loading:G,dark:z,styles:{button:{backgroundColor:C}},children:de}),Be&&Ze&&e.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:z?k.shell:"white",borderRadius:z?"12px":"6px",padding:"16px 0"},children:e.jsx(gn,{type:"payment",isOpen:Be.status!=="processing",isProcessing:G||Be.status==="processing",closeOnComplete:!1,chainName:H.getChainName(R),explorerUrl:H.getExplorerUrl(R,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{lt(!1),Xe(null),_e()},onNewTx:jt,onClose:()=>{lt(!1),Xe(null)},onComplete:jt,results:se,styles:g,dark:z})})]})})}return e.jsxs(Mt,{isOpen:t,onClose:n,title:Oe,subtitle:pt,dark:z,styles:g,theme:v,children:[e.jsx("div",{style:{marginBottom:"16px"},children:e.jsx(dn,{assets:Ee,selectedAsset:ne||void 0,onAssetSelect:gt,onAmountChange:Bt,disabled:G||_==="success",showBalance:!0,showMaxButton:!0,label:"From Spice Balance",placeholder:"0.00",theme:O,styles:g,dark:F,maxAmount:bt>0?bt.toString():void 0})}),ne?.asset&&!ut&&e.jsx(Ws,{variant:"supply",destinationSymbol:s.symbol,destinationLogoURI:s.logoURI,destinationDecimals:s.decimals,primaryColor:C,fontFamily:T,textPrimary:M,textSecondary:ee,cardBg:$,cardBorder:L,dark:z,isQuoting:xt,quoteError:vt,estimatedOutput:zt}),_!=="idle"&&e.jsxs("div",{style:{padding:"10px 14px",borderRadius:"10px",marginBottom:"16px",backgroundColor:_==="success"?P.successBg:_==="error"?P.errorBg:$,border:`1px solid ${_==="success"?P.successBorder:_==="error"?P.errorBorder:L}`},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[_==="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:P.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):_==="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:P.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):e.jsx(De.Spinner,{size:14,color:C}),e.jsx("span",{style:{fontSize:"13px",fontWeight:500,color:_==="success"?P.successText:_==="error"?P.errorText:M,fontFamily:T,flex:1},children:_==="success"?"Transaction successful!":_==="error"?A||"Transaction failed":qs[_]||A}),_==="success"&&re&&e.jsx("a",{href:`${Gt}/tx/${re}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:C,fontFamily:T,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),_==="error"&&e.jsx("button",{onClick:()=>{fe("idle"),N(null),setTimeout(ct,50)},style:{background:"none",border:"none",fontSize:"12px",color:C,fontFamily:T,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),Zt>=0&&_!=="success"&&_!=="error"&&e.jsx("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${ee}22`,overflow:"hidden"},children:e.jsx("div",{style:{height:"100%",borderRadius:"2px",backgroundColor:C,width:`${(Zt+1)/Xs.length*100}%`,transition:"width 400ms ease"}})})]}),E&&_==="idle"&&e.jsx("div",{style:{padding:"10px 14px",borderRadius:"10px",backgroundColor:P.errorBg,border:`1px solid ${P.errorBorder}`,marginBottom:"16px"},children:e.jsx("p",{style:{fontSize:"13px",color:P.errorText,margin:0,fontFamily:T},children:E})}),e.jsx(De.Button,{variant:"outline",fullWidth:!0,disabled:Ue,onClick:Te,style:{height:"56px",backgroundColor:Ue?`${Z}66`:_==="success"?P.successBg:Z,color:_==="success"?P.successText:te,border:`1px solid ${_==="success"?P.successBorder:Dt}`,fontSize:"14px",fontWeight:700,letterSpacing:"2px",fontFamily:'"IBM Plex Mono", monospace',boxShadow:Ue?"none":`3px 3px 0px ${Rt}, 4px 4px 0px ${Dt}`,cursor:Ue?"not-allowed":"pointer",opacity:Ue?.6:1},children:K})]})},Ur=t=>e.jsx(Gs,{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}),zr=({label:t="Export Wallet",style:n,className:s,onExport:a,onError:i})=>{const[l,r]=o.useState(!1),[c,d]=o.useState(!1),{primaryColor:h}=V.useSpiceBrand(),u=o.useContext(V.SpiceFlowProviderContext),{isAuthenticated:x}=Ht();let y=null;try{y=Nt.usePrivy()}catch{}let p=null,f=null;try{p=hn.useEmbeddedReveal(),f=hn.useDynamicContext()}catch{p=null,f=null}const w=Vt.getDynamicEmbeddedWallet(f),g=o.useCallback(async()=>{if(!x){i?.("User is not authenticated. Please log in first.");return}try{if(u?.provider==="dynamic"){if(!p||!w){i?.("Dynamic is not available. Ensure the app is wrapped in a DynamicContextProvider.");return}await p.initExportProcess(!1),a?.();return}if(!y){i?.("Privy is not available. Ensure the app is wrapped in a PrivyProvider.");return}await y.exportWallet(),a?.()}catch(b){const m=b instanceof Error?b.message:"Failed to export wallet";console.error("Export wallet error:",b),i?.(m)}},[w,p,x,i,a,y,u?.provider]),S=!x,D={padding:"10px 20px",borderRadius:"8px",fontFamily:'"IBM Plex Mono", monospace',fontSize:"14px",fontWeight:500,letterSpacing:"0.4px",textTransform:"uppercase",cursor:S?"not-allowed":"pointer",opacity:S?.5:1,border:"1px solid #0e0d0b",color:"#0e0d0b",backgroundColor:c?`${h}cc`:l?`${h}ee`:h,transition:"all 150ms ease",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"8px",...n};return e.jsxs("button",{onClick:g,onMouseEnter:()=>r(!0),onMouseLeave:()=>{r(!1),d(!1)},onMouseDown:()=>d(!0),onMouseUp:()=>d(!1),disabled:S,className:s,style:D,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 Js(t){const n=o.useContext(V.SpiceFlowProviderContext),s=Pt(),a=t?.enabled===!1?void 0:s,i=n?.network?{network:n.network,pollIntervalMs:t?.pollIntervalMs,chainIds:t?.chainIds??n.supportedChainIds}:void 0;return{...ks(a,i),embeddedWalletAddress:s}}const Lr=({appName:t,status:n,statusLabel:s,totalUsdValue:a,breakdownSubtitle:i,address:l,dk:r,dark:c=!1,showModeToggle:d,isEmbeddedMode:h=!0,onModeToggle:u})=>{const[x,y]=o.useState(!1),p=async()=>{l&&await vo(l)&&(y(!0),setTimeout(()=>y(!1),2e3))},f=n==="active",w=s||(f?"Active":"Inactive"),g=f?"#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:h?"#22c55e":"#f59e0b"}}),e.jsx("span",{children:h?"Embedded":"External"})]}):e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:c?r.hoverBg:f?"#ecfdf5":"#f3f4f6",border:c?`1px solid ${r.cardBorder}`:f?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[e.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:g}}),e.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:c?r.textSecondary:f?"#065f46":"#6b7280"},children:w})]})]}),e.jsx("div",{style:{fontSize:"28px",fontWeight:700,color:c?r.textPrimary:"#111827",lineHeight:1.2,marginBottom:"2px"},children:ln(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:wo(l)}),e.jsx("button",{onClick:p,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"})]})]})},Pr=({pendingDeposits:t,onCompleteDeposit:n,dk:s,dark:a=!1})=>t.length===0?null:e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:a?s.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=H.getChainConfig(i.chainId)?.displayName||`Chain ${i.chainId}`;return e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:a?s.warningBg:"#fffbeb",border:a?`1px solid ${s.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?s.hoverBg:"#fde68a",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:a?s.warningText:"#92400e"},children:i.tokenSymbol.charAt(0)}),e.jsxs("div",{children:[e.jsxs("div",{style:{fontSize:"13px",fontWeight:500,color:a?s.textPrimary:"#111827"},children:[i.amount," ",i.tokenSymbol]}),e.jsxs("div",{style:{fontSize:"11px",color:a?s.warningText:"#92400e"},children:["on ",r]})]})]}),e.jsx("button",{onClick:()=>n?.(i),style:{padding:"4px 12px",fontSize:"11px",fontWeight:600,backgroundColor:a?s.hoverBg:"#fef3c7",color:a?s.textPrimary:"#92400e",border:a?`1px solid ${s.warningBorder}`:"1px solid #fde68a",borderRadius:"9999px",cursor:"pointer",transition:"all 150ms ease"},children:"Complete"})]},`${i.tokenAddress}-${i.chainId}-${l}`)})})]}),Hr=({spiceAssets:t,loading:n,dk:s,dark:a=!1})=>{const i={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:a?s.textSecondary:"#6b7280",marginBottom:"8px",textTransform:"uppercase"},l={backgroundColor:a?s.cardBg:"#f9fafb",border:a?`1px solid ${s.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return n?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?s.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=H.getChainConfig(r.chainId),h=r.chainDisplayName||d?.displayName||`Chain ${r.chainId}`,u=r.tokenDisplaySymbol||r.tokenDisplayName||r.tokenSymbol;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?s.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:a?s.textSecondary:"#6b7280"},children:u.charAt(0)}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:a?s.textPrimary:"#111827"},children:u}),e.jsx("div",{style:{fontSize:"11px",color:a?s.textSecondary:"#9ca3af"},children:h})]})]}),e.jsxs("div",{style:{textAlign:"right"},children:[e.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:a?s.textPrimary:"#111827"},children:$t(r.balanceFormatted)}),e.jsx("div",{style:{fontSize:"11px",color:a?s.textSecondary:"#9ca3af"},children:ln(r.usdValue)})]})]},`${r.tokenAddress}-${r.chainId}-${c}`)})})]})},Or=({section:t,dk:n,dark:s=!1})=>{const a=i=>{switch(i){case"green":return"#10b981";case"red":return"#ef4444";default:return s?n.textPrimary:"#111827"}};return e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:s?n.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:s?n.cardBg:"#f9fafb",border:s?`1px solid ${n.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:s?n.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",fontWeight:600,color:s?n.textSecondary:"#6b7280"},children:i.tokenSymbol.charAt(0)}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:s?n.textPrimary:"#111827"},children:i.tokenSymbol}),e.jsx("div",{style:{fontSize:"11px",color:s?n.textSecondary:"#6b7280"},children:i.label})]})]}),e.jsx("div",{style:{fontSize:"13px",fontWeight:600,color:a(i.valueColor)},children:i.displayValue})]},l))})]})},Vr=({onDepositClick:t,onWithdrawClick:n,depositDisabled:s=!1,withdrawDisabled:a=!1,primaryColor:i="#EA4B4B",dark:l=!1})=>!t&&!n?null:e.jsxs("div",{style:{display:"flex",gap:"8px"},children:[t&&e.jsx(De.Button,{variant:"outline",onClick:t,disabled:s,dark:l,styles:{button:{backgroundColor:i}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),n&&e.jsx(De.Button,{variant:"outline",onClick:n,disabled:a,dark:l,styles:{button:{backgroundColor:i}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),Qr=({appName:t,status:n,statusLabel:s,totalUsdValue:a,breakdownSubtitle:i,address:l,spiceAssets:r,spiceAssetsLoading:c,pendingDeposits:d,customSections:h,onDepositClick:u,onWithdrawClick:x,onCompleteDeposit:y,primaryColor:p,dk:f,dark:w=!1,showModeToggle:g,isEmbeddedMode:S,onModeToggle:D})=>{const[b,m]=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(Lr,{appName:t,status:n,statusLabel:s,totalUsdValue:a,breakdownSubtitle:i,address:l,dk:f,dark:w,showModeToggle:g,isEmbeddedMode:S,onModeToggle:D}),e.jsx("div",{style:{height:"1px",backgroundColor:w?"#2d2d2d":"#e5e7eb"}}),e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>m(!b),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:w?f.cardBg:"#f9fafb",border:w?`1px solid ${f.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:w?f.textSecondary:"#6b7280",fontSize:"12px",fontWeight:500},children:[e.jsx("span",{children:"How It Works"}),e.jsx("span",{style:{transform:b?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),b&&e.jsxs("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:w?f.cardBg:"#f0fdf4",border:w?`1px solid ${f.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:w?f.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(Pr,{pendingDeposits:d,onCompleteDeposit:y,dk:f,dark:w}),e.jsx(Hr,{spiceAssets:r,loading:c,dk:f,dark:w}),h.map((B,U)=>e.jsx(Or,{section:B,dk:f,dark:w},U)),e.jsx(Vr,{onDepositClick:u,onWithdrawClick:x,primaryColor:p,dark:w})]})},es=380,un=8,Yr=({appName:t="Spice",status:n="active",statusLabel:s,customSections:a=[],extraAssets:i=[],tokenPrices:l={},breakdownLabels:r=[],supportedChains:c,styles:d,dark:h=!1,onDepositSuccess:u,onDepositClick:x,onWithdrawClick:y,onCompleteDeposit:p,showModeToggle:f=!1,defaultMode:w})=>{const g=o.useContext(V.SpiceFlowProviderContext),S=g?.mode!=="7702";o.useEffect(()=>{w&&g?.setMode&&g.setMode(w==="non7702"?"ondemand":"7702")},[g,w]);const[D,b]=o.useState(!1),[m,B]=o.useState(null),[U,I]=o.useState({top:0,left:0,placement:"below"}),v=o.useRef(null),z=o.useRef(null),{address:C,isConnected:k}=Ht(),P=Pt(),{address:T}=qe.useAccount(),{dark:F,primaryColor:M,dk:ee}=V.useSpiceBrand(d,h),$=o.useMemo(()=>c||Y.getChainIdsByNetwork("mainnet"),[c]),{assets:L,loading:Z}=an({address:C,supportedChains:$,enabled:!!C&&!S,refetchInterval:3e4}),te=o.useMemo(()=>[...S?[]:L.map(oe=>{const Ee=oe.balanceUsd||0,ne=Number.isFinite(oe.balanceFormatted)?oe.balanceFormatted:0,le=Ee>0?Ee:(l[oe.symbol]||0)*ne;return{tokenAddress:oe.address,tokenSymbol:oe.symbol,tokenDisplaySymbol:Pn(oe),tokenDisplayName:ko(oe),tokenDecimals:oe.decimals,chainId:oe.chainId,chainDisplayName:Hn(oe),balance:oe.balance.toString(),balanceFormatted:oe.balanceFormatted,usdValue:le,logoURI:oe.logoURI}}),...i].filter(oe=>oe.balanceFormatted>0),[S,L,l,i]),O=o.useMemo(()=>te.reduce((oe,Ee)=>oe+Ee.usdValue,0),[te]),{pendingDeposits:R}=Js({chainIds:$,enabled:!!C}),ae=o.useMemo(()=>a.reduce((oe,Ee)=>oe+Ee.totalValue,0),[a]),ye=O+ae,ke=o.useMemo(()=>{const oe=[];O>0&&oe.push(`${ln(O)} idle`);for(const Ee of a){const ne=r.find(le=>le.sectionTitle===Ee.title)?.label||Ee.title.toLowerCase();oe.push(`${ln(Ee.totalValue)} ${ne}`)}return oe.join(" \xB7 ")},[O,a,r]),he=o.useCallback(oe=>{p?p(oe):B(oe)},[p]),ge=o.useCallback(()=>{B(null)},[]),be=o.useCallback(()=>{B(null),u?.()},[u]),Me=o.useCallback(()=>{if(!v.current)return;const oe=v.current.getBoundingClientRect(),Ee=window.innerHeight-oe.bottom-un,ne=oe.top-un,le=Ee>=400||Ee>=ne?"below":"above",Je=Math.max(un,Math.min(oe.right-es,window.innerWidth-es-un)),Ye=le==="below"?oe.bottom+un:oe.top-un;I({top:Ye,left:Je,placement:le})},[]);o.useLayoutEffect(()=>{D&&Me()},[D,Me]),o.useEffect(()=>{if(!D)return;const oe=le=>{v.current&&!v.current.contains(le.target)&&z.current&&!z.current.contains(le.target)&&b(!1)},Ee=le=>{le.key==="Escape"&&b(!1)},ne=()=>Me();return document.addEventListener("mousedown",oe),document.addEventListener("keydown",Ee),window.addEventListener("scroll",ne,{passive:!0}),window.addEventListener("resize",Me),()=>{document.removeEventListener("mousedown",oe),document.removeEventListener("keydown",Ee),window.removeEventListener("scroll",ne),window.removeEventListener("resize",Me)}},[D,Me]);const Se=g?.mode==="7702",Ve=Se?P||C:T||C,me=o.useCallback(()=>{g?.setMode&&g.setMode(Se?"ondemand":"7702")},[g,Se]);if(typeof window>"u")return null;const Ne=e.jsxs("button",{ref:v,onClick:()=>b(!D),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:F?ee.hoverBg:"#ffffff",border:F?`1px solid ${ee.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:'"Helvetica Neue", sans-serif',color:F?ee.textPrimary:"#111827",transition:"all 150ms ease",boxShadow:F?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[e.jsx("span",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:M,flexShrink:0}}),e.jsxs("span",{children:[t," Account"]}),k&&e.jsxs("span",{style:{color:F?ee.textSecondary:"#6b7280"},children:["\xB7 ",ln(ye)]}),e.jsx("span",{style:{fontSize:"10px",color:F?ee.textSecondary:"#9ca3af",transform:D?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),Le=D?Bn.createPortal(e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:9998},onClick:()=>b(!1)}),e.jsx("div",{ref:z,style:{position:"fixed",top:U.placement==="below"?`${U.top}px`:"auto",bottom:U.placement==="above"?`${window.innerHeight-U.top}px`:"auto",left:`${U.left}px`,width:`${es}px`,maxHeight:"80vh",backgroundColor:F?ee.shell:"#ffffff",border:F?`1px solid ${ee.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:F?"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(Qr,{appName:t,status:n,statusLabel:s,totalUsdValue:ye,breakdownSubtitle:ke,address:f?Ve:C,spiceAssets:te,spiceAssetsLoading:Z,pendingDeposits:R,customSections:a,onDepositClick:x,onWithdrawClick:y,onCompleteDeposit:he,primaryColor:M,dk:ee,dark:F,showModeToggle:f,isEmbeddedMode:Se,onModeToggle:me})}),e.jsx("style",{children:`
|
|
115
115
|
@keyframes accountDisplayFadeIn {
|
|
116
116
|
from { opacity: 0; transform: translateY(-4px); }
|
|
117
117
|
to { opacity: 1; transform: translateY(0); }
|
package/dist/index.js
CHANGED
|
@@ -111,7 +111,7 @@ import{jsxs as l,jsx as e,Fragment as tn}from"react/jsx-runtime";import jt,{useS
|
|
|
111
111
|
from { transform: rotate(0deg); }
|
|
112
112
|
to { transform: rotate(360deg); }
|
|
113
113
|
}
|
|
114
|
-
`})]})},Oa=({color:t})=>l("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",style:{marginTop:"1px",flexShrink:0},children:[e("circle",{cx:"7",cy:"7",r:"6.5",stroke:t,strokeWidth:"1.2"}),e("path",{d:"M7 6v4",stroke:t,strokeWidth:"1.2",strokeLinecap:"round"}),e("circle",{cx:"7",cy:"4.5",r:"0.7",fill:t})]}),Va=({isOpen:t,onClose:n,lockBatches:o,lockTokenSymbol:s,lockTokenLogoURI:a,destinationInputHook:i,sourceAssetInputHook:r,lockDurationHook:c,lockChainId:d,durationOptions:h,votingPowerEstimate:p,sourceChains:f,sourceAssets:x=[],escrowAddress:u,includeWalletAssets:g=!1,destinationTokenAddress:w,onLockSuccess:m,onLockExecute:I,sourceToDestinationConversionRate:z,estimatedOutputAmount:C,onAddFunds:y,styles:R,dark:L=!1})=>{const{theme:S,dark:v,primaryColor:P,dk:b}=Ze(R,L),k=S.typography.fontFamily,j=Dt(Ft),W=(j?.mode||"7702")!=="7702",T=v?b.cardBg:R?.assetSelector?.backgroundColor||R?.secondaryBackground||"#e9e9e9",D=v?`1px solid ${b.cardBorder}`:"0.5px solid #A8A8A7",J=v?"12px":"6px",q=v?b.textPrimary:"#111827",H=v?b.textSecondary:"#6b7280",V=xe(()=>({...R,assetSelector:{...R?.assetSelector,backgroundColor:v?b.cardBg:R?.assetSelector?.backgroundColor,borderRadius:v?"12px":R?.assetSelector?.borderRadius},secondaryBackground:v?b.cardBg:R?.secondaryBackground}),[R,v]),$=xe(()=>v?{...S,colors:{...S.colors,secondary:b.cardBg,surfaceHover:b.hoverBg,border:b.cardBorder,borderHover:b.inputBorder}}:S,[v,S]),[O,M]=A(null),[re,ye]=A(0),ke=c?.selectedDurationIdx??re,pe=c?.setSelectedDurationIdx??ye,[ge,Ce]=A(!1),[De,Ie]=A(null),[Qe,me]=A(!1),[Ne,Pe]=A(!1),[ne,Be]=A(null);qn(),Tn();const{chain:_,address:ae}=nn();_o();const tt=Se(_);te(()=>{tt.current=_},[_]);const Xe=sn(),{isReady:K,isAuthenticated:ue,isConnected:B,address:U,provider:G,actions:he}=Xe,{externalWallet:F,embeddedAddress:Y}=Wo(),{intentStatus:oe,startStatusPolling:de,clearStatus:qe}=So({checkStepStatus:(Q,ie)=>ft.checkStepStatus(Q,ie),retryStep:async(Q,ie)=>{const[We,Ue]=Q.split("/"),Ve=parseInt(Ue||"0",10);await ft.executeStep(We,Ve,ie,{action:"execute"})},maxRetries:3}),{assets:gt,refetch:Re}=Dn({address:U,supportedChains:f,enabled:B&&!W,refetchInterval:3e4}),Je=xe(()=>{if(x.length===0)return gt;const Q=new Set(x.map(ie=>ie.toLowerCase()));return gt.filter(ie=>Q.has(ie.address.toLowerCase()))},[gt,x]),ve=rn(),pt=W?ae:ve,Ct=xe(()=>{if(!g)return[];const Q=new Set,ie=[],We=Ue=>{if(!Ue)return;const Ve=Ue.toLowerCase();Q.has(Ve)||(Q.add(Ve),ie.push(zt(Ue)))};if(w&&We(w),W)for(const Ue of x)We(Ue);return ie},[g,W,w,x]),Te=xe(()=>Ct.map(Q=>Q.toLowerCase()).sort().join(","),[Ct]),At=xe(()=>JSON.stringify([...f||[]].sort()),[f]),[wt,Tt]=A([]),en=Se(0),Lt=fe(async()=>{if(!g||!pt||Ct.length===0){en.current++,Tt([]);return}const Q=++en.current,ie=zt(pt),We=f&&f.length>0?f:[d],Ue=Ct.map(le=>{const be=le.toLowerCase();for(const Ae of We){const Me=je(Ae)?.supportedTokens?.find(Fe=>Fe.address.toLowerCase()===be);if(Me)return{address:le,chainId:Ae,configToken:{decimals:Me.decimals,symbol:Me.symbol,name:Me.name,logo:Me.logo}}}return{address:le,chainId:d}}),Ve=new Map;for(const le of Ue){const be=Ve.get(le.chainId)||[];be.push(le),Ve.set(le.chainId,be)}const bt=async(le,be)=>{try{const Ae=await In(le,{address:be.address,abi:Rt,functionName:"balanceOf",args:[ie]});let Me,Fe,ze,we;if(be.configToken)Me=be.configToken.decimals,Fe=be.configToken.symbol,ze=be.configToken.name,we=be.configToken.logo;else{const[E,X,Ee]=await Promise.all([In(le,{address:be.address,abi:Rt,functionName:"decimals",args:[]}).catch(()=>18),In(le,{address:be.address,abi:Rt,functionName:"symbol",args:[]}).catch(()=>"TOKEN"),In(le,{address:be.address,abi:Rt,functionName:"name",args:[]}).catch(()=>"TOKEN")]);Me=Number(E),Fe=X,ze=Ee}const N=!!w&&be.address.toLowerCase()===w.toLowerCase()&&be.chainId===d;N&&a&&(we=a),N&&s&&!be.configToken&&(Fe==="TOKEN"&&(Fe=s),ze==="TOKEN"&&(ze=s));const Z=parseFloat((Number(Ae)/Math.pow(10,Me)).toFixed(6));return{address:be.address,name:ze,symbol:Fe,decimals:Me,balance:Ae,balanceFormatted:Z,balanceUsd:0,logoURI:we,isNative:!1,chainId:be.chainId}}catch{return null}},ee=await Promise.all(Array.from(Ve.entries()).map(async([le,be])=>{let Ae;try{Ae=lt(le)}catch{return[]}const Me=[],Fe=[];for(const we of be){const N=Me.length;Me.push({address:we.address,abi:Rt,functionName:"balanceOf",args:[ie]}),we.configToken||Me.push({address:we.address,abi:Rt,functionName:"decimals",args:[]},{address:we.address,abi:Rt,functionName:"symbol",args:[]},{address:we.address,abi:Rt,functionName:"name",args:[]}),Fe.push({start:N,item:we})}let ze=null;try{ze=await Ae.multicall({contracts:Me})}catch{ze=null}return ze?Fe.map(({start:we,item:N})=>{const Z=ze[we],E=Z?.status==="success"?Z.result:0n;let X,Ee,rt,st;if(N.configToken)X=N.configToken.decimals,Ee=N.configToken.symbol,rt=N.configToken.name,st=N.configToken.logo;else{const Ye=ze[we+1],dt=ze[we+2],ct=ze[we+3];X=Ye?.status==="success"?Number(Ye.result):18,Ee=dt?.status==="success"?dt.result:"TOKEN",rt=ct?.status==="success"?ct.result:Ee}const Le=!!w&&N.address.toLowerCase()===w.toLowerCase()&&N.chainId===d;Le&&a&&(st=a),Le&&s&&!N.configToken&&(Ee==="TOKEN"&&(Ee=s),rt==="TOKEN"&&(rt=s));const ht=parseFloat((Number(E)/Math.pow(10,X)).toFixed(6));return{address:N.address,name:rt,symbol:Ee,decimals:X,balance:E,balanceFormatted:ht,balanceUsd:0,logoURI:st,isNative:!1,chainId:N.chainId}}):(await Promise.all(be.map(we=>bt(Ae,we)))).filter(we=>we!==null)}));Q===en.current&&Tt(ee.flat())},[g,pt,Te,At,d,w,a,s]);te(()=>{if(!g){Tt([]);return}Lt();const Q=setInterval(()=>{Lt()},15e3);return()=>clearInterval(Q)},[Lt,g]);const it=fe(()=>{Lt()},[Lt]),Ot=xe(()=>wt.filter(Q=>Q.balance>0n),[wt]),Mt=xe(()=>{if(W)return Ot.map(ie=>({...ie,_source:"wallet"}));if(!g)return Je;const Q=[];for(const ie of Ot)Q.push({...ie,_source:"wallet"});for(const ie of Je)Q.push({...ie,_source:"spice"});return Q},[W,g,Ot,Je]),xt=Se(null),It=Se(null);te(()=>{It.current=O},[O]),te(()=>{t||(M(null),Ie(null),Ce(!1),Pe(!1),Be(null),me(!1),qe())},[t,qe]),te(()=>{i&&i.assetAmount!==(O?.amount||"")&&M(Q=>Q&&{...Q,amount:i.assetAmount})},[i?.assetAmount]),te(()=>{r&&r.assetAmount!==(O?.amount||"")&&M(Q=>Q&&{...Q,amount:r.assetAmount})},[r?.assetAmount]),te(()=>{if(!W&&oe?.overallStatus==="success"&&oe.intentId&&xt.current!==oe.intentId&&U&&oe.steps.find(Q=>Q.transactionHash)?.transactionHash){xt.current=oe.intentId;const Q=It.current;if(!Q?.asset||!Q.amount||Q.asset._source==="wallet"||at(Q.amount,Q.asset.decimals)===0n)return;Re()}},[oe,U,d,Re,W]);const $e=parseFloat(O?.amount||"")||0,mt=xe(()=>O?.asset?O.asset._source==="wallet"?O.asset.balanceFormatted??0:Je.find(Q=>Q.address.toLowerCase()===O.asset.address.toLowerCase()&&Q.chainId===O.asset.chainId)?.balanceFormatted??0:0,[O?.asset,Je]),Et=$e>0&&$e>mt,vt=c?.selectedDuration??h[ke]??h[0],kt=xe(()=>!O?.asset||!w?!1:O.asset.address.toLowerCase()===w.toLowerCase()&&O.asset.chainId===d,[O?.asset,w,d]),Vt=xe(()=>$e<=0?0:kt?$e:!z||z<=0?0:$e/z,[$e,z,kt]),se=xe(()=>Vt<=0?null:Vt.toLocaleString(void 0,{maximumFractionDigits:2}),[Vt]),ce=p&&Vt>0&&vt?p(Vt,vt.months):void 0,He=xe(()=>$e<=0?"$0.00":kt&&z?($e*z).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!z||z<=0?"$0.00":$e.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[$e,z,kt]),nt=xe(()=>{if(!se)return null;const Q=parseFloat(se.replace(/,/g,""));return kt&&z?(Q*z).toLocaleString(void 0,{maximumFractionDigits:2}):z?(Q*z).toLocaleString(void 0,{maximumFractionDigits:2}):null},[se,z,kt]),ut=fe(Q=>{M(ie=>({asset:Q,amount:ie?.asset?.address===Q.address&&ie?.asset?.chainId===Q.chainId&&ie.amount||""})),Ie(null),r?.setSelectedAsset&&r.setSelectedAsset({symbol:Q.symbol,address:Q.address,decimals:Q.decimals,chainId:Q.chainId})},[r?.setSelectedAsset]),yt=fe(Q=>{M(ie=>ie&&{...ie,amount:Q}),Ie(null),i&&i.setAssetAmount(Q),r&&r.setAssetAmount(Q)},[i,r]),ot=fe(()=>{if(typeof o=="function"){if(!O?.asset||!O.amount)throw new Error("Select an asset and enter an amount");return o({asset:O.asset,amount:O.amount,amountWei:at(O.amount,O.asset.decimals)})}return o},[o,O]),Ge=fe(async()=>{const Q=W&&Y||U;if(!B||!Q)throw new Error("Please connect your wallet to continue");const ie=ot();if(ie.length===0)throw new Error("No lock batches configured");if(!K||!ue)throw new Error(`Please authenticate with ${G||"wallet provider"} to continue`);const We=[...ie],Ue=[...new Set(We.map(we=>we.chainId))],Ve=[];for(const we of Ue){const N=lt(we),Z=Fn(we),E=await Gn(Q,N),X=await he.signAuthorization({contractAddress:Z,chainId:we,nonce:Number(E)});Ve.push(X)}const bt=Jn(We),ee=Math.floor(Date.now()/1e3)+60*10,le=bt.map(we=>we.hash),be=eo(to([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,BigInt(ee),le])),Ae=await he.signMessage({raw:be}),Me=typeof Ae=="string"?Ae:Ae.signature;if(!Me)throw new Error("Failed to sign intent authorization");const Fe={mode:"7702",signatureType:"ecdsa",signature:Me,nbf:0,exp:ee,chainBatches:bt.map((we,N)=>({hash:we.hash,chainId:we.chainId,tokenTransfers:We[N].tokenTransfers??[],calls:we.calls}))},ze=await ft.createAction({user:Q,chainAuthorizations:Ve.map(we=>({r:we.r,s:we.s,yParity:we.yParity,address:we.address,chainId:Number(we.chainId),nonce:Number(we.nonce)})),intents:[Fe]});if(ze){const we=Xn(We,Nt),[N,Z]=ze.intentIds[0].split("/"),E=parseInt(Z||"0",10);de(ze.intentIds[0],we);for(let X=0;X<We.length;X++)await ir(()=>ft.executeStep(N,E,X,{action:"execute"}))}},[ot,Xe,de,W,Y]),Wt=fe(async()=>{if(!O?.asset||!O.amount)throw new Error("Select an asset and enter an amount");if(!U||!ve)throw new Error("Embedded wallet not connected");const Q=O.asset,ie=at(O.amount,Q.decimals),We=u||Fn(d),Ue=await he.getEthereumProvider();await Ue.request({method:"wallet_switchEthereumChain",params:[{chainId:`0x${d.toString(16)}`}]});const Ve=je(d),bt=Mn({account:ve,transport:Wn(Ue),chain:Ve?.viemChain});let ee;if(Q.isNative||_e(Q.address))ee=await bt.sendTransaction({to:We,value:ie,chain:Ve?.viemChain});else{const le=qt({abi:Rt,functionName:"transfer",args:[We,ie]});ee=await bt.sendTransaction({to:Q.address,data:le,chain:Ve?.viemChain})}if((await lt(d).waitForTransactionReceipt({hash:ee,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to escrow failed");await Re(),it(),await Ge()},[O,U,ve,he,u,d,Ge,Re,it]),Pt=fe(async()=>{if(!O?.asset||!O.amount)throw new Error("Select an asset and enter an amount");if(!ae||!F)throw new Error("Please connect your external wallet to continue");if(!(ve||Y))throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");if(I){const Me=ot();if(Me.length===0)throw new Error("No lock batches configured");const Fe=O.asset,ze=at(O.amount,Fe.decimals),we=await I({asset:Fe,amount:O.amount,amountWei:ze,lockDurationMonths:vt?.months??0,chainBatches:Me});we&&m?.(we);return}const Q=O.asset,ie=at(O.amount,Q.decimals),We=Q.chainId,Ue=u||un,Ve=await F.getEthereumProvider();let bt=null;try{const Me=await Ve.request({method:"eth_chainId"});bt=parseInt(Me,16)}catch{bt=null}if(bt!==We)try{await Ve.request({method:"wallet_switchEthereumChain",params:[{chainId:`0x${We.toString(16)}`}]})}catch(Me){if(Me?.code===4902||Me?.message?.includes("Unrecognized chain ID")){const Fe=je(We);Fe&&await Ve.request({method:"wallet_addEthereumChain",params:[{chainId:`0x${We.toString(16)}`,chainName:Fe.name||`Chain ${We}`,nativeCurrency:Fe.nativeCurrency||{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:[Fe.rpcUrl],blockExplorerUrls:Fe.blockExplorer?[Fe.blockExplorer]:void 0}]})}else throw Me}const ee=je(We),le=Mn({account:ae,chain:ee?.viemChain,transport:Wn(Ve)}),be=Xt(Q.address),Ae=Q.isNative||_e(be)?await le.sendTransaction({to:Ue,value:ie,chain:ee?.viemChain}):await le.sendTransaction({to:be,data:qt({abi:Rt,functionName:"transfer",args:[Ue,ie]}),chain:ee?.viemChain});if((await lt(We).waitForTransactionReceipt({hash:Ae,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Escrow deposit failed");await Ge()},[O,F,ae,ve,Y,u,I,ot,vt,m,Ge]),Qt=fe(async()=>{if(!O?.asset||!O.amount)throw new Error("Select an asset and enter an amount");if(!ae||!F)throw new Error("Please connect your external wallet to continue");const Q=ot();if(Q.length===0)throw new Error("No lock batches configured");const ie=Q.find(be=>be.chainId===d)||Q[0];if(!ie)throw new Error("No lock batch for lock chain");const We=await F.getEthereumProvider();let Ue=null;try{const be=await We.request({method:"eth_chainId"});Ue=parseInt(be,16)}catch{Ue=null}if(Ue!==d)try{await We.request({method:"wallet_switchEthereumChain",params:[{chainId:`0x${d.toString(16)}`}]})}catch(be){if(be?.code===4902||be?.message?.includes("Unrecognized chain ID")){const Ae=je(d);Ae&&await We.request({method:"wallet_addEthereumChain",params:[{chainId:`0x${d.toString(16)}`,chainName:Ae.name||`Chain ${d}`,nativeCurrency:Ae.nativeCurrency||{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:[Ae.rpcUrl],blockExplorerUrls:Ae.blockExplorer?[Ae.blockExplorer]:void 0}]})}else throw be}const Ve=je(d),bt=Mn({account:ae,chain:Ve?.viemChain,transport:Wn(We)}),ee=lt(d);let le;for(const be of ie.calls){const Ae=await bt.sendTransaction({to:be.to,data:be.data,value:be.value,chain:Ve?.viemChain});if((await ee.waitForTransactionReceipt({hash:Ae,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Lock transaction failed");le=Ae}le&&m?.(le)},[O,F,ae,ot,d,m]);te(()=>{if(oe?.overallStatus==="success"){const Q=oe.steps.find(ie=>ie.transactionHash);m?.(Q?.transactionHash)}},[oe?.overallStatus,m]);const Ht=g&&O?.asset?._source==="wallet"&&O?.asset?.chainId===d,Yt=fe(async()=>{if(!O?.asset||$e<=0){Ie("Select an asset and enter an amount");return}if(Et){Ie("Insufficient balance. Add more assets.");return}Ce(!0),Ie(null);const Q=ie=>{console.error("[SpiceLockModal] lock failed:",ie);const We=on(ie,""),Ue=typeof ie?.shortMessage=="string"?ie.shortMessage:typeof ie?.message=="string"?ie.message:"";Ie(We||Ue||"Transaction failed. Please try again.")};if(W){if(kt){try{await Qt()}catch(ie){Q(ie)}finally{Ce(!1)}return}me(!0);try{await Pt()}catch(ie){Q(ie)}finally{Ce(!1)}return}me(!0);try{Ht&&!kt?await Wt():await Ge()}catch(ie){Q(ie)}finally{Ce(!1)}},[O,$e,Et,W,Pt,Qt,Ht,kt,Wt,Ge]),Jt=!!O?.asset&&$e>0&&!Et&&!ge,mn=l("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[e(Oa,{color:H}),l("p",{style:{fontSize:"13px",color:H,margin:0,lineHeight:"1.5"},children:["Add ",s," by converting assets from your account"]})]});if(!t)return null;const cn={backgroundColor:T,border:D,borderRadius:J,padding:"16px",marginBottom:"16px"};return e(Gt,{isOpen:t,onClose:n,title:`Add ${s} to your account`,subtitle:mn,styles:R,dark:v,footerLinkText:"Spicenet accounts \u2192",overlayContent:Ne?e("div",{}):void 0,children:l("div",{style:{padding:"0 24px 8px 24px",position:"relative"},children:[l("div",{style:{marginBottom:"12px"},children:[y&&e("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:l("button",{onClick:y,style:{background:"none",border:"none",cursor:"pointer",padding:0,display:"flex",alignItems:"center",gap:"4px",color:P,fontSize:"12px",fontWeight:500,fontFamily:k,textDecoration:"underline",textUnderlineOffset:"2px"},children:["Add Funds",l("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:P,strokeWidth:"1.8",children:[e("circle",{cx:"6",cy:"6",r:"5"}),e("path",{d:"M6 4v4M4 6h4",strokeLinecap:"round"})]})]})}),e(Nn,{assets:Mt,selectedAsset:O??void 0,onAssetSelect:ut,onAmountChange:yt,label:"Amount",showBalance:!0,showMaxButton:!0,theme:$,styles:V}),e("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:H,fontFamily:k},children:He})]}),l("div",{style:cn,children:[l("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:v?`1px solid ${b.cardBorder}`:"1px solid #e5e7eb"},children:[l("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[a?e("img",{src:a,alt:s,style:{width:"32px",height:"32px",borderRadius:"50%",objectFit:"cover"}}):e("div",{style:{width:"32px",height:"32px",borderRadius:"50%",backgroundColor:v?b.inputBg:"#d1d5db",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:700,color:q},children:s.slice(0,2)}),e("span",{style:{fontSize:"16px",fontWeight:600,color:q,fontFamily:k},children:s})]}),l("div",{style:{textAlign:"right"},children:[e("div",{style:{fontSize:"22px",fontWeight:700,color:q,fontFamily:k,lineHeight:1.1},children:se??"0.00"}),l("div",{style:{fontSize:"12px",color:H,fontFamily:k,marginTop:"2px"},children:["~$",nt??"0.00"]})]})]}),l("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:v?`1px solid ${b.cardBorder}`:"1px solid #e5e7eb"},children:[l("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[e("span",{style:{fontSize:"15px",fontWeight:500,color:H,fontFamily:k},children:"Lock Duration"}),e("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:e("path",{d:"M4 6L8 10L12 6",stroke:H,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),e(Ua,{options:h,selectedIndex:ke,onSelect:pe,primaryColor:P,dark:v,textPrimary:q,textSecondary:H})]}),l("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[e(Pa,{durationMonths:vt?.months,fontFamily:k,dark:v,textPrimary:q,textSecondary:H}),p&&e(Ha,{votes:ce,fontFamily:k,dark:v,textPrimary:q,textSecondary:H})]})]}),De&&e("div",{style:{marginBottom:"12px",padding:"10px 14px",backgroundColor:v?"rgba(239,68,68,0.12)":"#fef2f2",border:`1px solid ${v?"rgba(239,68,68,0.3)":"#fecaca"}`,borderRadius:"6px"},children:e("p",{style:{color:"#ef4444",fontSize:"13px",margin:0,fontFamily:k},children:De})}),e(et,{variant:"outline",fullWidth:!0,onClick:Yt,disabled:!Jt,loading:ge,dark:v,styles:{button:{backgroundColor:P}},children:ge?Ht&&!kt?"DEPOSITING...":kt?"LOCKING...":"CONVERTING...":Ht&&!kt?`DEPOSIT ${s}`:kt?`LOCK ${s}`:`CONVERT TO ${s}`}),e(ja,{isOpen:Ne,data:ne,isLocking:ge,lockError:De,onContinue:Yt,onClose:()=>Pe(!1),primaryColor:P,fontFamily:k,dark:v}),oe&&Qe&&e("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:v?b.shell:"white",borderRadius:J,padding:"16px 0"},children:e(On,{type:"deposit",isOpen:!!oe&&oe.overallStatus!=="processing",isProcessing:ge||oe?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{qe(),me(!1),Yt()},onNewTx:()=>{qe(),me(!1),M(null),xt.current=null,Re(),it()},onClose:()=>{qe(),me(!1)},onComplete:()=>{qe(),me(!1),M(null),xt.current=null,Re(),it()},results:oe?.overallStatus==="success"||oe?.overallStatus==="failed"?oe.steps.map(Q=>({asset:{symbol:O?.asset?.symbol||s,address:O?.asset?.address||""},txHash:Q.transactionHash||"",success:Q.status==="success",amount:O?.amount})):void 0,chainName:Nt(d),explorerUrl:kn(d,"").replace(/\/tx\/.*$/,"")||void 0,theme:S,styles:R,dark:v})})]})})},Dr=({variant:t,destinationSymbol:n,destinationLogoURI:o,destinationDecimals:s,primaryColor:a,fontFamily:i,textPrimary:r,textSecondary:c,cardBg:d,cardBorder:h,dk:p,dark:f,isQuoting:x,quoteError:u,estimatedOutput:g,paymentAmount:w,needsSwap:m,exactOutputSwap:I,adjustable:z=!1,maxAmount:C,onAmountChange:y})=>t==="supply"?e("div",{style:{backgroundColor:d,border:`1px solid ${h}`,borderRadius:"12px",padding:"14px 16px",marginBottom:"16px"},children:l("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[l("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[e(zr,{symbol:n,logoURI:o,primaryColor:a,size:28}),l("span",{style:{fontSize:"13px",fontWeight:500,color:c,fontFamily:i},children:["Estimated ",n]})]}),e("div",{style:{textAlign:"right"},children:x?e("span",{style:{fontSize:"14px",color:c,fontFamily:i},children:"Quoting..."}):u?e("span",{style:{fontSize:"13px",color:"#ef4444",fontFamily:i},children:"Quote failed"}):g?l("span",{style:{fontSize:"16px",fontWeight:600,color:r,fontFamily:i},children:["\u2248 ",g]}):e("span",{style:{fontSize:"14px",color:c,fontFamily:i},children:"\u2014"})})]})}):e(Qa,{destinationSymbol:n,destinationLogoURI:o,destinationDecimals:s,primaryColor:a,fontFamily:i,textPrimary:r,textSecondary:c,cardBg:d,cardBorder:h,dk:p,dark:f,paymentAmount:w||"0",needsSwap:m,exactOutputSwap:I,isQuoting:x,adjustable:z,maxAmount:C,onAmountChange:y}),zr=({symbol:t,logoURI:n,primaryColor:o,size:s})=>n?e("img",{src:n,alt:t,style:{width:s,height:s,borderRadius:"50%",objectFit:"cover"}}):e("div",{style:{width:s,height:s,borderRadius:"50%",backgroundColor:`${o}22`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:s<30?"11px":"12px",fontWeight:700,color:o},children:t.slice(0,2)}),Qa=({destinationSymbol:t,destinationLogoURI:n,destinationDecimals:o,primaryColor:s,fontFamily:a,textPrimary:i,textSecondary:r,cardBg:c,cardBorder:d,dk:h,dark:p,paymentAmount:f,needsSwap:x,exactOutputSwap:u,isQuoting:g,adjustable:w,maxAmount:m,onAmountChange:I})=>{const z='"IBM Plex Mono", monospace',C=parseFloat(f||"0"),y=m?parseFloat(m):0,[R,L]=A(f||""),S=Se(null),[v,P]=A(null),[b,k]=A(null);te(()=>{w||L(f||"")},[f,w]);const j=D=>{let J=D;J.startsWith(".")&&(J="0"+J);const q=ar(J);let H=q;m&&parseFloat(q)>parseFloat(m)&&(H=m),L(H),S.current&&clearTimeout(S.current),S.current=setTimeout(()=>I?.(H),300)},W=D=>{if(!y)return;if(D===100){L(m||y.toString()),S.current&&clearTimeout(S.current),I?.(m||y.toString());return}const J=10**o,q=(Math.floor(y*D/100*J)/J).toString();L(q),S.current&&clearTimeout(S.current),I?.(q)},T=y>0?parseFloat(R||"0")/y*100:0;return te(()=>()=>{S.current&&clearTimeout(S.current)},[]),l("div",{style:{backgroundColor:c,border:`1px solid ${d}`,borderRadius:p?"12px":"6px",padding:"16px",marginBottom:"16px"},children:[l("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[l("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[e(zr,{symbol:t,logoURI:n,primaryColor:s,size:32}),l("div",{children:[e("span",{style:{fontSize:"14px",fontWeight:600,color:i,fontFamily:a},children:"Payment"}),e("div",{style:{fontSize:"12px",color:r,fontFamily:a,marginTop:"2px"},children:t})]})]}),l("div",{style:{textAlign:"right"},children:[w?e("input",{type:"text",value:R,onChange:D=>j(D.target.value),placeholder:"0.0",style:{fontSize:"20px",fontWeight:700,color:i,fontFamily:z,lineHeight:1.1,backgroundColor:"transparent",border:"none",outline:"none",padding:0,width:"120px",textAlign:"right"}}):e("div",{style:{fontSize:"20px",fontWeight:700,color:i,fontFamily:z,lineHeight:1.1},children:C>0?f:"0.00"}),e("div",{style:{fontSize:"12px",color:r,fontFamily:z,marginTop:"2px"},children:t}),w&&y>0&&e("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((D,J)=>{const q=Math.abs(T-D)<1,H=J===4,V=D/100,$=v===D,O=b===D;return e("button",{onClick:()=>W(D),onMouseEnter:()=>P(D),onMouseLeave:()=>{P(null),k(null)},onMouseDown:()=>k(D),onMouseUp:()=>k(null),title:`${D}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:q?1:$?.8:.5,transform:O?"scale(0.85)":$?"scale(1.15)":"scale(1)",transition:"all 0.15s ease"},children:l("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[e("circle",{cx:"7",cy:"7",r:"6.84375",fill:H?s:"none",stroke:H?s:p?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!H&&V>0&&e("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${V>.5?1:0} 1 ${7+6.84375*Math.sin(V*2*Math.PI)} ${7-6.84375*Math.cos(V*2*Math.PI)} Z`,fill:p?h?.textSecondary||"#9ca3af":"#3C3E42"})]})},D)})})]})]}),x&&u&&!g&&e("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:p?`1px solid ${h?.cardBorder||d}`:"1px solid #e5e7eb",display:"flex",justifyContent:"flex-end"},children:l("span",{style:{fontSize:"11px",color:r,fontFamily:a,opacity:.7},children:["via ",u.venue]})})]})};function Nr(t,n,o){const s=t.address.toLowerCase()===n,a=t.chainId===o,i=t._source==="wallet";return i&&s&&a?0:i&&a?1:!i&&s?2:!i&&a?3:4}function Ya(t){const{address:n,destinationToken:o,supportedSourceAssets:s,sourceChains:a,enabled:i}=t,r=rn(),{assets:c,refetch:d}=Dn({address:n,supportedChains:a,enabled:i,refetchInterval:3e4}),h=xe(()=>{if(!s||s.length===0)return c;const u=s.map(g=>g.toLowerCase());return c.filter(g=>u.includes(g.address.toLowerCase()))},[c,s]),[p,f]=A(null);te(()=>{if(!o.address||!r||!i){f(null);return}let u=!1;const g=zt(o.address),w=zt(r),m=lt(o.chainId),I=async()=>{try{const C=await m.multicall({contracts:[{address:g,abi:Ut,functionName:"balanceOf",args:[w]},{address:g,abi:Ut,functionName:"decimals",args:[]},{address:g,abi:Ut,functionName:"symbol",args:[]},{address:g,abi:Ut,functionName:"name",args:[]}]});if(u)return;const y=C[0].status==="success"?C[0].result:0n,R=C[1].status==="success"?Number(C[1].result):o.decimals,L=C[2].status==="success"?C[2].result:o.symbol,S=C[3].status==="success"?C[3].result:o.symbol;y>0n?f({address:g,name:S,symbol:L,decimals:R,balance:y,balanceFormatted:parseFloat((Number(y)/Math.pow(10,R)).toFixed(6)),balanceUsd:0,logoURI:o.logoURI,isNative:!1,chainId:o.chainId}):f(null)}catch{u||f(null)}};I();const z=setInterval(I,15e3);return()=>{u=!0,clearInterval(z)}},[o.address,o.chainId,o.decimals,o.symbol,o.logoURI,r,i]);const x=fe(()=>{if(!o.address||!r)return;const u=lt(o.chainId),g=zt(o.address),w=zt(r);u.multicall({contracts:[{address:g,abi:Ut,functionName:"balanceOf",args:[w]},{address:g,abi:Ut,functionName:"decimals",args:[]}]}).then(m=>{const I=m[0].status==="success"?m[0].result:0n,z=m[1].status==="success"?Number(m[1].result):18;I>0n?f(C=>C?{...C,balance:I,balanceFormatted:parseFloat((Number(I)/Math.pow(10,z)).toFixed(6))}:null):f(null)}).catch(()=>{})},[o.address,o.chainId,r]);return{displayAssets:xe(()=>{const u=[];p&&u.push({...p,_source:"wallet"});for(const w of h)u.push({...w,_source:"spice"});const g=o.address.toLowerCase();return u.sort((w,m)=>Nr(w,g,o.chainId)-Nr(m,g,o.chainId)),u},[p,h,o.address,o.chainId]),filteredSpiceAssets:h,embeddedWalletAddress:r,refreshSpiceAssets:d,refreshWalletAssets:x}}async function Ur(t){const{tokenIn:n,tokenOut:o,amountIn:s,fee:a,chainId:i,config:r}=t;if(s<=0n)throw new Error("amountIn must be greater than 0");const c=(await lt(i).simulateContract({address:r.quoterV2,abi:us,functionName:"quoteExactInputSingle",args:[{tokenIn:n,tokenOut:o,amountIn:s,fee:a,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 Lr(t){const n=t.feeTiers??[100,500,3e3,1e4],o=await Promise.allSettled(n.map(a=>Ur({...t,fee:a})));let s=null;for(let a=0;a<o.length;a++){const i=o[a];i.status==="fulfilled"&&(!s||i.value.amountOut>s.amountOut)&&(s={...i.value,fee:n[a]})}if(!s)throw new Error("No liquidity found for this pair on any fee tier.");return s}const Za=[{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 Ka(t){const{tokenIn:n,tokenOut:o,amountOut:s,fee:a,chainId:i,config:r}=t;if(s<=0n)throw new Error("amountOut must be greater than 0");const c=(await lt(i).simulateContract({address:r.quoterV2,abi:Za,functionName:"quoteExactOutputSingle",args:[{tokenIn:n,tokenOut:o,amount:s,fee:a,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 Xa(t){const n=t.feeTiers??[100,500,3e3,1e4],o=await Promise.allSettled(n.map(a=>Ka({...t,fee:a})));let s=null;for(let a=0;a<o.length;a++){const i=o[a];i.status==="fulfilled"&&(!s||i.value.amountIn<s.amountIn)&&(s={...i.value,fee:n[a]})}if(!s)throw new Error("No liquidity found for this pair on any fee tier.");return s}function Pr(t){return t.type==="swap"}const Ho=.02,qa=[1,8453,42161,10,137,43114,56],Ga="https://api.1inch.dev/swap/v6.0";function Hr(t,n){return fs(t,n)}function jr(t){const n=t?.baseUrl??Ga;return{name:"1inch",chainIds:t?.chainIds??qa,resolve:async(o,s,a)=>{const i=o.maxSlippage??Ho,r=i*100,c=_e(o.tokenIn)?tr:o.tokenIn,d=_e(o.tokenOut)?tr:o.tokenOut,h=_e(o.tokenIn);try{const p=new URL(`${n}/${s}/swap`);p.searchParams.set("src",c),p.searchParams.set("dst",d),p.searchParams.set("amount",o.amountIn.toString()),p.searchParams.set("from",a),p.searchParams.set("slippage",r.toString()),p.searchParams.set("disableEstimate","true"),p.searchParams.set("allowPartialFill","false");const f={Accept:"application/json"};t?.apiKey&&(f.Authorization=`Bearer ${t.apiKey}`);const x=await fetch(p.toString(),{headers:f});if(!x.ok)throw new Ke("VENUE_API_ERROR",`[1inchVenue] API returned ${x.status} for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${s}`,{venue:"1inch",chainId:s,tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountIn:o.amountIn.toString(),cause:`HTTP ${x.status}`});const u=await x.json();if(!u.dstAmount||!u.tx)return console.warn(`[1inchVenue] No route data for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${s}`),null;const g=BigInt(u.dstAmount);if(g<=0n)return console.warn(`[1inchVenue] Zero output for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${s}`),null;const w=Hr(g,i),m=[];return u.tx.to&&!h&&m.push({to:o.tokenIn,value:0n,data:qt({abi:Ut,functionName:"approve",args:[u.tx.to,o.amountIn]})}),m.push({to:u.tx.to,value:BigInt(u.tx.value||"0"),data:u.tx.data}),{venue:"1inch",amountOut:g,amountOutMinimum:w,calls:m}}catch(p){if(p instanceof Ke)throw p;const f=p instanceof Error?p.message:String(p);throw new Ke("VENUE_API_ERROR",`[1inchVenue] Exception for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${s}: ${f}`,{venue:"1inch",chainId:s,tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountIn:o.amountIn.toString(),cause:f})}}}}const Or=[4114,5115],jo={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425"},Vr={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453]};function Qr(t){return{name:"satsuma",chainIds:t.chainIds??Or,resolve:async(n,o,s)=>{const a=n.maxSlippage??Ho,i=_e(n.tokenIn);let r;try{r=await Lr({tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn,chainId:o,config:{swapRouter:t.swapRouter,quoterV2:t.quoterV2},feeTiers:t.feeTiers})}catch{return console.warn(`[SatsumaVenue] No viable fee tier for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}.`),null}const c=Hr(r.amountOut,a),d=[];return i||d.push({to:n.tokenIn,value:0n,data:qt({abi:Ut,functionName:"approve",args:[t.swapRouter,n.amountIn]})}),d.push({to:t.swapRouter,value:i?n.amountIn:0n,data:qt({abi:hs,functionName:"exactInputSingle",args:[{tokenIn:n.tokenIn,tokenOut:n.tokenOut,fee:r.fee,recipient:s,amountIn:n.amountIn,amountOutMinimum:c,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:r.amountOut,amountOutMinimum:c,calls:d}}}}function Yr(t){return{name:"satsuma",chainIds:t.chainIds??Or,resolve:async(n,o,s)=>{const a=n.maxSlippage??Ho,i=_e(n.tokenIn);let r;try{r=await Xa({tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountOut:n.amountOut,chainId:o,config:{swapRouter:t.swapRouter,quoterV2:t.quoterV2},feeTiers:t.feeTiers})}catch{return null}const c=BigInt(Math.round(a*1e4)),d=r.amountIn+r.amountIn*c/10000n,h=[];return h.push({to:t.swapRouter,value:i?d:0n,data:qt({abi:Ja,functionName:"exactOutputSingle",args:[{tokenIn:n.tokenIn,tokenOut:n.tokenOut,fee:r.fee,recipient:s,amountOut:n.amountOut,amountInMaximum:d,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:r.amountIn,amountInMax:d,amountOut:n.amountOut,calls:h}}}}const Ja=[{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 Zr(t){const n=[];t?.customVenues&&n.push(...t.customVenues),t?.satsuma&&n.push(Qr(t.satsuma)),n.push(jr(t?.oneInch));function o(a){return n.find(i=>i.chainIds.includes(a))}async function s(a,i,r){const c=[],d=[];for(const h of a){if(!Pr(h)){c.push(h);continue}const p=o(i);if(!p)throw new Ke("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${i}. Cannot resolve swap ${h.tokenIn} \u2192 ${h.tokenOut}.`,{chainId:i,tokenIn:h.tokenIn,tokenOut:h.tokenOut,amountIn:h.amountIn.toString()});const f=await p.resolve(h,i,r);if(!f)throw new Ke("NO_LIQUIDITY",`${p.name} returned no quote for ${h.tokenIn} \u2192 ${h.tokenOut} on chain ${i}.`,{venue:p.name,chainId:i,tokenIn:h.tokenIn,tokenOut:h.tokenOut,amountIn:h.amountIn.toString()});c.push(...f.calls),d.push(f)}return{calls:c,resolvedSwaps:d}}return{resolveSwapIntents:s,getVenueForChain:o,venues:n}}function $a(t){const n=t?.customVenues??[];async function o(s,a,i){const r=n.filter(d=>d.chainIds.includes(a));if(r.length===0)throw new Ke("NO_SWAP_ROUTE",`No exact-output venue supports chain ${a}`,{chainId:a,tokenIn:s.tokenIn,tokenOut:s.tokenOut});const c=(await Promise.allSettled(r.map(d=>d.resolve(s,a,i)))).filter(d=>d.status==="fulfilled").map(d=>d.value).filter(d=>d!==null);if(c.length===0)throw new Ke("NO_SWAP_ROUTE",`All aggregators failed for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${a}`,{chainId:a,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountOut:s.amountOut.toString()});return c.sort((d,h)=>d.amountIn<h.amountIn?-1:d.amountIn>h.amountIn?1:0),c[0]}return{getQuote:o,venues:n}}function _a(t){const{direction:n,selectedAsset:o,destinationToken:s,chainId:a,recipient:i,paymentAmount:r}=t,[c,d]=A(!1),[h,p]=A(null),[f,x]=A(null),[u,g]=A(null),[w,m]=A(null),[I,z]=A(null),[C,y]=A(null),R=Se(null),L=xe(()=>Zr({satsuma:jo}),[]),S=xe(()=>$a({customVenues:[Yr(jo),Yr(Vr)]}),[]),v=xe(()=>{if(!o?.asset)return null;if(o.asset.chainId===a)return o.asset.address;const W=gn(o.asset.address,a);return W?W.address:null},[o?.asset?.address,o?.asset?.chainId,a]),P=xe(()=>o?.asset?o.asset.address.toLowerCase()===s.address.toLowerCase()&&o.asset.chainId===a?!0:v?v.toLowerCase()===s.address.toLowerCase():!1:!1,[o,s.address,a,v]),b=v?v.toLowerCase()===s.address.toLowerCase():!1,k=n==="output"&&parseFloat(r||"0")===0,j=!!o?.asset&&!P&&!b&&!k;return te(()=>{R.current&&clearTimeout(R.current);const W=n==="input"?o?.amount:r,T=parseFloat(W||"0");if(!j||T<=0||!o?.asset||!i||!v){x(null),g(null),m(null),z(null),y(null),p(null),d(!1);return}return d(!0),R.current=setTimeout(async()=>{try{if(n==="input"){const D=at(o.amount,o.asset.decimals),J=L.getVenueForChain(a);if(!J)throw new Error("No swap venue for this chain");const q=await J.resolve({type:"swap",tokenIn:v,tokenOut:s.address,amountIn:D},a,i);if(!q)throw new Error("No liquidity for this pair");y(q.amountOut),m(q),z(null);const H=hn(q.amountOut,s.decimals),V=parseFloat(H);x(V<.01?V.toPrecision(4):V.toLocaleString(void 0,{maximumFractionDigits:6})),g(null),p(null)}else{const D=at(r||"0",s.decimals),J=await S.getQuote({tokenIn:v,tokenOut:s.address,amountOut:D},a,i);z(J),m(null),y(null),g(parseFloat(hn(J.amountIn,o.asset.decimals)).toFixed(6)),x(null),p(null)}}catch(D){const J=D instanceof Error?D.message:"Failed to get quote";p(J),x(null),g(null),m(null),z(null),y(null)}finally{d(!1)}},500),()=>{R.current&&clearTimeout(R.current)}},[n,j,o?.amount,o?.asset?.address,o?.asset?.decimals,r,v,a,s.address,s.decimals,i,L,S]),{isQuoting:c,quoteError:h,estimatedOutput:f,estimatedInput:u,resolvedSwap:w,exactOutputSwap:I,quoteAmountOut:C,resolvedTokenIn:v,isDirect:b,needsSwap:j,selectedIsEquivalent:P}}const Kr={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Transaction successful!",error:"Transaction failed"},Xr=["signing-delegation","signing-intent","submitting","executing"],ei=({color:t})=>l("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",style:{marginTop:"1px",flexShrink:0},children:[e("circle",{cx:"7",cy:"7",r:"6.5",stroke:t,strokeWidth:"1.2"}),e("path",{d:"M7 6v4",stroke:t,strokeWidth:"1.2",strokeLinecap:"round"}),e("circle",{cx:"7",cy:"4.5",r:"0.7",fill:t})]}),qr=({isOpen:t,onClose:n,destinationToken:o,buildActionCalls:s,buildSpicenetBatch:a,actionLabel:i,amountDirection:r="input",swapDescription:c,directDescription:d,supportedSourceAssets:h,sourceChains:p,paymentAmount:f,amountInputMode:x="fixed",minPaymentAmount:u,maxPaymentAmount:g,onAmountChange:w,styles:m,dark:I,title:z,subtitle:C,onAddFunds:y,onSuccess:R,onError:L})=>{const S=r==="output",{theme:v,dark:P,primaryColor:b,dk:k,palette:j}=Ze(m,I),W=v.typography.fontFamily,T=m?.inputVariant?m.inputVariant==="dark":P,D=j.textPrimary,J=j.textSecondary,q=T?k.cardBg:"#f9fafb",H=T?k.cardBorder:"#e5e7eb",V=m?.button?.backgroundColor??b,$=m?.button?.color??"#0e0d0b",O=T?{...v,colors:{...v.colors,secondary:k.cardBg,surfaceHover:k.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:v,M=o.chainId,re=sn(),{address:ye,isConnected:ke,isReady:pe,isAuthenticated:ge,provider:Ce}=re,{executeGasless:De}=co(),{displayAssets:Ie,filteredSpiceAssets:Qe,embeddedWalletAddress:me,refreshSpiceAssets:Ne,refreshWalletAssets:Pe}=Ya({address:ye,destinationToken:o,supportedSourceAssets:h,sourceChains:p,enabled:t&&!!ye}),ne=xe(()=>Qe.map(ee=>({...ee,_source:"spice"})),[Qe]),Be=S?Ie:ne,[_,ae]=A(null),[tt,Xe]=A(f||""),[K,ue]=A(!1),[B,U]=A(null),[G,he]=A("idle"),[F,Y]=A(""),[oe,de]=A(null),[qe,gt]=A(!1),[Re,Je]=A(null),ve=Se(_),pt=Se(!1),Ct=Se(null);te(()=>{ve.current=_},[_]);const Te=x==="adjustable"?tt:f||"0",At=me||ye,{isQuoting:wt,quoteError:Tt,estimatedOutput:en,resolvedSwap:Lt,exactOutputSwap:it,quoteAmountOut:Ot,resolvedTokenIn:Mt,isDirect:xt,needsSwap:It,selectedIsEquivalent:$e}=_a({direction:r,selectedAsset:_,destinationToken:o,chainId:M,recipient:At,paymentAmount:Te}),mt=S?parseFloat(Te||"0"):parseFloat(_?.amount||"")||0,Et=xe(()=>_?.asset?Qe.find(ee=>ee.address.toLowerCase()===_.asset.address.toLowerCase())?.balanceFormatted??0:0,[_,Qe]),vt=xe(()=>_?.asset?S?$e?mt>_.asset.balanceFormatted:it?parseFloat(hn(it.amountInMax,_.asset.decimals))>_.asset.balanceFormatted:!1:mt>Et:!1,[_,S,$e,mt,it,Et]);te(()=>{t||(ae(null),U(null),ue(!1),he("idle"),Y(""),de(null),gt(!1),Je(null),pt.current=!1,x==="adjustable"&&Xe(f||""),Ct.current&&(Ct.current.abort(),Ct.current=null))},[t]);const kt=fe(ee=>{ae(le=>({asset:ee,amount:le?.asset?.address===ee.address&&le?.asset?.chainId===ee.chainId&&le.amount||""})),U(null)},[]),Vt=fe(ee=>{ae(le=>le&&{...le,amount:ee}),U(null)},[]),se=fe(ee=>{let le=ee;g&&parseFloat(le)>parseFloat(g)&&(le=g),Xe(le),w?.(le),U(null)},[g,w]);fe(ee=>{if(pt.current||!ye)return;const le=ve.current;!le?.asset||!le.amount||le.asset?._source==="wallet"||at(S?Te:le.amount,le.asset.decimals)===0n||(pt.current=!0,Ne())},[ye,M,Ne,S,Te]);const ce=fe(ee=>{he({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[ee.step]||"executing"),Y(ee.message),ee.txHash&&de(ee.txHash)},[]),He=fe(()=>{const ee=at(Te,o.decimals),le={userAddress:me,chainId:M,destinationToken:o.address},be=s(ee,le),Ae={chainId:M,calls:be},Me=_?.asset?._source==="spice",Fe=(ze,we)=>({token:ze,from:"solver",to:me,amount:we});if(ee===0n)return[Ae];if(It&&it){let ze=_.asset.address;if(_.asset.chainId!==M){const Z=_n(_.asset.address)?.deployments.find(E=>E.chainId===M);Z&&(ze=Z.address)}const we=Me?[Fe(ze,it.amountInMax)]:[],N={to:ze,value:0n,data:qt({abi:Ut,functionName:"approve",args:[it.calls[0]?.to,it.amountInMax]})};return[{chainId:M,calls:[N,...it.calls,...be],tokenTransfers:[...we,...Ae.tokenTransfers??[]]}]}if(Me){let ze=o.address;if(_.asset.chainId!==M){const we=_n(_.asset.address)?.deployments.find(N=>N.chainId===M);we&&(ze=we.address)}return[{...Ae,tokenTransfers:[Fe(ze,ee),...Ae.tokenTransfers??[]]}]}return[Ae]},[Te,o,me,M,s,_,It,it]),nt=fe(()=>{if(!_?.asset||!me)return[];const ee=at(_.amount,_.asset.decimals),le={userAddress:me,chainId:M,destinationToken:o.address},be=s(ee,le),Ae=_.asset?._source==="spice";if(!Ae)return[{chainId:M,calls:be}];const Me=(N,Z)=>({token:N,from:"solver",to:me,amount:Z});if(It&&Lt&&Ot&&Mt){const N=s(Ot,le),Z={chainId:M,calls:[...Lt.calls,...N],tokenTransfers:[Me(Mt,ee)]};if(!a)return[Z];const E=a({userAddress:me,destinationChainId:M,deliveryToken:Mt,deliveryAmount:ee});return console.log("[SpiceSupply] buildSupplyChainBatches:swap",{isSpiceSourced:Ae,hasBuildSpicenetBatch:!!a,amountIn:ee.toString(),resolvedTokenIn:Mt,spicenetBatch:E}),E?[E,Z]:[Z]}let Fe=o.address;if(_.asset.chainId!==M){const N=_n(_.asset.address)?.deployments.find(Z=>Z.chainId===M);N&&(Fe=N.address)}const ze={chainId:M,calls:be,tokenTransfers:[Me(Fe,ee)]};if(!a)return[ze];const we=a({userAddress:me,destinationChainId:M,deliveryToken:Fe,deliveryAmount:ee});return console.log("[SpiceSupply] buildSupplyChainBatches:direct",{isSpiceSourced:Ae,hasBuildSpicenetBatch:!!a,amountIn:ee.toString(),deliveryToken:Fe,spicenetBatch:we}),we?[we,ze]:[ze]},[_,me,M,o,s,It,Lt,Ot,Mt,a]),ut=xe(()=>{if(!_?.asset)return o.address;if(_.asset.chainId===M)return _.asset.address;const ee=_n(_.asset.address)?.deployments.find(le=>le.chainId===M);return ee?ee.address:o.address},[_,o.address,M]),yt=fe(async()=>{if(!_?.asset||mt<=0){U("Select an asset and enter an amount");return}if(vt){U("Insufficient balance");return}if(!me){U("Wallet not ready");return}ue(!0),U(null),he("signing-delegation"),Y("Building transaction..."),de(null),pt.current=!1;const ee=new AbortController;Ct.current=ee;try{const le=at(_.amount,_.asset.decimals),be=nt(),Ae=be.some(Me=>Me.tokenTransfers?.length);await De(be,ut,le,ce,ee.signal,Ae?{useCustomTransfers:!0}:void 0),he("success"),Y("Transaction successful!")}catch(le){const be=le instanceof Error?le:new Error(String(le));if(be.name==="AbortError"||ee.signal.aborted){he("idle");return}const Ae=be.message||"Transaction failed";he("error"),Y(Ae),U(Ae),L?.(be)}finally{ue(!1)}},[_,mt,vt,me,ut,nt,De,ce,L]),ot=fe(async()=>{if(mt<0){U("Enter a valid payment amount");return}if(!_?.asset){U("Select a payment source");return}if(vt){U("Insufficient balance");return}if(It&&!it){U("Swap quote not available. Try a different asset.");return}if(!ke||!ye){U("Please connect your wallet to continue");return}if(!pe||!ge){U(`Please authenticate with ${Ce||"wallet provider"} to continue`);return}ue(!0),U(null),gt(!0),Je({status:"processing"});try{const ee=He(),le=ee.some(Fe=>Fe.tokenTransfers?.length),be=at(Te,o.decimals),Ae=_?.asset?.address||o.address,Me=await De(ee,Ae,be,Fe=>{Fe.txHash&&(Je(ze=>({...ze,txHash:Fe.txHash})),de(Fe.txHash))},void 0,le?{useCustomTransfers:!0}:void 0);Je(Fe=>({status:"success",txHash:Fe?.txHash||Me}))}catch(ee){const le=on(ee,"Payment failed. Please try again.");U(le),Je({status:"failed",error:le}),L?.(ee instanceof Error?ee:new Error(le))}finally{ue(!1)}},[mt,_,vt,It,it,ke,ye,pe,ge,Ce,He,Te,o,De,L]);te(()=>{!S&&G==="success"&&oe&&(Ne(),R?.(oe))},[S,G,oe,Ne,R]),te(()=>{if(!S||Re?.status!=="success"||pt.current||!ye)return;pt.current=!0;const ee=ve.current;!ee?.asset||ee.asset?._source==="wallet"||Ne()},[S,Re?.status,ye,Ne]);const Ge=Se(R),Wt=Se(L);te(()=>{Ge.current=R},[R]),te(()=>{Wt.current=L},[L]),te(()=>{S&&(Re?.status==="success"&&Ge.current?.(Re.txHash||""),Re?.status==="failed"&&Wt.current?.(new Error("Payment execution failed")))},[S,Re?.status]);const Pt=fe(()=>{gt(!1),Je(null),ae(null),pt.current=!1,Ne(),Pe()},[Ne,Pe]),Qt=S?!!_?.asset&&mt>=0&&!vt&&!K&&(!It||!!it):!!_?.asset&&mt>0&&!vt&&!K&&(xt||!!Lt&&!wt),Ht=xt?d||`Your ${o.symbol} will be used directly.`:c||"Your assets will be swapped and used in a single atomic transaction.",Yt=P?k.shell:"white",Jt=P?k.buttonBorder:"#0e0d0b",mn=(M?je(M):void 0)?.viemChain?.blockExplorers?.default?.url??"",cn=Xr.indexOf(G),Q=K?(Kr[G]||"EXECUTING...").toUpperCase():G==="success"?"DONE":vt?"INSUFFICIENT BALANCE":i.toUpperCase(),ie=xe(()=>{if(K)return"PAYING...";if(vt&&_?.asset)return`INSUFFICIENT ${_.asset.symbol}`;const ee=mt>0?` ${Te} ${o.symbol}`:"";return It?`SWAP & PAY${ee}`:`PAY${ee}`},[K,vt,_,mt,Te,o.symbol,It]),We=G==="success"?()=>{he("idle"),ae(null),de(null),Ne()}:yt,Ue=G==="success"?!1:!Qt;if(!t)return null;const Ve=S?z||`Pay ${o.symbol}`:i,bt=S?C:l("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[e(ei,{color:J}),e("p",{style:{fontSize:"13px",color:J,margin:0,lineHeight:"1.5"},children:Ht})]});if(S){const ee=Re&&(Re.status==="success"||Re.status==="failed")?[{asset:{symbol:_?.asset?.symbol||o.symbol,address:_?.asset?.address||""},amount:Te,txHash:Re.txHash||"",success:Re.status==="success",error:Re.status==="failed"?Re.error:void 0}]:void 0;return e(Gt,{isOpen:t,onClose:n,title:Ve,subtitle:bt,styles:m,dark:P,footerLinkText:"Spicenet accounts \u2192",children:l("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[y&&e("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:l("button",{onClick:y,style:{background:"none",border:"none",cursor:"pointer",padding:0,display:"flex",alignItems:"center",gap:"4px",color:b,fontSize:"12px",fontWeight:500,fontFamily:W,textDecoration:"underline",textUnderlineOffset:"2px"},children:["Add Funds",l("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:b,strokeWidth:"1.8",children:[e("circle",{cx:"6",cy:"6",r:"5"}),e("path",{d:"M6 4v4M4 6h4",strokeLinecap:"round"})]})]})}),e("div",{style:{marginBottom:"12px"},children:e(Nn,{assets:Be,selectedAsset:_??void 0,onAssetSelect:kt,onAmountChange:()=>{},label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:_?.asset?It?wt?"...":it?`~${parseFloat(hn(it.amountIn,_.asset.decimals)).toFixed(6)}`:void 0:Te??void 0:void 0,dark:P,theme:O,styles:m})}),e(Dr,{variant:"pay",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:b,fontFamily:W,textPrimary:D,textSecondary:J,cardBg:q,cardBorder:H,dk:k,dark:P,isQuoting:wt,quoteError:Tt,estimatedOutput:en,paymentAmount:Te,needsSwap:It,exactOutputSwap:it,adjustable:x==="adjustable",maxAmount:g,onAmountChange:se}),B&&e("div",{style:{marginBottom:"12px",padding:"10px 14px",backgroundColor:j.errorBg,border:`1px solid ${j.errorBorder}`,borderRadius:"6px"},children:e("p",{style:{color:j.errorText,fontSize:"13px",margin:0,fontFamily:W},children:B})}),e(et,{variant:"outline",fullWidth:!0,onClick:ot,disabled:!Qt,loading:K,dark:P,styles:{button:{backgroundColor:b}},children:ie}),Re&&qe&&e("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:P?k.shell:"white",borderRadius:P?"12px":"6px",padding:"16px 0"},children:e(On,{type:"payment",isOpen:Re.status!=="processing",isProcessing:K||Re.status==="processing",closeOnComplete:!1,chainName:Nt(M),explorerUrl:kn(M,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{gt(!1),Je(null),ot()},onNewTx:Pt,onClose:()=>{gt(!1),Je(null)},onComplete:Pt,results:ee,styles:m,dark:P})})]})})}return l(Gt,{isOpen:t,onClose:n,title:Ve,subtitle:bt,dark:P,styles:m,theme:v,children:[e("div",{style:{marginBottom:"16px"},children:e(Nn,{assets:Be,selectedAsset:_||void 0,onAssetSelect:kt,onAmountChange:Vt,disabled:K||G==="success",showBalance:!0,showMaxButton:!0,label:"From Spice Balance",placeholder:"0.00",theme:O,styles:m,dark:T,maxAmount:Et>0?Et.toString():void 0})}),_?.asset&&!xt&&e(Dr,{variant:"supply",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:b,fontFamily:W,textPrimary:D,textSecondary:J,cardBg:q,cardBorder:H,dark:P,isQuoting:wt,quoteError:Tt,estimatedOutput:en}),G!=="idle"&&l("div",{style:{padding:"10px 14px",borderRadius:"10px",marginBottom:"16px",backgroundColor:G==="success"?j.successBg:G==="error"?j.errorBg:q,border:`1px solid ${G==="success"?j.successBorder:G==="error"?j.errorBorder:H}`},children:[l("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[G==="success"?e("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:e("path",{d:"M5 13l4 4L19 7",stroke:j.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):G==="error"?e("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:e("path",{d:"M18 6L6 18M6 6l12 12",stroke:j.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):e(Bn,{size:14,color:b}),e("span",{style:{fontSize:"13px",fontWeight:500,color:G==="success"?j.successText:G==="error"?j.errorText:D,fontFamily:W,flex:1},children:G==="success"?"Transaction successful!":G==="error"?F||"Transaction failed":Kr[G]||F}),G==="success"&&oe&&e("a",{href:`${mn}/tx/${oe}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:b,fontFamily:W,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),G==="error"&&e("button",{onClick:()=>{he("idle"),U(null),setTimeout(yt,50)},style:{background:"none",border:"none",fontSize:"12px",color:b,fontFamily:W,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),cn>=0&&G!=="success"&&G!=="error"&&e("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${J}22`,overflow:"hidden"},children:e("div",{style:{height:"100%",borderRadius:"2px",backgroundColor:b,width:`${(cn+1)/Xr.length*100}%`,transition:"width 400ms ease"}})})]}),B&&G==="idle"&&e("div",{style:{padding:"10px 14px",borderRadius:"10px",backgroundColor:j.errorBg,border:`1px solid ${j.errorBorder}`,marginBottom:"16px"},children:e("p",{style:{fontSize:"13px",color:j.errorText,margin:0,fontFamily:W},children:B})}),e(et,{variant:"outline",fullWidth:!0,disabled:Ue,onClick:We,style:{height:"56px",backgroundColor:Ue?`${V}66`:G==="success"?j.successBg:V,color:G==="success"?j.successText:$,border:`1px solid ${G==="success"?j.successBorder:Jt}`,fontSize:"14px",fontWeight:700,letterSpacing:"2px",fontFamily:'"IBM Plex Mono", monospace',boxShadow:Ue?"none":`3px 3px 0px ${Yt}, 4px 4px 0px ${Jt}`,cursor:Ue?"not-allowed":"pointer",opacity:Ue?.6:1},children:Q})]})},ti=t=>e(qr,{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}),ni=({label:t="Export Wallet",style:n,className:o,onExport:s,onError:a})=>{const[i,r]=A(!1),[c,d]=A(!1),{primaryColor:h}=Ze(),p=Dt(Ft),{isAuthenticated:f}=sn();let x=null;try{x=no()}catch{}let u=null,g=null;try{u=Cs(),g=oo()}catch{u=null,g=null}const w=ro(g),m=fe(async()=>{if(!f){a?.("User is not authenticated. Please log in first.");return}try{if(p?.provider==="dynamic"){if(!u||!w){a?.("Dynamic is not available. Ensure the app is wrapped in a DynamicContextProvider.");return}await u.initExportProcess(!1),s?.();return}if(!x){a?.("Privy is not available. Ensure the app is wrapped in a PrivyProvider.");return}await x.exportWallet(),s?.()}catch(C){const y=C instanceof Error?C.message:"Failed to export wallet";console.error("Export wallet error:",C),a?.(y)}},[w,u,f,a,s,x,p?.provider]),I=!f,z={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?`${h}cc`:i?`${h}ee`:h,transition:"all 150ms ease",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"8px",...n};return l("button",{onClick:m,onMouseEnter:()=>r(!0),onMouseLeave:()=>{r(!1),d(!1)},onMouseDown:()=>d(!0),onMouseUp:()=>d(!1),disabled:I,className:o,style:z,children:[l("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),e("polyline",{points:"17 8 12 3 7 8"}),e("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]}),t]})};function Gr(t){const n=Dt(Ft),o=rn(),s=t?.enabled===!1?void 0:o,a=n?.network?{network:n.network,pollIntervalMs:t?.pollIntervalMs,chainIds:t?.chainIds??n.supportedChainIds}:void 0;return{...vr(s,a),embeddedWalletAddress:o}}const oi=({appName:t,status:n,statusLabel:o,totalUsdValue:s,breakdownSubtitle:a,address:i,dk:r,dark:c=!1,showModeToggle:d,isEmbeddedMode:h=!0,onModeToggle:p})=>{const[f,x]=A(!1),u=async()=>{i&&await Hs(i)&&(x(!0),setTimeout(()=>x(!1),2e3))},g=n==="active",w=o||(g?"Active":"Inactive"),m=g?"#10b981":"#9ca3af";return l("div",{children:[l("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[l("div",{style:{fontSize:"13px",fontWeight:600,color:c?r.textPrimary:"#111827"},children:[t," Account"]}),d?l("button",{onClick:p,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("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:h?"#22c55e":"#f59e0b"}}),e("span",{children:h?"Embedded":"External"})]}):l("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:c?r.hoverBg:g?"#ecfdf5":"#f3f4f6",border:c?`1px solid ${r.cardBorder}`:g?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[e("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:m}}),e("span",{style:{fontSize:"11px",fontWeight:500,color:c?r.textSecondary:g?"#065f46":"#6b7280"},children:w})]})]}),e("div",{style:{fontSize:"28px",fontWeight:700,color:c?r.textPrimary:"#111827",lineHeight:1.2,marginBottom:"2px"},children:zn(s)}),a&&e("div",{style:{fontSize:"12px",color:c?r.textSecondary:"#6b7280",marginBottom:"8px"},children:a}),i&&l("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[e("span",{style:{fontSize:"12px",fontFamily:'"IBM Plex Mono", monospace',color:c?r.textSecondary:"#9ca3af"},children:Ps(i)}),e("button",{onClick:u,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:f?"Copied":"Copy"})]})]})},ri=({pendingDeposits:t,onCompleteDeposit:n,dk:o,dark:s=!1})=>t.length===0?null:l("div",{children:[e("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:s?o.textSecondary:"#6b7280",marginBottom:"8px",textTransform:"uppercase"},children:"Pending Deposits"}),e("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:t.map((a,i)=>{const r=je(a.chainId)?.displayName||`Chain ${a.chainId}`;return l("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:s?o.warningBg:"#fffbeb",border:s?`1px solid ${o.warningBorder}`:"1px solid #fde68a",borderRadius:"8px"},children:[l("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:s?o.hoverBg:"#fde68a",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:s?o.warningText:"#92400e"},children:a.tokenSymbol.charAt(0)}),l("div",{children:[l("div",{style:{fontSize:"13px",fontWeight:500,color:s?o.textPrimary:"#111827"},children:[a.amount," ",a.tokenSymbol]}),l("div",{style:{fontSize:"11px",color:s?o.warningText:"#92400e"},children:["on ",r]})]})]}),e("button",{onClick:()=>n?.(a),style:{padding:"4px 12px",fontSize:"11px",fontWeight:600,backgroundColor:s?o.hoverBg:"#fef3c7",color:s?o.textPrimary:"#92400e",border:s?`1px solid ${o.warningBorder}`:"1px solid #fde68a",borderRadius:"9999px",cursor:"pointer",transition:"all 150ms ease"},children:"Complete"})]},`${a.tokenAddress}-${a.chainId}-${i}`)})})]}),si=({spiceAssets:t,loading:n,dk:o,dark:s=!1})=>{const a={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:s?o.textSecondary:"#6b7280",marginBottom:"8px",textTransform:"uppercase"},i={backgroundColor:s?o.cardBg:"#f9fafb",border:s?`1px solid ${o.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return n?l("div",{children:[e("div",{style:a,children:"Idle Balances"}),[1,2].map(r=>e("div",{style:{...i,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},r))]}):t.length===0?l("div",{children:[e("div",{style:a,children:"Idle Balances"}),e("div",{style:{...i,padding:"16px",textAlign:"center",fontSize:"13px",color:s?o.textSecondary:"#9ca3af"},children:"No assets yet. Deposit to get started."})]}):l("div",{children:[e("div",{style:a,children:"Idle Balances"}),e("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:t.map((r,c)=>{const d=je(r.chainId),h=r.chainDisplayName||d?.displayName||`Chain ${r.chainId}`,p=r.tokenDisplaySymbol||r.tokenDisplayName||r.tokenSymbol;return l("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...i},children:[l("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[r.logoURI?e("img",{src:r.logoURI,alt:r.tokenSymbol,style:{width:"24px",height:"24px",borderRadius:"50%"}}):e("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:s?o.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:s?o.textSecondary:"#6b7280"},children:p.charAt(0)}),l("div",{children:[e("div",{style:{fontSize:"13px",fontWeight:500,color:s?o.textPrimary:"#111827"},children:p}),e("div",{style:{fontSize:"11px",color:s?o.textSecondary:"#9ca3af"},children:h})]})]}),l("div",{style:{textAlign:"right"},children:[e("div",{style:{fontSize:"13px",fontWeight:500,color:s?o.textPrimary:"#111827"},children:xn(r.balanceFormatted)}),e("div",{style:{fontSize:"11px",color:s?o.textSecondary:"#9ca3af"},children:zn(r.usdValue)})]})]},`${r.tokenAddress}-${r.chainId}-${c}`)})})]})},ai=({section:t,dk:n,dark:o=!1})=>{const s=a=>{switch(a){case"green":return"#10b981";case"red":return"#ef4444";default:return o?n.textPrimary:"#111827"}};return l("div",{children:[e("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:o?n.textSecondary:"#6b7280",marginBottom:"8px",textTransform:"uppercase"},children:t.title}),e("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:t.items.map((a,i)=>l("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:o?n.cardBg:"#f9fafb",border:o?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"},children:[l("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[a.tokenLogoURI?e("img",{src:a.tokenLogoURI,alt:a.tokenSymbol,style:{width:"20px",height:"20px",borderRadius:"50%"}}):e("div",{style:{width:"20px",height:"20px",borderRadius:"50%",backgroundColor:o?n.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",fontWeight:600,color:o?n.textSecondary:"#6b7280"},children:a.tokenSymbol.charAt(0)}),l("div",{children:[e("div",{style:{fontSize:"13px",fontWeight:500,color:o?n.textPrimary:"#111827"},children:a.tokenSymbol}),e("div",{style:{fontSize:"11px",color:o?n.textSecondary:"#6b7280"},children:a.label})]})]}),e("div",{style:{fontSize:"13px",fontWeight:600,color:s(a.valueColor)},children:a.displayValue})]},i))})]})},ii=({onDepositClick:t,onWithdrawClick:n,depositDisabled:o=!1,withdrawDisabled:s=!1,primaryColor:a="#EA4B4B",dark:i=!1})=>!t&&!n?null:l("div",{style:{display:"flex",gap:"8px"},children:[t&&e(et,{variant:"outline",onClick:t,disabled:o,dark:i,styles:{button:{backgroundColor:a}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),n&&e(et,{variant:"outline",onClick:n,disabled:s,dark:i,styles:{button:{backgroundColor:a}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),li=({appName:t,status:n,statusLabel:o,totalUsdValue:s,breakdownSubtitle:a,address:i,spiceAssets:r,spiceAssetsLoading:c,pendingDeposits:d,customSections:h,onDepositClick:p,onWithdrawClick:f,onCompleteDeposit:x,primaryColor:u,dk:g,dark:w=!1,showModeToggle:m,isEmbeddedMode:I,onModeToggle:z})=>{const[C,y]=A(!1);return l("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[e(oi,{appName:t,status:n,statusLabel:o,totalUsdValue:s,breakdownSubtitle:a,address:i,dk:g,dark:w,showModeToggle:m,isEmbeddedMode:I,onModeToggle:z}),e("div",{style:{height:"1px",backgroundColor:w?"#2d2d2d":"#e5e7eb"}}),l("div",{children:[l("button",{onClick:()=>y(!C),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:w?g.cardBg:"#f9fafb",border:w?`1px solid ${g.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:w?g.textSecondary:"#6b7280",fontSize:"12px",fontWeight:500},children:[e("span",{children:"How It Works"}),e("span",{style:{transform:C?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),C&&l("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:w?g.cardBg:"#f0fdf4",border:w?`1px solid ${g.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:w?g.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(ri,{pendingDeposits:d,onCompleteDeposit:x,dk:g,dark:w}),e(si,{spiceAssets:r,loading:c,dk:g,dark:w}),h.map((R,L)=>e(ai,{section:R,dk:g,dark:w},L)),e(ii,{onDepositClick:p,onWithdrawClick:f,primaryColor:u,dark:w})]})},Oo=380,Ln=8,di=({appName:t="Spice",status:n="active",statusLabel:o,customSections:s=[],extraAssets:a=[],tokenPrices:i={},breakdownLabels:r=[],supportedChains:c,styles:d,dark:h=!1,onDepositSuccess:p,onDepositClick:f,onWithdrawClick:x,onCompleteDeposit:u,showModeToggle:g=!1,defaultMode:w})=>{const m=Dt(Ft),I=m?.mode!=="7702";te(()=>{w&&m?.setMode&&m.setMode(w==="non7702"?"ondemand":"7702")},[m,w]);const[z,C]=A(!1),[y,R]=A(null),[L,S]=A({top:0,left:0,placement:"below"}),v=Se(null),P=Se(null),{address:b,isConnected:k}=sn(),j=rn(),{address:W}=nn(),{dark:T,primaryColor:D,dk:J}=Ze(d,h),q=xe(()=>c||$n("mainnet"),[c]),{assets:H,loading:V}=Dn({address:b,supportedChains:q,enabled:!!b&&!I,refetchInterval:3e4}),$=xe(()=>[...I?[]:H.map(ne=>{const Be=ne.balanceUsd||0,_=Number(ne.balance)/Math.pow(10,ne.decimals),ae=Be>0?Be:(i[ne.symbol]||0)*_;return{tokenAddress:ne.address,tokenSymbol:ne.symbol,tokenDisplaySymbol:Bo(ne),tokenDisplayName:js(ne),tokenDecimals:ne.decimals,chainId:ne.chainId,chainDisplayName:Fo(ne),balance:ne.balance.toString(),balanceFormatted:ne.balanceFormatted,usdValue:ae,logoURI:ne.logoURI}}),...a].filter(ne=>ne.balanceFormatted>0),[I,H,i,a]),O=xe(()=>$.reduce((ne,Be)=>ne+Be.usdValue,0),[$]),{pendingDeposits:M}=Gr({chainIds:q,enabled:!!b}),re=xe(()=>s.reduce((ne,Be)=>ne+Be.totalValue,0),[s]),ye=O+re,ke=xe(()=>{const ne=[];O>0&&ne.push(`${zn(O)} idle`);for(const Be of s){const _=r.find(ae=>ae.sectionTitle===Be.title)?.label||Be.title.toLowerCase();ne.push(`${zn(Be.totalValue)} ${_}`)}return ne.join(" \xB7 ")},[O,s,r]),pe=fe(ne=>{u?u(ne):R(ne)},[u]),ge=fe(()=>{R(null)},[]),Ce=fe(()=>{R(null),p?.()},[p]),De=fe(()=>{if(!v.current)return;const ne=v.current.getBoundingClientRect(),Be=window.innerHeight-ne.bottom-Ln,_=ne.top-Ln,ae=Be>=400||Be>=_?"below":"above",tt=Math.max(Ln,Math.min(ne.right-Oo,window.innerWidth-Oo-Ln)),Xe=ae==="below"?ne.bottom+Ln:ne.top-Ln;S({top:Xe,left:tt,placement:ae})},[]);ts(()=>{z&&De()},[z,De]),te(()=>{if(!z)return;const ne=ae=>{v.current&&!v.current.contains(ae.target)&&P.current&&!P.current.contains(ae.target)&&C(!1)},Be=ae=>{ae.key==="Escape"&&C(!1)},_=()=>De();return document.addEventListener("mousedown",ne),document.addEventListener("keydown",Be),window.addEventListener("scroll",_,{passive:!0}),window.addEventListener("resize",De),()=>{document.removeEventListener("mousedown",ne),document.removeEventListener("keydown",Be),window.removeEventListener("scroll",_),window.removeEventListener("resize",De)}},[z,De]);const Ie=m?.mode==="7702",Qe=Ie?j||b:W||b,me=fe(()=>{m?.setMode&&m.setMode(Ie?"ondemand":"7702")},[m,Ie]);if(typeof window>"u")return null;const Ne=l("button",{ref:v,onClick:()=>C(!z),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:T?J.hoverBg:"#ffffff",border:T?`1px solid ${J.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:'"Helvetica Neue", sans-serif',color:T?J.textPrimary:"#111827",transition:"all 150ms ease",boxShadow:T?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[e("span",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:D,flexShrink:0}}),l("span",{children:[t," Account"]}),k&&l("span",{style:{color:T?J.textSecondary:"#6b7280"},children:["\xB7 ",zn(ye)]}),e("span",{style:{fontSize:"10px",color:T?J.textSecondary:"#9ca3af",transform:z?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),Pe=z?Ss.createPortal(l(tn,{children:[e("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:9998},onClick:()=>C(!1)}),e("div",{ref:P,style:{position:"fixed",top:L.placement==="below"?`${L.top}px`:"auto",bottom:L.placement==="above"?`${window.innerHeight-L.top}px`:"auto",left:`${L.left}px`,width:`${Oo}px`,maxHeight:"80vh",backgroundColor:T?J.shell:"#ffffff",border:T?`1px solid ${J.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:T?"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(li,{appName:t,status:n,statusLabel:o,totalUsdValue:ye,breakdownSubtitle:ke,address:g?Qe:b,spiceAssets:$,spiceAssetsLoading:V,pendingDeposits:M,customSections:s,onDepositClick:f,onWithdrawClick:x,onCompleteDeposit:pe,primaryColor:D,dk:J,dark:T,showModeToggle:g,isEmbeddedMode:Ie,onModeToggle:me})}),e("style",{children:`
|
|
114
|
+
`})]})},Oa=({color:t})=>l("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",style:{marginTop:"1px",flexShrink:0},children:[e("circle",{cx:"7",cy:"7",r:"6.5",stroke:t,strokeWidth:"1.2"}),e("path",{d:"M7 6v4",stroke:t,strokeWidth:"1.2",strokeLinecap:"round"}),e("circle",{cx:"7",cy:"4.5",r:"0.7",fill:t})]}),Va=({isOpen:t,onClose:n,lockBatches:o,lockTokenSymbol:s,lockTokenLogoURI:a,destinationInputHook:i,sourceAssetInputHook:r,lockDurationHook:c,lockChainId:d,durationOptions:h,votingPowerEstimate:p,sourceChains:f,sourceAssets:x=[],escrowAddress:u,includeWalletAssets:g=!1,destinationTokenAddress:w,onLockSuccess:m,onLockExecute:I,sourceToDestinationConversionRate:z,estimatedOutputAmount:C,onAddFunds:y,styles:R,dark:L=!1})=>{const{theme:S,dark:v,primaryColor:P,dk:b}=Ze(R,L),k=S.typography.fontFamily,j=Dt(Ft),W=(j?.mode||"7702")!=="7702",T=v?b.cardBg:R?.assetSelector?.backgroundColor||R?.secondaryBackground||"#e9e9e9",D=v?`1px solid ${b.cardBorder}`:"0.5px solid #A8A8A7",J=v?"12px":"6px",q=v?b.textPrimary:"#111827",H=v?b.textSecondary:"#6b7280",V=xe(()=>({...R,assetSelector:{...R?.assetSelector,backgroundColor:v?b.cardBg:R?.assetSelector?.backgroundColor,borderRadius:v?"12px":R?.assetSelector?.borderRadius},secondaryBackground:v?b.cardBg:R?.secondaryBackground}),[R,v]),$=xe(()=>v?{...S,colors:{...S.colors,secondary:b.cardBg,surfaceHover:b.hoverBg,border:b.cardBorder,borderHover:b.inputBorder}}:S,[v,S]),[O,M]=A(null),[re,ye]=A(0),ke=c?.selectedDurationIdx??re,pe=c?.setSelectedDurationIdx??ye,[ge,Ce]=A(!1),[De,Ie]=A(null),[Qe,me]=A(!1),[Ne,Pe]=A(!1),[ne,Be]=A(null);qn(),Tn();const{chain:_,address:ae}=nn();_o();const tt=Se(_);te(()=>{tt.current=_},[_]);const Xe=sn(),{isReady:K,isAuthenticated:ue,isConnected:B,address:U,provider:G,actions:he}=Xe,{externalWallet:F,embeddedAddress:Y}=Wo(),{intentStatus:oe,startStatusPolling:de,clearStatus:qe}=So({checkStepStatus:(Q,ie)=>ft.checkStepStatus(Q,ie),retryStep:async(Q,ie)=>{const[We,Ue]=Q.split("/"),Ve=parseInt(Ue||"0",10);await ft.executeStep(We,Ve,ie,{action:"execute"})},maxRetries:3}),{assets:gt,refetch:Re}=Dn({address:U,supportedChains:f,enabled:B&&!W,refetchInterval:3e4}),Je=xe(()=>{if(x.length===0)return gt;const Q=new Set(x.map(ie=>ie.toLowerCase()));return gt.filter(ie=>Q.has(ie.address.toLowerCase()))},[gt,x]),ve=rn(),pt=W?ae:ve,Ct=xe(()=>{if(!g)return[];const Q=new Set,ie=[],We=Ue=>{if(!Ue)return;const Ve=Ue.toLowerCase();Q.has(Ve)||(Q.add(Ve),ie.push(zt(Ue)))};if(w&&We(w),W)for(const Ue of x)We(Ue);return ie},[g,W,w,x]),Te=xe(()=>Ct.map(Q=>Q.toLowerCase()).sort().join(","),[Ct]),At=xe(()=>JSON.stringify([...f||[]].sort()),[f]),[wt,Tt]=A([]),en=Se(0),Lt=fe(async()=>{if(!g||!pt||Ct.length===0){en.current++,Tt([]);return}const Q=++en.current,ie=zt(pt),We=f&&f.length>0?f:[d],Ue=Ct.map(le=>{const be=le.toLowerCase();for(const Ae of We){const Me=je(Ae)?.supportedTokens?.find(Fe=>Fe.address.toLowerCase()===be);if(Me)return{address:le,chainId:Ae,configToken:{decimals:Me.decimals,symbol:Me.symbol,name:Me.name,logo:Me.logo}}}return{address:le,chainId:d}}),Ve=new Map;for(const le of Ue){const be=Ve.get(le.chainId)||[];be.push(le),Ve.set(le.chainId,be)}const bt=async(le,be)=>{try{const Ae=await In(le,{address:be.address,abi:Rt,functionName:"balanceOf",args:[ie]});let Me,Fe,ze,we;if(be.configToken)Me=be.configToken.decimals,Fe=be.configToken.symbol,ze=be.configToken.name,we=be.configToken.logo;else{const[E,X,Ee]=await Promise.all([In(le,{address:be.address,abi:Rt,functionName:"decimals",args:[]}).catch(()=>18),In(le,{address:be.address,abi:Rt,functionName:"symbol",args:[]}).catch(()=>"TOKEN"),In(le,{address:be.address,abi:Rt,functionName:"name",args:[]}).catch(()=>"TOKEN")]);Me=Number(E),Fe=X,ze=Ee}const N=!!w&&be.address.toLowerCase()===w.toLowerCase()&&be.chainId===d;N&&a&&(we=a),N&&s&&!be.configToken&&(Fe==="TOKEN"&&(Fe=s),ze==="TOKEN"&&(ze=s));const Z=parseFloat((Number(Ae)/Math.pow(10,Me)).toFixed(6));return{address:be.address,name:ze,symbol:Fe,decimals:Me,balance:Ae,balanceFormatted:Z,balanceUsd:0,logoURI:we,isNative:!1,chainId:be.chainId}}catch{return null}},ee=await Promise.all(Array.from(Ve.entries()).map(async([le,be])=>{let Ae;try{Ae=lt(le)}catch{return[]}const Me=[],Fe=[];for(const we of be){const N=Me.length;Me.push({address:we.address,abi:Rt,functionName:"balanceOf",args:[ie]}),we.configToken||Me.push({address:we.address,abi:Rt,functionName:"decimals",args:[]},{address:we.address,abi:Rt,functionName:"symbol",args:[]},{address:we.address,abi:Rt,functionName:"name",args:[]}),Fe.push({start:N,item:we})}let ze=null;try{ze=await Ae.multicall({contracts:Me})}catch{ze=null}return ze?Fe.map(({start:we,item:N})=>{const Z=ze[we],E=Z?.status==="success"?Z.result:0n;let X,Ee,rt,st;if(N.configToken)X=N.configToken.decimals,Ee=N.configToken.symbol,rt=N.configToken.name,st=N.configToken.logo;else{const Ye=ze[we+1],dt=ze[we+2],ct=ze[we+3];X=Ye?.status==="success"?Number(Ye.result):18,Ee=dt?.status==="success"?dt.result:"TOKEN",rt=ct?.status==="success"?ct.result:Ee}const Le=!!w&&N.address.toLowerCase()===w.toLowerCase()&&N.chainId===d;Le&&a&&(st=a),Le&&s&&!N.configToken&&(Ee==="TOKEN"&&(Ee=s),rt==="TOKEN"&&(rt=s));const ht=parseFloat((Number(E)/Math.pow(10,X)).toFixed(6));return{address:N.address,name:rt,symbol:Ee,decimals:X,balance:E,balanceFormatted:ht,balanceUsd:0,logoURI:st,isNative:!1,chainId:N.chainId}}):(await Promise.all(be.map(we=>bt(Ae,we)))).filter(we=>we!==null)}));Q===en.current&&Tt(ee.flat())},[g,pt,Te,At,d,w,a,s]);te(()=>{if(!g){Tt([]);return}Lt();const Q=setInterval(()=>{Lt()},15e3);return()=>clearInterval(Q)},[Lt,g]);const it=fe(()=>{Lt()},[Lt]),Ot=xe(()=>wt.filter(Q=>Q.balance>0n),[wt]),Mt=xe(()=>{if(W)return Ot.map(ie=>({...ie,_source:"wallet"}));if(!g)return Je;const Q=[];for(const ie of Ot)Q.push({...ie,_source:"wallet"});for(const ie of Je)Q.push({...ie,_source:"spice"});return Q},[W,g,Ot,Je]),xt=Se(null),It=Se(null);te(()=>{It.current=O},[O]),te(()=>{t||(M(null),Ie(null),Ce(!1),Pe(!1),Be(null),me(!1),qe())},[t,qe]),te(()=>{i&&i.assetAmount!==(O?.amount||"")&&M(Q=>Q&&{...Q,amount:i.assetAmount})},[i?.assetAmount]),te(()=>{r&&r.assetAmount!==(O?.amount||"")&&M(Q=>Q&&{...Q,amount:r.assetAmount})},[r?.assetAmount]),te(()=>{if(!W&&oe?.overallStatus==="success"&&oe.intentId&&xt.current!==oe.intentId&&U&&oe.steps.find(Q=>Q.transactionHash)?.transactionHash){xt.current=oe.intentId;const Q=It.current;if(!Q?.asset||!Q.amount||Q.asset._source==="wallet"||at(Q.amount,Q.asset.decimals)===0n)return;Re()}},[oe,U,d,Re,W]);const $e=parseFloat(O?.amount||"")||0,mt=xe(()=>O?.asset?O.asset._source==="wallet"?O.asset.balanceFormatted??0:Je.find(Q=>Q.address.toLowerCase()===O.asset.address.toLowerCase()&&Q.chainId===O.asset.chainId)?.balanceFormatted??0:0,[O?.asset,Je]),Et=$e>0&&$e>mt,vt=c?.selectedDuration??h[ke]??h[0],kt=xe(()=>!O?.asset||!w?!1:O.asset.address.toLowerCase()===w.toLowerCase()&&O.asset.chainId===d,[O?.asset,w,d]),Vt=xe(()=>$e<=0?0:kt?$e:!z||z<=0?0:$e/z,[$e,z,kt]),se=xe(()=>Vt<=0?null:Vt.toLocaleString(void 0,{maximumFractionDigits:2}),[Vt]),ce=p&&Vt>0&&vt?p(Vt,vt.months):void 0,He=xe(()=>$e<=0?"$0.00":kt&&z?($e*z).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!z||z<=0?"$0.00":$e.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[$e,z,kt]),nt=xe(()=>{if(!se)return null;const Q=parseFloat(se.replace(/,/g,""));return kt&&z?(Q*z).toLocaleString(void 0,{maximumFractionDigits:2}):z?(Q*z).toLocaleString(void 0,{maximumFractionDigits:2}):null},[se,z,kt]),ut=fe(Q=>{M(ie=>({asset:Q,amount:ie?.asset?.address===Q.address&&ie?.asset?.chainId===Q.chainId&&ie.amount||""})),Ie(null),r?.setSelectedAsset&&r.setSelectedAsset({symbol:Q.symbol,address:Q.address,decimals:Q.decimals,chainId:Q.chainId})},[r?.setSelectedAsset]),yt=fe(Q=>{M(ie=>ie&&{...ie,amount:Q}),Ie(null),i&&i.setAssetAmount(Q),r&&r.setAssetAmount(Q)},[i,r]),ot=fe(()=>{if(typeof o=="function"){if(!O?.asset||!O.amount)throw new Error("Select an asset and enter an amount");return o({asset:O.asset,amount:O.amount,amountWei:at(O.amount,O.asset.decimals)})}return o},[o,O]),Ge=fe(async()=>{const Q=W&&Y||U;if(!B||!Q)throw new Error("Please connect your wallet to continue");const ie=ot();if(ie.length===0)throw new Error("No lock batches configured");if(!K||!ue)throw new Error(`Please authenticate with ${G||"wallet provider"} to continue`);const We=[...ie],Ue=[...new Set(We.map(we=>we.chainId))],Ve=[];for(const we of Ue){const N=lt(we),Z=Fn(we),E=await Gn(Q,N),X=await he.signAuthorization({contractAddress:Z,chainId:we,nonce:Number(E)});Ve.push(X)}const bt=Jn(We),ee=Math.floor(Date.now()/1e3)+60*10,le=bt.map(we=>we.hash),be=eo(to([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,BigInt(ee),le])),Ae=await he.signMessage({raw:be}),Me=typeof Ae=="string"?Ae:Ae.signature;if(!Me)throw new Error("Failed to sign intent authorization");const Fe={mode:"7702",signatureType:"ecdsa",signature:Me,nbf:0,exp:ee,chainBatches:bt.map((we,N)=>({hash:we.hash,chainId:we.chainId,tokenTransfers:We[N].tokenTransfers??[],calls:we.calls}))},ze=await ft.createAction({user:Q,chainAuthorizations:Ve.map(we=>({r:we.r,s:we.s,yParity:we.yParity,address:we.address,chainId:Number(we.chainId),nonce:Number(we.nonce)})),intents:[Fe]});if(ze){const we=Xn(We,Nt),[N,Z]=ze.intentIds[0].split("/"),E=parseInt(Z||"0",10);de(ze.intentIds[0],we);for(let X=0;X<We.length;X++)await ir(()=>ft.executeStep(N,E,X,{action:"execute"}))}},[ot,Xe,de,W,Y]),Wt=fe(async()=>{if(!O?.asset||!O.amount)throw new Error("Select an asset and enter an amount");if(!U||!ve)throw new Error("Embedded wallet not connected");const Q=O.asset,ie=at(O.amount,Q.decimals),We=u||Fn(d),Ue=await he.getEthereumProvider();await Ue.request({method:"wallet_switchEthereumChain",params:[{chainId:`0x${d.toString(16)}`}]});const Ve=je(d),bt=Mn({account:ve,transport:Wn(Ue),chain:Ve?.viemChain});let ee;if(Q.isNative||_e(Q.address))ee=await bt.sendTransaction({to:We,value:ie,chain:Ve?.viemChain});else{const le=qt({abi:Rt,functionName:"transfer",args:[We,ie]});ee=await bt.sendTransaction({to:Q.address,data:le,chain:Ve?.viemChain})}if((await lt(d).waitForTransactionReceipt({hash:ee,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to escrow failed");await Re(),it(),await Ge()},[O,U,ve,he,u,d,Ge,Re,it]),Pt=fe(async()=>{if(!O?.asset||!O.amount)throw new Error("Select an asset and enter an amount");if(!ae||!F)throw new Error("Please connect your external wallet to continue");if(!(ve||Y))throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");if(I){const Me=ot();if(Me.length===0)throw new Error("No lock batches configured");const Fe=O.asset,ze=at(O.amount,Fe.decimals),we=await I({asset:Fe,amount:O.amount,amountWei:ze,lockDurationMonths:vt?.months??0,chainBatches:Me});we&&m?.(we);return}const Q=O.asset,ie=at(O.amount,Q.decimals),We=Q.chainId,Ue=u||un,Ve=await F.getEthereumProvider();let bt=null;try{const Me=await Ve.request({method:"eth_chainId"});bt=parseInt(Me,16)}catch{bt=null}if(bt!==We)try{await Ve.request({method:"wallet_switchEthereumChain",params:[{chainId:`0x${We.toString(16)}`}]})}catch(Me){if(Me?.code===4902||Me?.message?.includes("Unrecognized chain ID")){const Fe=je(We);Fe&&await Ve.request({method:"wallet_addEthereumChain",params:[{chainId:`0x${We.toString(16)}`,chainName:Fe.name||`Chain ${We}`,nativeCurrency:Fe.nativeCurrency||{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:[Fe.rpcUrl],blockExplorerUrls:Fe.blockExplorer?[Fe.blockExplorer]:void 0}]})}else throw Me}const ee=je(We),le=Mn({account:ae,chain:ee?.viemChain,transport:Wn(Ve)}),be=Xt(Q.address),Ae=Q.isNative||_e(be)?await le.sendTransaction({to:Ue,value:ie,chain:ee?.viemChain}):await le.sendTransaction({to:be,data:qt({abi:Rt,functionName:"transfer",args:[Ue,ie]}),chain:ee?.viemChain});if((await lt(We).waitForTransactionReceipt({hash:Ae,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Escrow deposit failed");await Ge()},[O,F,ae,ve,Y,u,I,ot,vt,m,Ge]),Qt=fe(async()=>{if(!O?.asset||!O.amount)throw new Error("Select an asset and enter an amount");if(!ae||!F)throw new Error("Please connect your external wallet to continue");const Q=ot();if(Q.length===0)throw new Error("No lock batches configured");const ie=Q.find(be=>be.chainId===d)||Q[0];if(!ie)throw new Error("No lock batch for lock chain");const We=await F.getEthereumProvider();let Ue=null;try{const be=await We.request({method:"eth_chainId"});Ue=parseInt(be,16)}catch{Ue=null}if(Ue!==d)try{await We.request({method:"wallet_switchEthereumChain",params:[{chainId:`0x${d.toString(16)}`}]})}catch(be){if(be?.code===4902||be?.message?.includes("Unrecognized chain ID")){const Ae=je(d);Ae&&await We.request({method:"wallet_addEthereumChain",params:[{chainId:`0x${d.toString(16)}`,chainName:Ae.name||`Chain ${d}`,nativeCurrency:Ae.nativeCurrency||{name:"ETH",symbol:"ETH",decimals:18},rpcUrls:[Ae.rpcUrl],blockExplorerUrls:Ae.blockExplorer?[Ae.blockExplorer]:void 0}]})}else throw be}const Ve=je(d),bt=Mn({account:ae,chain:Ve?.viemChain,transport:Wn(We)}),ee=lt(d);let le;for(const be of ie.calls){const Ae=await bt.sendTransaction({to:be.to,data:be.data,value:be.value,chain:Ve?.viemChain});if((await ee.waitForTransactionReceipt({hash:Ae,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Lock transaction failed");le=Ae}le&&m?.(le)},[O,F,ae,ot,d,m]);te(()=>{if(oe?.overallStatus==="success"){const Q=oe.steps.find(ie=>ie.transactionHash);m?.(Q?.transactionHash)}},[oe?.overallStatus,m]);const Ht=g&&O?.asset?._source==="wallet"&&O?.asset?.chainId===d,Yt=fe(async()=>{if(!O?.asset||$e<=0){Ie("Select an asset and enter an amount");return}if(Et){Ie("Insufficient balance. Add more assets.");return}Ce(!0),Ie(null);const Q=ie=>{console.error("[SpiceLockModal] lock failed:",ie);const We=on(ie,""),Ue=typeof ie?.shortMessage=="string"?ie.shortMessage:typeof ie?.message=="string"?ie.message:"";Ie(We||Ue||"Transaction failed. Please try again.")};if(W){if(kt){try{await Qt()}catch(ie){Q(ie)}finally{Ce(!1)}return}me(!0);try{await Pt()}catch(ie){Q(ie)}finally{Ce(!1)}return}me(!0);try{Ht&&!kt?await Wt():await Ge()}catch(ie){Q(ie)}finally{Ce(!1)}},[O,$e,Et,W,Pt,Qt,Ht,kt,Wt,Ge]),Jt=!!O?.asset&&$e>0&&!Et&&!ge,mn=l("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[e(Oa,{color:H}),l("p",{style:{fontSize:"13px",color:H,margin:0,lineHeight:"1.5"},children:["Add ",s," by converting assets from your account"]})]});if(!t)return null;const cn={backgroundColor:T,border:D,borderRadius:J,padding:"16px",marginBottom:"16px"};return e(Gt,{isOpen:t,onClose:n,title:`Add ${s} to your account`,subtitle:mn,styles:R,dark:v,footerLinkText:"Spicenet accounts \u2192",overlayContent:Ne?e("div",{}):void 0,children:l("div",{style:{padding:"0 24px 8px 24px",position:"relative"},children:[l("div",{style:{marginBottom:"12px"},children:[y&&e("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:l("button",{onClick:y,style:{background:"none",border:"none",cursor:"pointer",padding:0,display:"flex",alignItems:"center",gap:"4px",color:P,fontSize:"12px",fontWeight:500,fontFamily:k,textDecoration:"underline",textUnderlineOffset:"2px"},children:["Add Funds",l("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:P,strokeWidth:"1.8",children:[e("circle",{cx:"6",cy:"6",r:"5"}),e("path",{d:"M6 4v4M4 6h4",strokeLinecap:"round"})]})]})}),e(Nn,{assets:Mt,selectedAsset:O??void 0,onAssetSelect:ut,onAmountChange:yt,label:"Amount",showBalance:!0,showMaxButton:!0,theme:$,styles:V}),e("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:H,fontFamily:k},children:He})]}),l("div",{style:cn,children:[l("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:v?`1px solid ${b.cardBorder}`:"1px solid #e5e7eb"},children:[l("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[a?e("img",{src:a,alt:s,style:{width:"32px",height:"32px",borderRadius:"50%",objectFit:"cover"}}):e("div",{style:{width:"32px",height:"32px",borderRadius:"50%",backgroundColor:v?b.inputBg:"#d1d5db",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:700,color:q},children:s.slice(0,2)}),e("span",{style:{fontSize:"16px",fontWeight:600,color:q,fontFamily:k},children:s})]}),l("div",{style:{textAlign:"right"},children:[e("div",{style:{fontSize:"22px",fontWeight:700,color:q,fontFamily:k,lineHeight:1.1},children:se??"0.00"}),l("div",{style:{fontSize:"12px",color:H,fontFamily:k,marginTop:"2px"},children:["~$",nt??"0.00"]})]})]}),l("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:v?`1px solid ${b.cardBorder}`:"1px solid #e5e7eb"},children:[l("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[e("span",{style:{fontSize:"15px",fontWeight:500,color:H,fontFamily:k},children:"Lock Duration"}),e("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:e("path",{d:"M4 6L8 10L12 6",stroke:H,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),e(Ua,{options:h,selectedIndex:ke,onSelect:pe,primaryColor:P,dark:v,textPrimary:q,textSecondary:H})]}),l("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[e(Pa,{durationMonths:vt?.months,fontFamily:k,dark:v,textPrimary:q,textSecondary:H}),p&&e(Ha,{votes:ce,fontFamily:k,dark:v,textPrimary:q,textSecondary:H})]})]}),De&&e("div",{style:{marginBottom:"12px",padding:"10px 14px",backgroundColor:v?"rgba(239,68,68,0.12)":"#fef2f2",border:`1px solid ${v?"rgba(239,68,68,0.3)":"#fecaca"}`,borderRadius:"6px"},children:e("p",{style:{color:"#ef4444",fontSize:"13px",margin:0,fontFamily:k},children:De})}),e(et,{variant:"outline",fullWidth:!0,onClick:Yt,disabled:!Jt,loading:ge,dark:v,styles:{button:{backgroundColor:P}},children:ge?Ht&&!kt?"DEPOSITING...":kt?"LOCKING...":"CONVERTING...":Ht&&!kt?`DEPOSIT ${s}`:kt?`LOCK ${s}`:`CONVERT TO ${s}`}),e(ja,{isOpen:Ne,data:ne,isLocking:ge,lockError:De,onContinue:Yt,onClose:()=>Pe(!1),primaryColor:P,fontFamily:k,dark:v}),oe&&Qe&&e("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:v?b.shell:"white",borderRadius:J,padding:"16px 0"},children:e(On,{type:"deposit",isOpen:!!oe&&oe.overallStatus!=="processing",isProcessing:ge||oe?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{qe(),me(!1),Yt()},onNewTx:()=>{qe(),me(!1),M(null),xt.current=null,Re(),it()},onClose:()=>{qe(),me(!1)},onComplete:()=>{qe(),me(!1),M(null),xt.current=null,Re(),it()},results:oe?.overallStatus==="success"||oe?.overallStatus==="failed"?oe.steps.map(Q=>({asset:{symbol:O?.asset?.symbol||s,address:O?.asset?.address||""},txHash:Q.transactionHash||"",success:Q.status==="success",amount:O?.amount})):void 0,chainName:Nt(d),explorerUrl:kn(d,"").replace(/\/tx\/.*$/,"")||void 0,theme:S,styles:R,dark:v})})]})})},Dr=({variant:t,destinationSymbol:n,destinationLogoURI:o,destinationDecimals:s,primaryColor:a,fontFamily:i,textPrimary:r,textSecondary:c,cardBg:d,cardBorder:h,dk:p,dark:f,isQuoting:x,quoteError:u,estimatedOutput:g,paymentAmount:w,needsSwap:m,exactOutputSwap:I,adjustable:z=!1,maxAmount:C,onAmountChange:y})=>t==="supply"?e("div",{style:{backgroundColor:d,border:`1px solid ${h}`,borderRadius:"12px",padding:"14px 16px",marginBottom:"16px"},children:l("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[l("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[e(zr,{symbol:n,logoURI:o,primaryColor:a,size:28}),l("span",{style:{fontSize:"13px",fontWeight:500,color:c,fontFamily:i},children:["Estimated ",n]})]}),e("div",{style:{textAlign:"right"},children:x?e("span",{style:{fontSize:"14px",color:c,fontFamily:i},children:"Quoting..."}):u?e("span",{style:{fontSize:"13px",color:"#ef4444",fontFamily:i},children:"Quote failed"}):g?l("span",{style:{fontSize:"16px",fontWeight:600,color:r,fontFamily:i},children:["\u2248 ",g]}):e("span",{style:{fontSize:"14px",color:c,fontFamily:i},children:"\u2014"})})]})}):e(Qa,{destinationSymbol:n,destinationLogoURI:o,destinationDecimals:s,primaryColor:a,fontFamily:i,textPrimary:r,textSecondary:c,cardBg:d,cardBorder:h,dk:p,dark:f,paymentAmount:w||"0",needsSwap:m,exactOutputSwap:I,isQuoting:x,adjustable:z,maxAmount:C,onAmountChange:y}),zr=({symbol:t,logoURI:n,primaryColor:o,size:s})=>n?e("img",{src:n,alt:t,style:{width:s,height:s,borderRadius:"50%",objectFit:"cover"}}):e("div",{style:{width:s,height:s,borderRadius:"50%",backgroundColor:`${o}22`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:s<30?"11px":"12px",fontWeight:700,color:o},children:t.slice(0,2)}),Qa=({destinationSymbol:t,destinationLogoURI:n,destinationDecimals:o,primaryColor:s,fontFamily:a,textPrimary:i,textSecondary:r,cardBg:c,cardBorder:d,dk:h,dark:p,paymentAmount:f,needsSwap:x,exactOutputSwap:u,isQuoting:g,adjustable:w,maxAmount:m,onAmountChange:I})=>{const z='"IBM Plex Mono", monospace',C=parseFloat(f||"0"),y=m?parseFloat(m):0,[R,L]=A(f||""),S=Se(null),[v,P]=A(null),[b,k]=A(null);te(()=>{w||L(f||"")},[f,w]);const j=D=>{let J=D;J.startsWith(".")&&(J="0"+J);const q=ar(J);let H=q;m&&parseFloat(q)>parseFloat(m)&&(H=m),L(H),S.current&&clearTimeout(S.current),S.current=setTimeout(()=>I?.(H),300)},W=D=>{if(!y)return;if(D===100){L(m||y.toString()),S.current&&clearTimeout(S.current),I?.(m||y.toString());return}const J=10**o,q=(Math.floor(y*D/100*J)/J).toString();L(q),S.current&&clearTimeout(S.current),I?.(q)},T=y>0?parseFloat(R||"0")/y*100:0;return te(()=>()=>{S.current&&clearTimeout(S.current)},[]),l("div",{style:{backgroundColor:c,border:`1px solid ${d}`,borderRadius:p?"12px":"6px",padding:"16px",marginBottom:"16px"},children:[l("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[l("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[e(zr,{symbol:t,logoURI:n,primaryColor:s,size:32}),l("div",{children:[e("span",{style:{fontSize:"14px",fontWeight:600,color:i,fontFamily:a},children:"Payment"}),e("div",{style:{fontSize:"12px",color:r,fontFamily:a,marginTop:"2px"},children:t})]})]}),l("div",{style:{textAlign:"right"},children:[w?e("input",{type:"text",value:R,onChange:D=>j(D.target.value),placeholder:"0.0",style:{fontSize:"20px",fontWeight:700,color:i,fontFamily:z,lineHeight:1.1,backgroundColor:"transparent",border:"none",outline:"none",padding:0,width:"120px",textAlign:"right"}}):e("div",{style:{fontSize:"20px",fontWeight:700,color:i,fontFamily:z,lineHeight:1.1},children:C>0?f:"0.00"}),e("div",{style:{fontSize:"12px",color:r,fontFamily:z,marginTop:"2px"},children:t}),w&&y>0&&e("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((D,J)=>{const q=Math.abs(T-D)<1,H=J===4,V=D/100,$=v===D,O=b===D;return e("button",{onClick:()=>W(D),onMouseEnter:()=>P(D),onMouseLeave:()=>{P(null),k(null)},onMouseDown:()=>k(D),onMouseUp:()=>k(null),title:`${D}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:q?1:$?.8:.5,transform:O?"scale(0.85)":$?"scale(1.15)":"scale(1)",transition:"all 0.15s ease"},children:l("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[e("circle",{cx:"7",cy:"7",r:"6.84375",fill:H?s:"none",stroke:H?s:p?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!H&&V>0&&e("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${V>.5?1:0} 1 ${7+6.84375*Math.sin(V*2*Math.PI)} ${7-6.84375*Math.cos(V*2*Math.PI)} Z`,fill:p?h?.textSecondary||"#9ca3af":"#3C3E42"})]})},D)})})]})]}),x&&u&&!g&&e("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:p?`1px solid ${h?.cardBorder||d}`:"1px solid #e5e7eb",display:"flex",justifyContent:"flex-end"},children:l("span",{style:{fontSize:"11px",color:r,fontFamily:a,opacity:.7},children:["via ",u.venue]})})]})};function Nr(t,n,o){const s=t.address.toLowerCase()===n,a=t.chainId===o,i=t._source==="wallet";return i&&s&&a?0:i&&a?1:!i&&s?2:!i&&a?3:4}function Ya(t){const{address:n,destinationToken:o,supportedSourceAssets:s,sourceChains:a,enabled:i}=t,r=rn(),{assets:c,refetch:d}=Dn({address:n,supportedChains:a,enabled:i,refetchInterval:3e4}),h=xe(()=>{if(!s||s.length===0)return c;const u=s.map(g=>g.toLowerCase());return c.filter(g=>u.includes(g.address.toLowerCase()))},[c,s]),[p,f]=A(null);te(()=>{if(!o.address||!r||!i){f(null);return}let u=!1;const g=zt(o.address),w=zt(r),m=lt(o.chainId),I=async()=>{try{const C=await m.multicall({contracts:[{address:g,abi:Ut,functionName:"balanceOf",args:[w]},{address:g,abi:Ut,functionName:"decimals",args:[]},{address:g,abi:Ut,functionName:"symbol",args:[]},{address:g,abi:Ut,functionName:"name",args:[]}]});if(u)return;const y=C[0].status==="success"?C[0].result:0n,R=C[1].status==="success"?Number(C[1].result):o.decimals,L=C[2].status==="success"?C[2].result:o.symbol,S=C[3].status==="success"?C[3].result:o.symbol;y>0n?f({address:g,name:S,symbol:L,decimals:R,balance:y,balanceFormatted:parseFloat((Number(y)/Math.pow(10,R)).toFixed(6)),balanceUsd:0,logoURI:o.logoURI,isNative:!1,chainId:o.chainId}):f(null)}catch{u||f(null)}};I();const z=setInterval(I,15e3);return()=>{u=!0,clearInterval(z)}},[o.address,o.chainId,o.decimals,o.symbol,o.logoURI,r,i]);const x=fe(()=>{if(!o.address||!r)return;const u=lt(o.chainId),g=zt(o.address),w=zt(r);u.multicall({contracts:[{address:g,abi:Ut,functionName:"balanceOf",args:[w]},{address:g,abi:Ut,functionName:"decimals",args:[]}]}).then(m=>{const I=m[0].status==="success"?m[0].result:0n,z=m[1].status==="success"?Number(m[1].result):18;I>0n?f(C=>C?{...C,balance:I,balanceFormatted:parseFloat((Number(I)/Math.pow(10,z)).toFixed(6))}:null):f(null)}).catch(()=>{})},[o.address,o.chainId,r]);return{displayAssets:xe(()=>{const u=[];p&&u.push({...p,_source:"wallet"});for(const w of h)u.push({...w,_source:"spice"});const g=o.address.toLowerCase();return u.sort((w,m)=>Nr(w,g,o.chainId)-Nr(m,g,o.chainId)),u},[p,h,o.address,o.chainId]),filteredSpiceAssets:h,embeddedWalletAddress:r,refreshSpiceAssets:d,refreshWalletAssets:x}}async function Ur(t){const{tokenIn:n,tokenOut:o,amountIn:s,fee:a,chainId:i,config:r}=t;if(s<=0n)throw new Error("amountIn must be greater than 0");const c=(await lt(i).simulateContract({address:r.quoterV2,abi:us,functionName:"quoteExactInputSingle",args:[{tokenIn:n,tokenOut:o,amountIn:s,fee:a,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 Lr(t){const n=t.feeTiers??[100,500,3e3,1e4],o=await Promise.allSettled(n.map(a=>Ur({...t,fee:a})));let s=null;for(let a=0;a<o.length;a++){const i=o[a];i.status==="fulfilled"&&(!s||i.value.amountOut>s.amountOut)&&(s={...i.value,fee:n[a]})}if(!s)throw new Error("No liquidity found for this pair on any fee tier.");return s}const Za=[{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 Ka(t){const{tokenIn:n,tokenOut:o,amountOut:s,fee:a,chainId:i,config:r}=t;if(s<=0n)throw new Error("amountOut must be greater than 0");const c=(await lt(i).simulateContract({address:r.quoterV2,abi:Za,functionName:"quoteExactOutputSingle",args:[{tokenIn:n,tokenOut:o,amount:s,fee:a,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 Xa(t){const n=t.feeTiers??[100,500,3e3,1e4],o=await Promise.allSettled(n.map(a=>Ka({...t,fee:a})));let s=null;for(let a=0;a<o.length;a++){const i=o[a];i.status==="fulfilled"&&(!s||i.value.amountIn<s.amountIn)&&(s={...i.value,fee:n[a]})}if(!s)throw new Error("No liquidity found for this pair on any fee tier.");return s}function Pr(t){return t.type==="swap"}const Ho=.02,qa=[1,8453,42161,10,137,43114,56],Ga="https://api.1inch.dev/swap/v6.0";function Hr(t,n){return fs(t,n)}function jr(t){const n=t?.baseUrl??Ga;return{name:"1inch",chainIds:t?.chainIds??qa,resolve:async(o,s,a)=>{const i=o.maxSlippage??Ho,r=i*100,c=_e(o.tokenIn)?tr:o.tokenIn,d=_e(o.tokenOut)?tr:o.tokenOut,h=_e(o.tokenIn);try{const p=new URL(`${n}/${s}/swap`);p.searchParams.set("src",c),p.searchParams.set("dst",d),p.searchParams.set("amount",o.amountIn.toString()),p.searchParams.set("from",a),p.searchParams.set("slippage",r.toString()),p.searchParams.set("disableEstimate","true"),p.searchParams.set("allowPartialFill","false");const f={Accept:"application/json"};t?.apiKey&&(f.Authorization=`Bearer ${t.apiKey}`);const x=await fetch(p.toString(),{headers:f});if(!x.ok)throw new Ke("VENUE_API_ERROR",`[1inchVenue] API returned ${x.status} for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${s}`,{venue:"1inch",chainId:s,tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountIn:o.amountIn.toString(),cause:`HTTP ${x.status}`});const u=await x.json();if(!u.dstAmount||!u.tx)return console.warn(`[1inchVenue] No route data for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${s}`),null;const g=BigInt(u.dstAmount);if(g<=0n)return console.warn(`[1inchVenue] Zero output for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${s}`),null;const w=Hr(g,i),m=[];return u.tx.to&&!h&&m.push({to:o.tokenIn,value:0n,data:qt({abi:Ut,functionName:"approve",args:[u.tx.to,o.amountIn]})}),m.push({to:u.tx.to,value:BigInt(u.tx.value||"0"),data:u.tx.data}),{venue:"1inch",amountOut:g,amountOutMinimum:w,calls:m}}catch(p){if(p instanceof Ke)throw p;const f=p instanceof Error?p.message:String(p);throw new Ke("VENUE_API_ERROR",`[1inchVenue] Exception for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${s}: ${f}`,{venue:"1inch",chainId:s,tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountIn:o.amountIn.toString(),cause:f})}}}}const Or=[4114,5115],jo={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425"},Vr={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453]};function Qr(t){return{name:"satsuma",chainIds:t.chainIds??Or,resolve:async(n,o,s)=>{const a=n.maxSlippage??Ho,i=_e(n.tokenIn);let r;try{r=await Lr({tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn,chainId:o,config:{swapRouter:t.swapRouter,quoterV2:t.quoterV2},feeTiers:t.feeTiers})}catch{return console.warn(`[SatsumaVenue] No viable fee tier for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}.`),null}const c=Hr(r.amountOut,a),d=[];return i||d.push({to:n.tokenIn,value:0n,data:qt({abi:Ut,functionName:"approve",args:[t.swapRouter,n.amountIn]})}),d.push({to:t.swapRouter,value:i?n.amountIn:0n,data:qt({abi:hs,functionName:"exactInputSingle",args:[{tokenIn:n.tokenIn,tokenOut:n.tokenOut,fee:r.fee,recipient:s,amountIn:n.amountIn,amountOutMinimum:c,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:r.amountOut,amountOutMinimum:c,calls:d}}}}function Yr(t){return{name:"satsuma",chainIds:t.chainIds??Or,resolve:async(n,o,s)=>{const a=n.maxSlippage??Ho,i=_e(n.tokenIn);let r;try{r=await Xa({tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountOut:n.amountOut,chainId:o,config:{swapRouter:t.swapRouter,quoterV2:t.quoterV2},feeTiers:t.feeTiers})}catch{return null}const c=BigInt(Math.round(a*1e4)),d=r.amountIn+r.amountIn*c/10000n,h=[];return h.push({to:t.swapRouter,value:i?d:0n,data:qt({abi:Ja,functionName:"exactOutputSingle",args:[{tokenIn:n.tokenIn,tokenOut:n.tokenOut,fee:r.fee,recipient:s,amountOut:n.amountOut,amountInMaximum:d,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:r.amountIn,amountInMax:d,amountOut:n.amountOut,calls:h}}}}const Ja=[{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 Zr(t){const n=[];t?.customVenues&&n.push(...t.customVenues),t?.satsuma&&n.push(Qr(t.satsuma)),n.push(jr(t?.oneInch));function o(a){return n.find(i=>i.chainIds.includes(a))}async function s(a,i,r){const c=[],d=[];for(const h of a){if(!Pr(h)){c.push(h);continue}const p=o(i);if(!p)throw new Ke("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${i}. Cannot resolve swap ${h.tokenIn} \u2192 ${h.tokenOut}.`,{chainId:i,tokenIn:h.tokenIn,tokenOut:h.tokenOut,amountIn:h.amountIn.toString()});const f=await p.resolve(h,i,r);if(!f)throw new Ke("NO_LIQUIDITY",`${p.name} returned no quote for ${h.tokenIn} \u2192 ${h.tokenOut} on chain ${i}.`,{venue:p.name,chainId:i,tokenIn:h.tokenIn,tokenOut:h.tokenOut,amountIn:h.amountIn.toString()});c.push(...f.calls),d.push(f)}return{calls:c,resolvedSwaps:d}}return{resolveSwapIntents:s,getVenueForChain:o,venues:n}}function $a(t){const n=t?.customVenues??[];async function o(s,a,i){const r=n.filter(d=>d.chainIds.includes(a));if(r.length===0)throw new Ke("NO_SWAP_ROUTE",`No exact-output venue supports chain ${a}`,{chainId:a,tokenIn:s.tokenIn,tokenOut:s.tokenOut});const c=(await Promise.allSettled(r.map(d=>d.resolve(s,a,i)))).filter(d=>d.status==="fulfilled").map(d=>d.value).filter(d=>d!==null);if(c.length===0)throw new Ke("NO_SWAP_ROUTE",`All aggregators failed for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${a}`,{chainId:a,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountOut:s.amountOut.toString()});return c.sort((d,h)=>d.amountIn<h.amountIn?-1:d.amountIn>h.amountIn?1:0),c[0]}return{getQuote:o,venues:n}}function _a(t){const{direction:n,selectedAsset:o,destinationToken:s,chainId:a,recipient:i,paymentAmount:r}=t,[c,d]=A(!1),[h,p]=A(null),[f,x]=A(null),[u,g]=A(null),[w,m]=A(null),[I,z]=A(null),[C,y]=A(null),R=Se(null),L=xe(()=>Zr({satsuma:jo}),[]),S=xe(()=>$a({customVenues:[Yr(jo),Yr(Vr)]}),[]),v=xe(()=>{if(!o?.asset)return null;if(o.asset.chainId===a)return o.asset.address;const W=gn(o.asset.address,a);return W?W.address:null},[o?.asset?.address,o?.asset?.chainId,a]),P=xe(()=>o?.asset?o.asset.address.toLowerCase()===s.address.toLowerCase()&&o.asset.chainId===a?!0:v?v.toLowerCase()===s.address.toLowerCase():!1:!1,[o,s.address,a,v]),b=v?v.toLowerCase()===s.address.toLowerCase():!1,k=n==="output"&&parseFloat(r||"0")===0,j=!!o?.asset&&!P&&!b&&!k;return te(()=>{R.current&&clearTimeout(R.current);const W=n==="input"?o?.amount:r,T=parseFloat(W||"0");if(!j||T<=0||!o?.asset||!i||!v){x(null),g(null),m(null),z(null),y(null),p(null),d(!1);return}return d(!0),R.current=setTimeout(async()=>{try{if(n==="input"){const D=at(o.amount,o.asset.decimals),J=L.getVenueForChain(a);if(!J)throw new Error("No swap venue for this chain");const q=await J.resolve({type:"swap",tokenIn:v,tokenOut:s.address,amountIn:D},a,i);if(!q)throw new Error("No liquidity for this pair");y(q.amountOut),m(q),z(null);const H=hn(q.amountOut,s.decimals),V=parseFloat(H);x(V<.01?V.toPrecision(4):V.toLocaleString(void 0,{maximumFractionDigits:6})),g(null),p(null)}else{const D=at(r||"0",s.decimals),J=await S.getQuote({tokenIn:v,tokenOut:s.address,amountOut:D},a,i);z(J),m(null),y(null),g(parseFloat(hn(J.amountIn,o.asset.decimals)).toFixed(6)),x(null),p(null)}}catch(D){const J=D instanceof Error?D.message:"Failed to get quote";p(J),x(null),g(null),m(null),z(null),y(null)}finally{d(!1)}},500),()=>{R.current&&clearTimeout(R.current)}},[n,j,o?.amount,o?.asset?.address,o?.asset?.decimals,r,v,a,s.address,s.decimals,i,L,S]),{isQuoting:c,quoteError:h,estimatedOutput:f,estimatedInput:u,resolvedSwap:w,exactOutputSwap:I,quoteAmountOut:C,resolvedTokenIn:v,isDirect:b,needsSwap:j,selectedIsEquivalent:P}}const Kr={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Transaction successful!",error:"Transaction failed"},Xr=["signing-delegation","signing-intent","submitting","executing"],ei=({color:t})=>l("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",style:{marginTop:"1px",flexShrink:0},children:[e("circle",{cx:"7",cy:"7",r:"6.5",stroke:t,strokeWidth:"1.2"}),e("path",{d:"M7 6v4",stroke:t,strokeWidth:"1.2",strokeLinecap:"round"}),e("circle",{cx:"7",cy:"4.5",r:"0.7",fill:t})]}),qr=({isOpen:t,onClose:n,destinationToken:o,buildActionCalls:s,buildSpicenetBatch:a,actionLabel:i,amountDirection:r="input",swapDescription:c,directDescription:d,supportedSourceAssets:h,sourceChains:p,paymentAmount:f,amountInputMode:x="fixed",minPaymentAmount:u,maxPaymentAmount:g,onAmountChange:w,styles:m,dark:I,title:z,subtitle:C,onAddFunds:y,onSuccess:R,onError:L})=>{const S=r==="output",{theme:v,dark:P,primaryColor:b,dk:k,palette:j}=Ze(m,I),W=v.typography.fontFamily,T=m?.inputVariant?m.inputVariant==="dark":P,D=j.textPrimary,J=j.textSecondary,q=T?k.cardBg:"#f9fafb",H=T?k.cardBorder:"#e5e7eb",V=m?.button?.backgroundColor??b,$=m?.button?.color??"#0e0d0b",O=T?{...v,colors:{...v.colors,secondary:k.cardBg,surfaceHover:k.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:v,M=o.chainId,re=sn(),{address:ye,isConnected:ke,isReady:pe,isAuthenticated:ge,provider:Ce}=re,{executeGasless:De}=co(),{displayAssets:Ie,filteredSpiceAssets:Qe,embeddedWalletAddress:me,refreshSpiceAssets:Ne,refreshWalletAssets:Pe}=Ya({address:ye,destinationToken:o,supportedSourceAssets:h,sourceChains:p,enabled:t&&!!ye}),ne=xe(()=>Qe.map(ee=>({...ee,_source:"spice"})),[Qe]),Be=S?Ie:ne,[_,ae]=A(null),[tt,Xe]=A(f||""),[K,ue]=A(!1),[B,U]=A(null),[G,he]=A("idle"),[F,Y]=A(""),[oe,de]=A(null),[qe,gt]=A(!1),[Re,Je]=A(null),ve=Se(_),pt=Se(!1),Ct=Se(null);te(()=>{ve.current=_},[_]);const Te=x==="adjustable"?tt:f||"0",At=me||ye,{isQuoting:wt,quoteError:Tt,estimatedOutput:en,resolvedSwap:Lt,exactOutputSwap:it,quoteAmountOut:Ot,resolvedTokenIn:Mt,isDirect:xt,needsSwap:It,selectedIsEquivalent:$e}=_a({direction:r,selectedAsset:_,destinationToken:o,chainId:M,recipient:At,paymentAmount:Te}),mt=S?parseFloat(Te||"0"):parseFloat(_?.amount||"")||0,Et=xe(()=>_?.asset?Qe.find(ee=>ee.address.toLowerCase()===_.asset.address.toLowerCase())?.balanceFormatted??0:0,[_,Qe]),vt=xe(()=>_?.asset?S?$e?mt>_.asset.balanceFormatted:it?parseFloat(hn(it.amountInMax,_.asset.decimals))>_.asset.balanceFormatted:!1:mt>Et:!1,[_,S,$e,mt,it,Et]);te(()=>{t||(ae(null),U(null),ue(!1),he("idle"),Y(""),de(null),gt(!1),Je(null),pt.current=!1,x==="adjustable"&&Xe(f||""),Ct.current&&(Ct.current.abort(),Ct.current=null))},[t]);const kt=fe(ee=>{ae(le=>({asset:ee,amount:le?.asset?.address===ee.address&&le?.asset?.chainId===ee.chainId&&le.amount||""})),U(null)},[]),Vt=fe(ee=>{ae(le=>le&&{...le,amount:ee}),U(null)},[]),se=fe(ee=>{let le=ee;g&&parseFloat(le)>parseFloat(g)&&(le=g),Xe(le),w?.(le),U(null)},[g,w]);fe(ee=>{if(pt.current||!ye)return;const le=ve.current;!le?.asset||!le.amount||le.asset?._source==="wallet"||at(S?Te:le.amount,le.asset.decimals)===0n||(pt.current=!0,Ne())},[ye,M,Ne,S,Te]);const ce=fe(ee=>{he({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[ee.step]||"executing"),Y(ee.message),ee.txHash&&de(ee.txHash)},[]),He=fe(()=>{const ee=at(Te,o.decimals),le={userAddress:me,chainId:M,destinationToken:o.address},be=s(ee,le),Ae={chainId:M,calls:be},Me=_?.asset?._source==="spice",Fe=(ze,we)=>({token:ze,from:"solver",to:me,amount:we});if(ee===0n)return[Ae];if(It&&it){let ze=_.asset.address;if(_.asset.chainId!==M){const Z=_n(_.asset.address)?.deployments.find(E=>E.chainId===M);Z&&(ze=Z.address)}const we=Me?[Fe(ze,it.amountInMax)]:[],N={to:ze,value:0n,data:qt({abi:Ut,functionName:"approve",args:[it.calls[0]?.to,it.amountInMax]})};return[{chainId:M,calls:[N,...it.calls,...be],tokenTransfers:[...we,...Ae.tokenTransfers??[]]}]}if(Me){let ze=o.address;if(_.asset.chainId!==M){const we=_n(_.asset.address)?.deployments.find(N=>N.chainId===M);we&&(ze=we.address)}return[{...Ae,tokenTransfers:[Fe(ze,ee),...Ae.tokenTransfers??[]]}]}return[Ae]},[Te,o,me,M,s,_,It,it]),nt=fe(()=>{if(!_?.asset||!me)return[];const ee=at(_.amount,_.asset.decimals),le={userAddress:me,chainId:M,destinationToken:o.address},be=s(ee,le),Ae=_.asset?._source==="spice";if(!Ae)return[{chainId:M,calls:be}];const Me=(N,Z)=>({token:N,from:"solver",to:me,amount:Z});if(It&&Lt&&Ot&&Mt){const N=s(Ot,le),Z={chainId:M,calls:[...Lt.calls,...N],tokenTransfers:[Me(Mt,ee)]};if(!a)return[Z];const E=a({userAddress:me,destinationChainId:M,deliveryToken:Mt,deliveryAmount:ee});return console.log("[SpiceSupply] buildSupplyChainBatches:swap",{isSpiceSourced:Ae,hasBuildSpicenetBatch:!!a,amountIn:ee.toString(),resolvedTokenIn:Mt,spicenetBatch:E}),E?[E,Z]:[Z]}let Fe=o.address;if(_.asset.chainId!==M){const N=_n(_.asset.address)?.deployments.find(Z=>Z.chainId===M);N&&(Fe=N.address)}const ze={chainId:M,calls:be,tokenTransfers:[Me(Fe,ee)]};if(!a)return[ze];const we=a({userAddress:me,destinationChainId:M,deliveryToken:Fe,deliveryAmount:ee});return console.log("[SpiceSupply] buildSupplyChainBatches:direct",{isSpiceSourced:Ae,hasBuildSpicenetBatch:!!a,amountIn:ee.toString(),deliveryToken:Fe,spicenetBatch:we}),we?[we,ze]:[ze]},[_,me,M,o,s,It,Lt,Ot,Mt,a]),ut=xe(()=>{if(!_?.asset)return o.address;if(_.asset.chainId===M)return _.asset.address;const ee=_n(_.asset.address)?.deployments.find(le=>le.chainId===M);return ee?ee.address:o.address},[_,o.address,M]),yt=fe(async()=>{if(!_?.asset||mt<=0){U("Select an asset and enter an amount");return}if(vt){U("Insufficient balance");return}if(!me){U("Wallet not ready");return}ue(!0),U(null),he("signing-delegation"),Y("Building transaction..."),de(null),pt.current=!1;const ee=new AbortController;Ct.current=ee;try{const le=at(_.amount,_.asset.decimals),be=nt(),Ae=be.some(Me=>Me.tokenTransfers?.length);await De(be,ut,le,ce,ee.signal,Ae?{useCustomTransfers:!0}:void 0),he("success"),Y("Transaction successful!")}catch(le){const be=le instanceof Error?le:new Error(String(le));if(be.name==="AbortError"||ee.signal.aborted){he("idle");return}const Ae=be.message||"Transaction failed";he("error"),Y(Ae),U(Ae),L?.(be)}finally{ue(!1)}},[_,mt,vt,me,ut,nt,De,ce,L]),ot=fe(async()=>{if(mt<0){U("Enter a valid payment amount");return}if(!_?.asset){U("Select a payment source");return}if(vt){U("Insufficient balance");return}if(It&&!it){U("Swap quote not available. Try a different asset.");return}if(!ke||!ye){U("Please connect your wallet to continue");return}if(!pe||!ge){U(`Please authenticate with ${Ce||"wallet provider"} to continue`);return}ue(!0),U(null),gt(!0),Je({status:"processing"});try{const ee=He(),le=ee.some(Fe=>Fe.tokenTransfers?.length),be=at(Te,o.decimals),Ae=_?.asset?.address||o.address,Me=await De(ee,Ae,be,Fe=>{Fe.txHash&&(Je(ze=>({...ze,txHash:Fe.txHash})),de(Fe.txHash))},void 0,le?{useCustomTransfers:!0}:void 0);Je(Fe=>({status:"success",txHash:Fe?.txHash||Me}))}catch(ee){const le=on(ee,"Payment failed. Please try again.");U(le),Je({status:"failed",error:le}),L?.(ee instanceof Error?ee:new Error(le))}finally{ue(!1)}},[mt,_,vt,It,it,ke,ye,pe,ge,Ce,He,Te,o,De,L]);te(()=>{!S&&G==="success"&&oe&&(Ne(),R?.(oe))},[S,G,oe,Ne,R]),te(()=>{if(!S||Re?.status!=="success"||pt.current||!ye)return;pt.current=!0;const ee=ve.current;!ee?.asset||ee.asset?._source==="wallet"||Ne()},[S,Re?.status,ye,Ne]);const Ge=Se(R),Wt=Se(L);te(()=>{Ge.current=R},[R]),te(()=>{Wt.current=L},[L]),te(()=>{S&&(Re?.status==="success"&&Ge.current?.(Re.txHash||""),Re?.status==="failed"&&Wt.current?.(new Error("Payment execution failed")))},[S,Re?.status]);const Pt=fe(()=>{gt(!1),Je(null),ae(null),pt.current=!1,Ne(),Pe()},[Ne,Pe]),Qt=S?!!_?.asset&&mt>=0&&!vt&&!K&&(!It||!!it):!!_?.asset&&mt>0&&!vt&&!K&&(xt||!!Lt&&!wt),Ht=xt?d||`Your ${o.symbol} will be used directly.`:c||"Your assets will be swapped and used in a single atomic transaction.",Yt=P?k.shell:"white",Jt=P?k.buttonBorder:"#0e0d0b",mn=(M?je(M):void 0)?.viemChain?.blockExplorers?.default?.url??"",cn=Xr.indexOf(G),Q=K?(Kr[G]||"EXECUTING...").toUpperCase():G==="success"?"DONE":vt?"INSUFFICIENT BALANCE":i.toUpperCase(),ie=xe(()=>{if(K)return"PAYING...";if(vt&&_?.asset)return`INSUFFICIENT ${_.asset.symbol}`;const ee=mt>0?` ${Te} ${o.symbol}`:"";return It?`SWAP & PAY${ee}`:`PAY${ee}`},[K,vt,_,mt,Te,o.symbol,It]),We=G==="success"?()=>{he("idle"),ae(null),de(null),Ne()}:yt,Ue=G==="success"?!1:!Qt;if(!t)return null;const Ve=S?z||`Pay ${o.symbol}`:i,bt=S?C:l("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[e(ei,{color:J}),e("p",{style:{fontSize:"13px",color:J,margin:0,lineHeight:"1.5"},children:Ht})]});if(S){const ee=Re&&(Re.status==="success"||Re.status==="failed")?[{asset:{symbol:_?.asset?.symbol||o.symbol,address:_?.asset?.address||""},amount:Te,txHash:Re.txHash||"",success:Re.status==="success",error:Re.status==="failed"?Re.error:void 0}]:void 0;return e(Gt,{isOpen:t,onClose:n,title:Ve,subtitle:bt,styles:m,dark:P,footerLinkText:"Spicenet accounts \u2192",children:l("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[y&&e("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:l("button",{onClick:y,style:{background:"none",border:"none",cursor:"pointer",padding:0,display:"flex",alignItems:"center",gap:"4px",color:b,fontSize:"12px",fontWeight:500,fontFamily:W,textDecoration:"underline",textUnderlineOffset:"2px"},children:["Add Funds",l("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:b,strokeWidth:"1.8",children:[e("circle",{cx:"6",cy:"6",r:"5"}),e("path",{d:"M6 4v4M4 6h4",strokeLinecap:"round"})]})]})}),e("div",{style:{marginBottom:"12px"},children:e(Nn,{assets:Be,selectedAsset:_??void 0,onAssetSelect:kt,onAmountChange:()=>{},label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:_?.asset?It?wt?"...":it?`~${parseFloat(hn(it.amountIn,_.asset.decimals)).toFixed(6)}`:void 0:Te??void 0:void 0,dark:P,theme:O,styles:m})}),e(Dr,{variant:"pay",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:b,fontFamily:W,textPrimary:D,textSecondary:J,cardBg:q,cardBorder:H,dk:k,dark:P,isQuoting:wt,quoteError:Tt,estimatedOutput:en,paymentAmount:Te,needsSwap:It,exactOutputSwap:it,adjustable:x==="adjustable",maxAmount:g,onAmountChange:se}),B&&e("div",{style:{marginBottom:"12px",padding:"10px 14px",backgroundColor:j.errorBg,border:`1px solid ${j.errorBorder}`,borderRadius:"6px"},children:e("p",{style:{color:j.errorText,fontSize:"13px",margin:0,fontFamily:W},children:B})}),e(et,{variant:"outline",fullWidth:!0,onClick:ot,disabled:!Qt,loading:K,dark:P,styles:{button:{backgroundColor:b}},children:ie}),Re&&qe&&e("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:P?k.shell:"white",borderRadius:P?"12px":"6px",padding:"16px 0"},children:e(On,{type:"payment",isOpen:Re.status!=="processing",isProcessing:K||Re.status==="processing",closeOnComplete:!1,chainName:Nt(M),explorerUrl:kn(M,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{gt(!1),Je(null),ot()},onNewTx:Pt,onClose:()=>{gt(!1),Je(null)},onComplete:Pt,results:ee,styles:m,dark:P})})]})})}return l(Gt,{isOpen:t,onClose:n,title:Ve,subtitle:bt,dark:P,styles:m,theme:v,children:[e("div",{style:{marginBottom:"16px"},children:e(Nn,{assets:Be,selectedAsset:_||void 0,onAssetSelect:kt,onAmountChange:Vt,disabled:K||G==="success",showBalance:!0,showMaxButton:!0,label:"From Spice Balance",placeholder:"0.00",theme:O,styles:m,dark:T,maxAmount:Et>0?Et.toString():void 0})}),_?.asset&&!xt&&e(Dr,{variant:"supply",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:b,fontFamily:W,textPrimary:D,textSecondary:J,cardBg:q,cardBorder:H,dark:P,isQuoting:wt,quoteError:Tt,estimatedOutput:en}),G!=="idle"&&l("div",{style:{padding:"10px 14px",borderRadius:"10px",marginBottom:"16px",backgroundColor:G==="success"?j.successBg:G==="error"?j.errorBg:q,border:`1px solid ${G==="success"?j.successBorder:G==="error"?j.errorBorder:H}`},children:[l("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[G==="success"?e("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:e("path",{d:"M5 13l4 4L19 7",stroke:j.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):G==="error"?e("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:e("path",{d:"M18 6L6 18M6 6l12 12",stroke:j.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):e(Bn,{size:14,color:b}),e("span",{style:{fontSize:"13px",fontWeight:500,color:G==="success"?j.successText:G==="error"?j.errorText:D,fontFamily:W,flex:1},children:G==="success"?"Transaction successful!":G==="error"?F||"Transaction failed":Kr[G]||F}),G==="success"&&oe&&e("a",{href:`${mn}/tx/${oe}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:b,fontFamily:W,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),G==="error"&&e("button",{onClick:()=>{he("idle"),U(null),setTimeout(yt,50)},style:{background:"none",border:"none",fontSize:"12px",color:b,fontFamily:W,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),cn>=0&&G!=="success"&&G!=="error"&&e("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${J}22`,overflow:"hidden"},children:e("div",{style:{height:"100%",borderRadius:"2px",backgroundColor:b,width:`${(cn+1)/Xr.length*100}%`,transition:"width 400ms ease"}})})]}),B&&G==="idle"&&e("div",{style:{padding:"10px 14px",borderRadius:"10px",backgroundColor:j.errorBg,border:`1px solid ${j.errorBorder}`,marginBottom:"16px"},children:e("p",{style:{fontSize:"13px",color:j.errorText,margin:0,fontFamily:W},children:B})}),e(et,{variant:"outline",fullWidth:!0,disabled:Ue,onClick:We,style:{height:"56px",backgroundColor:Ue?`${V}66`:G==="success"?j.successBg:V,color:G==="success"?j.successText:$,border:`1px solid ${G==="success"?j.successBorder:Jt}`,fontSize:"14px",fontWeight:700,letterSpacing:"2px",fontFamily:'"IBM Plex Mono", monospace',boxShadow:Ue?"none":`3px 3px 0px ${Yt}, 4px 4px 0px ${Jt}`,cursor:Ue?"not-allowed":"pointer",opacity:Ue?.6:1},children:Q})]})},ti=t=>e(qr,{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}),ni=({label:t="Export Wallet",style:n,className:o,onExport:s,onError:a})=>{const[i,r]=A(!1),[c,d]=A(!1),{primaryColor:h}=Ze(),p=Dt(Ft),{isAuthenticated:f}=sn();let x=null;try{x=no()}catch{}let u=null,g=null;try{u=Cs(),g=oo()}catch{u=null,g=null}const w=ro(g),m=fe(async()=>{if(!f){a?.("User is not authenticated. Please log in first.");return}try{if(p?.provider==="dynamic"){if(!u||!w){a?.("Dynamic is not available. Ensure the app is wrapped in a DynamicContextProvider.");return}await u.initExportProcess(!1),s?.();return}if(!x){a?.("Privy is not available. Ensure the app is wrapped in a PrivyProvider.");return}await x.exportWallet(),s?.()}catch(C){const y=C instanceof Error?C.message:"Failed to export wallet";console.error("Export wallet error:",C),a?.(y)}},[w,u,f,a,s,x,p?.provider]),I=!f,z={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?`${h}cc`:i?`${h}ee`:h,transition:"all 150ms ease",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"8px",...n};return l("button",{onClick:m,onMouseEnter:()=>r(!0),onMouseLeave:()=>{r(!1),d(!1)},onMouseDown:()=>d(!0),onMouseUp:()=>d(!1),disabled:I,className:o,style:z,children:[l("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),e("polyline",{points:"17 8 12 3 7 8"}),e("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]}),t]})};function Gr(t){const n=Dt(Ft),o=rn(),s=t?.enabled===!1?void 0:o,a=n?.network?{network:n.network,pollIntervalMs:t?.pollIntervalMs,chainIds:t?.chainIds??n.supportedChainIds}:void 0;return{...vr(s,a),embeddedWalletAddress:o}}const oi=({appName:t,status:n,statusLabel:o,totalUsdValue:s,breakdownSubtitle:a,address:i,dk:r,dark:c=!1,showModeToggle:d,isEmbeddedMode:h=!0,onModeToggle:p})=>{const[f,x]=A(!1),u=async()=>{i&&await Hs(i)&&(x(!0),setTimeout(()=>x(!1),2e3))},g=n==="active",w=o||(g?"Active":"Inactive"),m=g?"#10b981":"#9ca3af";return l("div",{children:[l("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[l("div",{style:{fontSize:"13px",fontWeight:600,color:c?r.textPrimary:"#111827"},children:[t," Account"]}),d?l("button",{onClick:p,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("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:h?"#22c55e":"#f59e0b"}}),e("span",{children:h?"Embedded":"External"})]}):l("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:c?r.hoverBg:g?"#ecfdf5":"#f3f4f6",border:c?`1px solid ${r.cardBorder}`:g?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[e("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:m}}),e("span",{style:{fontSize:"11px",fontWeight:500,color:c?r.textSecondary:g?"#065f46":"#6b7280"},children:w})]})]}),e("div",{style:{fontSize:"28px",fontWeight:700,color:c?r.textPrimary:"#111827",lineHeight:1.2,marginBottom:"2px"},children:zn(s)}),a&&e("div",{style:{fontSize:"12px",color:c?r.textSecondary:"#6b7280",marginBottom:"8px"},children:a}),i&&l("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[e("span",{style:{fontSize:"12px",fontFamily:'"IBM Plex Mono", monospace',color:c?r.textSecondary:"#9ca3af"},children:Ps(i)}),e("button",{onClick:u,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:f?"Copied":"Copy"})]})]})},ri=({pendingDeposits:t,onCompleteDeposit:n,dk:o,dark:s=!1})=>t.length===0?null:l("div",{children:[e("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:s?o.textSecondary:"#6b7280",marginBottom:"8px",textTransform:"uppercase"},children:"Pending Deposits"}),e("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:t.map((a,i)=>{const r=je(a.chainId)?.displayName||`Chain ${a.chainId}`;return l("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:s?o.warningBg:"#fffbeb",border:s?`1px solid ${o.warningBorder}`:"1px solid #fde68a",borderRadius:"8px"},children:[l("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:s?o.hoverBg:"#fde68a",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:s?o.warningText:"#92400e"},children:a.tokenSymbol.charAt(0)}),l("div",{children:[l("div",{style:{fontSize:"13px",fontWeight:500,color:s?o.textPrimary:"#111827"},children:[a.amount," ",a.tokenSymbol]}),l("div",{style:{fontSize:"11px",color:s?o.warningText:"#92400e"},children:["on ",r]})]})]}),e("button",{onClick:()=>n?.(a),style:{padding:"4px 12px",fontSize:"11px",fontWeight:600,backgroundColor:s?o.hoverBg:"#fef3c7",color:s?o.textPrimary:"#92400e",border:s?`1px solid ${o.warningBorder}`:"1px solid #fde68a",borderRadius:"9999px",cursor:"pointer",transition:"all 150ms ease"},children:"Complete"})]},`${a.tokenAddress}-${a.chainId}-${i}`)})})]}),si=({spiceAssets:t,loading:n,dk:o,dark:s=!1})=>{const a={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:s?o.textSecondary:"#6b7280",marginBottom:"8px",textTransform:"uppercase"},i={backgroundColor:s?o.cardBg:"#f9fafb",border:s?`1px solid ${o.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return n?l("div",{children:[e("div",{style:a,children:"Idle Balances"}),[1,2].map(r=>e("div",{style:{...i,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},r))]}):t.length===0?l("div",{children:[e("div",{style:a,children:"Idle Balances"}),e("div",{style:{...i,padding:"16px",textAlign:"center",fontSize:"13px",color:s?o.textSecondary:"#9ca3af"},children:"No assets yet. Deposit to get started."})]}):l("div",{children:[e("div",{style:a,children:"Idle Balances"}),e("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:t.map((r,c)=>{const d=je(r.chainId),h=r.chainDisplayName||d?.displayName||`Chain ${r.chainId}`,p=r.tokenDisplaySymbol||r.tokenDisplayName||r.tokenSymbol;return l("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...i},children:[l("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[r.logoURI?e("img",{src:r.logoURI,alt:r.tokenSymbol,style:{width:"24px",height:"24px",borderRadius:"50%"}}):e("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:s?o.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:s?o.textSecondary:"#6b7280"},children:p.charAt(0)}),l("div",{children:[e("div",{style:{fontSize:"13px",fontWeight:500,color:s?o.textPrimary:"#111827"},children:p}),e("div",{style:{fontSize:"11px",color:s?o.textSecondary:"#9ca3af"},children:h})]})]}),l("div",{style:{textAlign:"right"},children:[e("div",{style:{fontSize:"13px",fontWeight:500,color:s?o.textPrimary:"#111827"},children:xn(r.balanceFormatted)}),e("div",{style:{fontSize:"11px",color:s?o.textSecondary:"#9ca3af"},children:zn(r.usdValue)})]})]},`${r.tokenAddress}-${r.chainId}-${c}`)})})]})},ai=({section:t,dk:n,dark:o=!1})=>{const s=a=>{switch(a){case"green":return"#10b981";case"red":return"#ef4444";default:return o?n.textPrimary:"#111827"}};return l("div",{children:[e("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:o?n.textSecondary:"#6b7280",marginBottom:"8px",textTransform:"uppercase"},children:t.title}),e("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:t.items.map((a,i)=>l("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:o?n.cardBg:"#f9fafb",border:o?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"},children:[l("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[a.tokenLogoURI?e("img",{src:a.tokenLogoURI,alt:a.tokenSymbol,style:{width:"20px",height:"20px",borderRadius:"50%"}}):e("div",{style:{width:"20px",height:"20px",borderRadius:"50%",backgroundColor:o?n.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",fontWeight:600,color:o?n.textSecondary:"#6b7280"},children:a.tokenSymbol.charAt(0)}),l("div",{children:[e("div",{style:{fontSize:"13px",fontWeight:500,color:o?n.textPrimary:"#111827"},children:a.tokenSymbol}),e("div",{style:{fontSize:"11px",color:o?n.textSecondary:"#6b7280"},children:a.label})]})]}),e("div",{style:{fontSize:"13px",fontWeight:600,color:s(a.valueColor)},children:a.displayValue})]},i))})]})},ii=({onDepositClick:t,onWithdrawClick:n,depositDisabled:o=!1,withdrawDisabled:s=!1,primaryColor:a="#EA4B4B",dark:i=!1})=>!t&&!n?null:l("div",{style:{display:"flex",gap:"8px"},children:[t&&e(et,{variant:"outline",onClick:t,disabled:o,dark:i,styles:{button:{backgroundColor:a}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),n&&e(et,{variant:"outline",onClick:n,disabled:s,dark:i,styles:{button:{backgroundColor:a}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),li=({appName:t,status:n,statusLabel:o,totalUsdValue:s,breakdownSubtitle:a,address:i,spiceAssets:r,spiceAssetsLoading:c,pendingDeposits:d,customSections:h,onDepositClick:p,onWithdrawClick:f,onCompleteDeposit:x,primaryColor:u,dk:g,dark:w=!1,showModeToggle:m,isEmbeddedMode:I,onModeToggle:z})=>{const[C,y]=A(!1);return l("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[e(oi,{appName:t,status:n,statusLabel:o,totalUsdValue:s,breakdownSubtitle:a,address:i,dk:g,dark:w,showModeToggle:m,isEmbeddedMode:I,onModeToggle:z}),e("div",{style:{height:"1px",backgroundColor:w?"#2d2d2d":"#e5e7eb"}}),l("div",{children:[l("button",{onClick:()=>y(!C),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:w?g.cardBg:"#f9fafb",border:w?`1px solid ${g.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:w?g.textSecondary:"#6b7280",fontSize:"12px",fontWeight:500},children:[e("span",{children:"How It Works"}),e("span",{style:{transform:C?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),C&&l("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:w?g.cardBg:"#f0fdf4",border:w?`1px solid ${g.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:w?g.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(ri,{pendingDeposits:d,onCompleteDeposit:x,dk:g,dark:w}),e(si,{spiceAssets:r,loading:c,dk:g,dark:w}),h.map((R,L)=>e(ai,{section:R,dk:g,dark:w},L)),e(ii,{onDepositClick:p,onWithdrawClick:f,primaryColor:u,dark:w})]})},Oo=380,Ln=8,di=({appName:t="Spice",status:n="active",statusLabel:o,customSections:s=[],extraAssets:a=[],tokenPrices:i={},breakdownLabels:r=[],supportedChains:c,styles:d,dark:h=!1,onDepositSuccess:p,onDepositClick:f,onWithdrawClick:x,onCompleteDeposit:u,showModeToggle:g=!1,defaultMode:w})=>{const m=Dt(Ft),I=m?.mode!=="7702";te(()=>{w&&m?.setMode&&m.setMode(w==="non7702"?"ondemand":"7702")},[m,w]);const[z,C]=A(!1),[y,R]=A(null),[L,S]=A({top:0,left:0,placement:"below"}),v=Se(null),P=Se(null),{address:b,isConnected:k}=sn(),j=rn(),{address:W}=nn(),{dark:T,primaryColor:D,dk:J}=Ze(d,h),q=xe(()=>c||$n("mainnet"),[c]),{assets:H,loading:V}=Dn({address:b,supportedChains:q,enabled:!!b&&!I,refetchInterval:3e4}),$=xe(()=>[...I?[]:H.map(ne=>{const Be=ne.balanceUsd||0,_=Number.isFinite(ne.balanceFormatted)?ne.balanceFormatted:0,ae=Be>0?Be:(i[ne.symbol]||0)*_;return{tokenAddress:ne.address,tokenSymbol:ne.symbol,tokenDisplaySymbol:Bo(ne),tokenDisplayName:js(ne),tokenDecimals:ne.decimals,chainId:ne.chainId,chainDisplayName:Fo(ne),balance:ne.balance.toString(),balanceFormatted:ne.balanceFormatted,usdValue:ae,logoURI:ne.logoURI}}),...a].filter(ne=>ne.balanceFormatted>0),[I,H,i,a]),O=xe(()=>$.reduce((ne,Be)=>ne+Be.usdValue,0),[$]),{pendingDeposits:M}=Gr({chainIds:q,enabled:!!b}),re=xe(()=>s.reduce((ne,Be)=>ne+Be.totalValue,0),[s]),ye=O+re,ke=xe(()=>{const ne=[];O>0&&ne.push(`${zn(O)} idle`);for(const Be of s){const _=r.find(ae=>ae.sectionTitle===Be.title)?.label||Be.title.toLowerCase();ne.push(`${zn(Be.totalValue)} ${_}`)}return ne.join(" \xB7 ")},[O,s,r]),pe=fe(ne=>{u?u(ne):R(ne)},[u]),ge=fe(()=>{R(null)},[]),Ce=fe(()=>{R(null),p?.()},[p]),De=fe(()=>{if(!v.current)return;const ne=v.current.getBoundingClientRect(),Be=window.innerHeight-ne.bottom-Ln,_=ne.top-Ln,ae=Be>=400||Be>=_?"below":"above",tt=Math.max(Ln,Math.min(ne.right-Oo,window.innerWidth-Oo-Ln)),Xe=ae==="below"?ne.bottom+Ln:ne.top-Ln;S({top:Xe,left:tt,placement:ae})},[]);ts(()=>{z&&De()},[z,De]),te(()=>{if(!z)return;const ne=ae=>{v.current&&!v.current.contains(ae.target)&&P.current&&!P.current.contains(ae.target)&&C(!1)},Be=ae=>{ae.key==="Escape"&&C(!1)},_=()=>De();return document.addEventListener("mousedown",ne),document.addEventListener("keydown",Be),window.addEventListener("scroll",_,{passive:!0}),window.addEventListener("resize",De),()=>{document.removeEventListener("mousedown",ne),document.removeEventListener("keydown",Be),window.removeEventListener("scroll",_),window.removeEventListener("resize",De)}},[z,De]);const Ie=m?.mode==="7702",Qe=Ie?j||b:W||b,me=fe(()=>{m?.setMode&&m.setMode(Ie?"ondemand":"7702")},[m,Ie]);if(typeof window>"u")return null;const Ne=l("button",{ref:v,onClick:()=>C(!z),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:T?J.hoverBg:"#ffffff",border:T?`1px solid ${J.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:'"Helvetica Neue", sans-serif',color:T?J.textPrimary:"#111827",transition:"all 150ms ease",boxShadow:T?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[e("span",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:D,flexShrink:0}}),l("span",{children:[t," Account"]}),k&&l("span",{style:{color:T?J.textSecondary:"#6b7280"},children:["\xB7 ",zn(ye)]}),e("span",{style:{fontSize:"10px",color:T?J.textSecondary:"#9ca3af",transform:z?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),Pe=z?Ss.createPortal(l(tn,{children:[e("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:9998},onClick:()=>C(!1)}),e("div",{ref:P,style:{position:"fixed",top:L.placement==="below"?`${L.top}px`:"auto",bottom:L.placement==="above"?`${window.innerHeight-L.top}px`:"auto",left:`${L.left}px`,width:`${Oo}px`,maxHeight:"80vh",backgroundColor:T?J.shell:"#ffffff",border:T?`1px solid ${J.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:T?"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(li,{appName:t,status:n,statusLabel:o,totalUsdValue:ye,breakdownSubtitle:ke,address:g?Qe:b,spiceAssets:$,spiceAssetsLoading:V,pendingDeposits:M,customSections:s,onDepositClick:f,onWithdrawClick:x,onCompleteDeposit:pe,primaryColor:D,dk:J,dark:T,showModeToggle:g,isEmbeddedMode:Ie,onModeToggle:me})}),e("style",{children:`
|
|
115
115
|
@keyframes accountDisplayFadeIn {
|
|
116
116
|
from { opacity: 0; transform: translateY(-4px); }
|
|
117
117
|
to { opacity: 1; transform: translateY(0); }
|