@spicenet-io/spiceflow-ui 3.3.53 → 3.3.54

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(w=>w.chainId===l.chainId);if(!h)return l;const p=Xt(h),g=p.totalFee;if(g<=0n)return l;const x=(l.tokenTransfers??[]).find(w=>a(w)&&j.getAddress(w.to).toLowerCase()===t.toLowerCase()&&!F.isNativeToken(j.getAddress(w.token)));if(!x)return l;const m=j.getAddress(x.token);let y=!1;const k=(l.tokenTransfers??[]).map(w=>y||!a(w)||j.getAddress(w.to).toLowerCase()!==t.toLowerCase()||j.getAddress(w.token).toLowerCase()!==m.toLowerCase()?w:(y=!0,{...w,amount:o?.payoutAlreadyGross?BigInt(w.amount):BigInt(w.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:k,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],k=y.domain==="spicenet";return{hash:x.hash,chainId:x.chainId,tokenTransfers:k?[]: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("/"),k=parseInt(y||"0",10),S=g.intentIds[0];e.startStatusPolling(g.intentIds[0],x),await To({actionId:m,intentIndex:k,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 k=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 w=f.getChainConfig(a),I=j.createWalletClient({account:e.externalWalletAddress,chain:w?.viemChain,transport:j.custom(S)}),C=u?await I.sendTransaction({to:t,value:k,chain:w?.viemChain}):await I.sendTransaction({to:d,data:j.encodeFunctionData({abi:f.U,functionName:"transfer",args:[t,k]}),chain:w?.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]})}]}),k=(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=k(l,d),b=null,w;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=w?.grossAmount===A.grossAmount&&w?.netAmount===A.netAmount&&w?.feeAmount===A.feeAmount;if(b=E,w=A,d=un(e,A),S=k(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:k,sourceToDestinationConversionRate:S,estimatedOutputAmount:b,onAddFunds:w,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",H=!!D?.isWhitelistGateActive,U=R!=="7702",z=c.useMemo(()=>D?.supportedChainIds??[],[D?.supportedChainIds]),K=c.useMemo(()=>{if(H)return[];const J=D?.allowedTokens;if(!J||J.length===0)return[];const ce=new Set(J.map(ze=>ze.toLowerCase())),Fe=[],je=new Set;for(const ze of z){const pt=f.getChainConfig(ze);for(const qt of pt?.supportedTokens??[]){if(!ce.has(qt.symbol.toLowerCase()))continue;const Z=`${ze}:${qt.address.toLowerCase()}`;je.has(Z)||(je.add(Z),Fe.push(j.getAddress(qt.address)))}}return Fe},[D?.allowedTokens,z,H]),N=M?v.cardBg:C?.assetSelector?.backgroundColor||C?.secondaryBackground||"#e9e9e9",q=M?`1px solid ${v.cardBorder}`:"0.5px solid #A8A8A7",P=M?"12px":"6px",V=M?v.textPrimary:"#111827",L=M?v.textSecondary:"#6b7280",X=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]),he=c.useMemo(()=>M?{...A,colors:{...A.colors,secondary:v.cardBg,surfaceHover:v.hoverBg,border:v.cardBorder,borderHover:v.inputBorder}}:A,[M,A]),[W,ee]=c.useState(null),[ue,xe]=c.useState(0),Ae=u?.selectedDurationIdx??ue,pe=u?.setSelectedDurationIdx??xe,[ge,Q]=c.useState(!1),[re,G]=c.useState(null),[ie,me]=c.useState(null),[Se,te]=c.useState(!1),[O,ae]=c.useState(!1),[ye,Te]=c.useState(null),[at,Ye]=c.useState(!1),Xe=c.useRef(0),[Ee,oe]=c.useState(!1),[Ne,Y]=c.useState(null);At.useWalletClient(),At.useSwitchChain();const{chain:be,address:dt}=At.useAccount();At.useConfig();const gt=c.useRef(be);c.useEffect(()=>{gt.current=be},[be]);const Je=f.useWallet(),{isReady:Lt,isAuthenticated:Tt,isConnected:xt,address:ke,provider:Mt,actions:Jt}=Je,{externalWallet:$t,embeddedAddress:bt,externalAddress:Ot}=f.useProviderWallets(),{intentStatus:$e,startStatusPolling:kt,clearStatus:Ve}=lo({checkStepStatus:(J,ce)=>f.relayerService.checkStepStatus(J,ce),retryStep:async(J,ce)=>{const[Fe,je]=J.split("/"),ze=parseInt(je||"0",10);await f.relayerService.executeStep(Fe,ze,ce,{action:"execute"})},maxRetries:3}),{assets:et,refetch:tt}=Pn({address:ke,supportedChains:z,enabled:e&&xt&&!U&&!H,refetchInterval:3e4}),ft=c.useMemo(()=>{if(H)return[];if(K.length===0)return et;const J=new Set(K.map(ce=>ce.toLowerCase()));return et.filter(ce=>J.has(ce.address.toLowerCase()))},[et,K,H]),Et=f.useEmbeddedWalletAddress(),fe=Ot||dt,rt=U?fe:Et,it=c.useMemo(()=>{if(!x)return[];if(H)return m?[j.getAddress(m)]:[];const J=new Set,ce=[],Fe=je=>{if(!je)return;const ze=je.toLowerCase();J.has(ze)||(J.add(ze),ce.push(j.getAddress(je)))};if(m&&Fe(m),U)for(const je of K)Fe(je);return ce},[x,U,m,K,H]),vt=c.useMemo(()=>it.map(J=>J.toLowerCase()).sort().join(","),[it]),Ce=c.useMemo(()=>JSON.stringify([...z||[]].sort()),[z]),[Rt,nt]=c.useState([]),ht=c.useRef(0),St=c.useRef(async()=>{}),Kt=c.useCallback(async()=>{if(!x||!rt||it.length===0){ht.current++,nt([]);return}const J=++ht.current,ce=j.getAddress(rt),Fe=z&&z.length>0?z:[l],je=it.map(_=>{const le=_.toLowerCase();if(m&&f.addressesEqual(_,m)){const $=f.getChainConfig(l)?.supportedTokens?.find(Ie=>f.addressesEqual(Ie.address,le));return{address:_,chainId:l,configToken:$?{decimals:$.decimals,symbol:$.symbol,name:$.name,logo:$.logo}:void 0}}for(const $ of Fe){const Ie=f.getChainConfig($)?.supportedTokens?.find(De=>f.addressesEqual(De.address,le));if(Ie)return{address:_,chainId:$,configToken:{decimals:Ie.decimals,symbol:Ie.symbol,name:Ie.name,logo:Ie.logo}}}return{address:_,chainId:l}}),ze=new Map;for(const _ of je){const le=ze.get(_.chainId)||[];le.push(_),ze.set(_.chainId,le)}const pt=async(_,le)=>{try{const $=await Bt.readContract(_,{address:le.address,abi:f.U,functionName:"balanceOf",args:[ce]});let Ie,De,ot,Ke;if(le.configToken)Ie=le.configToken.decimals,De=le.configToken.symbol,ot=le.configToken.name,Ke=le.configToken.logo;else{const[yt,Nt,Ut]=await Promise.all([Bt.readContract(_,{address:le.address,abi:f.U,functionName:"decimals",args:[]}).catch(()=>18),Bt.readContract(_,{address:le.address,abi:f.U,functionName:"symbol",args:[]}).catch(()=>"TOKEN"),Bt.readContract(_,{address:le.address,abi:f.U,functionName:"name",args:[]}).catch(()=>"TOKEN")]);Ie=Number(yt),De=Nt,ot=Ut}const lt=!!m&&f.addressesEqual(le.address,m)&&le.chainId===l;lt&&a&&(Ke=a),lt&&r&&!le.configToken&&(De==="TOKEN"&&(De=r),ot==="TOKEN"&&(ot=r));const Ft=parseFloat((Number($)/Math.pow(10,Ie)).toFixed(6));return{address:le.address,name:ot,symbol:De,decimals:Ie,balance:$,balanceFormatted:Ft,balanceUsd:0,logoURI:Ke,isNative:!1,chainId:le.chainId}}catch{return null}},qt=await Promise.all(Array.from(ze.entries()).map(async([_,le])=>{let $;try{$=f.getClientForChain(_)}catch{return[]}const Ie=[],De=[];for(const Ke of le){const lt=Ie.length;Ie.push({address:Ke.address,abi:f.U,functionName:"balanceOf",args:[ce]}),Ke.configToken||Ie.push({address:Ke.address,abi:f.U,functionName:"decimals",args:[]},{address:Ke.address,abi:f.U,functionName:"symbol",args:[]},{address:Ke.address,abi:f.U,functionName:"name",args:[]}),De.push({start:lt,item:Ke})}let ot=null;try{ot=await $.multicall({contracts:Ie})}catch{ot=null}return ot?De.map(({start:Ke,item:lt})=>{const Ft=ot[Ke],yt=Ft?.status==="success"?Ft.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=ot[Ke+1],Be=ot[Ke+2],Ct=ot[Ke+3];Nt=de?.status==="success"?Number(de.result):18,Ut=Be?.status==="success"?Be.result:"TOKEN",_t=Ct?.status==="success"?Ct.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 we=parseFloat((Number(yt)/Math.pow(10,Nt)).toFixed(6));return{address:lt.address,name:_t,symbol:Ut,decimals:Nt,balance:yt,balanceFormatted:we,balanceUsd:0,logoURI:pn,isNative:!1,chainId:lt.chainId}}):(await Promise.all(le.map(Ke=>pt($,Ke)))).filter(Ke=>Ke!==null)}));if(J!==ht.current)return;const Z=qt.flat();nt(Z)},[x,rt,vt,Ce,l,m,a,r]);c.useEffect(()=>{St.current=Kt},[Kt]),c.useEffect(()=>{if(!e||!x){nt([]);return}St.current();const J=setInterval(()=>{St.current()},15e3);return()=>clearInterval(J)},[x,e,rt,vt,Ce,l,m]);const Ht=c.useCallback(()=>{Kt()},[Kt]),_e=c.useMemo(()=>Rt.filter(J=>J.balance>0n),[Rt]),Zt=c.useMemo(()=>{if(U)return _e.map(ce=>({...ce,_source:"wallet"}));if(!x)return ft;const J=[];for(const ce of _e)J.push({...ce,_source:"wallet"});for(const ce of ft)J.push({...ce,_source:"spice"});return J},[U,x,_e,ft]),Me=c.useMemo(()=>H?m?Zt.filter(J=>f.addressesEqual(J.address,m)&&J.chainId===l):[]:Zt,[Zt,H,m,l]),ut=c.useRef(null),It=c.useRef(null);c.useEffect(()=>{It.current=W},[W]),c.useEffect(()=>{!H||!W?.asset||m&&f.addressesEqual(W.asset.address,m)&&W.asset.chainId===l||ee(null)},[H,W?.asset,m,l]),c.useEffect(()=>{e||(ee(null),G(null),me(null),te(!1),ae(!1),Te(null),Q(!1),oe(!1),Y(null),Ye(!1),Ve())},[e,Ve]),c.useEffect(()=>{i&&i.assetAmount!==(W?.amount||"")&&ee(J=>J&&{...J,amount:i.assetAmount})},[i?.assetAmount]),c.useEffect(()=>{d&&d.assetAmount!==(W?.amount||"")&&ee(J=>J&&{...J,amount:d.assetAmount})},[d?.assetAmount]),c.useEffect(()=>{if(!U&&$e?.overallStatus==="success"&&$e.intentId&&ut.current!==$e.intentId&&ke&&$e.steps.find(J=>J.transactionHash)?.transactionHash){ut.current=$e.intentId;const J=It.current;if(!J?.asset||!J.amount||J.asset._source==="wallet"||j.parseUnits(J.amount,J.asset.decimals)===0n)return;tt()}},[$e,ke,l,tt,U]);const Le=parseFloat(W?.amount||"")||0,Ze=c.useMemo(()=>W?.asset?W.asset._source==="wallet"?W.asset.balanceFormatted??0:ft.find(J=>f.addressesEqual(J.address,W.asset.address)&&J.chainId===W.asset.chainId)?.balanceFormatted??0:0,[W?.asset,ft]),jt=Le>0&&(ye?parseFloat(j.formatUnits(ye.grossAmount,ye.decimals))>Ze:Le>Ze),ct=u?.selectedDuration??h[Ae]??h[0],Re=c.useMemo(()=>!W?.asset||!m?!1:f.addressesEqual(W.asset.address,m)&&W.asset.chainId===l,[W?.asset,m,l]),Oe=c.useMemo(()=>Le<=0?0:Re?Le:!S||S<=0?0:Le/S,[Le,S,Re]),mt=c.useMemo(()=>Oe<=0?null:Oe.toLocaleString(void 0,{maximumFractionDigits:2}),[Oe]),st=p&&Oe>0&&ct?p(Oe,ct.months):void 0,Qt=c.useMemo(()=>Le<=0?"$0.00":Re&&S?(Le*S).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!S||S<=0?"$0.00":Le.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[Le,S,Re]),Ue=c.useMemo(()=>{if(!mt)return null;const J=parseFloat(mt.replace(/,/g,""));return Re&&S?(J*S).toLocaleString(void 0,{maximumFractionDigits:2}):S?(J*S).toLocaleString(void 0,{maximumFractionDigits:2}):null},[mt,S,Re]),Gt=c.useCallback(J=>{ee(ce=>({asset:J,amount:ce?.asset?.address===J.address&&ce?.asset?.chainId===J.chainId&&ce.amount||""})),G(null),me(null),ae(!1),Te(null),d?.setSelectedAsset&&d.setSelectedAsset({symbol:J.symbol,address:J.address,decimals:J.decimals,chainId:J.chainId})},[d?.setSelectedAsset]),Vt=c.useCallback(J=>{ee(ce=>ce&&{...ce,amount:J}),G(null),me(null),ae(!1),Te(null),i&&i.setAssetAmount(J),d&&d.setAssetAmount(J)},[i,d]),Dt=c.useCallback(J=>{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:J?.amount??W.amount,amountWei:J?.amountWei??j.parseUnits(W.amount,W.asset.decimals),grossAmount:J?.grossAmount,grossAmountWei:J?.grossAmountWei,feeAdjusted:!!J})}return o},[o,W]),ne=c.useRef(null),se=c.useMemo(()=>!W?.asset||Le<=0?!1:U?!Re&&!k:!0,[W,Le,U,Re,k]),ve=c.useCallback(()=>Zi(ne.current),[]);c.useEffect(()=>{if(!e||ge)return;if(!W?.asset||Le<=0){me(null),te(!1),ae(!1),Te(null);return}if(!se){me(null),te(!1),ae(!0),Te(null);return}let J=!1;const ce=async()=>{const ze=++Xe.current;me(null),ae(!1),te(!0);try{const pt=await ve();if(J||Xe.current!==ze)return;me(null),ae(!0),Te(pt)}catch(pt){if(J||Xe.current!==ze)return;me(f.sanitizeError(pt,"Unable to calculate fees for this lock.")),ae(!1)}finally{!J&&Xe.current===ze&&te(!1)}},Fe=window.setTimeout(()=>{ce()},250),je=window.setInterval(()=>{ce()},1e4);return()=>{J=!0,clearTimeout(Fe),window.clearInterval(je),te(!1),ae(!1)}},[e,ge,W,Le,se,ve]),c.useEffect(()=>{if($e?.overallStatus==="success"){const J=$e.steps.find(ce=>ce.transactionHash);y?.(J?.transactionHash)}},[$e?.overallStatus,y]);const He=x&&W?.asset?._source==="wallet"&&W?.asset?.chainId===l,Ge=c.useCallback(()=>Yi(ne.current),[]),qe=!!W?.asset&&Le>0&&!jt&&!ge&&(!se||O&&!Se&&!ie),Qe=re||ie,We=n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[n.jsx(Ss,{color:L}),n.jsxs("p",{style:{fontSize:"13px",color:L,margin:0,lineHeight:"1.5"},children:["Add ",r," by converting assets from your account"]})]});if(ne.current={selectedAsset:W,parsedAmount:Le,selectedDuration:ct,isInsufficientBalance:jt,isSemi7702:U,isSourceDestToken:Re,isDirectDeposit:He,requiresRelayerFeeEstimate:se,address:ke,embeddedWalletAddress:Et,providerEmbeddedAddress:bt,externalWallet:$t,externalWalletAddress:fe,isConnected:xt,ready:Lt,authenticated:Tt,provider:Mt,actions:Jt,lockChainId:l,escrowAddress:g,onLockExecute:k,onLockSuccess:y,buildSpicenetBatch:I,resolveLockBatches:Dt,startStatusPolling:kt,refreshSpiceAssets:tt,refreshWalletAssets:Ht,ui:{setError:G,setIsExecuting:Q,setShowStatusPanel:Ye}},!e)return null;const Pe={backgroundColor:N,border:q,borderRadius:P,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:Ee?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:[w&&n.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:n.jsx(Is,{onClick:w,color:T,fontFamily:B})}),n.jsx("div",{style:{marginTop:"10px",fontSize:"13px",color:L,fontFamily:B},children:n.jsx(Un,{assets:Me,selectedAsset:W??void 0,onAssetSelect:Gt,onAmountChange:Vt,label:"Amount",showBalance:!0,showMaxButton:!0,theme:he,styles:X})}),n.jsx("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:L,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:mt??"0.00"}),n.jsxs("div",{style:{fontSize:"12px",color:L,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:L,fontFamily:B},children:"Lock Duration"}),n.jsx(on,{color:L})]}),n.jsx(Di,{options:h,selectedIndex:Ae,onSelect:pe,primaryColor:T,dark:M,textPrimary:V,textSecondary:L})]}),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:L}),p&&n.jsx(Wi,{votes:st,fontFamily:B,dark:M,textPrimary:V,textSecondary:L})]})]}),se&&n.jsx(qn,{fontFamily:B,textPrimary:V,textSecondary:L,cardBg:N,cardBorder:q,resolvedDark:M,darkCardBorder:v.cardBorder,primaryColor:T,feePreview:ye,isLoading:Se,errorText:ie}),Qe&&n.jsx(In,{variant:"error",palette:v,fontFamily:B,style:{marginBottom:"12px"},children:Qe}),n.jsx(f.Button,{variant:"outline",fullWidth:!0,onClick:Ge,disabled:!qe,loading:ge,dark:M,styles:{...C,button:{...C?.button,backgroundColor:T}},children:ge?He&&!Re?"DEPOSITING...":Re?"LOCKING...":"CONVERTING...":Se&&se?"CALCULATING FEES...":He&&!Re?`DEPOSIT ${r}`:Re?`LOCK ${r}`:`CONVERT TO ${r}`}),n.jsx(Pi,{isOpen:Ee,data:Ne,isLocking:ge,lockError:Qe,onContinue:Ge,onClose:()=>oe(!1),primaryColor:T,fontFamily:B,dark:M}),$e&&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:P},children:n.jsx(Bs,{type:"deposit",showStepBreakdown:!1,isOpen:!!$e&&$e.overallStatus!=="processing",isProcessing:ge||$e?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{Ve(),Ye(!1),Ge()},onNewTx:()=>{Ve(),Ye(!1),ee(null),ut.current=null,tt(),Ht()},onClose:()=>{Ve(),Ye(!1)},onComplete:()=>{Ve(),Ye(!1),ee(null),ut.current=null,tt(),Ht()},results:$e?.overallStatus==="success"||$e?.overallStatus==="failed"?$e.steps.map(J=>({asset:{symbol:W?.asset?.symbol||r,address:W?.asset?.address||""},txHash:J.transactionHash||"",success:J.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:k}=e,S=j.parseUnits(s,o.decimals),b=t?.actionAmountOverride??S,w=r||a||(d?void 0:i);if(!w)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const I={userAddress:w,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:w,amount:v});if(S===0n)return[E];if(m&&y){const T=k??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:w,destinationChainId:l,deliveryToken:T,deliveryAmount:v,deliveryRecipient:w,deliveryTransfers:os(R),sourceAsset:x.asset}):[R]}if(A){const T=k??tn(x.asset,l)??o.address,v=t?.fundingAmountOverride??S,B={...E,tokenTransfers:[M(T,v),...E.tokenTransfers??[]]};return ss(B,g,{userAddress:w,destinationChainId:l,deliveryToken:T,deliveryAmount:v,deliveryRecipient:w,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,k=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),w=t?.fundingAmountOverride??b,I=t?.sourceFundingAmountOverride??b,C=t?.deliveryAmountOverride??w,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:w,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||k===null)throw new Error("Swap quote not available yet")}if(g&&x&&k){const q=d(t?.actionAmountOverride??k,{...M,netAmount:t?.actionAmountOverride??k}),{feeCall:P,remainingCalls:V}=qs(q,u,g,M.feeToken);return[{chainId:a,calls:[...P?[P]:[],...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||k===null)throw new Error("Swap quote not available yet")}if(g&&x&&k){const q=d(t?.actionAmountOverride??k,{...M,netAmount:t?.actionAmountOverride??k}),{feeCall:P,remainingCalls:V}=qs(q,u,g,M.feeToken);return[{chainId:a,calls:[...P?[P]:[],...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,H=(q,P)=>({token:q,from:D?"solver":"escrow",to:o,amount:P}),U=(q,P)=>D?[{token:q,from:"escrow",to:F.SPICE_SOLVER_ADDRESS,amount:P}]:[];if(g){if(!y)throw new Error("Swap input token could not be resolved");if(!x||k===null)throw new Error("Swap quote not available yet")}if(g&&x&&k&&y){const q=d(t?.actionAmountOverride??k,{...M,netAmount:t?.actionAmountOverride??k}),{feeCall:P,remainingCalls:V}=qs(q,u,g,M.feeToken),L={chainId:a,calls:[...P?[P]:[],...x.calls,...V],tokenTransfers:[...U(y,E),H(y,C)]},X=await ss(L,l,{userAddress:o,destinationChainId:a,deliveryToken:y,deliveryAmount:C,withdrawalAmount:E,deliveryRecipient:o,deliveryTransfers:os(L),sourceAsset:s.asset});return R?[R,...X]:X}const z=y??tn(s.asset,a)??i.address,K={chainId:a,calls:T,tokenTransfers:[...U(z,E),H(z,C)]},N=await ss(K,l,{userAddress:o,destinationChainId:a,deliveryToken:z,deliveryAmount:C,withdrawalAmount:E,deliveryRecipient:o,deliveryTransfers:os(K),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(w=>w.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}),k=y?jn(y.gasFee,y.decimals,t.decimals):0n,S=y?jn(y.spicenetFee,y.decimals,t.decimals):0n,b=tl(t.balance,k,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:k,ready:S,authenticated:b,isDirect:w,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),q=p||tn(t.asset,m)||t.asset.address||l.address,P={chainId:m,tokenAddress:q,symbol:F.getTokenByAddress(q,m)?.symbol??t.asset.symbol,decimals:F.getTokenByAddress(q,m)?.decimals??t.asset.decimals};if(i){const ee=g||x;if(!ee)return null;const ue=ee,xe=r?a?.amountInMax??0n:N;if(xe===0n)return null;const Ae=await v(xe,Q=>A({fundingAmountOverride:Q}).then(re=>zt(yn(re),ue)),q,{userOverride:ee,useCustomTransfers:!0}),pe=zt(yn(await A({fundingAmountOverride:Ae})),ue),ge=await T(pe,q,Ae,{userOverride:ee,useCustomTransfers:!0,feeExecutionMode:h});return cn(ge,P)}if(!y||!k||!S||!b)return null;const V=g||x||k,L=r?a?.amountInMax??0n:N;if(L===0n)return null;const X=await v(L,ee=>A({fundingAmountOverride:ee}).then(ue=>zt(yn(ue),V)),q,{useCustomTransfers:!0});let he=zt(yn(await A({fundingAmountOverride:X})),V);const W=await T(he,q,X,{useCustomTransfers:!0,feeExecutionMode:h});return cn(W,P)}if(o<=0||!g)return null;const B=g||x;if(!(!s&&!i&&t.asset?._source==="wallet"&&t.asset.chainId!==m)&&!w&&!I&&!C||C)return null;const D=j.parseUnits(t.amount,t.asset.decimals),R=await M();if(R.length===0)return null;const H=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(H){const N=await f.relayerService.estimateBatchGas({user:B,outputToken:E,stepIndex:0,chainBatches:R}),q=$n(D,10n),P=q+N.gasFee;return{...U,grossAmount:D+P,netAmount:D,totalFee:P,gasFee:N.gasFee,spicenetFee:q,bridgeFee:0n,gasQuoteSource:N.gasQuoteSource}}const z=R.some(N=>N.tokenTransfers?.length),K=await T(R,E,D,z?{userOverride:B,useCustomTransfers:!0,feeExecutionMode:h}:h?{userOverride:B,feeExecutionMode:h}:{userOverride:B});return cn(K,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 k=p?.grossAmount??y?.grossAmount??u;if(k===u){u=k;break}u=k,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 k=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&e.resolvedTokenIn?e.resolvedTokenIn:e.executionTokenAddress;sr(m,e.resolvedChainId,k);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,k=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 w=f.getChainConfig(y),I=j.createWalletClient({account:e.externalWalletAddress,chain:w?.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:k,value:m,chain:w?.viemChain}):await I.sendTransaction({to:C,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"transfer",args:[k,m]}),chain:w?.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 k=await e.gasless.buildPayChainBatches({fundingAmountOverride:u}),S=k.some(b=>b.tokenTransfers?.length);return await e.gasless.executeGasless(k,i,u,b=>{b.txHash&&(e.ui.setPaymentResult(w=>({...w??{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:k,exactOutputSwap:S,adjustable:b=!1,maxAmount:w,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:k,exactOutputSwap:S,isQuoting:g,adjustable:b,maxAmount:w,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:k,onAmountChange:S})=>{const b='"IBM Plex Mono", monospace',w=parseFloat(p||"0"),I=k?parseFloat(k):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 z=U;z.startsWith(".")&&(z="0"+z);const K=kn(z);let N=K;k&&parseFloat(K)>parseFloat(k)&&(N=k),E(N),A.current&&clearTimeout(A.current),A.current=setTimeout(()=>S?.(N),300)},R=U=>{if(!I)return;if(U===100){E(k||I.toString()),A.current&&clearTimeout(A.current),S?.(k||I.toString());return}const z=10**s,K=Math.floor(I*U/100*z)/z,N=vn(K,s);E(N),A.current&&clearTimeout(A.current),S?.(N)},H=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:w>0?p:"0.00",title:w>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,z)=>{const K=Math.abs(H-U)<1,N=z===4,q=U/100,P=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:K?1:P?.8:.5,transform:V?"scale(0.85)":P?"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&&q>0&&n.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${q>.5?1:0} 1 ${7+6.84375*Math.sin(q*2*Math.PI)} ${7-6.84375*Math.cos(q*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]),k=c.useMemo(()=>JSON.stringify([...o||[]].sort()),[o]),[S,b]=c.useState([]),w=c.useRef(0),I=c.useRef(async()=>{}),C=c.useCallback(async()=>{if(!r||!x||m.length===0){w.current++,b([]);return}const A=++w.current,M=j.getAddress(x),T=a?o&&o.length>0?o:[t.chainId]:[t.chainId],v=[];for(const H of m){const U=H.toLowerCase();if(U===F.ZERO_ADDRESS)continue;if(U===t.address.toLowerCase()){const K=f.getChainConfig(t.chainId)?.supportedTokens?.find(N=>f.addressesEqual(N.address,U));v.push({address:H,chainId:t.chainId,configToken:K?{decimals:K.decimals,symbol:K.symbol,name:K.name,logo:K.logo}:void 0});continue}let z=!1;for(const K of T){const N=f.getChainConfig(K)?.supportedTokens?.find(q=>f.addressesEqual(q.address,U));if(N){v.push({address:H,chainId:K,configToken:{decimals:N.decimals,symbol:N.symbol,name:N.name,logo:N.logo}}),z=!0;break}}z||v.push({address:H,chainId:t.chainId})}const B=new Map;for(const H of v){const U=B.get(H.chainId)||[];U.push(H),B.set(H.chainId,U)}const D=async(H,U)=>{try{const z=await Bt.readContract(H,{address:U.address,abi:j.erc20Abi,functionName:"balanceOf",args:[M]});let K,N,q,P;if(U.configToken)K=U.configToken.decimals,N=U.configToken.symbol,q=U.configToken.name,P=U.configToken.logo;else{const[X,he,W]=await Promise.all([Bt.readContract(H,{address:U.address,abi:j.erc20Abi,functionName:"decimals"}).catch(()=>18),Bt.readContract(H,{address:U.address,abi:j.erc20Abi,functionName:"symbol"}).catch(()=>"TOKEN"),Bt.readContract(H,{address:U.address,abi:j.erc20Abi,functionName:"name"}).catch(()=>"TOKEN")]);K=Number(X),N=he,q=W}const V=f.addressesEqual(U.address,t.address)&&U.chainId===t.chainId;V&&t.logoURI&&(P=t.logoURI),V&&!U.configToken&&N==="TOKEN"&&(N=t.symbol,q=t.symbol);const L=parseFloat((Number(z)/Math.pow(10,K)).toFixed(6));return{address:U.address,name:q,symbol:N,decimals:K,balance:z,balanceFormatted:L,balanceUsd:0,logoURI:P,isNative:!1,chainId:U.chainId}}catch{return null}},R=await Promise.all(Array.from(B.entries()).map(async([H,U])=>{let z;try{z=f.getClientForChain(H)}catch{return[]}const K=[],N=[];for(const P of U){const V=K.length;K.push({address:P.address,abi:j.erc20Abi,functionName:"balanceOf",args:[M]}),P.configToken||K.push({address:P.address,abi:j.erc20Abi,functionName:"decimals"},{address:P.address,abi:j.erc20Abi,functionName:"symbol"},{address:P.address,abi:j.erc20Abi,functionName:"name"}),N.push({start:V,item:P})}let q=null;try{q=await z.multicall({contracts:K})}catch{q=null}return q?N.map(({start:P,item:V})=>{const L=q[P],X=L?.status==="success"?L.result:0n;let he,W,ee,ue;if(V.configToken)he=V.configToken.decimals,W=V.configToken.symbol,ee=V.configToken.name,ue=V.configToken.logo;else{const pe=q[P+1],ge=q[P+2],Q=q[P+3];he=pe?.status==="success"?Number(pe.result):18,W=ge?.status==="success"?ge.result:"TOKEN",ee=Q?.status==="success"?Q.result:W}const xe=f.addressesEqual(V.address,t.address)&&V.chainId===t.chainId;xe&&t.logoURI&&(ue=t.logoURI),xe&&!V.configToken&&W==="TOKEN"&&(W=t.symbol,ee=t.symbol);const Ae=parseFloat((Number(X)/Math.pow(10,he)).toFixed(6));return{address:V.address,name:ee,symbol:W,decimals:he,balance:X,balanceFormatted:Ae,balanceUsd:0,logoURI:ue,isNative:!1,chainId:V.chainId}}):(await Promise.all(U.map(P=>D(z,P)))).filter(P=>P!==null)}));A===w.current&&b(R.flat())},[r,a,x,y,k,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,k,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),k=[];return x.tx.to&&!l&&k.push({to:s.tokenIn,value:0n,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"approve",args:[x.tx.to,s.amountIn]})}),k.push({to:x.tx.to,value:BigInt(x.tx.value||"0"),data:x.tx.data}),{venue:"1inch",amountOut:m,amountOutMinimum:y,calls:k}}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,k]=c.useState(null),[S,b]=c.useState(null),[w,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,[]),H=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 ee=an(s.asset.address,r,s.asset.chainId);return ee?ee.address:null},[s?.asset,r]),z=c.useMemo(()=>s?.asset?Yn(s.asset,r):[],[s?.asset,r]),K=c.useMemo(()=>z.map(W=>W.toLowerCase()).join(","),[z]);c.useEffect(()=>{let W=!1;if(v.current&&(clearTimeout(v.current),v.current=null),!s?.asset||z.length<=1){M(null);return}return v.current=setTimeout(async()=>{const ee=t==="input"?s.amount:i||"0";let ue=0n;try{ue=t==="input"?j.parseUnits(ee,s.asset.decimals):0n}catch{ue=0n}try{const xe=await jo(s.asset,r,{requiredAmount:ue});W||M(xe)}catch{W||M(null)}},400),()=>{W=!0,v.current&&(clearTimeout(v.current),v.current=null)}},[s?.asset,s?.amount,r,z.length,K,t,i]);const N=c.useMemo(()=>A??U,[A,U]),q=c.useMemo(()=>!s?.asset||!N?[]:[N,...z.filter(W=>W.toLowerCase()!==N.toLowerCase())],[s?.asset,N,z]),P=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,L=t==="output"&&parseFloat(i||"0")===0,X=!!s?.asset&&!P&&!V&&!L,he=X?C??N:N;return c.useEffect(()=>{T.current&&clearTimeout(T.current);const W=t==="input"?s?.amount:i,ee=parseFloat(W||"0");if(!X||!Number.isFinite(ee)||ee<=0||!s?.asset||!a||q.length===0){B.current++,g(null),m(null),k(null),b(null),I(null),E(null),h(null),u(!1);return}const ue=s.asset.decimals;let xe;try{xe=t==="input"?j.parseUnits(s.amount,ue):j.parseUnits(i||"0",o.decimals)}catch{B.current++,h("Invalid amount"),u(!1);return}const Ae=++B.current,pe=()=>Ae!==B.current;u(!0);const ge=t==="output"?150:400;return T.current=setTimeout(async()=>{try{if(t==="input"){const Q=R.getVenueForChain(r);if(!Q)throw new Error("No swap venue for this chain");let re=null,G=null;for(const me of q){const Se=`${t}:${r}:${me.toLowerCase()}:${o.address.toLowerCase()}:${xe.toString()}`,te=D.current.get(Se);if(te&&te.expiresAt>Date.now()&&te.resolvedSwap){re=te.resolvedSwap,G=me;break}const O=await Q.resolve({type:"swap",tokenIn:me,tokenOut:o.address,amountIn:xe},r,a);if(pe())return;if(O){D.current.set(Se,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:O}),re=O,G=me;break}}if(!re||!G)throw new Error("No liquidity for this pair");E(G),I(re.amountOut),k(re),b(null);const ie=parseFloat(j.formatUnits(re.amountOut,o.decimals));g(ie<.01?ie.toPrecision(4):ie.toLocaleString(void 0,{maximumFractionDigits:6})),m(null),h(null)}else{let Q=null,re=null;for(const G of q){const ie=`${t}:${r}:${G.toLowerCase()}:${o.address.toLowerCase()}:${xe.toString()}`,me=D.current.get(ie);if(me&&me.expiresAt>Date.now()&&me.exactOutputSwap){Q=me.exactOutputSwap,re=G;break}try{const Se=await H.getQuote({tokenIn:G,tokenOut:o.address,amountOut:xe},r,a);if(pe())return;D.current.set(ie,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:Se}),Q=Se,re=G;break}catch{if(pe())return}}if(!Q||!re)throw new Error("No liquidity for this pair");E(re),b(Q),k(null),I(null),m(parseFloat(j.formatUnits(Q.amountIn,ue)).toFixed(6)),g(null),h(null)}}catch(Q){if(pe())return;const re=Q instanceof Error?Q.message:"Failed to get quote";h(re),g(null),m(null),k(null),b(null),I(null),E(null)}finally{pe()||u(!1)}},ge),()=>{T.current&&clearTimeout(T.current)}},[t,X,s?.amount,s?.asset?.address,s?.asset?.decimals,i,q,r,o.address,o.decimals,a,R,H]),{isQuoting:d,quoteError:l,estimatedOutput:p,estimatedInput:x,resolvedSwap:y,exactOutputSwap:S,quoteAmountOut:w,resolvedTokenIn:he,isDirect:V,needsSwap:X,selectedIsEquivalent:P}}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:k,maxPaymentAmount:S,onAmountChange:b,styles:w,dark:I,title:C,subtitle:E,onAddFunds:A,onSuccess:M,onError:T})=>{const v=p==="output",{theme:B,dark:D,primaryColor:R,dk:H,palette:U,fontFamily:z,monoFont:K,inputDark:N,cardBg:q,cardBorder:P,textPrimary:V,textSecondary:L,subtitleText:X}=f.useSpiceBrand(w,I),he=N?{...B,colors:{...B.colors,secondary:H.cardBg,surfaceHover:H.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:B,W=o.chainId,ee=c.useContext(f.SpiceFlowProviderContext),ue=(ee?.mode||"7702")!=="7702",xe=!!ee?.isWhitelistGateActive,Ae=c.useMemo(()=>r??ee?.supportedChainIds??[],[r,ee?.supportedChainIds]),pe=c.useMemo(()=>{if(xe)return[];if(a)return a;const de=ee?.allowedTokens;if(!de||de.length===0)return;const Be=new Set(de.map(Yt=>Yt.toLowerCase())),Ct=[],en=new Set;for(const Yt of Ae){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),Ct.push(hn.address))}}return Ct},[a,ee?.allowedTokens,Ae,xe]),ge=f.useWallet(),{address:Q,isConnected:re,isReady:G,isAuthenticated:ie,provider:me}=ge,{executeGasless:Se,estimateGasless:te}=ns(),{externalWallet:O,externalAddress:ae,embeddedAddress:ye}=f.useProviderWallets(),Te=f.useEmbeddedWalletAddress()||ye,{displayAssets:at,filteredSpiceAssets:Ye,embeddedWalletAddress:Xe,refreshSpiceAssets:Ee,refreshWalletAssets:oe}=hl({destinationToken:o,supportedSourceAssets:pe,sourceChains:Ae,enabled:e&&(ue?!!ae:!!Te)}),Ne=xe||v||ue?at:Ye,[Y,be]=c.useState(null),[dt,gt]=c.useState(m||""),[Je,Lt]=c.useState(!1),[Tt,xt]=c.useState(null),[ke,Mt]=c.useState("idle"),[Jt,$t]=c.useState(""),[bt,Ot]=c.useState(null),[$e,kt]=c.useState(!1),[Ve,et]=c.useState(null),[tt,ft]=c.useState(null),[Et,fe]=c.useState(!1),[rt,it]=c.useState(!1),[vt,Ce]=c.useState(null),Rt=c.useRef(Y),nt=c.useRef(!1),ht=c.useRef(null),St=c.useRef(0),Kt=c.useRef(null),Ht=c.useRef(null);c.useEffect(()=>{Rt.current=Y},[Y]);const _e=y==="adjustable"?dt:m||"0",Zt=Xe||ye||Q,{isQuoting:Me,quoteError:ut,estimatedOutput:It,resolvedSwap:Le,exactOutputSwap:Ze,quoteAmountOut:jt,resolvedTokenIn:ct,isDirect:Re,needsSwap:Oe,selectedIsEquivalent:mt}=vl({direction:p,selectedAsset:Y,destinationToken:o,chainId:W,recipient:Zt,paymentAmount:_e}),st=v?parseFloat(_e||"0"):parseFloat(Y?.amount||"")||0,Qt=Y?.asset?._source==="wallet",Ue=!!Y?.asset&&Qt&&Y.asset.chainId!==W,Gt=c.useMemo(()=>Y?.asset?Ye.find(de=>f.addressesEqual(de.address,Y.asset.address))?.balanceFormatted??0:0,[Y,Ye]),Vt=Qt?Y?.asset.balanceFormatted??0:Gt,Dt=c.useMemo(()=>{if(!Y?.asset)return!1;if(v)return tt?jn(tt.grossAmount,tt.decimals,Y.asset.decimals)>Y.asset.balance:mt||Re?st>Y.asset.balanceFormatted:Ze?parseFloat(j.formatUnits(Ze.amountInMax,Y.asset.decimals))>Y.asset.balanceFormatted:!1;if(tt){const de=jn(tt.grossAmount,tt.decimals,Y.asset.decimals);return Qt?de>Y.asset.balance:parseFloat(j.formatUnits(de,Y.asset.decimals))>Vt}return st>Vt},[Y,v,tt,mt,st,Ze,Vt,Qt,Re]);c.useEffect(()=>{e||(be(null),xt(null),Lt(!1),Mt("idle"),$t(""),Ot(null),kt(!1),et(null),ft(null),fe(!1),it(!1),Ce(null),nt.current=!1,y==="adjustable"&&gt(m||""),ht.current&&(ht.current.abort(),ht.current=null))},[e]);const ne=c.useCallback(de=>{be(Be=>({asset:de,amount:Be?.asset?.address===de.address&&Be?.asset?.chainId===de.chainId&&Be.amount||""})),xt(null),Ce(null),it(!1)},[]),se=c.useCallback(de=>{be(Be=>Be&&{...Be,amount:de}),xt(null),Ce(null),it(!1)},[]),ve=c.useCallback(de=>{let Be=de;S&&parseFloat(Be)>parseFloat(S)&&(Be=S),gt(Be),b?.(Be),xt(null),Ce(null),it(!1)},[S,b]);c.useCallback(de=>{if(nt.current||!Q)return;const Be=Rt.current;!Be?.asset||!Be.amount||Be.asset?._source==="wallet"||j.parseUnits(v?_e:Be.amount,Be.asset.decimals)===0n||(nt.current=!0,Ee())},[Q,W,Ee,v,_e]);const He=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)},[]),Ge=c.useMemo(()=>({currentPaymentAmount:_e,destinationToken:o,embeddedWalletAddress:Xe,providerEmbeddedAddress:ye,externalWalletAddress:ae,address:Q,isNon7702:ue,isPayMode:v,resolvedChainId:W,buildActionCalls:i,feeExecutionMode:d,buildSpicenetBatch:u,selectedAsset:Y,needsSwap:Oe,resolvedSwap:Le,exactOutputSwap:Ze,quoteAmountOut:jt,resolvedTokenIn:ct}),[_e,o,Xe,ye,ae,Q,ue,v,W,i,d,u,Y,Oe,Le,Ze,jt,ct]),qe=c.useCallback(de=>$i(Ge,de),[Ge]),Qe=c.useCallback(de=>_i(Ge,de),[Ge]),We=c.useCallback((de,Be,Ct,en)=>el(de,Be,Ct,te,en),[te]),Pe=c.useMemo(()=>Y?.asset?Oe&&ct?ct:Y.asset.chainId===W?Y.asset.address:ct??tn(Y.asset,W)??o.address:o.address,[Y,o.address,Oe,W,ct]),J=c.useCallback(()=>ll(Ht.current),[]),ce=c.useMemo(()=>Y?.asset?f.addressesEqual(Y.asset.address,o.address)&&Y.asset.chainId===o.chainId:!1,[Y,o.address,o.chainId]),Fe=ue&&ce,je=Fe&&st>0&&!!Y?.asset,ze=Tt,pt=c.useMemo(()=>!(!Y?.asset||st<=0),[Y,st,je]),qt=c.useMemo(()=>!e||Je||ke!=="idle"||!pt||je||!Y?.asset?null:[v?"pay":"supply",p,Y.asset.address.toLowerCase(),Y.asset.chainId,Y.amount,_e,o.address.toLowerCase(),o.chainId,W,ct?.toLowerCase()??"",Oe?"swap":"direct",Re?"direct-token":"routed-token",ue?"non7702":"7702",ce?"source-dest":"cross-chain",Me?"quoting":"quoted",Ze?.amountIn?.toString()??"",Ze?.amountInMax?.toString()??"",Ze?.venue??"",Le?.amountOut?.toString()??"",jt?.toString()??"",Xe??"",ye??"",Q??""].join("|"),[e,Je,ke,pt,je,Y,v,p,_e,o,W,ct,Oe,Re,ue,ce,Me,Ze,Le,jt,Xe,ye,Q]),Z=c.useCallback(()=>ol({selectedAsset:Y,isPayMode:v,parsedAmount:st,needsSwap:Oe,exactOutputSwap:Ze,isNon7702:ue,isSourceDestToken:ce,currentPaymentAmount:_e,destinationToken:o,feeExecutionMode:d,resolvedTokenIn:ct,embeddedWalletAddress:Xe,providerEmbeddedAddress:ye,resolvedChainId:W,isConnected:re,address:Q,ready:G,authenticated:ie,isDirect:Re,resolvedSwap:Le,isQuoting:Me,executionTokenAddress:Pe,buildPayChainBatches:qe,buildSupplyChainBatches:Qe,estimateGasless:te,estimateRequiredGrossFunding:We}),[Y,v,st,Oe,Ze,ue,ce,_e,o,d,ct,Xe,ye,We,qe,te,W,re,Q,G,ie,Re,Le,Me,Qe,Pe]);c.useEffect(()=>{Kt.current=Z},[Z]);const _=c.useCallback(de=>sl({asset:de,isPayMode:v,isNon7702:ue,needsSwap:Oe,isQuoting:Me,embeddedWalletAddress:Xe,buildSupplyChainBatches:Qe,estimateGasless:te,executionTokenAddress:Pe,feeExecutionMode:d}),[v,ue,Oe,Me,Xe,Qe,te,Pe,d]);c.useEffect(()=>{if(!e){fe(!1),it(!1),Ce(null),ft(null);return}if(Je||ke!=="idle"){St.current+=1,fe(!1);return}if(!pt){ft(null),fe(!1),it(!1),Ce(null);return}if(je){ft(null),fe(!1),it(!0),Ce(null);return}if(Me){St.current+=1,fe(!1),it(!1);return}if(!qt)return;let de=!1;const Be=async()=>{const en=++St.current;Ce(null),fe(!0);try{const Yt=await Kt.current?.();if(de||St.current!==en)return;Yt?(ft(Yt),it(!0)):(ft(null),it(!1)),Ce(null)}catch(Yt){if(de||St.current!==en)return;const Bn=f.sanitizeError(Yt,"Unable to calculate fees for this action.");ft(null),it(!1),Ce(Bn)}finally{!de&&St.current===en&&fe(!1)}},Ct=window.setTimeout(()=>{Be()},250);return()=>{de=!0,clearTimeout(Ct),fe(!1)}},[e,Je,ke,pt,je,Me,qt]);const le=c.useCallback(()=>ul(Ht.current),[]);c.useEffect(()=>{!v&&ke==="success"&&bt&&(Ee(),M?.(bt))},[v,ke,bt,Ee,M]),c.useEffect(()=>{if(!v||Ve?.status!=="success"||nt.current||!Q)return;nt.current=!0;const de=Rt.current;!de?.asset||de.asset?._source==="wallet"||Ee()},[v,Ve?.status,Q,Ee]);const $=c.useRef(M),Ie=c.useRef(T);c.useEffect(()=>{$.current=M},[M]),c.useEffect(()=>{Ie.current=T},[T]),c.useEffect(()=>{e&&(Ee(),oe())},[e,Ee,oe]),c.useEffect(()=>{v&&(Ve?.status==="success"&&$.current?.(Ve.txHash||""),Ve?.status==="failed"&&Ie.current?.(new Error("Payment execution failed")))},[v,Ve?.status]);const De=c.useCallback(()=>{kt(!1),et(null),be(null),nt.current=!1,Ee(),oe()},[Ee,oe]);Ht.current={selectedAsset:Y,parsedAmount:st,currentPaymentAmount:_e,isInsufficientBalance:Dt,isPayMode:v,isNon7702:ue,isSourceDestToken:ce,needsSwap:Oe,exactOutputSwap:Ze,selectedIsEquivalent:mt,resolvedTokenIn:ct,embeddedWalletAddress:Xe,providerEmbeddedAddress:ye,externalWallet:O,externalWalletAddress:ae,address:Q,isConnected:re,ready:G,authenticated:ie,provider:me,resolvedChainId:W,executionTokenAddress:Pe,destinationToken:o,buildActionCalls:i,feeExecutionMode:d,buildSpicenetBatch:u,onPayExecute:l,onError:T,gasless:{estimateGasless:te,executeGasless:Se,buildPayChainBatches:qe,buildSupplyChainBatches:Qe,estimateRequiredGrossFunding:We,onProgress:He},ui:{setError:xt,setStep:Mt,setStatusMsg:$t,setTxHash:Ot,setIsExecuting:Lt,setShowStatusPanel:kt,setPaymentResult:et},refs:{spiceDepositSubmittedRef:nt,abortControllerRef:ht}};const ot=v&&st===0,Ke=v?!!Y?.asset&&st>=0&&!Dt&&!Je&&(ot||je||rt)&&!vt&&(ot||!Oe||!!Ze):!!Y?.asset&&st>0&&!Dt&&!Je&&(Fe||rt)&&!vt&&(Ue||Re||!!Le&&!Me),lt=Re?x||`Your ${o.symbol} will be used directly.`:g||"Your assets will be swapped and used in a single atomic transaction.",Ft=(W?f.getChainConfig(W):void 0)?.viemChain?.blockExplorers?.default?.url??"",yt=Cr.indexOf(ke),Nt=Je?(yr[ke]||"EXECUTING...").toUpperCase():ke==="success"?"DONE":Dt?"INSUFFICIENT BALANCE":h.toUpperCase(),Ut=c.useMemo(()=>{if(Je)return"PAYING...";if(Dt&&Y?.asset)return`INSUFFICIENT ${Y.asset.symbol}`;if(h)return h.toUpperCase();const de=st>0?` ${_e} ${o.symbol}`:"";return Oe?`SWAP & PAY${de}`:`PAY${de}`},[Je,Dt,Y,h,st,_e,o.symbol,Oe]),_t=ke==="success"?()=>{Mt("idle"),be(null),Ot(null),Ee()}:J,pn=ke==="success"?!1:!Ke;if(!e)return null;const fn=v?C||`Pay ${o.symbol}`:h,we=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:X})}),n.jsx("p",{style:{fontSize:"12px",color:X,margin:0,lineHeight:"1.4",fontFamily:z},children:lt})]});if(v){const de=Ve&&(Ve.status==="success"||Ve.status==="failed")?[{asset:{symbol:Y?.asset?.symbol||o.symbol,address:Y?.asset?.address||""},amount:_e,txHash:Ve.txHash||"",success:Ve.status==="success",error:Ve.status==="failed"?Ve.error:void 0}]:void 0;return n.jsx(sn,{isOpen:e,onClose:t,title:fn,subtitle:we,styles:w,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:z})}),n.jsx("div",{style:{marginBottom:"12px"},children:n.jsx(Un,{assets:Ne,selectedAsset:Y??void 0,onAssetSelect:ne,onAmountChange:()=>{},label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:Y?.asset?Oe?Me?"...":Ze?`~${parseFloat(j.formatUnits(Ze.amountIn,Y.asset.decimals)).toFixed(6)}`:void 0:_e??void 0:void 0,dark:D,theme:he,styles:w})}),n.jsx(rr,{variant:"pay",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:R,fontFamily:z,textPrimary:V,textSecondary:L,cardBg:q,cardBorder:P,dk:H,dark:D,isQuoting:Me,quoteError:ut,estimatedOutput:It,paymentAmount:_e,needsSwap:Oe,exactOutputSwap:Ze,adjustable:y==="adjustable",maxAmount:S,onAmountChange:ve}),pt&&n.jsx(qn,{fontFamily:z,textPrimary:V,textSecondary:L,cardBg:q,cardBorder:P,resolvedDark:D,darkCardBorder:H.cardBorder,primaryColor:R,feePreview:tt,isLoading:Et,errorText:vt,directExecutionFeeNote:je}),ze&&n.jsx(In,{variant:"error",palette:U,fontFamily:z,style:{marginBottom:"12px"},children:ze}),n.jsx(f.Button,{variant:"outline",fullWidth:!0,onClick:le,disabled:!Ke,loading:Je,dark:D,styles:{...w,button:{...w?.button,backgroundColor:R}},children:Ut}),Ve&&$e&&n.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:D?H.shell:"white",borderRadius:D?"12px":"6px",padding:"16px 0"},children:n.jsx(Bs,{type:"payment",isOpen:Ve.status!=="processing",isProcessing:Je||Ve.status==="processing",closeOnComplete:!1,chainName:f.getChainName(W),explorerUrl:f.getExplorerUrl(W,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{kt(!1),et(null),le()},onNewTx:De,onClose:()=>{kt(!1),et(null)},onComplete:De,results:de,styles:w,dark:D})})]})})}return n.jsx(sn,{isOpen:e,onClose:t,title:fn,subtitle:we,dark:D,styles:w,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:Ne,selectedAsset:Y||void 0,onAssetSelect:ne,onAmountChange:se,disabled:Je||ke==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:he,styles:w,dark:N,resolveMaxAmount:_,maxAmount:Vt>0?vn(Vt,Y?.asset.decimals??o.decimals):void 0})}),Y?.asset&&!Re&&n.jsx(rr,{variant:"supply",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:R,fontFamily:z,textPrimary:V,textSecondary:L,cardBg:q,cardBorder:P,dark:D,isQuoting:Me,quoteError:ut,estimatedOutput:It}),pt&&n.jsx(qn,{fontFamily:z,textPrimary:V,textSecondary:L,cardBg:q,cardBorder:P,resolvedDark:D,darkCardBorder:H.cardBorder,primaryColor:R,feePreview:tt,isLoading:Et,errorText:vt,directExecutionFeeNote:je}),ke!=="idle"&&n.jsxs("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:ke==="success"?q:ke==="error"?U.errorBg:q,border:`1px solid ${ke==="success"?P:ke==="error"?U.errorBorder:P}`},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[ke==="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"})}):ke==="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:ke==="success"?V:ke==="error"?U.errorText:V,fontFamily:z,flex:1},children:ke==="success"?"Deposit confirmed":ke==="error"?Jt||"Transaction failed":yr[ke]||Jt}),ke==="success"&&bt&&n.jsx("a",{href:`${Ft}/tx/${bt}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:R,fontFamily:z,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),ke==="error"&&n.jsx("button",{onClick:()=>{Mt("idle"),xt(null),setTimeout(J,50)},style:{background:"none",border:"none",fontSize:"12px",color:R,fontFamily:z,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),yt>=0&&ke!=="success"&&ke!=="error"&&n.jsx("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${L}22`,overflow:"hidden"},children:n.jsx("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:R,transformOrigin:"left center",transform:`scaleX(${(yt+1)/Cr.length})`,transition:"transform 400ms ease"}})})]}),Tt&&ke==="idle"&&n.jsx(In,{variant:"error",palette:U,fontFamily:z,style:{marginBottom:"16px"},children:Tt}),n.jsx(f.Button,{variant:"outline",fullWidth:!0,disabled:pn,onClick:_t,theme:B,dark:D,styles:{...w,button:{...w?.button,backgroundColor:R}},style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:K},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),k=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(w){const I=w instanceof Error?w.message:"Failed to export wallet";console.error("Export wallet error:",w),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:k,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"),k=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:k}}),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:k,isEmbeddedMode:S,onModeToggle:b,showConnectExternalCta:w,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:k,isEmbeddedMode:S,onModeToggle:b}),w&&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),k=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[w,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:H,embeddedAddress:U}=f.useProviderWallets(),{dark:z,primaryColor:K,dk:N}=f.useSpiceBrand(d,u),q=k&&!H,P=!k||q,V=P?R||U:B,L=c.useMemo(()=>y?.supportedChainIds??F.getChainIdsByNetwork("mainnet"),[y?.supportedChainIds]),{assets:X,loading:he}=Pn({address:V,supportedChains:L,enabled:!!V&&P,refetchInterval:3e4}),W=c.useMemo(()=>{const oe=P?X.map(Y=>{const be=Y.balanceUsd||0,dt=Number.isFinite(Y.balanceFormatted)?Y.balanceFormatted:0,gt=be>0?be:Rl(Y,a)*dt;return{tokenAddress:Y.address,tokenSymbol:Y.symbol,tokenDisplaySymbol:Cs(Y),tokenDisplayName:ea(Y),tokenDecimals:Y.decimals,chainId:Y.chainId,chainDisplayName:bs(Y),balance:Y.balance.toString(),balanceFormatted:Y.balanceFormatted,usdValue:gt,logoURI:Y.logoURI}}):[],Ne=q?[]:r;return[...oe,...Ne].filter(Y=>Y.balanceFormatted>0)},[P,q,X,a,r]),ee=c.useMemo(()=>W.reduce((oe,Ne)=>oe+Ne.usdValue,0),[W]),{pendingDeposits:ue}=wr({chainIds:L,enabled:!!B,discoverWalletBalances:!1}),xe=c.useMemo(()=>o.reduce((oe,Ne)=>oe+Ne.totalValue,0),[o]),Ae=ee+xe,pe=c.useMemo(()=>{const oe=[];ee>0&&oe.push(`${wn(ee)} idle`);for(const Ne of o){const Y=i.find(be=>be.sectionTitle===Ne.title)?.label||Ne.title.toLowerCase();oe.push(`${wn(Ne.totalValue)} ${Y}`)}return oe.join(" \xB7 ")},[ee,o,i]),ge=c.useCallback(oe=>{g?g(oe):E(oe)},[g]),Q=c.useCallback(()=>{E(null)},[]),re=c.useCallback(()=>{E(null),l?.()},[l]),G=c.useCallback(()=>{if(!T.current)return;const oe=T.current.getBoundingClientRect(),Ne=window.innerHeight-oe.bottom-Cn,Y=oe.top-Cn,be=Ne>=400||Ne>=Y?"below":"above",dt=Math.max(Cn,Math.min(oe.right-Gs,window.innerWidth-Gs-Cn)),gt=be==="below"?oe.bottom+Cn:oe.top-Cn,Je=be==="above"?window.innerHeight-gt:0;M({top:gt,bottom:Je,left:dt,placement:be})},[]);c.useLayoutEffect(()=>{w&&G()},[w,G]),c.useEffect(()=>{if(!w)return;const oe=be=>{T.current&&!T.current.contains(be.target)&&v.current&&!v.current.contains(be.target)&&I(!1)},Ne=be=>{be.key==="Escape"&&I(!1)},Y=()=>G();return document.addEventListener("mousedown",oe),document.addEventListener("keydown",Ne),window.addEventListener("scroll",Y,{passive:!0}),window.addEventListener("resize",G),()=>{document.removeEventListener("mousedown",oe),document.removeEventListener("keydown",Ne),window.removeEventListener("scroll",Y),window.removeEventListener("resize",G)}},[w,G]);const ie=P?R||U||B:H||B,me=c.useCallback(()=>{y?.setMode&&y.setMode(P?"ondemand":"7702")},[y,P]),[Se,te]=c.useState(null);let O=null;try{O=cs.useConnectWallet({onSuccess:()=>te(null),onError:oe=>te(f.sanitizeError(oe,"Failed to connect wallet."))}).connectWallet}catch{O=null}const ae=c.useCallback(()=>{O&&(I(!1),te(null),O({walletChainType:"ethereum-only"}))},[O]),ye=!H&&!!O,Te=c.useCallback(()=>{I(!1),h?.()},[h]),at=c.useCallback(()=>{I(!1),p?.()},[p]),Ye=c.useCallback(oe=>{I(!1),ge(oe)},[ge]);if(typeof window>"u")return null;const Xe=n.jsxs("button",{ref:T,onClick:()=>I(!w),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:z?N.hoverBg:"#ffffff",border:z?`1px solid ${N.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:'"Helvetica Neue", sans-serif',color:z?N.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:z?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[n.jsx("span",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:K,flexShrink:0}}),n.jsxs("span",{children:[e," Account"]}),D&&n.jsxs("span",{style:{color:z?N.textSecondary:"#6b7280"},children:["\xB7 ",wn(Ae)]}),n.jsx("span",{style:{fontSize:"10px",color:z?N.textSecondary:"#9ca3af",transform:w?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),Ee=w?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:z?N.shell:"#ffffff",border:z?`1px solid ${N.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:z?"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 ${wt.out}`},children:n.jsx(Ml,{appName:e,status:t,statusLabel:s,totalUsdValue:Ae,breakdownSubtitle:pe,address:P?ie:B,spiceAssets:W,spiceAssetsLoading:he,pendingDeposits:ue,customSections:o,onDepositClick:h?Te:void 0,onWithdrawClick:p?at:void 0,onCompleteDeposit:Ye,primaryColor:K,dk:N,dark:z,showModeToggle:x,isEmbeddedMode:P,onModeToggle:me,showConnectExternalCta:ye,onConnectExternalWallet:ae,connectExternalError:Se,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(w=>w.chainId===l.chainId);if(!h)return l;const p=Xt(h),g=p.totalFee;if(g<=0n)return l;const x=(l.tokenTransfers??[]).find(w=>a(w)&&j.getAddress(w.to).toLowerCase()===t.toLowerCase()&&!F.isNativeToken(j.getAddress(w.token)));if(!x)return l;const m=j.getAddress(x.token);let y=!1;const k=(l.tokenTransfers??[]).map(w=>y||!a(w)||j.getAddress(w.to).toLowerCase()!==t.toLowerCase()||j.getAddress(w.token).toLowerCase()!==m.toLowerCase()?w:(y=!0,{...w,amount:o?.payoutAlreadyGross?BigInt(w.amount):BigInt(w.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:k,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],k=y.domain==="spicenet";return{hash:x.hash,chainId:x.chainId,tokenTransfers:k?[]: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("/"),k=parseInt(y||"0",10),S=g.intentIds[0];e.startStatusPolling(g.intentIds[0],x),await To({actionId:m,intentIndex:k,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 k=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 w=f.getChainConfig(a),I=j.createWalletClient({account:e.externalWalletAddress,chain:w?.viemChain,transport:j.custom(S)}),C=u?await I.sendTransaction({to:t,value:k,chain:w?.viemChain}):await I.sendTransaction({to:d,data:j.encodeFunctionData({abi:f.U,functionName:"transfer",args:[t,k]}),chain:w?.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]})}]}),k=(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=k(l,d),b=null,w;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=w?.grossAmount===A.grossAmount&&w?.netAmount===A.netAmount&&w?.feeAmount===A.feeAmount;if(b=E,w=A,d=un(e,A),S=k(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:k,sourceToDestinationConversionRate:S,estimatedOutputAmount:b,onAddFunds:w,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",H=!!D?.isWhitelistGateActive,U=R!=="7702",z=c.useMemo(()=>D?.supportedChainIds??[],[D?.supportedChainIds]),K=c.useMemo(()=>{if(H)return[];const J=D?.allowedTokens;if(!J||J.length===0)return[];const ce=new Set(J.map(ze=>ze.toLowerCase())),Fe=[],je=new Set;for(const ze of z){const pt=f.getChainConfig(ze);for(const qt of pt?.supportedTokens??[]){if(!ce.has(qt.symbol.toLowerCase()))continue;const Z=`${ze}:${qt.address.toLowerCase()}`;je.has(Z)||(je.add(Z),Fe.push(j.getAddress(qt.address)))}}return Fe},[D?.allowedTokens,z,H]),N=M?v.cardBg:C?.assetSelector?.backgroundColor||C?.secondaryBackground||"#e9e9e9",q=M?`1px solid ${v.cardBorder}`:"0.5px solid #A8A8A7",P=M?"12px":"6px",V=M?v.textPrimary:"#111827",L=M?v.textSecondary:"#6b7280",X=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]),he=c.useMemo(()=>M?{...A,colors:{...A.colors,secondary:v.cardBg,surfaceHover:v.hoverBg,border:v.cardBorder,borderHover:v.inputBorder}}:A,[M,A]),[W,ee]=c.useState(null),[ue,xe]=c.useState(0),Ae=u?.selectedDurationIdx??ue,pe=u?.setSelectedDurationIdx??xe,[ge,Q]=c.useState(!1),[re,G]=c.useState(null),[ie,me]=c.useState(null),[Se,te]=c.useState(!1),[O,ae]=c.useState(!1),[ye,Te]=c.useState(null),[at,Ye]=c.useState(!1),Xe=c.useRef(0),[Ee,oe]=c.useState(!1),[Ne,Y]=c.useState(null);At.useWalletClient(),At.useSwitchChain();const{chain:be,address:dt}=At.useAccount();At.useConfig();const gt=c.useRef(be);c.useEffect(()=>{gt.current=be},[be]);const Je=f.useWallet(),{isReady:Lt,isAuthenticated:Tt,isConnected:xt,address:ke,provider:Mt,actions:Jt}=Je,{externalWallet:$t,embeddedAddress:bt,externalAddress:Ot}=f.useProviderWallets(),{intentStatus:$e,startStatusPolling:kt,clearStatus:Ve}=lo({checkStepStatus:(J,ce)=>f.relayerService.checkStepStatus(J,ce),retryStep:async(J,ce)=>{const[Fe,je]=J.split("/"),ze=parseInt(je||"0",10);await f.relayerService.executeStep(Fe,ze,ce,{action:"execute"})},maxRetries:3}),{assets:et,refetch:tt}=Pn({address:ke,supportedChains:z,enabled:e&&xt&&!U&&!H,refetchInterval:3e4}),ft=c.useMemo(()=>{if(H)return[];if(K.length===0)return et;const J=new Set(K.map(ce=>ce.toLowerCase()));return et.filter(ce=>J.has(ce.address.toLowerCase()))},[et,K,H]),Et=f.useEmbeddedWalletAddress(),fe=Ot||dt,rt=U?fe:Et,it=c.useMemo(()=>{if(!x)return[];if(H)return m?[j.getAddress(m)]:[];const J=new Set,ce=[],Fe=je=>{if(!je)return;const ze=je.toLowerCase();J.has(ze)||(J.add(ze),ce.push(j.getAddress(je)))};if(m&&Fe(m),U)for(const je of K)Fe(je);return ce},[x,U,m,K,H]),vt=c.useMemo(()=>it.map(J=>J.toLowerCase()).sort().join(","),[it]),Ce=c.useMemo(()=>JSON.stringify([...z||[]].sort()),[z]),[Rt,nt]=c.useState([]),ht=c.useRef(0),St=c.useRef(async()=>{}),Kt=c.useCallback(async()=>{if(!x||!rt||it.length===0){ht.current++,nt([]);return}const J=++ht.current,ce=j.getAddress(rt),Fe=z&&z.length>0?z:[l],je=it.map(_=>{const le=_.toLowerCase();if(m&&f.addressesEqual(_,m)){const $=f.getChainConfig(l)?.supportedTokens?.find(Ie=>f.addressesEqual(Ie.address,le));return{address:_,chainId:l,configToken:$?{decimals:$.decimals,symbol:$.symbol,name:$.name,logo:$.logo}:void 0}}for(const $ of Fe){const Ie=f.getChainConfig($)?.supportedTokens?.find(De=>f.addressesEqual(De.address,le));if(Ie)return{address:_,chainId:$,configToken:{decimals:Ie.decimals,symbol:Ie.symbol,name:Ie.name,logo:Ie.logo}}}return{address:_,chainId:l}}),ze=new Map;for(const _ of je){const le=ze.get(_.chainId)||[];le.push(_),ze.set(_.chainId,le)}const pt=async(_,le)=>{try{const $=await Bt.readContract(_,{address:le.address,abi:f.U,functionName:"balanceOf",args:[ce]});let Ie,De,ot,Ke;if(le.configToken)Ie=le.configToken.decimals,De=le.configToken.symbol,ot=le.configToken.name,Ke=le.configToken.logo;else{const[yt,Nt,Ut]=await Promise.all([Bt.readContract(_,{address:le.address,abi:f.U,functionName:"decimals",args:[]}).catch(()=>18),Bt.readContract(_,{address:le.address,abi:f.U,functionName:"symbol",args:[]}).catch(()=>"TOKEN"),Bt.readContract(_,{address:le.address,abi:f.U,functionName:"name",args:[]}).catch(()=>"TOKEN")]);Ie=Number(yt),De=Nt,ot=Ut}const lt=!!m&&f.addressesEqual(le.address,m)&&le.chainId===l;lt&&a&&(Ke=a),lt&&r&&!le.configToken&&(De==="TOKEN"&&(De=r),ot==="TOKEN"&&(ot=r));const Ft=parseFloat((Number($)/Math.pow(10,Ie)).toFixed(6));return{address:le.address,name:ot,symbol:De,decimals:Ie,balance:$,balanceFormatted:Ft,balanceUsd:0,logoURI:Ke,isNative:!1,chainId:le.chainId}}catch{return null}},qt=await Promise.all(Array.from(ze.entries()).map(async([_,le])=>{let $;try{$=f.getClientForChain(_)}catch{return[]}const Ie=[],De=[];for(const Ke of le){const lt=Ie.length;Ie.push({address:Ke.address,abi:f.U,functionName:"balanceOf",args:[ce]}),Ke.configToken||Ie.push({address:Ke.address,abi:f.U,functionName:"decimals",args:[]},{address:Ke.address,abi:f.U,functionName:"symbol",args:[]},{address:Ke.address,abi:f.U,functionName:"name",args:[]}),De.push({start:lt,item:Ke})}let ot=null;try{ot=await $.multicall({contracts:Ie})}catch{ot=null}return ot?De.map(({start:Ke,item:lt})=>{const Ft=ot[Ke],yt=Ft?.status==="success"?Ft.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=ot[Ke+1],Be=ot[Ke+2],Ct=ot[Ke+3];Nt=de?.status==="success"?Number(de.result):18,Ut=Be?.status==="success"?Be.result:"TOKEN",_t=Ct?.status==="success"?Ct.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 we=parseFloat((Number(yt)/Math.pow(10,Nt)).toFixed(6));return{address:lt.address,name:_t,symbol:Ut,decimals:Nt,balance:yt,balanceFormatted:we,balanceUsd:0,logoURI:pn,isNative:!1,chainId:lt.chainId}}):(await Promise.all(le.map(Ke=>pt($,Ke)))).filter(Ke=>Ke!==null)}));if(J!==ht.current)return;const Z=qt.flat();nt(Z)},[x,rt,vt,Ce,l,m,a,r]);c.useEffect(()=>{St.current=Kt},[Kt]),c.useEffect(()=>{if(!e||!x){nt([]);return}St.current();const J=setInterval(()=>{St.current()},15e3);return()=>clearInterval(J)},[x,e,rt,vt,Ce,l,m]);const Ht=c.useCallback(()=>{Kt()},[Kt]),_e=c.useMemo(()=>Rt.filter(J=>J.balance>0n),[Rt]),Zt=c.useMemo(()=>{if(U)return _e.map(ce=>({...ce,_source:"wallet"}));if(!x)return ft;const J=[];for(const ce of _e)J.push({...ce,_source:"wallet"});for(const ce of ft)J.push({...ce,_source:"spice"});return J},[U,x,_e,ft]),Me=c.useMemo(()=>H?m?Zt.filter(J=>f.addressesEqual(J.address,m)&&J.chainId===l):[]:Zt,[Zt,H,m,l]),ut=c.useRef(null),It=c.useRef(null);c.useEffect(()=>{It.current=W},[W]),c.useEffect(()=>{!H||!W?.asset||m&&f.addressesEqual(W.asset.address,m)&&W.asset.chainId===l||ee(null)},[H,W?.asset,m,l]),c.useEffect(()=>{e||(ee(null),G(null),me(null),te(!1),ae(!1),Te(null),Q(!1),oe(!1),Y(null),Ye(!1),Ve())},[e,Ve]),c.useEffect(()=>{i&&i.assetAmount!==(W?.amount||"")&&ee(J=>J&&{...J,amount:i.assetAmount})},[i?.assetAmount]),c.useEffect(()=>{d&&d.assetAmount!==(W?.amount||"")&&ee(J=>J&&{...J,amount:d.assetAmount})},[d?.assetAmount]),c.useEffect(()=>{if(!U&&$e?.overallStatus==="success"&&$e.intentId&&ut.current!==$e.intentId&&ke&&$e.steps.find(J=>J.transactionHash)?.transactionHash){ut.current=$e.intentId;const J=It.current;if(!J?.asset||!J.amount||J.asset._source==="wallet"||j.parseUnits(J.amount,J.asset.decimals)===0n)return;tt()}},[$e,ke,l,tt,U]);const Le=parseFloat(W?.amount||"")||0,Ze=c.useMemo(()=>W?.asset?W.asset._source==="wallet"?W.asset.balanceFormatted??0:ft.find(J=>f.addressesEqual(J.address,W.asset.address)&&J.chainId===W.asset.chainId)?.balanceFormatted??0:0,[W?.asset,ft]),jt=Le>0&&(ye?parseFloat(j.formatUnits(ye.grossAmount,ye.decimals))>Ze:Le>Ze),ct=u?.selectedDuration??h[Ae]??h[0],Re=c.useMemo(()=>!W?.asset||!m?!1:f.addressesEqual(W.asset.address,m)&&W.asset.chainId===l,[W?.asset,m,l]),Oe=c.useMemo(()=>Le<=0?0:Re?Le:!S||S<=0?0:Le/S,[Le,S,Re]),mt=c.useMemo(()=>Oe<=0?null:Oe.toLocaleString(void 0,{maximumFractionDigits:2}),[Oe]),st=p&&Oe>0&&ct?p(Oe,ct.months):void 0,Qt=c.useMemo(()=>Le<=0?"$0.00":Re&&S?(Le*S).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!S||S<=0?"$0.00":Le.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[Le,S,Re]),Ue=c.useMemo(()=>{if(!mt)return null;const J=parseFloat(mt.replace(/,/g,""));return Re&&S?(J*S).toLocaleString(void 0,{maximumFractionDigits:2}):S?(J*S).toLocaleString(void 0,{maximumFractionDigits:2}):null},[mt,S,Re]),Gt=c.useCallback(J=>{ee(ce=>({asset:J,amount:ce?.asset?.address===J.address&&ce?.asset?.chainId===J.chainId&&ce.amount||""})),G(null),me(null),ae(!1),Te(null),d?.setSelectedAsset&&d.setSelectedAsset({symbol:J.symbol,address:J.address,decimals:J.decimals,chainId:J.chainId})},[d?.setSelectedAsset]),Vt=c.useCallback(J=>{ee(ce=>ce&&{...ce,amount:J}),G(null),me(null),ae(!1),Te(null),i&&i.setAssetAmount(J),d&&d.setAssetAmount(J)},[i,d]),Dt=c.useCallback(J=>{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:J?.amount??W.amount,amountWei:J?.amountWei??j.parseUnits(W.amount,W.asset.decimals),grossAmount:J?.grossAmount,grossAmountWei:J?.grossAmountWei,feeAdjusted:!!J})}return o},[o,W]),ne=c.useRef(null),se=c.useMemo(()=>!W?.asset||Le<=0?!1:U?!Re&&!k:!0,[W,Le,U,Re,k]),ve=c.useCallback(()=>Zi(ne.current),[]);c.useEffect(()=>{if(!e||ge)return;if(!W?.asset||Le<=0){me(null),te(!1),ae(!1),Te(null);return}if(!se){me(null),te(!1),ae(!0),Te(null);return}let J=!1;const ce=async()=>{const ze=++Xe.current;me(null),ae(!1),te(!0);try{const pt=await ve();if(J||Xe.current!==ze)return;me(null),ae(!0),Te(pt)}catch(pt){if(J||Xe.current!==ze)return;me(f.sanitizeError(pt,"Unable to calculate fees for this lock.")),ae(!1)}finally{!J&&Xe.current===ze&&te(!1)}},Fe=window.setTimeout(()=>{ce()},250),je=window.setInterval(()=>{ce()},1e4);return()=>{J=!0,clearTimeout(Fe),window.clearInterval(je),te(!1),ae(!1)}},[e,ge,W,Le,se,ve]),c.useEffect(()=>{if($e?.overallStatus==="success"){const J=$e.steps.find(ce=>ce.transactionHash);y?.(J?.transactionHash)}},[$e?.overallStatus,y]);const He=x&&W?.asset?._source==="wallet"&&W?.asset?.chainId===l,Ge=c.useCallback(()=>Yi(ne.current),[]),qe=!!W?.asset&&Le>0&&!jt&&!ge&&(!se||O&&!Se&&!ie),Qe=re||ie,We=n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[n.jsx(Ss,{color:L}),n.jsxs("p",{style:{fontSize:"13px",color:L,margin:0,lineHeight:"1.5"},children:["Add ",r," by converting assets from your account"]})]});if(ne.current={selectedAsset:W,parsedAmount:Le,selectedDuration:ct,isInsufficientBalance:jt,isSemi7702:U,isSourceDestToken:Re,isDirectDeposit:He,requiresRelayerFeeEstimate:se,address:ke,embeddedWalletAddress:Et,providerEmbeddedAddress:bt,externalWallet:$t,externalWalletAddress:fe,isConnected:xt,ready:Lt,authenticated:Tt,provider:Mt,actions:Jt,lockChainId:l,escrowAddress:g,onLockExecute:k,onLockSuccess:y,buildSpicenetBatch:I,resolveLockBatches:Dt,startStatusPolling:kt,refreshSpiceAssets:tt,refreshWalletAssets:Ht,ui:{setError:G,setIsExecuting:Q,setShowStatusPanel:Ye}},!e)return null;const Pe={backgroundColor:N,border:q,borderRadius:P,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:Ee?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:[w&&n.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:n.jsx(Is,{onClick:w,color:T,fontFamily:B})}),n.jsx("div",{style:{marginTop:"10px",fontSize:"13px",color:L,fontFamily:B},children:n.jsx(Un,{assets:Me,selectedAsset:W??void 0,onAssetSelect:Gt,onAmountChange:Vt,label:"Amount",showBalance:!0,showMaxButton:!0,theme:he,styles:X})}),n.jsx("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:L,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:mt??"0.00"}),n.jsxs("div",{style:{fontSize:"12px",color:L,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:L,fontFamily:B},children:"Lock Duration"}),n.jsx(on,{color:L})]}),n.jsx(Di,{options:h,selectedIndex:Ae,onSelect:pe,primaryColor:T,dark:M,textPrimary:V,textSecondary:L})]}),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:L}),p&&n.jsx(Wi,{votes:st,fontFamily:B,dark:M,textPrimary:V,textSecondary:L})]})]}),se&&n.jsx(qn,{fontFamily:B,textPrimary:V,textSecondary:L,cardBg:N,cardBorder:q,resolvedDark:M,darkCardBorder:v.cardBorder,primaryColor:T,feePreview:ye,isLoading:Se,errorText:ie}),Qe&&n.jsx(In,{variant:"error",palette:v,fontFamily:B,style:{marginBottom:"12px"},children:Qe}),n.jsx(f.Button,{variant:"outline",fullWidth:!0,onClick:Ge,disabled:!qe,loading:ge,dark:M,styles:{...C,button:{...C?.button,backgroundColor:T}},children:ge?He&&!Re?"DEPOSITING...":Re?"LOCKING...":"CONVERTING...":Se&&se?"CALCULATING FEES...":He&&!Re?`DEPOSIT ${r}`:Re?`LOCK ${r}`:`CONVERT TO ${r}`}),n.jsx(Pi,{isOpen:Ee,data:Ne,isLocking:ge,lockError:Qe,onContinue:Ge,onClose:()=>oe(!1),primaryColor:T,fontFamily:B,dark:M}),$e&&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:P},children:n.jsx(Bs,{type:"deposit",showStepBreakdown:!1,isOpen:!!$e&&$e.overallStatus!=="processing",isProcessing:ge||$e?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{Ve(),Ye(!1),Ge()},onNewTx:()=>{Ve(),Ye(!1),ee(null),ut.current=null,tt(),Ht()},onClose:()=>{Ve(),Ye(!1)},onComplete:()=>{Ve(),Ye(!1),ee(null),ut.current=null,tt(),Ht()},results:$e?.overallStatus==="success"||$e?.overallStatus==="failed"?$e.steps.map(J=>({asset:{symbol:W?.asset?.symbol||r,address:W?.asset?.address||""},txHash:J.transactionHash||"",success:J.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:k}=e,S=j.parseUnits(s,o.decimals),b=t?.actionAmountOverride??S,w=r||a||(d?void 0:i);if(!w)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const I={userAddress:w,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:w,amount:v});if(S===0n)return[E];if(m&&y){const T=k??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:w,destinationChainId:l,deliveryToken:T,deliveryAmount:v,deliveryRecipient:w,deliveryTransfers:os(R),sourceAsset:x.asset}):[R]}if(A){const T=k??tn(x.asset,l)??o.address,v=t?.fundingAmountOverride??S,B={...E,tokenTransfers:[M(T,v),...E.tokenTransfers??[]]};return ss(B,g,{userAddress:w,destinationChainId:l,deliveryToken:T,deliveryAmount:v,deliveryRecipient:w,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,k=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),w=t?.fundingAmountOverride??b,I=t?.sourceFundingAmountOverride??b,C=t?.deliveryAmountOverride??w,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:w,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||k===null)throw new Error("Swap quote not available yet")}if(g&&x&&k){const q=d(t?.actionAmountOverride??k,{...M,netAmount:t?.actionAmountOverride??k}),{feeCall:P,remainingCalls:V}=qs(q,u,g,M.feeToken);return[{chainId:a,calls:[...P?[P]:[],...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||k===null)throw new Error("Swap quote not available yet")}if(g&&x&&k){const q=d(t?.actionAmountOverride??k,{...M,netAmount:t?.actionAmountOverride??k}),{feeCall:P,remainingCalls:V}=qs(q,u,g,M.feeToken);return[{chainId:a,calls:[...P?[P]:[],...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,H=(q,P)=>({token:q,from:D?"solver":"escrow",to:o,amount:P}),U=(q,P)=>D?[{token:q,from:"escrow",to:F.SPICE_SOLVER_ADDRESS,amount:P}]:[];if(g){if(!y)throw new Error("Swap input token could not be resolved");if(!x||k===null)throw new Error("Swap quote not available yet")}if(g&&x&&k&&y){const q=d(t?.actionAmountOverride??k,{...M,netAmount:t?.actionAmountOverride??k}),{feeCall:P,remainingCalls:V}=qs(q,u,g,M.feeToken),L={chainId:a,calls:[...P?[P]:[],...x.calls,...V],tokenTransfers:[...U(y,E),H(y,C)]},X=await ss(L,l,{userAddress:o,destinationChainId:a,deliveryToken:y,deliveryAmount:C,withdrawalAmount:E,deliveryRecipient:o,deliveryTransfers:os(L),sourceAsset:s.asset});return R?[R,...X]:X}const z=y??tn(s.asset,a)??i.address,K={chainId:a,calls:T,tokenTransfers:[...U(z,E),H(z,C)]},N=await ss(K,l,{userAddress:o,destinationChainId:a,deliveryToken:z,deliveryAmount:C,withdrawalAmount:E,deliveryRecipient:o,deliveryTransfers:os(K),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(w=>w.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}),k=y?jn(y.gasFee,y.decimals,t.decimals):0n,S=y?jn(y.spicenetFee,y.decimals,t.decimals):0n,b=tl(t.balance,k,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:k,ready:S,authenticated:b,isDirect:w,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),q=p||tn(t.asset,m)||t.asset.address||l.address,P={chainId:m,tokenAddress:q,symbol:F.getTokenByAddress(q,m)?.symbol??t.asset.symbol,decimals:F.getTokenByAddress(q,m)?.decimals??t.asset.decimals};if(i){const ee=g||x;if(!ee)return null;const ue=ee,xe=r?a?.amountInMax??0n:N;if(xe===0n)return null;const Ae=await v(xe,Q=>A({fundingAmountOverride:Q}).then(re=>zt(yn(re),ue)),q,{userOverride:ee,useCustomTransfers:!0}),pe=zt(yn(await A({fundingAmountOverride:Ae})),ue),ge=await T(pe,q,Ae,{userOverride:ee,useCustomTransfers:!0,feeExecutionMode:h});return cn(ge,P)}if(!y||!k||!S||!b)return null;const V=g||x||k,L=r?a?.amountInMax??0n:N;if(L===0n)return null;const X=await v(L,ee=>A({fundingAmountOverride:ee}).then(ue=>zt(yn(ue),V)),q,{useCustomTransfers:!0});let he=zt(yn(await A({fundingAmountOverride:X})),V);const W=await T(he,q,X,{useCustomTransfers:!0,feeExecutionMode:h});return cn(W,P)}if(o<=0||!g)return null;const B=g||x;if(!(!s&&!i&&t.asset?._source==="wallet"&&t.asset.chainId!==m)&&!w&&!I&&!C||C)return null;const D=j.parseUnits(t.amount,t.asset.decimals),R=await M();if(R.length===0)return null;const H=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(H){const N=await f.relayerService.estimateBatchGas({user:B,outputToken:E,stepIndex:0,chainBatches:R}),q=$n(D,10n),P=q+N.gasFee;return{...U,grossAmount:D+P,netAmount:D,totalFee:P,gasFee:N.gasFee,spicenetFee:q,bridgeFee:0n,gasQuoteSource:N.gasQuoteSource}}const z=R.some(N=>N.tokenTransfers?.length),K=await T(R,E,D,z?{userOverride:B,useCustomTransfers:!0,feeExecutionMode:h}:h?{userOverride:B,feeExecutionMode:h}:{userOverride:B});return cn(K,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 k=p?.grossAmount??y?.grossAmount??u;if(k===u){u=k;break}u=k,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 k=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&e.resolvedTokenIn?e.resolvedTokenIn:e.executionTokenAddress;sr(m,e.resolvedChainId,k);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,k=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 w=f.getChainConfig(y),I=j.createWalletClient({account:e.externalWalletAddress,chain:w?.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:k,value:m,chain:w?.viemChain}):await I.sendTransaction({to:C,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"transfer",args:[k,m]}),chain:w?.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 k=await e.gasless.buildPayChainBatches({fundingAmountOverride:u}),S=k.some(b=>b.tokenTransfers?.length);return await e.gasless.executeGasless(k,i,u,b=>{b.txHash&&(e.ui.setPaymentResult(w=>({...w??{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:k,exactOutputSwap:S,adjustable:b=!1,maxAmount:w,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:k,exactOutputSwap:S,isQuoting:g,adjustable:b,maxAmount:w,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:k,onAmountChange:S})=>{const b='"IBM Plex Mono", monospace',w=parseFloat(p||"0"),I=k?parseFloat(k):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 z=U;z.startsWith(".")&&(z="0"+z);const K=kn(z);let N=K;k&&parseFloat(K)>parseFloat(k)&&(N=k),E(N),A.current&&clearTimeout(A.current),A.current=setTimeout(()=>S?.(N),300)},R=U=>{if(!I)return;if(U===100){E(k||I.toString()),A.current&&clearTimeout(A.current),S?.(k||I.toString());return}const z=10**s,K=Math.floor(I*U/100*z)/z,N=vn(K,s);E(N),A.current&&clearTimeout(A.current),S?.(N)},H=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:w>0?p:"0.00",title:w>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,z)=>{const K=Math.abs(H-U)<1,N=z===4,q=U/100,P=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:K?1:P?.8:.5,transform:V?"scale(0.85)":P?"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&&q>0&&n.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${q>.5?1:0} 1 ${7+6.84375*Math.sin(q*2*Math.PI)} ${7-6.84375*Math.cos(q*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]),k=c.useMemo(()=>JSON.stringify([...o||[]].sort()),[o]),[S,b]=c.useState([]),w=c.useRef(0),I=c.useRef(async()=>{}),C=c.useCallback(async()=>{if(!r||!x||m.length===0){w.current++,b([]);return}const A=++w.current,M=j.getAddress(x),T=a?o&&o.length>0?o:[t.chainId]:[t.chainId],v=[];for(const H of m){const U=H.toLowerCase();if(U===F.ZERO_ADDRESS)continue;if(U===t.address.toLowerCase()){const K=f.getChainConfig(t.chainId)?.supportedTokens?.find(N=>f.addressesEqual(N.address,U));v.push({address:H,chainId:t.chainId,configToken:K?{decimals:K.decimals,symbol:K.symbol,name:K.name,logo:K.logo}:void 0});continue}let z=!1;for(const K of T){const N=f.getChainConfig(K)?.supportedTokens?.find(q=>f.addressesEqual(q.address,U));if(N){v.push({address:H,chainId:K,configToken:{decimals:N.decimals,symbol:N.symbol,name:N.name,logo:N.logo}}),z=!0;break}}z||v.push({address:H,chainId:t.chainId})}const B=new Map;for(const H of v){const U=B.get(H.chainId)||[];U.push(H),B.set(H.chainId,U)}const D=async(H,U)=>{try{const z=await Bt.readContract(H,{address:U.address,abi:j.erc20Abi,functionName:"balanceOf",args:[M]});let K,N,q,P;if(U.configToken)K=U.configToken.decimals,N=U.configToken.symbol,q=U.configToken.name,P=U.configToken.logo;else{const[X,he,W]=await Promise.all([Bt.readContract(H,{address:U.address,abi:j.erc20Abi,functionName:"decimals"}).catch(()=>18),Bt.readContract(H,{address:U.address,abi:j.erc20Abi,functionName:"symbol"}).catch(()=>"TOKEN"),Bt.readContract(H,{address:U.address,abi:j.erc20Abi,functionName:"name"}).catch(()=>"TOKEN")]);K=Number(X),N=he,q=W}const V=f.addressesEqual(U.address,t.address)&&U.chainId===t.chainId;V&&t.logoURI&&(P=t.logoURI),V&&!U.configToken&&N==="TOKEN"&&(N=t.symbol,q=t.symbol);const L=parseFloat((Number(z)/Math.pow(10,K)).toFixed(6));return{address:U.address,name:q,symbol:N,decimals:K,balance:z,balanceFormatted:L,balanceUsd:0,logoURI:P,isNative:!1,chainId:U.chainId}}catch{return null}},R=await Promise.all(Array.from(B.entries()).map(async([H,U])=>{let z;try{z=f.getClientForChain(H)}catch{return[]}const K=[],N=[];for(const P of U){const V=K.length;K.push({address:P.address,abi:j.erc20Abi,functionName:"balanceOf",args:[M]}),P.configToken||K.push({address:P.address,abi:j.erc20Abi,functionName:"decimals"},{address:P.address,abi:j.erc20Abi,functionName:"symbol"},{address:P.address,abi:j.erc20Abi,functionName:"name"}),N.push({start:V,item:P})}let q=null;try{q=await z.multicall({contracts:K})}catch{q=null}return q?N.map(({start:P,item:V})=>{const L=q[P],X=L?.status==="success"?L.result:0n;let he,W,ee,ue;if(V.configToken)he=V.configToken.decimals,W=V.configToken.symbol,ee=V.configToken.name,ue=V.configToken.logo;else{const pe=q[P+1],ge=q[P+2],Q=q[P+3];he=pe?.status==="success"?Number(pe.result):18,W=ge?.status==="success"?ge.result:"TOKEN",ee=Q?.status==="success"?Q.result:W}const xe=f.addressesEqual(V.address,t.address)&&V.chainId===t.chainId;xe&&t.logoURI&&(ue=t.logoURI),xe&&!V.configToken&&W==="TOKEN"&&(W=t.symbol,ee=t.symbol);const Ae=parseFloat((Number(X)/Math.pow(10,he)).toFixed(6));return{address:V.address,name:ee,symbol:W,decimals:he,balance:X,balanceFormatted:Ae,balanceUsd:0,logoURI:ue,isNative:!1,chainId:V.chainId}}):(await Promise.all(U.map(P=>D(z,P)))).filter(P=>P!==null)}));A===w.current&&b(R.flat())},[r,a,x,y,k,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,k,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),k=[];return x.tx.to&&!l&&k.push({to:s.tokenIn,value:0n,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"approve",args:[x.tx.to,s.amountIn]})}),k.push({to:x.tx.to,value:BigInt(x.tx.value||"0"),data:x.tx.data}),{venue:"1inch",amountOut:m,amountOutMinimum:y,calls:k}}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,k]=c.useState(null),[S,b]=c.useState(null),[w,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,[]),H=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 ee=an(s.asset.address,r,s.asset.chainId);return ee?ee.address:null},[s?.asset,r]),z=c.useMemo(()=>s?.asset?Yn(s.asset,r):[],[s?.asset,r]),K=c.useMemo(()=>z.map(W=>W.toLowerCase()).join(","),[z]);c.useEffect(()=>{let W=!1;if(v.current&&(clearTimeout(v.current),v.current=null),!s?.asset||z.length<=1){M(null);return}return v.current=setTimeout(async()=>{const ee=t==="input"?s.amount:i||"0";let ue=0n;try{ue=t==="input"?j.parseUnits(ee,s.asset.decimals):0n}catch{ue=0n}try{const xe=await jo(s.asset,r,{requiredAmount:ue});W||M(xe)}catch{W||M(null)}},400),()=>{W=!0,v.current&&(clearTimeout(v.current),v.current=null)}},[s?.asset,s?.amount,r,z.length,K,t,i]);const N=c.useMemo(()=>A??U,[A,U]),q=c.useMemo(()=>!s?.asset||!N?[]:[N,...z.filter(W=>W.toLowerCase()!==N.toLowerCase())],[s?.asset,N,z]),P=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,L=t==="output"&&parseFloat(i||"0")===0,X=!!s?.asset&&!P&&!V&&!L,he=X?C??N:N;return c.useEffect(()=>{T.current&&clearTimeout(T.current);const W=t==="input"?s?.amount:i,ee=parseFloat(W||"0");if(!X||!Number.isFinite(ee)||ee<=0||!s?.asset||!a||q.length===0){B.current++,g(null),m(null),k(null),b(null),I(null),E(null),h(null),u(!1);return}const ue=s.asset.decimals;let xe;try{xe=t==="input"?j.parseUnits(s.amount,ue):j.parseUnits(i||"0",o.decimals)}catch{B.current++,h("Invalid amount"),u(!1);return}const Ae=++B.current,pe=()=>Ae!==B.current;u(!0);const ge=t==="output"?150:400;return T.current=setTimeout(async()=>{try{if(t==="input"){const Q=R.getVenueForChain(r);if(!Q)throw new Error("No swap venue for this chain");let re=null,G=null;for(const me of q){const Se=`${t}:${r}:${me.toLowerCase()}:${o.address.toLowerCase()}:${xe.toString()}`,te=D.current.get(Se);if(te&&te.expiresAt>Date.now()&&te.resolvedSwap){re=te.resolvedSwap,G=me;break}const O=await Q.resolve({type:"swap",tokenIn:me,tokenOut:o.address,amountIn:xe},r,a);if(pe())return;if(O){D.current.set(Se,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:O}),re=O,G=me;break}}if(!re||!G)throw new Error("No liquidity for this pair");E(G),I(re.amountOut),k(re),b(null);const ie=parseFloat(j.formatUnits(re.amountOut,o.decimals));g(ie<.01?ie.toPrecision(4):ie.toLocaleString(void 0,{maximumFractionDigits:6})),m(null),h(null)}else{let Q=null,re=null;for(const G of q){const ie=`${t}:${r}:${G.toLowerCase()}:${o.address.toLowerCase()}:${xe.toString()}`,me=D.current.get(ie);if(me&&me.expiresAt>Date.now()&&me.exactOutputSwap){Q=me.exactOutputSwap,re=G;break}try{const Se=await H.getQuote({tokenIn:G,tokenOut:o.address,amountOut:xe},r,a);if(pe())return;D.current.set(ie,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:Se}),Q=Se,re=G;break}catch{if(pe())return}}if(!Q||!re)throw new Error("No liquidity for this pair");E(re),b(Q),k(null),I(null),m(parseFloat(j.formatUnits(Q.amountIn,ue)).toFixed(6)),g(null),h(null)}}catch(Q){if(pe())return;const re=Q instanceof Error?Q.message:"Failed to get quote";h(re),g(null),m(null),k(null),b(null),I(null),E(null)}finally{pe()||u(!1)}},ge),()=>{T.current&&clearTimeout(T.current)}},[t,X,s?.amount,s?.asset?.address,s?.asset?.decimals,i,q,r,o.address,o.decimals,a,R,H]),{isQuoting:d,quoteError:l,estimatedOutput:p,estimatedInput:x,resolvedSwap:y,exactOutputSwap:S,quoteAmountOut:w,resolvedTokenIn:he,isDirect:V,needsSwap:X,selectedIsEquivalent:P}}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:k,maxPaymentAmount:S,onAmountChange:b,styles:w,dark:I,title:C,subtitle:E,onAddFunds:A,onSuccess:M,onError:T})=>{const v=p==="output",{theme:B,dark:D,primaryColor:R,dk:H,palette:U,fontFamily:z,monoFont:K,inputDark:N,cardBg:q,cardBorder:P,textPrimary:V,textSecondary:L,subtitleText:X}=f.useSpiceBrand(w,I),he=N?{...B,colors:{...B.colors,secondary:H.cardBg,surfaceHover:H.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:B,W=o.chainId,ee=c.useContext(f.SpiceFlowProviderContext),ue=(ee?.mode||"7702")!=="7702",xe=!!ee?.isWhitelistGateActive,Ae=c.useMemo(()=>r??ee?.supportedChainIds??[],[r,ee?.supportedChainIds]),pe=c.useMemo(()=>{if(xe)return[];if(a)return a;const de=ee?.allowedTokens;if(!de||de.length===0)return;const Be=new Set(de.map(Yt=>Yt.toLowerCase())),Ct=[],en=new Set;for(const Yt of Ae){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),Ct.push(hn.address))}}return Ct},[a,ee?.allowedTokens,Ae,xe]),ge=f.useWallet(),{address:Q,isConnected:re,isReady:G,isAuthenticated:ie,provider:me}=ge,{executeGasless:Se,estimateGasless:te}=ns(),{externalWallet:O,externalAddress:ae,embeddedAddress:ye}=f.useProviderWallets(),Te=f.useEmbeddedWalletAddress()||ye,{displayAssets:at,filteredSpiceAssets:Ye,embeddedWalletAddress:Xe,refreshSpiceAssets:Ee,refreshWalletAssets:oe}=hl({destinationToken:o,supportedSourceAssets:pe,sourceChains:Ae,enabled:e&&(ue?!!ae:!!Te)}),Ne=xe||v||ue?at:Ye,[Y,be]=c.useState(null),[dt,gt]=c.useState(m||""),[Je,Lt]=c.useState(!1),[Tt,xt]=c.useState(null),[ke,Mt]=c.useState("idle"),[Jt,$t]=c.useState(""),[bt,Ot]=c.useState(null),[$e,kt]=c.useState(!1),[Ve,et]=c.useState(null),[tt,ft]=c.useState(null),[Et,fe]=c.useState(!1),[rt,it]=c.useState(!1),[vt,Ce]=c.useState(null),Rt=c.useRef(Y),nt=c.useRef(!1),ht=c.useRef(null),St=c.useRef(0),Kt=c.useRef(null),Ht=c.useRef(null);c.useEffect(()=>{Rt.current=Y},[Y]);const _e=y==="adjustable"?dt:m||"0",Zt=Xe||ye||Q,{isQuoting:Me,quoteError:ut,estimatedOutput:It,resolvedSwap:Le,exactOutputSwap:Ze,quoteAmountOut:jt,resolvedTokenIn:ct,isDirect:Re,needsSwap:Oe,selectedIsEquivalent:mt}=vl({direction:p,selectedAsset:Y,destinationToken:o,chainId:W,recipient:Zt,paymentAmount:_e}),st=v?parseFloat(_e||"0"):parseFloat(Y?.amount||"")||0,Qt=Y?.asset?._source==="wallet",Ue=!!Y?.asset&&Qt&&Y.asset.chainId!==W,Gt=c.useMemo(()=>Y?.asset?Ye.find(de=>f.addressesEqual(de.address,Y.asset.address))?.balanceFormatted??0:0,[Y,Ye]),Vt=Qt?Y?.asset.balanceFormatted??0:Gt,Dt=c.useMemo(()=>{if(!Y?.asset)return!1;if(v)return tt?jn(tt.grossAmount,tt.decimals,Y.asset.decimals)>Y.asset.balance:mt||Re?st>Y.asset.balanceFormatted:Ze?parseFloat(j.formatUnits(Ze.amountInMax,Y.asset.decimals))>Y.asset.balanceFormatted:!1;if(tt){const de=jn(tt.grossAmount,tt.decimals,Y.asset.decimals);return Qt?de>Y.asset.balance:parseFloat(j.formatUnits(de,Y.asset.decimals))>Vt}return st>Vt},[Y,v,tt,mt,st,Ze,Vt,Qt,Re]);c.useEffect(()=>{e||(be(null),xt(null),Lt(!1),Mt("idle"),$t(""),Ot(null),kt(!1),et(null),ft(null),fe(!1),it(!1),Ce(null),nt.current=!1,y==="adjustable"&&gt(m||""),ht.current&&(ht.current.abort(),ht.current=null))},[e]);const ne=c.useCallback(de=>{be(Be=>({asset:de,amount:Be?.asset?.address===de.address&&Be?.asset?.chainId===de.chainId&&Be.amount||""})),xt(null),Ce(null),it(!1)},[]),se=c.useCallback(de=>{be(Be=>Be&&{...Be,amount:de}),xt(null),Ce(null),it(!1)},[]),ve=c.useCallback(de=>{let Be=de;S&&parseFloat(Be)>parseFloat(S)&&(Be=S),gt(Be),b?.(Be),xt(null),Ce(null),it(!1)},[S,b]);c.useCallback(de=>{if(nt.current||!Q)return;const Be=Rt.current;!Be?.asset||!Be.amount||Be.asset?._source==="wallet"||j.parseUnits(v?_e:Be.amount,Be.asset.decimals)===0n||(nt.current=!0,Ee())},[Q,W,Ee,v,_e]);const He=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)},[]),Ge=c.useMemo(()=>({currentPaymentAmount:_e,destinationToken:o,embeddedWalletAddress:Xe,providerEmbeddedAddress:ye,externalWalletAddress:ae,address:Q,isNon7702:ue,isPayMode:v,resolvedChainId:W,buildActionCalls:i,feeExecutionMode:d,buildSpicenetBatch:u,selectedAsset:Y,needsSwap:Oe,resolvedSwap:Le,exactOutputSwap:Ze,quoteAmountOut:jt,resolvedTokenIn:ct}),[_e,o,Xe,ye,ae,Q,ue,v,W,i,d,u,Y,Oe,Le,Ze,jt,ct]),qe=c.useCallback(de=>$i(Ge,de),[Ge]),Qe=c.useCallback(de=>_i(Ge,de),[Ge]),We=c.useCallback((de,Be,Ct,en)=>el(de,Be,Ct,te,en),[te]),Pe=c.useMemo(()=>Y?.asset?Oe&&ct?ct:Y.asset.chainId===W?Y.asset.address:ct??tn(Y.asset,W)??o.address:o.address,[Y,o.address,Oe,W,ct]),J=c.useCallback(()=>ll(Ht.current),[]),ce=c.useMemo(()=>Y?.asset?f.addressesEqual(Y.asset.address,o.address)&&Y.asset.chainId===o.chainId:!1,[Y,o.address,o.chainId]),Fe=ue&&ce,je=Fe&&st>0&&!!Y?.asset,ze=Tt,pt=c.useMemo(()=>!(!Y?.asset||st<=0),[Y,st,je]),qt=c.useMemo(()=>!e||Je||ke!=="idle"||!pt||je||!Y?.asset?null:[v?"pay":"supply",p,Y.asset.address.toLowerCase(),Y.asset.chainId,Y.amount,_e,o.address.toLowerCase(),o.chainId,W,ct?.toLowerCase()??"",Oe?"swap":"direct",Re?"direct-token":"routed-token",ue?"non7702":"7702",ce?"source-dest":"cross-chain",Me?"quoting":"quoted",Ze?.amountIn?.toString()??"",Ze?.amountInMax?.toString()??"",Ze?.venue??"",Le?.amountOut?.toString()??"",jt?.toString()??"",Xe??"",ye??"",Q??""].join("|"),[e,Je,ke,pt,je,Y,v,p,_e,o,W,ct,Oe,Re,ue,ce,Me,Ze,Le,jt,Xe,ye,Q]),Z=c.useCallback(()=>ol({selectedAsset:Y,isPayMode:v,parsedAmount:st,needsSwap:Oe,exactOutputSwap:Ze,isNon7702:ue,isSourceDestToken:ce,currentPaymentAmount:_e,destinationToken:o,feeExecutionMode:d,resolvedTokenIn:ct,embeddedWalletAddress:Xe,providerEmbeddedAddress:ye,resolvedChainId:W,isConnected:re,address:Q,ready:G,authenticated:ie,isDirect:Re,resolvedSwap:Le,isQuoting:Me,executionTokenAddress:Pe,buildPayChainBatches:qe,buildSupplyChainBatches:Qe,estimateGasless:te,estimateRequiredGrossFunding:We}),[Y,v,st,Oe,Ze,ue,ce,_e,o,d,ct,Xe,ye,We,qe,te,W,re,Q,G,ie,Re,Le,Me,Qe,Pe]);c.useEffect(()=>{Kt.current=Z},[Z]);const _=c.useCallback(de=>sl({asset:de,isPayMode:v,isNon7702:ue,needsSwap:Oe,isQuoting:Me,embeddedWalletAddress:Xe,buildSupplyChainBatches:Qe,estimateGasless:te,executionTokenAddress:Pe,feeExecutionMode:d}),[v,ue,Oe,Me,Xe,Qe,te,Pe,d]);c.useEffect(()=>{if(!e){fe(!1),it(!1),Ce(null),ft(null);return}if(Je||ke!=="idle"){St.current+=1,fe(!1);return}if(!pt){ft(null),fe(!1),it(!1),Ce(null);return}if(je){ft(null),fe(!1),it(!0),Ce(null);return}if(Me){St.current+=1,fe(!1),it(!1);return}if(!qt)return;let de=!1;const Be=async()=>{const en=++St.current;Ce(null),fe(!0);try{const Yt=await Kt.current?.();if(de||St.current!==en)return;Yt?(ft(Yt),it(!0)):(ft(null),it(!1)),Ce(null)}catch(Yt){if(de||St.current!==en)return;const Bn=f.sanitizeError(Yt,"Unable to calculate fees for this action.");ft(null),it(!1),Ce(Bn)}finally{!de&&St.current===en&&fe(!1)}},Ct=window.setTimeout(()=>{Be()},250);return()=>{de=!0,clearTimeout(Ct),fe(!1)}},[e,Je,ke,pt,je,Me,qt]);const le=c.useCallback(()=>ul(Ht.current),[]);c.useEffect(()=>{!v&&ke==="success"&&bt&&(Ee(),M?.(bt))},[v,ke,bt,Ee,M]),c.useEffect(()=>{if(!v||Ve?.status!=="success"||nt.current||!Q)return;nt.current=!0;const de=Rt.current;!de?.asset||de.asset?._source==="wallet"||Ee()},[v,Ve?.status,Q,Ee]);const $=c.useRef(M),Ie=c.useRef(T);c.useEffect(()=>{$.current=M},[M]),c.useEffect(()=>{Ie.current=T},[T]),c.useEffect(()=>{e&&(Ee(),oe())},[e,Ee,oe]),c.useEffect(()=>{v&&(Ve?.status==="success"&&$.current?.(Ve.txHash||""),Ve?.status==="failed"&&Ie.current?.(new Error("Payment execution failed")))},[v,Ve?.status]);const De=c.useCallback(()=>{kt(!1),et(null),be(null),nt.current=!1,Ee(),oe()},[Ee,oe]);Ht.current={selectedAsset:Y,parsedAmount:st,currentPaymentAmount:_e,isInsufficientBalance:Dt,isPayMode:v,isNon7702:ue,isSourceDestToken:ce,needsSwap:Oe,exactOutputSwap:Ze,selectedIsEquivalent:mt,resolvedTokenIn:ct,embeddedWalletAddress:Xe,providerEmbeddedAddress:ye,externalWallet:O,externalWalletAddress:ae,address:Q,isConnected:re,ready:G,authenticated:ie,provider:me,resolvedChainId:W,executionTokenAddress:Pe,destinationToken:o,buildActionCalls:i,feeExecutionMode:d,buildSpicenetBatch:u,onPayExecute:l,onError:T,gasless:{estimateGasless:te,executeGasless:Se,buildPayChainBatches:qe,buildSupplyChainBatches:Qe,estimateRequiredGrossFunding:We,onProgress:He},ui:{setError:xt,setStep:Mt,setStatusMsg:$t,setTxHash:Ot,setIsExecuting:Lt,setShowStatusPanel:kt,setPaymentResult:et},refs:{spiceDepositSubmittedRef:nt,abortControllerRef:ht}};const ot=v&&st===0,Ke=v?!!Y?.asset&&st>=0&&!Dt&&!Je&&(ot||je||rt)&&!vt&&(ot||!Oe||!!Ze):!!Y?.asset&&st>0&&!Dt&&!Je&&(Fe||rt)&&!vt&&(Ue||Re||!!Le&&!Me),lt=Re?x||`Your ${o.symbol} will be used directly.`:g||"Your assets will be swapped and used in a single atomic transaction.",Ft=(W?f.getChainConfig(W):void 0)?.viemChain?.blockExplorers?.default?.url??"",yt=Cr.indexOf(ke),Nt=Je?(yr[ke]||"EXECUTING...").toUpperCase():ke==="success"?"DONE":Dt?"INSUFFICIENT BALANCE":h.toUpperCase(),Ut=c.useMemo(()=>{if(Je)return"PAYING...";if(Dt&&Y?.asset)return`INSUFFICIENT ${Y.asset.symbol}`;if(h)return h.toUpperCase();const de=st>0?` ${_e} ${o.symbol}`:"";return Oe?`SWAP & PAY${de}`:`PAY${de}`},[Je,Dt,Y,h,st,_e,o.symbol,Oe]),_t=ke==="success"?()=>{Mt("idle"),be(null),Ot(null),Ee()}:J,pn=ke==="success"?!1:!Ke;if(!e)return null;const fn=v?C||`Pay ${o.symbol}`:h,we=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:X})}),n.jsx("p",{style:{fontSize:"12px",color:X,margin:0,lineHeight:"1.4",fontFamily:z},children:lt})]});if(v){const de=Ve&&(Ve.status==="success"||Ve.status==="failed")?[{asset:{symbol:Y?.asset?.symbol||o.symbol,address:Y?.asset?.address||""},amount:_e,txHash:Ve.txHash||"",success:Ve.status==="success",error:Ve.status==="failed"?Ve.error:void 0}]:void 0;return n.jsx(sn,{isOpen:e,onClose:t,title:fn,subtitle:we,styles:w,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:z})}),n.jsx("div",{style:{marginBottom:"12px"},children:n.jsx(Un,{assets:Ne,selectedAsset:Y??void 0,onAssetSelect:ne,onAmountChange:()=>{},label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:Y?.asset?Oe?Me?"...":Ze?`~${parseFloat(j.formatUnits(Ze.amountIn,Y.asset.decimals)).toFixed(6)}`:void 0:_e??void 0:void 0,dark:D,theme:he,styles:w})}),n.jsx(rr,{variant:"pay",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:R,fontFamily:z,textPrimary:V,textSecondary:L,cardBg:q,cardBorder:P,dk:H,dark:D,isQuoting:Me,quoteError:ut,estimatedOutput:It,paymentAmount:_e,needsSwap:Oe,exactOutputSwap:Ze,adjustable:y==="adjustable",maxAmount:S,onAmountChange:ve}),pt&&n.jsx(qn,{fontFamily:z,textPrimary:V,textSecondary:L,cardBg:q,cardBorder:P,resolvedDark:D,darkCardBorder:H.cardBorder,primaryColor:R,feePreview:tt,isLoading:Et,errorText:vt,directExecutionFeeNote:je}),ze&&n.jsx(In,{variant:"error",palette:U,fontFamily:z,style:{marginBottom:"12px"},children:ze}),n.jsx(f.Button,{variant:"outline",fullWidth:!0,onClick:le,disabled:!Ke,loading:Je,dark:D,styles:{...w,button:{...w?.button,backgroundColor:R}},children:Ut}),Ve&&$e&&n.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:D?H.shell:"white",borderRadius:D?"12px":"6px",padding:"16px 0"},children:n.jsx(Bs,{type:"payment",isOpen:Ve.status!=="processing",isProcessing:Je||Ve.status==="processing",closeOnComplete:!1,chainName:f.getChainName(W),explorerUrl:f.getExplorerUrl(W,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{kt(!1),et(null),le()},onNewTx:De,onClose:()=>{kt(!1),et(null)},onComplete:De,results:de,styles:w,dark:D})})]})})}return n.jsx(sn,{isOpen:e,onClose:t,title:fn,subtitle:we,dark:D,styles:w,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:Ne,selectedAsset:Y||void 0,onAssetSelect:ne,onAmountChange:se,disabled:Je||ke==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:he,styles:w,dark:N,resolveMaxAmount:_,maxAmount:Vt>0?vn(Vt,Y?.asset.decimals??o.decimals):void 0})}),Y?.asset&&!Re&&n.jsx(rr,{variant:"supply",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:R,fontFamily:z,textPrimary:V,textSecondary:L,cardBg:q,cardBorder:P,dark:D,isQuoting:Me,quoteError:ut,estimatedOutput:It}),pt&&n.jsx(qn,{fontFamily:z,textPrimary:V,textSecondary:L,cardBg:q,cardBorder:P,resolvedDark:D,darkCardBorder:H.cardBorder,primaryColor:R,feePreview:tt,isLoading:Et,errorText:vt,directExecutionFeeNote:je}),ke!=="idle"&&n.jsxs("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:ke==="success"?q:ke==="error"?U.errorBg:q,border:`1px solid ${ke==="success"?P:ke==="error"?U.errorBorder:P}`},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[ke==="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"})}):ke==="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:ke==="success"?V:ke==="error"?U.errorText:V,fontFamily:z,flex:1},children:ke==="success"?"Deposit confirmed":ke==="error"?Jt||"Transaction failed":yr[ke]||Jt}),ke==="success"&&bt&&n.jsx("a",{href:`${Ft}/tx/${bt}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:R,fontFamily:z,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),ke==="error"&&n.jsx("button",{onClick:()=>{Mt("idle"),xt(null),setTimeout(J,50)},style:{background:"none",border:"none",fontSize:"12px",color:R,fontFamily:z,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),yt>=0&&ke!=="success"&&ke!=="error"&&n.jsx("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${L}22`,overflow:"hidden"},children:n.jsx("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:R,transformOrigin:"left center",transform:`scaleX(${(yt+1)/Cr.length})`,transition:"transform 400ms ease"}})})]}),Tt&&ke==="idle"&&n.jsx(In,{variant:"error",palette:U,fontFamily:z,style:{marginBottom:"16px"},children:Tt}),n.jsx(f.Button,{variant:"outline",fullWidth:!0,disabled:pn,onClick:_t,theme:B,dark:D,styles:{...w,button:{...w?.button,backgroundColor:R}},style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:K},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),k=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(w){const I=w instanceof Error?w.message:"Failed to export wallet";console.error("Export wallet error:",w),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:k,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"),k=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("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:k}}),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:k,isEmbeddedMode:S,onModeToggle:b,showConnectExternalCta:w,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:k,isEmbeddedMode:S,onModeToggle:b}),w&&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),k=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[w,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:H,embeddedAddress:U}=f.useProviderWallets(),{dark:z,primaryColor:K,dk:N}=f.useSpiceBrand(d,u),q=k&&!H,P=!k||q,V=P?R||U:B,L=c.useMemo(()=>y?.supportedChainIds??F.getChainIdsByNetwork("mainnet"),[y?.supportedChainIds]),{assets:X,loading:he}=Pn({address:V,supportedChains:L,enabled:!!V&&P,refetchInterval:3e4}),W=c.useMemo(()=>{const oe=P?X.map(Y=>{const be=Y.balanceUsd||0,dt=Number.isFinite(Y.balanceFormatted)?Y.balanceFormatted:0,gt=be>0?be:Rl(Y,a)*dt;return{tokenAddress:Y.address,tokenSymbol:Y.symbol,tokenDisplaySymbol:Cs(Y),tokenDisplayName:ea(Y),tokenDecimals:Y.decimals,chainId:Y.chainId,chainDisplayName:bs(Y),balance:Y.balance.toString(),balanceFormatted:Y.balanceFormatted,usdValue:gt,logoURI:Y.logoURI}}):[],Ne=q?[]:r;return[...oe,...Ne].filter(Y=>Y.balanceFormatted>0)},[P,q,X,a,r]),ee=c.useMemo(()=>W.reduce((oe,Ne)=>oe+Ne.usdValue,0),[W]),{pendingDeposits:ue}=wr({chainIds:L,enabled:!!B,discoverWalletBalances:!0}),xe=c.useMemo(()=>o.reduce((oe,Ne)=>oe+Ne.totalValue,0),[o]),Ae=ee+xe,pe=c.useMemo(()=>{const oe=[];ee>0&&oe.push(`${wn(ee)} idle`);for(const Ne of o){const Y=i.find(be=>be.sectionTitle===Ne.title)?.label||Ne.title.toLowerCase();oe.push(`${wn(Ne.totalValue)} ${Y}`)}return oe.join(" \xB7 ")},[ee,o,i]),ge=c.useCallback(oe=>{g?g(oe):E(oe)},[g]),Q=c.useCallback(()=>{E(null)},[]),re=c.useCallback(()=>{E(null),l?.()},[l]),G=c.useCallback(()=>{if(!T.current)return;const oe=T.current.getBoundingClientRect(),Ne=window.innerHeight-oe.bottom-Cn,Y=oe.top-Cn,be=Ne>=400||Ne>=Y?"below":"above",dt=Math.max(Cn,Math.min(oe.right-Gs,window.innerWidth-Gs-Cn)),gt=be==="below"?oe.bottom+Cn:oe.top-Cn,Je=be==="above"?window.innerHeight-gt:0;M({top:gt,bottom:Je,left:dt,placement:be})},[]);c.useLayoutEffect(()=>{w&&G()},[w,G]),c.useEffect(()=>{if(!w)return;const oe=be=>{T.current&&!T.current.contains(be.target)&&v.current&&!v.current.contains(be.target)&&I(!1)},Ne=be=>{be.key==="Escape"&&I(!1)},Y=()=>G();return document.addEventListener("mousedown",oe),document.addEventListener("keydown",Ne),window.addEventListener("scroll",Y,{passive:!0}),window.addEventListener("resize",G),()=>{document.removeEventListener("mousedown",oe),document.removeEventListener("keydown",Ne),window.removeEventListener("scroll",Y),window.removeEventListener("resize",G)}},[w,G]);const ie=P?R||U||B:H||B,me=c.useCallback(()=>{y?.setMode&&y.setMode(P?"ondemand":"7702")},[y,P]),[Se,te]=c.useState(null);let O=null;try{O=cs.useConnectWallet({onSuccess:()=>te(null),onError:oe=>te(f.sanitizeError(oe,"Failed to connect wallet."))}).connectWallet}catch{O=null}const ae=c.useCallback(()=>{O&&(I(!1),te(null),O({walletChainType:"ethereum-only"}))},[O]),ye=!H&&!!O,Te=c.useCallback(()=>{I(!1),h?.()},[h]),at=c.useCallback(()=>{I(!1),p?.()},[p]),Ye=c.useCallback(oe=>{I(!1),ge(oe)},[ge]);if(typeof window>"u")return null;const Xe=n.jsxs("button",{ref:T,onClick:()=>I(!w),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:z?N.hoverBg:"#ffffff",border:z?`1px solid ${N.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:'"Helvetica Neue", sans-serif',color:z?N.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:z?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[n.jsxs("span",{children:[e," Account"]}),D&&n.jsxs("span",{style:{color:z?N.textSecondary:"#6b7280"},children:["\xB7 ",wn(Ae)]}),n.jsx("span",{style:{fontSize:"10px",color:z?N.textSecondary:"#9ca3af",transform:w?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),Ee=w?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:z?N.shell:"#ffffff",border:z?`1px solid ${N.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:z?"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 ${wt.out}`},children:n.jsx(Ml,{appName:e,status:t,statusLabel:s,totalUsdValue:Ae,breakdownSubtitle:pe,address:P?ie:B,spiceAssets:W,spiceAssetsLoading:he,pendingDeposits:ue,customSections:o,onDepositClick:h?Te:void 0,onWithdrawClick:p?at:void 0,onCompleteDeposit:Ye,primaryColor:K,dk:N,dark:z,showModeToggle:x,isEmbeddedMode:P,onModeToggle:me,showConnectExternalCta:ye,onConnectExternalWallet:ae,connectExternalError:Se,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); }