@spicenet-io/spiceflow-ui 3.3.60 → 3.3.61-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -100,7 +100,7 @@ import{jsxs as g,jsx as a,Fragment as nn}from"react/jsx-runtime";import an,{useS
100
100
  from { transform: rotate(0deg); }
101
101
  to { transform: rotate(360deg); }
102
102
  }
103
- `})]})},mc="0xa9059cbb";function gc(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const o=Me(n.token),s=Me(n.to),r=`${o.toLowerCase()}:${s.toLowerCase()}`,i=t.get(r);i?i.amount+=n.amount:t.set(r,{token:o,to:s,amount:n.amount})}return[...t.values()]}function yc(e,t){return`0x${t}${e.slice(4)}`}function xc(e,t,n){if(!Array.isArray(e))return 0n;const o=`evm:${t}:${n.slice(2).toLowerCase()}`;let s=0n;for(const r of e){if(!r||typeof r!="object")continue;const i=r,c=i.chainTokens;if((Array.isArray(c)?c.filter(d=>typeof d=="string"):c&&typeof c=="object"?Object.keys(c):[]).some(d=>d.toLowerCase()===o))try{s+=BigInt(i.balanceAvailable??"0")}catch{}}return s}async function la(e,t,n,o){const s=await fetch(`${e}/wallets/${t}/balance`,{cache:"no-store"});if(!s.ok)throw new Error(`Failed to fetch spice balance: ${s.status}`);const r=await s.json();return xc(r?.balances,n,o)}async function bc({apiBaseUrl:e,user:t,chainId:n,tokenAddress:o,prevBalance:s,timeoutMs:r=3e4,pollIntervalMs:i=1500}){const c=Date.now()+r;for(await new Promise(d=>setTimeout(d,800));Date.now()<c;){try{if(await la(e,t,n,o)>s)return}catch(d){console.warn("[SpiceLockModal] spice balance poll failed:",d?.message)}await new Promise(d=>setTimeout(d,i))}console.warn("[SpiceLockModal] Spicenet indexer did not reflect deposit within timeout; proceeding with intent")}function Hs(e,t){return js(e,t)}function js(e,t,n){const o=wc(t,e),s=Math.floor(Date.now()/1e3)+60*10,r=Un(o);return{user:e,...n?{chainAuthorizations:n}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:"0x00",nbf:0,exp:s,chainBatches:r.map((i,c)=>({hash:i.hash,chainId:i.chainId,tokenTransfers:o[c].domain==="spicenet"?[]:o[c].tokenTransfers??[],calls:i.calls}))}]}}function wc(e,t){return e.map(n=>{if(n.domain==="spicenet"||n.calls.length===0)return n;const o=new Set((n.tokenTransfers??[]).filter(r=>(r.from==="escrow"||r.from==="solver")&&Me(r.to).toLowerCase()===t.toLowerCase()).map(r=>Me(r.token).toLowerCase()));if(o.size===0)return n;let s=0;for(const r of n.calls){if(!r.data?.startsWith(mc))break;try{const i=Co({abi:Ke,data:r.data});if(i.functionName!=="transfer")break;const[c]=i.args;if(c.toLowerCase()===t.toLowerCase()||!o.has(Me(r.to).toLowerCase()))break;s+=1}catch{break}}return s===0?n:{...n,calls:n.calls.slice(s)}})}function dn(e,t,n,o){if(e.some(l=>l.domain==="spicenet"))return e;const s=n?.intents.flatMap(l=>l.batches),r=l=>l.from==="escrow",i=e.map(l=>{const p=s?.find(C=>C.chainId===l.chainId);if(!p)return l;const u=Fn(p),f=u.totalFee;if(f<=0n)return l;const h=(l.tokenTransfers??[]).find(C=>r(C)&&Me(C.to).toLowerCase()===t.toLowerCase()&&!Ue(Me(C.token)));if(!h)return l;const m=Me(h.token);let y=!1;const x=(l.tokenTransfers??[]).map(C=>y||!r(C)||Me(C.to).toLowerCase()!==t.toLowerCase()||Me(C.token).toLowerCase()!==m.toLowerCase()?C:(y=!0,{...C,amount:o?.payoutAlreadyGross?BigInt(C.amount):BigInt(C.amount)+f}));if(!y)return l;const k=[];u.spicenetFee>0n&&k.push({to:m,value:0n,data:gt({abi:Ke,functionName:"transfer",args:[xo,u.spicenetFee]})});const w=u.gasFee+u.bridgeFee;return w>0n&&k.push({to:m,value:0n,data:gt({abi:Ke,functionName:"transfer",args:[Dn,w]})}),{...l,tokenTransfers:x,calls:[...k,...l.calls]}}),c=i.flatMap(l=>(l.tokenTransfers??[]).filter(r).map(p=>{const u=Me(p.token),f=Me(p.to),h=[{token:u,to:f,amount:BigInt(p.amount)}];return{chainId:l.chainId,transfers:gc(h)}}));if(c.length===0)return e;const d=BigInt(Math.floor(Date.now()/1e3))+3600n;return[{chainId:si,domain:"spicenet",tokenTransfers:[],calls:c.map((l,p)=>{const u=bo(wo([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,l.transfers[0].token,l.transfers.reduce((h,m)=>h+m.amount,0n),BigInt(l.chainId),BigInt(Date.now()+p)])),f=yc(u,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:gt({abi:cs,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${l.chainId}`,idempotenceKey:f,nbf:0n,exp:d,metadata:"{}",transfers:l.transfers.map(h=>({token:h.token.toLowerCase(),to:h.to,amount:h.amount}))}]})}})},...i]}function Qs(e,t){return t?e.some(n=>(n.tokenTransfers??[]).some(o=>o.from==="escrow"&&BigInt(o.amount)>=t.grossAmount)):!1}function Vs(e){const t=e.selectedAsset?.asset,n=e.selectedAsset?.amount;if(!(!t||!n))return Qe(n,t.decimals)}function Jn(e,t){const n=e.selectedAsset?.asset;if(!n||!e.selectedAsset?.amount)throw new Error("Select an asset and enter an amount");const o=Qe(e.selectedAsset.amount,n.decimals),s=t?.grossAmount??o;return e.resolveLockBatches({amount:e.selectedAsset.amount,amountWei:o,grossAmount:ct(s,n.decimals),grossAmountWei:s})}async function qs(e,t,n){const o=[...new Set(n.filter(r=>r.domain!=="spicenet").map(r=>r.chainId))],s=[];for(const r of o){const i=dt(r),c=mo(r),d=await ls(t,i),l=await e.actions.signAuthorization({contractAddress:c,chainId:r,nonce:Number(d)});s.push(l)}return s}async function ca(e,t,n){const o=e.isSemi7702&&e.providerEmbeddedAddress||e.address;if(!e.isConnected||!o)throw new Error("Please connect your wallet to continue");if(t.length===0)throw new Error("No lock batches configured");if(!e.ready||!e.authenticated)throw new Error(`Please authenticate with ${e.provider||"wallet provider"} to continue`);const s=n??await qs(e,o,t),r=Un(t),i=Math.floor(Date.now()/1e3)+60*10,c=r.map(h=>h.hash),d=bo(wo([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,BigInt(i),c])),l=await e.actions.signMessage({raw:d}),p=typeof l=="string"?l:l.signature;if(!p)throw new Error("Failed to sign intent authorization");const u={mode:"7702",signatureType:"ecdsa",signature:p,nbf:0,exp:i,chainBatches:r.map((h,m)=>{const y=t[m],x=y.domain==="spicenet";return{hash:h.hash,chainId:h.chainId,tokenTransfers:x?[]:y.tokenTransfers??[],calls:h.calls}})},f=await ot.createAction({user:o,chainAuthorizations:s.map(h=>({r:h.r,s:h.s,yParity:h.yParity,address:h.address,chainId:Number(h.chainId),nonce:Number(h.nonce)})),intents:[u]});if(f){const h=ss(t,ln),[m,y]=f.intentIds[0].split("/"),x=parseInt(y||"0",10),k=f.intentIds[0];e.startStatusPolling(f.intentIds[0],h),await Qr({actionId:m,intentIndex:x,intentId:k,totalSteps:t.length,isSpicenetStep:w=>t[w]?.domain==="spicenet",maxExecuteAttemptsForStep:w=>t[w]?.domain==="spicenet"?6:3,maxPolls:180})}}async function da(e){let t=Jn(e);if(t.length===0)throw new Error("No lock batches configured");const n=e.isSemi7702&&e.providerEmbeddedAddress||e.address;if(!e.isConnected||!n)throw new Error("Please connect your wallet to continue");const o=await qs(e,n,t);let s=dn([...t],n),r;for(let i=0;i<4;i+=1){const c=await ot.estimateActionFees(js(n,s,o.map(u=>({r:u.r,s:u.s,yParity:u.yParity,address:u.address,chainId:Number(u.chainId),nonce:Number(u.nonce)})))),d=Fo(c,{symbol:e.selectedAsset?.asset.symbol??"",decimals:e.selectedAsset?.asset.decimals??18,actionAmount:Vs(e)});if(!d)break;const l={grossAmount:d.grossAmount,netAmount:d.netAmount,feeAmount:d.totalFee??0n},p=r?.grossAmount===l.grossAmount&&r?.netAmount===l.netAmount&&r?.feeAmount===l.feeAmount;if(r=l,t=Jn(e,r),s=dn([...t],n,c,{payoutAlreadyGross:Qs(t,r)}),p)break}await ca(e,s,o)}async function Cc(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");if(!e.address||!e.embeddedWalletAddress)throw new Error("Embedded wallet not connected");const t=e.selectedAsset.asset,n=Qe(e.selectedAsset.amount,t.decimals),o=e.escrowAddress||mo(e.lockChainId),s=ot.getBaseUrl(),r=Tt(t.address);let i=0n;try{i=await la(s,e.embeddedWalletAddress,e.lockChainId,r)}catch(u){console.warn("[SpiceLockModal] could not snapshot spice balance pre-deposit:",u?.message)}const c=await e.actions.getEthereumProvider();await Yn(c,e.lockChainId);const d=Be(e.lockChainId),l=Ln({account:e.embeddedWalletAddress,transport:zn(c),chain:d?.viemChain});let p;if(t.isNative||Ue(t.address))p=await l.sendTransaction({to:o,value:n,chain:d?.viemChain});else{const u=gt({abi:Ke,functionName:"transfer",args:[o,n]});p=await l.sendTransaction({to:t.address,data:u,chain:d?.viemChain})}if((await dt(e.lockChainId).waitForTransactionReceipt({hash:p,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to escrow failed");await bc({apiBaseUrl:s,user:e.embeddedWalletAddress,chainId:e.lockChainId,tokenAddress:r,prevBalance:i}),await e.refreshSpiceAssets(),e.refreshWalletAssets(),await da(e)}async function kc(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");if(e.onLockExecute){const S=e.resolveLockBatches();if(S.length===0)throw new Error("No lock batches configured");const E=e.selectedAsset.asset,F=Qe(e.selectedAsset.amount,E.decimals),T=await e.onLockExecute({asset:E,amount:e.selectedAsset.amount,amountWei:F,lockDurationMonths:e.selectedDuration?.months??0,chainBatches:S});T&&e.onLockSuccess?.(T);return}const n=e.resolveLockBatches();if(n.length===0)throw new Error("No lock batches configured");const o=e.selectedAsset.asset,s=Qe(e.selectedAsset.amount,o.decimals),r=o.chainId,i=e.escrowAddress||An(r),c=Tt(o.address),d=o.isNative||Ue(c),l=n.some(S=>S.tokenTransfers?.some(E=>E.from==="escrow")),p=S=>({chainId:r,calls:d?[{to:i,value:S,data:"0x"}]:[{to:c,value:0n,data:gt({abi:Ke,functionName:"transfer",args:[i,S]})}]}),u=(S,E,F)=>{const T=p(S);if(!l)return[T,...E];const I=dn([...E],t,F,{payoutAlreadyGross:Qs(E,y)});return[T,...I]};let f=Jn(e),h=u(s,f);const m=await qs(e,t,h);let y;if(l)for(let S=0;S<4;S+=1){const E=await ot.estimateActionFees(js(t,h,m.map(A=>({r:A.r,s:A.s,yParity:A.yParity,address:A.address,chainId:Number(A.chainId),nonce:Number(A.nonce)})))),F=Fo(E,{symbol:o.symbol,decimals:o.decimals,actionAmount:s});if(!F)break;const T={grossAmount:F.grossAmount,netAmount:F.netAmount,feeAmount:F.totalFee??0n},I=y?.grossAmount===T.grossAmount&&y?.netAmount===T.netAmount&&y?.feeAmount===T.feeAmount;if(y=T,f=Jn(e,y),h=u(T.grossAmount,f,E),I)break}const x=y?.grossAmount??s,k=await e.externalWallet.getEthereumProvider();let w=null;try{const S=await k.request({method:"eth_chainId"});w=parseInt(S,16)}catch{w=null}w!==r&&await Yn(k,r);const C=Be(r),v=Ln({account:e.externalWalletAddress,chain:C?.viemChain,transport:zn(k)}),b=d?await v.sendTransaction({to:t,value:x,chain:C?.viemChain}):await v.sendTransaction({to:c,data:gt({abi:Ke,functionName:"transfer",args:[t,x]}),chain:C?.viemChain});if((await dt(r).waitForTransactionReceipt({hash:b,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to embedded wallet failed");await ca(e,h,m)}async function vc(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount||!e.requiresRelayerFeeEstimate)return null;if(e.isSemi7702){const i=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!i)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");let c=Jn(e);if(c.length===0)throw new Error("No lock batches configured");const d=e.selectedAsset.asset,l=Qe(e.selectedAsset.amount,d.decimals),p=d.chainId,u=e.escrowAddress||An(p),f=Tt(d.address),h=d.isNative||Ue(f),m=c.some(v=>v.tokenTransfers?.some(b=>b.from==="escrow")),y=v=>({chainId:p,calls:h?[{to:u,value:v,data:"0x"}]:[{to:f,value:0n,data:gt({abi:Ke,functionName:"transfer",args:[u,v]})}]}),x=(v,b,S)=>{const E=y(v);if(!m)return[E,...b];const F=dn([...b],i,S,{payoutAlreadyGross:b.some(T=>(T.tokenTransfers??[]).some(I=>I.from==="escrow"&&BigInt(I.amount)>=v))});return[E,...F]};let k=x(l,c),w=null,C;for(let v=0;v<4;v+=1){const b=await ot.estimateActionFees(Hs(i,k)),S=Fo(b,{symbol:d.symbol,decimals:d.decimals,actionAmount:l});if(!S)return w;const E={grossAmount:S.grossAmount,netAmount:S.netAmount,feeAmount:S.totalFee??0n},F=C?.grossAmount===E.grossAmount&&C?.netAmount===E.netAmount&&C?.feeAmount===E.feeAmount;if(w=S,C=E,c=Jn(e,E),k=x(E.grossAmount,c,b),F)break}return w}const t=e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");let n=Jn(e);if(n.length===0)throw new Error("No lock batches configured");let o=dn([...n],t),s=null;for(let i=0;i<4;i+=1){const c=await ot.estimateActionFees(Hs(t,o)),d=Fo(c,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:Vs(e)});if(!d)return null;const l={grossAmount:d.grossAmount},p=s?.grossAmount===d.grossAmount&&s?.netAmount===d.netAmount&&s?.totalFee===d.totalFee;if(s=d,n=Jn(e,l),o=dn([...n],t,c,{payoutAlreadyGross:Qs(n,l)}),p)break}if(s)return s;const r=await ot.estimateActionFees(Hs(t,o));return Fo(r,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:Vs(e)})}async function Ic(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");const t=e.activeSignerWallet??e.externalWallet,n=e.activeSignerAddress??e.externalWalletAddress;if(!n||!t)throw new Error("Please connect your wallet to continue");const o=e.resolveLockBatches();if(o.length===0)throw new Error("No lock batches configured");const s=o.find(u=>u.chainId===e.lockChainId)||o[0];if(!s)throw new Error("No lock batch for lock chain");const r=await t.getEthereumProvider();let i=null;try{const u=await r.request({method:"eth_chainId"});i=parseInt(u,16)}catch{i=null}i!==e.lockChainId&&await Yn(r,e.lockChainId);const c=Be(e.lockChainId),d=Ln({account:n,chain:c?.viemChain,transport:zn(r)}),l=dt(e.lockChainId);let p;for(const u of s.calls){const f=await d.sendTransaction({to:u.to,data:u.data,value:u.value,chain:c?.viemChain});if((await l.waitForTransactionReceipt({hash:f,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Lock transaction failed");p=f}p&&e.onLockSuccess?.(p)}async function Ac(e){if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance. Add more assets.");return}e.ui.setIsExecuting(!0),e.ui.setError(null);const t=n=>{console.error("[SpiceLockModal] lock failed:",n);const o=In(n,""),s=typeof n?.shortMessage=="string"?n.shortMessage:typeof n?.message=="string"?n.message:"";e.ui.setError(o||s||"Transaction failed. Please try again.")};if(e.isSemi7702){if(e.isSourceDestToken){try{await Ic(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{await kc(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{e.isDirectDeposit&&!e.isSourceDestToken?await Cc(e):await da(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}}const ua=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,lockBatches:o,lockTokenSymbol:s,lockTokenLogoURI:r,destinationInputHook:i,sourceAssetInputHook:c,lockDurationHook:d,lockChainId:l,durationOptions:p,votingPowerEstimate:u,escrowAddress:f,includeWalletAssets:h=!1,destinationTokenAddress:m,onLockSuccess:y,onLockExecute:x,sourceToDestinationConversionRate:k,estimatedOutputAmount:w,onAddFunds:C,buildSpicenetBatch:v,styles:b,dark:S=!1})=>{const{theme:E,dark:F,primaryColor:T,dk:I}=lt(b,S),A=E.typography.fontFamily,B=Zt(Ht),M=B?.mode||"7702",U=!!B?.isWhitelistGateActive,W=M!=="7702",L=re(()=>B?.supportedChainIds??[],[B?.supportedChainIds]),q=re(()=>{if(U)return[];const K=B?.allowedTokens;if(!K||K.length===0)return[];const Ie=new Set(K.map(_e=>_e.toLowerCase())),mt=[],At=new Set;for(const _e of L){const tn=Be(_e);for(const Y of tn?.supportedTokens??[]){if(!Ie.has(Y.symbol.toLowerCase()))continue;const $=`${_e}:${Y.address.toLowerCase()}`;At.has($)||(At.add($),mt.push(Me(Y.address)))}}return mt},[B?.allowedTokens,L,U]),D=F?I.cardBg:b?.assetSelector?.backgroundColor||b?.secondaryBackground||"#e9e9e9",P=F?`1px solid ${I.cardBorder}`:"0.5px solid #A8A8A7",O=F?"12px":"6px",j=F?I.textPrimary:"#111827",z=F?I.textSecondary:"#6b7280",J=re(()=>({...b,assetSelector:{...b?.assetSelector,backgroundColor:F?I.cardBg:b?.assetSelector?.backgroundColor,borderRadius:F?"12px":b?.assetSelector?.borderRadius},secondaryBackground:F?I.cardBg:b?.secondaryBackground}),[b,F]),pe=re(()=>F?{...E,colors:{...E.colors,secondary:I.cardBg,surfaceHover:I.hoverBg,border:I.cardBorder,borderHover:I.inputBorder}}:E,[F,E]),[N,ae]=R(null),[le,ge]=R(0),Re=d?.selectedDurationIdx??le,de=d?.setSelectedDurationIdx??ge,[ke,H]=R(!1),[oe,X]=R(null),[se,fe]=R(null),[Ee,be]=R(!1),[V,Q]=R(!1),[he,Le]=R(null),[kt,zt]=R(!1),Ot=ie(0),[st,rt]=R(!1),[G,We]=R(null);sr(),rs();const{chain:we,address:_}=go();_a();const Ze=ie(we);Z(()=>{Ze.current=we},[we]);const Rt=Mn(),{isReady:un,isAuthenticated:ut,isConnected:on,address:Nt,provider:Xt,actions:De}=Rt,{externalWallet:pn,embeddedAddress:sn,externalAddress:xn,activeWallet:Vt,activeAddress:rn}=_n(),{intentStatus:yt,startStatusPolling:pt,clearStatus:Ye}=Cr({checkStepStatus:(K,Ie)=>ot.checkStepStatus(K,Ie),retryStep:async(K,Ie)=>{const[mt,At]=K.split("/"),_e=parseInt(At||"0",10);await ot.executeStep(mt,_e,Ie,{action:"execute"})},maxRetries:3}),{assets:Jt,refetch:xt}=Eo({address:Nt,supportedChains:L,enabled:e&&on&&!W&&!U,refetchInterval:3e4}),me=re(()=>{if(U)return[];if(q.length===0)return Jt;const K=new Set(q.map(Ie=>Ie.toLowerCase()));return Jt.filter(Ie=>K.has(Ie.address.toLowerCase()))},[Jt,q,U]),bt=Rn(),tt=xn||_,fn=W?rn??tt:bt,ye=re(()=>{if(!h)return[];if(U)return m?[Me(m)]:[];const K=new Set,Ie=[],mt=At=>{if(!At)return;const _e=At.toLowerCase();K.has(_e)||(K.add(_e),Ie.push(Me(At)))};if(m&&mt(m),W)for(const At of q)mt(At);return Ie},[h,W,m,q,U]),qt=re(()=>ye.map(K=>K.toLowerCase()).sort().join(","),[ye]),ft=re(()=>JSON.stringify([...L||[]].sort()),[L]),[Dt,Mt]=R([]),hn=ie(0),Yt=ie(async()=>{}),bn=ce(async()=>{if(!h||!fn||ye.length===0){hn.current++,Mt([]);return}const K=++hn.current,Ie=Me(fn),mt=L&&L.length>0?L:[l],At=ye.map(ue=>{const ne=ue.toLowerCase();if(m&&Ae(ue,m)){const Fe=Be(l)?.supportedTokens?.find(Se=>Ae(Se.address,ne));return{address:ue,chainId:l,configToken:Fe?{decimals:Fe.decimals,symbol:Fe.symbol,name:Fe.name,logo:Fe.logo}:void 0}}for(const Fe of mt){const Se=Be(Fe)?.supportedTokens?.find(Ft=>Ae(Ft.address,ne));if(Se)return{address:ue,chainId:Fe,configToken:{decimals:Se.decimals,symbol:Se.symbol,name:Se.name,logo:Se.logo}}}return{address:ue,chainId:l}}),_e=new Map;for(const ue of At){const ne=_e.get(ue.chainId)||[];ne.push(ue),_e.set(ue.chainId,ne)}const tn=async(ue,ne)=>{try{const Fe=await En(ue,{address:ne.address,abi:Ke,functionName:"balanceOf",args:[Ie]});let Se,Ft,it,je;if(ne.configToken)Se=ne.configToken.decimals,Ft=ne.configToken.symbol,it=ne.configToken.name,je=ne.configToken.logo;else{const[Bn,Tn,mn]=await Promise.all([En(ue,{address:ne.address,abi:Ke,functionName:"decimals",args:[]}).catch(()=>18),En(ue,{address:ne.address,abi:Ke,functionName:"symbol",args:[]}).catch(()=>"TOKEN"),En(ue,{address:ne.address,abi:Ke,functionName:"name",args:[]}).catch(()=>"TOKEN")]);Se=Number(Bn),Ft=Tn,it=mn}const Ct=!!m&&Ae(ne.address,m)&&ne.chainId===l;Ct&&r&&(je=r),Ct&&s&&!ne.configToken&&(Ft==="TOKEN"&&(Ft=s),it==="TOKEN"&&(it=s));const Cn=parseFloat((Number(Fe)/Math.pow(10,Se)).toFixed(6));return{address:ne.address,name:it,symbol:Ft,decimals:Se,balance:Fe,balanceFormatted:Cn,balanceUsd:0,logoURI:je,isNative:!1,chainId:ne.chainId}}catch{return null}},Y=await Promise.all(Array.from(_e.entries()).map(async([ue,ne])=>{let Fe;try{Fe=dt(ue)}catch{return[]}const Se=[],Ft=[];for(const je of ne){const Ct=Se.length;Se.push({address:je.address,abi:Ke,functionName:"balanceOf",args:[Ie]}),je.configToken||Se.push({address:je.address,abi:Ke,functionName:"decimals",args:[]},{address:je.address,abi:Ke,functionName:"symbol",args:[]},{address:je.address,abi:Ke,functionName:"name",args:[]}),Ft.push({start:Ct,item:je})}let it=null;try{it=await Fe.multicall({contracts:Se})}catch{it=null}return it?Ft.map(({start:je,item:Ct})=>{const Cn=it[je],Bn=Cn?.status==="success"?Cn.result:0n;let Tn,mn,xe,St;if(Ct.configToken)Tn=Ct.configToken.decimals,mn=Ct.configToken.symbol,xe=Ct.configToken.name,St=Ct.configToken.logo;else{const Ce=it[je+1],et=it[je+2],kn=it[je+3];Tn=Ce?.status==="success"?Number(Ce.result):18,mn=et?.status==="success"?et.result:"TOKEN",xe=kn?.status==="success"?kn.result:mn}const Kt=!!m&&Ae(Ct.address,m)&&Ct.chainId===l;Kt&&r&&(St=r),Kt&&s&&!Ct.configToken&&(mn==="TOKEN"&&(mn=s),xe==="TOKEN"&&(xe=s));const gn=parseFloat((Number(Bn)/Math.pow(10,Tn)).toFixed(6));return{address:Ct.address,name:xe,symbol:mn,decimals:Tn,balance:Bn,balanceFormatted:gn,balanceUsd:0,logoURI:St,isNative:!1,chainId:Ct.chainId}}):(await Promise.all(ne.map(je=>tn(Fe,je)))).filter(je=>je!==null)}));if(K!==hn.current)return;const $=Y.flat();Mt($)},[h,fn,qt,ft,l,m,r,s]);Z(()=>{Yt.current=bn},[bn]),Z(()=>{if(!e||!h){Mt([]);return}Yt.current();const K=setInterval(()=>{Yt.current()},15e3);return()=>clearInterval(K)},[h,e,fn,qt,ft,l,m]);const wn=ce(()=>{bn()},[bn]),Ne=re(()=>Dt.filter(K=>K.balance>0n),[Dt]),Pt=re(()=>{if(W)return Ne.map(Ie=>({...Ie,_source:"wallet"}));if(!h)return me;const K=[];for(const Ie of Ne)K.push({...Ie,_source:"wallet"});for(const Ie of me)K.push({...Ie,_source:"spice"});return K},[W,h,Ne,me]),Je=re(()=>U?m?Pt.filter(K=>Ae(K.address,m)&&K.chainId===l):[]:Pt,[Pt,U,m,l]),$t=ie(null),Nn=ie(null);Z(()=>{Nn.current=N},[N]),Z(()=>{!U||!N?.asset||m&&Ae(N.asset.address,m)&&N.asset.chainId===l||ae(null)},[U,N?.asset,m,l]),Z(()=>{e||(ae(null),X(null),fe(null),be(!1),Q(!1),Le(null),H(!1),rt(!1),We(null),zt(!1),Ye())},[e,Ye]),Z(()=>{i&&i.assetAmount!==(N?.amount||"")&&ae(K=>K&&{...K,amount:i.assetAmount})},[i?.assetAmount]),Z(()=>{c&&c.assetAmount!==(N?.amount||"")&&ae(K=>K&&{...K,amount:c.assetAmount})},[c?.assetAmount]),Z(()=>{if(!W&&yt?.overallStatus==="success"&&yt.intentId&&$t.current!==yt.intentId&&Nt&&yt.steps.find(K=>K.transactionHash)?.transactionHash){$t.current=yt.intentId;const K=Nn.current;if(!K?.asset||!K.amount||K.asset._source==="wallet"||Qe(K.amount,K.asset.decimals)===0n)return;xt()}},[yt,Nt,l,xt,W]);const Ge=parseFloat(N?.amount||"")||0,$e=re(()=>N?.asset?N.asset._source==="wallet"?N.asset.balanceFormatted??0:me.find(K=>Ae(K.address,N.asset.address)&&K.chainId===N.asset.chainId)?.balanceFormatted??0:0,[N?.asset,me]),Wt=Ge>0&&(he?parseFloat(ct(he.grossAmount,he.decimals))>$e:Ge>$e),vt=d?.selectedDuration??p[Re]??p[0],ze=re(()=>!N?.asset||!m?!1:Ae(N.asset.address,m)&&N.asset.chainId===l,[N?.asset,m,l]),Xe=re(()=>Ge<=0?0:ze?Ge:!k||k<=0?0:Ge/k,[Ge,k,ze]),_t=re(()=>Xe<=0?null:Xe.toLocaleString(void 0,{maximumFractionDigits:2}),[Xe]),Et=u&&Xe>0&&vt?u(Xe,vt.months):void 0,en=re(()=>Ge<=0?"$0.00":ze&&k?(Ge*k).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!k||k<=0?"$0.00":Ge.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[Ge,k,ze]),Oe=re(()=>{if(!_t)return null;const K=parseFloat(_t.replace(/,/g,""));return ze&&k?(K*k).toLocaleString(void 0,{maximumFractionDigits:2}):k?(K*k).toLocaleString(void 0,{maximumFractionDigits:2}):null},[_t,k,ze]),Pn=ce(K=>{ae(Ie=>({asset:K,amount:Ie?.asset?.address===K.address&&Ie?.asset?.chainId===K.chainId&&Ie.amount||""})),X(null),fe(null),Q(!1),Le(null),c?.setSelectedAsset&&c.setSelectedAsset({symbol:K.symbol,address:K.address,decimals:K.decimals,chainId:K.chainId})},[c?.setSelectedAsset]),ee=ce(K=>{ae(Ie=>Ie&&{...Ie,amount:K}),X(null),fe(null),Q(!1),Le(null),i&&i.setAssetAmount(K),c&&c.setAssetAmount(K)},[i,c]),te=ce(K=>{if(typeof o=="function"){if(!N?.asset||!N.amount)throw new Error("Select an asset and enter an amount");return o({asset:N.asset,amount:K?.amount??N.amount,amountWei:K?.amountWei??Qe(N.amount,N.asset.decimals),grossAmount:K?.grossAmount,grossAmountWei:K?.grossAmountWei,feeAdjusted:!!K})}return o},[o,N]),ve=ie(null),Ve=re(()=>!N?.asset||Ge<=0?!1:W?!ze&&!x:!0,[N,Ge,W,ze,x]),It=ce(()=>vc(ve.current),[]),wt=re(()=>!N?.asset||Ge<=0?null:`${N.asset.address.toLowerCase()}:${N.asset.chainId}:${N.amount??""}`,[N?.asset?.address,N?.asset?.chainId,N?.amount,Ge]);Z(()=>{if(!e||ke)return;if(!N?.asset||Ge<=0){fe(null),be(!1),Q(!1),Le(null);return}if(!Ve){fe(null),be(!1),Q(!0),Le(null);return}let K=!1;const Ie=async _e=>{const tn=++Ot.current;_e||(fe(null),Q(!1),be(!0));try{const Y=await It();if(K||Ot.current!==tn)return;fe(null),Q(!0),Le(Y)}catch(Y){if(K||Ot.current!==tn)return;_e||(fe(In(Y,"Unable to calculate fees for this lock.")),Q(!1))}finally{!K&&Ot.current===tn&&!_e&&be(!1)}},mt=window.setTimeout(()=>{Ie(!1)},250),At=window.setInterval(()=>{Ie(!0)},3e4);return()=>{K=!0,clearTimeout(mt),window.clearInterval(At)}},[e,ke,wt,Ve,It]),Z(()=>{if(yt?.overallStatus==="success"){const K=yt.steps.find(Ie=>Ie.transactionHash);y?.(K?.transactionHash)}},[yt?.overallStatus,y]);const ht=h&&N?.asset?._source==="wallet"&&N?.asset?.chainId===l,at=ce(()=>Ac(ve.current),[]),He=!!N?.asset&&Ge>0&&!Wt&&!ke&&(!Ve||V&&!Ee&&!se),nt=oe||se,Pe=g("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[a(As,{color:z}),g("p",{style:{fontSize:"13px",color:z,margin:0,lineHeight:"1.5"},children:["Add ",s," by converting assets from your account"]})]});if(ve.current={selectedAsset:N,parsedAmount:Ge,selectedDuration:vt,isInsufficientBalance:Wt,isSemi7702:W,isSourceDestToken:ze,isDirectDeposit:ht,requiresRelayerFeeEstimate:Ve,address:Nt,embeddedWalletAddress:bt,providerEmbeddedAddress:sn,externalWallet:pn,externalWalletAddress:tt,activeSignerWallet:Vt,activeSignerAddress:rn,isConnected:on,ready:un,authenticated:ut,provider:Xt,actions:De,lockChainId:l,escrowAddress:f,onLockExecute:x,onLockSuccess:y,buildSpicenetBatch:v,resolveLockBatches:te,startStatusPolling:pt,refreshSpiceAssets:xt,refreshWalletAssets:wn,ui:{setError:X,setIsExecuting:H,setShowStatusPanel:zt}},!e)return null;const qe={backgroundColor:D,border:P,borderRadius:O,padding:"16px",marginBottom:"16px"};return a(Hn,{isOpen:e,onClose:t,title:`Add ${s} to your account`,subtitle:Pe,styles:b,dark:F,footerLinkText:"Spicenet accounts \u2192",overlayContent:st?a("div",{}):void 0,closeOnBackdropClick:n,children:g("div",{style:{padding:"0 24px 8px 24px",position:"relative"},children:[g("div",{style:{marginBottom:"12px"},children:[C&&a("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:a(Ss,{onClick:C,color:T,fontFamily:A})}),a("div",{style:{marginTop:"10px",fontSize:"13px",color:z,fontFamily:A},children:a(Ao,{assets:Je,selectedAsset:N??void 0,onAssetSelect:Pn,onAmountChange:ee,label:"Amount",showBalance:!0,showMaxButton:!0,theme:pe,styles:J})}),a("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:z,fontFamily:A},children:en})]}),g("div",{style:qe,children:[g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:F?`1px solid ${I.cardBorder}`:"1px solid #e5e7eb"},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[r?a("img",{src:r,alt:s,style:{width:"32px",height:"32px",borderRadius:"50%",objectFit:"cover"}}):a("div",{style:{width:"32px",height:"32px",borderRadius:"50%",backgroundColor:F?I.inputBg:"#d1d5db",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:700,color:j},children:s.slice(0,2)}),a("span",{style:{fontSize:"16px",fontWeight:600,color:j,fontFamily:A},children:s})]}),g("div",{style:{textAlign:"right"},children:[a("div",{style:{fontSize:"22px",fontWeight:700,color:j,fontFamily:A,lineHeight:1.1},children:_t??"0.00"}),g("div",{style:{fontSize:"12px",color:z,fontFamily:A,marginTop:"2px"},children:["~$",Oe??"0.00"]})]})]}),g("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:F?`1px solid ${I.cardBorder}`:"1px solid #e5e7eb"},children:[g("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[a("span",{style:{fontSize:"15px",fontWeight:500,color:z,fontFamily:A},children:"Lock Duration"}),a(jn,{color:z})]}),a(dc,{options:p,selectedIndex:Re,onSelect:de,primaryColor:T,dark:F,textPrimary:j,textSecondary:z})]}),g("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[a(pc,{durationMonths:vt?.months,fontFamily:A,dark:F,textPrimary:j,textSecondary:z}),u&&a(fc,{votes:Et,fontFamily:A,dark:F,textPrimary:j,textSecondary:z})]})]}),Ve&&a(Lo,{fontFamily:A,textPrimary:j,textSecondary:z,cardBg:D,cardBorder:P,resolvedDark:F,darkCardBorder:I.cardBorder,primaryColor:T,feePreview:he,isLoading:Ee,errorText:se}),nt&&a(co,{variant:"error",palette:I,fontFamily:A,style:{marginBottom:"12px"},children:nt}),a(Bt,{variant:"outline",fullWidth:!0,onClick:at,disabled:!He,loading:ke,dark:F,styles:{...b,button:{...b?.button,backgroundColor:T}},children:ke?ht&&!ze?"DEPOSITING...":ze?"LOCKING...":"CONVERTING...":Ee&&Ve?"CALCULATING FEES...":ht&&!ze?`DEPOSIT ${s}`:ze?`LOCK ${s}`:`CONVERT TO ${s}`}),a(hc,{isOpen:st,data:G,isLocking:ke,lockError:nt,onContinue:at,onClose:()=>rt(!1),primaryColor:T,fontFamily:A,dark:F}),yt&&kt&&a("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:F?"rgba(0, 0, 0, 0.45)":"rgba(255, 255, 255, 0.55)",backdropFilter:"blur(2px)",WebkitBackdropFilter:"blur(2px)",borderRadius:O},children:a(Ms,{type:"deposit",showStepBreakdown:!1,isOpen:!!yt&&yt.overallStatus!=="processing",isProcessing:ke||yt?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{Ye(),zt(!1),at()},onNewTx:()=>{Ye(),zt(!1),ae(null),$t.current=null,xt(),wn()},onClose:()=>{Ye(),zt(!1)},onComplete:()=>{Ye(),zt(!1),ae(null),$t.current=null,xt(),wn()},results:yt?.overallStatus==="success"||yt?.overallStatus==="failed"?yt.steps.map(K=>({asset:{symbol:N?.asset?.symbol||s,address:N?.asset?.address||""},txHash:K.transactionHash||"",success:K.status==="success",amount:N?.amount})):void 0,chainName:ln(l),explorerUrl:ro(l,"").replace(/\/tx\/.*$/,"")||void 0,theme:E,styles:b,dark:F})})]})})},Sc="0xa9059cbb";function Ec(e,t,n){return Ue(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:gt({abi:Qt,functionName:"transfer",args:[n,t]})}}function Ys(e,t,n,o){return t!=="user-transfer"||!n||e.length===0||e[0]?.to.toLowerCase()!==o.toLowerCase()||!e[0]?.data.startsWith(Sc)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function Xo(e,t,n){if(!t)return[e];const o=await t(n);return o?[o,e]:[e]}function oo(e){return e.filter(t=>t.domain!=="spicenet")}function Jo(e){const t=(e.tokenTransfers??[]).filter(n=>n.from==="escrow").map(n=>({token:Tt(n.token),recipient:n.to,amount:BigInt(n.amount)})).filter(n=>n.amount>0n);return t.length>0?t:void 0}function fo(e,t,n){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const o=10n**BigInt(t-n);return(e+o-1n)/o}async function Fc(e,t){const{currentPaymentAmount:n,destinationToken:o,embeddedWalletAddress:s,providerEmbeddedAddress:r,address:i,isNon7702:c,isPayMode:d,resolvedChainId:l,buildActionCalls:p,feeExecutionMode:u,buildSpicenetBatch:f,selectedAsset:h,needsSwap:m,exactOutputSwap:y,resolvedTokenIn:x}=e,k=Qe(n,o.decimals),w=t?.actionAmountOverride??k,C=s||r||(c?void 0:i);if(!C)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const v={userAddress:C,chainId:l,destinationToken:o.address,grossAmount:t?.fundingAmountOverride??k,netAmount:w,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:u,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},b=p(w,v),S={chainId:l,calls:b},E=(!d&&!c?!0:h?.asset?._source==="spice")||c,F=(T,I)=>({token:T,from:c?"solver":"escrow",to:C,amount:I});if(k===0n)return[S];if(m&&y){const T=x??Wn(h.asset,l)??h.asset.address,I=t?.fundingAmountOverride??y.amountInMax,A=E?[F(T,I)]:[],B={to:T,value:0n,data:gt({abi:Qt,functionName:"approve",args:[y.calls[0]?.to,y.amountInMax]})},M={chainId:l,calls:[B,...y.calls,...b],tokenTransfers:[...A,...S.tokenTransfers??[]]};return E?Xo(M,f,{userAddress:C,destinationChainId:l,deliveryToken:T,deliveryAmount:I,deliveryRecipient:C,deliveryTransfers:Jo(M),sourceAsset:h.asset}):[M]}if(E){const T=x??Wn(h.asset,l)??o.address,I=t?.fundingAmountOverride??k,A={...S,tokenTransfers:[F(T,I),...S.tokenTransfers??[]]};return Xo(A,f,{userAddress:C,destinationChainId:l,deliveryToken:T,deliveryAmount:I,deliveryRecipient:C,deliveryTransfers:Jo(A),sourceAsset:h.asset})}return[S]}async function Bc(e,t){const{selectedAsset:n,embeddedWalletAddress:o,externalWalletAddress:s,resolvedChainId:r,destinationToken:i,buildActionCalls:c,feeExecutionMode:d,buildSpicenetBatch:l,isPayMode:p,isNon7702:u,needsSwap:f,resolvedSwap:h,quoteAmountOut:m,resolvedTokenIn:y}=e,x=h?.amountOutMinimum??m;if(!n?.asset||!o)return[];const k=u?s:o;if(!k)return[];const w=t?.fundingAmountOverride??t?.actionAmountOverride??Qe(n.amount,n.asset.decimals),C=t?.fundingAmountOverride??w,v=t?.sourceFundingAmountOverride??w,b=t?.deliveryAmountOverride??C,S=t?.withdrawalAmountOverride??b,E=t?.actionAmountOverride??w,F={userAddress:k,chainId:r,destinationToken:i.address,feeToken:d==="user-transfer"&&f&&y?y:i.address,grossAmount:C,netAmount:E,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:d,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},T=c(E,F),I=n.asset?._source==="wallet";if(!p&&u&&I&&n.asset.chainId===r){if(f){if(!y)throw new Error("Swap input token could not be resolved");if(!h||x===null)throw new Error("Swap quote not available yet")}if(f&&h&&x){const P=c(t?.actionAmountOverride??x,{...F,netAmount:t?.actionAmountOverride??x}),{feeCall:O,remainingCalls:j}=Ys(P,d,f,F.feeToken);return[{chainId:r,calls:[...O?[O]:[],...h.calls,...j]}]}return[{chainId:r,calls:T}]}if(!p&&!u&&I){if(n.asset.chainId===r){if(f){if(!y)throw new Error("Swap input token could not be resolved");if(!h||x===null)throw new Error("Swap quote not available yet")}if(f&&h&&x){const P=c(t?.actionAmountOverride??x,{...F,netAmount:t?.actionAmountOverride??x}),{feeCall:O,remainingCalls:j}=Ys(P,d,f,F.feeToken);return[{chainId:r,calls:[...O?[O]:[],...h.calls,...j]}]}return[{chainId:r,calls:T}]}throw new Error("Cross-chain wallet supplies require external wallet mode")}const A=!p&&!u?n.asset?._source!=="wallet":n.asset?._source==="spice",B=u&&I;if(!(A||B))return[{chainId:r,calls:T}];const M=B&&n.asset.chainId!==r?{chainId:n.asset.chainId,calls:[Ec(Tt(n.asset.address),v,An(n.asset.chainId))]}:null,U=(P,O)=>({token:P,from:B?"solver":"escrow",to:o,amount:O}),W=(P,O)=>B?[{token:P,from:"escrow",to:ri,amount:O}]:[];if(f){if(!y)throw new Error("Swap input token could not be resolved");if(!h||x===null)throw new Error("Swap quote not available yet")}if(f&&h&&x&&y){const P=c(t?.actionAmountOverride??x,{...F,netAmount:t?.actionAmountOverride??x}),{feeCall:O,remainingCalls:j}=Ys(P,d,f,F.feeToken),z={chainId:r,calls:[...O?[O]:[],...h.calls,...j],tokenTransfers:[...W(y,S),U(y,b)]},J=await Xo(z,l,{userAddress:o,destinationChainId:r,deliveryToken:y,deliveryAmount:b,withdrawalAmount:S,deliveryRecipient:o,deliveryTransfers:Jo(z),sourceAsset:n.asset});return M?[M,...J]:J}const L=y??Wn(n.asset,r)??i.address,q={chainId:r,calls:T,tokenTransfers:[...W(L,S),U(L,b)]},D=await Xo(q,l,{userAddress:o,destinationChainId:r,deliveryToken:L,deliveryAmount:b,withdrawalAmount:S,deliveryRecipient:o,deliveryTransfers:Jo(q),sourceAsset:n.asset});return M?[M,...D]:D}async function Tc(e,t,n,o,s){let r=e;for(let i=0;i<4;i++){const c=await t(r),d=await o(c,n,r,s),l=Ll(d);if(l===null||l>=e)return r;const p=r-l,u=e+p;if(u<=r)return r;r=u}return r}function Mc(e,t,n,o){if(e<=0n)return 0n;const s=e-t;if(s<=0n)return 0n;const r=o+n;return r<=0n?s:s*o/r}function Rc(e,t){const n=ct(e,t);return n.includes(".")?n.replace(/\.?0+$/,"")||"0":n}async function Dc(e){const{asset:t,isPayMode:n,isNon7702:o,needsSwap:s,isQuoting:r,embeddedWalletAddress:i,buildSupplyChainBatches:c,estimateGasless:d,executionTokenAddress:l,feeExecutionMode:p}=e;if(n||o||s||r||!i||t.balance<=0n)return null;const u=i,f=await c({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(f.length===0)return null;const h=f.some(C=>C.tokenTransfers?.length),m=await d(f,l,t.balance,h?{userOverride:u,useCustomTransfers:!0,feeExecutionMode:p}:p?{userOverride:u,feeExecutionMode:p}:{userOverride:u}),y=Gn(m,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),x=y?fo(y.gasFee,y.decimals,t.decimals):0n,k=y?fo(y.spicenetFee,y.decimals,t.decimals):0n,w=Mc(t.balance,x,k,t.balance);return w>0n?Rc(w,t.decimals):null}async function Wc(e){const{selectedAsset:t,isPayMode:n,parsedAmount:o,needsSwap:s,exactOutputSwap:r,isNon7702:i,isSourceDestToken:c,currentPaymentAmount:d,destinationToken:l,feeExecutionMode:p,resolvedTokenIn:u,embeddedWalletAddress:f,providerEmbeddedAddress:h,resolvedChainId:m,isConnected:y,address:x,ready:k,authenticated:w,isDirect:C,resolvedSwap:v,isQuoting:b,executionTokenAddress:S,buildPayChainBatches:E,buildSupplyChainBatches:F,estimateGasless:T,estimateRequiredGrossFunding:I}=e;if(!t?.asset)return null;if(n){if(o<=0||s&&!r||i&&c)return null;const D=Qe(d,l.decimals),P=u||Wn(t.asset,m)||t.asset.address||l.address,O={chainId:m,tokenAddress:P,symbol:Ut(P,m)?.symbol??t.asset.symbol,decimals:Ut(P,m)?.decimals??t.asset.decimals};if(i){const ae=f||h;if(!ae)return null;const le=ae,ge=s?r?.amountInMax??0n:D;if(ge===0n)return null;const Re=await I(ge,H=>E({fundingAmountOverride:H}).then(oe=>dn(oo(oe),le)),P,{userOverride:ae,useCustomTransfers:!0}),de=dn(oo(await E({fundingAmountOverride:Re})),le),ke=await T(de,P,Re,{userOverride:ae,useCustomTransfers:!0,feeExecutionMode:p});return Gn(ke,O)}if(!y||!x||!k||!w)return null;const j=f||h||x,z=s?r?.amountInMax??0n:D;if(z===0n)return null;const J=await I(z,ae=>E({fundingAmountOverride:ae}).then(le=>dn(oo(le),j)),P,{useCustomTransfers:!0});let pe=dn(oo(await E({fundingAmountOverride:J})),j);const N=await T(pe,P,J,{useCustomTransfers:!0,feeExecutionMode:p});return Gn(N,O)}if(o<=0||!f)return null;const A=f||h;if(!(!n&&!i&&t.asset?._source==="wallet"&&t.asset.chainId!==m)&&!C&&!v&&!b||b)return null;const B=Qe(t.amount,t.asset.decimals),M=await F();if(M.length===0)return null;const U=i&&t.asset?._source==="wallet"&&t.asset.chainId===m,W={chainId:m,tokenAddress:S,symbol:Ut(S,m)?.symbol??l.symbol,decimals:Ut(S,m)?.decimals??l.decimals};if(U){const D=await ot.estimateBatchGas({user:A,outputToken:S,stepIndex:0,chainBatches:M}),P=qo(B,10n),O=P+D.gasFee;return{...W,grossAmount:B+O,netAmount:B,totalFee:O,gasFee:D.gasFee,spicenetFee:P,bridgeFee:0n,gasQuoteSource:D.gasQuoteSource}}const L=M.some(D=>D.tokenTransfers?.length),q=await T(M,S,B,L?{userOverride:A,useCustomTransfers:!0,feeExecutionMode:p}:p?{userOverride:A,feeExecutionMode:p}:{userOverride:A});return Gn(q,W)}const Nc=10n;function pa(e,t){const n=e.selectedAsset?.asset;if(!n||n?._source!=="wallet")return;const o=Wn(n,e.resolvedChainId);if(!o||!Ae(o,e.executionTokenAddress))return;const s=Ut(e.executionTokenAddress,e.resolvedChainId),r=fo(t,s?.decimals??e.destinationToken.decimals,n.decimals);if(r<=n.balance)return;const i=ct(r,n.decimals),c=ct(n.balance,n.decimals);throw new Error(`Insufficient ${n.symbol} for amount plus fees. Required ${i} ${n.symbol}; available ${c} ${n.symbol}.`)}function fa(e){const t=Ut(e.executionTokenAddress,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:t?.symbol??e.destinationToken.symbol,decimals:t?.decimals??e.destinationToken.decimals}}function ha(e,t,n){const o=Gn(e,fa(t));if(!o)return;const s=qo(n,Nc),r=o.bridgeFee??0n,i=s+o.gasFee+r;return{grossAmount:n+i,netAmount:n,combinedFeeAmount:i,feeExecutionMode:"user-transfer",feeBreakdown:{spicenetFee:s,gasFee:o.gasFee,bridgeFee:r}}}function ho(e,t,n){if(e===t)return!0;const o=e>t?e:t;return o===0n?!1:(e>t?e-t:t-e)*10000n<=o*n}function ma(e,t,n){let o=0n,s=0n;const r=n.toLowerCase();for(const i of e)if(i.chainId===t){for(const c of i.calls??[])if(c.to.toLowerCase()===r)try{const d=Co({abi:Qt,data:c.data});if(d.functionName!=="transfer")continue;const l=d.args[0].toLowerCase(),p=d.args[1];l===xo.toLowerCase()?o+=p:l===Dn.toLowerCase()&&(s+=p)}catch{continue}}return{spicenetFee:o,gasFee:s}}function Pc(e,t,n){const o=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,s=ma(e,t.resolvedChainId,o);return s.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||s.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:ho(s.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&ho(s.gasFee,n.feeBreakdown.gasFee,100n)}function Uc(e,t){return e?ho(e.grossAmount,t.grossAmount,100n)&&ho(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&ho(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&ho(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}async function Lc(e){if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.isNon7702){const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setTxHash(null);try{if(e.isSourceDestToken){e.ui.setStep("executing"),e.ui.setStatusMsg("Submitting transaction...");const o=await ga(e);e.ui.setTxHash(o??null)}else{e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.refs.spiceDepositSubmittedRef.current=!1;const o=new AbortController;e.refs.abortControllerRef.current=o,await zc(e,o.signal)}e.ui.setStep("success"),e.ui.setStatusMsg(e.isSourceDestToken?"Transaction confirmed":"Deposit confirmed")}catch(o){const s=o instanceof Error?o:new Error(String(o));if(s.name==="AbortError"||e.refs.abortControllerRef.current?.signal.aborted){e.ui.setStep("idle");return}const r=s.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(r),e.ui.setError(r),e.onError?.(s)}finally{e.ui.setIsExecuting(!1)}return}if(!e.embeddedWalletAddress){e.ui.setError("Wallet not ready");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.ui.setTxHash(null),e.refs.spiceDepositSubmittedRef.current=!1;const t=new AbortController;e.refs.abortControllerRef.current=t;try{const n=Qe(e.selectedAsset.amount,e.selectedAsset.asset.decimals),o=n;let s=await e.gasless.buildSupplyChainBatches();const r=e.selectedAsset.asset?._source==="wallet",i=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!r&&!s.some(h=>Do(h.chainId)))throw new Error("Spice-funded supplies must include a Spicenet funding batch before the destination chain batch.");const c=s.some(h=>h.tokenTransfers?.length)?{userOverride:i,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}:e.feeExecutionMode?{userOverride:i,feeExecutionMode:e.feeExecutionMode}:{userOverride:i};let d=n;const l=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,p=e.feeExecutionMode==="user-transfer"&&!l?o:void 0;let u;for(let h=0;h<4;h+=1){const m=await e.gasless.estimateGasless(s,e.executionTokenAddress,d,c),y=Gn(m,fa(e));u=e.feeExecutionMode==="user-transfer"&&y?ha(m,e,o):void 0;const x=u?.grossAmount??y?.grossAmount??d;if(x===d){d=x;break}d=x,s=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:d,actionAmountOverride:p,actionContextOverride:u})}e.feeExecutionMode==="user-transfer"&&(pa(e,d),s=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:d,actionAmountOverride:p,actionContextOverride:u}));let f=u;await e.gasless.executeGasless(s,e.executionTokenAddress,d,e.gasless.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...c,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:h,chainBatches:m})=>{const y=ha(h,e,o);if(!y)return null;const x=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&e.resolvedTokenIn?e.resolvedTokenIn:e.executionTokenAddress;ma(m,e.resolvedChainId,x);const k=Uc(f,y),w=Pc(m,e,y);return k||w?null:(f=y,e.gasless.buildSupplyChainBatches({fundingAmountOverride:y.grossAmount,actionAmountOverride:p,actionContextOverride:y}))}}:c),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){const o=n instanceof Error?n:new Error(String(n));if(o.name==="AbortError"||t.signal.aborted){e.ui.setStep("idle");return}const s=o.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(s),e.ui.setError(s),e.onError?.(o)}finally{e.ui.setIsExecuting(!1)}}async function zc(e,t){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const n=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!n)throw new Error("Embedded wallet not available \u2014 sign in to create one before supplying");const o=e.selectedAsset.asset,s=Qe(e.selectedAsset.amount,o.decimals),r=s,i=o?._source==="wallet"&&o.chainId===e.resolvedChainId;let c=await e.gasless.buildSupplyChainBatches();const d={userOverride:n,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode};let l=s;const p=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,u=e.feeExecutionMode==="user-transfer"&&!p?r:void 0;let f;if(i){const F=await ot.estimateBatchGas({user:n,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:c}),T=qo(s,10n),I=T+F.gasFee;l=s+I,e.feeExecutionMode==="user-transfer"&&(f={grossAmount:l,netAmount:r,combinedFeeAmount:I,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:T,gasFee:F.gasFee,bridgeFee:0n}})}else{const F=await e.gasless.estimateGasless(c,e.executionTokenAddress,0n,d),T=Gn(F,{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:Ut(e.executionTokenAddress,e.resolvedChainId)?.symbol??e.destinationToken.symbol,decimals:Ut(e.executionTokenAddress,e.resolvedChainId)?.decimals??e.destinationToken.decimals});T&&(l=T.grossAmount>s?T.grossAmount:s,e.feeExecutionMode==="user-transfer"&&(f={grossAmount:l,netAmount:r,combinedFeeAmount:T.totalFee,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:T.spicenetFee,gasFee:T.gasFee,bridgeFee:T.bridgeFee??0n}}))}const h=Ut(e.executionTokenAddress,e.resolvedChainId),m=i?l:fo(l,h?.decimals??e.destinationToken.decimals,o.decimals);pa(e,l),c=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:l,sourceFundingAmountOverride:m,withdrawalAmountOverride:l,actionAmountOverride:u,actionContextOverride:f});const y=o.chainId,x=n,k=await e.externalWallet.getEthereumProvider();let w=null;try{const F=await k.request({method:"eth_chainId"});w=parseInt(F,16)}catch{w=null}w!==y&&(e.ui.setStatusMsg("Switching source network..."),await Yn(k,y));const C=Be(y),v=Ln({account:e.externalWalletAddress,chain:C?.viemChain,transport:zn(k)}),b=Tt(o.address),S=o.isNative||Ue(b);e.ui.setStatusMsg("Funding embedded wallet...");const E=S?await v.sendTransaction({to:x,value:m,chain:C?.viemChain}):await v.sendTransaction({to:b,data:gt({abi:Qt,functionName:"transfer",args:[x,m]}),chain:C?.viemChain});if((await dt(y).waitForTransactionReceipt({hash:E,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Embedded wallet funding failed");e.ui.setStatusMsg("Signing supply intent..."),await e.gasless.executeGasless(c,e.executionTokenAddress,0n,e.gasless.onProgress,t,d)}async function ga(e){const t=e.isPayMode&&e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t)throw new Error("Select a payment source");const n=e.activeSignerWallet??e.externalWallet,o=e.activeSignerAddress??e.externalWalletAddress;if(!o||!n)throw new Error("Please connect your wallet to continue");const s=Qe(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),r={userAddress:o,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},i=e.buildActionCalls(s,r);if(i.length===0)throw new Error("No action calls configured");const c=await n.getEthereumProvider();let d=null;try{const h=await c.request({method:"eth_chainId"});d=parseInt(h,16)}catch{d=null}d!==e.resolvedChainId&&await Yn(c,e.resolvedChainId);const l=Be(e.resolvedChainId),p=Ln({account:o,chain:l?.viemChain,transport:zn(c)}),u=dt(e.resolvedChainId);let f;for(const h of i){const m=await p.sendTransaction({to:h.to,data:h.data,value:h.value,chain:l?.viemChain});if((await u.waitForTransactionReceipt({hash:m,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transaction failed");f=m}return f}async function Oc(e){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const n=e.selectedAsset.asset,o=n.chainId,s=Qe(e.currentPaymentAmount,e.destinationToken.decimals),r=e.selectedIsEquivalent?s:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(r===0n)throw new Error("Quote not available yet");const i=e.resolvedTokenIn||e.selectedAsset.asset.address,c={userOverride:t,useCustomTransfers:!0},d=await e.gasless.estimateRequiredGrossFunding(r,w=>e.gasless.buildPayChainBatches({fundingAmountOverride:w}),i,c),l=An(o),p=await e.externalWallet.getEthereumProvider();let u=null;try{const w=await p.request({method:"eth_chainId"});u=parseInt(w,16)}catch{u=null}u!==o&&await Yn(p,o);const f=Be(o),h=Ln({account:e.externalWalletAddress,chain:f?.viemChain,transport:zn(p)}),m=Tt(n.address),y=n.isNative||Ue(m)?await h.sendTransaction({to:l,value:d,chain:f?.viemChain}):await h.sendTransaction({to:m,data:gt({abi:Qt,functionName:"transfer",args:[l,d]}),chain:f?.viemChain});if((await dt(o).waitForTransactionReceipt({hash:y,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Escrow deposit failed");const x=await e.gasless.buildPayChainBatches({fundingAmountOverride:d}),k=x.some(w=>w.tokenTransfers?.length);return await e.gasless.executeGasless(x,i,d,w=>{w.txHash&&(e.ui.setPaymentResult(C=>({...C??{status:"processing"},txHash:w.txHash})),e.ui.setTxHash(w.txHash))},void 0,k?c:{userOverride:t})}async function Hc(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}const t=e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t){e.ui.setError("Select a payment source");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.parsedAmount>0&&e.needsSwap&&!e.exactOutputSwap){e.ui.setError("Swap quote not available. Try a different asset.");return}if(e.isNon7702){if(t){e.ui.setError(null),e.ui.setShowStatusPanel(!1),e.onSuccess?.("");return}const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{let o;if(e.isSourceDestToken||e.parsedAmount===0)o=await ga(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const s=e.selectedAsset.asset,r=Qe(e.currentPaymentAmount,e.destinationToken.decimals),i=e.selectedIsEquivalent?r:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(i===0n)throw new Error("Quote not available yet");const c=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!c)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const d=e.resolvedTokenIn||s.address,l=await e.gasless.estimateRequiredGrossFunding(i,f=>e.gasless.buildPayChainBatches({fundingAmountOverride:f}),d,{userOverride:c,useCustomTransfers:!0}),p=await e.gasless.buildPayChainBatches({fundingAmountOverride:l}),u=await e.onPayExecute({asset:s,amount:e.currentPaymentAmount,amountWei:r,destinationToken:e.destinationToken,chainBatches:p,requiredNetFunding:i,grossFundingAmount:l,selectedIsEquivalent:e.selectedIsEquivalent,resolvedTokenIn:d,exactOutputSwapAmountInMax:e.exactOutputSwap?.amountInMax});u&&(e.ui.setTxHash(u),e.ui.setPaymentResult(f=>({...f??{status:"processing"},txHash:u}))),o=u||void 0}else o=await Oc(e);e.ui.setPaymentResult(s=>({status:"success",txHash:s?.txHash||o||""}))}catch(o){const s=In(o,"Payment failed. Please try again.");e.ui.setError(s),e.ui.setPaymentResult({status:"failed",error:s}),e.onError?.(o instanceof Error?o:new Error(s))}finally{e.ui.setIsExecuting(!1)}return}if(!e.isConnected||!e.address){e.ui.setError("Please connect your wallet to continue");return}if(!e.ready||!e.authenticated){e.ui.setError(`Please authenticate with ${e.provider||"wallet provider"} to continue`);return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{const n=Qe(e.currentPaymentAmount,e.destinationToken.decimals),o={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode};if(t){const y=await e.gasless.buildPayChainBatches({actionAmountOverride:0n,fundingAmountOverride:0n}),x=await e.gasless.executeGasless(y,e.destinationToken.address,0n,k=>{k.txHash&&(e.ui.setPaymentResult(w=>({...w,txHash:k.txHash})),e.ui.setTxHash(k.txHash))},void 0,o);e.ui.setPaymentResult(k=>({status:"success",txHash:k?.txHash||x}));return}const s=e.selectedAsset?.asset;if(!s)throw new Error("Select a payment source");const r=e.resolvedTokenIn||s.address||e.destinationToken.address,i=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:n,c=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,d=await e.gasless.estimateRequiredGrossFunding(i,y=>e.gasless.buildPayChainBatches({fundingAmountOverride:y}).then(x=>dn(oo(x),c)),r,o);let l=d,p=dn(oo(await e.gasless.buildPayChainBatches({fundingAmountOverride:d})),c);const u=await e.gasless.estimateGasless(p,r,d,o),f=Gn(u,{chainId:e.resolvedChainId,tokenAddress:r,symbol:Ut(r,e.resolvedChainId)?.symbol??s.symbol,decimals:Ut(r,e.resolvedChainId)?.decimals??s.decimals})?.grossAmount??d;f!==d&&(l=f),p=dn(oo(await e.gasless.buildPayChainBatches({fundingAmountOverride:l})),c,u,{payoutAlreadyGross:!0});const h=p.some(y=>y.tokenTransfers?.length),m=await e.gasless.executeGasless(p,r,h?l:0n,y=>{y.txHash&&(e.ui.setPaymentResult(x=>({...x,txHash:y.txHash})),e.ui.setTxHash(y.txHash))},void 0,o);e.ui.setPaymentResult(y=>({status:"success",txHash:y?.txHash||m}))}catch(n){const o=In(n,"Payment failed. Please try again.");e.ui.setError(o),e.ui.setPaymentResult({status:"failed",error:o}),e.onError?.(n instanceof Error?n:new Error(o))}finally{e.ui.setIsExecuting(!1)}}const ya=({variant:e,destinationSymbol:t,destinationLogoURI:n,destinationDecimals:o,primaryColor:s,fontFamily:r,textPrimary:i,textSecondary:c,cardBg:d,cardBorder:l,dk:p,dark:u,isQuoting:f,quoteError:h,estimatedOutput:m,paymentAmount:y,needsSwap:x,exactOutputSwap:k,adjustable:w=!1,maxAmount:C,onAmountChange:v})=>e==="supply"?g("div",{style:{backgroundColor:d,border:`1px solid ${l}`,borderRadius:u?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",minHeight:"112px",display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[g("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"12px"},children:[g("div",{style:{minWidth:0},children:[a("span",{style:{fontFamily:r,fontSize:"17px",fontWeight:500,color:u?"#a7abb2":"#7D7C7B",lineHeight:"24px"},children:"Used in TX"}),a("div",{style:{fontSize:"12px",fontWeight:500,color:c,fontFamily:r,marginTop:"10px"},children:"Net amount after swap and fees"})]}),g("div",{style:{textAlign:"right",minWidth:0,display:"inline-flex",alignItems:"center",gap:"8px",border:`1px solid ${l}`,borderRadius:"8px",padding:"8px 10px",minHeight:"42px"},children:[a(xa,{symbol:t,logoURI:n,primaryColor:s,size:24}),a("span",{style:{fontSize:"16px",fontWeight:500,color:u?"#f3f4f6":"#3C3E42",lineHeight:"1.3",fontFamily:r,letterSpacing:0},children:t})]})]}),a("div",{style:{textAlign:"right",minWidth:0},children:f?a("span",{style:{fontSize:"18px",color:c,fontFamily:r},children:"Quoting..."}):h?a("span",{style:{fontSize:"13px",color:u?"#f87171":"#dc2626",fontFamily:r},children:"Quote failed"}):m?a(eo,{value:m,title:m,fontFamily:r,color:i,lineHeight:"0.95",textAlign:"right",maxFontSize:32,minFontSize:18}):a("span",{style:{fontSize:"20px",color:c,fontFamily:r},children:"\u2014"})})]}):a(jc,{destinationSymbol:t,destinationLogoURI:n,destinationDecimals:o,primaryColor:s,fontFamily:r,textPrimary:i,textSecondary:c,cardBg:d,cardBorder:l,dk:p,dark:u,paymentAmount:y||"0",needsSwap:x,exactOutputSwap:k,isQuoting:f,adjustable:w,maxAmount:C,onAmountChange:v}),xa=({symbol:e,logoURI:t,primaryColor:n,size:o})=>t?a("img",{src:t,alt:e,style:{width:o,height:o,borderRadius:"50%",objectFit:"cover"}}):a("div",{style:{width:o,height:o,borderRadius:"50%",backgroundColor:`${n}22`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:o<30?"11px":"12px",fontWeight:700,color:n},children:e.slice(0,2)}),jc=({destinationSymbol:e,destinationLogoURI:t,destinationDecimals:n,primaryColor:o,fontFamily:s,textPrimary:r,textSecondary:i,cardBg:c,cardBorder:d,dk:l,dark:p,paymentAmount:u,needsSwap:f,exactOutputSwap:h,isQuoting:m,adjustable:y,maxAmount:x,onAmountChange:k})=>{const w='"IBM Plex Mono", monospace',C=parseFloat(u||"0"),v=x?parseFloat(x):0,[b,S]=R(u||""),E=ie(null),[F,T]=R(null),[I,A]=R(null);Z(()=>{y||S(u||"")},[u,y]);const B=W=>{let L=W;L.startsWith(".")&&(L="0"+L);const q=io(L);let D=q;x&&parseFloat(q)>parseFloat(x)&&(D=x),S(D),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>k?.(D),300)},M=W=>{if(!v)return;if(W===100){S(x||v.toString()),E.current&&clearTimeout(E.current),k?.(x||v.toString());return}const L=10**n,q=Math.floor(v*W/100*L)/L,D=lo(q,n);S(D),E.current&&clearTimeout(E.current),k?.(D)},U=v>0?parseFloat(b||"0")/v*100:0;return Z(()=>()=>{E.current&&clearTimeout(E.current)},[]),g("div",{style:{backgroundColor:c,border:`1px solid ${d}`,borderRadius:p?"12px":"6px",padding:"16px",marginBottom:"16px"},children:[g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[a(xa,{symbol:e,logoURI:t,primaryColor:o,size:32}),g("div",{children:[a("span",{style:{fontSize:"14px",fontWeight:600,color:r,fontFamily:s},children:"Payment"}),a("div",{style:{fontSize:"12px",color:i,fontFamily:s,marginTop:"2px"},children:e})]})]}),g("div",{style:{textAlign:"right"},children:[y?a(eo,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:b,onChange:W=>B(W.target.value),placeholder:"0.0",fontFamily:w,color:r,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):a(eo,{element:"div",value:C>0?u:"0.00",title:C>0?u:"0.00",fontFamily:w,color:r,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),a("div",{style:{fontSize:"12px",color:i,fontFamily:w,marginTop:"2px"},children:e}),y&&v>0&&a("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((W,L)=>{const q=Math.abs(U-W)<1,D=L===4,P=W/100,O=F===W,j=I===W;return a("button",{onClick:()=>M(W),onMouseEnter:()=>T(W),onMouseLeave:()=>{T(null),A(null)},onMouseDown:()=>A(W),onMouseUp:()=>A(null),title:`${W}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:q?1:O?.8:.5,transform:j?"scale(0.85)":O?"scale(1.15)":"scale(1)",transition:cn.interactive},children:g("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[a("circle",{cx:"7",cy:"7",r:"6.84375",fill:D?o:"none",stroke:D?o:p?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!D&&P>0&&a("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${P>.5?1:0} 1 ${7+6.84375*Math.sin(P*2*Math.PI)} ${7-6.84375*Math.cos(P*2*Math.PI)} Z`,fill:p?l?.textSecondary||"#9ca3af":"#3C3E42"})]})},W)})})]})]}),f&&h&&!m&&a("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:p?`1px solid ${l?.cardBorder||d}`:"1px solid #e5e7eb",display:"flex",justifyContent:"flex-end"},children:g("span",{style:{fontSize:"11px",color:i,fontFamily:s,opacity:.7},children:["via ",h.venue]})})]})};function ba(e,t,n){const o=Ae(e.address,t),s=e.chainId===n,r=e._source==="wallet";return r&&o&&s?0:r&&s?1:!r&&o?2:!r&&s?3:4}function Qc(e,t){return!t||t.length===0||t.some(n=>Ae(n,e.address))?!0:Object.keys(e.chainTokens??{}).some(n=>{const o=po(n);return o?t.some(s=>Ae(s,o.address)):!1})}function Vc(e){const{destinationToken:t,supportedSourceAssets:n,sourceChains:o,enabled:s}=e,r=(Zt(Ht)?.mode||"7702")!=="7702",i=Rn(),{externalAddress:c,embeddedAddress:d,activeAddress:l}=_n(),p=i||d,{assets:u,refetch:f}=Eo({address:p,supportedChains:o,enabled:s&&!r&&!!p,refetchInterval:3e4}),h=re(()=>r?[]:u.filter(F=>Qc(F,n)),[u,n,r]),m=r?l??c:i,y=re(()=>{const F=new Set,T=[],I=A=>{if(!A)return;const B=A.toLowerCase();F.has(B)||(F.add(B),T.push(Me(A)))};if(I(t.address),r&&n)for(const A of n)I(A);return T},[r,t.address,n]),x=re(()=>y.map(F=>F.toLowerCase()).sort().join(","),[y]),k=re(()=>JSON.stringify([...o||[]].sort()),[o]),[w,C]=R([]),v=ie(0),b=ie(async()=>{}),S=ce(async()=>{if(!s||!m||y.length===0){v.current++,C([]);return}const F=++v.current,T=Me(m),I=r?o&&o.length>0?o:[t.chainId]:[t.chainId],A=[];for(const W of y){const L=W.toLowerCase();if(L===jt)continue;if(L===t.address.toLowerCase()){const D=Be(t.chainId)?.supportedTokens?.find(P=>Ae(P.address,L));A.push({address:W,chainId:t.chainId,configToken:D?{decimals:D.decimals,symbol:D.symbol,name:D.name,logo:D.logo}:void 0});continue}let q=!1;for(const D of I){const P=Be(D)?.supportedTokens?.find(O=>Ae(O.address,L));if(P){A.push({address:W,chainId:D,configToken:{decimals:P.decimals,symbol:P.symbol,name:P.name,logo:P.logo}}),q=!0;break}}q||A.push({address:W,chainId:t.chainId})}const B=new Map;for(const W of A){const L=B.get(W.chainId)||[];L.push(W),B.set(W.chainId,L)}const M=async(W,L)=>{try{const q=await En(W,{address:L.address,abi:Qt,functionName:"balanceOf",args:[T]});let D,P,O,j;if(L.configToken)D=L.configToken.decimals,P=L.configToken.symbol,O=L.configToken.name,j=L.configToken.logo;else{const[pe,N,ae]=await Promise.all([En(W,{address:L.address,abi:Qt,functionName:"decimals"}).catch(()=>18),En(W,{address:L.address,abi:Qt,functionName:"symbol"}).catch(()=>"TOKEN"),En(W,{address:L.address,abi:Qt,functionName:"name"}).catch(()=>"TOKEN")]);D=Number(pe),P=N,O=ae}const z=Ae(L.address,t.address)&&L.chainId===t.chainId;z&&t.logoURI&&(j=t.logoURI),z&&!L.configToken&&P==="TOKEN"&&(P=t.symbol,O=t.symbol);const J=parseFloat((Number(q)/Math.pow(10,D)).toFixed(6));return{address:L.address,name:O,symbol:P,decimals:D,balance:q,balanceFormatted:J,balanceUsd:0,logoURI:j,isNative:!1,chainId:L.chainId}}catch{return null}},U=await Promise.all(Array.from(B.entries()).map(async([W,L])=>{let q;try{q=dt(W)}catch{return[]}const D=[],P=[];for(const j of L){const z=D.length;D.push({address:j.address,abi:Qt,functionName:"balanceOf",args:[T]}),j.configToken||D.push({address:j.address,abi:Qt,functionName:"decimals"},{address:j.address,abi:Qt,functionName:"symbol"},{address:j.address,abi:Qt,functionName:"name"}),P.push({start:z,item:j})}let O=null;try{O=await q.multicall({contracts:D})}catch{O=null}return O?P.map(({start:j,item:z})=>{const J=O[j],pe=J?.status==="success"?J.result:0n;let N,ae,le,ge;if(z.configToken)N=z.configToken.decimals,ae=z.configToken.symbol,le=z.configToken.name,ge=z.configToken.logo;else{const ke=O[j+1],H=O[j+2],oe=O[j+3];N=ke?.status==="success"?Number(ke.result):18,ae=H?.status==="success"?H.result:"TOKEN",le=oe?.status==="success"?oe.result:ae}const Re=Ae(z.address,t.address)&&z.chainId===t.chainId;Re&&t.logoURI&&(ge=t.logoURI),Re&&!z.configToken&&ae==="TOKEN"&&(ae=t.symbol,le=t.symbol);const de=parseFloat((Number(pe)/Math.pow(10,N)).toFixed(6));return{address:z.address,name:le,symbol:ae,decimals:N,balance:pe,balanceFormatted:de,balanceUsd:0,logoURI:ge,isNative:!1,chainId:z.chainId}}):(await Promise.all(L.map(j=>M(q,j)))).filter(j=>j!==null)}));F===v.current&&C(U.flat())},[s,r,m,x,k,t.address,t.chainId,t.symbol,t.logoURI]);Z(()=>{b.current=S},[S]),Z(()=>{if(!s){C([]);return}b.current();const F=setInterval(()=>{b.current()},15e3);return()=>clearInterval(F)},[s,r,m,x,k,t.address,t.chainId]);const E=ce(()=>{S()},[S]);return{displayAssets:re(()=>{const F=[],T=w.filter(A=>A.balance>0n);for(const A of T)F.push({...A,_source:"wallet"});for(const A of h)F.push({...A,_source:"spice"});const I=t.address.toLowerCase();return F.sort((A,B)=>ba(A,I,t.chainId)-ba(B,I,t.chainId)),F},[w,h,t.address,t.chainId]),filteredSpiceAssets:h,walletAssets:w,embeddedWalletAddress:p,externalAddress:c,isNon7702:r,refreshSpiceAssets:f,refreshWalletAssets:E}}async function wa(e){const{tokenIn:t,tokenOut:n,amountIn:o,fee:s,chainId:r,config:i}=e;if(o<=0n)throw new Error("amountIn must be greater than 0");const c=(await dt(r).simulateContract({address:i.quoterV2,abi:ai,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:o,fee:s,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 Ca(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(s=>wa({...e,fee:s})));let o=null;for(let s=0;s<n.length;s++){const r=n[s];r.status==="fulfilled"&&(!o||r.value.amountOut>o.amountOut)&&(o={...r.value,fee:t[s]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}const qc=[{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 Yc(e){const{tokenIn:t,tokenOut:n,amountOut:o,fee:s,chainId:r,config:i}=e;if(o<=0n)throw new Error("amountOut must be greater than 0");const c=(await dt(r).simulateContract({address:i.quoterV2,abi:qc,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:o,fee:s,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 Kc(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(s=>Yc({...e,fee:s})));let o=null;for(let s=0;s<n.length;s++){const r=n[s];r.status==="fulfilled"&&(!o||r.value.amountIn<o.amountIn)&&(o={...r.value,fee:t[s]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}function ka(e){return e.type==="swap"}const Ks=.02,Zc=[1,8453,42161,10,137,43114,56],Gc="https://api.1inch.dev/swap/v6.0";function va(e,t){return li(e,t)}function Ia(e){const t=e?.baseUrl??Gc;return{name:"1inch",chainIds:e?.chainIds??Zc,resolve:async(n,o,s)=>{const r=n.maxSlippage??Ks,i=r*100,c=Ue(n.tokenIn)?ir:n.tokenIn,d=Ue(n.tokenOut)?ir:n.tokenOut,l=Ue(n.tokenIn);try{const p=new URL(`${t}/${o}/swap`);p.searchParams.set("src",c),p.searchParams.set("dst",d),p.searchParams.set("amount",n.amountIn.toString()),p.searchParams.set("from",s),p.searchParams.set("slippage",i.toString()),p.searchParams.set("disableEstimate","true"),p.searchParams.set("allowPartialFill","false");const u={Accept:"application/json"};e?.apiKey&&(u.Authorization=`Bearer ${e.apiKey}`);const f=await fetch(p.toString(),{headers:u});if(!f.ok)throw new Te("VENUE_API_ERROR",`[1inchVenue] API returned ${f.status} for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`,{venue:"1inch",chainId:o,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:`HTTP ${f.status}`});const h=await f.json();if(!h.dstAmount||!h.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const m=BigInt(h.dstAmount);if(m<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const y=va(m,r),x=[];return h.tx.to&&!l&&x.push({to:n.tokenIn,value:0n,data:gt({abi:Qt,functionName:"approve",args:[h.tx.to,n.amountIn]})}),x.push({to:h.tx.to,value:BigInt(h.tx.value||"0"),data:h.tx.data}),{venue:"1inch",amountOut:m,amountOutMinimum:y,calls:x}}catch(p){if(p instanceof Te)throw p;const u=p instanceof Error?p.message:String(p);throw new Te("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}: ${u}`,{venue:"1inch",chainId:o,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:u})}}}}const Aa=[4114,5115],Zs={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},Sa={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[3e3]};function Ea(e){return{name:"satsuma",chainIds:e.chainIds??Aa,resolve:async(t,n,o)=>{const s=t.maxSlippage??Ks,r=Ue(t.tokenIn);let i;try{i=await Ca({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountIn:t.amountIn,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return console.warn(`[SatsumaVenue] No viable fee tier for ${t.tokenIn} \u2192 ${t.tokenOut} on chain ${n}.`),null}const c=va(i.amountOut,s),d=[];return r||d.push({to:t.tokenIn,value:0n,data:gt({abi:Qt,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),d.push({to:e.swapRouter,value:r?t.amountIn:0n,data:gt({abi:ii,functionName:"exactInputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:i.fee,recipient:o,amountIn:t.amountIn,amountOutMinimum:c,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:i.amountOut,amountOutMinimum:c,calls:d}}}}function Fa(e){return{name:"satsuma",chainIds:e.chainIds??Aa,resolve:async(t,n,o)=>{const s=t.maxSlippage??Ks,r=Ue(t.tokenIn);let i;try{i=await Kc({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountOut:t.amountOut,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return null}const c=BigInt(Math.round(s*1e4)),d=i.amountIn+i.amountIn*c/10000n,l=[];return l.push({to:e.swapRouter,value:r?d:0n,data:gt({abi:Xc,functionName:"exactOutputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:i.fee,recipient:o,amountOut:t.amountOut,amountInMaximum:d,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:i.amountIn,amountInMax:d,amountOut:t.amountOut,calls:l}}}}const Xc=[{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 Ba(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(Ea(e.satsuma)),t.push(Ia(e?.oneInch));function n(s){return t.find(r=>r.chainIds.includes(s))}async function o(s,r,i){const c=[],d=[];for(const l of s){if(!ka(l)){c.push(l);continue}const p=n(r);if(!p)throw new Te("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${r}. Cannot resolve swap ${l.tokenIn} \u2192 ${l.tokenOut}.`,{chainId:r,tokenIn:l.tokenIn,tokenOut:l.tokenOut,amountIn:l.amountIn.toString()});const u=await p.resolve(l,r,i);if(!u)throw new Te("NO_LIQUIDITY",`${p.name} returned no quote for ${l.tokenIn} \u2192 ${l.tokenOut} on chain ${r}.`,{venue:p.name,chainId:r,tokenIn:l.tokenIn,tokenOut:l.tokenOut,amountIn:l.amountIn.toString()});c.push(...u.calls),d.push(u)}return{calls:c,resolvedSwaps:d}}return{resolveSwapIntents:o,getVenueForChain:n,venues:t}}function Jc(e){const t=e?.customVenues??[];async function n(o,s,r){const i=t.filter(d=>d.chainIds.includes(s));if(i.length===0)throw new Te("NO_SWAP_ROUTE",`No exact-output venue supports chain ${s}`,{chainId:s,tokenIn:o.tokenIn,tokenOut:o.tokenOut});const c=(await Promise.allSettled(i.map(d=>d.resolve(o,s,r)))).filter(d=>d.status==="fulfilled").map(d=>d.value).filter(d=>d!==null);if(c.length===0)throw new Te("NO_SWAP_ROUTE",`All aggregators failed for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${s}`,{chainId:s,tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountOut:o.amountOut.toString()});return c.sort((d,l)=>d.amountIn<l.amountIn?-1:d.amountIn>l.amountIn?1:0),c[0]}return{getQuote:n,venues:t}}const $c=Ba({satsuma:Zs});function _c(e){const{direction:t,selectedAsset:n,destinationToken:o,chainId:s,recipient:r,paymentAmount:i}=e,[c,d]=R(!1),[l,p]=R(null),[u,f]=R(null),[h,m]=R(null),[y,x]=R(null),[k,w]=R(null),[C,v]=R(null),[b,S]=R(null),[E,F]=R(null),T=ie(null),I=ie(null),A=ie(0),B=ie(new Map),M=re(()=>$c,[]),U=re(()=>Jc({customVenues:[Fa(Zs),Fa(Sa)]}),[]),W=re(()=>{if(!n?.asset)return null;const N=Wn(n.asset,s);if(N)return N;const ae=Vn(n.asset.address,s,n.asset.chainId);return ae?ae.address:null},[n?.asset,s]),L=re(()=>n?.asset?jo(n.asset,s):[],[n?.asset,s]),q=re(()=>L.map(N=>N.toLowerCase()).join(","),[L]);Z(()=>{let N=!1;if(I.current&&(clearTimeout(I.current),I.current=null),!n?.asset||L.length<=1){F(null);return}return I.current=setTimeout(async()=>{const ae=t==="input"?n.amount:i||"0";let le=0n;try{le=t==="input"?Qe(ae,n.asset.decimals):0n}catch{le=0n}try{const ge=await Or(n.asset,s,{requiredAmount:le});N||F(ge)}catch{N||F(null)}},400),()=>{N=!0,I.current&&(clearTimeout(I.current),I.current=null)}},[n?.asset,n?.amount,s,L.length,q,t,i]);const D=re(()=>E??W,[E,W]),P=re(()=>!n?.asset||!D?[]:[D,...L.filter(N=>N.toLowerCase()!==D.toLowerCase())],[n?.asset,D,L]),O=re(()=>!n?.asset||!So(n.asset.address,n.asset.chainId,o.address,o.chainId)||!D?!1:Ae(D,o.address),[n,o.address,o.chainId,D]),j=D?Ae(D,o.address):!1,z=t==="output"&&parseFloat(i||"0")===0,J=!!n?.asset&&!O&&!j&&!z,pe=J?b??D:D;return Z(()=>{T.current&&clearTimeout(T.current);const N=t==="input"?n?.amount:i,ae=parseFloat(N||"0");if(!J||!Number.isFinite(ae)||ae<=0||!n?.asset||!r||P.length===0){A.current++,f(null),m(null),x(null),w(null),v(null),S(null),p(null),d(!1);return}const le=n.asset.decimals;let ge;try{ge=t==="input"?Qe(n.amount,le):Qe(i||"0",o.decimals)}catch{A.current++,p("Invalid amount"),d(!1);return}const Re=++A.current,de=()=>Re!==A.current;d(!0);const ke=t==="output"?150:400;return T.current=setTimeout(async()=>{try{if(t==="input"){const H=M.getVenueForChain(s);if(!H)throw new Error("No swap venue for this chain");let oe=null,X=null;for(const fe of P){const Ee=`${t}:${s}:${fe.toLowerCase()}:${o.address.toLowerCase()}:${ge.toString()}`,be=B.current.get(Ee);if(be&&be.expiresAt>Date.now()&&be.resolvedSwap){oe=be.resolvedSwap,X=fe;break}const V=await H.resolve({type:"swap",tokenIn:fe,tokenOut:o.address,amountIn:ge},s,r);if(de())return;if(V){B.current.set(Ee,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:V}),oe=V,X=fe;break}}if(!oe||!X)throw new Error("No liquidity for this pair");S(X),v(oe.amountOut),x(oe),w(null);const se=parseFloat(ct(oe.amountOut,o.decimals));f(se<.01?se.toPrecision(4):se.toLocaleString(void 0,{maximumFractionDigits:6})),m(null),p(null)}else{let H=null,oe=null;for(const X of P){const se=`${t}:${s}:${X.toLowerCase()}:${o.address.toLowerCase()}:${ge.toString()}`,fe=B.current.get(se);if(fe&&fe.expiresAt>Date.now()&&fe.exactOutputSwap){H=fe.exactOutputSwap,oe=X;break}try{const Ee=await U.getQuote({tokenIn:X,tokenOut:o.address,amountOut:ge},s,r);if(de())return;B.current.set(se,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:Ee}),H=Ee,oe=X;break}catch{if(de())return}}if(!H||!oe)throw new Error("No liquidity for this pair");S(oe),w(H),x(null),v(null),m(parseFloat(ct(H.amountIn,le)).toFixed(6)),f(null),p(null)}}catch(H){if(de())return;const oe=H instanceof Error?H.message:"Failed to get quote";p(oe),f(null),m(null),x(null),w(null),v(null),S(null)}finally{de()||d(!1)}},ke),()=>{T.current&&clearTimeout(T.current)}},[t,J,n?.amount,n?.asset?.address,n?.asset?.decimals,i,P,s,o.address,o.decimals,r,M,U]),{isQuoting:c,quoteError:l,estimatedOutput:u,estimatedInput:h,resolvedSwap:y,exactOutputSwap:k,quoteAmountOut:C,resolvedTokenIn:pe,isDirect:j,needsSwap:J,selectedIsEquivalent:O}}const Ta={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},Ma=["signing-delegation","signing-intent","submitting","executing"],Ra=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,destinationToken:o,sourceChains:s,supportedSourceAssets:r,buildActionCalls:i,feeExecutionMode:c="user-transfer",buildSpicenetBatch:d,onPayExecute:l,actionLabel:p,amountDirection:u="input",swapDescription:f,directDescription:h,paymentAmount:m,amountInputMode:y="fixed",minPaymentAmount:x,maxPaymentAmount:k,onAmountChange:w,styles:C,dark:v,title:b,subtitle:S,onAddFunds:E,onSuccess:F,onError:T})=>{const I=u==="output",{theme:A,dark:B,primaryColor:M,dk:U,palette:W,fontFamily:L,monoFont:q,inputDark:D,cardBg:P,cardBorder:O,textPrimary:j,textSecondary:z,subtitleText:J}=lt(C,v),pe=D?{...A,colors:{...A.colors,secondary:U.cardBg,surfaceHover:U.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:A,N=o.chainId,ae=Zt(Ht),le=(ae?.mode||"7702")!=="7702",ge=!!ae?.isWhitelistGateActive,Re=re(()=>s??ae?.supportedChainIds??[],[s,ae?.supportedChainIds]),de=re(()=>{if(ge)return[];if(r)return r;const Ce=ae?.allowedTokens;if(!Ce||Ce.length===0)return;const et=new Set(Ce.map(vn=>vn.toLowerCase())),kn=[],yn=new Set;for(const vn of Re){const ts=Be(vn);for(const ns of ts?.supportedTokens??[]){if(!et.has(ns.symbol.toLowerCase()))continue;const $s=ns.address.toLowerCase();yn.has($s)||(yn.add($s),kn.push(ns.address))}}return kn},[r,ae?.allowedTokens,Re,ge]),ke=Mn(),{address:H,isConnected:oe,isReady:X,isAuthenticated:se,provider:fe}=ke,{executeGasless:Ee,estimateGasless:be}=Go(),{externalWallet:V,externalAddress:Q,embeddedAddress:he,activeWallet:Le,activeAddress:kt}=_n(),zt=Rn()||he,{displayAssets:Ot,filteredSpiceAssets:st,embeddedWalletAddress:rt,refreshSpiceAssets:G,refreshWalletAssets:We}=Vc({destinationToken:o,supportedSourceAssets:de,sourceChains:Re,enabled:e&&(le?!!Q:!!zt)}),we=ge||I||le?Ot:st,[_,Ze]=R(null),[Rt,un]=R(m||""),[ut,on]=R(!1),[Nt,Xt]=R(null),[De,pn]=R("idle"),[sn,xn]=R(""),[Vt,rn]=R(null),[yt,pt]=R(!1),[Ye,Jt]=R(null),[xt,me]=R(null),[bt,tt]=R(!1),[fn,ye]=R(!1),[qt,ft]=R(null),Dt=ie(_),Mt=ie(!1),hn=ie(null),Yt=ie(0),bn=ie(null),wn=ie(null);Z(()=>{Dt.current=_},[_]);const Ne=y==="adjustable"?Rt:m||"0",Pt=rt||he||H,{isQuoting:Je,quoteError:$t,estimatedOutput:Nn,resolvedSwap:Ge,exactOutputSwap:$e,quoteAmountOut:Wt,resolvedTokenIn:vt,isDirect:ze,needsSwap:Xe,selectedIsEquivalent:_t}=_c({direction:u,selectedAsset:_,destinationToken:o,chainId:N,recipient:Pt,paymentAmount:Ne}),Et=I?parseFloat(Ne||"0"):parseFloat(_?.amount||"")||0,en=_?.asset?._source==="wallet",Oe=!!_?.asset&&en&&_.asset.chainId!==N,Pn=re(()=>_?.asset?st.find(Ce=>Ae(Ce.address,_.asset.address))?.balanceFormatted??0:0,[_,st]),ee=en?_?.asset.balanceFormatted??0:Pn,te=re(()=>{if(!_?.asset)return!1;if(I)return xt?fo(xt.grossAmount,xt.decimals,_.asset.decimals)>_.asset.balance:_t||ze?Et>_.asset.balanceFormatted:$e?parseFloat(ct($e.amountInMax,_.asset.decimals))>_.asset.balanceFormatted:!1;if(xt){const Ce=fo(xt.grossAmount,xt.decimals,_.asset.decimals);return en?Ce>_.asset.balance:parseFloat(ct(Ce,_.asset.decimals))>ee}return Et>ee},[_,I,xt,_t,Et,$e,ee,en,ze]);Z(()=>{e||(Ze(null),Xt(null),on(!1),pn("idle"),xn(""),rn(null),pt(!1),Jt(null),me(null),tt(!1),ye(!1),ft(null),Mt.current=!1,y==="adjustable"&&un(m||""),hn.current&&(hn.current.abort(),hn.current=null))},[e]);const ve=ce(Ce=>{Ze(et=>({asset:Ce,amount:et?.asset?.address===Ce.address&&et?.asset?.chainId===Ce.chainId&&et.amount||""})),Xt(null),ft(null),ye(!1)},[]),Ve=ce(Ce=>{Ze(et=>et&&{...et,amount:Ce}),Xt(null),ft(null),ye(!1)},[]),It=ce(Ce=>{let et=Ce;k&&parseFloat(et)>parseFloat(k)&&(et=k),un(et),w?.(et),Xt(null),ft(null),ye(!1)},[k,w]);ce(Ce=>{if(Mt.current||!H)return;const et=Dt.current;!et?.asset||!et.amount||et.asset?._source==="wallet"||Qe(I?Ne:et.amount,et.asset.decimals)===0n||(Mt.current=!0,G())},[H,N,G,I,Ne]);const wt=ce(Ce=>{pn({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[Ce.step]||"executing"),xn(Ce.message),Ce.txHash&&rn(Ce.txHash)},[]),ht=re(()=>({currentPaymentAmount:Ne,destinationToken:o,embeddedWalletAddress:rt,providerEmbeddedAddress:he,externalWalletAddress:Q,address:H,isNon7702:le,isPayMode:I,resolvedChainId:N,buildActionCalls:i,feeExecutionMode:c,buildSpicenetBatch:d,selectedAsset:_,needsSwap:Xe,resolvedSwap:Ge,exactOutputSwap:$e,quoteAmountOut:Wt,resolvedTokenIn:vt}),[Ne,o,rt,he,Q,H,le,I,N,i,c,d,_,Xe,Ge,$e,Wt,vt]),at=ce(Ce=>Fc(ht,Ce),[ht]),He=ce(Ce=>Bc(ht,Ce),[ht]),nt=ce((Ce,et,kn,yn)=>Tc(Ce,et,kn,be,yn),[be]),Pe=re(()=>_?.asset?Xe&&vt?vt:_.asset.chainId===N?_.asset.address:vt??Wn(_.asset,N)??o.address:o.address,[_,o.address,Xe,N,vt]),qe=ce(()=>Lc(wn.current),[]),K=re(()=>_?.asset?Ae(_.asset.address,o.address)&&_.asset.chainId===o.chainId:!1,[_,o.address,o.chainId]),Ie=le&&K,mt=Ie&&Et>0&&!!_?.asset,At=Nt,_e=re(()=>!(!_?.asset||Et<=0),[_,Et,mt]),tn=re(()=>!e||ut||De!=="idle"||!_e||mt||!_?.asset?null:[I?"pay":"supply",u,_.asset.address.toLowerCase(),_.asset.chainId,_.amount,Ne,o.address.toLowerCase(),o.chainId,N,vt?.toLowerCase()??"",Xe?"swap":"direct",ze?"direct-token":"routed-token",le?"non7702":"7702",K?"source-dest":"cross-chain",Je?"quoting":"quoted",$e?.amountIn?.toString()??"",$e?.amountInMax?.toString()??"",$e?.venue??"",Ge?.amountOut?.toString()??"",Wt?.toString()??"",rt??"",he??"",H??""].join("|"),[e,ut,De,_e,mt,_,I,u,Ne,o,N,vt,Xe,ze,le,K,Je,$e,Ge,Wt,rt,he,H]),Y=ce(()=>Wc({selectedAsset:_,isPayMode:I,parsedAmount:Et,needsSwap:Xe,exactOutputSwap:$e,isNon7702:le,isSourceDestToken:K,currentPaymentAmount:Ne,destinationToken:o,feeExecutionMode:c,resolvedTokenIn:vt,embeddedWalletAddress:rt,providerEmbeddedAddress:he,resolvedChainId:N,isConnected:oe,address:H,ready:X,authenticated:se,isDirect:ze,resolvedSwap:Ge,isQuoting:Je,executionTokenAddress:Pe,buildPayChainBatches:at,buildSupplyChainBatches:He,estimateGasless:be,estimateRequiredGrossFunding:nt}),[_,I,Et,Xe,$e,le,K,Ne,o,c,vt,rt,he,nt,at,be,N,oe,H,X,se,ze,Ge,Je,He,Pe]);Z(()=>{bn.current=Y},[Y]);const $=ce(Ce=>Dc({asset:Ce,isPayMode:I,isNon7702:le,needsSwap:Xe,isQuoting:Je,embeddedWalletAddress:rt,buildSupplyChainBatches:He,estimateGasless:be,executionTokenAddress:Pe,feeExecutionMode:c}),[I,le,Xe,Je,rt,He,be,Pe,c]);Z(()=>{if(!e){tt(!1),ye(!1),ft(null),me(null);return}if(ut||De!=="idle"){Yt.current+=1,tt(!1);return}if(!_e){me(null),tt(!1),ye(!1),ft(null);return}if(mt){me(null),tt(!1),ye(!0),ft(null);return}if(Je){Yt.current+=1,tt(!1),ye(!1);return}if(!tn)return;let Ce=!1;const et=async()=>{const yn=++Yt.current;ft(null),tt(!0);try{const vn=await bn.current?.();if(Ce||Yt.current!==yn)return;vn?(me(vn),ye(!0)):(me(null),ye(!1)),ft(null)}catch(vn){if(Ce||Yt.current!==yn)return;const ts=In(vn,"Unable to calculate fees for this action.");me(null),ye(!1),ft(ts)}finally{!Ce&&Yt.current===yn&&tt(!1)}},kn=window.setTimeout(()=>{et()},250);return()=>{Ce=!0,clearTimeout(kn),tt(!1)}},[e,ut,De,_e,mt,Je,tn]);const ue=ce(()=>Hc(wn.current),[]);Z(()=>{!I&&De==="success"&&Vt&&(G(),F?.(Vt))},[I,De,Vt,G,F]),Z(()=>{if(!I||Ye?.status!=="success"||Mt.current||!H)return;Mt.current=!0;const Ce=Dt.current;!Ce?.asset||Ce.asset?._source==="wallet"||G()},[I,Ye?.status,H,G]);const ne=ie(F),Fe=ie(T);Z(()=>{ne.current=F},[F]),Z(()=>{Fe.current=T},[T]),Z(()=>{e&&(G(),We())},[e,G,We]),Z(()=>{I&&(Ye?.status==="success"&&ne.current?.(Ye.txHash||""),Ye?.status==="failed"&&Fe.current?.(new Error("Payment execution failed")))},[I,Ye?.status]);const Se=ce(()=>{pt(!1),Jt(null),Ze(null),Mt.current=!1,G(),We()},[G,We]);wn.current={selectedAsset:_,parsedAmount:Et,currentPaymentAmount:Ne,isInsufficientBalance:te,isPayMode:I,isNon7702:le,isSourceDestToken:K,needsSwap:Xe,exactOutputSwap:$e,selectedIsEquivalent:_t,resolvedTokenIn:vt,embeddedWalletAddress:rt,providerEmbeddedAddress:he,externalWallet:V,externalWalletAddress:Q,activeSignerWallet:Le,activeSignerAddress:kt,address:H,isConnected:oe,ready:X,authenticated:se,provider:fe,resolvedChainId:N,executionTokenAddress:Pe,destinationToken:o,buildActionCalls:i,feeExecutionMode:c,buildSpicenetBatch:d,onPayExecute:l,onSuccess:F,onError:T,gasless:{estimateGasless:be,executeGasless:Ee,buildPayChainBatches:at,buildSupplyChainBatches:He,estimateRequiredGrossFunding:nt,onProgress:wt},ui:{setError:Xt,setStep:pn,setStatusMsg:xn,setTxHash:rn,setIsExecuting:on,setShowStatusPanel:pt,setPaymentResult:Jt},refs:{spiceDepositSubmittedRef:Mt,abortControllerRef:hn}};const Ft=m?.trim(),it=I&&y==="fixed"&&Ft!==void 0&&Ft!==""&&Et===0,je=I?(it||!!_?.asset)&&Et>=0&&!te&&!ut&&(it||mt||fn)&&!qt&&(it||!Xe||!!$e):!!_?.asset&&Et>0&&!te&&!ut&&(Ie||fn)&&!qt&&(Oe||ze||!!Ge&&!Je),Ct=ze?h||`Your ${o.symbol} will be used directly.`:f||"Your assets will be swapped and used in a single atomic transaction.",Cn=(N?Be(N):void 0)?.viemChain?.blockExplorers?.default?.url??"",Bn=Ma.indexOf(De),Tn=ut?(Ta[De]||"EXECUTING...").toUpperCase():De==="success"?"DONE":te?"INSUFFICIENT BALANCE":p.toUpperCase(),mn=re(()=>{if(ut)return"PAYING...";if(te&&_?.asset)return`INSUFFICIENT ${_.asset.symbol}`;if(p)return p.toUpperCase();const Ce=Et>0?` ${Ne} ${o.symbol}`:"";return Xe?`SWAP & PAY${Ce}`:`PAY${Ce}`},[ut,te,_,p,Et,Ne,o.symbol,Xe]),xe=De==="success"?()=>{pn("idle"),Ze(null),rn(null),G()}:qe,St=De==="success"?!1:!je;if(!e)return null;const Kt=I?b||`Pay ${o.symbol}`:p,gn=I?S:g("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[a("span",{style:{marginTop:"3px",flexShrink:0},children:a(As,{color:J})}),a("p",{style:{fontSize:"12px",color:J,margin:0,lineHeight:"1.4",fontFamily:L},children:Ct})]});if(I){const Ce=Ye&&(Ye.status==="success"||Ye.status==="failed")?[{asset:{symbol:_?.asset?.symbol||o.symbol,address:_?.asset?.address||""},amount:Ne,txHash:Ye.txHash||"",success:Ye.status==="success",error:Ye.status==="failed"?Ye.error:void 0}]:void 0;return a(Hn,{isOpen:e,onClose:t,title:Kt,subtitle:gn,styles:C,dark:B,footerLinkText:"Spicenet accounts \u2192",closeOnBackdropClick:n,children:g("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[E&&a("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:a(Ss,{onClick:E,color:M,fontFamily:L})}),!it&&a("div",{style:{marginBottom:"12px"},children:a(Ao,{assets:we,selectedAsset:_??void 0,onAssetSelect:ve,onAmountChange:()=>{},label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:_?.asset?Xe?Je?"...":$e?`~${parseFloat(ct($e.amountIn,_.asset.decimals)).toFixed(6)}`:void 0:Ne??void 0:void 0,dark:B,theme:pe,styles:C})}),a(ya,{variant:"pay",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:M,fontFamily:L,textPrimary:j,textSecondary:z,cardBg:P,cardBorder:O,dk:U,dark:B,isQuoting:Je,quoteError:$t,estimatedOutput:Nn,paymentAmount:Ne,needsSwap:Xe,exactOutputSwap:$e,adjustable:y==="adjustable",maxAmount:k,onAmountChange:It}),_e&&a(Lo,{fontFamily:L,textPrimary:j,textSecondary:z,cardBg:P,cardBorder:O,resolvedDark:B,darkCardBorder:U.cardBorder,primaryColor:M,feePreview:xt,isLoading:bt,errorText:qt,directExecutionFeeNote:mt}),At&&a(co,{variant:"error",palette:W,fontFamily:L,style:{marginBottom:"12px"},children:At}),a(Bt,{variant:"outline",fullWidth:!0,onClick:ue,disabled:!je,loading:ut,dark:B,styles:{...C,button:{...C?.button,backgroundColor:M}},children:mn}),Ye&&yt&&a("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:B?U.shell:"white",borderRadius:B?"12px":"6px",padding:"16px 0"},children:a(Ms,{type:"payment",isOpen:Ye.status!=="processing",isProcessing:ut||Ye.status==="processing",closeOnComplete:!1,chainName:ln(N),explorerUrl:ro(N,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{pt(!1),Jt(null),ue()},onNewTx:Se,onClose:()=>{pt(!1),Jt(null)},onComplete:Se,results:Ce,styles:C,dark:B})})]})})}return a(Hn,{isOpen:e,onClose:t,title:Kt,subtitle:gn,dark:B,styles:C,theme:A,closeOnBackdropClick:n,children:g("div",{style:{padding:"24px 24px 5px 24px",position:"relative"},children:[a("div",{style:{marginBottom:"16px"},children:a(Ao,{assets:we,selectedAsset:_||void 0,onAssetSelect:ve,onAmountChange:Ve,disabled:ut||De==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:pe,styles:C,dark:D,resolveMaxAmount:$,maxAmount:ee>0?lo(ee,_?.asset.decimals??o.decimals):void 0})}),_?.asset&&!ze&&a(ya,{variant:"supply",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:M,fontFamily:L,textPrimary:j,textSecondary:z,cardBg:P,cardBorder:O,dark:B,isQuoting:Je,quoteError:$t,estimatedOutput:Nn}),_e&&a(Lo,{fontFamily:L,textPrimary:j,textSecondary:z,cardBg:P,cardBorder:O,resolvedDark:B,darkCardBorder:U.cardBorder,primaryColor:M,feePreview:xt,isLoading:bt,errorText:qt,directExecutionFeeNote:mt}),De!=="idle"&&g("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:De==="success"?P:De==="error"?W.errorBg:P,border:`1px solid ${De==="success"?O:De==="error"?W.errorBorder:O}`},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[De==="success"?a("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:a("path",{d:"M5 13l4 4L19 7",stroke:W.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):De==="error"?a("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:a("path",{d:"M18 6L6 18M6 6l12 12",stroke:W.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):a(qn,{size:14,color:M}),a("span",{style:{fontSize:"13px",fontWeight:500,color:De==="success"?j:De==="error"?W.errorText:j,fontFamily:L,flex:1},children:De==="success"?"Deposit confirmed":De==="error"?sn||"Transaction failed":Ta[De]||sn}),De==="success"&&Vt&&a("a",{href:`${Cn}/tx/${Vt}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:M,fontFamily:L,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),De==="error"&&a("button",{onClick:()=>{pn("idle"),Xt(null),setTimeout(qe,50)},style:{background:"none",border:"none",fontSize:"12px",color:M,fontFamily:L,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),Bn>=0&&De!=="success"&&De!=="error"&&a("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${z}22`,overflow:"hidden"},children:a("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:M,transformOrigin:"left center",transform:`scaleX(${(Bn+1)/Ma.length})`,transition:"transform 400ms ease"}})})]}),Nt&&De==="idle"&&a(co,{variant:"error",palette:W,fontFamily:L,style:{marginBottom:"16px"},children:Nt}),a(Bt,{variant:"outline",fullWidth:!0,disabled:St,onClick:xe,theme:A,dark:B,styles:{...C,button:{...C?.button,backgroundColor:M}},style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:q},children:Tn})]})})},ed=e=>a(Ra,{isOpen:e.isOpen,onClose:e.onClose,closeOnBackdropClick:e.closeOnBackdropClick,amountDirection:"output",destinationToken:{address:e.paymentTokenAddress,symbol:e.paymentTokenSymbol,decimals:e.paymentTokenDecimals,chainId:e.paymentChainId,logoURI:e.paymentTokenLogoURI},buildActionCalls:e.buildActionCalls,buildSpicenetBatch:e.buildSpicenetBatch,actionLabel:e.ctaLabel||"PAY",paymentAmount:e.paymentAmount,amountInputMode:e.amountInputMode,minPaymentAmount:e.minPaymentAmount,maxPaymentAmount:e.maxPaymentAmount,onAmountChange:e.onAmountChange,title:e.title,subtitle:e.subtitle,onAddFunds:e.onAddFunds,styles:e.styles,dark:e.dark,onSuccess:e.onPaymentSuccess,onError:e.onPaymentError}),td=({label:e="Export Wallet",style:t,className:n,onExport:o,onError:s})=>{const[r,i]=R(!1),[c,d]=R(!1),{primaryColor:l}=lt(),p=Zt(Ht),{isAuthenticated:u}=Mn();let f=null;try{f=ui()}catch{}let h=null,m=null;try{h=fi(),m=hi()}catch{h=null,m=null}const y=Za(m),x=ce(async()=>{if(!u){s?.("User is not authenticated. Please log in first.");return}try{if(p?.provider==="dynamic"){if(!h||!y){s?.("Dynamic is not available. Ensure the app is wrapped in a DynamicContextProvider.");return}await h.initExportProcess(!1),o?.();return}if(!f){s?.("Privy is not available. Ensure the app is wrapped in a PrivyProvider.");return}await f.exportWallet(),o?.()}catch(C){const v=C instanceof Error?C.message:"Failed to export wallet";console.error("Export wallet error:",C),s?.(v)}},[y,h,u,s,o,f,p?.provider]),k=!u,w={padding:"10px 20px",borderRadius:"8px",fontFamily:'"IBM Plex Mono", monospace',fontSize:"14px",fontWeight:500,letterSpacing:"0.4px",textTransform:"uppercase",cursor:k?"not-allowed":"pointer",opacity:k?.5:1,border:"1px solid #0e0d0b",color:"#0e0d0b",backgroundColor:c?`${l}cc`:r?`${l}ee`:l,transition:"background-color 150ms ease, transform 150ms ease",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"8px",...t};return g("button",{onClick:x,onMouseEnter:()=>i(!0),onMouseLeave:()=>{i(!1),d(!1)},onMouseDown:()=>d(!0),onMouseUp:()=>d(!1),disabled:k,className:n,style:w,children:[g("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),a("polyline",{points:"17 8 12 3 7 8"}),a("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]}),e]})};function Da(e){const t=Zt(Ht),n=Rn(),o=e?.enabled===!1?void 0:n,s=t?.network?{network:t.network,pollIntervalMs:e?.pollIntervalMs,chainIds:e?.chainIds??t.supportedChainIds,discoverWalletBalances:e?.discoverWalletBalances}:void 0;return{...Tr(o,s),embeddedWalletAddress:n}}var nd="data:image/svg+xml,%3csvg width='11' height='11' viewBox='0 0 24 24' fill='none' stroke='black' stroke-opacity='0.5' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' xmlns='http://www.w3.org/2000/svg'%3e%3cpolyline points='17 1 21 5 17 9' /%3e%3cpath d='M3 11V9a4 4 0 0 1 4-4h14' /%3e%3cpolyline points='7 23 3 19 7 15' /%3e%3cpath d='M21 13v2a4 4 0 0 1-4 4H3' /%3e%3c/svg%3e";const od=({appName:e,status:t,statusLabel:n,totalUsdValue:o,breakdownSubtitle:s,address:r,dk:i,dark:c=!1,showModeToggle:d,isEmbeddedMode:l=!0,onModeToggle:p})=>{const[u,f]=R(!1),h=async()=>{r&&await Ii(r)&&(f(!0),setTimeout(()=>f(!1),2e3))},m=t==="active",y=n||(m?"Active":"Inactive"),x=m?"#10b981":"#9ca3af",k=g("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[g("div",{children:[a("strong",{children:"Embedded:"})," Deposit assets into ",e," account and use them here."]}),g("div",{children:[a("strong",{children:"External:"})," Use assets from your connected wallet here."]})]});return g("div",{children:[g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[g("div",{style:{fontSize:"13px",fontWeight:600,color:i.textPrimary},children:[e," Account"]}),d?g("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[g("button",{onClick:p,style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:c?i.hoverBg:"#f3f4f6",border:c?`1px solid ${i.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"11px",fontWeight:600,fontFamily:'"IBM Plex Mono", monospace',color:i.textSecondary,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease",letterSpacing:"0.02em"},children:[a("span",{children:l?"Embedded":"External"}),a("img",{src:nd,alt:"","aria-hidden":"true",style:{width:"11px",height:"11px",display:"block",...c?{filter:"invert(0.65)"}:{}}})]}),a(kr,{content:k,label:"Account mode info",textColor:c?i.textPrimary:"#f9fafb",backgroundColor:c?i.cardBg:"#111827",borderColor:c?i.cardBorder:"rgba(255,255,255,0.08)",accentColor:c?i.textSecondary:"#6b7280",children:a("img",{src:Bs,alt:"","aria-hidden":"true",style:{width:"12px",height:"12px",display:"block",...c?{filter:"invert(0.65)"}:{}}})})]}):g("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:c?i.hoverBg:m?"#ecfdf5":"#f3f4f6",border:c?`1px solid ${i.cardBorder}`:m?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[a("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:x}}),a("span",{style:{fontSize:"11px",fontWeight:500,color:c?i.textSecondary:m?"#065f46":"#6b7280"},children:y})]})]}),a("div",{style:{fontSize:"28px",fontWeight:700,color:i.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:ao(o)}),s&&a("div",{style:{fontSize:"12px",color:i.textSecondary,marginBottom:"8px"},children:s}),r&&g("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[a("span",{style:{fontSize:"12px",fontFamily:'"IBM Plex Mono", monospace',color:c?i.textSecondary:"#9ca3af"},children:hr(r)}),a("button",{onClick:h,style:{padding:"2px 6px",fontSize:"10px",fontWeight:500,backgroundColor:"transparent",color:c?i.textSecondary:"#9ca3af",border:"none",cursor:"pointer",borderRadius:"4px",transition:"background-color 150ms ease, color 150ms ease"},title:"Copy address",children:u?"Copied":"Copy"})]})]})},sd=({pendingDeposits:e,onCompleteDeposit:t,dk:n,dark:o=!1})=>e.length===0?null:g("div",{children:[a("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:"Pending Deposits"}),a("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((s,r)=>{const i=Be(s.chainId)?.displayName||`Chain ${s.chainId}`;return g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:o?n.warningBg:"#fffbeb",border:o?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"8px"},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[a("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:o?n.hoverBg:"#fde68a",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:n.warningText},children:s.tokenSymbol.charAt(0)}),g("div",{children:[g("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:[s.amount," ",s.tokenSymbol]}),g("div",{style:{fontSize:"11px",color:n.warningText},children:["on ",i]})]})]}),a("button",{onClick:()=>t?.(s),style:{padding:"4px 12px",fontSize:"11px",fontWeight:600,backgroundColor:o?n.hoverBg:"#fef3c7",color:o?n.textPrimary:"#92400e",border:o?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"9999px",cursor:"pointer",transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease"},children:"Complete"})]},`${s.tokenAddress}-${s.chainId}-${r}`)})})]}),rd=({spiceAssets:e,loading:t,dk:n,dark:o=!1})=>{const s={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},r={backgroundColor:n.cardBg,border:o?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return t?g("div",{children:[a("div",{style:s,children:"Idle Balances"}),[1,2].map(i=>a("div",{style:{...r,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},i))]}):e.length===0?g("div",{children:[a("div",{style:s,children:"Idle Balances"}),a("div",{style:{...r,padding:"16px",textAlign:"center",fontSize:"13px",color:o?n.textSecondary:"#9ca3af"},children:"No assets yet. Deposit to get started."})]}):g("div",{children:[a("div",{style:s,children:"Idle Balances"}),a("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((i,c)=>{const d=Be(i.chainId),l=i.chainDisplayName||d?.displayName||`Chain ${i.chainId}`,p=i.tokenDisplaySymbol||i.tokenDisplayName||i.tokenSymbol;return g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...r},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[i.logoURI?a("img",{src:i.logoURI,alt:i.tokenSymbol,style:{width:"24px",height:"24px",borderRadius:"50%"}}):a("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:o?n.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:n.textSecondary},children:p.charAt(0)}),g("div",{children:[a("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:p}),a("div",{style:{fontSize:"11px",color:o?n.textSecondary:"#9ca3af"},children:l})]})]}),g("div",{style:{textAlign:"right"},children:[a("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:Zn(i.balanceFormatted)}),a("div",{style:{fontSize:"11px",color:o?n.textSecondary:"#9ca3af"},children:ao(i.usdValue)})]})]},`${i.tokenAddress}-${i.chainId}-${c}`)})})]})},ad=({section:e,dk:t,dark:n=!1})=>{const o=s=>{switch(s){case"green":return"#10b981";case"red":return"#ef4444";default:return t.textPrimary}};return g("div",{children:[a("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:t.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:e.title}),a("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.items.map((s,r)=>g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:t.cardBg,border:n?`1px solid ${t.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.tokenLogoURI?a("img",{src:s.tokenLogoURI,alt:s.tokenSymbol,style:{width:"20px",height:"20px",borderRadius:"50%"}}):a("div",{style:{width:"20px",height:"20px",borderRadius:"50%",backgroundColor:n?t.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",fontWeight:600,color:t.textSecondary},children:s.tokenSymbol.charAt(0)}),g("div",{children:[a("div",{style:{fontSize:"13px",fontWeight:500,color:t.textPrimary},children:s.tokenSymbol}),a("div",{style:{fontSize:"11px",color:t.textSecondary},children:s.label})]})]}),a("div",{style:{fontSize:"13px",fontWeight:600,color:o(s.valueColor)},children:s.displayValue})]},r))})]})},id=({onDepositClick:e,onWithdrawClick:t,depositDisabled:n=!1,withdrawDisabled:o=!1,primaryColor:s="#EA4B4B",dark:r=!1})=>!e&&!t?null:g("div",{style:{display:"flex",gap:"8px"},children:[e&&a(Bt,{variant:"outline",onClick:e,disabled:n,dark:r,styles:{button:{backgroundColor:s}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&a(Bt,{variant:"outline",onClick:t,disabled:o,dark:r,styles:{button:{backgroundColor:s}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),ld=({appName:e,status:t,statusLabel:n,totalUsdValue:o,breakdownSubtitle:s,address:r,spiceAssets:i,spiceAssetsLoading:c,pendingDeposits:d,customSections:l,notice:p,onDepositClick:u,onWithdrawClick:f,onCompleteDeposit:h,primaryColor:m,dk:y,dark:x=!1,showModeToggle:k,isEmbeddedMode:w,onModeToggle:C,showConnectExternalCta:v,onConnectExternalWallet:b,connectExternalError:S,showHowItWorks:E=!0})=>{const[F,T]=R(!1);return g("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[a(od,{appName:e,status:t,statusLabel:n,totalUsdValue:o,breakdownSubtitle:s,address:r,dk:y,dark:x,showModeToggle:k,isEmbeddedMode:w,onModeToggle:C}),p&&a("div",{style:{padding:"10px 12px",borderRadius:"8px",backgroundColor:p.tone==="warning"?x?"rgba(245, 158, 11, 0.12)":"#fffbeb":p.tone==="success"?x?"rgba(16, 185, 129, 0.12)":"#ecfdf5":y.cardBg,border:p.tone==="warning"?x?"1px solid rgba(245, 158, 11, 0.35)":"1px solid #fde68a":p.tone==="success"?x?"1px solid rgba(16, 185, 129, 0.35)":"1px solid #a7f3d0":x?`1px solid ${y.cardBorder}`:"1px solid #e5e7eb",color:p.tone==="warning"?x?"#fbbf24":"#92400e":p.tone==="success"?x?"#34d399":"#047857":y.textSecondary,fontSize:"12px",lineHeight:1.45,fontWeight:500},children:p.message}),v&&g("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[a("button",{onClick:b,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:m||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:'"Helvetica Neue", sans-serif',transition:"opacity 150ms ease"},children:"Connect External Wallet"}),S&&a("span",{style:{fontSize:"11px",color:x?y.errorText:"#b91c1c",lineHeight:1.4},children:S})]}),a("div",{style:{height:"1px",backgroundColor:x?"#2d2d2d":"#e5e7eb"}}),a(id,{onDepositClick:u,onWithdrawClick:f,primaryColor:m,dark:x}),E&&g("div",{children:[g("button",{onClick:()=>T(!F),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:y.cardBg,border:x?`1px solid ${y.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:y.textSecondary,fontSize:"12px",fontWeight:500},children:[a("span",{children:"How It Works"}),a("span",{style:{transform:F?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),F&&g("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:x?y.cardBg:"#f0fdf4",border:x?`1px solid ${y.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:x?y.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),a(sd,{pendingDeposits:d,onCompleteDeposit:h,dk:y,dark:x}),a(rd,{spiceAssets:i,loading:c,dk:y,dark:x}),l.map((I,A)=>a(ad,{section:I,dk:y,dark:x},A))]})},Gs=380,so=8;function Wa(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function cd(e,t){const n=new Map;Object.entries(t).forEach(([s,r])=>{if(!Number.isFinite(r)||r<=0)return;n.set(s,r),n.set(s.toUpperCase(),r);const i=Wa(s);i&&n.set(i,r)});const o=[e.symbol,e.displaySymbol,e.receiptTokenName,e.name,e.displayName];for(const s of o){if(!s)continue;const r=n.get(s)??n.get(s.toUpperCase());if(r!==void 0)return r;const i=Wa(s);if(!i)continue;const c=n.get(i);if(c!==void 0)return c}return 0}const dd=({appName:e="Spice",status:t="active",statusLabel:n,customSections:o=[],extraAssets:s=[],tokenPrices:r={},breakdownLabels:i=[],notice:c,styles:d,dark:l=!1,onDepositSuccess:p,onDepositClick:u,onWithdrawClick:f,onCompleteDeposit:h,showModeToggle:m=!1,defaultMode:y})=>{const x=Zt(Ht),k=x?.mode!=="7702",w=!!x?.isWhitelistGateActive,C=ie(!1);Z(()=>{if(!C.current){if(Ga()){C.current=!0;return}y&&x?.setMode&&(x.setMode(y==="non7702"?"ondemand":"7702"),C.current=!0)}},[x,y]);const[v,b]=R(!1),[S,E]=R(null),[F,T]=R({top:0,bottom:0,left:0,placement:"below"}),I=ie(null),A=ie(null),{address:B,isConnected:M}=Mn(),U=Rn(),{externalAddress:W,embeddedAddress:L}=_n(),{dark:q,primaryColor:D,dk:P}=lt(d,l),O=k&&!W,j=!k||O,z=j?U||L:B,J=re(()=>x?.supportedChainIds??Ro("mainnet"),[x?.supportedChainIds]),{assets:pe,loading:N}=Eo({address:z,supportedChains:J,enabled:!!z&&j,refetchInterval:3e4}),ae=re(()=>{const G=j?pe.map(we=>{const _=we.balanceUsd||0,Ze=Number.isFinite(we.balanceFormatted)?we.balanceFormatted:0,Rt=_>0?_:cd(we,r)*Ze;return{tokenAddress:we.address,tokenSymbol:we.symbol,tokenDisplaySymbol:Cs(we),tokenDisplayName:Ti(we),tokenDecimals:we.decimals,chainId:we.chainId,chainDisplayName:ks(we),balance:we.balance.toString(),balanceFormatted:we.balanceFormatted,usdValue:Rt,logoURI:we.logoURI}}):[],We=O?[]:s;return[...G,...We].filter(we=>we.balanceFormatted>0)},[j,O,pe,r,s]),le=re(()=>ae.reduce((G,We)=>G+We.usdValue,0),[ae]),{pendingDeposits:ge}=Da({chainIds:J,enabled:!!B,discoverWalletBalances:!0}),Re=re(()=>o.reduce((G,We)=>G+We.totalValue,0),[o]),de=le+Re,ke=re(()=>{const G=[];le>0&&G.push(`${ao(le)} idle`);for(const We of o){const we=i.find(_=>_.sectionTitle===We.title)?.label||We.title.toLowerCase();G.push(`${ao(We.totalValue)} ${we}`)}return G.join(" \xB7 ")},[le,o,i]),H=ce(G=>{h?h(G):E(G)},[h]),oe=ce(()=>{E(null)},[]),X=ce(()=>{E(null),p?.()},[p]),se=ce(()=>{if(!I.current)return;const G=I.current.getBoundingClientRect(),We=window.innerHeight-G.bottom-so,we=G.top-so,_=We>=400||We>=we?"below":"above",Ze=Math.max(so,Math.min(G.right-Gs,window.innerWidth-Gs-so)),Rt=_==="below"?G.bottom+so:G.top-so,un=_==="above"?window.innerHeight-Rt:0;T({top:Rt,bottom:un,left:Ze,placement:_})},[]);_s(()=>{v&&se()},[v,se]),Z(()=>{if(!v)return;const G=_=>{I.current&&!I.current.contains(_.target)&&A.current&&!A.current.contains(_.target)&&b(!1)},We=_=>{_.key==="Escape"&&b(!1)},we=()=>se();return document.addEventListener("mousedown",G),document.addEventListener("keydown",We),window.addEventListener("scroll",we,{passive:!0}),window.addEventListener("resize",se),()=>{document.removeEventListener("mousedown",G),document.removeEventListener("keydown",We),window.removeEventListener("scroll",we),window.removeEventListener("resize",se)}},[v,se]);const fe=j?U||L||B:W||B,Ee=ce(()=>{x?.setMode&&x.setMode(j?"ondemand":"7702")},[x,j]),[be,V]=R(null);let Q=null;try{Q=lr({onSuccess:()=>V(null),onError:G=>V(In(G,"Failed to connect wallet."))}).connectWallet}catch{Q=null}const he=ce(()=>{Q&&(b(!1),V(null),Q({walletChainType:"ethereum-only"}))},[Q]),Le=!W&&!!Q,kt=ce(()=>{b(!1),u?.()},[u]),zt=ce(()=>{b(!1),f?.()},[f]),Ot=ce(G=>{b(!1),H(G)},[H]);if(typeof window>"u")return null;const st=g("button",{ref:I,onClick:()=>b(!v),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:q?P.hoverBg:"#ffffff",border:q?`1px solid ${P.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:'"Helvetica Neue", sans-serif',color:q?P.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:q?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[g("span",{children:[e," Account"]}),M&&g("span",{style:{color:q?P.textSecondary:"#6b7280"},children:["\xB7 ",ao(de)]}),a("span",{style:{fontSize:"10px",color:q?P.textSecondary:"#9ca3af",transform:v?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),rt=v?cr.createPortal(g(nn,{children:[a("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:Kn.popover},onClick:()=>b(!1)}),a("div",{ref:A,style:{position:"fixed",top:F.placement==="below"?`${F.top}px`:"auto",bottom:F.placement==="above"?`${F.bottom}px`:"auto",left:`${F.left}px`,width:`${Gs}px`,maxWidth:`calc(100vw - ${so*2}px)`,maxHeight:"80vh",backgroundColor:q?P.shell:"#ffffff",border:q?`1px solid ${P.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:q?"0 10px 40px rgba(0, 0, 0, 0.5)":"0 10px 40px rgba(0, 0, 0, 0.12)",zIndex:Kn.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${Lt.out}`},children:a(ld,{appName:e,status:t,statusLabel:n,totalUsdValue:de,breakdownSubtitle:ke,address:j?fe:B,spiceAssets:ae,spiceAssetsLoading:N,pendingDeposits:ge,customSections:o,notice:c,onDepositClick:u?kt:void 0,onWithdrawClick:f?zt:void 0,onCompleteDeposit:Ot,primaryColor:D,dk:P,dark:q,showModeToggle:m,isEmbeddedMode:j,onModeToggle:Ee,showConnectExternalCta:Le,onConnectExternalWallet:he,connectExternalError:be,showHowItWorks:!w})}),a("style",{children:`
103
+ `})]})},mc="0xa9059cbb";function gc(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const o=Me(n.token),s=Me(n.to),r=`${o.toLowerCase()}:${s.toLowerCase()}`,i=t.get(r);i?i.amount+=n.amount:t.set(r,{token:o,to:s,amount:n.amount})}return[...t.values()]}function yc(e,t){return`0x${t}${e.slice(4)}`}function xc(e,t,n){if(!Array.isArray(e))return 0n;const o=`evm:${t}:${n.slice(2).toLowerCase()}`;let s=0n;for(const r of e){if(!r||typeof r!="object")continue;const i=r,c=i.chainTokens;if((Array.isArray(c)?c.filter(d=>typeof d=="string"):c&&typeof c=="object"?Object.keys(c):[]).some(d=>d.toLowerCase()===o))try{s+=BigInt(i.balanceAvailable??"0")}catch{}}return s}async function la(e,t,n,o){const s=await fetch(`${e}/wallets/${t}/balance`,{cache:"no-store"});if(!s.ok)throw new Error(`Failed to fetch spice balance: ${s.status}`);const r=await s.json();return xc(r?.balances,n,o)}async function bc({apiBaseUrl:e,user:t,chainId:n,tokenAddress:o,prevBalance:s,timeoutMs:r=3e4,pollIntervalMs:i=1500}){const c=Date.now()+r;for(await new Promise(d=>setTimeout(d,800));Date.now()<c;){try{if(await la(e,t,n,o)>s)return}catch(d){console.warn("[SpiceLockModal] spice balance poll failed:",d?.message)}await new Promise(d=>setTimeout(d,i))}console.warn("[SpiceLockModal] Spicenet indexer did not reflect deposit within timeout; proceeding with intent")}function Hs(e,t){return js(e,t)}function js(e,t,n){const o=wc(t,e),s=Math.floor(Date.now()/1e3)+60*10,r=Un(o);return{user:e,...n?{chainAuthorizations:n}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:"0x00",nbf:0,exp:s,chainBatches:r.map((i,c)=>({hash:i.hash,chainId:i.chainId,tokenTransfers:o[c].domain==="spicenet"?[]:o[c].tokenTransfers??[],calls:i.calls}))}]}}function wc(e,t){return e.map(n=>{if(n.domain==="spicenet"||n.calls.length===0)return n;const o=new Set((n.tokenTransfers??[]).filter(r=>(r.from==="escrow"||r.from==="solver")&&Me(r.to).toLowerCase()===t.toLowerCase()).map(r=>Me(r.token).toLowerCase()));if(o.size===0)return n;let s=0;for(const r of n.calls){if(!r.data?.startsWith(mc))break;try{const i=Co({abi:Ke,data:r.data});if(i.functionName!=="transfer")break;const[c]=i.args;if(c.toLowerCase()===t.toLowerCase()||!o.has(Me(r.to).toLowerCase()))break;s+=1}catch{break}}return s===0?n:{...n,calls:n.calls.slice(s)}})}function dn(e,t,n,o){if(e.some(l=>l.domain==="spicenet"))return e;const s=n?.intents.flatMap(l=>l.batches),r=l=>l.from==="escrow",i=e.map(l=>{const p=s?.find(C=>C.chainId===l.chainId);if(!p)return l;const u=Fn(p),f=u.totalFee;if(f<=0n)return l;const h=(l.tokenTransfers??[]).find(C=>r(C)&&Me(C.to).toLowerCase()===t.toLowerCase()&&!Ue(Me(C.token)));if(!h)return l;const m=Me(h.token);let y=!1;const x=(l.tokenTransfers??[]).map(C=>y||!r(C)||Me(C.to).toLowerCase()!==t.toLowerCase()||Me(C.token).toLowerCase()!==m.toLowerCase()?C:(y=!0,{...C,amount:o?.payoutAlreadyGross?BigInt(C.amount):BigInt(C.amount)+f}));if(!y)return l;const k=[];u.spicenetFee>0n&&k.push({to:m,value:0n,data:gt({abi:Ke,functionName:"transfer",args:[xo,u.spicenetFee]})});const w=u.gasFee+u.bridgeFee;return w>0n&&k.push({to:m,value:0n,data:gt({abi:Ke,functionName:"transfer",args:[Dn,w]})}),{...l,tokenTransfers:x,calls:[...k,...l.calls]}}),c=i.flatMap(l=>(l.tokenTransfers??[]).filter(r).map(p=>{const u=Me(p.token),f=Me(p.to),h=[{token:u,to:f,amount:BigInt(p.amount)}];return{chainId:l.chainId,transfers:gc(h)}}));if(c.length===0)return e;const d=BigInt(Math.floor(Date.now()/1e3))+3600n;return[{chainId:si,domain:"spicenet",tokenTransfers:[],calls:c.map((l,p)=>{const u=bo(wo([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,l.transfers[0].token,l.transfers.reduce((h,m)=>h+m.amount,0n),BigInt(l.chainId),BigInt(Date.now()+p)])),f=yc(u,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:gt({abi:cs,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${l.chainId}`,idempotenceKey:f,nbf:0n,exp:d,metadata:"{}",transfers:l.transfers.map(h=>({token:h.token.toLowerCase(),to:h.to,amount:h.amount}))}]})}})},...i]}function Qs(e,t){return t?e.some(n=>(n.tokenTransfers??[]).some(o=>o.from==="escrow"&&BigInt(o.amount)>=t.grossAmount)):!1}function Vs(e){const t=e.selectedAsset?.asset,n=e.selectedAsset?.amount;if(!(!t||!n))return Qe(n,t.decimals)}function Jn(e,t){const n=e.selectedAsset?.asset;if(!n||!e.selectedAsset?.amount)throw new Error("Select an asset and enter an amount");const o=Qe(e.selectedAsset.amount,n.decimals),s=t?.grossAmount??o;return e.resolveLockBatches({amount:e.selectedAsset.amount,amountWei:o,grossAmount:ct(s,n.decimals),grossAmountWei:s})}async function qs(e,t,n){const o=[...new Set(n.filter(r=>r.domain!=="spicenet").map(r=>r.chainId))],s=[];for(const r of o){const i=dt(r),c=mo(r),d=await ls(t,i),l=await e.actions.signAuthorization({contractAddress:c,chainId:r,nonce:Number(d)});s.push(l)}return s}async function ca(e,t,n){const o=e.isSemi7702&&e.providerEmbeddedAddress||e.address;if(!e.isConnected||!o)throw new Error("Please connect your wallet to continue");if(t.length===0)throw new Error("No lock batches configured");if(!e.ready||!e.authenticated)throw new Error(`Please authenticate with ${e.provider||"wallet provider"} to continue`);const s=n??await qs(e,o,t),r=Un(t),i=Math.floor(Date.now()/1e3)+60*10,c=r.map(h=>h.hash),d=bo(wo([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,BigInt(i),c])),l=await e.actions.signMessage({raw:d}),p=typeof l=="string"?l:l.signature;if(!p)throw new Error("Failed to sign intent authorization");const u={mode:"7702",signatureType:"ecdsa",signature:p,nbf:0,exp:i,chainBatches:r.map((h,m)=>{const y=t[m],x=y.domain==="spicenet";return{hash:h.hash,chainId:h.chainId,tokenTransfers:x?[]:y.tokenTransfers??[],calls:h.calls}})},f=await ot.createAction({user:o,chainAuthorizations:s.map(h=>({r:h.r,s:h.s,yParity:h.yParity,address:h.address,chainId:Number(h.chainId),nonce:Number(h.nonce)})),intents:[u]});if(f){const h=ss(t,ln),[m,y]=f.intentIds[0].split("/"),x=parseInt(y||"0",10),k=f.intentIds[0];e.startStatusPolling(f.intentIds[0],h),await Qr({actionId:m,intentIndex:x,intentId:k,totalSteps:t.length,isSpicenetStep:w=>t[w]?.domain==="spicenet",maxExecuteAttemptsForStep:w=>t[w]?.domain==="spicenet"?6:3,maxPolls:180})}}async function da(e){let t=Jn(e);if(t.length===0)throw new Error("No lock batches configured");const n=e.isSemi7702&&e.providerEmbeddedAddress||e.address;if(!e.isConnected||!n)throw new Error("Please connect your wallet to continue");const o=await qs(e,n,t);let s=dn([...t],n),r;for(let i=0;i<4;i+=1){const c=await ot.estimateActionFees(js(n,s,o.map(u=>({r:u.r,s:u.s,yParity:u.yParity,address:u.address,chainId:Number(u.chainId),nonce:Number(u.nonce)})))),d=Fo(c,{symbol:e.selectedAsset?.asset.symbol??"",decimals:e.selectedAsset?.asset.decimals??18,actionAmount:Vs(e)});if(!d)break;const l={grossAmount:d.grossAmount,netAmount:d.netAmount,feeAmount:d.totalFee??0n},p=r?.grossAmount===l.grossAmount&&r?.netAmount===l.netAmount&&r?.feeAmount===l.feeAmount;if(r=l,t=Jn(e,r),s=dn([...t],n,c,{payoutAlreadyGross:Qs(t,r)}),p)break}await ca(e,s,o)}async function Cc(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");if(!e.address||!e.embeddedWalletAddress)throw new Error("Embedded wallet not connected");const t=e.selectedAsset.asset,n=Qe(e.selectedAsset.amount,t.decimals),o=e.escrowAddress||mo(e.lockChainId),s=ot.getBaseUrl(),r=Tt(t.address);let i=0n;try{i=await la(s,e.embeddedWalletAddress,e.lockChainId,r)}catch(u){console.warn("[SpiceLockModal] could not snapshot spice balance pre-deposit:",u?.message)}const c=await e.actions.getEthereumProvider();await Yn(c,e.lockChainId);const d=Be(e.lockChainId),l=Ln({account:e.embeddedWalletAddress,transport:zn(c),chain:d?.viemChain});let p;if(t.isNative||Ue(t.address))p=await l.sendTransaction({to:o,value:n,chain:d?.viemChain});else{const u=gt({abi:Ke,functionName:"transfer",args:[o,n]});p=await l.sendTransaction({to:t.address,data:u,chain:d?.viemChain})}if((await dt(e.lockChainId).waitForTransactionReceipt({hash:p,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to escrow failed");await bc({apiBaseUrl:s,user:e.embeddedWalletAddress,chainId:e.lockChainId,tokenAddress:r,prevBalance:i}),await e.refreshSpiceAssets(),e.refreshWalletAssets(),await da(e)}async function kc(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");if(e.onLockExecute){const S=e.resolveLockBatches();if(S.length===0)throw new Error("No lock batches configured");const E=e.selectedAsset.asset,F=Qe(e.selectedAsset.amount,E.decimals),T=await e.onLockExecute({asset:E,amount:e.selectedAsset.amount,amountWei:F,lockDurationMonths:e.selectedDuration?.months??0,chainBatches:S});T&&e.onLockSuccess?.(T);return}const n=e.resolveLockBatches();if(n.length===0)throw new Error("No lock batches configured");const o=e.selectedAsset.asset,s=Qe(e.selectedAsset.amount,o.decimals),r=o.chainId,i=e.escrowAddress||An(r),c=Tt(o.address),d=o.isNative||Ue(c),l=n.some(S=>S.tokenTransfers?.some(E=>E.from==="escrow")),p=S=>({chainId:r,calls:d?[{to:i,value:S,data:"0x"}]:[{to:c,value:0n,data:gt({abi:Ke,functionName:"transfer",args:[i,S]})}]}),u=(S,E,F)=>{const T=p(S);if(!l)return[T,...E];const I=dn([...E],t,F,{payoutAlreadyGross:Qs(E,y)});return[T,...I]};let f=Jn(e),h=u(s,f);const m=await qs(e,t,h);let y;if(l)for(let S=0;S<4;S+=1){const E=await ot.estimateActionFees(js(t,h,m.map(A=>({r:A.r,s:A.s,yParity:A.yParity,address:A.address,chainId:Number(A.chainId),nonce:Number(A.nonce)})))),F=Fo(E,{symbol:o.symbol,decimals:o.decimals,actionAmount:s});if(!F)break;const T={grossAmount:F.grossAmount,netAmount:F.netAmount,feeAmount:F.totalFee??0n},I=y?.grossAmount===T.grossAmount&&y?.netAmount===T.netAmount&&y?.feeAmount===T.feeAmount;if(y=T,f=Jn(e,y),h=u(T.grossAmount,f,E),I)break}const x=y?.grossAmount??s,k=await e.externalWallet.getEthereumProvider();let w=null;try{const S=await k.request({method:"eth_chainId"});w=parseInt(S,16)}catch{w=null}w!==r&&await Yn(k,r);const C=Be(r),v=Ln({account:e.externalWalletAddress,chain:C?.viemChain,transport:zn(k)}),b=d?await v.sendTransaction({to:t,value:x,chain:C?.viemChain}):await v.sendTransaction({to:c,data:gt({abi:Ke,functionName:"transfer",args:[t,x]}),chain:C?.viemChain});if((await dt(r).waitForTransactionReceipt({hash:b,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to embedded wallet failed");await ca(e,h,m)}async function vc(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount||!e.requiresRelayerFeeEstimate)return null;if(e.isSemi7702){const i=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!i)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");let c=Jn(e);if(c.length===0)throw new Error("No lock batches configured");const d=e.selectedAsset.asset,l=Qe(e.selectedAsset.amount,d.decimals),p=d.chainId,u=e.escrowAddress||An(p),f=Tt(d.address),h=d.isNative||Ue(f),m=c.some(v=>v.tokenTransfers?.some(b=>b.from==="escrow")),y=v=>({chainId:p,calls:h?[{to:u,value:v,data:"0x"}]:[{to:f,value:0n,data:gt({abi:Ke,functionName:"transfer",args:[u,v]})}]}),x=(v,b,S)=>{const E=y(v);if(!m)return[E,...b];const F=dn([...b],i,S,{payoutAlreadyGross:b.some(T=>(T.tokenTransfers??[]).some(I=>I.from==="escrow"&&BigInt(I.amount)>=v))});return[E,...F]};let k=x(l,c),w=null,C;for(let v=0;v<4;v+=1){const b=await ot.estimateActionFees(Hs(i,k)),S=Fo(b,{symbol:d.symbol,decimals:d.decimals,actionAmount:l});if(!S)return w;const E={grossAmount:S.grossAmount,netAmount:S.netAmount,feeAmount:S.totalFee??0n},F=C?.grossAmount===E.grossAmount&&C?.netAmount===E.netAmount&&C?.feeAmount===E.feeAmount;if(w=S,C=E,c=Jn(e,E),k=x(E.grossAmount,c,b),F)break}return w}const t=e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");let n=Jn(e);if(n.length===0)throw new Error("No lock batches configured");let o=dn([...n],t),s=null;for(let i=0;i<4;i+=1){const c=await ot.estimateActionFees(Hs(t,o)),d=Fo(c,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:Vs(e)});if(!d)return null;const l={grossAmount:d.grossAmount},p=s?.grossAmount===d.grossAmount&&s?.netAmount===d.netAmount&&s?.totalFee===d.totalFee;if(s=d,n=Jn(e,l),o=dn([...n],t,c,{payoutAlreadyGross:Qs(n,l)}),p)break}if(s)return s;const r=await ot.estimateActionFees(Hs(t,o));return Fo(r,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:Vs(e)})}async function Ic(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");const t=e.activeSignerWallet??e.externalWallet,n=e.activeSignerAddress??e.externalWalletAddress;if(!n||!t)throw new Error("Please connect your wallet to continue");const o=e.resolveLockBatches();if(o.length===0)throw new Error("No lock batches configured");const s=o.find(u=>u.chainId===e.lockChainId)||o[0];if(!s)throw new Error("No lock batch for lock chain");const r=await t.getEthereumProvider();let i=null;try{const u=await r.request({method:"eth_chainId"});i=parseInt(u,16)}catch{i=null}i!==e.lockChainId&&await Yn(r,e.lockChainId);const c=Be(e.lockChainId),d=Ln({account:n,chain:c?.viemChain,transport:zn(r)}),l=dt(e.lockChainId);let p;for(const u of s.calls){const f=await d.sendTransaction({to:u.to,data:u.data,value:u.value,chain:c?.viemChain});if((await l.waitForTransactionReceipt({hash:f,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Lock transaction failed");p=f}p&&e.onLockSuccess?.(p)}async function Ac(e){if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance. Add more assets.");return}e.ui.setIsExecuting(!0),e.ui.setError(null);const t=n=>{console.error("[SpiceLockModal] lock failed:",n);const o=In(n,""),s=typeof n?.shortMessage=="string"?n.shortMessage:typeof n?.message=="string"?n.message:"";e.ui.setError(o||s||"Transaction failed. Please try again.")};if(e.isSemi7702){if(e.isSourceDestToken){try{await Ic(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{await kc(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{e.isDirectDeposit&&!e.isSourceDestToken?await Cc(e):await da(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}}const ua=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,lockBatches:o,lockTokenSymbol:s,lockTokenLogoURI:r,destinationInputHook:i,sourceAssetInputHook:c,lockDurationHook:d,lockChainId:l,durationOptions:p,votingPowerEstimate:u,escrowAddress:f,includeWalletAssets:h=!1,destinationTokenAddress:m,onLockSuccess:y,onLockExecute:x,sourceToDestinationConversionRate:k,estimatedOutputAmount:w,onAddFunds:C,buildSpicenetBatch:v,styles:b,dark:S=!1})=>{const{theme:E,dark:F,primaryColor:T,dk:I}=lt(b,S),A=E.typography.fontFamily,B=Zt(Ht),M=B?.mode||"7702",U=!!B?.isWhitelistGateActive,W=M!=="7702",L=re(()=>B?.supportedChainIds??[],[B?.supportedChainIds]),q=re(()=>{if(U)return[];const K=B?.allowedTokens;if(!K||K.length===0)return[];const Ie=new Set(K.map(_e=>_e.toLowerCase())),mt=[],At=new Set;for(const _e of L){const tn=Be(_e);for(const Y of tn?.supportedTokens??[]){if(!Ie.has(Y.symbol.toLowerCase()))continue;const $=`${_e}:${Y.address.toLowerCase()}`;At.has($)||(At.add($),mt.push(Me(Y.address)))}}return mt},[B?.allowedTokens,L,U]),D=F?I.cardBg:b?.assetSelector?.backgroundColor||b?.secondaryBackground||"#e9e9e9",P=F?`1px solid ${I.cardBorder}`:"0.5px solid #A8A8A7",O=F?"12px":"6px",j=F?I.textPrimary:"#111827",z=F?I.textSecondary:"#6b7280",J=re(()=>({...b,assetSelector:{...b?.assetSelector,backgroundColor:F?I.cardBg:b?.assetSelector?.backgroundColor,borderRadius:F?"12px":b?.assetSelector?.borderRadius},secondaryBackground:F?I.cardBg:b?.secondaryBackground}),[b,F]),pe=re(()=>F?{...E,colors:{...E.colors,secondary:I.cardBg,surfaceHover:I.hoverBg,border:I.cardBorder,borderHover:I.inputBorder}}:E,[F,E]),[N,ae]=R(null),[le,ge]=R(0),Re=d?.selectedDurationIdx??le,de=d?.setSelectedDurationIdx??ge,[ke,H]=R(!1),[oe,X]=R(null),[se,fe]=R(null),[Ee,be]=R(!1),[V,Q]=R(!1),[he,Le]=R(null),[kt,zt]=R(!1),Ot=ie(0),[st,rt]=R(!1),[G,We]=R(null);sr(),rs();const{chain:we,address:_}=go();_a();const Ze=ie(we);Z(()=>{Ze.current=we},[we]);const Rt=Mn(),{isReady:un,isAuthenticated:ut,isConnected:on,address:Nt,provider:Xt,actions:De}=Rt,{externalWallet:pn,embeddedAddress:sn,externalAddress:xn,activeWallet:Vt,activeAddress:rn}=_n(),{intentStatus:yt,startStatusPolling:pt,clearStatus:Ye}=Cr({checkStepStatus:(K,Ie)=>ot.checkStepStatus(K,Ie),retryStep:async(K,Ie)=>{const[mt,At]=K.split("/"),_e=parseInt(At||"0",10);await ot.executeStep(mt,_e,Ie,{action:"execute"})},maxRetries:3}),{assets:Jt,refetch:xt}=Eo({address:Nt,supportedChains:L,enabled:e&&on&&!W&&!U,refetchInterval:3e4}),me=re(()=>{if(U)return[];if(q.length===0)return Jt;const K=new Set(q.map(Ie=>Ie.toLowerCase()));return Jt.filter(Ie=>K.has(Ie.address.toLowerCase()))},[Jt,q,U]),bt=Rn(),tt=xn||_,fn=W?rn??tt:bt,ye=re(()=>{if(!h)return[];if(U)return m?[Me(m)]:[];const K=new Set,Ie=[],mt=At=>{if(!At)return;const _e=At.toLowerCase();K.has(_e)||(K.add(_e),Ie.push(Me(At)))};if(m&&mt(m),W)for(const At of q)mt(At);return Ie},[h,W,m,q,U]),qt=re(()=>ye.map(K=>K.toLowerCase()).sort().join(","),[ye]),ft=re(()=>JSON.stringify([...L||[]].sort()),[L]),[Dt,Mt]=R([]),hn=ie(0),Yt=ie(async()=>{}),bn=ce(async()=>{if(!h||!fn||ye.length===0){hn.current++,Mt([]);return}const K=++hn.current,Ie=Me(fn),mt=L&&L.length>0?L:[l],At=ye.map(ue=>{const ne=ue.toLowerCase();if(m&&Ae(ue,m)){const Fe=Be(l)?.supportedTokens?.find(Se=>Ae(Se.address,ne));return{address:ue,chainId:l,configToken:Fe?{decimals:Fe.decimals,symbol:Fe.symbol,name:Fe.name,logo:Fe.logo}:void 0}}for(const Fe of mt){const Se=Be(Fe)?.supportedTokens?.find(Ft=>Ae(Ft.address,ne));if(Se)return{address:ue,chainId:Fe,configToken:{decimals:Se.decimals,symbol:Se.symbol,name:Se.name,logo:Se.logo}}}return{address:ue,chainId:l}}),_e=new Map;for(const ue of At){const ne=_e.get(ue.chainId)||[];ne.push(ue),_e.set(ue.chainId,ne)}const tn=async(ue,ne)=>{try{const Fe=await En(ue,{address:ne.address,abi:Ke,functionName:"balanceOf",args:[Ie]});let Se,Ft,it,je;if(ne.configToken)Se=ne.configToken.decimals,Ft=ne.configToken.symbol,it=ne.configToken.name,je=ne.configToken.logo;else{const[Bn,Tn,mn]=await Promise.all([En(ue,{address:ne.address,abi:Ke,functionName:"decimals",args:[]}).catch(()=>18),En(ue,{address:ne.address,abi:Ke,functionName:"symbol",args:[]}).catch(()=>"TOKEN"),En(ue,{address:ne.address,abi:Ke,functionName:"name",args:[]}).catch(()=>"TOKEN")]);Se=Number(Bn),Ft=Tn,it=mn}const Ct=!!m&&Ae(ne.address,m)&&ne.chainId===l;Ct&&r&&(je=r),Ct&&s&&!ne.configToken&&(Ft==="TOKEN"&&(Ft=s),it==="TOKEN"&&(it=s));const Cn=parseFloat((Number(Fe)/Math.pow(10,Se)).toFixed(6));return{address:ne.address,name:it,symbol:Ft,decimals:Se,balance:Fe,balanceFormatted:Cn,balanceUsd:0,logoURI:je,isNative:!1,chainId:ne.chainId}}catch{return null}},Y=await Promise.all(Array.from(_e.entries()).map(async([ue,ne])=>{let Fe;try{Fe=dt(ue)}catch{return[]}const Se=[],Ft=[];for(const je of ne){const Ct=Se.length;Se.push({address:je.address,abi:Ke,functionName:"balanceOf",args:[Ie]}),je.configToken||Se.push({address:je.address,abi:Ke,functionName:"decimals",args:[]},{address:je.address,abi:Ke,functionName:"symbol",args:[]},{address:je.address,abi:Ke,functionName:"name",args:[]}),Ft.push({start:Ct,item:je})}let it=null;try{it=await Fe.multicall({contracts:Se})}catch{it=null}return it?Ft.map(({start:je,item:Ct})=>{const Cn=it[je],Bn=Cn?.status==="success"?Cn.result:0n;let Tn,mn,xe,St;if(Ct.configToken)Tn=Ct.configToken.decimals,mn=Ct.configToken.symbol,xe=Ct.configToken.name,St=Ct.configToken.logo;else{const Ce=it[je+1],et=it[je+2],kn=it[je+3];Tn=Ce?.status==="success"?Number(Ce.result):18,mn=et?.status==="success"?et.result:"TOKEN",xe=kn?.status==="success"?kn.result:mn}const Kt=!!m&&Ae(Ct.address,m)&&Ct.chainId===l;Kt&&r&&(St=r),Kt&&s&&!Ct.configToken&&(mn==="TOKEN"&&(mn=s),xe==="TOKEN"&&(xe=s));const gn=parseFloat((Number(Bn)/Math.pow(10,Tn)).toFixed(6));return{address:Ct.address,name:xe,symbol:mn,decimals:Tn,balance:Bn,balanceFormatted:gn,balanceUsd:0,logoURI:St,isNative:!1,chainId:Ct.chainId}}):(await Promise.all(ne.map(je=>tn(Fe,je)))).filter(je=>je!==null)}));if(K!==hn.current)return;const $=Y.flat();Mt($)},[h,fn,qt,ft,l,m,r,s]);Z(()=>{Yt.current=bn},[bn]),Z(()=>{if(!e||!h){Mt([]);return}Yt.current();const K=setInterval(()=>{Yt.current()},15e3);return()=>clearInterval(K)},[h,e,fn,qt,ft,l,m]);const wn=ce(()=>{bn()},[bn]),Ne=re(()=>Dt.filter(K=>K.balance>0n),[Dt]),Pt=re(()=>{if(W)return Ne.map(Ie=>({...Ie,_source:"wallet"}));if(!h)return me;const K=[];for(const Ie of Ne)K.push({...Ie,_source:"wallet"});for(const Ie of me)K.push({...Ie,_source:"spice"});return K},[W,h,Ne,me]),Je=re(()=>U?m?Pt.filter(K=>Ae(K.address,m)&&K.chainId===l):[]:Pt,[Pt,U,m,l]),$t=ie(null),Nn=ie(null);Z(()=>{Nn.current=N},[N]),Z(()=>{!U||!N?.asset||m&&Ae(N.asset.address,m)&&N.asset.chainId===l||ae(null)},[U,N?.asset,m,l]),Z(()=>{e||(ae(null),X(null),fe(null),be(!1),Q(!1),Le(null),H(!1),rt(!1),We(null),zt(!1),Ye())},[e,Ye]),Z(()=>{i&&i.assetAmount!==(N?.amount||"")&&ae(K=>K&&{...K,amount:i.assetAmount})},[i?.assetAmount]),Z(()=>{c&&c.assetAmount!==(N?.amount||"")&&ae(K=>K&&{...K,amount:c.assetAmount})},[c?.assetAmount]),Z(()=>{if(!W&&yt?.overallStatus==="success"&&yt.intentId&&$t.current!==yt.intentId&&Nt&&yt.steps.find(K=>K.transactionHash)?.transactionHash){$t.current=yt.intentId;const K=Nn.current;if(!K?.asset||!K.amount||K.asset._source==="wallet"||Qe(K.amount,K.asset.decimals)===0n)return;xt()}},[yt,Nt,l,xt,W]);const Ge=parseFloat(N?.amount||"")||0,$e=re(()=>N?.asset?N.asset._source==="wallet"?N.asset.balanceFormatted??0:me.find(K=>Ae(K.address,N.asset.address)&&K.chainId===N.asset.chainId)?.balanceFormatted??0:0,[N?.asset,me]),Wt=Ge>0&&(he?parseFloat(ct(he.grossAmount,he.decimals))>$e:Ge>$e),vt=d?.selectedDuration??p[Re]??p[0],ze=re(()=>!N?.asset||!m?!1:Ae(N.asset.address,m)&&N.asset.chainId===l,[N?.asset,m,l]),Xe=re(()=>Ge<=0?0:ze?Ge:!k||k<=0?0:Ge/k,[Ge,k,ze]),_t=re(()=>Xe<=0?null:Xe.toLocaleString(void 0,{maximumFractionDigits:2}),[Xe]),Et=u&&Xe>0&&vt?u(Xe,vt.months):void 0,en=re(()=>Ge<=0?"$0.00":ze&&k?(Ge*k).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!k||k<=0?"$0.00":Ge.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[Ge,k,ze]),Oe=re(()=>{if(!_t)return null;const K=parseFloat(_t.replace(/,/g,""));return ze&&k?(K*k).toLocaleString(void 0,{maximumFractionDigits:2}):k?(K*k).toLocaleString(void 0,{maximumFractionDigits:2}):null},[_t,k,ze]),Pn=ce(K=>{ae(Ie=>({asset:K,amount:Ie?.asset?.address===K.address&&Ie?.asset?.chainId===K.chainId&&Ie.amount||""})),X(null),fe(null),Q(!1),Le(null),c?.setSelectedAsset&&c.setSelectedAsset({symbol:K.symbol,address:K.address,decimals:K.decimals,chainId:K.chainId})},[c?.setSelectedAsset]),ee=ce(K=>{ae(Ie=>Ie&&{...Ie,amount:K}),X(null),fe(null),Q(!1),Le(null),i&&i.setAssetAmount(K),c&&c.setAssetAmount(K)},[i,c]),te=ce(K=>{if(typeof o=="function"){if(!N?.asset||!N.amount)throw new Error("Select an asset and enter an amount");return o({asset:N.asset,amount:K?.amount??N.amount,amountWei:K?.amountWei??Qe(N.amount,N.asset.decimals),grossAmount:K?.grossAmount,grossAmountWei:K?.grossAmountWei,feeAdjusted:!!K})}return o},[o,N]),ve=ie(null),Ve=re(()=>!N?.asset||Ge<=0?!1:W?!ze&&!x:!0,[N,Ge,W,ze,x]),It=ce(()=>vc(ve.current),[]),wt=re(()=>!N?.asset||Ge<=0?null:`${N.asset.address.toLowerCase()}:${N.asset.chainId}:${N.amount??""}`,[N?.asset?.address,N?.asset?.chainId,N?.amount,Ge]);Z(()=>{if(!e||ke)return;if(!N?.asset||Ge<=0){fe(null),be(!1),Q(!1),Le(null);return}if(!Ve){fe(null),be(!1),Q(!0),Le(null);return}let K=!1;const Ie=async _e=>{const tn=++Ot.current;_e||(fe(null),Q(!1),be(!0));try{const Y=await It();if(K||Ot.current!==tn)return;fe(null),Q(!0),Le(Y)}catch(Y){if(K||Ot.current!==tn)return;_e||(fe(In(Y,"Unable to calculate fees for this lock.")),Q(!1))}finally{!K&&Ot.current===tn&&!_e&&be(!1)}},mt=window.setTimeout(()=>{Ie(!1)},250),At=window.setInterval(()=>{Ie(!0)},3e4);return()=>{K=!0,clearTimeout(mt),window.clearInterval(At)}},[e,ke,wt,Ve,It]),Z(()=>{if(yt?.overallStatus==="success"){const K=yt.steps.find(Ie=>Ie.transactionHash);y?.(K?.transactionHash)}},[yt?.overallStatus,y]);const ht=h&&N?.asset?._source==="wallet"&&N?.asset?.chainId===l,at=ce(()=>Ac(ve.current),[]),He=!!N?.asset&&Ge>0&&!Wt&&!ke&&(!Ve||V&&!Ee&&!se),nt=oe||se,Pe=g("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[a(As,{color:z}),g("p",{style:{fontSize:"13px",color:z,margin:0,lineHeight:"1.5"},children:["Add ",s," by converting assets from your account"]})]});if(ve.current={selectedAsset:N,parsedAmount:Ge,selectedDuration:vt,isInsufficientBalance:Wt,isSemi7702:W,isSourceDestToken:ze,isDirectDeposit:ht,requiresRelayerFeeEstimate:Ve,address:Nt,embeddedWalletAddress:bt,providerEmbeddedAddress:sn,externalWallet:pn,externalWalletAddress:tt,activeSignerWallet:Vt,activeSignerAddress:rn,isConnected:on,ready:un,authenticated:ut,provider:Xt,actions:De,lockChainId:l,escrowAddress:f,onLockExecute:x,onLockSuccess:y,buildSpicenetBatch:v,resolveLockBatches:te,startStatusPolling:pt,refreshSpiceAssets:xt,refreshWalletAssets:wn,ui:{setError:X,setIsExecuting:H,setShowStatusPanel:zt}},!e)return null;const qe={backgroundColor:D,border:P,borderRadius:O,padding:"16px",marginBottom:"16px"};return a(Hn,{isOpen:e,onClose:t,title:`Add ${s} to your account`,subtitle:Pe,styles:b,dark:F,footerLinkText:"Spicenet accounts \u2192",overlayContent:st?a("div",{}):void 0,closeOnBackdropClick:n,children:g("div",{style:{padding:"0 24px 8px 24px",position:"relative"},children:[g("div",{style:{marginBottom:"12px"},children:[C&&a("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:a(Ss,{onClick:C,color:T,fontFamily:A})}),a("div",{style:{marginTop:"10px",fontSize:"13px",color:z,fontFamily:A},children:a(Ao,{assets:Je,selectedAsset:N??void 0,onAssetSelect:Pn,onAmountChange:ee,label:"Amount",showBalance:!0,showMaxButton:!0,theme:pe,styles:J})}),a("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:z,fontFamily:A},children:en})]}),g("div",{style:qe,children:[g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:F?`1px solid ${I.cardBorder}`:"1px solid #e5e7eb"},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[r?a("img",{src:r,alt:s,style:{width:"32px",height:"32px",borderRadius:"50%",objectFit:"cover"}}):a("div",{style:{width:"32px",height:"32px",borderRadius:"50%",backgroundColor:F?I.inputBg:"#d1d5db",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:700,color:j},children:s.slice(0,2)}),a("span",{style:{fontSize:"16px",fontWeight:600,color:j,fontFamily:A},children:s})]}),g("div",{style:{textAlign:"right"},children:[a("div",{style:{fontSize:"22px",fontWeight:700,color:j,fontFamily:A,lineHeight:1.1},children:_t??"0.00"}),g("div",{style:{fontSize:"12px",color:z,fontFamily:A,marginTop:"2px"},children:["~$",Oe??"0.00"]})]})]}),g("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:F?`1px solid ${I.cardBorder}`:"1px solid #e5e7eb"},children:[g("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[a("span",{style:{fontSize:"15px",fontWeight:500,color:z,fontFamily:A},children:"Lock Duration"}),a(jn,{color:z})]}),a(dc,{options:p,selectedIndex:Re,onSelect:de,primaryColor:T,dark:F,textPrimary:j,textSecondary:z})]}),g("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[a(pc,{durationMonths:vt?.months,fontFamily:A,dark:F,textPrimary:j,textSecondary:z}),u&&a(fc,{votes:Et,fontFamily:A,dark:F,textPrimary:j,textSecondary:z})]})]}),Ve&&a(Lo,{fontFamily:A,textPrimary:j,textSecondary:z,cardBg:D,cardBorder:P,resolvedDark:F,darkCardBorder:I.cardBorder,primaryColor:T,feePreview:he,isLoading:Ee,errorText:se}),nt&&a(co,{variant:"error",palette:I,fontFamily:A,style:{marginBottom:"12px"},children:nt}),a(Bt,{variant:"outline",fullWidth:!0,onClick:at,disabled:!He,loading:ke,dark:F,styles:{...b,button:{...b?.button,backgroundColor:T}},children:ke?ht&&!ze?"DEPOSITING...":ze?"LOCKING...":"CONVERTING...":Ee&&Ve?"CALCULATING FEES...":ht&&!ze?`DEPOSIT ${s}`:ze?`LOCK ${s}`:`CONVERT TO ${s}`}),a(hc,{isOpen:st,data:G,isLocking:ke,lockError:nt,onContinue:at,onClose:()=>rt(!1),primaryColor:T,fontFamily:A,dark:F}),yt&&kt&&a("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:F?"rgba(0, 0, 0, 0.45)":"rgba(255, 255, 255, 0.55)",backdropFilter:"blur(2px)",WebkitBackdropFilter:"blur(2px)",borderRadius:O},children:a(Ms,{type:"deposit",showStepBreakdown:!1,isOpen:!!yt&&yt.overallStatus!=="processing",isProcessing:ke||yt?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{Ye(),zt(!1),at()},onNewTx:()=>{Ye(),zt(!1),ae(null),$t.current=null,xt(),wn()},onClose:()=>{Ye(),zt(!1)},onComplete:()=>{Ye(),zt(!1),ae(null),$t.current=null,xt(),wn()},results:yt?.overallStatus==="success"||yt?.overallStatus==="failed"?yt.steps.map(K=>({asset:{symbol:N?.asset?.symbol||s,address:N?.asset?.address||""},txHash:K.transactionHash||"",success:K.status==="success",amount:N?.amount})):void 0,chainName:ln(l),explorerUrl:ro(l,"").replace(/\/tx\/.*$/,"")||void 0,theme:E,styles:b,dark:F})})]})})},Sc="0xa9059cbb";function Ec(e,t,n){return Ue(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:gt({abi:Qt,functionName:"transfer",args:[n,t]})}}function Ys(e,t,n,o){return t!=="user-transfer"||!n||e.length===0||e[0]?.to.toLowerCase()!==o.toLowerCase()||!e[0]?.data.startsWith(Sc)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function Xo(e,t,n){if(!t)return[e];const o=await t(n);return o?[o,e]:[e]}function oo(e){return e.filter(t=>t.domain!=="spicenet")}function Jo(e){const t=(e.tokenTransfers??[]).filter(n=>n.from==="escrow").map(n=>({token:Tt(n.token),recipient:n.to,amount:BigInt(n.amount)})).filter(n=>n.amount>0n);return t.length>0?t:void 0}function fo(e,t,n){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const o=10n**BigInt(t-n);return(e+o-1n)/o}async function Fc(e,t){const{currentPaymentAmount:n,destinationToken:o,embeddedWalletAddress:s,providerEmbeddedAddress:r,address:i,isNon7702:c,isPayMode:d,resolvedChainId:l,buildActionCalls:p,feeExecutionMode:u,buildSpicenetBatch:f,selectedAsset:h,needsSwap:m,exactOutputSwap:y,resolvedTokenIn:x}=e,k=Qe(n,o.decimals),w=t?.actionAmountOverride??k,C=s||r||(c?void 0:i);if(!C)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const v={userAddress:C,chainId:l,destinationToken:o.address,grossAmount:t?.fundingAmountOverride??k,netAmount:w,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:u,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},b=p(w,v),S={chainId:l,calls:b},E=(!d&&!c?!0:h?.asset?._source==="spice")||c,F=(T,I)=>({token:T,from:c?"solver":"escrow",to:C,amount:I});if(k===0n)return[S];if(m&&y){const T=x??Wn(h.asset,l)??h.asset.address,I=t?.fundingAmountOverride??y.amountInMax,A=E?[F(T,I)]:[],B={to:T,value:0n,data:gt({abi:Qt,functionName:"approve",args:[y.calls[0]?.to,y.amountInMax]})},M={chainId:l,calls:[B,...y.calls,...b],tokenTransfers:[...A,...S.tokenTransfers??[]]};return E?Xo(M,f,{userAddress:C,destinationChainId:l,deliveryToken:T,deliveryAmount:I,deliveryRecipient:C,deliveryTransfers:Jo(M),sourceAsset:h.asset}):[M]}if(E){const T=x??Wn(h.asset,l)??o.address,I=t?.fundingAmountOverride??k,A={...S,tokenTransfers:[F(T,I),...S.tokenTransfers??[]]};return Xo(A,f,{userAddress:C,destinationChainId:l,deliveryToken:T,deliveryAmount:I,deliveryRecipient:C,deliveryTransfers:Jo(A),sourceAsset:h.asset})}return[S]}async function Bc(e,t){const{selectedAsset:n,embeddedWalletAddress:o,externalWalletAddress:s,resolvedChainId:r,destinationToken:i,buildActionCalls:c,feeExecutionMode:d,buildSpicenetBatch:l,isPayMode:p,isNon7702:u,needsSwap:f,resolvedSwap:h,quoteAmountOut:m,resolvedTokenIn:y}=e,x=h?.amountOutMinimum??m;if(!n?.asset||!o)return[];const k=u?s:o;if(!k)return[];const w=t?.fundingAmountOverride??t?.actionAmountOverride??Qe(n.amount,n.asset.decimals),C=t?.fundingAmountOverride??w,v=t?.sourceFundingAmountOverride??w,b=t?.deliveryAmountOverride??C,S=t?.withdrawalAmountOverride??b,E=t?.actionAmountOverride??w,F={userAddress:k,chainId:r,destinationToken:i.address,feeToken:d==="user-transfer"&&f&&y?y:i.address,grossAmount:C,netAmount:E,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:d,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},T=c(E,F),I=n.asset?._source==="wallet";if(!p&&u&&I&&n.asset.chainId===r){if(f){if(!y)throw new Error("Swap input token could not be resolved");if(!h||x===null)throw new Error("Swap quote not available yet")}if(f&&h&&x){const P=c(t?.actionAmountOverride??x,{...F,netAmount:t?.actionAmountOverride??x}),{feeCall:O,remainingCalls:j}=Ys(P,d,f,F.feeToken);return[{chainId:r,calls:[...O?[O]:[],...h.calls,...j]}]}return[{chainId:r,calls:T}]}if(!p&&!u&&I){if(n.asset.chainId===r){if(f){if(!y)throw new Error("Swap input token could not be resolved");if(!h||x===null)throw new Error("Swap quote not available yet")}if(f&&h&&x){const P=c(t?.actionAmountOverride??x,{...F,netAmount:t?.actionAmountOverride??x}),{feeCall:O,remainingCalls:j}=Ys(P,d,f,F.feeToken);return[{chainId:r,calls:[...O?[O]:[],...h.calls,...j]}]}return[{chainId:r,calls:T}]}throw new Error("Cross-chain wallet supplies require external wallet mode")}const A=!p&&!u?n.asset?._source!=="wallet":n.asset?._source==="spice",B=u&&I;if(!(A||B))return[{chainId:r,calls:T}];const M=B&&n.asset.chainId!==r?{chainId:n.asset.chainId,calls:[Ec(Tt(n.asset.address),v,An(n.asset.chainId))]}:null,U=(P,O)=>({token:P,from:B?"solver":"escrow",to:o,amount:O}),W=(P,O)=>B?[{token:P,from:"escrow",to:ri,amount:O}]:[];if(f){if(!y)throw new Error("Swap input token could not be resolved");if(!h||x===null)throw new Error("Swap quote not available yet")}if(f&&h&&x&&y){const P=c(t?.actionAmountOverride??x,{...F,netAmount:t?.actionAmountOverride??x}),{feeCall:O,remainingCalls:j}=Ys(P,d,f,F.feeToken),z={chainId:r,calls:[...O?[O]:[],...h.calls,...j],tokenTransfers:[...W(y,S),U(y,b)]},J=await Xo(z,l,{userAddress:o,destinationChainId:r,deliveryToken:y,deliveryAmount:b,withdrawalAmount:S,deliveryRecipient:o,deliveryTransfers:Jo(z),sourceAsset:n.asset});return M?[M,...J]:J}const L=y??Wn(n.asset,r)??i.address,q={chainId:r,calls:T,tokenTransfers:[...W(L,S),U(L,b)]},D=await Xo(q,l,{userAddress:o,destinationChainId:r,deliveryToken:L,deliveryAmount:b,withdrawalAmount:S,deliveryRecipient:o,deliveryTransfers:Jo(q),sourceAsset:n.asset});return M?[M,...D]:D}async function Tc(e,t,n,o,s){let r=e;for(let i=0;i<4;i++){const c=await t(r),d=await o(c,n,r,s),l=Ll(d);if(l===null||l>=e)return r;const p=r-l,u=e+p;if(u<=r)return r;r=u}return r}function Mc(e,t,n,o){if(e<=0n)return 0n;const s=e-t;if(s<=0n)return 0n;const r=o+n;return r<=0n?s:s*o/r}function Rc(e,t){const n=ct(e,t);return n.includes(".")?n.replace(/\.?0+$/,"")||"0":n}async function Dc(e){const{asset:t,isPayMode:n,isNon7702:o,needsSwap:s,isQuoting:r,embeddedWalletAddress:i,buildSupplyChainBatches:c,estimateGasless:d,executionTokenAddress:l,feeExecutionMode:p}=e;if(n||o||s||r||!i||t.balance<=0n)return null;const u=i,f=await c({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(f.length===0)return null;const h=f.some(C=>C.tokenTransfers?.length),m=await d(f,l,t.balance,h?{userOverride:u,useCustomTransfers:!0,feeExecutionMode:p}:p?{userOverride:u,feeExecutionMode:p}:{userOverride:u}),y=Gn(m,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),x=y?fo(y.gasFee,y.decimals,t.decimals):0n,k=y?fo(y.spicenetFee,y.decimals,t.decimals):0n,w=Mc(t.balance,x,k,t.balance);return w>0n?Rc(w,t.decimals):null}async function Wc(e){const{selectedAsset:t,isPayMode:n,parsedAmount:o,needsSwap:s,exactOutputSwap:r,isNon7702:i,isSourceDestToken:c,currentPaymentAmount:d,destinationToken:l,feeExecutionMode:p,resolvedTokenIn:u,embeddedWalletAddress:f,providerEmbeddedAddress:h,resolvedChainId:m,isConnected:y,address:x,ready:k,authenticated:w,isDirect:C,resolvedSwap:v,isQuoting:b,executionTokenAddress:S,buildPayChainBatches:E,buildSupplyChainBatches:F,estimateGasless:T,estimateRequiredGrossFunding:I}=e;if(!t?.asset)return null;if(n){if(o<=0||s&&!r||i&&c)return null;const D=Qe(d,l.decimals),P=u||Wn(t.asset,m)||t.asset.address||l.address,O={chainId:m,tokenAddress:P,symbol:Ut(P,m)?.symbol??t.asset.symbol,decimals:Ut(P,m)?.decimals??t.asset.decimals};if(i){const ae=f||h;if(!ae)return null;const le=ae,ge=s?r?.amountInMax??0n:D;if(ge===0n)return null;const Re=await I(ge,H=>E({fundingAmountOverride:H}).then(oe=>dn(oo(oe),le)),P,{userOverride:ae,useCustomTransfers:!0}),de=dn(oo(await E({fundingAmountOverride:Re})),le),ke=await T(de,P,Re,{userOverride:ae,useCustomTransfers:!0,feeExecutionMode:p});return Gn(ke,O)}if(!y||!x||!k||!w)return null;const j=f||h||x,z=s?r?.amountInMax??0n:D;if(z===0n)return null;const J=await I(z,ae=>E({fundingAmountOverride:ae}).then(le=>dn(oo(le),j)),P,{useCustomTransfers:!0});let pe=dn(oo(await E({fundingAmountOverride:J})),j);const N=await T(pe,P,J,{useCustomTransfers:!0,feeExecutionMode:p});return Gn(N,O)}if(o<=0||!f)return null;const A=f||h;if(!(!n&&!i&&t.asset?._source==="wallet"&&t.asset.chainId!==m)&&!C&&!v&&!b||b)return null;const B=Qe(t.amount,t.asset.decimals),M=await F();if(M.length===0)return null;const U=i&&t.asset?._source==="wallet"&&t.asset.chainId===m,W={chainId:m,tokenAddress:S,symbol:Ut(S,m)?.symbol??l.symbol,decimals:Ut(S,m)?.decimals??l.decimals};if(U){const D=await ot.estimateBatchGas({user:A,outputToken:S,stepIndex:0,chainBatches:M}),P=qo(B,10n),O=P+D.gasFee;return{...W,grossAmount:B+O,netAmount:B,totalFee:O,gasFee:D.gasFee,spicenetFee:P,bridgeFee:0n,gasQuoteSource:D.gasQuoteSource}}const L=M.some(D=>D.tokenTransfers?.length),q=await T(M,S,B,L?{userOverride:A,useCustomTransfers:!0,feeExecutionMode:p}:p?{userOverride:A,feeExecutionMode:p}:{userOverride:A});return Gn(q,W)}const Nc=10n;function pa(e,t){const n=e.selectedAsset?.asset;if(!n||n?._source!=="wallet")return;const o=Wn(n,e.resolvedChainId);if(!o||!Ae(o,e.executionTokenAddress))return;const s=Ut(e.executionTokenAddress,e.resolvedChainId),r=fo(t,s?.decimals??e.destinationToken.decimals,n.decimals);if(r<=n.balance)return;const i=ct(r,n.decimals),c=ct(n.balance,n.decimals);throw new Error(`Insufficient ${n.symbol} for amount plus fees. Required ${i} ${n.symbol}; available ${c} ${n.symbol}.`)}function fa(e){const t=Ut(e.executionTokenAddress,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:t?.symbol??e.destinationToken.symbol,decimals:t?.decimals??e.destinationToken.decimals}}function ha(e,t,n){const o=Gn(e,fa(t));if(!o)return;const s=qo(n,Nc),r=o.bridgeFee??0n,i=s+o.gasFee+r;return{grossAmount:n+i,netAmount:n,combinedFeeAmount:i,feeExecutionMode:"user-transfer",feeBreakdown:{spicenetFee:s,gasFee:o.gasFee,bridgeFee:r}}}function ho(e,t,n){if(e===t)return!0;const o=e>t?e:t;return o===0n?!1:(e>t?e-t:t-e)*10000n<=o*n}function ma(e,t,n){let o=0n,s=0n;const r=n.toLowerCase();for(const i of e)if(i.chainId===t){for(const c of i.calls??[])if(c.to.toLowerCase()===r)try{const d=Co({abi:Qt,data:c.data});if(d.functionName!=="transfer")continue;const l=d.args[0].toLowerCase(),p=d.args[1];l===xo.toLowerCase()?o+=p:l===Dn.toLowerCase()&&(s+=p)}catch{continue}}return{spicenetFee:o,gasFee:s}}function Pc(e,t,n){const o=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,s=ma(e,t.resolvedChainId,o);return s.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||s.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:ho(s.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&ho(s.gasFee,n.feeBreakdown.gasFee,100n)}function Uc(e,t){return e?ho(e.grossAmount,t.grossAmount,100n)&&ho(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&ho(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&ho(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}async function Lc(e){if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.isNon7702){const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setTxHash(null);try{if(e.isSourceDestToken){e.ui.setStep("executing"),e.ui.setStatusMsg("Submitting transaction...");const o=await ga(e);e.ui.setTxHash(o??null)}else{e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.refs.spiceDepositSubmittedRef.current=!1;const o=new AbortController;e.refs.abortControllerRef.current=o,await zc(e,o.signal)}e.ui.setStep("success"),e.ui.setStatusMsg(e.isSourceDestToken?"Transaction confirmed":"Deposit confirmed")}catch(o){const s=o instanceof Error?o:new Error(String(o));if(s.name==="AbortError"||e.refs.abortControllerRef.current?.signal.aborted){e.ui.setStep("idle");return}const r=s.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(r),e.ui.setError(r),e.onError?.(s)}finally{e.ui.setIsExecuting(!1)}return}if(!e.embeddedWalletAddress){e.ui.setError("Wallet not ready");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.ui.setTxHash(null),e.refs.spiceDepositSubmittedRef.current=!1;const t=new AbortController;e.refs.abortControllerRef.current=t;try{const n=Qe(e.selectedAsset.amount,e.selectedAsset.asset.decimals),o=n;let s=await e.gasless.buildSupplyChainBatches();const r=e.selectedAsset.asset?._source==="wallet",i=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!r&&!s.some(h=>Do(h.chainId)))throw new Error("Spice-funded supplies must include a Spicenet funding batch before the destination chain batch.");const c=s.some(h=>h.tokenTransfers?.length)?{userOverride:i,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}:e.feeExecutionMode?{userOverride:i,feeExecutionMode:e.feeExecutionMode}:{userOverride:i};let d=n;const l=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,p=e.feeExecutionMode==="user-transfer"&&!l?o:void 0;let u;for(let h=0;h<4;h+=1){const m=await e.gasless.estimateGasless(s,e.executionTokenAddress,d,c),y=Gn(m,fa(e));u=e.feeExecutionMode==="user-transfer"&&y?ha(m,e,o):void 0;const x=u?.grossAmount??y?.grossAmount??d;if(x===d){d=x;break}d=x,s=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:d,actionAmountOverride:p,actionContextOverride:u})}e.feeExecutionMode==="user-transfer"&&(pa(e,d),s=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:d,actionAmountOverride:p,actionContextOverride:u}));let f=u;await e.gasless.executeGasless(s,e.executionTokenAddress,d,e.gasless.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...c,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:h,chainBatches:m})=>{const y=ha(h,e,o);if(!y)return null;const x=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&e.resolvedTokenIn?e.resolvedTokenIn:e.executionTokenAddress;ma(m,e.resolvedChainId,x);const k=Uc(f,y),w=Pc(m,e,y);return k||w?null:(f=y,e.gasless.buildSupplyChainBatches({fundingAmountOverride:y.grossAmount,actionAmountOverride:p,actionContextOverride:y}))}}:c),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){const o=n instanceof Error?n:new Error(String(n));if(o.name==="AbortError"||t.signal.aborted){e.ui.setStep("idle");return}const s=o.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(s),e.ui.setError(s),e.onError?.(o)}finally{e.ui.setIsExecuting(!1)}}async function zc(e,t){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const n=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!n)throw new Error("Embedded wallet not available \u2014 sign in to create one before supplying");const o=e.selectedAsset.asset,s=Qe(e.selectedAsset.amount,o.decimals),r=s,i=o?._source==="wallet"&&o.chainId===e.resolvedChainId;let c=await e.gasless.buildSupplyChainBatches();const d={userOverride:n,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode};let l=s;const p=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,u=e.feeExecutionMode==="user-transfer"&&!p?r:void 0;let f;if(i){const F=await ot.estimateBatchGas({user:n,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:c}),T=qo(s,10n),I=T+F.gasFee;l=s+I,e.feeExecutionMode==="user-transfer"&&(f={grossAmount:l,netAmount:r,combinedFeeAmount:I,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:T,gasFee:F.gasFee,bridgeFee:0n}})}else{const F=await e.gasless.estimateGasless(c,e.executionTokenAddress,0n,d),T=Gn(F,{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:Ut(e.executionTokenAddress,e.resolvedChainId)?.symbol??e.destinationToken.symbol,decimals:Ut(e.executionTokenAddress,e.resolvedChainId)?.decimals??e.destinationToken.decimals});T&&(l=T.grossAmount>s?T.grossAmount:s,e.feeExecutionMode==="user-transfer"&&(f={grossAmount:l,netAmount:r,combinedFeeAmount:T.totalFee,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:T.spicenetFee,gasFee:T.gasFee,bridgeFee:T.bridgeFee??0n}}))}const h=Ut(e.executionTokenAddress,e.resolvedChainId),m=i?l:fo(l,h?.decimals??e.destinationToken.decimals,o.decimals);pa(e,l),c=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:l,sourceFundingAmountOverride:m,withdrawalAmountOverride:l,actionAmountOverride:u,actionContextOverride:f});const y=o.chainId,x=n,k=await e.externalWallet.getEthereumProvider();let w=null;try{const F=await k.request({method:"eth_chainId"});w=parseInt(F,16)}catch{w=null}w!==y&&(e.ui.setStatusMsg("Switching source network..."),await Yn(k,y));const C=Be(y),v=Ln({account:e.externalWalletAddress,chain:C?.viemChain,transport:zn(k)}),b=Tt(o.address),S=o.isNative||Ue(b);e.ui.setStatusMsg("Funding embedded wallet...");const E=S?await v.sendTransaction({to:x,value:m,chain:C?.viemChain}):await v.sendTransaction({to:b,data:gt({abi:Qt,functionName:"transfer",args:[x,m]}),chain:C?.viemChain});if((await dt(y).waitForTransactionReceipt({hash:E,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Embedded wallet funding failed");e.ui.setStatusMsg("Signing supply intent..."),await e.gasless.executeGasless(c,e.executionTokenAddress,0n,e.gasless.onProgress,t,d)}async function ga(e){const t=e.isPayMode&&e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t)throw new Error("Select a payment source");const n=e.activeSignerWallet??e.externalWallet,o=e.activeSignerAddress??e.externalWalletAddress;if(!o||!n)throw new Error("Please connect your wallet to continue");const s=Qe(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),r={userAddress:o,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},i=e.buildActionCalls(s,r);if(i.length===0)throw new Error("No action calls configured");const c=await n.getEthereumProvider();let d=null;try{const h=await c.request({method:"eth_chainId"});d=parseInt(h,16)}catch{d=null}d!==e.resolvedChainId&&await Yn(c,e.resolvedChainId);const l=Be(e.resolvedChainId),p=Ln({account:o,chain:l?.viemChain,transport:zn(c)}),u=dt(e.resolvedChainId);let f;for(const h of i){const m=await p.sendTransaction({to:h.to,data:h.data,value:h.value,chain:l?.viemChain});if((await u.waitForTransactionReceipt({hash:m,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transaction failed");f=m}return f}async function Oc(e){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const n=e.selectedAsset.asset,o=n.chainId,s=Qe(e.currentPaymentAmount,e.destinationToken.decimals),r=e.selectedIsEquivalent?s:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(r===0n)throw new Error("Quote not available yet");const i=e.resolvedTokenIn||e.selectedAsset.asset.address,c={userOverride:t,useCustomTransfers:!0},d=await e.gasless.estimateRequiredGrossFunding(r,w=>e.gasless.buildPayChainBatches({fundingAmountOverride:w}),i,c),l=An(o),p=await e.externalWallet.getEthereumProvider();let u=null;try{const w=await p.request({method:"eth_chainId"});u=parseInt(w,16)}catch{u=null}u!==o&&await Yn(p,o);const f=Be(o),h=Ln({account:e.externalWalletAddress,chain:f?.viemChain,transport:zn(p)}),m=Tt(n.address),y=n.isNative||Ue(m)?await h.sendTransaction({to:l,value:d,chain:f?.viemChain}):await h.sendTransaction({to:m,data:gt({abi:Qt,functionName:"transfer",args:[l,d]}),chain:f?.viemChain});if((await dt(o).waitForTransactionReceipt({hash:y,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Escrow deposit failed");const x=await e.gasless.buildPayChainBatches({fundingAmountOverride:d}),k=x.some(w=>w.tokenTransfers?.length);return await e.gasless.executeGasless(x,i,d,w=>{w.txHash&&(e.ui.setPaymentResult(C=>({...C??{status:"processing"},txHash:w.txHash})),e.ui.setTxHash(w.txHash))},void 0,k?c:{userOverride:t})}async function Hc(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}const t=e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t){e.ui.setError("Select a payment source");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.parsedAmount>0&&e.needsSwap&&!e.exactOutputSwap){e.ui.setError("Swap quote not available. Try a different asset.");return}if(e.isNon7702){const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken||t?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{let o;if(e.isSourceDestToken||e.parsedAmount===0)o=await ga(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const s=e.selectedAsset.asset,r=Qe(e.currentPaymentAmount,e.destinationToken.decimals),i=e.selectedIsEquivalent?r:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(i===0n)throw new Error("Quote not available yet");const c=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!c)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const d=e.resolvedTokenIn||s.address,l=await e.gasless.estimateRequiredGrossFunding(i,f=>e.gasless.buildPayChainBatches({fundingAmountOverride:f}),d,{userOverride:c,useCustomTransfers:!0}),p=await e.gasless.buildPayChainBatches({fundingAmountOverride:l}),u=await e.onPayExecute({asset:s,amount:e.currentPaymentAmount,amountWei:r,destinationToken:e.destinationToken,chainBatches:p,requiredNetFunding:i,grossFundingAmount:l,selectedIsEquivalent:e.selectedIsEquivalent,resolvedTokenIn:d,exactOutputSwapAmountInMax:e.exactOutputSwap?.amountInMax});u&&(e.ui.setTxHash(u),e.ui.setPaymentResult(f=>({...f??{status:"processing"},txHash:u}))),o=u||void 0}else o=await Oc(e);e.ui.setPaymentResult(s=>({status:"success",txHash:s?.txHash||o||""}))}catch(o){const s=In(o,"Payment failed. Please try again.");e.ui.setError(s),e.ui.setPaymentResult({status:"failed",error:s}),e.onError?.(o instanceof Error?o:new Error(s))}finally{e.ui.setIsExecuting(!1)}return}if(!e.isConnected||!e.address){e.ui.setError("Please connect your wallet to continue");return}if(!e.ready||!e.authenticated){e.ui.setError(`Please authenticate with ${e.provider||"wallet provider"} to continue`);return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{const n=Qe(e.currentPaymentAmount,e.destinationToken.decimals),o={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode};if(t){const y=await e.gasless.buildPayChainBatches({actionAmountOverride:0n,fundingAmountOverride:0n}),x=await e.gasless.executeGasless(y,e.destinationToken.address,0n,k=>{k.txHash&&(e.ui.setPaymentResult(w=>({...w,txHash:k.txHash})),e.ui.setTxHash(k.txHash))},void 0,o);e.ui.setPaymentResult(k=>({status:"success",txHash:k?.txHash||x}));return}const s=e.selectedAsset?.asset;if(!s)throw new Error("Select a payment source");const r=e.resolvedTokenIn||s.address||e.destinationToken.address,i=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:n,c=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,d=await e.gasless.estimateRequiredGrossFunding(i,y=>e.gasless.buildPayChainBatches({fundingAmountOverride:y}).then(x=>dn(oo(x),c)),r,o);let l=d,p=dn(oo(await e.gasless.buildPayChainBatches({fundingAmountOverride:d})),c);const u=await e.gasless.estimateGasless(p,r,d,o),f=Gn(u,{chainId:e.resolvedChainId,tokenAddress:r,symbol:Ut(r,e.resolvedChainId)?.symbol??s.symbol,decimals:Ut(r,e.resolvedChainId)?.decimals??s.decimals})?.grossAmount??d;f!==d&&(l=f),p=dn(oo(await e.gasless.buildPayChainBatches({fundingAmountOverride:l})),c,u,{payoutAlreadyGross:!0});const h=p.some(y=>y.tokenTransfers?.length),m=await e.gasless.executeGasless(p,r,h?l:0n,y=>{y.txHash&&(e.ui.setPaymentResult(x=>({...x,txHash:y.txHash})),e.ui.setTxHash(y.txHash))},void 0,o);e.ui.setPaymentResult(y=>({status:"success",txHash:y?.txHash||m}))}catch(n){const o=In(n,"Payment failed. Please try again.");e.ui.setError(o),e.ui.setPaymentResult({status:"failed",error:o}),e.onError?.(n instanceof Error?n:new Error(o))}finally{e.ui.setIsExecuting(!1)}}const ya=({variant:e,destinationSymbol:t,destinationLogoURI:n,destinationDecimals:o,primaryColor:s,fontFamily:r,textPrimary:i,textSecondary:c,cardBg:d,cardBorder:l,dk:p,dark:u,isQuoting:f,quoteError:h,estimatedOutput:m,paymentAmount:y,needsSwap:x,exactOutputSwap:k,adjustable:w=!1,maxAmount:C,onAmountChange:v})=>e==="supply"?g("div",{style:{backgroundColor:d,border:`1px solid ${l}`,borderRadius:u?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",minHeight:"112px",display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[g("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"12px"},children:[g("div",{style:{minWidth:0},children:[a("span",{style:{fontFamily:r,fontSize:"17px",fontWeight:500,color:u?"#a7abb2":"#7D7C7B",lineHeight:"24px"},children:"Used in TX"}),a("div",{style:{fontSize:"12px",fontWeight:500,color:c,fontFamily:r,marginTop:"10px"},children:"Net amount after swap and fees"})]}),g("div",{style:{textAlign:"right",minWidth:0,display:"inline-flex",alignItems:"center",gap:"8px",border:`1px solid ${l}`,borderRadius:"8px",padding:"8px 10px",minHeight:"42px"},children:[a(xa,{symbol:t,logoURI:n,primaryColor:s,size:24}),a("span",{style:{fontSize:"16px",fontWeight:500,color:u?"#f3f4f6":"#3C3E42",lineHeight:"1.3",fontFamily:r,letterSpacing:0},children:t})]})]}),a("div",{style:{textAlign:"right",minWidth:0},children:f?a("span",{style:{fontSize:"18px",color:c,fontFamily:r},children:"Quoting..."}):h?a("span",{style:{fontSize:"13px",color:u?"#f87171":"#dc2626",fontFamily:r},children:"Quote failed"}):m?a(eo,{value:m,title:m,fontFamily:r,color:i,lineHeight:"0.95",textAlign:"right",maxFontSize:32,minFontSize:18}):a("span",{style:{fontSize:"20px",color:c,fontFamily:r},children:"\u2014"})})]}):a(jc,{destinationSymbol:t,destinationLogoURI:n,destinationDecimals:o,primaryColor:s,fontFamily:r,textPrimary:i,textSecondary:c,cardBg:d,cardBorder:l,dk:p,dark:u,paymentAmount:y||"0",needsSwap:x,exactOutputSwap:k,isQuoting:f,adjustable:w,maxAmount:C,onAmountChange:v}),xa=({symbol:e,logoURI:t,primaryColor:n,size:o})=>t?a("img",{src:t,alt:e,style:{width:o,height:o,borderRadius:"50%",objectFit:"cover"}}):a("div",{style:{width:o,height:o,borderRadius:"50%",backgroundColor:`${n}22`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:o<30?"11px":"12px",fontWeight:700,color:n},children:e.slice(0,2)}),jc=({destinationSymbol:e,destinationLogoURI:t,destinationDecimals:n,primaryColor:o,fontFamily:s,textPrimary:r,textSecondary:i,cardBg:c,cardBorder:d,dk:l,dark:p,paymentAmount:u,needsSwap:f,exactOutputSwap:h,isQuoting:m,adjustable:y,maxAmount:x,onAmountChange:k})=>{const w='"IBM Plex Mono", monospace',C=parseFloat(u||"0"),v=x?parseFloat(x):0,[b,S]=R(u||""),E=ie(null),[F,T]=R(null),[I,A]=R(null);Z(()=>{y||S(u||"")},[u,y]);const B=W=>{let L=W;L.startsWith(".")&&(L="0"+L);const q=io(L);let D=q;x&&parseFloat(q)>parseFloat(x)&&(D=x),S(D),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>k?.(D),300)},M=W=>{if(!v)return;if(W===100){S(x||v.toString()),E.current&&clearTimeout(E.current),k?.(x||v.toString());return}const L=10**n,q=Math.floor(v*W/100*L)/L,D=lo(q,n);S(D),E.current&&clearTimeout(E.current),k?.(D)},U=v>0?parseFloat(b||"0")/v*100:0;return Z(()=>()=>{E.current&&clearTimeout(E.current)},[]),g("div",{style:{backgroundColor:c,border:`1px solid ${d}`,borderRadius:p?"12px":"6px",padding:"16px",marginBottom:"16px"},children:[g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[a(xa,{symbol:e,logoURI:t,primaryColor:o,size:32}),g("div",{children:[a("span",{style:{fontSize:"14px",fontWeight:600,color:r,fontFamily:s},children:"Payment"}),a("div",{style:{fontSize:"12px",color:i,fontFamily:s,marginTop:"2px"},children:e})]})]}),g("div",{style:{textAlign:"right"},children:[y?a(eo,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:b,onChange:W=>B(W.target.value),placeholder:"0.0",fontFamily:w,color:r,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):a(eo,{element:"div",value:C>0?u:"0.00",title:C>0?u:"0.00",fontFamily:w,color:r,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),a("div",{style:{fontSize:"12px",color:i,fontFamily:w,marginTop:"2px"},children:e}),y&&v>0&&a("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((W,L)=>{const q=Math.abs(U-W)<1,D=L===4,P=W/100,O=F===W,j=I===W;return a("button",{onClick:()=>M(W),onMouseEnter:()=>T(W),onMouseLeave:()=>{T(null),A(null)},onMouseDown:()=>A(W),onMouseUp:()=>A(null),title:`${W}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:q?1:O?.8:.5,transform:j?"scale(0.85)":O?"scale(1.15)":"scale(1)",transition:cn.interactive},children:g("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[a("circle",{cx:"7",cy:"7",r:"6.84375",fill:D?o:"none",stroke:D?o:p?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!D&&P>0&&a("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${P>.5?1:0} 1 ${7+6.84375*Math.sin(P*2*Math.PI)} ${7-6.84375*Math.cos(P*2*Math.PI)} Z`,fill:p?l?.textSecondary||"#9ca3af":"#3C3E42"})]})},W)})})]})]}),f&&h&&!m&&a("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:p?`1px solid ${l?.cardBorder||d}`:"1px solid #e5e7eb",display:"flex",justifyContent:"flex-end"},children:g("span",{style:{fontSize:"11px",color:i,fontFamily:s,opacity:.7},children:["via ",h.venue]})})]})};function ba(e,t,n){const o=Ae(e.address,t),s=e.chainId===n,r=e._source==="wallet";return r&&o&&s?0:r&&s?1:!r&&o?2:!r&&s?3:4}function Qc(e,t){return!t||t.length===0||t.some(n=>Ae(n,e.address))?!0:Object.keys(e.chainTokens??{}).some(n=>{const o=po(n);return o?t.some(s=>Ae(s,o.address)):!1})}function Vc(e){const{destinationToken:t,supportedSourceAssets:n,sourceChains:o,enabled:s}=e,r=(Zt(Ht)?.mode||"7702")!=="7702",i=Rn(),{externalAddress:c,embeddedAddress:d,activeAddress:l}=_n(),p=i||d,{assets:u,refetch:f}=Eo({address:p,supportedChains:o,enabled:s&&!r&&!!p,refetchInterval:3e4}),h=re(()=>r?[]:u.filter(F=>Qc(F,n)),[u,n,r]),m=r?l??c:i,y=re(()=>{const F=new Set,T=[],I=A=>{if(!A)return;const B=A.toLowerCase();F.has(B)||(F.add(B),T.push(Me(A)))};if(I(t.address),r&&n)for(const A of n)I(A);return T},[r,t.address,n]),x=re(()=>y.map(F=>F.toLowerCase()).sort().join(","),[y]),k=re(()=>JSON.stringify([...o||[]].sort()),[o]),[w,C]=R([]),v=ie(0),b=ie(async()=>{}),S=ce(async()=>{if(!s||!m||y.length===0){v.current++,C([]);return}const F=++v.current,T=Me(m),I=r?o&&o.length>0?o:[t.chainId]:[t.chainId],A=[];for(const W of y){const L=W.toLowerCase();if(L===jt)continue;if(L===t.address.toLowerCase()){const D=Be(t.chainId)?.supportedTokens?.find(P=>Ae(P.address,L));A.push({address:W,chainId:t.chainId,configToken:D?{decimals:D.decimals,symbol:D.symbol,name:D.name,logo:D.logo}:void 0});continue}let q=!1;for(const D of I){const P=Be(D)?.supportedTokens?.find(O=>Ae(O.address,L));if(P){A.push({address:W,chainId:D,configToken:{decimals:P.decimals,symbol:P.symbol,name:P.name,logo:P.logo}}),q=!0;break}}q||A.push({address:W,chainId:t.chainId})}const B=new Map;for(const W of A){const L=B.get(W.chainId)||[];L.push(W),B.set(W.chainId,L)}const M=async(W,L)=>{try{const q=await En(W,{address:L.address,abi:Qt,functionName:"balanceOf",args:[T]});let D,P,O,j;if(L.configToken)D=L.configToken.decimals,P=L.configToken.symbol,O=L.configToken.name,j=L.configToken.logo;else{const[pe,N,ae]=await Promise.all([En(W,{address:L.address,abi:Qt,functionName:"decimals"}).catch(()=>18),En(W,{address:L.address,abi:Qt,functionName:"symbol"}).catch(()=>"TOKEN"),En(W,{address:L.address,abi:Qt,functionName:"name"}).catch(()=>"TOKEN")]);D=Number(pe),P=N,O=ae}const z=Ae(L.address,t.address)&&L.chainId===t.chainId;z&&t.logoURI&&(j=t.logoURI),z&&!L.configToken&&P==="TOKEN"&&(P=t.symbol,O=t.symbol);const J=parseFloat((Number(q)/Math.pow(10,D)).toFixed(6));return{address:L.address,name:O,symbol:P,decimals:D,balance:q,balanceFormatted:J,balanceUsd:0,logoURI:j,isNative:!1,chainId:L.chainId}}catch{return null}},U=await Promise.all(Array.from(B.entries()).map(async([W,L])=>{let q;try{q=dt(W)}catch{return[]}const D=[],P=[];for(const j of L){const z=D.length;D.push({address:j.address,abi:Qt,functionName:"balanceOf",args:[T]}),j.configToken||D.push({address:j.address,abi:Qt,functionName:"decimals"},{address:j.address,abi:Qt,functionName:"symbol"},{address:j.address,abi:Qt,functionName:"name"}),P.push({start:z,item:j})}let O=null;try{O=await q.multicall({contracts:D})}catch{O=null}return O?P.map(({start:j,item:z})=>{const J=O[j],pe=J?.status==="success"?J.result:0n;let N,ae,le,ge;if(z.configToken)N=z.configToken.decimals,ae=z.configToken.symbol,le=z.configToken.name,ge=z.configToken.logo;else{const ke=O[j+1],H=O[j+2],oe=O[j+3];N=ke?.status==="success"?Number(ke.result):18,ae=H?.status==="success"?H.result:"TOKEN",le=oe?.status==="success"?oe.result:ae}const Re=Ae(z.address,t.address)&&z.chainId===t.chainId;Re&&t.logoURI&&(ge=t.logoURI),Re&&!z.configToken&&ae==="TOKEN"&&(ae=t.symbol,le=t.symbol);const de=parseFloat((Number(pe)/Math.pow(10,N)).toFixed(6));return{address:z.address,name:le,symbol:ae,decimals:N,balance:pe,balanceFormatted:de,balanceUsd:0,logoURI:ge,isNative:!1,chainId:z.chainId}}):(await Promise.all(L.map(j=>M(q,j)))).filter(j=>j!==null)}));F===v.current&&C(U.flat())},[s,r,m,x,k,t.address,t.chainId,t.symbol,t.logoURI]);Z(()=>{b.current=S},[S]),Z(()=>{if(!s){C([]);return}b.current();const F=setInterval(()=>{b.current()},15e3);return()=>clearInterval(F)},[s,r,m,x,k,t.address,t.chainId]);const E=ce(()=>{S()},[S]);return{displayAssets:re(()=>{const F=[],T=w.filter(A=>A.balance>0n);for(const A of T)F.push({...A,_source:"wallet"});for(const A of h)F.push({...A,_source:"spice"});const I=t.address.toLowerCase();return F.sort((A,B)=>ba(A,I,t.chainId)-ba(B,I,t.chainId)),F},[w,h,t.address,t.chainId]),filteredSpiceAssets:h,walletAssets:w,embeddedWalletAddress:p,externalAddress:c,isNon7702:r,refreshSpiceAssets:f,refreshWalletAssets:E}}async function wa(e){const{tokenIn:t,tokenOut:n,amountIn:o,fee:s,chainId:r,config:i}=e;if(o<=0n)throw new Error("amountIn must be greater than 0");const c=(await dt(r).simulateContract({address:i.quoterV2,abi:ai,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:o,fee:s,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 Ca(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(s=>wa({...e,fee:s})));let o=null;for(let s=0;s<n.length;s++){const r=n[s];r.status==="fulfilled"&&(!o||r.value.amountOut>o.amountOut)&&(o={...r.value,fee:t[s]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}const qc=[{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 Yc(e){const{tokenIn:t,tokenOut:n,amountOut:o,fee:s,chainId:r,config:i}=e;if(o<=0n)throw new Error("amountOut must be greater than 0");const c=(await dt(r).simulateContract({address:i.quoterV2,abi:qc,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:o,fee:s,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 Kc(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(s=>Yc({...e,fee:s})));let o=null;for(let s=0;s<n.length;s++){const r=n[s];r.status==="fulfilled"&&(!o||r.value.amountIn<o.amountIn)&&(o={...r.value,fee:t[s]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}function ka(e){return e.type==="swap"}const Ks=.02,Zc=[1,8453,42161,10,137,43114,56],Gc="https://api.1inch.dev/swap/v6.0";function va(e,t){return li(e,t)}function Ia(e){const t=e?.baseUrl??Gc;return{name:"1inch",chainIds:e?.chainIds??Zc,resolve:async(n,o,s)=>{const r=n.maxSlippage??Ks,i=r*100,c=Ue(n.tokenIn)?ir:n.tokenIn,d=Ue(n.tokenOut)?ir:n.tokenOut,l=Ue(n.tokenIn);try{const p=new URL(`${t}/${o}/swap`);p.searchParams.set("src",c),p.searchParams.set("dst",d),p.searchParams.set("amount",n.amountIn.toString()),p.searchParams.set("from",s),p.searchParams.set("slippage",i.toString()),p.searchParams.set("disableEstimate","true"),p.searchParams.set("allowPartialFill","false");const u={Accept:"application/json"};e?.apiKey&&(u.Authorization=`Bearer ${e.apiKey}`);const f=await fetch(p.toString(),{headers:u});if(!f.ok)throw new Te("VENUE_API_ERROR",`[1inchVenue] API returned ${f.status} for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`,{venue:"1inch",chainId:o,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:`HTTP ${f.status}`});const h=await f.json();if(!h.dstAmount||!h.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const m=BigInt(h.dstAmount);if(m<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const y=va(m,r),x=[];return h.tx.to&&!l&&x.push({to:n.tokenIn,value:0n,data:gt({abi:Qt,functionName:"approve",args:[h.tx.to,n.amountIn]})}),x.push({to:h.tx.to,value:BigInt(h.tx.value||"0"),data:h.tx.data}),{venue:"1inch",amountOut:m,amountOutMinimum:y,calls:x}}catch(p){if(p instanceof Te)throw p;const u=p instanceof Error?p.message:String(p);throw new Te("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}: ${u}`,{venue:"1inch",chainId:o,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:u})}}}}const Aa=[4114,5115],Zs={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},Sa={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[3e3]};function Ea(e){return{name:"satsuma",chainIds:e.chainIds??Aa,resolve:async(t,n,o)=>{const s=t.maxSlippage??Ks,r=Ue(t.tokenIn);let i;try{i=await Ca({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountIn:t.amountIn,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return console.warn(`[SatsumaVenue] No viable fee tier for ${t.tokenIn} \u2192 ${t.tokenOut} on chain ${n}.`),null}const c=va(i.amountOut,s),d=[];return r||d.push({to:t.tokenIn,value:0n,data:gt({abi:Qt,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),d.push({to:e.swapRouter,value:r?t.amountIn:0n,data:gt({abi:ii,functionName:"exactInputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:i.fee,recipient:o,amountIn:t.amountIn,amountOutMinimum:c,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:i.amountOut,amountOutMinimum:c,calls:d}}}}function Fa(e){return{name:"satsuma",chainIds:e.chainIds??Aa,resolve:async(t,n,o)=>{const s=t.maxSlippage??Ks,r=Ue(t.tokenIn);let i;try{i=await Kc({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountOut:t.amountOut,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return null}const c=BigInt(Math.round(s*1e4)),d=i.amountIn+i.amountIn*c/10000n,l=[];return l.push({to:e.swapRouter,value:r?d:0n,data:gt({abi:Xc,functionName:"exactOutputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:i.fee,recipient:o,amountOut:t.amountOut,amountInMaximum:d,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:i.amountIn,amountInMax:d,amountOut:t.amountOut,calls:l}}}}const Xc=[{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 Ba(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(Ea(e.satsuma)),t.push(Ia(e?.oneInch));function n(s){return t.find(r=>r.chainIds.includes(s))}async function o(s,r,i){const c=[],d=[];for(const l of s){if(!ka(l)){c.push(l);continue}const p=n(r);if(!p)throw new Te("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${r}. Cannot resolve swap ${l.tokenIn} \u2192 ${l.tokenOut}.`,{chainId:r,tokenIn:l.tokenIn,tokenOut:l.tokenOut,amountIn:l.amountIn.toString()});const u=await p.resolve(l,r,i);if(!u)throw new Te("NO_LIQUIDITY",`${p.name} returned no quote for ${l.tokenIn} \u2192 ${l.tokenOut} on chain ${r}.`,{venue:p.name,chainId:r,tokenIn:l.tokenIn,tokenOut:l.tokenOut,amountIn:l.amountIn.toString()});c.push(...u.calls),d.push(u)}return{calls:c,resolvedSwaps:d}}return{resolveSwapIntents:o,getVenueForChain:n,venues:t}}function Jc(e){const t=e?.customVenues??[];async function n(o,s,r){const i=t.filter(d=>d.chainIds.includes(s));if(i.length===0)throw new Te("NO_SWAP_ROUTE",`No exact-output venue supports chain ${s}`,{chainId:s,tokenIn:o.tokenIn,tokenOut:o.tokenOut});const c=(await Promise.allSettled(i.map(d=>d.resolve(o,s,r)))).filter(d=>d.status==="fulfilled").map(d=>d.value).filter(d=>d!==null);if(c.length===0)throw new Te("NO_SWAP_ROUTE",`All aggregators failed for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${s}`,{chainId:s,tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountOut:o.amountOut.toString()});return c.sort((d,l)=>d.amountIn<l.amountIn?-1:d.amountIn>l.amountIn?1:0),c[0]}return{getQuote:n,venues:t}}const $c=Ba({satsuma:Zs});function _c(e){const{direction:t,selectedAsset:n,destinationToken:o,chainId:s,recipient:r,paymentAmount:i}=e,[c,d]=R(!1),[l,p]=R(null),[u,f]=R(null),[h,m]=R(null),[y,x]=R(null),[k,w]=R(null),[C,v]=R(null),[b,S]=R(null),[E,F]=R(null),T=ie(null),I=ie(null),A=ie(0),B=ie(new Map),M=re(()=>$c,[]),U=re(()=>Jc({customVenues:[Fa(Zs),Fa(Sa)]}),[]),W=re(()=>{if(!n?.asset)return null;const N=Wn(n.asset,s);if(N)return N;const ae=Vn(n.asset.address,s,n.asset.chainId);return ae?ae.address:null},[n?.asset,s]),L=re(()=>n?.asset?jo(n.asset,s):[],[n?.asset,s]),q=re(()=>L.map(N=>N.toLowerCase()).join(","),[L]);Z(()=>{let N=!1;if(I.current&&(clearTimeout(I.current),I.current=null),!n?.asset||L.length<=1){F(null);return}return I.current=setTimeout(async()=>{const ae=t==="input"?n.amount:i||"0";let le=0n;try{le=t==="input"?Qe(ae,n.asset.decimals):0n}catch{le=0n}try{const ge=await Or(n.asset,s,{requiredAmount:le});N||F(ge)}catch{N||F(null)}},400),()=>{N=!0,I.current&&(clearTimeout(I.current),I.current=null)}},[n?.asset,n?.amount,s,L.length,q,t,i]);const D=re(()=>E??W,[E,W]),P=re(()=>!n?.asset||!D?[]:[D,...L.filter(N=>N.toLowerCase()!==D.toLowerCase())],[n?.asset,D,L]),O=re(()=>!n?.asset||!So(n.asset.address,n.asset.chainId,o.address,o.chainId)||!D?!1:Ae(D,o.address),[n,o.address,o.chainId,D]),j=D?Ae(D,o.address):!1,z=t==="output"&&parseFloat(i||"0")===0,J=!!n?.asset&&!O&&!j&&!z,pe=J?b??D:D;return Z(()=>{T.current&&clearTimeout(T.current);const N=t==="input"?n?.amount:i,ae=parseFloat(N||"0");if(!J||!Number.isFinite(ae)||ae<=0||!n?.asset||!r||P.length===0){A.current++,f(null),m(null),x(null),w(null),v(null),S(null),p(null),d(!1);return}const le=n.asset.decimals;let ge;try{ge=t==="input"?Qe(n.amount,le):Qe(i||"0",o.decimals)}catch{A.current++,p("Invalid amount"),d(!1);return}const Re=++A.current,de=()=>Re!==A.current;d(!0);const ke=t==="output"?150:400;return T.current=setTimeout(async()=>{try{if(t==="input"){const H=M.getVenueForChain(s);if(!H)throw new Error("No swap venue for this chain");let oe=null,X=null;for(const fe of P){const Ee=`${t}:${s}:${fe.toLowerCase()}:${o.address.toLowerCase()}:${ge.toString()}`,be=B.current.get(Ee);if(be&&be.expiresAt>Date.now()&&be.resolvedSwap){oe=be.resolvedSwap,X=fe;break}const V=await H.resolve({type:"swap",tokenIn:fe,tokenOut:o.address,amountIn:ge},s,r);if(de())return;if(V){B.current.set(Ee,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:V}),oe=V,X=fe;break}}if(!oe||!X)throw new Error("No liquidity for this pair");S(X),v(oe.amountOut),x(oe),w(null);const se=parseFloat(ct(oe.amountOut,o.decimals));f(se<.01?se.toPrecision(4):se.toLocaleString(void 0,{maximumFractionDigits:6})),m(null),p(null)}else{let H=null,oe=null;for(const X of P){const se=`${t}:${s}:${X.toLowerCase()}:${o.address.toLowerCase()}:${ge.toString()}`,fe=B.current.get(se);if(fe&&fe.expiresAt>Date.now()&&fe.exactOutputSwap){H=fe.exactOutputSwap,oe=X;break}try{const Ee=await U.getQuote({tokenIn:X,tokenOut:o.address,amountOut:ge},s,r);if(de())return;B.current.set(se,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:Ee}),H=Ee,oe=X;break}catch{if(de())return}}if(!H||!oe)throw new Error("No liquidity for this pair");S(oe),w(H),x(null),v(null),m(parseFloat(ct(H.amountIn,le)).toFixed(6)),f(null),p(null)}}catch(H){if(de())return;const oe=H instanceof Error?H.message:"Failed to get quote";p(oe),f(null),m(null),x(null),w(null),v(null),S(null)}finally{de()||d(!1)}},ke),()=>{T.current&&clearTimeout(T.current)}},[t,J,n?.amount,n?.asset?.address,n?.asset?.decimals,i,P,s,o.address,o.decimals,r,M,U]),{isQuoting:c,quoteError:l,estimatedOutput:u,estimatedInput:h,resolvedSwap:y,exactOutputSwap:k,quoteAmountOut:C,resolvedTokenIn:pe,isDirect:j,needsSwap:J,selectedIsEquivalent:O}}const Ta={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},Ma=["signing-delegation","signing-intent","submitting","executing"],Ra=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,destinationToken:o,sourceChains:s,supportedSourceAssets:r,buildActionCalls:i,feeExecutionMode:c="user-transfer",buildSpicenetBatch:d,onPayExecute:l,actionLabel:p,amountDirection:u="input",swapDescription:f,directDescription:h,paymentAmount:m,amountInputMode:y="fixed",minPaymentAmount:x,maxPaymentAmount:k,onAmountChange:w,styles:C,dark:v,title:b,subtitle:S,onAddFunds:E,onSuccess:F,onError:T})=>{const I=u==="output",{theme:A,dark:B,primaryColor:M,dk:U,palette:W,fontFamily:L,monoFont:q,inputDark:D,cardBg:P,cardBorder:O,textPrimary:j,textSecondary:z,subtitleText:J}=lt(C,v),pe=D?{...A,colors:{...A.colors,secondary:U.cardBg,surfaceHover:U.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:A,N=o.chainId,ae=Zt(Ht),le=(ae?.mode||"7702")!=="7702",ge=!!ae?.isWhitelistGateActive,Re=re(()=>s??ae?.supportedChainIds??[],[s,ae?.supportedChainIds]),de=re(()=>{if(ge)return[];if(r)return r;const Ce=ae?.allowedTokens;if(!Ce||Ce.length===0)return;const et=new Set(Ce.map(vn=>vn.toLowerCase())),kn=[],yn=new Set;for(const vn of Re){const ts=Be(vn);for(const ns of ts?.supportedTokens??[]){if(!et.has(ns.symbol.toLowerCase()))continue;const $s=ns.address.toLowerCase();yn.has($s)||(yn.add($s),kn.push(ns.address))}}return kn},[r,ae?.allowedTokens,Re,ge]),ke=Mn(),{address:H,isConnected:oe,isReady:X,isAuthenticated:se,provider:fe}=ke,{executeGasless:Ee,estimateGasless:be}=Go(),{externalWallet:V,externalAddress:Q,embeddedAddress:he,activeWallet:Le,activeAddress:kt}=_n(),zt=Rn()||he,{displayAssets:Ot,filteredSpiceAssets:st,embeddedWalletAddress:rt,refreshSpiceAssets:G,refreshWalletAssets:We}=Vc({destinationToken:o,supportedSourceAssets:de,sourceChains:Re,enabled:e&&(le?!!Q:!!zt)}),we=ge||I||le?Ot:st,[_,Ze]=R(null),[Rt,un]=R(m||""),[ut,on]=R(!1),[Nt,Xt]=R(null),[De,pn]=R("idle"),[sn,xn]=R(""),[Vt,rn]=R(null),[yt,pt]=R(!1),[Ye,Jt]=R(null),[xt,me]=R(null),[bt,tt]=R(!1),[fn,ye]=R(!1),[qt,ft]=R(null),Dt=ie(_),Mt=ie(!1),hn=ie(null),Yt=ie(0),bn=ie(null),wn=ie(null);Z(()=>{Dt.current=_},[_]);const Ne=y==="adjustable"?Rt:m||"0",Pt=rt||he||H,{isQuoting:Je,quoteError:$t,estimatedOutput:Nn,resolvedSwap:Ge,exactOutputSwap:$e,quoteAmountOut:Wt,resolvedTokenIn:vt,isDirect:ze,needsSwap:Xe,selectedIsEquivalent:_t}=_c({direction:u,selectedAsset:_,destinationToken:o,chainId:N,recipient:Pt,paymentAmount:Ne}),Et=I?parseFloat(Ne||"0"):parseFloat(_?.amount||"")||0,en=_?.asset?._source==="wallet",Oe=!!_?.asset&&en&&_.asset.chainId!==N,Pn=re(()=>_?.asset?st.find(Ce=>Ae(Ce.address,_.asset.address))?.balanceFormatted??0:0,[_,st]),ee=en?_?.asset.balanceFormatted??0:Pn,te=re(()=>{if(!_?.asset)return!1;if(I)return xt?fo(xt.grossAmount,xt.decimals,_.asset.decimals)>_.asset.balance:_t||ze?Et>_.asset.balanceFormatted:$e?parseFloat(ct($e.amountInMax,_.asset.decimals))>_.asset.balanceFormatted:!1;if(xt){const Ce=fo(xt.grossAmount,xt.decimals,_.asset.decimals);return en?Ce>_.asset.balance:parseFloat(ct(Ce,_.asset.decimals))>ee}return Et>ee},[_,I,xt,_t,Et,$e,ee,en,ze]);Z(()=>{e||(Ze(null),Xt(null),on(!1),pn("idle"),xn(""),rn(null),pt(!1),Jt(null),me(null),tt(!1),ye(!1),ft(null),Mt.current=!1,y==="adjustable"&&un(m||""),hn.current&&(hn.current.abort(),hn.current=null))},[e]);const ve=ce(Ce=>{Ze(et=>({asset:Ce,amount:et?.asset?.address===Ce.address&&et?.asset?.chainId===Ce.chainId&&et.amount||""})),Xt(null),ft(null),ye(!1)},[]),Ve=ce(Ce=>{Ze(et=>et&&{...et,amount:Ce}),Xt(null),ft(null),ye(!1)},[]),It=ce(Ce=>{let et=Ce;k&&parseFloat(et)>parseFloat(k)&&(et=k),un(et),w?.(et),Xt(null),ft(null),ye(!1)},[k,w]);ce(Ce=>{if(Mt.current||!H)return;const et=Dt.current;!et?.asset||!et.amount||et.asset?._source==="wallet"||Qe(I?Ne:et.amount,et.asset.decimals)===0n||(Mt.current=!0,G())},[H,N,G,I,Ne]);const wt=ce(Ce=>{pn({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[Ce.step]||"executing"),xn(Ce.message),Ce.txHash&&rn(Ce.txHash)},[]),ht=re(()=>({currentPaymentAmount:Ne,destinationToken:o,embeddedWalletAddress:rt,providerEmbeddedAddress:he,externalWalletAddress:Q,address:H,isNon7702:le,isPayMode:I,resolvedChainId:N,buildActionCalls:i,feeExecutionMode:c,buildSpicenetBatch:d,selectedAsset:_,needsSwap:Xe,resolvedSwap:Ge,exactOutputSwap:$e,quoteAmountOut:Wt,resolvedTokenIn:vt}),[Ne,o,rt,he,Q,H,le,I,N,i,c,d,_,Xe,Ge,$e,Wt,vt]),at=ce(Ce=>Fc(ht,Ce),[ht]),He=ce(Ce=>Bc(ht,Ce),[ht]),nt=ce((Ce,et,kn,yn)=>Tc(Ce,et,kn,be,yn),[be]),Pe=re(()=>_?.asset?Xe&&vt?vt:_.asset.chainId===N?_.asset.address:vt??Wn(_.asset,N)??o.address:o.address,[_,o.address,Xe,N,vt]),qe=ce(()=>Lc(wn.current),[]),K=re(()=>_?.asset?Ae(_.asset.address,o.address)&&_.asset.chainId===o.chainId:!1,[_,o.address,o.chainId]),Ie=le&&K,mt=Ie&&Et>0&&!!_?.asset,At=Nt,_e=re(()=>!(!_?.asset||Et<=0),[_,Et,mt]),tn=re(()=>!e||ut||De!=="idle"||!_e||mt||!_?.asset?null:[I?"pay":"supply",u,_.asset.address.toLowerCase(),_.asset.chainId,_.amount,Ne,o.address.toLowerCase(),o.chainId,N,vt?.toLowerCase()??"",Xe?"swap":"direct",ze?"direct-token":"routed-token",le?"non7702":"7702",K?"source-dest":"cross-chain",Je?"quoting":"quoted",$e?.amountIn?.toString()??"",$e?.amountInMax?.toString()??"",$e?.venue??"",Ge?.amountOut?.toString()??"",Wt?.toString()??"",rt??"",he??"",H??""].join("|"),[e,ut,De,_e,mt,_,I,u,Ne,o,N,vt,Xe,ze,le,K,Je,$e,Ge,Wt,rt,he,H]),Y=ce(()=>Wc({selectedAsset:_,isPayMode:I,parsedAmount:Et,needsSwap:Xe,exactOutputSwap:$e,isNon7702:le,isSourceDestToken:K,currentPaymentAmount:Ne,destinationToken:o,feeExecutionMode:c,resolvedTokenIn:vt,embeddedWalletAddress:rt,providerEmbeddedAddress:he,resolvedChainId:N,isConnected:oe,address:H,ready:X,authenticated:se,isDirect:ze,resolvedSwap:Ge,isQuoting:Je,executionTokenAddress:Pe,buildPayChainBatches:at,buildSupplyChainBatches:He,estimateGasless:be,estimateRequiredGrossFunding:nt}),[_,I,Et,Xe,$e,le,K,Ne,o,c,vt,rt,he,nt,at,be,N,oe,H,X,se,ze,Ge,Je,He,Pe]);Z(()=>{bn.current=Y},[Y]);const $=ce(Ce=>Dc({asset:Ce,isPayMode:I,isNon7702:le,needsSwap:Xe,isQuoting:Je,embeddedWalletAddress:rt,buildSupplyChainBatches:He,estimateGasless:be,executionTokenAddress:Pe,feeExecutionMode:c}),[I,le,Xe,Je,rt,He,be,Pe,c]);Z(()=>{if(!e){tt(!1),ye(!1),ft(null),me(null);return}if(ut||De!=="idle"){Yt.current+=1,tt(!1);return}if(!_e){me(null),tt(!1),ye(!1),ft(null);return}if(mt){me(null),tt(!1),ye(!0),ft(null);return}if(Je){Yt.current+=1,tt(!1),ye(!1);return}if(!tn)return;let Ce=!1;const et=async()=>{const yn=++Yt.current;ft(null),tt(!0);try{const vn=await bn.current?.();if(Ce||Yt.current!==yn)return;vn?(me(vn),ye(!0)):(me(null),ye(!1)),ft(null)}catch(vn){if(Ce||Yt.current!==yn)return;const ts=In(vn,"Unable to calculate fees for this action.");me(null),ye(!1),ft(ts)}finally{!Ce&&Yt.current===yn&&tt(!1)}},kn=window.setTimeout(()=>{et()},250);return()=>{Ce=!0,clearTimeout(kn),tt(!1)}},[e,ut,De,_e,mt,Je,tn]);const ue=ce(()=>Hc(wn.current),[]);Z(()=>{!I&&De==="success"&&Vt&&(G(),F?.(Vt))},[I,De,Vt,G,F]),Z(()=>{if(!I||Ye?.status!=="success"||Mt.current||!H)return;Mt.current=!0;const Ce=Dt.current;!Ce?.asset||Ce.asset?._source==="wallet"||G()},[I,Ye?.status,H,G]);const ne=ie(F),Fe=ie(T);Z(()=>{ne.current=F},[F]),Z(()=>{Fe.current=T},[T]),Z(()=>{e&&(G(),We())},[e,G,We]),Z(()=>{I&&(Ye?.status==="success"&&ne.current?.(Ye.txHash||""),Ye?.status==="failed"&&Fe.current?.(new Error("Payment execution failed")))},[I,Ye?.status]);const Se=ce(()=>{pt(!1),Jt(null),Ze(null),Mt.current=!1,G(),We()},[G,We]);wn.current={selectedAsset:_,parsedAmount:Et,currentPaymentAmount:Ne,isInsufficientBalance:te,isPayMode:I,isNon7702:le,isSourceDestToken:K,needsSwap:Xe,exactOutputSwap:$e,selectedIsEquivalent:_t,resolvedTokenIn:vt,embeddedWalletAddress:rt,providerEmbeddedAddress:he,externalWallet:V,externalWalletAddress:Q,activeSignerWallet:Le,activeSignerAddress:kt,address:H,isConnected:oe,ready:X,authenticated:se,provider:fe,resolvedChainId:N,executionTokenAddress:Pe,destinationToken:o,buildActionCalls:i,feeExecutionMode:c,buildSpicenetBatch:d,onPayExecute:l,onSuccess:F,onError:T,gasless:{estimateGasless:be,executeGasless:Ee,buildPayChainBatches:at,buildSupplyChainBatches:He,estimateRequiredGrossFunding:nt,onProgress:wt},ui:{setError:Xt,setStep:pn,setStatusMsg:xn,setTxHash:rn,setIsExecuting:on,setShowStatusPanel:pt,setPaymentResult:Jt},refs:{spiceDepositSubmittedRef:Mt,abortControllerRef:hn}};const Ft=m?.trim(),it=I&&y==="fixed"&&Ft!==void 0&&Ft!==""&&Et===0,je=I?(it||!!_?.asset)&&Et>=0&&!te&&!ut&&(it||mt||fn)&&!qt&&(it||!Xe||!!$e):!!_?.asset&&Et>0&&!te&&!ut&&(Ie||fn)&&!qt&&(Oe||ze||!!Ge&&!Je),Ct=ze?h||`Your ${o.symbol} will be used directly.`:f||"Your assets will be swapped and used in a single atomic transaction.",Cn=(N?Be(N):void 0)?.viemChain?.blockExplorers?.default?.url??"",Bn=Ma.indexOf(De),Tn=ut?(Ta[De]||"EXECUTING...").toUpperCase():De==="success"?"DONE":te?"INSUFFICIENT BALANCE":p.toUpperCase(),mn=re(()=>{if(ut)return"PAYING...";if(te&&_?.asset)return`INSUFFICIENT ${_.asset.symbol}`;if(p)return p.toUpperCase();const Ce=Et>0?` ${Ne} ${o.symbol}`:"";return Xe?`SWAP & PAY${Ce}`:`PAY${Ce}`},[ut,te,_,p,Et,Ne,o.symbol,Xe]),xe=De==="success"?()=>{pn("idle"),Ze(null),rn(null),G()}:qe,St=De==="success"?!1:!je;if(!e)return null;const Kt=I?b||`Pay ${o.symbol}`:p,gn=I?S:g("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[a("span",{style:{marginTop:"3px",flexShrink:0},children:a(As,{color:J})}),a("p",{style:{fontSize:"12px",color:J,margin:0,lineHeight:"1.4",fontFamily:L},children:Ct})]});if(I){const Ce=Ye&&(Ye.status==="success"||Ye.status==="failed")?[{asset:{symbol:_?.asset?.symbol||o.symbol,address:_?.asset?.address||""},amount:Ne,txHash:Ye.txHash||"",success:Ye.status==="success",error:Ye.status==="failed"?Ye.error:void 0}]:void 0;return a(Hn,{isOpen:e,onClose:t,title:Kt,subtitle:gn,styles:C,dark:B,footerLinkText:"Spicenet accounts \u2192",closeOnBackdropClick:n,children:g("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[E&&a("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:a(Ss,{onClick:E,color:M,fontFamily:L})}),!it&&a("div",{style:{marginBottom:"12px"},children:a(Ao,{assets:we,selectedAsset:_??void 0,onAssetSelect:ve,onAmountChange:()=>{},label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:_?.asset?Xe?Je?"...":$e?`~${parseFloat(ct($e.amountIn,_.asset.decimals)).toFixed(6)}`:void 0:Ne??void 0:void 0,dark:B,theme:pe,styles:C})}),a(ya,{variant:"pay",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:M,fontFamily:L,textPrimary:j,textSecondary:z,cardBg:P,cardBorder:O,dk:U,dark:B,isQuoting:Je,quoteError:$t,estimatedOutput:Nn,paymentAmount:Ne,needsSwap:Xe,exactOutputSwap:$e,adjustable:y==="adjustable",maxAmount:k,onAmountChange:It}),_e&&a(Lo,{fontFamily:L,textPrimary:j,textSecondary:z,cardBg:P,cardBorder:O,resolvedDark:B,darkCardBorder:U.cardBorder,primaryColor:M,feePreview:xt,isLoading:bt,errorText:qt,directExecutionFeeNote:mt}),At&&a(co,{variant:"error",palette:W,fontFamily:L,style:{marginBottom:"12px"},children:At}),a(Bt,{variant:"outline",fullWidth:!0,onClick:ue,disabled:!je,loading:ut,dark:B,styles:{...C,button:{...C?.button,backgroundColor:M}},children:mn}),Ye&&yt&&a("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:B?U.shell:"white",borderRadius:B?"12px":"6px",padding:"16px 0"},children:a(Ms,{type:"payment",isOpen:Ye.status!=="processing",isProcessing:ut||Ye.status==="processing",closeOnComplete:!1,chainName:ln(N),explorerUrl:ro(N,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{pt(!1),Jt(null),ue()},onNewTx:Se,onClose:()=>{pt(!1),Jt(null)},onComplete:Se,results:Ce,styles:C,dark:B})})]})})}return a(Hn,{isOpen:e,onClose:t,title:Kt,subtitle:gn,dark:B,styles:C,theme:A,closeOnBackdropClick:n,children:g("div",{style:{padding:"24px 24px 5px 24px",position:"relative"},children:[a("div",{style:{marginBottom:"16px"},children:a(Ao,{assets:we,selectedAsset:_||void 0,onAssetSelect:ve,onAmountChange:Ve,disabled:ut||De==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:pe,styles:C,dark:D,resolveMaxAmount:$,maxAmount:ee>0?lo(ee,_?.asset.decimals??o.decimals):void 0})}),_?.asset&&!ze&&a(ya,{variant:"supply",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:M,fontFamily:L,textPrimary:j,textSecondary:z,cardBg:P,cardBorder:O,dark:B,isQuoting:Je,quoteError:$t,estimatedOutput:Nn}),_e&&a(Lo,{fontFamily:L,textPrimary:j,textSecondary:z,cardBg:P,cardBorder:O,resolvedDark:B,darkCardBorder:U.cardBorder,primaryColor:M,feePreview:xt,isLoading:bt,errorText:qt,directExecutionFeeNote:mt}),De!=="idle"&&g("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:De==="success"?P:De==="error"?W.errorBg:P,border:`1px solid ${De==="success"?O:De==="error"?W.errorBorder:O}`},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[De==="success"?a("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:a("path",{d:"M5 13l4 4L19 7",stroke:W.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):De==="error"?a("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:a("path",{d:"M18 6L6 18M6 6l12 12",stroke:W.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):a(qn,{size:14,color:M}),a("span",{style:{fontSize:"13px",fontWeight:500,color:De==="success"?j:De==="error"?W.errorText:j,fontFamily:L,flex:1},children:De==="success"?"Deposit confirmed":De==="error"?sn||"Transaction failed":Ta[De]||sn}),De==="success"&&Vt&&a("a",{href:`${Cn}/tx/${Vt}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:M,fontFamily:L,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),De==="error"&&a("button",{onClick:()=>{pn("idle"),Xt(null),setTimeout(qe,50)},style:{background:"none",border:"none",fontSize:"12px",color:M,fontFamily:L,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),Bn>=0&&De!=="success"&&De!=="error"&&a("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${z}22`,overflow:"hidden"},children:a("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:M,transformOrigin:"left center",transform:`scaleX(${(Bn+1)/Ma.length})`,transition:"transform 400ms ease"}})})]}),Nt&&De==="idle"&&a(co,{variant:"error",palette:W,fontFamily:L,style:{marginBottom:"16px"},children:Nt}),a(Bt,{variant:"outline",fullWidth:!0,disabled:St,onClick:xe,theme:A,dark:B,styles:{...C,button:{...C?.button,backgroundColor:M}},style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:q},children:Tn})]})})},ed=e=>a(Ra,{isOpen:e.isOpen,onClose:e.onClose,closeOnBackdropClick:e.closeOnBackdropClick,amountDirection:"output",destinationToken:{address:e.paymentTokenAddress,symbol:e.paymentTokenSymbol,decimals:e.paymentTokenDecimals,chainId:e.paymentChainId,logoURI:e.paymentTokenLogoURI},buildActionCalls:e.buildActionCalls,buildSpicenetBatch:e.buildSpicenetBatch,actionLabel:e.ctaLabel||"PAY",paymentAmount:e.paymentAmount,amountInputMode:e.amountInputMode,minPaymentAmount:e.minPaymentAmount,maxPaymentAmount:e.maxPaymentAmount,onAmountChange:e.onAmountChange,title:e.title,subtitle:e.subtitle,onAddFunds:e.onAddFunds,styles:e.styles,dark:e.dark,onSuccess:e.onPaymentSuccess,onError:e.onPaymentError}),td=({label:e="Export Wallet",style:t,className:n,onExport:o,onError:s})=>{const[r,i]=R(!1),[c,d]=R(!1),{primaryColor:l}=lt(),p=Zt(Ht),{isAuthenticated:u}=Mn();let f=null;try{f=ui()}catch{}let h=null,m=null;try{h=fi(),m=hi()}catch{h=null,m=null}const y=Za(m),x=ce(async()=>{if(!u){s?.("User is not authenticated. Please log in first.");return}try{if(p?.provider==="dynamic"){if(!h||!y){s?.("Dynamic is not available. Ensure the app is wrapped in a DynamicContextProvider.");return}await h.initExportProcess(!1),o?.();return}if(!f){s?.("Privy is not available. Ensure the app is wrapped in a PrivyProvider.");return}await f.exportWallet(),o?.()}catch(C){const v=C instanceof Error?C.message:"Failed to export wallet";console.error("Export wallet error:",C),s?.(v)}},[y,h,u,s,o,f,p?.provider]),k=!u,w={padding:"10px 20px",borderRadius:"8px",fontFamily:'"IBM Plex Mono", monospace',fontSize:"14px",fontWeight:500,letterSpacing:"0.4px",textTransform:"uppercase",cursor:k?"not-allowed":"pointer",opacity:k?.5:1,border:"1px solid #0e0d0b",color:"#0e0d0b",backgroundColor:c?`${l}cc`:r?`${l}ee`:l,transition:"background-color 150ms ease, transform 150ms ease",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"8px",...t};return g("button",{onClick:x,onMouseEnter:()=>i(!0),onMouseLeave:()=>{i(!1),d(!1)},onMouseDown:()=>d(!0),onMouseUp:()=>d(!1),disabled:k,className:n,style:w,children:[g("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),a("polyline",{points:"17 8 12 3 7 8"}),a("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]}),e]})};function Da(e){const t=Zt(Ht),n=Rn(),o=e?.enabled===!1?void 0:n,s=t?.network?{network:t.network,pollIntervalMs:e?.pollIntervalMs,chainIds:e?.chainIds??t.supportedChainIds,discoverWalletBalances:e?.discoverWalletBalances}:void 0;return{...Tr(o,s),embeddedWalletAddress:n}}var nd="data:image/svg+xml,%3csvg width='11' height='11' viewBox='0 0 24 24' fill='none' stroke='black' stroke-opacity='0.5' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' xmlns='http://www.w3.org/2000/svg'%3e%3cpolyline points='17 1 21 5 17 9' /%3e%3cpath d='M3 11V9a4 4 0 0 1 4-4h14' /%3e%3cpolyline points='7 23 3 19 7 15' /%3e%3cpath d='M21 13v2a4 4 0 0 1-4 4H3' /%3e%3c/svg%3e";const od=({appName:e,status:t,statusLabel:n,totalUsdValue:o,breakdownSubtitle:s,address:r,dk:i,dark:c=!1,showModeToggle:d,isEmbeddedMode:l=!0,onModeToggle:p})=>{const[u,f]=R(!1),h=async()=>{r&&await Ii(r)&&(f(!0),setTimeout(()=>f(!1),2e3))},m=t==="active",y=n||(m?"Active":"Inactive"),x=m?"#10b981":"#9ca3af",k=g("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[g("div",{children:[a("strong",{children:"Embedded:"})," Deposit assets into ",e," account and use them here."]}),g("div",{children:[a("strong",{children:"External:"})," Use assets from your connected wallet here."]})]});return g("div",{children:[g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[g("div",{style:{fontSize:"13px",fontWeight:600,color:i.textPrimary},children:[e," Account"]}),d?g("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[g("button",{onClick:p,style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:c?i.hoverBg:"#f3f4f6",border:c?`1px solid ${i.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"11px",fontWeight:600,fontFamily:'"IBM Plex Mono", monospace',color:i.textSecondary,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease",letterSpacing:"0.02em"},children:[a("span",{children:l?"Embedded":"External"}),a("img",{src:nd,alt:"","aria-hidden":"true",style:{width:"11px",height:"11px",display:"block",...c?{filter:"invert(0.65)"}:{}}})]}),a(kr,{content:k,label:"Account mode info",textColor:c?i.textPrimary:"#f9fafb",backgroundColor:c?i.cardBg:"#111827",borderColor:c?i.cardBorder:"rgba(255,255,255,0.08)",accentColor:c?i.textSecondary:"#6b7280",children:a("img",{src:Bs,alt:"","aria-hidden":"true",style:{width:"12px",height:"12px",display:"block",...c?{filter:"invert(0.65)"}:{}}})})]}):g("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:c?i.hoverBg:m?"#ecfdf5":"#f3f4f6",border:c?`1px solid ${i.cardBorder}`:m?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[a("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:x}}),a("span",{style:{fontSize:"11px",fontWeight:500,color:c?i.textSecondary:m?"#065f46":"#6b7280"},children:y})]})]}),a("div",{style:{fontSize:"28px",fontWeight:700,color:i.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:ao(o)}),s&&a("div",{style:{fontSize:"12px",color:i.textSecondary,marginBottom:"8px"},children:s}),r&&g("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[a("span",{style:{fontSize:"12px",fontFamily:'"IBM Plex Mono", monospace',color:c?i.textSecondary:"#9ca3af"},children:hr(r)}),a("button",{onClick:h,style:{padding:"2px 6px",fontSize:"10px",fontWeight:500,backgroundColor:"transparent",color:c?i.textSecondary:"#9ca3af",border:"none",cursor:"pointer",borderRadius:"4px",transition:"background-color 150ms ease, color 150ms ease"},title:"Copy address",children:u?"Copied":"Copy"})]})]})},sd=({pendingDeposits:e,onCompleteDeposit:t,dk:n,dark:o=!1})=>e.length===0?null:g("div",{children:[a("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:"Pending Deposits"}),a("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((s,r)=>{const i=Be(s.chainId)?.displayName||`Chain ${s.chainId}`;return g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:o?n.warningBg:"#fffbeb",border:o?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"8px"},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[a("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:o?n.hoverBg:"#fde68a",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:n.warningText},children:s.tokenSymbol.charAt(0)}),g("div",{children:[g("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:[s.amount," ",s.tokenSymbol]}),g("div",{style:{fontSize:"11px",color:n.warningText},children:["on ",i]})]})]}),a("button",{onClick:()=>t?.(s),style:{padding:"4px 12px",fontSize:"11px",fontWeight:600,backgroundColor:o?n.hoverBg:"#fef3c7",color:o?n.textPrimary:"#92400e",border:o?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"9999px",cursor:"pointer",transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease"},children:"Complete"})]},`${s.tokenAddress}-${s.chainId}-${r}`)})})]}),rd=({spiceAssets:e,loading:t,dk:n,dark:o=!1})=>{const s={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},r={backgroundColor:n.cardBg,border:o?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return t?g("div",{children:[a("div",{style:s,children:"Idle Balances"}),[1,2].map(i=>a("div",{style:{...r,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},i))]}):e.length===0?g("div",{children:[a("div",{style:s,children:"Idle Balances"}),a("div",{style:{...r,padding:"16px",textAlign:"center",fontSize:"13px",color:o?n.textSecondary:"#9ca3af"},children:"No assets yet. Deposit to get started."})]}):g("div",{children:[a("div",{style:s,children:"Idle Balances"}),a("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((i,c)=>{const d=Be(i.chainId),l=i.chainDisplayName||d?.displayName||`Chain ${i.chainId}`,p=i.tokenDisplaySymbol||i.tokenDisplayName||i.tokenSymbol;return g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...r},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[i.logoURI?a("img",{src:i.logoURI,alt:i.tokenSymbol,style:{width:"24px",height:"24px",borderRadius:"50%"}}):a("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:o?n.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:n.textSecondary},children:p.charAt(0)}),g("div",{children:[a("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:p}),a("div",{style:{fontSize:"11px",color:o?n.textSecondary:"#9ca3af"},children:l})]})]}),g("div",{style:{textAlign:"right"},children:[a("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:Zn(i.balanceFormatted)}),a("div",{style:{fontSize:"11px",color:o?n.textSecondary:"#9ca3af"},children:ao(i.usdValue)})]})]},`${i.tokenAddress}-${i.chainId}-${c}`)})})]})},ad=({section:e,dk:t,dark:n=!1})=>{const o=s=>{switch(s){case"green":return"#10b981";case"red":return"#ef4444";default:return t.textPrimary}};return g("div",{children:[a("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:t.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:e.title}),a("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.items.map((s,r)=>g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:t.cardBg,border:n?`1px solid ${t.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.tokenLogoURI?a("img",{src:s.tokenLogoURI,alt:s.tokenSymbol,style:{width:"20px",height:"20px",borderRadius:"50%"}}):a("div",{style:{width:"20px",height:"20px",borderRadius:"50%",backgroundColor:n?t.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",fontWeight:600,color:t.textSecondary},children:s.tokenSymbol.charAt(0)}),g("div",{children:[a("div",{style:{fontSize:"13px",fontWeight:500,color:t.textPrimary},children:s.tokenSymbol}),a("div",{style:{fontSize:"11px",color:t.textSecondary},children:s.label})]})]}),a("div",{style:{fontSize:"13px",fontWeight:600,color:o(s.valueColor)},children:s.displayValue})]},r))})]})},id=({onDepositClick:e,onWithdrawClick:t,depositDisabled:n=!1,withdrawDisabled:o=!1,primaryColor:s="#EA4B4B",dark:r=!1})=>!e&&!t?null:g("div",{style:{display:"flex",gap:"8px"},children:[e&&a(Bt,{variant:"outline",onClick:e,disabled:n,dark:r,styles:{button:{backgroundColor:s}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&a(Bt,{variant:"outline",onClick:t,disabled:o,dark:r,styles:{button:{backgroundColor:s}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),ld=({appName:e,status:t,statusLabel:n,totalUsdValue:o,breakdownSubtitle:s,address:r,spiceAssets:i,spiceAssetsLoading:c,pendingDeposits:d,customSections:l,notice:p,onDepositClick:u,onWithdrawClick:f,onCompleteDeposit:h,primaryColor:m,dk:y,dark:x=!1,showModeToggle:k,isEmbeddedMode:w,onModeToggle:C,showConnectExternalCta:v,onConnectExternalWallet:b,connectExternalError:S,showHowItWorks:E=!0})=>{const[F,T]=R(!1);return g("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[a(od,{appName:e,status:t,statusLabel:n,totalUsdValue:o,breakdownSubtitle:s,address:r,dk:y,dark:x,showModeToggle:k,isEmbeddedMode:w,onModeToggle:C}),p&&a("div",{style:{padding:"10px 12px",borderRadius:"8px",backgroundColor:p.tone==="warning"?x?"rgba(245, 158, 11, 0.12)":"#fffbeb":p.tone==="success"?x?"rgba(16, 185, 129, 0.12)":"#ecfdf5":y.cardBg,border:p.tone==="warning"?x?"1px solid rgba(245, 158, 11, 0.35)":"1px solid #fde68a":p.tone==="success"?x?"1px solid rgba(16, 185, 129, 0.35)":"1px solid #a7f3d0":x?`1px solid ${y.cardBorder}`:"1px solid #e5e7eb",color:p.tone==="warning"?x?"#fbbf24":"#92400e":p.tone==="success"?x?"#34d399":"#047857":y.textSecondary,fontSize:"12px",lineHeight:1.45,fontWeight:500},children:p.message}),v&&g("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[a("button",{onClick:b,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:m||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:'"Helvetica Neue", sans-serif',transition:"opacity 150ms ease"},children:"Connect External Wallet"}),S&&a("span",{style:{fontSize:"11px",color:x?y.errorText:"#b91c1c",lineHeight:1.4},children:S})]}),a("div",{style:{height:"1px",backgroundColor:x?"#2d2d2d":"#e5e7eb"}}),a(id,{onDepositClick:u,onWithdrawClick:f,primaryColor:m,dark:x}),E&&g("div",{children:[g("button",{onClick:()=>T(!F),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:y.cardBg,border:x?`1px solid ${y.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:y.textSecondary,fontSize:"12px",fontWeight:500},children:[a("span",{children:"How It Works"}),a("span",{style:{transform:F?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),F&&g("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:x?y.cardBg:"#f0fdf4",border:x?`1px solid ${y.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:x?y.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),a(sd,{pendingDeposits:d,onCompleteDeposit:h,dk:y,dark:x}),a(rd,{spiceAssets:i,loading:c,dk:y,dark:x}),l.map((I,A)=>a(ad,{section:I,dk:y,dark:x},A))]})},Gs=380,so=8;function Wa(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function cd(e,t){const n=new Map;Object.entries(t).forEach(([s,r])=>{if(!Number.isFinite(r)||r<=0)return;n.set(s,r),n.set(s.toUpperCase(),r);const i=Wa(s);i&&n.set(i,r)});const o=[e.symbol,e.displaySymbol,e.receiptTokenName,e.name,e.displayName];for(const s of o){if(!s)continue;const r=n.get(s)??n.get(s.toUpperCase());if(r!==void 0)return r;const i=Wa(s);if(!i)continue;const c=n.get(i);if(c!==void 0)return c}return 0}const dd=({appName:e="Spice",status:t="active",statusLabel:n,customSections:o=[],extraAssets:s=[],tokenPrices:r={},breakdownLabels:i=[],notice:c,styles:d,dark:l=!1,onDepositSuccess:p,onDepositClick:u,onWithdrawClick:f,onCompleteDeposit:h,showModeToggle:m=!1,defaultMode:y})=>{const x=Zt(Ht),k=x?.mode!=="7702",w=!!x?.isWhitelistGateActive,C=ie(!1);Z(()=>{if(!C.current){if(Ga()){C.current=!0;return}y&&x?.setMode&&(x.setMode(y==="non7702"?"ondemand":"7702"),C.current=!0)}},[x,y]);const[v,b]=R(!1),[S,E]=R(null),[F,T]=R({top:0,bottom:0,left:0,placement:"below"}),I=ie(null),A=ie(null),{address:B,isConnected:M}=Mn(),U=Rn(),{externalAddress:W,embeddedAddress:L}=_n(),{dark:q,primaryColor:D,dk:P}=lt(d,l),O=k&&!W,j=!k||O,z=j?U||L:B,J=re(()=>x?.supportedChainIds??Ro("mainnet"),[x?.supportedChainIds]),{assets:pe,loading:N}=Eo({address:z,supportedChains:J,enabled:!!z&&j,refetchInterval:3e4}),ae=re(()=>{const G=j?pe.map(we=>{const _=we.balanceUsd||0,Ze=Number.isFinite(we.balanceFormatted)?we.balanceFormatted:0,Rt=_>0?_:cd(we,r)*Ze;return{tokenAddress:we.address,tokenSymbol:we.symbol,tokenDisplaySymbol:Cs(we),tokenDisplayName:Ti(we),tokenDecimals:we.decimals,chainId:we.chainId,chainDisplayName:ks(we),balance:we.balance.toString(),balanceFormatted:we.balanceFormatted,usdValue:Rt,logoURI:we.logoURI}}):[],We=O?[]:s;return[...G,...We].filter(we=>we.balanceFormatted>0)},[j,O,pe,r,s]),le=re(()=>ae.reduce((G,We)=>G+We.usdValue,0),[ae]),{pendingDeposits:ge}=Da({chainIds:J,enabled:!!B,discoverWalletBalances:!0}),Re=re(()=>o.reduce((G,We)=>G+We.totalValue,0),[o]),de=le+Re,ke=re(()=>{const G=[];le>0&&G.push(`${ao(le)} idle`);for(const We of o){const we=i.find(_=>_.sectionTitle===We.title)?.label||We.title.toLowerCase();G.push(`${ao(We.totalValue)} ${we}`)}return G.join(" \xB7 ")},[le,o,i]),H=ce(G=>{h?h(G):E(G)},[h]),oe=ce(()=>{E(null)},[]),X=ce(()=>{E(null),p?.()},[p]),se=ce(()=>{if(!I.current)return;const G=I.current.getBoundingClientRect(),We=window.innerHeight-G.bottom-so,we=G.top-so,_=We>=400||We>=we?"below":"above",Ze=Math.max(so,Math.min(G.right-Gs,window.innerWidth-Gs-so)),Rt=_==="below"?G.bottom+so:G.top-so,un=_==="above"?window.innerHeight-Rt:0;T({top:Rt,bottom:un,left:Ze,placement:_})},[]);_s(()=>{v&&se()},[v,se]),Z(()=>{if(!v)return;const G=_=>{I.current&&!I.current.contains(_.target)&&A.current&&!A.current.contains(_.target)&&b(!1)},We=_=>{_.key==="Escape"&&b(!1)},we=()=>se();return document.addEventListener("mousedown",G),document.addEventListener("keydown",We),window.addEventListener("scroll",we,{passive:!0}),window.addEventListener("resize",se),()=>{document.removeEventListener("mousedown",G),document.removeEventListener("keydown",We),window.removeEventListener("scroll",we),window.removeEventListener("resize",se)}},[v,se]);const fe=j?U||L||B:W||B,Ee=ce(()=>{x?.setMode&&x.setMode(j?"ondemand":"7702")},[x,j]),[be,V]=R(null);let Q=null;try{Q=lr({onSuccess:()=>V(null),onError:G=>V(In(G,"Failed to connect wallet."))}).connectWallet}catch{Q=null}const he=ce(()=>{Q&&(b(!1),V(null),Q({walletChainType:"ethereum-only"}))},[Q]),Le=!W&&!!Q,kt=ce(()=>{b(!1),u?.()},[u]),zt=ce(()=>{b(!1),f?.()},[f]),Ot=ce(G=>{b(!1),H(G)},[H]);if(typeof window>"u")return null;const st=g("button",{ref:I,onClick:()=>b(!v),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:q?P.hoverBg:"#ffffff",border:q?`1px solid ${P.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:'"Helvetica Neue", sans-serif',color:q?P.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:q?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[g("span",{children:[e," Account"]}),M&&g("span",{style:{color:q?P.textSecondary:"#6b7280"},children:["\xB7 ",ao(de)]}),a("span",{style:{fontSize:"10px",color:q?P.textSecondary:"#9ca3af",transform:v?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),rt=v?cr.createPortal(g(nn,{children:[a("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:Kn.popover},onClick:()=>b(!1)}),a("div",{ref:A,style:{position:"fixed",top:F.placement==="below"?`${F.top}px`:"auto",bottom:F.placement==="above"?`${F.bottom}px`:"auto",left:`${F.left}px`,width:`${Gs}px`,maxWidth:`calc(100vw - ${so*2}px)`,maxHeight:"80vh",backgroundColor:q?P.shell:"#ffffff",border:q?`1px solid ${P.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:q?"0 10px 40px rgba(0, 0, 0, 0.5)":"0 10px 40px rgba(0, 0, 0, 0.12)",zIndex:Kn.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${Lt.out}`},children:a(ld,{appName:e,status:t,statusLabel:n,totalUsdValue:de,breakdownSubtitle:ke,address:j?fe:B,spiceAssets:ae,spiceAssetsLoading:N,pendingDeposits:ge,customSections:o,notice:c,onDepositClick:u?kt:void 0,onWithdrawClick:f?zt:void 0,onCompleteDeposit:Ot,primaryColor:D,dk:P,dark:q,showModeToggle:m,isEmbeddedMode:j,onModeToggle:Ee,showConnectExternalCta:Le,onConnectExternalWallet:he,connectExternalError:be,showHowItWorks:!w})}),a("style",{children:`
104
104
  @keyframes accountDisplayFadeIn {
105
105
  from { opacity: 0; transform: translateY(-4px); }
106
106
  to { opacity: 1; transform: translateY(0); }