@spicenet-io/spiceflow-ui 4.1.3 → 4.1.5
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 +4 -4
- package/dist/index.js +5 -5
- package/package.json +1 -1
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,ue=ce,pe=f,Ee=ue??pe,{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||!pe){oe.current=null,te(L);return}if(q.address?.toLowerCase()!==pe?.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:pe,chain:$e.viemChain,transport:D.custom(ie)}):_e)}).catch(()=>{oe.current=null,te(L)})},[ne,pe,L]);const ge=l.useRef(null),[G,Ie]=l.useState([]),{assets:ze,loading:Ze,error:Ft,refreshAssets:ht}=ls({address:v?ue:pe||ue,supportedChains:a,fetchBalances:is,enabled:e,refreshInterval:e?5e3:0}),Ue=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 Ue.filter(ie=>ie.chainId===q)},[Ue,G]),[Ae,Ke]=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,fe]=l.useState("idle"),De=l.useCallback(q=>{typeof q=="string"&&q&&nt.current?.(q,p.getRelayerErrorDetail(q))},[]),[gt,xt]=l.useState(!1),[Bt,Fe]=l.useState(null),[Xe,yt]=l.useState("idle"),[kt,Tt]=l.useState(null),[Oe,st]=l.useState(null),[Mt,Ct]=l.useState(null),[he,He]=l.useState(null),[ot,ct]=l.useState(null),{intentStatus:be,startStatusPolling:mt,clearStatus:Rt,execute:Ge}=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=Ue.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})},[Ue,G.length]),l.useEffect(()=>{if(!R||G.length>0||Ue.length===0)return;const q=Ue.find(ie=>ie.chainId===R.chainId&&p.addressesEqual(ie.address,R.address));q&&(Ie([{asset:q,amount:""}]),u?.(q))},[R,Ue,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{fe("executing"),await y(q),fe("success"),Fe(q),xt(!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),fe("error"),De(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||(xt(!1),Fe(null),yt("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]),Me=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||Ct(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,pt(null),it(null))},[e]);const[Le,bt]=l.useState(!1),[Nt,at]=l.useState(null),[Te,pt]=l.useState(null),[ft,it]=l.useState(null),[Je,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]),We=l.useMemo(()=>re?[re.chainId,re.token.toLowerCase(),re.amount.toString(),v?"escrow":"normal"].join("|"):null,[re,v]),_=l.useCallback(async q=>ue?No({address:ue,depositQuote:q,escrowOnly:v}):null,[ue,v]),Ce=l.useCallback(async()=>re?_(re):null,[re,_]),Ne=l.useRef(Ce);Ne.current=Ce,l.useEffect(()=>{let q=!1;if(!e||de||!We||Le||Ae){pt(null),$(null),It(!1);return}const ie=async()=>{$(null),It(!0);try{const me=await Ne.current();q||pt(me)}catch(me){if(q)return;pt(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,We,Le,Ae]),l.useEffect(()=>{Le||Ae||it(null)},[Le,Ae,We]);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),bt(!0)},Pe=l.useRef(be);Pe.current=be;const vt=l.useRef(we);vt.current=we;const Re=async()=>{await Ii({selectedDepositAssets:G,escrowOnly:v,sourceAddress:pe,isNon7702:de,address:ue,embeddedWalletAddress:ce,isReady:H,isAuthenticated:J,zeroCreditError:je,depositBalanceError:St,externalWalletClient:ee,externalProvider:oe.current,effectiveDepositFee:Ye,depositBatches:r,destinationChainId:x,destinationTokenAddress:m,isCrossDenomination:rt,convertedUsdAmount:he,mode:U,sponsorGas:b,nativeChainId:k,spiceBalanceUser:Ee,depositDataRef:ge,bridgedAmountRef:Wt,setIsExecuting:Ke,setError:ke,setConfirmationData:at,setShowConfirmation:bt,setDirectDepositStatus:yt,setDirectDepositChainId:st,setDirectDepositTxHash:Tt,setPostDepositStatus:fe,setPostDepositError:De,setPostDepositAmount:Fe,setPostDepositSuccess:xt,startStatusPolling:mt,clearStatus:Rt,refreshAssets:ht,onDepositExecute:y,onDepositSelect:s,onDepositSuccess:j,execution:{execute:Ge},getCurrentIntentStatus:()=>Pe.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]),qe=!de&&!!re,Ye=ft??Te,Et=!!re&&!!Ye&&Ye.chainId===re.chainId&&p.addressesEqual(Ye.token,re.token),St=l.useMemo(()=>{if(!qe||!re||!Et)return null;const q=v?re.amount:re.amount+Ye.fee;return re.asset.balance>=q?null:`Insufficient ${re.asset.symbol}. Need ${D.formatUnits(q,re.asset.decimals)} ${re.asset.symbol} including gas.`},[qe,re,Et,Ye,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=!qe||Et&&!Je&&!Y&&!St,nn=l.useCallback((q,ie)=>Ei({asset:q,assetIndex:ie,selectedAssetCount:G.length,address:ue,escrowOnly:v,isNon7702:de}),[de,G.length,ue,v]),dn=l.useMemo(()=>{if(!re||!Ye||!Et)return null;const q=v?re.amount:re.amount+Ye.fee;return{symbol:re.asset.symbol,decimals:re.asset.decimals,grossAmount:q,netAmount:Ye.net,totalFee:Ye.fee,gasFee:Ye.fee,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"estimated"}},[re,Ye,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":qe&&!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:Le||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:Ue,secondAssetOptions:le,loadingAssets:Ze,allowSecondAsset:g,theme:P,styles:d,dark:Q,dk:X,onSelect:Qe,onAmountChange:Me,onAdd:ut,onRemove:At,resolveMaxAmount:nn,onViewAllAssets:S}),qe&&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:Je||qe&&!Et,errorText:Y}),o.jsx(bi,{intentStatus:be,postDepositSuccess:gt,postDepositAmount:Bt,postDepositStatus:we,depositActionLabel:C,sourceChainName:G[0]?.asset?.chainId?p.getChainName(G[0].asset.chainId):"Destination Chain",directDepositStatus:Xe,directDepositTxHash:kt,directDepositChainId:Oe,styles:d}),o.jsx(Ci,{isOpen:Le||!!be||we!=="idle"&&!!y,onClose:()=>{bt(!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),[ue,pe]=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(()=>{pe(null),te("awaiting-disconnect"),P("connect-wallet")},[]),ge=l.useCallback(async le=>{ve(!0),pe(null);try{if(!S)throw new Error("Embedded wallet not available");const Ae=await E.getEthereumProvider(),Ke=p.getChainConfig(le.chainId);await p.ensureWalletOnChain(Ae,le.chainId);const et=p.getClientForChain(le.chainId),ae=await Pt.getBalance(et,{address:S}),nt=Ke?.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:Ke?.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 fe;le.isNative||B.isNativeToken(le.tokenAddress)?fe=await ke.sendTransaction({to:we,value:le.verifiedBalance,chain:Ke?.viemChain}):fe=await ke.sendTransaction({to:le.tokenAddress,data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"transfer",args:[we,le.verifiedBalance]}),chain:Ke?.viemChain}),await et.waitForTransactionReceipt({hash:fe,confirmations:1}),Bs(le.embeddedWalletAddress,le.chainId,le.tokenAddress),J(),xe.length<=1&&P(z())}catch(Ae){const Ke=Ae?.message||"Couldn't return your funds. Please try again.",et=/insufficient funds for gas/i.test(Ke);pe(et?"Not enough ETH in your embedded wallet to cover gas fees. Complete the deposit instead \u2014 it doesn't require gas.":Ke)}finally{ve(!1)}},[E,S,U,xe,J]);l.useEffect(()=>{e||(ce(null),pe(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]),Ze=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")},[]),ht=l.useCallback(()=>{if(K(null),a?.(""),!U){P("connect-wallet");return}P("select-token")},[U,a]),Ue=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:Ue,closeOnBackdropClick:n,deposits:xe,onComplete:oe,onCancel:ge,onSkip:Z,onChangeWallet:ne,isProcessing:de,error:ue,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:Ue,closeOnBackdropClick:n,onContinue:Ze,requiredChainId:k?R:void 0,styles:s});if(N==="select-token")return U?o.jsx(Da,{isOpen:e,onClose:Ue,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:Ue,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:ht})}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,ue=ce,pe=f,Ee=ue??pe,{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||!pe){oe.current=null,te(L);return}if(q.address?.toLowerCase()!==pe?.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:pe,chain:$e.viemChain,transport:D.custom(ie)}):_e)}).catch(()=>{oe.current=null,te(L)})},[ne,pe,L]);const ge=l.useRef(null),[G,Ie]=l.useState([]),{assets:ze,loading:Ke,error:Ft,refreshAssets:mt}=ls({address:v?ue:pe||ue,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,fe]=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),[he,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{fe("executing"),await y(q),fe("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),fe("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=>ue?No({address:ue,depositQuote:q,escrowOnly:v}):null,[ue,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:pe,isNon7702:de,address:ue,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:he,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:fe,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:ue,escrowOnly:v,isNon7702:de}),[de,G.length,ue,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),[ue,pe]=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(()=>{pe(null),te("awaiting-disconnect"),P("connect-wallet")},[]),ge=l.useCallback(async le=>{ve(!0),pe(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 fe;le.isNative||B.isNativeToken(le.tokenAddress)?fe=await ke.sendTransaction({to:we,value:le.verifiedBalance,chain:Xe?.viemChain}):fe=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:fe,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);pe(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),pe(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:ue,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); }
|
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
from { opacity: 0; transform: translateY(4px); }
|
|
41
41
|
to { opacity: 1; transform: translateY(0); }
|
|
42
42
|
}
|
|
43
|
-
`,Oo=({title:e,showChevron:t,expanded:n,onToggleDetails:s,showClose:r,onClose:a,fontFamily:i,labelColor:d,textPrimary:u,closeHoverBg:c,closePressedBg:f})=>{const[h,g]=l.useState(!1),[x,m]=l.useState(!1);return o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"16px"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:s?"pointer":"default"},onClick:s,children:[o.jsxs("span",{style:{fontSize:"13px",fontWeight:500,color:d,fontFamily:i},children:[e," "]}),t&&o.jsx(on,{color:d,direction:n?"up":"down"})]}),r&&o.jsx("button",{onClick:a,onMouseEnter:()=>g(!0),onMouseLeave:()=>{g(!1),m(!1)},onMouseDown:()=>m(!0),onMouseUp:()=>m(!1),style:{background:x?f:h?c:"none",border:"none",borderRadius:"4px",cursor:"pointer",padding:"4px",display:"flex",alignItems:"center",justifyContent:"center",color:h||x?u:d,transform:x?"scale(0.9)":h?"scale(1.1)":"scale(1)",transition:p.transition.interactive},children:o.jsx(Sn,{size:16})})]})},Ho=({chainName:e,bg:t,border:n,textPrimary:s,labelColor:r,primaryColor:a})=>o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"20px 16px",borderRadius:"8px",backgroundColor:t,border:`1px solid ${n}`,gap:"12px"},children:[o.jsx(p.Spinner,{size:24,borderWidth:3,color:a}),o.jsxs("div",{children:[o.jsx("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:p.font.mono,letterSpacing:"0.5px",color:s},children:"PROCESSING TRANSACTION"}),o.jsxs("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:r},children:["on ",e]})]})]}),Qo=({bg:e,border:t,left:n,right:s})=>o.jsxs("div",{style:{padding:"10px 12px",borderRadius:"6px",backgroundColor:e,border:`1px solid ${t}`,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[n,s]}),Ms=({isOpen:e,onClose:t,onComplete:n,closeOnComplete:s=!1,type:r,results:a,chainId:i,chainName:d,explorerUrl:u,theme:c,styles:f,dark:h,intentStatus:g,onRetry:x,onNewTx:m,onRetryTx:y,asOverlay:C=!0,isProcessing:k=!1,showStepBreakdown:b=!0})=>{const{theme:R,primaryColor:v,dark:w,dk:T}=p.useSpiceBrand(f,h),I=c||R,[F,j]=l.useState(!1),A=d??(i?p.getChainName(i):"Network"),E=u??(i&&p.getExplorerUrl(i,"").replace(/\/tx\/.*$/,"")||void 0),S=w?T.cardBg:"#ffffff",M=w?"0 4px 20px rgba(0, 0, 0, 0.4)":"0 4px 20px rgba(0, 0, 0, 0.1)",U=w?"0 -4px 8px -2px rgba(0, 0, 0, 0.4)":"0 -4px 8px -2px rgba(0, 0, 0, 0.15)",W=T.textSecondary,O=w?T.textPrimary:"#374151",z=w?T.inputBg:"#f9fafb",N=w?T.inputBorder:"#e5e7eb",P=w?T.inputBg:"#f3f4f6",Q=w?T.inputBorder:"#e5e7eb",[K,V]=l.useState(!0),X=w?T.inputBg:"#f9fafb",xe=w?T.hoverBg:"#f3f4f6",H=w?{successBg:T.successBg,successBorder:T.successBorder,successText:T.successText,errorBg:T.errorBg,errorBorder:T.errorBorder,errorText:T.errorText}:{},J=g?.steps.find(pe=>pe.status==="failed")?.error;l.useEffect(()=>{!e&&!g&&j(!1)},[e,g]);const se=()=>{j(!0),setTimeout(()=>{window.dispatchEvent(new CustomEvent("tx-complete",{detail:{type:r,results:a}})),window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:{type:r,status:"success",results:a}})),n?.(),s&&t()},300)},ce=()=>{V(!K)};if(g){const{steps:pe,overallStatus:Ee}=g,L=Ee==="processing",ee=Ee==="success",te=Ee==="failed",oe=pe.filter(G=>G.transactionHash)[0],Z=pe.length>1?pe.map(G=>G.chainName).filter(Boolean).join(" and "):A!=="Network"?A:pe[0]?.chainName||A,ne=E||(oe?p.getExplorerUrl(oe.chainId,oe.transactionHash||"").replace(/\/tx\/.*$/,""):void 0),ge=o.jsxs(o.Fragment,{children:[o.jsx(Oo,{title:L?`Processing ${r.charAt(0).toUpperCase()+r.slice(1)}`:`${r.charAt(0).toUpperCase()+r.slice(1)} results`,showChevron:b,expanded:K,onToggleDetails:ce,showClose:!L,onClose:t,fontFamily:f?.fontFamily||I.typography.fontFamily,labelColor:W,textPrimary:O,closeHoverBg:X,closePressedBg:xe}),o.jsx("div",{style:{marginBottom:"16px"},children:L?o.jsx(Ho,{chainName:Z,bg:P,border:Q,textPrimary:O,labelColor:W,primaryColor:v}):o.jsx(Lo,{isSuccess:ee,type:r,chainName:Z,explorerUrl:ne,txHash:oe?.transactionHash,dark:w,...H,textSecondary:W})}),b&&o.jsx("div",{style:{overflow:"hidden",maxHeight:K?"300px":"0px",opacity:K?1:0,transition:"max-height 0.3s ease, opacity 0.3s ease",marginBottom:K?"16px":"0"},children:o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:pe.map((G,Ie)=>{const ze=G.transactionHash?p.getExplorerUrl(G.chainId,G.transactionHash):null;return o.jsx(Qo,{bg:z,border:N,left:o.jsx("span",{style:{fontSize:"13px",color:O},children:G.chainName?`On ${G.chainName}`:G.description||`Step ${Ie+1}`}),right:o.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:G.status==="success"?"#10b981":G.status==="failed"?"#ef4444":W,fontWeight:500},children:[ze&&o.jsx("a",{href:ze,target:"_blank",rel:"noopener noreferrer",style:{color:w?T.infoText:"#2563eb",textDecoration:"none"},onClick:Ze=>Ze.stopPropagation(),children:"View"}),G.status==="success"?"\u2713":G.status==="failed"?"\u2717":"\u25CB"]})},Ie)})})}),!L&&o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[te&&x&&o.jsx(p.Button,{variant:"outline",fullWidth:!0,onClick:x,theme:I,styles:f,dark:w,children:"TRY AGAIN"}),m&&o.jsxs(p.Button,{variant:"outline",fullWidth:!0,onClick:m,theme:I,styles:f,dark:w,children:["NEW ",r.toUpperCase()," \u2192"]})]})]});return C?o.jsxs("div",{style:{position:"absolute",bottom:0,left:0,right:0,zIndex:10,animation:F?"slideDown 0.3s ease-in forwards":"slideUp 0.3s ease-out forwards",pointerEvents:"auto"},children:[o.jsx("div",{style:{backgroundColor:S,borderRadius:"12px 12px 0 0",width:"100%",padding:"18px 24px 24px",boxShadow:U},children:ge}),o.jsx("style",{children:zo})]}):o.jsx("div",{style:{backgroundColor:S,borderRadius:"12px",padding:"24px",width:"100%",boxShadow:M},children:ge})}if(!e&&!k||!k&&(!a||a.length===0))return null;const de=a?a.every(pe=>pe.success):!1,ve=a?.[0],ue=[...a??[]].reverse().find(pe=>pe.txHash)?.txHash||ve?.txHash;return o.jsxs("div",{style:{position:C?"absolute":"relative",bottom:C?0:void 0,left:C?0:void 0,right:C?0:void 0,zIndex:C?10:void 0,animation:C?F?"slideDown 0.3s ease-in forwards":"slideUp 0.3s ease-out forwards":void 0,pointerEvents:"auto",width:"100%"},children:[o.jsx("div",{style:{backgroundColor:S,borderRadius:C?"12px 12px 0 0":"12px",width:"100%",padding:"18px 0 24px",boxShadow:C?U:M},children:o.jsxs("div",{style:{width:"100%",boxSizing:"border-box",padding:"0 24px"},children:[o.jsx(Oo,{title:k?`Processing ${r.charAt(0).toUpperCase()+r.slice(1)}`:`${r.charAt(0).toUpperCase()+r.slice(1)} results`,showChevron:!k&&b,expanded:K,onToggleDetails:k?void 0:ce,showClose:!k,onClose:t,fontFamily:f?.fontFamily||I.typography.fontFamily,labelColor:W,textPrimary:O,closeHoverBg:X,closePressedBg:xe}),o.jsx("div",{style:{marginBottom:"16px",animation:"statusFadeIn 220ms cubic-bezier(0.22, 1, 0.36, 1) both"},children:k?o.jsx(Ho,{chainName:A,bg:P,border:Q,textPrimary:O,labelColor:W,primaryColor:v}):o.jsx(Lo,{isSuccess:de,type:r,chainName:A,explorerUrl:E,txHash:ue,dark:w,...H,textSecondary:W})},k?"processing":de?"success":"error"),!k&&b&&a&&a.length>1&&o.jsx("div",{style:{overflow:"hidden",maxHeight:K?"200px":"0px",opacity:K?1:0,transition:"max-height 0.3s ease, opacity 0.3s ease",marginBottom:K?"16px":"0"},children:o.jsx("div",{style:{maxHeight:"180px",overflowY:"auto",display:"flex",flexDirection:"column",gap:"8px"},children:a.map((pe,Ee)=>o.jsx(Qo,{bg:z,border:N,left:o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[o.jsx("span",{style:{fontWeight:600,fontSize:"13px",color:T.textPrimary,fontFamily:p.font.mono},children:pe.asset.symbol}),pe.amount&&o.jsx("span",{style:{fontSize:"12px",color:W},children:pe.amount})]}),right:o.jsx("span",{style:{fontSize:"12px",color:pe.success?"#10b981":"#ef4444",fontWeight:500},children:pe.success?"\u2713":"\u2717"})},Ee))})}),!k&&!de&&a&&o.jsx("div",{style:{padding:"12px",backgroundColor:T.errorBg,border:`1px solid ${T.errorBorder}`,borderRadius:"8px",marginBottom:"16px"},children:o.jsx("p",{style:{fontSize:"13px",color:T.errorText,margin:0,lineHeight:1.5},children:J||a.find(pe=>!pe.success)?.error||`${r.charAt(0).toUpperCase()+r.slice(1)} failed. Please try again.`})}),!k&&o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[!de&&y&&o.jsxs(p.Button,{variant:"outline",fullWidth:!0,onClick:y,theme:I,styles:f,dark:w,children:["TRY AGAIN ",r.toUpperCase()]}),de&&o.jsx(p.Button,{variant:"outline",fullWidth:!0,onClick:se,theme:I,styles:f,dark:w,children:"DONE"})]})]})}),o.jsx("style",{children:zo})]})};function zi(e){const t=e.chainTokens??e.chainTokenConfig;if(Array.isArray(t))return t.filter(n=>typeof n=="string");if(t&&typeof t=="object")return t}const jn=({address:e,supportedChains:t,enabled:n=!0,refetchInterval:s})=>{const r=l.useContext(p.SpiceFlowProviderContext)?.apiUrl||p.RELAYER_API_URL,[a,i]=l.useState([]),[d,u]=l.useState(!1),[c,f]=l.useState(null),[h,g]=l.useState(!1),x=l.useRef(!1),m=l.useRef(!1),y=t?JSON.stringify([...t].sort()):"",C=l.useCallback(async(R=!1)=>{if(!e||!n){i([]),g(!1),x.current=!1;return}if(!m.current){m.current=!0,!x.current&&!R&&u(!0),f(null);try{const v=await p.relayerFetch(`${r}/wallets/${e}/balance`,{cache:"no-store"});if(!v.ok)throw new Error(`Failed to fetch balance: ${v.status}`);const w=await v.json();if(w.balances&&Array.isArray(w.balances)){const T=w.balances.map(I=>Xa({receiptToken:typeof I.receiptToken=="string"?I.receiptToken:void 0,tokenName:String(I.tokenName??""),balanceAvailable:String(I.balanceAvailable??"0"),chainTokens:zi(I),decimals:typeof I.decimals=="number"?I.decimals:void 0,balanceUsd:typeof I.balanceUsd=="number"||typeof I.balanceUsd=="string"?I.balanceUsd:null},t)).filter(I=>I!==null);i(T),g(T.length>0),x.current=!0}else i([]),g(!1)}catch(v){const w=v instanceof Error?v.message:"Failed to fetch balance";f(w),console.error("Error fetching Spice assets:",v),x.current||(i([]),g(!1))}finally{u(!1),m.current=!1}}},[e,n,y,r]);l.useEffect(()=>{n&&e&&(x.current=!1,C(!1))},[e,n,y]),l.useEffect(()=>{if(!n||!e||!s)return;const R=setInterval(()=>{C(!0)},s);return()=>clearInterval(R)},[e,n,s,y]);const k=l.useCallback(R=>a.filter(v=>v.chainId===R),[a]),b=l.useCallback(async()=>{await C(!0)},[C]);return{assets:a,loading:d,error:c,hasBalance:h,refetch:b,getAssetsByChain:k}};function Vo(e,t,n,s){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const r=10n**BigInt(t-n);return s==="ceil"?(e+r-1n)/r:e/r}const Oi={usdc:1,"usdc.e":1,usdt:1,dai:1,ctusd:1,wbtc:1e5,wcbtc:1e5,cbtc:1e5};function Ws(e,t){return D.formatUnits(e,t).replace(/(\.\d*?[1-9])0+$|\.0+$/,"$1")}function qo(e,t,n){return Vo(e,t,n,"floor")}function Yo(e,t){const n=t?Oi[t.trim().toLowerCase()]??0:0,s=e*n;return s<=0?"$0":s>=1?`$${s.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}`:`$${s.toFixed(4).replace(/0+$/,"").replace(/\.$/,"")}`}function Hi(e,t){return t?JSON.stringify({tokenAddress:t.toLowerCase(),batches:e.map(n=>({chainId:n.chainId,calls:n.calls.map(s=>({to:s.to.toLowerCase(),value:s.value.toString(),data:s.data})),tokenTransfers:(n.tokenTransfers??[]).map(s=>({from:s.from,to:s.to.toLowerCase(),token:s.token.toLowerCase(),amount:s.amount.toString()}))}))}):null}function Qi(e){const t=e.find(n=>B.isSpicenetChainId(n.chainId))?.calls?.[0]?.data;if(!t)return null;try{const n=D.decodeFunctionData({abi:B.spicenetAbi,data:t});return n.functionName!=="createWithdrawalRequest"?null:n.args[0].transfers.map(s=>({token:s.token,recipient:s.to,amount:s.amount}))}catch{return null}}function Vi(e,t){return!e||e.length!==t.length?!1:e.every((n,s)=>{const r=t[s];return n.token.toLowerCase()!==r.token.toLowerCase()||n.recipient.toLowerCase()!==r.recipient.toLowerCase()?!1:n.recipient.toLowerCase()===B.SPICE_GAS_FEE_RECIPIENT.toLowerCase()?Jt(n.amount,r.amount,100n):n.amount===r.amount})}function qi(e,t){const n=e.intents.flatMap(a=>a.batches).filter(a=>{const i=jt(a);return BigInt(a.quotedAmount)>0n||BigInt(a.totalDebit)>0n||i.totalFee>0n}),s=n.filter(a=>a.chainId===t),r=s.length>0?s:n;return r.length===1?r[0]:null}function Yi(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const s=n.token.toLowerCase(),r=n.recipient.toLowerCase(),a=`${s}:${r}`,i=t.get(a);i?i.amount+=n.amount:t.set(a,{...n})}return[...t.values()]}function Zo(e,t){if(!e.token||!e.recipient||e.chainId===null)return null;const n=qi(t,e.chainId);if(!n)return null;const{gasFee:s,bridgeFee:r,spicenetFee:a}=jt(n),i=s+r,d=[{token:e.token.address,recipient:e.recipient,amount:e.receiveAmountRaw}];return i>0n&&d.push({token:e.token.address,recipient:B.SPICE_GAS_FEE_RECIPIENT,amount:i}),a>0n&&d.push({token:e.token.address,recipient:B.SPICE_PLATFORM_FEE_RECIPIENT,amount:a}),Yi(d)}function Ko(e,t,n){const s=Zo(e,t);return!s||Vi(Qi(n),s)?null:e.buildWithdrawBatches(s)}async function Xo(e){if(!(!e.batches.length||!e.walletAddress||!e.recipient)){e.ui.setIsExecuting(!0),e.ui.setExecutionError(null),e.ui.setExecutionProgress(null),e.executionContextRef.current=null,e.ui.setLockedGasFee(e.gasFee);try{let t=e.batches;if(e.isNon7702&&e.onWithdrawExecute)await e.onWithdrawExecute(e.amount);else{if(!e.isNon7702&&!t.some(r=>B.isSpicenetChainId(r.chainId)))throw new Error("Spice withdrawals must include a Spicenet funding batch before the destination chain batch.");const n=e.token?.address||"",s={useCustomTransfers:!0};if(e.buildSpicenetBatch){const r=await e.execution.estimate(t,n,0n,{...s,adjustBatchesForEstimate:({feeEstimate:d,chainBatches:u})=>Ko(e,d,u)}),a=Zo(e,r);a&&(t=e.buildWithdrawBatches(a));const i=r.intents[0]?.batches.find(d=>d.chainId===e.chainId)??r.intents[0]?.batches[0]??null;i&&e.ui.setLockedGasFee(jt(i).totalFee)}else{const r=(await e.execution.estimate(t,n,0n,s)).intents[0]?.batches[0]??null;r&&e.ui.setLockedGasFee(jt(r).totalFee)}await e.execution.execute(t,n,0n,r=>{r.actionId&&r.intentId&&typeof r.intentIndex=="number"&&typeof r.totalSteps=="number"&&(e.executionContextRef.current={actionId:r.actionId,intentId:r.intentId,intentIndex:r.intentIndex,totalSteps:r.totalSteps}),e.ui.setExecutionProgress(r)},void 0,e.buildSpicenetBatch?{...s,adjustBatchesForEstimate:({feeEstimate:r,chainBatches:a})=>Ko(e,r,a)}:s)}Go(e)}catch(t){const n=t instanceof Error?t.message:"Withdraw failed";e.ui.setExecutionError(n)}finally{e.ui.setIsExecuting(!1)}}}function Go(e){window.dispatchEvent(new CustomEvent("withdraw-completed")),e.onWithdrawSuccess?.({token:e.token?.symbol||"",amount:e.amount,chainId:e.chainId})}async function Zi(e){const t=e.executionContextRef.current;if(!t){e.ui.setExecutionProgress(null),await Xo(e);return}e.ui.setIsExecuting(!0),e.ui.setExecutionError(null),e.ui.setExecutionProgress({step:"executing",message:"Resuming existing action...",actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps});try{let n=t.totalSteps;for(let s=0;s<t.totalSteps;s++)if((await p.relayerService.checkStepStatus(t.intentId,s)).data.status!=="success"){n=s;break}if(n>=t.totalSteps)e.ui.setExecutionProgress(s=>({...s||{step:"success",message:"Transaction successful!",actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps},step:"success",message:"Transaction successful!"}));else for(let s=n;s<t.totalSteps;s++){const r=await yo({actionId:t.actionId,intentIndex:t.intentIndex,intentId:t.intentId,stepIndex:s,chainId:e.chainId??void 0,onStatusMessage:(a,i)=>{e.isMountedRef.current&&e.ui.setExecutionProgress({step:"executing",message:a,txHash:i,actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps})}});if(!e.isMountedRef.current)return;e.ui.setExecutionProgress({step:s===t.totalSteps-1?"success":"executing",message:s===t.totalSteps-1?"Transaction successful!":"Executing remaining steps...",txHash:r,actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps})}Go(e)}catch(n){const s=n instanceof Error?n.message:"Withdraw failed";e.ui.setExecutionError(s)}finally{e.ui.setIsExecuting(!1)}}async function Ki(e){const t=await e.estimate(e.batches,e.tokenAddress,0n,{useCustomTransfers:!0}),n=t.intents.flatMap(r=>r.batches).filter(r=>jt(r).totalFee>0n),s=n.filter(r=>r.chainId===e.chainId)[0]??n[0]??t.intents[0]?.batches[0];if(!s)throw new Error("No gas fee estimate was returned for this withdraw.");return jt(s).totalFee}const Jo=p.font.mono,$o=p.font.ui,Xi=({show:e,position:t,popoverRef:n,spiceAssets:s,dark:r,dk:a})=>{if(!e||!t)return null;const i=r?a.textSecondary:"#71757A",d=r?a.textPrimary:"#0E0D0B",u=s||[];return o.jsxs("div",{ref:n,"data-balance-popover":!0,style:{position:"fixed",top:`${t.top}px`,left:`${t.left}px`,width:"220px",background:r?a.cardBg:"#FFFFFF",border:`1px solid ${r?a.cardBorder:"#D6D6D6"}`,borderRadius:"10px",boxShadow:r?"0 12px 32px rgba(0,0,0,0.32)":"0 12px 28px rgba(15, 23, 42, 0.14)",padding:"10px",zIndex:40},children:[o.jsx("div",{style:{fontFamily:Jo,fontSize:"11px",letterSpacing:"0.05em",color:i,marginBottom:"8px"},children:"ALL BALANCES"}),o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:u.length>0?u.map(c=>{const f=c.displaySymbol||c.receiptTokenName||c.symbol;return o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"10px",padding:"6px 0"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0},children:[c.logoURI?o.jsx("img",{src:c.logoURI,alt:f,style:{width:"18px",height:"18px",borderRadius:"50%",flexShrink:0}}):o.jsx("div",{style:{width:"18px",height:"18px",borderRadius:"50%",border:`1px solid ${r?a.cardBorder:"#C8C8C8"}`,flexShrink:0}}),o.jsx("span",{style:{fontFamily:$o,fontSize:"13px",color:d,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:f})]}),o.jsx("span",{style:{fontFamily:Jo,fontSize:"12px",color:d,flexShrink:0},children:p.formatBalance(c.balanceFormatted)})]},c.receiptTokenId||c.address)}):o.jsx("span",{style:{fontFamily:$o,fontSize:"13px",color:i},children:"No balances"})})]})},Gi=p.font.ui,$t=p.font.mono,Ji=({show:e,onToggle:t,showCustomAddress:n,setShowCustomAddress:s,customRecipient:r,setCustomRecipient:a,externalAddress:i,recipientAddress:d,destChainName:u,destChainLogo:c,compatibleDestinationChains:f,txDetailsChainSwitchRef:h,onOpenNetworkPopover:g,sourceChainLabel:x,sourceDetailsLogo:m,sourceTokenLabel:y,amount:C,totalSourceDebitDisplay:k,receiveAmountDisplay:b,destTokenSymbol:R,shouldQuoteWithdrawGas:v,estimatingFee:w,feeError:T,displayedGasFee:I,selectedDestToken:F,theme:j,styles:A,dark:E,dk:S})=>{const M=E?S.textSecondary:"#71757A",U=E?S.textPrimary:"#0E0D0B",W=f.length>1,O=n&&r?D.isAddress(r)?p.truncateAddress(r):r:d?p.truncateAddress(d):"\u2014";return o.jsxs(o.Fragment,{children:[o.jsxs("div",{onClick:t,style:{display:"flex",alignItems:"center",gap:"6px",marginBottom:e?"10px":"0",cursor:"pointer",userSelect:"none"},children:[o.jsx("span",{style:{fontSize:"13px",color:M,fontFamily:Gi,fontWeight:600},children:"Transaction Details"}),o.jsx(sa,{size:12,color:M,style:{transform:e?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s"}})]}),e&&o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"7px"},children:[o.jsxs("div",{children:[o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[o.jsx("span",{style:{fontSize:"12px",color:M,fontFamily:$t,fontWeight:500,letterSpacing:"0.03em"},children:"TO"}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[o.jsx("span",{style:{fontSize:"13px",color:U,fontFamily:$t,fontWeight:500},children:O}),o.jsx("button",{onClick:()=>{s(z=>!z),!n&&i&&a(i)},style:{background:"none",border:"none",cursor:"pointer",padding:"0",fontSize:"9.5px",fontFamily:$t,color:M,textDecoration:"underline",fontWeight:600},children:n?"Reset":"Switch"})]})]}),n&&o.jsxs("div",{style:{marginTop:"6px"},children:[o.jsx("div",{style:{marginBottom:"6px",padding:"7px 9px",borderRadius:"6px",border:"1px solid rgba(239, 68, 68, 0.55)",backgroundColor:"rgba(239, 68, 68, 0.12)",color:"#ef4444",fontSize:"10px",lineHeight:1.35,fontFamily:$t,fontWeight:700,letterSpacing:0,textTransform:"uppercase"},children:"CAUTION: ENTERING AN INCORRECT ADDRESS WILL RESULT IN LOSS OF FUNDS"}),o.jsx("input",{type:"text",autoComplete:"off",spellCheck:!1,"aria-label":"Recipient address","aria-invalid":r&&!D.isAddress(r)?!0:void 0,"data-spiceflow-focus":!0,value:r,onChange:z=>a(z.target.value),placeholder:"0x...",style:{width:"100%",padding:"8px 10px",borderRadius:"6px",border:`1px solid ${r&&!D.isAddress(r)?E?S.errorBorder:"#fca5a5":E?S.inputBorder:"#d1d5db"}`,backgroundColor:E?S.inputBg:"#f9fafb",color:E?S.inputText:"#111827",fontSize:"12px",fontFamily:$t,outline:"none",boxSizing:"border-box"}}),r&&!D.isAddress(r)&&o.jsx("span",{style:{fontSize:"11px",color:S.errorText,marginTop:"3px",display:"block"},children:"Invalid address"})]})]}),o.jsx(gn,{palette:S,labelColor:M,valueColor:U,label:"RECEIVING CHAIN",value:o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"7px"},children:[c&&o.jsx("img",{src:c,alt:u,style:{width:"14px",height:"14px",borderRadius:"50%"}}),o.jsx("span",{style:{fontSize:"13px",color:U,fontWeight:500,fontFamily:$t,textTransform:"uppercase"},children:u}),o.jsx("button",{ref:h,onClick:z=>{z.stopPropagation(),g(h.current)},style:{background:"none",border:"none",cursor:W?"pointer":"not-allowed",padding:"0",fontSize:"9.5px",fontFamily:$t,color:M,textDecoration:"underline",fontWeight:600,opacity:W?1:.45},children:"Switch"})]})}),o.jsx(gn,{palette:S,labelColor:M,valueColor:U,label:"REQUESTED WITHDRAWAL",value:o.jsxs(Ns,{logo:m||null,alt:x,primaryText:U,children:[C||"0"," ",y]})}),v&&o.jsx(gn,{palette:S,labelColor:M,valueColor:U,label:"TOTAL SOURCE DEBIT",value:o.jsxs(Ns,{logo:m||null,alt:x,primaryText:U,children:[k," ",y]})}),o.jsx(gn,{palette:S,labelColor:M,valueColor:U,label:"YOU RECEIVE",value:o.jsxs(Ns,{logo:c,alt:u,primaryText:U,gap:"4px",children:[b," ",R]})}),v&&o.jsxs(o.Fragment,{children:[o.jsx(gn,{palette:S,labelColor:M,label:"EST. GAS FEE",valueColor:T?"#f87171":U,value:w?"Estimating...":T?"Unavailable":I!==null&&F?`${Ws(I,F.decimals)} ${F.symbol}`:"Estimating..."}),T&&o.jsx(an,{variant:"error",size:"compact",palette:S,fontFamily:A?.fontFamily||j.typography.fontFamily,children:T})]})]})]})},$i=l.memo(Ji),Ns=({logo:e,alt:t,primaryText:n,gap:s="6px",children:r})=>o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:s},children:[e&&o.jsx("img",{src:e,alt:t,style:{width:"13px",height:"13px",borderRadius:"50%"}}),o.jsx("span",{style:{fontSize:"13px",color:n,fontWeight:500,fontFamily:$t},children:r})]}),_i=({dark:e,dk:t})=>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,...e?{filter:"invert(0.6)"}:{}}}),o.jsx("p",{style:{fontSize:"13px",color:e?t.textSecondary:"#979AA0",margin:"0",lineHeight:"1.4",fontFamily:p.font.ui},children:"Withdraw collateral from your account to 10+ EVM blockchains."})]}),_o=p.font.ui,el=({label:e,spiceAssetsLoading:t,totalSelectedBalance:n,onOpenBalancePopover:s,dark:r,dk:a})=>{const i=r?a.textSecondary:"#7D7C7B",d=r?a.textSecondary:"#71757A";return o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[o.jsx("span",{style:{fontFamily:_o,fontSize:"17px",fontWeight:500,color:i,lineHeight:"24px"},children:e}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",fontFamily:_o,fontSize:"13px",fontWeight:500,color:d,lineHeight:"16px"},children:["Balance:"," ",t?"...":p.formatBalance(n),o.jsx("button",{type:"button","data-balance-trigger":!0,onClick:u=>{u.stopPropagation(),s(u.currentTarget)},style:{width:"15px",height:"15px",borderRadius:"999px",border:"1px solid #EA4B4B",color:"#EA4B4B",display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:"9px",fontWeight:500,lineHeight:1,boxSizing:"border-box",background:"transparent",padding:0,cursor:"pointer"},children:o.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"1.5px"},children:[0,1,2].map(u=>o.jsx("span",{style:{width:"1.75px",height:"1.75px",borderRadius:"999px",backgroundColor:"#EA4B4B",display:"block"}},u))})})]})]})},er=({isOpen:e,position:t,title:n,items:s,selectedId:r,onSelect:a,portalAttribute:i})=>{const{dark:d,dk:u,primaryColor:c}=p.useSpiceBrand(),[f,h]=l.useState(null),[g,x]=l.useState(!1);return l.useEffect(()=>{if(!e){x(!1);return}const m=requestAnimationFrame(()=>{requestAnimationFrame(()=>x(!0))});return()=>cancelAnimationFrame(m)},[e]),!e||!t||s.length===0?null:Cn.createPortal(o.jsxs("div",{[`data-${i}-popover`]:"true",style:{position:"fixed",top:`${t.top}px`,left:`${t.left}px`,opacity:g?1:0,transform:g?"scale(1) translateY(0)":"scale(0.96) translateY(-6px)",transition:`opacity 200ms ${p.easing.out}, transform 200ms ${p.easing.out}`,backgroundColor:d?u.shell:"#ffffff",borderRadius:"10px",padding:"10px 12px",boxShadow:d?"0 16px 48px rgba(0,0,0,0.45)":"0 12px 32px rgba(0,0,0,0.12)",border:`1px solid ${u.cardBorder}`,minWidth:"220px",zIndex:p.z.dropdown,fontFamily:p.font.mono},children:[o.jsx("div",{style:{marginBottom:"6px"},children:o.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:d?u.textPrimary:"#0e0d0b",textTransform:"uppercase",letterSpacing:"1px"},children:n})}),o.jsx("div",{style:{borderBottom:`1px solid ${u.cardBorder}`,marginBottom:"6px"}}),o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"2px"},children:s.map(m=>{const y=r===m.id,C=f===m.id;return o.jsxs("button",{onClick:k=>{k.stopPropagation(),a(m.id)},onMouseEnter:()=>h(m.id),onMouseLeave:()=>h(null),style:{display:"flex",alignItems:"center",gap:"8px",padding:"6px 4px",borderRadius:"8px",border:"none",cursor:"pointer",backgroundColor:y?d?u.hoverBg:"#f3f4f6":C?d?u.cardBg:"#f9fafb":"transparent",transition:"background-color 0.15s",width:"100%",fontFamily:p.font.mono},children:[m.icon&&o.jsx("img",{src:m.icon,alt:m.label,style:{width:"22px",height:"22px",borderRadius:"50%"}}),o.jsx("span",{style:{fontSize:"13px",fontWeight:y?700:500,textTransform:"uppercase",color:d?u.textPrimary:"#0e0d0b",letterSpacing:"0.5px",flex:1,textAlign:"left"},children:m.label}),m.detail&&o.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:u.textSecondary},children:m.detail}),y&&o.jsx(_s,{color:c,style:{flexShrink:0}})]},m.id)})})]}),document.body)},Fn=p.font.ui,tl=170,nl=({header:e,amount:t,setAmount:n,isInsufficient:s,sourceAmountDecimals:r,selectedSourceAsset:a,resolvedSelectedSourceAsset:i,spiceAssets:d,setSelectedSourceAsset:u,sourceUsdEstimate:c,sourceTokenLabel:f,sourceChainLabel:h,totalSelectedBalance:g,showSourceTokenPopover:x,setShowSourceTokenPopover:m,tokenPopoverPos:y,setTokenPopoverPos:C,tokenTriggerRef:k,primaryColor:b,dark:R,dk:v})=>{const w=R?v.cardBg:"#E9E9E9",T=R?v.cardBorder:"#C6C6C6",I=R?v.textSecondary:"#71757A",F=R?v.textPrimary:"#0E0D0B",j=R?v.cardBorder:"#C5C5C4",A=R?"rgba(255,255,255,0.08)":"#D4D3D3",E=f.length>8?"14px":f.length>6?"16px":"18px";return o.jsxs("div",{style:{backgroundColor:w,border:`1px solid ${T}`,borderRadius:"7px",padding:"14px 16px 12px 16px",minHeight:"138px",display:"flex",flexDirection:"column",gap:"6px",position:"relative"},children:[e,o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[o.jsxs("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[o.jsx(rn,{element:"input",ariaLabel:"Withdraw amount",ariaInvalid:s,dataSpiceflowFocus:!0,value:t,onChange:S=>{const M=S.target.value;if(M===""){n("");return}/^\d*\.?\d*$/.test(M)&&n(p.parseNumericInput(M.startsWith(".")?`0${M}`:M,r??a?.decimals))},placeholder:"0.0",fontFamily:Fn,color:s?"#ef4444":t?F:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,style:{width:"100%"}}),o.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:I,fontFamily:Fn,marginTop:"10px"},children:c})]}),o.jsx("div",{style:{width:`${tl}px`,flexShrink:0},children:o.jsxs("div",{style:{backgroundColor:"transparent",border:`1px solid ${j}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[o.jsxs("div",{ref:k,onClick:S=>{if(S.stopPropagation(),!x&&k.current){const M=k.current.getBoundingClientRect(),U=220,W=16;C({top:M.bottom+8,left:Math.min(Math.max(W,M.right-U),window.innerWidth-U-W)})}m(M=>!M)},style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px",cursor:"pointer"},children:[o.jsx("img",{src:ds,alt:f,style:{width:"24px",height:"24px",borderRadius:"50%"}}),o.jsx("span",{style:{fontSize:E,fontWeight:500,color:F,lineHeight:"1.3",fontFamily:Fn,flex:1,minWidth:0,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",letterSpacing:0},children:f}),o.jsx(on,{size:15,color:F,strokeWidth:2.25})]}),o.jsx(er,{isOpen:x,position:y,title:"SELECT TOKEN",portalAttribute:"token",items:(d||[]).map(S=>({id:S.receiptTokenId||S.address,label:S.displaySymbol||S.receiptTokenName||S.symbol,icon:ds,detail:p.formatBalance(S.balanceFormatted)})),selectedId:i?.receiptTokenId||i?.address||null,onSelect:S=>{const M=(d||[]).find(U=>(U.receiptTokenId||U.address)===S);M&&(u(M),n("")),m(!1)}}),o.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:A,borderTop:`1px solid ${j}`},children:o.jsx("span",{style:{fontSize:"11px",fontWeight:400,color:F,fontFamily:Fn,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:h})})]})})]}),o.jsxs("div",{style:{minHeight:"18px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[s?o.jsx("span",{style:{fontSize:"12px",color:v.errorText,fontFamily:Fn,fontWeight:500},children:"Insufficient Balance"}):o.jsx("span",{}),o.jsx("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0px",minHeight:"32px",marginRight:"-9px"},children:[0,25,50,75,100].map((S,M)=>{const U=M===4,W=parseFloat(t)||0,O=g>0&&Math.abs(W/g*100-S)<1;return o.jsx("button",{type:"button","aria-label":`Set amount to ${S}%`,"aria-pressed":O,onClick:()=>{const z=g*S/100,N=a?.decimals??6,P=Math.floor(z*10**N)/10**N;n(S===0?"":P>0?p.formatDecimalInput(P,N):"")},title:`${S}%`,disabled:g===0,"data-spiceflow-focus":!0,style:{width:"32px",height:"32px",padding:"9px",border:"none",backgroundColor:"transparent",cursor:g===0?"not-allowed":"pointer",opacity:O?1:.5,transition:"opacity 0.15s ease",display:"flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box"},children:o.jsx(cs,{pct:S,isMax:U,primaryColor:b,dark:R,fillColor:R?v.textSecondary:"#3C3E42"})},S)})})]})]})},Xn=p.font.ui,sl=p.font.mono,ol=170,rl=({header:e,amount:t,receiveAmountDisplay:n,receiveUsdEstimate:s,selectedDestToken:r,destTokenSymbol:a,destChainName:i,destChainLogo:d,compatibleDestinationChains:u,networkSwitchRef:c,onOpenNetworkPopover:f,showNetworkPopover:h,setShowNetworkPopover:g,networkPopoverPos:x,selectedChainId:m,setSelectedChainId:y,dark:C,dk:k})=>{const b=C?k.cardBg:"#E9E9E9",R=C?k.cardBorder:"#C6C6C6",v=C?k.textSecondary:"#71757A",w=C?k.textPrimary:"#0E0D0B",T=C?k.cardBorder:"#C5C5C4",I=C?"rgba(255,255,255,0.08)":"#D4D3D3",F=a.length>8?"14px":a.length>6?"16px":"18px";return o.jsxs("div",{style:{backgroundColor:b,border:`1px solid ${R}`,borderRadius:"7px",padding:"14px 16px 12px 16px",minHeight:"138px",display:"flex",flexDirection:"column",gap:"6px"},children:[e,o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[o.jsxs("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[o.jsx(rn,{element:"div",value:n,title:n,fontFamily:Xn,color:t?w:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,overflow:"wrap"}),o.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:v,fontFamily:Xn,marginTop:"10px"},children:s})]}),o.jsxs("div",{style:{width:`${ol}px`,flexShrink:0,display:"flex",flexDirection:"column",alignItems:"stretch",gap:"8px"},children:[o.jsxs("div",{style:{backgroundColor:"transparent",border:`1px solid ${T}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px"},children:[o.jsx("img",{src:r?.logoURI||fa,alt:a,style:{width:"24px",height:"24px",borderRadius:"50%"}}),o.jsx("span",{style:{fontSize:F,fontWeight:500,color:w,lineHeight:"1.3",fontFamily:Xn,flex:1,minWidth:0,letterSpacing:0},children:a})]}),o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:I,borderTop:`1px solid ${T}`},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[d&&o.jsx("img",{src:d,alt:i,style:{width:"13px",height:"13px",borderRadius:"50%",flexShrink:0}}),o.jsx("span",{style:{fontSize:"11px",fontWeight:400,color:w,fontFamily:Xn,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:i})]}),o.jsx("button",{ref:c,onClick:j=>{j.stopPropagation(),f(c.current)},style:{background:"none",border:"none",cursor:u.length>1?"pointer":"not-allowed",padding:"0 0 0 8px",fontSize:"9.5px",fontFamily:sl,color:v,textDecoration:"underline",fontWeight:600,opacity:u.length>1?1:.45},children:"Switch"}),o.jsx(er,{isOpen:h,position:x,title:"SELECT NETWORK",portalAttribute:"network",items:u.map(j=>{const A=p.getChainConfig(j);return{id:String(j),label:A?.displayName||String(j),icon:Gt[j]||wn}}),selectedId:m!==null?String(m):null,onSelect:j=>{y(Number(j)),g(!1)}})]})]}),o.jsx("div",{style:{minHeight:"14px"}})]})]})]})};function tr(e){const t=new Set(B.getEquivalentAddresses(e).map(n=>n.toLowerCase()));return t.add(e.toLowerCase()),t}const al=["USDC","USDT","WETH","WBTC"];function nr(e,t){const n=p.getChainConfig(t);if(!n)return;if(n.nativeCurrency.symbol.toUpperCase()===e.toUpperCase())return{address:B.ZERO_ADDRESS,symbol:n.nativeCurrency.symbol,decimals:n.nativeCurrency.decimals,chainId:t};const s=n.supportedTokens?.find(r=>r.symbol.toUpperCase()===e.toUpperCase());if(s)return{address:s.address.toLowerCase(),symbol:s.symbol,decimals:s.decimals,chainId:t}}function Xt(e,t,n){const s=p.getChainConfig(t);if(!s)return;if(n!==void 0){const i=mo(e,n,t);if(i)return{address:i.address.toLowerCase(),symbol:i.symbol,decimals:i.decimals,chainId:t}}const r=tr(e);if([...r].some(i=>B.isNativeToken(i)))return{address:B.ZERO_ADDRESS,symbol:s.nativeCurrency.symbol,decimals:s.nativeCurrency.decimals,chainId:t};const a=s.supportedTokens?.find(i=>r.has(i.address.toLowerCase()));if(a)return{address:a.address.toLowerCase(),symbol:a.symbol,decimals:a.decimals,chainId:t}}function il(e){const{sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:r,intermediaryCandidates:a=al}=e;if(Ln(t,n))return{strategy:"direct",sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:r,summary:`${t.symbol} fronted directly`};if(Xt(t.address,r,s))return{strategy:"direct",sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:r,summary:`${t.symbol} fronted on destination, swapped to ${n.symbol}`};if(Xt(n.address,s,r))return{strategy:"source-swap",sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:r,summary:`${t.symbol} \u2192 ${n.symbol} on source chain, then fronted`};for(const i of a){const d=nr(i,s);if(!d||Ln(t,d)||Ln(n,d))continue;const u=nr(i,r);if(u&&Ln(d,u))return{strategy:"intermediary",sourceAsset:t,outputAsset:n,intermediaryAsset:u,sourceChainId:s,destinationChainId:r,summary:`${t.symbol} \u2192 ${i} on source, fronted, then ${i} \u2192 ${n.symbol} on destination`}}throw new p.SpiceflowError("ROUTE_STRATEGY_ERROR",`No viable cross-chain route found from ${t.symbol} (chain ${s}) to ${n.symbol} (chain ${r}). No intermediary asset is available on both chains.`,{sourceAsset:t.symbol,outputAsset:n.symbol,sourceChainId:s,destinationChainId:r,candidatesChecked:a})}async function ll(e){const{route:t,sourceAmount:n,userAddress:s,registry:r,actionCalls:a,slippage:i}=e;async function d(u,c,f,h){const g=r.getVenueForChain(u);if(!g)throw new p.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${u}. Cannot resolve swap ${c} \u2192 ${f}.`,{chainId:u,tokenIn:c,tokenOut:f,amountIn:h.toString()});const x=await g.resolve({type:"swap",tokenIn:c,tokenOut:f,amountIn:h,maxSlippage:i},u,s);if(!x)throw new p.SpiceflowError("NO_LIQUIDITY",`${g.name} returned no quote for ${c} \u2192 ${f} on chain ${u}. No liquidity available for this pair.`,{venue:g.name,chainId:u,tokenIn:c,tokenOut:f,amountIn:h.toString()});return x}switch(t.strategy){case"direct":{const u=Xt(t.sourceAsset.address,t.destinationChainId,t.sourceChainId)||t.sourceAsset;if(tr(u.address).has(t.outputAsset.address.toLowerCase()))return{chainBatches:[{chainId:t.destinationChainId,calls:a}],solverFrontToken:u,solverFrontAmount:n,resolvedSwaps:{}};const c=await d(t.destinationChainId,u.address,t.outputAsset.address,n);return{chainBatches:[{chainId:t.destinationChainId,calls:[...c.calls,...a]}],solverFrontToken:u,solverFrontAmount:n,resolvedSwaps:{destinationSwap:c}}}case"source-swap":{const u=Xt(t.outputAsset.address,t.sourceChainId,t.destinationChainId);if(!u)throw new p.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Output asset ${t.outputAsset.symbol} (${t.outputAsset.address}) not found on source chain ${t.sourceChainId}`,{token:t.outputAsset.symbol,address:t.outputAsset.address,chainId:t.sourceChainId,side:"source"});const c=Xt(t.outputAsset.address,t.destinationChainId,t.destinationChainId);if(!c)throw new p.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Output asset ${t.outputAsset.symbol} (${t.outputAsset.address}) not found on destination chain ${t.destinationChainId}`,{token:t.outputAsset.symbol,address:t.outputAsset.address,chainId:t.destinationChainId,side:"destination"});const f=await d(t.sourceChainId,t.sourceAsset.address,u.address,n);return{chainBatches:[{chainId:t.sourceChainId,calls:f.calls},{chainId:t.destinationChainId,calls:a}],solverFrontToken:c,solverFrontAmount:f.amountOutMinimum,resolvedSwaps:{sourceSwap:f}}}case"intermediary":{if(!t.intermediaryAsset)throw new p.SpiceflowError("ROUTE_STRATEGY_ERROR","Intermediary strategy requires an intermediary asset but none was provided in the route plan.",{strategy:t.strategy});const u=Xt(t.intermediaryAsset.address,t.sourceChainId,t.destinationChainId);if(!u)throw new p.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Intermediary ${t.intermediaryAsset.symbol} (${t.intermediaryAsset.address}) not found on source chain ${t.sourceChainId}`,{token:t.intermediaryAsset.symbol,address:t.intermediaryAsset.address,chainId:t.sourceChainId,side:"source"});const c=await d(t.sourceChainId,t.sourceAsset.address,u.address,n),f=await d(t.destinationChainId,t.intermediaryAsset.address,t.outputAsset.address,c.amountOutMinimum);return{chainBatches:[{chainId:t.sourceChainId,calls:c.calls},{chainId:t.destinationChainId,calls:[...f.calls,...a]}],solverFrontToken:t.intermediaryAsset,solverFrontAmount:c.amountOutMinimum,resolvedSwaps:{sourceSwap:c,destinationSwap:f}}}default:throw new p.SpiceflowError("ROUTE_STRATEGY_ERROR",`Unknown route strategy: ${t.strategy}`,{strategy:t.strategy})}}const cl=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,styles:s,onWithdrawExecute:r,onWithdrawSuccess:a,onWithdrawError:i,availableTokens:d,buildSpicenetBatch:u})=>{const c=l.useContext(p.SpiceFlowProviderContext);if(!c)return o.jsx("div",{children:"Error: SpiceWithdraw must be used within SpiceFlowProvider"});const f=c.mode||"7702",h=f==="presign"||f==="ondemand",g=c.supportedChainIds,x=c.allowedTokens,m=c.isWhitelistGateActive,{theme:y,dark:C,dk:k}=p.useSpiceBrand(s),b=c.network,R=()=>h?"select":"provider-login",[v,w]=l.useState(R()),[T,I]=l.useState(!1),[F,j]=l.useState(null),[A,E]=l.useState(null),[S,M]=l.useState(""),[U,W]=l.useState(!1),[O,z]=l.useState(!1),[N,P]=l.useState(!1),[Q,K]=l.useState(!1),[V,X]=l.useState(""),[xe,H]=l.useState(!0),J=l.useRef(null),se=l.useRef(null),ce=l.useRef(null),de=l.useRef(null),[ve,ue]=l.useState(null),[pe,Ee]=l.useState(null),[L,ee]=l.useState(null),te=p.useWallet(),{isReady:oe,isAuthenticated:Z,address:ne}=te,ge=c?.embeddedWalletAddress,{address:G,chainId:Ie}=Qt.useAccount(),[ze,Ze]=l.useState(!1),[Ft,ht]=l.useState(null),Ue=l.useRef(i);Ue.current=i;const le=l.useCallback(Y=>{ht(Y),typeof Y=="string"&&Y&&Ue.current?.(Y,p.getRelayerErrorDetail(Y))},[]),[Ae,Ke]=l.useState(null),et=l.useRef(null),ae=l.useRef(!0),nt=l.useRef(null);l.useEffect(()=>(ae.current=!0,()=>{ae.current=!1}),[]);const{execute:ke,estimate:we}=mn(),[fe,De]=l.useState(null),[gt,xt]=l.useState(null),[Bt,Fe]=l.useState(!1),[Xe,yt]=l.useState(null),{assets:kt,loading:Tt}=jn({address:ge,enabled:e&&!!ge,refetchInterval:3e4}),Oe=l.useMemo(()=>{if(m)return[];if(!x||x.length===0)return kt;const Y=new Set(x.map($=>$.toLowerCase()));return(kt||[]).filter($=>[$.symbol,$.displaySymbol,$.receiptTokenName].some(re=>typeof re=="string"&&Y.has(re.toLowerCase())))},[kt,x,m]),st=l.useMemo(()=>[...new Set([...g??[],...Object.keys(d??{}).map(Number),...(Oe||[]).map(Y=>Y.chainId),...(Oe||[]).flatMap(Y=>Object.keys(Y.chainTokens??{}).map($=>{const[,re]=$.split(":"),We=Number(re);return Number.isFinite(We)?We:null}).filter($=>$!==null))])].filter(Y=>p.getChainConfig(Y)?.network===b),[g,d,Oe,b]),Mt=l.useMemo(()=>{if(d)return d;const Y={};for(const $ of Oe||[]){const re=Object.entries($.chainTokens??{});if(re.length>0){for(const[We,_]of re){const[Ce,Ne,lt]=We.split(":");if(Ce!=="evm"||!Ne||!lt)continue;const Pe=Number(Ne);if(!Number.isFinite(Pe))continue;const vt=lt.startsWith("0x")?lt.toLowerCase():`0x${lt.toLowerCase()}`,Re=p.getChainConfig(Pe)?.supportedTokens?.find(je=>p.addressesEqual(je.address,vt));Re&&ys($,vt,Pe)&&(Y[Pe]||(Y[Pe]=[]),Y[Pe].find(je=>p.addressesEqual(je.address,vt))||Y[Pe].push({address:vt,symbol:Re?.symbol||_?.name||$.symbol,name:Re?.name||_?.name||$.displayName||$.name||$.symbol,decimals:Re?.decimals??_?.decimals??$.decimals,logoURI:Re?.logo||$.logoURI}))}continue}Y[$.chainId]||(Y[$.chainId]=[]),Y[$.chainId].find(We=>p.addressesEqual(We.address,$.address))||Y[$.chainId].push({address:$.address,symbol:$.symbol,name:$.displayName||$.name||$.symbol,decimals:$.decimals,logoURI:$.logoURI})}return Y},[d,Oe]),Ct=l.useCallback((Y,$)=>{if(!Y||!$)return null;const re=Un(Y,$),We=Object.entries(Y.chainTokens??{}).flatMap(([Re,je])=>{const qe=hn(Re);return qe?.chainId===$?[{parsed:qe,detail:je}]:[]}),_=Mt?.[$]||[],Ce=Re=>_.find(je=>p.addressesEqual(je.address,Re))??null,Ne=Re=>{const je=p.getChainConfig($)?.supportedTokens?.find(Ye=>p.addressesEqual(Ye.address,Re));if(!je||!ys(Y,Re,$))return null;const qe=We.find(({parsed:Ye})=>p.addressesEqual(Ye.address,Re));return qe?{address:qe.parsed.address,symbol:je.symbol,name:je.name||qe.detail?.name||Y.displayName||Y.name||Y.symbol,decimals:je.decimals,logoURI:je.logo||Y.logoURI}:null};for(const Re of re){const je=Ce(Re);if(je)return je;const qe=Ne(Re);if(qe)return qe}const lt=zt(Y,$);if(lt){const Re=Ce(lt);if(Re)return Re;const je=Ne(lt);if(je)return je}const Pe=Xt(Y.address,$,Y.chainId);return Pe?Ce(Pe.address)||(_.length>0?null:{address:Pe.address,symbol:Pe.symbol||Y.symbol,name:Y.displayName||Y.name||Y.symbol,decimals:Pe.decimals??Y.decimals,logoURI:Y.logoURI}):null},[Mt]),he=l.useMemo(()=>{if(!F)return null;const Y=F.receiptTokenId||`${F.chainId}:${F.address.toLowerCase()}`;return Oe.find($=>($.receiptTokenId||`${$.chainId}:${$.address.toLowerCase()}`)===Y)||F},[F,Oe]),He=l.useMemo(()=>{if(!he)return[];const Y=Object.keys(he.chainTokens??{}).map($=>hn($)?.chainId??null).filter($=>$!==null);return Array.from(new Set([...Y,he.chainId,...st].filter(Number.isFinite))).filter($=>$!==1&&p.getChainConfig($)?.network===b&&Ct(he,$)!==null)},[he,st,Ct,b]),ot=l.useMemo(()=>{if(!he||typeof window>"u")return null;const Y=`spiceflow:withdraw-chain:${he.receiptTokenId||he.address.toLowerCase()}`,$=window.localStorage.getItem(Y),re=$?Number($):null;return re!==null&&Number.isFinite(re)&&He.includes(re)?re:null},[he,He]),ct=l.useMemo(()=>he?ot!==null?ot:Ie&&He.includes(Ie)?Ie:he.chainId&&He.includes(he.chainId)?he.chainId:He[0]??st[0]??null:st[0]??null,[he,ot,Ie,He,st]),be=l.useMemo(()=>Ct(he,A),[Ct,he,A]);l.useEffect(()=>{!Oe?.length||he||j(Oe[0])},[Oe,he]),l.useEffect(()=>{he&&(A===null||!He.includes(A))&&E(ct)},[he,A,ct,He]),l.useEffect(()=>{if(!U&&!O&&!N)return;const Y=$=>{const re=$.target;U&&!J.current?.contains(re)&&!se.current?.contains(re)&&!re?.closest?.("[data-network-popover]")&&W(!1),O&&!ce.current?.contains(re)&&!re?.closest?.("[data-token-popover]")&&z(!1),N&&!de.current?.contains(re)&&!re?.closest?.("[data-balance-trigger]")&&P(!1)};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[U,O,N]);const mt=l.useCallback(Y=>{if(!Y||He.length<=1)return;const $=Y.getBoundingClientRect(),re=220,We=16;ue({top:$.bottom+8,left:Math.min(Math.max(We,$.right-re),window.innerWidth-re-We)}),W(_=>!_)},[He.length]),Rt=l.useCallback(()=>H(Y=>!Y),[]);l.useEffect(()=>{if(!he||A===null||typeof window>"u")return;const Y=`spiceflow:withdraw-chain:${he.receiptTokenId||he.address.toLowerCase()}`;window.localStorage.setItem(Y,String(A))},[he,A]);const Ge=Q&&V&&D.isAddress(V)?V:G||ge,Be=he?.balanceFormatted??0,rt=l.useCallback(Y=>{if(!Y)return;const $=Y.getBoundingClientRect();ee({top:$.bottom+8,left:$.right-220}),P(!0)},[]),Wt=he?.displaySymbol||he?.receiptTokenName||he?.symbol||"spiceUSDC",dt=he?.displayChainName||"Spicenet",Qe=he?.receiptTokenDecimals??he?.decimals,Me=l.useMemo(()=>{if(!be||!Qe)return 0n;try{return D.parseUnits(S||"0",Qe)}catch{return 0n}},[S,be,Qe]),ut=l.useMemo(()=>!be||!Qe?0n:qo(Me,Qe,be.decimals),[be,Qe,Me]),At=l.useMemo(()=>{const Y=gt??fe;return!Y||Y<=0n||!be||!Qe?0n:qo(Y,be.decimals,Qe)},[gt,fe,be,Qe]),Ve=l.useMemo(()=>Me+At,[Me,At]),Ht=gt??fe,Le=l.useCallback(Y=>{if(!A||!be)return[];if(Me===0n||ut===0n||!Ge)return[];const $=Array.isArray(Y)?Y.filter(Ce=>Ce.amount>0n):[{token:be.address,recipient:Ge,amount:Y??ut}],re=$.reduce((Ce,Ne)=>Ce+Ne.amount,0n);if(re<=0n)return[];const We={chainId:A,calls:[],tokenTransfers:$.map(Ce=>({from:"escrow",to:Ce.recipient,token:Ce.token,amount:Ce.amount}))};if(!u)return[We];const _=u({destinationChainId:A,deliveryToken:be.address,deliveryAmount:re,deliveryRecipient:Ge,deliveryTransfers:$,requestTimestampMs:nt.current??Date.now()});return _?[_,We]:[We]},[A,be,Me,ut,Ge,u]),bt=l.useMemo(()=>Le(),[Le]),Nt=l.useMemo(()=>Hi(bt,be?.address),[bt,be?.address]),at=l.useRef(null),Te=l.useRef(0);l.useEffect(()=>{let Y=!1;if(!e||h||ze||!be||!A||Me===0n){at.current=null,De(null),yt(null),Fe(!1);return}if(bt.length===0){at.current=null,De(null),Fe(!0);return}if(!Nt){at.current=null,De(null),yt(null),Fe(!1);return}if(at.current===Nt)return;at.current=Nt;const $=++Te.current;return(async()=>{Fe(!0),yt(null);try{const re=await Ki({batches:bt,tokenAddress:be.address,chainId:A,estimate:we});if(Y||$!==Te.current)return;De(re)}catch(re){if(Y||$!==Te.current)return;at.current=null,De(null),yt(re instanceof Error?re.message:"Failed to estimate gas fee")}finally{!Y&&$===Te.current&&Fe(!1)}})(),()=>{Y=!0}},[e,h,ze,be,we,Me,bt,Nt]),l.useEffect(()=>{ze||xt(null)},[ze,S,A,be?.address]);const pt=l.useCallback(()=>{I(!0),w("select")},[]),ft=l.useCallback(()=>{t()},[t]),it=l.useRef(null);it.current={batches:bt,walletAddress:ne,recipient:Ge,token:be,chainId:A,amount:S,receiveAmountRaw:ut,gasFee:fe,isNon7702:h,buildWithdrawBatches:Le,execution:{estimate:we,execute:ke},ui:{setIsExecuting:Ze,setExecutionError:le,setExecutionProgress:Ke,setLockedGasFee:xt},executionContextRef:et,isMountedRef:ae,onWithdrawExecute:r,onWithdrawSuccess:a,buildSpicenetBatch:u};const Je=l.useCallback(()=>(nt.current=Date.now(),Xo(it.current)),[]),It=l.useCallback(()=>(nt.current=Date.now(),Zi(it.current)),[]);if(l.useEffect(()=>{if(!e){const Y=setTimeout(()=>{w(R()),I(!1),j(null),E(null),M(""),W(!1),z(!1),K(!1),X(""),Ze(!1),le(null),Ke(null),et.current=null},300);return()=>clearTimeout(Y)}},[e,h]),l.useEffect(()=>{if(!h&&e&&v==="provider-login"&&oe&&Z&&ge&&!T){const Y=setTimeout(()=>{I(!0),w("select")},100);return()=>clearTimeout(Y)}},[h,e,v,oe,Z,ge,T]),!e)return null;if(v==="provider-login"&&!h)return o.jsx(Ds,{onAuthSuccess:pt,autoTrigger:!0});if(v==="select"){const Y=parseFloat(S)||0,$=Qe?Ws(Ve,Qe):S||"0",re=parseFloat($)||0,We=re>0&&re>Be,_=(A?p.getChainConfig(A):null)?.displayName||"Network",Ce=A?Gt[A]||wn:null,Ne=be?.symbol||"\u2014",lt=Wt,Pe=be?Ws(ut,be.decimals):"0",vt=Yo(Y,be?.symbol||he?.symbol),Re=Yo(parseFloat(Pe)||0,be?.symbol||he?.symbol),je=!Q||!V||D.isAddress(V),qe=!h&&Y>0&&be!==null,Ye=!qe||fe!==null&&!Bt&&!Xe,Et=Y>0&&Y<Kt,St=Y>0&&!Et&&!We&&F!==null&&A!==null&&be!==null&&Ge&&je&&Ye&&ut>0n,cn=!St,Dt=F===null?"NO BALANCE":Y===0?"ENTER AMOUNT":Et?`MINIMUM ${Kt}`:We?"INSUFFICIENT BALANCE":qe&&!Ye?Xe?"GAS UNAVAILABLE":"ESTIMATING GAS":qe&&ut===0n?"AMOUNT TOO SMALL":"WITHDRAW",Ut=!!Ae&&(Ae.step==="success"||Ae.step==="error"),wt=s?.primaryColor||y.colors.primary,tn=402,nn=dn=>o.jsx(el,{label:dn,spiceAssetsLoading:Tt,totalSelectedBalance:Be,onOpenBalancePopover:rt,dark:C,dk:k});return o.jsx(Vt,{isOpen:!0,onClose:ft,title:"Withdraw",subtitle:o.jsx(_i,{dark:C,dk:k}),styles:s,theme:y,dark:C,maxWidth:"486px",footerLinkText:"Spicenet accounts \u2192",overlayDimmed:!1,closeOnBackdropClick:n,overlayContent:Ut?o.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,display:"flex",flexDirection:"column",justifyContent:"flex-end",pointerEvents:"none",zIndex:20},children:o.jsx("div",{style:{pointerEvents:"auto"},children:o.jsx(Ms,{type:"withdraw",isOpen:!0,isProcessing:ze,onRetryTx:()=>{It()},onNewTx:()=>{Ke(null),M(""),le(null),et.current=null},onClose:()=>{Ke(null),le(null),Ze(!1),et.current=null},onComplete:()=>{Ke(null),le(null),Ze(!1),et.current=null},results:[{asset:{symbol:be?.symbol||"Token",address:be?.address||""},txHash:Ae?.txHash||"",success:Ae?.step==="success",error:Ae?.error,amount:S}],chainId:A??void 0,theme:y})})}):null,children:o.jsxs("div",{style:{width:`${tn}px`,margin:"0 auto",padding:"0 0 4px 0",position:"relative"},children:[o.jsx(Xi,{show:N,position:L,popoverRef:de,spiceAssets:Oe,dark:C,dk:k}),o.jsxs("div",{style:{marginTop:"16px",marginBottom:"16px",display:"flex",flexDirection:"column",gap:"16px"},children:[o.jsx(nl,{header:nn("Source"),amount:S,setAmount:M,isInsufficient:We,sourceAmountDecimals:Qe,selectedSourceAsset:F,resolvedSelectedSourceAsset:he,spiceAssets:Oe,setSelectedSourceAsset:j,sourceUsdEstimate:vt,sourceTokenLabel:lt,sourceChainLabel:dt,totalSelectedBalance:Be,showSourceTokenPopover:O,setShowSourceTokenPopover:z,tokenPopoverPos:pe,setTokenPopoverPos:Ee,tokenTriggerRef:ce,primaryColor:wt,dark:C,dk:k}),o.jsx(rl,{header:nn("Destination"),amount:S,receiveAmountDisplay:Pe,receiveUsdEstimate:Re,selectedDestToken:be,destTokenSymbol:Ne,destChainName:_,destChainLogo:Ce,compatibleDestinationChains:He,networkSwitchRef:J,onOpenNetworkPopover:mt,showNetworkPopover:U,setShowNetworkPopover:W,networkPopoverPos:ve,selectedChainId:A,setSelectedChainId:E,dark:C,dk:k})]}),o.jsxs("div",{style:{marginBottom:y.spacing.sm},children:[o.jsx($i,{show:xe,onToggle:Rt,showCustomAddress:Q,setShowCustomAddress:K,customRecipient:V,setCustomRecipient:X,externalAddress:G,recipientAddress:Ge,destChainName:_,destChainLogo:Ce,compatibleDestinationChains:He,txDetailsChainSwitchRef:se,onOpenNetworkPopover:mt,sourceChainLabel:dt,sourceDetailsLogo:ds,sourceTokenLabel:lt,amount:S,totalSourceDebitDisplay:$,receiveAmountDisplay:Pe,destTokenSymbol:Ne,shouldQuoteWithdrawGas:qe,estimatingFee:Bt,feeError:Xe,displayedGasFee:Ht,selectedDestToken:be,theme:y,styles:s,dark:C,dk:k}),Ft&&o.jsx(an,{variant:"error",size:"compact",palette:k,fontFamily:s?.fontFamily||y.typography.fontFamily,style:{marginBottom:"12px"},children:Ft}),o.jsx(p.Button,{variant:"outline",fullWidth:!0,onClick:()=>{St&&Je()},disabled:cn||ze,theme:y,dark:C,styles:s,style:{marginTop:"8px"},children:ze?"EXECUTING...":Dt})]})]})})}return null},dl=cl;function sr(e){const t=l.useRef(0),n=l.useRef(e.run);n.current=e.run;const s=l.useRef(e.onSkip);s.current=e.onSkip;const r=l.useRef(e.onCleanup);r.current=e.onCleanup,l.useEffect(()=>{if(!e.shouldRun){t.current+=1,s.current?.();return}let a=!1;const i=c=>{const f=++t.current;n.current({isBackground:c,isCurrent:()=>!a&&t.current===f})},d=window.setTimeout(()=>i(!1),e.delayMs??250),u=e.backgroundIntervalMs?window.setInterval(()=>i(!0),e.backgroundIntervalMs):void 0;return()=>{a=!0,clearTimeout(d),u!==void 0&&window.clearInterval(u),r.current?.()}},[e.shouldRun,e.delayMs,e.backgroundIntervalMs,...e.deps])}async function or(e,t,n){if(n)return{decimals:n.decimals,symbol:n.symbol,name:n.name,logoURI:n.logo};const[s,r,a]=await Promise.all([Pt.readContract(e,{address:t,abi:D.erc20Abi,functionName:"decimals"}).catch(()=>18),Pt.readContract(e,{address:t,abi:D.erc20Abi,functionName:"symbol"}).catch(()=>"TOKEN"),Pt.readContract(e,{address:t,abi:D.erc20Abi,functionName:"name"}).catch(()=>"TOKEN")]);return{decimals:Number(s),symbol:r,name:a,logoURI:void 0}}function ul(e){const{isOpen:t,includeWalletAssets:n,isWhitelistGateActive:s,isSemi7702:r,destinationTokenAddress:a,sourceAssets:i,sourceChains:d,walletAddressForAssets:u,lockChainId:c,lockTokenSymbol:f,lockTokenLogoURI:h}=e,g=l.useMemo(()=>{if(!n)return[];if(s)return a?[D.getAddress(a)]:[];const w=new Set,T=[],I=F=>{if(!F)return;const j=F.toLowerCase();w.has(j)||(w.add(j),T.push(D.getAddress(F)))};a&&I(a);for(const F of i)I(F);return T},[n,r,a,i,s]),x=l.useMemo(()=>g.map(w=>w.toLowerCase()).sort().join(","),[g]),m=l.useMemo(()=>JSON.stringify([...d||[]].sort()),[d]),[y,C]=l.useState([]),k=l.useRef(0),b=l.useRef(async()=>{}),R=l.useCallback(async()=>{if(!n||!u||g.length===0){k.current++,C([]);return}const w=++k.current,T=D.getAddress(u),I=r?d&&d.length>0?d:[c]:[c],F=g.map(W=>{const O=W.toLowerCase();if(a&&p.addressesEqual(W,a)){const z=p.getChainConfig(c)?.supportedTokens?.find(N=>p.addressesEqual(N.address,O));return{address:W,chainId:c,configToken:z?{decimals:z.decimals,symbol:z.symbol,name:z.name,logo:z.logo}:void 0}}for(const z of I){const N=p.getChainConfig(z)?.supportedTokens?.find(P=>p.addressesEqual(P.address,O));if(N)return{address:W,chainId:z,configToken:{decimals:N.decimals,symbol:N.symbol,name:N.name,logo:N.logo}}}return{address:W,chainId:c}}),j=new Map;for(const W of F){const O=j.get(W.chainId)||[];O.push(W),j.set(W.chainId,O)}const A=(W,O)=>{let{symbol:z,name:N,logoURI:P}=O;const Q=!!a&&p.addressesEqual(W.address,a)&&W.chainId===c;return Q&&h&&(P=h),Q&&f&&!W.configToken&&(z==="TOKEN"&&(z=f),N==="TOKEN"&&(N=f)),{symbol:z,name:N,logoURI:P}},E=(W,O,z,N)=>{const P=A(W,N),Q=parseFloat((Number(O)/Math.pow(10,z)).toFixed(6));return{address:W.address,name:P.name,symbol:P.symbol,decimals:z,balance:O,balanceFormatted:Q,balanceUsd:0,logoURI:P.logoURI,isNative:!1,chainId:W.chainId}},S=async(W,O)=>{try{const z=await Pt.readContract(W,{address:O.address,abi:D.erc20Abi,functionName:"balanceOf",args:[T]}),N=await or(W,O.address,O.configToken);return E(O,z,N.decimals,N)}catch{return null}},M=await Promise.all(Array.from(j.entries()).map(async([W,O])=>{let z;try{z=p.getClientForChain(W)}catch{return[]}const N=[],P=[];for(const K of O){const V=N.length;N.push({address:K.address,abi:D.erc20Abi,functionName:"balanceOf",args:[T]}),K.configToken||N.push({address:K.address,abi:D.erc20Abi,functionName:"decimals",args:[]},{address:K.address,abi:D.erc20Abi,functionName:"symbol",args:[]},{address:K.address,abi:D.erc20Abi,functionName:"name",args:[]}),P.push({start:V,item:K})}let Q=null;try{Q=await z.multicall({contracts:N})}catch{Q=null}return Q?P.map(({start:K,item:V})=>{const X=Q[K],xe=X?.status==="success"?X.result:0n;let H,J,se,ce;if(V.configToken)H=V.configToken.decimals,J=V.configToken.symbol,se=V.configToken.name,ce=V.configToken.logo;else{const de=Q[K+1],ve=Q[K+2],ue=Q[K+3];H=de?.status==="success"?Number(de.result):18,J=ve?.status==="success"?ve.result:"TOKEN",se=ue?.status==="success"?ue.result:J}return E(V,xe,H,{symbol:J,name:se,logoURI:ce})}):(await Promise.all(O.map(K=>S(z,K)))).filter(K=>K!==null)}));if(w!==k.current)return;const U=M.flat();C(U)},[n,r,u,x,m,c,a,h,f]);l.useEffect(()=>{b.current=R},[R]),l.useEffect(()=>{if(!t||!n){C([]);return}b.current();const w=setInterval(()=>{b.current()},15e3);return()=>clearInterval(w)},[n,t,u,x,m,c,a]);const v=l.useCallback(()=>{R()},[R]);return{walletAssets:y,refreshWalletAssets:v}}const pl=({options:e,selectedIndex:t,onSelect:n,primaryColor:s,dark:r=!1,textPrimary:a="#111827",textSecondary:i="#6b7280",trackColor:d})=>{const u=e.length-1,c=d||(r?"#3a3a3a":"#d1d5db"),f=r?"4px":"50%",h=r?"none":"2px solid white",g=r?"none":`0 0 0 1px ${s}`;return o.jsxs("div",{style:{width:"100%",userSelect:"none"},children:[o.jsxs("div",{style:{position:"relative",paddingBottom:"4px"},children:[o.jsx("div",{style:{position:"absolute",top:"50%",left:0,right:0,height:"4px",background:c,borderRadius:"2px",transform:"translateY(-50%)",pointerEvents:"none"}}),o.jsx("div",{style:{position:"absolute",top:"50%",left:0,width:`${t/u*100}%`,height:"4px",background:s,borderRadius:"2px",transform:"translateY(-50%)",pointerEvents:"none",transition:"width 0.15s ease"}}),o.jsx("input",{type:"range","aria-label":"Lock duration","aria-valuetext":e[t]?.label,"data-spiceflow-focus":!0,min:0,max:u,step:1,value:t,onChange:x=>n(Number(x.target.value)),style:{WebkitAppearance:"none",appearance:"none",width:"100%",height:"20px",background:"transparent",cursor:"pointer",outline:"none",border:"none",position:"relative",zIndex:1,margin:0,padding:0}})]}),o.jsx("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"6px"},children:e.map((x,m)=>o.jsxs("div",{onClick:()=>n(m),style:{display:"flex",flexDirection:"column",alignItems:m===0?"flex-start":m===u?"flex-end":"center",cursor:"pointer",flex:1},children:[o.jsx("span",{style:{fontSize:"12px",fontWeight:m===t?700:400,color:m===t?a:i,whiteSpace:"nowrap",transition:"color 0.15s, font-weight 0.15s"},children:x.label}),x.highlight&&o.jsx("span",{style:{fontSize:"10px",color:i,whiteSpace:"nowrap"},children:"(most common)"})]},m))}),o.jsx("style",{children:`
|
|
43
|
+
`,Oo=({title:e,showChevron:t,expanded:n,onToggleDetails:s,showClose:r,onClose:a,fontFamily:i,labelColor:d,textPrimary:u,closeHoverBg:c,closePressedBg:f})=>{const[h,g]=l.useState(!1),[x,m]=l.useState(!1);return o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"16px"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:s?"pointer":"default"},onClick:s,children:[o.jsxs("span",{style:{fontSize:"13px",fontWeight:500,color:d,fontFamily:i},children:[e," "]}),t&&o.jsx(on,{color:d,direction:n?"up":"down"})]}),r&&o.jsx("button",{onClick:a,onMouseEnter:()=>g(!0),onMouseLeave:()=>{g(!1),m(!1)},onMouseDown:()=>m(!0),onMouseUp:()=>m(!1),style:{background:x?f:h?c:"none",border:"none",borderRadius:"4px",cursor:"pointer",padding:"4px",display:"flex",alignItems:"center",justifyContent:"center",color:h||x?u:d,transform:x?"scale(0.9)":h?"scale(1.1)":"scale(1)",transition:p.transition.interactive},children:o.jsx(Sn,{size:16})})]})},Ho=({chainName:e,bg:t,border:n,textPrimary:s,labelColor:r,primaryColor:a})=>o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"20px 16px",borderRadius:"8px",backgroundColor:t,border:`1px solid ${n}`,gap:"12px"},children:[o.jsx(p.Spinner,{size:24,borderWidth:3,color:a}),o.jsxs("div",{children:[o.jsx("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:p.font.mono,letterSpacing:"0.5px",color:s},children:"PROCESSING TRANSACTION"}),o.jsxs("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:r},children:["on ",e]})]})]}),Qo=({bg:e,border:t,left:n,right:s})=>o.jsxs("div",{style:{padding:"10px 12px",borderRadius:"6px",backgroundColor:e,border:`1px solid ${t}`,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[n,s]}),Ms=({isOpen:e,onClose:t,onComplete:n,closeOnComplete:s=!1,type:r,results:a,chainId:i,chainName:d,explorerUrl:u,theme:c,styles:f,dark:h,intentStatus:g,onRetry:x,onNewTx:m,onRetryTx:y,asOverlay:C=!0,isProcessing:k=!1,showStepBreakdown:b=!0})=>{const{theme:R,primaryColor:v,dark:w,dk:T}=p.useSpiceBrand(f,h),I=c||R,[F,j]=l.useState(!1),A=d??(i?p.getChainName(i):"Network"),E=u??(i&&p.getExplorerUrl(i,"").replace(/\/tx\/.*$/,"")||void 0),S=w?T.cardBg:"#ffffff",M=w?"0 4px 20px rgba(0, 0, 0, 0.4)":"0 4px 20px rgba(0, 0, 0, 0.1)",U=w?"0 -4px 8px -2px rgba(0, 0, 0, 0.4)":"0 -4px 8px -2px rgba(0, 0, 0, 0.15)",W=T.textSecondary,O=w?T.textPrimary:"#374151",z=w?T.inputBg:"#f9fafb",N=w?T.inputBorder:"#e5e7eb",P=w?T.inputBg:"#f3f4f6",Q=w?T.inputBorder:"#e5e7eb",[K,V]=l.useState(!0),X=w?T.inputBg:"#f9fafb",xe=w?T.hoverBg:"#f3f4f6",H=w?{successBg:T.successBg,successBorder:T.successBorder,successText:T.successText,errorBg:T.errorBg,errorBorder:T.errorBorder,errorText:T.errorText}:{},J=g?.steps.find(pe=>pe.status==="failed")?.error;l.useEffect(()=>{!e&&!g&&j(!1)},[e,g]);const se=()=>{j(!0),setTimeout(()=>{window.dispatchEvent(new CustomEvent("tx-complete",{detail:{type:r,results:a}})),window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:{type:r,status:"success",results:a}})),n?.(),s&&t()},300)},ce=()=>{V(!K)};if(g){const{steps:pe,overallStatus:Ee}=g,L=Ee==="processing",ee=Ee==="success",te=Ee==="failed",oe=pe.filter(G=>G.transactionHash)[0],Z=pe.length>1?pe.map(G=>G.chainName).filter(Boolean).join(" and "):A!=="Network"?A:pe[0]?.chainName||A,ne=E||(oe?p.getExplorerUrl(oe.chainId,oe.transactionHash||"").replace(/\/tx\/.*$/,""):void 0),ge=o.jsxs(o.Fragment,{children:[o.jsx(Oo,{title:L?`Processing ${r.charAt(0).toUpperCase()+r.slice(1)}`:`${r.charAt(0).toUpperCase()+r.slice(1)} results`,showChevron:b,expanded:K,onToggleDetails:ce,showClose:!L,onClose:t,fontFamily:f?.fontFamily||I.typography.fontFamily,labelColor:W,textPrimary:O,closeHoverBg:X,closePressedBg:xe}),o.jsx("div",{style:{marginBottom:"16px"},children:L?o.jsx(Ho,{chainName:Z,bg:P,border:Q,textPrimary:O,labelColor:W,primaryColor:v}):o.jsx(Lo,{isSuccess:ee,type:r,chainName:Z,explorerUrl:ne,txHash:oe?.transactionHash,dark:w,...H,textSecondary:W})}),b&&o.jsx("div",{style:{overflow:"hidden",maxHeight:K?"300px":"0px",opacity:K?1:0,transition:"max-height 0.3s ease, opacity 0.3s ease",marginBottom:K?"16px":"0"},children:o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:pe.map((G,Ie)=>{const ze=G.transactionHash?p.getExplorerUrl(G.chainId,G.transactionHash):null;return o.jsx(Qo,{bg:z,border:N,left:o.jsx("span",{style:{fontSize:"13px",color:O},children:G.chainName?`On ${G.chainName}`:G.description||`Step ${Ie+1}`}),right:o.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:G.status==="success"?"#10b981":G.status==="failed"?"#ef4444":W,fontWeight:500},children:[ze&&o.jsx("a",{href:ze,target:"_blank",rel:"noopener noreferrer",style:{color:w?T.infoText:"#2563eb",textDecoration:"none"},onClick:Ke=>Ke.stopPropagation(),children:"View"}),G.status==="success"?"\u2713":G.status==="failed"?"\u2717":"\u25CB"]})},Ie)})})}),!L&&o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[te&&x&&o.jsx(p.Button,{variant:"outline",fullWidth:!0,onClick:x,theme:I,styles:f,dark:w,children:"TRY AGAIN"}),m&&o.jsxs(p.Button,{variant:"outline",fullWidth:!0,onClick:m,theme:I,styles:f,dark:w,children:["NEW ",r.toUpperCase()," \u2192"]})]})]});return C?o.jsxs("div",{style:{position:"absolute",bottom:0,left:0,right:0,zIndex:10,animation:F?"slideDown 0.3s ease-in forwards":"slideUp 0.3s ease-out forwards",pointerEvents:"auto"},children:[o.jsx("div",{style:{backgroundColor:S,borderRadius:"12px 12px 0 0",width:"100%",padding:"18px 24px 24px",boxShadow:U},children:ge}),o.jsx("style",{children:zo})]}):o.jsx("div",{style:{backgroundColor:S,borderRadius:"12px",padding:"24px",width:"100%",boxShadow:M},children:ge})}if(!e&&!k||!k&&(!a||a.length===0))return null;const de=a?a.every(pe=>pe.success):!1,ve=a?.[0],ue=[...a??[]].reverse().find(pe=>pe.txHash)?.txHash||ve?.txHash;return o.jsxs("div",{style:{position:C?"absolute":"relative",bottom:C?0:void 0,left:C?0:void 0,right:C?0:void 0,zIndex:C?10:void 0,animation:C?F?"slideDown 0.3s ease-in forwards":"slideUp 0.3s ease-out forwards":void 0,pointerEvents:"auto",width:"100%"},children:[o.jsx("div",{style:{backgroundColor:S,borderRadius:C?"12px 12px 0 0":"12px",width:"100%",padding:"18px 0 24px",boxShadow:C?U:M},children:o.jsxs("div",{style:{width:"100%",boxSizing:"border-box",padding:"0 24px"},children:[o.jsx(Oo,{title:k?`Processing ${r.charAt(0).toUpperCase()+r.slice(1)}`:`${r.charAt(0).toUpperCase()+r.slice(1)} results`,showChevron:!k&&b,expanded:K,onToggleDetails:k?void 0:ce,showClose:!k,onClose:t,fontFamily:f?.fontFamily||I.typography.fontFamily,labelColor:W,textPrimary:O,closeHoverBg:X,closePressedBg:xe}),o.jsx("div",{style:{marginBottom:"16px",animation:"statusFadeIn 220ms cubic-bezier(0.22, 1, 0.36, 1) both"},children:k?o.jsx(Ho,{chainName:A,bg:P,border:Q,textPrimary:O,labelColor:W,primaryColor:v}):o.jsx(Lo,{isSuccess:de,type:r,chainName:A,explorerUrl:E,txHash:ue,dark:w,...H,textSecondary:W})},k?"processing":de?"success":"error"),!k&&b&&a&&a.length>1&&o.jsx("div",{style:{overflow:"hidden",maxHeight:K?"200px":"0px",opacity:K?1:0,transition:"max-height 0.3s ease, opacity 0.3s ease",marginBottom:K?"16px":"0"},children:o.jsx("div",{style:{maxHeight:"180px",overflowY:"auto",display:"flex",flexDirection:"column",gap:"8px"},children:a.map((pe,Ee)=>o.jsx(Qo,{bg:z,border:N,left:o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[o.jsx("span",{style:{fontWeight:600,fontSize:"13px",color:T.textPrimary,fontFamily:p.font.mono},children:pe.asset.symbol}),pe.amount&&o.jsx("span",{style:{fontSize:"12px",color:W},children:pe.amount})]}),right:o.jsx("span",{style:{fontSize:"12px",color:pe.success?"#10b981":"#ef4444",fontWeight:500},children:pe.success?"\u2713":"\u2717"})},Ee))})}),!k&&!de&&a&&o.jsx("div",{style:{padding:"12px",backgroundColor:T.errorBg,border:`1px solid ${T.errorBorder}`,borderRadius:"8px",marginBottom:"16px"},children:o.jsx("p",{style:{fontSize:"13px",color:T.errorText,margin:0,lineHeight:1.5},children:J||a.find(pe=>!pe.success)?.error||`${r.charAt(0).toUpperCase()+r.slice(1)} failed. Please try again.`})}),!k&&o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[!de&&y&&o.jsxs(p.Button,{variant:"outline",fullWidth:!0,onClick:y,theme:I,styles:f,dark:w,children:["TRY AGAIN ",r.toUpperCase()]}),de&&o.jsx(p.Button,{variant:"outline",fullWidth:!0,onClick:se,theme:I,styles:f,dark:w,children:"DONE"})]})]})}),o.jsx("style",{children:zo})]})};function zi(e){const t=e.chainTokens??e.chainTokenConfig;if(Array.isArray(t))return t.filter(n=>typeof n=="string");if(t&&typeof t=="object")return t}const jn=({address:e,supportedChains:t,enabled:n=!0,refetchInterval:s})=>{const r=l.useContext(p.SpiceFlowProviderContext)?.apiUrl||p.RELAYER_API_URL,[a,i]=l.useState([]),[d,u]=l.useState(!1),[c,f]=l.useState(null),[h,g]=l.useState(!1),x=l.useRef(!1),m=l.useRef(!1),y=t?JSON.stringify([...t].sort()):"",C=l.useCallback(async(R=!1)=>{if(!e||!n){i([]),g(!1),x.current=!1;return}if(!m.current){m.current=!0,!x.current&&!R&&u(!0),f(null);try{const v=await p.relayerFetch(`${r}/wallets/${e}/balance`,{cache:"no-store"});if(!v.ok)throw new Error(`Failed to fetch balance: ${v.status}`);const w=await v.json();if(w.balances&&Array.isArray(w.balances)){const T=w.balances.map(I=>Xa({receiptToken:typeof I.receiptToken=="string"?I.receiptToken:void 0,tokenName:String(I.tokenName??""),balanceAvailable:String(I.balanceAvailable??"0"),chainTokens:zi(I),decimals:typeof I.decimals=="number"?I.decimals:void 0,balanceUsd:typeof I.balanceUsd=="number"||typeof I.balanceUsd=="string"?I.balanceUsd:null},t)).filter(I=>I!==null);i(T),g(T.length>0),x.current=!0}else i([]),g(!1)}catch(v){const w=v instanceof Error?v.message:"Failed to fetch balance";f(w),console.error("Error fetching Spice assets:",v),x.current||(i([]),g(!1))}finally{u(!1),m.current=!1}}},[e,n,y,r]);l.useEffect(()=>{n&&e&&(x.current=!1,C(!1))},[e,n,y]),l.useEffect(()=>{if(!n||!e||!s)return;const R=setInterval(()=>{C(!0)},s);return()=>clearInterval(R)},[e,n,s,y]);const k=l.useCallback(R=>a.filter(v=>v.chainId===R),[a]),b=l.useCallback(async()=>{await C(!0)},[C]);return{assets:a,loading:d,error:c,hasBalance:h,refetch:b,getAssetsByChain:k}};function Vo(e,t,n,s){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const r=10n**BigInt(t-n);return s==="ceil"?(e+r-1n)/r:e/r}const Oi={usdc:1,"usdc.e":1,usdt:1,dai:1,ctusd:1,wbtc:1e5,wcbtc:1e5,cbtc:1e5};function Ws(e,t){return D.formatUnits(e,t).replace(/(\.\d*?[1-9])0+$|\.0+$/,"$1")}function qo(e,t,n){return Vo(e,t,n,"floor")}function Yo(e,t){const n=t?Oi[t.trim().toLowerCase()]??0:0,s=e*n;return s<=0?"$0":s>=1?`$${s.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}`:`$${s.toFixed(4).replace(/0+$/,"").replace(/\.$/,"")}`}function Hi(e,t){return t?JSON.stringify({tokenAddress:t.toLowerCase(),batches:e.map(n=>({chainId:n.chainId,calls:n.calls.map(s=>({to:s.to.toLowerCase(),value:s.value.toString(),data:s.data})),tokenTransfers:(n.tokenTransfers??[]).map(s=>({from:s.from,to:s.to.toLowerCase(),token:s.token.toLowerCase(),amount:s.amount.toString()}))}))}):null}function Qi(e){const t=e.find(n=>B.isSpicenetChainId(n.chainId))?.calls?.[0]?.data;if(!t)return null;try{const n=D.decodeFunctionData({abi:B.spicenetAbi,data:t});return n.functionName!=="createWithdrawalRequest"?null:n.args[0].transfers.map(s=>({token:s.token,recipient:s.to,amount:s.amount}))}catch{return null}}function Vi(e,t){return!e||e.length!==t.length?!1:e.every((n,s)=>{const r=t[s];return n.token.toLowerCase()!==r.token.toLowerCase()||n.recipient.toLowerCase()!==r.recipient.toLowerCase()?!1:n.recipient.toLowerCase()===B.SPICE_GAS_FEE_RECIPIENT.toLowerCase()?Jt(n.amount,r.amount,100n):n.amount===r.amount})}function qi(e,t){const n=e.intents.flatMap(a=>a.batches).filter(a=>{const i=jt(a);return BigInt(a.quotedAmount)>0n||BigInt(a.totalDebit)>0n||i.totalFee>0n}),s=n.filter(a=>a.chainId===t),r=s.length>0?s:n;return r.length===1?r[0]:null}function Yi(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const s=n.token.toLowerCase(),r=n.recipient.toLowerCase(),a=`${s}:${r}`,i=t.get(a);i?i.amount+=n.amount:t.set(a,{...n})}return[...t.values()]}function Zo(e,t){if(!e.token||!e.recipient||e.chainId===null)return null;const n=qi(t,e.chainId);if(!n)return null;const{gasFee:s,bridgeFee:r,spicenetFee:a}=jt(n),i=s+r,d=[{token:e.token.address,recipient:e.recipient,amount:e.receiveAmountRaw}];return i>0n&&d.push({token:e.token.address,recipient:B.SPICE_GAS_FEE_RECIPIENT,amount:i}),a>0n&&d.push({token:e.token.address,recipient:B.SPICE_PLATFORM_FEE_RECIPIENT,amount:a}),Yi(d)}function Ko(e,t,n){const s=Zo(e,t);return!s||Vi(Qi(n),s)?null:e.buildWithdrawBatches(s)}async function Xo(e){if(!(!e.batches.length||!e.walletAddress||!e.recipient)){e.ui.setIsExecuting(!0),e.ui.setExecutionError(null),e.ui.setExecutionProgress(null),e.executionContextRef.current=null,e.ui.setLockedGasFee(e.gasFee);try{let t=e.batches;if(e.isNon7702&&e.onWithdrawExecute)await e.onWithdrawExecute(e.amount);else{if(!e.isNon7702&&!t.some(r=>B.isSpicenetChainId(r.chainId)))throw new Error("Spice withdrawals must include a Spicenet funding batch before the destination chain batch.");const n=e.token?.address||"",s={useCustomTransfers:!0};if(e.buildSpicenetBatch){const r=await e.execution.estimate(t,n,0n,{...s,adjustBatchesForEstimate:({feeEstimate:d,chainBatches:u})=>Ko(e,d,u)}),a=Zo(e,r);a&&(t=e.buildWithdrawBatches(a));const i=r.intents[0]?.batches.find(d=>d.chainId===e.chainId)??r.intents[0]?.batches[0]??null;i&&e.ui.setLockedGasFee(jt(i).totalFee)}else{const r=(await e.execution.estimate(t,n,0n,s)).intents[0]?.batches[0]??null;r&&e.ui.setLockedGasFee(jt(r).totalFee)}await e.execution.execute(t,n,0n,r=>{r.actionId&&r.intentId&&typeof r.intentIndex=="number"&&typeof r.totalSteps=="number"&&(e.executionContextRef.current={actionId:r.actionId,intentId:r.intentId,intentIndex:r.intentIndex,totalSteps:r.totalSteps}),e.ui.setExecutionProgress(r)},void 0,e.buildSpicenetBatch?{...s,adjustBatchesForEstimate:({feeEstimate:r,chainBatches:a})=>Ko(e,r,a)}:s)}Go(e)}catch(t){const n=t instanceof Error?t.message:"Withdraw failed";e.ui.setExecutionError(n)}finally{e.ui.setIsExecuting(!1)}}}function Go(e){window.dispatchEvent(new CustomEvent("withdraw-completed")),e.onWithdrawSuccess?.({token:e.token?.symbol||"",amount:e.amount,chainId:e.chainId})}async function Zi(e){const t=e.executionContextRef.current;if(!t){e.ui.setExecutionProgress(null),await Xo(e);return}e.ui.setIsExecuting(!0),e.ui.setExecutionError(null),e.ui.setExecutionProgress({step:"executing",message:"Resuming existing action...",actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps});try{let n=t.totalSteps;for(let s=0;s<t.totalSteps;s++)if((await p.relayerService.checkStepStatus(t.intentId,s)).data.status!=="success"){n=s;break}if(n>=t.totalSteps)e.ui.setExecutionProgress(s=>({...s||{step:"success",message:"Transaction successful!",actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps},step:"success",message:"Transaction successful!"}));else for(let s=n;s<t.totalSteps;s++){const r=await yo({actionId:t.actionId,intentIndex:t.intentIndex,intentId:t.intentId,stepIndex:s,chainId:e.chainId??void 0,onStatusMessage:(a,i)=>{e.isMountedRef.current&&e.ui.setExecutionProgress({step:"executing",message:a,txHash:i,actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps})}});if(!e.isMountedRef.current)return;e.ui.setExecutionProgress({step:s===t.totalSteps-1?"success":"executing",message:s===t.totalSteps-1?"Transaction successful!":"Executing remaining steps...",txHash:r,actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps})}Go(e)}catch(n){const s=n instanceof Error?n.message:"Withdraw failed";e.ui.setExecutionError(s)}finally{e.ui.setIsExecuting(!1)}}async function Ki(e){const t=await e.estimate(e.batches,e.tokenAddress,0n,{useCustomTransfers:!0}),n=t.intents.flatMap(r=>r.batches).filter(r=>jt(r).totalFee>0n),s=n.filter(r=>r.chainId===e.chainId)[0]??n[0]??t.intents[0]?.batches[0];if(!s)throw new Error("No gas fee estimate was returned for this withdraw.");return jt(s).totalFee}const Jo=p.font.mono,$o=p.font.ui,Xi=({show:e,position:t,popoverRef:n,spiceAssets:s,dark:r,dk:a})=>{if(!e||!t)return null;const i=r?a.textSecondary:"#71757A",d=r?a.textPrimary:"#0E0D0B",u=s||[];return o.jsxs("div",{ref:n,"data-balance-popover":!0,style:{position:"fixed",top:`${t.top}px`,left:`${t.left}px`,width:"220px",background:r?a.cardBg:"#FFFFFF",border:`1px solid ${r?a.cardBorder:"#D6D6D6"}`,borderRadius:"10px",boxShadow:r?"0 12px 32px rgba(0,0,0,0.32)":"0 12px 28px rgba(15, 23, 42, 0.14)",padding:"10px",zIndex:40},children:[o.jsx("div",{style:{fontFamily:Jo,fontSize:"11px",letterSpacing:"0.05em",color:i,marginBottom:"8px"},children:"ALL BALANCES"}),o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:u.length>0?u.map(c=>{const f=c.displaySymbol||c.receiptTokenName||c.symbol;return o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"10px",padding:"6px 0"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0},children:[c.logoURI?o.jsx("img",{src:c.logoURI,alt:f,style:{width:"18px",height:"18px",borderRadius:"50%",flexShrink:0}}):o.jsx("div",{style:{width:"18px",height:"18px",borderRadius:"50%",border:`1px solid ${r?a.cardBorder:"#C8C8C8"}`,flexShrink:0}}),o.jsx("span",{style:{fontFamily:$o,fontSize:"13px",color:d,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:f})]}),o.jsx("span",{style:{fontFamily:Jo,fontSize:"12px",color:d,flexShrink:0},children:p.formatBalance(c.balanceFormatted)})]},c.receiptTokenId||c.address)}):o.jsx("span",{style:{fontFamily:$o,fontSize:"13px",color:i},children:"No balances"})})]})},Gi=p.font.ui,$t=p.font.mono,Ji=({show:e,onToggle:t,showCustomAddress:n,setShowCustomAddress:s,customRecipient:r,setCustomRecipient:a,externalAddress:i,recipientAddress:d,destChainName:u,destChainLogo:c,compatibleDestinationChains:f,txDetailsChainSwitchRef:h,onOpenNetworkPopover:g,sourceChainLabel:x,sourceDetailsLogo:m,sourceTokenLabel:y,amount:C,totalSourceDebitDisplay:k,receiveAmountDisplay:b,destTokenSymbol:R,shouldQuoteWithdrawGas:v,estimatingFee:w,feeError:T,displayedGasFee:I,selectedDestToken:F,theme:j,styles:A,dark:E,dk:S})=>{const M=E?S.textSecondary:"#71757A",U=E?S.textPrimary:"#0E0D0B",W=f.length>1,O=n&&r?D.isAddress(r)?p.truncateAddress(r):r:d?p.truncateAddress(d):"\u2014";return o.jsxs(o.Fragment,{children:[o.jsxs("div",{onClick:t,style:{display:"flex",alignItems:"center",gap:"6px",marginBottom:e?"10px":"0",cursor:"pointer",userSelect:"none"},children:[o.jsx("span",{style:{fontSize:"13px",color:M,fontFamily:Gi,fontWeight:600},children:"Transaction Details"}),o.jsx(sa,{size:12,color:M,style:{transform:e?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s"}})]}),e&&o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"7px"},children:[o.jsxs("div",{children:[o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[o.jsx("span",{style:{fontSize:"12px",color:M,fontFamily:$t,fontWeight:500,letterSpacing:"0.03em"},children:"TO"}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[o.jsx("span",{style:{fontSize:"13px",color:U,fontFamily:$t,fontWeight:500},children:O}),o.jsx("button",{onClick:()=>{s(z=>!z),!n&&i&&a(i)},style:{background:"none",border:"none",cursor:"pointer",padding:"0",fontSize:"9.5px",fontFamily:$t,color:M,textDecoration:"underline",fontWeight:600},children:n?"Reset":"Switch"})]})]}),n&&o.jsxs("div",{style:{marginTop:"6px"},children:[o.jsx("div",{style:{marginBottom:"6px",padding:"7px 9px",borderRadius:"6px",border:"1px solid rgba(239, 68, 68, 0.55)",backgroundColor:"rgba(239, 68, 68, 0.12)",color:"#ef4444",fontSize:"10px",lineHeight:1.35,fontFamily:$t,fontWeight:700,letterSpacing:0,textTransform:"uppercase"},children:"CAUTION: ENTERING AN INCORRECT ADDRESS WILL RESULT IN LOSS OF FUNDS"}),o.jsx("input",{type:"text",autoComplete:"off",spellCheck:!1,"aria-label":"Recipient address","aria-invalid":r&&!D.isAddress(r)?!0:void 0,"data-spiceflow-focus":!0,value:r,onChange:z=>a(z.target.value),placeholder:"0x...",style:{width:"100%",padding:"8px 10px",borderRadius:"6px",border:`1px solid ${r&&!D.isAddress(r)?E?S.errorBorder:"#fca5a5":E?S.inputBorder:"#d1d5db"}`,backgroundColor:E?S.inputBg:"#f9fafb",color:E?S.inputText:"#111827",fontSize:"12px",fontFamily:$t,outline:"none",boxSizing:"border-box"}}),r&&!D.isAddress(r)&&o.jsx("span",{style:{fontSize:"11px",color:S.errorText,marginTop:"3px",display:"block"},children:"Invalid address"})]})]}),o.jsx(gn,{palette:S,labelColor:M,valueColor:U,label:"RECEIVING CHAIN",value:o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"7px"},children:[c&&o.jsx("img",{src:c,alt:u,style:{width:"14px",height:"14px",borderRadius:"50%"}}),o.jsx("span",{style:{fontSize:"13px",color:U,fontWeight:500,fontFamily:$t,textTransform:"uppercase"},children:u}),o.jsx("button",{ref:h,onClick:z=>{z.stopPropagation(),g(h.current)},style:{background:"none",border:"none",cursor:W?"pointer":"not-allowed",padding:"0",fontSize:"9.5px",fontFamily:$t,color:M,textDecoration:"underline",fontWeight:600,opacity:W?1:.45},children:"Switch"})]})}),o.jsx(gn,{palette:S,labelColor:M,valueColor:U,label:"REQUESTED WITHDRAWAL",value:o.jsxs(Ns,{logo:m||null,alt:x,primaryText:U,children:[C||"0"," ",y]})}),v&&o.jsx(gn,{palette:S,labelColor:M,valueColor:U,label:"TOTAL SOURCE DEBIT",value:o.jsxs(Ns,{logo:m||null,alt:x,primaryText:U,children:[k," ",y]})}),o.jsx(gn,{palette:S,labelColor:M,valueColor:U,label:"YOU RECEIVE",value:o.jsxs(Ns,{logo:c,alt:u,primaryText:U,gap:"4px",children:[b," ",R]})}),v&&o.jsxs(o.Fragment,{children:[o.jsx(gn,{palette:S,labelColor:M,label:"EST. GAS FEE",valueColor:T?"#f87171":U,value:w?"Estimating...":T?"Unavailable":I!==null&&F?`${Ws(I,F.decimals)} ${F.symbol}`:"Estimating..."}),T&&o.jsx(an,{variant:"error",size:"compact",palette:S,fontFamily:A?.fontFamily||j.typography.fontFamily,children:T})]})]})]})},$i=l.memo(Ji),Ns=({logo:e,alt:t,primaryText:n,gap:s="6px",children:r})=>o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:s},children:[e&&o.jsx("img",{src:e,alt:t,style:{width:"13px",height:"13px",borderRadius:"50%"}}),o.jsx("span",{style:{fontSize:"13px",color:n,fontWeight:500,fontFamily:$t},children:r})]}),_i=({dark:e,dk:t})=>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,...e?{filter:"invert(0.6)"}:{}}}),o.jsx("p",{style:{fontSize:"13px",color:e?t.textSecondary:"#979AA0",margin:"0",lineHeight:"1.4",fontFamily:p.font.ui},children:"Withdraw collateral from your account to 10+ EVM blockchains."})]}),_o=p.font.ui,el=({label:e,spiceAssetsLoading:t,totalSelectedBalance:n,onOpenBalancePopover:s,dark:r,dk:a})=>{const i=r?a.textSecondary:"#7D7C7B",d=r?a.textSecondary:"#71757A";return o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[o.jsx("span",{style:{fontFamily:_o,fontSize:"17px",fontWeight:500,color:i,lineHeight:"24px"},children:e}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",fontFamily:_o,fontSize:"13px",fontWeight:500,color:d,lineHeight:"16px"},children:["Balance:"," ",t?"...":p.formatBalance(n),o.jsx("button",{type:"button","data-balance-trigger":!0,onClick:u=>{u.stopPropagation(),s(u.currentTarget)},style:{width:"15px",height:"15px",borderRadius:"999px",border:"1px solid #EA4B4B",color:"#EA4B4B",display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:"9px",fontWeight:500,lineHeight:1,boxSizing:"border-box",background:"transparent",padding:0,cursor:"pointer"},children:o.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"1.5px"},children:[0,1,2].map(u=>o.jsx("span",{style:{width:"1.75px",height:"1.75px",borderRadius:"999px",backgroundColor:"#EA4B4B",display:"block"}},u))})})]})]})},er=({isOpen:e,position:t,title:n,items:s,selectedId:r,onSelect:a,portalAttribute:i})=>{const{dark:d,dk:u,primaryColor:c}=p.useSpiceBrand(),[f,h]=l.useState(null),[g,x]=l.useState(!1);return l.useEffect(()=>{if(!e){x(!1);return}const m=requestAnimationFrame(()=>{requestAnimationFrame(()=>x(!0))});return()=>cancelAnimationFrame(m)},[e]),!e||!t||s.length===0?null:Cn.createPortal(o.jsxs("div",{[`data-${i}-popover`]:"true",style:{position:"fixed",top:`${t.top}px`,left:`${t.left}px`,opacity:g?1:0,transform:g?"scale(1) translateY(0)":"scale(0.96) translateY(-6px)",transition:`opacity 200ms ${p.easing.out}, transform 200ms ${p.easing.out}`,backgroundColor:d?u.shell:"#ffffff",borderRadius:"10px",padding:"10px 12px",boxShadow:d?"0 16px 48px rgba(0,0,0,0.45)":"0 12px 32px rgba(0,0,0,0.12)",border:`1px solid ${u.cardBorder}`,minWidth:"220px",zIndex:p.z.dropdown,fontFamily:p.font.mono},children:[o.jsx("div",{style:{marginBottom:"6px"},children:o.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:d?u.textPrimary:"#0e0d0b",textTransform:"uppercase",letterSpacing:"1px"},children:n})}),o.jsx("div",{style:{borderBottom:`1px solid ${u.cardBorder}`,marginBottom:"6px"}}),o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"2px"},children:s.map(m=>{const y=r===m.id,C=f===m.id;return o.jsxs("button",{onClick:k=>{k.stopPropagation(),a(m.id)},onMouseEnter:()=>h(m.id),onMouseLeave:()=>h(null),style:{display:"flex",alignItems:"center",gap:"8px",padding:"6px 4px",borderRadius:"8px",border:"none",cursor:"pointer",backgroundColor:y?d?u.hoverBg:"#f3f4f6":C?d?u.cardBg:"#f9fafb":"transparent",transition:"background-color 0.15s",width:"100%",fontFamily:p.font.mono},children:[m.icon&&o.jsx("img",{src:m.icon,alt:m.label,style:{width:"22px",height:"22px",borderRadius:"50%"}}),o.jsx("span",{style:{fontSize:"13px",fontWeight:y?700:500,textTransform:"uppercase",color:d?u.textPrimary:"#0e0d0b",letterSpacing:"0.5px",flex:1,textAlign:"left"},children:m.label}),m.detail&&o.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:u.textSecondary},children:m.detail}),y&&o.jsx(_s,{color:c,style:{flexShrink:0}})]},m.id)})})]}),document.body)},Fn=p.font.ui,tl=170,nl=({header:e,amount:t,setAmount:n,isInsufficient:s,sourceAmountDecimals:r,selectedSourceAsset:a,resolvedSelectedSourceAsset:i,spiceAssets:d,setSelectedSourceAsset:u,sourceUsdEstimate:c,sourceTokenLabel:f,sourceChainLabel:h,totalSelectedBalance:g,showSourceTokenPopover:x,setShowSourceTokenPopover:m,tokenPopoverPos:y,setTokenPopoverPos:C,tokenTriggerRef:k,primaryColor:b,dark:R,dk:v})=>{const w=R?v.cardBg:"#E9E9E9",T=R?v.cardBorder:"#C6C6C6",I=R?v.textSecondary:"#71757A",F=R?v.textPrimary:"#0E0D0B",j=R?v.cardBorder:"#C5C5C4",A=R?"rgba(255,255,255,0.08)":"#D4D3D3",E=f.length>8?"14px":f.length>6?"16px":"18px";return o.jsxs("div",{style:{backgroundColor:w,border:`1px solid ${T}`,borderRadius:"7px",padding:"14px 16px 12px 16px",minHeight:"138px",display:"flex",flexDirection:"column",gap:"6px",position:"relative"},children:[e,o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[o.jsxs("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[o.jsx(rn,{element:"input",ariaLabel:"Withdraw amount",ariaInvalid:s,dataSpiceflowFocus:!0,value:t,onChange:S=>{const M=S.target.value;if(M===""){n("");return}/^\d*\.?\d*$/.test(M)&&n(p.parseNumericInput(M.startsWith(".")?`0${M}`:M,r??a?.decimals))},placeholder:"0.0",fontFamily:Fn,color:s?"#ef4444":t?F:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,style:{width:"100%"}}),o.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:I,fontFamily:Fn,marginTop:"10px"},children:c})]}),o.jsx("div",{style:{width:`${tl}px`,flexShrink:0},children:o.jsxs("div",{style:{backgroundColor:"transparent",border:`1px solid ${j}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[o.jsxs("div",{ref:k,onClick:S=>{if(S.stopPropagation(),!x&&k.current){const M=k.current.getBoundingClientRect(),U=220,W=16;C({top:M.bottom+8,left:Math.min(Math.max(W,M.right-U),window.innerWidth-U-W)})}m(M=>!M)},style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px",cursor:"pointer"},children:[o.jsx("img",{src:ds,alt:f,style:{width:"24px",height:"24px",borderRadius:"50%"}}),o.jsx("span",{style:{fontSize:E,fontWeight:500,color:F,lineHeight:"1.3",fontFamily:Fn,flex:1,minWidth:0,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",letterSpacing:0},children:f}),o.jsx(on,{size:15,color:F,strokeWidth:2.25})]}),o.jsx(er,{isOpen:x,position:y,title:"SELECT TOKEN",portalAttribute:"token",items:(d||[]).map(S=>({id:S.receiptTokenId||S.address,label:S.displaySymbol||S.receiptTokenName||S.symbol,icon:ds,detail:p.formatBalance(S.balanceFormatted)})),selectedId:i?.receiptTokenId||i?.address||null,onSelect:S=>{const M=(d||[]).find(U=>(U.receiptTokenId||U.address)===S);M&&(u(M),n("")),m(!1)}}),o.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:A,borderTop:`1px solid ${j}`},children:o.jsx("span",{style:{fontSize:"11px",fontWeight:400,color:F,fontFamily:Fn,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:h})})]})})]}),o.jsxs("div",{style:{minHeight:"18px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[s?o.jsx("span",{style:{fontSize:"12px",color:v.errorText,fontFamily:Fn,fontWeight:500},children:"Insufficient Balance"}):o.jsx("span",{}),o.jsx("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0px",minHeight:"32px",marginRight:"-9px"},children:[0,25,50,75,100].map((S,M)=>{const U=M===4,W=parseFloat(t)||0,O=g>0&&Math.abs(W/g*100-S)<1;return o.jsx("button",{type:"button","aria-label":`Set amount to ${S}%`,"aria-pressed":O,onClick:()=>{const z=g*S/100,N=a?.decimals??6,P=Math.floor(z*10**N)/10**N;n(S===0?"":P>0?p.formatDecimalInput(P,N):"")},title:`${S}%`,disabled:g===0,"data-spiceflow-focus":!0,style:{width:"32px",height:"32px",padding:"9px",border:"none",backgroundColor:"transparent",cursor:g===0?"not-allowed":"pointer",opacity:O?1:.5,transition:"opacity 0.15s ease",display:"flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box"},children:o.jsx(cs,{pct:S,isMax:U,primaryColor:b,dark:R,fillColor:R?v.textSecondary:"#3C3E42"})},S)})})]})]})},Xn=p.font.ui,sl=p.font.mono,ol=170,rl=({header:e,amount:t,receiveAmountDisplay:n,receiveUsdEstimate:s,selectedDestToken:r,destTokenSymbol:a,destChainName:i,destChainLogo:d,compatibleDestinationChains:u,networkSwitchRef:c,onOpenNetworkPopover:f,showNetworkPopover:h,setShowNetworkPopover:g,networkPopoverPos:x,selectedChainId:m,setSelectedChainId:y,dark:C,dk:k})=>{const b=C?k.cardBg:"#E9E9E9",R=C?k.cardBorder:"#C6C6C6",v=C?k.textSecondary:"#71757A",w=C?k.textPrimary:"#0E0D0B",T=C?k.cardBorder:"#C5C5C4",I=C?"rgba(255,255,255,0.08)":"#D4D3D3",F=a.length>8?"14px":a.length>6?"16px":"18px";return o.jsxs("div",{style:{backgroundColor:b,border:`1px solid ${R}`,borderRadius:"7px",padding:"14px 16px 12px 16px",minHeight:"138px",display:"flex",flexDirection:"column",gap:"6px"},children:[e,o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[o.jsxs("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[o.jsx(rn,{element:"div",value:n,title:n,fontFamily:Xn,color:t?w:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,overflow:"wrap"}),o.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:v,fontFamily:Xn,marginTop:"10px"},children:s})]}),o.jsxs("div",{style:{width:`${ol}px`,flexShrink:0,display:"flex",flexDirection:"column",alignItems:"stretch",gap:"8px"},children:[o.jsxs("div",{style:{backgroundColor:"transparent",border:`1px solid ${T}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px"},children:[o.jsx("img",{src:r?.logoURI||fa,alt:a,style:{width:"24px",height:"24px",borderRadius:"50%"}}),o.jsx("span",{style:{fontSize:F,fontWeight:500,color:w,lineHeight:"1.3",fontFamily:Xn,flex:1,minWidth:0,letterSpacing:0},children:a})]}),o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:I,borderTop:`1px solid ${T}`},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[d&&o.jsx("img",{src:d,alt:i,style:{width:"13px",height:"13px",borderRadius:"50%",flexShrink:0}}),o.jsx("span",{style:{fontSize:"11px",fontWeight:400,color:w,fontFamily:Xn,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:i})]}),o.jsx("button",{ref:c,onClick:j=>{j.stopPropagation(),f(c.current)},style:{background:"none",border:"none",cursor:u.length>1?"pointer":"not-allowed",padding:"0 0 0 8px",fontSize:"9.5px",fontFamily:sl,color:v,textDecoration:"underline",fontWeight:600,opacity:u.length>1?1:.45},children:"Switch"}),o.jsx(er,{isOpen:h,position:x,title:"SELECT NETWORK",portalAttribute:"network",items:u.map(j=>{const A=p.getChainConfig(j);return{id:String(j),label:A?.displayName||String(j),icon:Gt[j]||wn}}),selectedId:m!==null?String(m):null,onSelect:j=>{y(Number(j)),g(!1)}})]})]}),o.jsx("div",{style:{minHeight:"14px"}})]})]})]})};function tr(e){const t=new Set(B.getEquivalentAddresses(e).map(n=>n.toLowerCase()));return t.add(e.toLowerCase()),t}const al=["USDC","USDT","WETH","WBTC"];function nr(e,t){const n=p.getChainConfig(t);if(!n)return;if(n.nativeCurrency.symbol.toUpperCase()===e.toUpperCase())return{address:B.ZERO_ADDRESS,symbol:n.nativeCurrency.symbol,decimals:n.nativeCurrency.decimals,chainId:t};const s=n.supportedTokens?.find(r=>r.symbol.toUpperCase()===e.toUpperCase());if(s)return{address:s.address.toLowerCase(),symbol:s.symbol,decimals:s.decimals,chainId:t}}function Xt(e,t,n){const s=p.getChainConfig(t);if(!s)return;if(n!==void 0){const i=mo(e,n,t);if(i)return{address:i.address.toLowerCase(),symbol:i.symbol,decimals:i.decimals,chainId:t}}const r=tr(e);if([...r].some(i=>B.isNativeToken(i)))return{address:B.ZERO_ADDRESS,symbol:s.nativeCurrency.symbol,decimals:s.nativeCurrency.decimals,chainId:t};const a=s.supportedTokens?.find(i=>r.has(i.address.toLowerCase()));if(a)return{address:a.address.toLowerCase(),symbol:a.symbol,decimals:a.decimals,chainId:t}}function il(e){const{sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:r,intermediaryCandidates:a=al}=e;if(Ln(t,n))return{strategy:"direct",sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:r,summary:`${t.symbol} fronted directly`};if(Xt(t.address,r,s))return{strategy:"direct",sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:r,summary:`${t.symbol} fronted on destination, swapped to ${n.symbol}`};if(Xt(n.address,s,r))return{strategy:"source-swap",sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:r,summary:`${t.symbol} \u2192 ${n.symbol} on source chain, then fronted`};for(const i of a){const d=nr(i,s);if(!d||Ln(t,d)||Ln(n,d))continue;const u=nr(i,r);if(u&&Ln(d,u))return{strategy:"intermediary",sourceAsset:t,outputAsset:n,intermediaryAsset:u,sourceChainId:s,destinationChainId:r,summary:`${t.symbol} \u2192 ${i} on source, fronted, then ${i} \u2192 ${n.symbol} on destination`}}throw new p.SpiceflowError("ROUTE_STRATEGY_ERROR",`No viable cross-chain route found from ${t.symbol} (chain ${s}) to ${n.symbol} (chain ${r}). No intermediary asset is available on both chains.`,{sourceAsset:t.symbol,outputAsset:n.symbol,sourceChainId:s,destinationChainId:r,candidatesChecked:a})}async function ll(e){const{route:t,sourceAmount:n,userAddress:s,registry:r,actionCalls:a,slippage:i}=e;async function d(u,c,f,h){const g=r.getVenueForChain(u);if(!g)throw new p.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${u}. Cannot resolve swap ${c} \u2192 ${f}.`,{chainId:u,tokenIn:c,tokenOut:f,amountIn:h.toString()});const x=await g.resolve({type:"swap",tokenIn:c,tokenOut:f,amountIn:h,maxSlippage:i},u,s);if(!x)throw new p.SpiceflowError("NO_LIQUIDITY",`${g.name} returned no quote for ${c} \u2192 ${f} on chain ${u}. No liquidity available for this pair.`,{venue:g.name,chainId:u,tokenIn:c,tokenOut:f,amountIn:h.toString()});return x}switch(t.strategy){case"direct":{const u=Xt(t.sourceAsset.address,t.destinationChainId,t.sourceChainId)||t.sourceAsset;if(tr(u.address).has(t.outputAsset.address.toLowerCase()))return{chainBatches:[{chainId:t.destinationChainId,calls:a}],solverFrontToken:u,solverFrontAmount:n,resolvedSwaps:{}};const c=await d(t.destinationChainId,u.address,t.outputAsset.address,n);return{chainBatches:[{chainId:t.destinationChainId,calls:[...c.calls,...a]}],solverFrontToken:u,solverFrontAmount:n,resolvedSwaps:{destinationSwap:c}}}case"source-swap":{const u=Xt(t.outputAsset.address,t.sourceChainId,t.destinationChainId);if(!u)throw new p.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Output asset ${t.outputAsset.symbol} (${t.outputAsset.address}) not found on source chain ${t.sourceChainId}`,{token:t.outputAsset.symbol,address:t.outputAsset.address,chainId:t.sourceChainId,side:"source"});const c=Xt(t.outputAsset.address,t.destinationChainId,t.destinationChainId);if(!c)throw new p.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Output asset ${t.outputAsset.symbol} (${t.outputAsset.address}) not found on destination chain ${t.destinationChainId}`,{token:t.outputAsset.symbol,address:t.outputAsset.address,chainId:t.destinationChainId,side:"destination"});const f=await d(t.sourceChainId,t.sourceAsset.address,u.address,n);return{chainBatches:[{chainId:t.sourceChainId,calls:f.calls},{chainId:t.destinationChainId,calls:a}],solverFrontToken:c,solverFrontAmount:f.amountOutMinimum,resolvedSwaps:{sourceSwap:f}}}case"intermediary":{if(!t.intermediaryAsset)throw new p.SpiceflowError("ROUTE_STRATEGY_ERROR","Intermediary strategy requires an intermediary asset but none was provided in the route plan.",{strategy:t.strategy});const u=Xt(t.intermediaryAsset.address,t.sourceChainId,t.destinationChainId);if(!u)throw new p.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Intermediary ${t.intermediaryAsset.symbol} (${t.intermediaryAsset.address}) not found on source chain ${t.sourceChainId}`,{token:t.intermediaryAsset.symbol,address:t.intermediaryAsset.address,chainId:t.sourceChainId,side:"source"});const c=await d(t.sourceChainId,t.sourceAsset.address,u.address,n),f=await d(t.destinationChainId,t.intermediaryAsset.address,t.outputAsset.address,c.amountOutMinimum);return{chainBatches:[{chainId:t.sourceChainId,calls:c.calls},{chainId:t.destinationChainId,calls:[...f.calls,...a]}],solverFrontToken:t.intermediaryAsset,solverFrontAmount:c.amountOutMinimum,resolvedSwaps:{sourceSwap:c,destinationSwap:f}}}default:throw new p.SpiceflowError("ROUTE_STRATEGY_ERROR",`Unknown route strategy: ${t.strategy}`,{strategy:t.strategy})}}const cl=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,styles:s,onWithdrawExecute:r,onWithdrawSuccess:a,onWithdrawError:i,availableTokens:d,buildSpicenetBatch:u})=>{const c=l.useContext(p.SpiceFlowProviderContext);if(!c)return o.jsx("div",{children:"Error: SpiceWithdraw must be used within SpiceFlowProvider"});const f=c.mode||"7702",h=f==="presign"||f==="ondemand",g=c.supportedChainIds,x=c.allowedTokens,m=c.isWhitelistGateActive,{theme:y,dark:C,dk:k}=p.useSpiceBrand(s),b=c.network,R=()=>h?"select":"provider-login",[v,w]=l.useState(R()),[T,I]=l.useState(!1),[F,j]=l.useState(null),[A,E]=l.useState(null),[S,M]=l.useState(""),[U,W]=l.useState(!1),[O,z]=l.useState(!1),[N,P]=l.useState(!1),[Q,K]=l.useState(!1),[V,X]=l.useState(""),[xe,H]=l.useState(!0),J=l.useRef(null),se=l.useRef(null),ce=l.useRef(null),de=l.useRef(null),[ve,ue]=l.useState(null),[pe,Ee]=l.useState(null),[L,ee]=l.useState(null),te=p.useWallet(),{isReady:oe,isAuthenticated:Z,address:ne}=te,ge=c?.embeddedWalletAddress,{address:G,chainId:Ie}=Qt.useAccount(),[ze,Ke]=l.useState(!1),[Ft,mt]=l.useState(null),Le=l.useRef(i);Le.current=i;const le=l.useCallback(Y=>{mt(Y),typeof Y=="string"&&Y&&Le.current?.(Y,p.getRelayerErrorDetail(Y))},[]),[Ae,Xe]=l.useState(null),et=l.useRef(null),ae=l.useRef(!0),nt=l.useRef(null);l.useEffect(()=>(ae.current=!0,()=>{ae.current=!1}),[]);const{execute:ke,estimate:we}=mn(),[fe,Me]=l.useState(null),[xt,yt]=l.useState(null),[Bt,Fe]=l.useState(!1),[Ge,Ct]=l.useState(null),{assets:kt,loading:Tt}=jn({address:ge,enabled:e&&!!ge,refetchInterval:3e4}),Oe=l.useMemo(()=>{if(m)return[];if(!x||x.length===0)return kt;const Y=new Set(x.map($=>$.toLowerCase()));return(kt||[]).filter($=>[$.symbol,$.displaySymbol,$.receiptTokenName].some(re=>typeof re=="string"&&Y.has(re.toLowerCase())))},[kt,x,m]),st=l.useMemo(()=>[...new Set([...g??[],...Object.keys(d??{}).map(Number),...(Oe||[]).map(Y=>Y.chainId),...(Oe||[]).flatMap(Y=>Object.keys(Y.chainTokens??{}).map($=>{const[,re]=$.split(":"),Ne=Number(re);return Number.isFinite(Ne)?Ne:null}).filter($=>$!==null))])].filter(Y=>p.getChainConfig(Y)?.network===b),[g,d,Oe,b]),Mt=l.useMemo(()=>{if(d)return d;const Y={};for(const $ of Oe||[]){const re=Object.entries($.chainTokens??{});if(re.length>0){for(const[Ne,_]of re){const[Ce,Pe,lt]=Ne.split(":");if(Ce!=="evm"||!Pe||!lt)continue;const Ue=Number(Pe);if(!Number.isFinite(Ue))continue;const vt=lt.startsWith("0x")?lt.toLowerCase():`0x${lt.toLowerCase()}`,Re=p.getChainConfig(Ue)?.supportedTokens?.find(je=>p.addressesEqual(je.address,vt));Re&&ys($,vt,Ue)&&(Y[Ue]||(Y[Ue]=[]),Y[Ue].find(je=>p.addressesEqual(je.address,vt))||Y[Ue].push({address:vt,symbol:Re?.symbol||_?.name||$.symbol,name:Re?.name||_?.name||$.displayName||$.name||$.symbol,decimals:Re?.decimals??_?.decimals??$.decimals,logoURI:Re?.logo||$.logoURI}))}continue}Y[$.chainId]||(Y[$.chainId]=[]),Y[$.chainId].find(Ne=>p.addressesEqual(Ne.address,$.address))||Y[$.chainId].push({address:$.address,symbol:$.symbol,name:$.displayName||$.name||$.symbol,decimals:$.decimals,logoURI:$.logoURI})}return Y},[d,Oe]),bt=l.useCallback((Y,$)=>{if(!Y||!$)return null;const re=Un(Y,$),Ne=Object.entries(Y.chainTokens??{}).flatMap(([Re,je])=>{const Ye=hn(Re);return Ye?.chainId===$?[{parsed:Ye,detail:je}]:[]}),_=Mt?.[$]||[],Ce=Re=>_.find(je=>p.addressesEqual(je.address,Re))??null,Pe=Re=>{const je=p.getChainConfig($)?.supportedTokens?.find(Ze=>p.addressesEqual(Ze.address,Re));if(!je||!ys(Y,Re,$))return null;const Ye=Ne.find(({parsed:Ze})=>p.addressesEqual(Ze.address,Re));return Ye?{address:Ye.parsed.address,symbol:je.symbol,name:je.name||Ye.detail?.name||Y.displayName||Y.name||Y.symbol,decimals:je.decimals,logoURI:je.logo||Y.logoURI}:null};for(const Re of re){const je=Ce(Re);if(je)return je;const Ye=Pe(Re);if(Ye)return Ye}const lt=zt(Y,$);if(lt){const Re=Ce(lt);if(Re)return Re;const je=Pe(lt);if(je)return je}const Ue=Xt(Y.address,$,Y.chainId);return Ue?Ce(Ue.address)||(_.length>0?null:{address:Ue.address,symbol:Ue.symbol||Y.symbol,name:Y.displayName||Y.name||Y.symbol,decimals:Ue.decimals??Y.decimals,logoURI:Y.logoURI}):null},[Mt]),he=l.useMemo(()=>{if(!F)return null;const Y=F.receiptTokenId||`${F.chainId}:${F.address.toLowerCase()}`;return Oe.find($=>($.receiptTokenId||`${$.chainId}:${$.address.toLowerCase()}`)===Y)||F},[F,Oe]),He=l.useMemo(()=>{if(!he)return[];const Y=Object.keys(he.chainTokens??{}).map($=>hn($)?.chainId??null).filter($=>$!==null);return Array.from(new Set([...Y,he.chainId,...st].filter(Number.isFinite))).filter($=>$!==1&&p.getChainConfig($)?.network===b&&bt(he,$)!==null)},[he,st,bt,b]),ot=l.useMemo(()=>{if(!he||typeof window>"u")return null;const Y=`spiceflow:withdraw-chain:${he.receiptTokenId||he.address.toLowerCase()}`,$=window.localStorage.getItem(Y),re=$?Number($):null;return re!==null&&Number.isFinite(re)&&He.includes(re)?re:null},[he,He]),ct=l.useMemo(()=>he?ot!==null?ot:Ie&&He.includes(Ie)?Ie:he.chainId&&He.includes(he.chainId)?he.chainId:He[0]??st[0]??null:st[0]??null,[he,ot,Ie,He,st]),be=l.useMemo(()=>bt(he,A),[bt,he,A]);l.useEffect(()=>{!Oe?.length||he||j(Oe[0])},[Oe,he]),l.useEffect(()=>{he&&(A===null||!He.includes(A))&&E(ct)},[he,A,ct,He]),l.useEffect(()=>{if(!U&&!O&&!N)return;const Y=$=>{const re=$.target;U&&!J.current?.contains(re)&&!se.current?.contains(re)&&!re?.closest?.("[data-network-popover]")&&W(!1),O&&!ce.current?.contains(re)&&!re?.closest?.("[data-token-popover]")&&z(!1),N&&!de.current?.contains(re)&&!re?.closest?.("[data-balance-trigger]")&&P(!1)};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[U,O,N]);const gt=l.useCallback(Y=>{if(!Y||He.length<=1)return;const $=Y.getBoundingClientRect(),re=220,Ne=16;ue({top:$.bottom+8,left:Math.min(Math.max(Ne,$.right-re),window.innerWidth-re-Ne)}),W(_=>!_)},[He.length]),Rt=l.useCallback(()=>H(Y=>!Y),[]);l.useEffect(()=>{if(!he||A===null||typeof window>"u")return;const Y=`spiceflow:withdraw-chain:${he.receiptTokenId||he.address.toLowerCase()}`;window.localStorage.setItem(Y,String(A))},[he,A]);const Je=Q&&V&&D.isAddress(V)?V:G||ge,Be=he?.balanceFormatted??0,rt=l.useCallback(Y=>{if(!Y)return;const $=Y.getBoundingClientRect();ee({top:$.bottom+8,left:$.right-220}),P(!0)},[]),Wt=he?.displaySymbol||he?.receiptTokenName||he?.symbol||"spiceUSDC",dt=he?.displayChainName||"Spicenet",Qe=he?.receiptTokenDecimals??he?.decimals,We=l.useMemo(()=>{if(!be||!Qe)return 0n;try{return D.parseUnits(S||"0",Qe)}catch{return 0n}},[S,be,Qe]),ut=l.useMemo(()=>!be||!Qe?0n:qo(We,Qe,be.decimals),[be,Qe,We]),At=l.useMemo(()=>{const Y=xt??fe;return!Y||Y<=0n||!be||!Qe?0n:qo(Y,be.decimals,Qe)},[xt,fe,be,Qe]),Ve=l.useMemo(()=>We+At,[We,At]),Ht=xt??fe,De=l.useCallback(Y=>{if(!A||!be)return[];if(We===0n||ut===0n||!Je)return[];const $=Array.isArray(Y)?Y.filter(Ce=>Ce.amount>0n):[{token:be.address,recipient:Je,amount:Y??ut}],re=$.reduce((Ce,Pe)=>Ce+Pe.amount,0n);if(re<=0n)return[];const Ne={chainId:A,calls:[],tokenTransfers:$.map(Ce=>({from:"escrow",to:Ce.recipient,token:Ce.token,amount:Ce.amount}))};if(!u)return[Ne];const _=u({destinationChainId:A,deliveryToken:be.address,deliveryAmount:re,deliveryRecipient:Je,deliveryTransfers:$,requestTimestampMs:nt.current??Date.now()});return _?[_,Ne]:[Ne]},[A,be,We,ut,Je,u]),pt=l.useMemo(()=>De(),[De]),Nt=l.useMemo(()=>Hi(pt,be?.address),[pt,be?.address]),at=l.useRef(null),Te=l.useRef(0);l.useEffect(()=>{let Y=!1;if(!e||h||ze||!be||!A||We===0n){at.current=null,Me(null),Ct(null),Fe(!1);return}if(pt.length===0){at.current=null,Me(null),Fe(!0);return}if(!Nt){at.current=null,Me(null),Ct(null),Fe(!1);return}if(at.current===Nt)return;at.current=Nt;const $=++Te.current;return(async()=>{Fe(!0),Ct(null);try{const re=await Ki({batches:pt,tokenAddress:be.address,chainId:A,estimate:we});if(Y||$!==Te.current)return;Me(re)}catch(re){if(Y||$!==Te.current)return;at.current=null,Me(null),Ct(re instanceof Error?re.message:"Failed to estimate gas fee")}finally{!Y&&$===Te.current&&Fe(!1)}})(),()=>{Y=!0}},[e,h,ze,be,we,We,pt,Nt]),l.useEffect(()=>{ze||yt(null)},[ze,S,A,be?.address]);const ft=l.useCallback(()=>{I(!0),w("select")},[]),ht=l.useCallback(()=>{t()},[t]),it=l.useRef(null);it.current={batches:pt,walletAddress:ne,recipient:Je,token:be,chainId:A,amount:S,receiveAmountRaw:ut,gasFee:fe,isNon7702:h,buildWithdrawBatches:De,execution:{estimate:we,execute:ke},ui:{setIsExecuting:Ke,setExecutionError:le,setExecutionProgress:Xe,setLockedGasFee:yt},executionContextRef:et,isMountedRef:ae,onWithdrawExecute:r,onWithdrawSuccess:a,buildSpicenetBatch:u};const qe=l.useCallback(()=>(nt.current=Date.now(),Xo(it.current)),[]),It=l.useCallback(()=>(nt.current=Date.now(),Zi(it.current)),[]);if(l.useEffect(()=>{if(!e){const Y=setTimeout(()=>{w(R()),I(!1),j(null),E(null),M(""),W(!1),z(!1),K(!1),X(""),Ke(!1),le(null),Xe(null),et.current=null},300);return()=>clearTimeout(Y)}},[e,h]),l.useEffect(()=>{if(!h&&e&&v==="provider-login"&&oe&&Z&&ge&&!T){const Y=setTimeout(()=>{I(!0),w("select")},100);return()=>clearTimeout(Y)}},[h,e,v,oe,Z,ge,T]),!e)return null;if(v==="provider-login"&&!h)return o.jsx(Ds,{onAuthSuccess:ft,autoTrigger:!0});if(v==="select"){const Y=parseFloat(S)||0,$=Qe?Ws(Ve,Qe):S||"0",re=parseFloat($)||0,Ne=re>0&&re>Be,_=(A?p.getChainConfig(A):null)?.displayName||"Network",Ce=A?Gt[A]||wn:null,Pe=be?.symbol||"\u2014",lt=Wt,Ue=be?Ws(ut,be.decimals):"0",vt=Yo(Y,be?.symbol||he?.symbol),Re=Yo(parseFloat(Ue)||0,be?.symbol||he?.symbol),je=!Q||!V||D.isAddress(V),Ye=!h&&Y>0&&be!==null,Ze=!Ye||fe!==null&&!Bt&&!Ge,Et=Y>0&&Y<Kt,St=Y>0&&!Et&&!Ne&&F!==null&&A!==null&&be!==null&&Je&&je&&Ze&&ut>0n,cn=!St,Dt=F===null?"NO BALANCE":Y===0?"ENTER AMOUNT":Et?`MINIMUM ${Kt}`:Ne?"INSUFFICIENT BALANCE":Ye&&!Ze?Ge?"GAS UNAVAILABLE":"ESTIMATING GAS":Ye&&ut===0n?"AMOUNT TOO SMALL":"WITHDRAW",Ut=!!Ae&&(Ae.step==="success"||Ae.step==="error"),wt=s?.primaryColor||y.colors.primary,tn=402,nn=dn=>o.jsx(el,{label:dn,spiceAssetsLoading:Tt,totalSelectedBalance:Be,onOpenBalancePopover:rt,dark:C,dk:k});return o.jsx(Vt,{isOpen:!0,onClose:ht,title:"Withdraw",subtitle:o.jsx(_i,{dark:C,dk:k}),styles:s,theme:y,dark:C,maxWidth:"486px",footerLinkText:"Spicenet accounts \u2192",overlayDimmed:!1,closeOnBackdropClick:n,overlayContent:Ut?o.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,display:"flex",flexDirection:"column",justifyContent:"flex-end",pointerEvents:"none",zIndex:20},children:o.jsx("div",{style:{pointerEvents:"auto"},children:o.jsx(Ms,{type:"withdraw",isOpen:!0,isProcessing:ze,onRetryTx:()=>{It()},onNewTx:()=>{Xe(null),M(""),le(null),et.current=null},onClose:()=>{Xe(null),le(null),Ke(!1),et.current=null},onComplete:()=>{Xe(null),le(null),Ke(!1),et.current=null},results:[{asset:{symbol:be?.symbol||"Token",address:be?.address||""},txHash:Ae?.txHash||"",success:Ae?.step==="success",error:Ae?.error,amount:S}],chainId:A??void 0,theme:y})})}):null,children:o.jsxs("div",{style:{width:`${tn}px`,margin:"0 auto",padding:"0 0 4px 0",position:"relative"},children:[o.jsx(Xi,{show:N,position:L,popoverRef:de,spiceAssets:Oe,dark:C,dk:k}),o.jsxs("div",{style:{marginTop:"16px",marginBottom:"16px",display:"flex",flexDirection:"column",gap:"16px"},children:[o.jsx(nl,{header:nn("Source"),amount:S,setAmount:M,isInsufficient:Ne,sourceAmountDecimals:Qe,selectedSourceAsset:F,resolvedSelectedSourceAsset:he,spiceAssets:Oe,setSelectedSourceAsset:j,sourceUsdEstimate:vt,sourceTokenLabel:lt,sourceChainLabel:dt,totalSelectedBalance:Be,showSourceTokenPopover:O,setShowSourceTokenPopover:z,tokenPopoverPos:pe,setTokenPopoverPos:Ee,tokenTriggerRef:ce,primaryColor:wt,dark:C,dk:k}),o.jsx(rl,{header:nn("Destination"),amount:S,receiveAmountDisplay:Ue,receiveUsdEstimate:Re,selectedDestToken:be,destTokenSymbol:Pe,destChainName:_,destChainLogo:Ce,compatibleDestinationChains:He,networkSwitchRef:J,onOpenNetworkPopover:gt,showNetworkPopover:U,setShowNetworkPopover:W,networkPopoverPos:ve,selectedChainId:A,setSelectedChainId:E,dark:C,dk:k})]}),o.jsxs("div",{style:{marginBottom:y.spacing.sm},children:[o.jsx($i,{show:xe,onToggle:Rt,showCustomAddress:Q,setShowCustomAddress:K,customRecipient:V,setCustomRecipient:X,externalAddress:G,recipientAddress:Je,destChainName:_,destChainLogo:Ce,compatibleDestinationChains:He,txDetailsChainSwitchRef:se,onOpenNetworkPopover:gt,sourceChainLabel:dt,sourceDetailsLogo:ds,sourceTokenLabel:lt,amount:S,totalSourceDebitDisplay:$,receiveAmountDisplay:Ue,destTokenSymbol:Pe,shouldQuoteWithdrawGas:Ye,estimatingFee:Bt,feeError:Ge,displayedGasFee:Ht,selectedDestToken:be,theme:y,styles:s,dark:C,dk:k}),Ft&&o.jsx(an,{variant:"error",size:"compact",palette:k,fontFamily:s?.fontFamily||y.typography.fontFamily,style:{marginBottom:"12px"},children:Ft}),o.jsx(p.Button,{variant:"outline",fullWidth:!0,onClick:()=>{St&&qe()},disabled:cn||ze,theme:y,dark:C,styles:s,style:{marginTop:"8px"},children:ze?"EXECUTING...":Dt})]})]})})}return null},dl=cl;function sr(e){const t=l.useRef(0),n=l.useRef(e.run);n.current=e.run;const s=l.useRef(e.onSkip);s.current=e.onSkip;const r=l.useRef(e.onCleanup);r.current=e.onCleanup,l.useEffect(()=>{if(!e.shouldRun){t.current+=1,s.current?.();return}let a=!1;const i=c=>{const f=++t.current;n.current({isBackground:c,isCurrent:()=>!a&&t.current===f})},d=window.setTimeout(()=>i(!1),e.delayMs??250),u=e.backgroundIntervalMs?window.setInterval(()=>i(!0),e.backgroundIntervalMs):void 0;return()=>{a=!0,clearTimeout(d),u!==void 0&&window.clearInterval(u),r.current?.()}},[e.shouldRun,e.delayMs,e.backgroundIntervalMs,...e.deps])}async function or(e,t,n){if(n)return{decimals:n.decimals,symbol:n.symbol,name:n.name,logoURI:n.logo};const[s,r,a]=await Promise.all([Pt.readContract(e,{address:t,abi:D.erc20Abi,functionName:"decimals"}).catch(()=>18),Pt.readContract(e,{address:t,abi:D.erc20Abi,functionName:"symbol"}).catch(()=>"TOKEN"),Pt.readContract(e,{address:t,abi:D.erc20Abi,functionName:"name"}).catch(()=>"TOKEN")]);return{decimals:Number(s),symbol:r,name:a,logoURI:void 0}}function ul(e){const{isOpen:t,includeWalletAssets:n,isWhitelistGateActive:s,isSemi7702:r,destinationTokenAddress:a,sourceAssets:i,sourceChains:d,walletAddressForAssets:u,lockChainId:c,lockTokenSymbol:f,lockTokenLogoURI:h}=e,g=l.useMemo(()=>{if(!n)return[];if(s)return a?[D.getAddress(a)]:[];const w=new Set,T=[],I=F=>{if(!F)return;const j=F.toLowerCase();w.has(j)||(w.add(j),T.push(D.getAddress(F)))};a&&I(a);for(const F of i)I(F);return T},[n,r,a,i,s]),x=l.useMemo(()=>g.map(w=>w.toLowerCase()).sort().join(","),[g]),m=l.useMemo(()=>JSON.stringify([...d||[]].sort()),[d]),[y,C]=l.useState([]),k=l.useRef(0),b=l.useRef(async()=>{}),R=l.useCallback(async()=>{if(!n||!u||g.length===0){k.current++,C([]);return}const w=++k.current,T=D.getAddress(u),I=r?d&&d.length>0?d:[c]:[c],F=g.map(W=>{const O=W.toLowerCase();if(a&&p.addressesEqual(W,a)){const z=p.getChainConfig(c)?.supportedTokens?.find(N=>p.addressesEqual(N.address,O));return{address:W,chainId:c,configToken:z?{decimals:z.decimals,symbol:z.symbol,name:z.name,logo:z.logo}:void 0}}for(const z of I){const N=p.getChainConfig(z)?.supportedTokens?.find(P=>p.addressesEqual(P.address,O));if(N)return{address:W,chainId:z,configToken:{decimals:N.decimals,symbol:N.symbol,name:N.name,logo:N.logo}}}return{address:W,chainId:c}}),j=new Map;for(const W of F){const O=j.get(W.chainId)||[];O.push(W),j.set(W.chainId,O)}const A=(W,O)=>{let{symbol:z,name:N,logoURI:P}=O;const Q=!!a&&p.addressesEqual(W.address,a)&&W.chainId===c;return Q&&h&&(P=h),Q&&f&&!W.configToken&&(z==="TOKEN"&&(z=f),N==="TOKEN"&&(N=f)),{symbol:z,name:N,logoURI:P}},E=(W,O,z,N)=>{const P=A(W,N),Q=parseFloat((Number(O)/Math.pow(10,z)).toFixed(6));return{address:W.address,name:P.name,symbol:P.symbol,decimals:z,balance:O,balanceFormatted:Q,balanceUsd:0,logoURI:P.logoURI,isNative:!1,chainId:W.chainId}},S=async(W,O)=>{try{const z=await Pt.readContract(W,{address:O.address,abi:D.erc20Abi,functionName:"balanceOf",args:[T]}),N=await or(W,O.address,O.configToken);return E(O,z,N.decimals,N)}catch{return null}},M=await Promise.all(Array.from(j.entries()).map(async([W,O])=>{let z;try{z=p.getClientForChain(W)}catch{return[]}const N=[],P=[];for(const K of O){const V=N.length;N.push({address:K.address,abi:D.erc20Abi,functionName:"balanceOf",args:[T]}),K.configToken||N.push({address:K.address,abi:D.erc20Abi,functionName:"decimals",args:[]},{address:K.address,abi:D.erc20Abi,functionName:"symbol",args:[]},{address:K.address,abi:D.erc20Abi,functionName:"name",args:[]}),P.push({start:V,item:K})}let Q=null;try{Q=await z.multicall({contracts:N})}catch{Q=null}return Q?P.map(({start:K,item:V})=>{const X=Q[K],xe=X?.status==="success"?X.result:0n;let H,J,se,ce;if(V.configToken)H=V.configToken.decimals,J=V.configToken.symbol,se=V.configToken.name,ce=V.configToken.logo;else{const de=Q[K+1],ve=Q[K+2],ue=Q[K+3];H=de?.status==="success"?Number(de.result):18,J=ve?.status==="success"?ve.result:"TOKEN",se=ue?.status==="success"?ue.result:J}return E(V,xe,H,{symbol:J,name:se,logoURI:ce})}):(await Promise.all(O.map(K=>S(z,K)))).filter(K=>K!==null)}));if(w!==k.current)return;const U=M.flat();C(U)},[n,r,u,x,m,c,a,h,f]);l.useEffect(()=>{b.current=R},[R]),l.useEffect(()=>{if(!t||!n){C([]);return}b.current();const w=setInterval(()=>{b.current()},15e3);return()=>clearInterval(w)},[n,t,u,x,m,c,a]);const v=l.useCallback(()=>{R()},[R]);return{walletAssets:y,refreshWalletAssets:v}}const pl=({options:e,selectedIndex:t,onSelect:n,primaryColor:s,dark:r=!1,textPrimary:a="#111827",textSecondary:i="#6b7280",trackColor:d})=>{const u=e.length-1,c=d||(r?"#3a3a3a":"#d1d5db"),f=r?"4px":"50%",h=r?"none":"2px solid white",g=r?"none":`0 0 0 1px ${s}`;return o.jsxs("div",{style:{width:"100%",userSelect:"none"},children:[o.jsxs("div",{style:{position:"relative",paddingBottom:"4px"},children:[o.jsx("div",{style:{position:"absolute",top:"50%",left:0,right:0,height:"4px",background:c,borderRadius:"2px",transform:"translateY(-50%)",pointerEvents:"none"}}),o.jsx("div",{style:{position:"absolute",top:"50%",left:0,width:`${t/u*100}%`,height:"4px",background:s,borderRadius:"2px",transform:"translateY(-50%)",pointerEvents:"none",transition:"width 0.15s ease"}}),o.jsx("input",{type:"range","aria-label":"Lock duration","aria-valuetext":e[t]?.label,"data-spiceflow-focus":!0,min:0,max:u,step:1,value:t,onChange:x=>n(Number(x.target.value)),style:{WebkitAppearance:"none",appearance:"none",width:"100%",height:"20px",background:"transparent",cursor:"pointer",outline:"none",border:"none",position:"relative",zIndex:1,margin:0,padding:0}})]}),o.jsx("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"6px"},children:e.map((x,m)=>o.jsxs("div",{onClick:()=>n(m),style:{display:"flex",flexDirection:"column",alignItems:m===0?"flex-start":m===u?"flex-end":"center",cursor:"pointer",flex:1},children:[o.jsx("span",{style:{fontSize:"12px",fontWeight:m===t?700:400,color:m===t?a:i,whiteSpace:"nowrap",transition:"color 0.15s, font-weight 0.15s"},children:x.label}),x.highlight&&o.jsx("span",{style:{fontSize:"10px",color:i,whiteSpace:"nowrap"},children:"(most common)"})]},m))}),o.jsx("style",{children:`
|
|
44
44
|
input[type='range']::-webkit-slider-thumb {
|
|
45
45
|
-webkit-appearance: none;
|
|
46
46
|
width: 20px;
|
|
@@ -77,9 +77,9 @@
|
|
|
77
77
|
from { transform: rotate(0deg); }
|
|
78
78
|
to { transform: rotate(360deg); }
|
|
79
79
|
}
|
|
80
|
-
`})]})};function xl(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const s=D.getAddress(n.token),r=D.getAddress(n.to),a=`${s.toLowerCase()}:${r.toLowerCase()}`,i=t.get(a);i?i.amount+=n.amount:t.set(a,{token:s,to:r,amount:n.amount})}return[...t.values()]}function yl(e,t){return`0x${t}${e.slice(4)}`}function ar(e,t){return ir(e,t)}function ir(e,t,n){const s=On(t,e),r=Math.floor(Date.now()/1e3)+60*10,a=B.hashChainBatches(s);return{user:e,...n?{chainAuthorizations:n}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:"0x00",nbf:0,exp:r,chainBatches:a.map((i,d)=>({hash:i.hash,chainId:i.chainId,tokenTransfers:s[d].domain==="spicenet"?[]:s[d].tokenTransfers??[],calls:i.calls}))}]}}function _t(e,t,n,s){if(e.some(f=>f.domain==="spicenet"))return e;const r=n?.intents.flatMap(f=>f.batches),a=f=>f.from==="escrow",i=e.map(f=>{const h=r?.find(v=>v.chainId===f.chainId);if(!h)return f;const g=jt(h),x=g.totalFee;if(x<=0n)return f;const m=(f.tokenTransfers??[]).find(v=>a(v)&&D.getAddress(v.to).toLowerCase()===t.toLowerCase()&&!B.isNativeToken(D.getAddress(v.token)));if(!m)return f;const y=D.getAddress(m.token);let C=!1;const k=(f.tokenTransfers??[]).map(v=>C||!a(v)||D.getAddress(v.to).toLowerCase()!==t.toLowerCase()||D.getAddress(v.token).toLowerCase()!==y.toLowerCase()?v:(C=!0,{...v,amount:s?.payoutAlreadyGross?BigInt(v.amount):BigInt(v.amount)+x}));if(!C)return f;const b=[];g.spicenetFee>0n&&b.push({to:y,value:0n,data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"transfer",args:[B.SPICE_PLATFORM_FEE_RECIPIENT,g.spicenetFee]})});const R=g.gasFee+g.bridgeFee;return R>0n&&b.push({to:y,value:0n,data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"transfer",args:[B.SPICE_GAS_FEE_RECIPIENT,R]})}),{...f,tokenTransfers:k,calls:[...b,...f.calls]}}),d=i.flatMap(f=>(f.tokenTransfers??[]).filter(a).map(h=>{const g=D.getAddress(h.token),x=D.getAddress(h.to),m=[{token:g,to:x,amount:BigInt(h.amount)}];return{chainId:f.chainId,transfers:xl(m)}}));if(d.length===0)return e;const u=s?.requestTimestampMs??Date.now(),c=BigInt(Math.floor(u/1e3))+3600n;return[{chainId:B.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:d.map((f,h)=>{const g=D.keccak256(D.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,f.transfers[0].token,f.transfers.reduce((m,y)=>m+y.amount,0n),BigInt(f.chainId),BigInt(u+h)])),x=yl(g,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:D.encodeFunctionData({abi:B.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${f.chainId}`,idempotenceKey:x,nbf:0n,exp:c,metadata:"{}",transfers:f.transfers.map(m=>({token:m.token.toLowerCase(),to:m.to,amount:m.amount}))}]})}})},...i]}const Cl=60*60;function Ps(e,t){return t?e.some(n=>(n.tokenTransfers??[]).some(s=>s.from==="escrow"&&BigInt(s.amount)>=t.grossAmount)):!1}function lr(e){return!e.isSemi7702&&e.isDirectDeposit&&!e.isSourceDestToken}function cr(e){const t=e.selectedAsset?.asset,n=e.selectedAsset?.amount;if(!(!t||!n))return D.parseUnits(n,t.decimals)}async function Gn({user:e,batches:t,authorizations:n,adjustBatchesForEstimate:s}){let r=t;for(let a=0;a<10;a+=1){const i=await p.relayerService.estimateActionFees(ir(e,r,n)),d=await s({feeEstimate:i,batches:r});if(!d||bo(r,d))return r;r=d}throw new Error("Fee estimate did not converge. Please retry.")}function bl(e){return{chainId:e.sourceChainId,calls:e.isNative?[{to:e.target,value:e.amount,data:"0x"}]:[{to:e.tokenAddr,value:0n,data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"transfer",args:[e.target,e.amount]})}]}}function Us(e,t,n,s){const r=e.selectedAsset.asset,a=D.parseUnits(e.selectedAsset.amount,r.decimals),i=r.chainId,d=e.escrowAddress||B.getEscrowContractAddress(i),u=B.normalizeNativeTokenAddress(r.address),c=r.isNative||B.isNativeToken(u),f=n.some(h=>h.tokenTransfers?.some(g=>g.from==="escrow"));return{asset:r,userNetAmountWei:a,sourceChainId:i,tokenAddr:u,isNative:c,hasEscrowBackedPayout:f,composeBatches:(h,g,x,m)=>{const y=bl({sourceChainId:i,target:d,tokenAddr:u,isNative:c,amount:h});if(!f)return[y,...g];const C=_t([...g],t,x,{payoutAlreadyGross:Ps(g,m),...s!==void 0?{requestTimestampMs:s}:{}});return[y,...C]}}}function Ls(e){const t={};return{state:t,adjustBatchesForEstimate:({feeEstimate:n})=>{const s=bs(n,{symbol:e.symbol,decimals:e.decimals,actionAmount:e.actionAmount});if(!s)return null;t.plan={grossAmount:s.grossAmount,netAmount:s.netAmount,feeAmount:s.totalFee??0n};const r=en(e.ctx,t.plan);return e.rebuild(r,n,t.plan)}}}function en(e,t){const n=e.selectedAsset?.asset;if(!n||!e.selectedAsset?.amount)throw new Error("Select an asset and enter an amount");const s=D.parseUnits(e.selectedAsset.amount,n.decimals),r=t?.grossAmount??s;return e.resolveLockBatches({amount:e.selectedAsset.amount,amountWei:s,grossAmount:D.formatUnits(r,n.decimals),grossAmountWei:r})}async function zs(e,t,n){const s=e.isSemi7702&&e.embeddedWalletAddress||e.address;if(!e.isConnected||!s)throw new Error("Please connect your wallet to continue");if(t.length===0)throw new Error("No lock batches configured");if(!e.ready||!e.authenticated)throw new Error(`Please authenticate with ${e.provider||"wallet provider"} to continue`);const r=n??await In({chainBatches:t,signingAddress:s,actions:e.actions}),a=B.hashChainBatches(t),i=Math.floor(Date.now()/1e3)+Cl,d={mode:"7702",signatureType:"ecdsa",signature:await vo(e.actions,t,BigInt(i)),nbf:0,exp:i,chainBatches:a.map((c,f)=>{const h=t[f],g=h.domain==="spicenet";return{hash:c.hash,chainId:c.chainId,tokenTransfers:g?[]:h.tokenTransfers??[],calls:c.calls}})},u=await p.relayerService.createAction({user:s,chainAuthorizations:r,intents:[d]});if(u){const c=p.createInitialSteps(t,p.getChainName),[f,h]=u.intentIds[0].split("/"),g=parseInt(h||"0",10),x=u.intentIds[0];e.beginStatusTracking(u.intentIds[0],c),await Co({actionId:f,intentIndex:g,intentId:x,totalSteps:t.length,isSpicenetStep:m=>t[m]?.domain==="spicenet",maxExecuteAttemptsForStep:m=>t[m]?.domain==="spicenet"?6:3,onStepUpdate:e.applyStepUpdate,maxPolls:72})}}async function wl(e){const t=en(e);if(t.length===0)throw new Error("No lock batches configured");const n=e.isSemi7702&&e.embeddedWalletAddress||e.address;if(!e.isConnected||!n)throw new Error("Please connect your wallet to continue");const s=await In({chainBatches:t,signingAddress:n,actions:e.actions}),r=Date.now();let a=_t([...t],n,void 0,{requestTimestampMs:r});const i=Ls({ctx:e,actionAmount:cr(e),symbol:e.selectedAsset?.asset.symbol??"",decimals:e.selectedAsset?.asset.decimals??18,rebuild:(d,u,c)=>_t([...d],n,u,{payoutAlreadyGross:Ps(d,c),requestTimestampMs:r})});a=await Gn({user:n,batches:a,authorizations:s,adjustBatchesForEstimate:i.adjustBatchesForEstimate}),await zs(e,a,s)}async function kl(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");const t=e.embeddedWalletAddress||e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");const n=e.resolveLockBatches();if(n.length===0)throw new Error("No lock batches configured");const s=Us(e,t,n,Date.now()),r=Ls({ctx:e,actionAmount:s.userNetAmountWei,symbol:s.asset.symbol,decimals:s.asset.decimals,rebuild:(d,u,c)=>s.composeBatches(c.grossAmount,d,u,c)});let a=s.composeBatches(s.userNetAmountWei,en(e));const i=await In({chainBatches:a,signingAddress:t,actions:e.actions});s.hasEscrowBackedPayout&&(a=await Gn({user:t,batches:a,authorizations:i,adjustBatchesForEstimate:r.adjustBatchesForEstimate})),await zs(e,a,i)}async function vl(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.embeddedWalletAddress;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");if(e.onLockExecute){const m=e.resolveLockBatches();if(m.length===0)throw new Error("No lock batches configured");const y=e.selectedAsset.asset,C=D.parseUnits(e.selectedAsset.amount,y.decimals),k=await e.onLockExecute({asset:y,amount:e.selectedAsset.amount,amountWei:C,lockDurationMonths:e.selectedDuration?.months??0,chainBatches:m});k&&e.onLockSuccess?.(k);return}const n=e.resolveLockBatches();if(n.length===0)throw new Error("No lock batches configured");const s=Us(e,t,n,Date.now()),{userNetAmountWei:r}=s,a=Ls({ctx:e,actionAmount:r,symbol:s.asset.symbol,decimals:s.asset.decimals,rebuild:(m,y,C)=>s.composeBatches(C.grossAmount,m,y,C)});let i=s.composeBatches(r,en(e));const d=await In({chainBatches:i,signingAddress:t,actions:e.actions});s.hasEscrowBackedPayout&&(i=await Gn({user:t,batches:i,authorizations:d,adjustBatchesForEstimate:a.adjustBatchesForEstimate}));const u=a.state.plan?.grossAmount??r,{extWc:c,viemChain:f}=await xn({wallet:e.externalWallet,account:e.externalWalletAddress,chainId:s.sourceChainId}),h=p.getClientForChain(s.sourceChainId),g=m=>js({extWc:c,sourceClient:h,recipient:t,tokenAddr:s.tokenAddr,isNative:s.isNative,amount:m,viemChain:f});await g(u);let x=u;if(s.hasEscrowBackedPayout)for(let m=0;m<4;m+=1){i=await Gn({user:t,batches:i,authorizations:d,adjustBatchesForEstimate:a.adjustBatchesForEstimate});const y=a.state.plan?.grossAmount??r;if(y<=x)break;await g(y-x),x=y}await zs(e,i,d)}async function Sl(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount||!e.requiresRelayerFeeEstimate)return null;if(e.isSemi7702||lr(e)){const a=e.embeddedWalletAddress||e.address;if(!a)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");let i=en(e);if(i.length===0)throw new Error("No lock batches configured");const d=Us(e,a,i),{asset:u,userNetAmountWei:c}=d;let f=d.composeBatches(c,i,void 0,{grossAmount:c,netAmount:0n,feeAmount:0n}),h=null,g;for(let x=0;x<4;x+=1){const m=await p.relayerService.estimateActionFees(ar(a,f)),y=bs(m,{symbol:u.symbol,decimals:u.decimals,actionAmount:c});if(!y)return h;const C={grossAmount:y.grossAmount,netAmount:y.netAmount,feeAmount:y.totalFee??0n},k=g?.grossAmount===C.grossAmount&&g?.netAmount===C.netAmount&&g?.feeAmount===C.feeAmount;if(h=y,g=C,i=en(e,C),f=d.composeBatches(C.grossAmount,i,m,C),k)break}return h}const t=e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");let n=en(e);if(n.length===0)throw new Error("No lock batches configured");let s=_t([...n],t),r=null;for(let a=0;a<4;a+=1){const i=await p.relayerService.estimateActionFees(ar(t,s)),d=bs(i,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:cr(e)});if(!d)return null;const u={grossAmount:d.grossAmount},c=r?.grossAmount===d.grossAmount&&r?.netAmount===d.netAmount&&r?.totalFee===d.totalFee;if(r=d,n=en(e,u),s=_t([...n],t,i,{payoutAlreadyGross:Ps(n,u)}),c)break}return r}async function Al(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");const t=e.activeSignerWallet??e.externalWallet,n=e.activeSignerAddress??e.externalWalletAddress;if(!n||!t)throw new Error("Please connect your wallet to continue");const s=e.resolveLockBatches();if(s.length===0)throw new Error("No lock batches configured");const r=s.find(c=>c.chainId===e.lockChainId)||s[0];if(!r)throw new Error("No lock batch for lock chain");const{extWc:a,viemChain:i}=await xn({wallet:t,account:n,chainId:e.lockChainId}),d=p.getClientForChain(e.lockChainId),u=await Ro({extWc:a,client:d,calls:r.calls,viemChain:i,errorMessage:"Lock transaction failed"});u&&e.onLockSuccess?.(u)}async function Il(e){if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance. Add more assets.");return}e.ui.setIsExecuting(!0),e.ui.setError(null);const t=n=>{console.error("[SpiceLock] lock failed:",n);const s=p.sanitizeError(n,""),r=typeof n?.shortMessage=="string"?n.shortMessage:typeof n?.message=="string"?n.message:"";e.ui.setError(s||r||"Transaction failed. Please try again.")};if(e.isSemi7702){if(e.isSourceDestToken){try{await Al(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{await vl(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{lr(e)?await kl(e):await wl(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}}const El=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,lockBatches:s,lockTokenSymbol:r,lockTokenLogoURI:a,destinationInputHook:i,sourceAssetInputHook:d,lockDurationHook:u,lockChainId:c,durationOptions:f,votingPowerEstimate:h,escrowAddress:g,includeWalletAssets:x=!1,destinationTokenAddress:m,onLockSuccess:y,onLockError:C,onLockExecute:k,sourceToDestinationConversionRate:b,onAddFunds:R,buildSpicenetBatch:v,styles:w,dark:T=!1})=>{const{theme:I,dark:F,primaryColor:j,dk:A}=p.useSpiceBrand(w,T),E=I.typography.fontFamily,S=l.useContext(p.SpiceFlowProviderContext),M=S?.mode||"7702",U=!!S?.isWhitelistGateActive,W=M!=="7702",O=l.useMemo(()=>S?.supportedChainIds??[],[S?.supportedChainIds]),z=l.useMemo(()=>{if(U)return[];const _=S?.allowedTokens;if(!_||_.length===0)return[];const Ce=new Set(_.map(Pe=>Pe.toLowerCase())),Ne=[],lt=new Set;for(const Pe of O){const vt=p.getChainConfig(Pe);for(const Re of vt?.supportedTokens??[]){if(!Ce.has(Re.symbol.toLowerCase()))continue;const je=`${Pe}:${Re.address.toLowerCase()}`;lt.has(je)||(lt.add(je),Ne.push(D.getAddress(Re.address)))}}return Ne},[S?.allowedTokens,O,U]),N=F?A.cardBg:w?.assetSelector?.backgroundColor||w?.secondaryBackground||"#e9e9e9",P=F?`1px solid ${A.cardBorder}`:"0.5px solid #A8A8A7",Q=F?"12px":"6px",K=F?A.textPrimary:"#111827",V=F?A.textSecondary:"#6b7280",X=l.useMemo(()=>({...w,assetSelector:{...w?.assetSelector,backgroundColor:F?A.cardBg:w?.assetSelector?.backgroundColor,borderRadius:F?"12px":w?.assetSelector?.borderRadius},secondaryBackground:F?A.cardBg:w?.secondaryBackground}),[w,F]),xe=l.useMemo(()=>F?{...I,colors:{...I.colors,secondary:A.cardBg,surfaceHover:A.hoverBg,border:A.cardBorder,borderHover:A.inputBorder}}:I,[F,I]),[H,J]=l.useState(null),[se,ce]=l.useState(0),de=u?.selectedDurationIdx??se,ve=u?.setSelectedDurationIdx??ce,[ue,pe]=l.useState(!1),[Ee,L]=l.useState(null),ee=l.useRef(C);ee.current=C;const te=l.useCallback(_=>{L(_),typeof _=="string"&&_&&ee.current?.(_,p.getRelayerErrorDetail(_))},[]),[oe,Z]=l.useState(null),[ne,ge]=l.useState(!1),[G,Ie]=l.useState(!1),[ze,Ze]=l.useState(null),[Ft,ht]=l.useState(!1),[Ue,le]=l.useState(!1),[Ae,Ke]=l.useState(null),et=p.useWallet(),{isReady:ae,isAuthenticated:nt,isConnected:ke,address:we,provider:fe,actions:De}=et,{externalWallet:gt,activeWallet:xt,activeAddress:Bt}=p.useProviderWallets(),{intentStatus:Fe,beginStatusTracking:Xe,applyStepUpdate:yt,clearStatus:kt}=mn(),{assets:Tt,refetch:Oe}=jn({address:we,supportedChains:O,enabled:e&&ke&&!W&&!U,refetchInterval:3e4}),st=l.useMemo(()=>{if(U)return[];if(z.length===0)return Tt;const _=new Set(z.map(Ce=>Ce.toLowerCase()));return Tt.filter(Ce=>_.has(Ce.address.toLowerCase()))},[Tt,z,U]),Mt=S?.embeddedWalletAddress,Ct=S?.externalWalletAddress,he=W?Bt??Ct:Mt,{walletAssets:He,refreshWalletAssets:ot}=ul({isOpen:e,includeWalletAssets:x,isWhitelistGateActive:U,isSemi7702:W,destinationTokenAddress:m,sourceAssets:z,sourceChains:O,walletAddressForAssets:he,lockChainId:c,lockTokenSymbol:r,lockTokenLogoURI:a}),ct=l.useMemo(()=>He.filter(_=>_.balance>0n),[He]),be=l.useMemo(()=>{if(W)return ct.map(Ce=>({...Ce,_source:"wallet"}));if(!x)return st;const _=[];for(const Ce of ct)_.push({...Ce,_source:"wallet"});for(const Ce of st)_.push({...Ce,_source:"spice"});return _},[W,x,ct,st]),mt=l.useMemo(()=>U?m?be.filter(_=>p.addressesEqual(_.address,m)&&_.chainId===c):[]:be,[be,U,m,c]),Rt=l.useRef(null),Ge=l.useRef(null);l.useEffect(()=>{Ge.current=H},[H]),l.useEffect(()=>{!U||!H?.asset||m&&p.addressesEqual(H.asset.address,m)&&H.asset.chainId===c||J(null)},[U,H?.asset,m,c]),l.useEffect(()=>{e||(J(null),te(null),Z(null),ge(!1),Ie(!1),Ze(null),pe(!1),le(!1),Ke(null),ht(!1),kt())},[e,kt]),l.useEffect(()=>{i&&i.assetAmount!==(H?.amount||"")&&J(_=>_&&{..._,amount:i.assetAmount})},[i?.assetAmount]),l.useEffect(()=>{d&&d.assetAmount!==(H?.amount||"")&&J(_=>_&&{..._,amount:d.assetAmount})},[d?.assetAmount]),l.useEffect(()=>{if(!W&&Fe?.overallStatus==="success"&&Fe.intentId&&Rt.current!==Fe.intentId&&we&&Fe.steps.find(_=>_.transactionHash)?.transactionHash){Rt.current=Fe.intentId;const _=Ge.current;if(!_?.asset||!_.amount||_.asset._source==="wallet"||D.parseUnits(_.amount,_.asset.decimals)===0n)return;Oe()}},[Fe,we,c,Oe,W]);const Be=parseFloat(H?.amount||"")||0,rt=Be>0&&Be<Kt,Wt=l.useMemo(()=>H?.asset?H.asset._source==="wallet"?H.asset.balanceFormatted??0:st.find(_=>p.addressesEqual(_.address,H.asset.address)&&_.chainId===H.asset.chainId)?.balanceFormatted??0:0,[H?.asset,st]),dt=Be>0&&(ze?parseFloat(D.formatUnits(ze.grossAmount,ze.decimals))>Wt:Be>Wt),Qe=u?.selectedDuration??f[de]??f[0],Me=l.useMemo(()=>!H?.asset||!m?!1:p.addressesEqual(H.asset.address,m)&&H.asset.chainId===c,[H?.asset,m,c]),ut=l.useMemo(()=>Be<=0?0:Me?Be:!b||b<=0?0:Be/b,[Be,b,Me]),At=l.useMemo(()=>ut<=0?null:ut.toLocaleString(void 0,{maximumFractionDigits:2}),[ut]),Ve=h&&ut>0&&Qe?h(ut,Qe.months):void 0,Ht=l.useMemo(()=>Be<=0?"$0.00":Me&&b?(Be*b).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!b||b<=0?"$0.00":Be.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[Be,b,Me]),Le=l.useMemo(()=>{if(!At)return null;const _=parseFloat(At.replace(/,/g,""));return Me&&b?(_*b).toLocaleString(void 0,{maximumFractionDigits:2}):b?(_*b).toLocaleString(void 0,{maximumFractionDigits:2}):null},[At,b,Me]),bt=l.useCallback(_=>{J(Ce=>({asset:_,amount:Ce?.asset?.address===_.address&&Ce?.asset?.chainId===_.chainId&&Ce.amount||""})),te(null),Z(null),Ie(!1),Ze(null),d?.setSelectedAsset&&d.setSelectedAsset({symbol:_.symbol,address:_.address,decimals:_.decimals,chainId:_.chainId})},[d?.setSelectedAsset]),Nt=l.useCallback(_=>{J(Ce=>Ce&&{...Ce,amount:_}),te(null),Z(null),Ie(!1),Ze(null),i&&i.setAssetAmount(_),d&&d.setAssetAmount(_)},[i,d]),at=l.useCallback(_=>{if(typeof s=="function"){if(!H?.asset||!H.amount)throw new Error("Select an asset and enter an amount");return s({asset:H.asset,amount:_?.amount??H.amount,amountWei:_?.amountWei??D.parseUnits(H.amount,H.asset.decimals),grossAmount:_?.grossAmount,grossAmountWei:_?.grossAmountWei,feeAdjusted:!!_})}return s},[s,H]),Te=l.useRef(null),pt=l.useMemo(()=>!H?.asset||Be<=0?!1:W?!Me&&!k:!0,[H,Be,W,Me,k]),ft=l.useCallback(()=>Sl(Te.current),[]),it=l.useMemo(()=>!H?.asset||Be<=0?null:`${H.asset.address.toLowerCase()}:${H.asset.chainId}:${H.amount??""}`,[H?.asset?.address,H?.asset?.chainId,H?.amount,Be]);sr({shouldRun:e&&!ue&&!!H?.asset&&Be>0&&pt,deps:[e,ue,it,pt,ft],backgroundIntervalMs:3e4,onSkip:()=>{if(!(!e||ue)){if(!H?.asset||Be<=0){Z(null),ge(!1),Ie(!1),Ze(null);return}Z(null),ge(!1),Ie(!0),Ze(null)}},run:async({isBackground:_,isCurrent:Ce})=>{_||(Z(null),Ie(!1),ge(!0));try{const Ne=await ft();if(!Ce())return;Z(null),Ie(!0),Ze(Ne)}catch(Ne){if(!Ce())return;_||(Z(p.sanitizeError(Ne,"Unable to calculate fees for this lock.")),Ie(!1))}finally{Ce()&&!_&&ge(!1)}}}),l.useEffect(()=>{if(Fe?.overallStatus==="success"){const _=Fe.steps.find(Ce=>Ce.transactionHash);y?.(_?.transactionHash)}},[Fe?.overallStatus,y]);const Je=x&&H?.asset?._source==="wallet"&&H?.asset?.chainId===c,It=l.useCallback(()=>Il(Te.current),[]),Y=!!H?.asset&&Be>0&&!rt&&!dt&&!ue&&(!pt||G&&!ne&&!oe),$=Ee||oe,re=o.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[o.jsx(Ss,{color:V}),o.jsxs("p",{style:{fontSize:"13px",color:V,margin:0,lineHeight:"1.5"},children:["Add ",r," by converting assets from your account"]})]});if(Te.current={selectedAsset:H,parsedAmount:Be,selectedDuration:Qe,isInsufficientBalance:dt,isSemi7702:W,isSourceDestToken:Me,isDirectDeposit:Je,requiresRelayerFeeEstimate:pt,address:we,embeddedWalletAddress:Mt,externalWallet:gt,externalWalletAddress:Ct,activeSignerWallet:xt,activeSignerAddress:Bt,isConnected:ke,ready:ae,authenticated:nt,provider:fe,actions:De,lockChainId:c,escrowAddress:g,onLockExecute:k,onLockSuccess:y,buildSpicenetBatch:v,resolveLockBatches:at,beginStatusTracking:Xe,applyStepUpdate:yt,refreshSpiceAssets:Oe,refreshWalletAssets:ot,ui:{setError:te,setIsExecuting:pe,setShowStatusPanel:ht}},!e)return null;const We={backgroundColor:N,border:P,borderRadius:Q,padding:"16px",marginBottom:"16px"};return o.jsx(Vt,{isOpen:e,onClose:t,title:`Add ${r} to your account`,subtitle:re,styles:w,dark:F,footerLinkText:"Spicenet accounts \u2192",overlayContent:Ue?o.jsx("div",{}):void 0,closeOnBackdropClick:n,children:o.jsxs("div",{style:{padding:"0 24px 8px 24px",position:"relative"},children:[o.jsxs("div",{style:{marginBottom:"12px"},children:[R&&o.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:o.jsx(Es,{onClick:R,color:j,fontFamily:E})}),o.jsx("div",{style:{marginTop:"10px",fontSize:"13px",color:V,fontFamily:E},children:o.jsx(vn,{assets:mt,selectedAsset:H??void 0,onAssetSelect:bt,onAmountChange:Nt,label:"Amount",showBalance:!0,showMaxButton:!0,theme:xe,styles:X})}),o.jsx("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:V,fontFamily:E},children:Ht})]}),o.jsxs("div",{style:We,children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:F?`1px solid ${A.cardBorder}`:"1px solid #e5e7eb"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[a?o.jsx("img",{src:a,alt:r,style:{width:"32px",height:"32px",borderRadius:"50%",objectFit:"cover"}}):o.jsx("div",{style:{width:"32px",height:"32px",borderRadius:"50%",backgroundColor:F?A.inputBg:"#d1d5db",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:700,color:K},children:r.slice(0,2)}),o.jsx("span",{style:{fontSize:"16px",fontWeight:600,color:K,fontFamily:E},children:r})]}),o.jsxs("div",{style:{textAlign:"right"},children:[o.jsx("div",{style:{fontSize:"22px",fontWeight:700,color:K,fontFamily:E,lineHeight:1.1},children:At??"0.00"}),o.jsxs("div",{style:{fontSize:"12px",color:V,fontFamily:E,marginTop:"2px"},children:["~$",Le??"0.00"]})]})]}),o.jsxs("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:F?`1px solid ${A.cardBorder}`:"1px solid #e5e7eb"},children:[o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[o.jsx("span",{style:{fontSize:"15px",fontWeight:500,color:V,fontFamily:E},children:"Lock Duration"}),o.jsx(on,{color:V})]}),o.jsx(fl,{options:f,selectedIndex:de,onSelect:ve,primaryColor:j,dark:F,textPrimary:K,textSecondary:V})]}),o.jsxs("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[o.jsx(rr,{label:"Estimated Lock Expiry",value:Qe?.months!==void 0?hl(Qe.months):"\u2014",fontFamily:E,dark:F,textPrimary:K,textSecondary:V}),h&&o.jsx(rr,{label:"Estimated voting power",value:Ve!==void 0?`${Ve} votes/epoch`:"\u2014",fontFamily:E,dark:F,textPrimary:K,textSecondary:V})]})]}),pt&&o.jsx(Is,{fontFamily:E,textPrimary:K,textSecondary:V,cardBg:N,cardBorder:P,resolvedDark:F,darkCardBorder:A.cardBorder,primaryColor:j,feePreview:ze,isLoading:ne,errorText:oe}),$&&o.jsx(an,{variant:"error",palette:A,fontFamily:E,style:{marginBottom:"12px"},children:$}),o.jsx(p.Button,{variant:"outline",fullWidth:!0,onClick:It,disabled:!Y,loading:ue,dark:F,styles:{...w,button:{...w?.button,backgroundColor:j}},children:ue?Me?"LOCKING...":"CONVERTING...":rt?`MINIMUM ${Kt}`:ne&&pt?"CALCULATING FEES...":Me?`LOCK ${r}`:`CONVERT TO ${r}`}),o.jsx(gl,{isOpen:Ue,data:Ae,isLocking:ue,lockError:$,onContinue:It,onClose:()=>le(!1),primaryColor:j,fontFamily:E,dark:F}),Fe&&Ft&&o.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:F?"rgba(0, 0, 0, 0.45)":"rgba(255, 255, 255, 0.55)",backdropFilter:"blur(2px)",WebkitBackdropFilter:"blur(2px)",borderRadius:Q},children:o.jsx(Ms,{type:"lock",showStepBreakdown:!1,isOpen:!!Fe&&Fe.overallStatus!=="processing",isProcessing:ue||Fe?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{kt(),ht(!1),It()},onNewTx:()=>{kt(),ht(!1),J(null),Rt.current=null,Oe(),ot()},onClose:()=>{kt(),ht(!1)},onComplete:()=>{kt(),ht(!1),J(null),Rt.current=null,Oe(),ot()},results:Fe?.overallStatus==="success"||Fe?.overallStatus==="failed"?Fe.steps.map(_=>({asset:{symbol:H?.asset?.symbol||r,address:H?.asset?.address||""},txHash:_.transactionHash||"",success:_.status==="success",amount:H?.amount})):void 0,chainId:c,theme:I,styles:w,dark:F})})]})})};function dr(e){const t=l.useContext(p.SpiceFlowProviderContext),n=t?.embeddedWalletAddress,s=e?.enabled===!1?void 0:n,r=t?.network?{network:t.network,pollIntervalMs:e?.pollIntervalMs,chainIds:e?.chainIds??t.supportedChainIds,discoverWalletBalances:e?.discoverWalletBalances}:void 0;return{...Uo(s,r),embeddedWalletAddress:n}}var jl="data:image/svg+xml,%3csvg width='11' height='11' viewBox='0 0 24 24' fill='none' stroke='black' stroke-opacity='0.5' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' xmlns='http://www.w3.org/2000/svg'%3e%3cpolyline points='17 1 21 5 17 9' /%3e%3cpath d='M3 11V9a4 4 0 0 1 4-4h14' /%3e%3cpolyline points='7 23 3 19 7 15' /%3e%3cpath d='M21 13v2a4 4 0 0 1-4 4H3' /%3e%3c/svg%3e";const Fl=({appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:r,address:a,dk:i,dark:d=!1,showModeToggle:u,isEmbeddedMode:c=!0,onModeToggle:f})=>{const[h,g]=l.useState(!1),x=async()=>{a&&await p.copyToClipboard(a)&&(g(!0),setTimeout(()=>g(!1),2e3))},m=t==="active",y=n||(m?"Active":"Inactive"),C=m?"#10b981":"#9ca3af",k=o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[o.jsxs("div",{children:[o.jsx("strong",{children:"Embedded:"})," Deposit assets into ",e," account and use them here."]}),o.jsxs("div",{children:[o.jsx("strong",{children:"External:"})," Use assets from your connected wallet here."]})]});return o.jsxs("div",{children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[o.jsxs("div",{style:{fontSize:"13px",fontWeight:600,color:i.textPrimary},children:[e," Account"]}),u?o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[o.jsxs("button",{onClick:f,style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:d?i.hoverBg:"#f3f4f6",border:d?`1px solid ${i.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"11px",fontWeight:600,fontFamily:p.font.mono,color:i.textSecondary,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease",letterSpacing:"0.02em"},children:[o.jsx("span",{children:c?"Embedded":"External"}),o.jsx("img",{src:jl,alt:"","aria-hidden":"true",style:{width:"11px",height:"11px",display:"block",...d?{filter:"invert(0.65)"}:{}}})]}),o.jsx(Bo,{content:k,label:"Account mode info",textColor:d?i.textPrimary:"#f9fafb",backgroundColor:d?i.cardBg:"#111827",borderColor:d?i.cardBorder:"rgba(255,255,255,0.08)",accentColor:d?i.textSecondary:"#6b7280",children:o.jsx("img",{src:Rs,alt:"","aria-hidden":"true",style:{width:"12px",height:"12px",display:"block",...d?{filter:"invert(0.65)"}:{}}})})]}):o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:d?i.hoverBg:m?"#ecfdf5":"#f3f4f6",border:d?`1px solid ${i.cardBorder}`:m?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[o.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:C}}),o.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:d?i.textSecondary:m?"#065f46":"#6b7280"},children:y})]})]}),o.jsx("div",{style:{fontSize:"28px",fontWeight:700,color:i.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:p.formatUsd(s)}),r&&o.jsx("div",{style:{fontSize:"12px",color:i.textSecondary,marginBottom:"8px"},children:r}),a&&o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[o.jsx("span",{style:{fontSize:"12px",fontFamily:p.font.mono,color:d?i.textSecondary:"#9ca3af"},children:p.truncateAddress(a)}),o.jsx("button",{onClick:x,style:{padding:"2px 6px",fontSize:"10px",fontWeight:500,backgroundColor:"transparent",color:d?i.textSecondary:"#9ca3af",border:"none",cursor:"pointer",borderRadius:"4px",transition:"background-color 150ms ease, color 150ms ease"},title:"Copy address",children:h?"Copied":"Copy"})]})]})},Bl=l.memo(Fl),Tl=({pendingDeposits:e,onCompleteDeposit:t,dk:n,dark:s=!1})=>e.length===0?null:o.jsxs("div",{children:[o.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:"Pending Deposits"}),o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((r,a)=>{const i=p.getChainConfig(r.chainId)?.displayName||`Chain ${r.chainId}`;return o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:s?n.warningBg:"#fffbeb",border:s?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"8px"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[o.jsx("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:s?n.hoverBg:"#fde68a",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:n.warningText},children:r.tokenSymbol.charAt(0)}),o.jsxs("div",{children:[o.jsxs("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:[r.amount," ",r.tokenSymbol]}),o.jsxs("div",{style:{fontSize:"11px",color:n.warningText},children:["on ",i]})]})]}),o.jsx("button",{onClick:()=>t?.(r),style:{padding:"4px 12px",fontSize:"11px",fontWeight:600,backgroundColor:s?n.hoverBg:"#fef3c7",color:s?n.textPrimary:"#92400e",border:s?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"9999px",cursor:"pointer",transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease"},children:"Complete"})]},`${r.tokenAddress}-${r.chainId}-${a}`)})})]}),Rl=l.memo(Tl),Dl=e=>`${e.tokenAddress}-${e.chainId}`,Ml=({spiceAssets:e,loading:t,dk:n,dark:s=!1,canDirectWithdraw:r=!1,onDirectWithdraw:a,directWithdrawState:i})=>{const d={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},u={backgroundColor:n.cardBg,border:s?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return t?o.jsxs("div",{children:[o.jsx("div",{style:d,children:"Idle Balances"}),[1,2].map(c=>o.jsx("div",{style:{...u,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},c))]}):e.length===0?o.jsxs("div",{children:[o.jsx("div",{style:d,children:"Idle Balances"}),o.jsx("div",{style:{...u,padding:"16px",textAlign:"center",fontSize:"13px",color:s?n.textSecondary:"#9ca3af"},children:"No assets yet. Deposit to get started."})]}):o.jsxs("div",{children:[o.jsx("div",{style:d,children:"Idle Balances"}),o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((c,f)=>{const h=p.getChainConfig(c.chainId),g=c.chainDisplayName||h?.displayName||`Chain ${c.chainId}`,x=c.tokenDisplaySymbol||c.tokenDisplayName||c.tokenSymbol,m=Dl(c),y=r&&c.directWithdraw&&!!a,C=i?.key===m?i:null,k=C?.step==="pending";return o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...u},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[c.logoURI?o.jsx("img",{src:c.logoURI,alt:c.tokenSymbol,style:{width:"24px",height:"24px",borderRadius:"50%"}}):o.jsx("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:s?n.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:n.textSecondary},children:x.charAt(0)}),o.jsxs("div",{children:[o.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:x}),o.jsx("div",{style:{fontSize:"11px",color:s?n.textSecondary:"#9ca3af"},children:g})]})]}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[o.jsxs("div",{style:{textAlign:"right"},children:[o.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:p.formatBalance(c.balanceFormatted)}),o.jsx("div",{style:{fontSize:"11px",color:C?.step==="error"?n.errorText:s?n.textSecondary:"#9ca3af"},children:C?.step==="error"?C.message||"Withdraw failed":p.formatUsd(c.usdValue)})]}),y&&o.jsx("button",{onClick:()=>!k&&a(c),disabled:k,title:"Withdraw to external wallet",style:{padding:"6px 10px",borderRadius:"6px",border:s?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",backgroundColor:s?n.hoverBg:"#ffffff",color:n.textPrimary,fontSize:"11px",fontWeight:600,cursor:k?"default":"pointer",opacity:k?.6:1,whiteSpace:"nowrap"},children:k?"Withdrawing\u2026":"Withdraw"})]})]},`${c.tokenAddress}-${c.chainId}-${f}`)})})]})},Wl=l.memo(Ml),Nl=({section:e,dk:t,dark:n=!1})=>{const s=r=>{switch(r){case"green":return"#10b981";case"red":return"#ef4444";default:return t.textPrimary}};return o.jsxs("div",{children:[o.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:t.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:e.title}),o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.items.map((r,a)=>o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:t.cardBg,border:n?`1px solid ${t.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[r.tokenLogoURI?o.jsx("img",{src:r.tokenLogoURI,alt:r.tokenSymbol,style:{width:"20px",height:"20px",borderRadius:"50%"}}):o.jsx("div",{style:{width:"20px",height:"20px",borderRadius:"50%",backgroundColor:n?t.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",fontWeight:600,color:t.textSecondary},children:r.tokenSymbol.charAt(0)}),o.jsxs("div",{children:[o.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:t.textPrimary},children:r.tokenSymbol}),o.jsx("div",{style:{fontSize:"11px",color:t.textSecondary},children:r.label})]})]}),o.jsx("div",{style:{fontSize:"13px",fontWeight:600,color:s(r.valueColor)},children:r.displayValue})]},a))})]})},Pl=l.memo(Nl),Ul=({onDepositClick:e,onWithdrawClick:t,depositDisabled:n=!1,withdrawDisabled:s=!1,primaryColor:r="#EA4B4B",dark:a=!1})=>!e&&!t?null:o.jsxs("div",{style:{display:"flex",gap:"8px"},children:[e&&o.jsx(p.Button,{variant:"outline",onClick:e,disabled:n,dark:a,styles:{button:{backgroundColor:r}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&o.jsx(p.Button,{variant:"outline",onClick:t,disabled:s,dark:a,styles:{button:{backgroundColor:r}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),Ll=l.memo(Ul),zl=({appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:r,address:a,spiceAssets:i,spiceAssetsLoading:d,pendingDeposits:u,customSections:c,notice:f,onDepositClick:h,onWithdrawClick:g,depositDisabled:x,onCompleteDeposit:m,primaryColor:y,dk:C,dark:k=!1,showModeToggle:b,isEmbeddedMode:R,onModeToggle:v,showConnectExternalCta:w,onConnectExternalWallet:T,connectExternalError:I,showHowItWorks:F=!0,canDirectWithdraw:j,onDirectWithdraw:A,directWithdrawState:E})=>{const[S,M]=l.useState(!1);return o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[o.jsx(Bl,{appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:r,address:a,dk:C,dark:k,showModeToggle:b,isEmbeddedMode:R,onModeToggle:v}),f&&o.jsx("div",{style:{padding:"10px 12px",borderRadius:"8px",backgroundColor:f.tone==="warning"?k?"rgba(245, 158, 11, 0.12)":"#fffbeb":f.tone==="success"?k?"rgba(16, 185, 129, 0.12)":"#ecfdf5":C.cardBg,border:f.tone==="warning"?k?"1px solid rgba(245, 158, 11, 0.35)":"1px solid #fde68a":f.tone==="success"?k?"1px solid rgba(16, 185, 129, 0.35)":"1px solid #a7f3d0":k?`1px solid ${C.cardBorder}`:"1px solid #e5e7eb",color:f.tone==="warning"?k?"#fbbf24":"#92400e":f.tone==="success"?k?"#34d399":"#047857":C.textSecondary,fontSize:"12px",lineHeight:1.45,fontWeight:500},children:f.message}),w&&o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[o.jsx("button",{onClick:T,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:y||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:p.font.ui,transition:"opacity 150ms ease"},children:"Connect External Wallet"}),I&&o.jsx("span",{style:{fontSize:"11px",color:k?C.errorText:"#b91c1c",lineHeight:1.4},children:I})]}),o.jsx("div",{style:{height:"1px",backgroundColor:k?"#2d2d2d":"#e5e7eb"}}),o.jsx(Ll,{onDepositClick:h,onWithdrawClick:g,depositDisabled:x,primaryColor:y,dark:k}),F&&o.jsxs("div",{children:[o.jsxs("button",{onClick:()=>M(!S),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:C.cardBg,border:k?`1px solid ${C.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:C.textSecondary,fontSize:"12px",fontWeight:500},children:[o.jsx("span",{children:"How It Works"}),o.jsx("span",{style:{transform:S?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),S&&o.jsxs("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:k?C.cardBg:"#f0fdf4",border:k?`1px solid ${C.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:k?C.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),o.jsx(Rl,{pendingDeposits:u,onCompleteDeposit:m,dk:C,dark:k}),o.jsx(Wl,{spiceAssets:i,loading:d,dk:C,dark:k,canDirectWithdraw:j,onDirectWithdraw:A,directWithdrawState:E}),c.map((U,W)=>o.jsx(Pl,{section:U,dk:C,dark:k},W))]})},Ol=l.memo(zl);function Hl(e){return!!e.embeddedAddress&&!!e.externalAddress}function Ql(e,t,n){const s=t-n.gasBridge-n.spicenetFee;if(s<=0n)throw new Error("Balance is too small to cover the network fee.");const r=[{recipient:e,amount:s}];return n.gasBridge>0n&&r.push({recipient:B.SPICE_GAS_FEE_RECIPIENT,amount:n.gasBridge}),n.spicenetFee>0n&&r.push({recipient:B.SPICE_PLATFORM_FEE_RECIPIENT,amount:n.spicenetFee}),r}const Vl=new Set([B.SPICE_GAS_FEE_RECIPIENT,B.SPICE_PLATFORM_FEE_RECIPIENT].map(e=>e.toLowerCase()));function ql(e,t){return!e||e.length!==t.length?!1:e.every((n,s)=>{const r=t[s];return n.recipient.toLowerCase()!==r.recipient.toLowerCase()?!1:Vl.has(n.recipient.toLowerCase())?Jt(n.amount,r.amount,100n):!0})}function ur(e,t,n){return{chainId:e,domain:"evm",tokenTransfers:[],calls:n.filter(s=>s.amount>0n).map(s=>({to:t,value:0n,data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"transfer",args:[s.recipient,s.amount]})}))}}function Yl(e,t){const n=e.intents.flatMap(r=>r.batches).filter(r=>jt(r).totalFee>0n),s=n.filter(r=>r.chainId===t);return(s.length>0?s:n)[0]??null}function Zl(e,t,n,s){const r=Yl(s,e),{gasFee:a,bridgeFee:i,spicenetFee:d}=r?jt(r):{gasFee:0n,bridgeFee:0n,spicenetFee:0n};return Ql(t,n,{gasBridge:a+i,spicenetFee:d})}function Kl(){const{execute:e}=mn(),t=l.useContext(p.SpiceFlowProviderContext)?.embeddedWalletAddress,{embeddedAddress:n}=p.useProviderWallets(),s=t||n;return{withdraw:l.useCallback(async({tokenAddress:r,chainId:a,balance:i,recipient:d,onProgress:u})=>{const c=r,f=d;if(i<=0n)throw new Error("Nothing to withdraw.");const h=[ur(a,c,[{recipient:f,amount:i}])];let g=null;return e(h,c,0n,u,void 0,{useCustomTransfers:!0,userOverride:s,adjustBatchesForEstimate:({feeEstimate:x})=>{const m=Zl(a,f,i,x);return ql(g,m)?null:(g=m,[ur(a,c,m)])}})},[e,s])}}const Os=380,ln=8,Xl=[];function pr(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function Gl(e,t){const n=new Map;Object.entries(t).forEach(([r,a])=>{if(!Number.isFinite(a)||a<=0)return;n.set(r,a),n.set(r.toUpperCase(),a);const i=pr(r);i&&n.set(i,a)});const s=[e.symbol,e.displaySymbol,e.receiptTokenName,e.name,e.displayName];for(const r of s){if(!r)continue;const a=n.get(r)??n.get(r.toUpperCase());if(a!==void 0)return a;const i=pr(r);if(!i)continue;const d=n.get(i);if(d!==void 0)return d}return 0}const Jl=({appName:e="Spice",status:t="active",statusLabel:n,customSections:s=Xl,extraAssets:r=[],tokenPrices:a={},breakdownLabels:i=[],notice:d,styles:u,dark:c=!1,onDepositSuccess:f,onDepositClick:h,onWithdrawClick:g,onCompleteDeposit:x,showModeToggle:m=!1,defaultMode:y})=>{const C=l.useContext(p.SpiceFlowProviderContext),k=C?.mode!=="7702",b=!!C?.isWhitelistGateActive,R=!!C?.isWhitelistConfigured&&C?.isUserWhitelisted!==!0,v=l.useRef(!1);l.useEffect(()=>{if(!v.current){if(p.hasStoredSpiceFlowMode()){v.current=!0;return}y&&C?.setMode&&(C.setMode(y==="non7702"?"ondemand":"7702"),v.current=!0)}},[C,y]);const[w,T]=l.useState(!1),[I,F]=l.useState(null),[j,A]=l.useState({top:0,bottom:0,left:0,placement:"below"}),E=l.useRef(null),S=l.useRef(null),{address:M,isConnected:U}=p.useWallet(),W=C?.embeddedWalletAddress,O=C?.externalWalletAddress,{embeddedAddress:z}=p.useProviderWallets(),{dark:N,primaryColor:P,dk:Q}=p.useSpiceBrand(u,c),K=k&&!O,V=!k||K,X=V?W||z:M,xe=l.useMemo(()=>C?.supportedChainIds??B.getChainIdsByNetwork("mainnet"),[C?.supportedChainIds]),{assets:H,loading:J}=jn({address:X,supportedChains:xe,enabled:!!X&&V,refetchInterval:3e4}),se=l.useMemo(()=>{const ke=V?H.map(fe=>{const De=fe.balanceUsd||0,gt=Number.isFinite(fe.balanceFormatted)?fe.balanceFormatted:0,xt=De>0?De:Gl(fe,a)*gt;return{tokenAddress:fe.address,tokenSymbol:fe.symbol,tokenDisplaySymbol:ps(fe),tokenDisplayName:ga(fe),tokenDecimals:fe.decimals,chainId:fe.chainId,chainDisplayName:fs(fe),balance:fe.balance.toString(),balanceFormatted:fe.balanceFormatted,usdValue:xt,logoURI:fe.logoURI}}):[],we=K?[]:r;return[...ke,...we].filter(fe=>fe.balanceFormatted>0)},[V,K,H,a,r]),ce=l.useMemo(()=>se.reduce((ke,we)=>ke+we.usdValue,0),[se]),{pendingDeposits:de}=dr({chainIds:xe,enabled:!!M,discoverWalletBalances:!0}),ve=l.useMemo(()=>s.reduce((ke,we)=>ke+we.totalValue,0),[s]),ue=ce+ve,pe=l.useMemo(()=>{const ke=[];ce>0&&ke.push(`${p.formatUsd(ce)} idle`);for(const we of s){const fe=i.find(De=>De.sectionTitle===we.title)?.label||we.title.toLowerCase();ke.push(`${p.formatUsd(we.totalValue)} ${fe}`)}return ke.join(" \xB7 ")},[ce,s,i]),Ee=l.useCallback(ke=>{x?x(ke):F(ke)},[x]),L=l.useCallback(()=>{F(null)},[]),ee=l.useCallback(()=>{F(null),f?.()},[f]),te=l.useCallback(()=>{if(!E.current)return;const ke=E.current.getBoundingClientRect(),we=window.innerHeight-ke.bottom-ln,fe=ke.top-ln,De=we>=400||we>=fe?"below":"above",gt=Math.max(ln,Math.min(ke.right-Os,window.innerWidth-Os-ln)),xt=De==="below"?ke.bottom+ln:ke.top-ln,Bt=De==="above"?window.innerHeight-xt:0;A({top:xt,bottom:Bt,left:gt,placement:De})},[]);l.useLayoutEffect(()=>{w&&te()},[w,te]),l.useEffect(()=>{if(!w)return;const ke=De=>{E.current&&!E.current.contains(De.target)&&S.current&&!S.current.contains(De.target)&&T(!1)},we=De=>{De.key==="Escape"&&T(!1)},fe=()=>te();return document.addEventListener("mousedown",ke),document.addEventListener("keydown",we),window.addEventListener("scroll",fe,{passive:!0}),window.addEventListener("resize",te),()=>{document.removeEventListener("mousedown",ke),document.removeEventListener("keydown",we),window.removeEventListener("scroll",fe),window.removeEventListener("resize",te)}},[w,te]);const oe=V?W||z||M:O||M,Z=l.useCallback(()=>{C?.setMode&&C.setMode(V?"ondemand":"7702")},[C,V]),[ne,ge]=l.useState(null);let G=null;try{G=$s.useConnectWallet({onSuccess:()=>ge(null),onError:ke=>ge(p.sanitizeError(ke,"Failed to connect wallet."))}).connectWallet}catch{G=null}const Ie=l.useCallback(()=>{G&&(T(!1),ge(null),G({walletChainType:"ethereum-only"}))},[G]),ze=!O&&!!G,Ze=l.useCallback(()=>{T(!1),h?.()},[h]),Ft=l.useCallback(()=>{T(!1),g?.()},[g]),ht=l.useCallback(ke=>{T(!1),Ee(ke)},[Ee]),{withdraw:Ue}=Kl(),[le,Ae]=l.useState(null),Ke=Hl({embeddedAddress:W||z,externalAddress:O}),et=l.useCallback(async ke=>{if(!O)return;const we=`${ke.tokenAddress}-${ke.chainId}`;Ae({key:we,step:"pending"});try{await Ue({tokenAddress:ke.tokenAddress,chainId:ke.chainId,balance:BigInt(ke.balance),recipient:O}),Ae(null)}catch(fe){Ae({key:we,step:"error",message:p.sanitizeError(fe,"Withdraw failed")})}},[Ue,O]);if(typeof window>"u")return null;const ae=o.jsxs("button",{ref:E,onClick:()=>T(!w),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:N?Q.hoverBg:"#ffffff",border:N?`1px solid ${Q.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:p.font.ui,color:N?Q.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:N?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[o.jsxs("span",{children:[e," Account"]}),U&&o.jsxs("span",{style:{color:N?Q.textSecondary:"#6b7280"},children:["\xB7 ",p.formatUsd(ue)]}),o.jsx("span",{style:{fontSize:"10px",color:N?Q.textSecondary:"#9ca3af",transform:w?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),nt=w?Cn.createPortal(o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:p.z.popover},onClick:()=>T(!1)}),o.jsx("div",{ref:S,style:{position:"fixed",top:j.placement==="below"?`${j.top}px`:"auto",bottom:j.placement==="above"?`${j.bottom}px`:"auto",left:`${j.left}px`,width:`${Os}px`,maxWidth:`calc(100vw - ${ln*2}px)`,maxHeight:"80vh",backgroundColor:N?Q.shell:"#ffffff",border:N?`1px solid ${Q.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:N?"0 10px 40px rgba(0, 0, 0, 0.5)":"0 10px 40px rgba(0, 0, 0, 0.12)",zIndex:p.z.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${p.easing.out}`},children:o.jsx(Ol,{appName:e,status:t,statusLabel:n,totalUsdValue:ue,breakdownSubtitle:pe,address:V?oe:M,spiceAssets:se,spiceAssetsLoading:J,pendingDeposits:de,customSections:s,notice:d,onDepositClick:h?Ze:void 0,onWithdrawClick:g?Ft:void 0,depositDisabled:R,onCompleteDeposit:ht,primaryColor:P,dk:Q,dark:N,showModeToggle:m,isEmbeddedMode:V,onModeToggle:Z,showConnectExternalCta:ze,onConnectExternalWallet:Ie,connectExternalError:ne,showHowItWorks:!b,canDirectWithdraw:Ke,onDirectWithdraw:et,directWithdrawState:le})}),o.jsx("style",{children:`
|
|
80
|
+
`})]})};function xl(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const s=D.getAddress(n.token),r=D.getAddress(n.to),a=`${s.toLowerCase()}:${r.toLowerCase()}`,i=t.get(a);i?i.amount+=n.amount:t.set(a,{token:s,to:r,amount:n.amount})}return[...t.values()]}function yl(e,t){return`0x${t}${e.slice(4)}`}function ar(e,t){return ir(e,t)}function ir(e,t,n){const s=On(t,e),r=Math.floor(Date.now()/1e3)+60*10,a=B.hashChainBatches(s);return{user:e,...n?{chainAuthorizations:n}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:"0x00",nbf:0,exp:r,chainBatches:a.map((i,d)=>({hash:i.hash,chainId:i.chainId,tokenTransfers:s[d].domain==="spicenet"?[]:s[d].tokenTransfers??[],calls:i.calls}))}]}}function _t(e,t,n,s){if(e.some(f=>f.domain==="spicenet"))return e;const r=n?.intents.flatMap(f=>f.batches),a=f=>f.from==="escrow",i=e.map(f=>{const h=r?.find(v=>v.chainId===f.chainId);if(!h)return f;const g=jt(h),x=g.totalFee;if(x<=0n)return f;const m=(f.tokenTransfers??[]).find(v=>a(v)&&D.getAddress(v.to).toLowerCase()===t.toLowerCase()&&!B.isNativeToken(D.getAddress(v.token)));if(!m)return f;const y=D.getAddress(m.token);let C=!1;const k=(f.tokenTransfers??[]).map(v=>C||!a(v)||D.getAddress(v.to).toLowerCase()!==t.toLowerCase()||D.getAddress(v.token).toLowerCase()!==y.toLowerCase()?v:(C=!0,{...v,amount:s?.payoutAlreadyGross?BigInt(v.amount):BigInt(v.amount)+x}));if(!C)return f;const b=[];g.spicenetFee>0n&&b.push({to:y,value:0n,data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"transfer",args:[B.SPICE_PLATFORM_FEE_RECIPIENT,g.spicenetFee]})});const R=g.gasFee+g.bridgeFee;return R>0n&&b.push({to:y,value:0n,data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"transfer",args:[B.SPICE_GAS_FEE_RECIPIENT,R]})}),{...f,tokenTransfers:k,calls:[...b,...f.calls]}}),d=i.flatMap(f=>(f.tokenTransfers??[]).filter(a).map(h=>{const g=D.getAddress(h.token),x=D.getAddress(h.to),m=[{token:g,to:x,amount:BigInt(h.amount)}];return{chainId:f.chainId,transfers:xl(m)}}));if(d.length===0)return e;const u=s?.requestTimestampMs??Date.now(),c=BigInt(Math.floor(u/1e3))+3600n;return[{chainId:B.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:d.map((f,h)=>{const g=D.keccak256(D.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,f.transfers[0].token,f.transfers.reduce((m,y)=>m+y.amount,0n),BigInt(f.chainId),BigInt(u+h)])),x=yl(g,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:D.encodeFunctionData({abi:B.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${f.chainId}`,idempotenceKey:x,nbf:0n,exp:c,metadata:"{}",transfers:f.transfers.map(m=>({token:m.token.toLowerCase(),to:m.to,amount:m.amount}))}]})}})},...i]}const Cl=60*60;function Ps(e,t){return t?e.some(n=>(n.tokenTransfers??[]).some(s=>s.from==="escrow"&&BigInt(s.amount)>=t.grossAmount)):!1}function lr(e){return!e.isSemi7702&&e.isDirectDeposit&&!e.isSourceDestToken}function cr(e){const t=e.selectedAsset?.asset,n=e.selectedAsset?.amount;if(!(!t||!n))return D.parseUnits(n,t.decimals)}async function Gn({user:e,batches:t,authorizations:n,adjustBatchesForEstimate:s}){let r=t;for(let a=0;a<10;a+=1){const i=await p.relayerService.estimateActionFees(ir(e,r,n)),d=await s({feeEstimate:i,batches:r});if(!d||bo(r,d))return r;r=d}throw new Error("Fee estimate did not converge. Please retry.")}function bl(e){return{chainId:e.sourceChainId,calls:e.isNative?[{to:e.target,value:e.amount,data:"0x"}]:[{to:e.tokenAddr,value:0n,data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"transfer",args:[e.target,e.amount]})}]}}function Us(e,t,n,s){const r=e.selectedAsset.asset,a=D.parseUnits(e.selectedAsset.amount,r.decimals),i=r.chainId,d=e.escrowAddress||B.getEscrowContractAddress(i),u=B.normalizeNativeTokenAddress(r.address),c=r.isNative||B.isNativeToken(u),f=n.some(h=>h.tokenTransfers?.some(g=>g.from==="escrow"));return{asset:r,userNetAmountWei:a,sourceChainId:i,tokenAddr:u,isNative:c,hasEscrowBackedPayout:f,composeBatches:(h,g,x,m)=>{const y=bl({sourceChainId:i,target:d,tokenAddr:u,isNative:c,amount:h});if(!f)return[y,...g];const C=_t([...g],t,x,{payoutAlreadyGross:Ps(g,m),...s!==void 0?{requestTimestampMs:s}:{}});return[y,...C]}}}function Ls(e){const t={};return{state:t,adjustBatchesForEstimate:({feeEstimate:n})=>{const s=bs(n,{symbol:e.symbol,decimals:e.decimals,actionAmount:e.actionAmount});if(!s)return null;t.plan={grossAmount:s.grossAmount,netAmount:s.netAmount,feeAmount:s.totalFee??0n};const r=en(e.ctx,t.plan);return e.rebuild(r,n,t.plan)}}}function en(e,t){const n=e.selectedAsset?.asset;if(!n||!e.selectedAsset?.amount)throw new Error("Select an asset and enter an amount");const s=D.parseUnits(e.selectedAsset.amount,n.decimals),r=t?.grossAmount??s;return e.resolveLockBatches({amount:e.selectedAsset.amount,amountWei:s,grossAmount:D.formatUnits(r,n.decimals),grossAmountWei:r})}async function zs(e,t,n){const s=e.isSemi7702&&e.embeddedWalletAddress||e.address;if(!e.isConnected||!s)throw new Error("Please connect your wallet to continue");if(t.length===0)throw new Error("No lock batches configured");if(!e.ready||!e.authenticated)throw new Error(`Please authenticate with ${e.provider||"wallet provider"} to continue`);const r=n??await In({chainBatches:t,signingAddress:s,actions:e.actions}),a=B.hashChainBatches(t),i=Math.floor(Date.now()/1e3)+Cl,d={mode:"7702",signatureType:"ecdsa",signature:await vo(e.actions,t,BigInt(i)),nbf:0,exp:i,chainBatches:a.map((c,f)=>{const h=t[f],g=h.domain==="spicenet";return{hash:c.hash,chainId:c.chainId,tokenTransfers:g?[]:h.tokenTransfers??[],calls:c.calls}})},u=await p.relayerService.createAction({user:s,chainAuthorizations:r,intents:[d]});if(u){const c=p.createInitialSteps(t,p.getChainName),[f,h]=u.intentIds[0].split("/"),g=parseInt(h||"0",10),x=u.intentIds[0];e.beginStatusTracking(u.intentIds[0],c),await Co({actionId:f,intentIndex:g,intentId:x,totalSteps:t.length,isSpicenetStep:m=>t[m]?.domain==="spicenet",maxExecuteAttemptsForStep:m=>t[m]?.domain==="spicenet"?6:3,onStepUpdate:e.applyStepUpdate,maxPolls:72})}}async function wl(e){const t=en(e);if(t.length===0)throw new Error("No lock batches configured");const n=e.isSemi7702&&e.embeddedWalletAddress||e.address;if(!e.isConnected||!n)throw new Error("Please connect your wallet to continue");const s=await In({chainBatches:t,signingAddress:n,actions:e.actions}),r=Date.now();let a=_t([...t],n,void 0,{requestTimestampMs:r});const i=Ls({ctx:e,actionAmount:cr(e),symbol:e.selectedAsset?.asset.symbol??"",decimals:e.selectedAsset?.asset.decimals??18,rebuild:(d,u,c)=>_t([...d],n,u,{payoutAlreadyGross:Ps(d,c),requestTimestampMs:r})});a=await Gn({user:n,batches:a,authorizations:s,adjustBatchesForEstimate:i.adjustBatchesForEstimate}),await zs(e,a,s)}async function kl(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");const t=e.embeddedWalletAddress||e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");const n=e.resolveLockBatches();if(n.length===0)throw new Error("No lock batches configured");const s=Us(e,t,n,Date.now()),r=Ls({ctx:e,actionAmount:s.userNetAmountWei,symbol:s.asset.symbol,decimals:s.asset.decimals,rebuild:(d,u,c)=>s.composeBatches(c.grossAmount,d,u,c)});let a=s.composeBatches(s.userNetAmountWei,en(e));const i=await In({chainBatches:a,signingAddress:t,actions:e.actions});s.hasEscrowBackedPayout&&(a=await Gn({user:t,batches:a,authorizations:i,adjustBatchesForEstimate:r.adjustBatchesForEstimate})),await zs(e,a,i)}async function vl(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.embeddedWalletAddress;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");if(e.onLockExecute){const m=e.resolveLockBatches();if(m.length===0)throw new Error("No lock batches configured");const y=e.selectedAsset.asset,C=D.parseUnits(e.selectedAsset.amount,y.decimals),k=await e.onLockExecute({asset:y,amount:e.selectedAsset.amount,amountWei:C,lockDurationMonths:e.selectedDuration?.months??0,chainBatches:m});k&&e.onLockSuccess?.(k);return}const n=e.resolveLockBatches();if(n.length===0)throw new Error("No lock batches configured");const s=Us(e,t,n,Date.now()),{userNetAmountWei:r}=s,a=Ls({ctx:e,actionAmount:r,symbol:s.asset.symbol,decimals:s.asset.decimals,rebuild:(m,y,C)=>s.composeBatches(C.grossAmount,m,y,C)});let i=s.composeBatches(r,en(e));const d=await In({chainBatches:i,signingAddress:t,actions:e.actions});s.hasEscrowBackedPayout&&(i=await Gn({user:t,batches:i,authorizations:d,adjustBatchesForEstimate:a.adjustBatchesForEstimate}));const u=a.state.plan?.grossAmount??r,{extWc:c,viemChain:f}=await xn({wallet:e.externalWallet,account:e.externalWalletAddress,chainId:s.sourceChainId}),h=p.getClientForChain(s.sourceChainId),g=m=>js({extWc:c,sourceClient:h,recipient:t,tokenAddr:s.tokenAddr,isNative:s.isNative,amount:m,viemChain:f});await g(u);let x=u;if(s.hasEscrowBackedPayout)for(let m=0;m<4;m+=1){i=await Gn({user:t,batches:i,authorizations:d,adjustBatchesForEstimate:a.adjustBatchesForEstimate});const y=a.state.plan?.grossAmount??r;if(y<=x)break;await g(y-x),x=y}await zs(e,i,d)}async function Sl(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount||!e.requiresRelayerFeeEstimate)return null;if(e.isSemi7702||lr(e)){const a=e.embeddedWalletAddress||e.address;if(!a)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");let i=en(e);if(i.length===0)throw new Error("No lock batches configured");const d=Us(e,a,i),{asset:u,userNetAmountWei:c}=d;let f=d.composeBatches(c,i,void 0,{grossAmount:c,netAmount:0n,feeAmount:0n}),h=null,g;for(let x=0;x<4;x+=1){const m=await p.relayerService.estimateActionFees(ar(a,f)),y=bs(m,{symbol:u.symbol,decimals:u.decimals,actionAmount:c});if(!y)return h;const C={grossAmount:y.grossAmount,netAmount:y.netAmount,feeAmount:y.totalFee??0n},k=g?.grossAmount===C.grossAmount&&g?.netAmount===C.netAmount&&g?.feeAmount===C.feeAmount;if(h=y,g=C,i=en(e,C),f=d.composeBatches(C.grossAmount,i,m,C),k)break}return h}const t=e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");let n=en(e);if(n.length===0)throw new Error("No lock batches configured");let s=_t([...n],t),r=null;for(let a=0;a<4;a+=1){const i=await p.relayerService.estimateActionFees(ar(t,s)),d=bs(i,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:cr(e)});if(!d)return null;const u={grossAmount:d.grossAmount},c=r?.grossAmount===d.grossAmount&&r?.netAmount===d.netAmount&&r?.totalFee===d.totalFee;if(r=d,n=en(e,u),s=_t([...n],t,i,{payoutAlreadyGross:Ps(n,u)}),c)break}return r}async function Al(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");const t=e.activeSignerWallet??e.externalWallet,n=e.activeSignerAddress??e.externalWalletAddress;if(!n||!t)throw new Error("Please connect your wallet to continue");const s=e.resolveLockBatches();if(s.length===0)throw new Error("No lock batches configured");const r=s.find(c=>c.chainId===e.lockChainId)||s[0];if(!r)throw new Error("No lock batch for lock chain");const{extWc:a,viemChain:i}=await xn({wallet:t,account:n,chainId:e.lockChainId}),d=p.getClientForChain(e.lockChainId),u=await Ro({extWc:a,client:d,calls:r.calls,viemChain:i,errorMessage:"Lock transaction failed"});u&&e.onLockSuccess?.(u)}async function Il(e){if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance. Add more assets.");return}e.ui.setIsExecuting(!0),e.ui.setError(null);const t=n=>{console.error("[SpiceLock] lock failed:",n);const s=p.sanitizeError(n,""),r=typeof n?.shortMessage=="string"?n.shortMessage:typeof n?.message=="string"?n.message:"";e.ui.setError(s||r||"Transaction failed. Please try again.")};if(e.isSemi7702){if(e.isSourceDestToken){try{await Al(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{await vl(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{lr(e)?await kl(e):await wl(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}}const El=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,lockBatches:s,lockTokenSymbol:r,lockTokenLogoURI:a,destinationInputHook:i,sourceAssetInputHook:d,lockDurationHook:u,lockChainId:c,durationOptions:f,votingPowerEstimate:h,escrowAddress:g,includeWalletAssets:x=!1,destinationTokenAddress:m,onLockSuccess:y,onLockError:C,onLockExecute:k,sourceToDestinationConversionRate:b,onAddFunds:R,buildSpicenetBatch:v,styles:w,dark:T=!1})=>{const{theme:I,dark:F,primaryColor:j,dk:A}=p.useSpiceBrand(w,T),E=I.typography.fontFamily,S=l.useContext(p.SpiceFlowProviderContext),M=S?.mode||"7702",U=!!S?.isWhitelistGateActive,W=M!=="7702",O=l.useMemo(()=>S?.supportedChainIds??[],[S?.supportedChainIds]),z=l.useMemo(()=>{if(U)return[];const _=S?.allowedTokens;if(!_||_.length===0)return[];const Ce=new Set(_.map(Ue=>Ue.toLowerCase())),Pe=[],lt=new Set;for(const Ue of O){const vt=p.getChainConfig(Ue);for(const Re of vt?.supportedTokens??[]){if(!Ce.has(Re.symbol.toLowerCase()))continue;const je=`${Ue}:${Re.address.toLowerCase()}`;lt.has(je)||(lt.add(je),Pe.push(D.getAddress(Re.address)))}}return Pe},[S?.allowedTokens,O,U]),N=F?A.cardBg:w?.assetSelector?.backgroundColor||w?.secondaryBackground||"#e9e9e9",P=F?`1px solid ${A.cardBorder}`:"0.5px solid #A8A8A7",Q=F?"12px":"6px",K=F?A.textPrimary:"#111827",V=F?A.textSecondary:"#6b7280",X=l.useMemo(()=>({...w,assetSelector:{...w?.assetSelector,backgroundColor:F?A.cardBg:w?.assetSelector?.backgroundColor,borderRadius:F?"12px":w?.assetSelector?.borderRadius},secondaryBackground:F?A.cardBg:w?.secondaryBackground}),[w,F]),xe=l.useMemo(()=>F?{...I,colors:{...I.colors,secondary:A.cardBg,surfaceHover:A.hoverBg,border:A.cardBorder,borderHover:A.inputBorder}}:I,[F,I]),[H,J]=l.useState(null),[se,ce]=l.useState(0),de=u?.selectedDurationIdx??se,ve=u?.setSelectedDurationIdx??ce,[ue,pe]=l.useState(!1),[Ee,L]=l.useState(null),ee=l.useRef(C);ee.current=C;const te=l.useCallback(_=>{L(_),typeof _=="string"&&_&&ee.current?.(_,p.getRelayerErrorDetail(_))},[]),[oe,Z]=l.useState(null),[ne,ge]=l.useState(!1),[G,Ie]=l.useState(!1),[ze,Ke]=l.useState(null),[Ft,mt]=l.useState(!1),[Le,le]=l.useState(!1),[Ae,Xe]=l.useState(null),et=p.useWallet(),{isReady:ae,isAuthenticated:nt,isConnected:ke,address:we,provider:fe,actions:Me}=et,{externalWallet:xt,activeWallet:yt,activeAddress:Bt}=p.useProviderWallets(),{intentStatus:Fe,beginStatusTracking:Ge,applyStepUpdate:Ct,clearStatus:kt}=mn(),{assets:Tt,refetch:Oe}=jn({address:we,supportedChains:O,enabled:e&&ke&&!W&&!U,refetchInterval:3e4}),st=l.useMemo(()=>{if(U)return[];if(z.length===0)return Tt;const _=new Set(z.map(Ce=>Ce.toLowerCase()));return Tt.filter(Ce=>_.has(Ce.address.toLowerCase()))},[Tt,z,U]),Mt=S?.embeddedWalletAddress,bt=S?.externalWalletAddress,he=W?Bt??bt:Mt,{walletAssets:He,refreshWalletAssets:ot}=ul({isOpen:e,includeWalletAssets:x,isWhitelistGateActive:U,isSemi7702:W,destinationTokenAddress:m,sourceAssets:z,sourceChains:O,walletAddressForAssets:he,lockChainId:c,lockTokenSymbol:r,lockTokenLogoURI:a}),ct=l.useMemo(()=>He.filter(_=>_.balance>0n),[He]),be=l.useMemo(()=>{if(W)return ct.map(Ce=>({...Ce,_source:"wallet"}));if(!x)return st;const _=[];for(const Ce of ct)_.push({...Ce,_source:"wallet"});for(const Ce of st)_.push({...Ce,_source:"spice"});return _},[W,x,ct,st]),gt=l.useMemo(()=>U?m?be.filter(_=>p.addressesEqual(_.address,m)&&_.chainId===c):[]:be,[be,U,m,c]),Rt=l.useRef(null),Je=l.useRef(null);l.useEffect(()=>{Je.current=H},[H]),l.useEffect(()=>{!U||!H?.asset||m&&p.addressesEqual(H.asset.address,m)&&H.asset.chainId===c||J(null)},[U,H?.asset,m,c]),l.useEffect(()=>{e||(J(null),te(null),Z(null),ge(!1),Ie(!1),Ke(null),pe(!1),le(!1),Xe(null),mt(!1),kt())},[e,kt]),l.useEffect(()=>{i&&i.assetAmount!==(H?.amount||"")&&J(_=>_&&{..._,amount:i.assetAmount})},[i?.assetAmount]),l.useEffect(()=>{d&&d.assetAmount!==(H?.amount||"")&&J(_=>_&&{..._,amount:d.assetAmount})},[d?.assetAmount]),l.useEffect(()=>{if(!W&&Fe?.overallStatus==="success"&&Fe.intentId&&Rt.current!==Fe.intentId&&we&&Fe.steps.find(_=>_.transactionHash)?.transactionHash){Rt.current=Fe.intentId;const _=Je.current;if(!_?.asset||!_.amount||_.asset._source==="wallet"||D.parseUnits(_.amount,_.asset.decimals)===0n)return;Oe()}},[Fe,we,c,Oe,W]);const Be=parseFloat(H?.amount||"")||0,rt=Be>0&&Be<Kt,Wt=l.useMemo(()=>H?.asset?H.asset._source==="wallet"?H.asset.balanceFormatted??0:st.find(_=>p.addressesEqual(_.address,H.asset.address)&&_.chainId===H.asset.chainId)?.balanceFormatted??0:0,[H?.asset,st]),dt=Be>0&&(ze?parseFloat(D.formatUnits(ze.grossAmount,ze.decimals))>Wt:Be>Wt),Qe=u?.selectedDuration??f[de]??f[0],We=l.useMemo(()=>!H?.asset||!m?!1:p.addressesEqual(H.asset.address,m)&&H.asset.chainId===c,[H?.asset,m,c]),ut=l.useMemo(()=>Be<=0?0:We?Be:!b||b<=0?0:Be/b,[Be,b,We]),At=l.useMemo(()=>ut<=0?null:ut.toLocaleString(void 0,{maximumFractionDigits:2}),[ut]),Ve=h&&ut>0&&Qe?h(ut,Qe.months):void 0,Ht=l.useMemo(()=>Be<=0?"$0.00":We&&b?(Be*b).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!b||b<=0?"$0.00":Be.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[Be,b,We]),De=l.useMemo(()=>{if(!At)return null;const _=parseFloat(At.replace(/,/g,""));return We&&b?(_*b).toLocaleString(void 0,{maximumFractionDigits:2}):b?(_*b).toLocaleString(void 0,{maximumFractionDigits:2}):null},[At,b,We]),pt=l.useCallback(_=>{J(Ce=>({asset:_,amount:Ce?.asset?.address===_.address&&Ce?.asset?.chainId===_.chainId&&Ce.amount||""})),te(null),Z(null),Ie(!1),Ke(null),d?.setSelectedAsset&&d.setSelectedAsset({symbol:_.symbol,address:_.address,decimals:_.decimals,chainId:_.chainId})},[d?.setSelectedAsset]),Nt=l.useCallback(_=>{J(Ce=>Ce&&{...Ce,amount:_}),te(null),Z(null),Ie(!1),Ke(null),i&&i.setAssetAmount(_),d&&d.setAssetAmount(_)},[i,d]),at=l.useCallback(_=>{if(typeof s=="function"){if(!H?.asset||!H.amount)throw new Error("Select an asset and enter an amount");return s({asset:H.asset,amount:_?.amount??H.amount,amountWei:_?.amountWei??D.parseUnits(H.amount,H.asset.decimals),grossAmount:_?.grossAmount,grossAmountWei:_?.grossAmountWei,feeAdjusted:!!_})}return s},[s,H]),Te=l.useRef(null),ft=l.useMemo(()=>!H?.asset||Be<=0?!1:W?!We&&!k:!0,[H,Be,W,We,k]),ht=l.useCallback(()=>Sl(Te.current),[]),it=l.useMemo(()=>!H?.asset||Be<=0?null:`${H.asset.address.toLowerCase()}:${H.asset.chainId}:${H.amount??""}`,[H?.asset?.address,H?.asset?.chainId,H?.amount,Be]);sr({shouldRun:e&&!ue&&!!H?.asset&&Be>0&&ft,deps:[e,ue,it,ft,ht],backgroundIntervalMs:3e4,onSkip:()=>{if(!(!e||ue)){if(!H?.asset||Be<=0){Z(null),ge(!1),Ie(!1),Ke(null);return}Z(null),ge(!1),Ie(!0),Ke(null)}},run:async({isBackground:_,isCurrent:Ce})=>{_||(Z(null),Ie(!1),ge(!0));try{const Pe=await ht();if(!Ce())return;Z(null),Ie(!0),Ke(Pe)}catch(Pe){if(!Ce())return;_||(Z(p.sanitizeError(Pe,"Unable to calculate fees for this lock.")),Ie(!1))}finally{Ce()&&!_&&ge(!1)}}}),l.useEffect(()=>{if(Fe?.overallStatus==="success"){const _=Fe.steps.find(Ce=>Ce.transactionHash);y?.(_?.transactionHash)}},[Fe?.overallStatus,y]);const qe=x&&H?.asset?._source==="wallet"&&H?.asset?.chainId===c,It=l.useCallback(()=>Il(Te.current),[]),Y=!!H?.asset&&Be>0&&!rt&&!dt&&!ue&&(!ft||G&&!ne&&!oe),$=Ee||oe,re=o.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[o.jsx(Ss,{color:V}),o.jsxs("p",{style:{fontSize:"13px",color:V,margin:0,lineHeight:"1.5"},children:["Add ",r," by converting assets from your account"]})]});if(Te.current={selectedAsset:H,parsedAmount:Be,selectedDuration:Qe,isInsufficientBalance:dt,isSemi7702:W,isSourceDestToken:We,isDirectDeposit:qe,requiresRelayerFeeEstimate:ft,address:we,embeddedWalletAddress:Mt,externalWallet:xt,externalWalletAddress:bt,activeSignerWallet:yt,activeSignerAddress:Bt,isConnected:ke,ready:ae,authenticated:nt,provider:fe,actions:Me,lockChainId:c,escrowAddress:g,onLockExecute:k,onLockSuccess:y,buildSpicenetBatch:v,resolveLockBatches:at,beginStatusTracking:Ge,applyStepUpdate:Ct,refreshSpiceAssets:Oe,refreshWalletAssets:ot,ui:{setError:te,setIsExecuting:pe,setShowStatusPanel:mt}},!e)return null;const Ne={backgroundColor:N,border:P,borderRadius:Q,padding:"16px",marginBottom:"16px"};return o.jsx(Vt,{isOpen:e,onClose:t,title:`Add ${r} to your account`,subtitle:re,styles:w,dark:F,footerLinkText:"Spicenet accounts \u2192",overlayContent:Le?o.jsx("div",{}):void 0,closeOnBackdropClick:n,children:o.jsxs("div",{style:{padding:"0 24px 8px 24px",position:"relative"},children:[o.jsxs("div",{style:{marginBottom:"12px"},children:[R&&o.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:o.jsx(Es,{onClick:R,color:j,fontFamily:E})}),o.jsx("div",{style:{marginTop:"10px",fontSize:"13px",color:V,fontFamily:E},children:o.jsx(vn,{assets:gt,selectedAsset:H??void 0,onAssetSelect:pt,onAmountChange:Nt,label:"Amount",showBalance:!0,showMaxButton:!0,theme:xe,styles:X})}),o.jsx("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:V,fontFamily:E},children:Ht})]}),o.jsxs("div",{style:Ne,children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:F?`1px solid ${A.cardBorder}`:"1px solid #e5e7eb"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[a?o.jsx("img",{src:a,alt:r,style:{width:"32px",height:"32px",borderRadius:"50%",objectFit:"cover"}}):o.jsx("div",{style:{width:"32px",height:"32px",borderRadius:"50%",backgroundColor:F?A.inputBg:"#d1d5db",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:700,color:K},children:r.slice(0,2)}),o.jsx("span",{style:{fontSize:"16px",fontWeight:600,color:K,fontFamily:E},children:r})]}),o.jsxs("div",{style:{textAlign:"right"},children:[o.jsx("div",{style:{fontSize:"22px",fontWeight:700,color:K,fontFamily:E,lineHeight:1.1},children:At??"0.00"}),o.jsxs("div",{style:{fontSize:"12px",color:V,fontFamily:E,marginTop:"2px"},children:["~$",De??"0.00"]})]})]}),o.jsxs("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:F?`1px solid ${A.cardBorder}`:"1px solid #e5e7eb"},children:[o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[o.jsx("span",{style:{fontSize:"15px",fontWeight:500,color:V,fontFamily:E},children:"Lock Duration"}),o.jsx(on,{color:V})]}),o.jsx(fl,{options:f,selectedIndex:de,onSelect:ve,primaryColor:j,dark:F,textPrimary:K,textSecondary:V})]}),o.jsxs("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[o.jsx(rr,{label:"Estimated Lock Expiry",value:Qe?.months!==void 0?hl(Qe.months):"\u2014",fontFamily:E,dark:F,textPrimary:K,textSecondary:V}),h&&o.jsx(rr,{label:"Estimated voting power",value:Ve!==void 0?`${Ve} votes/epoch`:"\u2014",fontFamily:E,dark:F,textPrimary:K,textSecondary:V})]})]}),ft&&o.jsx(Is,{fontFamily:E,textPrimary:K,textSecondary:V,cardBg:N,cardBorder:P,resolvedDark:F,darkCardBorder:A.cardBorder,primaryColor:j,feePreview:ze,isLoading:ne,errorText:oe}),$&&o.jsx(an,{variant:"error",palette:A,fontFamily:E,style:{marginBottom:"12px"},children:$}),o.jsx(p.Button,{variant:"outline",fullWidth:!0,onClick:It,disabled:!Y,loading:ue,dark:F,styles:{...w,button:{...w?.button,backgroundColor:j}},children:ue?We?"LOCKING...":"CONVERTING...":rt?`MINIMUM ${Kt}`:ne&&ft?"CALCULATING FEES...":We?`LOCK ${r}`:`CONVERT TO ${r}`}),o.jsx(gl,{isOpen:Le,data:Ae,isLocking:ue,lockError:$,onContinue:It,onClose:()=>le(!1),primaryColor:j,fontFamily:E,dark:F}),Fe&&Ft&&o.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:F?"rgba(0, 0, 0, 0.45)":"rgba(255, 255, 255, 0.55)",backdropFilter:"blur(2px)",WebkitBackdropFilter:"blur(2px)",borderRadius:Q},children:o.jsx(Ms,{type:"lock",showStepBreakdown:!1,isOpen:!!Fe&&Fe.overallStatus!=="processing",isProcessing:ue||Fe?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{kt(),mt(!1),It()},onNewTx:()=>{kt(),mt(!1),J(null),Rt.current=null,Oe(),ot()},onClose:()=>{kt(),mt(!1)},onComplete:()=>{kt(),mt(!1),J(null),Rt.current=null,Oe(),ot()},results:Fe?.overallStatus==="success"||Fe?.overallStatus==="failed"?Fe.steps.map(_=>({asset:{symbol:H?.asset?.symbol||r,address:H?.asset?.address||""},txHash:_.transactionHash||"",success:_.status==="success",amount:H?.amount})):void 0,chainId:c,theme:I,styles:w,dark:F})})]})})};function dr(e){const t=l.useContext(p.SpiceFlowProviderContext),n=t?.embeddedWalletAddress,s=e?.enabled===!1?void 0:n,r=t?.network?{network:t.network,pollIntervalMs:e?.pollIntervalMs,chainIds:e?.chainIds??t.supportedChainIds,discoverWalletBalances:e?.discoverWalletBalances}:void 0;return{...Uo(s,r),embeddedWalletAddress:n}}var jl="data:image/svg+xml,%3csvg width='11' height='11' viewBox='0 0 24 24' fill='none' stroke='black' stroke-opacity='0.5' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' xmlns='http://www.w3.org/2000/svg'%3e%3cpolyline points='17 1 21 5 17 9' /%3e%3cpath d='M3 11V9a4 4 0 0 1 4-4h14' /%3e%3cpolyline points='7 23 3 19 7 15' /%3e%3cpath d='M21 13v2a4 4 0 0 1-4 4H3' /%3e%3c/svg%3e";const Fl=({appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:r,address:a,dk:i,dark:d=!1,showModeToggle:u,isEmbeddedMode:c=!0,onModeToggle:f})=>{const[h,g]=l.useState(!1),x=async()=>{a&&await p.copyToClipboard(a)&&(g(!0),setTimeout(()=>g(!1),2e3))},m=t==="active",y=n||(m?"Active":"Inactive"),C=m?"#10b981":"#9ca3af",k=o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[o.jsxs("div",{children:[o.jsx("strong",{children:"Embedded:"})," Deposit assets into ",e," account and use them here."]}),o.jsxs("div",{children:[o.jsx("strong",{children:"External:"})," Use assets from your connected wallet here."]})]});return o.jsxs("div",{children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[o.jsxs("div",{style:{fontSize:"13px",fontWeight:600,color:i.textPrimary},children:[e," Account"]}),u?o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[o.jsxs("button",{onClick:f,style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:d?i.hoverBg:"#f3f4f6",border:d?`1px solid ${i.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"11px",fontWeight:600,fontFamily:p.font.mono,color:i.textSecondary,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease",letterSpacing:"0.02em"},children:[o.jsx("span",{children:c?"Embedded":"External"}),o.jsx("img",{src:jl,alt:"","aria-hidden":"true",style:{width:"11px",height:"11px",display:"block",...d?{filter:"invert(0.65)"}:{}}})]}),o.jsx(Bo,{content:k,label:"Account mode info",textColor:d?i.textPrimary:"#f9fafb",backgroundColor:d?i.cardBg:"#111827",borderColor:d?i.cardBorder:"rgba(255,255,255,0.08)",accentColor:d?i.textSecondary:"#6b7280",children:o.jsx("img",{src:Rs,alt:"","aria-hidden":"true",style:{width:"12px",height:"12px",display:"block",...d?{filter:"invert(0.65)"}:{}}})})]}):o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:d?i.hoverBg:m?"#ecfdf5":"#f3f4f6",border:d?`1px solid ${i.cardBorder}`:m?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[o.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:C}}),o.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:d?i.textSecondary:m?"#065f46":"#6b7280"},children:y})]})]}),o.jsx("div",{style:{fontSize:"28px",fontWeight:700,color:i.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:p.formatUsd(s)}),r&&o.jsx("div",{style:{fontSize:"12px",color:i.textSecondary,marginBottom:"8px"},children:r}),a&&o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[o.jsx("span",{style:{fontSize:"12px",fontFamily:p.font.mono,color:d?i.textSecondary:"#9ca3af"},children:p.truncateAddress(a)}),o.jsx("button",{onClick:x,style:{padding:"2px 6px",fontSize:"10px",fontWeight:500,backgroundColor:"transparent",color:d?i.textSecondary:"#9ca3af",border:"none",cursor:"pointer",borderRadius:"4px",transition:"background-color 150ms ease, color 150ms ease"},title:"Copy address",children:h?"Copied":"Copy"})]})]})},Bl=l.memo(Fl),Tl=({pendingDeposits:e,onCompleteDeposit:t,dk:n,dark:s=!1})=>e.length===0?null:o.jsxs("div",{children:[o.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:"Pending Deposits"}),o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((r,a)=>{const i=p.getChainConfig(r.chainId)?.displayName||`Chain ${r.chainId}`;return o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:s?n.warningBg:"#fffbeb",border:s?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"8px"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[o.jsx("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:s?n.hoverBg:"#fde68a",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:n.warningText},children:r.tokenSymbol.charAt(0)}),o.jsxs("div",{children:[o.jsxs("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:[r.amount," ",r.tokenSymbol]}),o.jsxs("div",{style:{fontSize:"11px",color:n.warningText},children:["on ",i]})]})]}),o.jsx("button",{onClick:()=>t?.(r),style:{padding:"4px 12px",fontSize:"11px",fontWeight:600,backgroundColor:s?n.hoverBg:"#fef3c7",color:s?n.textPrimary:"#92400e",border:s?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"9999px",cursor:"pointer",transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease"},children:"Complete"})]},`${r.tokenAddress}-${r.chainId}-${a}`)})})]}),Rl=l.memo(Tl),Dl=e=>`${e.tokenAddress}-${e.chainId}`,Ml=({spiceAssets:e,loading:t,dk:n,dark:s=!1,canDirectWithdraw:r=!1,onDirectWithdraw:a,directWithdrawState:i})=>{const d={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},u={backgroundColor:n.cardBg,border:s?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return t?o.jsxs("div",{children:[o.jsx("div",{style:d,children:"Idle Balances"}),[1,2].map(c=>o.jsx("div",{style:{...u,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},c))]}):e.length===0?o.jsxs("div",{children:[o.jsx("div",{style:d,children:"Idle Balances"}),o.jsx("div",{style:{...u,padding:"16px",textAlign:"center",fontSize:"13px",color:s?n.textSecondary:"#9ca3af"},children:"No assets yet. Deposit to get started."})]}):o.jsxs("div",{children:[o.jsx("div",{style:d,children:"Idle Balances"}),o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((c,f)=>{const h=p.getChainConfig(c.chainId),g=c.chainDisplayName||h?.displayName||`Chain ${c.chainId}`,x=c.tokenDisplaySymbol||c.tokenDisplayName||c.tokenSymbol,m=Dl(c),y=r&&c.directWithdraw&&!!a,C=i?.key===m?i:null,k=C?.step==="pending";return o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...u},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[c.logoURI?o.jsx("img",{src:c.logoURI,alt:c.tokenSymbol,style:{width:"24px",height:"24px",borderRadius:"50%"}}):o.jsx("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:s?n.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:n.textSecondary},children:x.charAt(0)}),o.jsxs("div",{children:[o.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:x}),o.jsx("div",{style:{fontSize:"11px",color:s?n.textSecondary:"#9ca3af"},children:g})]})]}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[o.jsxs("div",{style:{textAlign:"right"},children:[o.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:p.formatBalance(c.balanceFormatted)}),o.jsx("div",{style:{fontSize:"11px",color:C?.step==="error"?n.errorText:s?n.textSecondary:"#9ca3af"},children:C?.step==="error"?C.message||"Withdraw failed":p.formatUsd(c.usdValue)})]}),y&&o.jsx("button",{onClick:()=>!k&&a(c),disabled:k,title:"Withdraw to external wallet",style:{padding:"6px 10px",borderRadius:"6px",border:s?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",backgroundColor:s?n.hoverBg:"#ffffff",color:n.textPrimary,fontSize:"11px",fontWeight:600,cursor:k?"default":"pointer",opacity:k?.6:1,whiteSpace:"nowrap"},children:k?"Withdrawing\u2026":"Withdraw"})]})]},`${c.tokenAddress}-${c.chainId}-${f}`)})})]})},Wl=l.memo(Ml),Nl=({section:e,dk:t,dark:n=!1})=>{const s=r=>{switch(r){case"green":return"#10b981";case"red":return"#ef4444";default:return t.textPrimary}};return o.jsxs("div",{children:[o.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:t.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:e.title}),o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.items.map((r,a)=>o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:t.cardBg,border:n?`1px solid ${t.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[r.tokenLogoURI?o.jsx("img",{src:r.tokenLogoURI,alt:r.tokenSymbol,style:{width:"20px",height:"20px",borderRadius:"50%"}}):o.jsx("div",{style:{width:"20px",height:"20px",borderRadius:"50%",backgroundColor:n?t.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",fontWeight:600,color:t.textSecondary},children:r.tokenSymbol.charAt(0)}),o.jsxs("div",{children:[o.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:t.textPrimary},children:r.tokenSymbol}),o.jsx("div",{style:{fontSize:"11px",color:t.textSecondary},children:r.label})]})]}),o.jsx("div",{style:{fontSize:"13px",fontWeight:600,color:s(r.valueColor)},children:r.displayValue})]},a))})]})},Pl=l.memo(Nl),Ul=({onDepositClick:e,onWithdrawClick:t,depositDisabled:n=!1,withdrawDisabled:s=!1,primaryColor:r="#EA4B4B",dark:a=!1})=>!e&&!t?null:o.jsxs("div",{style:{display:"flex",gap:"8px"},children:[e&&o.jsx(p.Button,{variant:"outline",onClick:e,disabled:n,dark:a,styles:{button:{backgroundColor:r}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&o.jsx(p.Button,{variant:"outline",onClick:t,disabled:s,dark:a,styles:{button:{backgroundColor:r}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),Ll=l.memo(Ul),zl=({appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:r,address:a,spiceAssets:i,spiceAssetsLoading:d,pendingDeposits:u,customSections:c,notice:f,onDepositClick:h,onWithdrawClick:g,depositDisabled:x,onCompleteDeposit:m,primaryColor:y,dk:C,dark:k=!1,showModeToggle:b,isEmbeddedMode:R,onModeToggle:v,showConnectExternalCta:w,onConnectExternalWallet:T,connectExternalError:I,showHowItWorks:F=!0,canDirectWithdraw:j,onDirectWithdraw:A,directWithdrawState:E})=>{const[S,M]=l.useState(!1);return o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[o.jsx(Bl,{appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:r,address:a,dk:C,dark:k,showModeToggle:b,isEmbeddedMode:R,onModeToggle:v}),f&&o.jsx("div",{style:{padding:"10px 12px",borderRadius:"8px",backgroundColor:f.tone==="warning"?k?"rgba(245, 158, 11, 0.12)":"#fffbeb":f.tone==="success"?k?"rgba(16, 185, 129, 0.12)":"#ecfdf5":C.cardBg,border:f.tone==="warning"?k?"1px solid rgba(245, 158, 11, 0.35)":"1px solid #fde68a":f.tone==="success"?k?"1px solid rgba(16, 185, 129, 0.35)":"1px solid #a7f3d0":k?`1px solid ${C.cardBorder}`:"1px solid #e5e7eb",color:f.tone==="warning"?k?"#fbbf24":"#92400e":f.tone==="success"?k?"#34d399":"#047857":C.textSecondary,fontSize:"12px",lineHeight:1.45,fontWeight:500},children:f.message}),w&&o.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[o.jsx("button",{onClick:T,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:y||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:p.font.ui,transition:"opacity 150ms ease"},children:"Connect External Wallet"}),I&&o.jsx("span",{style:{fontSize:"11px",color:k?C.errorText:"#b91c1c",lineHeight:1.4},children:I})]}),o.jsx("div",{style:{height:"1px",backgroundColor:k?"#2d2d2d":"#e5e7eb"}}),o.jsx(Ll,{onDepositClick:h,onWithdrawClick:g,depositDisabled:x,primaryColor:y,dark:k}),F&&o.jsxs("div",{children:[o.jsxs("button",{onClick:()=>M(!S),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:C.cardBg,border:k?`1px solid ${C.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:C.textSecondary,fontSize:"12px",fontWeight:500},children:[o.jsx("span",{children:"How It Works"}),o.jsx("span",{style:{transform:S?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),S&&o.jsxs("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:k?C.cardBg:"#f0fdf4",border:k?`1px solid ${C.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:k?C.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),o.jsx(Rl,{pendingDeposits:u,onCompleteDeposit:m,dk:C,dark:k}),o.jsx(Wl,{spiceAssets:i,loading:d,dk:C,dark:k,canDirectWithdraw:j,onDirectWithdraw:A,directWithdrawState:E}),c.map((U,W)=>o.jsx(Pl,{section:U,dk:C,dark:k},W))]})},Ol=l.memo(zl);function Hl(e){return!!e.embeddedAddress&&!!e.externalAddress}function Ql(e,t,n){const s=t-n.gasBridge-n.spicenetFee;if(s<=0n)throw new Error("Balance is too small to cover the network fee.");const r=[{recipient:e,amount:s}];return n.gasBridge>0n&&r.push({recipient:B.SPICE_GAS_FEE_RECIPIENT,amount:n.gasBridge}),n.spicenetFee>0n&&r.push({recipient:B.SPICE_PLATFORM_FEE_RECIPIENT,amount:n.spicenetFee}),r}const Vl=new Set([B.SPICE_GAS_FEE_RECIPIENT,B.SPICE_PLATFORM_FEE_RECIPIENT].map(e=>e.toLowerCase()));function ql(e,t){return!e||e.length!==t.length?!1:e.every((n,s)=>{const r=t[s];return n.recipient.toLowerCase()!==r.recipient.toLowerCase()?!1:Vl.has(n.recipient.toLowerCase())?Jt(n.amount,r.amount,100n):!0})}function ur(e,t,n){return{chainId:e,domain:"evm",tokenTransfers:[],calls:n.filter(s=>s.amount>0n).map(s=>({to:t,value:0n,data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"transfer",args:[s.recipient,s.amount]})}))}}function Yl(e,t){const n=e.intents.flatMap(r=>r.batches).filter(r=>jt(r).totalFee>0n),s=n.filter(r=>r.chainId===t);return(s.length>0?s:n)[0]??null}function Zl(e,t,n,s){const r=Yl(s,e),{gasFee:a,bridgeFee:i,spicenetFee:d}=r?jt(r):{gasFee:0n,bridgeFee:0n,spicenetFee:0n};return Ql(t,n,{gasBridge:a+i,spicenetFee:d})}function Kl(){const{execute:e}=mn(),t=l.useContext(p.SpiceFlowProviderContext)?.embeddedWalletAddress,{embeddedAddress:n}=p.useProviderWallets(),s=t||n;return{withdraw:l.useCallback(async({tokenAddress:r,chainId:a,balance:i,recipient:d,onProgress:u})=>{const c=r,f=d;if(i<=0n)throw new Error("Nothing to withdraw.");const h=[ur(a,c,[{recipient:f,amount:i}])];let g=null;return e(h,c,0n,u,void 0,{useCustomTransfers:!0,userOverride:s,adjustBatchesForEstimate:({feeEstimate:x})=>{const m=Zl(a,f,i,x);return ql(g,m)?null:(g=m,[ur(a,c,m)])}})},[e,s])}}const Os=380,ln=8,Xl=[];function pr(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function Gl(e,t){const n=new Map;Object.entries(t).forEach(([r,a])=>{if(!Number.isFinite(a)||a<=0)return;n.set(r,a),n.set(r.toUpperCase(),a);const i=pr(r);i&&n.set(i,a)});const s=[e.symbol,e.displaySymbol,e.receiptTokenName,e.name,e.displayName];for(const r of s){if(!r)continue;const a=n.get(r)??n.get(r.toUpperCase());if(a!==void 0)return a;const i=pr(r);if(!i)continue;const d=n.get(i);if(d!==void 0)return d}return 0}const Jl=({appName:e="Spice",status:t="active",statusLabel:n,customSections:s=Xl,extraAssets:r=[],tokenPrices:a={},breakdownLabels:i=[],notice:d,styles:u,dark:c=!1,onDepositSuccess:f,onDepositClick:h,onWithdrawClick:g,onCompleteDeposit:x,showModeToggle:m=!1,defaultMode:y})=>{const C=l.useContext(p.SpiceFlowProviderContext),k=C?.mode!=="7702",b=!!C?.isWhitelistGateActive,R=!!C?.isWhitelistConfigured&&C?.isUserWhitelisted!==!0,v=l.useRef(!1);l.useEffect(()=>{if(!v.current){if(p.hasStoredSpiceFlowMode()){v.current=!0;return}y&&C?.setMode&&(C.setMode(y==="non7702"?"ondemand":"7702"),v.current=!0)}},[C,y]);const[w,T]=l.useState(!1),[I,F]=l.useState(null),[j,A]=l.useState({top:0,bottom:0,left:0,placement:"below"}),E=l.useRef(null),S=l.useRef(null),{address:M,isConnected:U}=p.useWallet(),W=C?.embeddedWalletAddress,O=C?.externalWalletAddress,{embeddedAddress:z}=p.useProviderWallets(),{dark:N,primaryColor:P,dk:Q}=p.useSpiceBrand(u,c),K=k&&!O,V=!k||K,X=V?W||z:M,xe=l.useMemo(()=>C?.supportedChainIds??B.getChainIdsByNetwork("mainnet"),[C?.supportedChainIds]),{assets:H,loading:J}=jn({address:X,supportedChains:xe,enabled:!!X&&V,refetchInterval:3e4}),se=l.useMemo(()=>{const ke=V?H.map(fe=>{const Me=fe.balanceUsd||0,xt=Number.isFinite(fe.balanceFormatted)?fe.balanceFormatted:0,yt=Me>0?Me:Gl(fe,a)*xt;return{tokenAddress:fe.address,tokenSymbol:fe.symbol,tokenDisplaySymbol:ps(fe),tokenDisplayName:ga(fe),tokenDecimals:fe.decimals,chainId:fe.chainId,chainDisplayName:fs(fe),balance:fe.balance.toString(),balanceFormatted:fe.balanceFormatted,usdValue:yt,logoURI:fe.logoURI}}):[],we=K?[]:r;return[...ke,...we].filter(fe=>fe.balanceFormatted>0)},[V,K,H,a,r]),ce=l.useMemo(()=>se.reduce((ke,we)=>ke+we.usdValue,0),[se]),{pendingDeposits:de}=dr({chainIds:xe,enabled:!!M,discoverWalletBalances:!0}),ve=l.useMemo(()=>s.reduce((ke,we)=>ke+we.totalValue,0),[s]),ue=ce+ve,pe=l.useMemo(()=>{const ke=[];ce>0&&ke.push(`${p.formatUsd(ce)} idle`);for(const we of s){const fe=i.find(Me=>Me.sectionTitle===we.title)?.label||we.title.toLowerCase();ke.push(`${p.formatUsd(we.totalValue)} ${fe}`)}return ke.join(" \xB7 ")},[ce,s,i]),Ee=l.useCallback(ke=>{x?x(ke):F(ke)},[x]),L=l.useCallback(()=>{F(null)},[]),ee=l.useCallback(()=>{F(null),f?.()},[f]),te=l.useCallback(()=>{if(!E.current)return;const ke=E.current.getBoundingClientRect(),we=window.innerHeight-ke.bottom-ln,fe=ke.top-ln,Me=we>=400||we>=fe?"below":"above",xt=Math.max(ln,Math.min(ke.right-Os,window.innerWidth-Os-ln)),yt=Me==="below"?ke.bottom+ln:ke.top-ln,Bt=Me==="above"?window.innerHeight-yt:0;A({top:yt,bottom:Bt,left:xt,placement:Me})},[]);l.useLayoutEffect(()=>{w&&te()},[w,te]),l.useEffect(()=>{if(!w)return;const ke=Me=>{E.current&&!E.current.contains(Me.target)&&S.current&&!S.current.contains(Me.target)&&T(!1)},we=Me=>{Me.key==="Escape"&&T(!1)},fe=()=>te();return document.addEventListener("mousedown",ke),document.addEventListener("keydown",we),window.addEventListener("scroll",fe,{passive:!0}),window.addEventListener("resize",te),()=>{document.removeEventListener("mousedown",ke),document.removeEventListener("keydown",we),window.removeEventListener("scroll",fe),window.removeEventListener("resize",te)}},[w,te]);const oe=V?W||z||M:O||M,Z=l.useCallback(()=>{C?.setMode&&C.setMode(V?"ondemand":"7702")},[C,V]),[ne,ge]=l.useState(null);let G=null;try{G=$s.useConnectWallet({onSuccess:()=>ge(null),onError:ke=>ge(p.sanitizeError(ke,"Failed to connect wallet."))}).connectWallet}catch{G=null}const Ie=l.useCallback(()=>{G&&(T(!1),ge(null),G({walletChainType:"ethereum-only"}))},[G]),ze=!O&&!!G,Ke=l.useCallback(()=>{T(!1),h?.()},[h]),Ft=l.useCallback(()=>{T(!1),g?.()},[g]),mt=l.useCallback(ke=>{T(!1),Ee(ke)},[Ee]),{withdraw:Le}=Kl(),[le,Ae]=l.useState(null),Xe=Hl({embeddedAddress:W||z,externalAddress:O}),et=l.useCallback(async ke=>{if(!O)return;const we=`${ke.tokenAddress}-${ke.chainId}`;Ae({key:we,step:"pending"});try{await Le({tokenAddress:ke.tokenAddress,chainId:ke.chainId,balance:BigInt(ke.balance),recipient:O}),Ae(null)}catch(fe){Ae({key:we,step:"error",message:p.sanitizeError(fe,"Withdraw failed")})}},[Le,O]);if(typeof window>"u")return null;const ae=o.jsxs("button",{ref:E,onClick:()=>T(!w),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:N?Q.hoverBg:"#ffffff",border:N?`1px solid ${Q.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:p.font.ui,color:N?Q.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:N?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[o.jsxs("span",{children:[e," Account"]}),U&&o.jsxs("span",{style:{color:N?Q.textSecondary:"#6b7280"},children:["\xB7 ",p.formatUsd(ue)]}),o.jsx("span",{style:{fontSize:"10px",color:N?Q.textSecondary:"#9ca3af",transform:w?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),nt=w?Cn.createPortal(o.jsxs(o.Fragment,{children:[o.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:p.z.popover},onClick:()=>T(!1)}),o.jsx("div",{ref:S,style:{position:"fixed",top:j.placement==="below"?`${j.top}px`:"auto",bottom:j.placement==="above"?`${j.bottom}px`:"auto",left:`${j.left}px`,width:`${Os}px`,maxWidth:`calc(100vw - ${ln*2}px)`,maxHeight:"80vh",backgroundColor:N?Q.shell:"#ffffff",border:N?`1px solid ${Q.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:N?"0 10px 40px rgba(0, 0, 0, 0.5)":"0 10px 40px rgba(0, 0, 0, 0.12)",zIndex:p.z.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${p.easing.out}`},children:o.jsx(Ol,{appName:e,status:t,statusLabel:n,totalUsdValue:ue,breakdownSubtitle:pe,address:V?oe:M,spiceAssets:se,spiceAssetsLoading:J,pendingDeposits:de,customSections:s,notice:d,onDepositClick:h?Ke:void 0,onWithdrawClick:g?Ft:void 0,depositDisabled:R,onCompleteDeposit:mt,primaryColor:P,dk:Q,dark:N,showModeToggle:m,isEmbeddedMode:V,onModeToggle:Z,showConnectExternalCta:ze,onConnectExternalWallet:Ie,connectExternalError:ne,showHowItWorks:!b,canDirectWithdraw:Xe,onDirectWithdraw:et,directWithdrawState:le})}),o.jsx("style",{children:`
|
|
81
81
|
@keyframes accountDisplayFadeIn {
|
|
82
82
|
from { opacity: 0; transform: translateY(-4px); }
|
|
83
83
|
to { opacity: 1; transform: translateY(0); }
|
|
84
84
|
}
|
|
85
|
-
`})]}),document.body):null;return o.jsxs(o.Fragment,{children:[ae,nt,I&&Cn.createPortal(o.jsx(Po,{isOpen:!0,onClose:L,supportedChains:[I.chainId],escrowOnly:!0,escrowTokenAddress:I.tokenAddress,escrowAmount:I.amount,escrowTokenDecimals:I.tokenDecimals,escrowTokenSymbol:I.tokenSymbol,styles:u,onDepositSuccess:ee}),document.body)]})},$l="0xa9059cbb";function fr(e,t,n){return B.isNativeToken(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"transfer",args:[n,t]})}}function hr(e,t,n){return{chainId:n,calls:[fr(e,t,B.getEscrowContractAddress(n))]}}function mr(e,t,n){return!t&&e?.asset?._source==="wallet"&&e?.asset.chainId===n}function gr(e,t,n,s){return t!=="user-transfer"||!n||e.length===0||e[0]?.to.toLowerCase()!==s.toLowerCase()||!e[0]?.data.startsWith($l)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function Jn(e,t,n,s){if(!t)return[e];const r=await t({...n,requestTimestampMs:s});return r?[r,e]:[e]}function Hs(e){return e.filter(t=>t.domain!=="spicenet")}function $n(e){const t=(e.tokenTransfers??[]).filter(n=>n.from==="escrow").map(n=>({token:B.normalizeNativeTokenAddress(n.token),recipient:n.to,amount:BigInt(n.amount)})).filter(n=>n.amount>0n);return t.length>0?t:void 0}function Ot(e,t,n){return Vo(e,t,n,"ceil")}async function xr(e,t){const{currentPaymentAmount:n,destinationToken:s,embeddedWalletAddress:r,providerEmbeddedAddress:a,address:i,isNon7702:d,isPayMode:u,resolvedChainId:c,buildActionCalls:f,feeExecutionMode:h,buildSpicenetBatch:g,selectedAsset:x,needsSwap:m,exactOutputSwap:y,resolvedTokenIn:C,requestTimestampMs:k}=e,b=D.parseUnits(n,s.decimals),R=t?.actionAmountOverride??b,v=r||a||(d?void 0:i);if(!v)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const w={userAddress:v,chainId:c,destinationToken:s.address,grossAmount:t?.fundingAmountOverride??b,netAmount:R,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:h,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},T=f(R,w),I={chainId:c,calls:T},F=!u&&!d?!0:x?.asset?._source==="spice",j=mr(x??null,d,c),A=F||d||j,E=(M,U)=>({token:M,from:"escrow",to:v,amount:U}),S=(M,U,W)=>j?[hr(M,U,c),...W]:W;if(b===0n)return[I];if(m&&y){const M=C??zt(x.asset,c)??x.asset.address,U=t?.fundingAmountOverride??y.amountInMax,W=A?[E(M,U)]:[],O={to:M,value:0n,data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"approve",args:[y.calls[0]?.to,y.amountInMax]})},z={chainId:c,calls:[O,...y.calls,...T],tokenTransfers:[...W,...I.tokenTransfers??[]]};if(!A)return[z];const N=await Jn(z,g,{userAddress:v,destinationChainId:c,deliveryToken:M,deliveryAmount:U,deliveryRecipient:v,deliveryTransfers:$n(z),sourceAsset:x.asset},k);return S(M,U,N)}if(A){const M=C??zt(x.asset,c)??s.address;if(j&&M.toLowerCase()===s.address.toLowerCase())return[I];const U=t?.fundingAmountOverride??b,W={...I,tokenTransfers:[E(M,U),...I.tokenTransfers??[]]},O=await Jn(W,g,{userAddress:v,destinationChainId:c,deliveryToken:M,deliveryAmount:U,deliveryRecipient:v,deliveryTransfers:$n(W),sourceAsset:x.asset},k);return S(M,U,O)}return[I]}async function yr(e,t){const{selectedAsset:n,embeddedWalletAddress:s,externalWalletAddress:r,recipient:a,resolvedChainId:i,destinationToken:d,buildActionCalls:u,feeExecutionMode:c,buildSpicenetBatch:f,isPayMode:h,isNon7702:g,needsSwap:x,resolvedSwap:m,quoteAmountOut:y,resolvedTokenIn:C,requestTimestampMs:k}=e,b=m?.amountOutMinimum??y;if(!n?.asset||!s)return[];const R=a??(g?r:s);if(!R)return[];const v=t?.fundingAmountOverride??t?.actionAmountOverride??D.parseUnits(n.amount,n.asset.decimals),w=t?.fundingAmountOverride??v,T=t?.sourceFundingAmountOverride??v,I=t?.deliveryAmountOverride??w,F=t?.withdrawalAmountOverride??I,j=t?.actionAmountOverride??v,A={userAddress:R,chainId:i,destinationToken:d.address,feeToken:c==="user-transfer"&&x&&C?C:d.address,grossAmount:w,netAmount:j,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:c,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},E=u(j,A),S=n.asset?._source==="wallet";if(!h&&g&&S&&n.asset.chainId===i){if(x){if(!C)throw new Error("Swap input token could not be resolved");if(!m||b===null)throw new Error("Swap quote not available yet")}if(x&&m&&b){const V=u(t?.actionAmountOverride??b,{...A,netAmount:t?.actionAmountOverride??b}),{feeCall:X,remainingCalls:xe}=gr(V,c,x,A.feeToken);return[{chainId:i,calls:[...X?[X]:[],...m.calls,...xe]}]}return[{chainId:i,calls:E}]}if(!h&&!g&&S&&n.asset.chainId!==i)throw new Error("Cross-chain wallet supplies require external wallet mode");const M=!h&&!g?n.asset?._source!=="wallet":n.asset?._source==="spice",U=g&&S,W=mr(n,g,i);if(!(M||U||W))return[{chainId:i,calls:E}];const O=W?hr(C??B.normalizeNativeTokenAddress(n.asset.address),T,i):U&&n.asset.chainId!==i?{chainId:n.asset.chainId,calls:[fr(B.normalizeNativeTokenAddress(n.asset.address),T,B.getEscrowContractAddress(n.asset.chainId))]}:null,z=(V,X)=>({token:V,from:U?"solver":"escrow",to:s,amount:X}),N=(V,X)=>U?[{token:V,from:"escrow",to:B.SPICE_SOLVER_ADDRESS,amount:X}]:[];if(x){if(!C)throw new Error("Swap input token could not be resolved");if(!m||b===null)throw new Error("Swap quote not available yet")}if(x&&m&&b&&C){const V=u(t?.actionAmountOverride??b,{...A,netAmount:t?.actionAmountOverride??b}),{feeCall:X,remainingCalls:xe}=gr(V,c,x,A.feeToken),H={chainId:i,calls:[...X?[X]:[],...m.calls,...xe],tokenTransfers:[...N(C,F),z(C,I)]},J=await Jn(H,f,{userAddress:s,destinationChainId:i,deliveryToken:C,deliveryAmount:I,withdrawalAmount:F,deliveryRecipient:s,deliveryTransfers:$n(H),sourceAsset:n.asset},k);return O?[O,...J]:J}const P=C??zt(n.asset,i)??d.address,Q={chainId:i,calls:E,tokenTransfers:[...N(P,F),z(P,I)]},K=await Jn(Q,f,{userAddress:s,destinationChainId:i,deliveryToken:P,deliveryAmount:I,withdrawalAmount:F,deliveryRecipient:s,deliveryTransfers:$n(Q),sourceAsset:n.asset},k);return O?[O,...K]:K}async function Cr(e,t,n,s,r){let a=e;for(let i=0;i<4;i++){const d=await t(a),u=await s(d,n,a,r),c=ri(u);if(c===null||c>=e)return a;const f=a-c,h=e+f;if(h<=a)return a;a=h}return a}function _l(e,t,n,s){if(e<=0n)return 0n;const r=e-t;if(r<=0n)return 0n;const a=s+n;return a<=0n?r:r*s/a}async function br(e){const{asset:t,isPayMode:n,isNon7702:s,needsSwap:r,isQuoting:a,embeddedWalletAddress:i,buildSupplyChainBatches:d,estimate:u,executionTokenAddress:c,feeExecutionMode:f}=e;if(n||s||r||a||!i||t.balance<=0n)return null;const h=i,g=await d({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(g.length===0)return null;const x=g.some(R=>R.tokenTransfers?.length),m=await u(g,c,t.balance,x?{userOverride:h,useCustomTransfers:!0,feeExecutionMode:f}:f?{userOverride:h,feeExecutionMode:f}:{userOverride:h}),y=Zt(m,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),C=y?Ot(y.gasFee,y.decimals,t.decimals):0n,k=y?Ot(y.spicenetFee,y.decimals,t.decimals):0n,b=_l(t.balance,C,k,t.balance);return b>0n?So(b,t.decimals):null}async function wr(e){const{selectedAsset:t,isPayMode:n,parsedAmount:s,needsSwap:r,exactOutputSwap:a,isNon7702:i,isSourceDestToken:d,currentPaymentAmount:u,destinationToken:c,feeExecutionMode:f,resolvedTokenIn:h,embeddedWalletAddress:g,providerEmbeddedAddress:x,resolvedChainId:m,isConnected:y,address:C,ready:k,authenticated:b,isDirect:R,resolvedSwap:v,isQuoting:w,executionTokenAddress:T,buildPayChainBatches:I,buildSupplyChainBatches:F,estimate:j,estimateRequiredGrossFunding:A}=e;if(!t?.asset)return null;if(n){if(s<=0||r&&!a||d)return null;const N=D.parseUnits(u,c.decimals),P=h||zt(t.asset,m)||t.asset.address||c.address,Q={chainId:m,tokenAddress:P,symbol:B.getTokenByAddress(P,m)?.symbol??t.asset.symbol,decimals:B.getTokenByAddress(P,m)?.decimals??t.asset.decimals};if(i){const J=g||x;if(!J)return null;const se=r?a?.amountInMax??0n:N;if(se===0n)return null;const ce={userOverride:J,useCustomTransfers:!0},de=await A(se,pe=>I({fundingAmountOverride:pe}),P,ce),ve=await I({fundingAmountOverride:de}),ue=await j(ve,P,de,{...ce,feeExecutionMode:f});return Zt(ue,Q)}if(!y||!C||!k||!b)return null;const K=g||x||C,V=r?a?.amountInMax??0n:N;if(V===0n)return null;const X=await A(V,J=>I({fundingAmountOverride:J}).then(se=>_t(Hs(se),K)),P,{useCustomTransfers:!0});let xe=_t(Hs(await I({fundingAmountOverride:X})),K);const H=await j(xe,P,X,{useCustomTransfers:!0,feeExecutionMode:f});return Zt(H,Q)}if(s<=0||!g)return null;const E=g||x;if(!(!n&&!i&&t.asset?._source==="wallet"&&t.asset.chainId!==m)&&!R&&!v&&!w||w)return null;const S=D.parseUnits(t.amount,t.asset.decimals),M=await F();if(M.length===0)return null;const U=i&&t.asset?._source==="wallet"&&t.asset.chainId===m,W={chainId:m,tokenAddress:T,symbol:B.getTokenByAddress(T,m)?.symbol??c.symbol,decimals:B.getTokenByAddress(T,m)?.decimals??c.decimals};if(U){const N=await p.relayerService.estimateBatchGas({user:E,outputToken:T,stepIndex:0,chainBatches:M}),P=Qn(S,10n),Q=P+N.gasFee;return{...W,grossAmount:S+Q,netAmount:S,totalFee:Q,gasFee:N.gasFee,spicenetFee:P,bridgeFee:0n,gasQuoteSource:N.gasQuoteSource}}const O=M.some(N=>N.tokenTransfers?.length),z=await j(M,T,S,O?{userOverride:E,useCustomTransfers:!0,feeExecutionMode:f}:f?{userOverride:E,feeExecutionMode:f}:{userOverride:E});return Zt(z,W)}const ec=10n;function kr(e,t){const n=e.selectedAsset?.asset;if(!n||n?._source!=="wallet")return;const s=zt(n,e.resolvedChainId);if(!s||!p.addressesEqual(s,e.executionTokenAddress))return;const r=B.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),a=Ot(t,r?.decimals??e.destinationToken.decimals,n.decimals);if(a<=n.balance)return;const i=D.formatUnits(a,n.decimals),d=D.formatUnits(n.balance,n.decimals);throw new Error(`Insufficient ${n.symbol} for amount plus fees. Required ${i} ${n.symbol}; available ${d} ${n.symbol}.`)}function Qs(e){const t=B.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:t?.symbol??e.destinationToken.symbol,decimals:t?.decimals??e.destinationToken.decimals}}function Bn(e,t,n){const s=Zt(e,Qs(t));if(!s)return;const r=Qn(n,ec),a=s.bridgeFee??0n,i=r+s.gasFee+a;return{grossAmount:n+i,netAmount:n,combinedFeeAmount:i,feeExecutionMode:"user-transfer",feeBreakdown:{spicenetFee:r,gasFee:s.gasFee,bridgeFee:a}}}function tc(e,t,n){let s=0n,r=0n;const a=n.toLowerCase();for(const i of e)if(i.chainId===t){for(const d of i.calls??[])if(d.to.toLowerCase()===a)try{const u=D.decodeFunctionData({abi:D.erc20Abi,data:d.data});if(u.functionName!=="transfer")continue;const c=u.args[0].toLowerCase(),f=u.args[1];c===B.SPICE_PLATFORM_FEE_RECIPIENT.toLowerCase()?s+=f:c===B.SPICE_GAS_FEE_RECIPIENT.toLowerCase()&&(r+=f)}catch{continue}}return{spicenetFee:s,gasFee:r}}function Vs(e,t,n){const s=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,r=tc(e,t.resolvedChainId,s);return r.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||r.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:Jt(r.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&Jt(r.gasFee,n.feeBreakdown.gasFee,100n)}function vr(e,t){return e?Jt(e.grossAmount,t.grossAmount,100n)&&Jt(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&Jt(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&Jt(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}function _n(e,t,n,s){const r=Hs(e),a=u=>(u.tokenTransfers??[]).some(c=>c.from==="escrow"),i=r.filter(u=>!a(u)),d=r.filter(a);return[...i,..._t(d,t,n,s)]}function Sr(e,t){const n=e.selectedIsEquivalent?t:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(n===0n)throw new Error("Quote not available yet");return n}function Ar(e,t,n){const s=t instanceof Error?t:new Error(String(t));if(s.name==="AbortError"||n){e.ui.setStep("idle");return}const r=s.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(r),e.ui.setError(r)}function Ir(e,t){const n=p.sanitizeError(t,"Payment failed. Please try again.");e.ui.setError(n),e.ui.setPaymentResult({status:"failed",error:n})}async function Er(e){if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.isNon7702){const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setTxHash(null);try{if(e.isSourceDestToken){e.ui.setStep("executing"),e.ui.setStatusMsg("Submitting transaction...");const s=await jr(e);e.ui.setTxHash(s??null)}else{e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.refs.spiceDepositSubmittedRef.current=!1;const s=new AbortController;e.refs.abortControllerRef.current=s,await nc(e,s.signal)}e.ui.setStep("success"),e.ui.setStatusMsg(e.isSourceDestToken?"Transaction confirmed":"Deposit confirmed")}catch(s){Ar(e,s,!!e.refs.abortControllerRef.current?.signal.aborted)}finally{e.ui.setIsExecuting(!1)}return}if(!e.embeddedWalletAddress){e.ui.setError("Wallet not ready");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.ui.setTxHash(null),e.refs.spiceDepositSubmittedRef.current=!1;const t=new AbortController;e.refs.abortControllerRef.current=t;try{const n=D.parseUnits(e.selectedAsset.amount,e.selectedAsset.asset.decimals),s=n;let r=await e.execution.buildSupplyChainBatches();const a=e.selectedAsset.asset?._source==="wallet",i=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!a&&!r.some(x=>B.isSpicenetChainId(x.chainId)))throw new Error("Spice-funded supplies must include a Spicenet funding batch before the destination chain batch.");const d=r.some(x=>x.tokenTransfers?.length)?{userOverride:i,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}:e.feeExecutionMode?{userOverride:i,feeExecutionMode:e.feeExecutionMode}:{userOverride:i};let u=n;const c=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,f=e.feeExecutionMode==="user-transfer"&&!c?s:void 0;let h;for(let x=0;x<4;x+=1){const m=await e.execution.estimate(r,e.executionTokenAddress,u,d),y=Zt(m,Qs(e));h=e.feeExecutionMode==="user-transfer"&&y?Bn(m,e,s):void 0;const C=h?.grossAmount??y?.grossAmount??u;if(C===u){u=C;break}u=C,r=await e.execution.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:f,actionContextOverride:h})}e.feeExecutionMode==="user-transfer"&&(kr(e,u),r=await e.execution.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:f,actionContextOverride:h}));let g=h;await e.execution.execute(r,e.executionTokenAddress,u,e.execution.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...d,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:x,chainBatches:m})=>{const y=Bn(x,e,s);if(!y)return null;const C=vr(g,y),k=Vs(m,e,y);return C||k?null:(g=y,e.execution.buildSupplyChainBatches({fundingAmountOverride:y.grossAmount,actionAmountOverride:f,actionContextOverride:y}))}}:d),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){Ar(e,n,t.signal.aborted)}finally{e.ui.setIsExecuting(!1)}}async function nc(e,t){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const n=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!n)throw new Error("Embedded wallet not available \u2014 sign in to create one before supplying");const s=e.selectedAsset.asset,r=D.parseUnits(e.selectedAsset.amount,s.decimals),a=r,i=s?._source==="wallet"&&s.chainId===e.resolvedChainId;let d=await e.execution.buildSupplyChainBatches();const u={userOverride:n,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,signAuthorizationsForEstimate:!0};let c=r;const f=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,h=e.feeExecutionMode==="user-transfer"&&!f?a:void 0;let g;if(i){const j=await p.relayerService.estimateBatchGas({user:n,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:d}),A=Qn(r,10n),E=A+j.gasFee;c=r+E,e.feeExecutionMode==="user-transfer"&&(g={grossAmount:c,netAmount:a,combinedFeeAmount:E,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:A,gasFee:j.gasFee,bridgeFee:0n}})}else for(let j=0;j<4;j+=1){const A=await e.execution.estimate(d,e.executionTokenAddress,0n,u),E=e.feeExecutionMode==="user-transfer"?Bn(A,e,a):void 0,S=Zt(A,Qs(e)),M=E?.grossAmount??(S?S.grossAmount>r?S.grossAmount:r:c);if(g=E,M===c){c=M;break}c=M;const U=B.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),W=Ot(c,U?.decimals??e.destinationToken.decimals,s.decimals);d=await e.execution.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:W,withdrawalAmountOverride:c,actionAmountOverride:h,actionContextOverride:E})}const x=B.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);let m=i?c:Ot(c,x?.decimals??e.destinationToken.decimals,s.decimals);kr(e,c),d=await e.execution.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:m,withdrawalAmountOverride:c,actionAmountOverride:h,actionContextOverride:g});const y=s.chainId,C=n,{extWc:k,viemChain:b}=await xn({wallet:e.externalWallet,account:e.externalWalletAddress,chainId:y,onSwitch:()=>e.ui.setStatusMsg("Switching source network...")}),R=B.normalizeNativeTokenAddress(s.address),v=s.isNative||B.isNativeToken(R),w=p.getClientForChain(y),T=j=>js({extWc:k,sourceClient:w,recipient:C,tokenAddr:R,isNative:v,amount:j,viemChain:b});e.ui.setStatusMsg("Funding embedded wallet..."),await T(m);let I=m;if(e.feeExecutionMode==="user-transfer")for(let j=0;j<4;j+=1){const A=await e.execution.estimate(d,e.executionTokenAddress,0n,u),E=Bn(A,e,a);if(!E)break;const S=i?E.grossAmount:Ot(E.grossAmount,x?.decimals??e.destinationToken.decimals,s.decimals);if(S>I&&(e.ui.setStatusMsg("Topping up embedded wallet..."),await T(S-I),I=S),g=E,c=E.grossAmount,m=S,d=await e.execution.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:m,withdrawalAmountOverride:c,actionAmountOverride:h,actionContextOverride:E}),Vs(d,e,E))break}e.ui.setStatusMsg("Signing supply intent...");let F=g;await e.execution.execute(d,e.executionTokenAddress,0n,e.execution.onProgress,t,e.feeExecutionMode==="user-transfer"?{...u,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:j,chainBatches:A})=>{const E=Bn(j,e,a);if(!E)return null;const S=vr(F,E),M=Vs(A,e,E);if(S||M)return null;if(E.grossAmount>c)throw new Error("Fee estimate increased after wallet funding. Please retry so the signed fee can match the latest relayer estimate.");F=E;const U=i?E.grossAmount:Ot(E.grossAmount,x?.decimals??e.destinationToken.decimals,s.decimals);return e.execution.buildSupplyChainBatches({fundingAmountOverride:E.grossAmount,sourceFundingAmountOverride:U,withdrawalAmountOverride:E.grossAmount,actionAmountOverride:h,actionContextOverride:E})}}:u)}async function jr(e){const t=e.isPayMode&&e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t)throw new Error("Select a payment source");const n=e.activeSignerWallet??e.externalWallet,s=e.activeSignerAddress??e.externalWalletAddress;if(!s||!n)throw new Error("Please connect your wallet to continue");const r=D.parseUnits(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),a={userAddress:s,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},i=e.buildActionCalls(r,a);if(i.length===0)throw new Error("No action calls configured");const{extWc:d,viemChain:u}=await xn({wallet:n,account:s,chainId:e.resolvedChainId}),c=p.getClientForChain(e.resolvedChainId);return Ro({extWc:d,client:c,calls:i,viemChain:u,errorMessage:"Transaction failed"})}async function sc(e){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const n=e.selectedAsset.asset,s=n.chainId,r=D.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),a=Sr(e,r),i=e.resolvedTokenIn||e.selectedAsset.asset.address,d={userOverride:t,useCustomTransfers:!0},u=B.getEscrowContractAddress(s),c=B.normalizeNativeTokenAddress(n.address),f=n.isNative||B.isNativeToken(c),h=t,g=F=>({chainId:s,calls:f?[{to:u,value:F,data:"0x"}]:[{to:c,value:0n,data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"transfer",args:[u,F]})}]}),x=async(F,j,A)=>[g(F),..._n(await e.execution.buildPayChainBatches({fundingAmountOverride:F}),h,j,A)],m=await e.execution.estimateRequiredGrossFunding(a,F=>x(F),i,d);let y=m,C=await x(m);const k=await e.execution.estimate(C,i,m,{...d,feeExecutionMode:e.feeExecutionMode}),b=Zt(k,{chainId:e.resolvedChainId,tokenAddress:i,symbol:B.getTokenByAddress(i,e.resolvedChainId)?.symbol??n.symbol,decimals:B.getTokenByAddress(i,e.resolvedChainId)?.decimals??n.decimals})?.grossAmount??m;b!==m&&(y=b),C=await x(y,k,{payoutAlreadyGross:!0});const{extWc:R,viemChain:v}=await xn({wallet:e.externalWallet,account:e.externalWalletAddress,chainId:s}),w=p.getClientForChain(s);await js({extWc:R,sourceClient:w,recipient:t,tokenAddr:c,isNative:f,amount:y,viemChain:v});const T=C.some(F=>F.tokenTransfers?.length),I={...d,skipUserFundingPreflight:!0};return await e.execution.execute(C,i,T?y:0n,F=>{F.txHash&&(e.ui.setPaymentResult(j=>({...j??{status:"processing"},txHash:F.txHash})),e.ui.setTxHash(F.txHash))},void 0,T?I:{userOverride:t,skipUserFundingPreflight:!0})}async function Fr(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}const t=e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t){e.ui.setError("Select a payment source");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.parsedAmount>0&&e.needsSwap&&!e.exactOutputSwap){e.ui.setError("Swap quote not available. Try a different asset.");return}if(e.isNon7702){const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken||t?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{let s;if(e.isSourceDestToken||e.parsedAmount===0)s=await jr(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const r=e.selectedAsset.asset,a=D.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),i=Sr(e,a),d=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!d)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const u=e.resolvedTokenIn||r.address,c=await e.execution.estimateRequiredGrossFunding(i,g=>e.execution.buildPayChainBatches({fundingAmountOverride:g}),u,{userOverride:d,useCustomTransfers:!0}),f=await e.execution.buildPayChainBatches({fundingAmountOverride:c}),h=await e.onPayExecute({asset:r,amount:e.currentPaymentAmount,amountWei:a,destinationToken:e.destinationToken,chainBatches:f,requiredNetFunding:i,grossFundingAmount:c,selectedIsEquivalent:e.selectedIsEquivalent,resolvedTokenIn:u,exactOutputSwapAmountInMax:e.exactOutputSwap?.amountInMax});h&&(e.ui.setTxHash(h),e.ui.setPaymentResult(g=>({...g??{status:"processing"},txHash:h}))),s=h||void 0}else s=await sc(e);e.ui.setPaymentResult(r=>({status:"success",txHash:r?.txHash||s||""}))}catch(s){Ir(e,s)}finally{e.ui.setIsExecuting(!1)}return}if(!e.isConnected||!e.address){e.ui.setError("Please connect your wallet to continue");return}if(!e.ready||!e.authenticated){e.ui.setError(`Please authenticate with ${e.provider||"wallet provider"} to continue`);return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{const n=D.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),s={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode};if(t){const y=await e.execution.buildPayChainBatches(),C=await e.execution.execute(y,e.executionTokenAddress,0n,k=>{k.txHash&&(e.ui.setPaymentResult(b=>({...b??{status:"processing"},txHash:k.txHash})),e.ui.setTxHash(k.txHash))},void 0,s);e.ui.setPaymentResult(k=>({status:"success",txHash:k?.txHash||C}));return}const r=e.selectedAsset?.asset;if(!r)throw new Error("Select a payment source");const a=e.resolvedTokenIn||r.address||e.destinationToken.address,i=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:n,d=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,u=await e.execution.estimateRequiredGrossFunding(i,y=>e.execution.buildPayChainBatches({fundingAmountOverride:y}).then(C=>_n(C,d)),a,s);let c=u,f=_n(await e.execution.buildPayChainBatches({fundingAmountOverride:u}),d);const h=await e.execution.estimate(f,a,u,s),g=Zt(h,{chainId:e.resolvedChainId,tokenAddress:a,symbol:B.getTokenByAddress(a,e.resolvedChainId)?.symbol??r.symbol,decimals:B.getTokenByAddress(a,e.resolvedChainId)?.decimals??r.decimals})?.grossAmount??u;g!==u&&(c=g),f=_n(await e.execution.buildPayChainBatches({fundingAmountOverride:c}),d,h,{payoutAlreadyGross:!0});const x=f.some(y=>y.tokenTransfers?.length),m=await e.execution.execute(f,a,x?c:0n,y=>{y.txHash&&(e.ui.setPaymentResult(C=>({...C,txHash:y.txHash})),e.ui.setTxHash(y.txHash))},void 0,s);e.ui.setPaymentResult(y=>({status:"success",txHash:y?.txHash||m}))}catch(n){Ir(e,n)}finally{e.ui.setIsExecuting(!1)}}const oc=({variant:e,destinationSymbol:t,destinationLogoURI:n,destinationDecimals:s,primaryColor:r,fontFamily:a,textPrimary:i,textSecondary:d,cardBg:u,cardBorder:c,dk:f,dark:h,isQuoting:g,quoteError:x,estimatedOutput:m,paymentAmount:y,needsSwap:C,exactOutputSwap:k,adjustable:b=!1,maxAmount:R,onAmountChange:v})=>e==="supply"?o.jsxs("div",{style:{backgroundColor:u,border:`1px solid ${c}`,borderRadius:h?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",minHeight:"112px",display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"12px"},children:[o.jsxs("div",{style:{minWidth:0},children:[o.jsx("span",{style:{fontFamily:a,fontSize:"17px",fontWeight:500,color:h?"#a7abb2":"#7D7C7B",lineHeight:"24px"},children:"Used in TX"}),o.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:d,fontFamily:a,marginTop:"10px"},children:"Net amount after swap and fees"})]}),o.jsxs("div",{style:{textAlign:"right",minWidth:0,display:"inline-flex",alignItems:"center",gap:"8px",border:`1px solid ${c}`,borderRadius:"8px",padding:"8px 10px",minHeight:"42px"},children:[o.jsx(Tr,{symbol:t,logoURI:n,primaryColor:r,size:24}),o.jsx("span",{style:{fontSize:"16px",fontWeight:500,color:h?"#f3f4f6":"#3C3E42",lineHeight:"1.3",fontFamily:a,letterSpacing:0},children:t})]})]}),o.jsx("div",{style:{textAlign:"right",minWidth:0},children:g?o.jsx("span",{style:{fontSize:"18px",color:d,fontFamily:a},children:"Quoting..."}):x?o.jsx("span",{style:{fontSize:"13px",color:h?"#f87171":"#dc2626",fontFamily:a},children:"Quote failed"}):m?o.jsx(rn,{value:m,title:m,fontFamily:a,color:i,lineHeight:"0.95",textAlign:"right",maxFontSize:32,minFontSize:18}):o.jsx("span",{style:{fontSize:"20px",color:d,fontFamily:a},children:"\u2014"})})]}):o.jsx(rc,{destinationSymbol:t,destinationLogoURI:n,destinationDecimals:s,primaryColor:r,fontFamily:a,textPrimary:i,textSecondary:d,cardBg:u,cardBorder:c,dk:f,dark:h,paymentAmount:y||"0",needsSwap:C,exactOutputSwap:k,isQuoting:g,adjustable:b,maxAmount:R,onAmountChange:v}),Br=l.memo(oc),Tr=({symbol:e,logoURI:t,primaryColor:n,size:s})=>t?o.jsx("img",{src:t,alt:e,style:{width:s,height:s,borderRadius:"50%",objectFit:"cover"}}):o.jsx("div",{style:{width:s,height:s,borderRadius:"50%",backgroundColor:`${n}22`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:s<30?"11px":"12px",fontWeight:700,color:n},children:e.slice(0,2)}),rc=({destinationSymbol:e,destinationLogoURI:t,destinationDecimals:n,primaryColor:s,fontFamily:r,textPrimary:a,textSecondary:i,cardBg:d,cardBorder:u,dk:c,dark:f,paymentAmount:h,needsSwap:g,exactOutputSwap:x,isQuoting:m,adjustable:y,maxAmount:C,onAmountChange:k})=>{const b=p.font.mono,R=parseFloat(h||"0"),v=C?parseFloat(C):0,[w,T]=l.useState(h||""),I=l.useRef(null),[F,j]=l.useState(null),[A,E]=l.useState(null);l.useEffect(()=>{y||T(h||"")},[h,y]);const S=W=>{let O=W;O.startsWith(".")&&(O="0"+O);const z=p.parseNumericInput(O);let N=z;C&&parseFloat(z)>parseFloat(C)&&(N=C),T(N),I.current&&clearTimeout(I.current),I.current=setTimeout(()=>k?.(N),300)},M=W=>{if(!v)return;if(W===100){T(C||v.toString()),I.current&&clearTimeout(I.current),k?.(C||v.toString());return}const O=10**n,z=Math.floor(v*W/100*O)/O,N=p.formatDecimalInput(z,n);T(N),I.current&&clearTimeout(I.current),k?.(N)},U=v>0?parseFloat(w||"0")/v*100:0;return l.useEffect(()=>()=>{I.current&&clearTimeout(I.current)},[]),o.jsxs("div",{style:{backgroundColor:d,border:`1px solid ${u}`,borderRadius:f?"12px":"6px",padding:"16px",marginBottom:"16px"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[o.jsx(Tr,{symbol:e,logoURI:t,primaryColor:s,size:32}),o.jsxs("div",{children:[o.jsx("span",{style:{fontSize:"14px",fontWeight:600,color:a,fontFamily:r},children:"Payment"}),o.jsx("div",{style:{fontSize:"12px",color:i,fontFamily:r,marginTop:"2px"},children:e})]})]}),o.jsxs("div",{style:{textAlign:"right"},children:[y?o.jsx(rn,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:w,onChange:W=>S(W.target.value),placeholder:"0.0",fontFamily:b,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):o.jsx(rn,{element:"div",value:R>0?h:"0.00",title:R>0?h:"0.00",fontFamily:b,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),o.jsx("div",{style:{fontSize:"12px",color:i,fontFamily:b,marginTop:"2px"},children:e}),y&&v>0&&o.jsx("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((W,O)=>{const z=Math.abs(U-W)<1,N=O===4,P=F===W,Q=A===W;return o.jsx("button",{onClick:()=>M(W),onMouseEnter:()=>j(W),onMouseLeave:()=>{j(null),E(null)},onMouseDown:()=>E(W),onMouseUp:()=>E(null),title:`${W}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:z?1:P?.8:.5,transform:Q?"scale(0.85)":P?"scale(1.15)":"scale(1)",transition:p.transition.interactive},children:o.jsx(cs,{pct:W,isMax:N,primaryColor:s,dark:f,fillColor:f?c?.textSecondary||"#9ca3af":"#3C3E42"})},W)})})]})]}),g&&x&&!m&&o.jsx("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:f?`1px solid ${c?.cardBorder||u}`:"1px solid #e5e7eb",display:"flex",justifyContent:"flex-end"},children:o.jsxs("span",{style:{fontSize:"11px",color:i,fontFamily:r,opacity:.7},children:["via ",x.venue]})})]})},Rr={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},Dr=["signing-delegation","signing-intent","submitting","executing"],ac=({step:e,statusMsg:t,txHash:n,explorerUrl:s,currentStepIdx:r,palette:a,cardBg:i,cardBorder:d,textPrimary:u,textSecondary:c,fontFamily:f,primaryColor:h,onRetry:g})=>o.jsxs("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:e==="success"?i:e==="error"?a.errorBg:i,border:`1px solid ${e==="success"?d:e==="error"?a.errorBorder:d}`},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[e==="success"?o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:o.jsx("path",{d:"M5 13l4 4L19 7",stroke:a.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):e==="error"?o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:o.jsx("path",{d:"M18 6L6 18M6 6l12 12",stroke:a.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):o.jsx(p.Spinner,{size:14,color:h}),o.jsx("span",{style:{fontSize:"13px",fontWeight:500,color:e==="success"?u:e==="error"?a.errorText:u,fontFamily:f,flex:1},children:e==="success"?"Deposit confirmed":e==="error"?t||"Transaction failed":Rr[e]||t}),e==="success"&&n&&o.jsx("a",{href:`${s}/tx/${n}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:h,fontFamily:f,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),e==="error"&&o.jsx("button",{onClick:g,style:{background:"none",border:"none",fontSize:"12px",color:h,fontFamily:f,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),r>=0&&e!=="success"&&e!=="error"&&o.jsx("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${c}22`,overflow:"hidden"},children:o.jsx("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:h,transformOrigin:"left center",transform:`scaleX(${(r+1)/Dr.length})`,transition:"transform 400ms ease"}})})]});function Mr(e,t,n){const s=p.addressesEqual(e.address,t),r=e.chainId===n,a=e._source==="wallet";return a&&s&&r?0:a&&r?1:!a&&s?2:!a&&r?3:4}function Wr(e,t){return!t||t.length===0||t.some(n=>p.addressesEqual(n,e.address))?!0:Object.keys(e.chainTokens??{}).some(n=>{const s=hn(n);return s?t.some(r=>p.addressesEqual(r,s.address)):!1})}function Nr(e,t,n){let{symbol:s,name:r,logoURI:a}=t;const i=p.addressesEqual(e.address,n.address)&&e.chainId===n.chainId;i&&n.logoURI&&(a=n.logoURI),i&&!e.configToken&&s==="TOKEN"&&(s=n.symbol,r=n.symbol);const d=parseFloat((Number(t.balance)/Math.pow(10,t.decimals)).toFixed(6));return{address:e.address,name:r,symbol:s,decimals:t.decimals,balance:t.balance,balanceFormatted:d,balanceUsd:0,logoURI:a,isNative:!1,chainId:e.chainId}}function Pr(e){const{destinationToken:t,supportedSourceAssets:n,sourceChains:s,enabled:r}=e,a=l.useContext(p.SpiceFlowProviderContext),i=(a?.mode||"7702")!=="7702",d=a?.embeddedWalletAddress,{externalAddress:u,embeddedAddress:c,activeAddress:f}=p.useProviderWallets(),h=d||c,{assets:g,refetch:x}=jn({address:h,supportedChains:s,enabled:r&&!i&&!!h,refetchInterval:3e4}),m=l.useMemo(()=>i?[]:g.filter(j=>Wr(j,n)),[g,n,i]),y=i?f??u:d,C=l.useMemo(()=>{const j=new Set,A=[],E=S=>{if(!S)return;const M=S.toLowerCase();j.has(M)||(j.add(M),A.push(D.getAddress(S)))};if(E(t.address),n)for(const S of n)E(S);return A},[i,t.address,n]),k=l.useMemo(()=>C.map(j=>j.toLowerCase()).sort().join(","),[C]),b=l.useMemo(()=>JSON.stringify([...s||[]].sort()),[s]),[R,v]=l.useState([]),w=l.useRef(0),T=l.useRef(async()=>{}),I=l.useCallback(async()=>{if(!r||!y||C.length===0){w.current++,v([]);return}const j=++w.current,A=D.getAddress(y),E=i?s&&s.length>0?s:[t.chainId]:[t.chainId],S=[];for(const O of C){const z=O.toLowerCase();if(z===B.ZERO_ADDRESS)continue;if(z===t.address.toLowerCase()){const P=p.getChainConfig(t.chainId)?.supportedTokens?.find(Q=>p.addressesEqual(Q.address,z));S.push({address:O,chainId:t.chainId,configToken:P?{decimals:P.decimals,symbol:P.symbol,name:P.name,logo:P.logo}:void 0});continue}let N=!1;for(const P of E){const Q=p.getChainConfig(P)?.supportedTokens?.find(K=>p.addressesEqual(K.address,z));if(Q){S.push({address:O,chainId:P,configToken:{decimals:Q.decimals,symbol:Q.symbol,name:Q.name,logo:Q.logo}}),N=!0;break}}N||S.push({address:O,chainId:t.chainId})}const M=new Map;for(const O of S){const z=M.get(O.chainId)||[];z.push(O),M.set(O.chainId,z)}const U=async(O,z)=>{try{const N=await Pt.readContract(O,{address:z.address,abi:D.erc20Abi,functionName:"balanceOf",args:[A]}),{decimals:P,symbol:Q,name:K,logoURI:V}=await or(O,z.address,z.configToken);return Nr(z,{decimals:P,symbol:Q,name:K,logoURI:V,balance:N},t)}catch{return null}},W=await Promise.all(Array.from(M.entries()).map(async([O,z])=>{let N;try{N=p.getClientForChain(O)}catch{return[]}const P=[],Q=[];for(const V of z){const X=P.length;P.push({address:V.address,abi:D.erc20Abi,functionName:"balanceOf",args:[A]}),V.configToken||P.push({address:V.address,abi:D.erc20Abi,functionName:"decimals"},{address:V.address,abi:D.erc20Abi,functionName:"symbol"},{address:V.address,abi:D.erc20Abi,functionName:"name"}),Q.push({start:X,item:V})}let K=null;try{K=await N.multicall({contracts:P})}catch{K=null}return K?Q.map(({start:V,item:X})=>{const xe=K[V],H=xe?.status==="success"?xe.result:0n;let J,se,ce,de;if(X.configToken)J=X.configToken.decimals,se=X.configToken.symbol,ce=X.configToken.name,de=X.configToken.logo;else{const ve=K[V+1],ue=K[V+2],pe=K[V+3];J=ve?.status==="success"?Number(ve.result):18,se=ue?.status==="success"?ue.result:"TOKEN",ce=pe?.status==="success"?pe.result:se}return Nr(X,{decimals:J,symbol:se,name:ce,logoURI:de,balance:H},t)}):(await Promise.all(z.map(V=>U(N,V)))).filter(V=>V!==null)}));j===w.current&&v(W.flat())},[r,i,y,k,b,t.address,t.chainId,t.symbol,t.logoURI]);l.useEffect(()=>{T.current=I},[I]),l.useEffect(()=>{if(!r){v([]);return}T.current();const j=setInterval(()=>{T.current()},15e3);return()=>clearInterval(j)},[r,i,y,k,b,t.address,t.chainId]);const F=l.useCallback(()=>{I()},[I]);return{displayAssets:l.useMemo(()=>{const j=[],A=R.filter(S=>S.balance>0n);for(const S of A)j.push({...S,_source:"wallet"});for(const S of m)j.push({...S,_source:"spice"});const E=t.address.toLowerCase();return j.sort((S,M)=>Mr(S,E,t.chainId)-Mr(M,E,t.chainId)),j},[R,m,t.address,t.chainId]),filteredSpiceAssets:m,walletAssets:R,embeddedWalletAddress:h,externalAddress:u,isNon7702:i,refreshSpiceAssets:x,refreshWalletAssets:F}}async function ic(e){const{tokenIn:t,tokenOut:n,amountIn:s,fee:r,chainId:a,config:i}=e;if(s<=0n)throw new Error("amountIn must be greater than 0");const d=(await p.getClientForChain(a).simulateContract({address:i.quoterV2,abi:B.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:s,fee:r,sqrtPriceLimitX96:0n}]})).result;if(d[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:d[0],sqrtPriceX96After:d[1],gasEstimate:d[3]}}async function Ur(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(r=>ic({...e,fee:r})));let s=null;for(let r=0;r<n.length;r++){const a=n[r];a.status==="fulfilled"&&(!s||a.value.amountOut>s.amountOut)&&(s={...a.value,fee:t[r]})}if(!s)throw new Error("No liquidity found for this pair on any fee tier.");return s}const lc=[{inputs:[{components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"amount",type:"uint256"},{name:"fee",type:"uint24"},{name:"sqrtPriceLimitX96",type:"uint160"}],name:"params",type:"tuple"}],name:"quoteExactOutputSingle",outputs:[{name:"amountIn",type:"uint256"},{name:"sqrtPriceX96After",type:"uint160"},{name:"initializedTicksCrossed",type:"uint32"},{name:"gasEstimate",type:"uint256"}],stateMutability:"nonpayable",type:"function"}];async function cc(e){const{tokenIn:t,tokenOut:n,amountOut:s,fee:r,chainId:a,config:i}=e;if(s<=0n)throw new Error("amountOut must be greater than 0");const d=(await p.getClientForChain(a).simulateContract({address:i.quoterV2,abi:lc,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:s,fee:r,sqrtPriceLimitX96:0n}]})).result;if(d[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:d[0],sqrtPriceX96After:d[1],gasEstimate:d[3]}}async function dc(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(r=>cc({...e,fee:r})));let s=null;for(let r=0;r<n.length;r++){const a=n[r];a.status==="fulfilled"&&(!s||a.value.amountIn<s.amountIn)&&(s={...a.value,fee:t[r]})}if(!s)throw new Error("No liquidity found for this pair on any fee tier.");return s}function uc(e){return e.type==="swap"}const qs=.02,pc=[1,8453,42161,10,137,43114,56],fc="https://api.1inch.dev/swap/v6.0";function Lr(e,t){return B.applySlippage(e,t)}function hc(e){const t=e?.baseUrl??fc;return{name:"1inch",chainIds:e?.chainIds??pc,resolve:async(n,s,r)=>{const a=n.maxSlippage??qs,i=a*100,d=B.isNativeToken(n.tokenIn)?B.NATIVE_TOKEN_ADDRESS:n.tokenIn,u=B.isNativeToken(n.tokenOut)?B.NATIVE_TOKEN_ADDRESS:n.tokenOut,c=B.isNativeToken(n.tokenIn);try{const f=new URL(`${t}/${s}/swap`);f.searchParams.set("src",d),f.searchParams.set("dst",u),f.searchParams.set("amount",n.amountIn.toString()),f.searchParams.set("from",r),f.searchParams.set("slippage",i.toString()),f.searchParams.set("disableEstimate","true"),f.searchParams.set("allowPartialFill","false");const h={Accept:"application/json"};e?.apiKey&&(h.Authorization=`Bearer ${e.apiKey}`);const g=await fetch(f.toString(),{headers:h});if(!g.ok)throw new p.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${g.status} for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:`HTTP ${g.status}`});const x=await g.json();if(!x.dstAmount||!x.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const m=BigInt(x.dstAmount);if(m<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const y=Lr(m,a),C=[];return x.tx.to&&!c&&C.push({to:n.tokenIn,value:0n,data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"approve",args:[x.tx.to,n.amountIn]})}),C.push({to:x.tx.to,value:BigInt(x.tx.value||"0"),data:x.tx.data}),{venue:"1inch",amountOut:m,amountOutMinimum:y,calls:C}}catch(f){if(f instanceof p.SpiceflowError)throw f;const h=f instanceof Error?f.message:String(f);throw new p.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}: ${h}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:h})}}}}const zr=[4114,5115],Ys={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},Or={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[3e3]};function Hr(e){return{name:"satsuma",chainIds:e.chainIds??zr,resolve:async(t,n,s)=>{const r=t.maxSlippage??qs,a=B.isNativeToken(t.tokenIn);let i;try{i=await Ur({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountIn:t.amountIn,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return console.warn(`[SatsumaVenue] No viable fee tier for ${t.tokenIn} \u2192 ${t.tokenOut} on chain ${n}.`),null}const d=Lr(i.amountOut,r),u=[];return a||u.push({to:t.tokenIn,value:0n,data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),u.push({to:e.swapRouter,value:a?t.amountIn:0n,data:D.encodeFunctionData({abi:B.uniV3SwapRouterAbi,functionName:"exactInputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:i.fee,recipient:s,amountIn:t.amountIn,amountOutMinimum:d,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:i.amountOut,amountOutMinimum:d,calls:u}}}}function Qr(e){return{name:"satsuma",chainIds:e.chainIds??zr,resolve:async(t,n,s)=>{const r=t.maxSlippage??qs,a=B.isNativeToken(t.tokenIn);let i;try{i=await dc({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountOut:t.amountOut,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return null}const d=BigInt(Math.round(r*1e4)),u=i.amountIn+i.amountIn*d/10000n,c=[];return c.push({to:e.swapRouter,value:a?u:0n,data:D.encodeFunctionData({abi:mc,functionName:"exactOutputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:i.fee,recipient:s,amountOut:t.amountOut,amountInMaximum:u,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:i.amountIn,amountInMax:u,amountOut:t.amountOut,calls:c}}}}const mc=[{inputs:[{components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"fee",type:"uint24"},{name:"recipient",type:"address"},{name:"amountOut",type:"uint256"},{name:"amountInMaximum",type:"uint256"},{name:"sqrtPriceLimitX96",type:"uint160"}],name:"params",type:"tuple"}],name:"exactOutputSingle",outputs:[{name:"amountIn",type:"uint256"}],stateMutability:"payable",type:"function"}];function Vr(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(Hr(e.satsuma)),t.push(hc(e?.oneInch));function n(r){return t.find(a=>a.chainIds.includes(r))}async function s(r,a,i){const d=[],u=[];for(const c of r){if(!uc(c)){d.push(c);continue}const f=n(a);if(!f)throw new p.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${a}. Cannot resolve swap ${c.tokenIn} \u2192 ${c.tokenOut}.`,{chainId:a,tokenIn:c.tokenIn,tokenOut:c.tokenOut,amountIn:c.amountIn.toString()});const h=await f.resolve(c,a,i);if(!h)throw new p.SpiceflowError("NO_LIQUIDITY",`${f.name} returned no quote for ${c.tokenIn} \u2192 ${c.tokenOut} on chain ${a}.`,{venue:f.name,chainId:a,tokenIn:c.tokenIn,tokenOut:c.tokenOut,amountIn:c.amountIn.toString()});d.push(...h.calls),u.push(h)}return{calls:d,resolvedSwaps:u}}return{resolveSwapIntents:s,getVenueForChain:n,venues:t}}function qr(e){const t=e?.customVenues??[];async function n(s,r,a){const i=t.filter(c=>c.chainIds.includes(r));if(i.length===0)throw new p.SpiceflowError("NO_SWAP_ROUTE",`No exact-output venue supports chain ${r}`,{chainId:r,tokenIn:s.tokenIn,tokenOut:s.tokenOut});const d=(await Promise.allSettled(i.map(async c=>({venue:c,quote:await c.resolve(s,r,a)})))).filter(c=>c.status==="fulfilled").map(c=>c.value).filter(c=>c.quote!==null);if(d.length===0)throw new p.SpiceflowError("NO_SWAP_ROUTE",`All aggregators failed for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${r}`,{chainId:r,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountOut:s.amountOut.toString()});const u=d.find(c=>c.venue.preferred);return u?u.quote:(d.sort((c,f)=>c.quote.amountIn<f.quote.amountIn?-1:c.quote.amountIn>f.quote.amountIn?1:0),d[0].quote)}return{getQuote:n,venues:t}}const Yr=Vr({satsuma:Ys});async function gc(e){const t=Yr.getVenueForChain(e.chainId);if(!t)throw new Error(`No swap venue configured for chain ${e.chainId}.`);const n=await t.resolve({type:"swap",tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:e.amountIn},e.chainId,e.recipient);if(!n)throw new Error("No liquidity for this pair.");return n}function Zr(e){const{direction:t,selectedAsset:n,destinationToken:s,chainId:r,recipient:a,paymentAmount:i,resolveExactOutputSwap:d}=e,[u,c]=l.useState(!1),[f,h]=l.useState(null),[g,x]=l.useState(null),[m,y]=l.useState(null),[C,k]=l.useState(null),[b,R]=l.useState(null),[v,w]=l.useState(null),[T,I]=l.useState(null),[F,j]=l.useState(null),A=l.useRef(null),E=l.useRef(null),S=l.useRef(0),M=l.useRef(new Map),U=l.useMemo(()=>Yr,[]),W=l.useMemo(()=>qr({customVenues:[...d?[{name:"consumer-exact-output",chainIds:[r],preferred:!0,resolve:d}]:[],Qr(Ys),Qr(Or)]}),[d,r]),O=l.useMemo(()=>{if(!n?.asset)return null;const J=zt(n.asset,r);if(J)return J;const se=Xt(n.asset.address,r,n.asset.chainId);return se?se.address:null},[n?.asset,r]),z=l.useMemo(()=>n?.asset?Un(n.asset,r):[],[n?.asset,r]),N=l.useMemo(()=>z.map(J=>J.toLowerCase()).join(","),[z]);l.useEffect(()=>{let J=!1;if(E.current&&(clearTimeout(E.current),E.current=null),!n?.asset||z.length<=1){j(null);return}return E.current=setTimeout(async()=>{const se=t==="input"?n.amount:i||"0";let ce=0n;try{ce=t==="input"?D.parseUnits(se,n.asset.decimals):0n}catch{ce=0n}try{const de=await go(n.asset,r,{requiredAmount:ce});J||j(de)}catch{J||j(null)}},400),()=>{J=!0,E.current&&(clearTimeout(E.current),E.current=null)}},[n?.asset,n?.amount,r,z.length,N,t,i]);const P=l.useMemo(()=>F??O,[F,O]),Q=l.useMemo(()=>!n?.asset||!P?[]:[P,...z.filter(J=>J.toLowerCase()!==P.toLowerCase())],[n?.asset,P,z]),K=l.useMemo(()=>!n?.asset||!An(n.asset.address,n.asset.chainId,s.address,s.chainId)||!P?!1:p.addressesEqual(P,s.address),[n,s.address,s.chainId,P]),V=P?p.addressesEqual(P,s.address):!1,X=t==="output"&&parseFloat(i||"0")===0,xe=!!n?.asset&&!K&&!V&&!X,H=xe?T??P:P;return l.useEffect(()=>{A.current&&clearTimeout(A.current);const J=t==="input"?n?.amount:i,se=parseFloat(J||"0");if(!xe||!Number.isFinite(se)||se<=0||!n?.asset||!a||Q.length===0){S.current++,x(null),y(null),k(null),R(null),w(null),I(null),h(null),c(!1);return}const ce=n.asset.decimals;let de;try{de=t==="input"?D.parseUnits(n.amount,ce):D.parseUnits(i||"0",s.decimals)}catch{S.current++,h("Invalid amount"),c(!1);return}const ve=++S.current,ue=()=>ve!==S.current;c(!0);const pe=t==="output"?150:400,Ee=async(L,ee,te)=>{for(const oe of Q){const Z=`${t}:${r}:${oe.toLowerCase()}:${s.address.toLowerCase()}:${de.toString()}`,ne=M.current.get(Z),ge=ne&&ne.expiresAt>Date.now()?L(ne):void 0;if(ge)return{quote:ge,tokenIn:oe};const G=await te(oe);if(ue())return"stale";if(G)return M.current.set(Z,{expiresAt:Date.now()+3e4,direction:t,...ee(G)}),{quote:G,tokenIn:oe}}return null};return A.current=setTimeout(async()=>{try{if(t==="input"){const L=U.getVenueForChain(r);if(!L)throw new Error("No swap venue for this chain");const ee=await Ee(oe=>oe.resolvedSwap,oe=>({resolvedSwap:oe}),oe=>L.resolve({type:"swap",tokenIn:oe,tokenOut:s.address,amountIn:de},r,a));if(ee==="stale")return;if(!ee)throw new Error("No liquidity for this pair");I(ee.tokenIn),w(ee.quote.amountOut),k(ee.quote),R(null);const te=parseFloat(D.formatUnits(ee.quote.amountOut,s.decimals));x(te<.01?te.toPrecision(4):te.toLocaleString(void 0,{maximumFractionDigits:6})),y(null),h(null)}else{const L=await Ee(ee=>ee.exactOutputSwap,ee=>({exactOutputSwap:ee}),async ee=>{try{return await W.getQuote({tokenIn:ee,tokenOut:s.address,amountOut:de},r,a)}catch{return null}});if(L==="stale")return;if(!L)throw new Error("No liquidity for this pair");I(L.tokenIn),R(L.quote),k(null),w(null),y(parseFloat(D.formatUnits(L.quote.amountIn,ce)).toFixed(6)),x(null),h(null)}}catch(L){if(ue())return;const ee=L instanceof Error?L.message:"Failed to get quote";h(ee),x(null),y(null),k(null),R(null),w(null),I(null)}finally{ue()||c(!1)}},pe),()=>{A.current&&clearTimeout(A.current)}},[t,xe,n?.amount,n?.asset?.address,n?.asset?.decimals,i,Q,r,s.address,s.decimals,a,U,W]),{isQuoting:u,quoteError:f,estimatedOutput:g,estimatedInput:m,resolvedSwap:C,exactOutputSwap:b,quoteAmountOut:v,resolvedTokenIn:H,isDirect:V,needsSwap:xe,selectedIsEquivalent:K}}const xc=()=>{},yc=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,destinationToken:s,sourceChains:r,supportedSourceAssets:a,buildActionCalls:i,feeExecutionMode:d="user-transfer",buildSpicenetBatch:u,onPayExecute:c,resolveExactOutputSwap:f,actionLabel:h,amountDirection:g="input",swapDescription:x,directDescription:m,paymentAmount:y,amountInputMode:C="fixed",minPaymentAmount:k,maxPaymentAmount:b,onAmountChange:R,styles:v,dark:w,title:T,subtitle:I,onAddFunds:F,onSuccess:j,onError:A})=>{const E=g==="output",{theme:S,dark:M,primaryColor:U,dk:W,palette:O,fontFamily:z,monoFont:N,inputDark:P,cardBg:Q,cardBorder:K,textPrimary:V,textSecondary:X,subtitleText:xe}=p.useSpiceBrand(v,w),H=l.useMemo(()=>P?{...S,colors:{...S.colors,secondary:W.cardBg,surfaceHover:W.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:S,[P,S,W.cardBg,W.hoverBg]),J=s.chainId,se=l.useContext(p.SpiceFlowProviderContext),ce=(se?.mode||"7702")!=="7702",de=!!se?.isWhitelistGateActive,ve=!!se?.isWhitelistConfigured&&se?.isUserWhitelisted!==!0,ue=l.useMemo(()=>r??se?.supportedChainIds??[],[r,se?.supportedChainIds]),pe=l.useMemo(()=>{if(de)return[];if(a)return a;const ye=se?.allowedTokens;if(!ye||ye.length===0)return;const tt=new Set(ye.map(ns=>ns.toLowerCase())),pn=[],Wn=new Set;for(const ns of ue){const Gr=p.getChainConfig(ns);for(const ss of Gr?.supportedTokens??[]){if(!tt.has(ss.symbol.toLowerCase()))continue;const Js=ss.address.toLowerCase();Wn.has(Js)||(Wn.add(Js),pn.push(ss.address))}}return pn},[a,se?.allowedTokens,ue,de]),{address:Ee,isConnected:L,isReady:ee,isAuthenticated:te,provider:oe}=p.useWallet(),{execute:Z,estimate:ne}=mn(),{externalWallet:ge,embeddedAddress:G,activeWallet:Ie,activeAddress:ze}=p.useProviderWallets(),Ze=se?.externalWalletAddress,Ft=se?.embeddedWalletAddress||G,{displayAssets:ht,filteredSpiceAssets:Ue,embeddedWalletAddress:le,refreshSpiceAssets:Ae,refreshWalletAssets:Ke}=Pr({destinationToken:s,supportedSourceAssets:pe,sourceChains:ue,enabled:e&&(ce?!!Ze:!!Ft)}),et=de||E||ce?ht:Ue,[ae,nt]=l.useState(null),[ke,we]=l.useState(y||""),[fe,De]=l.useState(!1),[gt,xt]=l.useState(null),Bt=l.useRef(A);Bt.current=A;const Fe=l.useCallback(ye=>{xt(ye),typeof ye=="string"&&ye&&Bt.current?.(new Error(ye),p.getRelayerErrorDetail(ye))},[]),[Xe,yt]=l.useState("idle"),[kt,Tt]=l.useState(""),[Oe,st]=l.useState(null),[Mt,Ct]=l.useState(!1),[he,He]=l.useState(null),[ot,ct]=l.useState(null),[be,mt]=l.useState(!1),[Rt,Ge]=l.useState(!1),[Be,rt]=l.useState(null),Wt=l.useRef(ae),dt=l.useRef(!1),Qe=l.useRef(null),Me=l.useRef(null),ut=l.useRef(null),At=l.useRef(null);l.useEffect(()=>{Wt.current=ae},[ae]);const Ve=C==="adjustable"?ke:y||"0",Ht=le||G||Ee,{isQuoting:Le,quoteError:bt,estimatedOutput:Nt,resolvedSwap:at,exactOutputSwap:Te,quoteAmountOut:pt,resolvedTokenIn:ft,isDirect:it,needsSwap:Je,selectedIsEquivalent:It}=Zr({direction:g,selectedAsset:ae,destinationToken:s,chainId:J,recipient:Ht,paymentAmount:Ve,resolveExactOutputSwap:f}),Y=E?parseFloat(Ve||"0"):parseFloat(ae?.amount||"")||0,$=Y>0&&Y<Kt,re=ae?.asset?._source==="wallet",We=!!ae?.asset&&re&&ae.asset.chainId!==J,_=l.useMemo(()=>ae?.asset?Ue.find(ye=>p.addressesEqual(ye.address,ae.asset.address))?.balanceFormatted??0:0,[ae,Ue]),Ce=re?ae?.asset.balanceFormatted??0:_,Ne=l.useMemo(()=>{if(!ae?.asset)return!1;if(E)return ot?Ot(ot.grossAmount,ot.decimals,ae.asset.decimals)>ae.asset.balance:It||it?Y>ae.asset.balanceFormatted:Te?parseFloat(D.formatUnits(Te.amountInMax,ae.asset.decimals))>ae.asset.balanceFormatted:!1;if(ot){const ye=Ot(ot.grossAmount,ot.decimals,ae.asset.decimals);return re?ye>ae.asset.balance:parseFloat(D.formatUnits(ye,ae.asset.decimals))>Ce}return Y>Ce},[ae,E,ot,It,Y,Te,Ce,re,it]);l.useEffect(()=>{e||(nt(null),Fe(null),De(!1),yt("idle"),Tt(""),st(null),Ct(!1),He(null),ct(null),mt(!1),Ge(!1),rt(null),dt.current=!1,C==="adjustable"&&we(y||""),Qe.current&&(Qe.current.abort(),Qe.current=null))},[e]);const lt=l.useCallback(ye=>{nt(tt=>({asset:ye,amount:tt?.asset?.address===ye.address&&tt?.asset?.chainId===ye.chainId&&tt.amount||""})),Fe(null),rt(null),Ge(!1)},[]),Pe=l.useCallback(ye=>{nt(tt=>tt&&{...tt,amount:ye}),Fe(null),rt(null),Ge(!1)},[]),vt=l.useCallback(ye=>{let tt=ye;b&&parseFloat(tt)>parseFloat(b)&&(tt=b),we(tt),R?.(tt),Fe(null),rt(null),Ge(!1)},[b,R]),Re=l.useCallback(ye=>{yt({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[ye.step]||"executing"),Tt(ye.message),ye.txHash&&st(ye.txHash)},[]),je=l.useMemo(()=>({currentPaymentAmount:Ve,destinationToken:s,embeddedWalletAddress:le,providerEmbeddedAddress:G,externalWalletAddress:Ze,address:Ee,isNon7702:ce,isPayMode:E,resolvedChainId:J,buildActionCalls:i,feeExecutionMode:d,buildSpicenetBatch:u,selectedAsset:ae,needsSwap:Je,resolvedSwap:at,exactOutputSwap:Te,quoteAmountOut:pt,resolvedTokenIn:ft}),[Ve,s,le,G,Ze,Ee,ce,E,J,i,d,u,ae,Je,at,Te,pt,ft]),qe=l.useCallback(ye=>xr({...je,requestTimestampMs:Me.current??Date.now()},ye),[je]),Ye=l.useCallback(ye=>yr({...je,requestTimestampMs:Me.current??Date.now()},ye),[je]),Et=l.useCallback((ye,tt,pn,Wn)=>Cr(ye,tt,pn,ne,Wn),[ne]),St=l.useMemo(()=>ae?.asset?Je&&ft?ft:ae.asset.chainId===J?ae.asset.address:ft??zt(ae.asset,J)??s.address:s.address,[ae,s.address,Je,J,ft]),cn=l.useCallback(()=>(Me.current=Date.now(),Er(At.current)),[]),Dt=l.useMemo(()=>ae?.asset?p.addressesEqual(ae.asset.address,s.address)&&ae.asset.chainId===s.chainId:!1,[ae,s.address,s.chainId]),Ut=Dt&&(ce||E),wt=Ut&&Y>0&&!!ae?.asset,tn=ve&&!Ut,nn=l.useMemo(()=>{if(!wt)return null;let ye;try{ye=D.parseUnits(Ve||"0",s.decimals)}catch{return null}return{symbol:s.symbol,decimals:s.decimals,grossAmount:ye,netAmount:ye,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}},[wt,Ve,s.symbol,s.decimals]),dn=gt,Lt=l.useMemo(()=>!(!ae?.asset||Y<=0),[ae,Y,wt]),yn=l.useMemo(()=>!e||fe||Xe!=="idle"||!Lt||wt||!ae?.asset?null:[E?"pay":"supply",g,ae.asset.address.toLowerCase(),ae.asset.chainId,ae.amount,Ve,s.address.toLowerCase(),s.chainId,J,ft?.toLowerCase()??"",Je?"swap":"direct",it?"direct-token":"routed-token",ce?"non7702":"7702",Dt?"source-dest":"cross-chain",Le?"quoting":"quoted",Te?.amountIn?.toString()??"",Te?.amountInMax?.toString()??"",Te?.venue??"",at?.amountOut?.toString()??"",pt?.toString()??"",le??"",G??"",Ee??""].join("|"),[e,fe,Xe,Lt,wt,ae,E,g,Ve,s,J,ft,Je,it,ce,Dt,Le,Te,at,pt,le,G,Ee]),un=l.useCallback(()=>wr({selectedAsset:ae,isPayMode:E,parsedAmount:Y,needsSwap:Je,exactOutputSwap:Te,isNon7702:ce,isSourceDestToken:Dt,currentPaymentAmount:Ve,destinationToken:s,feeExecutionMode:d,resolvedTokenIn:ft,embeddedWalletAddress:le,providerEmbeddedAddress:G,resolvedChainId:J,isConnected:L,address:Ee,ready:ee,authenticated:te,isDirect:it,resolvedSwap:at,isQuoting:Le,executionTokenAddress:St,buildPayChainBatches:qe,buildSupplyChainBatches:Ye,estimate:ne,estimateRequiredGrossFunding:Et}),[ae,E,Y,Je,Te,ce,Dt,Ve,s,d,ft,le,G,Et,qe,ne,J,L,Ee,ee,te,it,at,Le,Ye,St]);l.useEffect(()=>{ut.current=un},[un]);const Tn=l.useCallback(ye=>br({asset:ye,isPayMode:E,isNon7702:ce,needsSwap:Je,isQuoting:Le,embeddedWalletAddress:le,buildSupplyChainBatches:Ye,estimate:ne,executionTokenAddress:St,feeExecutionMode:d}),[E,ce,Je,Le,le,Ye,ne,St,d]);sr({shouldRun:e&&!fe&&Xe==="idle"&&Lt&&!wt&&!Le&&!!yn,deps:[e,fe,Xe,Lt,wt,nn,Le,yn],onSkip:()=>{if(!e){mt(!1),Ge(!1),rt(null),ct(null);return}if(fe||Xe!=="idle"){mt(!1);return}if(!Lt){ct(null),mt(!1),Ge(!1),rt(null);return}if(wt){ct(nn),mt(!1),Ge(!0),rt(null);return}Le&&(mt(!1),Ge(!1))},onCleanup:()=>mt(!1),run:async({isCurrent:ye})=>{rt(null),mt(!0);try{const tt=await ut.current?.();if(!ye())return;tt?(ct(tt),Ge(!0)):(ct(null),Ge(!1)),rt(null)}catch(tt){if(!ye())return;const pn=p.sanitizeError(tt,"Unable to calculate fees for this action.");ct(null),Ge(!1),rt(pn)}finally{ye()&&mt(!1)}}});const Rn=l.useCallback(()=>(Me.current=Date.now(),Fr(At.current)),[]);l.useEffect(()=>{!E&&Xe==="success"&&Oe&&(Ae(),j?.(Oe))},[E,Xe,Oe,Ae,j]),l.useEffect(()=>{if(!E||he?.status!=="success"||dt.current||!Ee)return;dt.current=!0;const ye=Wt.current;!ye?.asset||ye.asset?._source==="wallet"||Ae()},[E,he?.status,Ee,Ae]);const q=l.useRef(j),ie=l.useRef(A);l.useEffect(()=>{q.current=j},[j]),l.useEffect(()=>{ie.current=A},[A]),l.useEffect(()=>{e&&(Ae(),Ke())},[e,Ae,Ke]),l.useEffect(()=>{E&&(he?.status==="success"&&q.current?.(he.txHash||""),he?.status==="failed"&&ie.current?.(new Error("Payment execution failed")))},[E,he?.status]);const Se=l.useCallback(()=>{Ct(!1),He(null),nt(null),dt.current=!1,Ae(),Ke()},[Ae,Ke]);At.current={selectedAsset:ae,parsedAmount:Y,currentPaymentAmount:Ve,isInsufficientBalance:Ne,isPayMode:E,isNon7702:ce,isSourceDestToken:Dt,needsSwap:Je,exactOutputSwap:Te,selectedIsEquivalent:It,resolvedTokenIn:ft,embeddedWalletAddress:le,providerEmbeddedAddress:G,externalWallet:ge,externalWalletAddress:Ze,activeSignerWallet:Ie,activeSignerAddress:ze,address:Ee,isConnected:L,ready:ee,authenticated:te,provider:oe,resolvedChainId:J,executionTokenAddress:St,destinationToken:s,buildActionCalls:i,feeExecutionMode:d,buildSpicenetBatch:u,onPayExecute:c,onSuccess:j,execution:{estimate:ne,execute:Z,buildPayChainBatches:qe,buildSupplyChainBatches:Ye,estimateRequiredGrossFunding:Et,onProgress:Re},ui:{setError:Fe,setStep:yt,setStatusMsg:Tt,setTxHash:st,setIsExecuting:De,setShowStatusPanel:Ct,setPaymentResult:He},refs:{spiceDepositSubmittedRef:dt,abortControllerRef:Qe}};const me=y?.trim(),$e=E&&C==="fixed"&&me!==void 0&&me!==""&&Y===0,_e=E?($e||!!ae?.asset)&&Y>=0&&!$&&!Ne&&!fe&&($e||wt||Rt)&&!Be&&($e||!Je||!!Te)&&!tn:!!ae?.asset&&Y>0&&!$&&!Ne&&!fe&&(Ut||Rt)&&!Be&&(We||it||!!at&&!Le)&&!tn,sn=it?m||`Your ${s.symbol} will be used directly.`:x||"Your assets will be swapped and used in a single atomic transaction.",Dn=(J?p.getChainConfig(J):void 0)?.viemChain?.blockExplorers?.default?.url??"",Mn=Dr.indexOf(Xe),es=fe?(Rr[Xe]||"EXECUTING...").toUpperCase():Xe==="success"?"DONE":$?`MINIMUM ${Kt}`:Ne?"INSUFFICIENT BALANCE":h.toUpperCase(),ts=l.useMemo(()=>{if(fe)return"PAYING...";if($)return`MINIMUM ${Kt}`;if(Ne&&ae?.asset)return`INSUFFICIENT ${ae.asset.symbol}`;if(h)return h.toUpperCase();const ye=Y>0?` ${Ve} ${s.symbol}`:"";return Je?`SWAP & PAY${ye}`:`PAY${ye}`},[fe,$,Ne,ae,h,Y,Ve,s.symbol,Je]),Kr=Xe==="success"?()=>{yt("idle"),nt(null),st(null),Ae()}:cn,Xr=Xe==="success"?!1:!_e;if(!e)return null;const Zs=E?T||`Pay ${s.symbol}`:h,Ks=E?I:o.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[o.jsx("span",{style:{marginTop:"3px",flexShrink:0},children:o.jsx(Ss,{color:xe})}),o.jsx("p",{style:{fontSize:"12px",color:xe,margin:0,lineHeight:"1.4",fontFamily:z},children:sn})]}),Xs={...v,button:{...v?.button,backgroundColor:U}},Gs=Lt&&o.jsx(Is,{fontFamily:z,textPrimary:V,textSecondary:X,cardBg:Q,cardBorder:K,resolvedDark:M,darkCardBorder:W.cardBorder,primaryColor:U,feePreview:ot,isLoading:be,errorText:Be,directExecutionFeeNote:wt});if(E){const ye=he&&(he.status==="success"||he.status==="failed")?[{asset:{symbol:ae?.asset?.symbol||s.symbol,address:ae?.asset?.address||""},amount:Ve,txHash:he.txHash||"",success:he.status==="success",error:he.status==="failed"?he.error:void 0}]:void 0;return o.jsx(Vt,{isOpen:e,onClose:t,title:Zs,subtitle:Ks,styles:v,dark:M,footerLinkText:"Spicenet accounts \u2192",closeOnBackdropClick:n,children:o.jsxs("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[F&&o.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:o.jsx(Es,{onClick:F,color:U,fontFamily:z})}),!$e&&o.jsx("div",{style:{marginBottom:"12px"},children:o.jsx(vn,{assets:et,selectedAsset:ae??void 0,onAssetSelect:lt,onAmountChange:xc,label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:ae?.asset?Je?Le?"...":Te?`~${parseFloat(D.formatUnits(Te.amountIn,ae.asset.decimals)).toFixed(6)}`:void 0:Ve??void 0:void 0,dark:M,theme:H,styles:v})}),o.jsx(Br,{variant:"pay",destinationSymbol:s.symbol,destinationLogoURI:s.logoURI,destinationDecimals:s.decimals,primaryColor:U,fontFamily:z,textPrimary:V,textSecondary:X,cardBg:Q,cardBorder:K,dk:W,dark:M,isQuoting:Le,quoteError:bt,estimatedOutput:Nt,paymentAmount:Ve,needsSwap:Je,exactOutputSwap:Te,adjustable:C==="adjustable",maxAmount:b,onAmountChange:vt}),Gs,dn&&o.jsx(an,{variant:"error",palette:O,fontFamily:z,style:{marginBottom:"12px"},children:dn}),o.jsx(p.Button,{variant:"outline",fullWidth:!0,onClick:Rn,disabled:!_e,loading:fe,dark:M,styles:Xs,children:ts}),he&&Mt&&o.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:M?W.shell:"white",borderRadius:M?"12px":"6px",padding:"16px 0"},children:o.jsx(Ms,{type:"payment",isOpen:he.status!=="processing",isProcessing:fe||he.status==="processing",closeOnComplete:!1,chainId:J,onRetryTx:()=>{Ct(!1),He(null),Rn()},onNewTx:Se,onClose:()=>{Ct(!1),He(null)},onComplete:Se,results:ye,styles:v,dark:M})})]})})}return o.jsx(Vt,{isOpen:e,onClose:t,title:Zs,subtitle:Ks,dark:M,styles:v,theme:S,closeOnBackdropClick:n,children:o.jsxs("div",{style:{padding:"24px 24px 5px 24px",position:"relative"},children:[o.jsx("div",{style:{marginBottom:"16px"},children:o.jsx(vn,{assets:et,selectedAsset:ae||void 0,onAssetSelect:lt,onAmountChange:Pe,disabled:fe||Xe==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:H,styles:v,dark:P,resolveMaxAmount:Tn,maxAmount:Ce>0?p.formatDecimalInput(Ce,ae?.asset.decimals??s.decimals):void 0})}),ae?.asset&&!it&&o.jsx(Br,{variant:"supply",destinationSymbol:s.symbol,destinationLogoURI:s.logoURI,destinationDecimals:s.decimals,primaryColor:U,fontFamily:z,textPrimary:V,textSecondary:X,cardBg:Q,cardBorder:K,dark:M,isQuoting:Le,quoteError:bt,estimatedOutput:Nt}),Gs,Xe!=="idle"&&o.jsx(ac,{step:Xe,statusMsg:kt,txHash:Oe,explorerUrl:Dn,currentStepIdx:Mn,palette:O,cardBg:Q,cardBorder:K,textPrimary:V,textSecondary:X,fontFamily:z,primaryColor:U,onRetry:()=>{yt("idle"),Fe(null),setTimeout(cn,50)}}),gt&&Xe==="idle"&&o.jsx(an,{variant:"error",palette:O,fontFamily:z,style:{marginBottom:"16px"},children:gt}),o.jsx(p.Button,{variant:"outline",fullWidth:!0,disabled:Xr,onClick:Kr,theme:S,dark:M,styles:Xs,style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:N},children:es})]})})},Cc=()=>{const[e,t]=l.useState("0"),[n,s]=l.useState(null);return{assetAmount:e,setAssetAmount:t,selectedAsset:n,setSelectedAsset:s}};function bc(e,t=0){const[n,s]=l.useState(t),r=e[n]??e[0],a=l.useMemo(()=>r?BigInt(Math.round(r.months*30*24*3600)):0n,[r?.months]);return{selectedDurationIdx:n,setSelectedDurationIdx:s,selectedDuration:r,durationSeconds:a}}function wc(){const{actions:e,isReady:t,isAuthenticated:n}=p.useWallet(),s=l.useContext(p.SpiceFlowProviderContext)?.embeddedWalletAddress,r=l.useRef(!1),a=l.useRef(0),i=l.useRef(null),d=l.useRef(e),[u,c]=l.useState(0);d.current=e,l.useEffect(()=>{r.current=!1,a.current=0,i.current&&(clearTimeout(i.current),i.current=null)},[s]),l.useEffect(()=>{if(!s||!t||!n||r.current)return;r.current=!0;let f=!1;return(async()=>{await qt(2e3);try{await p.ensureSmartWallet(s,d.current.signMessage),a.current=0}catch(h){console.warn("[SmartWallet] Registration failed:",h),r.current=!1,!f&&a.current<3&&(a.current+=1,i.current=setTimeout(()=>{c(g=>g+1)},5e3))}})(),()=>{f=!0,i.current&&(clearTimeout(i.current),i.current=null)}},[s,t,n,u])}ta(),exports.SpiceFlowProvider=p.SpiceFlowProvider,exports.SpiceFlowProviderContext=p.SpiceFlowProviderContext,exports.SpiceflowError=p.SpiceflowError,exports.Spinner=p.Spinner,exports.buildDarkPalette=p.buildDarkPalette,exports.buildLightPalette=p.buildLightPalette,exports.duration=p.duration,exports.easing=p.easing,exports.font=p.font,exports.getChainConfig=p.getChainConfig,exports.getChainName=p.getChainName,exports.isSpiceflowError=p.isSpiceflowError,exports.radius=p.radius,exports.relayerService=p.relayerService,exports.resolveTheme=p.resolveTheme,exports.transition=p.transition,exports.useIsUserWhitelisted=p.useIsUserWhitelisted,exports.useSpiceBrand=p.useSpiceBrand,exports.useWallet=p.useWallet,exports.z=p.z,Object.defineProperty(exports,"NATIVE_TOKEN_ADDRESS",{enumerable:!0,get:function(){return B.ZERO_ADDRESS}}),Object.defineProperty(exports,"SPICENET_NATIVE_CHAIN_ID",{enumerable:!0,get:function(){return B.SPICENET_NATIVE_CHAIN_ID}}),Object.defineProperty(exports,"SPICE_COMBINED_FEE_RECIPIENT",{enumerable:!0,get:function(){return B.SPICE_COMBINED_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_GAS_FEE_RECIPIENT",{enumerable:!0,get:function(){return B.SPICE_GAS_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_PLATFORM_FEE_RECIPIENT",{enumerable:!0,get:function(){return B.SPICE_PLATFORM_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_SOLVER_ADDRESS",{enumerable:!0,get:function(){return B.SPICE_SOLVER_ADDRESS}}),Object.defineProperty(exports,"applySlippage",{enumerable:!0,get:function(){return B.applySlippage}}),Object.defineProperty(exports,"buildUniV3SwapCalls",{enumerable:!0,get:function(){return B.buildUniV3SwapCalls}}),Object.defineProperty(exports,"getChainIdsByNetwork",{enumerable:!0,get:function(){return B.getChainIdsByNetwork}}),Object.defineProperty(exports,"getEscrowContractAddress",{enumerable:!0,get:function(){return B.getEscrowContractAddress}}),Object.defineProperty(exports,"isNativeToken",{enumerable:!0,get:function(){return B.isNativeToken}}),Object.defineProperty(exports,"isSpicenetChainId",{enumerable:!0,get:function(){return B.isSpicenetChainId}}),Object.defineProperty(exports,"normalizeNativeTokenAddress",{enumerable:!0,get:function(){return B.normalizeNativeTokenAddress}}),Object.defineProperty(exports,"spicenetAbi",{enumerable:!0,get:function(){return B.spicenetAbi}}),Object.defineProperty(exports,"spicenetWithdrawalAbi",{enumerable:!0,get:function(){return B.spicenetAbi}}),exports.AccountDisplay=Jl,exports.AddFundsLink=Es,exports.CheckIcon=_s,exports.ChevronIcon=on,exports.CloseIcon=Sn,exports.DetailRow=gn,exports.ProviderLogin=Ds,exports.SATSUMA_CITREA_CONFIG=Ys,exports.SearchInput=rs,exports.SelectChainModal=Li,exports.SpiceDeposit=Ui,exports.SpiceLock=El,exports.SpiceSupply=yc,exports.SpiceWithdraw=dl,exports.StatusBanner=an,exports.UNIV3_BASE_CONFIG=Or,exports.areEquivalentOnChains=An,exports.buildPayChainBatches=xr,exports.buildRoutedBatches=ll,exports.buildSupplyChainBatches=yr,exports.createExactOutputRegistry=qr,exports.createLiquidityRegistry=Vr,exports.createSatsumaVenue=Hr,exports.estimateFeePreview=wr,exports.estimateRequiredGrossFunding=Cr,exports.estimateSupplyMaxAmount=br,exports.executePay=Fr,exports.executeSupply=Er,exports.findEquivalentOnChain=Xt,exports.getAssetChainTokenCandidates=Un,exports.getBestUniV3Quote=Ur,exports.isSupportedSupplyAsset=Wr,exports.resolveAssetTokenAddressOnChain=zt,exports.resolveFundedToken=go,exports.resolveInputSupplySwapQuote=gc,exports.resolveRoute=il,exports.scaleTokenAmount=Ot,exports.useAssetInput=Cc,exports.useLockDuration=bc,exports.useSmartWallet=wc,exports.useSpiceAssets=jn,exports.useSpiceExecution=mn,exports.useSpicePendingDeposits=dr,exports.useSupplyAssets=Pr,exports.useSupplyQuote=Zr;
|
|
85
|
+
`})]}),document.body):null;return o.jsxs(o.Fragment,{children:[ae,nt,I&&Cn.createPortal(o.jsx(Po,{isOpen:!0,onClose:L,supportedChains:[I.chainId],escrowOnly:!0,escrowTokenAddress:I.tokenAddress,escrowAmount:I.amount,escrowTokenDecimals:I.tokenDecimals,escrowTokenSymbol:I.tokenSymbol,styles:u,onDepositSuccess:ee}),document.body)]})},$l="0xa9059cbb";function fr(e,t,n){return B.isNativeToken(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"transfer",args:[n,t]})}}function hr(e,t,n){return{chainId:n,calls:[fr(e,t,B.getEscrowContractAddress(n))]}}function mr(e,t,n){return!t&&e?.asset?._source==="wallet"&&e?.asset.chainId===n}function gr(e,t,n,s){return t!=="user-transfer"||!n||e.length===0||e[0]?.to.toLowerCase()!==s.toLowerCase()||!e[0]?.data.startsWith($l)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function Jn(e,t,n,s){if(!t)return[e];const r=await t({...n,requestTimestampMs:s});return r?[r,e]:[e]}function Hs(e){return e.filter(t=>t.domain!=="spicenet")}function $n(e){const t=(e.tokenTransfers??[]).filter(n=>n.from==="escrow").map(n=>({token:B.normalizeNativeTokenAddress(n.token),recipient:n.to,amount:BigInt(n.amount)})).filter(n=>n.amount>0n);return t.length>0?t:void 0}function Ot(e,t,n){return Vo(e,t,n,"ceil")}async function xr(e,t){const{currentPaymentAmount:n,destinationToken:s,embeddedWalletAddress:r,providerEmbeddedAddress:a,address:i,isNon7702:d,isPayMode:u,resolvedChainId:c,buildActionCalls:f,feeExecutionMode:h,buildSpicenetBatch:g,selectedAsset:x,needsSwap:m,exactOutputSwap:y,resolvedTokenIn:C,requestTimestampMs:k}=e,b=D.parseUnits(n,s.decimals),R=t?.actionAmountOverride??b,v=r||a||(d?void 0:i);if(!v)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const w={userAddress:v,chainId:c,destinationToken:s.address,grossAmount:t?.fundingAmountOverride??b,netAmount:R,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:h,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},T=f(R,w),I={chainId:c,calls:T},F=!u&&!d?!0:x?.asset?._source==="spice",j=mr(x??null,d,c),A=F||d||j,E=(M,U)=>({token:M,from:"escrow",to:v,amount:U}),S=(M,U,W)=>j?[hr(M,U,c),...W]:W;if(b===0n)return[I];if(m&&y){const M=C??zt(x.asset,c)??x.asset.address,U=t?.fundingAmountOverride??y.amountInMax,W=A?[E(M,U)]:[],O={to:M,value:0n,data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"approve",args:[y.calls[0]?.to,y.amountInMax]})},z={chainId:c,calls:[O,...y.calls,...T],tokenTransfers:[...W,...I.tokenTransfers??[]]};if(!A)return[z];const N=await Jn(z,g,{userAddress:v,destinationChainId:c,deliveryToken:M,deliveryAmount:U,deliveryRecipient:v,deliveryTransfers:$n(z),sourceAsset:x.asset},k);return S(M,U,N)}if(A){const M=C??zt(x.asset,c)??s.address;if(j&&M.toLowerCase()===s.address.toLowerCase())return[I];const U=t?.fundingAmountOverride??b,W={...I,tokenTransfers:[E(M,U),...I.tokenTransfers??[]]},O=await Jn(W,g,{userAddress:v,destinationChainId:c,deliveryToken:M,deliveryAmount:U,deliveryRecipient:v,deliveryTransfers:$n(W),sourceAsset:x.asset},k);return S(M,U,O)}return[I]}async function yr(e,t){const{selectedAsset:n,embeddedWalletAddress:s,externalWalletAddress:r,recipient:a,resolvedChainId:i,destinationToken:d,buildActionCalls:u,feeExecutionMode:c,buildSpicenetBatch:f,isPayMode:h,isNon7702:g,needsSwap:x,resolvedSwap:m,quoteAmountOut:y,resolvedTokenIn:C,requestTimestampMs:k}=e,b=m?.amountOutMinimum??y;if(!n?.asset||!s)return[];const R=a??(g?r:s);if(!R)return[];const v=t?.fundingAmountOverride??t?.actionAmountOverride??D.parseUnits(n.amount,n.asset.decimals),w=t?.fundingAmountOverride??v,T=t?.sourceFundingAmountOverride??v,I=t?.deliveryAmountOverride??w,F=t?.withdrawalAmountOverride??I,j=t?.actionAmountOverride??v,A={userAddress:R,chainId:i,destinationToken:d.address,feeToken:c==="user-transfer"&&x&&C?C:d.address,grossAmount:w,netAmount:j,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:c,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},E=u(j,A),S=n.asset?._source==="wallet";if(!h&&g&&S&&n.asset.chainId===i){if(x){if(!C)throw new Error("Swap input token could not be resolved");if(!m||b===null)throw new Error("Swap quote not available yet")}if(x&&m&&b){const V=u(t?.actionAmountOverride??b,{...A,netAmount:t?.actionAmountOverride??b}),{feeCall:X,remainingCalls:xe}=gr(V,c,x,A.feeToken);return[{chainId:i,calls:[...X?[X]:[],...m.calls,...xe]}]}return[{chainId:i,calls:E}]}if(!h&&!g&&S&&n.asset.chainId!==i)throw new Error("Cross-chain wallet supplies require external wallet mode");const M=!h&&!g?n.asset?._source!=="wallet":n.asset?._source==="spice",U=g&&S,W=mr(n,g,i);if(!(M||U||W))return[{chainId:i,calls:E}];const O=W?hr(C??B.normalizeNativeTokenAddress(n.asset.address),T,i):U&&n.asset.chainId!==i?{chainId:n.asset.chainId,calls:[fr(B.normalizeNativeTokenAddress(n.asset.address),T,B.getEscrowContractAddress(n.asset.chainId))]}:null,z=(V,X)=>({token:V,from:U?"solver":"escrow",to:s,amount:X}),N=(V,X)=>U?[{token:V,from:"escrow",to:B.SPICE_SOLVER_ADDRESS,amount:X}]:[];if(x){if(!C)throw new Error("Swap input token could not be resolved");if(!m||b===null)throw new Error("Swap quote not available yet")}if(x&&m&&b&&C){const V=u(t?.actionAmountOverride??b,{...A,netAmount:t?.actionAmountOverride??b}),{feeCall:X,remainingCalls:xe}=gr(V,c,x,A.feeToken),H={chainId:i,calls:[...X?[X]:[],...m.calls,...xe],tokenTransfers:[...N(C,F),z(C,I)]},J=await Jn(H,f,{userAddress:s,destinationChainId:i,deliveryToken:C,deliveryAmount:I,withdrawalAmount:F,deliveryRecipient:s,deliveryTransfers:$n(H),sourceAsset:n.asset},k);return O?[O,...J]:J}const P=C??zt(n.asset,i)??d.address,Q={chainId:i,calls:E,tokenTransfers:[...N(P,F),z(P,I)]},K=await Jn(Q,f,{userAddress:s,destinationChainId:i,deliveryToken:P,deliveryAmount:I,withdrawalAmount:F,deliveryRecipient:s,deliveryTransfers:$n(Q),sourceAsset:n.asset},k);return O?[O,...K]:K}async function Cr(e,t,n,s,r){let a=e;for(let i=0;i<4;i++){const d=await t(a),u=await s(d,n,a,r),c=ri(u);if(c===null||c>=e)return a;const f=a-c,h=e+f;if(h<=a)return a;a=h}return a}function _l(e,t,n,s){if(e<=0n)return 0n;const r=e-t;if(r<=0n)return 0n;const a=s+n;return a<=0n?r:r*s/a}async function br(e){const{asset:t,isPayMode:n,isNon7702:s,needsSwap:r,isQuoting:a,embeddedWalletAddress:i,buildSupplyChainBatches:d,estimate:u,executionTokenAddress:c,feeExecutionMode:f}=e;if(n||s||r||a||!i||t.balance<=0n)return null;const h=i,g=await d({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(g.length===0)return null;const x=g.some(R=>R.tokenTransfers?.length),m=await u(g,c,t.balance,x?{userOverride:h,useCustomTransfers:!0,feeExecutionMode:f}:f?{userOverride:h,feeExecutionMode:f}:{userOverride:h}),y=Zt(m,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),C=y?Ot(y.gasFee,y.decimals,t.decimals):0n,k=y?Ot(y.spicenetFee,y.decimals,t.decimals):0n,b=_l(t.balance,C,k,t.balance);return b>0n?So(b,t.decimals):null}async function wr(e){const{selectedAsset:t,isPayMode:n,parsedAmount:s,needsSwap:r,exactOutputSwap:a,isNon7702:i,isSourceDestToken:d,currentPaymentAmount:u,destinationToken:c,feeExecutionMode:f,resolvedTokenIn:h,embeddedWalletAddress:g,providerEmbeddedAddress:x,resolvedChainId:m,isConnected:y,address:C,ready:k,authenticated:b,isDirect:R,resolvedSwap:v,isQuoting:w,executionTokenAddress:T,buildPayChainBatches:I,buildSupplyChainBatches:F,estimate:j,estimateRequiredGrossFunding:A}=e;if(!t?.asset)return null;if(n){if(s<=0||r&&!a||d)return null;const N=D.parseUnits(u,c.decimals),P=h||zt(t.asset,m)||t.asset.address||c.address,Q={chainId:m,tokenAddress:P,symbol:B.getTokenByAddress(P,m)?.symbol??t.asset.symbol,decimals:B.getTokenByAddress(P,m)?.decimals??t.asset.decimals};if(i){const J=g||x;if(!J)return null;const se=r?a?.amountInMax??0n:N;if(se===0n)return null;const ce={userOverride:J,useCustomTransfers:!0},de=await A(se,pe=>I({fundingAmountOverride:pe}),P,ce),ve=await I({fundingAmountOverride:de}),ue=await j(ve,P,de,{...ce,feeExecutionMode:f});return Zt(ue,Q)}if(!y||!C||!k||!b)return null;const K=g||x||C,V=r?a?.amountInMax??0n:N;if(V===0n)return null;const X=await A(V,J=>I({fundingAmountOverride:J}).then(se=>_t(Hs(se),K)),P,{useCustomTransfers:!0});let xe=_t(Hs(await I({fundingAmountOverride:X})),K);const H=await j(xe,P,X,{useCustomTransfers:!0,feeExecutionMode:f});return Zt(H,Q)}if(s<=0||!g)return null;const E=g||x;if(!(!n&&!i&&t.asset?._source==="wallet"&&t.asset.chainId!==m)&&!R&&!v&&!w||w)return null;const S=D.parseUnits(t.amount,t.asset.decimals),M=await F();if(M.length===0)return null;const U=i&&t.asset?._source==="wallet"&&t.asset.chainId===m,W={chainId:m,tokenAddress:T,symbol:B.getTokenByAddress(T,m)?.symbol??c.symbol,decimals:B.getTokenByAddress(T,m)?.decimals??c.decimals};if(U){const N=await p.relayerService.estimateBatchGas({user:E,outputToken:T,stepIndex:0,chainBatches:M}),P=Qn(S,10n),Q=P+N.gasFee;return{...W,grossAmount:S+Q,netAmount:S,totalFee:Q,gasFee:N.gasFee,spicenetFee:P,bridgeFee:0n,gasQuoteSource:N.gasQuoteSource}}const O=M.some(N=>N.tokenTransfers?.length),z=await j(M,T,S,O?{userOverride:E,useCustomTransfers:!0,feeExecutionMode:f}:f?{userOverride:E,feeExecutionMode:f}:{userOverride:E});return Zt(z,W)}const ec=10n;function kr(e,t){const n=e.selectedAsset?.asset;if(!n||n?._source!=="wallet")return;const s=zt(n,e.resolvedChainId);if(!s||!p.addressesEqual(s,e.executionTokenAddress))return;const r=B.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),a=Ot(t,r?.decimals??e.destinationToken.decimals,n.decimals);if(a<=n.balance)return;const i=D.formatUnits(a,n.decimals),d=D.formatUnits(n.balance,n.decimals);throw new Error(`Insufficient ${n.symbol} for amount plus fees. Required ${i} ${n.symbol}; available ${d} ${n.symbol}.`)}function Qs(e){const t=B.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:t?.symbol??e.destinationToken.symbol,decimals:t?.decimals??e.destinationToken.decimals}}function Bn(e,t,n){const s=Zt(e,Qs(t));if(!s)return;const r=Qn(n,ec),a=s.bridgeFee??0n,i=r+s.gasFee+a;return{grossAmount:n+i,netAmount:n,combinedFeeAmount:i,feeExecutionMode:"user-transfer",feeBreakdown:{spicenetFee:r,gasFee:s.gasFee,bridgeFee:a}}}function tc(e,t,n){let s=0n,r=0n;const a=n.toLowerCase();for(const i of e)if(i.chainId===t){for(const d of i.calls??[])if(d.to.toLowerCase()===a)try{const u=D.decodeFunctionData({abi:D.erc20Abi,data:d.data});if(u.functionName!=="transfer")continue;const c=u.args[0].toLowerCase(),f=u.args[1];c===B.SPICE_PLATFORM_FEE_RECIPIENT.toLowerCase()?s+=f:c===B.SPICE_GAS_FEE_RECIPIENT.toLowerCase()&&(r+=f)}catch{continue}}return{spicenetFee:s,gasFee:r}}function Vs(e,t,n){const s=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,r=tc(e,t.resolvedChainId,s);return r.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||r.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:Jt(r.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&Jt(r.gasFee,n.feeBreakdown.gasFee,100n)}function vr(e,t){return e?Jt(e.grossAmount,t.grossAmount,100n)&&Jt(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&Jt(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&Jt(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}function _n(e,t,n,s){const r=Hs(e),a=u=>(u.tokenTransfers??[]).some(c=>c.from==="escrow"),i=r.filter(u=>!a(u)),d=r.filter(a);return[...i,..._t(d,t,n,s)]}function Sr(e,t){const n=e.selectedIsEquivalent?t:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(n===0n)throw new Error("Quote not available yet");return n}function Ar(e,t,n){const s=t instanceof Error?t:new Error(String(t));if(s.name==="AbortError"||n){e.ui.setStep("idle");return}const r=s.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(r),e.ui.setError(r)}function Ir(e,t){const n=p.sanitizeError(t,"Payment failed. Please try again.");e.ui.setError(n),e.ui.setPaymentResult({status:"failed",error:n})}async function Er(e){if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.isNon7702){const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setTxHash(null);try{if(e.isSourceDestToken){e.ui.setStep("executing"),e.ui.setStatusMsg("Submitting transaction...");const s=await jr(e);e.ui.setTxHash(s??null)}else{e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.refs.spiceDepositSubmittedRef.current=!1;const s=new AbortController;e.refs.abortControllerRef.current=s,await nc(e,s.signal)}e.ui.setStep("success"),e.ui.setStatusMsg(e.isSourceDestToken?"Transaction confirmed":"Deposit confirmed")}catch(s){Ar(e,s,!!e.refs.abortControllerRef.current?.signal.aborted)}finally{e.ui.setIsExecuting(!1)}return}if(!e.embeddedWalletAddress){e.ui.setError("Wallet not ready");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.ui.setTxHash(null),e.refs.spiceDepositSubmittedRef.current=!1;const t=new AbortController;e.refs.abortControllerRef.current=t;try{const n=D.parseUnits(e.selectedAsset.amount,e.selectedAsset.asset.decimals),s=n;let r=await e.execution.buildSupplyChainBatches();const a=e.selectedAsset.asset?._source==="wallet",i=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!a&&!r.some(x=>B.isSpicenetChainId(x.chainId)))throw new Error("Spice-funded supplies must include a Spicenet funding batch before the destination chain batch.");const d=r.some(x=>x.tokenTransfers?.length)?{userOverride:i,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}:e.feeExecutionMode?{userOverride:i,feeExecutionMode:e.feeExecutionMode}:{userOverride:i};let u=n;const c=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,f=e.feeExecutionMode==="user-transfer"&&!c?s:void 0;let h;for(let x=0;x<4;x+=1){const m=await e.execution.estimate(r,e.executionTokenAddress,u,d),y=Zt(m,Qs(e));h=e.feeExecutionMode==="user-transfer"&&y?Bn(m,e,s):void 0;const C=h?.grossAmount??y?.grossAmount??u;if(C===u){u=C;break}u=C,r=await e.execution.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:f,actionContextOverride:h})}e.feeExecutionMode==="user-transfer"&&(kr(e,u),r=await e.execution.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:f,actionContextOverride:h}));let g=h;await e.execution.execute(r,e.executionTokenAddress,u,e.execution.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...d,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:x,chainBatches:m})=>{const y=Bn(x,e,s);if(!y)return null;const C=vr(g,y),k=Vs(m,e,y);return C||k?null:(g=y,e.execution.buildSupplyChainBatches({fundingAmountOverride:y.grossAmount,actionAmountOverride:f,actionContextOverride:y}))}}:d),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){Ar(e,n,t.signal.aborted)}finally{e.ui.setIsExecuting(!1)}}async function nc(e,t){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const n=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!n)throw new Error("Embedded wallet not available \u2014 sign in to create one before supplying");const s=e.selectedAsset.asset,r=D.parseUnits(e.selectedAsset.amount,s.decimals),a=r,i=s?._source==="wallet"&&s.chainId===e.resolvedChainId;let d=await e.execution.buildSupplyChainBatches();const u={userOverride:n,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,signAuthorizationsForEstimate:!0};let c=r;const f=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,h=e.feeExecutionMode==="user-transfer"&&!f?a:void 0;let g;if(i){const j=await p.relayerService.estimateBatchGas({user:n,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:d}),A=Qn(r,10n),E=A+j.gasFee;c=r+E,e.feeExecutionMode==="user-transfer"&&(g={grossAmount:c,netAmount:a,combinedFeeAmount:E,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:A,gasFee:j.gasFee,bridgeFee:0n}})}else for(let j=0;j<4;j+=1){const A=await e.execution.estimate(d,e.executionTokenAddress,0n,u),E=e.feeExecutionMode==="user-transfer"?Bn(A,e,a):void 0,S=Zt(A,Qs(e)),M=E?.grossAmount??(S?S.grossAmount>r?S.grossAmount:r:c);if(g=E,M===c){c=M;break}c=M;const U=B.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),W=Ot(c,U?.decimals??e.destinationToken.decimals,s.decimals);d=await e.execution.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:W,withdrawalAmountOverride:c,actionAmountOverride:h,actionContextOverride:E})}const x=B.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);let m=i?c:Ot(c,x?.decimals??e.destinationToken.decimals,s.decimals);kr(e,c),d=await e.execution.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:m,withdrawalAmountOverride:c,actionAmountOverride:h,actionContextOverride:g});const y=s.chainId,C=n,{extWc:k,viemChain:b}=await xn({wallet:e.externalWallet,account:e.externalWalletAddress,chainId:y,onSwitch:()=>e.ui.setStatusMsg("Switching source network...")}),R=B.normalizeNativeTokenAddress(s.address),v=s.isNative||B.isNativeToken(R),w=p.getClientForChain(y),T=j=>js({extWc:k,sourceClient:w,recipient:C,tokenAddr:R,isNative:v,amount:j,viemChain:b});e.ui.setStatusMsg("Funding embedded wallet..."),await T(m);let I=m;if(e.feeExecutionMode==="user-transfer")for(let j=0;j<4;j+=1){const A=await e.execution.estimate(d,e.executionTokenAddress,0n,u),E=Bn(A,e,a);if(!E)break;const S=i?E.grossAmount:Ot(E.grossAmount,x?.decimals??e.destinationToken.decimals,s.decimals);if(S>I&&(e.ui.setStatusMsg("Topping up embedded wallet..."),await T(S-I),I=S),g=E,c=E.grossAmount,m=S,d=await e.execution.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:m,withdrawalAmountOverride:c,actionAmountOverride:h,actionContextOverride:E}),Vs(d,e,E))break}e.ui.setStatusMsg("Signing supply intent...");let F=g;await e.execution.execute(d,e.executionTokenAddress,0n,e.execution.onProgress,t,e.feeExecutionMode==="user-transfer"?{...u,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:j,chainBatches:A})=>{const E=Bn(j,e,a);if(!E)return null;const S=vr(F,E),M=Vs(A,e,E);if(S||M)return null;if(E.grossAmount>c)throw new Error("Fee estimate increased after wallet funding. Please retry so the signed fee can match the latest relayer estimate.");F=E;const U=i?E.grossAmount:Ot(E.grossAmount,x?.decimals??e.destinationToken.decimals,s.decimals);return e.execution.buildSupplyChainBatches({fundingAmountOverride:E.grossAmount,sourceFundingAmountOverride:U,withdrawalAmountOverride:E.grossAmount,actionAmountOverride:h,actionContextOverride:E})}}:u)}async function jr(e){const t=e.isPayMode&&e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t)throw new Error("Select a payment source");const n=e.activeSignerWallet??e.externalWallet,s=e.activeSignerAddress??e.externalWalletAddress;if(!s||!n)throw new Error("Please connect your wallet to continue");const r=D.parseUnits(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),a={userAddress:s,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},i=e.buildActionCalls(r,a);if(i.length===0)throw new Error("No action calls configured");const{extWc:d,viemChain:u}=await xn({wallet:n,account:s,chainId:e.resolvedChainId}),c=p.getClientForChain(e.resolvedChainId);return Ro({extWc:d,client:c,calls:i,viemChain:u,errorMessage:"Transaction failed"})}async function sc(e){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const n=e.selectedAsset.asset,s=n.chainId,r=D.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),a=Sr(e,r),i=e.resolvedTokenIn||e.selectedAsset.asset.address,d={userOverride:t,useCustomTransfers:!0},u=B.getEscrowContractAddress(s),c=B.normalizeNativeTokenAddress(n.address),f=n.isNative||B.isNativeToken(c),h=t,g=F=>({chainId:s,calls:f?[{to:u,value:F,data:"0x"}]:[{to:c,value:0n,data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"transfer",args:[u,F]})}]}),x=async(F,j,A)=>[g(F),..._n(await e.execution.buildPayChainBatches({fundingAmountOverride:F}),h,j,A)],m=await e.execution.estimateRequiredGrossFunding(a,F=>x(F),i,d);let y=m,C=await x(m);const k=await e.execution.estimate(C,i,m,{...d,feeExecutionMode:e.feeExecutionMode}),b=Zt(k,{chainId:e.resolvedChainId,tokenAddress:i,symbol:B.getTokenByAddress(i,e.resolvedChainId)?.symbol??n.symbol,decimals:B.getTokenByAddress(i,e.resolvedChainId)?.decimals??n.decimals})?.grossAmount??m;b!==m&&(y=b),C=await x(y,k,{payoutAlreadyGross:!0});const{extWc:R,viemChain:v}=await xn({wallet:e.externalWallet,account:e.externalWalletAddress,chainId:s}),w=p.getClientForChain(s);await js({extWc:R,sourceClient:w,recipient:t,tokenAddr:c,isNative:f,amount:y,viemChain:v});const T=C.some(F=>F.tokenTransfers?.length),I={...d,skipUserFundingPreflight:!0};return await e.execution.execute(C,i,T?y:0n,F=>{F.txHash&&(e.ui.setPaymentResult(j=>({...j??{status:"processing"},txHash:F.txHash})),e.ui.setTxHash(F.txHash))},void 0,T?I:{userOverride:t,skipUserFundingPreflight:!0})}async function Fr(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}const t=e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t){e.ui.setError("Select a payment source");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.parsedAmount>0&&e.needsSwap&&!e.exactOutputSwap){e.ui.setError("Swap quote not available. Try a different asset.");return}if(e.isNon7702){const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken||t?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{let s;if(e.isSourceDestToken||e.parsedAmount===0)s=await jr(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const r=e.selectedAsset.asset,a=D.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),i=Sr(e,a),d=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!d)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const u=e.resolvedTokenIn||r.address,c=await e.execution.estimateRequiredGrossFunding(i,g=>e.execution.buildPayChainBatches({fundingAmountOverride:g}),u,{userOverride:d,useCustomTransfers:!0}),f=await e.execution.buildPayChainBatches({fundingAmountOverride:c}),h=await e.onPayExecute({asset:r,amount:e.currentPaymentAmount,amountWei:a,destinationToken:e.destinationToken,chainBatches:f,requiredNetFunding:i,grossFundingAmount:c,selectedIsEquivalent:e.selectedIsEquivalent,resolvedTokenIn:u,exactOutputSwapAmountInMax:e.exactOutputSwap?.amountInMax});h&&(e.ui.setTxHash(h),e.ui.setPaymentResult(g=>({...g??{status:"processing"},txHash:h}))),s=h||void 0}else s=await sc(e);e.ui.setPaymentResult(r=>({status:"success",txHash:r?.txHash||s||""}))}catch(s){Ir(e,s)}finally{e.ui.setIsExecuting(!1)}return}if(!e.isConnected||!e.address){e.ui.setError("Please connect your wallet to continue");return}if(!e.ready||!e.authenticated){e.ui.setError(`Please authenticate with ${e.provider||"wallet provider"} to continue`);return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{const n=D.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),s={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode};if(t){const y=await e.execution.buildPayChainBatches(),C=await e.execution.execute(y,e.executionTokenAddress,0n,k=>{k.txHash&&(e.ui.setPaymentResult(b=>({...b??{status:"processing"},txHash:k.txHash})),e.ui.setTxHash(k.txHash))},void 0,s);e.ui.setPaymentResult(k=>({status:"success",txHash:k?.txHash||C}));return}const r=e.selectedAsset?.asset;if(!r)throw new Error("Select a payment source");const a=e.resolvedTokenIn||r.address||e.destinationToken.address,i=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:n,d=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,u=await e.execution.estimateRequiredGrossFunding(i,y=>e.execution.buildPayChainBatches({fundingAmountOverride:y}).then(C=>_n(C,d)),a,s);let c=u,f=_n(await e.execution.buildPayChainBatches({fundingAmountOverride:u}),d);const h=await e.execution.estimate(f,a,u,s),g=Zt(h,{chainId:e.resolvedChainId,tokenAddress:a,symbol:B.getTokenByAddress(a,e.resolvedChainId)?.symbol??r.symbol,decimals:B.getTokenByAddress(a,e.resolvedChainId)?.decimals??r.decimals})?.grossAmount??u;g!==u&&(c=g),f=_n(await e.execution.buildPayChainBatches({fundingAmountOverride:c}),d,h,{payoutAlreadyGross:!0});const x=f.some(y=>y.tokenTransfers?.length),m=await e.execution.execute(f,a,x?c:0n,y=>{y.txHash&&(e.ui.setPaymentResult(C=>({...C,txHash:y.txHash})),e.ui.setTxHash(y.txHash))},void 0,s);e.ui.setPaymentResult(y=>({status:"success",txHash:y?.txHash||m}))}catch(n){Ir(e,n)}finally{e.ui.setIsExecuting(!1)}}const oc=({variant:e,destinationSymbol:t,destinationLogoURI:n,destinationDecimals:s,primaryColor:r,fontFamily:a,textPrimary:i,textSecondary:d,cardBg:u,cardBorder:c,dk:f,dark:h,isQuoting:g,quoteError:x,estimatedOutput:m,paymentAmount:y,needsSwap:C,exactOutputSwap:k,adjustable:b=!1,maxAmount:R,onAmountChange:v})=>e==="supply"?o.jsxs("div",{style:{backgroundColor:u,border:`1px solid ${c}`,borderRadius:h?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",minHeight:"112px",display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"12px"},children:[o.jsxs("div",{style:{minWidth:0},children:[o.jsx("span",{style:{fontFamily:a,fontSize:"17px",fontWeight:500,color:h?"#a7abb2":"#7D7C7B",lineHeight:"24px"},children:"Used in TX"}),o.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:d,fontFamily:a,marginTop:"10px"},children:"Net amount after swap and fees"})]}),o.jsxs("div",{style:{textAlign:"right",minWidth:0,display:"inline-flex",alignItems:"center",gap:"8px",border:`1px solid ${c}`,borderRadius:"8px",padding:"8px 10px",minHeight:"42px"},children:[o.jsx(Tr,{symbol:t,logoURI:n,primaryColor:r,size:24}),o.jsx("span",{style:{fontSize:"16px",fontWeight:500,color:h?"#f3f4f6":"#3C3E42",lineHeight:"1.3",fontFamily:a,letterSpacing:0},children:t})]})]}),o.jsx("div",{style:{textAlign:"right",minWidth:0},children:g?o.jsx("span",{style:{fontSize:"18px",color:d,fontFamily:a},children:"Quoting..."}):x?o.jsx("span",{style:{fontSize:"13px",color:h?"#f87171":"#dc2626",fontFamily:a},children:"Quote failed"}):m?o.jsx(rn,{value:m,title:m,fontFamily:a,color:i,lineHeight:"0.95",textAlign:"right",maxFontSize:32,minFontSize:18}):o.jsx("span",{style:{fontSize:"20px",color:d,fontFamily:a},children:"\u2014"})})]}):o.jsx(rc,{destinationSymbol:t,destinationLogoURI:n,destinationDecimals:s,primaryColor:r,fontFamily:a,textPrimary:i,textSecondary:d,cardBg:u,cardBorder:c,dk:f,dark:h,paymentAmount:y||"0",needsSwap:C,exactOutputSwap:k,isQuoting:g,adjustable:b,maxAmount:R,onAmountChange:v}),Br=l.memo(oc),Tr=({symbol:e,logoURI:t,primaryColor:n,size:s})=>t?o.jsx("img",{src:t,alt:e,style:{width:s,height:s,borderRadius:"50%",objectFit:"cover"}}):o.jsx("div",{style:{width:s,height:s,borderRadius:"50%",backgroundColor:`${n}22`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:s<30?"11px":"12px",fontWeight:700,color:n},children:e.slice(0,2)}),rc=({destinationSymbol:e,destinationLogoURI:t,destinationDecimals:n,primaryColor:s,fontFamily:r,textPrimary:a,textSecondary:i,cardBg:d,cardBorder:u,dk:c,dark:f,paymentAmount:h,needsSwap:g,exactOutputSwap:x,isQuoting:m,adjustable:y,maxAmount:C,onAmountChange:k})=>{const b=p.font.mono,R=parseFloat(h||"0"),v=C?parseFloat(C):0,[w,T]=l.useState(h||""),I=l.useRef(null),[F,j]=l.useState(null),[A,E]=l.useState(null);l.useEffect(()=>{y||T(h||"")},[h,y]);const S=W=>{let O=W;O.startsWith(".")&&(O="0"+O);const z=p.parseNumericInput(O);let N=z;C&&parseFloat(z)>parseFloat(C)&&(N=C),T(N),I.current&&clearTimeout(I.current),I.current=setTimeout(()=>k?.(N),300)},M=W=>{if(!v)return;if(W===100){T(C||v.toString()),I.current&&clearTimeout(I.current),k?.(C||v.toString());return}const O=10**n,z=Math.floor(v*W/100*O)/O,N=p.formatDecimalInput(z,n);T(N),I.current&&clearTimeout(I.current),k?.(N)},U=v>0?parseFloat(w||"0")/v*100:0;return l.useEffect(()=>()=>{I.current&&clearTimeout(I.current)},[]),o.jsxs("div",{style:{backgroundColor:d,border:`1px solid ${u}`,borderRadius:f?"12px":"6px",padding:"16px",marginBottom:"16px"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[o.jsx(Tr,{symbol:e,logoURI:t,primaryColor:s,size:32}),o.jsxs("div",{children:[o.jsx("span",{style:{fontSize:"14px",fontWeight:600,color:a,fontFamily:r},children:"Payment"}),o.jsx("div",{style:{fontSize:"12px",color:i,fontFamily:r,marginTop:"2px"},children:e})]})]}),o.jsxs("div",{style:{textAlign:"right"},children:[y?o.jsx(rn,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:w,onChange:W=>S(W.target.value),placeholder:"0.0",fontFamily:b,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):o.jsx(rn,{element:"div",value:R>0?h:"0.00",title:R>0?h:"0.00",fontFamily:b,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),o.jsx("div",{style:{fontSize:"12px",color:i,fontFamily:b,marginTop:"2px"},children:e}),y&&v>0&&o.jsx("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((W,O)=>{const z=Math.abs(U-W)<1,N=O===4,P=F===W,Q=A===W;return o.jsx("button",{onClick:()=>M(W),onMouseEnter:()=>j(W),onMouseLeave:()=>{j(null),E(null)},onMouseDown:()=>E(W),onMouseUp:()=>E(null),title:`${W}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:z?1:P?.8:.5,transform:Q?"scale(0.85)":P?"scale(1.15)":"scale(1)",transition:p.transition.interactive},children:o.jsx(cs,{pct:W,isMax:N,primaryColor:s,dark:f,fillColor:f?c?.textSecondary||"#9ca3af":"#3C3E42"})},W)})})]})]}),g&&x&&!m&&o.jsx("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:f?`1px solid ${c?.cardBorder||u}`:"1px solid #e5e7eb",display:"flex",justifyContent:"flex-end"},children:o.jsxs("span",{style:{fontSize:"11px",color:i,fontFamily:r,opacity:.7},children:["via ",x.venue]})})]})},Rr={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},Dr=["signing-delegation","signing-intent","submitting","executing"],ac=({step:e,statusMsg:t,txHash:n,explorerUrl:s,currentStepIdx:r,palette:a,cardBg:i,cardBorder:d,textPrimary:u,textSecondary:c,fontFamily:f,primaryColor:h,onRetry:g})=>o.jsxs("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:e==="success"?i:e==="error"?a.errorBg:i,border:`1px solid ${e==="success"?d:e==="error"?a.errorBorder:d}`},children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[e==="success"?o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:o.jsx("path",{d:"M5 13l4 4L19 7",stroke:a.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):e==="error"?o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:o.jsx("path",{d:"M18 6L6 18M6 6l12 12",stroke:a.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):o.jsx(p.Spinner,{size:14,color:h}),o.jsx("span",{style:{fontSize:"13px",fontWeight:500,color:e==="success"?u:e==="error"?a.errorText:u,fontFamily:f,flex:1},children:e==="success"?"Deposit confirmed":e==="error"?t||"Transaction failed":Rr[e]||t}),e==="success"&&n&&o.jsx("a",{href:`${s}/tx/${n}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:h,fontFamily:f,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),e==="error"&&o.jsx("button",{onClick:g,style:{background:"none",border:"none",fontSize:"12px",color:h,fontFamily:f,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),r>=0&&e!=="success"&&e!=="error"&&o.jsx("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${c}22`,overflow:"hidden"},children:o.jsx("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:h,transformOrigin:"left center",transform:`scaleX(${(r+1)/Dr.length})`,transition:"transform 400ms ease"}})})]});function Mr(e,t,n){const s=p.addressesEqual(e.address,t),r=e.chainId===n,a=e._source==="wallet";return a&&s&&r?0:a&&r?1:!a&&s?2:!a&&r?3:4}function Wr(e,t){return!t||t.length===0||t.some(n=>p.addressesEqual(n,e.address))?!0:Object.keys(e.chainTokens??{}).some(n=>{const s=hn(n);return s?t.some(r=>p.addressesEqual(r,s.address)):!1})}function Nr(e,t,n){let{symbol:s,name:r,logoURI:a}=t;const i=p.addressesEqual(e.address,n.address)&&e.chainId===n.chainId;i&&n.logoURI&&(a=n.logoURI),i&&!e.configToken&&s==="TOKEN"&&(s=n.symbol,r=n.symbol);const d=parseFloat((Number(t.balance)/Math.pow(10,t.decimals)).toFixed(6));return{address:e.address,name:r,symbol:s,decimals:t.decimals,balance:t.balance,balanceFormatted:d,balanceUsd:0,logoURI:a,isNative:!1,chainId:e.chainId}}function Pr(e){const{destinationToken:t,supportedSourceAssets:n,sourceChains:s,enabled:r}=e,a=l.useContext(p.SpiceFlowProviderContext),i=(a?.mode||"7702")!=="7702",d=a?.embeddedWalletAddress,{externalAddress:u,embeddedAddress:c,activeAddress:f}=p.useProviderWallets(),h=d||c,{assets:g,refetch:x}=jn({address:h,supportedChains:s,enabled:r&&!i&&!!h,refetchInterval:3e4}),m=l.useMemo(()=>i?[]:g.filter(j=>Wr(j,n)),[g,n,i]),y=i?f??u:d,C=l.useMemo(()=>{const j=new Set,A=[],E=S=>{if(!S)return;const M=S.toLowerCase();j.has(M)||(j.add(M),A.push(D.getAddress(S)))};if(E(t.address),n)for(const S of n)E(S);return A},[i,t.address,n]),k=l.useMemo(()=>C.map(j=>j.toLowerCase()).sort().join(","),[C]),b=l.useMemo(()=>JSON.stringify([...s||[]].sort()),[s]),[R,v]=l.useState([]),w=l.useRef(0),T=l.useRef(async()=>{}),I=l.useCallback(async()=>{if(!r||!y||C.length===0){w.current++,v([]);return}const j=++w.current,A=D.getAddress(y),E=i?s&&s.length>0?s:[t.chainId]:[t.chainId],S=[];for(const O of C){const z=O.toLowerCase();if(z===B.ZERO_ADDRESS)continue;if(z===t.address.toLowerCase()){const P=p.getChainConfig(t.chainId)?.supportedTokens?.find(Q=>p.addressesEqual(Q.address,z));S.push({address:O,chainId:t.chainId,configToken:P?{decimals:P.decimals,symbol:P.symbol,name:P.name,logo:P.logo}:void 0});continue}let N=!1;for(const P of E){const Q=p.getChainConfig(P)?.supportedTokens?.find(K=>p.addressesEqual(K.address,z));if(Q){S.push({address:O,chainId:P,configToken:{decimals:Q.decimals,symbol:Q.symbol,name:Q.name,logo:Q.logo}}),N=!0;break}}N||S.push({address:O,chainId:t.chainId})}const M=new Map;for(const O of S){const z=M.get(O.chainId)||[];z.push(O),M.set(O.chainId,z)}const U=async(O,z)=>{try{const N=await Pt.readContract(O,{address:z.address,abi:D.erc20Abi,functionName:"balanceOf",args:[A]}),{decimals:P,symbol:Q,name:K,logoURI:V}=await or(O,z.address,z.configToken);return Nr(z,{decimals:P,symbol:Q,name:K,logoURI:V,balance:N},t)}catch{return null}},W=await Promise.all(Array.from(M.entries()).map(async([O,z])=>{let N;try{N=p.getClientForChain(O)}catch{return[]}const P=[],Q=[];for(const V of z){const X=P.length;P.push({address:V.address,abi:D.erc20Abi,functionName:"balanceOf",args:[A]}),V.configToken||P.push({address:V.address,abi:D.erc20Abi,functionName:"decimals"},{address:V.address,abi:D.erc20Abi,functionName:"symbol"},{address:V.address,abi:D.erc20Abi,functionName:"name"}),Q.push({start:X,item:V})}let K=null;try{K=await N.multicall({contracts:P})}catch{K=null}return K?Q.map(({start:V,item:X})=>{const xe=K[V],H=xe?.status==="success"?xe.result:0n;let J,se,ce,de;if(X.configToken)J=X.configToken.decimals,se=X.configToken.symbol,ce=X.configToken.name,de=X.configToken.logo;else{const ve=K[V+1],ue=K[V+2],pe=K[V+3];J=ve?.status==="success"?Number(ve.result):18,se=ue?.status==="success"?ue.result:"TOKEN",ce=pe?.status==="success"?pe.result:se}return Nr(X,{decimals:J,symbol:se,name:ce,logoURI:de,balance:H},t)}):(await Promise.all(z.map(V=>U(N,V)))).filter(V=>V!==null)}));j===w.current&&v(W.flat())},[r,i,y,k,b,t.address,t.chainId,t.symbol,t.logoURI]);l.useEffect(()=>{T.current=I},[I]),l.useEffect(()=>{if(!r){v([]);return}T.current();const j=setInterval(()=>{T.current()},15e3);return()=>clearInterval(j)},[r,i,y,k,b,t.address,t.chainId]);const F=l.useCallback(()=>{I()},[I]);return{displayAssets:l.useMemo(()=>{const j=[],A=R.filter(S=>S.balance>0n);for(const S of A)j.push({...S,_source:"wallet"});for(const S of m)j.push({...S,_source:"spice"});const E=t.address.toLowerCase();return j.sort((S,M)=>Mr(S,E,t.chainId)-Mr(M,E,t.chainId)),j},[R,m,t.address,t.chainId]),filteredSpiceAssets:m,walletAssets:R,embeddedWalletAddress:h,externalAddress:u,isNon7702:i,refreshSpiceAssets:x,refreshWalletAssets:F}}async function ic(e){const{tokenIn:t,tokenOut:n,amountIn:s,fee:r,chainId:a,config:i}=e;if(s<=0n)throw new Error("amountIn must be greater than 0");const d=(await p.getClientForChain(a).simulateContract({address:i.quoterV2,abi:B.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:s,fee:r,sqrtPriceLimitX96:0n}]})).result;if(d[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:d[0],sqrtPriceX96After:d[1],gasEstimate:d[3]}}async function Ur(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(r=>ic({...e,fee:r})));let s=null;for(let r=0;r<n.length;r++){const a=n[r];a.status==="fulfilled"&&(!s||a.value.amountOut>s.amountOut)&&(s={...a.value,fee:t[r]})}if(!s)throw new Error("No liquidity found for this pair on any fee tier.");return s}const lc=[{inputs:[{components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"amount",type:"uint256"},{name:"fee",type:"uint24"},{name:"sqrtPriceLimitX96",type:"uint160"}],name:"params",type:"tuple"}],name:"quoteExactOutputSingle",outputs:[{name:"amountIn",type:"uint256"},{name:"sqrtPriceX96After",type:"uint160"},{name:"initializedTicksCrossed",type:"uint32"},{name:"gasEstimate",type:"uint256"}],stateMutability:"nonpayable",type:"function"}];async function cc(e){const{tokenIn:t,tokenOut:n,amountOut:s,fee:r,chainId:a,config:i}=e;if(s<=0n)throw new Error("amountOut must be greater than 0");const d=(await p.getClientForChain(a).simulateContract({address:i.quoterV2,abi:lc,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:s,fee:r,sqrtPriceLimitX96:0n}]})).result;if(d[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:d[0],sqrtPriceX96After:d[1],gasEstimate:d[3]}}async function dc(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(r=>cc({...e,fee:r})));let s=null;for(let r=0;r<n.length;r++){const a=n[r];a.status==="fulfilled"&&(!s||a.value.amountIn<s.amountIn)&&(s={...a.value,fee:t[r]})}if(!s)throw new Error("No liquidity found for this pair on any fee tier.");return s}function uc(e){return e.type==="swap"}const qs=.02,pc=[1,8453,42161,10,137,43114,56],fc="https://api.1inch.dev/swap/v6.0";function Lr(e,t){return B.applySlippage(e,t)}function hc(e){const t=e?.baseUrl??fc;return{name:"1inch",chainIds:e?.chainIds??pc,resolve:async(n,s,r)=>{const a=n.maxSlippage??qs,i=a*100,d=B.isNativeToken(n.tokenIn)?B.NATIVE_TOKEN_ADDRESS:n.tokenIn,u=B.isNativeToken(n.tokenOut)?B.NATIVE_TOKEN_ADDRESS:n.tokenOut,c=B.isNativeToken(n.tokenIn);try{const f=new URL(`${t}/${s}/swap`);f.searchParams.set("src",d),f.searchParams.set("dst",u),f.searchParams.set("amount",n.amountIn.toString()),f.searchParams.set("from",r),f.searchParams.set("slippage",i.toString()),f.searchParams.set("disableEstimate","true"),f.searchParams.set("allowPartialFill","false");const h={Accept:"application/json"};e?.apiKey&&(h.Authorization=`Bearer ${e.apiKey}`);const g=await fetch(f.toString(),{headers:h});if(!g.ok)throw new p.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${g.status} for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:`HTTP ${g.status}`});const x=await g.json();if(!x.dstAmount||!x.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const m=BigInt(x.dstAmount);if(m<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const y=Lr(m,a),C=[];return x.tx.to&&!c&&C.push({to:n.tokenIn,value:0n,data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"approve",args:[x.tx.to,n.amountIn]})}),C.push({to:x.tx.to,value:BigInt(x.tx.value||"0"),data:x.tx.data}),{venue:"1inch",amountOut:m,amountOutMinimum:y,calls:C}}catch(f){if(f instanceof p.SpiceflowError)throw f;const h=f instanceof Error?f.message:String(f);throw new p.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}: ${h}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:h})}}}}const zr=[4114,5115],Ys={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},Or={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[3e3]};function Hr(e){return{name:"satsuma",chainIds:e.chainIds??zr,resolve:async(t,n,s)=>{const r=t.maxSlippage??qs,a=B.isNativeToken(t.tokenIn);let i;try{i=await Ur({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountIn:t.amountIn,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return console.warn(`[SatsumaVenue] No viable fee tier for ${t.tokenIn} \u2192 ${t.tokenOut} on chain ${n}.`),null}const d=Lr(i.amountOut,r),u=[];return a||u.push({to:t.tokenIn,value:0n,data:D.encodeFunctionData({abi:D.erc20Abi,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),u.push({to:e.swapRouter,value:a?t.amountIn:0n,data:D.encodeFunctionData({abi:B.uniV3SwapRouterAbi,functionName:"exactInputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:i.fee,recipient:s,amountIn:t.amountIn,amountOutMinimum:d,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:i.amountOut,amountOutMinimum:d,calls:u}}}}function Qr(e){return{name:"satsuma",chainIds:e.chainIds??zr,resolve:async(t,n,s)=>{const r=t.maxSlippage??qs,a=B.isNativeToken(t.tokenIn);let i;try{i=await dc({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountOut:t.amountOut,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return null}const d=BigInt(Math.round(r*1e4)),u=i.amountIn+i.amountIn*d/10000n,c=[];return c.push({to:e.swapRouter,value:a?u:0n,data:D.encodeFunctionData({abi:mc,functionName:"exactOutputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:i.fee,recipient:s,amountOut:t.amountOut,amountInMaximum:u,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:i.amountIn,amountInMax:u,amountOut:t.amountOut,calls:c}}}}const mc=[{inputs:[{components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"fee",type:"uint24"},{name:"recipient",type:"address"},{name:"amountOut",type:"uint256"},{name:"amountInMaximum",type:"uint256"},{name:"sqrtPriceLimitX96",type:"uint160"}],name:"params",type:"tuple"}],name:"exactOutputSingle",outputs:[{name:"amountIn",type:"uint256"}],stateMutability:"payable",type:"function"}];function Vr(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(Hr(e.satsuma)),t.push(hc(e?.oneInch));function n(r){return t.find(a=>a.chainIds.includes(r))}async function s(r,a,i){const d=[],u=[];for(const c of r){if(!uc(c)){d.push(c);continue}const f=n(a);if(!f)throw new p.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${a}. Cannot resolve swap ${c.tokenIn} \u2192 ${c.tokenOut}.`,{chainId:a,tokenIn:c.tokenIn,tokenOut:c.tokenOut,amountIn:c.amountIn.toString()});const h=await f.resolve(c,a,i);if(!h)throw new p.SpiceflowError("NO_LIQUIDITY",`${f.name} returned no quote for ${c.tokenIn} \u2192 ${c.tokenOut} on chain ${a}.`,{venue:f.name,chainId:a,tokenIn:c.tokenIn,tokenOut:c.tokenOut,amountIn:c.amountIn.toString()});d.push(...h.calls),u.push(h)}return{calls:d,resolvedSwaps:u}}return{resolveSwapIntents:s,getVenueForChain:n,venues:t}}function qr(e){const t=e?.customVenues??[];async function n(s,r,a){const i=t.filter(c=>c.chainIds.includes(r));if(i.length===0)throw new p.SpiceflowError("NO_SWAP_ROUTE",`No exact-output venue supports chain ${r}`,{chainId:r,tokenIn:s.tokenIn,tokenOut:s.tokenOut});const d=(await Promise.allSettled(i.map(async c=>({venue:c,quote:await c.resolve(s,r,a)})))).filter(c=>c.status==="fulfilled").map(c=>c.value).filter(c=>c.quote!==null);if(d.length===0)throw new p.SpiceflowError("NO_SWAP_ROUTE",`All aggregators failed for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${r}`,{chainId:r,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountOut:s.amountOut.toString()});const u=d.find(c=>c.venue.preferred);return u?u.quote:(d.sort((c,f)=>c.quote.amountIn<f.quote.amountIn?-1:c.quote.amountIn>f.quote.amountIn?1:0),d[0].quote)}return{getQuote:n,venues:t}}const Yr=Vr({satsuma:Ys});async function gc(e){const t=Yr.getVenueForChain(e.chainId);if(!t)throw new Error(`No swap venue configured for chain ${e.chainId}.`);const n=await t.resolve({type:"swap",tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:e.amountIn},e.chainId,e.recipient);if(!n)throw new Error("No liquidity for this pair.");return n}function Zr(e){const{direction:t,selectedAsset:n,destinationToken:s,chainId:r,recipient:a,paymentAmount:i,resolveExactOutputSwap:d}=e,[u,c]=l.useState(!1),[f,h]=l.useState(null),[g,x]=l.useState(null),[m,y]=l.useState(null),[C,k]=l.useState(null),[b,R]=l.useState(null),[v,w]=l.useState(null),[T,I]=l.useState(null),[F,j]=l.useState(null),A=l.useRef(null),E=l.useRef(null),S=l.useRef(0),M=l.useRef(new Map),U=l.useMemo(()=>Yr,[]),W=l.useMemo(()=>qr({customVenues:[...d?[{name:"consumer-exact-output",chainIds:[r],preferred:!0,resolve:d}]:[],Qr(Ys),Qr(Or)]}),[d,r]),O=l.useMemo(()=>{if(!n?.asset)return null;const J=zt(n.asset,r);if(J)return J;const se=Xt(n.asset.address,r,n.asset.chainId);return se?se.address:null},[n?.asset,r]),z=l.useMemo(()=>n?.asset?Un(n.asset,r):[],[n?.asset,r]),N=l.useMemo(()=>z.map(J=>J.toLowerCase()).join(","),[z]);l.useEffect(()=>{let J=!1;if(E.current&&(clearTimeout(E.current),E.current=null),!n?.asset||z.length<=1){j(null);return}return E.current=setTimeout(async()=>{const se=t==="input"?n.amount:i||"0";let ce=0n;try{ce=t==="input"?D.parseUnits(se,n.asset.decimals):0n}catch{ce=0n}try{const de=await go(n.asset,r,{requiredAmount:ce});J||j(de)}catch{J||j(null)}},400),()=>{J=!0,E.current&&(clearTimeout(E.current),E.current=null)}},[n?.asset,n?.amount,r,z.length,N,t,i]);const P=l.useMemo(()=>F??O,[F,O]),Q=l.useMemo(()=>!n?.asset||!P?[]:[P,...z.filter(J=>J.toLowerCase()!==P.toLowerCase())],[n?.asset,P,z]),K=l.useMemo(()=>!n?.asset||!An(n.asset.address,n.asset.chainId,s.address,s.chainId)||!P?!1:p.addressesEqual(P,s.address),[n,s.address,s.chainId,P]),V=P?p.addressesEqual(P,s.address):!1,X=t==="output"&&parseFloat(i||"0")===0,xe=!!n?.asset&&!K&&!V&&!X,H=xe?T??P:P;return l.useEffect(()=>{A.current&&clearTimeout(A.current);const J=t==="input"?n?.amount:i,se=parseFloat(J||"0");if(!xe||!Number.isFinite(se)||se<=0||!n?.asset||!a||Q.length===0){S.current++,x(null),y(null),k(null),R(null),w(null),I(null),h(null),c(!1);return}const ce=n.asset.decimals;let de;try{de=t==="input"?D.parseUnits(n.amount,ce):D.parseUnits(i||"0",s.decimals)}catch{S.current++,h("Invalid amount"),c(!1);return}const ve=++S.current,ue=()=>ve!==S.current;c(!0);const pe=t==="output"?150:400,Ee=async(L,ee,te)=>{for(const oe of Q){const Z=`${t}:${r}:${oe.toLowerCase()}:${s.address.toLowerCase()}:${de.toString()}`,ne=M.current.get(Z),ge=ne&&ne.expiresAt>Date.now()?L(ne):void 0;if(ge)return{quote:ge,tokenIn:oe};const G=await te(oe);if(ue())return"stale";if(G)return M.current.set(Z,{expiresAt:Date.now()+3e4,direction:t,...ee(G)}),{quote:G,tokenIn:oe}}return null};return A.current=setTimeout(async()=>{try{if(t==="input"){const L=U.getVenueForChain(r);if(!L)throw new Error("No swap venue for this chain");const ee=await Ee(oe=>oe.resolvedSwap,oe=>({resolvedSwap:oe}),oe=>L.resolve({type:"swap",tokenIn:oe,tokenOut:s.address,amountIn:de},r,a));if(ee==="stale")return;if(!ee)throw new Error("No liquidity for this pair");I(ee.tokenIn),w(ee.quote.amountOut),k(ee.quote),R(null);const te=parseFloat(D.formatUnits(ee.quote.amountOut,s.decimals));x(te<.01?te.toPrecision(4):te.toLocaleString(void 0,{maximumFractionDigits:6})),y(null),h(null)}else{const L=await Ee(ee=>ee.exactOutputSwap,ee=>({exactOutputSwap:ee}),async ee=>{try{return await W.getQuote({tokenIn:ee,tokenOut:s.address,amountOut:de},r,a)}catch{return null}});if(L==="stale")return;if(!L)throw new Error("No liquidity for this pair");I(L.tokenIn),R(L.quote),k(null),w(null),y(parseFloat(D.formatUnits(L.quote.amountIn,ce)).toFixed(6)),x(null),h(null)}}catch(L){if(ue())return;const ee=L instanceof Error?L.message:"Failed to get quote";h(ee),x(null),y(null),k(null),R(null),w(null),I(null)}finally{ue()||c(!1)}},pe),()=>{A.current&&clearTimeout(A.current)}},[t,xe,n?.amount,n?.asset?.address,n?.asset?.decimals,i,Q,r,s.address,s.decimals,a,U,W]),{isQuoting:u,quoteError:f,estimatedOutput:g,estimatedInput:m,resolvedSwap:C,exactOutputSwap:b,quoteAmountOut:v,resolvedTokenIn:H,isDirect:V,needsSwap:xe,selectedIsEquivalent:K}}const xc=()=>{},yc=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,destinationToken:s,sourceChains:r,supportedSourceAssets:a,buildActionCalls:i,feeExecutionMode:d="user-transfer",buildSpicenetBatch:u,onPayExecute:c,resolveExactOutputSwap:f,actionLabel:h,amountDirection:g="input",swapDescription:x,directDescription:m,paymentAmount:y,amountInputMode:C="fixed",minPaymentAmount:k,maxPaymentAmount:b,onAmountChange:R,styles:v,dark:w,title:T,subtitle:I,onAddFunds:F,onSuccess:j,onError:A})=>{const E=g==="output",{theme:S,dark:M,primaryColor:U,dk:W,palette:O,fontFamily:z,monoFont:N,inputDark:P,cardBg:Q,cardBorder:K,textPrimary:V,textSecondary:X,subtitleText:xe}=p.useSpiceBrand(v,w),H=l.useMemo(()=>P?{...S,colors:{...S.colors,secondary:W.cardBg,surfaceHover:W.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:S,[P,S,W.cardBg,W.hoverBg]),J=s.chainId,se=l.useContext(p.SpiceFlowProviderContext),ce=(se?.mode||"7702")!=="7702",de=!!se?.isWhitelistGateActive,ve=!!se?.isWhitelistConfigured&&se?.isUserWhitelisted!==!0,ue=l.useMemo(()=>r??se?.supportedChainIds??[],[r,se?.supportedChainIds]),pe=l.useMemo(()=>{if(de)return[];if(a)return a;const ye=se?.allowedTokens;if(!ye||ye.length===0)return;const tt=new Set(ye.map(ns=>ns.toLowerCase())),pn=[],Wn=new Set;for(const ns of ue){const Gr=p.getChainConfig(ns);for(const ss of Gr?.supportedTokens??[]){if(!tt.has(ss.symbol.toLowerCase()))continue;const Js=ss.address.toLowerCase();Wn.has(Js)||(Wn.add(Js),pn.push(ss.address))}}return pn},[a,se?.allowedTokens,ue,de]),{address:Ee,isConnected:L,isReady:ee,isAuthenticated:te,provider:oe}=p.useWallet(),{execute:Z,estimate:ne}=mn(),{externalWallet:ge,embeddedAddress:G,activeWallet:Ie,activeAddress:ze}=p.useProviderWallets(),Ke=se?.externalWalletAddress,Ft=se?.embeddedWalletAddress||G,{displayAssets:mt,filteredSpiceAssets:Le,embeddedWalletAddress:le,refreshSpiceAssets:Ae,refreshWalletAssets:Xe}=Pr({destinationToken:s,supportedSourceAssets:pe,sourceChains:ue,enabled:e&&(ce?!!Ke:!!Ft)}),et=de||E||ce?mt:Le,[ae,nt]=l.useState(null),[ke,we]=l.useState(y||""),[fe,Me]=l.useState(!1),[xt,yt]=l.useState(null),Bt=l.useRef(A);Bt.current=A;const Fe=l.useCallback(ye=>{yt(ye),typeof ye=="string"&&ye&&Bt.current?.(new Error(ye),p.getRelayerErrorDetail(ye))},[]),[Ge,Ct]=l.useState("idle"),[kt,Tt]=l.useState(""),[Oe,st]=l.useState(null),[Mt,bt]=l.useState(!1),[he,He]=l.useState(null),[ot,ct]=l.useState(null),[be,gt]=l.useState(!1),[Rt,Je]=l.useState(!1),[Be,rt]=l.useState(null),Wt=l.useRef(ae),dt=l.useRef(!1),Qe=l.useRef(null),We=l.useRef(null),ut=l.useRef(null),At=l.useRef(null);l.useEffect(()=>{Wt.current=ae},[ae]);const Ve=C==="adjustable"?ke:y||"0",Ht=le||G||Ee,{isQuoting:De,quoteError:pt,estimatedOutput:Nt,resolvedSwap:at,exactOutputSwap:Te,quoteAmountOut:ft,resolvedTokenIn:ht,isDirect:it,needsSwap:qe,selectedIsEquivalent:It}=Zr({direction:g,selectedAsset:ae,destinationToken:s,chainId:J,recipient:Ht,paymentAmount:Ve,resolveExactOutputSwap:f}),Y=E?parseFloat(Ve||"0"):parseFloat(ae?.amount||"")||0,$=Y>0&&Y<Kt,re=ae?.asset?._source==="wallet",Ne=!!ae?.asset&&re&&ae.asset.chainId!==J,_=l.useMemo(()=>ae?.asset?Le.find(ye=>p.addressesEqual(ye.address,ae.asset.address))?.balanceFormatted??0:0,[ae,Le]),Ce=re?ae?.asset.balanceFormatted??0:_,Pe=l.useMemo(()=>{if(!ae?.asset)return!1;if(E)return ot?Ot(ot.grossAmount,ot.decimals,ae.asset.decimals)>ae.asset.balance:It||it?Y>ae.asset.balanceFormatted:Te?parseFloat(D.formatUnits(Te.amountInMax,ae.asset.decimals))>ae.asset.balanceFormatted:!1;if(ot){const ye=Ot(ot.grossAmount,ot.decimals,ae.asset.decimals);return re?ye>ae.asset.balance:parseFloat(D.formatUnits(ye,ae.asset.decimals))>Ce}return Y>Ce},[ae,E,ot,It,Y,Te,Ce,re,it]);l.useEffect(()=>{e||(nt(null),Fe(null),Me(!1),Ct("idle"),Tt(""),st(null),bt(!1),He(null),ct(null),gt(!1),Je(!1),rt(null),dt.current=!1,C==="adjustable"&&we(y||""),Qe.current&&(Qe.current.abort(),Qe.current=null))},[e]);const lt=l.useCallback(ye=>{nt(tt=>({asset:ye,amount:tt?.asset?.address===ye.address&&tt?.asset?.chainId===ye.chainId&&tt.amount||""})),Fe(null),rt(null),Je(!1)},[]),Ue=l.useCallback(ye=>{nt(tt=>tt&&{...tt,amount:ye}),Fe(null),rt(null),Je(!1)},[]),vt=l.useCallback(ye=>{let tt=ye;b&&parseFloat(tt)>parseFloat(b)&&(tt=b),we(tt),R?.(tt),Fe(null),rt(null),Je(!1)},[b,R]),Re=l.useCallback(ye=>{Ct({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[ye.step]||"executing"),Tt(ye.message),ye.txHash&&st(ye.txHash)},[]),je=l.useMemo(()=>({currentPaymentAmount:Ve,destinationToken:s,embeddedWalletAddress:le,providerEmbeddedAddress:G,externalWalletAddress:Ke,address:Ee,isNon7702:ce,isPayMode:E,resolvedChainId:J,buildActionCalls:i,feeExecutionMode:d,buildSpicenetBatch:u,selectedAsset:ae,needsSwap:qe,resolvedSwap:at,exactOutputSwap:Te,quoteAmountOut:ft,resolvedTokenIn:ht}),[Ve,s,le,G,Ke,Ee,ce,E,J,i,d,u,ae,qe,at,Te,ft,ht]),Ye=l.useCallback(ye=>xr({...je,requestTimestampMs:We.current??Date.now()},ye),[je]),Ze=l.useCallback(ye=>yr({...je,requestTimestampMs:We.current??Date.now()},ye),[je]),Et=l.useCallback((ye,tt,pn,Wn)=>Cr(ye,tt,pn,ne,Wn),[ne]),St=l.useMemo(()=>ae?.asset?qe&&ht?ht:ae.asset.chainId===J?ae.asset.address:ht??zt(ae.asset,J)??s.address:s.address,[ae,s.address,qe,J,ht]),cn=l.useCallback(()=>(We.current=Date.now(),Er(At.current)),[]),Dt=l.useMemo(()=>ae?.asset?p.addressesEqual(ae.asset.address,s.address)&&ae.asset.chainId===s.chainId:!1,[ae,s.address,s.chainId]),Ut=Dt&&(ce||E),wt=Ut&&Y>0&&!!ae?.asset,tn=ve&&!Ut,nn=l.useMemo(()=>{if(!wt)return null;let ye;try{ye=D.parseUnits(Ve||"0",s.decimals)}catch{return null}return{symbol:s.symbol,decimals:s.decimals,grossAmount:ye,netAmount:ye,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}},[wt,Ve,s.symbol,s.decimals]),dn=xt,Lt=l.useMemo(()=>!(!ae?.asset||Y<=0),[ae,Y,wt]),yn=l.useMemo(()=>!e||fe||Ge!=="idle"||!Lt||wt||!ae?.asset?null:[E?"pay":"supply",g,ae.asset.address.toLowerCase(),ae.asset.chainId,ae.amount,Ve,s.address.toLowerCase(),s.chainId,J,ht?.toLowerCase()??"",qe?"swap":"direct",it?"direct-token":"routed-token",ce?"non7702":"7702",Dt?"source-dest":"cross-chain",De?"quoting":"quoted",Te?.amountIn?.toString()??"",Te?.amountInMax?.toString()??"",Te?.venue??"",at?.amountOut?.toString()??"",ft?.toString()??"",le??"",G??"",Ee??""].join("|"),[e,fe,Ge,Lt,wt,ae,E,g,Ve,s,J,ht,qe,it,ce,Dt,De,Te,at,ft,le,G,Ee]),un=l.useCallback(()=>wr({selectedAsset:ae,isPayMode:E,parsedAmount:Y,needsSwap:qe,exactOutputSwap:Te,isNon7702:ce,isSourceDestToken:Dt,currentPaymentAmount:Ve,destinationToken:s,feeExecutionMode:d,resolvedTokenIn:ht,embeddedWalletAddress:le,providerEmbeddedAddress:G,resolvedChainId:J,isConnected:L,address:Ee,ready:ee,authenticated:te,isDirect:it,resolvedSwap:at,isQuoting:De,executionTokenAddress:St,buildPayChainBatches:Ye,buildSupplyChainBatches:Ze,estimate:ne,estimateRequiredGrossFunding:Et}),[ae,E,Y,qe,Te,ce,Dt,Ve,s,d,ht,le,G,Et,Ye,ne,J,L,Ee,ee,te,it,at,De,Ze,St]);l.useEffect(()=>{ut.current=un},[un]);const Tn=l.useCallback(ye=>br({asset:ye,isPayMode:E,isNon7702:ce,needsSwap:qe,isQuoting:De,embeddedWalletAddress:le,buildSupplyChainBatches:Ze,estimate:ne,executionTokenAddress:St,feeExecutionMode:d}),[E,ce,qe,De,le,Ze,ne,St,d]);sr({shouldRun:e&&!fe&&Ge==="idle"&&Lt&&!wt&&!De&&!!yn,deps:[e,fe,Ge,Lt,wt,nn,De,yn],onSkip:()=>{if(!e){gt(!1),Je(!1),rt(null),ct(null);return}if(fe||Ge!=="idle"){gt(!1);return}if(!Lt){ct(null),gt(!1),Je(!1),rt(null);return}if(wt){ct(nn),gt(!1),Je(!0),rt(null);return}De&&(gt(!1),Je(!1))},onCleanup:()=>gt(!1),run:async({isCurrent:ye})=>{rt(null),gt(!0);try{const tt=await ut.current?.();if(!ye())return;tt?(ct(tt),Je(!0)):(ct(null),Je(!1)),rt(null)}catch(tt){if(!ye())return;const pn=p.sanitizeError(tt,"Unable to calculate fees for this action.");ct(null),Je(!1),rt(pn)}finally{ye()&>(!1)}}});const Rn=l.useCallback(()=>(We.current=Date.now(),Fr(At.current)),[]);l.useEffect(()=>{!E&&Ge==="success"&&Oe&&(Ae(),j?.(Oe))},[E,Ge,Oe,Ae,j]),l.useEffect(()=>{if(!E||he?.status!=="success"||dt.current||!Ee)return;dt.current=!0;const ye=Wt.current;!ye?.asset||ye.asset?._source==="wallet"||Ae()},[E,he?.status,Ee,Ae]);const q=l.useRef(j),ie=l.useRef(A);l.useEffect(()=>{q.current=j},[j]),l.useEffect(()=>{ie.current=A},[A]),l.useEffect(()=>{e&&(Ae(),Xe())},[e,Ae,Xe]),l.useEffect(()=>{E&&(he?.status==="success"&&q.current?.(he.txHash||""),he?.status==="failed"&&ie.current?.(new Error("Payment execution failed")))},[E,he?.status]);const Se=l.useCallback(()=>{bt(!1),He(null),nt(null),dt.current=!1,Ae(),Xe()},[Ae,Xe]);At.current={selectedAsset:ae,parsedAmount:Y,currentPaymentAmount:Ve,isInsufficientBalance:Pe,isPayMode:E,isNon7702:ce,isSourceDestToken:Dt,needsSwap:qe,exactOutputSwap:Te,selectedIsEquivalent:It,resolvedTokenIn:ht,embeddedWalletAddress:le,providerEmbeddedAddress:G,externalWallet:ge,externalWalletAddress:Ke,activeSignerWallet:Ie,activeSignerAddress:ze,address:Ee,isConnected:L,ready:ee,authenticated:te,provider:oe,resolvedChainId:J,executionTokenAddress:St,destinationToken:s,buildActionCalls:i,feeExecutionMode:d,buildSpicenetBatch:u,onPayExecute:c,onSuccess:j,execution:{estimate:ne,execute:Z,buildPayChainBatches:Ye,buildSupplyChainBatches:Ze,estimateRequiredGrossFunding:Et,onProgress:Re},ui:{setError:Fe,setStep:Ct,setStatusMsg:Tt,setTxHash:st,setIsExecuting:Me,setShowStatusPanel:bt,setPaymentResult:He},refs:{spiceDepositSubmittedRef:dt,abortControllerRef:Qe}};const me=y?.trim(),$e=E&&C==="fixed"&&me!==void 0&&me!==""&&Y===0,_e=E?($e||!!ae?.asset)&&Y>=0&&!$&&!Pe&&!fe&&($e||wt||Rt)&&!Be&&($e||!qe||!!Te)&&!tn:!!ae?.asset&&Y>0&&!$&&!Pe&&!fe&&(Ut||Rt)&&!Be&&(Ne||it||!!at&&!De)&&!tn,sn=it?m||`Your ${s.symbol} will be used directly.`:x||"Your assets will be swapped and used in a single atomic transaction.",Dn=(J?p.getChainConfig(J):void 0)?.viemChain?.blockExplorers?.default?.url??"",Mn=Dr.indexOf(Ge),es=fe?(Rr[Ge]||"EXECUTING...").toUpperCase():Ge==="success"?"DONE":$?`MINIMUM ${Kt}`:Pe?"INSUFFICIENT BALANCE":qe&&pt&&!De?"QUOTE ERROR":h.toUpperCase(),ts=l.useMemo(()=>{if(fe)return"PAYING...";if($)return`MINIMUM ${Kt}`;if(Pe&&ae?.asset)return`INSUFFICIENT ${ae.asset.symbol}`;if(qe&&pt&&!De)return"QUOTE ERROR";if(h)return h.toUpperCase();const ye=Y>0?` ${Ve} ${s.symbol}`:"";return qe?`SWAP & PAY${ye}`:`PAY${ye}`},[fe,$,Pe,ae,h,Y,Ve,s.symbol,qe,pt,De]),Kr=Ge==="success"?()=>{Ct("idle"),nt(null),st(null),Ae()}:cn,Xr=Ge==="success"?!1:!_e;if(!e)return null;const Zs=E?T||`Pay ${s.symbol}`:h,Ks=E?I:o.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[o.jsx("span",{style:{marginTop:"3px",flexShrink:0},children:o.jsx(Ss,{color:xe})}),o.jsx("p",{style:{fontSize:"12px",color:xe,margin:0,lineHeight:"1.4",fontFamily:z},children:sn})]}),Xs={...v,button:{...v?.button,backgroundColor:U}},Gs=Lt&&o.jsx(Is,{fontFamily:z,textPrimary:V,textSecondary:X,cardBg:Q,cardBorder:K,resolvedDark:M,darkCardBorder:W.cardBorder,primaryColor:U,feePreview:ot,isLoading:be,errorText:Be,directExecutionFeeNote:wt});if(E){const ye=he&&(he.status==="success"||he.status==="failed")?[{asset:{symbol:ae?.asset?.symbol||s.symbol,address:ae?.asset?.address||""},amount:Ve,txHash:he.txHash||"",success:he.status==="success",error:he.status==="failed"?he.error:void 0}]:void 0;return o.jsx(Vt,{isOpen:e,onClose:t,title:Zs,subtitle:Ks,styles:v,dark:M,footerLinkText:"Spicenet accounts \u2192",closeOnBackdropClick:n,children:o.jsxs("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[F&&o.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:o.jsx(Es,{onClick:F,color:U,fontFamily:z})}),!$e&&o.jsx("div",{style:{marginBottom:"12px"},children:o.jsx(vn,{assets:et,selectedAsset:ae??void 0,onAssetSelect:lt,onAmountChange:xc,label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:ae?.asset?qe?De?"...":Te?`~${parseFloat(D.formatUnits(Te.amountIn,ae.asset.decimals)).toFixed(6)}`:void 0:Ve??void 0:void 0,dark:M,theme:H,styles:v})}),o.jsx(Br,{variant:"pay",destinationSymbol:s.symbol,destinationLogoURI:s.logoURI,destinationDecimals:s.decimals,primaryColor:U,fontFamily:z,textPrimary:V,textSecondary:X,cardBg:Q,cardBorder:K,dk:W,dark:M,isQuoting:De,quoteError:pt,estimatedOutput:Nt,paymentAmount:Ve,needsSwap:qe,exactOutputSwap:Te,adjustable:C==="adjustable",maxAmount:b,onAmountChange:vt}),Gs,dn&&o.jsx(an,{variant:"error",palette:O,fontFamily:z,style:{marginBottom:"12px"},children:dn}),o.jsx(p.Button,{variant:"outline",fullWidth:!0,onClick:Rn,disabled:!_e,loading:fe,dark:M,styles:Xs,children:ts}),he&&Mt&&o.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:M?W.shell:"white",borderRadius:M?"12px":"6px",padding:"16px 0"},children:o.jsx(Ms,{type:"payment",isOpen:he.status!=="processing",isProcessing:fe||he.status==="processing",closeOnComplete:!1,chainId:J,onRetryTx:()=>{bt(!1),He(null),Rn()},onNewTx:Se,onClose:()=>{bt(!1),He(null)},onComplete:Se,results:ye,styles:v,dark:M})})]})})}return o.jsx(Vt,{isOpen:e,onClose:t,title:Zs,subtitle:Ks,dark:M,styles:v,theme:S,closeOnBackdropClick:n,children:o.jsxs("div",{style:{padding:"24px 24px 5px 24px",position:"relative"},children:[o.jsx("div",{style:{marginBottom:"16px"},children:o.jsx(vn,{assets:et,selectedAsset:ae||void 0,onAssetSelect:lt,onAmountChange:Ue,disabled:fe||Ge==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:H,styles:v,dark:P,resolveMaxAmount:Tn,maxAmount:Ce>0?p.formatDecimalInput(Ce,ae?.asset.decimals??s.decimals):void 0})}),ae?.asset&&!it&&o.jsx(Br,{variant:"supply",destinationSymbol:s.symbol,destinationLogoURI:s.logoURI,destinationDecimals:s.decimals,primaryColor:U,fontFamily:z,textPrimary:V,textSecondary:X,cardBg:Q,cardBorder:K,dark:M,isQuoting:De,quoteError:pt,estimatedOutput:Nt}),Gs,Ge!=="idle"&&o.jsx(ac,{step:Ge,statusMsg:kt,txHash:Oe,explorerUrl:Dn,currentStepIdx:Mn,palette:O,cardBg:Q,cardBorder:K,textPrimary:V,textSecondary:X,fontFamily:z,primaryColor:U,onRetry:()=>{Ct("idle"),Fe(null),setTimeout(cn,50)}}),xt&&Ge==="idle"&&o.jsx(an,{variant:"error",palette:O,fontFamily:z,style:{marginBottom:"16px"},children:xt}),o.jsx(p.Button,{variant:"outline",fullWidth:!0,disabled:Xr,onClick:Kr,theme:S,dark:M,styles:Xs,style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:N},children:es})]})})},Cc=()=>{const[e,t]=l.useState("0"),[n,s]=l.useState(null);return{assetAmount:e,setAssetAmount:t,selectedAsset:n,setSelectedAsset:s}};function bc(e,t=0){const[n,s]=l.useState(t),r=e[n]??e[0],a=l.useMemo(()=>r?BigInt(Math.round(r.months*30*24*3600)):0n,[r?.months]);return{selectedDurationIdx:n,setSelectedDurationIdx:s,selectedDuration:r,durationSeconds:a}}function wc(){const{actions:e,isReady:t,isAuthenticated:n}=p.useWallet(),s=l.useContext(p.SpiceFlowProviderContext)?.embeddedWalletAddress,r=l.useRef(!1),a=l.useRef(0),i=l.useRef(null),d=l.useRef(e),[u,c]=l.useState(0);d.current=e,l.useEffect(()=>{r.current=!1,a.current=0,i.current&&(clearTimeout(i.current),i.current=null)},[s]),l.useEffect(()=>{if(!s||!t||!n||r.current)return;r.current=!0;let f=!1;return(async()=>{await qt(2e3);try{await p.ensureSmartWallet(s,d.current.signMessage),a.current=0}catch(h){console.warn("[SmartWallet] Registration failed:",h),r.current=!1,!f&&a.current<3&&(a.current+=1,i.current=setTimeout(()=>{c(g=>g+1)},5e3))}})(),()=>{f=!0,i.current&&(clearTimeout(i.current),i.current=null)}},[s,t,n,u])}ta(),exports.SpiceFlowProvider=p.SpiceFlowProvider,exports.SpiceFlowProviderContext=p.SpiceFlowProviderContext,exports.SpiceflowError=p.SpiceflowError,exports.Spinner=p.Spinner,exports.buildDarkPalette=p.buildDarkPalette,exports.buildLightPalette=p.buildLightPalette,exports.duration=p.duration,exports.easing=p.easing,exports.font=p.font,exports.getChainConfig=p.getChainConfig,exports.getChainName=p.getChainName,exports.isSpiceflowError=p.isSpiceflowError,exports.radius=p.radius,exports.relayerService=p.relayerService,exports.resolveTheme=p.resolveTheme,exports.transition=p.transition,exports.useIsUserWhitelisted=p.useIsUserWhitelisted,exports.useSpiceBrand=p.useSpiceBrand,exports.useWallet=p.useWallet,exports.z=p.z,Object.defineProperty(exports,"NATIVE_TOKEN_ADDRESS",{enumerable:!0,get:function(){return B.ZERO_ADDRESS}}),Object.defineProperty(exports,"SPICENET_NATIVE_CHAIN_ID",{enumerable:!0,get:function(){return B.SPICENET_NATIVE_CHAIN_ID}}),Object.defineProperty(exports,"SPICE_COMBINED_FEE_RECIPIENT",{enumerable:!0,get:function(){return B.SPICE_COMBINED_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_GAS_FEE_RECIPIENT",{enumerable:!0,get:function(){return B.SPICE_GAS_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_PLATFORM_FEE_RECIPIENT",{enumerable:!0,get:function(){return B.SPICE_PLATFORM_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_SOLVER_ADDRESS",{enumerable:!0,get:function(){return B.SPICE_SOLVER_ADDRESS}}),Object.defineProperty(exports,"applySlippage",{enumerable:!0,get:function(){return B.applySlippage}}),Object.defineProperty(exports,"buildUniV3SwapCalls",{enumerable:!0,get:function(){return B.buildUniV3SwapCalls}}),Object.defineProperty(exports,"getChainIdsByNetwork",{enumerable:!0,get:function(){return B.getChainIdsByNetwork}}),Object.defineProperty(exports,"getEscrowContractAddress",{enumerable:!0,get:function(){return B.getEscrowContractAddress}}),Object.defineProperty(exports,"isNativeToken",{enumerable:!0,get:function(){return B.isNativeToken}}),Object.defineProperty(exports,"isSpicenetChainId",{enumerable:!0,get:function(){return B.isSpicenetChainId}}),Object.defineProperty(exports,"normalizeNativeTokenAddress",{enumerable:!0,get:function(){return B.normalizeNativeTokenAddress}}),Object.defineProperty(exports,"spicenetAbi",{enumerable:!0,get:function(){return B.spicenetAbi}}),Object.defineProperty(exports,"spicenetWithdrawalAbi",{enumerable:!0,get:function(){return B.spicenetAbi}}),exports.AccountDisplay=Jl,exports.AddFundsLink=Es,exports.CheckIcon=_s,exports.ChevronIcon=on,exports.CloseIcon=Sn,exports.DetailRow=gn,exports.ProviderLogin=Ds,exports.SATSUMA_CITREA_CONFIG=Ys,exports.SearchInput=rs,exports.SelectChainModal=Li,exports.SpiceDeposit=Ui,exports.SpiceLock=El,exports.SpiceSupply=yc,exports.SpiceWithdraw=dl,exports.StatusBanner=an,exports.UNIV3_BASE_CONFIG=Or,exports.areEquivalentOnChains=An,exports.buildPayChainBatches=xr,exports.buildRoutedBatches=ll,exports.buildSupplyChainBatches=yr,exports.createExactOutputRegistry=qr,exports.createLiquidityRegistry=Vr,exports.createSatsumaVenue=Hr,exports.estimateFeePreview=wr,exports.estimateRequiredGrossFunding=Cr,exports.estimateSupplyMaxAmount=br,exports.executePay=Fr,exports.executeSupply=Er,exports.findEquivalentOnChain=Xt,exports.getAssetChainTokenCandidates=Un,exports.getBestUniV3Quote=Ur,exports.isSupportedSupplyAsset=Wr,exports.resolveAssetTokenAddressOnChain=zt,exports.resolveFundedToken=go,exports.resolveInputSupplySwapQuote=gc,exports.resolveRoute=il,exports.scaleTokenAmount=Ot,exports.useAssetInput=Cc,exports.useLockDuration=bc,exports.useSmartWallet=wc,exports.useSpiceAssets=jn,exports.useSpiceExecution=mn,exports.useSpicePendingDeposits=dr,exports.useSupplyAssets=Pr,exports.useSupplyQuote=Zr;
|