@spicenet-io/spiceflow-ui 4.1.6 → 4.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +2 -2
package/dist/index.cjs.js
CHANGED
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
transform: translateY(0);
|
|
28
28
|
}
|
|
29
29
|
}
|
|
30
|
-
`})]})};async function wi(e,t,n){let s=null;try{const r=await e.request({method:"eth_chainId"});s=parseInt(r,16)}catch{s=null}s!==t&&(n?.(),await p.ensureWalletOnChain(e,t))}async function xn(e){const t=e.provider??await e.wallet?.getEthereumProvider();if(!t)throw new Error("External wallet provider not available");await wi(t,e.chainId,e.onSwitch);const n=p.getChainConfig(e.chainId)?.viemChain;return{extWc:D.createWalletClient({account:e.account,chain:n,transport:D.custom(t)}),viemChain:n}}async function Ro(e){let t;for(const n of e.calls){const s=await e.extWc.sendTransaction({to:n.to,data:n.data,value:n.value,chain:e.viemChain});if((await e.client.waitForTransactionReceipt({hash:s,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error(e.errorMessage);t=s}return t}function Do(e,t){return t.isNative?e.sendTransaction({to:t.recipient,value:t.amount,chain:t.viemChain}):e.sendTransaction({to:t.tokenAddr,data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"transfer",args:[t.recipient,t.amount]}),chain:t.viemChain})}async function js(e){const{extWc:t,sourceClient:n,recipient:s,tokenAddr:r,isNative:a,amount:i}=e;if(i<=0n)return;const d=await Do(t,{recipient:s,tokenAddr:r,isNative:a,amount:i,viemChain:e.viemChain});if((await n.waitForTransactionReceipt({hash:d,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Embedded wallet funding failed")}const Mo="spiceflow:pendingDeposit",Kn="spiceflow:pendingDepositChanged";function Wo(e,t,n){return`${Mo}:${e.toLowerCase()}:${t}:${n.toLowerCase()}`}function Fs(){try{const e="__spiceflow_storage_test__";return localStorage.setItem(e,"1"),localStorage.removeItem(e),!0}catch{return!1}}function ki(e){if(!Fs())return;const t=Wo(e.embeddedWalletAddress,e.chainId,e.tokenAddress);try{localStorage.setItem(t,JSON.stringify(e)),window.dispatchEvent(new Event(Kn))}catch(n){console.error("[pendingDeposit] Failed to save:",n)}}function vi(e){if(!Fs())return[];const t=`${Mo}:${e.toLowerCase()}:`,n=[],s=Date.now();for(let r=0;r<localStorage.length;r++){const a=localStorage.key(r);if(!(!a||!a.startsWith(t)))try{const i=localStorage.getItem(a);if(!i)continue;const d=JSON.parse(i);if(s-d.timestamp>6048e5){localStorage.removeItem(a);continue}n.push(d)}catch{localStorage.removeItem(a)}}return n}function Bs(e,t,n){if(!Fs())return;const s=Wo(e,t,n);localStorage.removeItem(s),window.dispatchEvent(new Event(Kn))}function Si({sourceChainId:e,selectedAsset:t,destinationChainId:n,destinationTokenAddress:s,isCrossDenomination:r,convertedUsdAmount:a}){const i=B.normalizeNativeTokenAddress(t.asset.address),d=s;let u,c;if(d&&n)if(u=p.CHAIN_CONFIGS[n]?.supportedTokens?.find(f=>p.addressesEqual(f.address,d))?.decimals??t.asset.decimals,r){if(!a)throw new Error("Destination amount is still being calculated. Please retry in a moment.");c=a}else{const f=D.parseUnits(t.amount,t.asset.decimals);c=B.convertAmountBetweenDecimals(f,t.asset.decimals,u)}return{sourceChainId:e,depositTokenAddress:i,depositAmount:t.amount,depositTokenDecimals:t.asset.decimals,destinationChainId:n,destinationTokenAddress:d,destinationAmount:c,destinationTokenDecimals:u}}async function Ai(e,t){if(!e)return[];if(Array.isArray(e))return e;const n=e;return e.length>=2?n(t.depositAmount,t.depositTokenAddress):n(t)}async function Ts(e,t){const n=await Do(e,{recipient:t.recipient,tokenAddr:t.tokenAddr,isNative:t.isNative,amount:t.amount});t.afterSend?.(n);const s=p.getClientForChain(t.chainId),r=await s.waitForTransactionReceipt({hash:n,timeout:12e4,pollingInterval:2e3,confirmations:2});if(r.status!=="success")throw new Error(t.failureMessage);return t.settle&&await s.getBlockNumber()-r.blockNumber<2n&&await qt(3e3),r.transactionHash}async function Ii(e){const t=e.selectedDepositAssets.filter(s=>s.asset&&s.amount&&parseFloat(s.amount)>0);if(t.length===0){console.error("[DepositModal] No valid assets for deposit"),e.setError("Please select an asset and enter an amount");return}if(!e.escrowOnly&&!e.sourceAddress){e.setError("External wallet not connected. Please connect your wallet in the previous step.");return}if(!e.isNon7702){if(!e.address||!e.embeddedWalletAddress){e.setError("Couldn't find your account wallet. Try reconnecting.");return}if(!e.isReady||!e.isAuthenticated){e.setError("Sign in to continue.");return}}if(e.zeroCreditError){e.setError(e.zeroCreditError);return}if(e.depositBalanceError){e.setError(e.depositBalanceError);return}e.setIsExecuting(!0),e.setError(null);let n=!1;try{const s=t[0].asset.chainId,r=B.getEscrowContractAddress(s);let a=e.externalWalletClient;if(!e.escrowOnly){if(!a)throw new Error("External wallet not connected");if(e.externalProvider){const i=await xn({provider:e.externalProvider,account:e.sourceAddress,chainId:s});i.viemChain&&(a=i.extWc)}}if(e.isNon7702){if(!a)throw new Error("External wallet not connected");if(!e.sourceAddress)throw new Error("External wallet address not available");if(e.nativeChainId&&s===e.nativeChainId){const i=p.getChainConfig(s),d=t.map(c=>`${c.amount} ${c.asset.symbol}`).join(", ");e.setConfirmationData({network:i?.displayName||`Chain ${s}`,amount:d,symbol:"",chainId:s}),e.setShowConfirmation(!0);let u=null;e.setDirectDepositStatus("processing"),e.setDirectDepositChainId(s);for(const c of t){const f=D.parseUnits(c.amount,c.asset.decimals),h=B.normalizeNativeTokenAddress(c.asset.address),g=c.asset.isNative||B.isNativeToken(h),x=await Ts(a,{chainId:s,recipient:r,tokenAddr:h,isNative:g,amount:f,failureMessage:`Escrow deposit failed for ${c.asset.symbol}`});u=x,e.setDirectDepositTxHash(x)}if(t[0]?.amount){const c=t[0].amount;if(e.onDepositExecute){e.setPostDepositStatus("executing");try{await e.onDepositExecute(c),e.setPostDepositStatus("success")}catch(h){console.error("ctx.onDepositExecute failed:",h),e.setPostDepositStatus("error"),e.setPostDepositError(h?.message||"Post-deposit instruction failed")}}else e.setPostDepositStatus("success");e.setDirectDepositStatus("success"),e.setPostDepositAmount(c),e.setPostDepositSuccess(!0);const f={type:"deposit",status:"success",amount:c,asset:t[0].asset.symbol,sourceChain:i?.displayName||`Chain ${s}`,txHash:u??void 0};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:f})),e.onDepositSuccess?.(f)}e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset)}else{const i=e.destinationChainId||e.nativeChainId;if(!i)throw new Error("Destination chain ID is required for non-7702 mode. Either pass ctx.destinationChainId to <SpiceDeposit> or set ctx.nativeChainId on <SpiceFlowProvider>.");const d=p.getDelegateContractAddress(s),u=r,c=[];let f=null;for(const h of t){const g=D.parseUnits(h.amount,h.asset.decimals),x=B.normalizeNativeTokenAddress(h.asset.address),m=h.asset.isNative||B.isNativeToken(x),y=await Ts(a,{chainId:s,recipient:u,tokenAddr:x,isNative:m,amount:g,failureMessage:`Transfer failed for ${h.asset.symbol}`,afterSend:C=>{f||(f=C)},settle:!0});e.depositDataRef.current||(e.depositDataRef.current=[]),e.depositDataRef.current.push({txHash:y,sender:e.sourceAddress,tokenAddress:x,chainId:s,amount:g.toString(),user:e.spiceBalanceUser}),c.push({tokenAddress:x,tokenAmount:g.toString(),sender:e.sourceAddress,receiver:u})}if(!f)throw new Error("No transaction hash generated");if(!e.destinationTokenAddress){const h={type:"deposit",status:"success",amount:t[0]?.amount,asset:t[0]?.asset?.symbol,sourceChain:p.getChainName(s),txHash:f};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:h})),e.onDepositSuccess?.(h),e.depositDataRef.current=null,e.bridgedAmountRef.current=t[0]?.amount||null,e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset),e.setShowConfirmation(!1);return}if(e.sponsorGas&&e.nativeChainId){const h=D.parseUnits("0.05",18);c.push({tokenAddress:B.ZERO_ADDRESS,tokenAmount:h.toString(),sender:e.sourceAddress,receiver:u})}if(e.mode==="ondemand"){const h={to:d,value:BigInt(0),data:"0x"},g=await p.getTokenDecimals(i,e.destinationTokenAddress);let x=BigInt(0);for(const T of c){const I=BigInt(T.tokenAmount),F=B.normalizeNativeTokenAddress(T.tokenAddress),j=t.find(E=>{const S=B.normalizeNativeTokenAddress(E.asset.address);return p.addressesEqual(S,F)}),A=j?j.asset.decimals:await p.getTokenDecimals(s,B.ZERO_ADDRESS);x+=B.convertAmountBetweenDecimals(I,A,g)}e.isCrossDenomination&&e.convertedUsdAmount&&(x=e.convertedUsdAmount);const m={chainId:s,tokenTransfers:c.map(T=>({from:T.sender,to:T.receiver,token:T.tokenAddress,amount:BigInt(T.tokenAmount)})),call:h},y=e.isCrossDenomination&&e.convertedUsdAmount?[{from:e.sourceAddress,to:r,token:B.normalizeNativeTokenAddress(t[0].asset.address),amount:D.parseUnits(t[0].amount,t[0].asset.decimals)}]:[],C={chainId:i,tokenTransfers:[...y,{from:"escrow",to:e.sourceAddress,token:e.destinationTokenAddress,amount:x}],call:{to:e.destinationTokenAddress,value:BigInt(0),data:"0x"}},k={mode:"non-7702:on-demand",chainBatches:[m,C]},b={user:e.sourceAddress,intents:[k]},R=await p.relayerService.createAction(b),v=R.actionId,w=R.intentIds[0];if(!f)throw new Error("No transaction hash available");e.startStatusPolling(w,p.createInitialSteps([{chainId:s,calls:[h]},{chainId:i,calls:[C.call]}],T=>p.getChainName(T))),await p.relayerService.executeStep(v,0,0,{action:"execute",hash:f}),t[0]?.amount&&(e.bridgedAmountRef.current=t[0].amount),e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset),e.setShowConfirmation(!1)}else throw new Error("Presign mode not yet fully supported for cross-chain deposits")}}else{const i=[],d=t[0],u=d&&t.length===1&&e.effectiveDepositFee&&e.effectiveDepositFee.chainId===s&&p.addressesEqual(e.effectiveDepositFee.token,B.normalizeNativeTokenAddress(d.asset.address))?D.formatUnits(e.effectiveDepositFee.net,d.asset.decimals):d?.amount;for(const b of t){const R=D.parseUnits(b.amount,b.asset.decimals),v=t.length===1&&!!e.effectiveDepositFee&&e.effectiveDepositFee.chainId===s&&p.addressesEqual(e.effectiveDepositFee.token,B.normalizeNativeTokenAddress(b.asset.address)),w=v?e.effectiveDepositFee.fee:0n,T=v?e.effectiveDepositFee.net:R,I=e.escrowOnly?R:R+w,F=B.normalizeNativeTokenAddress(b.asset.address),j=b.asset.isNative||B.isNativeToken(F);e.escrowOnly||await Ts(a,{chainId:s,recipient:e.address,tokenAddr:F,isNative:j,amount:I,failureMessage:`Transfer to embedded wallet failed for ${b.asset.symbol}`,afterSend:()=>ki({chainId:s,tokenAddress:B.normalizeNativeTokenAddress(b.asset.address),tokenSymbol:b.asset.symbol,tokenDecimals:b.asset.decimals,amount:b.amount,rawAmount:R.toString(),embeddedWalletAddress:e.address,externalWalletAddress:e.sourceAddress,timestamp:Date.now(),isNative:j}),settle:!0}),i.push(j?{to:r,value:T,data:"0x"}:{to:F,value:BigInt(0),data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"transfer",args:[r,T]})}),w>0n&&i.push(j?{to:B.SPICE_GAS_FEE_RECIPIENT,value:w,data:"0x"}:{to:F,value:BigInt(0),data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"transfer",args:[B.SPICE_GAS_FEE_RECIPIENT,w]})})}const c=await p.getClientForChain(s).getBlockNumber(),f=i.map(b=>({...b,to:D.getAddress(b.to)})),h={chainId:s,recentBlock:c,calls:f,tokenTransfers:[]},g=Si({sourceChainId:s,selectedAsset:d&&u?{...d,amount:u}:t[0],destinationChainId:e.destinationChainId,destinationTokenAddress:e.destinationTokenAddress,isCrossDenomination:e.isCrossDenomination,convertedUsdAmount:e.convertedUsdAmount}),x=await Ai(e.depositBatches,g),m=[h,...x];if(!e.address)throw new Error("Address not available");const y=[];if(e.isCrossDenomination&&e.convertedUsdAmount&&e.destinationTokenAddress){const b=e.selectedDepositAssets[0]?.asset;if(b){const R=D.parseUnits(e.selectedDepositAssets[0].amount,b.decimals);y.push({from:e.address,to:r,token:B.normalizeNativeTokenAddress(b.address),amount:R}),y.push({from:"escrow",to:e.address,token:e.destinationTokenAddress,amount:e.convertedUsdAmount})}}y.length>0&&m[1]&&(m[1].tokenTransfers=y);const C=p.createInitialSteps(m,b=>p.getChainName(b));let k=!1;if(await e.execution.execute(m,B.ZERO_ADDRESS,0n,b=>{if(b.intentId&&!k){k=!0;for(const R of t)Bs(e.address,s,B.normalizeNativeTokenAddress(R.asset.address));e.startStatusPolling(b.intentId,C)}},void 0,{userOverride:e.address,useCustomTransfers:!0,skipPreSubmitFeeEstimate:!0,skipUserFundingPreflight:!0}),e.refreshAssets(),e.onDepositExecute&&t[0]?.amount)try{e.setPostDepositStatus("executing"),await e.onDepositExecute(u||t[0].amount),e.setPostDepositStatus("success"),e.setPostDepositAmount(u||t[0].amount),e.setPostDepositSuccess(!0)}catch(b){console.error("ctx.onDepositExecute failed (7702):",b),e.setPostDepositStatus("error"),e.setPostDepositError(b?.message||"Post-deposit instruction failed")}e.onDepositSelect&&e.onDepositSelect(t[0].asset)}}catch(s){n=!0,console.error("[DepositModal] executeDeposit CAUGHT ERROR:",s),console.error("[DepositModal] Error details:",{message:s?.message,code:s?.code,name:s?.name,stack:s?.stack?.slice(0,500)}),e.setError(p.sanitizeError(s,"Deposit failed")),e.clearStatus()}finally{e.setIsExecuting(!1),n&&e.setDirectDepositStatus("idle"),n||!e.getCurrentIntentStatus()&&e.getCurrentPostDepositStatus()!=="idle"||e.setShowConfirmation(!1)}}async function Ei(e){const{asset:t,assetIndex:n,selectedAssetCount:s,address:r,escrowOnly:a,isNon7702:i}=e;if(n!==0||i||s>1||!r||t.balance<=0n)return null;const d=await No({address:r,depositQuote:{asset:t,amount:t.balance,token:B.normalizeNativeTokenAddress(t.address),chainId:t.chainId},escrowOnly:a}),u=a?t.balance:t.balance>d.fee?t.balance-d.fee:0n;return So(u,t.decimals)}async function No(e){const{address:t,depositQuote:n,escrowOnly:s}=e,{asset:r,amount:a,token:i,chainId:d}=n,u=B.getEscrowContractAddress(d),c=r.isNative||B.isNativeToken(i),f=a>1n?1n:0n,h=[c?{to:u,value:a,data:"0x"}:{to:i,value:0n,data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"transfer",args:[u,a]})}];f>0n&&h.push(c?{to:B.SPICE_GAS_FEE_RECIPIENT,value:f,data:"0x"}:{to:i,value:0n,data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"transfer",args:[B.SPICE_GAS_FEE_RECIPIENT,f]})});const g={chainId:d,tokenTransfers:[],calls:h},x=(await p.relayerService.estimateBatchGas({user:t,outputToken:i,chainBatches:[{...g,hash:B.hashChainBatches([g])[0].hash}]})).gasFee,m=s&&x<a?a-x:a;return{fee:x,net:m,token:i,chainId:d}}const ji=({selectedDepositAssets:e,depositAssets:t,secondAssetOptions:n,loadingAssets:s,allowSecondAsset:r,theme:a,styles:i,dark:d,dk:u,onSelect:c,onAmountChange:f,onAdd:h,onRemove:g,resolveMaxAmount:x,onViewAllAssets:m})=>o.jsxs(o.Fragment,{children:[e.map((y,C)=>{const k=e.length===1?"Deposit":`Asset ${C+1}`;return o.jsxs("div",{style:{marginBottom:a.spacing.md,position:"relative"},children:[o.jsx(vn,{assets:C===0?t:n,selectedAsset:y||void 0,onAssetSelect:b=>c(b,C),onAmountChange:b=>f(b,C),loading:s,label:k,showBalance:!0,theme:a,styles:i,allowSecondAsset:r&&C===0,onAddAsset:h,canAddAsset:e.length===1&&!!e[0]?.asset,resolveMaxAmount:x?b=>x(b,C):void 0,onViewAllAssets:C===0?m:void 0}),C===1&&o.jsx("button",{onClick:()=>g(C),style:{position:"absolute",top:"-2px",right:"-2px",background:d?`${u.cardBg}ee`:"rgba(255, 255, 255, 0.9)",border:`1px solid ${u.cardBorder}`,borderRadius:"50%",cursor:"pointer",color:a.colors.textMuted,fontSize:"16px",padding:"2px",width:"22px",height:"22px",display:"flex",alignItems:"center",justifyContent:"center",transition:p.transition.interactive,boxShadow:"0 1px 3px rgba(0, 0, 0, 0.1)"},onMouseEnter:b=>{b.currentTarget.style.color=d?u.errorText:"#ef4444",b.currentTarget.style.background=d?u.cardBg:"#fff",b.currentTarget.style.borderColor=d?u.errorBorder:"#fecaca"},onMouseLeave:b=>{b.currentTarget.style.color=a.colors.textMuted,b.currentTarget.style.background=d?`${u.cardBg}ee`:"rgba(255, 255, 255, 0.9)",b.currentTarget.style.borderColor=d?u.cardBorder:"#e5e7eb"},title:"Remove asset",children:"\xD7"})]},`asset-${C}`)}),e.length===0&&o.jsx("div",{style:{marginBottom:a.spacing.md},children:o.jsx(vn,{assets:t,selectedAsset:void 0,onAssetSelect:y=>c(y,0),onAmountChange:y=>f(y,0),loading:s,label:"Deposit",showBalance:!0,theme:a,styles:i,allowSecondAsset:r,onAddAsset:h,canAddAsset:!1,resolveMaxAmount:x?y=>x(y,0):void 0},"initial-selector")})]}),Fi=l.memo(ji);var Rs="data:image/svg+xml,%3csvg width='10' height='10' viewBox='0 0 10 10' fill='none' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M5 4.99995V6.99995M5 3.31245V3.31189M9.5 5C9.5 7.48528 7.48528 9.5 5 9.5C2.51472 9.5 0.5 7.48528 0.5 5C0.5 2.51472 2.51472 0.5 5 0.5C7.48528 0.5 9.5 2.51472 9.5 5Z' stroke='black' stroke-opacity='0.4' stroke-linecap='round' stroke-linejoin='round'/%3e%3c/svg%3e";const Po=l.memo(({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,onDepositSelect:s,depositBatches:r,supportedChains:a,title:i,styles:d,onDepositAssetChange:u,assetInputHook:c,externalWalletAddress:f,onDepositAmountChange:h,allowSecondAsset:g=!1,destinationChainId:x,destinationTokenAddress:m,onDepositExecute:y,depositActionLabel:C,nativeChainId:k,sponsorGas:b=!1,preSelectedAsset:R,escrowOnly:v=!1,escrowTokenAddress:w,escrowAmount:T,escrowTokenDecimals:I,escrowTokenSymbol:F,onDepositSuccess:j,onDepositError:A,embeddedWalletAddress:E,onViewAllAssets:S})=>{const M=l.useContext(p.SpiceFlowProviderContext),U=M?.mode||"7702",W=M?.allowedTokens,O=!!M?.isWhitelistGateActive,z=!v&&!!M?.isWhitelistConfigured&&M?.isUserWhitelisted!==!0,N=c?.assetAmount||"",{theme:P,dark:Q,appName:K,primaryColor:V,dk:X}=p.useSpiceBrand(d),xe=p.useWallet(),{isReady:H,isAuthenticated:J}=xe,{externalWallet:se}=p.useProviderWallets(),ce=M?.embeddedWalletAddress||E,de=U!="7702",ve=de?!!f:H&&J&&!!ce,pe=ce,fe=f,Ee=pe??fe,{data:L}=Qt.useWalletClient(),[ee,te]=l.useState(L),oe=l.useRef(null),Z=l.useRef(se);Z.current=se;const ne=se?.address;l.useEffect(()=>{const q=Z.current;if(!q||!fe){oe.current=null,te(L);return}if(q.address?.toLowerCase()!==fe?.toLowerCase()){oe.current=null,te(L);return}q.getEthereumProvider().then(async ie=>{oe.current=ie;const Se=await ie.request({method:"eth_chainId"}),me=parseInt(Se,16),$e=p.getChainConfig(me),_e=await q.getWalletClient(me);te($e?D.createWalletClient({account:fe,chain:$e.viemChain,transport:D.custom(ie)}):_e)}).catch(()=>{oe.current=null,te(L)})},[ne,fe,L]);const ge=l.useRef(null),[G,Ie]=l.useState([]),{assets:ze,loading:Ke,error:Ft,refreshAssets:mt}=ls({address:v?pe:fe||pe,supportedChains:a,fetchBalances:is,enabled:e,refreshInterval:e?5e3:0}),Le=l.useMemo(()=>{if(O)return[];const q=a.flatMap(ie=>p.getAllAssetsForChain(ie,ze));return W&&W.length>0?q.filter(ie=>W.includes(ie.symbol.toLowerCase())||ie.isNative&&W.includes("native")).sort((ie,Se)=>{const me=ie.balance>BigInt(0)?1:0;return(Se.balance>BigInt(0)?1:0)-me}):q.filter(ie=>ie.balance>BigInt(0))},[a,ze,W,O]),le=l.useMemo(()=>{if(!G[0]?.asset)return[];const q=G[0].asset.chainId;return Le.filter(ie=>ie.chainId===q)},[Le,G]),[Ae,Xe]=l.useState(!1),[et,ae]=l.useState(null),nt=l.useRef(A);nt.current=A;const ke=l.useCallback(q=>{ae(q),typeof q=="string"&&q&&nt.current?.(q,p.getRelayerErrorDetail(q))},[]),[we,he]=l.useState("idle"),Me=l.useCallback(q=>{typeof q=="string"&&q&&nt.current?.(q,p.getRelayerErrorDetail(q))},[]),[xt,yt]=l.useState(!1),[Bt,Fe]=l.useState(null),[Ge,Ct]=l.useState("idle"),[kt,Tt]=l.useState(null),[Oe,st]=l.useState(null),[Mt,bt]=l.useState(null),[ue,He]=l.useState(null),[ot,ct]=l.useState(null),{intentStatus:be,startStatusPolling:gt,clearStatus:Rt,execute:Je}=mn(),Be=l.useCallback((q,ie)=>{const Se=p.CHAIN_CONFIGS[ie];return Se?Se.supportedTokens?.find(me=>p.addressesEqual(me.address,q))?.symbol??null:null},[]),rt=l.useMemo(()=>{const q=G[0]?.asset;if(!q||!m||!x)return!1;const ie=Be(m,x);return Aa(q.symbol)&&!!ie&&Ia(ie)},[G,m,x,Be]);l.useEffect(()=>{G.length>0&&N!==G[0]?.amount&&Ie(q=>{if(q.length===0)return q;const ie=[...q];return ie[0]={...ie[0],amount:N||""},ie})},[N]),l.useEffect(()=>{G.length!==0&&Ie(q=>{let ie=!1;const Se=q.map(me=>{if(!me.asset)return me;const $e=Le.find(_e=>_e.chainId===me.asset.chainId&&p.addressesEqual(_e.address,me.asset.address));return $e?$e===me.asset||$e.balance===me.asset.balance?me:(ie=!0,{...me,asset:$e,amount:me.amount}):me});return ie?Se:q})},[Le,G.length]),l.useEffect(()=>{if(!R||G.length>0||Le.length===0)return;const q=Le.find(ie=>ie.chainId===R.chainId&&p.addressesEqual(ie.address,R.address));q&&(Ie([{asset:q,amount:""}]),u?.(q))},[R,Le,G.length]);const Wt=l.useRef(null);l.useEffect(()=>{if(de&&be?.overallStatus==="success"&&y&&we==="idle"){const q=Wt.current,ie=ge.current;q&&(async()=>{try{he("executing"),await y(q),he("success"),Fe(q),yt(!0);const Se=Array.isArray(ie)?ie[0]:void 0,me={type:"deposit",status:"success",amount:q,asset:Se?.tokenAddress,sourceChain:Se?String(Se.chainId):void 0,txHash:Se?.txHash};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:me})),j?.(me)}catch(Se){console.error("onDepositExecute failed:",Se),he("error"),Me(p.sanitizeError(Se,"Post-deposit instruction failed"))}finally{Wt.current=null,ge.current=null}})()}},[be?.overallStatus,de,we]);const dt=l.useCallback(()=>{ke(null)},[]);l.useEffect(()=>{e||(yt(!1),Fe(null),Ct("idle"),Tt(null),st(null))},[e]);const Qe=l.useCallback((q,ie)=>{Ie(Se=>{const me=[...Se];return me[ie]={asset:q,amount:me[ie]?.amount||""},me}),ie===0&&u?.(q),dt()},[u,dt]),We=l.useCallback(async(q,ie)=>{if(Ie(Se=>{const me=[...Se];return me[ie]&&(me[ie]={...me[ie],amount:q}),me}),dt(),ie===0)if(c?.setAssetAmount(q),rt&&q&&parseFloat(q)>0)try{const Se=Mt??await Sa();Mt||bt(Se);const me=G[0]?.asset;if(!me)return;const $e=D.parseUnits(q,me.decimals),_e=m?Be(m,x):null,sn=p.CHAIN_CONFIGS[x]?.supportedTokens?.find(ts=>p.addressesEqual(ts.address,m))?.decimals??6,Dn=Ea($e,me.decimals,sn,Se);He(Dn);const Mn=D.formatUnits(Dn,sn),es=Se.toLocaleString("en-US",{maximumFractionDigits:0});ct(`${q} ${me.symbol} \u2248 $${parseFloat(Mn).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})} ${_e??"USD"} (rate: $${es}/BTC)`),h?.(Mn)}catch(Se){console.error("Failed to fetch BTC/USD price:",Se),ct(null),He(null),h?.(q)}else ct(null),He(null),h?.(q)},[dt,c,h,rt,Mt,G,m,x,Be]),ut=l.useCallback(()=>{G.length<2&&Ie(q=>[...q,{asset:null,amount:""}])},[G.length]),At=l.useCallback(q=>{Ie(ie=>ie.filter((Se,me)=>me!==q)),dt()},[dt]),Ve=l.useRef(!1),Ht=l.useRef(!1);l.useEffect(()=>{e||(Ve.current=!1,Ht.current=!1,ft(null),it(null))},[e]);const[De,pt]=l.useState(!1),[Nt,at]=l.useState(null),[Te,ft]=l.useState(null),[ht,it]=l.useState(null),[qe,It]=l.useState(!1),[Y,$]=l.useState(null),re=l.useMemo(()=>{const q=G[0];if(G.length!==1||!q?.asset||!q.amount||parseFloat(q.amount)<=0)return null;try{return{asset:q.asset,amount:D.parseUnits(q.amount,q.asset.decimals),token:B.normalizeNativeTokenAddress(q.asset.address),chainId:q.asset.chainId}}catch{return null}},[G]),Ne=l.useMemo(()=>re?[re.chainId,re.token.toLowerCase(),re.amount.toString(),v?"escrow":"normal"].join("|"):null,[re,v]),_=l.useCallback(async q=>pe?No({address:pe,depositQuote:q,escrowOnly:v}):null,[pe,v]),Ce=l.useCallback(async()=>re?_(re):null,[re,_]),Pe=l.useRef(Ce);Pe.current=Ce,l.useEffect(()=>{let q=!1;if(!e||de||!Ne||De||Ae){ft(null),$(null),It(!1);return}const ie=async()=>{$(null),It(!0);try{const me=await Pe.current();q||ft(me)}catch(me){if(q)return;ft(null),$(me instanceof Error?me.message:"Failed to estimate gas fee")}finally{q||It(!1)}};ie();const Se=window.setInterval(()=>{ie()},1e4);return()=>{q=!0,window.clearInterval(Se)}},[e,de,Ne,De,Ae]),l.useEffect(()=>{De||Ae||it(null)},[De,Ae,Ne]);const lt=async()=>{if(G.length===0||!G[0]?.asset)return;const q=G.filter(_e=>_e.asset&&_e.amount&&parseFloat(_e.amount)>0);if(q.length===0)return;const ie=q[0],Se=p.getChainConfig(ie.asset.chainId),me=q.map(_e=>{const sn=parseFloat(_e.amount);return`${isNaN(sn)?_e.amount:sn.toPrecision(6).replace(/\.?0+$/,"")} ${_e.asset.symbol}`}).join(", "),$e={network:Se?.displayName||`Chain ${ie.asset.chainId}`,amount:me,symbol:"",chainId:ie.asset.chainId};if(!de&&q.length===1&&Te){it(Te);const _e=q[0];$e.creditedAmount=`${D.formatUnits(Te.net,_e.asset.decimals)} ${_e.asset.symbol}`,$e.networkFee=`${D.formatUnits(Te.fee,_e.asset.decimals)} ${_e.asset.symbol}`}at($e),pt(!0)},Ue=l.useRef(be);Ue.current=be;const vt=l.useRef(we);vt.current=we;const Re=async()=>{await Ii({selectedDepositAssets:G,escrowOnly:v,sourceAddress:fe,isNon7702:de,address:pe,embeddedWalletAddress:ce,isReady:H,isAuthenticated:J,zeroCreditError:je,depositBalanceError:St,externalWalletClient:ee,externalProvider:oe.current,effectiveDepositFee:Ze,depositBatches:r,destinationChainId:x,destinationTokenAddress:m,isCrossDenomination:rt,convertedUsdAmount:ue,mode:U,sponsorGas:b,nativeChainId:k,spiceBalanceUser:Ee,depositDataRef:ge,bridgedAmountRef:Wt,setIsExecuting:Xe,setError:ke,setConfirmationData:at,setShowConfirmation:pt,setDirectDepositStatus:Ct,setDirectDepositChainId:st,setDirectDepositTxHash:Tt,setPostDepositStatus:he,setPostDepositError:Me,setPostDepositAmount:Fe,setPostDepositSuccess:yt,startStatusPolling:gt,clearStatus:Rt,refreshAssets:mt,onDepositExecute:y,onDepositSelect:s,onDepositSuccess:j,execution:{execute:Je},getCurrentIntentStatus:()=>Ue.current,getCurrentPostDepositStatus:()=>vt.current})},je=l.useMemo(()=>{for(const q of G)if(!(!q?.asset||!q.amount||parseFloat(q.amount)<=0))try{const ie=q.asset.decimals,Se=D.parseUnits(q.amount,ie);if(Se<=0n)continue;const me=B.getEquivalenceGroup(B.normalizeNativeTokenAddress(q.asset.address)),$e=q.asset.receiptTokenDecimals??(me==="ETH"||me==="ARB"?18:me==="USDC"||me==="SUSD"||me==="WBTC"||me==="CBTC"?6:void 0);if($e===void 0||ie<=$e||B.convertAmountBetweenDecimals(Se,ie,$e)>0n)continue;return`Amount too small. Minimum deposit for this asset is ${D.formatUnits(10n**BigInt(ie-$e),ie)} ${q.asset.symbol}.`}catch{continue}return null},[G]),Ye=!de&&!!re,Ze=ht??Te,Et=!!re&&!!Ze&&Ze.chainId===re.chainId&&p.addressesEqual(Ze.token,re.token),St=l.useMemo(()=>{if(!Ye||!re||!Et)return null;const q=v?re.amount:re.amount+Ze.fee;return re.asset.balance>=q?null:`Insufficient ${re.asset.symbol}. Need ${D.formatUnits(q,re.asset.decimals)} ${re.asset.symbol} including gas.`},[Ye,re,Et,Ze,v]),[cn,Dt]=l.useState(!1),Ut=G[0]?.asset?.chainId,wt=ze.find(q=>q.isNative&&q.chainId===Ut)?.balance??0n;l.useEffect(()=>{if(!e||!Ut){Dt(!1);return}let q=!1;return(async()=>{try{const ie=await p.getClientForChain(Ut).getGasPrice()*150000n;q||Dt(wt<ie)}catch{q||Dt(!1)}})(),()=>{q=!0}},[e,Ut,wt]);const tn=!Ye||Et&&!qe&&!Y&&!St,nn=l.useCallback((q,ie)=>Ei({asset:q,assetIndex:ie,selectedAssetCount:G.length,address:pe,escrowOnly:v,isNon7702:de}),[de,G.length,pe,v]),dn=l.useMemo(()=>{if(!re||!Ze||!Et)return null;const q=v?re.amount:re.amount+Ze.fee;return{symbol:re.asset.symbol,decimals:re.asset.decimals,grossAmount:q,netAmount:Ze.net,totalFee:Ze.fee,gasFee:Ze.fee,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"estimated"}},[re,Ze,Et,v]),Lt=parseFloat(G[0]?.amount||"")||0,yn=Lt>0&&Lt<Kt,un=G.length>0&&G[0]?.asset&&G[0]?.amount&&Lt>0&&!yn&&ve&&!Ae&&!je&&!St&&tn&&!z;l.useEffect(()=>{if(!v||!w||!T||Ve.current||!ve)return;const q=a[0];if(!q)return;const ie=p.getAllAssetsForChain(q,[]).find(me=>p.addressesEqual(me.address,w));let Se;if(ie)Se=ie;else if(I!==void 0&&F)Se={address:w,symbol:F,name:F,decimals:I,chainId:q,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,isNative:B.isNativeToken(w)};else{console.warn("[DepositModal] escrowOnly: no matching asset and missing escrowTokenDecimals/escrowTokenSymbol for",w);return}Ve.current=!0,Ie([{asset:Se,amount:T}])},[v,w,T,I,F,ve,a]),l.useEffect(()=>{!v||!un||Ht.current||Ae||(Ht.current=!0,Re())},[v,un,Ae]);const Tn=Ft||et||je||St,Rn=()=>{if(Ae)return"Executing Deposit...";if(!ve)return"Wallet Not Connected";if(U==="7702"){if(!H)return"Loading...";if(!J)return"Authentication Required"}return G[0]?.asset?G[0]?.amount?yn?`MINIMUM ${Kt}`:je?"AMOUNT TOO SMALL":St?"INSUFFICIENT BALANCE":Ye&&!tn?Y?"GAS UNAVAILABLE":"ESTIMATING GAS":"DEPOSIT":"ENTER AMOUNT":"SELECT TOKEN"};return e?o.jsx(Vt,{isOpen:e,onClose:t,closeOnBackdropClick:n,title:i||`Deposit to your ${K} account`,subtitle:o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[o.jsx("img",{src:Rs,alt:"","aria-hidden":"true",style:{width:"13px",height:"13px",flexShrink:0,...Q?{filter:"invert(0.6)"}:{}}}),o.jsx("p",{style:{fontSize:"12px",color:X.textSecondary,margin:"0",lineHeight:"1.4",fontFamily:p.font.ui},children:`Deposit collateral to your ${K} Account from any supported network.`})]}),dark:Q,overlayContent:De||be||we!=="idle"&&y?o.jsx("div",{}):void 0,styles:d,theme:P,children:o.jsxs("div",{style:{padding:"24px 24px 5px 24px"},children:[o.jsx(Fi,{selectedDepositAssets:G,depositAssets:Le,secondAssetOptions:le,loadingAssets:Ke,allowSecondAsset:g,theme:P,styles:d,dark:Q,dk:X,onSelect:Qe,onAmountChange:We,onAdd:ut,onRemove:At,resolveMaxAmount:nn,onViewAllAssets:S}),Ye&&re&&o.jsx(Is,{fontFamily:d?.fontFamily||P.typography.fontFamily,textPrimary:X.textPrimary,textSecondary:X.textSecondary,cardBg:Q?X.inputBg:"#ffffff",cardBorder:X.cardBorder,resolvedDark:Q,darkCardBorder:X.cardBorder,primaryColor:V,feePreview:dn,isLoading:qe||Ye&&!Et,errorText:Y}),o.jsx(bi,{intentStatus:be,postDepositSuccess:xt,postDepositAmount:Bt,postDepositStatus:we,depositActionLabel:C,sourceChainName:G[0]?.asset?.chainId?p.getChainName(G[0].asset.chainId):"Destination Chain",directDepositStatus:Ge,directDepositTxHash:kt,directDepositChainId:Oe,styles:d}),o.jsx(Ci,{isOpen:De||!!be||we!=="idle"&&!!y,onClose:()=>{pt(!1),be&&Rt();const q=we==="success"&&!be,ie=be?.overallStatus==="success"&&we==="success"&&y;(q||ie)&&t()},onConfirm:Re,data:Nt,isExecuting:Ae,error:et,theme:P,styles:d,intentStatus:be,postDepositStatus:we,hasPostDepositInstruction:!!y}),ot&&o.jsxs(co,{dk:X,dark:Q,borderRadius:P.borderRadius.md,children:["\u26A1 ",ot]}),cn&&o.jsx(co,{dk:X,dark:Q,borderRadius:P.borderRadius.md,children:"Low native balance in the external wallet. The deposit to spicenet account might fail."}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:0,marginBottom:0,margin:0,padding:0},children:[Tn?o.jsx("div",{style:{marginBottom:"10px",fontSize:"12px",lineHeight:"1.45",color:X.errorText,fontFamily:d?.fontFamily||P.typography.fontFamily},children:Tn}):null,o.jsx(p.Button,{variant:"outline",fullWidth:!0,onClick:lt,disabled:!un||!ve||Ae,theme:P,dark:Q,styles:d,children:Rn()})]})]})}):null}),Bi=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,deposits:s,onComplete:r,onCancel:a,onSkip:i,onChangeWallet:d,isProcessing:u,error:c,styles:f})=>{const{dark:h,dk:g,theme:x}=p.useSpiceBrand(f);if(!e||s.length===0)return null;const m=s[0],y=f?.fontFamily||p.font.ui,C=p.font.mono,k=p.getChainName(m.chainId),b=parseFloat(m.amount).toPrecision(6).replace(/\.?0+$/,""),R=D.formatUnits(m.verifiedBalance,m.tokenDecimals);return o.jsx(Vt,{isOpen:e,onClose:t,title:"Incomplete Deposit",styles:f,closeOnBackdropClick:n,children:o.jsxs("div",{style:{padding:"18px 24px 24px",fontFamily:y},children:[o.jsx("p",{style:{fontSize:"14px",color:g.textSecondary,lineHeight:"1.6",margin:"0 0 18px 0"},children:"Your funds reached your wallet, but the deposit didn't finish."}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) auto",gap:"14px 18px",marginBottom:"24px",padding:"16px 18px",backgroundColor:h?g.cardBg:"#f8fafc",border:`1px solid ${g.cardBorder}`,borderRadius:h?"14px":"10px",boxShadow:h?"inset 0 1px 0 rgba(255,255,255,0.03)":"0 1px 2px rgba(16,24,40,0.04)"},children:[o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px"},children:[o.jsx("span",{style:{fontSize:"12px",fontWeight:600,color:g.textSecondary,fontFamily:C,letterSpacing:"0.8px"},children:"NETWORK"}),o.jsx("span",{style:{fontSize:"18px",fontWeight:600,color:g.textPrimary,fontFamily:y,lineHeight:1.2},children:k})]}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px",alignItems:"flex-end",textAlign:"right"},children:[o.jsx("span",{style:{fontSize:"12px",fontWeight:600,color:g.textSecondary,fontFamily:C,letterSpacing:"0.8px"},children:"DEPOSITED AMOUNT"}),o.jsxs("span",{style:{fontSize:"24px",fontWeight:700,color:g.successText,fontFamily:C,lineHeight:1.1},children:[b," ",m.tokenSymbol]}),o.jsx("span",{style:{fontSize:"12px",color:g.textSecondary,fontWeight:500,fontFamily:y},children:"Sent to embedded wallet"})]})]}),!m.hasFullBalance&&m.verifiedBalance>0n&&o.jsxs("div",{style:{marginBottom:"16px",padding:"8px 12px",backgroundColor:g.warningBg,border:`1px solid ${h?g.warningBorder:"#fcd34d"}`,borderRadius:"8px",fontSize:"13px",color:g.warningText,lineHeight:"1.4"},children:["Partial balance \u2014 only ",parseFloat(R).toFixed(4)," ",m.tokenSymbol," available."]}),c&&o.jsx("div",{style:{marginBottom:"16px",padding:"10px 12px",backgroundColor:g.errorBg,border:`1px solid ${h?g.errorBorder:"#fca5a5"}`,borderRadius:"8px",fontSize:"13px",color:h?g.errorText:"#991b1b",lineHeight:"1.4"},children:c}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[o.jsx(p.Button,{variant:"outline",fullWidth:!0,disabled:u,onClick:()=>r(m),theme:x,dark:h,styles:f,children:"CONFIRM DEPOSIT"}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:[o.jsx(p.Button,{variant:"ghost",fullWidth:!0,disabled:u,onClick:()=>a(m),theme:x,dark:h,style:{height:"48px",fontSize:"13px",letterSpacing:"0.4px",color:h?g.textPrimary:"#374151",border:`1px solid ${h?g.cardBorder:"#d1d5db"}`,borderRadius:"12px",backgroundColor:h?"rgba(255,255,255,0.02)":"#ffffff"},children:u?"RETURNING...":"RETURN FUNDS"}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:d?"1fr 1fr":"1fr",gap:"10px"},children:[o.jsx(p.Button,{variant:"ghost",fullWidth:!0,disabled:u,onClick:i,theme:x,dark:h,style:{height:"44px",fontSize:"12px",letterSpacing:"0.4px",color:g.textSecondary,border:`1px solid ${h?g.cardBorder:"#d1d5db"}`,borderRadius:"12px",backgroundColor:"transparent"},children:"START OVER"}),d&&o.jsx(p.Button,{variant:"ghost",fullWidth:!0,disabled:u,onClick:d,theme:x,dark:h,style:{height:"44px",fontSize:"12px",letterSpacing:"0.4px",color:g.textSecondary,border:`1px solid ${h?g.cardBorder:"#d1d5db"}`,borderRadius:"12px",backgroundColor:"transparent"},children:"CHANGE WALLET"})]})]})]}),s.length>1&&o.jsxs("p",{style:{fontSize:"12px",color:g.textSecondary,textAlign:"center",marginTop:"14px",marginBottom:0,lineHeight:"1.5"},children:[s.length," incomplete deposits found \u2014 resolving one at a time."]})]})})},Ds=e=>{const[t,n]=l.useState(!1),s=l.useContext(p.SpiceFlowProviderContext),{dark:r,dk:a}=p.useSpiceBrand();if(l.useEffect(()=>{n(!0)},[]),!t)return o.jsx("div",{className:e.className,children:o.jsx("button",{disabled:!0,style:{padding:"12px 24px",fontSize:"16px",backgroundColor:r?a.hoverBg:"#ccc",color:r?a.textSecondary:"white",border:r?`1px solid ${a.buttonBorder}`:"none",borderRadius:"4px",cursor:"not-allowed"},children:"Loading..."})});if(!s){const i='ProviderLogin must be used within SpiceFlowProvider. Please wrap your app with <SpiceFlowProvider provider="privy">.';return o.jsx("div",{className:e.className,children:o.jsx("button",{onClick:()=>{e.onAuthError&&e.onAuthError(i)},style:{padding:"12px 24px",fontSize:"16px",backgroundColor:r?a.errorBg:"#dc2626",color:r?a.errorText:"white",border:r?`1px solid ${a.errorBorder}`:"none",borderRadius:"4px",cursor:"pointer"},children:"Provider Not Found"})})}return o.jsx(p.PrivyLogin,{...e})},Ti=.01,Ri=5*60*1e3;function Di(e){const t=Number(D.formatUnits(e.verifiedBalance,e.tokenDecimals));return Number.isFinite(t)?t:0}async function Mi(e){const t=Wi(e);let n;try{n=await hs(t.map(s=>s.tokenSymbol))}catch{return t}return t.filter(s=>{const r=Di(s);if(r<=0)return!0;const a=n[s.tokenSymbol.toUpperCase()]??0;return!Number.isFinite(a)||a<=0?!0:r*a>=Ti})}function Wi(e){const t=new Map;for(const n of e){const s=`${n.chainId}:${n.tokenAddress.toLowerCase()}`;t.get(s)||t.set(s,{...n,amount:n.timestamp===0?D.formatUnits(n.verifiedBalance,n.tokenDecimals):n.amount,rawAmount:n.timestamp===0?n.verifiedBalance.toString():n.rawAmount,hasFullBalance:n.timestamp===0?!0:n.hasFullBalance})}return Array.from(t.values())}function Uo(e,t){const[n,s]=l.useState([]),[r,a]=l.useState(!1),i=l.useRef(t);i.current=t;const d=l.useRef(0),u=l.useRef(0),c=l.useCallback(async({forceDiscovery:f=!1}={})=>{if(!e){s([]),a(!1);return}const h=++u.current,g=()=>h!==u.current;a(!0);try{const x=[],m=vi(e);for(const b of m){if(g())return;try{const R=p.getClientForChain(b.chainId);let v;if(b.isNative||B.isNativeToken(b.tokenAddress)?v=await Pt.getBalance(R,{address:e}):v=await Pt.readContract(R,{address:D.getAddress(b.tokenAddress),abi:D.erc20Abi,functionName:"balanceOf",args:[e]}),g())return;v>0n?x.push({...b,verifiedBalance:v,hasFullBalance:v>=BigInt(b.rawAmount)}):Date.now()-b.timestamp>15*60*1e3&&Bs(e,b.chainId,b.tokenAddress)}catch(R){console.warn(`[usePendingDeposit] Failed to verify balance for ${b.tokenSymbol} on chain ${b.chainId}:`,R),x.push({...b,verifiedBalance:0n,hasFullBalance:!1})}}if(g())return;const y=i.current,C=Date.now(),k=(y?.discoverWalletBalances??!0)&&(f||C-d.current>=Ri);if(y?.network&&k){d.current=C;const b=y.chainIds??B.getChainIdsByNetwork(y.network),R=new Set(x.map(w=>`${w.chainId}:${w.tokenAddress.toLowerCase()}`)),v=[];for(const w of b){const T=p.getChainConfig(w);if(T?.supportedTokens)for(const I of T.supportedTokens){if(B.isNativeToken(I.address))continue;const F=`${w}:${I.address.toLowerCase()}`;R.has(F)||v.push((async()=>{try{const j=p.getClientForChain(w),A=await Pt.readContract(j,{address:D.getAddress(I.address),abi:D.erc20Abi,functionName:"balanceOf",args:[e]});return A>0n?{chainId:w,tokenAddress:I.address,tokenSymbol:I.symbol,tokenDecimals:I.decimals,amount:D.formatUnits(A,I.decimals),rawAmount:A.toString(),embeddedWalletAddress:e,externalWalletAddress:"",timestamp:0,isNative:!1,verifiedBalance:A,hasFullBalance:!0}:null}catch{return null}})())}}if(v.length>0){const w=await Promise.allSettled(v);if(g())return;for(const T of w)T.status==="fulfilled"&&T.value&&x.push(T.value)}}if(!g()){const b=await Mi(x);if(g())return;s(b)}}catch(x){console.error("[usePendingDeposit] Verification error:",x),g()||s([])}finally{g()||a(!1)}},[e]);return l.useEffect(()=>{if(!i.current?.enabled){u.current++,s([]),a(!1);return}c({forceDiscovery:!0});const f=i.current?.pollIntervalMs??3e4;if(f<=0||!e)return()=>{u.current++};const h=setInterval(()=>{c({forceDiscovery:!1})},f),g=()=>c({forceDiscovery:!0});return window.addEventListener(Kn,g),()=>{u.current++,window.removeEventListener(Kn,g),clearInterval(h)}},[c,e]),{pendingDeposits:n,loading:r,refresh:()=>c({forceDiscovery:!0})}}function Ni(e,t,n,s,r){return{address:t,symbol:n||"UNKNOWN",name:n||"Unknown Token",decimals:s||18,chainId:e,balance:0n,balanceFormatted:r?parseFloat(r):0,balanceUsd:0,isNative:B.isNativeToken(t)}}const Pi=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,styles:s,depositBatches:r,onDepositAmountChange:a,destinationChainId:i,destinationTokenAddress:d,onDepositExecute:u,depositActionLabel:c,sponsorGas:f=!1,escrowRecovery:h,skipTokenSelection:g=!1,onDepositSuccess:x,onDepositError:m,skipRecovery:y=!1})=>{const C=l.useContext(p.SpiceFlowProviderContext);if(!C)return o.jsx("div",{children:"Error: SpiceDeposit must be used within SpiceFlowProvider"});const k=(C.mode||"7702")!="7702",b=k,R=C.nativeChainId,v=C.network||"testnet",{dark:w,dk:T}=p.useSpiceBrand(s),I=!!h,F=p.useWallet(),{isReady:j,isAuthenticated:A,actions:E}=F,S=C?.embeddedWalletAddress,{address:M}=Qt.useAccount(),U=C?.externalWalletAddress??M,W=!!U,O=()=>g?"deposit":"select-token",z=()=>b?W?O():"connect-wallet":"provider-login",[N,P]=l.useState(z()),[Q,K]=l.useState(null),[V,X]=l.useState(!1),{pendingDeposits:xe,loading:H,refresh:J}=Uo(S,{enabled:e,network:v,chainIds:C.supportedChainIds}),[se,ce]=l.useState(null),[de,ve]=l.useState(!1),[pe,fe]=l.useState(null),[Ee,L]=l.useState(!1),[ee,te]=l.useState("idle");l.useEffect(()=>{e&&!y&&!I&&!se&&!Ee&&ee==="idle"&&A&&S&&W&&U&&!H&&xe.length>0&&N!=="recovery"&&N!=="deposit"&&P("recovery")},[e,y,I,A,S,W,U,H,xe,N,se,Ee,ee]);const oe=l.useCallback(le=>{const Ae={address:le.tokenAddress,symbol:le.tokenSymbol,name:le.tokenSymbol,decimals:le.tokenDecimals,chainId:le.chainId,balance:le.verifiedBalance,balanceFormatted:parseFloat(le.amount),balanceUsd:0,isNative:le.isNative};K(Ae),ce(le),P("deposit")},[]),Z=l.useCallback(()=>{L(!0),P(A&&S&&W&&U?g?"deposit":"select-token":A&&S?"connect-wallet":"provider-login")},[A,S,W,U,g]),ne=l.useCallback(()=>{fe(null),te("awaiting-disconnect"),P("connect-wallet")},[]),ge=l.useCallback(async le=>{ve(!0),fe(null);try{if(!S)throw new Error("Embedded wallet not available");const Ae=await E.getEthereumProvider(),Xe=p.getChainConfig(le.chainId);await p.ensureWalletOnChain(Ae,le.chainId);const et=p.getClientForChain(le.chainId),ae=await Pt.getBalance(et,{address:S}),nt=Xe?.viemChain?.name||`chain ${le.chainId}`;if(ae===0n)throw new Error(`Your embedded wallet has no ETH on ${nt} to pay for gas. We recommend completing the deposit instead \u2014 it doesn't require gas.`);const ke=D.createWalletClient({account:S,transport:D.custom(Ae),chain:Xe?.viemChain}),we=le.externalWalletAddress&&D.isAddress(le.externalWalletAddress)?le.externalWalletAddress:U;if(!we||!D.isAddress(we))throw new Error("Connect the external wallet that should receive these funds, then try again.");let he;le.isNative||B.isNativeToken(le.tokenAddress)?he=await ke.sendTransaction({to:we,value:le.verifiedBalance,chain:Xe?.viemChain}):he=await ke.sendTransaction({to:le.tokenAddress,data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"transfer",args:[we,le.verifiedBalance]}),chain:Xe?.viemChain}),await et.waitForTransactionReceipt({hash:he,confirmations:1}),Bs(le.embeddedWalletAddress,le.chainId,le.tokenAddress),J(),xe.length<=1&&P(z())}catch(Ae){const Xe=Ae?.message||"Couldn't return your funds. Please try again.",et=/insufficient funds for gas/i.test(Xe);fe(et?"Not enough ETH in your embedded wallet to cover gas fees. Complete the deposit instead \u2014 it doesn't require gas.":Xe)}finally{ve(!1)}},[E,S,U,xe,J]);l.useEffect(()=>{e||(ce(null),fe(null),ve(!1),L(!1),te("idle"))},[e]),l.useEffect(()=>{if(ee!=="idle"){if(ee==="awaiting-disconnect"){(!W||!U)&&te("awaiting-reconnect");return}e&&!H&&xe.length>0&&A&&S&&(te("idle"),P("recovery"))}},[ee,W,U,e,H,xe,A,S]),l.useEffect(()=>{!I||!e||(A&&S?(X(!0),!Q&&h?.chainId&&h?.tokenAddress&&K(Ni(h.chainId,h.tokenAddress,h.tokenSymbol,h.tokenDecimals,h.amount)),P("deposit")):P("provider-login"))},[I,e,N,A,S]);const{assets:G,loading:Ie}=ls({address:U,supportedChains:C.supportedChainIds,fetchBalances:is,enabled:e&&!!U,refreshInterval:e?5e3:0}),ze=l.useCallback(()=>{X(!0),P(I?"deposit":W?g?"deposit":"select-token":"connect-wallet")},[I,W,g]),Ke=l.useCallback(async()=>{if((!W||!U)&&(await qt(500),!W||!U)){alert("Please connect your wallet first");return}P(g?"deposit":"select-token")},[W,U,g]),Ft=l.useCallback(le=>{K(le),P("deposit")},[]),mt=l.useCallback(()=>{if(K(null),a?.(""),!U){P("connect-wallet");return}P("select-token")},[U,a]),Le=l.useCallback(()=>{t()},[t]);if(l.useEffect(()=>{if(!e){const le=setTimeout(()=>{I||(P(z()),K(null)),X(!1)},300);return()=>clearTimeout(le)}},[e,I,h?.chainId]),l.useEffect(()=>{e&&N==="deposit"&&!Q&&!I&&!se&&!g&&P("select-token")},[e,N,Q,I,se,g]),l.useEffect(()=>{e&&N==="connect-wallet"&&W&&U&&ee==="idle"&&P(g?"deposit":"select-token")},[e,N,W,U,ee,g]),l.useEffect(()=>{if(!b&&e&&N==="provider-login"&&j&&A&&S&&!V){const le=setTimeout(()=>{X(!0),P(W?g?"deposit":"select-token":"connect-wallet")},100);return()=>clearTimeout(le)}},[b,e,N,j,A,S,W,g,V]),!e)return null;if(N==="recovery")return o.jsx(Bi,{isOpen:e,onClose:Le,closeOnBackdropClick:n,deposits:xe,onComplete:oe,onCancel:ge,onSkip:Z,onChangeWallet:ne,isProcessing:de,error:pe,styles:s});if(N==="provider-login"&&!b)return o.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.5)",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",zIndex:50},children:o.jsx("div",{style:{backgroundColor:w?T.cardBg:"white",borderRadius:"9px",padding:"32px 24px",maxWidth:"400px",width:"100%"},children:o.jsx(Ds,{onAuthSuccess:ze,autoTrigger:!0})})});if(N==="connect-wallet")return o.jsx(Na,{isOpen:e,onClose:Le,closeOnBackdropClick:n,onContinue:Ke,requiredChainId:k?R:void 0,styles:s});if(N==="select-token")return U?o.jsx(Da,{isOpen:e,onClose:Le,closeOnBackdropClick:n,onTokenSelect:Ft,walletAddress:U,supportedChainIds:C.supportedChainIds,network:v,prefetchedAssets:Ie?null:G??null,styles:s,dark:w}):(P("connect-wallet"),null);if(N==="deposit"){if(!Q&&!g)return null;const le=!!se;return o.jsx(Po,{isOpen:e,onClose:Le,closeOnBackdropClick:n,supportedChains:Q?[Q.chainId]:C.supportedChainIds??[],styles:s,externalWalletAddress:U,depositBatches:le?void 0:r,onDepositAmountChange:a,destinationChainId:i,destinationTokenAddress:d,onDepositExecute:u,depositActionLabel:c,nativeChainId:R,sponsorGas:f,preSelectedAsset:Q??void 0,escrowOnly:I||le,escrowTokenAddress:le?se.tokenAddress:h?.tokenAddress,escrowAmount:le?se.amount:h?.amount,escrowTokenDecimals:le?se.tokenDecimals:h?.tokenDecimals,escrowTokenSymbol:le?se.tokenSymbol:h?.tokenSymbol,onDepositSuccess:x,onDepositError:m,embeddedWalletAddress:S,onViewAllAssets:g?void 0:mt})}return null},Ui=e=>l.useContext(p.SpiceFlowProviderContext)?o.jsx(Pi,{...e}):o.jsx("div",{children:"Error: SpiceDeposit must be used within SpiceFlowProvider"}),Li=({isOpen:e,onClose:t,onChainSelect:n,supportedChains:s,closeOnSelect:r=!0,styles:a})=>{const{theme:i,dark:d,primaryColor:u,dk:c}=p.useSpiceBrand(a),[f,h]=l.useState(""),[g,x]=l.useState(null),[m,y]=l.useState(null),[C,k]=l.useState(!1),[b,R]=l.useState(null),{switchChainAsync:v}=Qt.useSwitchChain(),w=l.useMemo(()=>new Set(s||[]),[s]),T=l.useMemo(()=>{if(!s||s.length===0)return[];const A=[];return s.forEach((E,S)=>{if(typeof E!="number")return;const M=p.getChainConfig(E);M&&A.push({id:E.toString(),name:M.displayName,icon:Gt[E]||wn,chainId:E,verified:!0,order:S})}),A},[s]);l.useEffect(()=>{g&&!w.has(parseInt(g,10))&&x(null)},[g,w]);const I=l.useMemo(()=>T.filter(A=>A.name.toLowerCase().includes(f.toLowerCase())).sort((A,E)=>A.order-E.order),[T,f]),F=async()=>{if(!g)return;const A=parseInt(g,10);k(!0),R(null);try{await v({chainId:A}),n&&n(g),r&&t()}catch(E){console.error("Failed to switch chain:",E),R(p.sanitizeError(E,"Failed to switch chain."))}finally{k(!1)}},j=!g||C;return o.jsxs(Vt,{isOpen:e,onClose:t,title:"Select Chain",styles:a,theme:i,dark:d,children:[o.jsx("div",{style:{padding:"24px 20px"},children:o.jsx(rs,{value:f,onChange:h,ariaLabel:"Search chains",placeholder:"Search chain name, symbol or address",size:"md",dark:d,styles:a,endAdornment:o.jsx("div",{style:{padding:"5px 5px",borderRadius:"3px",fontSize:"13px",backgroundColor:d?c.cardBg:"#E9E9E9",color:d?c.textSecondary:"#485066",fontWeight:500,flexShrink:0},"aria-hidden":"true",children:"\u2318F"})})}),o.jsx("div",{style:{padding:"0 32px 20px",display:"flex",flexDirection:"column",gap:"12px"},children:I.map(A=>{const E=g===A.id,S=m===A.id;return o.jsxs("button",{onClick:()=>x(A.id),onMouseEnter:()=>y(A.id),onMouseLeave:()=>y(null),style:{width:"100%",display:"flex",alignItems:"center",gap:"16px",padding:"8px",borderRadius:"8px",backgroundColor:E?d?`${u}15`:`${u}12`:"transparent",border:E?d?`1px solid ${u}66`:`1px solid ${u}88`:S?d?`1px solid ${u}44`:`1px solid ${u}66`:"1px solid transparent",cursor:"pointer",transition:p.transition.interactive},children:[o.jsx("div",{style:{width:"40px",height:"40px",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"30px"},children:o.jsx("img",{src:A.icon,alt:A.name,loading:"lazy",decoding:"async",style:{width:"100%",height:"100%",borderRadius:"50%"}})}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",flex:1},children:[o.jsx("span",{style:{fontFamily:p.font.mono,fontSize:"17px",fontWeight:500,letterSpacing:"0.4px",color:c.textPrimary,textAlign:"left"},children:A.name}),A.verified&&o.jsx("img",{src:ao,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:16,height:16,style:{width:"16px",height:"16px",filter:d?"brightness(0) invert(1)":"none"}})]})]},A.id)})}),b&&o.jsx("div",{style:{padding:"0 25px 12px"},children:o.jsx(an,{variant:"error",size:"compact",palette:c,children:b})}),o.jsx("div",{style:{padding:"0 25px 25px"},children:o.jsxs(p.Button,{variant:"outline",onClick:F,disabled:j,fullWidth:!0,theme:i,styles:a,dark:d,children:["SELECT",o.jsx(oa,{size:20})]})})]})},Lo=({isSuccess:e,type:t,chainName:n,explorerUrl:s,txHash:r,dark:a=!1,successBg:i="#d1fae5",successBorder:d="#6ee7b7",successText:u="#065f46",errorBg:c="#fee2e2",errorBorder:f="#fca5a5",errorText:h="#dc2626",textSecondary:g="#6b7280"})=>o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px",borderRadius:"8px",backgroundColor:e?i:c,border:e?`1px solid ${d}`:`1px solid ${f}`},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[o.jsx("div",{style:{width:"28px",height:"28px",borderRadius:"50%",backgroundColor:e?"#10b981":"#ef4444",display:"flex",alignItems:"center",justifyContent:"center"},children:e?o.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:o.jsx("path",{d:"M11.6667 3.5L5.25 9.91667L2.33333 7",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}):o.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:o.jsx("path",{d:"M10.5 3.5L3.5 10.5M3.5 3.5L10.5 10.5",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),o.jsxs("div",{children:[o.jsx("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:p.font.mono,letterSpacing:"0.5px",color:e?u:h},children:e?`${t.toUpperCase()} CONFIRMED`:`${t.toUpperCase()} FAILED`}),o.jsxs("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:g},children:["on ",n]})]})]}),s&&r&&o.jsxs("a",{href:`${s}/tx/${r}`,target:"_blank",rel:"noopener noreferrer",style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"13px",color:g,textDecoration:"none",whiteSpace:"nowrap"},children:["View on explorer",o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:[o.jsx("path",{d:"M9 6.5V9.5C9 9.76522 8.89464 10.0196 8.70711 10.2071C8.51957 10.3946 8.26522 10.5 8 10.5H2.5C2.23478 10.5 1.98043 10.3946 1.79289 10.2071C1.60536 10.0196 1.5 9.76522 1.5 9.5V4C1.5 3.73478 1.60536 3.48043 1.79289 3.29289C1.98043 3.10536 2.23478 3 2.5 3H5.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),o.jsx("path",{d:"M7.5 1.5H10.5V4.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),o.jsx("path",{d:"M5 7L10.5 1.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})]})]})]}),zo=`
|
|
30
|
+
`})]})};async function wi(e,t,n){let s=null;try{const r=await e.request({method:"eth_chainId"});s=parseInt(r,16)}catch{s=null}s!==t&&(n?.(),await p.ensureWalletOnChain(e,t))}async function xn(e){const t=e.provider??await e.wallet?.getEthereumProvider();if(!t)throw new Error("External wallet provider not available");await wi(t,e.chainId,e.onSwitch);const n=p.getChainConfig(e.chainId)?.viemChain;return{extWc:D.createWalletClient({account:e.account,chain:n,transport:D.custom(t)}),viemChain:n}}async function Ro(e){let t;for(const n of e.calls){const s=await e.extWc.sendTransaction({to:n.to,data:n.data,value:n.value,chain:e.viemChain});if((await e.client.waitForTransactionReceipt({hash:s,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error(e.errorMessage);t=s}return t}function Do(e,t){return t.isNative?e.sendTransaction({to:t.recipient,value:t.amount,chain:t.viemChain}):e.sendTransaction({to:t.tokenAddr,data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"transfer",args:[t.recipient,t.amount]}),chain:t.viemChain})}async function js(e){const{extWc:t,sourceClient:n,recipient:s,tokenAddr:r,isNative:a,amount:i}=e;if(i<=0n)return;const d=await Do(t,{recipient:s,tokenAddr:r,isNative:a,amount:i,viemChain:e.viemChain});if((await n.waitForTransactionReceipt({hash:d,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Embedded wallet funding failed")}const Mo="spiceflow:pendingDeposit",Kn="spiceflow:pendingDepositChanged";function Wo(e,t,n){return`${Mo}:${e.toLowerCase()}:${t}:${n.toLowerCase()}`}function Fs(){try{const e="__spiceflow_storage_test__";return localStorage.setItem(e,"1"),localStorage.removeItem(e),!0}catch{return!1}}function ki(e){if(!Fs())return;const t=Wo(e.embeddedWalletAddress,e.chainId,e.tokenAddress);try{localStorage.setItem(t,JSON.stringify(e)),window.dispatchEvent(new Event(Kn))}catch(n){console.error("[pendingDeposit] Failed to save:",n)}}function vi(e){if(!Fs())return[];const t=`${Mo}:${e.toLowerCase()}:`,n=[],s=Date.now();for(let r=0;r<localStorage.length;r++){const a=localStorage.key(r);if(!(!a||!a.startsWith(t)))try{const i=localStorage.getItem(a);if(!i)continue;const d=JSON.parse(i);if(s-d.timestamp>6048e5){localStorage.removeItem(a);continue}n.push(d)}catch{localStorage.removeItem(a)}}return n}function Bs(e,t,n){if(!Fs())return;const s=Wo(e,t,n);localStorage.removeItem(s),window.dispatchEvent(new Event(Kn))}function Si({sourceChainId:e,selectedAsset:t,destinationChainId:n,destinationTokenAddress:s,isCrossDenomination:r,convertedUsdAmount:a}){const i=B.normalizeNativeTokenAddress(t.asset.address),d=s;let u,c;if(d&&n)if(u=p.CHAIN_CONFIGS[n]?.supportedTokens?.find(f=>p.addressesEqual(f.address,d))?.decimals??t.asset.decimals,r){if(!a)throw new Error("Destination amount is still being calculated. Please retry in a moment.");c=a}else{const f=D.parseUnits(t.amount,t.asset.decimals);c=B.convertAmountBetweenDecimals(f,t.asset.decimals,u)}return{sourceChainId:e,depositTokenAddress:i,depositAmount:t.amount,depositTokenDecimals:t.asset.decimals,destinationChainId:n,destinationTokenAddress:d,destinationAmount:c,destinationTokenDecimals:u}}async function Ai(e,t){if(!e)return[];if(Array.isArray(e))return e;const n=e;return e.length>=2?n(t.depositAmount,t.depositTokenAddress):n(t)}async function Ts(e,t){const n=await Do(e,{recipient:t.recipient,tokenAddr:t.tokenAddr,isNative:t.isNative,amount:t.amount});t.afterSend?.(n);const s=p.getClientForChain(t.chainId),r=await s.waitForTransactionReceipt({hash:n,timeout:12e4,pollingInterval:2e3,confirmations:2});if(r.status!=="success")throw new Error(t.failureMessage);return t.settle&&await s.getBlockNumber()-r.blockNumber<2n&&await qt(3e3),r.transactionHash}async function Ii(e){const t=e.selectedDepositAssets.filter(s=>s.asset&&s.amount&&parseFloat(s.amount)>0);if(t.length===0){console.error("[DepositModal] No valid assets for deposit"),e.setError("Please select an asset and enter an amount");return}if(!e.escrowOnly&&!e.sourceAddress){e.setError("External wallet not connected. Please connect your wallet in the previous step.");return}if(!e.isNon7702){if(!e.address||!e.embeddedWalletAddress){e.setError("Couldn't find your account wallet. Try reconnecting.");return}if(!e.isReady||!e.isAuthenticated){e.setError("Sign in to continue.");return}}if(e.zeroCreditError){e.setError(e.zeroCreditError);return}if(e.depositBalanceError){e.setError(e.depositBalanceError);return}e.setIsExecuting(!0),e.setError(null);let n=!1;try{const s=t[0].asset.chainId,r=B.getEscrowContractAddress(s);let a=e.externalWalletClient;if(!e.escrowOnly){if(!a)throw new Error("External wallet not connected");if(e.externalProvider){const i=await xn({provider:e.externalProvider,account:e.sourceAddress,chainId:s});i.viemChain&&(a=i.extWc)}}if(e.isNon7702){if(!a)throw new Error("External wallet not connected");if(!e.sourceAddress)throw new Error("External wallet address not available");if(e.nativeChainId&&s===e.nativeChainId){const i=p.getChainConfig(s),d=t.map(c=>`${c.amount} ${c.asset.symbol}`).join(", ");e.setConfirmationData({network:i?.displayName||`Chain ${s}`,amount:d,symbol:"",chainId:s}),e.setShowConfirmation(!0);let u=null;e.setDirectDepositStatus("processing"),e.setDirectDepositChainId(s);for(const c of t){const f=D.parseUnits(c.amount,c.asset.decimals),h=B.normalizeNativeTokenAddress(c.asset.address),g=c.asset.isNative||B.isNativeToken(h),x=await Ts(a,{chainId:s,recipient:r,tokenAddr:h,isNative:g,amount:f,failureMessage:`Escrow deposit failed for ${c.asset.symbol}`});u=x,e.setDirectDepositTxHash(x)}if(t[0]?.amount){const c=t[0].amount;if(e.onDepositExecute){e.setPostDepositStatus("executing");try{await e.onDepositExecute(c),e.setPostDepositStatus("success")}catch(h){console.error("ctx.onDepositExecute failed:",h),e.setPostDepositStatus("error"),e.setPostDepositError(h?.message||"Post-deposit instruction failed")}}else e.setPostDepositStatus("success");e.setDirectDepositStatus("success"),e.setPostDepositAmount(c),e.setPostDepositSuccess(!0);const f={type:"deposit",status:"success",amount:c,asset:t[0].asset.symbol,sourceChain:i?.displayName||`Chain ${s}`,txHash:u??void 0};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:f})),e.onDepositSuccess?.(f)}e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset)}else{const i=e.destinationChainId||e.nativeChainId;if(!i)throw new Error("Destination chain ID is required for non-7702 mode. Either pass ctx.destinationChainId to <SpiceDeposit> or set ctx.nativeChainId on <SpiceFlowProvider>.");const d=p.getDelegateContractAddress(s),u=r,c=[];let f=null;for(const h of t){const g=D.parseUnits(h.amount,h.asset.decimals),x=B.normalizeNativeTokenAddress(h.asset.address),m=h.asset.isNative||B.isNativeToken(x),y=await Ts(a,{chainId:s,recipient:u,tokenAddr:x,isNative:m,amount:g,failureMessage:`Transfer failed for ${h.asset.symbol}`,afterSend:C=>{f||(f=C)},settle:!0});e.depositDataRef.current||(e.depositDataRef.current=[]),e.depositDataRef.current.push({txHash:y,sender:e.sourceAddress,tokenAddress:x,chainId:s,amount:g.toString(),user:e.spiceBalanceUser}),c.push({tokenAddress:x,tokenAmount:g.toString(),sender:e.sourceAddress,receiver:u})}if(!f)throw new Error("No transaction hash generated");if(!e.destinationTokenAddress){const h={type:"deposit",status:"success",amount:t[0]?.amount,asset:t[0]?.asset?.symbol,sourceChain:p.getChainName(s),txHash:f};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:h})),e.onDepositSuccess?.(h),e.depositDataRef.current=null,e.bridgedAmountRef.current=t[0]?.amount||null,e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset),e.setShowConfirmation(!1);return}if(e.sponsorGas&&e.nativeChainId){const h=D.parseUnits("0.05",18);c.push({tokenAddress:B.ZERO_ADDRESS,tokenAmount:h.toString(),sender:e.sourceAddress,receiver:u})}if(e.mode==="ondemand"){const h={to:d,value:BigInt(0),data:"0x"},g=await p.getTokenDecimals(i,e.destinationTokenAddress);let x=BigInt(0);for(const T of c){const I=BigInt(T.tokenAmount),F=B.normalizeNativeTokenAddress(T.tokenAddress),j=t.find(E=>{const S=B.normalizeNativeTokenAddress(E.asset.address);return p.addressesEqual(S,F)}),A=j?j.asset.decimals:await p.getTokenDecimals(s,B.ZERO_ADDRESS);x+=B.convertAmountBetweenDecimals(I,A,g)}e.isCrossDenomination&&e.convertedUsdAmount&&(x=e.convertedUsdAmount);const m={chainId:s,tokenTransfers:c.map(T=>({from:T.sender,to:T.receiver,token:T.tokenAddress,amount:BigInt(T.tokenAmount)})),call:h},y=e.isCrossDenomination&&e.convertedUsdAmount?[{from:e.sourceAddress,to:r,token:B.normalizeNativeTokenAddress(t[0].asset.address),amount:D.parseUnits(t[0].amount,t[0].asset.decimals)}]:[],C={chainId:i,tokenTransfers:[...y,{from:"escrow",to:e.sourceAddress,token:e.destinationTokenAddress,amount:x}],call:{to:e.destinationTokenAddress,value:BigInt(0),data:"0x"}},k={mode:"non-7702:on-demand",chainBatches:[m,C]},b={user:e.sourceAddress,intents:[k]},R=await p.relayerService.createAction(b),v=R.actionId,w=R.intentIds[0];if(!f)throw new Error("No transaction hash available");e.startStatusPolling(w,p.createInitialSteps([{chainId:s,calls:[h]},{chainId:i,calls:[C.call]}],T=>p.getChainName(T))),await p.relayerService.executeStep(v,0,0,{action:"execute",hash:f}),t[0]?.amount&&(e.bridgedAmountRef.current=t[0].amount),e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset),e.setShowConfirmation(!1)}else throw new Error("Presign mode not yet fully supported for cross-chain deposits")}}else{const i=[],d=t[0],u=d&&t.length===1&&e.effectiveDepositFee&&e.effectiveDepositFee.chainId===s&&p.addressesEqual(e.effectiveDepositFee.token,B.normalizeNativeTokenAddress(d.asset.address))?D.formatUnits(e.effectiveDepositFee.net,d.asset.decimals):d?.amount;for(const b of t){const R=D.parseUnits(b.amount,b.asset.decimals),v=t.length===1&&!!e.effectiveDepositFee&&e.effectiveDepositFee.chainId===s&&p.addressesEqual(e.effectiveDepositFee.token,B.normalizeNativeTokenAddress(b.asset.address)),w=v?e.effectiveDepositFee.fee:0n,T=v?e.effectiveDepositFee.net:R,I=e.escrowOnly?R:R+w,F=B.normalizeNativeTokenAddress(b.asset.address),j=b.asset.isNative||B.isNativeToken(F);e.escrowOnly||await Ts(a,{chainId:s,recipient:e.address,tokenAddr:F,isNative:j,amount:I,failureMessage:`Transfer to embedded wallet failed for ${b.asset.symbol}`,afterSend:()=>ki({chainId:s,tokenAddress:B.normalizeNativeTokenAddress(b.asset.address),tokenSymbol:b.asset.symbol,tokenDecimals:b.asset.decimals,amount:b.amount,rawAmount:R.toString(),embeddedWalletAddress:e.address,externalWalletAddress:e.sourceAddress,timestamp:Date.now(),isNative:j}),settle:!0}),i.push(j?{to:r,value:T,data:"0x"}:{to:F,value:BigInt(0),data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"transfer",args:[r,T]})}),w>0n&&i.push(j?{to:B.SPICE_GAS_FEE_RECIPIENT,value:w,data:"0x"}:{to:F,value:BigInt(0),data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"transfer",args:[B.SPICE_GAS_FEE_RECIPIENT,w]})})}const c=await p.getClientForChain(s).getBlockNumber(),f=i.map(b=>({...b,to:D.getAddress(b.to)})),h={chainId:s,recentBlock:c,calls:f,tokenTransfers:[]},g=Si({sourceChainId:s,selectedAsset:d&&u?{...d,amount:u}:t[0],destinationChainId:e.destinationChainId,destinationTokenAddress:e.destinationTokenAddress,isCrossDenomination:e.isCrossDenomination,convertedUsdAmount:e.convertedUsdAmount}),x=await Ai(e.depositBatches,g),m=[h,...x];if(!e.address)throw new Error("Address not available");const y=[];if(e.isCrossDenomination&&e.convertedUsdAmount&&e.destinationTokenAddress){const b=e.selectedDepositAssets[0]?.asset;if(b){const R=D.parseUnits(e.selectedDepositAssets[0].amount,b.decimals);y.push({from:e.address,to:r,token:B.normalizeNativeTokenAddress(b.address),amount:R}),y.push({from:"escrow",to:e.address,token:e.destinationTokenAddress,amount:e.convertedUsdAmount})}}y.length>0&&m[1]&&(m[1].tokenTransfers=y);const C=p.createInitialSteps(m,b=>p.getChainName(b));let k=!1;if(await e.execution.execute(m,B.ZERO_ADDRESS,0n,b=>{if(b.intentId&&!k){k=!0;for(const R of t)Bs(e.address,s,B.normalizeNativeTokenAddress(R.asset.address));e.startStatusPolling(b.intentId,C)}},void 0,{userOverride:e.address,useCustomTransfers:!0,skipPreSubmitFeeEstimate:!0,skipUserFundingPreflight:!0}),e.refreshAssets(),e.onDepositExecute&&t[0]?.amount)try{e.setPostDepositStatus("executing"),await e.onDepositExecute(u||t[0].amount),e.setPostDepositStatus("success"),e.setPostDepositAmount(u||t[0].amount),e.setPostDepositSuccess(!0)}catch(b){console.error("ctx.onDepositExecute failed (7702):",b),e.setPostDepositStatus("error"),e.setPostDepositError(b?.message||"Post-deposit instruction failed")}e.onDepositSelect&&e.onDepositSelect(t[0].asset)}}catch(s){n=!0,console.error("[DepositModal] executeDeposit CAUGHT ERROR:",s),console.error("[DepositModal] Error details:",{message:s?.message,code:s?.code,name:s?.name,stack:s?.stack?.slice(0,500)}),e.setError(p.sanitizeError(s,"Deposit failed")),e.clearStatus()}finally{e.setIsExecuting(!1),n&&e.setDirectDepositStatus("idle"),n||!e.getCurrentIntentStatus()&&e.getCurrentPostDepositStatus()!=="idle"||e.setShowConfirmation(!1)}}async function Ei(e){const{asset:t,assetIndex:n,selectedAssetCount:s,address:r,escrowOnly:a,isNon7702:i}=e;if(n!==0||i||s>1||!r||t.balance<=0n)return null;const d=await No({address:r,depositQuote:{asset:t,amount:t.balance,token:B.normalizeNativeTokenAddress(t.address),chainId:t.chainId},escrowOnly:a}),u=a?t.balance:t.balance>d.fee?t.balance-d.fee:0n;return So(u,t.decimals)}async function No(e){const{address:t,depositQuote:n,escrowOnly:s}=e,{asset:r,amount:a,token:i,chainId:d}=n,u=B.getEscrowContractAddress(d),c=r.isNative||B.isNativeToken(i),f=a>1n?1n:0n,h=[c?{to:u,value:a,data:"0x"}:{to:i,value:0n,data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"transfer",args:[u,a]})}];f>0n&&h.push(c?{to:B.SPICE_GAS_FEE_RECIPIENT,value:f,data:"0x"}:{to:i,value:0n,data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"transfer",args:[B.SPICE_GAS_FEE_RECIPIENT,f]})});const g={chainId:d,tokenTransfers:[],calls:h},x=(await p.relayerService.estimateBatchGas({user:t,outputToken:i,chainBatches:[{...g,hash:B.hashChainBatches([g])[0].hash}]})).gasFee,m=s&&x<a?a-x:a;return{fee:x,net:m,token:i,chainId:d}}const ji=({selectedDepositAssets:e,depositAssets:t,secondAssetOptions:n,loadingAssets:s,allowSecondAsset:r,theme:a,styles:i,dark:d,dk:u,onSelect:c,onAmountChange:f,onAdd:h,onRemove:g,resolveMaxAmount:x,onViewAllAssets:m})=>o.jsxs(o.Fragment,{children:[e.map((y,C)=>{const k=e.length===1?"Deposit":`Asset ${C+1}`;return o.jsxs("div",{style:{marginBottom:a.spacing.md,position:"relative"},children:[o.jsx(vn,{assets:C===0?t:n,selectedAsset:y||void 0,onAssetSelect:b=>c(b,C),onAmountChange:b=>f(b,C),loading:s,label:k,showBalance:!0,theme:a,styles:i,allowSecondAsset:r&&C===0,onAddAsset:h,canAddAsset:e.length===1&&!!e[0]?.asset,resolveMaxAmount:x?b=>x(b,C):void 0,onViewAllAssets:C===0?m:void 0}),C===1&&o.jsx("button",{onClick:()=>g(C),style:{position:"absolute",top:"-2px",right:"-2px",background:d?`${u.cardBg}ee`:"rgba(255, 255, 255, 0.9)",border:`1px solid ${u.cardBorder}`,borderRadius:"50%",cursor:"pointer",color:a.colors.textMuted,fontSize:"16px",padding:"2px",width:"22px",height:"22px",display:"flex",alignItems:"center",justifyContent:"center",transition:p.transition.interactive,boxShadow:"0 1px 3px rgba(0, 0, 0, 0.1)"},onMouseEnter:b=>{b.currentTarget.style.color=d?u.errorText:"#ef4444",b.currentTarget.style.background=d?u.cardBg:"#fff",b.currentTarget.style.borderColor=d?u.errorBorder:"#fecaca"},onMouseLeave:b=>{b.currentTarget.style.color=a.colors.textMuted,b.currentTarget.style.background=d?`${u.cardBg}ee`:"rgba(255, 255, 255, 0.9)",b.currentTarget.style.borderColor=d?u.cardBorder:"#e5e7eb"},title:"Remove asset",children:"\xD7"})]},`asset-${C}`)}),e.length===0&&o.jsx("div",{style:{marginBottom:a.spacing.md},children:o.jsx(vn,{assets:t,selectedAsset:void 0,onAssetSelect:y=>c(y,0),onAmountChange:y=>f(y,0),loading:s,label:"Deposit",showBalance:!0,theme:a,styles:i,allowSecondAsset:r,onAddAsset:h,canAddAsset:!1,resolveMaxAmount:x?y=>x(y,0):void 0},"initial-selector")})]}),Fi=l.memo(ji);var Rs="data:image/svg+xml,%3csvg width='10' height='10' viewBox='0 0 10 10' fill='none' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M5 4.99995V6.99995M5 3.31245V3.31189M9.5 5C9.5 7.48528 7.48528 9.5 5 9.5C2.51472 9.5 0.5 7.48528 0.5 5C0.5 2.51472 2.51472 0.5 5 0.5C7.48528 0.5 9.5 2.51472 9.5 5Z' stroke='black' stroke-opacity='0.4' stroke-linecap='round' stroke-linejoin='round'/%3e%3c/svg%3e";const Po=l.memo(({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,onDepositSelect:s,depositBatches:r,supportedChains:a,title:i,styles:d,onDepositAssetChange:u,assetInputHook:c,externalWalletAddress:f,onDepositAmountChange:h,allowSecondAsset:g=!1,destinationChainId:x,destinationTokenAddress:m,onDepositExecute:y,depositActionLabel:C,nativeChainId:k,sponsorGas:b=!1,preSelectedAsset:R,escrowOnly:v=!1,escrowTokenAddress:w,escrowAmount:T,escrowTokenDecimals:I,escrowTokenSymbol:F,onDepositSuccess:j,onDepositError:A,embeddedWalletAddress:E,onViewAllAssets:S})=>{const M=l.useContext(p.SpiceFlowProviderContext),U=M?.mode||"7702",W=M?.allowedTokens,O=!!M?.isWhitelistGateActive,z=!v&&!!M?.isWhitelistConfigured&&M?.isUserWhitelisted!==!0,N=c?.assetAmount||"",{theme:P,dark:Q,appName:K,primaryColor:V,dk:X}=p.useSpiceBrand(d),xe=p.useWallet(),{isReady:H,isAuthenticated:J}=xe,{externalWallet:se}=p.useProviderWallets(),ce=M?.embeddedWalletAddress||E,de=U!="7702",ve=de?!!f:H&&J&&!!ce,pe=ce,fe=f,Ee=pe??fe,{data:L}=Qt.useWalletClient(),[ee,te]=l.useState(L),oe=l.useRef(null),Z=l.useRef(se);Z.current=se;const ne=se?.address;l.useEffect(()=>{const q=Z.current;if(!q||!fe){oe.current=null,te(L);return}if(q.address?.toLowerCase()!==fe?.toLowerCase()){oe.current=null,te(L);return}q.getEthereumProvider().then(async ie=>{oe.current=ie;const Se=await ie.request({method:"eth_chainId"}),me=parseInt(Se,16),$e=p.getChainConfig(me),_e=await q.getWalletClient(me);te($e?D.createWalletClient({account:fe,chain:$e.viemChain,transport:D.custom(ie)}):_e)}).catch(()=>{oe.current=null,te(L)})},[ne,fe,L]);const ge=l.useRef(null),[G,Ie]=l.useState([]),{assets:ze,loading:Ke,error:Ft,refreshAssets:mt}=ls({address:v?pe:fe||pe,supportedChains:a,fetchBalances:is,enabled:e,refreshInterval:e?5e3:0}),Le=l.useMemo(()=>{if(O)return[];const q=a.flatMap(ie=>p.getAllAssetsForChain(ie,ze));return W&&W.length>0?q.filter(ie=>W.includes(ie.symbol.toLowerCase())||ie.isNative&&W.includes("native")).sort((ie,Se)=>{const me=ie.balance>BigInt(0)?1:0;return(Se.balance>BigInt(0)?1:0)-me}):q.filter(ie=>ie.balance>BigInt(0))},[a,ze,W,O]),le=l.useMemo(()=>{if(!G[0]?.asset)return[];const q=G[0].asset.chainId;return Le.filter(ie=>ie.chainId===q)},[Le,G]),[Ae,Xe]=l.useState(!1),[et,ae]=l.useState(null),nt=l.useRef(A);nt.current=A;const ke=l.useCallback(q=>{ae(q),typeof q=="string"&&q&&nt.current?.(q,p.getRelayerErrorDetail(q))},[]),[we,he]=l.useState("idle"),Me=l.useCallback(q=>{typeof q=="string"&&q&&nt.current?.(q,p.getRelayerErrorDetail(q))},[]),[xt,yt]=l.useState(!1),[Bt,Fe]=l.useState(null),[Ge,Ct]=l.useState("idle"),[kt,Tt]=l.useState(null),[Oe,st]=l.useState(null),[Mt,bt]=l.useState(null),[ue,He]=l.useState(null),[ot,ct]=l.useState(null),{intentStatus:be,startStatusPolling:gt,clearStatus:Rt,execute:Je}=mn(),Be=l.useCallback((q,ie)=>{const Se=p.CHAIN_CONFIGS[ie];return Se?Se.supportedTokens?.find(me=>p.addressesEqual(me.address,q))?.symbol??null:null},[]),rt=l.useMemo(()=>{const q=G[0]?.asset;if(!q||!m||!x)return!1;const ie=Be(m,x);return Aa(q.symbol)&&!!ie&&Ia(ie)},[G,m,x,Be]);l.useEffect(()=>{G.length>0&&N!==G[0]?.amount&&Ie(q=>{if(q.length===0)return q;const ie=[...q];return ie[0]={...ie[0],amount:N||""},ie})},[N]),l.useEffect(()=>{G.length!==0&&Ie(q=>{let ie=!1;const Se=q.map(me=>{if(!me.asset)return me;const $e=Le.find(_e=>_e.chainId===me.asset.chainId&&p.addressesEqual(_e.address,me.asset.address));return $e?$e===me.asset||$e.balance===me.asset.balance?me:(ie=!0,{...me,asset:$e,amount:me.amount}):me});return ie?Se:q})},[Le,G.length]),l.useEffect(()=>{if(!R||G.length>0||Le.length===0)return;const q=Le.find(ie=>ie.chainId===R.chainId&&p.addressesEqual(ie.address,R.address));q&&(Ie([{asset:q,amount:""}]),u?.(q))},[R,Le,G.length]);const Wt=l.useRef(null);l.useEffect(()=>{if(de&&be?.overallStatus==="success"&&y&&we==="idle"){const q=Wt.current,ie=ge.current;q&&(async()=>{try{he("executing"),await y(q),he("success"),Fe(q),yt(!0);const Se=Array.isArray(ie)?ie[0]:void 0,me={type:"deposit",status:"success",amount:q,asset:Se?.tokenAddress,sourceChain:Se?String(Se.chainId):void 0,txHash:Se?.txHash};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:me})),j?.(me)}catch(Se){console.error("onDepositExecute failed:",Se),he("error"),Me(p.sanitizeError(Se,"Post-deposit instruction failed"))}finally{Wt.current=null,ge.current=null}})()}},[be?.overallStatus,de,we]);const dt=l.useCallback(()=>{ke(null)},[]);l.useEffect(()=>{e||(yt(!1),Fe(null),Ct("idle"),Tt(null),st(null))},[e]);const Qe=l.useCallback((q,ie)=>{Ie(Se=>{const me=[...Se];return me[ie]={asset:q,amount:me[ie]?.amount||""},me}),ie===0&&u?.(q),dt()},[u,dt]),We=l.useCallback(async(q,ie)=>{if(Ie(Se=>{const me=[...Se];return me[ie]&&(me[ie]={...me[ie],amount:q}),me}),dt(),ie===0)if(c?.setAssetAmount(q),rt&&q&&parseFloat(q)>0)try{const Se=Mt??await Sa();Mt||bt(Se);const me=G[0]?.asset;if(!me)return;const $e=D.parseUnits(q,me.decimals),_e=m?Be(m,x):null,sn=p.CHAIN_CONFIGS[x]?.supportedTokens?.find(ts=>p.addressesEqual(ts.address,m))?.decimals??6,Dn=Ea($e,me.decimals,sn,Se);He(Dn);const Mn=D.formatUnits(Dn,sn),es=Se.toLocaleString("en-US",{maximumFractionDigits:0});ct(`${q} ${me.symbol} \u2248 $${parseFloat(Mn).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})} ${_e??"USD"} (rate: $${es}/BTC)`),h?.(Mn)}catch(Se){console.error("Failed to fetch BTC/USD price:",Se),ct(null),He(null),h?.(q)}else ct(null),He(null),h?.(q)},[dt,c,h,rt,Mt,G,m,x,Be]),ut=l.useCallback(()=>{G.length<2&&Ie(q=>[...q,{asset:null,amount:""}])},[G.length]),At=l.useCallback(q=>{Ie(ie=>ie.filter((Se,me)=>me!==q)),dt()},[dt]),Ve=l.useRef(!1),Ht=l.useRef(!1);l.useEffect(()=>{e||(Ve.current=!1,Ht.current=!1,ft(null),it(null))},[e]);const[De,pt]=l.useState(!1),[Nt,at]=l.useState(null),[Te,ft]=l.useState(null),[ht,it]=l.useState(null),[qe,It]=l.useState(!1),[Y,$]=l.useState(null),re=l.useMemo(()=>{const q=G[0];if(G.length!==1||!q?.asset||!q.amount||parseFloat(q.amount)<=0)return null;try{return{asset:q.asset,amount:D.parseUnits(q.amount,q.asset.decimals),token:B.normalizeNativeTokenAddress(q.asset.address),chainId:q.asset.chainId}}catch{return null}},[G]),Ne=l.useMemo(()=>re?[re.chainId,re.token.toLowerCase(),re.amount.toString(),v?"escrow":"normal"].join("|"):null,[re,v]),_=l.useCallback(async q=>pe?No({address:pe,depositQuote:q,escrowOnly:v}):null,[pe,v]),Ce=l.useCallback(async()=>re?_(re):null,[re,_]),Pe=l.useRef(Ce);Pe.current=Ce,l.useEffect(()=>{let q=!1;if(!e||de||!Ne||De||Ae){ft(null),$(null),It(!1);return}const ie=async()=>{$(null),It(!0);try{const me=await Pe.current();q||ft(me)}catch(me){if(q)return;ft(null),$(me instanceof Error?me.message:"Failed to estimate gas fee")}finally{q||It(!1)}};ie();const Se=window.setInterval(()=>{ie()},1e4);return()=>{q=!0,window.clearInterval(Se)}},[e,de,Ne,De,Ae]),l.useEffect(()=>{De||Ae||it(null)},[De,Ae,Ne]);const lt=async()=>{if(G.length===0||!G[0]?.asset)return;const q=G.filter(_e=>_e.asset&&_e.amount&&parseFloat(_e.amount)>0);if(q.length===0)return;const ie=q[0],Se=p.getChainConfig(ie.asset.chainId),me=q.map(_e=>{const sn=parseFloat(_e.amount);return`${isNaN(sn)?_e.amount:sn.toPrecision(6).replace(/\.?0+$/,"")} ${_e.asset.symbol}`}).join(", "),$e={network:Se?.displayName||`Chain ${ie.asset.chainId}`,amount:me,symbol:"",chainId:ie.asset.chainId};if(!de&&q.length===1&&Te){it(Te);const _e=q[0];$e.creditedAmount=`${D.formatUnits(Te.net,_e.asset.decimals)} ${_e.asset.symbol}`,$e.networkFee=`${D.formatUnits(Te.fee,_e.asset.decimals)} ${_e.asset.symbol}`}at($e),pt(!0)},Ue=l.useRef(be);Ue.current=be;const vt=l.useRef(we);vt.current=we;const Re=async()=>{await Ii({selectedDepositAssets:G,escrowOnly:v,sourceAddress:fe,isNon7702:de,address:pe,embeddedWalletAddress:ce,isReady:H,isAuthenticated:J,zeroCreditError:je,depositBalanceError:St,externalWalletClient:ee,externalProvider:oe.current,effectiveDepositFee:Ze,depositBatches:r,destinationChainId:x,destinationTokenAddress:m,isCrossDenomination:rt,convertedUsdAmount:ue,mode:U,sponsorGas:b,nativeChainId:k,spiceBalanceUser:Ee,depositDataRef:ge,bridgedAmountRef:Wt,setIsExecuting:Xe,setError:ke,setConfirmationData:at,setShowConfirmation:pt,setDirectDepositStatus:Ct,setDirectDepositChainId:st,setDirectDepositTxHash:Tt,setPostDepositStatus:he,setPostDepositError:Me,setPostDepositAmount:Fe,setPostDepositSuccess:yt,startStatusPolling:gt,clearStatus:Rt,refreshAssets:mt,onDepositExecute:y,onDepositSelect:s,onDepositSuccess:j,execution:{execute:Je},getCurrentIntentStatus:()=>Ue.current,getCurrentPostDepositStatus:()=>vt.current})},je=l.useMemo(()=>{for(const q of G)if(!(!q?.asset||!q.amount||parseFloat(q.amount)<=0))try{const ie=q.asset.decimals,Se=D.parseUnits(q.amount,ie);if(Se<=0n)continue;const me=B.getEquivalenceGroup(B.normalizeNativeTokenAddress(q.asset.address)),$e=q.asset.receiptTokenDecimals??(me==="ETH"||me==="ARB"?18:me==="USDC"||me==="SUSD"||me==="WBTC"||me==="CBTC"?6:void 0);if($e===void 0||ie<=$e||B.convertAmountBetweenDecimals(Se,ie,$e)>0n)continue;return`Amount too small. Minimum deposit for this asset is ${D.formatUnits(10n**BigInt(ie-$e),ie)} ${q.asset.symbol}.`}catch{continue}return null},[G]),Ye=!de&&!!re,Ze=ht??Te,Et=!!re&&!!Ze&&Ze.chainId===re.chainId&&p.addressesEqual(Ze.token,re.token),St=l.useMemo(()=>{if(!Ye||!re||!Et)return null;const q=v?re.amount:re.amount+Ze.fee;return re.asset.balance>=q?null:`Insufficient ${re.asset.symbol}. Need ${D.formatUnits(q,re.asset.decimals)} ${re.asset.symbol} including gas.`},[Ye,re,Et,Ze,v]),[cn,Dt]=l.useState(!1),Ut=G[0]?.asset?.chainId,wt=ze.find(q=>q.isNative&&q.chainId===Ut)?.balance??0n;l.useEffect(()=>{if(!e||!Ut){Dt(!1);return}let q=!1;return(async()=>{try{const ie=await p.getClientForChain(Ut).getGasPrice()*150000n;q||Dt(wt<ie)}catch{q||Dt(!1)}})(),()=>{q=!0}},[e,Ut,wt]);const tn=!Ye||Et&&!qe&&!Y&&!St,nn=l.useCallback((q,ie)=>Ei({asset:q,assetIndex:ie,selectedAssetCount:G.length,address:pe,escrowOnly:v,isNon7702:de}),[de,G.length,pe,v]),dn=l.useMemo(()=>{if(!re||!Ze||!Et)return null;const q=v?re.amount:re.amount+Ze.fee;return{symbol:re.asset.symbol,decimals:re.asset.decimals,grossAmount:q,netAmount:Ze.net,totalFee:Ze.fee,gasFee:Ze.fee,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"estimated"}},[re,Ze,Et,v]),Lt=parseFloat(G[0]?.amount||"")||0,yn=Lt>0&&Lt<Kt,un=G.length>0&&G[0]?.asset&&G[0]?.amount&&Lt>0&&!yn&&ve&&!Ae&&!je&&!St&&tn&&!z;l.useEffect(()=>{if(!v||!w||!T||Ve.current||!ve)return;const q=a[0];if(!q)return;const ie=p.getAllAssetsForChain(q,[]).find(me=>p.addressesEqual(me.address,w));let Se;if(ie)Se=ie;else if(I!==void 0&&F)Se={address:w,symbol:F,name:F,decimals:I,chainId:q,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,isNative:B.isNativeToken(w)};else{console.warn("[DepositModal] escrowOnly: no matching asset and missing escrowTokenDecimals/escrowTokenSymbol for",w);return}Ve.current=!0,Ie([{asset:Se,amount:T}])},[v,w,T,I,F,ve,a]),l.useEffect(()=>{!v||!un||Ht.current||Ae||(Ht.current=!0,Re())},[v,un,Ae]);const Tn=Ft||et||je||St,Rn=()=>{if(Ae)return"Executing Deposit...";if(!ve)return"Wallet Not Connected";if(U==="7702"){if(!H)return"Loading...";if(!J)return"Authentication Required"}return G[0]?.asset?G[0]?.amount?yn?`MINIMUM ${Kt}`:je?"AMOUNT TOO SMALL":St?"INSUFFICIENT BALANCE":Ye&&!tn?Y?"GAS UNAVAILABLE":"ESTIMATING GAS":"DEPOSIT":"ENTER AMOUNT":"SELECT TOKEN"};return e?o.jsx(Vt,{isOpen:e,onClose:t,closeOnBackdropClick:n,title:i||`Deposit to your ${K} account`,subtitle:o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[o.jsx("img",{src:Rs,alt:"","aria-hidden":"true",style:{width:"13px",height:"13px",flexShrink:0,...Q?{filter:"invert(0.6)"}:{}}}),o.jsx("p",{style:{fontSize:"12px",color:X.textSecondary,margin:"0",lineHeight:"1.4",fontFamily:p.font.ui},children:`Deposit collateral to your ${K} Account from any supported network.`})]}),dark:Q,overlayContent:De||be||we!=="idle"&&y?o.jsx("div",{}):void 0,styles:d,theme:P,children:o.jsxs("div",{style:{padding:"24px 24px 5px 24px"},children:[o.jsx(Fi,{selectedDepositAssets:G,depositAssets:Le,secondAssetOptions:le,loadingAssets:Ke,allowSecondAsset:g,theme:P,styles:d,dark:Q,dk:X,onSelect:Qe,onAmountChange:We,onAdd:ut,onRemove:At,resolveMaxAmount:nn,onViewAllAssets:S}),Ye&&re&&o.jsx(Is,{fontFamily:d?.fontFamily||P.typography.fontFamily,textPrimary:X.textPrimary,textSecondary:X.textSecondary,cardBg:Q?X.inputBg:"#ffffff",cardBorder:X.cardBorder,resolvedDark:Q,darkCardBorder:X.cardBorder,primaryColor:V,feePreview:dn,isLoading:qe||Ye&&!Et,errorText:Y}),o.jsx(bi,{intentStatus:be,postDepositSuccess:xt,postDepositAmount:Bt,postDepositStatus:we,depositActionLabel:C,sourceChainName:G[0]?.asset?.chainId?p.getChainName(G[0].asset.chainId):"Destination Chain",directDepositStatus:Ge,directDepositTxHash:kt,directDepositChainId:Oe,styles:d}),o.jsx(Ci,{isOpen:De||!!be||we!=="idle"&&!!y,onClose:()=>{pt(!1),be&&Rt();const q=we==="success"&&!be,ie=be?.overallStatus==="success"&&(y?we==="success":!0);(q||ie)&&t()},onConfirm:Re,data:Nt,isExecuting:Ae,error:et,theme:P,styles:d,intentStatus:be,postDepositStatus:we,hasPostDepositInstruction:!!y}),ot&&o.jsxs(co,{dk:X,dark:Q,borderRadius:P.borderRadius.md,children:["\u26A1 ",ot]}),cn&&o.jsx(co,{dk:X,dark:Q,borderRadius:P.borderRadius.md,children:"Low native balance in the external wallet. The deposit to spicenet account might fail."}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:0,marginBottom:0,margin:0,padding:0},children:[Tn?o.jsx("div",{style:{marginBottom:"10px",fontSize:"12px",lineHeight:"1.45",color:X.errorText,fontFamily:d?.fontFamily||P.typography.fontFamily},children:Tn}):null,o.jsx(p.Button,{variant:"outline",fullWidth:!0,onClick:lt,disabled:!un||!ve||Ae,theme:P,dark:Q,styles:d,children:Rn()})]})]})}):null}),Bi=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,deposits:s,onComplete:r,onCancel:a,onSkip:i,onChangeWallet:d,isProcessing:u,error:c,styles:f})=>{const{dark:h,dk:g,theme:x}=p.useSpiceBrand(f);if(!e||s.length===0)return null;const m=s[0],y=f?.fontFamily||p.font.ui,C=p.font.mono,k=p.getChainName(m.chainId),b=parseFloat(m.amount).toPrecision(6).replace(/\.?0+$/,""),R=D.formatUnits(m.verifiedBalance,m.tokenDecimals);return o.jsx(Vt,{isOpen:e,onClose:t,title:"Incomplete Deposit",styles:f,closeOnBackdropClick:n,children:o.jsxs("div",{style:{padding:"18px 24px 24px",fontFamily:y},children:[o.jsx("p",{style:{fontSize:"14px",color:g.textSecondary,lineHeight:"1.6",margin:"0 0 18px 0"},children:"Your funds reached your wallet, but the deposit didn't finish."}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) auto",gap:"14px 18px",marginBottom:"24px",padding:"16px 18px",backgroundColor:h?g.cardBg:"#f8fafc",border:`1px solid ${g.cardBorder}`,borderRadius:h?"14px":"10px",boxShadow:h?"inset 0 1px 0 rgba(255,255,255,0.03)":"0 1px 2px rgba(16,24,40,0.04)"},children:[o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px"},children:[o.jsx("span",{style:{fontSize:"12px",fontWeight:600,color:g.textSecondary,fontFamily:C,letterSpacing:"0.8px"},children:"NETWORK"}),o.jsx("span",{style:{fontSize:"18px",fontWeight:600,color:g.textPrimary,fontFamily:y,lineHeight:1.2},children:k})]}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px",alignItems:"flex-end",textAlign:"right"},children:[o.jsx("span",{style:{fontSize:"12px",fontWeight:600,color:g.textSecondary,fontFamily:C,letterSpacing:"0.8px"},children:"DEPOSITED AMOUNT"}),o.jsxs("span",{style:{fontSize:"24px",fontWeight:700,color:g.successText,fontFamily:C,lineHeight:1.1},children:[b," ",m.tokenSymbol]}),o.jsx("span",{style:{fontSize:"12px",color:g.textSecondary,fontWeight:500,fontFamily:y},children:"Sent to embedded wallet"})]})]}),!m.hasFullBalance&&m.verifiedBalance>0n&&o.jsxs("div",{style:{marginBottom:"16px",padding:"8px 12px",backgroundColor:g.warningBg,border:`1px solid ${h?g.warningBorder:"#fcd34d"}`,borderRadius:"8px",fontSize:"13px",color:g.warningText,lineHeight:"1.4"},children:["Partial balance \u2014 only ",parseFloat(R).toFixed(4)," ",m.tokenSymbol," available."]}),c&&o.jsx("div",{style:{marginBottom:"16px",padding:"10px 12px",backgroundColor:g.errorBg,border:`1px solid ${h?g.errorBorder:"#fca5a5"}`,borderRadius:"8px",fontSize:"13px",color:h?g.errorText:"#991b1b",lineHeight:"1.4"},children:c}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[o.jsx(p.Button,{variant:"outline",fullWidth:!0,disabled:u,onClick:()=>r(m),theme:x,dark:h,styles:f,children:"CONFIRM DEPOSIT"}),o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:[o.jsx(p.Button,{variant:"ghost",fullWidth:!0,disabled:u,onClick:()=>a(m),theme:x,dark:h,style:{height:"48px",fontSize:"13px",letterSpacing:"0.4px",color:h?g.textPrimary:"#374151",border:`1px solid ${h?g.cardBorder:"#d1d5db"}`,borderRadius:"12px",backgroundColor:h?"rgba(255,255,255,0.02)":"#ffffff"},children:u?"RETURNING...":"RETURN FUNDS"}),o.jsxs("div",{style:{display:"grid",gridTemplateColumns:d?"1fr 1fr":"1fr",gap:"10px"},children:[o.jsx(p.Button,{variant:"ghost",fullWidth:!0,disabled:u,onClick:i,theme:x,dark:h,style:{height:"44px",fontSize:"12px",letterSpacing:"0.4px",color:g.textSecondary,border:`1px solid ${h?g.cardBorder:"#d1d5db"}`,borderRadius:"12px",backgroundColor:"transparent"},children:"START OVER"}),d&&o.jsx(p.Button,{variant:"ghost",fullWidth:!0,disabled:u,onClick:d,theme:x,dark:h,style:{height:"44px",fontSize:"12px",letterSpacing:"0.4px",color:g.textSecondary,border:`1px solid ${h?g.cardBorder:"#d1d5db"}`,borderRadius:"12px",backgroundColor:"transparent"},children:"CHANGE WALLET"})]})]})]}),s.length>1&&o.jsxs("p",{style:{fontSize:"12px",color:g.textSecondary,textAlign:"center",marginTop:"14px",marginBottom:0,lineHeight:"1.5"},children:[s.length," incomplete deposits found \u2014 resolving one at a time."]})]})})},Ds=e=>{const[t,n]=l.useState(!1),s=l.useContext(p.SpiceFlowProviderContext),{dark:r,dk:a}=p.useSpiceBrand();if(l.useEffect(()=>{n(!0)},[]),!t)return o.jsx("div",{className:e.className,children:o.jsx("button",{disabled:!0,style:{padding:"12px 24px",fontSize:"16px",backgroundColor:r?a.hoverBg:"#ccc",color:r?a.textSecondary:"white",border:r?`1px solid ${a.buttonBorder}`:"none",borderRadius:"4px",cursor:"not-allowed"},children:"Loading..."})});if(!s){const i='ProviderLogin must be used within SpiceFlowProvider. Please wrap your app with <SpiceFlowProvider provider="privy">.';return o.jsx("div",{className:e.className,children:o.jsx("button",{onClick:()=>{e.onAuthError&&e.onAuthError(i)},style:{padding:"12px 24px",fontSize:"16px",backgroundColor:r?a.errorBg:"#dc2626",color:r?a.errorText:"white",border:r?`1px solid ${a.errorBorder}`:"none",borderRadius:"4px",cursor:"pointer"},children:"Provider Not Found"})})}return o.jsx(p.PrivyLogin,{...e})},Ti=.01,Ri=5*60*1e3;function Di(e){const t=Number(D.formatUnits(e.verifiedBalance,e.tokenDecimals));return Number.isFinite(t)?t:0}async function Mi(e){const t=Wi(e);let n;try{n=await hs(t.map(s=>s.tokenSymbol))}catch{return t}return t.filter(s=>{const r=Di(s);if(r<=0)return!0;const a=n[s.tokenSymbol.toUpperCase()]??0;return!Number.isFinite(a)||a<=0?!0:r*a>=Ti})}function Wi(e){const t=new Map;for(const n of e){const s=`${n.chainId}:${n.tokenAddress.toLowerCase()}`;t.get(s)||t.set(s,{...n,amount:n.timestamp===0?D.formatUnits(n.verifiedBalance,n.tokenDecimals):n.amount,rawAmount:n.timestamp===0?n.verifiedBalance.toString():n.rawAmount,hasFullBalance:n.timestamp===0?!0:n.hasFullBalance})}return Array.from(t.values())}function Uo(e,t){const[n,s]=l.useState([]),[r,a]=l.useState(!1),i=l.useRef(t);i.current=t;const d=l.useRef(0),u=l.useRef(0),c=l.useCallback(async({forceDiscovery:f=!1}={})=>{if(!e){s([]),a(!1);return}const h=++u.current,g=()=>h!==u.current;a(!0);try{const x=[],m=vi(e);for(const b of m){if(g())return;try{const R=p.getClientForChain(b.chainId);let v;if(b.isNative||B.isNativeToken(b.tokenAddress)?v=await Pt.getBalance(R,{address:e}):v=await Pt.readContract(R,{address:D.getAddress(b.tokenAddress),abi:D.erc20Abi,functionName:"balanceOf",args:[e]}),g())return;v>0n?x.push({...b,verifiedBalance:v,hasFullBalance:v>=BigInt(b.rawAmount)}):Date.now()-b.timestamp>15*60*1e3&&Bs(e,b.chainId,b.tokenAddress)}catch(R){console.warn(`[usePendingDeposit] Failed to verify balance for ${b.tokenSymbol} on chain ${b.chainId}:`,R),x.push({...b,verifiedBalance:0n,hasFullBalance:!1})}}if(g())return;const y=i.current,C=Date.now(),k=(y?.discoverWalletBalances??!0)&&(f||C-d.current>=Ri);if(y?.network&&k){d.current=C;const b=y.chainIds??B.getChainIdsByNetwork(y.network),R=new Set(x.map(w=>`${w.chainId}:${w.tokenAddress.toLowerCase()}`)),v=[];for(const w of b){const T=p.getChainConfig(w);if(T?.supportedTokens)for(const I of T.supportedTokens){if(B.isNativeToken(I.address))continue;const F=`${w}:${I.address.toLowerCase()}`;R.has(F)||v.push((async()=>{try{const j=p.getClientForChain(w),A=await Pt.readContract(j,{address:D.getAddress(I.address),abi:D.erc20Abi,functionName:"balanceOf",args:[e]});return A>0n?{chainId:w,tokenAddress:I.address,tokenSymbol:I.symbol,tokenDecimals:I.decimals,amount:D.formatUnits(A,I.decimals),rawAmount:A.toString(),embeddedWalletAddress:e,externalWalletAddress:"",timestamp:0,isNative:!1,verifiedBalance:A,hasFullBalance:!0}:null}catch{return null}})())}}if(v.length>0){const w=await Promise.allSettled(v);if(g())return;for(const T of w)T.status==="fulfilled"&&T.value&&x.push(T.value)}}if(!g()){const b=await Mi(x);if(g())return;s(b)}}catch(x){console.error("[usePendingDeposit] Verification error:",x),g()||s([])}finally{g()||a(!1)}},[e]);return l.useEffect(()=>{if(!i.current?.enabled){u.current++,s([]),a(!1);return}c({forceDiscovery:!0});const f=i.current?.pollIntervalMs??3e4;if(f<=0||!e)return()=>{u.current++};const h=setInterval(()=>{c({forceDiscovery:!1})},f),g=()=>c({forceDiscovery:!0});return window.addEventListener(Kn,g),()=>{u.current++,window.removeEventListener(Kn,g),clearInterval(h)}},[c,e]),{pendingDeposits:n,loading:r,refresh:()=>c({forceDiscovery:!0})}}function Ni(e,t,n,s,r){return{address:t,symbol:n||"UNKNOWN",name:n||"Unknown Token",decimals:s||18,chainId:e,balance:0n,balanceFormatted:r?parseFloat(r):0,balanceUsd:0,isNative:B.isNativeToken(t)}}const Pi=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,styles:s,depositBatches:r,onDepositAmountChange:a,destinationChainId:i,destinationTokenAddress:d,onDepositExecute:u,depositActionLabel:c,sponsorGas:f=!1,escrowRecovery:h,skipTokenSelection:g=!1,onDepositSuccess:x,onDepositError:m,skipRecovery:y=!1})=>{const C=l.useContext(p.SpiceFlowProviderContext);if(!C)return o.jsx("div",{children:"Error: SpiceDeposit must be used within SpiceFlowProvider"});const k=(C.mode||"7702")!="7702",b=k,R=C.nativeChainId,v=C.network||"testnet",{dark:w,dk:T}=p.useSpiceBrand(s),I=!!h,F=p.useWallet(),{isReady:j,isAuthenticated:A,actions:E}=F,S=C?.embeddedWalletAddress,{address:M}=Qt.useAccount(),U=C?.externalWalletAddress??M,W=!!U,O=()=>g?"deposit":"select-token",z=()=>b?W?O():"connect-wallet":"provider-login",[N,P]=l.useState(z()),[Q,K]=l.useState(null),[V,X]=l.useState(!1),{pendingDeposits:xe,loading:H,refresh:J}=Uo(S,{enabled:e,network:v,chainIds:C.supportedChainIds}),[se,ce]=l.useState(null),[de,ve]=l.useState(!1),[pe,fe]=l.useState(null),[Ee,L]=l.useState(!1),[ee,te]=l.useState("idle");l.useEffect(()=>{e&&!y&&!I&&!se&&!Ee&&ee==="idle"&&A&&S&&W&&U&&!H&&xe.length>0&&N!=="recovery"&&N!=="deposit"&&P("recovery")},[e,y,I,A,S,W,U,H,xe,N,se,Ee,ee]);const oe=l.useCallback(le=>{const Ae={address:le.tokenAddress,symbol:le.tokenSymbol,name:le.tokenSymbol,decimals:le.tokenDecimals,chainId:le.chainId,balance:le.verifiedBalance,balanceFormatted:parseFloat(le.amount),balanceUsd:0,isNative:le.isNative};K(Ae),ce(le),P("deposit")},[]),Z=l.useCallback(()=>{L(!0),P(A&&S&&W&&U?g?"deposit":"select-token":A&&S?"connect-wallet":"provider-login")},[A,S,W,U,g]),ne=l.useCallback(()=>{fe(null),te("awaiting-disconnect"),P("connect-wallet")},[]),ge=l.useCallback(async le=>{ve(!0),fe(null);try{if(!S)throw new Error("Embedded wallet not available");const Ae=await E.getEthereumProvider(),Xe=p.getChainConfig(le.chainId);await p.ensureWalletOnChain(Ae,le.chainId);const et=p.getClientForChain(le.chainId),ae=await Pt.getBalance(et,{address:S}),nt=Xe?.viemChain?.name||`chain ${le.chainId}`;if(ae===0n)throw new Error(`Your embedded wallet has no ETH on ${nt} to pay for gas. We recommend completing the deposit instead \u2014 it doesn't require gas.`);const ke=D.createWalletClient({account:S,transport:D.custom(Ae),chain:Xe?.viemChain}),we=le.externalWalletAddress&&D.isAddress(le.externalWalletAddress)?le.externalWalletAddress:U;if(!we||!D.isAddress(we))throw new Error("Connect the external wallet that should receive these funds, then try again.");let he;le.isNative||B.isNativeToken(le.tokenAddress)?he=await ke.sendTransaction({to:we,value:le.verifiedBalance,chain:Xe?.viemChain}):he=await ke.sendTransaction({to:le.tokenAddress,data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"transfer",args:[we,le.verifiedBalance]}),chain:Xe?.viemChain}),await et.waitForTransactionReceipt({hash:he,confirmations:1}),Bs(le.embeddedWalletAddress,le.chainId,le.tokenAddress),J(),xe.length<=1&&P(z())}catch(Ae){const Xe=Ae?.message||"Couldn't return your funds. Please try again.",et=/insufficient funds for gas/i.test(Xe);fe(et?"Not enough ETH in your embedded wallet to cover gas fees. Complete the deposit instead \u2014 it doesn't require gas.":Xe)}finally{ve(!1)}},[E,S,U,xe,J]);l.useEffect(()=>{e||(ce(null),fe(null),ve(!1),L(!1),te("idle"))},[e]),l.useEffect(()=>{if(ee!=="idle"){if(ee==="awaiting-disconnect"){(!W||!U)&&te("awaiting-reconnect");return}e&&!H&&xe.length>0&&A&&S&&(te("idle"),P("recovery"))}},[ee,W,U,e,H,xe,A,S]),l.useEffect(()=>{!I||!e||(A&&S?(X(!0),!Q&&h?.chainId&&h?.tokenAddress&&K(Ni(h.chainId,h.tokenAddress,h.tokenSymbol,h.tokenDecimals,h.amount)),P("deposit")):P("provider-login"))},[I,e,N,A,S]);const{assets:G,loading:Ie}=ls({address:U,supportedChains:C.supportedChainIds,fetchBalances:is,enabled:e&&!!U,refreshInterval:e?5e3:0}),ze=l.useCallback(()=>{X(!0),P(I?"deposit":W?g?"deposit":"select-token":"connect-wallet")},[I,W,g]),Ke=l.useCallback(async()=>{if((!W||!U)&&(await qt(500),!W||!U)){alert("Please connect your wallet first");return}P(g?"deposit":"select-token")},[W,U,g]),Ft=l.useCallback(le=>{K(le),P("deposit")},[]),mt=l.useCallback(()=>{if(K(null),a?.(""),!U){P("connect-wallet");return}P("select-token")},[U,a]),Le=l.useCallback(()=>{t()},[t]);if(l.useEffect(()=>{if(!e){const le=setTimeout(()=>{I||(P(z()),K(null)),X(!1)},300);return()=>clearTimeout(le)}},[e,I,h?.chainId]),l.useEffect(()=>{e&&N==="deposit"&&!Q&&!I&&!se&&!g&&P("select-token")},[e,N,Q,I,se,g]),l.useEffect(()=>{e&&N==="connect-wallet"&&W&&U&&ee==="idle"&&P(g?"deposit":"select-token")},[e,N,W,U,ee,g]),l.useEffect(()=>{if(!b&&e&&N==="provider-login"&&j&&A&&S&&!V){const le=setTimeout(()=>{X(!0),P(W?g?"deposit":"select-token":"connect-wallet")},100);return()=>clearTimeout(le)}},[b,e,N,j,A,S,W,g,V]),!e)return null;if(N==="recovery")return o.jsx(Bi,{isOpen:e,onClose:Le,closeOnBackdropClick:n,deposits:xe,onComplete:oe,onCancel:ge,onSkip:Z,onChangeWallet:ne,isProcessing:de,error:pe,styles:s});if(N==="provider-login"&&!b)return o.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.5)",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",zIndex:50},children:o.jsx("div",{style:{backgroundColor:w?T.cardBg:"white",borderRadius:"9px",padding:"32px 24px",maxWidth:"400px",width:"100%"},children:o.jsx(Ds,{onAuthSuccess:ze,autoTrigger:!0})})});if(N==="connect-wallet")return o.jsx(Na,{isOpen:e,onClose:Le,closeOnBackdropClick:n,onContinue:Ke,requiredChainId:k?R:void 0,styles:s});if(N==="select-token")return U?o.jsx(Da,{isOpen:e,onClose:Le,closeOnBackdropClick:n,onTokenSelect:Ft,walletAddress:U,supportedChainIds:C.supportedChainIds,network:v,prefetchedAssets:Ie?null:G??null,styles:s,dark:w}):(P("connect-wallet"),null);if(N==="deposit"){if(!Q&&!g)return null;const le=!!se;return o.jsx(Po,{isOpen:e,onClose:Le,closeOnBackdropClick:n,supportedChains:Q?[Q.chainId]:C.supportedChainIds??[],styles:s,externalWalletAddress:U,depositBatches:le?void 0:r,onDepositAmountChange:a,destinationChainId:i,destinationTokenAddress:d,onDepositExecute:u,depositActionLabel:c,nativeChainId:R,sponsorGas:f,preSelectedAsset:Q??void 0,escrowOnly:I||le,escrowTokenAddress:le?se.tokenAddress:h?.tokenAddress,escrowAmount:le?se.amount:h?.amount,escrowTokenDecimals:le?se.tokenDecimals:h?.tokenDecimals,escrowTokenSymbol:le?se.tokenSymbol:h?.tokenSymbol,onDepositSuccess:x,onDepositError:m,embeddedWalletAddress:S,onViewAllAssets:g?void 0:mt})}return null},Ui=e=>l.useContext(p.SpiceFlowProviderContext)?o.jsx(Pi,{...e}):o.jsx("div",{children:"Error: SpiceDeposit must be used within SpiceFlowProvider"}),Li=({isOpen:e,onClose:t,onChainSelect:n,supportedChains:s,closeOnSelect:r=!0,styles:a})=>{const{theme:i,dark:d,primaryColor:u,dk:c}=p.useSpiceBrand(a),[f,h]=l.useState(""),[g,x]=l.useState(null),[m,y]=l.useState(null),[C,k]=l.useState(!1),[b,R]=l.useState(null),{switchChainAsync:v}=Qt.useSwitchChain(),w=l.useMemo(()=>new Set(s||[]),[s]),T=l.useMemo(()=>{if(!s||s.length===0)return[];const A=[];return s.forEach((E,S)=>{if(typeof E!="number")return;const M=p.getChainConfig(E);M&&A.push({id:E.toString(),name:M.displayName,icon:Gt[E]||wn,chainId:E,verified:!0,order:S})}),A},[s]);l.useEffect(()=>{g&&!w.has(parseInt(g,10))&&x(null)},[g,w]);const I=l.useMemo(()=>T.filter(A=>A.name.toLowerCase().includes(f.toLowerCase())).sort((A,E)=>A.order-E.order),[T,f]),F=async()=>{if(!g)return;const A=parseInt(g,10);k(!0),R(null);try{await v({chainId:A}),n&&n(g),r&&t()}catch(E){console.error("Failed to switch chain:",E),R(p.sanitizeError(E,"Failed to switch chain."))}finally{k(!1)}},j=!g||C;return o.jsxs(Vt,{isOpen:e,onClose:t,title:"Select Chain",styles:a,theme:i,dark:d,children:[o.jsx("div",{style:{padding:"24px 20px"},children:o.jsx(rs,{value:f,onChange:h,ariaLabel:"Search chains",placeholder:"Search chain name, symbol or address",size:"md",dark:d,styles:a,endAdornment:o.jsx("div",{style:{padding:"5px 5px",borderRadius:"3px",fontSize:"13px",backgroundColor:d?c.cardBg:"#E9E9E9",color:d?c.textSecondary:"#485066",fontWeight:500,flexShrink:0},"aria-hidden":"true",children:"\u2318F"})})}),o.jsx("div",{style:{padding:"0 32px 20px",display:"flex",flexDirection:"column",gap:"12px"},children:I.map(A=>{const E=g===A.id,S=m===A.id;return o.jsxs("button",{onClick:()=>x(A.id),onMouseEnter:()=>y(A.id),onMouseLeave:()=>y(null),style:{width:"100%",display:"flex",alignItems:"center",gap:"16px",padding:"8px",borderRadius:"8px",backgroundColor:E?d?`${u}15`:`${u}12`:"transparent",border:E?d?`1px solid ${u}66`:`1px solid ${u}88`:S?d?`1px solid ${u}44`:`1px solid ${u}66`:"1px solid transparent",cursor:"pointer",transition:p.transition.interactive},children:[o.jsx("div",{style:{width:"40px",height:"40px",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"30px"},children:o.jsx("img",{src:A.icon,alt:A.name,loading:"lazy",decoding:"async",style:{width:"100%",height:"100%",borderRadius:"50%"}})}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",flex:1},children:[o.jsx("span",{style:{fontFamily:p.font.mono,fontSize:"17px",fontWeight:500,letterSpacing:"0.4px",color:c.textPrimary,textAlign:"left"},children:A.name}),A.verified&&o.jsx("img",{src:ao,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:16,height:16,style:{width:"16px",height:"16px",filter:d?"brightness(0) invert(1)":"none"}})]})]},A.id)})}),b&&o.jsx("div",{style:{padding:"0 25px 12px"},children:o.jsx(an,{variant:"error",size:"compact",palette:c,children:b})}),o.jsx("div",{style:{padding:"0 25px 25px"},children:o.jsxs(p.Button,{variant:"outline",onClick:F,disabled:j,fullWidth:!0,theme:i,styles:a,dark:d,children:["SELECT",o.jsx(oa,{size:20})]})})]})},Lo=({isSuccess:e,type:t,chainName:n,explorerUrl:s,txHash:r,dark:a=!1,successBg:i="#d1fae5",successBorder:d="#6ee7b7",successText:u="#065f46",errorBg:c="#fee2e2",errorBorder:f="#fca5a5",errorText:h="#dc2626",textSecondary:g="#6b7280"})=>o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px",borderRadius:"8px",backgroundColor:e?i:c,border:e?`1px solid ${d}`:`1px solid ${f}`},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[o.jsx("div",{style:{width:"28px",height:"28px",borderRadius:"50%",backgroundColor:e?"#10b981":"#ef4444",display:"flex",alignItems:"center",justifyContent:"center"},children:e?o.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:o.jsx("path",{d:"M11.6667 3.5L5.25 9.91667L2.33333 7",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}):o.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:o.jsx("path",{d:"M10.5 3.5L3.5 10.5M3.5 3.5L10.5 10.5",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),o.jsxs("div",{children:[o.jsx("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:p.font.mono,letterSpacing:"0.5px",color:e?u:h},children:e?`${t.toUpperCase()} CONFIRMED`:`${t.toUpperCase()} FAILED`}),o.jsxs("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:g},children:["on ",n]})]})]}),s&&r&&o.jsxs("a",{href:`${s}/tx/${r}`,target:"_blank",rel:"noopener noreferrer",style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"13px",color:g,textDecoration:"none",whiteSpace:"nowrap"},children:["View on explorer",o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:[o.jsx("path",{d:"M9 6.5V9.5C9 9.76522 8.89464 10.0196 8.70711 10.2071C8.51957 10.3946 8.26522 10.5 8 10.5H2.5C2.23478 10.5 1.98043 10.3946 1.79289 10.2071C1.60536 10.0196 1.5 9.76522 1.5 9.5V4C1.5 3.73478 1.60536 3.48043 1.79289 3.29289C1.98043 3.10536 2.23478 3 2.5 3H5.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),o.jsx("path",{d:"M7.5 1.5H10.5V4.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),o.jsx("path",{d:"M5 7L10.5 1.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})]})]})]}),zo=`
|
|
31
31
|
@keyframes slideUp {
|
|
32
32
|
from { transform: translateY(100%); }
|
|
33
33
|
to { transform: translateY(0); }
|
package/dist/index.js
CHANGED
|
@@ -27,7 +27,7 @@ import{jsx as c,jsxs as x,Fragment as on}from"react/jsx-runtime";import mn,{useS
|
|
|
27
27
|
transform: translateY(0);
|
|
28
28
|
}
|
|
29
29
|
}
|
|
30
|
-
`})]})};async function ic(e,t,n){let o=null;try{const s=await e.request({method:"eth_chainId"});o=parseInt(s,16)}catch{o=null}o!==t&&(n?.(),await sr(e,t))}async function so(e){const t=e.provider??await e.wallet?.getEthereumProvider();if(!t)throw new Error("External wallet provider not available");await ic(t,e.chainId,e.onSwitch);const n=Me(e.chainId)?.viemChain;return{extWc:ns({account:e.account,chain:n,transport:os(t)}),viemChain:n}}async function Zr(e){let t;for(const n of e.calls){const o=await e.extWc.sendTransaction({to:n.to,data:n.data,value:n.value,chain:e.viemChain});if((await e.client.waitForTransactionReceipt({hash:o,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error(e.errorMessage);t=o}return t}function Xr(e,t){return t.isNative?e.sendTransaction({to:t.recipient,value:t.amount,chain:t.viemChain}):e.sendTransaction({to:t.tokenAddr,data:St({abi:We,functionName:"transfer",args:[t.recipient,t.amount]}),chain:t.viemChain})}async function Ts(e){const{extWc:t,sourceClient:n,recipient:o,tokenAddr:s,isNative:r,amount:a}=e;if(a<=0n)return;const l=await Xr(t,{recipient:o,tokenAddr:s,isNative:r,amount:a,viemChain:e.viemChain});if((await n.waitForTransactionReceipt({hash:l,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Embedded wallet funding failed")}const Gr="spiceflow:pendingDeposit",jo="spiceflow:pendingDepositChanged";function Jr(e,t,n){return`${Gr}:${e.toLowerCase()}:${t}:${n.toLowerCase()}`}function Rs(){try{const e="__spiceflow_storage_test__";return localStorage.setItem(e,"1"),localStorage.removeItem(e),!0}catch{return!1}}function lc(e){if(!Rs())return;const t=Jr(e.embeddedWalletAddress,e.chainId,e.tokenAddress);try{localStorage.setItem(t,JSON.stringify(e)),window.dispatchEvent(new Event(jo))}catch(n){console.error("[pendingDeposit] Failed to save:",n)}}function cc(e){if(!Rs())return[];const t=`${Gr}:${e.toLowerCase()}:`,n=[],o=Date.now();for(let s=0;s<localStorage.length;s++){const r=localStorage.key(s);if(!(!r||!r.startsWith(t)))try{const a=localStorage.getItem(r);if(!a)continue;const l=JSON.parse(a);if(o-l.timestamp>6048e5){localStorage.removeItem(r);continue}n.push(l)}catch{localStorage.removeItem(r)}}return n}function Ws(e,t,n){if(!Rs())return;const o=Jr(e,t,n);localStorage.removeItem(o),window.dispatchEvent(new Event(jo))}function dc({sourceChainId:e,selectedAsset:t,destinationChainId:n,destinationTokenAddress:o,isCrossDenomination:s,convertedUsdAmount:r}){const a=ht(t.asset.address),l=o;let d,i;if(l&&n)if(d=So[n]?.supportedTokens?.find(u=>Ee(u.address,l))?.decimals??t.asset.decimals,s){if(!r)throw new Error("Destination amount is still being calculated. Please retry in a moment.");i=r}else{const u=Oe(t.amount,t.asset.decimals);i=io(u,t.asset.decimals,d)}return{sourceChainId:e,depositTokenAddress:a,depositAmount:t.amount,depositTokenDecimals:t.asset.decimals,destinationChainId:n,destinationTokenAddress:l,destinationAmount:i,destinationTokenDecimals:d}}async function uc(e,t){if(!e)return[];if(Array.isArray(e))return e;const n=e;return e.length>=2?n(t.depositAmount,t.depositTokenAddress):n(t)}async function Ds(e,t){const n=await Xr(e,{recipient:t.recipient,tokenAddr:t.tokenAddr,isNative:t.isNative,amount:t.amount});t.afterSend?.(n);const o=pt(t.chainId),s=await o.waitForTransactionReceipt({hash:n,timeout:12e4,pollingInterval:2e3,confirmations:2});if(s.status!=="success")throw new Error(t.failureMessage);return t.settle&&await o.getBlockNumber()-s.blockNumber<2n&&await wn(3e3),s.transactionHash}async function pc(e){const t=e.selectedDepositAssets.filter(o=>o.asset&&o.amount&&parseFloat(o.amount)>0);if(t.length===0){console.error("[DepositModal] No valid assets for deposit"),e.setError("Please select an asset and enter an amount");return}if(!e.escrowOnly&&!e.sourceAddress){e.setError("External wallet not connected. Please connect your wallet in the previous step.");return}if(!e.isNon7702){if(!e.address||!e.embeddedWalletAddress){e.setError("Couldn't find your account wallet. Try reconnecting.");return}if(!e.isReady||!e.isAuthenticated){e.setError("Sign in to continue.");return}}if(e.zeroCreditError){e.setError(e.zeroCreditError);return}if(e.depositBalanceError){e.setError(e.depositBalanceError);return}e.setIsExecuting(!0),e.setError(null);let n=!1;try{const o=t[0].asset.chainId,s=pn(o);let r=e.externalWalletClient;if(!e.escrowOnly){if(!r)throw new Error("External wallet not connected");if(e.externalProvider){const a=await so({provider:e.externalProvider,account:e.sourceAddress,chainId:o});a.viemChain&&(r=a.extWc)}}if(e.isNon7702){if(!r)throw new Error("External wallet not connected");if(!e.sourceAddress)throw new Error("External wallet address not available");if(e.nativeChainId&&o===e.nativeChainId){const a=Me(o),l=t.map(i=>`${i.amount} ${i.asset.symbol}`).join(", ");e.setConfirmationData({network:a?.displayName||`Chain ${o}`,amount:l,symbol:"",chainId:o}),e.setShowConfirmation(!0);let d=null;e.setDirectDepositStatus("processing"),e.setDirectDepositChainId(o);for(const i of t){const u=Oe(i.amount,i.asset.decimals),p=ht(i.asset.address),f=i.asset.isNative||Ue(p),m=await Ds(r,{chainId:o,recipient:s,tokenAddr:p,isNative:f,amount:u,failureMessage:`Escrow deposit failed for ${i.asset.symbol}`});d=m,e.setDirectDepositTxHash(m)}if(t[0]?.amount){const i=t[0].amount;if(e.onDepositExecute){e.setPostDepositStatus("executing");try{await e.onDepositExecute(i),e.setPostDepositStatus("success")}catch(p){console.error("ctx.onDepositExecute failed:",p),e.setPostDepositStatus("error"),e.setPostDepositError(p?.message||"Post-deposit instruction failed")}}else e.setPostDepositStatus("success");e.setDirectDepositStatus("success"),e.setPostDepositAmount(i),e.setPostDepositSuccess(!0);const u={type:"deposit",status:"success",amount:i,asset:t[0].asset.symbol,sourceChain:a?.displayName||`Chain ${o}`,txHash:d??void 0};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:u})),e.onDepositSuccess?.(u)}e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset)}else{const a=e.destinationChainId||e.nativeChainId;if(!a)throw new Error("Destination chain ID is required for non-7702 mode. Either pass ctx.destinationChainId to <SpiceDeposit> or set ctx.nativeChainId on <SpiceFlowProvider>.");const l=or(o),d=s,i=[];let u=null;for(const p of t){const f=Oe(p.amount,p.asset.decimals),m=ht(p.asset.address),h=p.asset.isNative||Ue(m),g=await Ds(r,{chainId:o,recipient:d,tokenAddr:m,isNative:h,amount:f,failureMessage:`Transfer failed for ${p.asset.symbol}`,afterSend:y=>{u||(u=y)},settle:!0});e.depositDataRef.current||(e.depositDataRef.current=[]),e.depositDataRef.current.push({txHash:g,sender:e.sourceAddress,tokenAddress:m,chainId:o,amount:f.toString(),user:e.spiceBalanceUser}),i.push({tokenAddress:m,tokenAmount:f.toString(),sender:e.sourceAddress,receiver:d})}if(!u)throw new Error("No transaction hash generated");if(!e.destinationTokenAddress){const p={type:"deposit",status:"success",amount:t[0]?.amount,asset:t[0]?.asset?.symbol,sourceChain:cn(o),txHash:u};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:p})),e.onDepositSuccess?.(p),e.depositDataRef.current=null,e.bridgedAmountRef.current=t[0]?.amount||null,e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset),e.setShowConfirmation(!1);return}if(e.sponsorGas&&e.nativeChainId){const p=Oe("0.05",18);i.push({tokenAddress:Dt,tokenAmount:p.toString(),sender:e.sourceAddress,receiver:d})}if(e.mode==="ondemand"){const p={to:l,value:BigInt(0),data:"0x"},f=await rr(a,e.destinationTokenAddress);let m=BigInt(0);for(const B of i){const A=BigInt(B.tokenAmount),F=ht(B.tokenAddress),E=t.find(S=>{const v=ht(S.asset.address);return Ee(v,F)}),I=E?E.asset.decimals:await rr(o,Dt);m+=io(A,I,f)}e.isCrossDenomination&&e.convertedUsdAmount&&(m=e.convertedUsdAmount);const h={chainId:o,tokenTransfers:i.map(B=>({from:B.sender,to:B.receiver,token:B.tokenAddress,amount:BigInt(B.tokenAmount)})),call:p},g=e.isCrossDenomination&&e.convertedUsdAmount?[{from:e.sourceAddress,to:s,token:ht(t[0].asset.address),amount:Oe(t[0].amount,t[0].asset.decimals)}]:[],y={chainId:a,tokenTransfers:[...g,{from:"escrow",to:e.sourceAddress,token:e.destinationTokenAddress,amount:m}],call:{to:e.destinationTokenAddress,value:BigInt(0),data:"0x"}},w={mode:"non-7702:on-demand",chainBatches:[h,y]},b={user:e.sourceAddress,intents:[w]},T=await It.createAction(b),k=T.actionId,C=T.intentIds[0];if(!u)throw new Error("No transaction hash available");e.startStatusPolling(C,es([{chainId:o,calls:[p]},{chainId:a,calls:[y.call]}],B=>cn(B))),await It.executeStep(k,0,0,{action:"execute",hash:u}),t[0]?.amount&&(e.bridgedAmountRef.current=t[0].amount),e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset),e.setShowConfirmation(!1)}else throw new Error("Presign mode not yet fully supported for cross-chain deposits")}}else{const a=[],l=t[0],d=l&&t.length===1&&e.effectiveDepositFee&&e.effectiveDepositFee.chainId===o&&Ee(e.effectiveDepositFee.token,ht(l.asset.address))?Xe(e.effectiveDepositFee.net,l.asset.decimals):l?.amount;for(const b of t){const T=Oe(b.amount,b.asset.decimals),k=t.length===1&&!!e.effectiveDepositFee&&e.effectiveDepositFee.chainId===o&&Ee(e.effectiveDepositFee.token,ht(b.asset.address)),C=k?e.effectiveDepositFee.fee:0n,B=k?e.effectiveDepositFee.net:T,A=e.escrowOnly?T:T+C,F=ht(b.asset.address),E=b.asset.isNative||Ue(F);e.escrowOnly||await Ds(r,{chainId:o,recipient:e.address,tokenAddr:F,isNative:E,amount:A,failureMessage:`Transfer to embedded wallet failed for ${b.asset.symbol}`,afterSend:()=>lc({chainId:o,tokenAddress:ht(b.asset.address),tokenSymbol:b.asset.symbol,tokenDecimals:b.asset.decimals,amount:b.amount,rawAmount:T.toString(),embeddedWalletAddress:e.address,externalWalletAddress:e.sourceAddress,timestamp:Date.now(),isNative:E}),settle:!0}),a.push(E?{to:s,value:B,data:"0x"}:{to:F,value:BigInt(0),data:St({abi:We,functionName:"transfer",args:[s,B]})}),C>0n&&a.push(E?{to:sn,value:C,data:"0x"}:{to:F,value:BigInt(0),data:St({abi:We,functionName:"transfer",args:[sn,C]})})}const i=await pt(o).getBlockNumber(),u=a.map(b=>({...b,to:lt(b.to)})),p={chainId:o,recentBlock:i,calls:u,tokenTransfers:[]},f=dc({sourceChainId:o,selectedAsset:l&&d?{...l,amount:d}:t[0],destinationChainId:e.destinationChainId,destinationTokenAddress:e.destinationTokenAddress,isCrossDenomination:e.isCrossDenomination,convertedUsdAmount:e.convertedUsdAmount}),m=await uc(e.depositBatches,f),h=[p,...m];if(!e.address)throw new Error("Address not available");const g=[];if(e.isCrossDenomination&&e.convertedUsdAmount&&e.destinationTokenAddress){const b=e.selectedDepositAssets[0]?.asset;if(b){const T=Oe(e.selectedDepositAssets[0].amount,b.decimals);g.push({from:e.address,to:s,token:ht(b.address),amount:T}),g.push({from:"escrow",to:e.address,token:e.destinationTokenAddress,amount:e.convertedUsdAmount})}}g.length>0&&h[1]&&(h[1].tokenTransfers=g);const y=es(h,b=>cn(b));let w=!1;if(await e.execution.execute(h,Dt,0n,b=>{if(b.intentId&&!w){w=!0;for(const T of t)Ws(e.address,o,ht(T.asset.address));e.startStatusPolling(b.intentId,y)}},void 0,{userOverride:e.address,useCustomTransfers:!0,skipPreSubmitFeeEstimate:!0,skipUserFundingPreflight:!0}),e.refreshAssets(),e.onDepositExecute&&t[0]?.amount)try{e.setPostDepositStatus("executing"),await e.onDepositExecute(d||t[0].amount),e.setPostDepositStatus("success"),e.setPostDepositAmount(d||t[0].amount),e.setPostDepositSuccess(!0)}catch(b){console.error("ctx.onDepositExecute failed (7702):",b),e.setPostDepositStatus("error"),e.setPostDepositError(b?.message||"Post-deposit instruction failed")}e.onDepositSelect&&e.onDepositSelect(t[0].asset)}}catch(o){n=!0,console.error("[DepositModal] executeDeposit CAUGHT ERROR:",o),console.error("[DepositModal] Error details:",{message:o?.message,code:o?.code,name:o?.name,stack:o?.stack?.slice(0,500)}),e.setError(un(o,"Deposit failed")),e.clearStatus()}finally{e.setIsExecuting(!1),n&&e.setDirectDepositStatus("idle"),n||!e.getCurrentIntentStatus()&&e.getCurrentPostDepositStatus()!=="idle"||e.setShowConfirmation(!1)}}async function hc(e){const{asset:t,assetIndex:n,selectedAssetCount:o,address:s,escrowOnly:r,isNon7702:a}=e;if(n!==0||a||o>1||!s||t.balance<=0n)return null;const l=await $r({address:s,depositQuote:{asset:t,amount:t.balance,token:ht(t.address),chainId:t.chainId},escrowOnly:r}),d=r?t.balance:t.balance>l.fee?t.balance-l.fee:0n;return Or(d,t.decimals)}async function $r(e){const{address:t,depositQuote:n,escrowOnly:o}=e,{asset:s,amount:r,token:a,chainId:l}=n,d=pn(l),i=s.isNative||Ue(a),u=r>1n?1n:0n,p=[i?{to:d,value:r,data:"0x"}:{to:a,value:0n,data:St({abi:We,functionName:"transfer",args:[d,r]})}];u>0n&&p.push(i?{to:sn,value:u,data:"0x"}:{to:a,value:0n,data:St({abi:We,functionName:"transfer",args:[sn,u]})});const f={chainId:l,tokenTransfers:[],calls:p},m=(await It.estimateBatchGas({user:t,outputToken:a,chainBatches:[{...f,hash:Sn([f])[0].hash}]})).gasFee,h=o&&m<r?r-m:r;return{fee:m,net:h,token:a,chainId:l}}const fc=({selectedDepositAssets:e,depositAssets:t,secondAssetOptions:n,loadingAssets:o,allowSecondAsset:s,theme:r,styles:a,dark:l,dk:d,onSelect:i,onAmountChange:u,onAdd:p,onRemove:f,resolveMaxAmount:m,onViewAllAssets:h})=>x(on,{children:[e.map((g,y)=>{const w=e.length===1?"Deposit":`Asset ${y+1}`;return x("div",{style:{marginBottom:r.spacing.md,position:"relative"},children:[c(po,{assets:y===0?t:n,selectedAsset:g||void 0,onAssetSelect:b=>i(b,y),onAmountChange:b=>u(b,y),loading:o,label:w,showBalance:!0,theme:r,styles:a,allowSecondAsset:s&&y===0,onAddAsset:p,canAddAsset:e.length===1&&!!e[0]?.asset,resolveMaxAmount:m?b=>m(b,y):void 0,onViewAllAssets:y===0?h:void 0}),y===1&&c("button",{onClick:()=>f(y),style:{position:"absolute",top:"-2px",right:"-2px",background:l?`${d.cardBg}ee`:"rgba(255, 255, 255, 0.9)",border:`1px solid ${d.cardBorder}`,borderRadius:"50%",cursor:"pointer",color:r.colors.textMuted,fontSize:"16px",padding:"2px",width:"22px",height:"22px",display:"flex",alignItems:"center",justifyContent:"center",transition:dn.interactive,boxShadow:"0 1px 3px rgba(0, 0, 0, 0.1)"},onMouseEnter:b=>{b.currentTarget.style.color=l?d.errorText:"#ef4444",b.currentTarget.style.background=l?d.cardBg:"#fff",b.currentTarget.style.borderColor=l?d.errorBorder:"#fecaca"},onMouseLeave:b=>{b.currentTarget.style.color=r.colors.textMuted,b.currentTarget.style.background=l?`${d.cardBg}ee`:"rgba(255, 255, 255, 0.9)",b.currentTarget.style.borderColor=l?d.cardBorder:"#e5e7eb"},title:"Remove asset",children:"\xD7"})]},`asset-${y}`)}),e.length===0&&c("div",{style:{marginBottom:r.spacing.md},children:c(po,{assets:t,selectedAsset:void 0,onAssetSelect:g=>i(g,0),onAmountChange:g=>u(g,0),loading:o,label:"Deposit",showBalance:!0,theme:r,styles:a,allowSecondAsset:s,onAddAsset:p,canAddAsset:!1,resolveMaxAmount:m?g=>m(g,0):void 0},"initial-selector")})]}),mc=Xt(fc);var Ms="data:image/svg+xml,%3csvg width='10' height='10' viewBox='0 0 10 10' fill='none' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M5 4.99995V6.99995M5 3.31245V3.31189M9.5 5C9.5 7.48528 7.48528 9.5 5 9.5C2.51472 9.5 0.5 7.48528 0.5 5C0.5 2.51472 2.51472 0.5 5 0.5C7.48528 0.5 9.5 2.51472 9.5 5Z' stroke='black' stroke-opacity='0.4' stroke-linecap='round' stroke-linejoin='round'/%3e%3c/svg%3e";const _r=mn.memo(({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,onDepositSelect:o,depositBatches:s,supportedChains:r,title:a,styles:l,onDepositAssetChange:d,assetInputHook:i,externalWalletAddress:u,onDepositAmountChange:p,allowSecondAsset:f=!1,destinationChainId:m,destinationTokenAddress:h,onDepositExecute:g,depositActionLabel:y,nativeChainId:w,sponsorGas:b=!1,preSelectedAsset:T,escrowOnly:k=!1,escrowTokenAddress:C,escrowAmount:B,escrowTokenDecimals:A,escrowTokenSymbol:F,onDepositSuccess:E,onDepositError:I,embeddedWalletAddress:S,onViewAllAssets:v})=>{const R=qt(Ut),U=R?.mode||"7702",W=R?.allowedTokens,z=!!R?.isWhitelistGateActive,P=!k&&!!R?.isWhitelistConfigured&&R?.isUserWhitelisted!==!0,M=i?.assetAmount||"",{theme:N,dark:H,appName:Y,primaryColor:j,dk:K}=ut(l),be=bn(),{isReady:O,isAuthenticated:X}=be,{externalWallet:re}=_n(),ue=R?.embeddedWalletAddress||S,pe=U!="7702",Se=pe?!!u:O&&X&&!!ue,fe=ue,me=u,Re=fe??me,{data:L}=Ii(),[_,oe]=mn.useState(L),ae=mn.useRef(null),q=mn.useRef(re);q.current=re;const se=re?.address;mn.useEffect(()=>{const Q=q.current;if(!Q||!me){ae.current=null,oe(L);return}if(Q.address?.toLowerCase()!==me?.toLowerCase()){ae.current=null,oe(L);return}Q.getEthereumProvider().then(async ce=>{ae.current=ce;const Fe=await ce.request({method:"eth_chainId"}),ye=parseInt(Fe,16),ct=Me(ye),dt=await Q.getWalletClient(ye);oe(ct?ns({account:me,chain:ct.viemChain,transport:os(ce)}):dt)}).catch(()=>{ae.current=null,oe(L)})},[se,me,L]);const xe=mn.useRef(null),[Z,Te]=D([]),{assets:Ge,loading:st,error:$t,refreshAssets:Mt}=ds({address:k?fe:me||fe,supportedChains:r,fetchBalances:cs,enabled:e,refreshInterval:e?5e3:0}),Ze=ne(()=>{if(z)return[];const Q=r.flatMap(ce=>ar(ce,Ge));return W&&W.length>0?Q.filter(ce=>W.includes(ce.symbol.toLowerCase())||ce.isNative&&W.includes("native")).sort((ce,Fe)=>{const ye=ce.balance>BigInt(0)?1:0;return(Fe.balance>BigInt(0)?1:0)-ye}):Q.filter(ce=>ce.balance>BigInt(0))},[r,Ge,W,z]),de=ne(()=>{if(!Z[0]?.asset)return[];const Q=Z[0].asset.chainId;return Ze.filter(ce=>ce.chainId===Q)},[Ze,Z]),[Be,rt]=D(!1),[ft,le]=D(null),gt=ee(I);gt.current=I;const Ae=te(Q=>{le(Q),typeof Q=="string"&&Q&>.current?.(Q,ao(Q))},[]),[Ie,ge]=D("idle"),Qe=te(Q=>{typeof Q=="string"&&Q&>.current?.(Q,ao(Q))},[]),[Lt,Pt]=D(!1),[_t,Le]=D(null),[at,zt]=D("idle"),[jt,en]=D(null),[Je,yt]=D(null),[rn,Ot]=D(null),[he,$e]=D(null),[xt,Et]=D(null),{intentStatus:ke,startStatusPolling:Nt,clearStatus:tn,execute:it}=no(),Pe=te((Q,ce)=>{const Fe=So[ce];return Fe?Fe.supportedTokens?.find(ye=>Ee(ye.address,Q))?.symbol??null:null},[]),bt=ne(()=>{const Q=Z[0]?.asset;if(!Q||!h||!m)return!1;const ce=Pe(h,m);return ul(Q.symbol)&&!!ce&&pl(ce)},[Z,h,m,Pe]);G(()=>{Z.length>0&&M!==Z[0]?.amount&&Te(Q=>{if(Q.length===0)return Q;const ce=[...Q];return ce[0]={...ce[0],amount:M||""},ce})},[M]),G(()=>{Z.length!==0&&Te(Q=>{let ce=!1;const Fe=Q.map(ye=>{if(!ye.asset)return ye;const ct=Ze.find(dt=>dt.chainId===ye.asset.chainId&&Ee(dt.address,ye.asset.address));return ct?ct===ye.asset||ct.balance===ye.asset.balance?ye:(ce=!0,{...ye,asset:ct,amount:ye.amount}):ye});return ce?Fe:Q})},[Ze,Z.length]),G(()=>{if(!T||Z.length>0||Ze.length===0)return;const Q=Ze.find(ce=>ce.chainId===T.chainId&&Ee(ce.address,T.address));Q&&(Te([{asset:Q,amount:""}]),d?.(Q))},[T,Ze,Z.length]);const an=mn.useRef(null);G(()=>{if(pe&&ke?.overallStatus==="success"&&g&&Ie==="idle"){const Q=an.current,ce=xe.current;Q&&(async()=>{try{ge("executing"),await g(Q),ge("success"),Le(Q),Pt(!0);const Fe=Array.isArray(ce)?ce[0]:void 0,ye={type:"deposit",status:"success",amount:Q,asset:Fe?.tokenAddress,sourceChain:Fe?String(Fe.chainId):void 0,txHash:Fe?.txHash};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:ye})),E?.(ye)}catch(Fe){console.error("onDepositExecute failed:",Fe),ge("error"),Qe(un(Fe,"Post-deposit instruction failed"))}finally{an.current=null,xe.current=null}})()}},[ke?.overallStatus,pe,Ie]);const Ft=te(()=>{Ae(null)},[]);G(()=>{e||(Pt(!1),Le(null),zt("idle"),en(null),yt(null))},[e]);const _e=te((Q,ce)=>{Te(Fe=>{const ye=[...Fe];return ye[ce]={asset:Q,amount:ye[ce]?.amount||""},ye}),ce===0&&d?.(Q),Ft()},[d,Ft]),Ve=te(async(Q,ce)=>{if(Te(Fe=>{const ye=[...Fe];return ye[ce]&&(ye[ce]={...ye[ce],amount:Q}),ye}),Ft(),ce===0)if(i?.setAssetAmount(Q),bt&&Q&&parseFloat(Q)>0)try{const Fe=rn??await dl();rn||Ot(Fe);const ye=Z[0]?.asset;if(!ye)return;const ct=Oe(Q,ye.decimals),dt=h?Pe(h,m):null,Nn=So[m]?.supportedTokens?.find(Xo=>Ee(Xo.address,h))?.decimals??6,ko=hl(ct,ye.decimals,Nn,Fe);$e(ko);const vo=Xe(ko,Nn),Zo=Fe.toLocaleString("en-US",{maximumFractionDigits:0});Et(`${Q} ${ye.symbol} \u2248 $${parseFloat(vo).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})} ${dt??"USD"} (rate: $${Zo}/BTC)`),p?.(vo)}catch(Fe){console.error("Failed to fetch BTC/USD price:",Fe),Et(null),$e(null),p?.(Q)}else Et(null),$e(null),p?.(Q)},[Ft,i,p,bt,rn,Z,h,m,Pe]),Bt=te(()=>{Z.length<2&&Te(Q=>[...Q,{asset:null,amount:""}])},[Z.length]),Yt=te(Q=>{Te(ce=>ce.filter((Fe,ye)=>ye!==Q)),Ft()},[Ft]),et=ee(!1),xn=ee(!1);G(()=>{e||(et.current=!1,xn.current=!1,Rt(null),wt(null))},[e]);const[je,Tt]=D(!1),[ln,Ct]=D(null),[ze,Rt]=D(null),[Wt,wt]=D(null),[tt,Kt]=D(!1),[V,J]=D(null),ie=ne(()=>{const Q=Z[0];if(Z.length!==1||!Q?.asset||!Q.amount||parseFloat(Q.amount)<=0)return null;try{return{asset:Q.asset,amount:Oe(Q.amount,Q.asset.decimals),token:ht(Q.asset.address),chainId:Q.asset.chainId}}catch{return null}},[Z]),qe=ne(()=>ie?[ie.chainId,ie.token.toLowerCase(),ie.amount.toString(),k?"escrow":"normal"].join("|"):null,[ie,k]),$=te(async Q=>fe?$r({address:fe,depositQuote:Q,escrowOnly:k}):null,[fe,k]),we=te(async()=>ie?$(ie):null,[ie,$]),Ye=ee(we);Ye.current=we,G(()=>{let Q=!1;if(!e||pe||!qe||je||Be){Rt(null),J(null),Kt(!1);return}const ce=async()=>{J(null),Kt(!0);try{const ye=await Ye.current();Q||Rt(ye)}catch(ye){if(Q)return;Rt(null),J(ye instanceof Error?ye.message:"Failed to estimate gas fee")}finally{Q||Kt(!1)}};ce();const Fe=window.setInterval(()=>{ce()},1e4);return()=>{Q=!0,window.clearInterval(Fe)}},[e,pe,qe,je,Be]),G(()=>{je||Be||wt(null)},[je,Be,qe]);const kt=async()=>{if(Z.length===0||!Z[0]?.asset)return;const Q=Z.filter(dt=>dt.asset&&dt.amount&&parseFloat(dt.amount)>0);if(Q.length===0)return;const ce=Q[0],Fe=Me(ce.asset.chainId),ye=Q.map(dt=>{const Nn=parseFloat(dt.amount);return`${isNaN(Nn)?dt.amount:Nn.toPrecision(6).replace(/\.?0+$/,"")} ${dt.asset.symbol}`}).join(", "),ct={network:Fe?.displayName||`Chain ${ce.asset.chainId}`,amount:ye,symbol:"",chainId:ce.asset.chainId};if(!pe&&Q.length===1&&ze){wt(ze);const dt=Q[0];ct.creditedAmount=`${Xe(ze.net,dt.asset.decimals)} ${dt.asset.symbol}`,ct.networkFee=`${Xe(ze.fee,dt.asset.decimals)} ${dt.asset.symbol}`}Ct(ct),Tt(!0)},Ke=ee(ke);Ke.current=ke;const Qt=ee(Ie);Qt.current=Ie;const He=async()=>{await pc({selectedDepositAssets:Z,escrowOnly:k,sourceAddress:me,isNon7702:pe,address:fe,embeddedWalletAddress:ue,isReady:O,isAuthenticated:X,zeroCreditError:Ne,depositBalanceError:Vt,externalWalletClient:_,externalProvider:ae.current,effectiveDepositFee:ot,depositBatches:s,destinationChainId:m,destinationTokenAddress:h,isCrossDenomination:bt,convertedUsdAmount:he,mode:U,sponsorGas:b,nativeChainId:w,spiceBalanceUser:Re,depositDataRef:xe,bridgedAmountRef:an,setIsExecuting:rt,setError:Ae,setConfirmationData:Ct,setShowConfirmation:Tt,setDirectDepositStatus:zt,setDirectDepositChainId:yt,setDirectDepositTxHash:en,setPostDepositStatus:ge,setPostDepositError:Qe,setPostDepositAmount:Le,setPostDepositSuccess:Pt,startStatusPolling:Nt,clearStatus:tn,refreshAssets:Mt,onDepositExecute:g,onDepositSelect:o,onDepositSuccess:E,execution:{execute:it},getCurrentIntentStatus:()=>Ke.current,getCurrentPostDepositStatus:()=>Qt.current})},Ne=ne(()=>{for(const Q of Z)if(!(!Q?.asset||!Q.amount||parseFloat(Q.amount)<=0))try{const ce=Q.asset.decimals,Fe=Oe(Q.amount,ce);if(Fe<=0n)continue;const ye=Ti(ht(Q.asset.address)),ct=Q.asset.receiptTokenDecimals??(ye==="ETH"||ye==="ARB"?18:ye==="USDC"||ye==="SUSD"||ye==="WBTC"||ye==="CBTC"?6:void 0);if(ct===void 0||ce<=ct||io(Fe,ce,ct)>0n)continue;return`Amount too small. Minimum deposit for this asset is ${Xe(10n**BigInt(ce-ct),ce)} ${Q.asset.symbol}.`}catch{continue}return null},[Z]),nt=!pe&&!!ie,ot=Wt??ze,Zt=!!ie&&!!ot&&ot.chainId===ie.chainId&&Ee(ot.token,ie.token),Vt=ne(()=>{if(!nt||!ie||!Zt)return null;const Q=k?ie.amount:ie.amount+ot.fee;return ie.asset.balance>=Q?null:`Insufficient ${ie.asset.symbol}. Need ${Xe(Q,ie.asset.decimals)} ${ie.asset.symbol} including gas.`},[nt,ie,Zt,ot,k]),[qn,nn]=D(!1),hn=Z[0]?.asset?.chainId,Ht=Ge.find(Q=>Q.isNative&&Q.chainId===hn)?.balance??0n;G(()=>{if(!e||!hn){nn(!1);return}let Q=!1;return(async()=>{try{const ce=await pt(hn).getGasPrice()*150000n;Q||nn(Ht<ce)}catch{Q||nn(!1)}})(),()=>{Q=!0}},[e,hn,Ht]);const Dn=!nt||Zt&&!tt&&!V&&!Vt,Mn=te((Q,ce)=>hc({asset:Q,assetIndex:ce,selectedAssetCount:Z.length,address:fe,escrowOnly:k,isNon7702:pe}),[pe,Z.length,fe,k]),Yn=ne(()=>{if(!ie||!ot||!Zt)return null;const Q=k?ie.amount:ie.amount+ot.fee;return{symbol:ie.asset.symbol,decimals:ie.asset.decimals,grossAmount:Q,netAmount:ot.net,totalFee:ot.fee,gasFee:ot.fee,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"estimated"}},[ie,ot,Zt,k]),fn=parseFloat(Z[0]?.amount||"")||0,ro=fn>0&&fn<In,Kn=Z.length>0&&Z[0]?.asset&&Z[0]?.amount&&fn>0&&!ro&&Se&&!Be&&!Ne&&!Vt&&Dn&&!P;G(()=>{if(!k||!C||!B||et.current||!Se)return;const Q=r[0];if(!Q)return;const ce=ar(Q,[]).find(ye=>Ee(ye.address,C));let Fe;if(ce)Fe=ce;else if(A!==void 0&&F)Fe={address:C,symbol:F,name:F,decimals:A,chainId:Q,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,isNative:Ue(C)};else{console.warn("[DepositModal] escrowOnly: no matching asset and missing escrowTokenDecimals/escrowTokenSymbol for",C);return}et.current=!0,Te([{asset:Fe,amount:B}])},[k,C,B,A,F,Se,r]),G(()=>{!k||!Kn||xn.current||Be||(xn.current=!0,He())},[k,Kn,Be]);const Co=$t||ft||Ne||Vt,wo=()=>{if(Be)return"Executing Deposit...";if(!Se)return"Wallet Not Connected";if(U==="7702"){if(!O)return"Loading...";if(!X)return"Authentication Required"}return Z[0]?.asset?Z[0]?.amount?ro?`MINIMUM ${In}`:Ne?"AMOUNT TOO SMALL":Vt?"INSUFFICIENT BALANCE":nt&&!Dn?V?"GAS UNAVAILABLE":"ESTIMATING GAS":"DEPOSIT":"ENTER AMOUNT":"SELECT TOKEN"};return e?c(Cn,{isOpen:e,onClose:t,closeOnBackdropClick:n,title:a||`Deposit to your ${Y} account`,subtitle:x("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[c("img",{src:Ms,alt:"","aria-hidden":"true",style:{width:"13px",height:"13px",flexShrink:0,...H?{filter:"invert(0.6)"}:{}}}),c("p",{style:{fontSize:"12px",color:K.textSecondary,margin:"0",lineHeight:"1.4",fontFamily:ve.ui},children:`Deposit collateral to your ${Y} Account from any supported network.`})]}),dark:H,overlayContent:je||ke||Ie!=="idle"&&g?c("div",{}):void 0,styles:l,theme:N,children:x("div",{style:{padding:"24px 24px 5px 24px"},children:[c(mc,{selectedDepositAssets:Z,depositAssets:Ze,secondAssetOptions:de,loadingAssets:st,allowSecondAsset:f,theme:N,styles:l,dark:H,dk:K,onSelect:_e,onAmountChange:Ve,onAdd:Bt,onRemove:Yt,resolveMaxAmount:Mn,onViewAllAssets:v}),nt&&ie&&c(Fs,{fontFamily:l?.fontFamily||N.typography.fontFamily,textPrimary:K.textPrimary,textSecondary:K.textSecondary,cardBg:H?K.inputBg:"#ffffff",cardBorder:K.cardBorder,resolvedDark:H,darkCardBorder:K.cardBorder,primaryColor:j,feePreview:Yn,isLoading:tt||nt&&!Zt,errorText:V}),c(ac,{intentStatus:ke,postDepositSuccess:Lt,postDepositAmount:_t,postDepositStatus:Ie,depositActionLabel:y,sourceChainName:Z[0]?.asset?.chainId?cn(Z[0].asset.chainId):"Destination Chain",directDepositStatus:at,directDepositTxHash:jt,directDepositChainId:Je,styles:l}),c(rc,{isOpen:je||!!ke||Ie!=="idle"&&!!g,onClose:()=>{Tt(!1),ke&&tn();const Q=Ie==="success"&&!ke,ce=ke?.overallStatus==="success"&&Ie==="success"&&g;(Q||ce)&&t()},onConfirm:He,data:ln,isExecuting:Be,error:ft,theme:N,styles:l,intentStatus:ke,postDepositStatus:Ie,hasPostDepositInstruction:!!g}),xt&&x(Sr,{dk:K,dark:H,borderRadius:N.borderRadius.md,children:["\u26A1 ",xt]}),qn&&c(Sr,{dk:K,dark:H,borderRadius:N.borderRadius.md,children:"Low native balance in the external wallet. The deposit to spicenet account might fail."}),x("div",{style:{display:"flex",flexDirection:"column",gap:0,marginBottom:0,margin:0,padding:0},children:[Co?c("div",{style:{marginBottom:"10px",fontSize:"12px",lineHeight:"1.45",color:K.errorText,fontFamily:l?.fontFamily||N.typography.fontFamily},children:Co}):null,c(vt,{variant:"outline",fullWidth:!0,onClick:kt,disabled:!Kn||!Se||Be,theme:N,dark:H,styles:l,children:wo()})]})]})}):null}),gc=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,deposits:o,onComplete:s,onCancel:r,onSkip:a,onChangeWallet:l,isProcessing:d,error:i,styles:u})=>{const{dark:p,dk:f,theme:m}=ut(u);if(!e||o.length===0)return null;const h=o[0],g=u?.fontFamily||ve.ui,y=ve.mono,w=cn(h.chainId),b=parseFloat(h.amount).toPrecision(6).replace(/\.?0+$/,""),T=Xe(h.verifiedBalance,h.tokenDecimals);return c(Cn,{isOpen:e,onClose:t,title:"Incomplete Deposit",styles:u,closeOnBackdropClick:n,children:x("div",{style:{padding:"18px 24px 24px",fontFamily:g},children:[c("p",{style:{fontSize:"14px",color:f.textSecondary,lineHeight:"1.6",margin:"0 0 18px 0"},children:"Your funds reached your wallet, but the deposit didn't finish."}),x("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) auto",gap:"14px 18px",marginBottom:"24px",padding:"16px 18px",backgroundColor:p?f.cardBg:"#f8fafc",border:`1px solid ${f.cardBorder}`,borderRadius:p?"14px":"10px",boxShadow:p?"inset 0 1px 0 rgba(255,255,255,0.03)":"0 1px 2px rgba(16,24,40,0.04)"},children:[x("div",{style:{display:"flex",flexDirection:"column",gap:"4px"},children:[c("span",{style:{fontSize:"12px",fontWeight:600,color:f.textSecondary,fontFamily:y,letterSpacing:"0.8px"},children:"NETWORK"}),c("span",{style:{fontSize:"18px",fontWeight:600,color:f.textPrimary,fontFamily:g,lineHeight:1.2},children:w})]}),x("div",{style:{display:"flex",flexDirection:"column",gap:"4px",alignItems:"flex-end",textAlign:"right"},children:[c("span",{style:{fontSize:"12px",fontWeight:600,color:f.textSecondary,fontFamily:y,letterSpacing:"0.8px"},children:"DEPOSITED AMOUNT"}),x("span",{style:{fontSize:"24px",fontWeight:700,color:f.successText,fontFamily:y,lineHeight:1.1},children:[b," ",h.tokenSymbol]}),c("span",{style:{fontSize:"12px",color:f.textSecondary,fontWeight:500,fontFamily:g},children:"Sent to embedded wallet"})]})]}),!h.hasFullBalance&&h.verifiedBalance>0n&&x("div",{style:{marginBottom:"16px",padding:"8px 12px",backgroundColor:f.warningBg,border:`1px solid ${p?f.warningBorder:"#fcd34d"}`,borderRadius:"8px",fontSize:"13px",color:f.warningText,lineHeight:"1.4"},children:["Partial balance \u2014 only ",parseFloat(T).toFixed(4)," ",h.tokenSymbol," available."]}),i&&c("div",{style:{marginBottom:"16px",padding:"10px 12px",backgroundColor:f.errorBg,border:`1px solid ${p?f.errorBorder:"#fca5a5"}`,borderRadius:"8px",fontSize:"13px",color:p?f.errorText:"#991b1b",lineHeight:"1.4"},children:i}),x("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[c(vt,{variant:"outline",fullWidth:!0,disabled:d,onClick:()=>s(h),theme:m,dark:p,styles:u,children:"CONFIRM DEPOSIT"}),x("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:[c(vt,{variant:"ghost",fullWidth:!0,disabled:d,onClick:()=>r(h),theme:m,dark:p,style:{height:"48px",fontSize:"13px",letterSpacing:"0.4px",color:p?f.textPrimary:"#374151",border:`1px solid ${p?f.cardBorder:"#d1d5db"}`,borderRadius:"12px",backgroundColor:p?"rgba(255,255,255,0.02)":"#ffffff"},children:d?"RETURNING...":"RETURN FUNDS"}),x("div",{style:{display:"grid",gridTemplateColumns:l?"1fr 1fr":"1fr",gap:"10px"},children:[c(vt,{variant:"ghost",fullWidth:!0,disabled:d,onClick:a,theme:m,dark:p,style:{height:"44px",fontSize:"12px",letterSpacing:"0.4px",color:f.textSecondary,border:`1px solid ${p?f.cardBorder:"#d1d5db"}`,borderRadius:"12px",backgroundColor:"transparent"},children:"START OVER"}),l&&c(vt,{variant:"ghost",fullWidth:!0,disabled:d,onClick:l,theme:m,dark:p,style:{height:"44px",fontSize:"12px",letterSpacing:"0.4px",color:f.textSecondary,border:`1px solid ${p?f.cardBorder:"#d1d5db"}`,borderRadius:"12px",backgroundColor:"transparent"},children:"CHANGE WALLET"})]})]})]}),o.length>1&&x("p",{style:{fontSize:"12px",color:f.textSecondary,textAlign:"center",marginTop:"14px",marginBottom:0,lineHeight:"1.5"},children:[o.length," incomplete deposits found \u2014 resolving one at a time."]})]})})},Ns=e=>{const[t,n]=D(!1),o=qt(Ut),{dark:s,dk:r}=ut();if(G(()=>{n(!0)},[]),!t)return c("div",{className:e.className,children:c("button",{disabled:!0,style:{padding:"12px 24px",fontSize:"16px",backgroundColor:s?r.hoverBg:"#ccc",color:s?r.textSecondary:"white",border:s?`1px solid ${r.buttonBorder}`:"none",borderRadius:"4px",cursor:"not-allowed"},children:"Loading..."})});if(!o){const a='ProviderLogin must be used within SpiceFlowProvider. Please wrap your app with <SpiceFlowProvider provider="privy">.';return c("div",{className:e.className,children:c("button",{onClick:()=>{e.onAuthError&&e.onAuthError(a)},style:{padding:"12px 24px",fontSize:"16px",backgroundColor:s?r.errorBg:"#dc2626",color:s?r.errorText:"white",border:s?`1px solid ${r.errorBorder}`:"none",borderRadius:"4px",cursor:"pointer"},children:"Provider Not Found"})})}return c(mi,{...e})},yc=.01,xc=5*60*1e3;function bc(e){const t=Number(Xe(e.verifiedBalance,e.tokenDecimals));return Number.isFinite(t)?t:0}async function Cc(e){const t=wc(e);let n;try{n=await gs(t.map(o=>o.tokenSymbol))}catch{return t}return t.filter(o=>{const s=bc(o);if(s<=0)return!0;const r=n[o.tokenSymbol.toUpperCase()]??0;return!Number.isFinite(r)||r<=0?!0:s*r>=yc})}function wc(e){const t=new Map;for(const n of e){const o=`${n.chainId}:${n.tokenAddress.toLowerCase()}`;t.get(o)||t.set(o,{...n,amount:n.timestamp===0?Xe(n.verifiedBalance,n.tokenDecimals):n.amount,rawAmount:n.timestamp===0?n.verifiedBalance.toString():n.rawAmount,hasFullBalance:n.timestamp===0?!0:n.hasFullBalance})}return Array.from(t.values())}function ea(e,t){const[n,o]=D([]),[s,r]=D(!1),a=ee(t);a.current=t;const l=ee(0),d=ee(0),i=te(async({forceDiscovery:u=!1}={})=>{if(!e){o([]),r(!1);return}const p=++d.current,f=()=>p!==d.current;r(!0);try{const m=[],h=cc(e);for(const b of h){if(f())return;try{const T=pt(b.chainId);let k;if(b.isNative||Ue(b.tokenAddress)?k=await ss(T,{address:e}):k=await En(T,{address:lt(b.tokenAddress),abi:We,functionName:"balanceOf",args:[e]}),f())return;k>0n?m.push({...b,verifiedBalance:k,hasFullBalance:k>=BigInt(b.rawAmount)}):Date.now()-b.timestamp>15*60*1e3&&Ws(e,b.chainId,b.tokenAddress)}catch(T){console.warn(`[usePendingDeposit] Failed to verify balance for ${b.tokenSymbol} on chain ${b.chainId}:`,T),m.push({...b,verifiedBalance:0n,hasFullBalance:!1})}}if(f())return;const g=a.current,y=Date.now(),w=(g?.discoverWalletBalances??!0)&&(u||y-l.current>=xc);if(g?.network&&w){l.current=y;const b=g.chainIds??Fo(g.network),T=new Set(m.map(C=>`${C.chainId}:${C.tokenAddress.toLowerCase()}`)),k=[];for(const C of b){const B=Me(C);if(B?.supportedTokens)for(const A of B.supportedTokens){if(Ue(A.address))continue;const F=`${C}:${A.address.toLowerCase()}`;T.has(F)||k.push((async()=>{try{const E=pt(C),I=await En(E,{address:lt(A.address),abi:We,functionName:"balanceOf",args:[e]});return I>0n?{chainId:C,tokenAddress:A.address,tokenSymbol:A.symbol,tokenDecimals:A.decimals,amount:Xe(I,A.decimals),rawAmount:I.toString(),embeddedWalletAddress:e,externalWalletAddress:"",timestamp:0,isNative:!1,verifiedBalance:I,hasFullBalance:!0}:null}catch{return null}})())}}if(k.length>0){const C=await Promise.allSettled(k);if(f())return;for(const B of C)B.status==="fulfilled"&&B.value&&m.push(B.value)}}if(!f()){const b=await Cc(m);if(f())return;o(b)}}catch(m){console.error("[usePendingDeposit] Verification error:",m),f()||o([])}finally{f()||r(!1)}},[e]);return G(()=>{if(!a.current?.enabled){d.current++,o([]),r(!1);return}i({forceDiscovery:!0});const u=a.current?.pollIntervalMs??3e4;if(u<=0||!e)return()=>{d.current++};const p=setInterval(()=>{i({forceDiscovery:!1})},u),f=()=>i({forceDiscovery:!0});return window.addEventListener(jo,f),()=>{d.current++,window.removeEventListener(jo,f),clearInterval(p)}},[i,e]),{pendingDeposits:n,loading:s,refresh:()=>i({forceDiscovery:!0})}}function kc(e,t,n,o,s){return{address:t,symbol:n||"UNKNOWN",name:n||"Unknown Token",decimals:o||18,chainId:e,balance:0n,balanceFormatted:s?parseFloat(s):0,balanceUsd:0,isNative:Ue(t)}}const vc=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,styles:o,depositBatches:s,onDepositAmountChange:r,destinationChainId:a,destinationTokenAddress:l,onDepositExecute:d,depositActionLabel:i,sponsorGas:u=!1,escrowRecovery:p,skipTokenSelection:f=!1,onDepositSuccess:m,onDepositError:h,skipRecovery:g=!1})=>{const y=qt(Ut);if(!y)return c("div",{children:"Error: SpiceDeposit must be used within SpiceFlowProvider"});const w=(y.mode||"7702")!="7702",b=w,T=y.nativeChainId,k=y.network||"testnet",{dark:C,dk:B}=ut(o),A=!!p,F=bn(),{isReady:E,isAuthenticated:I,actions:S}=F,v=y?.embeddedWalletAddress,{address:R}=ts(),U=y?.externalWalletAddress??R,W=!!U,z=()=>f?"deposit":"select-token",P=()=>b?W?z():"connect-wallet":"provider-login",[M,N]=D(P()),[H,Y]=D(null),[j,K]=D(!1),{pendingDeposits:be,loading:O,refresh:X}=ea(v,{enabled:e,network:k,chainIds:y.supportedChainIds}),[re,ue]=D(null),[pe,Se]=D(!1),[fe,me]=D(null),[Re,L]=D(!1),[_,oe]=D("idle");G(()=>{e&&!g&&!A&&!re&&!Re&&_==="idle"&&I&&v&&W&&U&&!O&&be.length>0&&M!=="recovery"&&M!=="deposit"&&N("recovery")},[e,g,A,I,v,W,U,O,be,M,re,Re,_]);const ae=te(de=>{const Be={address:de.tokenAddress,symbol:de.tokenSymbol,name:de.tokenSymbol,decimals:de.tokenDecimals,chainId:de.chainId,balance:de.verifiedBalance,balanceFormatted:parseFloat(de.amount),balanceUsd:0,isNative:de.isNative};Y(Be),ue(de),N("deposit")},[]),q=te(()=>{L(!0),N(I&&v&&W&&U?f?"deposit":"select-token":I&&v?"connect-wallet":"provider-login")},[I,v,W,U,f]),se=te(()=>{me(null),oe("awaiting-disconnect"),N("connect-wallet")},[]),xe=te(async de=>{Se(!0),me(null);try{if(!v)throw new Error("Embedded wallet not available");const Be=await S.getEthereumProvider(),rt=Me(de.chainId);await sr(Be,de.chainId);const ft=pt(de.chainId),le=await ss(ft,{address:v}),gt=rt?.viemChain?.name||`chain ${de.chainId}`;if(le===0n)throw new Error(`Your embedded wallet has no ETH on ${gt} to pay for gas. We recommend completing the deposit instead \u2014 it doesn't require gas.`);const Ae=ns({account:v,transport:os(Be),chain:rt?.viemChain}),Ie=de.externalWalletAddress&&Gt(de.externalWalletAddress)?de.externalWalletAddress:U;if(!Ie||!Gt(Ie))throw new Error("Connect the external wallet that should receive these funds, then try again.");let ge;de.isNative||Ue(de.tokenAddress)?ge=await Ae.sendTransaction({to:Ie,value:de.verifiedBalance,chain:rt?.viemChain}):ge=await Ae.sendTransaction({to:de.tokenAddress,data:St({abi:We,functionName:"transfer",args:[Ie,de.verifiedBalance]}),chain:rt?.viemChain}),await ft.waitForTransactionReceipt({hash:ge,confirmations:1}),Ws(de.embeddedWalletAddress,de.chainId,de.tokenAddress),X(),be.length<=1&&N(P())}catch(Be){const rt=Be?.message||"Couldn't return your funds. Please try again.",ft=/insufficient funds for gas/i.test(rt);me(ft?"Not enough ETH in your embedded wallet to cover gas fees. Complete the deposit instead \u2014 it doesn't require gas.":rt)}finally{Se(!1)}},[S,v,U,be,X]);G(()=>{e||(ue(null),me(null),Se(!1),L(!1),oe("idle"))},[e]),G(()=>{if(_!=="idle"){if(_==="awaiting-disconnect"){(!W||!U)&&oe("awaiting-reconnect");return}e&&!O&&be.length>0&&I&&v&&(oe("idle"),N("recovery"))}},[_,W,U,e,O,be,I,v]),G(()=>{!A||!e||(I&&v?(K(!0),!H&&p?.chainId&&p?.tokenAddress&&Y(kc(p.chainId,p.tokenAddress,p.tokenSymbol,p.tokenDecimals,p.amount)),N("deposit")):N("provider-login"))},[A,e,M,I,v]);const{assets:Z,loading:Te}=ds({address:U,supportedChains:y.supportedChainIds,fetchBalances:cs,enabled:e&&!!U,refreshInterval:e?5e3:0}),Ge=te(()=>{K(!0),N(A?"deposit":W?f?"deposit":"select-token":"connect-wallet")},[A,W,f]),st=te(async()=>{if((!W||!U)&&(await wn(500),!W||!U)){alert("Please connect your wallet first");return}N(f?"deposit":"select-token")},[W,U,f]),$t=te(de=>{Y(de),N("deposit")},[]),Mt=te(()=>{if(Y(null),r?.(""),!U){N("connect-wallet");return}N("select-token")},[U,r]),Ze=te(()=>{t()},[t]);if(G(()=>{if(!e){const de=setTimeout(()=>{A||(N(P()),Y(null)),K(!1)},300);return()=>clearTimeout(de)}},[e,A,p?.chainId]),G(()=>{e&&M==="deposit"&&!H&&!A&&!re&&!f&&N("select-token")},[e,M,H,A,re,f]),G(()=>{e&&M==="connect-wallet"&&W&&U&&_==="idle"&&N(f?"deposit":"select-token")},[e,M,W,U,_,f]),G(()=>{if(!b&&e&&M==="provider-login"&&E&&I&&v&&!j){const de=setTimeout(()=>{K(!0),N(W?f?"deposit":"select-token":"connect-wallet")},100);return()=>clearTimeout(de)}},[b,e,M,E,I,v,W,f,j]),!e)return null;if(M==="recovery")return c(gc,{isOpen:e,onClose:Ze,closeOnBackdropClick:n,deposits:be,onComplete:ae,onCancel:xe,onSkip:q,onChangeWallet:se,isProcessing:pe,error:fe,styles:o});if(M==="provider-login"&&!b)return c("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.5)",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",zIndex:50},children:c("div",{style:{backgroundColor:C?B.cardBg:"white",borderRadius:"9px",padding:"32px 24px",maxWidth:"400px",width:"100%"},children:c(Ns,{onAuthSuccess:Ge,autoTrigger:!0})})});if(M==="connect-wallet")return c(kl,{isOpen:e,onClose:Ze,closeOnBackdropClick:n,onContinue:st,requiredChainId:w?T:void 0,styles:o});if(M==="select-token")return U?c(bl,{isOpen:e,onClose:Ze,closeOnBackdropClick:n,onTokenSelect:$t,walletAddress:U,supportedChainIds:y.supportedChainIds,network:k,prefetchedAssets:Te?null:Z??null,styles:o,dark:C}):(N("connect-wallet"),null);if(M==="deposit"){if(!H&&!f)return null;const de=!!re;return c(_r,{isOpen:e,onClose:Ze,closeOnBackdropClick:n,supportedChains:H?[H.chainId]:y.supportedChainIds??[],styles:o,externalWalletAddress:U,depositBatches:de?void 0:s,onDepositAmountChange:r,destinationChainId:a,destinationTokenAddress:l,onDepositExecute:d,depositActionLabel:i,nativeChainId:T,sponsorGas:u,preSelectedAsset:H??void 0,escrowOnly:A||de,escrowTokenAddress:de?re.tokenAddress:p?.tokenAddress,escrowAmount:de?re.amount:p?.amount,escrowTokenDecimals:de?re.tokenDecimals:p?.tokenDecimals,escrowTokenSymbol:de?re.tokenSymbol:p?.tokenSymbol,onDepositSuccess:m,onDepositError:h,embeddedWalletAddress:v,onViewAllAssets:f?void 0:Mt})}return null},Ic=e=>qt(Ut)?c(vc,{...e}):c("div",{children:"Error: SpiceDeposit must be used within SpiceFlowProvider"}),Ac=({isOpen:e,onClose:t,onChainSelect:n,supportedChains:o,closeOnSelect:s=!0,styles:r})=>{const{theme:a,dark:l,primaryColor:d,dk:i}=ut(r),[u,p]=D(""),[f,m]=D(null),[h,g]=D(null),[y,w]=D(!1),[b,T]=D(null),{switchChainAsync:k}=ir(),C=ne(()=>new Set(o||[]),[o]),B=ne(()=>{if(!o||o.length===0)return[];const I=[];return o.forEach((S,v)=>{if(typeof S!="number")return;const R=Me(S);R&&I.push({id:S.toString(),name:R.displayName,icon:Fn[S]||co,chainId:S,verified:!0,order:v})}),I},[o]);G(()=>{f&&!C.has(parseInt(f,10))&&m(null)},[f,C]);const A=ne(()=>B.filter(I=>I.name.toLowerCase().includes(u.toLowerCase())).sort((I,S)=>I.order-S.order),[B,u]),F=async()=>{if(!f)return;const I=parseInt(f,10);w(!0),T(null);try{await k({chainId:I}),n&&n(f),s&&t()}catch(S){console.error("Failed to switch chain:",S),T(un(S,"Failed to switch chain."))}finally{w(!1)}},E=!f||y;return x(Cn,{isOpen:e,onClose:t,title:"Select Chain",styles:r,theme:a,dark:l,children:[c("div",{style:{padding:"24px 20px"},children:c(is,{value:u,onChange:p,ariaLabel:"Search chains",placeholder:"Search chain name, symbol or address",size:"md",dark:l,styles:r,endAdornment:c("div",{style:{padding:"5px 5px",borderRadius:"3px",fontSize:"13px",backgroundColor:l?i.cardBg:"#E9E9E9",color:l?i.textSecondary:"#485066",fontWeight:500,flexShrink:0},"aria-hidden":"true",children:"\u2318F"})})}),c("div",{style:{padding:"0 32px 20px",display:"flex",flexDirection:"column",gap:"12px"},children:A.map(I=>{const S=f===I.id,v=h===I.id;return x("button",{onClick:()=>m(I.id),onMouseEnter:()=>g(I.id),onMouseLeave:()=>g(null),style:{width:"100%",display:"flex",alignItems:"center",gap:"16px",padding:"8px",borderRadius:"8px",backgroundColor:S?l?`${d}15`:`${d}12`:"transparent",border:S?l?`1px solid ${d}66`:`1px solid ${d}88`:v?l?`1px solid ${d}44`:`1px solid ${d}66`:"1px solid transparent",cursor:"pointer",transition:dn.interactive},children:[c("div",{style:{width:"40px",height:"40px",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"30px"},children:c("img",{src:I.icon,alt:I.name,loading:"lazy",decoding:"async",style:{width:"100%",height:"100%",borderRadius:"50%"}})}),x("div",{style:{display:"flex",alignItems:"center",gap:"6px",flex:1},children:[c("span",{style:{fontFamily:ve.mono,fontSize:"17px",fontWeight:500,letterSpacing:"0.4px",color:i.textPrimary,textAlign:"left"},children:I.name}),I.verified&&c("img",{src:vr,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:16,height:16,style:{width:"16px",height:"16px",filter:l?"brightness(0) invert(1)":"none"}})]})]},I.id)})}),b&&c("div",{style:{padding:"0 25px 12px"},children:c(Qn,{variant:"error",size:"compact",palette:i,children:b})}),c("div",{style:{padding:"0 25px 25px"},children:x(vt,{variant:"outline",onClick:F,disabled:E,fullWidth:!0,theme:a,styles:r,dark:l,children:["SELECT",c(Vi,{size:20})]})})]})},ta=({isSuccess:e,type:t,chainName:n,explorerUrl:o,txHash:s,dark:r=!1,successBg:a="#d1fae5",successBorder:l="#6ee7b7",successText:d="#065f46",errorBg:i="#fee2e2",errorBorder:u="#fca5a5",errorText:p="#dc2626",textSecondary:f="#6b7280"})=>x("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px",borderRadius:"8px",backgroundColor:e?a:i,border:e?`1px solid ${l}`:`1px solid ${u}`},children:[x("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[c("div",{style:{width:"28px",height:"28px",borderRadius:"50%",backgroundColor:e?"#10b981":"#ef4444",display:"flex",alignItems:"center",justifyContent:"center"},children:e?c("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:c("path",{d:"M11.6667 3.5L5.25 9.91667L2.33333 7",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}):c("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:c("path",{d:"M10.5 3.5L3.5 10.5M3.5 3.5L10.5 10.5",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),x("div",{children:[c("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:ve.mono,letterSpacing:"0.5px",color:e?d:p},children:e?`${t.toUpperCase()} CONFIRMED`:`${t.toUpperCase()} FAILED`}),x("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:f},children:["on ",n]})]})]}),o&&s&&x("a",{href:`${o}/tx/${s}`,target:"_blank",rel:"noopener noreferrer",style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"13px",color:f,textDecoration:"none",whiteSpace:"nowrap"},children:["View on explorer",x("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:[c("path",{d:"M9 6.5V9.5C9 9.76522 8.89464 10.0196 8.70711 10.2071C8.51957 10.3946 8.26522 10.5 8 10.5H2.5C2.23478 10.5 1.98043 10.3946 1.79289 10.2071C1.60536 10.0196 1.5 9.76522 1.5 9.5V4C1.5 3.73478 1.60536 3.48043 1.79289 3.29289C1.98043 3.10536 2.23478 3 2.5 3H5.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),c("path",{d:"M7.5 1.5H10.5V4.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),c("path",{d:"M5 7L10.5 1.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})]})]})]}),na=`
|
|
30
|
+
`})]})};async function ic(e,t,n){let o=null;try{const s=await e.request({method:"eth_chainId"});o=parseInt(s,16)}catch{o=null}o!==t&&(n?.(),await sr(e,t))}async function so(e){const t=e.provider??await e.wallet?.getEthereumProvider();if(!t)throw new Error("External wallet provider not available");await ic(t,e.chainId,e.onSwitch);const n=Me(e.chainId)?.viemChain;return{extWc:ns({account:e.account,chain:n,transport:os(t)}),viemChain:n}}async function Zr(e){let t;for(const n of e.calls){const o=await e.extWc.sendTransaction({to:n.to,data:n.data,value:n.value,chain:e.viemChain});if((await e.client.waitForTransactionReceipt({hash:o,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error(e.errorMessage);t=o}return t}function Xr(e,t){return t.isNative?e.sendTransaction({to:t.recipient,value:t.amount,chain:t.viemChain}):e.sendTransaction({to:t.tokenAddr,data:St({abi:We,functionName:"transfer",args:[t.recipient,t.amount]}),chain:t.viemChain})}async function Ts(e){const{extWc:t,sourceClient:n,recipient:o,tokenAddr:s,isNative:r,amount:a}=e;if(a<=0n)return;const l=await Xr(t,{recipient:o,tokenAddr:s,isNative:r,amount:a,viemChain:e.viemChain});if((await n.waitForTransactionReceipt({hash:l,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Embedded wallet funding failed")}const Gr="spiceflow:pendingDeposit",jo="spiceflow:pendingDepositChanged";function Jr(e,t,n){return`${Gr}:${e.toLowerCase()}:${t}:${n.toLowerCase()}`}function Rs(){try{const e="__spiceflow_storage_test__";return localStorage.setItem(e,"1"),localStorage.removeItem(e),!0}catch{return!1}}function lc(e){if(!Rs())return;const t=Jr(e.embeddedWalletAddress,e.chainId,e.tokenAddress);try{localStorage.setItem(t,JSON.stringify(e)),window.dispatchEvent(new Event(jo))}catch(n){console.error("[pendingDeposit] Failed to save:",n)}}function cc(e){if(!Rs())return[];const t=`${Gr}:${e.toLowerCase()}:`,n=[],o=Date.now();for(let s=0;s<localStorage.length;s++){const r=localStorage.key(s);if(!(!r||!r.startsWith(t)))try{const a=localStorage.getItem(r);if(!a)continue;const l=JSON.parse(a);if(o-l.timestamp>6048e5){localStorage.removeItem(r);continue}n.push(l)}catch{localStorage.removeItem(r)}}return n}function Ws(e,t,n){if(!Rs())return;const o=Jr(e,t,n);localStorage.removeItem(o),window.dispatchEvent(new Event(jo))}function dc({sourceChainId:e,selectedAsset:t,destinationChainId:n,destinationTokenAddress:o,isCrossDenomination:s,convertedUsdAmount:r}){const a=ht(t.asset.address),l=o;let d,i;if(l&&n)if(d=So[n]?.supportedTokens?.find(u=>Ee(u.address,l))?.decimals??t.asset.decimals,s){if(!r)throw new Error("Destination amount is still being calculated. Please retry in a moment.");i=r}else{const u=Oe(t.amount,t.asset.decimals);i=io(u,t.asset.decimals,d)}return{sourceChainId:e,depositTokenAddress:a,depositAmount:t.amount,depositTokenDecimals:t.asset.decimals,destinationChainId:n,destinationTokenAddress:l,destinationAmount:i,destinationTokenDecimals:d}}async function uc(e,t){if(!e)return[];if(Array.isArray(e))return e;const n=e;return e.length>=2?n(t.depositAmount,t.depositTokenAddress):n(t)}async function Ds(e,t){const n=await Xr(e,{recipient:t.recipient,tokenAddr:t.tokenAddr,isNative:t.isNative,amount:t.amount});t.afterSend?.(n);const o=pt(t.chainId),s=await o.waitForTransactionReceipt({hash:n,timeout:12e4,pollingInterval:2e3,confirmations:2});if(s.status!=="success")throw new Error(t.failureMessage);return t.settle&&await o.getBlockNumber()-s.blockNumber<2n&&await wn(3e3),s.transactionHash}async function pc(e){const t=e.selectedDepositAssets.filter(o=>o.asset&&o.amount&&parseFloat(o.amount)>0);if(t.length===0){console.error("[DepositModal] No valid assets for deposit"),e.setError("Please select an asset and enter an amount");return}if(!e.escrowOnly&&!e.sourceAddress){e.setError("External wallet not connected. Please connect your wallet in the previous step.");return}if(!e.isNon7702){if(!e.address||!e.embeddedWalletAddress){e.setError("Couldn't find your account wallet. Try reconnecting.");return}if(!e.isReady||!e.isAuthenticated){e.setError("Sign in to continue.");return}}if(e.zeroCreditError){e.setError(e.zeroCreditError);return}if(e.depositBalanceError){e.setError(e.depositBalanceError);return}e.setIsExecuting(!0),e.setError(null);let n=!1;try{const o=t[0].asset.chainId,s=pn(o);let r=e.externalWalletClient;if(!e.escrowOnly){if(!r)throw new Error("External wallet not connected");if(e.externalProvider){const a=await so({provider:e.externalProvider,account:e.sourceAddress,chainId:o});a.viemChain&&(r=a.extWc)}}if(e.isNon7702){if(!r)throw new Error("External wallet not connected");if(!e.sourceAddress)throw new Error("External wallet address not available");if(e.nativeChainId&&o===e.nativeChainId){const a=Me(o),l=t.map(i=>`${i.amount} ${i.asset.symbol}`).join(", ");e.setConfirmationData({network:a?.displayName||`Chain ${o}`,amount:l,symbol:"",chainId:o}),e.setShowConfirmation(!0);let d=null;e.setDirectDepositStatus("processing"),e.setDirectDepositChainId(o);for(const i of t){const u=Oe(i.amount,i.asset.decimals),p=ht(i.asset.address),f=i.asset.isNative||Ue(p),m=await Ds(r,{chainId:o,recipient:s,tokenAddr:p,isNative:f,amount:u,failureMessage:`Escrow deposit failed for ${i.asset.symbol}`});d=m,e.setDirectDepositTxHash(m)}if(t[0]?.amount){const i=t[0].amount;if(e.onDepositExecute){e.setPostDepositStatus("executing");try{await e.onDepositExecute(i),e.setPostDepositStatus("success")}catch(p){console.error("ctx.onDepositExecute failed:",p),e.setPostDepositStatus("error"),e.setPostDepositError(p?.message||"Post-deposit instruction failed")}}else e.setPostDepositStatus("success");e.setDirectDepositStatus("success"),e.setPostDepositAmount(i),e.setPostDepositSuccess(!0);const u={type:"deposit",status:"success",amount:i,asset:t[0].asset.symbol,sourceChain:a?.displayName||`Chain ${o}`,txHash:d??void 0};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:u})),e.onDepositSuccess?.(u)}e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset)}else{const a=e.destinationChainId||e.nativeChainId;if(!a)throw new Error("Destination chain ID is required for non-7702 mode. Either pass ctx.destinationChainId to <SpiceDeposit> or set ctx.nativeChainId on <SpiceFlowProvider>.");const l=or(o),d=s,i=[];let u=null;for(const p of t){const f=Oe(p.amount,p.asset.decimals),m=ht(p.asset.address),h=p.asset.isNative||Ue(m),g=await Ds(r,{chainId:o,recipient:d,tokenAddr:m,isNative:h,amount:f,failureMessage:`Transfer failed for ${p.asset.symbol}`,afterSend:y=>{u||(u=y)},settle:!0});e.depositDataRef.current||(e.depositDataRef.current=[]),e.depositDataRef.current.push({txHash:g,sender:e.sourceAddress,tokenAddress:m,chainId:o,amount:f.toString(),user:e.spiceBalanceUser}),i.push({tokenAddress:m,tokenAmount:f.toString(),sender:e.sourceAddress,receiver:d})}if(!u)throw new Error("No transaction hash generated");if(!e.destinationTokenAddress){const p={type:"deposit",status:"success",amount:t[0]?.amount,asset:t[0]?.asset?.symbol,sourceChain:cn(o),txHash:u};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:p})),e.onDepositSuccess?.(p),e.depositDataRef.current=null,e.bridgedAmountRef.current=t[0]?.amount||null,e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset),e.setShowConfirmation(!1);return}if(e.sponsorGas&&e.nativeChainId){const p=Oe("0.05",18);i.push({tokenAddress:Dt,tokenAmount:p.toString(),sender:e.sourceAddress,receiver:d})}if(e.mode==="ondemand"){const p={to:l,value:BigInt(0),data:"0x"},f=await rr(a,e.destinationTokenAddress);let m=BigInt(0);for(const B of i){const A=BigInt(B.tokenAmount),F=ht(B.tokenAddress),E=t.find(S=>{const v=ht(S.asset.address);return Ee(v,F)}),I=E?E.asset.decimals:await rr(o,Dt);m+=io(A,I,f)}e.isCrossDenomination&&e.convertedUsdAmount&&(m=e.convertedUsdAmount);const h={chainId:o,tokenTransfers:i.map(B=>({from:B.sender,to:B.receiver,token:B.tokenAddress,amount:BigInt(B.tokenAmount)})),call:p},g=e.isCrossDenomination&&e.convertedUsdAmount?[{from:e.sourceAddress,to:s,token:ht(t[0].asset.address),amount:Oe(t[0].amount,t[0].asset.decimals)}]:[],y={chainId:a,tokenTransfers:[...g,{from:"escrow",to:e.sourceAddress,token:e.destinationTokenAddress,amount:m}],call:{to:e.destinationTokenAddress,value:BigInt(0),data:"0x"}},w={mode:"non-7702:on-demand",chainBatches:[h,y]},b={user:e.sourceAddress,intents:[w]},T=await It.createAction(b),k=T.actionId,C=T.intentIds[0];if(!u)throw new Error("No transaction hash available");e.startStatusPolling(C,es([{chainId:o,calls:[p]},{chainId:a,calls:[y.call]}],B=>cn(B))),await It.executeStep(k,0,0,{action:"execute",hash:u}),t[0]?.amount&&(e.bridgedAmountRef.current=t[0].amount),e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset),e.setShowConfirmation(!1)}else throw new Error("Presign mode not yet fully supported for cross-chain deposits")}}else{const a=[],l=t[0],d=l&&t.length===1&&e.effectiveDepositFee&&e.effectiveDepositFee.chainId===o&&Ee(e.effectiveDepositFee.token,ht(l.asset.address))?Xe(e.effectiveDepositFee.net,l.asset.decimals):l?.amount;for(const b of t){const T=Oe(b.amount,b.asset.decimals),k=t.length===1&&!!e.effectiveDepositFee&&e.effectiveDepositFee.chainId===o&&Ee(e.effectiveDepositFee.token,ht(b.asset.address)),C=k?e.effectiveDepositFee.fee:0n,B=k?e.effectiveDepositFee.net:T,A=e.escrowOnly?T:T+C,F=ht(b.asset.address),E=b.asset.isNative||Ue(F);e.escrowOnly||await Ds(r,{chainId:o,recipient:e.address,tokenAddr:F,isNative:E,amount:A,failureMessage:`Transfer to embedded wallet failed for ${b.asset.symbol}`,afterSend:()=>lc({chainId:o,tokenAddress:ht(b.asset.address),tokenSymbol:b.asset.symbol,tokenDecimals:b.asset.decimals,amount:b.amount,rawAmount:T.toString(),embeddedWalletAddress:e.address,externalWalletAddress:e.sourceAddress,timestamp:Date.now(),isNative:E}),settle:!0}),a.push(E?{to:s,value:B,data:"0x"}:{to:F,value:BigInt(0),data:St({abi:We,functionName:"transfer",args:[s,B]})}),C>0n&&a.push(E?{to:sn,value:C,data:"0x"}:{to:F,value:BigInt(0),data:St({abi:We,functionName:"transfer",args:[sn,C]})})}const i=await pt(o).getBlockNumber(),u=a.map(b=>({...b,to:lt(b.to)})),p={chainId:o,recentBlock:i,calls:u,tokenTransfers:[]},f=dc({sourceChainId:o,selectedAsset:l&&d?{...l,amount:d}:t[0],destinationChainId:e.destinationChainId,destinationTokenAddress:e.destinationTokenAddress,isCrossDenomination:e.isCrossDenomination,convertedUsdAmount:e.convertedUsdAmount}),m=await uc(e.depositBatches,f),h=[p,...m];if(!e.address)throw new Error("Address not available");const g=[];if(e.isCrossDenomination&&e.convertedUsdAmount&&e.destinationTokenAddress){const b=e.selectedDepositAssets[0]?.asset;if(b){const T=Oe(e.selectedDepositAssets[0].amount,b.decimals);g.push({from:e.address,to:s,token:ht(b.address),amount:T}),g.push({from:"escrow",to:e.address,token:e.destinationTokenAddress,amount:e.convertedUsdAmount})}}g.length>0&&h[1]&&(h[1].tokenTransfers=g);const y=es(h,b=>cn(b));let w=!1;if(await e.execution.execute(h,Dt,0n,b=>{if(b.intentId&&!w){w=!0;for(const T of t)Ws(e.address,o,ht(T.asset.address));e.startStatusPolling(b.intentId,y)}},void 0,{userOverride:e.address,useCustomTransfers:!0,skipPreSubmitFeeEstimate:!0,skipUserFundingPreflight:!0}),e.refreshAssets(),e.onDepositExecute&&t[0]?.amount)try{e.setPostDepositStatus("executing"),await e.onDepositExecute(d||t[0].amount),e.setPostDepositStatus("success"),e.setPostDepositAmount(d||t[0].amount),e.setPostDepositSuccess(!0)}catch(b){console.error("ctx.onDepositExecute failed (7702):",b),e.setPostDepositStatus("error"),e.setPostDepositError(b?.message||"Post-deposit instruction failed")}e.onDepositSelect&&e.onDepositSelect(t[0].asset)}}catch(o){n=!0,console.error("[DepositModal] executeDeposit CAUGHT ERROR:",o),console.error("[DepositModal] Error details:",{message:o?.message,code:o?.code,name:o?.name,stack:o?.stack?.slice(0,500)}),e.setError(un(o,"Deposit failed")),e.clearStatus()}finally{e.setIsExecuting(!1),n&&e.setDirectDepositStatus("idle"),n||!e.getCurrentIntentStatus()&&e.getCurrentPostDepositStatus()!=="idle"||e.setShowConfirmation(!1)}}async function hc(e){const{asset:t,assetIndex:n,selectedAssetCount:o,address:s,escrowOnly:r,isNon7702:a}=e;if(n!==0||a||o>1||!s||t.balance<=0n)return null;const l=await $r({address:s,depositQuote:{asset:t,amount:t.balance,token:ht(t.address),chainId:t.chainId},escrowOnly:r}),d=r?t.balance:t.balance>l.fee?t.balance-l.fee:0n;return Or(d,t.decimals)}async function $r(e){const{address:t,depositQuote:n,escrowOnly:o}=e,{asset:s,amount:r,token:a,chainId:l}=n,d=pn(l),i=s.isNative||Ue(a),u=r>1n?1n:0n,p=[i?{to:d,value:r,data:"0x"}:{to:a,value:0n,data:St({abi:We,functionName:"transfer",args:[d,r]})}];u>0n&&p.push(i?{to:sn,value:u,data:"0x"}:{to:a,value:0n,data:St({abi:We,functionName:"transfer",args:[sn,u]})});const f={chainId:l,tokenTransfers:[],calls:p},m=(await It.estimateBatchGas({user:t,outputToken:a,chainBatches:[{...f,hash:Sn([f])[0].hash}]})).gasFee,h=o&&m<r?r-m:r;return{fee:m,net:h,token:a,chainId:l}}const fc=({selectedDepositAssets:e,depositAssets:t,secondAssetOptions:n,loadingAssets:o,allowSecondAsset:s,theme:r,styles:a,dark:l,dk:d,onSelect:i,onAmountChange:u,onAdd:p,onRemove:f,resolveMaxAmount:m,onViewAllAssets:h})=>x(on,{children:[e.map((g,y)=>{const w=e.length===1?"Deposit":`Asset ${y+1}`;return x("div",{style:{marginBottom:r.spacing.md,position:"relative"},children:[c(po,{assets:y===0?t:n,selectedAsset:g||void 0,onAssetSelect:b=>i(b,y),onAmountChange:b=>u(b,y),loading:o,label:w,showBalance:!0,theme:r,styles:a,allowSecondAsset:s&&y===0,onAddAsset:p,canAddAsset:e.length===1&&!!e[0]?.asset,resolveMaxAmount:m?b=>m(b,y):void 0,onViewAllAssets:y===0?h:void 0}),y===1&&c("button",{onClick:()=>f(y),style:{position:"absolute",top:"-2px",right:"-2px",background:l?`${d.cardBg}ee`:"rgba(255, 255, 255, 0.9)",border:`1px solid ${d.cardBorder}`,borderRadius:"50%",cursor:"pointer",color:r.colors.textMuted,fontSize:"16px",padding:"2px",width:"22px",height:"22px",display:"flex",alignItems:"center",justifyContent:"center",transition:dn.interactive,boxShadow:"0 1px 3px rgba(0, 0, 0, 0.1)"},onMouseEnter:b=>{b.currentTarget.style.color=l?d.errorText:"#ef4444",b.currentTarget.style.background=l?d.cardBg:"#fff",b.currentTarget.style.borderColor=l?d.errorBorder:"#fecaca"},onMouseLeave:b=>{b.currentTarget.style.color=r.colors.textMuted,b.currentTarget.style.background=l?`${d.cardBg}ee`:"rgba(255, 255, 255, 0.9)",b.currentTarget.style.borderColor=l?d.cardBorder:"#e5e7eb"},title:"Remove asset",children:"\xD7"})]},`asset-${y}`)}),e.length===0&&c("div",{style:{marginBottom:r.spacing.md},children:c(po,{assets:t,selectedAsset:void 0,onAssetSelect:g=>i(g,0),onAmountChange:g=>u(g,0),loading:o,label:"Deposit",showBalance:!0,theme:r,styles:a,allowSecondAsset:s,onAddAsset:p,canAddAsset:!1,resolveMaxAmount:m?g=>m(g,0):void 0},"initial-selector")})]}),mc=Xt(fc);var Ms="data:image/svg+xml,%3csvg width='10' height='10' viewBox='0 0 10 10' fill='none' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M5 4.99995V6.99995M5 3.31245V3.31189M9.5 5C9.5 7.48528 7.48528 9.5 5 9.5C2.51472 9.5 0.5 7.48528 0.5 5C0.5 2.51472 2.51472 0.5 5 0.5C7.48528 0.5 9.5 2.51472 9.5 5Z' stroke='black' stroke-opacity='0.4' stroke-linecap='round' stroke-linejoin='round'/%3e%3c/svg%3e";const _r=mn.memo(({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,onDepositSelect:o,depositBatches:s,supportedChains:r,title:a,styles:l,onDepositAssetChange:d,assetInputHook:i,externalWalletAddress:u,onDepositAmountChange:p,allowSecondAsset:f=!1,destinationChainId:m,destinationTokenAddress:h,onDepositExecute:g,depositActionLabel:y,nativeChainId:w,sponsorGas:b=!1,preSelectedAsset:T,escrowOnly:k=!1,escrowTokenAddress:C,escrowAmount:B,escrowTokenDecimals:A,escrowTokenSymbol:F,onDepositSuccess:E,onDepositError:I,embeddedWalletAddress:S,onViewAllAssets:v})=>{const R=qt(Ut),U=R?.mode||"7702",W=R?.allowedTokens,z=!!R?.isWhitelistGateActive,P=!k&&!!R?.isWhitelistConfigured&&R?.isUserWhitelisted!==!0,M=i?.assetAmount||"",{theme:N,dark:H,appName:Y,primaryColor:j,dk:K}=ut(l),be=bn(),{isReady:O,isAuthenticated:X}=be,{externalWallet:re}=_n(),ue=R?.embeddedWalletAddress||S,pe=U!="7702",Se=pe?!!u:O&&X&&!!ue,fe=ue,me=u,Re=fe??me,{data:L}=Ii(),[_,oe]=mn.useState(L),ae=mn.useRef(null),q=mn.useRef(re);q.current=re;const se=re?.address;mn.useEffect(()=>{const Q=q.current;if(!Q||!me){ae.current=null,oe(L);return}if(Q.address?.toLowerCase()!==me?.toLowerCase()){ae.current=null,oe(L);return}Q.getEthereumProvider().then(async ce=>{ae.current=ce;const Fe=await ce.request({method:"eth_chainId"}),ye=parseInt(Fe,16),ct=Me(ye),dt=await Q.getWalletClient(ye);oe(ct?ns({account:me,chain:ct.viemChain,transport:os(ce)}):dt)}).catch(()=>{ae.current=null,oe(L)})},[se,me,L]);const xe=mn.useRef(null),[Z,Te]=D([]),{assets:Ge,loading:st,error:$t,refreshAssets:Mt}=ds({address:k?fe:me||fe,supportedChains:r,fetchBalances:cs,enabled:e,refreshInterval:e?5e3:0}),Ze=ne(()=>{if(z)return[];const Q=r.flatMap(ce=>ar(ce,Ge));return W&&W.length>0?Q.filter(ce=>W.includes(ce.symbol.toLowerCase())||ce.isNative&&W.includes("native")).sort((ce,Fe)=>{const ye=ce.balance>BigInt(0)?1:0;return(Fe.balance>BigInt(0)?1:0)-ye}):Q.filter(ce=>ce.balance>BigInt(0))},[r,Ge,W,z]),de=ne(()=>{if(!Z[0]?.asset)return[];const Q=Z[0].asset.chainId;return Ze.filter(ce=>ce.chainId===Q)},[Ze,Z]),[Be,rt]=D(!1),[ft,le]=D(null),gt=ee(I);gt.current=I;const Ae=te(Q=>{le(Q),typeof Q=="string"&&Q&>.current?.(Q,ao(Q))},[]),[Ie,ge]=D("idle"),Qe=te(Q=>{typeof Q=="string"&&Q&>.current?.(Q,ao(Q))},[]),[Lt,Pt]=D(!1),[_t,Le]=D(null),[at,zt]=D("idle"),[jt,en]=D(null),[Je,yt]=D(null),[rn,Ot]=D(null),[he,$e]=D(null),[xt,Et]=D(null),{intentStatus:ke,startStatusPolling:Nt,clearStatus:tn,execute:it}=no(),Pe=te((Q,ce)=>{const Fe=So[ce];return Fe?Fe.supportedTokens?.find(ye=>Ee(ye.address,Q))?.symbol??null:null},[]),bt=ne(()=>{const Q=Z[0]?.asset;if(!Q||!h||!m)return!1;const ce=Pe(h,m);return ul(Q.symbol)&&!!ce&&pl(ce)},[Z,h,m,Pe]);G(()=>{Z.length>0&&M!==Z[0]?.amount&&Te(Q=>{if(Q.length===0)return Q;const ce=[...Q];return ce[0]={...ce[0],amount:M||""},ce})},[M]),G(()=>{Z.length!==0&&Te(Q=>{let ce=!1;const Fe=Q.map(ye=>{if(!ye.asset)return ye;const ct=Ze.find(dt=>dt.chainId===ye.asset.chainId&&Ee(dt.address,ye.asset.address));return ct?ct===ye.asset||ct.balance===ye.asset.balance?ye:(ce=!0,{...ye,asset:ct,amount:ye.amount}):ye});return ce?Fe:Q})},[Ze,Z.length]),G(()=>{if(!T||Z.length>0||Ze.length===0)return;const Q=Ze.find(ce=>ce.chainId===T.chainId&&Ee(ce.address,T.address));Q&&(Te([{asset:Q,amount:""}]),d?.(Q))},[T,Ze,Z.length]);const an=mn.useRef(null);G(()=>{if(pe&&ke?.overallStatus==="success"&&g&&Ie==="idle"){const Q=an.current,ce=xe.current;Q&&(async()=>{try{ge("executing"),await g(Q),ge("success"),Le(Q),Pt(!0);const Fe=Array.isArray(ce)?ce[0]:void 0,ye={type:"deposit",status:"success",amount:Q,asset:Fe?.tokenAddress,sourceChain:Fe?String(Fe.chainId):void 0,txHash:Fe?.txHash};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:ye})),E?.(ye)}catch(Fe){console.error("onDepositExecute failed:",Fe),ge("error"),Qe(un(Fe,"Post-deposit instruction failed"))}finally{an.current=null,xe.current=null}})()}},[ke?.overallStatus,pe,Ie]);const Ft=te(()=>{Ae(null)},[]);G(()=>{e||(Pt(!1),Le(null),zt("idle"),en(null),yt(null))},[e]);const _e=te((Q,ce)=>{Te(Fe=>{const ye=[...Fe];return ye[ce]={asset:Q,amount:ye[ce]?.amount||""},ye}),ce===0&&d?.(Q),Ft()},[d,Ft]),Ve=te(async(Q,ce)=>{if(Te(Fe=>{const ye=[...Fe];return ye[ce]&&(ye[ce]={...ye[ce],amount:Q}),ye}),Ft(),ce===0)if(i?.setAssetAmount(Q),bt&&Q&&parseFloat(Q)>0)try{const Fe=rn??await dl();rn||Ot(Fe);const ye=Z[0]?.asset;if(!ye)return;const ct=Oe(Q,ye.decimals),dt=h?Pe(h,m):null,Nn=So[m]?.supportedTokens?.find(Xo=>Ee(Xo.address,h))?.decimals??6,ko=hl(ct,ye.decimals,Nn,Fe);$e(ko);const vo=Xe(ko,Nn),Zo=Fe.toLocaleString("en-US",{maximumFractionDigits:0});Et(`${Q} ${ye.symbol} \u2248 $${parseFloat(vo).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})} ${dt??"USD"} (rate: $${Zo}/BTC)`),p?.(vo)}catch(Fe){console.error("Failed to fetch BTC/USD price:",Fe),Et(null),$e(null),p?.(Q)}else Et(null),$e(null),p?.(Q)},[Ft,i,p,bt,rn,Z,h,m,Pe]),Bt=te(()=>{Z.length<2&&Te(Q=>[...Q,{asset:null,amount:""}])},[Z.length]),Yt=te(Q=>{Te(ce=>ce.filter((Fe,ye)=>ye!==Q)),Ft()},[Ft]),et=ee(!1),xn=ee(!1);G(()=>{e||(et.current=!1,xn.current=!1,Rt(null),wt(null))},[e]);const[je,Tt]=D(!1),[ln,Ct]=D(null),[ze,Rt]=D(null),[Wt,wt]=D(null),[tt,Kt]=D(!1),[V,J]=D(null),ie=ne(()=>{const Q=Z[0];if(Z.length!==1||!Q?.asset||!Q.amount||parseFloat(Q.amount)<=0)return null;try{return{asset:Q.asset,amount:Oe(Q.amount,Q.asset.decimals),token:ht(Q.asset.address),chainId:Q.asset.chainId}}catch{return null}},[Z]),qe=ne(()=>ie?[ie.chainId,ie.token.toLowerCase(),ie.amount.toString(),k?"escrow":"normal"].join("|"):null,[ie,k]),$=te(async Q=>fe?$r({address:fe,depositQuote:Q,escrowOnly:k}):null,[fe,k]),we=te(async()=>ie?$(ie):null,[ie,$]),Ye=ee(we);Ye.current=we,G(()=>{let Q=!1;if(!e||pe||!qe||je||Be){Rt(null),J(null),Kt(!1);return}const ce=async()=>{J(null),Kt(!0);try{const ye=await Ye.current();Q||Rt(ye)}catch(ye){if(Q)return;Rt(null),J(ye instanceof Error?ye.message:"Failed to estimate gas fee")}finally{Q||Kt(!1)}};ce();const Fe=window.setInterval(()=>{ce()},1e4);return()=>{Q=!0,window.clearInterval(Fe)}},[e,pe,qe,je,Be]),G(()=>{je||Be||wt(null)},[je,Be,qe]);const kt=async()=>{if(Z.length===0||!Z[0]?.asset)return;const Q=Z.filter(dt=>dt.asset&&dt.amount&&parseFloat(dt.amount)>0);if(Q.length===0)return;const ce=Q[0],Fe=Me(ce.asset.chainId),ye=Q.map(dt=>{const Nn=parseFloat(dt.amount);return`${isNaN(Nn)?dt.amount:Nn.toPrecision(6).replace(/\.?0+$/,"")} ${dt.asset.symbol}`}).join(", "),ct={network:Fe?.displayName||`Chain ${ce.asset.chainId}`,amount:ye,symbol:"",chainId:ce.asset.chainId};if(!pe&&Q.length===1&&ze){wt(ze);const dt=Q[0];ct.creditedAmount=`${Xe(ze.net,dt.asset.decimals)} ${dt.asset.symbol}`,ct.networkFee=`${Xe(ze.fee,dt.asset.decimals)} ${dt.asset.symbol}`}Ct(ct),Tt(!0)},Ke=ee(ke);Ke.current=ke;const Qt=ee(Ie);Qt.current=Ie;const He=async()=>{await pc({selectedDepositAssets:Z,escrowOnly:k,sourceAddress:me,isNon7702:pe,address:fe,embeddedWalletAddress:ue,isReady:O,isAuthenticated:X,zeroCreditError:Ne,depositBalanceError:Vt,externalWalletClient:_,externalProvider:ae.current,effectiveDepositFee:ot,depositBatches:s,destinationChainId:m,destinationTokenAddress:h,isCrossDenomination:bt,convertedUsdAmount:he,mode:U,sponsorGas:b,nativeChainId:w,spiceBalanceUser:Re,depositDataRef:xe,bridgedAmountRef:an,setIsExecuting:rt,setError:Ae,setConfirmationData:Ct,setShowConfirmation:Tt,setDirectDepositStatus:zt,setDirectDepositChainId:yt,setDirectDepositTxHash:en,setPostDepositStatus:ge,setPostDepositError:Qe,setPostDepositAmount:Le,setPostDepositSuccess:Pt,startStatusPolling:Nt,clearStatus:tn,refreshAssets:Mt,onDepositExecute:g,onDepositSelect:o,onDepositSuccess:E,execution:{execute:it},getCurrentIntentStatus:()=>Ke.current,getCurrentPostDepositStatus:()=>Qt.current})},Ne=ne(()=>{for(const Q of Z)if(!(!Q?.asset||!Q.amount||parseFloat(Q.amount)<=0))try{const ce=Q.asset.decimals,Fe=Oe(Q.amount,ce);if(Fe<=0n)continue;const ye=Ti(ht(Q.asset.address)),ct=Q.asset.receiptTokenDecimals??(ye==="ETH"||ye==="ARB"?18:ye==="USDC"||ye==="SUSD"||ye==="WBTC"||ye==="CBTC"?6:void 0);if(ct===void 0||ce<=ct||io(Fe,ce,ct)>0n)continue;return`Amount too small. Minimum deposit for this asset is ${Xe(10n**BigInt(ce-ct),ce)} ${Q.asset.symbol}.`}catch{continue}return null},[Z]),nt=!pe&&!!ie,ot=Wt??ze,Zt=!!ie&&!!ot&&ot.chainId===ie.chainId&&Ee(ot.token,ie.token),Vt=ne(()=>{if(!nt||!ie||!Zt)return null;const Q=k?ie.amount:ie.amount+ot.fee;return ie.asset.balance>=Q?null:`Insufficient ${ie.asset.symbol}. Need ${Xe(Q,ie.asset.decimals)} ${ie.asset.symbol} including gas.`},[nt,ie,Zt,ot,k]),[qn,nn]=D(!1),hn=Z[0]?.asset?.chainId,Ht=Ge.find(Q=>Q.isNative&&Q.chainId===hn)?.balance??0n;G(()=>{if(!e||!hn){nn(!1);return}let Q=!1;return(async()=>{try{const ce=await pt(hn).getGasPrice()*150000n;Q||nn(Ht<ce)}catch{Q||nn(!1)}})(),()=>{Q=!0}},[e,hn,Ht]);const Dn=!nt||Zt&&!tt&&!V&&!Vt,Mn=te((Q,ce)=>hc({asset:Q,assetIndex:ce,selectedAssetCount:Z.length,address:fe,escrowOnly:k,isNon7702:pe}),[pe,Z.length,fe,k]),Yn=ne(()=>{if(!ie||!ot||!Zt)return null;const Q=k?ie.amount:ie.amount+ot.fee;return{symbol:ie.asset.symbol,decimals:ie.asset.decimals,grossAmount:Q,netAmount:ot.net,totalFee:ot.fee,gasFee:ot.fee,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"estimated"}},[ie,ot,Zt,k]),fn=parseFloat(Z[0]?.amount||"")||0,ro=fn>0&&fn<In,Kn=Z.length>0&&Z[0]?.asset&&Z[0]?.amount&&fn>0&&!ro&&Se&&!Be&&!Ne&&!Vt&&Dn&&!P;G(()=>{if(!k||!C||!B||et.current||!Se)return;const Q=r[0];if(!Q)return;const ce=ar(Q,[]).find(ye=>Ee(ye.address,C));let Fe;if(ce)Fe=ce;else if(A!==void 0&&F)Fe={address:C,symbol:F,name:F,decimals:A,chainId:Q,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,isNative:Ue(C)};else{console.warn("[DepositModal] escrowOnly: no matching asset and missing escrowTokenDecimals/escrowTokenSymbol for",C);return}et.current=!0,Te([{asset:Fe,amount:B}])},[k,C,B,A,F,Se,r]),G(()=>{!k||!Kn||xn.current||Be||(xn.current=!0,He())},[k,Kn,Be]);const Co=$t||ft||Ne||Vt,wo=()=>{if(Be)return"Executing Deposit...";if(!Se)return"Wallet Not Connected";if(U==="7702"){if(!O)return"Loading...";if(!X)return"Authentication Required"}return Z[0]?.asset?Z[0]?.amount?ro?`MINIMUM ${In}`:Ne?"AMOUNT TOO SMALL":Vt?"INSUFFICIENT BALANCE":nt&&!Dn?V?"GAS UNAVAILABLE":"ESTIMATING GAS":"DEPOSIT":"ENTER AMOUNT":"SELECT TOKEN"};return e?c(Cn,{isOpen:e,onClose:t,closeOnBackdropClick:n,title:a||`Deposit to your ${Y} account`,subtitle:x("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[c("img",{src:Ms,alt:"","aria-hidden":"true",style:{width:"13px",height:"13px",flexShrink:0,...H?{filter:"invert(0.6)"}:{}}}),c("p",{style:{fontSize:"12px",color:K.textSecondary,margin:"0",lineHeight:"1.4",fontFamily:ve.ui},children:`Deposit collateral to your ${Y} Account from any supported network.`})]}),dark:H,overlayContent:je||ke||Ie!=="idle"&&g?c("div",{}):void 0,styles:l,theme:N,children:x("div",{style:{padding:"24px 24px 5px 24px"},children:[c(mc,{selectedDepositAssets:Z,depositAssets:Ze,secondAssetOptions:de,loadingAssets:st,allowSecondAsset:f,theme:N,styles:l,dark:H,dk:K,onSelect:_e,onAmountChange:Ve,onAdd:Bt,onRemove:Yt,resolveMaxAmount:Mn,onViewAllAssets:v}),nt&&ie&&c(Fs,{fontFamily:l?.fontFamily||N.typography.fontFamily,textPrimary:K.textPrimary,textSecondary:K.textSecondary,cardBg:H?K.inputBg:"#ffffff",cardBorder:K.cardBorder,resolvedDark:H,darkCardBorder:K.cardBorder,primaryColor:j,feePreview:Yn,isLoading:tt||nt&&!Zt,errorText:V}),c(ac,{intentStatus:ke,postDepositSuccess:Lt,postDepositAmount:_t,postDepositStatus:Ie,depositActionLabel:y,sourceChainName:Z[0]?.asset?.chainId?cn(Z[0].asset.chainId):"Destination Chain",directDepositStatus:at,directDepositTxHash:jt,directDepositChainId:Je,styles:l}),c(rc,{isOpen:je||!!ke||Ie!=="idle"&&!!g,onClose:()=>{Tt(!1),ke&&tn();const Q=Ie==="success"&&!ke,ce=ke?.overallStatus==="success"&&(g?Ie==="success":!0);(Q||ce)&&t()},onConfirm:He,data:ln,isExecuting:Be,error:ft,theme:N,styles:l,intentStatus:ke,postDepositStatus:Ie,hasPostDepositInstruction:!!g}),xt&&x(Sr,{dk:K,dark:H,borderRadius:N.borderRadius.md,children:["\u26A1 ",xt]}),qn&&c(Sr,{dk:K,dark:H,borderRadius:N.borderRadius.md,children:"Low native balance in the external wallet. The deposit to spicenet account might fail."}),x("div",{style:{display:"flex",flexDirection:"column",gap:0,marginBottom:0,margin:0,padding:0},children:[Co?c("div",{style:{marginBottom:"10px",fontSize:"12px",lineHeight:"1.45",color:K.errorText,fontFamily:l?.fontFamily||N.typography.fontFamily},children:Co}):null,c(vt,{variant:"outline",fullWidth:!0,onClick:kt,disabled:!Kn||!Se||Be,theme:N,dark:H,styles:l,children:wo()})]})]})}):null}),gc=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,deposits:o,onComplete:s,onCancel:r,onSkip:a,onChangeWallet:l,isProcessing:d,error:i,styles:u})=>{const{dark:p,dk:f,theme:m}=ut(u);if(!e||o.length===0)return null;const h=o[0],g=u?.fontFamily||ve.ui,y=ve.mono,w=cn(h.chainId),b=parseFloat(h.amount).toPrecision(6).replace(/\.?0+$/,""),T=Xe(h.verifiedBalance,h.tokenDecimals);return c(Cn,{isOpen:e,onClose:t,title:"Incomplete Deposit",styles:u,closeOnBackdropClick:n,children:x("div",{style:{padding:"18px 24px 24px",fontFamily:g},children:[c("p",{style:{fontSize:"14px",color:f.textSecondary,lineHeight:"1.6",margin:"0 0 18px 0"},children:"Your funds reached your wallet, but the deposit didn't finish."}),x("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) auto",gap:"14px 18px",marginBottom:"24px",padding:"16px 18px",backgroundColor:p?f.cardBg:"#f8fafc",border:`1px solid ${f.cardBorder}`,borderRadius:p?"14px":"10px",boxShadow:p?"inset 0 1px 0 rgba(255,255,255,0.03)":"0 1px 2px rgba(16,24,40,0.04)"},children:[x("div",{style:{display:"flex",flexDirection:"column",gap:"4px"},children:[c("span",{style:{fontSize:"12px",fontWeight:600,color:f.textSecondary,fontFamily:y,letterSpacing:"0.8px"},children:"NETWORK"}),c("span",{style:{fontSize:"18px",fontWeight:600,color:f.textPrimary,fontFamily:g,lineHeight:1.2},children:w})]}),x("div",{style:{display:"flex",flexDirection:"column",gap:"4px",alignItems:"flex-end",textAlign:"right"},children:[c("span",{style:{fontSize:"12px",fontWeight:600,color:f.textSecondary,fontFamily:y,letterSpacing:"0.8px"},children:"DEPOSITED AMOUNT"}),x("span",{style:{fontSize:"24px",fontWeight:700,color:f.successText,fontFamily:y,lineHeight:1.1},children:[b," ",h.tokenSymbol]}),c("span",{style:{fontSize:"12px",color:f.textSecondary,fontWeight:500,fontFamily:g},children:"Sent to embedded wallet"})]})]}),!h.hasFullBalance&&h.verifiedBalance>0n&&x("div",{style:{marginBottom:"16px",padding:"8px 12px",backgroundColor:f.warningBg,border:`1px solid ${p?f.warningBorder:"#fcd34d"}`,borderRadius:"8px",fontSize:"13px",color:f.warningText,lineHeight:"1.4"},children:["Partial balance \u2014 only ",parseFloat(T).toFixed(4)," ",h.tokenSymbol," available."]}),i&&c("div",{style:{marginBottom:"16px",padding:"10px 12px",backgroundColor:f.errorBg,border:`1px solid ${p?f.errorBorder:"#fca5a5"}`,borderRadius:"8px",fontSize:"13px",color:p?f.errorText:"#991b1b",lineHeight:"1.4"},children:i}),x("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[c(vt,{variant:"outline",fullWidth:!0,disabled:d,onClick:()=>s(h),theme:m,dark:p,styles:u,children:"CONFIRM DEPOSIT"}),x("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:[c(vt,{variant:"ghost",fullWidth:!0,disabled:d,onClick:()=>r(h),theme:m,dark:p,style:{height:"48px",fontSize:"13px",letterSpacing:"0.4px",color:p?f.textPrimary:"#374151",border:`1px solid ${p?f.cardBorder:"#d1d5db"}`,borderRadius:"12px",backgroundColor:p?"rgba(255,255,255,0.02)":"#ffffff"},children:d?"RETURNING...":"RETURN FUNDS"}),x("div",{style:{display:"grid",gridTemplateColumns:l?"1fr 1fr":"1fr",gap:"10px"},children:[c(vt,{variant:"ghost",fullWidth:!0,disabled:d,onClick:a,theme:m,dark:p,style:{height:"44px",fontSize:"12px",letterSpacing:"0.4px",color:f.textSecondary,border:`1px solid ${p?f.cardBorder:"#d1d5db"}`,borderRadius:"12px",backgroundColor:"transparent"},children:"START OVER"}),l&&c(vt,{variant:"ghost",fullWidth:!0,disabled:d,onClick:l,theme:m,dark:p,style:{height:"44px",fontSize:"12px",letterSpacing:"0.4px",color:f.textSecondary,border:`1px solid ${p?f.cardBorder:"#d1d5db"}`,borderRadius:"12px",backgroundColor:"transparent"},children:"CHANGE WALLET"})]})]})]}),o.length>1&&x("p",{style:{fontSize:"12px",color:f.textSecondary,textAlign:"center",marginTop:"14px",marginBottom:0,lineHeight:"1.5"},children:[o.length," incomplete deposits found \u2014 resolving one at a time."]})]})})},Ns=e=>{const[t,n]=D(!1),o=qt(Ut),{dark:s,dk:r}=ut();if(G(()=>{n(!0)},[]),!t)return c("div",{className:e.className,children:c("button",{disabled:!0,style:{padding:"12px 24px",fontSize:"16px",backgroundColor:s?r.hoverBg:"#ccc",color:s?r.textSecondary:"white",border:s?`1px solid ${r.buttonBorder}`:"none",borderRadius:"4px",cursor:"not-allowed"},children:"Loading..."})});if(!o){const a='ProviderLogin must be used within SpiceFlowProvider. Please wrap your app with <SpiceFlowProvider provider="privy">.';return c("div",{className:e.className,children:c("button",{onClick:()=>{e.onAuthError&&e.onAuthError(a)},style:{padding:"12px 24px",fontSize:"16px",backgroundColor:s?r.errorBg:"#dc2626",color:s?r.errorText:"white",border:s?`1px solid ${r.errorBorder}`:"none",borderRadius:"4px",cursor:"pointer"},children:"Provider Not Found"})})}return c(mi,{...e})},yc=.01,xc=5*60*1e3;function bc(e){const t=Number(Xe(e.verifiedBalance,e.tokenDecimals));return Number.isFinite(t)?t:0}async function Cc(e){const t=wc(e);let n;try{n=await gs(t.map(o=>o.tokenSymbol))}catch{return t}return t.filter(o=>{const s=bc(o);if(s<=0)return!0;const r=n[o.tokenSymbol.toUpperCase()]??0;return!Number.isFinite(r)||r<=0?!0:s*r>=yc})}function wc(e){const t=new Map;for(const n of e){const o=`${n.chainId}:${n.tokenAddress.toLowerCase()}`;t.get(o)||t.set(o,{...n,amount:n.timestamp===0?Xe(n.verifiedBalance,n.tokenDecimals):n.amount,rawAmount:n.timestamp===0?n.verifiedBalance.toString():n.rawAmount,hasFullBalance:n.timestamp===0?!0:n.hasFullBalance})}return Array.from(t.values())}function ea(e,t){const[n,o]=D([]),[s,r]=D(!1),a=ee(t);a.current=t;const l=ee(0),d=ee(0),i=te(async({forceDiscovery:u=!1}={})=>{if(!e){o([]),r(!1);return}const p=++d.current,f=()=>p!==d.current;r(!0);try{const m=[],h=cc(e);for(const b of h){if(f())return;try{const T=pt(b.chainId);let k;if(b.isNative||Ue(b.tokenAddress)?k=await ss(T,{address:e}):k=await En(T,{address:lt(b.tokenAddress),abi:We,functionName:"balanceOf",args:[e]}),f())return;k>0n?m.push({...b,verifiedBalance:k,hasFullBalance:k>=BigInt(b.rawAmount)}):Date.now()-b.timestamp>15*60*1e3&&Ws(e,b.chainId,b.tokenAddress)}catch(T){console.warn(`[usePendingDeposit] Failed to verify balance for ${b.tokenSymbol} on chain ${b.chainId}:`,T),m.push({...b,verifiedBalance:0n,hasFullBalance:!1})}}if(f())return;const g=a.current,y=Date.now(),w=(g?.discoverWalletBalances??!0)&&(u||y-l.current>=xc);if(g?.network&&w){l.current=y;const b=g.chainIds??Fo(g.network),T=new Set(m.map(C=>`${C.chainId}:${C.tokenAddress.toLowerCase()}`)),k=[];for(const C of b){const B=Me(C);if(B?.supportedTokens)for(const A of B.supportedTokens){if(Ue(A.address))continue;const F=`${C}:${A.address.toLowerCase()}`;T.has(F)||k.push((async()=>{try{const E=pt(C),I=await En(E,{address:lt(A.address),abi:We,functionName:"balanceOf",args:[e]});return I>0n?{chainId:C,tokenAddress:A.address,tokenSymbol:A.symbol,tokenDecimals:A.decimals,amount:Xe(I,A.decimals),rawAmount:I.toString(),embeddedWalletAddress:e,externalWalletAddress:"",timestamp:0,isNative:!1,verifiedBalance:I,hasFullBalance:!0}:null}catch{return null}})())}}if(k.length>0){const C=await Promise.allSettled(k);if(f())return;for(const B of C)B.status==="fulfilled"&&B.value&&m.push(B.value)}}if(!f()){const b=await Cc(m);if(f())return;o(b)}}catch(m){console.error("[usePendingDeposit] Verification error:",m),f()||o([])}finally{f()||r(!1)}},[e]);return G(()=>{if(!a.current?.enabled){d.current++,o([]),r(!1);return}i({forceDiscovery:!0});const u=a.current?.pollIntervalMs??3e4;if(u<=0||!e)return()=>{d.current++};const p=setInterval(()=>{i({forceDiscovery:!1})},u),f=()=>i({forceDiscovery:!0});return window.addEventListener(jo,f),()=>{d.current++,window.removeEventListener(jo,f),clearInterval(p)}},[i,e]),{pendingDeposits:n,loading:s,refresh:()=>i({forceDiscovery:!0})}}function kc(e,t,n,o,s){return{address:t,symbol:n||"UNKNOWN",name:n||"Unknown Token",decimals:o||18,chainId:e,balance:0n,balanceFormatted:s?parseFloat(s):0,balanceUsd:0,isNative:Ue(t)}}const vc=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,styles:o,depositBatches:s,onDepositAmountChange:r,destinationChainId:a,destinationTokenAddress:l,onDepositExecute:d,depositActionLabel:i,sponsorGas:u=!1,escrowRecovery:p,skipTokenSelection:f=!1,onDepositSuccess:m,onDepositError:h,skipRecovery:g=!1})=>{const y=qt(Ut);if(!y)return c("div",{children:"Error: SpiceDeposit must be used within SpiceFlowProvider"});const w=(y.mode||"7702")!="7702",b=w,T=y.nativeChainId,k=y.network||"testnet",{dark:C,dk:B}=ut(o),A=!!p,F=bn(),{isReady:E,isAuthenticated:I,actions:S}=F,v=y?.embeddedWalletAddress,{address:R}=ts(),U=y?.externalWalletAddress??R,W=!!U,z=()=>f?"deposit":"select-token",P=()=>b?W?z():"connect-wallet":"provider-login",[M,N]=D(P()),[H,Y]=D(null),[j,K]=D(!1),{pendingDeposits:be,loading:O,refresh:X}=ea(v,{enabled:e,network:k,chainIds:y.supportedChainIds}),[re,ue]=D(null),[pe,Se]=D(!1),[fe,me]=D(null),[Re,L]=D(!1),[_,oe]=D("idle");G(()=>{e&&!g&&!A&&!re&&!Re&&_==="idle"&&I&&v&&W&&U&&!O&&be.length>0&&M!=="recovery"&&M!=="deposit"&&N("recovery")},[e,g,A,I,v,W,U,O,be,M,re,Re,_]);const ae=te(de=>{const Be={address:de.tokenAddress,symbol:de.tokenSymbol,name:de.tokenSymbol,decimals:de.tokenDecimals,chainId:de.chainId,balance:de.verifiedBalance,balanceFormatted:parseFloat(de.amount),balanceUsd:0,isNative:de.isNative};Y(Be),ue(de),N("deposit")},[]),q=te(()=>{L(!0),N(I&&v&&W&&U?f?"deposit":"select-token":I&&v?"connect-wallet":"provider-login")},[I,v,W,U,f]),se=te(()=>{me(null),oe("awaiting-disconnect"),N("connect-wallet")},[]),xe=te(async de=>{Se(!0),me(null);try{if(!v)throw new Error("Embedded wallet not available");const Be=await S.getEthereumProvider(),rt=Me(de.chainId);await sr(Be,de.chainId);const ft=pt(de.chainId),le=await ss(ft,{address:v}),gt=rt?.viemChain?.name||`chain ${de.chainId}`;if(le===0n)throw new Error(`Your embedded wallet has no ETH on ${gt} to pay for gas. We recommend completing the deposit instead \u2014 it doesn't require gas.`);const Ae=ns({account:v,transport:os(Be),chain:rt?.viemChain}),Ie=de.externalWalletAddress&&Gt(de.externalWalletAddress)?de.externalWalletAddress:U;if(!Ie||!Gt(Ie))throw new Error("Connect the external wallet that should receive these funds, then try again.");let ge;de.isNative||Ue(de.tokenAddress)?ge=await Ae.sendTransaction({to:Ie,value:de.verifiedBalance,chain:rt?.viemChain}):ge=await Ae.sendTransaction({to:de.tokenAddress,data:St({abi:We,functionName:"transfer",args:[Ie,de.verifiedBalance]}),chain:rt?.viemChain}),await ft.waitForTransactionReceipt({hash:ge,confirmations:1}),Ws(de.embeddedWalletAddress,de.chainId,de.tokenAddress),X(),be.length<=1&&N(P())}catch(Be){const rt=Be?.message||"Couldn't return your funds. Please try again.",ft=/insufficient funds for gas/i.test(rt);me(ft?"Not enough ETH in your embedded wallet to cover gas fees. Complete the deposit instead \u2014 it doesn't require gas.":rt)}finally{Se(!1)}},[S,v,U,be,X]);G(()=>{e||(ue(null),me(null),Se(!1),L(!1),oe("idle"))},[e]),G(()=>{if(_!=="idle"){if(_==="awaiting-disconnect"){(!W||!U)&&oe("awaiting-reconnect");return}e&&!O&&be.length>0&&I&&v&&(oe("idle"),N("recovery"))}},[_,W,U,e,O,be,I,v]),G(()=>{!A||!e||(I&&v?(K(!0),!H&&p?.chainId&&p?.tokenAddress&&Y(kc(p.chainId,p.tokenAddress,p.tokenSymbol,p.tokenDecimals,p.amount)),N("deposit")):N("provider-login"))},[A,e,M,I,v]);const{assets:Z,loading:Te}=ds({address:U,supportedChains:y.supportedChainIds,fetchBalances:cs,enabled:e&&!!U,refreshInterval:e?5e3:0}),Ge=te(()=>{K(!0),N(A?"deposit":W?f?"deposit":"select-token":"connect-wallet")},[A,W,f]),st=te(async()=>{if((!W||!U)&&(await wn(500),!W||!U)){alert("Please connect your wallet first");return}N(f?"deposit":"select-token")},[W,U,f]),$t=te(de=>{Y(de),N("deposit")},[]),Mt=te(()=>{if(Y(null),r?.(""),!U){N("connect-wallet");return}N("select-token")},[U,r]),Ze=te(()=>{t()},[t]);if(G(()=>{if(!e){const de=setTimeout(()=>{A||(N(P()),Y(null)),K(!1)},300);return()=>clearTimeout(de)}},[e,A,p?.chainId]),G(()=>{e&&M==="deposit"&&!H&&!A&&!re&&!f&&N("select-token")},[e,M,H,A,re,f]),G(()=>{e&&M==="connect-wallet"&&W&&U&&_==="idle"&&N(f?"deposit":"select-token")},[e,M,W,U,_,f]),G(()=>{if(!b&&e&&M==="provider-login"&&E&&I&&v&&!j){const de=setTimeout(()=>{K(!0),N(W?f?"deposit":"select-token":"connect-wallet")},100);return()=>clearTimeout(de)}},[b,e,M,E,I,v,W,f,j]),!e)return null;if(M==="recovery")return c(gc,{isOpen:e,onClose:Ze,closeOnBackdropClick:n,deposits:be,onComplete:ae,onCancel:xe,onSkip:q,onChangeWallet:se,isProcessing:pe,error:fe,styles:o});if(M==="provider-login"&&!b)return c("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.5)",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",zIndex:50},children:c("div",{style:{backgroundColor:C?B.cardBg:"white",borderRadius:"9px",padding:"32px 24px",maxWidth:"400px",width:"100%"},children:c(Ns,{onAuthSuccess:Ge,autoTrigger:!0})})});if(M==="connect-wallet")return c(kl,{isOpen:e,onClose:Ze,closeOnBackdropClick:n,onContinue:st,requiredChainId:w?T:void 0,styles:o});if(M==="select-token")return U?c(bl,{isOpen:e,onClose:Ze,closeOnBackdropClick:n,onTokenSelect:$t,walletAddress:U,supportedChainIds:y.supportedChainIds,network:k,prefetchedAssets:Te?null:Z??null,styles:o,dark:C}):(N("connect-wallet"),null);if(M==="deposit"){if(!H&&!f)return null;const de=!!re;return c(_r,{isOpen:e,onClose:Ze,closeOnBackdropClick:n,supportedChains:H?[H.chainId]:y.supportedChainIds??[],styles:o,externalWalletAddress:U,depositBatches:de?void 0:s,onDepositAmountChange:r,destinationChainId:a,destinationTokenAddress:l,onDepositExecute:d,depositActionLabel:i,nativeChainId:T,sponsorGas:u,preSelectedAsset:H??void 0,escrowOnly:A||de,escrowTokenAddress:de?re.tokenAddress:p?.tokenAddress,escrowAmount:de?re.amount:p?.amount,escrowTokenDecimals:de?re.tokenDecimals:p?.tokenDecimals,escrowTokenSymbol:de?re.tokenSymbol:p?.tokenSymbol,onDepositSuccess:m,onDepositError:h,embeddedWalletAddress:v,onViewAllAssets:f?void 0:Mt})}return null},Ic=e=>qt(Ut)?c(vc,{...e}):c("div",{children:"Error: SpiceDeposit must be used within SpiceFlowProvider"}),Ac=({isOpen:e,onClose:t,onChainSelect:n,supportedChains:o,closeOnSelect:s=!0,styles:r})=>{const{theme:a,dark:l,primaryColor:d,dk:i}=ut(r),[u,p]=D(""),[f,m]=D(null),[h,g]=D(null),[y,w]=D(!1),[b,T]=D(null),{switchChainAsync:k}=ir(),C=ne(()=>new Set(o||[]),[o]),B=ne(()=>{if(!o||o.length===0)return[];const I=[];return o.forEach((S,v)=>{if(typeof S!="number")return;const R=Me(S);R&&I.push({id:S.toString(),name:R.displayName,icon:Fn[S]||co,chainId:S,verified:!0,order:v})}),I},[o]);G(()=>{f&&!C.has(parseInt(f,10))&&m(null)},[f,C]);const A=ne(()=>B.filter(I=>I.name.toLowerCase().includes(u.toLowerCase())).sort((I,S)=>I.order-S.order),[B,u]),F=async()=>{if(!f)return;const I=parseInt(f,10);w(!0),T(null);try{await k({chainId:I}),n&&n(f),s&&t()}catch(S){console.error("Failed to switch chain:",S),T(un(S,"Failed to switch chain."))}finally{w(!1)}},E=!f||y;return x(Cn,{isOpen:e,onClose:t,title:"Select Chain",styles:r,theme:a,dark:l,children:[c("div",{style:{padding:"24px 20px"},children:c(is,{value:u,onChange:p,ariaLabel:"Search chains",placeholder:"Search chain name, symbol or address",size:"md",dark:l,styles:r,endAdornment:c("div",{style:{padding:"5px 5px",borderRadius:"3px",fontSize:"13px",backgroundColor:l?i.cardBg:"#E9E9E9",color:l?i.textSecondary:"#485066",fontWeight:500,flexShrink:0},"aria-hidden":"true",children:"\u2318F"})})}),c("div",{style:{padding:"0 32px 20px",display:"flex",flexDirection:"column",gap:"12px"},children:A.map(I=>{const S=f===I.id,v=h===I.id;return x("button",{onClick:()=>m(I.id),onMouseEnter:()=>g(I.id),onMouseLeave:()=>g(null),style:{width:"100%",display:"flex",alignItems:"center",gap:"16px",padding:"8px",borderRadius:"8px",backgroundColor:S?l?`${d}15`:`${d}12`:"transparent",border:S?l?`1px solid ${d}66`:`1px solid ${d}88`:v?l?`1px solid ${d}44`:`1px solid ${d}66`:"1px solid transparent",cursor:"pointer",transition:dn.interactive},children:[c("div",{style:{width:"40px",height:"40px",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"30px"},children:c("img",{src:I.icon,alt:I.name,loading:"lazy",decoding:"async",style:{width:"100%",height:"100%",borderRadius:"50%"}})}),x("div",{style:{display:"flex",alignItems:"center",gap:"6px",flex:1},children:[c("span",{style:{fontFamily:ve.mono,fontSize:"17px",fontWeight:500,letterSpacing:"0.4px",color:i.textPrimary,textAlign:"left"},children:I.name}),I.verified&&c("img",{src:vr,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",width:16,height:16,style:{width:"16px",height:"16px",filter:l?"brightness(0) invert(1)":"none"}})]})]},I.id)})}),b&&c("div",{style:{padding:"0 25px 12px"},children:c(Qn,{variant:"error",size:"compact",palette:i,children:b})}),c("div",{style:{padding:"0 25px 25px"},children:x(vt,{variant:"outline",onClick:F,disabled:E,fullWidth:!0,theme:a,styles:r,dark:l,children:["SELECT",c(Vi,{size:20})]})})]})},ta=({isSuccess:e,type:t,chainName:n,explorerUrl:o,txHash:s,dark:r=!1,successBg:a="#d1fae5",successBorder:l="#6ee7b7",successText:d="#065f46",errorBg:i="#fee2e2",errorBorder:u="#fca5a5",errorText:p="#dc2626",textSecondary:f="#6b7280"})=>x("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px",borderRadius:"8px",backgroundColor:e?a:i,border:e?`1px solid ${l}`:`1px solid ${u}`},children:[x("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[c("div",{style:{width:"28px",height:"28px",borderRadius:"50%",backgroundColor:e?"#10b981":"#ef4444",display:"flex",alignItems:"center",justifyContent:"center"},children:e?c("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:c("path",{d:"M11.6667 3.5L5.25 9.91667L2.33333 7",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}):c("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:c("path",{d:"M10.5 3.5L3.5 10.5M3.5 3.5L10.5 10.5",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),x("div",{children:[c("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:ve.mono,letterSpacing:"0.5px",color:e?d:p},children:e?`${t.toUpperCase()} CONFIRMED`:`${t.toUpperCase()} FAILED`}),x("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:f},children:["on ",n]})]})]}),o&&s&&x("a",{href:`${o}/tx/${s}`,target:"_blank",rel:"noopener noreferrer",style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"13px",color:f,textDecoration:"none",whiteSpace:"nowrap"},children:["View on explorer",x("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:[c("path",{d:"M9 6.5V9.5C9 9.76522 8.89464 10.0196 8.70711 10.2071C8.51957 10.3946 8.26522 10.5 8 10.5H2.5C2.23478 10.5 1.98043 10.3946 1.79289 10.2071C1.60536 10.0196 1.5 9.76522 1.5 9.5V4C1.5 3.73478 1.60536 3.48043 1.79289 3.29289C1.98043 3.10536 2.23478 3 2.5 3H5.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),c("path",{d:"M7.5 1.5H10.5V4.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),c("path",{d:"M5 7L10.5 1.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})]})]})]}),na=`
|
|
31
31
|
@keyframes slideUp {
|
|
32
32
|
from { transform: translateY(100%); }
|
|
33
33
|
to { transform: translateY(0); }
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@spicenet-io/spiceflow-ui",
|
|
3
|
-
"version": "4.1.
|
|
3
|
+
"version": "4.1.8",
|
|
4
4
|
"description": "Spiceflow UI SDK",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"packageManager": "bun@1.3.13",
|
|
@@ -54,7 +54,7 @@
|
|
|
54
54
|
"author": "",
|
|
55
55
|
"license": "MIT",
|
|
56
56
|
"dependencies": {
|
|
57
|
-
"@spicenet-io/spiceflow-core": "^0.5.
|
|
57
|
+
"@spicenet-io/spiceflow-core": "^0.5.1",
|
|
58
58
|
"tslib": "2.8.1"
|
|
59
59
|
},
|
|
60
60
|
"peerDependencies": {
|