@spicenet-io/spiceflow-ui 3.3.14 → 3.3.15
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
|
-
`})]})},ri="0xa9059cbb";function ai(e){const t=new Map;for(const s of e){if(s.amount<=0n)continue;const o=j.getAddress(s.token),r=j.getAddress(s.to),a=`${o.toLowerCase()}:${r.toLowerCase()}`,i=t.get(a);i?i.amount+=s.amount:t.set(a,{token:o,to:r,amount:s.amount})}return[...t.values()]}function ii(e,t){return`0x${t}${e.slice(4)}`}function li(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,c=i.chainTokens;if((Array.isArray(c)?c.filter(u=>typeof u=="string"):c&&typeof c=="object"?Object.keys(c):[]).some(u=>u.toLowerCase()===o))try{r+=BigInt(i.balanceAvailable??"0")}catch{}}return r}async function To(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 li(a?.balances,s,o)}async function ci({apiBaseUrl:e,user:t,chainId:s,tokenAddress:o,prevBalance:r,timeoutMs:a=3e4,pollIntervalMs:i=1500}){const c=Date.now()+a;for(await new Promise(u=>setTimeout(u,800));Date.now()<c;){try{if(await To(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 Ts(e,t){return Mo(e,t)}function Mo(e,t,s){const o=di(t,e),r=Math.floor(Date.now()/1e3)+60*10,a=R.hashChainBatches(o);return{user:e,...s?{chainAuthorizations:s}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:"0x00",nbf:0,exp:r,chainBatches:a.map((i,c)=>({hash:i.hash,chainId:i.chainId,tokenTransfers:o[c].domain==="spicenet"?[]:o[c].tokenTransfers??[],calls:i.calls}))}]}}function di(e,t){return e.map(s=>{if(s.domain==="spicenet"||s.calls.length===0)return s;const o=new Set((s.tokenTransfers??[]).filter(a=>(a.from==="escrow"||a.from==="solver")&&j.getAddress(a.to).toLowerCase()===t.toLowerCase()).map(a=>j.getAddress(a.token).toLowerCase()));if(o.size===0)return s;let r=0;for(const a of s.calls){if(!a.data?.startsWith(ri))break;try{const i=j.decodeFunctionData({abi:h._,data:a.data});if(i.functionName!=="transfer")break;const[c]=i.args;if(c.toLowerCase()===t.toLowerCase()||!o.has(j.getAddress(a.to).toLowerCase()))break;r+=1}catch{break}}return r===0?s:{...s,calls:s.calls.slice(r)}})}function Gn(e,t,s){if(e.some(u=>u.domain==="spicenet"))return e;const o=s?.intents.flatMap(u=>u.batches),r=u=>u.from==="escrow",a=e.map(u=>{const d=o?.find(y=>y.chainId===u.chainId);if(!d)return u;const f=an(d).totalFee;if(f<=0n)return u;const p=(u.tokenTransfers??[]).find(y=>r(y)&&j.getAddress(y.to).toLowerCase()===t.toLowerCase()&&!R.isNativeToken(j.getAddress(y.token)));if(!p)return u;const g=j.getAddress(p.token);let m=!1;const x=(u.tokenTransfers??[]).map(y=>m||!r(y)||j.getAddress(y.to).toLowerCase()!==t.toLowerCase()||j.getAddress(y.token).toLowerCase()!==g.toLowerCase()?y:(m=!0,{...y,amount:BigInt(y.amount)+f}));return m?{...u,tokenTransfers:x,calls:[{to:g,value:0n,data:j.encodeFunctionData({abi:h._,functionName:"transfer",args:[gn,f]})},...u.calls]}:u}),i=a.flatMap(u=>(u.tokenTransfers??[]).filter(r).map(d=>{const f=j.getAddress(d.token),p=j.getAddress(d.to),g=[{token:f,to:p,amount:BigInt(d.amount)}];return{chainId:u.chainId,transfers:ai(g)}}));if(i.length===0)return e;const c=BigInt(Math.floor(Date.now()/1e3))+3600n;return[{chainId:R.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:i.map((u,d)=>{const f=j.keccak256(j.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,u.transfers[0].token,u.transfers.reduce((g,m)=>g+m.amount,0n),BigInt(u.chainId),BigInt(Date.now()+d)])),p=ii(f,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:j.encodeFunctionData({abi:R.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${u.chainId}`,idempotenceKey:p,nbf:0n,exp:c,metadata:"{}",transfers:u.transfers.map(g=>({token:g.token.toLowerCase(),to:g.to,amount:g.amount}))}]})}})},...a]}function Jn(e,t){const s=e.selectedAsset?.asset;if(!s||!e.selectedAsset?.amount)throw new Error("Select an asset and enter an amount");const o=t?.netAmount??j.parseUnits(e.selectedAsset.amount,s.decimals),r=t?.grossAmount??o;return e.resolveLockBatches({amount:j.formatUnits(o,s.decimals),amountWei:o,grossAmount:j.formatUnits(r,s.decimals),grossAmountWei:r})}async function Ro(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=h.getClientForChain(a),c=h.getDelegateContractAddress(a),u=await R.getAccountNonce(t,i),d=await e.actions.signAuthorization({contractAddress:c,chainId:a,nonce:Number(u)});r.push(d)}return r}async function Do(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 Ro(e,o,t),a=R.hashChainBatches(t),i=Math.floor(Date.now()/1e3)+60*10,c=a.map(m=>m.hash),u=j.keccak256(j.encodeAbiParameters([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,BigInt(i),c])),d=await e.actions.signMessage({raw:u}),f=typeof d=="string"?d:d.signature;if(!f)throw new Error("Failed to sign intent authorization");const p={mode:"7702",signatureType:"ecdsa",signature:f,nbf:0,exp:i,chainBatches:a.map((m,x)=>{const y=t[x],k=y.domain==="spicenet";return{hash:m.hash,chainId:m.chainId,tokenTransfers:k?[]:y.tokenTransfers??[],calls:m.calls}})},g=await h.relayerService.createAction({user:o,chainAuthorizations:r.map(m=>({r:m.r,s:m.s,yParity:m.yParity,address:m.address,chainId:Number(m.chainId),nonce:Number(m.nonce)})),intents:[p]});if(g){const m=h.createInitialSteps(t,h.getChainName),[x,y]=g.intentIds[0].split("/"),k=parseInt(y||"0",10),C=g.intentIds[0];e.startStatusPolling(g.intentIds[0],m),await xo({actionId:x,intentIndex:k,intentId:C,totalSteps:t.length,isSpicenetStep:w=>t[w]?.domain==="spicenet",maxExecuteAttemptsForStep:w=>t[w]?.domain==="spicenet"?6:3,maxPolls:180})}}async function No(e){let t=Jn(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 Ro(e,s,t);let r=Gn([...t],s),a;for(let i=0;i<4;i+=1){const c=await h.relayerService.estimateActionFees(Mo(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=Xn(c,{symbol:e.selectedAsset?.asset.symbol??"",decimals:e.selectedAsset?.asset.decimals??18});if(!u)break;const d={grossAmount:u.grossAmount,netAmount:u.netAmount,feeAmount:u.totalFee??0n},f=a?.grossAmount===d.grossAmount&&a?.netAmount===d.netAmount&&a?.feeAmount===d.feeAmount;if(a=d,t=Jn(e,a),r=Gn([...t],s,c),f)break}await Do(e,r,o)}async function ui(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");if(!e.address||!e.embeddedWalletAddress)throw new Error("Embedded wallet not connected");const t=e.selectedAsset.asset,s=j.parseUnits(e.selectedAsset.amount,t.decimals),o=e.escrowAddress||h.getDelegateContractAddress(e.lockChainId),r=h.relayerService.getBaseUrl(),a=R.normalizeNativeTokenAddress(t.address);let i=0n;try{i=await To(r,e.embeddedWalletAddress,e.lockChainId,a)}catch(p){console.warn("[SpiceLockModal] could not snapshot spice balance pre-deposit:",p?.message)}const c=await e.actions.getEthereumProvider();await h.ensureWalletOnChain(c,e.lockChainId);const u=h.getChainConfig(e.lockChainId),d=j.createWalletClient({account:e.embeddedWalletAddress,transport:j.custom(c),chain:u?.viemChain});let f;if(t.isNative||R.isNativeToken(t.address))f=await d.sendTransaction({to:o,value:s,chain:u?.viemChain});else{const p=j.encodeFunctionData({abi:h._,functionName:"transfer",args:[o,s]});f=await d.sendTransaction({to:t.address,data:p,chain:u?.viemChain})}if((await h.getClientForChain(e.lockChainId).waitForTransactionReceipt({hash:f,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to escrow failed");await ci({apiBaseUrl:r,user:e.embeddedWalletAddress,chainId:e.lockChainId,tokenAddress:a,prevBalance:i}),await e.refreshSpiceAssets(),e.refreshWalletAssets(),await No(e)}async function pi(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 w=e.resolveLockBatches();if(w.length===0)throw new Error("No lock batches configured");const b=e.selectedAsset.asset,S=j.parseUnits(e.selectedAsset.amount,b.decimals),I=await e.onLockExecute({asset:b,amount:e.selectedAsset.amount,amountWei:S,lockDurationMonths:e.selectedDuration?.months??0,chainBatches:w});I&&e.onLockSuccess?.(I);return}const s=e.resolveLockBatches();if(s.length===0)throw new Error("No lock batches configured");const o=e.selectedAsset.asset,r=j.parseUnits(e.selectedAsset.amount,o.decimals),a=o.chainId,i=e.escrowAddress||R.getEscrowContractAddress(a),c=R.normalizeNativeTokenAddress(o.address),u=o.isNative||R.isNativeToken(c);let d=null;for(const w of s){const b=w.tokenTransfers?.find(S=>S.from==="escrow");if(b){d={batch:w,to:b.to,token:b.token,amount:BigInt(b.amount)};break}}const f=await e.externalWallet.getEthereumProvider();let p=null;try{const w=await f.request({method:"eth_chainId"});p=parseInt(w,16)}catch{p=null}p!==a&&await h.ensureWalletOnChain(f,a);const g=h.getChainConfig(a),m=j.createWalletClient({account:e.externalWalletAddress,chain:g?.viemChain,transport:j.custom(f)}),x=u?await m.sendTransaction({to:t,value:r,chain:g?.viemChain}):await m.sendTransaction({to:c,data:j.encodeFunctionData({abi:h._,functionName:"transfer",args:[t,r]}),chain:g?.viemChain});if((await h.getClientForChain(a).waitForTransactionReceipt({hash:x,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to embedded wallet failed");const y={chainId:a,calls:u?[{to:i,value:r,data:"0x"}]:[{to:c,value:0n,data:j.encodeFunctionData({abi:h._,functionName:"transfer",args:[i,r]})}]};let k=null;if(d){if(!e.buildSpicenetBatch)throw new Error("Lock batches declare an escrow-backed ERC20 payout but no `buildSpicenetBatch` callback was provided. The relayer rejects 7702 intents with escrow-backed ERC20 transfers unless the intent includes a Spicenet batch authorising the withdrawal.");const w=e.buildSpicenetBatch({userAddress:t,destinationChainId:d.batch.chainId,deliveryToken:d.token,deliveryAmount:d.amount,deliveryRecipient:d.to});w&&(k={...w,domain:w.domain??"spicenet"})}const C=[y];k&&C.push(k),C.push(...s),await Do(e,C)}async function fi(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");const c=e.resolveLockBatches();if(c.length===0)throw new Error("No lock batches configured");const u=e.selectedAsset.asset,d=j.parseUnits(e.selectedAsset.amount,u.decimals),f=u.chainId,p=e.escrowAddress||R.getEscrowContractAddress(f),g=R.normalizeNativeTokenAddress(u.address),m=u.isNative||R.isNativeToken(g);let x=null;for(const b of c){const S=b.tokenTransfers?.find(I=>I.from==="escrow");if(S){x={batch:b,to:S.to,token:S.token,amount:BigInt(S.amount)};break}}const y={chainId:f,calls:m?[{to:p,value:d,data:"0x"}]:[{to:g,value:0n,data:j.encodeFunctionData({abi:h._,functionName:"transfer",args:[p,d]})}]};let k=null;if(x){if(!e.buildSpicenetBatch)throw new Error("Lock batches declare an escrow-backed payout but no `buildSpicenetBatch` callback was provided.");const b=e.buildSpicenetBatch({userAddress:i,destinationChainId:x.batch.chainId,deliveryToken:x.token,deliveryAmount:x.amount,deliveryRecipient:x.to});b&&(k={...b,domain:b.domain??"spicenet"})}const C=[y];k&&C.push(k),C.push(...c);const w=await h.relayerService.estimateActionFees(Ts(i,C));return Xn(w,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals})}const t=e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");let s=Jn(e);if(s.length===0)throw new Error("No lock batches configured");let o=Gn([...s],t),r=null;for(let i=0;i<4;i+=1){const c=await h.relayerService.estimateActionFees(Ts(t,o)),u=Xn(c,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals});if(!u)return null;const d={grossAmount:u.grossAmount,netAmount:u.netAmount},f=r?.grossAmount===u.grossAmount&&r?.netAmount===u.netAmount&&r?.totalFee===u.totalFee;if(r=u,s=Jn(e,d),o=Gn([...s],t,c),f)break}if(r)return r;const a=await h.relayerService.estimateActionFees(Ts(t,o));return Xn(a,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals})}async function hi(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.resolveLockBatches();if(t.length===0)throw new Error("No lock batches configured");const s=t.find(d=>d.chainId===e.lockChainId)||t[0];if(!s)throw new Error("No lock batch for lock chain");const o=await e.externalWallet.getEthereumProvider();let r=null;try{const d=await o.request({method:"eth_chainId"});r=parseInt(d,16)}catch{r=null}r!==e.lockChainId&&await h.ensureWalletOnChain(o,e.lockChainId);const a=h.getChainConfig(e.lockChainId),i=j.createWalletClient({account:e.externalWalletAddress,chain:a?.viemChain,transport:j.custom(o)}),c=h.getClientForChain(e.lockChainId);let u;for(const d of s.calls){const f=await i.sendTransaction({to:d.to,data:d.data,value:d.value,chain:a?.viemChain});if((await c.waitForTransactionReceipt({hash:f,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Lock transaction failed");u=f}u&&e.onLockSuccess?.(u)}async function mi(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=h.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 hi(e)}catch(s){t(s)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{await pi(e)}catch(s){t(s)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{e.isDirectDeposit&&!e.isSourceDestToken?await ui(e):await No(e)}catch(s){t(s)}finally{e.ui.setIsExecuting(!1)}}const Wo=({isOpen:e,onClose:t,closeOnBackdropClick:s=!1,lockBatches:o,lockTokenSymbol:r,lockTokenLogoURI:a,destinationInputHook:i,sourceAssetInputHook:c,lockDurationHook:u,lockChainId:d,durationOptions:f,votingPowerEstimate:p,escrowAddress:g,includeWalletAssets:m=!1,destinationTokenAddress:x,onLockSuccess:y,onLockExecute:k,sourceToDestinationConversionRate:C,estimatedOutputAmount:w,onAddFunds:b,buildSpicenetBatch:S,styles:I,dark:A=!1})=>{const{theme:F,dark:E,primaryColor:T,dk:v}=h.useSpiceBrand(I,A),M=F.typography.fontFamily,B=l.useContext(h.SpiceFlowProviderContext),N=(B?.mode||"7702")!=="7702",D=l.useMemo(()=>B?.supportedChainIds??[],[B?.supportedChainIds]),q=l.useMemo(()=>{const K=B?.allowedTokens;if(!K||K.length===0)return[];const le=new Set(K.map(Ve=>Ve.toLowerCase())),De=[],Ie=new Set;for(const Ve of D){const We=h.getChainConfig(Ve);for(const ze of We?.supportedTokens??[]){if(!le.has(ze.symbol.toLowerCase()))continue;const Ge=`${Ve}:${ze.address.toLowerCase()}`;Ie.has(Ge)||(Ie.add(Ge),De.push(j.getAddress(ze.address)))}}return De},[B?.allowedTokens,D]),z=E?v.cardBg:I?.assetSelector?.backgroundColor||I?.secondaryBackground||"#e9e9e9",O=E?`1px solid ${v.cardBorder}`:"0.5px solid #A8A8A7",U=E?"12px":"6px",Y=E?v.textPrimary:"#111827",L=E?v.textSecondary:"#6b7280",ne=l.useMemo(()=>({...I,assetSelector:{...I?.assetSelector,backgroundColor:E?v.cardBg:I?.assetSelector?.backgroundColor,borderRadius:E?"12px":I?.assetSelector?.borderRadius},secondaryBackground:E?v.cardBg:I?.secondaryBackground}),[I,E]),H=l.useMemo(()=>E?{...F,colors:{...F.colors,secondary:v.cardBg,surfaceHover:v.hoverBg,border:v.cardBorder,borderHover:v.inputBorder}}:F,[E,F]),[W,re]=l.useState(null),[ee,ie]=l.useState(0),we=u?.selectedDurationIdx??ee,Ae=u?.setSelectedDurationIdx??ie,[X,ue]=l.useState(!1),[xe,Z]=l.useState(null),[ce,V]=l.useState(null),[te,Ce]=l.useState(!1),[se,P]=l.useState(!1),[ae,ye]=l.useState(null),[Fe,Be]=l.useState(!1),de=l.useRef(0),[Le,G]=l.useState(!1),[Ue,ge]=l.useState(null);ut.useWalletClient(),ut.useSwitchChain();const{chain:Je,address:Se}=ut.useAccount();ut.useConfig();const rt=l.useRef(Je);l.useEffect(()=>{rt.current=Je},[Je]);const jt=Jt(),{isReady:pt,isAuthenticated:Te,isConnected:at,address:wt,provider:kt,actions:Rt}=jt,{externalWallet:Pt,embeddedAddress:cn,externalAddress:ht}=Rn(),{intentStatus:Ee,startStatusPolling:vt,clearStatus:_e}=Gs({checkStepStatus:(K,le)=>h.relayerService.checkStepStatus(K,le),retryStep:async(K,le)=>{const[De,Ie]=K.split("/"),Ve=parseInt(Ie||"0",10);await h.relayerService.executeStep(De,Ve,le,{action:"execute"})},maxRetries:3}),{assets:mt,refetch:et}=Dn({address:wt,supportedChains:D,enabled:at&&!N,refetchInterval:3e4}),tt=l.useMemo(()=>{if(q.length===0)return mt;const K=new Set(q.map(le=>le.toLowerCase()));return mt.filter(le=>K.has(le.address.toLowerCase()))},[mt,q]),Ht=Gt(),st=N?Se||ht:Ht,pe=l.useMemo(()=>{if(!m)return[];const K=new Set,le=[],De=Ie=>{if(!Ie)return;const Ve=Ie.toLowerCase();K.has(Ve)||(K.add(Ve),le.push(j.getAddress(Ie)))};if(x&&De(x),N)for(const Ie of q)De(Ie);return le},[m,N,x,q]),Ye=l.useMemo(()=>pe.map(K=>K.toLowerCase()).sort().join(","),[pe]),Ut=l.useMemo(()=>JSON.stringify([...D||[]].sort()),[D]),[lt,ke]=l.useState([]),gt=l.useRef(0),nt=l.useCallback(async()=>{if(!m||!st||pe.length===0){gt.current++,ke([]);return}const K=++gt.current,le=j.getAddress(st),De=D&&D.length>0?D:[d],Ie=pe.map(Xe=>{const qe=Xe.toLowerCase();for(const Q of De){const J=h.getChainConfig(Q)?.supportedTokens?.find(he=>h.addressesEqual(he.address,qe));if(J)return{address:Xe,chainId:Q,configToken:{decimals:J.decimals,symbol:J.symbol,name:J.name,logo:J.logo}}}return{address:Xe,chainId:d}}),Ve=new Map;for(const Xe of Ie){const qe=Ve.get(Xe.chainId)||[];qe.push(Xe),Ve.set(Xe.chainId,qe)}const We=async(Xe,qe)=>{try{const Q=await Tt.readContract(Xe,{address:qe.address,abi:h._,functionName:"balanceOf",args:[le]});let J,he,oe,fe;if(qe.configToken)J=qe.configToken.decimals,he=qe.configToken.symbol,oe=qe.configToken.name,fe=qe.configToken.logo;else{const[Ot,Et,Ct]=await Promise.all([Tt.readContract(Xe,{address:qe.address,abi:h._,functionName:"decimals",args:[]}).catch(()=>18),Tt.readContract(Xe,{address:qe.address,abi:h._,functionName:"symbol",args:[]}).catch(()=>"TOKEN"),Tt.readContract(Xe,{address:qe.address,abi:h._,functionName:"name",args:[]}).catch(()=>"TOKEN")]);J=Number(Ot),he=Et,oe=Ct}const Me=!!x&&h.addressesEqual(qe.address,x)&&qe.chainId===d;Me&&a&&(fe=a),Me&&r&&!qe.configToken&&(he==="TOKEN"&&(he=r),oe==="TOKEN"&&(oe=r));const At=parseFloat((Number(Q)/Math.pow(10,J)).toFixed(6));return{address:qe.address,name:oe,symbol:he,decimals:J,balance:Q,balanceFormatted:At,balanceUsd:0,logoURI:fe,isNative:!1,chainId:qe.chainId}}catch{return null}},ze=await Promise.all(Array.from(Ve.entries()).map(async([Xe,qe])=>{let Q;try{Q=h.getClientForChain(Xe)}catch{return[]}const J=[],he=[];for(const fe of qe){const Me=J.length;J.push({address:fe.address,abi:h._,functionName:"balanceOf",args:[le]}),fe.configToken||J.push({address:fe.address,abi:h._,functionName:"decimals",args:[]},{address:fe.address,abi:h._,functionName:"symbol",args:[]},{address:fe.address,abi:h._,functionName:"name",args:[]}),he.push({start:Me,item:fe})}let oe=null;try{oe=await Q.multicall({contracts:J})}catch{oe=null}return oe?he.map(({start:fe,item:Me})=>{const At=oe[fe],Ot=At?.status==="success"?At.result:0n;let Et,Ct,me,Ne;if(Me.configToken)Et=Me.configToken.decimals,Ct=Me.configToken.symbol,me=Me.configToken.name,Ne=Me.configToken.logo;else{const Dt=oe[fe+1],Yt=oe[fe+2],Xt=oe[fe+3];Et=Dt?.status==="success"?Number(Dt.result):18,Ct=Yt?.status==="success"?Yt.result:"TOKEN",me=Xt?.status==="success"?Xt.result:Ct}const Bt=!!x&&h.addressesEqual(Me.address,x)&&Me.chainId===d;Bt&&a&&(Ne=a),Bt&&r&&!Me.configToken&&(Ct==="TOKEN"&&(Ct=r),me==="TOKEN"&&(me=r));const qt=parseFloat((Number(Ot)/Math.pow(10,Et)).toFixed(6));return{address:Me.address,name:me,symbol:Ct,decimals:Et,balance:Ot,balanceFormatted:qt,balanceUsd:0,logoURI:Ne,isNative:!1,chainId:Me.chainId}}):(await Promise.all(qe.map(fe=>We(Q,fe)))).filter(fe=>fe!==null)}));if(K!==gt.current)return;const Ge=ze.flat();ke(Ge)},[m,st,Ye,Ut,d,x,a,r]);l.useEffect(()=>{if(!m){ke([]);return}nt();const K=setInterval(()=>{nt()},15e3);return()=>clearInterval(K)},[nt,m]);const Oe=l.useCallback(()=>{nt()},[nt]),Kt=l.useMemo(()=>lt.filter(K=>K.balance>0n),[lt]),xt=l.useMemo(()=>{if(N)return Kt.map(le=>({...le,_source:"wallet"}));if(!m)return tt;const K=[];for(const le of Kt)K.push({...le,_source:"wallet"});for(const le of tt)K.push({...le,_source:"spice"});return K},[N,m,Kt,tt]),zt=l.useRef(null),Qt=l.useRef(null);l.useEffect(()=>{Qt.current=W},[W]),l.useEffect(()=>{e||(re(null),Z(null),V(null),Ce(!1),P(!1),ye(null),ue(!1),G(!1),ge(null),Be(!1),_e())},[e,_e]),l.useEffect(()=>{i&&i.assetAmount!==(W?.amount||"")&&re(K=>K&&{...K,amount:i.assetAmount})},[i?.assetAmount]),l.useEffect(()=>{c&&c.assetAmount!==(W?.amount||"")&&re(K=>K&&{...K,amount:c.assetAmount})},[c?.assetAmount]),l.useEffect(()=>{if(!N&&Ee?.overallStatus==="success"&&Ee.intentId&&zt.current!==Ee.intentId&&wt&&Ee.steps.find(K=>K.transactionHash)?.transactionHash){zt.current=Ee.intentId;const K=Qt.current;if(!K?.asset||!K.amount||K.asset._source==="wallet"||j.parseUnits(K.amount,K.asset.decimals)===0n)return;et()}},[Ee,wt,d,et,N]);const He=parseFloat(W?.amount||"")||0,je=l.useMemo(()=>W?.asset?W.asset._source==="wallet"?W.asset.balanceFormatted??0:tt.find(K=>h.addressesEqual(K.address,W.asset.address)&&K.chainId===W.asset.chainId)?.balanceFormatted??0:0,[W?.asset,tt]),it=He>0&&(ae?parseFloat(j.formatUnits(ae.grossAmount,ae.decimals))>je:He>je),$e=u?.selectedDuration??f[we]??f[0],Ze=l.useMemo(()=>!W?.asset||!x?!1:h.addressesEqual(W.asset.address,x)&&W.asset.chainId===d,[W?.asset,x,d]),Ke=l.useMemo(()=>He<=0?0:Ze?He:!C||C<=0?0:He/C,[He,C,Ze]),St=l.useMemo(()=>Ke<=0?null:Ke.toLocaleString(void 0,{maximumFractionDigits:2}),[Ke]),ot=p&&Ke>0&&$e?p(Ke,$e.months):void 0,ct=l.useMemo(()=>He<=0?"$0.00":Ze&&C?(He*C).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!C||C<=0?"$0.00":He.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[He,C,Ze]),yt=l.useMemo(()=>{if(!St)return null;const K=parseFloat(St.replace(/,/g,""));return Ze&&C?(K*C).toLocaleString(void 0,{maximumFractionDigits:2}):C?(K*C).toLocaleString(void 0,{maximumFractionDigits:2}):null},[St,C,Ze]),It=l.useCallback(K=>{re(le=>({asset:K,amount:le?.asset?.address===K.address&&le?.asset?.chainId===K.chainId&&le.amount||""})),Z(null),V(null),P(!1),ye(null),c?.setSelectedAsset&&c.setSelectedAsset({symbol:K.symbol,address:K.address,decimals:K.decimals,chainId:K.chainId})},[c?.setSelectedAsset]),Lt=l.useCallback(K=>{re(le=>le&&{...le,amount:K}),Z(null),V(null),P(!1),ye(null),i&&i.setAssetAmount(K),c&&c.setAssetAmount(K)},[i,c]),$t=l.useCallback(K=>{if(typeof o=="function"){if(!W?.asset||!W.amount)throw new Error("Select an asset and enter an amount");return o({asset:W.asset,amount:K?.amount??W.amount,amountWei:K?.amountWei??j.parseUnits(W.amount,W.asset.decimals),grossAmount:K?.grossAmount,grossAmountWei:K?.grossAmountWei,feeAdjusted:!!K})}return o},[o,W]),Re=l.useRef(null),dt=l.useMemo(()=>!W?.asset||He<=0?!1:N?!Ze&&!k:!0,[W,He,N,Ze,k]),Vt=l.useCallback(()=>fi(Re.current),[]);l.useEffect(()=>{if(!e||X)return;if(!W?.asset||He<=0){V(null),Ce(!1),P(!1),ye(null);return}if(!dt){V(null),Ce(!1),P(!0),ye(null);return}let K=!1;const le=async()=>{const Ve=++de.current;V(null),P(!1),Ce(!0);try{const We=await Vt();if(K||de.current!==Ve)return;V(null),P(!0),ye(We)}catch(We){if(K||de.current!==Ve)return;V(h.sanitizeError(We,"Unable to calculate fees for this lock.")),P(!1)}finally{!K&&de.current===Ve&&Ce(!1)}},De=window.setTimeout(()=>{le()},250),Ie=window.setInterval(()=>{le()},1e4);return()=>{K=!0,clearTimeout(De),window.clearInterval(Ie),Ce(!1),P(!1)}},[e,X,W,He,dt,Vt]),l.useEffect(()=>{if(Ee?.overallStatus==="success"){const K=Ee.steps.find(le=>le.transactionHash);y?.(K?.transactionHash)}},[Ee?.overallStatus,y]);const Ft=m&&W?.asset?._source==="wallet"&&W?.asset?.chainId===d,$=l.useCallback(()=>mi(Re.current),[]),_=!!W?.asset&&He>0&&!it&&!X&&(!dt||se&&!te&&!ce),be=xe||ce,Pe=n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[n.jsx(ys,{color:L}),n.jsxs("p",{style:{fontSize:"13px",color:L,margin:0,lineHeight:"1.5"},children:["Add ",r," by converting assets from your account"]})]});if(Re.current={selectedAsset:W,parsedAmount:He,selectedDuration:$e,isInsufficientBalance:it,isSemi7702:N,isSourceDestToken:Ze,isDirectDeposit:Ft,requiresRelayerFeeEstimate:dt,address:wt,embeddedWalletAddress:Ht,providerEmbeddedAddress:cn,externalWallet:Pt,externalWalletAddress:Se,isConnected:at,ready:pt,authenticated:Te,provider:kt,actions:Rt,lockChainId:d,escrowAddress:g,onLockExecute:k,onLockSuccess:y,buildSpicenetBatch:S,resolveLockBatches:$t,startStatusPolling:vt,refreshSpiceAssets:et,refreshWalletAssets:Oe,ui:{setError:Z,setIsExecuting:ue,setShowStatusPanel:Be}},!e)return null;const Qe={backgroundColor:z,border:O,borderRadius:U,padding:"16px",marginBottom:"16px"};return n.jsx(nn,{isOpen:e,onClose:t,title:`Add ${r} to your account`,subtitle:Pe,styles:I,dark:E,footerLinkText:"Spicenet accounts \u2192",overlayContent:Le?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:[b&&n.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:n.jsx(Cs,{onClick:b,color:T,fontFamily:M})}),n.jsx("div",{style:{marginTop:"10px",fontSize:"13px",color:L,fontFamily:M},children:n.jsx(Mn,{assets:xt,selectedAsset:W??void 0,onAssetSelect:It,onAmountChange:Lt,label:"Amount",showBalance:!0,showMaxButton:!0,theme:H,styles:ne})}),n.jsx("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:L,fontFamily:M},children:ct})]}),n.jsxs("div",{style:Qe,children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:E?`1px solid ${v.cardBorder}`:"1px solid #e5e7eb"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[a?n.jsx("img",{src:a,alt:r,style:{width:"32px",height:"32px",borderRadius:"50%",objectFit:"cover"}}):n.jsx("div",{style:{width:"32px",height:"32px",borderRadius:"50%",backgroundColor:E?v.inputBg:"#d1d5db",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:700,color:Y},children:r.slice(0,2)}),n.jsx("span",{style:{fontSize:"16px",fontWeight:600,color:Y,fontFamily:M},children:r})]}),n.jsxs("div",{style:{textAlign:"right"},children:[n.jsx("div",{style:{fontSize:"22px",fontWeight:700,color:Y,fontFamily:M,lineHeight:1.1},children:St??"0.00"}),n.jsxs("div",{style:{fontSize:"12px",color:L,fontFamily:M,marginTop:"2px"},children:["~$",yt??"0.00"]})]})]}),n.jsxs("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:E?`1px solid ${v.cardBorder}`:"1px solid #e5e7eb"},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[n.jsx("span",{style:{fontSize:"15px",fontWeight:500,color:L,fontFamily:M},children:"Lock Duration"}),n.jsx(sn,{color:L})]}),n.jsx(ei,{options:f,selectedIndex:we,onSelect:Ae,primaryColor:T,dark:E,textPrimary:Y,textSecondary:L})]}),n.jsxs("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[n.jsx(ni,{durationMonths:$e?.months,fontFamily:M,dark:E,textPrimary:Y,textSecondary:L}),p&&n.jsx(si,{votes:ot,fontFamily:M,dark:E,textPrimary:Y,textSecondary:L})]})]}),dt&&n.jsx(Ln,{fontFamily:M,textPrimary:Y,textSecondary:L,cardBg:z,cardBorder:O,resolvedDark:E,darkCardBorder:v.cardBorder,primaryColor:T,feePreview:ae,isLoading:te,errorText:ce}),be&&n.jsx(In,{variant:"error",palette:v,fontFamily:M,style:{marginBottom:"12px"},children:be}),n.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:$,disabled:!_,loading:X,dark:E,styles:{...I,button:{...I?.button,backgroundColor:T}},children:X?Ft&&!Ze?"DEPOSITING...":Ze?"LOCKING...":"CONVERTING...":te&&dt?"CALCULATING FEES...":Ft&&!Ze?`DEPOSIT ${r}`:Ze?`LOCK ${r}`:`CONVERT TO ${r}`}),n.jsx(oi,{isOpen:Le,data:Ue,isLocking:X,lockError:be,onContinue:$,onClose:()=>G(!1),primaryColor:T,fontFamily:M,dark:E}),Ee&&Fe&&n.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:E?v.shell:"white",borderRadius:U,padding:"16px 0"},children:n.jsx(Ss,{type:"deposit",isOpen:!!Ee&&Ee.overallStatus!=="processing",isProcessing:X||Ee?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{_e(),Be(!1),$()},onNewTx:()=>{_e(),Be(!1),re(null),zt.current=null,et(),Oe()},onClose:()=>{_e(),Be(!1)},onComplete:()=>{_e(),Be(!1),re(null),zt.current=null,et(),Oe()},results:Ee?.overallStatus==="success"||Ee?.overallStatus==="failed"?Ee.steps.map(K=>({asset:{symbol:W?.asset?.symbol||r,address:W?.asset?.address||""},txHash:K.transactionHash||"",success:K.status==="success",amount:W?.amount})):void 0,chainName:h.getChainName(d),explorerUrl:h.getExplorerUrl(d,"").replace(/\/tx\/.*$/,"")||void 0,theme:F,styles:I,dark:E})})]})})},gi="0xa9059cbb";function xi(e,t,s,o){return t!=="user-transfer"||!s||e.length===0||e[0]?.to.toLowerCase()!==o.toLowerCase()||!e[0]?.data.startsWith(gi)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function $n(e,t,s){if(!t)return[e];const o=await t(s);return o?[o,e]:[e]}function _n(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 yi(e,t){const{currentPaymentAmount:s,destinationToken:o,embeddedWalletAddress:r,providerEmbeddedAddress:a,address:i,isNon7702:c,isPayMode:u,resolvedChainId:d,buildActionCalls:f,feeExecutionMode:p,buildSpicenetBatch:g,selectedAsset:m,needsSwap:x,exactOutputSwap:y,resolvedTokenIn:k}=e,C=j.parseUnits(s,o.decimals),w=t?.actionAmountOverride??C,b=r||a||(c?void 0:i);if(!b)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const S={userAddress:b,chainId:d,destinationToken:o.address,grossAmount:t?.fundingAmountOverride??C,netAmount:w,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:p,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},I=f(w,S),A={chainId:d,calls:I},F=(!u&&!c?!0:m?.asset?._source==="spice")||c,E=(T,v)=>({token:T,from:c?"solver":"escrow",to:b,amount:v});if(C===0n)return[A];if(x&&y){const T=k??on(m.asset,d)??m.asset.address,v=t?.fundingAmountOverride??y.amountInMax,M=F?[E(T,v)]:[],B={to:T,value:0n,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"approve",args:[y.calls[0]?.to,y.amountInMax]})},N={chainId:d,calls:[B,...y.calls,...I],tokenTransfers:[...M,...A.tokenTransfers??[]]};return F?$n(N,g,{userAddress:b,destinationChainId:d,deliveryToken:T,deliveryAmount:v,deliveryRecipient:b,sourceAsset:m.asset}):[N]}if(F){const T=k??on(m.asset,d)??o.address,v=t?.fundingAmountOverride??C,M={...A,tokenTransfers:[E(T,v),...A.tokenTransfers??[]]};return $n(M,g,{userAddress:b,destinationChainId:d,deliveryToken:T,deliveryAmount:v,deliveryRecipient:b,sourceAsset:m.asset})}return[A]}async function Ci(e,t){const{selectedAsset:s,embeddedWalletAddress:o,resolvedChainId:r,destinationToken:a,buildActionCalls:i,feeExecutionMode:c,buildSpicenetBatch:u,isPayMode:d,isNon7702:f,needsSwap:p,resolvedSwap:g,quoteAmountOut:m,resolvedTokenIn:x}=e,y=g?.amountOutMinimum??m;if(!s?.asset||!o)return[];const k=t?.fundingAmountOverride??t?.actionAmountOverride??j.parseUnits(s.amount,s.asset.decimals),C=t?.fundingAmountOverride??k,w=t?.actionAmountOverride??k,b={userAddress:o,chainId:r,destinationToken:a.address,feeToken:c==="user-transfer"&&p&&x?x:a.address,grossAmount:C,netAmount:w,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:c,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},S=i(w,b);if(!(!d&&!f||s.asset?._source==="spice"))return[{chainId:r,calls:S}];const I=(E,T)=>({token:E,from:"escrow",to:o,amount:T});if(p){if(!x)throw new Error("Swap input token could not be resolved");if(!g||y===null)throw new Error("Swap quote not available yet")}if(p&&g&&y&&x){const E=i(t?.actionAmountOverride??y,{...b,netAmount:t?.actionAmountOverride??y}),{feeCall:T,remainingCalls:v}=xi(E,c,p,b.feeToken),M={chainId:r,calls:[...T?[T]:[],...g.calls,...v],tokenTransfers:[I(x,C)]};return $n(M,u,{userAddress:o,destinationChainId:r,deliveryToken:x,deliveryAmount:C,deliveryRecipient:o,sourceAsset:s.asset})}const A=x??on(s.asset,r)??a.address,F={chainId:r,calls:S,tokenTransfers:[I(A,C)]};return $n(F,u,{userAddress:o,destinationChainId:r,deliveryToken:A,deliveryAmount:C,deliveryRecipient:o,sourceAsset:s.asset})}async function bi(e,t,s,o,r){let a=e;for(let i=0;i<4;i++){const c=await t(a),u=await o(c,s,a,r),d=Pa(u);if(d===null||d>=e)return a;const f=a-d,p=e+f;if(p<=a)return a;a=p}return a}function wi(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 ki(e,t){const s=j.formatUnits(e,t);return s.includes(".")?s.replace(/\.?0+$/,"")||"0":s}async function vi(e){const{asset:t,isPayMode:s,isNon7702:o,needsSwap:r,isQuoting:a,embeddedWalletAddress:i,buildSupplyChainBatches:c,estimateGasless:u,executionTokenAddress:d,feeExecutionMode:f}=e;if(s||o||r||a||!i||t.balance<=0n)return null;const p=await c({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(p.length===0)return null;const g=p.some(C=>C.tokenTransfers?.length),m=await u(p,d,t.balance,g?{useCustomTransfers:!0,feeExecutionMode:f}:f?{feeExecutionMode:f}:void 0),x=yn(m,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),y=x?_n(x.gasFee,x.decimals,t.decimals):0n,k=x?_n(x.spicenetFee,x.decimals,t.decimals):0n;return ki(wi(t.balance,y,k,t.balance),t.decimals)}async function Si(e){const{selectedAsset:t,isPayMode:s,parsedAmount:o,needsSwap:r,exactOutputSwap:a,isNon7702:i,isSourceDestToken:c,currentPaymentAmount:u,destinationToken:d,feeExecutionMode:f,resolvedTokenIn:p,embeddedWalletAddress:g,providerEmbeddedAddress:m,resolvedChainId:x,isConnected:y,address:k,ready:C,authenticated:w,isDirect:b,resolvedSwap:S,isQuoting:I,executionTokenAddress:A,buildPayChainBatches:F,buildSupplyChainBatches:E,estimateGasless:T,estimateRequiredGrossFunding:v}=e;if(!t?.asset)return null;if(s){if(o<=0||r&&!a||i&&c)return null;const q=j.parseUnits(u,d.decimals),z=p||on(t.asset,x)||t.asset.address||d.address,O={chainId:x,tokenAddress:z,symbol:R.getTokenByAddress(z,x)?.symbol??t.asset.symbol,decimals:R.getTokenByAddress(z,x)?.decimals??t.asset.decimals};if(i){const re=g||m;if(!re)return null;const ee=r?a?.amountInMax??0n:q;if(ee===0n)return null;const ie=await v(ee,X=>F({fundingAmountOverride:X}),z,{userOverride:re,useCustomTransfers:!0}),we=await F({fundingAmountOverride:ie}),Ae=await T(we,z,ie,{userOverride:re,useCustomTransfers:!0,feeExecutionMode:f});return yn(Ae,O)}if(!y||!k||!C||!w)return null;const U=r?a?.amountInMax??0n:q;if(U===0n)return null;const Y=await v(U,re=>F({fundingAmountOverride:re}),z,{useCustomTransfers:!0});let L=await F({fundingAmountOverride:Y});const ne=await T(L,z,Y,{useCustomTransfers:!0,feeExecutionMode:f}),H=yn(ne,O)?.grossAmount??Y;H!==Y&&(L=await F({fundingAmountOverride:H}));const W=await T(L,z,H,{useCustomTransfers:!0,feeExecutionMode:f});return yn(W,O)}if(o<=0||!g||!b&&!S&&!I||I)return null;const M=j.parseUnits(t.amount,t.asset.decimals),B=await E();if(B.length===0)return null;const N=B.some(q=>q.tokenTransfers?.length),D=await T(B,A,M,N?{useCustomTransfers:!0,feeExecutionMode:f}:f?{feeExecutionMode:f}:void 0);return yn(D,{chainId:x,tokenAddress:A,symbol:R.getTokenByAddress(A,x)?.symbol??d.symbol,decimals:R.getTokenByAddress(A,x)?.decimals??d.decimals})}async function Ii(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.embeddedWalletAddress){e.ui.setError("Wallet not ready");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.ui.setTxHash(null),e.refs.spiceDepositSubmittedRef.current=!1;const t=new AbortController;e.refs.abortControllerRef.current=t;try{const s=j.parseUnits(e.selectedAsset.amount,e.selectedAsset.asset.decimals),o=s;let r=await e.gasless.buildSupplyChainBatches();if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!r.some(f=>R.isSpicenetChainId(f.chainId)))throw new Error("Spice-funded supplies must include a Spicenet funding batch before the destination chain batch.");const a=r.some(f=>f.tokenTransfers?.length)?{useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}:e.feeExecutionMode?{feeExecutionMode:e.feeExecutionMode}:void 0;let i=s;const c=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,u=e.feeExecutionMode==="user-transfer"&&!c?o:void 0;let d;for(let f=0;f<4;f+=1){const p=await e.gasless.estimateGasless(r,e.executionTokenAddress,i,a),g=yn(p,{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:R.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId)?.symbol??e.destinationToken.symbol,decimals:R.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId)?.decimals??e.destinationToken.decimals}),m=g?.grossAmount??i;if(m===i){i=m;break}i=m,d=e.feeExecutionMode==="user-transfer"&&g?{grossAmount:g.grossAmount,netAmount:o,combinedFeeAmount:g.totalFee,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:g.spicenetFee,gasFee:g.gasFee,bridgeFee:g.bridgeFee??0n}}:void 0,r=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:i,actionAmountOverride:u,actionContextOverride:d})}e.feeExecutionMode==="user-transfer"&&(r=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:i,actionAmountOverride:u,actionContextOverride:d})),await e.gasless.executeGasless(r,e.executionTokenAddress,i,e.gasless.onProgress,t.signal,a),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 Ai(e){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=j.parseUnits(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),s={userAddress:e.externalWalletAddress,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},o=e.buildActionCalls(t,s);if(o.length===0)throw new Error("No action calls configured");const r=await e.externalWallet.getEthereumProvider();let a=null;try{const f=await r.request({method:"eth_chainId"});a=parseInt(f,16)}catch{a=null}a!==e.resolvedChainId&&await h.ensureWalletOnChain(r,e.resolvedChainId);const i=h.getChainConfig(e.resolvedChainId),c=j.createWalletClient({account:e.externalWalletAddress,chain:i?.viemChain,transport:j.custom(r)}),u=h.getClientForChain(e.resolvedChainId);let d;for(const f of o){const p=await c.sendTransaction({to:f.to,data:f.data,value:f.value,chain:i?.viemChain});if((await u.waitForTransactionReceipt({hash:p,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transaction failed");d=p}return d}async function Ei(e){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const s=e.selectedAsset.asset,o=s.chainId,r=j.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),a=e.selectedIsEquivalent?r:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(a===0n)throw new Error("Quote not available yet");const i=e.resolvedTokenIn||e.selectedAsset.asset.address,c={userOverride:t,useCustomTransfers:!0},u=await e.gasless.estimateRequiredGrossFunding(a,w=>e.gasless.buildPayChainBatches({fundingAmountOverride:w}),i,c),d=R.getEscrowContractAddress(o),f=await e.externalWallet.getEthereumProvider();let p=null;try{const w=await f.request({method:"eth_chainId"});p=parseInt(w,16)}catch{p=null}p!==o&&await h.ensureWalletOnChain(f,o);const g=h.getChainConfig(o),m=j.createWalletClient({account:e.externalWalletAddress,chain:g?.viemChain,transport:j.custom(f)}),x=R.normalizeNativeTokenAddress(s.address),y=s.isNative||R.isNativeToken(x)?await m.sendTransaction({to:d,value:u,chain:g?.viemChain}):await m.sendTransaction({to:x,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"transfer",args:[d,u]}),chain:g?.viemChain});if((await h.getClientForChain(o).waitForTransactionReceipt({hash:y,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Escrow deposit failed");const k=await e.gasless.buildPayChainBatches({fundingAmountOverride:u}),C=k.some(w=>w.tokenTransfers?.length);return await e.gasless.executeGasless(k,i,u,w=>{w.txHash&&(e.ui.setPaymentResult(b=>({...b??{status:"processing"},txHash:w.txHash})),e.ui.setTxHash(w.txHash))},void 0,C?c:{userOverride:t})}async function ji(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}if(!e.selectedAsset?.asset){e.ui.setError("Select a payment source");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.parsedAmount>0&&e.needsSwap&&!e.exactOutputSwap){e.ui.setError("Swap quote not available. Try a different asset.");return}if(e.isNon7702){if(!e.externalWalletAddress){e.ui.setError("Please connect your external wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{let t;if(e.isSourceDestToken||e.parsedAmount===0)t=await Ai(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const s=e.selectedAsset.asset,o=j.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),r=e.selectedIsEquivalent?o:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(r===0n)throw new Error("Quote not available yet");const a=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!a)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const i=e.resolvedTokenIn||s.address,c=await e.gasless.estimateRequiredGrossFunding(r,f=>e.gasless.buildPayChainBatches({fundingAmountOverride:f}),i,{userOverride:a,useCustomTransfers:!0}),u=await e.gasless.buildPayChainBatches({fundingAmountOverride:c}),d=await e.onPayExecute({asset:s,amount:e.currentPaymentAmount,amountWei:o,destinationToken:e.destinationToken,chainBatches:u,requiredNetFunding:r,grossFundingAmount:c,selectedIsEquivalent:e.selectedIsEquivalent,resolvedTokenIn:i,exactOutputSwapAmountInMax:e.exactOutputSwap?.amountInMax});d&&(e.ui.setTxHash(d),e.ui.setPaymentResult(f=>({...f??{status:"processing"},txHash:d}))),t=d||void 0}else t=await Ei(e);e.ui.setPaymentResult(s=>({status:"success",txHash:s?.txHash||t||""}))}catch(t){const s=h.sanitizeError(t,"Payment failed. Please try again.");e.ui.setError(s),e.ui.setPaymentResult({status:"failed",error:s}),e.onError?.(t instanceof Error?t:new Error(s))}finally{e.ui.setIsExecuting(!1)}return}if(!e.isConnected||!e.address){e.ui.setError("Please connect your wallet to continue");return}if(!e.ready||!e.authenticated){e.ui.setError(`Please authenticate with ${e.provider||"wallet provider"} to continue`);return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{const t=j.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),s=e.resolvedTokenIn||e.selectedAsset?.asset?.address||e.destinationToken.address,o=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:t,r={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode},a=await e.gasless.estimateRequiredGrossFunding(o,g=>e.gasless.buildPayChainBatches({fundingAmountOverride:g}),s,r);let i=a,c=await e.gasless.buildPayChainBatches({fundingAmountOverride:a});const u=await e.gasless.estimateGasless(c,s,a,r),d=yn(u,{chainId:e.resolvedChainId,tokenAddress:s,symbol:R.getTokenByAddress(s,e.resolvedChainId)?.symbol??e.selectedAsset.asset.symbol,decimals:R.getTokenByAddress(s,e.resolvedChainId)?.decimals??e.selectedAsset.asset.decimals})?.grossAmount??a;d!==a&&(i=d,c=await e.gasless.buildPayChainBatches({fundingAmountOverride:d}));const f=c.some(g=>g.tokenTransfers?.length),p=await e.gasless.executeGasless(c,s,f?i:0n,g=>{g.txHash&&(e.ui.setPaymentResult(m=>({...m,txHash:g.txHash})),e.ui.setTxHash(g.txHash))},void 0,r);e.ui.setPaymentResult(g=>({status:"success",txHash:g?.txHash||p}))}catch(t){const s=h.sanitizeError(t,"Payment failed. Please try again.");e.ui.setError(s),e.ui.setPaymentResult({status:"failed",error:s}),e.onError?.(t instanceof Error?t:new Error(s))}finally{e.ui.setIsExecuting(!1)}}const Po=({variant:e,destinationSymbol:t,destinationLogoURI:s,destinationDecimals:o,primaryColor:r,fontFamily:a,textPrimary:i,textSecondary:c,cardBg:u,cardBorder:d,dk:f,dark:p,isQuoting:g,quoteError:m,estimatedOutput:x,paymentAmount:y,needsSwap:k,exactOutputSwap:C,adjustable:w=!1,maxAmount:b,onAmountChange:S})=>e==="supply"?n.jsxs("div",{style:{backgroundColor:u,border:`1px solid ${d}`,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:c,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 ${d}`,borderRadius:"8px",padding:"8px 10px",minHeight:"42px"},children:[n.jsx(Uo,{symbol:t,logoURI:s,primaryColor:r,size:24}),n.jsx("span",{style:{fontSize:"16px",fontWeight:500,color:p?"#f3f4f6":"#3C3E42",lineHeight:"1.3",fontFamily:a,letterSpacing:0},children:t})]})]}),n.jsx("div",{style:{textAlign:"right",minWidth:0},children:g?n.jsx("span",{style:{fontSize:"18px",color:c,fontFamily:a},children:"Quoting..."}):m?n.jsx("span",{style:{fontSize:"13px",color:p?"#f87171":"#dc2626",fontFamily:a},children:"Quote failed"}):x?n.jsx(mn,{value:x,title:x,fontFamily:a,color:i,lineHeight:"0.95",textAlign:"right",maxFontSize:32,minFontSize:18}):n.jsx("span",{style:{fontSize:"20px",color:c,fontFamily:a},children:"\u2014"})})]}):n.jsx(Fi,{destinationSymbol:t,destinationLogoURI:s,destinationDecimals:o,primaryColor:r,fontFamily:a,textPrimary:i,textSecondary:c,cardBg:u,cardBorder:d,dk:f,dark:p,paymentAmount:y||"0",needsSwap:k,exactOutputSwap:C,isQuoting:g,adjustable:w,maxAmount:b,onAmountChange:S}),Uo=({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)}),Fi=({destinationSymbol:e,destinationLogoURI:t,destinationDecimals:s,primaryColor:o,fontFamily:r,textPrimary:a,textSecondary:i,cardBg:c,cardBorder:u,dk:d,dark:f,paymentAmount:p,needsSwap:g,exactOutputSwap:m,isQuoting:x,adjustable:y,maxAmount:k,onAmountChange:C})=>{const w='"IBM Plex Mono", monospace',b=parseFloat(p||"0"),S=k?parseFloat(k):0,[I,A]=l.useState(p||""),F=l.useRef(null),[E,T]=l.useState(null),[v,M]=l.useState(null);l.useEffect(()=>{y||A(p||"")},[p,y]);const B=q=>{let z=q;z.startsWith(".")&&(z="0"+z);const O=kn(z);let U=O;k&&parseFloat(O)>parseFloat(k)&&(U=k),A(U),F.current&&clearTimeout(F.current),F.current=setTimeout(()=>C?.(U),300)},N=q=>{if(!S)return;if(q===100){A(k||S.toString()),F.current&&clearTimeout(F.current),C?.(k||S.toString());return}const z=10**s,O=Math.floor(S*q/100*z)/z,U=vn(O,s);A(U),F.current&&clearTimeout(F.current),C?.(U)},D=S>0?parseFloat(I||"0")/S*100:0;return l.useEffect(()=>()=>{F.current&&clearTimeout(F.current)},[]),n.jsxs("div",{style:{backgroundColor:c,border:`1px solid ${u}`,borderRadius:f?"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(Uo,{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(mn,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:I,onChange:q=>B(q.target.value),placeholder:"0.0",fontFamily:w,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):n.jsx(mn,{element:"div",value:b>0?p:"0.00",title:b>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((q,z)=>{const O=Math.abs(D-q)<1,U=z===4,Y=q/100,L=E===q,ne=v===q;return n.jsx("button",{onClick:()=>N(q),onMouseEnter:()=>T(q),onMouseLeave:()=>{T(null),M(null)},onMouseDown:()=>M(q),onMouseUp:()=>M(null),title:`${q}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:O?1:L?.8:.5,transform:ne?"scale(0.85)":L?"scale(1.15)":"scale(1)",transition:Wt.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:U?o:"none",stroke:U?o:f?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!U&&Y>0&&n.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${Y>.5?1:0} 1 ${7+6.84375*Math.sin(Y*2*Math.PI)} ${7-6.84375*Math.cos(Y*2*Math.PI)} Z`,fill:f?d?.textSecondary||"#9ca3af":"#3C3E42"})]})},q)})})]})]}),g&&m&&!x&&n.jsx("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:f?`1px solid ${d?.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 ",m.venue]})})]})};function zo(e,t,s){const o=h.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 Bi(e){const{address:t,destinationToken:s,supportedSourceAssets:o,sourceChains:r,enabled:a}=e,i=(l.useContext(h.SpiceFlowProviderContext)?.mode||"7702")!=="7702",c=Gt(),{externalAddress:u,embeddedAddress:d}=Rn(),{assets:f,refetch:p}=Dn({address:t,supportedChains:r,enabled:a&&!i,refetchInterval:3e4}),g=l.useMemo(()=>{if(i)return[];if(!o||o.length===0)return f;const A=o.map(F=>F.toLowerCase());return f.filter(F=>A.includes(F.address.toLowerCase()))},[f,o,i]),m=i?u:c,x=l.useMemo(()=>{const A=new Set,F=[],E=T=>{if(!T)return;const v=T.toLowerCase();A.has(v)||(A.add(v),F.push(j.getAddress(T)))};if(E(s.address),i&&o)for(const T of o)E(T);return F},[i,s.address,o]),y=l.useMemo(()=>x.map(A=>A.toLowerCase()).sort().join(","),[x]),k=l.useMemo(()=>JSON.stringify([...r||[]].sort()),[r]),[C,w]=l.useState([]),b=l.useRef(0),S=l.useCallback(async()=>{if(!a||!m||x.length===0){b.current++,w([]);return}const A=++b.current,F=j.getAddress(m),E=i?r&&r.length>0?r:[s.chainId]:[s.chainId],T=[];for(const N of x){const D=N.toLowerCase();if(D===s.address.toLowerCase()){const z=h.getChainConfig(s.chainId)?.supportedTokens?.find(O=>h.addressesEqual(O.address,D));T.push({address:N,chainId:s.chainId,configToken:z?{decimals:z.decimals,symbol:z.symbol,name:z.name,logo:z.logo}:void 0});continue}let q=!1;for(const z of E){const O=h.getChainConfig(z)?.supportedTokens?.find(U=>h.addressesEqual(U.address,D));if(O){T.push({address:N,chainId:z,configToken:{decimals:O.decimals,symbol:O.symbol,name:O.name,logo:O.logo}}),q=!0;break}}q||T.push({address:N,chainId:s.chainId})}const v=new Map;for(const N of T){const D=v.get(N.chainId)||[];D.push(N),v.set(N.chainId,D)}const M=async(N,D)=>{try{const q=await Tt.readContract(N,{address:D.address,abi:j.erc20Abi,functionName:"balanceOf",args:[F]});let z,O,U,Y;if(D.configToken)z=D.configToken.decimals,O=D.configToken.symbol,U=D.configToken.name,Y=D.configToken.logo;else{const[H,W,re]=await Promise.all([Tt.readContract(N,{address:D.address,abi:j.erc20Abi,functionName:"decimals"}).catch(()=>18),Tt.readContract(N,{address:D.address,abi:j.erc20Abi,functionName:"symbol"}).catch(()=>"TOKEN"),Tt.readContract(N,{address:D.address,abi:j.erc20Abi,functionName:"name"}).catch(()=>"TOKEN")]);z=Number(H),O=W,U=re}const L=h.addressesEqual(D.address,s.address)&&D.chainId===s.chainId;L&&s.logoURI&&(Y=s.logoURI),L&&!D.configToken&&O==="TOKEN"&&(O=s.symbol,U=s.symbol);const ne=parseFloat((Number(q)/Math.pow(10,z)).toFixed(6));return{address:D.address,name:U,symbol:O,decimals:z,balance:q,balanceFormatted:ne,balanceUsd:0,logoURI:Y,isNative:!1,chainId:D.chainId}}catch{return null}},B=await Promise.all(Array.from(v.entries()).map(async([N,D])=>{let q;try{q=h.getClientForChain(N)}catch{return[]}const z=[],O=[];for(const Y of D){const L=z.length;z.push({address:Y.address,abi:j.erc20Abi,functionName:"balanceOf",args:[F]}),Y.configToken||z.push({address:Y.address,abi:j.erc20Abi,functionName:"decimals"},{address:Y.address,abi:j.erc20Abi,functionName:"symbol"},{address:Y.address,abi:j.erc20Abi,functionName:"name"}),O.push({start:L,item:Y})}let U=null;try{U=await q.multicall({contracts:z})}catch{U=null}return U?O.map(({start:Y,item:L})=>{const ne=U[Y],H=ne?.status==="success"?ne.result:0n;let W,re,ee,ie;if(L.configToken)W=L.configToken.decimals,re=L.configToken.symbol,ee=L.configToken.name,ie=L.configToken.logo;else{const X=U[Y+1],ue=U[Y+2],xe=U[Y+3];W=X?.status==="success"?Number(X.result):18,re=ue?.status==="success"?ue.result:"TOKEN",ee=xe?.status==="success"?xe.result:re}const we=h.addressesEqual(L.address,s.address)&&L.chainId===s.chainId;we&&s.logoURI&&(ie=s.logoURI),we&&!L.configToken&&re==="TOKEN"&&(re=s.symbol,ee=s.symbol);const Ae=parseFloat((Number(H)/Math.pow(10,W)).toFixed(6));return{address:L.address,name:ee,symbol:re,decimals:W,balance:H,balanceFormatted:Ae,balanceUsd:0,logoURI:ie,isNative:!1,chainId:L.chainId}}):(await Promise.all(D.map(Y=>M(q,Y)))).filter(Y=>Y!==null)}));A===b.current&&w(B.flat())},[a,m,y,k,i,s.address,s.chainId,s.symbol,s.logoURI]);l.useEffect(()=>{if(!a){w([]);return}S();const A=setInterval(()=>{S()},15e3);return()=>clearInterval(A)},[S,a]);const I=l.useCallback(()=>{S()},[S]);return{displayAssets:l.useMemo(()=>{const A=[],F=C.filter(T=>T.balance>0n);for(const T of F)A.push({...T,_source:"wallet"});for(const T of g)A.push({...T,_source:"spice"});const E=s.address.toLowerCase();return A.sort((T,v)=>zo(T,E,s.chainId)-zo(v,E,s.chainId)),A},[C,g,s.address,s.chainId]),filteredSpiceAssets:g,walletAssets:C,embeddedWalletAddress:c||d,externalAddress:u,isNon7702:i,refreshSpiceAssets:p,refreshWalletAssets:I}}async function Lo(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 c=(await h.getClientForChain(a).simulateContract({address:i.quoterV2,abi:R.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:s,amountIn:o,fee:r,sqrtPriceLimitX96:0n}]})).result;if(c[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:c[0],sqrtPriceX96After:c[1],gasEstimate:c[3]}}async function Oo(e){const t=e.feeTiers??[100,500,3e3,1e4],s=await Promise.allSettled(t.map(r=>Lo({...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 Ti=[{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 Mi(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 c=(await h.getClientForChain(a).simulateContract({address:i.quoterV2,abi:Ti,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:s,amount:o,fee:r,sqrtPriceLimitX96:0n}]})).result;if(c[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:c[0],sqrtPriceX96After:c[1],gasEstimate:c[3]}}async function Ri(e){const t=e.feeTiers??[100,500,3e3,1e4],s=await Promise.allSettled(t.map(r=>Mi({...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 Ho(e){return e.type==="swap"}const Ms=.02,Di=[1,8453,42161,10,137,43114,56],Ni="https://api.1inch.dev/swap/v6.0";function Qo(e,t){return R.applySlippage(e,t)}function Vo(e){const t=e?.baseUrl??Ni;return{name:"1inch",chainIds:e?.chainIds??Di,resolve:async(s,o,r)=>{const a=s.maxSlippage??Ms,i=a*100,c=R.isNativeToken(s.tokenIn)?R.NATIVE_TOKEN_ADDRESS:s.tokenIn,u=R.isNativeToken(s.tokenOut)?R.NATIVE_TOKEN_ADDRESS:s.tokenOut,d=R.isNativeToken(s.tokenIn);try{const f=new URL(`${t}/${o}/swap`);f.searchParams.set("src",c),f.searchParams.set("dst",u),f.searchParams.set("amount",s.amountIn.toString()),f.searchParams.set("from",r),f.searchParams.set("slippage",i.toString()),f.searchParams.set("disableEstimate","true"),f.searchParams.set("allowPartialFill","false");const p={Accept:"application/json"};e?.apiKey&&(p.Authorization=`Bearer ${e.apiKey}`);const g=await fetch(f.toString(),{headers:p});if(!g.ok)throw new h.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${g.status} for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}`,{venue:"1inch",chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn.toString(),cause:`HTTP ${g.status}`});const m=await g.json();if(!m.dstAmount||!m.tx)return console.warn(`[1inchVenue] No route data for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}`),null;const x=BigInt(m.dstAmount);if(x<=0n)return console.warn(`[1inchVenue] Zero output for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}`),null;const y=Qo(x,a),k=[];return m.tx.to&&!d&&k.push({to:s.tokenIn,value:0n,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"approve",args:[m.tx.to,s.amountIn]})}),k.push({to:m.tx.to,value:BigInt(m.tx.value||"0"),data:m.tx.data}),{venue:"1inch",amountOut:x,amountOutMinimum:y,calls:k}}catch(f){if(f instanceof h.SpiceflowError)throw f;const p=f instanceof Error?f.message:String(f);throw new h.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 qo=[4114,5115],Rs={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425"},Yo={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453]};function Zo(e){return{name:"satsuma",chainIds:e.chainIds??qo,resolve:async(t,s,o)=>{const r=t.maxSlippage??Ms,a=R.isNativeToken(t.tokenIn);let i;try{i=await Oo({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 c=Qo(i.amountOut,r),u=[];return a||u.push({to:t.tokenIn,value:0n,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),u.push({to:e.swapRouter,value:a?t.amountIn:0n,data:j.encodeFunctionData({abi:R.uniV3SwapRouterAbi,functionName:"exactInputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:i.fee,recipient:o,amountIn:t.amountIn,amountOutMinimum:c,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:i.amountOut,amountOutMinimum:c,calls:u}}}}function Ko(e){return{name:"satsuma",chainIds:e.chainIds??qo,resolve:async(t,s,o)=>{const r=t.maxSlippage??Ms,a=R.isNativeToken(t.tokenIn);let i;try{i=await Ri({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 c=BigInt(Math.round(r*1e4)),u=i.amountIn+i.amountIn*c/10000n,d=[];return d.push({to:e.swapRouter,value:a?u:0n,data:j.encodeFunctionData({abi:Wi,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:d}}}}const Wi=[{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 Xo(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(Zo(e.satsuma)),t.push(Vo(e?.oneInch));function s(r){return t.find(a=>a.chainIds.includes(r))}async function o(r,a,i){const c=[],u=[];for(const d of r){if(!Ho(d)){c.push(d);continue}const f=s(a);if(!f)throw new h.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${a}. Cannot resolve swap ${d.tokenIn} \u2192 ${d.tokenOut}.`,{chainId:a,tokenIn:d.tokenIn,tokenOut:d.tokenOut,amountIn:d.amountIn.toString()});const p=await f.resolve(d,a,i);if(!p)throw new h.SpiceflowError("NO_LIQUIDITY",`${f.name} returned no quote for ${d.tokenIn} \u2192 ${d.tokenOut} on chain ${a}.`,{venue:f.name,chainId:a,tokenIn:d.tokenIn,tokenOut:d.tokenOut,amountIn:d.amountIn.toString()});c.push(...p.calls),u.push(p)}return{calls:c,resolvedSwaps:u}}return{resolveSwapIntents:o,getVenueForChain:s,venues:t}}function Pi(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 h.SpiceflowError("NO_SWAP_ROUTE",`No exact-output venue supports chain ${r}`,{chainId:r,tokenIn:o.tokenIn,tokenOut:o.tokenOut});const c=(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(c.length===0)throw new h.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 c.sort((u,d)=>u.amountIn<d.amountIn?-1:u.amountIn>d.amountIn?1:0),c[0]}return{getQuote:s,venues:t}}const Ui=Xo({satsuma:Rs});function zi(e){const{direction:t,selectedAsset:s,destinationToken:o,chainId:r,recipient:a,paymentAmount:i}=e,[c,u]=l.useState(!1),[d,f]=l.useState(null),[p,g]=l.useState(null),[m,x]=l.useState(null),[y,k]=l.useState(null),[C,w]=l.useState(null),[b,S]=l.useState(null),[I,A]=l.useState(null),[F,E]=l.useState(null),T=l.useRef(null),v=l.useRef(0),M=l.useRef(new Map),B=l.useMemo(()=>Ui,[]),N=l.useMemo(()=>Pi({customVenues:[Ko(Rs),Ko(Yo)]}),[]),D=l.useMemo(()=>{if(!s?.asset)return null;const W=on(s.asset,r);if(W)return W;const re=ln(s.asset.address,r,s.asset.chainId);return re?re.address:null},[s?.asset,r]),q=l.useMemo(()=>s?.asset?Vn(s.asset,r):[],[s?.asset,r]);l.useEffect(()=>{let W=!1;if(!s?.asset||q.length<=1){E(null);return}return(async()=>{const re=t==="input"?s.amount:i||"0";let ee=0n;try{ee=t==="input"?j.parseUnits(re,s.asset.decimals):0n}catch{ee=0n}try{const ie=await mo(s.asset,r,{requiredAmount:ee});W||E(ie)}catch{W||E(null)}})(),()=>{W=!0}},[s?.asset,s?.amount,r,q,t,i]);const z=l.useMemo(()=>F??D,[F,D]),O=l.useMemo(()=>!s?.asset||!z?[]:[z,...q.filter(W=>W.toLowerCase()!==z.toLowerCase())],[s?.asset,z,q]),U=l.useMemo(()=>!s?.asset||!qn(s.asset.address,s.asset.chainId,o.address,o.chainId)||!z?!1:h.addressesEqual(z,o.address),[s,o.address,o.chainId,z]),Y=z?h.addressesEqual(z,o.address):!1,L=t==="output"&&parseFloat(i||"0")===0,ne=!!s?.asset&&!U&&!Y&&!L,H=ne?I??z:z;return l.useEffect(()=>{T.current&&clearTimeout(T.current);const W=t==="input"?s?.amount:i,re=parseFloat(W||"0");if(!ne||!Number.isFinite(re)||re<=0||!s?.asset||!a||O.length===0){v.current++,g(null),x(null),k(null),w(null),S(null),A(null),f(null),u(!1);return}const ee=s.asset.decimals;let ie;try{ie=t==="input"?j.parseUnits(s.amount,ee):j.parseUnits(i||"0",o.decimals)}catch{v.current++,f("Invalid amount"),u(!1);return}const we=++v.current,Ae=()=>we!==v.current;u(!0);const X=t==="output"?150:400;return T.current=setTimeout(async()=>{try{if(t==="input"){const ue=B.getVenueForChain(r);if(!ue)throw new Error("No swap venue for this chain");let xe=null,Z=null;for(const V of O){const te=`${t}:${r}:${V.toLowerCase()}:${o.address.toLowerCase()}:${ie.toString()}`,Ce=M.current.get(te);if(Ce&&Ce.expiresAt>Date.now()&&Ce.resolvedSwap){xe=Ce.resolvedSwap,Z=V;break}const se=await ue.resolve({type:"swap",tokenIn:V,tokenOut:o.address,amountIn:ie},r,a);if(Ae())return;if(se){M.current.set(te,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:se}),xe=se,Z=V;break}}if(!xe||!Z)throw new Error("No liquidity for this pair");A(Z),S(xe.amountOut),k(xe),w(null);const ce=parseFloat(j.formatUnits(xe.amountOut,o.decimals));g(ce<.01?ce.toPrecision(4):ce.toLocaleString(void 0,{maximumFractionDigits:6})),x(null),f(null)}else{let ue=null,xe=null;for(const Z of O){const ce=`${t}:${r}:${Z.toLowerCase()}:${o.address.toLowerCase()}:${ie.toString()}`,V=M.current.get(ce);if(V&&V.expiresAt>Date.now()&&V.exactOutputSwap){ue=V.exactOutputSwap,xe=Z;break}try{const te=await N.getQuote({tokenIn:Z,tokenOut:o.address,amountOut:ie},r,a);if(Ae())return;M.current.set(ce,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:te}),ue=te,xe=Z;break}catch{if(Ae())return}}if(!ue||!xe)throw new Error("No liquidity for this pair");A(xe),w(ue),k(null),S(null),x(parseFloat(j.formatUnits(ue.amountIn,ee)).toFixed(6)),g(null),f(null)}}catch(ue){if(Ae())return;const xe=ue instanceof Error?ue.message:"Failed to get quote";f(xe),g(null),x(null),k(null),w(null),S(null),A(null)}finally{Ae()||u(!1)}},X),()=>{T.current&&clearTimeout(T.current)}},[t,ne,s?.amount,s?.asset?.address,s?.asset?.decimals,i,O,r,o.address,o.decimals,a,B,N]),{isQuoting:c,quoteError:d,estimatedOutput:p,estimatedInput:m,resolvedSwap:y,exactOutputSwap:C,quoteAmountOut:b,resolvedTokenIn:H,isDirect:Y,needsSwap:ne,selectedIsEquivalent:U}}const Go={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},Jo=["signing-delegation","signing-intent","submitting","executing"],$o=({isOpen:e,onClose:t,closeOnBackdropClick:s=!1,destinationToken:o,buildActionCalls:r,feeExecutionMode:a="user-transfer",buildSpicenetBatch:i,onPayExecute:c,actionLabel:u,amountDirection:d="input",swapDescription:f,directDescription:p,paymentAmount:g,amountInputMode:m="fixed",minPaymentAmount:x,maxPaymentAmount:y,onAmountChange:k,styles:C,dark:w,title:b,subtitle:S,onAddFunds:I,onSuccess:A,onError:F})=>{const E=d==="output",{theme:T,dark:v,primaryColor:M,dk:B,palette:N,fontFamily:D,monoFont:q,inputDark:z,cardBg:O,cardBorder:U,textPrimary:Y,textSecondary:L,subtitleText:ne}=h.useSpiceBrand(C,w),H=z?{...T,colors:{...T.colors,secondary:B.cardBg,surfaceHover:B.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:T,W=o.chainId,re=l.useContext(h.SpiceFlowProviderContext),ee=(re?.mode||"7702")!=="7702",ie=l.useMemo(()=>re?.supportedChainIds??[],[re?.supportedChainIds]),we=l.useMemo(()=>{const me=re?.allowedTokens;if(!me||me.length===0)return;const Ne=new Set(me.map(Dt=>Dt.toLowerCase())),Bt=[],qt=new Set;for(const Dt of ie){const Yt=h.getChainConfig(Dt);for(const Xt of Yt?.supportedTokens??[]){if(!Ne.has(Xt.symbol.toLowerCase()))continue;const ve=Xt.address.toLowerCase();qt.has(ve)||(qt.add(ve),Bt.push(Xt.address))}}return Bt},[re?.allowedTokens,ie]),Ae=Jt(),{address:X,isConnected:ue,isReady:xe,isAuthenticated:Z,provider:ce}=Ae,{executeGasless:V,estimateGasless:te}=Kn(),{externalWallet:Ce,externalAddress:se,embeddedAddress:P}=Rn(),{displayAssets:ae,filteredSpiceAssets:ye,embeddedWalletAddress:Fe,refreshSpiceAssets:Be,refreshWalletAssets:de}=Bi({address:X,destinationToken:o,supportedSourceAssets:we,sourceChains:ie,enabled:e&&(ee?!!se:!!X)}),Le=E||ee?ae:ye,[G,Ue]=l.useState(null),[ge,Je]=l.useState(g||""),[Se,rt]=l.useState(!1),[jt,pt]=l.useState(null),[Te,at]=l.useState("idle"),[wt,kt]=l.useState(""),[Rt,Pt]=l.useState(null),[cn,ht]=l.useState(!1),[Ee,vt]=l.useState(null),[_e,mt]=l.useState(null),[et,tt]=l.useState(!1),[Ht,st]=l.useState(!1),[pe,Ye]=l.useState(null),Ut=l.useRef(G),lt=l.useRef(!1),ke=l.useRef(null),gt=l.useRef(0),nt=l.useRef(null);l.useEffect(()=>{Ut.current=G},[G]);const Oe=m==="adjustable"?ge:g||"0",Kt=Fe||P||X,{isQuoting:xt,quoteError:zt,estimatedOutput:Qt,resolvedSwap:He,exactOutputSwap:je,quoteAmountOut:it,resolvedTokenIn:$e,isDirect:Ze,needsSwap:Ke,selectedIsEquivalent:St}=zi({direction:d,selectedAsset:G,destinationToken:o,chainId:W,recipient:Kt,paymentAmount:Oe}),ot=E?parseFloat(Oe||"0"):parseFloat(G?.amount||"")||0,ct=l.useMemo(()=>G?.asset?ye.find(me=>h.addressesEqual(me.address,G.asset.address))?.balanceFormatted??0:0,[G,ye]),yt=l.useMemo(()=>G?.asset?E?_e?_n(_e.grossAmount,_e.decimals,G.asset.decimals)>G.asset.balance:St||Ze?ot>G.asset.balanceFormatted:je?parseFloat(j.formatUnits(je.amountInMax,G.asset.decimals))>G.asset.balanceFormatted:!1:_e?parseFloat(j.formatUnits(_n(_e.grossAmount,_e.decimals,G.asset.decimals),G.asset.decimals))>ct:ot>ct:!1,[G,E,_e,St,ot,je,ct,Ze]);l.useEffect(()=>{e||(Ue(null),pt(null),rt(!1),at("idle"),kt(""),Pt(null),ht(!1),vt(null),mt(null),tt(!1),st(!1),Ye(null),lt.current=!1,m==="adjustable"&&Je(g||""),ke.current&&(ke.current.abort(),ke.current=null))},[e]);const It=l.useCallback(me=>{Ue(Ne=>({asset:me,amount:Ne?.asset?.address===me.address&&Ne?.asset?.chainId===me.chainId&&Ne.amount||""})),pt(null),Ye(null),st(!1)},[]),Lt=l.useCallback(me=>{Ue(Ne=>Ne&&{...Ne,amount:me}),pt(null),Ye(null),st(!1)},[]),$t=l.useCallback(me=>{let Ne=me;y&&parseFloat(Ne)>parseFloat(y)&&(Ne=y),Je(Ne),k?.(Ne),pt(null),Ye(null),st(!1)},[y,k]);l.useCallback(me=>{if(lt.current||!X)return;const Ne=Ut.current;!Ne?.asset||!Ne.amount||Ne.asset?._source==="wallet"||j.parseUnits(E?Oe:Ne.amount,Ne.asset.decimals)===0n||(lt.current=!0,Be())},[X,W,Be,E,Oe]);const Re=l.useCallback(me=>{at({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[me.step]||"executing"),kt(me.message),me.txHash&&Pt(me.txHash)},[]),dt=l.useMemo(()=>({currentPaymentAmount:Oe,destinationToken:o,embeddedWalletAddress:Fe,providerEmbeddedAddress:P,address:X,isNon7702:ee,isPayMode:E,resolvedChainId:W,buildActionCalls:r,feeExecutionMode:a,buildSpicenetBatch:i,selectedAsset:G,needsSwap:Ke,resolvedSwap:He,exactOutputSwap:je,quoteAmountOut:it,resolvedTokenIn:$e}),[Oe,o,Fe,P,X,ee,E,W,r,a,i,G,Ke,He,je,it,$e]),Vt=l.useCallback(me=>yi(dt,me),[dt]),Ft=l.useCallback(me=>Ci(dt,me),[dt]),$=l.useCallback((me,Ne,Bt,qt)=>bi(me,Ne,Bt,te,qt),[te]),_=l.useMemo(()=>G?.asset?G.asset.chainId===W?G.asset.address:$e??on(G.asset,W)??o.address:o.address,[G,o.address,W,$e]),be=l.useCallback(()=>Ii(nt.current),[]),Pe=l.useMemo(()=>G?.asset?h.addressesEqual(G.asset.address,o.address)&&G.asset.chainId===o.chainId:!1,[G,o.address,o.chainId]),Qe=E&&ee&&Pe&&ot>0&&!!G?.asset,K=jt,le=l.useMemo(()=>!(!G?.asset||ot<=0),[G,ot,Qe]),De=l.useMemo(()=>!e||Se||Te!=="idle"||!le||Qe||!G?.asset?null:[E?"pay":"supply",d,G.asset.address.toLowerCase(),G.asset.chainId,G.amount,Oe,o.address.toLowerCase(),o.chainId,W,$e?.toLowerCase()??"",Ke?"swap":"direct",Ze?"direct-token":"routed-token",ee?"non7702":"7702",Pe?"source-dest":"cross-chain",xt?"quoting":"quoted",je?.amountIn?.toString()??"",je?.amountInMax?.toString()??"",je?.venue??"",He?.amountOut?.toString()??"",it?.toString()??"",Fe??"",P??"",X??""].join("|"),[e,Se,Te,le,Qe,G,E,d,Oe,o,W,$e,Ke,Ze,ee,Pe,xt,je,He,it,Fe,P,X]),Ie=l.useCallback(()=>Si({selectedAsset:G,isPayMode:E,parsedAmount:ot,needsSwap:Ke,exactOutputSwap:je,isNon7702:ee,isSourceDestToken:Pe,currentPaymentAmount:Oe,destinationToken:o,feeExecutionMode:a,resolvedTokenIn:$e,embeddedWalletAddress:Fe,providerEmbeddedAddress:P,resolvedChainId:W,isConnected:ue,address:X,ready:xe,authenticated:Z,isDirect:Ze,resolvedSwap:He,isQuoting:xt,executionTokenAddress:_,buildPayChainBatches:Vt,buildSupplyChainBatches:Ft,estimateGasless:te,estimateRequiredGrossFunding:$}),[G,E,ot,Ke,je,ee,Pe,Oe,o,a,$e,Fe,P,$,Vt,te,W,ue,X,xe,Z,Ze,He,xt,Ft,_]),Ve=l.useCallback(me=>vi({asset:me,isPayMode:E,isNon7702:ee,needsSwap:Ke,isQuoting:xt,embeddedWalletAddress:Fe,buildSupplyChainBatches:Ft,estimateGasless:te,executionTokenAddress:_,feeExecutionMode:a}),[E,ee,Ke,xt,Fe,Ft,te,_,a]);l.useEffect(()=>{if(!e){tt(!1),st(!1),Ye(null),mt(null);return}if(Se||Te!=="idle"){gt.current+=1,tt(!1);return}if(!le){mt(null),tt(!1),st(!1),Ye(null);return}if(Qe){mt(null),tt(!1),st(!0),Ye(null);return}if(!De)return;let me=!1;const Ne=async()=>{const Dt=++gt.current;Ye(null),tt(!0);try{const Yt=await Ie();if(me||gt.current!==Dt)return;Yt?(mt(Yt),st(!0)):(mt(null),st(!1)),Ye(null)}catch(Yt){if(me||gt.current!==Dt)return;const Xt=h.sanitizeError(Yt,"Unable to calculate fees for this action.");mt(null),st(!1),Ye(Xt)}finally{!me&>.current===Dt&&tt(!1)}},Bt=window.setTimeout(()=>{Ne()},250),qt=window.setInterval(()=>{Ne()},1e4);return()=>{me=!0,clearTimeout(Bt),window.clearInterval(qt),tt(!1)}},[e,Se,Te,Ie,le,Qe,De]);const We=l.useCallback(()=>ji(nt.current),[]);l.useEffect(()=>{!E&&Te==="success"&&Rt&&(Be(),A?.(Rt))},[E,Te,Rt,Be,A]),l.useEffect(()=>{if(!E||Ee?.status!=="success"||lt.current||!X)return;lt.current=!0;const me=Ut.current;!me?.asset||me.asset?._source==="wallet"||Be()},[E,Ee?.status,X,Be]);const ze=l.useRef(A),Ge=l.useRef(F);l.useEffect(()=>{ze.current=A},[A]),l.useEffect(()=>{Ge.current=F},[F]),l.useEffect(()=>{e&&(Be(),de())},[e,Be,de]),l.useEffect(()=>{E&&(Ee?.status==="success"&&ze.current?.(Ee.txHash||""),Ee?.status==="failed"&&Ge.current?.(new Error("Payment execution failed")))},[E,Ee?.status]);const Xe=l.useCallback(()=>{ht(!1),vt(null),Ue(null),lt.current=!1,Be(),de()},[Be,de]);nt.current={selectedAsset:G,parsedAmount:ot,currentPaymentAmount:Oe,isInsufficientBalance:yt,isPayMode:E,isNon7702:ee,isSourceDestToken:Pe,needsSwap:Ke,exactOutputSwap:je,selectedIsEquivalent:St,resolvedTokenIn:$e,embeddedWalletAddress:Fe,providerEmbeddedAddress:P,externalWallet:Ce,externalWalletAddress:se,address:X,isConnected:ue,ready:xe,authenticated:Z,provider:ce,resolvedChainId:W,executionTokenAddress:_,destinationToken:o,buildActionCalls:r,feeExecutionMode:a,buildSpicenetBatch:i,onPayExecute:c,onError:F,gasless:{estimateGasless:te,executeGasless:V,buildPayChainBatches:Vt,buildSupplyChainBatches:Ft,estimateRequiredGrossFunding:$,onProgress:Re},ui:{setError:pt,setStep:at,setStatusMsg:kt,setTxHash:Pt,setIsExecuting:rt,setShowStatusPanel:ht,setPaymentResult:vt},refs:{spiceDepositSubmittedRef:lt,abortControllerRef:ke}};const qe=E&&ot===0,Q=E?!!G?.asset&&ot>=0&&!yt&&!Se&&(qe||Qe||Ht)&&!pe&&(qe||!Ke||!!je):!!G?.asset&&ot>0&&!yt&&!Se&&Ht&&!pe&&(Ze||!!He&&!xt),J=Ze?p||`Your ${o.symbol} will be used directly.`:f||"Your assets will be swapped and used in a single atomic transaction.",he=(W?h.getChainConfig(W):void 0)?.viemChain?.blockExplorers?.default?.url??"",oe=Jo.indexOf(Te),fe=Se?(Go[Te]||"EXECUTING...").toUpperCase():Te==="success"?"DONE":yt?"INSUFFICIENT BALANCE":u.toUpperCase(),Me=l.useMemo(()=>{if(Se)return"PAYING...";if(yt&&G?.asset)return`INSUFFICIENT ${G.asset.symbol}`;if(u)return u.toUpperCase();const me=ot>0?` ${Oe} ${o.symbol}`:"";return Ke?`SWAP & PAY${me}`:`PAY${me}`},[Se,yt,G,u,ot,Oe,o.symbol,Ke]),At=Te==="success"?()=>{at("idle"),Ue(null),Pt(null),Be()}:be,Ot=Te==="success"?!1:!Q;if(!e)return null;const Et=E?b||`Pay ${o.symbol}`:u,Ct=E?S:n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[n.jsx("span",{style:{marginTop:"3px",flexShrink:0},children:n.jsx(ys,{color:ne})}),n.jsx("p",{style:{fontSize:"12px",color:ne,margin:0,lineHeight:"1.4",fontFamily:D},children:J})]});if(E){const me=Ee&&(Ee.status==="success"||Ee.status==="failed")?[{asset:{symbol:G?.asset?.symbol||o.symbol,address:G?.asset?.address||""},amount:Oe,txHash:Ee.txHash||"",success:Ee.status==="success",error:Ee.status==="failed"?Ee.error:void 0}]:void 0;return n.jsx(nn,{isOpen:e,onClose:t,title:Et,subtitle:Ct,styles:C,dark:v,footerLinkText:"Spicenet accounts \u2192",closeOnBackdropClick:s,children:n.jsxs("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[I&&n.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:n.jsx(Cs,{onClick:I,color:M,fontFamily:D})}),n.jsx("div",{style:{marginBottom:"12px"},children:n.jsx(Mn,{assets:Le,selectedAsset:G??void 0,onAssetSelect:It,onAmountChange:()=>{},label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:G?.asset?Ke?xt?"...":je?`~${parseFloat(j.formatUnits(je.amountIn,G.asset.decimals)).toFixed(6)}`:void 0:Oe??void 0:void 0,dark:v,theme:H,styles:C})}),n.jsx(Po,{variant:"pay",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:M,fontFamily:D,textPrimary:Y,textSecondary:L,cardBg:O,cardBorder:U,dk:B,dark:v,isQuoting:xt,quoteError:zt,estimatedOutput:Qt,paymentAmount:Oe,needsSwap:Ke,exactOutputSwap:je,adjustable:m==="adjustable",maxAmount:y,onAmountChange:$t}),le&&n.jsx(Ln,{fontFamily:D,textPrimary:Y,textSecondary:L,cardBg:O,cardBorder:U,resolvedDark:v,darkCardBorder:B.cardBorder,primaryColor:M,feePreview:_e,isLoading:et,errorText:pe,directExecutionFeeNote:Qe}),K&&n.jsx(In,{variant:"error",palette:N,fontFamily:D,style:{marginBottom:"12px"},children:K}),n.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:We,disabled:!Q,loading:Se,dark:v,styles:{...C,button:{...C?.button,backgroundColor:M}},children:Me}),Ee&&cn&&n.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:v?B.shell:"white",borderRadius:v?"12px":"6px",padding:"16px 0"},children:n.jsx(Ss,{type:"payment",isOpen:Ee.status!=="processing",isProcessing:Se||Ee.status==="processing",closeOnComplete:!1,chainName:h.getChainName(W),explorerUrl:h.getExplorerUrl(W,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{ht(!1),vt(null),We()},onNewTx:Xe,onClose:()=>{ht(!1),vt(null)},onComplete:Xe,results:me,styles:C,dark:v})})]})})}return n.jsx(nn,{isOpen:e,onClose:t,title:Et,subtitle:Ct,dark:v,styles:C,theme:T,closeOnBackdropClick:s,children:n.jsxs("div",{style:{padding:"24px 24px 5px 24px",position:"relative"},children:[n.jsx("div",{style:{marginBottom:"16px"},children:n.jsx(Mn,{assets:Le,selectedAsset:G||void 0,onAssetSelect:It,onAmountChange:Lt,disabled:Se||Te==="success",showBalance:!0,showMaxButton:!0,label:"From Spice Balance",placeholder:"0.00",theme:H,styles:C,dark:z,resolveMaxAmount:Ve,maxAmount:ct>0?vn(ct,G?.asset.decimals??o.decimals):void 0})}),G?.asset&&!Ze&&n.jsx(Po,{variant:"supply",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:M,fontFamily:D,textPrimary:Y,textSecondary:L,cardBg:O,cardBorder:U,dark:v,isQuoting:xt,quoteError:zt,estimatedOutput:Qt}),le&&n.jsx(Ln,{fontFamily:D,textPrimary:Y,textSecondary:L,cardBg:O,cardBorder:U,resolvedDark:v,darkCardBorder:B.cardBorder,primaryColor:M,feePreview:_e,isLoading:et,errorText:pe}),Te!=="idle"&&n.jsxs("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:Te==="success"?O:Te==="error"?N.errorBg:O,border:`1px solid ${Te==="success"?U:Te==="error"?N.errorBorder:U}`},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[Te==="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:N.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):Te==="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:N.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):n.jsx(h.Spinner,{size:14,color:M}),n.jsx("span",{style:{fontSize:"13px",fontWeight:500,color:Te==="success"?Y:Te==="error"?N.errorText:Y,fontFamily:D,flex:1},children:Te==="success"?"Deposit confirmed":Te==="error"?wt||"Transaction failed":Go[Te]||wt}),Te==="success"&&Rt&&n.jsx("a",{href:`${he}/tx/${Rt}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:M,fontFamily:D,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),Te==="error"&&n.jsx("button",{onClick:()=>{at("idle"),pt(null),setTimeout(be,50)},style:{background:"none",border:"none",fontSize:"12px",color:M,fontFamily:D,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),oe>=0&&Te!=="success"&&Te!=="error"&&n.jsx("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${L}22`,overflow:"hidden"},children:n.jsx("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:M,transformOrigin:"left center",transform:`scaleX(${(oe+1)/Jo.length})`,transition:"transform 400ms ease"}})})]}),jt&&Te==="idle"&&n.jsx(In,{variant:"error",palette:N,fontFamily:D,style:{marginBottom:"16px"},children:jt}),n.jsx(h.Button,{variant:"outline",fullWidth:!0,disabled:Ot,onClick:At,theme:T,dark:v,styles:{...C,button:{...C?.button,backgroundColor:M}},style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:q},children:fe})]})})},Li=e=>n.jsx($o,{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}),Oi=({label:e="Export Wallet",style:t,className:s,onExport:o,onError:r})=>{const[a,i]=l.useState(!1),[c,u]=l.useState(!1),{primaryColor:d}=h.useSpiceBrand(),f=l.useContext(h.SpiceFlowProviderContext),{isAuthenticated:p}=Jt();let g=null;try{g=Mt.usePrivy()}catch{}let m=null,x=null;try{m=En.useEmbeddedReveal(),x=En.useDynamicContext()}catch{m=null,x=null}const y=en.getDynamicEmbeddedWallet(x),k=l.useCallback(async()=>{if(!p){r?.("User is not authenticated. Please log in first.");return}try{if(f?.provider==="dynamic"){if(!m||!y){r?.("Dynamic is not available. Ensure the app is wrapped in a DynamicContextProvider.");return}await m.initExportProcess(!1),o?.();return}if(!g){r?.("Privy is not available. Ensure the app is wrapped in a PrivyProvider.");return}await g.exportWallet(),o?.()}catch(b){const S=b instanceof Error?b.message:"Failed to export wallet";console.error("Export wallet error:",b),r?.(S)}},[y,m,p,r,o,g,f?.provider]),C=!p,w={padding:"10px 20px",borderRadius:"8px",fontFamily:'"IBM Plex Mono", monospace',fontSize:"14px",fontWeight:500,letterSpacing:"0.4px",textTransform:"uppercase",cursor:C?"not-allowed":"pointer",opacity:C?.5:1,border:"1px solid #0e0d0b",color:"#0e0d0b",backgroundColor:c?`${d}cc`:a?`${d}ee`:d,transition:"background-color 150ms ease, transform 150ms ease",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"8px",...t};return n.jsxs("button",{onClick:k,onMouseEnter:()=>i(!0),onMouseLeave:()=>{i(!1),u(!1)},onMouseDown:()=>u(!0),onMouseUp:()=>u(!1),disabled:C,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 _o(e){const t=l.useContext(h.SpiceFlowProviderContext),s=Gt(),o=e?.enabled===!1?void 0:s,r=t?.network?{network:t.network,pollIntervalMs:e?.pollIntervalMs,chainIds:e?.chainIds??t.supportedChainIds}:void 0;return{...ro(o,r),embeddedWalletAddress:s}}const Hi=({appName:e,status:t,statusLabel:s,totalUsdValue:o,breakdownSubtitle:r,address:a,dk:i,dark:c=!1,showModeToggle:u,isEmbeddedMode:d=!0,onModeToggle:f})=>{const[p,g]=l.useState(!1),m=async()=>{a&&await Er(a)&&(g(!0),setTimeout(()=>g(!1),2e3))},x=t==="active",y=s||(x?"Active":"Inactive"),k=x?"#10b981":"#9ca3af";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("button",{onClick:f,style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:c?i.hoverBg:"#f3f4f6",border:c?`1px solid ${i.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"11px",fontWeight:600,fontFamily:'"IBM Plex Mono", monospace',color:i.textSecondary,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease",letterSpacing:"0.02em"},children:[n.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:d?"#22c55e":"#f59e0b"}}),n.jsx("span",{children:d?"Embedded":"External"})]}):n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:c?i.hoverBg:x?"#ecfdf5":"#f3f4f6",border:c?`1px solid ${i.cardBorder}`:x?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[n.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:k}}),n.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:c?i.textSecondary:x?"#065f46":"#6b7280"},children:y})]})]}),n.jsx("div",{style:{fontSize:"28px",fontWeight:700,color:i.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:wn(o)}),r&&n.jsx("div",{style:{fontSize:"12px",color:i.textSecondary,marginBottom:"8px"},children:r}),a&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[n.jsx("span",{style:{fontSize:"12px",fontFamily:'"IBM Plex Mono", monospace',color:c?i.textSecondary:"#9ca3af"},children:Ar(a)}),n.jsx("button",{onClick:m,style:{padding:"2px 6px",fontSize:"10px",fontWeight:500,backgroundColor:"transparent",color:c?i.textSecondary:"#9ca3af",border:"none",cursor:"pointer",borderRadius:"4px",transition:"background-color 150ms ease, color 150ms ease"},title:"Copy address",children:p?"Copied":"Copy"})]})]})},Qi=({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=h.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}`)})})]}),Vi=({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,c)=>{const u=h.getChainConfig(i.chainId),d=i.chainDisplayName||u?.displayName||`Chain ${i.chainId}`,f=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:f.charAt(0)}),n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:s.textPrimary},children:f}),n.jsx("div",{style:{fontSize:"11px",color:o?s.textSecondary:"#9ca3af"},children:d})]})]}),n.jsxs("div",{style:{textAlign:"right"},children:[n.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:s.textPrimary},children:un(i.balanceFormatted)}),n.jsx("div",{style:{fontSize:"11px",color:o?s.textSecondary:"#9ca3af"},children:wn(i.usdValue)})]})]},`${i.tokenAddress}-${i.chainId}-${c}`)})})]})},qi=({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))})]})},Yi=({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(h.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(h.Button,{variant:"outline",onClick:t,disabled:o,dark:a,styles:{button:{backgroundColor:r}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),Zi=({appName:e,status:t,statusLabel:s,totalUsdValue:o,breakdownSubtitle:r,address:a,spiceAssets:i,spiceAssetsLoading:c,pendingDeposits:u,customSections:d,onDepositClick:f,onWithdrawClick:p,onCompleteDeposit:g,primaryColor:m,dk:x,dark:y=!1,showModeToggle:k,isEmbeddedMode:C,onModeToggle:w,showConnectExternalCta:b,onConnectExternalWallet:S,connectExternalError:I})=>{const[A,F]=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(Hi,{appName:e,status:t,statusLabel:s,totalUsdValue:o,breakdownSubtitle:r,address:a,dk:x,dark:y,showModeToggle:k,isEmbeddedMode:C,onModeToggle:w}),b&&n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[n.jsx("button",{onClick:S,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:m||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:'"Helvetica Neue", sans-serif',transition:"opacity 150ms ease"},children:"Connect External Wallet"}),I&&n.jsx("span",{style:{fontSize:"11px",color:y?x.errorText:"#b91c1c",lineHeight:1.4},children:I})]}),n.jsx("div",{style:{height:"1px",backgroundColor:y?"#2d2d2d":"#e5e7eb"}}),n.jsx(Yi,{onDepositClick:f,onWithdrawClick:p,primaryColor:m,dark:y}),n.jsxs("div",{children:[n.jsxs("button",{onClick:()=>F(!A),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:x.cardBg,border:y?`1px solid ${x.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:x.textSecondary,fontSize:"12px",fontWeight:500},children:[n.jsx("span",{children:"How It Works"}),n.jsx("span",{style:{transform:A?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),A&&n.jsxs("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:y?x.cardBg:"#f0fdf4",border:y?`1px solid ${x.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:y?x.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),n.jsx(Qi,{pendingDeposits:u,onCompleteDeposit:g,dk:x,dark:y}),n.jsx(Vi,{spiceAssets:i,loading:c,dk:x,dark:y}),d.map((E,T)=>n.jsx(qi,{section:E,dk:x,dark:y},T))]})},Ds=380,Cn=8;function er(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function Ki(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 c=s.get(i);if(c!==void 0)return c}return 0}const Xi=({appName:e="Spice",status:t="active",statusLabel:s,customSections:o=[],extraAssets:r=[],tokenPrices:a={},breakdownLabels:i=[],styles:c,dark:u=!1,onDepositSuccess:d,onDepositClick:f,onWithdrawClick:p,onCompleteDeposit:g,showModeToggle:m=!1,defaultMode:x})=>{const y=l.useContext(h.SpiceFlowProviderContext),k=y?.mode!=="7702",C=l.useRef(!1);l.useEffect(()=>{if(!C.current){if(h.hasStoredSpiceFlowMode()){C.current=!0;return}x&&y?.setMode&&(y.setMode(x==="non7702"?"ondemand":"7702"),C.current=!0)}},[y,x]);const[w,b]=l.useState(!1),[S,I]=l.useState(null),[A,F]=l.useState({top:0,bottom:0,left:0,placement:"below"}),E=l.useRef(null),T=l.useRef(null),{address:v,isConnected:M}=Jt(),B=Gt(),{address:N}=ut.useAccount(),{dark:D,primaryColor:q,dk:z}=h.useSpiceBrand(c,u),O=l.useMemo(()=>y?.supportedChainIds??R.getChainIdsByNetwork("mainnet"),[y?.supportedChainIds]),{assets:U,loading:Y}=Dn({address:v,supportedChains:O,enabled:!!v&&!k,refetchInterval:3e4}),L=l.useMemo(()=>[...k?[]:U.map(de=>{const Le=de.balanceUsd||0,G=Number.isFinite(de.balanceFormatted)?de.balanceFormatted:0,Ue=Le>0?Le:Ki(de,a)*G;return{tokenAddress:de.address,tokenSymbol:de.symbol,tokenDisplaySymbol:hs(de),tokenDisplayName:Rr(de),tokenDecimals:de.decimals,chainId:de.chainId,chainDisplayName:ms(de),balance:de.balance.toString(),balanceFormatted:de.balanceFormatted,usdValue:Ue,logoURI:de.logoURI}}),...r].filter(de=>de.balanceFormatted>0),[k,U,a,r]),ne=l.useMemo(()=>L.reduce((de,Le)=>de+Le.usdValue,0),[L]),{pendingDeposits:H}=_o({chainIds:O,enabled:!!v}),W=l.useMemo(()=>o.reduce((de,Le)=>de+Le.totalValue,0),[o]),re=ne+W,ee=l.useMemo(()=>{const de=[];ne>0&&de.push(`${wn(ne)} idle`);for(const Le of o){const G=i.find(Ue=>Ue.sectionTitle===Le.title)?.label||Le.title.toLowerCase();de.push(`${wn(Le.totalValue)} ${G}`)}return de.join(" \xB7 ")},[ne,o,i]),ie=l.useCallback(de=>{g?g(de):I(de)},[g]),we=l.useCallback(()=>{I(null)},[]),Ae=l.useCallback(()=>{I(null),d?.()},[d]),X=l.useCallback(()=>{if(!E.current)return;const de=E.current.getBoundingClientRect(),Le=window.innerHeight-de.bottom-Cn,G=de.top-Cn,Ue=Le>=400||Le>=G?"below":"above",ge=Math.max(Cn,Math.min(de.right-Ds,window.innerWidth-Ds-Cn)),Je=Ue==="below"?de.bottom+Cn:de.top-Cn,Se=Ue==="above"?window.innerHeight-Je:0;F({top:Je,bottom:Se,left:ge,placement:Ue})},[]);l.useLayoutEffect(()=>{w&&X()},[w,X]),l.useEffect(()=>{if(!w)return;const de=Ue=>{E.current&&!E.current.contains(Ue.target)&&T.current&&!T.current.contains(Ue.target)&&b(!1)},Le=Ue=>{Ue.key==="Escape"&&b(!1)},G=()=>X();return document.addEventListener("mousedown",de),document.addEventListener("keydown",Le),window.addEventListener("scroll",G,{passive:!0}),window.addEventListener("resize",X),()=>{document.removeEventListener("mousedown",de),document.removeEventListener("keydown",Le),window.removeEventListener("scroll",G),window.removeEventListener("resize",X)}},[w,X]);const ue=y?.mode==="7702",xe=ue?B||v:N||v,Z=l.useCallback(()=>{y?.setMode&&y.setMode(ue?"ondemand":"7702")},[y,ue]),[ce,V]=l.useState(null);let te=null;try{te=Mt.useConnectWallet({onSuccess:()=>V(null),onError:de=>V(h.sanitizeError(de,"Failed to connect wallet."))}).connectWallet}catch{te=null}const Ce=l.useCallback(()=>{te&&(b(!1),V(null),te({walletChainType:"ethereum-only"}))},[te]),se=m&&!ue&&!N&&!!te,P=l.useCallback(()=>{b(!1),f?.()},[f]),ae=l.useCallback(()=>{b(!1),p?.()},[p]),ye=l.useCallback(de=>{b(!1),ie(de)},[ie]);if(typeof window>"u")return null;const Fe=n.jsxs("button",{ref:E,onClick:()=>b(!w),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:D?z.hoverBg:"#ffffff",border:D?`1px solid ${z.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:'"Helvetica Neue", sans-serif',color:D?z.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:D?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[n.jsx("span",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:q,flexShrink:0}}),n.jsxs("span",{children:[e," Account"]}),M&&n.jsxs("span",{style:{color:D?z.textSecondary:"#6b7280"},children:["\xB7 ",wn(re)]}),n.jsx("span",{style:{fontSize:"10px",color:D?z.textSecondary:"#9ca3af",transform:w?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),Be=w?jn.createPortal(n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:hn.popover},onClick:()=>b(!1)}),n.jsx("div",{ref:T,style:{position:"fixed",top:A.placement==="below"?`${A.top}px`:"auto",bottom:A.placement==="above"?`${A.bottom}px`:"auto",left:`${A.left}px`,width:`${Ds}px`,maxWidth:`calc(100vw - ${Cn*2}px)`,maxHeight:"80vh",backgroundColor:D?z.shell:"#ffffff",border:D?`1px solid ${z.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:D?"0 10px 40px rgba(0, 0, 0, 0.5)":"0 10px 40px rgba(0, 0, 0, 0.12)",zIndex:hn.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${bt.out}`},children:n.jsx(Zi,{appName:e,status:t,statusLabel:s,totalUsdValue:re,breakdownSubtitle:ee,address:m?xe:v,spiceAssets:L,spiceAssetsLoading:Y,pendingDeposits:H,customSections:o,onDepositClick:f?P:void 0,onWithdrawClick:p?ae:void 0,onCompleteDeposit:ye,primaryColor:q,dk:z,dark:D,showModeToggle:m,isEmbeddedMode:ue,onModeToggle:Z,showConnectExternalCta:se,onConnectExternalWallet:Ce,connectExternalError:ce})}),n.jsx("style",{children:`
|
|
103
|
+
`})]})},ri="0xa9059cbb";function ai(e){const t=new Map;for(const s of e){if(s.amount<=0n)continue;const o=j.getAddress(s.token),r=j.getAddress(s.to),a=`${o.toLowerCase()}:${r.toLowerCase()}`,i=t.get(a);i?i.amount+=s.amount:t.set(a,{token:o,to:r,amount:s.amount})}return[...t.values()]}function ii(e,t){return`0x${t}${e.slice(4)}`}function li(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,c=i.chainTokens;if((Array.isArray(c)?c.filter(u=>typeof u=="string"):c&&typeof c=="object"?Object.keys(c):[]).some(u=>u.toLowerCase()===o))try{r+=BigInt(i.balanceAvailable??"0")}catch{}}return r}async function To(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 li(a?.balances,s,o)}async function ci({apiBaseUrl:e,user:t,chainId:s,tokenAddress:o,prevBalance:r,timeoutMs:a=3e4,pollIntervalMs:i=1500}){const c=Date.now()+a;for(await new Promise(u=>setTimeout(u,800));Date.now()<c;){try{if(await To(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 Ts(e,t){return Mo(e,t)}function Mo(e,t,s){const o=di(t,e),r=Math.floor(Date.now()/1e3)+60*10,a=R.hashChainBatches(o);return{user:e,...s?{chainAuthorizations:s}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:"0x00",nbf:0,exp:r,chainBatches:a.map((i,c)=>({hash:i.hash,chainId:i.chainId,tokenTransfers:o[c].domain==="spicenet"?[]:o[c].tokenTransfers??[],calls:i.calls}))}]}}function di(e,t){return e.map(s=>{if(s.domain==="spicenet"||s.calls.length===0)return s;const o=new Set((s.tokenTransfers??[]).filter(a=>(a.from==="escrow"||a.from==="solver")&&j.getAddress(a.to).toLowerCase()===t.toLowerCase()).map(a=>j.getAddress(a.token).toLowerCase()));if(o.size===0)return s;let r=0;for(const a of s.calls){if(!a.data?.startsWith(ri))break;try{const i=j.decodeFunctionData({abi:h._,data:a.data});if(i.functionName!=="transfer")break;const[c]=i.args;if(c.toLowerCase()===t.toLowerCase()||!o.has(j.getAddress(a.to).toLowerCase()))break;r+=1}catch{break}}return r===0?s:{...s,calls:s.calls.slice(r)}})}function Gn(e,t,s){if(e.some(u=>u.domain==="spicenet"))return e;const o=s?.intents.flatMap(u=>u.batches),r=u=>u.from==="escrow",a=e.map(u=>{const d=o?.find(y=>y.chainId===u.chainId);if(!d)return u;const f=an(d).totalFee;if(f<=0n)return u;const p=(u.tokenTransfers??[]).find(y=>r(y)&&j.getAddress(y.to).toLowerCase()===t.toLowerCase()&&!R.isNativeToken(j.getAddress(y.token)));if(!p)return u;const g=j.getAddress(p.token);let m=!1;const x=(u.tokenTransfers??[]).map(y=>m||!r(y)||j.getAddress(y.to).toLowerCase()!==t.toLowerCase()||j.getAddress(y.token).toLowerCase()!==g.toLowerCase()?y:(m=!0,{...y,amount:BigInt(y.amount)+f}));return m?{...u,tokenTransfers:x,calls:[{to:g,value:0n,data:j.encodeFunctionData({abi:h._,functionName:"transfer",args:[gn,f]})},...u.calls]}:u}),i=a.flatMap(u=>(u.tokenTransfers??[]).filter(r).map(d=>{const f=j.getAddress(d.token),p=j.getAddress(d.to),g=[{token:f,to:p,amount:BigInt(d.amount)}];return{chainId:u.chainId,transfers:ai(g)}}));if(i.length===0)return e;const c=BigInt(Math.floor(Date.now()/1e3))+3600n;return[{chainId:R.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:i.map((u,d)=>{const f=j.keccak256(j.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,u.transfers[0].token,u.transfers.reduce((g,m)=>g+m.amount,0n),BigInt(u.chainId),BigInt(Date.now()+d)])),p=ii(f,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:j.encodeFunctionData({abi:R.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${u.chainId}`,idempotenceKey:p,nbf:0n,exp:c,metadata:"{}",transfers:u.transfers.map(g=>({token:g.token.toLowerCase(),to:g.to,amount:g.amount}))}]})}})},...a]}function Jn(e,t){const s=e.selectedAsset?.asset;if(!s||!e.selectedAsset?.amount)throw new Error("Select an asset and enter an amount");const o=t?.netAmount??j.parseUnits(e.selectedAsset.amount,s.decimals),r=t?.grossAmount??o;return e.resolveLockBatches({amount:j.formatUnits(o,s.decimals),amountWei:o,grossAmount:j.formatUnits(r,s.decimals),grossAmountWei:r})}async function Ro(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=h.getClientForChain(a),c=h.getDelegateContractAddress(a),u=await R.getAccountNonce(t,i),d=await e.actions.signAuthorization({contractAddress:c,chainId:a,nonce:Number(u)});r.push(d)}return r}async function Do(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 Ro(e,o,t),a=R.hashChainBatches(t),i=Math.floor(Date.now()/1e3)+60*10,c=a.map(m=>m.hash),u=j.keccak256(j.encodeAbiParameters([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,BigInt(i),c])),d=await e.actions.signMessage({raw:u}),f=typeof d=="string"?d:d.signature;if(!f)throw new Error("Failed to sign intent authorization");const p={mode:"7702",signatureType:"ecdsa",signature:f,nbf:0,exp:i,chainBatches:a.map((m,x)=>{const y=t[x],k=y.domain==="spicenet";return{hash:m.hash,chainId:m.chainId,tokenTransfers:k?[]:y.tokenTransfers??[],calls:m.calls}})},g=await h.relayerService.createAction({user:o,chainAuthorizations:r.map(m=>({r:m.r,s:m.s,yParity:m.yParity,address:m.address,chainId:Number(m.chainId),nonce:Number(m.nonce)})),intents:[p]});if(g){const m=h.createInitialSteps(t,h.getChainName),[x,y]=g.intentIds[0].split("/"),k=parseInt(y||"0",10),C=g.intentIds[0];e.startStatusPolling(g.intentIds[0],m),await xo({actionId:x,intentIndex:k,intentId:C,totalSteps:t.length,isSpicenetStep:w=>t[w]?.domain==="spicenet",maxExecuteAttemptsForStep:w=>t[w]?.domain==="spicenet"?6:3,maxPolls:180})}}async function No(e){let t=Jn(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 Ro(e,s,t);let r=Gn([...t],s),a;for(let i=0;i<4;i+=1){const c=await h.relayerService.estimateActionFees(Mo(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=Xn(c,{symbol:e.selectedAsset?.asset.symbol??"",decimals:e.selectedAsset?.asset.decimals??18});if(!u)break;const d={grossAmount:u.grossAmount,netAmount:u.netAmount,feeAmount:u.totalFee??0n},f=a?.grossAmount===d.grossAmount&&a?.netAmount===d.netAmount&&a?.feeAmount===d.feeAmount;if(a=d,t=Jn(e,a),r=Gn([...t],s,c),f)break}await Do(e,r,o)}async function ui(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");if(!e.address||!e.embeddedWalletAddress)throw new Error("Embedded wallet not connected");const t=e.selectedAsset.asset,s=j.parseUnits(e.selectedAsset.amount,t.decimals),o=e.escrowAddress||h.getDelegateContractAddress(e.lockChainId),r=h.relayerService.getBaseUrl(),a=R.normalizeNativeTokenAddress(t.address);let i=0n;try{i=await To(r,e.embeddedWalletAddress,e.lockChainId,a)}catch(p){console.warn("[SpiceLockModal] could not snapshot spice balance pre-deposit:",p?.message)}const c=await e.actions.getEthereumProvider();await h.ensureWalletOnChain(c,e.lockChainId);const u=h.getChainConfig(e.lockChainId),d=j.createWalletClient({account:e.embeddedWalletAddress,transport:j.custom(c),chain:u?.viemChain});let f;if(t.isNative||R.isNativeToken(t.address))f=await d.sendTransaction({to:o,value:s,chain:u?.viemChain});else{const p=j.encodeFunctionData({abi:h._,functionName:"transfer",args:[o,s]});f=await d.sendTransaction({to:t.address,data:p,chain:u?.viemChain})}if((await h.getClientForChain(e.lockChainId).waitForTransactionReceipt({hash:f,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to escrow failed");await ci({apiBaseUrl:r,user:e.embeddedWalletAddress,chainId:e.lockChainId,tokenAddress:a,prevBalance:i}),await e.refreshSpiceAssets(),e.refreshWalletAssets(),await No(e)}async function pi(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 w=e.resolveLockBatches();if(w.length===0)throw new Error("No lock batches configured");const b=e.selectedAsset.asset,S=j.parseUnits(e.selectedAsset.amount,b.decimals),I=await e.onLockExecute({asset:b,amount:e.selectedAsset.amount,amountWei:S,lockDurationMonths:e.selectedDuration?.months??0,chainBatches:w});I&&e.onLockSuccess?.(I);return}const s=e.resolveLockBatches();if(s.length===0)throw new Error("No lock batches configured");const o=e.selectedAsset.asset,r=j.parseUnits(e.selectedAsset.amount,o.decimals),a=o.chainId,i=e.escrowAddress||R.getEscrowContractAddress(a),c=R.normalizeNativeTokenAddress(o.address),u=o.isNative||R.isNativeToken(c);let d=null;for(const w of s){const b=w.tokenTransfers?.find(S=>S.from==="escrow");if(b){d={batch:w,to:b.to,token:b.token,amount:BigInt(b.amount)};break}}const f=await e.externalWallet.getEthereumProvider();let p=null;try{const w=await f.request({method:"eth_chainId"});p=parseInt(w,16)}catch{p=null}p!==a&&await h.ensureWalletOnChain(f,a);const g=h.getChainConfig(a),m=j.createWalletClient({account:e.externalWalletAddress,chain:g?.viemChain,transport:j.custom(f)}),x=u?await m.sendTransaction({to:t,value:r,chain:g?.viemChain}):await m.sendTransaction({to:c,data:j.encodeFunctionData({abi:h._,functionName:"transfer",args:[t,r]}),chain:g?.viemChain});if((await h.getClientForChain(a).waitForTransactionReceipt({hash:x,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to embedded wallet failed");const y={chainId:a,calls:u?[{to:i,value:r,data:"0x"}]:[{to:c,value:0n,data:j.encodeFunctionData({abi:h._,functionName:"transfer",args:[i,r]})}]};let k=null;if(d){if(!e.buildSpicenetBatch)throw new Error("Lock batches declare an escrow-backed ERC20 payout but no `buildSpicenetBatch` callback was provided. The relayer rejects 7702 intents with escrow-backed ERC20 transfers unless the intent includes a Spicenet batch authorising the withdrawal.");const w=e.buildSpicenetBatch({userAddress:t,destinationChainId:d.batch.chainId,deliveryToken:d.token,deliveryAmount:d.amount,deliveryRecipient:d.to});w&&(k={...w,domain:w.domain??"spicenet"})}const C=[y];k&&C.push(k),C.push(...s),await Do(e,C)}async function fi(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");const c=e.resolveLockBatches();if(c.length===0)throw new Error("No lock batches configured");const u=e.selectedAsset.asset,d=j.parseUnits(e.selectedAsset.amount,u.decimals),f=u.chainId,p=e.escrowAddress||R.getEscrowContractAddress(f),g=R.normalizeNativeTokenAddress(u.address),m=u.isNative||R.isNativeToken(g);let x=null;for(const b of c){const S=b.tokenTransfers?.find(I=>I.from==="escrow");if(S){x={batch:b,to:S.to,token:S.token,amount:BigInt(S.amount)};break}}const y={chainId:f,calls:m?[{to:p,value:d,data:"0x"}]:[{to:g,value:0n,data:j.encodeFunctionData({abi:h._,functionName:"transfer",args:[p,d]})}]};let k=null;if(x){if(!e.buildSpicenetBatch)throw new Error("Lock batches declare an escrow-backed payout but no `buildSpicenetBatch` callback was provided.");const b=e.buildSpicenetBatch({userAddress:i,destinationChainId:x.batch.chainId,deliveryToken:x.token,deliveryAmount:x.amount,deliveryRecipient:x.to});b&&(k={...b,domain:b.domain??"spicenet"})}const C=[y];k&&C.push(k),C.push(...c);const w=await h.relayerService.estimateActionFees(Ts(i,C));return Xn(w,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals})}const t=e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");let s=Jn(e);if(s.length===0)throw new Error("No lock batches configured");let o=Gn([...s],t),r=null;for(let i=0;i<4;i+=1){const c=await h.relayerService.estimateActionFees(Ts(t,o)),u=Xn(c,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals});if(!u)return null;const d={grossAmount:u.grossAmount,netAmount:u.netAmount},f=r?.grossAmount===u.grossAmount&&r?.netAmount===u.netAmount&&r?.totalFee===u.totalFee;if(r=u,s=Jn(e,d),o=Gn([...s],t,c),f)break}if(r)return r;const a=await h.relayerService.estimateActionFees(Ts(t,o));return Xn(a,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals})}async function hi(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.resolveLockBatches();if(t.length===0)throw new Error("No lock batches configured");const s=t.find(d=>d.chainId===e.lockChainId)||t[0];if(!s)throw new Error("No lock batch for lock chain");const o=await e.externalWallet.getEthereumProvider();let r=null;try{const d=await o.request({method:"eth_chainId"});r=parseInt(d,16)}catch{r=null}r!==e.lockChainId&&await h.ensureWalletOnChain(o,e.lockChainId);const a=h.getChainConfig(e.lockChainId),i=j.createWalletClient({account:e.externalWalletAddress,chain:a?.viemChain,transport:j.custom(o)}),c=h.getClientForChain(e.lockChainId);let u;for(const d of s.calls){const f=await i.sendTransaction({to:d.to,data:d.data,value:d.value,chain:a?.viemChain});if((await c.waitForTransactionReceipt({hash:f,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Lock transaction failed");u=f}u&&e.onLockSuccess?.(u)}async function mi(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=h.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 hi(e)}catch(s){t(s)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{await pi(e)}catch(s){t(s)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{e.isDirectDeposit&&!e.isSourceDestToken?await ui(e):await No(e)}catch(s){t(s)}finally{e.ui.setIsExecuting(!1)}}const Wo=({isOpen:e,onClose:t,closeOnBackdropClick:s=!1,lockBatches:o,lockTokenSymbol:r,lockTokenLogoURI:a,destinationInputHook:i,sourceAssetInputHook:c,lockDurationHook:u,lockChainId:d,durationOptions:f,votingPowerEstimate:p,escrowAddress:g,includeWalletAssets:m=!1,destinationTokenAddress:x,onLockSuccess:y,onLockExecute:k,sourceToDestinationConversionRate:C,estimatedOutputAmount:w,onAddFunds:b,buildSpicenetBatch:S,styles:I,dark:A=!1})=>{const{theme:F,dark:E,primaryColor:T,dk:v}=h.useSpiceBrand(I,A),M=F.typography.fontFamily,B=l.useContext(h.SpiceFlowProviderContext),N=(B?.mode||"7702")!=="7702",D=l.useMemo(()=>B?.supportedChainIds??[],[B?.supportedChainIds]),q=l.useMemo(()=>{const K=B?.allowedTokens;if(!K||K.length===0)return[];const le=new Set(K.map(Ve=>Ve.toLowerCase())),De=[],Ie=new Set;for(const Ve of D){const We=h.getChainConfig(Ve);for(const ze of We?.supportedTokens??[]){if(!le.has(ze.symbol.toLowerCase()))continue;const Ge=`${Ve}:${ze.address.toLowerCase()}`;Ie.has(Ge)||(Ie.add(Ge),De.push(j.getAddress(ze.address)))}}return De},[B?.allowedTokens,D]),z=E?v.cardBg:I?.assetSelector?.backgroundColor||I?.secondaryBackground||"#e9e9e9",O=E?`1px solid ${v.cardBorder}`:"0.5px solid #A8A8A7",U=E?"12px":"6px",Y=E?v.textPrimary:"#111827",L=E?v.textSecondary:"#6b7280",ne=l.useMemo(()=>({...I,assetSelector:{...I?.assetSelector,backgroundColor:E?v.cardBg:I?.assetSelector?.backgroundColor,borderRadius:E?"12px":I?.assetSelector?.borderRadius},secondaryBackground:E?v.cardBg:I?.secondaryBackground}),[I,E]),H=l.useMemo(()=>E?{...F,colors:{...F.colors,secondary:v.cardBg,surfaceHover:v.hoverBg,border:v.cardBorder,borderHover:v.inputBorder}}:F,[E,F]),[W,re]=l.useState(null),[ee,ie]=l.useState(0),we=u?.selectedDurationIdx??ee,Ae=u?.setSelectedDurationIdx??ie,[X,ue]=l.useState(!1),[xe,Z]=l.useState(null),[ce,V]=l.useState(null),[te,Ce]=l.useState(!1),[se,P]=l.useState(!1),[ae,ye]=l.useState(null),[Fe,Be]=l.useState(!1),de=l.useRef(0),[Le,G]=l.useState(!1),[Ue,ge]=l.useState(null);ut.useWalletClient(),ut.useSwitchChain();const{chain:Je,address:Se}=ut.useAccount();ut.useConfig();const rt=l.useRef(Je);l.useEffect(()=>{rt.current=Je},[Je]);const jt=Jt(),{isReady:pt,isAuthenticated:Te,isConnected:at,address:wt,provider:kt,actions:Rt}=jt,{externalWallet:Pt,embeddedAddress:cn,externalAddress:ht}=Rn(),{intentStatus:Ee,startStatusPolling:vt,clearStatus:_e}=Gs({checkStepStatus:(K,le)=>h.relayerService.checkStepStatus(K,le),retryStep:async(K,le)=>{const[De,Ie]=K.split("/"),Ve=parseInt(Ie||"0",10);await h.relayerService.executeStep(De,Ve,le,{action:"execute"})},maxRetries:3}),{assets:mt,refetch:et}=Dn({address:wt,supportedChains:D,enabled:at&&!N,refetchInterval:3e4}),tt=l.useMemo(()=>{if(q.length===0)return mt;const K=new Set(q.map(le=>le.toLowerCase()));return mt.filter(le=>K.has(le.address.toLowerCase()))},[mt,q]),Ht=Gt(),st=N?Se||ht:Ht,pe=l.useMemo(()=>{if(!m)return[];const K=new Set,le=[],De=Ie=>{if(!Ie)return;const Ve=Ie.toLowerCase();K.has(Ve)||(K.add(Ve),le.push(j.getAddress(Ie)))};if(x&&De(x),N)for(const Ie of q)De(Ie);return le},[m,N,x,q]),Ye=l.useMemo(()=>pe.map(K=>K.toLowerCase()).sort().join(","),[pe]),Ut=l.useMemo(()=>JSON.stringify([...D||[]].sort()),[D]),[lt,ke]=l.useState([]),gt=l.useRef(0),nt=l.useCallback(async()=>{if(!m||!st||pe.length===0){gt.current++,ke([]);return}const K=++gt.current,le=j.getAddress(st),De=D&&D.length>0?D:[d],Ie=pe.map(Xe=>{const qe=Xe.toLowerCase();for(const Q of De){const J=h.getChainConfig(Q)?.supportedTokens?.find(he=>h.addressesEqual(he.address,qe));if(J)return{address:Xe,chainId:Q,configToken:{decimals:J.decimals,symbol:J.symbol,name:J.name,logo:J.logo}}}return{address:Xe,chainId:d}}),Ve=new Map;for(const Xe of Ie){const qe=Ve.get(Xe.chainId)||[];qe.push(Xe),Ve.set(Xe.chainId,qe)}const We=async(Xe,qe)=>{try{const Q=await Tt.readContract(Xe,{address:qe.address,abi:h._,functionName:"balanceOf",args:[le]});let J,he,oe,fe;if(qe.configToken)J=qe.configToken.decimals,he=qe.configToken.symbol,oe=qe.configToken.name,fe=qe.configToken.logo;else{const[Ot,Et,Ct]=await Promise.all([Tt.readContract(Xe,{address:qe.address,abi:h._,functionName:"decimals",args:[]}).catch(()=>18),Tt.readContract(Xe,{address:qe.address,abi:h._,functionName:"symbol",args:[]}).catch(()=>"TOKEN"),Tt.readContract(Xe,{address:qe.address,abi:h._,functionName:"name",args:[]}).catch(()=>"TOKEN")]);J=Number(Ot),he=Et,oe=Ct}const Me=!!x&&h.addressesEqual(qe.address,x)&&qe.chainId===d;Me&&a&&(fe=a),Me&&r&&!qe.configToken&&(he==="TOKEN"&&(he=r),oe==="TOKEN"&&(oe=r));const At=parseFloat((Number(Q)/Math.pow(10,J)).toFixed(6));return{address:qe.address,name:oe,symbol:he,decimals:J,balance:Q,balanceFormatted:At,balanceUsd:0,logoURI:fe,isNative:!1,chainId:qe.chainId}}catch{return null}},ze=await Promise.all(Array.from(Ve.entries()).map(async([Xe,qe])=>{let Q;try{Q=h.getClientForChain(Xe)}catch{return[]}const J=[],he=[];for(const fe of qe){const Me=J.length;J.push({address:fe.address,abi:h._,functionName:"balanceOf",args:[le]}),fe.configToken||J.push({address:fe.address,abi:h._,functionName:"decimals",args:[]},{address:fe.address,abi:h._,functionName:"symbol",args:[]},{address:fe.address,abi:h._,functionName:"name",args:[]}),he.push({start:Me,item:fe})}let oe=null;try{oe=await Q.multicall({contracts:J})}catch{oe=null}return oe?he.map(({start:fe,item:Me})=>{const At=oe[fe],Ot=At?.status==="success"?At.result:0n;let Et,Ct,me,Ne;if(Me.configToken)Et=Me.configToken.decimals,Ct=Me.configToken.symbol,me=Me.configToken.name,Ne=Me.configToken.logo;else{const Dt=oe[fe+1],Yt=oe[fe+2],Xt=oe[fe+3];Et=Dt?.status==="success"?Number(Dt.result):18,Ct=Yt?.status==="success"?Yt.result:"TOKEN",me=Xt?.status==="success"?Xt.result:Ct}const Bt=!!x&&h.addressesEqual(Me.address,x)&&Me.chainId===d;Bt&&a&&(Ne=a),Bt&&r&&!Me.configToken&&(Ct==="TOKEN"&&(Ct=r),me==="TOKEN"&&(me=r));const qt=parseFloat((Number(Ot)/Math.pow(10,Et)).toFixed(6));return{address:Me.address,name:me,symbol:Ct,decimals:Et,balance:Ot,balanceFormatted:qt,balanceUsd:0,logoURI:Ne,isNative:!1,chainId:Me.chainId}}):(await Promise.all(qe.map(fe=>We(Q,fe)))).filter(fe=>fe!==null)}));if(K!==gt.current)return;const Ge=ze.flat();ke(Ge)},[m,st,Ye,Ut,d,x,a,r]);l.useEffect(()=>{if(!m){ke([]);return}nt();const K=setInterval(()=>{nt()},15e3);return()=>clearInterval(K)},[nt,m]);const Oe=l.useCallback(()=>{nt()},[nt]),Kt=l.useMemo(()=>lt.filter(K=>K.balance>0n),[lt]),xt=l.useMemo(()=>{if(N)return Kt.map(le=>({...le,_source:"wallet"}));if(!m)return tt;const K=[];for(const le of Kt)K.push({...le,_source:"wallet"});for(const le of tt)K.push({...le,_source:"spice"});return K},[N,m,Kt,tt]),zt=l.useRef(null),Qt=l.useRef(null);l.useEffect(()=>{Qt.current=W},[W]),l.useEffect(()=>{e||(re(null),Z(null),V(null),Ce(!1),P(!1),ye(null),ue(!1),G(!1),ge(null),Be(!1),_e())},[e,_e]),l.useEffect(()=>{i&&i.assetAmount!==(W?.amount||"")&&re(K=>K&&{...K,amount:i.assetAmount})},[i?.assetAmount]),l.useEffect(()=>{c&&c.assetAmount!==(W?.amount||"")&&re(K=>K&&{...K,amount:c.assetAmount})},[c?.assetAmount]),l.useEffect(()=>{if(!N&&Ee?.overallStatus==="success"&&Ee.intentId&&zt.current!==Ee.intentId&&wt&&Ee.steps.find(K=>K.transactionHash)?.transactionHash){zt.current=Ee.intentId;const K=Qt.current;if(!K?.asset||!K.amount||K.asset._source==="wallet"||j.parseUnits(K.amount,K.asset.decimals)===0n)return;et()}},[Ee,wt,d,et,N]);const He=parseFloat(W?.amount||"")||0,je=l.useMemo(()=>W?.asset?W.asset._source==="wallet"?W.asset.balanceFormatted??0:tt.find(K=>h.addressesEqual(K.address,W.asset.address)&&K.chainId===W.asset.chainId)?.balanceFormatted??0:0,[W?.asset,tt]),it=He>0&&(ae?parseFloat(j.formatUnits(ae.grossAmount,ae.decimals))>je:He>je),$e=u?.selectedDuration??f[we]??f[0],Ze=l.useMemo(()=>!W?.asset||!x?!1:h.addressesEqual(W.asset.address,x)&&W.asset.chainId===d,[W?.asset,x,d]),Ke=l.useMemo(()=>He<=0?0:Ze?He:!C||C<=0?0:He/C,[He,C,Ze]),St=l.useMemo(()=>Ke<=0?null:Ke.toLocaleString(void 0,{maximumFractionDigits:2}),[Ke]),ot=p&&Ke>0&&$e?p(Ke,$e.months):void 0,ct=l.useMemo(()=>He<=0?"$0.00":Ze&&C?(He*C).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!C||C<=0?"$0.00":He.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[He,C,Ze]),yt=l.useMemo(()=>{if(!St)return null;const K=parseFloat(St.replace(/,/g,""));return Ze&&C?(K*C).toLocaleString(void 0,{maximumFractionDigits:2}):C?(K*C).toLocaleString(void 0,{maximumFractionDigits:2}):null},[St,C,Ze]),It=l.useCallback(K=>{re(le=>({asset:K,amount:le?.asset?.address===K.address&&le?.asset?.chainId===K.chainId&&le.amount||""})),Z(null),V(null),P(!1),ye(null),c?.setSelectedAsset&&c.setSelectedAsset({symbol:K.symbol,address:K.address,decimals:K.decimals,chainId:K.chainId})},[c?.setSelectedAsset]),Lt=l.useCallback(K=>{re(le=>le&&{...le,amount:K}),Z(null),V(null),P(!1),ye(null),i&&i.setAssetAmount(K),c&&c.setAssetAmount(K)},[i,c]),$t=l.useCallback(K=>{if(typeof o=="function"){if(!W?.asset||!W.amount)throw new Error("Select an asset and enter an amount");return o({asset:W.asset,amount:K?.amount??W.amount,amountWei:K?.amountWei??j.parseUnits(W.amount,W.asset.decimals),grossAmount:K?.grossAmount,grossAmountWei:K?.grossAmountWei,feeAdjusted:!!K})}return o},[o,W]),Re=l.useRef(null),dt=l.useMemo(()=>!W?.asset||He<=0?!1:N?!Ze&&!k:!0,[W,He,N,Ze,k]),Vt=l.useCallback(()=>fi(Re.current),[]);l.useEffect(()=>{if(!e||X)return;if(!W?.asset||He<=0){V(null),Ce(!1),P(!1),ye(null);return}if(!dt){V(null),Ce(!1),P(!0),ye(null);return}let K=!1;const le=async()=>{const Ve=++de.current;V(null),P(!1),Ce(!0);try{const We=await Vt();if(K||de.current!==Ve)return;V(null),P(!0),ye(We)}catch(We){if(K||de.current!==Ve)return;V(h.sanitizeError(We,"Unable to calculate fees for this lock.")),P(!1)}finally{!K&&de.current===Ve&&Ce(!1)}},De=window.setTimeout(()=>{le()},250),Ie=window.setInterval(()=>{le()},1e4);return()=>{K=!0,clearTimeout(De),window.clearInterval(Ie),Ce(!1),P(!1)}},[e,X,W,He,dt,Vt]),l.useEffect(()=>{if(Ee?.overallStatus==="success"){const K=Ee.steps.find(le=>le.transactionHash);y?.(K?.transactionHash)}},[Ee?.overallStatus,y]);const Ft=m&&W?.asset?._source==="wallet"&&W?.asset?.chainId===d,$=l.useCallback(()=>mi(Re.current),[]),_=!!W?.asset&&He>0&&!it&&!X&&(!dt||se&&!te&&!ce),be=xe||ce,Pe=n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[n.jsx(ys,{color:L}),n.jsxs("p",{style:{fontSize:"13px",color:L,margin:0,lineHeight:"1.5"},children:["Add ",r," by converting assets from your account"]})]});if(Re.current={selectedAsset:W,parsedAmount:He,selectedDuration:$e,isInsufficientBalance:it,isSemi7702:N,isSourceDestToken:Ze,isDirectDeposit:Ft,requiresRelayerFeeEstimate:dt,address:wt,embeddedWalletAddress:Ht,providerEmbeddedAddress:cn,externalWallet:Pt,externalWalletAddress:Se,isConnected:at,ready:pt,authenticated:Te,provider:kt,actions:Rt,lockChainId:d,escrowAddress:g,onLockExecute:k,onLockSuccess:y,buildSpicenetBatch:S,resolveLockBatches:$t,startStatusPolling:vt,refreshSpiceAssets:et,refreshWalletAssets:Oe,ui:{setError:Z,setIsExecuting:ue,setShowStatusPanel:Be}},!e)return null;const Qe={backgroundColor:z,border:O,borderRadius:U,padding:"16px",marginBottom:"16px"};return n.jsx(nn,{isOpen:e,onClose:t,title:`Add ${r} to your account`,subtitle:Pe,styles:I,dark:E,footerLinkText:"Spicenet accounts \u2192",overlayContent:Le?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:[b&&n.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:n.jsx(Cs,{onClick:b,color:T,fontFamily:M})}),n.jsx("div",{style:{marginTop:"10px",fontSize:"13px",color:L,fontFamily:M},children:n.jsx(Mn,{assets:xt,selectedAsset:W??void 0,onAssetSelect:It,onAmountChange:Lt,label:"Amount",showBalance:!0,showMaxButton:!0,theme:H,styles:ne})}),n.jsx("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:L,fontFamily:M},children:ct})]}),n.jsxs("div",{style:Qe,children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:E?`1px solid ${v.cardBorder}`:"1px solid #e5e7eb"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[a?n.jsx("img",{src:a,alt:r,style:{width:"32px",height:"32px",borderRadius:"50%",objectFit:"cover"}}):n.jsx("div",{style:{width:"32px",height:"32px",borderRadius:"50%",backgroundColor:E?v.inputBg:"#d1d5db",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:700,color:Y},children:r.slice(0,2)}),n.jsx("span",{style:{fontSize:"16px",fontWeight:600,color:Y,fontFamily:M},children:r})]}),n.jsxs("div",{style:{textAlign:"right"},children:[n.jsx("div",{style:{fontSize:"22px",fontWeight:700,color:Y,fontFamily:M,lineHeight:1.1},children:St??"0.00"}),n.jsxs("div",{style:{fontSize:"12px",color:L,fontFamily:M,marginTop:"2px"},children:["~$",yt??"0.00"]})]})]}),n.jsxs("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:E?`1px solid ${v.cardBorder}`:"1px solid #e5e7eb"},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[n.jsx("span",{style:{fontSize:"15px",fontWeight:500,color:L,fontFamily:M},children:"Lock Duration"}),n.jsx(sn,{color:L})]}),n.jsx(ei,{options:f,selectedIndex:we,onSelect:Ae,primaryColor:T,dark:E,textPrimary:Y,textSecondary:L})]}),n.jsxs("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[n.jsx(ni,{durationMonths:$e?.months,fontFamily:M,dark:E,textPrimary:Y,textSecondary:L}),p&&n.jsx(si,{votes:ot,fontFamily:M,dark:E,textPrimary:Y,textSecondary:L})]})]}),dt&&n.jsx(Ln,{fontFamily:M,textPrimary:Y,textSecondary:L,cardBg:z,cardBorder:O,resolvedDark:E,darkCardBorder:v.cardBorder,primaryColor:T,feePreview:ae,isLoading:te,errorText:ce}),be&&n.jsx(In,{variant:"error",palette:v,fontFamily:M,style:{marginBottom:"12px"},children:be}),n.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:$,disabled:!_,loading:X,dark:E,styles:{...I,button:{...I?.button,backgroundColor:T}},children:X?Ft&&!Ze?"DEPOSITING...":Ze?"LOCKING...":"CONVERTING...":te&&dt?"CALCULATING FEES...":Ft&&!Ze?`DEPOSIT ${r}`:Ze?`LOCK ${r}`:`CONVERT TO ${r}`}),n.jsx(oi,{isOpen:Le,data:Ue,isLocking:X,lockError:be,onContinue:$,onClose:()=>G(!1),primaryColor:T,fontFamily:M,dark:E}),Ee&&Fe&&n.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:E?v.shell:"white",borderRadius:U,padding:"16px 0"},children:n.jsx(Ss,{type:"deposit",isOpen:!!Ee&&Ee.overallStatus!=="processing",isProcessing:X||Ee?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{_e(),Be(!1),$()},onNewTx:()=>{_e(),Be(!1),re(null),zt.current=null,et(),Oe()},onClose:()=>{_e(),Be(!1)},onComplete:()=>{_e(),Be(!1),re(null),zt.current=null,et(),Oe()},results:Ee?.overallStatus==="success"||Ee?.overallStatus==="failed"?Ee.steps.map(K=>({asset:{symbol:W?.asset?.symbol||r,address:W?.asset?.address||""},txHash:K.transactionHash||"",success:K.status==="success",amount:W?.amount})):void 0,chainName:h.getChainName(d),explorerUrl:h.getExplorerUrl(d,"").replace(/\/tx\/.*$/,"")||void 0,theme:F,styles:I,dark:E})})]})})},gi="0xa9059cbb";function xi(e,t,s,o){return t!=="user-transfer"||!s||e.length===0||e[0]?.to.toLowerCase()!==o.toLowerCase()||!e[0]?.data.startsWith(gi)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function $n(e,t,s){if(!t)return[e];const o=await t(s);return o?[o,e]:[e]}function _n(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 yi(e,t){const{currentPaymentAmount:s,destinationToken:o,embeddedWalletAddress:r,providerEmbeddedAddress:a,address:i,isNon7702:c,isPayMode:u,resolvedChainId:d,buildActionCalls:f,feeExecutionMode:p,buildSpicenetBatch:g,selectedAsset:m,needsSwap:x,exactOutputSwap:y,resolvedTokenIn:k}=e,C=j.parseUnits(s,o.decimals),w=t?.actionAmountOverride??C,b=r||a||(c?void 0:i);if(!b)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const S={userAddress:b,chainId:d,destinationToken:o.address,grossAmount:t?.fundingAmountOverride??C,netAmount:w,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:p,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},I=f(w,S),A={chainId:d,calls:I},F=(!u&&!c?!0:m?.asset?._source==="spice")||c,E=(T,v)=>({token:T,from:c?"solver":"escrow",to:b,amount:v});if(C===0n)return[A];if(x&&y){const T=k??on(m.asset,d)??m.asset.address,v=t?.fundingAmountOverride??y.amountInMax,M=F?[E(T,v)]:[],B={to:T,value:0n,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"approve",args:[y.calls[0]?.to,y.amountInMax]})},N={chainId:d,calls:[B,...y.calls,...I],tokenTransfers:[...M,...A.tokenTransfers??[]]};return F?$n(N,g,{userAddress:b,destinationChainId:d,deliveryToken:T,deliveryAmount:v,deliveryRecipient:b,sourceAsset:m.asset}):[N]}if(F){const T=k??on(m.asset,d)??o.address,v=t?.fundingAmountOverride??C,M={...A,tokenTransfers:[E(T,v),...A.tokenTransfers??[]]};return $n(M,g,{userAddress:b,destinationChainId:d,deliveryToken:T,deliveryAmount:v,deliveryRecipient:b,sourceAsset:m.asset})}return[A]}async function Ci(e,t){const{selectedAsset:s,embeddedWalletAddress:o,resolvedChainId:r,destinationToken:a,buildActionCalls:i,feeExecutionMode:c,buildSpicenetBatch:u,isPayMode:d,isNon7702:f,needsSwap:p,resolvedSwap:g,quoteAmountOut:m,resolvedTokenIn:x}=e,y=g?.amountOutMinimum??m;if(!s?.asset||!o)return[];const k=t?.fundingAmountOverride??t?.actionAmountOverride??j.parseUnits(s.amount,s.asset.decimals),C=t?.fundingAmountOverride??k,w=t?.actionAmountOverride??k,b={userAddress:o,chainId:r,destinationToken:a.address,feeToken:c==="user-transfer"&&p&&x?x:a.address,grossAmount:C,netAmount:w,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:c,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},S=i(w,b);if(!(!d&&!f||s.asset?._source==="spice"))return[{chainId:r,calls:S}];const I=(E,T)=>({token:E,from:"escrow",to:o,amount:T});if(p){if(!x)throw new Error("Swap input token could not be resolved");if(!g||y===null)throw new Error("Swap quote not available yet")}if(p&&g&&y&&x){const E=i(t?.actionAmountOverride??y,{...b,netAmount:t?.actionAmountOverride??y}),{feeCall:T,remainingCalls:v}=xi(E,c,p,b.feeToken),M={chainId:r,calls:[...T?[T]:[],...g.calls,...v],tokenTransfers:[I(x,C)]};return $n(M,u,{userAddress:o,destinationChainId:r,deliveryToken:x,deliveryAmount:C,deliveryRecipient:o,sourceAsset:s.asset})}const A=x??on(s.asset,r)??a.address,F={chainId:r,calls:S,tokenTransfers:[I(A,C)]};return $n(F,u,{userAddress:o,destinationChainId:r,deliveryToken:A,deliveryAmount:C,deliveryRecipient:o,sourceAsset:s.asset})}async function bi(e,t,s,o,r){let a=e;for(let i=0;i<4;i++){const c=await t(a),u=await o(c,s,a,r),d=Pa(u);if(d===null||d>=e)return a;const f=a-d,p=e+f;if(p<=a)return a;a=p}return a}function wi(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 ki(e,t){const s=j.formatUnits(e,t);return s.includes(".")?s.replace(/\.?0+$/,"")||"0":s}async function vi(e){const{asset:t,isPayMode:s,isNon7702:o,needsSwap:r,isQuoting:a,embeddedWalletAddress:i,buildSupplyChainBatches:c,estimateGasless:u,executionTokenAddress:d,feeExecutionMode:f}=e;if(s||o||r||a||!i||t.balance<=0n)return null;const p=await c({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(p.length===0)return null;const g=p.some(C=>C.tokenTransfers?.length),m=await u(p,d,t.balance,g?{useCustomTransfers:!0,feeExecutionMode:f}:f?{feeExecutionMode:f}:void 0),x=yn(m,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),y=x?_n(x.gasFee,x.decimals,t.decimals):0n,k=x?_n(x.spicenetFee,x.decimals,t.decimals):0n;return ki(wi(t.balance,y,k,t.balance),t.decimals)}async function Si(e){const{selectedAsset:t,isPayMode:s,parsedAmount:o,needsSwap:r,exactOutputSwap:a,isNon7702:i,isSourceDestToken:c,currentPaymentAmount:u,destinationToken:d,feeExecutionMode:f,resolvedTokenIn:p,embeddedWalletAddress:g,providerEmbeddedAddress:m,resolvedChainId:x,isConnected:y,address:k,ready:C,authenticated:w,isDirect:b,resolvedSwap:S,isQuoting:I,executionTokenAddress:A,buildPayChainBatches:F,buildSupplyChainBatches:E,estimateGasless:T,estimateRequiredGrossFunding:v}=e;if(!t?.asset)return null;if(s){if(o<=0||r&&!a||i&&c)return null;const q=j.parseUnits(u,d.decimals),z=p||on(t.asset,x)||t.asset.address||d.address,O={chainId:x,tokenAddress:z,symbol:R.getTokenByAddress(z,x)?.symbol??t.asset.symbol,decimals:R.getTokenByAddress(z,x)?.decimals??t.asset.decimals};if(i){const re=g||m;if(!re)return null;const ee=r?a?.amountInMax??0n:q;if(ee===0n)return null;const ie=await v(ee,X=>F({fundingAmountOverride:X}),z,{userOverride:re,useCustomTransfers:!0}),we=await F({fundingAmountOverride:ie}),Ae=await T(we,z,ie,{userOverride:re,useCustomTransfers:!0,feeExecutionMode:f});return yn(Ae,O)}if(!y||!k||!C||!w)return null;const U=r?a?.amountInMax??0n:q;if(U===0n)return null;const Y=await v(U,re=>F({fundingAmountOverride:re}),z,{useCustomTransfers:!0});let L=await F({fundingAmountOverride:Y});const ne=await T(L,z,Y,{useCustomTransfers:!0,feeExecutionMode:f}),H=yn(ne,O)?.grossAmount??Y;H!==Y&&(L=await F({fundingAmountOverride:H}));const W=await T(L,z,H,{useCustomTransfers:!0,feeExecutionMode:f});return yn(W,O)}if(o<=0||!g||!b&&!S&&!I||I)return null;const M=j.parseUnits(t.amount,t.asset.decimals),B=await E();if(B.length===0)return null;const N=B.some(q=>q.tokenTransfers?.length),D=await T(B,A,M,N?{useCustomTransfers:!0,feeExecutionMode:f}:f?{feeExecutionMode:f}:void 0);return yn(D,{chainId:x,tokenAddress:A,symbol:R.getTokenByAddress(A,x)?.symbol??d.symbol,decimals:R.getTokenByAddress(A,x)?.decimals??d.decimals})}async function Ii(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.embeddedWalletAddress){e.ui.setError("Wallet not ready");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.ui.setTxHash(null),e.refs.spiceDepositSubmittedRef.current=!1;const t=new AbortController;e.refs.abortControllerRef.current=t;try{const s=j.parseUnits(e.selectedAsset.amount,e.selectedAsset.asset.decimals),o=s;let r=await e.gasless.buildSupplyChainBatches();if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!r.some(f=>R.isSpicenetChainId(f.chainId)))throw new Error("Spice-funded supplies must include a Spicenet funding batch before the destination chain batch.");const a=r.some(f=>f.tokenTransfers?.length)?{useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}:e.feeExecutionMode?{feeExecutionMode:e.feeExecutionMode}:void 0;let i=s;const c=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,u=e.feeExecutionMode==="user-transfer"&&!c?o:void 0;let d;for(let f=0;f<4;f+=1){const p=await e.gasless.estimateGasless(r,e.executionTokenAddress,i,a),g=yn(p,{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:R.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId)?.symbol??e.destinationToken.symbol,decimals:R.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId)?.decimals??e.destinationToken.decimals}),m=g?.grossAmount??i;if(d=e.feeExecutionMode==="user-transfer"&&g?{grossAmount:g.grossAmount,netAmount:o,combinedFeeAmount:g.totalFee,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:g.spicenetFee,gasFee:g.gasFee,bridgeFee:g.bridgeFee??0n}}:void 0,e.feeExecutionMode==="user-transfer"&&g){i=m;break}if(m===i){i=m;break}i=m,r=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:i,actionAmountOverride:u,actionContextOverride:d})}e.feeExecutionMode==="user-transfer"&&(r=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:i,actionAmountOverride:u,actionContextOverride:d})),await e.gasless.executeGasless(r,e.executionTokenAddress,i,e.gasless.onProgress,t.signal,a),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 Ai(e){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=j.parseUnits(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),s={userAddress:e.externalWalletAddress,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},o=e.buildActionCalls(t,s);if(o.length===0)throw new Error("No action calls configured");const r=await e.externalWallet.getEthereumProvider();let a=null;try{const f=await r.request({method:"eth_chainId"});a=parseInt(f,16)}catch{a=null}a!==e.resolvedChainId&&await h.ensureWalletOnChain(r,e.resolvedChainId);const i=h.getChainConfig(e.resolvedChainId),c=j.createWalletClient({account:e.externalWalletAddress,chain:i?.viemChain,transport:j.custom(r)}),u=h.getClientForChain(e.resolvedChainId);let d;for(const f of o){const p=await c.sendTransaction({to:f.to,data:f.data,value:f.value,chain:i?.viemChain});if((await u.waitForTransactionReceipt({hash:p,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transaction failed");d=p}return d}async function Ei(e){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const s=e.selectedAsset.asset,o=s.chainId,r=j.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),a=e.selectedIsEquivalent?r:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(a===0n)throw new Error("Quote not available yet");const i=e.resolvedTokenIn||e.selectedAsset.asset.address,c={userOverride:t,useCustomTransfers:!0},u=await e.gasless.estimateRequiredGrossFunding(a,w=>e.gasless.buildPayChainBatches({fundingAmountOverride:w}),i,c),d=R.getEscrowContractAddress(o),f=await e.externalWallet.getEthereumProvider();let p=null;try{const w=await f.request({method:"eth_chainId"});p=parseInt(w,16)}catch{p=null}p!==o&&await h.ensureWalletOnChain(f,o);const g=h.getChainConfig(o),m=j.createWalletClient({account:e.externalWalletAddress,chain:g?.viemChain,transport:j.custom(f)}),x=R.normalizeNativeTokenAddress(s.address),y=s.isNative||R.isNativeToken(x)?await m.sendTransaction({to:d,value:u,chain:g?.viemChain}):await m.sendTransaction({to:x,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"transfer",args:[d,u]}),chain:g?.viemChain});if((await h.getClientForChain(o).waitForTransactionReceipt({hash:y,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Escrow deposit failed");const k=await e.gasless.buildPayChainBatches({fundingAmountOverride:u}),C=k.some(w=>w.tokenTransfers?.length);return await e.gasless.executeGasless(k,i,u,w=>{w.txHash&&(e.ui.setPaymentResult(b=>({...b??{status:"processing"},txHash:w.txHash})),e.ui.setTxHash(w.txHash))},void 0,C?c:{userOverride:t})}async function ji(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}if(!e.selectedAsset?.asset){e.ui.setError("Select a payment source");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.parsedAmount>0&&e.needsSwap&&!e.exactOutputSwap){e.ui.setError("Swap quote not available. Try a different asset.");return}if(e.isNon7702){if(!e.externalWalletAddress){e.ui.setError("Please connect your external wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{let t;if(e.isSourceDestToken||e.parsedAmount===0)t=await Ai(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const s=e.selectedAsset.asset,o=j.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),r=e.selectedIsEquivalent?o:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(r===0n)throw new Error("Quote not available yet");const a=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!a)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const i=e.resolvedTokenIn||s.address,c=await e.gasless.estimateRequiredGrossFunding(r,f=>e.gasless.buildPayChainBatches({fundingAmountOverride:f}),i,{userOverride:a,useCustomTransfers:!0}),u=await e.gasless.buildPayChainBatches({fundingAmountOverride:c}),d=await e.onPayExecute({asset:s,amount:e.currentPaymentAmount,amountWei:o,destinationToken:e.destinationToken,chainBatches:u,requiredNetFunding:r,grossFundingAmount:c,selectedIsEquivalent:e.selectedIsEquivalent,resolvedTokenIn:i,exactOutputSwapAmountInMax:e.exactOutputSwap?.amountInMax});d&&(e.ui.setTxHash(d),e.ui.setPaymentResult(f=>({...f??{status:"processing"},txHash:d}))),t=d||void 0}else t=await Ei(e);e.ui.setPaymentResult(s=>({status:"success",txHash:s?.txHash||t||""}))}catch(t){const s=h.sanitizeError(t,"Payment failed. Please try again.");e.ui.setError(s),e.ui.setPaymentResult({status:"failed",error:s}),e.onError?.(t instanceof Error?t:new Error(s))}finally{e.ui.setIsExecuting(!1)}return}if(!e.isConnected||!e.address){e.ui.setError("Please connect your wallet to continue");return}if(!e.ready||!e.authenticated){e.ui.setError(`Please authenticate with ${e.provider||"wallet provider"} to continue`);return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{const t=j.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),s=e.resolvedTokenIn||e.selectedAsset?.asset?.address||e.destinationToken.address,o=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:t,r={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode},a=await e.gasless.estimateRequiredGrossFunding(o,g=>e.gasless.buildPayChainBatches({fundingAmountOverride:g}),s,r);let i=a,c=await e.gasless.buildPayChainBatches({fundingAmountOverride:a});const u=await e.gasless.estimateGasless(c,s,a,r),d=yn(u,{chainId:e.resolvedChainId,tokenAddress:s,symbol:R.getTokenByAddress(s,e.resolvedChainId)?.symbol??e.selectedAsset.asset.symbol,decimals:R.getTokenByAddress(s,e.resolvedChainId)?.decimals??e.selectedAsset.asset.decimals})?.grossAmount??a;d!==a&&(i=d,c=await e.gasless.buildPayChainBatches({fundingAmountOverride:d}));const f=c.some(g=>g.tokenTransfers?.length),p=await e.gasless.executeGasless(c,s,f?i:0n,g=>{g.txHash&&(e.ui.setPaymentResult(m=>({...m,txHash:g.txHash})),e.ui.setTxHash(g.txHash))},void 0,r);e.ui.setPaymentResult(g=>({status:"success",txHash:g?.txHash||p}))}catch(t){const s=h.sanitizeError(t,"Payment failed. Please try again.");e.ui.setError(s),e.ui.setPaymentResult({status:"failed",error:s}),e.onError?.(t instanceof Error?t:new Error(s))}finally{e.ui.setIsExecuting(!1)}}const Po=({variant:e,destinationSymbol:t,destinationLogoURI:s,destinationDecimals:o,primaryColor:r,fontFamily:a,textPrimary:i,textSecondary:c,cardBg:u,cardBorder:d,dk:f,dark:p,isQuoting:g,quoteError:m,estimatedOutput:x,paymentAmount:y,needsSwap:k,exactOutputSwap:C,adjustable:w=!1,maxAmount:b,onAmountChange:S})=>e==="supply"?n.jsxs("div",{style:{backgroundColor:u,border:`1px solid ${d}`,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:c,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 ${d}`,borderRadius:"8px",padding:"8px 10px",minHeight:"42px"},children:[n.jsx(Uo,{symbol:t,logoURI:s,primaryColor:r,size:24}),n.jsx("span",{style:{fontSize:"16px",fontWeight:500,color:p?"#f3f4f6":"#3C3E42",lineHeight:"1.3",fontFamily:a,letterSpacing:0},children:t})]})]}),n.jsx("div",{style:{textAlign:"right",minWidth:0},children:g?n.jsx("span",{style:{fontSize:"18px",color:c,fontFamily:a},children:"Quoting..."}):m?n.jsx("span",{style:{fontSize:"13px",color:p?"#f87171":"#dc2626",fontFamily:a},children:"Quote failed"}):x?n.jsx(mn,{value:x,title:x,fontFamily:a,color:i,lineHeight:"0.95",textAlign:"right",maxFontSize:32,minFontSize:18}):n.jsx("span",{style:{fontSize:"20px",color:c,fontFamily:a},children:"\u2014"})})]}):n.jsx(Fi,{destinationSymbol:t,destinationLogoURI:s,destinationDecimals:o,primaryColor:r,fontFamily:a,textPrimary:i,textSecondary:c,cardBg:u,cardBorder:d,dk:f,dark:p,paymentAmount:y||"0",needsSwap:k,exactOutputSwap:C,isQuoting:g,adjustable:w,maxAmount:b,onAmountChange:S}),Uo=({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)}),Fi=({destinationSymbol:e,destinationLogoURI:t,destinationDecimals:s,primaryColor:o,fontFamily:r,textPrimary:a,textSecondary:i,cardBg:c,cardBorder:u,dk:d,dark:f,paymentAmount:p,needsSwap:g,exactOutputSwap:m,isQuoting:x,adjustable:y,maxAmount:k,onAmountChange:C})=>{const w='"IBM Plex Mono", monospace',b=parseFloat(p||"0"),S=k?parseFloat(k):0,[I,A]=l.useState(p||""),F=l.useRef(null),[E,T]=l.useState(null),[v,M]=l.useState(null);l.useEffect(()=>{y||A(p||"")},[p,y]);const B=q=>{let z=q;z.startsWith(".")&&(z="0"+z);const O=kn(z);let U=O;k&&parseFloat(O)>parseFloat(k)&&(U=k),A(U),F.current&&clearTimeout(F.current),F.current=setTimeout(()=>C?.(U),300)},N=q=>{if(!S)return;if(q===100){A(k||S.toString()),F.current&&clearTimeout(F.current),C?.(k||S.toString());return}const z=10**s,O=Math.floor(S*q/100*z)/z,U=vn(O,s);A(U),F.current&&clearTimeout(F.current),C?.(U)},D=S>0?parseFloat(I||"0")/S*100:0;return l.useEffect(()=>()=>{F.current&&clearTimeout(F.current)},[]),n.jsxs("div",{style:{backgroundColor:c,border:`1px solid ${u}`,borderRadius:f?"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(Uo,{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(mn,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:I,onChange:q=>B(q.target.value),placeholder:"0.0",fontFamily:w,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):n.jsx(mn,{element:"div",value:b>0?p:"0.00",title:b>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((q,z)=>{const O=Math.abs(D-q)<1,U=z===4,Y=q/100,L=E===q,ne=v===q;return n.jsx("button",{onClick:()=>N(q),onMouseEnter:()=>T(q),onMouseLeave:()=>{T(null),M(null)},onMouseDown:()=>M(q),onMouseUp:()=>M(null),title:`${q}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:O?1:L?.8:.5,transform:ne?"scale(0.85)":L?"scale(1.15)":"scale(1)",transition:Wt.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:U?o:"none",stroke:U?o:f?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!U&&Y>0&&n.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${Y>.5?1:0} 1 ${7+6.84375*Math.sin(Y*2*Math.PI)} ${7-6.84375*Math.cos(Y*2*Math.PI)} Z`,fill:f?d?.textSecondary||"#9ca3af":"#3C3E42"})]})},q)})})]})]}),g&&m&&!x&&n.jsx("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:f?`1px solid ${d?.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 ",m.venue]})})]})};function zo(e,t,s){const o=h.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 Bi(e){const{address:t,destinationToken:s,supportedSourceAssets:o,sourceChains:r,enabled:a}=e,i=(l.useContext(h.SpiceFlowProviderContext)?.mode||"7702")!=="7702",c=Gt(),{externalAddress:u,embeddedAddress:d}=Rn(),{assets:f,refetch:p}=Dn({address:t,supportedChains:r,enabled:a&&!i,refetchInterval:3e4}),g=l.useMemo(()=>{if(i)return[];if(!o||o.length===0)return f;const A=o.map(F=>F.toLowerCase());return f.filter(F=>A.includes(F.address.toLowerCase()))},[f,o,i]),m=i?u:c,x=l.useMemo(()=>{const A=new Set,F=[],E=T=>{if(!T)return;const v=T.toLowerCase();A.has(v)||(A.add(v),F.push(j.getAddress(T)))};if(E(s.address),i&&o)for(const T of o)E(T);return F},[i,s.address,o]),y=l.useMemo(()=>x.map(A=>A.toLowerCase()).sort().join(","),[x]),k=l.useMemo(()=>JSON.stringify([...r||[]].sort()),[r]),[C,w]=l.useState([]),b=l.useRef(0),S=l.useCallback(async()=>{if(!a||!m||x.length===0){b.current++,w([]);return}const A=++b.current,F=j.getAddress(m),E=i?r&&r.length>0?r:[s.chainId]:[s.chainId],T=[];for(const N of x){const D=N.toLowerCase();if(D===s.address.toLowerCase()){const z=h.getChainConfig(s.chainId)?.supportedTokens?.find(O=>h.addressesEqual(O.address,D));T.push({address:N,chainId:s.chainId,configToken:z?{decimals:z.decimals,symbol:z.symbol,name:z.name,logo:z.logo}:void 0});continue}let q=!1;for(const z of E){const O=h.getChainConfig(z)?.supportedTokens?.find(U=>h.addressesEqual(U.address,D));if(O){T.push({address:N,chainId:z,configToken:{decimals:O.decimals,symbol:O.symbol,name:O.name,logo:O.logo}}),q=!0;break}}q||T.push({address:N,chainId:s.chainId})}const v=new Map;for(const N of T){const D=v.get(N.chainId)||[];D.push(N),v.set(N.chainId,D)}const M=async(N,D)=>{try{const q=await Tt.readContract(N,{address:D.address,abi:j.erc20Abi,functionName:"balanceOf",args:[F]});let z,O,U,Y;if(D.configToken)z=D.configToken.decimals,O=D.configToken.symbol,U=D.configToken.name,Y=D.configToken.logo;else{const[H,W,re]=await Promise.all([Tt.readContract(N,{address:D.address,abi:j.erc20Abi,functionName:"decimals"}).catch(()=>18),Tt.readContract(N,{address:D.address,abi:j.erc20Abi,functionName:"symbol"}).catch(()=>"TOKEN"),Tt.readContract(N,{address:D.address,abi:j.erc20Abi,functionName:"name"}).catch(()=>"TOKEN")]);z=Number(H),O=W,U=re}const L=h.addressesEqual(D.address,s.address)&&D.chainId===s.chainId;L&&s.logoURI&&(Y=s.logoURI),L&&!D.configToken&&O==="TOKEN"&&(O=s.symbol,U=s.symbol);const ne=parseFloat((Number(q)/Math.pow(10,z)).toFixed(6));return{address:D.address,name:U,symbol:O,decimals:z,balance:q,balanceFormatted:ne,balanceUsd:0,logoURI:Y,isNative:!1,chainId:D.chainId}}catch{return null}},B=await Promise.all(Array.from(v.entries()).map(async([N,D])=>{let q;try{q=h.getClientForChain(N)}catch{return[]}const z=[],O=[];for(const Y of D){const L=z.length;z.push({address:Y.address,abi:j.erc20Abi,functionName:"balanceOf",args:[F]}),Y.configToken||z.push({address:Y.address,abi:j.erc20Abi,functionName:"decimals"},{address:Y.address,abi:j.erc20Abi,functionName:"symbol"},{address:Y.address,abi:j.erc20Abi,functionName:"name"}),O.push({start:L,item:Y})}let U=null;try{U=await q.multicall({contracts:z})}catch{U=null}return U?O.map(({start:Y,item:L})=>{const ne=U[Y],H=ne?.status==="success"?ne.result:0n;let W,re,ee,ie;if(L.configToken)W=L.configToken.decimals,re=L.configToken.symbol,ee=L.configToken.name,ie=L.configToken.logo;else{const X=U[Y+1],ue=U[Y+2],xe=U[Y+3];W=X?.status==="success"?Number(X.result):18,re=ue?.status==="success"?ue.result:"TOKEN",ee=xe?.status==="success"?xe.result:re}const we=h.addressesEqual(L.address,s.address)&&L.chainId===s.chainId;we&&s.logoURI&&(ie=s.logoURI),we&&!L.configToken&&re==="TOKEN"&&(re=s.symbol,ee=s.symbol);const Ae=parseFloat((Number(H)/Math.pow(10,W)).toFixed(6));return{address:L.address,name:ee,symbol:re,decimals:W,balance:H,balanceFormatted:Ae,balanceUsd:0,logoURI:ie,isNative:!1,chainId:L.chainId}}):(await Promise.all(D.map(Y=>M(q,Y)))).filter(Y=>Y!==null)}));A===b.current&&w(B.flat())},[a,m,y,k,i,s.address,s.chainId,s.symbol,s.logoURI]);l.useEffect(()=>{if(!a){w([]);return}S();const A=setInterval(()=>{S()},15e3);return()=>clearInterval(A)},[S,a]);const I=l.useCallback(()=>{S()},[S]);return{displayAssets:l.useMemo(()=>{const A=[],F=C.filter(T=>T.balance>0n);for(const T of F)A.push({...T,_source:"wallet"});for(const T of g)A.push({...T,_source:"spice"});const E=s.address.toLowerCase();return A.sort((T,v)=>zo(T,E,s.chainId)-zo(v,E,s.chainId)),A},[C,g,s.address,s.chainId]),filteredSpiceAssets:g,walletAssets:C,embeddedWalletAddress:c||d,externalAddress:u,isNon7702:i,refreshSpiceAssets:p,refreshWalletAssets:I}}async function Lo(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 c=(await h.getClientForChain(a).simulateContract({address:i.quoterV2,abi:R.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:s,amountIn:o,fee:r,sqrtPriceLimitX96:0n}]})).result;if(c[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:c[0],sqrtPriceX96After:c[1],gasEstimate:c[3]}}async function Oo(e){const t=e.feeTiers??[100,500,3e3,1e4],s=await Promise.allSettled(t.map(r=>Lo({...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 Ti=[{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 Mi(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 c=(await h.getClientForChain(a).simulateContract({address:i.quoterV2,abi:Ti,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:s,amount:o,fee:r,sqrtPriceLimitX96:0n}]})).result;if(c[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:c[0],sqrtPriceX96After:c[1],gasEstimate:c[3]}}async function Ri(e){const t=e.feeTiers??[100,500,3e3,1e4],s=await Promise.allSettled(t.map(r=>Mi({...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 Ho(e){return e.type==="swap"}const Ms=.02,Di=[1,8453,42161,10,137,43114,56],Ni="https://api.1inch.dev/swap/v6.0";function Qo(e,t){return R.applySlippage(e,t)}function Vo(e){const t=e?.baseUrl??Ni;return{name:"1inch",chainIds:e?.chainIds??Di,resolve:async(s,o,r)=>{const a=s.maxSlippage??Ms,i=a*100,c=R.isNativeToken(s.tokenIn)?R.NATIVE_TOKEN_ADDRESS:s.tokenIn,u=R.isNativeToken(s.tokenOut)?R.NATIVE_TOKEN_ADDRESS:s.tokenOut,d=R.isNativeToken(s.tokenIn);try{const f=new URL(`${t}/${o}/swap`);f.searchParams.set("src",c),f.searchParams.set("dst",u),f.searchParams.set("amount",s.amountIn.toString()),f.searchParams.set("from",r),f.searchParams.set("slippage",i.toString()),f.searchParams.set("disableEstimate","true"),f.searchParams.set("allowPartialFill","false");const p={Accept:"application/json"};e?.apiKey&&(p.Authorization=`Bearer ${e.apiKey}`);const g=await fetch(f.toString(),{headers:p});if(!g.ok)throw new h.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${g.status} for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}`,{venue:"1inch",chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn.toString(),cause:`HTTP ${g.status}`});const m=await g.json();if(!m.dstAmount||!m.tx)return console.warn(`[1inchVenue] No route data for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}`),null;const x=BigInt(m.dstAmount);if(x<=0n)return console.warn(`[1inchVenue] Zero output for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}`),null;const y=Qo(x,a),k=[];return m.tx.to&&!d&&k.push({to:s.tokenIn,value:0n,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"approve",args:[m.tx.to,s.amountIn]})}),k.push({to:m.tx.to,value:BigInt(m.tx.value||"0"),data:m.tx.data}),{venue:"1inch",amountOut:x,amountOutMinimum:y,calls:k}}catch(f){if(f instanceof h.SpiceflowError)throw f;const p=f instanceof Error?f.message:String(f);throw new h.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 qo=[4114,5115],Rs={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425"},Yo={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453]};function Zo(e){return{name:"satsuma",chainIds:e.chainIds??qo,resolve:async(t,s,o)=>{const r=t.maxSlippage??Ms,a=R.isNativeToken(t.tokenIn);let i;try{i=await Oo({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 c=Qo(i.amountOut,r),u=[];return a||u.push({to:t.tokenIn,value:0n,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),u.push({to:e.swapRouter,value:a?t.amountIn:0n,data:j.encodeFunctionData({abi:R.uniV3SwapRouterAbi,functionName:"exactInputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:i.fee,recipient:o,amountIn:t.amountIn,amountOutMinimum:c,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:i.amountOut,amountOutMinimum:c,calls:u}}}}function Ko(e){return{name:"satsuma",chainIds:e.chainIds??qo,resolve:async(t,s,o)=>{const r=t.maxSlippage??Ms,a=R.isNativeToken(t.tokenIn);let i;try{i=await Ri({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 c=BigInt(Math.round(r*1e4)),u=i.amountIn+i.amountIn*c/10000n,d=[];return d.push({to:e.swapRouter,value:a?u:0n,data:j.encodeFunctionData({abi:Wi,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:d}}}}const Wi=[{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 Xo(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(Zo(e.satsuma)),t.push(Vo(e?.oneInch));function s(r){return t.find(a=>a.chainIds.includes(r))}async function o(r,a,i){const c=[],u=[];for(const d of r){if(!Ho(d)){c.push(d);continue}const f=s(a);if(!f)throw new h.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${a}. Cannot resolve swap ${d.tokenIn} \u2192 ${d.tokenOut}.`,{chainId:a,tokenIn:d.tokenIn,tokenOut:d.tokenOut,amountIn:d.amountIn.toString()});const p=await f.resolve(d,a,i);if(!p)throw new h.SpiceflowError("NO_LIQUIDITY",`${f.name} returned no quote for ${d.tokenIn} \u2192 ${d.tokenOut} on chain ${a}.`,{venue:f.name,chainId:a,tokenIn:d.tokenIn,tokenOut:d.tokenOut,amountIn:d.amountIn.toString()});c.push(...p.calls),u.push(p)}return{calls:c,resolvedSwaps:u}}return{resolveSwapIntents:o,getVenueForChain:s,venues:t}}function Pi(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 h.SpiceflowError("NO_SWAP_ROUTE",`No exact-output venue supports chain ${r}`,{chainId:r,tokenIn:o.tokenIn,tokenOut:o.tokenOut});const c=(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(c.length===0)throw new h.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 c.sort((u,d)=>u.amountIn<d.amountIn?-1:u.amountIn>d.amountIn?1:0),c[0]}return{getQuote:s,venues:t}}const Ui=Xo({satsuma:Rs});function zi(e){const{direction:t,selectedAsset:s,destinationToken:o,chainId:r,recipient:a,paymentAmount:i}=e,[c,u]=l.useState(!1),[d,f]=l.useState(null),[p,g]=l.useState(null),[m,x]=l.useState(null),[y,k]=l.useState(null),[C,w]=l.useState(null),[b,S]=l.useState(null),[I,A]=l.useState(null),[F,E]=l.useState(null),T=l.useRef(null),v=l.useRef(0),M=l.useRef(new Map),B=l.useMemo(()=>Ui,[]),N=l.useMemo(()=>Pi({customVenues:[Ko(Rs),Ko(Yo)]}),[]),D=l.useMemo(()=>{if(!s?.asset)return null;const W=on(s.asset,r);if(W)return W;const re=ln(s.asset.address,r,s.asset.chainId);return re?re.address:null},[s?.asset,r]),q=l.useMemo(()=>s?.asset?Vn(s.asset,r):[],[s?.asset,r]);l.useEffect(()=>{let W=!1;if(!s?.asset||q.length<=1){E(null);return}return(async()=>{const re=t==="input"?s.amount:i||"0";let ee=0n;try{ee=t==="input"?j.parseUnits(re,s.asset.decimals):0n}catch{ee=0n}try{const ie=await mo(s.asset,r,{requiredAmount:ee});W||E(ie)}catch{W||E(null)}})(),()=>{W=!0}},[s?.asset,s?.amount,r,q,t,i]);const z=l.useMemo(()=>F??D,[F,D]),O=l.useMemo(()=>!s?.asset||!z?[]:[z,...q.filter(W=>W.toLowerCase()!==z.toLowerCase())],[s?.asset,z,q]),U=l.useMemo(()=>!s?.asset||!qn(s.asset.address,s.asset.chainId,o.address,o.chainId)||!z?!1:h.addressesEqual(z,o.address),[s,o.address,o.chainId,z]),Y=z?h.addressesEqual(z,o.address):!1,L=t==="output"&&parseFloat(i||"0")===0,ne=!!s?.asset&&!U&&!Y&&!L,H=ne?I??z:z;return l.useEffect(()=>{T.current&&clearTimeout(T.current);const W=t==="input"?s?.amount:i,re=parseFloat(W||"0");if(!ne||!Number.isFinite(re)||re<=0||!s?.asset||!a||O.length===0){v.current++,g(null),x(null),k(null),w(null),S(null),A(null),f(null),u(!1);return}const ee=s.asset.decimals;let ie;try{ie=t==="input"?j.parseUnits(s.amount,ee):j.parseUnits(i||"0",o.decimals)}catch{v.current++,f("Invalid amount"),u(!1);return}const we=++v.current,Ae=()=>we!==v.current;u(!0);const X=t==="output"?150:400;return T.current=setTimeout(async()=>{try{if(t==="input"){const ue=B.getVenueForChain(r);if(!ue)throw new Error("No swap venue for this chain");let xe=null,Z=null;for(const V of O){const te=`${t}:${r}:${V.toLowerCase()}:${o.address.toLowerCase()}:${ie.toString()}`,Ce=M.current.get(te);if(Ce&&Ce.expiresAt>Date.now()&&Ce.resolvedSwap){xe=Ce.resolvedSwap,Z=V;break}const se=await ue.resolve({type:"swap",tokenIn:V,tokenOut:o.address,amountIn:ie},r,a);if(Ae())return;if(se){M.current.set(te,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:se}),xe=se,Z=V;break}}if(!xe||!Z)throw new Error("No liquidity for this pair");A(Z),S(xe.amountOut),k(xe),w(null);const ce=parseFloat(j.formatUnits(xe.amountOut,o.decimals));g(ce<.01?ce.toPrecision(4):ce.toLocaleString(void 0,{maximumFractionDigits:6})),x(null),f(null)}else{let ue=null,xe=null;for(const Z of O){const ce=`${t}:${r}:${Z.toLowerCase()}:${o.address.toLowerCase()}:${ie.toString()}`,V=M.current.get(ce);if(V&&V.expiresAt>Date.now()&&V.exactOutputSwap){ue=V.exactOutputSwap,xe=Z;break}try{const te=await N.getQuote({tokenIn:Z,tokenOut:o.address,amountOut:ie},r,a);if(Ae())return;M.current.set(ce,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:te}),ue=te,xe=Z;break}catch{if(Ae())return}}if(!ue||!xe)throw new Error("No liquidity for this pair");A(xe),w(ue),k(null),S(null),x(parseFloat(j.formatUnits(ue.amountIn,ee)).toFixed(6)),g(null),f(null)}}catch(ue){if(Ae())return;const xe=ue instanceof Error?ue.message:"Failed to get quote";f(xe),g(null),x(null),k(null),w(null),S(null),A(null)}finally{Ae()||u(!1)}},X),()=>{T.current&&clearTimeout(T.current)}},[t,ne,s?.amount,s?.asset?.address,s?.asset?.decimals,i,O,r,o.address,o.decimals,a,B,N]),{isQuoting:c,quoteError:d,estimatedOutput:p,estimatedInput:m,resolvedSwap:y,exactOutputSwap:C,quoteAmountOut:b,resolvedTokenIn:H,isDirect:Y,needsSwap:ne,selectedIsEquivalent:U}}const Go={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},Jo=["signing-delegation","signing-intent","submitting","executing"],$o=({isOpen:e,onClose:t,closeOnBackdropClick:s=!1,destinationToken:o,buildActionCalls:r,feeExecutionMode:a="user-transfer",buildSpicenetBatch:i,onPayExecute:c,actionLabel:u,amountDirection:d="input",swapDescription:f,directDescription:p,paymentAmount:g,amountInputMode:m="fixed",minPaymentAmount:x,maxPaymentAmount:y,onAmountChange:k,styles:C,dark:w,title:b,subtitle:S,onAddFunds:I,onSuccess:A,onError:F})=>{const E=d==="output",{theme:T,dark:v,primaryColor:M,dk:B,palette:N,fontFamily:D,monoFont:q,inputDark:z,cardBg:O,cardBorder:U,textPrimary:Y,textSecondary:L,subtitleText:ne}=h.useSpiceBrand(C,w),H=z?{...T,colors:{...T.colors,secondary:B.cardBg,surfaceHover:B.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:T,W=o.chainId,re=l.useContext(h.SpiceFlowProviderContext),ee=(re?.mode||"7702")!=="7702",ie=l.useMemo(()=>re?.supportedChainIds??[],[re?.supportedChainIds]),we=l.useMemo(()=>{const me=re?.allowedTokens;if(!me||me.length===0)return;const Ne=new Set(me.map(Dt=>Dt.toLowerCase())),Bt=[],qt=new Set;for(const Dt of ie){const Yt=h.getChainConfig(Dt);for(const Xt of Yt?.supportedTokens??[]){if(!Ne.has(Xt.symbol.toLowerCase()))continue;const ve=Xt.address.toLowerCase();qt.has(ve)||(qt.add(ve),Bt.push(Xt.address))}}return Bt},[re?.allowedTokens,ie]),Ae=Jt(),{address:X,isConnected:ue,isReady:xe,isAuthenticated:Z,provider:ce}=Ae,{executeGasless:V,estimateGasless:te}=Kn(),{externalWallet:Ce,externalAddress:se,embeddedAddress:P}=Rn(),{displayAssets:ae,filteredSpiceAssets:ye,embeddedWalletAddress:Fe,refreshSpiceAssets:Be,refreshWalletAssets:de}=Bi({address:X,destinationToken:o,supportedSourceAssets:we,sourceChains:ie,enabled:e&&(ee?!!se:!!X)}),Le=E||ee?ae:ye,[G,Ue]=l.useState(null),[ge,Je]=l.useState(g||""),[Se,rt]=l.useState(!1),[jt,pt]=l.useState(null),[Te,at]=l.useState("idle"),[wt,kt]=l.useState(""),[Rt,Pt]=l.useState(null),[cn,ht]=l.useState(!1),[Ee,vt]=l.useState(null),[_e,mt]=l.useState(null),[et,tt]=l.useState(!1),[Ht,st]=l.useState(!1),[pe,Ye]=l.useState(null),Ut=l.useRef(G),lt=l.useRef(!1),ke=l.useRef(null),gt=l.useRef(0),nt=l.useRef(null);l.useEffect(()=>{Ut.current=G},[G]);const Oe=m==="adjustable"?ge:g||"0",Kt=Fe||P||X,{isQuoting:xt,quoteError:zt,estimatedOutput:Qt,resolvedSwap:He,exactOutputSwap:je,quoteAmountOut:it,resolvedTokenIn:$e,isDirect:Ze,needsSwap:Ke,selectedIsEquivalent:St}=zi({direction:d,selectedAsset:G,destinationToken:o,chainId:W,recipient:Kt,paymentAmount:Oe}),ot=E?parseFloat(Oe||"0"):parseFloat(G?.amount||"")||0,ct=l.useMemo(()=>G?.asset?ye.find(me=>h.addressesEqual(me.address,G.asset.address))?.balanceFormatted??0:0,[G,ye]),yt=l.useMemo(()=>G?.asset?E?_e?_n(_e.grossAmount,_e.decimals,G.asset.decimals)>G.asset.balance:St||Ze?ot>G.asset.balanceFormatted:je?parseFloat(j.formatUnits(je.amountInMax,G.asset.decimals))>G.asset.balanceFormatted:!1:_e?parseFloat(j.formatUnits(_n(_e.grossAmount,_e.decimals,G.asset.decimals),G.asset.decimals))>ct:ot>ct:!1,[G,E,_e,St,ot,je,ct,Ze]);l.useEffect(()=>{e||(Ue(null),pt(null),rt(!1),at("idle"),kt(""),Pt(null),ht(!1),vt(null),mt(null),tt(!1),st(!1),Ye(null),lt.current=!1,m==="adjustable"&&Je(g||""),ke.current&&(ke.current.abort(),ke.current=null))},[e]);const It=l.useCallback(me=>{Ue(Ne=>({asset:me,amount:Ne?.asset?.address===me.address&&Ne?.asset?.chainId===me.chainId&&Ne.amount||""})),pt(null),Ye(null),st(!1)},[]),Lt=l.useCallback(me=>{Ue(Ne=>Ne&&{...Ne,amount:me}),pt(null),Ye(null),st(!1)},[]),$t=l.useCallback(me=>{let Ne=me;y&&parseFloat(Ne)>parseFloat(y)&&(Ne=y),Je(Ne),k?.(Ne),pt(null),Ye(null),st(!1)},[y,k]);l.useCallback(me=>{if(lt.current||!X)return;const Ne=Ut.current;!Ne?.asset||!Ne.amount||Ne.asset?._source==="wallet"||j.parseUnits(E?Oe:Ne.amount,Ne.asset.decimals)===0n||(lt.current=!0,Be())},[X,W,Be,E,Oe]);const Re=l.useCallback(me=>{at({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[me.step]||"executing"),kt(me.message),me.txHash&&Pt(me.txHash)},[]),dt=l.useMemo(()=>({currentPaymentAmount:Oe,destinationToken:o,embeddedWalletAddress:Fe,providerEmbeddedAddress:P,address:X,isNon7702:ee,isPayMode:E,resolvedChainId:W,buildActionCalls:r,feeExecutionMode:a,buildSpicenetBatch:i,selectedAsset:G,needsSwap:Ke,resolvedSwap:He,exactOutputSwap:je,quoteAmountOut:it,resolvedTokenIn:$e}),[Oe,o,Fe,P,X,ee,E,W,r,a,i,G,Ke,He,je,it,$e]),Vt=l.useCallback(me=>yi(dt,me),[dt]),Ft=l.useCallback(me=>Ci(dt,me),[dt]),$=l.useCallback((me,Ne,Bt,qt)=>bi(me,Ne,Bt,te,qt),[te]),_=l.useMemo(()=>G?.asset?G.asset.chainId===W?G.asset.address:$e??on(G.asset,W)??o.address:o.address,[G,o.address,W,$e]),be=l.useCallback(()=>Ii(nt.current),[]),Pe=l.useMemo(()=>G?.asset?h.addressesEqual(G.asset.address,o.address)&&G.asset.chainId===o.chainId:!1,[G,o.address,o.chainId]),Qe=E&&ee&&Pe&&ot>0&&!!G?.asset,K=jt,le=l.useMemo(()=>!(!G?.asset||ot<=0),[G,ot,Qe]),De=l.useMemo(()=>!e||Se||Te!=="idle"||!le||Qe||!G?.asset?null:[E?"pay":"supply",d,G.asset.address.toLowerCase(),G.asset.chainId,G.amount,Oe,o.address.toLowerCase(),o.chainId,W,$e?.toLowerCase()??"",Ke?"swap":"direct",Ze?"direct-token":"routed-token",ee?"non7702":"7702",Pe?"source-dest":"cross-chain",xt?"quoting":"quoted",je?.amountIn?.toString()??"",je?.amountInMax?.toString()??"",je?.venue??"",He?.amountOut?.toString()??"",it?.toString()??"",Fe??"",P??"",X??""].join("|"),[e,Se,Te,le,Qe,G,E,d,Oe,o,W,$e,Ke,Ze,ee,Pe,xt,je,He,it,Fe,P,X]),Ie=l.useCallback(()=>Si({selectedAsset:G,isPayMode:E,parsedAmount:ot,needsSwap:Ke,exactOutputSwap:je,isNon7702:ee,isSourceDestToken:Pe,currentPaymentAmount:Oe,destinationToken:o,feeExecutionMode:a,resolvedTokenIn:$e,embeddedWalletAddress:Fe,providerEmbeddedAddress:P,resolvedChainId:W,isConnected:ue,address:X,ready:xe,authenticated:Z,isDirect:Ze,resolvedSwap:He,isQuoting:xt,executionTokenAddress:_,buildPayChainBatches:Vt,buildSupplyChainBatches:Ft,estimateGasless:te,estimateRequiredGrossFunding:$}),[G,E,ot,Ke,je,ee,Pe,Oe,o,a,$e,Fe,P,$,Vt,te,W,ue,X,xe,Z,Ze,He,xt,Ft,_]),Ve=l.useCallback(me=>vi({asset:me,isPayMode:E,isNon7702:ee,needsSwap:Ke,isQuoting:xt,embeddedWalletAddress:Fe,buildSupplyChainBatches:Ft,estimateGasless:te,executionTokenAddress:_,feeExecutionMode:a}),[E,ee,Ke,xt,Fe,Ft,te,_,a]);l.useEffect(()=>{if(!e){tt(!1),st(!1),Ye(null),mt(null);return}if(Se||Te!=="idle"){gt.current+=1,tt(!1);return}if(!le){mt(null),tt(!1),st(!1),Ye(null);return}if(Qe){mt(null),tt(!1),st(!0),Ye(null);return}if(!De)return;let me=!1;const Ne=async()=>{const Dt=++gt.current;Ye(null),tt(!0);try{const Yt=await Ie();if(me||gt.current!==Dt)return;Yt?(mt(Yt),st(!0)):(mt(null),st(!1)),Ye(null)}catch(Yt){if(me||gt.current!==Dt)return;const Xt=h.sanitizeError(Yt,"Unable to calculate fees for this action.");mt(null),st(!1),Ye(Xt)}finally{!me&>.current===Dt&&tt(!1)}},Bt=window.setTimeout(()=>{Ne()},250),qt=window.setInterval(()=>{Ne()},1e4);return()=>{me=!0,clearTimeout(Bt),window.clearInterval(qt),tt(!1)}},[e,Se,Te,Ie,le,Qe,De]);const We=l.useCallback(()=>ji(nt.current),[]);l.useEffect(()=>{!E&&Te==="success"&&Rt&&(Be(),A?.(Rt))},[E,Te,Rt,Be,A]),l.useEffect(()=>{if(!E||Ee?.status!=="success"||lt.current||!X)return;lt.current=!0;const me=Ut.current;!me?.asset||me.asset?._source==="wallet"||Be()},[E,Ee?.status,X,Be]);const ze=l.useRef(A),Ge=l.useRef(F);l.useEffect(()=>{ze.current=A},[A]),l.useEffect(()=>{Ge.current=F},[F]),l.useEffect(()=>{e&&(Be(),de())},[e,Be,de]),l.useEffect(()=>{E&&(Ee?.status==="success"&&ze.current?.(Ee.txHash||""),Ee?.status==="failed"&&Ge.current?.(new Error("Payment execution failed")))},[E,Ee?.status]);const Xe=l.useCallback(()=>{ht(!1),vt(null),Ue(null),lt.current=!1,Be(),de()},[Be,de]);nt.current={selectedAsset:G,parsedAmount:ot,currentPaymentAmount:Oe,isInsufficientBalance:yt,isPayMode:E,isNon7702:ee,isSourceDestToken:Pe,needsSwap:Ke,exactOutputSwap:je,selectedIsEquivalent:St,resolvedTokenIn:$e,embeddedWalletAddress:Fe,providerEmbeddedAddress:P,externalWallet:Ce,externalWalletAddress:se,address:X,isConnected:ue,ready:xe,authenticated:Z,provider:ce,resolvedChainId:W,executionTokenAddress:_,destinationToken:o,buildActionCalls:r,feeExecutionMode:a,buildSpicenetBatch:i,onPayExecute:c,onError:F,gasless:{estimateGasless:te,executeGasless:V,buildPayChainBatches:Vt,buildSupplyChainBatches:Ft,estimateRequiredGrossFunding:$,onProgress:Re},ui:{setError:pt,setStep:at,setStatusMsg:kt,setTxHash:Pt,setIsExecuting:rt,setShowStatusPanel:ht,setPaymentResult:vt},refs:{spiceDepositSubmittedRef:lt,abortControllerRef:ke}};const qe=E&&ot===0,Q=E?!!G?.asset&&ot>=0&&!yt&&!Se&&(qe||Qe||Ht)&&!pe&&(qe||!Ke||!!je):!!G?.asset&&ot>0&&!yt&&!Se&&Ht&&!pe&&(Ze||!!He&&!xt),J=Ze?p||`Your ${o.symbol} will be used directly.`:f||"Your assets will be swapped and used in a single atomic transaction.",he=(W?h.getChainConfig(W):void 0)?.viemChain?.blockExplorers?.default?.url??"",oe=Jo.indexOf(Te),fe=Se?(Go[Te]||"EXECUTING...").toUpperCase():Te==="success"?"DONE":yt?"INSUFFICIENT BALANCE":u.toUpperCase(),Me=l.useMemo(()=>{if(Se)return"PAYING...";if(yt&&G?.asset)return`INSUFFICIENT ${G.asset.symbol}`;if(u)return u.toUpperCase();const me=ot>0?` ${Oe} ${o.symbol}`:"";return Ke?`SWAP & PAY${me}`:`PAY${me}`},[Se,yt,G,u,ot,Oe,o.symbol,Ke]),At=Te==="success"?()=>{at("idle"),Ue(null),Pt(null),Be()}:be,Ot=Te==="success"?!1:!Q;if(!e)return null;const Et=E?b||`Pay ${o.symbol}`:u,Ct=E?S:n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[n.jsx("span",{style:{marginTop:"3px",flexShrink:0},children:n.jsx(ys,{color:ne})}),n.jsx("p",{style:{fontSize:"12px",color:ne,margin:0,lineHeight:"1.4",fontFamily:D},children:J})]});if(E){const me=Ee&&(Ee.status==="success"||Ee.status==="failed")?[{asset:{symbol:G?.asset?.symbol||o.symbol,address:G?.asset?.address||""},amount:Oe,txHash:Ee.txHash||"",success:Ee.status==="success",error:Ee.status==="failed"?Ee.error:void 0}]:void 0;return n.jsx(nn,{isOpen:e,onClose:t,title:Et,subtitle:Ct,styles:C,dark:v,footerLinkText:"Spicenet accounts \u2192",closeOnBackdropClick:s,children:n.jsxs("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[I&&n.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:n.jsx(Cs,{onClick:I,color:M,fontFamily:D})}),n.jsx("div",{style:{marginBottom:"12px"},children:n.jsx(Mn,{assets:Le,selectedAsset:G??void 0,onAssetSelect:It,onAmountChange:()=>{},label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:G?.asset?Ke?xt?"...":je?`~${parseFloat(j.formatUnits(je.amountIn,G.asset.decimals)).toFixed(6)}`:void 0:Oe??void 0:void 0,dark:v,theme:H,styles:C})}),n.jsx(Po,{variant:"pay",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:M,fontFamily:D,textPrimary:Y,textSecondary:L,cardBg:O,cardBorder:U,dk:B,dark:v,isQuoting:xt,quoteError:zt,estimatedOutput:Qt,paymentAmount:Oe,needsSwap:Ke,exactOutputSwap:je,adjustable:m==="adjustable",maxAmount:y,onAmountChange:$t}),le&&n.jsx(Ln,{fontFamily:D,textPrimary:Y,textSecondary:L,cardBg:O,cardBorder:U,resolvedDark:v,darkCardBorder:B.cardBorder,primaryColor:M,feePreview:_e,isLoading:et,errorText:pe,directExecutionFeeNote:Qe}),K&&n.jsx(In,{variant:"error",palette:N,fontFamily:D,style:{marginBottom:"12px"},children:K}),n.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:We,disabled:!Q,loading:Se,dark:v,styles:{...C,button:{...C?.button,backgroundColor:M}},children:Me}),Ee&&cn&&n.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:v?B.shell:"white",borderRadius:v?"12px":"6px",padding:"16px 0"},children:n.jsx(Ss,{type:"payment",isOpen:Ee.status!=="processing",isProcessing:Se||Ee.status==="processing",closeOnComplete:!1,chainName:h.getChainName(W),explorerUrl:h.getExplorerUrl(W,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{ht(!1),vt(null),We()},onNewTx:Xe,onClose:()=>{ht(!1),vt(null)},onComplete:Xe,results:me,styles:C,dark:v})})]})})}return n.jsx(nn,{isOpen:e,onClose:t,title:Et,subtitle:Ct,dark:v,styles:C,theme:T,closeOnBackdropClick:s,children:n.jsxs("div",{style:{padding:"24px 24px 5px 24px",position:"relative"},children:[n.jsx("div",{style:{marginBottom:"16px"},children:n.jsx(Mn,{assets:Le,selectedAsset:G||void 0,onAssetSelect:It,onAmountChange:Lt,disabled:Se||Te==="success",showBalance:!0,showMaxButton:!0,label:"From Spice Balance",placeholder:"0.00",theme:H,styles:C,dark:z,resolveMaxAmount:Ve,maxAmount:ct>0?vn(ct,G?.asset.decimals??o.decimals):void 0})}),G?.asset&&!Ze&&n.jsx(Po,{variant:"supply",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:M,fontFamily:D,textPrimary:Y,textSecondary:L,cardBg:O,cardBorder:U,dark:v,isQuoting:xt,quoteError:zt,estimatedOutput:Qt}),le&&n.jsx(Ln,{fontFamily:D,textPrimary:Y,textSecondary:L,cardBg:O,cardBorder:U,resolvedDark:v,darkCardBorder:B.cardBorder,primaryColor:M,feePreview:_e,isLoading:et,errorText:pe}),Te!=="idle"&&n.jsxs("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:Te==="success"?O:Te==="error"?N.errorBg:O,border:`1px solid ${Te==="success"?U:Te==="error"?N.errorBorder:U}`},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[Te==="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:N.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):Te==="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:N.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):n.jsx(h.Spinner,{size:14,color:M}),n.jsx("span",{style:{fontSize:"13px",fontWeight:500,color:Te==="success"?Y:Te==="error"?N.errorText:Y,fontFamily:D,flex:1},children:Te==="success"?"Deposit confirmed":Te==="error"?wt||"Transaction failed":Go[Te]||wt}),Te==="success"&&Rt&&n.jsx("a",{href:`${he}/tx/${Rt}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:M,fontFamily:D,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),Te==="error"&&n.jsx("button",{onClick:()=>{at("idle"),pt(null),setTimeout(be,50)},style:{background:"none",border:"none",fontSize:"12px",color:M,fontFamily:D,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),oe>=0&&Te!=="success"&&Te!=="error"&&n.jsx("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${L}22`,overflow:"hidden"},children:n.jsx("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:M,transformOrigin:"left center",transform:`scaleX(${(oe+1)/Jo.length})`,transition:"transform 400ms ease"}})})]}),jt&&Te==="idle"&&n.jsx(In,{variant:"error",palette:N,fontFamily:D,style:{marginBottom:"16px"},children:jt}),n.jsx(h.Button,{variant:"outline",fullWidth:!0,disabled:Ot,onClick:At,theme:T,dark:v,styles:{...C,button:{...C?.button,backgroundColor:M}},style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:q},children:fe})]})})},Li=e=>n.jsx($o,{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}),Oi=({label:e="Export Wallet",style:t,className:s,onExport:o,onError:r})=>{const[a,i]=l.useState(!1),[c,u]=l.useState(!1),{primaryColor:d}=h.useSpiceBrand(),f=l.useContext(h.SpiceFlowProviderContext),{isAuthenticated:p}=Jt();let g=null;try{g=Mt.usePrivy()}catch{}let m=null,x=null;try{m=En.useEmbeddedReveal(),x=En.useDynamicContext()}catch{m=null,x=null}const y=en.getDynamicEmbeddedWallet(x),k=l.useCallback(async()=>{if(!p){r?.("User is not authenticated. Please log in first.");return}try{if(f?.provider==="dynamic"){if(!m||!y){r?.("Dynamic is not available. Ensure the app is wrapped in a DynamicContextProvider.");return}await m.initExportProcess(!1),o?.();return}if(!g){r?.("Privy is not available. Ensure the app is wrapped in a PrivyProvider.");return}await g.exportWallet(),o?.()}catch(b){const S=b instanceof Error?b.message:"Failed to export wallet";console.error("Export wallet error:",b),r?.(S)}},[y,m,p,r,o,g,f?.provider]),C=!p,w={padding:"10px 20px",borderRadius:"8px",fontFamily:'"IBM Plex Mono", monospace',fontSize:"14px",fontWeight:500,letterSpacing:"0.4px",textTransform:"uppercase",cursor:C?"not-allowed":"pointer",opacity:C?.5:1,border:"1px solid #0e0d0b",color:"#0e0d0b",backgroundColor:c?`${d}cc`:a?`${d}ee`:d,transition:"background-color 150ms ease, transform 150ms ease",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"8px",...t};return n.jsxs("button",{onClick:k,onMouseEnter:()=>i(!0),onMouseLeave:()=>{i(!1),u(!1)},onMouseDown:()=>u(!0),onMouseUp:()=>u(!1),disabled:C,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 _o(e){const t=l.useContext(h.SpiceFlowProviderContext),s=Gt(),o=e?.enabled===!1?void 0:s,r=t?.network?{network:t.network,pollIntervalMs:e?.pollIntervalMs,chainIds:e?.chainIds??t.supportedChainIds}:void 0;return{...ro(o,r),embeddedWalletAddress:s}}const Hi=({appName:e,status:t,statusLabel:s,totalUsdValue:o,breakdownSubtitle:r,address:a,dk:i,dark:c=!1,showModeToggle:u,isEmbeddedMode:d=!0,onModeToggle:f})=>{const[p,g]=l.useState(!1),m=async()=>{a&&await Er(a)&&(g(!0),setTimeout(()=>g(!1),2e3))},x=t==="active",y=s||(x?"Active":"Inactive"),k=x?"#10b981":"#9ca3af";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("button",{onClick:f,style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:c?i.hoverBg:"#f3f4f6",border:c?`1px solid ${i.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"11px",fontWeight:600,fontFamily:'"IBM Plex Mono", monospace',color:i.textSecondary,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease",letterSpacing:"0.02em"},children:[n.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:d?"#22c55e":"#f59e0b"}}),n.jsx("span",{children:d?"Embedded":"External"})]}):n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:c?i.hoverBg:x?"#ecfdf5":"#f3f4f6",border:c?`1px solid ${i.cardBorder}`:x?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[n.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:k}}),n.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:c?i.textSecondary:x?"#065f46":"#6b7280"},children:y})]})]}),n.jsx("div",{style:{fontSize:"28px",fontWeight:700,color:i.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:wn(o)}),r&&n.jsx("div",{style:{fontSize:"12px",color:i.textSecondary,marginBottom:"8px"},children:r}),a&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[n.jsx("span",{style:{fontSize:"12px",fontFamily:'"IBM Plex Mono", monospace',color:c?i.textSecondary:"#9ca3af"},children:Ar(a)}),n.jsx("button",{onClick:m,style:{padding:"2px 6px",fontSize:"10px",fontWeight:500,backgroundColor:"transparent",color:c?i.textSecondary:"#9ca3af",border:"none",cursor:"pointer",borderRadius:"4px",transition:"background-color 150ms ease, color 150ms ease"},title:"Copy address",children:p?"Copied":"Copy"})]})]})},Qi=({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=h.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}`)})})]}),Vi=({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,c)=>{const u=h.getChainConfig(i.chainId),d=i.chainDisplayName||u?.displayName||`Chain ${i.chainId}`,f=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:f.charAt(0)}),n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:s.textPrimary},children:f}),n.jsx("div",{style:{fontSize:"11px",color:o?s.textSecondary:"#9ca3af"},children:d})]})]}),n.jsxs("div",{style:{textAlign:"right"},children:[n.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:s.textPrimary},children:un(i.balanceFormatted)}),n.jsx("div",{style:{fontSize:"11px",color:o?s.textSecondary:"#9ca3af"},children:wn(i.usdValue)})]})]},`${i.tokenAddress}-${i.chainId}-${c}`)})})]})},qi=({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))})]})},Yi=({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(h.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(h.Button,{variant:"outline",onClick:t,disabled:o,dark:a,styles:{button:{backgroundColor:r}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),Zi=({appName:e,status:t,statusLabel:s,totalUsdValue:o,breakdownSubtitle:r,address:a,spiceAssets:i,spiceAssetsLoading:c,pendingDeposits:u,customSections:d,onDepositClick:f,onWithdrawClick:p,onCompleteDeposit:g,primaryColor:m,dk:x,dark:y=!1,showModeToggle:k,isEmbeddedMode:C,onModeToggle:w,showConnectExternalCta:b,onConnectExternalWallet:S,connectExternalError:I})=>{const[A,F]=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(Hi,{appName:e,status:t,statusLabel:s,totalUsdValue:o,breakdownSubtitle:r,address:a,dk:x,dark:y,showModeToggle:k,isEmbeddedMode:C,onModeToggle:w}),b&&n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[n.jsx("button",{onClick:S,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:m||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:'"Helvetica Neue", sans-serif',transition:"opacity 150ms ease"},children:"Connect External Wallet"}),I&&n.jsx("span",{style:{fontSize:"11px",color:y?x.errorText:"#b91c1c",lineHeight:1.4},children:I})]}),n.jsx("div",{style:{height:"1px",backgroundColor:y?"#2d2d2d":"#e5e7eb"}}),n.jsx(Yi,{onDepositClick:f,onWithdrawClick:p,primaryColor:m,dark:y}),n.jsxs("div",{children:[n.jsxs("button",{onClick:()=>F(!A),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:x.cardBg,border:y?`1px solid ${x.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:x.textSecondary,fontSize:"12px",fontWeight:500},children:[n.jsx("span",{children:"How It Works"}),n.jsx("span",{style:{transform:A?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),A&&n.jsxs("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:y?x.cardBg:"#f0fdf4",border:y?`1px solid ${x.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:y?x.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),n.jsx(Qi,{pendingDeposits:u,onCompleteDeposit:g,dk:x,dark:y}),n.jsx(Vi,{spiceAssets:i,loading:c,dk:x,dark:y}),d.map((E,T)=>n.jsx(qi,{section:E,dk:x,dark:y},T))]})},Ds=380,Cn=8;function er(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function Ki(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 c=s.get(i);if(c!==void 0)return c}return 0}const Xi=({appName:e="Spice",status:t="active",statusLabel:s,customSections:o=[],extraAssets:r=[],tokenPrices:a={},breakdownLabels:i=[],styles:c,dark:u=!1,onDepositSuccess:d,onDepositClick:f,onWithdrawClick:p,onCompleteDeposit:g,showModeToggle:m=!1,defaultMode:x})=>{const y=l.useContext(h.SpiceFlowProviderContext),k=y?.mode!=="7702",C=l.useRef(!1);l.useEffect(()=>{if(!C.current){if(h.hasStoredSpiceFlowMode()){C.current=!0;return}x&&y?.setMode&&(y.setMode(x==="non7702"?"ondemand":"7702"),C.current=!0)}},[y,x]);const[w,b]=l.useState(!1),[S,I]=l.useState(null),[A,F]=l.useState({top:0,bottom:0,left:0,placement:"below"}),E=l.useRef(null),T=l.useRef(null),{address:v,isConnected:M}=Jt(),B=Gt(),{address:N}=ut.useAccount(),{dark:D,primaryColor:q,dk:z}=h.useSpiceBrand(c,u),O=l.useMemo(()=>y?.supportedChainIds??R.getChainIdsByNetwork("mainnet"),[y?.supportedChainIds]),{assets:U,loading:Y}=Dn({address:v,supportedChains:O,enabled:!!v&&!k,refetchInterval:3e4}),L=l.useMemo(()=>[...k?[]:U.map(de=>{const Le=de.balanceUsd||0,G=Number.isFinite(de.balanceFormatted)?de.balanceFormatted:0,Ue=Le>0?Le:Ki(de,a)*G;return{tokenAddress:de.address,tokenSymbol:de.symbol,tokenDisplaySymbol:hs(de),tokenDisplayName:Rr(de),tokenDecimals:de.decimals,chainId:de.chainId,chainDisplayName:ms(de),balance:de.balance.toString(),balanceFormatted:de.balanceFormatted,usdValue:Ue,logoURI:de.logoURI}}),...r].filter(de=>de.balanceFormatted>0),[k,U,a,r]),ne=l.useMemo(()=>L.reduce((de,Le)=>de+Le.usdValue,0),[L]),{pendingDeposits:H}=_o({chainIds:O,enabled:!!v}),W=l.useMemo(()=>o.reduce((de,Le)=>de+Le.totalValue,0),[o]),re=ne+W,ee=l.useMemo(()=>{const de=[];ne>0&&de.push(`${wn(ne)} idle`);for(const Le of o){const G=i.find(Ue=>Ue.sectionTitle===Le.title)?.label||Le.title.toLowerCase();de.push(`${wn(Le.totalValue)} ${G}`)}return de.join(" \xB7 ")},[ne,o,i]),ie=l.useCallback(de=>{g?g(de):I(de)},[g]),we=l.useCallback(()=>{I(null)},[]),Ae=l.useCallback(()=>{I(null),d?.()},[d]),X=l.useCallback(()=>{if(!E.current)return;const de=E.current.getBoundingClientRect(),Le=window.innerHeight-de.bottom-Cn,G=de.top-Cn,Ue=Le>=400||Le>=G?"below":"above",ge=Math.max(Cn,Math.min(de.right-Ds,window.innerWidth-Ds-Cn)),Je=Ue==="below"?de.bottom+Cn:de.top-Cn,Se=Ue==="above"?window.innerHeight-Je:0;F({top:Je,bottom:Se,left:ge,placement:Ue})},[]);l.useLayoutEffect(()=>{w&&X()},[w,X]),l.useEffect(()=>{if(!w)return;const de=Ue=>{E.current&&!E.current.contains(Ue.target)&&T.current&&!T.current.contains(Ue.target)&&b(!1)},Le=Ue=>{Ue.key==="Escape"&&b(!1)},G=()=>X();return document.addEventListener("mousedown",de),document.addEventListener("keydown",Le),window.addEventListener("scroll",G,{passive:!0}),window.addEventListener("resize",X),()=>{document.removeEventListener("mousedown",de),document.removeEventListener("keydown",Le),window.removeEventListener("scroll",G),window.removeEventListener("resize",X)}},[w,X]);const ue=y?.mode==="7702",xe=ue?B||v:N||v,Z=l.useCallback(()=>{y?.setMode&&y.setMode(ue?"ondemand":"7702")},[y,ue]),[ce,V]=l.useState(null);let te=null;try{te=Mt.useConnectWallet({onSuccess:()=>V(null),onError:de=>V(h.sanitizeError(de,"Failed to connect wallet."))}).connectWallet}catch{te=null}const Ce=l.useCallback(()=>{te&&(b(!1),V(null),te({walletChainType:"ethereum-only"}))},[te]),se=m&&!ue&&!N&&!!te,P=l.useCallback(()=>{b(!1),f?.()},[f]),ae=l.useCallback(()=>{b(!1),p?.()},[p]),ye=l.useCallback(de=>{b(!1),ie(de)},[ie]);if(typeof window>"u")return null;const Fe=n.jsxs("button",{ref:E,onClick:()=>b(!w),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:D?z.hoverBg:"#ffffff",border:D?`1px solid ${z.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:'"Helvetica Neue", sans-serif',color:D?z.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:D?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[n.jsx("span",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:q,flexShrink:0}}),n.jsxs("span",{children:[e," Account"]}),M&&n.jsxs("span",{style:{color:D?z.textSecondary:"#6b7280"},children:["\xB7 ",wn(re)]}),n.jsx("span",{style:{fontSize:"10px",color:D?z.textSecondary:"#9ca3af",transform:w?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),Be=w?jn.createPortal(n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:hn.popover},onClick:()=>b(!1)}),n.jsx("div",{ref:T,style:{position:"fixed",top:A.placement==="below"?`${A.top}px`:"auto",bottom:A.placement==="above"?`${A.bottom}px`:"auto",left:`${A.left}px`,width:`${Ds}px`,maxWidth:`calc(100vw - ${Cn*2}px)`,maxHeight:"80vh",backgroundColor:D?z.shell:"#ffffff",border:D?`1px solid ${z.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:D?"0 10px 40px rgba(0, 0, 0, 0.5)":"0 10px 40px rgba(0, 0, 0, 0.12)",zIndex:hn.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${bt.out}`},children:n.jsx(Zi,{appName:e,status:t,statusLabel:s,totalUsdValue:re,breakdownSubtitle:ee,address:m?xe:v,spiceAssets:L,spiceAssetsLoading:Y,pendingDeposits:H,customSections:o,onDepositClick:f?P:void 0,onWithdrawClick:p?ae:void 0,onCompleteDeposit:ye,primaryColor:q,dk:z,dark:D,showModeToggle:m,isEmbeddedMode:ue,onModeToggle:Z,showConnectExternalCta:se,onConnectExternalWallet:Ce,connectExternalError:ce})}),n.jsx("style",{children:`
|
|
104
104
|
@keyframes accountDisplayFadeIn {
|
|
105
105
|
from { opacity: 0; transform: translateY(-4px); }
|
|
106
106
|
to { opacity: 1; transform: translateY(0); }
|
package/dist/index.js
CHANGED
|
@@ -100,7 +100,7 @@ import{jsxs as g,jsx as a,Fragment as ln}from"react/jsx-runtime";import dn,{useS
|
|
|
100
100
|
from { transform: rotate(0deg); }
|
|
101
101
|
to { transform: rotate(360deg); }
|
|
102
102
|
}
|
|
103
|
-
`})]})},Ml="0xa9059cbb";function Rl(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const o=Re(n.token),s=Re(n.to),r=`${o.toLowerCase()}:${s.toLowerCase()}`,i=t.get(r);i?i.amount+=n.amount:t.set(r,{token:o,to:s,amount:n.amount})}return[...t.values()]}function Dl(e,t){return`0x${t}${e.slice(4)}`}function Wl(e,t,n){if(!Array.isArray(e))return 0n;const o=`evm:${t}:${n.slice(2).toLowerCase()}`;let s=0n;for(const r of e){if(!r||typeof r!="object")continue;const i=r,l=i.chainTokens;if((Array.isArray(l)?l.filter(c=>typeof c=="string"):l&&typeof l=="object"?Object.keys(l):[]).some(c=>c.toLowerCase()===o))try{s+=BigInt(i.balanceAvailable??"0")}catch{}}return s}async function zr(e,t,n,o){const s=await fetch(`${e}/wallets/${t}/balance`,{cache:"no-store"});if(!s.ok)throw new Error(`Failed to fetch spice balance: ${s.status}`);const r=await s.json();return Wl(r?.balances,n,o)}async function Nl({apiBaseUrl:e,user:t,chainId:n,tokenAddress:o,prevBalance:s,timeoutMs:r=3e4,pollIntervalMs:i=1500}){const l=Date.now()+r;for(await new Promise(c=>setTimeout(c,800));Date.now()<l;){try{if(await zr(e,t,n,o)>s)return}catch(c){console.warn("[SpiceLockModal] spice balance poll failed:",c?.message)}await new Promise(c=>setTimeout(c,i))}console.warn("[SpiceLockModal] Spicenet indexer did not reflect deposit within timeout; proceeding with intent")}function Es(e,t){return Lr(e,t)}function Lr(e,t,n){const o=Pl(t,e),s=Math.floor(Date.now()/1e3)+60*10,r=Pn(o);return{user:e,...n?{chainAuthorizations:n}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:"0x00",nbf:0,exp:s,chainBatches:r.map((i,l)=>({hash:i.hash,chainId:i.chainId,tokenTransfers:o[l].domain==="spicenet"?[]:o[l].tokenTransfers??[],calls:i.calls}))}]}}function Pl(e,t){return e.map(n=>{if(n.domain==="spicenet"||n.calls.length===0)return n;const o=new Set((n.tokenTransfers??[]).filter(r=>(r.from==="escrow"||r.from==="solver")&&Re(r.to).toLowerCase()===t.toLowerCase()).map(r=>Re(r.token).toLowerCase()));if(o.size===0)return n;let s=0;for(const r of n.calls){if(!r.data?.startsWith(Ml))break;try{const i=xo({abi:Xe,data:r.data});if(i.functionName!=="transfer")break;const[l]=i.args;if(l.toLowerCase()===t.toLowerCase()||!o.has(Re(r.to).toLowerCase()))break;s+=1}catch{break}}return s===0?n:{...n,calls:n.calls.slice(s)}})}function No(e,t,n){if(e.some(c=>c.domain==="spicenet"))return e;const o=n?.intents.flatMap(c=>c.batches),s=c=>c.from==="escrow",r=e.map(c=>{const d=o?.find(y=>y.chainId===c.chainId);if(!d)return c;const p=Mn(d).totalFee;if(p<=0n)return c;const u=(c.tokenTransfers??[]).find(y=>s(y)&&Re(y.to).toLowerCase()===t.toLowerCase()&&!Qe(Re(y.token)));if(!u)return c;const f=Re(u.token);let h=!1;const m=(c.tokenTransfers??[]).map(y=>h||!s(y)||Re(y.to).toLowerCase()!==t.toLowerCase()||Re(y.token).toLowerCase()!==f.toLowerCase()?y:(h=!0,{...y,amount:BigInt(y.amount)+p}));return h?{...c,tokenTransfers:m,calls:[{to:f,value:0n,data:gt({abi:Xe,functionName:"transfer",args:[Yn,p]})},...c.calls]}:c}),i=r.flatMap(c=>(c.tokenTransfers??[]).filter(s).map(d=>{const p=Re(d.token),u=Re(d.to),f=[{token:p,to:u,amount:BigInt(d.amount)}];return{chainId:c.chainId,transfers:Rl(f)}}));if(i.length===0)return e;const l=BigInt(Math.floor(Date.now()/1e3))+3600n;return[{chainId:Ta,domain:"spicenet",tokenTransfers:[],calls:i.map((c,d)=>{const p=so(ro([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,c.transfers[0].token,c.transfers.reduce((f,h)=>f+h.amount,0n),BigInt(c.chainId),BigInt(Date.now()+d)])),u=Dl(p,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:gt({abi:Go,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${c.chainId}`,idempotenceKey:u,nbf:0n,exp:l,metadata:"{}",transfers:c.transfers.map(f=>({token:f.token.toLowerCase(),to:f.to,amount:f.amount}))}]})}})},...r]}function Po(e,t){const n=e.selectedAsset?.asset;if(!n||!e.selectedAsset?.amount)throw new Error("Select an asset and enter an amount");const o=t?.netAmount??Ge(e.selectedAsset.amount,n.decimals),s=t?.grossAmount??o;return e.resolveLockBatches({amount:xt(o,n.decimals),amountWei:o,grossAmount:xt(s,n.decimals),grossAmountWei:s})}async function Or(e,t,n){const o=[...new Set(n.filter(r=>r.domain!=="spicenet").map(r=>r.chainId))],s=[];for(const r of o){const i=dt(r),l=oo(r),c=await Xo(t,i),d=await e.actions.signAuthorization({contractAddress:l,chainId:r,nonce:Number(c)});s.push(d)}return s}async function Hr(e,t,n){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 s=n??await Or(e,o,t),r=Pn(t),i=Math.floor(Date.now()/1e3)+60*10,l=r.map(h=>h.hash),c=so(ro([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,BigInt(i),l])),d=await e.actions.signMessage({raw:c}),p=typeof d=="string"?d:d.signature;if(!p)throw new Error("Failed to sign intent authorization");const u={mode:"7702",signatureType:"ecdsa",signature:p,nbf:0,exp:i,chainBatches:r.map((h,m)=>{const y=t[m],C=y.domain==="spicenet";return{hash:h.hash,chainId:h.chainId,tokenTransfers:C?[]:y.tokenTransfers??[],calls:h.calls}})},f=await ft.createAction({user:o,chainAuthorizations:s.map(h=>({r:h.r,s:h.s,yParity:h.yParity,address:h.address,chainId:Number(h.chainId),nonce:Number(h.nonce)})),intents:[u]});if(f){const h=Vo(t,$t),[m,y]=f.intentIds[0].split("/"),C=parseInt(y||"0",10),x=f.intentIds[0];e.startStatusPolling(f.intentIds[0],h),await Ir({actionId:m,intentIndex:C,intentId:x,totalSteps:t.length,isSpicenetStep:w=>t[w]?.domain==="spicenet",maxExecuteAttemptsForStep:w=>t[w]?.domain==="spicenet"?6:3,maxPolls:180})}}async function jr(e){let t=Po(e);if(t.length===0)throw new Error("No lock batches configured");const n=e.isSemi7702&&e.providerEmbeddedAddress||e.address;if(!e.isConnected||!n)throw new Error("Please connect your wallet to continue");const o=await Or(e,n,t);let s=No([...t],n),r;for(let i=0;i<4;i+=1){const l=await ft.estimateActionFees(Lr(n,s,o.map(u=>({r:u.r,s:u.s,yParity:u.yParity,address:u.address,chainId:Number(u.chainId),nonce:Number(u.nonce)})))),c=Wo(l,{symbol:e.selectedAsset?.asset.symbol??"",decimals:e.selectedAsset?.asset.decimals??18});if(!c)break;const d={grossAmount:c.grossAmount,netAmount:c.netAmount,feeAmount:c.totalFee??0n},p=r?.grossAmount===d.grossAmount&&r?.netAmount===d.netAmount&&r?.feeAmount===d.feeAmount;if(r=d,t=Po(e,r),s=No([...t],n,l),p)break}await Hr(e,s,o)}async function Ul(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,n=Ge(e.selectedAsset.amount,t.decimals),o=e.escrowAddress||oo(e.lockChainId),s=ft.getBaseUrl(),r=It(t.address);let i=0n;try{i=await zr(s,e.embeddedWalletAddress,e.lockChainId,r)}catch(u){console.warn("[SpiceLockModal] could not snapshot spice balance pre-deposit:",u?.message)}const l=await e.actions.getEthereumProvider();await Qn(l,e.lockChainId);const c=Me(e.lockChainId),d=Un({account:e.embeddedWalletAddress,transport:zn(l),chain:c?.viemChain});let p;if(t.isNative||Qe(t.address))p=await d.sendTransaction({to:o,value:n,chain:c?.viemChain});else{const u=gt({abi:Xe,functionName:"transfer",args:[o,n]});p=await d.sendTransaction({to:t.address,data:u,chain:c?.viemChain})}if((await dt(e.lockChainId).waitForTransactionReceipt({hash:p,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to escrow failed");await Nl({apiBaseUrl:s,user:e.embeddedWalletAddress,chainId:e.lockChainId,tokenAddress:r,prevBalance:i}),await e.refreshSpiceAssets(),e.refreshWalletAssets(),await jr(e)}async function zl(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 w=e.resolveLockBatches();if(w.length===0)throw new Error("No lock batches configured");const b=e.selectedAsset.asset,k=Ge(e.selectedAsset.amount,b.decimals),I=await e.onLockExecute({asset:b,amount:e.selectedAsset.amount,amountWei:k,lockDurationMonths:e.selectedDuration?.months??0,chainBatches:w});I&&e.onLockSuccess?.(I);return}const n=e.resolveLockBatches();if(n.length===0)throw new Error("No lock batches configured");const o=e.selectedAsset.asset,s=Ge(e.selectedAsset.amount,o.decimals),r=o.chainId,i=e.escrowAddress||Cn(r),l=It(o.address),c=o.isNative||Qe(l);let d=null;for(const w of n){const b=w.tokenTransfers?.find(k=>k.from==="escrow");if(b){d={batch:w,to:b.to,token:b.token,amount:BigInt(b.amount)};break}}const p=await e.externalWallet.getEthereumProvider();let u=null;try{const w=await p.request({method:"eth_chainId"});u=parseInt(w,16)}catch{u=null}u!==r&&await Qn(p,r);const f=Me(r),h=Un({account:e.externalWalletAddress,chain:f?.viemChain,transport:zn(p)}),m=c?await h.sendTransaction({to:t,value:s,chain:f?.viemChain}):await h.sendTransaction({to:l,data:gt({abi:Xe,functionName:"transfer",args:[t,s]}),chain:f?.viemChain});if((await dt(r).waitForTransactionReceipt({hash:m,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to embedded wallet failed");const y={chainId:r,calls:c?[{to:i,value:s,data:"0x"}]:[{to:l,value:0n,data:gt({abi:Xe,functionName:"transfer",args:[i,s]})}]};let C=null;if(d){if(!e.buildSpicenetBatch)throw new Error("Lock batches declare an escrow-backed ERC20 payout but no `buildSpicenetBatch` callback was provided. The relayer rejects 7702 intents with escrow-backed ERC20 transfers unless the intent includes a Spicenet batch authorising the withdrawal.");const w=e.buildSpicenetBatch({userAddress:t,destinationChainId:d.batch.chainId,deliveryToken:d.token,deliveryAmount:d.amount,deliveryRecipient:d.to});w&&(C={...w,domain:w.domain??"spicenet"})}const x=[y];C&&x.push(C),x.push(...n),await Hr(e,x)}async function Ll(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");const l=e.resolveLockBatches();if(l.length===0)throw new Error("No lock batches configured");const c=e.selectedAsset.asset,d=Ge(e.selectedAsset.amount,c.decimals),p=c.chainId,u=e.escrowAddress||Cn(p),f=It(c.address),h=c.isNative||Qe(f);let m=null;for(const b of l){const k=b.tokenTransfers?.find(I=>I.from==="escrow");if(k){m={batch:b,to:k.to,token:k.token,amount:BigInt(k.amount)};break}}const y={chainId:p,calls:h?[{to:u,value:d,data:"0x"}]:[{to:f,value:0n,data:gt({abi:Xe,functionName:"transfer",args:[u,d]})}]};let C=null;if(m){if(!e.buildSpicenetBatch)throw new Error("Lock batches declare an escrow-backed payout but no `buildSpicenetBatch` callback was provided.");const b=e.buildSpicenetBatch({userAddress:i,destinationChainId:m.batch.chainId,deliveryToken:m.token,deliveryAmount:m.amount,deliveryRecipient:m.to});b&&(C={...b,domain:b.domain??"spicenet"})}const x=[y];C&&x.push(C),x.push(...l);const w=await ft.estimateActionFees(Es(i,x));return Wo(w,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals})}const t=e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");let n=Po(e);if(n.length===0)throw new Error("No lock batches configured");let o=No([...n],t),s=null;for(let i=0;i<4;i+=1){const l=await ft.estimateActionFees(Es(t,o)),c=Wo(l,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals});if(!c)return null;const d={grossAmount:c.grossAmount,netAmount:c.netAmount},p=s?.grossAmount===c.grossAmount&&s?.netAmount===c.netAmount&&s?.totalFee===c.totalFee;if(s=c,n=Po(e,d),o=No([...n],t,l),p)break}if(s)return s;const r=await ft.estimateActionFees(Es(t,o));return Wo(r,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals})}async function Ol(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.resolveLockBatches();if(t.length===0)throw new Error("No lock batches configured");const n=t.find(d=>d.chainId===e.lockChainId)||t[0];if(!n)throw new Error("No lock batch for lock chain");const o=await e.externalWallet.getEthereumProvider();let s=null;try{const d=await o.request({method:"eth_chainId"});s=parseInt(d,16)}catch{s=null}s!==e.lockChainId&&await Qn(o,e.lockChainId);const r=Me(e.lockChainId),i=Un({account:e.externalWalletAddress,chain:r?.viemChain,transport:zn(o)}),l=dt(e.lockChainId);let c;for(const d of n.calls){const p=await i.sendTransaction({to:d.to,data:d.data,value:d.value,chain:r?.viemChain});if((await l.waitForTransactionReceipt({hash:p,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Lock transaction failed");c=p}c&&e.onLockSuccess?.(c)}async function Hl(e){if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance. Add more assets.");return}e.ui.setIsExecuting(!0),e.ui.setError(null);const t=n=>{console.error("[SpiceLockModal] lock failed:",n);const o=mn(n,""),s=typeof n?.shortMessage=="string"?n.shortMessage:typeof n?.message=="string"?n.message:"";e.ui.setError(o||s||"Transaction failed. Please try again.")};if(e.isSemi7702){if(e.isSourceDestToken){try{await Ol(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{await zl(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{e.isDirectDeposit&&!e.isSourceDestToken?await Ul(e):await jr(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}}const Qr=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,lockBatches:o,lockTokenSymbol:s,lockTokenLogoURI:r,destinationInputHook:i,sourceAssetInputHook:l,lockDurationHook:c,lockChainId:d,durationOptions:p,votingPowerEstimate:u,escrowAddress:f,includeWalletAssets:h=!1,destinationTokenAddress:m,onLockSuccess:y,onLockExecute:C,sourceToDestinationConversionRate:x,estimatedOutputAmount:w,onAddFunds:b,buildSpicenetBatch:k,styles:I,dark:S=!1})=>{const{theme:E,dark:A,primaryColor:F,dk:v}=at(I,S),M=E.typography.fontFamily,B=Bt(kt),D=(B?.mode||"7702")!=="7702",R=ne(()=>B?.supportedChainIds??[],[B?.supportedChainIds]),Q=ne(()=>{const Y=B?.allowedTokens;if(!Y||Y.length===0)return[];const ce=new Set(Y.map(_e=>_e.toLowerCase())),Le=[],Ee=new Set;for(const _e of R){const He=Me(_e);for(const Ye of He?.supportedTokens??[]){if(!ce.has(Ye.symbol.toLowerCase()))continue;const rt=`${_e}:${Ye.address.toLowerCase()}`;Ee.has(rt)||(Ee.add(rt),Le.push(Re(Ye.address)))}}return Le},[B?.allowedTokens,R]),U=A?v.cardBg:I?.assetSelector?.backgroundColor||I?.secondaryBackground||"#e9e9e9",L=A?`1px solid ${v.cardBorder}`:"0.5px solid #A8A8A7",P=A?"12px":"6px",V=A?v.textPrimary:"#111827",z=A?v.textSecondary:"#6b7280",te=ne(()=>({...I,assetSelector:{...I?.assetSelector,backgroundColor:A?v.cardBg:I?.assetSelector?.backgroundColor,borderRadius:A?"12px":I?.assetSelector?.borderRadius},secondaryBackground:A?v.cardBg:I?.secondaryBackground}),[I,A]),O=ne(()=>A?{...E,colors:{...E.colors,secondary:v.cardBg,surfaceHover:v.hoverBg,border:v.cardBorder,borderHover:v.inputBorder}}:E,[A,E]),[W,re]=T(null),[_,de]=T(0),ke=c?.selectedDurationIdx??_,Be=c?.setSelectedDurationIdx??de,[Z,he]=T(!1),[be,q]=T(null),[ue,j]=T(null),[ee,Ce]=T(!1),[oe,N]=T(!1),[ae,we]=T(null),[De,We]=T(!1),pe=ie(0),[Ke,X]=T(!1),[qe,xe]=T(null);Os(),qo();const{chain:it,address:Ae}=Nn();Sa();const wt=ie(it);K(()=>{wt.current=it},[it]);const qt=kn(),{isReady:Ft,isAuthenticated:Ne,isConnected:Ct,address:zt,provider:Lt,actions:Gt}=qt,{externalWallet:nn,embeddedAddress:Dn,externalAddress:Mt}=uo(),{intentStatus:Fe,startStatusPolling:Ot,clearStatus:ct}=sr({checkStepStatus:(Y,ce)=>ft.checkStepStatus(Y,ce),retryStep:async(Y,ce)=>{const[Le,Ee]=Y.split("/"),_e=parseInt(Ee||"0",10);await ft.executeStep(Le,_e,ce,{action:"execute"})},maxRetries:3}),{assets:Rt,refetch:ut}=po({address:zt,supportedChains:R,enabled:Ct&&!D,refetchInterval:3e4}),pt=ne(()=>{if(Q.length===0)return Rt;const Y=new Set(Q.map(ce=>ce.toLowerCase()));return Rt.filter(ce=>Y.has(ce.address.toLowerCase()))},[Rt,Q]),cn=vn(),mt=D?Ae||Mt:cn,fe=ne(()=>{if(!h)return[];const Y=new Set,ce=[],Le=Ee=>{if(!Ee)return;const _e=Ee.toLowerCase();Y.has(_e)||(Y.add(_e),ce.push(Re(Ee)))};if(m&&Le(m),D)for(const Ee of Q)Le(Ee);return ce},[h,D,m,Q]),tt=ne(()=>fe.map(Y=>Y.toLowerCase()).sort().join(","),[fe]),on=ne(()=>JSON.stringify([...R||[]].sort()),[R]),[St,Ie]=T([]),Dt=ie(0),ht=le(async()=>{if(!h||!mt||fe.length===0){Dt.current++,Ie([]);return}const Y=++Dt.current,ce=Re(mt),Le=R&&R.length>0?R:[d],Ee=fe.map(st=>{const et=st.toLowerCase();for(const H of Le){const G=Me(H)?.supportedTokens?.find(ge=>je(ge.address,et));if(G)return{address:st,chainId:H,configToken:{decimals:G.decimals,symbol:G.symbol,name:G.name,logo:G.logo}}}return{address:st,chainId:d}}),_e=new Map;for(const st of Ee){const et=_e.get(st.chainId)||[];et.push(st),_e.set(st.chainId,et)}const He=async(st,et)=>{try{const H=await yn(st,{address:et.address,abi:Xe,functionName:"balanceOf",args:[ce]});let G,ge,se,me;if(et.configToken)G=et.configToken.decimals,ge=et.configToken.symbol,se=et.configToken.name,me=et.configToken.logo;else{const[an,Vt,Pt]=await Promise.all([yn(st,{address:et.address,abi:Xe,functionName:"decimals",args:[]}).catch(()=>18),yn(st,{address:et.address,abi:Xe,functionName:"symbol",args:[]}).catch(()=>"TOKEN"),yn(st,{address:et.address,abi:Xe,functionName:"name",args:[]}).catch(()=>"TOKEN")]);G=Number(an),ge=Vt,se=Pt}const Pe=!!m&&je(et.address,m)&&et.chainId===d;Pe&&r&&(me=r),Pe&&s&&!et.configToken&&(ge==="TOKEN"&&(ge=s),se==="TOKEN"&&(se=s));const Qt=parseFloat((Number(H)/Math.pow(10,G)).toFixed(6));return{address:et.address,name:se,symbol:ge,decimals:G,balance:H,balanceFormatted:Qt,balanceUsd:0,logoURI:me,isNative:!1,chainId:et.chainId}}catch{return null}},Ye=await Promise.all(Array.from(_e.entries()).map(async([st,et])=>{let H;try{H=dt(st)}catch{return[]}const G=[],ge=[];for(const me of et){const Pe=G.length;G.push({address:me.address,abi:Xe,functionName:"balanceOf",args:[ce]}),me.configToken||G.push({address:me.address,abi:Xe,functionName:"decimals",args:[]},{address:me.address,abi:Xe,functionName:"symbol",args:[]},{address:me.address,abi:Xe,functionName:"name",args:[]}),ge.push({start:Pe,item:me})}let se=null;try{se=await H.multicall({contracts:G})}catch{se=null}return se?ge.map(({start:me,item:Pe})=>{const Qt=se[me],an=Qt?.status==="success"?Qt.result:0n;let Vt,Pt,ye,Oe;if(Pe.configToken)Vt=Pe.configToken.decimals,Pt=Pe.configToken.symbol,ye=Pe.configToken.name,Oe=Pe.configToken.logo;else{const Jt=se[me+1],fn=se[me+2],wn=se[me+3];Vt=Jt?.status==="success"?Number(Jt.result):18,Pt=fn?.status==="success"?fn.result:"TOKEN",ye=wn?.status==="success"?wn.result:Pt}const Kt=!!m&&je(Pe.address,m)&&Pe.chainId===d;Kt&&r&&(Oe=r),Kt&&s&&!Pe.configToken&&(Pt==="TOKEN"&&(Pt=s),ye==="TOKEN"&&(ye=s));const hn=parseFloat((Number(an)/Math.pow(10,Vt)).toFixed(6));return{address:Pe.address,name:ye,symbol:Pt,decimals:Vt,balance:an,balanceFormatted:hn,balanceUsd:0,logoURI:Oe,isNative:!1,chainId:Pe.chainId}}):(await Promise.all(et.map(me=>He(H,me)))).filter(me=>me!==null)}));if(Y!==Dt.current)return;const rt=Ye.flat();Ie(rt)},[h,mt,tt,on,d,m,r,s]);K(()=>{if(!h){Ie([]);return}ht();const Y=setInterval(()=>{ht()},15e3);return()=>clearInterval(Y)},[ht,h]);const Ze=le(()=>{ht()},[ht]),bn=ne(()=>St.filter(Y=>Y.balance>0n),[St]),Wt=ne(()=>{if(D)return bn.map(ce=>({...ce,_source:"wallet"}));if(!h)return pt;const Y=[];for(const ce of bn)Y.push({...ce,_source:"wallet"});for(const ce of pt)Y.push({...ce,_source:"spice"});return Y},[D,h,bn,pt]),sn=ie(null),un=ie(null);K(()=>{un.current=W},[W]),K(()=>{e||(re(null),q(null),j(null),Ce(!1),N(!1),we(null),he(!1),X(!1),xe(null),We(!1),ct())},[e,ct]),K(()=>{i&&i.assetAmount!==(W?.amount||"")&&re(Y=>Y&&{...Y,amount:i.assetAmount})},[i?.assetAmount]),K(()=>{l&&l.assetAmount!==(W?.amount||"")&&re(Y=>Y&&{...Y,amount:l.assetAmount})},[l?.assetAmount]),K(()=>{if(!D&&Fe?.overallStatus==="success"&&Fe.intentId&&sn.current!==Fe.intentId&&zt&&Fe.steps.find(Y=>Y.transactionHash)?.transactionHash){sn.current=Fe.intentId;const Y=un.current;if(!Y?.asset||!Y.amount||Y.asset._source==="wallet"||Ge(Y.amount,Y.asset.decimals)===0n)return;ut()}},[Fe,zt,d,ut,D]);const Je=parseFloat(W?.amount||"")||0,Te=ne(()=>W?.asset?W.asset._source==="wallet"?W.asset.balanceFormatted??0:pt.find(Y=>je(Y.address,W.asset.address)&&Y.chainId===W.asset.chainId)?.balanceFormatted??0:0,[W?.asset,pt]),vt=Je>0&&(ae?parseFloat(xt(ae.grossAmount,ae.decimals))>Te:Je>Te),lt=c?.selectedDuration??p[ke]??p[0],nt=ne(()=>!W?.asset||!m?!1:je(W.asset.address,m)&&W.asset.chainId===d,[W?.asset,m,d]),ot=ne(()=>Je<=0?0:nt?Je:!x||x<=0?0:Je/x,[Je,x,nt]),Ht=ne(()=>ot<=0?null:ot.toLocaleString(void 0,{maximumFractionDigits:2}),[ot]),yt=u&&ot>0&<?u(ot,lt.months):void 0,At=ne(()=>Je<=0?"$0.00":nt&&x?(Je*x).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!x||x<=0?"$0.00":Je.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[Je,x,nt]),Nt=ne(()=>{if(!Ht)return null;const Y=parseFloat(Ht.replace(/,/g,""));return nt&&x?(Y*x).toLocaleString(void 0,{maximumFractionDigits:2}):x?(Y*x).toLocaleString(void 0,{maximumFractionDigits:2}):null},[Ht,x,nt]),jt=le(Y=>{re(ce=>({asset:Y,amount:ce?.asset?.address===Y.address&&ce?.asset?.chainId===Y.chainId&&ce.amount||""})),q(null),j(null),N(!1),we(null),l?.setSelectedAsset&&l.setSelectedAsset({symbol:Y.symbol,address:Y.address,decimals:Y.decimals,chainId:Y.chainId})},[l?.setSelectedAsset]),rn=le(Y=>{re(ce=>ce&&{...ce,amount:Y}),q(null),j(null),N(!1),we(null),i&&i.setAssetAmount(Y),l&&l.setAssetAmount(Y)},[i,l]),In=le(Y=>{if(typeof o=="function"){if(!W?.asset||!W.amount)throw new Error("Select an asset and enter an amount");return o({asset:W.asset,amount:Y?.amount??W.amount,amountWei:Y?.amountWei??Ge(W.amount,W.asset.decimals),grossAmount:Y?.grossAmount,grossAmountWei:Y?.grossAmountWei,feeAdjusted:!!Y})}return o},[o,W]),ze=ie(null),Et=ne(()=>!W?.asset||Je<=0?!1:D?!nt&&!C:!0,[W,Je,D,nt,C]),pn=le(()=>Ll(ze.current),[]);K(()=>{if(!e||Z)return;if(!W?.asset||Je<=0){j(null),Ce(!1),N(!1),we(null);return}if(!Et){j(null),Ce(!1),N(!0),we(null);return}let Y=!1;const ce=async()=>{const _e=++pe.current;j(null),N(!1),Ce(!0);try{const He=await pn();if(Y||pe.current!==_e)return;j(null),N(!0),we(He)}catch(He){if(Y||pe.current!==_e)return;j(mn(He,"Unable to calculate fees for this lock.")),N(!1)}finally{!Y&&pe.current===_e&&Ce(!1)}},Le=window.setTimeout(()=>{ce()},250),Ee=window.setInterval(()=>{ce()},1e4);return()=>{Y=!0,clearTimeout(Le),window.clearInterval(Ee),Ce(!1),N(!1)}},[e,Z,W,Je,Et,pn]),K(()=>{if(Fe?.overallStatus==="success"){const Y=Fe.steps.find(ce=>ce.transactionHash);y?.(Y?.transactionHash)}},[Fe?.overallStatus,y]);const Yt=h&&W?.asset?._source==="wallet"&&W?.asset?.chainId===d,J=le(()=>Hl(ze.current),[]),$=!!W?.asset&&Je>0&&!vt&&!Z&&(!Et||oe&&!ee&&!ue),ve=be||ue,Ve=g("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[a(fs,{color:z}),g("p",{style:{fontSize:"13px",color:z,margin:0,lineHeight:"1.5"},children:["Add ",s," by converting assets from your account"]})]});if(ze.current={selectedAsset:W,parsedAmount:Je,selectedDuration:lt,isInsufficientBalance:vt,isSemi7702:D,isSourceDestToken:nt,isDirectDeposit:Yt,requiresRelayerFeeEstimate:Et,address:zt,embeddedWalletAddress:cn,providerEmbeddedAddress:Dn,externalWallet:nn,externalWalletAddress:Ae,isConnected:Ct,ready:Ft,authenticated:Ne,provider:Lt,actions:Gt,lockChainId:d,escrowAddress:f,onLockExecute:C,onLockSuccess:y,buildSpicenetBatch:k,resolveLockBatches:In,startStatusPolling:Ot,refreshSpiceAssets:ut,refreshWalletAssets:Ze,ui:{setError:q,setIsExecuting:he,setShowStatusPanel:We}},!e)return null;const $e={backgroundColor:U,border:L,borderRadius:P,padding:"16px",marginBottom:"16px"};return a(En,{isOpen:e,onClose:t,title:`Add ${s} to your account`,subtitle:Ve,styles:I,dark:A,footerLinkText:"Spicenet accounts \u2192",overlayContent:Ke?a("div",{}):void 0,closeOnBackdropClick:n,children:g("div",{style:{padding:"0 24px 8px 24px",position:"relative"},children:[g("div",{style:{marginBottom:"12px"},children:[b&&a("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:a(ms,{onClick:b,color:F,fontFamily:M})}),a("div",{style:{marginTop:"10px",fontSize:"13px",color:z,fontFamily:M},children:a(co,{assets:Wt,selectedAsset:W??void 0,onAssetSelect:jt,onAmountChange:rn,label:"Amount",showBalance:!0,showMaxButton:!0,theme:O,styles:te})}),a("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:z,fontFamily:M},children:At})]}),g("div",{style:$e,children:[g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:A?`1px solid ${v.cardBorder}`:"1px solid #e5e7eb"},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[r?a("img",{src:r,alt:s,style:{width:"32px",height:"32px",borderRadius:"50%",objectFit:"cover"}}):a("div",{style:{width:"32px",height:"32px",borderRadius:"50%",backgroundColor:A?v.inputBg:"#d1d5db",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:700,color:V},children:s.slice(0,2)}),a("span",{style:{fontSize:"16px",fontWeight:600,color:V,fontFamily:M},children:s})]}),g("div",{style:{textAlign:"right"},children:[a("div",{style:{fontSize:"22px",fontWeight:700,color:V,fontFamily:M,lineHeight:1.1},children:Ht??"0.00"}),g("div",{style:{fontSize:"12px",color:z,fontFamily:M,marginTop:"2px"},children:["~$",Nt??"0.00"]})]})]}),g("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:A?`1px solid ${v.cardBorder}`:"1px solid #e5e7eb"},children:[g("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[a("span",{style:{fontSize:"15px",fontWeight:500,color:z,fontFamily:M},children:"Lock Duration"}),a(Bn,{color:z})]}),a(Al,{options:p,selectedIndex:ke,onSelect:Be,primaryColor:F,dark:A,textPrimary:V,textSecondary:z})]}),g("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[a(Bl,{durationMonths:lt?.months,fontFamily:M,dark:A,textPrimary:V,textSecondary:z}),u&&a(Fl,{votes:yt,fontFamily:M,dark:A,textPrimary:V,textSecondary:z})]})]}),Et&&a(So,{fontFamily:M,textPrimary:V,textSecondary:z,cardBg:U,cardBorder:L,resolvedDark:A,darkCardBorder:v.cardBorder,primaryColor:F,feePreview:ae,isLoading:ee,errorText:ue}),ve&&a(to,{variant:"error",palette:v,fontFamily:M,style:{marginBottom:"12px"},children:ve}),a(bt,{variant:"outline",fullWidth:!0,onClick:J,disabled:!$,loading:Z,dark:A,styles:{...I,button:{...I?.button,backgroundColor:F}},children:Z?Yt&&!nt?"DEPOSITING...":nt?"LOCKING...":"CONVERTING...":ee&&Et?"CALCULATING FEES...":Yt&&!nt?`DEPOSIT ${s}`:nt?`LOCK ${s}`:`CONVERT TO ${s}`}),a(Tl,{isOpen:Ke,data:qe,isLocking:Z,lockError:ve,onContinue:J,onClose:()=>X(!1),primaryColor:F,fontFamily:M,dark:A}),Fe&&De&&a("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:A?v.shell:"white",borderRadius:P,padding:"16px 0"},children:a(ws,{type:"deposit",isOpen:!!Fe&&Fe.overallStatus!=="processing",isProcessing:Z||Fe?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{ct(),We(!1),J()},onNewTx:()=>{ct(),We(!1),re(null),sn.current=null,ut(),Ze()},onClose:()=>{ct(),We(!1)},onComplete:()=>{ct(),We(!1),re(null),sn.current=null,ut(),Ze()},results:Fe?.overallStatus==="success"||Fe?.overallStatus==="failed"?Fe.steps.map(Y=>({asset:{symbol:W?.asset?.symbol||s,address:W?.asset?.address||""},txHash:Y.transactionHash||"",success:Y.status==="success",amount:W?.amount})):void 0,chainName:$t(d),explorerUrl:Gn(d,"").replace(/\/tx\/.*$/,"")||void 0,theme:E,styles:I,dark:A})})]})})},jl="0xa9059cbb";function Ql(e,t,n,o){return t!=="user-transfer"||!n||e.length===0||e[0]?.to.toLowerCase()!==o.toLowerCase()||!e[0]?.data.startsWith(jl)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function Uo(e,t,n){if(!t)return[e];const o=await t(n);return o?[o,e]:[e]}function zo(e,t,n){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const o=10n**BigInt(t-n);return(e+o-1n)/o}async function Vl(e,t){const{currentPaymentAmount:n,destinationToken:o,embeddedWalletAddress:s,providerEmbeddedAddress:r,address:i,isNon7702:l,isPayMode:c,resolvedChainId:d,buildActionCalls:p,feeExecutionMode:u,buildSpicenetBatch:f,selectedAsset:h,needsSwap:m,exactOutputSwap:y,resolvedTokenIn:C}=e,x=Ge(n,o.decimals),w=t?.actionAmountOverride??x,b=s||r||(l?void 0:i);if(!b)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const k={userAddress:b,chainId:d,destinationToken:o.address,grossAmount:t?.fundingAmountOverride??x,netAmount:w,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:u,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},I=p(w,k),S={chainId:d,calls:I},E=(!c&&!l?!0:h?.asset?._source==="spice")||l,A=(F,v)=>({token:F,from:l?"solver":"escrow",to:b,amount:v});if(x===0n)return[S];if(m&&y){const F=C??Fn(h.asset,d)??h.asset.address,v=t?.fundingAmountOverride??y.amountInMax,M=E?[A(F,v)]:[],B={to:F,value:0n,data:gt({abi:_t,functionName:"approve",args:[y.calls[0]?.to,y.amountInMax]})},D={chainId:d,calls:[B,...y.calls,...I],tokenTransfers:[...M,...S.tokenTransfers??[]]};return E?Uo(D,f,{userAddress:b,destinationChainId:d,deliveryToken:F,deliveryAmount:v,deliveryRecipient:b,sourceAsset:h.asset}):[D]}if(E){const F=C??Fn(h.asset,d)??o.address,v=t?.fundingAmountOverride??x,M={...S,tokenTransfers:[A(F,v),...S.tokenTransfers??[]]};return Uo(M,f,{userAddress:b,destinationChainId:d,deliveryToken:F,deliveryAmount:v,deliveryRecipient:b,sourceAsset:h.asset})}return[S]}async function ql(e,t){const{selectedAsset:n,embeddedWalletAddress:o,resolvedChainId:s,destinationToken:r,buildActionCalls:i,feeExecutionMode:l,buildSpicenetBatch:c,isPayMode:d,isNon7702:p,needsSwap:u,resolvedSwap:f,quoteAmountOut:h,resolvedTokenIn:m}=e,y=f?.amountOutMinimum??h;if(!n?.asset||!o)return[];const C=t?.fundingAmountOverride??t?.actionAmountOverride??Ge(n.amount,n.asset.decimals),x=t?.fundingAmountOverride??C,w=t?.actionAmountOverride??C,b={userAddress:o,chainId:s,destinationToken:r.address,feeToken:l==="user-transfer"&&u&&m?m:r.address,grossAmount:x,netAmount:w,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:l,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},k=i(w,b);if(!(!d&&!p||n.asset?._source==="spice"))return[{chainId:s,calls:k}];const I=(A,F)=>({token:A,from:"escrow",to:o,amount:F});if(u){if(!m)throw new Error("Swap input token could not be resolved");if(!f||y===null)throw new Error("Swap quote not available yet")}if(u&&f&&y&&m){const A=i(t?.actionAmountOverride??y,{...b,netAmount:t?.actionAmountOverride??y}),{feeCall:F,remainingCalls:v}=Ql(A,l,u,b.feeToken),M={chainId:s,calls:[...F?[F]:[],...f.calls,...v],tokenTransfers:[I(m,x)]};return Uo(M,c,{userAddress:o,destinationChainId:s,deliveryToken:m,deliveryAmount:x,deliveryRecipient:o,sourceAsset:n.asset})}const S=m??Fn(n.asset,s)??r.address,E={chainId:s,calls:k,tokenTransfers:[I(S,x)]};return Uo(E,c,{userAddress:o,destinationChainId:s,deliveryToken:S,deliveryAmount:x,deliveryRecipient:o,sourceAsset:n.asset})}async function Yl(e,t,n,o,s){let r=e;for(let i=0;i<4;i++){const l=await t(r),c=await o(l,n,r,s),d=dl(c);if(d===null||d>=e)return r;const p=r-d,u=e+p;if(u<=r)return r;r=u}return r}function Kl(e,t,n,o){if(e<=0n)return 0n;const s=e-t;if(s<=0n)return 0n;const r=o+n;return r<=0n?s:s*o/r}function Zl(e,t){const n=xt(e,t);return n.includes(".")?n.replace(/\.?0+$/,"")||"0":n}async function Xl(e){const{asset:t,isPayMode:n,isNon7702:o,needsSwap:s,isQuoting:r,embeddedWalletAddress:i,buildSupplyChainBatches:l,estimateGasless:c,executionTokenAddress:d,feeExecutionMode:p}=e;if(n||o||s||r||!i||t.balance<=0n)return null;const u=await l({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(u.length===0)return null;const f=u.some(x=>x.tokenTransfers?.length),h=await c(u,d,t.balance,f?{useCustomTransfers:!0,feeExecutionMode:p}:p?{feeExecutionMode:p}:void 0),m=Zn(h,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),y=m?zo(m.gasFee,m.decimals,t.decimals):0n,C=m?zo(m.spicenetFee,m.decimals,t.decimals):0n;return Zl(Kl(t.balance,y,C,t.balance),t.decimals)}async function Gl(e){const{selectedAsset:t,isPayMode:n,parsedAmount:o,needsSwap:s,exactOutputSwap:r,isNon7702:i,isSourceDestToken:l,currentPaymentAmount:c,destinationToken:d,feeExecutionMode:p,resolvedTokenIn:u,embeddedWalletAddress:f,providerEmbeddedAddress:h,resolvedChainId:m,isConnected:y,address:C,ready:x,authenticated:w,isDirect:b,resolvedSwap:k,isQuoting:I,executionTokenAddress:S,buildPayChainBatches:E,buildSupplyChainBatches:A,estimateGasless:F,estimateRequiredGrossFunding:v}=e;if(!t?.asset)return null;if(n){if(o<=0||s&&!r||i&&l)return null;const Q=Ge(c,d.decimals),U=u||Fn(t.asset,m)||t.asset.address||d.address,L={chainId:m,tokenAddress:U,symbol:Xt(U,m)?.symbol??t.asset.symbol,decimals:Xt(U,m)?.decimals??t.asset.decimals};if(i){const re=f||h;if(!re)return null;const _=s?r?.amountInMax??0n:Q;if(_===0n)return null;const de=await v(_,Z=>E({fundingAmountOverride:Z}),U,{userOverride:re,useCustomTransfers:!0}),ke=await E({fundingAmountOverride:de}),Be=await F(ke,U,de,{userOverride:re,useCustomTransfers:!0,feeExecutionMode:p});return Zn(Be,L)}if(!y||!C||!x||!w)return null;const P=s?r?.amountInMax??0n:Q;if(P===0n)return null;const V=await v(P,re=>E({fundingAmountOverride:re}),U,{useCustomTransfers:!0});let z=await E({fundingAmountOverride:V});const te=await F(z,U,V,{useCustomTransfers:!0,feeExecutionMode:p}),O=Zn(te,L)?.grossAmount??V;O!==V&&(z=await E({fundingAmountOverride:O}));const W=await F(z,U,O,{useCustomTransfers:!0,feeExecutionMode:p});return Zn(W,L)}if(o<=0||!f||!b&&!k&&!I||I)return null;const M=Ge(t.amount,t.asset.decimals),B=await A();if(B.length===0)return null;const D=B.some(Q=>Q.tokenTransfers?.length),R=await F(B,S,M,D?{useCustomTransfers:!0,feeExecutionMode:p}:p?{feeExecutionMode:p}:void 0);return Zn(R,{chainId:m,tokenAddress:S,symbol:Xt(S,m)?.symbol??d.symbol,decimals:Xt(S,m)?.decimals??d.decimals})}async function Jl(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.embeddedWalletAddress){e.ui.setError("Wallet not ready");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.ui.setTxHash(null),e.refs.spiceDepositSubmittedRef.current=!1;const t=new AbortController;e.refs.abortControllerRef.current=t;try{const n=Ge(e.selectedAsset.amount,e.selectedAsset.asset.decimals),o=n;let s=await e.gasless.buildSupplyChainBatches();if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!s.some(p=>yo(p.chainId)))throw new Error("Spice-funded supplies must include a Spicenet funding batch before the destination chain batch.");const r=s.some(p=>p.tokenTransfers?.length)?{useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}:e.feeExecutionMode?{feeExecutionMode:e.feeExecutionMode}:void 0;let i=n;const l=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,c=e.feeExecutionMode==="user-transfer"&&!l?o:void 0;let d;for(let p=0;p<4;p+=1){const u=await e.gasless.estimateGasless(s,e.executionTokenAddress,i,r),f=Zn(u,{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:Xt(e.executionTokenAddress,e.resolvedChainId)?.symbol??e.destinationToken.symbol,decimals:Xt(e.executionTokenAddress,e.resolvedChainId)?.decimals??e.destinationToken.decimals}),h=f?.grossAmount??i;if(h===i){i=h;break}i=h,d=e.feeExecutionMode==="user-transfer"&&f?{grossAmount:f.grossAmount,netAmount:o,combinedFeeAmount:f.totalFee,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:f.spicenetFee,gasFee:f.gasFee,bridgeFee:f.bridgeFee??0n}}:void 0,s=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:i,actionAmountOverride:c,actionContextOverride:d})}e.feeExecutionMode==="user-transfer"&&(s=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:i,actionAmountOverride:c,actionContextOverride:d})),await e.gasless.executeGasless(s,e.executionTokenAddress,i,e.gasless.onProgress,t.signal,r),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){const o=n instanceof Error?n:new Error(String(n));if(o.name==="AbortError"||t.signal.aborted){e.ui.setStep("idle");return}const s=o.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(s),e.ui.setError(s),e.onError?.(o)}finally{e.ui.setIsExecuting(!1)}}async function $l(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=Ge(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),n={userAddress:e.externalWalletAddress,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},o=e.buildActionCalls(t,n);if(o.length===0)throw new Error("No action calls configured");const s=await e.externalWallet.getEthereumProvider();let r=null;try{const p=await s.request({method:"eth_chainId"});r=parseInt(p,16)}catch{r=null}r!==e.resolvedChainId&&await Qn(s,e.resolvedChainId);const i=Me(e.resolvedChainId),l=Un({account:e.externalWalletAddress,chain:i?.viemChain,transport:zn(s)}),c=dt(e.resolvedChainId);let d;for(const p of o){const u=await l.sendTransaction({to:p.to,data:p.data,value:p.value,chain:i?.viemChain});if((await c.waitForTransactionReceipt({hash:u,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transaction failed");d=u}return d}async function _l(e){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const n=e.selectedAsset.asset,o=n.chainId,s=Ge(e.currentPaymentAmount,e.destinationToken.decimals),r=e.selectedIsEquivalent?s:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(r===0n)throw new Error("Quote not available yet");const i=e.resolvedTokenIn||e.selectedAsset.asset.address,l={userOverride:t,useCustomTransfers:!0},c=await e.gasless.estimateRequiredGrossFunding(r,w=>e.gasless.buildPayChainBatches({fundingAmountOverride:w}),i,l),d=Cn(o),p=await e.externalWallet.getEthereumProvider();let u=null;try{const w=await p.request({method:"eth_chainId"});u=parseInt(w,16)}catch{u=null}u!==o&&await Qn(p,o);const f=Me(o),h=Un({account:e.externalWalletAddress,chain:f?.viemChain,transport:zn(p)}),m=It(n.address),y=n.isNative||Qe(m)?await h.sendTransaction({to:d,value:c,chain:f?.viemChain}):await h.sendTransaction({to:m,data:gt({abi:_t,functionName:"transfer",args:[d,c]}),chain:f?.viemChain});if((await dt(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:c}),x=C.some(w=>w.tokenTransfers?.length);return await e.gasless.executeGasless(C,i,c,w=>{w.txHash&&(e.ui.setPaymentResult(b=>({...b??{status:"processing"},txHash:w.txHash})),e.ui.setTxHash(w.txHash))},void 0,x?l:{userOverride:t})}async function ed(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}if(!e.selectedAsset?.asset){e.ui.setError("Select a payment source");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.parsedAmount>0&&e.needsSwap&&!e.exactOutputSwap){e.ui.setError("Swap quote not available. Try a different asset.");return}if(e.isNon7702){if(!e.externalWalletAddress){e.ui.setError("Please connect your external wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{let t;if(e.isSourceDestToken||e.parsedAmount===0)t=await $l(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const n=e.selectedAsset.asset,o=Ge(e.currentPaymentAmount,e.destinationToken.decimals),s=e.selectedIsEquivalent?o:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(s===0n)throw new Error("Quote not available yet");const r=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!r)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const i=e.resolvedTokenIn||n.address,l=await e.gasless.estimateRequiredGrossFunding(s,p=>e.gasless.buildPayChainBatches({fundingAmountOverride:p}),i,{userOverride:r,useCustomTransfers:!0}),c=await e.gasless.buildPayChainBatches({fundingAmountOverride:l}),d=await e.onPayExecute({asset:n,amount:e.currentPaymentAmount,amountWei:o,destinationToken:e.destinationToken,chainBatches:c,requiredNetFunding:s,grossFundingAmount:l,selectedIsEquivalent:e.selectedIsEquivalent,resolvedTokenIn:i,exactOutputSwapAmountInMax:e.exactOutputSwap?.amountInMax});d&&(e.ui.setTxHash(d),e.ui.setPaymentResult(p=>({...p??{status:"processing"},txHash:d}))),t=d||void 0}else t=await _l(e);e.ui.setPaymentResult(n=>({status:"success",txHash:n?.txHash||t||""}))}catch(t){const n=mn(t,"Payment failed. Please try again.");e.ui.setError(n),e.ui.setPaymentResult({status:"failed",error:n}),e.onError?.(t instanceof Error?t:new Error(n))}finally{e.ui.setIsExecuting(!1)}return}if(!e.isConnected||!e.address){e.ui.setError("Please connect your wallet to continue");return}if(!e.ready||!e.authenticated){e.ui.setError(`Please authenticate with ${e.provider||"wallet provider"} to continue`);return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{const t=Ge(e.currentPaymentAmount,e.destinationToken.decimals),n=e.resolvedTokenIn||e.selectedAsset?.asset?.address||e.destinationToken.address,o=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:t,s={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode},r=await e.gasless.estimateRequiredGrossFunding(o,f=>e.gasless.buildPayChainBatches({fundingAmountOverride:f}),n,s);let i=r,l=await e.gasless.buildPayChainBatches({fundingAmountOverride:r});const c=await e.gasless.estimateGasless(l,n,r,s),d=Zn(c,{chainId:e.resolvedChainId,tokenAddress:n,symbol:Xt(n,e.resolvedChainId)?.symbol??e.selectedAsset.asset.symbol,decimals:Xt(n,e.resolvedChainId)?.decimals??e.selectedAsset.asset.decimals})?.grossAmount??r;d!==r&&(i=d,l=await e.gasless.buildPayChainBatches({fundingAmountOverride:d}));const p=l.some(f=>f.tokenTransfers?.length),u=await e.gasless.executeGasless(l,n,p?i:0n,f=>{f.txHash&&(e.ui.setPaymentResult(h=>({...h,txHash:f.txHash})),e.ui.setTxHash(f.txHash))},void 0,s);e.ui.setPaymentResult(f=>({status:"success",txHash:f?.txHash||u}))}catch(t){const n=mn(t,"Payment failed. Please try again.");e.ui.setError(n),e.ui.setPaymentResult({status:"failed",error:n}),e.onError?.(t instanceof Error?t:new Error(n))}finally{e.ui.setIsExecuting(!1)}}const Vr=({variant:e,destinationSymbol:t,destinationLogoURI:n,destinationDecimals:o,primaryColor:s,fontFamily:r,textPrimary:i,textSecondary:l,cardBg:c,cardBorder:d,dk:p,dark:u,isQuoting:f,quoteError:h,estimatedOutput:m,paymentAmount:y,needsSwap:C,exactOutputSwap:x,adjustable:w=!1,maxAmount:b,onAmountChange:k})=>e==="supply"?g("div",{style:{backgroundColor:c,border:`1px solid ${d}`,borderRadius:u?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",minHeight:"112px",display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[g("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"12px"},children:[g("div",{style:{minWidth:0},children:[a("span",{style:{fontFamily:r,fontSize:"17px",fontWeight:500,color:u?"#a7abb2":"#7D7C7B",lineHeight:"24px"},children:"Used in TX"}),a("div",{style:{fontSize:"12px",fontWeight:500,color:l,fontFamily:r,marginTop:"10px"},children:"Net amount after swap and fees"})]}),g("div",{style:{textAlign:"right",minWidth:0,display:"inline-flex",alignItems:"center",gap:"8px",border:`1px solid ${d}`,borderRadius:"8px",padding:"8px 10px",minHeight:"42px"},children:[a(qr,{symbol:t,logoURI:n,primaryColor:s,size:24}),a("span",{style:{fontSize:"16px",fontWeight:500,color:u?"#f3f4f6":"#3C3E42",lineHeight:"1.3",fontFamily:r,letterSpacing:0},children:t})]})]}),a("div",{style:{textAlign:"right",minWidth:0},children:f?a("span",{style:{fontSize:"18px",color:l,fontFamily:r},children:"Quoting..."}):h?a("span",{style:{fontSize:"13px",color:u?"#f87171":"#dc2626",fontFamily:r},children:"Quote failed"}):m?a(qn,{value:m,title:m,fontFamily:r,color:i,lineHeight:"0.95",textAlign:"right",maxFontSize:32,minFontSize:18}):a("span",{style:{fontSize:"20px",color:l,fontFamily:r},children:"\u2014"})})]}):a(td,{destinationSymbol:t,destinationLogoURI:n,destinationDecimals:o,primaryColor:s,fontFamily:r,textPrimary:i,textSecondary:l,cardBg:c,cardBorder:d,dk:p,dark:u,paymentAmount:y||"0",needsSwap:C,exactOutputSwap:x,isQuoting:f,adjustable:w,maxAmount:b,onAmountChange:k}),qr=({symbol:e,logoURI:t,primaryColor:n,size:o})=>t?a("img",{src:t,alt:e,style:{width:o,height:o,borderRadius:"50%",objectFit:"cover"}}):a("div",{style:{width:o,height:o,borderRadius:"50%",backgroundColor:`${n}22`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:o<30?"11px":"12px",fontWeight:700,color:n},children:e.slice(0,2)}),td=({destinationSymbol:e,destinationLogoURI:t,destinationDecimals:n,primaryColor:o,fontFamily:s,textPrimary:r,textSecondary:i,cardBg:l,cardBorder:c,dk:d,dark:p,paymentAmount:u,needsSwap:f,exactOutputSwap:h,isQuoting:m,adjustable:y,maxAmount:C,onAmountChange:x})=>{const w='"IBM Plex Mono", monospace',b=parseFloat(u||"0"),k=C?parseFloat(C):0,[I,S]=T(u||""),E=ie(null),[A,F]=T(null),[v,M]=T(null);K(()=>{y||S(u||"")},[u,y]);const B=Q=>{let U=Q;U.startsWith(".")&&(U="0"+U);const L=$n(U);let P=L;C&&parseFloat(L)>parseFloat(C)&&(P=C),S(P),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>x?.(P),300)},D=Q=>{if(!k)return;if(Q===100){S(C||k.toString()),E.current&&clearTimeout(E.current),x?.(C||k.toString());return}const U=10**n,L=Math.floor(k*Q/100*U)/U,P=_n(L,n);S(P),E.current&&clearTimeout(E.current),x?.(P)},R=k>0?parseFloat(I||"0")/k*100:0;return K(()=>()=>{E.current&&clearTimeout(E.current)},[]),g("div",{style:{backgroundColor:l,border:`1px solid ${c}`,borderRadius:p?"12px":"6px",padding:"16px",marginBottom:"16px"},children:[g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[a(qr,{symbol:e,logoURI:t,primaryColor:o,size:32}),g("div",{children:[a("span",{style:{fontSize:"14px",fontWeight:600,color:r,fontFamily:s},children:"Payment"}),a("div",{style:{fontSize:"12px",color:i,fontFamily:s,marginTop:"2px"},children:e})]})]}),g("div",{style:{textAlign:"right"},children:[y?a(qn,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:I,onChange:Q=>B(Q.target.value),placeholder:"0.0",fontFamily:w,color:r,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):a(qn,{element:"div",value:b>0?u:"0.00",title:b>0?u:"0.00",fontFamily:w,color:r,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),a("div",{style:{fontSize:"12px",color:i,fontFamily:w,marginTop:"2px"},children:e}),y&&k>0&&a("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((Q,U)=>{const L=Math.abs(R-Q)<1,P=U===4,V=Q/100,z=A===Q,te=v===Q;return a("button",{onClick:()=>D(Q),onMouseEnter:()=>F(Q),onMouseLeave:()=>{F(null),M(null)},onMouseDown:()=>M(Q),onMouseUp:()=>M(null),title:`${Q}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:L?1:z?.8:.5,transform:te?"scale(0.85)":z?"scale(1.15)":"scale(1)",transition:tn.interactive},children:g("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[a("circle",{cx:"7",cy:"7",r:"6.84375",fill:P?o:"none",stroke:P?o:p?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!P&&V>0&&a("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${V>.5?1:0} 1 ${7+6.84375*Math.sin(V*2*Math.PI)} ${7-6.84375*Math.cos(V*2*Math.PI)} Z`,fill:p?d?.textSecondary||"#9ca3af":"#3C3E42"})]})},Q)})})]})]}),f&&h&&!m&&a("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:p?`1px solid ${d?.cardBorder||c}`:"1px solid #e5e7eb",display:"flex",justifyContent:"flex-end"},children:g("span",{style:{fontSize:"11px",color:i,fontFamily:s,opacity:.7},children:["via ",h.venue]})})]})};function Yr(e,t,n){const o=je(e.address,t),s=e.chainId===n,r=e._source==="wallet";return r&&o&&s?0:r&&s?1:!r&&o?2:!r&&s?3:4}function nd(e){const{address:t,destinationToken:n,supportedSourceAssets:o,sourceChains:s,enabled:r}=e,i=(Bt(kt)?.mode||"7702")!=="7702",l=vn(),{externalAddress:c,embeddedAddress:d}=uo(),{assets:p,refetch:u}=po({address:t,supportedChains:s,enabled:r&&!i,refetchInterval:3e4}),f=ne(()=>{if(i)return[];if(!o||o.length===0)return p;const S=o.map(E=>E.toLowerCase());return p.filter(E=>S.includes(E.address.toLowerCase()))},[p,o,i]),h=i?c:l,m=ne(()=>{const S=new Set,E=[],A=F=>{if(!F)return;const v=F.toLowerCase();S.has(v)||(S.add(v),E.push(Re(F)))};if(A(n.address),i&&o)for(const F of o)A(F);return E},[i,n.address,o]),y=ne(()=>m.map(S=>S.toLowerCase()).sort().join(","),[m]),C=ne(()=>JSON.stringify([...s||[]].sort()),[s]),[x,w]=T([]),b=ie(0),k=le(async()=>{if(!r||!h||m.length===0){b.current++,w([]);return}const S=++b.current,E=Re(h),A=i?s&&s.length>0?s:[n.chainId]:[n.chainId],F=[];for(const D of m){const R=D.toLowerCase();if(R===n.address.toLowerCase()){const U=Me(n.chainId)?.supportedTokens?.find(L=>je(L.address,R));F.push({address:D,chainId:n.chainId,configToken:U?{decimals:U.decimals,symbol:U.symbol,name:U.name,logo:U.logo}:void 0});continue}let Q=!1;for(const U of A){const L=Me(U)?.supportedTokens?.find(P=>je(P.address,R));if(L){F.push({address:D,chainId:U,configToken:{decimals:L.decimals,symbol:L.symbol,name:L.name,logo:L.logo}}),Q=!0;break}}Q||F.push({address:D,chainId:n.chainId})}const v=new Map;for(const D of F){const R=v.get(D.chainId)||[];R.push(D),v.set(D.chainId,R)}const M=async(D,R)=>{try{const Q=await yn(D,{address:R.address,abi:_t,functionName:"balanceOf",args:[E]});let U,L,P,V;if(R.configToken)U=R.configToken.decimals,L=R.configToken.symbol,P=R.configToken.name,V=R.configToken.logo;else{const[O,W,re]=await Promise.all([yn(D,{address:R.address,abi:_t,functionName:"decimals"}).catch(()=>18),yn(D,{address:R.address,abi:_t,functionName:"symbol"}).catch(()=>"TOKEN"),yn(D,{address:R.address,abi:_t,functionName:"name"}).catch(()=>"TOKEN")]);U=Number(O),L=W,P=re}const z=je(R.address,n.address)&&R.chainId===n.chainId;z&&n.logoURI&&(V=n.logoURI),z&&!R.configToken&&L==="TOKEN"&&(L=n.symbol,P=n.symbol);const te=parseFloat((Number(Q)/Math.pow(10,U)).toFixed(6));return{address:R.address,name:P,symbol:L,decimals:U,balance:Q,balanceFormatted:te,balanceUsd:0,logoURI:V,isNative:!1,chainId:R.chainId}}catch{return null}},B=await Promise.all(Array.from(v.entries()).map(async([D,R])=>{let Q;try{Q=dt(D)}catch{return[]}const U=[],L=[];for(const V of R){const z=U.length;U.push({address:V.address,abi:_t,functionName:"balanceOf",args:[E]}),V.configToken||U.push({address:V.address,abi:_t,functionName:"decimals"},{address:V.address,abi:_t,functionName:"symbol"},{address:V.address,abi:_t,functionName:"name"}),L.push({start:z,item:V})}let P=null;try{P=await Q.multicall({contracts:U})}catch{P=null}return P?L.map(({start:V,item:z})=>{const te=P[V],O=te?.status==="success"?te.result:0n;let W,re,_,de;if(z.configToken)W=z.configToken.decimals,re=z.configToken.symbol,_=z.configToken.name,de=z.configToken.logo;else{const Z=P[V+1],he=P[V+2],be=P[V+3];W=Z?.status==="success"?Number(Z.result):18,re=he?.status==="success"?he.result:"TOKEN",_=be?.status==="success"?be.result:re}const ke=je(z.address,n.address)&&z.chainId===n.chainId;ke&&n.logoURI&&(de=n.logoURI),ke&&!z.configToken&&re==="TOKEN"&&(re=n.symbol,_=n.symbol);const Be=parseFloat((Number(O)/Math.pow(10,W)).toFixed(6));return{address:z.address,name:_,symbol:re,decimals:W,balance:O,balanceFormatted:Be,balanceUsd:0,logoURI:de,isNative:!1,chainId:z.chainId}}):(await Promise.all(R.map(V=>M(Q,V)))).filter(V=>V!==null)}));S===b.current&&w(B.flat())},[r,h,y,C,i,n.address,n.chainId,n.symbol,n.logoURI]);K(()=>{if(!r){w([]);return}k();const S=setInterval(()=>{k()},15e3);return()=>clearInterval(S)},[k,r]);const I=le(()=>{k()},[k]);return{displayAssets:ne(()=>{const S=[],E=x.filter(F=>F.balance>0n);for(const F of E)S.push({...F,_source:"wallet"});for(const F of f)S.push({...F,_source:"spice"});const A=n.address.toLowerCase();return S.sort((F,v)=>Yr(F,A,n.chainId)-Yr(v,A,n.chainId)),S},[x,f,n.address,n.chainId]),filteredSpiceAssets:f,walletAssets:x,embeddedWalletAddress:l||d,externalAddress:c,isNon7702:i,refreshSpiceAssets:u,refreshWalletAssets:I}}async function Kr(e){const{tokenIn:t,tokenOut:n,amountIn:o,fee:s,chainId:r,config:i}=e;if(o<=0n)throw new Error("amountIn must be greater than 0");const l=(await dt(r).simulateContract({address:i.quoterV2,abi:Ma,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:o,fee:s,sqrtPriceLimitX96:0n}]})).result;if(l[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:l[0],sqrtPriceX96After:l[1],gasEstimate:l[3]}}async function Zr(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(s=>Kr({...e,fee:s})));let o=null;for(let s=0;s<n.length;s++){const r=n[s];r.status==="fulfilled"&&(!o||r.value.amountOut>o.amountOut)&&(o={...r.value,fee:t[s]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}const od=[{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 sd(e){const{tokenIn:t,tokenOut:n,amountOut:o,fee:s,chainId:r,config:i}=e;if(o<=0n)throw new Error("amountOut must be greater than 0");const l=(await dt(r).simulateContract({address:i.quoterV2,abi:od,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:o,fee:s,sqrtPriceLimitX96:0n}]})).result;if(l[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:l[0],sqrtPriceX96After:l[1],gasEstimate:l[3]}}async function rd(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(s=>sd({...e,fee:s})));let o=null;for(let s=0;s<n.length;s++){const r=n[s];r.status==="fulfilled"&&(!o||r.value.amountIn<o.amountIn)&&(o={...r.value,fee:t[s]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}function Xr(e){return e.type==="swap"}const Bs=.02,ad=[1,8453,42161,10,137,43114,56],id="https://api.1inch.dev/swap/v6.0";function Gr(e,t){return Da(e,t)}function Jr(e){const t=e?.baseUrl??id;return{name:"1inch",chainIds:e?.chainIds??ad,resolve:async(n,o,s)=>{const r=n.maxSlippage??Bs,i=r*100,l=Qe(n.tokenIn)?Qs:n.tokenIn,c=Qe(n.tokenOut)?Qs:n.tokenOut,d=Qe(n.tokenIn);try{const p=new URL(`${t}/${o}/swap`);p.searchParams.set("src",l),p.searchParams.set("dst",c),p.searchParams.set("amount",n.amountIn.toString()),p.searchParams.set("from",s),p.searchParams.set("slippage",i.toString()),p.searchParams.set("disableEstimate","true"),p.searchParams.set("allowPartialFill","false");const u={Accept:"application/json"};e?.apiKey&&(u.Authorization=`Bearer ${e.apiKey}`);const f=await fetch(p.toString(),{headers:u});if(!f.ok)throw new Ue("VENUE_API_ERROR",`[1inchVenue] API returned ${f.status} for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`,{venue:"1inch",chainId:o,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:`HTTP ${f.status}`});const h=await f.json();if(!h.dstAmount||!h.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const m=BigInt(h.dstAmount);if(m<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const y=Gr(m,r),C=[];return h.tx.to&&!d&&C.push({to:n.tokenIn,value:0n,data:gt({abi:_t,functionName:"approve",args:[h.tx.to,n.amountIn]})}),C.push({to:h.tx.to,value:BigInt(h.tx.value||"0"),data:h.tx.data}),{venue:"1inch",amountOut:m,amountOutMinimum:y,calls:C}}catch(p){if(p instanceof Ue)throw p;const u=p instanceof Error?p.message:String(p);throw new Ue("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}: ${u}`,{venue:"1inch",chainId:o,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:u})}}}}const $r=[4114,5115],Fs={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425"},_r={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453]};function ea(e){return{name:"satsuma",chainIds:e.chainIds??$r,resolve:async(t,n,o)=>{const s=t.maxSlippage??Bs,r=Qe(t.tokenIn);let i;try{i=await Zr({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountIn:t.amountIn,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return console.warn(`[SatsumaVenue] No viable fee tier for ${t.tokenIn} \u2192 ${t.tokenOut} on chain ${n}.`),null}const l=Gr(i.amountOut,s),c=[];return r||c.push({to:t.tokenIn,value:0n,data:gt({abi:_t,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),c.push({to:e.swapRouter,value:r?t.amountIn:0n,data:gt({abi:Ra,functionName:"exactInputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:i.fee,recipient:o,amountIn:t.amountIn,amountOutMinimum:l,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:i.amountOut,amountOutMinimum:l,calls:c}}}}function ta(e){return{name:"satsuma",chainIds:e.chainIds??$r,resolve:async(t,n,o)=>{const s=t.maxSlippage??Bs,r=Qe(t.tokenIn);let i;try{i=await rd({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountOut:t.amountOut,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return null}const l=BigInt(Math.round(s*1e4)),c=i.amountIn+i.amountIn*l/10000n,d=[];return d.push({to:e.swapRouter,value:r?c:0n,data:gt({abi:ld,functionName:"exactOutputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:i.fee,recipient:o,amountOut:t.amountOut,amountInMaximum:c,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:i.amountIn,amountInMax:c,amountOut:t.amountOut,calls:d}}}}const ld=[{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 na(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(ea(e.satsuma)),t.push(Jr(e?.oneInch));function n(s){return t.find(r=>r.chainIds.includes(s))}async function o(s,r,i){const l=[],c=[];for(const d of s){if(!Xr(d)){l.push(d);continue}const p=n(r);if(!p)throw new Ue("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${r}. Cannot resolve swap ${d.tokenIn} \u2192 ${d.tokenOut}.`,{chainId:r,tokenIn:d.tokenIn,tokenOut:d.tokenOut,amountIn:d.amountIn.toString()});const u=await p.resolve(d,r,i);if(!u)throw new Ue("NO_LIQUIDITY",`${p.name} returned no quote for ${d.tokenIn} \u2192 ${d.tokenOut} on chain ${r}.`,{venue:p.name,chainId:r,tokenIn:d.tokenIn,tokenOut:d.tokenOut,amountIn:d.amountIn.toString()});l.push(...u.calls),c.push(u)}return{calls:l,resolvedSwaps:c}}return{resolveSwapIntents:o,getVenueForChain:n,venues:t}}function dd(e){const t=e?.customVenues??[];async function n(o,s,r){const i=t.filter(c=>c.chainIds.includes(s));if(i.length===0)throw new Ue("NO_SWAP_ROUTE",`No exact-output venue supports chain ${s}`,{chainId:s,tokenIn:o.tokenIn,tokenOut:o.tokenOut});const l=(await Promise.allSettled(i.map(c=>c.resolve(o,s,r)))).filter(c=>c.status==="fulfilled").map(c=>c.value).filter(c=>c!==null);if(l.length===0)throw new Ue("NO_SWAP_ROUTE",`All aggregators failed for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${s}`,{chainId:s,tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountOut:o.amountOut.toString()});return l.sort((c,d)=>c.amountIn<d.amountIn?-1:c.amountIn>d.amountIn?1:0),l[0]}return{getQuote:n,venues:t}}const cd=na({satsuma:Fs});function ud(e){const{direction:t,selectedAsset:n,destinationToken:o,chainId:s,recipient:r,paymentAmount:i}=e,[l,c]=T(!1),[d,p]=T(null),[u,f]=T(null),[h,m]=T(null),[y,C]=T(null),[x,w]=T(null),[b,k]=T(null),[I,S]=T(null),[E,A]=T(null),F=ie(null),v=ie(0),M=ie(new Map),B=ne(()=>cd,[]),D=ne(()=>dd({customVenues:[ta(Fs),ta(_r)]}),[]),R=ne(()=>{if(!n?.asset)return null;const W=Fn(n.asset,s);if(W)return W;const re=Rn(n.asset.address,s,n.asset.chainId);return re?re.address:null},[n?.asset,s]),Q=ne(()=>n?.asset?Fo(n.asset,s):[],[n?.asset,s]);K(()=>{let W=!1;if(!n?.asset||Q.length<=1){A(null);return}return(async()=>{const re=t==="input"?n.amount:i||"0";let _=0n;try{_=t==="input"?Ge(re,n.asset.decimals):0n}catch{_=0n}try{const de=await vr(n.asset,s,{requiredAmount:_});W||A(de)}catch{W||A(null)}})(),()=>{W=!0}},[n?.asset,n?.amount,s,Q,t,i]);const U=ne(()=>E??R,[E,R]),L=ne(()=>!n?.asset||!U?[]:[U,...Q.filter(W=>W.toLowerCase()!==U.toLowerCase())],[n?.asset,U,Q]),P=ne(()=>!n?.asset||!To(n.asset.address,n.asset.chainId,o.address,o.chainId)||!U?!1:je(U,o.address),[n,o.address,o.chainId,U]),V=U?je(U,o.address):!1,z=t==="output"&&parseFloat(i||"0")===0,te=!!n?.asset&&!P&&!V&&!z,O=te?I??U:U;return K(()=>{F.current&&clearTimeout(F.current);const W=t==="input"?n?.amount:i,re=parseFloat(W||"0");if(!te||!Number.isFinite(re)||re<=0||!n?.asset||!r||L.length===0){v.current++,f(null),m(null),C(null),w(null),k(null),S(null),p(null),c(!1);return}const _=n.asset.decimals;let de;try{de=t==="input"?Ge(n.amount,_):Ge(i||"0",o.decimals)}catch{v.current++,p("Invalid amount"),c(!1);return}const ke=++v.current,Be=()=>ke!==v.current;c(!0);const Z=t==="output"?150:400;return F.current=setTimeout(async()=>{try{if(t==="input"){const he=B.getVenueForChain(s);if(!he)throw new Error("No swap venue for this chain");let be=null,q=null;for(const j of L){const ee=`${t}:${s}:${j.toLowerCase()}:${o.address.toLowerCase()}:${de.toString()}`,Ce=M.current.get(ee);if(Ce&&Ce.expiresAt>Date.now()&&Ce.resolvedSwap){be=Ce.resolvedSwap,q=j;break}const oe=await he.resolve({type:"swap",tokenIn:j,tokenOut:o.address,amountIn:de},s,r);if(Be())return;if(oe){M.current.set(ee,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:oe}),be=oe,q=j;break}}if(!be||!q)throw new Error("No liquidity for this pair");S(q),k(be.amountOut),C(be),w(null);const ue=parseFloat(xt(be.amountOut,o.decimals));f(ue<.01?ue.toPrecision(4):ue.toLocaleString(void 0,{maximumFractionDigits:6})),m(null),p(null)}else{let he=null,be=null;for(const q of L){const ue=`${t}:${s}:${q.toLowerCase()}:${o.address.toLowerCase()}:${de.toString()}`,j=M.current.get(ue);if(j&&j.expiresAt>Date.now()&&j.exactOutputSwap){he=j.exactOutputSwap,be=q;break}try{const ee=await D.getQuote({tokenIn:q,tokenOut:o.address,amountOut:de},s,r);if(Be())return;M.current.set(ue,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:ee}),he=ee,be=q;break}catch{if(Be())return}}if(!he||!be)throw new Error("No liquidity for this pair");S(be),w(he),C(null),k(null),m(parseFloat(xt(he.amountIn,_)).toFixed(6)),f(null),p(null)}}catch(he){if(Be())return;const be=he instanceof Error?he.message:"Failed to get quote";p(be),f(null),m(null),C(null),w(null),k(null),S(null)}finally{Be()||c(!1)}},Z),()=>{F.current&&clearTimeout(F.current)}},[t,te,n?.amount,n?.asset?.address,n?.asset?.decimals,i,L,s,o.address,o.decimals,r,B,D]),{isQuoting:l,quoteError:d,estimatedOutput:u,estimatedInput:h,resolvedSwap:y,exactOutputSwap:x,quoteAmountOut:b,resolvedTokenIn:O,isDirect:V,needsSwap:te,selectedIsEquivalent:P}}const oa={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},sa=["signing-delegation","signing-intent","submitting","executing"],ra=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,destinationToken:o,buildActionCalls:s,feeExecutionMode:r="user-transfer",buildSpicenetBatch:i,onPayExecute:l,actionLabel:c,amountDirection:d="input",swapDescription:p,directDescription:u,paymentAmount:f,amountInputMode:h="fixed",minPaymentAmount:m,maxPaymentAmount:y,onAmountChange:C,styles:x,dark:w,title:b,subtitle:k,onAddFunds:I,onSuccess:S,onError:E})=>{const A=d==="output",{theme:F,dark:v,primaryColor:M,dk:B,palette:D,fontFamily:R,monoFont:Q,inputDark:U,cardBg:L,cardBorder:P,textPrimary:V,textSecondary:z,subtitleText:te}=at(x,w),O=U?{...F,colors:{...F.colors,secondary:B.cardBg,surfaceHover:B.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:F,W=o.chainId,re=Bt(kt),_=(re?.mode||"7702")!=="7702",de=ne(()=>re?.supportedChainIds??[],[re?.supportedChainIds]),ke=ne(()=>{const ye=re?.allowedTokens;if(!ye||ye.length===0)return;const Oe=new Set(ye.map(Jt=>Jt.toLowerCase())),Kt=[],hn=new Set;for(const Jt of de){const fn=Me(Jt);for(const wn of fn?.supportedTokens??[]){if(!Oe.has(wn.symbol.toLowerCase()))continue;const Se=wn.address.toLowerCase();hn.has(Se)||(hn.add(Se),Kt.push(wn.address))}}return Kt},[re?.allowedTokens,de]),Be=kn(),{address:Z,isConnected:he,isReady:be,isAuthenticated:q,provider:ue}=Be,{executeGasless:j,estimateGasless:ee}=Do(),{externalWallet:Ce,externalAddress:oe,embeddedAddress:N}=uo(),{displayAssets:ae,filteredSpiceAssets:we,embeddedWalletAddress:De,refreshSpiceAssets:We,refreshWalletAssets:pe}=nd({address:Z,destinationToken:o,supportedSourceAssets:ke,sourceChains:de,enabled:e&&(_?!!oe:!!Z)}),Ke=A||_?ae:we,[X,qe]=T(null),[xe,it]=T(f||""),[Ae,wt]=T(!1),[qt,Ft]=T(null),[Ne,Ct]=T("idle"),[zt,Lt]=T(""),[Gt,nn]=T(null),[Dn,Mt]=T(!1),[Fe,Ot]=T(null),[ct,Rt]=T(null),[ut,pt]=T(!1),[cn,mt]=T(!1),[fe,tt]=T(null),on=ie(X),St=ie(!1),Ie=ie(null),Dt=ie(0),ht=ie(null);K(()=>{on.current=X},[X]);const Ze=h==="adjustable"?xe:f||"0",bn=De||N||Z,{isQuoting:Wt,quoteError:sn,estimatedOutput:un,resolvedSwap:Je,exactOutputSwap:Te,quoteAmountOut:vt,resolvedTokenIn:lt,isDirect:nt,needsSwap:ot,selectedIsEquivalent:Ht}=ud({direction:d,selectedAsset:X,destinationToken:o,chainId:W,recipient:bn,paymentAmount:Ze}),yt=A?parseFloat(Ze||"0"):parseFloat(X?.amount||"")||0,At=ne(()=>X?.asset?we.find(ye=>je(ye.address,X.asset.address))?.balanceFormatted??0:0,[X,we]),Nt=ne(()=>X?.asset?A?ct?zo(ct.grossAmount,ct.decimals,X.asset.decimals)>X.asset.balance:Ht||nt?yt>X.asset.balanceFormatted:Te?parseFloat(xt(Te.amountInMax,X.asset.decimals))>X.asset.balanceFormatted:!1:ct?parseFloat(xt(zo(ct.grossAmount,ct.decimals,X.asset.decimals),X.asset.decimals))>At:yt>At:!1,[X,A,ct,Ht,yt,Te,At,nt]);K(()=>{e||(qe(null),Ft(null),wt(!1),Ct("idle"),Lt(""),nn(null),Mt(!1),Ot(null),Rt(null),pt(!1),mt(!1),tt(null),St.current=!1,h==="adjustable"&&it(f||""),Ie.current&&(Ie.current.abort(),Ie.current=null))},[e]);const jt=le(ye=>{qe(Oe=>({asset:ye,amount:Oe?.asset?.address===ye.address&&Oe?.asset?.chainId===ye.chainId&&Oe.amount||""})),Ft(null),tt(null),mt(!1)},[]),rn=le(ye=>{qe(Oe=>Oe&&{...Oe,amount:ye}),Ft(null),tt(null),mt(!1)},[]),In=le(ye=>{let Oe=ye;y&&parseFloat(Oe)>parseFloat(y)&&(Oe=y),it(Oe),C?.(Oe),Ft(null),tt(null),mt(!1)},[y,C]);le(ye=>{if(St.current||!Z)return;const Oe=on.current;!Oe?.asset||!Oe.amount||Oe.asset?._source==="wallet"||Ge(A?Ze:Oe.amount,Oe.asset.decimals)===0n||(St.current=!0,We())},[Z,W,We,A,Ze]);const ze=le(ye=>{Ct({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[ye.step]||"executing"),Lt(ye.message),ye.txHash&&nn(ye.txHash)},[]),Et=ne(()=>({currentPaymentAmount:Ze,destinationToken:o,embeddedWalletAddress:De,providerEmbeddedAddress:N,address:Z,isNon7702:_,isPayMode:A,resolvedChainId:W,buildActionCalls:s,feeExecutionMode:r,buildSpicenetBatch:i,selectedAsset:X,needsSwap:ot,resolvedSwap:Je,exactOutputSwap:Te,quoteAmountOut:vt,resolvedTokenIn:lt}),[Ze,o,De,N,Z,_,A,W,s,r,i,X,ot,Je,Te,vt,lt]),pn=le(ye=>Vl(Et,ye),[Et]),Yt=le(ye=>ql(Et,ye),[Et]),J=le((ye,Oe,Kt,hn)=>Yl(ye,Oe,Kt,ee,hn),[ee]),$=ne(()=>X?.asset?X.asset.chainId===W?X.asset.address:lt??Fn(X.asset,W)??o.address:o.address,[X,o.address,W,lt]),ve=le(()=>Jl(ht.current),[]),Ve=ne(()=>X?.asset?je(X.asset.address,o.address)&&X.asset.chainId===o.chainId:!1,[X,o.address,o.chainId]),$e=A&&_&&Ve&&yt>0&&!!X?.asset,Y=qt,ce=ne(()=>!(!X?.asset||yt<=0),[X,yt,$e]),Le=ne(()=>!e||Ae||Ne!=="idle"||!ce||$e||!X?.asset?null:[A?"pay":"supply",d,X.asset.address.toLowerCase(),X.asset.chainId,X.amount,Ze,o.address.toLowerCase(),o.chainId,W,lt?.toLowerCase()??"",ot?"swap":"direct",nt?"direct-token":"routed-token",_?"non7702":"7702",Ve?"source-dest":"cross-chain",Wt?"quoting":"quoted",Te?.amountIn?.toString()??"",Te?.amountInMax?.toString()??"",Te?.venue??"",Je?.amountOut?.toString()??"",vt?.toString()??"",De??"",N??"",Z??""].join("|"),[e,Ae,Ne,ce,$e,X,A,d,Ze,o,W,lt,ot,nt,_,Ve,Wt,Te,Je,vt,De,N,Z]),Ee=le(()=>Gl({selectedAsset:X,isPayMode:A,parsedAmount:yt,needsSwap:ot,exactOutputSwap:Te,isNon7702:_,isSourceDestToken:Ve,currentPaymentAmount:Ze,destinationToken:o,feeExecutionMode:r,resolvedTokenIn:lt,embeddedWalletAddress:De,providerEmbeddedAddress:N,resolvedChainId:W,isConnected:he,address:Z,ready:be,authenticated:q,isDirect:nt,resolvedSwap:Je,isQuoting:Wt,executionTokenAddress:$,buildPayChainBatches:pn,buildSupplyChainBatches:Yt,estimateGasless:ee,estimateRequiredGrossFunding:J}),[X,A,yt,ot,Te,_,Ve,Ze,o,r,lt,De,N,J,pn,ee,W,he,Z,be,q,nt,Je,Wt,Yt,$]),_e=le(ye=>Xl({asset:ye,isPayMode:A,isNon7702:_,needsSwap:ot,isQuoting:Wt,embeddedWalletAddress:De,buildSupplyChainBatches:Yt,estimateGasless:ee,executionTokenAddress:$,feeExecutionMode:r}),[A,_,ot,Wt,De,Yt,ee,$,r]);K(()=>{if(!e){pt(!1),mt(!1),tt(null),Rt(null);return}if(Ae||Ne!=="idle"){Dt.current+=1,pt(!1);return}if(!ce){Rt(null),pt(!1),mt(!1),tt(null);return}if($e){Rt(null),pt(!1),mt(!0),tt(null);return}if(!Le)return;let ye=!1;const Oe=async()=>{const Jt=++Dt.current;tt(null),pt(!0);try{const fn=await Ee();if(ye||Dt.current!==Jt)return;fn?(Rt(fn),mt(!0)):(Rt(null),mt(!1)),tt(null)}catch(fn){if(ye||Dt.current!==Jt)return;const wn=mn(fn,"Unable to calculate fees for this action.");Rt(null),mt(!1),tt(wn)}finally{!ye&&Dt.current===Jt&&pt(!1)}},Kt=window.setTimeout(()=>{Oe()},250),hn=window.setInterval(()=>{Oe()},1e4);return()=>{ye=!0,clearTimeout(Kt),window.clearInterval(hn),pt(!1)}},[e,Ae,Ne,Ee,ce,$e,Le]);const He=le(()=>ed(ht.current),[]);K(()=>{!A&&Ne==="success"&&Gt&&(We(),S?.(Gt))},[A,Ne,Gt,We,S]),K(()=>{if(!A||Fe?.status!=="success"||St.current||!Z)return;St.current=!0;const ye=on.current;!ye?.asset||ye.asset?._source==="wallet"||We()},[A,Fe?.status,Z,We]);const Ye=ie(S),rt=ie(E);K(()=>{Ye.current=S},[S]),K(()=>{rt.current=E},[E]),K(()=>{e&&(We(),pe())},[e,We,pe]),K(()=>{A&&(Fe?.status==="success"&&Ye.current?.(Fe.txHash||""),Fe?.status==="failed"&&rt.current?.(new Error("Payment execution failed")))},[A,Fe?.status]);const st=le(()=>{Mt(!1),Ot(null),qe(null),St.current=!1,We(),pe()},[We,pe]);ht.current={selectedAsset:X,parsedAmount:yt,currentPaymentAmount:Ze,isInsufficientBalance:Nt,isPayMode:A,isNon7702:_,isSourceDestToken:Ve,needsSwap:ot,exactOutputSwap:Te,selectedIsEquivalent:Ht,resolvedTokenIn:lt,embeddedWalletAddress:De,providerEmbeddedAddress:N,externalWallet:Ce,externalWalletAddress:oe,address:Z,isConnected:he,ready:be,authenticated:q,provider:ue,resolvedChainId:W,executionTokenAddress:$,destinationToken:o,buildActionCalls:s,feeExecutionMode:r,buildSpicenetBatch:i,onPayExecute:l,onError:E,gasless:{estimateGasless:ee,executeGasless:j,buildPayChainBatches:pn,buildSupplyChainBatches:Yt,estimateRequiredGrossFunding:J,onProgress:ze},ui:{setError:Ft,setStep:Ct,setStatusMsg:Lt,setTxHash:nn,setIsExecuting:wt,setShowStatusPanel:Mt,setPaymentResult:Ot},refs:{spiceDepositSubmittedRef:St,abortControllerRef:Ie}};const et=A&&yt===0,H=A?!!X?.asset&&yt>=0&&!Nt&&!Ae&&(et||$e||cn)&&!fe&&(et||!ot||!!Te):!!X?.asset&&yt>0&&!Nt&&!Ae&&cn&&!fe&&(nt||!!Je&&!Wt),G=nt?u||`Your ${o.symbol} will be used directly.`:p||"Your assets will be swapped and used in a single atomic transaction.",ge=(W?Me(W):void 0)?.viemChain?.blockExplorers?.default?.url??"",se=sa.indexOf(Ne),me=Ae?(oa[Ne]||"EXECUTING...").toUpperCase():Ne==="success"?"DONE":Nt?"INSUFFICIENT BALANCE":c.toUpperCase(),Pe=ne(()=>{if(Ae)return"PAYING...";if(Nt&&X?.asset)return`INSUFFICIENT ${X.asset.symbol}`;if(c)return c.toUpperCase();const ye=yt>0?` ${Ze} ${o.symbol}`:"";return ot?`SWAP & PAY${ye}`:`PAY${ye}`},[Ae,Nt,X,c,yt,Ze,o.symbol,ot]),Qt=Ne==="success"?()=>{Ct("idle"),qe(null),nn(null),We()}:ve,an=Ne==="success"?!1:!H;if(!e)return null;const Vt=A?b||`Pay ${o.symbol}`:c,Pt=A?k:g("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[a("span",{style:{marginTop:"3px",flexShrink:0},children:a(fs,{color:te})}),a("p",{style:{fontSize:"12px",color:te,margin:0,lineHeight:"1.4",fontFamily:R},children:G})]});if(A){const ye=Fe&&(Fe.status==="success"||Fe.status==="failed")?[{asset:{symbol:X?.asset?.symbol||o.symbol,address:X?.asset?.address||""},amount:Ze,txHash:Fe.txHash||"",success:Fe.status==="success",error:Fe.status==="failed"?Fe.error:void 0}]:void 0;return a(En,{isOpen:e,onClose:t,title:Vt,subtitle:Pt,styles:x,dark:v,footerLinkText:"Spicenet accounts \u2192",closeOnBackdropClick:n,children:g("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[I&&a("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:a(ms,{onClick:I,color:M,fontFamily:R})}),a("div",{style:{marginBottom:"12px"},children:a(co,{assets:Ke,selectedAsset:X??void 0,onAssetSelect:jt,onAmountChange:()=>{},label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:X?.asset?ot?Wt?"...":Te?`~${parseFloat(xt(Te.amountIn,X.asset.decimals)).toFixed(6)}`:void 0:Ze??void 0:void 0,dark:v,theme:O,styles:x})}),a(Vr,{variant:"pay",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:M,fontFamily:R,textPrimary:V,textSecondary:z,cardBg:L,cardBorder:P,dk:B,dark:v,isQuoting:Wt,quoteError:sn,estimatedOutput:un,paymentAmount:Ze,needsSwap:ot,exactOutputSwap:Te,adjustable:h==="adjustable",maxAmount:y,onAmountChange:In}),ce&&a(So,{fontFamily:R,textPrimary:V,textSecondary:z,cardBg:L,cardBorder:P,resolvedDark:v,darkCardBorder:B.cardBorder,primaryColor:M,feePreview:ct,isLoading:ut,errorText:fe,directExecutionFeeNote:$e}),Y&&a(to,{variant:"error",palette:D,fontFamily:R,style:{marginBottom:"12px"},children:Y}),a(bt,{variant:"outline",fullWidth:!0,onClick:He,disabled:!H,loading:Ae,dark:v,styles:{...x,button:{...x?.button,backgroundColor:M}},children:Pe}),Fe&&Dn&&a("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:v?B.shell:"white",borderRadius:v?"12px":"6px",padding:"16px 0"},children:a(ws,{type:"payment",isOpen:Fe.status!=="processing",isProcessing:Ae||Fe.status==="processing",closeOnComplete:!1,chainName:$t(W),explorerUrl:Gn(W,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{Mt(!1),Ot(null),He()},onNewTx:st,onClose:()=>{Mt(!1),Ot(null)},onComplete:st,results:ye,styles:x,dark:v})})]})})}return a(En,{isOpen:e,onClose:t,title:Vt,subtitle:Pt,dark:v,styles:x,theme:F,closeOnBackdropClick:n,children:g("div",{style:{padding:"24px 24px 5px 24px",position:"relative"},children:[a("div",{style:{marginBottom:"16px"},children:a(co,{assets:Ke,selectedAsset:X||void 0,onAssetSelect:jt,onAmountChange:rn,disabled:Ae||Ne==="success",showBalance:!0,showMaxButton:!0,label:"From Spice Balance",placeholder:"0.00",theme:O,styles:x,dark:U,resolveMaxAmount:_e,maxAmount:At>0?_n(At,X?.asset.decimals??o.decimals):void 0})}),X?.asset&&!nt&&a(Vr,{variant:"supply",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:M,fontFamily:R,textPrimary:V,textSecondary:z,cardBg:L,cardBorder:P,dark:v,isQuoting:Wt,quoteError:sn,estimatedOutput:un}),ce&&a(So,{fontFamily:R,textPrimary:V,textSecondary:z,cardBg:L,cardBorder:P,resolvedDark:v,darkCardBorder:B.cardBorder,primaryColor:M,feePreview:ct,isLoading:ut,errorText:fe}),Ne!=="idle"&&g("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:Ne==="success"?L:Ne==="error"?D.errorBg:L,border:`1px solid ${Ne==="success"?P:Ne==="error"?D.errorBorder:P}`},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[Ne==="success"?a("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:a("path",{d:"M5 13l4 4L19 7",stroke:D.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):Ne==="error"?a("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:a("path",{d:"M18 6L6 18M6 6l12 12",stroke:D.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):a(Wn,{size:14,color:M}),a("span",{style:{fontSize:"13px",fontWeight:500,color:Ne==="success"?V:Ne==="error"?D.errorText:V,fontFamily:R,flex:1},children:Ne==="success"?"Deposit confirmed":Ne==="error"?zt||"Transaction failed":oa[Ne]||zt}),Ne==="success"&&Gt&&a("a",{href:`${ge}/tx/${Gt}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:M,fontFamily:R,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),Ne==="error"&&a("button",{onClick:()=>{Ct("idle"),Ft(null),setTimeout(ve,50)},style:{background:"none",border:"none",fontSize:"12px",color:M,fontFamily:R,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),se>=0&&Ne!=="success"&&Ne!=="error"&&a("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${z}22`,overflow:"hidden"},children:a("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:M,transformOrigin:"left center",transform:`scaleX(${(se+1)/sa.length})`,transition:"transform 400ms ease"}})})]}),qt&&Ne==="idle"&&a(to,{variant:"error",palette:D,fontFamily:R,style:{marginBottom:"16px"},children:qt}),a(bt,{variant:"outline",fullWidth:!0,disabled:an,onClick:Qt,theme:F,dark:v,styles:{...x,button:{...x?.button,backgroundColor:M}},style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:Q},children:me})]})})},pd=e=>a(ra,{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}),hd=({label:e="Export Wallet",style:t,className:n,onExport:o,onError:s})=>{const[r,i]=T(!1),[l,c]=T(!1),{primaryColor:d}=at(),p=Bt(kt),{isAuthenticated:u}=kn();let f=null;try{f=bo()}catch{}let h=null,m=null;try{h=za(),m=wo()}catch{h=null,m=null}const y=Co(m),C=le(async()=>{if(!u){s?.("User is not authenticated. Please log in first.");return}try{if(p?.provider==="dynamic"){if(!h||!y){s?.("Dynamic is not available. Ensure the app is wrapped in a DynamicContextProvider.");return}await h.initExportProcess(!1),o?.();return}if(!f){s?.("Privy is not available. Ensure the app is wrapped in a PrivyProvider.");return}await f.exportWallet(),o?.()}catch(b){const k=b instanceof Error?b.message:"Failed to export wallet";console.error("Export wallet error:",b),s?.(k)}},[y,h,u,s,o,f,p?.provider]),x=!u,w={padding:"10px 20px",borderRadius:"8px",fontFamily:'"IBM Plex Mono", monospace',fontSize:"14px",fontWeight:500,letterSpacing:"0.4px",textTransform:"uppercase",cursor:x?"not-allowed":"pointer",opacity:x?.5:1,border:"1px solid #0e0d0b",color:"#0e0d0b",backgroundColor:l?`${d}cc`:r?`${d}ee`:d,transition:"background-color 150ms ease, transform 150ms ease",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"8px",...t};return g("button",{onClick:C,onMouseEnter:()=>i(!0),onMouseLeave:()=>{i(!1),c(!1)},onMouseDown:()=>c(!0),onMouseUp:()=>c(!1),disabled:x,className:n,style:w,children:[g("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),a("polyline",{points:"17 8 12 3 7 8"}),a("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]}),e]})};function aa(e){const t=Bt(kt),n=vn(),o=e?.enabled===!1?void 0:n,s=t?.network?{network:t.network,pollIntervalMs:e?.pollIntervalMs,chainIds:e?.chainIds??t.supportedChainIds}:void 0;return{...hr(o,s),embeddedWalletAddress:n}}const fd=({appName:e,status:t,statusLabel:n,totalUsdValue:o,breakdownSubtitle:s,address:r,dk:i,dark:l=!1,showModeToggle:c,isEmbeddedMode:d=!0,onModeToggle:p})=>{const[u,f]=T(!1),h=async()=>{r&&await _a(r)&&(f(!0),setTimeout(()=>f(!1),2e3))},m=t==="active",y=n||(m?"Active":"Inactive"),C=m?"#10b981":"#9ca3af";return g("div",{children:[g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[g("div",{style:{fontSize:"13px",fontWeight:600,color:i.textPrimary},children:[e," Account"]}),c?g("button",{onClick:p,style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:l?i.hoverBg:"#f3f4f6",border:l?`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:[a("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:d?"#22c55e":"#f59e0b"}}),a("span",{children:d?"Embedded":"External"})]}):g("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:l?i.hoverBg:m?"#ecfdf5":"#f3f4f6",border:l?`1px solid ${i.cardBorder}`:m?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[a("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:C}}),a("span",{style:{fontSize:"11px",fontWeight:500,color:l?i.textSecondary:m?"#065f46":"#6b7280"},children:y})]})]}),a("div",{style:{fontSize:"28px",fontWeight:700,color:i.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:Jn(o)}),s&&a("div",{style:{fontSize:"12px",color:i.textSecondary,marginBottom:"8px"},children:s}),r&&g("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[a("span",{style:{fontSize:"12px",fontFamily:'"IBM Plex Mono", monospace',color:l?i.textSecondary:"#9ca3af"},children:$a(r)}),a("button",{onClick:h,style:{padding:"2px 6px",fontSize:"10px",fontWeight:500,backgroundColor:"transparent",color:l?i.textSecondary:"#9ca3af",border:"none",cursor:"pointer",borderRadius:"4px",transition:"background-color 150ms ease, color 150ms ease"},title:"Copy address",children:u?"Copied":"Copy"})]})]})},md=({pendingDeposits:e,onCompleteDeposit:t,dk:n,dark:o=!1})=>e.length===0?null:g("div",{children:[a("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:"Pending Deposits"}),a("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((s,r)=>{const i=Me(s.chainId)?.displayName||`Chain ${s.chainId}`;return g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:o?n.warningBg:"#fffbeb",border:o?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"8px"},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[a("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:o?n.hoverBg:"#fde68a",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:n.warningText},children:s.tokenSymbol.charAt(0)}),g("div",{children:[g("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:[s.amount," ",s.tokenSymbol]}),g("div",{style:{fontSize:"11px",color:n.warningText},children:["on ",i]})]})]}),a("button",{onClick:()=>t?.(s),style:{padding:"4px 12px",fontSize:"11px",fontWeight:600,backgroundColor:o?n.hoverBg:"#fef3c7",color:o?n.textPrimary:"#92400e",border:o?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"9999px",cursor:"pointer",transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease"},children:"Complete"})]},`${s.tokenAddress}-${s.chainId}-${r}`)})})]}),gd=({spiceAssets:e,loading:t,dk:n,dark:o=!1})=>{const s={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},r={backgroundColor:n.cardBg,border:o?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return t?g("div",{children:[a("div",{style:s,children:"Idle Balances"}),[1,2].map(i=>a("div",{style:{...r,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},i))]}):e.length===0?g("div",{children:[a("div",{style:s,children:"Idle Balances"}),a("div",{style:{...r,padding:"16px",textAlign:"center",fontSize:"13px",color:o?n.textSecondary:"#9ca3af"},children:"No assets yet. Deposit to get started."})]}):g("div",{children:[a("div",{style:s,children:"Idle Balances"}),a("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((i,l)=>{const c=Me(i.chainId),d=i.chainDisplayName||c?.displayName||`Chain ${i.chainId}`,p=i.tokenDisplaySymbol||i.tokenDisplayName||i.tokenSymbol;return g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...r},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[i.logoURI?a("img",{src:i.logoURI,alt:i.tokenSymbol,style:{width:"24px",height:"24px",borderRadius:"50%"}}):a("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:o?n.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:n.textSecondary},children:p.charAt(0)}),g("div",{children:[a("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:p}),a("div",{style:{fontSize:"11px",color:o?n.textSecondary:"#9ca3af"},children:d})]})]}),g("div",{style:{textAlign:"right"},children:[a("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:Ln(i.balanceFormatted)}),a("div",{style:{fontSize:"11px",color:o?n.textSecondary:"#9ca3af"},children:Jn(i.usdValue)})]})]},`${i.tokenAddress}-${i.chainId}-${l}`)})})]})},yd=({section:e,dk:t,dark:n=!1})=>{const o=s=>{switch(s){case"green":return"#10b981";case"red":return"#ef4444";default:return t.textPrimary}};return g("div",{children:[a("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:t.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:e.title}),a("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.items.map((s,r)=>g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:t.cardBg,border:n?`1px solid ${t.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.tokenLogoURI?a("img",{src:s.tokenLogoURI,alt:s.tokenSymbol,style:{width:"20px",height:"20px",borderRadius:"50%"}}):a("div",{style:{width:"20px",height:"20px",borderRadius:"50%",backgroundColor:n?t.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",fontWeight:600,color:t.textSecondary},children:s.tokenSymbol.charAt(0)}),g("div",{children:[a("div",{style:{fontSize:"13px",fontWeight:500,color:t.textPrimary},children:s.tokenSymbol}),a("div",{style:{fontSize:"11px",color:t.textSecondary},children:s.label})]})]}),a("div",{style:{fontSize:"13px",fontWeight:600,color:o(s.valueColor)},children:s.displayValue})]},r))})]})},xd=({onDepositClick:e,onWithdrawClick:t,depositDisabled:n=!1,withdrawDisabled:o=!1,primaryColor:s="#EA4B4B",dark:r=!1})=>!e&&!t?null:g("div",{style:{display:"flex",gap:"8px"},children:[e&&a(bt,{variant:"outline",onClick:e,disabled:n,dark:r,styles:{button:{backgroundColor:s}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&a(bt,{variant:"outline",onClick:t,disabled:o,dark:r,styles:{button:{backgroundColor:s}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),bd=({appName:e,status:t,statusLabel:n,totalUsdValue:o,breakdownSubtitle:s,address:r,spiceAssets:i,spiceAssetsLoading:l,pendingDeposits:c,customSections:d,onDepositClick:p,onWithdrawClick:u,onCompleteDeposit:f,primaryColor:h,dk:m,dark:y=!1,showModeToggle:C,isEmbeddedMode:x,onModeToggle:w,showConnectExternalCta:b,onConnectExternalWallet:k,connectExternalError:I})=>{const[S,E]=T(!1);return g("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[a(fd,{appName:e,status:t,statusLabel:n,totalUsdValue:o,breakdownSubtitle:s,address:r,dk:m,dark:y,showModeToggle:C,isEmbeddedMode:x,onModeToggle:w}),b&&g("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[a("button",{onClick:k,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:h||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:'"Helvetica Neue", sans-serif',transition:"opacity 150ms ease"},children:"Connect External Wallet"}),I&&a("span",{style:{fontSize:"11px",color:y?m.errorText:"#b91c1c",lineHeight:1.4},children:I})]}),a("div",{style:{height:"1px",backgroundColor:y?"#2d2d2d":"#e5e7eb"}}),a(xd,{onDepositClick:p,onWithdrawClick:u,primaryColor:h,dark:y}),g("div",{children:[g("button",{onClick:()=>E(!S),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:m.cardBg,border:y?`1px solid ${m.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:m.textSecondary,fontSize:"12px",fontWeight:500},children:[a("span",{children:"How It Works"}),a("span",{style:{transform:S?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),S&&g("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:y?m.cardBg:"#f0fdf4",border:y?`1px solid ${m.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:y?m.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),a(md,{pendingDeposits:c,onCompleteDeposit:f,dk:m,dark:y}),a(gd,{spiceAssets:i,loading:l,dk:m,dark:y}),d.map((A,F)=>a(yd,{section:A,dk:m,dark:y},F))]})},Ts=380,Xn=8;function ia(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function wd(e,t){const n=new Map;Object.entries(t).forEach(([s,r])=>{if(!Number.isFinite(r)||r<=0)return;n.set(s,r),n.set(s.toUpperCase(),r);const i=ia(s);i&&n.set(i,r)});const o=[e.symbol,e.displaySymbol,e.receiptTokenName,e.name,e.displayName];for(const s of o){if(!s)continue;const r=n.get(s)??n.get(s.toUpperCase());if(r!==void 0)return r;const i=ia(s);if(!i)continue;const l=n.get(i);if(l!==void 0)return l}return 0}const Cd=({appName:e="Spice",status:t="active",statusLabel:n,customSections:o=[],extraAssets:s=[],tokenPrices:r={},breakdownLabels:i=[],styles:l,dark:c=!1,onDepositSuccess:d,onDepositClick:p,onWithdrawClick:u,onCompleteDeposit:f,showModeToggle:h=!1,defaultMode:m})=>{const y=Bt(kt),C=y?.mode!=="7702",x=ie(!1);K(()=>{if(!x.current){if(va()){x.current=!0;return}m&&y?.setMode&&(y.setMode(m==="non7702"?"ondemand":"7702"),x.current=!0)}},[y,m]);const[w,b]=T(!1),[k,I]=T(null),[S,E]=T({top:0,bottom:0,left:0,placement:"below"}),A=ie(null),F=ie(null),{address:v,isConnected:M}=kn(),B=vn(),{address:D}=Nn(),{dark:R,primaryColor:Q,dk:U}=at(l,c),L=ne(()=>y?.supportedChainIds??go("mainnet"),[y?.supportedChainIds]),{assets:P,loading:V}=po({address:v,supportedChains:L,enabled:!!v&&!C,refetchInterval:3e4}),z=ne(()=>[...C?[]:P.map(pe=>{const Ke=pe.balanceUsd||0,X=Number.isFinite(pe.balanceFormatted)?pe.balanceFormatted:0,qe=Ke>0?Ke:wd(pe,r)*X;return{tokenAddress:pe.address,tokenSymbol:pe.symbol,tokenDisplaySymbol:cs(pe),tokenDisplayName:ri(pe),tokenDecimals:pe.decimals,chainId:pe.chainId,chainDisplayName:us(pe),balance:pe.balance.toString(),balanceFormatted:pe.balanceFormatted,usdValue:qe,logoURI:pe.logoURI}}),...s].filter(pe=>pe.balanceFormatted>0),[C,P,r,s]),te=ne(()=>z.reduce((pe,Ke)=>pe+Ke.usdValue,0),[z]),{pendingDeposits:O}=aa({chainIds:L,enabled:!!v}),W=ne(()=>o.reduce((pe,Ke)=>pe+Ke.totalValue,0),[o]),re=te+W,_=ne(()=>{const pe=[];te>0&&pe.push(`${Jn(te)} idle`);for(const Ke of o){const X=i.find(qe=>qe.sectionTitle===Ke.title)?.label||Ke.title.toLowerCase();pe.push(`${Jn(Ke.totalValue)} ${X}`)}return pe.join(" \xB7 ")},[te,o,i]),de=le(pe=>{f?f(pe):I(pe)},[f]),ke=le(()=>{I(null)},[]),Be=le(()=>{I(null),d?.()},[d]),Z=le(()=>{if(!A.current)return;const pe=A.current.getBoundingClientRect(),Ke=window.innerHeight-pe.bottom-Xn,X=pe.top-Xn,qe=Ke>=400||Ke>=X?"below":"above",xe=Math.max(Xn,Math.min(pe.right-Ts,window.innerWidth-Ts-Xn)),it=qe==="below"?pe.bottom+Xn:pe.top-Xn,Ae=qe==="above"?window.innerHeight-it:0;E({top:it,bottom:Ae,left:xe,placement:qe})},[]);Ns(()=>{w&&Z()},[w,Z]),K(()=>{if(!w)return;const pe=qe=>{A.current&&!A.current.contains(qe.target)&&F.current&&!F.current.contains(qe.target)&&b(!1)},Ke=qe=>{qe.key==="Escape"&&b(!1)},X=()=>Z();return document.addEventListener("mousedown",pe),document.addEventListener("keydown",Ke),window.addEventListener("scroll",X,{passive:!0}),window.addEventListener("resize",Z),()=>{document.removeEventListener("mousedown",pe),document.removeEventListener("keydown",Ke),window.removeEventListener("scroll",X),window.removeEventListener("resize",Z)}},[w,Z]);const he=y?.mode==="7702",be=he?B||v:D||v,q=le(()=>{y?.setMode&&y.setMode(he?"ondemand":"7702")},[y,he]),[ue,j]=T(null);let ee=null;try{ee=Vs({onSuccess:()=>j(null),onError:pe=>j(mn(pe,"Failed to connect wallet."))}).connectWallet}catch{ee=null}const Ce=le(()=>{ee&&(b(!1),j(null),ee({walletChainType:"ethereum-only"}))},[ee]),oe=h&&!he&&!D&&!!ee,N=le(()=>{b(!1),p?.()},[p]),ae=le(()=>{b(!1),u?.()},[u]),we=le(pe=>{b(!1),de(pe)},[de]);if(typeof window>"u")return null;const De=g("button",{ref:A,onClick:()=>b(!w),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:R?U.hoverBg:"#ffffff",border:R?`1px solid ${U.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:'"Helvetica Neue", sans-serif',color:R?U.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:R?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[a("span",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:Q,flexShrink:0}}),g("span",{children:[e," Account"]}),M&&g("span",{style:{color:R?U.textSecondary:"#6b7280"},children:["\xB7 ",Jn(re)]}),a("span",{style:{fontSize:"10px",color:R?U.textSecondary:"#9ca3af",transform:w?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),We=w?Ys.createPortal(g(ln,{children:[a("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:Vn.popover},onClick:()=>b(!1)}),a("div",{ref:F,style:{position:"fixed",top:S.placement==="below"?`${S.top}px`:"auto",bottom:S.placement==="above"?`${S.bottom}px`:"auto",left:`${S.left}px`,width:`${Ts}px`,maxWidth:`calc(100vw - ${Xn*2}px)`,maxHeight:"80vh",backgroundColor:R?U.shell:"#ffffff",border:R?`1px solid ${U.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:R?"0 10px 40px rgba(0, 0, 0, 0.5)":"0 10px 40px rgba(0, 0, 0, 0.12)",zIndex:Vn.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${Ut.out}`},children:a(bd,{appName:e,status:t,statusLabel:n,totalUsdValue:re,breakdownSubtitle:_,address:h?be:v,spiceAssets:z,spiceAssetsLoading:V,pendingDeposits:O,customSections:o,onDepositClick:p?N:void 0,onWithdrawClick:u?ae:void 0,onCompleteDeposit:we,primaryColor:Q,dk:U,dark:R,showModeToggle:h,isEmbeddedMode:he,onModeToggle:q,showConnectExternalCta:oe,onConnectExternalWallet:Ce,connectExternalError:ue})}),a("style",{children:`
|
|
103
|
+
`})]})},Ml="0xa9059cbb";function Rl(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const o=Re(n.token),s=Re(n.to),r=`${o.toLowerCase()}:${s.toLowerCase()}`,i=t.get(r);i?i.amount+=n.amount:t.set(r,{token:o,to:s,amount:n.amount})}return[...t.values()]}function Dl(e,t){return`0x${t}${e.slice(4)}`}function Wl(e,t,n){if(!Array.isArray(e))return 0n;const o=`evm:${t}:${n.slice(2).toLowerCase()}`;let s=0n;for(const r of e){if(!r||typeof r!="object")continue;const i=r,l=i.chainTokens;if((Array.isArray(l)?l.filter(c=>typeof c=="string"):l&&typeof l=="object"?Object.keys(l):[]).some(c=>c.toLowerCase()===o))try{s+=BigInt(i.balanceAvailable??"0")}catch{}}return s}async function zr(e,t,n,o){const s=await fetch(`${e}/wallets/${t}/balance`,{cache:"no-store"});if(!s.ok)throw new Error(`Failed to fetch spice balance: ${s.status}`);const r=await s.json();return Wl(r?.balances,n,o)}async function Nl({apiBaseUrl:e,user:t,chainId:n,tokenAddress:o,prevBalance:s,timeoutMs:r=3e4,pollIntervalMs:i=1500}){const l=Date.now()+r;for(await new Promise(c=>setTimeout(c,800));Date.now()<l;){try{if(await zr(e,t,n,o)>s)return}catch(c){console.warn("[SpiceLockModal] spice balance poll failed:",c?.message)}await new Promise(c=>setTimeout(c,i))}console.warn("[SpiceLockModal] Spicenet indexer did not reflect deposit within timeout; proceeding with intent")}function Es(e,t){return Lr(e,t)}function Lr(e,t,n){const o=Pl(t,e),s=Math.floor(Date.now()/1e3)+60*10,r=Pn(o);return{user:e,...n?{chainAuthorizations:n}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:"0x00",nbf:0,exp:s,chainBatches:r.map((i,l)=>({hash:i.hash,chainId:i.chainId,tokenTransfers:o[l].domain==="spicenet"?[]:o[l].tokenTransfers??[],calls:i.calls}))}]}}function Pl(e,t){return e.map(n=>{if(n.domain==="spicenet"||n.calls.length===0)return n;const o=new Set((n.tokenTransfers??[]).filter(r=>(r.from==="escrow"||r.from==="solver")&&Re(r.to).toLowerCase()===t.toLowerCase()).map(r=>Re(r.token).toLowerCase()));if(o.size===0)return n;let s=0;for(const r of n.calls){if(!r.data?.startsWith(Ml))break;try{const i=xo({abi:Xe,data:r.data});if(i.functionName!=="transfer")break;const[l]=i.args;if(l.toLowerCase()===t.toLowerCase()||!o.has(Re(r.to).toLowerCase()))break;s+=1}catch{break}}return s===0?n:{...n,calls:n.calls.slice(s)}})}function No(e,t,n){if(e.some(c=>c.domain==="spicenet"))return e;const o=n?.intents.flatMap(c=>c.batches),s=c=>c.from==="escrow",r=e.map(c=>{const d=o?.find(y=>y.chainId===c.chainId);if(!d)return c;const p=Mn(d).totalFee;if(p<=0n)return c;const u=(c.tokenTransfers??[]).find(y=>s(y)&&Re(y.to).toLowerCase()===t.toLowerCase()&&!Qe(Re(y.token)));if(!u)return c;const f=Re(u.token);let h=!1;const m=(c.tokenTransfers??[]).map(y=>h||!s(y)||Re(y.to).toLowerCase()!==t.toLowerCase()||Re(y.token).toLowerCase()!==f.toLowerCase()?y:(h=!0,{...y,amount:BigInt(y.amount)+p}));return h?{...c,tokenTransfers:m,calls:[{to:f,value:0n,data:gt({abi:Xe,functionName:"transfer",args:[Yn,p]})},...c.calls]}:c}),i=r.flatMap(c=>(c.tokenTransfers??[]).filter(s).map(d=>{const p=Re(d.token),u=Re(d.to),f=[{token:p,to:u,amount:BigInt(d.amount)}];return{chainId:c.chainId,transfers:Rl(f)}}));if(i.length===0)return e;const l=BigInt(Math.floor(Date.now()/1e3))+3600n;return[{chainId:Ta,domain:"spicenet",tokenTransfers:[],calls:i.map((c,d)=>{const p=so(ro([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,c.transfers[0].token,c.transfers.reduce((f,h)=>f+h.amount,0n),BigInt(c.chainId),BigInt(Date.now()+d)])),u=Dl(p,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:gt({abi:Go,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${c.chainId}`,idempotenceKey:u,nbf:0n,exp:l,metadata:"{}",transfers:c.transfers.map(f=>({token:f.token.toLowerCase(),to:f.to,amount:f.amount}))}]})}})},...r]}function Po(e,t){const n=e.selectedAsset?.asset;if(!n||!e.selectedAsset?.amount)throw new Error("Select an asset and enter an amount");const o=t?.netAmount??Ge(e.selectedAsset.amount,n.decimals),s=t?.grossAmount??o;return e.resolveLockBatches({amount:xt(o,n.decimals),amountWei:o,grossAmount:xt(s,n.decimals),grossAmountWei:s})}async function Or(e,t,n){const o=[...new Set(n.filter(r=>r.domain!=="spicenet").map(r=>r.chainId))],s=[];for(const r of o){const i=dt(r),l=oo(r),c=await Xo(t,i),d=await e.actions.signAuthorization({contractAddress:l,chainId:r,nonce:Number(c)});s.push(d)}return s}async function Hr(e,t,n){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 s=n??await Or(e,o,t),r=Pn(t),i=Math.floor(Date.now()/1e3)+60*10,l=r.map(h=>h.hash),c=so(ro([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,BigInt(i),l])),d=await e.actions.signMessage({raw:c}),p=typeof d=="string"?d:d.signature;if(!p)throw new Error("Failed to sign intent authorization");const u={mode:"7702",signatureType:"ecdsa",signature:p,nbf:0,exp:i,chainBatches:r.map((h,m)=>{const y=t[m],C=y.domain==="spicenet";return{hash:h.hash,chainId:h.chainId,tokenTransfers:C?[]:y.tokenTransfers??[],calls:h.calls}})},f=await ft.createAction({user:o,chainAuthorizations:s.map(h=>({r:h.r,s:h.s,yParity:h.yParity,address:h.address,chainId:Number(h.chainId),nonce:Number(h.nonce)})),intents:[u]});if(f){const h=Vo(t,$t),[m,y]=f.intentIds[0].split("/"),C=parseInt(y||"0",10),x=f.intentIds[0];e.startStatusPolling(f.intentIds[0],h),await Ir({actionId:m,intentIndex:C,intentId:x,totalSteps:t.length,isSpicenetStep:w=>t[w]?.domain==="spicenet",maxExecuteAttemptsForStep:w=>t[w]?.domain==="spicenet"?6:3,maxPolls:180})}}async function jr(e){let t=Po(e);if(t.length===0)throw new Error("No lock batches configured");const n=e.isSemi7702&&e.providerEmbeddedAddress||e.address;if(!e.isConnected||!n)throw new Error("Please connect your wallet to continue");const o=await Or(e,n,t);let s=No([...t],n),r;for(let i=0;i<4;i+=1){const l=await ft.estimateActionFees(Lr(n,s,o.map(u=>({r:u.r,s:u.s,yParity:u.yParity,address:u.address,chainId:Number(u.chainId),nonce:Number(u.nonce)})))),c=Wo(l,{symbol:e.selectedAsset?.asset.symbol??"",decimals:e.selectedAsset?.asset.decimals??18});if(!c)break;const d={grossAmount:c.grossAmount,netAmount:c.netAmount,feeAmount:c.totalFee??0n},p=r?.grossAmount===d.grossAmount&&r?.netAmount===d.netAmount&&r?.feeAmount===d.feeAmount;if(r=d,t=Po(e,r),s=No([...t],n,l),p)break}await Hr(e,s,o)}async function Ul(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,n=Ge(e.selectedAsset.amount,t.decimals),o=e.escrowAddress||oo(e.lockChainId),s=ft.getBaseUrl(),r=It(t.address);let i=0n;try{i=await zr(s,e.embeddedWalletAddress,e.lockChainId,r)}catch(u){console.warn("[SpiceLockModal] could not snapshot spice balance pre-deposit:",u?.message)}const l=await e.actions.getEthereumProvider();await Qn(l,e.lockChainId);const c=Me(e.lockChainId),d=Un({account:e.embeddedWalletAddress,transport:zn(l),chain:c?.viemChain});let p;if(t.isNative||Qe(t.address))p=await d.sendTransaction({to:o,value:n,chain:c?.viemChain});else{const u=gt({abi:Xe,functionName:"transfer",args:[o,n]});p=await d.sendTransaction({to:t.address,data:u,chain:c?.viemChain})}if((await dt(e.lockChainId).waitForTransactionReceipt({hash:p,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to escrow failed");await Nl({apiBaseUrl:s,user:e.embeddedWalletAddress,chainId:e.lockChainId,tokenAddress:r,prevBalance:i}),await e.refreshSpiceAssets(),e.refreshWalletAssets(),await jr(e)}async function zl(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 w=e.resolveLockBatches();if(w.length===0)throw new Error("No lock batches configured");const b=e.selectedAsset.asset,k=Ge(e.selectedAsset.amount,b.decimals),I=await e.onLockExecute({asset:b,amount:e.selectedAsset.amount,amountWei:k,lockDurationMonths:e.selectedDuration?.months??0,chainBatches:w});I&&e.onLockSuccess?.(I);return}const n=e.resolveLockBatches();if(n.length===0)throw new Error("No lock batches configured");const o=e.selectedAsset.asset,s=Ge(e.selectedAsset.amount,o.decimals),r=o.chainId,i=e.escrowAddress||Cn(r),l=It(o.address),c=o.isNative||Qe(l);let d=null;for(const w of n){const b=w.tokenTransfers?.find(k=>k.from==="escrow");if(b){d={batch:w,to:b.to,token:b.token,amount:BigInt(b.amount)};break}}const p=await e.externalWallet.getEthereumProvider();let u=null;try{const w=await p.request({method:"eth_chainId"});u=parseInt(w,16)}catch{u=null}u!==r&&await Qn(p,r);const f=Me(r),h=Un({account:e.externalWalletAddress,chain:f?.viemChain,transport:zn(p)}),m=c?await h.sendTransaction({to:t,value:s,chain:f?.viemChain}):await h.sendTransaction({to:l,data:gt({abi:Xe,functionName:"transfer",args:[t,s]}),chain:f?.viemChain});if((await dt(r).waitForTransactionReceipt({hash:m,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to embedded wallet failed");const y={chainId:r,calls:c?[{to:i,value:s,data:"0x"}]:[{to:l,value:0n,data:gt({abi:Xe,functionName:"transfer",args:[i,s]})}]};let C=null;if(d){if(!e.buildSpicenetBatch)throw new Error("Lock batches declare an escrow-backed ERC20 payout but no `buildSpicenetBatch` callback was provided. The relayer rejects 7702 intents with escrow-backed ERC20 transfers unless the intent includes a Spicenet batch authorising the withdrawal.");const w=e.buildSpicenetBatch({userAddress:t,destinationChainId:d.batch.chainId,deliveryToken:d.token,deliveryAmount:d.amount,deliveryRecipient:d.to});w&&(C={...w,domain:w.domain??"spicenet"})}const x=[y];C&&x.push(C),x.push(...n),await Hr(e,x)}async function Ll(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");const l=e.resolveLockBatches();if(l.length===0)throw new Error("No lock batches configured");const c=e.selectedAsset.asset,d=Ge(e.selectedAsset.amount,c.decimals),p=c.chainId,u=e.escrowAddress||Cn(p),f=It(c.address),h=c.isNative||Qe(f);let m=null;for(const b of l){const k=b.tokenTransfers?.find(I=>I.from==="escrow");if(k){m={batch:b,to:k.to,token:k.token,amount:BigInt(k.amount)};break}}const y={chainId:p,calls:h?[{to:u,value:d,data:"0x"}]:[{to:f,value:0n,data:gt({abi:Xe,functionName:"transfer",args:[u,d]})}]};let C=null;if(m){if(!e.buildSpicenetBatch)throw new Error("Lock batches declare an escrow-backed payout but no `buildSpicenetBatch` callback was provided.");const b=e.buildSpicenetBatch({userAddress:i,destinationChainId:m.batch.chainId,deliveryToken:m.token,deliveryAmount:m.amount,deliveryRecipient:m.to});b&&(C={...b,domain:b.domain??"spicenet"})}const x=[y];C&&x.push(C),x.push(...l);const w=await ft.estimateActionFees(Es(i,x));return Wo(w,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals})}const t=e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");let n=Po(e);if(n.length===0)throw new Error("No lock batches configured");let o=No([...n],t),s=null;for(let i=0;i<4;i+=1){const l=await ft.estimateActionFees(Es(t,o)),c=Wo(l,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals});if(!c)return null;const d={grossAmount:c.grossAmount,netAmount:c.netAmount},p=s?.grossAmount===c.grossAmount&&s?.netAmount===c.netAmount&&s?.totalFee===c.totalFee;if(s=c,n=Po(e,d),o=No([...n],t,l),p)break}if(s)return s;const r=await ft.estimateActionFees(Es(t,o));return Wo(r,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals})}async function Ol(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.resolveLockBatches();if(t.length===0)throw new Error("No lock batches configured");const n=t.find(d=>d.chainId===e.lockChainId)||t[0];if(!n)throw new Error("No lock batch for lock chain");const o=await e.externalWallet.getEthereumProvider();let s=null;try{const d=await o.request({method:"eth_chainId"});s=parseInt(d,16)}catch{s=null}s!==e.lockChainId&&await Qn(o,e.lockChainId);const r=Me(e.lockChainId),i=Un({account:e.externalWalletAddress,chain:r?.viemChain,transport:zn(o)}),l=dt(e.lockChainId);let c;for(const d of n.calls){const p=await i.sendTransaction({to:d.to,data:d.data,value:d.value,chain:r?.viemChain});if((await l.waitForTransactionReceipt({hash:p,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Lock transaction failed");c=p}c&&e.onLockSuccess?.(c)}async function Hl(e){if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance. Add more assets.");return}e.ui.setIsExecuting(!0),e.ui.setError(null);const t=n=>{console.error("[SpiceLockModal] lock failed:",n);const o=mn(n,""),s=typeof n?.shortMessage=="string"?n.shortMessage:typeof n?.message=="string"?n.message:"";e.ui.setError(o||s||"Transaction failed. Please try again.")};if(e.isSemi7702){if(e.isSourceDestToken){try{await Ol(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{await zl(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{e.isDirectDeposit&&!e.isSourceDestToken?await Ul(e):await jr(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}}const Qr=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,lockBatches:o,lockTokenSymbol:s,lockTokenLogoURI:r,destinationInputHook:i,sourceAssetInputHook:l,lockDurationHook:c,lockChainId:d,durationOptions:p,votingPowerEstimate:u,escrowAddress:f,includeWalletAssets:h=!1,destinationTokenAddress:m,onLockSuccess:y,onLockExecute:C,sourceToDestinationConversionRate:x,estimatedOutputAmount:w,onAddFunds:b,buildSpicenetBatch:k,styles:I,dark:S=!1})=>{const{theme:E,dark:A,primaryColor:F,dk:v}=at(I,S),M=E.typography.fontFamily,B=Bt(kt),D=(B?.mode||"7702")!=="7702",R=ne(()=>B?.supportedChainIds??[],[B?.supportedChainIds]),Q=ne(()=>{const Y=B?.allowedTokens;if(!Y||Y.length===0)return[];const ce=new Set(Y.map(_e=>_e.toLowerCase())),Le=[],Ee=new Set;for(const _e of R){const He=Me(_e);for(const Ye of He?.supportedTokens??[]){if(!ce.has(Ye.symbol.toLowerCase()))continue;const rt=`${_e}:${Ye.address.toLowerCase()}`;Ee.has(rt)||(Ee.add(rt),Le.push(Re(Ye.address)))}}return Le},[B?.allowedTokens,R]),U=A?v.cardBg:I?.assetSelector?.backgroundColor||I?.secondaryBackground||"#e9e9e9",L=A?`1px solid ${v.cardBorder}`:"0.5px solid #A8A8A7",P=A?"12px":"6px",V=A?v.textPrimary:"#111827",z=A?v.textSecondary:"#6b7280",te=ne(()=>({...I,assetSelector:{...I?.assetSelector,backgroundColor:A?v.cardBg:I?.assetSelector?.backgroundColor,borderRadius:A?"12px":I?.assetSelector?.borderRadius},secondaryBackground:A?v.cardBg:I?.secondaryBackground}),[I,A]),O=ne(()=>A?{...E,colors:{...E.colors,secondary:v.cardBg,surfaceHover:v.hoverBg,border:v.cardBorder,borderHover:v.inputBorder}}:E,[A,E]),[W,re]=T(null),[_,de]=T(0),ke=c?.selectedDurationIdx??_,Be=c?.setSelectedDurationIdx??de,[Z,he]=T(!1),[be,q]=T(null),[ue,j]=T(null),[ee,Ce]=T(!1),[oe,N]=T(!1),[ae,we]=T(null),[De,We]=T(!1),pe=ie(0),[Ke,X]=T(!1),[qe,xe]=T(null);Os(),qo();const{chain:it,address:Ae}=Nn();Sa();const wt=ie(it);K(()=>{wt.current=it},[it]);const qt=kn(),{isReady:Ft,isAuthenticated:Ne,isConnected:Ct,address:zt,provider:Lt,actions:Gt}=qt,{externalWallet:nn,embeddedAddress:Dn,externalAddress:Mt}=uo(),{intentStatus:Fe,startStatusPolling:Ot,clearStatus:ct}=sr({checkStepStatus:(Y,ce)=>ft.checkStepStatus(Y,ce),retryStep:async(Y,ce)=>{const[Le,Ee]=Y.split("/"),_e=parseInt(Ee||"0",10);await ft.executeStep(Le,_e,ce,{action:"execute"})},maxRetries:3}),{assets:Rt,refetch:ut}=po({address:zt,supportedChains:R,enabled:Ct&&!D,refetchInterval:3e4}),pt=ne(()=>{if(Q.length===0)return Rt;const Y=new Set(Q.map(ce=>ce.toLowerCase()));return Rt.filter(ce=>Y.has(ce.address.toLowerCase()))},[Rt,Q]),cn=vn(),mt=D?Ae||Mt:cn,fe=ne(()=>{if(!h)return[];const Y=new Set,ce=[],Le=Ee=>{if(!Ee)return;const _e=Ee.toLowerCase();Y.has(_e)||(Y.add(_e),ce.push(Re(Ee)))};if(m&&Le(m),D)for(const Ee of Q)Le(Ee);return ce},[h,D,m,Q]),tt=ne(()=>fe.map(Y=>Y.toLowerCase()).sort().join(","),[fe]),on=ne(()=>JSON.stringify([...R||[]].sort()),[R]),[St,Ie]=T([]),Dt=ie(0),ht=le(async()=>{if(!h||!mt||fe.length===0){Dt.current++,Ie([]);return}const Y=++Dt.current,ce=Re(mt),Le=R&&R.length>0?R:[d],Ee=fe.map(st=>{const et=st.toLowerCase();for(const H of Le){const G=Me(H)?.supportedTokens?.find(ge=>je(ge.address,et));if(G)return{address:st,chainId:H,configToken:{decimals:G.decimals,symbol:G.symbol,name:G.name,logo:G.logo}}}return{address:st,chainId:d}}),_e=new Map;for(const st of Ee){const et=_e.get(st.chainId)||[];et.push(st),_e.set(st.chainId,et)}const He=async(st,et)=>{try{const H=await yn(st,{address:et.address,abi:Xe,functionName:"balanceOf",args:[ce]});let G,ge,se,me;if(et.configToken)G=et.configToken.decimals,ge=et.configToken.symbol,se=et.configToken.name,me=et.configToken.logo;else{const[an,Vt,Pt]=await Promise.all([yn(st,{address:et.address,abi:Xe,functionName:"decimals",args:[]}).catch(()=>18),yn(st,{address:et.address,abi:Xe,functionName:"symbol",args:[]}).catch(()=>"TOKEN"),yn(st,{address:et.address,abi:Xe,functionName:"name",args:[]}).catch(()=>"TOKEN")]);G=Number(an),ge=Vt,se=Pt}const Pe=!!m&&je(et.address,m)&&et.chainId===d;Pe&&r&&(me=r),Pe&&s&&!et.configToken&&(ge==="TOKEN"&&(ge=s),se==="TOKEN"&&(se=s));const Qt=parseFloat((Number(H)/Math.pow(10,G)).toFixed(6));return{address:et.address,name:se,symbol:ge,decimals:G,balance:H,balanceFormatted:Qt,balanceUsd:0,logoURI:me,isNative:!1,chainId:et.chainId}}catch{return null}},Ye=await Promise.all(Array.from(_e.entries()).map(async([st,et])=>{let H;try{H=dt(st)}catch{return[]}const G=[],ge=[];for(const me of et){const Pe=G.length;G.push({address:me.address,abi:Xe,functionName:"balanceOf",args:[ce]}),me.configToken||G.push({address:me.address,abi:Xe,functionName:"decimals",args:[]},{address:me.address,abi:Xe,functionName:"symbol",args:[]},{address:me.address,abi:Xe,functionName:"name",args:[]}),ge.push({start:Pe,item:me})}let se=null;try{se=await H.multicall({contracts:G})}catch{se=null}return se?ge.map(({start:me,item:Pe})=>{const Qt=se[me],an=Qt?.status==="success"?Qt.result:0n;let Vt,Pt,ye,Oe;if(Pe.configToken)Vt=Pe.configToken.decimals,Pt=Pe.configToken.symbol,ye=Pe.configToken.name,Oe=Pe.configToken.logo;else{const Jt=se[me+1],fn=se[me+2],wn=se[me+3];Vt=Jt?.status==="success"?Number(Jt.result):18,Pt=fn?.status==="success"?fn.result:"TOKEN",ye=wn?.status==="success"?wn.result:Pt}const Kt=!!m&&je(Pe.address,m)&&Pe.chainId===d;Kt&&r&&(Oe=r),Kt&&s&&!Pe.configToken&&(Pt==="TOKEN"&&(Pt=s),ye==="TOKEN"&&(ye=s));const hn=parseFloat((Number(an)/Math.pow(10,Vt)).toFixed(6));return{address:Pe.address,name:ye,symbol:Pt,decimals:Vt,balance:an,balanceFormatted:hn,balanceUsd:0,logoURI:Oe,isNative:!1,chainId:Pe.chainId}}):(await Promise.all(et.map(me=>He(H,me)))).filter(me=>me!==null)}));if(Y!==Dt.current)return;const rt=Ye.flat();Ie(rt)},[h,mt,tt,on,d,m,r,s]);K(()=>{if(!h){Ie([]);return}ht();const Y=setInterval(()=>{ht()},15e3);return()=>clearInterval(Y)},[ht,h]);const Ze=le(()=>{ht()},[ht]),bn=ne(()=>St.filter(Y=>Y.balance>0n),[St]),Wt=ne(()=>{if(D)return bn.map(ce=>({...ce,_source:"wallet"}));if(!h)return pt;const Y=[];for(const ce of bn)Y.push({...ce,_source:"wallet"});for(const ce of pt)Y.push({...ce,_source:"spice"});return Y},[D,h,bn,pt]),sn=ie(null),un=ie(null);K(()=>{un.current=W},[W]),K(()=>{e||(re(null),q(null),j(null),Ce(!1),N(!1),we(null),he(!1),X(!1),xe(null),We(!1),ct())},[e,ct]),K(()=>{i&&i.assetAmount!==(W?.amount||"")&&re(Y=>Y&&{...Y,amount:i.assetAmount})},[i?.assetAmount]),K(()=>{l&&l.assetAmount!==(W?.amount||"")&&re(Y=>Y&&{...Y,amount:l.assetAmount})},[l?.assetAmount]),K(()=>{if(!D&&Fe?.overallStatus==="success"&&Fe.intentId&&sn.current!==Fe.intentId&&zt&&Fe.steps.find(Y=>Y.transactionHash)?.transactionHash){sn.current=Fe.intentId;const Y=un.current;if(!Y?.asset||!Y.amount||Y.asset._source==="wallet"||Ge(Y.amount,Y.asset.decimals)===0n)return;ut()}},[Fe,zt,d,ut,D]);const Je=parseFloat(W?.amount||"")||0,Te=ne(()=>W?.asset?W.asset._source==="wallet"?W.asset.balanceFormatted??0:pt.find(Y=>je(Y.address,W.asset.address)&&Y.chainId===W.asset.chainId)?.balanceFormatted??0:0,[W?.asset,pt]),vt=Je>0&&(ae?parseFloat(xt(ae.grossAmount,ae.decimals))>Te:Je>Te),lt=c?.selectedDuration??p[ke]??p[0],nt=ne(()=>!W?.asset||!m?!1:je(W.asset.address,m)&&W.asset.chainId===d,[W?.asset,m,d]),ot=ne(()=>Je<=0?0:nt?Je:!x||x<=0?0:Je/x,[Je,x,nt]),Ht=ne(()=>ot<=0?null:ot.toLocaleString(void 0,{maximumFractionDigits:2}),[ot]),yt=u&&ot>0&<?u(ot,lt.months):void 0,At=ne(()=>Je<=0?"$0.00":nt&&x?(Je*x).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!x||x<=0?"$0.00":Je.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[Je,x,nt]),Nt=ne(()=>{if(!Ht)return null;const Y=parseFloat(Ht.replace(/,/g,""));return nt&&x?(Y*x).toLocaleString(void 0,{maximumFractionDigits:2}):x?(Y*x).toLocaleString(void 0,{maximumFractionDigits:2}):null},[Ht,x,nt]),jt=le(Y=>{re(ce=>({asset:Y,amount:ce?.asset?.address===Y.address&&ce?.asset?.chainId===Y.chainId&&ce.amount||""})),q(null),j(null),N(!1),we(null),l?.setSelectedAsset&&l.setSelectedAsset({symbol:Y.symbol,address:Y.address,decimals:Y.decimals,chainId:Y.chainId})},[l?.setSelectedAsset]),rn=le(Y=>{re(ce=>ce&&{...ce,amount:Y}),q(null),j(null),N(!1),we(null),i&&i.setAssetAmount(Y),l&&l.setAssetAmount(Y)},[i,l]),In=le(Y=>{if(typeof o=="function"){if(!W?.asset||!W.amount)throw new Error("Select an asset and enter an amount");return o({asset:W.asset,amount:Y?.amount??W.amount,amountWei:Y?.amountWei??Ge(W.amount,W.asset.decimals),grossAmount:Y?.grossAmount,grossAmountWei:Y?.grossAmountWei,feeAdjusted:!!Y})}return o},[o,W]),ze=ie(null),Et=ne(()=>!W?.asset||Je<=0?!1:D?!nt&&!C:!0,[W,Je,D,nt,C]),pn=le(()=>Ll(ze.current),[]);K(()=>{if(!e||Z)return;if(!W?.asset||Je<=0){j(null),Ce(!1),N(!1),we(null);return}if(!Et){j(null),Ce(!1),N(!0),we(null);return}let Y=!1;const ce=async()=>{const _e=++pe.current;j(null),N(!1),Ce(!0);try{const He=await pn();if(Y||pe.current!==_e)return;j(null),N(!0),we(He)}catch(He){if(Y||pe.current!==_e)return;j(mn(He,"Unable to calculate fees for this lock.")),N(!1)}finally{!Y&&pe.current===_e&&Ce(!1)}},Le=window.setTimeout(()=>{ce()},250),Ee=window.setInterval(()=>{ce()},1e4);return()=>{Y=!0,clearTimeout(Le),window.clearInterval(Ee),Ce(!1),N(!1)}},[e,Z,W,Je,Et,pn]),K(()=>{if(Fe?.overallStatus==="success"){const Y=Fe.steps.find(ce=>ce.transactionHash);y?.(Y?.transactionHash)}},[Fe?.overallStatus,y]);const Yt=h&&W?.asset?._source==="wallet"&&W?.asset?.chainId===d,J=le(()=>Hl(ze.current),[]),$=!!W?.asset&&Je>0&&!vt&&!Z&&(!Et||oe&&!ee&&!ue),ve=be||ue,Ve=g("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[a(fs,{color:z}),g("p",{style:{fontSize:"13px",color:z,margin:0,lineHeight:"1.5"},children:["Add ",s," by converting assets from your account"]})]});if(ze.current={selectedAsset:W,parsedAmount:Je,selectedDuration:lt,isInsufficientBalance:vt,isSemi7702:D,isSourceDestToken:nt,isDirectDeposit:Yt,requiresRelayerFeeEstimate:Et,address:zt,embeddedWalletAddress:cn,providerEmbeddedAddress:Dn,externalWallet:nn,externalWalletAddress:Ae,isConnected:Ct,ready:Ft,authenticated:Ne,provider:Lt,actions:Gt,lockChainId:d,escrowAddress:f,onLockExecute:C,onLockSuccess:y,buildSpicenetBatch:k,resolveLockBatches:In,startStatusPolling:Ot,refreshSpiceAssets:ut,refreshWalletAssets:Ze,ui:{setError:q,setIsExecuting:he,setShowStatusPanel:We}},!e)return null;const $e={backgroundColor:U,border:L,borderRadius:P,padding:"16px",marginBottom:"16px"};return a(En,{isOpen:e,onClose:t,title:`Add ${s} to your account`,subtitle:Ve,styles:I,dark:A,footerLinkText:"Spicenet accounts \u2192",overlayContent:Ke?a("div",{}):void 0,closeOnBackdropClick:n,children:g("div",{style:{padding:"0 24px 8px 24px",position:"relative"},children:[g("div",{style:{marginBottom:"12px"},children:[b&&a("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:a(ms,{onClick:b,color:F,fontFamily:M})}),a("div",{style:{marginTop:"10px",fontSize:"13px",color:z,fontFamily:M},children:a(co,{assets:Wt,selectedAsset:W??void 0,onAssetSelect:jt,onAmountChange:rn,label:"Amount",showBalance:!0,showMaxButton:!0,theme:O,styles:te})}),a("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:z,fontFamily:M},children:At})]}),g("div",{style:$e,children:[g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:A?`1px solid ${v.cardBorder}`:"1px solid #e5e7eb"},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[r?a("img",{src:r,alt:s,style:{width:"32px",height:"32px",borderRadius:"50%",objectFit:"cover"}}):a("div",{style:{width:"32px",height:"32px",borderRadius:"50%",backgroundColor:A?v.inputBg:"#d1d5db",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:700,color:V},children:s.slice(0,2)}),a("span",{style:{fontSize:"16px",fontWeight:600,color:V,fontFamily:M},children:s})]}),g("div",{style:{textAlign:"right"},children:[a("div",{style:{fontSize:"22px",fontWeight:700,color:V,fontFamily:M,lineHeight:1.1},children:Ht??"0.00"}),g("div",{style:{fontSize:"12px",color:z,fontFamily:M,marginTop:"2px"},children:["~$",Nt??"0.00"]})]})]}),g("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:A?`1px solid ${v.cardBorder}`:"1px solid #e5e7eb"},children:[g("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[a("span",{style:{fontSize:"15px",fontWeight:500,color:z,fontFamily:M},children:"Lock Duration"}),a(Bn,{color:z})]}),a(Al,{options:p,selectedIndex:ke,onSelect:Be,primaryColor:F,dark:A,textPrimary:V,textSecondary:z})]}),g("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[a(Bl,{durationMonths:lt?.months,fontFamily:M,dark:A,textPrimary:V,textSecondary:z}),u&&a(Fl,{votes:yt,fontFamily:M,dark:A,textPrimary:V,textSecondary:z})]})]}),Et&&a(So,{fontFamily:M,textPrimary:V,textSecondary:z,cardBg:U,cardBorder:L,resolvedDark:A,darkCardBorder:v.cardBorder,primaryColor:F,feePreview:ae,isLoading:ee,errorText:ue}),ve&&a(to,{variant:"error",palette:v,fontFamily:M,style:{marginBottom:"12px"},children:ve}),a(bt,{variant:"outline",fullWidth:!0,onClick:J,disabled:!$,loading:Z,dark:A,styles:{...I,button:{...I?.button,backgroundColor:F}},children:Z?Yt&&!nt?"DEPOSITING...":nt?"LOCKING...":"CONVERTING...":ee&&Et?"CALCULATING FEES...":Yt&&!nt?`DEPOSIT ${s}`:nt?`LOCK ${s}`:`CONVERT TO ${s}`}),a(Tl,{isOpen:Ke,data:qe,isLocking:Z,lockError:ve,onContinue:J,onClose:()=>X(!1),primaryColor:F,fontFamily:M,dark:A}),Fe&&De&&a("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:A?v.shell:"white",borderRadius:P,padding:"16px 0"},children:a(ws,{type:"deposit",isOpen:!!Fe&&Fe.overallStatus!=="processing",isProcessing:Z||Fe?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{ct(),We(!1),J()},onNewTx:()=>{ct(),We(!1),re(null),sn.current=null,ut(),Ze()},onClose:()=>{ct(),We(!1)},onComplete:()=>{ct(),We(!1),re(null),sn.current=null,ut(),Ze()},results:Fe?.overallStatus==="success"||Fe?.overallStatus==="failed"?Fe.steps.map(Y=>({asset:{symbol:W?.asset?.symbol||s,address:W?.asset?.address||""},txHash:Y.transactionHash||"",success:Y.status==="success",amount:W?.amount})):void 0,chainName:$t(d),explorerUrl:Gn(d,"").replace(/\/tx\/.*$/,"")||void 0,theme:E,styles:I,dark:A})})]})})},jl="0xa9059cbb";function Ql(e,t,n,o){return t!=="user-transfer"||!n||e.length===0||e[0]?.to.toLowerCase()!==o.toLowerCase()||!e[0]?.data.startsWith(jl)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function Uo(e,t,n){if(!t)return[e];const o=await t(n);return o?[o,e]:[e]}function zo(e,t,n){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const o=10n**BigInt(t-n);return(e+o-1n)/o}async function Vl(e,t){const{currentPaymentAmount:n,destinationToken:o,embeddedWalletAddress:s,providerEmbeddedAddress:r,address:i,isNon7702:l,isPayMode:c,resolvedChainId:d,buildActionCalls:p,feeExecutionMode:u,buildSpicenetBatch:f,selectedAsset:h,needsSwap:m,exactOutputSwap:y,resolvedTokenIn:C}=e,x=Ge(n,o.decimals),w=t?.actionAmountOverride??x,b=s||r||(l?void 0:i);if(!b)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const k={userAddress:b,chainId:d,destinationToken:o.address,grossAmount:t?.fundingAmountOverride??x,netAmount:w,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:u,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},I=p(w,k),S={chainId:d,calls:I},E=(!c&&!l?!0:h?.asset?._source==="spice")||l,A=(F,v)=>({token:F,from:l?"solver":"escrow",to:b,amount:v});if(x===0n)return[S];if(m&&y){const F=C??Fn(h.asset,d)??h.asset.address,v=t?.fundingAmountOverride??y.amountInMax,M=E?[A(F,v)]:[],B={to:F,value:0n,data:gt({abi:_t,functionName:"approve",args:[y.calls[0]?.to,y.amountInMax]})},D={chainId:d,calls:[B,...y.calls,...I],tokenTransfers:[...M,...S.tokenTransfers??[]]};return E?Uo(D,f,{userAddress:b,destinationChainId:d,deliveryToken:F,deliveryAmount:v,deliveryRecipient:b,sourceAsset:h.asset}):[D]}if(E){const F=C??Fn(h.asset,d)??o.address,v=t?.fundingAmountOverride??x,M={...S,tokenTransfers:[A(F,v),...S.tokenTransfers??[]]};return Uo(M,f,{userAddress:b,destinationChainId:d,deliveryToken:F,deliveryAmount:v,deliveryRecipient:b,sourceAsset:h.asset})}return[S]}async function ql(e,t){const{selectedAsset:n,embeddedWalletAddress:o,resolvedChainId:s,destinationToken:r,buildActionCalls:i,feeExecutionMode:l,buildSpicenetBatch:c,isPayMode:d,isNon7702:p,needsSwap:u,resolvedSwap:f,quoteAmountOut:h,resolvedTokenIn:m}=e,y=f?.amountOutMinimum??h;if(!n?.asset||!o)return[];const C=t?.fundingAmountOverride??t?.actionAmountOverride??Ge(n.amount,n.asset.decimals),x=t?.fundingAmountOverride??C,w=t?.actionAmountOverride??C,b={userAddress:o,chainId:s,destinationToken:r.address,feeToken:l==="user-transfer"&&u&&m?m:r.address,grossAmount:x,netAmount:w,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:l,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},k=i(w,b);if(!(!d&&!p||n.asset?._source==="spice"))return[{chainId:s,calls:k}];const I=(A,F)=>({token:A,from:"escrow",to:o,amount:F});if(u){if(!m)throw new Error("Swap input token could not be resolved");if(!f||y===null)throw new Error("Swap quote not available yet")}if(u&&f&&y&&m){const A=i(t?.actionAmountOverride??y,{...b,netAmount:t?.actionAmountOverride??y}),{feeCall:F,remainingCalls:v}=Ql(A,l,u,b.feeToken),M={chainId:s,calls:[...F?[F]:[],...f.calls,...v],tokenTransfers:[I(m,x)]};return Uo(M,c,{userAddress:o,destinationChainId:s,deliveryToken:m,deliveryAmount:x,deliveryRecipient:o,sourceAsset:n.asset})}const S=m??Fn(n.asset,s)??r.address,E={chainId:s,calls:k,tokenTransfers:[I(S,x)]};return Uo(E,c,{userAddress:o,destinationChainId:s,deliveryToken:S,deliveryAmount:x,deliveryRecipient:o,sourceAsset:n.asset})}async function Yl(e,t,n,o,s){let r=e;for(let i=0;i<4;i++){const l=await t(r),c=await o(l,n,r,s),d=dl(c);if(d===null||d>=e)return r;const p=r-d,u=e+p;if(u<=r)return r;r=u}return r}function Kl(e,t,n,o){if(e<=0n)return 0n;const s=e-t;if(s<=0n)return 0n;const r=o+n;return r<=0n?s:s*o/r}function Zl(e,t){const n=xt(e,t);return n.includes(".")?n.replace(/\.?0+$/,"")||"0":n}async function Xl(e){const{asset:t,isPayMode:n,isNon7702:o,needsSwap:s,isQuoting:r,embeddedWalletAddress:i,buildSupplyChainBatches:l,estimateGasless:c,executionTokenAddress:d,feeExecutionMode:p}=e;if(n||o||s||r||!i||t.balance<=0n)return null;const u=await l({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(u.length===0)return null;const f=u.some(x=>x.tokenTransfers?.length),h=await c(u,d,t.balance,f?{useCustomTransfers:!0,feeExecutionMode:p}:p?{feeExecutionMode:p}:void 0),m=Zn(h,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),y=m?zo(m.gasFee,m.decimals,t.decimals):0n,C=m?zo(m.spicenetFee,m.decimals,t.decimals):0n;return Zl(Kl(t.balance,y,C,t.balance),t.decimals)}async function Gl(e){const{selectedAsset:t,isPayMode:n,parsedAmount:o,needsSwap:s,exactOutputSwap:r,isNon7702:i,isSourceDestToken:l,currentPaymentAmount:c,destinationToken:d,feeExecutionMode:p,resolvedTokenIn:u,embeddedWalletAddress:f,providerEmbeddedAddress:h,resolvedChainId:m,isConnected:y,address:C,ready:x,authenticated:w,isDirect:b,resolvedSwap:k,isQuoting:I,executionTokenAddress:S,buildPayChainBatches:E,buildSupplyChainBatches:A,estimateGasless:F,estimateRequiredGrossFunding:v}=e;if(!t?.asset)return null;if(n){if(o<=0||s&&!r||i&&l)return null;const Q=Ge(c,d.decimals),U=u||Fn(t.asset,m)||t.asset.address||d.address,L={chainId:m,tokenAddress:U,symbol:Xt(U,m)?.symbol??t.asset.symbol,decimals:Xt(U,m)?.decimals??t.asset.decimals};if(i){const re=f||h;if(!re)return null;const _=s?r?.amountInMax??0n:Q;if(_===0n)return null;const de=await v(_,Z=>E({fundingAmountOverride:Z}),U,{userOverride:re,useCustomTransfers:!0}),ke=await E({fundingAmountOverride:de}),Be=await F(ke,U,de,{userOverride:re,useCustomTransfers:!0,feeExecutionMode:p});return Zn(Be,L)}if(!y||!C||!x||!w)return null;const P=s?r?.amountInMax??0n:Q;if(P===0n)return null;const V=await v(P,re=>E({fundingAmountOverride:re}),U,{useCustomTransfers:!0});let z=await E({fundingAmountOverride:V});const te=await F(z,U,V,{useCustomTransfers:!0,feeExecutionMode:p}),O=Zn(te,L)?.grossAmount??V;O!==V&&(z=await E({fundingAmountOverride:O}));const W=await F(z,U,O,{useCustomTransfers:!0,feeExecutionMode:p});return Zn(W,L)}if(o<=0||!f||!b&&!k&&!I||I)return null;const M=Ge(t.amount,t.asset.decimals),B=await A();if(B.length===0)return null;const D=B.some(Q=>Q.tokenTransfers?.length),R=await F(B,S,M,D?{useCustomTransfers:!0,feeExecutionMode:p}:p?{feeExecutionMode:p}:void 0);return Zn(R,{chainId:m,tokenAddress:S,symbol:Xt(S,m)?.symbol??d.symbol,decimals:Xt(S,m)?.decimals??d.decimals})}async function Jl(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.embeddedWalletAddress){e.ui.setError("Wallet not ready");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.ui.setTxHash(null),e.refs.spiceDepositSubmittedRef.current=!1;const t=new AbortController;e.refs.abortControllerRef.current=t;try{const n=Ge(e.selectedAsset.amount,e.selectedAsset.asset.decimals),o=n;let s=await e.gasless.buildSupplyChainBatches();if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!s.some(p=>yo(p.chainId)))throw new Error("Spice-funded supplies must include a Spicenet funding batch before the destination chain batch.");const r=s.some(p=>p.tokenTransfers?.length)?{useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}:e.feeExecutionMode?{feeExecutionMode:e.feeExecutionMode}:void 0;let i=n;const l=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,c=e.feeExecutionMode==="user-transfer"&&!l?o:void 0;let d;for(let p=0;p<4;p+=1){const u=await e.gasless.estimateGasless(s,e.executionTokenAddress,i,r),f=Zn(u,{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:Xt(e.executionTokenAddress,e.resolvedChainId)?.symbol??e.destinationToken.symbol,decimals:Xt(e.executionTokenAddress,e.resolvedChainId)?.decimals??e.destinationToken.decimals}),h=f?.grossAmount??i;if(d=e.feeExecutionMode==="user-transfer"&&f?{grossAmount:f.grossAmount,netAmount:o,combinedFeeAmount:f.totalFee,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:f.spicenetFee,gasFee:f.gasFee,bridgeFee:f.bridgeFee??0n}}:void 0,e.feeExecutionMode==="user-transfer"&&f){i=h;break}if(h===i){i=h;break}i=h,s=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:i,actionAmountOverride:c,actionContextOverride:d})}e.feeExecutionMode==="user-transfer"&&(s=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:i,actionAmountOverride:c,actionContextOverride:d})),await e.gasless.executeGasless(s,e.executionTokenAddress,i,e.gasless.onProgress,t.signal,r),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){const o=n instanceof Error?n:new Error(String(n));if(o.name==="AbortError"||t.signal.aborted){e.ui.setStep("idle");return}const s=o.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(s),e.ui.setError(s),e.onError?.(o)}finally{e.ui.setIsExecuting(!1)}}async function $l(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=Ge(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),n={userAddress:e.externalWalletAddress,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},o=e.buildActionCalls(t,n);if(o.length===0)throw new Error("No action calls configured");const s=await e.externalWallet.getEthereumProvider();let r=null;try{const p=await s.request({method:"eth_chainId"});r=parseInt(p,16)}catch{r=null}r!==e.resolvedChainId&&await Qn(s,e.resolvedChainId);const i=Me(e.resolvedChainId),l=Un({account:e.externalWalletAddress,chain:i?.viemChain,transport:zn(s)}),c=dt(e.resolvedChainId);let d;for(const p of o){const u=await l.sendTransaction({to:p.to,data:p.data,value:p.value,chain:i?.viemChain});if((await c.waitForTransactionReceipt({hash:u,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transaction failed");d=u}return d}async function _l(e){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const n=e.selectedAsset.asset,o=n.chainId,s=Ge(e.currentPaymentAmount,e.destinationToken.decimals),r=e.selectedIsEquivalent?s:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(r===0n)throw new Error("Quote not available yet");const i=e.resolvedTokenIn||e.selectedAsset.asset.address,l={userOverride:t,useCustomTransfers:!0},c=await e.gasless.estimateRequiredGrossFunding(r,w=>e.gasless.buildPayChainBatches({fundingAmountOverride:w}),i,l),d=Cn(o),p=await e.externalWallet.getEthereumProvider();let u=null;try{const w=await p.request({method:"eth_chainId"});u=parseInt(w,16)}catch{u=null}u!==o&&await Qn(p,o);const f=Me(o),h=Un({account:e.externalWalletAddress,chain:f?.viemChain,transport:zn(p)}),m=It(n.address),y=n.isNative||Qe(m)?await h.sendTransaction({to:d,value:c,chain:f?.viemChain}):await h.sendTransaction({to:m,data:gt({abi:_t,functionName:"transfer",args:[d,c]}),chain:f?.viemChain});if((await dt(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:c}),x=C.some(w=>w.tokenTransfers?.length);return await e.gasless.executeGasless(C,i,c,w=>{w.txHash&&(e.ui.setPaymentResult(b=>({...b??{status:"processing"},txHash:w.txHash})),e.ui.setTxHash(w.txHash))},void 0,x?l:{userOverride:t})}async function ed(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}if(!e.selectedAsset?.asset){e.ui.setError("Select a payment source");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.parsedAmount>0&&e.needsSwap&&!e.exactOutputSwap){e.ui.setError("Swap quote not available. Try a different asset.");return}if(e.isNon7702){if(!e.externalWalletAddress){e.ui.setError("Please connect your external wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{let t;if(e.isSourceDestToken||e.parsedAmount===0)t=await $l(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const n=e.selectedAsset.asset,o=Ge(e.currentPaymentAmount,e.destinationToken.decimals),s=e.selectedIsEquivalent?o:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(s===0n)throw new Error("Quote not available yet");const r=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!r)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const i=e.resolvedTokenIn||n.address,l=await e.gasless.estimateRequiredGrossFunding(s,p=>e.gasless.buildPayChainBatches({fundingAmountOverride:p}),i,{userOverride:r,useCustomTransfers:!0}),c=await e.gasless.buildPayChainBatches({fundingAmountOverride:l}),d=await e.onPayExecute({asset:n,amount:e.currentPaymentAmount,amountWei:o,destinationToken:e.destinationToken,chainBatches:c,requiredNetFunding:s,grossFundingAmount:l,selectedIsEquivalent:e.selectedIsEquivalent,resolvedTokenIn:i,exactOutputSwapAmountInMax:e.exactOutputSwap?.amountInMax});d&&(e.ui.setTxHash(d),e.ui.setPaymentResult(p=>({...p??{status:"processing"},txHash:d}))),t=d||void 0}else t=await _l(e);e.ui.setPaymentResult(n=>({status:"success",txHash:n?.txHash||t||""}))}catch(t){const n=mn(t,"Payment failed. Please try again.");e.ui.setError(n),e.ui.setPaymentResult({status:"failed",error:n}),e.onError?.(t instanceof Error?t:new Error(n))}finally{e.ui.setIsExecuting(!1)}return}if(!e.isConnected||!e.address){e.ui.setError("Please connect your wallet to continue");return}if(!e.ready||!e.authenticated){e.ui.setError(`Please authenticate with ${e.provider||"wallet provider"} to continue`);return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{const t=Ge(e.currentPaymentAmount,e.destinationToken.decimals),n=e.resolvedTokenIn||e.selectedAsset?.asset?.address||e.destinationToken.address,o=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:t,s={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode},r=await e.gasless.estimateRequiredGrossFunding(o,f=>e.gasless.buildPayChainBatches({fundingAmountOverride:f}),n,s);let i=r,l=await e.gasless.buildPayChainBatches({fundingAmountOverride:r});const c=await e.gasless.estimateGasless(l,n,r,s),d=Zn(c,{chainId:e.resolvedChainId,tokenAddress:n,symbol:Xt(n,e.resolvedChainId)?.symbol??e.selectedAsset.asset.symbol,decimals:Xt(n,e.resolvedChainId)?.decimals??e.selectedAsset.asset.decimals})?.grossAmount??r;d!==r&&(i=d,l=await e.gasless.buildPayChainBatches({fundingAmountOverride:d}));const p=l.some(f=>f.tokenTransfers?.length),u=await e.gasless.executeGasless(l,n,p?i:0n,f=>{f.txHash&&(e.ui.setPaymentResult(h=>({...h,txHash:f.txHash})),e.ui.setTxHash(f.txHash))},void 0,s);e.ui.setPaymentResult(f=>({status:"success",txHash:f?.txHash||u}))}catch(t){const n=mn(t,"Payment failed. Please try again.");e.ui.setError(n),e.ui.setPaymentResult({status:"failed",error:n}),e.onError?.(t instanceof Error?t:new Error(n))}finally{e.ui.setIsExecuting(!1)}}const Vr=({variant:e,destinationSymbol:t,destinationLogoURI:n,destinationDecimals:o,primaryColor:s,fontFamily:r,textPrimary:i,textSecondary:l,cardBg:c,cardBorder:d,dk:p,dark:u,isQuoting:f,quoteError:h,estimatedOutput:m,paymentAmount:y,needsSwap:C,exactOutputSwap:x,adjustable:w=!1,maxAmount:b,onAmountChange:k})=>e==="supply"?g("div",{style:{backgroundColor:c,border:`1px solid ${d}`,borderRadius:u?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",minHeight:"112px",display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[g("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"12px"},children:[g("div",{style:{minWidth:0},children:[a("span",{style:{fontFamily:r,fontSize:"17px",fontWeight:500,color:u?"#a7abb2":"#7D7C7B",lineHeight:"24px"},children:"Used in TX"}),a("div",{style:{fontSize:"12px",fontWeight:500,color:l,fontFamily:r,marginTop:"10px"},children:"Net amount after swap and fees"})]}),g("div",{style:{textAlign:"right",minWidth:0,display:"inline-flex",alignItems:"center",gap:"8px",border:`1px solid ${d}`,borderRadius:"8px",padding:"8px 10px",minHeight:"42px"},children:[a(qr,{symbol:t,logoURI:n,primaryColor:s,size:24}),a("span",{style:{fontSize:"16px",fontWeight:500,color:u?"#f3f4f6":"#3C3E42",lineHeight:"1.3",fontFamily:r,letterSpacing:0},children:t})]})]}),a("div",{style:{textAlign:"right",minWidth:0},children:f?a("span",{style:{fontSize:"18px",color:l,fontFamily:r},children:"Quoting..."}):h?a("span",{style:{fontSize:"13px",color:u?"#f87171":"#dc2626",fontFamily:r},children:"Quote failed"}):m?a(qn,{value:m,title:m,fontFamily:r,color:i,lineHeight:"0.95",textAlign:"right",maxFontSize:32,minFontSize:18}):a("span",{style:{fontSize:"20px",color:l,fontFamily:r},children:"\u2014"})})]}):a(td,{destinationSymbol:t,destinationLogoURI:n,destinationDecimals:o,primaryColor:s,fontFamily:r,textPrimary:i,textSecondary:l,cardBg:c,cardBorder:d,dk:p,dark:u,paymentAmount:y||"0",needsSwap:C,exactOutputSwap:x,isQuoting:f,adjustable:w,maxAmount:b,onAmountChange:k}),qr=({symbol:e,logoURI:t,primaryColor:n,size:o})=>t?a("img",{src:t,alt:e,style:{width:o,height:o,borderRadius:"50%",objectFit:"cover"}}):a("div",{style:{width:o,height:o,borderRadius:"50%",backgroundColor:`${n}22`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:o<30?"11px":"12px",fontWeight:700,color:n},children:e.slice(0,2)}),td=({destinationSymbol:e,destinationLogoURI:t,destinationDecimals:n,primaryColor:o,fontFamily:s,textPrimary:r,textSecondary:i,cardBg:l,cardBorder:c,dk:d,dark:p,paymentAmount:u,needsSwap:f,exactOutputSwap:h,isQuoting:m,adjustable:y,maxAmount:C,onAmountChange:x})=>{const w='"IBM Plex Mono", monospace',b=parseFloat(u||"0"),k=C?parseFloat(C):0,[I,S]=T(u||""),E=ie(null),[A,F]=T(null),[v,M]=T(null);K(()=>{y||S(u||"")},[u,y]);const B=Q=>{let U=Q;U.startsWith(".")&&(U="0"+U);const L=$n(U);let P=L;C&&parseFloat(L)>parseFloat(C)&&(P=C),S(P),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>x?.(P),300)},D=Q=>{if(!k)return;if(Q===100){S(C||k.toString()),E.current&&clearTimeout(E.current),x?.(C||k.toString());return}const U=10**n,L=Math.floor(k*Q/100*U)/U,P=_n(L,n);S(P),E.current&&clearTimeout(E.current),x?.(P)},R=k>0?parseFloat(I||"0")/k*100:0;return K(()=>()=>{E.current&&clearTimeout(E.current)},[]),g("div",{style:{backgroundColor:l,border:`1px solid ${c}`,borderRadius:p?"12px":"6px",padding:"16px",marginBottom:"16px"},children:[g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[a(qr,{symbol:e,logoURI:t,primaryColor:o,size:32}),g("div",{children:[a("span",{style:{fontSize:"14px",fontWeight:600,color:r,fontFamily:s},children:"Payment"}),a("div",{style:{fontSize:"12px",color:i,fontFamily:s,marginTop:"2px"},children:e})]})]}),g("div",{style:{textAlign:"right"},children:[y?a(qn,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:I,onChange:Q=>B(Q.target.value),placeholder:"0.0",fontFamily:w,color:r,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):a(qn,{element:"div",value:b>0?u:"0.00",title:b>0?u:"0.00",fontFamily:w,color:r,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),a("div",{style:{fontSize:"12px",color:i,fontFamily:w,marginTop:"2px"},children:e}),y&&k>0&&a("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((Q,U)=>{const L=Math.abs(R-Q)<1,P=U===4,V=Q/100,z=A===Q,te=v===Q;return a("button",{onClick:()=>D(Q),onMouseEnter:()=>F(Q),onMouseLeave:()=>{F(null),M(null)},onMouseDown:()=>M(Q),onMouseUp:()=>M(null),title:`${Q}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:L?1:z?.8:.5,transform:te?"scale(0.85)":z?"scale(1.15)":"scale(1)",transition:tn.interactive},children:g("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[a("circle",{cx:"7",cy:"7",r:"6.84375",fill:P?o:"none",stroke:P?o:p?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!P&&V>0&&a("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${V>.5?1:0} 1 ${7+6.84375*Math.sin(V*2*Math.PI)} ${7-6.84375*Math.cos(V*2*Math.PI)} Z`,fill:p?d?.textSecondary||"#9ca3af":"#3C3E42"})]})},Q)})})]})]}),f&&h&&!m&&a("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:p?`1px solid ${d?.cardBorder||c}`:"1px solid #e5e7eb",display:"flex",justifyContent:"flex-end"},children:g("span",{style:{fontSize:"11px",color:i,fontFamily:s,opacity:.7},children:["via ",h.venue]})})]})};function Yr(e,t,n){const o=je(e.address,t),s=e.chainId===n,r=e._source==="wallet";return r&&o&&s?0:r&&s?1:!r&&o?2:!r&&s?3:4}function nd(e){const{address:t,destinationToken:n,supportedSourceAssets:o,sourceChains:s,enabled:r}=e,i=(Bt(kt)?.mode||"7702")!=="7702",l=vn(),{externalAddress:c,embeddedAddress:d}=uo(),{assets:p,refetch:u}=po({address:t,supportedChains:s,enabled:r&&!i,refetchInterval:3e4}),f=ne(()=>{if(i)return[];if(!o||o.length===0)return p;const S=o.map(E=>E.toLowerCase());return p.filter(E=>S.includes(E.address.toLowerCase()))},[p,o,i]),h=i?c:l,m=ne(()=>{const S=new Set,E=[],A=F=>{if(!F)return;const v=F.toLowerCase();S.has(v)||(S.add(v),E.push(Re(F)))};if(A(n.address),i&&o)for(const F of o)A(F);return E},[i,n.address,o]),y=ne(()=>m.map(S=>S.toLowerCase()).sort().join(","),[m]),C=ne(()=>JSON.stringify([...s||[]].sort()),[s]),[x,w]=T([]),b=ie(0),k=le(async()=>{if(!r||!h||m.length===0){b.current++,w([]);return}const S=++b.current,E=Re(h),A=i?s&&s.length>0?s:[n.chainId]:[n.chainId],F=[];for(const D of m){const R=D.toLowerCase();if(R===n.address.toLowerCase()){const U=Me(n.chainId)?.supportedTokens?.find(L=>je(L.address,R));F.push({address:D,chainId:n.chainId,configToken:U?{decimals:U.decimals,symbol:U.symbol,name:U.name,logo:U.logo}:void 0});continue}let Q=!1;for(const U of A){const L=Me(U)?.supportedTokens?.find(P=>je(P.address,R));if(L){F.push({address:D,chainId:U,configToken:{decimals:L.decimals,symbol:L.symbol,name:L.name,logo:L.logo}}),Q=!0;break}}Q||F.push({address:D,chainId:n.chainId})}const v=new Map;for(const D of F){const R=v.get(D.chainId)||[];R.push(D),v.set(D.chainId,R)}const M=async(D,R)=>{try{const Q=await yn(D,{address:R.address,abi:_t,functionName:"balanceOf",args:[E]});let U,L,P,V;if(R.configToken)U=R.configToken.decimals,L=R.configToken.symbol,P=R.configToken.name,V=R.configToken.logo;else{const[O,W,re]=await Promise.all([yn(D,{address:R.address,abi:_t,functionName:"decimals"}).catch(()=>18),yn(D,{address:R.address,abi:_t,functionName:"symbol"}).catch(()=>"TOKEN"),yn(D,{address:R.address,abi:_t,functionName:"name"}).catch(()=>"TOKEN")]);U=Number(O),L=W,P=re}const z=je(R.address,n.address)&&R.chainId===n.chainId;z&&n.logoURI&&(V=n.logoURI),z&&!R.configToken&&L==="TOKEN"&&(L=n.symbol,P=n.symbol);const te=parseFloat((Number(Q)/Math.pow(10,U)).toFixed(6));return{address:R.address,name:P,symbol:L,decimals:U,balance:Q,balanceFormatted:te,balanceUsd:0,logoURI:V,isNative:!1,chainId:R.chainId}}catch{return null}},B=await Promise.all(Array.from(v.entries()).map(async([D,R])=>{let Q;try{Q=dt(D)}catch{return[]}const U=[],L=[];for(const V of R){const z=U.length;U.push({address:V.address,abi:_t,functionName:"balanceOf",args:[E]}),V.configToken||U.push({address:V.address,abi:_t,functionName:"decimals"},{address:V.address,abi:_t,functionName:"symbol"},{address:V.address,abi:_t,functionName:"name"}),L.push({start:z,item:V})}let P=null;try{P=await Q.multicall({contracts:U})}catch{P=null}return P?L.map(({start:V,item:z})=>{const te=P[V],O=te?.status==="success"?te.result:0n;let W,re,_,de;if(z.configToken)W=z.configToken.decimals,re=z.configToken.symbol,_=z.configToken.name,de=z.configToken.logo;else{const Z=P[V+1],he=P[V+2],be=P[V+3];W=Z?.status==="success"?Number(Z.result):18,re=he?.status==="success"?he.result:"TOKEN",_=be?.status==="success"?be.result:re}const ke=je(z.address,n.address)&&z.chainId===n.chainId;ke&&n.logoURI&&(de=n.logoURI),ke&&!z.configToken&&re==="TOKEN"&&(re=n.symbol,_=n.symbol);const Be=parseFloat((Number(O)/Math.pow(10,W)).toFixed(6));return{address:z.address,name:_,symbol:re,decimals:W,balance:O,balanceFormatted:Be,balanceUsd:0,logoURI:de,isNative:!1,chainId:z.chainId}}):(await Promise.all(R.map(V=>M(Q,V)))).filter(V=>V!==null)}));S===b.current&&w(B.flat())},[r,h,y,C,i,n.address,n.chainId,n.symbol,n.logoURI]);K(()=>{if(!r){w([]);return}k();const S=setInterval(()=>{k()},15e3);return()=>clearInterval(S)},[k,r]);const I=le(()=>{k()},[k]);return{displayAssets:ne(()=>{const S=[],E=x.filter(F=>F.balance>0n);for(const F of E)S.push({...F,_source:"wallet"});for(const F of f)S.push({...F,_source:"spice"});const A=n.address.toLowerCase();return S.sort((F,v)=>Yr(F,A,n.chainId)-Yr(v,A,n.chainId)),S},[x,f,n.address,n.chainId]),filteredSpiceAssets:f,walletAssets:x,embeddedWalletAddress:l||d,externalAddress:c,isNon7702:i,refreshSpiceAssets:u,refreshWalletAssets:I}}async function Kr(e){const{tokenIn:t,tokenOut:n,amountIn:o,fee:s,chainId:r,config:i}=e;if(o<=0n)throw new Error("amountIn must be greater than 0");const l=(await dt(r).simulateContract({address:i.quoterV2,abi:Ma,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:o,fee:s,sqrtPriceLimitX96:0n}]})).result;if(l[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:l[0],sqrtPriceX96After:l[1],gasEstimate:l[3]}}async function Zr(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(s=>Kr({...e,fee:s})));let o=null;for(let s=0;s<n.length;s++){const r=n[s];r.status==="fulfilled"&&(!o||r.value.amountOut>o.amountOut)&&(o={...r.value,fee:t[s]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}const od=[{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 sd(e){const{tokenIn:t,tokenOut:n,amountOut:o,fee:s,chainId:r,config:i}=e;if(o<=0n)throw new Error("amountOut must be greater than 0");const l=(await dt(r).simulateContract({address:i.quoterV2,abi:od,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:o,fee:s,sqrtPriceLimitX96:0n}]})).result;if(l[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:l[0],sqrtPriceX96After:l[1],gasEstimate:l[3]}}async function rd(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(s=>sd({...e,fee:s})));let o=null;for(let s=0;s<n.length;s++){const r=n[s];r.status==="fulfilled"&&(!o||r.value.amountIn<o.amountIn)&&(o={...r.value,fee:t[s]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}function Xr(e){return e.type==="swap"}const Bs=.02,ad=[1,8453,42161,10,137,43114,56],id="https://api.1inch.dev/swap/v6.0";function Gr(e,t){return Da(e,t)}function Jr(e){const t=e?.baseUrl??id;return{name:"1inch",chainIds:e?.chainIds??ad,resolve:async(n,o,s)=>{const r=n.maxSlippage??Bs,i=r*100,l=Qe(n.tokenIn)?Qs:n.tokenIn,c=Qe(n.tokenOut)?Qs:n.tokenOut,d=Qe(n.tokenIn);try{const p=new URL(`${t}/${o}/swap`);p.searchParams.set("src",l),p.searchParams.set("dst",c),p.searchParams.set("amount",n.amountIn.toString()),p.searchParams.set("from",s),p.searchParams.set("slippage",i.toString()),p.searchParams.set("disableEstimate","true"),p.searchParams.set("allowPartialFill","false");const u={Accept:"application/json"};e?.apiKey&&(u.Authorization=`Bearer ${e.apiKey}`);const f=await fetch(p.toString(),{headers:u});if(!f.ok)throw new Ue("VENUE_API_ERROR",`[1inchVenue] API returned ${f.status} for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`,{venue:"1inch",chainId:o,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:`HTTP ${f.status}`});const h=await f.json();if(!h.dstAmount||!h.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const m=BigInt(h.dstAmount);if(m<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const y=Gr(m,r),C=[];return h.tx.to&&!d&&C.push({to:n.tokenIn,value:0n,data:gt({abi:_t,functionName:"approve",args:[h.tx.to,n.amountIn]})}),C.push({to:h.tx.to,value:BigInt(h.tx.value||"0"),data:h.tx.data}),{venue:"1inch",amountOut:m,amountOutMinimum:y,calls:C}}catch(p){if(p instanceof Ue)throw p;const u=p instanceof Error?p.message:String(p);throw new Ue("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}: ${u}`,{venue:"1inch",chainId:o,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:u})}}}}const $r=[4114,5115],Fs={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425"},_r={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453]};function ea(e){return{name:"satsuma",chainIds:e.chainIds??$r,resolve:async(t,n,o)=>{const s=t.maxSlippage??Bs,r=Qe(t.tokenIn);let i;try{i=await Zr({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountIn:t.amountIn,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return console.warn(`[SatsumaVenue] No viable fee tier for ${t.tokenIn} \u2192 ${t.tokenOut} on chain ${n}.`),null}const l=Gr(i.amountOut,s),c=[];return r||c.push({to:t.tokenIn,value:0n,data:gt({abi:_t,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),c.push({to:e.swapRouter,value:r?t.amountIn:0n,data:gt({abi:Ra,functionName:"exactInputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:i.fee,recipient:o,amountIn:t.amountIn,amountOutMinimum:l,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:i.amountOut,amountOutMinimum:l,calls:c}}}}function ta(e){return{name:"satsuma",chainIds:e.chainIds??$r,resolve:async(t,n,o)=>{const s=t.maxSlippage??Bs,r=Qe(t.tokenIn);let i;try{i=await rd({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountOut:t.amountOut,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return null}const l=BigInt(Math.round(s*1e4)),c=i.amountIn+i.amountIn*l/10000n,d=[];return d.push({to:e.swapRouter,value:r?c:0n,data:gt({abi:ld,functionName:"exactOutputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:i.fee,recipient:o,amountOut:t.amountOut,amountInMaximum:c,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:i.amountIn,amountInMax:c,amountOut:t.amountOut,calls:d}}}}const ld=[{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 na(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(ea(e.satsuma)),t.push(Jr(e?.oneInch));function n(s){return t.find(r=>r.chainIds.includes(s))}async function o(s,r,i){const l=[],c=[];for(const d of s){if(!Xr(d)){l.push(d);continue}const p=n(r);if(!p)throw new Ue("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${r}. Cannot resolve swap ${d.tokenIn} \u2192 ${d.tokenOut}.`,{chainId:r,tokenIn:d.tokenIn,tokenOut:d.tokenOut,amountIn:d.amountIn.toString()});const u=await p.resolve(d,r,i);if(!u)throw new Ue("NO_LIQUIDITY",`${p.name} returned no quote for ${d.tokenIn} \u2192 ${d.tokenOut} on chain ${r}.`,{venue:p.name,chainId:r,tokenIn:d.tokenIn,tokenOut:d.tokenOut,amountIn:d.amountIn.toString()});l.push(...u.calls),c.push(u)}return{calls:l,resolvedSwaps:c}}return{resolveSwapIntents:o,getVenueForChain:n,venues:t}}function dd(e){const t=e?.customVenues??[];async function n(o,s,r){const i=t.filter(c=>c.chainIds.includes(s));if(i.length===0)throw new Ue("NO_SWAP_ROUTE",`No exact-output venue supports chain ${s}`,{chainId:s,tokenIn:o.tokenIn,tokenOut:o.tokenOut});const l=(await Promise.allSettled(i.map(c=>c.resolve(o,s,r)))).filter(c=>c.status==="fulfilled").map(c=>c.value).filter(c=>c!==null);if(l.length===0)throw new Ue("NO_SWAP_ROUTE",`All aggregators failed for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${s}`,{chainId:s,tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountOut:o.amountOut.toString()});return l.sort((c,d)=>c.amountIn<d.amountIn?-1:c.amountIn>d.amountIn?1:0),l[0]}return{getQuote:n,venues:t}}const cd=na({satsuma:Fs});function ud(e){const{direction:t,selectedAsset:n,destinationToken:o,chainId:s,recipient:r,paymentAmount:i}=e,[l,c]=T(!1),[d,p]=T(null),[u,f]=T(null),[h,m]=T(null),[y,C]=T(null),[x,w]=T(null),[b,k]=T(null),[I,S]=T(null),[E,A]=T(null),F=ie(null),v=ie(0),M=ie(new Map),B=ne(()=>cd,[]),D=ne(()=>dd({customVenues:[ta(Fs),ta(_r)]}),[]),R=ne(()=>{if(!n?.asset)return null;const W=Fn(n.asset,s);if(W)return W;const re=Rn(n.asset.address,s,n.asset.chainId);return re?re.address:null},[n?.asset,s]),Q=ne(()=>n?.asset?Fo(n.asset,s):[],[n?.asset,s]);K(()=>{let W=!1;if(!n?.asset||Q.length<=1){A(null);return}return(async()=>{const re=t==="input"?n.amount:i||"0";let _=0n;try{_=t==="input"?Ge(re,n.asset.decimals):0n}catch{_=0n}try{const de=await vr(n.asset,s,{requiredAmount:_});W||A(de)}catch{W||A(null)}})(),()=>{W=!0}},[n?.asset,n?.amount,s,Q,t,i]);const U=ne(()=>E??R,[E,R]),L=ne(()=>!n?.asset||!U?[]:[U,...Q.filter(W=>W.toLowerCase()!==U.toLowerCase())],[n?.asset,U,Q]),P=ne(()=>!n?.asset||!To(n.asset.address,n.asset.chainId,o.address,o.chainId)||!U?!1:je(U,o.address),[n,o.address,o.chainId,U]),V=U?je(U,o.address):!1,z=t==="output"&&parseFloat(i||"0")===0,te=!!n?.asset&&!P&&!V&&!z,O=te?I??U:U;return K(()=>{F.current&&clearTimeout(F.current);const W=t==="input"?n?.amount:i,re=parseFloat(W||"0");if(!te||!Number.isFinite(re)||re<=0||!n?.asset||!r||L.length===0){v.current++,f(null),m(null),C(null),w(null),k(null),S(null),p(null),c(!1);return}const _=n.asset.decimals;let de;try{de=t==="input"?Ge(n.amount,_):Ge(i||"0",o.decimals)}catch{v.current++,p("Invalid amount"),c(!1);return}const ke=++v.current,Be=()=>ke!==v.current;c(!0);const Z=t==="output"?150:400;return F.current=setTimeout(async()=>{try{if(t==="input"){const he=B.getVenueForChain(s);if(!he)throw new Error("No swap venue for this chain");let be=null,q=null;for(const j of L){const ee=`${t}:${s}:${j.toLowerCase()}:${o.address.toLowerCase()}:${de.toString()}`,Ce=M.current.get(ee);if(Ce&&Ce.expiresAt>Date.now()&&Ce.resolvedSwap){be=Ce.resolvedSwap,q=j;break}const oe=await he.resolve({type:"swap",tokenIn:j,tokenOut:o.address,amountIn:de},s,r);if(Be())return;if(oe){M.current.set(ee,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:oe}),be=oe,q=j;break}}if(!be||!q)throw new Error("No liquidity for this pair");S(q),k(be.amountOut),C(be),w(null);const ue=parseFloat(xt(be.amountOut,o.decimals));f(ue<.01?ue.toPrecision(4):ue.toLocaleString(void 0,{maximumFractionDigits:6})),m(null),p(null)}else{let he=null,be=null;for(const q of L){const ue=`${t}:${s}:${q.toLowerCase()}:${o.address.toLowerCase()}:${de.toString()}`,j=M.current.get(ue);if(j&&j.expiresAt>Date.now()&&j.exactOutputSwap){he=j.exactOutputSwap,be=q;break}try{const ee=await D.getQuote({tokenIn:q,tokenOut:o.address,amountOut:de},s,r);if(Be())return;M.current.set(ue,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:ee}),he=ee,be=q;break}catch{if(Be())return}}if(!he||!be)throw new Error("No liquidity for this pair");S(be),w(he),C(null),k(null),m(parseFloat(xt(he.amountIn,_)).toFixed(6)),f(null),p(null)}}catch(he){if(Be())return;const be=he instanceof Error?he.message:"Failed to get quote";p(be),f(null),m(null),C(null),w(null),k(null),S(null)}finally{Be()||c(!1)}},Z),()=>{F.current&&clearTimeout(F.current)}},[t,te,n?.amount,n?.asset?.address,n?.asset?.decimals,i,L,s,o.address,o.decimals,r,B,D]),{isQuoting:l,quoteError:d,estimatedOutput:u,estimatedInput:h,resolvedSwap:y,exactOutputSwap:x,quoteAmountOut:b,resolvedTokenIn:O,isDirect:V,needsSwap:te,selectedIsEquivalent:P}}const oa={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},sa=["signing-delegation","signing-intent","submitting","executing"],ra=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,destinationToken:o,buildActionCalls:s,feeExecutionMode:r="user-transfer",buildSpicenetBatch:i,onPayExecute:l,actionLabel:c,amountDirection:d="input",swapDescription:p,directDescription:u,paymentAmount:f,amountInputMode:h="fixed",minPaymentAmount:m,maxPaymentAmount:y,onAmountChange:C,styles:x,dark:w,title:b,subtitle:k,onAddFunds:I,onSuccess:S,onError:E})=>{const A=d==="output",{theme:F,dark:v,primaryColor:M,dk:B,palette:D,fontFamily:R,monoFont:Q,inputDark:U,cardBg:L,cardBorder:P,textPrimary:V,textSecondary:z,subtitleText:te}=at(x,w),O=U?{...F,colors:{...F.colors,secondary:B.cardBg,surfaceHover:B.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:F,W=o.chainId,re=Bt(kt),_=(re?.mode||"7702")!=="7702",de=ne(()=>re?.supportedChainIds??[],[re?.supportedChainIds]),ke=ne(()=>{const ye=re?.allowedTokens;if(!ye||ye.length===0)return;const Oe=new Set(ye.map(Jt=>Jt.toLowerCase())),Kt=[],hn=new Set;for(const Jt of de){const fn=Me(Jt);for(const wn of fn?.supportedTokens??[]){if(!Oe.has(wn.symbol.toLowerCase()))continue;const Se=wn.address.toLowerCase();hn.has(Se)||(hn.add(Se),Kt.push(wn.address))}}return Kt},[re?.allowedTokens,de]),Be=kn(),{address:Z,isConnected:he,isReady:be,isAuthenticated:q,provider:ue}=Be,{executeGasless:j,estimateGasless:ee}=Do(),{externalWallet:Ce,externalAddress:oe,embeddedAddress:N}=uo(),{displayAssets:ae,filteredSpiceAssets:we,embeddedWalletAddress:De,refreshSpiceAssets:We,refreshWalletAssets:pe}=nd({address:Z,destinationToken:o,supportedSourceAssets:ke,sourceChains:de,enabled:e&&(_?!!oe:!!Z)}),Ke=A||_?ae:we,[X,qe]=T(null),[xe,it]=T(f||""),[Ae,wt]=T(!1),[qt,Ft]=T(null),[Ne,Ct]=T("idle"),[zt,Lt]=T(""),[Gt,nn]=T(null),[Dn,Mt]=T(!1),[Fe,Ot]=T(null),[ct,Rt]=T(null),[ut,pt]=T(!1),[cn,mt]=T(!1),[fe,tt]=T(null),on=ie(X),St=ie(!1),Ie=ie(null),Dt=ie(0),ht=ie(null);K(()=>{on.current=X},[X]);const Ze=h==="adjustable"?xe:f||"0",bn=De||N||Z,{isQuoting:Wt,quoteError:sn,estimatedOutput:un,resolvedSwap:Je,exactOutputSwap:Te,quoteAmountOut:vt,resolvedTokenIn:lt,isDirect:nt,needsSwap:ot,selectedIsEquivalent:Ht}=ud({direction:d,selectedAsset:X,destinationToken:o,chainId:W,recipient:bn,paymentAmount:Ze}),yt=A?parseFloat(Ze||"0"):parseFloat(X?.amount||"")||0,At=ne(()=>X?.asset?we.find(ye=>je(ye.address,X.asset.address))?.balanceFormatted??0:0,[X,we]),Nt=ne(()=>X?.asset?A?ct?zo(ct.grossAmount,ct.decimals,X.asset.decimals)>X.asset.balance:Ht||nt?yt>X.asset.balanceFormatted:Te?parseFloat(xt(Te.amountInMax,X.asset.decimals))>X.asset.balanceFormatted:!1:ct?parseFloat(xt(zo(ct.grossAmount,ct.decimals,X.asset.decimals),X.asset.decimals))>At:yt>At:!1,[X,A,ct,Ht,yt,Te,At,nt]);K(()=>{e||(qe(null),Ft(null),wt(!1),Ct("idle"),Lt(""),nn(null),Mt(!1),Ot(null),Rt(null),pt(!1),mt(!1),tt(null),St.current=!1,h==="adjustable"&&it(f||""),Ie.current&&(Ie.current.abort(),Ie.current=null))},[e]);const jt=le(ye=>{qe(Oe=>({asset:ye,amount:Oe?.asset?.address===ye.address&&Oe?.asset?.chainId===ye.chainId&&Oe.amount||""})),Ft(null),tt(null),mt(!1)},[]),rn=le(ye=>{qe(Oe=>Oe&&{...Oe,amount:ye}),Ft(null),tt(null),mt(!1)},[]),In=le(ye=>{let Oe=ye;y&&parseFloat(Oe)>parseFloat(y)&&(Oe=y),it(Oe),C?.(Oe),Ft(null),tt(null),mt(!1)},[y,C]);le(ye=>{if(St.current||!Z)return;const Oe=on.current;!Oe?.asset||!Oe.amount||Oe.asset?._source==="wallet"||Ge(A?Ze:Oe.amount,Oe.asset.decimals)===0n||(St.current=!0,We())},[Z,W,We,A,Ze]);const ze=le(ye=>{Ct({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[ye.step]||"executing"),Lt(ye.message),ye.txHash&&nn(ye.txHash)},[]),Et=ne(()=>({currentPaymentAmount:Ze,destinationToken:o,embeddedWalletAddress:De,providerEmbeddedAddress:N,address:Z,isNon7702:_,isPayMode:A,resolvedChainId:W,buildActionCalls:s,feeExecutionMode:r,buildSpicenetBatch:i,selectedAsset:X,needsSwap:ot,resolvedSwap:Je,exactOutputSwap:Te,quoteAmountOut:vt,resolvedTokenIn:lt}),[Ze,o,De,N,Z,_,A,W,s,r,i,X,ot,Je,Te,vt,lt]),pn=le(ye=>Vl(Et,ye),[Et]),Yt=le(ye=>ql(Et,ye),[Et]),J=le((ye,Oe,Kt,hn)=>Yl(ye,Oe,Kt,ee,hn),[ee]),$=ne(()=>X?.asset?X.asset.chainId===W?X.asset.address:lt??Fn(X.asset,W)??o.address:o.address,[X,o.address,W,lt]),ve=le(()=>Jl(ht.current),[]),Ve=ne(()=>X?.asset?je(X.asset.address,o.address)&&X.asset.chainId===o.chainId:!1,[X,o.address,o.chainId]),$e=A&&_&&Ve&&yt>0&&!!X?.asset,Y=qt,ce=ne(()=>!(!X?.asset||yt<=0),[X,yt,$e]),Le=ne(()=>!e||Ae||Ne!=="idle"||!ce||$e||!X?.asset?null:[A?"pay":"supply",d,X.asset.address.toLowerCase(),X.asset.chainId,X.amount,Ze,o.address.toLowerCase(),o.chainId,W,lt?.toLowerCase()??"",ot?"swap":"direct",nt?"direct-token":"routed-token",_?"non7702":"7702",Ve?"source-dest":"cross-chain",Wt?"quoting":"quoted",Te?.amountIn?.toString()??"",Te?.amountInMax?.toString()??"",Te?.venue??"",Je?.amountOut?.toString()??"",vt?.toString()??"",De??"",N??"",Z??""].join("|"),[e,Ae,Ne,ce,$e,X,A,d,Ze,o,W,lt,ot,nt,_,Ve,Wt,Te,Je,vt,De,N,Z]),Ee=le(()=>Gl({selectedAsset:X,isPayMode:A,parsedAmount:yt,needsSwap:ot,exactOutputSwap:Te,isNon7702:_,isSourceDestToken:Ve,currentPaymentAmount:Ze,destinationToken:o,feeExecutionMode:r,resolvedTokenIn:lt,embeddedWalletAddress:De,providerEmbeddedAddress:N,resolvedChainId:W,isConnected:he,address:Z,ready:be,authenticated:q,isDirect:nt,resolvedSwap:Je,isQuoting:Wt,executionTokenAddress:$,buildPayChainBatches:pn,buildSupplyChainBatches:Yt,estimateGasless:ee,estimateRequiredGrossFunding:J}),[X,A,yt,ot,Te,_,Ve,Ze,o,r,lt,De,N,J,pn,ee,W,he,Z,be,q,nt,Je,Wt,Yt,$]),_e=le(ye=>Xl({asset:ye,isPayMode:A,isNon7702:_,needsSwap:ot,isQuoting:Wt,embeddedWalletAddress:De,buildSupplyChainBatches:Yt,estimateGasless:ee,executionTokenAddress:$,feeExecutionMode:r}),[A,_,ot,Wt,De,Yt,ee,$,r]);K(()=>{if(!e){pt(!1),mt(!1),tt(null),Rt(null);return}if(Ae||Ne!=="idle"){Dt.current+=1,pt(!1);return}if(!ce){Rt(null),pt(!1),mt(!1),tt(null);return}if($e){Rt(null),pt(!1),mt(!0),tt(null);return}if(!Le)return;let ye=!1;const Oe=async()=>{const Jt=++Dt.current;tt(null),pt(!0);try{const fn=await Ee();if(ye||Dt.current!==Jt)return;fn?(Rt(fn),mt(!0)):(Rt(null),mt(!1)),tt(null)}catch(fn){if(ye||Dt.current!==Jt)return;const wn=mn(fn,"Unable to calculate fees for this action.");Rt(null),mt(!1),tt(wn)}finally{!ye&&Dt.current===Jt&&pt(!1)}},Kt=window.setTimeout(()=>{Oe()},250),hn=window.setInterval(()=>{Oe()},1e4);return()=>{ye=!0,clearTimeout(Kt),window.clearInterval(hn),pt(!1)}},[e,Ae,Ne,Ee,ce,$e,Le]);const He=le(()=>ed(ht.current),[]);K(()=>{!A&&Ne==="success"&&Gt&&(We(),S?.(Gt))},[A,Ne,Gt,We,S]),K(()=>{if(!A||Fe?.status!=="success"||St.current||!Z)return;St.current=!0;const ye=on.current;!ye?.asset||ye.asset?._source==="wallet"||We()},[A,Fe?.status,Z,We]);const Ye=ie(S),rt=ie(E);K(()=>{Ye.current=S},[S]),K(()=>{rt.current=E},[E]),K(()=>{e&&(We(),pe())},[e,We,pe]),K(()=>{A&&(Fe?.status==="success"&&Ye.current?.(Fe.txHash||""),Fe?.status==="failed"&&rt.current?.(new Error("Payment execution failed")))},[A,Fe?.status]);const st=le(()=>{Mt(!1),Ot(null),qe(null),St.current=!1,We(),pe()},[We,pe]);ht.current={selectedAsset:X,parsedAmount:yt,currentPaymentAmount:Ze,isInsufficientBalance:Nt,isPayMode:A,isNon7702:_,isSourceDestToken:Ve,needsSwap:ot,exactOutputSwap:Te,selectedIsEquivalent:Ht,resolvedTokenIn:lt,embeddedWalletAddress:De,providerEmbeddedAddress:N,externalWallet:Ce,externalWalletAddress:oe,address:Z,isConnected:he,ready:be,authenticated:q,provider:ue,resolvedChainId:W,executionTokenAddress:$,destinationToken:o,buildActionCalls:s,feeExecutionMode:r,buildSpicenetBatch:i,onPayExecute:l,onError:E,gasless:{estimateGasless:ee,executeGasless:j,buildPayChainBatches:pn,buildSupplyChainBatches:Yt,estimateRequiredGrossFunding:J,onProgress:ze},ui:{setError:Ft,setStep:Ct,setStatusMsg:Lt,setTxHash:nn,setIsExecuting:wt,setShowStatusPanel:Mt,setPaymentResult:Ot},refs:{spiceDepositSubmittedRef:St,abortControllerRef:Ie}};const et=A&&yt===0,H=A?!!X?.asset&&yt>=0&&!Nt&&!Ae&&(et||$e||cn)&&!fe&&(et||!ot||!!Te):!!X?.asset&&yt>0&&!Nt&&!Ae&&cn&&!fe&&(nt||!!Je&&!Wt),G=nt?u||`Your ${o.symbol} will be used directly.`:p||"Your assets will be swapped and used in a single atomic transaction.",ge=(W?Me(W):void 0)?.viemChain?.blockExplorers?.default?.url??"",se=sa.indexOf(Ne),me=Ae?(oa[Ne]||"EXECUTING...").toUpperCase():Ne==="success"?"DONE":Nt?"INSUFFICIENT BALANCE":c.toUpperCase(),Pe=ne(()=>{if(Ae)return"PAYING...";if(Nt&&X?.asset)return`INSUFFICIENT ${X.asset.symbol}`;if(c)return c.toUpperCase();const ye=yt>0?` ${Ze} ${o.symbol}`:"";return ot?`SWAP & PAY${ye}`:`PAY${ye}`},[Ae,Nt,X,c,yt,Ze,o.symbol,ot]),Qt=Ne==="success"?()=>{Ct("idle"),qe(null),nn(null),We()}:ve,an=Ne==="success"?!1:!H;if(!e)return null;const Vt=A?b||`Pay ${o.symbol}`:c,Pt=A?k:g("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[a("span",{style:{marginTop:"3px",flexShrink:0},children:a(fs,{color:te})}),a("p",{style:{fontSize:"12px",color:te,margin:0,lineHeight:"1.4",fontFamily:R},children:G})]});if(A){const ye=Fe&&(Fe.status==="success"||Fe.status==="failed")?[{asset:{symbol:X?.asset?.symbol||o.symbol,address:X?.asset?.address||""},amount:Ze,txHash:Fe.txHash||"",success:Fe.status==="success",error:Fe.status==="failed"?Fe.error:void 0}]:void 0;return a(En,{isOpen:e,onClose:t,title:Vt,subtitle:Pt,styles:x,dark:v,footerLinkText:"Spicenet accounts \u2192",closeOnBackdropClick:n,children:g("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[I&&a("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:a(ms,{onClick:I,color:M,fontFamily:R})}),a("div",{style:{marginBottom:"12px"},children:a(co,{assets:Ke,selectedAsset:X??void 0,onAssetSelect:jt,onAmountChange:()=>{},label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:X?.asset?ot?Wt?"...":Te?`~${parseFloat(xt(Te.amountIn,X.asset.decimals)).toFixed(6)}`:void 0:Ze??void 0:void 0,dark:v,theme:O,styles:x})}),a(Vr,{variant:"pay",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:M,fontFamily:R,textPrimary:V,textSecondary:z,cardBg:L,cardBorder:P,dk:B,dark:v,isQuoting:Wt,quoteError:sn,estimatedOutput:un,paymentAmount:Ze,needsSwap:ot,exactOutputSwap:Te,adjustable:h==="adjustable",maxAmount:y,onAmountChange:In}),ce&&a(So,{fontFamily:R,textPrimary:V,textSecondary:z,cardBg:L,cardBorder:P,resolvedDark:v,darkCardBorder:B.cardBorder,primaryColor:M,feePreview:ct,isLoading:ut,errorText:fe,directExecutionFeeNote:$e}),Y&&a(to,{variant:"error",palette:D,fontFamily:R,style:{marginBottom:"12px"},children:Y}),a(bt,{variant:"outline",fullWidth:!0,onClick:He,disabled:!H,loading:Ae,dark:v,styles:{...x,button:{...x?.button,backgroundColor:M}},children:Pe}),Fe&&Dn&&a("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:v?B.shell:"white",borderRadius:v?"12px":"6px",padding:"16px 0"},children:a(ws,{type:"payment",isOpen:Fe.status!=="processing",isProcessing:Ae||Fe.status==="processing",closeOnComplete:!1,chainName:$t(W),explorerUrl:Gn(W,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{Mt(!1),Ot(null),He()},onNewTx:st,onClose:()=>{Mt(!1),Ot(null)},onComplete:st,results:ye,styles:x,dark:v})})]})})}return a(En,{isOpen:e,onClose:t,title:Vt,subtitle:Pt,dark:v,styles:x,theme:F,closeOnBackdropClick:n,children:g("div",{style:{padding:"24px 24px 5px 24px",position:"relative"},children:[a("div",{style:{marginBottom:"16px"},children:a(co,{assets:Ke,selectedAsset:X||void 0,onAssetSelect:jt,onAmountChange:rn,disabled:Ae||Ne==="success",showBalance:!0,showMaxButton:!0,label:"From Spice Balance",placeholder:"0.00",theme:O,styles:x,dark:U,resolveMaxAmount:_e,maxAmount:At>0?_n(At,X?.asset.decimals??o.decimals):void 0})}),X?.asset&&!nt&&a(Vr,{variant:"supply",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:M,fontFamily:R,textPrimary:V,textSecondary:z,cardBg:L,cardBorder:P,dark:v,isQuoting:Wt,quoteError:sn,estimatedOutput:un}),ce&&a(So,{fontFamily:R,textPrimary:V,textSecondary:z,cardBg:L,cardBorder:P,resolvedDark:v,darkCardBorder:B.cardBorder,primaryColor:M,feePreview:ct,isLoading:ut,errorText:fe}),Ne!=="idle"&&g("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:Ne==="success"?L:Ne==="error"?D.errorBg:L,border:`1px solid ${Ne==="success"?P:Ne==="error"?D.errorBorder:P}`},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[Ne==="success"?a("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:a("path",{d:"M5 13l4 4L19 7",stroke:D.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):Ne==="error"?a("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:a("path",{d:"M18 6L6 18M6 6l12 12",stroke:D.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):a(Wn,{size:14,color:M}),a("span",{style:{fontSize:"13px",fontWeight:500,color:Ne==="success"?V:Ne==="error"?D.errorText:V,fontFamily:R,flex:1},children:Ne==="success"?"Deposit confirmed":Ne==="error"?zt||"Transaction failed":oa[Ne]||zt}),Ne==="success"&&Gt&&a("a",{href:`${ge}/tx/${Gt}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:M,fontFamily:R,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),Ne==="error"&&a("button",{onClick:()=>{Ct("idle"),Ft(null),setTimeout(ve,50)},style:{background:"none",border:"none",fontSize:"12px",color:M,fontFamily:R,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),se>=0&&Ne!=="success"&&Ne!=="error"&&a("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${z}22`,overflow:"hidden"},children:a("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:M,transformOrigin:"left center",transform:`scaleX(${(se+1)/sa.length})`,transition:"transform 400ms ease"}})})]}),qt&&Ne==="idle"&&a(to,{variant:"error",palette:D,fontFamily:R,style:{marginBottom:"16px"},children:qt}),a(bt,{variant:"outline",fullWidth:!0,disabled:an,onClick:Qt,theme:F,dark:v,styles:{...x,button:{...x?.button,backgroundColor:M}},style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:Q},children:me})]})})},pd=e=>a(ra,{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}),hd=({label:e="Export Wallet",style:t,className:n,onExport:o,onError:s})=>{const[r,i]=T(!1),[l,c]=T(!1),{primaryColor:d}=at(),p=Bt(kt),{isAuthenticated:u}=kn();let f=null;try{f=bo()}catch{}let h=null,m=null;try{h=za(),m=wo()}catch{h=null,m=null}const y=Co(m),C=le(async()=>{if(!u){s?.("User is not authenticated. Please log in first.");return}try{if(p?.provider==="dynamic"){if(!h||!y){s?.("Dynamic is not available. Ensure the app is wrapped in a DynamicContextProvider.");return}await h.initExportProcess(!1),o?.();return}if(!f){s?.("Privy is not available. Ensure the app is wrapped in a PrivyProvider.");return}await f.exportWallet(),o?.()}catch(b){const k=b instanceof Error?b.message:"Failed to export wallet";console.error("Export wallet error:",b),s?.(k)}},[y,h,u,s,o,f,p?.provider]),x=!u,w={padding:"10px 20px",borderRadius:"8px",fontFamily:'"IBM Plex Mono", monospace',fontSize:"14px",fontWeight:500,letterSpacing:"0.4px",textTransform:"uppercase",cursor:x?"not-allowed":"pointer",opacity:x?.5:1,border:"1px solid #0e0d0b",color:"#0e0d0b",backgroundColor:l?`${d}cc`:r?`${d}ee`:d,transition:"background-color 150ms ease, transform 150ms ease",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"8px",...t};return g("button",{onClick:C,onMouseEnter:()=>i(!0),onMouseLeave:()=>{i(!1),c(!1)},onMouseDown:()=>c(!0),onMouseUp:()=>c(!1),disabled:x,className:n,style:w,children:[g("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),a("polyline",{points:"17 8 12 3 7 8"}),a("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]}),e]})};function aa(e){const t=Bt(kt),n=vn(),o=e?.enabled===!1?void 0:n,s=t?.network?{network:t.network,pollIntervalMs:e?.pollIntervalMs,chainIds:e?.chainIds??t.supportedChainIds}:void 0;return{...hr(o,s),embeddedWalletAddress:n}}const fd=({appName:e,status:t,statusLabel:n,totalUsdValue:o,breakdownSubtitle:s,address:r,dk:i,dark:l=!1,showModeToggle:c,isEmbeddedMode:d=!0,onModeToggle:p})=>{const[u,f]=T(!1),h=async()=>{r&&await _a(r)&&(f(!0),setTimeout(()=>f(!1),2e3))},m=t==="active",y=n||(m?"Active":"Inactive"),C=m?"#10b981":"#9ca3af";return g("div",{children:[g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[g("div",{style:{fontSize:"13px",fontWeight:600,color:i.textPrimary},children:[e," Account"]}),c?g("button",{onClick:p,style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:l?i.hoverBg:"#f3f4f6",border:l?`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:[a("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:d?"#22c55e":"#f59e0b"}}),a("span",{children:d?"Embedded":"External"})]}):g("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:l?i.hoverBg:m?"#ecfdf5":"#f3f4f6",border:l?`1px solid ${i.cardBorder}`:m?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[a("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:C}}),a("span",{style:{fontSize:"11px",fontWeight:500,color:l?i.textSecondary:m?"#065f46":"#6b7280"},children:y})]})]}),a("div",{style:{fontSize:"28px",fontWeight:700,color:i.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:Jn(o)}),s&&a("div",{style:{fontSize:"12px",color:i.textSecondary,marginBottom:"8px"},children:s}),r&&g("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[a("span",{style:{fontSize:"12px",fontFamily:'"IBM Plex Mono", monospace',color:l?i.textSecondary:"#9ca3af"},children:$a(r)}),a("button",{onClick:h,style:{padding:"2px 6px",fontSize:"10px",fontWeight:500,backgroundColor:"transparent",color:l?i.textSecondary:"#9ca3af",border:"none",cursor:"pointer",borderRadius:"4px",transition:"background-color 150ms ease, color 150ms ease"},title:"Copy address",children:u?"Copied":"Copy"})]})]})},md=({pendingDeposits:e,onCompleteDeposit:t,dk:n,dark:o=!1})=>e.length===0?null:g("div",{children:[a("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:"Pending Deposits"}),a("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((s,r)=>{const i=Me(s.chainId)?.displayName||`Chain ${s.chainId}`;return g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:o?n.warningBg:"#fffbeb",border:o?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"8px"},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[a("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:o?n.hoverBg:"#fde68a",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:n.warningText},children:s.tokenSymbol.charAt(0)}),g("div",{children:[g("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:[s.amount," ",s.tokenSymbol]}),g("div",{style:{fontSize:"11px",color:n.warningText},children:["on ",i]})]})]}),a("button",{onClick:()=>t?.(s),style:{padding:"4px 12px",fontSize:"11px",fontWeight:600,backgroundColor:o?n.hoverBg:"#fef3c7",color:o?n.textPrimary:"#92400e",border:o?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"9999px",cursor:"pointer",transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease"},children:"Complete"})]},`${s.tokenAddress}-${s.chainId}-${r}`)})})]}),gd=({spiceAssets:e,loading:t,dk:n,dark:o=!1})=>{const s={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},r={backgroundColor:n.cardBg,border:o?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return t?g("div",{children:[a("div",{style:s,children:"Idle Balances"}),[1,2].map(i=>a("div",{style:{...r,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},i))]}):e.length===0?g("div",{children:[a("div",{style:s,children:"Idle Balances"}),a("div",{style:{...r,padding:"16px",textAlign:"center",fontSize:"13px",color:o?n.textSecondary:"#9ca3af"},children:"No assets yet. Deposit to get started."})]}):g("div",{children:[a("div",{style:s,children:"Idle Balances"}),a("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((i,l)=>{const c=Me(i.chainId),d=i.chainDisplayName||c?.displayName||`Chain ${i.chainId}`,p=i.tokenDisplaySymbol||i.tokenDisplayName||i.tokenSymbol;return g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...r},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[i.logoURI?a("img",{src:i.logoURI,alt:i.tokenSymbol,style:{width:"24px",height:"24px",borderRadius:"50%"}}):a("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:o?n.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:n.textSecondary},children:p.charAt(0)}),g("div",{children:[a("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:p}),a("div",{style:{fontSize:"11px",color:o?n.textSecondary:"#9ca3af"},children:d})]})]}),g("div",{style:{textAlign:"right"},children:[a("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:Ln(i.balanceFormatted)}),a("div",{style:{fontSize:"11px",color:o?n.textSecondary:"#9ca3af"},children:Jn(i.usdValue)})]})]},`${i.tokenAddress}-${i.chainId}-${l}`)})})]})},yd=({section:e,dk:t,dark:n=!1})=>{const o=s=>{switch(s){case"green":return"#10b981";case"red":return"#ef4444";default:return t.textPrimary}};return g("div",{children:[a("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:t.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:e.title}),a("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.items.map((s,r)=>g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:t.cardBg,border:n?`1px solid ${t.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.tokenLogoURI?a("img",{src:s.tokenLogoURI,alt:s.tokenSymbol,style:{width:"20px",height:"20px",borderRadius:"50%"}}):a("div",{style:{width:"20px",height:"20px",borderRadius:"50%",backgroundColor:n?t.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",fontWeight:600,color:t.textSecondary},children:s.tokenSymbol.charAt(0)}),g("div",{children:[a("div",{style:{fontSize:"13px",fontWeight:500,color:t.textPrimary},children:s.tokenSymbol}),a("div",{style:{fontSize:"11px",color:t.textSecondary},children:s.label})]})]}),a("div",{style:{fontSize:"13px",fontWeight:600,color:o(s.valueColor)},children:s.displayValue})]},r))})]})},xd=({onDepositClick:e,onWithdrawClick:t,depositDisabled:n=!1,withdrawDisabled:o=!1,primaryColor:s="#EA4B4B",dark:r=!1})=>!e&&!t?null:g("div",{style:{display:"flex",gap:"8px"},children:[e&&a(bt,{variant:"outline",onClick:e,disabled:n,dark:r,styles:{button:{backgroundColor:s}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&a(bt,{variant:"outline",onClick:t,disabled:o,dark:r,styles:{button:{backgroundColor:s}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),bd=({appName:e,status:t,statusLabel:n,totalUsdValue:o,breakdownSubtitle:s,address:r,spiceAssets:i,spiceAssetsLoading:l,pendingDeposits:c,customSections:d,onDepositClick:p,onWithdrawClick:u,onCompleteDeposit:f,primaryColor:h,dk:m,dark:y=!1,showModeToggle:C,isEmbeddedMode:x,onModeToggle:w,showConnectExternalCta:b,onConnectExternalWallet:k,connectExternalError:I})=>{const[S,E]=T(!1);return g("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[a(fd,{appName:e,status:t,statusLabel:n,totalUsdValue:o,breakdownSubtitle:s,address:r,dk:m,dark:y,showModeToggle:C,isEmbeddedMode:x,onModeToggle:w}),b&&g("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[a("button",{onClick:k,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:h||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:'"Helvetica Neue", sans-serif',transition:"opacity 150ms ease"},children:"Connect External Wallet"}),I&&a("span",{style:{fontSize:"11px",color:y?m.errorText:"#b91c1c",lineHeight:1.4},children:I})]}),a("div",{style:{height:"1px",backgroundColor:y?"#2d2d2d":"#e5e7eb"}}),a(xd,{onDepositClick:p,onWithdrawClick:u,primaryColor:h,dark:y}),g("div",{children:[g("button",{onClick:()=>E(!S),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:m.cardBg,border:y?`1px solid ${m.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:m.textSecondary,fontSize:"12px",fontWeight:500},children:[a("span",{children:"How It Works"}),a("span",{style:{transform:S?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),S&&g("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:y?m.cardBg:"#f0fdf4",border:y?`1px solid ${m.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:y?m.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),a(md,{pendingDeposits:c,onCompleteDeposit:f,dk:m,dark:y}),a(gd,{spiceAssets:i,loading:l,dk:m,dark:y}),d.map((A,F)=>a(yd,{section:A,dk:m,dark:y},F))]})},Ts=380,Xn=8;function ia(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function wd(e,t){const n=new Map;Object.entries(t).forEach(([s,r])=>{if(!Number.isFinite(r)||r<=0)return;n.set(s,r),n.set(s.toUpperCase(),r);const i=ia(s);i&&n.set(i,r)});const o=[e.symbol,e.displaySymbol,e.receiptTokenName,e.name,e.displayName];for(const s of o){if(!s)continue;const r=n.get(s)??n.get(s.toUpperCase());if(r!==void 0)return r;const i=ia(s);if(!i)continue;const l=n.get(i);if(l!==void 0)return l}return 0}const Cd=({appName:e="Spice",status:t="active",statusLabel:n,customSections:o=[],extraAssets:s=[],tokenPrices:r={},breakdownLabels:i=[],styles:l,dark:c=!1,onDepositSuccess:d,onDepositClick:p,onWithdrawClick:u,onCompleteDeposit:f,showModeToggle:h=!1,defaultMode:m})=>{const y=Bt(kt),C=y?.mode!=="7702",x=ie(!1);K(()=>{if(!x.current){if(va()){x.current=!0;return}m&&y?.setMode&&(y.setMode(m==="non7702"?"ondemand":"7702"),x.current=!0)}},[y,m]);const[w,b]=T(!1),[k,I]=T(null),[S,E]=T({top:0,bottom:0,left:0,placement:"below"}),A=ie(null),F=ie(null),{address:v,isConnected:M}=kn(),B=vn(),{address:D}=Nn(),{dark:R,primaryColor:Q,dk:U}=at(l,c),L=ne(()=>y?.supportedChainIds??go("mainnet"),[y?.supportedChainIds]),{assets:P,loading:V}=po({address:v,supportedChains:L,enabled:!!v&&!C,refetchInterval:3e4}),z=ne(()=>[...C?[]:P.map(pe=>{const Ke=pe.balanceUsd||0,X=Number.isFinite(pe.balanceFormatted)?pe.balanceFormatted:0,qe=Ke>0?Ke:wd(pe,r)*X;return{tokenAddress:pe.address,tokenSymbol:pe.symbol,tokenDisplaySymbol:cs(pe),tokenDisplayName:ri(pe),tokenDecimals:pe.decimals,chainId:pe.chainId,chainDisplayName:us(pe),balance:pe.balance.toString(),balanceFormatted:pe.balanceFormatted,usdValue:qe,logoURI:pe.logoURI}}),...s].filter(pe=>pe.balanceFormatted>0),[C,P,r,s]),te=ne(()=>z.reduce((pe,Ke)=>pe+Ke.usdValue,0),[z]),{pendingDeposits:O}=aa({chainIds:L,enabled:!!v}),W=ne(()=>o.reduce((pe,Ke)=>pe+Ke.totalValue,0),[o]),re=te+W,_=ne(()=>{const pe=[];te>0&&pe.push(`${Jn(te)} idle`);for(const Ke of o){const X=i.find(qe=>qe.sectionTitle===Ke.title)?.label||Ke.title.toLowerCase();pe.push(`${Jn(Ke.totalValue)} ${X}`)}return pe.join(" \xB7 ")},[te,o,i]),de=le(pe=>{f?f(pe):I(pe)},[f]),ke=le(()=>{I(null)},[]),Be=le(()=>{I(null),d?.()},[d]),Z=le(()=>{if(!A.current)return;const pe=A.current.getBoundingClientRect(),Ke=window.innerHeight-pe.bottom-Xn,X=pe.top-Xn,qe=Ke>=400||Ke>=X?"below":"above",xe=Math.max(Xn,Math.min(pe.right-Ts,window.innerWidth-Ts-Xn)),it=qe==="below"?pe.bottom+Xn:pe.top-Xn,Ae=qe==="above"?window.innerHeight-it:0;E({top:it,bottom:Ae,left:xe,placement:qe})},[]);Ns(()=>{w&&Z()},[w,Z]),K(()=>{if(!w)return;const pe=qe=>{A.current&&!A.current.contains(qe.target)&&F.current&&!F.current.contains(qe.target)&&b(!1)},Ke=qe=>{qe.key==="Escape"&&b(!1)},X=()=>Z();return document.addEventListener("mousedown",pe),document.addEventListener("keydown",Ke),window.addEventListener("scroll",X,{passive:!0}),window.addEventListener("resize",Z),()=>{document.removeEventListener("mousedown",pe),document.removeEventListener("keydown",Ke),window.removeEventListener("scroll",X),window.removeEventListener("resize",Z)}},[w,Z]);const he=y?.mode==="7702",be=he?B||v:D||v,q=le(()=>{y?.setMode&&y.setMode(he?"ondemand":"7702")},[y,he]),[ue,j]=T(null);let ee=null;try{ee=Vs({onSuccess:()=>j(null),onError:pe=>j(mn(pe,"Failed to connect wallet."))}).connectWallet}catch{ee=null}const Ce=le(()=>{ee&&(b(!1),j(null),ee({walletChainType:"ethereum-only"}))},[ee]),oe=h&&!he&&!D&&!!ee,N=le(()=>{b(!1),p?.()},[p]),ae=le(()=>{b(!1),u?.()},[u]),we=le(pe=>{b(!1),de(pe)},[de]);if(typeof window>"u")return null;const De=g("button",{ref:A,onClick:()=>b(!w),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:R?U.hoverBg:"#ffffff",border:R?`1px solid ${U.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:'"Helvetica Neue", sans-serif',color:R?U.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:R?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[a("span",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:Q,flexShrink:0}}),g("span",{children:[e," Account"]}),M&&g("span",{style:{color:R?U.textSecondary:"#6b7280"},children:["\xB7 ",Jn(re)]}),a("span",{style:{fontSize:"10px",color:R?U.textSecondary:"#9ca3af",transform:w?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),We=w?Ys.createPortal(g(ln,{children:[a("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:Vn.popover},onClick:()=>b(!1)}),a("div",{ref:F,style:{position:"fixed",top:S.placement==="below"?`${S.top}px`:"auto",bottom:S.placement==="above"?`${S.bottom}px`:"auto",left:`${S.left}px`,width:`${Ts}px`,maxWidth:`calc(100vw - ${Xn*2}px)`,maxHeight:"80vh",backgroundColor:R?U.shell:"#ffffff",border:R?`1px solid ${U.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:R?"0 10px 40px rgba(0, 0, 0, 0.5)":"0 10px 40px rgba(0, 0, 0, 0.12)",zIndex:Vn.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${Ut.out}`},children:a(bd,{appName:e,status:t,statusLabel:n,totalUsdValue:re,breakdownSubtitle:_,address:h?be:v,spiceAssets:z,spiceAssetsLoading:V,pendingDeposits:O,customSections:o,onDepositClick:p?N:void 0,onWithdrawClick:u?ae:void 0,onCompleteDeposit:we,primaryColor:Q,dk:U,dark:R,showModeToggle:h,isEmbeddedMode:he,onModeToggle:q,showConnectExternalCta:oe,onConnectExternalWallet:Ce,connectExternalError:ue})}),a("style",{children:`
|
|
104
104
|
@keyframes accountDisplayFadeIn {
|
|
105
105
|
from { opacity: 0; transform: translateY(-4px); }
|
|
106
106
|
to { opacity: 1; transform: translateY(0); }
|