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