@spicenet-io/spiceflow-ui 3.3.65 → 3.3.66
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +2 -2
- package/dist/index.js +2 -2
- package/dist/types/status.d.ts +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -36,7 +36,7 @@ import{jsxs as g,jsx as a,Fragment as en}from"react/jsx-runtime";import ln,{useS
|
|
|
36
36
|
from { transform: translateY(0); }
|
|
37
37
|
to { transform: translateY(100%); }
|
|
38
38
|
}
|
|
39
|
-
`})]}):a("div",{style:{backgroundColor:T,borderRadius:"12px",padding:"24px",width:"100%",boxShadow:I},children:we})}if(!e&&!x||!x&&(!r||r.length===0))return null;const ce=r?r.every(ue=>ue.success):!1;r&&r.some(ue=>!ue.success);const xe=r?.[0],De=r
|
|
39
|
+
`})]}):a("div",{style:{backgroundColor:T,borderRadius:"12px",padding:"24px",width:"100%",boxShadow:I},children:we})}if(!e&&!x||!x&&(!r||r.length===0))return null;const ce=r?r.every(ue=>ue.success):!1;r&&r.some(ue=>!ue.success);const xe=r?.[0],De=[...r??[]].reverse().find(ue=>ue.txHash)?.txHash||xe?.txHash;return g("div",{style:{position:y?"absolute":"relative",bottom:y?0:void 0,left:y?0:void 0,right:y?0:void 0,zIndex:y?10:void 0,animation:y?E?"slideDown 0.3s ease-in forwards":"slideUp 0.3s ease-out forwards":void 0,pointerEvents:"auto",width:"100%"},children:[a("div",{style:{backgroundColor:T,borderRadius:y?"12px 12px 0 0":"12px",width:"100%",padding:"18px 0 24px",boxShadow:y?A:I},children:g("div",{style:{width:"100%",boxSizing:"border-box",padding:"0 24px"},children:[g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"16px"},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:x?"default":"pointer"},onClick:x?void 0:re,children:[g("span",{style:{fontSize:"13px",fontWeight:500,color:F,fontFamily:l?.fontFamily||S.typography.fontFamily},children:[x?`Processing ${s.charAt(0).toUpperCase()+s.slice(1)}`:`${s.charAt(0).toUpperCase()+s.slice(1)} results`," "]}),!x&&k&&a(Qn,{color:F,direction:D?"up":"down"})]}),!x&&a("button",{onClick:t,onMouseEnter:()=>j("close"),onMouseLeave:()=>{j(null),J(null)},onMouseDown:()=>J("close"),onMouseUp:()=>J(null),style:{background:L==="close"?v?b.hoverBg:"#f3f4f6":O==="close"?v?b.inputBg:"#f9fafb":"none",border:"none",borderRadius:"4px",cursor:"pointer",padding:"4px",display:"flex",alignItems:"center",justifyContent:"center",color:O==="close"||L==="close"?M:F,transform:L==="close"?"scale(0.9)":O==="close"?"scale(1.1)":"scale(1)",transition:dn.interactive},children:a(no,{size:16})})]}),a("div",{style:{marginBottom:"16px",animation:"statusFadeIn 220ms cubic-bezier(0.22, 1, 0.36, 1) both"},children:x?g("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"20px 16px",borderRadius:"8px",backgroundColor:z,border:`1px solid ${q}`,gap:"12px"},children:[a(Kn,{size:24,borderWidth:3,color:C}),g("div",{children:[a("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:'"IBM Plex Mono", monospace',letterSpacing:"0.5px",color:M},children:"PROCESSING TRANSACTION"}),g("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:F},children:["on ",i]})]})]}):a(Nr,{isSuccess:ce,type:s,chainName:i,explorerUrl:c,txHash:De,dark:v,...v?{successBg:b.successBg,successBorder:b.successBorder,successText:b.successText,errorBg:b.errorBg,errorBorder:b.errorBorder,errorText:b.errorText}:{},textSecondary:F})},x?"processing":ce?"success":"error"),!x&&k&&r&&r.length>1&&a("div",{style:{overflow:"hidden",maxHeight:D?"200px":"0px",opacity:D?1:0,transition:"max-height 0.3s ease, opacity 0.3s ease",marginBottom:D?"16px":"0"},children:a("div",{style:{maxHeight:"180px",overflowY:"auto",display:"flex",flexDirection:"column",gap:"8px"},children:r.map((ue,ve)=>g("div",{style:{padding:"10px 12px",borderRadius:"6px",backgroundColor:U,border:`1px solid ${W}`,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[a("span",{style:{fontWeight:600,fontSize:"13px",color:b.textPrimary,fontFamily:'"IBM Plex Mono", monospace'},children:ue.asset.symbol}),ue.amount&&a("span",{style:{fontSize:"12px",color:F},children:ue.amount})]}),a("span",{style:{fontSize:"12px",color:ue.success?"#10b981":"#ef4444",fontWeight:500},children:ue.success?"\u2713":"\u2717"})]},ve))})}),!x&&!ce&&r&&a("div",{style:{padding:"12px",backgroundColor:b.errorBg,border:`1px solid ${b.errorBorder}`,borderRadius:"8px",marginBottom:"16px"},children:a("p",{style:{fontSize:"13px",color:b.errorText,margin:0,lineHeight:1.5},children:pe||r.find(ue=>!ue.success)?.error||`${s.charAt(0).toUpperCase()+s.slice(1)} failed. Please try again.`})}),!x&&g("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[!ce&&m&&g(Ft,{variant:"outline",fullWidth:!0,onClick:m,theme:S,styles:l,dark:v,children:["TRY AGAIN ",s.toUpperCase()]}),ce&&a(Ft,{variant:"outline",fullWidth:!0,onClick:N,theme:S,styles:l,dark:v,children:"DONE"})]})]})}),a("style",{children:`
|
|
40
40
|
@keyframes slideUp {
|
|
41
41
|
from {
|
|
42
42
|
transform: translateY(100%);
|
|
@@ -100,7 +100,7 @@ import{jsxs as g,jsx as a,Fragment as en}from"react/jsx-runtime";import ln,{useS
|
|
|
100
100
|
from { transform: rotate(0deg); }
|
|
101
101
|
to { transform: rotate(360deg); }
|
|
102
102
|
}
|
|
103
|
-
`})]})},kc="0xa9059cbb";function vc(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 Ic(e,t){return`0x${t}${e.slice(4)}`}function Ac(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 ca(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 Ac(r?.balances,n,o)}async function Sc({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 ca(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 js(e,t){return Qs(e,t)}function Qs(e,t,n){const o=Ec(t,e),s=Math.floor(Date.now()/1e3)+60*10,r=zn(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 Ec(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(kc))break;try{const i=vo({abi:qe,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 un(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=Bn(p),f=u.totalFee;if(f<=0n)return l;const h=(l.tokenTransfers??[]).find(C=>r(C)&&Me(C.to).toLowerCase()===t.toLowerCase()&&!Pe(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:qe,functionName:"transfer",args:[wo,u.spicenetFee]})});const w=u.gasFee+u.bridgeFee;return w>0n&&k.push({to:m,value:0n,data:gt({abi:qe,functionName:"transfer",args:[Wn,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:vc(h)}}));if(c.length===0)return e;const d=BigInt(Math.floor(Date.now()/1e3))+3600n;return[{chainId:ri,domain:"spicenet",tokenTransfers:[],calls:c.map((l,p)=>{const u=Co(ko([{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=Ic(u,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:gt({abi:ds,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 Vs(e,t){return t?e.some(n=>(n.tokenTransfers??[]).some(o=>o.from==="escrow"&&BigInt(o.amount)>=t.grossAmount)):!1}function qs(e){const t=e.selectedAsset?.asset,n=e.selectedAsset?.amount;if(!(!t||!n))return Le(n,t.decimals)}function $n(e,t){const n=e.selectedAsset?.asset;if(!n||!e.selectedAsset?.amount)throw new Error("Select an asset and enter an amount");const o=Le(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 Ks(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=pt(r),c=yo(r),d=await cs(t,i),l=await e.actions.signAuthorization({contractAddress:c,chainId:r,nonce:Number(d)});s.push(l)}return s}async function da(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 Ks(e,o,t),r=zn(t),i=Math.floor(Date.now()/1e3)+60*10,c=r.map(h=>h.hash),d=Co(ko([{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 nt.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=rs(t,cn),[m,y]=f.intentIds[0].split("/"),x=parseInt(y||"0",10),k=f.intentIds[0];e.startStatusPolling(f.intentIds[0],h),await Vr({actionId:m,intentIndex:x,intentId:k,totalSteps:t.length,isSpicenetStep:w=>t[w]?.domain==="spicenet",maxExecuteAttemptsForStep:w=>t[w]?.domain==="spicenet"?6:3,maxPolls:72})}}async function ua(e){let t=$n(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 Ks(e,n,t);let s=un([...t],n),r;for(let i=0;i<4;i+=1){const c=await nt.estimateActionFees(Qs(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=To(c,{symbol:e.selectedAsset?.asset.symbol??"",decimals:e.selectedAsset?.asset.decimals??18,actionAmount:qs(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=$n(e,r),s=un([...t],n,c,{payoutAlreadyGross:Vs(t,r)}),p)break}await da(e,s,o)}async function Bc(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=Le(e.selectedAsset.amount,t.decimals),o=e.escrowAddress||yo(e.lockChainId),s=nt.getBaseUrl(),r=Tt(t.address);let i=0n;try{i=await ca(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=Fe(e.lockChainId),l=Ln({account:e.embeddedWalletAddress,transport:On(c),chain:d?.viemChain});let p;if(t.isNative||Pe(t.address))p=await l.sendTransaction({to:o,value:n,chain:d?.viemChain});else{const u=gt({abi:qe,functionName:"transfer",args:[o,n]});p=await l.sendTransaction({to:t.address,data:u,chain:d?.viemChain})}if((await pt(e.lockChainId).waitForTransactionReceipt({hash:p,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to escrow failed");await Sc({apiBaseUrl:s,user:e.embeddedWalletAddress,chainId:e.lockChainId,tokenAddress:r,prevBalance:i}),await e.refreshSpiceAssets(),e.refreshWalletAssets(),await ua(e)}async function Fc(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,B=Le(e.selectedAsset.amount,E.decimals),T=await e.onLockExecute({asset:E,amount:e.selectedAsset.amount,amountWei:B,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=Le(e.selectedAsset.amount,o.decimals),r=o.chainId,i=e.escrowAddress||An(r),c=Tt(o.address),d=o.isNative||Pe(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:qe,functionName:"transfer",args:[i,S]})}]}),u=(S,E,B)=>{const T=p(S);if(!l)return[T,...E];const I=un([...E],t,B,{payoutAlreadyGross:Vs(E,y)});return[T,...I]};let f=$n(e),h=u(s,f);const m=await Ks(e,t,h);let y;if(l)for(let S=0;S<4;S+=1){const E=await nt.estimateActionFees(Qs(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)})))),B=To(E,{symbol:o.symbol,decimals:o.decimals,actionAmount:s});if(!B)break;const T={grossAmount:B.grossAmount,netAmount:B.netAmount,feeAmount:B.totalFee??0n},I=y?.grossAmount===T.grossAmount&&y?.netAmount===T.netAmount&&y?.feeAmount===T.feeAmount;if(y=T,f=$n(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=Fe(r),v=Ln({account:e.externalWalletAddress,chain:C?.viemChain,transport:On(k)}),b=d?await v.sendTransaction({to:t,value:x,chain:C?.viemChain}):await v.sendTransaction({to:c,data:gt({abi:qe,functionName:"transfer",args:[t,x]}),chain:C?.viemChain});if((await pt(r).waitForTransactionReceipt({hash:b,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to embedded wallet failed");await da(e,h,m)}async function Tc(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=$n(e);if(c.length===0)throw new Error("No lock batches configured");const d=e.selectedAsset.asset,l=Le(e.selectedAsset.amount,d.decimals),p=d.chainId,u=e.escrowAddress||An(p),f=Tt(d.address),h=d.isNative||Pe(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:qe,functionName:"transfer",args:[u,v]})}]}),x=(v,b,S)=>{const E=y(v);if(!m)return[E,...b];const B=un([...b],i,S,{payoutAlreadyGross:b.some(T=>(T.tokenTransfers??[]).some(I=>I.from==="escrow"&&BigInt(I.amount)>=v))});return[E,...B]};let k=x(l,c),w=null,C;for(let v=0;v<4;v+=1){const b=await nt.estimateActionFees(js(i,k)),S=To(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},B=C?.grossAmount===E.grossAmount&&C?.netAmount===E.netAmount&&C?.feeAmount===E.feeAmount;if(w=S,C=E,c=$n(e,E),k=x(E.grossAmount,c,b),B)break}return w}const t=e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");let n=$n(e);if(n.length===0)throw new Error("No lock batches configured");let o=un([...n],t),s=null;for(let i=0;i<4;i+=1){const c=await nt.estimateActionFees(js(t,o)),d=To(c,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:qs(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=$n(e,l),o=un([...n],t,c,{payoutAlreadyGross:Vs(n,l)}),p)break}if(s)return s;const r=await nt.estimateActionFees(js(t,o));return To(r,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:qs(e)})}async function Mc(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=Fe(e.lockChainId),d=Ln({account:n,chain:c?.viemChain,transport:On(r)}),l=pt(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 Rc(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 Mc(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{await Fc(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{e.isDirectDeposit&&!e.isSourceDestToken?await Bc(e):await ua(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}}const pa=({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:B,primaryColor:T,dk:I}=lt(b,S),A=E.typography.fontFamily,F=Yt(Ht),M=F?.mode||"7702",U=!!F?.isWhitelistGateActive,W=M!=="7702",z=se(()=>F?.supportedChainIds??[],[F?.supportedChainIds]),q=se(()=>{if(U)return[];const Y=F?.allowedTokens;if(!Y||Y.length===0)return[];const ge=new Set(Y.map(_e=>_e.toLowerCase())),$e=[],wt=new Set;for(const _e of z){const $t=Fe(_e);for(const K of $t?.supportedTokens??[]){if(!ge.has(K.symbol.toLowerCase()))continue;const ie=`${_e}:${K.address.toLowerCase()}`;wt.has(ie)||(wt.add(ie),$e.push(Me(K.address)))}}return $e},[F?.allowedTokens,z,U]),D=B?I.cardBg:b?.assetSelector?.backgroundColor||b?.secondaryBackground||"#e9e9e9",P=B?`1px solid ${I.cardBorder}`:"0.5px solid #A8A8A7",O=B?"12px":"6px",j=B?I.textPrimary:"#111827",L=B?I.textSecondary:"#6b7280",J=se(()=>({...b,assetSelector:{...b?.assetSelector,backgroundColor:B?I.cardBg:b?.assetSelector?.backgroundColor,borderRadius:B?"12px":b?.assetSelector?.borderRadius},secondaryBackground:B?I.cardBg:b?.secondaryBackground}),[b,B]),pe=se(()=>B?{...E,colors:{...E.colors,secondary:I.cardBg,surfaceHover:I.hoverBg,border:I.cardBorder,borderHover:I.inputBorder}}:E,[B,E]),[N,re]=R(null),[ce,xe]=R(0),De=d?.selectedDurationIdx??ce,ue=d?.setSelectedDurationIdx??xe,[ve,H]=R(!1),[ne,X]=R(null),[oe,fe]=R(null),[Ee,we]=R(!1),[V,Q]=R(!1),[he,Ue]=R(null),[kt,zt]=R(!1),Lt=ae(0),[ot,st]=R(!1),[Z,Ne]=R(null);rr(),as();const{chain:Ce,address:_}=xo();ei();const Ke=ae(Ce);G(()=>{Ke.current=Ce},[Ce]);const Mt=Rn(),{isReady:pn,isAuthenticated:ft,isConnected:nn,address:Wt,provider:Zt,actions:We}=Mt,{externalWallet:fn,embeddedAddress:on,externalAddress:Cn,activeWallet:qt,activeAddress:sn}=eo(),{intentStatus:yt,startStatusPolling:ht,clearStatus:Qe}=kr({checkStepStatus:(Y,ge)=>nt.checkStepStatus(Y,ge),retryStep:async(Y,ge)=>{const[$e,wt]=Y.split("/"),_e=parseInt(wt||"0",10);await nt.executeStep($e,_e,ge,{action:"execute"})},maxRetries:3}),{assets:Xt,refetch:xt}=Fo({address:Wt,supportedChains:z,enabled:e&&nn&&!W&&!U,refetchInterval:3e4}),ye=se(()=>{if(U)return[];if(q.length===0)return Xt;const Y=new Set(q.map(ge=>ge.toLowerCase()));return Xt.filter(ge=>Y.has(ge.address.toLowerCase()))},[Xt,q,U]),bt=Dn(),et=Cn||_,hn=W?sn??et:bt,be=se(()=>{if(!h)return[];if(U)return m?[Me(m)]:[];const Y=new Set,ge=[],$e=wt=>{if(!wt)return;const _e=wt.toLowerCase();Y.has(_e)||(Y.add(_e),ge.push(Me(wt)))};if(m&&$e(m),W)for(const wt of q)$e(wt);return ge},[h,W,m,q,U]),Kt=se(()=>be.map(Y=>Y.toLowerCase()).sort().join(","),[be]),Rt=se(()=>JSON.stringify([...z||[]].sort()),[z]),[Nt,rt]=R([]),rn=ae(0),Jt=ae(async()=>{}),mn=le(async()=>{if(!h||!hn||be.length===0){rn.current++,rt([]);return}const Y=++rn.current,ge=Me(hn),$e=z&&z.length>0?z:[l],wt=be.map(de=>{const te=de.toLowerCase();if(m&&Ae(de,m)){const Be=Fe(l)?.supportedTokens?.find(Se=>Ae(Se.address,te));return{address:de,chainId:l,configToken:Be?{decimals:Be.decimals,symbol:Be.symbol,name:Be.name,logo:Be.logo}:void 0}}for(const Be of $e){const Se=Fe(Be)?.supportedTokens?.find(Bt=>Ae(Bt.address,te));if(Se)return{address:de,chainId:Be,configToken:{decimals:Se.decimals,symbol:Se.symbol,name:Se.name,logo:Se.logo}}}return{address:de,chainId:l}}),_e=new Map;for(const de of wt){const te=_e.get(de.chainId)||[];te.push(de),_e.set(de.chainId,te)}const $t=async(de,te)=>{try{const Be=await En(de,{address:te.address,abi:qe,functionName:"balanceOf",args:[ge]});let Se,Bt,Ct,Ve;if(te.configToken)Se=te.configToken.decimals,Bt=te.configToken.symbol,Ct=te.configToken.name,Ve=te.configToken.logo;else{const[Tn,vn,xn]=await Promise.all([En(de,{address:te.address,abi:qe,functionName:"decimals",args:[]}).catch(()=>18),En(de,{address:te.address,abi:qe,functionName:"symbol",args:[]}).catch(()=>"TOKEN"),En(de,{address:te.address,abi:qe,functionName:"name",args:[]}).catch(()=>"TOKEN")]);Se=Number(Tn),Bt=vn,Ct=xn}const it=!!m&&Ae(te.address,m)&&te.chainId===l;it&&r&&(Ve=r),it&&s&&!te.configToken&&(Bt==="TOKEN"&&(Bt=s),Ct==="TOKEN"&&(Ct=s));const an=parseFloat((Number(Be)/Math.pow(10,Se)).toFixed(6));return{address:te.address,name:Ct,symbol:Bt,decimals:Se,balance:Be,balanceFormatted:an,balanceUsd:0,logoURI:Ve,isNative:!1,chainId:te.chainId}}catch{return null}},K=await Promise.all(Array.from(_e.entries()).map(async([de,te])=>{let Be;try{Be=pt(de)}catch{return[]}const Se=[],Bt=[];for(const Ve of te){const it=Se.length;Se.push({address:Ve.address,abi:qe,functionName:"balanceOf",args:[ge]}),Ve.configToken||Se.push({address:Ve.address,abi:qe,functionName:"decimals",args:[]},{address:Ve.address,abi:qe,functionName:"symbol",args:[]},{address:Ve.address,abi:qe,functionName:"name",args:[]}),Bt.push({start:it,item:Ve})}let Ct=null;try{Ct=await Be.multicall({contracts:Se})}catch{Ct=null}return Ct?Bt.map(({start:Ve,item:it})=>{const an=Ct[Ve],Tn=an?.status==="success"?an.result:0n;let vn,xn,Un,Ie;if(it.configToken)vn=it.configToken.decimals,xn=it.configToken.symbol,Un=it.configToken.name,Ie=it.configToken.logo;else{const me=Ct[Ve+1],tt=Ct[Ve+2],bn=Ct[Ve+3];vn=me?.status==="success"?Number(me.result):18,xn=tt?.status==="success"?tt.result:"TOKEN",Un=bn?.status==="success"?bn.result:xn}const vt=!!m&&Ae(it.address,m)&&it.chainId===l;vt&&r&&(Ie=r),vt&&s&&!it.configToken&&(xn==="TOKEN"&&(xn=s),Un==="TOKEN"&&(Un=s));const _t=parseFloat((Number(Tn)/Math.pow(10,vn)).toFixed(6));return{address:it.address,name:Un,symbol:xn,decimals:vn,balance:Tn,balanceFormatted:_t,balanceUsd:0,logoURI:Ie,isNative:!1,chainId:it.chainId}}):(await Promise.all(te.map(Ve=>$t(Be,Ve)))).filter(Ve=>Ve!==null)}));if(Y!==rn.current)return;const ie=K.flat();rt(ie)},[h,hn,Kt,Rt,l,m,r,s]);G(()=>{Jt.current=mn},[mn]),G(()=>{if(!e||!h){rt([]);return}Jt.current();const Y=setInterval(()=>{Jt.current()},15e3);return()=>clearInterval(Y)},[h,e,hn,Kt,Rt,l,m]);const kn=le(()=>{mn()},[mn]),dt=se(()=>Nt.filter(Y=>Y.balance>0n),[Nt]),It=se(()=>{if(W)return dt.map(ge=>({...ge,_source:"wallet"}));if(!h)return ye;const Y=[];for(const ge of dt)Y.push({...ge,_source:"wallet"});for(const ge of ye)Y.push({...ge,_source:"spice"});return Y},[W,h,dt,ye]),Ye=se(()=>U?m?It.filter(Y=>Ae(Y.address,m)&&Y.chainId===l):[]:It,[It,U,m,l]),Dt=ae(null),Fn=ae(null);G(()=>{Fn.current=N},[N]),G(()=>{!U||!N?.asset||m&&Ae(N.asset.address,m)&&N.asset.chainId===l||re(null)},[U,N?.asset,m,l]),G(()=>{e||(re(null),X(null),fe(null),we(!1),Q(!1),Ue(null),H(!1),st(!1),Ne(null),zt(!1),Qe())},[e,Qe]),G(()=>{i&&i.assetAmount!==(N?.amount||"")&&re(Y=>Y&&{...Y,amount:i.assetAmount})},[i?.assetAmount]),G(()=>{c&&c.assetAmount!==(N?.amount||"")&&re(Y=>Y&&{...Y,amount:c.assetAmount})},[c?.assetAmount]),G(()=>{if(!W&&yt?.overallStatus==="success"&&yt.intentId&&Dt.current!==yt.intentId&&Wt&&yt.steps.find(Y=>Y.transactionHash)?.transactionHash){Dt.current=yt.intentId;const Y=Fn.current;if(!Y?.asset||!Y.amount||Y.asset._source==="wallet"||Le(Y.amount,Y.asset.decimals)===0n)return;xt()}},[yt,Wt,l,xt,W]);const Ge=parseFloat(N?.amount||"")||0,at=se(()=>N?.asset?N.asset._source==="wallet"?N.asset.balanceFormatted??0:ye.find(Y=>Ae(Y.address,N.asset.address)&&Y.chainId===N.asset.chainId)?.balanceFormatted??0:0,[N?.asset,ye]),jt=Ge>0&&(he?parseFloat(ct(he.grossAmount,he.decimals))>at:Ge>at),mt=d?.selectedDuration??p[De]??p[0],Oe=se(()=>!N?.asset||!m?!1:Ae(N.asset.address,m)&&N.asset.chainId===l,[N?.asset,m,l]),He=se(()=>Ge<=0?0:Oe?Ge:!k||k<=0?0:Ge/k,[Ge,k,Oe]),Ot=se(()=>He<=0?null:He.toLocaleString(void 0,{maximumFractionDigits:2}),[He]),At=u&&He>0&&mt?u(He,mt.months):void 0,gn=se(()=>Ge<=0?"$0.00":Oe&&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,Oe]),ze=se(()=>{if(!Ot)return null;const Y=parseFloat(Ot.replace(/,/g,""));return Oe&&k?(Y*k).toLocaleString(void 0,{maximumFractionDigits:2}):k?(Y*k).toLocaleString(void 0,{maximumFractionDigits:2}):null},[Ot,k,Oe]),Pn=le(Y=>{re(ge=>({asset:Y,amount:ge?.asset?.address===Y.address&&ge?.asset?.chainId===Y.chainId&&ge.amount||""})),X(null),fe(null),Q(!1),Ue(null),c?.setSelectedAsset&&c.setSelectedAsset({symbol:Y.symbol,address:Y.address,decimals:Y.decimals,chainId:Y.chainId})},[c?.setSelectedAsset]),yn=le(Y=>{re(ge=>ge&&{...ge,amount:Y}),X(null),fe(null),Q(!1),Ue(null),i&&i.setAssetAmount(Y),c&&c.setAssetAmount(Y)},[i,c]),$=le(Y=>{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:Y?.amount??N.amount,amountWei:Y?.amountWei??Le(N.amount,N.asset.decimals),grossAmount:Y?.grossAmount,grossAmountWei:Y?.grossAmountWei,feeAdjusted:!!Y})}return o},[o,N]),ee=ae(null),ke=se(()=>!N?.asset||Ge<=0?!1:W?!Oe&&!x:!0,[N,Ge,W,Oe,x]),Ze=le(()=>Tc(ee.current),[]),St=se(()=>!N?.asset||Ge<=0?null:`${N.asset.address.toLowerCase()}:${N.asset.chainId}:${N.amount??""}`,[N?.asset?.address,N?.asset?.chainId,N?.amount,Ge]);G(()=>{if(!e||ve)return;if(!N?.asset||Ge<=0){fe(null),we(!1),Q(!1),Ue(null);return}if(!ke){fe(null),we(!1),Q(!0),Ue(null);return}let Y=!1;const ge=async _e=>{const $t=++Lt.current;_e||(fe(null),Q(!1),we(!0));try{const K=await Ze();if(Y||Lt.current!==$t)return;fe(null),Q(!0),Ue(K)}catch(K){if(Y||Lt.current!==$t)return;_e||(fe(In(K,"Unable to calculate fees for this lock.")),Q(!1))}finally{!Y&&Lt.current===$t&&!_e&&we(!1)}},$e=window.setTimeout(()=>{ge(!1)},250),wt=window.setInterval(()=>{ge(!0)},3e4);return()=>{Y=!0,clearTimeout($e),window.clearInterval(wt)}},[e,ve,St,ke,Ze]),G(()=>{if(yt?.overallStatus==="success"){const Y=yt.steps.find(ge=>ge.transactionHash);y?.(Y?.transactionHash)}},[yt?.overallStatus,y]);const Xe=h&&N?.asset?._source==="wallet"&&N?.asset?.chainId===l,ut=le(()=>Rc(ee.current),[]),Je=!!N?.asset&&Ge>0&&!jt&&!ve&&(!ke||V&&!Ee&&!oe),Re=ne||oe,Et=g("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[a(Ss,{color:L}),g("p",{style:{fontSize:"13px",color:L,margin:0,lineHeight:"1.5"},children:["Add ",s," by converting assets from your account"]})]});if(ee.current={selectedAsset:N,parsedAmount:Ge,selectedDuration:mt,isInsufficientBalance:jt,isSemi7702:W,isSourceDestToken:Oe,isDirectDeposit:Xe,requiresRelayerFeeEstimate:ke,address:Wt,embeddedWalletAddress:bt,providerEmbeddedAddress:on,externalWallet:fn,externalWalletAddress:et,activeSignerWallet:qt,activeSignerAddress:sn,isConnected:nn,ready:pn,authenticated:ft,provider:Zt,actions:We,lockChainId:l,escrowAddress:f,onLockExecute:x,onLockSuccess:y,buildSpicenetBatch:v,resolveLockBatches:$,startStatusPolling:ht,refreshSpiceAssets:xt,refreshWalletAssets:kn,ui:{setError:X,setIsExecuting:H,setShowStatusPanel:zt}},!e)return null;const je={backgroundColor:D,border:P,borderRadius:O,padding:"16px",marginBottom:"16px"};return a(jn,{isOpen:e,onClose:t,title:`Add ${s} to your account`,subtitle:Et,styles:b,dark:B,footerLinkText:"Spicenet accounts \u2192",overlayContent:ot?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(Es,{onClick:C,color:T,fontFamily:A})}),a("div",{style:{marginTop:"10px",fontSize:"13px",color:L,fontFamily:A},children:a(Eo,{assets:Ye,selectedAsset:N??void 0,onAssetSelect:Pn,onAmountChange:yn,label:"Amount",showBalance:!0,showMaxButton:!0,theme:pe,styles:J})}),a("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:L,fontFamily:A},children:gn})]}),g("div",{style:je,children:[g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:B?`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:B?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:Ot??"0.00"}),g("div",{style:{fontSize:"12px",color:L,fontFamily:A,marginTop:"2px"},children:["~$",ze??"0.00"]})]})]}),g("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:B?`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:L,fontFamily:A},children:"Lock Duration"}),a(Qn,{color:L})]}),a(mc,{options:p,selectedIndex:De,onSelect:ue,primaryColor:T,dark:B,textPrimary:j,textSecondary:L})]}),g("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[a(xc,{durationMonths:mt?.months,fontFamily:A,dark:B,textPrimary:j,textSecondary:L}),u&&a(wc,{votes:At,fontFamily:A,dark:B,textPrimary:j,textSecondary:L})]})]}),ke&&a(Oo,{fontFamily:A,textPrimary:j,textSecondary:L,cardBg:D,cardBorder:P,resolvedDark:B,darkCardBorder:I.cardBorder,primaryColor:T,feePreview:he,isLoading:Ee,errorText:oe}),Re&&a(po,{variant:"error",palette:I,fontFamily:A,style:{marginBottom:"12px"},children:Re}),a(Ft,{variant:"outline",fullWidth:!0,onClick:ut,disabled:!Je,loading:ve,dark:B,styles:{...b,button:{...b?.button,backgroundColor:T}},children:ve?Xe&&!Oe?"DEPOSITING...":Oe?"LOCKING...":"CONVERTING...":Ee&&ke?"CALCULATING FEES...":Xe&&!Oe?`DEPOSIT ${s}`:Oe?`LOCK ${s}`:`CONVERT TO ${s}`}),a(Cc,{isOpen:ot,data:Z,isLocking:ve,lockError:Re,onContinue:ut,onClose:()=>st(!1),primaryColor:T,fontFamily:A,dark:B}),yt&&kt&&a("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:B?"rgba(0, 0, 0, 0.45)":"rgba(255, 255, 255, 0.55)",backdropFilter:"blur(2px)",WebkitBackdropFilter:"blur(2px)",borderRadius:O},children:a(Rs,{type:"deposit",showStepBreakdown:!1,isOpen:!!yt&&yt.overallStatus!=="processing",isProcessing:ve||yt?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{Qe(),zt(!1),ut()},onNewTx:()=>{Qe(),zt(!1),re(null),Dt.current=null,xt(),kn()},onClose:()=>{Qe(),zt(!1)},onComplete:()=>{Qe(),zt(!1),re(null),Dt.current=null,xt(),kn()},results:yt?.overallStatus==="success"||yt?.overallStatus==="failed"?yt.steps.map(Y=>({asset:{symbol:N?.asset?.symbol||s,address:N?.asset?.address||""},txHash:Y.transactionHash||"",success:Y.status==="success",amount:N?.amount})):void 0,chainName:cn(l),explorerUrl:io(l,"").replace(/\/tx\/.*$/,"")||void 0,theme:E,styles:b,dark:B})})]})})},Dc="0xa9059cbb";function Wc(e,t,n){return Pe(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:gt({abi:Vt,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(Dc)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function $o(e,t,n){if(!t)return[e];const o=await t(n);return o?[o,e]:[e]}function so(e){return e.filter(t=>t.domain!=="spicenet")}function _o(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 mo(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 Nc(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=Le(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,B=(T,I)=>({token:T,from:c?"solver":"escrow",to:C,amount:I});if(k===0n)return[S];if(m&&y){const T=x??Nn(h.asset,l)??h.asset.address,I=t?.fundingAmountOverride??y.amountInMax,A=E?[B(T,I)]:[],F={to:T,value:0n,data:gt({abi:Vt,functionName:"approve",args:[y.calls[0]?.to,y.amountInMax]})},M={chainId:l,calls:[F,...y.calls,...b],tokenTransfers:[...A,...S.tokenTransfers??[]]};return E?$o(M,f,{userAddress:C,destinationChainId:l,deliveryToken:T,deliveryAmount:I,deliveryRecipient:C,deliveryTransfers:_o(M),sourceAsset:h.asset}):[M]}if(E){const T=x??Nn(h.asset,l)??o.address,I=t?.fundingAmountOverride??k,A={...S,tokenTransfers:[B(T,I),...S.tokenTransfers??[]]};return $o(A,f,{userAddress:C,destinationChainId:l,deliveryToken:T,deliveryAmount:I,deliveryRecipient:C,deliveryTransfers:_o(A),sourceAsset:h.asset})}return[S]}async function Pc(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??Le(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,B={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,B),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,{...B,netAmount:t?.actionAmountOverride??x}),{feeCall:O,remainingCalls:j}=Ys(P,d,f,B.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,{...B,netAmount:t?.actionAmountOverride??x}),{feeCall:O,remainingCalls:j}=Ys(P,d,f,B.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",F=u&&I;if(!(A||F))return[{chainId:r,calls:T}];const M=F&&n.asset.chainId!==r?{chainId:n.asset.chainId,calls:[Wc(Tt(n.asset.address),v,An(n.asset.chainId))]}:null,U=(P,O)=>({token:P,from:F?"solver":"escrow",to:o,amount:O}),W=(P,O)=>F?[{token:P,from:"escrow",to:ai,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,{...B,netAmount:t?.actionAmountOverride??x}),{feeCall:O,remainingCalls:j}=Ys(P,d,f,B.feeToken),L={chainId:r,calls:[...O?[O]:[],...h.calls,...j],tokenTransfers:[...W(y,S),U(y,b)]},J=await $o(L,l,{userAddress:o,destinationChainId:r,deliveryToken:y,deliveryAmount:b,withdrawalAmount:S,deliveryRecipient:o,deliveryTransfers:_o(L),sourceAsset:n.asset});return M?[M,...J]:J}const z=y??Nn(n.asset,r)??i.address,q={chainId:r,calls:T,tokenTransfers:[...W(z,S),U(z,b)]},D=await $o(q,l,{userAddress:o,destinationChainId:r,deliveryToken:z,deliveryAmount:b,withdrawalAmount:S,deliveryRecipient:o,deliveryTransfers:_o(q),sourceAsset:n.asset});return M?[M,...D]:D}async function Uc(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=Hl(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 zc(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 Lc(e,t){const n=ct(e,t);return n.includes(".")?n.replace(/\.?0+$/,"")||"0":n}async function Oc(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=Xn(m,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),x=y?mo(y.gasFee,y.decimals,t.decimals):0n,k=y?mo(y.spicenetFee,y.decimals,t.decimals):0n,w=zc(t.balance,x,k,t.balance);return w>0n?Lc(w,t.decimals):null}async function Hc(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:B,estimateGasless:T,estimateRequiredGrossFunding:I}=e;if(!t?.asset)return null;if(n){if(o<=0||s&&!r||i&&c)return null;const D=Le(d,l.decimals),P=u||Nn(t.asset,m)||t.asset.address||l.address,O={chainId:m,tokenAddress:P,symbol:Pt(P,m)?.symbol??t.asset.symbol,decimals:Pt(P,m)?.decimals??t.asset.decimals};if(i){const re=f||h;if(!re)return null;const ce=re,xe=s?r?.amountInMax??0n:D;if(xe===0n)return null;const De=await I(xe,H=>E({fundingAmountOverride:H}).then(ne=>un(so(ne),ce)),P,{userOverride:re,useCustomTransfers:!0}),ue=un(so(await E({fundingAmountOverride:De})),ce),ve=await T(ue,P,De,{userOverride:re,useCustomTransfers:!0,feeExecutionMode:p});return Xn(ve,O)}if(!y||!x||!k||!w)return null;const j=f||h||x,L=s?r?.amountInMax??0n:D;if(L===0n)return null;const J=await I(L,re=>E({fundingAmountOverride:re}).then(ce=>un(so(ce),j)),P,{useCustomTransfers:!0});let pe=un(so(await E({fundingAmountOverride:J})),j);const N=await T(pe,P,J,{useCustomTransfers:!0,feeExecutionMode:p});return Xn(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 F=Le(t.amount,t.asset.decimals),M=await B();if(M.length===0)return null;const U=i&&t.asset?._source==="wallet"&&t.asset.chainId===m,W={chainId:m,tokenAddress:S,symbol:Pt(S,m)?.symbol??l.symbol,decimals:Pt(S,m)?.decimals??l.decimals};if(U){const D=await nt.estimateBatchGas({user:A,outputToken:S,stepIndex:0,chainBatches:M}),P=Yo(F,10n),O=P+D.gasFee;return{...W,grossAmount:F+O,netAmount:F,totalFee:O,gasFee:D.gasFee,spicenetFee:P,bridgeFee:0n,gasQuoteSource:D.gasQuoteSource}}const z=M.some(D=>D.tokenTransfers?.length),q=await T(M,S,F,z?{userOverride:A,useCustomTransfers:!0,feeExecutionMode:p}:p?{userOverride:A,feeExecutionMode:p}:{userOverride:A});return Xn(q,W)}const jc=10n;function fa(e,t){const n=e.selectedAsset?.asset;if(!n||n?._source!=="wallet")return;const o=Nn(n,e.resolvedChainId);if(!o||!Ae(o,e.executionTokenAddress))return;const s=Pt(e.executionTokenAddress,e.resolvedChainId),r=mo(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 ha(e){const t=Pt(e.executionTokenAddress,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:t?.symbol??e.destinationToken.symbol,decimals:t?.decimals??e.destinationToken.decimals}}function ma(e,t,n){const o=Xn(e,ha(t));if(!o)return;const s=Yo(n,jc),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 go(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 ga(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=vo({abi:Vt,data:c.data});if(d.functionName!=="transfer")continue;const l=d.args[0].toLowerCase(),p=d.args[1];l===wo.toLowerCase()?o+=p:l===Wn.toLowerCase()&&(s+=p)}catch{continue}}return{spicenetFee:o,gasFee:s}}function Qc(e,t,n){const o=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,s=ga(e,t.resolvedChainId,o);return s.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||s.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:go(s.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&go(s.gasFee,n.feeBreakdown.gasFee,100n)}function Vc(e,t){return e?go(e.grossAmount,t.grossAmount,100n)&&go(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&go(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&go(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}async function qc(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 ya(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 Kc(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=Le(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=>No(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=Xn(m,ha(e));u=e.feeExecutionMode==="user-transfer"&&y?ma(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"&&(fa(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=ma(h,e,o);if(!y)return null;const x=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&e.resolvedTokenIn?e.resolvedTokenIn:e.executionTokenAddress;ga(m,e.resolvedChainId,x);const k=Vc(f,y),w=Qc(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 Kc(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=Le(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 B=await nt.estimateBatchGas({user:n,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:c}),T=Yo(s,10n),I=T+B.gasFee;l=s+I,e.feeExecutionMode==="user-transfer"&&(f={grossAmount:l,netAmount:r,combinedFeeAmount:I,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:T,gasFee:B.gasFee,bridgeFee:0n}})}else{const B=await e.gasless.estimateGasless(c,e.executionTokenAddress,0n,d),T=Xn(B,{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:Pt(e.executionTokenAddress,e.resolvedChainId)?.symbol??e.destinationToken.symbol,decimals:Pt(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=Pt(e.executionTokenAddress,e.resolvedChainId),m=i?l:mo(l,h?.decimals??e.destinationToken.decimals,o.decimals);fa(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 B=await k.request({method:"eth_chainId"});w=parseInt(B,16)}catch{w=null}w!==y&&(e.ui.setStatusMsg("Switching source network..."),await Yn(k,y));const C=Fe(y),v=Ln({account:e.externalWalletAddress,chain:C?.viemChain,transport:On(k)}),b=Tt(o.address),S=o.isNative||Pe(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:Vt,functionName:"transfer",args:[x,m]}),chain:C?.viemChain});if((await pt(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 ya(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=Le(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=Fe(e.resolvedChainId),p=Ln({account:o,chain:l?.viemChain,transport:On(c)}),u=pt(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 Yc(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=Le(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=Fe(o),h=Ln({account:e.externalWalletAddress,chain:f?.viemChain,transport:On(p)}),m=Tt(n.address),y=n.isNative||Pe(m)?await h.sendTransaction({to:l,value:d,chain:f?.viemChain}):await h.sendTransaction({to:m,data:gt({abi:Vt,functionName:"transfer",args:[l,d]}),chain:f?.viemChain});if((await pt(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 Gc(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 ya(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const s=e.selectedAsset.asset,r=Le(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 Yc(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=Le(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=>un(so(x),c)),r,o);let l=d,p=un(so(await e.gasless.buildPayChainBatches({fundingAmountOverride:d})),c);const u=await e.gasless.estimateGasless(p,r,d,o),f=Xn(u,{chainId:e.resolvedChainId,tokenAddress:r,symbol:Pt(r,e.resolvedChainId)?.symbol??s.symbol,decimals:Pt(r,e.resolvedChainId)?.decimals??s.decimals})?.grossAmount??d;f!==d&&(l=f),p=un(so(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 Zc=({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(ba,{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(to,{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(Xc,{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=tn(Zc),ba=({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)}),Xc=({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=ae(null),[B,T]=R(null),[I,A]=R(null);G(()=>{y||S(u||"")},[u,y]);const F=W=>{let z=W;z.startsWith(".")&&(z="0"+z);const q=co(z);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 z=10**n,q=Math.floor(v*W/100*z)/z,D=uo(q,n);S(D),E.current&&clearTimeout(E.current),k?.(D)},U=v>0?parseFloat(b||"0")/v*100:0;return G(()=>()=>{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(ba,{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(to,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:b,onChange:W=>F(W.target.value),placeholder:"0.0",fontFamily:w,color:r,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):a(to,{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,z)=>{const q=Math.abs(U-W)<1,D=z===4,P=W/100,O=B===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:dn.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 wa(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 Jc(e,t){return!t||t.length===0||t.some(n=>Ae(n,e.address))?!0:Object.keys(e.chainTokens??{}).some(n=>{const o=ho(n);return o?t.some(s=>Ae(s,o.address)):!1})}function $c(e){const{destinationToken:t,supportedSourceAssets:n,sourceChains:o,enabled:s}=e,r=(Yt(Ht)?.mode||"7702")!=="7702",i=Dn(),{externalAddress:c,embeddedAddress:d,activeAddress:l}=eo(),p=i||d,{assets:u,refetch:f}=Fo({address:p,supportedChains:o,enabled:s&&!r&&!!p,refetchInterval:3e4}),h=se(()=>r?[]:u.filter(B=>Jc(B,n)),[u,n,r]),m=r?l??c:i,y=se(()=>{const B=new Set,T=[],I=A=>{if(!A)return;const F=A.toLowerCase();B.has(F)||(B.add(F),T.push(Me(A)))};if(I(t.address),r&&n)for(const A of n)I(A);return T},[r,t.address,n]),x=se(()=>y.map(B=>B.toLowerCase()).sort().join(","),[y]),k=se(()=>JSON.stringify([...o||[]].sort()),[o]),[w,C]=R([]),v=ae(0),b=ae(async()=>{}),S=le(async()=>{if(!s||!m||y.length===0){v.current++,C([]);return}const B=++v.current,T=Me(m),I=r?o&&o.length>0?o:[t.chainId]:[t.chainId],A=[];for(const W of y){const z=W.toLowerCase();if(z===Qt)continue;if(z===t.address.toLowerCase()){const D=Fe(t.chainId)?.supportedTokens?.find(P=>Ae(P.address,z));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=Fe(D)?.supportedTokens?.find(O=>Ae(O.address,z));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 F=new Map;for(const W of A){const z=F.get(W.chainId)||[];z.push(W),F.set(W.chainId,z)}const M=async(W,z)=>{try{const q=await En(W,{address:z.address,abi:Vt,functionName:"balanceOf",args:[T]});let D,P,O,j;if(z.configToken)D=z.configToken.decimals,P=z.configToken.symbol,O=z.configToken.name,j=z.configToken.logo;else{const[pe,N,re]=await Promise.all([En(W,{address:z.address,abi:Vt,functionName:"decimals"}).catch(()=>18),En(W,{address:z.address,abi:Vt,functionName:"symbol"}).catch(()=>"TOKEN"),En(W,{address:z.address,abi:Vt,functionName:"name"}).catch(()=>"TOKEN")]);D=Number(pe),P=N,O=re}const L=Ae(z.address,t.address)&&z.chainId===t.chainId;L&&t.logoURI&&(j=t.logoURI),L&&!z.configToken&&P==="TOKEN"&&(P=t.symbol,O=t.symbol);const J=parseFloat((Number(q)/Math.pow(10,D)).toFixed(6));return{address:z.address,name:O,symbol:P,decimals:D,balance:q,balanceFormatted:J,balanceUsd:0,logoURI:j,isNative:!1,chainId:z.chainId}}catch{return null}},U=await Promise.all(Array.from(F.entries()).map(async([W,z])=>{let q;try{q=pt(W)}catch{return[]}const D=[],P=[];for(const j of z){const L=D.length;D.push({address:j.address,abi:Vt,functionName:"balanceOf",args:[T]}),j.configToken||D.push({address:j.address,abi:Vt,functionName:"decimals"},{address:j.address,abi:Vt,functionName:"symbol"},{address:j.address,abi:Vt,functionName:"name"}),P.push({start:L,item:j})}let O=null;try{O=await q.multicall({contracts:D})}catch{O=null}return O?P.map(({start:j,item:L})=>{const J=O[j],pe=J?.status==="success"?J.result:0n;let N,re,ce,xe;if(L.configToken)N=L.configToken.decimals,re=L.configToken.symbol,ce=L.configToken.name,xe=L.configToken.logo;else{const ve=O[j+1],H=O[j+2],ne=O[j+3];N=ve?.status==="success"?Number(ve.result):18,re=H?.status==="success"?H.result:"TOKEN",ce=ne?.status==="success"?ne.result:re}const De=Ae(L.address,t.address)&&L.chainId===t.chainId;De&&t.logoURI&&(xe=t.logoURI),De&&!L.configToken&&re==="TOKEN"&&(re=t.symbol,ce=t.symbol);const ue=parseFloat((Number(pe)/Math.pow(10,N)).toFixed(6));return{address:L.address,name:ce,symbol:re,decimals:N,balance:pe,balanceFormatted:ue,balanceUsd:0,logoURI:xe,isNative:!1,chainId:L.chainId}}):(await Promise.all(z.map(j=>M(q,j)))).filter(j=>j!==null)}));B===v.current&&C(U.flat())},[s,r,m,x,k,t.address,t.chainId,t.symbol,t.logoURI]);G(()=>{b.current=S},[S]),G(()=>{if(!s){C([]);return}b.current();const B=setInterval(()=>{b.current()},15e3);return()=>clearInterval(B)},[s,r,m,x,k,t.address,t.chainId]);const E=le(()=>{S()},[S]);return{displayAssets:se(()=>{const B=[],T=w.filter(A=>A.balance>0n);for(const A of T)B.push({...A,_source:"wallet"});for(const A of h)B.push({...A,_source:"spice"});const I=t.address.toLowerCase();return B.sort((A,F)=>wa(A,I,t.chainId)-wa(F,I,t.chainId)),B},[w,h,t.address,t.chainId]),filteredSpiceAssets:h,walletAssets:w,embeddedWalletAddress:p,externalAddress:c,isNon7702:r,refreshSpiceAssets:f,refreshWalletAssets:E}}async function Ca(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 pt(r).simulateContract({address:i.quoterV2,abi:ii,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 ka(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(s=>Ca({...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 _c=[{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 ed(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 pt(r).simulateContract({address:i.quoterV2,abi:_c,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 td(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(s=>ed({...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 va(e){return e.type==="swap"}const Gs=.02,nd=[1,8453,42161,10,137,43114,56],od="https://api.1inch.dev/swap/v6.0";function Ia(e,t){return ci(e,t)}function Aa(e){const t=e?.baseUrl??od;return{name:"1inch",chainIds:e?.chainIds??nd,resolve:async(n,o,s)=>{const r=n.maxSlippage??Gs,i=r*100,c=Pe(n.tokenIn)?lr:n.tokenIn,d=Pe(n.tokenOut)?lr:n.tokenOut,l=Pe(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=Ia(m,r),x=[];return h.tx.to&&!l&&x.push({to:n.tokenIn,value:0n,data:gt({abi:Vt,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 Sa=[4114,5115],Zs={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},Ea={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[3e3]};function Ba(e){return{name:"satsuma",chainIds:e.chainIds??Sa,resolve:async(t,n,o)=>{const s=t.maxSlippage??Gs,r=Pe(t.tokenIn);let i;try{i=await ka({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=Ia(i.amountOut,s),d=[];return r||d.push({to:t.tokenIn,value:0n,data:gt({abi:Vt,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),d.push({to:e.swapRouter,value:r?t.amountIn:0n,data:gt({abi:li,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??Sa,resolve:async(t,n,o)=>{const s=t.maxSlippage??Gs,r=Pe(t.tokenIn);let i;try{i=await td({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:sd,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 sd=[{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 Ta(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(Ba(e.satsuma)),t.push(Aa(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(!va(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 rd(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 ad=Ta({satsuma:Zs});function id(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,B]=R(null),T=ae(null),I=ae(null),A=ae(0),F=ae(new Map),M=se(()=>ad,[]),U=se(()=>rd({customVenues:[Fa(Zs),Fa(Ea)]}),[]),W=se(()=>{if(!n?.asset)return null;const N=Nn(n.asset,s);if(N)return N;const re=qn(n.asset.address,s,n.asset.chainId);return re?re.address:null},[n?.asset,s]),z=se(()=>n?.asset?Vo(n.asset,s):[],[n?.asset,s]),q=se(()=>z.map(N=>N.toLowerCase()).join(","),[z]);G(()=>{let N=!1;if(I.current&&(clearTimeout(I.current),I.current=null),!n?.asset||z.length<=1){B(null);return}return I.current=setTimeout(async()=>{const re=t==="input"?n.amount:i||"0";let ce=0n;try{ce=t==="input"?Le(re,n.asset.decimals):0n}catch{ce=0n}try{const xe=await Hr(n.asset,s,{requiredAmount:ce});N||B(xe)}catch{N||B(null)}},400),()=>{N=!0,I.current&&(clearTimeout(I.current),I.current=null)}},[n?.asset,n?.amount,s,z.length,q,t,i]);const D=se(()=>E??W,[E,W]),P=se(()=>!n?.asset||!D?[]:[D,...z.filter(N=>N.toLowerCase()!==D.toLowerCase())],[n?.asset,D,z]),O=se(()=>!n?.asset||!Bo(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,L=t==="output"&&parseFloat(i||"0")===0,J=!!n?.asset&&!O&&!j&&!L,pe=J?b??D:D;return G(()=>{T.current&&clearTimeout(T.current);const N=t==="input"?n?.amount:i,re=parseFloat(N||"0");if(!J||!Number.isFinite(re)||re<=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 ce=n.asset.decimals;let xe;try{xe=t==="input"?Le(n.amount,ce):Le(i||"0",o.decimals)}catch{A.current++,p("Invalid amount"),d(!1);return}const De=++A.current,ue=()=>De!==A.current;d(!0);const ve=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 ne=null,X=null;for(const fe of P){const Ee=`${t}:${s}:${fe.toLowerCase()}:${o.address.toLowerCase()}:${xe.toString()}`,we=F.current.get(Ee);if(we&&we.expiresAt>Date.now()&&we.resolvedSwap){ne=we.resolvedSwap,X=fe;break}const V=await H.resolve({type:"swap",tokenIn:fe,tokenOut:o.address,amountIn:xe},s,r);if(ue())return;if(V){F.current.set(Ee,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:V}),ne=V,X=fe;break}}if(!ne||!X)throw new Error("No liquidity for this pair");S(X),v(ne.amountOut),x(ne),w(null);const oe=parseFloat(ct(ne.amountOut,o.decimals));f(oe<.01?oe.toPrecision(4):oe.toLocaleString(void 0,{maximumFractionDigits:6})),m(null),p(null)}else{let H=null,ne=null;for(const X of P){const oe=`${t}:${s}:${X.toLowerCase()}:${o.address.toLowerCase()}:${xe.toString()}`,fe=F.current.get(oe);if(fe&&fe.expiresAt>Date.now()&&fe.exactOutputSwap){H=fe.exactOutputSwap,ne=X;break}try{const Ee=await U.getQuote({tokenIn:X,tokenOut:o.address,amountOut:xe},s,r);if(ue())return;F.current.set(oe,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:Ee}),H=Ee,ne=X;break}catch{if(ue())return}}if(!H||!ne)throw new Error("No liquidity for this pair");S(ne),w(H),x(null),v(null),m(parseFloat(ct(H.amountIn,ce)).toFixed(6)),f(null),p(null)}}catch(H){if(ue())return;const ne=H instanceof Error?H.message:"Failed to get quote";p(ne),f(null),m(null),x(null),w(null),v(null),S(null)}finally{ue()||d(!1)}},ve),()=>{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 Ma={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},Ra=["signing-delegation","signing-intent","submitting","executing"],ld=()=>{},Da=({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:B,onError:T})=>{const I=u==="output",{theme:A,dark:F,primaryColor:M,dk:U,palette:W,fontFamily:z,monoFont:q,inputDark:D,cardBg:P,cardBorder:O,textPrimary:j,textSecondary:L,subtitleText:J}=lt(C,v),pe=se(()=>D?{...A,colors:{...A.colors,secondary:U.cardBg,surfaceHover:U.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:A,[D,A,U.cardBg,U.hoverBg]),N=o.chainId,re=Yt(Ht),ce=(re?.mode||"7702")!=="7702",xe=!!re?.isWhitelistGateActive,De=se(()=>s??re?.supportedChainIds??[],[s,re?.supportedChainIds]),ue=se(()=>{if(xe)return[];if(r)return r;const me=re?.allowedTokens;if(!me||me.length===0)return;const tt=new Set(me.map(wn=>wn.toLowerCase())),bn=[],Mn=new Set;for(const wn of De){const ao=Fe(wn);for(const os of ao?.supportedTokens??[]){if(!tt.has(os.symbol.toLowerCase()))continue;const _s=os.address.toLowerCase();Mn.has(_s)||(Mn.add(_s),bn.push(os.address))}}return bn},[r,re?.allowedTokens,De,xe]),ve=Rn(),{address:H,isConnected:ne,isReady:X,isAuthenticated:oe,provider:fe}=ve,{executeGasless:Ee,estimateGasless:we}=Jo(),{externalWallet:V,externalAddress:Q,embeddedAddress:he,activeWallet:Ue,activeAddress:kt}=eo(),zt=Dn()||he,{displayAssets:Lt,filteredSpiceAssets:ot,embeddedWalletAddress:st,refreshSpiceAssets:Z,refreshWalletAssets:Ne}=$c({destinationToken:o,supportedSourceAssets:ue,sourceChains:De,enabled:e&&(ce?!!Q:!!zt)}),Ce=xe||I||ce?Lt:ot,[_,Ke]=R(null),[Mt,pn]=R(m||""),[ft,nn]=R(!1),[Wt,Zt]=R(null),[We,fn]=R("idle"),[on,Cn]=R(""),[qt,sn]=R(null),[yt,ht]=R(!1),[Qe,Xt]=R(null),[xt,ye]=R(null),[bt,et]=R(!1),[hn,be]=R(!1),[Kt,Rt]=R(null),Nt=ae(_),rt=ae(!1),rn=ae(null),Jt=ae(0),mn=ae(null),kn=ae(null);G(()=>{Nt.current=_},[_]);const dt=y==="adjustable"?Mt:m||"0",It=st||he||H,{isQuoting:Ye,quoteError:Dt,estimatedOutput:Fn,resolvedSwap:Ge,exactOutputSwap:at,quoteAmountOut:jt,resolvedTokenIn:mt,isDirect:Oe,needsSwap:He,selectedIsEquivalent:Ot}=id({direction:u,selectedAsset:_,destinationToken:o,chainId:N,recipient:It,paymentAmount:dt}),At=I?parseFloat(dt||"0"):parseFloat(_?.amount||"")||0,gn=_?.asset?._source==="wallet",ze=!!_?.asset&&gn&&_.asset.chainId!==N,Pn=se(()=>_?.asset?ot.find(me=>Ae(me.address,_.asset.address))?.balanceFormatted??0:0,[_,ot]),yn=gn?_?.asset.balanceFormatted??0:Pn,$=se(()=>{if(!_?.asset)return!1;if(I)return xt?mo(xt.grossAmount,xt.decimals,_.asset.decimals)>_.asset.balance:Ot||Oe?At>_.asset.balanceFormatted:at?parseFloat(ct(at.amountInMax,_.asset.decimals))>_.asset.balanceFormatted:!1;if(xt){const me=mo(xt.grossAmount,xt.decimals,_.asset.decimals);return gn?me>_.asset.balance:parseFloat(ct(me,_.asset.decimals))>yn}return At>yn},[_,I,xt,Ot,At,at,yn,gn,Oe]);G(()=>{e||(Ke(null),Zt(null),nn(!1),fn("idle"),Cn(""),sn(null),ht(!1),Xt(null),ye(null),et(!1),be(!1),Rt(null),rt.current=!1,y==="adjustable"&&pn(m||""),rn.current&&(rn.current.abort(),rn.current=null))},[e]);const ee=le(me=>{Ke(tt=>({asset:me,amount:tt?.asset?.address===me.address&&tt?.asset?.chainId===me.chainId&&tt.amount||""})),Zt(null),Rt(null),be(!1)},[]),ke=le(me=>{Ke(tt=>tt&&{...tt,amount:me}),Zt(null),Rt(null),be(!1)},[]),Ze=le(me=>{let tt=me;k&&parseFloat(tt)>parseFloat(k)&&(tt=k),pn(tt),w?.(tt),Zt(null),Rt(null),be(!1)},[k,w]);le(me=>{if(rt.current||!H)return;const tt=Nt.current;!tt?.asset||!tt.amount||tt.asset?._source==="wallet"||Le(I?dt:tt.amount,tt.asset.decimals)===0n||(rt.current=!0,Z())},[H,N,Z,I,dt]);const St=le(me=>{fn({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[me.step]||"executing"),Cn(me.message),me.txHash&&sn(me.txHash)},[]),Xe=se(()=>({currentPaymentAmount:dt,destinationToken:o,embeddedWalletAddress:st,providerEmbeddedAddress:he,externalWalletAddress:Q,address:H,isNon7702:ce,isPayMode:I,resolvedChainId:N,buildActionCalls:i,feeExecutionMode:c,buildSpicenetBatch:d,selectedAsset:_,needsSwap:He,resolvedSwap:Ge,exactOutputSwap:at,quoteAmountOut:jt,resolvedTokenIn:mt}),[dt,o,st,he,Q,H,ce,I,N,i,c,d,_,He,Ge,at,jt,mt]),ut=le(me=>Nc(Xe,me),[Xe]),Je=le(me=>Pc(Xe,me),[Xe]),Re=le((me,tt,bn,Mn)=>Uc(me,tt,bn,we,Mn),[we]),Et=se(()=>_?.asset?He&&mt?mt:_.asset.chainId===N?_.asset.address:mt??Nn(_.asset,N)??o.address:o.address,[_,o.address,He,N,mt]),je=le(()=>qc(kn.current),[]),Y=se(()=>_?.asset?Ae(_.asset.address,o.address)&&_.asset.chainId===o.chainId:!1,[_,o.address,o.chainId]),ge=ce&&Y,$e=ge&&At>0&&!!_?.asset,wt=Wt,_e=se(()=>!(!_?.asset||At<=0),[_,At,$e]),$t=se(()=>!e||ft||We!=="idle"||!_e||$e||!_?.asset?null:[I?"pay":"supply",u,_.asset.address.toLowerCase(),_.asset.chainId,_.amount,dt,o.address.toLowerCase(),o.chainId,N,mt?.toLowerCase()??"",He?"swap":"direct",Oe?"direct-token":"routed-token",ce?"non7702":"7702",Y?"source-dest":"cross-chain",Ye?"quoting":"quoted",at?.amountIn?.toString()??"",at?.amountInMax?.toString()??"",at?.venue??"",Ge?.amountOut?.toString()??"",jt?.toString()??"",st??"",he??"",H??""].join("|"),[e,ft,We,_e,$e,_,I,u,dt,o,N,mt,He,Oe,ce,Y,Ye,at,Ge,jt,st,he,H]),K=le(()=>Hc({selectedAsset:_,isPayMode:I,parsedAmount:At,needsSwap:He,exactOutputSwap:at,isNon7702:ce,isSourceDestToken:Y,currentPaymentAmount:dt,destinationToken:o,feeExecutionMode:c,resolvedTokenIn:mt,embeddedWalletAddress:st,providerEmbeddedAddress:he,resolvedChainId:N,isConnected:ne,address:H,ready:X,authenticated:oe,isDirect:Oe,resolvedSwap:Ge,isQuoting:Ye,executionTokenAddress:Et,buildPayChainBatches:ut,buildSupplyChainBatches:Je,estimateGasless:we,estimateRequiredGrossFunding:Re}),[_,I,At,He,at,ce,Y,dt,o,c,mt,st,he,Re,ut,we,N,ne,H,X,oe,Oe,Ge,Ye,Je,Et]);G(()=>{mn.current=K},[K]);const ie=le(me=>Oc({asset:me,isPayMode:I,isNon7702:ce,needsSwap:He,isQuoting:Ye,embeddedWalletAddress:st,buildSupplyChainBatches:Je,estimateGasless:we,executionTokenAddress:Et,feeExecutionMode:c}),[I,ce,He,Ye,st,Je,we,Et,c]);G(()=>{if(!e){et(!1),be(!1),Rt(null),ye(null);return}if(ft||We!=="idle"){Jt.current+=1,et(!1);return}if(!_e){ye(null),et(!1),be(!1),Rt(null);return}if($e){ye(null),et(!1),be(!0),Rt(null);return}if(Ye){Jt.current+=1,et(!1),be(!1);return}if(!$t)return;let me=!1;const tt=async()=>{const Mn=++Jt.current;Rt(null),et(!0);try{const wn=await mn.current?.();if(me||Jt.current!==Mn)return;wn?(ye(wn),be(!0)):(ye(null),be(!1)),Rt(null)}catch(wn){if(me||Jt.current!==Mn)return;const ao=In(wn,"Unable to calculate fees for this action.");ye(null),be(!1),Rt(ao)}finally{!me&&Jt.current===Mn&&et(!1)}},bn=window.setTimeout(()=>{tt()},250);return()=>{me=!0,clearTimeout(bn),et(!1)}},[e,ft,We,_e,$e,Ye,$t]);const de=le(()=>Gc(kn.current),[]);G(()=>{!I&&We==="success"&&qt&&(Z(),B?.(qt))},[I,We,qt,Z,B]),G(()=>{if(!I||Qe?.status!=="success"||rt.current||!H)return;rt.current=!0;const me=Nt.current;!me?.asset||me.asset?._source==="wallet"||Z()},[I,Qe?.status,H,Z]);const te=ae(B),Be=ae(T);G(()=>{te.current=B},[B]),G(()=>{Be.current=T},[T]),G(()=>{e&&(Z(),Ne())},[e,Z,Ne]),G(()=>{I&&(Qe?.status==="success"&&te.current?.(Qe.txHash||""),Qe?.status==="failed"&&Be.current?.(new Error("Payment execution failed")))},[I,Qe?.status]);const Se=le(()=>{ht(!1),Xt(null),Ke(null),rt.current=!1,Z(),Ne()},[Z,Ne]);kn.current={selectedAsset:_,parsedAmount:At,currentPaymentAmount:dt,isInsufficientBalance:$,isPayMode:I,isNon7702:ce,isSourceDestToken:Y,needsSwap:He,exactOutputSwap:at,selectedIsEquivalent:Ot,resolvedTokenIn:mt,embeddedWalletAddress:st,providerEmbeddedAddress:he,externalWallet:V,externalWalletAddress:Q,activeSignerWallet:Ue,activeSignerAddress:kt,address:H,isConnected:ne,ready:X,authenticated:oe,provider:fe,resolvedChainId:N,executionTokenAddress:Et,destinationToken:o,buildActionCalls:i,feeExecutionMode:c,buildSpicenetBatch:d,onPayExecute:l,onSuccess:B,onError:T,gasless:{estimateGasless:we,executeGasless:Ee,buildPayChainBatches:ut,buildSupplyChainBatches:Je,estimateRequiredGrossFunding:Re,onProgress:St},ui:{setError:Zt,setStep:fn,setStatusMsg:Cn,setTxHash:sn,setIsExecuting:nn,setShowStatusPanel:ht,setPaymentResult:Xt},refs:{spiceDepositSubmittedRef:rt,abortControllerRef:rn}};const Bt=m?.trim(),Ct=I&&y==="fixed"&&Bt!==void 0&&Bt!==""&&At===0,Ve=I?(Ct||!!_?.asset)&&At>=0&&!$&&!ft&&(Ct||$e||hn)&&!Kt&&(Ct||!He||!!at):!!_?.asset&&At>0&&!$&&!ft&&(ge||hn)&&!Kt&&(ze||Oe||!!Ge&&!Ye),it=Oe?h||`Your ${o.symbol} will be used directly.`:f||"Your assets will be swapped and used in a single atomic transaction.",an=(N?Fe(N):void 0)?.viemChain?.blockExplorers?.default?.url??"",Tn=Ra.indexOf(We),vn=ft?(Ma[We]||"EXECUTING...").toUpperCase():We==="success"?"DONE":$?"INSUFFICIENT BALANCE":p.toUpperCase(),xn=se(()=>{if(ft)return"PAYING...";if($&&_?.asset)return`INSUFFICIENT ${_.asset.symbol}`;if(p)return p.toUpperCase();const me=At>0?` ${dt} ${o.symbol}`:"";return He?`SWAP & PAY${me}`:`PAY${me}`},[ft,$,_,p,At,dt,o.symbol,He]),Un=We==="success"?()=>{fn("idle"),Ke(null),sn(null),Z()}:je,Ie=We==="success"?!1:!Ve;if(!e)return null;const vt=I?b||`Pay ${o.symbol}`:p,_t=I?S:g("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[a("span",{style:{marginTop:"3px",flexShrink:0},children:a(Ss,{color:J})}),a("p",{style:{fontSize:"12px",color:J,margin:0,lineHeight:"1.4",fontFamily:z},children:it})]});if(I){const me=Qe&&(Qe.status==="success"||Qe.status==="failed")?[{asset:{symbol:_?.asset?.symbol||o.symbol,address:_?.asset?.address||""},amount:dt,txHash:Qe.txHash||"",success:Qe.status==="success",error:Qe.status==="failed"?Qe.error:void 0}]:void 0;return a(jn,{isOpen:e,onClose:t,title:vt,subtitle:_t,styles:C,dark:F,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(Es,{onClick:E,color:M,fontFamily:z})}),!Ct&&a("div",{style:{marginBottom:"12px"},children:a(Eo,{assets:Ce,selectedAsset:_??void 0,onAssetSelect:ee,onAmountChange:ld,label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:_?.asset?He?Ye?"...":at?`~${parseFloat(ct(at.amountIn,_.asset.decimals)).toFixed(6)}`:void 0:dt??void 0:void 0,dark:F,theme:pe,styles:C})}),a(xa,{variant:"pay",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:M,fontFamily:z,textPrimary:j,textSecondary:L,cardBg:P,cardBorder:O,dk:U,dark:F,isQuoting:Ye,quoteError:Dt,estimatedOutput:Fn,paymentAmount:dt,needsSwap:He,exactOutputSwap:at,adjustable:y==="adjustable",maxAmount:k,onAmountChange:Ze}),_e&&a(Oo,{fontFamily:z,textPrimary:j,textSecondary:L,cardBg:P,cardBorder:O,resolvedDark:F,darkCardBorder:U.cardBorder,primaryColor:M,feePreview:xt,isLoading:bt,errorText:Kt,directExecutionFeeNote:$e}),wt&&a(po,{variant:"error",palette:W,fontFamily:z,style:{marginBottom:"12px"},children:wt}),a(Ft,{variant:"outline",fullWidth:!0,onClick:de,disabled:!Ve,loading:ft,dark:F,styles:{...C,button:{...C?.button,backgroundColor:M}},children:xn}),Qe&&yt&&a("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:F?U.shell:"white",borderRadius:F?"12px":"6px",padding:"16px 0"},children:a(Rs,{type:"payment",isOpen:Qe.status!=="processing",isProcessing:ft||Qe.status==="processing",closeOnComplete:!1,chainName:cn(N),explorerUrl:io(N,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{ht(!1),Xt(null),de()},onNewTx:Se,onClose:()=>{ht(!1),Xt(null)},onComplete:Se,results:me,styles:C,dark:F})})]})})}return a(jn,{isOpen:e,onClose:t,title:vt,subtitle:_t,dark:F,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(Eo,{assets:Ce,selectedAsset:_||void 0,onAssetSelect:ee,onAmountChange:ke,disabled:ft||We==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:pe,styles:C,dark:D,resolveMaxAmount:ie,maxAmount:yn>0?uo(yn,_?.asset.decimals??o.decimals):void 0})}),_?.asset&&!Oe&&a(xa,{variant:"supply",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:M,fontFamily:z,textPrimary:j,textSecondary:L,cardBg:P,cardBorder:O,dark:F,isQuoting:Ye,quoteError:Dt,estimatedOutput:Fn}),_e&&a(Oo,{fontFamily:z,textPrimary:j,textSecondary:L,cardBg:P,cardBorder:O,resolvedDark:F,darkCardBorder:U.cardBorder,primaryColor:M,feePreview:xt,isLoading:bt,errorText:Kt,directExecutionFeeNote:$e}),We!=="idle"&&g("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:We==="success"?P:We==="error"?W.errorBg:P,border:`1px solid ${We==="success"?O:We==="error"?W.errorBorder:O}`},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[We==="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"})}):We==="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(Kn,{size:14,color:M}),a("span",{style:{fontSize:"13px",fontWeight:500,color:We==="success"?j:We==="error"?W.errorText:j,fontFamily:z,flex:1},children:We==="success"?"Deposit confirmed":We==="error"?on||"Transaction failed":Ma[We]||on}),We==="success"&&qt&&a("a",{href:`${an}/tx/${qt}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:M,fontFamily:z,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),We==="error"&&a("button",{onClick:()=>{fn("idle"),Zt(null),setTimeout(je,50)},style:{background:"none",border:"none",fontSize:"12px",color:M,fontFamily:z,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),Tn>=0&&We!=="success"&&We!=="error"&&a("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${L}22`,overflow:"hidden"},children:a("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:M,transformOrigin:"left center",transform:`scaleX(${(Tn+1)/Ra.length})`,transition:"transform 400ms ease"}})})]}),Wt&&We==="idle"&&a(po,{variant:"error",palette:W,fontFamily:z,style:{marginBottom:"16px"},children:Wt}),a(Ft,{variant:"outline",fullWidth:!0,disabled:Ie,onClick:Un,theme:A,dark:F,styles:{...C,button:{...C?.button,backgroundColor:M}},style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:q},children:vn})]})})},cd=e=>a(Da,{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}),dd=({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=Yt(Ht),{isAuthenticated:u}=Rn();let f=null;try{f=pi()}catch{}let h=null,m=null;try{h=hi(),m=mi()}catch{h=null,m=null}const y=Za(m),x=le(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 Wa(e){const t=Yt(Ht),n=Dn(),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{...Mr(o,s),embeddedWalletAddress:n}}var ud="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 pd=({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 Ai(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:ud,alt:"","aria-hidden":"true",style:{width:"11px",height:"11px",display:"block",...c?{filter:"invert(0.65)"}:{}}})]}),a(vr,{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:Ts,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:lo(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:mr(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"})]})]})},fd=tn(pd),hd=({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=Fe(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}`)})})]}),md=tn(hd),gd=({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=Fe(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:lo(i.usdValue)})]})]},`${i.tokenAddress}-${i.chainId}-${c}`)})})]})},yd=tn(gd),xd=({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))})]})},bd=tn(xd),wd=({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(Ft,{variant:"outline",onClick:e,disabled:n,dark:r,styles:{button:{backgroundColor:s}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&a(Ft,{variant:"outline",onClick:t,disabled:o,dark:r,styles:{button:{backgroundColor:s}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),Cd=tn(wd),kd=({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[B,T]=R(!1);return g("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[a(fd,{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(Cd,{onDepositClick:u,onWithdrawClick:f,primaryColor:m,dark:x}),E&&g("div",{children:[g("button",{onClick:()=>T(!B),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:B?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),B&&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(md,{pendingDeposits:d,onCompleteDeposit:h,dk:y,dark:x}),a(yd,{spiceAssets:i,loading:c,dk:y,dark:x}),l.map((I,A)=>a(bd,{section:I,dk:y,dark:x},A))]})},vd=tn(kd),Xs=380,ro=8,Id=[];function Na(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function Ad(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=Na(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=Na(s);if(!i)continue;const c=n.get(i);if(c!==void 0)return c}return 0}const Sd=({appName:e="Spice",status:t="active",statusLabel:n,customSections:o=Id,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=Yt(Ht),k=x?.mode!=="7702",w=!!x?.isWhitelistGateActive,C=ae(!1);G(()=>{if(!C.current){if(Xa()){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),[B,T]=R({top:0,bottom:0,left:0,placement:"below"}),I=ae(null),A=ae(null),{address:F,isConnected:M}=Rn(),U=Dn(),{externalAddress:W,embeddedAddress:z}=eo(),{dark:q,primaryColor:D,dk:P}=lt(d,l),O=k&&!W,j=!k||O,L=j?U||z:F,J=se(()=>x?.supportedChainIds??Wo("mainnet"),[x?.supportedChainIds]),{assets:pe,loading:N}=Fo({address:L,supportedChains:J,enabled:!!L&&j,refetchInterval:3e4}),re=se(()=>{const Z=j?pe.map(Ce=>{const _=Ce.balanceUsd||0,Ke=Number.isFinite(Ce.balanceFormatted)?Ce.balanceFormatted:0,Mt=_>0?_:Ad(Ce,r)*Ke;return{tokenAddress:Ce.address,tokenSymbol:Ce.symbol,tokenDisplaySymbol:ks(Ce),tokenDisplayName:Mi(Ce),tokenDecimals:Ce.decimals,chainId:Ce.chainId,chainDisplayName:vs(Ce),balance:Ce.balance.toString(),balanceFormatted:Ce.balanceFormatted,usdValue:Mt,logoURI:Ce.logoURI}}):[],Ne=O?[]:s;return[...Z,...Ne].filter(Ce=>Ce.balanceFormatted>0)},[j,O,pe,r,s]),ce=se(()=>re.reduce((Z,Ne)=>Z+Ne.usdValue,0),[re]),{pendingDeposits:xe}=Wa({chainIds:J,enabled:!!F,discoverWalletBalances:!0}),De=se(()=>o.reduce((Z,Ne)=>Z+Ne.totalValue,0),[o]),ue=ce+De,ve=se(()=>{const Z=[];ce>0&&Z.push(`${lo(ce)} idle`);for(const Ne of o){const Ce=i.find(_=>_.sectionTitle===Ne.title)?.label||Ne.title.toLowerCase();Z.push(`${lo(Ne.totalValue)} ${Ce}`)}return Z.join(" \xB7 ")},[ce,o,i]),H=le(Z=>{h?h(Z):E(Z)},[h]),ne=le(()=>{E(null)},[]),X=le(()=>{E(null),p?.()},[p]),oe=le(()=>{if(!I.current)return;const Z=I.current.getBoundingClientRect(),Ne=window.innerHeight-Z.bottom-ro,Ce=Z.top-ro,_=Ne>=400||Ne>=Ce?"below":"above",Ke=Math.max(ro,Math.min(Z.right-Xs,window.innerWidth-Xs-ro)),Mt=_==="below"?Z.bottom+ro:Z.top-ro,pn=_==="above"?window.innerHeight-Mt:0;T({top:Mt,bottom:pn,left:Ke,placement:_})},[]);er(()=>{v&&oe()},[v,oe]),G(()=>{if(!v)return;const Z=_=>{I.current&&!I.current.contains(_.target)&&A.current&&!A.current.contains(_.target)&&b(!1)},Ne=_=>{_.key==="Escape"&&b(!1)},Ce=()=>oe();return document.addEventListener("mousedown",Z),document.addEventListener("keydown",Ne),window.addEventListener("scroll",Ce,{passive:!0}),window.addEventListener("resize",oe),()=>{document.removeEventListener("mousedown",Z),document.removeEventListener("keydown",Ne),window.removeEventListener("scroll",Ce),window.removeEventListener("resize",oe)}},[v,oe]);const fe=j?U||z||F:W||F,Ee=le(()=>{x?.setMode&&x.setMode(j?"ondemand":"7702")},[x,j]),[we,V]=R(null);let Q=null;try{Q=cr({onSuccess:()=>V(null),onError:Z=>V(In(Z,"Failed to connect wallet."))}).connectWallet}catch{Q=null}const he=le(()=>{Q&&(b(!1),V(null),Q({walletChainType:"ethereum-only"}))},[Q]),Ue=!W&&!!Q,kt=le(()=>{b(!1),u?.()},[u]),zt=le(()=>{b(!1),f?.()},[f]),Lt=le(Z=>{b(!1),H(Z)},[H]);if(typeof window>"u")return null;const ot=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 ",lo(ue)]}),a("span",{style:{fontSize:"10px",color:q?P.textSecondary:"#9ca3af",transform:v?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),st=v?dr.createPortal(g(en,{children:[a("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:Gn.popover},onClick:()=>b(!1)}),a("div",{ref:A,style:{position:"fixed",top:B.placement==="below"?`${B.top}px`:"auto",bottom:B.placement==="above"?`${B.bottom}px`:"auto",left:`${B.left}px`,width:`${Xs}px`,maxWidth:`calc(100vw - ${ro*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:Gn.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${Ut.out}`},children:a(vd,{appName:e,status:t,statusLabel:n,totalUsdValue:ue,breakdownSubtitle:ve,address:j?fe:F,spiceAssets:re,spiceAssetsLoading:N,pendingDeposits:xe,customSections:o,notice:c,onDepositClick:u?kt:void 0,onWithdrawClick:f?zt:void 0,onCompleteDeposit:Lt,primaryColor:D,dk:P,dark:q,showModeToggle:m,isEmbeddedMode:j,onModeToggle:Ee,showConnectExternalCta:Ue,onConnectExternalWallet:he,connectExternalError:we,showHowItWorks:!w})}),a("style",{children:`
|
|
103
|
+
`})]})},kc="0xa9059cbb";function vc(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 Ic(e,t){return`0x${t}${e.slice(4)}`}function Ac(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 ca(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 Ac(r?.balances,n,o)}async function Sc({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 ca(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 js(e,t){return Qs(e,t)}function Qs(e,t,n){const o=Ec(t,e),s=Math.floor(Date.now()/1e3)+60*10,r=zn(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 Ec(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(kc))break;try{const i=vo({abi:qe,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 un(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=Bn(p),f=u.totalFee;if(f<=0n)return l;const h=(l.tokenTransfers??[]).find(C=>r(C)&&Me(C.to).toLowerCase()===t.toLowerCase()&&!Pe(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:qe,functionName:"transfer",args:[wo,u.spicenetFee]})});const w=u.gasFee+u.bridgeFee;return w>0n&&k.push({to:m,value:0n,data:gt({abi:qe,functionName:"transfer",args:[Wn,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:vc(h)}}));if(c.length===0)return e;const d=BigInt(Math.floor(Date.now()/1e3))+3600n;return[{chainId:ri,domain:"spicenet",tokenTransfers:[],calls:c.map((l,p)=>{const u=Co(ko([{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=Ic(u,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:gt({abi:ds,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 Vs(e,t){return t?e.some(n=>(n.tokenTransfers??[]).some(o=>o.from==="escrow"&&BigInt(o.amount)>=t.grossAmount)):!1}function qs(e){const t=e.selectedAsset?.asset,n=e.selectedAsset?.amount;if(!(!t||!n))return Le(n,t.decimals)}function $n(e,t){const n=e.selectedAsset?.asset;if(!n||!e.selectedAsset?.amount)throw new Error("Select an asset and enter an amount");const o=Le(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 Ks(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=pt(r),c=yo(r),d=await cs(t,i),l=await e.actions.signAuthorization({contractAddress:c,chainId:r,nonce:Number(d)});s.push(l)}return s}async function da(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 Ks(e,o,t),r=zn(t),i=Math.floor(Date.now()/1e3)+60*10,c=r.map(h=>h.hash),d=Co(ko([{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 nt.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=rs(t,cn),[m,y]=f.intentIds[0].split("/"),x=parseInt(y||"0",10),k=f.intentIds[0];e.startStatusPolling(f.intentIds[0],h),await Vr({actionId:m,intentIndex:x,intentId:k,totalSteps:t.length,isSpicenetStep:w=>t[w]?.domain==="spicenet",maxExecuteAttemptsForStep:w=>t[w]?.domain==="spicenet"?6:3,maxPolls:72})}}async function ua(e){let t=$n(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 Ks(e,n,t);let s=un([...t],n),r;for(let i=0;i<4;i+=1){const c=await nt.estimateActionFees(Qs(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=To(c,{symbol:e.selectedAsset?.asset.symbol??"",decimals:e.selectedAsset?.asset.decimals??18,actionAmount:qs(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=$n(e,r),s=un([...t],n,c,{payoutAlreadyGross:Vs(t,r)}),p)break}await da(e,s,o)}async function Bc(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=Le(e.selectedAsset.amount,t.decimals),o=e.escrowAddress||yo(e.lockChainId),s=nt.getBaseUrl(),r=Tt(t.address);let i=0n;try{i=await ca(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=Fe(e.lockChainId),l=Ln({account:e.embeddedWalletAddress,transport:On(c),chain:d?.viemChain});let p;if(t.isNative||Pe(t.address))p=await l.sendTransaction({to:o,value:n,chain:d?.viemChain});else{const u=gt({abi:qe,functionName:"transfer",args:[o,n]});p=await l.sendTransaction({to:t.address,data:u,chain:d?.viemChain})}if((await pt(e.lockChainId).waitForTransactionReceipt({hash:p,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to escrow failed");await Sc({apiBaseUrl:s,user:e.embeddedWalletAddress,chainId:e.lockChainId,tokenAddress:r,prevBalance:i}),await e.refreshSpiceAssets(),e.refreshWalletAssets(),await ua(e)}async function Fc(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,B=Le(e.selectedAsset.amount,E.decimals),T=await e.onLockExecute({asset:E,amount:e.selectedAsset.amount,amountWei:B,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=Le(e.selectedAsset.amount,o.decimals),r=o.chainId,i=e.escrowAddress||An(r),c=Tt(o.address),d=o.isNative||Pe(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:qe,functionName:"transfer",args:[i,S]})}]}),u=(S,E,B)=>{const T=p(S);if(!l)return[T,...E];const I=un([...E],t,B,{payoutAlreadyGross:Vs(E,y)});return[T,...I]};let f=$n(e),h=u(s,f);const m=await Ks(e,t,h);let y;if(l)for(let S=0;S<4;S+=1){const E=await nt.estimateActionFees(Qs(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)})))),B=To(E,{symbol:o.symbol,decimals:o.decimals,actionAmount:s});if(!B)break;const T={grossAmount:B.grossAmount,netAmount:B.netAmount,feeAmount:B.totalFee??0n},I=y?.grossAmount===T.grossAmount&&y?.netAmount===T.netAmount&&y?.feeAmount===T.feeAmount;if(y=T,f=$n(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=Fe(r),v=Ln({account:e.externalWalletAddress,chain:C?.viemChain,transport:On(k)}),b=d?await v.sendTransaction({to:t,value:x,chain:C?.viemChain}):await v.sendTransaction({to:c,data:gt({abi:qe,functionName:"transfer",args:[t,x]}),chain:C?.viemChain});if((await pt(r).waitForTransactionReceipt({hash:b,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to embedded wallet failed");await da(e,h,m)}async function Tc(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=$n(e);if(c.length===0)throw new Error("No lock batches configured");const d=e.selectedAsset.asset,l=Le(e.selectedAsset.amount,d.decimals),p=d.chainId,u=e.escrowAddress||An(p),f=Tt(d.address),h=d.isNative||Pe(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:qe,functionName:"transfer",args:[u,v]})}]}),x=(v,b,S)=>{const E=y(v);if(!m)return[E,...b];const B=un([...b],i,S,{payoutAlreadyGross:b.some(T=>(T.tokenTransfers??[]).some(I=>I.from==="escrow"&&BigInt(I.amount)>=v))});return[E,...B]};let k=x(l,c),w=null,C;for(let v=0;v<4;v+=1){const b=await nt.estimateActionFees(js(i,k)),S=To(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},B=C?.grossAmount===E.grossAmount&&C?.netAmount===E.netAmount&&C?.feeAmount===E.feeAmount;if(w=S,C=E,c=$n(e,E),k=x(E.grossAmount,c,b),B)break}return w}const t=e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");let n=$n(e);if(n.length===0)throw new Error("No lock batches configured");let o=un([...n],t),s=null;for(let i=0;i<4;i+=1){const c=await nt.estimateActionFees(js(t,o)),d=To(c,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:qs(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=$n(e,l),o=un([...n],t,c,{payoutAlreadyGross:Vs(n,l)}),p)break}if(s)return s;const r=await nt.estimateActionFees(js(t,o));return To(r,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:qs(e)})}async function Mc(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=Fe(e.lockChainId),d=Ln({account:n,chain:c?.viemChain,transport:On(r)}),l=pt(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 Rc(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 Mc(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{await Fc(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{e.isDirectDeposit&&!e.isSourceDestToken?await Bc(e):await ua(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}}const pa=({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:B,primaryColor:T,dk:I}=lt(b,S),A=E.typography.fontFamily,F=Yt(Ht),M=F?.mode||"7702",U=!!F?.isWhitelistGateActive,W=M!=="7702",z=se(()=>F?.supportedChainIds??[],[F?.supportedChainIds]),q=se(()=>{if(U)return[];const Y=F?.allowedTokens;if(!Y||Y.length===0)return[];const ge=new Set(Y.map(_e=>_e.toLowerCase())),$e=[],wt=new Set;for(const _e of z){const $t=Fe(_e);for(const K of $t?.supportedTokens??[]){if(!ge.has(K.symbol.toLowerCase()))continue;const ie=`${_e}:${K.address.toLowerCase()}`;wt.has(ie)||(wt.add(ie),$e.push(Me(K.address)))}}return $e},[F?.allowedTokens,z,U]),D=B?I.cardBg:b?.assetSelector?.backgroundColor||b?.secondaryBackground||"#e9e9e9",P=B?`1px solid ${I.cardBorder}`:"0.5px solid #A8A8A7",O=B?"12px":"6px",j=B?I.textPrimary:"#111827",L=B?I.textSecondary:"#6b7280",J=se(()=>({...b,assetSelector:{...b?.assetSelector,backgroundColor:B?I.cardBg:b?.assetSelector?.backgroundColor,borderRadius:B?"12px":b?.assetSelector?.borderRadius},secondaryBackground:B?I.cardBg:b?.secondaryBackground}),[b,B]),pe=se(()=>B?{...E,colors:{...E.colors,secondary:I.cardBg,surfaceHover:I.hoverBg,border:I.cardBorder,borderHover:I.inputBorder}}:E,[B,E]),[N,re]=R(null),[ce,xe]=R(0),De=d?.selectedDurationIdx??ce,ue=d?.setSelectedDurationIdx??xe,[ve,H]=R(!1),[ne,X]=R(null),[oe,fe]=R(null),[Ee,we]=R(!1),[V,Q]=R(!1),[he,Ue]=R(null),[kt,zt]=R(!1),Lt=ae(0),[ot,st]=R(!1),[Z,Ne]=R(null);rr(),as();const{chain:Ce,address:_}=xo();ei();const Ke=ae(Ce);G(()=>{Ke.current=Ce},[Ce]);const Mt=Rn(),{isReady:pn,isAuthenticated:ft,isConnected:nn,address:Wt,provider:Zt,actions:We}=Mt,{externalWallet:fn,embeddedAddress:on,externalAddress:Cn,activeWallet:qt,activeAddress:sn}=eo(),{intentStatus:yt,startStatusPolling:ht,clearStatus:Qe}=kr({checkStepStatus:(Y,ge)=>nt.checkStepStatus(Y,ge),retryStep:async(Y,ge)=>{const[$e,wt]=Y.split("/"),_e=parseInt(wt||"0",10);await nt.executeStep($e,_e,ge,{action:"execute"})},maxRetries:3}),{assets:Xt,refetch:xt}=Fo({address:Wt,supportedChains:z,enabled:e&&nn&&!W&&!U,refetchInterval:3e4}),ye=se(()=>{if(U)return[];if(q.length===0)return Xt;const Y=new Set(q.map(ge=>ge.toLowerCase()));return Xt.filter(ge=>Y.has(ge.address.toLowerCase()))},[Xt,q,U]),bt=Dn(),et=Cn||_,hn=W?sn??et:bt,be=se(()=>{if(!h)return[];if(U)return m?[Me(m)]:[];const Y=new Set,ge=[],$e=wt=>{if(!wt)return;const _e=wt.toLowerCase();Y.has(_e)||(Y.add(_e),ge.push(Me(wt)))};if(m&&$e(m),W)for(const wt of q)$e(wt);return ge},[h,W,m,q,U]),Kt=se(()=>be.map(Y=>Y.toLowerCase()).sort().join(","),[be]),Rt=se(()=>JSON.stringify([...z||[]].sort()),[z]),[Nt,rt]=R([]),rn=ae(0),Jt=ae(async()=>{}),mn=le(async()=>{if(!h||!hn||be.length===0){rn.current++,rt([]);return}const Y=++rn.current,ge=Me(hn),$e=z&&z.length>0?z:[l],wt=be.map(de=>{const te=de.toLowerCase();if(m&&Ae(de,m)){const Be=Fe(l)?.supportedTokens?.find(Se=>Ae(Se.address,te));return{address:de,chainId:l,configToken:Be?{decimals:Be.decimals,symbol:Be.symbol,name:Be.name,logo:Be.logo}:void 0}}for(const Be of $e){const Se=Fe(Be)?.supportedTokens?.find(Bt=>Ae(Bt.address,te));if(Se)return{address:de,chainId:Be,configToken:{decimals:Se.decimals,symbol:Se.symbol,name:Se.name,logo:Se.logo}}}return{address:de,chainId:l}}),_e=new Map;for(const de of wt){const te=_e.get(de.chainId)||[];te.push(de),_e.set(de.chainId,te)}const $t=async(de,te)=>{try{const Be=await En(de,{address:te.address,abi:qe,functionName:"balanceOf",args:[ge]});let Se,Bt,Ct,Ve;if(te.configToken)Se=te.configToken.decimals,Bt=te.configToken.symbol,Ct=te.configToken.name,Ve=te.configToken.logo;else{const[Tn,vn,xn]=await Promise.all([En(de,{address:te.address,abi:qe,functionName:"decimals",args:[]}).catch(()=>18),En(de,{address:te.address,abi:qe,functionName:"symbol",args:[]}).catch(()=>"TOKEN"),En(de,{address:te.address,abi:qe,functionName:"name",args:[]}).catch(()=>"TOKEN")]);Se=Number(Tn),Bt=vn,Ct=xn}const it=!!m&&Ae(te.address,m)&&te.chainId===l;it&&r&&(Ve=r),it&&s&&!te.configToken&&(Bt==="TOKEN"&&(Bt=s),Ct==="TOKEN"&&(Ct=s));const an=parseFloat((Number(Be)/Math.pow(10,Se)).toFixed(6));return{address:te.address,name:Ct,symbol:Bt,decimals:Se,balance:Be,balanceFormatted:an,balanceUsd:0,logoURI:Ve,isNative:!1,chainId:te.chainId}}catch{return null}},K=await Promise.all(Array.from(_e.entries()).map(async([de,te])=>{let Be;try{Be=pt(de)}catch{return[]}const Se=[],Bt=[];for(const Ve of te){const it=Se.length;Se.push({address:Ve.address,abi:qe,functionName:"balanceOf",args:[ge]}),Ve.configToken||Se.push({address:Ve.address,abi:qe,functionName:"decimals",args:[]},{address:Ve.address,abi:qe,functionName:"symbol",args:[]},{address:Ve.address,abi:qe,functionName:"name",args:[]}),Bt.push({start:it,item:Ve})}let Ct=null;try{Ct=await Be.multicall({contracts:Se})}catch{Ct=null}return Ct?Bt.map(({start:Ve,item:it})=>{const an=Ct[Ve],Tn=an?.status==="success"?an.result:0n;let vn,xn,Un,Ie;if(it.configToken)vn=it.configToken.decimals,xn=it.configToken.symbol,Un=it.configToken.name,Ie=it.configToken.logo;else{const me=Ct[Ve+1],tt=Ct[Ve+2],bn=Ct[Ve+3];vn=me?.status==="success"?Number(me.result):18,xn=tt?.status==="success"?tt.result:"TOKEN",Un=bn?.status==="success"?bn.result:xn}const vt=!!m&&Ae(it.address,m)&&it.chainId===l;vt&&r&&(Ie=r),vt&&s&&!it.configToken&&(xn==="TOKEN"&&(xn=s),Un==="TOKEN"&&(Un=s));const _t=parseFloat((Number(Tn)/Math.pow(10,vn)).toFixed(6));return{address:it.address,name:Un,symbol:xn,decimals:vn,balance:Tn,balanceFormatted:_t,balanceUsd:0,logoURI:Ie,isNative:!1,chainId:it.chainId}}):(await Promise.all(te.map(Ve=>$t(Be,Ve)))).filter(Ve=>Ve!==null)}));if(Y!==rn.current)return;const ie=K.flat();rt(ie)},[h,hn,Kt,Rt,l,m,r,s]);G(()=>{Jt.current=mn},[mn]),G(()=>{if(!e||!h){rt([]);return}Jt.current();const Y=setInterval(()=>{Jt.current()},15e3);return()=>clearInterval(Y)},[h,e,hn,Kt,Rt,l,m]);const kn=le(()=>{mn()},[mn]),dt=se(()=>Nt.filter(Y=>Y.balance>0n),[Nt]),It=se(()=>{if(W)return dt.map(ge=>({...ge,_source:"wallet"}));if(!h)return ye;const Y=[];for(const ge of dt)Y.push({...ge,_source:"wallet"});for(const ge of ye)Y.push({...ge,_source:"spice"});return Y},[W,h,dt,ye]),Ye=se(()=>U?m?It.filter(Y=>Ae(Y.address,m)&&Y.chainId===l):[]:It,[It,U,m,l]),Dt=ae(null),Fn=ae(null);G(()=>{Fn.current=N},[N]),G(()=>{!U||!N?.asset||m&&Ae(N.asset.address,m)&&N.asset.chainId===l||re(null)},[U,N?.asset,m,l]),G(()=>{e||(re(null),X(null),fe(null),we(!1),Q(!1),Ue(null),H(!1),st(!1),Ne(null),zt(!1),Qe())},[e,Qe]),G(()=>{i&&i.assetAmount!==(N?.amount||"")&&re(Y=>Y&&{...Y,amount:i.assetAmount})},[i?.assetAmount]),G(()=>{c&&c.assetAmount!==(N?.amount||"")&&re(Y=>Y&&{...Y,amount:c.assetAmount})},[c?.assetAmount]),G(()=>{if(!W&&yt?.overallStatus==="success"&&yt.intentId&&Dt.current!==yt.intentId&&Wt&&yt.steps.find(Y=>Y.transactionHash)?.transactionHash){Dt.current=yt.intentId;const Y=Fn.current;if(!Y?.asset||!Y.amount||Y.asset._source==="wallet"||Le(Y.amount,Y.asset.decimals)===0n)return;xt()}},[yt,Wt,l,xt,W]);const Ge=parseFloat(N?.amount||"")||0,at=se(()=>N?.asset?N.asset._source==="wallet"?N.asset.balanceFormatted??0:ye.find(Y=>Ae(Y.address,N.asset.address)&&Y.chainId===N.asset.chainId)?.balanceFormatted??0:0,[N?.asset,ye]),jt=Ge>0&&(he?parseFloat(ct(he.grossAmount,he.decimals))>at:Ge>at),mt=d?.selectedDuration??p[De]??p[0],Oe=se(()=>!N?.asset||!m?!1:Ae(N.asset.address,m)&&N.asset.chainId===l,[N?.asset,m,l]),He=se(()=>Ge<=0?0:Oe?Ge:!k||k<=0?0:Ge/k,[Ge,k,Oe]),Ot=se(()=>He<=0?null:He.toLocaleString(void 0,{maximumFractionDigits:2}),[He]),At=u&&He>0&&mt?u(He,mt.months):void 0,gn=se(()=>Ge<=0?"$0.00":Oe&&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,Oe]),ze=se(()=>{if(!Ot)return null;const Y=parseFloat(Ot.replace(/,/g,""));return Oe&&k?(Y*k).toLocaleString(void 0,{maximumFractionDigits:2}):k?(Y*k).toLocaleString(void 0,{maximumFractionDigits:2}):null},[Ot,k,Oe]),Pn=le(Y=>{re(ge=>({asset:Y,amount:ge?.asset?.address===Y.address&&ge?.asset?.chainId===Y.chainId&&ge.amount||""})),X(null),fe(null),Q(!1),Ue(null),c?.setSelectedAsset&&c.setSelectedAsset({symbol:Y.symbol,address:Y.address,decimals:Y.decimals,chainId:Y.chainId})},[c?.setSelectedAsset]),yn=le(Y=>{re(ge=>ge&&{...ge,amount:Y}),X(null),fe(null),Q(!1),Ue(null),i&&i.setAssetAmount(Y),c&&c.setAssetAmount(Y)},[i,c]),$=le(Y=>{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:Y?.amount??N.amount,amountWei:Y?.amountWei??Le(N.amount,N.asset.decimals),grossAmount:Y?.grossAmount,grossAmountWei:Y?.grossAmountWei,feeAdjusted:!!Y})}return o},[o,N]),ee=ae(null),ke=se(()=>!N?.asset||Ge<=0?!1:W?!Oe&&!x:!0,[N,Ge,W,Oe,x]),Ze=le(()=>Tc(ee.current),[]),St=se(()=>!N?.asset||Ge<=0?null:`${N.asset.address.toLowerCase()}:${N.asset.chainId}:${N.amount??""}`,[N?.asset?.address,N?.asset?.chainId,N?.amount,Ge]);G(()=>{if(!e||ve)return;if(!N?.asset||Ge<=0){fe(null),we(!1),Q(!1),Ue(null);return}if(!ke){fe(null),we(!1),Q(!0),Ue(null);return}let Y=!1;const ge=async _e=>{const $t=++Lt.current;_e||(fe(null),Q(!1),we(!0));try{const K=await Ze();if(Y||Lt.current!==$t)return;fe(null),Q(!0),Ue(K)}catch(K){if(Y||Lt.current!==$t)return;_e||(fe(In(K,"Unable to calculate fees for this lock.")),Q(!1))}finally{!Y&&Lt.current===$t&&!_e&&we(!1)}},$e=window.setTimeout(()=>{ge(!1)},250),wt=window.setInterval(()=>{ge(!0)},3e4);return()=>{Y=!0,clearTimeout($e),window.clearInterval(wt)}},[e,ve,St,ke,Ze]),G(()=>{if(yt?.overallStatus==="success"){const Y=yt.steps.find(ge=>ge.transactionHash);y?.(Y?.transactionHash)}},[yt?.overallStatus,y]);const Xe=h&&N?.asset?._source==="wallet"&&N?.asset?.chainId===l,ut=le(()=>Rc(ee.current),[]),Je=!!N?.asset&&Ge>0&&!jt&&!ve&&(!ke||V&&!Ee&&!oe),Re=ne||oe,Et=g("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[a(Ss,{color:L}),g("p",{style:{fontSize:"13px",color:L,margin:0,lineHeight:"1.5"},children:["Add ",s," by converting assets from your account"]})]});if(ee.current={selectedAsset:N,parsedAmount:Ge,selectedDuration:mt,isInsufficientBalance:jt,isSemi7702:W,isSourceDestToken:Oe,isDirectDeposit:Xe,requiresRelayerFeeEstimate:ke,address:Wt,embeddedWalletAddress:bt,providerEmbeddedAddress:on,externalWallet:fn,externalWalletAddress:et,activeSignerWallet:qt,activeSignerAddress:sn,isConnected:nn,ready:pn,authenticated:ft,provider:Zt,actions:We,lockChainId:l,escrowAddress:f,onLockExecute:x,onLockSuccess:y,buildSpicenetBatch:v,resolveLockBatches:$,startStatusPolling:ht,refreshSpiceAssets:xt,refreshWalletAssets:kn,ui:{setError:X,setIsExecuting:H,setShowStatusPanel:zt}},!e)return null;const je={backgroundColor:D,border:P,borderRadius:O,padding:"16px",marginBottom:"16px"};return a(jn,{isOpen:e,onClose:t,title:`Add ${s} to your account`,subtitle:Et,styles:b,dark:B,footerLinkText:"Spicenet accounts \u2192",overlayContent:ot?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(Es,{onClick:C,color:T,fontFamily:A})}),a("div",{style:{marginTop:"10px",fontSize:"13px",color:L,fontFamily:A},children:a(Eo,{assets:Ye,selectedAsset:N??void 0,onAssetSelect:Pn,onAmountChange:yn,label:"Amount",showBalance:!0,showMaxButton:!0,theme:pe,styles:J})}),a("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:L,fontFamily:A},children:gn})]}),g("div",{style:je,children:[g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:B?`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:B?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:Ot??"0.00"}),g("div",{style:{fontSize:"12px",color:L,fontFamily:A,marginTop:"2px"},children:["~$",ze??"0.00"]})]})]}),g("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:B?`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:L,fontFamily:A},children:"Lock Duration"}),a(Qn,{color:L})]}),a(mc,{options:p,selectedIndex:De,onSelect:ue,primaryColor:T,dark:B,textPrimary:j,textSecondary:L})]}),g("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[a(xc,{durationMonths:mt?.months,fontFamily:A,dark:B,textPrimary:j,textSecondary:L}),u&&a(wc,{votes:At,fontFamily:A,dark:B,textPrimary:j,textSecondary:L})]})]}),ke&&a(Oo,{fontFamily:A,textPrimary:j,textSecondary:L,cardBg:D,cardBorder:P,resolvedDark:B,darkCardBorder:I.cardBorder,primaryColor:T,feePreview:he,isLoading:Ee,errorText:oe}),Re&&a(po,{variant:"error",palette:I,fontFamily:A,style:{marginBottom:"12px"},children:Re}),a(Ft,{variant:"outline",fullWidth:!0,onClick:ut,disabled:!Je,loading:ve,dark:B,styles:{...b,button:{...b?.button,backgroundColor:T}},children:ve?Xe&&!Oe?"DEPOSITING...":Oe?"LOCKING...":"CONVERTING...":Ee&&ke?"CALCULATING FEES...":Xe&&!Oe?`DEPOSIT ${s}`:Oe?`LOCK ${s}`:`CONVERT TO ${s}`}),a(Cc,{isOpen:ot,data:Z,isLocking:ve,lockError:Re,onContinue:ut,onClose:()=>st(!1),primaryColor:T,fontFamily:A,dark:B}),yt&&kt&&a("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:B?"rgba(0, 0, 0, 0.45)":"rgba(255, 255, 255, 0.55)",backdropFilter:"blur(2px)",WebkitBackdropFilter:"blur(2px)",borderRadius:O},children:a(Rs,{type:"lock",showStepBreakdown:!1,isOpen:!!yt&&yt.overallStatus!=="processing",isProcessing:ve||yt?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{Qe(),zt(!1),ut()},onNewTx:()=>{Qe(),zt(!1),re(null),Dt.current=null,xt(),kn()},onClose:()=>{Qe(),zt(!1)},onComplete:()=>{Qe(),zt(!1),re(null),Dt.current=null,xt(),kn()},results:yt?.overallStatus==="success"||yt?.overallStatus==="failed"?yt.steps.map(Y=>({asset:{symbol:N?.asset?.symbol||s,address:N?.asset?.address||""},txHash:Y.transactionHash||"",success:Y.status==="success",amount:N?.amount})):void 0,chainName:cn(l),explorerUrl:io(l,"").replace(/\/tx\/.*$/,"")||void 0,theme:E,styles:b,dark:B})})]})})},Dc="0xa9059cbb";function Wc(e,t,n){return Pe(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:gt({abi:Vt,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(Dc)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function $o(e,t,n){if(!t)return[e];const o=await t(n);return o?[o,e]:[e]}function so(e){return e.filter(t=>t.domain!=="spicenet")}function _o(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 mo(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 Nc(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=Le(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,B=(T,I)=>({token:T,from:c?"solver":"escrow",to:C,amount:I});if(k===0n)return[S];if(m&&y){const T=x??Nn(h.asset,l)??h.asset.address,I=t?.fundingAmountOverride??y.amountInMax,A=E?[B(T,I)]:[],F={to:T,value:0n,data:gt({abi:Vt,functionName:"approve",args:[y.calls[0]?.to,y.amountInMax]})},M={chainId:l,calls:[F,...y.calls,...b],tokenTransfers:[...A,...S.tokenTransfers??[]]};return E?$o(M,f,{userAddress:C,destinationChainId:l,deliveryToken:T,deliveryAmount:I,deliveryRecipient:C,deliveryTransfers:_o(M),sourceAsset:h.asset}):[M]}if(E){const T=x??Nn(h.asset,l)??o.address,I=t?.fundingAmountOverride??k,A={...S,tokenTransfers:[B(T,I),...S.tokenTransfers??[]]};return $o(A,f,{userAddress:C,destinationChainId:l,deliveryToken:T,deliveryAmount:I,deliveryRecipient:C,deliveryTransfers:_o(A),sourceAsset:h.asset})}return[S]}async function Pc(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??Le(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,B={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,B),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,{...B,netAmount:t?.actionAmountOverride??x}),{feeCall:O,remainingCalls:j}=Ys(P,d,f,B.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,{...B,netAmount:t?.actionAmountOverride??x}),{feeCall:O,remainingCalls:j}=Ys(P,d,f,B.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",F=u&&I;if(!(A||F))return[{chainId:r,calls:T}];const M=F&&n.asset.chainId!==r?{chainId:n.asset.chainId,calls:[Wc(Tt(n.asset.address),v,An(n.asset.chainId))]}:null,U=(P,O)=>({token:P,from:F?"solver":"escrow",to:o,amount:O}),W=(P,O)=>F?[{token:P,from:"escrow",to:ai,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,{...B,netAmount:t?.actionAmountOverride??x}),{feeCall:O,remainingCalls:j}=Ys(P,d,f,B.feeToken),L={chainId:r,calls:[...O?[O]:[],...h.calls,...j],tokenTransfers:[...W(y,S),U(y,b)]},J=await $o(L,l,{userAddress:o,destinationChainId:r,deliveryToken:y,deliveryAmount:b,withdrawalAmount:S,deliveryRecipient:o,deliveryTransfers:_o(L),sourceAsset:n.asset});return M?[M,...J]:J}const z=y??Nn(n.asset,r)??i.address,q={chainId:r,calls:T,tokenTransfers:[...W(z,S),U(z,b)]},D=await $o(q,l,{userAddress:o,destinationChainId:r,deliveryToken:z,deliveryAmount:b,withdrawalAmount:S,deliveryRecipient:o,deliveryTransfers:_o(q),sourceAsset:n.asset});return M?[M,...D]:D}async function Uc(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=Hl(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 zc(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 Lc(e,t){const n=ct(e,t);return n.includes(".")?n.replace(/\.?0+$/,"")||"0":n}async function Oc(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=Xn(m,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),x=y?mo(y.gasFee,y.decimals,t.decimals):0n,k=y?mo(y.spicenetFee,y.decimals,t.decimals):0n,w=zc(t.balance,x,k,t.balance);return w>0n?Lc(w,t.decimals):null}async function Hc(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:B,estimateGasless:T,estimateRequiredGrossFunding:I}=e;if(!t?.asset)return null;if(n){if(o<=0||s&&!r||i&&c)return null;const D=Le(d,l.decimals),P=u||Nn(t.asset,m)||t.asset.address||l.address,O={chainId:m,tokenAddress:P,symbol:Pt(P,m)?.symbol??t.asset.symbol,decimals:Pt(P,m)?.decimals??t.asset.decimals};if(i){const re=f||h;if(!re)return null;const ce=re,xe=s?r?.amountInMax??0n:D;if(xe===0n)return null;const De=await I(xe,H=>E({fundingAmountOverride:H}).then(ne=>un(so(ne),ce)),P,{userOverride:re,useCustomTransfers:!0}),ue=un(so(await E({fundingAmountOverride:De})),ce),ve=await T(ue,P,De,{userOverride:re,useCustomTransfers:!0,feeExecutionMode:p});return Xn(ve,O)}if(!y||!x||!k||!w)return null;const j=f||h||x,L=s?r?.amountInMax??0n:D;if(L===0n)return null;const J=await I(L,re=>E({fundingAmountOverride:re}).then(ce=>un(so(ce),j)),P,{useCustomTransfers:!0});let pe=un(so(await E({fundingAmountOverride:J})),j);const N=await T(pe,P,J,{useCustomTransfers:!0,feeExecutionMode:p});return Xn(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 F=Le(t.amount,t.asset.decimals),M=await B();if(M.length===0)return null;const U=i&&t.asset?._source==="wallet"&&t.asset.chainId===m,W={chainId:m,tokenAddress:S,symbol:Pt(S,m)?.symbol??l.symbol,decimals:Pt(S,m)?.decimals??l.decimals};if(U){const D=await nt.estimateBatchGas({user:A,outputToken:S,stepIndex:0,chainBatches:M}),P=Yo(F,10n),O=P+D.gasFee;return{...W,grossAmount:F+O,netAmount:F,totalFee:O,gasFee:D.gasFee,spicenetFee:P,bridgeFee:0n,gasQuoteSource:D.gasQuoteSource}}const z=M.some(D=>D.tokenTransfers?.length),q=await T(M,S,F,z?{userOverride:A,useCustomTransfers:!0,feeExecutionMode:p}:p?{userOverride:A,feeExecutionMode:p}:{userOverride:A});return Xn(q,W)}const jc=10n;function fa(e,t){const n=e.selectedAsset?.asset;if(!n||n?._source!=="wallet")return;const o=Nn(n,e.resolvedChainId);if(!o||!Ae(o,e.executionTokenAddress))return;const s=Pt(e.executionTokenAddress,e.resolvedChainId),r=mo(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 ha(e){const t=Pt(e.executionTokenAddress,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:t?.symbol??e.destinationToken.symbol,decimals:t?.decimals??e.destinationToken.decimals}}function ma(e,t,n){const o=Xn(e,ha(t));if(!o)return;const s=Yo(n,jc),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 go(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 ga(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=vo({abi:Vt,data:c.data});if(d.functionName!=="transfer")continue;const l=d.args[0].toLowerCase(),p=d.args[1];l===wo.toLowerCase()?o+=p:l===Wn.toLowerCase()&&(s+=p)}catch{continue}}return{spicenetFee:o,gasFee:s}}function Qc(e,t,n){const o=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,s=ga(e,t.resolvedChainId,o);return s.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||s.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:go(s.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&go(s.gasFee,n.feeBreakdown.gasFee,100n)}function Vc(e,t){return e?go(e.grossAmount,t.grossAmount,100n)&&go(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&go(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&go(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}async function qc(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 ya(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 Kc(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=Le(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=>No(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=Xn(m,ha(e));u=e.feeExecutionMode==="user-transfer"&&y?ma(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"&&(fa(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=ma(h,e,o);if(!y)return null;const x=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&e.resolvedTokenIn?e.resolvedTokenIn:e.executionTokenAddress;ga(m,e.resolvedChainId,x);const k=Vc(f,y),w=Qc(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 Kc(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=Le(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 B=await nt.estimateBatchGas({user:n,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:c}),T=Yo(s,10n),I=T+B.gasFee;l=s+I,e.feeExecutionMode==="user-transfer"&&(f={grossAmount:l,netAmount:r,combinedFeeAmount:I,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:T,gasFee:B.gasFee,bridgeFee:0n}})}else{const B=await e.gasless.estimateGasless(c,e.executionTokenAddress,0n,d),T=Xn(B,{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:Pt(e.executionTokenAddress,e.resolvedChainId)?.symbol??e.destinationToken.symbol,decimals:Pt(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=Pt(e.executionTokenAddress,e.resolvedChainId),m=i?l:mo(l,h?.decimals??e.destinationToken.decimals,o.decimals);fa(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 B=await k.request({method:"eth_chainId"});w=parseInt(B,16)}catch{w=null}w!==y&&(e.ui.setStatusMsg("Switching source network..."),await Yn(k,y));const C=Fe(y),v=Ln({account:e.externalWalletAddress,chain:C?.viemChain,transport:On(k)}),b=Tt(o.address),S=o.isNative||Pe(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:Vt,functionName:"transfer",args:[x,m]}),chain:C?.viemChain});if((await pt(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 ya(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=Le(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=Fe(e.resolvedChainId),p=Ln({account:o,chain:l?.viemChain,transport:On(c)}),u=pt(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 Yc(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=Le(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=Fe(o),h=Ln({account:e.externalWalletAddress,chain:f?.viemChain,transport:On(p)}),m=Tt(n.address),y=n.isNative||Pe(m)?await h.sendTransaction({to:l,value:d,chain:f?.viemChain}):await h.sendTransaction({to:m,data:gt({abi:Vt,functionName:"transfer",args:[l,d]}),chain:f?.viemChain});if((await pt(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 Gc(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 ya(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const s=e.selectedAsset.asset,r=Le(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 Yc(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=Le(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=>un(so(x),c)),r,o);let l=d,p=un(so(await e.gasless.buildPayChainBatches({fundingAmountOverride:d})),c);const u=await e.gasless.estimateGasless(p,r,d,o),f=Xn(u,{chainId:e.resolvedChainId,tokenAddress:r,symbol:Pt(r,e.resolvedChainId)?.symbol??s.symbol,decimals:Pt(r,e.resolvedChainId)?.decimals??s.decimals})?.grossAmount??d;f!==d&&(l=f),p=un(so(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 Zc=({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(ba,{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(to,{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(Xc,{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=tn(Zc),ba=({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)}),Xc=({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=ae(null),[B,T]=R(null),[I,A]=R(null);G(()=>{y||S(u||"")},[u,y]);const F=W=>{let z=W;z.startsWith(".")&&(z="0"+z);const q=co(z);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 z=10**n,q=Math.floor(v*W/100*z)/z,D=uo(q,n);S(D),E.current&&clearTimeout(E.current),k?.(D)},U=v>0?parseFloat(b||"0")/v*100:0;return G(()=>()=>{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(ba,{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(to,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:b,onChange:W=>F(W.target.value),placeholder:"0.0",fontFamily:w,color:r,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):a(to,{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,z)=>{const q=Math.abs(U-W)<1,D=z===4,P=W/100,O=B===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:dn.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 wa(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 Jc(e,t){return!t||t.length===0||t.some(n=>Ae(n,e.address))?!0:Object.keys(e.chainTokens??{}).some(n=>{const o=ho(n);return o?t.some(s=>Ae(s,o.address)):!1})}function $c(e){const{destinationToken:t,supportedSourceAssets:n,sourceChains:o,enabled:s}=e,r=(Yt(Ht)?.mode||"7702")!=="7702",i=Dn(),{externalAddress:c,embeddedAddress:d,activeAddress:l}=eo(),p=i||d,{assets:u,refetch:f}=Fo({address:p,supportedChains:o,enabled:s&&!r&&!!p,refetchInterval:3e4}),h=se(()=>r?[]:u.filter(B=>Jc(B,n)),[u,n,r]),m=r?l??c:i,y=se(()=>{const B=new Set,T=[],I=A=>{if(!A)return;const F=A.toLowerCase();B.has(F)||(B.add(F),T.push(Me(A)))};if(I(t.address),r&&n)for(const A of n)I(A);return T},[r,t.address,n]),x=se(()=>y.map(B=>B.toLowerCase()).sort().join(","),[y]),k=se(()=>JSON.stringify([...o||[]].sort()),[o]),[w,C]=R([]),v=ae(0),b=ae(async()=>{}),S=le(async()=>{if(!s||!m||y.length===0){v.current++,C([]);return}const B=++v.current,T=Me(m),I=r?o&&o.length>0?o:[t.chainId]:[t.chainId],A=[];for(const W of y){const z=W.toLowerCase();if(z===Qt)continue;if(z===t.address.toLowerCase()){const D=Fe(t.chainId)?.supportedTokens?.find(P=>Ae(P.address,z));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=Fe(D)?.supportedTokens?.find(O=>Ae(O.address,z));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 F=new Map;for(const W of A){const z=F.get(W.chainId)||[];z.push(W),F.set(W.chainId,z)}const M=async(W,z)=>{try{const q=await En(W,{address:z.address,abi:Vt,functionName:"balanceOf",args:[T]});let D,P,O,j;if(z.configToken)D=z.configToken.decimals,P=z.configToken.symbol,O=z.configToken.name,j=z.configToken.logo;else{const[pe,N,re]=await Promise.all([En(W,{address:z.address,abi:Vt,functionName:"decimals"}).catch(()=>18),En(W,{address:z.address,abi:Vt,functionName:"symbol"}).catch(()=>"TOKEN"),En(W,{address:z.address,abi:Vt,functionName:"name"}).catch(()=>"TOKEN")]);D=Number(pe),P=N,O=re}const L=Ae(z.address,t.address)&&z.chainId===t.chainId;L&&t.logoURI&&(j=t.logoURI),L&&!z.configToken&&P==="TOKEN"&&(P=t.symbol,O=t.symbol);const J=parseFloat((Number(q)/Math.pow(10,D)).toFixed(6));return{address:z.address,name:O,symbol:P,decimals:D,balance:q,balanceFormatted:J,balanceUsd:0,logoURI:j,isNative:!1,chainId:z.chainId}}catch{return null}},U=await Promise.all(Array.from(F.entries()).map(async([W,z])=>{let q;try{q=pt(W)}catch{return[]}const D=[],P=[];for(const j of z){const L=D.length;D.push({address:j.address,abi:Vt,functionName:"balanceOf",args:[T]}),j.configToken||D.push({address:j.address,abi:Vt,functionName:"decimals"},{address:j.address,abi:Vt,functionName:"symbol"},{address:j.address,abi:Vt,functionName:"name"}),P.push({start:L,item:j})}let O=null;try{O=await q.multicall({contracts:D})}catch{O=null}return O?P.map(({start:j,item:L})=>{const J=O[j],pe=J?.status==="success"?J.result:0n;let N,re,ce,xe;if(L.configToken)N=L.configToken.decimals,re=L.configToken.symbol,ce=L.configToken.name,xe=L.configToken.logo;else{const ve=O[j+1],H=O[j+2],ne=O[j+3];N=ve?.status==="success"?Number(ve.result):18,re=H?.status==="success"?H.result:"TOKEN",ce=ne?.status==="success"?ne.result:re}const De=Ae(L.address,t.address)&&L.chainId===t.chainId;De&&t.logoURI&&(xe=t.logoURI),De&&!L.configToken&&re==="TOKEN"&&(re=t.symbol,ce=t.symbol);const ue=parseFloat((Number(pe)/Math.pow(10,N)).toFixed(6));return{address:L.address,name:ce,symbol:re,decimals:N,balance:pe,balanceFormatted:ue,balanceUsd:0,logoURI:xe,isNative:!1,chainId:L.chainId}}):(await Promise.all(z.map(j=>M(q,j)))).filter(j=>j!==null)}));B===v.current&&C(U.flat())},[s,r,m,x,k,t.address,t.chainId,t.symbol,t.logoURI]);G(()=>{b.current=S},[S]),G(()=>{if(!s){C([]);return}b.current();const B=setInterval(()=>{b.current()},15e3);return()=>clearInterval(B)},[s,r,m,x,k,t.address,t.chainId]);const E=le(()=>{S()},[S]);return{displayAssets:se(()=>{const B=[],T=w.filter(A=>A.balance>0n);for(const A of T)B.push({...A,_source:"wallet"});for(const A of h)B.push({...A,_source:"spice"});const I=t.address.toLowerCase();return B.sort((A,F)=>wa(A,I,t.chainId)-wa(F,I,t.chainId)),B},[w,h,t.address,t.chainId]),filteredSpiceAssets:h,walletAssets:w,embeddedWalletAddress:p,externalAddress:c,isNon7702:r,refreshSpiceAssets:f,refreshWalletAssets:E}}async function Ca(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 pt(r).simulateContract({address:i.quoterV2,abi:ii,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 ka(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(s=>Ca({...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 _c=[{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 ed(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 pt(r).simulateContract({address:i.quoterV2,abi:_c,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 td(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(s=>ed({...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 va(e){return e.type==="swap"}const Gs=.02,nd=[1,8453,42161,10,137,43114,56],od="https://api.1inch.dev/swap/v6.0";function Ia(e,t){return ci(e,t)}function Aa(e){const t=e?.baseUrl??od;return{name:"1inch",chainIds:e?.chainIds??nd,resolve:async(n,o,s)=>{const r=n.maxSlippage??Gs,i=r*100,c=Pe(n.tokenIn)?lr:n.tokenIn,d=Pe(n.tokenOut)?lr:n.tokenOut,l=Pe(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=Ia(m,r),x=[];return h.tx.to&&!l&&x.push({to:n.tokenIn,value:0n,data:gt({abi:Vt,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 Sa=[4114,5115],Zs={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},Ea={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[3e3]};function Ba(e){return{name:"satsuma",chainIds:e.chainIds??Sa,resolve:async(t,n,o)=>{const s=t.maxSlippage??Gs,r=Pe(t.tokenIn);let i;try{i=await ka({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=Ia(i.amountOut,s),d=[];return r||d.push({to:t.tokenIn,value:0n,data:gt({abi:Vt,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),d.push({to:e.swapRouter,value:r?t.amountIn:0n,data:gt({abi:li,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??Sa,resolve:async(t,n,o)=>{const s=t.maxSlippage??Gs,r=Pe(t.tokenIn);let i;try{i=await td({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:sd,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 sd=[{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 Ta(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(Ba(e.satsuma)),t.push(Aa(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(!va(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 rd(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 ad=Ta({satsuma:Zs});function id(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,B]=R(null),T=ae(null),I=ae(null),A=ae(0),F=ae(new Map),M=se(()=>ad,[]),U=se(()=>rd({customVenues:[Fa(Zs),Fa(Ea)]}),[]),W=se(()=>{if(!n?.asset)return null;const N=Nn(n.asset,s);if(N)return N;const re=qn(n.asset.address,s,n.asset.chainId);return re?re.address:null},[n?.asset,s]),z=se(()=>n?.asset?Vo(n.asset,s):[],[n?.asset,s]),q=se(()=>z.map(N=>N.toLowerCase()).join(","),[z]);G(()=>{let N=!1;if(I.current&&(clearTimeout(I.current),I.current=null),!n?.asset||z.length<=1){B(null);return}return I.current=setTimeout(async()=>{const re=t==="input"?n.amount:i||"0";let ce=0n;try{ce=t==="input"?Le(re,n.asset.decimals):0n}catch{ce=0n}try{const xe=await Hr(n.asset,s,{requiredAmount:ce});N||B(xe)}catch{N||B(null)}},400),()=>{N=!0,I.current&&(clearTimeout(I.current),I.current=null)}},[n?.asset,n?.amount,s,z.length,q,t,i]);const D=se(()=>E??W,[E,W]),P=se(()=>!n?.asset||!D?[]:[D,...z.filter(N=>N.toLowerCase()!==D.toLowerCase())],[n?.asset,D,z]),O=se(()=>!n?.asset||!Bo(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,L=t==="output"&&parseFloat(i||"0")===0,J=!!n?.asset&&!O&&!j&&!L,pe=J?b??D:D;return G(()=>{T.current&&clearTimeout(T.current);const N=t==="input"?n?.amount:i,re=parseFloat(N||"0");if(!J||!Number.isFinite(re)||re<=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 ce=n.asset.decimals;let xe;try{xe=t==="input"?Le(n.amount,ce):Le(i||"0",o.decimals)}catch{A.current++,p("Invalid amount"),d(!1);return}const De=++A.current,ue=()=>De!==A.current;d(!0);const ve=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 ne=null,X=null;for(const fe of P){const Ee=`${t}:${s}:${fe.toLowerCase()}:${o.address.toLowerCase()}:${xe.toString()}`,we=F.current.get(Ee);if(we&&we.expiresAt>Date.now()&&we.resolvedSwap){ne=we.resolvedSwap,X=fe;break}const V=await H.resolve({type:"swap",tokenIn:fe,tokenOut:o.address,amountIn:xe},s,r);if(ue())return;if(V){F.current.set(Ee,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:V}),ne=V,X=fe;break}}if(!ne||!X)throw new Error("No liquidity for this pair");S(X),v(ne.amountOut),x(ne),w(null);const oe=parseFloat(ct(ne.amountOut,o.decimals));f(oe<.01?oe.toPrecision(4):oe.toLocaleString(void 0,{maximumFractionDigits:6})),m(null),p(null)}else{let H=null,ne=null;for(const X of P){const oe=`${t}:${s}:${X.toLowerCase()}:${o.address.toLowerCase()}:${xe.toString()}`,fe=F.current.get(oe);if(fe&&fe.expiresAt>Date.now()&&fe.exactOutputSwap){H=fe.exactOutputSwap,ne=X;break}try{const Ee=await U.getQuote({tokenIn:X,tokenOut:o.address,amountOut:xe},s,r);if(ue())return;F.current.set(oe,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:Ee}),H=Ee,ne=X;break}catch{if(ue())return}}if(!H||!ne)throw new Error("No liquidity for this pair");S(ne),w(H),x(null),v(null),m(parseFloat(ct(H.amountIn,ce)).toFixed(6)),f(null),p(null)}}catch(H){if(ue())return;const ne=H instanceof Error?H.message:"Failed to get quote";p(ne),f(null),m(null),x(null),w(null),v(null),S(null)}finally{ue()||d(!1)}},ve),()=>{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 Ma={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},Ra=["signing-delegation","signing-intent","submitting","executing"],ld=()=>{},Da=({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:B,onError:T})=>{const I=u==="output",{theme:A,dark:F,primaryColor:M,dk:U,palette:W,fontFamily:z,monoFont:q,inputDark:D,cardBg:P,cardBorder:O,textPrimary:j,textSecondary:L,subtitleText:J}=lt(C,v),pe=se(()=>D?{...A,colors:{...A.colors,secondary:U.cardBg,surfaceHover:U.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:A,[D,A,U.cardBg,U.hoverBg]),N=o.chainId,re=Yt(Ht),ce=(re?.mode||"7702")!=="7702",xe=!!re?.isWhitelistGateActive,De=se(()=>s??re?.supportedChainIds??[],[s,re?.supportedChainIds]),ue=se(()=>{if(xe)return[];if(r)return r;const me=re?.allowedTokens;if(!me||me.length===0)return;const tt=new Set(me.map(wn=>wn.toLowerCase())),bn=[],Mn=new Set;for(const wn of De){const ao=Fe(wn);for(const os of ao?.supportedTokens??[]){if(!tt.has(os.symbol.toLowerCase()))continue;const _s=os.address.toLowerCase();Mn.has(_s)||(Mn.add(_s),bn.push(os.address))}}return bn},[r,re?.allowedTokens,De,xe]),ve=Rn(),{address:H,isConnected:ne,isReady:X,isAuthenticated:oe,provider:fe}=ve,{executeGasless:Ee,estimateGasless:we}=Jo(),{externalWallet:V,externalAddress:Q,embeddedAddress:he,activeWallet:Ue,activeAddress:kt}=eo(),zt=Dn()||he,{displayAssets:Lt,filteredSpiceAssets:ot,embeddedWalletAddress:st,refreshSpiceAssets:Z,refreshWalletAssets:Ne}=$c({destinationToken:o,supportedSourceAssets:ue,sourceChains:De,enabled:e&&(ce?!!Q:!!zt)}),Ce=xe||I||ce?Lt:ot,[_,Ke]=R(null),[Mt,pn]=R(m||""),[ft,nn]=R(!1),[Wt,Zt]=R(null),[We,fn]=R("idle"),[on,Cn]=R(""),[qt,sn]=R(null),[yt,ht]=R(!1),[Qe,Xt]=R(null),[xt,ye]=R(null),[bt,et]=R(!1),[hn,be]=R(!1),[Kt,Rt]=R(null),Nt=ae(_),rt=ae(!1),rn=ae(null),Jt=ae(0),mn=ae(null),kn=ae(null);G(()=>{Nt.current=_},[_]);const dt=y==="adjustable"?Mt:m||"0",It=st||he||H,{isQuoting:Ye,quoteError:Dt,estimatedOutput:Fn,resolvedSwap:Ge,exactOutputSwap:at,quoteAmountOut:jt,resolvedTokenIn:mt,isDirect:Oe,needsSwap:He,selectedIsEquivalent:Ot}=id({direction:u,selectedAsset:_,destinationToken:o,chainId:N,recipient:It,paymentAmount:dt}),At=I?parseFloat(dt||"0"):parseFloat(_?.amount||"")||0,gn=_?.asset?._source==="wallet",ze=!!_?.asset&&gn&&_.asset.chainId!==N,Pn=se(()=>_?.asset?ot.find(me=>Ae(me.address,_.asset.address))?.balanceFormatted??0:0,[_,ot]),yn=gn?_?.asset.balanceFormatted??0:Pn,$=se(()=>{if(!_?.asset)return!1;if(I)return xt?mo(xt.grossAmount,xt.decimals,_.asset.decimals)>_.asset.balance:Ot||Oe?At>_.asset.balanceFormatted:at?parseFloat(ct(at.amountInMax,_.asset.decimals))>_.asset.balanceFormatted:!1;if(xt){const me=mo(xt.grossAmount,xt.decimals,_.asset.decimals);return gn?me>_.asset.balance:parseFloat(ct(me,_.asset.decimals))>yn}return At>yn},[_,I,xt,Ot,At,at,yn,gn,Oe]);G(()=>{e||(Ke(null),Zt(null),nn(!1),fn("idle"),Cn(""),sn(null),ht(!1),Xt(null),ye(null),et(!1),be(!1),Rt(null),rt.current=!1,y==="adjustable"&&pn(m||""),rn.current&&(rn.current.abort(),rn.current=null))},[e]);const ee=le(me=>{Ke(tt=>({asset:me,amount:tt?.asset?.address===me.address&&tt?.asset?.chainId===me.chainId&&tt.amount||""})),Zt(null),Rt(null),be(!1)},[]),ke=le(me=>{Ke(tt=>tt&&{...tt,amount:me}),Zt(null),Rt(null),be(!1)},[]),Ze=le(me=>{let tt=me;k&&parseFloat(tt)>parseFloat(k)&&(tt=k),pn(tt),w?.(tt),Zt(null),Rt(null),be(!1)},[k,w]);le(me=>{if(rt.current||!H)return;const tt=Nt.current;!tt?.asset||!tt.amount||tt.asset?._source==="wallet"||Le(I?dt:tt.amount,tt.asset.decimals)===0n||(rt.current=!0,Z())},[H,N,Z,I,dt]);const St=le(me=>{fn({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[me.step]||"executing"),Cn(me.message),me.txHash&&sn(me.txHash)},[]),Xe=se(()=>({currentPaymentAmount:dt,destinationToken:o,embeddedWalletAddress:st,providerEmbeddedAddress:he,externalWalletAddress:Q,address:H,isNon7702:ce,isPayMode:I,resolvedChainId:N,buildActionCalls:i,feeExecutionMode:c,buildSpicenetBatch:d,selectedAsset:_,needsSwap:He,resolvedSwap:Ge,exactOutputSwap:at,quoteAmountOut:jt,resolvedTokenIn:mt}),[dt,o,st,he,Q,H,ce,I,N,i,c,d,_,He,Ge,at,jt,mt]),ut=le(me=>Nc(Xe,me),[Xe]),Je=le(me=>Pc(Xe,me),[Xe]),Re=le((me,tt,bn,Mn)=>Uc(me,tt,bn,we,Mn),[we]),Et=se(()=>_?.asset?He&&mt?mt:_.asset.chainId===N?_.asset.address:mt??Nn(_.asset,N)??o.address:o.address,[_,o.address,He,N,mt]),je=le(()=>qc(kn.current),[]),Y=se(()=>_?.asset?Ae(_.asset.address,o.address)&&_.asset.chainId===o.chainId:!1,[_,o.address,o.chainId]),ge=ce&&Y,$e=ge&&At>0&&!!_?.asset,wt=Wt,_e=se(()=>!(!_?.asset||At<=0),[_,At,$e]),$t=se(()=>!e||ft||We!=="idle"||!_e||$e||!_?.asset?null:[I?"pay":"supply",u,_.asset.address.toLowerCase(),_.asset.chainId,_.amount,dt,o.address.toLowerCase(),o.chainId,N,mt?.toLowerCase()??"",He?"swap":"direct",Oe?"direct-token":"routed-token",ce?"non7702":"7702",Y?"source-dest":"cross-chain",Ye?"quoting":"quoted",at?.amountIn?.toString()??"",at?.amountInMax?.toString()??"",at?.venue??"",Ge?.amountOut?.toString()??"",jt?.toString()??"",st??"",he??"",H??""].join("|"),[e,ft,We,_e,$e,_,I,u,dt,o,N,mt,He,Oe,ce,Y,Ye,at,Ge,jt,st,he,H]),K=le(()=>Hc({selectedAsset:_,isPayMode:I,parsedAmount:At,needsSwap:He,exactOutputSwap:at,isNon7702:ce,isSourceDestToken:Y,currentPaymentAmount:dt,destinationToken:o,feeExecutionMode:c,resolvedTokenIn:mt,embeddedWalletAddress:st,providerEmbeddedAddress:he,resolvedChainId:N,isConnected:ne,address:H,ready:X,authenticated:oe,isDirect:Oe,resolvedSwap:Ge,isQuoting:Ye,executionTokenAddress:Et,buildPayChainBatches:ut,buildSupplyChainBatches:Je,estimateGasless:we,estimateRequiredGrossFunding:Re}),[_,I,At,He,at,ce,Y,dt,o,c,mt,st,he,Re,ut,we,N,ne,H,X,oe,Oe,Ge,Ye,Je,Et]);G(()=>{mn.current=K},[K]);const ie=le(me=>Oc({asset:me,isPayMode:I,isNon7702:ce,needsSwap:He,isQuoting:Ye,embeddedWalletAddress:st,buildSupplyChainBatches:Je,estimateGasless:we,executionTokenAddress:Et,feeExecutionMode:c}),[I,ce,He,Ye,st,Je,we,Et,c]);G(()=>{if(!e){et(!1),be(!1),Rt(null),ye(null);return}if(ft||We!=="idle"){Jt.current+=1,et(!1);return}if(!_e){ye(null),et(!1),be(!1),Rt(null);return}if($e){ye(null),et(!1),be(!0),Rt(null);return}if(Ye){Jt.current+=1,et(!1),be(!1);return}if(!$t)return;let me=!1;const tt=async()=>{const Mn=++Jt.current;Rt(null),et(!0);try{const wn=await mn.current?.();if(me||Jt.current!==Mn)return;wn?(ye(wn),be(!0)):(ye(null),be(!1)),Rt(null)}catch(wn){if(me||Jt.current!==Mn)return;const ao=In(wn,"Unable to calculate fees for this action.");ye(null),be(!1),Rt(ao)}finally{!me&&Jt.current===Mn&&et(!1)}},bn=window.setTimeout(()=>{tt()},250);return()=>{me=!0,clearTimeout(bn),et(!1)}},[e,ft,We,_e,$e,Ye,$t]);const de=le(()=>Gc(kn.current),[]);G(()=>{!I&&We==="success"&&qt&&(Z(),B?.(qt))},[I,We,qt,Z,B]),G(()=>{if(!I||Qe?.status!=="success"||rt.current||!H)return;rt.current=!0;const me=Nt.current;!me?.asset||me.asset?._source==="wallet"||Z()},[I,Qe?.status,H,Z]);const te=ae(B),Be=ae(T);G(()=>{te.current=B},[B]),G(()=>{Be.current=T},[T]),G(()=>{e&&(Z(),Ne())},[e,Z,Ne]),G(()=>{I&&(Qe?.status==="success"&&te.current?.(Qe.txHash||""),Qe?.status==="failed"&&Be.current?.(new Error("Payment execution failed")))},[I,Qe?.status]);const Se=le(()=>{ht(!1),Xt(null),Ke(null),rt.current=!1,Z(),Ne()},[Z,Ne]);kn.current={selectedAsset:_,parsedAmount:At,currentPaymentAmount:dt,isInsufficientBalance:$,isPayMode:I,isNon7702:ce,isSourceDestToken:Y,needsSwap:He,exactOutputSwap:at,selectedIsEquivalent:Ot,resolvedTokenIn:mt,embeddedWalletAddress:st,providerEmbeddedAddress:he,externalWallet:V,externalWalletAddress:Q,activeSignerWallet:Ue,activeSignerAddress:kt,address:H,isConnected:ne,ready:X,authenticated:oe,provider:fe,resolvedChainId:N,executionTokenAddress:Et,destinationToken:o,buildActionCalls:i,feeExecutionMode:c,buildSpicenetBatch:d,onPayExecute:l,onSuccess:B,onError:T,gasless:{estimateGasless:we,executeGasless:Ee,buildPayChainBatches:ut,buildSupplyChainBatches:Je,estimateRequiredGrossFunding:Re,onProgress:St},ui:{setError:Zt,setStep:fn,setStatusMsg:Cn,setTxHash:sn,setIsExecuting:nn,setShowStatusPanel:ht,setPaymentResult:Xt},refs:{spiceDepositSubmittedRef:rt,abortControllerRef:rn}};const Bt=m?.trim(),Ct=I&&y==="fixed"&&Bt!==void 0&&Bt!==""&&At===0,Ve=I?(Ct||!!_?.asset)&&At>=0&&!$&&!ft&&(Ct||$e||hn)&&!Kt&&(Ct||!He||!!at):!!_?.asset&&At>0&&!$&&!ft&&(ge||hn)&&!Kt&&(ze||Oe||!!Ge&&!Ye),it=Oe?h||`Your ${o.symbol} will be used directly.`:f||"Your assets will be swapped and used in a single atomic transaction.",an=(N?Fe(N):void 0)?.viemChain?.blockExplorers?.default?.url??"",Tn=Ra.indexOf(We),vn=ft?(Ma[We]||"EXECUTING...").toUpperCase():We==="success"?"DONE":$?"INSUFFICIENT BALANCE":p.toUpperCase(),xn=se(()=>{if(ft)return"PAYING...";if($&&_?.asset)return`INSUFFICIENT ${_.asset.symbol}`;if(p)return p.toUpperCase();const me=At>0?` ${dt} ${o.symbol}`:"";return He?`SWAP & PAY${me}`:`PAY${me}`},[ft,$,_,p,At,dt,o.symbol,He]),Un=We==="success"?()=>{fn("idle"),Ke(null),sn(null),Z()}:je,Ie=We==="success"?!1:!Ve;if(!e)return null;const vt=I?b||`Pay ${o.symbol}`:p,_t=I?S:g("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[a("span",{style:{marginTop:"3px",flexShrink:0},children:a(Ss,{color:J})}),a("p",{style:{fontSize:"12px",color:J,margin:0,lineHeight:"1.4",fontFamily:z},children:it})]});if(I){const me=Qe&&(Qe.status==="success"||Qe.status==="failed")?[{asset:{symbol:_?.asset?.symbol||o.symbol,address:_?.asset?.address||""},amount:dt,txHash:Qe.txHash||"",success:Qe.status==="success",error:Qe.status==="failed"?Qe.error:void 0}]:void 0;return a(jn,{isOpen:e,onClose:t,title:vt,subtitle:_t,styles:C,dark:F,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(Es,{onClick:E,color:M,fontFamily:z})}),!Ct&&a("div",{style:{marginBottom:"12px"},children:a(Eo,{assets:Ce,selectedAsset:_??void 0,onAssetSelect:ee,onAmountChange:ld,label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:_?.asset?He?Ye?"...":at?`~${parseFloat(ct(at.amountIn,_.asset.decimals)).toFixed(6)}`:void 0:dt??void 0:void 0,dark:F,theme:pe,styles:C})}),a(xa,{variant:"pay",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:M,fontFamily:z,textPrimary:j,textSecondary:L,cardBg:P,cardBorder:O,dk:U,dark:F,isQuoting:Ye,quoteError:Dt,estimatedOutput:Fn,paymentAmount:dt,needsSwap:He,exactOutputSwap:at,adjustable:y==="adjustable",maxAmount:k,onAmountChange:Ze}),_e&&a(Oo,{fontFamily:z,textPrimary:j,textSecondary:L,cardBg:P,cardBorder:O,resolvedDark:F,darkCardBorder:U.cardBorder,primaryColor:M,feePreview:xt,isLoading:bt,errorText:Kt,directExecutionFeeNote:$e}),wt&&a(po,{variant:"error",palette:W,fontFamily:z,style:{marginBottom:"12px"},children:wt}),a(Ft,{variant:"outline",fullWidth:!0,onClick:de,disabled:!Ve,loading:ft,dark:F,styles:{...C,button:{...C?.button,backgroundColor:M}},children:xn}),Qe&&yt&&a("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:F?U.shell:"white",borderRadius:F?"12px":"6px",padding:"16px 0"},children:a(Rs,{type:"payment",isOpen:Qe.status!=="processing",isProcessing:ft||Qe.status==="processing",closeOnComplete:!1,chainName:cn(N),explorerUrl:io(N,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{ht(!1),Xt(null),de()},onNewTx:Se,onClose:()=>{ht(!1),Xt(null)},onComplete:Se,results:me,styles:C,dark:F})})]})})}return a(jn,{isOpen:e,onClose:t,title:vt,subtitle:_t,dark:F,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(Eo,{assets:Ce,selectedAsset:_||void 0,onAssetSelect:ee,onAmountChange:ke,disabled:ft||We==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:pe,styles:C,dark:D,resolveMaxAmount:ie,maxAmount:yn>0?uo(yn,_?.asset.decimals??o.decimals):void 0})}),_?.asset&&!Oe&&a(xa,{variant:"supply",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:M,fontFamily:z,textPrimary:j,textSecondary:L,cardBg:P,cardBorder:O,dark:F,isQuoting:Ye,quoteError:Dt,estimatedOutput:Fn}),_e&&a(Oo,{fontFamily:z,textPrimary:j,textSecondary:L,cardBg:P,cardBorder:O,resolvedDark:F,darkCardBorder:U.cardBorder,primaryColor:M,feePreview:xt,isLoading:bt,errorText:Kt,directExecutionFeeNote:$e}),We!=="idle"&&g("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:We==="success"?P:We==="error"?W.errorBg:P,border:`1px solid ${We==="success"?O:We==="error"?W.errorBorder:O}`},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[We==="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"})}):We==="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(Kn,{size:14,color:M}),a("span",{style:{fontSize:"13px",fontWeight:500,color:We==="success"?j:We==="error"?W.errorText:j,fontFamily:z,flex:1},children:We==="success"?"Deposit confirmed":We==="error"?on||"Transaction failed":Ma[We]||on}),We==="success"&&qt&&a("a",{href:`${an}/tx/${qt}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:M,fontFamily:z,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),We==="error"&&a("button",{onClick:()=>{fn("idle"),Zt(null),setTimeout(je,50)},style:{background:"none",border:"none",fontSize:"12px",color:M,fontFamily:z,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),Tn>=0&&We!=="success"&&We!=="error"&&a("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${L}22`,overflow:"hidden"},children:a("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:M,transformOrigin:"left center",transform:`scaleX(${(Tn+1)/Ra.length})`,transition:"transform 400ms ease"}})})]}),Wt&&We==="idle"&&a(po,{variant:"error",palette:W,fontFamily:z,style:{marginBottom:"16px"},children:Wt}),a(Ft,{variant:"outline",fullWidth:!0,disabled:Ie,onClick:Un,theme:A,dark:F,styles:{...C,button:{...C?.button,backgroundColor:M}},style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:q},children:vn})]})})},cd=e=>a(Da,{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}),dd=({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=Yt(Ht),{isAuthenticated:u}=Rn();let f=null;try{f=pi()}catch{}let h=null,m=null;try{h=hi(),m=mi()}catch{h=null,m=null}const y=Za(m),x=le(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 Wa(e){const t=Yt(Ht),n=Dn(),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{...Mr(o,s),embeddedWalletAddress:n}}var ud="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 pd=({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 Ai(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:ud,alt:"","aria-hidden":"true",style:{width:"11px",height:"11px",display:"block",...c?{filter:"invert(0.65)"}:{}}})]}),a(vr,{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:Ts,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:lo(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:mr(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"})]})]})},fd=tn(pd),hd=({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=Fe(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}`)})})]}),md=tn(hd),gd=({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=Fe(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:lo(i.usdValue)})]})]},`${i.tokenAddress}-${i.chainId}-${c}`)})})]})},yd=tn(gd),xd=({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))})]})},bd=tn(xd),wd=({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(Ft,{variant:"outline",onClick:e,disabled:n,dark:r,styles:{button:{backgroundColor:s}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&a(Ft,{variant:"outline",onClick:t,disabled:o,dark:r,styles:{button:{backgroundColor:s}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),Cd=tn(wd),kd=({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[B,T]=R(!1);return g("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[a(fd,{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(Cd,{onDepositClick:u,onWithdrawClick:f,primaryColor:m,dark:x}),E&&g("div",{children:[g("button",{onClick:()=>T(!B),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:B?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),B&&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(md,{pendingDeposits:d,onCompleteDeposit:h,dk:y,dark:x}),a(yd,{spiceAssets:i,loading:c,dk:y,dark:x}),l.map((I,A)=>a(bd,{section:I,dk:y,dark:x},A))]})},vd=tn(kd),Xs=380,ro=8,Id=[];function Na(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function Ad(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=Na(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=Na(s);if(!i)continue;const c=n.get(i);if(c!==void 0)return c}return 0}const Sd=({appName:e="Spice",status:t="active",statusLabel:n,customSections:o=Id,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=Yt(Ht),k=x?.mode!=="7702",w=!!x?.isWhitelistGateActive,C=ae(!1);G(()=>{if(!C.current){if(Xa()){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),[B,T]=R({top:0,bottom:0,left:0,placement:"below"}),I=ae(null),A=ae(null),{address:F,isConnected:M}=Rn(),U=Dn(),{externalAddress:W,embeddedAddress:z}=eo(),{dark:q,primaryColor:D,dk:P}=lt(d,l),O=k&&!W,j=!k||O,L=j?U||z:F,J=se(()=>x?.supportedChainIds??Wo("mainnet"),[x?.supportedChainIds]),{assets:pe,loading:N}=Fo({address:L,supportedChains:J,enabled:!!L&&j,refetchInterval:3e4}),re=se(()=>{const Z=j?pe.map(Ce=>{const _=Ce.balanceUsd||0,Ke=Number.isFinite(Ce.balanceFormatted)?Ce.balanceFormatted:0,Mt=_>0?_:Ad(Ce,r)*Ke;return{tokenAddress:Ce.address,tokenSymbol:Ce.symbol,tokenDisplaySymbol:ks(Ce),tokenDisplayName:Mi(Ce),tokenDecimals:Ce.decimals,chainId:Ce.chainId,chainDisplayName:vs(Ce),balance:Ce.balance.toString(),balanceFormatted:Ce.balanceFormatted,usdValue:Mt,logoURI:Ce.logoURI}}):[],Ne=O?[]:s;return[...Z,...Ne].filter(Ce=>Ce.balanceFormatted>0)},[j,O,pe,r,s]),ce=se(()=>re.reduce((Z,Ne)=>Z+Ne.usdValue,0),[re]),{pendingDeposits:xe}=Wa({chainIds:J,enabled:!!F,discoverWalletBalances:!0}),De=se(()=>o.reduce((Z,Ne)=>Z+Ne.totalValue,0),[o]),ue=ce+De,ve=se(()=>{const Z=[];ce>0&&Z.push(`${lo(ce)} idle`);for(const Ne of o){const Ce=i.find(_=>_.sectionTitle===Ne.title)?.label||Ne.title.toLowerCase();Z.push(`${lo(Ne.totalValue)} ${Ce}`)}return Z.join(" \xB7 ")},[ce,o,i]),H=le(Z=>{h?h(Z):E(Z)},[h]),ne=le(()=>{E(null)},[]),X=le(()=>{E(null),p?.()},[p]),oe=le(()=>{if(!I.current)return;const Z=I.current.getBoundingClientRect(),Ne=window.innerHeight-Z.bottom-ro,Ce=Z.top-ro,_=Ne>=400||Ne>=Ce?"below":"above",Ke=Math.max(ro,Math.min(Z.right-Xs,window.innerWidth-Xs-ro)),Mt=_==="below"?Z.bottom+ro:Z.top-ro,pn=_==="above"?window.innerHeight-Mt:0;T({top:Mt,bottom:pn,left:Ke,placement:_})},[]);er(()=>{v&&oe()},[v,oe]),G(()=>{if(!v)return;const Z=_=>{I.current&&!I.current.contains(_.target)&&A.current&&!A.current.contains(_.target)&&b(!1)},Ne=_=>{_.key==="Escape"&&b(!1)},Ce=()=>oe();return document.addEventListener("mousedown",Z),document.addEventListener("keydown",Ne),window.addEventListener("scroll",Ce,{passive:!0}),window.addEventListener("resize",oe),()=>{document.removeEventListener("mousedown",Z),document.removeEventListener("keydown",Ne),window.removeEventListener("scroll",Ce),window.removeEventListener("resize",oe)}},[v,oe]);const fe=j?U||z||F:W||F,Ee=le(()=>{x?.setMode&&x.setMode(j?"ondemand":"7702")},[x,j]),[we,V]=R(null);let Q=null;try{Q=cr({onSuccess:()=>V(null),onError:Z=>V(In(Z,"Failed to connect wallet."))}).connectWallet}catch{Q=null}const he=le(()=>{Q&&(b(!1),V(null),Q({walletChainType:"ethereum-only"}))},[Q]),Ue=!W&&!!Q,kt=le(()=>{b(!1),u?.()},[u]),zt=le(()=>{b(!1),f?.()},[f]),Lt=le(Z=>{b(!1),H(Z)},[H]);if(typeof window>"u")return null;const ot=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 ",lo(ue)]}),a("span",{style:{fontSize:"10px",color:q?P.textSecondary:"#9ca3af",transform:v?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),st=v?dr.createPortal(g(en,{children:[a("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:Gn.popover},onClick:()=>b(!1)}),a("div",{ref:A,style:{position:"fixed",top:B.placement==="below"?`${B.top}px`:"auto",bottom:B.placement==="above"?`${B.bottom}px`:"auto",left:`${B.left}px`,width:`${Xs}px`,maxWidth:`calc(100vw - ${ro*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:Gn.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${Ut.out}`},children:a(vd,{appName:e,status:t,statusLabel:n,totalUsdValue:ue,breakdownSubtitle:ve,address:j?fe:F,spiceAssets:re,spiceAssetsLoading:N,pendingDeposits:xe,customSections:o,notice:c,onDepositClick:u?kt:void 0,onWithdrawClick:f?zt:void 0,onCompleteDeposit:Lt,primaryColor:D,dk:P,dark:q,showModeToggle:m,isEmbeddedMode:j,onModeToggle:Ee,showConnectExternalCta:Ue,onConnectExternalWallet:he,connectExternalError:we,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); }
|