@spicenet-io/spiceflow-ui 4.9.6-consistency.7 → 4.9.6-consistency.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -40,7 +40,7 @@
40
40
  from { opacity: 0; transform: translateY(4px); }
41
41
  to { opacity: 1; transform: translateY(0); }
42
42
  }
43
- `,Va=({title:e,showChevron:t,expanded:n,onToggleDetails:s,showClose:o,onClose:a,fontFamily:i,labelColor:l,textPrimary:d,closeHoverBg:c,closePressedBg:p})=>{const[m,h]=u.useState(!1),[g,x]=u.useState(!1);return r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"16px"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:s?"pointer":"default"},onClick:s,children:[r.jsxs("span",{style:{fontSize:"13px",fontWeight:500,color:l,fontFamily:i},children:[e," "]}),t&&r.jsx(Pn,{color:l,direction:n?"up":"down"})]}),o&&r.jsx("button",{onClick:a,onMouseEnter:()=>h(!0),onMouseLeave:()=>{h(!1),x(!1)},onMouseDown:()=>x(!0),onMouseUp:()=>x(!1),style:{background:g?p:m?c:"none",border:"none",borderRadius:"4px",cursor:"pointer",padding:"4px",display:"flex",alignItems:"center",justifyContent:"center",color:m||g?d:l,transform:g?"scale(0.9)":m?"scale(1.1)":"scale(1)",transition:f.transition.interactive},children:r.jsx(ns,{size:16})})]})},Qa=({chainName:e,bg:t,border:n,textPrimary:s,labelColor:o,primaryColor:a})=>r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"20px 16px",borderRadius:"8px",backgroundColor:t,border:`1px solid ${n}`,gap:"12px"},children:[r.jsx(f.Spinner,{size:24,borderWidth:3,color:a}),r.jsxs("div",{children:[r.jsx("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:f.font.mono,letterSpacing:"0.5px",color:s},children:"PROCESSING TRANSACTION"}),r.jsxs("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:o},children:["on ",e]})]})]}),Ga=({bg:e,border:t,left:n,right:s})=>r.jsxs("div",{style:{padding:"10px 12px",borderRadius:"6px",backgroundColor:e,border:`1px solid ${t}`,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[n,s]}),Lo=({isOpen:e,onClose:t,onComplete:n,closeOnComplete:s=!1,type:o,results:a,chainId:i,chainName:l,explorerUrl:d,theme:c,styles:p,dark:m,intentStatus:h,onRetry:g,onNewTx:x,onRetryTx:y,asOverlay:C=!0,isProcessing:w=!1,showStepBreakdown:b=!0})=>{const{theme:I,primaryColor:S,dark:v,dk:B}=f.useSpiceBrand(p,m),E=c||I,[j,N]=u.useState(!1),T=l??(i?f.getChainName(i):"Network"),P=d??(i&&f.getExplorerUrl(i,"").replace(/\/tx\/.*$/,"")||void 0),M=v?B.cardBg:"#ffffff",D=v?"0 4px 20px rgba(0, 0, 0, 0.4)":"0 4px 20px rgba(0, 0, 0, 0.1)",L=v?"0 -4px 8px -2px rgba(0, 0, 0, 0.4)":"0 -4px 8px -2px rgba(0, 0, 0, 0.15)",R=B.textSecondary,U=v?B.textPrimary:"#374151",X=v?B.inputBg:"#f9fafb",Y=v?B.inputBorder:"#e5e7eb",V=v?B.inputBg:"#f3f4f6",J=v?B.inputBorder:"#e5e7eb",[ce,G]=u.useState(!0),q=v?B.inputBg:"#f9fafb",Z=v?B.hoverBg:"#f3f4f6",_=v?{successBg:B.successBg,successBorder:B.successBorder,successText:B.successText,errorBg:B.errorBg,errorBorder:B.errorBorder,errorText:B.errorText}:{},H=h?.steps.find(ae=>ae.status==="failed")?.error;u.useEffect(()=>{!e&&!h&&N(!1)},[e,h]);const F=()=>{N(!0),setTimeout(()=>{window.dispatchEvent(new CustomEvent("tx-complete",{detail:{type:o,results:a}})),window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:{type:o,status:"success",results:a}})),n?.(),s&&t()},300)},de=()=>{G(!ce)};if(h){const{steps:ae,overallStatus:be}=h,O=be==="processing",se=be==="success",W=be==="failed",$=ae.filter(ne=>ne.transactionHash)[0],oe=ae.length>1?ae.map(ne=>ne.chainName).filter(Boolean).join(" and "):T!=="Network"?T:ae[0]?.chainName||T,Ce=P||($?f.getExplorerUrl($.chainId,$.transactionHash||"").replace(/\/tx\/.*$/,""):void 0),Me=r.jsxs(r.Fragment,{children:[r.jsx(Va,{title:O?`Processing ${o.charAt(0).toUpperCase()+o.slice(1)}`:`${o.charAt(0).toUpperCase()+o.slice(1)} results`,showChevron:b,expanded:ce,onToggleDetails:de,showClose:!O,onClose:t,fontFamily:p?.fontFamily||E.typography.fontFamily,labelColor:R,textPrimary:U,closeHoverBg:q,closePressedBg:Z}),r.jsx("div",{style:{marginBottom:"16px"},children:O?r.jsx(Qa,{chainName:oe,bg:V,border:J,textPrimary:U,labelColor:R,primaryColor:S}):r.jsx(qa,{isSuccess:se,type:o,chainName:oe,explorerUrl:Ce,txHash:$?.transactionHash,dark:v,..._,textSecondary:R})}),b&&r.jsx("div",{style:{overflow:"hidden",maxHeight:ce?"300px":"0px",opacity:ce?1:0,transition:"max-height 0.3s ease, opacity 0.3s ease",marginBottom:ce?"16px":"0"},children:r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:ae.map((ne,Ie)=>{const ge=ne.transactionHash?f.getExplorerUrl(ne.chainId,ne.transactionHash):null;return r.jsx(Ga,{bg:X,border:Y,left:r.jsx("span",{style:{fontSize:"13px",color:U},children:ne.chainName?`On ${ne.chainName}`:ne.description||`Step ${Ie+1}`}),right:r.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:ne.status==="success"?"#10b981":ne.status==="failed"?"#ef4444":R,fontWeight:500},children:[ge&&r.jsx("a",{href:ge,target:"_blank",rel:"noopener noreferrer",style:{color:v?B.infoText:"#2563eb",textDecoration:"none"},onClick:Ye=>Ye.stopPropagation(),children:"View"}),ne.status==="success"?"\u2713":ne.status==="failed"?"\u2717":"\u25CB"]})},Ie)})})}),!O&&r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[W&&g&&r.jsx(f.Button,{variant:"outline",fullWidth:!0,onClick:g,theme:E,styles:p,dark:v,children:"TRY AGAIN"}),x&&r.jsxs(f.Button,{variant:"outline",fullWidth:!0,onClick:x,theme:E,styles:p,dark:v,children:["NEW ",o.toUpperCase()," \u2192"]})]})]});return C?r.jsxs("div",{style:{position:"absolute",bottom:0,left:0,right:0,zIndex:10,animation:j?"slideDown 0.3s ease-in forwards":"slideUp 0.3s ease-out forwards",pointerEvents:"auto"},children:[r.jsx("div",{style:{backgroundColor:M,borderRadius:"12px 12px 0 0",width:"100%",padding:"18px 24px 24px",boxShadow:L},children:Me}),r.jsx("style",{children:Ha})]}):r.jsx("div",{style:{backgroundColor:M,borderRadius:"12px",padding:"24px",width:"100%",boxShadow:D},children:Me})}if(!e&&!w||!w&&(!a||a.length===0))return null;const re=a?a.every(ae=>ae.success):!1,xe=a?.[0],he=[...a??[]].reverse().find(ae=>ae.txHash)?.txHash||xe?.txHash;return r.jsxs("div",{style:{position:C?"absolute":"relative",bottom:C?0:void 0,left:C?0:void 0,right:C?0:void 0,zIndex:C?10:void 0,animation:C?j?"slideDown 0.3s ease-in forwards":"slideUp 0.3s ease-out forwards":void 0,pointerEvents:"auto",width:"100%"},children:[r.jsx("div",{style:{backgroundColor:M,borderRadius:C?"12px 12px 0 0":"12px",width:"100%",padding:"18px 0 24px",boxShadow:C?L:D},children:r.jsxs("div",{style:{width:"100%",boxSizing:"border-box",padding:"0 24px"},children:[r.jsx(Va,{title:w?`Processing ${o.charAt(0).toUpperCase()+o.slice(1)}`:`${o.charAt(0).toUpperCase()+o.slice(1)} results`,showChevron:!w&&b,expanded:ce,onToggleDetails:w?void 0:de,showClose:!w,onClose:t,fontFamily:p?.fontFamily||E.typography.fontFamily,labelColor:R,textPrimary:U,closeHoverBg:q,closePressedBg:Z}),r.jsx("div",{style:{marginBottom:"16px",animation:"statusFadeIn 220ms cubic-bezier(0.22, 1, 0.36, 1) both"},children:w?r.jsx(Qa,{chainName:T,bg:V,border:J,textPrimary:U,labelColor:R,primaryColor:S}):r.jsx(qa,{isSuccess:re,type:o,chainName:T,explorerUrl:P,txHash:he,dark:v,..._,textSecondary:R})},w?"processing":re?"success":"error"),!w&&b&&a&&a.length>1&&r.jsx("div",{style:{overflow:"hidden",maxHeight:ce?"200px":"0px",opacity:ce?1:0,transition:"max-height 0.3s ease, opacity 0.3s ease",marginBottom:ce?"16px":"0"},children:r.jsx("div",{style:{maxHeight:"180px",overflowY:"auto",display:"flex",flexDirection:"column",gap:"8px"},children:a.map((ae,be)=>r.jsx(Ga,{bg:X,border:Y,left:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[r.jsx("span",{style:{fontWeight:600,fontSize:"13px",color:B.textPrimary,fontFamily:f.font.mono},children:ae.asset.symbol}),ae.amount&&r.jsx("span",{style:{fontSize:"12px",color:R},children:ae.amount})]}),right:r.jsx("span",{style:{fontSize:"12px",color:ae.success?"#10b981":"#ef4444",fontWeight:500},children:ae.success?"\u2713":"\u2717"})},be))})}),!w&&!re&&a&&r.jsx("div",{style:{padding:"12px",backgroundColor:B.errorBg,border:`1px solid ${B.errorBorder}`,borderRadius:"8px",marginBottom:"16px"},children:r.jsx("p",{style:{fontSize:"13px",color:B.errorText,margin:0,lineHeight:1.5},children:H||a.find(ae=>!ae.success)?.error||`${o.charAt(0).toUpperCase()+o.slice(1)} failed. Please try again.`})}),!w&&r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[!re&&y&&r.jsxs(f.Button,{variant:"outline",fullWidth:!0,onClick:y,theme:E,styles:p,dark:v,children:["TRY AGAIN ",o.toUpperCase()]}),re&&r.jsx(f.Button,{variant:"outline",fullWidth:!0,onClick:F,theme:E,styles:p,dark:v,children:"DONE"})]})]})}),r.jsx("style",{children:Ha})]})};function Ka(e){const t=new Set(k.getEquivalentAddresses(e).map(n=>n.toLowerCase()));return t.add(e.toLowerCase()),t}const gd=["USDC","USDT","WETH","WBTC"];function Za(e,t){const n=f.getChainConfig(t);if(!n)return;if(n.nativeCurrency.symbol.toUpperCase()===e.toUpperCase())return{address:k.ZERO_ADDRESS,symbol:n.nativeCurrency.symbol,decimals:n.nativeCurrency.decimals,chainId:t};const s=n.supportedTokens?.find(o=>o.symbol.toUpperCase()===e.toUpperCase());if(s)return{address:s.address.toLowerCase(),symbol:s.symbol,decimals:s.decimals,chainId:t}}function un(e,t,n){const s=f.getChainConfig(t);if(!s)return;if(n!==void 0){if(k.isNativeToken(e)&&!k.getTokenByAddress(e,n))return;const i=lo(e,n,t);return i?{address:i.address.toLowerCase(),symbol:i.symbol,decimals:i.decimals,chainId:t}:void 0}if(k.isNativeToken(e))return;const o=Ka(e),a=s.supportedTokens?.find(i=>o.has(i.address.toLowerCase()));if(a)return{address:a.address.toLowerCase(),symbol:a.symbol,decimals:a.decimals,chainId:t}}function xd(e){const{sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:o,intermediaryCandidates:a=gd}=e;if(vs(t,n))return{strategy:"direct",sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:o,summary:`${t.symbol} fronted directly`};if(s===o&&(k.isNativeToken(t.address)||!k.getTokenByAddress(t.address,s)))return{strategy:"direct-swap",sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:o,summary:`${t.symbol} \u2192 ${n.symbol} on chain ${s}, no escrow`};if(un(t.address,o,s))return{strategy:"direct",sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:o,summary:`${t.symbol} fronted on destination, swapped to ${n.symbol}`};if(un(n.address,s,o))return{strategy:"source-swap",sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:o,summary:`${t.symbol} \u2192 ${n.symbol} on source chain, then fronted`};for(const i of a){const l=Za(i,s);if(!l||vs(t,l)||vs(n,l))continue;const d=Za(i,o);if(d&&vs(l,d))return{strategy:"intermediary",sourceAsset:t,outputAsset:n,intermediaryAsset:d,sourceChainId:s,destinationChainId:o,summary:`${t.symbol} \u2192 ${i} on source, fronted, then ${i} \u2192 ${n.symbol} on destination`}}throw new f.SpiceflowError("ROUTE_STRATEGY_ERROR",`No viable cross-chain route found from ${t.symbol} (chain ${s}) to ${n.symbol} (chain ${o}). No intermediary asset is available on both chains.`,{sourceAsset:t.symbol,outputAsset:n.symbol,sourceChainId:s,destinationChainId:o,candidatesChecked:a})}async function yd(e){const{route:t,sourceAmount:n,userAddress:s,registry:o,actionCalls:a,slippage:i}=e;async function l(d,c,p,m){const h=await o.resolveSwap({type:"swap",tokenIn:c,tokenOut:p,amountIn:m,maxSlippage:i},d,s);if(!h)throw new f.SpiceflowError("NO_LIQUIDITY",`No venue returned a quote for ${c} \u2192 ${p} on chain ${d}. No liquidity available for this pair.`,{chainId:d,tokenIn:c,tokenOut:p,amountIn:m.toString()});return h}switch(t.strategy){case"direct-swap":{const d=await l(t.destinationChainId,t.sourceAsset.address,t.outputAsset.address,n);return{chainBatches:[{chainId:t.destinationChainId,calls:[...d.calls,...a]}],solverFrontToken:t.outputAsset,solverFrontAmount:0n,resolvedSwaps:{sourceSwap:d}}}case"direct":{const d=un(t.sourceAsset.address,t.destinationChainId,t.sourceChainId)||t.sourceAsset;if(Ka(d.address).has(t.outputAsset.address.toLowerCase()))return{chainBatches:[{chainId:t.destinationChainId,calls:a}],solverFrontToken:d,solverFrontAmount:n,resolvedSwaps:{}};const c=await l(t.destinationChainId,d.address,t.outputAsset.address,n);return{chainBatches:[{chainId:t.destinationChainId,calls:[...c.calls,...a]}],solverFrontToken:d,solverFrontAmount:n,resolvedSwaps:{destinationSwap:c}}}case"source-swap":{const d=un(t.outputAsset.address,t.sourceChainId,t.destinationChainId);if(!d)throw new f.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Output asset ${t.outputAsset.symbol} (${t.outputAsset.address}) not found on source chain ${t.sourceChainId}`,{token:t.outputAsset.symbol,address:t.outputAsset.address,chainId:t.sourceChainId,side:"source"});const c=un(t.outputAsset.address,t.destinationChainId,t.destinationChainId);if(!c)throw new f.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Output asset ${t.outputAsset.symbol} (${t.outputAsset.address}) not found on destination chain ${t.destinationChainId}`,{token:t.outputAsset.symbol,address:t.outputAsset.address,chainId:t.destinationChainId,side:"destination"});const p=await l(t.sourceChainId,t.sourceAsset.address,d.address,n);return{chainBatches:[{chainId:t.sourceChainId,calls:p.calls},{chainId:t.destinationChainId,calls:a}],solverFrontToken:c,solverFrontAmount:p.amountOutMinimum,resolvedSwaps:{sourceSwap:p}}}case"intermediary":{if(!t.intermediaryAsset)throw new f.SpiceflowError("ROUTE_STRATEGY_ERROR","Intermediary strategy requires an intermediary asset but none was provided in the route plan.",{strategy:t.strategy});const d=un(t.intermediaryAsset.address,t.sourceChainId,t.destinationChainId);if(!d)throw new f.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Intermediary ${t.intermediaryAsset.symbol} (${t.intermediaryAsset.address}) not found on source chain ${t.sourceChainId}`,{token:t.intermediaryAsset.symbol,address:t.intermediaryAsset.address,chainId:t.sourceChainId,side:"source"});const c=await l(t.sourceChainId,t.sourceAsset.address,d.address,n),p=await l(t.destinationChainId,t.intermediaryAsset.address,t.outputAsset.address,c.amountOutMinimum);return{chainBatches:[{chainId:t.sourceChainId,calls:c.calls},{chainId:t.destinationChainId,calls:[...p.calls,...a]}],solverFrontToken:t.intermediaryAsset,solverFrontAmount:c.amountOutMinimum,resolvedSwaps:{sourceSwap:c,destinationSwap:p}}}default:throw new f.SpiceflowError("ROUTE_STRATEGY_ERROR",`Unknown route strategy: ${t.strategy}`,{strategy:t.strategy})}}function wd(e,t,n){if(!e||!t)return null;const s=Dn(e,t),o=Object.entries(e.chainTokens??{}).flatMap(([m,h])=>{const g=cn(m);return g?.chainId===t?[{parsed:g,detail:h}]:[]}),a=m=>n.find(h=>f.addressesEqual(h.address,m))??null,i=m=>{const h=o.find(({parsed:y})=>f.addressesEqual(y.address,m));if(!h)return null;const g=f.getChainConfig(t);if(k.isNativeToken(m))return g?{address:k.ZERO_ADDRESS,symbol:g.nativeCurrency.symbol,name:g.nativeCurrency.name,decimals:g.nativeCurrency.decimals,logoURI:e.logoURI}:null;const x=g?.supportedTokens?.find(y=>f.addressesEqual(y.address,m));return!x||!io(e,m,t)?null:{address:h.parsed.address,symbol:x.symbol,name:x.name||h.detail?.name||e.displayName||e.name||e.symbol,decimals:x.decimals,logoURI:x.logo||e.logoURI}},l=o.map(({parsed:m})=>m.address).filter(k.isNativeToken);for(const m of[...s,...l]){if(k.isNativeToken(m)){const x=i(m);if(x)return x}const h=a(m);if(h)return h;const g=i(m);if(g)return g}if(e.chainTokens||e.receiptTokenId)return null;const d=Wt(e,t);if(d){const m=a(d);if(m)return m}const c=un(e.address,t,e.chainId);return c?a(c.address)||(n.length>0?null:{address:c.address,symbol:c.symbol||e.symbol,name:e.displayName||e.name||e.symbol,decimals:c.decimals??e.decimals,logoURI:e.logoURI}):null}function bd(e){const t=e.find(n=>k.isSpicenetChainId(n.chainId))?.calls?.[0]?.data;if(!t)return null;try{const n=A.decodeFunctionData({abi:k.spicenetAbi,data:t});return n.functionName!=="createWithdrawalRequest"?null:n.args[0].transfers.map(s=>({token:s.token,recipient:s.to,amount:s.amount}))}catch{return null}}function Cd(e,t){return!e||e.length!==t.length?!1:e.every((n,s)=>{const o=t[s];return n.token.toLowerCase()!==o.token.toLowerCase()||n.recipient.toLowerCase()!==o.recipient.toLowerCase()?!1:n.recipient.toLowerCase()===k.SPICE_GAS_FEE_RECIPIENT.toLowerCase()?Sn(n.amount,o.amount,100n):n.amount===o.amount})}function vd(e,t){const n=e.intents.flatMap(a=>a.batches).filter(a=>{const i=nn(a);return BigInt(a.quotedAmount)>0n||BigInt(a.totalDebit)>0n||i.totalFee>0n}),s=n.filter(a=>a.chainId===t),o=s.length>0?s:n;return o.length===1?o[0]:null}function kd(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const s=n.token.toLowerCase(),o=n.recipient.toLowerCase(),a=`${s}:${o}`,i=t.get(a);i?i.amount+=n.amount:t.set(a,{...n})}return[...t.values()]}function Ya(e,t){if(!e.token||!e.recipient||e.chainId===null)return null;const n=vd(t,e.chainId);if(!n)return null;const{gasFee:s,bridgeFee:o,spicenetFee:a}=nn(n),i=s+o,l=[{token:e.token.address,recipient:e.recipient,amount:e.receiveAmountRaw}];return i>0n&&l.push({token:e.token.address,recipient:k.SPICE_GAS_FEE_RECIPIENT,amount:i}),a>0n&&l.push({token:e.token.address,recipient:k.SPICE_PLATFORM_FEE_RECIPIENT,amount:a}),kd(l)}function Sd(e,t,n){const s=Ya(e,t);return!s||Cd(bd(n),s)?null:e.buildWithdrawBatches(s)}async function Xa(e){if(!(!e.batches.length||!e.walletAddress||!e.recipient)){e.ui.setIsExecuting(!0),e.ui.setExecutionError(null),e.ui.setExecutionProgress(null),e.executionContextRef.current=null,e.ui.setLockedGasFee(e.gasFee);try{let t=e.batches;if(e.isNon7702&&e.onWithdrawExecute)await e.onWithdrawExecute(e.amount);else{if(!e.isNon7702&&!t.some(o=>k.isSpicenetChainId(o.chainId)))throw new Error("Spice withdrawals must include a Spicenet funding batch before the destination chain batch.");const n=e.token?.address||"",s={useCustomTransfers:!0};if(e.buildSpicenetBatch){const o=e.feeEstimate??await e.execution.estimate(t,n,0n,s),a=Ya(e,o);a&&(t=e.buildWithdrawBatches(a));const i=o.intents[0]?.batches.find(l=>l.chainId===e.chainId)??o.intents[0]?.batches[0]??null;i&&e.ui.setLockedGasFee(nn(i).totalFee)}else{const o=(e.feeEstimate??await e.execution.estimate(t,n,0n,s)).intents[0]?.batches[0]??null;o&&e.ui.setLockedGasFee(nn(o).totalFee)}await e.execution.execute(t,n,0n,o=>{o.actionId&&o.intentId&&typeof o.intentIndex=="number"&&typeof o.totalSteps=="number"&&(e.executionContextRef.current={actionId:o.actionId,intentId:o.intentId,intentIndex:o.intentIndex,totalSteps:o.totalSteps}),e.ui.setExecutionProgress(o)},void 0,e.buildSpicenetBatch?{...s,adjustBatchesForEstimate:({feeEstimate:o,chainBatches:a})=>Sd(e,o,a)}:{...s,skipPreSubmitFeeEstimate:!0})}Ja(e)}catch(t){const n=t instanceof Error?t.message:"Withdraw failed";e.ui.setExecutionError(n)}finally{e.ui.setIsExecuting(!1)}}}function Ja(e){window.dispatchEvent(new CustomEvent("withdraw-completed")),e.onWithdrawSuccess?.({token:e.token?.symbol||"",amount:e.amount,chainId:e.chainId})}async function Id(e){const t=e.executionContextRef.current;if(!t){e.ui.setExecutionProgress(null),await Xa(e);return}e.ui.setIsExecuting(!0),e.ui.setExecutionError(null),e.ui.setExecutionProgress({step:"executing",message:"Resuming existing action...",actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps});try{let n=t.totalSteps;for(let s=0;s<t.totalSteps;s++)if((await f.relayerService.checkStepStatus(t.intentId,s)).data.status!=="success"){n=s;break}if(n>=t.totalSteps)e.ui.setExecutionProgress(s=>({...s||{step:"success",message:"Transaction successful!",actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps},step:"success",message:"Transaction successful!"}));else for(let s=n;s<t.totalSteps;s++){const o=await Sa({actionId:t.actionId,intentIndex:t.intentIndex,intentId:t.intentId,stepIndex:s,chainId:e.chainId??void 0,onStatusMessage:(a,i)=>{e.isMountedRef.current&&e.ui.setExecutionProgress({step:"executing",message:a,txHash:i,actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps})}});if(!e.isMountedRef.current)return;e.ui.setExecutionProgress({step:s===t.totalSteps-1?"success":"executing",message:s===t.totalSteps-1?"Transaction successful!":"Executing remaining steps...",txHash:o,actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps})}Ja(e)}catch(n){const s=n instanceof Error?n.message:"Withdraw failed";e.ui.setExecutionError(s)}finally{e.ui.setIsExecuting(!1)}}async function Ad(e){const t=await e.estimate(e.batches,e.tokenAddress,0n,{useCustomTransfers:!0,signal:e.signal}),n=t.intents.flatMap(o=>o.batches).filter(o=>nn(o).totalFee>0n),s=n.filter(o=>o.chainId===e.chainId)[0]??n[0]??t.intents[0]?.batches[0];if(!s)throw new Error("No gas fee estimate was returned for this withdraw.");return{gasFee:nn(s).totalFee,feeEstimate:t}}function zo(e,t){return A.formatUnits(e,t).replace(/(\.\d*?[1-9])0+$|\.0+$/,"$1")}function $a(e,t,n){return Pt(e,t,n,"floor")}function _a(e,t,n=!1){if(e<=0)return"$0";if(!t||!Number.isFinite(t)||t<=0)return"\u2014";const s=e*t;return`$${s>=1?s.toFixed(3).replace(/0+$/,"").replace(/\.$/,""):s.toFixed(4).replace(/0+$/,"").replace(/\.$/,"")}${n?" (stale)":""}`}function Ed(e,t){return t?JSON.stringify({tokenAddress:t.toLowerCase(),batches:e.map(n=>({chainId:n.chainId,calls:n.calls.map(s=>({to:s.to.toLowerCase(),value:s.value.toString(),data:s.data})),tokenTransfers:(n.tokenTransfers??[]).map(s=>({from:s.from,to:s.to.toLowerCase(),token:s.token.toLowerCase(),amount:s.amount.toString()}))}))}):null}function ei(e,t,n){const s=n.filter(o=>o.amount>0n);return{chainId:e,domain:"evm",tokenTransfers:[],calls:k.isNativeToken(t)?s.map(o=>({to:o.recipient,value:o.amount,data:"0x"})):s.map(o=>({to:t,value:0n,data:A.encodeFunctionData({abi:A.erc20Abi,functionName:"transfer",args:[o.recipient,o.amount]})}))}}new Set([k.SPICE_GAS_FEE_RECIPIENT,k.SPICE_PLATFORM_FEE_RECIPIENT].map(e=>e.toLowerCase()));function Fd(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const s=A.getAddress(n.token),o=A.getAddress(n.to),a=`${s.toLowerCase()}:${o.toLowerCase()}`,i=t.get(a);i?i.amount+=n.amount:t.set(a,{token:s,to:o,amount:n.amount})}return[...t.values()]}function jd(e,t){return`0x${t}${e.slice(4)}`}function ti(e,t,n,s){if(e.some(p=>p.domain==="spicenet"))return e;const o=n?.intents.flatMap(p=>p.batches),a=p=>p.from==="escrow",i=e.map(p=>{const m=o?.find(E=>E.chainId===p.chainId);if(!m)return p;const h=nn(m),g=h.totalFee;if(g<=0n)return p;const x=(p.tokenTransfers??[]).filter(E=>a(E)&&A.getAddress(E.to).toLowerCase()===t.toLowerCase()),y=x.find(E=>!k.isNativeToken(A.getAddress(E.token)))??x[0];if(!y)return p;const C=A.getAddress(y.token),w=k.isNativeToken(C);let b=!1;const I=(p.tokenTransfers??[]).map(E=>b||!a(E)||A.getAddress(E.to).toLowerCase()!==t.toLowerCase()||A.getAddress(E.token).toLowerCase()!==C.toLowerCase()?E:(b=!0,{...E,amount:s?.payoutAlreadyGross?BigInt(E.amount):BigInt(E.amount)+g}));if(!b)return p;const S=(E,j)=>w?{to:E,value:j,data:"0x"}:{to:C,value:0n,data:A.encodeFunctionData({abi:A.erc20Abi,functionName:"transfer",args:[E,j]})},v=[];h.spicenetFee>0n&&v.push(S(k.SPICE_PLATFORM_FEE_RECIPIENT,h.spicenetFee));const B=h.gasFee+h.bridgeFee;return B>0n&&v.push(S(k.SPICE_GAS_FEE_RECIPIENT,B)),{...p,tokenTransfers:I,calls:[...v,...p.calls]}}),l=i.flatMap(p=>(p.tokenTransfers??[]).filter(a).map(m=>{const h=A.getAddress(m.token),g=A.getAddress(m.to),x=[{token:h,to:g,amount:BigInt(m.amount)}];return{chainId:p.chainId,transfers:Fd(x)}}));if(l.length===0)return e;const d=s?.requestTimestampMs??Date.now(),c=BigInt(Math.floor(d/1e3))+3600n;return[{chainId:k.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:l.map((p,m)=>{const h=A.keccak256(A.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,p.transfers[0].token,p.transfers.reduce((x,y)=>x+y.amount,0n),BigInt(p.chainId),BigInt(d+m)])),g=jd(h,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:A.encodeFunctionData({abi:k.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${p.chainId}`,idempotenceKey:g,nbf:0n,exp:c,metadata:"{}",transfers:p.transfers.map(x=>({token:x.token.toLowerCase(),to:x.to,amount:x.amount}))}]})}})},...i]}function En(e,t,n,s){const o=e.filter(i=>i.domain!=="spicenet"),a=i=>(i.tokenTransfers??[]).some(l=>l.from==="escrow");return[...o.filter(i=>!a(i)),...ti(o.filter(a),t,n,s)]}function qo(e,t,n,s,o){const a=e[e.length-1];if(!a?.calls.length||a.domain==="spicenet")throw new Error("Proceeds fees require a final destination action");const i=[{to:k.SPICE_PLATFORM_FEE_RECIPIENT,amount:o},{to:k.SPICE_GAS_FEE_RECIPIENT,amount:s}].filter(l=>l.amount>0n);return e.map(l=>l===a?{...l,calls:[...l.calls,...i.map(d=>({to:n,value:0n,data:A.encodeFunctionData({abi:A.erc20Abi,functionName:"transfer",args:[d.to,d.amount]})}))],tokenTransfers:[...l.tokenTransfers??[],...i.map(d=>({from:t,to:d.to,token:n,amount:d.amount}))]}:l)}async function ni(e,t,n,s,o){const a=k.hashChainBatches(e),i=await f.relayerService.estimateBatchGas({user:t,outputToken:n,signal:s,requireSimulation:!0,includePlatformFee:o!==void 0,chainBatches:e.map((l,d)=>({...l,hash:a[d].hash}))});if(i.gasQuoteSource!=="estimated"||!i.simulationVerified)throw new Error("Action proceeds require a successful live batch simulation; fallback gas pricing is not sufficient");if(o!==void 0&&(i.platformFee===void 0||i.platformFee>o))throw new Error("Fee conversion platform price changed; refresh before retrying");return i.gasFee}async function Td(e){if(e.proceeds.token.toLowerCase()!==e.token.toLowerCase())throw new Error("Action proceeds must use the destination fee token");const t=await e.proceeds.resolve(e.signal);if(e.signal?.aborted)throw new Error("Action proceeds quote was cancelled");if(t<0n)throw new Error("Action proceeds cannot be negative");const n=await e.baseline();if(!n?.feeEstimate)throw new Error("Action fee quote is unavailable");let s=n.preview.gasFee;const o=n.preview.spicenetFee,a=n.preview.bridgeFee??0n;for(let i=0;i<5;i++){const l=s+o+a,d=t<l?t:l,c=l-d,p=c>0n?(c*110n+99n)/100n+2n:0n;let m=p,h;const g=En(await e.buildBatches(p,{onSourceSpend:C=>{m=C},onActionCalls:C=>{h=C}}),e.owner),x=qo(g,e.owner,e.token,s+a,o),y=await ni(x,e.owner,e.token,e.signal);if(y===s)return{preview:{...n.preview,grossAmount:p,netAmount:0n,gasFee:s,totalFee:l,gasQuoteSource:"estimated"},feeEstimate:n.feeEstimate,grossFundingAmount:p,proceedsAvailable:t,proceedsUsed:d,fundingBatches:x,sourceSpendCap:m,destinationAmount:0n,actionDefinition:h};s=y}throw new Error("Action proceeds fee estimate did not converge")}function si(e,t){let n,s;if(k.isNativeToken(t)){if(e.data!=="0x")return null;n=e.to,s=e.value}else{if(!f.addressesEqual(e.to,t))return null;try{const o=A.decodeFunctionData({abi:A.erc20Abi,data:e.data});if(o.functionName!=="transfer")return null;[n,s]=o.args}catch{return null}}return f.addressesEqual(n,k.SPICE_GAS_FEE_RECIPIENT)?{gas:s,platform:0n}:f.addressesEqual(n,k.SPICE_PLATFORM_FEE_RECIPIENT)?{gas:0n,platform:s}:null}function Ps(e,t,n){return e.map(s=>s.chainId===t?{...s,calls:s.calls.filter(o=>!si(o,n))}:s)}function Bd(e,t,n){if(!e.feeOnlyAction)return{};const s=e.embeddedWalletAddress??e.providerEmbeddedAddress;if(e.actionProceeds||e.feeQuote?.fundingConversion){const l=e.feeQuote?.fundingConversion,d=e.actionProceeds??{token:t,resolve:async()=>0n},c=e.feeQuote?.preview,p=e.feeQuote?.proceedsUsed,m=l?.fromProceeds?l.tokenIn:t;if(!c||p===void 0||d.token.toLowerCase()!==m.toLowerCase())throw new Error("Refresh the action proceeds quote");const h=c.gasFee+(c.bridgeFee??0n),g=c.spicenetFee,x=async()=>{e.validateFeeQuote?.();const C=await d.resolve(e.signal);if(e.validateFeeQuote?.(),e.signal?.aborted||(l?.fromProceeds?C<l.amountInMax||l.amountOut<h+g:C<p||C+(l?.amountOut??n)<h+g))throw new Error("Action proceeds changed; refresh before retrying");return l?.fromProceeds?[{chainId:e.resolvedChainId,token:l.tokenIn,amount:l.amountInMax},{chainId:e.resolvedChainId,token:t,amount:l.amountOut}]:[{chainId:e.resolvedChainId,token:t,amount:p+(l?.amountOut??0n)}]},y=async C=>{await x();const w=await ni(C,s,t,e.signal,l?g:void 0);if(await x(),(w>c.gasFee?w-c.gasFee:c.gasFee-w)*100n>w*15n)throw new Error("Action gas quote changed; refresh before retrying")};return{resolveActionOutputCredits:x,prepareForSigning:async C=>{const w=Ps(C,e.resolvedChainId,t).map(I=>({...I,tokenTransfers:I.tokenTransfers?.filter(S=>!(typeof S.from=="string"&&f.addressesEqual(S.from,s)&&(f.addressesEqual(S.to,k.SPICE_GAS_FEE_RECIPIENT)||f.addressesEqual(S.to,k.SPICE_PLATFORM_FEE_RECIPIENT))))})),b=qo(w,s,t,h,g);return await y(b),b},validateBeforeSubmit:y}}const o=k.getTokenByAddress(t,e.resolvedChainId),a={chainId:e.resolvedChainId,tokenAddress:t,symbol:o?.symbol??e.destinationToken.symbol,decimals:e.executionTokenDecimals??o?.decimals??e.destinationToken.decimals},i=async l=>{e.validateFeeQuote?.();const d=Ps(l,e.resolvedChainId,t),c=await e.execution.estimate(d,t,n,{userOverride:s,useCustomTransfers:!0,feeExecutionMode:"backend-transfer"});e.validateFeeQuote?.();const p=In(c,a);if(!p||p.chainId!==e.resolvedChainId)throw new Error("The fee service did not return the destination action's fee quote");if(p.gasFee+p.spicenetFee+(p.bridgeFee??0n)+2n>n)throw new Error("Fees exceed the displayed maximum funding; refresh the quote before retrying");return{raw:d,feeEstimate:c,fees:p}};return{prepareForSigning:async l=>{const{raw:d,feeEstimate:c}=await i(l);return En(d,s,c,{payoutAlreadyGross:!0})},validateBeforeSubmit:async l=>{const{fees:d}=await i(l);let c=0n,p=0n;for(const h of l)if(h.chainId===e.resolvedChainId)for(const g of h.calls){const x=si(g,t);x&&(c+=x.gas,p+=x.platform)}if(c+p+2n>n)throw new Error("Signed fees exceed the displayed maximum funding");const m=d.gasFee+(d.bridgeFee??0n);if((c>m?c-m:m-c)*100n>m*15n||p!==d.spicenetFee)throw new Error("The signed gas quote changed materially; refresh before retrying")}}}const Rd="0xa9059cbb";function os(e,t,n){return k.isNativeToken(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:A.encodeFunctionData({abi:A.erc20Abi,functionName:"transfer",args:[n,t]})}}function oi(e,t,n){return{chainId:n,calls:[os(e,t,k.getEscrowContractAddress(n))]}}function Dd(e,t,n,s){const o=t.source.chainId;return{chainId:o,calls:[...e.calls,os(t.source.address,n,k.getEscrowContractAddress(o)),...s>0n?[os(t.source.address,s,k.SPICE_GAS_FEE_RECIPIENT)]:[]]}}function ri(e,t){const n=e.amountOutMinimum-t;if(n<=0n)throw new Error("Amount is too small to cover fees. Increase the amount and retry.");return n}function ai(e,t,n){return e?.asset?._source==="wallet"&&e?.asset.chainId===n}function ii(e){return e.isNative||k.isNativeToken(e.address)?!0:!k.getTokenByAddress(e.address,e.chainId)}function li(e,t,n,s){return t!=="user-transfer"||!n||e.length===0||e[0]?.to.toLowerCase()!==s.toLowerCase()||!e[0]?.data.startsWith(Rd)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function rs(e,t,n,s){if(!t)return[e];const o=await t({...n,requestTimestampMs:s});return o?[o,e]:[e]}function Od(e){return e.filter(t=>t.domain!=="spicenet")}function as(e,t){const n=(e.tokenTransfers??[]).filter(s=>s.from==="escrow").map(s=>({token:k.normalizeNativeTokenAddress(s.token),recipient:s.to,amount:BigInt(s.amount)})).filter(s=>s.amount>0n);return t!==void 0&&n.length===1&&(n[0]={...n[0],amount:t}),n.length>0?n:void 0}function Wn(e,t,n){return Pt(e,t,n,"ceil")}function ci(e){const t=e.selectedAsset?.asset;return e.isPayMode&&!!t&&t._source==="wallet"&&t.chainId!==e.resolvedChainId&&!!e.pivot}function Ho(e){const t=e.selectedAsset?.asset;return!e.isPayMode&&!!t&&t._source==="wallet"&&t.chainId!==e.resolvedChainId&&!!e.sourceSwap&&!!e.pivot}function Us(e,t){if(t?.sourceSpendCap!==void 0&&e>t.sourceSpendCap)throw new Error("The source amount increased. Review the updated quote before submitting.");t?.onSourceSpend?.(e)}async function di(e,t,n){let s;const o=await e({...t,buildActionCalls:async(a,i)=>{s=a;const l=await t.buildActionCalls(a,i);return n?.onActionCalls?.({amount:a,context:i,calls:l}),l}},n);if(s!==void 0){if(n?.minimumDestinationAmount!==void 0&&s<n.minimumDestinationAmount)throw new Error("The destination amount decreased. Review the refreshed quote before submitting.");n?.onDestinationAmount?.(s)}return o}const Vo=(e,t)=>di(Nd,e,t),Ws=async(e,t)=>{const n=await di(Md,e,t),s=t?.actionContextOverride?.feeBreakdown,o=n[n.length-1];if(e.feeExecutionMode!=="user-transfer"||!s||!o)return n;const a=e.needsSwap&&e.resolvedTokenIn?e.resolvedTokenIn:e.destinationToken.address,[i]=Ps([o],e.resolvedChainId,a),l=ei(e.resolvedChainId,a,[{recipient:k.SPICE_PLATFORM_FEE_RECIPIENT,amount:s.spicenetFee},{recipient:k.SPICE_GAS_FEE_RECIPIENT,amount:s.gasFee+(s.bridgeFee??0n)}]).calls,d=o.calls.filter(c=>!i.calls.includes(c));return d.length===l.length&&l.every(c=>d.some(p=>p.to.toLowerCase()===c.to.toLowerCase()&&p.value===c.value&&p.data===c.data))?n:[...n.slice(0,-1),{...i,calls:[...l,...i.calls]}]};async function Nd(e,t){const{currentPaymentAmount:n,destinationToken:s,embeddedWalletAddress:o,providerEmbeddedAddress:a,address:i,isNon7702:l,resolvedChainId:d,buildActionCalls:c,feeExecutionMode:p,buildSpicenetBatch:m,selectedAsset:h,needsSwap:g,exactOutputSwap:x,resolvedTokenIn:y,requestTimestampMs:C}=e,w=t?.fundingTokenOverride??y,b=qt(n,s.decimals),I=e.feeOnlyAction?0n:t?.actionAmountOverride??b,S=!!e.feeOnlyAction&&(t?.fundingAmountOverride??0n)>0n,v=o||a||i;if(!v)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const B={userAddress:e.recipient??v,executorAddress:v,beneficiary:e.recipient??v,outputRecipient:g?v:void 0,chainId:d,destinationToken:s.address,grossAmount:t?.fundingAmountOverride??b,netAmount:I,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:p,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},E=await c(I,B),j={chainId:d,calls:E},N=!!h&&h.asset._source!=="wallet",T=ai(h??null,l,d),P=N||T&&!!h&&!ii(h.asset),M=(L,R)=>({token:k.normalizeNativeTokenAddress(L),from:"escrow",to:v,amount:R}),D=(L,R,U)=>T?[oi(L,R,d),...U]:U;if(b===0n&&!S)return[j];if(h?.asset._source==="wallet"&&h.asset.chainId!==d&&!e.pivot)throw new Error("A current source-to-destination funding route is required");if(e.feeOnlyAction&&t?.fundingTokenOverride&&T)return Us(t.fundingAmountOverride??0n,t),[j];if(ci(e)){if(g&&!x)throw new Error("Swap quote not available yet");const L=t?.fundingAmountOverride??(x?x.amountInMax:b),R=t?.sourceGasSkimOverride??0n,U=Pt(L,e.pivot.destination.decimals,e.pivot.source.decimals,"ceil"),X=U+R,Y=e.sourceExactOutputSwap,V=Y&&(t?.reuseQuotedSourceSwap||Y.amountOut>=X)?Y:e.resolveSourceExactOutputSwap?await e.resolveSourceExactOutputSwap(X):null;if(!V)throw new Error("Swap quote not available yet");Us(V.amountInMax,t);const J=h.asset;if(V.amountInMax>J.balance)throw new Error(`Insufficient ${J.symbol} for this payment. Required ${A.formatUnits(V.amountInMax,J.decimals)} ${J.symbol}; available ${A.formatUnits(J.balance,J.decimals)} ${J.symbol}.`);const ce=V.amountOut>=X?U:V.amountOut-R;if(ce<=0n)throw new Error("Amount is too small to cover fees. Increase the amount and retry.");const G={chainId:e.pivot.source.chainId,calls:[...V.calls,os(e.pivot.source.address,ce,k.getEscrowContractAddress(e.pivot.source.chainId)),...R>0n?[os(e.pivot.source.address,R,k.SPICE_GAS_FEE_RECIPIENT)]:[]]},q={chainId:d,calls:[...x?.calls??[],...E],tokenTransfers:[M(e.pivot.destination.address,L),...j.tokenTransfers??[]]},Z=await rs(q,m,{userAddress:v,destinationChainId:d,deliveryToken:e.pivot.destination.address,deliveryAmount:L,deliveryRecipient:v,deliveryTransfers:as(q),sourceAsset:h.asset},C);return[G,...Z]}if(h){const L=t?.fundingAmountOverride??x?.amountInMax??b;Us(Wn(L,await xn(h.asset,w??h.asset.address,d,s),h.asset.decimals),t)}if(g&&x){const L=w??Wt(h.asset,d)??h.asset.address,R=t?.fundingAmountOverride??x.amountInMax,U=P?[M(L,R)]:[],X={chainId:d,calls:[...x.calls,...E],tokenTransfers:[...U,...j.tokenTransfers??[]]};if(!P)return[X];const Y=await rs(X,m,{userAddress:v,destinationChainId:d,deliveryToken:L,deliveryAmount:R,deliveryRecipient:v,deliveryTransfers:as(X),sourceAsset:h.asset},C);return D(L,R,Y)}if(P){const L=w??Wt(h.asset,d)??s.address;if(T&&!e.feeOnlyAction&&L.toLowerCase()===s.address.toLowerCase())return[j];const R=t?.fundingAmountOverride??b,U={...j,tokenTransfers:[M(L,R),...j.tokenTransfers??[]]},X=await rs(U,m,{userAddress:v,destinationChainId:d,deliveryToken:L,deliveryAmount:R,deliveryRecipient:v,deliveryTransfers:as(U),sourceAsset:h.asset},C);return D(L,R,X)}return[j]}async function Md(e,t){const{selectedAsset:n,embeddedWalletAddress:s,recipient:o,resolvedChainId:a,destinationToken:i,buildActionCalls:l,feeExecutionMode:d,buildSpicenetBatch:c,isPayMode:p,isNon7702:m,needsSwap:h,resolvedSwap:g,quoteAmountOut:x,resolvedTokenIn:y,requestTimestampMs:C}=e;if(!n?.asset||!s)return[];const w=o??s;if(!w)return[];const b=Ho(e);let I=e.sourceSwap,S=qt(n.amount,n.asset.decimals),v=b?ri(e.sourceSwap,t?.sourceGasSkimOverride??0n):null;if(b&&!e.isFeeInclusiveInput&&t?.fundingAmountOverride!==void 0&&!t.reuseQuotedSourceSwap){v=Wn(t.fundingAmountOverride,e.pivot.destination.decimals,e.pivot.source.decimals);const H=v+(t.sourceGasSkimOverride??0n);if(!e.resolveSourceExactOutputSwap)throw new Error("The source quote cannot include fees yet.");const F=await e.resolveSourceExactOutputSwap(H);if(F.amountOut<H)throw new Error("The source quote does not cover the accepted funding amount.");S=F.amountInMax,I={...F,amountOutMinimum:F.amountOut}}const B=b?e.pivot.destination.address:y??Wt(n.asset,a)??i.address,E=b?e.pivot.destination.decimals:await xn(n.asset,B,a,i),j=t?.fundingAmountOverride??t?.actionAmountOverride??(b?Pt(v,e.pivot.source.decimals,E,"floor"):Ms(qt(n.amount,n.asset.decimals),n.asset.decimals,E)),N=t?.fundingAmountOverride??j,T=t?.sourceFundingAmountOverride??Wn(j,E,n.asset.decimals);Us(b?S:T,t);const P=t?.deliveryAmountOverride??(d==="user-transfer"?N:t?.actionContextOverride?.netAmount??N),M=t?.withdrawalAmountOverride??N,D=t?.actionAmountOverride??t?.actionContextOverride?.netAmount??j;let L=g;if(h&&!p&&(t?.actionContextOverride?.netAmount!==void 0||b&&(t?.sourceGasSkimOverride??0n)>0n&&!t?.reuseQuotedSourceSwap)){if(!e.resolveInputSwap)throw new Error("Swap quote cannot be refreshed for the amount after fees.");const H=t?.actionContextOverride?.netAmount??D;(!L||e.swapInputAmount!==H)&&(L=await e.resolveInputSwap(H))}L&&t?.onSwap?.(L,t?.actionContextOverride?.netAmount??e.swapInputAmount??D);const R=L?.amountOutMinimum??x,U={userAddress:w,executorAddress:s,beneficiary:w,outputRecipient:h?s:void 0,chainId:a,destinationToken:i.address,feeToken:d==="user-transfer"&&h&&y?y:i.address,grossAmount:N,netAmount:D,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:d,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},X=await l(D,U),Y=n.asset?._source==="wallet";if(!p&&Y&&n.asset.chainId===a&&ii(n.asset)){if(h){if(!y)throw new Error("Swap input token could not be resolved");if(!L||R===null)throw new Error("Swap quote not available yet")}if(h&&L&&R){const H=await l(t?.actionAmountOverride??R,{...U,netAmount:t?.actionAmountOverride??R}),{feeCall:F,remainingCalls:de}=li(H,d,h,U.feeToken);return[{chainId:a,calls:[...F?[F]:[],...L.calls,...de]}]}return[{chainId:a,calls:X}]}if(!p&&Y&&n.asset.chainId!==a&&!b)throw new Error("A current source-to-destination funding route is required");const V=n.asset._source!=="wallet",J=ai(n,m,a);if(!(V||J||b))return[{chainId:a,calls:X}];const ce=b?Dd(I,e.pivot,v,t?.sourceGasSkimOverride??0n):J?oi(y??k.normalizeNativeTokenAddress(n.asset.address),T,a):null,G=(H,F)=>({token:k.normalizeNativeTokenAddress(H),from:"escrow",to:s,amount:F});if(h){if(!y)throw new Error("Swap input token could not be resolved");if(!L||R===null)throw new Error("Swap quote not available yet")}if(h&&L&&R&&y){const H=await l(t?.actionAmountOverride??R,{...U,netAmount:t?.actionAmountOverride??R}),{feeCall:F,remainingCalls:de}=li(H,d,h,U.feeToken),re={chainId:a,calls:[...F?[F]:[],...L.calls,...de],tokenTransfers:[G(y,P)]},xe=await rs(re,c,{userAddress:s,destinationChainId:a,deliveryToken:y,deliveryAmount:P,withdrawalAmount:M,deliveryRecipient:s,deliveryTransfers:as(re,M),sourceAsset:n.asset},C);return ce?[ce,...xe]:xe}const q=y??Wt(n.asset,a)??i.address,Z={chainId:a,calls:X,tokenTransfers:[G(q,P)]},_=await rs(Z,c,{userAddress:s,destinationChainId:a,deliveryToken:q,deliveryAmount:P,withdrawalAmount:M,deliveryRecipient:s,deliveryTransfers:as(Z,M),sourceAsset:n.asset},C);return ce?[ce,..._]:_}async function Pd(e,t,n,s,o){let a=e;for(let i=0;i<4;i++){const l=await t(a),d=await s(l,n,a,o),c=zc(d);if(c===null||c>=e)return a;const p=a-c,m=e+p;if(m<=a)return a;a=m}return a}function Ud(e){return{...e,resolve:async(t,n,s)=>{const o=await e.resolve(t,n,s),a=o?.calls[0]?.to;return!o||!a||k.isNativeToken(t.tokenIn)?o:{...o,calls:[{to:t.tokenIn,value:0n,data:A.encodeFunctionData({abi:A.erc20Abi,functionName:"approve",args:[a,o.amountInMax]})},...o.calls]}}}}function Ls(e){const t=(e?.customVenues??[]).map(s=>fl(Ud(s)));async function n(s,o,a){const i=t.filter(c=>c.chainIds.includes(o));if(i.length===0)throw new f.SpiceflowError("NO_SWAP_ROUTE",`No exact-output venue supports chain ${o}`,{chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut});const l=(await Promise.allSettled(i.map(async c=>({venue:c,quote:await c.resolve(s,o,a)})))).filter(c=>c.status==="fulfilled").map(c=>c.value).filter(c=>c.quote!==null);if(l.length===0)throw new f.SpiceflowError("NO_SWAP_ROUTE",`All aggregators failed for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}`,{chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountOut:s.amountOut.toString()});const d=l.find(c=>c.venue.preferred);return d?d.quote:(l.sort((c,p)=>c.quote.amountIn<p.quote.amountIn?-1:c.quote.amountIn>p.quote.amountIn?1:0),l[0].quote)}return{getQuote:n,venues:t}}function Wd(e,t,n){if(e._source==="wallet")return e.chainId===t?e.address:null;const s=Dn(e,t);return s.find(o=>o.toLowerCase()===n.toLowerCase())??s[0]??null}class Ld extends Error{constructor(t,n){super("The selected balance cannot cover the fee funding amount"),this.requiredAmount=t,this.balance=n,this.name="InsufficientFeeFundingBalanceError"}}async function ui(e){const t=e.selectedAsset?.asset,n=!!e.actionProceeds&&e.actionProceeds.token.toLowerCase()!==e.destinationToken.address.toLowerCase(),s=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!s||!n&&(!t||t._source!=="spice"&&!(t._source==="wallet"&&t.chainId===e.resolvedChainId)))throw new Error("A local embedded or Spice balance is required for fee conversion");const o=n?e.actionProceeds.token:Wd(t,e.resolvedChainId,e.destinationToken.address);if(!o)throw new Error("This receipt has no registered destination withdrawal token");const a=k.getTokenByAddress(o,e.resolvedChainId)?.decimals??(k.isNativeToken(o)?18:n?k.isNativeToken(o)?18:await f.getClientForChain(e.resolvedChainId).readContract({address:o,abi:A.erc20Abi,functionName:"decimals"}):t?._source==="wallet"?t.decimals:void 0);if(a===void 0)throw new Error("Fee funding token metadata is unavailable");const i=e.destinationToken.address;if(e.actionProceeds&&!n&&e.actionProceeds.token.toLowerCase()!==i.toLowerCase())throw new Error("Action proceeds must use the destination fee token");const l=e.actionProceeds?await e.actionProceeds.resolve(e.signal):0n;if(l<0n||e.signal?.aborted)throw new Error("Action proceeds quote was cancelled or invalid");const d=Ls({customVenues:[...e.resolveExactOutputSwap?[{name:"consumer-exact-output",chainIds:[e.resolvedChainId],preferred:!0,resolve:e.resolveExactOutputSwap}]:[],...Rn(e.liquidityVenues).output]}),c=async m=>{const h=k.hashChainBatches(m),g=await f.relayerService.estimateBatchGas({user:s,outputToken:i,requireSimulation:!0,includePlatformFee:!0,signal:e.signal,chainBatches:m.map((x,y)=>({...x,hash:h[y].hash}))});if(!g.simulationVerified||g.gasQuoteSource!=="estimated"||g.platformFee===void 0||g.gasFee<=0n)throw new Error("Fee conversion requires verified gas and platform pricing");return g};let p=await c(await e.buildPayChainBatches({fundingAmountOverride:0n}));for(let m=0;m<8;m++){const h=p.gasFee+p.platformFee,g=n?0n:l<h?l:h,x=h-g,y=x>0n?(x*110n+99n)/100n+2n:0n,C=y>0n?await d.getQuote({tokenIn:o,tokenOut:i,amountOut:y,maxSlippage:e.maxSlippage},e.resolvedChainId,s):null;if(e.signal?.aborted)throw new Error("Fee conversion quote was cancelled");if(C&&(C.amountOut!==y||C.amountInMax<=0n||C.amountInMax<C.amountIn||!C.calls.length))throw new Error("Invalid exact-output fee conversion quote");const w=C?.amountInMax??0n,b=n?0n:Wn(w,a,t.decimals);if(n&&w>l)throw new Error("Action proceeds cannot cover the quoted fee conversion; choose an account balance");if(!n&&b>t.balance)throw new Ld(b,t.balance);let I,S=En(await e.buildPayChainBatches({fundingAmountOverride:n?0n:w,...n?{}:{fundingTokenOverride:o},onActionCalls:B=>{I=B}}),s);if(C){const B=S.length-1;S=S.map((E,j)=>j===B?{...E,calls:[...E.calls,...C.calls]}:E)}S=qo(S,s,i,p.gasFee,p.platformFee);const v=await c(S);if(v.gasFee<=p.gasFee&&(p.gasFee-v.gasFee)*100n<=v.gasFee*15n&&v.platformFee===p.platformFee){const B={tokenIn:o,tokenOut:i,amountInMax:w,amountOut:y,sourceAmountMax:b,...n?{fromProceeds:!0}:{}};return{feeEstimate:null,preview:{symbol:e.destinationToken.symbol,decimals:e.destinationToken.decimals,grossAmount:n?0n:y,netAmount:0n,gasFee:p.gasFee,spicenetFee:p.platformFee,totalFee:h,gasQuoteSource:"estimated"},grossFundingAmount:n?0n:w,proceedsAvailable:l,proceedsUsed:n?h:g,fundingConversion:B,fundingBatches:S,sourceSpendCap:b,destinationAmount:0n,actionDefinition:I}}p=v}throw new Error("Fee conversion pricing did not converge")}async function Qo(e){const[t]=await e.buildSupplyChainBatches({sourceGasSkimOverride:1n,reuseQuotedSourceSwap:!0});if(!t)throw new Error("Swap quote not available yet");const{gasFee:n}=await f.relayerService.estimateBatchGas({user:e.user,outputToken:e.pivot.source.address,stepIndex:0,chainBatches:[t],signal:e.signal});return n}const pi=(e,t)=>(e+t-1n)/t;function fi(e,t){const n=e.spicenetFee+(e.bridgeFee??0n);return e.grossAmount<=n?t+e.gasFee+n:pi((t+e.gasFee)*e.grossAmount,e.grossAmount-n)+2n}async function mi(e){const{requiredNetFunding:t}=e;if(e.feeOnlyAction){const c=e.executionOptions?.userOverride;if(!c||t!==0n)throw new Error("Fee-only estimates require a zero action amount and its embedded executor");let p=1n,m;for(let h=0;h<8;h++){const g=En(await e.buildBatches(p),c,m,{payoutAlreadyGross:!0}),x=await e.estimate(Ps(g,e.tokenDescriptor.chainId,e.fundingToken),e.fundingToken,p,{...e.executionOptions,feeExecutionMode:"backend-transfer"}),y=In(x,e.tokenDescriptor);if(!y)throw new Error("The fee service did not return a fee quote for this action");const C=y.gasFee+y.spicenetFee+(y.bridgeFee??0n);if(m&&C+2n<=p)return{preview:{...y,grossAmount:p,netAmount:0n},feeEstimate:x,grossFundingAmount:p};p=(C*110n+99n)/100n+2n,m=x}throw new Error("Fee-only funding did not converge; refresh the fee quote before retrying")}const n=await e.buildBatches(t),s=await e.estimate(n,e.fundingToken,t,e.executionOptions),o=In(s,e.tokenDescriptor);if(!o)return{preview:js(n,e.tokenDescriptor,t),feeEstimate:s,grossFundingAmount:t};const a=fi(o,t),i=c=>o.grossAmount>0n?pi(c*a,o.grossAmount):c,l=i(o.spicenetFee),d=i(o.bridgeFee??0n);return{preview:{...o,grossAmount:a,netAmount:t,spicenetFee:l,bridgeFee:d,totalFee:o.gasFee+l+d},feeEstimate:s,grossFundingAmount:a}}async function hi(e){if(e.balance<=0n)throw new Error("No spendable balance remains after source gas.");let t=e.balance;for(let n=0;n<8;n++){const s=await e.planForAmount(t);if(!s||s.sourceSpendCap===void 0||s.sourceSpendCap<=0n)throw new Error("Max requires a current route and fee estimate.");if(s.sourceSpendCap<=e.balance)return es(t,e.decimals);const o=t*e.balance/s.sourceSpendCap;if(o<=0n||o>=t)throw new Error("The balance cannot cover this action and its fees.");t=o}throw new Error("Max fees did not converge. Refresh the quote before retrying.")}async function zd(e){if(e.isPayMode||e.needsSwap||e.isQuoting||e.pivot||!e.embeddedWalletAddress)return null;const t=e.asset,n=k.getTokenByAddress(e.executionTokenAddress,t.chainId);return!n||t.balance<=0n?null:hi({balance:t.balance,decimals:t.decimals,planForAmount:s=>is({selectedAsset:{asset:t,amount:es(s,t.decimals)},isPayMode:!1,isNon7702:!1,isFeeInclusiveInput:!1,parsedAmount:Number(es(s,t.decimals)),currentPaymentAmount:"0",destinationToken:{...n,address:e.executionTokenAddress,chainId:t.chainId},resolvedChainId:t.chainId,resolvedTokenIn:e.executionTokenAddress,executionTokenAddress:e.executionTokenAddress,embeddedWalletAddress:e.embeddedWalletAddress,providerEmbeddedAddress:e.embeddedWalletAddress,address:e.embeddedWalletAddress,isConnected:!0,ready:!0,authenticated:!0,isDirect:!0,isSourceDestToken:!0,needsSwap:!1,isQuoting:!1,resolvedSwap:null,exactOutputSwap:null,buildPayChainBatches:async()=>[],buildSupplyChainBatches:o=>e.buildSupplyChainBatches({...o,actionAmountOverride:s}),estimate:e.estimate,feeExecutionMode:e.feeExecutionMode})})}async function is(e){const{signal:t,selectedAsset:n,isPayMode:s,isFeeInclusiveInput:o=!1,parsedAmount:a,needsSwap:i,exactOutputSwap:l,isNon7702:d,currentPaymentAmount:c,destinationToken:p,feeExecutionMode:m,resolvedTokenIn:h,embeddedWalletAddress:g,providerEmbeddedAddress:x,resolvedChainId:y,isConnected:C,address:w,ready:b,authenticated:I,isDirect:S,resolvedSwap:v,sourceSwap:B,pivot:E,isQuoting:j,executionTokenAddress:N,buildPayChainBatches:T,buildSupplyChainBatches:P,estimate:M}=e;if(e.feeOnlyAction&&e.actionProceeds&&e.actionProceeds.token.toLowerCase()!==p.address.toLowerCase()||e.feeOnlyAction&&n&&(n.asset._source==="spice"||n.asset._source==="wallet"&&n.asset.chainId===y)&&(h?h.toLowerCase()!==p.address.toLowerCase():n.asset.receiptTokenId||n.asset.chainTokens))return ui(e);if(e.actionProceeds&&e.feeOnlyAction){const G=g||x;if(!G||!b||!I)return null;if(h&&h.toLowerCase()!==p.address.toLowerCase())throw new Error("Action proceeds require a matching fee-token source");return Td({proceeds:e.actionProceeds,owner:G,token:p.address,signal:t,buildBatches:(q,Z)=>T({...Z,fundingAmountOverride:q}),baseline:()=>is({...e,actionProceeds:void 0,selectedAsset:n??{amount:"0",asset:{...p,name:p.symbol,balance:0n,balanceFormatted:0,balanceUsd:0,isNative:!1,_source:"spice"}}})})}if(!n?.asset)return null;if(s){if(!g&&!x||a<=0&&!e.feeOnlyAction||i&&!l&&!e.feeOnlyAction)return null;const G=qt(c,p.decimals),q=h||Wt(n.asset,y)||n.asset.address||p.address,Z={chainId:y,tokenAddress:q,symbol:k.getTokenByAddress(q,y)?.symbol??n.asset.symbol,decimals:await xn(n.asset,q,y,p)};if(!C||!w||!b||!I)return null;const _=g||x||w,H=i?l?.amountInMax??0n:G;if(H===0n&&!e.feeOnlyAction)return null;const F=E?await Qo({user:_,pivot:E,buildSupplyChainBatches:O=>T({...O,sourceGasSkimOverride:1n}),signal:t}):0n;let de=await mi({requiredNetFunding:H,feeOnlyAction:e.feeOnlyAction,buildBatches:O=>T({fundingAmountOverride:O,sourceGasSkimOverride:F}).then(se=>ti(Od(se),_)),fundingToken:q,estimate:M,executionOptions:{userOverride:_,useCustomTransfers:!0,feeExecutionMode:m,signal:t},tokenDescriptor:Z});if(!de.preview)return null;let re=0n,xe,he=[],ae=!1;for(let O=0;O<8;O++){if(t?.aborted)throw new Error("Fee estimation cancelled");if(he=En(await T({fundingAmountOverride:de.grossFundingAmount,sourceGasSkimOverride:F,onSourceSpend:Ce=>{re=Ce},onActionCalls:Ce=>{xe=Ce}}),_,de.feeEstimate,{payoutAlreadyGross:!0}),e.feeOnlyAction){ae=!0;break}const se=await M(he,q,de.grossFundingAmount,{userOverride:_,useCustomTransfers:!0,feeExecutionMode:m,signal:t}),W=In(se,Z)??js(he,Z,H);if(!W)return null;const $=W.gasQuoteSource==="static_zero"?H:fi(W,H),oe=de.grossFundingAmount>=$&&de.grossFundingAmount-$<=2n;if(de={feeEstimate:se,grossFundingAmount:oe?de.grossFundingAmount:$,preview:{...W,grossAmount:oe?de.grossFundingAmount:$,netAmount:H}},oe){ae=!0;break}}if(!ae)throw new Error("Payment fees did not converge. Refresh the quote before submitting.");if(!de.preview)return null;const be=E?Pt(F,E.source.decimals,E.destination.decimals,"ceil"):0n;return{...de,batches:he,sourceSpendCap:re,actionDefinition:xe,destinationAmount:G,preview:{...de.preview,grossAmount:de.preview.grossAmount+be,gasFee:de.preview.gasFee+be,totalFee:(de.preview.totalFee??0n)+be},...E?{sourceGasSkim:F}:{}}}if(a<=0||!g)return null;const D=g||x;if(E&&!B)return null;const L=Ho({isPayMode:s,selectedAsset:n,resolvedChainId:y,sourceSwap:B,pivot:E});if(!(!s&&!d&&n.asset?._source==="wallet"&&n.asset.chainId!==y)&&!S&&!v&&!j||j)return null;let R=await P();if(R.length===0)return null;const U={chainId:y,tokenAddress:N,symbol:k.getTokenByAddress(N,y)?.symbol??(n.asset.chainId===y&&f.addressesEqual(n.asset.address,N)?n.asset.symbol:p.symbol),decimals:await xn(n.asset,N,y,p)},X=L?await Qo({user:D,pivot:E,buildSupplyChainBatches:P,signal:t}):0n;L&&X>0n&&(R=await P({sourceGasSkimOverride:X}));const Y=L?Pt(o?ri(B,X):B.amountOutMinimum,E.source.decimals,E.destination.decimals,"floor"):Pt(qt(n.amount,n.asset.decimals),n.asset.decimals,U.decimals,"floor"),V={userOverride:D,useCustomTransfers:!0,feeExecutionMode:m,signal:t,...L?{skipUserFundingPreflight:!0}:{}};let J=Y,ce=await M(R,N,J,V);for(let G=0;G<8;G++){if(t?.aborted)throw new Error("Fee estimation cancelled");const q=In(ce,U)??js(R,U,J);if(!q)return null;const Z=Go(q,Y,o,m);J=Z.grossAmount;let _,H,F,de,re;const xe=await P({fundingAmountOverride:J,sourceGasSkimOverride:X,actionContextOverride:Z,onDestinationAmount:O=>{_=O},onSourceSpend:O=>{H=O},onSwap:(O,se)=>{F=O,de=se},onActionCalls:O=>{re=O}}),he=await M(xe,N,J,V),ae=In(he,U)??js(xe,U,J);if(!ae)return null;const be=Go(ae,Y,o,m);if(JSON.stringify(Z,(O,se)=>typeof se=="bigint"?se.toString():se)===JSON.stringify(be,(O,se)=>typeof se=="bigint"?se.toString():se)){const O=L?Pt(X,E.source.decimals,E.destination.decimals,"ceil"):0n;return{batches:xe,fundingAmount:J,actionContext:Z,sourceSpendCap:H,destinationAmount:_,destinationSwap:F,swapInputAmount:de,actionDefinition:re,feeEstimate:he,sourceGasSkim:X,preview:{...ae,grossAmount:J+O,netAmount:Z.netAmount,gasFee:ae.gasFee+O,spicenetFee:Z.feeBreakdown.spicenetFee,totalFee:Z.combinedFeeAmount+O}}}ce=he,R=xe}throw new Error("Fees did not converge. Refresh the quote before submitting.")}function Go(e,t,n,s){const o=e.gasFee+(e.bridgeFee??0n);if(e.gasQuoteSource==="static_zero")return{grossAmount:t,netAmount:t,combinedFeeAmount:0n,feeExecutionMode:s??"backend-transfer",feeBreakdown:{gasFee:0n,bridgeFee:0n,spicenetFee:0n}};const a=n?Uc(t,o,10n):null;if(a&&!a.coversFees)throw new Error("Amount is too small to cover fees. Increase the amount and retry.");const i=a?.spicenetFee??(s==="user-transfer"?Fs(t,10n):e.spicenetFee);return{grossAmount:a?.grossAmount??t+i+o,netAmount:a?.netAmount??t,combinedFeeAmount:i+o,feeExecutionMode:s??"backend-transfer",feeBreakdown:{gasFee:e.gasFee,bridgeFee:e.bridgeFee??0n,spicenetFee:i}}}function qd(e,t){const n=e.selectedAsset?.asset;if(!n||n?._source!=="wallet")return;const s=Wt(n,e.resolvedChainId);if(!s||!f.addressesEqual(s,e.executionTokenAddress))return;const o=k.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),a=Wn(t,o?.decimals??e.destinationToken.decimals,n.decimals);if(a<=n.balance)return;const i=A.formatUnits(a,n.decimals),l=A.formatUnits(n.balance,n.decimals);throw new Error(`Insufficient ${n.symbol} for this total amount. Required ${i} ${n.symbol}; available ${l} ${n.symbol}.`)}function Hd(e){const t=k.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:t?.symbol??e.destinationToken.symbol,decimals:t?.decimals??e.destinationToken.decimals}}function Vd(e){const t=e.selectedAsset.asset,n=qt(e.selectedAsset.amount,t.decimals);if(n<=t.balance)return n;throw new Error(`Insufficient ${t.symbol} for this total amount. Required ${A.formatUnits(n,t.decimals)} ${t.symbol}; available ${A.formatUnits(t.balance,t.decimals)} ${t.symbol}.`)}async function Qd(e,t){return e.feeQuote?.sourceGasSkim!==void 0?e.feeQuote.sourceGasSkim:Qo({user:t,pivot:e.pivot,buildSupplyChainBatches:e.execution.buildSupplyChainBatches})}function Gd(e,t,n){const s=In(e,Hd(t));if(s)return Go(s,n,!!t.isFeeInclusiveInput,t.feeExecutionMode)}function Kd(e,t,n){let s=0n,o=0n;const a=n.toLowerCase();for(const i of e)if(i.chainId===t){for(const l of i.calls??[])if(l.to.toLowerCase()===a)try{const d=A.decodeFunctionData({abi:A.erc20Abi,data:l.data});if(d.functionName!=="transfer")continue;const c=d.args[0].toLowerCase(),p=d.args[1];c===k.SPICE_PLATFORM_FEE_RECIPIENT.toLowerCase()?s+=p:c===k.SPICE_GAS_FEE_RECIPIENT.toLowerCase()&&(o+=p)}catch{continue}}return{spicenetFee:s,gasFee:o}}function Zd(e,t,n){const s=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,o=Kd(e,t.resolvedChainId,s);return o.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||o.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:Sn(o.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&Sn(o.gasFee,n.feeBreakdown.gasFee,100n)}function Yd(e,t){return e?Sn(e.grossAmount,t.grossAmount,100n)&&Sn(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&Sn(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&Sn(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}function Xd(e,t){const n=k.getTokenByAddress(t,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:t,symbol:n?.symbol??e.selectedAsset?.asset.symbol??"",decimals:n?.decimals??e.selectedAsset?.asset.decimals??e.destinationToken.decimals}}async function Jd(e,t){const n=e.feeQuote;return n?.feeEstimate&&n.grossFundingAmount!==void 0?{grossFundingAmount:n.grossFundingAmount,feeEstimate:n.feeEstimate}:mi({...t,feeOnlyAction:e.feeOnlyAction,estimate:e.execution.estimate,tokenDescriptor:Xd(e,t.fundingToken)})}function $d(e,t,n){const s=t instanceof Error?t:new Error(String(t));if(s.name==="AbortError"||n){e.ui.setStep("idle");return}const o=s.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(o),e.ui.setError(o)}function _d(e,t){const n=f.sanitizeError(t,"Payment failed. Please try again.");e.ui.setError(n),e.ui.setPaymentResult({status:"failed",error:n})}async function gi(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=e.embeddedWalletAddress||e.providerEmbeddedAddress,s=Ho(e),o=s?await Qd(e,n):0n,a=y=>e.execution.buildSupplyChainBatches(s?{...y,sourceGasSkimOverride:o}:y);s&&Vd(e);const i=e.feeQuote?.batches?e.feeQuote:await is({...e,feeExecutionMode:e.feeExecutionMode,isDirect:!e.needsSwap,isQuoting:!1,resolvedSwap:null,buildPayChainBatches:e.execution.buildPayChainBatches,buildSupplyChainBatches:e.execution.buildSupplyChainBatches,estimate:e.execution.estimate});if(!i?.batches||i.fundingAmount===void 0||!i.actionContext)throw new Error("A current action plan is required. Refresh the quote before submitting.");const l=e.isFeeInclusiveInput?i.actionContext.grossAmount:i.actionContext.netAmount;let d=i.batches;const c=d.some(y=>y.tokenTransfers?.length),p={userOverride:n,useCustomTransfers:c,feeExecutionMode:e.feeExecutionMode,...s?{skipUserFundingPreflight:!0}:{}},m=i.fundingAmount,h=i.actionContext;qd(e,m);let g=h;const x=await e.execution.execute(d,e.executionTokenAddress,c?m:0n,e.execution.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...p,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:y,chainBatches:C})=>{const w=Gd(y,e,l);if(!w)return null;const b=Yd(g,w),I=Zd(C,e,w);return b||I?null:(g=w,a({fundingAmountOverride:w.grossAmount,actionContextOverride:w}))}}:{...p,skipPreSubmitFeeEstimate:!0});e.ui.setTxHash(x),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){$d(e,n,t.signal.aborted)}finally{e.ui.setIsExecuting(!1)}}async function xi(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}const t=e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t){e.ui.setError("Select a payment source");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.parsedAmount>0&&e.needsSwap&&!e.exactOutputSwap){e.ui.setError("Swap quote not available. Try a different asset.");return}const n=ci(e)&&!t,s=n?e.feeQuote?.sourceGasSkim??0n:0n,o=a=>e.execution.buildPayChainBatches(n?{...a,sourceGasSkimOverride:s}:a);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 a=qt(e.currentPaymentAmount,e.destinationToken.decimals),i={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,...n?{skipUserFundingPreflight:!0}:{}};if(t&&!e.feeOnlyAction){const w=await o(),b=await e.execution.execute(w,e.executionTokenAddress,0n,I=>{I.txHash&&(e.ui.setPaymentResult(S=>({...S??{status:"processing"},txHash:I.txHash})),e.ui.setTxHash(I.txHash))},void 0,i);e.ui.setPaymentResult(I=>({status:"success",txHash:I?.txHash||b}));return}const l=e.selectedAsset?.asset;if(!l&&!e.actionProceeds)throw new Error("Select a payment source");const d=e.feeQuote?.fundingConversion?.tokenIn||e.resolvedTokenIn||l?.address||e.destinationToken.address,c=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:a,p=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,{grossFundingAmount:m,feeEstimate:h}=e.feeQuote?.fundingConversion?{grossFundingAmount:e.feeQuote.grossFundingAmount,feeEstimate:void 0}:await Jd(e,{requiredNetFunding:c,buildBatches:w=>e.execution.buildPayChainBatches({fundingAmountOverride:w}).then(b=>En(b,p)),fundingToken:d,executionOptions:i});let g=e.feeQuote?.fundingBatches??e.feeQuote?.batches??En(await o({fundingAmountOverride:m}),p,e.actionProceeds?void 0:h,{payoutAlreadyGross:!0});const x=Bd(e,e.feeQuote?.fundingConversion?.tokenOut??d,m);x.prepareForSigning&&(g=await x.prepareForSigning(g));const y=g.some(w=>w.tokenTransfers?.length),C=await e.execution.execute(g,d,y?m:0n,w=>{w.txHash&&(e.ui.setPaymentResult(b=>({...b,txHash:w.txHash})),e.ui.setTxHash(w.txHash))},void 0,{...i,...x,skipPreSubmitFeeEstimate:!0});e.ui.setPaymentResult(w=>({status:"success",txHash:w?.txHash||C}))}catch(a){_d(e,a)}finally{e.ui.setIsExecuting(!1)}}const Ln=e=>JSON.stringify(e,(t,n)=>typeof n=="bigint"?{raw:n.toString(),type:"spice-quantity"}:n);function ls(e){const t=JSON.parse(e,(n,s)=>s?.type==="spice-quantity"?BigInt(s.raw):s);if(!t||typeof t.amount!="bigint"||!t.context||!Array.isArray(t.calls))throw new Error("The funded action definition cannot be restored. Reconcile its existing result before retrying.");return t}async function cs(e,t){const n=await t(e.amount,e.context);if(Ln(n)!==Ln(e.calls))throw new Error("The destination action or beneficiary changed. Restore the funded action before submitting.")}const Ko=new Set;function Fn(e,t,n){return`spiceflow:pendingDeposit:${e.toLowerCase()}:${t}:${k.normalizeNativeTokenAddress(n).toLowerCase()}`}async function Zo(e,t,n){if(typeof navigator<"u"&&navigator.locks)return navigator.locks.request(e,{ifAvailable:!0},s=>{if(!s)throw new Error("This source is already executing in another view.");return n()});if(t)throw new Error("This browser cannot safely coordinate wallet funding. Use a browser with Web Locks support.");if(Ko.has(e))throw new Error("This source is already executing in another view.");Ko.add(e);try{return await n()}finally{Ko.delete(e)}}async function eu(e){return Zo(Fn(e.embeddedWalletAddress,e.chainId,e.tokenAddress),!1,async()=>{const t=kn(e.embeddedWalletAddress).find(s=>Fn(s.embeddedWalletAddress,s.chainId,s.tokenAddress)===Fn(e.embeddedWalletAddress,e.chainId,e.tokenAddress));if(!t||t.actionFunding?.identity!==e.actionFunding?.identity)throw new Error("The pending action changed in another view.");const n=await yi(t);return t.actionFunding.completedHash=n,_n(t),n})}async function yi(e){const t=e.actionFunding;if(t?.completedHash)return t.completedHash;if(!t?.submitted||!t.intentId||!t.stepCount)throw new Error("The submission result is uncertain. Reconcile the existing action before submitting again.");const[n,s]=t.intentId.split("/");if(!t.recovery)throw new Error("The destination chain and receipt must be reconciled before completing this historical action. Do not submit another payment.");const o=t.recovery,a=await Ia({actionId:n,intentIndex:Number(s||0),intentId:t.intentId,totalSteps:t.stepCount,resume:!0,maxPolls:180,isSpicenetStep:i=>o.spicenetSteps[i],maxExecuteAttemptsForStep:i=>o.spicenetSteps[i]?6:3,beforeStep:async i=>{if(!(!o.spicenetSteps[i]||!o.baseline||!o.deposits.length)&&!await ba({deposits:o.deposits.map(l=>({...l,amount:BigInt(l.amount)})),baseline:o.baseline,fetchEntries:()=>f.getWalletBalanceEntries(e.embeddedWalletAddress)}))throw new Error("The existing source deposit is still waiting for verified Spice credit.")}});if(!a||!/^0x[0-9a-f]{64}$/i.test(a))throw new Error("The destination receipt is not available yet. Continue reconciling this action.");if(!o.destinationChainId)throw new Error("The destination chain must be reconciled before completing this historical action.");return aa(f.getClientForChain(o.destinationChainId),a)}function wi(e,t,n){return e&&t>BigInt(e.rawAmount)?"The new plan exceeds the existing funded amount. Reconcile the funded source before increasing it.":e?.actionFunding?.minimumDestinationAmount&&n!==void 0&&n<BigInt(e.actionFunding.minimumDestinationAmount)?"The new plan reduces the accepted destination amount. Review the updated minimum before continuing.":null}async function tu(e){const t=e.record,n=Fn(t.embeddedWalletAddress,t.chainId,t.tokenAddress);await Zo(n,!0,async()=>{const s=kn(t.embeddedWalletAddress).find(l=>Fn(l.embeddedWalletAddress,l.chainId,l.tokenAddress)===n);if(!s||JSON.stringify(s)!==JSON.stringify(t))throw new Error("The funded operation changed. Review it again before accepting a quote.");const o=s.actionFunding;if(!o?.source||o.source.pending||o.submitted||o.intentId||o.completedHash||!o.actionDefinition||!o.minimumDestinationAmount||BigInt(o.source.confirmedAmount)<BigInt(s.rawAmount)||e.sourceSpendCap!==BigInt(s.rawAmount)||e.minimumDestinationAmount<=0n||e.minimumDestinationAmount>=BigInt(o.minimumDestinationAmount))throw new Error("Only a fully funded, unsubmitted action can accept an updated minimum with the same source amount.");const a=ls(o.actionDefinition),i=ls(e.actionDefinition);for(const l of["userAddress","executorAddress","beneficiary","outputRecipient","chainId","destinationToken","feeToken","feeExecutionMode"])if(a.context[l]!==i.context[l])throw new Error("Restore the original beneficiary and configuration before reviewing this quote.");if(i.amount!==e.minimumDestinationAmount)throw new Error("The updated action does not match the reviewed destination minimum.");if(i.context.grossAmount!==a.context.grossAmount)throw new Error("The updated action changes the funded source amount.");e.assertCurrent(),await cs(a,e.buildActionCalls),await cs(i,e.buildActionCalls),e.assertCurrent(),o.minimumDestinationAmount=e.minimumDestinationAmount.toString(),o.actionDefinition=e.actionDefinition,_n(s)})}async function bi(e){const t=e.asset;if(So(e.embedded),await e.assertCurrent(),!t)return e.run({validateBeforeSubmit:e.assertCurrent});const n=Fn(e.embedded,t.chainId,t.address),s=async()=>{So(e.embedded);let o=kn(e.embedded).find(c=>Fn(c.embeddedWalletAddress,c.chainId,c.tokenAddress)===n);if(o&&(!o.actionFunding||o.actionFunding.identity!==e.identity))throw new Error("This source has a pending funded operation. Restore and reconcile it before starting another action.");const a=wi(o,e.sourceSpendCap,e.minimumDestinationAmount);if(a)throw new Error(a);const i=()=>{o&&_n(o)},l=()=>({chainId:t.chainId,tokenAddress:t.address,tokenSymbol:t.symbol,tokenDecimals:t.decimals,isNative:t.isNative,amount:A.formatUnits(e.sourceSpendCap,t.decimals),rawAmount:e.sourceSpendCap.toString(),embeddedWalletAddress:e.embedded,externalWalletAddress:e.external??e.embedded,timestamp:Date.now(),actionFunding:{identity:e.identity,purpose:e.purpose,selection:e.selection?{...e.selection,asset:{...e.selection.asset,balance:e.selection.asset.balance.toString()}}:void 0,minimumDestinationAmount:e.minimumDestinationAmount?.toString(),actionDefinition:e.actionDefinition}});if(o?.actionFunding?.submitted||o?.actionFunding?.completedHash){const c=await yi(o);return o.actionFunding.completedHash=c,i(),c}if(e.fundExternal){if(!e.external||!e.externalWallet)throw new Error("Connect the source wallet before funding.");e.onFunding?.(),await uc({identity:e.identity,state:o?.actionFunding?.source,recipient:e.embedded,tokenAddr:t.address,isNative:t.isNative||k.isNativeToken(t.address),requiredAmount:e.sourceSpendCap,sourceClient:f.getClientForChain(t.chainId),createWallet:async()=>{const c=e.sourceSpendCap-BigInt(o?.actionFunding?.source?.confirmedAmount??"0"),p=f.getClientForChain(t.chainId),m=t.isNative||k.isNativeToken(t.address),[h,g]=await Promise.all([ca({client:p,account:e.external,recipient:e.embedded,token:t.address,isNative:m,amount:c}),p.getBalance({address:e.external})]);if(g<h+(m?c:0n))throw new Error("The source wallet has insufficient native balance for funding and gas.");return la({wallet:e.externalWallet,account:e.external,chainId:t.chainId})},observer:{onSending:e.assertCurrent},onState:c=>{o??(o=l()),o.actionFunding.source=c,i()}})}if(await e.assertCurrent(),e.fundOnly)return"";const d=await e.run({validateBeforeSubmit:e.assertCurrent,beforeActionSubmit:async()=>{await e.assertCurrent(),o??(o=l()),o?.actionFunding&&(o.actionFunding.submitted=!0,i())},onActionCreated:(c,p,m)=>{o?.actionFunding&&(Object.assign(o.actionFunding,{intentId:c,stepCount:p,recovery:m}),i())}});return o?.actionFunding&&(o.actionFunding.completedHash=d,i()),d};return Zo(n,e.fundExternal,s)}function Ci(e,t,n){return f.addressesEqual(e.address,t)&&e.chainId===n?e._source==="wallet"?0:1:2}function nu(e,t,n,s){const o=Ci(e,n,s)-Ci(t,n,s);return o!==0?o:(t.balanceUsd||0)-(e.balanceUsd||0)}const su=Vr;function vi(e){const t=u.useContext(f.SpiceFlowProviderContext),n=f.useProviderWallets(),s=t?.embeddedWalletAddress||n.embeddedAddress,o=t?.externalWalletAddress||n.externalAddress,a=(t?.mode||"7702")!=="7702",i=Nn({...e,owner:s,enabled:e.enabled&&!!s&&(!a||!!e.includeCrossChainEmbeddedAssets),role:"spend-source",destination:e.destinationToken}),l=Nn({...e,owner:o,enabled:e.enabled&&!!o&&(a||!!e.includeExternalWalletAssets),role:"spend-source",destination:e.destinationToken});return{displayAssets:u.useMemo(()=>[...i.assets,...l.assets].sort((d,c)=>nu(d,c,e.destinationToken.address,e.destinationToken.chainId)),[i.assets,l.assets,e.destinationToken.address,e.destinationToken.chainId]),filteredSpiceAssets:i.rollupAssets,walletAssets:[...i.walletAssets,...l.walletAssets],embeddedWalletAddress:s,externalAddress:o,isNon7702:a,refreshSpiceAssets:i.refresh,refreshWalletAssets:i.refresh,loading:i.loading||l.loading,refreshing:i.refreshing||l.refreshing,error:i.error||l.error}}function ou(e,t){return!e||e._source!=="wallet"?null:co(e,t)}function Yo(e,t){return Sr({aerodrome:!1,oneInch:e?.includeDefaults===!1?{chainIds:[]}:void 0,customVenues:t})}const Xo=Rn(),ru=Yo(void 0,Xo.input);function ki(e){return{venue:"mapped-transfer",amountOut:e,amountOutMinimum:e,calls:[]}}function Si(e){return{venue:"mapped-transfer",amountIn:e,amountInMax:e,amountOut:e,calls:[]}}async function Jo(e){if(f.addressesEqual(e.tokenIn,e.tokenOut))return ki(e.amountIn);if(e.resolveInputSwap){const n=await e.resolveInputSwap({type:"swap",tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:e.amountIn,maxSlippage:e.maxSlippage},e.chainId,e.recipient);if(n)return n}const t=await(e.liquidityVenues?Yo(e.liquidityVenues,Rn(e.liquidityVenues).input):ru).resolveSwap({type:"swap",tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:e.amountIn,maxSlippage:e.maxSlippage},e.chainId,e.recipient);if(!t)throw new Error("No liquidity for this pair.");return t}async function au(e){return f.addressesEqual(e.tokenIn,e.tokenOut)?Si(e.amountOut):Ls({customVenues:e.liquidityVenues?Rn(e.liquidityVenues).output:Xo.output}).getQuote({tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountOut:e.amountOut,maxSlippage:e.maxSlippage},e.chainId,e.recipient)}function Ii(e){const{enabled:t=!0,direction:n,selectedAsset:s,destinationToken:o,chainId:a,recipient:i,paymentAmount:l,maxSlippage:d,refreshIntervalMs:c,resolveInputSwap:p,resolveExactOutputSwap:m}=e,h=u.useContext(f.SpiceFlowProviderContext),g=h?.liquidityVenues,x=JSON.stringify([h?.network,h?.apiUrl,h?.rpcOverrides]),[y,C]=u.useState(!1),[w,b]=u.useState(null),[I,S]=u.useState(null),[v,B]=u.useState(null),[E,j]=u.useState(null),[N,T]=u.useState(null),[P,M]=u.useState(null),[D,L]=u.useState(null),[R,U]=u.useState(null),[X,Y]=u.useState(null),[V,J]=u.useState(null),[ce,G]=u.useState(null),[q,Z]=u.useState(null),[_,H]=u.useState(null),[F,de]=u.useState(0),[re,xe]=u.useState(null),[he,ae]=u.useState(null),be=u.useRef(null),O=u.useRef(null),se=u.useRef(0),W=u.useRef(new Map),$=u.useCallback(()=>{se.current++,W.current.clear(),ae(null),de(Pe=>Pe+1)},[]),oe=c&&c>0?c:null,Ce=g?JSON.stringify(g):"",Me=u.useMemo(()=>g?Rn(g):Xo,[Ce]),ne=u.useMemo(()=>Yo(g,Me.input),[Me]),Ie=u.useMemo(()=>Ls({customVenues:[...m?[{name:"consumer-exact-output",chainIds:[a],preferred:!0,resolve:m}]:[],...Me.output]}),[m,a,Me]);u.useEffect(()=>{W.current.clear()},[Ie]);const ge=u.useMemo(()=>t?ou(s?.asset,a):null,[t,s?.asset,a]),Ye=u.useMemo(()=>{if(!t||!s?.asset)return null;if(ge)return ge.destination.address;const Pe=Wt(s.asset,a);if(Pe)return Pe;const Te=un(s.asset.address,a,s.asset.chainId);return Te?Te.address:null},[t,s?.asset,a,ge]),tt=u.useMemo(()=>t&&s?.asset?Dn(s.asset,a):[],[t,s?.asset,a]),dt=u.useMemo(()=>tt.map(Pe=>Pe.toLowerCase()).join(","),[tt]),Xe=JSON.stringify([t,x,s?.asset.owner,s?.asset.location,s?.asset.receiptTokenId,s?.asset.address,s?.asset.chainId,s?.asset.decimals,s?.amount,a,dt,n,l]);u.useEffect(()=>{let Pe=!1;if(O.current&&(clearTimeout(O.current),O.current=null),!t||!s?.asset||ge||tt.length<=1){Z(null),H(null);return}return O.current=setTimeout(async()=>{const Te=n==="input"?s.amount:l||"0";let Ke=0n;try{Ke=n==="input"?qt(Te,s.asset.decimals):0n}catch{Ke=0n}try{const st=await qr(s.asset,a,{requiredAmount:Ke});Pe||(Z(st),H(Xe))}catch{Pe||Z(null)}},400),()=>{Pe=!0,O.current&&(clearTimeout(O.current),O.current=null)}},[Xe]);const $e=u.useMemo(()=>(_===Xe?q:null)??Ye,[q,_,Xe,Ye]),qe=u.useMemo(()=>!s?.asset||!$e?[]:[$e,...tt.filter(Pe=>Pe.toLowerCase()!==$e.toLowerCase())],[s?.asset,$e,tt]),nt=u.useMemo(()=>!s?.asset||!Gn(s.asset.address,s.asset.chainId,o.address,o.chainId)||!$e?!1:f.addressesEqual($e,o.address),[s,o.address,o.chainId,$e]),Ve=$e?f.addressesEqual($e,o.address):!1,Re=n==="output"&&parseFloat(l||"0")===0,Le=t&&!!s?.asset&&!nt&&!Ve&&!Re,ot=JSON.stringify([t,Ce,n,Le,x,s?.asset.owner,s?.asset.location,s?.asset.receiptTokenId,s?.asset.address,s?.asset.chainId,s?.asset.decimals,n==="input"?s?.amount:l,qe.map(Pe=>Pe.toLowerCase()),a,o.address.toLowerCase(),o.chainId,o.decimals,i?.toLowerCase(),d,oe,ge?.source.address.toLowerCase()??""]),Qe=u.useMemo(()=>({}),[ot,ne,Ie,p,F]),Ge=he?.request===Qe&&(!oe||he.expiresAt>Date.now());return u.useEffect(()=>{if(!oe||he?.request!==Qe)return;const Pe=setTimeout($,Math.max(0,he.expiresAt-Date.now()));return()=>clearTimeout(Pe)},[oe,he,Qe,$]),u.useEffect(()=>{be.current&&clearTimeout(be.current),xe(Qe),ae(null),b(null);const Pe=n==="input"?s?.amount:l,Te=parseFloat(Pe||"0");if(!t||!Number.isFinite(Te)||Te<=0||!s?.asset||!i||qe.length===0){se.current++,S(null),B(null),j(null),T(null),M(null),L(null),U(null),G(null),b(null),C(!1);return}const Ke=s.asset.decimals;let st;try{st=n==="input"?qt(s.amount,Ke):qt(l||"0",o.decimals)}catch(me){se.current++,b(me instanceof Error?me.message:"Invalid amount or token precision"),C(!1);return}const Se=++se.current,De=()=>Se!==se.current;C(!0);const gt=n==="output"?150:400,te=async(me,ye,K,ze={chainId:a,tokenOut:o.address,amountIn:st},Ae=qe)=>{for(const Fe of Ae){const Ee=`${x}:${Ce}:${n}:${ze.chainId}:${Fe.toLowerCase()}:${ze.tokenOut.toLowerCase()}:${ze.amountIn.toString()}:${i.toLowerCase()}:${d??"default"}:${oe??"default"}`,ie=W.current.get(Ee),Q=ie&&ie.expiresAt>Date.now()?me(ie):void 0;if(Q)return{quote:Q,tokenIn:Fe,expiresAt:ie.expiresAt};const we=await K(Fe);if(De())return"stale";if(!we)continue;const He=Date.now()+Math.min(oe??3e4,3e4);return W.current.set(Ee,{expiresAt:He,direction:n,...ye(we)}),{quote:we,tokenIn:Fe,expiresAt:He}}return null},Ue=me=>te(ye=>ye.resolvedSwap,ye=>({resolvedSwap:ye}),async ye=>{const K=!ge&&me.chainId===a&&s.asset._source!=="wallet",ze=K?await xn(s.asset,ye,me.chainId,o):Ke;if(De())return null;const Ae=K?Ms(me.amountIn,Ke,ze):me.amountIn;if(f.addressesEqual(ye,me.tokenOut))return ki(Ae);const Fe={type:"swap",tokenIn:ye,tokenOut:me.tokenOut,amountIn:Ae,maxSlippage:d};if(p){const Ee=await p(Fe,me.chainId,i);if(Ee)return Ee}return ne.resolveSwap(Fe,me.chainId,i)},me,me.candidates);return be.current=setTimeout(async()=>{try{if(n==="input"){let me=null,ye=st;if(ge){if(me=await Ue({chainId:ge.source.chainId,tokenOut:ge.source.address,amountIn:st,candidates:[s.asset.address]}),me==="stale"||De())return;if(!me)throw new Error("No liquidity for this pair");ye=Pt(me.quote.amountOutMinimum,ge.source.decimals,ge.destination.decimals,"floor")}const K=Le||!ge?await Ue({chainId:a,tokenOut:o.address,amountIn:ye,candidates:qe}):null;if(K==="stale"||De())return;if(Le&&!K)throw new Error("No liquidity for this pair");const ze=K?K.quote.amountOut:ye,Ae=Math.min(K?.expiresAt??1/0,me?.expiresAt??1/0),Fe=ge?.destination.decimals??await xn(s.asset,K.tokenIn,a,o),Ee=!ge&&s.asset._source!=="wallet"?Ms(ye,Ke,Fe):ye;if(De())return;G(K?.tokenIn??ge?.destination.address??null),ae({request:Qe,key:`${A.keccak256(A.toHex(ot))}:${Se}`,expiresAt:Ae}),U(ze),Y(Ee),J(Fe),j(Le?K?.quote??null:null),T(me?.quote??null),M(null),L(null);const ie=parseFloat(A.formatUnits(ze,o.decimals));S(ie<.01?ie.toPrecision(4):ie.toLocaleString(void 0,{maximumFractionDigits:6})),B(null),b(null)}else{const me=Ee=>te(ie=>ie.exactOutputSwap,ie=>({exactOutputSwap:ie}),async ie=>{try{return f.addressesEqual(ie,Ee.tokenOut)?Si(Ee.amountOut):await Ie.getQuote({tokenIn:ie,tokenOut:Ee.tokenOut,amountOut:Ee.amountOut,maxSlippage:d},Ee.chainId,i)}catch{return null}},{chainId:Ee.chainId,tokenOut:Ee.tokenOut,amountIn:Ee.amountOut},Ee.candidates),ye=!ge||Le,K=ye?await me({chainId:a,tokenOut:o.address,amountOut:st,candidates:qe}):null;if(K==="stale"||De())return;if(ye&&!K)throw new Error("No liquidity for this pair");let ze=null;if(ge){const Ee=K?K.quote.amountInMax:st;if(ze=await me({chainId:ge.source.chainId,tokenOut:ge.source.address,amountOut:Pt(Ee,ge.destination.decimals,ge.source.decimals,"ceil"),candidates:[s.asset.address]}),ze==="stale"||De())return;if(!ze)throw new Error("No liquidity for this pair")}const Ae=ze?Ke:await xn(s.asset,K.tokenIn,a,o);if(De())return;G(K?.tokenIn??ge?.destination.address??null),ae({request:Qe,key:`${A.keccak256(A.toHex(ot))}:${Se}`,expiresAt:Math.min(K?.expiresAt??1/0,ze?.expiresAt??1/0)}),L(K?.quote??null),M(ze?.quote??null),j(null),T(null),U(null);const Fe=ze?.quote.amountIn??K.quote.amountIn;B(A.formatUnits(Fe,Ae)),S(null),b(null)}}catch(me){if(De())return;const ye=me instanceof Error?me.message:"Failed to get quote";b(ye),S(null),B(null),j(null),T(null),M(null),L(null),U(null),G(null)}finally{De()||C(!1)}},Le||ge?gt:0),()=>{se.current++,be.current&&clearTimeout(be.current)}},[Qe]),{inputAmount:Ge&&n==="input"?X:null,inputDecimals:Ge&&n==="input"?V:null,quoteKey:Ge?he.key:null,quoteExpiresAt:Ge?he.expiresAt:null,refreshQuote:$,isQuoting:re===Qe?y:Le||!!ge,quoteError:re===Qe?w:null,estimatedOutput:Ge?I:null,estimatedInput:Ge?v:null,resolvedSwap:Ge?E:null,exactOutputSwap:Ge?D:null,quoteAmountOut:Ge?R:null,resolvedTokenIn:Le&&Ge?ce??$e:$e,isDirect:Ve,needsSwap:Le,selectedIsEquivalent:nt,sourceSwap:Ge?N:null,sourceExactOutputSwap:Ge?P:null,pivot:ge}}function ds(e){const{enabled:t,destinationToken:n,selectedAsset:s,paymentAmount:o="0",sourceChains:a,supportedSourceAssets:i,buildActionCalls:l,feeExecutionMode:d="user-transfer",buildSpicenetBatch:c,onPayExecute:p,resolveExactOutputSwap:m,amountDirection:h="input",onSuccess:g,onError:x}=e,y=h==="output",C=h==="input-inclusive",w=y?"output":"input",b=n.chainId,I=u.useContext(f.SpiceFlowProviderContext),S=I?.mode||"7702",v=!1,B=p?"Move onPayExecute protocol calls to buildActionCalls and application updates to onSuccess before continuing.":e.actionExecution?.wallet==="external"?"This action requires the external wallet as its caller. Configure a beneficiary-capable embedded action before upgrading this integration.":null,E=!!I?.isWhitelistGateActive,j=!!I?.isWhitelistConfigured&&I?.isUserWhitelisted!==!0,N=u.useMemo(()=>a??I?.supportedChainIds??[],[a,I?.supportedChainIds]),T=i,{address:P,isConnected:M,isReady:D,isAuthenticated:L,provider:R}=f.useWallet(),{execute:U,estimate:X}=Rs(),{externalWallet:Y,embeddedAddress:V,activeWallet:J,activeAddress:ce}=f.useProviderWallets(),G=I?.externalWalletAddress,q=I?.embeddedWalletAddress||V,Z=e.sourceFundingRecoveryKey??e.actionExecution?.recoveryKey??`${n.chainId}:${n.address.toLowerCase()}:${h}`,_=za(q,Z),H=_.selection?Ln(_.selection):"",F=u.useMemo(()=>_.selection,[H])??s,de=Hr(F?.asset,S!=="7702"),{displayAssets:re,filteredSpiceAssets:xe,walletAssets:he,embeddedWalletAddress:ae,refreshSpiceAssets:be,refreshWalletAssets:O,loading:se,refreshing:W,error:$}=vi({address:P,destinationToken:n,supportedSourceAssets:T,sourceChains:N,additionalSourceTokens:[...e.additionalSourceTokens??[],...F?.asset._source==="wallet"?[{address:F.asset.address,chainId:F.asset.chainId,decimals:F.asset.decimals,symbol:F.asset.symbol,name:F.asset.name,logoURI:F.asset.logoURI}]:[]],includeExternalWalletAssets:e.includeExternalWalletAssets,includeCrossChainEmbeddedAssets:e.includeCrossChainEmbeddedAssets,enabled:t&&(S!=="7702"?!!G:!!q)}),oe=re,Ce=F?[...he,...xe].find(le=>ct(le)===ct(F.asset)):void 0,Me=u.useMemo(()=>F&&Ce?{...F,asset:Ce}:F,[F,Ce]),ne=F?vn(Ce??F.asset,"spend-source",{allowedTokens:I?.allowedTokens,rpcOverrides:I?.rpcOverrides,liquidityVenues:I?.liquidityVenues,isWhitelistGateActive:E},n,T):null,Ie=_.record?F?.asset.balance??0n:Ce?Ce.balance<(F?.asset.balance??0n)?Ce.balance:F.asset.balance:0n,[ge,Ye]=u.useState(!1),[tt,dt]=u.useState(!1),[Xe,$e]=u.useState(null),qe=u.useRef(x);qe.current=x;const nt=u.useCallback(le=>{$e(le),typeof le=="string"&&le&&qe.current?.(new Error(le),f.getRelayerErrorDetail(le))},[]),[Ve,Re]=u.useState("idle"),[Le,ot]=u.useState(""),[Qe,Ge]=u.useState(null),[Pe,Te]=u.useState(!1),[Ke,st]=u.useState(null),[Se,De]=u.useState(null),[gt,te]=u.useState(!1),[Ue,me]=u.useState(!1),[ye,K]=u.useState(null),ze=u.useRef(F),Ae=u.useRef(!1),Fe=u.useRef(null),Ee=u.useRef(null),ie=u.useRef(null),Q=u.useRef(null),we=u.useRef(null),He=u.useRef(null),Et=u.useRef(g),Ft=u.useRef(null),[ve,wt]=u.useState(null),[ut,St]=u.useState(null),[Kt,on]=u.useState(!1),[pn,Zt]=u.useState(0);u.useEffect(()=>{ze.current=F},[F]);const at=ae||V||P,rt=Ii({enabled:t&&!j,direction:w,selectedAsset:F,destinationToken:n,chainId:b,recipient:at,paymentAmount:o,resolveExactOutputSwap:m,resolveInputSwap:e.resolveInputSwap,maxSlippage:e.maxSlippage,refreshIntervalMs:3e4}),bt=rt,Oe=rt,{isQuoting:Ht,resolvedSwap:Rt,exactOutputSwap:Mt,quoteAmountOut:mt,resolvedTokenIn:We,isDirect:Dt,needsSwap:jt,selectedIsEquivalent:Vt,sourceSwap:It,sourceExactOutputSwap:ke,pivot:je}=bt,Ct=y?parseFloat(o||"0"):parseFloat(F?.amount||"")||0,pt=F?.asset?._source==="wallet",xt=!!F?.asset&&pt&&F.asset.chainId!==b,fn=F?Number(A.formatUnits(Ie,F.asset.decimals)):0,qn=u.useMemo(()=>{if(!F||y)return!1;try{return qt(F.amount||"0",F.asset.decimals)>Ie}catch{return!0}},[F,y,Ie]);u.useEffect(()=>{t||(nt(null),Ye(!1),Re("idle"),ot(""),Ge(null),Te(!1),st(null),De(null),te(!1),me(!1),K(null),Ae.current=!1,Fe.current&&(Fe.current.abort(),Fe.current=null))},[t]);const Tn=u.useCallback(le=>{Re({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[le.step]||"executing"),ot(le.message),le.txHash&&Ge(le.txHash)},[]),ee=u.useMemo(()=>({currentPaymentAmount:o,isFeeInclusiveInput:C,feeOnlyAction:e.feeOnlyAction,swapInputAmount:bt.inputAmount,destinationToken:n,embeddedWalletAddress:ae,providerEmbeddedAddress:V,externalWalletAddress:G,address:P,recipient:e.recipient??(S!=="7702"?G:void 0),isNon7702:v,isPayMode:y,resolvedChainId:b,buildActionCalls:l,feeExecutionMode:d,buildSpicenetBatch:c,selectedAsset:F,needsSwap:jt,resolvedSwap:Rt,exactOutputSwap:Mt,quoteAmountOut:mt,resolvedTokenIn:We,sourceSwap:It,sourceExactOutputSwap:ke,pivot:je,resolveSourceExactOutputSwap:async le=>{if(!je||!at)throw new Error("Swap route is not ready.");const kt=await au({chainId:je.source.chainId,recipient:at,tokenIn:F.asset.address,tokenOut:je.source.address,amountOut:le,liquidityVenues:I?.liquidityVenues,maxSlippage:e.maxSlippage}).catch(()=>null);if(!kt)throw new Error("No liquidity for this pair.");return kt},resolveInputSwap:async le=>{if(!We||!at)throw new Error("Swap route is not ready.");return Jo({chainId:b,recipient:at,tokenIn:We,tokenOut:n.address,amountIn:le,liquidityVenues:I?.liquidityVenues,maxSlippage:e.maxSlippage,resolveInputSwap:e.resolveInputSwap})}}),[o,n,ae,V,G,P,e.recipient,e.feeOnlyAction,e.maxSlippage,e.resolveInputSwap,bt.inputAmount,C,S,v,y,b,l,d,c,F,jt,Rt,Mt,mt,We,It,ke,je,at,I?.liquidityVenues]),ue=u.useCallback(le=>Vo({...ee,requestTimestampMs:Ee.current??Date.now()},le),[ee]),Be=ee,_e=u.useCallback(le=>Ws({...Be,requestTimestampMs:Ee.current??Date.now()},le),[Be]),it=u.useMemo(()=>F?.asset?je?je.destination.address:jt&&We?We:F.asset.chainId===b?F.asset.address:We??Wt(F.asset,b)??n.address:n.address,[F,n.address,jt,b,We,je]),et=A.keccak256(A.stringToHex(JSON.stringify([F&&ct(F.asset),F?.amount,o,h,n.address,n.chainId,n.decimals,e.recipient,Z,S,G,ae,I?.apiUrl,I?.rpcOverrides,e.maxSlippage,d,e.feeOnlyAction,I?.liquidityVenues,I?.allowedTokens,E,T,N]))),vt=_.record?.actionFunding?.identity&&_.record.actionFunding.identity!==et?"Restore the original wallet mode, beneficiary and configuration to continue this funded action.":null,ht=u.useRef({key:et,buildActionCalls:l,enabled:t,sourceBalance:Ie});ht.current={key:et,buildActionCalls:l,enabled:t,sourceBalance:Ie};const At=u.useRef(null),yt=u.useRef(!1),Ut=u.useCallback(()=>(Ee.current=Date.now(),He.current?He.current():yt.current?(yt.current=!1,Et.current=we.current.onSuccess,At.current={key:ht.current.key,quote:we.current.feeQuote},gi(we.current)):Promise.resolve()),[]),Nt=u.useMemo(()=>F?.asset?f.addressesEqual(F.asset.address,n.address)&&F.asset.chainId===n.chainId:!1,[F,n.address,n.chainId]),Yt=!1,mn=null,Cn=j,rn=(C||!!je)&&!!Se&&Se.netAmount===0n,Xt=u.useMemo(()=>(!!F?.asset||!!e.actionProceeds)&&(Ct>0||!!e.feeOnlyAction),[F,Ct,e.actionProceeds,e.feeOnlyAction]),Qt=u.useMemo(()=>!t||!Xt||Yt||!F?.asset&&!e.actionProceeds?null:[et,y?"pay":"supply",h,F?ct(F.asset):"proceeds",JSON.stringify(I?.rpcOverrides),I?.apiUrl,e.recipient,F?.asset.address.toLowerCase(),F?.asset.chainId,F?.amount,o,n.address.toLowerCase(),n.chainId,b,Oe.resolvedTokenIn?.toLowerCase()??"",Oe.quoteKey,Oe.needsSwap?"swap":"direct",Oe.isDirect?"direct-token":"routed-token","7702",Nt?"source-dest":"cross-chain",Oe.isQuoting?"quoting":"quoted",Oe.exactOutputSwap?.amountIn?.toString()??"",Oe.exactOutputSwap?.amountInMax?.toString()??"",Oe.exactOutputSwap?.venue??"",Oe.resolvedSwap?.amountOut?.toString()??"",Oe.quoteAmountOut?.toString()??"",Oe.sourceSwap?.amountOutMinimum?.toString()??"",Oe.sourceExactOutputSwap?.amountInMax?.toString()??"",Oe.pivot?.source.address.toLowerCase()??"",ae??"",V??"",P??""].join("|"),[t,et,e.actionProceeds,e.feeOnlyAction,ge,Ve,Xt,Yt,F,y,h,o,n,b,Oe,v,Nt,ae,V,P]),z=u.useCallback(async(le,kt)=>await is({signal:le,feeOnlyAction:e.feeOnlyAction,actionProceeds:e.actionProceeds,liquidityVenues:I?.liquidityVenues,maxSlippage:e.maxSlippage,resolveExactOutputSwap:m,selectedAsset:F,isPayMode:y,isFeeInclusiveInput:C,parsedAmount:Ct,needsSwap:Oe.needsSwap,exactOutputSwap:Oe.exactOutputSwap,isNon7702:v,isSourceDestToken:Nt,currentPaymentAmount:o,destinationToken:n,feeExecutionMode:d,resolvedTokenIn:Oe.resolvedTokenIn,embeddedWalletAddress:ae,providerEmbeddedAddress:V,resolvedChainId:b,isConnected:M,address:P,ready:D,authenticated:L,isDirect:Oe.isDirect,resolvedSwap:Oe.resolvedSwap,sourceSwap:Oe.sourceSwap,sourceExactOutputSwap:Oe.sourceExactOutputSwap,pivot:Oe.pivot,isQuoting:Oe.isQuoting,executionTokenAddress:it,buildPayChainBatches:ue,buildSupplyChainBatches:_e,estimate:X,...kt}),[F,e.feeOnlyAction,e.actionProceeds,e.maxSlippage,m,I?.liquidityVenues,y,C,Ct,Oe,v,Nt,o,n,d,ae,V,ue,X,b,M,P,D,L,_e,it]);u.useEffect(()=>{ie.current=z},[z]);const pe=u.useCallback(async le=>{if(y)return null;if(!F||ct(le)!==ct(F.asset)||!at||!We)throw new Error("Select a source before calculating Max.");let kt=le.balance;if(de&&(le.isNative||k.isNativeToken(le.address))){if(!G)throw new Error("Connect the source wallet before calculating Max.");const Bt=await ca({client:f.getClientForChain(le.chainId),account:G,recipient:at,token:le.address,isNative:!0,amount:1n});kt-=Bt}return hi({balance:kt,decimals:le.decimals,planForAmount:async Bt=>{const ft={...ee,selectedAsset:{asset:le,amount:A.formatUnits(Bt,le.decimals)}};let Tt=Bt;return je?(ft.sourceSwap=await Jo({chainId:le.chainId,recipient:at,tokenIn:le.address,tokenOut:je.source.address,amountIn:Bt,maxSlippage:e.maxSlippage,liquidityVenues:I?.liquidityVenues,resolveInputSwap:e.resolveInputSwap}),Tt=Pt(ft.sourceSwap.amountOutMinimum,je.source.decimals,je.destination.decimals,"floor")):Tt=Ms(Bt,le.decimals,await xn(le,We,b,n)),ft.resolvedSwap=jt?await ft.resolveInputSwap(Tt):null,ft.swapInputAmount=Tt,ft.quoteAmountOut=ft.resolvedSwap?.amountOut??Tt,z(void 0,{selectedAsset:ft.selectedAsset,parsedAmount:Number(ft.selectedAsset.amount),sourceSwap:ft.sourceSwap,resolvedSwap:ft.resolvedSwap,isQuoting:!1,buildSupplyChainBatches:$t=>Ws(ft,$t)})}})},[F,ee,y,at,We,b,n,de,G,je,jt,z,e.maxSlippage,e.resolveInputSwap,I?.liquidityVenues]);Ao({shouldRun:t&&!ge&&Ve==="idle"&&Xt&&!Yt&&!Oe.isQuoting&&!!Qt,deps:[t,ge,Ve,Xt,Yt,mn,Oe.isQuoting,Qt],onSkip:()=>{if(!t){te(!1),me(!1),K(null),De(null);return}if(ge||Ve!=="idle"){te(!1);return}if(!Xt){De(null),te(!1),me(!1),K(null);return}Oe.isQuoting&&(te(!1),me(!1))},onCleanup:()=>te(!1),delayMs:500,backgroundIntervalMs:5e3,run:async({isBackground:le,isCurrent:kt,signal:Bt})=>{const ft=Qt;le||(K(null),te(!0));try{const Tt=await ie.current?.(Bt);if(!kt())return;Tt&&ft?(Tt.expiresAt=Math.min(Date.now()+3e4,Oe.quoteExpiresAt??1/0),Q.current={key:ft,quote:Tt},De(Tt.preview),me(!0)):(Q.current=null,De(null),me(!1)),K(null)}catch(Tt){if(!kt())return;if(le&&Q.current?.key===ft){console.warn("[SpiceSupply] fee refresh failed:",Tt);return}const $t=f.sanitizeError(Tt,"Unable to calculate fees for this action.");Q.current=null,De(null),me(!1),K($t)}finally{kt()&&te(!1)}}});const Ne=u.useCallback(()=>(Ee.current=Date.now(),He.current?He.current():yt.current?(yt.current=!1,Et.current=we.current.onSuccess,At.current={key:ht.current.key,quote:we.current.feeQuote},xi(we.current)):Promise.resolve()),[]),fe=y&&Ke?.status==="success"?Ke.txHash:Ve==="success"?Qe:null;u.useEffect(()=>{!fe||Ft.current===fe||(Ft.current=fe,on(!0),St(null),Promise.resolve().then(()=>Et.current?.(fe)).then(()=>{for(const le of kn(q??""))le.actionFunding?.identity===et&&le.actionFunding.completedHash===fe&&Is(le.embeddedWalletAddress,le.chainId,le.tokenAddress);wt(fe),be()}).catch(le=>{St(`Transaction confirmed; application update needs retry: ${f.sanitizeError(le,"Unable to finalize the action")}`)}).finally(()=>on(!1)))},[fe,pn]);const Ze=!!fe&&ve!==fe,lt=Ze&&!ut,an=u.useCallback(()=>{Ft.current=null,Zt(le=>le+1)},[]),fs=u.useCallback(()=>{Te(!1),st(null),Ae.current=!1,be(),O()},[be,O]),Je=Qt&&Q.current?.key===Qt?Q.current.quote:null,hn=Je?.sourceSpendCap,gn=Je?.destinationAmount,tr=hn!==void 0&&!_.record?.actionFunding?.submitted?wi(_.record,hn,gn):null,ms=()=>{if(B)throw new Error(B);if(!ht.current.enabled||ht.current.key!==et)throw new Error("The source, amount, beneficiary or configuration changed. Review the form before continuing.");if(F&&(!Je||(Je.expiresAt??0)<=Date.now()))throw new Error("The quote expired. Review the refreshed quote before submitting.");if(_.error||vt)throw new Error(_.error??vt);if(F&&(Je?.sourceSpendCap??0n)>ht.current.sourceBalance)throw new Error("The source balance changed. Review the available amount before continuing.");if(F&&!ne?.eligible)throw new Error(ne?.reason??"This source is unavailable.")},Hs=async()=>{ms();const le=_.record?.actionFunding?.actionDefinition;le&&await cs(ls(le),ht.current.buildActionCalls),Je?.actionDefinition&&await cs(Je.actionDefinition,ht.current.buildActionCalls),ms()},nr=le=>({...le,sourceSpendCap:Je?.sourceSpendCap,minimumDestinationAmount:Je?.destinationAmount}),hs=F&&Je?.sourceSpendCap!==void 0?Je.sourceSpendCap>Ie:qn,sr={...ee,resolvedSwap:Je?.destinationSwap??ee.resolvedSwap,swapInputAmount:Je?.swapInputAmount??ee.swapInputAmount};we.current={selectedAsset:F,parsedAmount:Ct,currentPaymentAmount:o,isInsufficientBalance:hs,isPayMode:y,isFeeInclusiveInput:C,feeOnlyAction:e.feeOnlyAction,actionProceeds:e.actionProceeds,validateFeeQuote:ms,isNon7702:v,isSourceDestToken:Nt,needsSwap:jt,exactOutputSwap:Mt,selectedIsEquivalent:Vt,resolvedTokenIn:We,sourceSwap:It,sourceExactOutputSwap:ke,pivot:je,embeddedWalletAddress:ae,providerEmbeddedAddress:V,externalWallet:Y,externalWalletAddress:G,activeSignerWallet:J,activeSignerAddress:ce,address:P,isConnected:M,ready:D,authenticated:L,provider:R,resolvedChainId:b,executionTokenAddress:it,destinationToken:n,buildActionCalls:l,feeExecutionMode:d,buildSpicenetBatch:c,onPayExecute:p,onSuccess:g,feeQuote:Je,execution:{estimate:(le,kt,Bt,ft)=>X(le,kt,Bt,{...ft,userOverride:at}),execute:(le,kt,Bt,ft,Tt,$t)=>bi({asset:F?.asset??{...n,name:n.symbol,balance:0n,balanceFormatted:0,balanceUsd:0,isNative:!1,_source:"spice",owner:at,location:"rollup"},embedded:at,external:G,externalWallet:Y,fundExternal:de,sourceSpendCap:Je?.sourceSpendCap??0n,identity:et,purpose:Z,selection:F,minimumDestinationAmount:Je?.destinationAmount,actionDefinition:Je?.actionDefinition?Ln(Je.actionDefinition):void 0,assertCurrent:Hs,onFunding:()=>ot("Transfer the selected source to your embedded wallet"),run:Xi=>U(le,kt,Bt,ft,Tt,{...$t,...Xi,userOverride:at,requireDestinationReceipt:!0,validateBeforeSubmit:async Ji=>{await Hs(),await $t?.validateBeforeSubmit?.(Ji)}})}),buildPayChainBatches:le=>Vo(sr,nr(le)),buildSupplyChainBatches:le=>Ws(sr,nr(le)),onProgress:Tn},ui:{setError:nt,setStep:Re,setStatusMsg:ot,setTxHash:Ge,setIsExecuting:Ye,setShowStatusPanel:Te,setPaymentResult:st},refs:{spiceDepositSubmittedRef:Ae,abortControllerRef:Fe}};const Bn=!!e.isZeroAmountPay&&!e.feeOnlyAction&&y&&Ct===0,Hi=y?(Bn||!!F?.asset||!!e.actionProceeds)&&Ct>=0&&!hs&&!ge&&(Bn||Yt||Ue)&&!ye&&(Bn||e.feeOnlyAction||!jt||!!Mt)&&(Bn||e.feeOnlyAction||!je||!!ke)&&!Cn:!!F?.asset&&Ct>0&&!hs&&!ge&&Ue&&!ye&&!rn&&(je?!!It&&!Ht&&(Dt||!!Rt):xt||Dt||!!Rt&&!Ht)&&!Cn,or=!!_.record?.actionFunding?.submitted&&!ge&&!vt&&t;He.current=or?async()=>{const le=_.record;if(!(yt.current===!1||ge)){yt.current=!1,Et.current=g,Ye(!0),nt(null),ot("Checking the existing funded transaction...");try{const kt=async()=>{for(let ft=0;ft<3;ft++){const Tt=ht.current.buildActionCalls;le.actionFunding?.actionDefinition&&await cs(ls(le.actionFunding.actionDefinition),Tt);const $t=ht.current;if(!$t.enabled||$t.key!==et)throw new Error("Restore the original wallet mode, beneficiary and configuration to continue this funded action.");if($t.buildActionCalls===Tt)return}throw new Error("The action changed while checking recovery. Restore its original details and retry.")};await kt();const Bt=await eu(le);le.actionFunding.completedHash=Bt,_n(le),await kt(),Ge(Bt),y?st({status:"success",txHash:Bt}):Re("success")}catch(kt){nt(f.sanitizeError(kt,"Unable to reconcile this action"))}finally{Ye(!1)}}}:null;const rr=!B&&!tt&&!!at&&(S==="7702"||!!G)&&!Kt&&!ut&&(or||t&&!_.error&&!vt&&!tr&&Hi&&(Bn||!F&&!!e.actionProceeds||!!ne?.eligible)&&Ve!=="success"&&Ke?.status!=="success"&&!bt.quoteError&&(Bn||!!Qt&&Q.current?.key===Qt&&(Q.current.quote.expiresAt??0)>Date.now()));yt.current=rr;const Vi=u.useCallback(()=>{yt.current=!1,Q.current=null,me(!1),rt.refreshQuote(),Re("idle"),nt(null)},[rt.refreshQuote,nt]),Qi=u.useCallback(()=>{Te(!1)},[]),Gi=u.useCallback(()=>{Re("idle"),Ge(null),be()},[be]),Ot=Je??(Q.current?.key.startsWith(`${et}|`)?Q.current.quote:null)??(At.current?.key===et?At.current.quote:null),Ki=async le=>{if(de){if(!Je||le!==Je.sourceSpendCap)throw new Error("Use the displayed source funding maximum before preparing this action.");await bi({asset:F?.asset,embedded:at,external:G,externalWallet:Y,fundExternal:!0,sourceSpendCap:le,identity:et,purpose:Z,selection:F,minimumDestinationAmount:Je.destinationAmount,actionDefinition:Je.actionDefinition?Ln(Je.actionDefinition):void 0,assertCurrent:Hs,fundOnly:!0,run:async()=>{throw new Error("Funding preparation cannot submit an action")}})}},Zi=u.useMemo(()=>_.record?{matchesPurpose:!0,matchesSelection:!0,phase:_.record.actionFunding?.completedHash?"complete":_.record.actionFunding?.submitted?"routing":"funding",amount:_.record.amount}:null,[_.record]),Jt=_.record?.actionFunding,Yi=!y&&!e.feeOnlyAction&&!e.actionProceeds&&!ge&&!Kt&&!_.error&&!vt&&Jt?.source&&!Jt.source.pending&&!Jt.submitted&&!Jt.intentId&&!Jt.completedHash&&Jt.actionDefinition&&Jt.minimumDestinationAmount&&Je?.actionDefinition&&(Je.expiresAt??0)>Date.now()&&hn!==void 0&&gn!==void 0&&hn===BigInt(_.record.rawAmount)&&BigInt(Jt.source.confirmedAmount)>=hn&&gn>0n&&gn<BigInt(Jt.minimumDestinationAmount)?{previousMinimum:BigInt(Jt.minimumDestinationAmount),minimum:gn,accepting:tt,accept:async()=>{if(!tt){dt(!0);try{await tu({record:_.record,sourceSpendCap:hn,minimumDestinationAmount:gn,actionDefinition:Ln(Je.actionDefinition),buildActionCalls:ht.current.buildActionCalls,assertCurrent:()=>{if(ms(),Q.current?.quote!==Je)throw new Error("The quote changed. Review its current minimum before accepting.")}}),nt(null),Re("idle")}catch(le){nt(f.sanitizeError(le,"Unable to accept this updated quote"))}finally{dt(!1)}}}}:null;return{selectedAsset:Me,fundingQuoteReview:Yi,capability:ne,assets:{selectable:oe,displayAssets:oe,filteredSpiceAssets:xe,embeddedWalletAddress:ae,externalAddress:G,isNon7702:S!=="7702",refreshSpiceAssets:be,refreshWalletAssets:O,loading:se,refreshing:W,error:$},quote:{...bt,hasSourceConversion:!!je,executionInput:je&&Ot?{address:je.destination.address,chainId:je.destination.chainId,decimals:je.destination.decimals,amount:Ot.preview.netAmount}:null,...Ot?.destinationSwap?{resolvedSwap:Ot.destinationSwap,inputAmount:Ot.swapInputAmount,estimatedOutput:A.formatUnits(Ot.destinationSwap.amountOut,n.decimals)}:{}},fees:{fundingConversion:Ot?.fundingConversion,proceedsUsed:Ot?.proceedsUsed,fundingShortfall:Ot?.grossFundingAmount,source:je&&Ot?{address:je.source.address,chainId:je.source.chainId,symbol:je.source.symbol,decimals:je.source.decimals,gasFee:Ot.sourceGasSkim??0n,spicenetFee:0n}:null,destinationAmount:Ot?.destinationAmount,sourceSpendCap:Ot?.sourceSpendCap,preview:Ot?.preview??Se,isLoading:gt,ready:!!Je&&(Je.expiresAt??0)>Date.now(),error:ye},amount:{sourceRequiredAmount:Ot?.sourceSpendCap??null,parsed:Ct,isInsufficientBalance:hs,sourceBalance:fn,feesExceedAmount:rn},status:{sourceFunding:Zi,finalizing:Kt||lt,finalizationError:ut,externalAction:null,step:Ze&&Ve==="success"?"executing":Ve,statusMsg:Ze?ut??"Transaction confirmed. Updating application...":Le,txHash:Qe,isExecuting:ge||lt,error:B||ut||Xe||_.error||vt||tr||ne?.reason||null,showStatusPanel:Pe,paymentResult:Ze&&Ke?.status==="success"?{...Ke,status:"processing"}:Ke},flags:{directExecutionFeeNote:Yt},retryFinalization:an,fundEmbeddedSource:Ki,canExecute:rr,submitSupply:Ut,submitPay:Ne,retrySupply:Vi,dismissPaymentStatus:Qi,resolveMaxAmount:pe,resetAfterSuccess:Gi,resetPaymentState:fs}}function iu(e){return`0x77${e.slice(4)}`}function Ai({userAddress:e,destinationChainId:t,deliveryToken:n,deliveryAmount:s,withdrawalAmount:o,deliveryRecipient:a,deliveryTransfers:i,requestTimestampMs:l}){const d=i?.length?i:[{token:n,recipient:a,amount:o??s}],c=d.reduce((g,x)=>g+x.amount,0n);if(c<=0n)return null;const p=l??Date.now(),m=BigInt(Math.floor(p/1e3)),h=iu(A.keccak256(A.encodeAbiParameters([{type:"address"},{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[e??a,n,a,c,BigInt(t),BigInt(p)])));return{chainId:k.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:[{to:k.ZERO_ADDRESS,value:0n,data:A.encodeFunctionData({abi:k.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${t}`,idempotenceKey:h,nbf:0n,exp:m+3600n,metadata:"{}",transfers:d.map(g=>({token:A.getAddress(g.token).toLowerCase(),to:A.getAddress(g.recipient).toLowerCase(),amount:g.amount}))}]})}]}}const us=ct;function Ei(e){const{asset:t,amount:n,recipient:s,owner:o,onSuccess:a}=e,i=t?.chainId??e.sourceChains?.[0]??0,l=u.useMemo(()=>k.getTokensForChain(i).find(w=>w.equivalenceGroup==="USDC"),[i]),[d,c]=u.useState(null),p=u.useRef(!1),m=u.useCallback((w,b)=>{if(!t||n<=0n||n>t.balance&&!p.current||!s||!o||f.addressesEqual(o,s))throw new Error("Enter a valid withdrawal amount and recipient.");if(b.chainId!==t.chainId||!f.addressesEqual(b.executorAddress??b.userAddress,o))throw new Error("The withdrawal wallet or network changed. Review the withdrawal again.");return ei(t.chainId,t.address,[{recipient:s,amount:n}]).calls},[t?.address,t?.chainId,t?.balance,n,s,o]),h=u.useMemo(()=>d?{asset:d,amount:"0"}:null,[d]),g=ds({enabled:e.enabled&&!!l&&!!t&&n>0n&&!!s&&!!o&&!f.addressesEqual(o,s),feeOnlyAction:!0,isZeroAmountPay:!0,amountDirection:"output",paymentAmount:"0",destinationToken:{address:l?.address??k.ZERO_ADDRESS,symbol:l?.symbol??"USDC",decimals:l?.decimals??6,chainId:i},recipient:o,selectedAsset:h,sourceChains:e.sourceChains,includeCrossChainEmbeddedAssets:!0,includeExternalWalletAssets:!1,feeExecutionMode:"backend-transfer",buildActionCalls:m,buildSpicenetBatch:Ai,onError:(w,b)=>e.onError?.(w.message,b),sourceFundingRecoveryKey:`withdraw:${t?.chainId}:${t?.address.toLowerCase()}`,onSuccess:async()=>{t&&(window.dispatchEvent(new CustomEvent("withdraw-completed")),await a?.({token:t.symbol,amount:A.formatUnits(n,t.decimals),chainId:i}))}});p.current=g.status.sourceFunding?.phase==="routing"||g.status.sourceFunding?.phase==="complete";const x=`${e.enabled}:${t?.chainId}:${t?.address}:${n}:${s}`,y=u.useRef(x);u.useEffect(()=>{y.current===x||g.status.isExecuting||(y.current=x,(g.status.step==="success"||g.status.paymentResult?.status==="success")&&g.resetAfterSuccess())},[x,g.status.isExecuting,g.status.step,g.status.paymentResult?.status,g.resetAfterSuccess]);const C=u.useMemo(()=>l?g.assets.displayAssets.flatMap(w=>{if(w.location==="external")return[];const b=t&&w._source==="wallet"&&w.chainId===t.chainId&&f.addressesEqual(w.address,t.address)?n:0n,I=w.balance-b;return I>0n?[{...w,balance:I,balanceFormatted:Number(A.formatUnits(I,w.decimals))}]:[]}).sort((w,b)=>{const I=S=>S._source==="wallet"&&S.chainId===i?0:S._source==="spice"?1:2;return I(w)-I(b)||b.balanceFormatted-w.balanceFormatted}):[],[g.assets.displayAssets,l,i,t?.address,t?.chainId,n]);return u.useEffect(()=>{if(!e.enabled||g.status.isExecuting)return;const w=(d&&C.find(b=>us(b)===us(d)))??C[0]??null;(!d||!w||us(d)!==us(w)||d.balance!==w.balance)&&c(w)},[e.enabled,g.status.isExecuting,C,d]),{supply:g,candidates:C,source:d,setSource:c,feeToken:l,sourceKey:us}}const Fi=f.font.ui,lu=({label:e,loading:t,balance:n,dark:s,dk:o})=>{const a=s?o.textSecondary:"#7D7C7B",i=s?o.textSecondary:"#71757A";return r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[r.jsx("span",{style:{fontFamily:Fi,fontSize:"17px",fontWeight:500,color:a,lineHeight:"24px"},children:e}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",fontFamily:Fi,fontSize:"13px",fontWeight:500,color:i,lineHeight:"16px"},children:["Balance:"," ",t?"...":n===null?"\u2014":f.formatBalance(n)]})]})},ji=({isOpen:e,position:t,title:n,items:s,selectedId:o,onSelect:a,portalAttribute:i})=>{const{dark:l,dk:d,primaryColor:c}=f.useSpiceBrand(),[p,m]=u.useState(null),[h,g]=u.useState(!1);return u.useEffect(()=>{if(!e){g(!1);return}const x=requestAnimationFrame(()=>{requestAnimationFrame(()=>g(!0))});return()=>cancelAnimationFrame(x)},[e]),!e||!t||s.length===0?null:Hn.createPortal(r.jsxs("div",{[`data-${i}-popover`]:"true",style:{position:"fixed",top:`${t.top}px`,left:`${t.left}px`,opacity:h?1:0,transform:h?"scale(1) translateY(0)":"scale(0.96) translateY(-6px)",transition:`opacity 200ms ${f.easing.out}, transform 200ms ${f.easing.out}`,backgroundColor:l?d.shell:"#ffffff",borderRadius:"10px",padding:"10px 12px",boxShadow:l?"0 16px 48px rgba(0,0,0,0.45)":"0 12px 32px rgba(0,0,0,0.12)",border:`1px solid ${d.cardBorder}`,minWidth:"220px",zIndex:f.z.dropdown,fontFamily:f.font.mono},children:[r.jsx("div",{style:{marginBottom:"6px"},children:r.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:l?d.textPrimary:"#0e0d0b",textTransform:"uppercase",letterSpacing:"1px"},children:n})}),r.jsx("div",{style:{borderBottom:`1px solid ${d.cardBorder}`,marginBottom:"6px"}}),r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"2px"},children:s.map(x=>{const y=o===x.id,C=p===x.id;return r.jsxs("button",{onClick:w=>{w.stopPropagation(),a(x.id)},onMouseEnter:()=>m(x.id),onMouseLeave:()=>m(null),style:{display:"flex",alignItems:"center",gap:"8px",padding:"6px 4px",borderRadius:"8px",border:"none",cursor:"pointer",backgroundColor:y?l?d.hoverBg:"#f3f4f6":C?l?d.cardBg:"#f9fafb":"transparent",transition:"background-color 0.15s",width:"100%",fontFamily:f.font.mono},children:[x.icon&&r.jsx("img",{src:x.icon,alt:x.label,style:{width:"22px",height:"22px",borderRadius:"50%"}}),r.jsx("span",{style:{fontSize:"13px",fontWeight:y?700:500,textTransform:"uppercase",color:l?d.textPrimary:"#0e0d0b",letterSpacing:"0.5px",flex:1,textAlign:"left"},children:x.label}),x.detail&&r.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:d.textSecondary},children:x.detail}),y&&r.jsx(Ba,{color:c,style:{flexShrink:0}})]},x.id)})})]}),document.body)},zs=f.font.ui,cu=f.font.mono,du=170,uu=({header:e,amount:t,receiveAmountDisplay:n,receiveUsdEstimate:s,selectedDestToken:o,destTokenSymbol:a,destChainName:i,destChainLogo:l,compatibleDestinationChains:d,networkSwitchRef:c,onOpenNetworkPopover:p,showNetworkPopover:m,setShowNetworkPopover:h,networkPopoverPos:g,selectedChainId:x,setSelectedChainId:y,dark:C,dk:w})=>{const b=C?w.cardBg:"#E9E9E9",I=C?w.cardBorder:"#C6C6C6",S=C?w.textSecondary:"#71757A",v=C?w.textPrimary:"#0E0D0B",B=C?w.cardBorder:"#C5C5C4",E=C?"rgba(255,255,255,0.08)":"#D4D3D3",j=a.length>8?"14px":a.length>6?"16px":"18px";return r.jsxs("div",{style:{backgroundColor:b,border:`1px solid ${I}`,borderRadius:"7px",padding:"14px 16px 12px 16px",minHeight:"138px",display:"flex",flexDirection:"column",gap:"6px"},children:[e,r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[r.jsxs("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[r.jsx(An,{element:"div",value:n,title:n,fontFamily:zs,color:t?v:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,overflow:"wrap"}),r.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:S,fontFamily:zs,marginTop:"10px"},children:s})]}),r.jsxs("div",{style:{width:`${du}px`,flexShrink:0,display:"flex",flexDirection:"column",alignItems:"stretch",gap:"8px"},children:[r.jsxs("div",{style:{backgroundColor:"transparent",border:`1px solid ${B}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px"},children:[r.jsx("img",{src:o?.logoURI||Ql,alt:a,style:{width:"24px",height:"24px",borderRadius:"50%"}}),r.jsx("span",{style:{fontSize:j,fontWeight:500,color:v,lineHeight:"1.3",fontFamily:zs,flex:1,minWidth:0,letterSpacing:0},children:a})]}),r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:E,borderTop:`1px solid ${B}`},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[l&&r.jsx("img",{src:l,alt:i,style:{width:"13px",height:"13px",borderRadius:"50%",flexShrink:0}}),r.jsx("span",{style:{fontSize:"11px",fontWeight:400,color:v,fontFamily:zs,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:i})]}),r.jsx("button",{ref:c,onClick:N=>{N.stopPropagation(),p(c.current)},style:{background:"none",border:"none",cursor:d.length>1?"pointer":"not-allowed",padding:"0 0 0 8px",fontSize:"9.5px",fontFamily:cu,color:S,textDecoration:"underline",fontWeight:600,opacity:d.length>1?1:.45},children:"Switch"}),r.jsx(ji,{isOpen:m,position:g,title:"SELECT NETWORK",portalAttribute:"network",items:d.map(N=>{const T=f.getChainConfig(N);return{id:String(N),label:T?.displayName||String(N),icon:yn[N]||Kn}}),selectedId:x!==null?String(x):null,onSelect:N=>{y(Number(N)),h(!1)}})]})]}),r.jsx("div",{style:{minHeight:"14px"}})]})]})]})},pu=f.font.ui,bn=f.font.mono,fu=({show:e,onToggle:t,showCustomAddress:n,setShowCustomAddress:s,customRecipient:o,setCustomRecipient:a,externalAddress:i,recipientAddress:l,destChainName:d,destChainLogo:c,compatibleDestinationChains:p,txDetailsChainSwitchRef:m,onOpenNetworkPopover:h,sourceChainLabel:g,sourceDetailsLogo:x,sourceTokenLabel:y,amount:C,totalSourceDebitDisplay:w,receiveAmountDisplay:b,destTokenSymbol:I,shouldQuoteWithdrawGas:S,estimatingFee:v,feeError:B,displayedGasFee:E,selectedDestToken:j,theme:N,styles:T,dark:P,dk:M})=>{const D=P?M.textSecondary:"#71757A",L=P?M.textPrimary:"#0E0D0B",R=p.length>1,U=n&&o?A.isAddress(o)?f.truncateAddress(o):o:l?f.truncateAddress(l):"\u2014";return r.jsxs(r.Fragment,{children:[r.jsxs("div",{onClick:t,style:{display:"flex",alignItems:"center",gap:"6px",marginBottom:e?"10px":"0",cursor:"pointer",userSelect:"none"},children:[r.jsx("span",{style:{fontSize:"13px",color:D,fontFamily:pu,fontWeight:600},children:"Transaction Details"}),r.jsx($c,{size:12,color:D,style:{transform:e?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s"}})]}),e&&r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"7px"},children:[r.jsxs("div",{children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[r.jsx("span",{style:{fontSize:"12px",color:D,fontFamily:bn,fontWeight:500,letterSpacing:"0.03em"},children:"TO"}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[r.jsx("span",{style:{fontSize:"13px",color:L,fontFamily:bn,fontWeight:500},children:U}),r.jsx("button",{onClick:()=>{s(X=>!X),!n&&i&&a(i)},style:{background:"none",border:"none",cursor:"pointer",padding:"0",fontSize:"9.5px",fontFamily:bn,color:D,textDecoration:"underline",fontWeight:600},children:n?"Reset":"Switch"})]})]}),n&&r.jsxs("div",{style:{marginTop:"6px"},children:[r.jsx("div",{style:{marginBottom:"6px",padding:"7px 9px",borderRadius:"6px",border:"1px solid rgba(239, 68, 68, 0.55)",backgroundColor:"rgba(239, 68, 68, 0.12)",color:"#ef4444",fontSize:"10px",lineHeight:1.35,fontFamily:bn,fontWeight:700,letterSpacing:0,textTransform:"uppercase"},children:"CAUTION: ENTERING AN INCORRECT ADDRESS WILL RESULT IN LOSS OF FUNDS"}),r.jsx("input",{type:"text",autoComplete:"off",spellCheck:!1,"aria-label":"Recipient address","aria-invalid":o&&!A.isAddress(o)?!0:void 0,"data-spiceflow-focus":!0,value:o,onChange:X=>a(X.target.value),placeholder:"0x...",style:{width:"100%",padding:"8px 10px",borderRadius:"6px",border:`1px solid ${o&&!A.isAddress(o)?P?M.errorBorder:"#fca5a5":P?M.inputBorder:"#d1d5db"}`,backgroundColor:P?M.inputBg:"#f9fafb",color:P?M.inputText:"#111827",fontSize:"12px",fontFamily:bn,outline:"none",boxSizing:"border-box"}}),o&&!A.isAddress(o)&&r.jsx("span",{style:{fontSize:"11px",color:M.errorText,marginTop:"3px",display:"block"},children:"Invalid address"})]})]}),r.jsx(wn,{palette:M,labelColor:D,valueColor:L,label:"RECEIVING CHAIN",value:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"7px"},children:[c&&r.jsx("img",{src:c,alt:d,style:{width:"14px",height:"14px",borderRadius:"50%"}}),r.jsx("span",{style:{fontSize:"13px",color:L,fontWeight:500,fontFamily:bn,textTransform:"uppercase"},children:d}),r.jsx("button",{ref:m,onClick:X=>{X.stopPropagation(),h(m.current)},style:{background:"none",border:"none",cursor:R?"pointer":"not-allowed",padding:"0",fontSize:"9.5px",fontFamily:bn,color:D,textDecoration:"underline",fontWeight:600,opacity:R?1:.45},children:"Switch"})]})}),r.jsx(wn,{palette:M,labelColor:D,valueColor:L,label:"REQUESTED WITHDRAWAL",value:r.jsxs($o,{logo:x||null,alt:g,primaryText:L,children:[C||"0"," ",y]})}),S&&r.jsx(wn,{palette:M,labelColor:D,valueColor:L,label:"TOTAL SOURCE DEBIT",value:r.jsxs($o,{logo:x||null,alt:g,primaryText:L,children:[w," ",y]})}),r.jsx(wn,{palette:M,labelColor:D,valueColor:L,label:"YOU RECEIVE",value:r.jsxs($o,{logo:c,alt:d,primaryText:L,gap:"4px",children:[b," ",I]})}),S&&r.jsxs(r.Fragment,{children:[r.jsx(wn,{palette:M,labelColor:D,label:"EST. NETWORK FEE",valueColor:B?"#f87171":L,value:v?"Estimating...":B?"Unavailable":E!==null&&j?`${zo(E,j.decimals)} ${j.symbol}`:"Estimating..."}),B&&r.jsx(sn,{variant:"error",size:"compact",palette:M,fontFamily:T?.fontFamily||N.typography.fontFamily,children:B})]})]})]})},mu=u.memo(fu),$o=({logo:e,alt:t,primaryText:n,gap:s="6px",children:o})=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:s},children:[e&&r.jsx("img",{src:e,alt:t,style:{width:"13px",height:"13px",borderRadius:"50%"}}),r.jsx("span",{style:{fontSize:"13px",color:n,fontWeight:500,fontFamily:bn},children:o})]}),ps=f.font.ui,hu=170,gu=({header:e,amount:t,setAmount:n,isInsufficient:s,sourceAmountDecimals:o,selectedSourceAsset:a,resolvedSelectedSourceAsset:i,spiceAssets:l,setSelectedSourceAsset:d,sourceUsdEstimate:c,sourceTokenLabel:p,sourceChainLabel:m,totalSelectedBalance:h,showSourceTokenPopover:g,setShowSourceTokenPopover:x,tokenPopoverPos:y,setTokenPopoverPos:C,tokenTriggerRef:w,primaryColor:b,dark:I,dk:S})=>{const v=I?S.cardBg:"#E9E9E9",B=I?S.cardBorder:"#C6C6C6",E=I?S.textSecondary:"#71757A",j=I?S.textPrimary:"#0E0D0B",N=I?S.cardBorder:"#C5C5C4",T=I?"rgba(255,255,255,0.08)":"#D4D3D3",P=p.length>8?"14px":p.length>6?"16px":"18px";return r.jsxs("div",{style:{backgroundColor:v,border:`1px solid ${B}`,borderRadius:"7px",padding:"14px 16px 12px 16px",minHeight:"138px",display:"flex",flexDirection:"column",gap:"6px",position:"relative"},children:[e,r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[r.jsxs("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[r.jsx(An,{element:"input",ariaLabel:"Withdraw amount",ariaInvalid:s,dataSpiceflowFocus:!0,value:t,onChange:M=>{const D=M.target.value;if(D===""){n("");return}/^\d*\.?\d*$/.test(D)&&n(f.parseNumericInput(D.startsWith(".")?`0${D}`:D,o??a?.decimals))},placeholder:"0.0",fontFamily:ps,color:s?"#ef4444":t?j:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,style:{width:"100%"}}),r.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:E,fontFamily:ps,marginTop:"10px"},children:c})]}),r.jsx("div",{style:{width:`${hu}px`,flexShrink:0},children:r.jsxs("div",{style:{backgroundColor:"transparent",border:`1px solid ${N}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[r.jsxs("div",{ref:w,onClick:M=>{if(M.stopPropagation(),!g&&w.current){const D=w.current.getBoundingClientRect(),L=220,R=16;C({top:D.bottom+8,left:Math.min(Math.max(R,D.right-L),window.innerWidth-L-R)})}x(D=>!D)},style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px",cursor:"pointer"},children:[r.jsx("img",{src:po,alt:p,style:{width:"24px",height:"24px",borderRadius:"50%"}}),r.jsx("span",{style:{fontSize:P,fontWeight:500,color:j,lineHeight:"1.3",fontFamily:ps,flex:1,minWidth:0,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",letterSpacing:0},children:p}),r.jsx(Pn,{size:15,color:j,strokeWidth:2.25})]}),r.jsx(ji,{isOpen:g,position:y,title:"SELECT TOKEN",portalAttribute:"token",items:(l||[]).map(M=>({id:M.receiptTokenId||M.address,label:M.displaySymbol||M.receiptTokenName||M.symbol,icon:po,detail:f.formatBalance(M.balanceFormatted)})),selectedId:i?.receiptTokenId||i?.address||null,onSelect:M=>{const D=(l||[]).find(L=>(L.receiptTokenId||L.address)===M);D&&(d(D),n("")),x(!1)}}),r.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:T,borderTop:`1px solid ${N}`},children:r.jsx("span",{style:{fontSize:"11px",fontWeight:400,color:j,fontFamily:ps,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:m})})]})})]}),r.jsxs("div",{style:{minHeight:"18px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[s?r.jsx("span",{style:{fontSize:"12px",color:S.errorText,fontFamily:ps,fontWeight:500},children:"Insufficient Balance"}):r.jsx("span",{}),r.jsx("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0px",minHeight:"32px",marginRight:"-9px"},children:[0,25,50,75,100].map((M,D)=>{const L=D===4,R=parseFloat(t)||0,U=h>0&&Math.abs(R/h*100-M)<1;return r.jsx("button",{type:"button","aria-label":`Set amount to ${M}%`,"aria-pressed":U,onClick:()=>{const X=h*M/100,Y=a?.decimals??6,V=Math.floor(X*10**Y)/10**Y;n(M===0?"":V>0?f.formatDecimalInput(V,Y):"")},title:`${M}%`,disabled:h===0,"data-spiceflow-focus":!0,style:{width:"32px",height:"32px",padding:"9px",border:"none",backgroundColor:"transparent",cursor:h===0?"not-allowed":"pointer",opacity:U?1:.5,transition:"opacity 0.15s ease",display:"flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box"},children:r.jsx(No,{pct:M,isMax:L,primaryColor:b,dark:I,fillColor:I?S.textSecondary:"#3C3E42"})},M)})})]})]})},xu=({dark:e,dk:t})=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[r.jsx("img",{src:Io,alt:"","aria-hidden":"true",style:{width:"13px",height:"13px",flexShrink:0,...e?{filter:"invert(0.6)"}:{}}}),r.jsx("p",{style:{fontSize:"13px",color:e?t.textSecondary:"#979AA0",margin:"0",lineHeight:"1.4",fontFamily:f.font.ui},children:"Withdraw collateral from your account to 10+ EVM blockchains."})]});function yu(e){const{record:t}=e,n=u.useContext(f.SpiceFlowProviderContext),s=t.actionFunding.identity,o=t.actionFunding?.actionDefinition,a=t.actionFunding?.purpose,i=t.embeddedWalletAddress,[l,d]=u.useState(0),[c,p]=u.useState(),[,m,h]=a?.split(":")??[],g=e.knownAssets.find(C=>C.chainId===Number(m)&&f.addressesEqual(C.address,h));u.useEffect(()=>{let C=!0;return(async()=>{try{if(!o||!h||!A.isAddress(h))throw new Error("The original withdrawal details are unavailable. Preserve this pending action for reconciliation.");const w=ls(o),b=Number(m);if(w.context.chainId!==b||!f.addressesEqual(w.context.executorAddress??w.context.userAddress,i)||w.calls.length!==1)throw new Error("The original withdrawal details do not match this account.");const I=w.calls[0];let S,v;if(k.isNativeToken(h)){if(I.data!=="0x")throw new Error("Invalid original native withdrawal.");S=I.to,v=I.value}else{const j=A.decodeFunctionData({abi:A.erc20Abi,data:I.data});if(!f.addressesEqual(I.to,h)||I.value!==0n||j.functionName!=="transfer")throw new Error("Invalid original token withdrawal.");[S,v]=j.args}if(v<=0n||!A.isAddress(S)||f.addressesEqual(S,i))throw new Error("Invalid original withdrawal recipient or amount.");const B=k.getTokenByAddress(h,b),E=g??B??await na(f.getClientForChain(b),h);C&&p({identity:s,amount:v,recipient:S,asset:{address:h,chainId:b,symbol:E.symbol,name:E.name,decimals:E.decimals,balance:0n,balanceFormatted:0,balanceUsd:0,isNative:k.isNativeToken(h),owner:i,_source:"wallet",location:"embedded"}})}catch(w){C&&p({identity:s,error:f.sanitizeError(w,"Unable to restore the original withdrawal.")})}})(),()=>{C=!1}},[s,o,a,i,g?.symbol,g?.name,g?.decimals,n?.rpcOverrides?.[Number(m)],l]);const x=c?.identity===s?c:void 0,{supply:y}=Ei({enabled:!!x?.asset&&!!t.actionFunding?.submitted,asset:x?.asset??null,amount:x?.amount??0n,recipient:x?.recipient,owner:i,sourceChains:e.sourceChains,onSuccess:e.onSuccess,onError:e.onError});return r.jsxs("div",{style:{display:"grid",gap:16,padding:"16px 0"},children:[r.jsx("p",{children:"This account has a pending withdrawal."}),x?.asset?r.jsxs(r.Fragment,{children:[r.jsxs("div",{children:[A.formatUnits(x.amount,x.asset.decimals)," ",x.asset.symbol]}),r.jsxs("div",{style:{overflowWrap:"anywhere"},children:["To ",x.recipient]}),r.jsx(f.Button,{fullWidth:!0,disabled:!y.canExecute,loading:y.status.isExecuting,onClick:()=>void y.submitPay(),children:"Check withdrawal"})]}):x?.error?null:r.jsx("span",{role:"status",children:"Restoring withdrawal details\u2026"}),(x?.error||y.status.error)&&r.jsx("p",{role:"alert",children:x?.error||y.status.error}),x?.error&&r.jsx(f.Button,{onClick:()=>{p(void 0),d(C=>C+1)},children:"Retry details"}),y.status.finalizationError&&r.jsx(f.Button,{disabled:y.status.finalizing,onClick:()=>void y.retryFinalization(),children:"Retry application update"}),y.status.statusMsg&&r.jsx("span",{role:"status",children:y.status.statusMsg})]})}const wu=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,styles:s,onWithdrawExecute:o,onWithdrawSuccess:a,onWithdrawError:i,availableTokens:l,initialSourceAssetId:d,walletAssets:c,buildSpicenetBatch:p})=>{const m=u.useContext(f.SpiceFlowProviderContext);if(!m)return r.jsx("div",{children:"Error: SpiceWithdraw must be used within SpiceFlowProvider"});const h=m.mode||"7702",g=h==="presign"||h==="ondemand",x=m.supportedChainIds,y=m.allowedTokens,C=!!c,w=c?.initialAsset,b=u.useMemo(()=>[...c?.extraAssets??[],...w?[w]:[]].map(ee=>({address:ee.address,chainId:ee.chainId,symbol:ee.symbol,decimals:ee.decimals})),[c?.extraAssets,w]),I=m.isWhitelistGateActive,{theme:S,dark:v,dk:B}=f.useSpiceBrand(s),E=m.network,j=()=>g?"select":"provider-login",[N,T]=u.useState(j()),[P,M]=u.useState(!1),[D,L]=u.useState(null),[R,U]=u.useState(null),[X,Y]=u.useState(""),[V,J]=u.useState(!1),[ce,G]=u.useState(!1),[q,Z]=u.useState(!1),[_,H]=u.useState(""),[F,de]=u.useState(!0),re=u.useRef(null),xe=u.useRef(null),he=u.useRef(null),[ae,be]=u.useState(null),[O,se]=u.useState(null),W=f.useWallet(),{isReady:$,isAuthenticated:oe,address:Ce}=W,Me=m?.embeddedWalletAddress,ne=za(Me,"withdraw:",!0),{address:Ie,chainId:ge}=_t.useAccount(),Ye=m.externalWalletAddress||Ie,[tt,dt]=u.useState(!1),[Xe,$e]=u.useState(null),qe=u.useRef(i);qe.current=i;const nt=u.useCallback(ee=>{$e(ee),typeof ee=="string"&&ee&&qe.current?.(ee,f.getRelayerErrorDetail(ee))},[]),[Ve,Re]=u.useState(null),Le=u.useRef(null),ot=u.useRef(!0),Qe=u.useRef(null);u.useEffect(()=>(ot.current=!0,()=>{ot.current=!1}),[]);const{execute:Ge,estimate:Pe}=Rs(),[Te,Ke]=u.useState(null),[st,Se]=u.useState(null),[De,gt]=u.useState(!1),[te,Ue]=u.useState(null),{assets:me,loading:ye,error:K,refresh:ze}=Nn({owner:Me,role:"holding",includeWalletAssets:C,additionalSourceTokens:b,enabled:e&&!!Me}),Ae=u.useMemo(()=>{if(I)return[];const ee=(ue,Be)=>(Be.balanceUsd||0)-(ue.balanceUsd||0);return(me??[]).filter(ue=>ue.balance>0n&&vn(ue,"holding",{allowedTokens:y,isWhitelistGateActive:I}).eligible).sort(ee)},[me,y,I]),Fe=u.useMemo(()=>[...new Set([...x??[],...Object.keys(l??{}).map(Number),...(Ae||[]).map(ee=>ee.chainId),...(Ae||[]).flatMap(ee=>Object.keys(ee.chainTokens??{}).map(ue=>{const[,Be]=ue.split(":"),_e=Number(Be);return Number.isFinite(_e)?_e:null}).filter(ue=>ue!==null))])].filter(ee=>f.getChainConfig(ee)?.network===E),[x,l,Ae,E]),Ee=u.useMemo(()=>{if(l)return l;const ee={};for(const ue of Ae||[]){const Be=Object.entries(ue.chainTokens??{});if(Be.length>0){for(const[_e,it]of Be){const[et,vt,ht]=_e.split(":");if(et!=="evm"||!vt||!ht)continue;const At=Number(vt);if(!Number.isFinite(At))continue;const yt=ht.startsWith("0x")?ht.toLowerCase():`0x${ht.toLowerCase()}`,Ut=f.getChainConfig(At)?.supportedTokens?.find(Nt=>f.addressesEqual(Nt.address,yt));Ut&&io(ue,yt,At)&&(ee[At]||(ee[At]=[]),ee[At].find(Nt=>f.addressesEqual(Nt.address,yt))||ee[At].push({address:yt,symbol:Ut?.symbol||it?.name||ue.symbol,name:Ut?.name||it?.name||ue.displayName||ue.name||ue.symbol,decimals:Ut?.decimals??it?.decimals??ue.decimals,logoURI:Ut?.logo||ue.logoURI}))}continue}ee[ue.chainId]||(ee[ue.chainId]=[]),ee[ue.chainId].find(_e=>f.addressesEqual(_e.address,ue.address))||ee[ue.chainId].push({address:ue.address,symbol:ue.symbol,name:ue.displayName||ue.name||ue.symbol,decimals:ue.decimals,logoURI:ue.logoURI})}return ee},[l,Ae]),ie=u.useCallback((ee,ue)=>{const Be=wd(ee,ue,ue?Ee[ue]??[]:[]);return!ee||!Be||!ue||ee._source==="wallet"&&ue!==ee.chainId?null:vn(ee,"withdraw-destination",m,{...Be,chainId:ue}).eligible?Be:null},[Ee,m.allowedTokens,m.rpcOverrides,m.isWhitelistGateActive]),Q=u.useMemo(()=>D?Ae.find(ee=>ct(ee)===ct(D))??null:null,[D,Ae]),we=Q?._source==="wallet",He=u.useMemo(()=>{if(!Q)return[];const ee=Object.keys(Q.chainTokens??{}).map(ue=>cn(ue)?.chainId??null).filter(ue=>ue!==null);return Array.from(new Set([...ee,Q.chainId,...Fe].filter(Number.isFinite))).filter(ue=>f.getChainConfig(ue)?.network===E&&ie(Q,ue)!==null)},[Q,Fe,ie,E]),Et=u.useMemo(()=>{if(!Q||typeof window>"u")return null;const ee=`spiceflow:withdraw-chain:${Q.receiptTokenId||Q.address.toLowerCase()}`,ue=window.localStorage.getItem(ee),Be=ue?Number(ue):null;return Be!==null&&Number.isFinite(Be)&&He.includes(Be)?Be:null},[Q,He]),Ft=u.useMemo(()=>Q?Et!==null?Et:ge&&He.includes(ge)?ge:Q.chainId&&He.includes(Q.chainId)?Q.chainId:He[0]??null:Fe[0]??null,[Q,Et,ge,He,Fe]),ve=u.useMemo(()=>ie(Q,R),[ie,Q,R]);u.useEffect(()=>{e&&(L(null),Y(""))},[e,d,w?.address,w?.chainId]),u.useEffect(()=>{if(!e||!Ae.length||D)return;const ee=w?Ae.find(ue=>ue.chainId===w.chainId&&f.addressesEqual(ue.address,w.address)&&ue._source==="wallet"):d?Ae.find(ue=>ue.receiptTokenId===d):Ae[0];L(ee??null),Y("")},[e,Ae,D,d,w]),u.useEffect(()=>{Q&&(R===null||!He.includes(R))&&U(Ft)},[Q,R,Ft,He]),u.useEffect(()=>{if(!V&&!ce)return;const ee=ue=>{const Be=ue.target;V&&!re.current?.contains(Be)&&!xe.current?.contains(Be)&&!Be?.closest?.("[data-network-popover]")&&J(!1),ce&&!he.current?.contains(Be)&&!Be?.closest?.("[data-token-popover]")&&G(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[V,ce]);const wt=u.useCallback(ee=>{if(!ee||He.length<=1)return;const ue=ee.getBoundingClientRect(),Be=220,_e=16;be({top:ue.bottom+8,left:Math.min(Math.max(_e,ue.right-Be),window.innerWidth-Be-_e)}),J(it=>!it)},[He.length]),ut=u.useCallback(()=>de(ee=>!ee),[]);u.useEffect(()=>{if(!Q||R===null||typeof window>"u")return;const ee=`spiceflow:withdraw-chain:${Q.receiptTokenId||Q.address.toLowerCase()}`;window.localStorage.setItem(ee,String(R))},[Q,R]);const St=q?A.isAddress(_)?_:void 0:Ye||(we?void 0:Me),Kt=Nn({owner:St,role:"holding",includeRollupAssets:!1,sourceChains:R?[R]:[],additionalSourceTokens:ve&&R?[{...ve,chainId:R}]:[],enabled:e&&!!St&&!!ve&&!!R}),on=Kt.walletAssets.find(ee=>f.addressesEqual(ee.owner,St)&&ee.chainId===R&&f.addressesEqual(ee.address,ve?.address)),pn=Q?.balanceFormatted??0,Zt=Q?.displaySymbol||Q?.receiptTokenName||Q?.symbol||"Select token",at=Q?.displayChainName||(we?f.getChainConfig(Q.chainId)?.displayName:"Spicenet")||"Network",rt=Q?.receiptTokenDecimals??Q?.decimals,bt=u.useMemo(()=>{if(!ve||rt===void 0)return 0n;try{return qt(X||"0",rt)}catch{return 0n}},[X,ve,rt]),Oe=u.useMemo(()=>!ve||rt===void 0?0n:$a(bt,rt,ve.decimals),[ve,rt,bt]),Ht=u.useMemo(()=>{if(we)return 0n;const ee=st??Te;return!ee||ee<=0n||!ve||rt===void 0?0n:$a(ee,ve.decimals,rt)},[we,st,Te,ve,rt]),Rt=u.useMemo(()=>bt+Ht,[bt,Ht]),Mt=st??Te,mt=Ei({enabled:e&&we,asset:we?Q:null,amount:bt,recipient:St,owner:Me,sourceChains:x,onSuccess:a,onError:i}),We=mt.supply,Dt=tt||we&&(We.status.isExecuting||We.status.finalizing),jt=We.status.step==="success"||We.status.paymentResult?.status==="success",Vt=u.useCallback(ee=>{if(we||!R||!ve)return[];if(bt===0n||Oe===0n||!St)return[];const ue=Array.isArray(ee)?ee.filter(et=>et.amount>0n):[{token:ve.address,recipient:St,amount:ee??Oe}],Be=ue.reduce((et,vt)=>et+vt.amount,0n);if(Be<=0n)return[];const _e={chainId:R,calls:[],tokenTransfers:ue.map(et=>({from:"escrow",to:et.recipient,token:et.token,amount:et.amount}))};if(!p)return[_e];const it=p({destinationChainId:R,deliveryToken:ve.address,deliveryAmount:Be,deliveryRecipient:St,deliveryTransfers:ue,requestTimestampMs:Qe.current??Date.now()});return it?[it,_e]:[_e]},[we,R,ve,bt,Oe,St,p]),It=u.useMemo(()=>Vt(),[Vt]),ke=u.useMemo(()=>Ed(It,ve?.address),[It,ve?.address]),je=u.useRef(null),Ct=!we&&e&&!g&&!tt&&!!ve&&!!R&&bt!==0n;Ao({shouldRun:Ct&&It.length>0&&!!ke,deps:[Ct,It.length>0,ke],delayMs:500,onSkip:()=>{je.current=null,Ke(null),Ue(null),gt(Ct&&It.length===0)},onCleanup:()=>gt(!1),run:async({isCurrent:ee,signal:ue})=>{const Be=ke;gt(!0),Ue(null);try{const _e=await Ad({batches:It,tokenAddress:ve.address,chainId:R,estimate:Pe,signal:ue});if(!ee())return;je.current={key:Be,quote:_e},Ke(_e.gasFee)}catch(_e){if(!ee())return;je.current=null,Ke(null),Ue(_e instanceof Error?_e.message:"Failed to estimate gas fee")}finally{ee()&&gt(!1)}}}),u.useEffect(()=>{tt||Se(null)},[tt,X,R,ve?.address]);const pt=u.useCallback(()=>{M(!0),T("select")},[]),xt=u.useCallback(()=>{Dt||t()},[t,Dt]),fn=u.useRef(null);fn.current={batches:It,walletAddress:Ce,recipient:St,token:ve,chainId:R,amount:X,receiveAmountRaw:Oe,gasFee:Te,feeEstimate:ke&&je.current?.key===ke?je.current.quote.feeEstimate:null,isNon7702:g,buildWithdrawBatches:Vt,execution:{estimate:Pe,execute:Ge},ui:{setIsExecuting:dt,setExecutionError:nt,setExecutionProgress:Re,setLockedGasFee:Se},executionContextRef:Le,isMountedRef:ot,onWithdrawExecute:o,onWithdrawSuccess:a,buildSpicenetBatch:p};const qn=u.useCallback(()=>(Qe.current=Date.now(),Xa(fn.current)),[]),Tn=u.useCallback(()=>(Qe.current=Date.now(),Id(fn.current)),[]);if(u.useEffect(()=>{if(!e){const ee=setTimeout(()=>{T(j()),M(!1),L(null),U(null),Y(""),J(!1),G(!1),Z(!1),H(""),dt(!1),nt(null),Re(null),Le.current=null},300);return()=>clearTimeout(ee)}},[e,g]),u.useEffect(()=>{if(!g&&e&&N==="provider-login"&&$&&oe&&Me&&!P){const ee=setTimeout(()=>{M(!0),T("select")},100);return()=>clearTimeout(ee)}},[g,e,N,$,oe,Me,P]),!e)return null;if(N==="provider-login"&&!g)return r.jsx(Wo,{onAuthSuccess:pt,autoTrigger:!0});if(!Dt&&(ne.record||ne.error))return r.jsx(zt,{isOpen:!0,onClose:xt,title:"Withdraw",styles:s,theme:S,dark:v,maxWidth:"486px",closeOnBackdropClick:n,children:ne.error?r.jsx("p",{role:"alert",children:ne.error}):r.jsx(yu,{record:ne.record,knownAssets:[...me,...c?.extraAssets??[],...w?[w]:[]],sourceChains:x,onSuccess:a,onError:i},ne.record.actionFunding.identity)});if(N==="select"){const ee=parseFloat(X)||0,ue=rt?zo(Rt,rt):X||"0",Be=!!Q&&Rt>Q.balance,_e=(R?f.getChainConfig(R):null)?.displayName||"Network",it=R?yn[R]||Kn:null,et=ve?.symbol||"\u2014",vt=Zt,ht=ve?zo(Oe,ve.decimals):"0",At=Q&&Q.balanceFormatted>0?Q.balanceUsd/Q.balanceFormatted:void 0,yt=Q?.priceStatus==="stale",Ut=_a(ee,At,yt),Nt=_a(parseFloat(ht)||0,At,yt),Yt=(!q||A.isAddress(_))&&(!we||!f.addressesEqual(St,Me)),mn=!g&&!we&&ee>0&&ve!==null,Cn=!mn||Te!==null&&!De&&!te,rn=ee>0&&!Be&&!ye&&!K&&Q!==null&&R!==null&&ve!==null&&St&&Yt&&Cn&&Oe>0n&&(!we||We.canExecute&&!jt),Xt=!rn,Qt=ye?"LOADING BALANCES":K?"BALANCES UNAVAILABLE":Q===null?"NO BALANCE":ee===0?"ENTER AMOUNT":Be?"INSUFFICIENT BALANCE":mn&&!Cn?te?"GAS UNAVAILABLE":"ESTIMATING GAS":mn&&Oe===0n?"AMOUNT TOO SMALL":we&&!We.canExecute?"REVIEW FEES":"WITHDRAW",z=!!Ve&&(Ve.step==="success"||Ve.step==="error"),pe=s?.primaryColor||S.colors.primary,Ne=402,fe=(Ze,lt,an)=>r.jsx(lu,{label:Ze,loading:an,balance:lt,dark:v,dk:B});return r.jsx(zt,{isOpen:!0,onClose:xt,title:"Withdraw",subtitle:r.jsx(xu,{dark:v,dk:B}),styles:s,theme:S,dark:v,maxWidth:"486px",footerLinkText:"Spicenet accounts \u2192",overlayDimmed:!1,closeOnBackdropClick:n,overlayContent:z?r.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,display:"flex",flexDirection:"column",justifyContent:"flex-end",pointerEvents:"none",zIndex:20},children:r.jsx("div",{style:{pointerEvents:"auto"},children:r.jsx(Lo,{type:"withdraw",isOpen:!0,isProcessing:tt,onRetryTx:()=>{Tn()},onNewTx:()=>{Re(null),Y(""),nt(null),Le.current=null},onClose:()=>{Re(null),nt(null),dt(!1),Le.current=null},onComplete:()=>{Re(null),nt(null),dt(!1),Le.current=null},results:[{asset:{symbol:ve?.symbol||"Token",address:ve?.address||""},txHash:Ve?.txHash||"",success:Ve?.step==="success",error:Ve?.error,amount:X}],chainId:R??void 0,theme:S})})}):null,children:r.jsxs("fieldset",{disabled:Dt,style:{border:0,minWidth:0,width:`${Ne}px`,margin:"0 auto",padding:"0 0 4px 0",position:"relative"},children:[r.jsxs("div",{style:{marginTop:"16px",marginBottom:"16px",display:"flex",flexDirection:"column",gap:"16px"},children:[r.jsx(gu,{header:fe("Source",pn,ye),amount:X,setAmount:Y,isInsufficient:Be,sourceAmountDecimals:rt,selectedSourceAsset:Q,resolvedSelectedSourceAsset:Q,spiceAssets:Ae,setSelectedSourceAsset:L,sourceUsdEstimate:Ut,sourceTokenLabel:vt,sourceChainLabel:at,totalSelectedBalance:pn,showSourceTokenPopover:ce,setShowSourceTokenPopover:G,tokenPopoverPos:O,setTokenPopoverPos:se,tokenTriggerRef:he,primaryColor:pe,dark:v,dk:B}),r.jsx(uu,{header:fe("Destination",on?.balanceFormatted??null,Kt.loading),amount:X,receiveAmountDisplay:ht,receiveUsdEstimate:Nt,selectedDestToken:ve,destTokenSymbol:et,destChainName:_e,destChainLogo:it,compatibleDestinationChains:He,networkSwitchRef:re,onOpenNetworkPopover:wt,showNetworkPopover:V,setShowNetworkPopover:J,networkPopoverPos:ae,selectedChainId:R,setSelectedChainId:U,dark:v,dk:B})]}),r.jsxs("div",{style:{marginBottom:S.spacing.sm},children:[r.jsx(mu,{show:F,onToggle:ut,showCustomAddress:q,setShowCustomAddress:Z,customRecipient:_,setCustomRecipient:H,externalAddress:Ye,recipientAddress:St,destChainName:_e,destChainLogo:it,compatibleDestinationChains:He,txDetailsChainSwitchRef:xe,onOpenNetworkPopover:wt,sourceChainLabel:at,sourceDetailsLogo:po,sourceTokenLabel:vt,amount:X,totalSourceDebitDisplay:ue,receiveAmountDisplay:ht,destTokenSymbol:et,shouldQuoteWithdrawGas:mn,estimatingFee:De,feeError:te,displayedGasFee:Mt,selectedDestToken:ve,theme:S,styles:s,dark:v,dk:B}),we&&r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[r.jsx(wn,{palette:B,label:"FEE ASSET",value:r.jsxs("select",{"aria-label":"Withdrawal fee asset",disabled:Dt,value:mt.source?mt.sourceKey(mt.source):"",onChange:Ze=>mt.setSource(mt.candidates.find(lt=>mt.sourceKey(lt)===Ze.target.value)??null),children:[!mt.candidates.length&&r.jsx("option",{value:"",children:"No eligible fee balance"}),mt.candidates.map(Ze=>r.jsxs("option",{value:mt.sourceKey(Ze),children:[Ze.displaySymbol||Ze.symbol," \xB7"," ",Ze._source==="spice"?"Spicenet":f.getChainConfig(Ze.chainId)?.displayName]},mt.sourceKey(Ze)))]})}),r.jsx(wn,{palette:B,label:"MAXIMUM FEE FUNDING",value:We.fees.isLoading?"Estimating...":We.fees.ready&&mt.source&&We.amount.sourceRequiredAmount!==null?`${A.formatUnits(We.amount.sourceRequiredAmount,mt.source.decimals)} ${mt.source.displaySymbol||mt.source.symbol}`:"Unavailable"}),(We.status.error||We.fees.error)&&r.jsx(sn,{variant:"error",size:"compact",palette:B,children:We.status.error||We.fees.error}),We.status.finalizationError&&r.jsx(f.Button,{variant:"outline",dark:v,disabled:We.status.finalizing,onClick:()=>void We.retryFinalization(),children:"Retry application update"}),We.status.statusMsg&&r.jsx("span",{role:"status",children:We.status.statusMsg})]}),Q&&!ye&&He.length===0&&r.jsx(sn,{variant:"warning",size:"compact",palette:B,children:"No withdrawal networks are available for this asset."}),Xe&&r.jsx(sn,{variant:"error",size:"compact",palette:B,fontFamily:s?.fontFamily||S.typography.fontFamily,style:{marginBottom:"12px"},children:Xe}),K&&r.jsxs(sn,{variant:"error",size:"compact",palette:B,children:["Unable to load balances. Please try again."," ",r.jsx("button",{type:"button",onClick:()=>void ze(),children:"Retry"})]}),r.jsx(f.Button,{variant:"outline",fullWidth:!0,onClick:()=>{rn&&(we?We.submitPay():qn())},disabled:Xt||Dt,theme:S,dark:v,styles:s,style:{marginTop:"8px"},children:Dt?"EXECUTING...":we&&jt?"WITHDRAWN":Qt})]})]})})}return null},Ti=wu,bu=({onDepositClick:e,onWithdrawClick:t,depositDisabled:n=!1,withdrawDisabled:s=!1,primaryColor:o="#EA4B4B",dark:a=!1})=>!e&&!t?null:r.jsxs("div",{style:{display:"flex",gap:"8px"},children:[e&&r.jsx(f.Button,{variant:"outline",onClick:e,disabled:n,dark:a,styles:{button:{backgroundColor:o}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&r.jsx(f.Button,{variant:"outline",onClick:()=>t(),disabled:s,dark:a,styles:{button:{backgroundColor:o}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),Cu=u.memo(bu),vu=({section:e,dk:t,dark:n=!1})=>{const s=o=>{switch(o){case"green":return"#10b981";case"red":return"#ef4444";default:return t.textPrimary}};return r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:t.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:e.title}),r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.items.map((o,a)=>r.jsxs("div",{role:o.onClick?"button":void 0,tabIndex:o.onClick?0:void 0,onClick:o.onClick,onKeyDown:o.onClick?i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),o.onClick?.())}:void 0,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:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[o.tokenLogoURI?r.jsx("img",{src:o.tokenLogoURI,alt:o.tokenSymbol,style:{width:"20px",height:"20px",borderRadius:"50%"}}):r.jsx("div",{style:{width:"20px",height:"20px",borderRadius:"50%",backgroundColor:n?t.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",fontWeight:600,color:t.textSecondary},children:o.tokenSymbol.charAt(0)}),r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:t.textPrimary},children:o.tokenSymbol}),r.jsx("div",{style:{fontSize:"11px",color:t.textSecondary},children:o.label})]})]}),r.jsx("div",{style:{fontSize:"13px",fontWeight:600,color:s(o.valueColor)},children:o.displayValue})]},a))})]})},ku=u.memo(vu);var Su="data:image/svg+xml,%3csvg width='11' height='11' viewBox='0 0 24 24' fill='none' stroke='black' stroke-opacity='0.5' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' xmlns='http://www.w3.org/2000/svg'%3e%3cpolyline points='17 1 21 5 17 9' /%3e%3cpath d='M3 11V9a4 4 0 0 1 4-4h14' /%3e%3cpolyline points='7 23 3 19 7 15' /%3e%3cpath d='M21 13v2a4 4 0 0 1-4 4H3' /%3e%3c/svg%3e";const Iu=({appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,showUsdSummary:a=!0,address:i,dk:l,dark:d=!1,showModeToggle:c,isEmbeddedMode:p=!0,onModeToggle:m})=>{const[h,g]=u.useState(!1),x=async()=>{i&&await f.copyToClipboard(i)&&(g(!0),setTimeout(()=>g(!1),2e3))},y=t==="active",C=n||(y?"Active":"Inactive"),w=y?"#10b981":"#9ca3af",b=r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[r.jsxs("div",{children:[r.jsx("strong",{children:"Embedded:"})," Deposit assets into ",e," account and use them here."]}),r.jsxs("div",{children:[r.jsx("strong",{children:"External:"})," Use assets from your connected wallet here."]})]});return r.jsxs("div",{children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[r.jsxs("div",{style:{fontSize:"13px",fontWeight:600,color:l.textPrimary},children:[e," Account"]}),c?r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[r.jsxs("button",{onClick:m,style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:d?l.hoverBg:"#f3f4f6",border:d?`1px solid ${l.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"11px",fontWeight:600,fontFamily:f.font.mono,color:l.textSecondary,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease",letterSpacing:"0.02em"},children:[r.jsx("span",{children:p?"Embedded":"External"}),r.jsx("img",{src:Su,alt:"","aria-hidden":"true",style:{width:"11px",height:"11px",display:"block",...d?{filter:"invert(0.65)"}:{}}})]}),r.jsx(Ta,{content:b,label:"Account mode info",textColor:d?l.textPrimary:"#f9fafb",backgroundColor:d?l.cardBg:"#111827",borderColor:d?l.cardBorder:"rgba(255,255,255,0.08)",accentColor:d?l.textSecondary:"#6b7280",children:r.jsx("img",{src:Io,alt:"","aria-hidden":"true",style:{width:"12px",height:"12px",display:"block",...d?{filter:"invert(0.65)"}:{}}})})]}):r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:d?l.hoverBg:y?"#ecfdf5":"#f3f4f6",border:d?`1px solid ${l.cardBorder}`:y?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[r.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:w}}),r.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:d?l.textSecondary:y?"#065f46":"#6b7280"},children:C})]})]}),a&&r.jsx("div",{style:{fontSize:"28px",fontWeight:700,color:l.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:f.formatUsd(s)}),a&&o&&r.jsx("div",{style:{fontSize:"12px",color:l.textSecondary,marginBottom:"8px"},children:o}),i&&r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[r.jsx("span",{style:{fontSize:"12px",fontFamily:f.font.mono,color:d?l.textSecondary:"#9ca3af"},children:f.truncateAddress(i)}),r.jsx("button",{onClick:x,style:{padding:"2px 6px",fontSize:"10px",fontWeight:500,backgroundColor:"transparent",color:d?l.textSecondary:"#9ca3af",border:"none",cursor:"pointer",borderRadius:"4px",transition:"background-color 150ms ease, color 150ms ease"},title:"Copy address",children:h?"Copied":"Copy"})]})]})},Au=u.memo(Iu),Eu=e=>`${e.tokenAddress}-${e.chainId}`,Fu=({spiceAssets:e,loading:t,dk:n,dark:s=!1,canDirectWithdraw:o=!1,onDirectWithdraw:a,directWithdrawState:i,onWithdrawClick:l})=>{const d={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},c={backgroundColor:n.cardBg,border:s?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return t?r.jsxs("div",{children:[r.jsx("div",{style:d,children:"Idle Balances"}),[1,2].map(p=>r.jsx("div",{style:{...c,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},p))]}):e.length===0?r.jsxs("div",{children:[r.jsx("div",{style:d,children:"Idle Balances"}),r.jsx("div",{style:{...c,padding:"16px",textAlign:"center",fontSize:"13px",color:s?n.textSecondary:"#9ca3af"},children:"No assets yet. Deposit to get started."})]}):r.jsxs("div",{children:[r.jsx("div",{style:d,children:"Idle Balances"}),r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map(p=>{const m=f.getChainConfig(p.chainId),h=p.chainDisplayName||m?.displayName||`Chain ${p.chainId}`,g=p.tokenDisplaySymbol||p.tokenDisplayName||p.tokenSymbol,x=Eu(p),y=p.receiptTokenId&&l,C=y||o&&p.directWithdraw&&!!a,w=!y&&i?.key===x?i:null,b=w?.step==="pending";return r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...c},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[p.logoURI?r.jsx("img",{src:p.logoURI,alt:p.tokenSymbol,style:{width:"24px",height:"24px",borderRadius:"50%"}}):r.jsx("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:s?n.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:n.textSecondary},children:g.charAt(0)}),r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:g}),r.jsx("div",{style:{fontSize:"11px",color:s?n.textSecondary:"#9ca3af"},children:h})]})]}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[r.jsxs("div",{style:{textAlign:"right"},children:[r.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:Zs({balance:BigInt(p.balance),decimals:p.tokenDecimals})}),r.jsx("div",{style:{fontSize:"11px",color:w?.step==="error"?n.errorText:s?n.textSecondary:"#9ca3af"},children:w?.step==="error"?w.message||"Withdraw failed":!Number.isFinite(p.usdValue)||p.usdValue<=0?"\u2014":`${f.formatUsd(p.usdValue)}${p.priceStatus==="stale"?" (stale)":""}`})]}),C&&r.jsx("button",{onClick:()=>{b||(y?y(p.receiptTokenId):a(p))},disabled:b,title:y?"Choose withdrawal network":"Withdraw to external wallet",style:{padding:"6px 10px",borderRadius:"6px",border:s?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",backgroundColor:s?n.hoverBg:"#ffffff",color:n.textPrimary,fontSize:"11px",fontWeight:600,cursor:b?"default":"pointer",opacity:b?.6:1,whiteSpace:"nowrap"},children:b?"Withdrawing\u2026":"Withdraw"})]})]},p.positionId??`${p.owner??""}:${p.location??""}:${p.receiptTokenId??`${p.tokenAddress}-${p.chainId}`}`)})})]})},ju=u.memo(Fu),Tu=({pendingDeposits:e,onCompleteDeposit:t,dk:n,dark:s=!1})=>e.length===0?null:r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:"Pending Deposits"}),r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((o,a)=>{const i=f.getChainConfig(o.chainId)?.displayName||`Chain ${o.chainId}`;return r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:s?n.warningBg:"#fffbeb",border:s?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"8px"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[r.jsx("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:s?n.hoverBg:"#fde68a",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:n.warningText},children:o.tokenSymbol.charAt(0)}),r.jsxs("div",{children:[r.jsxs("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:[o.amount," ",o.tokenSymbol]}),r.jsxs("div",{style:{fontSize:"11px",color:n.warningText},children:["on ",i]})]})]}),r.jsx("button",{onClick:()=>t?.(o),style:{padding:"4px 12px",fontSize:"11px",fontWeight:600,backgroundColor:s?n.hoverBg:"#fef3c7",color:s?n.textPrimary:"#92400e",border:s?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"9999px",cursor:"pointer",transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease"},children:"Complete"})]},`${o.tokenAddress}-${o.chainId}-${a}`)})})]}),Bu=u.memo(Tu),Ru=({appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,showUsdSummary:a,address:i,spiceAssets:l,spiceAssetsLoading:d,pendingDeposits:c,customSections:p,notice:m,onDepositClick:h,onWithdrawClick:g,depositDisabled:x,onCompleteDeposit:y,primaryColor:C,dk:w,dark:b=!1,showModeToggle:I,isEmbeddedMode:S,onModeToggle:v,showConnectExternalCta:B,onConnectExternalWallet:E,connectExternalError:j,showHowItWorks:N=!0,canDirectWithdraw:T,onDirectWithdraw:P,directWithdrawState:M})=>{const[D,L]=u.useState(!1);return r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[r.jsx(Au,{appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,showUsdSummary:a,address:i,dk:w,dark:b,showModeToggle:I,isEmbeddedMode:S,onModeToggle:v}),m&&r.jsx("div",{style:{padding:"10px 12px",borderRadius:"8px",backgroundColor:m.tone==="warning"?b?"rgba(245, 158, 11, 0.12)":"#fffbeb":m.tone==="success"?b?"rgba(16, 185, 129, 0.12)":"#ecfdf5":w.cardBg,border:m.tone==="warning"?b?"1px solid rgba(245, 158, 11, 0.35)":"1px solid #fde68a":m.tone==="success"?b?"1px solid rgba(16, 185, 129, 0.35)":"1px solid #a7f3d0":b?`1px solid ${w.cardBorder}`:"1px solid #e5e7eb",color:m.tone==="warning"?b?"#fbbf24":"#92400e":m.tone==="success"?b?"#34d399":"#047857":w.textSecondary,fontSize:"12px",lineHeight:1.45,fontWeight:500},children:m.message}),B&&r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[r.jsx("button",{onClick:E,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:C||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:f.font.ui,transition:"opacity 150ms ease"},children:"Connect External Wallet"}),j&&r.jsx("span",{style:{fontSize:"11px",color:b?w.errorText:"#b91c1c",lineHeight:1.4},children:j})]}),r.jsx("div",{style:{height:"1px",backgroundColor:b?"#2d2d2d":"#e5e7eb"}}),r.jsx(Cu,{onDepositClick:h,onWithdrawClick:g,depositDisabled:x,primaryColor:C,dark:b}),N&&r.jsxs("div",{children:[r.jsxs("button",{onClick:()=>L(!D),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:w.cardBg,border:b?`1px solid ${w.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:w.textSecondary,fontSize:"12px",fontWeight:500},children:[r.jsx("span",{children:"How It Works"}),r.jsx("span",{style:{transform:D?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),D&&r.jsxs("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:b?w.cardBg:"#f0fdf4",border:b?`1px solid ${w.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:b?w.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),r.jsx(Bu,{pendingDeposits:c,onCompleteDeposit:y,dk:w,dark:b}),r.jsx(ju,{spiceAssets:l,loading:d,dk:w,dark:b,canDirectWithdraw:T,onDirectWithdraw:P,directWithdrawState:M,onWithdrawClick:g}),p.map((R,U)=>r.jsx(ku,{section:R,dk:w,dark:b},U))]})},Du=u.memo(Ru);function Ou({dark:e,onSuccess:t,onError:n}){const{disconnect:s}=_t.useDisconnect(),{logout:o}=Vs.usePrivy(),[a,i]=u.useState(!1);return r.jsx(f.Button,{variant:"ghost",fullWidth:!0,dark:e,loading:a,onClick:async()=>{i(!0);try{s(),await o(),t()}catch(l){n(f.sanitizeError(l,"Unable to disconnect. Please try again."))}finally{i(!1)}},children:"Disconnect"})}const _o=380,jn=8,Nu=[],Mu={};function Bi(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function Pu(e,t){const n=new Map;Object.entries(t).forEach(([o,a])=>{if(!Number.isFinite(a)||a<=0)return;n.set(o,a),n.set(o.toUpperCase(),a);const i=Bi(o);i&&n.set(i,a)});const s=[e.symbol,e.displaySymbol,e.receiptTokenName,e.name,e.displayName];for(const o of s){if(!o)continue;const a=n.get(o)??n.get(o.toUpperCase());if(a!==void 0)return a;const i=Bi(o);if(!i)continue;const l=n.get(i);if(l!==void 0)return l}return 0}const Uu=({appName:e="Spice",status:t="active",statusLabel:n,customSections:s=Nu,extraAssets:o=[],tokenPrices:a={},tokenLogos:i=Mu,breakdownLabels:l=[],notice:d,styles:c,dark:p=!1,onDepositSuccess:m,onDepositClick:h,onWithdrawClick:g,onCompleteDeposit:x,showModeToggle:y=!1,defaultMode:C,showUsdSummary:w=!0,alwaysShowEmbeddedIdle:b=!1,showDisconnect:I=!1})=>{const S=u.useContext(f.SpiceFlowProviderContext),v=S?.mode!=="7702",B=!!S?.isWhitelistGateActive,E=!!S?.isWhitelistConfigured&&S?.isUserWhitelisted!==!0,j=u.useRef(!1);u.useEffect(()=>{if(!j.current){if(f.hasStoredSpiceFlowMode()){j.current=!0;return}C&&S?.setMode&&(S.setMode(C==="non7702"?"ondemand":"7702"),j.current=!0)}},[S,C]);const[N,T]=u.useState(!1),[P,M]=u.useState(null),[D,L]=u.useState({top:0,bottom:0,left:0,placement:"below"}),R=u.useRef(null),U=u.useRef(null),{address:X,isConnected:Y}=f.useWallet(),V=S?.embeddedWalletAddress,J=S?.externalWalletAddress,{embeddedAddress:ce}=f.useProviderWallets(),{dark:G,primaryColor:q,dk:Z}=f.useSpiceBrand(c,p),_=v&&!J,H=!v||b,F=H?V||ce:X,de=u.useMemo(()=>S?.supportedChainIds??k.getChainIdsByNetwork("mainnet"),[S?.supportedChainIds]),re=Nn({owner:H?F:J,role:"holding",sourceChains:de,additionalSourceTokens:o.filter(te=>!te.receiptTokenId&&(!te.owner||f.addressesEqual(te.owner,H?F:J))).map(te=>({address:te.tokenAddress,chainId:te.chainId,decimals:te.tokenDecimals,symbol:te.tokenSymbol,logoURI:te.logoURI})),includeRollupAssets:H,enabled:H?!!F:!!J}),xe=re.assets.filter(te=>te._source==="spice"),he=re.walletAssets,ae=re.loading,be=re.refresh,O=H?F:J,se=u.useMemo(()=>o.filter(te=>!te.owner||te.owner.toLowerCase()===O?.toLowerCase()).map(te=>({...te,owner:te.owner??O,location:te.location??(te.receiptTokenId?"rollup":H?"embedded":"external")})),[o,O,H]),W=u.useMemo(()=>he.map(te=>({owner:te.owner,location:te.location,positionId:ct(te),tokenAddress:te.address,tokenSymbol:te.symbol,tokenDecimals:te.decimals,chainId:te.chainId,chainDisplayName:f.getChainName(te.chainId),balance:te.balance.toString(),balanceFormatted:te.balanceFormatted,usdValue:te.balanceUsd||0,logoURI:te.logoURI||i[te.symbol],directWithdraw:H})),[he,se,i,H]),$=u.useMemo(()=>{const te=H?xe.map(K=>{const ze=K.balanceUsd||0,Ae=Number.isFinite(K.balanceFormatted)?K.balanceFormatted:0,Fe=Pu(K,a),Ee=K.priceStatus&&Fe>0?Fe*Ae:ze>0?ze:Fe*Ae;return{owner:K.owner,location:K.location,positionId:ct(K),tokenAddress:K.address,tokenSymbol:K.symbol,tokenDisplaySymbol:Gs(K),tokenDisplayName:dl(K),tokenDecimals:K.decimals,chainId:K.chainId,chainDisplayName:Ks(K),balance:K.balance.toString(),balanceFormatted:K.balanceFormatted,usdValue:Ee,priceStatus:Fe>0?void 0:K.priceStatus,logoURI:K.logoURI,receiptTokenId:K.receiptTokenId}}):[],Ue=K=>`${K.owner?.toLowerCase()}:${K.location}:${K.chainId}:${K.receiptTokenId??k.normalizeNativeTokenAddress(K.tokenAddress).toLowerCase()}`,me=new Map([...re.rollupAssets,...he].map(K=>[Ue({...K,tokenAddress:K.address}),K])),ye=new Map([...te,...W].map(K=>[Ue(K),K]));for(const K of _?[]:se){const ze=Ue(K),Ae=ye.get(ze);ye.set(ze,Ae?{...K,...Ae,logoURI:K.logoURI??Ae.logoURI,tokenDisplayName:K.tokenDisplayName??Ae.tokenDisplayName,tokenDisplaySymbol:K.tokenDisplaySymbol??Ae.tokenDisplaySymbol}:K)}return[...ye.values()].filter(K=>BigInt(K.balance)>0n&&ir(me.get(Ue(K))??{address:K.tokenAddress,symbol:K.tokenSymbol,displaySymbol:K.tokenDisplaySymbol},S?.allowedTokens)).sort((K,ze)=>ze.usdValue-K.usdValue)},[H,_,xe,re.rollupAssets,a,W,se,S?.allowedTokens]),oe=u.useMemo(()=>$.reduce((te,Ue)=>te+Ue.usdValue,0),[$]),{pendingDeposits:Ce,refresh:Me}=ga({chainIds:de,enabled:!!X,discoverWalletBalances:!0}),ne=u.useMemo(()=>s.reduce((te,Ue)=>te+(Ue.totalValue??0),0),[s]),Ie=oe+ne,ge=u.useMemo(()=>{const te=[];oe>0&&te.push(`${f.formatUsd(oe)} idle`);for(const Ue of s){const me=l.find(ye=>ye.sectionTitle===Ue.title)?.label||Ue.title.toLowerCase();te.push(`${f.formatUsd(Ue.totalValue??0)} ${me}`)}return te.join(" \xB7 ")},[oe,s,l]),Ye=u.useCallback(te=>{x?x(te):M(te)},[x]),tt=u.useCallback(()=>{M(null)},[]),dt=u.useCallback(()=>{M(null),m?.()},[m]),Xe=u.useCallback(()=>{if(!R.current)return;const te=R.current.getBoundingClientRect(),Ue=window.innerHeight-te.bottom-jn,me=te.top-jn,ye=Ue>=400||Ue>=me?"below":"above",K=Math.max(jn,Math.min(te.right-_o,window.innerWidth-_o-jn)),ze=ye==="below"?te.bottom+jn:te.top-jn,Ae=ye==="above"?window.innerHeight-ze:0;L({top:ze,bottom:Ae,left:K,placement:ye})},[]);u.useLayoutEffect(()=>{N&&Xe()},[N,Xe]),u.useEffect(()=>{if(!N)return;const te=ye=>{R.current&&!R.current.contains(ye.target)&&U.current&&!U.current.contains(ye.target)&&T(!1)},Ue=ye=>{ye.key==="Escape"&&T(!1)},me=()=>Xe();return document.addEventListener("mousedown",te),document.addEventListener("keydown",Ue),window.addEventListener("scroll",me,{passive:!0}),window.addEventListener("resize",Xe),()=>{document.removeEventListener("mousedown",te),document.removeEventListener("keydown",Ue),window.removeEventListener("scroll",me),window.removeEventListener("resize",Xe)}},[N,Xe]);const $e=H?V||ce||X:J||X,qe=u.useCallback(()=>{S?.setMode&&S.setMode(v?"7702":"ondemand")},[S,v]),[nt,Ve]=u.useState(null);let Re=null;try{Re=Vs.useConnectWallet({onSuccess:()=>Ve(null),onError:te=>Ve(f.sanitizeError(te,"Failed to connect wallet."))}).connectWallet}catch{Re=null}const Le=u.useCallback(()=>{Re&&(T(!1),Ve(null),Re({walletChainType:"ethereum-only"}))},[Re]),ot=!J&&!!Re,Qe=u.useCallback(()=>{T(!1),h?.()},[h]),Ge=u.useCallback(te=>{T(!1),g?.(te)},[g]),Pe=u.useCallback(te=>{T(!1),Ye(te)},[Ye]),[Te,Ke]=u.useState(null),st=H&&!!J&&!f.addressesEqual(O,J),Se=u.useCallback(te=>{const Ue=he.find(me=>me.chainId===te.chainId&&f.addressesEqual(me.address,te.tokenAddress));Ue&&(T(!1),Ke(Ue))},[he]);if(typeof window>"u")return null;const De=r.jsxs("button",{ref:R,onClick:()=>T(!N),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:G?Z.hoverBg:"#ffffff",border:G?`1px solid ${Z.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:f.font.ui,color:G?Z.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:G?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[r.jsxs("span",{children:[e," Account"]}),Y&&w&&r.jsxs("span",{style:{color:G?Z.textSecondary:"#6b7280"},children:["\xB7 ",f.formatUsd(Ie)]}),r.jsx("span",{style:{fontSize:"10px",color:G?Z.textSecondary:"#9ca3af",transform:N?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),gt=N?Hn.createPortal(r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:f.z.popover},onClick:()=>T(!1)}),r.jsxs("div",{ref:U,style:{position:"fixed",top:D.placement==="below"?`${D.top}px`:"auto",bottom:D.placement==="above"?`${D.bottom}px`:"auto",left:`${D.left}px`,width:`${_o}px`,maxWidth:`calc(100vw - ${jn*2}px)`,maxHeight:"80vh",backgroundColor:G?Z.shell:"#ffffff",border:G?`1px solid ${Z.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:G?"0 10px 40px rgba(0, 0, 0, 0.5)":"0 10px 40px rgba(0, 0, 0, 0.12)",zIndex:f.z.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${f.easing.out}`},children:[r.jsx(Du,{appName:e,status:t,statusLabel:n,totalUsdValue:Ie,breakdownSubtitle:ge,showUsdSummary:w,address:H?$e:X,spiceAssets:$,spiceAssetsLoading:ae,pendingDeposits:Ce,customSections:s,notice:d,onDepositClick:h?Qe:void 0,onWithdrawClick:g?Ge:void 0,depositDisabled:E,onCompleteDeposit:Pe,primaryColor:q,dk:Z,dark:G,showModeToggle:y,isEmbeddedMode:!v,onModeToggle:qe,showConnectExternalCta:ot,onConnectExternalWallet:Le,connectExternalError:nt,showHowItWorks:!B,canDirectWithdraw:st,onDirectWithdraw:Se}),I&&Y&&r.jsx("div",{style:{padding:"0 16px 16px"},children:r.jsx(Ou,{dark:G,onSuccess:()=>T(!1),onError:Ve})})]}),r.jsx("style",{children:`
43
+ `,Va=({title:e,showChevron:t,expanded:n,onToggleDetails:s,showClose:o,onClose:a,fontFamily:i,labelColor:l,textPrimary:d,closeHoverBg:c,closePressedBg:p})=>{const[m,h]=u.useState(!1),[g,x]=u.useState(!1);return r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"16px"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:s?"pointer":"default"},onClick:s,children:[r.jsxs("span",{style:{fontSize:"13px",fontWeight:500,color:l,fontFamily:i},children:[e," "]}),t&&r.jsx(Pn,{color:l,direction:n?"up":"down"})]}),o&&r.jsx("button",{onClick:a,onMouseEnter:()=>h(!0),onMouseLeave:()=>{h(!1),x(!1)},onMouseDown:()=>x(!0),onMouseUp:()=>x(!1),style:{background:g?p:m?c:"none",border:"none",borderRadius:"4px",cursor:"pointer",padding:"4px",display:"flex",alignItems:"center",justifyContent:"center",color:m||g?d:l,transform:g?"scale(0.9)":m?"scale(1.1)":"scale(1)",transition:f.transition.interactive},children:r.jsx(ns,{size:16})})]})},Qa=({chainName:e,bg:t,border:n,textPrimary:s,labelColor:o,primaryColor:a})=>r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"20px 16px",borderRadius:"8px",backgroundColor:t,border:`1px solid ${n}`,gap:"12px"},children:[r.jsx(f.Spinner,{size:24,borderWidth:3,color:a}),r.jsxs("div",{children:[r.jsx("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:f.font.mono,letterSpacing:"0.5px",color:s},children:"PROCESSING TRANSACTION"}),r.jsxs("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:o},children:["on ",e]})]})]}),Ga=({bg:e,border:t,left:n,right:s})=>r.jsxs("div",{style:{padding:"10px 12px",borderRadius:"6px",backgroundColor:e,border:`1px solid ${t}`,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[n,s]}),Lo=({isOpen:e,onClose:t,onComplete:n,closeOnComplete:s=!1,type:o,results:a,chainId:i,chainName:l,explorerUrl:d,theme:c,styles:p,dark:m,intentStatus:h,onRetry:g,onNewTx:x,onRetryTx:y,asOverlay:C=!0,isProcessing:w=!1,showStepBreakdown:b=!0})=>{const{theme:I,primaryColor:S,dark:v,dk:B}=f.useSpiceBrand(p,m),E=c||I,[j,N]=u.useState(!1),T=l??(i?f.getChainName(i):"Network"),P=d??(i&&f.getExplorerUrl(i,"").replace(/\/tx\/.*$/,"")||void 0),M=v?B.cardBg:"#ffffff",D=v?"0 4px 20px rgba(0, 0, 0, 0.4)":"0 4px 20px rgba(0, 0, 0, 0.1)",L=v?"0 -4px 8px -2px rgba(0, 0, 0, 0.4)":"0 -4px 8px -2px rgba(0, 0, 0, 0.15)",R=B.textSecondary,U=v?B.textPrimary:"#374151",X=v?B.inputBg:"#f9fafb",Y=v?B.inputBorder:"#e5e7eb",V=v?B.inputBg:"#f3f4f6",J=v?B.inputBorder:"#e5e7eb",[ce,G]=u.useState(!0),q=v?B.inputBg:"#f9fafb",Z=v?B.hoverBg:"#f3f4f6",_=v?{successBg:B.successBg,successBorder:B.successBorder,successText:B.successText,errorBg:B.errorBg,errorBorder:B.errorBorder,errorText:B.errorText}:{},H=h?.steps.find(ae=>ae.status==="failed")?.error;u.useEffect(()=>{!e&&!h&&N(!1)},[e,h]);const F=()=>{N(!0),setTimeout(()=>{window.dispatchEvent(new CustomEvent("tx-complete",{detail:{type:o,results:a}})),window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:{type:o,status:"success",results:a}})),n?.(),s&&t()},300)},de=()=>{G(!ce)};if(h){const{steps:ae,overallStatus:be}=h,O=be==="processing",se=be==="success",W=be==="failed",$=ae.filter(ne=>ne.transactionHash)[0],oe=ae.length>1?ae.map(ne=>ne.chainName).filter(Boolean).join(" and "):T!=="Network"?T:ae[0]?.chainName||T,Ce=P||($?f.getExplorerUrl($.chainId,$.transactionHash||"").replace(/\/tx\/.*$/,""):void 0),Me=r.jsxs(r.Fragment,{children:[r.jsx(Va,{title:O?`Processing ${o.charAt(0).toUpperCase()+o.slice(1)}`:`${o.charAt(0).toUpperCase()+o.slice(1)} results`,showChevron:b,expanded:ce,onToggleDetails:de,showClose:!O,onClose:t,fontFamily:p?.fontFamily||E.typography.fontFamily,labelColor:R,textPrimary:U,closeHoverBg:q,closePressedBg:Z}),r.jsx("div",{style:{marginBottom:"16px"},children:O?r.jsx(Qa,{chainName:oe,bg:V,border:J,textPrimary:U,labelColor:R,primaryColor:S}):r.jsx(qa,{isSuccess:se,type:o,chainName:oe,explorerUrl:Ce,txHash:$?.transactionHash,dark:v,..._,textSecondary:R})}),b&&r.jsx("div",{style:{overflow:"hidden",maxHeight:ce?"300px":"0px",opacity:ce?1:0,transition:"max-height 0.3s ease, opacity 0.3s ease",marginBottom:ce?"16px":"0"},children:r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:ae.map((ne,Ie)=>{const ge=ne.transactionHash?f.getExplorerUrl(ne.chainId,ne.transactionHash):null;return r.jsx(Ga,{bg:X,border:Y,left:r.jsx("span",{style:{fontSize:"13px",color:U},children:ne.chainName?`On ${ne.chainName}`:ne.description||`Step ${Ie+1}`}),right:r.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:ne.status==="success"?"#10b981":ne.status==="failed"?"#ef4444":R,fontWeight:500},children:[ge&&r.jsx("a",{href:ge,target:"_blank",rel:"noopener noreferrer",style:{color:v?B.infoText:"#2563eb",textDecoration:"none"},onClick:Ye=>Ye.stopPropagation(),children:"View"}),ne.status==="success"?"\u2713":ne.status==="failed"?"\u2717":"\u25CB"]})},Ie)})})}),!O&&r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[W&&g&&r.jsx(f.Button,{variant:"outline",fullWidth:!0,onClick:g,theme:E,styles:p,dark:v,children:"TRY AGAIN"}),x&&r.jsxs(f.Button,{variant:"outline",fullWidth:!0,onClick:x,theme:E,styles:p,dark:v,children:["NEW ",o.toUpperCase()," \u2192"]})]})]});return C?r.jsxs("div",{style:{position:"absolute",bottom:0,left:0,right:0,zIndex:10,animation:j?"slideDown 0.3s ease-in forwards":"slideUp 0.3s ease-out forwards",pointerEvents:"auto"},children:[r.jsx("div",{style:{backgroundColor:M,borderRadius:"12px 12px 0 0",width:"100%",padding:"18px 24px 24px",boxShadow:L},children:Me}),r.jsx("style",{children:Ha})]}):r.jsx("div",{style:{backgroundColor:M,borderRadius:"12px",padding:"24px",width:"100%",boxShadow:D},children:Me})}if(!e&&!w||!w&&(!a||a.length===0))return null;const re=a?a.every(ae=>ae.success):!1,xe=a?.[0],he=[...a??[]].reverse().find(ae=>ae.txHash)?.txHash||xe?.txHash;return r.jsxs("div",{style:{position:C?"absolute":"relative",bottom:C?0:void 0,left:C?0:void 0,right:C?0:void 0,zIndex:C?10:void 0,animation:C?j?"slideDown 0.3s ease-in forwards":"slideUp 0.3s ease-out forwards":void 0,pointerEvents:"auto",width:"100%"},children:[r.jsx("div",{style:{backgroundColor:M,borderRadius:C?"12px 12px 0 0":"12px",width:"100%",padding:"18px 0 24px",boxShadow:C?L:D},children:r.jsxs("div",{style:{width:"100%",boxSizing:"border-box",padding:"0 24px"},children:[r.jsx(Va,{title:w?`Processing ${o.charAt(0).toUpperCase()+o.slice(1)}`:`${o.charAt(0).toUpperCase()+o.slice(1)} results`,showChevron:!w&&b,expanded:ce,onToggleDetails:w?void 0:de,showClose:!w,onClose:t,fontFamily:p?.fontFamily||E.typography.fontFamily,labelColor:R,textPrimary:U,closeHoverBg:q,closePressedBg:Z}),r.jsx("div",{style:{marginBottom:"16px",animation:"statusFadeIn 220ms cubic-bezier(0.22, 1, 0.36, 1) both"},children:w?r.jsx(Qa,{chainName:T,bg:V,border:J,textPrimary:U,labelColor:R,primaryColor:S}):r.jsx(qa,{isSuccess:re,type:o,chainName:T,explorerUrl:P,txHash:he,dark:v,..._,textSecondary:R})},w?"processing":re?"success":"error"),!w&&b&&a&&a.length>1&&r.jsx("div",{style:{overflow:"hidden",maxHeight:ce?"200px":"0px",opacity:ce?1:0,transition:"max-height 0.3s ease, opacity 0.3s ease",marginBottom:ce?"16px":"0"},children:r.jsx("div",{style:{maxHeight:"180px",overflowY:"auto",display:"flex",flexDirection:"column",gap:"8px"},children:a.map((ae,be)=>r.jsx(Ga,{bg:X,border:Y,left:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[r.jsx("span",{style:{fontWeight:600,fontSize:"13px",color:B.textPrimary,fontFamily:f.font.mono},children:ae.asset.symbol}),ae.amount&&r.jsx("span",{style:{fontSize:"12px",color:R},children:ae.amount})]}),right:r.jsx("span",{style:{fontSize:"12px",color:ae.success?"#10b981":"#ef4444",fontWeight:500},children:ae.success?"\u2713":"\u2717"})},be))})}),!w&&!re&&a&&r.jsx("div",{style:{padding:"12px",backgroundColor:B.errorBg,border:`1px solid ${B.errorBorder}`,borderRadius:"8px",marginBottom:"16px"},children:r.jsx("p",{style:{fontSize:"13px",color:B.errorText,margin:0,lineHeight:1.5},children:H||a.find(ae=>!ae.success)?.error||`${o.charAt(0).toUpperCase()+o.slice(1)} failed. Please try again.`})}),!w&&r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[!re&&y&&r.jsxs(f.Button,{variant:"outline",fullWidth:!0,onClick:y,theme:E,styles:p,dark:v,children:["TRY AGAIN ",o.toUpperCase()]}),re&&r.jsx(f.Button,{variant:"outline",fullWidth:!0,onClick:F,theme:E,styles:p,dark:v,children:"DONE"})]})]})}),r.jsx("style",{children:Ha})]})};function Ka(e){const t=new Set(k.getEquivalentAddresses(e).map(n=>n.toLowerCase()));return t.add(e.toLowerCase()),t}const gd=["USDC","USDT","WETH","WBTC"];function Za(e,t){const n=f.getChainConfig(t);if(!n)return;if(n.nativeCurrency.symbol.toUpperCase()===e.toUpperCase())return{address:k.ZERO_ADDRESS,symbol:n.nativeCurrency.symbol,decimals:n.nativeCurrency.decimals,chainId:t};const s=n.supportedTokens?.find(o=>o.symbol.toUpperCase()===e.toUpperCase());if(s)return{address:s.address.toLowerCase(),symbol:s.symbol,decimals:s.decimals,chainId:t}}function un(e,t,n){const s=f.getChainConfig(t);if(!s)return;if(n!==void 0){if(k.isNativeToken(e)&&!k.getTokenByAddress(e,n))return;const i=lo(e,n,t);return i?{address:i.address.toLowerCase(),symbol:i.symbol,decimals:i.decimals,chainId:t}:void 0}if(k.isNativeToken(e))return;const o=Ka(e),a=s.supportedTokens?.find(i=>o.has(i.address.toLowerCase()));if(a)return{address:a.address.toLowerCase(),symbol:a.symbol,decimals:a.decimals,chainId:t}}function xd(e){const{sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:o,intermediaryCandidates:a=gd}=e;if(vs(t,n))return{strategy:"direct",sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:o,summary:`${t.symbol} fronted directly`};if(s===o&&(k.isNativeToken(t.address)||!k.getTokenByAddress(t.address,s)))return{strategy:"direct-swap",sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:o,summary:`${t.symbol} \u2192 ${n.symbol} on chain ${s}, no escrow`};if(un(t.address,o,s))return{strategy:"direct",sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:o,summary:`${t.symbol} fronted on destination, swapped to ${n.symbol}`};if(un(n.address,s,o))return{strategy:"source-swap",sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:o,summary:`${t.symbol} \u2192 ${n.symbol} on source chain, then fronted`};for(const i of a){const l=Za(i,s);if(!l||vs(t,l)||vs(n,l))continue;const d=Za(i,o);if(d&&vs(l,d))return{strategy:"intermediary",sourceAsset:t,outputAsset:n,intermediaryAsset:d,sourceChainId:s,destinationChainId:o,summary:`${t.symbol} \u2192 ${i} on source, fronted, then ${i} \u2192 ${n.symbol} on destination`}}throw new f.SpiceflowError("ROUTE_STRATEGY_ERROR",`No viable cross-chain route found from ${t.symbol} (chain ${s}) to ${n.symbol} (chain ${o}). No intermediary asset is available on both chains.`,{sourceAsset:t.symbol,outputAsset:n.symbol,sourceChainId:s,destinationChainId:o,candidatesChecked:a})}async function yd(e){const{route:t,sourceAmount:n,userAddress:s,registry:o,actionCalls:a,slippage:i}=e;async function l(d,c,p,m){const h=await o.resolveSwap({type:"swap",tokenIn:c,tokenOut:p,amountIn:m,maxSlippage:i},d,s);if(!h)throw new f.SpiceflowError("NO_LIQUIDITY",`No venue returned a quote for ${c} \u2192 ${p} on chain ${d}. No liquidity available for this pair.`,{chainId:d,tokenIn:c,tokenOut:p,amountIn:m.toString()});return h}switch(t.strategy){case"direct-swap":{const d=await l(t.destinationChainId,t.sourceAsset.address,t.outputAsset.address,n);return{chainBatches:[{chainId:t.destinationChainId,calls:[...d.calls,...a]}],solverFrontToken:t.outputAsset,solverFrontAmount:0n,resolvedSwaps:{sourceSwap:d}}}case"direct":{const d=un(t.sourceAsset.address,t.destinationChainId,t.sourceChainId)||t.sourceAsset;if(Ka(d.address).has(t.outputAsset.address.toLowerCase()))return{chainBatches:[{chainId:t.destinationChainId,calls:a}],solverFrontToken:d,solverFrontAmount:n,resolvedSwaps:{}};const c=await l(t.destinationChainId,d.address,t.outputAsset.address,n);return{chainBatches:[{chainId:t.destinationChainId,calls:[...c.calls,...a]}],solverFrontToken:d,solverFrontAmount:n,resolvedSwaps:{destinationSwap:c}}}case"source-swap":{const d=un(t.outputAsset.address,t.sourceChainId,t.destinationChainId);if(!d)throw new f.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Output asset ${t.outputAsset.symbol} (${t.outputAsset.address}) not found on source chain ${t.sourceChainId}`,{token:t.outputAsset.symbol,address:t.outputAsset.address,chainId:t.sourceChainId,side:"source"});const c=un(t.outputAsset.address,t.destinationChainId,t.destinationChainId);if(!c)throw new f.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Output asset ${t.outputAsset.symbol} (${t.outputAsset.address}) not found on destination chain ${t.destinationChainId}`,{token:t.outputAsset.symbol,address:t.outputAsset.address,chainId:t.destinationChainId,side:"destination"});const p=await l(t.sourceChainId,t.sourceAsset.address,d.address,n);return{chainBatches:[{chainId:t.sourceChainId,calls:p.calls},{chainId:t.destinationChainId,calls:a}],solverFrontToken:c,solverFrontAmount:p.amountOutMinimum,resolvedSwaps:{sourceSwap:p}}}case"intermediary":{if(!t.intermediaryAsset)throw new f.SpiceflowError("ROUTE_STRATEGY_ERROR","Intermediary strategy requires an intermediary asset but none was provided in the route plan.",{strategy:t.strategy});const d=un(t.intermediaryAsset.address,t.sourceChainId,t.destinationChainId);if(!d)throw new f.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Intermediary ${t.intermediaryAsset.symbol} (${t.intermediaryAsset.address}) not found on source chain ${t.sourceChainId}`,{token:t.intermediaryAsset.symbol,address:t.intermediaryAsset.address,chainId:t.sourceChainId,side:"source"});const c=await l(t.sourceChainId,t.sourceAsset.address,d.address,n),p=await l(t.destinationChainId,t.intermediaryAsset.address,t.outputAsset.address,c.amountOutMinimum);return{chainBatches:[{chainId:t.sourceChainId,calls:c.calls},{chainId:t.destinationChainId,calls:[...p.calls,...a]}],solverFrontToken:t.intermediaryAsset,solverFrontAmount:c.amountOutMinimum,resolvedSwaps:{sourceSwap:c,destinationSwap:p}}}default:throw new f.SpiceflowError("ROUTE_STRATEGY_ERROR",`Unknown route strategy: ${t.strategy}`,{strategy:t.strategy})}}function wd(e,t,n){if(!e||!t)return null;const s=Dn(e,t),o=Object.entries(e.chainTokens??{}).flatMap(([m,h])=>{const g=cn(m);return g?.chainId===t?[{parsed:g,detail:h}]:[]}),a=m=>n.find(h=>f.addressesEqual(h.address,m))??null,i=m=>{const h=o.find(({parsed:y})=>f.addressesEqual(y.address,m));if(!h)return null;const g=f.getChainConfig(t);if(k.isNativeToken(m))return g?{address:k.ZERO_ADDRESS,symbol:g.nativeCurrency.symbol,name:g.nativeCurrency.name,decimals:g.nativeCurrency.decimals,logoURI:e.logoURI}:null;const x=g?.supportedTokens?.find(y=>f.addressesEqual(y.address,m));return!x||!io(e,m,t)?null:{address:h.parsed.address,symbol:x.symbol,name:x.name||h.detail?.name||e.displayName||e.name||e.symbol,decimals:x.decimals,logoURI:x.logo||e.logoURI}},l=o.map(({parsed:m})=>m.address).filter(k.isNativeToken);for(const m of[...s,...l]){if(k.isNativeToken(m)){const x=i(m);if(x)return x}const h=a(m);if(h)return h;const g=i(m);if(g)return g}if(e.chainTokens||e.receiptTokenId)return null;const d=Wt(e,t);if(d){const m=a(d);if(m)return m}const c=un(e.address,t,e.chainId);return c?a(c.address)||(n.length>0?null:{address:c.address,symbol:c.symbol||e.symbol,name:e.displayName||e.name||e.symbol,decimals:c.decimals??e.decimals,logoURI:e.logoURI}):null}function bd(e){const t=e.find(n=>k.isSpicenetChainId(n.chainId))?.calls?.[0]?.data;if(!t)return null;try{const n=A.decodeFunctionData({abi:k.spicenetAbi,data:t});return n.functionName!=="createWithdrawalRequest"?null:n.args[0].transfers.map(s=>({token:s.token,recipient:s.to,amount:s.amount}))}catch{return null}}function Cd(e,t){return!e||e.length!==t.length?!1:e.every((n,s)=>{const o=t[s];return n.token.toLowerCase()!==o.token.toLowerCase()||n.recipient.toLowerCase()!==o.recipient.toLowerCase()?!1:n.recipient.toLowerCase()===k.SPICE_GAS_FEE_RECIPIENT.toLowerCase()?Sn(n.amount,o.amount,100n):n.amount===o.amount})}function vd(e,t){const n=e.intents.flatMap(a=>a.batches).filter(a=>{const i=nn(a);return BigInt(a.quotedAmount)>0n||BigInt(a.totalDebit)>0n||i.totalFee>0n}),s=n.filter(a=>a.chainId===t),o=s.length>0?s:n;return o.length===1?o[0]:null}function kd(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const s=n.token.toLowerCase(),o=n.recipient.toLowerCase(),a=`${s}:${o}`,i=t.get(a);i?i.amount+=n.amount:t.set(a,{...n})}return[...t.values()]}function Ya(e,t){if(!e.token||!e.recipient||e.chainId===null)return null;const n=vd(t,e.chainId);if(!n)return null;const{gasFee:s,bridgeFee:o,spicenetFee:a}=nn(n),i=s+o,l=[{token:e.token.address,recipient:e.recipient,amount:e.receiveAmountRaw}];return i>0n&&l.push({token:e.token.address,recipient:k.SPICE_GAS_FEE_RECIPIENT,amount:i}),a>0n&&l.push({token:e.token.address,recipient:k.SPICE_PLATFORM_FEE_RECIPIENT,amount:a}),kd(l)}function Sd(e,t,n){const s=Ya(e,t);return!s||Cd(bd(n),s)?null:e.buildWithdrawBatches(s)}async function Xa(e){if(!(!e.batches.length||!e.walletAddress||!e.recipient)){e.ui.setIsExecuting(!0),e.ui.setExecutionError(null),e.ui.setExecutionProgress(null),e.executionContextRef.current=null,e.ui.setLockedGasFee(e.gasFee);try{let t=e.batches;if(e.isNon7702&&e.onWithdrawExecute)await e.onWithdrawExecute(e.amount);else{if(!e.isNon7702&&!t.some(o=>k.isSpicenetChainId(o.chainId)))throw new Error("Spice withdrawals must include a Spicenet funding batch before the destination chain batch.");const n=e.token?.address||"",s={useCustomTransfers:!0};if(e.buildSpicenetBatch){const o=e.feeEstimate??await e.execution.estimate(t,n,0n,s),a=Ya(e,o);a&&(t=e.buildWithdrawBatches(a));const i=o.intents[0]?.batches.find(l=>l.chainId===e.chainId)??o.intents[0]?.batches[0]??null;i&&e.ui.setLockedGasFee(nn(i).totalFee)}else{const o=(e.feeEstimate??await e.execution.estimate(t,n,0n,s)).intents[0]?.batches[0]??null;o&&e.ui.setLockedGasFee(nn(o).totalFee)}await e.execution.execute(t,n,0n,o=>{o.actionId&&o.intentId&&typeof o.intentIndex=="number"&&typeof o.totalSteps=="number"&&(e.executionContextRef.current={actionId:o.actionId,intentId:o.intentId,intentIndex:o.intentIndex,totalSteps:o.totalSteps}),e.ui.setExecutionProgress(o)},void 0,e.buildSpicenetBatch?{...s,adjustBatchesForEstimate:({feeEstimate:o,chainBatches:a})=>Sd(e,o,a)}:{...s,skipPreSubmitFeeEstimate:!0})}Ja(e)}catch(t){const n=t instanceof Error?t.message:"Withdraw failed";e.ui.setExecutionError(n)}finally{e.ui.setIsExecuting(!1)}}}function Ja(e){window.dispatchEvent(new CustomEvent("withdraw-completed")),e.onWithdrawSuccess?.({token:e.token?.symbol||"",amount:e.amount,chainId:e.chainId})}async function Id(e){const t=e.executionContextRef.current;if(!t){e.ui.setExecutionProgress(null),await Xa(e);return}e.ui.setIsExecuting(!0),e.ui.setExecutionError(null),e.ui.setExecutionProgress({step:"executing",message:"Resuming existing action...",actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps});try{let n=t.totalSteps;for(let s=0;s<t.totalSteps;s++)if((await f.relayerService.checkStepStatus(t.intentId,s)).data.status!=="success"){n=s;break}if(n>=t.totalSteps)e.ui.setExecutionProgress(s=>({...s||{step:"success",message:"Transaction successful!",actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps},step:"success",message:"Transaction successful!"}));else for(let s=n;s<t.totalSteps;s++){const o=await Sa({actionId:t.actionId,intentIndex:t.intentIndex,intentId:t.intentId,stepIndex:s,chainId:e.chainId??void 0,onStatusMessage:(a,i)=>{e.isMountedRef.current&&e.ui.setExecutionProgress({step:"executing",message:a,txHash:i,actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps})}});if(!e.isMountedRef.current)return;e.ui.setExecutionProgress({step:s===t.totalSteps-1?"success":"executing",message:s===t.totalSteps-1?"Transaction successful!":"Executing remaining steps...",txHash:o,actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps})}Ja(e)}catch(n){const s=n instanceof Error?n.message:"Withdraw failed";e.ui.setExecutionError(s)}finally{e.ui.setIsExecuting(!1)}}async function Ad(e){const t=await e.estimate(e.batches,e.tokenAddress,0n,{useCustomTransfers:!0,signal:e.signal}),n=t.intents.flatMap(o=>o.batches).filter(o=>nn(o).totalFee>0n),s=n.filter(o=>o.chainId===e.chainId)[0]??n[0]??t.intents[0]?.batches[0];if(!s)throw new Error("No gas fee estimate was returned for this withdraw.");return{gasFee:nn(s).totalFee,feeEstimate:t}}function zo(e,t){return A.formatUnits(e,t).replace(/(\.\d*?[1-9])0+$|\.0+$/,"$1")}function $a(e,t,n){return Pt(e,t,n,"floor")}function _a(e,t,n=!1){if(e<=0)return"$0";if(!t||!Number.isFinite(t)||t<=0)return"\u2014";const s=e*t;return`$${s>=1?s.toFixed(3).replace(/0+$/,"").replace(/\.$/,""):s.toFixed(4).replace(/0+$/,"").replace(/\.$/,"")}${n?" (stale)":""}`}function Ed(e,t){return t?JSON.stringify({tokenAddress:t.toLowerCase(),batches:e.map(n=>({chainId:n.chainId,calls:n.calls.map(s=>({to:s.to.toLowerCase(),value:s.value.toString(),data:s.data})),tokenTransfers:(n.tokenTransfers??[]).map(s=>({from:s.from,to:s.to.toLowerCase(),token:s.token.toLowerCase(),amount:s.amount.toString()}))}))}):null}function ei(e,t,n){const s=n.filter(o=>o.amount>0n);return{chainId:e,domain:"evm",tokenTransfers:[],calls:k.isNativeToken(t)?s.map(o=>({to:o.recipient,value:o.amount,data:"0x"})):s.map(o=>({to:t,value:0n,data:A.encodeFunctionData({abi:A.erc20Abi,functionName:"transfer",args:[o.recipient,o.amount]})}))}}new Set([k.SPICE_GAS_FEE_RECIPIENT,k.SPICE_PLATFORM_FEE_RECIPIENT].map(e=>e.toLowerCase()));function Fd(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const s=A.getAddress(n.token),o=A.getAddress(n.to),a=`${s.toLowerCase()}:${o.toLowerCase()}`,i=t.get(a);i?i.amount+=n.amount:t.set(a,{token:s,to:o,amount:n.amount})}return[...t.values()]}function jd(e,t){return`0x${t}${e.slice(4)}`}function ti(e,t,n,s){if(e.some(p=>p.domain==="spicenet"))return e;const o=n?.intents.flatMap(p=>p.batches),a=p=>p.from==="escrow",i=e.map(p=>{const m=o?.find(E=>E.chainId===p.chainId);if(!m)return p;const h=nn(m),g=h.totalFee;if(g<=0n)return p;const x=(p.tokenTransfers??[]).filter(E=>a(E)&&A.getAddress(E.to).toLowerCase()===t.toLowerCase()),y=x.find(E=>!k.isNativeToken(A.getAddress(E.token)))??x[0];if(!y)return p;const C=A.getAddress(y.token),w=k.isNativeToken(C);let b=!1;const I=(p.tokenTransfers??[]).map(E=>b||!a(E)||A.getAddress(E.to).toLowerCase()!==t.toLowerCase()||A.getAddress(E.token).toLowerCase()!==C.toLowerCase()?E:(b=!0,{...E,amount:s?.payoutAlreadyGross?BigInt(E.amount):BigInt(E.amount)+g}));if(!b)return p;const S=(E,j)=>w?{to:E,value:j,data:"0x"}:{to:C,value:0n,data:A.encodeFunctionData({abi:A.erc20Abi,functionName:"transfer",args:[E,j]})},v=[];h.spicenetFee>0n&&v.push(S(k.SPICE_PLATFORM_FEE_RECIPIENT,h.spicenetFee));const B=h.gasFee+h.bridgeFee;return B>0n&&v.push(S(k.SPICE_GAS_FEE_RECIPIENT,B)),{...p,tokenTransfers:I,calls:[...v,...p.calls]}}),l=i.flatMap(p=>(p.tokenTransfers??[]).filter(a).map(m=>{const h=A.getAddress(m.token),g=A.getAddress(m.to),x=[{token:h,to:g,amount:BigInt(m.amount)}];return{chainId:p.chainId,transfers:Fd(x)}}));if(l.length===0)return e;const d=s?.requestTimestampMs??Date.now(),c=BigInt(Math.floor(d/1e3))+3600n;return[{chainId:k.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:l.map((p,m)=>{const h=A.keccak256(A.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,p.transfers[0].token,p.transfers.reduce((x,y)=>x+y.amount,0n),BigInt(p.chainId),BigInt(d+m)])),g=jd(h,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:A.encodeFunctionData({abi:k.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${p.chainId}`,idempotenceKey:g,nbf:0n,exp:c,metadata:"{}",transfers:p.transfers.map(x=>({token:x.token.toLowerCase(),to:x.to,amount:x.amount}))}]})}})},...i]}function En(e,t,n,s){const o=e.filter(i=>i.domain!=="spicenet"),a=i=>(i.tokenTransfers??[]).some(l=>l.from==="escrow");return[...o.filter(i=>!a(i)),...ti(o.filter(a),t,n,s)]}function qo(e,t,n,s,o){const a=e[e.length-1];if(!a?.calls.length||a.domain==="spicenet")throw new Error("Proceeds fees require a final destination action");const i=[{to:k.SPICE_PLATFORM_FEE_RECIPIENT,amount:o},{to:k.SPICE_GAS_FEE_RECIPIENT,amount:s}].filter(l=>l.amount>0n);return e.map(l=>l===a?{...l,calls:[...l.calls,...i.map(d=>({to:n,value:0n,data:A.encodeFunctionData({abi:A.erc20Abi,functionName:"transfer",args:[d.to,d.amount]})}))],tokenTransfers:[...l.tokenTransfers??[],...i.map(d=>({from:t,to:d.to,token:n,amount:d.amount}))]}:l)}async function ni(e,t,n,s,o){const a=k.hashChainBatches(e),i=await f.relayerService.estimateBatchGas({user:t,outputToken:n,signal:s,requireSimulation:!0,includePlatformFee:o!==void 0,chainBatches:e.map((l,d)=>({...l,hash:a[d].hash}))});if(i.gasQuoteSource!=="estimated"||!i.simulationVerified)throw new Error("Action proceeds require a successful live batch simulation; fallback gas pricing is not sufficient");if(o!==void 0&&(i.platformFee===void 0||i.platformFee>o))throw new Error("Fee conversion platform price changed; refresh before retrying");return i.gasFee}async function Td(e){if(e.proceeds.token.toLowerCase()!==e.token.toLowerCase())throw new Error("Action proceeds must use the destination fee token");const t=await e.proceeds.resolve(e.signal);if(e.signal?.aborted)throw new Error("Action proceeds quote was cancelled");if(t<0n)throw new Error("Action proceeds cannot be negative");const n=await e.baseline();if(!n?.feeEstimate)throw new Error("Action fee quote is unavailable");let s=n.preview.gasFee;const o=n.preview.spicenetFee,a=n.preview.bridgeFee??0n;for(let i=0;i<5;i++){const l=s+o+a,d=t<l?t:l,c=l-d,p=c>0n?(c*110n+99n)/100n+2n:0n;let m=p,h;const g=En(await e.buildBatches(p,{onSourceSpend:C=>{m=C},onActionCalls:C=>{h=C}}),e.owner),x=qo(g,e.owner,e.token,s+a,o),y=await ni(x,e.owner,e.token,e.signal);if(y===s)return{preview:{...n.preview,grossAmount:p,netAmount:0n,gasFee:s,totalFee:l,gasQuoteSource:"estimated"},feeEstimate:n.feeEstimate,grossFundingAmount:p,proceedsAvailable:t,proceedsUsed:d,fundingBatches:x,sourceSpendCap:m,destinationAmount:0n,actionDefinition:h};s=y}throw new Error("Action proceeds fee estimate did not converge")}function si(e,t){let n,s;if(k.isNativeToken(t)){if(e.data!=="0x")return null;n=e.to,s=e.value}else{if(!f.addressesEqual(e.to,t))return null;try{const o=A.decodeFunctionData({abi:A.erc20Abi,data:e.data});if(o.functionName!=="transfer")return null;[n,s]=o.args}catch{return null}}return f.addressesEqual(n,k.SPICE_GAS_FEE_RECIPIENT)?{gas:s,platform:0n}:f.addressesEqual(n,k.SPICE_PLATFORM_FEE_RECIPIENT)?{gas:0n,platform:s}:null}function Ps(e,t,n){return e.map(s=>s.chainId===t?{...s,calls:s.calls.filter(o=>!si(o,n))}:s)}function Bd(e,t,n){if(!e.feeOnlyAction)return{};const s=e.embeddedWalletAddress??e.providerEmbeddedAddress;if(e.actionProceeds||e.feeQuote?.fundingConversion){const l=e.feeQuote?.fundingConversion,d=e.actionProceeds??{token:t,resolve:async()=>0n},c=e.feeQuote?.preview,p=e.feeQuote?.proceedsUsed,m=l?.fromProceeds?l.tokenIn:t;if(!c||p===void 0||d.token.toLowerCase()!==m.toLowerCase())throw new Error("Refresh the action proceeds quote");const h=c.gasFee+(c.bridgeFee??0n),g=c.spicenetFee,x=async()=>{e.validateFeeQuote?.();const C=await d.resolve(e.signal);if(e.validateFeeQuote?.(),e.signal?.aborted||(l?.fromProceeds?C<l.amountInMax||l.amountOut<h+g:C<p||C+(l?.amountOut??n)<h+g))throw new Error("Action proceeds changed; refresh before retrying");return l?.fromProceeds?[{chainId:e.resolvedChainId,token:l.tokenIn,amount:l.amountInMax},{chainId:e.resolvedChainId,token:t,amount:l.amountOut}]:[{chainId:e.resolvedChainId,token:t,amount:p+(l?.amountOut??0n)}]},y=async C=>{await x();const w=await ni(C,s,t,e.signal,l?g:void 0);if(await x(),(w>c.gasFee?w-c.gasFee:c.gasFee-w)*100n>w*15n)throw new Error("Action gas quote changed; refresh before retrying")};return{resolveActionOutputCredits:x,prepareForSigning:async C=>{const w=Ps(C,e.resolvedChainId,t).map(I=>({...I,tokenTransfers:I.tokenTransfers?.filter(S=>!(typeof S.from=="string"&&f.addressesEqual(S.from,s)&&(f.addressesEqual(S.to,k.SPICE_GAS_FEE_RECIPIENT)||f.addressesEqual(S.to,k.SPICE_PLATFORM_FEE_RECIPIENT))))})),b=qo(w,s,t,h,g);return await y(b),b},validateBeforeSubmit:y}}const o=k.getTokenByAddress(t,e.resolvedChainId),a={chainId:e.resolvedChainId,tokenAddress:t,symbol:o?.symbol??e.destinationToken.symbol,decimals:e.executionTokenDecimals??o?.decimals??e.destinationToken.decimals},i=async l=>{e.validateFeeQuote?.();const d=Ps(l,e.resolvedChainId,t),c=await e.execution.estimate(d,t,n,{userOverride:s,useCustomTransfers:!0,feeExecutionMode:"backend-transfer"});e.validateFeeQuote?.();const p=In(c,a);if(!p||p.chainId!==e.resolvedChainId)throw new Error("The fee service did not return the destination action's fee quote");if(p.gasFee+p.spicenetFee+(p.bridgeFee??0n)+2n>n)throw new Error("Fees exceed the displayed maximum funding; refresh the quote before retrying");return{raw:d,feeEstimate:c,fees:p}};return{prepareForSigning:async l=>{const{raw:d,feeEstimate:c}=await i(l);return En(d,s,c,{payoutAlreadyGross:!0})},validateBeforeSubmit:async l=>{const{fees:d}=await i(l);let c=0n,p=0n;for(const h of l)if(h.chainId===e.resolvedChainId)for(const g of h.calls){const x=si(g,t);x&&(c+=x.gas,p+=x.platform)}if(c+p+2n>n)throw new Error("Signed fees exceed the displayed maximum funding");const m=d.gasFee+(d.bridgeFee??0n);if((c>m?c-m:m-c)*100n>m*15n||p!==d.spicenetFee)throw new Error("The signed gas quote changed materially; refresh before retrying")}}}const Rd="0xa9059cbb";function os(e,t,n){return k.isNativeToken(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:A.encodeFunctionData({abi:A.erc20Abi,functionName:"transfer",args:[n,t]})}}function oi(e,t,n){return{chainId:n,calls:[os(e,t,k.getEscrowContractAddress(n))]}}function Dd(e,t,n,s){const o=t.source.chainId;return{chainId:o,calls:[...e.calls,os(t.source.address,n,k.getEscrowContractAddress(o)),...s>0n?[os(t.source.address,s,k.SPICE_GAS_FEE_RECIPIENT)]:[]]}}function ri(e,t){const n=e.amountOutMinimum-t;if(n<=0n)throw new Error("Amount is too small to cover fees. Increase the amount and retry.");return n}function ai(e,t,n){return e?.asset?._source==="wallet"&&e?.asset.chainId===n}function ii(e){return e.isNative||k.isNativeToken(e.address)?!0:!k.getTokenByAddress(e.address,e.chainId)}function li(e,t,n,s){return t!=="user-transfer"||!n||e.length===0||e[0]?.to.toLowerCase()!==s.toLowerCase()||!e[0]?.data.startsWith(Rd)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function rs(e,t,n,s){if(!t)return[e];const o=await t({...n,requestTimestampMs:s});return o?[o,e]:[e]}function Od(e){return e.filter(t=>t.domain!=="spicenet")}function as(e,t){const n=(e.tokenTransfers??[]).filter(s=>s.from==="escrow").map(s=>({token:k.normalizeNativeTokenAddress(s.token),recipient:s.to,amount:BigInt(s.amount)})).filter(s=>s.amount>0n);return t!==void 0&&n.length===1&&(n[0]={...n[0],amount:t}),n.length>0?n:void 0}function Wn(e,t,n){return Pt(e,t,n,"ceil")}function ci(e){const t=e.selectedAsset?.asset;return e.isPayMode&&!!t&&t._source==="wallet"&&t.chainId!==e.resolvedChainId&&!!e.pivot}function Ho(e){const t=e.selectedAsset?.asset;return!e.isPayMode&&!!t&&t._source==="wallet"&&t.chainId!==e.resolvedChainId&&!!e.sourceSwap&&!!e.pivot}function Us(e,t){if(t?.sourceSpendCap!==void 0&&e>t.sourceSpendCap)throw new Error("The source amount increased. Review the updated quote before submitting.");t?.onSourceSpend?.(e)}async function di(e,t,n){let s;const o=await e({...t,buildActionCalls:async(a,i)=>{s=a;const l=await t.buildActionCalls(a,i);return n?.onActionCalls?.({amount:a,context:i,calls:l}),l}},n);if(s!==void 0){if(n?.minimumDestinationAmount!==void 0&&s<n.minimumDestinationAmount)throw new Error("The destination amount decreased. Review the refreshed quote before submitting.");n?.onDestinationAmount?.(s)}return o}const Vo=(e,t)=>di(Nd,e,t),Ws=async(e,t)=>{const n=await di(Md,e,t),s=t?.actionContextOverride?.feeBreakdown,o=n[n.length-1];if(e.feeExecutionMode!=="user-transfer"||!s||!o)return n;const a=e.needsSwap&&e.resolvedTokenIn?e.resolvedTokenIn:e.destinationToken.address,[i]=Ps([o],e.resolvedChainId,a),l=ei(e.resolvedChainId,a,[{recipient:k.SPICE_PLATFORM_FEE_RECIPIENT,amount:s.spicenetFee},{recipient:k.SPICE_GAS_FEE_RECIPIENT,amount:s.gasFee+(s.bridgeFee??0n)}]).calls,d=o.calls.filter(c=>!i.calls.includes(c));return d.length===l.length&&l.every(c=>d.some(p=>p.to.toLowerCase()===c.to.toLowerCase()&&p.value===c.value&&p.data===c.data))?n:[...n.slice(0,-1),{...i,calls:[...l,...i.calls]}]};async function Nd(e,t){const{currentPaymentAmount:n,destinationToken:s,embeddedWalletAddress:o,providerEmbeddedAddress:a,address:i,isNon7702:l,resolvedChainId:d,buildActionCalls:c,feeExecutionMode:p,buildSpicenetBatch:m,selectedAsset:h,needsSwap:g,exactOutputSwap:x,resolvedTokenIn:y,requestTimestampMs:C}=e,w=t?.fundingTokenOverride??y,b=qt(n,s.decimals),I=e.feeOnlyAction?0n:t?.actionAmountOverride??b,S=!!e.feeOnlyAction&&(t?.fundingAmountOverride??0n)>0n,v=o||a||i;if(!v)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const B={userAddress:e.recipient??v,executorAddress:v,beneficiary:e.recipient??v,outputRecipient:g?v:void 0,chainId:d,destinationToken:s.address,grossAmount:t?.fundingAmountOverride??b,netAmount:I,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:p,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},E=await c(I,B),j={chainId:d,calls:E},N=!!h&&h.asset._source!=="wallet",T=ai(h??null,l,d),P=N||T&&!!h&&!ii(h.asset),M=(L,R)=>({token:k.normalizeNativeTokenAddress(L),from:"escrow",to:v,amount:R}),D=(L,R,U)=>T?[oi(L,R,d),...U]:U;if(b===0n&&!S)return[j];if(h?.asset._source==="wallet"&&h.asset.chainId!==d&&!e.pivot)throw new Error("A current source-to-destination funding route is required");if(e.feeOnlyAction&&t?.fundingTokenOverride&&T)return Us(t.fundingAmountOverride??0n,t),[j];if(ci(e)){if(g&&!x)throw new Error("Swap quote not available yet");const L=t?.fundingAmountOverride??(x?x.amountInMax:b),R=t?.sourceGasSkimOverride??0n,U=Pt(L,e.pivot.destination.decimals,e.pivot.source.decimals,"ceil"),X=U+R,Y=e.sourceExactOutputSwap,V=Y&&(t?.reuseQuotedSourceSwap||Y.amountOut>=X)?Y:e.resolveSourceExactOutputSwap?await e.resolveSourceExactOutputSwap(X):null;if(!V)throw new Error("Swap quote not available yet");Us(V.amountInMax,t);const J=h.asset;if(V.amountInMax>J.balance)throw new Error(`Insufficient ${J.symbol} for this payment. Required ${A.formatUnits(V.amountInMax,J.decimals)} ${J.symbol}; available ${A.formatUnits(J.balance,J.decimals)} ${J.symbol}.`);const ce=V.amountOut>=X?U:V.amountOut-R;if(ce<=0n)throw new Error("Amount is too small to cover fees. Increase the amount and retry.");const G={chainId:e.pivot.source.chainId,calls:[...V.calls,os(e.pivot.source.address,ce,k.getEscrowContractAddress(e.pivot.source.chainId)),...R>0n?[os(e.pivot.source.address,R,k.SPICE_GAS_FEE_RECIPIENT)]:[]]},q={chainId:d,calls:[...x?.calls??[],...E],tokenTransfers:[M(e.pivot.destination.address,L),...j.tokenTransfers??[]]},Z=await rs(q,m,{userAddress:v,destinationChainId:d,deliveryToken:e.pivot.destination.address,deliveryAmount:L,deliveryRecipient:v,deliveryTransfers:as(q),sourceAsset:h.asset},C);return[G,...Z]}if(h){const L=t?.fundingAmountOverride??x?.amountInMax??b;Us(Wn(L,await xn(h.asset,w??h.asset.address,d,s),h.asset.decimals),t)}if(g&&x){const L=w??Wt(h.asset,d)??h.asset.address,R=t?.fundingAmountOverride??x.amountInMax,U=P?[M(L,R)]:[],X={chainId:d,calls:[...x.calls,...E],tokenTransfers:[...U,...j.tokenTransfers??[]]};if(!P)return[X];const Y=await rs(X,m,{userAddress:v,destinationChainId:d,deliveryToken:L,deliveryAmount:R,deliveryRecipient:v,deliveryTransfers:as(X),sourceAsset:h.asset},C);return D(L,R,Y)}if(P){const L=w??Wt(h.asset,d)??s.address;if(T&&!e.feeOnlyAction&&L.toLowerCase()===s.address.toLowerCase())return[j];const R=t?.fundingAmountOverride??b,U={...j,tokenTransfers:[M(L,R),...j.tokenTransfers??[]]},X=await rs(U,m,{userAddress:v,destinationChainId:d,deliveryToken:L,deliveryAmount:R,deliveryRecipient:v,deliveryTransfers:as(U),sourceAsset:h.asset},C);return D(L,R,X)}return[j]}async function Md(e,t){const{selectedAsset:n,embeddedWalletAddress:s,recipient:o,resolvedChainId:a,destinationToken:i,buildActionCalls:l,feeExecutionMode:d,buildSpicenetBatch:c,isPayMode:p,isNon7702:m,needsSwap:h,resolvedSwap:g,quoteAmountOut:x,resolvedTokenIn:y,requestTimestampMs:C}=e;if(!n?.asset||!s)return[];const w=o??s;if(!w)return[];const b=Ho(e);let I=e.sourceSwap,S=qt(n.amount,n.asset.decimals),v=b?ri(e.sourceSwap,t?.sourceGasSkimOverride??0n):null;if(b&&!e.isFeeInclusiveInput&&t?.fundingAmountOverride!==void 0&&!t.reuseQuotedSourceSwap){v=Wn(t.fundingAmountOverride,e.pivot.destination.decimals,e.pivot.source.decimals);const H=v+(t.sourceGasSkimOverride??0n);if(!e.resolveSourceExactOutputSwap)throw new Error("The source quote cannot include fees yet.");const F=await e.resolveSourceExactOutputSwap(H);if(F.amountOut<H)throw new Error("The source quote does not cover the accepted funding amount.");S=F.amountInMax,I={...F,amountOutMinimum:F.amountOut}}const B=b?e.pivot.destination.address:y??Wt(n.asset,a)??i.address,E=b?e.pivot.destination.decimals:await xn(n.asset,B,a,i),j=t?.fundingAmountOverride??t?.actionAmountOverride??(b?Pt(v,e.pivot.source.decimals,E,"floor"):Ms(qt(n.amount,n.asset.decimals),n.asset.decimals,E)),N=t?.fundingAmountOverride??j,T=t?.sourceFundingAmountOverride??Wn(j,E,n.asset.decimals);Us(b?S:T,t);const P=t?.deliveryAmountOverride??(d==="user-transfer"?N:t?.actionContextOverride?.netAmount??N),M=t?.withdrawalAmountOverride??N,D=t?.actionAmountOverride??t?.actionContextOverride?.netAmount??j;let L=g;if(h&&!p&&(t?.actionContextOverride?.netAmount!==void 0||b&&(t?.sourceGasSkimOverride??0n)>0n&&!t?.reuseQuotedSourceSwap)){if(!e.resolveInputSwap)throw new Error("Swap quote cannot be refreshed for the amount after fees.");const H=t?.actionContextOverride?.netAmount??D;(!L||e.swapInputAmount!==H)&&(L=await e.resolveInputSwap(H))}L&&t?.onSwap?.(L,t?.actionContextOverride?.netAmount??e.swapInputAmount??D);const R=L?.amountOutMinimum??x,U={userAddress:w,executorAddress:s,beneficiary:w,outputRecipient:h?s:void 0,chainId:a,destinationToken:i.address,feeToken:d==="user-transfer"&&h&&y?y:i.address,grossAmount:N,netAmount:D,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:d,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},X=await l(D,U),Y=n.asset?._source==="wallet";if(!p&&Y&&n.asset.chainId===a&&ii(n.asset)){if(h){if(!y)throw new Error("Swap input token could not be resolved");if(!L||R===null)throw new Error("Swap quote not available yet")}if(h&&L&&R){const H=await l(t?.actionAmountOverride??R,{...U,netAmount:t?.actionAmountOverride??R}),{feeCall:F,remainingCalls:de}=li(H,d,h,U.feeToken);return[{chainId:a,calls:[...F?[F]:[],...L.calls,...de]}]}return[{chainId:a,calls:X}]}if(!p&&Y&&n.asset.chainId!==a&&!b)throw new Error("A current source-to-destination funding route is required");const V=n.asset._source!=="wallet",J=ai(n,m,a);if(!(V||J||b))return[{chainId:a,calls:X}];const ce=b?Dd(I,e.pivot,v,t?.sourceGasSkimOverride??0n):J?oi(y??k.normalizeNativeTokenAddress(n.asset.address),T,a):null,G=(H,F)=>({token:k.normalizeNativeTokenAddress(H),from:"escrow",to:s,amount:F});if(h){if(!y)throw new Error("Swap input token could not be resolved");if(!L||R===null)throw new Error("Swap quote not available yet")}if(h&&L&&R&&y){const H=await l(t?.actionAmountOverride??R,{...U,netAmount:t?.actionAmountOverride??R}),{feeCall:F,remainingCalls:de}=li(H,d,h,U.feeToken),re={chainId:a,calls:[...F?[F]:[],...L.calls,...de],tokenTransfers:[G(y,P)]},xe=await rs(re,c,{userAddress:s,destinationChainId:a,deliveryToken:y,deliveryAmount:P,withdrawalAmount:M,deliveryRecipient:s,deliveryTransfers:as(re,M),sourceAsset:n.asset},C);return ce?[ce,...xe]:xe}const q=y??Wt(n.asset,a)??i.address,Z={chainId:a,calls:X,tokenTransfers:[G(q,P)]},_=await rs(Z,c,{userAddress:s,destinationChainId:a,deliveryToken:q,deliveryAmount:P,withdrawalAmount:M,deliveryRecipient:s,deliveryTransfers:as(Z,M),sourceAsset:n.asset},C);return ce?[ce,..._]:_}async function Pd(e,t,n,s,o){let a=e;for(let i=0;i<4;i++){const l=await t(a),d=await s(l,n,a,o),c=zc(d);if(c===null||c>=e)return a;const p=a-c,m=e+p;if(m<=a)return a;a=m}return a}function Ud(e){return{...e,resolve:async(t,n,s)=>{const o=await e.resolve(t,n,s),a=o?.calls[0]?.to;return!o||!a||k.isNativeToken(t.tokenIn)?o:{...o,calls:[{to:t.tokenIn,value:0n,data:A.encodeFunctionData({abi:A.erc20Abi,functionName:"approve",args:[a,o.amountInMax]})},...o.calls]}}}}function Ls(e){const t=(e?.customVenues??[]).map(s=>fl(Ud(s)));async function n(s,o,a){const i=t.filter(c=>c.chainIds.includes(o));if(i.length===0)throw new f.SpiceflowError("NO_SWAP_ROUTE",`No exact-output venue supports chain ${o}`,{chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut});const l=(await Promise.allSettled(i.map(async c=>({venue:c,quote:await c.resolve(s,o,a)})))).filter(c=>c.status==="fulfilled").map(c=>c.value).filter(c=>c.quote!==null);if(l.length===0)throw new f.SpiceflowError("NO_SWAP_ROUTE",`All aggregators failed for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}`,{chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountOut:s.amountOut.toString()});const d=l.find(c=>c.venue.preferred);return d?d.quote:(l.sort((c,p)=>c.quote.amountIn<p.quote.amountIn?-1:c.quote.amountIn>p.quote.amountIn?1:0),l[0].quote)}return{getQuote:n,venues:t}}function Wd(e,t,n){if(e._source==="wallet")return e.chainId===t?e.address:null;const s=Dn(e,t);return s.find(o=>o.toLowerCase()===n.toLowerCase())??s[0]??null}class Ld extends Error{constructor(t,n){super("The selected balance cannot cover the fee funding amount"),this.requiredAmount=t,this.balance=n,this.name="InsufficientFeeFundingBalanceError"}}async function ui(e){const t=e.selectedAsset?.asset,n=!!e.actionProceeds&&e.actionProceeds.token.toLowerCase()!==e.destinationToken.address.toLowerCase(),s=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!s||!n&&(!t||t._source!=="spice"&&!(t._source==="wallet"&&t.chainId===e.resolvedChainId)))throw new Error("A local embedded or Spice balance is required for fee conversion");const o=n?e.actionProceeds.token:Wd(t,e.resolvedChainId,e.destinationToken.address);if(!o)throw new Error("This receipt has no registered destination withdrawal token");const a=k.getTokenByAddress(o,e.resolvedChainId)?.decimals??(k.isNativeToken(o)?18:n?k.isNativeToken(o)?18:await f.getClientForChain(e.resolvedChainId).readContract({address:o,abi:A.erc20Abi,functionName:"decimals"}):t?._source==="wallet"?t.decimals:void 0);if(a===void 0)throw new Error("Fee funding token metadata is unavailable");const i=e.destinationToken.address;if(e.actionProceeds&&!n&&e.actionProceeds.token.toLowerCase()!==i.toLowerCase())throw new Error("Action proceeds must use the destination fee token");const l=e.actionProceeds?await e.actionProceeds.resolve(e.signal):0n;if(l<0n||e.signal?.aborted)throw new Error("Action proceeds quote was cancelled or invalid");const d=Ls({customVenues:[...e.resolveExactOutputSwap?[{name:"consumer-exact-output",chainIds:[e.resolvedChainId],preferred:!0,resolve:e.resolveExactOutputSwap}]:[],...Rn(e.liquidityVenues).output]}),c=async m=>{const h=k.hashChainBatches(m),g=await f.relayerService.estimateBatchGas({user:s,outputToken:i,requireSimulation:!0,includePlatformFee:!0,signal:e.signal,chainBatches:m.map((x,y)=>({...x,hash:h[y].hash}))});if(!g.simulationVerified||g.gasQuoteSource!=="estimated"||g.platformFee===void 0||g.gasFee<=0n)throw new Error("Fee conversion requires verified gas and platform pricing");return g};let p=await c(await e.buildPayChainBatches({fundingAmountOverride:0n}));for(let m=0;m<8;m++){const h=p.gasFee+p.platformFee,g=n?0n:l<h?l:h,x=h-g,y=x>0n?(x*110n+99n)/100n+2n:0n,C=y>0n?await d.getQuote({tokenIn:o,tokenOut:i,amountOut:y,maxSlippage:e.maxSlippage},e.resolvedChainId,s):null;if(e.signal?.aborted)throw new Error("Fee conversion quote was cancelled");if(C&&(C.amountOut!==y||C.amountInMax<=0n||C.amountInMax<C.amountIn||!C.calls.length))throw new Error("Invalid exact-output fee conversion quote");const w=C?.amountInMax??0n,b=n?0n:Wn(w,a,t.decimals);if(n&&w>l)throw new Error("Action proceeds cannot cover the quoted fee conversion; choose an account balance");if(!n&&b>t.balance)throw new Ld(b,t.balance);let I,S=En(await e.buildPayChainBatches({fundingAmountOverride:n?0n:w,...n?{}:{fundingTokenOverride:o},onActionCalls:B=>{I=B}}),s);if(C){const B=S.length-1;S=S.map((E,j)=>j===B?{...E,calls:[...E.calls,...C.calls]}:E)}S=qo(S,s,i,p.gasFee,p.platformFee);const v=await c(S);if(v.gasFee<=p.gasFee&&(p.gasFee-v.gasFee)*100n<=v.gasFee*15n&&v.platformFee===p.platformFee){const B={tokenIn:o,tokenOut:i,amountInMax:w,amountOut:y,sourceAmountMax:b,...n?{fromProceeds:!0}:{}};return{feeEstimate:null,preview:{symbol:e.destinationToken.symbol,decimals:e.destinationToken.decimals,grossAmount:n?0n:y,netAmount:0n,gasFee:p.gasFee,spicenetFee:p.platformFee,totalFee:h,gasQuoteSource:"estimated"},grossFundingAmount:n?0n:w,proceedsAvailable:l,proceedsUsed:n?h:g,fundingConversion:B,fundingBatches:S,sourceSpendCap:b,destinationAmount:0n,actionDefinition:I}}p=v}throw new Error("Fee conversion pricing did not converge")}async function Qo(e){const[t]=await e.buildSupplyChainBatches({sourceGasSkimOverride:1n,reuseQuotedSourceSwap:!0});if(!t)throw new Error("Swap quote not available yet");const{gasFee:n}=await f.relayerService.estimateBatchGas({user:e.user,outputToken:e.pivot.source.address,stepIndex:0,chainBatches:[t],signal:e.signal});return n}const pi=(e,t)=>(e+t-1n)/t;function fi(e,t){const n=e.spicenetFee+(e.bridgeFee??0n);return e.grossAmount<=n?t+e.gasFee+n:pi((t+e.gasFee)*e.grossAmount,e.grossAmount-n)+2n}async function mi(e){const{requiredNetFunding:t}=e;if(e.feeOnlyAction){const c=e.executionOptions?.userOverride;if(!c||t!==0n)throw new Error("Fee-only estimates require a zero action amount and its embedded executor");let p=1n,m;for(let h=0;h<8;h++){const g=En(await e.buildBatches(p),c,m,{payoutAlreadyGross:!0}),x=await e.estimate(Ps(g,e.tokenDescriptor.chainId,e.fundingToken),e.fundingToken,p,{...e.executionOptions,feeExecutionMode:"backend-transfer"}),y=In(x,e.tokenDescriptor);if(!y)throw new Error("The fee service did not return a fee quote for this action");const C=y.gasFee+y.spicenetFee+(y.bridgeFee??0n);if(m&&C+2n<=p)return{preview:{...y,grossAmount:p,netAmount:0n},feeEstimate:x,grossFundingAmount:p};p=(C*110n+99n)/100n+2n,m=x}throw new Error("Fee-only funding did not converge; refresh the fee quote before retrying")}const n=await e.buildBatches(t),s=await e.estimate(n,e.fundingToken,t,e.executionOptions),o=In(s,e.tokenDescriptor);if(!o)return{preview:js(n,e.tokenDescriptor,t),feeEstimate:s,grossFundingAmount:t};const a=fi(o,t),i=c=>o.grossAmount>0n?pi(c*a,o.grossAmount):c,l=i(o.spicenetFee),d=i(o.bridgeFee??0n);return{preview:{...o,grossAmount:a,netAmount:t,spicenetFee:l,bridgeFee:d,totalFee:o.gasFee+l+d},feeEstimate:s,grossFundingAmount:a}}async function hi(e){if(e.balance<=0n)throw new Error("No spendable balance remains after source gas.");let t=e.balance;for(let n=0;n<8;n++){const s=await e.planForAmount(t);if(!s||s.sourceSpendCap===void 0||s.sourceSpendCap<=0n)throw new Error("Max requires a current route and fee estimate.");if(s.sourceSpendCap<=e.balance)return es(t,e.decimals);const o=t*e.balance/s.sourceSpendCap;if(o<=0n||o>=t)throw new Error("The balance cannot cover this action and its fees.");t=o}throw new Error("Max fees did not converge. Refresh the quote before retrying.")}async function zd(e){if(e.isPayMode||e.needsSwap||e.isQuoting||e.pivot||!e.embeddedWalletAddress)return null;const t=e.asset,n=k.getTokenByAddress(e.executionTokenAddress,t.chainId);return!n||t.balance<=0n?null:hi({balance:t.balance,decimals:t.decimals,planForAmount:s=>is({selectedAsset:{asset:t,amount:es(s,t.decimals)},isPayMode:!1,isNon7702:!1,isFeeInclusiveInput:!1,parsedAmount:Number(es(s,t.decimals)),currentPaymentAmount:"0",destinationToken:{...n,address:e.executionTokenAddress,chainId:t.chainId},resolvedChainId:t.chainId,resolvedTokenIn:e.executionTokenAddress,executionTokenAddress:e.executionTokenAddress,embeddedWalletAddress:e.embeddedWalletAddress,providerEmbeddedAddress:e.embeddedWalletAddress,address:e.embeddedWalletAddress,isConnected:!0,ready:!0,authenticated:!0,isDirect:!0,isSourceDestToken:!0,needsSwap:!1,isQuoting:!1,resolvedSwap:null,exactOutputSwap:null,buildPayChainBatches:async()=>[],buildSupplyChainBatches:o=>e.buildSupplyChainBatches({...o,actionAmountOverride:s}),estimate:e.estimate,feeExecutionMode:e.feeExecutionMode})})}async function is(e){const{signal:t,selectedAsset:n,isPayMode:s,isFeeInclusiveInput:o=!1,parsedAmount:a,needsSwap:i,exactOutputSwap:l,isNon7702:d,currentPaymentAmount:c,destinationToken:p,feeExecutionMode:m,resolvedTokenIn:h,embeddedWalletAddress:g,providerEmbeddedAddress:x,resolvedChainId:y,isConnected:C,address:w,ready:b,authenticated:I,isDirect:S,resolvedSwap:v,sourceSwap:B,pivot:E,isQuoting:j,executionTokenAddress:N,buildPayChainBatches:T,buildSupplyChainBatches:P,estimate:M}=e;if(e.feeOnlyAction&&e.actionProceeds&&e.actionProceeds.token.toLowerCase()!==p.address.toLowerCase()||e.feeOnlyAction&&n&&(n.asset._source==="spice"||n.asset._source==="wallet"&&n.asset.chainId===y)&&(h?h.toLowerCase()!==p.address.toLowerCase():n.asset.receiptTokenId||n.asset.chainTokens))return ui(e);if(e.actionProceeds&&e.feeOnlyAction){const G=g||x;if(!G||!b||!I)return null;if(h&&h.toLowerCase()!==p.address.toLowerCase())throw new Error("Action proceeds require a matching fee-token source");return Td({proceeds:e.actionProceeds,owner:G,token:p.address,signal:t,buildBatches:(q,Z)=>T({...Z,fundingAmountOverride:q}),baseline:()=>is({...e,actionProceeds:void 0,selectedAsset:n??{amount:"0",asset:{...p,name:p.symbol,balance:0n,balanceFormatted:0,balanceUsd:0,isNative:!1,_source:"spice"}}})})}if(!n?.asset)return null;if(s){if(!g&&!x||a<=0&&!e.feeOnlyAction||i&&!l&&!e.feeOnlyAction)return null;const G=qt(c,p.decimals),q=h||Wt(n.asset,y)||n.asset.address||p.address,Z={chainId:y,tokenAddress:q,symbol:k.getTokenByAddress(q,y)?.symbol??n.asset.symbol,decimals:await xn(n.asset,q,y,p)};if(!C||!w||!b||!I)return null;const _=g||x||w,H=i?l?.amountInMax??0n:G;if(H===0n&&!e.feeOnlyAction)return null;const F=E?await Qo({user:_,pivot:E,buildSupplyChainBatches:O=>T({...O,sourceGasSkimOverride:1n}),signal:t}):0n;let de=await mi({requiredNetFunding:H,feeOnlyAction:e.feeOnlyAction,buildBatches:O=>T({fundingAmountOverride:O,sourceGasSkimOverride:F}).then(se=>ti(Od(se),_)),fundingToken:q,estimate:M,executionOptions:{userOverride:_,useCustomTransfers:!0,feeExecutionMode:m,signal:t},tokenDescriptor:Z});if(!de.preview)return null;let re=0n,xe,he=[],ae=!1;for(let O=0;O<8;O++){if(t?.aborted)throw new Error("Fee estimation cancelled");if(he=En(await T({fundingAmountOverride:de.grossFundingAmount,sourceGasSkimOverride:F,onSourceSpend:Ce=>{re=Ce},onActionCalls:Ce=>{xe=Ce}}),_,de.feeEstimate,{payoutAlreadyGross:!0}),e.feeOnlyAction){ae=!0;break}const se=await M(he,q,de.grossFundingAmount,{userOverride:_,useCustomTransfers:!0,feeExecutionMode:m,signal:t}),W=In(se,Z)??js(he,Z,H);if(!W)return null;const $=W.gasQuoteSource==="static_zero"?H:fi(W,H),oe=de.grossFundingAmount>=$&&de.grossFundingAmount-$<=2n;if(de={feeEstimate:se,grossFundingAmount:oe?de.grossFundingAmount:$,preview:{...W,grossAmount:oe?de.grossFundingAmount:$,netAmount:H}},oe){ae=!0;break}}if(!ae)throw new Error("Payment fees did not converge. Refresh the quote before submitting.");if(!de.preview)return null;const be=E?Pt(F,E.source.decimals,E.destination.decimals,"ceil"):0n;return{...de,batches:he,sourceSpendCap:re,actionDefinition:xe,destinationAmount:G,preview:{...de.preview,grossAmount:de.preview.grossAmount+be,gasFee:de.preview.gasFee+be,totalFee:(de.preview.totalFee??0n)+be},...E?{sourceGasSkim:F}:{}}}if(a<=0||!g)return null;const D=g||x;if(E&&!B)return null;const L=Ho({isPayMode:s,selectedAsset:n,resolvedChainId:y,sourceSwap:B,pivot:E});if(!(!s&&!d&&n.asset?._source==="wallet"&&n.asset.chainId!==y)&&!S&&!v&&!j||j)return null;let R=await P();if(R.length===0)return null;const U={chainId:y,tokenAddress:N,symbol:k.getTokenByAddress(N,y)?.symbol??(n.asset.chainId===y&&f.addressesEqual(n.asset.address,N)?n.asset.symbol:p.symbol),decimals:await xn(n.asset,N,y,p)},X=L?await Qo({user:D,pivot:E,buildSupplyChainBatches:P,signal:t}):0n;L&&X>0n&&(R=await P({sourceGasSkimOverride:X}));const Y=L?Pt(o?ri(B,X):B.amountOutMinimum,E.source.decimals,E.destination.decimals,"floor"):Pt(qt(n.amount,n.asset.decimals),n.asset.decimals,U.decimals,"floor"),V={userOverride:D,useCustomTransfers:!0,feeExecutionMode:m,signal:t,...L?{skipUserFundingPreflight:!0}:{}};let J=Y,ce=await M(R,N,J,V);for(let G=0;G<8;G++){if(t?.aborted)throw new Error("Fee estimation cancelled");const q=In(ce,U)??js(R,U,J);if(!q)return null;const Z=Go(q,Y,o,m);J=Z.grossAmount;let _,H,F,de,re;const xe=await P({fundingAmountOverride:J,sourceGasSkimOverride:X,actionContextOverride:Z,onDestinationAmount:O=>{_=O},onSourceSpend:O=>{H=O},onSwap:(O,se)=>{F=O,de=se},onActionCalls:O=>{re=O}}),he=await M(xe,N,J,V),ae=In(he,U)??js(xe,U,J);if(!ae)return null;const be=Go(ae,Y,o,m);if(JSON.stringify(Z,(O,se)=>typeof se=="bigint"?se.toString():se)===JSON.stringify(be,(O,se)=>typeof se=="bigint"?se.toString():se)){const O=L?Pt(X,E.source.decimals,E.destination.decimals,"ceil"):0n;return{batches:xe,fundingAmount:J,actionContext:Z,sourceSpendCap:H,destinationAmount:_,destinationSwap:F,swapInputAmount:de,actionDefinition:re,feeEstimate:he,sourceGasSkim:X,preview:{...ae,grossAmount:J+O,netAmount:Z.netAmount,gasFee:ae.gasFee+O,spicenetFee:Z.feeBreakdown.spicenetFee,totalFee:Z.combinedFeeAmount+O}}}ce=he,R=xe}throw new Error("Fees did not converge. Refresh the quote before submitting.")}function Go(e,t,n,s){const o=e.gasFee+(e.bridgeFee??0n);if(e.gasQuoteSource==="static_zero")return{grossAmount:t,netAmount:t,combinedFeeAmount:0n,feeExecutionMode:s??"backend-transfer",feeBreakdown:{gasFee:0n,bridgeFee:0n,spicenetFee:0n}};const a=n?Uc(t,o,10n):null;if(a&&!a.coversFees)throw new Error("Amount is too small to cover fees. Increase the amount and retry.");const i=a?.spicenetFee??(s==="user-transfer"?Fs(t,10n):e.spicenetFee);return{grossAmount:a?.grossAmount??t+i+o,netAmount:a?.netAmount??t,combinedFeeAmount:i+o,feeExecutionMode:s??"backend-transfer",feeBreakdown:{gasFee:e.gasFee,bridgeFee:e.bridgeFee??0n,spicenetFee:i}}}function qd(e,t){const n=e.selectedAsset?.asset;if(!n||n?._source!=="wallet")return;const s=Wt(n,e.resolvedChainId);if(!s||!f.addressesEqual(s,e.executionTokenAddress))return;const o=k.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),a=Wn(t,o?.decimals??e.destinationToken.decimals,n.decimals);if(a<=n.balance)return;const i=A.formatUnits(a,n.decimals),l=A.formatUnits(n.balance,n.decimals);throw new Error(`Insufficient ${n.symbol} for this total amount. Required ${i} ${n.symbol}; available ${l} ${n.symbol}.`)}function Hd(e){const t=k.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:t?.symbol??e.destinationToken.symbol,decimals:t?.decimals??e.destinationToken.decimals}}function Vd(e){const t=e.selectedAsset.asset,n=qt(e.selectedAsset.amount,t.decimals);if(n<=t.balance)return n;throw new Error(`Insufficient ${t.symbol} for this total amount. Required ${A.formatUnits(n,t.decimals)} ${t.symbol}; available ${A.formatUnits(t.balance,t.decimals)} ${t.symbol}.`)}async function Qd(e,t){return e.feeQuote?.sourceGasSkim!==void 0?e.feeQuote.sourceGasSkim:Qo({user:t,pivot:e.pivot,buildSupplyChainBatches:e.execution.buildSupplyChainBatches})}function Gd(e,t,n){const s=In(e,Hd(t));if(s)return Go(s,n,!!t.isFeeInclusiveInput,t.feeExecutionMode)}function Kd(e,t,n){let s=0n,o=0n;const a=n.toLowerCase();for(const i of e)if(i.chainId===t){for(const l of i.calls??[])if(l.to.toLowerCase()===a)try{const d=A.decodeFunctionData({abi:A.erc20Abi,data:l.data});if(d.functionName!=="transfer")continue;const c=d.args[0].toLowerCase(),p=d.args[1];c===k.SPICE_PLATFORM_FEE_RECIPIENT.toLowerCase()?s+=p:c===k.SPICE_GAS_FEE_RECIPIENT.toLowerCase()&&(o+=p)}catch{continue}}return{spicenetFee:s,gasFee:o}}function Zd(e,t,n){const s=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,o=Kd(e,t.resolvedChainId,s);return o.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||o.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:Sn(o.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&Sn(o.gasFee,n.feeBreakdown.gasFee,100n)}function Yd(e,t){return e?Sn(e.grossAmount,t.grossAmount,100n)&&Sn(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&Sn(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&Sn(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}function Xd(e,t){const n=k.getTokenByAddress(t,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:t,symbol:n?.symbol??e.selectedAsset?.asset.symbol??"",decimals:n?.decimals??e.selectedAsset?.asset.decimals??e.destinationToken.decimals}}async function Jd(e,t){const n=e.feeQuote;return n?.feeEstimate&&n.grossFundingAmount!==void 0?{grossFundingAmount:n.grossFundingAmount,feeEstimate:n.feeEstimate}:mi({...t,feeOnlyAction:e.feeOnlyAction,estimate:e.execution.estimate,tokenDescriptor:Xd(e,t.fundingToken)})}function $d(e,t,n){const s=t instanceof Error?t:new Error(String(t));if(s.name==="AbortError"||n){e.ui.setStep("idle");return}const o=s.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(o),e.ui.setError(o)}function _d(e,t){const n=f.sanitizeError(t,"Payment failed. Please try again.");e.ui.setError(n),e.ui.setPaymentResult({status:"failed",error:n})}async function gi(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=e.embeddedWalletAddress||e.providerEmbeddedAddress,s=Ho(e),o=s?await Qd(e,n):0n,a=y=>e.execution.buildSupplyChainBatches(s?{...y,sourceGasSkimOverride:o}:y);s&&Vd(e);const i=e.feeQuote?.batches?e.feeQuote:await is({...e,feeExecutionMode:e.feeExecutionMode,isDirect:!e.needsSwap,isQuoting:!1,resolvedSwap:null,buildPayChainBatches:e.execution.buildPayChainBatches,buildSupplyChainBatches:e.execution.buildSupplyChainBatches,estimate:e.execution.estimate});if(!i?.batches||i.fundingAmount===void 0||!i.actionContext)throw new Error("A current action plan is required. Refresh the quote before submitting.");const l=e.isFeeInclusiveInput?i.actionContext.grossAmount:i.actionContext.netAmount;let d=i.batches;const c=d.some(y=>y.tokenTransfers?.length),p={userOverride:n,useCustomTransfers:c,feeExecutionMode:e.feeExecutionMode,...s?{skipUserFundingPreflight:!0}:{}},m=i.fundingAmount,h=i.actionContext;qd(e,m);let g=h;const x=await e.execution.execute(d,e.executionTokenAddress,c?m:0n,e.execution.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...p,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:y,chainBatches:C})=>{const w=Gd(y,e,l);if(!w)return null;const b=Yd(g,w),I=Zd(C,e,w);return b||I?null:(g=w,a({fundingAmountOverride:w.grossAmount,actionContextOverride:w}))}}:{...p,skipPreSubmitFeeEstimate:!0});e.ui.setTxHash(x),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){$d(e,n,t.signal.aborted)}finally{e.ui.setIsExecuting(!1)}}async function xi(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}const t=e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t){e.ui.setError("Select a payment source");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.parsedAmount>0&&e.needsSwap&&!e.exactOutputSwap){e.ui.setError("Swap quote not available. Try a different asset.");return}const n=ci(e)&&!t,s=n?e.feeQuote?.sourceGasSkim??0n:0n,o=a=>e.execution.buildPayChainBatches(n?{...a,sourceGasSkimOverride:s}:a);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 a=qt(e.currentPaymentAmount,e.destinationToken.decimals),i={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,...n?{skipUserFundingPreflight:!0}:{}};if(t&&!e.feeOnlyAction){const w=await o(),b=await e.execution.execute(w,e.executionTokenAddress,0n,I=>{I.txHash&&(e.ui.setPaymentResult(S=>({...S??{status:"processing"},txHash:I.txHash})),e.ui.setTxHash(I.txHash))},void 0,i);e.ui.setPaymentResult(I=>({status:"success",txHash:I?.txHash||b}));return}const l=e.selectedAsset?.asset;if(!l&&!e.actionProceeds)throw new Error("Select a payment source");const d=e.feeQuote?.fundingConversion?.tokenIn||e.resolvedTokenIn||l?.address||e.destinationToken.address,c=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:a,p=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,{grossFundingAmount:m,feeEstimate:h}=e.feeQuote?.fundingConversion?{grossFundingAmount:e.feeQuote.grossFundingAmount,feeEstimate:void 0}:await Jd(e,{requiredNetFunding:c,buildBatches:w=>e.execution.buildPayChainBatches({fundingAmountOverride:w}).then(b=>En(b,p)),fundingToken:d,executionOptions:i});let g=e.feeQuote?.fundingBatches??e.feeQuote?.batches??En(await o({fundingAmountOverride:m}),p,e.actionProceeds?void 0:h,{payoutAlreadyGross:!0});const x=Bd(e,e.feeQuote?.fundingConversion?.tokenOut??d,m);x.prepareForSigning&&(g=await x.prepareForSigning(g));const y=g.some(w=>w.tokenTransfers?.length),C=await e.execution.execute(g,d,y?m:0n,w=>{w.txHash&&(e.ui.setPaymentResult(b=>({...b,txHash:w.txHash})),e.ui.setTxHash(w.txHash))},void 0,{...i,...x,skipPreSubmitFeeEstimate:!0});e.ui.setPaymentResult(w=>({status:"success",txHash:w?.txHash||C}))}catch(a){_d(e,a)}finally{e.ui.setIsExecuting(!1)}}const Ln=e=>JSON.stringify(e,(t,n)=>typeof n=="bigint"?{raw:n.toString(),type:"spice-quantity"}:n);function ls(e){const t=JSON.parse(e,(n,s)=>s?.type==="spice-quantity"?BigInt(s.raw):s);if(!t||typeof t.amount!="bigint"||!t.context||!Array.isArray(t.calls))throw new Error("The funded action definition cannot be restored. Reconcile its existing result before retrying.");return t}async function cs(e,t){const n=await t(e.amount,e.context);if(Ln(n)!==Ln(e.calls))throw new Error("The destination action or beneficiary changed. Restore the funded action before submitting.")}const Ko=new Set;function Fn(e,t,n){return`spiceflow:pendingDeposit:${e.toLowerCase()}:${t}:${k.normalizeNativeTokenAddress(n).toLowerCase()}`}async function Zo(e,t,n){if(typeof navigator<"u"&&navigator.locks)return navigator.locks.request(e,{ifAvailable:!0},s=>{if(!s)throw new Error("This source is already executing in another view.");return n()});if(t)throw new Error("This browser cannot safely coordinate wallet funding. Use a browser with Web Locks support.");if(Ko.has(e))throw new Error("This source is already executing in another view.");Ko.add(e);try{return await n()}finally{Ko.delete(e)}}async function eu(e){return Zo(Fn(e.embeddedWalletAddress,e.chainId,e.tokenAddress),!1,async()=>{const t=kn(e.embeddedWalletAddress).find(s=>Fn(s.embeddedWalletAddress,s.chainId,s.tokenAddress)===Fn(e.embeddedWalletAddress,e.chainId,e.tokenAddress));if(!t||t.actionFunding?.identity!==e.actionFunding?.identity)throw new Error("The pending action changed in another view.");const n=await yi(t);return t.actionFunding.completedHash=n,_n(t),n})}async function yi(e){const t=e.actionFunding;if(t?.completedHash)return t.completedHash;if(!t?.submitted||!t.intentId||!t.stepCount)throw new Error("The submission result is uncertain. Reconcile the existing action before submitting again.");const[n,s]=t.intentId.split("/");if(!t.recovery)throw new Error("The destination chain and receipt must be reconciled before completing this historical action. Do not submit another payment.");const o=t.recovery,a=await Ia({actionId:n,intentIndex:Number(s||0),intentId:t.intentId,totalSteps:t.stepCount,resume:!0,maxPolls:180,isSpicenetStep:i=>o.spicenetSteps[i],maxExecuteAttemptsForStep:i=>o.spicenetSteps[i]?6:3,beforeStep:async i=>{if(!(!o.spicenetSteps[i]||!o.baseline||!o.deposits.length)&&!await ba({deposits:o.deposits.map(l=>({...l,amount:BigInt(l.amount)})),baseline:o.baseline,fetchEntries:()=>f.getWalletBalanceEntries(e.embeddedWalletAddress)}))throw new Error("The existing source deposit is still waiting for verified Spice credit.")}});if(!a||!/^0x[0-9a-f]{64}$/i.test(a))throw new Error("The destination receipt is not available yet. Continue reconciling this action.");if(!o.destinationChainId)throw new Error("The destination chain must be reconciled before completing this historical action.");return aa(f.getClientForChain(o.destinationChainId),a)}function wi(e,t,n){return e&&t>BigInt(e.rawAmount)?"The new plan exceeds the existing funded amount. Reconcile the funded source before increasing it.":e?.actionFunding?.minimumDestinationAmount&&n!==void 0&&n<BigInt(e.actionFunding.minimumDestinationAmount)?"The new plan reduces the accepted destination amount. Review the updated minimum before continuing.":null}async function tu(e){const t=e.record,n=Fn(t.embeddedWalletAddress,t.chainId,t.tokenAddress);await Zo(n,!0,async()=>{const s=kn(t.embeddedWalletAddress).find(l=>Fn(l.embeddedWalletAddress,l.chainId,l.tokenAddress)===n);if(!s||JSON.stringify(s)!==JSON.stringify(t))throw new Error("The funded operation changed. Review it again before accepting a quote.");const o=s.actionFunding;if(!o?.source||o.source.pending||o.submitted||o.intentId||o.completedHash||!o.actionDefinition||!o.minimumDestinationAmount||BigInt(o.source.confirmedAmount)<BigInt(s.rawAmount)||e.sourceSpendCap!==BigInt(s.rawAmount)||e.minimumDestinationAmount<=0n||e.minimumDestinationAmount>=BigInt(o.minimumDestinationAmount))throw new Error("Only a fully funded, unsubmitted action can accept an updated minimum with the same source amount.");const a=ls(o.actionDefinition),i=ls(e.actionDefinition);for(const l of["userAddress","executorAddress","beneficiary","outputRecipient","chainId","destinationToken","feeToken","feeExecutionMode"])if(a.context[l]!==i.context[l])throw new Error("Restore the original beneficiary and configuration before reviewing this quote.");if(i.amount!==e.minimumDestinationAmount)throw new Error("The updated action does not match the reviewed destination minimum.");e.assertCurrent(),await cs(a,e.buildActionCalls),await cs(i,e.buildActionCalls),e.assertCurrent(),o.minimumDestinationAmount=e.minimumDestinationAmount.toString(),o.actionDefinition=e.actionDefinition,_n(s)})}async function bi(e){const t=e.asset;if(So(e.embedded),await e.assertCurrent(),!t)return e.run({validateBeforeSubmit:e.assertCurrent});const n=Fn(e.embedded,t.chainId,t.address),s=async()=>{So(e.embedded);let o=kn(e.embedded).find(c=>Fn(c.embeddedWalletAddress,c.chainId,c.tokenAddress)===n);if(o&&(!o.actionFunding||o.actionFunding.identity!==e.identity))throw new Error("This source has a pending funded operation. Restore and reconcile it before starting another action.");const a=wi(o,e.sourceSpendCap,e.minimumDestinationAmount);if(a)throw new Error(a);const i=()=>{o&&_n(o)},l=()=>({chainId:t.chainId,tokenAddress:t.address,tokenSymbol:t.symbol,tokenDecimals:t.decimals,isNative:t.isNative,amount:A.formatUnits(e.sourceSpendCap,t.decimals),rawAmount:e.sourceSpendCap.toString(),embeddedWalletAddress:e.embedded,externalWalletAddress:e.external??e.embedded,timestamp:Date.now(),actionFunding:{identity:e.identity,purpose:e.purpose,selection:e.selection?{...e.selection,asset:{...e.selection.asset,balance:e.selection.asset.balance.toString()}}:void 0,minimumDestinationAmount:e.minimumDestinationAmount?.toString(),actionDefinition:e.actionDefinition}});if(o?.actionFunding?.submitted||o?.actionFunding?.completedHash){const c=await yi(o);return o.actionFunding.completedHash=c,i(),c}if(e.fundExternal){if(!e.external||!e.externalWallet)throw new Error("Connect the source wallet before funding.");e.onFunding?.(),await uc({identity:e.identity,state:o?.actionFunding?.source,recipient:e.embedded,tokenAddr:t.address,isNative:t.isNative||k.isNativeToken(t.address),requiredAmount:e.sourceSpendCap,sourceClient:f.getClientForChain(t.chainId),createWallet:async()=>{const c=e.sourceSpendCap-BigInt(o?.actionFunding?.source?.confirmedAmount??"0"),p=f.getClientForChain(t.chainId),m=t.isNative||k.isNativeToken(t.address),[h,g]=await Promise.all([ca({client:p,account:e.external,recipient:e.embedded,token:t.address,isNative:m,amount:c}),p.getBalance({address:e.external})]);if(g<h+(m?c:0n))throw new Error("The source wallet has insufficient native balance for funding and gas.");return la({wallet:e.externalWallet,account:e.external,chainId:t.chainId})},observer:{onSending:e.assertCurrent},onState:c=>{o??(o=l()),o.actionFunding.source=c,i()}})}if(await e.assertCurrent(),e.fundOnly)return"";const d=await e.run({validateBeforeSubmit:e.assertCurrent,beforeActionSubmit:async()=>{await e.assertCurrent(),o??(o=l()),o?.actionFunding&&(o.actionFunding.submitted=!0,i())},onActionCreated:(c,p,m)=>{o?.actionFunding&&(Object.assign(o.actionFunding,{intentId:c,stepCount:p,recovery:m}),i())}});return o?.actionFunding&&(o.actionFunding.completedHash=d,i()),d};return Zo(n,e.fundExternal,s)}function Ci(e,t,n){return f.addressesEqual(e.address,t)&&e.chainId===n?e._source==="wallet"?0:1:2}function nu(e,t,n,s){const o=Ci(e,n,s)-Ci(t,n,s);return o!==0?o:(t.balanceUsd||0)-(e.balanceUsd||0)}const su=Vr;function vi(e){const t=u.useContext(f.SpiceFlowProviderContext),n=f.useProviderWallets(),s=t?.embeddedWalletAddress||n.embeddedAddress,o=t?.externalWalletAddress||n.externalAddress,a=(t?.mode||"7702")!=="7702",i=Nn({...e,owner:s,enabled:e.enabled&&!!s&&(!a||!!e.includeCrossChainEmbeddedAssets),role:"spend-source",destination:e.destinationToken}),l=Nn({...e,owner:o,enabled:e.enabled&&!!o&&(a||!!e.includeExternalWalletAssets),role:"spend-source",destination:e.destinationToken});return{displayAssets:u.useMemo(()=>[...i.assets,...l.assets].sort((d,c)=>nu(d,c,e.destinationToken.address,e.destinationToken.chainId)),[i.assets,l.assets,e.destinationToken.address,e.destinationToken.chainId]),filteredSpiceAssets:i.rollupAssets,walletAssets:[...i.walletAssets,...l.walletAssets],embeddedWalletAddress:s,externalAddress:o,isNon7702:a,refreshSpiceAssets:i.refresh,refreshWalletAssets:i.refresh,loading:i.loading||l.loading,refreshing:i.refreshing||l.refreshing,error:i.error||l.error}}function ou(e,t){return!e||e._source!=="wallet"?null:co(e,t)}function Yo(e,t){return Sr({aerodrome:!1,oneInch:e?.includeDefaults===!1?{chainIds:[]}:void 0,customVenues:t})}const Xo=Rn(),ru=Yo(void 0,Xo.input);function ki(e){return{venue:"mapped-transfer",amountOut:e,amountOutMinimum:e,calls:[]}}function Si(e){return{venue:"mapped-transfer",amountIn:e,amountInMax:e,amountOut:e,calls:[]}}async function Jo(e){if(f.addressesEqual(e.tokenIn,e.tokenOut))return ki(e.amountIn);if(e.resolveInputSwap){const n=await e.resolveInputSwap({type:"swap",tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:e.amountIn,maxSlippage:e.maxSlippage},e.chainId,e.recipient);if(n)return n}const t=await(e.liquidityVenues?Yo(e.liquidityVenues,Rn(e.liquidityVenues).input):ru).resolveSwap({type:"swap",tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:e.amountIn,maxSlippage:e.maxSlippage},e.chainId,e.recipient);if(!t)throw new Error("No liquidity for this pair.");return t}async function au(e){return f.addressesEqual(e.tokenIn,e.tokenOut)?Si(e.amountOut):Ls({customVenues:e.liquidityVenues?Rn(e.liquidityVenues).output:Xo.output}).getQuote({tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountOut:e.amountOut,maxSlippage:e.maxSlippage},e.chainId,e.recipient)}function Ii(e){const{enabled:t=!0,direction:n,selectedAsset:s,destinationToken:o,chainId:a,recipient:i,paymentAmount:l,maxSlippage:d,refreshIntervalMs:c,resolveInputSwap:p,resolveExactOutputSwap:m}=e,h=u.useContext(f.SpiceFlowProviderContext),g=h?.liquidityVenues,x=JSON.stringify([h?.network,h?.apiUrl,h?.rpcOverrides]),[y,C]=u.useState(!1),[w,b]=u.useState(null),[I,S]=u.useState(null),[v,B]=u.useState(null),[E,j]=u.useState(null),[N,T]=u.useState(null),[P,M]=u.useState(null),[D,L]=u.useState(null),[R,U]=u.useState(null),[X,Y]=u.useState(null),[V,J]=u.useState(null),[ce,G]=u.useState(null),[q,Z]=u.useState(null),[_,H]=u.useState(null),[F,de]=u.useState(0),[re,xe]=u.useState(null),[he,ae]=u.useState(null),be=u.useRef(null),O=u.useRef(null),se=u.useRef(0),W=u.useRef(new Map),$=u.useCallback(()=>{se.current++,W.current.clear(),ae(null),de(Pe=>Pe+1)},[]),oe=c&&c>0?c:null,Ce=g?JSON.stringify(g):"",Me=u.useMemo(()=>g?Rn(g):Xo,[Ce]),ne=u.useMemo(()=>Yo(g,Me.input),[Me]),Ie=u.useMemo(()=>Ls({customVenues:[...m?[{name:"consumer-exact-output",chainIds:[a],preferred:!0,resolve:m}]:[],...Me.output]}),[m,a,Me]);u.useEffect(()=>{W.current.clear()},[Ie]);const ge=u.useMemo(()=>t?ou(s?.asset,a):null,[t,s?.asset,a]),Ye=u.useMemo(()=>{if(!t||!s?.asset)return null;if(ge)return ge.destination.address;const Pe=Wt(s.asset,a);if(Pe)return Pe;const Te=un(s.asset.address,a,s.asset.chainId);return Te?Te.address:null},[t,s?.asset,a,ge]),tt=u.useMemo(()=>t&&s?.asset?Dn(s.asset,a):[],[t,s?.asset,a]),dt=u.useMemo(()=>tt.map(Pe=>Pe.toLowerCase()).join(","),[tt]),Xe=JSON.stringify([t,x,s?.asset.owner,s?.asset.location,s?.asset.receiptTokenId,s?.asset.address,s?.asset.chainId,s?.asset.decimals,s?.amount,a,dt,n,l]);u.useEffect(()=>{let Pe=!1;if(O.current&&(clearTimeout(O.current),O.current=null),!t||!s?.asset||ge||tt.length<=1){Z(null),H(null);return}return O.current=setTimeout(async()=>{const Te=n==="input"?s.amount:l||"0";let Ke=0n;try{Ke=n==="input"?qt(Te,s.asset.decimals):0n}catch{Ke=0n}try{const st=await qr(s.asset,a,{requiredAmount:Ke});Pe||(Z(st),H(Xe))}catch{Pe||Z(null)}},400),()=>{Pe=!0,O.current&&(clearTimeout(O.current),O.current=null)}},[Xe]);const $e=u.useMemo(()=>(_===Xe?q:null)??Ye,[q,_,Xe,Ye]),qe=u.useMemo(()=>!s?.asset||!$e?[]:[$e,...tt.filter(Pe=>Pe.toLowerCase()!==$e.toLowerCase())],[s?.asset,$e,tt]),nt=u.useMemo(()=>!s?.asset||!Gn(s.asset.address,s.asset.chainId,o.address,o.chainId)||!$e?!1:f.addressesEqual($e,o.address),[s,o.address,o.chainId,$e]),Ve=$e?f.addressesEqual($e,o.address):!1,Re=n==="output"&&parseFloat(l||"0")===0,Le=t&&!!s?.asset&&!nt&&!Ve&&!Re,ot=JSON.stringify([t,Ce,n,Le,x,s?.asset.owner,s?.asset.location,s?.asset.receiptTokenId,s?.asset.address,s?.asset.chainId,s?.asset.decimals,n==="input"?s?.amount:l,qe.map(Pe=>Pe.toLowerCase()),a,o.address.toLowerCase(),o.chainId,o.decimals,i?.toLowerCase(),d,oe,ge?.source.address.toLowerCase()??""]),Qe=u.useMemo(()=>({}),[ot,ne,Ie,p,F]),Ge=he?.request===Qe&&(!oe||he.expiresAt>Date.now());return u.useEffect(()=>{if(!oe||he?.request!==Qe)return;const Pe=setTimeout($,Math.max(0,he.expiresAt-Date.now()));return()=>clearTimeout(Pe)},[oe,he,Qe,$]),u.useEffect(()=>{be.current&&clearTimeout(be.current),xe(Qe),ae(null),b(null);const Pe=n==="input"?s?.amount:l,Te=parseFloat(Pe||"0");if(!t||!Number.isFinite(Te)||Te<=0||!s?.asset||!i||qe.length===0){se.current++,S(null),B(null),j(null),T(null),M(null),L(null),U(null),G(null),b(null),C(!1);return}const Ke=s.asset.decimals;let st;try{st=n==="input"?qt(s.amount,Ke):qt(l||"0",o.decimals)}catch(me){se.current++,b(me instanceof Error?me.message:"Invalid amount or token precision"),C(!1);return}const Se=++se.current,De=()=>Se!==se.current;C(!0);const gt=n==="output"?150:400,te=async(me,ye,K,ze={chainId:a,tokenOut:o.address,amountIn:st},Ae=qe)=>{for(const Fe of Ae){const Ee=`${x}:${Ce}:${n}:${ze.chainId}:${Fe.toLowerCase()}:${ze.tokenOut.toLowerCase()}:${ze.amountIn.toString()}:${i.toLowerCase()}:${d??"default"}:${oe??"default"}`,ie=W.current.get(Ee),Q=ie&&ie.expiresAt>Date.now()?me(ie):void 0;if(Q)return{quote:Q,tokenIn:Fe,expiresAt:ie.expiresAt};const we=await K(Fe);if(De())return"stale";if(!we)continue;const He=Date.now()+Math.min(oe??3e4,3e4);return W.current.set(Ee,{expiresAt:He,direction:n,...ye(we)}),{quote:we,tokenIn:Fe,expiresAt:He}}return null},Ue=me=>te(ye=>ye.resolvedSwap,ye=>({resolvedSwap:ye}),async ye=>{const K=!ge&&me.chainId===a&&s.asset._source!=="wallet",ze=K?await xn(s.asset,ye,me.chainId,o):Ke;if(De())return null;const Ae=K?Ms(me.amountIn,Ke,ze):me.amountIn;if(f.addressesEqual(ye,me.tokenOut))return ki(Ae);const Fe={type:"swap",tokenIn:ye,tokenOut:me.tokenOut,amountIn:Ae,maxSlippage:d};if(p){const Ee=await p(Fe,me.chainId,i);if(Ee)return Ee}return ne.resolveSwap(Fe,me.chainId,i)},me,me.candidates);return be.current=setTimeout(async()=>{try{if(n==="input"){let me=null,ye=st;if(ge){if(me=await Ue({chainId:ge.source.chainId,tokenOut:ge.source.address,amountIn:st,candidates:[s.asset.address]}),me==="stale"||De())return;if(!me)throw new Error("No liquidity for this pair");ye=Pt(me.quote.amountOutMinimum,ge.source.decimals,ge.destination.decimals,"floor")}const K=Le||!ge?await Ue({chainId:a,tokenOut:o.address,amountIn:ye,candidates:qe}):null;if(K==="stale"||De())return;if(Le&&!K)throw new Error("No liquidity for this pair");const ze=K?K.quote.amountOut:ye,Ae=Math.min(K?.expiresAt??1/0,me?.expiresAt??1/0),Fe=ge?.destination.decimals??await xn(s.asset,K.tokenIn,a,o),Ee=!ge&&s.asset._source!=="wallet"?Ms(ye,Ke,Fe):ye;if(De())return;G(K?.tokenIn??ge?.destination.address??null),ae({request:Qe,key:`${A.keccak256(A.toHex(ot))}:${Se}`,expiresAt:Ae}),U(ze),Y(Ee),J(Fe),j(Le?K?.quote??null:null),T(me?.quote??null),M(null),L(null);const ie=parseFloat(A.formatUnits(ze,o.decimals));S(ie<.01?ie.toPrecision(4):ie.toLocaleString(void 0,{maximumFractionDigits:6})),B(null),b(null)}else{const me=Ee=>te(ie=>ie.exactOutputSwap,ie=>({exactOutputSwap:ie}),async ie=>{try{return f.addressesEqual(ie,Ee.tokenOut)?Si(Ee.amountOut):await Ie.getQuote({tokenIn:ie,tokenOut:Ee.tokenOut,amountOut:Ee.amountOut,maxSlippage:d},Ee.chainId,i)}catch{return null}},{chainId:Ee.chainId,tokenOut:Ee.tokenOut,amountIn:Ee.amountOut},Ee.candidates),ye=!ge||Le,K=ye?await me({chainId:a,tokenOut:o.address,amountOut:st,candidates:qe}):null;if(K==="stale"||De())return;if(ye&&!K)throw new Error("No liquidity for this pair");let ze=null;if(ge){const Ee=K?K.quote.amountInMax:st;if(ze=await me({chainId:ge.source.chainId,tokenOut:ge.source.address,amountOut:Pt(Ee,ge.destination.decimals,ge.source.decimals,"ceil"),candidates:[s.asset.address]}),ze==="stale"||De())return;if(!ze)throw new Error("No liquidity for this pair")}const Ae=ze?Ke:await xn(s.asset,K.tokenIn,a,o);if(De())return;G(K?.tokenIn??ge?.destination.address??null),ae({request:Qe,key:`${A.keccak256(A.toHex(ot))}:${Se}`,expiresAt:Math.min(K?.expiresAt??1/0,ze?.expiresAt??1/0)}),L(K?.quote??null),M(ze?.quote??null),j(null),T(null),U(null);const Fe=ze?.quote.amountIn??K.quote.amountIn;B(A.formatUnits(Fe,Ae)),S(null),b(null)}}catch(me){if(De())return;const ye=me instanceof Error?me.message:"Failed to get quote";b(ye),S(null),B(null),j(null),T(null),M(null),L(null),U(null),G(null)}finally{De()||C(!1)}},Le||ge?gt:0),()=>{se.current++,be.current&&clearTimeout(be.current)}},[Qe]),{inputAmount:Ge&&n==="input"?X:null,inputDecimals:Ge&&n==="input"?V:null,quoteKey:Ge?he.key:null,quoteExpiresAt:Ge?he.expiresAt:null,refreshQuote:$,isQuoting:re===Qe?y:Le||!!ge,quoteError:re===Qe?w:null,estimatedOutput:Ge?I:null,estimatedInput:Ge?v:null,resolvedSwap:Ge?E:null,exactOutputSwap:Ge?D:null,quoteAmountOut:Ge?R:null,resolvedTokenIn:Le&&Ge?ce??$e:$e,isDirect:Ve,needsSwap:Le,selectedIsEquivalent:nt,sourceSwap:Ge?N:null,sourceExactOutputSwap:Ge?P:null,pivot:ge}}function ds(e){const{enabled:t,destinationToken:n,selectedAsset:s,paymentAmount:o="0",sourceChains:a,supportedSourceAssets:i,buildActionCalls:l,feeExecutionMode:d="user-transfer",buildSpicenetBatch:c,onPayExecute:p,resolveExactOutputSwap:m,amountDirection:h="input",onSuccess:g,onError:x}=e,y=h==="output",C=h==="input-inclusive",w=y?"output":"input",b=n.chainId,I=u.useContext(f.SpiceFlowProviderContext),S=I?.mode||"7702",v=!1,B=p?"Move onPayExecute protocol calls to buildActionCalls and application updates to onSuccess before continuing.":e.actionExecution?.wallet==="external"?"This action requires the external wallet as its caller. Configure a beneficiary-capable embedded action before upgrading this integration.":null,E=!!I?.isWhitelistGateActive,j=!!I?.isWhitelistConfigured&&I?.isUserWhitelisted!==!0,N=u.useMemo(()=>a??I?.supportedChainIds??[],[a,I?.supportedChainIds]),T=i,{address:P,isConnected:M,isReady:D,isAuthenticated:L,provider:R}=f.useWallet(),{execute:U,estimate:X}=Rs(),{externalWallet:Y,embeddedAddress:V,activeWallet:J,activeAddress:ce}=f.useProviderWallets(),G=I?.externalWalletAddress,q=I?.embeddedWalletAddress||V,Z=e.sourceFundingRecoveryKey??e.actionExecution?.recoveryKey??`${n.chainId}:${n.address.toLowerCase()}:${h}`,_=za(q,Z),H=_.selection?Ln(_.selection):"",F=u.useMemo(()=>_.selection,[H])??s,de=Hr(F?.asset,S!=="7702"),{displayAssets:re,filteredSpiceAssets:xe,walletAssets:he,embeddedWalletAddress:ae,refreshSpiceAssets:be,refreshWalletAssets:O,loading:se,refreshing:W,error:$}=vi({address:P,destinationToken:n,supportedSourceAssets:T,sourceChains:N,additionalSourceTokens:[...e.additionalSourceTokens??[],...F?.asset._source==="wallet"?[{address:F.asset.address,chainId:F.asset.chainId,decimals:F.asset.decimals,symbol:F.asset.symbol,name:F.asset.name,logoURI:F.asset.logoURI}]:[]],includeExternalWalletAssets:e.includeExternalWalletAssets,includeCrossChainEmbeddedAssets:e.includeCrossChainEmbeddedAssets,enabled:t&&(S!=="7702"?!!G:!!q)}),oe=re,Ce=F?[...he,...xe].find(le=>ct(le)===ct(F.asset)):void 0,Me=u.useMemo(()=>F&&Ce?{...F,asset:Ce}:F,[F,Ce]),ne=F?vn(Ce??F.asset,"spend-source",{allowedTokens:I?.allowedTokens,rpcOverrides:I?.rpcOverrides,liquidityVenues:I?.liquidityVenues,isWhitelistGateActive:E},n,T):null,Ie=_.record?F?.asset.balance??0n:Ce?Ce.balance<(F?.asset.balance??0n)?Ce.balance:F.asset.balance:0n,[ge,Ye]=u.useState(!1),[tt,dt]=u.useState(!1),[Xe,$e]=u.useState(null),qe=u.useRef(x);qe.current=x;const nt=u.useCallback(le=>{$e(le),typeof le=="string"&&le&&qe.current?.(new Error(le),f.getRelayerErrorDetail(le))},[]),[Ve,Re]=u.useState("idle"),[Le,ot]=u.useState(""),[Qe,Ge]=u.useState(null),[Pe,Te]=u.useState(!1),[Ke,st]=u.useState(null),[Se,De]=u.useState(null),[gt,te]=u.useState(!1),[Ue,me]=u.useState(!1),[ye,K]=u.useState(null),ze=u.useRef(F),Ae=u.useRef(!1),Fe=u.useRef(null),Ee=u.useRef(null),ie=u.useRef(null),Q=u.useRef(null),we=u.useRef(null),He=u.useRef(null),Et=u.useRef(g),Ft=u.useRef(null),[ve,wt]=u.useState(null),[ut,St]=u.useState(null),[Kt,on]=u.useState(!1),[pn,Zt]=u.useState(0);u.useEffect(()=>{ze.current=F},[F]);const at=ae||V||P,rt=Ii({enabled:t&&!j,direction:w,selectedAsset:F,destinationToken:n,chainId:b,recipient:at,paymentAmount:o,resolveExactOutputSwap:m,resolveInputSwap:e.resolveInputSwap,maxSlippage:e.maxSlippage,refreshIntervalMs:3e4}),bt=rt,Oe=rt,{isQuoting:Ht,resolvedSwap:Rt,exactOutputSwap:Mt,quoteAmountOut:mt,resolvedTokenIn:We,isDirect:Dt,needsSwap:jt,selectedIsEquivalent:Vt,sourceSwap:It,sourceExactOutputSwap:ke,pivot:je}=bt,Ct=y?parseFloat(o||"0"):parseFloat(F?.amount||"")||0,pt=F?.asset?._source==="wallet",xt=!!F?.asset&&pt&&F.asset.chainId!==b,fn=F?Number(A.formatUnits(Ie,F.asset.decimals)):0,qn=u.useMemo(()=>{if(!F||y)return!1;try{return qt(F.amount||"0",F.asset.decimals)>Ie}catch{return!0}},[F,y,Ie]);u.useEffect(()=>{t||(nt(null),Ye(!1),Re("idle"),ot(""),Ge(null),Te(!1),st(null),De(null),te(!1),me(!1),K(null),Ae.current=!1,Fe.current&&(Fe.current.abort(),Fe.current=null))},[t]);const Tn=u.useCallback(le=>{Re({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[le.step]||"executing"),ot(le.message),le.txHash&&Ge(le.txHash)},[]),ee=u.useMemo(()=>({currentPaymentAmount:o,isFeeInclusiveInput:C,feeOnlyAction:e.feeOnlyAction,swapInputAmount:bt.inputAmount,destinationToken:n,embeddedWalletAddress:ae,providerEmbeddedAddress:V,externalWalletAddress:G,address:P,recipient:e.recipient??(S!=="7702"?G:void 0),isNon7702:v,isPayMode:y,resolvedChainId:b,buildActionCalls:l,feeExecutionMode:d,buildSpicenetBatch:c,selectedAsset:F,needsSwap:jt,resolvedSwap:Rt,exactOutputSwap:Mt,quoteAmountOut:mt,resolvedTokenIn:We,sourceSwap:It,sourceExactOutputSwap:ke,pivot:je,resolveSourceExactOutputSwap:async le=>{if(!je||!at)throw new Error("Swap route is not ready.");const kt=await au({chainId:je.source.chainId,recipient:at,tokenIn:F.asset.address,tokenOut:je.source.address,amountOut:le,liquidityVenues:I?.liquidityVenues,maxSlippage:e.maxSlippage}).catch(()=>null);if(!kt)throw new Error("No liquidity for this pair.");return kt},resolveInputSwap:async le=>{if(!We||!at)throw new Error("Swap route is not ready.");return Jo({chainId:b,recipient:at,tokenIn:We,tokenOut:n.address,amountIn:le,liquidityVenues:I?.liquidityVenues,maxSlippage:e.maxSlippage,resolveInputSwap:e.resolveInputSwap})}}),[o,n,ae,V,G,P,e.recipient,e.feeOnlyAction,e.maxSlippage,e.resolveInputSwap,bt.inputAmount,C,S,v,y,b,l,d,c,F,jt,Rt,Mt,mt,We,It,ke,je,at,I?.liquidityVenues]),ue=u.useCallback(le=>Vo({...ee,requestTimestampMs:Ee.current??Date.now()},le),[ee]),Be=ee,_e=u.useCallback(le=>Ws({...Be,requestTimestampMs:Ee.current??Date.now()},le),[Be]),it=u.useMemo(()=>F?.asset?je?je.destination.address:jt&&We?We:F.asset.chainId===b?F.asset.address:We??Wt(F.asset,b)??n.address:n.address,[F,n.address,jt,b,We,je]),et=A.keccak256(A.stringToHex(JSON.stringify([F&&ct(F.asset),F?.amount,o,h,n.address,n.chainId,n.decimals,e.recipient,Z,S,G,ae,I?.apiUrl,I?.rpcOverrides,e.maxSlippage,d,e.feeOnlyAction,I?.liquidityVenues,I?.allowedTokens,E,T,N]))),vt=_.record?.actionFunding?.identity&&_.record.actionFunding.identity!==et?"Restore the original wallet mode, beneficiary and configuration to continue this funded action.":null,ht=u.useRef({key:et,buildActionCalls:l,enabled:t,sourceBalance:Ie});ht.current={key:et,buildActionCalls:l,enabled:t,sourceBalance:Ie};const At=u.useRef(null),yt=u.useRef(!1),Ut=u.useCallback(()=>(Ee.current=Date.now(),He.current?He.current():yt.current?(yt.current=!1,Et.current=we.current.onSuccess,At.current={key:ht.current.key,quote:we.current.feeQuote},gi(we.current)):Promise.resolve()),[]),Nt=u.useMemo(()=>F?.asset?f.addressesEqual(F.asset.address,n.address)&&F.asset.chainId===n.chainId:!1,[F,n.address,n.chainId]),Yt=!1,mn=null,Cn=j,rn=(C||!!je)&&!!Se&&Se.netAmount===0n,Xt=u.useMemo(()=>(!!F?.asset||!!e.actionProceeds)&&(Ct>0||!!e.feeOnlyAction),[F,Ct,e.actionProceeds,e.feeOnlyAction]),Qt=u.useMemo(()=>!t||!Xt||Yt||!F?.asset&&!e.actionProceeds?null:[et,y?"pay":"supply",h,F?ct(F.asset):"proceeds",JSON.stringify(I?.rpcOverrides),I?.apiUrl,e.recipient,F?.asset.address.toLowerCase(),F?.asset.chainId,F?.amount,o,n.address.toLowerCase(),n.chainId,b,Oe.resolvedTokenIn?.toLowerCase()??"",Oe.quoteKey,Oe.needsSwap?"swap":"direct",Oe.isDirect?"direct-token":"routed-token","7702",Nt?"source-dest":"cross-chain",Oe.isQuoting?"quoting":"quoted",Oe.exactOutputSwap?.amountIn?.toString()??"",Oe.exactOutputSwap?.amountInMax?.toString()??"",Oe.exactOutputSwap?.venue??"",Oe.resolvedSwap?.amountOut?.toString()??"",Oe.quoteAmountOut?.toString()??"",Oe.sourceSwap?.amountOutMinimum?.toString()??"",Oe.sourceExactOutputSwap?.amountInMax?.toString()??"",Oe.pivot?.source.address.toLowerCase()??"",ae??"",V??"",P??""].join("|"),[t,et,e.actionProceeds,e.feeOnlyAction,ge,Ve,Xt,Yt,F,y,h,o,n,b,Oe,v,Nt,ae,V,P]),z=u.useCallback(async(le,kt)=>await is({signal:le,feeOnlyAction:e.feeOnlyAction,actionProceeds:e.actionProceeds,liquidityVenues:I?.liquidityVenues,maxSlippage:e.maxSlippage,resolveExactOutputSwap:m,selectedAsset:F,isPayMode:y,isFeeInclusiveInput:C,parsedAmount:Ct,needsSwap:Oe.needsSwap,exactOutputSwap:Oe.exactOutputSwap,isNon7702:v,isSourceDestToken:Nt,currentPaymentAmount:o,destinationToken:n,feeExecutionMode:d,resolvedTokenIn:Oe.resolvedTokenIn,embeddedWalletAddress:ae,providerEmbeddedAddress:V,resolvedChainId:b,isConnected:M,address:P,ready:D,authenticated:L,isDirect:Oe.isDirect,resolvedSwap:Oe.resolvedSwap,sourceSwap:Oe.sourceSwap,sourceExactOutputSwap:Oe.sourceExactOutputSwap,pivot:Oe.pivot,isQuoting:Oe.isQuoting,executionTokenAddress:it,buildPayChainBatches:ue,buildSupplyChainBatches:_e,estimate:X,...kt}),[F,e.feeOnlyAction,e.actionProceeds,e.maxSlippage,m,I?.liquidityVenues,y,C,Ct,Oe,v,Nt,o,n,d,ae,V,ue,X,b,M,P,D,L,_e,it]);u.useEffect(()=>{ie.current=z},[z]);const pe=u.useCallback(async le=>{if(y)return null;if(!F||ct(le)!==ct(F.asset)||!at||!We)throw new Error("Select a source before calculating Max.");let kt=le.balance;if(de&&(le.isNative||k.isNativeToken(le.address))){if(!G)throw new Error("Connect the source wallet before calculating Max.");const Bt=await ca({client:f.getClientForChain(le.chainId),account:G,recipient:at,token:le.address,isNative:!0,amount:1n});kt-=Bt}return hi({balance:kt,decimals:le.decimals,planForAmount:async Bt=>{const ft={...ee,selectedAsset:{asset:le,amount:A.formatUnits(Bt,le.decimals)}};let Tt=Bt;return je?(ft.sourceSwap=await Jo({chainId:le.chainId,recipient:at,tokenIn:le.address,tokenOut:je.source.address,amountIn:Bt,maxSlippage:e.maxSlippage,liquidityVenues:I?.liquidityVenues,resolveInputSwap:e.resolveInputSwap}),Tt=Pt(ft.sourceSwap.amountOutMinimum,je.source.decimals,je.destination.decimals,"floor")):Tt=Ms(Bt,le.decimals,await xn(le,We,b,n)),ft.resolvedSwap=jt?await ft.resolveInputSwap(Tt):null,ft.swapInputAmount=Tt,ft.quoteAmountOut=ft.resolvedSwap?.amountOut??Tt,z(void 0,{selectedAsset:ft.selectedAsset,parsedAmount:Number(ft.selectedAsset.amount),sourceSwap:ft.sourceSwap,resolvedSwap:ft.resolvedSwap,isQuoting:!1,buildSupplyChainBatches:$t=>Ws(ft,$t)})}})},[F,ee,y,at,We,b,n,de,G,je,jt,z,e.maxSlippage,e.resolveInputSwap,I?.liquidityVenues]);Ao({shouldRun:t&&!ge&&Ve==="idle"&&Xt&&!Yt&&!Oe.isQuoting&&!!Qt,deps:[t,ge,Ve,Xt,Yt,mn,Oe.isQuoting,Qt],onSkip:()=>{if(!t){te(!1),me(!1),K(null),De(null);return}if(ge||Ve!=="idle"){te(!1);return}if(!Xt){De(null),te(!1),me(!1),K(null);return}Oe.isQuoting&&(te(!1),me(!1))},onCleanup:()=>te(!1),delayMs:500,backgroundIntervalMs:5e3,run:async({isBackground:le,isCurrent:kt,signal:Bt})=>{const ft=Qt;le||(K(null),te(!0));try{const Tt=await ie.current?.(Bt);if(!kt())return;Tt&&ft?(Tt.expiresAt=Math.min(Date.now()+3e4,Oe.quoteExpiresAt??1/0),Q.current={key:ft,quote:Tt},De(Tt.preview),me(!0)):(Q.current=null,De(null),me(!1)),K(null)}catch(Tt){if(!kt())return;if(le&&Q.current?.key===ft){console.warn("[SpiceSupply] fee refresh failed:",Tt);return}const $t=f.sanitizeError(Tt,"Unable to calculate fees for this action.");Q.current=null,De(null),me(!1),K($t)}finally{kt()&&te(!1)}}});const Ne=u.useCallback(()=>(Ee.current=Date.now(),He.current?He.current():yt.current?(yt.current=!1,Et.current=we.current.onSuccess,At.current={key:ht.current.key,quote:we.current.feeQuote},xi(we.current)):Promise.resolve()),[]),fe=y&&Ke?.status==="success"?Ke.txHash:Ve==="success"?Qe:null;u.useEffect(()=>{!fe||Ft.current===fe||(Ft.current=fe,on(!0),St(null),Promise.resolve().then(()=>Et.current?.(fe)).then(()=>{for(const le of kn(q??""))le.actionFunding?.identity===et&&le.actionFunding.completedHash===fe&&Is(le.embeddedWalletAddress,le.chainId,le.tokenAddress);wt(fe),be()}).catch(le=>{St(`Transaction confirmed; application update needs retry: ${f.sanitizeError(le,"Unable to finalize the action")}`)}).finally(()=>on(!1)))},[fe,pn]);const Ze=!!fe&&ve!==fe,lt=Ze&&!ut,an=u.useCallback(()=>{Ft.current=null,Zt(le=>le+1)},[]),fs=u.useCallback(()=>{Te(!1),st(null),Ae.current=!1,be(),O()},[be,O]),Je=Qt&&Q.current?.key===Qt?Q.current.quote:null,hn=Je?.sourceSpendCap,gn=Je?.destinationAmount,tr=hn!==void 0&&!_.record?.actionFunding?.submitted?wi(_.record,hn,gn):null,ms=()=>{if(B)throw new Error(B);if(!ht.current.enabled||ht.current.key!==et)throw new Error("The source, amount, beneficiary or configuration changed. Review the form before continuing.");if(F&&(!Je||(Je.expiresAt??0)<=Date.now()))throw new Error("The quote expired. Review the refreshed quote before submitting.");if(_.error||vt)throw new Error(_.error??vt);if(F&&(Je?.sourceSpendCap??0n)>ht.current.sourceBalance)throw new Error("The source balance changed. Review the available amount before continuing.");if(F&&!ne?.eligible)throw new Error(ne?.reason??"This source is unavailable.")},Hs=async()=>{ms();const le=_.record?.actionFunding?.actionDefinition;le&&await cs(ls(le),ht.current.buildActionCalls),Je?.actionDefinition&&await cs(Je.actionDefinition,ht.current.buildActionCalls),ms()},nr=le=>({...le,sourceSpendCap:Je?.sourceSpendCap,minimumDestinationAmount:Je?.destinationAmount}),hs=F&&Je?.sourceSpendCap!==void 0?Je.sourceSpendCap>Ie:qn,sr={...ee,resolvedSwap:Je?.destinationSwap??ee.resolvedSwap,swapInputAmount:Je?.swapInputAmount??ee.swapInputAmount};we.current={selectedAsset:F,parsedAmount:Ct,currentPaymentAmount:o,isInsufficientBalance:hs,isPayMode:y,isFeeInclusiveInput:C,feeOnlyAction:e.feeOnlyAction,actionProceeds:e.actionProceeds,validateFeeQuote:ms,isNon7702:v,isSourceDestToken:Nt,needsSwap:jt,exactOutputSwap:Mt,selectedIsEquivalent:Vt,resolvedTokenIn:We,sourceSwap:It,sourceExactOutputSwap:ke,pivot:je,embeddedWalletAddress:ae,providerEmbeddedAddress:V,externalWallet:Y,externalWalletAddress:G,activeSignerWallet:J,activeSignerAddress:ce,address:P,isConnected:M,ready:D,authenticated:L,provider:R,resolvedChainId:b,executionTokenAddress:it,destinationToken:n,buildActionCalls:l,feeExecutionMode:d,buildSpicenetBatch:c,onPayExecute:p,onSuccess:g,feeQuote:Je,execution:{estimate:(le,kt,Bt,ft)=>X(le,kt,Bt,{...ft,userOverride:at}),execute:(le,kt,Bt,ft,Tt,$t)=>bi({asset:F?.asset??{...n,name:n.symbol,balance:0n,balanceFormatted:0,balanceUsd:0,isNative:!1,_source:"spice",owner:at,location:"rollup"},embedded:at,external:G,externalWallet:Y,fundExternal:de,sourceSpendCap:Je?.sourceSpendCap??0n,identity:et,purpose:Z,selection:F,minimumDestinationAmount:Je?.destinationAmount,actionDefinition:Je?.actionDefinition?Ln(Je.actionDefinition):void 0,assertCurrent:Hs,onFunding:()=>ot("Transfer the selected source to your embedded wallet"),run:Xi=>U(le,kt,Bt,ft,Tt,{...$t,...Xi,userOverride:at,requireDestinationReceipt:!0,validateBeforeSubmit:async Ji=>{await Hs(),await $t?.validateBeforeSubmit?.(Ji)}})}),buildPayChainBatches:le=>Vo(sr,nr(le)),buildSupplyChainBatches:le=>Ws(sr,nr(le)),onProgress:Tn},ui:{setError:nt,setStep:Re,setStatusMsg:ot,setTxHash:Ge,setIsExecuting:Ye,setShowStatusPanel:Te,setPaymentResult:st},refs:{spiceDepositSubmittedRef:Ae,abortControllerRef:Fe}};const Bn=!!e.isZeroAmountPay&&!e.feeOnlyAction&&y&&Ct===0,Hi=y?(Bn||!!F?.asset||!!e.actionProceeds)&&Ct>=0&&!hs&&!ge&&(Bn||Yt||Ue)&&!ye&&(Bn||e.feeOnlyAction||!jt||!!Mt)&&(Bn||e.feeOnlyAction||!je||!!ke)&&!Cn:!!F?.asset&&Ct>0&&!hs&&!ge&&Ue&&!ye&&!rn&&(je?!!It&&!Ht&&(Dt||!!Rt):xt||Dt||!!Rt&&!Ht)&&!Cn,or=!!_.record?.actionFunding?.submitted&&!ge&&!vt&&t;He.current=or?async()=>{const le=_.record;if(!(yt.current===!1||ge)){yt.current=!1,Et.current=g,Ye(!0),nt(null),ot("Checking the existing funded transaction...");try{const kt=async()=>{for(let ft=0;ft<3;ft++){const Tt=ht.current.buildActionCalls;le.actionFunding?.actionDefinition&&await cs(ls(le.actionFunding.actionDefinition),Tt);const $t=ht.current;if(!$t.enabled||$t.key!==et)throw new Error("Restore the original wallet mode, beneficiary and configuration to continue this funded action.");if($t.buildActionCalls===Tt)return}throw new Error("The action changed while checking recovery. Restore its original details and retry.")};await kt();const Bt=await eu(le);le.actionFunding.completedHash=Bt,_n(le),await kt(),Ge(Bt),y?st({status:"success",txHash:Bt}):Re("success")}catch(kt){nt(f.sanitizeError(kt,"Unable to reconcile this action"))}finally{Ye(!1)}}}:null;const rr=!B&&!tt&&!!at&&(S==="7702"||!!G)&&!Kt&&!ut&&(or||t&&!_.error&&!vt&&!tr&&Hi&&(Bn||!F&&!!e.actionProceeds||!!ne?.eligible)&&Ve!=="success"&&Ke?.status!=="success"&&!bt.quoteError&&(Bn||!!Qt&&Q.current?.key===Qt&&(Q.current.quote.expiresAt??0)>Date.now()));yt.current=rr;const Vi=u.useCallback(()=>{yt.current=!1,Q.current=null,me(!1),rt.refreshQuote(),Re("idle"),nt(null)},[rt.refreshQuote,nt]),Qi=u.useCallback(()=>{Te(!1)},[]),Gi=u.useCallback(()=>{Re("idle"),Ge(null),be()},[be]),Ot=Je??(Q.current?.key.startsWith(`${et}|`)?Q.current.quote:null)??(At.current?.key===et?At.current.quote:null),Ki=async le=>{if(de){if(!Je||le!==Je.sourceSpendCap)throw new Error("Use the displayed source funding maximum before preparing this action.");await bi({asset:F?.asset,embedded:at,external:G,externalWallet:Y,fundExternal:!0,sourceSpendCap:le,identity:et,purpose:Z,selection:F,minimumDestinationAmount:Je.destinationAmount,actionDefinition:Je.actionDefinition?Ln(Je.actionDefinition):void 0,assertCurrent:Hs,fundOnly:!0,run:async()=>{throw new Error("Funding preparation cannot submit an action")}})}},Zi=u.useMemo(()=>_.record?{matchesPurpose:!0,matchesSelection:!0,phase:_.record.actionFunding?.completedHash?"complete":_.record.actionFunding?.submitted?"routing":"funding",amount:_.record.amount}:null,[_.record]),Jt=_.record?.actionFunding,Yi=!y&&!e.feeOnlyAction&&!e.actionProceeds&&!ge&&!Kt&&!_.error&&!vt&&Jt?.source&&!Jt.source.pending&&!Jt.submitted&&!Jt.intentId&&!Jt.completedHash&&Jt.actionDefinition&&Jt.minimumDestinationAmount&&Je?.actionDefinition&&(Je.expiresAt??0)>Date.now()&&hn!==void 0&&gn!==void 0&&hn===BigInt(_.record.rawAmount)&&BigInt(Jt.source.confirmedAmount)>=hn&&gn>0n&&gn<BigInt(Jt.minimumDestinationAmount)?{previousMinimum:BigInt(Jt.minimumDestinationAmount),minimum:gn,accepting:tt,accept:async()=>{if(!tt){dt(!0);try{await tu({record:_.record,sourceSpendCap:hn,minimumDestinationAmount:gn,actionDefinition:Ln(Je.actionDefinition),buildActionCalls:ht.current.buildActionCalls,assertCurrent:()=>{if(ms(),Q.current?.quote!==Je)throw new Error("The quote changed. Review its current minimum before accepting.")}}),nt(null),Re("idle")}catch(le){nt(f.sanitizeError(le,"Unable to accept this updated quote"))}finally{dt(!1)}}}}:null;return{selectedAsset:Me,fundingQuoteReview:Yi,capability:ne,assets:{selectable:oe,displayAssets:oe,filteredSpiceAssets:xe,embeddedWalletAddress:ae,externalAddress:G,isNon7702:S!=="7702",refreshSpiceAssets:be,refreshWalletAssets:O,loading:se,refreshing:W,error:$},quote:{...bt,hasSourceConversion:!!je,executionInput:je&&Ot?{address:je.destination.address,chainId:je.destination.chainId,decimals:je.destination.decimals,amount:Ot.preview.netAmount}:null,...Ot?.destinationSwap?{resolvedSwap:Ot.destinationSwap,inputAmount:Ot.swapInputAmount,estimatedOutput:A.formatUnits(Ot.destinationSwap.amountOut,n.decimals)}:{}},fees:{fundingConversion:Ot?.fundingConversion,proceedsUsed:Ot?.proceedsUsed,fundingShortfall:Ot?.grossFundingAmount,source:je&&Ot?{address:je.source.address,chainId:je.source.chainId,symbol:je.source.symbol,decimals:je.source.decimals,gasFee:Ot.sourceGasSkim??0n,spicenetFee:0n}:null,destinationAmount:Ot?.destinationAmount,sourceSpendCap:Ot?.sourceSpendCap,preview:Ot?.preview??Se,isLoading:gt,ready:!!Je&&(Je.expiresAt??0)>Date.now(),error:ye},amount:{sourceRequiredAmount:Ot?.sourceSpendCap??null,parsed:Ct,isInsufficientBalance:hs,sourceBalance:fn,feesExceedAmount:rn},status:{sourceFunding:Zi,finalizing:Kt||lt,finalizationError:ut,externalAction:null,step:Ze&&Ve==="success"?"executing":Ve,statusMsg:Ze?ut??"Transaction confirmed. Updating application...":Le,txHash:Qe,isExecuting:ge||lt,error:B||ut||Xe||_.error||vt||tr||ne?.reason||null,showStatusPanel:Pe,paymentResult:Ze&&Ke?.status==="success"?{...Ke,status:"processing"}:Ke},flags:{directExecutionFeeNote:Yt},retryFinalization:an,fundEmbeddedSource:Ki,canExecute:rr,submitSupply:Ut,submitPay:Ne,retrySupply:Vi,dismissPaymentStatus:Qi,resolveMaxAmount:pe,resetAfterSuccess:Gi,resetPaymentState:fs}}function iu(e){return`0x77${e.slice(4)}`}function Ai({userAddress:e,destinationChainId:t,deliveryToken:n,deliveryAmount:s,withdrawalAmount:o,deliveryRecipient:a,deliveryTransfers:i,requestTimestampMs:l}){const d=i?.length?i:[{token:n,recipient:a,amount:o??s}],c=d.reduce((g,x)=>g+x.amount,0n);if(c<=0n)return null;const p=l??Date.now(),m=BigInt(Math.floor(p/1e3)),h=iu(A.keccak256(A.encodeAbiParameters([{type:"address"},{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[e??a,n,a,c,BigInt(t),BigInt(p)])));return{chainId:k.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:[{to:k.ZERO_ADDRESS,value:0n,data:A.encodeFunctionData({abi:k.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${t}`,idempotenceKey:h,nbf:0n,exp:m+3600n,metadata:"{}",transfers:d.map(g=>({token:A.getAddress(g.token).toLowerCase(),to:A.getAddress(g.recipient).toLowerCase(),amount:g.amount}))}]})}]}}const us=ct;function Ei(e){const{asset:t,amount:n,recipient:s,owner:o,onSuccess:a}=e,i=t?.chainId??e.sourceChains?.[0]??0,l=u.useMemo(()=>k.getTokensForChain(i).find(w=>w.equivalenceGroup==="USDC"),[i]),[d,c]=u.useState(null),p=u.useRef(!1),m=u.useCallback((w,b)=>{if(!t||n<=0n||n>t.balance&&!p.current||!s||!o||f.addressesEqual(o,s))throw new Error("Enter a valid withdrawal amount and recipient.");if(b.chainId!==t.chainId||!f.addressesEqual(b.executorAddress??b.userAddress,o))throw new Error("The withdrawal wallet or network changed. Review the withdrawal again.");return ei(t.chainId,t.address,[{recipient:s,amount:n}]).calls},[t?.address,t?.chainId,t?.balance,n,s,o]),h=u.useMemo(()=>d?{asset:d,amount:"0"}:null,[d]),g=ds({enabled:e.enabled&&!!l&&!!t&&n>0n&&!!s&&!!o&&!f.addressesEqual(o,s),feeOnlyAction:!0,isZeroAmountPay:!0,amountDirection:"output",paymentAmount:"0",destinationToken:{address:l?.address??k.ZERO_ADDRESS,symbol:l?.symbol??"USDC",decimals:l?.decimals??6,chainId:i},recipient:o,selectedAsset:h,sourceChains:e.sourceChains,includeCrossChainEmbeddedAssets:!0,includeExternalWalletAssets:!1,feeExecutionMode:"backend-transfer",buildActionCalls:m,buildSpicenetBatch:Ai,onError:(w,b)=>e.onError?.(w.message,b),sourceFundingRecoveryKey:`withdraw:${t?.chainId}:${t?.address.toLowerCase()}`,onSuccess:async()=>{t&&(window.dispatchEvent(new CustomEvent("withdraw-completed")),await a?.({token:t.symbol,amount:A.formatUnits(n,t.decimals),chainId:i}))}});p.current=g.status.sourceFunding?.phase==="routing"||g.status.sourceFunding?.phase==="complete";const x=`${e.enabled}:${t?.chainId}:${t?.address}:${n}:${s}`,y=u.useRef(x);u.useEffect(()=>{y.current===x||g.status.isExecuting||(y.current=x,(g.status.step==="success"||g.status.paymentResult?.status==="success")&&g.resetAfterSuccess())},[x,g.status.isExecuting,g.status.step,g.status.paymentResult?.status,g.resetAfterSuccess]);const C=u.useMemo(()=>l?g.assets.displayAssets.flatMap(w=>{if(w.location==="external")return[];const b=t&&w._source==="wallet"&&w.chainId===t.chainId&&f.addressesEqual(w.address,t.address)?n:0n,I=w.balance-b;return I>0n?[{...w,balance:I,balanceFormatted:Number(A.formatUnits(I,w.decimals))}]:[]}).sort((w,b)=>{const I=S=>S._source==="wallet"&&S.chainId===i?0:S._source==="spice"?1:2;return I(w)-I(b)||b.balanceFormatted-w.balanceFormatted}):[],[g.assets.displayAssets,l,i,t?.address,t?.chainId,n]);return u.useEffect(()=>{if(!e.enabled||g.status.isExecuting)return;const w=(d&&C.find(b=>us(b)===us(d)))??C[0]??null;(!d||!w||us(d)!==us(w)||d.balance!==w.balance)&&c(w)},[e.enabled,g.status.isExecuting,C,d]),{supply:g,candidates:C,source:d,setSource:c,feeToken:l,sourceKey:us}}const Fi=f.font.ui,lu=({label:e,loading:t,balance:n,dark:s,dk:o})=>{const a=s?o.textSecondary:"#7D7C7B",i=s?o.textSecondary:"#71757A";return r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[r.jsx("span",{style:{fontFamily:Fi,fontSize:"17px",fontWeight:500,color:a,lineHeight:"24px"},children:e}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",fontFamily:Fi,fontSize:"13px",fontWeight:500,color:i,lineHeight:"16px"},children:["Balance:"," ",t?"...":n===null?"\u2014":f.formatBalance(n)]})]})},ji=({isOpen:e,position:t,title:n,items:s,selectedId:o,onSelect:a,portalAttribute:i})=>{const{dark:l,dk:d,primaryColor:c}=f.useSpiceBrand(),[p,m]=u.useState(null),[h,g]=u.useState(!1);return u.useEffect(()=>{if(!e){g(!1);return}const x=requestAnimationFrame(()=>{requestAnimationFrame(()=>g(!0))});return()=>cancelAnimationFrame(x)},[e]),!e||!t||s.length===0?null:Hn.createPortal(r.jsxs("div",{[`data-${i}-popover`]:"true",style:{position:"fixed",top:`${t.top}px`,left:`${t.left}px`,opacity:h?1:0,transform:h?"scale(1) translateY(0)":"scale(0.96) translateY(-6px)",transition:`opacity 200ms ${f.easing.out}, transform 200ms ${f.easing.out}`,backgroundColor:l?d.shell:"#ffffff",borderRadius:"10px",padding:"10px 12px",boxShadow:l?"0 16px 48px rgba(0,0,0,0.45)":"0 12px 32px rgba(0,0,0,0.12)",border:`1px solid ${d.cardBorder}`,minWidth:"220px",zIndex:f.z.dropdown,fontFamily:f.font.mono},children:[r.jsx("div",{style:{marginBottom:"6px"},children:r.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:l?d.textPrimary:"#0e0d0b",textTransform:"uppercase",letterSpacing:"1px"},children:n})}),r.jsx("div",{style:{borderBottom:`1px solid ${d.cardBorder}`,marginBottom:"6px"}}),r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"2px"},children:s.map(x=>{const y=o===x.id,C=p===x.id;return r.jsxs("button",{onClick:w=>{w.stopPropagation(),a(x.id)},onMouseEnter:()=>m(x.id),onMouseLeave:()=>m(null),style:{display:"flex",alignItems:"center",gap:"8px",padding:"6px 4px",borderRadius:"8px",border:"none",cursor:"pointer",backgroundColor:y?l?d.hoverBg:"#f3f4f6":C?l?d.cardBg:"#f9fafb":"transparent",transition:"background-color 0.15s",width:"100%",fontFamily:f.font.mono},children:[x.icon&&r.jsx("img",{src:x.icon,alt:x.label,style:{width:"22px",height:"22px",borderRadius:"50%"}}),r.jsx("span",{style:{fontSize:"13px",fontWeight:y?700:500,textTransform:"uppercase",color:l?d.textPrimary:"#0e0d0b",letterSpacing:"0.5px",flex:1,textAlign:"left"},children:x.label}),x.detail&&r.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:d.textSecondary},children:x.detail}),y&&r.jsx(Ba,{color:c,style:{flexShrink:0}})]},x.id)})})]}),document.body)},zs=f.font.ui,cu=f.font.mono,du=170,uu=({header:e,amount:t,receiveAmountDisplay:n,receiveUsdEstimate:s,selectedDestToken:o,destTokenSymbol:a,destChainName:i,destChainLogo:l,compatibleDestinationChains:d,networkSwitchRef:c,onOpenNetworkPopover:p,showNetworkPopover:m,setShowNetworkPopover:h,networkPopoverPos:g,selectedChainId:x,setSelectedChainId:y,dark:C,dk:w})=>{const b=C?w.cardBg:"#E9E9E9",I=C?w.cardBorder:"#C6C6C6",S=C?w.textSecondary:"#71757A",v=C?w.textPrimary:"#0E0D0B",B=C?w.cardBorder:"#C5C5C4",E=C?"rgba(255,255,255,0.08)":"#D4D3D3",j=a.length>8?"14px":a.length>6?"16px":"18px";return r.jsxs("div",{style:{backgroundColor:b,border:`1px solid ${I}`,borderRadius:"7px",padding:"14px 16px 12px 16px",minHeight:"138px",display:"flex",flexDirection:"column",gap:"6px"},children:[e,r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[r.jsxs("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[r.jsx(An,{element:"div",value:n,title:n,fontFamily:zs,color:t?v:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,overflow:"wrap"}),r.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:S,fontFamily:zs,marginTop:"10px"},children:s})]}),r.jsxs("div",{style:{width:`${du}px`,flexShrink:0,display:"flex",flexDirection:"column",alignItems:"stretch",gap:"8px"},children:[r.jsxs("div",{style:{backgroundColor:"transparent",border:`1px solid ${B}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px"},children:[r.jsx("img",{src:o?.logoURI||Ql,alt:a,style:{width:"24px",height:"24px",borderRadius:"50%"}}),r.jsx("span",{style:{fontSize:j,fontWeight:500,color:v,lineHeight:"1.3",fontFamily:zs,flex:1,minWidth:0,letterSpacing:0},children:a})]}),r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:E,borderTop:`1px solid ${B}`},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[l&&r.jsx("img",{src:l,alt:i,style:{width:"13px",height:"13px",borderRadius:"50%",flexShrink:0}}),r.jsx("span",{style:{fontSize:"11px",fontWeight:400,color:v,fontFamily:zs,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:i})]}),r.jsx("button",{ref:c,onClick:N=>{N.stopPropagation(),p(c.current)},style:{background:"none",border:"none",cursor:d.length>1?"pointer":"not-allowed",padding:"0 0 0 8px",fontSize:"9.5px",fontFamily:cu,color:S,textDecoration:"underline",fontWeight:600,opacity:d.length>1?1:.45},children:"Switch"}),r.jsx(ji,{isOpen:m,position:g,title:"SELECT NETWORK",portalAttribute:"network",items:d.map(N=>{const T=f.getChainConfig(N);return{id:String(N),label:T?.displayName||String(N),icon:yn[N]||Kn}}),selectedId:x!==null?String(x):null,onSelect:N=>{y(Number(N)),h(!1)}})]})]}),r.jsx("div",{style:{minHeight:"14px"}})]})]})]})},pu=f.font.ui,bn=f.font.mono,fu=({show:e,onToggle:t,showCustomAddress:n,setShowCustomAddress:s,customRecipient:o,setCustomRecipient:a,externalAddress:i,recipientAddress:l,destChainName:d,destChainLogo:c,compatibleDestinationChains:p,txDetailsChainSwitchRef:m,onOpenNetworkPopover:h,sourceChainLabel:g,sourceDetailsLogo:x,sourceTokenLabel:y,amount:C,totalSourceDebitDisplay:w,receiveAmountDisplay:b,destTokenSymbol:I,shouldQuoteWithdrawGas:S,estimatingFee:v,feeError:B,displayedGasFee:E,selectedDestToken:j,theme:N,styles:T,dark:P,dk:M})=>{const D=P?M.textSecondary:"#71757A",L=P?M.textPrimary:"#0E0D0B",R=p.length>1,U=n&&o?A.isAddress(o)?f.truncateAddress(o):o:l?f.truncateAddress(l):"\u2014";return r.jsxs(r.Fragment,{children:[r.jsxs("div",{onClick:t,style:{display:"flex",alignItems:"center",gap:"6px",marginBottom:e?"10px":"0",cursor:"pointer",userSelect:"none"},children:[r.jsx("span",{style:{fontSize:"13px",color:D,fontFamily:pu,fontWeight:600},children:"Transaction Details"}),r.jsx($c,{size:12,color:D,style:{transform:e?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s"}})]}),e&&r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"7px"},children:[r.jsxs("div",{children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[r.jsx("span",{style:{fontSize:"12px",color:D,fontFamily:bn,fontWeight:500,letterSpacing:"0.03em"},children:"TO"}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[r.jsx("span",{style:{fontSize:"13px",color:L,fontFamily:bn,fontWeight:500},children:U}),r.jsx("button",{onClick:()=>{s(X=>!X),!n&&i&&a(i)},style:{background:"none",border:"none",cursor:"pointer",padding:"0",fontSize:"9.5px",fontFamily:bn,color:D,textDecoration:"underline",fontWeight:600},children:n?"Reset":"Switch"})]})]}),n&&r.jsxs("div",{style:{marginTop:"6px"},children:[r.jsx("div",{style:{marginBottom:"6px",padding:"7px 9px",borderRadius:"6px",border:"1px solid rgba(239, 68, 68, 0.55)",backgroundColor:"rgba(239, 68, 68, 0.12)",color:"#ef4444",fontSize:"10px",lineHeight:1.35,fontFamily:bn,fontWeight:700,letterSpacing:0,textTransform:"uppercase"},children:"CAUTION: ENTERING AN INCORRECT ADDRESS WILL RESULT IN LOSS OF FUNDS"}),r.jsx("input",{type:"text",autoComplete:"off",spellCheck:!1,"aria-label":"Recipient address","aria-invalid":o&&!A.isAddress(o)?!0:void 0,"data-spiceflow-focus":!0,value:o,onChange:X=>a(X.target.value),placeholder:"0x...",style:{width:"100%",padding:"8px 10px",borderRadius:"6px",border:`1px solid ${o&&!A.isAddress(o)?P?M.errorBorder:"#fca5a5":P?M.inputBorder:"#d1d5db"}`,backgroundColor:P?M.inputBg:"#f9fafb",color:P?M.inputText:"#111827",fontSize:"12px",fontFamily:bn,outline:"none",boxSizing:"border-box"}}),o&&!A.isAddress(o)&&r.jsx("span",{style:{fontSize:"11px",color:M.errorText,marginTop:"3px",display:"block"},children:"Invalid address"})]})]}),r.jsx(wn,{palette:M,labelColor:D,valueColor:L,label:"RECEIVING CHAIN",value:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"7px"},children:[c&&r.jsx("img",{src:c,alt:d,style:{width:"14px",height:"14px",borderRadius:"50%"}}),r.jsx("span",{style:{fontSize:"13px",color:L,fontWeight:500,fontFamily:bn,textTransform:"uppercase"},children:d}),r.jsx("button",{ref:m,onClick:X=>{X.stopPropagation(),h(m.current)},style:{background:"none",border:"none",cursor:R?"pointer":"not-allowed",padding:"0",fontSize:"9.5px",fontFamily:bn,color:D,textDecoration:"underline",fontWeight:600,opacity:R?1:.45},children:"Switch"})]})}),r.jsx(wn,{palette:M,labelColor:D,valueColor:L,label:"REQUESTED WITHDRAWAL",value:r.jsxs($o,{logo:x||null,alt:g,primaryText:L,children:[C||"0"," ",y]})}),S&&r.jsx(wn,{palette:M,labelColor:D,valueColor:L,label:"TOTAL SOURCE DEBIT",value:r.jsxs($o,{logo:x||null,alt:g,primaryText:L,children:[w," ",y]})}),r.jsx(wn,{palette:M,labelColor:D,valueColor:L,label:"YOU RECEIVE",value:r.jsxs($o,{logo:c,alt:d,primaryText:L,gap:"4px",children:[b," ",I]})}),S&&r.jsxs(r.Fragment,{children:[r.jsx(wn,{palette:M,labelColor:D,label:"EST. NETWORK FEE",valueColor:B?"#f87171":L,value:v?"Estimating...":B?"Unavailable":E!==null&&j?`${zo(E,j.decimals)} ${j.symbol}`:"Estimating..."}),B&&r.jsx(sn,{variant:"error",size:"compact",palette:M,fontFamily:T?.fontFamily||N.typography.fontFamily,children:B})]})]})]})},mu=u.memo(fu),$o=({logo:e,alt:t,primaryText:n,gap:s="6px",children:o})=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:s},children:[e&&r.jsx("img",{src:e,alt:t,style:{width:"13px",height:"13px",borderRadius:"50%"}}),r.jsx("span",{style:{fontSize:"13px",color:n,fontWeight:500,fontFamily:bn},children:o})]}),ps=f.font.ui,hu=170,gu=({header:e,amount:t,setAmount:n,isInsufficient:s,sourceAmountDecimals:o,selectedSourceAsset:a,resolvedSelectedSourceAsset:i,spiceAssets:l,setSelectedSourceAsset:d,sourceUsdEstimate:c,sourceTokenLabel:p,sourceChainLabel:m,totalSelectedBalance:h,showSourceTokenPopover:g,setShowSourceTokenPopover:x,tokenPopoverPos:y,setTokenPopoverPos:C,tokenTriggerRef:w,primaryColor:b,dark:I,dk:S})=>{const v=I?S.cardBg:"#E9E9E9",B=I?S.cardBorder:"#C6C6C6",E=I?S.textSecondary:"#71757A",j=I?S.textPrimary:"#0E0D0B",N=I?S.cardBorder:"#C5C5C4",T=I?"rgba(255,255,255,0.08)":"#D4D3D3",P=p.length>8?"14px":p.length>6?"16px":"18px";return r.jsxs("div",{style:{backgroundColor:v,border:`1px solid ${B}`,borderRadius:"7px",padding:"14px 16px 12px 16px",minHeight:"138px",display:"flex",flexDirection:"column",gap:"6px",position:"relative"},children:[e,r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[r.jsxs("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[r.jsx(An,{element:"input",ariaLabel:"Withdraw amount",ariaInvalid:s,dataSpiceflowFocus:!0,value:t,onChange:M=>{const D=M.target.value;if(D===""){n("");return}/^\d*\.?\d*$/.test(D)&&n(f.parseNumericInput(D.startsWith(".")?`0${D}`:D,o??a?.decimals))},placeholder:"0.0",fontFamily:ps,color:s?"#ef4444":t?j:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,style:{width:"100%"}}),r.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:E,fontFamily:ps,marginTop:"10px"},children:c})]}),r.jsx("div",{style:{width:`${hu}px`,flexShrink:0},children:r.jsxs("div",{style:{backgroundColor:"transparent",border:`1px solid ${N}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[r.jsxs("div",{ref:w,onClick:M=>{if(M.stopPropagation(),!g&&w.current){const D=w.current.getBoundingClientRect(),L=220,R=16;C({top:D.bottom+8,left:Math.min(Math.max(R,D.right-L),window.innerWidth-L-R)})}x(D=>!D)},style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px",cursor:"pointer"},children:[r.jsx("img",{src:po,alt:p,style:{width:"24px",height:"24px",borderRadius:"50%"}}),r.jsx("span",{style:{fontSize:P,fontWeight:500,color:j,lineHeight:"1.3",fontFamily:ps,flex:1,minWidth:0,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",letterSpacing:0},children:p}),r.jsx(Pn,{size:15,color:j,strokeWidth:2.25})]}),r.jsx(ji,{isOpen:g,position:y,title:"SELECT TOKEN",portalAttribute:"token",items:(l||[]).map(M=>({id:M.receiptTokenId||M.address,label:M.displaySymbol||M.receiptTokenName||M.symbol,icon:po,detail:f.formatBalance(M.balanceFormatted)})),selectedId:i?.receiptTokenId||i?.address||null,onSelect:M=>{const D=(l||[]).find(L=>(L.receiptTokenId||L.address)===M);D&&(d(D),n("")),x(!1)}}),r.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:T,borderTop:`1px solid ${N}`},children:r.jsx("span",{style:{fontSize:"11px",fontWeight:400,color:j,fontFamily:ps,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:m})})]})})]}),r.jsxs("div",{style:{minHeight:"18px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[s?r.jsx("span",{style:{fontSize:"12px",color:S.errorText,fontFamily:ps,fontWeight:500},children:"Insufficient Balance"}):r.jsx("span",{}),r.jsx("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0px",minHeight:"32px",marginRight:"-9px"},children:[0,25,50,75,100].map((M,D)=>{const L=D===4,R=parseFloat(t)||0,U=h>0&&Math.abs(R/h*100-M)<1;return r.jsx("button",{type:"button","aria-label":`Set amount to ${M}%`,"aria-pressed":U,onClick:()=>{const X=h*M/100,Y=a?.decimals??6,V=Math.floor(X*10**Y)/10**Y;n(M===0?"":V>0?f.formatDecimalInput(V,Y):"")},title:`${M}%`,disabled:h===0,"data-spiceflow-focus":!0,style:{width:"32px",height:"32px",padding:"9px",border:"none",backgroundColor:"transparent",cursor:h===0?"not-allowed":"pointer",opacity:U?1:.5,transition:"opacity 0.15s ease",display:"flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box"},children:r.jsx(No,{pct:M,isMax:L,primaryColor:b,dark:I,fillColor:I?S.textSecondary:"#3C3E42"})},M)})})]})]})},xu=({dark:e,dk:t})=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[r.jsx("img",{src:Io,alt:"","aria-hidden":"true",style:{width:"13px",height:"13px",flexShrink:0,...e?{filter:"invert(0.6)"}:{}}}),r.jsx("p",{style:{fontSize:"13px",color:e?t.textSecondary:"#979AA0",margin:"0",lineHeight:"1.4",fontFamily:f.font.ui},children:"Withdraw collateral from your account to 10+ EVM blockchains."})]});function yu(e){const{record:t}=e,n=u.useContext(f.SpiceFlowProviderContext),s=t.actionFunding.identity,o=t.actionFunding?.actionDefinition,a=t.actionFunding?.purpose,i=t.embeddedWalletAddress,[l,d]=u.useState(0),[c,p]=u.useState(),[,m,h]=a?.split(":")??[],g=e.knownAssets.find(C=>C.chainId===Number(m)&&f.addressesEqual(C.address,h));u.useEffect(()=>{let C=!0;return(async()=>{try{if(!o||!h||!A.isAddress(h))throw new Error("The original withdrawal details are unavailable. Preserve this pending action for reconciliation.");const w=ls(o),b=Number(m);if(w.context.chainId!==b||!f.addressesEqual(w.context.executorAddress??w.context.userAddress,i)||w.calls.length!==1)throw new Error("The original withdrawal details do not match this account.");const I=w.calls[0];let S,v;if(k.isNativeToken(h)){if(I.data!=="0x")throw new Error("Invalid original native withdrawal.");S=I.to,v=I.value}else{const j=A.decodeFunctionData({abi:A.erc20Abi,data:I.data});if(!f.addressesEqual(I.to,h)||I.value!==0n||j.functionName!=="transfer")throw new Error("Invalid original token withdrawal.");[S,v]=j.args}if(v<=0n||!A.isAddress(S)||f.addressesEqual(S,i))throw new Error("Invalid original withdrawal recipient or amount.");const B=k.getTokenByAddress(h,b),E=g??B??await na(f.getClientForChain(b),h);C&&p({identity:s,amount:v,recipient:S,asset:{address:h,chainId:b,symbol:E.symbol,name:E.name,decimals:E.decimals,balance:0n,balanceFormatted:0,balanceUsd:0,isNative:k.isNativeToken(h),owner:i,_source:"wallet",location:"embedded"}})}catch(w){C&&p({identity:s,error:f.sanitizeError(w,"Unable to restore the original withdrawal.")})}})(),()=>{C=!1}},[s,o,a,i,g?.symbol,g?.name,g?.decimals,n?.rpcOverrides?.[Number(m)],l]);const x=c?.identity===s?c:void 0,{supply:y}=Ei({enabled:!!x?.asset&&!!t.actionFunding?.submitted,asset:x?.asset??null,amount:x?.amount??0n,recipient:x?.recipient,owner:i,sourceChains:e.sourceChains,onSuccess:e.onSuccess,onError:e.onError});return r.jsxs("div",{style:{display:"grid",gap:16,padding:"16px 0"},children:[r.jsx("p",{children:"This account has a pending withdrawal."}),x?.asset?r.jsxs(r.Fragment,{children:[r.jsxs("div",{children:[A.formatUnits(x.amount,x.asset.decimals)," ",x.asset.symbol]}),r.jsxs("div",{style:{overflowWrap:"anywhere"},children:["To ",x.recipient]}),r.jsx(f.Button,{fullWidth:!0,disabled:!y.canExecute,loading:y.status.isExecuting,onClick:()=>void y.submitPay(),children:"Check withdrawal"})]}):x?.error?null:r.jsx("span",{role:"status",children:"Restoring withdrawal details\u2026"}),(x?.error||y.status.error)&&r.jsx("p",{role:"alert",children:x?.error||y.status.error}),x?.error&&r.jsx(f.Button,{onClick:()=>{p(void 0),d(C=>C+1)},children:"Retry details"}),y.status.finalizationError&&r.jsx(f.Button,{disabled:y.status.finalizing,onClick:()=>void y.retryFinalization(),children:"Retry application update"}),y.status.statusMsg&&r.jsx("span",{role:"status",children:y.status.statusMsg})]})}const wu=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,styles:s,onWithdrawExecute:o,onWithdrawSuccess:a,onWithdrawError:i,availableTokens:l,initialSourceAssetId:d,walletAssets:c,buildSpicenetBatch:p})=>{const m=u.useContext(f.SpiceFlowProviderContext);if(!m)return r.jsx("div",{children:"Error: SpiceWithdraw must be used within SpiceFlowProvider"});const h=m.mode||"7702",g=h==="presign"||h==="ondemand",x=m.supportedChainIds,y=m.allowedTokens,C=!!c,w=c?.initialAsset,b=u.useMemo(()=>[...c?.extraAssets??[],...w?[w]:[]].map(ee=>({address:ee.address,chainId:ee.chainId,symbol:ee.symbol,decimals:ee.decimals})),[c?.extraAssets,w]),I=m.isWhitelistGateActive,{theme:S,dark:v,dk:B}=f.useSpiceBrand(s),E=m.network,j=()=>g?"select":"provider-login",[N,T]=u.useState(j()),[P,M]=u.useState(!1),[D,L]=u.useState(null),[R,U]=u.useState(null),[X,Y]=u.useState(""),[V,J]=u.useState(!1),[ce,G]=u.useState(!1),[q,Z]=u.useState(!1),[_,H]=u.useState(""),[F,de]=u.useState(!0),re=u.useRef(null),xe=u.useRef(null),he=u.useRef(null),[ae,be]=u.useState(null),[O,se]=u.useState(null),W=f.useWallet(),{isReady:$,isAuthenticated:oe,address:Ce}=W,Me=m?.embeddedWalletAddress,ne=za(Me,"withdraw:",!0),{address:Ie,chainId:ge}=_t.useAccount(),Ye=m.externalWalletAddress||Ie,[tt,dt]=u.useState(!1),[Xe,$e]=u.useState(null),qe=u.useRef(i);qe.current=i;const nt=u.useCallback(ee=>{$e(ee),typeof ee=="string"&&ee&&qe.current?.(ee,f.getRelayerErrorDetail(ee))},[]),[Ve,Re]=u.useState(null),Le=u.useRef(null),ot=u.useRef(!0),Qe=u.useRef(null);u.useEffect(()=>(ot.current=!0,()=>{ot.current=!1}),[]);const{execute:Ge,estimate:Pe}=Rs(),[Te,Ke]=u.useState(null),[st,Se]=u.useState(null),[De,gt]=u.useState(!1),[te,Ue]=u.useState(null),{assets:me,loading:ye,error:K,refresh:ze}=Nn({owner:Me,role:"holding",includeWalletAssets:C,additionalSourceTokens:b,enabled:e&&!!Me}),Ae=u.useMemo(()=>{if(I)return[];const ee=(ue,Be)=>(Be.balanceUsd||0)-(ue.balanceUsd||0);return(me??[]).filter(ue=>ue.balance>0n&&vn(ue,"holding",{allowedTokens:y,isWhitelistGateActive:I}).eligible).sort(ee)},[me,y,I]),Fe=u.useMemo(()=>[...new Set([...x??[],...Object.keys(l??{}).map(Number),...(Ae||[]).map(ee=>ee.chainId),...(Ae||[]).flatMap(ee=>Object.keys(ee.chainTokens??{}).map(ue=>{const[,Be]=ue.split(":"),_e=Number(Be);return Number.isFinite(_e)?_e:null}).filter(ue=>ue!==null))])].filter(ee=>f.getChainConfig(ee)?.network===E),[x,l,Ae,E]),Ee=u.useMemo(()=>{if(l)return l;const ee={};for(const ue of Ae||[]){const Be=Object.entries(ue.chainTokens??{});if(Be.length>0){for(const[_e,it]of Be){const[et,vt,ht]=_e.split(":");if(et!=="evm"||!vt||!ht)continue;const At=Number(vt);if(!Number.isFinite(At))continue;const yt=ht.startsWith("0x")?ht.toLowerCase():`0x${ht.toLowerCase()}`,Ut=f.getChainConfig(At)?.supportedTokens?.find(Nt=>f.addressesEqual(Nt.address,yt));Ut&&io(ue,yt,At)&&(ee[At]||(ee[At]=[]),ee[At].find(Nt=>f.addressesEqual(Nt.address,yt))||ee[At].push({address:yt,symbol:Ut?.symbol||it?.name||ue.symbol,name:Ut?.name||it?.name||ue.displayName||ue.name||ue.symbol,decimals:Ut?.decimals??it?.decimals??ue.decimals,logoURI:Ut?.logo||ue.logoURI}))}continue}ee[ue.chainId]||(ee[ue.chainId]=[]),ee[ue.chainId].find(_e=>f.addressesEqual(_e.address,ue.address))||ee[ue.chainId].push({address:ue.address,symbol:ue.symbol,name:ue.displayName||ue.name||ue.symbol,decimals:ue.decimals,logoURI:ue.logoURI})}return ee},[l,Ae]),ie=u.useCallback((ee,ue)=>{const Be=wd(ee,ue,ue?Ee[ue]??[]:[]);return!ee||!Be||!ue||ee._source==="wallet"&&ue!==ee.chainId?null:vn(ee,"withdraw-destination",m,{...Be,chainId:ue}).eligible?Be:null},[Ee,m.allowedTokens,m.rpcOverrides,m.isWhitelistGateActive]),Q=u.useMemo(()=>D?Ae.find(ee=>ct(ee)===ct(D))??null:null,[D,Ae]),we=Q?._source==="wallet",He=u.useMemo(()=>{if(!Q)return[];const ee=Object.keys(Q.chainTokens??{}).map(ue=>cn(ue)?.chainId??null).filter(ue=>ue!==null);return Array.from(new Set([...ee,Q.chainId,...Fe].filter(Number.isFinite))).filter(ue=>f.getChainConfig(ue)?.network===E&&ie(Q,ue)!==null)},[Q,Fe,ie,E]),Et=u.useMemo(()=>{if(!Q||typeof window>"u")return null;const ee=`spiceflow:withdraw-chain:${Q.receiptTokenId||Q.address.toLowerCase()}`,ue=window.localStorage.getItem(ee),Be=ue?Number(ue):null;return Be!==null&&Number.isFinite(Be)&&He.includes(Be)?Be:null},[Q,He]),Ft=u.useMemo(()=>Q?Et!==null?Et:ge&&He.includes(ge)?ge:Q.chainId&&He.includes(Q.chainId)?Q.chainId:He[0]??null:Fe[0]??null,[Q,Et,ge,He,Fe]),ve=u.useMemo(()=>ie(Q,R),[ie,Q,R]);u.useEffect(()=>{e&&(L(null),Y(""))},[e,d,w?.address,w?.chainId]),u.useEffect(()=>{if(!e||!Ae.length||D)return;const ee=w?Ae.find(ue=>ue.chainId===w.chainId&&f.addressesEqual(ue.address,w.address)&&ue._source==="wallet"):d?Ae.find(ue=>ue.receiptTokenId===d):Ae[0];L(ee??null),Y("")},[e,Ae,D,d,w]),u.useEffect(()=>{Q&&(R===null||!He.includes(R))&&U(Ft)},[Q,R,Ft,He]),u.useEffect(()=>{if(!V&&!ce)return;const ee=ue=>{const Be=ue.target;V&&!re.current?.contains(Be)&&!xe.current?.contains(Be)&&!Be?.closest?.("[data-network-popover]")&&J(!1),ce&&!he.current?.contains(Be)&&!Be?.closest?.("[data-token-popover]")&&G(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[V,ce]);const wt=u.useCallback(ee=>{if(!ee||He.length<=1)return;const ue=ee.getBoundingClientRect(),Be=220,_e=16;be({top:ue.bottom+8,left:Math.min(Math.max(_e,ue.right-Be),window.innerWidth-Be-_e)}),J(it=>!it)},[He.length]),ut=u.useCallback(()=>de(ee=>!ee),[]);u.useEffect(()=>{if(!Q||R===null||typeof window>"u")return;const ee=`spiceflow:withdraw-chain:${Q.receiptTokenId||Q.address.toLowerCase()}`;window.localStorage.setItem(ee,String(R))},[Q,R]);const St=q?A.isAddress(_)?_:void 0:Ye||(we?void 0:Me),Kt=Nn({owner:St,role:"holding",includeRollupAssets:!1,sourceChains:R?[R]:[],additionalSourceTokens:ve&&R?[{...ve,chainId:R}]:[],enabled:e&&!!St&&!!ve&&!!R}),on=Kt.walletAssets.find(ee=>f.addressesEqual(ee.owner,St)&&ee.chainId===R&&f.addressesEqual(ee.address,ve?.address)),pn=Q?.balanceFormatted??0,Zt=Q?.displaySymbol||Q?.receiptTokenName||Q?.symbol||"Select token",at=Q?.displayChainName||(we?f.getChainConfig(Q.chainId)?.displayName:"Spicenet")||"Network",rt=Q?.receiptTokenDecimals??Q?.decimals,bt=u.useMemo(()=>{if(!ve||rt===void 0)return 0n;try{return qt(X||"0",rt)}catch{return 0n}},[X,ve,rt]),Oe=u.useMemo(()=>!ve||rt===void 0?0n:$a(bt,rt,ve.decimals),[ve,rt,bt]),Ht=u.useMemo(()=>{if(we)return 0n;const ee=st??Te;return!ee||ee<=0n||!ve||rt===void 0?0n:$a(ee,ve.decimals,rt)},[we,st,Te,ve,rt]),Rt=u.useMemo(()=>bt+Ht,[bt,Ht]),Mt=st??Te,mt=Ei({enabled:e&&we,asset:we?Q:null,amount:bt,recipient:St,owner:Me,sourceChains:x,onSuccess:a,onError:i}),We=mt.supply,Dt=tt||we&&(We.status.isExecuting||We.status.finalizing),jt=We.status.step==="success"||We.status.paymentResult?.status==="success",Vt=u.useCallback(ee=>{if(we||!R||!ve)return[];if(bt===0n||Oe===0n||!St)return[];const ue=Array.isArray(ee)?ee.filter(et=>et.amount>0n):[{token:ve.address,recipient:St,amount:ee??Oe}],Be=ue.reduce((et,vt)=>et+vt.amount,0n);if(Be<=0n)return[];const _e={chainId:R,calls:[],tokenTransfers:ue.map(et=>({from:"escrow",to:et.recipient,token:et.token,amount:et.amount}))};if(!p)return[_e];const it=p({destinationChainId:R,deliveryToken:ve.address,deliveryAmount:Be,deliveryRecipient:St,deliveryTransfers:ue,requestTimestampMs:Qe.current??Date.now()});return it?[it,_e]:[_e]},[we,R,ve,bt,Oe,St,p]),It=u.useMemo(()=>Vt(),[Vt]),ke=u.useMemo(()=>Ed(It,ve?.address),[It,ve?.address]),je=u.useRef(null),Ct=!we&&e&&!g&&!tt&&!!ve&&!!R&&bt!==0n;Ao({shouldRun:Ct&&It.length>0&&!!ke,deps:[Ct,It.length>0,ke],delayMs:500,onSkip:()=>{je.current=null,Ke(null),Ue(null),gt(Ct&&It.length===0)},onCleanup:()=>gt(!1),run:async({isCurrent:ee,signal:ue})=>{const Be=ke;gt(!0),Ue(null);try{const _e=await Ad({batches:It,tokenAddress:ve.address,chainId:R,estimate:Pe,signal:ue});if(!ee())return;je.current={key:Be,quote:_e},Ke(_e.gasFee)}catch(_e){if(!ee())return;je.current=null,Ke(null),Ue(_e instanceof Error?_e.message:"Failed to estimate gas fee")}finally{ee()&&gt(!1)}}}),u.useEffect(()=>{tt||Se(null)},[tt,X,R,ve?.address]);const pt=u.useCallback(()=>{M(!0),T("select")},[]),xt=u.useCallback(()=>{Dt||t()},[t,Dt]),fn=u.useRef(null);fn.current={batches:It,walletAddress:Ce,recipient:St,token:ve,chainId:R,amount:X,receiveAmountRaw:Oe,gasFee:Te,feeEstimate:ke&&je.current?.key===ke?je.current.quote.feeEstimate:null,isNon7702:g,buildWithdrawBatches:Vt,execution:{estimate:Pe,execute:Ge},ui:{setIsExecuting:dt,setExecutionError:nt,setExecutionProgress:Re,setLockedGasFee:Se},executionContextRef:Le,isMountedRef:ot,onWithdrawExecute:o,onWithdrawSuccess:a,buildSpicenetBatch:p};const qn=u.useCallback(()=>(Qe.current=Date.now(),Xa(fn.current)),[]),Tn=u.useCallback(()=>(Qe.current=Date.now(),Id(fn.current)),[]);if(u.useEffect(()=>{if(!e){const ee=setTimeout(()=>{T(j()),M(!1),L(null),U(null),Y(""),J(!1),G(!1),Z(!1),H(""),dt(!1),nt(null),Re(null),Le.current=null},300);return()=>clearTimeout(ee)}},[e,g]),u.useEffect(()=>{if(!g&&e&&N==="provider-login"&&$&&oe&&Me&&!P){const ee=setTimeout(()=>{M(!0),T("select")},100);return()=>clearTimeout(ee)}},[g,e,N,$,oe,Me,P]),!e)return null;if(N==="provider-login"&&!g)return r.jsx(Wo,{onAuthSuccess:pt,autoTrigger:!0});if(!Dt&&(ne.record||ne.error))return r.jsx(zt,{isOpen:!0,onClose:xt,title:"Withdraw",styles:s,theme:S,dark:v,maxWidth:"486px",closeOnBackdropClick:n,children:ne.error?r.jsx("p",{role:"alert",children:ne.error}):r.jsx(yu,{record:ne.record,knownAssets:[...me,...c?.extraAssets??[],...w?[w]:[]],sourceChains:x,onSuccess:a,onError:i},ne.record.actionFunding.identity)});if(N==="select"){const ee=parseFloat(X)||0,ue=rt?zo(Rt,rt):X||"0",Be=!!Q&&Rt>Q.balance,_e=(R?f.getChainConfig(R):null)?.displayName||"Network",it=R?yn[R]||Kn:null,et=ve?.symbol||"\u2014",vt=Zt,ht=ve?zo(Oe,ve.decimals):"0",At=Q&&Q.balanceFormatted>0?Q.balanceUsd/Q.balanceFormatted:void 0,yt=Q?.priceStatus==="stale",Ut=_a(ee,At,yt),Nt=_a(parseFloat(ht)||0,At,yt),Yt=(!q||A.isAddress(_))&&(!we||!f.addressesEqual(St,Me)),mn=!g&&!we&&ee>0&&ve!==null,Cn=!mn||Te!==null&&!De&&!te,rn=ee>0&&!Be&&!ye&&!K&&Q!==null&&R!==null&&ve!==null&&St&&Yt&&Cn&&Oe>0n&&(!we||We.canExecute&&!jt),Xt=!rn,Qt=ye?"LOADING BALANCES":K?"BALANCES UNAVAILABLE":Q===null?"NO BALANCE":ee===0?"ENTER AMOUNT":Be?"INSUFFICIENT BALANCE":mn&&!Cn?te?"GAS UNAVAILABLE":"ESTIMATING GAS":mn&&Oe===0n?"AMOUNT TOO SMALL":we&&!We.canExecute?"REVIEW FEES":"WITHDRAW",z=!!Ve&&(Ve.step==="success"||Ve.step==="error"),pe=s?.primaryColor||S.colors.primary,Ne=402,fe=(Ze,lt,an)=>r.jsx(lu,{label:Ze,loading:an,balance:lt,dark:v,dk:B});return r.jsx(zt,{isOpen:!0,onClose:xt,title:"Withdraw",subtitle:r.jsx(xu,{dark:v,dk:B}),styles:s,theme:S,dark:v,maxWidth:"486px",footerLinkText:"Spicenet accounts \u2192",overlayDimmed:!1,closeOnBackdropClick:n,overlayContent:z?r.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,display:"flex",flexDirection:"column",justifyContent:"flex-end",pointerEvents:"none",zIndex:20},children:r.jsx("div",{style:{pointerEvents:"auto"},children:r.jsx(Lo,{type:"withdraw",isOpen:!0,isProcessing:tt,onRetryTx:()=>{Tn()},onNewTx:()=>{Re(null),Y(""),nt(null),Le.current=null},onClose:()=>{Re(null),nt(null),dt(!1),Le.current=null},onComplete:()=>{Re(null),nt(null),dt(!1),Le.current=null},results:[{asset:{symbol:ve?.symbol||"Token",address:ve?.address||""},txHash:Ve?.txHash||"",success:Ve?.step==="success",error:Ve?.error,amount:X}],chainId:R??void 0,theme:S})})}):null,children:r.jsxs("fieldset",{disabled:Dt,style:{border:0,minWidth:0,width:`${Ne}px`,margin:"0 auto",padding:"0 0 4px 0",position:"relative"},children:[r.jsxs("div",{style:{marginTop:"16px",marginBottom:"16px",display:"flex",flexDirection:"column",gap:"16px"},children:[r.jsx(gu,{header:fe("Source",pn,ye),amount:X,setAmount:Y,isInsufficient:Be,sourceAmountDecimals:rt,selectedSourceAsset:Q,resolvedSelectedSourceAsset:Q,spiceAssets:Ae,setSelectedSourceAsset:L,sourceUsdEstimate:Ut,sourceTokenLabel:vt,sourceChainLabel:at,totalSelectedBalance:pn,showSourceTokenPopover:ce,setShowSourceTokenPopover:G,tokenPopoverPos:O,setTokenPopoverPos:se,tokenTriggerRef:he,primaryColor:pe,dark:v,dk:B}),r.jsx(uu,{header:fe("Destination",on?.balanceFormatted??null,Kt.loading),amount:X,receiveAmountDisplay:ht,receiveUsdEstimate:Nt,selectedDestToken:ve,destTokenSymbol:et,destChainName:_e,destChainLogo:it,compatibleDestinationChains:He,networkSwitchRef:re,onOpenNetworkPopover:wt,showNetworkPopover:V,setShowNetworkPopover:J,networkPopoverPos:ae,selectedChainId:R,setSelectedChainId:U,dark:v,dk:B})]}),r.jsxs("div",{style:{marginBottom:S.spacing.sm},children:[r.jsx(mu,{show:F,onToggle:ut,showCustomAddress:q,setShowCustomAddress:Z,customRecipient:_,setCustomRecipient:H,externalAddress:Ye,recipientAddress:St,destChainName:_e,destChainLogo:it,compatibleDestinationChains:He,txDetailsChainSwitchRef:xe,onOpenNetworkPopover:wt,sourceChainLabel:at,sourceDetailsLogo:po,sourceTokenLabel:vt,amount:X,totalSourceDebitDisplay:ue,receiveAmountDisplay:ht,destTokenSymbol:et,shouldQuoteWithdrawGas:mn,estimatingFee:De,feeError:te,displayedGasFee:Mt,selectedDestToken:ve,theme:S,styles:s,dark:v,dk:B}),we&&r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[r.jsx(wn,{palette:B,label:"FEE ASSET",value:r.jsxs("select",{"aria-label":"Withdrawal fee asset",disabled:Dt,value:mt.source?mt.sourceKey(mt.source):"",onChange:Ze=>mt.setSource(mt.candidates.find(lt=>mt.sourceKey(lt)===Ze.target.value)??null),children:[!mt.candidates.length&&r.jsx("option",{value:"",children:"No eligible fee balance"}),mt.candidates.map(Ze=>r.jsxs("option",{value:mt.sourceKey(Ze),children:[Ze.displaySymbol||Ze.symbol," \xB7"," ",Ze._source==="spice"?"Spicenet":f.getChainConfig(Ze.chainId)?.displayName]},mt.sourceKey(Ze)))]})}),r.jsx(wn,{palette:B,label:"MAXIMUM FEE FUNDING",value:We.fees.isLoading?"Estimating...":We.fees.ready&&mt.source&&We.amount.sourceRequiredAmount!==null?`${A.formatUnits(We.amount.sourceRequiredAmount,mt.source.decimals)} ${mt.source.displaySymbol||mt.source.symbol}`:"Unavailable"}),(We.status.error||We.fees.error)&&r.jsx(sn,{variant:"error",size:"compact",palette:B,children:We.status.error||We.fees.error}),We.status.finalizationError&&r.jsx(f.Button,{variant:"outline",dark:v,disabled:We.status.finalizing,onClick:()=>void We.retryFinalization(),children:"Retry application update"}),We.status.statusMsg&&r.jsx("span",{role:"status",children:We.status.statusMsg})]}),Q&&!ye&&He.length===0&&r.jsx(sn,{variant:"warning",size:"compact",palette:B,children:"No withdrawal networks are available for this asset."}),Xe&&r.jsx(sn,{variant:"error",size:"compact",palette:B,fontFamily:s?.fontFamily||S.typography.fontFamily,style:{marginBottom:"12px"},children:Xe}),K&&r.jsxs(sn,{variant:"error",size:"compact",palette:B,children:["Unable to load balances. Please try again."," ",r.jsx("button",{type:"button",onClick:()=>void ze(),children:"Retry"})]}),r.jsx(f.Button,{variant:"outline",fullWidth:!0,onClick:()=>{rn&&(we?We.submitPay():qn())},disabled:Xt||Dt,theme:S,dark:v,styles:s,style:{marginTop:"8px"},children:Dt?"EXECUTING...":we&&jt?"WITHDRAWN":Qt})]})]})})}return null},Ti=wu,bu=({onDepositClick:e,onWithdrawClick:t,depositDisabled:n=!1,withdrawDisabled:s=!1,primaryColor:o="#EA4B4B",dark:a=!1})=>!e&&!t?null:r.jsxs("div",{style:{display:"flex",gap:"8px"},children:[e&&r.jsx(f.Button,{variant:"outline",onClick:e,disabled:n,dark:a,styles:{button:{backgroundColor:o}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&r.jsx(f.Button,{variant:"outline",onClick:()=>t(),disabled:s,dark:a,styles:{button:{backgroundColor:o}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),Cu=u.memo(bu),vu=({section:e,dk:t,dark:n=!1})=>{const s=o=>{switch(o){case"green":return"#10b981";case"red":return"#ef4444";default:return t.textPrimary}};return r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:t.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:e.title}),r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.items.map((o,a)=>r.jsxs("div",{role:o.onClick?"button":void 0,tabIndex:o.onClick?0:void 0,onClick:o.onClick,onKeyDown:o.onClick?i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),o.onClick?.())}:void 0,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:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[o.tokenLogoURI?r.jsx("img",{src:o.tokenLogoURI,alt:o.tokenSymbol,style:{width:"20px",height:"20px",borderRadius:"50%"}}):r.jsx("div",{style:{width:"20px",height:"20px",borderRadius:"50%",backgroundColor:n?t.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",fontWeight:600,color:t.textSecondary},children:o.tokenSymbol.charAt(0)}),r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:t.textPrimary},children:o.tokenSymbol}),r.jsx("div",{style:{fontSize:"11px",color:t.textSecondary},children:o.label})]})]}),r.jsx("div",{style:{fontSize:"13px",fontWeight:600,color:s(o.valueColor)},children:o.displayValue})]},a))})]})},ku=u.memo(vu);var Su="data:image/svg+xml,%3csvg width='11' height='11' viewBox='0 0 24 24' fill='none' stroke='black' stroke-opacity='0.5' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' xmlns='http://www.w3.org/2000/svg'%3e%3cpolyline points='17 1 21 5 17 9' /%3e%3cpath d='M3 11V9a4 4 0 0 1 4-4h14' /%3e%3cpolyline points='7 23 3 19 7 15' /%3e%3cpath d='M21 13v2a4 4 0 0 1-4 4H3' /%3e%3c/svg%3e";const Iu=({appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,showUsdSummary:a=!0,address:i,dk:l,dark:d=!1,showModeToggle:c,isEmbeddedMode:p=!0,onModeToggle:m})=>{const[h,g]=u.useState(!1),x=async()=>{i&&await f.copyToClipboard(i)&&(g(!0),setTimeout(()=>g(!1),2e3))},y=t==="active",C=n||(y?"Active":"Inactive"),w=y?"#10b981":"#9ca3af",b=r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[r.jsxs("div",{children:[r.jsx("strong",{children:"Embedded:"})," Deposit assets into ",e," account and use them here."]}),r.jsxs("div",{children:[r.jsx("strong",{children:"External:"})," Use assets from your connected wallet here."]})]});return r.jsxs("div",{children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[r.jsxs("div",{style:{fontSize:"13px",fontWeight:600,color:l.textPrimary},children:[e," Account"]}),c?r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[r.jsxs("button",{onClick:m,style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:d?l.hoverBg:"#f3f4f6",border:d?`1px solid ${l.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"11px",fontWeight:600,fontFamily:f.font.mono,color:l.textSecondary,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease",letterSpacing:"0.02em"},children:[r.jsx("span",{children:p?"Embedded":"External"}),r.jsx("img",{src:Su,alt:"","aria-hidden":"true",style:{width:"11px",height:"11px",display:"block",...d?{filter:"invert(0.65)"}:{}}})]}),r.jsx(Ta,{content:b,label:"Account mode info",textColor:d?l.textPrimary:"#f9fafb",backgroundColor:d?l.cardBg:"#111827",borderColor:d?l.cardBorder:"rgba(255,255,255,0.08)",accentColor:d?l.textSecondary:"#6b7280",children:r.jsx("img",{src:Io,alt:"","aria-hidden":"true",style:{width:"12px",height:"12px",display:"block",...d?{filter:"invert(0.65)"}:{}}})})]}):r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:d?l.hoverBg:y?"#ecfdf5":"#f3f4f6",border:d?`1px solid ${l.cardBorder}`:y?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[r.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:w}}),r.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:d?l.textSecondary:y?"#065f46":"#6b7280"},children:C})]})]}),a&&r.jsx("div",{style:{fontSize:"28px",fontWeight:700,color:l.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:f.formatUsd(s)}),a&&o&&r.jsx("div",{style:{fontSize:"12px",color:l.textSecondary,marginBottom:"8px"},children:o}),i&&r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[r.jsx("span",{style:{fontSize:"12px",fontFamily:f.font.mono,color:d?l.textSecondary:"#9ca3af"},children:f.truncateAddress(i)}),r.jsx("button",{onClick:x,style:{padding:"2px 6px",fontSize:"10px",fontWeight:500,backgroundColor:"transparent",color:d?l.textSecondary:"#9ca3af",border:"none",cursor:"pointer",borderRadius:"4px",transition:"background-color 150ms ease, color 150ms ease"},title:"Copy address",children:h?"Copied":"Copy"})]})]})},Au=u.memo(Iu),Eu=e=>`${e.tokenAddress}-${e.chainId}`,Fu=({spiceAssets:e,loading:t,dk:n,dark:s=!1,canDirectWithdraw:o=!1,onDirectWithdraw:a,directWithdrawState:i,onWithdrawClick:l})=>{const d={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},c={backgroundColor:n.cardBg,border:s?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return t?r.jsxs("div",{children:[r.jsx("div",{style:d,children:"Idle Balances"}),[1,2].map(p=>r.jsx("div",{style:{...c,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},p))]}):e.length===0?r.jsxs("div",{children:[r.jsx("div",{style:d,children:"Idle Balances"}),r.jsx("div",{style:{...c,padding:"16px",textAlign:"center",fontSize:"13px",color:s?n.textSecondary:"#9ca3af"},children:"No assets yet. Deposit to get started."})]}):r.jsxs("div",{children:[r.jsx("div",{style:d,children:"Idle Balances"}),r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map(p=>{const m=f.getChainConfig(p.chainId),h=p.chainDisplayName||m?.displayName||`Chain ${p.chainId}`,g=p.tokenDisplaySymbol||p.tokenDisplayName||p.tokenSymbol,x=Eu(p),y=p.receiptTokenId&&l,C=y||o&&p.directWithdraw&&!!a,w=!y&&i?.key===x?i:null,b=w?.step==="pending";return r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...c},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[p.logoURI?r.jsx("img",{src:p.logoURI,alt:p.tokenSymbol,style:{width:"24px",height:"24px",borderRadius:"50%"}}):r.jsx("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:s?n.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:n.textSecondary},children:g.charAt(0)}),r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:g}),r.jsx("div",{style:{fontSize:"11px",color:s?n.textSecondary:"#9ca3af"},children:h})]})]}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[r.jsxs("div",{style:{textAlign:"right"},children:[r.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:Zs({balance:BigInt(p.balance),decimals:p.tokenDecimals})}),r.jsx("div",{style:{fontSize:"11px",color:w?.step==="error"?n.errorText:s?n.textSecondary:"#9ca3af"},children:w?.step==="error"?w.message||"Withdraw failed":!Number.isFinite(p.usdValue)||p.usdValue<=0?"\u2014":`${f.formatUsd(p.usdValue)}${p.priceStatus==="stale"?" (stale)":""}`})]}),C&&r.jsx("button",{onClick:()=>{b||(y?y(p.receiptTokenId):a(p))},disabled:b,title:y?"Choose withdrawal network":"Withdraw to external wallet",style:{padding:"6px 10px",borderRadius:"6px",border:s?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",backgroundColor:s?n.hoverBg:"#ffffff",color:n.textPrimary,fontSize:"11px",fontWeight:600,cursor:b?"default":"pointer",opacity:b?.6:1,whiteSpace:"nowrap"},children:b?"Withdrawing\u2026":"Withdraw"})]})]},p.positionId??`${p.owner??""}:${p.location??""}:${p.receiptTokenId??`${p.tokenAddress}-${p.chainId}`}`)})})]})},ju=u.memo(Fu),Tu=({pendingDeposits:e,onCompleteDeposit:t,dk:n,dark:s=!1})=>e.length===0?null:r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:"Pending Deposits"}),r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((o,a)=>{const i=f.getChainConfig(o.chainId)?.displayName||`Chain ${o.chainId}`;return r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:s?n.warningBg:"#fffbeb",border:s?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"8px"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[r.jsx("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:s?n.hoverBg:"#fde68a",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:n.warningText},children:o.tokenSymbol.charAt(0)}),r.jsxs("div",{children:[r.jsxs("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:[o.amount," ",o.tokenSymbol]}),r.jsxs("div",{style:{fontSize:"11px",color:n.warningText},children:["on ",i]})]})]}),r.jsx("button",{onClick:()=>t?.(o),style:{padding:"4px 12px",fontSize:"11px",fontWeight:600,backgroundColor:s?n.hoverBg:"#fef3c7",color:s?n.textPrimary:"#92400e",border:s?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"9999px",cursor:"pointer",transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease"},children:"Complete"})]},`${o.tokenAddress}-${o.chainId}-${a}`)})})]}),Bu=u.memo(Tu),Ru=({appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,showUsdSummary:a,address:i,spiceAssets:l,spiceAssetsLoading:d,pendingDeposits:c,customSections:p,notice:m,onDepositClick:h,onWithdrawClick:g,depositDisabled:x,onCompleteDeposit:y,primaryColor:C,dk:w,dark:b=!1,showModeToggle:I,isEmbeddedMode:S,onModeToggle:v,showConnectExternalCta:B,onConnectExternalWallet:E,connectExternalError:j,showHowItWorks:N=!0,canDirectWithdraw:T,onDirectWithdraw:P,directWithdrawState:M})=>{const[D,L]=u.useState(!1);return r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[r.jsx(Au,{appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,showUsdSummary:a,address:i,dk:w,dark:b,showModeToggle:I,isEmbeddedMode:S,onModeToggle:v}),m&&r.jsx("div",{style:{padding:"10px 12px",borderRadius:"8px",backgroundColor:m.tone==="warning"?b?"rgba(245, 158, 11, 0.12)":"#fffbeb":m.tone==="success"?b?"rgba(16, 185, 129, 0.12)":"#ecfdf5":w.cardBg,border:m.tone==="warning"?b?"1px solid rgba(245, 158, 11, 0.35)":"1px solid #fde68a":m.tone==="success"?b?"1px solid rgba(16, 185, 129, 0.35)":"1px solid #a7f3d0":b?`1px solid ${w.cardBorder}`:"1px solid #e5e7eb",color:m.tone==="warning"?b?"#fbbf24":"#92400e":m.tone==="success"?b?"#34d399":"#047857":w.textSecondary,fontSize:"12px",lineHeight:1.45,fontWeight:500},children:m.message}),B&&r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[r.jsx("button",{onClick:E,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:C||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:f.font.ui,transition:"opacity 150ms ease"},children:"Connect External Wallet"}),j&&r.jsx("span",{style:{fontSize:"11px",color:b?w.errorText:"#b91c1c",lineHeight:1.4},children:j})]}),r.jsx("div",{style:{height:"1px",backgroundColor:b?"#2d2d2d":"#e5e7eb"}}),r.jsx(Cu,{onDepositClick:h,onWithdrawClick:g,depositDisabled:x,primaryColor:C,dark:b}),N&&r.jsxs("div",{children:[r.jsxs("button",{onClick:()=>L(!D),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:w.cardBg,border:b?`1px solid ${w.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:w.textSecondary,fontSize:"12px",fontWeight:500},children:[r.jsx("span",{children:"How It Works"}),r.jsx("span",{style:{transform:D?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),D&&r.jsxs("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:b?w.cardBg:"#f0fdf4",border:b?`1px solid ${w.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:b?w.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),r.jsx(Bu,{pendingDeposits:c,onCompleteDeposit:y,dk:w,dark:b}),r.jsx(ju,{spiceAssets:l,loading:d,dk:w,dark:b,canDirectWithdraw:T,onDirectWithdraw:P,directWithdrawState:M,onWithdrawClick:g}),p.map((R,U)=>r.jsx(ku,{section:R,dk:w,dark:b},U))]})},Du=u.memo(Ru);function Ou({dark:e,onSuccess:t,onError:n}){const{disconnect:s}=_t.useDisconnect(),{logout:o}=Vs.usePrivy(),[a,i]=u.useState(!1);return r.jsx(f.Button,{variant:"ghost",fullWidth:!0,dark:e,loading:a,onClick:async()=>{i(!0);try{s(),await o(),t()}catch(l){n(f.sanitizeError(l,"Unable to disconnect. Please try again."))}finally{i(!1)}},children:"Disconnect"})}const _o=380,jn=8,Nu=[],Mu={};function Bi(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function Pu(e,t){const n=new Map;Object.entries(t).forEach(([o,a])=>{if(!Number.isFinite(a)||a<=0)return;n.set(o,a),n.set(o.toUpperCase(),a);const i=Bi(o);i&&n.set(i,a)});const s=[e.symbol,e.displaySymbol,e.receiptTokenName,e.name,e.displayName];for(const o of s){if(!o)continue;const a=n.get(o)??n.get(o.toUpperCase());if(a!==void 0)return a;const i=Bi(o);if(!i)continue;const l=n.get(i);if(l!==void 0)return l}return 0}const Uu=({appName:e="Spice",status:t="active",statusLabel:n,customSections:s=Nu,extraAssets:o=[],tokenPrices:a={},tokenLogos:i=Mu,breakdownLabels:l=[],notice:d,styles:c,dark:p=!1,onDepositSuccess:m,onDepositClick:h,onWithdrawClick:g,onCompleteDeposit:x,showModeToggle:y=!1,defaultMode:C,showUsdSummary:w=!0,alwaysShowEmbeddedIdle:b=!1,showDisconnect:I=!1})=>{const S=u.useContext(f.SpiceFlowProviderContext),v=S?.mode!=="7702",B=!!S?.isWhitelistGateActive,E=!!S?.isWhitelistConfigured&&S?.isUserWhitelisted!==!0,j=u.useRef(!1);u.useEffect(()=>{if(!j.current){if(f.hasStoredSpiceFlowMode()){j.current=!0;return}C&&S?.setMode&&(S.setMode(C==="non7702"?"ondemand":"7702"),j.current=!0)}},[S,C]);const[N,T]=u.useState(!1),[P,M]=u.useState(null),[D,L]=u.useState({top:0,bottom:0,left:0,placement:"below"}),R=u.useRef(null),U=u.useRef(null),{address:X,isConnected:Y}=f.useWallet(),V=S?.embeddedWalletAddress,J=S?.externalWalletAddress,{embeddedAddress:ce}=f.useProviderWallets(),{dark:G,primaryColor:q,dk:Z}=f.useSpiceBrand(c,p),_=v&&!J,H=!v||b,F=H?V||ce:X,de=u.useMemo(()=>S?.supportedChainIds??k.getChainIdsByNetwork("mainnet"),[S?.supportedChainIds]),re=Nn({owner:H?F:J,role:"holding",sourceChains:de,additionalSourceTokens:o.filter(te=>!te.receiptTokenId&&(!te.owner||f.addressesEqual(te.owner,H?F:J))).map(te=>({address:te.tokenAddress,chainId:te.chainId,decimals:te.tokenDecimals,symbol:te.tokenSymbol,logoURI:te.logoURI})),includeRollupAssets:H,enabled:H?!!F:!!J}),xe=re.assets.filter(te=>te._source==="spice"),he=re.walletAssets,ae=re.loading,be=re.refresh,O=H?F:J,se=u.useMemo(()=>o.filter(te=>!te.owner||te.owner.toLowerCase()===O?.toLowerCase()).map(te=>({...te,owner:te.owner??O,location:te.location??(te.receiptTokenId?"rollup":H?"embedded":"external")})),[o,O,H]),W=u.useMemo(()=>he.map(te=>({owner:te.owner,location:te.location,positionId:ct(te),tokenAddress:te.address,tokenSymbol:te.symbol,tokenDecimals:te.decimals,chainId:te.chainId,chainDisplayName:f.getChainName(te.chainId),balance:te.balance.toString(),balanceFormatted:te.balanceFormatted,usdValue:te.balanceUsd||0,logoURI:te.logoURI||i[te.symbol],directWithdraw:H})),[he,se,i,H]),$=u.useMemo(()=>{const te=H?xe.map(K=>{const ze=K.balanceUsd||0,Ae=Number.isFinite(K.balanceFormatted)?K.balanceFormatted:0,Fe=Pu(K,a),Ee=K.priceStatus&&Fe>0?Fe*Ae:ze>0?ze:Fe*Ae;return{owner:K.owner,location:K.location,positionId:ct(K),tokenAddress:K.address,tokenSymbol:K.symbol,tokenDisplaySymbol:Gs(K),tokenDisplayName:dl(K),tokenDecimals:K.decimals,chainId:K.chainId,chainDisplayName:Ks(K),balance:K.balance.toString(),balanceFormatted:K.balanceFormatted,usdValue:Ee,priceStatus:Fe>0?void 0:K.priceStatus,logoURI:K.logoURI,receiptTokenId:K.receiptTokenId}}):[],Ue=K=>`${K.owner?.toLowerCase()}:${K.location}:${K.chainId}:${K.receiptTokenId??k.normalizeNativeTokenAddress(K.tokenAddress).toLowerCase()}`,me=new Map([...re.rollupAssets,...he].map(K=>[Ue({...K,tokenAddress:K.address}),K])),ye=new Map([...te,...W].map(K=>[Ue(K),K]));for(const K of _?[]:se){const ze=Ue(K),Ae=ye.get(ze);ye.set(ze,Ae?{...K,...Ae,logoURI:K.logoURI??Ae.logoURI,tokenDisplayName:K.tokenDisplayName??Ae.tokenDisplayName,tokenDisplaySymbol:K.tokenDisplaySymbol??Ae.tokenDisplaySymbol}:K)}return[...ye.values()].filter(K=>BigInt(K.balance)>0n&&ir(me.get(Ue(K))??{address:K.tokenAddress,symbol:K.tokenSymbol,displaySymbol:K.tokenDisplaySymbol},S?.allowedTokens)).sort((K,ze)=>ze.usdValue-K.usdValue)},[H,_,xe,re.rollupAssets,a,W,se,S?.allowedTokens]),oe=u.useMemo(()=>$.reduce((te,Ue)=>te+Ue.usdValue,0),[$]),{pendingDeposits:Ce,refresh:Me}=ga({chainIds:de,enabled:!!X,discoverWalletBalances:!0}),ne=u.useMemo(()=>s.reduce((te,Ue)=>te+(Ue.totalValue??0),0),[s]),Ie=oe+ne,ge=u.useMemo(()=>{const te=[];oe>0&&te.push(`${f.formatUsd(oe)} idle`);for(const Ue of s){const me=l.find(ye=>ye.sectionTitle===Ue.title)?.label||Ue.title.toLowerCase();te.push(`${f.formatUsd(Ue.totalValue??0)} ${me}`)}return te.join(" \xB7 ")},[oe,s,l]),Ye=u.useCallback(te=>{x?x(te):M(te)},[x]),tt=u.useCallback(()=>{M(null)},[]),dt=u.useCallback(()=>{M(null),m?.()},[m]),Xe=u.useCallback(()=>{if(!R.current)return;const te=R.current.getBoundingClientRect(),Ue=window.innerHeight-te.bottom-jn,me=te.top-jn,ye=Ue>=400||Ue>=me?"below":"above",K=Math.max(jn,Math.min(te.right-_o,window.innerWidth-_o-jn)),ze=ye==="below"?te.bottom+jn:te.top-jn,Ae=ye==="above"?window.innerHeight-ze:0;L({top:ze,bottom:Ae,left:K,placement:ye})},[]);u.useLayoutEffect(()=>{N&&Xe()},[N,Xe]),u.useEffect(()=>{if(!N)return;const te=ye=>{R.current&&!R.current.contains(ye.target)&&U.current&&!U.current.contains(ye.target)&&T(!1)},Ue=ye=>{ye.key==="Escape"&&T(!1)},me=()=>Xe();return document.addEventListener("mousedown",te),document.addEventListener("keydown",Ue),window.addEventListener("scroll",me,{passive:!0}),window.addEventListener("resize",Xe),()=>{document.removeEventListener("mousedown",te),document.removeEventListener("keydown",Ue),window.removeEventListener("scroll",me),window.removeEventListener("resize",Xe)}},[N,Xe]);const $e=H?V||ce||X:J||X,qe=u.useCallback(()=>{S?.setMode&&S.setMode(v?"7702":"ondemand")},[S,v]),[nt,Ve]=u.useState(null);let Re=null;try{Re=Vs.useConnectWallet({onSuccess:()=>Ve(null),onError:te=>Ve(f.sanitizeError(te,"Failed to connect wallet."))}).connectWallet}catch{Re=null}const Le=u.useCallback(()=>{Re&&(T(!1),Ve(null),Re({walletChainType:"ethereum-only"}))},[Re]),ot=!J&&!!Re,Qe=u.useCallback(()=>{T(!1),h?.()},[h]),Ge=u.useCallback(te=>{T(!1),g?.(te)},[g]),Pe=u.useCallback(te=>{T(!1),Ye(te)},[Ye]),[Te,Ke]=u.useState(null),st=H&&!!J&&!f.addressesEqual(O,J),Se=u.useCallback(te=>{const Ue=he.find(me=>me.chainId===te.chainId&&f.addressesEqual(me.address,te.tokenAddress));Ue&&(T(!1),Ke(Ue))},[he]);if(typeof window>"u")return null;const De=r.jsxs("button",{ref:R,onClick:()=>T(!N),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:G?Z.hoverBg:"#ffffff",border:G?`1px solid ${Z.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:f.font.ui,color:G?Z.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:G?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[r.jsxs("span",{children:[e," Account"]}),Y&&w&&r.jsxs("span",{style:{color:G?Z.textSecondary:"#6b7280"},children:["\xB7 ",f.formatUsd(Ie)]}),r.jsx("span",{style:{fontSize:"10px",color:G?Z.textSecondary:"#9ca3af",transform:N?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),gt=N?Hn.createPortal(r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:f.z.popover},onClick:()=>T(!1)}),r.jsxs("div",{ref:U,style:{position:"fixed",top:D.placement==="below"?`${D.top}px`:"auto",bottom:D.placement==="above"?`${D.bottom}px`:"auto",left:`${D.left}px`,width:`${_o}px`,maxWidth:`calc(100vw - ${jn*2}px)`,maxHeight:"80vh",backgroundColor:G?Z.shell:"#ffffff",border:G?`1px solid ${Z.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:G?"0 10px 40px rgba(0, 0, 0, 0.5)":"0 10px 40px rgba(0, 0, 0, 0.12)",zIndex:f.z.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${f.easing.out}`},children:[r.jsx(Du,{appName:e,status:t,statusLabel:n,totalUsdValue:Ie,breakdownSubtitle:ge,showUsdSummary:w,address:H?$e:X,spiceAssets:$,spiceAssetsLoading:ae,pendingDeposits:Ce,customSections:s,notice:d,onDepositClick:h?Qe:void 0,onWithdrawClick:g?Ge:void 0,depositDisabled:E,onCompleteDeposit:Pe,primaryColor:q,dk:Z,dark:G,showModeToggle:y,isEmbeddedMode:!v,onModeToggle:qe,showConnectExternalCta:ot,onConnectExternalWallet:Le,connectExternalError:nt,showHowItWorks:!B,canDirectWithdraw:st,onDirectWithdraw:Se}),I&&Y&&r.jsx("div",{style:{padding:"0 16px 16px"},children:r.jsx(Ou,{dark:G,onSuccess:()=>T(!1),onError:Ve})})]}),r.jsx("style",{children:`
44
44
  @keyframes accountDisplayFadeIn {
45
45
  from { opacity: 0; transform: translateY(-4px); }
46
46
  to { opacity: 1; transform: translateY(0); }