@spicenet-io/spiceflow-ui 3.3.51 → 3.3.52

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 CHANGED
@@ -100,7 +100,7 @@
100
100
  from { transform: rotate(0deg); }
101
101
  to { transform: rotate(360deg); }
102
102
  }
103
- `})]})},zi="0xa9059cbb";function Li(e){const t=new Map;for(const s of e){if(s.amount<=0n)continue;const o=j.getAddress(s.token),r=j.getAddress(s.to),a=`${o.toLowerCase()}:${r.toLowerCase()}`,i=t.get(a);i?i.amount+=s.amount:t.set(a,{token:o,to:r,amount:s.amount})}return[...t.values()]}function Oi(e,t){return`0x${t}${e.slice(4)}`}function Hi(e,t,s){if(!Array.isArray(e))return 0n;const o=`evm:${t}:${s.slice(2).toLowerCase()}`;let r=0n;for(const a of e){if(!a||typeof a!="object")continue;const i=a,d=i.chainTokens;if((Array.isArray(d)?d.filter(u=>typeof u=="string"):d&&typeof d=="object"?Object.keys(d):[]).some(u=>u.toLowerCase()===o))try{r+=BigInt(i.balanceAvailable??"0")}catch{}}return r}async function Xo(e,t,s,o){const r=await fetch(`${e}/wallets/${t}/balance`,{cache:"no-store"});if(!r.ok)throw new Error(`Failed to fetch spice balance: ${r.status}`);const a=await r.json();return Hi(a?.balances,s,o)}async function Qi({apiBaseUrl:e,user:t,chainId:s,tokenAddress:o,prevBalance:r,timeoutMs:a=3e4,pollIntervalMs:i=1500}){const d=Date.now()+a;for(await new Promise(u=>setTimeout(u,800));Date.now()<d;){try{if(await Xo(e,t,s,o)>r)return}catch(u){console.warn("[SpiceLockModal] spice balance poll failed:",u?.message)}await new Promise(u=>setTimeout(u,i))}console.warn("[SpiceLockModal] Spicenet indexer did not reflect deposit within timeout; proceeding with intent")}function Ls(e,t){return Os(e,t)}function Os(e,t,s){const o=Vi(t,e),r=Math.floor(Date.now()/1e3)+60*10,a=F.hashChainBatches(o);return{user:e,...s?{chainAuthorizations:s}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:"0x00",nbf:0,exp:r,chainBatches:a.map((i,d)=>({hash:i.hash,chainId:i.chainId,tokenTransfers:o[d].domain==="spicenet"?[]:o[d].tokenTransfers??[],calls:i.calls}))}]}}function Vi(e,t){return e.map(s=>{if(s.domain==="spicenet"||s.calls.length===0)return s;const o=new Set((s.tokenTransfers??[]).filter(a=>(a.from==="escrow"||a.from==="solver")&&j.getAddress(a.to).toLowerCase()===t.toLowerCase()).map(a=>j.getAddress(a.token).toLowerCase()));if(o.size===0)return s;let r=0;for(const a of s.calls){if(!a.data?.startsWith(zi))break;try{const i=j.decodeFunctionData({abi:f.U,data:a.data});if(i.functionName!=="transfer")break;const[d]=i.args;if(d.toLowerCase()===t.toLowerCase()||!o.has(j.getAddress(a.to).toLowerCase()))break;r+=1}catch{break}}return r===0?s:{...s,calls:s.calls.slice(r)}})}function zt(e,t,s,o){if(e.some(l=>l.domain==="spicenet"))return e;const r=s?.intents.flatMap(l=>l.batches),a=l=>l.from==="escrow",i=e.map(l=>{const h=r?.find(k=>k.chainId===l.chainId);if(!h)return l;const p=Xt(h),g=p.totalFee;if(g<=0n)return l;const x=(l.tokenTransfers??[]).find(k=>a(k)&&j.getAddress(k.to).toLowerCase()===t.toLowerCase()&&!F.isNativeToken(j.getAddress(k.token)));if(!x)return l;const m=j.getAddress(x.token);let y=!1;const w=(l.tokenTransfers??[]).map(k=>y||!a(k)||j.getAddress(k.to).toLowerCase()!==t.toLowerCase()||j.getAddress(k.token).toLowerCase()!==m.toLowerCase()?k:(y=!0,{...k,amount:o?.payoutAlreadyGross?BigInt(k.amount):BigInt(k.amount)+g}));if(!y)return l;const S=[];p.spicenetFee>0n&&S.push({to:m,value:0n,data:j.encodeFunctionData({abi:f.U,functionName:"transfer",args:[F.SPICE_PLATFORM_FEE_RECIPIENT,p.spicenetFee]})});const b=p.gasFee+p.bridgeFee;return b>0n&&S.push({to:m,value:0n,data:j.encodeFunctionData({abi:f.U,functionName:"transfer",args:[F.SPICE_GAS_FEE_RECIPIENT,b]})}),{...l,tokenTransfers:w,calls:[...S,...l.calls]}}),d=i.flatMap(l=>(l.tokenTransfers??[]).filter(a).map(h=>{const p=j.getAddress(h.token),g=j.getAddress(h.to),x=[{token:p,to:g,amount:BigInt(h.amount)}];return{chainId:l.chainId,transfers:Li(x)}}));if(d.length===0)return e;const u=BigInt(Math.floor(Date.now()/1e3))+3600n;return[{chainId:F.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:d.map((l,h)=>{const p=j.keccak256(j.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,l.transfers[0].token,l.transfers.reduce((x,m)=>x+m.amount,0n),BigInt(l.chainId),BigInt(Date.now()+h)])),g=Oi(p,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:j.encodeFunctionData({abi:F.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${l.chainId}`,idempotenceKey:g,nbf:0n,exp:u,metadata:"{}",transfers:l.transfers.map(x=>({token:x.token.toLowerCase(),to:x.to,amount:x.amount}))}]})}})},...i]}function Hs(e,t){return t?e.some(s=>(s.tokenTransfers??[]).some(o=>o.from==="escrow"&&BigInt(o.amount)>=t.grossAmount)):!1}function Qs(e){const t=e.selectedAsset?.asset,s=e.selectedAsset?.amount;if(!(!t||!s))return j.parseUnits(s,t.decimals)}function un(e,t){const s=e.selectedAsset?.asset;if(!s||!e.selectedAsset?.amount)throw new Error("Select an asset and enter an amount");const o=j.parseUnits(e.selectedAsset.amount,s.decimals),r=t?.grossAmount??o;return e.resolveLockBatches({amount:e.selectedAsset.amount,amountWei:o,grossAmount:j.formatUnits(r,s.decimals),grossAmountWei:r})}async function Vs(e,t,s){const o=[...new Set(s.filter(a=>a.domain!=="spicenet").map(a=>a.chainId))],r=[];for(const a of o){const i=f.getClientForChain(a),d=f.getDelegateContractAddress(a),u=await F.getAccountNonce(t,i),l=await e.actions.signAuthorization({contractAddress:d,chainId:a,nonce:Number(u)});r.push(l)}return r}async function Jo(e,t,s){const o=e.isSemi7702&&e.providerEmbeddedAddress||e.address;if(!e.isConnected||!o)throw new Error("Please connect your wallet to continue");if(t.length===0)throw new Error("No lock batches configured");if(!e.ready||!e.authenticated)throw new Error(`Please authenticate with ${e.provider||"wallet provider"} to continue`);const r=s??await Vs(e,o,t),a=F.hashChainBatches(t),i=Math.floor(Date.now()/1e3)+60*10,d=a.map(x=>x.hash),u=j.keccak256(j.encodeAbiParameters([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,BigInt(i),d])),l=await e.actions.signMessage({raw:u}),h=typeof l=="string"?l:l.signature;if(!h)throw new Error("Failed to sign intent authorization");const p={mode:"7702",signatureType:"ecdsa",signature:h,nbf:0,exp:i,chainBatches:a.map((x,m)=>{const y=t[m],w=y.domain==="spicenet";return{hash:x.hash,chainId:x.chainId,tokenTransfers:w?[]:y.tokenTransfers??[],calls:x.calls}})},g=await f.relayerService.createAction({user:o,chainAuthorizations:r.map(x=>({r:x.r,s:x.s,yParity:x.yParity,address:x.address,chainId:Number(x.chainId),nonce:Number(x.nonce)})),intents:[p]});if(g){const x=f.createInitialSteps(t,f.getChainName),[m,y]=g.intentIds[0].split("/"),w=parseInt(y||"0",10),S=g.intentIds[0];e.startStatusPolling(g.intentIds[0],x),await To({actionId:m,intentIndex:w,intentId:S,totalSteps:t.length,isSpicenetStep:b=>t[b]?.domain==="spicenet",maxExecuteAttemptsForStep:b=>t[b]?.domain==="spicenet"?6:3,maxPolls:180})}}async function $o(e){let t=un(e);if(t.length===0)throw new Error("No lock batches configured");const s=e.isSemi7702&&e.providerEmbeddedAddress||e.address;if(!e.isConnected||!s)throw new Error("Please connect your wallet to continue");const o=await Vs(e,s,t);let r=zt([...t],s),a;for(let i=0;i<4;i+=1){const d=await f.relayerService.estimateActionFees(Os(s,r,o.map(p=>({r:p.r,s:p.s,yParity:p.yParity,address:p.address,chainId:Number(p.chainId),nonce:Number(p.nonce)})))),u=zn(d,{symbol:e.selectedAsset?.asset.symbol??"",decimals:e.selectedAsset?.asset.decimals??18,actionAmount:Qs(e)});if(!u)break;const l={grossAmount:u.grossAmount,netAmount:u.netAmount,feeAmount:u.totalFee??0n},h=a?.grossAmount===l.grossAmount&&a?.netAmount===l.netAmount&&a?.feeAmount===l.feeAmount;if(a=l,t=un(e,a),r=zt([...t],s,d,{payoutAlreadyGross:Hs(t,a)}),h)break}await Jo(e,r,o)}async function qi(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");if(!e.address||!e.embeddedWalletAddress)throw new Error("Embedded wallet not connected");const t=e.selectedAsset.asset,s=j.parseUnits(e.selectedAsset.amount,t.decimals),o=e.escrowAddress||f.getDelegateContractAddress(e.lockChainId),r=f.relayerService.getBaseUrl(),a=F.normalizeNativeTokenAddress(t.address);let i=0n;try{i=await Xo(r,e.embeddedWalletAddress,e.lockChainId,a)}catch(p){console.warn("[SpiceLockModal] could not snapshot spice balance pre-deposit:",p?.message)}const d=await e.actions.getEthereumProvider();await f.ensureWalletOnChain(d,e.lockChainId);const u=f.getChainConfig(e.lockChainId),l=j.createWalletClient({account:e.embeddedWalletAddress,transport:j.custom(d),chain:u?.viemChain});let h;if(t.isNative||F.isNativeToken(t.address))h=await l.sendTransaction({to:o,value:s,chain:u?.viemChain});else{const p=j.encodeFunctionData({abi:f.U,functionName:"transfer",args:[o,s]});h=await l.sendTransaction({to:t.address,data:p,chain:u?.viemChain})}if((await f.getClientForChain(e.lockChainId).waitForTransactionReceipt({hash:h,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to escrow failed");await Qi({apiBaseUrl:r,user:e.embeddedWalletAddress,chainId:e.lockChainId,tokenAddress:a,prevBalance:i}),await e.refreshSpiceAssets(),e.refreshWalletAssets(),await $o(e)}async function Ki(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");if(e.onLockExecute){const E=e.resolveLockBatches();if(E.length===0)throw new Error("No lock batches configured");const A=e.selectedAsset.asset,M=j.parseUnits(e.selectedAsset.amount,A.decimals),T=await e.onLockExecute({asset:A,amount:e.selectedAsset.amount,amountWei:M,lockDurationMonths:e.selectedDuration?.months??0,chainBatches:E});T&&e.onLockSuccess?.(T);return}const s=e.resolveLockBatches();if(s.length===0)throw new Error("No lock batches configured");const o=e.selectedAsset.asset,r=j.parseUnits(e.selectedAsset.amount,o.decimals),a=o.chainId,i=e.escrowAddress||F.getEscrowContractAddress(a),d=F.normalizeNativeTokenAddress(o.address),u=o.isNative||F.isNativeToken(d),l=s.some(E=>E.tokenTransfers?.some(A=>A.from==="escrow")),h=E=>({chainId:a,calls:u?[{to:i,value:E,data:"0x"}]:[{to:d,value:0n,data:j.encodeFunctionData({abi:f.U,functionName:"transfer",args:[i,E]})}]}),p=(E,A,M)=>{const T=h(E);if(!l)return[T,...A];const v=zt([...A],t,M,{payoutAlreadyGross:Hs(A,y)});return[T,...v]};let g=un(e),x=p(r,g);const m=await Vs(e,t,x);let y;if(l)for(let E=0;E<4;E+=1){const A=await f.relayerService.estimateActionFees(Os(t,x,m.map(B=>({r:B.r,s:B.s,yParity:B.yParity,address:B.address,chainId:Number(B.chainId),nonce:Number(B.nonce)})))),M=zn(A,{symbol:o.symbol,decimals:o.decimals,actionAmount:r});if(!M)break;const T={grossAmount:M.grossAmount,netAmount:M.netAmount,feeAmount:M.totalFee??0n},v=y?.grossAmount===T.grossAmount&&y?.netAmount===T.netAmount&&y?.feeAmount===T.feeAmount;if(y=T,g=un(e,y),x=p(T.grossAmount,g,A),v)break}const w=y?.grossAmount??r,S=await e.externalWallet.getEthereumProvider();let b=null;try{const E=await S.request({method:"eth_chainId"});b=parseInt(E,16)}catch{b=null}b!==a&&await f.ensureWalletOnChain(S,a);const k=f.getChainConfig(a),I=j.createWalletClient({account:e.externalWalletAddress,chain:k?.viemChain,transport:j.custom(S)}),C=u?await I.sendTransaction({to:t,value:w,chain:k?.viemChain}):await I.sendTransaction({to:d,data:j.encodeFunctionData({abi:f.U,functionName:"transfer",args:[t,w]}),chain:k?.viemChain});if((await f.getClientForChain(a).waitForTransactionReceipt({hash:C,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to embedded wallet failed");await Jo(e,x,m)}async function Zi(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount||!e.requiresRelayerFeeEstimate)return null;if(e.isSemi7702){const i=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!i)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");let d=un(e);if(d.length===0)throw new Error("No lock batches configured");const u=e.selectedAsset.asset,l=j.parseUnits(e.selectedAsset.amount,u.decimals),h=u.chainId,p=e.escrowAddress||F.getEscrowContractAddress(h),g=F.normalizeNativeTokenAddress(u.address),x=u.isNative||F.isNativeToken(g),m=d.some(I=>I.tokenTransfers?.some(C=>C.from==="escrow")),y=I=>({chainId:h,calls:x?[{to:p,value:I,data:"0x"}]:[{to:g,value:0n,data:j.encodeFunctionData({abi:f.U,functionName:"transfer",args:[p,I]})}]}),w=(I,C,E)=>{const A=y(I);if(!m)return[A,...C];const M=zt([...C],i,E,{payoutAlreadyGross:C.some(T=>(T.tokenTransfers??[]).some(v=>v.from==="escrow"&&BigInt(v.amount)>=I))});return[A,...M]};let S=w(l,d),b=null,k;for(let I=0;I<4;I+=1){const C=await f.relayerService.estimateActionFees(Ls(i,S)),E=zn(C,{symbol:u.symbol,decimals:u.decimals,actionAmount:l});if(!E)return b;const A={grossAmount:E.grossAmount,netAmount:E.netAmount,feeAmount:E.totalFee??0n},M=k?.grossAmount===A.grossAmount&&k?.netAmount===A.netAmount&&k?.feeAmount===A.feeAmount;if(b=E,k=A,d=un(e,A),S=w(A.grossAmount,d,C),M)break}return b}const t=e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");let s=un(e);if(s.length===0)throw new Error("No lock batches configured");let o=zt([...s],t),r=null;for(let i=0;i<4;i+=1){const d=await f.relayerService.estimateActionFees(Ls(t,o)),u=zn(d,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:Qs(e)});if(!u)return null;const l={grossAmount:u.grossAmount},h=r?.grossAmount===u.grossAmount&&r?.netAmount===u.netAmount&&r?.totalFee===u.totalFee;if(r=u,s=un(e,l),o=zt([...s],t,d,{payoutAlreadyGross:Hs(s,l)}),h)break}if(r)return r;const a=await f.relayerService.estimateActionFees(Ls(t,o));return zn(a,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:Qs(e)})}async function Gi(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.resolveLockBatches();if(t.length===0)throw new Error("No lock batches configured");const s=t.find(l=>l.chainId===e.lockChainId)||t[0];if(!s)throw new Error("No lock batch for lock chain");const o=await e.externalWallet.getEthereumProvider();let r=null;try{const l=await o.request({method:"eth_chainId"});r=parseInt(l,16)}catch{r=null}r!==e.lockChainId&&await f.ensureWalletOnChain(o,e.lockChainId);const a=f.getChainConfig(e.lockChainId),i=j.createWalletClient({account:e.externalWalletAddress,chain:a?.viemChain,transport:j.custom(o)}),d=f.getClientForChain(e.lockChainId);let u;for(const l of s.calls){const h=await i.sendTransaction({to:l.to,data:l.data,value:l.value,chain:a?.viemChain});if((await d.waitForTransactionReceipt({hash:h,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Lock transaction failed");u=h}u&&e.onLockSuccess?.(u)}async function Yi(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=s=>{console.error("[SpiceLockModal] lock failed:",s);const o=f.sanitizeError(s,""),r=typeof s?.shortMessage=="string"?s.shortMessage:typeof s?.message=="string"?s.message:"";e.ui.setError(o||r||"Transaction failed. Please try again.")};if(e.isSemi7702){if(e.isSourceDestToken){try{await Gi(e)}catch(s){t(s)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{await Ki(e)}catch(s){t(s)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{e.isDirectDeposit&&!e.isSourceDestToken?await qi(e):await $o(e)}catch(s){t(s)}finally{e.ui.setIsExecuting(!1)}}const _o=({isOpen:e,onClose:t,closeOnBackdropClick:s=!1,lockBatches:o,lockTokenSymbol:r,lockTokenLogoURI:a,destinationInputHook:i,sourceAssetInputHook:d,lockDurationHook:u,lockChainId:l,durationOptions:h,votingPowerEstimate:p,escrowAddress:g,includeWalletAssets:x=!1,destinationTokenAddress:m,onLockSuccess:y,onLockExecute:w,sourceToDestinationConversionRate:S,estimatedOutputAmount:b,onAddFunds:k,buildSpicenetBatch:I,styles:C,dark:E=!1})=>{const{theme:A,dark:M,primaryColor:T,dk:v}=f.useSpiceBrand(C,E),B=A.typography.fontFamily,D=c.useContext(f.SpiceFlowProviderContext),R=D?.mode||"7702",O=!!D?.isWhitelistGateActive,U=R!=="7702",H=c.useMemo(()=>D?.supportedChainIds??[],[D?.supportedChainIds]),q=c.useMemo(()=>{if(O)return[];const X=D?.allowedTokens;if(!X||X.length===0)return[];const ce=new Set(X.map(ze=>ze.toLowerCase())),Fe=[],Ee=new Set;for(const ze of H){const ut=f.getChainConfig(ze);for(const qt of ut?.supportedTokens??[]){if(!ce.has(qt.symbol.toLowerCase()))continue;const Z=`${ze}:${qt.address.toLowerCase()}`;Ee.has(Z)||(Ee.add(Z),Fe.push(j.getAddress(qt.address)))}}return Fe},[D?.allowedTokens,H,O]),N=M?v.cardBg:C?.assetSelector?.backgroundColor||C?.secondaryBackground||"#e9e9e9",K=M?`1px solid ${v.cardBorder}`:"0.5px solid #A8A8A7",L=M?"12px":"6px",V=M?v.textPrimary:"#111827",P=M?v.textSecondary:"#6b7280",G=c.useMemo(()=>({...C,assetSelector:{...C?.assetSelector,backgroundColor:M?v.cardBg:C?.assetSelector?.backgroundColor,borderRadius:M?"12px":C?.assetSelector?.borderRadius},secondaryBackground:M?v.cardBg:C?.secondaryBackground}),[C,M]),me=c.useMemo(()=>M?{...A,colors:{...A.colors,secondary:v.cardBg,surfaceHover:v.hoverBg,border:v.cardBorder,borderHover:v.inputBorder}}:A,[M,A]),[W,te]=c.useState(null),[ue,Ce]=c.useState(0),je=u?.selectedDurationIdx??ue,pe=u?.setSelectedDurationIdx??Ce,[ye,z]=c.useState(!1),[se,Y]=c.useState(null),[ae,ge]=c.useState(null),[be,ne]=c.useState(!1),[Q,re]=c.useState(!1),[we,Me]=c.useState(null),[at,Xe]=c.useState(!1),le=c.useRef(0),[xe,fe]=c.useState(!1),[Le,oe]=c.useState(null);It.useWalletClient(),It.useSwitchChain();const{chain:Te,address:mt}=It.useAccount();It.useConfig();const Bt=c.useRef(Te);c.useEffect(()=>{Bt.current=Te},[Te]);const ot=f.useWallet(),{isReady:Lt,isAuthenticated:Tt,isConnected:gt,address:Se,provider:Mt,actions:Jt}=ot,{externalWallet:$t,embeddedAddress:Ct,externalAddress:Ot}=f.useProviderWallets(),{intentStatus:Je,startStatusPolling:wt,clearStatus:qe}=lo({checkStepStatus:(X,ce)=>f.relayerService.checkStepStatus(X,ce),retryStep:async(X,ce)=>{const[Fe,Ee]=X.split("/"),ze=parseInt(Ee||"0",10);await f.relayerService.executeStep(Fe,ze,ce,{action:"execute"})},maxRetries:3}),{assets:_e,refetch:et}=Pn({address:Se,supportedChains:H,enabled:e&&gt&&!U&&!O,refetchInterval:3e4}),pt=c.useMemo(()=>{if(O)return[];if(q.length===0)return _e;const X=new Set(q.map(ce=>ce.toLowerCase()));return _e.filter(ce=>X.has(ce.address.toLowerCase()))},[_e,q,O]),At=f.useEmbeddedWalletAddress(),he=Ot||mt,rt=U?he:At,it=c.useMemo(()=>{if(!x)return[];if(O)return m?[j.getAddress(m)]:[];const X=new Set,ce=[],Fe=Ee=>{if(!Ee)return;const ze=Ee.toLowerCase();X.has(ze)||(X.add(ze),ce.push(j.getAddress(Ee)))};if(m&&Fe(m),U)for(const Ee of q)Fe(Ee);return ce},[x,U,m,q,O]),kt=c.useMemo(()=>it.map(X=>X.toLowerCase()).sort().join(","),[it]),ke=c.useMemo(()=>JSON.stringify([...H||[]].sort()),[H]),[Rt,tt]=c.useState([]),ft=c.useRef(0),vt=c.useRef(async()=>{}),Kt=c.useCallback(async()=>{if(!x||!rt||it.length===0){ft.current++,tt([]);return}const X=++ft.current,ce=j.getAddress(rt),Fe=H&&H.length>0?H:[l],Ee=it.map($=>{const ie=$.toLowerCase();if(m&&f.addressesEqual($,m)){const J=f.getChainConfig(l)?.supportedTokens?.find(Ae=>f.addressesEqual(Ae.address,ie));return{address:$,chainId:l,configToken:J?{decimals:J.decimals,symbol:J.symbol,name:J.name,logo:J.logo}:void 0}}for(const J of Fe){const Ae=f.getChainConfig(J)?.supportedTokens?.find(Ne=>f.addressesEqual(Ne.address,ie));if(Ae)return{address:$,chainId:J,configToken:{decimals:Ae.decimals,symbol:Ae.symbol,name:Ae.name,logo:Ae.logo}}}return{address:$,chainId:l}}),ze=new Map;for(const $ of Ee){const ie=ze.get($.chainId)||[];ie.push($),ze.set($.chainId,ie)}const ut=async($,ie)=>{try{const J=await Ft.readContract($,{address:ie.address,abi:f.U,functionName:"balanceOf",args:[ce]});let Ae,Ne,st,Ze;if(ie.configToken)Ae=ie.configToken.decimals,Ne=ie.configToken.symbol,st=ie.configToken.name,Ze=ie.configToken.logo;else{const[xt,Nt,Ut]=await Promise.all([Ft.readContract($,{address:ie.address,abi:f.U,functionName:"decimals",args:[]}).catch(()=>18),Ft.readContract($,{address:ie.address,abi:f.U,functionName:"symbol",args:[]}).catch(()=>"TOKEN"),Ft.readContract($,{address:ie.address,abi:f.U,functionName:"name",args:[]}).catch(()=>"TOKEN")]);Ae=Number(xt),Ne=Nt,st=Ut}const lt=!!m&&f.addressesEqual(ie.address,m)&&ie.chainId===l;lt&&a&&(Ze=a),lt&&r&&!ie.configToken&&(Ne==="TOKEN"&&(Ne=r),st==="TOKEN"&&(st=r));const jt=parseFloat((Number(J)/Math.pow(10,Ae)).toFixed(6));return{address:ie.address,name:st,symbol:Ne,decimals:Ae,balance:J,balanceFormatted:jt,balanceUsd:0,logoURI:Ze,isNative:!1,chainId:ie.chainId}}catch{return null}},qt=await Promise.all(Array.from(ze.entries()).map(async([$,ie])=>{let J;try{J=f.getClientForChain($)}catch{return[]}const Ae=[],Ne=[];for(const Ze of ie){const lt=Ae.length;Ae.push({address:Ze.address,abi:f.U,functionName:"balanceOf",args:[ce]}),Ze.configToken||Ae.push({address:Ze.address,abi:f.U,functionName:"decimals",args:[]},{address:Ze.address,abi:f.U,functionName:"symbol",args:[]},{address:Ze.address,abi:f.U,functionName:"name",args:[]}),Ne.push({start:lt,item:Ze})}let st=null;try{st=await J.multicall({contracts:Ae})}catch{st=null}return st?Ne.map(({start:Ze,item:lt})=>{const jt=st[Ze],xt=jt?.status==="success"?jt.result:0n;let Nt,Ut,_t,pn;if(lt.configToken)Nt=lt.configToken.decimals,Ut=lt.configToken.symbol,_t=lt.configToken.name,pn=lt.configToken.logo;else{const de=st[Ze+1],Be=st[Ze+2],yt=st[Ze+3];Nt=de?.status==="success"?Number(de.result):18,Ut=Be?.status==="success"?Be.result:"TOKEN",_t=yt?.status==="success"?yt.result:Ut}const fn=!!m&&f.addressesEqual(lt.address,m)&&lt.chainId===l;fn&&a&&(pn=a),fn&&r&&!lt.configToken&&(Ut==="TOKEN"&&(Ut=r),_t==="TOKEN"&&(_t=r));const ve=parseFloat((Number(xt)/Math.pow(10,Nt)).toFixed(6));return{address:lt.address,name:_t,symbol:Ut,decimals:Nt,balance:xt,balanceFormatted:ve,balanceUsd:0,logoURI:pn,isNative:!1,chainId:lt.chainId}}):(await Promise.all(ie.map(Ze=>ut(J,Ze)))).filter(Ze=>Ze!==null)}));if(X!==ft.current)return;const Z=qt.flat();tt(Z)},[x,rt,kt,ke,l,m,a,r]);c.useEffect(()=>{vt.current=Kt},[Kt]),c.useEffect(()=>{if(!e||!x){tt([]);return}vt.current();const X=setInterval(()=>{vt.current()},15e3);return()=>clearInterval(X)},[x,e,rt,kt,ke,l,m]);const Ht=c.useCallback(()=>{Kt()},[Kt]),$e=c.useMemo(()=>Rt.filter(X=>X.balance>0n),[Rt]),Zt=c.useMemo(()=>{if(U)return $e.map(ce=>({...ce,_source:"wallet"}));if(!x)return pt;const X=[];for(const ce of $e)X.push({...ce,_source:"wallet"});for(const ce of pt)X.push({...ce,_source:"spice"});return X},[U,x,$e,pt]),Re=c.useMemo(()=>O?m?Zt.filter(X=>f.addressesEqual(X.address,m)&&X.chainId===l):[]:Zt,[Zt,O,m,l]),dt=c.useRef(null),St=c.useRef(null);c.useEffect(()=>{St.current=W},[W]),c.useEffect(()=>{!O||!W?.asset||m&&f.addressesEqual(W.asset.address,m)&&W.asset.chainId===l||te(null)},[O,W?.asset,m,l]),c.useEffect(()=>{e||(te(null),Y(null),ge(null),ne(!1),re(!1),Me(null),z(!1),fe(!1),oe(null),Xe(!1),qe())},[e,qe]),c.useEffect(()=>{i&&i.assetAmount!==(W?.amount||"")&&te(X=>X&&{...X,amount:i.assetAmount})},[i?.assetAmount]),c.useEffect(()=>{d&&d.assetAmount!==(W?.amount||"")&&te(X=>X&&{...X,amount:d.assetAmount})},[d?.assetAmount]),c.useEffect(()=>{if(!U&&Je?.overallStatus==="success"&&Je.intentId&&dt.current!==Je.intentId&&Se&&Je.steps.find(X=>X.transactionHash)?.transactionHash){dt.current=Je.intentId;const X=St.current;if(!X?.asset||!X.amount||X.asset._source==="wallet"||j.parseUnits(X.amount,X.asset.decimals)===0n)return;et()}},[Je,Se,l,et,U]);const Oe=parseFloat(W?.amount||"")||0,Ge=c.useMemo(()=>W?.asset?W.asset._source==="wallet"?W.asset.balanceFormatted??0:pt.find(X=>f.addressesEqual(X.address,W.asset.address)&&X.chainId===W.asset.chainId)?.balanceFormatted??0:0,[W?.asset,pt]),Et=Oe>0&&(we?parseFloat(j.formatUnits(we.grossAmount,we.decimals))>Ge:Oe>Ge),ct=u?.selectedDuration??h[je]??h[0],De=c.useMemo(()=>!W?.asset||!m?!1:f.addressesEqual(W.asset.address,m)&&W.asset.chainId===l,[W?.asset,m,l]),He=c.useMemo(()=>Oe<=0?0:De?Oe:!S||S<=0?0:Oe/S,[Oe,S,De]),ht=c.useMemo(()=>He<=0?null:He.toLocaleString(void 0,{maximumFractionDigits:2}),[He]),nt=p&&He>0&&ct?p(He,ct.months):void 0,Qt=c.useMemo(()=>Oe<=0?"$0.00":De&&S?(Oe*S).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!S||S<=0?"$0.00":Oe.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[Oe,S,De]),Ue=c.useMemo(()=>{if(!ht)return null;const X=parseFloat(ht.replace(/,/g,""));return De&&S?(X*S).toLocaleString(void 0,{maximumFractionDigits:2}):S?(X*S).toLocaleString(void 0,{maximumFractionDigits:2}):null},[ht,S,De]),Gt=c.useCallback(X=>{te(ce=>({asset:X,amount:ce?.asset?.address===X.address&&ce?.asset?.chainId===X.chainId&&ce.amount||""})),Y(null),ge(null),re(!1),Me(null),d?.setSelectedAsset&&d.setSelectedAsset({symbol:X.symbol,address:X.address,decimals:X.decimals,chainId:X.chainId})},[d?.setSelectedAsset]),Vt=c.useCallback(X=>{te(ce=>ce&&{...ce,amount:X}),Y(null),ge(null),re(!1),Me(null),i&&i.setAssetAmount(X),d&&d.setAssetAmount(X)},[i,d]),Dt=c.useCallback(X=>{if(typeof o=="function"){if(!W?.asset||!W.amount)throw new Error("Select an asset and enter an amount");return o({asset:W.asset,amount:X?.amount??W.amount,amountWei:X?.amountWei??j.parseUnits(W.amount,W.asset.decimals),grossAmount:X?.grossAmount,grossAmountWei:X?.grossAmountWei,feeAdjusted:!!X})}return o},[o,W]),_=c.useRef(null),ee=c.useMemo(()=>!W?.asset||Oe<=0?!1:U?!De&&!w:!0,[W,Oe,U,De,w]),Ie=c.useCallback(()=>Zi(_.current),[]);c.useEffect(()=>{if(!e||ye)return;if(!W?.asset||Oe<=0){ge(null),ne(!1),re(!1),Me(null);return}if(!ee){ge(null),ne(!1),re(!0),Me(null);return}let X=!1;const ce=async()=>{const ze=++le.current;ge(null),re(!1),ne(!0);try{const ut=await Ie();if(X||le.current!==ze)return;ge(null),re(!0),Me(ut)}catch(ut){if(X||le.current!==ze)return;ge(f.sanitizeError(ut,"Unable to calculate fees for this lock.")),re(!1)}finally{!X&&le.current===ze&&ne(!1)}},Fe=window.setTimeout(()=>{ce()},250),Ee=window.setInterval(()=>{ce()},1e4);return()=>{X=!0,clearTimeout(Fe),window.clearInterval(Ee),ne(!1),re(!1)}},[e,ye,W,Oe,ee,Ie]),c.useEffect(()=>{if(Je?.overallStatus==="success"){const X=Je.steps.find(ce=>ce.transactionHash);y?.(X?.transactionHash)}},[Je?.overallStatus,y]);const Qe=x&&W?.asset?._source==="wallet"&&W?.asset?.chainId===l,Ye=c.useCallback(()=>Yi(_.current),[]),Ke=!!W?.asset&&Oe>0&&!Et&&!ye&&(!ee||Q&&!be&&!ae),Ve=se||ae,We=n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[n.jsx(Ss,{color:P}),n.jsxs("p",{style:{fontSize:"13px",color:P,margin:0,lineHeight:"1.5"},children:["Add ",r," by converting assets from your account"]})]});if(_.current={selectedAsset:W,parsedAmount:Oe,selectedDuration:ct,isInsufficientBalance:Et,isSemi7702:U,isSourceDestToken:De,isDirectDeposit:Qe,requiresRelayerFeeEstimate:ee,address:Se,embeddedWalletAddress:At,providerEmbeddedAddress:Ct,externalWallet:$t,externalWalletAddress:he,isConnected:gt,ready:Lt,authenticated:Tt,provider:Mt,actions:Jt,lockChainId:l,escrowAddress:g,onLockExecute:w,onLockSuccess:y,buildSpicenetBatch:I,resolveLockBatches:Dt,startStatusPolling:wt,refreshSpiceAssets:et,refreshWalletAssets:Ht,ui:{setError:Y,setIsExecuting:z,setShowStatusPanel:Xe}},!e)return null;const Pe={backgroundColor:N,border:K,borderRadius:L,padding:"16px",marginBottom:"16px"};return n.jsx(sn,{isOpen:e,onClose:t,title:`Add ${r} to your account`,subtitle:We,styles:C,dark:M,footerLinkText:"Spicenet accounts \u2192",overlayContent:xe?n.jsx("div",{}):void 0,closeOnBackdropClick:s,children:n.jsxs("div",{style:{padding:"0 24px 8px 24px",position:"relative"},children:[n.jsxs("div",{style:{marginBottom:"12px"},children:[k&&n.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:n.jsx(Is,{onClick:k,color:T,fontFamily:B})}),n.jsx("div",{style:{marginTop:"10px",fontSize:"13px",color:P,fontFamily:B},children:n.jsx(Un,{assets:Re,selectedAsset:W??void 0,onAssetSelect:Gt,onAmountChange:Vt,label:"Amount",showBalance:!0,showMaxButton:!0,theme:me,styles:G})}),n.jsx("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:P,fontFamily:B},children:Qt})]}),n.jsxs("div",{style:Pe,children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:M?`1px solid ${v.cardBorder}`:"1px solid #e5e7eb"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[a?n.jsx("img",{src:a,alt:r,style:{width:"32px",height:"32px",borderRadius:"50%",objectFit:"cover"}}):n.jsx("div",{style:{width:"32px",height:"32px",borderRadius:"50%",backgroundColor:M?v.inputBg:"#d1d5db",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:700,color:V},children:r.slice(0,2)}),n.jsx("span",{style:{fontSize:"16px",fontWeight:600,color:V,fontFamily:B},children:r})]}),n.jsxs("div",{style:{textAlign:"right"},children:[n.jsx("div",{style:{fontSize:"22px",fontWeight:700,color:V,fontFamily:B,lineHeight:1.1},children:ht??"0.00"}),n.jsxs("div",{style:{fontSize:"12px",color:P,fontFamily:B,marginTop:"2px"},children:["~$",Ue??"0.00"]})]})]}),n.jsxs("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:M?`1px solid ${v.cardBorder}`:"1px solid #e5e7eb"},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[n.jsx("span",{style:{fontSize:"15px",fontWeight:500,color:P,fontFamily:B},children:"Lock Duration"}),n.jsx(on,{color:P})]}),n.jsx(Di,{options:h,selectedIndex:je,onSelect:pe,primaryColor:T,dark:M,textPrimary:V,textSecondary:P})]}),n.jsxs("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[n.jsx(Ui,{durationMonths:ct?.months,fontFamily:B,dark:M,textPrimary:V,textSecondary:P}),p&&n.jsx(Wi,{votes:nt,fontFamily:B,dark:M,textPrimary:V,textSecondary:P})]})]}),ee&&n.jsx(qn,{fontFamily:B,textPrimary:V,textSecondary:P,cardBg:N,cardBorder:K,resolvedDark:M,darkCardBorder:v.cardBorder,primaryColor:T,feePreview:we,isLoading:be,errorText:ae}),Ve&&n.jsx(In,{variant:"error",palette:v,fontFamily:B,style:{marginBottom:"12px"},children:Ve}),n.jsx(f.Button,{variant:"outline",fullWidth:!0,onClick:Ye,disabled:!Ke,loading:ye,dark:M,styles:{...C,button:{...C?.button,backgroundColor:T}},children:ye?Qe&&!De?"DEPOSITING...":De?"LOCKING...":"CONVERTING...":be&&ee?"CALCULATING FEES...":Qe&&!De?`DEPOSIT ${r}`:De?`LOCK ${r}`:`CONVERT TO ${r}`}),n.jsx(Pi,{isOpen:xe,data:Le,isLocking:ye,lockError:Ve,onContinue:Ye,onClose:()=>fe(!1),primaryColor:T,fontFamily:B,dark:M}),Je&&at&&n.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:M?"rgba(0, 0, 0, 0.45)":"rgba(255, 255, 255, 0.55)",backdropFilter:"blur(2px)",WebkitBackdropFilter:"blur(2px)",borderRadius:L},children:n.jsx(Bs,{type:"deposit",showStepBreakdown:!1,isOpen:!!Je&&Je.overallStatus!=="processing",isProcessing:ye||Je?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{qe(),Xe(!1),Ye()},onNewTx:()=>{qe(),Xe(!1),te(null),dt.current=null,et(),Ht()},onClose:()=>{qe(),Xe(!1)},onComplete:()=>{qe(),Xe(!1),te(null),dt.current=null,et(),Ht()},results:Je?.overallStatus==="success"||Je?.overallStatus==="failed"?Je.steps.map(X=>({asset:{symbol:W?.asset?.symbol||r,address:W?.asset?.address||""},txHash:X.transactionHash||"",success:X.status==="success",amount:W?.amount})):void 0,chainName:f.getChainName(l),explorerUrl:f.getExplorerUrl(l,"").replace(/\/tx\/.*$/,"")||void 0,theme:A,styles:C,dark:M})})]})})},Xi="0xa9059cbb";function Ji(e,t,s){return F.isNativeToken(e)?{to:s,value:t,data:"0x"}:{to:e,value:0n,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"transfer",args:[s,t]})}}function qs(e,t,s,o){return t!=="user-transfer"||!s||e.length===0||e[0]?.to.toLowerCase()!==o.toLowerCase()||!e[0]?.data.startsWith(Xi)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function ss(e,t,s){if(!t)return[e];const o=await t(s);return o?[o,e]:[e]}function yn(e){return e.filter(t=>t.domain!=="spicenet")}function os(e){const t=(e.tokenTransfers??[]).filter(s=>s.from==="escrow").map(s=>({token:F.normalizeNativeTokenAddress(s.token),recipient:s.to,amount:BigInt(s.amount)})).filter(s=>s.amount>0n);return t.length>0?t:void 0}function jn(e,t,s){if(t===s)return e;if(t<s)return e*10n**BigInt(s-t);const o=10n**BigInt(t-s);return(e+o-1n)/o}async function $i(e,t){const{currentPaymentAmount:s,destinationToken:o,embeddedWalletAddress:r,providerEmbeddedAddress:a,address:i,isNon7702:d,isPayMode:u,resolvedChainId:l,buildActionCalls:h,feeExecutionMode:p,buildSpicenetBatch:g,selectedAsset:x,needsSwap:m,exactOutputSwap:y,resolvedTokenIn:w}=e,S=j.parseUnits(s,o.decimals),b=t?.actionAmountOverride??S,k=r||a||(d?void 0:i);if(!k)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const I={userAddress:k,chainId:l,destinationToken:o.address,grossAmount:t?.fundingAmountOverride??S,netAmount:b,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:p,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},C=h(b,I),E={chainId:l,calls:C},A=(!u&&!d?!0:x?.asset?._source==="spice")||d,M=(T,v)=>({token:T,from:d?"solver":"escrow",to:k,amount:v});if(S===0n)return[E];if(m&&y){const T=w??tn(x.asset,l)??x.asset.address,v=t?.fundingAmountOverride??y.amountInMax,B=A?[M(T,v)]:[],D={to:T,value:0n,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"approve",args:[y.calls[0]?.to,y.amountInMax]})},R={chainId:l,calls:[D,...y.calls,...C],tokenTransfers:[...B,...E.tokenTransfers??[]]};return A?ss(R,g,{userAddress:k,destinationChainId:l,deliveryToken:T,deliveryAmount:v,deliveryRecipient:k,deliveryTransfers:os(R),sourceAsset:x.asset}):[R]}if(A){const T=w??tn(x.asset,l)??o.address,v=t?.fundingAmountOverride??S,B={...E,tokenTransfers:[M(T,v),...E.tokenTransfers??[]]};return ss(B,g,{userAddress:k,destinationChainId:l,deliveryToken:T,deliveryAmount:v,deliveryRecipient:k,deliveryTransfers:os(B),sourceAsset:x.asset})}return[E]}async function _i(e,t){const{selectedAsset:s,embeddedWalletAddress:o,externalWalletAddress:r,resolvedChainId:a,destinationToken:i,buildActionCalls:d,feeExecutionMode:u,buildSpicenetBatch:l,isPayMode:h,isNon7702:p,needsSwap:g,resolvedSwap:x,quoteAmountOut:m,resolvedTokenIn:y}=e,w=x?.amountOutMinimum??m;if(!s?.asset||!o)return[];const S=p?r:o;if(!S)return[];const b=t?.fundingAmountOverride??t?.actionAmountOverride??j.parseUnits(s.amount,s.asset.decimals),k=t?.fundingAmountOverride??b,I=t?.sourceFundingAmountOverride??b,C=t?.deliveryAmountOverride??k,E=t?.withdrawalAmountOverride??C,A=t?.actionAmountOverride??b,M={userAddress:S,chainId:a,destinationToken:i.address,feeToken:u==="user-transfer"&&g&&y?y:i.address,grossAmount:k,netAmount:A,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:u,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},T=d(A,M),v=s.asset?._source==="wallet";if(!h&&p&&v&&s.asset.chainId===a){if(g){if(!y)throw new Error("Swap input token could not be resolved");if(!x||w===null)throw new Error("Swap quote not available yet")}if(g&&x&&w){const K=d(t?.actionAmountOverride??w,{...M,netAmount:t?.actionAmountOverride??w}),{feeCall:L,remainingCalls:V}=qs(K,u,g,M.feeToken);return[{chainId:a,calls:[...L?[L]:[],...x.calls,...V]}]}return[{chainId:a,calls:T}]}if(!h&&!p&&v){if(s.asset.chainId===a){if(g){if(!y)throw new Error("Swap input token could not be resolved");if(!x||w===null)throw new Error("Swap quote not available yet")}if(g&&x&&w){const K=d(t?.actionAmountOverride??w,{...M,netAmount:t?.actionAmountOverride??w}),{feeCall:L,remainingCalls:V}=qs(K,u,g,M.feeToken);return[{chainId:a,calls:[...L?[L]:[],...x.calls,...V]}]}return[{chainId:a,calls:T}]}throw new Error("Cross-chain wallet supplies require external wallet mode")}const B=!h&&!p?s.asset?._source!=="wallet":s.asset?._source==="spice",D=p&&v;if(!(B||D))return[{chainId:a,calls:T}];const R=D&&s.asset.chainId!==a?{chainId:s.asset.chainId,calls:[Ji(F.normalizeNativeTokenAddress(s.asset.address),I,F.getEscrowContractAddress(s.asset.chainId))]}:null,O=(K,L)=>({token:K,from:D?"solver":"escrow",to:o,amount:L}),U=(K,L)=>D?[{token:K,from:"escrow",to:F.SPICE_SOLVER_ADDRESS,amount:L}]:[];if(g){if(!y)throw new Error("Swap input token could not be resolved");if(!x||w===null)throw new Error("Swap quote not available yet")}if(g&&x&&w&&y){const K=d(t?.actionAmountOverride??w,{...M,netAmount:t?.actionAmountOverride??w}),{feeCall:L,remainingCalls:V}=qs(K,u,g,M.feeToken),P={chainId:a,calls:[...L?[L]:[],...x.calls,...V],tokenTransfers:[...U(y,E),O(y,C)]},G=await ss(P,l,{userAddress:o,destinationChainId:a,deliveryToken:y,deliveryAmount:C,withdrawalAmount:E,deliveryRecipient:o,deliveryTransfers:os(P),sourceAsset:s.asset});return R?[R,...G]:G}const H=y??tn(s.asset,a)??i.address,q={chainId:a,calls:T,tokenTransfers:[...U(H,E),O(H,C)]},N=await ss(q,l,{userAddress:o,destinationChainId:a,deliveryToken:H,deliveryAmount:C,withdrawalAmount:E,deliveryRecipient:o,deliveryTransfers:os(q),sourceAsset:s.asset});return R?[R,...N]:N}async function el(e,t,s,o,r){let a=e;for(let i=0;i<4;i++){const d=await t(a),u=await o(d,s,a,r),l=li(u);if(l===null||l>=e)return a;const h=a-l,p=e+h;if(p<=a)return a;a=p}return a}function tl(e,t,s,o){if(e<=0n)return 0n;const r=e-t;if(r<=0n)return 0n;const a=o+s;return a<=0n?r:r*o/a}function nl(e,t){const s=j.formatUnits(e,t);return s.includes(".")?s.replace(/\.?0+$/,"")||"0":s}async function sl(e){const{asset:t,isPayMode:s,isNon7702:o,needsSwap:r,isQuoting:a,embeddedWalletAddress:i,buildSupplyChainBatches:d,estimateGasless:u,executionTokenAddress:l,feeExecutionMode:h}=e;if(s||o||r||a||!i||t.balance<=0n)return null;const p=i,g=await d({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(g.length===0)return null;const x=g.some(k=>k.tokenTransfers?.length),m=await u(g,l,t.balance,x?{userOverride:p,useCustomTransfers:!0,feeExecutionMode:h}:h?{userOverride:p,feeExecutionMode:h}:{userOverride:p}),y=cn(m,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),w=y?jn(y.gasFee,y.decimals,t.decimals):0n,S=y?jn(y.spicenetFee,y.decimals,t.decimals):0n,b=tl(t.balance,w,S,t.balance);return b>0n?nl(b,t.decimals):null}async function ol(e){const{selectedAsset:t,isPayMode:s,parsedAmount:o,needsSwap:r,exactOutputSwap:a,isNon7702:i,isSourceDestToken:d,currentPaymentAmount:u,destinationToken:l,feeExecutionMode:h,resolvedTokenIn:p,embeddedWalletAddress:g,providerEmbeddedAddress:x,resolvedChainId:m,isConnected:y,address:w,ready:S,authenticated:b,isDirect:k,resolvedSwap:I,isQuoting:C,executionTokenAddress:E,buildPayChainBatches:A,buildSupplyChainBatches:M,estimateGasless:T,estimateRequiredGrossFunding:v}=e;if(!t?.asset)return null;if(s){if(o<=0||r&&!a||i&&d)return null;const N=j.parseUnits(u,l.decimals),K=p||tn(t.asset,m)||t.asset.address||l.address,L={chainId:m,tokenAddress:K,symbol:F.getTokenByAddress(K,m)?.symbol??t.asset.symbol,decimals:F.getTokenByAddress(K,m)?.decimals??t.asset.decimals};if(i){const te=g||x;if(!te)return null;const ue=te,Ce=r?a?.amountInMax??0n:N;if(Ce===0n)return null;const je=await v(Ce,z=>A({fundingAmountOverride:z}).then(se=>zt(yn(se),ue)),K,{userOverride:te,useCustomTransfers:!0}),pe=zt(yn(await A({fundingAmountOverride:je})),ue),ye=await T(pe,K,je,{userOverride:te,useCustomTransfers:!0,feeExecutionMode:h});return cn(ye,L)}if(!y||!w||!S||!b)return null;const V=g||x||w,P=r?a?.amountInMax??0n:N;if(P===0n)return null;const G=await v(P,te=>A({fundingAmountOverride:te}).then(ue=>zt(yn(ue),V)),K,{useCustomTransfers:!0});let me=zt(yn(await A({fundingAmountOverride:G})),V);const W=await T(me,K,G,{useCustomTransfers:!0,feeExecutionMode:h});return cn(W,L)}if(o<=0||!g)return null;const B=g||x;if(!(!s&&!i&&t.asset?._source==="wallet"&&t.asset.chainId!==m)&&!k&&!I&&!C||C)return null;const D=j.parseUnits(t.amount,t.asset.decimals),R=await M();if(R.length===0)return null;const O=i&&t.asset?._source==="wallet"&&t.asset.chainId===m,U={chainId:m,tokenAddress:E,symbol:F.getTokenByAddress(E,m)?.symbol??l.symbol,decimals:F.getTokenByAddress(E,m)?.decimals??l.decimals};if(O){const N=await f.relayerService.estimateBatchGas({user:B,outputToken:E,stepIndex:0,chainBatches:R}),K=$n(D,10n),L=K+N.gasFee;return{...U,grossAmount:D+L,netAmount:D,totalFee:L,gasFee:N.gasFee,spicenetFee:K,bridgeFee:0n,gasQuoteSource:N.gasQuoteSource}}const H=R.some(N=>N.tokenTransfers?.length),q=await T(R,E,D,H?{userOverride:B,useCustomTransfers:!0,feeExecutionMode:h}:h?{userOverride:B,feeExecutionMode:h}:{userOverride:B});return cn(q,U)}const rl=10n;function er(e,t){const s=e.selectedAsset?.asset;if(!s||s?._source!=="wallet")return;const o=tn(s,e.resolvedChainId);if(!o||!f.addressesEqual(o,e.executionTokenAddress))return;const r=F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),a=jn(t,r?.decimals??e.destinationToken.decimals,s.decimals);if(a<=s.balance)return;const i=j.formatUnits(a,s.decimals),d=j.formatUnits(s.balance,s.decimals);throw new Error(`Insufficient ${s.symbol} for amount plus fees. Required ${i} ${s.symbol}; available ${d} ${s.symbol}.`)}function tr(e){const t=F.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 nr(e,t,s){const o=cn(e,tr(t));if(!o)return;const r=$n(s,rl),a=o.bridgeFee??0n,i=r+o.gasFee+a;return{grossAmount:s+i,netAmount:s,combinedFeeAmount:i,feeExecutionMode:"user-transfer",feeBreakdown:{spicenetFee:r,gasFee:o.gasFee,bridgeFee:a}}}function Fn(e,t,s){if(e===t)return!0;const o=e>t?e:t;return o===0n?!1:(e>t?e-t:t-e)*10000n<=o*s}function sr(e,t,s){let o=0n,r=0n;const a=s.toLowerCase();for(const i of e)if(i.chainId===t){for(const d of i.calls??[])if(d.to.toLowerCase()===a)try{const u=j.decodeFunctionData({abi:j.erc20Abi,data:d.data});if(u.functionName!=="transfer")continue;const l=u.args[0].toLowerCase(),h=u.args[1];l===F.SPICE_PLATFORM_FEE_RECIPIENT.toLowerCase()?o+=h:l===F.SPICE_GAS_FEE_RECIPIENT.toLowerCase()&&(r+=h)}catch{continue}}return{spicenetFee:o,gasFee:r}}function al(e,t,s){const o=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,r=sr(e,t.resolvedChainId,o);return r.spicenetFee===0n&&s.feeBreakdown.spicenetFee>0n||r.gasFee===0n&&s.feeBreakdown.gasFee>0n?!1:Fn(r.spicenetFee,s.feeBreakdown.spicenetFee,100n)&&Fn(r.gasFee,s.feeBreakdown.gasFee,100n)}function il(e,t){return e?Fn(e.grossAmount,t.grossAmount,100n)&&Fn(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&Fn(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&Fn(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}async function ll(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){if(!e.externalWalletAddress){e.ui.setError("Please connect your external 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 or(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 cl(e,s.signal)}e.ui.setStep("success"),e.ui.setStatusMsg(e.isSourceDestToken?"Transaction confirmed":"Deposit confirmed")}catch(s){const o=s instanceof Error?s:new Error(String(s));if(o.name==="AbortError"||e.refs.abortControllerRef.current?.signal.aborted){e.ui.setStep("idle");return}const r=o.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(r),e.ui.setError(r),e.onError?.(o)}finally{e.ui.setIsExecuting(!1)}return}if(!e.embeddedWalletAddress){e.ui.setError("Wallet not ready");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.ui.setTxHash(null),e.refs.spiceDepositSubmittedRef.current=!1;const t=new AbortController;e.refs.abortControllerRef.current=t;try{const s=j.parseUnits(e.selectedAsset.amount,e.selectedAsset.asset.decimals),o=s;let r=await e.gasless.buildSupplyChainBatches();const a=e.selectedAsset.asset?._source==="wallet",i=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!a&&!r.some(x=>F.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=s;const l=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,h=e.feeExecutionMode==="user-transfer"&&!l?o:void 0;let p;for(let x=0;x<4;x+=1){const m=await e.gasless.estimateGasless(r,e.executionTokenAddress,u,d),y=cn(m,tr(e));p=e.feeExecutionMode==="user-transfer"&&y?nr(m,e,o):void 0;const w=p?.grossAmount??y?.grossAmount??u;if(w===u){u=w;break}u=w,r=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:h,actionContextOverride:p})}e.feeExecutionMode==="user-transfer"&&(er(e,u),r=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:h,actionContextOverride:p}));let g=p;await e.gasless.executeGasless(r,e.executionTokenAddress,u,e.gasless.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...d,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:x,chainBatches:m})=>{const y=nr(x,e,o);if(!y)return null;const w=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&e.resolvedTokenIn?e.resolvedTokenIn:e.executionTokenAddress;sr(m,e.resolvedChainId,w);const S=il(g,y),b=al(m,e,y);return S||b?null:(g=y,e.gasless.buildSupplyChainBatches({fundingAmountOverride:y.grossAmount,actionAmountOverride:h,actionContextOverride:y}))}}:d),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(s){const o=s instanceof Error?s:new Error(String(s));if(o.name==="AbortError"||t.signal.aborted){e.ui.setStep("idle");return}const r=o.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(r),e.ui.setError(r),e.onError?.(o)}finally{e.ui.setIsExecuting(!1)}}async function cl(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 s=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!s)throw new Error("Embedded wallet not available \u2014 sign in to create one before supplying");const o=e.selectedAsset.asset,r=j.parseUnits(e.selectedAsset.amount,o.decimals),a=r,i=o?._source==="wallet"&&o.chainId===e.resolvedChainId;let d=await e.gasless.buildSupplyChainBatches();const u={userOverride:s,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode};let l=r;const h=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,p=e.feeExecutionMode==="user-transfer"&&!h?a:void 0;let g;if(i){const M=await f.relayerService.estimateBatchGas({user:s,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:d}),T=$n(r,10n),v=T+M.gasFee;l=r+v,e.feeExecutionMode==="user-transfer"&&(g={grossAmount:l,netAmount:a,combinedFeeAmount:v,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:T,gasFee:M.gasFee,bridgeFee:0n}})}else{const M=await e.gasless.estimateGasless(d,e.executionTokenAddress,0n,u),T=cn(M,{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId)?.symbol??e.destinationToken.symbol,decimals:F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId)?.decimals??e.destinationToken.decimals});T&&(l=T.grossAmount>r?T.grossAmount:r,e.feeExecutionMode==="user-transfer"&&(g={grossAmount:l,netAmount:a,combinedFeeAmount:T.totalFee,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:T.spicenetFee,gasFee:T.gasFee,bridgeFee:T.bridgeFee??0n}}))}const x=F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),m=i?l:jn(l,x?.decimals??e.destinationToken.decimals,o.decimals);er(e,l),d=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:l,sourceFundingAmountOverride:m,withdrawalAmountOverride:l,actionAmountOverride:p,actionContextOverride:g});const y=o.chainId,w=s,S=await e.externalWallet.getEthereumProvider();let b=null;try{const M=await S.request({method:"eth_chainId"});b=parseInt(M,16)}catch{b=null}b!==y&&(e.ui.setStatusMsg("Switching source network..."),await f.ensureWalletOnChain(S,y));const k=f.getChainConfig(y),I=j.createWalletClient({account:e.externalWalletAddress,chain:k?.viemChain,transport:j.custom(S)}),C=F.normalizeNativeTokenAddress(o.address),E=o.isNative||F.isNativeToken(C);e.ui.setStatusMsg("Funding embedded wallet...");const A=E?await I.sendTransaction({to:w,value:m,chain:k?.viemChain}):await I.sendTransaction({to:C,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"transfer",args:[w,m]}),chain:k?.viemChain});if((await f.getClientForChain(y).waitForTransactionReceipt({hash:A,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Embedded wallet funding failed");e.ui.setStatusMsg("Signing supply intent..."),await e.gasless.executeGasless(d,e.executionTokenAddress,0n,e.gasless.onProgress,t,u)}async function or(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=j.parseUnits(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),s={userAddress:e.externalWalletAddress,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},o=e.buildActionCalls(t,s);if(o.length===0)throw new Error("No action calls configured");const r=await e.externalWallet.getEthereumProvider();let a=null;try{const h=await r.request({method:"eth_chainId"});a=parseInt(h,16)}catch{a=null}a!==e.resolvedChainId&&await f.ensureWalletOnChain(r,e.resolvedChainId);const i=f.getChainConfig(e.resolvedChainId),d=j.createWalletClient({account:e.externalWalletAddress,chain:i?.viemChain,transport:j.custom(r)}),u=f.getClientForChain(e.resolvedChainId);let l;for(const h of o){const p=await d.sendTransaction({to:h.to,data:h.data,value:h.value,chain:i?.viemChain});if((await u.waitForTransactionReceipt({hash:p,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transaction failed");l=p}return l}async function dl(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 s=e.selectedAsset.asset,o=s.chainId,r=j.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),a=e.selectedIsEquivalent?r:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(a===0n)throw new Error("Quote not available yet");const i=e.resolvedTokenIn||e.selectedAsset.asset.address,d={userOverride:t,useCustomTransfers:!0},u=await e.gasless.estimateRequiredGrossFunding(a,b=>e.gasless.buildPayChainBatches({fundingAmountOverride:b}),i,d),l=F.getEscrowContractAddress(o),h=await e.externalWallet.getEthereumProvider();let p=null;try{const b=await h.request({method:"eth_chainId"});p=parseInt(b,16)}catch{p=null}p!==o&&await f.ensureWalletOnChain(h,o);const g=f.getChainConfig(o),x=j.createWalletClient({account:e.externalWalletAddress,chain:g?.viemChain,transport:j.custom(h)}),m=F.normalizeNativeTokenAddress(s.address),y=s.isNative||F.isNativeToken(m)?await x.sendTransaction({to:l,value:u,chain:g?.viemChain}):await x.sendTransaction({to:m,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"transfer",args:[l,u]}),chain:g?.viemChain});if((await f.getClientForChain(o).waitForTransactionReceipt({hash:y,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Escrow deposit failed");const w=await e.gasless.buildPayChainBatches({fundingAmountOverride:u}),S=w.some(b=>b.tokenTransfers?.length);return await e.gasless.executeGasless(w,i,u,b=>{b.txHash&&(e.ui.setPaymentResult(k=>({...k??{status:"processing"},txHash:b.txHash})),e.ui.setTxHash(b.txHash))},void 0,S?d:{userOverride:t})}async function ul(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}if(!e.selectedAsset?.asset){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){if(!e.externalWalletAddress){e.ui.setError("Please connect your external wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{let t;if(e.isSourceDestToken||e.parsedAmount===0)t=await or(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const s=e.selectedAsset.asset,o=j.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),r=e.selectedIsEquivalent?o:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(r===0n)throw new Error("Quote not available yet");const a=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!a)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const i=e.resolvedTokenIn||s.address,d=await e.gasless.estimateRequiredGrossFunding(r,h=>e.gasless.buildPayChainBatches({fundingAmountOverride:h}),i,{userOverride:a,useCustomTransfers:!0}),u=await e.gasless.buildPayChainBatches({fundingAmountOverride:d}),l=await e.onPayExecute({asset:s,amount:e.currentPaymentAmount,amountWei:o,destinationToken:e.destinationToken,chainBatches:u,requiredNetFunding:r,grossFundingAmount:d,selectedIsEquivalent:e.selectedIsEquivalent,resolvedTokenIn:i,exactOutputSwapAmountInMax:e.exactOutputSwap?.amountInMax});l&&(e.ui.setTxHash(l),e.ui.setPaymentResult(h=>({...h??{status:"processing"},txHash:l}))),t=l||void 0}else t=await dl(e);e.ui.setPaymentResult(s=>({status:"success",txHash:s?.txHash||t||""}))}catch(t){const s=f.sanitizeError(t,"Payment failed. Please try again.");e.ui.setError(s),e.ui.setPaymentResult({status:"failed",error:s}),e.onError?.(t instanceof Error?t:new Error(s))}finally{e.ui.setIsExecuting(!1)}return}if(!e.isConnected||!e.address){e.ui.setError("Please connect your wallet to continue");return}if(!e.ready||!e.authenticated){e.ui.setError(`Please authenticate with ${e.provider||"wallet provider"} to continue`);return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{const t=j.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),s=e.resolvedTokenIn||e.selectedAsset?.asset?.address||e.destinationToken.address,o=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:t,r={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode},a=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,i=await e.gasless.estimateRequiredGrossFunding(o,x=>e.gasless.buildPayChainBatches({fundingAmountOverride:x}).then(m=>zt(yn(m),a)),s,r);let d=i,u=zt(yn(await e.gasless.buildPayChainBatches({fundingAmountOverride:i})),a);const l=await e.gasless.estimateGasless(u,s,i,r),h=cn(l,{chainId:e.resolvedChainId,tokenAddress:s,symbol:F.getTokenByAddress(s,e.resolvedChainId)?.symbol??e.selectedAsset.asset.symbol,decimals:F.getTokenByAddress(s,e.resolvedChainId)?.decimals??e.selectedAsset.asset.decimals})?.grossAmount??i;h!==i&&(d=h),u=zt(yn(await e.gasless.buildPayChainBatches({fundingAmountOverride:d})),a,l,{payoutAlreadyGross:!0});const p=u.some(x=>x.tokenTransfers?.length),g=await e.gasless.executeGasless(u,s,p?d:0n,x=>{x.txHash&&(e.ui.setPaymentResult(m=>({...m,txHash:x.txHash})),e.ui.setTxHash(x.txHash))},void 0,r);e.ui.setPaymentResult(x=>({status:"success",txHash:x?.txHash||g}))}catch(t){const s=f.sanitizeError(t,"Payment failed. Please try again.");e.ui.setError(s),e.ui.setPaymentResult({status:"failed",error:s}),e.onError?.(t instanceof Error?t:new Error(s))}finally{e.ui.setIsExecuting(!1)}}const rr=({variant:e,destinationSymbol:t,destinationLogoURI:s,destinationDecimals:o,primaryColor:r,fontFamily:a,textPrimary:i,textSecondary:d,cardBg:u,cardBorder:l,dk:h,dark:p,isQuoting:g,quoteError:x,estimatedOutput:m,paymentAmount:y,needsSwap:w,exactOutputSwap:S,adjustable:b=!1,maxAmount:k,onAmountChange:I})=>e==="supply"?n.jsxs("div",{style:{backgroundColor:u,border:`1px solid ${l}`,borderRadius:p?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",minHeight:"112px",display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"12px"},children:[n.jsxs("div",{style:{minWidth:0},children:[n.jsx("span",{style:{fontFamily:a,fontSize:"17px",fontWeight:500,color:p?"#a7abb2":"#7D7C7B",lineHeight:"24px"},children:"Used in TX"}),n.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:d,fontFamily:a,marginTop:"10px"},children:"Net amount after swap and fees"})]}),n.jsxs("div",{style:{textAlign:"right",minWidth:0,display:"inline-flex",alignItems:"center",gap:"8px",border:`1px solid ${l}`,borderRadius:"8px",padding:"8px 10px",minHeight:"42px"},children:[n.jsx(ar,{symbol:t,logoURI:s,primaryColor:r,size:24}),n.jsx("span",{style:{fontSize:"16px",fontWeight:500,color:p?"#f3f4f6":"#3C3E42",lineHeight:"1.3",fontFamily:a,letterSpacing:0},children:t})]})]}),n.jsx("div",{style:{textAlign:"right",minWidth:0},children:g?n.jsx("span",{style:{fontSize:"18px",color:d,fontFamily:a},children:"Quoting..."}):x?n.jsx("span",{style:{fontSize:"13px",color:p?"#f87171":"#dc2626",fontFamily:a},children:"Quote failed"}):m?n.jsx(gn,{value:m,title:m,fontFamily:a,color:i,lineHeight:"0.95",textAlign:"right",maxFontSize:32,minFontSize:18}):n.jsx("span",{style:{fontSize:"20px",color:d,fontFamily:a},children:"\u2014"})})]}):n.jsx(pl,{destinationSymbol:t,destinationLogoURI:s,destinationDecimals:o,primaryColor:r,fontFamily:a,textPrimary:i,textSecondary:d,cardBg:u,cardBorder:l,dk:h,dark:p,paymentAmount:y||"0",needsSwap:w,exactOutputSwap:S,isQuoting:g,adjustable:b,maxAmount:k,onAmountChange:I}),ar=({symbol:e,logoURI:t,primaryColor:s,size:o})=>t?n.jsx("img",{src:t,alt:e,style:{width:o,height:o,borderRadius:"50%",objectFit:"cover"}}):n.jsx("div",{style:{width:o,height:o,borderRadius:"50%",backgroundColor:`${s}22`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:o<30?"11px":"12px",fontWeight:700,color:s},children:e.slice(0,2)}),pl=({destinationSymbol:e,destinationLogoURI:t,destinationDecimals:s,primaryColor:o,fontFamily:r,textPrimary:a,textSecondary:i,cardBg:d,cardBorder:u,dk:l,dark:h,paymentAmount:p,needsSwap:g,exactOutputSwap:x,isQuoting:m,adjustable:y,maxAmount:w,onAmountChange:S})=>{const b='"IBM Plex Mono", monospace',k=parseFloat(p||"0"),I=w?parseFloat(w):0,[C,E]=c.useState(p||""),A=c.useRef(null),[M,T]=c.useState(null),[v,B]=c.useState(null);c.useEffect(()=>{y||E(p||"")},[p,y]);const D=U=>{let H=U;H.startsWith(".")&&(H="0"+H);const q=kn(H);let N=q;w&&parseFloat(q)>parseFloat(w)&&(N=w),E(N),A.current&&clearTimeout(A.current),A.current=setTimeout(()=>S?.(N),300)},R=U=>{if(!I)return;if(U===100){E(w||I.toString()),A.current&&clearTimeout(A.current),S?.(w||I.toString());return}const H=10**s,q=Math.floor(I*U/100*H)/H,N=vn(q,s);E(N),A.current&&clearTimeout(A.current),S?.(N)},O=I>0?parseFloat(C||"0")/I*100:0;return c.useEffect(()=>()=>{A.current&&clearTimeout(A.current)},[]),n.jsxs("div",{style:{backgroundColor:d,border:`1px solid ${u}`,borderRadius:h?"12px":"6px",padding:"16px",marginBottom:"16px"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[n.jsx(ar,{symbol:e,logoURI:t,primaryColor:o,size:32}),n.jsxs("div",{children:[n.jsx("span",{style:{fontSize:"14px",fontWeight:600,color:a,fontFamily:r},children:"Payment"}),n.jsx("div",{style:{fontSize:"12px",color:i,fontFamily:r,marginTop:"2px"},children:e})]})]}),n.jsxs("div",{style:{textAlign:"right"},children:[y?n.jsx(gn,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:C,onChange:U=>D(U.target.value),placeholder:"0.0",fontFamily:b,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):n.jsx(gn,{element:"div",value:k>0?p:"0.00",title:k>0?p:"0.00",fontFamily:b,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),n.jsx("div",{style:{fontSize:"12px",color:i,fontFamily:b,marginTop:"2px"},children:e}),y&&I>0&&n.jsx("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((U,H)=>{const q=Math.abs(O-U)<1,N=H===4,K=U/100,L=M===U,V=v===U;return n.jsx("button",{onClick:()=>R(U),onMouseEnter:()=>T(U),onMouseLeave:()=>{T(null),B(null)},onMouseDown:()=>B(U),onMouseUp:()=>B(null),title:`${U}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:q?1:L?.8:.5,transform:V?"scale(0.85)":L?"scale(1.15)":"scale(1)",transition:Pt.interactive},children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[n.jsx("circle",{cx:"7",cy:"7",r:"6.84375",fill:N?o:"none",stroke:N?o:h?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!N&&K>0&&n.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${K>.5?1:0} 1 ${7+6.84375*Math.sin(K*2*Math.PI)} ${7-6.84375*Math.cos(K*2*Math.PI)} Z`,fill:h?l?.textSecondary||"#9ca3af":"#3C3E42"})]})},U)})})]})]}),g&&x&&!m&&n.jsx("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:h?`1px solid ${l?.cardBorder||u}`:"1px solid #e5e7eb",display:"flex",justifyContent:"flex-end"},children:n.jsxs("span",{style:{fontSize:"11px",color:i,fontFamily:r,opacity:.7},children:["via ",x.venue]})})]})};function ir(e,t,s){const o=f.addressesEqual(e.address,t),r=e.chainId===s,a=e._source==="wallet";return a&&o&&r?0:a&&r?1:!a&&o?2:!a&&r?3:4}function fl(e,t){return!t||t.length===0||t.some(s=>f.addressesEqual(s,e.address))?!0:Object.keys(e.chainTokens??{}).some(s=>{const o=En(s);return o?t.some(r=>f.addressesEqual(r,o.address)):!1})}function hl(e){const{destinationToken:t,supportedSourceAssets:s,sourceChains:o,enabled:r}=e,a=(c.useContext(f.SpiceFlowProviderContext)?.mode||"7702")!=="7702",i=f.useEmbeddedWalletAddress(),{externalAddress:d,embeddedAddress:u}=f.useProviderWallets(),l=i||u,{assets:h,refetch:p}=Pn({address:l,supportedChains:o,enabled:r&&!a&&!!l,refetchInterval:3e4}),g=c.useMemo(()=>a?[]:h.filter(A=>fl(A,s)),[h,s,a]),x=a?d:i,m=c.useMemo(()=>{const A=new Set,M=[],T=v=>{if(!v)return;const B=v.toLowerCase();A.has(B)||(A.add(B),M.push(j.getAddress(v)))};if(T(t.address),a&&s)for(const v of s)T(v);return M},[a,t.address,s]),y=c.useMemo(()=>m.map(A=>A.toLowerCase()).sort().join(","),[m]),w=c.useMemo(()=>JSON.stringify([...o||[]].sort()),[o]),[S,b]=c.useState([]),k=c.useRef(0),I=c.useRef(async()=>{}),C=c.useCallback(async()=>{if(!r||!x||m.length===0){k.current++,b([]);return}const A=++k.current,M=j.getAddress(x),T=a?o&&o.length>0?o:[t.chainId]:[t.chainId],v=[];for(const O of m){const U=O.toLowerCase();if(U===F.ZERO_ADDRESS)continue;if(U===t.address.toLowerCase()){const q=f.getChainConfig(t.chainId)?.supportedTokens?.find(N=>f.addressesEqual(N.address,U));v.push({address:O,chainId:t.chainId,configToken:q?{decimals:q.decimals,symbol:q.symbol,name:q.name,logo:q.logo}:void 0});continue}let H=!1;for(const q of T){const N=f.getChainConfig(q)?.supportedTokens?.find(K=>f.addressesEqual(K.address,U));if(N){v.push({address:O,chainId:q,configToken:{decimals:N.decimals,symbol:N.symbol,name:N.name,logo:N.logo}}),H=!0;break}}H||v.push({address:O,chainId:t.chainId})}const B=new Map;for(const O of v){const U=B.get(O.chainId)||[];U.push(O),B.set(O.chainId,U)}const D=async(O,U)=>{try{const H=await Ft.readContract(O,{address:U.address,abi:j.erc20Abi,functionName:"balanceOf",args:[M]});let q,N,K,L;if(U.configToken)q=U.configToken.decimals,N=U.configToken.symbol,K=U.configToken.name,L=U.configToken.logo;else{const[G,me,W]=await Promise.all([Ft.readContract(O,{address:U.address,abi:j.erc20Abi,functionName:"decimals"}).catch(()=>18),Ft.readContract(O,{address:U.address,abi:j.erc20Abi,functionName:"symbol"}).catch(()=>"TOKEN"),Ft.readContract(O,{address:U.address,abi:j.erc20Abi,functionName:"name"}).catch(()=>"TOKEN")]);q=Number(G),N=me,K=W}const V=f.addressesEqual(U.address,t.address)&&U.chainId===t.chainId;V&&t.logoURI&&(L=t.logoURI),V&&!U.configToken&&N==="TOKEN"&&(N=t.symbol,K=t.symbol);const P=parseFloat((Number(H)/Math.pow(10,q)).toFixed(6));return{address:U.address,name:K,symbol:N,decimals:q,balance:H,balanceFormatted:P,balanceUsd:0,logoURI:L,isNative:!1,chainId:U.chainId}}catch{return null}},R=await Promise.all(Array.from(B.entries()).map(async([O,U])=>{let H;try{H=f.getClientForChain(O)}catch{return[]}const q=[],N=[];for(const L of U){const V=q.length;q.push({address:L.address,abi:j.erc20Abi,functionName:"balanceOf",args:[M]}),L.configToken||q.push({address:L.address,abi:j.erc20Abi,functionName:"decimals"},{address:L.address,abi:j.erc20Abi,functionName:"symbol"},{address:L.address,abi:j.erc20Abi,functionName:"name"}),N.push({start:V,item:L})}let K=null;try{K=await H.multicall({contracts:q})}catch{K=null}return K?N.map(({start:L,item:V})=>{const P=K[L],G=P?.status==="success"?P.result:0n;let me,W,te,ue;if(V.configToken)me=V.configToken.decimals,W=V.configToken.symbol,te=V.configToken.name,ue=V.configToken.logo;else{const pe=K[L+1],ye=K[L+2],z=K[L+3];me=pe?.status==="success"?Number(pe.result):18,W=ye?.status==="success"?ye.result:"TOKEN",te=z?.status==="success"?z.result:W}const Ce=f.addressesEqual(V.address,t.address)&&V.chainId===t.chainId;Ce&&t.logoURI&&(ue=t.logoURI),Ce&&!V.configToken&&W==="TOKEN"&&(W=t.symbol,te=t.symbol);const je=parseFloat((Number(G)/Math.pow(10,me)).toFixed(6));return{address:V.address,name:te,symbol:W,decimals:me,balance:G,balanceFormatted:je,balanceUsd:0,logoURI:ue,isNative:!1,chainId:V.chainId}}):(await Promise.all(U.map(L=>D(H,L)))).filter(L=>L!==null)}));A===k.current&&b(R.flat())},[r,a,x,y,w,t.address,t.chainId,t.symbol,t.logoURI]);c.useEffect(()=>{I.current=C},[C]),c.useEffect(()=>{if(!r){b([]);return}I.current();const A=setInterval(()=>{I.current()},15e3);return()=>clearInterval(A)},[r,a,x,y,w,t.address,t.chainId]);const E=c.useCallback(()=>{C()},[C]);return{displayAssets:c.useMemo(()=>{const A=[],M=S.filter(v=>v.balance>0n);for(const v of M)A.push({...v,_source:"wallet"});for(const v of g)A.push({...v,_source:"spice"});const T=t.address.toLowerCase();return A.sort((v,B)=>ir(v,T,t.chainId)-ir(B,T,t.chainId)),A},[S,g,t.address,t.chainId]),filteredSpiceAssets:g,walletAssets:S,embeddedWalletAddress:l,externalAddress:d,isNon7702:a,refreshSpiceAssets:p,refreshWalletAssets:E}}async function lr(e){const{tokenIn:t,tokenOut:s,amountIn:o,fee:r,chainId:a,config:i}=e;if(o<=0n)throw new Error("amountIn must be greater than 0");const d=(await f.getClientForChain(a).simulateContract({address:i.quoterV2,abi:F.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:s,amountIn:o,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 cr(e){const t=e.feeTiers??[100,500,3e3,1e4],s=await Promise.allSettled(t.map(r=>lr({...e,fee:r})));let o=null;for(let r=0;r<s.length;r++){const a=s[r];a.status==="fulfilled"&&(!o||a.value.amountOut>o.amountOut)&&(o={...a.value,fee:t[r]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}const ml=[{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 gl(e){const{tokenIn:t,tokenOut:s,amountOut:o,fee:r,chainId:a,config:i}=e;if(o<=0n)throw new Error("amountOut must be greater than 0");const d=(await f.getClientForChain(a).simulateContract({address:i.quoterV2,abi:ml,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:s,amount:o,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 xl(e){const t=e.feeTiers??[100,500,3e3,1e4],s=await Promise.allSettled(t.map(r=>gl({...e,fee:r})));let o=null;for(let r=0;r<s.length;r++){const a=s[r];a.status==="fulfilled"&&(!o||a.value.amountIn<o.amountIn)&&(o={...a.value,fee:t[r]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}function dr(e){return e.type==="swap"}const Ks=.02,yl=[1,8453,42161,10,137,43114,56],Cl="https://api.1inch.dev/swap/v6.0";function ur(e,t){return F.applySlippage(e,t)}function pr(e){const t=e?.baseUrl??Cl;return{name:"1inch",chainIds:e?.chainIds??yl,resolve:async(s,o,r)=>{const a=s.maxSlippage??Ks,i=a*100,d=F.isNativeToken(s.tokenIn)?F.NATIVE_TOKEN_ADDRESS:s.tokenIn,u=F.isNativeToken(s.tokenOut)?F.NATIVE_TOKEN_ADDRESS:s.tokenOut,l=F.isNativeToken(s.tokenIn);try{const h=new URL(`${t}/${o}/swap`);h.searchParams.set("src",d),h.searchParams.set("dst",u),h.searchParams.set("amount",s.amountIn.toString()),h.searchParams.set("from",r),h.searchParams.set("slippage",i.toString()),h.searchParams.set("disableEstimate","true"),h.searchParams.set("allowPartialFill","false");const p={Accept:"application/json"};e?.apiKey&&(p.Authorization=`Bearer ${e.apiKey}`);const g=await fetch(h.toString(),{headers:p});if(!g.ok)throw new f.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${g.status} for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}`,{venue:"1inch",chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn.toString(),cause:`HTTP ${g.status}`});const x=await g.json();if(!x.dstAmount||!x.tx)return console.warn(`[1inchVenue] No route data for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}`),null;const m=BigInt(x.dstAmount);if(m<=0n)return console.warn(`[1inchVenue] Zero output for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}`),null;const y=ur(m,a),w=[];return x.tx.to&&!l&&w.push({to:s.tokenIn,value:0n,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"approve",args:[x.tx.to,s.amountIn]})}),w.push({to:x.tx.to,value:BigInt(x.tx.value||"0"),data:x.tx.data}),{venue:"1inch",amountOut:m,amountOutMinimum:y,calls:w}}catch(h){if(h instanceof f.SpiceflowError)throw h;const p=h instanceof Error?h.message:String(h);throw new f.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] Exception for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}: ${p}`,{venue:"1inch",chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn.toString(),cause:p})}}}}const fr=[4114,5115],Zs={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},hr={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[3e3]};function mr(e){return{name:"satsuma",chainIds:e.chainIds??fr,resolve:async(t,s,o)=>{const r=t.maxSlippage??Ks,a=F.isNativeToken(t.tokenIn);let i;try{i=await cr({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountIn:t.amountIn,chainId:s,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 ${s}.`),null}const d=ur(i.amountOut,r),u=[];return a||u.push({to:t.tokenIn,value:0n,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),u.push({to:e.swapRouter,value:a?t.amountIn:0n,data:j.encodeFunctionData({abi:F.uniV3SwapRouterAbi,functionName:"exactInputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:i.fee,recipient:o,amountIn:t.amountIn,amountOutMinimum:d,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:i.amountOut,amountOutMinimum:d,calls:u}}}}function gr(e){return{name:"satsuma",chainIds:e.chainIds??fr,resolve:async(t,s,o)=>{const r=t.maxSlippage??Ks,a=F.isNativeToken(t.tokenIn);let i;try{i=await xl({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountOut:t.amountOut,chainId:s,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,l=[];return l.push({to:e.swapRouter,value:a?u:0n,data:j.encodeFunctionData({abi:bl,functionName:"exactOutputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:i.fee,recipient:o,amountOut:t.amountOut,amountInMaximum:u,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:i.amountIn,amountInMax:u,amountOut:t.amountOut,calls:l}}}}const bl=[{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 xr(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(mr(e.satsuma)),t.push(pr(e?.oneInch));function s(r){return t.find(a=>a.chainIds.includes(r))}async function o(r,a,i){const d=[],u=[];for(const l of r){if(!dr(l)){d.push(l);continue}const h=s(a);if(!h)throw new f.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${a}. Cannot resolve swap ${l.tokenIn} \u2192 ${l.tokenOut}.`,{chainId:a,tokenIn:l.tokenIn,tokenOut:l.tokenOut,amountIn:l.amountIn.toString()});const p=await h.resolve(l,a,i);if(!p)throw new f.SpiceflowError("NO_LIQUIDITY",`${h.name} returned no quote for ${l.tokenIn} \u2192 ${l.tokenOut} on chain ${a}.`,{venue:h.name,chainId:a,tokenIn:l.tokenIn,tokenOut:l.tokenOut,amountIn:l.amountIn.toString()});d.push(...p.calls),u.push(p)}return{calls:d,resolvedSwaps:u}}return{resolveSwapIntents:o,getVenueForChain:s,venues:t}}function wl(e){const t=e?.customVenues??[];async function s(o,r,a){const i=t.filter(u=>u.chainIds.includes(r));if(i.length===0)throw new f.SpiceflowError("NO_SWAP_ROUTE",`No exact-output venue supports chain ${r}`,{chainId:r,tokenIn:o.tokenIn,tokenOut:o.tokenOut});const d=(await Promise.allSettled(i.map(u=>u.resolve(o,r,a)))).filter(u=>u.status==="fulfilled").map(u=>u.value).filter(u=>u!==null);if(d.length===0)throw new f.SpiceflowError("NO_SWAP_ROUTE",`All aggregators failed for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${r}`,{chainId:r,tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountOut:o.amountOut.toString()});return d.sort((u,l)=>u.amountIn<l.amountIn?-1:u.amountIn>l.amountIn?1:0),d[0]}return{getQuote:s,venues:t}}const kl=xr({satsuma:Zs});function vl(e){const{direction:t,selectedAsset:s,destinationToken:o,chainId:r,recipient:a,paymentAmount:i}=e,[d,u]=c.useState(!1),[l,h]=c.useState(null),[p,g]=c.useState(null),[x,m]=c.useState(null),[y,w]=c.useState(null),[S,b]=c.useState(null),[k,I]=c.useState(null),[C,E]=c.useState(null),[A,M]=c.useState(null),T=c.useRef(null),v=c.useRef(null),B=c.useRef(0),D=c.useRef(new Map),R=c.useMemo(()=>kl,[]),O=c.useMemo(()=>wl({customVenues:[gr(Zs),gr(hr)]}),[]),U=c.useMemo(()=>{if(!s?.asset)return null;const W=tn(s.asset,r);if(W)return W;const te=an(s.asset.address,r,s.asset.chainId);return te?te.address:null},[s?.asset,r]),H=c.useMemo(()=>s?.asset?Yn(s.asset,r):[],[s?.asset,r]),q=c.useMemo(()=>H.map(W=>W.toLowerCase()).join(","),[H]);c.useEffect(()=>{let W=!1;if(v.current&&(clearTimeout(v.current),v.current=null),!s?.asset||H.length<=1){M(null);return}return v.current=setTimeout(async()=>{const te=t==="input"?s.amount:i||"0";let ue=0n;try{ue=t==="input"?j.parseUnits(te,s.asset.decimals):0n}catch{ue=0n}try{const Ce=await jo(s.asset,r,{requiredAmount:ue});W||M(Ce)}catch{W||M(null)}},400),()=>{W=!0,v.current&&(clearTimeout(v.current),v.current=null)}},[s?.asset,s?.amount,r,H.length,q,t,i]);const N=c.useMemo(()=>A??U,[A,U]),K=c.useMemo(()=>!s?.asset||!N?[]:[N,...H.filter(W=>W.toLowerCase()!==N.toLowerCase())],[s?.asset,N,H]),L=c.useMemo(()=>!s?.asset||!Wn(s.asset.address,s.asset.chainId,o.address,o.chainId)||!N?!1:f.addressesEqual(N,o.address),[s,o.address,o.chainId,N]),V=N?f.addressesEqual(N,o.address):!1,P=t==="output"&&parseFloat(i||"0")===0,G=!!s?.asset&&!L&&!V&&!P,me=G?C??N:N;return c.useEffect(()=>{T.current&&clearTimeout(T.current);const W=t==="input"?s?.amount:i,te=parseFloat(W||"0");if(!G||!Number.isFinite(te)||te<=0||!s?.asset||!a||K.length===0){B.current++,g(null),m(null),w(null),b(null),I(null),E(null),h(null),u(!1);return}const ue=s.asset.decimals;let Ce;try{Ce=t==="input"?j.parseUnits(s.amount,ue):j.parseUnits(i||"0",o.decimals)}catch{B.current++,h("Invalid amount"),u(!1);return}const je=++B.current,pe=()=>je!==B.current;u(!0);const ye=t==="output"?150:400;return T.current=setTimeout(async()=>{try{if(t==="input"){const z=R.getVenueForChain(r);if(!z)throw new Error("No swap venue for this chain");let se=null,Y=null;for(const ge of K){const be=`${t}:${r}:${ge.toLowerCase()}:${o.address.toLowerCase()}:${Ce.toString()}`,ne=D.current.get(be);if(ne&&ne.expiresAt>Date.now()&&ne.resolvedSwap){se=ne.resolvedSwap,Y=ge;break}const Q=await z.resolve({type:"swap",tokenIn:ge,tokenOut:o.address,amountIn:Ce},r,a);if(pe())return;if(Q){D.current.set(be,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:Q}),se=Q,Y=ge;break}}if(!se||!Y)throw new Error("No liquidity for this pair");E(Y),I(se.amountOut),w(se),b(null);const ae=parseFloat(j.formatUnits(se.amountOut,o.decimals));g(ae<.01?ae.toPrecision(4):ae.toLocaleString(void 0,{maximumFractionDigits:6})),m(null),h(null)}else{let z=null,se=null;for(const Y of K){const ae=`${t}:${r}:${Y.toLowerCase()}:${o.address.toLowerCase()}:${Ce.toString()}`,ge=D.current.get(ae);if(ge&&ge.expiresAt>Date.now()&&ge.exactOutputSwap){z=ge.exactOutputSwap,se=Y;break}try{const be=await O.getQuote({tokenIn:Y,tokenOut:o.address,amountOut:Ce},r,a);if(pe())return;D.current.set(ae,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:be}),z=be,se=Y;break}catch{if(pe())return}}if(!z||!se)throw new Error("No liquidity for this pair");E(se),b(z),w(null),I(null),m(parseFloat(j.formatUnits(z.amountIn,ue)).toFixed(6)),g(null),h(null)}}catch(z){if(pe())return;const se=z instanceof Error?z.message:"Failed to get quote";h(se),g(null),m(null),w(null),b(null),I(null),E(null)}finally{pe()||u(!1)}},ye),()=>{T.current&&clearTimeout(T.current)}},[t,G,s?.amount,s?.asset?.address,s?.asset?.decimals,i,K,r,o.address,o.decimals,a,R,O]),{isQuoting:d,quoteError:l,estimatedOutput:p,estimatedInput:x,resolvedSwap:y,exactOutputSwap:S,quoteAmountOut:k,resolvedTokenIn:me,isDirect:V,needsSwap:G,selectedIsEquivalent:L}}const yr={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},Cr=["signing-delegation","signing-intent","submitting","executing"],br=({isOpen:e,onClose:t,closeOnBackdropClick:s=!1,destinationToken:o,sourceChains:r,supportedSourceAssets:a,buildActionCalls:i,feeExecutionMode:d="user-transfer",buildSpicenetBatch:u,onPayExecute:l,actionLabel:h,amountDirection:p="input",swapDescription:g,directDescription:x,paymentAmount:m,amountInputMode:y="fixed",minPaymentAmount:w,maxPaymentAmount:S,onAmountChange:b,styles:k,dark:I,title:C,subtitle:E,onAddFunds:A,onSuccess:M,onError:T})=>{const v=p==="output",{theme:B,dark:D,primaryColor:R,dk:O,palette:U,fontFamily:H,monoFont:q,inputDark:N,cardBg:K,cardBorder:L,textPrimary:V,textSecondary:P,subtitleText:G}=f.useSpiceBrand(k,I),me=N?{...B,colors:{...B.colors,secondary:O.cardBg,surfaceHover:O.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:B,W=o.chainId,te=c.useContext(f.SpiceFlowProviderContext),ue=(te?.mode||"7702")!=="7702",Ce=!!te?.isWhitelistGateActive,je=c.useMemo(()=>r??te?.supportedChainIds??[],[r,te?.supportedChainIds]),pe=c.useMemo(()=>{if(Ce)return[];if(a)return a;const de=te?.allowedTokens;if(!de||de.length===0)return;const Be=new Set(de.map(Yt=>Yt.toLowerCase())),yt=[],en=new Set;for(const Yt of je){const Bn=f.getChainConfig(Yt);for(const hn of Bn?.supportedTokens??[]){if(!Be.has(hn.symbol.toLowerCase()))continue;const Tn=hn.address.toLowerCase();en.has(Tn)||(en.add(Tn),yt.push(hn.address))}}return yt},[a,te?.allowedTokens,je,Ce]),ye=f.useWallet(),{address:z,isConnected:se,isReady:Y,isAuthenticated:ae,provider:ge}=ye,{executeGasless:be,estimateGasless:ne}=ns(),{externalWallet:Q,externalAddress:re,embeddedAddress:we}=f.useProviderWallets(),Me=f.useEmbeddedWalletAddress()||we,{displayAssets:at,filteredSpiceAssets:Xe,embeddedWalletAddress:le,refreshSpiceAssets:xe,refreshWalletAssets:fe}=hl({destinationToken:o,supportedSourceAssets:pe,sourceChains:je,enabled:e&&(ue?!!re:!!Me)}),Le=Ce||v||ue?at:Xe,[oe,Te]=c.useState(null),[mt,Bt]=c.useState(m||""),[ot,Lt]=c.useState(!1),[Tt,gt]=c.useState(null),[Se,Mt]=c.useState("idle"),[Jt,$t]=c.useState(""),[Ct,Ot]=c.useState(null),[Je,wt]=c.useState(!1),[qe,_e]=c.useState(null),[et,pt]=c.useState(null),[At,he]=c.useState(!1),[rt,it]=c.useState(!1),[kt,ke]=c.useState(null),Rt=c.useRef(oe),tt=c.useRef(!1),ft=c.useRef(null),vt=c.useRef(0),Kt=c.useRef(null),Ht=c.useRef(null);c.useEffect(()=>{Rt.current=oe},[oe]);const $e=y==="adjustable"?mt:m||"0",Zt=le||we||z,{isQuoting:Re,quoteError:dt,estimatedOutput:St,resolvedSwap:Oe,exactOutputSwap:Ge,quoteAmountOut:Et,resolvedTokenIn:ct,isDirect:De,needsSwap:He,selectedIsEquivalent:ht}=vl({direction:p,selectedAsset:oe,destinationToken:o,chainId:W,recipient:Zt,paymentAmount:$e}),nt=v?parseFloat($e||"0"):parseFloat(oe?.amount||"")||0,Qt=oe?.asset?._source==="wallet",Ue=!!oe?.asset&&Qt&&oe.asset.chainId!==W,Gt=c.useMemo(()=>oe?.asset?Xe.find(de=>f.addressesEqual(de.address,oe.asset.address))?.balanceFormatted??0:0,[oe,Xe]),Vt=Qt?oe?.asset.balanceFormatted??0:Gt,Dt=c.useMemo(()=>{if(!oe?.asset)return!1;if(v)return et?jn(et.grossAmount,et.decimals,oe.asset.decimals)>oe.asset.balance:ht||De?nt>oe.asset.balanceFormatted:Ge?parseFloat(j.formatUnits(Ge.amountInMax,oe.asset.decimals))>oe.asset.balanceFormatted:!1;if(et){const de=jn(et.grossAmount,et.decimals,oe.asset.decimals);return Qt?de>oe.asset.balance:parseFloat(j.formatUnits(de,oe.asset.decimals))>Vt}return nt>Vt},[oe,v,et,ht,nt,Ge,Vt,Qt,De]);c.useEffect(()=>{e||(Te(null),gt(null),Lt(!1),Mt("idle"),$t(""),Ot(null),wt(!1),_e(null),pt(null),he(!1),it(!1),ke(null),tt.current=!1,y==="adjustable"&&Bt(m||""),ft.current&&(ft.current.abort(),ft.current=null))},[e]);const _=c.useCallback(de=>{Te(Be=>({asset:de,amount:Be?.asset?.address===de.address&&Be?.asset?.chainId===de.chainId&&Be.amount||""})),gt(null),ke(null),it(!1)},[]),ee=c.useCallback(de=>{Te(Be=>Be&&{...Be,amount:de}),gt(null),ke(null),it(!1)},[]),Ie=c.useCallback(de=>{let Be=de;S&&parseFloat(Be)>parseFloat(S)&&(Be=S),Bt(Be),b?.(Be),gt(null),ke(null),it(!1)},[S,b]);c.useCallback(de=>{if(tt.current||!z)return;const Be=Rt.current;!Be?.asset||!Be.amount||Be.asset?._source==="wallet"||j.parseUnits(v?$e:Be.amount,Be.asset.decimals)===0n||(tt.current=!0,xe())},[z,W,xe,v,$e]);const Qe=c.useCallback(de=>{Mt({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[de.step]||"executing"),$t(de.message),de.txHash&&Ot(de.txHash)},[]),Ye=c.useMemo(()=>({currentPaymentAmount:$e,destinationToken:o,embeddedWalletAddress:le,providerEmbeddedAddress:we,externalWalletAddress:re,address:z,isNon7702:ue,isPayMode:v,resolvedChainId:W,buildActionCalls:i,feeExecutionMode:d,buildSpicenetBatch:u,selectedAsset:oe,needsSwap:He,resolvedSwap:Oe,exactOutputSwap:Ge,quoteAmountOut:Et,resolvedTokenIn:ct}),[$e,o,le,we,re,z,ue,v,W,i,d,u,oe,He,Oe,Ge,Et,ct]),Ke=c.useCallback(de=>$i(Ye,de),[Ye]),Ve=c.useCallback(de=>_i(Ye,de),[Ye]),We=c.useCallback((de,Be,yt,en)=>el(de,Be,yt,ne,en),[ne]),Pe=c.useMemo(()=>oe?.asset?He&&ct?ct:oe.asset.chainId===W?oe.asset.address:ct??tn(oe.asset,W)??o.address:o.address,[oe,o.address,He,W,ct]),X=c.useCallback(()=>ll(Ht.current),[]),ce=c.useMemo(()=>oe?.asset?f.addressesEqual(oe.asset.address,o.address)&&oe.asset.chainId===o.chainId:!1,[oe,o.address,o.chainId]),Fe=ue&&ce,Ee=Fe&&nt>0&&!!oe?.asset,ze=Tt,ut=c.useMemo(()=>!(!oe?.asset||nt<=0),[oe,nt,Ee]),qt=c.useMemo(()=>!e||ot||Se!=="idle"||!ut||Ee||!oe?.asset?null:[v?"pay":"supply",p,oe.asset.address.toLowerCase(),oe.asset.chainId,oe.amount,$e,o.address.toLowerCase(),o.chainId,W,ct?.toLowerCase()??"",He?"swap":"direct",De?"direct-token":"routed-token",ue?"non7702":"7702",ce?"source-dest":"cross-chain",Re?"quoting":"quoted",Ge?.amountIn?.toString()??"",Ge?.amountInMax?.toString()??"",Ge?.venue??"",Oe?.amountOut?.toString()??"",Et?.toString()??"",le??"",we??"",z??""].join("|"),[e,ot,Se,ut,Ee,oe,v,p,$e,o,W,ct,He,De,ue,ce,Re,Ge,Oe,Et,le,we,z]),Z=c.useCallback(()=>ol({selectedAsset:oe,isPayMode:v,parsedAmount:nt,needsSwap:He,exactOutputSwap:Ge,isNon7702:ue,isSourceDestToken:ce,currentPaymentAmount:$e,destinationToken:o,feeExecutionMode:d,resolvedTokenIn:ct,embeddedWalletAddress:le,providerEmbeddedAddress:we,resolvedChainId:W,isConnected:se,address:z,ready:Y,authenticated:ae,isDirect:De,resolvedSwap:Oe,isQuoting:Re,executionTokenAddress:Pe,buildPayChainBatches:Ke,buildSupplyChainBatches:Ve,estimateGasless:ne,estimateRequiredGrossFunding:We}),[oe,v,nt,He,Ge,ue,ce,$e,o,d,ct,le,we,We,Ke,ne,W,se,z,Y,ae,De,Oe,Re,Ve,Pe]);c.useEffect(()=>{Kt.current=Z},[Z]);const $=c.useCallback(de=>sl({asset:de,isPayMode:v,isNon7702:ue,needsSwap:He,isQuoting:Re,embeddedWalletAddress:le,buildSupplyChainBatches:Ve,estimateGasless:ne,executionTokenAddress:Pe,feeExecutionMode:d}),[v,ue,He,Re,le,Ve,ne,Pe,d]);c.useEffect(()=>{if(!e){he(!1),it(!1),ke(null),pt(null);return}if(ot||Se!=="idle"){vt.current+=1,he(!1);return}if(!ut){pt(null),he(!1),it(!1),ke(null);return}if(Ee){pt(null),he(!1),it(!0),ke(null);return}if(Re){vt.current+=1,he(!1),it(!1);return}if(!qt)return;let de=!1;const Be=async()=>{const en=++vt.current;ke(null),he(!0);try{const Yt=await Kt.current?.();if(de||vt.current!==en)return;Yt?(pt(Yt),it(!0)):(pt(null),it(!1)),ke(null)}catch(Yt){if(de||vt.current!==en)return;const Bn=f.sanitizeError(Yt,"Unable to calculate fees for this action.");pt(null),it(!1),ke(Bn)}finally{!de&&vt.current===en&&he(!1)}},yt=window.setTimeout(()=>{Be()},250);return()=>{de=!0,clearTimeout(yt),he(!1)}},[e,ot,Se,ut,Ee,Re,qt]);const ie=c.useCallback(()=>ul(Ht.current),[]);c.useEffect(()=>{!v&&Se==="success"&&Ct&&(xe(),M?.(Ct))},[v,Se,Ct,xe,M]),c.useEffect(()=>{if(!v||qe?.status!=="success"||tt.current||!z)return;tt.current=!0;const de=Rt.current;!de?.asset||de.asset?._source==="wallet"||xe()},[v,qe?.status,z,xe]);const J=c.useRef(M),Ae=c.useRef(T);c.useEffect(()=>{J.current=M},[M]),c.useEffect(()=>{Ae.current=T},[T]),c.useEffect(()=>{e&&(xe(),fe())},[e,xe,fe]),c.useEffect(()=>{v&&(qe?.status==="success"&&J.current?.(qe.txHash||""),qe?.status==="failed"&&Ae.current?.(new Error("Payment execution failed")))},[v,qe?.status]);const Ne=c.useCallback(()=>{wt(!1),_e(null),Te(null),tt.current=!1,xe(),fe()},[xe,fe]);Ht.current={selectedAsset:oe,parsedAmount:nt,currentPaymentAmount:$e,isInsufficientBalance:Dt,isPayMode:v,isNon7702:ue,isSourceDestToken:ce,needsSwap:He,exactOutputSwap:Ge,selectedIsEquivalent:ht,resolvedTokenIn:ct,embeddedWalletAddress:le,providerEmbeddedAddress:we,externalWallet:Q,externalWalletAddress:re,address:z,isConnected:se,ready:Y,authenticated:ae,provider:ge,resolvedChainId:W,executionTokenAddress:Pe,destinationToken:o,buildActionCalls:i,feeExecutionMode:d,buildSpicenetBatch:u,onPayExecute:l,onError:T,gasless:{estimateGasless:ne,executeGasless:be,buildPayChainBatches:Ke,buildSupplyChainBatches:Ve,estimateRequiredGrossFunding:We,onProgress:Qe},ui:{setError:gt,setStep:Mt,setStatusMsg:$t,setTxHash:Ot,setIsExecuting:Lt,setShowStatusPanel:wt,setPaymentResult:_e},refs:{spiceDepositSubmittedRef:tt,abortControllerRef:ft}};const st=v&&nt===0,Ze=v?!!oe?.asset&&nt>=0&&!Dt&&!ot&&(st||Ee||rt)&&!kt&&(st||!He||!!Ge):!!oe?.asset&&nt>0&&!Dt&&!ot&&(Fe||rt)&&!kt&&(Ue||De||!!Oe&&!Re),lt=De?x||`Your ${o.symbol} will be used directly.`:g||"Your assets will be swapped and used in a single atomic transaction.",jt=(W?f.getChainConfig(W):void 0)?.viemChain?.blockExplorers?.default?.url??"",xt=Cr.indexOf(Se),Nt=ot?(yr[Se]||"EXECUTING...").toUpperCase():Se==="success"?"DONE":Dt?"INSUFFICIENT BALANCE":h.toUpperCase(),Ut=c.useMemo(()=>{if(ot)return"PAYING...";if(Dt&&oe?.asset)return`INSUFFICIENT ${oe.asset.symbol}`;if(h)return h.toUpperCase();const de=nt>0?` ${$e} ${o.symbol}`:"";return He?`SWAP & PAY${de}`:`PAY${de}`},[ot,Dt,oe,h,nt,$e,o.symbol,He]),_t=Se==="success"?()=>{Mt("idle"),Te(null),Ot(null),xe()}:X,pn=Se==="success"?!1:!Ze;if(!e)return null;const fn=v?C||`Pay ${o.symbol}`:h,ve=v?E:n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[n.jsx("span",{style:{marginTop:"3px",flexShrink:0},children:n.jsx(Ss,{color:G})}),n.jsx("p",{style:{fontSize:"12px",color:G,margin:0,lineHeight:"1.4",fontFamily:H},children:lt})]});if(v){const de=qe&&(qe.status==="success"||qe.status==="failed")?[{asset:{symbol:oe?.asset?.symbol||o.symbol,address:oe?.asset?.address||""},amount:$e,txHash:qe.txHash||"",success:qe.status==="success",error:qe.status==="failed"?qe.error:void 0}]:void 0;return n.jsx(sn,{isOpen:e,onClose:t,title:fn,subtitle:ve,styles:k,dark:D,footerLinkText:"Spicenet accounts \u2192",closeOnBackdropClick:s,children:n.jsxs("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[A&&n.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:n.jsx(Is,{onClick:A,color:R,fontFamily:H})}),n.jsx("div",{style:{marginBottom:"12px"},children:n.jsx(Un,{assets:Le,selectedAsset:oe??void 0,onAssetSelect:_,onAmountChange:()=>{},label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:oe?.asset?He?Re?"...":Ge?`~${parseFloat(j.formatUnits(Ge.amountIn,oe.asset.decimals)).toFixed(6)}`:void 0:$e??void 0:void 0,dark:D,theme:me,styles:k})}),n.jsx(rr,{variant:"pay",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:R,fontFamily:H,textPrimary:V,textSecondary:P,cardBg:K,cardBorder:L,dk:O,dark:D,isQuoting:Re,quoteError:dt,estimatedOutput:St,paymentAmount:$e,needsSwap:He,exactOutputSwap:Ge,adjustable:y==="adjustable",maxAmount:S,onAmountChange:Ie}),ut&&n.jsx(qn,{fontFamily:H,textPrimary:V,textSecondary:P,cardBg:K,cardBorder:L,resolvedDark:D,darkCardBorder:O.cardBorder,primaryColor:R,feePreview:et,isLoading:At,errorText:kt,directExecutionFeeNote:Ee}),ze&&n.jsx(In,{variant:"error",palette:U,fontFamily:H,style:{marginBottom:"12px"},children:ze}),n.jsx(f.Button,{variant:"outline",fullWidth:!0,onClick:ie,disabled:!Ze,loading:ot,dark:D,styles:{...k,button:{...k?.button,backgroundColor:R}},children:Ut}),qe&&Je&&n.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:D?O.shell:"white",borderRadius:D?"12px":"6px",padding:"16px 0"},children:n.jsx(Bs,{type:"payment",isOpen:qe.status!=="processing",isProcessing:ot||qe.status==="processing",closeOnComplete:!1,chainName:f.getChainName(W),explorerUrl:f.getExplorerUrl(W,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{wt(!1),_e(null),ie()},onNewTx:Ne,onClose:()=>{wt(!1),_e(null)},onComplete:Ne,results:de,styles:k,dark:D})})]})})}return n.jsx(sn,{isOpen:e,onClose:t,title:fn,subtitle:ve,dark:D,styles:k,theme:B,closeOnBackdropClick:s,children:n.jsxs("div",{style:{padding:"24px 24px 5px 24px",position:"relative"},children:[n.jsx("div",{style:{marginBottom:"16px"},children:n.jsx(Un,{assets:Le,selectedAsset:oe||void 0,onAssetSelect:_,onAmountChange:ee,disabled:ot||Se==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:me,styles:k,dark:N,resolveMaxAmount:$,maxAmount:Vt>0?vn(Vt,oe?.asset.decimals??o.decimals):void 0})}),oe?.asset&&!De&&n.jsx(rr,{variant:"supply",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:R,fontFamily:H,textPrimary:V,textSecondary:P,cardBg:K,cardBorder:L,dark:D,isQuoting:Re,quoteError:dt,estimatedOutput:St}),ut&&n.jsx(qn,{fontFamily:H,textPrimary:V,textSecondary:P,cardBg:K,cardBorder:L,resolvedDark:D,darkCardBorder:O.cardBorder,primaryColor:R,feePreview:et,isLoading:At,errorText:kt,directExecutionFeeNote:Ee}),Se!=="idle"&&n.jsxs("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:Se==="success"?K:Se==="error"?U.errorBg:K,border:`1px solid ${Se==="success"?L:Se==="error"?U.errorBorder:L}`},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[Se==="success"?n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:n.jsx("path",{d:"M5 13l4 4L19 7",stroke:U.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):Se==="error"?n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:n.jsx("path",{d:"M18 6L6 18M6 6l12 12",stroke:U.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):n.jsx(f.Spinner,{size:14,color:R}),n.jsx("span",{style:{fontSize:"13px",fontWeight:500,color:Se==="success"?V:Se==="error"?U.errorText:V,fontFamily:H,flex:1},children:Se==="success"?"Deposit confirmed":Se==="error"?Jt||"Transaction failed":yr[Se]||Jt}),Se==="success"&&Ct&&n.jsx("a",{href:`${jt}/tx/${Ct}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:R,fontFamily:H,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),Se==="error"&&n.jsx("button",{onClick:()=>{Mt("idle"),gt(null),setTimeout(X,50)},style:{background:"none",border:"none",fontSize:"12px",color:R,fontFamily:H,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),xt>=0&&Se!=="success"&&Se!=="error"&&n.jsx("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${P}22`,overflow:"hidden"},children:n.jsx("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:R,transformOrigin:"left center",transform:`scaleX(${(xt+1)/Cr.length})`,transition:"transform 400ms ease"}})})]}),Tt&&Se==="idle"&&n.jsx(In,{variant:"error",palette:U,fontFamily:H,style:{marginBottom:"16px"},children:Tt}),n.jsx(f.Button,{variant:"outline",fullWidth:!0,disabled:pn,onClick:_t,theme:B,dark:D,styles:{...k,button:{...k?.button,backgroundColor:R}},style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:q},children:Nt})]})})},Sl=e=>n.jsx(br,{isOpen:e.isOpen,onClose:e.onClose,closeOnBackdropClick:e.closeOnBackdropClick,amountDirection:"output",destinationToken:{address:e.paymentTokenAddress,symbol:e.paymentTokenSymbol,decimals:e.paymentTokenDecimals,chainId:e.paymentChainId,logoURI:e.paymentTokenLogoURI},buildActionCalls:e.buildActionCalls,buildSpicenetBatch:e.buildSpicenetBatch,actionLabel:e.ctaLabel||"PAY",paymentAmount:e.paymentAmount,amountInputMode:e.amountInputMode,minPaymentAmount:e.minPaymentAmount,maxPaymentAmount:e.maxPaymentAmount,onAmountChange:e.onAmountChange,title:e.title,subtitle:e.subtitle,onAddFunds:e.onAddFunds,styles:e.styles,dark:e.dark,onSuccess:e.onPaymentSuccess,onError:e.onPaymentError}),Il=({label:e="Export Wallet",style:t,className:s,onExport:o,onError:r})=>{const[a,i]=c.useState(!1),[d,u]=c.useState(!1),{primaryColor:l}=f.useSpiceBrand(),h=c.useContext(f.SpiceFlowProviderContext),{isAuthenticated:p}=f.useWallet();let g=null;try{g=cs.usePrivy()}catch{}let x=null,m=null;try{x=Js.useEmbeddedReveal(),m=Js.useDynamicContext()}catch{x=null,m=null}const y=f.getDynamicEmbeddedWallet(m),w=c.useCallback(async()=>{if(!p){r?.("User is not authenticated. Please log in first.");return}try{if(h?.provider==="dynamic"){if(!x||!y){r?.("Dynamic is not available. Ensure the app is wrapped in a DynamicContextProvider.");return}await x.initExportProcess(!1),o?.();return}if(!g){r?.("Privy is not available. Ensure the app is wrapped in a PrivyProvider.");return}await g.exportWallet(),o?.()}catch(k){const I=k instanceof Error?k.message:"Failed to export wallet";console.error("Export wallet error:",k),r?.(I)}},[y,x,p,r,o,g,h?.provider]),S=!p,b={padding:"10px 20px",borderRadius:"8px",fontFamily:'"IBM Plex Mono", monospace',fontSize:"14px",fontWeight:500,letterSpacing:"0.4px",textTransform:"uppercase",cursor:S?"not-allowed":"pointer",opacity:S?.5:1,border:"1px solid #0e0d0b",color:"#0e0d0b",backgroundColor:d?`${l}cc`:a?`${l}ee`:l,transition:"background-color 150ms ease, transform 150ms ease",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"8px",...t};return n.jsxs("button",{onClick:w,onMouseEnter:()=>i(!0),onMouseLeave:()=>{i(!1),u(!1)},onMouseDown:()=>u(!0),onMouseUp:()=>u(!1),disabled:S,className:s,style:b,children:[n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),n.jsx("polyline",{points:"17 8 12 3 7 8"}),n.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]}),e]})};function wr(e){const t=c.useContext(f.SpiceFlowProviderContext),s=f.useEmbeddedWalletAddress(),o=e?.enabled===!1?void 0:s,r=t?.network?{network:t.network,pollIntervalMs:e?.pollIntervalMs,chainIds:e?.chainIds??t.supportedChainIds,discoverWalletBalances:e?.discoverWalletBalances}:void 0;return{...yo(o,r),embeddedWalletAddress:s}}var Al="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 El=({appName:e,status:t,statusLabel:s,totalUsdValue:o,breakdownSubtitle:r,address:a,dk:i,dark:d=!1,showModeToggle:u,isEmbeddedMode:l=!0,onModeToggle:h})=>{const[p,g]=c.useState(!1),x=async()=>{a&&await Gr(a)&&(g(!0),setTimeout(()=>g(!1),2e3))},m=t==="active",y=s||(m?"Active":"Inactive"),w=m?"#10b981":"#9ca3af",S=n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[n.jsxs("div",{children:[n.jsx("strong",{children:"Embedded:"})," Deposit assets into ",e," account and use them here."]}),n.jsxs("div",{children:[n.jsx("strong",{children:"External:"})," Use assets from your connected wallet here."]})]});return n.jsxs("div",{children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[n.jsxs("div",{style:{fontSize:"13px",fontWeight:600,color:i.textPrimary},children:[e," Account"]}),u?n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[n.jsxs("button",{onClick:h,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:'"IBM Plex Mono", monospace',color:i.textSecondary,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease",letterSpacing:"0.02em"},children:[n.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:l?"#22c55e":"#f59e0b"}}),n.jsx("span",{children:l?"Embedded":"External"}),n.jsx("img",{src:Al,alt:"","aria-hidden":"true",style:{width:"11px",height:"11px",display:"block",...d?{filter:"invert(0.65)"}:{}}})]}),n.jsx(co,{content:S,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:n.jsx("img",{src:js,alt:"","aria-hidden":"true",style:{width:"12px",height:"12px",display:"block",...d?{filter:"invert(0.65)"}:{}}})})]}):n.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:[n.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:w}}),n.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:d?i.textSecondary:m?"#065f46":"#6b7280"},children:y})]})]}),n.jsx("div",{style:{fontSize:"28px",fontWeight:700,color:i.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:wn(o)}),r&&n.jsx("div",{style:{fontSize:"12px",color:i.textSecondary,marginBottom:"8px"},children:r}),a&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[n.jsx("span",{style:{fontSize:"12px",fontFamily:'"IBM Plex Mono", monospace',color:d?i.textSecondary:"#9ca3af"},children:Zr(a)}),n.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:p?"Copied":"Copy"})]})]})},jl=({pendingDeposits:e,onCompleteDeposit:t,dk:s,dark:o=!1})=>e.length===0?null:n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:s.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:"Pending Deposits"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((r,a)=>{const i=f.getChainConfig(r.chainId)?.displayName||`Chain ${r.chainId}`;return n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:o?s.warningBg:"#fffbeb",border:o?`1px solid ${s.warningBorder}`:"1px solid #fde68a",borderRadius:"8px"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[n.jsx("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:o?s.hoverBg:"#fde68a",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:s.warningText},children:r.tokenSymbol.charAt(0)}),n.jsxs("div",{children:[n.jsxs("div",{style:{fontSize:"13px",fontWeight:500,color:s.textPrimary},children:[r.amount," ",r.tokenSymbol]}),n.jsxs("div",{style:{fontSize:"11px",color:s.warningText},children:["on ",i]})]})]}),n.jsx("button",{onClick:()=>t?.(r),style:{padding:"4px 12px",fontSize:"11px",fontWeight:600,backgroundColor:o?s.hoverBg:"#fef3c7",color:o?s.textPrimary:"#92400e",border:o?`1px solid ${s.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}`)})})]}),Fl=({spiceAssets:e,loading:t,dk:s,dark:o=!1})=>{const r={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:s.textSecondary,marginBottom:"8px",textTransform:"uppercase"},a={backgroundColor:s.cardBg,border:o?`1px solid ${s.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return t?n.jsxs("div",{children:[n.jsx("div",{style:r,children:"Idle Balances"}),[1,2].map(i=>n.jsx("div",{style:{...a,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},i))]}):e.length===0?n.jsxs("div",{children:[n.jsx("div",{style:r,children:"Idle Balances"}),n.jsx("div",{style:{...a,padding:"16px",textAlign:"center",fontSize:"13px",color:o?s.textSecondary:"#9ca3af"},children:"No assets yet. Deposit to get started."})]}):n.jsxs("div",{children:[n.jsx("div",{style:r,children:"Idle Balances"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((i,d)=>{const u=f.getChainConfig(i.chainId),l=i.chainDisplayName||u?.displayName||`Chain ${i.chainId}`,h=i.tokenDisplaySymbol||i.tokenDisplayName||i.tokenSymbol;return n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...a},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[i.logoURI?n.jsx("img",{src:i.logoURI,alt:i.tokenSymbol,style:{width:"24px",height:"24px",borderRadius:"50%"}}):n.jsx("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:o?s.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:s.textSecondary},children:h.charAt(0)}),n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:s.textPrimary},children:h}),n.jsx("div",{style:{fontSize:"11px",color:o?s.textSecondary:"#9ca3af"},children:l})]})]}),n.jsxs("div",{style:{textAlign:"right"},children:[n.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:s.textPrimary},children:ln(i.balanceFormatted)}),n.jsx("div",{style:{fontSize:"11px",color:o?s.textSecondary:"#9ca3af"},children:wn(i.usdValue)})]})]},`${i.tokenAddress}-${i.chainId}-${d}`)})})]})},Bl=({section:e,dk:t,dark:s=!1})=>{const o=r=>{switch(r){case"green":return"#10b981";case"red":return"#ef4444";default:return t.textPrimary}};return n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:t.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:e.title}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.items.map((r,a)=>n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:t.cardBg,border:s?`1px solid ${t.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[r.tokenLogoURI?n.jsx("img",{src:r.tokenLogoURI,alt:r.tokenSymbol,style:{width:"20px",height:"20px",borderRadius:"50%"}}):n.jsx("div",{style:{width:"20px",height:"20px",borderRadius:"50%",backgroundColor:s?t.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",fontWeight:600,color:t.textSecondary},children:r.tokenSymbol.charAt(0)}),n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:t.textPrimary},children:r.tokenSymbol}),n.jsx("div",{style:{fontSize:"11px",color:t.textSecondary},children:r.label})]})]}),n.jsx("div",{style:{fontSize:"13px",fontWeight:600,color:o(r.valueColor)},children:r.displayValue})]},a))})]})},Tl=({onDepositClick:e,onWithdrawClick:t,depositDisabled:s=!1,withdrawDisabled:o=!1,primaryColor:r="#EA4B4B",dark:a=!1})=>!e&&!t?null:n.jsxs("div",{style:{display:"flex",gap:"8px"},children:[e&&n.jsx(f.Button,{variant:"outline",onClick:e,disabled:s,dark:a,styles:{button:{backgroundColor:r}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&n.jsx(f.Button,{variant:"outline",onClick:t,disabled:o,dark:a,styles:{button:{backgroundColor:r}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),Ml=({appName:e,status:t,statusLabel:s,totalUsdValue:o,breakdownSubtitle:r,address:a,spiceAssets:i,spiceAssetsLoading:d,pendingDeposits:u,customSections:l,onDepositClick:h,onWithdrawClick:p,onCompleteDeposit:g,primaryColor:x,dk:m,dark:y=!1,showModeToggle:w,isEmbeddedMode:S,onModeToggle:b,showConnectExternalCta:k,onConnectExternalWallet:I,connectExternalError:C,showHowItWorks:E=!0})=>{const[A,M]=c.useState(!1);return n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[n.jsx(El,{appName:e,status:t,statusLabel:s,totalUsdValue:o,breakdownSubtitle:r,address:a,dk:m,dark:y,showModeToggle:w,isEmbeddedMode:S,onModeToggle:b}),k&&n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[n.jsx("button",{onClick:I,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:x||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:'"Helvetica Neue", sans-serif',transition:"opacity 150ms ease"},children:"Connect External Wallet"}),C&&n.jsx("span",{style:{fontSize:"11px",color:y?m.errorText:"#b91c1c",lineHeight:1.4},children:C})]}),n.jsx("div",{style:{height:"1px",backgroundColor:y?"#2d2d2d":"#e5e7eb"}}),n.jsx(Tl,{onDepositClick:h,onWithdrawClick:p,primaryColor:x,dark:y}),E&&n.jsxs("div",{children:[n.jsxs("button",{onClick:()=>M(!A),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:m.cardBg,border:y?`1px solid ${m.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:m.textSecondary,fontSize:"12px",fontWeight:500},children:[n.jsx("span",{children:"How It Works"}),n.jsx("span",{style:{transform:A?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),A&&n.jsxs("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:y?m.cardBg:"#f0fdf4",border:y?`1px solid ${m.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:y?m.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),n.jsx(jl,{pendingDeposits:u,onCompleteDeposit:g,dk:m,dark:y}),n.jsx(Fl,{spiceAssets:i,loading:d,dk:m,dark:y}),l.map((T,v)=>n.jsx(Bl,{section:T,dk:m,dark:y},v))]})},Gs=380,Cn=8;function kr(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function Rl(e,t){const s=new Map;Object.entries(t).forEach(([r,a])=>{if(!Number.isFinite(a)||a<=0)return;s.set(r,a),s.set(r.toUpperCase(),a);const i=kr(r);i&&s.set(i,a)});const o=[e.symbol,e.displaySymbol,e.receiptTokenName,e.name,e.displayName];for(const r of o){if(!r)continue;const a=s.get(r)??s.get(r.toUpperCase());if(a!==void 0)return a;const i=kr(r);if(!i)continue;const d=s.get(i);if(d!==void 0)return d}return 0}const Dl=({appName:e="Spice",status:t="active",statusLabel:s,customSections:o=[],extraAssets:r=[],tokenPrices:a={},breakdownLabels:i=[],styles:d,dark:u=!1,onDepositSuccess:l,onDepositClick:h,onWithdrawClick:p,onCompleteDeposit:g,showModeToggle:x=!1,defaultMode:m})=>{const y=c.useContext(f.SpiceFlowProviderContext),w=y?.mode!=="7702",S=!!y?.isWhitelistGateActive,b=c.useRef(!1);c.useEffect(()=>{if(!b.current){if(f.hasStoredSpiceFlowMode()){b.current=!0;return}m&&y?.setMode&&(y.setMode(m==="non7702"?"ondemand":"7702"),b.current=!0)}},[y,m]);const[k,I]=c.useState(!1),[C,E]=c.useState(null),[A,M]=c.useState({top:0,bottom:0,left:0,placement:"below"}),T=c.useRef(null),v=c.useRef(null),{address:B,isConnected:D}=f.useWallet(),R=f.useEmbeddedWalletAddress(),{externalAddress:O}=f.useProviderWallets(),{dark:U,primaryColor:H,dk:q}=f.useSpiceBrand(d,u),N=!w&&R?R:B,K=c.useMemo(()=>y?.supportedChainIds??F.getChainIdsByNetwork("mainnet"),[y?.supportedChainIds]),{assets:L,loading:V}=Pn({address:N,supportedChains:K,enabled:!!N&&!w,refetchInterval:3e4}),P=c.useMemo(()=>[...w?[]:L.map(le=>{const xe=le.balanceUsd||0,fe=Number.isFinite(le.balanceFormatted)?le.balanceFormatted:0,Le=xe>0?xe:Rl(le,a)*fe;return{tokenAddress:le.address,tokenSymbol:le.symbol,tokenDisplaySymbol:Cs(le),tokenDisplayName:ea(le),tokenDecimals:le.decimals,chainId:le.chainId,chainDisplayName:bs(le),balance:le.balance.toString(),balanceFormatted:le.balanceFormatted,usdValue:Le,logoURI:le.logoURI}}),...r].filter(le=>le.balanceFormatted>0),[w,L,a,r]),G=c.useMemo(()=>P.reduce((le,xe)=>le+xe.usdValue,0),[P]),{pendingDeposits:me}=wr({chainIds:K,enabled:!!B,discoverWalletBalances:!1}),W=c.useMemo(()=>o.reduce((le,xe)=>le+xe.totalValue,0),[o]),te=G+W,ue=c.useMemo(()=>{const le=[];G>0&&le.push(`${wn(G)} idle`);for(const xe of o){const fe=i.find(Le=>Le.sectionTitle===xe.title)?.label||xe.title.toLowerCase();le.push(`${wn(xe.totalValue)} ${fe}`)}return le.join(" \xB7 ")},[G,o,i]),Ce=c.useCallback(le=>{g?g(le):E(le)},[g]),je=c.useCallback(()=>{E(null)},[]),pe=c.useCallback(()=>{E(null),l?.()},[l]),ye=c.useCallback(()=>{if(!T.current)return;const le=T.current.getBoundingClientRect(),xe=window.innerHeight-le.bottom-Cn,fe=le.top-Cn,Le=xe>=400||xe>=fe?"below":"above",oe=Math.max(Cn,Math.min(le.right-Gs,window.innerWidth-Gs-Cn)),Te=Le==="below"?le.bottom+Cn:le.top-Cn,mt=Le==="above"?window.innerHeight-Te:0;M({top:Te,bottom:mt,left:oe,placement:Le})},[]);c.useLayoutEffect(()=>{k&&ye()},[k,ye]),c.useEffect(()=>{if(!k)return;const le=Le=>{T.current&&!T.current.contains(Le.target)&&v.current&&!v.current.contains(Le.target)&&I(!1)},xe=Le=>{Le.key==="Escape"&&I(!1)},fe=()=>ye();return document.addEventListener("mousedown",le),document.addEventListener("keydown",xe),window.addEventListener("scroll",fe,{passive:!0}),window.addEventListener("resize",ye),()=>{document.removeEventListener("mousedown",le),document.removeEventListener("keydown",xe),window.removeEventListener("scroll",fe),window.removeEventListener("resize",ye)}},[k,ye]);const z=y?.mode==="7702",se=z?R||B:O||B,Y=c.useCallback(()=>{y?.setMode&&y.setMode(z?"ondemand":"7702")},[y,z]),[ae,ge]=c.useState(null);let be=null;try{be=cs.useConnectWallet({onSuccess:()=>ge(null),onError:le=>ge(f.sanitizeError(le,"Failed to connect wallet."))}).connectWallet}catch{be=null}const ne=c.useCallback(()=>{be&&(I(!1),ge(null),be({walletChainType:"ethereum-only"}))},[be]),Q=!O&&!!be,re=c.useCallback(()=>{I(!1),h?.()},[h]),we=c.useCallback(()=>{I(!1),p?.()},[p]),Me=c.useCallback(le=>{I(!1),Ce(le)},[Ce]);if(typeof window>"u")return null;const at=n.jsxs("button",{ref:T,onClick:()=>I(!k),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:U?q.hoverBg:"#ffffff",border:U?`1px solid ${q.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:'"Helvetica Neue", sans-serif',color:U?q.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:U?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[n.jsx("span",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:H,flexShrink:0}}),n.jsxs("span",{children:[e," Account"]}),D&&n.jsxs("span",{style:{color:U?q.textSecondary:"#6b7280"},children:["\xB7 ",wn(te)]}),n.jsx("span",{style:{fontSize:"10px",color:U?q.textSecondary:"#9ca3af",transform:k?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),Xe=k?Mn.createPortal(n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:mn.popover},onClick:()=>I(!1)}),n.jsx("div",{ref:v,style:{position:"fixed",top:A.placement==="below"?`${A.top}px`:"auto",bottom:A.placement==="above"?`${A.bottom}px`:"auto",left:`${A.left}px`,width:`${Gs}px`,maxWidth:`calc(100vw - ${Cn*2}px)`,maxHeight:"80vh",backgroundColor:U?q.shell:"#ffffff",border:U?`1px solid ${q.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:U?"0 10px 40px rgba(0, 0, 0, 0.5)":"0 10px 40px rgba(0, 0, 0, 0.12)",zIndex:mn.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${bt.out}`},children:n.jsx(Ml,{appName:e,status:t,statusLabel:s,totalUsdValue:te,breakdownSubtitle:ue,address:z?se:B,spiceAssets:P,spiceAssetsLoading:V,pendingDeposits:me,customSections:o,onDepositClick:h?re:void 0,onWithdrawClick:p?we:void 0,onCompleteDeposit:Me,primaryColor:H,dk:q,dark:U,showModeToggle:x,isEmbeddedMode:z,onModeToggle:Y,showConnectExternalCta:Q,onConnectExternalWallet:ne,connectExternalError:ae,showHowItWorks:!S})}),n.jsx("style",{children:`
103
+ `})]})},zi="0xa9059cbb";function Li(e){const t=new Map;for(const s of e){if(s.amount<=0n)continue;const o=j.getAddress(s.token),r=j.getAddress(s.to),a=`${o.toLowerCase()}:${r.toLowerCase()}`,i=t.get(a);i?i.amount+=s.amount:t.set(a,{token:o,to:r,amount:s.amount})}return[...t.values()]}function Oi(e,t){return`0x${t}${e.slice(4)}`}function Hi(e,t,s){if(!Array.isArray(e))return 0n;const o=`evm:${t}:${s.slice(2).toLowerCase()}`;let r=0n;for(const a of e){if(!a||typeof a!="object")continue;const i=a,d=i.chainTokens;if((Array.isArray(d)?d.filter(u=>typeof u=="string"):d&&typeof d=="object"?Object.keys(d):[]).some(u=>u.toLowerCase()===o))try{r+=BigInt(i.balanceAvailable??"0")}catch{}}return r}async function Xo(e,t,s,o){const r=await fetch(`${e}/wallets/${t}/balance`,{cache:"no-store"});if(!r.ok)throw new Error(`Failed to fetch spice balance: ${r.status}`);const a=await r.json();return Hi(a?.balances,s,o)}async function Qi({apiBaseUrl:e,user:t,chainId:s,tokenAddress:o,prevBalance:r,timeoutMs:a=3e4,pollIntervalMs:i=1500}){const d=Date.now()+a;for(await new Promise(u=>setTimeout(u,800));Date.now()<d;){try{if(await Xo(e,t,s,o)>r)return}catch(u){console.warn("[SpiceLockModal] spice balance poll failed:",u?.message)}await new Promise(u=>setTimeout(u,i))}console.warn("[SpiceLockModal] Spicenet indexer did not reflect deposit within timeout; proceeding with intent")}function Ls(e,t){return Os(e,t)}function Os(e,t,s){const o=Vi(t,e),r=Math.floor(Date.now()/1e3)+60*10,a=F.hashChainBatches(o);return{user:e,...s?{chainAuthorizations:s}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:"0x00",nbf:0,exp:r,chainBatches:a.map((i,d)=>({hash:i.hash,chainId:i.chainId,tokenTransfers:o[d].domain==="spicenet"?[]:o[d].tokenTransfers??[],calls:i.calls}))}]}}function Vi(e,t){return e.map(s=>{if(s.domain==="spicenet"||s.calls.length===0)return s;const o=new Set((s.tokenTransfers??[]).filter(a=>(a.from==="escrow"||a.from==="solver")&&j.getAddress(a.to).toLowerCase()===t.toLowerCase()).map(a=>j.getAddress(a.token).toLowerCase()));if(o.size===0)return s;let r=0;for(const a of s.calls){if(!a.data?.startsWith(zi))break;try{const i=j.decodeFunctionData({abi:f.U,data:a.data});if(i.functionName!=="transfer")break;const[d]=i.args;if(d.toLowerCase()===t.toLowerCase()||!o.has(j.getAddress(a.to).toLowerCase()))break;r+=1}catch{break}}return r===0?s:{...s,calls:s.calls.slice(r)}})}function zt(e,t,s,o){if(e.some(l=>l.domain==="spicenet"))return e;const r=s?.intents.flatMap(l=>l.batches),a=l=>l.from==="escrow",i=e.map(l=>{const h=r?.find(k=>k.chainId===l.chainId);if(!h)return l;const p=Xt(h),g=p.totalFee;if(g<=0n)return l;const x=(l.tokenTransfers??[]).find(k=>a(k)&&j.getAddress(k.to).toLowerCase()===t.toLowerCase()&&!F.isNativeToken(j.getAddress(k.token)));if(!x)return l;const m=j.getAddress(x.token);let y=!1;const w=(l.tokenTransfers??[]).map(k=>y||!a(k)||j.getAddress(k.to).toLowerCase()!==t.toLowerCase()||j.getAddress(k.token).toLowerCase()!==m.toLowerCase()?k:(y=!0,{...k,amount:o?.payoutAlreadyGross?BigInt(k.amount):BigInt(k.amount)+g}));if(!y)return l;const S=[];p.spicenetFee>0n&&S.push({to:m,value:0n,data:j.encodeFunctionData({abi:f.U,functionName:"transfer",args:[F.SPICE_PLATFORM_FEE_RECIPIENT,p.spicenetFee]})});const b=p.gasFee+p.bridgeFee;return b>0n&&S.push({to:m,value:0n,data:j.encodeFunctionData({abi:f.U,functionName:"transfer",args:[F.SPICE_GAS_FEE_RECIPIENT,b]})}),{...l,tokenTransfers:w,calls:[...S,...l.calls]}}),d=i.flatMap(l=>(l.tokenTransfers??[]).filter(a).map(h=>{const p=j.getAddress(h.token),g=j.getAddress(h.to),x=[{token:p,to:g,amount:BigInt(h.amount)}];return{chainId:l.chainId,transfers:Li(x)}}));if(d.length===0)return e;const u=BigInt(Math.floor(Date.now()/1e3))+3600n;return[{chainId:F.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:d.map((l,h)=>{const p=j.keccak256(j.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,l.transfers[0].token,l.transfers.reduce((x,m)=>x+m.amount,0n),BigInt(l.chainId),BigInt(Date.now()+h)])),g=Oi(p,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:j.encodeFunctionData({abi:F.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${l.chainId}`,idempotenceKey:g,nbf:0n,exp:u,metadata:"{}",transfers:l.transfers.map(x=>({token:x.token.toLowerCase(),to:x.to,amount:x.amount}))}]})}})},...i]}function Hs(e,t){return t?e.some(s=>(s.tokenTransfers??[]).some(o=>o.from==="escrow"&&BigInt(o.amount)>=t.grossAmount)):!1}function Qs(e){const t=e.selectedAsset?.asset,s=e.selectedAsset?.amount;if(!(!t||!s))return j.parseUnits(s,t.decimals)}function un(e,t){const s=e.selectedAsset?.asset;if(!s||!e.selectedAsset?.amount)throw new Error("Select an asset and enter an amount");const o=j.parseUnits(e.selectedAsset.amount,s.decimals),r=t?.grossAmount??o;return e.resolveLockBatches({amount:e.selectedAsset.amount,amountWei:o,grossAmount:j.formatUnits(r,s.decimals),grossAmountWei:r})}async function Vs(e,t,s){const o=[...new Set(s.filter(a=>a.domain!=="spicenet").map(a=>a.chainId))],r=[];for(const a of o){const i=f.getClientForChain(a),d=f.getDelegateContractAddress(a),u=await F.getAccountNonce(t,i),l=await e.actions.signAuthorization({contractAddress:d,chainId:a,nonce:Number(u)});r.push(l)}return r}async function Jo(e,t,s){const o=e.isSemi7702&&e.providerEmbeddedAddress||e.address;if(!e.isConnected||!o)throw new Error("Please connect your wallet to continue");if(t.length===0)throw new Error("No lock batches configured");if(!e.ready||!e.authenticated)throw new Error(`Please authenticate with ${e.provider||"wallet provider"} to continue`);const r=s??await Vs(e,o,t),a=F.hashChainBatches(t),i=Math.floor(Date.now()/1e3)+60*10,d=a.map(x=>x.hash),u=j.keccak256(j.encodeAbiParameters([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,BigInt(i),d])),l=await e.actions.signMessage({raw:u}),h=typeof l=="string"?l:l.signature;if(!h)throw new Error("Failed to sign intent authorization");const p={mode:"7702",signatureType:"ecdsa",signature:h,nbf:0,exp:i,chainBatches:a.map((x,m)=>{const y=t[m],w=y.domain==="spicenet";return{hash:x.hash,chainId:x.chainId,tokenTransfers:w?[]:y.tokenTransfers??[],calls:x.calls}})},g=await f.relayerService.createAction({user:o,chainAuthorizations:r.map(x=>({r:x.r,s:x.s,yParity:x.yParity,address:x.address,chainId:Number(x.chainId),nonce:Number(x.nonce)})),intents:[p]});if(g){const x=f.createInitialSteps(t,f.getChainName),[m,y]=g.intentIds[0].split("/"),w=parseInt(y||"0",10),S=g.intentIds[0];e.startStatusPolling(g.intentIds[0],x),await To({actionId:m,intentIndex:w,intentId:S,totalSteps:t.length,isSpicenetStep:b=>t[b]?.domain==="spicenet",maxExecuteAttemptsForStep:b=>t[b]?.domain==="spicenet"?6:3,maxPolls:180})}}async function $o(e){let t=un(e);if(t.length===0)throw new Error("No lock batches configured");const s=e.isSemi7702&&e.providerEmbeddedAddress||e.address;if(!e.isConnected||!s)throw new Error("Please connect your wallet to continue");const o=await Vs(e,s,t);let r=zt([...t],s),a;for(let i=0;i<4;i+=1){const d=await f.relayerService.estimateActionFees(Os(s,r,o.map(p=>({r:p.r,s:p.s,yParity:p.yParity,address:p.address,chainId:Number(p.chainId),nonce:Number(p.nonce)})))),u=zn(d,{symbol:e.selectedAsset?.asset.symbol??"",decimals:e.selectedAsset?.asset.decimals??18,actionAmount:Qs(e)});if(!u)break;const l={grossAmount:u.grossAmount,netAmount:u.netAmount,feeAmount:u.totalFee??0n},h=a?.grossAmount===l.grossAmount&&a?.netAmount===l.netAmount&&a?.feeAmount===l.feeAmount;if(a=l,t=un(e,a),r=zt([...t],s,d,{payoutAlreadyGross:Hs(t,a)}),h)break}await Jo(e,r,o)}async function qi(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");if(!e.address||!e.embeddedWalletAddress)throw new Error("Embedded wallet not connected");const t=e.selectedAsset.asset,s=j.parseUnits(e.selectedAsset.amount,t.decimals),o=e.escrowAddress||f.getDelegateContractAddress(e.lockChainId),r=f.relayerService.getBaseUrl(),a=F.normalizeNativeTokenAddress(t.address);let i=0n;try{i=await Xo(r,e.embeddedWalletAddress,e.lockChainId,a)}catch(p){console.warn("[SpiceLockModal] could not snapshot spice balance pre-deposit:",p?.message)}const d=await e.actions.getEthereumProvider();await f.ensureWalletOnChain(d,e.lockChainId);const u=f.getChainConfig(e.lockChainId),l=j.createWalletClient({account:e.embeddedWalletAddress,transport:j.custom(d),chain:u?.viemChain});let h;if(t.isNative||F.isNativeToken(t.address))h=await l.sendTransaction({to:o,value:s,chain:u?.viemChain});else{const p=j.encodeFunctionData({abi:f.U,functionName:"transfer",args:[o,s]});h=await l.sendTransaction({to:t.address,data:p,chain:u?.viemChain})}if((await f.getClientForChain(e.lockChainId).waitForTransactionReceipt({hash:h,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to escrow failed");await Qi({apiBaseUrl:r,user:e.embeddedWalletAddress,chainId:e.lockChainId,tokenAddress:a,prevBalance:i}),await e.refreshSpiceAssets(),e.refreshWalletAssets(),await $o(e)}async function Ki(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");if(e.onLockExecute){const E=e.resolveLockBatches();if(E.length===0)throw new Error("No lock batches configured");const A=e.selectedAsset.asset,M=j.parseUnits(e.selectedAsset.amount,A.decimals),T=await e.onLockExecute({asset:A,amount:e.selectedAsset.amount,amountWei:M,lockDurationMonths:e.selectedDuration?.months??0,chainBatches:E});T&&e.onLockSuccess?.(T);return}const s=e.resolveLockBatches();if(s.length===0)throw new Error("No lock batches configured");const o=e.selectedAsset.asset,r=j.parseUnits(e.selectedAsset.amount,o.decimals),a=o.chainId,i=e.escrowAddress||F.getEscrowContractAddress(a),d=F.normalizeNativeTokenAddress(o.address),u=o.isNative||F.isNativeToken(d),l=s.some(E=>E.tokenTransfers?.some(A=>A.from==="escrow")),h=E=>({chainId:a,calls:u?[{to:i,value:E,data:"0x"}]:[{to:d,value:0n,data:j.encodeFunctionData({abi:f.U,functionName:"transfer",args:[i,E]})}]}),p=(E,A,M)=>{const T=h(E);if(!l)return[T,...A];const v=zt([...A],t,M,{payoutAlreadyGross:Hs(A,y)});return[T,...v]};let g=un(e),x=p(r,g);const m=await Vs(e,t,x);let y;if(l)for(let E=0;E<4;E+=1){const A=await f.relayerService.estimateActionFees(Os(t,x,m.map(B=>({r:B.r,s:B.s,yParity:B.yParity,address:B.address,chainId:Number(B.chainId),nonce:Number(B.nonce)})))),M=zn(A,{symbol:o.symbol,decimals:o.decimals,actionAmount:r});if(!M)break;const T={grossAmount:M.grossAmount,netAmount:M.netAmount,feeAmount:M.totalFee??0n},v=y?.grossAmount===T.grossAmount&&y?.netAmount===T.netAmount&&y?.feeAmount===T.feeAmount;if(y=T,g=un(e,y),x=p(T.grossAmount,g,A),v)break}const w=y?.grossAmount??r,S=await e.externalWallet.getEthereumProvider();let b=null;try{const E=await S.request({method:"eth_chainId"});b=parseInt(E,16)}catch{b=null}b!==a&&await f.ensureWalletOnChain(S,a);const k=f.getChainConfig(a),I=j.createWalletClient({account:e.externalWalletAddress,chain:k?.viemChain,transport:j.custom(S)}),C=u?await I.sendTransaction({to:t,value:w,chain:k?.viemChain}):await I.sendTransaction({to:d,data:j.encodeFunctionData({abi:f.U,functionName:"transfer",args:[t,w]}),chain:k?.viemChain});if((await f.getClientForChain(a).waitForTransactionReceipt({hash:C,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to embedded wallet failed");await Jo(e,x,m)}async function Zi(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount||!e.requiresRelayerFeeEstimate)return null;if(e.isSemi7702){const i=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!i)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");let d=un(e);if(d.length===0)throw new Error("No lock batches configured");const u=e.selectedAsset.asset,l=j.parseUnits(e.selectedAsset.amount,u.decimals),h=u.chainId,p=e.escrowAddress||F.getEscrowContractAddress(h),g=F.normalizeNativeTokenAddress(u.address),x=u.isNative||F.isNativeToken(g),m=d.some(I=>I.tokenTransfers?.some(C=>C.from==="escrow")),y=I=>({chainId:h,calls:x?[{to:p,value:I,data:"0x"}]:[{to:g,value:0n,data:j.encodeFunctionData({abi:f.U,functionName:"transfer",args:[p,I]})}]}),w=(I,C,E)=>{const A=y(I);if(!m)return[A,...C];const M=zt([...C],i,E,{payoutAlreadyGross:C.some(T=>(T.tokenTransfers??[]).some(v=>v.from==="escrow"&&BigInt(v.amount)>=I))});return[A,...M]};let S=w(l,d),b=null,k;for(let I=0;I<4;I+=1){const C=await f.relayerService.estimateActionFees(Ls(i,S)),E=zn(C,{symbol:u.symbol,decimals:u.decimals,actionAmount:l});if(!E)return b;const A={grossAmount:E.grossAmount,netAmount:E.netAmount,feeAmount:E.totalFee??0n},M=k?.grossAmount===A.grossAmount&&k?.netAmount===A.netAmount&&k?.feeAmount===A.feeAmount;if(b=E,k=A,d=un(e,A),S=w(A.grossAmount,d,C),M)break}return b}const t=e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");let s=un(e);if(s.length===0)throw new Error("No lock batches configured");let o=zt([...s],t),r=null;for(let i=0;i<4;i+=1){const d=await f.relayerService.estimateActionFees(Ls(t,o)),u=zn(d,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:Qs(e)});if(!u)return null;const l={grossAmount:u.grossAmount},h=r?.grossAmount===u.grossAmount&&r?.netAmount===u.netAmount&&r?.totalFee===u.totalFee;if(r=u,s=un(e,l),o=zt([...s],t,d,{payoutAlreadyGross:Hs(s,l)}),h)break}if(r)return r;const a=await f.relayerService.estimateActionFees(Ls(t,o));return zn(a,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:Qs(e)})}async function Gi(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.resolveLockBatches();if(t.length===0)throw new Error("No lock batches configured");const s=t.find(l=>l.chainId===e.lockChainId)||t[0];if(!s)throw new Error("No lock batch for lock chain");const o=await e.externalWallet.getEthereumProvider();let r=null;try{const l=await o.request({method:"eth_chainId"});r=parseInt(l,16)}catch{r=null}r!==e.lockChainId&&await f.ensureWalletOnChain(o,e.lockChainId);const a=f.getChainConfig(e.lockChainId),i=j.createWalletClient({account:e.externalWalletAddress,chain:a?.viemChain,transport:j.custom(o)}),d=f.getClientForChain(e.lockChainId);let u;for(const l of s.calls){const h=await i.sendTransaction({to:l.to,data:l.data,value:l.value,chain:a?.viemChain});if((await d.waitForTransactionReceipt({hash:h,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Lock transaction failed");u=h}u&&e.onLockSuccess?.(u)}async function Yi(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=s=>{console.error("[SpiceLockModal] lock failed:",s);const o=f.sanitizeError(s,""),r=typeof s?.shortMessage=="string"?s.shortMessage:typeof s?.message=="string"?s.message:"";e.ui.setError(o||r||"Transaction failed. Please try again.")};if(e.isSemi7702){if(e.isSourceDestToken){try{await Gi(e)}catch(s){t(s)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{await Ki(e)}catch(s){t(s)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{e.isDirectDeposit&&!e.isSourceDestToken?await qi(e):await $o(e)}catch(s){t(s)}finally{e.ui.setIsExecuting(!1)}}const _o=({isOpen:e,onClose:t,closeOnBackdropClick:s=!1,lockBatches:o,lockTokenSymbol:r,lockTokenLogoURI:a,destinationInputHook:i,sourceAssetInputHook:d,lockDurationHook:u,lockChainId:l,durationOptions:h,votingPowerEstimate:p,escrowAddress:g,includeWalletAssets:x=!1,destinationTokenAddress:m,onLockSuccess:y,onLockExecute:w,sourceToDestinationConversionRate:S,estimatedOutputAmount:b,onAddFunds:k,buildSpicenetBatch:I,styles:C,dark:E=!1})=>{const{theme:A,dark:M,primaryColor:T,dk:v}=f.useSpiceBrand(C,E),B=A.typography.fontFamily,D=c.useContext(f.SpiceFlowProviderContext),R=D?.mode||"7702",O=!!D?.isWhitelistGateActive,U=R!=="7702",H=c.useMemo(()=>D?.supportedChainIds??[],[D?.supportedChainIds]),q=c.useMemo(()=>{if(O)return[];const X=D?.allowedTokens;if(!X||X.length===0)return[];const ce=new Set(X.map(ze=>ze.toLowerCase())),Fe=[],Ee=new Set;for(const ze of H){const ut=f.getChainConfig(ze);for(const qt of ut?.supportedTokens??[]){if(!ce.has(qt.symbol.toLowerCase()))continue;const Z=`${ze}:${qt.address.toLowerCase()}`;Ee.has(Z)||(Ee.add(Z),Fe.push(j.getAddress(qt.address)))}}return Fe},[D?.allowedTokens,H,O]),N=M?v.cardBg:C?.assetSelector?.backgroundColor||C?.secondaryBackground||"#e9e9e9",K=M?`1px solid ${v.cardBorder}`:"0.5px solid #A8A8A7",L=M?"12px":"6px",V=M?v.textPrimary:"#111827",P=M?v.textSecondary:"#6b7280",G=c.useMemo(()=>({...C,assetSelector:{...C?.assetSelector,backgroundColor:M?v.cardBg:C?.assetSelector?.backgroundColor,borderRadius:M?"12px":C?.assetSelector?.borderRadius},secondaryBackground:M?v.cardBg:C?.secondaryBackground}),[C,M]),me=c.useMemo(()=>M?{...A,colors:{...A.colors,secondary:v.cardBg,surfaceHover:v.hoverBg,border:v.cardBorder,borderHover:v.inputBorder}}:A,[M,A]),[W,te]=c.useState(null),[ue,Ce]=c.useState(0),je=u?.selectedDurationIdx??ue,pe=u?.setSelectedDurationIdx??Ce,[ye,z]=c.useState(!1),[se,Y]=c.useState(null),[ae,ge]=c.useState(null),[be,ne]=c.useState(!1),[Q,re]=c.useState(!1),[we,Me]=c.useState(null),[at,Xe]=c.useState(!1),le=c.useRef(0),[xe,fe]=c.useState(!1),[Le,oe]=c.useState(null);It.useWalletClient(),It.useSwitchChain();const{chain:Te,address:mt}=It.useAccount();It.useConfig();const Bt=c.useRef(Te);c.useEffect(()=>{Bt.current=Te},[Te]);const ot=f.useWallet(),{isReady:Lt,isAuthenticated:Tt,isConnected:gt,address:Se,provider:Mt,actions:Jt}=ot,{externalWallet:$t,embeddedAddress:Ct,externalAddress:Ot}=f.useProviderWallets(),{intentStatus:Je,startStatusPolling:wt,clearStatus:qe}=lo({checkStepStatus:(X,ce)=>f.relayerService.checkStepStatus(X,ce),retryStep:async(X,ce)=>{const[Fe,Ee]=X.split("/"),ze=parseInt(Ee||"0",10);await f.relayerService.executeStep(Fe,ze,ce,{action:"execute"})},maxRetries:3}),{assets:_e,refetch:et}=Pn({address:Se,supportedChains:H,enabled:e&&gt&&!U&&!O,refetchInterval:3e4}),pt=c.useMemo(()=>{if(O)return[];if(q.length===0)return _e;const X=new Set(q.map(ce=>ce.toLowerCase()));return _e.filter(ce=>X.has(ce.address.toLowerCase()))},[_e,q,O]),At=f.useEmbeddedWalletAddress(),he=Ot||mt,rt=U?he:At,it=c.useMemo(()=>{if(!x)return[];if(O)return m?[j.getAddress(m)]:[];const X=new Set,ce=[],Fe=Ee=>{if(!Ee)return;const ze=Ee.toLowerCase();X.has(ze)||(X.add(ze),ce.push(j.getAddress(Ee)))};if(m&&Fe(m),U)for(const Ee of q)Fe(Ee);return ce},[x,U,m,q,O]),kt=c.useMemo(()=>it.map(X=>X.toLowerCase()).sort().join(","),[it]),ke=c.useMemo(()=>JSON.stringify([...H||[]].sort()),[H]),[Rt,tt]=c.useState([]),ft=c.useRef(0),vt=c.useRef(async()=>{}),Kt=c.useCallback(async()=>{if(!x||!rt||it.length===0){ft.current++,tt([]);return}const X=++ft.current,ce=j.getAddress(rt),Fe=H&&H.length>0?H:[l],Ee=it.map($=>{const ie=$.toLowerCase();if(m&&f.addressesEqual($,m)){const J=f.getChainConfig(l)?.supportedTokens?.find(Ae=>f.addressesEqual(Ae.address,ie));return{address:$,chainId:l,configToken:J?{decimals:J.decimals,symbol:J.symbol,name:J.name,logo:J.logo}:void 0}}for(const J of Fe){const Ae=f.getChainConfig(J)?.supportedTokens?.find(Ne=>f.addressesEqual(Ne.address,ie));if(Ae)return{address:$,chainId:J,configToken:{decimals:Ae.decimals,symbol:Ae.symbol,name:Ae.name,logo:Ae.logo}}}return{address:$,chainId:l}}),ze=new Map;for(const $ of Ee){const ie=ze.get($.chainId)||[];ie.push($),ze.set($.chainId,ie)}const ut=async($,ie)=>{try{const J=await Ft.readContract($,{address:ie.address,abi:f.U,functionName:"balanceOf",args:[ce]});let Ae,Ne,st,Ze;if(ie.configToken)Ae=ie.configToken.decimals,Ne=ie.configToken.symbol,st=ie.configToken.name,Ze=ie.configToken.logo;else{const[xt,Nt,Ut]=await Promise.all([Ft.readContract($,{address:ie.address,abi:f.U,functionName:"decimals",args:[]}).catch(()=>18),Ft.readContract($,{address:ie.address,abi:f.U,functionName:"symbol",args:[]}).catch(()=>"TOKEN"),Ft.readContract($,{address:ie.address,abi:f.U,functionName:"name",args:[]}).catch(()=>"TOKEN")]);Ae=Number(xt),Ne=Nt,st=Ut}const lt=!!m&&f.addressesEqual(ie.address,m)&&ie.chainId===l;lt&&a&&(Ze=a),lt&&r&&!ie.configToken&&(Ne==="TOKEN"&&(Ne=r),st==="TOKEN"&&(st=r));const jt=parseFloat((Number(J)/Math.pow(10,Ae)).toFixed(6));return{address:ie.address,name:st,symbol:Ne,decimals:Ae,balance:J,balanceFormatted:jt,balanceUsd:0,logoURI:Ze,isNative:!1,chainId:ie.chainId}}catch{return null}},qt=await Promise.all(Array.from(ze.entries()).map(async([$,ie])=>{let J;try{J=f.getClientForChain($)}catch{return[]}const Ae=[],Ne=[];for(const Ze of ie){const lt=Ae.length;Ae.push({address:Ze.address,abi:f.U,functionName:"balanceOf",args:[ce]}),Ze.configToken||Ae.push({address:Ze.address,abi:f.U,functionName:"decimals",args:[]},{address:Ze.address,abi:f.U,functionName:"symbol",args:[]},{address:Ze.address,abi:f.U,functionName:"name",args:[]}),Ne.push({start:lt,item:Ze})}let st=null;try{st=await J.multicall({contracts:Ae})}catch{st=null}return st?Ne.map(({start:Ze,item:lt})=>{const jt=st[Ze],xt=jt?.status==="success"?jt.result:0n;let Nt,Ut,_t,pn;if(lt.configToken)Nt=lt.configToken.decimals,Ut=lt.configToken.symbol,_t=lt.configToken.name,pn=lt.configToken.logo;else{const de=st[Ze+1],Be=st[Ze+2],yt=st[Ze+3];Nt=de?.status==="success"?Number(de.result):18,Ut=Be?.status==="success"?Be.result:"TOKEN",_t=yt?.status==="success"?yt.result:Ut}const fn=!!m&&f.addressesEqual(lt.address,m)&&lt.chainId===l;fn&&a&&(pn=a),fn&&r&&!lt.configToken&&(Ut==="TOKEN"&&(Ut=r),_t==="TOKEN"&&(_t=r));const ve=parseFloat((Number(xt)/Math.pow(10,Nt)).toFixed(6));return{address:lt.address,name:_t,symbol:Ut,decimals:Nt,balance:xt,balanceFormatted:ve,balanceUsd:0,logoURI:pn,isNative:!1,chainId:lt.chainId}}):(await Promise.all(ie.map(Ze=>ut(J,Ze)))).filter(Ze=>Ze!==null)}));if(X!==ft.current)return;const Z=qt.flat();tt(Z)},[x,rt,kt,ke,l,m,a,r]);c.useEffect(()=>{vt.current=Kt},[Kt]),c.useEffect(()=>{if(!e||!x){tt([]);return}vt.current();const X=setInterval(()=>{vt.current()},15e3);return()=>clearInterval(X)},[x,e,rt,kt,ke,l,m]);const Ht=c.useCallback(()=>{Kt()},[Kt]),$e=c.useMemo(()=>Rt.filter(X=>X.balance>0n),[Rt]),Zt=c.useMemo(()=>{if(U)return $e.map(ce=>({...ce,_source:"wallet"}));if(!x)return pt;const X=[];for(const ce of $e)X.push({...ce,_source:"wallet"});for(const ce of pt)X.push({...ce,_source:"spice"});return X},[U,x,$e,pt]),Re=c.useMemo(()=>O?m?Zt.filter(X=>f.addressesEqual(X.address,m)&&X.chainId===l):[]:Zt,[Zt,O,m,l]),dt=c.useRef(null),St=c.useRef(null);c.useEffect(()=>{St.current=W},[W]),c.useEffect(()=>{!O||!W?.asset||m&&f.addressesEqual(W.asset.address,m)&&W.asset.chainId===l||te(null)},[O,W?.asset,m,l]),c.useEffect(()=>{e||(te(null),Y(null),ge(null),ne(!1),re(!1),Me(null),z(!1),fe(!1),oe(null),Xe(!1),qe())},[e,qe]),c.useEffect(()=>{i&&i.assetAmount!==(W?.amount||"")&&te(X=>X&&{...X,amount:i.assetAmount})},[i?.assetAmount]),c.useEffect(()=>{d&&d.assetAmount!==(W?.amount||"")&&te(X=>X&&{...X,amount:d.assetAmount})},[d?.assetAmount]),c.useEffect(()=>{if(!U&&Je?.overallStatus==="success"&&Je.intentId&&dt.current!==Je.intentId&&Se&&Je.steps.find(X=>X.transactionHash)?.transactionHash){dt.current=Je.intentId;const X=St.current;if(!X?.asset||!X.amount||X.asset._source==="wallet"||j.parseUnits(X.amount,X.asset.decimals)===0n)return;et()}},[Je,Se,l,et,U]);const Oe=parseFloat(W?.amount||"")||0,Ge=c.useMemo(()=>W?.asset?W.asset._source==="wallet"?W.asset.balanceFormatted??0:pt.find(X=>f.addressesEqual(X.address,W.asset.address)&&X.chainId===W.asset.chainId)?.balanceFormatted??0:0,[W?.asset,pt]),Et=Oe>0&&(we?parseFloat(j.formatUnits(we.grossAmount,we.decimals))>Ge:Oe>Ge),ct=u?.selectedDuration??h[je]??h[0],De=c.useMemo(()=>!W?.asset||!m?!1:f.addressesEqual(W.asset.address,m)&&W.asset.chainId===l,[W?.asset,m,l]),He=c.useMemo(()=>Oe<=0?0:De?Oe:!S||S<=0?0:Oe/S,[Oe,S,De]),ht=c.useMemo(()=>He<=0?null:He.toLocaleString(void 0,{maximumFractionDigits:2}),[He]),nt=p&&He>0&&ct?p(He,ct.months):void 0,Qt=c.useMemo(()=>Oe<=0?"$0.00":De&&S?(Oe*S).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!S||S<=0?"$0.00":Oe.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[Oe,S,De]),Ue=c.useMemo(()=>{if(!ht)return null;const X=parseFloat(ht.replace(/,/g,""));return De&&S?(X*S).toLocaleString(void 0,{maximumFractionDigits:2}):S?(X*S).toLocaleString(void 0,{maximumFractionDigits:2}):null},[ht,S,De]),Gt=c.useCallback(X=>{te(ce=>({asset:X,amount:ce?.asset?.address===X.address&&ce?.asset?.chainId===X.chainId&&ce.amount||""})),Y(null),ge(null),re(!1),Me(null),d?.setSelectedAsset&&d.setSelectedAsset({symbol:X.symbol,address:X.address,decimals:X.decimals,chainId:X.chainId})},[d?.setSelectedAsset]),Vt=c.useCallback(X=>{te(ce=>ce&&{...ce,amount:X}),Y(null),ge(null),re(!1),Me(null),i&&i.setAssetAmount(X),d&&d.setAssetAmount(X)},[i,d]),Dt=c.useCallback(X=>{if(typeof o=="function"){if(!W?.asset||!W.amount)throw new Error("Select an asset and enter an amount");return o({asset:W.asset,amount:X?.amount??W.amount,amountWei:X?.amountWei??j.parseUnits(W.amount,W.asset.decimals),grossAmount:X?.grossAmount,grossAmountWei:X?.grossAmountWei,feeAdjusted:!!X})}return o},[o,W]),_=c.useRef(null),ee=c.useMemo(()=>!W?.asset||Oe<=0?!1:U?!De&&!w:!0,[W,Oe,U,De,w]),Ie=c.useCallback(()=>Zi(_.current),[]);c.useEffect(()=>{if(!e||ye)return;if(!W?.asset||Oe<=0){ge(null),ne(!1),re(!1),Me(null);return}if(!ee){ge(null),ne(!1),re(!0),Me(null);return}let X=!1;const ce=async()=>{const ze=++le.current;ge(null),re(!1),ne(!0);try{const ut=await Ie();if(X||le.current!==ze)return;ge(null),re(!0),Me(ut)}catch(ut){if(X||le.current!==ze)return;ge(f.sanitizeError(ut,"Unable to calculate fees for this lock.")),re(!1)}finally{!X&&le.current===ze&&ne(!1)}},Fe=window.setTimeout(()=>{ce()},250),Ee=window.setInterval(()=>{ce()},1e4);return()=>{X=!0,clearTimeout(Fe),window.clearInterval(Ee),ne(!1),re(!1)}},[e,ye,W,Oe,ee,Ie]),c.useEffect(()=>{if(Je?.overallStatus==="success"){const X=Je.steps.find(ce=>ce.transactionHash);y?.(X?.transactionHash)}},[Je?.overallStatus,y]);const Qe=x&&W?.asset?._source==="wallet"&&W?.asset?.chainId===l,Ye=c.useCallback(()=>Yi(_.current),[]),Ke=!!W?.asset&&Oe>0&&!Et&&!ye&&(!ee||Q&&!be&&!ae),Ve=se||ae,We=n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[n.jsx(Ss,{color:P}),n.jsxs("p",{style:{fontSize:"13px",color:P,margin:0,lineHeight:"1.5"},children:["Add ",r," by converting assets from your account"]})]});if(_.current={selectedAsset:W,parsedAmount:Oe,selectedDuration:ct,isInsufficientBalance:Et,isSemi7702:U,isSourceDestToken:De,isDirectDeposit:Qe,requiresRelayerFeeEstimate:ee,address:Se,embeddedWalletAddress:At,providerEmbeddedAddress:Ct,externalWallet:$t,externalWalletAddress:he,isConnected:gt,ready:Lt,authenticated:Tt,provider:Mt,actions:Jt,lockChainId:l,escrowAddress:g,onLockExecute:w,onLockSuccess:y,buildSpicenetBatch:I,resolveLockBatches:Dt,startStatusPolling:wt,refreshSpiceAssets:et,refreshWalletAssets:Ht,ui:{setError:Y,setIsExecuting:z,setShowStatusPanel:Xe}},!e)return null;const Pe={backgroundColor:N,border:K,borderRadius:L,padding:"16px",marginBottom:"16px"};return n.jsx(sn,{isOpen:e,onClose:t,title:`Add ${r} to your account`,subtitle:We,styles:C,dark:M,footerLinkText:"Spicenet accounts \u2192",overlayContent:xe?n.jsx("div",{}):void 0,closeOnBackdropClick:s,children:n.jsxs("div",{style:{padding:"0 24px 8px 24px",position:"relative"},children:[n.jsxs("div",{style:{marginBottom:"12px"},children:[k&&n.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:n.jsx(Is,{onClick:k,color:T,fontFamily:B})}),n.jsx("div",{style:{marginTop:"10px",fontSize:"13px",color:P,fontFamily:B},children:n.jsx(Un,{assets:Re,selectedAsset:W??void 0,onAssetSelect:Gt,onAmountChange:Vt,label:"Amount",showBalance:!0,showMaxButton:!0,theme:me,styles:G})}),n.jsx("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:P,fontFamily:B},children:Qt})]}),n.jsxs("div",{style:Pe,children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:M?`1px solid ${v.cardBorder}`:"1px solid #e5e7eb"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[a?n.jsx("img",{src:a,alt:r,style:{width:"32px",height:"32px",borderRadius:"50%",objectFit:"cover"}}):n.jsx("div",{style:{width:"32px",height:"32px",borderRadius:"50%",backgroundColor:M?v.inputBg:"#d1d5db",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:700,color:V},children:r.slice(0,2)}),n.jsx("span",{style:{fontSize:"16px",fontWeight:600,color:V,fontFamily:B},children:r})]}),n.jsxs("div",{style:{textAlign:"right"},children:[n.jsx("div",{style:{fontSize:"22px",fontWeight:700,color:V,fontFamily:B,lineHeight:1.1},children:ht??"0.00"}),n.jsxs("div",{style:{fontSize:"12px",color:P,fontFamily:B,marginTop:"2px"},children:["~$",Ue??"0.00"]})]})]}),n.jsxs("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:M?`1px solid ${v.cardBorder}`:"1px solid #e5e7eb"},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[n.jsx("span",{style:{fontSize:"15px",fontWeight:500,color:P,fontFamily:B},children:"Lock Duration"}),n.jsx(on,{color:P})]}),n.jsx(Di,{options:h,selectedIndex:je,onSelect:pe,primaryColor:T,dark:M,textPrimary:V,textSecondary:P})]}),n.jsxs("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[n.jsx(Ui,{durationMonths:ct?.months,fontFamily:B,dark:M,textPrimary:V,textSecondary:P}),p&&n.jsx(Wi,{votes:nt,fontFamily:B,dark:M,textPrimary:V,textSecondary:P})]})]}),ee&&n.jsx(qn,{fontFamily:B,textPrimary:V,textSecondary:P,cardBg:N,cardBorder:K,resolvedDark:M,darkCardBorder:v.cardBorder,primaryColor:T,feePreview:we,isLoading:be,errorText:ae}),Ve&&n.jsx(In,{variant:"error",palette:v,fontFamily:B,style:{marginBottom:"12px"},children:Ve}),n.jsx(f.Button,{variant:"outline",fullWidth:!0,onClick:Ye,disabled:!Ke,loading:ye,dark:M,styles:{...C,button:{...C?.button,backgroundColor:T}},children:ye?Qe&&!De?"DEPOSITING...":De?"LOCKING...":"CONVERTING...":be&&ee?"CALCULATING FEES...":Qe&&!De?`DEPOSIT ${r}`:De?`LOCK ${r}`:`CONVERT TO ${r}`}),n.jsx(Pi,{isOpen:xe,data:Le,isLocking:ye,lockError:Ve,onContinue:Ye,onClose:()=>fe(!1),primaryColor:T,fontFamily:B,dark:M}),Je&&at&&n.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:M?"rgba(0, 0, 0, 0.45)":"rgba(255, 255, 255, 0.55)",backdropFilter:"blur(2px)",WebkitBackdropFilter:"blur(2px)",borderRadius:L},children:n.jsx(Bs,{type:"deposit",showStepBreakdown:!1,isOpen:!!Je&&Je.overallStatus!=="processing",isProcessing:ye||Je?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{qe(),Xe(!1),Ye()},onNewTx:()=>{qe(),Xe(!1),te(null),dt.current=null,et(),Ht()},onClose:()=>{qe(),Xe(!1)},onComplete:()=>{qe(),Xe(!1),te(null),dt.current=null,et(),Ht()},results:Je?.overallStatus==="success"||Je?.overallStatus==="failed"?Je.steps.map(X=>({asset:{symbol:W?.asset?.symbol||r,address:W?.asset?.address||""},txHash:X.transactionHash||"",success:X.status==="success",amount:W?.amount})):void 0,chainName:f.getChainName(l),explorerUrl:f.getExplorerUrl(l,"").replace(/\/tx\/.*$/,"")||void 0,theme:A,styles:C,dark:M})})]})})},Xi="0xa9059cbb";function Ji(e,t,s){return F.isNativeToken(e)?{to:s,value:t,data:"0x"}:{to:e,value:0n,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"transfer",args:[s,t]})}}function qs(e,t,s,o){return t!=="user-transfer"||!s||e.length===0||e[0]?.to.toLowerCase()!==o.toLowerCase()||!e[0]?.data.startsWith(Xi)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function ss(e,t,s){if(!t)return[e];const o=await t(s);return o?[o,e]:[e]}function yn(e){return e.filter(t=>t.domain!=="spicenet")}function os(e){const t=(e.tokenTransfers??[]).filter(s=>s.from==="escrow").map(s=>({token:F.normalizeNativeTokenAddress(s.token),recipient:s.to,amount:BigInt(s.amount)})).filter(s=>s.amount>0n);return t.length>0?t:void 0}function jn(e,t,s){if(t===s)return e;if(t<s)return e*10n**BigInt(s-t);const o=10n**BigInt(t-s);return(e+o-1n)/o}async function $i(e,t){const{currentPaymentAmount:s,destinationToken:o,embeddedWalletAddress:r,providerEmbeddedAddress:a,address:i,isNon7702:d,isPayMode:u,resolvedChainId:l,buildActionCalls:h,feeExecutionMode:p,buildSpicenetBatch:g,selectedAsset:x,needsSwap:m,exactOutputSwap:y,resolvedTokenIn:w}=e,S=j.parseUnits(s,o.decimals),b=t?.actionAmountOverride??S,k=r||a||(d?void 0:i);if(!k)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const I={userAddress:k,chainId:l,destinationToken:o.address,grossAmount:t?.fundingAmountOverride??S,netAmount:b,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:p,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},C=h(b,I),E={chainId:l,calls:C},A=(!u&&!d?!0:x?.asset?._source==="spice")||d,M=(T,v)=>({token:T,from:d?"solver":"escrow",to:k,amount:v});if(S===0n)return[E];if(m&&y){const T=w??tn(x.asset,l)??x.asset.address,v=t?.fundingAmountOverride??y.amountInMax,B=A?[M(T,v)]:[],D={to:T,value:0n,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"approve",args:[y.calls[0]?.to,y.amountInMax]})},R={chainId:l,calls:[D,...y.calls,...C],tokenTransfers:[...B,...E.tokenTransfers??[]]};return A?ss(R,g,{userAddress:k,destinationChainId:l,deliveryToken:T,deliveryAmount:v,deliveryRecipient:k,deliveryTransfers:os(R),sourceAsset:x.asset}):[R]}if(A){const T=w??tn(x.asset,l)??o.address,v=t?.fundingAmountOverride??S,B={...E,tokenTransfers:[M(T,v),...E.tokenTransfers??[]]};return ss(B,g,{userAddress:k,destinationChainId:l,deliveryToken:T,deliveryAmount:v,deliveryRecipient:k,deliveryTransfers:os(B),sourceAsset:x.asset})}return[E]}async function _i(e,t){const{selectedAsset:s,embeddedWalletAddress:o,externalWalletAddress:r,resolvedChainId:a,destinationToken:i,buildActionCalls:d,feeExecutionMode:u,buildSpicenetBatch:l,isPayMode:h,isNon7702:p,needsSwap:g,resolvedSwap:x,quoteAmountOut:m,resolvedTokenIn:y}=e,w=x?.amountOutMinimum??m;if(!s?.asset||!o)return[];const S=p?r:o;if(!S)return[];const b=t?.fundingAmountOverride??t?.actionAmountOverride??j.parseUnits(s.amount,s.asset.decimals),k=t?.fundingAmountOverride??b,I=t?.sourceFundingAmountOverride??b,C=t?.deliveryAmountOverride??k,E=t?.withdrawalAmountOverride??C,A=t?.actionAmountOverride??b,M={userAddress:S,chainId:a,destinationToken:i.address,feeToken:u==="user-transfer"&&g&&y?y:i.address,grossAmount:k,netAmount:A,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:u,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},T=d(A,M),v=s.asset?._source==="wallet";if(!h&&p&&v&&s.asset.chainId===a){if(g){if(!y)throw new Error("Swap input token could not be resolved");if(!x||w===null)throw new Error("Swap quote not available yet")}if(g&&x&&w){const K=d(t?.actionAmountOverride??w,{...M,netAmount:t?.actionAmountOverride??w}),{feeCall:L,remainingCalls:V}=qs(K,u,g,M.feeToken);return[{chainId:a,calls:[...L?[L]:[],...x.calls,...V]}]}return[{chainId:a,calls:T}]}if(!h&&!p&&v){if(s.asset.chainId===a){if(g){if(!y)throw new Error("Swap input token could not be resolved");if(!x||w===null)throw new Error("Swap quote not available yet")}if(g&&x&&w){const K=d(t?.actionAmountOverride??w,{...M,netAmount:t?.actionAmountOverride??w}),{feeCall:L,remainingCalls:V}=qs(K,u,g,M.feeToken);return[{chainId:a,calls:[...L?[L]:[],...x.calls,...V]}]}return[{chainId:a,calls:T}]}throw new Error("Cross-chain wallet supplies require external wallet mode")}const B=!h&&!p?s.asset?._source!=="wallet":s.asset?._source==="spice",D=p&&v;if(!(B||D))return[{chainId:a,calls:T}];const R=D&&s.asset.chainId!==a?{chainId:s.asset.chainId,calls:[Ji(F.normalizeNativeTokenAddress(s.asset.address),I,F.getEscrowContractAddress(s.asset.chainId))]}:null,O=(K,L)=>({token:K,from:D?"solver":"escrow",to:o,amount:L}),U=(K,L)=>D?[{token:K,from:"escrow",to:F.SPICE_SOLVER_ADDRESS,amount:L}]:[];if(g){if(!y)throw new Error("Swap input token could not be resolved");if(!x||w===null)throw new Error("Swap quote not available yet")}if(g&&x&&w&&y){const K=d(t?.actionAmountOverride??w,{...M,netAmount:t?.actionAmountOverride??w}),{feeCall:L,remainingCalls:V}=qs(K,u,g,M.feeToken),P={chainId:a,calls:[...L?[L]:[],...x.calls,...V],tokenTransfers:[...U(y,E),O(y,C)]},G=await ss(P,l,{userAddress:o,destinationChainId:a,deliveryToken:y,deliveryAmount:C,withdrawalAmount:E,deliveryRecipient:o,deliveryTransfers:os(P),sourceAsset:s.asset});return R?[R,...G]:G}const H=y??tn(s.asset,a)??i.address,q={chainId:a,calls:T,tokenTransfers:[...U(H,E),O(H,C)]},N=await ss(q,l,{userAddress:o,destinationChainId:a,deliveryToken:H,deliveryAmount:C,withdrawalAmount:E,deliveryRecipient:o,deliveryTransfers:os(q),sourceAsset:s.asset});return R?[R,...N]:N}async function el(e,t,s,o,r){let a=e;for(let i=0;i<4;i++){const d=await t(a),u=await o(d,s,a,r),l=li(u);if(l===null||l>=e)return a;const h=a-l,p=e+h;if(p<=a)return a;a=p}return a}function tl(e,t,s,o){if(e<=0n)return 0n;const r=e-t;if(r<=0n)return 0n;const a=o+s;return a<=0n?r:r*o/a}function nl(e,t){const s=j.formatUnits(e,t);return s.includes(".")?s.replace(/\.?0+$/,"")||"0":s}async function sl(e){const{asset:t,isPayMode:s,isNon7702:o,needsSwap:r,isQuoting:a,embeddedWalletAddress:i,buildSupplyChainBatches:d,estimateGasless:u,executionTokenAddress:l,feeExecutionMode:h}=e;if(s||o||r||a||!i||t.balance<=0n)return null;const p=i,g=await d({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(g.length===0)return null;const x=g.some(k=>k.tokenTransfers?.length),m=await u(g,l,t.balance,x?{userOverride:p,useCustomTransfers:!0,feeExecutionMode:h}:h?{userOverride:p,feeExecutionMode:h}:{userOverride:p}),y=cn(m,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),w=y?jn(y.gasFee,y.decimals,t.decimals):0n,S=y?jn(y.spicenetFee,y.decimals,t.decimals):0n,b=tl(t.balance,w,S,t.balance);return b>0n?nl(b,t.decimals):null}async function ol(e){const{selectedAsset:t,isPayMode:s,parsedAmount:o,needsSwap:r,exactOutputSwap:a,isNon7702:i,isSourceDestToken:d,currentPaymentAmount:u,destinationToken:l,feeExecutionMode:h,resolvedTokenIn:p,embeddedWalletAddress:g,providerEmbeddedAddress:x,resolvedChainId:m,isConnected:y,address:w,ready:S,authenticated:b,isDirect:k,resolvedSwap:I,isQuoting:C,executionTokenAddress:E,buildPayChainBatches:A,buildSupplyChainBatches:M,estimateGasless:T,estimateRequiredGrossFunding:v}=e;if(!t?.asset)return null;if(s){if(o<=0||r&&!a||i&&d)return null;const N=j.parseUnits(u,l.decimals),K=p||tn(t.asset,m)||t.asset.address||l.address,L={chainId:m,tokenAddress:K,symbol:F.getTokenByAddress(K,m)?.symbol??t.asset.symbol,decimals:F.getTokenByAddress(K,m)?.decimals??t.asset.decimals};if(i){const te=g||x;if(!te)return null;const ue=te,Ce=r?a?.amountInMax??0n:N;if(Ce===0n)return null;const je=await v(Ce,z=>A({fundingAmountOverride:z}).then(se=>zt(yn(se),ue)),K,{userOverride:te,useCustomTransfers:!0}),pe=zt(yn(await A({fundingAmountOverride:je})),ue),ye=await T(pe,K,je,{userOverride:te,useCustomTransfers:!0,feeExecutionMode:h});return cn(ye,L)}if(!y||!w||!S||!b)return null;const V=g||x||w,P=r?a?.amountInMax??0n:N;if(P===0n)return null;const G=await v(P,te=>A({fundingAmountOverride:te}).then(ue=>zt(yn(ue),V)),K,{useCustomTransfers:!0});let me=zt(yn(await A({fundingAmountOverride:G})),V);const W=await T(me,K,G,{useCustomTransfers:!0,feeExecutionMode:h});return cn(W,L)}if(o<=0||!g)return null;const B=g||x;if(!(!s&&!i&&t.asset?._source==="wallet"&&t.asset.chainId!==m)&&!k&&!I&&!C||C)return null;const D=j.parseUnits(t.amount,t.asset.decimals),R=await M();if(R.length===0)return null;const O=i&&t.asset?._source==="wallet"&&t.asset.chainId===m,U={chainId:m,tokenAddress:E,symbol:F.getTokenByAddress(E,m)?.symbol??l.symbol,decimals:F.getTokenByAddress(E,m)?.decimals??l.decimals};if(O){const N=await f.relayerService.estimateBatchGas({user:B,outputToken:E,stepIndex:0,chainBatches:R}),K=$n(D,10n),L=K+N.gasFee;return{...U,grossAmount:D+L,netAmount:D,totalFee:L,gasFee:N.gasFee,spicenetFee:K,bridgeFee:0n,gasQuoteSource:N.gasQuoteSource}}const H=R.some(N=>N.tokenTransfers?.length),q=await T(R,E,D,H?{userOverride:B,useCustomTransfers:!0,feeExecutionMode:h}:h?{userOverride:B,feeExecutionMode:h}:{userOverride:B});return cn(q,U)}const rl=10n;function er(e,t){const s=e.selectedAsset?.asset;if(!s||s?._source!=="wallet")return;const o=tn(s,e.resolvedChainId);if(!o||!f.addressesEqual(o,e.executionTokenAddress))return;const r=F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),a=jn(t,r?.decimals??e.destinationToken.decimals,s.decimals);if(a<=s.balance)return;const i=j.formatUnits(a,s.decimals),d=j.formatUnits(s.balance,s.decimals);throw new Error(`Insufficient ${s.symbol} for amount plus fees. Required ${i} ${s.symbol}; available ${d} ${s.symbol}.`)}function tr(e){const t=F.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 nr(e,t,s){const o=cn(e,tr(t));if(!o)return;const r=$n(s,rl),a=o.bridgeFee??0n,i=r+o.gasFee+a;return{grossAmount:s+i,netAmount:s,combinedFeeAmount:i,feeExecutionMode:"user-transfer",feeBreakdown:{spicenetFee:r,gasFee:o.gasFee,bridgeFee:a}}}function Fn(e,t,s){if(e===t)return!0;const o=e>t?e:t;return o===0n?!1:(e>t?e-t:t-e)*10000n<=o*s}function sr(e,t,s){let o=0n,r=0n;const a=s.toLowerCase();for(const i of e)if(i.chainId===t){for(const d of i.calls??[])if(d.to.toLowerCase()===a)try{const u=j.decodeFunctionData({abi:j.erc20Abi,data:d.data});if(u.functionName!=="transfer")continue;const l=u.args[0].toLowerCase(),h=u.args[1];l===F.SPICE_PLATFORM_FEE_RECIPIENT.toLowerCase()?o+=h:l===F.SPICE_GAS_FEE_RECIPIENT.toLowerCase()&&(r+=h)}catch{continue}}return{spicenetFee:o,gasFee:r}}function al(e,t,s){const o=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,r=sr(e,t.resolvedChainId,o);return r.spicenetFee===0n&&s.feeBreakdown.spicenetFee>0n||r.gasFee===0n&&s.feeBreakdown.gasFee>0n?!1:Fn(r.spicenetFee,s.feeBreakdown.spicenetFee,100n)&&Fn(r.gasFee,s.feeBreakdown.gasFee,100n)}function il(e,t){return e?Fn(e.grossAmount,t.grossAmount,100n)&&Fn(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&Fn(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&Fn(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}async function ll(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){if(!e.externalWalletAddress){e.ui.setError("Please connect your external 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 or(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 cl(e,s.signal)}e.ui.setStep("success"),e.ui.setStatusMsg(e.isSourceDestToken?"Transaction confirmed":"Deposit confirmed")}catch(s){const o=s instanceof Error?s:new Error(String(s));if(o.name==="AbortError"||e.refs.abortControllerRef.current?.signal.aborted){e.ui.setStep("idle");return}const r=o.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(r),e.ui.setError(r),e.onError?.(o)}finally{e.ui.setIsExecuting(!1)}return}if(!e.embeddedWalletAddress){e.ui.setError("Wallet not ready");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.ui.setTxHash(null),e.refs.spiceDepositSubmittedRef.current=!1;const t=new AbortController;e.refs.abortControllerRef.current=t;try{const s=j.parseUnits(e.selectedAsset.amount,e.selectedAsset.asset.decimals),o=s;let r=await e.gasless.buildSupplyChainBatches();const a=e.selectedAsset.asset?._source==="wallet",i=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!a&&!r.some(x=>F.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=s;const l=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,h=e.feeExecutionMode==="user-transfer"&&!l?o:void 0;let p;for(let x=0;x<4;x+=1){const m=await e.gasless.estimateGasless(r,e.executionTokenAddress,u,d),y=cn(m,tr(e));p=e.feeExecutionMode==="user-transfer"&&y?nr(m,e,o):void 0;const w=p?.grossAmount??y?.grossAmount??u;if(w===u){u=w;break}u=w,r=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:h,actionContextOverride:p})}e.feeExecutionMode==="user-transfer"&&(er(e,u),r=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:h,actionContextOverride:p}));let g=p;await e.gasless.executeGasless(r,e.executionTokenAddress,u,e.gasless.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...d,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:x,chainBatches:m})=>{const y=nr(x,e,o);if(!y)return null;const w=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&e.resolvedTokenIn?e.resolvedTokenIn:e.executionTokenAddress;sr(m,e.resolvedChainId,w);const S=il(g,y),b=al(m,e,y);return S||b?null:(g=y,e.gasless.buildSupplyChainBatches({fundingAmountOverride:y.grossAmount,actionAmountOverride:h,actionContextOverride:y}))}}:d),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(s){const o=s instanceof Error?s:new Error(String(s));if(o.name==="AbortError"||t.signal.aborted){e.ui.setStep("idle");return}const r=o.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(r),e.ui.setError(r),e.onError?.(o)}finally{e.ui.setIsExecuting(!1)}}async function cl(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 s=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!s)throw new Error("Embedded wallet not available \u2014 sign in to create one before supplying");const o=e.selectedAsset.asset,r=j.parseUnits(e.selectedAsset.amount,o.decimals),a=r,i=o?._source==="wallet"&&o.chainId===e.resolvedChainId;let d=await e.gasless.buildSupplyChainBatches();const u={userOverride:s,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode};let l=r;const h=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,p=e.feeExecutionMode==="user-transfer"&&!h?a:void 0;let g;if(i){const M=await f.relayerService.estimateBatchGas({user:s,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:d}),T=$n(r,10n),v=T+M.gasFee;l=r+v,e.feeExecutionMode==="user-transfer"&&(g={grossAmount:l,netAmount:a,combinedFeeAmount:v,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:T,gasFee:M.gasFee,bridgeFee:0n}})}else{const M=await e.gasless.estimateGasless(d,e.executionTokenAddress,0n,u),T=cn(M,{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId)?.symbol??e.destinationToken.symbol,decimals:F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId)?.decimals??e.destinationToken.decimals});T&&(l=T.grossAmount>r?T.grossAmount:r,e.feeExecutionMode==="user-transfer"&&(g={grossAmount:l,netAmount:a,combinedFeeAmount:T.totalFee,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:T.spicenetFee,gasFee:T.gasFee,bridgeFee:T.bridgeFee??0n}}))}const x=F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),m=i?l:jn(l,x?.decimals??e.destinationToken.decimals,o.decimals);er(e,l),d=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:l,sourceFundingAmountOverride:m,withdrawalAmountOverride:l,actionAmountOverride:p,actionContextOverride:g});const y=o.chainId,w=s,S=await e.externalWallet.getEthereumProvider();let b=null;try{const M=await S.request({method:"eth_chainId"});b=parseInt(M,16)}catch{b=null}b!==y&&(e.ui.setStatusMsg("Switching source network..."),await f.ensureWalletOnChain(S,y));const k=f.getChainConfig(y),I=j.createWalletClient({account:e.externalWalletAddress,chain:k?.viemChain,transport:j.custom(S)}),C=F.normalizeNativeTokenAddress(o.address),E=o.isNative||F.isNativeToken(C);e.ui.setStatusMsg("Funding embedded wallet...");const A=E?await I.sendTransaction({to:w,value:m,chain:k?.viemChain}):await I.sendTransaction({to:C,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"transfer",args:[w,m]}),chain:k?.viemChain});if((await f.getClientForChain(y).waitForTransactionReceipt({hash:A,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Embedded wallet funding failed");e.ui.setStatusMsg("Signing supply intent..."),await e.gasless.executeGasless(d,e.executionTokenAddress,0n,e.gasless.onProgress,t,u)}async function or(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=j.parseUnits(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),s={userAddress:e.externalWalletAddress,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},o=e.buildActionCalls(t,s);if(o.length===0)throw new Error("No action calls configured");const r=await e.externalWallet.getEthereumProvider();let a=null;try{const h=await r.request({method:"eth_chainId"});a=parseInt(h,16)}catch{a=null}a!==e.resolvedChainId&&await f.ensureWalletOnChain(r,e.resolvedChainId);const i=f.getChainConfig(e.resolvedChainId),d=j.createWalletClient({account:e.externalWalletAddress,chain:i?.viemChain,transport:j.custom(r)}),u=f.getClientForChain(e.resolvedChainId);let l;for(const h of o){const p=await d.sendTransaction({to:h.to,data:h.data,value:h.value,chain:i?.viemChain});if((await u.waitForTransactionReceipt({hash:p,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transaction failed");l=p}return l}async function dl(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 s=e.selectedAsset.asset,o=s.chainId,r=j.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),a=e.selectedIsEquivalent?r:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(a===0n)throw new Error("Quote not available yet");const i=e.resolvedTokenIn||e.selectedAsset.asset.address,d={userOverride:t,useCustomTransfers:!0},u=await e.gasless.estimateRequiredGrossFunding(a,b=>e.gasless.buildPayChainBatches({fundingAmountOverride:b}),i,d),l=F.getEscrowContractAddress(o),h=await e.externalWallet.getEthereumProvider();let p=null;try{const b=await h.request({method:"eth_chainId"});p=parseInt(b,16)}catch{p=null}p!==o&&await f.ensureWalletOnChain(h,o);const g=f.getChainConfig(o),x=j.createWalletClient({account:e.externalWalletAddress,chain:g?.viemChain,transport:j.custom(h)}),m=F.normalizeNativeTokenAddress(s.address),y=s.isNative||F.isNativeToken(m)?await x.sendTransaction({to:l,value:u,chain:g?.viemChain}):await x.sendTransaction({to:m,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"transfer",args:[l,u]}),chain:g?.viemChain});if((await f.getClientForChain(o).waitForTransactionReceipt({hash:y,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Escrow deposit failed");const w=await e.gasless.buildPayChainBatches({fundingAmountOverride:u}),S=w.some(b=>b.tokenTransfers?.length);return await e.gasless.executeGasless(w,i,u,b=>{b.txHash&&(e.ui.setPaymentResult(k=>({...k??{status:"processing"},txHash:b.txHash})),e.ui.setTxHash(b.txHash))},void 0,S?d:{userOverride:t})}async function ul(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}if(!e.selectedAsset?.asset){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){if(!e.externalWalletAddress){e.ui.setError("Please connect your external wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{let t;if(e.isSourceDestToken||e.parsedAmount===0)t=await or(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const s=e.selectedAsset.asset,o=j.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),r=e.selectedIsEquivalent?o:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(r===0n)throw new Error("Quote not available yet");const a=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!a)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const i=e.resolvedTokenIn||s.address,d=await e.gasless.estimateRequiredGrossFunding(r,h=>e.gasless.buildPayChainBatches({fundingAmountOverride:h}),i,{userOverride:a,useCustomTransfers:!0}),u=await e.gasless.buildPayChainBatches({fundingAmountOverride:d}),l=await e.onPayExecute({asset:s,amount:e.currentPaymentAmount,amountWei:o,destinationToken:e.destinationToken,chainBatches:u,requiredNetFunding:r,grossFundingAmount:d,selectedIsEquivalent:e.selectedIsEquivalent,resolvedTokenIn:i,exactOutputSwapAmountInMax:e.exactOutputSwap?.amountInMax});l&&(e.ui.setTxHash(l),e.ui.setPaymentResult(h=>({...h??{status:"processing"},txHash:l}))),t=l||void 0}else t=await dl(e);e.ui.setPaymentResult(s=>({status:"success",txHash:s?.txHash||t||""}))}catch(t){const s=f.sanitizeError(t,"Payment failed. Please try again.");e.ui.setError(s),e.ui.setPaymentResult({status:"failed",error:s}),e.onError?.(t instanceof Error?t:new Error(s))}finally{e.ui.setIsExecuting(!1)}return}if(!e.isConnected||!e.address){e.ui.setError("Please connect your wallet to continue");return}if(!e.ready||!e.authenticated){e.ui.setError(`Please authenticate with ${e.provider||"wallet provider"} to continue`);return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{const t=j.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),s=e.resolvedTokenIn||e.selectedAsset?.asset?.address||e.destinationToken.address,o=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:t,r={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode},a=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,i=await e.gasless.estimateRequiredGrossFunding(o,x=>e.gasless.buildPayChainBatches({fundingAmountOverride:x}).then(m=>zt(yn(m),a)),s,r);let d=i,u=zt(yn(await e.gasless.buildPayChainBatches({fundingAmountOverride:i})),a);const l=await e.gasless.estimateGasless(u,s,i,r),h=cn(l,{chainId:e.resolvedChainId,tokenAddress:s,symbol:F.getTokenByAddress(s,e.resolvedChainId)?.symbol??e.selectedAsset.asset.symbol,decimals:F.getTokenByAddress(s,e.resolvedChainId)?.decimals??e.selectedAsset.asset.decimals})?.grossAmount??i;h!==i&&(d=h),u=zt(yn(await e.gasless.buildPayChainBatches({fundingAmountOverride:d})),a,l,{payoutAlreadyGross:!0});const p=u.some(x=>x.tokenTransfers?.length),g=await e.gasless.executeGasless(u,s,p?d:0n,x=>{x.txHash&&(e.ui.setPaymentResult(m=>({...m,txHash:x.txHash})),e.ui.setTxHash(x.txHash))},void 0,r);e.ui.setPaymentResult(x=>({status:"success",txHash:x?.txHash||g}))}catch(t){const s=f.sanitizeError(t,"Payment failed. Please try again.");e.ui.setError(s),e.ui.setPaymentResult({status:"failed",error:s}),e.onError?.(t instanceof Error?t:new Error(s))}finally{e.ui.setIsExecuting(!1)}}const rr=({variant:e,destinationSymbol:t,destinationLogoURI:s,destinationDecimals:o,primaryColor:r,fontFamily:a,textPrimary:i,textSecondary:d,cardBg:u,cardBorder:l,dk:h,dark:p,isQuoting:g,quoteError:x,estimatedOutput:m,paymentAmount:y,needsSwap:w,exactOutputSwap:S,adjustable:b=!1,maxAmount:k,onAmountChange:I})=>e==="supply"?n.jsxs("div",{style:{backgroundColor:u,border:`1px solid ${l}`,borderRadius:p?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",minHeight:"112px",display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"12px"},children:[n.jsxs("div",{style:{minWidth:0},children:[n.jsx("span",{style:{fontFamily:a,fontSize:"17px",fontWeight:500,color:p?"#a7abb2":"#7D7C7B",lineHeight:"24px"},children:"Used in TX"}),n.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:d,fontFamily:a,marginTop:"10px"},children:"Net amount after swap and fees"})]}),n.jsxs("div",{style:{textAlign:"right",minWidth:0,display:"inline-flex",alignItems:"center",gap:"8px",border:`1px solid ${l}`,borderRadius:"8px",padding:"8px 10px",minHeight:"42px"},children:[n.jsx(ar,{symbol:t,logoURI:s,primaryColor:r,size:24}),n.jsx("span",{style:{fontSize:"16px",fontWeight:500,color:p?"#f3f4f6":"#3C3E42",lineHeight:"1.3",fontFamily:a,letterSpacing:0},children:t})]})]}),n.jsx("div",{style:{textAlign:"right",minWidth:0},children:g?n.jsx("span",{style:{fontSize:"18px",color:d,fontFamily:a},children:"Quoting..."}):x?n.jsx("span",{style:{fontSize:"13px",color:p?"#f87171":"#dc2626",fontFamily:a},children:"Quote failed"}):m?n.jsx(gn,{value:m,title:m,fontFamily:a,color:i,lineHeight:"0.95",textAlign:"right",maxFontSize:32,minFontSize:18}):n.jsx("span",{style:{fontSize:"20px",color:d,fontFamily:a},children:"\u2014"})})]}):n.jsx(pl,{destinationSymbol:t,destinationLogoURI:s,destinationDecimals:o,primaryColor:r,fontFamily:a,textPrimary:i,textSecondary:d,cardBg:u,cardBorder:l,dk:h,dark:p,paymentAmount:y||"0",needsSwap:w,exactOutputSwap:S,isQuoting:g,adjustable:b,maxAmount:k,onAmountChange:I}),ar=({symbol:e,logoURI:t,primaryColor:s,size:o})=>t?n.jsx("img",{src:t,alt:e,style:{width:o,height:o,borderRadius:"50%",objectFit:"cover"}}):n.jsx("div",{style:{width:o,height:o,borderRadius:"50%",backgroundColor:`${s}22`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:o<30?"11px":"12px",fontWeight:700,color:s},children:e.slice(0,2)}),pl=({destinationSymbol:e,destinationLogoURI:t,destinationDecimals:s,primaryColor:o,fontFamily:r,textPrimary:a,textSecondary:i,cardBg:d,cardBorder:u,dk:l,dark:h,paymentAmount:p,needsSwap:g,exactOutputSwap:x,isQuoting:m,adjustable:y,maxAmount:w,onAmountChange:S})=>{const b='"IBM Plex Mono", monospace',k=parseFloat(p||"0"),I=w?parseFloat(w):0,[C,E]=c.useState(p||""),A=c.useRef(null),[M,T]=c.useState(null),[v,B]=c.useState(null);c.useEffect(()=>{y||E(p||"")},[p,y]);const D=U=>{let H=U;H.startsWith(".")&&(H="0"+H);const q=kn(H);let N=q;w&&parseFloat(q)>parseFloat(w)&&(N=w),E(N),A.current&&clearTimeout(A.current),A.current=setTimeout(()=>S?.(N),300)},R=U=>{if(!I)return;if(U===100){E(w||I.toString()),A.current&&clearTimeout(A.current),S?.(w||I.toString());return}const H=10**s,q=Math.floor(I*U/100*H)/H,N=vn(q,s);E(N),A.current&&clearTimeout(A.current),S?.(N)},O=I>0?parseFloat(C||"0")/I*100:0;return c.useEffect(()=>()=>{A.current&&clearTimeout(A.current)},[]),n.jsxs("div",{style:{backgroundColor:d,border:`1px solid ${u}`,borderRadius:h?"12px":"6px",padding:"16px",marginBottom:"16px"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[n.jsx(ar,{symbol:e,logoURI:t,primaryColor:o,size:32}),n.jsxs("div",{children:[n.jsx("span",{style:{fontSize:"14px",fontWeight:600,color:a,fontFamily:r},children:"Payment"}),n.jsx("div",{style:{fontSize:"12px",color:i,fontFamily:r,marginTop:"2px"},children:e})]})]}),n.jsxs("div",{style:{textAlign:"right"},children:[y?n.jsx(gn,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:C,onChange:U=>D(U.target.value),placeholder:"0.0",fontFamily:b,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):n.jsx(gn,{element:"div",value:k>0?p:"0.00",title:k>0?p:"0.00",fontFamily:b,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),n.jsx("div",{style:{fontSize:"12px",color:i,fontFamily:b,marginTop:"2px"},children:e}),y&&I>0&&n.jsx("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((U,H)=>{const q=Math.abs(O-U)<1,N=H===4,K=U/100,L=M===U,V=v===U;return n.jsx("button",{onClick:()=>R(U),onMouseEnter:()=>T(U),onMouseLeave:()=>{T(null),B(null)},onMouseDown:()=>B(U),onMouseUp:()=>B(null),title:`${U}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:q?1:L?.8:.5,transform:V?"scale(0.85)":L?"scale(1.15)":"scale(1)",transition:Pt.interactive},children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[n.jsx("circle",{cx:"7",cy:"7",r:"6.84375",fill:N?o:"none",stroke:N?o:h?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!N&&K>0&&n.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${K>.5?1:0} 1 ${7+6.84375*Math.sin(K*2*Math.PI)} ${7-6.84375*Math.cos(K*2*Math.PI)} Z`,fill:h?l?.textSecondary||"#9ca3af":"#3C3E42"})]})},U)})})]})]}),g&&x&&!m&&n.jsx("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:h?`1px solid ${l?.cardBorder||u}`:"1px solid #e5e7eb",display:"flex",justifyContent:"flex-end"},children:n.jsxs("span",{style:{fontSize:"11px",color:i,fontFamily:r,opacity:.7},children:["via ",x.venue]})})]})};function ir(e,t,s){const o=f.addressesEqual(e.address,t),r=e.chainId===s,a=e._source==="wallet";return a&&o&&r?0:a&&r?1:!a&&o?2:!a&&r?3:4}function fl(e,t){return!t||t.length===0||t.some(s=>f.addressesEqual(s,e.address))?!0:Object.keys(e.chainTokens??{}).some(s=>{const o=En(s);return o?t.some(r=>f.addressesEqual(r,o.address)):!1})}function hl(e){const{destinationToken:t,supportedSourceAssets:s,sourceChains:o,enabled:r}=e,a=(c.useContext(f.SpiceFlowProviderContext)?.mode||"7702")!=="7702",i=f.useEmbeddedWalletAddress(),{externalAddress:d,embeddedAddress:u}=f.useProviderWallets(),l=i||u,{assets:h,refetch:p}=Pn({address:l,supportedChains:o,enabled:r&&!a&&!!l,refetchInterval:3e4}),g=c.useMemo(()=>a?[]:h.filter(A=>fl(A,s)),[h,s,a]),x=a?d:i,m=c.useMemo(()=>{const A=new Set,M=[],T=v=>{if(!v)return;const B=v.toLowerCase();A.has(B)||(A.add(B),M.push(j.getAddress(v)))};if(T(t.address),a&&s)for(const v of s)T(v);return M},[a,t.address,s]),y=c.useMemo(()=>m.map(A=>A.toLowerCase()).sort().join(","),[m]),w=c.useMemo(()=>JSON.stringify([...o||[]].sort()),[o]),[S,b]=c.useState([]),k=c.useRef(0),I=c.useRef(async()=>{}),C=c.useCallback(async()=>{if(!r||!x||m.length===0){k.current++,b([]);return}const A=++k.current,M=j.getAddress(x),T=a?o&&o.length>0?o:[t.chainId]:[t.chainId],v=[];for(const O of m){const U=O.toLowerCase();if(U===F.ZERO_ADDRESS)continue;if(U===t.address.toLowerCase()){const q=f.getChainConfig(t.chainId)?.supportedTokens?.find(N=>f.addressesEqual(N.address,U));v.push({address:O,chainId:t.chainId,configToken:q?{decimals:q.decimals,symbol:q.symbol,name:q.name,logo:q.logo}:void 0});continue}let H=!1;for(const q of T){const N=f.getChainConfig(q)?.supportedTokens?.find(K=>f.addressesEqual(K.address,U));if(N){v.push({address:O,chainId:q,configToken:{decimals:N.decimals,symbol:N.symbol,name:N.name,logo:N.logo}}),H=!0;break}}H||v.push({address:O,chainId:t.chainId})}const B=new Map;for(const O of v){const U=B.get(O.chainId)||[];U.push(O),B.set(O.chainId,U)}const D=async(O,U)=>{try{const H=await Ft.readContract(O,{address:U.address,abi:j.erc20Abi,functionName:"balanceOf",args:[M]});let q,N,K,L;if(U.configToken)q=U.configToken.decimals,N=U.configToken.symbol,K=U.configToken.name,L=U.configToken.logo;else{const[G,me,W]=await Promise.all([Ft.readContract(O,{address:U.address,abi:j.erc20Abi,functionName:"decimals"}).catch(()=>18),Ft.readContract(O,{address:U.address,abi:j.erc20Abi,functionName:"symbol"}).catch(()=>"TOKEN"),Ft.readContract(O,{address:U.address,abi:j.erc20Abi,functionName:"name"}).catch(()=>"TOKEN")]);q=Number(G),N=me,K=W}const V=f.addressesEqual(U.address,t.address)&&U.chainId===t.chainId;V&&t.logoURI&&(L=t.logoURI),V&&!U.configToken&&N==="TOKEN"&&(N=t.symbol,K=t.symbol);const P=parseFloat((Number(H)/Math.pow(10,q)).toFixed(6));return{address:U.address,name:K,symbol:N,decimals:q,balance:H,balanceFormatted:P,balanceUsd:0,logoURI:L,isNative:!1,chainId:U.chainId}}catch{return null}},R=await Promise.all(Array.from(B.entries()).map(async([O,U])=>{let H;try{H=f.getClientForChain(O)}catch{return[]}const q=[],N=[];for(const L of U){const V=q.length;q.push({address:L.address,abi:j.erc20Abi,functionName:"balanceOf",args:[M]}),L.configToken||q.push({address:L.address,abi:j.erc20Abi,functionName:"decimals"},{address:L.address,abi:j.erc20Abi,functionName:"symbol"},{address:L.address,abi:j.erc20Abi,functionName:"name"}),N.push({start:V,item:L})}let K=null;try{K=await H.multicall({contracts:q})}catch{K=null}return K?N.map(({start:L,item:V})=>{const P=K[L],G=P?.status==="success"?P.result:0n;let me,W,te,ue;if(V.configToken)me=V.configToken.decimals,W=V.configToken.symbol,te=V.configToken.name,ue=V.configToken.logo;else{const pe=K[L+1],ye=K[L+2],z=K[L+3];me=pe?.status==="success"?Number(pe.result):18,W=ye?.status==="success"?ye.result:"TOKEN",te=z?.status==="success"?z.result:W}const Ce=f.addressesEqual(V.address,t.address)&&V.chainId===t.chainId;Ce&&t.logoURI&&(ue=t.logoURI),Ce&&!V.configToken&&W==="TOKEN"&&(W=t.symbol,te=t.symbol);const je=parseFloat((Number(G)/Math.pow(10,me)).toFixed(6));return{address:V.address,name:te,symbol:W,decimals:me,balance:G,balanceFormatted:je,balanceUsd:0,logoURI:ue,isNative:!1,chainId:V.chainId}}):(await Promise.all(U.map(L=>D(H,L)))).filter(L=>L!==null)}));A===k.current&&b(R.flat())},[r,a,x,y,w,t.address,t.chainId,t.symbol,t.logoURI]);c.useEffect(()=>{I.current=C},[C]),c.useEffect(()=>{if(!r){b([]);return}I.current();const A=setInterval(()=>{I.current()},15e3);return()=>clearInterval(A)},[r,a,x,y,w,t.address,t.chainId]);const E=c.useCallback(()=>{C()},[C]);return{displayAssets:c.useMemo(()=>{const A=[],M=S.filter(v=>v.balance>0n);for(const v of M)A.push({...v,_source:"wallet"});for(const v of g)A.push({...v,_source:"spice"});const T=t.address.toLowerCase();return A.sort((v,B)=>ir(v,T,t.chainId)-ir(B,T,t.chainId)),A},[S,g,t.address,t.chainId]),filteredSpiceAssets:g,walletAssets:S,embeddedWalletAddress:l,externalAddress:d,isNon7702:a,refreshSpiceAssets:p,refreshWalletAssets:E}}async function lr(e){const{tokenIn:t,tokenOut:s,amountIn:o,fee:r,chainId:a,config:i}=e;if(o<=0n)throw new Error("amountIn must be greater than 0");const d=(await f.getClientForChain(a).simulateContract({address:i.quoterV2,abi:F.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:s,amountIn:o,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 cr(e){const t=e.feeTiers??[100,500,3e3,1e4],s=await Promise.allSettled(t.map(r=>lr({...e,fee:r})));let o=null;for(let r=0;r<s.length;r++){const a=s[r];a.status==="fulfilled"&&(!o||a.value.amountOut>o.amountOut)&&(o={...a.value,fee:t[r]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}const ml=[{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 gl(e){const{tokenIn:t,tokenOut:s,amountOut:o,fee:r,chainId:a,config:i}=e;if(o<=0n)throw new Error("amountOut must be greater than 0");const d=(await f.getClientForChain(a).simulateContract({address:i.quoterV2,abi:ml,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:s,amount:o,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 xl(e){const t=e.feeTiers??[100,500,3e3,1e4],s=await Promise.allSettled(t.map(r=>gl({...e,fee:r})));let o=null;for(let r=0;r<s.length;r++){const a=s[r];a.status==="fulfilled"&&(!o||a.value.amountIn<o.amountIn)&&(o={...a.value,fee:t[r]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}function dr(e){return e.type==="swap"}const Ks=.02,yl=[1,8453,42161,10,137,43114,56],Cl="https://api.1inch.dev/swap/v6.0";function ur(e,t){return F.applySlippage(e,t)}function pr(e){const t=e?.baseUrl??Cl;return{name:"1inch",chainIds:e?.chainIds??yl,resolve:async(s,o,r)=>{const a=s.maxSlippage??Ks,i=a*100,d=F.isNativeToken(s.tokenIn)?F.NATIVE_TOKEN_ADDRESS:s.tokenIn,u=F.isNativeToken(s.tokenOut)?F.NATIVE_TOKEN_ADDRESS:s.tokenOut,l=F.isNativeToken(s.tokenIn);try{const h=new URL(`${t}/${o}/swap`);h.searchParams.set("src",d),h.searchParams.set("dst",u),h.searchParams.set("amount",s.amountIn.toString()),h.searchParams.set("from",r),h.searchParams.set("slippage",i.toString()),h.searchParams.set("disableEstimate","true"),h.searchParams.set("allowPartialFill","false");const p={Accept:"application/json"};e?.apiKey&&(p.Authorization=`Bearer ${e.apiKey}`);const g=await fetch(h.toString(),{headers:p});if(!g.ok)throw new f.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${g.status} for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}`,{venue:"1inch",chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn.toString(),cause:`HTTP ${g.status}`});const x=await g.json();if(!x.dstAmount||!x.tx)return console.warn(`[1inchVenue] No route data for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}`),null;const m=BigInt(x.dstAmount);if(m<=0n)return console.warn(`[1inchVenue] Zero output for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}`),null;const y=ur(m,a),w=[];return x.tx.to&&!l&&w.push({to:s.tokenIn,value:0n,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"approve",args:[x.tx.to,s.amountIn]})}),w.push({to:x.tx.to,value:BigInt(x.tx.value||"0"),data:x.tx.data}),{venue:"1inch",amountOut:m,amountOutMinimum:y,calls:w}}catch(h){if(h instanceof f.SpiceflowError)throw h;const p=h instanceof Error?h.message:String(h);throw new f.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] Exception for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}: ${p}`,{venue:"1inch",chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn.toString(),cause:p})}}}}const fr=[4114,5115],Zs={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},hr={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[3e3]};function mr(e){return{name:"satsuma",chainIds:e.chainIds??fr,resolve:async(t,s,o)=>{const r=t.maxSlippage??Ks,a=F.isNativeToken(t.tokenIn);let i;try{i=await cr({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountIn:t.amountIn,chainId:s,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 ${s}.`),null}const d=ur(i.amountOut,r),u=[];return a||u.push({to:t.tokenIn,value:0n,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),u.push({to:e.swapRouter,value:a?t.amountIn:0n,data:j.encodeFunctionData({abi:F.uniV3SwapRouterAbi,functionName:"exactInputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:i.fee,recipient:o,amountIn:t.amountIn,amountOutMinimum:d,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:i.amountOut,amountOutMinimum:d,calls:u}}}}function gr(e){return{name:"satsuma",chainIds:e.chainIds??fr,resolve:async(t,s,o)=>{const r=t.maxSlippage??Ks,a=F.isNativeToken(t.tokenIn);let i;try{i=await xl({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountOut:t.amountOut,chainId:s,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,l=[];return l.push({to:e.swapRouter,value:a?u:0n,data:j.encodeFunctionData({abi:bl,functionName:"exactOutputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:i.fee,recipient:o,amountOut:t.amountOut,amountInMaximum:u,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:i.amountIn,amountInMax:u,amountOut:t.amountOut,calls:l}}}}const bl=[{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 xr(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(mr(e.satsuma)),t.push(pr(e?.oneInch));function s(r){return t.find(a=>a.chainIds.includes(r))}async function o(r,a,i){const d=[],u=[];for(const l of r){if(!dr(l)){d.push(l);continue}const h=s(a);if(!h)throw new f.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${a}. Cannot resolve swap ${l.tokenIn} \u2192 ${l.tokenOut}.`,{chainId:a,tokenIn:l.tokenIn,tokenOut:l.tokenOut,amountIn:l.amountIn.toString()});const p=await h.resolve(l,a,i);if(!p)throw new f.SpiceflowError("NO_LIQUIDITY",`${h.name} returned no quote for ${l.tokenIn} \u2192 ${l.tokenOut} on chain ${a}.`,{venue:h.name,chainId:a,tokenIn:l.tokenIn,tokenOut:l.tokenOut,amountIn:l.amountIn.toString()});d.push(...p.calls),u.push(p)}return{calls:d,resolvedSwaps:u}}return{resolveSwapIntents:o,getVenueForChain:s,venues:t}}function wl(e){const t=e?.customVenues??[];async function s(o,r,a){const i=t.filter(u=>u.chainIds.includes(r));if(i.length===0)throw new f.SpiceflowError("NO_SWAP_ROUTE",`No exact-output venue supports chain ${r}`,{chainId:r,tokenIn:o.tokenIn,tokenOut:o.tokenOut});const d=(await Promise.allSettled(i.map(u=>u.resolve(o,r,a)))).filter(u=>u.status==="fulfilled").map(u=>u.value).filter(u=>u!==null);if(d.length===0)throw new f.SpiceflowError("NO_SWAP_ROUTE",`All aggregators failed for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${r}`,{chainId:r,tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountOut:o.amountOut.toString()});return d.sort((u,l)=>u.amountIn<l.amountIn?-1:u.amountIn>l.amountIn?1:0),d[0]}return{getQuote:s,venues:t}}const kl=xr({satsuma:Zs});function vl(e){const{direction:t,selectedAsset:s,destinationToken:o,chainId:r,recipient:a,paymentAmount:i}=e,[d,u]=c.useState(!1),[l,h]=c.useState(null),[p,g]=c.useState(null),[x,m]=c.useState(null),[y,w]=c.useState(null),[S,b]=c.useState(null),[k,I]=c.useState(null),[C,E]=c.useState(null),[A,M]=c.useState(null),T=c.useRef(null),v=c.useRef(null),B=c.useRef(0),D=c.useRef(new Map),R=c.useMemo(()=>kl,[]),O=c.useMemo(()=>wl({customVenues:[gr(Zs),gr(hr)]}),[]),U=c.useMemo(()=>{if(!s?.asset)return null;const W=tn(s.asset,r);if(W)return W;const te=an(s.asset.address,r,s.asset.chainId);return te?te.address:null},[s?.asset,r]),H=c.useMemo(()=>s?.asset?Yn(s.asset,r):[],[s?.asset,r]),q=c.useMemo(()=>H.map(W=>W.toLowerCase()).join(","),[H]);c.useEffect(()=>{let W=!1;if(v.current&&(clearTimeout(v.current),v.current=null),!s?.asset||H.length<=1){M(null);return}return v.current=setTimeout(async()=>{const te=t==="input"?s.amount:i||"0";let ue=0n;try{ue=t==="input"?j.parseUnits(te,s.asset.decimals):0n}catch{ue=0n}try{const Ce=await jo(s.asset,r,{requiredAmount:ue});W||M(Ce)}catch{W||M(null)}},400),()=>{W=!0,v.current&&(clearTimeout(v.current),v.current=null)}},[s?.asset,s?.amount,r,H.length,q,t,i]);const N=c.useMemo(()=>A??U,[A,U]),K=c.useMemo(()=>!s?.asset||!N?[]:[N,...H.filter(W=>W.toLowerCase()!==N.toLowerCase())],[s?.asset,N,H]),L=c.useMemo(()=>!s?.asset||!Wn(s.asset.address,s.asset.chainId,o.address,o.chainId)||!N?!1:f.addressesEqual(N,o.address),[s,o.address,o.chainId,N]),V=N?f.addressesEqual(N,o.address):!1,P=t==="output"&&parseFloat(i||"0")===0,G=!!s?.asset&&!L&&!V&&!P,me=G?C??N:N;return c.useEffect(()=>{T.current&&clearTimeout(T.current);const W=t==="input"?s?.amount:i,te=parseFloat(W||"0");if(!G||!Number.isFinite(te)||te<=0||!s?.asset||!a||K.length===0){B.current++,g(null),m(null),w(null),b(null),I(null),E(null),h(null),u(!1);return}const ue=s.asset.decimals;let Ce;try{Ce=t==="input"?j.parseUnits(s.amount,ue):j.parseUnits(i||"0",o.decimals)}catch{B.current++,h("Invalid amount"),u(!1);return}const je=++B.current,pe=()=>je!==B.current;u(!0);const ye=t==="output"?150:400;return T.current=setTimeout(async()=>{try{if(t==="input"){const z=R.getVenueForChain(r);if(!z)throw new Error("No swap venue for this chain");let se=null,Y=null;for(const ge of K){const be=`${t}:${r}:${ge.toLowerCase()}:${o.address.toLowerCase()}:${Ce.toString()}`,ne=D.current.get(be);if(ne&&ne.expiresAt>Date.now()&&ne.resolvedSwap){se=ne.resolvedSwap,Y=ge;break}const Q=await z.resolve({type:"swap",tokenIn:ge,tokenOut:o.address,amountIn:Ce},r,a);if(pe())return;if(Q){D.current.set(be,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:Q}),se=Q,Y=ge;break}}if(!se||!Y)throw new Error("No liquidity for this pair");E(Y),I(se.amountOut),w(se),b(null);const ae=parseFloat(j.formatUnits(se.amountOut,o.decimals));g(ae<.01?ae.toPrecision(4):ae.toLocaleString(void 0,{maximumFractionDigits:6})),m(null),h(null)}else{let z=null,se=null;for(const Y of K){const ae=`${t}:${r}:${Y.toLowerCase()}:${o.address.toLowerCase()}:${Ce.toString()}`,ge=D.current.get(ae);if(ge&&ge.expiresAt>Date.now()&&ge.exactOutputSwap){z=ge.exactOutputSwap,se=Y;break}try{const be=await O.getQuote({tokenIn:Y,tokenOut:o.address,amountOut:Ce},r,a);if(pe())return;D.current.set(ae,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:be}),z=be,se=Y;break}catch{if(pe())return}}if(!z||!se)throw new Error("No liquidity for this pair");E(se),b(z),w(null),I(null),m(parseFloat(j.formatUnits(z.amountIn,ue)).toFixed(6)),g(null),h(null)}}catch(z){if(pe())return;const se=z instanceof Error?z.message:"Failed to get quote";h(se),g(null),m(null),w(null),b(null),I(null),E(null)}finally{pe()||u(!1)}},ye),()=>{T.current&&clearTimeout(T.current)}},[t,G,s?.amount,s?.asset?.address,s?.asset?.decimals,i,K,r,o.address,o.decimals,a,R,O]),{isQuoting:d,quoteError:l,estimatedOutput:p,estimatedInput:x,resolvedSwap:y,exactOutputSwap:S,quoteAmountOut:k,resolvedTokenIn:me,isDirect:V,needsSwap:G,selectedIsEquivalent:L}}const yr={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},Cr=["signing-delegation","signing-intent","submitting","executing"],br=({isOpen:e,onClose:t,closeOnBackdropClick:s=!1,destinationToken:o,sourceChains:r,supportedSourceAssets:a,buildActionCalls:i,feeExecutionMode:d="user-transfer",buildSpicenetBatch:u,onPayExecute:l,actionLabel:h,amountDirection:p="input",swapDescription:g,directDescription:x,paymentAmount:m,amountInputMode:y="fixed",minPaymentAmount:w,maxPaymentAmount:S,onAmountChange:b,styles:k,dark:I,title:C,subtitle:E,onAddFunds:A,onSuccess:M,onError:T})=>{const v=p==="output",{theme:B,dark:D,primaryColor:R,dk:O,palette:U,fontFamily:H,monoFont:q,inputDark:N,cardBg:K,cardBorder:L,textPrimary:V,textSecondary:P,subtitleText:G}=f.useSpiceBrand(k,I),me=N?{...B,colors:{...B.colors,secondary:O.cardBg,surfaceHover:O.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:B,W=o.chainId,te=c.useContext(f.SpiceFlowProviderContext),ue=(te?.mode||"7702")!=="7702",Ce=!!te?.isWhitelistGateActive,je=c.useMemo(()=>r??te?.supportedChainIds??[],[r,te?.supportedChainIds]),pe=c.useMemo(()=>{if(Ce)return[];if(a)return a;const de=te?.allowedTokens;if(!de||de.length===0)return;const Be=new Set(de.map(Yt=>Yt.toLowerCase())),yt=[],en=new Set;for(const Yt of je){const Bn=f.getChainConfig(Yt);for(const hn of Bn?.supportedTokens??[]){if(!Be.has(hn.symbol.toLowerCase()))continue;const Tn=hn.address.toLowerCase();en.has(Tn)||(en.add(Tn),yt.push(hn.address))}}return yt},[a,te?.allowedTokens,je,Ce]),ye=f.useWallet(),{address:z,isConnected:se,isReady:Y,isAuthenticated:ae,provider:ge}=ye,{executeGasless:be,estimateGasless:ne}=ns(),{externalWallet:Q,externalAddress:re,embeddedAddress:we}=f.useProviderWallets(),Me=f.useEmbeddedWalletAddress()||we,{displayAssets:at,filteredSpiceAssets:Xe,embeddedWalletAddress:le,refreshSpiceAssets:xe,refreshWalletAssets:fe}=hl({destinationToken:o,supportedSourceAssets:pe,sourceChains:je,enabled:e&&(ue?!!re:!!Me)}),Le=Ce||v||ue?at:Xe,[oe,Te]=c.useState(null),[mt,Bt]=c.useState(m||""),[ot,Lt]=c.useState(!1),[Tt,gt]=c.useState(null),[Se,Mt]=c.useState("idle"),[Jt,$t]=c.useState(""),[Ct,Ot]=c.useState(null),[Je,wt]=c.useState(!1),[qe,_e]=c.useState(null),[et,pt]=c.useState(null),[At,he]=c.useState(!1),[rt,it]=c.useState(!1),[kt,ke]=c.useState(null),Rt=c.useRef(oe),tt=c.useRef(!1),ft=c.useRef(null),vt=c.useRef(0),Kt=c.useRef(null),Ht=c.useRef(null);c.useEffect(()=>{Rt.current=oe},[oe]);const $e=y==="adjustable"?mt:m||"0",Zt=le||we||z,{isQuoting:Re,quoteError:dt,estimatedOutput:St,resolvedSwap:Oe,exactOutputSwap:Ge,quoteAmountOut:Et,resolvedTokenIn:ct,isDirect:De,needsSwap:He,selectedIsEquivalent:ht}=vl({direction:p,selectedAsset:oe,destinationToken:o,chainId:W,recipient:Zt,paymentAmount:$e}),nt=v?parseFloat($e||"0"):parseFloat(oe?.amount||"")||0,Qt=oe?.asset?._source==="wallet",Ue=!!oe?.asset&&Qt&&oe.asset.chainId!==W,Gt=c.useMemo(()=>oe?.asset?Xe.find(de=>f.addressesEqual(de.address,oe.asset.address))?.balanceFormatted??0:0,[oe,Xe]),Vt=Qt?oe?.asset.balanceFormatted??0:Gt,Dt=c.useMemo(()=>{if(!oe?.asset)return!1;if(v)return et?jn(et.grossAmount,et.decimals,oe.asset.decimals)>oe.asset.balance:ht||De?nt>oe.asset.balanceFormatted:Ge?parseFloat(j.formatUnits(Ge.amountInMax,oe.asset.decimals))>oe.asset.balanceFormatted:!1;if(et){const de=jn(et.grossAmount,et.decimals,oe.asset.decimals);return Qt?de>oe.asset.balance:parseFloat(j.formatUnits(de,oe.asset.decimals))>Vt}return nt>Vt},[oe,v,et,ht,nt,Ge,Vt,Qt,De]);c.useEffect(()=>{e||(Te(null),gt(null),Lt(!1),Mt("idle"),$t(""),Ot(null),wt(!1),_e(null),pt(null),he(!1),it(!1),ke(null),tt.current=!1,y==="adjustable"&&Bt(m||""),ft.current&&(ft.current.abort(),ft.current=null))},[e]);const _=c.useCallback(de=>{Te(Be=>({asset:de,amount:Be?.asset?.address===de.address&&Be?.asset?.chainId===de.chainId&&Be.amount||""})),gt(null),ke(null),it(!1)},[]),ee=c.useCallback(de=>{Te(Be=>Be&&{...Be,amount:de}),gt(null),ke(null),it(!1)},[]),Ie=c.useCallback(de=>{let Be=de;S&&parseFloat(Be)>parseFloat(S)&&(Be=S),Bt(Be),b?.(Be),gt(null),ke(null),it(!1)},[S,b]);c.useCallback(de=>{if(tt.current||!z)return;const Be=Rt.current;!Be?.asset||!Be.amount||Be.asset?._source==="wallet"||j.parseUnits(v?$e:Be.amount,Be.asset.decimals)===0n||(tt.current=!0,xe())},[z,W,xe,v,$e]);const Qe=c.useCallback(de=>{Mt({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[de.step]||"executing"),$t(de.message),de.txHash&&Ot(de.txHash)},[]),Ye=c.useMemo(()=>({currentPaymentAmount:$e,destinationToken:o,embeddedWalletAddress:le,providerEmbeddedAddress:we,externalWalletAddress:re,address:z,isNon7702:ue,isPayMode:v,resolvedChainId:W,buildActionCalls:i,feeExecutionMode:d,buildSpicenetBatch:u,selectedAsset:oe,needsSwap:He,resolvedSwap:Oe,exactOutputSwap:Ge,quoteAmountOut:Et,resolvedTokenIn:ct}),[$e,o,le,we,re,z,ue,v,W,i,d,u,oe,He,Oe,Ge,Et,ct]),Ke=c.useCallback(de=>$i(Ye,de),[Ye]),Ve=c.useCallback(de=>_i(Ye,de),[Ye]),We=c.useCallback((de,Be,yt,en)=>el(de,Be,yt,ne,en),[ne]),Pe=c.useMemo(()=>oe?.asset?He&&ct?ct:oe.asset.chainId===W?oe.asset.address:ct??tn(oe.asset,W)??o.address:o.address,[oe,o.address,He,W,ct]),X=c.useCallback(()=>ll(Ht.current),[]),ce=c.useMemo(()=>oe?.asset?f.addressesEqual(oe.asset.address,o.address)&&oe.asset.chainId===o.chainId:!1,[oe,o.address,o.chainId]),Fe=ue&&ce,Ee=Fe&&nt>0&&!!oe?.asset,ze=Tt,ut=c.useMemo(()=>!(!oe?.asset||nt<=0),[oe,nt,Ee]),qt=c.useMemo(()=>!e||ot||Se!=="idle"||!ut||Ee||!oe?.asset?null:[v?"pay":"supply",p,oe.asset.address.toLowerCase(),oe.asset.chainId,oe.amount,$e,o.address.toLowerCase(),o.chainId,W,ct?.toLowerCase()??"",He?"swap":"direct",De?"direct-token":"routed-token",ue?"non7702":"7702",ce?"source-dest":"cross-chain",Re?"quoting":"quoted",Ge?.amountIn?.toString()??"",Ge?.amountInMax?.toString()??"",Ge?.venue??"",Oe?.amountOut?.toString()??"",Et?.toString()??"",le??"",we??"",z??""].join("|"),[e,ot,Se,ut,Ee,oe,v,p,$e,o,W,ct,He,De,ue,ce,Re,Ge,Oe,Et,le,we,z]),Z=c.useCallback(()=>ol({selectedAsset:oe,isPayMode:v,parsedAmount:nt,needsSwap:He,exactOutputSwap:Ge,isNon7702:ue,isSourceDestToken:ce,currentPaymentAmount:$e,destinationToken:o,feeExecutionMode:d,resolvedTokenIn:ct,embeddedWalletAddress:le,providerEmbeddedAddress:we,resolvedChainId:W,isConnected:se,address:z,ready:Y,authenticated:ae,isDirect:De,resolvedSwap:Oe,isQuoting:Re,executionTokenAddress:Pe,buildPayChainBatches:Ke,buildSupplyChainBatches:Ve,estimateGasless:ne,estimateRequiredGrossFunding:We}),[oe,v,nt,He,Ge,ue,ce,$e,o,d,ct,le,we,We,Ke,ne,W,se,z,Y,ae,De,Oe,Re,Ve,Pe]);c.useEffect(()=>{Kt.current=Z},[Z]);const $=c.useCallback(de=>sl({asset:de,isPayMode:v,isNon7702:ue,needsSwap:He,isQuoting:Re,embeddedWalletAddress:le,buildSupplyChainBatches:Ve,estimateGasless:ne,executionTokenAddress:Pe,feeExecutionMode:d}),[v,ue,He,Re,le,Ve,ne,Pe,d]);c.useEffect(()=>{if(!e){he(!1),it(!1),ke(null),pt(null);return}if(ot||Se!=="idle"){vt.current+=1,he(!1);return}if(!ut){pt(null),he(!1),it(!1),ke(null);return}if(Ee){pt(null),he(!1),it(!0),ke(null);return}if(Re){vt.current+=1,he(!1),it(!1);return}if(!qt)return;let de=!1;const Be=async()=>{const en=++vt.current;ke(null),he(!0);try{const Yt=await Kt.current?.();if(de||vt.current!==en)return;Yt?(pt(Yt),it(!0)):(pt(null),it(!1)),ke(null)}catch(Yt){if(de||vt.current!==en)return;const Bn=f.sanitizeError(Yt,"Unable to calculate fees for this action.");pt(null),it(!1),ke(Bn)}finally{!de&&vt.current===en&&he(!1)}},yt=window.setTimeout(()=>{Be()},250);return()=>{de=!0,clearTimeout(yt),he(!1)}},[e,ot,Se,ut,Ee,Re,qt]);const ie=c.useCallback(()=>ul(Ht.current),[]);c.useEffect(()=>{!v&&Se==="success"&&Ct&&(xe(),M?.(Ct))},[v,Se,Ct,xe,M]),c.useEffect(()=>{if(!v||qe?.status!=="success"||tt.current||!z)return;tt.current=!0;const de=Rt.current;!de?.asset||de.asset?._source==="wallet"||xe()},[v,qe?.status,z,xe]);const J=c.useRef(M),Ae=c.useRef(T);c.useEffect(()=>{J.current=M},[M]),c.useEffect(()=>{Ae.current=T},[T]),c.useEffect(()=>{e&&(xe(),fe())},[e,xe,fe]),c.useEffect(()=>{v&&(qe?.status==="success"&&J.current?.(qe.txHash||""),qe?.status==="failed"&&Ae.current?.(new Error("Payment execution failed")))},[v,qe?.status]);const Ne=c.useCallback(()=>{wt(!1),_e(null),Te(null),tt.current=!1,xe(),fe()},[xe,fe]);Ht.current={selectedAsset:oe,parsedAmount:nt,currentPaymentAmount:$e,isInsufficientBalance:Dt,isPayMode:v,isNon7702:ue,isSourceDestToken:ce,needsSwap:He,exactOutputSwap:Ge,selectedIsEquivalent:ht,resolvedTokenIn:ct,embeddedWalletAddress:le,providerEmbeddedAddress:we,externalWallet:Q,externalWalletAddress:re,address:z,isConnected:se,ready:Y,authenticated:ae,provider:ge,resolvedChainId:W,executionTokenAddress:Pe,destinationToken:o,buildActionCalls:i,feeExecutionMode:d,buildSpicenetBatch:u,onPayExecute:l,onError:T,gasless:{estimateGasless:ne,executeGasless:be,buildPayChainBatches:Ke,buildSupplyChainBatches:Ve,estimateRequiredGrossFunding:We,onProgress:Qe},ui:{setError:gt,setStep:Mt,setStatusMsg:$t,setTxHash:Ot,setIsExecuting:Lt,setShowStatusPanel:wt,setPaymentResult:_e},refs:{spiceDepositSubmittedRef:tt,abortControllerRef:ft}};const st=v&&nt===0,Ze=v?!!oe?.asset&&nt>=0&&!Dt&&!ot&&(st||Ee||rt)&&!kt&&(st||!He||!!Ge):!!oe?.asset&&nt>0&&!Dt&&!ot&&(Fe||rt)&&!kt&&(Ue||De||!!Oe&&!Re),lt=De?x||`Your ${o.symbol} will be used directly.`:g||"Your assets will be swapped and used in a single atomic transaction.",jt=(W?f.getChainConfig(W):void 0)?.viemChain?.blockExplorers?.default?.url??"",xt=Cr.indexOf(Se),Nt=ot?(yr[Se]||"EXECUTING...").toUpperCase():Se==="success"?"DONE":Dt?"INSUFFICIENT BALANCE":h.toUpperCase(),Ut=c.useMemo(()=>{if(ot)return"PAYING...";if(Dt&&oe?.asset)return`INSUFFICIENT ${oe.asset.symbol}`;if(h)return h.toUpperCase();const de=nt>0?` ${$e} ${o.symbol}`:"";return He?`SWAP & PAY${de}`:`PAY${de}`},[ot,Dt,oe,h,nt,$e,o.symbol,He]),_t=Se==="success"?()=>{Mt("idle"),Te(null),Ot(null),xe()}:X,pn=Se==="success"?!1:!Ze;if(!e)return null;const fn=v?C||`Pay ${o.symbol}`:h,ve=v?E:n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[n.jsx("span",{style:{marginTop:"3px",flexShrink:0},children:n.jsx(Ss,{color:G})}),n.jsx("p",{style:{fontSize:"12px",color:G,margin:0,lineHeight:"1.4",fontFamily:H},children:lt})]});if(v){const de=qe&&(qe.status==="success"||qe.status==="failed")?[{asset:{symbol:oe?.asset?.symbol||o.symbol,address:oe?.asset?.address||""},amount:$e,txHash:qe.txHash||"",success:qe.status==="success",error:qe.status==="failed"?qe.error:void 0}]:void 0;return n.jsx(sn,{isOpen:e,onClose:t,title:fn,subtitle:ve,styles:k,dark:D,footerLinkText:"Spicenet accounts \u2192",closeOnBackdropClick:s,children:n.jsxs("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[A&&n.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:n.jsx(Is,{onClick:A,color:R,fontFamily:H})}),n.jsx("div",{style:{marginBottom:"12px"},children:n.jsx(Un,{assets:Le,selectedAsset:oe??void 0,onAssetSelect:_,onAmountChange:()=>{},label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:oe?.asset?He?Re?"...":Ge?`~${parseFloat(j.formatUnits(Ge.amountIn,oe.asset.decimals)).toFixed(6)}`:void 0:$e??void 0:void 0,dark:D,theme:me,styles:k})}),n.jsx(rr,{variant:"pay",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:R,fontFamily:H,textPrimary:V,textSecondary:P,cardBg:K,cardBorder:L,dk:O,dark:D,isQuoting:Re,quoteError:dt,estimatedOutput:St,paymentAmount:$e,needsSwap:He,exactOutputSwap:Ge,adjustable:y==="adjustable",maxAmount:S,onAmountChange:Ie}),ut&&n.jsx(qn,{fontFamily:H,textPrimary:V,textSecondary:P,cardBg:K,cardBorder:L,resolvedDark:D,darkCardBorder:O.cardBorder,primaryColor:R,feePreview:et,isLoading:At,errorText:kt,directExecutionFeeNote:Ee}),ze&&n.jsx(In,{variant:"error",palette:U,fontFamily:H,style:{marginBottom:"12px"},children:ze}),n.jsx(f.Button,{variant:"outline",fullWidth:!0,onClick:ie,disabled:!Ze,loading:ot,dark:D,styles:{...k,button:{...k?.button,backgroundColor:R}},children:Ut}),qe&&Je&&n.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:D?O.shell:"white",borderRadius:D?"12px":"6px",padding:"16px 0"},children:n.jsx(Bs,{type:"payment",isOpen:qe.status!=="processing",isProcessing:ot||qe.status==="processing",closeOnComplete:!1,chainName:f.getChainName(W),explorerUrl:f.getExplorerUrl(W,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{wt(!1),_e(null),ie()},onNewTx:Ne,onClose:()=>{wt(!1),_e(null)},onComplete:Ne,results:de,styles:k,dark:D})})]})})}return n.jsx(sn,{isOpen:e,onClose:t,title:fn,subtitle:ve,dark:D,styles:k,theme:B,closeOnBackdropClick:s,children:n.jsxs("div",{style:{padding:"24px 24px 5px 24px",position:"relative"},children:[n.jsx("div",{style:{marginBottom:"16px"},children:n.jsx(Un,{assets:Le,selectedAsset:oe||void 0,onAssetSelect:_,onAmountChange:ee,disabled:ot||Se==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:me,styles:k,dark:N,resolveMaxAmount:$,maxAmount:Vt>0?vn(Vt,oe?.asset.decimals??o.decimals):void 0})}),oe?.asset&&!De&&n.jsx(rr,{variant:"supply",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:R,fontFamily:H,textPrimary:V,textSecondary:P,cardBg:K,cardBorder:L,dark:D,isQuoting:Re,quoteError:dt,estimatedOutput:St}),ut&&n.jsx(qn,{fontFamily:H,textPrimary:V,textSecondary:P,cardBg:K,cardBorder:L,resolvedDark:D,darkCardBorder:O.cardBorder,primaryColor:R,feePreview:et,isLoading:At,errorText:kt,directExecutionFeeNote:Ee}),Se!=="idle"&&n.jsxs("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:Se==="success"?K:Se==="error"?U.errorBg:K,border:`1px solid ${Se==="success"?L:Se==="error"?U.errorBorder:L}`},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[Se==="success"?n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:n.jsx("path",{d:"M5 13l4 4L19 7",stroke:U.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):Se==="error"?n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:n.jsx("path",{d:"M18 6L6 18M6 6l12 12",stroke:U.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):n.jsx(f.Spinner,{size:14,color:R}),n.jsx("span",{style:{fontSize:"13px",fontWeight:500,color:Se==="success"?V:Se==="error"?U.errorText:V,fontFamily:H,flex:1},children:Se==="success"?"Deposit confirmed":Se==="error"?Jt||"Transaction failed":yr[Se]||Jt}),Se==="success"&&Ct&&n.jsx("a",{href:`${jt}/tx/${Ct}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:R,fontFamily:H,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),Se==="error"&&n.jsx("button",{onClick:()=>{Mt("idle"),gt(null),setTimeout(X,50)},style:{background:"none",border:"none",fontSize:"12px",color:R,fontFamily:H,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),xt>=0&&Se!=="success"&&Se!=="error"&&n.jsx("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${P}22`,overflow:"hidden"},children:n.jsx("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:R,transformOrigin:"left center",transform:`scaleX(${(xt+1)/Cr.length})`,transition:"transform 400ms ease"}})})]}),Tt&&Se==="idle"&&n.jsx(In,{variant:"error",palette:U,fontFamily:H,style:{marginBottom:"16px"},children:Tt}),n.jsx(f.Button,{variant:"outline",fullWidth:!0,disabled:pn,onClick:_t,theme:B,dark:D,styles:{...k,button:{...k?.button,backgroundColor:R}},style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:q},children:Nt})]})})},Sl=e=>n.jsx(br,{isOpen:e.isOpen,onClose:e.onClose,closeOnBackdropClick:e.closeOnBackdropClick,amountDirection:"output",destinationToken:{address:e.paymentTokenAddress,symbol:e.paymentTokenSymbol,decimals:e.paymentTokenDecimals,chainId:e.paymentChainId,logoURI:e.paymentTokenLogoURI},buildActionCalls:e.buildActionCalls,buildSpicenetBatch:e.buildSpicenetBatch,actionLabel:e.ctaLabel||"PAY",paymentAmount:e.paymentAmount,amountInputMode:e.amountInputMode,minPaymentAmount:e.minPaymentAmount,maxPaymentAmount:e.maxPaymentAmount,onAmountChange:e.onAmountChange,title:e.title,subtitle:e.subtitle,onAddFunds:e.onAddFunds,styles:e.styles,dark:e.dark,onSuccess:e.onPaymentSuccess,onError:e.onPaymentError}),Il=({label:e="Export Wallet",style:t,className:s,onExport:o,onError:r})=>{const[a,i]=c.useState(!1),[d,u]=c.useState(!1),{primaryColor:l}=f.useSpiceBrand(),h=c.useContext(f.SpiceFlowProviderContext),{isAuthenticated:p}=f.useWallet();let g=null;try{g=cs.usePrivy()}catch{}let x=null,m=null;try{x=Js.useEmbeddedReveal(),m=Js.useDynamicContext()}catch{x=null,m=null}const y=f.getDynamicEmbeddedWallet(m),w=c.useCallback(async()=>{if(!p){r?.("User is not authenticated. Please log in first.");return}try{if(h?.provider==="dynamic"){if(!x||!y){r?.("Dynamic is not available. Ensure the app is wrapped in a DynamicContextProvider.");return}await x.initExportProcess(!1),o?.();return}if(!g){r?.("Privy is not available. Ensure the app is wrapped in a PrivyProvider.");return}await g.exportWallet(),o?.()}catch(k){const I=k instanceof Error?k.message:"Failed to export wallet";console.error("Export wallet error:",k),r?.(I)}},[y,x,p,r,o,g,h?.provider]),S=!p,b={padding:"10px 20px",borderRadius:"8px",fontFamily:'"IBM Plex Mono", monospace',fontSize:"14px",fontWeight:500,letterSpacing:"0.4px",textTransform:"uppercase",cursor:S?"not-allowed":"pointer",opacity:S?.5:1,border:"1px solid #0e0d0b",color:"#0e0d0b",backgroundColor:d?`${l}cc`:a?`${l}ee`:l,transition:"background-color 150ms ease, transform 150ms ease",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"8px",...t};return n.jsxs("button",{onClick:w,onMouseEnter:()=>i(!0),onMouseLeave:()=>{i(!1),u(!1)},onMouseDown:()=>u(!0),onMouseUp:()=>u(!1),disabled:S,className:s,style:b,children:[n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),n.jsx("polyline",{points:"17 8 12 3 7 8"}),n.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]}),e]})};function wr(e){const t=c.useContext(f.SpiceFlowProviderContext),s=f.useEmbeddedWalletAddress(),o=e?.enabled===!1?void 0:s,r=t?.network?{network:t.network,pollIntervalMs:e?.pollIntervalMs,chainIds:e?.chainIds??t.supportedChainIds,discoverWalletBalances:e?.discoverWalletBalances}:void 0;return{...yo(o,r),embeddedWalletAddress:s}}var Al="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 El=({appName:e,status:t,statusLabel:s,totalUsdValue:o,breakdownSubtitle:r,address:a,dk:i,dark:d=!1,showModeToggle:u,isEmbeddedMode:l=!0,onModeToggle:h})=>{const[p,g]=c.useState(!1),x=async()=>{a&&await Gr(a)&&(g(!0),setTimeout(()=>g(!1),2e3))},m=t==="active",y=s||(m?"Active":"Inactive"),w=m?"#10b981":"#9ca3af",S=n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[n.jsxs("div",{children:[n.jsx("strong",{children:"Embedded:"})," Deposit assets into ",e," account and use them here."]}),n.jsxs("div",{children:[n.jsx("strong",{children:"External:"})," Use assets from your connected wallet here."]})]});return n.jsxs("div",{children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[n.jsxs("div",{style:{fontSize:"13px",fontWeight:600,color:i.textPrimary},children:[e," Account"]}),u?n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[n.jsxs("button",{onClick:h,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:'"IBM Plex Mono", monospace',color:i.textSecondary,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease",letterSpacing:"0.02em"},children:[n.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:l?"#22c55e":"#f59e0b"}}),n.jsx("span",{children:l?"Embedded":"External"}),n.jsx("img",{src:Al,alt:"","aria-hidden":"true",style:{width:"11px",height:"11px",display:"block",...d?{filter:"invert(0.65)"}:{}}})]}),n.jsx(co,{content:S,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:n.jsx("img",{src:js,alt:"","aria-hidden":"true",style:{width:"12px",height:"12px",display:"block",...d?{filter:"invert(0.65)"}:{}}})})]}):n.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:[n.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:w}}),n.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:d?i.textSecondary:m?"#065f46":"#6b7280"},children:y})]})]}),n.jsx("div",{style:{fontSize:"28px",fontWeight:700,color:i.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:wn(o)}),r&&n.jsx("div",{style:{fontSize:"12px",color:i.textSecondary,marginBottom:"8px"},children:r}),a&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[n.jsx("span",{style:{fontSize:"12px",fontFamily:'"IBM Plex Mono", monospace',color:d?i.textSecondary:"#9ca3af"},children:Zr(a)}),n.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:p?"Copied":"Copy"})]})]})},jl=({pendingDeposits:e,onCompleteDeposit:t,dk:s,dark:o=!1})=>e.length===0?null:n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:s.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:"Pending Deposits"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((r,a)=>{const i=f.getChainConfig(r.chainId)?.displayName||`Chain ${r.chainId}`;return n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:o?s.warningBg:"#fffbeb",border:o?`1px solid ${s.warningBorder}`:"1px solid #fde68a",borderRadius:"8px"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[n.jsx("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:o?s.hoverBg:"#fde68a",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:s.warningText},children:r.tokenSymbol.charAt(0)}),n.jsxs("div",{children:[n.jsxs("div",{style:{fontSize:"13px",fontWeight:500,color:s.textPrimary},children:[r.amount," ",r.tokenSymbol]}),n.jsxs("div",{style:{fontSize:"11px",color:s.warningText},children:["on ",i]})]})]}),n.jsx("button",{onClick:()=>t?.(r),style:{padding:"4px 12px",fontSize:"11px",fontWeight:600,backgroundColor:o?s.hoverBg:"#fef3c7",color:o?s.textPrimary:"#92400e",border:o?`1px solid ${s.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}`)})})]}),Fl=({spiceAssets:e,loading:t,dk:s,dark:o=!1})=>{const r={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:s.textSecondary,marginBottom:"8px",textTransform:"uppercase"},a={backgroundColor:s.cardBg,border:o?`1px solid ${s.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return t?n.jsxs("div",{children:[n.jsx("div",{style:r,children:"Idle Balances"}),[1,2].map(i=>n.jsx("div",{style:{...a,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},i))]}):e.length===0?n.jsxs("div",{children:[n.jsx("div",{style:r,children:"Idle Balances"}),n.jsx("div",{style:{...a,padding:"16px",textAlign:"center",fontSize:"13px",color:o?s.textSecondary:"#9ca3af"},children:"No assets yet. Deposit to get started."})]}):n.jsxs("div",{children:[n.jsx("div",{style:r,children:"Idle Balances"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((i,d)=>{const u=f.getChainConfig(i.chainId),l=i.chainDisplayName||u?.displayName||`Chain ${i.chainId}`,h=i.tokenDisplaySymbol||i.tokenDisplayName||i.tokenSymbol;return n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...a},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[i.logoURI?n.jsx("img",{src:i.logoURI,alt:i.tokenSymbol,style:{width:"24px",height:"24px",borderRadius:"50%"}}):n.jsx("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:o?s.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:s.textSecondary},children:h.charAt(0)}),n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:s.textPrimary},children:h}),n.jsx("div",{style:{fontSize:"11px",color:o?s.textSecondary:"#9ca3af"},children:l})]})]}),n.jsxs("div",{style:{textAlign:"right"},children:[n.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:s.textPrimary},children:ln(i.balanceFormatted)}),n.jsx("div",{style:{fontSize:"11px",color:o?s.textSecondary:"#9ca3af"},children:wn(i.usdValue)})]})]},`${i.tokenAddress}-${i.chainId}-${d}`)})})]})},Bl=({section:e,dk:t,dark:s=!1})=>{const o=r=>{switch(r){case"green":return"#10b981";case"red":return"#ef4444";default:return t.textPrimary}};return n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:t.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:e.title}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.items.map((r,a)=>n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:t.cardBg,border:s?`1px solid ${t.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[r.tokenLogoURI?n.jsx("img",{src:r.tokenLogoURI,alt:r.tokenSymbol,style:{width:"20px",height:"20px",borderRadius:"50%"}}):n.jsx("div",{style:{width:"20px",height:"20px",borderRadius:"50%",backgroundColor:s?t.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",fontWeight:600,color:t.textSecondary},children:r.tokenSymbol.charAt(0)}),n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:t.textPrimary},children:r.tokenSymbol}),n.jsx("div",{style:{fontSize:"11px",color:t.textSecondary},children:r.label})]})]}),n.jsx("div",{style:{fontSize:"13px",fontWeight:600,color:o(r.valueColor)},children:r.displayValue})]},a))})]})},Tl=({onDepositClick:e,onWithdrawClick:t,depositDisabled:s=!1,withdrawDisabled:o=!1,primaryColor:r="#EA4B4B",dark:a=!1})=>!e&&!t?null:n.jsxs("div",{style:{display:"flex",gap:"8px"},children:[e&&n.jsx(f.Button,{variant:"outline",onClick:e,disabled:s,dark:a,styles:{button:{backgroundColor:r}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&n.jsx(f.Button,{variant:"outline",onClick:t,disabled:o,dark:a,styles:{button:{backgroundColor:r}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),Ml=({appName:e,status:t,statusLabel:s,totalUsdValue:o,breakdownSubtitle:r,address:a,spiceAssets:i,spiceAssetsLoading:d,pendingDeposits:u,customSections:l,onDepositClick:h,onWithdrawClick:p,onCompleteDeposit:g,primaryColor:x,dk:m,dark:y=!1,showModeToggle:w,isEmbeddedMode:S,onModeToggle:b,showConnectExternalCta:k,onConnectExternalWallet:I,connectExternalError:C,showHowItWorks:E=!0})=>{const[A,M]=c.useState(!1);return n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[n.jsx(El,{appName:e,status:t,statusLabel:s,totalUsdValue:o,breakdownSubtitle:r,address:a,dk:m,dark:y,showModeToggle:w,isEmbeddedMode:S,onModeToggle:b}),k&&n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[n.jsx("button",{onClick:I,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:x||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:'"Helvetica Neue", sans-serif',transition:"opacity 150ms ease"},children:"Connect External Wallet"}),C&&n.jsx("span",{style:{fontSize:"11px",color:y?m.errorText:"#b91c1c",lineHeight:1.4},children:C})]}),n.jsx("div",{style:{height:"1px",backgroundColor:y?"#2d2d2d":"#e5e7eb"}}),n.jsx(Tl,{onDepositClick:h,onWithdrawClick:p,primaryColor:x,dark:y}),E&&n.jsxs("div",{children:[n.jsxs("button",{onClick:()=>M(!A),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:m.cardBg,border:y?`1px solid ${m.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:m.textSecondary,fontSize:"12px",fontWeight:500},children:[n.jsx("span",{children:"How It Works"}),n.jsx("span",{style:{transform:A?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),A&&n.jsxs("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:y?m.cardBg:"#f0fdf4",border:y?`1px solid ${m.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:y?m.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),n.jsx(jl,{pendingDeposits:u,onCompleteDeposit:g,dk:m,dark:y}),n.jsx(Fl,{spiceAssets:i,loading:d,dk:m,dark:y}),l.map((T,v)=>n.jsx(Bl,{section:T,dk:m,dark:y},v))]})},Gs=380,Cn=8;function kr(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function Rl(e,t){const s=new Map;Object.entries(t).forEach(([r,a])=>{if(!Number.isFinite(a)||a<=0)return;s.set(r,a),s.set(r.toUpperCase(),a);const i=kr(r);i&&s.set(i,a)});const o=[e.symbol,e.displaySymbol,e.receiptTokenName,e.name,e.displayName];for(const r of o){if(!r)continue;const a=s.get(r)??s.get(r.toUpperCase());if(a!==void 0)return a;const i=kr(r);if(!i)continue;const d=s.get(i);if(d!==void 0)return d}return 0}const Dl=({appName:e="Spice",status:t="active",statusLabel:s,customSections:o=[],extraAssets:r=[],tokenPrices:a={},breakdownLabels:i=[],styles:d,dark:u=!1,onDepositSuccess:l,onDepositClick:h,onWithdrawClick:p,onCompleteDeposit:g,showModeToggle:x=!1,defaultMode:m})=>{const y=c.useContext(f.SpiceFlowProviderContext),w=y?.mode!=="7702",S=!!y?.isWhitelistGateActive,b=c.useRef(!1);c.useEffect(()=>{if(!b.current){if(f.hasStoredSpiceFlowMode()){b.current=!0;return}m&&y?.setMode&&(y.setMode(m==="non7702"?"ondemand":"7702"),b.current=!0)}},[y,m]);const[k,I]=c.useState(!1),[C,E]=c.useState(null),[A,M]=c.useState({top:0,bottom:0,left:0,placement:"below"}),T=c.useRef(null),v=c.useRef(null),{address:B,isConnected:D}=f.useWallet(),R=f.useEmbeddedWalletAddress(),{externalAddress:O}=f.useProviderWallets(),{dark:U,primaryColor:H,dk:q}=f.useSpiceBrand(d,u),N=!w&&R?R:B,K=c.useMemo(()=>y?.supportedChainIds??F.getChainIdsByNetwork("mainnet"),[y?.supportedChainIds]),{assets:L,loading:V}=Pn({address:N,supportedChains:K,enabled:!!N&&!w,refetchInterval:3e4}),P=c.useMemo(()=>[...w?[]:L.map(le=>{const xe=le.balanceUsd||0,fe=Number.isFinite(le.balanceFormatted)?le.balanceFormatted:0,Le=xe>0?xe:Rl(le,a)*fe;return{tokenAddress:le.address,tokenSymbol:le.symbol,tokenDisplaySymbol:Cs(le),tokenDisplayName:ea(le),tokenDecimals:le.decimals,chainId:le.chainId,chainDisplayName:bs(le),balance:le.balance.toString(),balanceFormatted:le.balanceFormatted,usdValue:Le,logoURI:le.logoURI}}),...r].filter(le=>le.balanceFormatted>0),[w,L,a,r]),G=c.useMemo(()=>P.reduce((le,xe)=>le+xe.usdValue,0),[P]),{pendingDeposits:me}=wr({chainIds:K,enabled:!!B,discoverWalletBalances:!0}),W=c.useMemo(()=>o.reduce((le,xe)=>le+xe.totalValue,0),[o]),te=G+W,ue=c.useMemo(()=>{const le=[];G>0&&le.push(`${wn(G)} idle`);for(const xe of o){const fe=i.find(Le=>Le.sectionTitle===xe.title)?.label||xe.title.toLowerCase();le.push(`${wn(xe.totalValue)} ${fe}`)}return le.join(" \xB7 ")},[G,o,i]),Ce=c.useCallback(le=>{g?g(le):E(le)},[g]),je=c.useCallback(()=>{E(null)},[]),pe=c.useCallback(()=>{E(null),l?.()},[l]),ye=c.useCallback(()=>{if(!T.current)return;const le=T.current.getBoundingClientRect(),xe=window.innerHeight-le.bottom-Cn,fe=le.top-Cn,Le=xe>=400||xe>=fe?"below":"above",oe=Math.max(Cn,Math.min(le.right-Gs,window.innerWidth-Gs-Cn)),Te=Le==="below"?le.bottom+Cn:le.top-Cn,mt=Le==="above"?window.innerHeight-Te:0;M({top:Te,bottom:mt,left:oe,placement:Le})},[]);c.useLayoutEffect(()=>{k&&ye()},[k,ye]),c.useEffect(()=>{if(!k)return;const le=Le=>{T.current&&!T.current.contains(Le.target)&&v.current&&!v.current.contains(Le.target)&&I(!1)},xe=Le=>{Le.key==="Escape"&&I(!1)},fe=()=>ye();return document.addEventListener("mousedown",le),document.addEventListener("keydown",xe),window.addEventListener("scroll",fe,{passive:!0}),window.addEventListener("resize",ye),()=>{document.removeEventListener("mousedown",le),document.removeEventListener("keydown",xe),window.removeEventListener("scroll",fe),window.removeEventListener("resize",ye)}},[k,ye]);const z=y?.mode==="7702",se=z?R||B:O||B,Y=c.useCallback(()=>{y?.setMode&&y.setMode(z?"ondemand":"7702")},[y,z]),[ae,ge]=c.useState(null);let be=null;try{be=cs.useConnectWallet({onSuccess:()=>ge(null),onError:le=>ge(f.sanitizeError(le,"Failed to connect wallet."))}).connectWallet}catch{be=null}const ne=c.useCallback(()=>{be&&(I(!1),ge(null),be({walletChainType:"ethereum-only"}))},[be]),Q=!O&&!!be,re=c.useCallback(()=>{I(!1),h?.()},[h]),we=c.useCallback(()=>{I(!1),p?.()},[p]),Me=c.useCallback(le=>{I(!1),Ce(le)},[Ce]);if(typeof window>"u")return null;const at=n.jsxs("button",{ref:T,onClick:()=>I(!k),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:U?q.hoverBg:"#ffffff",border:U?`1px solid ${q.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:'"Helvetica Neue", sans-serif',color:U?q.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:U?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[n.jsx("span",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:H,flexShrink:0}}),n.jsxs("span",{children:[e," Account"]}),D&&n.jsxs("span",{style:{color:U?q.textSecondary:"#6b7280"},children:["\xB7 ",wn(te)]}),n.jsx("span",{style:{fontSize:"10px",color:U?q.textSecondary:"#9ca3af",transform:k?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),Xe=k?Mn.createPortal(n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:mn.popover},onClick:()=>I(!1)}),n.jsx("div",{ref:v,style:{position:"fixed",top:A.placement==="below"?`${A.top}px`:"auto",bottom:A.placement==="above"?`${A.bottom}px`:"auto",left:`${A.left}px`,width:`${Gs}px`,maxWidth:`calc(100vw - ${Cn*2}px)`,maxHeight:"80vh",backgroundColor:U?q.shell:"#ffffff",border:U?`1px solid ${q.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:U?"0 10px 40px rgba(0, 0, 0, 0.5)":"0 10px 40px rgba(0, 0, 0, 0.12)",zIndex:mn.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${bt.out}`},children:n.jsx(Ml,{appName:e,status:t,statusLabel:s,totalUsdValue:te,breakdownSubtitle:ue,address:z?se:B,spiceAssets:P,spiceAssetsLoading:V,pendingDeposits:me,customSections:o,onDepositClick:h?re:void 0,onWithdrawClick:p?we:void 0,onCompleteDeposit:Me,primaryColor:H,dk:q,dark:U,showModeToggle:x,isEmbeddedMode:z,onModeToggle:Y,showConnectExternalCta:Q,onConnectExternalWallet:ne,connectExternalError:ae,showHowItWorks:!S})}),n.jsx("style",{children:`
104
104
  @keyframes accountDisplayFadeIn {
105
105
  from { opacity: 0; transform: translateY(-4px); }
106
106
  to { opacity: 1; transform: translateY(0); }