@spicenet-io/spiceflow-ui 4.8.2-native.0 → 4.8.2-native.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/auth-privy.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{P as g}from"./privy-
|
|
2
|
+
import{P as g}from"./privy-CJGfIh5H.js";import"react/jsx-runtime";import"react";import"@spicenet-io/spiceflow-core";import"viem";import"viem/actions";import"@privy-io/react-auth";import"wagmi";import"@tanstack/react-query";export{g as PrivyLogin};
|
package/dist/index.cjs.js
CHANGED
|
@@ -77,7 +77,7 @@
|
|
|
77
77
|
from { transform: rotate(0deg); }
|
|
78
78
|
to { transform: rotate(360deg); }
|
|
79
79
|
}
|
|
80
|
-
`})]})};function Dc(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const s=E.getAddress(n.token),o=E.getAddress(n.to),a=`${s.toLowerCase()}:${o.toLowerCase()}`,i=t.get(a);i?i.amount+=n.amount:t.set(a,{token:s,to:o,amount:n.amount})}return[...t.values()]}function Mc(e,t){return`0x${t}${e.slice(4)}`}function Br(e,t){return Tr(e,t)}function Tr(e,t,n){const s=Qn(t,e),o=Math.floor(Date.now()/1e3)+60*10,a=A.hashChainBatches(s);return{user:e,...n?{chainAuthorizations:n}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:"0x00",nbf:0,exp:o,chainBatches:a.map((i,l)=>({hash:i.hash,chainId:i.chainId,tokenTransfers:s[l].domain==="spicenet"?[]:s[l].tokenTransfers??[],calls:i.calls}))}]}}function cn(e,t,n,s){if(e.some(m=>m.domain==="spicenet"))return e;const o=n?.intents.flatMap(m=>m.batches),a=m=>m.from==="escrow",i=e.map(m=>{const f=o?.find(I=>I.chainId===m.chainId);if(!f)return m;const h=Dt(f),x=h.totalFee;if(x<=0n)return m;const g=(m.tokenTransfers??[]).filter(I=>a(I)&&E.getAddress(I.to).toLowerCase()===t.toLowerCase()),y=g.find(I=>!A.isNativeToken(E.getAddress(I.token)))??g[0];if(!y)return m;const C=E.getAddress(y.token),v=A.isNativeToken(C);let b=!1;const M=(m.tokenTransfers??[]).map(I=>b||!a(I)||E.getAddress(I.to).toLowerCase()!==t.toLowerCase()||E.getAddress(I.token).toLowerCase()!==C.toLowerCase()?I:(b=!0,{...I,amount:s?.payoutAlreadyGross?BigInt(I.amount):BigInt(I.amount)+x}));if(!b)return m;const w=(I,D)=>v?{to:I,value:D,data:"0x"}:{to:C,value:0n,data:E.encodeFunctionData({abi:E.erc20Abi,functionName:"transfer",args:[I,D]})},k=[];h.spicenetFee>0n&&k.push(w(A.SPICE_PLATFORM_FEE_RECIPIENT,h.spicenetFee));const j=h.gasFee+h.bridgeFee;return j>0n&&k.push(w(A.SPICE_GAS_FEE_RECIPIENT,j)),{...m,tokenTransfers:M,calls:[...k,...m.calls]}}),l=i.flatMap(m=>(m.tokenTransfers??[]).filter(a).map(f=>{const h=E.getAddress(f.token),x=E.getAddress(f.to),g=[{token:h,to:x,amount:BigInt(f.amount)}];return{chainId:m.chainId,transfers:Dc(g)}}));if(l.length===0)return e;const u=s?.requestTimestampMs??Date.now(),d=BigInt(Math.floor(u/1e3))+3600n;return[{chainId:A.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:l.map((m,f)=>{const h=E.keccak256(E.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,m.transfers[0].token,m.transfers.reduce((g,y)=>g+y.amount,0n),BigInt(m.chainId),BigInt(u+f)])),x=Mc(h,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:E.encodeFunctionData({abi:A.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${m.chainId}`,idempotenceKey:x,nbf:0n,exp:d,metadata:"{}",transfers:m.transfers.map(g=>({token:g.token.toLowerCase(),to:g.to,amount:g.amount}))}]})}})},...i]}const Nc=60*60,Rr=(e,t)=>!!e&&e.grossAmount===t.grossAmount&&e.netAmount===t.netAmount&&e.feeAmount===t.feeAmount;function ts(e,t){return t?e.some(n=>(n.tokenTransfers??[]).some(s=>s.from==="escrow"&&BigInt(s.amount)>=t.grossAmount)):!1}function Dr(e){return!e.isSemi7702&&e.isDirectDeposit&&!e.isSourceDestToken}function Mr(e){const t=e.selectedAsset?.asset,n=e.selectedAsset?.amount;if(!(!t||!n))return E.parseUnits(n,t.decimals)}async function ns({user:e,batches:t,authorizations:n,adjustBatchesForEstimate:s}){let o=t;for(let a=0;a<10;a+=1){const i=await p.relayerService.estimateActionFees(Tr(e,o,n)),l=await s({feeEstimate:i,batches:o});if(!l||Vo(o,l))return o;o=l}throw new Error("Fee estimate did not converge. Please retry.")}function Wc(e){return{chainId:e.sourceChainId,calls:e.isNative?[{to:e.target,value:e.amount,data:"0x"}]:[{to:e.tokenAddr,value:0n,data:E.encodeFunctionData({abi:E.erc20Abi,functionName:"transfer",args:[e.target,e.amount]})}]}}function Js(e,t,n,s){const o=e.selectedAsset.asset,a=E.parseUnits(e.selectedAsset.amount,o.decimals),i=o.chainId,l=e.escrowAddress||A.getEscrowContractAddress(i),u=A.normalizeNativeTokenAddress(o.address),d=o.isNative||A.isNativeToken(u),m=n.some(f=>f.tokenTransfers?.some(h=>h.from==="escrow"));return{asset:o,userNetAmountWei:a,sourceChainId:i,tokenAddr:u,isNative:d,hasEscrowBackedPayout:m,composeBatches:(f,h,x,g)=>{const y=Wc({sourceChainId:i,target:l,tokenAddr:u,isNative:d,amount:f});if(!m)return[y,...h];const C=cn([...h],t,x,{payoutAlreadyGross:ts(h,g),...s!==void 0?{requestTimestampMs:s}:{}});return[y,...C]}}}function $s(e){const t={};return{state:t,adjustBatchesForEstimate:({feeEstimate:n})=>{const s=Ms(n,{symbol:e.symbol,decimals:e.decimals,actionAmount:e.actionAmount});if(!s)return null;t.plan={grossAmount:s.grossAmount,netAmount:s.netAmount,feeAmount:s.totalFee??0n};const o=sn(e.ctx,t.plan);return e.rebuild(o,n,t.plan)}}}function sn(e,t){const n=e.selectedAsset?.asset;if(!n||!e.selectedAsset?.amount)throw new Error("Select an asset and enter an amount");const s=E.parseUnits(e.selectedAsset.amount,n.decimals),o=t?.grossAmount??s;return e.resolveLockBatches({amount:e.selectedAsset.amount,amountWei:s,grossAmount:E.formatUnits(o,n.decimals),grossAmountWei:o})}async function _s(e,t,n){const s=e.isSemi7702&&e.embeddedWalletAddress||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 Fn({chainBatches:t,signingAddress:s,actions:e.actions}),a=A.hashChainBatches(t),i=Math.floor(Date.now()/1e3)+Nc,l={mode:"7702",signatureType:"ecdsa",signature:await Ko(e.actions,t,BigInt(i)),nbf:0,exp:i,chainBatches:a.map((d,m)=>{const f=t[m],h=f.domain==="spicenet";return{hash:d.hash,chainId:d.chainId,tokenTransfers:h?[]:f.tokenTransfers??[],calls:d.calls}})},u=await p.relayerService.createAction({user:s,chainAuthorizations:o,intents:[l]});if(u){const d=p.createInitialSteps(t,p.getChainName),[m,f]=u.intentIds[0].split("/"),h=parseInt(f||"0",10),x=u.intentIds[0];e.beginStatusTracking(u.intentIds[0],d),await Ho({actionId:m,intentIndex:h,intentId:x,totalSteps:t.length,isSpicenetStep:g=>t[g]?.domain==="spicenet",maxExecuteAttemptsForStep:g=>t[g]?.domain==="spicenet"?6:3,onStepUpdate:e.applyStepUpdate,maxPolls:72})}}function eo(e,t){const n=e.feeQuote;return n?t.adjustBatchesForEstimate({feeEstimate:n.feeEstimate,batches:[]}):null}async function Oc(e){const t=sn(e);if(t.length===0)throw new Error("No lock batches configured");const n=e.isSemi7702&&e.embeddedWalletAddress||e.address;if(!e.isConnected||!n)throw new Error("Please connect your wallet to continue");const s=await Fn({chainBatches:t,signingAddress:n,actions:e.actions}),o=Date.now(),a=$s({ctx:e,actionAmount:Mr(e),symbol:e.selectedAsset?.asset.symbol??"",decimals:e.selectedAsset?.asset.decimals??18,rebuild:(l,u,d)=>cn([...l],n,u,{payoutAlreadyGross:ts(l,d),requestTimestampMs:o})});let i=eo(e,a)??cn([...t],n,void 0,{requestTimestampMs:o});i=await ns({user:n,batches:i,authorizations:s,adjustBatchesForEstimate:a.adjustBatchesForEstimate}),await _s(e,i,s)}async function Pc(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");const t=e.embeddedWalletAddress||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=Js(e,t,n,Date.now()),o=$s({ctx:e,actionAmount:s.userNetAmountWei,symbol:s.asset.symbol,decimals:s.asset.decimals,rebuild:(l,u,d)=>s.composeBatches(d.grossAmount,l,u,d)});let a=eo(e,o)??s.composeBatches(s.userNetAmountWei,sn(e));const i=await Fn({chainBatches:a,signingAddress:t,actions:e.actions});s.hasEscrowBackedPayout&&(a=await ns({user:t,batches:a,authorizations:i,adjustBatchesForEstimate:o.adjustBatchesForEstimate})),await _s(e,a,i)}async function Uc(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;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");if(e.onLockExecute){const g=e.resolveLockBatches();if(g.length===0)throw new Error("No lock batches configured");const y=e.selectedAsset.asset,C=E.parseUnits(e.selectedAsset.amount,y.decimals),v=await e.onLockExecute({asset:y,amount:e.selectedAsset.amount,amountWei:C,lockDurationMonths:e.selectedDuration?.months??0,chainBatches:g});v&&e.onLockSuccess?.(v);return}const n=e.resolveLockBatches();if(n.length===0)throw new Error("No lock batches configured");const s=Js(e,t,n,Date.now()),{userNetAmountWei:o}=s,a=$s({ctx:e,actionAmount:o,symbol:s.asset.symbol,decimals:s.asset.decimals,rebuild:(g,y,C)=>s.composeBatches(C.grossAmount,g,y,C)});let i=eo(e,a)??s.composeBatches(o,sn(e));const l=await Fn({chainBatches:i,signingAddress:t,actions:e.actions});s.hasEscrowBackedPayout&&(i=await ns({user:t,batches:i,authorizations:l,adjustBatchesForEstimate:a.adjustBatchesForEstimate}));const u=a.state.plan?.grossAmount??o,{extWc:d,viemChain:m}=await yn({wallet:e.externalWallet,account:e.externalWalletAddress,chainId:s.sourceChainId}),f=p.getClientForChain(s.sourceChainId),h=g=>Hs({extWc:d,sourceClient:f,recipient:t,tokenAddr:s.tokenAddr,isNative:s.isNative,amount:g,viemChain:m});await h(u);let x=u;if(s.hasEscrowBackedPayout)for(let g=0;g<4;g+=1){i=await ns({user:t,batches:i,authorizations:l,adjustBatchesForEstimate:a.adjustBatchesForEstimate});const y=a.state.plan?.grossAmount??o;if(y<=x)break;await h(y-x),x=y}await _s(e,i,l)}async function zc(e,t){if(!e.selectedAsset?.asset||!e.selectedAsset.amount||!e.requiresRelayerFeeEstimate)return null;if(e.isSemi7702||Dr(e)){const u=e.embeddedWalletAddress||e.address;if(!u)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");const d=e.feeQuote;let m=sn(e,d?.plan);if(m.length===0)throw new Error("No lock batches configured");const f=Js(e,u,m),{asset:h,userNetAmountWei:x}=f;let g=d?f.composeBatches(d.plan.grossAmount,m,d.feeEstimate,d.plan):f.composeBatches(x,m,void 0,{grossAmount:x,netAmount:0n,feeAmount:0n}),y=null,C=d?.plan;for(let v=0;v<4;v+=1){const b=await p.relayerService.estimateActionFees(Br(u,g),{signal:t}),M=Ms(b,{symbol:h.symbol,decimals:h.decimals,actionAmount:x});if(!M)return y;const w={grossAmount:M.grossAmount,netAmount:M.netAmount,feeAmount:M.totalFee??0n},k=Rr(C,w);if(y={preview:M,feeEstimate:b,plan:w},C=w,m=sn(e,w),g=f.composeBatches(w.grossAmount,m,b,w),k)break}return y}const n=e.address;if(!e.isConnected||!n)throw new Error("Please connect your wallet to continue");const s=e.feeQuote;let o=sn(e,s?.plan);if(o.length===0)throw new Error("No lock batches configured");let a=cn([...o],n,s?.feeEstimate,s?{payoutAlreadyGross:ts(o,s.plan)}:void 0),i=null,l=s?.plan;for(let u=0;u<4;u+=1){const d=await p.relayerService.estimateActionFees(Br(n,a),{signal:t}),m=Ms(d,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:Mr(e)});if(!m)return null;const f={grossAmount:m.grossAmount,netAmount:m.netAmount,feeAmount:m.totalFee??0n},h=Rr(l,f);if(i={preview:m,feeEstimate:d,plan:f},l=f,o=sn(e,f),a=cn([...o],n,d,{payoutAlreadyGross:ts(o,f)}),h)break}return i}async function Lc(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(d=>d.chainId===e.lockChainId)||s[0];if(!o)throw new Error("No lock batch for lock chain");const{extWc:a,viemChain:i}=await yn({wallet:t,account:n,chainId:e.lockChainId}),l=p.getClientForChain(e.lockChainId),u=await tr({extWc:a,client:l,calls:o.calls,viemChain:i,errorMessage:"Lock transaction failed"});u&&e.onLockSuccess?.(u)}async function Hc(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("[SpiceLock] lock failed:",n);const s=p.sanitizeError(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 Lc(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{await Uc(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{Dr(e)?await Pc(e):await Oc(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}}const Vc=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,lockBatches:s,lockTokenSymbol:o,lockTokenLogoURI:a,destinationInputHook:i,sourceAssetInputHook:l,lockDurationHook:u,lockChainId:d,durationOptions:m,votingPowerEstimate:f,escrowAddress:h,includeWalletAssets:x=!1,destinationTokenAddress:g,onLockSuccess:y,onLockError:C,onLockExecute:v,sourceToDestinationConversionRate:b,onAddFunds:M,buildSpicenetBatch:w,styles:k,dark:j=!1})=>{const{theme:I,dark:D,primaryColor:B,dk:S}=p.useSpiceBrand(k,j),R=I.typography.fontFamily,F=c.useContext(p.SpiceFlowProviderContext),T=F?.mode||"7702",K=!!F?.isWhitelistGateActive,N=T!=="7702",W=c.useMemo(()=>F?.supportedChainIds??[],[F?.supportedChainIds]),P=c.useMemo(()=>{if(K)return[];const $=F?.allowedTokens;if(!$||$.length===0)return[];const ke=new Set($.map(Te=>Te.toLowerCase())),Je=[],Ke=new Set;for(const Te of W){const Bt=p.getChainConfig(Te);for(const Oe of Bt?.supportedTokens??[]){if(!ke.has(Oe.symbol.toLowerCase()))continue;const Ne=`${Te}:${Oe.address.toLowerCase()}`;Ke.has(Ne)||(Ke.add(Ne),Je.push(E.getAddress(Oe.address)))}}return Je},[F?.allowedTokens,W,K]),O=D?S.cardBg:k?.assetSelector?.backgroundColor||k?.secondaryBackground||"#e9e9e9",L=D?`1px solid ${S.cardBorder}`:"0.5px solid #A8A8A7",U=D?"12px":"6px",Z=D?S.textPrimary:"#111827",X=D?S.textSecondary:"#6b7280",V=c.useMemo(()=>({...k,assetSelector:{...k?.assetSelector,backgroundColor:D?S.cardBg:k?.assetSelector?.backgroundColor,borderRadius:D?"12px":k?.assetSelector?.borderRadius},secondaryBackground:D?S.cardBg:k?.secondaryBackground}),[k,D]),ee=c.useMemo(()=>D?{...I,colors:{...I.colors,secondary:S.cardBg,surfaceHover:S.hoverBg,border:S.cardBorder,borderHover:S.inputBorder}}:I,[D,I]),[H,q]=c.useState(null),[ie,pe]=c.useState(0),_=u?.selectedDurationIdx??ie,ve=u?.setSelectedDurationIdx??pe,[xe,ue]=c.useState(!1),[We,z]=c.useState(null),fe=c.useRef(C);fe.current=C;const le=c.useCallback($=>{z($),typeof $=="string"&&$&&fe.current?.($,p.getRelayerErrorDetail($))},[]),[te,Q]=c.useState(null),[se,me]=c.useState(!1),[J,he]=c.useState(!1),[Ue,Re]=c.useState(null),[kt,vt]=c.useState(!1),[et,ut]=c.useState(!1),[Ee,Ve]=c.useState(null),rt=p.useWallet(),{isReady:at,isAuthenticated:re,isConnected:pt,address:ye,provider:Fe,actions:Ce}=rt,{externalWallet:Be,activeWallet:ft,activeAddress:yt}=p.useProviderWallets(),{intentStatus:De,beginStatusTracking:St,applyStepUpdate:Le,clearStatus:it}=gn(),{assets:Mt,refetch:qe}=Bn({address:ye,supportedChains:W,enabled:e&&pt&&!N&&!K,refetchInterval:3e4}),tt=c.useMemo(()=>{if(K)return[];if(P.length===0)return Mt;const $=new Set(P.map(ke=>ke.toLowerCase()));return Mt.filter(ke=>$.has(ke.address.toLowerCase()))},[Mt,P,K]),It=F?.embeddedWalletAddress,Tt=F?.externalWalletAddress,we=N?yt??Tt:It,{walletAssets:Ie,refreshWalletAssets:_e}=Ec({isOpen:e,includeWalletAssets:x,isWhitelistGateActive:K,isSemi7702:N,destinationTokenAddress:g,sourceAssets:P,sourceChains:W,walletAddressForAssets:we,lockChainId:d,lockTokenSymbol:o,lockTokenLogoURI:a}),de=c.useMemo(()=>Ie.filter($=>$.balance>0n),[Ie]),ce=c.useMemo(()=>{if(N)return de.map(ke=>({...ke,_source:"wallet"}));if(!x)return tt;const $=[];for(const ke of de)$.push({...ke,_source:"wallet"});for(const ke of tt)$.push({...ke,_source:"spice"});return $},[N,x,de,tt]),Ze=c.useMemo(()=>K?g?ce.filter($=>p.addressesEqual($.address,g)&&$.chainId===d):[]:ce,[ce,K,g,d]),He=c.useRef(null),lt=c.useRef(null);c.useEffect(()=>{lt.current=H},[H]),c.useEffect(()=>{!K||!H?.asset||g&&p.addressesEqual(H.asset.address,g)&&H.asset.chainId===d||q(null)},[K,H?.asset,g,d]),c.useEffect(()=>{e||(q(null),le(null),Q(null),me(!1),he(!1),Re(null),ue(!1),ut(!1),Ve(null),vt(!1),it())},[e,it]),c.useEffect(()=>{i&&i.assetAmount!==(H?.amount||"")&&q($=>$&&{...$,amount:i.assetAmount})},[i?.assetAmount]),c.useEffect(()=>{l&&l.assetAmount!==(H?.amount||"")&&q($=>$&&{...$,amount:l.assetAmount})},[l?.assetAmount]),c.useEffect(()=>{if(!N&&De?.overallStatus==="success"&&De.intentId&&He.current!==De.intentId&&ye&&De.steps.find($=>$.transactionHash)?.transactionHash){He.current=De.intentId;const $=lt.current;if(!$?.asset||!$.amount||$.asset._source==="wallet"||E.parseUnits($.amount,$.asset.decimals)===0n)return;qe()}},[De,ye,d,qe,N]);const Se=parseFloat(H?.amount||"")||0,nt=c.useMemo(()=>H?.asset?H.asset._source==="wallet"?H.asset.balanceFormatted??0:tt.find($=>p.addressesEqual($.address,H.asset.address)&&$.chainId===H.asset.chainId)?.balanceFormatted??0:0,[H?.asset,tt]),ze=Se>0&&(Ue?parseFloat(E.formatUnits(Ue.grossAmount,Ue.decimals))>nt:Se>nt),Ge=u?.selectedDuration??m[_]??m[0],Me=c.useMemo(()=>!H?.asset||!g?!1:p.addressesEqual(H.asset.address,g)&&H.asset.chainId===d,[H?.asset,g,d]),ct=c.useMemo(()=>Se<=0?0:Me?Se:!b||b<=0?0:Se/b,[Se,b,Me]),mt=c.useMemo(()=>ct<=0?null:ct.toLocaleString(void 0,{maximumFractionDigits:2}),[ct]),Ut=f&&ct>0&&Ge?f(ct,Ge.months):void 0,jt=c.useMemo(()=>Se<=0?"$0.00":Me&&b?(Se*b).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!b||b<=0?"$0.00":Se.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[Se,b,Me]),Wt=c.useMemo(()=>{if(!mt)return null;const $=parseFloat(mt.replace(/,/g,""));return Me&&b?($*b).toLocaleString(void 0,{maximumFractionDigits:2}):b?($*b).toLocaleString(void 0,{maximumFractionDigits:2}):null},[mt,b,Me]),Pe=c.useCallback($=>{q(ke=>({asset:$,amount:ke?.asset?.address===$.address&&ke?.asset?.chainId===$.chainId&&ke.amount||""})),le(null),Q(null),he(!1),Re(null),l?.setSelectedAsset&&l.setSelectedAsset({symbol:$.symbol,address:$.address,decimals:$.decimals,chainId:$.chainId})},[l?.setSelectedAsset]),At=c.useCallback($=>{q(ke=>ke&&{...ke,amount:$}),le(null),Q(null),he(!1),Re(null),i&&i.setAssetAmount($),l&&l.setAssetAmount($)},[i,l]),Qe=c.useCallback($=>{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:$?.amount??H.amount,amountWei:$?.amountWei??E.parseUnits(H.amount,H.asset.decimals),grossAmount:$?.grossAmount,grossAmountWei:$?.grossAmountWei,feeAdjusted:!!$})}return s},[s,H]),gt=c.useRef(null),ht=c.useMemo(()=>!H?.asset||Se<=0?!1:N?!Me&&!v:!0,[H,Se,N,Me,v]),Ct=c.useCallback($=>zc(gt.current,$),[]),Xe=c.useRef(null),bt=c.useMemo(()=>!H?.asset||Se<=0?null:`${H.asset.address.toLowerCase()}:${H.asset.chainId}:${H.amount??""}`,[H?.asset?.address,H?.asset?.chainId,H?.amount,Se]);zn({shouldRun:e&&!xe&&!!H?.asset&&Se>0&&ht,deps:[e,xe,bt,ht,Ct],delayMs:500,backgroundIntervalMs:3e4,onSkip:()=>{if(!(!e||xe)){if(!H?.asset||Se<=0){Q(null),me(!1),he(!1),Re(null);return}Q(null),me(!1),he(!0),Re(null)}},run:async({isBackground:$,isCurrent:ke,signal:Je})=>{const Ke=bt;$||(Q(null),he(!1),me(!0));try{const Te=await Ct(Je);if(!ke())return;Xe.current=Te&&Ke?{key:Ke,quote:Te}:null,Q(null),he(!0),Re(Te?.preview??null)}catch(Te){if(!ke())return;$||(Q(p.sanitizeError(Te,"Unable to calculate fees for this lock.")),he(!1))}finally{ke()&&!$&&me(!1)}}}),c.useEffect(()=>{if(De?.overallStatus==="success"){const $=De.steps.find(ke=>ke.transactionHash);y?.($?.transactionHash)}},[De?.overallStatus,y]);const xt=x&&H?.asset?._source==="wallet"&&H?.asset?.chainId===d,dt=c.useCallback(()=>Hc(gt.current),[]),G=!!H?.asset&&Se>0&&!ze&&!xe&&(!ht||J&&!se&&!te),ne=We||te,oe=r.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[r.jsx(Ps,{color:X}),r.jsxs("p",{style:{fontSize:"13px",color:X,margin:0,lineHeight:"1.5"},children:["Add ",o," by converting assets from your account"]})]});if(gt.current={selectedAsset:H,parsedAmount:Se,selectedDuration:Ge,isInsufficientBalance:ze,isSemi7702:N,isSourceDestToken:Me,isDirectDeposit:xt,requiresRelayerFeeEstimate:ht,address:ye,embeddedWalletAddress:It,externalWallet:Be,externalWalletAddress:Tt,activeSignerWallet:ft,activeSignerAddress:yt,isConnected:pt,ready:at,authenticated:re,provider:Fe,actions:Ce,lockChainId:d,escrowAddress:h,onLockExecute:v,onLockSuccess:y,buildSpicenetBatch:w,resolveLockBatches:Qe,beginStatusTracking:St,applyStepUpdate:Le,refreshSpiceAssets:qe,refreshWalletAssets:_e,feeQuote:bt&&Xe.current?.key===bt?Xe.current.quote:null,ui:{setError:le,setIsExecuting:ue,setShowStatusPanel:vt}},!e)return null;const je={backgroundColor:O,border:L,borderRadius:U,padding:"16px",marginBottom:"16px"};return r.jsx(Pt,{isOpen:e,onClose:t,title:`Add ${o} to your account`,subtitle:oe,styles:k,dark:D,footerLinkText:"Spicenet accounts \u2192",overlayContent:et?r.jsx("div",{}):void 0,closeOnBackdropClick:n,children:r.jsxs("div",{style:{padding:"0 24px 8px 24px",position:"relative"},children:[r.jsxs("div",{style:{marginBottom:"12px"},children:[M&&r.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:r.jsx(Ls,{onClick:M,color:B,fontFamily:R})}),r.jsx("div",{style:{marginTop:"10px",fontSize:"13px",color:X,fontFamily:R},children:r.jsx(In,{assets:Ze,selectedAsset:H??void 0,onAssetSelect:Pe,onAmountChange:At,label:"Amount",showBalance:!0,showMaxButton:!0,theme:ee,styles:V})}),r.jsx("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:X,fontFamily:R},children:jt})]}),r.jsxs("div",{style:je,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:D?`1px solid ${S.cardBorder}`:"1px solid #e5e7eb"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[a?r.jsx("img",{src:a,alt:o,style:{width:"32px",height:"32px",borderRadius:"50%",objectFit:"cover"}}):r.jsx("div",{style:{width:"32px",height:"32px",borderRadius:"50%",backgroundColor:D?S.inputBg:"#d1d5db",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:700,color:Z},children:o.slice(0,2)}),r.jsx("span",{style:{fontSize:"16px",fontWeight:600,color:Z,fontFamily:R},children:o})]}),r.jsxs("div",{style:{textAlign:"right"},children:[r.jsx("div",{style:{fontSize:"22px",fontWeight:700,color:Z,fontFamily:R,lineHeight:1.1},children:mt??"0.00"}),r.jsxs("div",{style:{fontSize:"12px",color:X,fontFamily:R,marginTop:"2px"},children:["~$",Wt??"0.00"]})]})]}),r.jsxs("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:D?`1px solid ${S.cardBorder}`:"1px solid #e5e7eb"},children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[r.jsx("span",{style:{fontSize:"15px",fontWeight:500,color:X,fontFamily:R},children:"Lock Duration"}),r.jsx(on,{color:X})]}),r.jsx(jc,{options:m,selectedIndex:_,onSelect:ve,primaryColor:B,dark:D,textPrimary:Z,textSecondary:X})]}),r.jsxs("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[r.jsx(jr,{label:"Estimated Lock Expiry",value:Ge?.months!==void 0?Bc(Ge.months):"\u2014",fontFamily:R,dark:D,textPrimary:Z,textSecondary:X}),f&&r.jsx(jr,{label:"Estimated voting power",value:Ut!==void 0?`${Ut} votes/epoch`:"\u2014",fontFamily:R,dark:D,textPrimary:Z,textSecondary:X})]})]}),ht&&r.jsx(zs,{fontFamily:R,textPrimary:Z,textSecondary:X,cardBg:O,cardBorder:L,resolvedDark:D,darkCardBorder:S.cardBorder,primaryColor:B,feePreview:Ue,isLoading:se,errorText:te}),ne&&r.jsx(ln,{variant:"error",palette:S,fontFamily:R,style:{marginBottom:"12px"},children:ne}),r.jsx(p.Button,{variant:"outline",fullWidth:!0,onClick:dt,disabled:!G,loading:xe,dark:D,styles:{...k,button:{...k?.button,backgroundColor:B}},children:xe?Me?"LOCKING...":"CONVERTING...":se&&ht?"CALCULATING FEES...":Me?`LOCK ${o}`:`CONVERT TO ${o}`}),r.jsx(Rc,{isOpen:et,data:Ee,isLocking:xe,lockError:ne,onContinue:dt,onClose:()=>ut(!1),primaryColor:B,fontFamily:R,dark:D}),De&&kt&&r.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:D?"rgba(0, 0, 0, 0.45)":"rgba(255, 255, 255, 0.55)",backdropFilter:"blur(2px)",WebkitBackdropFilter:"blur(2px)",borderRadius:U},children:r.jsx(Zs,{type:"lock",showStepBreakdown:!1,isOpen:!!De&&De.overallStatus!=="processing",isProcessing:xe||De?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{it(),vt(!1),dt()},onNewTx:()=>{it(),vt(!1),q(null),He.current=null,qe(),_e()},onClose:()=>{it(),vt(!1)},onComplete:()=>{it(),vt(!1),q(null),He.current=null,qe(),_e()},results:De?.overallStatus==="success"||De?.overallStatus==="failed"?De.steps.map($=>({asset:{symbol:H?.asset?.symbol||o,address:H?.asset?.address||""},txHash:$.transactionHash||"",success:$.status==="success",amount:H?.amount})):void 0,chainId:d,theme:I,styles:k,dark:D})})]})})};function Nr(e){const t=c.useContext(p.SpiceFlowProviderContext),n=t?.embeddedWalletAddress,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{...dr(s,o),embeddedWalletAddress:n}}var qc="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 Qc=({appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,showUsdSummary:a=!0,address:i,dk:l,dark:u=!1,showModeToggle:d,isEmbeddedMode:m=!0,onModeToggle:f})=>{const[h,x]=c.useState(!1),g=async()=>{i&&await p.copyToClipboard(i)&&(x(!0),setTimeout(()=>x(!1),2e3))},y=t==="active",C=n||(y?"Active":"Inactive"),v=y?"#10b981":"#9ca3af",b=r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[r.jsxs("div",{children:[r.jsx("strong",{children:"Embedded:"})," Deposit assets into ",e," account and use them here."]}),r.jsxs("div",{children:[r.jsx("strong",{children:"External:"})," Use assets from your connected wallet here."]})]});return r.jsxs("div",{children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[r.jsxs("div",{style:{fontSize:"13px",fontWeight:600,color:l.textPrimary},children:[e," Account"]}),d?r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[r.jsxs("button",{onClick:f,style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:u?l.hoverBg:"#f3f4f6",border:u?`1px solid ${l.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"11px",fontWeight:600,fontFamily:p.font.mono,color:l.textSecondary,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease",letterSpacing:"0.02em"},children:[r.jsx("span",{children:m?"Embedded":"External"}),r.jsx("img",{src:qc,alt:"","aria-hidden":"true",style:{width:"11px",height:"11px",display:"block",...u?{filter:"invert(0.65)"}:{}}})]}),r.jsx(_o,{content:b,label:"Account mode info",textColor:u?l.textPrimary:"#f9fafb",backgroundColor:u?l.cardBg:"#111827",borderColor:u?l.cardBorder:"rgba(255,255,255,0.08)",accentColor:u?l.textSecondary:"#6b7280",children:r.jsx("img",{src:Ks,alt:"","aria-hidden":"true",style:{width:"12px",height:"12px",display:"block",...u?{filter:"invert(0.65)"}:{}}})})]}):r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:u?l.hoverBg:y?"#ecfdf5":"#f3f4f6",border:u?`1px solid ${l.cardBorder}`:y?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[r.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:v}}),r.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:u?l.textSecondary:y?"#065f46":"#6b7280"},children:C})]})]}),a&&r.jsx("div",{style:{fontSize:"28px",fontWeight:700,color:l.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:p.formatUsd(s)}),a&&o&&r.jsx("div",{style:{fontSize:"12px",color:l.textSecondary,marginBottom:"8px"},children:o}),i&&r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[r.jsx("span",{style:{fontSize:"12px",fontFamily:p.font.mono,color:u?l.textSecondary:"#9ca3af"},children:p.truncateAddress(i)}),r.jsx("button",{onClick:g,style:{padding:"2px 6px",fontSize:"10px",fontWeight:500,backgroundColor:"transparent",color:u?l.textSecondary:"#9ca3af",border:"none",cursor:"pointer",borderRadius:"4px",transition:"background-color 150ms ease, color 150ms ease"},title:"Copy address",children:h?"Copied":"Copy"})]})]})},Kc=c.memo(Qc),Yc=({pendingDeposits:e,onCompleteDeposit:t,dk:n,dark:s=!1})=>e.length===0?null:r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:"Pending Deposits"}),r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((o,a)=>{const i=p.getChainConfig(o.chainId)?.displayName||`Chain ${o.chainId}`;return r.jsxs("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:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[r.jsx("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)}),r.jsxs("div",{children:[r.jsxs("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:[o.amount," ",o.tokenSymbol]}),r.jsxs("div",{style:{fontSize:"11px",color:n.warningText},children:["on ",i]})]})]}),r.jsx("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}-${a}`)})})]}),Zc=c.memo(Yc),Gc=e=>`${e.tokenAddress}-${e.chainId}`,Xc=({spiceAssets:e,loading:t,dk:n,dark:s=!1,canDirectWithdraw:o=!1,onDirectWithdraw:a,directWithdrawState:i})=>{const l={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},u={backgroundColor:n.cardBg,border:s?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return t?r.jsxs("div",{children:[r.jsx("div",{style:l,children:"Idle Balances"}),[1,2].map(d=>r.jsx("div",{style:{...u,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},d))]}):e.length===0?r.jsxs("div",{children:[r.jsx("div",{style:l,children:"Idle Balances"}),r.jsx("div",{style:{...u,padding:"16px",textAlign:"center",fontSize:"13px",color:s?n.textSecondary:"#9ca3af"},children:"No assets yet. Deposit to get started."})]}):r.jsxs("div",{children:[r.jsx("div",{style:l,children:"Idle Balances"}),r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((d,m)=>{const f=p.getChainConfig(d.chainId),h=d.chainDisplayName||f?.displayName||`Chain ${d.chainId}`,x=d.tokenDisplaySymbol||d.tokenDisplayName||d.tokenSymbol,g=Gc(d),y=o&&d.directWithdraw&&!!a,C=i?.key===g?i:null,v=C?.step==="pending";return r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...u},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[d.logoURI?r.jsx("img",{src:d.logoURI,alt:d.tokenSymbol,style:{width:"24px",height:"24px",borderRadius:"50%"}}):r.jsx("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:x.charAt(0)}),r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:x}),r.jsx("div",{style:{fontSize:"11px",color:s?n.textSecondary:"#9ca3af"},children:h})]})]}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[r.jsxs("div",{style:{textAlign:"right"},children:[r.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:p.formatBalance(d.balanceFormatted)}),r.jsx("div",{style:{fontSize:"11px",color:C?.step==="error"?n.errorText:s?n.textSecondary:"#9ca3af"},children:C?.step==="error"?C.message||"Withdraw failed":p.formatUsd(d.usdValue)})]}),y&&r.jsx("button",{onClick:()=>!v&&a(d),disabled:v,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:v?"default":"pointer",opacity:v?.6:1,whiteSpace:"nowrap"},children:v?"Withdrawing\u2026":"Withdraw"})]})]},`${d.tokenAddress}-${d.chainId}-${m}`)})})]})},Jc=c.memo(Xc),$c=({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 r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:t.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:e.title}),r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.items.map((o,a)=>r.jsxs("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:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[o.tokenLogoURI?r.jsx("img",{src:o.tokenLogoURI,alt:o.tokenSymbol,style:{width:"20px",height:"20px",borderRadius:"50%"}}):r.jsx("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)}),r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:t.textPrimary},children:o.tokenSymbol}),r.jsx("div",{style:{fontSize:"11px",color:t.textSecondary},children:o.label})]})]}),r.jsx("div",{style:{fontSize:"13px",fontWeight:600,color:s(o.valueColor)},children:o.displayValue})]},a))})]})},_c=c.memo($c),ed=({onDepositClick:e,onWithdrawClick:t,depositDisabled:n=!1,withdrawDisabled:s=!1,primaryColor:o="#EA4B4B",dark:a=!1})=>!e&&!t?null:r.jsxs("div",{style:{display:"flex",gap:"8px"},children:[e&&r.jsx(p.Button,{variant:"outline",onClick:e,disabled:n,dark:a,styles:{button:{backgroundColor:o}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&r.jsx(p.Button,{variant:"outline",onClick:t,disabled:s,dark:a,styles:{button:{backgroundColor:o}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),td=c.memo(ed),nd=({appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,showUsdSummary:a,address:i,spiceAssets:l,spiceAssetsLoading:u,pendingDeposits:d,customSections:m,notice:f,onDepositClick:h,onWithdrawClick:x,depositDisabled:g,onCompleteDeposit:y,primaryColor:C,dk:v,dark:b=!1,showModeToggle:M,isEmbeddedMode:w,onModeToggle:k,showConnectExternalCta:j,onConnectExternalWallet:I,connectExternalError:D,showHowItWorks:B=!0,canDirectWithdraw:S,onDirectWithdraw:R,directWithdrawState:F})=>{const[T,K]=c.useState(!1);return r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[r.jsx(Kc,{appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,showUsdSummary:a,address:i,dk:v,dark:b,showModeToggle:M,isEmbeddedMode:w,onModeToggle:k}),f&&r.jsx("div",{style:{padding:"10px 12px",borderRadius:"8px",backgroundColor:f.tone==="warning"?b?"rgba(245, 158, 11, 0.12)":"#fffbeb":f.tone==="success"?b?"rgba(16, 185, 129, 0.12)":"#ecfdf5":v.cardBg,border:f.tone==="warning"?b?"1px solid rgba(245, 158, 11, 0.35)":"1px solid #fde68a":f.tone==="success"?b?"1px solid rgba(16, 185, 129, 0.35)":"1px solid #a7f3d0":b?`1px solid ${v.cardBorder}`:"1px solid #e5e7eb",color:f.tone==="warning"?b?"#fbbf24":"#92400e":f.tone==="success"?b?"#34d399":"#047857":v.textSecondary,fontSize:"12px",lineHeight:1.45,fontWeight:500},children:f.message}),j&&r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[r.jsx("button",{onClick:I,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:C||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:p.font.ui,transition:"opacity 150ms ease"},children:"Connect External Wallet"}),D&&r.jsx("span",{style:{fontSize:"11px",color:b?v.errorText:"#b91c1c",lineHeight:1.4},children:D})]}),r.jsx("div",{style:{height:"1px",backgroundColor:b?"#2d2d2d":"#e5e7eb"}}),r.jsx(td,{onDepositClick:h,onWithdrawClick:x,depositDisabled:g,primaryColor:C,dark:b}),B&&r.jsxs("div",{children:[r.jsxs("button",{onClick:()=>K(!T),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:v.cardBg,border:b?`1px solid ${v.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:v.textSecondary,fontSize:"12px",fontWeight:500},children:[r.jsx("span",{children:"How It Works"}),r.jsx("span",{style:{transform:T?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),T&&r.jsxs("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:b?v.cardBg:"#f0fdf4",border:b?`1px solid ${v.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:b?v.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),r.jsx(Zc,{pendingDeposits:d,onCompleteDeposit:y,dk:v,dark:b}),r.jsx(Jc,{spiceAssets:l,loading:u,dk:v,dark:b,canDirectWithdraw:S,onDirectWithdraw:R,directWithdrawState:F}),m.map((N,W)=>r.jsx(_c,{section:N,dk:v,dark:b},W))]})},sd=c.memo(nd);function od(e){return!!e.embeddedAddress&&!!e.externalAddress}function rd(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:A.SPICE_GAS_FEE_RECIPIENT,amount:n.gasBridge}),n.spicenetFee>0n&&o.push({recipient:A.SPICE_PLATFORM_FEE_RECIPIENT,amount:n.spicenetFee}),o}const ad=new Set([A.SPICE_GAS_FEE_RECIPIENT,A.SPICE_PLATFORM_FEE_RECIPIENT].map(e=>e.toLowerCase()));function id(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:ad.has(n.recipient.toLowerCase())?tn(n.amount,o.amount,100n):!0})}function Wr(e,t,n){return{chainId:e,domain:"evm",tokenTransfers:[],calls:n.filter(s=>s.amount>0n).map(s=>({to:t,value:0n,data:E.encodeFunctionData({abi:E.erc20Abi,functionName:"transfer",args:[s.recipient,s.amount]})}))}}function ld(e,t){const n=e.intents.flatMap(o=>o.batches).filter(o=>Dt(o).totalFee>0n),s=n.filter(o=>o.chainId===t);return(s.length>0?s:n)[0]??null}function cd(e,t,n,s){const o=ld(s,e),{gasFee:a,bridgeFee:i,spicenetFee:l}=o?Dt(o):{gasFee:0n,bridgeFee:0n,spicenetFee:0n};return rd(t,n,{gasBridge:a+i,spicenetFee:l})}function dd(){const{execute:e}=gn(),t=c.useContext(p.SpiceFlowProviderContext)?.embeddedWalletAddress,{embeddedAddress:n}=p.useProviderWallets(),s=t||n;return{withdraw:c.useCallback(async({tokenAddress:o,chainId:a,balance:i,recipient:l,onProgress:u})=>{const d=o,m=l;if(i<=0n)throw new Error("Nothing to withdraw.");const f=[Wr(a,d,[{recipient:m,amount:i}])];let h=null;return e(f,d,0n,u,void 0,{useCustomTransfers:!0,userOverride:s,adjustBatchesForEstimate:({feeEstimate:x})=>{const g=cd(a,m,i,x);return id(h,g)?null:(h=g,[Wr(a,d,g)])}})},[e,s])}}const to=380,dn=8,ud=[];function Or(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function pd(e,t){const n=new Map;Object.entries(t).forEach(([o,a])=>{if(!Number.isFinite(a)||a<=0)return;n.set(o,a),n.set(o.toUpperCase(),a);const i=Or(o);i&&n.set(i,a)});const s=[e.symbol,e.displaySymbol,e.receiptTokenName,e.name,e.displayName];for(const o of s){if(!o)continue;const a=n.get(o)??n.get(o.toUpperCase());if(a!==void 0)return a;const i=Or(o);if(!i)continue;const l=n.get(i);if(l!==void 0)return l}return 0}const fd=({appName:e="Spice",status:t="active",statusLabel:n,customSections:s=ud,extraAssets:o=[],tokenPrices:a={},breakdownLabels:i=[],notice:l,styles:u,dark:d=!1,onDepositSuccess:m,onDepositClick:f,onWithdrawClick:h,onCompleteDeposit:x,showModeToggle:g=!1,defaultMode:y,showUsdSummary:C=!0})=>{const v=c.useContext(p.SpiceFlowProviderContext),b=v?.mode!=="7702",M=!!v?.isWhitelistGateActive,w=!!v?.isWhitelistConfigured&&v?.isUserWhitelisted!==!0,k=c.useRef(!1);c.useEffect(()=>{if(!k.current){if(p.hasStoredSpiceFlowMode()){k.current=!0;return}y&&v?.setMode&&(v.setMode(y==="non7702"?"ondemand":"7702"),k.current=!0)}},[v,y]);const[j,I]=c.useState(!1),[D,B]=c.useState(null),[S,R]=c.useState({top:0,bottom:0,left:0,placement:"below"}),F=c.useRef(null),T=c.useRef(null),{address:K,isConnected:N}=p.useWallet(),W=v?.embeddedWalletAddress,P=v?.externalWalletAddress,{embeddedAddress:O}=p.useProviderWallets(),{dark:L,primaryColor:U,dk:Z}=p.useSpiceBrand(u,d),X=b&&!P,V=!b||X,ee=V?W||O:K,H=c.useMemo(()=>v?.supportedChainIds??A.getChainIdsByNetwork("mainnet"),[v?.supportedChainIds]),{assets:q,loading:ie}=Bn({address:ee,supportedChains:H,enabled:!!ee&&V,refetchInterval:3e4}),pe=c.useMemo(()=>{const ye=V?q.map(Ce=>{const Be=Ce.balanceUsd||0,ft=Number.isFinite(Ce.balanceFormatted)?Ce.balanceFormatted:0,yt=Be>0?Be:pd(Ce,a)*ft;return{tokenAddress:Ce.address,tokenSymbol:Ce.symbol,tokenDisplaySymbol:As(Ce),tokenDisplayName:Ci(Ce),tokenDecimals:Ce.decimals,chainId:Ce.chainId,chainDisplayName:Es(Ce),balance:Ce.balance.toString(),balanceFormatted:Ce.balanceFormatted,usdValue:yt,logoURI:Ce.logoURI}}):[],Fe=X?[]:o;return[...ye,...Fe].filter(Ce=>Ce.balanceFormatted>0)},[V,X,q,a,o]),_=c.useMemo(()=>pe.reduce((ye,Fe)=>ye+Fe.usdValue,0),[pe]),{pendingDeposits:ve}=Nr({chainIds:H,enabled:!!K,discoverWalletBalances:!0}),xe=c.useMemo(()=>s.reduce((ye,Fe)=>ye+Fe.totalValue,0),[s]),ue=_+xe,We=c.useMemo(()=>{const ye=[];_>0&&ye.push(`${p.formatUsd(_)} idle`);for(const Fe of s){const Ce=i.find(Be=>Be.sectionTitle===Fe.title)?.label||Fe.title.toLowerCase();ye.push(`${p.formatUsd(Fe.totalValue)} ${Ce}`)}return ye.join(" \xB7 ")},[_,s,i]),z=c.useCallback(ye=>{x?x(ye):B(ye)},[x]),fe=c.useCallback(()=>{B(null)},[]),le=c.useCallback(()=>{B(null),m?.()},[m]),te=c.useCallback(()=>{if(!F.current)return;const ye=F.current.getBoundingClientRect(),Fe=window.innerHeight-ye.bottom-dn,Ce=ye.top-dn,Be=Fe>=400||Fe>=Ce?"below":"above",ft=Math.max(dn,Math.min(ye.right-to,window.innerWidth-to-dn)),yt=Be==="below"?ye.bottom+dn:ye.top-dn,De=Be==="above"?window.innerHeight-yt:0;R({top:yt,bottom:De,left:ft,placement:Be})},[]);c.useLayoutEffect(()=>{j&&te()},[j,te]),c.useEffect(()=>{if(!j)return;const ye=Be=>{F.current&&!F.current.contains(Be.target)&&T.current&&!T.current.contains(Be.target)&&I(!1)},Fe=Be=>{Be.key==="Escape"&&I(!1)},Ce=()=>te();return document.addEventListener("mousedown",ye),document.addEventListener("keydown",Fe),window.addEventListener("scroll",Ce,{passive:!0}),window.addEventListener("resize",te),()=>{document.removeEventListener("mousedown",ye),document.removeEventListener("keydown",Fe),window.removeEventListener("scroll",Ce),window.removeEventListener("resize",te)}},[j,te]);const Q=V?W||O||K:P||K,se=c.useCallback(()=>{v?.setMode&&v.setMode(V?"ondemand":"7702")},[v,V]),[me,J]=c.useState(null);let he=null;try{he=wo.useConnectWallet({onSuccess:()=>J(null),onError:ye=>J(p.sanitizeError(ye,"Failed to connect wallet."))}).connectWallet}catch{he=null}const Ue=c.useCallback(()=>{he&&(I(!1),J(null),he({walletChainType:"ethereum-only"}))},[he]),Re=!P&&!!he,kt=c.useCallback(()=>{I(!1),f?.()},[f]),vt=c.useCallback(()=>{I(!1),h?.()},[h]),et=c.useCallback(ye=>{I(!1),z(ye)},[z]),{withdraw:ut}=dd(),[Ee,Ve]=c.useState(null),rt=od({embeddedAddress:W||O,externalAddress:P}),at=c.useCallback(async ye=>{if(!P)return;const Fe=`${ye.tokenAddress}-${ye.chainId}`;Ve({key:Fe,step:"pending"});try{await ut({tokenAddress:ye.tokenAddress,chainId:ye.chainId,balance:BigInt(ye.balance),recipient:P}),Ve(null)}catch(Ce){Ve({key:Fe,step:"error",message:p.sanitizeError(Ce,"Withdraw failed")})}},[ut,P]);if(typeof window>"u")return null;const re=r.jsxs("button",{ref:F,onClick:()=>I(!j),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:L?Z.hoverBg:"#ffffff",border:L?`1px solid ${Z.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:p.font.ui,color:L?Z.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:L?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[r.jsxs("span",{children:[e," Account"]}),N&&C&&r.jsxs("span",{style:{color:L?Z.textSecondary:"#6b7280"},children:["\xB7 ",p.formatUsd(ue)]}),r.jsx("span",{style:{fontSize:"10px",color:L?Z.textSecondary:"#9ca3af",transform:j?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),pt=j?wn.createPortal(r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:p.z.popover},onClick:()=>I(!1)}),r.jsx("div",{ref:T,style:{position:"fixed",top:S.placement==="below"?`${S.top}px`:"auto",bottom:S.placement==="above"?`${S.bottom}px`:"auto",left:`${S.left}px`,width:`${to}px`,maxWidth:`calc(100vw - ${dn*2}px)`,maxHeight:"80vh",backgroundColor:L?Z.shell:"#ffffff",border:L?`1px solid ${Z.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:L?"0 10px 40px rgba(0, 0, 0, 0.5)":"0 10px 40px rgba(0, 0, 0, 0.12)",zIndex:p.z.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${p.easing.out}`},children:r.jsx(sd,{appName:e,status:t,statusLabel:n,totalUsdValue:ue,breakdownSubtitle:We,showUsdSummary:C,address:V?Q:K,spiceAssets:pe,spiceAssetsLoading:ie,pendingDeposits:ve,customSections:s,notice:l,onDepositClick:f?kt:void 0,onWithdrawClick:h?vt:void 0,depositDisabled:w,onCompleteDeposit:et,primaryColor:U,dk:Z,dark:L,showModeToggle:g,isEmbeddedMode:V,onModeToggle:se,showConnectExternalCta:Re,onConnectExternalWallet:Ue,connectExternalError:me,showHowItWorks:!M,canDirectWithdraw:rt,onDirectWithdraw:at,directWithdrawState:Ee})}),r.jsx("style",{children:`
|
|
80
|
+
`})]})};function Dc(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const s=E.getAddress(n.token),o=E.getAddress(n.to),a=`${s.toLowerCase()}:${o.toLowerCase()}`,i=t.get(a);i?i.amount+=n.amount:t.set(a,{token:s,to:o,amount:n.amount})}return[...t.values()]}function Mc(e,t){return`0x${t}${e.slice(4)}`}function Br(e,t){return Tr(e,t)}function Tr(e,t,n){const s=Qn(t,e),o=Math.floor(Date.now()/1e3)+60*10,a=A.hashChainBatches(s);return{user:e,...n?{chainAuthorizations:n}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:"0x00",nbf:0,exp:o,chainBatches:a.map((i,l)=>({hash:i.hash,chainId:i.chainId,tokenTransfers:s[l].domain==="spicenet"?[]:s[l].tokenTransfers??[],calls:i.calls}))}]}}function cn(e,t,n,s){if(e.some(m=>m.domain==="spicenet"))return e;const o=n?.intents.flatMap(m=>m.batches),a=m=>m.from==="escrow",i=e.map(m=>{const f=o?.find(I=>I.chainId===m.chainId);if(!f)return m;const h=Dt(f),x=h.totalFee;if(x<=0n)return m;const g=(m.tokenTransfers??[]).filter(I=>a(I)&&E.getAddress(I.to).toLowerCase()===t.toLowerCase()),y=g.find(I=>!A.isNativeToken(E.getAddress(I.token)))??g[0];if(!y)return m;const C=E.getAddress(y.token),v=A.isNativeToken(C);let b=!1;const M=(m.tokenTransfers??[]).map(I=>b||!a(I)||E.getAddress(I.to).toLowerCase()!==t.toLowerCase()||E.getAddress(I.token).toLowerCase()!==C.toLowerCase()?I:(b=!0,{...I,amount:s?.payoutAlreadyGross?BigInt(I.amount):BigInt(I.amount)+x}));if(!b)return m;const w=(I,D)=>v?{to:I,value:D,data:"0x"}:{to:C,value:0n,data:E.encodeFunctionData({abi:E.erc20Abi,functionName:"transfer",args:[I,D]})},k=[];h.spicenetFee>0n&&k.push(w(A.SPICE_PLATFORM_FEE_RECIPIENT,h.spicenetFee));const j=h.gasFee+h.bridgeFee;return j>0n&&k.push(w(A.SPICE_GAS_FEE_RECIPIENT,j)),{...m,tokenTransfers:M,calls:[...k,...m.calls]}}),l=i.flatMap(m=>(m.tokenTransfers??[]).filter(a).map(f=>{const h=E.getAddress(f.token),x=E.getAddress(f.to),g=[{token:h,to:x,amount:BigInt(f.amount)}];return{chainId:m.chainId,transfers:Dc(g)}}));if(l.length===0)return e;const u=s?.requestTimestampMs??Date.now(),d=BigInt(Math.floor(u/1e3))+3600n;return[{chainId:A.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:l.map((m,f)=>{const h=E.keccak256(E.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,m.transfers[0].token,m.transfers.reduce((g,y)=>g+y.amount,0n),BigInt(m.chainId),BigInt(u+f)])),x=Mc(h,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:E.encodeFunctionData({abi:A.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${m.chainId}`,idempotenceKey:x,nbf:0n,exp:d,metadata:"{}",transfers:m.transfers.map(g=>({token:g.token.toLowerCase(),to:g.to,amount:g.amount}))}]})}})},...i]}const Nc=60*60,Rr=(e,t)=>!!e&&e.grossAmount===t.grossAmount&&e.netAmount===t.netAmount&&e.feeAmount===t.feeAmount;function ts(e,t){return t?e.some(n=>(n.tokenTransfers??[]).some(s=>s.from==="escrow"&&BigInt(s.amount)>=t.grossAmount)):!1}function Dr(e){return!e.isSemi7702&&e.isDirectDeposit&&!e.isSourceDestToken}function Mr(e){const t=e.selectedAsset?.asset,n=e.selectedAsset?.amount;if(!(!t||!n))return E.parseUnits(n,t.decimals)}async function ns({user:e,batches:t,authorizations:n,adjustBatchesForEstimate:s}){let o=t;for(let a=0;a<10;a+=1){const i=await p.relayerService.estimateActionFees(Tr(e,o,n)),l=await s({feeEstimate:i,batches:o});if(!l||Vo(o,l))return o;o=l}throw new Error("Fee estimate did not converge. Please retry.")}function Wc(e){return{chainId:e.sourceChainId,calls:e.isNative?[{to:e.target,value:e.amount,data:"0x"}]:[{to:e.tokenAddr,value:0n,data:E.encodeFunctionData({abi:E.erc20Abi,functionName:"transfer",args:[e.target,e.amount]})}]}}function Js(e,t,n,s){const o=e.selectedAsset.asset,a=E.parseUnits(e.selectedAsset.amount,o.decimals),i=o.chainId,l=e.escrowAddress||A.getEscrowContractAddress(i),u=A.normalizeNativeTokenAddress(o.address),d=o.isNative||A.isNativeToken(u),m=n.some(f=>f.tokenTransfers?.some(h=>h.from==="escrow"));return{asset:o,userNetAmountWei:a,sourceChainId:i,tokenAddr:u,isNative:d,hasEscrowBackedPayout:m,composeBatches:(f,h,x,g)=>{const y=Wc({sourceChainId:i,target:l,tokenAddr:u,isNative:d,amount:f});if(!m)return[y,...h];const C=cn([...h],t,x,{payoutAlreadyGross:ts(h,g),...s!==void 0?{requestTimestampMs:s}:{}});return[y,...C]}}}function $s(e){const t={};return{state:t,adjustBatchesForEstimate:({feeEstimate:n})=>{const s=Ms(n,{symbol:e.symbol,decimals:e.decimals,actionAmount:e.actionAmount});if(!s)return null;t.plan={grossAmount:s.grossAmount,netAmount:s.netAmount,feeAmount:s.totalFee??0n};const o=sn(e.ctx,t.plan);return e.rebuild(o,n,t.plan)}}}function sn(e,t){const n=e.selectedAsset?.asset;if(!n||!e.selectedAsset?.amount)throw new Error("Select an asset and enter an amount");const s=E.parseUnits(e.selectedAsset.amount,n.decimals),o=t?.grossAmount??s;return e.resolveLockBatches({amount:e.selectedAsset.amount,amountWei:s,grossAmount:E.formatUnits(o,n.decimals),grossAmountWei:o})}async function _s(e,t,n){const s=e.isSemi7702&&e.embeddedWalletAddress||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 Fn({chainBatches:t,signingAddress:s,actions:e.actions}),a=A.hashChainBatches(t),i=Math.floor(Date.now()/1e3)+Nc,l={mode:"7702",signatureType:"ecdsa",signature:await Ko(e.actions,t,BigInt(i)),nbf:0,exp:i,chainBatches:a.map((d,m)=>{const f=t[m],h=f.domain==="spicenet";return{hash:d.hash,chainId:d.chainId,tokenTransfers:h?[]:f.tokenTransfers??[],calls:d.calls}})},u=await p.relayerService.createAction({user:s,chainAuthorizations:o,intents:[l]});if(u){const d=p.createInitialSteps(t,p.getChainName),[m,f]=u.intentIds[0].split("/"),h=parseInt(f||"0",10),x=u.intentIds[0];e.beginStatusTracking(u.intentIds[0],d),await Ho({actionId:m,intentIndex:h,intentId:x,totalSteps:t.length,isSpicenetStep:g=>t[g]?.domain==="spicenet",maxExecuteAttemptsForStep:g=>t[g]?.domain==="spicenet"?6:3,onStepUpdate:e.applyStepUpdate,maxPolls:72})}}function eo(e,t){const n=e.feeQuote;return n?t.adjustBatchesForEstimate({feeEstimate:n.feeEstimate,batches:[]}):null}async function Oc(e){const t=sn(e);if(t.length===0)throw new Error("No lock batches configured");const n=e.isSemi7702&&e.embeddedWalletAddress||e.address;if(!e.isConnected||!n)throw new Error("Please connect your wallet to continue");const s=await Fn({chainBatches:t,signingAddress:n,actions:e.actions}),o=Date.now(),a=$s({ctx:e,actionAmount:Mr(e),symbol:e.selectedAsset?.asset.symbol??"",decimals:e.selectedAsset?.asset.decimals??18,rebuild:(l,u,d)=>cn([...l],n,u,{payoutAlreadyGross:ts(l,d),requestTimestampMs:o})});let i=eo(e,a)??cn([...t],n,void 0,{requestTimestampMs:o});i=await ns({user:n,batches:i,authorizations:s,adjustBatchesForEstimate:a.adjustBatchesForEstimate}),await _s(e,i,s)}async function Pc(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");const t=e.embeddedWalletAddress||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=Js(e,t,n,Date.now()),o=$s({ctx:e,actionAmount:s.userNetAmountWei,symbol:s.asset.symbol,decimals:s.asset.decimals,rebuild:(l,u,d)=>s.composeBatches(d.grossAmount,l,u,d)});let a=eo(e,o)??s.composeBatches(s.userNetAmountWei,sn(e));const i=await Fn({chainBatches:a,signingAddress:t,actions:e.actions});s.hasEscrowBackedPayout&&(a=await ns({user:t,batches:a,authorizations:i,adjustBatchesForEstimate:o.adjustBatchesForEstimate})),await _s(e,a,i)}async function Uc(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;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");if(e.onLockExecute){const g=e.resolveLockBatches();if(g.length===0)throw new Error("No lock batches configured");const y=e.selectedAsset.asset,C=E.parseUnits(e.selectedAsset.amount,y.decimals),v=await e.onLockExecute({asset:y,amount:e.selectedAsset.amount,amountWei:C,lockDurationMonths:e.selectedDuration?.months??0,chainBatches:g});v&&e.onLockSuccess?.(v);return}const n=e.resolveLockBatches();if(n.length===0)throw new Error("No lock batches configured");const s=Js(e,t,n,Date.now()),{userNetAmountWei:o}=s,a=$s({ctx:e,actionAmount:o,symbol:s.asset.symbol,decimals:s.asset.decimals,rebuild:(g,y,C)=>s.composeBatches(C.grossAmount,g,y,C)});let i=eo(e,a)??s.composeBatches(o,sn(e));const l=await Fn({chainBatches:i,signingAddress:t,actions:e.actions});s.hasEscrowBackedPayout&&(i=await ns({user:t,batches:i,authorizations:l,adjustBatchesForEstimate:a.adjustBatchesForEstimate}));const u=a.state.plan?.grossAmount??o,{extWc:d,viemChain:m}=await yn({wallet:e.externalWallet,account:e.externalWalletAddress,chainId:s.sourceChainId}),f=p.getClientForChain(s.sourceChainId),h=g=>Hs({extWc:d,sourceClient:f,recipient:t,tokenAddr:s.tokenAddr,isNative:s.isNative,amount:g,viemChain:m});await h(u);let x=u;if(s.hasEscrowBackedPayout)for(let g=0;g<4;g+=1){i=await ns({user:t,batches:i,authorizations:l,adjustBatchesForEstimate:a.adjustBatchesForEstimate});const y=a.state.plan?.grossAmount??o;if(y<=x)break;await h(y-x),x=y}await _s(e,i,l)}async function zc(e,t){if(!e.selectedAsset?.asset||!e.selectedAsset.amount||!e.requiresRelayerFeeEstimate)return null;if(e.isSemi7702||Dr(e)){const u=e.embeddedWalletAddress||e.address;if(!u)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");const d=e.feeQuote;let m=sn(e,d?.plan);if(m.length===0)throw new Error("No lock batches configured");const f=Js(e,u,m),{asset:h,userNetAmountWei:x}=f;let g=d?f.composeBatches(d.plan.grossAmount,m,d.feeEstimate,d.plan):f.composeBatches(x,m,void 0,{grossAmount:x,netAmount:0n,feeAmount:0n}),y=null,C=d?.plan;for(let v=0;v<4;v+=1){const b=await p.relayerService.estimateActionFees(Br(u,g),{signal:t}),M=Ms(b,{symbol:h.symbol,decimals:h.decimals,actionAmount:x});if(!M)return y;const w={grossAmount:M.grossAmount,netAmount:M.netAmount,feeAmount:M.totalFee??0n},k=Rr(C,w);if(y={preview:M,feeEstimate:b,plan:w},C=w,m=sn(e,w),g=f.composeBatches(w.grossAmount,m,b,w),k)break}return y}const n=e.address;if(!e.isConnected||!n)throw new Error("Please connect your wallet to continue");const s=e.feeQuote;let o=sn(e,s?.plan);if(o.length===0)throw new Error("No lock batches configured");let a=cn([...o],n,s?.feeEstimate,s?{payoutAlreadyGross:ts(o,s.plan)}:void 0),i=null,l=s?.plan;for(let u=0;u<4;u+=1){const d=await p.relayerService.estimateActionFees(Br(n,a),{signal:t}),m=Ms(d,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:Mr(e)});if(!m)return null;const f={grossAmount:m.grossAmount,netAmount:m.netAmount,feeAmount:m.totalFee??0n},h=Rr(l,f);if(i={preview:m,feeEstimate:d,plan:f},l=f,o=sn(e,f),a=cn([...o],n,d,{payoutAlreadyGross:ts(o,f)}),h)break}return i}async function Lc(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(d=>d.chainId===e.lockChainId)||s[0];if(!o)throw new Error("No lock batch for lock chain");const{extWc:a,viemChain:i}=await yn({wallet:t,account:n,chainId:e.lockChainId}),l=p.getClientForChain(e.lockChainId),u=await tr({extWc:a,client:l,calls:o.calls,viemChain:i,errorMessage:"Lock transaction failed"});u&&e.onLockSuccess?.(u)}async function Hc(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("[SpiceLock] lock failed:",n);const s=p.sanitizeError(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 Lc(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{await Uc(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{Dr(e)?await Pc(e):await Oc(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}}const Vc=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,lockBatches:s,lockTokenSymbol:o,lockTokenLogoURI:a,destinationInputHook:i,sourceAssetInputHook:l,lockDurationHook:u,lockChainId:d,durationOptions:m,votingPowerEstimate:f,escrowAddress:h,includeWalletAssets:x=!1,destinationTokenAddress:g,onLockSuccess:y,onLockError:C,onLockExecute:v,sourceToDestinationConversionRate:b,onAddFunds:M,buildSpicenetBatch:w,styles:k,dark:j=!1})=>{const{theme:I,dark:D,primaryColor:B,dk:S}=p.useSpiceBrand(k,j),R=I.typography.fontFamily,F=c.useContext(p.SpiceFlowProviderContext),T=F?.mode||"7702",K=!!F?.isWhitelistGateActive,N=T!=="7702",W=c.useMemo(()=>F?.supportedChainIds??[],[F?.supportedChainIds]),P=c.useMemo(()=>{if(K)return[];const $=F?.allowedTokens;if(!$||$.length===0)return[];const ke=new Set($.map(Te=>Te.toLowerCase())),Je=[],Ke=new Set;for(const Te of W){const Bt=p.getChainConfig(Te);for(const Oe of Bt?.supportedTokens??[]){if(!ke.has(Oe.symbol.toLowerCase()))continue;const Ne=`${Te}:${Oe.address.toLowerCase()}`;Ke.has(Ne)||(Ke.add(Ne),Je.push(E.getAddress(Oe.address)))}}return Je},[F?.allowedTokens,W,K]),O=D?S.cardBg:k?.assetSelector?.backgroundColor||k?.secondaryBackground||"#e9e9e9",L=D?`1px solid ${S.cardBorder}`:"0.5px solid #A8A8A7",U=D?"12px":"6px",Z=D?S.textPrimary:"#111827",X=D?S.textSecondary:"#6b7280",V=c.useMemo(()=>({...k,assetSelector:{...k?.assetSelector,backgroundColor:D?S.cardBg:k?.assetSelector?.backgroundColor,borderRadius:D?"12px":k?.assetSelector?.borderRadius},secondaryBackground:D?S.cardBg:k?.secondaryBackground}),[k,D]),ee=c.useMemo(()=>D?{...I,colors:{...I.colors,secondary:S.cardBg,surfaceHover:S.hoverBg,border:S.cardBorder,borderHover:S.inputBorder}}:I,[D,I]),[H,q]=c.useState(null),[ie,pe]=c.useState(0),_=u?.selectedDurationIdx??ie,ve=u?.setSelectedDurationIdx??pe,[xe,ue]=c.useState(!1),[We,z]=c.useState(null),fe=c.useRef(C);fe.current=C;const le=c.useCallback($=>{z($),typeof $=="string"&&$&&fe.current?.($,p.getRelayerErrorDetail($))},[]),[te,Q]=c.useState(null),[se,me]=c.useState(!1),[J,he]=c.useState(!1),[Ue,Re]=c.useState(null),[kt,vt]=c.useState(!1),[et,ut]=c.useState(!1),[Ee,Ve]=c.useState(null),rt=p.useWallet(),{isReady:at,isAuthenticated:re,isConnected:pt,address:ye,provider:Fe,actions:Ce}=rt,{externalWallet:Be,activeWallet:ft,activeAddress:yt}=p.useProviderWallets(),{intentStatus:De,beginStatusTracking:St,applyStepUpdate:Le,clearStatus:it}=gn(),{assets:Mt,refetch:qe}=Bn({address:ye,supportedChains:W,enabled:e&&pt&&!N&&!K,refetchInterval:3e4}),tt=c.useMemo(()=>{if(K)return[];if(P.length===0)return Mt;const $=new Set(P.map(ke=>A.normalizeNativeTokenAddress(ke).toLowerCase()));return Mt.filter(ke=>$.has(A.normalizeNativeTokenAddress(ke.address).toLowerCase()))},[Mt,P,K]),It=F?.embeddedWalletAddress,Tt=F?.externalWalletAddress,we=N?yt??Tt:It,{walletAssets:Ie,refreshWalletAssets:_e}=Ec({isOpen:e,includeWalletAssets:x,isWhitelistGateActive:K,isSemi7702:N,destinationTokenAddress:g,sourceAssets:P,sourceChains:W,walletAddressForAssets:we,lockChainId:d,lockTokenSymbol:o,lockTokenLogoURI:a}),de=c.useMemo(()=>Ie.filter($=>$.balance>0n),[Ie]),ce=c.useMemo(()=>{if(N)return de.map(ke=>({...ke,_source:"wallet"}));if(!x)return tt;const $=[];for(const ke of de)$.push({...ke,_source:"wallet"});for(const ke of tt)$.push({...ke,_source:"spice"});return $},[N,x,de,tt]),Ze=c.useMemo(()=>K?g?ce.filter($=>p.addressesEqual($.address,g)&&$.chainId===d):[]:ce,[ce,K,g,d]),He=c.useRef(null),lt=c.useRef(null);c.useEffect(()=>{lt.current=H},[H]),c.useEffect(()=>{!K||!H?.asset||g&&p.addressesEqual(H.asset.address,g)&&H.asset.chainId===d||q(null)},[K,H?.asset,g,d]),c.useEffect(()=>{e||(q(null),le(null),Q(null),me(!1),he(!1),Re(null),ue(!1),ut(!1),Ve(null),vt(!1),it())},[e,it]),c.useEffect(()=>{i&&i.assetAmount!==(H?.amount||"")&&q($=>$&&{...$,amount:i.assetAmount})},[i?.assetAmount]),c.useEffect(()=>{l&&l.assetAmount!==(H?.amount||"")&&q($=>$&&{...$,amount:l.assetAmount})},[l?.assetAmount]),c.useEffect(()=>{if(!N&&De?.overallStatus==="success"&&De.intentId&&He.current!==De.intentId&&ye&&De.steps.find($=>$.transactionHash)?.transactionHash){He.current=De.intentId;const $=lt.current;if(!$?.asset||!$.amount||$.asset._source==="wallet"||E.parseUnits($.amount,$.asset.decimals)===0n)return;qe()}},[De,ye,d,qe,N]);const Se=parseFloat(H?.amount||"")||0,nt=c.useMemo(()=>H?.asset?H.asset._source==="wallet"?H.asset.balanceFormatted??0:tt.find($=>p.addressesEqual($.address,H.asset.address)&&$.chainId===H.asset.chainId)?.balanceFormatted??0:0,[H?.asset,tt]),ze=Se>0&&(Ue?parseFloat(E.formatUnits(Ue.grossAmount,Ue.decimals))>nt:Se>nt),Ge=u?.selectedDuration??m[_]??m[0],Me=c.useMemo(()=>!H?.asset||!g?!1:p.addressesEqual(H.asset.address,g)&&H.asset.chainId===d,[H?.asset,g,d]),ct=c.useMemo(()=>Se<=0?0:Me?Se:!b||b<=0?0:Se/b,[Se,b,Me]),mt=c.useMemo(()=>ct<=0?null:ct.toLocaleString(void 0,{maximumFractionDigits:2}),[ct]),Ut=f&&ct>0&&Ge?f(ct,Ge.months):void 0,jt=c.useMemo(()=>Se<=0?"$0.00":Me&&b?(Se*b).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!b||b<=0?"$0.00":Se.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[Se,b,Me]),Wt=c.useMemo(()=>{if(!mt)return null;const $=parseFloat(mt.replace(/,/g,""));return Me&&b?($*b).toLocaleString(void 0,{maximumFractionDigits:2}):b?($*b).toLocaleString(void 0,{maximumFractionDigits:2}):null},[mt,b,Me]),Pe=c.useCallback($=>{q(ke=>({asset:$,amount:ke?.asset?.address===$.address&&ke?.asset?.chainId===$.chainId&&ke.amount||""})),le(null),Q(null),he(!1),Re(null),l?.setSelectedAsset&&l.setSelectedAsset({symbol:$.symbol,address:$.address,decimals:$.decimals,chainId:$.chainId})},[l?.setSelectedAsset]),At=c.useCallback($=>{q(ke=>ke&&{...ke,amount:$}),le(null),Q(null),he(!1),Re(null),i&&i.setAssetAmount($),l&&l.setAssetAmount($)},[i,l]),Qe=c.useCallback($=>{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:$?.amount??H.amount,amountWei:$?.amountWei??E.parseUnits(H.amount,H.asset.decimals),grossAmount:$?.grossAmount,grossAmountWei:$?.grossAmountWei,feeAdjusted:!!$})}return s},[s,H]),gt=c.useRef(null),ht=c.useMemo(()=>!H?.asset||Se<=0?!1:N?!Me&&!v:!0,[H,Se,N,Me,v]),Ct=c.useCallback($=>zc(gt.current,$),[]),Xe=c.useRef(null),bt=c.useMemo(()=>!H?.asset||Se<=0?null:`${H.asset.address.toLowerCase()}:${H.asset.chainId}:${H.amount??""}`,[H?.asset?.address,H?.asset?.chainId,H?.amount,Se]);zn({shouldRun:e&&!xe&&!!H?.asset&&Se>0&&ht,deps:[e,xe,bt,ht,Ct],delayMs:500,backgroundIntervalMs:3e4,onSkip:()=>{if(!(!e||xe)){if(!H?.asset||Se<=0){Q(null),me(!1),he(!1),Re(null);return}Q(null),me(!1),he(!0),Re(null)}},run:async({isBackground:$,isCurrent:ke,signal:Je})=>{const Ke=bt;$||(Q(null),he(!1),me(!0));try{const Te=await Ct(Je);if(!ke())return;Xe.current=Te&&Ke?{key:Ke,quote:Te}:null,Q(null),he(!0),Re(Te?.preview??null)}catch(Te){if(!ke())return;$||(Q(p.sanitizeError(Te,"Unable to calculate fees for this lock.")),he(!1))}finally{ke()&&!$&&me(!1)}}}),c.useEffect(()=>{if(De?.overallStatus==="success"){const $=De.steps.find(ke=>ke.transactionHash);y?.($?.transactionHash)}},[De?.overallStatus,y]);const xt=x&&H?.asset?._source==="wallet"&&H?.asset?.chainId===d,dt=c.useCallback(()=>Hc(gt.current),[]),G=!!H?.asset&&Se>0&&!ze&&!xe&&(!ht||J&&!se&&!te),ne=We||te,oe=r.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[r.jsx(Ps,{color:X}),r.jsxs("p",{style:{fontSize:"13px",color:X,margin:0,lineHeight:"1.5"},children:["Add ",o," by converting assets from your account"]})]});if(gt.current={selectedAsset:H,parsedAmount:Se,selectedDuration:Ge,isInsufficientBalance:ze,isSemi7702:N,isSourceDestToken:Me,isDirectDeposit:xt,requiresRelayerFeeEstimate:ht,address:ye,embeddedWalletAddress:It,externalWallet:Be,externalWalletAddress:Tt,activeSignerWallet:ft,activeSignerAddress:yt,isConnected:pt,ready:at,authenticated:re,provider:Fe,actions:Ce,lockChainId:d,escrowAddress:h,onLockExecute:v,onLockSuccess:y,buildSpicenetBatch:w,resolveLockBatches:Qe,beginStatusTracking:St,applyStepUpdate:Le,refreshSpiceAssets:qe,refreshWalletAssets:_e,feeQuote:bt&&Xe.current?.key===bt?Xe.current.quote:null,ui:{setError:le,setIsExecuting:ue,setShowStatusPanel:vt}},!e)return null;const je={backgroundColor:O,border:L,borderRadius:U,padding:"16px",marginBottom:"16px"};return r.jsx(Pt,{isOpen:e,onClose:t,title:`Add ${o} to your account`,subtitle:oe,styles:k,dark:D,footerLinkText:"Spicenet accounts \u2192",overlayContent:et?r.jsx("div",{}):void 0,closeOnBackdropClick:n,children:r.jsxs("div",{style:{padding:"0 24px 8px 24px",position:"relative"},children:[r.jsxs("div",{style:{marginBottom:"12px"},children:[M&&r.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:r.jsx(Ls,{onClick:M,color:B,fontFamily:R})}),r.jsx("div",{style:{marginTop:"10px",fontSize:"13px",color:X,fontFamily:R},children:r.jsx(In,{assets:Ze,selectedAsset:H??void 0,onAssetSelect:Pe,onAmountChange:At,label:"Amount",showBalance:!0,showMaxButton:!0,theme:ee,styles:V})}),r.jsx("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:X,fontFamily:R},children:jt})]}),r.jsxs("div",{style:je,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:D?`1px solid ${S.cardBorder}`:"1px solid #e5e7eb"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[a?r.jsx("img",{src:a,alt:o,style:{width:"32px",height:"32px",borderRadius:"50%",objectFit:"cover"}}):r.jsx("div",{style:{width:"32px",height:"32px",borderRadius:"50%",backgroundColor:D?S.inputBg:"#d1d5db",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:700,color:Z},children:o.slice(0,2)}),r.jsx("span",{style:{fontSize:"16px",fontWeight:600,color:Z,fontFamily:R},children:o})]}),r.jsxs("div",{style:{textAlign:"right"},children:[r.jsx("div",{style:{fontSize:"22px",fontWeight:700,color:Z,fontFamily:R,lineHeight:1.1},children:mt??"0.00"}),r.jsxs("div",{style:{fontSize:"12px",color:X,fontFamily:R,marginTop:"2px"},children:["~$",Wt??"0.00"]})]})]}),r.jsxs("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:D?`1px solid ${S.cardBorder}`:"1px solid #e5e7eb"},children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[r.jsx("span",{style:{fontSize:"15px",fontWeight:500,color:X,fontFamily:R},children:"Lock Duration"}),r.jsx(on,{color:X})]}),r.jsx(jc,{options:m,selectedIndex:_,onSelect:ve,primaryColor:B,dark:D,textPrimary:Z,textSecondary:X})]}),r.jsxs("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[r.jsx(jr,{label:"Estimated Lock Expiry",value:Ge?.months!==void 0?Bc(Ge.months):"\u2014",fontFamily:R,dark:D,textPrimary:Z,textSecondary:X}),f&&r.jsx(jr,{label:"Estimated voting power",value:Ut!==void 0?`${Ut} votes/epoch`:"\u2014",fontFamily:R,dark:D,textPrimary:Z,textSecondary:X})]})]}),ht&&r.jsx(zs,{fontFamily:R,textPrimary:Z,textSecondary:X,cardBg:O,cardBorder:L,resolvedDark:D,darkCardBorder:S.cardBorder,primaryColor:B,feePreview:Ue,isLoading:se,errorText:te}),ne&&r.jsx(ln,{variant:"error",palette:S,fontFamily:R,style:{marginBottom:"12px"},children:ne}),r.jsx(p.Button,{variant:"outline",fullWidth:!0,onClick:dt,disabled:!G,loading:xe,dark:D,styles:{...k,button:{...k?.button,backgroundColor:B}},children:xe?Me?"LOCKING...":"CONVERTING...":se&&ht?"CALCULATING FEES...":Me?`LOCK ${o}`:`CONVERT TO ${o}`}),r.jsx(Rc,{isOpen:et,data:Ee,isLocking:xe,lockError:ne,onContinue:dt,onClose:()=>ut(!1),primaryColor:B,fontFamily:R,dark:D}),De&&kt&&r.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:D?"rgba(0, 0, 0, 0.45)":"rgba(255, 255, 255, 0.55)",backdropFilter:"blur(2px)",WebkitBackdropFilter:"blur(2px)",borderRadius:U},children:r.jsx(Zs,{type:"lock",showStepBreakdown:!1,isOpen:!!De&&De.overallStatus!=="processing",isProcessing:xe||De?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{it(),vt(!1),dt()},onNewTx:()=>{it(),vt(!1),q(null),He.current=null,qe(),_e()},onClose:()=>{it(),vt(!1)},onComplete:()=>{it(),vt(!1),q(null),He.current=null,qe(),_e()},results:De?.overallStatus==="success"||De?.overallStatus==="failed"?De.steps.map($=>({asset:{symbol:H?.asset?.symbol||o,address:H?.asset?.address||""},txHash:$.transactionHash||"",success:$.status==="success",amount:H?.amount})):void 0,chainId:d,theme:I,styles:k,dark:D})})]})})};function Nr(e){const t=c.useContext(p.SpiceFlowProviderContext),n=t?.embeddedWalletAddress,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{...dr(s,o),embeddedWalletAddress:n}}var qc="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 Qc=({appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,showUsdSummary:a=!0,address:i,dk:l,dark:u=!1,showModeToggle:d,isEmbeddedMode:m=!0,onModeToggle:f})=>{const[h,x]=c.useState(!1),g=async()=>{i&&await p.copyToClipboard(i)&&(x(!0),setTimeout(()=>x(!1),2e3))},y=t==="active",C=n||(y?"Active":"Inactive"),v=y?"#10b981":"#9ca3af",b=r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[r.jsxs("div",{children:[r.jsx("strong",{children:"Embedded:"})," Deposit assets into ",e," account and use them here."]}),r.jsxs("div",{children:[r.jsx("strong",{children:"External:"})," Use assets from your connected wallet here."]})]});return r.jsxs("div",{children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[r.jsxs("div",{style:{fontSize:"13px",fontWeight:600,color:l.textPrimary},children:[e," Account"]}),d?r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[r.jsxs("button",{onClick:f,style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:u?l.hoverBg:"#f3f4f6",border:u?`1px solid ${l.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"11px",fontWeight:600,fontFamily:p.font.mono,color:l.textSecondary,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease",letterSpacing:"0.02em"},children:[r.jsx("span",{children:m?"Embedded":"External"}),r.jsx("img",{src:qc,alt:"","aria-hidden":"true",style:{width:"11px",height:"11px",display:"block",...u?{filter:"invert(0.65)"}:{}}})]}),r.jsx(_o,{content:b,label:"Account mode info",textColor:u?l.textPrimary:"#f9fafb",backgroundColor:u?l.cardBg:"#111827",borderColor:u?l.cardBorder:"rgba(255,255,255,0.08)",accentColor:u?l.textSecondary:"#6b7280",children:r.jsx("img",{src:Ks,alt:"","aria-hidden":"true",style:{width:"12px",height:"12px",display:"block",...u?{filter:"invert(0.65)"}:{}}})})]}):r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:u?l.hoverBg:y?"#ecfdf5":"#f3f4f6",border:u?`1px solid ${l.cardBorder}`:y?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[r.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:v}}),r.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:u?l.textSecondary:y?"#065f46":"#6b7280"},children:C})]})]}),a&&r.jsx("div",{style:{fontSize:"28px",fontWeight:700,color:l.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:p.formatUsd(s)}),a&&o&&r.jsx("div",{style:{fontSize:"12px",color:l.textSecondary,marginBottom:"8px"},children:o}),i&&r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[r.jsx("span",{style:{fontSize:"12px",fontFamily:p.font.mono,color:u?l.textSecondary:"#9ca3af"},children:p.truncateAddress(i)}),r.jsx("button",{onClick:g,style:{padding:"2px 6px",fontSize:"10px",fontWeight:500,backgroundColor:"transparent",color:u?l.textSecondary:"#9ca3af",border:"none",cursor:"pointer",borderRadius:"4px",transition:"background-color 150ms ease, color 150ms ease"},title:"Copy address",children:h?"Copied":"Copy"})]})]})},Kc=c.memo(Qc),Yc=({pendingDeposits:e,onCompleteDeposit:t,dk:n,dark:s=!1})=>e.length===0?null:r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:"Pending Deposits"}),r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((o,a)=>{const i=p.getChainConfig(o.chainId)?.displayName||`Chain ${o.chainId}`;return r.jsxs("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:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[r.jsx("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)}),r.jsxs("div",{children:[r.jsxs("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:[o.amount," ",o.tokenSymbol]}),r.jsxs("div",{style:{fontSize:"11px",color:n.warningText},children:["on ",i]})]})]}),r.jsx("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}-${a}`)})})]}),Zc=c.memo(Yc),Gc=e=>`${e.tokenAddress}-${e.chainId}`,Xc=({spiceAssets:e,loading:t,dk:n,dark:s=!1,canDirectWithdraw:o=!1,onDirectWithdraw:a,directWithdrawState:i})=>{const l={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},u={backgroundColor:n.cardBg,border:s?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return t?r.jsxs("div",{children:[r.jsx("div",{style:l,children:"Idle Balances"}),[1,2].map(d=>r.jsx("div",{style:{...u,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},d))]}):e.length===0?r.jsxs("div",{children:[r.jsx("div",{style:l,children:"Idle Balances"}),r.jsx("div",{style:{...u,padding:"16px",textAlign:"center",fontSize:"13px",color:s?n.textSecondary:"#9ca3af"},children:"No assets yet. Deposit to get started."})]}):r.jsxs("div",{children:[r.jsx("div",{style:l,children:"Idle Balances"}),r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((d,m)=>{const f=p.getChainConfig(d.chainId),h=d.chainDisplayName||f?.displayName||`Chain ${d.chainId}`,x=d.tokenDisplaySymbol||d.tokenDisplayName||d.tokenSymbol,g=Gc(d),y=o&&d.directWithdraw&&!!a,C=i?.key===g?i:null,v=C?.step==="pending";return r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...u},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[d.logoURI?r.jsx("img",{src:d.logoURI,alt:d.tokenSymbol,style:{width:"24px",height:"24px",borderRadius:"50%"}}):r.jsx("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:x.charAt(0)}),r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:x}),r.jsx("div",{style:{fontSize:"11px",color:s?n.textSecondary:"#9ca3af"},children:h})]})]}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[r.jsxs("div",{style:{textAlign:"right"},children:[r.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:p.formatBalance(d.balanceFormatted)}),r.jsx("div",{style:{fontSize:"11px",color:C?.step==="error"?n.errorText:s?n.textSecondary:"#9ca3af"},children:C?.step==="error"?C.message||"Withdraw failed":p.formatUsd(d.usdValue)})]}),y&&r.jsx("button",{onClick:()=>!v&&a(d),disabled:v,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:v?"default":"pointer",opacity:v?.6:1,whiteSpace:"nowrap"},children:v?"Withdrawing\u2026":"Withdraw"})]})]},`${d.tokenAddress}-${d.chainId}-${m}`)})})]})},Jc=c.memo(Xc),$c=({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 r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:t.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:e.title}),r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.items.map((o,a)=>r.jsxs("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:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[o.tokenLogoURI?r.jsx("img",{src:o.tokenLogoURI,alt:o.tokenSymbol,style:{width:"20px",height:"20px",borderRadius:"50%"}}):r.jsx("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)}),r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:t.textPrimary},children:o.tokenSymbol}),r.jsx("div",{style:{fontSize:"11px",color:t.textSecondary},children:o.label})]})]}),r.jsx("div",{style:{fontSize:"13px",fontWeight:600,color:s(o.valueColor)},children:o.displayValue})]},a))})]})},_c=c.memo($c),ed=({onDepositClick:e,onWithdrawClick:t,depositDisabled:n=!1,withdrawDisabled:s=!1,primaryColor:o="#EA4B4B",dark:a=!1})=>!e&&!t?null:r.jsxs("div",{style:{display:"flex",gap:"8px"},children:[e&&r.jsx(p.Button,{variant:"outline",onClick:e,disabled:n,dark:a,styles:{button:{backgroundColor:o}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&r.jsx(p.Button,{variant:"outline",onClick:t,disabled:s,dark:a,styles:{button:{backgroundColor:o}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),td=c.memo(ed),nd=({appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,showUsdSummary:a,address:i,spiceAssets:l,spiceAssetsLoading:u,pendingDeposits:d,customSections:m,notice:f,onDepositClick:h,onWithdrawClick:x,depositDisabled:g,onCompleteDeposit:y,primaryColor:C,dk:v,dark:b=!1,showModeToggle:M,isEmbeddedMode:w,onModeToggle:k,showConnectExternalCta:j,onConnectExternalWallet:I,connectExternalError:D,showHowItWorks:B=!0,canDirectWithdraw:S,onDirectWithdraw:R,directWithdrawState:F})=>{const[T,K]=c.useState(!1);return r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[r.jsx(Kc,{appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,showUsdSummary:a,address:i,dk:v,dark:b,showModeToggle:M,isEmbeddedMode:w,onModeToggle:k}),f&&r.jsx("div",{style:{padding:"10px 12px",borderRadius:"8px",backgroundColor:f.tone==="warning"?b?"rgba(245, 158, 11, 0.12)":"#fffbeb":f.tone==="success"?b?"rgba(16, 185, 129, 0.12)":"#ecfdf5":v.cardBg,border:f.tone==="warning"?b?"1px solid rgba(245, 158, 11, 0.35)":"1px solid #fde68a":f.tone==="success"?b?"1px solid rgba(16, 185, 129, 0.35)":"1px solid #a7f3d0":b?`1px solid ${v.cardBorder}`:"1px solid #e5e7eb",color:f.tone==="warning"?b?"#fbbf24":"#92400e":f.tone==="success"?b?"#34d399":"#047857":v.textSecondary,fontSize:"12px",lineHeight:1.45,fontWeight:500},children:f.message}),j&&r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[r.jsx("button",{onClick:I,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:C||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:p.font.ui,transition:"opacity 150ms ease"},children:"Connect External Wallet"}),D&&r.jsx("span",{style:{fontSize:"11px",color:b?v.errorText:"#b91c1c",lineHeight:1.4},children:D})]}),r.jsx("div",{style:{height:"1px",backgroundColor:b?"#2d2d2d":"#e5e7eb"}}),r.jsx(td,{onDepositClick:h,onWithdrawClick:x,depositDisabled:g,primaryColor:C,dark:b}),B&&r.jsxs("div",{children:[r.jsxs("button",{onClick:()=>K(!T),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:v.cardBg,border:b?`1px solid ${v.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:v.textSecondary,fontSize:"12px",fontWeight:500},children:[r.jsx("span",{children:"How It Works"}),r.jsx("span",{style:{transform:T?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),T&&r.jsxs("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:b?v.cardBg:"#f0fdf4",border:b?`1px solid ${v.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:b?v.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),r.jsx(Zc,{pendingDeposits:d,onCompleteDeposit:y,dk:v,dark:b}),r.jsx(Jc,{spiceAssets:l,loading:u,dk:v,dark:b,canDirectWithdraw:S,onDirectWithdraw:R,directWithdrawState:F}),m.map((N,W)=>r.jsx(_c,{section:N,dk:v,dark:b},W))]})},sd=c.memo(nd);function od(e){return!!e.embeddedAddress&&!!e.externalAddress}function rd(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:A.SPICE_GAS_FEE_RECIPIENT,amount:n.gasBridge}),n.spicenetFee>0n&&o.push({recipient:A.SPICE_PLATFORM_FEE_RECIPIENT,amount:n.spicenetFee}),o}const ad=new Set([A.SPICE_GAS_FEE_RECIPIENT,A.SPICE_PLATFORM_FEE_RECIPIENT].map(e=>e.toLowerCase()));function id(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:ad.has(n.recipient.toLowerCase())?tn(n.amount,o.amount,100n):!0})}function Wr(e,t,n){return{chainId:e,domain:"evm",tokenTransfers:[],calls:n.filter(s=>s.amount>0n).map(s=>({to:t,value:0n,data:E.encodeFunctionData({abi:E.erc20Abi,functionName:"transfer",args:[s.recipient,s.amount]})}))}}function ld(e,t){const n=e.intents.flatMap(o=>o.batches).filter(o=>Dt(o).totalFee>0n),s=n.filter(o=>o.chainId===t);return(s.length>0?s:n)[0]??null}function cd(e,t,n,s){const o=ld(s,e),{gasFee:a,bridgeFee:i,spicenetFee:l}=o?Dt(o):{gasFee:0n,bridgeFee:0n,spicenetFee:0n};return rd(t,n,{gasBridge:a+i,spicenetFee:l})}function dd(){const{execute:e}=gn(),t=c.useContext(p.SpiceFlowProviderContext)?.embeddedWalletAddress,{embeddedAddress:n}=p.useProviderWallets(),s=t||n;return{withdraw:c.useCallback(async({tokenAddress:o,chainId:a,balance:i,recipient:l,onProgress:u})=>{const d=o,m=l;if(i<=0n)throw new Error("Nothing to withdraw.");const f=[Wr(a,d,[{recipient:m,amount:i}])];let h=null;return e(f,d,0n,u,void 0,{useCustomTransfers:!0,userOverride:s,adjustBatchesForEstimate:({feeEstimate:x})=>{const g=cd(a,m,i,x);return id(h,g)?null:(h=g,[Wr(a,d,g)])}})},[e,s])}}const to=380,dn=8,ud=[];function Or(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function pd(e,t){const n=new Map;Object.entries(t).forEach(([o,a])=>{if(!Number.isFinite(a)||a<=0)return;n.set(o,a),n.set(o.toUpperCase(),a);const i=Or(o);i&&n.set(i,a)});const s=[e.symbol,e.displaySymbol,e.receiptTokenName,e.name,e.displayName];for(const o of s){if(!o)continue;const a=n.get(o)??n.get(o.toUpperCase());if(a!==void 0)return a;const i=Or(o);if(!i)continue;const l=n.get(i);if(l!==void 0)return l}return 0}const fd=({appName:e="Spice",status:t="active",statusLabel:n,customSections:s=ud,extraAssets:o=[],tokenPrices:a={},breakdownLabels:i=[],notice:l,styles:u,dark:d=!1,onDepositSuccess:m,onDepositClick:f,onWithdrawClick:h,onCompleteDeposit:x,showModeToggle:g=!1,defaultMode:y,showUsdSummary:C=!0})=>{const v=c.useContext(p.SpiceFlowProviderContext),b=v?.mode!=="7702",M=!!v?.isWhitelistGateActive,w=!!v?.isWhitelistConfigured&&v?.isUserWhitelisted!==!0,k=c.useRef(!1);c.useEffect(()=>{if(!k.current){if(p.hasStoredSpiceFlowMode()){k.current=!0;return}y&&v?.setMode&&(v.setMode(y==="non7702"?"ondemand":"7702"),k.current=!0)}},[v,y]);const[j,I]=c.useState(!1),[D,B]=c.useState(null),[S,R]=c.useState({top:0,bottom:0,left:0,placement:"below"}),F=c.useRef(null),T=c.useRef(null),{address:K,isConnected:N}=p.useWallet(),W=v?.embeddedWalletAddress,P=v?.externalWalletAddress,{embeddedAddress:O}=p.useProviderWallets(),{dark:L,primaryColor:U,dk:Z}=p.useSpiceBrand(u,d),X=b&&!P,V=!b||X,ee=V?W||O:K,H=c.useMemo(()=>v?.supportedChainIds??A.getChainIdsByNetwork("mainnet"),[v?.supportedChainIds]),{assets:q,loading:ie}=Bn({address:ee,supportedChains:H,enabled:!!ee&&V,refetchInterval:3e4}),pe=c.useMemo(()=>{const ye=V?q.map(Ce=>{const Be=Ce.balanceUsd||0,ft=Number.isFinite(Ce.balanceFormatted)?Ce.balanceFormatted:0,yt=Be>0?Be:pd(Ce,a)*ft;return{tokenAddress:Ce.address,tokenSymbol:Ce.symbol,tokenDisplaySymbol:As(Ce),tokenDisplayName:Ci(Ce),tokenDecimals:Ce.decimals,chainId:Ce.chainId,chainDisplayName:Es(Ce),balance:Ce.balance.toString(),balanceFormatted:Ce.balanceFormatted,usdValue:yt,logoURI:Ce.logoURI}}):[],Fe=X?[]:o;return[...ye,...Fe].filter(Ce=>Ce.balanceFormatted>0)},[V,X,q,a,o]),_=c.useMemo(()=>pe.reduce((ye,Fe)=>ye+Fe.usdValue,0),[pe]),{pendingDeposits:ve}=Nr({chainIds:H,enabled:!!K,discoverWalletBalances:!0}),xe=c.useMemo(()=>s.reduce((ye,Fe)=>ye+Fe.totalValue,0),[s]),ue=_+xe,We=c.useMemo(()=>{const ye=[];_>0&&ye.push(`${p.formatUsd(_)} idle`);for(const Fe of s){const Ce=i.find(Be=>Be.sectionTitle===Fe.title)?.label||Fe.title.toLowerCase();ye.push(`${p.formatUsd(Fe.totalValue)} ${Ce}`)}return ye.join(" \xB7 ")},[_,s,i]),z=c.useCallback(ye=>{x?x(ye):B(ye)},[x]),fe=c.useCallback(()=>{B(null)},[]),le=c.useCallback(()=>{B(null),m?.()},[m]),te=c.useCallback(()=>{if(!F.current)return;const ye=F.current.getBoundingClientRect(),Fe=window.innerHeight-ye.bottom-dn,Ce=ye.top-dn,Be=Fe>=400||Fe>=Ce?"below":"above",ft=Math.max(dn,Math.min(ye.right-to,window.innerWidth-to-dn)),yt=Be==="below"?ye.bottom+dn:ye.top-dn,De=Be==="above"?window.innerHeight-yt:0;R({top:yt,bottom:De,left:ft,placement:Be})},[]);c.useLayoutEffect(()=>{j&&te()},[j,te]),c.useEffect(()=>{if(!j)return;const ye=Be=>{F.current&&!F.current.contains(Be.target)&&T.current&&!T.current.contains(Be.target)&&I(!1)},Fe=Be=>{Be.key==="Escape"&&I(!1)},Ce=()=>te();return document.addEventListener("mousedown",ye),document.addEventListener("keydown",Fe),window.addEventListener("scroll",Ce,{passive:!0}),window.addEventListener("resize",te),()=>{document.removeEventListener("mousedown",ye),document.removeEventListener("keydown",Fe),window.removeEventListener("scroll",Ce),window.removeEventListener("resize",te)}},[j,te]);const Q=V?W||O||K:P||K,se=c.useCallback(()=>{v?.setMode&&v.setMode(V?"ondemand":"7702")},[v,V]),[me,J]=c.useState(null);let he=null;try{he=wo.useConnectWallet({onSuccess:()=>J(null),onError:ye=>J(p.sanitizeError(ye,"Failed to connect wallet."))}).connectWallet}catch{he=null}const Ue=c.useCallback(()=>{he&&(I(!1),J(null),he({walletChainType:"ethereum-only"}))},[he]),Re=!P&&!!he,kt=c.useCallback(()=>{I(!1),f?.()},[f]),vt=c.useCallback(()=>{I(!1),h?.()},[h]),et=c.useCallback(ye=>{I(!1),z(ye)},[z]),{withdraw:ut}=dd(),[Ee,Ve]=c.useState(null),rt=od({embeddedAddress:W||O,externalAddress:P}),at=c.useCallback(async ye=>{if(!P)return;const Fe=`${ye.tokenAddress}-${ye.chainId}`;Ve({key:Fe,step:"pending"});try{await ut({tokenAddress:ye.tokenAddress,chainId:ye.chainId,balance:BigInt(ye.balance),recipient:P}),Ve(null)}catch(Ce){Ve({key:Fe,step:"error",message:p.sanitizeError(Ce,"Withdraw failed")})}},[ut,P]);if(typeof window>"u")return null;const re=r.jsxs("button",{ref:F,onClick:()=>I(!j),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:L?Z.hoverBg:"#ffffff",border:L?`1px solid ${Z.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:p.font.ui,color:L?Z.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:L?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[r.jsxs("span",{children:[e," Account"]}),N&&C&&r.jsxs("span",{style:{color:L?Z.textSecondary:"#6b7280"},children:["\xB7 ",p.formatUsd(ue)]}),r.jsx("span",{style:{fontSize:"10px",color:L?Z.textSecondary:"#9ca3af",transform:j?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),pt=j?wn.createPortal(r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:p.z.popover},onClick:()=>I(!1)}),r.jsx("div",{ref:T,style:{position:"fixed",top:S.placement==="below"?`${S.top}px`:"auto",bottom:S.placement==="above"?`${S.bottom}px`:"auto",left:`${S.left}px`,width:`${to}px`,maxWidth:`calc(100vw - ${dn*2}px)`,maxHeight:"80vh",backgroundColor:L?Z.shell:"#ffffff",border:L?`1px solid ${Z.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:L?"0 10px 40px rgba(0, 0, 0, 0.5)":"0 10px 40px rgba(0, 0, 0, 0.12)",zIndex:p.z.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${p.easing.out}`},children:r.jsx(sd,{appName:e,status:t,statusLabel:n,totalUsdValue:ue,breakdownSubtitle:We,showUsdSummary:C,address:V?Q:K,spiceAssets:pe,spiceAssetsLoading:ie,pendingDeposits:ve,customSections:s,notice:l,onDepositClick:f?kt:void 0,onWithdrawClick:h?vt:void 0,depositDisabled:w,onCompleteDeposit:et,primaryColor:U,dk:Z,dark:L,showModeToggle:g,isEmbeddedMode:V,onModeToggle:se,showConnectExternalCta:Re,onConnectExternalWallet:Ue,connectExternalError:me,showHowItWorks:!M,canDirectWithdraw:rt,onDirectWithdraw:at,directWithdrawState:Ee})}),r.jsx("style",{children:`
|
|
81
81
|
@keyframes accountDisplayFadeIn {
|
|
82
82
|
from { opacity: 0; transform: translateY(-4px); }
|
|
83
83
|
to { opacity: 1; transform: translateY(0); }
|