@spicenet-io/spiceflow-ui 3.3.84 → 3.3.85
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -100,7 +100,7 @@ import{jsxs as g,jsx as a,Fragment as bn}from"react/jsx-runtime";import vn,{useS
|
|
|
100
100
|
from { transform: rotate(0deg); }
|
|
101
101
|
to { transform: rotate(360deg); }
|
|
102
102
|
}
|
|
103
|
-
`})]})},td="0xa9059cbb";function nd(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const s=Ne(n.token),o=Ne(n.to),r=`${s.toLowerCase()}:${o.toLowerCase()}`,i=t.get(r);i?i.amount+=n.amount:t.set(r,{token:s,to:o,amount:n.amount})}return[...t.values()]}function sd(e,t){return`0x${t}${e.slice(4)}`}function nr(e,t){return Ta(e,t)}function Ta(e,t,n){const s=od(t,e),o=Math.floor(Date.now()/1e3)+60*10,r=Nn(s);return{user:e,...n?{chainAuthorizations:n}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:"0x00",nbf:0,exp:o,chainBatches:r.map((i,c)=>({hash:i.hash,chainId:i.chainId,tokenTransfers:s[c].domain==="spicenet"?[]:s[c].tokenTransfers??[],calls:i.calls}))}]}}function od(e,t){return e.map(n=>{if(n.domain==="spicenet"||n.calls.length===0)return n;const s=new Set((n.tokenTransfers??[]).filter(r=>(r.from==="escrow"||r.from==="solver")&&Ne(r.to).toLowerCase()===t.toLowerCase()).map(r=>Ne(r.token).toLowerCase()));if(s.size===0)return n;let o=0;for(const r of n.calls){if(!r.data?.startsWith(td))break;try{const i=Es({abi:nt,data:r.data});if(i.functionName!=="transfer")break;const[c]=i.args;if(c.toLowerCase()===t.toLowerCase()||!s.has(Ne(r.to).toLowerCase()))break;o+=1}catch{break}}return o===0?n:{...n,calls:n.calls.slice(o)}})}function Rn(e,t,n,s){if(e.some(p=>p.domain==="spicenet"))return e;const o=n?.intents.flatMap(p=>p.batches),r=p=>p.from==="escrow",i=e.map(p=>{const u=o?.find(k=>k.chainId===p.chainId);if(!u)return p;const h=En(u),m=h.totalFee;if(m<=0n)return p;const f=(p.tokenTransfers??[]).find(k=>r(k)&&Ne(k.to).toLowerCase()===t.toLowerCase()&&!Ve(Ne(k.token)));if(!f)return p;const y=Ne(f.token);let x=!1;const C=(p.tokenTransfers??[]).map(k=>x||!r(k)||Ne(k.to).toLowerCase()!==t.toLowerCase()||Ne(k.token).toLowerCase()!==y.toLowerCase()?k:(x=!0,{...k,amount:s?.payoutAlreadyGross?BigInt(k.amount):BigInt(k.amount)+m}));if(!x)return p;const b=[];h.spicenetFee>0n&&b.push({to:y,value:0n,data:At({abi:nt,functionName:"transfer",args:[rs,h.spicenetFee]})});const A=h.gasFee+h.bridgeFee;return A>0n&&b.push({to:y,value:0n,data:At({abi:nt,functionName:"transfer",args:[Mn,A]})}),{...p,tokenTransfers:C,calls:[...b,...p.calls]}}),c=i.flatMap(p=>(p.tokenTransfers??[]).filter(r).map(u=>{const h=Ne(u.token),m=Ne(u.to),f=[{token:h,to:m,amount:BigInt(u.amount)}];return{chainId:p.chainId,transfers:nd(f)}}));if(c.length===0)return e;const d=s?.requestTimestampMs??Date.now(),l=BigInt(Math.floor(d/1e3))+3600n;return[{chainId:Ni,domain:"spicenet",tokenTransfers:[],calls:c.map((p,u)=>{const h=As(Ss([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,p.transfers[0].token,p.transfers.reduce((f,y)=>f+y.amount,0n),BigInt(p.chainId),BigInt(d+u)])),m=sd(h,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:At({abi:Io,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${p.chainId}`,idempotenceKey:m,nbf:0n,exp:l,metadata:"{}",transfers:p.transfers.map(f=>({token:f.token.toLowerCase(),to:f.to,amount:f.amount}))}]})}})},...i]}function ro(e,t){return t?e.some(n=>(n.tokenTransfers??[]).some(s=>s.from==="escrow"&&BigInt(s.amount)>=t.grossAmount)):!1}function Ma(e){return!e.isSemi7702&&e.isDirectDeposit&&!e.isSourceDestToken}function sr(e){const t=e.selectedAsset?.asset,n=e.selectedAsset?.amount;if(!(!t||!n))return Ye(n,t.decimals)}function Ra(e){return e.map(t=>({r:t.r,s:t.s,yParity:t.yParity,address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce)}))}function rd(e,t){if(e.length!==t.length)return!1;const n=Nn(e),s=Nn(t);return n.every((o,r)=>o.hash===s[r]?.hash)}async function ao({user:e,batches:t,authorizations:n,adjustBatchesForEstimate:s}){let o=t;const r=Ra(n);for(let i=0;i<10;i+=1){const c=await It.estimateActionFees(Ta(e,o,r)),d=await s({feeEstimate:c,batches:o});if(!d||rd(o,d))return o;o=d}throw new Error("Fee estimate did not converge. Please retry.")}function Ln(e,t){const n=e.selectedAsset?.asset;if(!n||!e.selectedAsset?.amount)throw new Error("Select an asset and enter an amount");const s=Ye(e.selectedAsset.amount,n.decimals),o=t?.grossAmount??s;return e.resolveLockBatches({amount:e.selectedAsset.amount,amountWei:s,grossAmount:pt(o,n.decimals),grossAmountWei:o})}async function io(e,t,n){const s=[...new Set(n.filter(r=>r.domain!=="spicenet").map(r=>r.chainId))],o=[];for(const r of s){const i=Tt(r),c=Hs(r),d=await vo(t,i),l=await e.actions.signAuthorization({contractAddress:c,chainId:r,nonce:Number(d)});o.push(l)}return o}async function or(e,t,n){const s=e.isSemi7702&&e.providerEmbeddedAddress||e.address;if(!e.isConnected||!s)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 o=n??await io(e,s,t),r=Nn(t),i=Math.floor(Date.now()/1e3)+60*10,c=r.map(m=>m.hash),d=As(Ss([{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((m,f)=>{const y=t[f],x=y.domain==="spicenet";return{hash:m.hash,chainId:m.chainId,tokenTransfers:x?[]:y.tokenTransfers??[],calls:m.calls}})},h=await It.createAction({user:s,chainAuthorizations:Ra(o),intents:[u]});if(h){const m=bo(t,In),[f,y]=h.intentIds[0].split("/"),x=parseInt(y||"0",10),C=h.intentIds[0];e.startStatusPolling(h.intentIds[0],m),await ua({actionId:f,intentIndex:x,intentId:C,totalSteps:t.length,isSpicenetStep:b=>t[b]?.domain==="spicenet",maxExecuteAttemptsForStep:b=>t[b]?.domain==="spicenet"?6:3,maxPolls:72})}}async function ad(e){let t=Ln(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 s=await io(e,n,t),o=Date.now();let r=Rn([...t],n,void 0,{requestTimestampMs:o}),i;r=await ao({user:n,batches:r,authorizations:s,adjustBatchesForEstimate:({feeEstimate:c})=>{const d=ls(c,{symbol:e.selectedAsset?.asset.symbol??"",decimals:e.selectedAsset?.asset.decimals??18,actionAmount:sr(e)});return d?(i={grossAmount:d.grossAmount,netAmount:d.netAmount,feeAmount:d.totalFee??0n},t=Ln(e,i),Rn([...t],n,c,{payoutAlreadyGross:ro(t,i),requestTimestampMs:o})):null}}),await or(e,r,s)}async function id(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");const n=e.resolveLockBatches();if(n.length===0)throw new Error("No lock batches configured");const s=e.selectedAsset.asset,o=Ye(e.selectedAsset.amount,s.decimals),r=s.chainId,i=e.escrowAddress||An(r),c=Lt(s.address),d=s.isNative||Ve(c),l=Date.now();let p;const u=n.some(C=>C.tokenTransfers?.some(b=>b.from==="escrow")),h=C=>({chainId:r,calls:d?[{to:i,value:C,data:"0x"}]:[{to:c,value:0n,data:At({abi:nt,functionName:"transfer",args:[i,C]})}]}),m=(C,b,A,k)=>{const w=h(C);if(!u)return[w,...b];const T=Rn([...b],t,A,{payoutAlreadyGross:ro(b,k),requestTimestampMs:l});return[w,...T]};let f=Ln(e),y=m(o,f);const x=await io(e,t,y);u&&(y=await ao({user:t,batches:y,authorizations:x,adjustBatchesForEstimate:({feeEstimate:C})=>{const b=ls(C,{symbol:s.symbol,decimals:s.decimals,actionAmount:o});return b?(p={grossAmount:b.grossAmount,netAmount:b.netAmount,feeAmount:b.totalFee??0n},f=Ln(e,p),m(p.grossAmount,f,C,p)):null}})),await or(e,y,x)}async function ld(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 B=e.resolveLockBatches();if(B.length===0)throw new Error("No lock batches configured");const F=e.selectedAsset.asset,v=Ye(e.selectedAsset.amount,F.decimals),E=await e.onLockExecute({asset:F,amount:e.selectedAsset.amount,amountWei:v,lockDurationMonths:e.selectedDuration?.months??0,chainBatches:B});E&&e.onLockSuccess?.(E);return}const n=e.resolveLockBatches();if(n.length===0)throw new Error("No lock batches configured");const s=e.selectedAsset.asset,o=Ye(e.selectedAsset.amount,s.decimals),r=s.chainId,i=e.escrowAddress||An(r),c=Lt(s.address),d=s.isNative||Ve(c),l=n.some(B=>B.tokenTransfers?.some(F=>F.from==="escrow")),p=Date.now();let u;const h=B=>({chainId:r,calls:d?[{to:i,value:B,data:"0x"}]:[{to:c,value:0n,data:At({abi:nt,functionName:"transfer",args:[i,B]})}]}),m=(B,F,v,E)=>{const I=h(B);if(!l)return[I,...F];const D=Rn([...F],t,v,{payoutAlreadyGross:ro(F,E),requestTimestampMs:p});return[I,...D]};let f=Ln(e),y=m(o,f);const x=await io(e,t,y);l&&(y=await ao({user:t,batches:y,authorizations:x,adjustBatchesForEstimate:({feeEstimate:B})=>{const F=ls(B,{symbol:s.symbol,decimals:s.decimals,actionAmount:o});return F?(u={grossAmount:F.grossAmount,netAmount:F.netAmount,feeAmount:F.totalFee??0n},f=Ln(e,u),m(u.grossAmount,f,B,u)):null}}));const C=u?.grossAmount??o,b=await e.externalWallet.getEthereumProvider();let A=null;try{const B=await b.request({method:"eth_chainId"});A=parseInt(B,16)}catch{A=null}A!==r&&await os(b,r);const k=De(r),w=Xn({account:e.externalWalletAddress,chain:k?.viemChain,transport:Jn(b)}),T=Tt(r),S=async B=>{if(B<=0n)return;const F=d?await w.sendTransaction({to:t,value:B,chain:k?.viemChain}):await w.sendTransaction({to:c,data:At({abi:nt,functionName:"transfer",args:[t,B]}),chain:k?.viemChain});if((await T.waitForTransactionReceipt({hash:F,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to embedded wallet failed")};await S(C);let W=C;if(l)for(let B=0;B<4;B+=1){y=await ao({user:t,batches:y,authorizations:x,adjustBatchesForEstimate:({feeEstimate:v})=>{const E=ls(v,{symbol:s.symbol,decimals:s.decimals,actionAmount:o});return E?(u={grossAmount:E.grossAmount,netAmount:E.netAmount,feeAmount:E.totalFee??0n},f=Ln(e,u),m(u.grossAmount,f,v,u)):null}});const F=u?.grossAmount??o;if(F<=W)break;await S(F-W),W=F}await or(e,y,x)}async function cd(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount||!e.requiresRelayerFeeEstimate)return null;if(e.isSemi7702||Ma(e)){const i=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address;if(!i)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");let c=Ln(e);if(c.length===0)throw new Error("No lock batches configured");const d=e.selectedAsset.asset,l=Ye(e.selectedAsset.amount,d.decimals),p=d.chainId,u=e.escrowAddress||An(p),h=Lt(d.address),m=d.isNative||Ve(h),f=c.some(k=>k.tokenTransfers?.some(w=>w.from==="escrow")),y=k=>({chainId:p,calls:m?[{to:u,value:k,data:"0x"}]:[{to:h,value:0n,data:At({abi:nt,functionName:"transfer",args:[u,k]})}]}),x=(k,w,T)=>{const S=y(k);if(!f)return[S,...w];const W=Rn([...w],i,T,{payoutAlreadyGross:w.some(B=>(B.tokenTransfers??[]).some(F=>F.from==="escrow"&&BigInt(F.amount)>=k))});return[S,...W]};let C=x(l,c),b=null,A;for(let k=0;k<4;k+=1){const w=await It.estimateActionFees(nr(i,C)),T=ls(w,{symbol:d.symbol,decimals:d.decimals,actionAmount:l});if(!T)return b;const S={grossAmount:T.grossAmount,netAmount:T.netAmount,feeAmount:T.totalFee??0n},W=A?.grossAmount===S.grossAmount&&A?.netAmount===S.netAmount&&A?.feeAmount===S.feeAmount;if(b=T,A=S,c=Ln(e,S),C=x(S.grossAmount,c,w),W)break}return b}const t=e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");let n=Ln(e);if(n.length===0)throw new Error("No lock batches configured");let s=Rn([...n],t),o=null;for(let i=0;i<4;i+=1){const c=await It.estimateActionFees(nr(t,s)),d=ls(c,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:sr(e)});if(!d)return null;const l={grossAmount:d.grossAmount},p=o?.grossAmount===d.grossAmount&&o?.netAmount===d.netAmount&&o?.totalFee===d.totalFee;if(o=d,n=Ln(e,l),s=Rn([...n],t,c,{payoutAlreadyGross:ro(n,l)}),p)break}if(o)return o;const r=await It.estimateActionFees(nr(t,s));return ls(r,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:sr(e)})}async function dd(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 s=e.resolveLockBatches();if(s.length===0)throw new Error("No lock batches configured");const o=s.find(u=>u.chainId===e.lockChainId)||s[0];if(!o)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 os(r,e.lockChainId);const c=De(e.lockChainId),d=Xn({account:n,chain:c?.viemChain,transport:Jn(r)}),l=Tt(e.lockChainId);let p;for(const u of o.calls){const h=await d.sendTransaction({to:u.to,data:u.data,value:u.value,chain:c?.viemChain});if((await l.waitForTransactionReceipt({hash:h,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Lock transaction failed");p=h}p&&e.onLockSuccess?.(p)}async function ud(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 s=Cn(n,""),o=typeof n?.shortMessage=="string"?n.shortMessage:typeof n?.message=="string"?n.message:"";e.ui.setError(s||o||"Transaction failed. Please try again.")};if(e.isSemi7702){if(e.isSourceDestToken){try{await dd(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{await ld(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{Ma(e)?await id(e):await ad(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}}const Da=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,lockBatches:s,lockTokenSymbol:o,lockTokenLogoURI:r,destinationInputHook:i,sourceAssetInputHook:c,lockDurationHook:d,lockChainId:l,durationOptions:p,votingPowerEstimate:u,escrowAddress:h,includeWalletAssets:m=!1,destinationTokenAddress:f,onLockSuccess:y,onLockExecute:x,sourceToDestinationConversionRate:C,estimatedOutputAmount:b,onAddFunds:A,buildSpicenetBatch:k,styles:w,dark:T=!1})=>{const{theme:S,dark:W,primaryColor:B,dk:F}=wt(w,T),v=S.typography.fontFamily,E=un(en),I=E?.mode||"7702",D=!!E?.isWhitelistGateActive,R=I!=="7702",L=te(()=>E?.supportedChainIds??[],[E?.supportedChainIds]),j=te(()=>{if(D)return[];const Z=E?.allowedTokens;if(!Z||Z.length===0)return[];const ke=new Set(Z.map(tt=>tt.toLowerCase())),vt=[],Nt=new Set;for(const tt of L){const Zt=De(tt);for(const xt of Zt?.supportedTokens??[]){if(!ke.has(xt.symbol.toLowerCase()))continue;const kn=`${tt}:${xt.address.toLowerCase()}`;Nt.has(kn)||(Nt.add(kn),vt.push(Ne(xt.address)))}}return vt},[E?.allowedTokens,L,D]),N=W?F.cardBg:w?.assetSelector?.backgroundColor||w?.secondaryBackground||"#e9e9e9",z=W?`1px solid ${F.cardBorder}`:"0.5px solid #A8A8A7",O=W?"12px":"6px",J=W?F.textPrimary:"#111827",P=W?F.textSecondary:"#6b7280",U=te(()=>({...w,assetSelector:{...w?.assetSelector,backgroundColor:W?F.cardBg:w?.assetSelector?.backgroundColor,borderRadius:W?"12px":w?.assetSelector?.borderRadius},secondaryBackground:W?F.cardBg:w?.secondaryBackground}),[w,W]),de=te(()=>W?{...S,colors:{...S.colors,secondary:F.cardBg,surfaceHover:F.hoverBg,border:F.cardBorder,borderHover:F.inputBorder}}:S,[W,S]),[H,$]=M(null),[ue,ve]=M(0),pe=d?.selectedDurationIdx??ue,me=d?.setSelectedDurationIdx??ve,[ge,K]=M(!1),[ie,X]=M(null),[ee,fe]=M(null),[Ce,be]=M(!1),[Q,ae]=M(!1),[_,Be]=M(null),[Ue,it]=M(!1),mt=ne(0),[Vt,st]=M(!1),[we,We]=M(null);Sr(),wo();const{chain:ze,address:$e}=vs();Ti();const lt=ne(ze);G(()=>{lt.current=ze},[ze]);const ft=Wn(),{isReady:q,isAuthenticated:qe,isConnected:Se,address:ot,provider:_e,actions:nn}=ft,{externalWallet:Ot,embeddedAddress:gt,externalAddress:Fe,activeWallet:St,activeAddress:Ht}=On(),{intentStatus:Le,startStatusPolling:sn,clearStatus:Me}=Qr({checkStepStatus:(Z,ke)=>It.checkStepStatus(Z,ke),retryStep:async(Z,ke)=>{const[vt,Nt]=Z.split("/"),tt=parseInt(Nt||"0",10);await It.executeStep(vt,tt,ke,{action:"execute"})},maxRetries:3}),{assets:Gt,refetch:Xt}=Ds({address:ot,supportedChains:L,enabled:e&&Se&&!R&&!D,refetchInterval:3e4}),Ge=te(()=>{if(D)return[];if(j.length===0)return Gt;const Z=new Set(j.map(ke=>ke.toLowerCase()));return Gt.filter(ke=>Z.has(ke.address.toLowerCase()))},[Gt,j,D]),ye=Tn(),Ze=Fe||$e,et=R?Ht??Ze:ye,rn=te(()=>{if(!m)return[];if(D)return f?[Ne(f)]:[];const Z=new Set,ke=[],vt=Nt=>{if(!Nt)return;const tt=Nt.toLowerCase();Z.has(tt)||(Z.add(tt),ke.push(Ne(Nt)))};f&&vt(f);for(const Nt of j)vt(Nt);return ke},[m,R,f,j,D]),Ie=te(()=>rn.map(Z=>Z.toLowerCase()).sort().join(","),[rn]),Yt=te(()=>JSON.stringify([...L||[]].sort()),[L]),[Mt,Ct]=M([]),Ke=ne(0),an=ne(async()=>{}),Pt=oe(async()=>{if(!m||!et||rn.length===0){Ke.current++,Ct([]);return}const Z=++Ke.current,ke=Ne(et),vt=R?L&&L.length>0?L:[l]:[l],Nt=rn.map(V=>{const Y=V.toLowerCase();if(f&&Ee(V,f)){const he=De(l)?.supportedTokens?.find(ce=>Ee(ce.address,Y));return{address:V,chainId:l,configToken:he?{decimals:he.decimals,symbol:he.symbol,name:he.name,logo:he.logo}:void 0}}for(const he of vt){const ce=De(he)?.supportedTokens?.find(je=>Ee(je.address,Y));if(ce)return{address:V,chainId:he,configToken:{decimals:ce.decimals,symbol:ce.symbol,name:ce.name,logo:ce.logo}}}return{address:V,chainId:l}}),tt=new Map;for(const V of Nt){const Y=tt.get(V.chainId)||[];Y.push(V),tt.set(V.chainId,Y)}const Zt=async(V,Y)=>{try{const he=await Un(V,{address:Y.address,abi:nt,functionName:"balanceOf",args:[ke]});let ce,je,Oe,at;if(Y.configToken)ce=Y.configToken.decimals,je=Y.configToken.symbol,Oe=Y.configToken.name,at=Y.configToken.logo;else{const[gn,yn,_t]=await Promise.all([Un(V,{address:Y.address,abi:nt,functionName:"decimals",args:[]}).catch(()=>18),Un(V,{address:Y.address,abi:nt,functionName:"symbol",args:[]}).catch(()=>"TOKEN"),Un(V,{address:Y.address,abi:nt,functionName:"name",args:[]}).catch(()=>"TOKEN")]);ce=Number(gn),je=yn,Oe=_t}const bt=!!f&&Ee(Y.address,f)&&Y.chainId===l;bt&&r&&(at=r),bt&&o&&!Y.configToken&&(je==="TOKEN"&&(je=o),Oe==="TOKEN"&&(Oe=o));const $t=parseFloat((Number(he)/Math.pow(10,ce)).toFixed(6));return{address:Y.address,name:Oe,symbol:je,decimals:ce,balance:he,balanceFormatted:$t,balanceUsd:0,logoURI:at,isNative:!1,chainId:Y.chainId}}catch{return null}},xt=await Promise.all(Array.from(tt.entries()).map(async([V,Y])=>{let he;try{he=Tt(V)}catch{return[]}const ce=[],je=[];for(const at of Y){const bt=ce.length;ce.push({address:at.address,abi:nt,functionName:"balanceOf",args:[ke]}),at.configToken||ce.push({address:at.address,abi:nt,functionName:"decimals",args:[]},{address:at.address,abi:nt,functionName:"symbol",args:[]},{address:at.address,abi:nt,functionName:"name",args:[]}),je.push({start:bt,item:at})}let Oe=null;try{Oe=await he.multicall({contracts:ce})}catch{Oe=null}return Oe?je.map(({start:at,item:bt})=>{const $t=Oe[at],gn=$t?.status==="success"?$t.result:0n;let yn,_t,Fn,ns;if(bt.configToken)yn=bt.configToken.decimals,_t=bt.configToken.symbol,Fn=bt.configToken.name,ns=bt.configToken.logo;else{const xn=Oe[at+1],Bn=Oe[at+2],us=Oe[at+3];yn=xn?.status==="success"?Number(xn.result):18,_t=Bn?.status==="success"?Bn.result:"TOKEN",Fn=us?.status==="success"?us.result:_t}const Te=!!f&&Ee(bt.address,f)&&bt.chainId===l;Te&&r&&(ns=r),Te&&o&&!bt.configToken&&(_t==="TOKEN"&&(_t=o),Fn==="TOKEN"&&(Fn=o));const jt=parseFloat((Number(gn)/Math.pow(10,yn)).toFixed(6));return{address:bt.address,name:Fn,symbol:_t,decimals:yn,balance:gn,balanceFormatted:jt,balanceUsd:0,logoURI:ns,isNative:!1,chainId:bt.chainId}}):(await Promise.all(Y.map(at=>Zt(he,at)))).filter(at=>at!==null)}));if(Z!==Ke.current)return;const kn=xt.flat();Ct(kn)},[m,R,et,Ie,Yt,l,f,r,o]);G(()=>{an.current=Pt},[Pt]),G(()=>{if(!e||!m){Ct([]);return}an.current();const Z=setInterval(()=>{an.current()},15e3);return()=>clearInterval(Z)},[m,e,et,Ie,Yt,l,f]);const ln=oe(()=>{Pt()},[Pt]),Jt=te(()=>Mt.filter(Z=>Z.balance>0n),[Mt]),qt=te(()=>{if(R)return Jt.map(ke=>({...ke,_source:"wallet"}));if(!m)return Ge;const Z=[];for(const ke of Jt)Z.push({...ke,_source:"wallet"});for(const ke of Ge)Z.push({...ke,_source:"spice"});return Z},[R,m,Jt,Ge]),Rt=te(()=>D?f?qt.filter(Z=>Ee(Z.address,f)&&Z.chainId===l):[]:qt,[qt,D,f,l]),yt=ne(null),Qe=ne(null);G(()=>{Qe.current=H},[H]),G(()=>{!D||!H?.asset||f&&Ee(H.asset.address,f)&&H.asset.chainId===l||$(null)},[D,H?.asset,f,l]),G(()=>{e||($(null),X(null),fe(null),be(!1),ae(!1),Be(null),K(!1),st(!1),We(null),it(!1),Me())},[e,Me]),G(()=>{i&&i.assetAmount!==(H?.amount||"")&&$(Z=>Z&&{...Z,amount:i.assetAmount})},[i?.assetAmount]),G(()=>{c&&c.assetAmount!==(H?.amount||"")&&$(Z=>Z&&{...Z,amount:c.assetAmount})},[c?.assetAmount]),G(()=>{if(!R&&Le?.overallStatus==="success"&&Le.intentId&&yt.current!==Le.intentId&&ot&&Le.steps.find(Z=>Z.transactionHash)?.transactionHash){yt.current=Le.intentId;const Z=Qe.current;if(!Z?.asset||!Z.amount||Z.asset._source==="wallet"||Ye(Z.amount,Z.asset.decimals)===0n)return;Xt()}},[Le,ot,l,Xt,R]);const ct=parseFloat(H?.amount||"")||0,Dt=ct>0&&ct<Vn,cn=te(()=>H?.asset?H.asset._source==="wallet"?H.asset.balanceFormatted??0:Ge.find(Z=>Ee(Z.address,H.asset.address)&&Z.chainId===H.asset.chainId)?.balanceFormatted??0:0,[H?.asset,Ge]),dn=ct>0&&(_?parseFloat(pt(_.grossAmount,_.decimals))>cn:ct>cn),Ut=d?.selectedDuration??p[pe]??p[0],le=te(()=>!H?.asset||!f?!1:Ee(H.asset.address,f)&&H.asset.chainId===l,[H?.asset,f,l]),ht=te(()=>ct<=0?0:le?ct:!C||C<=0?0:ct/C,[ct,C,le]),dt=te(()=>ht<=0?null:ht.toLocaleString(void 0,{maximumFractionDigits:2}),[ht]),Et=u&&ht>0&&Ut?u(ht,Ut.months):void 0,rt=te(()=>ct<=0?"$0.00":le&&C?(ct*C).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!C||C<=0?"$0.00":ct.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[ct,C,le]),Pe=te(()=>{if(!dt)return null;const Z=parseFloat(dt.replace(/,/g,""));return le&&C?(Z*C).toLocaleString(void 0,{maximumFractionDigits:2}):C?(Z*C).toLocaleString(void 0,{maximumFractionDigits:2}):null},[dt,C,le]),kt=oe(Z=>{$(ke=>({asset:Z,amount:ke?.asset?.address===Z.address&&ke?.asset?.chainId===Z.chainId&&ke.amount||""})),X(null),fe(null),ae(!1),Be(null),c?.setSelectedAsset&&c.setSelectedAsset({symbol:Z.symbol,address:Z.address,decimals:Z.decimals,chainId:Z.chainId})},[c?.setSelectedAsset]),mn=oe(Z=>{$(ke=>ke&&{...ke,amount:Z}),X(null),fe(null),ae(!1),Be(null),i&&i.setAssetAmount(Z),c&&c.setAssetAmount(Z)},[i,c]),se=oe(Z=>{if(typeof s=="function"){if(!H?.asset||!H.amount)throw new Error("Select an asset and enter an amount");return s({asset:H.asset,amount:Z?.amount??H.amount,amountWei:Z?.amountWei??Ye(H.amount,H.asset.decimals),grossAmount:Z?.grossAmount,grossAmountWei:Z?.grossAmountWei,feeAdjusted:!!Z})}return s},[s,H]),re=ne(null),Ae=te(()=>!H?.asset||ct<=0?!1:R?!le&&!x:!0,[H,ct,R,le,x]),Xe=oe(()=>cd(re.current),[]),ut=te(()=>!H?.asset||ct<=0?null:`${H.asset.address.toLowerCase()}:${H.asset.chainId}:${H.amount??""}`,[H?.asset?.address,H?.asset?.chainId,H?.amount,ct]);G(()=>{if(!e||ge)return;if(!H?.asset||ct<=0){fe(null),be(!1),ae(!1),Be(null);return}if(!Ae){fe(null),be(!1),ae(!0),Be(null);return}let Z=!1;const ke=async tt=>{const Zt=++mt.current;tt||(fe(null),ae(!1),be(!0));try{const xt=await Xe();if(Z||mt.current!==Zt)return;fe(null),ae(!0),Be(xt)}catch(xt){if(Z||mt.current!==Zt)return;tt||(fe(Cn(xt,"Unable to calculate fees for this lock.")),ae(!1))}finally{!Z&&mt.current===Zt&&!tt&&be(!1)}},vt=window.setTimeout(()=>{ke(!1)},250),Nt=window.setInterval(()=>{ke(!0)},3e4);return()=>{Z=!0,clearTimeout(vt),window.clearInterval(Nt)}},[e,ge,ut,Ae,Xe]),G(()=>{if(Le?.overallStatus==="success"){const Z=Le.steps.find(ke=>ke.transactionHash);y?.(Z?.transactionHash)}},[Le?.overallStatus,y]);const Ft=m&&H?.asset?._source==="wallet"&&H?.asset?.chainId===l,Wt=oe(()=>ud(re.current),[]),Bt=!!H?.asset&&ct>0&&!Dt&&!dn&&!ge&&(!Ae||Q&&!Ce&&!ee),He=ie||ee,Kt=g("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[a(Oo,{color:P}),g("p",{style:{fontSize:"13px",color:P,margin:0,lineHeight:"1.5"},children:["Add ",o," by converting assets from your account"]})]});if(re.current={selectedAsset:H,parsedAmount:ct,selectedDuration:Ut,isInsufficientBalance:dn,isSemi7702:R,isSourceDestToken:le,isDirectDeposit:Ft,requiresRelayerFeeEstimate:Ae,address:ot,embeddedWalletAddress:ye,providerEmbeddedAddress:gt,externalWallet:Ot,externalWalletAddress:Ze,activeSignerWallet:St,activeSignerAddress:Ht,isConnected:Se,ready:q,authenticated:qe,provider:_e,actions:nn,lockChainId:l,escrowAddress:h,onLockExecute:x,onLockSuccess:y,buildSpicenetBatch:k,resolveLockBatches:se,startStatusPolling:sn,refreshSpiceAssets:Xt,refreshWalletAssets:ln,ui:{setError:X,setIsExecuting:K,setShowStatusPanel:it}},!e)return null;const Je={backgroundColor:N,border:z,borderRadius:O,padding:"16px",marginBottom:"16px"};return a(jn,{isOpen:e,onClose:t,title:`Add ${o} to your account`,subtitle:Kt,styles:w,dark:W,footerLinkText:"Spicenet accounts \u2192",overlayContent:Vt?a("div",{}):void 0,closeOnBackdropClick:n,children:g("div",{style:{padding:"0 24px 8px 24px",position:"relative"},children:[g("div",{style:{marginBottom:"12px"},children:[A&&a("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:a(Ho,{onClick:A,color:B,fontFamily:v})}),a("div",{style:{marginTop:"10px",fontSize:"13px",color:P,fontFamily:v},children:a(Ms,{assets:Rt,selectedAsset:H??void 0,onAssetSelect:kt,onAmountChange:mn,label:"Amount",showBalance:!0,showMaxButton:!0,theme:de,styles:U})}),a("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:P,fontFamily:v},children:rt})]}),g("div",{style:Je,children:[g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:W?`1px solid ${F.cardBorder}`:"1px solid #e5e7eb"},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[r?a("img",{src:r,alt:o,style:{width:"32px",height:"32px",borderRadius:"50%",objectFit:"cover"}}):a("div",{style:{width:"32px",height:"32px",borderRadius:"50%",backgroundColor:W?F.inputBg:"#d1d5db",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:700,color:J},children:o.slice(0,2)}),a("span",{style:{fontSize:"16px",fontWeight:600,color:J,fontFamily:v},children:o})]}),g("div",{style:{textAlign:"right"},children:[a("div",{style:{fontSize:"22px",fontWeight:700,color:J,fontFamily:v,lineHeight:1.1},children:dt??"0.00"}),g("div",{style:{fontSize:"12px",color:P,fontFamily:v,marginTop:"2px"},children:["~$",Pe??"0.00"]})]})]}),g("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:W?`1px solid ${F.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:P,fontFamily:v},children:"Lock Duration"}),a(Qn,{color:P})]}),a(Gc,{options:p,selectedIndex:pe,onSelect:me,primaryColor:B,dark:W,textPrimary:J,textSecondary:P})]}),g("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[a(Jc,{durationMonths:Ut?.months,fontFamily:v,dark:W,textPrimary:J,textSecondary:P}),u&&a(_c,{votes:Et,fontFamily:v,dark:W,textPrimary:J,textSecondary:P})]})]}),Ae&&a(Gs,{fontFamily:v,textPrimary:J,textSecondary:P,cardBg:N,cardBorder:z,resolvedDark:W,darkCardBorder:F.cardBorder,primaryColor:B,feePreview:_,isLoading:Ce,errorText:ee}),He&&a(xs,{variant:"error",palette:F,fontFamily:v,style:{marginBottom:"12px"},children:He}),a(Qt,{variant:"outline",fullWidth:!0,onClick:Wt,disabled:!Bt,loading:ge,dark:W,styles:{...w,button:{...w?.button,backgroundColor:B}},children:ge?le?"LOCKING...":"CONVERTING...":Dt?`MINIMUM ${Vn}`:Ce&&Ae?"CALCULATING FEES...":le?`LOCK ${o}`:`CONVERT TO ${o}`}),a(ed,{isOpen:Vt,data:we,isLocking:ge,lockError:He,onContinue:Wt,onClose:()=>st(!1),primaryColor:B,fontFamily:v,dark:W}),Le&&Ue&&a("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:W?"rgba(0, 0, 0, 0.45)":"rgba(255, 255, 255, 0.55)",backdropFilter:"blur(2px)",WebkitBackdropFilter:"blur(2px)",borderRadius:O},children:a(Ko,{type:"lock",showStepBreakdown:!1,isOpen:!!Le&&Le.overallStatus!=="processing",isProcessing:ge||Le?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{Me(),it(!1),Wt()},onNewTx:()=>{Me(),it(!1),$(null),yt.current=null,Xt(),ln()},onClose:()=>{Me(),it(!1)},onComplete:()=>{Me(),it(!1),$(null),yt.current=null,Xt(),ln()},results:Le?.overallStatus==="success"||Le?.overallStatus==="failed"?Le.steps.map(Z=>({asset:{symbol:H?.asset?.symbol||o,address:H?.asset?.address||""},txHash:Z.transactionHash||"",success:Z.status==="success",amount:H?.amount})):void 0,chainName:In(l),explorerUrl:hs(l,"").replace(/\/tx\/.*$/,"")||void 0,theme:S,styles:w,dark:W})})]})})},pd="0xa9059cbb";function Wa(e,t,n){return Ve(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:At({abi:fn,functionName:"transfer",args:[n,t]})}}function Na(e,t,n){return{chainId:n,calls:[Wa(e,t,An(n))]}}function Pa(e,t,n){return!t&&e?.asset?._source==="wallet"&&e?.asset.chainId===n}function Ua(e,t,n,s){return t!=="user-transfer"||!n||e.length===0||e[0]?.to.toLowerCase()!==s.toLowerCase()||!e[0]?.data.startsWith(pd)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function lo(e,t,n,s){if(!t)return[e];const o=await t({...n,requestTimestampMs:s});return o?[o,e]:[e]}function Ns(e){return e.filter(t=>t.domain!=="spicenet")}function co(e){const t=(e.tokenTransfers??[]).filter(n=>n.from==="escrow").map(n=>({token:Lt(n.token),recipient:n.to,amount:BigInt(n.amount)})).filter(n=>n.amount>0n);return t.length>0?t:void 0}function Dn(e,t,n){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const s=10n**BigInt(t-n);return(e+s-1n)/s}async function rr(e,t){const{currentPaymentAmount:n,destinationToken:s,embeddedWalletAddress:o,providerEmbeddedAddress:r,address:i,isNon7702:c,isPayMode:d,resolvedChainId:l,buildActionCalls:p,feeExecutionMode:u,buildSpicenetBatch:h,selectedAsset:m,needsSwap:f,exactOutputSwap:y,resolvedTokenIn:x,requestTimestampMs:C}=e,b=Ye(n,s.decimals),A=t?.actionAmountOverride??b,k=o||r||(c?void 0:i);if(!k)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const w={userAddress:k,chainId:l,destinationToken:s.address,grossAmount:t?.fundingAmountOverride??b,netAmount:A,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:u,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},T=p(A,w),S={chainId:l,calls:T},W=!d&&!c?!0:m?.asset?._source==="spice",B=Pa(m??null,c,l),F=W||c||B,v=(I,D)=>({token:I,from:c?"solver":"escrow",to:k,amount:D}),E=(I,D,R)=>B?[Na(I,D,l),...R]:R;if(b===0n)return[S];if(f&&y){const I=x??zn(m.asset,l)??m.asset.address,D=t?.fundingAmountOverride??y.amountInMax,R=F?[v(I,D)]:[],L={to:I,value:0n,data:At({abi:fn,functionName:"approve",args:[y.calls[0]?.to,y.amountInMax]})},j={chainId:l,calls:[L,...y.calls,...T],tokenTransfers:[...R,...S.tokenTransfers??[]]};if(!F)return[j];const N=await lo(j,h,{userAddress:k,destinationChainId:l,deliveryToken:I,deliveryAmount:D,deliveryRecipient:k,deliveryTransfers:co(j),sourceAsset:m.asset},C);return E(I,D,N)}if(F){const I=x??zn(m.asset,l)??s.address,D=t?.fundingAmountOverride??b,R={...S,tokenTransfers:[v(I,D),...S.tokenTransfers??[]]},L=await lo(R,h,{userAddress:k,destinationChainId:l,deliveryToken:I,deliveryAmount:D,deliveryRecipient:k,deliveryTransfers:co(R),sourceAsset:m.asset},C);return E(I,D,L)}return[S]}async function ar(e,t){const{selectedAsset:n,embeddedWalletAddress:s,externalWalletAddress:o,recipient:r,resolvedChainId:i,destinationToken:c,buildActionCalls:d,feeExecutionMode:l,buildSpicenetBatch:p,isPayMode:u,isNon7702:h,needsSwap:m,resolvedSwap:f,quoteAmountOut:y,resolvedTokenIn:x,requestTimestampMs:C}=e,b=f?.amountOutMinimum??y;if(!n?.asset||!s)return[];const A=r??(h?o:s);if(!A)return[];const k=t?.fundingAmountOverride??t?.actionAmountOverride??Ye(n.amount,n.asset.decimals),w=t?.fundingAmountOverride??k,T=t?.sourceFundingAmountOverride??k,S=t?.deliveryAmountOverride??w,W=t?.withdrawalAmountOverride??S,B=t?.actionAmountOverride??k,F={userAddress:A,chainId:i,destinationToken:c.address,feeToken:l==="user-transfer"&&m&&x?x:c.address,grossAmount:w,netAmount:B,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:l,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},v=d(B,F),E=n.asset?._source==="wallet";if(!u&&h&&E&&n.asset.chainId===i){if(m){if(!x)throw new Error("Swap input token could not be resolved");if(!f||b===null)throw new Error("Swap quote not available yet")}if(m&&f&&b){const P=d(t?.actionAmountOverride??b,{...F,netAmount:t?.actionAmountOverride??b}),{feeCall:U,remainingCalls:de}=Ua(P,l,m,F.feeToken);return[{chainId:i,calls:[...U?[U]:[],...f.calls,...de]}]}return[{chainId:i,calls:v}]}if(!u&&!h&&E&&n.asset.chainId!==i)throw new Error("Cross-chain wallet supplies require external wallet mode");const I=!u&&!h?n.asset?._source!=="wallet":n.asset?._source==="spice",D=h&&E,R=Pa(n,h,i);if(!(I||D||R))return[{chainId:i,calls:v}];const L=R?Na(x??Lt(n.asset.address),T,i):D&&n.asset.chainId!==i?{chainId:n.asset.chainId,calls:[Wa(Lt(n.asset.address),T,An(n.asset.chainId))]}:null,j=(P,U)=>({token:P,from:D?"solver":"escrow",to:s,amount:U}),N=(P,U)=>D?[{token:P,from:"escrow",to:Pi,amount:U}]:[];if(m){if(!x)throw new Error("Swap input token could not be resolved");if(!f||b===null)throw new Error("Swap quote not available yet")}if(m&&f&&b&&x){const P=d(t?.actionAmountOverride??b,{...F,netAmount:t?.actionAmountOverride??b}),{feeCall:U,remainingCalls:de}=Ua(P,l,m,F.feeToken),H={chainId:i,calls:[...U?[U]:[],...f.calls,...de],tokenTransfers:[...N(x,W),j(x,S)]},$=await lo(H,p,{userAddress:s,destinationChainId:i,deliveryToken:x,deliveryAmount:S,withdrawalAmount:W,deliveryRecipient:s,deliveryTransfers:co(H),sourceAsset:n.asset},C);return L?[L,...$]:$}const z=x??zn(n.asset,i)??c.address,O={chainId:i,calls:v,tokenTransfers:[...N(z,W),j(z,S)]},J=await lo(O,p,{userAddress:s,destinationChainId:i,deliveryToken:z,deliveryAmount:S,withdrawalAmount:W,deliveryRecipient:s,deliveryTransfers:co(O),sourceAsset:n.asset},C);return L?[L,...J]:J}async function ir(e,t,n,s,o){let r=e;for(let i=0;i<4;i++){const c=await t(r),d=await s(c,n,r,o),l=wc(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 fd(e,t,n,s){if(e<=0n)return 0n;const o=e-t;if(o<=0n)return 0n;const r=s+n;return r<=0n?o:o*s/r}function hd(e,t){const n=pt(e,t);return n.includes(".")?n.replace(/\.?0+$/,"")||"0":n}async function za(e){const{asset:t,isPayMode:n,isNon7702:s,needsSwap:o,isQuoting:r,embeddedWalletAddress:i,buildSupplyChainBatches:c,estimateGasless:d,executionTokenAddress:l,feeExecutionMode:p}=e;if(n||s||o||r||!i||t.balance<=0n)return null;const u=i,h=await c({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(h.length===0)return null;const m=h.some(A=>A.tokenTransfers?.length),f=await d(h,l,t.balance,m?{userOverride:u,useCustomTransfers:!0,feeExecutionMode:p}:p?{userOverride:u,feeExecutionMode:p}:{userOverride:u}),y=es(f,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),x=y?Dn(y.gasFee,y.decimals,t.decimals):0n,C=y?Dn(y.spicenetFee,y.decimals,t.decimals):0n,b=fd(t.balance,x,C,t.balance);return b>0n?hd(b,t.decimals):null}async function lr(e){const{selectedAsset:t,isPayMode:n,parsedAmount:s,needsSwap:o,exactOutputSwap:r,isNon7702:i,isSourceDestToken:c,currentPaymentAmount:d,destinationToken:l,feeExecutionMode:p,resolvedTokenIn:u,embeddedWalletAddress:h,providerEmbeddedAddress:m,resolvedChainId:f,isConnected:y,address:x,ready:C,authenticated:b,isDirect:A,resolvedSwap:k,isQuoting:w,executionTokenAddress:T,buildPayChainBatches:S,buildSupplyChainBatches:W,estimateGasless:B,estimateRequiredGrossFunding:F}=e;if(!t?.asset)return null;if(n){if(s<=0||o&&!r||c)return null;const N=Ye(d,l.decimals),z=u||zn(t.asset,f)||t.asset.address||l.address,O={chainId:f,tokenAddress:z,symbol:on(z,f)?.symbol??t.asset.symbol,decimals:on(z,f)?.decimals??t.asset.decimals};if(i){const $=h||m;if(!$)return null;const ue=$,ve=o?r?.amountInMax??0n:N;if(ve===0n)return null;const pe=await F(ve,K=>S({fundingAmountOverride:K}).then(ie=>Rn(Ns(ie),ue)),z,{userOverride:$,useCustomTransfers:!0}),me=Rn(Ns(await S({fundingAmountOverride:pe})),ue),ge=await B(me,z,pe,{userOverride:$,useCustomTransfers:!0,feeExecutionMode:p});return es(ge,O)}if(!y||!x||!C||!b)return null;const J=h||m||x,P=o?r?.amountInMax??0n:N;if(P===0n)return null;const U=await F(P,$=>S({fundingAmountOverride:$}).then(ue=>Rn(Ns(ue),J)),z,{useCustomTransfers:!0});let de=Rn(Ns(await S({fundingAmountOverride:U})),J);const H=await B(de,z,U,{useCustomTransfers:!0,feeExecutionMode:p});return es(H,O)}if(s<=0||!h)return null;const v=h||m;if(!(!n&&!i&&t.asset?._source==="wallet"&&t.asset.chainId!==f)&&!A&&!k&&!w||w)return null;const E=Ye(t.amount,t.asset.decimals),I=await W();if(I.length===0)return null;const D=i&&t.asset?._source==="wallet"&&t.asset.chainId===f,R={chainId:f,tokenAddress:T,symbol:on(T,f)?.symbol??l.symbol,decimals:on(T,f)?.decimals??l.decimals};if(D){const N=await It.estimateBatchGas({user:v,outputToken:T,stepIndex:0,chainBatches:I}),z=to(E,10n),O=z+N.gasFee;return{...R,grossAmount:E+O,netAmount:E,totalFee:O,gasFee:N.gasFee,spicenetFee:z,bridgeFee:0n,gasQuoteSource:N.gasQuoteSource}}const L=I.some(N=>N.tokenTransfers?.length),j=await B(I,T,E,L?{userOverride:v,useCustomTransfers:!0,feeExecutionMode:p}:p?{userOverride:v,feeExecutionMode:p}:{userOverride:v});return es(j,R)}const md=10n;function La(e,t){const n=e.selectedAsset?.asset;if(!n||n?._source!=="wallet")return;const s=zn(n,e.resolvedChainId);if(!s||!Ee(s,e.executionTokenAddress))return;const o=on(e.executionTokenAddress,e.resolvedChainId),r=Dn(t,o?.decimals??e.destinationToken.decimals,n.decimals);if(r<=n.balance)return;const i=pt(r,n.decimals),c=pt(n.balance,n.decimals);throw new Error(`Insufficient ${n.symbol} for amount plus fees. Required ${i} ${n.symbol}; available ${c} ${n.symbol}.`)}function cr(e){const t=on(e.executionTokenAddress,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:t?.symbol??e.destinationToken.symbol,decimals:t?.decimals??e.destinationToken.decimals}}function Ps(e,t,n){const s=es(e,cr(t));if(!s)return;const o=to(n,md),r=s.bridgeFee??0n,i=o+s.gasFee+r;return{grossAmount:n+i,netAmount:n,combinedFeeAmount:i,feeExecutionMode:"user-transfer",feeBreakdown:{spicenetFee:o,gasFee:s.gasFee,bridgeFee:r}}}function ks(e,t,n){if(e===t)return!0;const s=e>t?e:t;return s===0n?!1:(e>t?e-t:t-e)*10000n<=s*n}function Oa(e,t,n){let s=0n,o=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=Es({abi:fn,data:c.data});if(d.functionName!=="transfer")continue;const l=d.args[0].toLowerCase(),p=d.args[1];l===rs.toLowerCase()?s+=p:l===Mn.toLowerCase()&&(o+=p)}catch{continue}}return{spicenetFee:s,gasFee:o}}function dr(e,t,n){const s=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,o=Oa(e,t.resolvedChainId,s);return o.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||o.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:ks(o.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&ks(o.gasFee,n.feeBreakdown.gasFee,100n)}function Ha(e,t){return e?ks(e.grossAmount,t.grossAmount,100n)&&ks(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&ks(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&ks(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}async function ur(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 s=await uo(e);e.ui.setTxHash(s??null)}else{e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.refs.spiceDepositSubmittedRef.current=!1;const s=new AbortController;e.refs.abortControllerRef.current=s,await ja(e,s.signal)}e.ui.setStep("success"),e.ui.setStatusMsg(e.isSourceDestToken?"Transaction confirmed":"Deposit confirmed")}catch(s){const o=s instanceof Error?s:new Error(String(s));if(o.name==="AbortError"||e.refs.abortControllerRef.current?.signal.aborted){e.ui.setStep("idle");return}const r=o.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(r),e.ui.setError(r),e.onError?.(o)}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=Ye(e.selectedAsset.amount,e.selectedAsset.asset.decimals),s=n;let o=await e.gasless.buildSupplyChainBatches();const r=e.selectedAsset.asset?._source==="wallet",i=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!r&&!o.some(m=>Qs(m.chainId)))throw new Error("Spice-funded supplies must include a Spicenet funding batch before the destination chain batch.");const c=o.some(m=>m.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?s:void 0;let u;for(let m=0;m<4;m+=1){const f=await e.gasless.estimateGasless(o,e.executionTokenAddress,d,c),y=es(f,cr(e));u=e.feeExecutionMode==="user-transfer"&&y?Ps(f,e,s):void 0;const x=u?.grossAmount??y?.grossAmount??d;if(x===d){d=x;break}d=x,o=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:d,actionAmountOverride:p,actionContextOverride:u})}e.feeExecutionMode==="user-transfer"&&(La(e,d),o=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:d,actionAmountOverride:p,actionContextOverride:u}));let h=u;await e.gasless.executeGasless(o,e.executionTokenAddress,d,e.gasless.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...c,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:m,chainBatches:f})=>{const y=Ps(m,e,s);if(!y)return null;const x=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&e.resolvedTokenIn?e.resolvedTokenIn:e.executionTokenAddress;Oa(f,e.resolvedChainId,x);const C=Ha(h,y),b=dr(f,e,y);return C||b?null:(h=y,e.gasless.buildSupplyChainBatches({fundingAmountOverride:y.grossAmount,actionAmountOverride:p,actionContextOverride:y}))}}:c),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){const s=n instanceof Error?n:new Error(String(n));if(s.name==="AbortError"||t.signal.aborted){e.ui.setStep("idle");return}const o=s.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(o),e.ui.setError(o),e.onError?.(s)}finally{e.ui.setIsExecuting(!1)}}async function ja(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 s=e.selectedAsset.asset,o=Ye(e.selectedAsset.amount,s.decimals),r=o,i=s?._source==="wallet"&&s.chainId===e.resolvedChainId;let c=await e.gasless.buildSupplyChainBatches();const d={userOverride:n,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,signAuthorizationsForEstimate:!0};let l=o;const p=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,u=e.feeExecutionMode==="user-transfer"&&!p?r:void 0;let h;if(i){const v=await It.estimateBatchGas({user:n,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:c}),E=to(o,10n),I=E+v.gasFee;l=o+I,e.feeExecutionMode==="user-transfer"&&(h={grossAmount:l,netAmount:r,combinedFeeAmount:I,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:E,gasFee:v.gasFee,bridgeFee:0n}})}else for(let v=0;v<4;v+=1){const E=await e.gasless.estimateGasless(c,e.executionTokenAddress,0n,d),I=e.feeExecutionMode==="user-transfer"?Ps(E,e,r):void 0,D=es(E,cr(e)),R=I?.grossAmount??(D?D.grossAmount>o?D.grossAmount:o:l);if(h=I,R===l){l=R;break}l=R;const L=on(e.executionTokenAddress,e.resolvedChainId),j=Dn(l,L?.decimals??e.destinationToken.decimals,s.decimals);c=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:l,sourceFundingAmountOverride:j,withdrawalAmountOverride:l,actionAmountOverride:u,actionContextOverride:I})}const m=on(e.executionTokenAddress,e.resolvedChainId);let f=i?l:Dn(l,m?.decimals??e.destinationToken.decimals,s.decimals);La(e,l),c=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:l,sourceFundingAmountOverride:f,withdrawalAmountOverride:l,actionAmountOverride:u,actionContextOverride:h});const y=s.chainId,x=n,C=await e.externalWallet.getEthereumProvider();let b=null;try{const v=await C.request({method:"eth_chainId"});b=parseInt(v,16)}catch{b=null}b!==y&&(e.ui.setStatusMsg("Switching source network..."),await os(C,y));const A=De(y),k=Xn({account:e.externalWalletAddress,chain:A?.viemChain,transport:Jn(C)}),w=Lt(s.address),T=s.isNative||Ve(w),S=Tt(y),W=async v=>{if(v<=0n)return;const E=T?await k.sendTransaction({to:x,value:v,chain:A?.viemChain}):await k.sendTransaction({to:w,data:At({abi:fn,functionName:"transfer",args:[x,v]}),chain:A?.viemChain});if((await S.waitForTransactionReceipt({hash:E,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Embedded wallet funding failed")};e.ui.setStatusMsg("Funding embedded wallet..."),await W(f);let B=f;if(e.feeExecutionMode==="user-transfer")for(let v=0;v<4;v+=1){const E=await e.gasless.estimateGasless(c,e.executionTokenAddress,0n,d),I=Ps(E,e,r);if(!I)break;const D=i?I.grossAmount:Dn(I.grossAmount,m?.decimals??e.destinationToken.decimals,s.decimals);if(D>B&&(e.ui.setStatusMsg("Topping up embedded wallet..."),await W(D-B),B=D),h=I,l=I.grossAmount,f=D,c=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:l,sourceFundingAmountOverride:f,withdrawalAmountOverride:l,actionAmountOverride:u,actionContextOverride:I}),dr(c,e,I))break}e.ui.setStatusMsg("Signing supply intent...");let F=h;await e.gasless.executeGasless(c,e.executionTokenAddress,0n,e.gasless.onProgress,t,e.feeExecutionMode==="user-transfer"?{...d,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:v,chainBatches:E})=>{const I=Ps(v,e,r);if(!I)return null;const D=Ha(F,I),R=dr(E,e,I);if(D||R)return null;if(I.grossAmount>l)throw new Error("Fee estimate increased after wallet funding. Please retry so the signed fee can match the latest relayer estimate.");F=I;const L=i?I.grossAmount:Dn(I.grossAmount,m?.decimals??e.destinationToken.decimals,s.decimals);return e.gasless.buildSupplyChainBatches({fundingAmountOverride:I.grossAmount,sourceFundingAmountOverride:L,withdrawalAmountOverride:I.grossAmount,actionAmountOverride:u,actionContextOverride:I})}}:d)}async function uo(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,s=e.activeSignerAddress??e.externalWalletAddress;if(!s||!n)throw new Error("Please connect your wallet to continue");const o=Ye(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),r={userAddress:s,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},i=e.buildActionCalls(o,r);if(i.length===0)throw new Error("No action calls configured");const c=await n.getEthereumProvider();let d=null;try{const m=await c.request({method:"eth_chainId"});d=parseInt(m,16)}catch{d=null}d!==e.resolvedChainId&&await os(c,e.resolvedChainId);const l=De(e.resolvedChainId),p=Xn({account:s,chain:l?.viemChain,transport:Jn(c)}),u=Tt(e.resolvedChainId);let h;for(const m of i){const f=await p.sendTransaction({to:m.to,data:m.data,value:m.value,chain:l?.viemChain});if((await u.waitForTransactionReceipt({hash:f,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transaction failed");h=f}return h}async function Qa(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,s=n.chainId,o=Ye(e.currentPaymentAmount,e.destinationToken.decimals),r=e.selectedIsEquivalent?o: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,b=>e.gasless.buildPayChainBatches({fundingAmountOverride:b}),i,c),l=An(s),p=await e.externalWallet.getEthereumProvider();let u=null;try{const b=await p.request({method:"eth_chainId"});u=parseInt(b,16)}catch{u=null}u!==s&&await os(p,s);const h=De(s),m=Xn({account:e.externalWalletAddress,chain:h?.viemChain,transport:Jn(p)}),f=Lt(n.address),y=n.isNative||Ve(f)?await m.sendTransaction({to:l,value:d,chain:h?.viemChain}):await m.sendTransaction({to:f,data:At({abi:fn,functionName:"transfer",args:[l,d]}),chain:h?.viemChain});if((await Tt(s).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}),C=x.some(b=>b.tokenTransfers?.length);return await e.gasless.executeGasless(x,i,d,b=>{b.txHash&&(e.ui.setPaymentResult(A=>({...A??{status:"processing"},txHash:b.txHash})),e.ui.setTxHash(b.txHash))},void 0,C?c:{userOverride:t})}async function pr(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 s;if(e.isSourceDestToken||e.parsedAmount===0)s=await uo(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const o=e.selectedAsset.asset,r=Ye(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||o.address,l=await e.gasless.estimateRequiredGrossFunding(i,h=>e.gasless.buildPayChainBatches({fundingAmountOverride:h}),d,{userOverride:c,useCustomTransfers:!0}),p=await e.gasless.buildPayChainBatches({fundingAmountOverride:l}),u=await e.onPayExecute({asset:o,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(h=>({...h??{status:"processing"},txHash:u}))),s=u||void 0}else s=await Qa(e);e.ui.setPaymentResult(o=>({status:"success",txHash:o?.txHash||s||""}))}catch(s){const o=Cn(s,"Payment failed. Please try again.");e.ui.setError(o),e.ui.setPaymentResult({status:"failed",error:o}),e.onError?.(s instanceof Error?s:new Error(o))}finally{e.ui.setIsExecuting(!1)}return}if(e.isSourceDestToken){if(!(e.activeSignerAddress??e.externalWalletAddress??e.address)){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{const n=await uo(e);e.ui.setPaymentResult(s=>({status:"success",txHash:s?.txHash||n||""}))}catch(n){const s=Cn(n,"Payment failed. Please try again.");e.ui.setError(s),e.ui.setPaymentResult({status:"failed",error:s}),e.onError?.(n instanceof Error?n: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=Ye(e.currentPaymentAmount,e.destinationToken.decimals),s={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode};if(t){const x=await e.gasless.buildPayChainBatches({actionAmountOverride:0n,fundingAmountOverride:0n}),C=await e.gasless.executeGasless(x,e.destinationToken.address,0n,b=>{b.txHash&&(e.ui.setPaymentResult(A=>({...A,txHash:b.txHash})),e.ui.setTxHash(b.txHash))},void 0,s);e.ui.setPaymentResult(b=>({status:"success",txHash:b?.txHash||C}));return}const o=e.selectedAsset?.asset;if(!o)throw new Error("Select a payment source");const r=e.resolvedTokenIn||o.address||e.destinationToken.address,i=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:n,c=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,d=(x,C,b)=>{const A=Ns(x),k=S=>(S.tokenTransfers??[]).some(W=>W.from==="escrow"),w=A.filter(S=>!k(S)),T=A.filter(k);return[...w,...Rn(T,c,C,b)]},l=await e.gasless.estimateRequiredGrossFunding(i,x=>e.gasless.buildPayChainBatches({fundingAmountOverride:x}).then(C=>d(C)),r,s);let p=l,u=d(await e.gasless.buildPayChainBatches({fundingAmountOverride:l}));const h=await e.gasless.estimateGasless(u,r,l,s),m=es(h,{chainId:e.resolvedChainId,tokenAddress:r,symbol:on(r,e.resolvedChainId)?.symbol??o.symbol,decimals:on(r,e.resolvedChainId)?.decimals??o.decimals})?.grossAmount??l;m!==l&&(p=m),u=d(await e.gasless.buildPayChainBatches({fundingAmountOverride:p}),h,{payoutAlreadyGross:!0});const f=u.some(x=>x.tokenTransfers?.length),y=await e.gasless.executeGasless(u,r,f?p:0n,x=>{x.txHash&&(e.ui.setPaymentResult(C=>({...C,txHash:x.txHash})),e.ui.setTxHash(x.txHash))},void 0,s);e.ui.setPaymentResult(x=>({status:"success",txHash:x?.txHash||y}))}catch(n){const s=Cn(n,"Payment failed. Please try again.");e.ui.setError(s),e.ui.setPaymentResult({status:"failed",error:s}),e.onError?.(n instanceof Error?n:new Error(s))}finally{e.ui.setIsExecuting(!1)}}const gd=({variant:e,destinationSymbol:t,destinationLogoURI:n,destinationDecimals:s,primaryColor:o,fontFamily:r,textPrimary:i,textSecondary:c,cardBg:d,cardBorder:l,dk:p,dark:u,isQuoting:h,quoteError:m,estimatedOutput:f,paymentAmount:y,needsSwap:x,exactOutputSwap:C,adjustable:b=!1,maxAmount:A,onAmountChange:k})=>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(qa,{symbol:t,logoURI:n,primaryColor:o,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:h?a("span",{style:{fontSize:"18px",color:c,fontFamily:r},children:"Quoting..."}):m?a("span",{style:{fontSize:"13px",color:u?"#f87171":"#dc2626",fontFamily:r},children:"Quote failed"}):f?a(as,{value:f,title:f,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(yd,{destinationSymbol:t,destinationLogoURI:n,destinationDecimals:s,primaryColor:o,fontFamily:r,textPrimary:i,textSecondary:c,cardBg:d,cardBorder:l,dk:p,dark:u,paymentAmount:y||"0",needsSwap:x,exactOutputSwap:C,isQuoting:h,adjustable:b,maxAmount:A,onAmountChange:k}),Va=wn(gd),qa=({symbol:e,logoURI:t,primaryColor:n,size:s})=>t?a("img",{src:t,alt:e,style:{width:s,height:s,borderRadius:"50%",objectFit:"cover"}}):a("div",{style:{width:s,height:s,borderRadius:"50%",backgroundColor:`${n}22`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:s<30?"11px":"12px",fontWeight:700,color:n},children:e.slice(0,2)}),yd=({destinationSymbol:e,destinationLogoURI:t,destinationDecimals:n,primaryColor:s,fontFamily:o,textPrimary:r,textSecondary:i,cardBg:c,cardBorder:d,dk:l,dark:p,paymentAmount:u,needsSwap:h,exactOutputSwap:m,isQuoting:f,adjustable:y,maxAmount:x,onAmountChange:C})=>{const b='"IBM Plex Mono", monospace',A=parseFloat(u||"0"),k=x?parseFloat(x):0,[w,T]=M(u||""),S=ne(null),[W,B]=M(null),[F,v]=M(null);G(()=>{y||T(u||"")},[u,y]);const E=R=>{let L=R;L.startsWith(".")&&(L="0"+L);const j=gs(L);let N=j;x&&parseFloat(j)>parseFloat(x)&&(N=x),T(N),S.current&&clearTimeout(S.current),S.current=setTimeout(()=>C?.(N),300)},I=R=>{if(!k)return;if(R===100){T(x||k.toString()),S.current&&clearTimeout(S.current),C?.(x||k.toString());return}const L=10**n,j=Math.floor(k*R/100*L)/L,N=ys(j,n);T(N),S.current&&clearTimeout(S.current),C?.(N)},D=k>0?parseFloat(w||"0")/k*100:0;return G(()=>()=>{S.current&&clearTimeout(S.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(qa,{symbol:e,logoURI:t,primaryColor:s,size:32}),g("div",{children:[a("span",{style:{fontSize:"14px",fontWeight:600,color:r,fontFamily:o},children:"Payment"}),a("div",{style:{fontSize:"12px",color:i,fontFamily:o,marginTop:"2px"},children:e})]})]}),g("div",{style:{textAlign:"right"},children:[y?a(as,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:w,onChange:R=>E(R.target.value),placeholder:"0.0",fontFamily:b,color:r,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):a(as,{element:"div",value:A>0?u:"0.00",title:A>0?u:"0.00",fontFamily:b,color:r,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),a("div",{style:{fontSize:"12px",color:i,fontFamily:b,marginTop:"2px"},children:e}),y&&k>0&&a("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((R,L)=>{const j=Math.abs(D-R)<1,N=L===4,z=R/100,O=W===R,J=F===R;return a("button",{onClick:()=>I(R),onMouseEnter:()=>B(R),onMouseLeave:()=>{B(null),v(null)},onMouseDown:()=>v(R),onMouseUp:()=>v(null),title:`${R}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:j?1:O?.8:.5,transform:J?"scale(0.85)":O?"scale(1.15)":"scale(1)",transition:Sn.interactive},children:g("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[a("circle",{cx:"7",cy:"7",r:"6.84375",fill:N?s:"none",stroke:N?s:p?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!N&&z>0&&a("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${z>.5?1:0} 1 ${7+6.84375*Math.sin(z*2*Math.PI)} ${7-6.84375*Math.cos(z*2*Math.PI)} Z`,fill:p?l?.textSecondary||"#9ca3af":"#3C3E42"})]})},R)})})]})]}),h&&m&&!f&&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:o,opacity:.7},children:["via ",m.venue]})})]})};function Ka(e,t,n){const s=Ee(e.address,t),o=e.chainId===n,r=e._source==="wallet";return r&&s&&o?0:r&&o?1:!r&&s?2:!r&&o?3:4}function Ya(e,t){return!t||t.length===0||t.some(n=>Ee(n,e.address))?!0:Object.keys(e.chainTokens??{}).some(n=>{const s=ws(n);return s?t.some(o=>Ee(o,s.address)):!1})}function fr(e){const{destinationToken:t,supportedSourceAssets:n,sourceChains:s,enabled:o}=e,r=(un(en)?.mode||"7702")!=="7702",i=Tn(),{externalAddress:c,embeddedAddress:d,activeAddress:l}=On(),p=i||d,{assets:u,refetch:h}=Ds({address:p,supportedChains:s,enabled:o&&!r&&!!p,refetchInterval:3e4}),m=te(()=>r?[]:u.filter(W=>Ya(W,n)),[u,n,r]),f=r?l??c:i,y=te(()=>{const W=new Set,B=[],F=v=>{if(!v)return;const E=v.toLowerCase();W.has(E)||(W.add(E),B.push(Ne(v)))};if(F(t.address),n)for(const v of n)F(v);return B},[r,t.address,n]),x=te(()=>y.map(W=>W.toLowerCase()).sort().join(","),[y]),C=te(()=>JSON.stringify([...s||[]].sort()),[s]),[b,A]=M([]),k=ne(0),w=ne(async()=>{}),T=oe(async()=>{if(!o||!f||y.length===0){k.current++,A([]);return}const W=++k.current,B=Ne(f),F=r?s&&s.length>0?s:[t.chainId]:[t.chainId],v=[];for(const R of y){const L=R.toLowerCase();if(L===pn)continue;if(L===t.address.toLowerCase()){const N=De(t.chainId)?.supportedTokens?.find(z=>Ee(z.address,L));v.push({address:R,chainId:t.chainId,configToken:N?{decimals:N.decimals,symbol:N.symbol,name:N.name,logo:N.logo}:void 0});continue}let j=!1;for(const N of F){const z=De(N)?.supportedTokens?.find(O=>Ee(O.address,L));if(z){v.push({address:R,chainId:N,configToken:{decimals:z.decimals,symbol:z.symbol,name:z.name,logo:z.logo}}),j=!0;break}}j||v.push({address:R,chainId:t.chainId})}const E=new Map;for(const R of v){const L=E.get(R.chainId)||[];L.push(R),E.set(R.chainId,L)}const I=async(R,L)=>{try{const j=await Un(R,{address:L.address,abi:fn,functionName:"balanceOf",args:[B]});let N,z,O,J;if(L.configToken)N=L.configToken.decimals,z=L.configToken.symbol,O=L.configToken.name,J=L.configToken.logo;else{const[de,H,$]=await Promise.all([Un(R,{address:L.address,abi:fn,functionName:"decimals"}).catch(()=>18),Un(R,{address:L.address,abi:fn,functionName:"symbol"}).catch(()=>"TOKEN"),Un(R,{address:L.address,abi:fn,functionName:"name"}).catch(()=>"TOKEN")]);N=Number(de),z=H,O=$}const P=Ee(L.address,t.address)&&L.chainId===t.chainId;P&&t.logoURI&&(J=t.logoURI),P&&!L.configToken&&z==="TOKEN"&&(z=t.symbol,O=t.symbol);const U=parseFloat((Number(j)/Math.pow(10,N)).toFixed(6));return{address:L.address,name:O,symbol:z,decimals:N,balance:j,balanceFormatted:U,balanceUsd:0,logoURI:J,isNative:!1,chainId:L.chainId}}catch{return null}},D=await Promise.all(Array.from(E.entries()).map(async([R,L])=>{let j;try{j=Tt(R)}catch{return[]}const N=[],z=[];for(const J of L){const P=N.length;N.push({address:J.address,abi:fn,functionName:"balanceOf",args:[B]}),J.configToken||N.push({address:J.address,abi:fn,functionName:"decimals"},{address:J.address,abi:fn,functionName:"symbol"},{address:J.address,abi:fn,functionName:"name"}),z.push({start:P,item:J})}let O=null;try{O=await j.multicall({contracts:N})}catch{O=null}return O?z.map(({start:J,item:P})=>{const U=O[J],de=U?.status==="success"?U.result:0n;let H,$,ue,ve;if(P.configToken)H=P.configToken.decimals,$=P.configToken.symbol,ue=P.configToken.name,ve=P.configToken.logo;else{const ge=O[J+1],K=O[J+2],ie=O[J+3];H=ge?.status==="success"?Number(ge.result):18,$=K?.status==="success"?K.result:"TOKEN",ue=ie?.status==="success"?ie.result:$}const pe=Ee(P.address,t.address)&&P.chainId===t.chainId;pe&&t.logoURI&&(ve=t.logoURI),pe&&!P.configToken&&$==="TOKEN"&&($=t.symbol,ue=t.symbol);const me=parseFloat((Number(de)/Math.pow(10,H)).toFixed(6));return{address:P.address,name:ue,symbol:$,decimals:H,balance:de,balanceFormatted:me,balanceUsd:0,logoURI:ve,isNative:!1,chainId:P.chainId}}):(await Promise.all(L.map(J=>I(j,J)))).filter(J=>J!==null)}));W===k.current&&A(D.flat())},[o,r,f,x,C,t.address,t.chainId,t.symbol,t.logoURI]);G(()=>{w.current=T},[T]),G(()=>{if(!o){A([]);return}w.current();const W=setInterval(()=>{w.current()},15e3);return()=>clearInterval(W)},[o,r,f,x,C,t.address,t.chainId]);const S=oe(()=>{T()},[T]);return{displayAssets:te(()=>{const W=[],B=b.filter(v=>v.balance>0n);for(const v of B)W.push({...v,_source:"wallet"});for(const v of m)W.push({...v,_source:"spice"});const F=t.address.toLowerCase();return W.sort((v,E)=>Ka(v,F,t.chainId)-Ka(E,F,t.chainId)),W},[b,m,t.address,t.chainId]),filteredSpiceAssets:m,walletAssets:b,embeddedWalletAddress:p,externalAddress:c,isNon7702:r,refreshSpiceAssets:h,refreshWalletAssets:S}}async function Ga(e){const{tokenIn:t,tokenOut:n,amountIn:s,fee:o,chainId:r,config:i}=e;if(s<=0n)throw new Error("amountIn must be greater than 0");const c=(await Tt(r).simulateContract({address:i.quoterV2,abi:Ui,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:s,fee:o,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 Za(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(o=>Ga({...e,fee:o})));let s=null;for(let o=0;o<n.length;o++){const r=n[o];r.status==="fulfilled"&&(!s||r.value.amountOut>s.amountOut)&&(s={...r.value,fee:t[o]})}if(!s)throw new Error("No liquidity found for this pair on any fee tier.");return s}const xd=[{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 bd(e){const{tokenIn:t,tokenOut:n,amountOut:s,fee:o,chainId:r,config:i}=e;if(s<=0n)throw new Error("amountOut must be greater than 0");const c=(await Tt(r).simulateContract({address:i.quoterV2,abi:xd,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:s,fee:o,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 wd(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(o=>bd({...e,fee:o})));let s=null;for(let o=0;o<n.length;o++){const r=n[o];r.status==="fulfilled"&&(!s||r.value.amountIn<s.amountIn)&&(s={...r.value,fee:t[o]})}if(!s)throw new Error("No liquidity found for this pair on any fee tier.");return s}function Xa(e){return e.type==="swap"}const hr=.02,Cd=[1,8453,42161,10,137,43114,56],kd="https://api.1inch.dev/swap/v6.0";function Ja(e,t){return Li(e,t)}function $a(e){const t=e?.baseUrl??kd;return{name:"1inch",chainIds:e?.chainIds??Cd,resolve:async(n,s,o)=>{const r=n.maxSlippage??hr,i=r*100,c=Ve(n.tokenIn)?Br:n.tokenIn,d=Ve(n.tokenOut)?Br:n.tokenOut,l=Ve(n.tokenIn);try{const p=new URL(`${t}/${s}/swap`);p.searchParams.set("src",c),p.searchParams.set("dst",d),p.searchParams.set("amount",n.amountIn.toString()),p.searchParams.set("from",o),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 h=await fetch(p.toString(),{headers:u});if(!h.ok)throw new Re("VENUE_API_ERROR",`[1inchVenue] API returned ${h.status} for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:`HTTP ${h.status}`});const m=await h.json();if(!m.dstAmount||!m.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const f=BigInt(m.dstAmount);if(f<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const y=Ja(f,r),x=[];return m.tx.to&&!l&&x.push({to:n.tokenIn,value:0n,data:At({abi:fn,functionName:"approve",args:[m.tx.to,n.amountIn]})}),x.push({to:m.tx.to,value:BigInt(m.tx.value||"0"),data:m.tx.data}),{venue:"1inch",amountOut:f,amountOutMinimum:y,calls:x}}catch(p){if(p instanceof Re)throw p;const u=p instanceof Error?p.message:String(p);throw new Re("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}: ${u}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:u})}}}}const _a=[4114,5115],mr={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},ei={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[3e3]};function ti(e){return{name:"satsuma",chainIds:e.chainIds??_a,resolve:async(t,n,s)=>{const o=t.maxSlippage??hr,r=Ve(t.tokenIn);let i;try{i=await Za({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=Ja(i.amountOut,o),d=[];return r||d.push({to:t.tokenIn,value:0n,data:At({abi:fn,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),d.push({to:e.swapRouter,value:r?t.amountIn:0n,data:At({abi:zi,functionName:"exactInputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:i.fee,recipient:s,amountIn:t.amountIn,amountOutMinimum:c,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:i.amountOut,amountOutMinimum:c,calls:d}}}}function ni(e){return{name:"satsuma",chainIds:e.chainIds??_a,resolve:async(t,n,s)=>{const o=t.maxSlippage??hr,r=Ve(t.tokenIn);let i;try{i=await wd({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(o*1e4)),d=i.amountIn+i.amountIn*c/10000n,l=[];return l.push({to:e.swapRouter,value:r?d:0n,data:At({abi:vd,functionName:"exactOutputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:i.fee,recipient:s,amountOut:t.amountOut,amountInMaximum:d,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:i.amountIn,amountInMax:d,amountOut:t.amountOut,calls:l}}}}const vd=[{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 si(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(ti(e.satsuma)),t.push($a(e?.oneInch));function n(o){return t.find(r=>r.chainIds.includes(o))}async function s(o,r,i){const c=[],d=[];for(const l of o){if(!Xa(l)){c.push(l);continue}const p=n(r);if(!p)throw new Re("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 Re("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:s,getVenueForChain:n,venues:t}}function oi(e){const t=e?.customVenues??[];async function n(s,o,r){const i=t.filter(d=>d.chainIds.includes(o));if(i.length===0)throw new Re("NO_SWAP_ROUTE",`No exact-output venue supports chain ${o}`,{chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut});const c=(await Promise.allSettled(i.map(d=>d.resolve(s,o,r)))).filter(d=>d.status==="fulfilled").map(d=>d.value).filter(d=>d!==null);if(c.length===0)throw new Re("NO_SWAP_ROUTE",`All aggregators failed for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}`,{chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountOut:s.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 ri=si({satsuma:mr});async function Id(e){const t=ri.getVenueForChain(e.chainId);if(!t)throw new Error(`No swap venue configured for chain ${e.chainId}.`);const n=await t.resolve({type:"swap",tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:e.amountIn},e.chainId,e.recipient);if(!n)throw new Error("No liquidity for this pair.");return n}function gr(e){const{direction:t,selectedAsset:n,destinationToken:s,chainId:o,recipient:r,paymentAmount:i,resolveExactOutputSwap:c}=e,[d,l]=M(!1),[p,u]=M(null),[h,m]=M(null),[f,y]=M(null),[x,C]=M(null),[b,A]=M(null),[k,w]=M(null),[T,S]=M(null),[W,B]=M(null),F=ne(null),v=ne(null),E=ne(0),I=ne(new Map),D=te(()=>ri,[]),R=te(()=>oi({customVenues:[...c?[{name:"consumer-exact-output",chainIds:[o],resolve:c}]:[],ni(mr),ni(ei)]}),[c,o]),L=te(()=>{if(!n?.asset)return null;const $=zn(n.asset,o);if($)return $;const ue=Kn(n.asset.address,o,n.asset.chainId);return ue?ue.address:null},[n?.asset,o]),j=te(()=>n?.asset?$s(n.asset,o):[],[n?.asset,o]),N=te(()=>j.map($=>$.toLowerCase()).join(","),[j]);G(()=>{let $=!1;if(v.current&&(clearTimeout(v.current),v.current=null),!n?.asset||j.length<=1){B(null);return}return v.current=setTimeout(async()=>{const ue=t==="input"?n.amount:i||"0";let ve=0n;try{ve=t==="input"?Ye(ue,n.asset.decimals):0n}catch{ve=0n}try{const pe=await la(n.asset,o,{requiredAmount:ve});$||B(pe)}catch{$||B(null)}},400),()=>{$=!0,v.current&&(clearTimeout(v.current),v.current=null)}},[n?.asset,n?.amount,o,j.length,N,t,i]);const z=te(()=>W??L,[W,L]),O=te(()=>!n?.asset||!z?[]:[z,...j.filter($=>$.toLowerCase()!==z.toLowerCase())],[n?.asset,z,j]),J=te(()=>!n?.asset||!Rs(n.asset.address,n.asset.chainId,s.address,s.chainId)||!z?!1:Ee(z,s.address),[n,s.address,s.chainId,z]),P=z?Ee(z,s.address):!1,U=t==="output"&&parseFloat(i||"0")===0,de=!!n?.asset&&!J&&!P&&!U,H=de?T??z:z;return G(()=>{F.current&&clearTimeout(F.current);const $=t==="input"?n?.amount:i,ue=parseFloat($||"0");if(!de||!Number.isFinite(ue)||ue<=0||!n?.asset||!r||O.length===0){E.current++,m(null),y(null),C(null),A(null),w(null),S(null),u(null),l(!1);return}const ve=n.asset.decimals;let pe;try{pe=t==="input"?Ye(n.amount,ve):Ye(i||"0",s.decimals)}catch{E.current++,u("Invalid amount"),l(!1);return}const me=++E.current,ge=()=>me!==E.current;l(!0);const K=t==="output"?150:400;return F.current=setTimeout(async()=>{try{if(t==="input"){const ie=D.getVenueForChain(o);if(!ie)throw new Error("No swap venue for this chain");let X=null,ee=null;for(const Ce of O){const be=`${t}:${o}:${Ce.toLowerCase()}:${s.address.toLowerCase()}:${pe.toString()}`,Q=I.current.get(be);if(Q&&Q.expiresAt>Date.now()&&Q.resolvedSwap){X=Q.resolvedSwap,ee=Ce;break}const ae=await ie.resolve({type:"swap",tokenIn:Ce,tokenOut:s.address,amountIn:pe},o,r);if(ge())return;if(ae){I.current.set(be,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:ae}),X=ae,ee=Ce;break}}if(!X||!ee)throw new Error("No liquidity for this pair");S(ee),w(X.amountOut),C(X),A(null);const fe=parseFloat(pt(X.amountOut,s.decimals));m(fe<.01?fe.toPrecision(4):fe.toLocaleString(void 0,{maximumFractionDigits:6})),y(null),u(null)}else{let ie=null,X=null;for(const ee of O){const fe=`${t}:${o}:${ee.toLowerCase()}:${s.address.toLowerCase()}:${pe.toString()}`,Ce=I.current.get(fe);if(Ce&&Ce.expiresAt>Date.now()&&Ce.exactOutputSwap){ie=Ce.exactOutputSwap,X=ee;break}try{const be=await R.getQuote({tokenIn:ee,tokenOut:s.address,amountOut:pe},o,r);if(ge())return;I.current.set(fe,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:be}),ie=be,X=ee;break}catch{if(ge())return}}if(!ie||!X)throw new Error("No liquidity for this pair");S(X),A(ie),C(null),w(null),y(parseFloat(pt(ie.amountIn,ve)).toFixed(6)),m(null),u(null)}}catch(ie){if(ge())return;const X=ie instanceof Error?ie.message:"Failed to get quote";u(X),m(null),y(null),C(null),A(null),w(null),S(null)}finally{ge()||l(!1)}},K),()=>{F.current&&clearTimeout(F.current)}},[t,de,n?.amount,n?.asset?.address,n?.asset?.decimals,i,O,o,s.address,s.decimals,r,D,R]),{isQuoting:d,quoteError:p,estimatedOutput:h,estimatedInput:f,resolvedSwap:x,exactOutputSwap:b,quoteAmountOut:k,resolvedTokenIn:H,isDirect:P,needsSwap:de,selectedIsEquivalent:J}}const ai={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},ii=["signing-delegation","signing-intent","submitting","executing"],Ad=()=>{},li=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,destinationToken:s,sourceChains:o,supportedSourceAssets:r,buildActionCalls:i,feeExecutionMode:c="user-transfer",buildSpicenetBatch:d,onPayExecute:l,resolveExactOutputSwap:p,actionLabel:u,amountDirection:h="input",swapDescription:m,directDescription:f,paymentAmount:y,amountInputMode:x="fixed",minPaymentAmount:C,maxPaymentAmount:b,onAmountChange:A,styles:k,dark:w,title:T,subtitle:S,onAddFunds:W,onSuccess:B,onError:F})=>{const v=h==="output",{theme:E,dark:I,primaryColor:D,dk:R,palette:L,fontFamily:j,monoFont:N,inputDark:z,cardBg:O,cardBorder:J,textPrimary:P,textSecondary:U,subtitleText:de}=wt(k,w),H=te(()=>z?{...E,colors:{...E.colors,secondary:R.cardBg,surfaceHover:R.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:E,[z,E,R.cardBg,R.hoverBg]),$=s.chainId,ue=un(en),ve=ue?.mode||"7702",pe=ve!=="7702",me=!!ue?.isWhitelistGateActive,ge=!!ue?.isWhitelistConfigured&&ue?.isUserWhitelisted!==!0,K=te(()=>o??ue?.supportedChainIds??[],[o,ue?.supportedChainIds]),ie=te(()=>{if(me)return[];if(r)return r;const xe=ue?.allowedTokens;if(!xe||xe.length===0)return;const zt=new Set(xe.map(Gn=>Gn.toLowerCase())),fs=[],Yn=new Set;for(const Gn of K){const go=De(Gn);for(const yo of go?.supportedTokens??[]){if(!zt.has(yo.symbol.toLowerCase()))continue;const wr=yo.address.toLowerCase();Yn.has(wr)||(Yn.add(wr),fs.push(yo.address))}}return fs},[r,ue?.allowedTokens,K,me]),X=Wn(),{address:ee,isConnected:fe,isReady:Ce,isAuthenticated:be,provider:Q}=X,{executeGasless:ae,estimateGasless:_}=Cs(),{externalWallet:Be,externalAddress:Ue,embeddedAddress:it,activeWallet:mt,activeAddress:Vt}=On(),st=Tn()||it,{displayAssets:we,filteredSpiceAssets:We,embeddedWalletAddress:ze,refreshSpiceAssets:$e,refreshWalletAssets:lt}=fr({destinationToken:s,supportedSourceAssets:ie,sourceChains:K,enabled:e&&(pe?!!Ue:!!st)}),ft=me||v||pe?we:We;G(()=>{e&&console.debug("[SpiceSupply] selectable assets",{mode:ve,walletAddressUsed:ze,count:ft.length,assets:ft.map(xe=>({symbol:xe.symbol,address:xe.address,chainId:xe.chainId,balanceFormatted:xe.balanceFormatted,source:xe?._source}))})},[e,ve,ze,ft]);const[q,qe]=M(null),[Se,ot]=M(y||""),[_e,nn]=M(!1),[Ot,gt]=M(null),[Fe,St]=M("idle"),[Ht,Le]=M(""),[sn,Me]=M(null),[Gt,Xt]=M(!1),[Ge,ye]=M(null),[Ze,et]=M(null),[rn,Ie]=M(!1),[Yt,Mt]=M(!1),[Ct,Ke]=M(null),an=ne(q),Pt=ne(!1),ln=ne(null),Jt=ne(null),qt=ne(0),Rt=ne(null),yt=ne(null);G(()=>{an.current=q},[q]);const Qe=x==="adjustable"?Se:y||"0",ct=ze||it||ee,{isQuoting:Dt,quoteError:cn,estimatedOutput:dn,resolvedSwap:Ut,exactOutputSwap:le,quoteAmountOut:ht,resolvedTokenIn:dt,isDirect:Et,needsSwap:rt,selectedIsEquivalent:Pe}=gr({direction:h,selectedAsset:q,destinationToken:s,chainId:$,recipient:ct,paymentAmount:Qe,resolveExactOutputSwap:p}),kt=v?parseFloat(Qe||"0"):parseFloat(q?.amount||"")||0,mn=kt>0&&kt<Vn,se=q?.asset?._source==="wallet",re=!!q?.asset&&se&&q.asset.chainId!==$,Ae=te(()=>q?.asset?We.find(xe=>Ee(xe.address,q.asset.address))?.balanceFormatted??0:0,[q,We]),Xe=se?q?.asset.balanceFormatted??0:Ae,ut=te(()=>{if(!q?.asset)return!1;if(v)return Ze?Dn(Ze.grossAmount,Ze.decimals,q.asset.decimals)>q.asset.balance:Pe||Et?kt>q.asset.balanceFormatted:le?parseFloat(pt(le.amountInMax,q.asset.decimals))>q.asset.balanceFormatted:!1;if(Ze){const xe=Dn(Ze.grossAmount,Ze.decimals,q.asset.decimals);return se?xe>q.asset.balance:parseFloat(pt(xe,q.asset.decimals))>Xe}return kt>Xe},[q,v,Ze,Pe,kt,le,Xe,se,Et]);G(()=>{e||(qe(null),gt(null),nn(!1),St("idle"),Le(""),Me(null),Xt(!1),ye(null),et(null),Ie(!1),Mt(!1),Ke(null),Pt.current=!1,x==="adjustable"&&ot(y||""),ln.current&&(ln.current.abort(),ln.current=null))},[e]);const Ft=oe(xe=>{qe(zt=>({asset:xe,amount:zt?.asset?.address===xe.address&&zt?.asset?.chainId===xe.chainId&&zt.amount||""})),gt(null),Ke(null),Mt(!1)},[]),Wt=oe(xe=>{qe(zt=>zt&&{...zt,amount:xe}),gt(null),Ke(null),Mt(!1)},[]),Bt=oe(xe=>{let zt=xe;b&&parseFloat(zt)>parseFloat(b)&&(zt=b),ot(zt),A?.(zt),gt(null),Ke(null),Mt(!1)},[b,A]);oe(xe=>{if(Pt.current||!ee)return;const zt=an.current;!zt?.asset||!zt.amount||zt.asset?._source==="wallet"||Ye(v?Qe:zt.amount,zt.asset.decimals)===0n||(Pt.current=!0,$e())},[ee,$,$e,v,Qe]);const He=oe(xe=>{St({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[xe.step]||"executing"),Le(xe.message),xe.txHash&&Me(xe.txHash)},[]),Kt=te(()=>({currentPaymentAmount:Qe,destinationToken:s,embeddedWalletAddress:ze,providerEmbeddedAddress:it,externalWalletAddress:Ue,address:ee,isNon7702:pe,isPayMode:v,resolvedChainId:$,buildActionCalls:i,feeExecutionMode:c,buildSpicenetBatch:d,selectedAsset:q,needsSwap:rt,resolvedSwap:Ut,exactOutputSwap:le,quoteAmountOut:ht,resolvedTokenIn:dt}),[Qe,s,ze,it,Ue,ee,pe,v,$,i,c,d,q,rt,Ut,le,ht,dt]),Je=oe(xe=>rr({...Kt,requestTimestampMs:Jt.current??Date.now()},xe),[Kt]),Z=oe(xe=>ar({...Kt,requestTimestampMs:Jt.current??Date.now()},xe),[Kt]),ke=oe((xe,zt,fs,Yn)=>ir(xe,zt,fs,_,Yn),[_]),vt=te(()=>q?.asset?rt&&dt?dt:q.asset.chainId===$?q.asset.address:dt??zn(q.asset,$)??s.address:s.address,[q,s.address,rt,$,dt]),Nt=oe(()=>(Jt.current=Date.now(),ur(yt.current)),[]),tt=te(()=>q?.asset?Ee(q.asset.address,s.address)&&q.asset.chainId===s.chainId:!1,[q,s.address,s.chainId]),Zt=tt&&(pe||v),xt=Zt&&kt>0&&!!q?.asset,kn=ge&&!Zt,V=te(()=>{if(!xt)return null;let xe;try{xe=Ye(Qe||"0",s.decimals)}catch{return null}return{symbol:s.symbol,decimals:s.decimals,grossAmount:xe,netAmount:xe,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}},[xt,Qe,s.symbol,s.decimals]),Y=Ot,he=te(()=>!(!q?.asset||kt<=0),[q,kt,xt]),ce=te(()=>!e||_e||Fe!=="idle"||!he||xt||!q?.asset?null:[v?"pay":"supply",h,q.asset.address.toLowerCase(),q.asset.chainId,q.amount,Qe,s.address.toLowerCase(),s.chainId,$,dt?.toLowerCase()??"",rt?"swap":"direct",Et?"direct-token":"routed-token",pe?"non7702":"7702",tt?"source-dest":"cross-chain",Dt?"quoting":"quoted",le?.amountIn?.toString()??"",le?.amountInMax?.toString()??"",le?.venue??"",Ut?.amountOut?.toString()??"",ht?.toString()??"",ze??"",it??"",ee??""].join("|"),[e,_e,Fe,he,xt,q,v,h,Qe,s,$,dt,rt,Et,pe,tt,Dt,le,Ut,ht,ze,it,ee]),je=oe(()=>lr({selectedAsset:q,isPayMode:v,parsedAmount:kt,needsSwap:rt,exactOutputSwap:le,isNon7702:pe,isSourceDestToken:tt,currentPaymentAmount:Qe,destinationToken:s,feeExecutionMode:c,resolvedTokenIn:dt,embeddedWalletAddress:ze,providerEmbeddedAddress:it,resolvedChainId:$,isConnected:fe,address:ee,ready:Ce,authenticated:be,isDirect:Et,resolvedSwap:Ut,isQuoting:Dt,executionTokenAddress:vt,buildPayChainBatches:Je,buildSupplyChainBatches:Z,estimateGasless:_,estimateRequiredGrossFunding:ke}),[q,v,kt,rt,le,pe,tt,Qe,s,c,dt,ze,it,ke,Je,_,$,fe,ee,Ce,be,Et,Ut,Dt,Z,vt]);G(()=>{Rt.current=je},[je]);const Oe=oe(xe=>za({asset:xe,isPayMode:v,isNon7702:pe,needsSwap:rt,isQuoting:Dt,embeddedWalletAddress:ze,buildSupplyChainBatches:Z,estimateGasless:_,executionTokenAddress:vt,feeExecutionMode:c}),[v,pe,rt,Dt,ze,Z,_,vt,c]);G(()=>{if(!e){Ie(!1),Mt(!1),Ke(null),et(null);return}if(_e||Fe!=="idle"){qt.current+=1,Ie(!1);return}if(!he){et(null),Ie(!1),Mt(!1),Ke(null);return}if(xt){et(V),Ie(!1),Mt(!0),Ke(null);return}if(Dt){qt.current+=1,Ie(!1),Mt(!1);return}if(!ce)return;let xe=!1;const zt=async()=>{const Yn=++qt.current;Ke(null),Ie(!0);try{const Gn=await Rt.current?.();if(xe||qt.current!==Yn)return;Gn?(et(Gn),Mt(!0)):(et(null),Mt(!1)),Ke(null)}catch(Gn){if(xe||qt.current!==Yn)return;const go=Cn(Gn,"Unable to calculate fees for this action.");et(null),Mt(!1),Ke(go)}finally{!xe&&qt.current===Yn&&Ie(!1)}},fs=window.setTimeout(()=>{zt()},250);return()=>{xe=!0,clearTimeout(fs),Ie(!1)}},[e,_e,Fe,he,xt,V,Dt,ce]);const at=oe(()=>(Jt.current=Date.now(),pr(yt.current)),[]);G(()=>{!v&&Fe==="success"&&sn&&($e(),B?.(sn))},[v,Fe,sn,$e,B]),G(()=>{if(!v||Ge?.status!=="success"||Pt.current||!ee)return;Pt.current=!0;const xe=an.current;!xe?.asset||xe.asset?._source==="wallet"||$e()},[v,Ge?.status,ee,$e]);const bt=ne(B),$t=ne(F);G(()=>{bt.current=B},[B]),G(()=>{$t.current=F},[F]),G(()=>{e&&($e(),lt())},[e,$e,lt]),G(()=>{v&&(Ge?.status==="success"&&bt.current?.(Ge.txHash||""),Ge?.status==="failed"&&$t.current?.(new Error("Payment execution failed")))},[v,Ge?.status]);const gn=oe(()=>{Xt(!1),ye(null),qe(null),Pt.current=!1,$e(),lt()},[$e,lt]);yt.current={selectedAsset:q,parsedAmount:kt,currentPaymentAmount:Qe,isInsufficientBalance:ut,isPayMode:v,isNon7702:pe,isSourceDestToken:tt,needsSwap:rt,exactOutputSwap:le,selectedIsEquivalent:Pe,resolvedTokenIn:dt,embeddedWalletAddress:ze,providerEmbeddedAddress:it,externalWallet:Be,externalWalletAddress:Ue,activeSignerWallet:mt,activeSignerAddress:Vt,address:ee,isConnected:fe,ready:Ce,authenticated:be,provider:Q,resolvedChainId:$,executionTokenAddress:vt,destinationToken:s,buildActionCalls:i,feeExecutionMode:c,buildSpicenetBatch:d,onPayExecute:l,onSuccess:B,onError:F,gasless:{estimateGasless:_,executeGasless:ae,buildPayChainBatches:Je,buildSupplyChainBatches:Z,estimateRequiredGrossFunding:ke,onProgress:He},ui:{setError:gt,setStep:St,setStatusMsg:Le,setTxHash:Me,setIsExecuting:nn,setShowStatusPanel:Xt,setPaymentResult:ye},refs:{spiceDepositSubmittedRef:Pt,abortControllerRef:ln}};const yn=y?.trim(),_t=v&&x==="fixed"&&yn!==void 0&&yn!==""&&kt===0,Fn=v?(_t||!!q?.asset)&&kt>=0&&!mn&&!ut&&!_e&&(_t||xt||Yt)&&!Ct&&(_t||!rt||!!le)&&!kn:!!q?.asset&&kt>0&&!mn&&!ut&&!_e&&(Zt||Yt)&&!Ct&&(re||Et||!!Ut&&!Dt)&&!kn;G(()=>{e&&console.debug("[SpiceSupply] canExecute gates",{canExecute:Fn,isPayMode:v,hasSelectedAsset:!!q?.asset,selectedAsset:q?.asset?{symbol:q.asset.symbol,address:q.asset.address,chainId:q.asset.chainId,balanceFormatted:q.asset.balanceFormatted,source:q.asset?._source}:null,parsedAmount:kt,isZeroAmountPay:_t,isBelowMinimum:mn,isInsufficientBalance:ut,isExecuting:_e,directExternalAction:Zt,directExecutionFeeNote:xt,feeEstimateReady:Yt,feeEstimateError:Ct,needsSwap:rt,isDirect:Et,isSourceDestToken:tt,hasExactOutputSwap:!!le,isQuoting:Dt,whitelistHoldPending:ge,supplyHeldForWhitelist:kn,isWhitelistGateActive:me,destinationToken:{symbol:s.symbol,address:s.address,chainId:s.chainId}})},[e,Fn,v,q,kt,_t,mn,ut,_e,Zt,xt,Yt,Ct,rt,Et,tt,le,Dt,ge,kn,me,s]);const ns=Et?f||`Your ${s.symbol} will be used directly.`:m||"Your assets will be swapped and used in a single atomic transaction.",Te=($?De($):void 0)?.viemChain?.blockExplorers?.default?.url??"",jt=ii.indexOf(Fe),xn=_e?(ai[Fe]||"EXECUTING...").toUpperCase():Fe==="success"?"DONE":mn?`MINIMUM ${Vn}`:ut?"INSUFFICIENT BALANCE":u.toUpperCase(),Bn=te(()=>{if(_e)return"PAYING...";if(mn)return`MINIMUM ${Vn}`;if(ut&&q?.asset)return`INSUFFICIENT ${q.asset.symbol}`;if(u)return u.toUpperCase();const xe=kt>0?` ${Qe} ${s.symbol}`:"";return rt?`SWAP & PAY${xe}`:`PAY${xe}`},[_e,mn,ut,q,u,kt,Qe,s.symbol,rt]),us=Fe==="success"?()=>{St("idle"),qe(null),Me(null),$e()}:Nt,zs=Fe==="success"?!1:!Fn;if(!e)return null;const Ls=v?T||`Pay ${s.symbol}`:u,ps=v?S:g("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[a("span",{style:{marginTop:"3px",flexShrink:0},children:a(Oo,{color:de})}),a("p",{style:{fontSize:"12px",color:de,margin:0,lineHeight:"1.4",fontFamily:j},children:ns})]});if(v){const xe=Ge&&(Ge.status==="success"||Ge.status==="failed")?[{asset:{symbol:q?.asset?.symbol||s.symbol,address:q?.asset?.address||""},amount:Qe,txHash:Ge.txHash||"",success:Ge.status==="success",error:Ge.status==="failed"?Ge.error:void 0}]:void 0;return a(jn,{isOpen:e,onClose:t,title:Ls,subtitle:ps,styles:k,dark:I,footerLinkText:"Spicenet accounts \u2192",closeOnBackdropClick:n,children:g("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[W&&a("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:a(Ho,{onClick:W,color:D,fontFamily:j})}),!_t&&a("div",{style:{marginBottom:"12px"},children:a(Ms,{assets:ft,selectedAsset:q??void 0,onAssetSelect:Ft,onAmountChange:Ad,label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:q?.asset?rt?Dt?"...":le?`~${parseFloat(pt(le.amountIn,q.asset.decimals)).toFixed(6)}`:void 0:Qe??void 0:void 0,dark:I,theme:H,styles:k})}),a(Va,{variant:"pay",destinationSymbol:s.symbol,destinationLogoURI:s.logoURI,destinationDecimals:s.decimals,primaryColor:D,fontFamily:j,textPrimary:P,textSecondary:U,cardBg:O,cardBorder:J,dk:R,dark:I,isQuoting:Dt,quoteError:cn,estimatedOutput:dn,paymentAmount:Qe,needsSwap:rt,exactOutputSwap:le,adjustable:x==="adjustable",maxAmount:b,onAmountChange:Bt}),he&&a(Gs,{fontFamily:j,textPrimary:P,textSecondary:U,cardBg:O,cardBorder:J,resolvedDark:I,darkCardBorder:R.cardBorder,primaryColor:D,feePreview:Ze,isLoading:rn,errorText:Ct,directExecutionFeeNote:xt}),Y&&a(xs,{variant:"error",palette:L,fontFamily:j,style:{marginBottom:"12px"},children:Y}),a(Qt,{variant:"outline",fullWidth:!0,onClick:at,disabled:!Fn,loading:_e,dark:I,styles:{...k,button:{...k?.button,backgroundColor:D}},children:Bn}),Ge&&Gt&&a("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:I?R.shell:"white",borderRadius:I?"12px":"6px",padding:"16px 0"},children:a(Ko,{type:"payment",isOpen:Ge.status!=="processing",isProcessing:_e||Ge.status==="processing",closeOnComplete:!1,chainName:In($),explorerUrl:hs($,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{Xt(!1),ye(null),at()},onNewTx:gn,onClose:()=>{Xt(!1),ye(null)},onComplete:gn,results:xe,styles:k,dark:I})})]})})}return a(jn,{isOpen:e,onClose:t,title:Ls,subtitle:ps,dark:I,styles:k,theme:E,closeOnBackdropClick:n,children:g("div",{style:{padding:"24px 24px 5px 24px",position:"relative"},children:[a("div",{style:{marginBottom:"16px"},children:a(Ms,{assets:ft,selectedAsset:q||void 0,onAssetSelect:Ft,onAmountChange:Wt,disabled:_e||Fe==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:H,styles:k,dark:z,resolveMaxAmount:Oe,maxAmount:Xe>0?ys(Xe,q?.asset.decimals??s.decimals):void 0})}),q?.asset&&!Et&&a(Va,{variant:"supply",destinationSymbol:s.symbol,destinationLogoURI:s.logoURI,destinationDecimals:s.decimals,primaryColor:D,fontFamily:j,textPrimary:P,textSecondary:U,cardBg:O,cardBorder:J,dark:I,isQuoting:Dt,quoteError:cn,estimatedOutput:dn}),he&&a(Gs,{fontFamily:j,textPrimary:P,textSecondary:U,cardBg:O,cardBorder:J,resolvedDark:I,darkCardBorder:R.cardBorder,primaryColor:D,feePreview:Ze,isLoading:rn,errorText:Ct,directExecutionFeeNote:xt}),Fe!=="idle"&&g("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:Fe==="success"?O:Fe==="error"?L.errorBg:O,border:`1px solid ${Fe==="success"?J:Fe==="error"?L.errorBorder:J}`},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[Fe==="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:L.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):Fe==="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:L.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):a(Zn,{size:14,color:D}),a("span",{style:{fontSize:"13px",fontWeight:500,color:Fe==="success"?P:Fe==="error"?L.errorText:P,fontFamily:j,flex:1},children:Fe==="success"?"Deposit confirmed":Fe==="error"?Ht||"Transaction failed":ai[Fe]||Ht}),Fe==="success"&&sn&&a("a",{href:`${Te}/tx/${sn}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:D,fontFamily:j,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),Fe==="error"&&a("button",{onClick:()=>{St("idle"),gt(null),setTimeout(Nt,50)},style:{background:"none",border:"none",fontSize:"12px",color:D,fontFamily:j,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),jt>=0&&Fe!=="success"&&Fe!=="error"&&a("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${U}22`,overflow:"hidden"},children:a("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:D,transformOrigin:"left center",transform:`scaleX(${(jt+1)/ii.length})`,transition:"transform 400ms ease"}})})]}),Ot&&Fe==="idle"&&a(xs,{variant:"error",palette:L,fontFamily:j,style:{marginBottom:"16px"},children:Ot}),a(Qt,{variant:"outline",fullWidth:!0,disabled:zs,onClick:us,theme:E,dark:I,styles:{...k,button:{...k?.button,backgroundColor:D}},style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:N},children:xn})]})})},Sd=e=>a(li,{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}),Ed=({label:e="Export Wallet",style:t,className:n,onExport:s,onError:o})=>{const[r,i]=M(!1),[c,d]=M(!1),{primaryColor:l}=wt(),p=un(en),{isAuthenticated:u}=Wn();let h=null;try{h=ji()}catch{}let m=null,f=null;try{m=Vi(),f=qi()}catch{m=null,f=null}const y=Ai(f),x=oe(async()=>{if(!u){o?.("User is not authenticated. Please log in first.");return}try{if(p?.provider==="dynamic"){if(!m||!y){o?.("Dynamic is not available. Ensure the app is wrapped in a DynamicContextProvider.");return}await m.initExportProcess(!1),s?.();return}if(!h){o?.("Privy is not available. Ensure the app is wrapped in a PrivyProvider.");return}await h.exportWallet(),s?.()}catch(A){const k=A instanceof Error?A.message:"Failed to export wallet";console.error("Export wallet error:",A),o?.(k)}},[y,m,u,o,s,h,p?.provider]),C=!u,b={padding:"10px 20px",borderRadius:"8px",fontFamily:'"IBM Plex Mono", monospace',fontSize:"14px",fontWeight:500,letterSpacing:"0.4px",textTransform:"uppercase",cursor:C?"not-allowed":"pointer",opacity:C?.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:C,className:n,style:b,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 ci(e){const t=un(en),n=Tn(),s=e?.enabled===!1?void 0:n,o=t?.network?{network:t.network,pollIntervalMs:e?.pollIntervalMs,chainIds:e?.chainIds??t.supportedChainIds,discoverWalletBalances:e?.discoverWalletBalances}:void 0;return{...$r(s,o),embeddedWalletAddress:n}}var Fd="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 Bd=({appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,address:r,dk:i,dark:c=!1,showModeToggle:d,isEmbeddedMode:l=!0,onModeToggle:p})=>{const[u,h]=M(!1),m=async()=>{r&&await tl(r)&&(h(!0),setTimeout(()=>h(!1),2e3))},f=t==="active",y=n||(f?"Active":"Inactive"),x=f?"#10b981":"#9ca3af",C=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:Fd,alt:"","aria-hidden":"true",style:{width:"11px",height:"11px",display:"block",...c?{filter:"invert(0.65)"}:{}}})]}),a(Vr,{content:C,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:Vo,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:f?"#ecfdf5":"#f3f4f6",border:c?`1px solid ${i.cardBorder}`:f?"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:f?"#065f46":"#6b7280"},children:y})]})]}),a("div",{style:{fontSize:"28px",fontWeight:700,color:i.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:ms(s)}),o&&a("div",{style:{fontSize:"12px",color:i.textSecondary,marginBottom:"8px"},children:o}),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:Pr(r)}),a("button",{onClick:m,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"})]})]})},Td=wn(Bd),Md=({pendingDeposits:e,onCompleteDeposit:t,dk:n,dark:s=!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((o,r)=>{const i=De(o.chainId)?.displayName||`Chain ${o.chainId}`;return g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:s?n.warningBg:"#fffbeb",border:s?`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:s?n.hoverBg:"#fde68a",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:n.warningText},children:o.tokenSymbol.charAt(0)}),g("div",{children:[g("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:[o.amount," ",o.tokenSymbol]}),g("div",{style:{fontSize:"11px",color:n.warningText},children:["on ",i]})]})]}),a("button",{onClick:()=>t?.(o),style:{padding:"4px 12px",fontSize:"11px",fontWeight:600,backgroundColor:s?n.hoverBg:"#fef3c7",color:s?n.textPrimary:"#92400e",border:s?`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"})]},`${o.tokenAddress}-${o.chainId}-${r}`)})})]}),Rd=wn(Md),Dd=e=>`${e.tokenAddress}-${e.chainId}`,Wd=({spiceAssets:e,loading:t,dk:n,dark:s=!1,canDirectWithdraw:o=!1,onDirectWithdraw:r,directWithdrawState:i})=>{const c={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},d={backgroundColor:n.cardBg,border:s?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return t?g("div",{children:[a("div",{style:c,children:"Idle Balances"}),[1,2].map(l=>a("div",{style:{...d,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},l))]}):e.length===0?g("div",{children:[a("div",{style:c,children:"Idle Balances"}),a("div",{style:{...d,padding:"16px",textAlign:"center",fontSize:"13px",color:s?n.textSecondary:"#9ca3af"},children:"No assets yet. Deposit to get started."})]}):g("div",{children:[a("div",{style:c,children:"Idle Balances"}),a("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((l,p)=>{const u=De(l.chainId),h=l.chainDisplayName||u?.displayName||`Chain ${l.chainId}`,m=l.tokenDisplaySymbol||l.tokenDisplayName||l.tokenSymbol,f=Dd(l),y=o&&l.directWithdraw&&!!r,x=i?.key===f?i:null,C=x?.step==="pending";return g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...d},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[l.logoURI?a("img",{src:l.logoURI,alt:l.tokenSymbol,style:{width:"24px",height:"24px",borderRadius:"50%"}}):a("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:s?n.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:n.textSecondary},children:m.charAt(0)}),g("div",{children:[a("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:m}),a("div",{style:{fontSize:"11px",color:s?n.textSecondary:"#9ca3af"},children:h})]})]}),g("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[g("div",{style:{textAlign:"right"},children:[a("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:_n(l.balanceFormatted)}),a("div",{style:{fontSize:"11px",color:x?.step==="error"?n.errorText:s?n.textSecondary:"#9ca3af"},children:x?.step==="error"?x.message||"Withdraw failed":ms(l.usdValue)})]}),y&&a("button",{onClick:()=>!C&&r(l),disabled:C,title:"Withdraw to external wallet",style:{padding:"6px 10px",borderRadius:"6px",border:s?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",backgroundColor:s?n.hoverBg:"#ffffff",color:n.textPrimary,fontSize:"11px",fontWeight:600,cursor:C?"default":"pointer",opacity:C?.6:1,whiteSpace:"nowrap"},children:C?"Withdrawing\u2026":"Withdraw"})]})]},`${l.tokenAddress}-${l.chainId}-${p}`)})})]})},Nd=wn(Wd),Pd=({section:e,dk:t,dark:n=!1})=>{const s=o=>{switch(o){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((o,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:[o.tokenLogoURI?a("img",{src:o.tokenLogoURI,alt:o.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:o.tokenSymbol.charAt(0)}),g("div",{children:[a("div",{style:{fontSize:"13px",fontWeight:500,color:t.textPrimary},children:o.tokenSymbol}),a("div",{style:{fontSize:"11px",color:t.textSecondary},children:o.label})]})]}),a("div",{style:{fontSize:"13px",fontWeight:600,color:s(o.valueColor)},children:o.displayValue})]},r))})]})},Ud=wn(Pd),zd=({onDepositClick:e,onWithdrawClick:t,depositDisabled:n=!1,withdrawDisabled:s=!1,primaryColor:o="#EA4B4B",dark:r=!1})=>!e&&!t?null:g("div",{style:{display:"flex",gap:"8px"},children:[e&&a(Qt,{variant:"outline",onClick:e,disabled:n,dark:r,styles:{button:{backgroundColor:o}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&a(Qt,{variant:"outline",onClick:t,disabled:s,dark:r,styles:{button:{backgroundColor:o}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),Ld=wn(zd),Od=({appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,address:r,spiceAssets:i,spiceAssetsLoading:c,pendingDeposits:d,customSections:l,notice:p,onDepositClick:u,onWithdrawClick:h,depositDisabled:m,onCompleteDeposit:f,primaryColor:y,dk:x,dark:C=!1,showModeToggle:b,isEmbeddedMode:A,onModeToggle:k,showConnectExternalCta:w,onConnectExternalWallet:T,connectExternalError:S,showHowItWorks:W=!0,canDirectWithdraw:B,onDirectWithdraw:F,directWithdrawState:v})=>{const[E,I]=M(!1);return g("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[a(Td,{appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,address:r,dk:x,dark:C,showModeToggle:b,isEmbeddedMode:A,onModeToggle:k}),p&&a("div",{style:{padding:"10px 12px",borderRadius:"8px",backgroundColor:p.tone==="warning"?C?"rgba(245, 158, 11, 0.12)":"#fffbeb":p.tone==="success"?C?"rgba(16, 185, 129, 0.12)":"#ecfdf5":x.cardBg,border:p.tone==="warning"?C?"1px solid rgba(245, 158, 11, 0.35)":"1px solid #fde68a":p.tone==="success"?C?"1px solid rgba(16, 185, 129, 0.35)":"1px solid #a7f3d0":C?`1px solid ${x.cardBorder}`:"1px solid #e5e7eb",color:p.tone==="warning"?C?"#fbbf24":"#92400e":p.tone==="success"?C?"#34d399":"#047857":x.textSecondary,fontSize:"12px",lineHeight:1.45,fontWeight:500},children:p.message}),w&&g("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[a("button",{onClick:T,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:y||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:'"Helvetica Neue", sans-serif',transition:"opacity 150ms ease"},children:"Connect External Wallet"}),S&&a("span",{style:{fontSize:"11px",color:C?x.errorText:"#b91c1c",lineHeight:1.4},children:S})]}),a("div",{style:{height:"1px",backgroundColor:C?"#2d2d2d":"#e5e7eb"}}),a(Ld,{onDepositClick:u,onWithdrawClick:h,depositDisabled:m,primaryColor:y,dark:C}),W&&g("div",{children:[g("button",{onClick:()=>I(!E),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:x.cardBg,border:C?`1px solid ${x.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:x.textSecondary,fontSize:"12px",fontWeight:500},children:[a("span",{children:"How It Works"}),a("span",{style:{transform:E?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),E&&g("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:C?x.cardBg:"#f0fdf4",border:C?`1px solid ${x.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:C?x.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),a(Rd,{pendingDeposits:d,onCompleteDeposit:f,dk:x,dark:C}),a(Nd,{spiceAssets:i,loading:c,dk:x,dark:C,canDirectWithdraw:B,onDirectWithdraw:F,directWithdrawState:v}),l.map((D,R)=>a(Ud,{section:D,dk:x,dark:C},R))]})},Hd=wn(Od);function jd(e,t,n){const s=t-n.gasBridge-n.spicenetFee;if(s<=0n)throw new Error("Balance is too small to cover the network fee.");const o=[{recipient:e,amount:s}];return n.gasBridge>0n&&o.push({recipient:Mn,amount:n.gasBridge}),n.spicenetFee>0n&&o.push({recipient:rs,amount:n.spicenetFee}),o}function Qd(e,t,n){if(e===t)return!0;const s=e>t?e:t;return s===0n?!1:(e>t?e-t:t-e)*10000n<=s*n}const Vd=new Set([Mn,rs].map(e=>e.toLowerCase()));function qd(e,t){return!e||e.length!==t.length?!1:e.every((n,s)=>{const o=t[s];return n.recipient.toLowerCase()!==o.recipient.toLowerCase()?!1:Vd.has(n.recipient.toLowerCase())?Qd(n.amount,o.amount,100n):!0})}function di(e,t,n){return{chainId:e,domain:"evm",tokenTransfers:[],calls:n.filter(s=>s.amount>0n).map(s=>({to:t,value:0n,data:At({abi:nt,functionName:"transfer",args:[s.recipient,s.amount]})}))}}function Kd(e,t){const n=e.intents.flatMap(o=>o.batches).filter(o=>En(o).totalFee>0n),s=n.filter(o=>o.chainId===t);return(s.length>0?s:n)[0]??null}function Yd(e,t,n,s){const o=Kd(s,e),{gasFee:r,bridgeFee:i,spicenetFee:c}=o?En(o):{gasFee:0n,bridgeFee:0n,spicenetFee:0n};return jd(t,n,{gasBridge:r+i,spicenetFee:c})}function Gd(){const{executeGasless:e}=Cs(),t=Tn(),{embeddedAddress:n}=On(),s=t||n;return{withdraw:oe(async({tokenAddress:o,chainId:r,balance:i,recipient:c,onProgress:d})=>{const l=o,p=c;if(i<=0n)throw new Error("Nothing to withdraw.");const u=[di(r,l,[{recipient:p,amount:i}])];let h=null;return e(u,l,0n,d,void 0,{useCustomTransfers:!0,userOverride:s,adjustBatchesForEstimate:({feeEstimate:m})=>{const f=Yd(r,p,i,m);return qd(h,f)?null:(h=f,[di(r,l,f)])}})},[e,s])}}function Zd(e){return!!e.embeddedAddress&&!!e.externalAddress}const yr=380,ds=8,Xd=[];function ui(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function Jd(e,t){const n=new Map;Object.entries(t).forEach(([o,r])=>{if(!Number.isFinite(r)||r<=0)return;n.set(o,r),n.set(o.toUpperCase(),r);const i=ui(o);i&&n.set(i,r)});const s=[e.symbol,e.displaySymbol,e.receiptTokenName,e.name,e.displayName];for(const o of s){if(!o)continue;const r=n.get(o)??n.get(o.toUpperCase());if(r!==void 0)return r;const i=ui(o);if(!i)continue;const c=n.get(i);if(c!==void 0)return c}return 0}const $d=({appName:e="Spice",status:t="active",statusLabel:n,customSections:s=Xd,extraAssets:o=[],tokenPrices:r={},breakdownLabels:i=[],notice:c,styles:d,dark:l=!1,onDepositSuccess:p,onDepositClick:u,onWithdrawClick:h,onCompleteDeposit:m,showModeToggle:f=!1,defaultMode:y})=>{const x=un(en),C=x?.mode!=="7702",b=!!x?.isWhitelistGateActive,A=!!x?.isWhitelistConfigured&&x?.isUserWhitelisted!==!0,k=ne(!1);G(()=>{if(!k.current){if(Si()){k.current=!0;return}y&&x?.setMode&&(x.setMode(y==="non7702"?"ondemand":"7702"),k.current=!0)}},[x,y]);const[w,T]=M(!1),[S,W]=M(null),[B,F]=M({top:0,bottom:0,left:0,placement:"below"}),v=ne(null),E=ne(null),{address:I,isConnected:D}=Wn(),R=Tn(),{externalAddress:L,embeddedAddress:j}=On(),{dark:N,primaryColor:z,dk:O}=wt(d,l),J=C&&!L,P=!C||J,U=P?R||j:I,de=te(()=>x?.supportedChainIds??js("mainnet"),[x?.supportedChainIds]),{assets:H,loading:$}=Ds({address:U,supportedChains:de,enabled:!!U&&P,refetchInterval:3e4}),ue=te(()=>{const q=P?H.map(Se=>{const ot=Se.balanceUsd||0,_e=Number.isFinite(Se.balanceFormatted)?Se.balanceFormatted:0,nn=ot>0?ot:Jd(Se,r)*_e;return{tokenAddress:Se.address,tokenSymbol:Se.symbol,tokenDisplaySymbol:Po(Se),tokenDisplayName:il(Se),tokenDecimals:Se.decimals,chainId:Se.chainId,chainDisplayName:Uo(Se),balance:Se.balance.toString(),balanceFormatted:Se.balanceFormatted,usdValue:nn,logoURI:Se.logoURI}}):[],qe=J?[]:o;return[...q,...qe].filter(Se=>Se.balanceFormatted>0)},[P,J,H,r,o]),ve=te(()=>ue.reduce((q,qe)=>q+qe.usdValue,0),[ue]),{pendingDeposits:pe}=ci({chainIds:de,enabled:!!I,discoverWalletBalances:!0}),me=te(()=>s.reduce((q,qe)=>q+qe.totalValue,0),[s]),ge=ve+me,K=te(()=>{const q=[];ve>0&&q.push(`${ms(ve)} idle`);for(const qe of s){const Se=i.find(ot=>ot.sectionTitle===qe.title)?.label||qe.title.toLowerCase();q.push(`${ms(qe.totalValue)} ${Se}`)}return q.join(" \xB7 ")},[ve,s,i]),ie=oe(q=>{m?m(q):W(q)},[m]),X=oe(()=>{W(null)},[]),ee=oe(()=>{W(null),p?.()},[p]),fe=oe(()=>{if(!v.current)return;const q=v.current.getBoundingClientRect(),qe=window.innerHeight-q.bottom-ds,Se=q.top-ds,ot=qe>=400||qe>=Se?"below":"above",_e=Math.max(ds,Math.min(q.right-yr,window.innerWidth-yr-ds)),nn=ot==="below"?q.bottom+ds:q.top-ds,Ot=ot==="above"?window.innerHeight-nn:0;F({top:nn,bottom:Ot,left:_e,placement:ot})},[]);Cr(()=>{w&&fe()},[w,fe]),G(()=>{if(!w)return;const q=ot=>{v.current&&!v.current.contains(ot.target)&&E.current&&!E.current.contains(ot.target)&&T(!1)},qe=ot=>{ot.key==="Escape"&&T(!1)},Se=()=>fe();return document.addEventListener("mousedown",q),document.addEventListener("keydown",qe),window.addEventListener("scroll",Se,{passive:!0}),window.addEventListener("resize",fe),()=>{document.removeEventListener("mousedown",q),document.removeEventListener("keydown",qe),window.removeEventListener("scroll",Se),window.removeEventListener("resize",fe)}},[w,fe]);const Ce=P?R||j||I:L||I,be=oe(()=>{x?.setMode&&x.setMode(P?"ondemand":"7702")},[x,P]),[Q,ae]=M(null);let _=null;try{_=Tr({onSuccess:()=>ae(null),onError:q=>ae(Cn(q,"Failed to connect wallet."))}).connectWallet}catch{_=null}const Be=oe(()=>{_&&(T(!1),ae(null),_({walletChainType:"ethereum-only"}))},[_]),Ue=!L&&!!_,it=oe(()=>{T(!1),u?.()},[u]),mt=oe(()=>{T(!1),h?.()},[h]),Vt=oe(q=>{T(!1),ie(q)},[ie]),{withdraw:st}=Gd(),[we,We]=M(null),ze=Zd({embeddedAddress:R||j,externalAddress:L}),$e=oe(async q=>{if(!L)return;const qe=`${q.tokenAddress}-${q.chainId}`;We({key:qe,step:"pending"});try{await st({tokenAddress:q.tokenAddress,chainId:q.chainId,balance:BigInt(q.balance),recipient:L}),We(null)}catch(Se){We({key:qe,step:"error",message:Cn(Se,"Withdraw failed")})}},[st,L]);if(typeof window>"u")return null;const lt=g("button",{ref:v,onClick:()=>T(!w),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:N?O.hoverBg:"#ffffff",border:N?`1px solid ${O.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:'"Helvetica Neue", sans-serif',color:N?O.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:N?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[g("span",{children:[e," Account"]}),D&&g("span",{style:{color:N?O.textSecondary:"#6b7280"},children:["\xB7 ",ms(ge)]}),a("span",{style:{fontSize:"10px",color:N?O.textSecondary:"#9ca3af",transform:w?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),ft=w?Mr.createPortal(g(bn,{children:[a("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:$n.popover},onClick:()=>T(!1)}),a("div",{ref:E,style:{position:"fixed",top:B.placement==="below"?`${B.top}px`:"auto",bottom:B.placement==="above"?`${B.bottom}px`:"auto",left:`${B.left}px`,width:`${yr}px`,maxWidth:`calc(100vw - ${ds*2}px)`,maxHeight:"80vh",backgroundColor:N?O.shell:"#ffffff",border:N?`1px solid ${O.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:N?"0 10px 40px rgba(0, 0, 0, 0.5)":"0 10px 40px rgba(0, 0, 0, 0.12)",zIndex:$n.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${tn.out}`},children:a(Hd,{appName:e,status:t,statusLabel:n,totalUsdValue:ge,breakdownSubtitle:K,address:P?Ce:I,spiceAssets:ue,spiceAssetsLoading:$,pendingDeposits:pe,customSections:s,notice:c,onDepositClick:u?it:void 0,onWithdrawClick:h?mt:void 0,depositDisabled:A,onCompleteDeposit:Vt,primaryColor:z,dk:O,dark:N,showModeToggle:f,isEmbeddedMode:P,onModeToggle:be,showConnectExternalCta:Ue,onConnectExternalWallet:Be,connectExternalError:Q,showHowItWorks:!b,canDirectWithdraw:ze,onDirectWithdraw:$e,directWithdrawState:we})}),a("style",{children:`
|
|
103
|
+
`})]})},td="0xa9059cbb";function nd(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const s=Ne(n.token),o=Ne(n.to),r=`${s.toLowerCase()}:${o.toLowerCase()}`,i=t.get(r);i?i.amount+=n.amount:t.set(r,{token:s,to:o,amount:n.amount})}return[...t.values()]}function sd(e,t){return`0x${t}${e.slice(4)}`}function nr(e,t){return Ta(e,t)}function Ta(e,t,n){const s=od(t,e),o=Math.floor(Date.now()/1e3)+60*10,r=Nn(s);return{user:e,...n?{chainAuthorizations:n}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:"0x00",nbf:0,exp:o,chainBatches:r.map((i,c)=>({hash:i.hash,chainId:i.chainId,tokenTransfers:s[c].domain==="spicenet"?[]:s[c].tokenTransfers??[],calls:i.calls}))}]}}function od(e,t){return e.map(n=>{if(n.domain==="spicenet"||n.calls.length===0)return n;const s=new Set((n.tokenTransfers??[]).filter(r=>(r.from==="escrow"||r.from==="solver")&&Ne(r.to).toLowerCase()===t.toLowerCase()).map(r=>Ne(r.token).toLowerCase()));if(s.size===0)return n;let o=0;for(const r of n.calls){if(!r.data?.startsWith(td))break;try{const i=Es({abi:nt,data:r.data});if(i.functionName!=="transfer")break;const[c]=i.args;if(c.toLowerCase()===t.toLowerCase()||!s.has(Ne(r.to).toLowerCase()))break;o+=1}catch{break}}return o===0?n:{...n,calls:n.calls.slice(o)}})}function Rn(e,t,n,s){if(e.some(p=>p.domain==="spicenet"))return e;const o=n?.intents.flatMap(p=>p.batches),r=p=>p.from==="escrow",i=e.map(p=>{const u=o?.find(k=>k.chainId===p.chainId);if(!u)return p;const h=En(u),m=h.totalFee;if(m<=0n)return p;const f=(p.tokenTransfers??[]).find(k=>r(k)&&Ne(k.to).toLowerCase()===t.toLowerCase()&&!Ve(Ne(k.token)));if(!f)return p;const y=Ne(f.token);let x=!1;const C=(p.tokenTransfers??[]).map(k=>x||!r(k)||Ne(k.to).toLowerCase()!==t.toLowerCase()||Ne(k.token).toLowerCase()!==y.toLowerCase()?k:(x=!0,{...k,amount:s?.payoutAlreadyGross?BigInt(k.amount):BigInt(k.amount)+m}));if(!x)return p;const b=[];h.spicenetFee>0n&&b.push({to:y,value:0n,data:At({abi:nt,functionName:"transfer",args:[rs,h.spicenetFee]})});const A=h.gasFee+h.bridgeFee;return A>0n&&b.push({to:y,value:0n,data:At({abi:nt,functionName:"transfer",args:[Mn,A]})}),{...p,tokenTransfers:C,calls:[...b,...p.calls]}}),c=i.flatMap(p=>(p.tokenTransfers??[]).filter(r).map(u=>{const h=Ne(u.token),m=Ne(u.to),f=[{token:h,to:m,amount:BigInt(u.amount)}];return{chainId:p.chainId,transfers:nd(f)}}));if(c.length===0)return e;const d=s?.requestTimestampMs??Date.now(),l=BigInt(Math.floor(d/1e3))+3600n;return[{chainId:Ni,domain:"spicenet",tokenTransfers:[],calls:c.map((p,u)=>{const h=As(Ss([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,p.transfers[0].token,p.transfers.reduce((f,y)=>f+y.amount,0n),BigInt(p.chainId),BigInt(d+u)])),m=sd(h,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:At({abi:Io,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${p.chainId}`,idempotenceKey:m,nbf:0n,exp:l,metadata:"{}",transfers:p.transfers.map(f=>({token:f.token.toLowerCase(),to:f.to,amount:f.amount}))}]})}})},...i]}function ro(e,t){return t?e.some(n=>(n.tokenTransfers??[]).some(s=>s.from==="escrow"&&BigInt(s.amount)>=t.grossAmount)):!1}function Ma(e){return!e.isSemi7702&&e.isDirectDeposit&&!e.isSourceDestToken}function sr(e){const t=e.selectedAsset?.asset,n=e.selectedAsset?.amount;if(!(!t||!n))return Ye(n,t.decimals)}function Ra(e){return e.map(t=>({r:t.r,s:t.s,yParity:t.yParity,address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce)}))}function rd(e,t){if(e.length!==t.length)return!1;const n=Nn(e),s=Nn(t);return n.every((o,r)=>o.hash===s[r]?.hash)}async function ao({user:e,batches:t,authorizations:n,adjustBatchesForEstimate:s}){let o=t;const r=Ra(n);for(let i=0;i<10;i+=1){const c=await It.estimateActionFees(Ta(e,o,r)),d=await s({feeEstimate:c,batches:o});if(!d||rd(o,d))return o;o=d}throw new Error("Fee estimate did not converge. Please retry.")}function Ln(e,t){const n=e.selectedAsset?.asset;if(!n||!e.selectedAsset?.amount)throw new Error("Select an asset and enter an amount");const s=Ye(e.selectedAsset.amount,n.decimals),o=t?.grossAmount??s;return e.resolveLockBatches({amount:e.selectedAsset.amount,amountWei:s,grossAmount:pt(o,n.decimals),grossAmountWei:o})}async function io(e,t,n){const s=[...new Set(n.filter(r=>r.domain!=="spicenet").map(r=>r.chainId))],o=[];for(const r of s){const i=Tt(r),c=Hs(r),d=await vo(t,i),l=await e.actions.signAuthorization({contractAddress:c,chainId:r,nonce:Number(d)});o.push(l)}return o}async function or(e,t,n){const s=e.isSemi7702&&e.providerEmbeddedAddress||e.address;if(!e.isConnected||!s)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 o=n??await io(e,s,t),r=Nn(t),i=Math.floor(Date.now()/1e3)+60*10,c=r.map(m=>m.hash),d=As(Ss([{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((m,f)=>{const y=t[f],x=y.domain==="spicenet";return{hash:m.hash,chainId:m.chainId,tokenTransfers:x?[]:y.tokenTransfers??[],calls:m.calls}})},h=await It.createAction({user:s,chainAuthorizations:Ra(o),intents:[u]});if(h){const m=bo(t,In),[f,y]=h.intentIds[0].split("/"),x=parseInt(y||"0",10),C=h.intentIds[0];e.startStatusPolling(h.intentIds[0],m),await ua({actionId:f,intentIndex:x,intentId:C,totalSteps:t.length,isSpicenetStep:b=>t[b]?.domain==="spicenet",maxExecuteAttemptsForStep:b=>t[b]?.domain==="spicenet"?6:3,maxPolls:72})}}async function ad(e){let t=Ln(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 s=await io(e,n,t),o=Date.now();let r=Rn([...t],n,void 0,{requestTimestampMs:o}),i;r=await ao({user:n,batches:r,authorizations:s,adjustBatchesForEstimate:({feeEstimate:c})=>{const d=ls(c,{symbol:e.selectedAsset?.asset.symbol??"",decimals:e.selectedAsset?.asset.decimals??18,actionAmount:sr(e)});return d?(i={grossAmount:d.grossAmount,netAmount:d.netAmount,feeAmount:d.totalFee??0n},t=Ln(e,i),Rn([...t],n,c,{payoutAlreadyGross:ro(t,i),requestTimestampMs:o})):null}}),await or(e,r,s)}async function id(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");const n=e.resolveLockBatches();if(n.length===0)throw new Error("No lock batches configured");const s=e.selectedAsset.asset,o=Ye(e.selectedAsset.amount,s.decimals),r=s.chainId,i=e.escrowAddress||An(r),c=Lt(s.address),d=s.isNative||Ve(c),l=Date.now();let p;const u=n.some(C=>C.tokenTransfers?.some(b=>b.from==="escrow")),h=C=>({chainId:r,calls:d?[{to:i,value:C,data:"0x"}]:[{to:c,value:0n,data:At({abi:nt,functionName:"transfer",args:[i,C]})}]}),m=(C,b,A,k)=>{const w=h(C);if(!u)return[w,...b];const T=Rn([...b],t,A,{payoutAlreadyGross:ro(b,k),requestTimestampMs:l});return[w,...T]};let f=Ln(e),y=m(o,f);const x=await io(e,t,y);u&&(y=await ao({user:t,batches:y,authorizations:x,adjustBatchesForEstimate:({feeEstimate:C})=>{const b=ls(C,{symbol:s.symbol,decimals:s.decimals,actionAmount:o});return b?(p={grossAmount:b.grossAmount,netAmount:b.netAmount,feeAmount:b.totalFee??0n},f=Ln(e,p),m(p.grossAmount,f,C,p)):null}})),await or(e,y,x)}async function ld(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 B=e.resolveLockBatches();if(B.length===0)throw new Error("No lock batches configured");const F=e.selectedAsset.asset,v=Ye(e.selectedAsset.amount,F.decimals),E=await e.onLockExecute({asset:F,amount:e.selectedAsset.amount,amountWei:v,lockDurationMonths:e.selectedDuration?.months??0,chainBatches:B});E&&e.onLockSuccess?.(E);return}const n=e.resolveLockBatches();if(n.length===0)throw new Error("No lock batches configured");const s=e.selectedAsset.asset,o=Ye(e.selectedAsset.amount,s.decimals),r=s.chainId,i=e.escrowAddress||An(r),c=Lt(s.address),d=s.isNative||Ve(c),l=n.some(B=>B.tokenTransfers?.some(F=>F.from==="escrow")),p=Date.now();let u;const h=B=>({chainId:r,calls:d?[{to:i,value:B,data:"0x"}]:[{to:c,value:0n,data:At({abi:nt,functionName:"transfer",args:[i,B]})}]}),m=(B,F,v,E)=>{const I=h(B);if(!l)return[I,...F];const D=Rn([...F],t,v,{payoutAlreadyGross:ro(F,E),requestTimestampMs:p});return[I,...D]};let f=Ln(e),y=m(o,f);const x=await io(e,t,y);l&&(y=await ao({user:t,batches:y,authorizations:x,adjustBatchesForEstimate:({feeEstimate:B})=>{const F=ls(B,{symbol:s.symbol,decimals:s.decimals,actionAmount:o});return F?(u={grossAmount:F.grossAmount,netAmount:F.netAmount,feeAmount:F.totalFee??0n},f=Ln(e,u),m(u.grossAmount,f,B,u)):null}}));const C=u?.grossAmount??o,b=await e.externalWallet.getEthereumProvider();let A=null;try{const B=await b.request({method:"eth_chainId"});A=parseInt(B,16)}catch{A=null}A!==r&&await os(b,r);const k=De(r),w=Xn({account:e.externalWalletAddress,chain:k?.viemChain,transport:Jn(b)}),T=Tt(r),S=async B=>{if(B<=0n)return;const F=d?await w.sendTransaction({to:t,value:B,chain:k?.viemChain}):await w.sendTransaction({to:c,data:At({abi:nt,functionName:"transfer",args:[t,B]}),chain:k?.viemChain});if((await T.waitForTransactionReceipt({hash:F,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to embedded wallet failed")};await S(C);let W=C;if(l)for(let B=0;B<4;B+=1){y=await ao({user:t,batches:y,authorizations:x,adjustBatchesForEstimate:({feeEstimate:v})=>{const E=ls(v,{symbol:s.symbol,decimals:s.decimals,actionAmount:o});return E?(u={grossAmount:E.grossAmount,netAmount:E.netAmount,feeAmount:E.totalFee??0n},f=Ln(e,u),m(u.grossAmount,f,v,u)):null}});const F=u?.grossAmount??o;if(F<=W)break;await S(F-W),W=F}await or(e,y,x)}async function cd(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount||!e.requiresRelayerFeeEstimate)return null;if(e.isSemi7702||Ma(e)){const i=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address;if(!i)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");let c=Ln(e);if(c.length===0)throw new Error("No lock batches configured");const d=e.selectedAsset.asset,l=Ye(e.selectedAsset.amount,d.decimals),p=d.chainId,u=e.escrowAddress||An(p),h=Lt(d.address),m=d.isNative||Ve(h),f=c.some(k=>k.tokenTransfers?.some(w=>w.from==="escrow")),y=k=>({chainId:p,calls:m?[{to:u,value:k,data:"0x"}]:[{to:h,value:0n,data:At({abi:nt,functionName:"transfer",args:[u,k]})}]}),x=(k,w,T)=>{const S=y(k);if(!f)return[S,...w];const W=Rn([...w],i,T,{payoutAlreadyGross:w.some(B=>(B.tokenTransfers??[]).some(F=>F.from==="escrow"&&BigInt(F.amount)>=k))});return[S,...W]};let C=x(l,c),b=null,A;for(let k=0;k<4;k+=1){const w=await It.estimateActionFees(nr(i,C)),T=ls(w,{symbol:d.symbol,decimals:d.decimals,actionAmount:l});if(!T)return b;const S={grossAmount:T.grossAmount,netAmount:T.netAmount,feeAmount:T.totalFee??0n},W=A?.grossAmount===S.grossAmount&&A?.netAmount===S.netAmount&&A?.feeAmount===S.feeAmount;if(b=T,A=S,c=Ln(e,S),C=x(S.grossAmount,c,w),W)break}return b}const t=e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");let n=Ln(e);if(n.length===0)throw new Error("No lock batches configured");let s=Rn([...n],t),o=null;for(let i=0;i<4;i+=1){const c=await It.estimateActionFees(nr(t,s)),d=ls(c,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:sr(e)});if(!d)return null;const l={grossAmount:d.grossAmount},p=o?.grossAmount===d.grossAmount&&o?.netAmount===d.netAmount&&o?.totalFee===d.totalFee;if(o=d,n=Ln(e,l),s=Rn([...n],t,c,{payoutAlreadyGross:ro(n,l)}),p)break}if(o)return o;const r=await It.estimateActionFees(nr(t,s));return ls(r,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:sr(e)})}async function dd(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 s=e.resolveLockBatches();if(s.length===0)throw new Error("No lock batches configured");const o=s.find(u=>u.chainId===e.lockChainId)||s[0];if(!o)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 os(r,e.lockChainId);const c=De(e.lockChainId),d=Xn({account:n,chain:c?.viemChain,transport:Jn(r)}),l=Tt(e.lockChainId);let p;for(const u of o.calls){const h=await d.sendTransaction({to:u.to,data:u.data,value:u.value,chain:c?.viemChain});if((await l.waitForTransactionReceipt({hash:h,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Lock transaction failed");p=h}p&&e.onLockSuccess?.(p)}async function ud(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 s=Cn(n,""),o=typeof n?.shortMessage=="string"?n.shortMessage:typeof n?.message=="string"?n.message:"";e.ui.setError(s||o||"Transaction failed. Please try again.")};if(e.isSemi7702){if(e.isSourceDestToken){try{await dd(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{await ld(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{Ma(e)?await id(e):await ad(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}}const Da=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,lockBatches:s,lockTokenSymbol:o,lockTokenLogoURI:r,destinationInputHook:i,sourceAssetInputHook:c,lockDurationHook:d,lockChainId:l,durationOptions:p,votingPowerEstimate:u,escrowAddress:h,includeWalletAssets:m=!1,destinationTokenAddress:f,onLockSuccess:y,onLockExecute:x,sourceToDestinationConversionRate:C,estimatedOutputAmount:b,onAddFunds:A,buildSpicenetBatch:k,styles:w,dark:T=!1})=>{const{theme:S,dark:W,primaryColor:B,dk:F}=wt(w,T),v=S.typography.fontFamily,E=un(en),I=E?.mode||"7702",D=!!E?.isWhitelistGateActive,R=I!=="7702",L=te(()=>E?.supportedChainIds??[],[E?.supportedChainIds]),j=te(()=>{if(D)return[];const Z=E?.allowedTokens;if(!Z||Z.length===0)return[];const ke=new Set(Z.map(tt=>tt.toLowerCase())),vt=[],Nt=new Set;for(const tt of L){const Zt=De(tt);for(const xt of Zt?.supportedTokens??[]){if(!ke.has(xt.symbol.toLowerCase()))continue;const kn=`${tt}:${xt.address.toLowerCase()}`;Nt.has(kn)||(Nt.add(kn),vt.push(Ne(xt.address)))}}return vt},[E?.allowedTokens,L,D]),N=W?F.cardBg:w?.assetSelector?.backgroundColor||w?.secondaryBackground||"#e9e9e9",z=W?`1px solid ${F.cardBorder}`:"0.5px solid #A8A8A7",O=W?"12px":"6px",J=W?F.textPrimary:"#111827",P=W?F.textSecondary:"#6b7280",U=te(()=>({...w,assetSelector:{...w?.assetSelector,backgroundColor:W?F.cardBg:w?.assetSelector?.backgroundColor,borderRadius:W?"12px":w?.assetSelector?.borderRadius},secondaryBackground:W?F.cardBg:w?.secondaryBackground}),[w,W]),de=te(()=>W?{...S,colors:{...S.colors,secondary:F.cardBg,surfaceHover:F.hoverBg,border:F.cardBorder,borderHover:F.inputBorder}}:S,[W,S]),[H,$]=M(null),[ue,ve]=M(0),pe=d?.selectedDurationIdx??ue,me=d?.setSelectedDurationIdx??ve,[ge,K]=M(!1),[ie,X]=M(null),[ee,fe]=M(null),[Ce,be]=M(!1),[Q,ae]=M(!1),[_,Be]=M(null),[Ue,it]=M(!1),mt=ne(0),[Vt,st]=M(!1),[we,We]=M(null);Sr(),wo();const{chain:ze,address:$e}=vs();Ti();const lt=ne(ze);G(()=>{lt.current=ze},[ze]);const ft=Wn(),{isReady:q,isAuthenticated:qe,isConnected:Se,address:ot,provider:_e,actions:nn}=ft,{externalWallet:Ot,embeddedAddress:gt,externalAddress:Fe,activeWallet:St,activeAddress:Ht}=On(),{intentStatus:Le,startStatusPolling:sn,clearStatus:Me}=Qr({checkStepStatus:(Z,ke)=>It.checkStepStatus(Z,ke),retryStep:async(Z,ke)=>{const[vt,Nt]=Z.split("/"),tt=parseInt(Nt||"0",10);await It.executeStep(vt,tt,ke,{action:"execute"})},maxRetries:3}),{assets:Gt,refetch:Xt}=Ds({address:ot,supportedChains:L,enabled:e&&Se&&!R&&!D,refetchInterval:3e4}),Ge=te(()=>{if(D)return[];if(j.length===0)return Gt;const Z=new Set(j.map(ke=>ke.toLowerCase()));return Gt.filter(ke=>Z.has(ke.address.toLowerCase()))},[Gt,j,D]),ye=Tn(),Ze=Fe||$e,et=R?Ht??Ze:ye,rn=te(()=>{if(!m)return[];if(D)return f?[Ne(f)]:[];const Z=new Set,ke=[],vt=Nt=>{if(!Nt)return;const tt=Nt.toLowerCase();Z.has(tt)||(Z.add(tt),ke.push(Ne(Nt)))};f&&vt(f);for(const Nt of j)vt(Nt);return ke},[m,R,f,j,D]),Ie=te(()=>rn.map(Z=>Z.toLowerCase()).sort().join(","),[rn]),Yt=te(()=>JSON.stringify([...L||[]].sort()),[L]),[Mt,Ct]=M([]),Ke=ne(0),an=ne(async()=>{}),Pt=oe(async()=>{if(!m||!et||rn.length===0){Ke.current++,Ct([]);return}const Z=++Ke.current,ke=Ne(et),vt=R?L&&L.length>0?L:[l]:[l],Nt=rn.map(V=>{const Y=V.toLowerCase();if(f&&Ee(V,f)){const he=De(l)?.supportedTokens?.find(ce=>Ee(ce.address,Y));return{address:V,chainId:l,configToken:he?{decimals:he.decimals,symbol:he.symbol,name:he.name,logo:he.logo}:void 0}}for(const he of vt){const ce=De(he)?.supportedTokens?.find(je=>Ee(je.address,Y));if(ce)return{address:V,chainId:he,configToken:{decimals:ce.decimals,symbol:ce.symbol,name:ce.name,logo:ce.logo}}}return{address:V,chainId:l}}),tt=new Map;for(const V of Nt){const Y=tt.get(V.chainId)||[];Y.push(V),tt.set(V.chainId,Y)}const Zt=async(V,Y)=>{try{const he=await Un(V,{address:Y.address,abi:nt,functionName:"balanceOf",args:[ke]});let ce,je,Oe,at;if(Y.configToken)ce=Y.configToken.decimals,je=Y.configToken.symbol,Oe=Y.configToken.name,at=Y.configToken.logo;else{const[gn,yn,_t]=await Promise.all([Un(V,{address:Y.address,abi:nt,functionName:"decimals",args:[]}).catch(()=>18),Un(V,{address:Y.address,abi:nt,functionName:"symbol",args:[]}).catch(()=>"TOKEN"),Un(V,{address:Y.address,abi:nt,functionName:"name",args:[]}).catch(()=>"TOKEN")]);ce=Number(gn),je=yn,Oe=_t}const bt=!!f&&Ee(Y.address,f)&&Y.chainId===l;bt&&r&&(at=r),bt&&o&&!Y.configToken&&(je==="TOKEN"&&(je=o),Oe==="TOKEN"&&(Oe=o));const $t=parseFloat((Number(he)/Math.pow(10,ce)).toFixed(6));return{address:Y.address,name:Oe,symbol:je,decimals:ce,balance:he,balanceFormatted:$t,balanceUsd:0,logoURI:at,isNative:!1,chainId:Y.chainId}}catch{return null}},xt=await Promise.all(Array.from(tt.entries()).map(async([V,Y])=>{let he;try{he=Tt(V)}catch{return[]}const ce=[],je=[];for(const at of Y){const bt=ce.length;ce.push({address:at.address,abi:nt,functionName:"balanceOf",args:[ke]}),at.configToken||ce.push({address:at.address,abi:nt,functionName:"decimals",args:[]},{address:at.address,abi:nt,functionName:"symbol",args:[]},{address:at.address,abi:nt,functionName:"name",args:[]}),je.push({start:bt,item:at})}let Oe=null;try{Oe=await he.multicall({contracts:ce})}catch{Oe=null}return Oe?je.map(({start:at,item:bt})=>{const $t=Oe[at],gn=$t?.status==="success"?$t.result:0n;let yn,_t,Fn,ns;if(bt.configToken)yn=bt.configToken.decimals,_t=bt.configToken.symbol,Fn=bt.configToken.name,ns=bt.configToken.logo;else{const xn=Oe[at+1],Bn=Oe[at+2],us=Oe[at+3];yn=xn?.status==="success"?Number(xn.result):18,_t=Bn?.status==="success"?Bn.result:"TOKEN",Fn=us?.status==="success"?us.result:_t}const Te=!!f&&Ee(bt.address,f)&&bt.chainId===l;Te&&r&&(ns=r),Te&&o&&!bt.configToken&&(_t==="TOKEN"&&(_t=o),Fn==="TOKEN"&&(Fn=o));const jt=parseFloat((Number(gn)/Math.pow(10,yn)).toFixed(6));return{address:bt.address,name:Fn,symbol:_t,decimals:yn,balance:gn,balanceFormatted:jt,balanceUsd:0,logoURI:ns,isNative:!1,chainId:bt.chainId}}):(await Promise.all(Y.map(at=>Zt(he,at)))).filter(at=>at!==null)}));if(Z!==Ke.current)return;const kn=xt.flat();Ct(kn)},[m,R,et,Ie,Yt,l,f,r,o]);G(()=>{an.current=Pt},[Pt]),G(()=>{if(!e||!m){Ct([]);return}an.current();const Z=setInterval(()=>{an.current()},15e3);return()=>clearInterval(Z)},[m,e,et,Ie,Yt,l,f]);const ln=oe(()=>{Pt()},[Pt]),Jt=te(()=>Mt.filter(Z=>Z.balance>0n),[Mt]),qt=te(()=>{if(R)return Jt.map(ke=>({...ke,_source:"wallet"}));if(!m)return Ge;const Z=[];for(const ke of Jt)Z.push({...ke,_source:"wallet"});for(const ke of Ge)Z.push({...ke,_source:"spice"});return Z},[R,m,Jt,Ge]),Rt=te(()=>D?f?qt.filter(Z=>Ee(Z.address,f)&&Z.chainId===l):[]:qt,[qt,D,f,l]),yt=ne(null),Qe=ne(null);G(()=>{Qe.current=H},[H]),G(()=>{!D||!H?.asset||f&&Ee(H.asset.address,f)&&H.asset.chainId===l||$(null)},[D,H?.asset,f,l]),G(()=>{e||($(null),X(null),fe(null),be(!1),ae(!1),Be(null),K(!1),st(!1),We(null),it(!1),Me())},[e,Me]),G(()=>{i&&i.assetAmount!==(H?.amount||"")&&$(Z=>Z&&{...Z,amount:i.assetAmount})},[i?.assetAmount]),G(()=>{c&&c.assetAmount!==(H?.amount||"")&&$(Z=>Z&&{...Z,amount:c.assetAmount})},[c?.assetAmount]),G(()=>{if(!R&&Le?.overallStatus==="success"&&Le.intentId&&yt.current!==Le.intentId&&ot&&Le.steps.find(Z=>Z.transactionHash)?.transactionHash){yt.current=Le.intentId;const Z=Qe.current;if(!Z?.asset||!Z.amount||Z.asset._source==="wallet"||Ye(Z.amount,Z.asset.decimals)===0n)return;Xt()}},[Le,ot,l,Xt,R]);const ct=parseFloat(H?.amount||"")||0,Dt=ct>0&&ct<Vn,cn=te(()=>H?.asset?H.asset._source==="wallet"?H.asset.balanceFormatted??0:Ge.find(Z=>Ee(Z.address,H.asset.address)&&Z.chainId===H.asset.chainId)?.balanceFormatted??0:0,[H?.asset,Ge]),dn=ct>0&&(_?parseFloat(pt(_.grossAmount,_.decimals))>cn:ct>cn),Ut=d?.selectedDuration??p[pe]??p[0],le=te(()=>!H?.asset||!f?!1:Ee(H.asset.address,f)&&H.asset.chainId===l,[H?.asset,f,l]),ht=te(()=>ct<=0?0:le?ct:!C||C<=0?0:ct/C,[ct,C,le]),dt=te(()=>ht<=0?null:ht.toLocaleString(void 0,{maximumFractionDigits:2}),[ht]),Et=u&&ht>0&&Ut?u(ht,Ut.months):void 0,rt=te(()=>ct<=0?"$0.00":le&&C?(ct*C).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!C||C<=0?"$0.00":ct.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[ct,C,le]),Pe=te(()=>{if(!dt)return null;const Z=parseFloat(dt.replace(/,/g,""));return le&&C?(Z*C).toLocaleString(void 0,{maximumFractionDigits:2}):C?(Z*C).toLocaleString(void 0,{maximumFractionDigits:2}):null},[dt,C,le]),kt=oe(Z=>{$(ke=>({asset:Z,amount:ke?.asset?.address===Z.address&&ke?.asset?.chainId===Z.chainId&&ke.amount||""})),X(null),fe(null),ae(!1),Be(null),c?.setSelectedAsset&&c.setSelectedAsset({symbol:Z.symbol,address:Z.address,decimals:Z.decimals,chainId:Z.chainId})},[c?.setSelectedAsset]),mn=oe(Z=>{$(ke=>ke&&{...ke,amount:Z}),X(null),fe(null),ae(!1),Be(null),i&&i.setAssetAmount(Z),c&&c.setAssetAmount(Z)},[i,c]),se=oe(Z=>{if(typeof s=="function"){if(!H?.asset||!H.amount)throw new Error("Select an asset and enter an amount");return s({asset:H.asset,amount:Z?.amount??H.amount,amountWei:Z?.amountWei??Ye(H.amount,H.asset.decimals),grossAmount:Z?.grossAmount,grossAmountWei:Z?.grossAmountWei,feeAdjusted:!!Z})}return s},[s,H]),re=ne(null),Ae=te(()=>!H?.asset||ct<=0?!1:R?!le&&!x:!0,[H,ct,R,le,x]),Xe=oe(()=>cd(re.current),[]),ut=te(()=>!H?.asset||ct<=0?null:`${H.asset.address.toLowerCase()}:${H.asset.chainId}:${H.amount??""}`,[H?.asset?.address,H?.asset?.chainId,H?.amount,ct]);G(()=>{if(!e||ge)return;if(!H?.asset||ct<=0){fe(null),be(!1),ae(!1),Be(null);return}if(!Ae){fe(null),be(!1),ae(!0),Be(null);return}let Z=!1;const ke=async tt=>{const Zt=++mt.current;tt||(fe(null),ae(!1),be(!0));try{const xt=await Xe();if(Z||mt.current!==Zt)return;fe(null),ae(!0),Be(xt)}catch(xt){if(Z||mt.current!==Zt)return;tt||(fe(Cn(xt,"Unable to calculate fees for this lock.")),ae(!1))}finally{!Z&&mt.current===Zt&&!tt&&be(!1)}},vt=window.setTimeout(()=>{ke(!1)},250),Nt=window.setInterval(()=>{ke(!0)},3e4);return()=>{Z=!0,clearTimeout(vt),window.clearInterval(Nt)}},[e,ge,ut,Ae,Xe]),G(()=>{if(Le?.overallStatus==="success"){const Z=Le.steps.find(ke=>ke.transactionHash);y?.(Z?.transactionHash)}},[Le?.overallStatus,y]);const Ft=m&&H?.asset?._source==="wallet"&&H?.asset?.chainId===l,Wt=oe(()=>ud(re.current),[]),Bt=!!H?.asset&&ct>0&&!Dt&&!dn&&!ge&&(!Ae||Q&&!Ce&&!ee),He=ie||ee,Kt=g("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[a(Oo,{color:P}),g("p",{style:{fontSize:"13px",color:P,margin:0,lineHeight:"1.5"},children:["Add ",o," by converting assets from your account"]})]});if(re.current={selectedAsset:H,parsedAmount:ct,selectedDuration:Ut,isInsufficientBalance:dn,isSemi7702:R,isSourceDestToken:le,isDirectDeposit:Ft,requiresRelayerFeeEstimate:Ae,address:ot,embeddedWalletAddress:ye,providerEmbeddedAddress:gt,externalWallet:Ot,externalWalletAddress:Ze,activeSignerWallet:St,activeSignerAddress:Ht,isConnected:Se,ready:q,authenticated:qe,provider:_e,actions:nn,lockChainId:l,escrowAddress:h,onLockExecute:x,onLockSuccess:y,buildSpicenetBatch:k,resolveLockBatches:se,startStatusPolling:sn,refreshSpiceAssets:Xt,refreshWalletAssets:ln,ui:{setError:X,setIsExecuting:K,setShowStatusPanel:it}},!e)return null;const Je={backgroundColor:N,border:z,borderRadius:O,padding:"16px",marginBottom:"16px"};return a(jn,{isOpen:e,onClose:t,title:`Add ${o} to your account`,subtitle:Kt,styles:w,dark:W,footerLinkText:"Spicenet accounts \u2192",overlayContent:Vt?a("div",{}):void 0,closeOnBackdropClick:n,children:g("div",{style:{padding:"0 24px 8px 24px",position:"relative"},children:[g("div",{style:{marginBottom:"12px"},children:[A&&a("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:a(Ho,{onClick:A,color:B,fontFamily:v})}),a("div",{style:{marginTop:"10px",fontSize:"13px",color:P,fontFamily:v},children:a(Ms,{assets:Rt,selectedAsset:H??void 0,onAssetSelect:kt,onAmountChange:mn,label:"Amount",showBalance:!0,showMaxButton:!0,theme:de,styles:U})}),a("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:P,fontFamily:v},children:rt})]}),g("div",{style:Je,children:[g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:W?`1px solid ${F.cardBorder}`:"1px solid #e5e7eb"},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[r?a("img",{src:r,alt:o,style:{width:"32px",height:"32px",borderRadius:"50%",objectFit:"cover"}}):a("div",{style:{width:"32px",height:"32px",borderRadius:"50%",backgroundColor:W?F.inputBg:"#d1d5db",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:700,color:J},children:o.slice(0,2)}),a("span",{style:{fontSize:"16px",fontWeight:600,color:J,fontFamily:v},children:o})]}),g("div",{style:{textAlign:"right"},children:[a("div",{style:{fontSize:"22px",fontWeight:700,color:J,fontFamily:v,lineHeight:1.1},children:dt??"0.00"}),g("div",{style:{fontSize:"12px",color:P,fontFamily:v,marginTop:"2px"},children:["~$",Pe??"0.00"]})]})]}),g("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:W?`1px solid ${F.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:P,fontFamily:v},children:"Lock Duration"}),a(Qn,{color:P})]}),a(Gc,{options:p,selectedIndex:pe,onSelect:me,primaryColor:B,dark:W,textPrimary:J,textSecondary:P})]}),g("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[a(Jc,{durationMonths:Ut?.months,fontFamily:v,dark:W,textPrimary:J,textSecondary:P}),u&&a(_c,{votes:Et,fontFamily:v,dark:W,textPrimary:J,textSecondary:P})]})]}),Ae&&a(Gs,{fontFamily:v,textPrimary:J,textSecondary:P,cardBg:N,cardBorder:z,resolvedDark:W,darkCardBorder:F.cardBorder,primaryColor:B,feePreview:_,isLoading:Ce,errorText:ee}),He&&a(xs,{variant:"error",palette:F,fontFamily:v,style:{marginBottom:"12px"},children:He}),a(Qt,{variant:"outline",fullWidth:!0,onClick:Wt,disabled:!Bt,loading:ge,dark:W,styles:{...w,button:{...w?.button,backgroundColor:B}},children:ge?le?"LOCKING...":"CONVERTING...":Dt?`MINIMUM ${Vn}`:Ce&&Ae?"CALCULATING FEES...":le?`LOCK ${o}`:`CONVERT TO ${o}`}),a(ed,{isOpen:Vt,data:we,isLocking:ge,lockError:He,onContinue:Wt,onClose:()=>st(!1),primaryColor:B,fontFamily:v,dark:W}),Le&&Ue&&a("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:W?"rgba(0, 0, 0, 0.45)":"rgba(255, 255, 255, 0.55)",backdropFilter:"blur(2px)",WebkitBackdropFilter:"blur(2px)",borderRadius:O},children:a(Ko,{type:"lock",showStepBreakdown:!1,isOpen:!!Le&&Le.overallStatus!=="processing",isProcessing:ge||Le?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{Me(),it(!1),Wt()},onNewTx:()=>{Me(),it(!1),$(null),yt.current=null,Xt(),ln()},onClose:()=>{Me(),it(!1)},onComplete:()=>{Me(),it(!1),$(null),yt.current=null,Xt(),ln()},results:Le?.overallStatus==="success"||Le?.overallStatus==="failed"?Le.steps.map(Z=>({asset:{symbol:H?.asset?.symbol||o,address:H?.asset?.address||""},txHash:Z.transactionHash||"",success:Z.status==="success",amount:H?.amount})):void 0,chainName:In(l),explorerUrl:hs(l,"").replace(/\/tx\/.*$/,"")||void 0,theme:S,styles:w,dark:W})})]})})},pd="0xa9059cbb";function Wa(e,t,n){return Ve(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:At({abi:fn,functionName:"transfer",args:[n,t]})}}function Na(e,t,n){return{chainId:n,calls:[Wa(e,t,An(n))]}}function Pa(e,t,n){return!t&&e?.asset?._source==="wallet"&&e?.asset.chainId===n}function Ua(e,t,n,s){return t!=="user-transfer"||!n||e.length===0||e[0]?.to.toLowerCase()!==s.toLowerCase()||!e[0]?.data.startsWith(pd)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function lo(e,t,n,s){if(!t)return[e];const o=await t({...n,requestTimestampMs:s});return o?[o,e]:[e]}function Ns(e){return e.filter(t=>t.domain!=="spicenet")}function co(e){const t=(e.tokenTransfers??[]).filter(n=>n.from==="escrow").map(n=>({token:Lt(n.token),recipient:n.to,amount:BigInt(n.amount)})).filter(n=>n.amount>0n);return t.length>0?t:void 0}function Dn(e,t,n){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const s=10n**BigInt(t-n);return(e+s-1n)/s}async function rr(e,t){const{currentPaymentAmount:n,destinationToken:s,embeddedWalletAddress:o,providerEmbeddedAddress:r,address:i,isNon7702:c,isPayMode:d,resolvedChainId:l,buildActionCalls:p,feeExecutionMode:u,buildSpicenetBatch:h,selectedAsset:m,needsSwap:f,exactOutputSwap:y,resolvedTokenIn:x,requestTimestampMs:C}=e,b=Ye(n,s.decimals),A=t?.actionAmountOverride??b,k=o||r||(c?void 0:i);if(!k)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const w={userAddress:k,chainId:l,destinationToken:s.address,grossAmount:t?.fundingAmountOverride??b,netAmount:A,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:u,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},T=p(A,w),S={chainId:l,calls:T},W=!d&&!c?!0:m?.asset?._source==="spice",B=Pa(m??null,c,l),F=W||c||B,v=(I,D)=>({token:I,from:c?"solver":"escrow",to:k,amount:D}),E=(I,D,R)=>B?[Na(I,D,l),...R]:R;if(b===0n)return[S];if(f&&y){const I=x??zn(m.asset,l)??m.asset.address,D=t?.fundingAmountOverride??y.amountInMax,R=F?[v(I,D)]:[],L={to:I,value:0n,data:At({abi:fn,functionName:"approve",args:[y.calls[0]?.to,y.amountInMax]})},j={chainId:l,calls:[L,...y.calls,...T],tokenTransfers:[...R,...S.tokenTransfers??[]]};if(!F)return[j];const N=await lo(j,h,{userAddress:k,destinationChainId:l,deliveryToken:I,deliveryAmount:D,deliveryRecipient:k,deliveryTransfers:co(j),sourceAsset:m.asset},C);return E(I,D,N)}if(F){const I=x??zn(m.asset,l)??s.address,D=t?.fundingAmountOverride??b,R={...S,tokenTransfers:[v(I,D),...S.tokenTransfers??[]]},L=await lo(R,h,{userAddress:k,destinationChainId:l,deliveryToken:I,deliveryAmount:D,deliveryRecipient:k,deliveryTransfers:co(R),sourceAsset:m.asset},C);return E(I,D,L)}return[S]}async function ar(e,t){const{selectedAsset:n,embeddedWalletAddress:s,externalWalletAddress:o,recipient:r,resolvedChainId:i,destinationToken:c,buildActionCalls:d,feeExecutionMode:l,buildSpicenetBatch:p,isPayMode:u,isNon7702:h,needsSwap:m,resolvedSwap:f,quoteAmountOut:y,resolvedTokenIn:x,requestTimestampMs:C}=e,b=f?.amountOutMinimum??y;if(!n?.asset||!s)return[];const A=r??(h?o:s);if(!A)return[];const k=t?.fundingAmountOverride??t?.actionAmountOverride??Ye(n.amount,n.asset.decimals),w=t?.fundingAmountOverride??k,T=t?.sourceFundingAmountOverride??k,S=t?.deliveryAmountOverride??w,W=t?.withdrawalAmountOverride??S,B=t?.actionAmountOverride??k,F={userAddress:A,chainId:i,destinationToken:c.address,feeToken:l==="user-transfer"&&m&&x?x:c.address,grossAmount:w,netAmount:B,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:l,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},v=d(B,F),E=n.asset?._source==="wallet";if(!u&&h&&E&&n.asset.chainId===i){if(m){if(!x)throw new Error("Swap input token could not be resolved");if(!f||b===null)throw new Error("Swap quote not available yet")}if(m&&f&&b){const P=d(t?.actionAmountOverride??b,{...F,netAmount:t?.actionAmountOverride??b}),{feeCall:U,remainingCalls:de}=Ua(P,l,m,F.feeToken);return[{chainId:i,calls:[...U?[U]:[],...f.calls,...de]}]}return[{chainId:i,calls:v}]}if(!u&&!h&&E&&n.asset.chainId!==i)throw new Error("Cross-chain wallet supplies require external wallet mode");const I=!u&&!h?n.asset?._source!=="wallet":n.asset?._source==="spice",D=h&&E,R=Pa(n,h,i);if(!(I||D||R))return[{chainId:i,calls:v}];const L=R?Na(x??Lt(n.asset.address),T,i):D&&n.asset.chainId!==i?{chainId:n.asset.chainId,calls:[Wa(Lt(n.asset.address),T,An(n.asset.chainId))]}:null,j=(P,U)=>({token:P,from:D?"solver":"escrow",to:s,amount:U}),N=(P,U)=>D?[{token:P,from:"escrow",to:Pi,amount:U}]:[];if(m){if(!x)throw new Error("Swap input token could not be resolved");if(!f||b===null)throw new Error("Swap quote not available yet")}if(m&&f&&b&&x){const P=d(t?.actionAmountOverride??b,{...F,netAmount:t?.actionAmountOverride??b}),{feeCall:U,remainingCalls:de}=Ua(P,l,m,F.feeToken),H={chainId:i,calls:[...U?[U]:[],...f.calls,...de],tokenTransfers:[...N(x,W),j(x,S)]},$=await lo(H,p,{userAddress:s,destinationChainId:i,deliveryToken:x,deliveryAmount:S,withdrawalAmount:W,deliveryRecipient:s,deliveryTransfers:co(H),sourceAsset:n.asset},C);return L?[L,...$]:$}const z=x??zn(n.asset,i)??c.address,O={chainId:i,calls:v,tokenTransfers:[...N(z,W),j(z,S)]},J=await lo(O,p,{userAddress:s,destinationChainId:i,deliveryToken:z,deliveryAmount:S,withdrawalAmount:W,deliveryRecipient:s,deliveryTransfers:co(O),sourceAsset:n.asset},C);return L?[L,...J]:J}async function ir(e,t,n,s,o){let r=e;for(let i=0;i<4;i++){const c=await t(r),d=await s(c,n,r,o),l=wc(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 fd(e,t,n,s){if(e<=0n)return 0n;const o=e-t;if(o<=0n)return 0n;const r=s+n;return r<=0n?o:o*s/r}function hd(e,t){const n=pt(e,t);return n.includes(".")?n.replace(/\.?0+$/,"")||"0":n}async function za(e){const{asset:t,isPayMode:n,isNon7702:s,needsSwap:o,isQuoting:r,embeddedWalletAddress:i,buildSupplyChainBatches:c,estimateGasless:d,executionTokenAddress:l,feeExecutionMode:p}=e;if(n||s||o||r||!i||t.balance<=0n)return null;const u=i,h=await c({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(h.length===0)return null;const m=h.some(A=>A.tokenTransfers?.length),f=await d(h,l,t.balance,m?{userOverride:u,useCustomTransfers:!0,feeExecutionMode:p}:p?{userOverride:u,feeExecutionMode:p}:{userOverride:u}),y=es(f,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),x=y?Dn(y.gasFee,y.decimals,t.decimals):0n,C=y?Dn(y.spicenetFee,y.decimals,t.decimals):0n,b=fd(t.balance,x,C,t.balance);return b>0n?hd(b,t.decimals):null}async function lr(e){const{selectedAsset:t,isPayMode:n,parsedAmount:s,needsSwap:o,exactOutputSwap:r,isNon7702:i,isSourceDestToken:c,currentPaymentAmount:d,destinationToken:l,feeExecutionMode:p,resolvedTokenIn:u,embeddedWalletAddress:h,providerEmbeddedAddress:m,resolvedChainId:f,isConnected:y,address:x,ready:C,authenticated:b,isDirect:A,resolvedSwap:k,isQuoting:w,executionTokenAddress:T,buildPayChainBatches:S,buildSupplyChainBatches:W,estimateGasless:B,estimateRequiredGrossFunding:F}=e;if(!t?.asset)return null;if(n){if(s<=0||o&&!r||c)return null;const N=Ye(d,l.decimals),z=u||zn(t.asset,f)||t.asset.address||l.address,O={chainId:f,tokenAddress:z,symbol:on(z,f)?.symbol??t.asset.symbol,decimals:on(z,f)?.decimals??t.asset.decimals};if(i){const $=h||m;if(!$)return null;const ue=$,ve=o?r?.amountInMax??0n:N;if(ve===0n)return null;const pe=await F(ve,K=>S({fundingAmountOverride:K}).then(ie=>Rn(Ns(ie),ue)),z,{userOverride:$,useCustomTransfers:!0}),me=Rn(Ns(await S({fundingAmountOverride:pe})),ue),ge=await B(me,z,pe,{userOverride:$,useCustomTransfers:!0,feeExecutionMode:p});return es(ge,O)}if(!y||!x||!C||!b)return null;const J=h||m||x,P=o?r?.amountInMax??0n:N;if(P===0n)return null;const U=await F(P,$=>S({fundingAmountOverride:$}).then(ue=>Rn(Ns(ue),J)),z,{useCustomTransfers:!0});let de=Rn(Ns(await S({fundingAmountOverride:U})),J);const H=await B(de,z,U,{useCustomTransfers:!0,feeExecutionMode:p});return es(H,O)}if(s<=0||!h)return null;const v=h||m;if(!(!n&&!i&&t.asset?._source==="wallet"&&t.asset.chainId!==f)&&!A&&!k&&!w||w)return null;const E=Ye(t.amount,t.asset.decimals),I=await W();if(I.length===0)return null;const D=i&&t.asset?._source==="wallet"&&t.asset.chainId===f,R={chainId:f,tokenAddress:T,symbol:on(T,f)?.symbol??l.symbol,decimals:on(T,f)?.decimals??l.decimals};if(D){const N=await It.estimateBatchGas({user:v,outputToken:T,stepIndex:0,chainBatches:I}),z=to(E,10n),O=z+N.gasFee;return{...R,grossAmount:E+O,netAmount:E,totalFee:O,gasFee:N.gasFee,spicenetFee:z,bridgeFee:0n,gasQuoteSource:N.gasQuoteSource}}const L=I.some(N=>N.tokenTransfers?.length),j=await B(I,T,E,L?{userOverride:v,useCustomTransfers:!0,feeExecutionMode:p}:p?{userOverride:v,feeExecutionMode:p}:{userOverride:v});return es(j,R)}const md=10n;function La(e,t){const n=e.selectedAsset?.asset;if(!n||n?._source!=="wallet")return;const s=zn(n,e.resolvedChainId);if(!s||!Ee(s,e.executionTokenAddress))return;const o=on(e.executionTokenAddress,e.resolvedChainId),r=Dn(t,o?.decimals??e.destinationToken.decimals,n.decimals);if(r<=n.balance)return;const i=pt(r,n.decimals),c=pt(n.balance,n.decimals);throw new Error(`Insufficient ${n.symbol} for amount plus fees. Required ${i} ${n.symbol}; available ${c} ${n.symbol}.`)}function cr(e){const t=on(e.executionTokenAddress,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:t?.symbol??e.destinationToken.symbol,decimals:t?.decimals??e.destinationToken.decimals}}function Ps(e,t,n){const s=es(e,cr(t));if(!s)return;const o=to(n,md),r=s.bridgeFee??0n,i=o+s.gasFee+r;return{grossAmount:n+i,netAmount:n,combinedFeeAmount:i,feeExecutionMode:"user-transfer",feeBreakdown:{spicenetFee:o,gasFee:s.gasFee,bridgeFee:r}}}function ks(e,t,n){if(e===t)return!0;const s=e>t?e:t;return s===0n?!1:(e>t?e-t:t-e)*10000n<=s*n}function Oa(e,t,n){let s=0n,o=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=Es({abi:fn,data:c.data});if(d.functionName!=="transfer")continue;const l=d.args[0].toLowerCase(),p=d.args[1];l===rs.toLowerCase()?s+=p:l===Mn.toLowerCase()&&(o+=p)}catch{continue}}return{spicenetFee:s,gasFee:o}}function dr(e,t,n){const s=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,o=Oa(e,t.resolvedChainId,s);return o.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||o.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:ks(o.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&ks(o.gasFee,n.feeBreakdown.gasFee,100n)}function Ha(e,t){return e?ks(e.grossAmount,t.grossAmount,100n)&&ks(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&ks(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&ks(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}async function ur(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 s=await uo(e);e.ui.setTxHash(s??null)}else{e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.refs.spiceDepositSubmittedRef.current=!1;const s=new AbortController;e.refs.abortControllerRef.current=s,await ja(e,s.signal)}e.ui.setStep("success"),e.ui.setStatusMsg(e.isSourceDestToken?"Transaction confirmed":"Deposit confirmed")}catch(s){const o=s instanceof Error?s:new Error(String(s));if(o.name==="AbortError"||e.refs.abortControllerRef.current?.signal.aborted){e.ui.setStep("idle");return}const r=o.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(r),e.ui.setError(r),e.onError?.(o)}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=Ye(e.selectedAsset.amount,e.selectedAsset.asset.decimals),s=n;let o=await e.gasless.buildSupplyChainBatches();const r=e.selectedAsset.asset?._source==="wallet",i=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!r&&!o.some(m=>Qs(m.chainId)))throw new Error("Spice-funded supplies must include a Spicenet funding batch before the destination chain batch.");const c=o.some(m=>m.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?s:void 0;let u;for(let m=0;m<4;m+=1){const f=await e.gasless.estimateGasless(o,e.executionTokenAddress,d,c),y=es(f,cr(e));u=e.feeExecutionMode==="user-transfer"&&y?Ps(f,e,s):void 0;const x=u?.grossAmount??y?.grossAmount??d;if(x===d){d=x;break}d=x,o=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:d,actionAmountOverride:p,actionContextOverride:u})}e.feeExecutionMode==="user-transfer"&&(La(e,d),o=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:d,actionAmountOverride:p,actionContextOverride:u}));let h=u;await e.gasless.executeGasless(o,e.executionTokenAddress,d,e.gasless.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...c,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:m,chainBatches:f})=>{const y=Ps(m,e,s);if(!y)return null;const x=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&e.resolvedTokenIn?e.resolvedTokenIn:e.executionTokenAddress;Oa(f,e.resolvedChainId,x);const C=Ha(h,y),b=dr(f,e,y);return C||b?null:(h=y,e.gasless.buildSupplyChainBatches({fundingAmountOverride:y.grossAmount,actionAmountOverride:p,actionContextOverride:y}))}}:c),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){const s=n instanceof Error?n:new Error(String(n));if(s.name==="AbortError"||t.signal.aborted){e.ui.setStep("idle");return}const o=s.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(o),e.ui.setError(o),e.onError?.(s)}finally{e.ui.setIsExecuting(!1)}}async function ja(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 s=e.selectedAsset.asset,o=Ye(e.selectedAsset.amount,s.decimals),r=o,i=s?._source==="wallet"&&s.chainId===e.resolvedChainId;let c=await e.gasless.buildSupplyChainBatches();const d={userOverride:n,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,signAuthorizationsForEstimate:!0};let l=o;const p=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,u=e.feeExecutionMode==="user-transfer"&&!p?r:void 0;let h;if(i){const v=await It.estimateBatchGas({user:n,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:c}),E=to(o,10n),I=E+v.gasFee;l=o+I,e.feeExecutionMode==="user-transfer"&&(h={grossAmount:l,netAmount:r,combinedFeeAmount:I,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:E,gasFee:v.gasFee,bridgeFee:0n}})}else for(let v=0;v<4;v+=1){const E=await e.gasless.estimateGasless(c,e.executionTokenAddress,0n,d),I=e.feeExecutionMode==="user-transfer"?Ps(E,e,r):void 0,D=es(E,cr(e)),R=I?.grossAmount??(D?D.grossAmount>o?D.grossAmount:o:l);if(h=I,R===l){l=R;break}l=R;const L=on(e.executionTokenAddress,e.resolvedChainId),j=Dn(l,L?.decimals??e.destinationToken.decimals,s.decimals);c=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:l,sourceFundingAmountOverride:j,withdrawalAmountOverride:l,actionAmountOverride:u,actionContextOverride:I})}const m=on(e.executionTokenAddress,e.resolvedChainId);let f=i?l:Dn(l,m?.decimals??e.destinationToken.decimals,s.decimals);La(e,l),c=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:l,sourceFundingAmountOverride:f,withdrawalAmountOverride:l,actionAmountOverride:u,actionContextOverride:h});const y=s.chainId,x=n,C=await e.externalWallet.getEthereumProvider();let b=null;try{const v=await C.request({method:"eth_chainId"});b=parseInt(v,16)}catch{b=null}b!==y&&(e.ui.setStatusMsg("Switching source network..."),await os(C,y));const A=De(y),k=Xn({account:e.externalWalletAddress,chain:A?.viemChain,transport:Jn(C)}),w=Lt(s.address),T=s.isNative||Ve(w),S=Tt(y),W=async v=>{if(v<=0n)return;const E=T?await k.sendTransaction({to:x,value:v,chain:A?.viemChain}):await k.sendTransaction({to:w,data:At({abi:fn,functionName:"transfer",args:[x,v]}),chain:A?.viemChain});if((await S.waitForTransactionReceipt({hash:E,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Embedded wallet funding failed")};e.ui.setStatusMsg("Funding embedded wallet..."),await W(f);let B=f;if(e.feeExecutionMode==="user-transfer")for(let v=0;v<4;v+=1){const E=await e.gasless.estimateGasless(c,e.executionTokenAddress,0n,d),I=Ps(E,e,r);if(!I)break;const D=i?I.grossAmount:Dn(I.grossAmount,m?.decimals??e.destinationToken.decimals,s.decimals);if(D>B&&(e.ui.setStatusMsg("Topping up embedded wallet..."),await W(D-B),B=D),h=I,l=I.grossAmount,f=D,c=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:l,sourceFundingAmountOverride:f,withdrawalAmountOverride:l,actionAmountOverride:u,actionContextOverride:I}),dr(c,e,I))break}e.ui.setStatusMsg("Signing supply intent...");let F=h;await e.gasless.executeGasless(c,e.executionTokenAddress,0n,e.gasless.onProgress,t,e.feeExecutionMode==="user-transfer"?{...d,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:v,chainBatches:E})=>{const I=Ps(v,e,r);if(!I)return null;const D=Ha(F,I),R=dr(E,e,I);if(D||R)return null;if(I.grossAmount>l)throw new Error("Fee estimate increased after wallet funding. Please retry so the signed fee can match the latest relayer estimate.");F=I;const L=i?I.grossAmount:Dn(I.grossAmount,m?.decimals??e.destinationToken.decimals,s.decimals);return e.gasless.buildSupplyChainBatches({fundingAmountOverride:I.grossAmount,sourceFundingAmountOverride:L,withdrawalAmountOverride:I.grossAmount,actionAmountOverride:u,actionContextOverride:I})}}:d)}async function uo(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,s=e.activeSignerAddress??e.externalWalletAddress;if(!s||!n)throw new Error("Please connect your wallet to continue");const o=Ye(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),r={userAddress:s,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},i=e.buildActionCalls(o,r);if(i.length===0)throw new Error("No action calls configured");const c=await n.getEthereumProvider();let d=null;try{const m=await c.request({method:"eth_chainId"});d=parseInt(m,16)}catch{d=null}d!==e.resolvedChainId&&await os(c,e.resolvedChainId);const l=De(e.resolvedChainId),p=Xn({account:s,chain:l?.viemChain,transport:Jn(c)}),u=Tt(e.resolvedChainId);let h;for(const m of i){const f=await p.sendTransaction({to:m.to,data:m.data,value:m.value,chain:l?.viemChain});if((await u.waitForTransactionReceipt({hash:f,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transaction failed");h=f}return h}async function Qa(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,s=n.chainId,o=Ye(e.currentPaymentAmount,e.destinationToken.decimals),r=e.selectedIsEquivalent?o: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,b=>e.gasless.buildPayChainBatches({fundingAmountOverride:b}),i,c),l=An(s),p=await e.externalWallet.getEthereumProvider();let u=null;try{const b=await p.request({method:"eth_chainId"});u=parseInt(b,16)}catch{u=null}u!==s&&await os(p,s);const h=De(s),m=Xn({account:e.externalWalletAddress,chain:h?.viemChain,transport:Jn(p)}),f=Lt(n.address),y=n.isNative||Ve(f)?await m.sendTransaction({to:l,value:d,chain:h?.viemChain}):await m.sendTransaction({to:f,data:At({abi:fn,functionName:"transfer",args:[l,d]}),chain:h?.viemChain});if((await Tt(s).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}),C=x.some(b=>b.tokenTransfers?.length);return await e.gasless.executeGasless(x,i,d,b=>{b.txHash&&(e.ui.setPaymentResult(A=>({...A??{status:"processing"},txHash:b.txHash})),e.ui.setTxHash(b.txHash))},void 0,C?c:{userOverride:t})}async function pr(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 s;if(e.isSourceDestToken||e.parsedAmount===0)s=await uo(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const o=e.selectedAsset.asset,r=Ye(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||o.address,l=await e.gasless.estimateRequiredGrossFunding(i,h=>e.gasless.buildPayChainBatches({fundingAmountOverride:h}),d,{userOverride:c,useCustomTransfers:!0}),p=await e.gasless.buildPayChainBatches({fundingAmountOverride:l}),u=await e.onPayExecute({asset:o,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(h=>({...h??{status:"processing"},txHash:u}))),s=u||void 0}else s=await Qa(e);e.ui.setPaymentResult(o=>({status:"success",txHash:o?.txHash||s||""}))}catch(s){const o=Cn(s,"Payment failed. Please try again.");e.ui.setError(o),e.ui.setPaymentResult({status:"failed",error:o}),e.onError?.(s instanceof Error?s:new Error(o))}finally{e.ui.setIsExecuting(!1)}return}if(e.isSourceDestToken||t){if(!(e.activeSignerAddress??e.externalWalletAddress??e.address)){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{const n=await uo(e);e.ui.setPaymentResult(s=>({status:"success",txHash:s?.txHash||n||""}))}catch(n){const s=Cn(n,"Payment failed. Please try again.");e.ui.setError(s),e.ui.setPaymentResult({status:"failed",error:s}),e.onError?.(n instanceof Error?n: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=Ye(e.currentPaymentAmount,e.destinationToken.decimals),s={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode};if(t){const x=await e.gasless.buildPayChainBatches({actionAmountOverride:0n,fundingAmountOverride:0n}),C=await e.gasless.executeGasless(x,e.destinationToken.address,0n,b=>{b.txHash&&(e.ui.setPaymentResult(A=>({...A,txHash:b.txHash})),e.ui.setTxHash(b.txHash))},void 0,s);e.ui.setPaymentResult(b=>({status:"success",txHash:b?.txHash||C}));return}const o=e.selectedAsset?.asset;if(!o)throw new Error("Select a payment source");const r=e.resolvedTokenIn||o.address||e.destinationToken.address,i=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:n,c=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,d=(x,C,b)=>{const A=Ns(x),k=S=>(S.tokenTransfers??[]).some(W=>W.from==="escrow"),w=A.filter(S=>!k(S)),T=A.filter(k);return[...w,...Rn(T,c,C,b)]},l=await e.gasless.estimateRequiredGrossFunding(i,x=>e.gasless.buildPayChainBatches({fundingAmountOverride:x}).then(C=>d(C)),r,s);let p=l,u=d(await e.gasless.buildPayChainBatches({fundingAmountOverride:l}));const h=await e.gasless.estimateGasless(u,r,l,s),m=es(h,{chainId:e.resolvedChainId,tokenAddress:r,symbol:on(r,e.resolvedChainId)?.symbol??o.symbol,decimals:on(r,e.resolvedChainId)?.decimals??o.decimals})?.grossAmount??l;m!==l&&(p=m),u=d(await e.gasless.buildPayChainBatches({fundingAmountOverride:p}),h,{payoutAlreadyGross:!0});const f=u.some(x=>x.tokenTransfers?.length),y=await e.gasless.executeGasless(u,r,f?p:0n,x=>{x.txHash&&(e.ui.setPaymentResult(C=>({...C,txHash:x.txHash})),e.ui.setTxHash(x.txHash))},void 0,s);e.ui.setPaymentResult(x=>({status:"success",txHash:x?.txHash||y}))}catch(n){const s=Cn(n,"Payment failed. Please try again.");e.ui.setError(s),e.ui.setPaymentResult({status:"failed",error:s}),e.onError?.(n instanceof Error?n:new Error(s))}finally{e.ui.setIsExecuting(!1)}}const gd=({variant:e,destinationSymbol:t,destinationLogoURI:n,destinationDecimals:s,primaryColor:o,fontFamily:r,textPrimary:i,textSecondary:c,cardBg:d,cardBorder:l,dk:p,dark:u,isQuoting:h,quoteError:m,estimatedOutput:f,paymentAmount:y,needsSwap:x,exactOutputSwap:C,adjustable:b=!1,maxAmount:A,onAmountChange:k})=>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(qa,{symbol:t,logoURI:n,primaryColor:o,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:h?a("span",{style:{fontSize:"18px",color:c,fontFamily:r},children:"Quoting..."}):m?a("span",{style:{fontSize:"13px",color:u?"#f87171":"#dc2626",fontFamily:r},children:"Quote failed"}):f?a(as,{value:f,title:f,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(yd,{destinationSymbol:t,destinationLogoURI:n,destinationDecimals:s,primaryColor:o,fontFamily:r,textPrimary:i,textSecondary:c,cardBg:d,cardBorder:l,dk:p,dark:u,paymentAmount:y||"0",needsSwap:x,exactOutputSwap:C,isQuoting:h,adjustable:b,maxAmount:A,onAmountChange:k}),Va=wn(gd),qa=({symbol:e,logoURI:t,primaryColor:n,size:s})=>t?a("img",{src:t,alt:e,style:{width:s,height:s,borderRadius:"50%",objectFit:"cover"}}):a("div",{style:{width:s,height:s,borderRadius:"50%",backgroundColor:`${n}22`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:s<30?"11px":"12px",fontWeight:700,color:n},children:e.slice(0,2)}),yd=({destinationSymbol:e,destinationLogoURI:t,destinationDecimals:n,primaryColor:s,fontFamily:o,textPrimary:r,textSecondary:i,cardBg:c,cardBorder:d,dk:l,dark:p,paymentAmount:u,needsSwap:h,exactOutputSwap:m,isQuoting:f,adjustable:y,maxAmount:x,onAmountChange:C})=>{const b='"IBM Plex Mono", monospace',A=parseFloat(u||"0"),k=x?parseFloat(x):0,[w,T]=M(u||""),S=ne(null),[W,B]=M(null),[F,v]=M(null);G(()=>{y||T(u||"")},[u,y]);const E=R=>{let L=R;L.startsWith(".")&&(L="0"+L);const j=gs(L);let N=j;x&&parseFloat(j)>parseFloat(x)&&(N=x),T(N),S.current&&clearTimeout(S.current),S.current=setTimeout(()=>C?.(N),300)},I=R=>{if(!k)return;if(R===100){T(x||k.toString()),S.current&&clearTimeout(S.current),C?.(x||k.toString());return}const L=10**n,j=Math.floor(k*R/100*L)/L,N=ys(j,n);T(N),S.current&&clearTimeout(S.current),C?.(N)},D=k>0?parseFloat(w||"0")/k*100:0;return G(()=>()=>{S.current&&clearTimeout(S.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(qa,{symbol:e,logoURI:t,primaryColor:s,size:32}),g("div",{children:[a("span",{style:{fontSize:"14px",fontWeight:600,color:r,fontFamily:o},children:"Payment"}),a("div",{style:{fontSize:"12px",color:i,fontFamily:o,marginTop:"2px"},children:e})]})]}),g("div",{style:{textAlign:"right"},children:[y?a(as,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:w,onChange:R=>E(R.target.value),placeholder:"0.0",fontFamily:b,color:r,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):a(as,{element:"div",value:A>0?u:"0.00",title:A>0?u:"0.00",fontFamily:b,color:r,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),a("div",{style:{fontSize:"12px",color:i,fontFamily:b,marginTop:"2px"},children:e}),y&&k>0&&a("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((R,L)=>{const j=Math.abs(D-R)<1,N=L===4,z=R/100,O=W===R,J=F===R;return a("button",{onClick:()=>I(R),onMouseEnter:()=>B(R),onMouseLeave:()=>{B(null),v(null)},onMouseDown:()=>v(R),onMouseUp:()=>v(null),title:`${R}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:j?1:O?.8:.5,transform:J?"scale(0.85)":O?"scale(1.15)":"scale(1)",transition:Sn.interactive},children:g("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[a("circle",{cx:"7",cy:"7",r:"6.84375",fill:N?s:"none",stroke:N?s:p?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!N&&z>0&&a("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${z>.5?1:0} 1 ${7+6.84375*Math.sin(z*2*Math.PI)} ${7-6.84375*Math.cos(z*2*Math.PI)} Z`,fill:p?l?.textSecondary||"#9ca3af":"#3C3E42"})]})},R)})})]})]}),h&&m&&!f&&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:o,opacity:.7},children:["via ",m.venue]})})]})};function Ka(e,t,n){const s=Ee(e.address,t),o=e.chainId===n,r=e._source==="wallet";return r&&s&&o?0:r&&o?1:!r&&s?2:!r&&o?3:4}function Ya(e,t){return!t||t.length===0||t.some(n=>Ee(n,e.address))?!0:Object.keys(e.chainTokens??{}).some(n=>{const s=ws(n);return s?t.some(o=>Ee(o,s.address)):!1})}function fr(e){const{destinationToken:t,supportedSourceAssets:n,sourceChains:s,enabled:o}=e,r=(un(en)?.mode||"7702")!=="7702",i=Tn(),{externalAddress:c,embeddedAddress:d,activeAddress:l}=On(),p=i||d,{assets:u,refetch:h}=Ds({address:p,supportedChains:s,enabled:o&&!r&&!!p,refetchInterval:3e4}),m=te(()=>r?[]:u.filter(W=>Ya(W,n)),[u,n,r]),f=r?l??c:i,y=te(()=>{const W=new Set,B=[],F=v=>{if(!v)return;const E=v.toLowerCase();W.has(E)||(W.add(E),B.push(Ne(v)))};if(F(t.address),n)for(const v of n)F(v);return B},[r,t.address,n]),x=te(()=>y.map(W=>W.toLowerCase()).sort().join(","),[y]),C=te(()=>JSON.stringify([...s||[]].sort()),[s]),[b,A]=M([]),k=ne(0),w=ne(async()=>{}),T=oe(async()=>{if(!o||!f||y.length===0){k.current++,A([]);return}const W=++k.current,B=Ne(f),F=r?s&&s.length>0?s:[t.chainId]:[t.chainId],v=[];for(const R of y){const L=R.toLowerCase();if(L===pn)continue;if(L===t.address.toLowerCase()){const N=De(t.chainId)?.supportedTokens?.find(z=>Ee(z.address,L));v.push({address:R,chainId:t.chainId,configToken:N?{decimals:N.decimals,symbol:N.symbol,name:N.name,logo:N.logo}:void 0});continue}let j=!1;for(const N of F){const z=De(N)?.supportedTokens?.find(O=>Ee(O.address,L));if(z){v.push({address:R,chainId:N,configToken:{decimals:z.decimals,symbol:z.symbol,name:z.name,logo:z.logo}}),j=!0;break}}j||v.push({address:R,chainId:t.chainId})}const E=new Map;for(const R of v){const L=E.get(R.chainId)||[];L.push(R),E.set(R.chainId,L)}const I=async(R,L)=>{try{const j=await Un(R,{address:L.address,abi:fn,functionName:"balanceOf",args:[B]});let N,z,O,J;if(L.configToken)N=L.configToken.decimals,z=L.configToken.symbol,O=L.configToken.name,J=L.configToken.logo;else{const[de,H,$]=await Promise.all([Un(R,{address:L.address,abi:fn,functionName:"decimals"}).catch(()=>18),Un(R,{address:L.address,abi:fn,functionName:"symbol"}).catch(()=>"TOKEN"),Un(R,{address:L.address,abi:fn,functionName:"name"}).catch(()=>"TOKEN")]);N=Number(de),z=H,O=$}const P=Ee(L.address,t.address)&&L.chainId===t.chainId;P&&t.logoURI&&(J=t.logoURI),P&&!L.configToken&&z==="TOKEN"&&(z=t.symbol,O=t.symbol);const U=parseFloat((Number(j)/Math.pow(10,N)).toFixed(6));return{address:L.address,name:O,symbol:z,decimals:N,balance:j,balanceFormatted:U,balanceUsd:0,logoURI:J,isNative:!1,chainId:L.chainId}}catch{return null}},D=await Promise.all(Array.from(E.entries()).map(async([R,L])=>{let j;try{j=Tt(R)}catch{return[]}const N=[],z=[];for(const J of L){const P=N.length;N.push({address:J.address,abi:fn,functionName:"balanceOf",args:[B]}),J.configToken||N.push({address:J.address,abi:fn,functionName:"decimals"},{address:J.address,abi:fn,functionName:"symbol"},{address:J.address,abi:fn,functionName:"name"}),z.push({start:P,item:J})}let O=null;try{O=await j.multicall({contracts:N})}catch{O=null}return O?z.map(({start:J,item:P})=>{const U=O[J],de=U?.status==="success"?U.result:0n;let H,$,ue,ve;if(P.configToken)H=P.configToken.decimals,$=P.configToken.symbol,ue=P.configToken.name,ve=P.configToken.logo;else{const ge=O[J+1],K=O[J+2],ie=O[J+3];H=ge?.status==="success"?Number(ge.result):18,$=K?.status==="success"?K.result:"TOKEN",ue=ie?.status==="success"?ie.result:$}const pe=Ee(P.address,t.address)&&P.chainId===t.chainId;pe&&t.logoURI&&(ve=t.logoURI),pe&&!P.configToken&&$==="TOKEN"&&($=t.symbol,ue=t.symbol);const me=parseFloat((Number(de)/Math.pow(10,H)).toFixed(6));return{address:P.address,name:ue,symbol:$,decimals:H,balance:de,balanceFormatted:me,balanceUsd:0,logoURI:ve,isNative:!1,chainId:P.chainId}}):(await Promise.all(L.map(J=>I(j,J)))).filter(J=>J!==null)}));W===k.current&&A(D.flat())},[o,r,f,x,C,t.address,t.chainId,t.symbol,t.logoURI]);G(()=>{w.current=T},[T]),G(()=>{if(!o){A([]);return}w.current();const W=setInterval(()=>{w.current()},15e3);return()=>clearInterval(W)},[o,r,f,x,C,t.address,t.chainId]);const S=oe(()=>{T()},[T]);return{displayAssets:te(()=>{const W=[],B=b.filter(v=>v.balance>0n);for(const v of B)W.push({...v,_source:"wallet"});for(const v of m)W.push({...v,_source:"spice"});const F=t.address.toLowerCase();return W.sort((v,E)=>Ka(v,F,t.chainId)-Ka(E,F,t.chainId)),W},[b,m,t.address,t.chainId]),filteredSpiceAssets:m,walletAssets:b,embeddedWalletAddress:p,externalAddress:c,isNon7702:r,refreshSpiceAssets:h,refreshWalletAssets:S}}async function Ga(e){const{tokenIn:t,tokenOut:n,amountIn:s,fee:o,chainId:r,config:i}=e;if(s<=0n)throw new Error("amountIn must be greater than 0");const c=(await Tt(r).simulateContract({address:i.quoterV2,abi:Ui,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:s,fee:o,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 Za(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(o=>Ga({...e,fee:o})));let s=null;for(let o=0;o<n.length;o++){const r=n[o];r.status==="fulfilled"&&(!s||r.value.amountOut>s.amountOut)&&(s={...r.value,fee:t[o]})}if(!s)throw new Error("No liquidity found for this pair on any fee tier.");return s}const xd=[{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 bd(e){const{tokenIn:t,tokenOut:n,amountOut:s,fee:o,chainId:r,config:i}=e;if(s<=0n)throw new Error("amountOut must be greater than 0");const c=(await Tt(r).simulateContract({address:i.quoterV2,abi:xd,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:s,fee:o,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 wd(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(o=>bd({...e,fee:o})));let s=null;for(let o=0;o<n.length;o++){const r=n[o];r.status==="fulfilled"&&(!s||r.value.amountIn<s.amountIn)&&(s={...r.value,fee:t[o]})}if(!s)throw new Error("No liquidity found for this pair on any fee tier.");return s}function Xa(e){return e.type==="swap"}const hr=.02,Cd=[1,8453,42161,10,137,43114,56],kd="https://api.1inch.dev/swap/v6.0";function Ja(e,t){return Li(e,t)}function $a(e){const t=e?.baseUrl??kd;return{name:"1inch",chainIds:e?.chainIds??Cd,resolve:async(n,s,o)=>{const r=n.maxSlippage??hr,i=r*100,c=Ve(n.tokenIn)?Br:n.tokenIn,d=Ve(n.tokenOut)?Br:n.tokenOut,l=Ve(n.tokenIn);try{const p=new URL(`${t}/${s}/swap`);p.searchParams.set("src",c),p.searchParams.set("dst",d),p.searchParams.set("amount",n.amountIn.toString()),p.searchParams.set("from",o),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 h=await fetch(p.toString(),{headers:u});if(!h.ok)throw new Re("VENUE_API_ERROR",`[1inchVenue] API returned ${h.status} for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:`HTTP ${h.status}`});const m=await h.json();if(!m.dstAmount||!m.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const f=BigInt(m.dstAmount);if(f<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const y=Ja(f,r),x=[];return m.tx.to&&!l&&x.push({to:n.tokenIn,value:0n,data:At({abi:fn,functionName:"approve",args:[m.tx.to,n.amountIn]})}),x.push({to:m.tx.to,value:BigInt(m.tx.value||"0"),data:m.tx.data}),{venue:"1inch",amountOut:f,amountOutMinimum:y,calls:x}}catch(p){if(p instanceof Re)throw p;const u=p instanceof Error?p.message:String(p);throw new Re("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}: ${u}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:u})}}}}const _a=[4114,5115],mr={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},ei={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[3e3]};function ti(e){return{name:"satsuma",chainIds:e.chainIds??_a,resolve:async(t,n,s)=>{const o=t.maxSlippage??hr,r=Ve(t.tokenIn);let i;try{i=await Za({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=Ja(i.amountOut,o),d=[];return r||d.push({to:t.tokenIn,value:0n,data:At({abi:fn,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),d.push({to:e.swapRouter,value:r?t.amountIn:0n,data:At({abi:zi,functionName:"exactInputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:i.fee,recipient:s,amountIn:t.amountIn,amountOutMinimum:c,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:i.amountOut,amountOutMinimum:c,calls:d}}}}function ni(e){return{name:"satsuma",chainIds:e.chainIds??_a,resolve:async(t,n,s)=>{const o=t.maxSlippage??hr,r=Ve(t.tokenIn);let i;try{i=await wd({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(o*1e4)),d=i.amountIn+i.amountIn*c/10000n,l=[];return l.push({to:e.swapRouter,value:r?d:0n,data:At({abi:vd,functionName:"exactOutputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:i.fee,recipient:s,amountOut:t.amountOut,amountInMaximum:d,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:i.amountIn,amountInMax:d,amountOut:t.amountOut,calls:l}}}}const vd=[{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 si(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(ti(e.satsuma)),t.push($a(e?.oneInch));function n(o){return t.find(r=>r.chainIds.includes(o))}async function s(o,r,i){const c=[],d=[];for(const l of o){if(!Xa(l)){c.push(l);continue}const p=n(r);if(!p)throw new Re("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 Re("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:s,getVenueForChain:n,venues:t}}function oi(e){const t=e?.customVenues??[];async function n(s,o,r){const i=t.filter(d=>d.chainIds.includes(o));if(i.length===0)throw new Re("NO_SWAP_ROUTE",`No exact-output venue supports chain ${o}`,{chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut});const c=(await Promise.allSettled(i.map(d=>d.resolve(s,o,r)))).filter(d=>d.status==="fulfilled").map(d=>d.value).filter(d=>d!==null);if(c.length===0)throw new Re("NO_SWAP_ROUTE",`All aggregators failed for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}`,{chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountOut:s.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 ri=si({satsuma:mr});async function Id(e){const t=ri.getVenueForChain(e.chainId);if(!t)throw new Error(`No swap venue configured for chain ${e.chainId}.`);const n=await t.resolve({type:"swap",tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:e.amountIn},e.chainId,e.recipient);if(!n)throw new Error("No liquidity for this pair.");return n}function gr(e){const{direction:t,selectedAsset:n,destinationToken:s,chainId:o,recipient:r,paymentAmount:i,resolveExactOutputSwap:c}=e,[d,l]=M(!1),[p,u]=M(null),[h,m]=M(null),[f,y]=M(null),[x,C]=M(null),[b,A]=M(null),[k,w]=M(null),[T,S]=M(null),[W,B]=M(null),F=ne(null),v=ne(null),E=ne(0),I=ne(new Map),D=te(()=>ri,[]),R=te(()=>oi({customVenues:[...c?[{name:"consumer-exact-output",chainIds:[o],resolve:c}]:[],ni(mr),ni(ei)]}),[c,o]),L=te(()=>{if(!n?.asset)return null;const $=zn(n.asset,o);if($)return $;const ue=Kn(n.asset.address,o,n.asset.chainId);return ue?ue.address:null},[n?.asset,o]),j=te(()=>n?.asset?$s(n.asset,o):[],[n?.asset,o]),N=te(()=>j.map($=>$.toLowerCase()).join(","),[j]);G(()=>{let $=!1;if(v.current&&(clearTimeout(v.current),v.current=null),!n?.asset||j.length<=1){B(null);return}return v.current=setTimeout(async()=>{const ue=t==="input"?n.amount:i||"0";let ve=0n;try{ve=t==="input"?Ye(ue,n.asset.decimals):0n}catch{ve=0n}try{const pe=await la(n.asset,o,{requiredAmount:ve});$||B(pe)}catch{$||B(null)}},400),()=>{$=!0,v.current&&(clearTimeout(v.current),v.current=null)}},[n?.asset,n?.amount,o,j.length,N,t,i]);const z=te(()=>W??L,[W,L]),O=te(()=>!n?.asset||!z?[]:[z,...j.filter($=>$.toLowerCase()!==z.toLowerCase())],[n?.asset,z,j]),J=te(()=>!n?.asset||!Rs(n.asset.address,n.asset.chainId,s.address,s.chainId)||!z?!1:Ee(z,s.address),[n,s.address,s.chainId,z]),P=z?Ee(z,s.address):!1,U=t==="output"&&parseFloat(i||"0")===0,de=!!n?.asset&&!J&&!P&&!U,H=de?T??z:z;return G(()=>{F.current&&clearTimeout(F.current);const $=t==="input"?n?.amount:i,ue=parseFloat($||"0");if(!de||!Number.isFinite(ue)||ue<=0||!n?.asset||!r||O.length===0){E.current++,m(null),y(null),C(null),A(null),w(null),S(null),u(null),l(!1);return}const ve=n.asset.decimals;let pe;try{pe=t==="input"?Ye(n.amount,ve):Ye(i||"0",s.decimals)}catch{E.current++,u("Invalid amount"),l(!1);return}const me=++E.current,ge=()=>me!==E.current;l(!0);const K=t==="output"?150:400;return F.current=setTimeout(async()=>{try{if(t==="input"){const ie=D.getVenueForChain(o);if(!ie)throw new Error("No swap venue for this chain");let X=null,ee=null;for(const Ce of O){const be=`${t}:${o}:${Ce.toLowerCase()}:${s.address.toLowerCase()}:${pe.toString()}`,Q=I.current.get(be);if(Q&&Q.expiresAt>Date.now()&&Q.resolvedSwap){X=Q.resolvedSwap,ee=Ce;break}const ae=await ie.resolve({type:"swap",tokenIn:Ce,tokenOut:s.address,amountIn:pe},o,r);if(ge())return;if(ae){I.current.set(be,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:ae}),X=ae,ee=Ce;break}}if(!X||!ee)throw new Error("No liquidity for this pair");S(ee),w(X.amountOut),C(X),A(null);const fe=parseFloat(pt(X.amountOut,s.decimals));m(fe<.01?fe.toPrecision(4):fe.toLocaleString(void 0,{maximumFractionDigits:6})),y(null),u(null)}else{let ie=null,X=null;for(const ee of O){const fe=`${t}:${o}:${ee.toLowerCase()}:${s.address.toLowerCase()}:${pe.toString()}`,Ce=I.current.get(fe);if(Ce&&Ce.expiresAt>Date.now()&&Ce.exactOutputSwap){ie=Ce.exactOutputSwap,X=ee;break}try{const be=await R.getQuote({tokenIn:ee,tokenOut:s.address,amountOut:pe},o,r);if(ge())return;I.current.set(fe,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:be}),ie=be,X=ee;break}catch{if(ge())return}}if(!ie||!X)throw new Error("No liquidity for this pair");S(X),A(ie),C(null),w(null),y(parseFloat(pt(ie.amountIn,ve)).toFixed(6)),m(null),u(null)}}catch(ie){if(ge())return;const X=ie instanceof Error?ie.message:"Failed to get quote";u(X),m(null),y(null),C(null),A(null),w(null),S(null)}finally{ge()||l(!1)}},K),()=>{F.current&&clearTimeout(F.current)}},[t,de,n?.amount,n?.asset?.address,n?.asset?.decimals,i,O,o,s.address,s.decimals,r,D,R]),{isQuoting:d,quoteError:p,estimatedOutput:h,estimatedInput:f,resolvedSwap:x,exactOutputSwap:b,quoteAmountOut:k,resolvedTokenIn:H,isDirect:P,needsSwap:de,selectedIsEquivalent:J}}const ai={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},ii=["signing-delegation","signing-intent","submitting","executing"],Ad=()=>{},li=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,destinationToken:s,sourceChains:o,supportedSourceAssets:r,buildActionCalls:i,feeExecutionMode:c="user-transfer",buildSpicenetBatch:d,onPayExecute:l,resolveExactOutputSwap:p,actionLabel:u,amountDirection:h="input",swapDescription:m,directDescription:f,paymentAmount:y,amountInputMode:x="fixed",minPaymentAmount:C,maxPaymentAmount:b,onAmountChange:A,styles:k,dark:w,title:T,subtitle:S,onAddFunds:W,onSuccess:B,onError:F})=>{const v=h==="output",{theme:E,dark:I,primaryColor:D,dk:R,palette:L,fontFamily:j,monoFont:N,inputDark:z,cardBg:O,cardBorder:J,textPrimary:P,textSecondary:U,subtitleText:de}=wt(k,w),H=te(()=>z?{...E,colors:{...E.colors,secondary:R.cardBg,surfaceHover:R.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:E,[z,E,R.cardBg,R.hoverBg]),$=s.chainId,ue=un(en),ve=ue?.mode||"7702",pe=ve!=="7702",me=!!ue?.isWhitelistGateActive,ge=!!ue?.isWhitelistConfigured&&ue?.isUserWhitelisted!==!0,K=te(()=>o??ue?.supportedChainIds??[],[o,ue?.supportedChainIds]),ie=te(()=>{if(me)return[];if(r)return r;const xe=ue?.allowedTokens;if(!xe||xe.length===0)return;const zt=new Set(xe.map(Gn=>Gn.toLowerCase())),fs=[],Yn=new Set;for(const Gn of K){const go=De(Gn);for(const yo of go?.supportedTokens??[]){if(!zt.has(yo.symbol.toLowerCase()))continue;const wr=yo.address.toLowerCase();Yn.has(wr)||(Yn.add(wr),fs.push(yo.address))}}return fs},[r,ue?.allowedTokens,K,me]),X=Wn(),{address:ee,isConnected:fe,isReady:Ce,isAuthenticated:be,provider:Q}=X,{executeGasless:ae,estimateGasless:_}=Cs(),{externalWallet:Be,externalAddress:Ue,embeddedAddress:it,activeWallet:mt,activeAddress:Vt}=On(),st=Tn()||it,{displayAssets:we,filteredSpiceAssets:We,embeddedWalletAddress:ze,refreshSpiceAssets:$e,refreshWalletAssets:lt}=fr({destinationToken:s,supportedSourceAssets:ie,sourceChains:K,enabled:e&&(pe?!!Ue:!!st)}),ft=me||v||pe?we:We;G(()=>{e&&console.debug("[SpiceSupply] selectable assets",{mode:ve,walletAddressUsed:ze,count:ft.length,assets:ft.map(xe=>({symbol:xe.symbol,address:xe.address,chainId:xe.chainId,balanceFormatted:xe.balanceFormatted,source:xe?._source}))})},[e,ve,ze,ft]);const[q,qe]=M(null),[Se,ot]=M(y||""),[_e,nn]=M(!1),[Ot,gt]=M(null),[Fe,St]=M("idle"),[Ht,Le]=M(""),[sn,Me]=M(null),[Gt,Xt]=M(!1),[Ge,ye]=M(null),[Ze,et]=M(null),[rn,Ie]=M(!1),[Yt,Mt]=M(!1),[Ct,Ke]=M(null),an=ne(q),Pt=ne(!1),ln=ne(null),Jt=ne(null),qt=ne(0),Rt=ne(null),yt=ne(null);G(()=>{an.current=q},[q]);const Qe=x==="adjustable"?Se:y||"0",ct=ze||it||ee,{isQuoting:Dt,quoteError:cn,estimatedOutput:dn,resolvedSwap:Ut,exactOutputSwap:le,quoteAmountOut:ht,resolvedTokenIn:dt,isDirect:Et,needsSwap:rt,selectedIsEquivalent:Pe}=gr({direction:h,selectedAsset:q,destinationToken:s,chainId:$,recipient:ct,paymentAmount:Qe,resolveExactOutputSwap:p}),kt=v?parseFloat(Qe||"0"):parseFloat(q?.amount||"")||0,mn=kt>0&&kt<Vn,se=q?.asset?._source==="wallet",re=!!q?.asset&&se&&q.asset.chainId!==$,Ae=te(()=>q?.asset?We.find(xe=>Ee(xe.address,q.asset.address))?.balanceFormatted??0:0,[q,We]),Xe=se?q?.asset.balanceFormatted??0:Ae,ut=te(()=>{if(!q?.asset)return!1;if(v)return Ze?Dn(Ze.grossAmount,Ze.decimals,q.asset.decimals)>q.asset.balance:Pe||Et?kt>q.asset.balanceFormatted:le?parseFloat(pt(le.amountInMax,q.asset.decimals))>q.asset.balanceFormatted:!1;if(Ze){const xe=Dn(Ze.grossAmount,Ze.decimals,q.asset.decimals);return se?xe>q.asset.balance:parseFloat(pt(xe,q.asset.decimals))>Xe}return kt>Xe},[q,v,Ze,Pe,kt,le,Xe,se,Et]);G(()=>{e||(qe(null),gt(null),nn(!1),St("idle"),Le(""),Me(null),Xt(!1),ye(null),et(null),Ie(!1),Mt(!1),Ke(null),Pt.current=!1,x==="adjustable"&&ot(y||""),ln.current&&(ln.current.abort(),ln.current=null))},[e]);const Ft=oe(xe=>{qe(zt=>({asset:xe,amount:zt?.asset?.address===xe.address&&zt?.asset?.chainId===xe.chainId&&zt.amount||""})),gt(null),Ke(null),Mt(!1)},[]),Wt=oe(xe=>{qe(zt=>zt&&{...zt,amount:xe}),gt(null),Ke(null),Mt(!1)},[]),Bt=oe(xe=>{let zt=xe;b&&parseFloat(zt)>parseFloat(b)&&(zt=b),ot(zt),A?.(zt),gt(null),Ke(null),Mt(!1)},[b,A]);oe(xe=>{if(Pt.current||!ee)return;const zt=an.current;!zt?.asset||!zt.amount||zt.asset?._source==="wallet"||Ye(v?Qe:zt.amount,zt.asset.decimals)===0n||(Pt.current=!0,$e())},[ee,$,$e,v,Qe]);const He=oe(xe=>{St({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[xe.step]||"executing"),Le(xe.message),xe.txHash&&Me(xe.txHash)},[]),Kt=te(()=>({currentPaymentAmount:Qe,destinationToken:s,embeddedWalletAddress:ze,providerEmbeddedAddress:it,externalWalletAddress:Ue,address:ee,isNon7702:pe,isPayMode:v,resolvedChainId:$,buildActionCalls:i,feeExecutionMode:c,buildSpicenetBatch:d,selectedAsset:q,needsSwap:rt,resolvedSwap:Ut,exactOutputSwap:le,quoteAmountOut:ht,resolvedTokenIn:dt}),[Qe,s,ze,it,Ue,ee,pe,v,$,i,c,d,q,rt,Ut,le,ht,dt]),Je=oe(xe=>rr({...Kt,requestTimestampMs:Jt.current??Date.now()},xe),[Kt]),Z=oe(xe=>ar({...Kt,requestTimestampMs:Jt.current??Date.now()},xe),[Kt]),ke=oe((xe,zt,fs,Yn)=>ir(xe,zt,fs,_,Yn),[_]),vt=te(()=>q?.asset?rt&&dt?dt:q.asset.chainId===$?q.asset.address:dt??zn(q.asset,$)??s.address:s.address,[q,s.address,rt,$,dt]),Nt=oe(()=>(Jt.current=Date.now(),ur(yt.current)),[]),tt=te(()=>q?.asset?Ee(q.asset.address,s.address)&&q.asset.chainId===s.chainId:!1,[q,s.address,s.chainId]),Zt=tt&&(pe||v),xt=Zt&&kt>0&&!!q?.asset,kn=ge&&!Zt,V=te(()=>{if(!xt)return null;let xe;try{xe=Ye(Qe||"0",s.decimals)}catch{return null}return{symbol:s.symbol,decimals:s.decimals,grossAmount:xe,netAmount:xe,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}},[xt,Qe,s.symbol,s.decimals]),Y=Ot,he=te(()=>!(!q?.asset||kt<=0),[q,kt,xt]),ce=te(()=>!e||_e||Fe!=="idle"||!he||xt||!q?.asset?null:[v?"pay":"supply",h,q.asset.address.toLowerCase(),q.asset.chainId,q.amount,Qe,s.address.toLowerCase(),s.chainId,$,dt?.toLowerCase()??"",rt?"swap":"direct",Et?"direct-token":"routed-token",pe?"non7702":"7702",tt?"source-dest":"cross-chain",Dt?"quoting":"quoted",le?.amountIn?.toString()??"",le?.amountInMax?.toString()??"",le?.venue??"",Ut?.amountOut?.toString()??"",ht?.toString()??"",ze??"",it??"",ee??""].join("|"),[e,_e,Fe,he,xt,q,v,h,Qe,s,$,dt,rt,Et,pe,tt,Dt,le,Ut,ht,ze,it,ee]),je=oe(()=>lr({selectedAsset:q,isPayMode:v,parsedAmount:kt,needsSwap:rt,exactOutputSwap:le,isNon7702:pe,isSourceDestToken:tt,currentPaymentAmount:Qe,destinationToken:s,feeExecutionMode:c,resolvedTokenIn:dt,embeddedWalletAddress:ze,providerEmbeddedAddress:it,resolvedChainId:$,isConnected:fe,address:ee,ready:Ce,authenticated:be,isDirect:Et,resolvedSwap:Ut,isQuoting:Dt,executionTokenAddress:vt,buildPayChainBatches:Je,buildSupplyChainBatches:Z,estimateGasless:_,estimateRequiredGrossFunding:ke}),[q,v,kt,rt,le,pe,tt,Qe,s,c,dt,ze,it,ke,Je,_,$,fe,ee,Ce,be,Et,Ut,Dt,Z,vt]);G(()=>{Rt.current=je},[je]);const Oe=oe(xe=>za({asset:xe,isPayMode:v,isNon7702:pe,needsSwap:rt,isQuoting:Dt,embeddedWalletAddress:ze,buildSupplyChainBatches:Z,estimateGasless:_,executionTokenAddress:vt,feeExecutionMode:c}),[v,pe,rt,Dt,ze,Z,_,vt,c]);G(()=>{if(!e){Ie(!1),Mt(!1),Ke(null),et(null);return}if(_e||Fe!=="idle"){qt.current+=1,Ie(!1);return}if(!he){et(null),Ie(!1),Mt(!1),Ke(null);return}if(xt){et(V),Ie(!1),Mt(!0),Ke(null);return}if(Dt){qt.current+=1,Ie(!1),Mt(!1);return}if(!ce)return;let xe=!1;const zt=async()=>{const Yn=++qt.current;Ke(null),Ie(!0);try{const Gn=await Rt.current?.();if(xe||qt.current!==Yn)return;Gn?(et(Gn),Mt(!0)):(et(null),Mt(!1)),Ke(null)}catch(Gn){if(xe||qt.current!==Yn)return;const go=Cn(Gn,"Unable to calculate fees for this action.");et(null),Mt(!1),Ke(go)}finally{!xe&&qt.current===Yn&&Ie(!1)}},fs=window.setTimeout(()=>{zt()},250);return()=>{xe=!0,clearTimeout(fs),Ie(!1)}},[e,_e,Fe,he,xt,V,Dt,ce]);const at=oe(()=>(Jt.current=Date.now(),pr(yt.current)),[]);G(()=>{!v&&Fe==="success"&&sn&&($e(),B?.(sn))},[v,Fe,sn,$e,B]),G(()=>{if(!v||Ge?.status!=="success"||Pt.current||!ee)return;Pt.current=!0;const xe=an.current;!xe?.asset||xe.asset?._source==="wallet"||$e()},[v,Ge?.status,ee,$e]);const bt=ne(B),$t=ne(F);G(()=>{bt.current=B},[B]),G(()=>{$t.current=F},[F]),G(()=>{e&&($e(),lt())},[e,$e,lt]),G(()=>{v&&(Ge?.status==="success"&&bt.current?.(Ge.txHash||""),Ge?.status==="failed"&&$t.current?.(new Error("Payment execution failed")))},[v,Ge?.status]);const gn=oe(()=>{Xt(!1),ye(null),qe(null),Pt.current=!1,$e(),lt()},[$e,lt]);yt.current={selectedAsset:q,parsedAmount:kt,currentPaymentAmount:Qe,isInsufficientBalance:ut,isPayMode:v,isNon7702:pe,isSourceDestToken:tt,needsSwap:rt,exactOutputSwap:le,selectedIsEquivalent:Pe,resolvedTokenIn:dt,embeddedWalletAddress:ze,providerEmbeddedAddress:it,externalWallet:Be,externalWalletAddress:Ue,activeSignerWallet:mt,activeSignerAddress:Vt,address:ee,isConnected:fe,ready:Ce,authenticated:be,provider:Q,resolvedChainId:$,executionTokenAddress:vt,destinationToken:s,buildActionCalls:i,feeExecutionMode:c,buildSpicenetBatch:d,onPayExecute:l,onSuccess:B,onError:F,gasless:{estimateGasless:_,executeGasless:ae,buildPayChainBatches:Je,buildSupplyChainBatches:Z,estimateRequiredGrossFunding:ke,onProgress:He},ui:{setError:gt,setStep:St,setStatusMsg:Le,setTxHash:Me,setIsExecuting:nn,setShowStatusPanel:Xt,setPaymentResult:ye},refs:{spiceDepositSubmittedRef:Pt,abortControllerRef:ln}};const yn=y?.trim(),_t=v&&x==="fixed"&&yn!==void 0&&yn!==""&&kt===0,Fn=v?(_t||!!q?.asset)&&kt>=0&&!mn&&!ut&&!_e&&(_t||xt||Yt)&&!Ct&&(_t||!rt||!!le)&&!kn:!!q?.asset&&kt>0&&!mn&&!ut&&!_e&&(Zt||Yt)&&!Ct&&(re||Et||!!Ut&&!Dt)&&!kn;G(()=>{e&&console.debug("[SpiceSupply] canExecute gates",{canExecute:Fn,isPayMode:v,hasSelectedAsset:!!q?.asset,selectedAsset:q?.asset?{symbol:q.asset.symbol,address:q.asset.address,chainId:q.asset.chainId,balanceFormatted:q.asset.balanceFormatted,source:q.asset?._source}:null,parsedAmount:kt,isZeroAmountPay:_t,isBelowMinimum:mn,isInsufficientBalance:ut,isExecuting:_e,directExternalAction:Zt,directExecutionFeeNote:xt,feeEstimateReady:Yt,feeEstimateError:Ct,needsSwap:rt,isDirect:Et,isSourceDestToken:tt,hasExactOutputSwap:!!le,isQuoting:Dt,whitelistHoldPending:ge,supplyHeldForWhitelist:kn,isWhitelistGateActive:me,destinationToken:{symbol:s.symbol,address:s.address,chainId:s.chainId}})},[e,Fn,v,q,kt,_t,mn,ut,_e,Zt,xt,Yt,Ct,rt,Et,tt,le,Dt,ge,kn,me,s]);const ns=Et?f||`Your ${s.symbol} will be used directly.`:m||"Your assets will be swapped and used in a single atomic transaction.",Te=($?De($):void 0)?.viemChain?.blockExplorers?.default?.url??"",jt=ii.indexOf(Fe),xn=_e?(ai[Fe]||"EXECUTING...").toUpperCase():Fe==="success"?"DONE":mn?`MINIMUM ${Vn}`:ut?"INSUFFICIENT BALANCE":u.toUpperCase(),Bn=te(()=>{if(_e)return"PAYING...";if(mn)return`MINIMUM ${Vn}`;if(ut&&q?.asset)return`INSUFFICIENT ${q.asset.symbol}`;if(u)return u.toUpperCase();const xe=kt>0?` ${Qe} ${s.symbol}`:"";return rt?`SWAP & PAY${xe}`:`PAY${xe}`},[_e,mn,ut,q,u,kt,Qe,s.symbol,rt]),us=Fe==="success"?()=>{St("idle"),qe(null),Me(null),$e()}:Nt,zs=Fe==="success"?!1:!Fn;if(!e)return null;const Ls=v?T||`Pay ${s.symbol}`:u,ps=v?S:g("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[a("span",{style:{marginTop:"3px",flexShrink:0},children:a(Oo,{color:de})}),a("p",{style:{fontSize:"12px",color:de,margin:0,lineHeight:"1.4",fontFamily:j},children:ns})]});if(v){const xe=Ge&&(Ge.status==="success"||Ge.status==="failed")?[{asset:{symbol:q?.asset?.symbol||s.symbol,address:q?.asset?.address||""},amount:Qe,txHash:Ge.txHash||"",success:Ge.status==="success",error:Ge.status==="failed"?Ge.error:void 0}]:void 0;return a(jn,{isOpen:e,onClose:t,title:Ls,subtitle:ps,styles:k,dark:I,footerLinkText:"Spicenet accounts \u2192",closeOnBackdropClick:n,children:g("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[W&&a("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:a(Ho,{onClick:W,color:D,fontFamily:j})}),!_t&&a("div",{style:{marginBottom:"12px"},children:a(Ms,{assets:ft,selectedAsset:q??void 0,onAssetSelect:Ft,onAmountChange:Ad,label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:q?.asset?rt?Dt?"...":le?`~${parseFloat(pt(le.amountIn,q.asset.decimals)).toFixed(6)}`:void 0:Qe??void 0:void 0,dark:I,theme:H,styles:k})}),a(Va,{variant:"pay",destinationSymbol:s.symbol,destinationLogoURI:s.logoURI,destinationDecimals:s.decimals,primaryColor:D,fontFamily:j,textPrimary:P,textSecondary:U,cardBg:O,cardBorder:J,dk:R,dark:I,isQuoting:Dt,quoteError:cn,estimatedOutput:dn,paymentAmount:Qe,needsSwap:rt,exactOutputSwap:le,adjustable:x==="adjustable",maxAmount:b,onAmountChange:Bt}),he&&a(Gs,{fontFamily:j,textPrimary:P,textSecondary:U,cardBg:O,cardBorder:J,resolvedDark:I,darkCardBorder:R.cardBorder,primaryColor:D,feePreview:Ze,isLoading:rn,errorText:Ct,directExecutionFeeNote:xt}),Y&&a(xs,{variant:"error",palette:L,fontFamily:j,style:{marginBottom:"12px"},children:Y}),a(Qt,{variant:"outline",fullWidth:!0,onClick:at,disabled:!Fn,loading:_e,dark:I,styles:{...k,button:{...k?.button,backgroundColor:D}},children:Bn}),Ge&&Gt&&a("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:I?R.shell:"white",borderRadius:I?"12px":"6px",padding:"16px 0"},children:a(Ko,{type:"payment",isOpen:Ge.status!=="processing",isProcessing:_e||Ge.status==="processing",closeOnComplete:!1,chainName:In($),explorerUrl:hs($,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{Xt(!1),ye(null),at()},onNewTx:gn,onClose:()=>{Xt(!1),ye(null)},onComplete:gn,results:xe,styles:k,dark:I})})]})})}return a(jn,{isOpen:e,onClose:t,title:Ls,subtitle:ps,dark:I,styles:k,theme:E,closeOnBackdropClick:n,children:g("div",{style:{padding:"24px 24px 5px 24px",position:"relative"},children:[a("div",{style:{marginBottom:"16px"},children:a(Ms,{assets:ft,selectedAsset:q||void 0,onAssetSelect:Ft,onAmountChange:Wt,disabled:_e||Fe==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:H,styles:k,dark:z,resolveMaxAmount:Oe,maxAmount:Xe>0?ys(Xe,q?.asset.decimals??s.decimals):void 0})}),q?.asset&&!Et&&a(Va,{variant:"supply",destinationSymbol:s.symbol,destinationLogoURI:s.logoURI,destinationDecimals:s.decimals,primaryColor:D,fontFamily:j,textPrimary:P,textSecondary:U,cardBg:O,cardBorder:J,dark:I,isQuoting:Dt,quoteError:cn,estimatedOutput:dn}),he&&a(Gs,{fontFamily:j,textPrimary:P,textSecondary:U,cardBg:O,cardBorder:J,resolvedDark:I,darkCardBorder:R.cardBorder,primaryColor:D,feePreview:Ze,isLoading:rn,errorText:Ct,directExecutionFeeNote:xt}),Fe!=="idle"&&g("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:Fe==="success"?O:Fe==="error"?L.errorBg:O,border:`1px solid ${Fe==="success"?J:Fe==="error"?L.errorBorder:J}`},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[Fe==="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:L.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):Fe==="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:L.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):a(Zn,{size:14,color:D}),a("span",{style:{fontSize:"13px",fontWeight:500,color:Fe==="success"?P:Fe==="error"?L.errorText:P,fontFamily:j,flex:1},children:Fe==="success"?"Deposit confirmed":Fe==="error"?Ht||"Transaction failed":ai[Fe]||Ht}),Fe==="success"&&sn&&a("a",{href:`${Te}/tx/${sn}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:D,fontFamily:j,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),Fe==="error"&&a("button",{onClick:()=>{St("idle"),gt(null),setTimeout(Nt,50)},style:{background:"none",border:"none",fontSize:"12px",color:D,fontFamily:j,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),jt>=0&&Fe!=="success"&&Fe!=="error"&&a("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${U}22`,overflow:"hidden"},children:a("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:D,transformOrigin:"left center",transform:`scaleX(${(jt+1)/ii.length})`,transition:"transform 400ms ease"}})})]}),Ot&&Fe==="idle"&&a(xs,{variant:"error",palette:L,fontFamily:j,style:{marginBottom:"16px"},children:Ot}),a(Qt,{variant:"outline",fullWidth:!0,disabled:zs,onClick:us,theme:E,dark:I,styles:{...k,button:{...k?.button,backgroundColor:D}},style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:N},children:xn})]})})},Sd=e=>a(li,{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}),Ed=({label:e="Export Wallet",style:t,className:n,onExport:s,onError:o})=>{const[r,i]=M(!1),[c,d]=M(!1),{primaryColor:l}=wt(),p=un(en),{isAuthenticated:u}=Wn();let h=null;try{h=ji()}catch{}let m=null,f=null;try{m=Vi(),f=qi()}catch{m=null,f=null}const y=Ai(f),x=oe(async()=>{if(!u){o?.("User is not authenticated. Please log in first.");return}try{if(p?.provider==="dynamic"){if(!m||!y){o?.("Dynamic is not available. Ensure the app is wrapped in a DynamicContextProvider.");return}await m.initExportProcess(!1),s?.();return}if(!h){o?.("Privy is not available. Ensure the app is wrapped in a PrivyProvider.");return}await h.exportWallet(),s?.()}catch(A){const k=A instanceof Error?A.message:"Failed to export wallet";console.error("Export wallet error:",A),o?.(k)}},[y,m,u,o,s,h,p?.provider]),C=!u,b={padding:"10px 20px",borderRadius:"8px",fontFamily:'"IBM Plex Mono", monospace',fontSize:"14px",fontWeight:500,letterSpacing:"0.4px",textTransform:"uppercase",cursor:C?"not-allowed":"pointer",opacity:C?.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:C,className:n,style:b,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 ci(e){const t=un(en),n=Tn(),s=e?.enabled===!1?void 0:n,o=t?.network?{network:t.network,pollIntervalMs:e?.pollIntervalMs,chainIds:e?.chainIds??t.supportedChainIds,discoverWalletBalances:e?.discoverWalletBalances}:void 0;return{...$r(s,o),embeddedWalletAddress:n}}var Fd="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 Bd=({appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,address:r,dk:i,dark:c=!1,showModeToggle:d,isEmbeddedMode:l=!0,onModeToggle:p})=>{const[u,h]=M(!1),m=async()=>{r&&await tl(r)&&(h(!0),setTimeout(()=>h(!1),2e3))},f=t==="active",y=n||(f?"Active":"Inactive"),x=f?"#10b981":"#9ca3af",C=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:Fd,alt:"","aria-hidden":"true",style:{width:"11px",height:"11px",display:"block",...c?{filter:"invert(0.65)"}:{}}})]}),a(Vr,{content:C,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:Vo,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:f?"#ecfdf5":"#f3f4f6",border:c?`1px solid ${i.cardBorder}`:f?"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:f?"#065f46":"#6b7280"},children:y})]})]}),a("div",{style:{fontSize:"28px",fontWeight:700,color:i.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:ms(s)}),o&&a("div",{style:{fontSize:"12px",color:i.textSecondary,marginBottom:"8px"},children:o}),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:Pr(r)}),a("button",{onClick:m,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"})]})]})},Td=wn(Bd),Md=({pendingDeposits:e,onCompleteDeposit:t,dk:n,dark:s=!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((o,r)=>{const i=De(o.chainId)?.displayName||`Chain ${o.chainId}`;return g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:s?n.warningBg:"#fffbeb",border:s?`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:s?n.hoverBg:"#fde68a",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:n.warningText},children:o.tokenSymbol.charAt(0)}),g("div",{children:[g("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:[o.amount," ",o.tokenSymbol]}),g("div",{style:{fontSize:"11px",color:n.warningText},children:["on ",i]})]})]}),a("button",{onClick:()=>t?.(o),style:{padding:"4px 12px",fontSize:"11px",fontWeight:600,backgroundColor:s?n.hoverBg:"#fef3c7",color:s?n.textPrimary:"#92400e",border:s?`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"})]},`${o.tokenAddress}-${o.chainId}-${r}`)})})]}),Rd=wn(Md),Dd=e=>`${e.tokenAddress}-${e.chainId}`,Wd=({spiceAssets:e,loading:t,dk:n,dark:s=!1,canDirectWithdraw:o=!1,onDirectWithdraw:r,directWithdrawState:i})=>{const c={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},d={backgroundColor:n.cardBg,border:s?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return t?g("div",{children:[a("div",{style:c,children:"Idle Balances"}),[1,2].map(l=>a("div",{style:{...d,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},l))]}):e.length===0?g("div",{children:[a("div",{style:c,children:"Idle Balances"}),a("div",{style:{...d,padding:"16px",textAlign:"center",fontSize:"13px",color:s?n.textSecondary:"#9ca3af"},children:"No assets yet. Deposit to get started."})]}):g("div",{children:[a("div",{style:c,children:"Idle Balances"}),a("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((l,p)=>{const u=De(l.chainId),h=l.chainDisplayName||u?.displayName||`Chain ${l.chainId}`,m=l.tokenDisplaySymbol||l.tokenDisplayName||l.tokenSymbol,f=Dd(l),y=o&&l.directWithdraw&&!!r,x=i?.key===f?i:null,C=x?.step==="pending";return g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...d},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[l.logoURI?a("img",{src:l.logoURI,alt:l.tokenSymbol,style:{width:"24px",height:"24px",borderRadius:"50%"}}):a("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:s?n.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:n.textSecondary},children:m.charAt(0)}),g("div",{children:[a("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:m}),a("div",{style:{fontSize:"11px",color:s?n.textSecondary:"#9ca3af"},children:h})]})]}),g("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[g("div",{style:{textAlign:"right"},children:[a("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:_n(l.balanceFormatted)}),a("div",{style:{fontSize:"11px",color:x?.step==="error"?n.errorText:s?n.textSecondary:"#9ca3af"},children:x?.step==="error"?x.message||"Withdraw failed":ms(l.usdValue)})]}),y&&a("button",{onClick:()=>!C&&r(l),disabled:C,title:"Withdraw to external wallet",style:{padding:"6px 10px",borderRadius:"6px",border:s?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",backgroundColor:s?n.hoverBg:"#ffffff",color:n.textPrimary,fontSize:"11px",fontWeight:600,cursor:C?"default":"pointer",opacity:C?.6:1,whiteSpace:"nowrap"},children:C?"Withdrawing\u2026":"Withdraw"})]})]},`${l.tokenAddress}-${l.chainId}-${p}`)})})]})},Nd=wn(Wd),Pd=({section:e,dk:t,dark:n=!1})=>{const s=o=>{switch(o){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((o,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:[o.tokenLogoURI?a("img",{src:o.tokenLogoURI,alt:o.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:o.tokenSymbol.charAt(0)}),g("div",{children:[a("div",{style:{fontSize:"13px",fontWeight:500,color:t.textPrimary},children:o.tokenSymbol}),a("div",{style:{fontSize:"11px",color:t.textSecondary},children:o.label})]})]}),a("div",{style:{fontSize:"13px",fontWeight:600,color:s(o.valueColor)},children:o.displayValue})]},r))})]})},Ud=wn(Pd),zd=({onDepositClick:e,onWithdrawClick:t,depositDisabled:n=!1,withdrawDisabled:s=!1,primaryColor:o="#EA4B4B",dark:r=!1})=>!e&&!t?null:g("div",{style:{display:"flex",gap:"8px"},children:[e&&a(Qt,{variant:"outline",onClick:e,disabled:n,dark:r,styles:{button:{backgroundColor:o}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&a(Qt,{variant:"outline",onClick:t,disabled:s,dark:r,styles:{button:{backgroundColor:o}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),Ld=wn(zd),Od=({appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,address:r,spiceAssets:i,spiceAssetsLoading:c,pendingDeposits:d,customSections:l,notice:p,onDepositClick:u,onWithdrawClick:h,depositDisabled:m,onCompleteDeposit:f,primaryColor:y,dk:x,dark:C=!1,showModeToggle:b,isEmbeddedMode:A,onModeToggle:k,showConnectExternalCta:w,onConnectExternalWallet:T,connectExternalError:S,showHowItWorks:W=!0,canDirectWithdraw:B,onDirectWithdraw:F,directWithdrawState:v})=>{const[E,I]=M(!1);return g("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[a(Td,{appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,address:r,dk:x,dark:C,showModeToggle:b,isEmbeddedMode:A,onModeToggle:k}),p&&a("div",{style:{padding:"10px 12px",borderRadius:"8px",backgroundColor:p.tone==="warning"?C?"rgba(245, 158, 11, 0.12)":"#fffbeb":p.tone==="success"?C?"rgba(16, 185, 129, 0.12)":"#ecfdf5":x.cardBg,border:p.tone==="warning"?C?"1px solid rgba(245, 158, 11, 0.35)":"1px solid #fde68a":p.tone==="success"?C?"1px solid rgba(16, 185, 129, 0.35)":"1px solid #a7f3d0":C?`1px solid ${x.cardBorder}`:"1px solid #e5e7eb",color:p.tone==="warning"?C?"#fbbf24":"#92400e":p.tone==="success"?C?"#34d399":"#047857":x.textSecondary,fontSize:"12px",lineHeight:1.45,fontWeight:500},children:p.message}),w&&g("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[a("button",{onClick:T,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:y||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:'"Helvetica Neue", sans-serif',transition:"opacity 150ms ease"},children:"Connect External Wallet"}),S&&a("span",{style:{fontSize:"11px",color:C?x.errorText:"#b91c1c",lineHeight:1.4},children:S})]}),a("div",{style:{height:"1px",backgroundColor:C?"#2d2d2d":"#e5e7eb"}}),a(Ld,{onDepositClick:u,onWithdrawClick:h,depositDisabled:m,primaryColor:y,dark:C}),W&&g("div",{children:[g("button",{onClick:()=>I(!E),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:x.cardBg,border:C?`1px solid ${x.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:x.textSecondary,fontSize:"12px",fontWeight:500},children:[a("span",{children:"How It Works"}),a("span",{style:{transform:E?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),E&&g("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:C?x.cardBg:"#f0fdf4",border:C?`1px solid ${x.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:C?x.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),a(Rd,{pendingDeposits:d,onCompleteDeposit:f,dk:x,dark:C}),a(Nd,{spiceAssets:i,loading:c,dk:x,dark:C,canDirectWithdraw:B,onDirectWithdraw:F,directWithdrawState:v}),l.map((D,R)=>a(Ud,{section:D,dk:x,dark:C},R))]})},Hd=wn(Od);function jd(e,t,n){const s=t-n.gasBridge-n.spicenetFee;if(s<=0n)throw new Error("Balance is too small to cover the network fee.");const o=[{recipient:e,amount:s}];return n.gasBridge>0n&&o.push({recipient:Mn,amount:n.gasBridge}),n.spicenetFee>0n&&o.push({recipient:rs,amount:n.spicenetFee}),o}function Qd(e,t,n){if(e===t)return!0;const s=e>t?e:t;return s===0n?!1:(e>t?e-t:t-e)*10000n<=s*n}const Vd=new Set([Mn,rs].map(e=>e.toLowerCase()));function qd(e,t){return!e||e.length!==t.length?!1:e.every((n,s)=>{const o=t[s];return n.recipient.toLowerCase()!==o.recipient.toLowerCase()?!1:Vd.has(n.recipient.toLowerCase())?Qd(n.amount,o.amount,100n):!0})}function di(e,t,n){return{chainId:e,domain:"evm",tokenTransfers:[],calls:n.filter(s=>s.amount>0n).map(s=>({to:t,value:0n,data:At({abi:nt,functionName:"transfer",args:[s.recipient,s.amount]})}))}}function Kd(e,t){const n=e.intents.flatMap(o=>o.batches).filter(o=>En(o).totalFee>0n),s=n.filter(o=>o.chainId===t);return(s.length>0?s:n)[0]??null}function Yd(e,t,n,s){const o=Kd(s,e),{gasFee:r,bridgeFee:i,spicenetFee:c}=o?En(o):{gasFee:0n,bridgeFee:0n,spicenetFee:0n};return jd(t,n,{gasBridge:r+i,spicenetFee:c})}function Gd(){const{executeGasless:e}=Cs(),t=Tn(),{embeddedAddress:n}=On(),s=t||n;return{withdraw:oe(async({tokenAddress:o,chainId:r,balance:i,recipient:c,onProgress:d})=>{const l=o,p=c;if(i<=0n)throw new Error("Nothing to withdraw.");const u=[di(r,l,[{recipient:p,amount:i}])];let h=null;return e(u,l,0n,d,void 0,{useCustomTransfers:!0,userOverride:s,adjustBatchesForEstimate:({feeEstimate:m})=>{const f=Yd(r,p,i,m);return qd(h,f)?null:(h=f,[di(r,l,f)])}})},[e,s])}}function Zd(e){return!!e.embeddedAddress&&!!e.externalAddress}const yr=380,ds=8,Xd=[];function ui(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function Jd(e,t){const n=new Map;Object.entries(t).forEach(([o,r])=>{if(!Number.isFinite(r)||r<=0)return;n.set(o,r),n.set(o.toUpperCase(),r);const i=ui(o);i&&n.set(i,r)});const s=[e.symbol,e.displaySymbol,e.receiptTokenName,e.name,e.displayName];for(const o of s){if(!o)continue;const r=n.get(o)??n.get(o.toUpperCase());if(r!==void 0)return r;const i=ui(o);if(!i)continue;const c=n.get(i);if(c!==void 0)return c}return 0}const $d=({appName:e="Spice",status:t="active",statusLabel:n,customSections:s=Xd,extraAssets:o=[],tokenPrices:r={},breakdownLabels:i=[],notice:c,styles:d,dark:l=!1,onDepositSuccess:p,onDepositClick:u,onWithdrawClick:h,onCompleteDeposit:m,showModeToggle:f=!1,defaultMode:y})=>{const x=un(en),C=x?.mode!=="7702",b=!!x?.isWhitelistGateActive,A=!!x?.isWhitelistConfigured&&x?.isUserWhitelisted!==!0,k=ne(!1);G(()=>{if(!k.current){if(Si()){k.current=!0;return}y&&x?.setMode&&(x.setMode(y==="non7702"?"ondemand":"7702"),k.current=!0)}},[x,y]);const[w,T]=M(!1),[S,W]=M(null),[B,F]=M({top:0,bottom:0,left:0,placement:"below"}),v=ne(null),E=ne(null),{address:I,isConnected:D}=Wn(),R=Tn(),{externalAddress:L,embeddedAddress:j}=On(),{dark:N,primaryColor:z,dk:O}=wt(d,l),J=C&&!L,P=!C||J,U=P?R||j:I,de=te(()=>x?.supportedChainIds??js("mainnet"),[x?.supportedChainIds]),{assets:H,loading:$}=Ds({address:U,supportedChains:de,enabled:!!U&&P,refetchInterval:3e4}),ue=te(()=>{const q=P?H.map(Se=>{const ot=Se.balanceUsd||0,_e=Number.isFinite(Se.balanceFormatted)?Se.balanceFormatted:0,nn=ot>0?ot:Jd(Se,r)*_e;return{tokenAddress:Se.address,tokenSymbol:Se.symbol,tokenDisplaySymbol:Po(Se),tokenDisplayName:il(Se),tokenDecimals:Se.decimals,chainId:Se.chainId,chainDisplayName:Uo(Se),balance:Se.balance.toString(),balanceFormatted:Se.balanceFormatted,usdValue:nn,logoURI:Se.logoURI}}):[],qe=J?[]:o;return[...q,...qe].filter(Se=>Se.balanceFormatted>0)},[P,J,H,r,o]),ve=te(()=>ue.reduce((q,qe)=>q+qe.usdValue,0),[ue]),{pendingDeposits:pe}=ci({chainIds:de,enabled:!!I,discoverWalletBalances:!0}),me=te(()=>s.reduce((q,qe)=>q+qe.totalValue,0),[s]),ge=ve+me,K=te(()=>{const q=[];ve>0&&q.push(`${ms(ve)} idle`);for(const qe of s){const Se=i.find(ot=>ot.sectionTitle===qe.title)?.label||qe.title.toLowerCase();q.push(`${ms(qe.totalValue)} ${Se}`)}return q.join(" \xB7 ")},[ve,s,i]),ie=oe(q=>{m?m(q):W(q)},[m]),X=oe(()=>{W(null)},[]),ee=oe(()=>{W(null),p?.()},[p]),fe=oe(()=>{if(!v.current)return;const q=v.current.getBoundingClientRect(),qe=window.innerHeight-q.bottom-ds,Se=q.top-ds,ot=qe>=400||qe>=Se?"below":"above",_e=Math.max(ds,Math.min(q.right-yr,window.innerWidth-yr-ds)),nn=ot==="below"?q.bottom+ds:q.top-ds,Ot=ot==="above"?window.innerHeight-nn:0;F({top:nn,bottom:Ot,left:_e,placement:ot})},[]);Cr(()=>{w&&fe()},[w,fe]),G(()=>{if(!w)return;const q=ot=>{v.current&&!v.current.contains(ot.target)&&E.current&&!E.current.contains(ot.target)&&T(!1)},qe=ot=>{ot.key==="Escape"&&T(!1)},Se=()=>fe();return document.addEventListener("mousedown",q),document.addEventListener("keydown",qe),window.addEventListener("scroll",Se,{passive:!0}),window.addEventListener("resize",fe),()=>{document.removeEventListener("mousedown",q),document.removeEventListener("keydown",qe),window.removeEventListener("scroll",Se),window.removeEventListener("resize",fe)}},[w,fe]);const Ce=P?R||j||I:L||I,be=oe(()=>{x?.setMode&&x.setMode(P?"ondemand":"7702")},[x,P]),[Q,ae]=M(null);let _=null;try{_=Tr({onSuccess:()=>ae(null),onError:q=>ae(Cn(q,"Failed to connect wallet."))}).connectWallet}catch{_=null}const Be=oe(()=>{_&&(T(!1),ae(null),_({walletChainType:"ethereum-only"}))},[_]),Ue=!L&&!!_,it=oe(()=>{T(!1),u?.()},[u]),mt=oe(()=>{T(!1),h?.()},[h]),Vt=oe(q=>{T(!1),ie(q)},[ie]),{withdraw:st}=Gd(),[we,We]=M(null),ze=Zd({embeddedAddress:R||j,externalAddress:L}),$e=oe(async q=>{if(!L)return;const qe=`${q.tokenAddress}-${q.chainId}`;We({key:qe,step:"pending"});try{await st({tokenAddress:q.tokenAddress,chainId:q.chainId,balance:BigInt(q.balance),recipient:L}),We(null)}catch(Se){We({key:qe,step:"error",message:Cn(Se,"Withdraw failed")})}},[st,L]);if(typeof window>"u")return null;const lt=g("button",{ref:v,onClick:()=>T(!w),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:N?O.hoverBg:"#ffffff",border:N?`1px solid ${O.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:'"Helvetica Neue", sans-serif',color:N?O.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:N?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[g("span",{children:[e," Account"]}),D&&g("span",{style:{color:N?O.textSecondary:"#6b7280"},children:["\xB7 ",ms(ge)]}),a("span",{style:{fontSize:"10px",color:N?O.textSecondary:"#9ca3af",transform:w?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),ft=w?Mr.createPortal(g(bn,{children:[a("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:$n.popover},onClick:()=>T(!1)}),a("div",{ref:E,style:{position:"fixed",top:B.placement==="below"?`${B.top}px`:"auto",bottom:B.placement==="above"?`${B.bottom}px`:"auto",left:`${B.left}px`,width:`${yr}px`,maxWidth:`calc(100vw - ${ds*2}px)`,maxHeight:"80vh",backgroundColor:N?O.shell:"#ffffff",border:N?`1px solid ${O.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:N?"0 10px 40px rgba(0, 0, 0, 0.5)":"0 10px 40px rgba(0, 0, 0, 0.12)",zIndex:$n.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${tn.out}`},children:a(Hd,{appName:e,status:t,statusLabel:n,totalUsdValue:ge,breakdownSubtitle:K,address:P?Ce:I,spiceAssets:ue,spiceAssetsLoading:$,pendingDeposits:pe,customSections:s,notice:c,onDepositClick:u?it:void 0,onWithdrawClick:h?mt:void 0,depositDisabled:A,onCompleteDeposit:Vt,primaryColor:z,dk:O,dark:N,showModeToggle:f,isEmbeddedMode:P,onModeToggle:be,showConnectExternalCta:Ue,onConnectExternalWallet:Be,connectExternalError:Q,showHowItWorks:!b,canDirectWithdraw:ze,onDirectWithdraw:$e,directWithdrawState:we})}),a("style",{children:`
|
|
104
104
|
@keyframes accountDisplayFadeIn {
|
|
105
105
|
from { opacity: 0; transform: translateY(-4px); }
|
|
106
106
|
to { opacity: 1; transform: translateY(0); }
|