@spicenet-io/spiceflow-ui 4.10.0-dev.20260916.0 → 4.10.0-dev.20260916.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
from { opacity: 0; transform: translateY(4px); }
|
|
41
41
|
to { opacity: 1; transform: translateY(0); }
|
|
42
42
|
}
|
|
43
|
-
`,Da=({title:e,showChevron:t,expanded:n,onToggleDetails:s,showClose:o,onClose:r,fontFamily:i,labelColor:l,textPrimary:c,closeHoverBg:d,closePressedBg:u})=>{const[f,m]=p.useState(!1),[g,y]=p.useState(!1);return a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"16px"},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:s?"pointer":"default"},onClick:s,children:[a.jsxs("span",{style:{fontSize:"13px",fontWeight:500,color:l,fontFamily:i},children:[e," "]}),t&&a.jsx(On,{color:l,direction:n?"up":"down"})]}),o&&a.jsx("button",{onClick:r,onMouseEnter:()=>m(!0),onMouseLeave:()=>{m(!1),y(!1)},onMouseDown:()=>y(!0),onMouseUp:()=>y(!1),style:{background:g?u:f?d:"none",border:"none",borderRadius:"4px",cursor:"pointer",padding:"4px",display:"flex",alignItems:"center",justifyContent:"center",color:f||g?c:l,transform:g?"scale(0.9)":f?"scale(1.1)":"scale(1)",transition:h.transition.interactive},children:a.jsx($n,{size:16})})]})},Oa=({chainName:e,bg:t,border:n,textPrimary:s,labelColor:o,primaryColor:r})=>a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"20px 16px",borderRadius:"8px",backgroundColor:t,border:`1px solid ${n}`,gap:"12px"},children:[a.jsx(h.Spinner,{size:24,borderWidth:3,color:r}),a.jsxs("div",{children:[a.jsx("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:h.font.mono,letterSpacing:"0.5px",color:s},children:"PROCESSING TRANSACTION"}),a.jsxs("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:o},children:["on ",e]})]})]}),Na=({bg:e,border:t,left:n,right:s})=>a.jsxs("div",{style:{padding:"10px 12px",borderRadius:"6px",backgroundColor:e,border:`1px solid ${t}`,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[n,s]}),Do=({isOpen:e,onClose:t,onComplete:n,closeOnComplete:s=!1,type:o,results:r,chainId:i,chainName:l,explorerUrl:c,theme:d,styles:u,dark:f,intentStatus:m,onRetry:g,onNewTx:y,onRetryTx:x,asOverlay:w=!0,isProcessing:C=!1,showStepBreakdown:b=!0})=>{const{theme:I,primaryColor:S,dark:k,dk:E}=h.useSpiceBrand(u,f),F=d||I,[T,D]=p.useState(!1),j=l??(i?h.getChainName(i):"Network"),U=c??(i&&h.getExplorerUrl(i,"").replace(/\/tx\/.*$/,"")||void 0),P=k?E.cardBg:"#ffffff",O=k?"0 4px 20px rgba(0, 0, 0, 0.4)":"0 4px 20px rgba(0, 0, 0, 0.1)",q=k?"0 -4px 8px -2px rgba(0, 0, 0, 0.4)":"0 -4px 8px -2px rgba(0, 0, 0, 0.15)",R=E.textSecondary,W=k?E.textPrimary:"#374151",K=k?E.inputBg:"#f9fafb",G=k?E.inputBorder:"#e5e7eb",_=k?E.inputBg:"#f3f4f6",X=k?E.inputBorder:"#e5e7eb",[Q,te]=p.useState(!0),B=k?E.inputBg:"#f9fafb",$=k?E.hoverBg:"#f3f4f6",ie=k?{successBg:E.successBg,successBorder:E.successBorder,successText:E.successText,errorBg:E.errorBg,errorBorder:E.errorBorder,errorText:E.errorText}:{},L=m?.steps.find(ce=>ce.status==="failed")?.error;p.useEffect(()=>{!e&&!m&&D(!1)},[e,m]);const H=()=>{D(!0),setTimeout(()=>{window.dispatchEvent(new CustomEvent("tx-complete",{detail:{type:o,results:r}})),window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:{type:o,status:"success",results:r}})),n?.(),s&&t()},300)},fe=()=>{te(!Q)};if(m){const{steps:ce,overallStatus:Ae}=m,N=Ae==="processing",J=Ae==="success",M=Ae==="failed",Y=ce.filter(oe=>oe.transactionHash)[0],ue=ce.length>1?ce.map(oe=>oe.chainName).filter(Boolean).join(" and "):j!=="Network"?j:ce[0]?.chainName||j,We=U||(Y?h.getExplorerUrl(Y.chainId,Y.transactionHash||"").replace(/\/tx\/.*$/,""):void 0),Ce=a.jsxs(a.Fragment,{children:[a.jsx(Da,{title:N?`Processing ${o.charAt(0).toUpperCase()+o.slice(1)}`:`${o.charAt(0).toUpperCase()+o.slice(1)} results`,showChevron:b,expanded:Q,onToggleDetails:fe,showClose:!N,onClose:t,fontFamily:u?.fontFamily||F.typography.fontFamily,labelColor:R,textPrimary:W,closeHoverBg:B,closePressedBg:$}),a.jsx("div",{style:{marginBottom:"16px"},children:N?a.jsx(Oa,{chainName:ue,bg:_,border:X,textPrimary:W,labelColor:R,primaryColor:S}):a.jsx(Ba,{isSuccess:J,type:o,chainName:ue,explorerUrl:We,txHash:Y?.transactionHash,dark:k,...ie,textSecondary:R})}),b&&a.jsx("div",{style:{overflow:"hidden",maxHeight:Q?"300px":"0px",opacity:Q?1:0,transition:"max-height 0.3s ease, opacity 0.3s ease",marginBottom:Q?"16px":"0"},children:a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:ce.map((oe,Ee)=>{const we=oe.transactionHash?h.getExplorerUrl(oe.chainId,oe.transactionHash):null;return a.jsx(Na,{bg:K,border:G,left:a.jsx("span",{style:{fontSize:"13px",color:W},children:oe.chainName?`On ${oe.chainName}`:oe.description||`Step ${Ee+1}`}),right:a.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:oe.status==="success"?"#10b981":oe.status==="failed"?"#ef4444":R,fontWeight:500},children:[we&&a.jsx("a",{href:we,target:"_blank",rel:"noopener noreferrer",style:{color:k?E.infoText:"#2563eb",textDecoration:"none"},onClick:Pe=>Pe.stopPropagation(),children:"View"}),oe.status==="success"?"\u2713":oe.status==="failed"?"\u2717":"\u25CB"]})},Ee)})})}),!N&&a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[M&&g&&a.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:g,theme:F,styles:u,dark:k,children:"TRY AGAIN"}),y&&a.jsxs(h.Button,{variant:"outline",fullWidth:!0,onClick:y,theme:F,styles:u,dark:k,children:["NEW ",o.toUpperCase()," \u2192"]})]})]});return w?a.jsxs("div",{style:{position:"absolute",bottom:0,left:0,right:0,zIndex:10,animation:T?"slideDown 0.3s ease-in forwards":"slideUp 0.3s ease-out forwards",pointerEvents:"auto"},children:[a.jsx("div",{style:{backgroundColor:P,borderRadius:"12px 12px 0 0",width:"100%",padding:"18px 24px 24px",boxShadow:q},children:Ce}),a.jsx("style",{children:Ra})]}):a.jsx("div",{style:{backgroundColor:P,borderRadius:"12px",padding:"24px",width:"100%",boxShadow:O},children:Ce})}if(!e&&!C||!C&&(!r||r.length===0))return null;const Z=r?r.every(ce=>ce.success):!1,he=r?.[0],ge=[...r??[]].reverse().find(ce=>ce.txHash)?.txHash||he?.txHash;return a.jsxs("div",{style:{position:w?"absolute":"relative",bottom:w?0:void 0,left:w?0:void 0,right:w?0:void 0,zIndex:w?10:void 0,animation:w?T?"slideDown 0.3s ease-in forwards":"slideUp 0.3s ease-out forwards":void 0,pointerEvents:"auto",width:"100%"},children:[a.jsx("div",{style:{backgroundColor:P,borderRadius:w?"12px 12px 0 0":"12px",width:"100%",padding:"18px 0 24px",boxShadow:w?q:O},children:a.jsxs("div",{style:{width:"100%",boxSizing:"border-box",padding:"0 24px"},children:[a.jsx(Da,{title:C?`Processing ${o.charAt(0).toUpperCase()+o.slice(1)}`:`${o.charAt(0).toUpperCase()+o.slice(1)} results`,showChevron:!C&&b,expanded:Q,onToggleDetails:C?void 0:fe,showClose:!C,onClose:t,fontFamily:u?.fontFamily||F.typography.fontFamily,labelColor:R,textPrimary:W,closeHoverBg:B,closePressedBg:$}),a.jsx("div",{style:{marginBottom:"16px",animation:"statusFadeIn 220ms cubic-bezier(0.22, 1, 0.36, 1) both"},children:C?a.jsx(Oa,{chainName:j,bg:_,border:X,textPrimary:W,labelColor:R,primaryColor:S}):a.jsx(Ba,{isSuccess:Z,type:o,chainName:j,explorerUrl:U,txHash:ge,dark:k,...ie,textSecondary:R})},C?"processing":Z?"success":"error"),!C&&b&&r&&r.length>1&&a.jsx("div",{style:{overflow:"hidden",maxHeight:Q?"200px":"0px",opacity:Q?1:0,transition:"max-height 0.3s ease, opacity 0.3s ease",marginBottom:Q?"16px":"0"},children:a.jsx("div",{style:{maxHeight:"180px",overflowY:"auto",display:"flex",flexDirection:"column",gap:"8px"},children:r.map((ce,Ae)=>a.jsx(Na,{bg:K,border:G,left:a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[a.jsx("span",{style:{fontWeight:600,fontSize:"13px",color:E.textPrimary,fontFamily:h.font.mono},children:ce.asset.symbol}),ce.amount&&a.jsx("span",{style:{fontSize:"12px",color:R},children:ce.amount})]}),right:a.jsx("span",{style:{fontSize:"12px",color:ce.success?"#10b981":"#ef4444",fontWeight:500},children:ce.success?"\u2713":"\u2717"})},Ae))})}),!C&&!Z&&r&&a.jsx("div",{style:{padding:"12px",backgroundColor:E.errorBg,border:`1px solid ${E.errorBorder}`,borderRadius:"8px",marginBottom:"16px"},children:a.jsx("p",{style:{fontSize:"13px",color:E.errorText,margin:0,lineHeight:1.5},children:L||r.find(ce=>!ce.success)?.error||`${o.charAt(0).toUpperCase()+o.slice(1)} failed. Please try again.`})}),!C&&a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[!Z&&x&&a.jsxs(h.Button,{variant:"outline",fullWidth:!0,onClick:x,theme:F,styles:u,dark:k,children:["TRY AGAIN ",o.toUpperCase()]}),Z&&a.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:H,theme:F,styles:u,dark:k,children:"DONE"})]})]})}),a.jsx("style",{children:Ra})]})};function Ma(e){const t=new Set(v.getEquivalentAddresses(e).map(n=>n.toLowerCase()));return t.add(e.toLowerCase()),t}const hd=["USDC","USDT","WETH","WBTC"];function Pa(e,t){const n=h.getChainConfig(t);if(!n)return;if(n.nativeCurrency.symbol.toUpperCase()===e.toUpperCase())return{address:v.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 an(e,t,n){const s=h.getChainConfig(t);if(!s)return;if(n!==void 0){if(v.isNativeToken(e)&&!v.getTokenByAddress(e,n))return;const i=oo(e,n,t);return i?{address:i.address.toLowerCase(),symbol:i.symbol,decimals:i.decimals,chainId:t}:void 0}if(v.isNativeToken(e))return;const o=Ma(e),r=s.supportedTokens?.find(i=>o.has(i.address.toLowerCase()));if(r)return{address:r.address.toLowerCase(),symbol:r.symbol,decimals:r.decimals,chainId:t}}function gd(e){const{sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:o,intermediaryCandidates:r=hd}=e;if(xs(t,n))return{strategy:"direct",sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:o,summary:`${t.symbol} fronted directly`};if(s===o&&(v.isNativeToken(t.address)||!v.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(an(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(an(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 r){const l=Pa(i,s);if(!l||xs(t,l)||xs(n,l))continue;const c=Pa(i,o);if(c&&xs(l,c))return{strategy:"intermediary",sourceAsset:t,outputAsset:n,intermediaryAsset:c,sourceChainId:s,destinationChainId:o,summary:`${t.symbol} \u2192 ${i} on source, fronted, then ${i} \u2192 ${n.symbol} on destination`}}throw new h.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:r})}async function xd(e){const{route:t,sourceAmount:n,userAddress:s,registry:o,actionCalls:r,slippage:i}=e;async function l(c,d,u,f){const m=await o.resolveSwap({type:"swap",tokenIn:d,tokenOut:u,amountIn:f,maxSlippage:i},c,s);if(!m)throw new h.SpiceflowError("NO_LIQUIDITY",`No venue returned a quote for ${d} \u2192 ${u} on chain ${c}. No liquidity available for this pair.`,{chainId:c,tokenIn:d,tokenOut:u,amountIn:f.toString()});return m}switch(t.strategy){case"direct-swap":{const c=await l(t.destinationChainId,t.sourceAsset.address,t.outputAsset.address,n);return{chainBatches:[{chainId:t.destinationChainId,calls:[...c.calls,...r]}],solverFrontToken:t.outputAsset,solverFrontAmount:0n,resolvedSwaps:{sourceSwap:c}}}case"direct":{const c=an(t.sourceAsset.address,t.destinationChainId,t.sourceChainId)||t.sourceAsset;if(Ma(c.address).has(t.outputAsset.address.toLowerCase()))return{chainBatches:[{chainId:t.destinationChainId,calls:r}],solverFrontToken:c,solverFrontAmount:n,resolvedSwaps:{}};const d=await l(t.destinationChainId,c.address,t.outputAsset.address,n);return{chainBatches:[{chainId:t.destinationChainId,calls:[...d.calls,...r]}],solverFrontToken:c,solverFrontAmount:n,resolvedSwaps:{destinationSwap:d}}}case"source-swap":{const c=an(t.outputAsset.address,t.sourceChainId,t.destinationChainId);if(!c)throw new h.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 d=an(t.outputAsset.address,t.destinationChainId,t.destinationChainId);if(!d)throw new h.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 u=await l(t.sourceChainId,t.sourceAsset.address,c.address,n);return{chainBatches:[{chainId:t.sourceChainId,calls:u.calls},{chainId:t.destinationChainId,calls:r}],solverFrontToken:d,solverFrontAmount:u.amountOutMinimum,resolvedSwaps:{sourceSwap:u}}}case"intermediary":{if(!t.intermediaryAsset)throw new h.SpiceflowError("ROUTE_STRATEGY_ERROR","Intermediary strategy requires an intermediary asset but none was provided in the route plan.",{strategy:t.strategy});const c=an(t.intermediaryAsset.address,t.sourceChainId,t.destinationChainId);if(!c)throw new h.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 d=await l(t.sourceChainId,t.sourceAsset.address,c.address,n),u=await l(t.destinationChainId,t.intermediaryAsset.address,t.outputAsset.address,d.amountOutMinimum);return{chainBatches:[{chainId:t.sourceChainId,calls:d.calls},{chainId:t.destinationChainId,calls:[...u.calls,...r]}],solverFrontToken:t.intermediaryAsset,solverFrontAmount:d.amountOutMinimum,resolvedSwaps:{sourceSwap:d,destinationSwap:u}}}default:throw new h.SpiceflowError("ROUTE_STRATEGY_ERROR",`Unknown route strategy: ${t.strategy}`,{strategy:t.strategy})}}function yd(e,t,n){if(!e||!t)return null;if(e._source==="wallet")return e._fundingWallet!=="embedded"||t!==e.chainId?null:{address:e.address,symbol:e.symbol,name:e.name,decimals:e.decimals,logoURI:e.logoURI};const s=Bn(e,t),o=Object.entries(e.chainTokens??{}).flatMap(([f,m])=>{const g=sn(f);return g?.chainId===t?[{parsed:g,detail:m}]:[]}),r=f=>n.find(m=>h.addressesEqual(m.address,f))??null,i=f=>{const m=o.find(({parsed:x})=>h.addressesEqual(x.address,f));if(!m)return null;const g=h.getChainConfig(t);if(v.isNativeToken(f))return g?{address:v.ZERO_ADDRESS,symbol:g.nativeCurrency.symbol,name:g.nativeCurrency.name,decimals:g.nativeCurrency.decimals,logoURI:e.logoURI}:null;const y=g?.supportedTokens?.find(x=>h.addressesEqual(x.address,f));return!y||!so(e,f,t)?null:{address:m.parsed.address,symbol:y.symbol,name:y.name||m.detail?.name||e.displayName||e.name||e.symbol,decimals:y.decimals,logoURI:y.logo||e.logoURI}},l=o.map(({parsed:f})=>f.address).filter(v.isNativeToken);for(const f of[...s,...l]){if(v.isNativeToken(f)){const y=i(f);if(y)return y}const m=r(f);if(m)return m;const g=i(f);if(g)return g}if(e.chainTokens||e.receiptTokenId)return null;const c=zt(e,t);if(c){const f=r(c);if(f)return f}const d=an(e.address,t,e.chainId);return d?r(d.address)||(n.length>0?null:{address:d.address,symbol:d.symbol||e.symbol,name:e.displayName||e.name||e.symbol,decimals:d.decimals??e.decimals,logoURI:e.logoURI}):null}function wd(e){const t=e.find(n=>v.isSpicenetChainId(n.chainId))?.calls?.[0]?.data;if(!t)return null;try{const n=A.decodeFunctionData({abi:v.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 bd(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()===v.SPICE_GAS_FEE_RECIPIENT.toLowerCase()?Cn(n.amount,o.amount,100n):n.amount===o.amount})}function Cd(e,t){const n=e.intents.flatMap(r=>r.batches).filter(r=>{const i=Jt(r);return BigInt(r.quotedAmount)>0n||BigInt(r.totalDebit)>0n||i.totalFee>0n}),s=n.filter(r=>r.chainId===t),o=s.length>0?s:n;return o.length===1?o[0]:null}function vd(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const s=n.token.toLowerCase(),o=n.recipient.toLowerCase(),r=`${s}:${o}`,i=t.get(r);i?i.amount+=n.amount:t.set(r,{...n})}return[...t.values()]}function Ua(e,t){if(!e.token||!e.recipient||e.chainId===null)return null;const n=Cd(t,e.chainId);if(!n)return null;const{gasFee:s,bridgeFee:o,spicenetFee:r}=Jt(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:v.SPICE_GAS_FEE_RECIPIENT,amount:i}),r>0n&&l.push({token:e.token.address,recipient:v.SPICE_PLATFORM_FEE_RECIPIENT,amount:r}),vd(l)}function kd(e,t,n){const s=Ua(e,t);return!s||bd(wd(n),s)?null:e.buildWithdrawBatches(s)}async function Wa(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=>v.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),r=Ua(e,o);r&&(t=e.buildWithdrawBatches(r));const i=o.intents[0]?.batches.find(l=>l.chainId===e.chainId)??o.intents[0]?.batches[0]??null;i&&e.ui.setLockedGasFee(Jt(i).totalFee)}else{const o=(e.feeEstimate??await e.execution.estimate(t,n,0n,s)).intents[0]?.batches[0]??null;o&&e.ui.setLockedGasFee(Jt(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:r})=>kd(e,o,r)}:{...s,skipPreSubmitFeeEstimate:!0})}La(e)}catch(t){const n=t instanceof Error?t.message:"Withdraw failed";e.ui.setExecutionError(n)}finally{e.ui.setIsExecuting(!1)}}}function La(e){window.dispatchEvent(new CustomEvent("withdraw-completed")),e.onWithdrawSuccess?.({token:e.token?.symbol||"",amount:e.amount,chainId:e.chainId})}async function Sd(e){const t=e.executionContextRef.current;if(!t){e.ui.setExecutionProgress(null),await Wa(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 h.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 ca({actionId:t.actionId,intentIndex:t.intentIndex,intentId:t.intentId,stepIndex:s,chainId:e.chainId??void 0,onStatusMessage:(r,i)=>{e.isMountedRef.current&&e.ui.setExecutionProgress({step:"executing",message:r,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})}La(e)}catch(n){const s=n instanceof Error?n.message:"Withdraw failed";e.ui.setExecutionError(s)}finally{e.ui.setIsExecuting(!1)}}async function Id(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=>Jt(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:Jt(s).totalFee,feeEstimate:t}}function Oo(e,t){return A.formatUnits(e,t).replace(/(\.\d*?[1-9])0+$|\.0+$/,"$1")}function za(e,t,n){return Mt(e,t,n,"floor")}function qa(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 Ad(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 Ha(e,t,n){const s=n.filter(o=>o.amount>0n);return{chainId:e,domain:"evm",tokenTransfers:[],calls:v.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([v.SPICE_GAS_FEE_RECIPIENT,v.SPICE_PLATFORM_FEE_RECIPIENT].map(e=>e.toLowerCase()));function Ed(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),r=`${s.toLowerCase()}:${o.toLowerCase()}`,i=t.get(r);i?i.amount+=n.amount:t.set(r,{token:s,to:o,amount:n.amount})}return[...t.values()]}function Fd(e,t){return`0x${t}${e.slice(4)}`}function Va(e,t,n,s){if(e.some(u=>u.domain==="spicenet"))return e;const o=n?.intents.flatMap(u=>u.batches),r=u=>u.from==="escrow",i=e.map(u=>{const f=o?.find(F=>F.chainId===u.chainId);if(!f)return u;const m=Jt(f),g=m.totalFee;if(g<=0n)return u;const y=(u.tokenTransfers??[]).filter(F=>r(F)&&A.getAddress(F.to).toLowerCase()===t.toLowerCase()),x=y.find(F=>!v.isNativeToken(A.getAddress(F.token)))??y[0];if(!x)return u;const w=A.getAddress(x.token),C=v.isNativeToken(w);let b=!1;const I=(u.tokenTransfers??[]).map(F=>b||!r(F)||A.getAddress(F.to).toLowerCase()!==t.toLowerCase()||A.getAddress(F.token).toLowerCase()!==w.toLowerCase()?F:(b=!0,{...F,amount:s?.payoutAlreadyGross?BigInt(F.amount):BigInt(F.amount)+g}));if(!b)return u;const S=(F,T)=>C?{to:F,value:T,data:"0x"}:{to:w,value:0n,data:A.encodeFunctionData({abi:A.erc20Abi,functionName:"transfer",args:[F,T]})},k=[];m.spicenetFee>0n&&k.push(S(v.SPICE_PLATFORM_FEE_RECIPIENT,m.spicenetFee));const E=m.gasFee+m.bridgeFee;return E>0n&&k.push(S(v.SPICE_GAS_FEE_RECIPIENT,E)),{...u,tokenTransfers:I,calls:[...k,...u.calls]}}),l=i.flatMap(u=>(u.tokenTransfers??[]).filter(r).map(f=>{const m=A.getAddress(f.token),g=A.getAddress(f.to),y=[{token:m,to:g,amount:BigInt(f.amount)}];return{chainId:u.chainId,transfers:Ed(y)}}));if(l.length===0)return e;const c=s?.requestTimestampMs??Date.now(),d=BigInt(Math.floor(c/1e3))+3600n;return[{chainId:v.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:l.map((u,f)=>{const m=A.keccak256(A.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,u.transfers[0].token,u.transfers.reduce((y,x)=>y+x.amount,0n),BigInt(u.chainId),BigInt(c+f)])),g=Fd(m,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:A.encodeFunctionData({abi:v.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${u.chainId}`,idempotenceKey:g,nbf:0n,exp:d,metadata:"{}",transfers:u.transfers.map(y=>({token:y.token.toLowerCase(),to:y.to,amount:y.amount}))}]})}})},...i]}function kn(e,t,n,s){const o=e.filter(i=>i.domain!=="spicenet"),r=i=>(i.tokenTransfers??[]).some(l=>l.from==="escrow");return[...o.filter(i=>!r(i)),...Va(o.filter(r),t,n,s)]}class es extends Error{constructor(t,n){super("The selected balance cannot cover the fee funding amount"),this.requiredAmount=t,this.balance=n,this.name="InsufficientFeeFundingBalanceError"}}function No(e,t,n,s,o){const r=e[e.length-1];if(!r?.calls.length||r.domain==="spicenet")throw new Error("Proceeds fees require a final destination action");const i=[{to:v.SPICE_PLATFORM_FEE_RECIPIENT,amount:o},{to:v.SPICE_GAS_FEE_RECIPIENT,amount:s}].filter(l=>l.amount>0n);return e.map(l=>l===r?{...l,calls:[...l.calls,...i.map(c=>({to:n,value:0n,data:A.encodeFunctionData({abi:A.erc20Abi,functionName:"transfer",args:[c.to,c.amount]})}))],tokenTransfers:[...l.tokenTransfers??[],...i.map(c=>({from:t,to:c.to,token:n,amount:c.amount}))]}:l)}async function Qa(e,t,n,s,o){const r=v.hashChainBatches(e),i=await h.relayerService.estimateBatchGas({user:t,outputToken:n,signal:s,requireSimulation:!0,includePlatformFee:o!==void 0,chainBatches:e.map((l,c)=>({...l,hash:r[c].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 Ga(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?.preview)throw new Error("Action fee quote is unavailable");let s=n.preview.gasFee;const o=n.preview.spicenetFee,r=n.preview.bridgeFee??0n;for(let i=0;i<5;i++){const l=s+o+r,c=t<l?t:l,d=l-c;if(d>0n&&e.fundShortfall===!1)throw new es(l,t);const u=d>0n?(d*110n+99n)/100n+2n:0n;let f=u,m;const g=kn(await e.buildBatches(u,{actionAmountOverride:e.actionAmountFor?.(l),onSourceSpend:w=>{f=w},onActionCalls:w=>{m=w}}),e.owner),y=No(g,e.owner,e.token,s+r,o),x=await Qa(y,e.owner,e.token,e.signal);if(x===s)return{preview:{...n.preview,grossAmount:u,netAmount:0n,gasFee:s,totalFee:l,gasQuoteSource:"estimated"},feeEstimate:n.feeEstimate,grossFundingAmount:u,proceedsAvailable:t,proceedsUsed:c,fundingBatches:y,sourceSpendCap:f,destinationAmount:0n,actionDefinition:m};s=x}throw new Error("Action proceeds fee estimate did not converge")}function Ka(e,t){let n,s;if(v.isNativeToken(t)){if(e.data!=="0x")return null;n=e.to,s=e.value}else{if(!h.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 h.addressesEqual(n,v.SPICE_GAS_FEE_RECIPIENT)?{gas:s,platform:0n}:h.addressesEqual(n,v.SPICE_PLATFORM_FEE_RECIPIENT)?{gas:0n,platform:s}:null}async function Td(e,t,n){const s=h.getClientForChain(e);return v.isNativeToken(n)?s.getBalance({address:t}):s.readContract({address:n,abi:A.erc20Abi,functionName:"balanceOf",args:[t]})}function Rs(e,t,n){return e.map(s=>s.chainId===t?{...s,calls:s.calls.filter(o=>!Ka(o,n))}:s)}function jd(e,t,n){if(!e.feeOnlyAction)return{};const s=e.embeddedWalletAddress??e.providerEmbeddedAddress,o=e.feeQuote?.fundingSource,r=o&&o.kind!=="proceeds"?void 0:e.actionProceeds,i=o&&(o.kind==="input"||o.kind==="balance"&&o.asset?._source==="wallet")?o:void 0;if(r||e.feeQuote?.fundingConversion||i){const u=e.feeQuote?.fundingConversion,f=r??{token:t,resolve:async()=>0n},m=e.feeQuote?.preview,g=e.feeQuote?.proceedsUsed,y=u?.fromProceeds?u.tokenIn:t;if(!m||g===void 0||!i&&f.token.toLowerCase()!==y.toLowerCase())throw new Error("Refresh the action proceeds quote");const x=m.gasFee+(m.bridgeFee??0n),w=m.spicenetFee,C=i?async()=>{e.validateFeeQuote?.();const I=await Td(e.resolvedChainId,s,i.token);e.validateFeeQuote?.();const S=i.kind==="input"?i.amount:u?.amountInMax??g;if(e.signal?.aborted||I<S||u&&u.amountOut<x+w)throw new Error("The fee funding balance changed; refresh before retrying");return u?[{chainId:e.resolvedChainId,token:t,amount:u.amountOut}]:[]}:async()=>{e.validateFeeQuote?.();const I=await f.resolve(e.signal);if(e.validateFeeQuote?.(),e.signal?.aborted||(u?.fromProceeds?I<u.amountInMax||u.amountOut<x+w:I<g||I+(u?.amountOut??n)<x+w))throw new Error("Action proceeds changed; refresh before retrying");return u?.fromProceeds?[{chainId:e.resolvedChainId,token:u.tokenIn,amount:u.amountInMax},{chainId:e.resolvedChainId,token:t,amount:u.amountOut}]:[{chainId:e.resolvedChainId,token:t,amount:g+(u?.amountOut??0n)}]},b=async I=>{await C();const S=await Qa(I,s,t,e.signal,u?w:void 0);if(await C(),(S>m.gasFee?S-m.gasFee:m.gasFee-S)*100n>S*15n)throw new Error("Action gas quote changed; refresh before retrying")};return{resolveActionOutputCredits:C,prepareForSigning:async I=>{const S=Rs(I,e.resolvedChainId,t).map(E=>({...E,tokenTransfers:E.tokenTransfers?.filter(F=>!(typeof F.from=="string"&&h.addressesEqual(F.from,s)&&(h.addressesEqual(F.to,v.SPICE_GAS_FEE_RECIPIENT)||h.addressesEqual(F.to,v.SPICE_PLATFORM_FEE_RECIPIENT))))})),k=No(S,s,t,x,w);return await b(k),k},validateBeforeSubmit:b}}const l=v.getTokenByAddress(t,e.resolvedChainId),c={chainId:e.resolvedChainId,tokenAddress:t,symbol:l?.symbol??e.destinationToken.symbol,decimals:e.executionTokenDecimals??l?.decimals??e.destinationToken.decimals},d=async u=>{e.validateFeeQuote?.();const f=Rs(u,e.resolvedChainId,t),m=await e.execution.estimate(f,t,n,{userOverride:s,useCustomTransfers:!0,feeExecutionMode:"backend-transfer"});e.validateFeeQuote?.();const g=hn(m,c);if(!g||g.chainId!==e.resolvedChainId)throw new Error("The fee service did not return the destination action's fee quote");if(g.gasFee+g.spicenetFee+(g.bridgeFee??0n)+2n>n)throw new Error("Fees exceed the displayed maximum funding; refresh the quote before retrying");return{raw:f,feeEstimate:m,fees:g}};return{prepareForSigning:async u=>{const{raw:f,feeEstimate:m}=await d(u);return kn(f,s,m,{payoutAlreadyGross:!0})},validateBeforeSubmit:async u=>{const{fees:f}=await d(u);let m=0n,g=0n;for(const x of u)if(x.chainId===e.resolvedChainId)for(const w of x.calls){const C=Ka(w,t);C&&(m+=C.gas,g+=C.platform)}if(m+g+2n>n)throw new Error("Signed fees exceed the displayed maximum funding");const y=f.gasFee+(f.bridgeFee??0n);if((m>y?m-y:y-m)*100n>y*15n||g!==f.spicenetFee)throw new Error("The signed gas quote changed materially; refresh before retrying")}}}const Bd="0xa9059cbb";function ts(e,t,n){return v.isNativeToken(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:A.encodeFunctionData({abi:A.erc20Abi,functionName:"transfer",args:[n,t]})}}function Za(e,t,n){return{chainId:n,calls:[ts(e,t,v.getEscrowContractAddress(n))]}}function Rd(e,t,n,s){const o=t.source.chainId;return{chainId:o,calls:[...e.calls,ts(t.source.address,n,v.getEscrowContractAddress(o)),...s>0n?[ts(t.source.address,s,v.SPICE_GAS_FEE_RECIPIENT)]:[]]}}function Ya(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 Xa(e,t,n){return e?.asset?._source==="wallet"&&e?.asset.chainId===n}function Ja(e){return e.isNative||v.isNativeToken(e.address)?!0:!v.getTokenByAddress(e.address,e.chainId)}function $a(e,t,n,s){return t!=="user-transfer"||!n||e.length===0||e[0]?.to.toLowerCase()!==s.toLowerCase()||!e[0]?.data.startsWith(Bd)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function ns(e,t,n,s){if(!t)return[e];const o=await t({...n,requestTimestampMs:s});return o?[o,e]:[e]}function Dd(e){return e.filter(t=>t.domain!=="spicenet")}function ss(e,t){const n=(e.tokenTransfers??[]).filter(s=>s.from==="escrow").map(s=>({token:v.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 Mn(e,t,n){return Mt(e,t,n,"ceil")}function _a(e){const t=e.selectedAsset?.asset;return e.isPayMode&&!!t&&t._source==="wallet"&&t.chainId!==e.resolvedChainId&&!!e.pivot}function Mo(e){const t=e.selectedAsset?.asset;return!e.isPayMode&&!!t&&t._source==="wallet"&&t.chainId!==e.resolvedChainId&&!!e.sourceSwap&&!!e.pivot}function Ds(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 ei(e,t,n){let s;const o=await e({...t,buildActionCalls:async(r,i)=>{s=r;const l=await t.buildActionCalls(r,i);return n?.onActionCalls?.({amount:r,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 Po=(e,t)=>ei(Od,e,t),Os=async(e,t)=>{const n=await ei(Nd,e,t),s=t?.actionContextOverride?.feeBreakdown,o=n[n.length-1];if(e.feeExecutionMode!=="user-transfer"||!s||!o)return n;const r=e.needsSwap&&e.resolvedTokenIn?e.resolvedTokenIn:e.destinationToken.address,[i]=Rs([o],e.resolvedChainId,r),l=Ha(e.resolvedChainId,r,[{recipient:v.SPICE_PLATFORM_FEE_RECIPIENT,amount:s.spicenetFee},{recipient:v.SPICE_GAS_FEE_RECIPIENT,amount:s.gasFee+(s.bridgeFee??0n)}]).calls,c=o.calls.filter(d=>!i.calls.includes(d));return c.length===l.length&&l.every(d=>c.some(u=>u.to.toLowerCase()===d.to.toLowerCase()&&u.value===d.value&&u.data===d.data))?n:[...n.slice(0,-1),{...i,calls:[...l,...i.calls]}]};async function Od(e,t){const{currentPaymentAmount:n,destinationToken:s,embeddedWalletAddress:o,providerEmbeddedAddress:r,address:i,isNon7702:l,resolvedChainId:c,buildActionCalls:d,feeExecutionMode:u,buildSpicenetBatch:f,needsSwap:m,exactOutputSwap:g,resolvedTokenIn:y,requestTimestampMs:x}=e,w=t?.sourceAssetOverride?{asset:t.sourceAssetOverride}:e.selectedAsset,C=t?.fundingTokenOverride??y,b=Pt(n,s.decimals),I=t?.actionAmountOverride??(e.feeOnlyAction?0n:b),S=!!e.feeOnlyAction&&(t?.fundingAmountOverride??0n)>0n,k=o||r||i;if(!k)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const E={userAddress:e.recipient??k,executorAddress:k,beneficiary:e.recipient??k,outputRecipient:m?k:void 0,chainId:c,destinationToken:s.address,grossAmount:t?.fundingAmountOverride??b,netAmount:I,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:u,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},F=await d(I,E),T={chainId:c,calls:F},D=!!w&&w.asset._source!=="wallet",j=Xa(w??null,l,c),U=D||j&&!!w&&!Ja(w.asset),P=(q,R)=>({token:v.normalizeNativeTokenAddress(q),from:"escrow",to:k,amount:R}),O=(q,R,W)=>j?[Za(q,R,c),...W]:W;if(b===0n&&!S)return[T];if(w?.asset._source==="wallet"&&w.asset.chainId!==c&&!e.pivot)throw new Error("A current source-to-destination funding route is required");if(e.feeOnlyAction&&t?.fundingTokenOverride&&j)return Ds(t.fundingAmountOverride??0n,t),[T];if(_a(e)){if(m&&!g)throw new Error("Swap quote not available yet");const q=t?.fundingAmountOverride??(g?g.amountInMax:b),R=t?.sourceGasSkimOverride??0n,W=Mt(q,e.pivot.destination.decimals,e.pivot.source.decimals,"ceil"),K=W+R,G=e.sourceExactOutputSwap,_=G&&(t?.reuseQuotedSourceSwap||G.amountOut>=K)?G:e.resolveSourceExactOutputSwap?await e.resolveSourceExactOutputSwap(K):null;if(!_)throw new Error("Swap quote not available yet");Ds(_.amountInMax,t);const X=w.asset;if(_.amountInMax>X.balance)throw new Error(`Insufficient ${X.symbol} for this payment. Required ${A.formatUnits(_.amountInMax,X.decimals)} ${X.symbol}; available ${A.formatUnits(X.balance,X.decimals)} ${X.symbol}.`);const Q=_.amountOut>=K?W:_.amountOut-R;if(Q<=0n)throw new Error("Amount is too small to cover fees. Increase the amount and retry.");const te={chainId:e.pivot.source.chainId,calls:[..._.calls,ts(e.pivot.source.address,Q,v.getEscrowContractAddress(e.pivot.source.chainId)),...R>0n?[ts(e.pivot.source.address,R,v.SPICE_GAS_FEE_RECIPIENT)]:[]]},B={chainId:c,calls:[...g?.calls??[],...F],tokenTransfers:[P(e.pivot.destination.address,q),...T.tokenTransfers??[]]},$=await ns(B,f,{userAddress:k,destinationChainId:c,deliveryToken:e.pivot.destination.address,deliveryAmount:q,deliveryRecipient:k,deliveryTransfers:ss(B),sourceAsset:w.asset},x);return[te,...$]}if(w){const q=t?.fundingAmountOverride??g?.amountInMax??b;Ds(Mn(q,await fn(w.asset,C??w.asset.address,c,s),w.asset.decimals),t)}if(m&&g){const q=C??zt(w.asset,c)??w.asset.address,R=t?.fundingAmountOverride??g.amountInMax,W=U?[P(q,R)]:[],K={chainId:c,calls:[...g.calls,...F],tokenTransfers:[...W,...T.tokenTransfers??[]]};if(!U)return[K];const G=await ns(K,f,{userAddress:k,destinationChainId:c,deliveryToken:q,deliveryAmount:R,deliveryRecipient:k,deliveryTransfers:ss(K),sourceAsset:w.asset},x);return O(q,R,G)}if(U){const q=C??zt(w.asset,c)??s.address;if(j&&!e.feeOnlyAction&&q.toLowerCase()===s.address.toLowerCase())return[T];const R=t?.fundingAmountOverride??b,W={...T,tokenTransfers:[P(q,R),...T.tokenTransfers??[]]},K=await ns(W,f,{userAddress:k,destinationChainId:c,deliveryToken:q,deliveryAmount:R,deliveryRecipient:k,deliveryTransfers:ss(W),sourceAsset:w.asset},x);return O(q,R,K)}return[T]}async function Nd(e,t){const{selectedAsset:n,embeddedWalletAddress:s,recipient:o,resolvedChainId:r,destinationToken:i,buildActionCalls:l,feeExecutionMode:c,buildSpicenetBatch:d,isPayMode:u,isNon7702:f,needsSwap:m,resolvedSwap:g,quoteAmountOut:y,resolvedTokenIn:x,requestTimestampMs:w}=e;if(!n?.asset||!s)return[];const C=o??s;if(!C)return[];const b=Mo(e);let I=e.sourceSwap,S=Pt(n.amount,n.asset.decimals),k=b?e.sourceSwap.amountOutMinimum:null;if(b&&e.isFeeInclusiveInput&&(k=Ya(e.sourceSwap,t?.sourceGasSkimOverride??0n)),b&&!e.isFeeInclusiveInput&&(t?.fundingAmountOverride!==void 0||(t?.sourceGasSkimOverride??0n)>0n)){k=t?.fundingAmountOverride!==void 0?Mn(t.fundingAmountOverride,e.pivot.destination.decimals,e.pivot.source.decimals):e.sourceSwap.amountOutMinimum;const L=k+(t?.sourceGasSkimOverride??0n);if(!e.resolveSourceExactOutputSwap)throw new Error("The source quote cannot include fees yet.");const H=await e.resolveSourceExactOutputSwap(L);if(H.amountOut<L)throw new Error("The source quote does not cover the accepted funding amount.");S=H.amountInMax,I={...H,amountOutMinimum:H.amountOut}}const E=b?e.pivot.destination.address:x??zt(n.asset,r)??i.address,F=b?e.pivot.destination.decimals:await fn(n.asset,E,r,i),T=t?.fundingAmountOverride??t?.actionAmountOverride??(b?Mt(k,e.pivot.source.decimals,F,"floor"):Bs(Pt(n.amount,n.asset.decimals),n.asset.decimals,F)),D=t?.fundingAmountOverride??T,j=t?.sourceFundingAmountOverride??Mn(T,F,n.asset.decimals);Ds(b?S:j,t);const U=t?.deliveryAmountOverride??(c==="user-transfer"?D:t?.actionContextOverride?.netAmount??D),P=t?.withdrawalAmountOverride??D,O=t?.actionAmountOverride??t?.actionContextOverride?.netAmount??T;let q=g;if(m&&!u&&(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 L=t?.actionContextOverride?.netAmount??O;(!q||e.swapInputAmount!==L)&&(q=await e.resolveInputSwap(L,g??void 0))}q&&t?.onSwap?.(q,t?.actionContextOverride?.netAmount??e.swapInputAmount??O);const R=q?.amountOutMinimum??y,W={userAddress:C,executorAddress:s,beneficiary:C,outputRecipient:m?s:void 0,chainId:r,destinationToken:i.address,feeToken:c==="user-transfer"&&m&&x?x:i.address,grossAmount:D,netAmount:O,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:c,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},K=await l(O,W),G=n.asset?._source==="wallet";if(!u&&G&&n.asset.chainId===r&&Ja(n.asset)){if(m){if(!x)throw new Error("Swap input token could not be resolved");if(!q||R===null)throw new Error("Swap quote not available yet")}if(m&&q&&R){const L=await l(t?.actionAmountOverride??R,{...W,netAmount:t?.actionAmountOverride??R}),{feeCall:H,remainingCalls:fe}=$a(L,c,m,W.feeToken);return[{chainId:r,calls:[...H?[H]:[],...q.calls,...fe]}]}return[{chainId:r,calls:K}]}if(!u&&G&&n.asset.chainId!==r&&!b)throw new Error("A current source-to-destination funding route is required");const _=n.asset._source!=="wallet",X=Xa(n,f,r);if(!(_||X||b))return[{chainId:r,calls:K}];const Q=b?Rd(I,e.pivot,k,t?.sourceGasSkimOverride??0n):X?Za(x??v.normalizeNativeTokenAddress(n.asset.address),j,r):null,te=(L,H)=>({token:v.normalizeNativeTokenAddress(L),from:"escrow",to:s,amount:H});if(m){if(!x)throw new Error("Swap input token could not be resolved");if(!q||R===null)throw new Error("Swap quote not available yet")}if(m&&q&&R&&x){const L=await l(t?.actionAmountOverride??R,{...W,netAmount:t?.actionAmountOverride??R}),{feeCall:H,remainingCalls:fe}=$a(L,c,m,W.feeToken),Z={chainId:r,calls:[...H?[H]:[],...q.calls,...fe],tokenTransfers:[te(x,U)]},he=await ns(Z,d,{userAddress:s,destinationChainId:r,deliveryToken:x,deliveryAmount:U,withdrawalAmount:P,deliveryRecipient:s,deliveryTransfers:ss(Z,P),sourceAsset:n.asset},w);return Q?[Q,...he]:he}const B=x??zt(n.asset,r)??i.address,$={chainId:r,calls:K,tokenTransfers:[te(B,U)]},ie=await ns($,d,{userAddress:s,destinationChainId:r,deliveryToken:B,deliveryAmount:U,withdrawalAmount:P,deliveryRecipient:s,deliveryTransfers:ss($,P),sourceAsset:n.asset},w);return Q?[Q,...ie]:ie}async function Md(e,t,n,s,o){let r=e;for(let i=0;i<4;i++){const l=await t(r),c=await s(l,n,r,o),d=Pc(c);if(d===null||d>=e)return r;const u=r-d,f=e+u;if(f<=r)return r;r=f}return r}function Pd(e){return{...e,resolve:async(t,n,s)=>{const o=await e.resolve(t,n,s),r=o?.calls[0]?.to;return!o||!r||v.isNativeToken(t.tokenIn)?o:{...o,calls:[{to:t.tokenIn,value:0n,data:A.encodeFunctionData({abi:A.erc20Abi,functionName:"approve",args:[r,o.amountInMax]})},...o.calls]}}}}function Ns(e){const t=(e?.customVenues??[]).map(s=>_i(Pd(s),e?.executorAddress));async function n(s,o,r){const i=t.filter(d=>d.chainIds.includes(o));if(i.length===0)throw new h.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 d=>({venue:d,quote:await d.resolve(s,o,r)})))).filter(d=>d.status==="fulfilled").map(d=>d.value).filter(d=>d.quote!==null);if(l.length===0)throw new h.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 c=l.find(d=>d.venue.preferred);return c?c.quote:(l.sort((d,u)=>d.quote.amountIn<u.quote.amountIn?-1:d.quote.amountIn>u.quote.amountIn?1:0),l[0].quote)}return{getQuote:n,venues:t}}function ti(e,t,n){if(e._source==="wallet")return e.chainId===t?e.address:null;const s=Bn(e,t);return s.find(o=>o.toLowerCase()===n.toLowerCase())??s[0]??null}async function ni(e,t,n,s){const o=v.hashChainBatches(s),r=await h.relayerService.estimateBatchGas({user:t,outputToken:n,requireSimulation:!0,includePlatformFee:!0,signal:e.signal,chainBatches:s.map((i,l)=>({...i,hash:o[l].hash}))});if(!r.simulationVerified||r.gasQuoteSource!=="estimated"||r.platformFee===void 0||r.gasFee<=0n)throw new Error("Fee funding requires verified gas and platform pricing");return r}async function os(e,t){const n=e.selectedAsset?.asset,s=!t&&!!e.actionProceeds&&e.actionProceeds.token.toLowerCase()!==e.destinationToken.address.toLowerCase(),o=!!t||s,r=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!r||!o&&(!n||n._source!=="spice"&&!(n._source==="wallet"&&n.chainId===e.resolvedChainId)))throw new Error("A local embedded or Spice balance is required for fee conversion");const i=t?t.token:s?e.actionProceeds.token:ti(n,e.resolvedChainId,e.destinationToken.address);if(!i)throw new Error("This receipt has no registered destination withdrawal token");const l=v.getTokenByAddress(i,e.resolvedChainId)?.decimals??(v.isNativeToken(i)?18:o?await h.getClientForChain(e.resolvedChainId).readContract({address:i,abi:A.erc20Abi,functionName:"decimals"}):n?._source==="wallet"?n.decimals:void 0);if(l===void 0)throw new Error("Fee funding token metadata is unavailable");const c=e.destinationToken.address;if(e.actionProceeds&&!s&&e.actionProceeds.token.toLowerCase()!==c.toLowerCase())throw new Error("Action proceeds must use the destination fee token");const d=t?t.amount:e.actionProceeds?await e.actionProceeds.resolve(e.signal):0n;if(d<0n||e.signal?.aborted)throw new Error("Action proceeds quote was cancelled or invalid");const u=Ns({customVenues:[...e.resolveExactOutputSwap?[{name:"consumer-exact-output",chainIds:[e.resolvedChainId],preferred:!0,resolve:e.resolveExactOutputSwap}]:[],...jn(e.liquidityVenues).output]}),f=g=>ni(e,r,c,g);let m=await f(await e.buildPayChainBatches({fundingAmountOverride:0n}));for(let g=0;g<8;g++){const y=m.gasFee+m.platformFee,x=o?0n:d<y?d:y,w=y-x,C=w>0n?(w*110n+99n)/100n+2n:0n,b=C>0n?await u.getQuote({tokenIn:i,tokenOut:c,amountOut:C,maxSlippage:e.maxSlippage},e.resolvedChainId,r):null;if(e.signal?.aborted)throw new Error("Fee conversion quote was cancelled");if(b&&(b.amountOut!==C||b.amountInMax<=0n||b.amountInMax<b.amountIn||!b.calls.length))throw new Error("Invalid exact-output fee conversion quote");const I=b?.amountInMax??0n,S=o?0n:Mn(I,l,n.decimals);if(o&&I>d)throw new es(I,d);if(!o&&S>n.balance)throw new es(S,n.balance);let k,E=kn(await e.buildPayChainBatches({fundingAmountOverride:o?0n:I,...o?{}:{fundingTokenOverride:i},...t?{actionAmountOverride:t.amount-I}:{},onActionCalls:T=>{k=T}}),r);if(b){const T=E.length-1;E=E.map((D,j)=>j===T?{...D,calls:[...D.calls,...b.calls]}:D)}E=No(E,r,c,m.gasFee,m.platformFee);const F=await f(E);if(F.gasFee<=m.gasFee&&(m.gasFee-F.gasFee)*100n<=F.gasFee*15n&&F.platformFee===m.platformFee){const T={tokenIn:i,tokenOut:c,amountInMax:I,amountOut:C,sourceAmountMax:S,...s?{fromProceeds:!0}:{},...t?{fromInput:!0}:{}};return{feeEstimate:null,preview:{symbol:e.destinationToken.symbol,decimals:e.destinationToken.decimals,grossAmount:o?0n:C,netAmount:0n,gasFee:m.gasFee,spicenetFee:m.platformFee,totalFee:y,gasQuoteSource:"estimated"},grossFundingAmount:o?0n:I,proceedsAvailable:d,proceedsUsed:o?y:x,fundingConversion:T,fundingBatches:E,sourceSpendCap:S,destinationAmount:0n,actionDefinition:k}}m=F}throw new Error("Fee conversion pricing did not converge")}const Ud=["input","proceeds","balance"];function Wd(e){const t=c=>h.addressesEqual(c,e.feeToken),n=(c,d)=>Number(c.swap)-Number(d.swap),s={input:[],proceeds:[],balance:[]};for(const c of e.inputs??[])c.amount>0n&&s.input.push({kind:"input",...c,swap:!t(c.token)});s.input.sort(n),e.proceeds&&e.proceeds.amount>0n&&s.proceeds.push({kind:"proceeds",...e.proceeds,swap:!t(e.proceeds.token)});const o=(c,d)=>d.balanceUsd-c.balanceUsd,r=e.balances.filter(c=>c._source==="wallet"&&c.chainId===e.chainId&&c.location!=="external").sort(o),i=e.balances.filter(c=>c._source==="spice").sort(o),l=c=>{const d=[];for(const u of c){if(u.balance<=0n)continue;const f=ti(u,e.chainId,e.feeToken);f&&(e.inputs?.some(m=>h.addressesEqual(m.token,f))||d.push({kind:"balance",token:f,amount:u.balance,asset:u,swap:!t(f)}))}return d.sort(n)};return s.balance=[...l(r),...l(i)],(e.order??Ud).flatMap(c=>s[c])}function Ld(e){return e instanceof es||e instanceof h.SpiceflowError&&e.code==="NO_SWAP_ROUTE"}async function zd(e,t){const n=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!n||!e.ready||!e.authenticated)return null;const s=e.destinationToken.address,o=e.actionProceeds?{token:e.actionProceeds.token,amount:await e.actionProceeds.resolve(e.signal)}:void 0;if(e.signal?.aborted)throw new Error("Fee funding quote was cancelled");if(o&&o.amount<0n)throw new Error("Action proceeds cannot be negative");const r=Wd({feeToken:s,chainId:e.resolvedChainId,inputs:e.actionInput,proceeds:o,balances:e.feeFundingBalances??[],order:e.feeFunding});let i;const l=()=>i??(i=(async()=>{const f=await ni(e,n,s,await e.buildPayChainBatches({fundingAmountOverride:0n}));return{feeEstimate:null,preview:{symbol:e.destinationToken.symbol,decimals:e.destinationToken.decimals,gasFee:f.gasFee,spicenetFee:f.platformFee,bridgeFee:0n,totalFee:f.gasFee+f.platformFee,grossAmount:0n,netAmount:0n,gasQuoteSource:"estimated"}}})()),c=(f,m)=>e.buildPayChainBatches({...m,fundingAmountOverride:f}),d=(f,m)=>Ga({proceeds:{token:s,resolve:async()=>f},owner:n,token:s,signal:e.signal,baseline:l,buildBatches:c,fundShortfall:!1,actionAmountFor:m}),u=async f=>{if(f.kind==="input")return f.swap?os({...e,actionProceeds:void 0},f):d(f.amount,x=>f.amount-x);if(f.kind==="proceeds"){const x={...e.actionProceeds,resolve:async()=>o.amount};return f.swap?os({...e,actionProceeds:x}):d(f.amount)}const m=f.asset;if(m._source==="wallet"&&!f.swap)return d(m.balance);const g={...e,selectedAsset:{asset:m,amount:"0"},resolvedTokenIn:f.token,actionInput:void 0,actionProceeds:void 0,buildPayChainBatches:x=>e.buildPayChainBatches({...x,sourceAssetOverride:m,fundingTokenOverride:x?.fundingTokenOverride??f.token})};if(f.swap)return os(g);const y=await t(g);if(y&&(y.sourceSpendCap??0n)>m.balance)throw new es(y.sourceSpendCap,m.balance);return y};for(const f of r)try{const m=await u(f);if(!m)continue;const{swap:g,...y}=f;return{...m,fundingSource:y}}catch(m){if(e.signal?.aborted||!Ld(m))throw m}throw new Error(`No available balance can cover this action's ${e.destinationToken.symbol} execution cost`)}async function qd(e){const t=e.selectedAsset.asset;if(t.chainId!==e.destinationToken.chainId||!h.addressesEqual(v.normalizeNativeTokenAddress(t.address),v.normalizeNativeTokenAddress(e.destinationToken.address)))throw new Error("Direct execution requires the destination token on its own chain.");if(t.decimals!==e.destinationToken.decimals)throw new Error("Source and destination token decimals do not match.");const n=Pt(e.paymentAmount??e.selectedAsset.amount,t.decimals);if(n<=0n)throw new Error("Enter a positive action amount.");const s={userAddress:e.beneficiary??e.account,executorAddress:e.account,beneficiary:e.beneficiary??e.account,chainId:e.destinationToken.chainId,destinationToken:e.destinationToken.address,feeToken:t.address,grossAmount:n,netAmount:n,combinedFeeAmount:0n,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:0n,gasFee:0n,bridgeFee:0n}},o=await e.buildActionCalls(n,s);if(!o.length)throw new Error("No action calls configured.");if(v.isNativeToken(t.address)&&o.reduce((r,i)=>r+i.value,0n)>n)throw new Error("The native action exceeds the accepted source amount.");return{actionDefinition:{amount:n,context:s,calls:o},actionContext:s,batches:[{chainId:s.chainId,calls:o}],fundingAmount:n,sourceSpendCap:n,destinationAmount:n,feeEstimate:null,preview:{symbol:t.symbol,decimals:t.decimals,grossAmount:n,netAmount:n,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}}}async function Uo(e){const[t]=await e.buildSupplyChainBatches({sourceGasSkimOverride:1n,reuseQuotedSourceSwap:!0});if(!t)throw new Error("Swap quote not available yet");const{gasFee:n}=await h.relayerService.estimateBatchGas({user:e.user,outputToken:e.pivot.source.address,stepIndex:0,chainBatches:[t],signal:e.signal});return n}const si=(e,t)=>(e+t-1n)/t;function oi(e,t){return{...e,intents:e.intents.map(n=>({...n,batches:n.batches.map(s=>{const o=t.intents.find(l=>l.intentIndex===n.intentIndex)?.batches.find(l=>l.chainId===s.chainId);if(!o)return s;const r={...s.feeBreakdown};let i=0n;for(const l of["gasFee","bridgeFee"]){const c=BigInt(r[l]??"0"),d=BigInt(o.feeBreakdown[l]??"0");d>c&&(r[l]=d.toString(),i+=d-c)}return{...s,feeBreakdown:r,totalDebit:(BigInt(s.totalDebit)+i).toString()}})}))}}function Hd(e,t){const n=e.spicenetFee+(e.bridgeFee??0n);return e.grossAmount<=n?t+e.gasFee+n:si((t+e.gasFee)*e.grossAmount,e.grossAmount-n)+2n}async function ri(e){const{requiredNetFunding:t}=e;if(e.feeOnlyAction){const d=e.executionOptions?.userOverride;if(!d||t!==0n)throw new Error("Fee-only estimates require a zero action amount and its embedded executor");let u=1n,f;for(let m=0;m<8;m++){const g=kn(await e.buildBatches(u),d,f,{payoutAlreadyGross:!0}),y=await e.estimate(Rs(g,e.tokenDescriptor.chainId,e.fundingToken),e.fundingToken,u,{...e.executionOptions,feeExecutionMode:"backend-transfer"}),x=hn(y,e.tokenDescriptor);if(!x)throw new Error("The fee service did not return a fee quote for this action");const w=x.gasFee+x.spicenetFee+(x.bridgeFee??0n);if(f&&w+2n<=u)return{preview:{...x,grossAmount:u,netAmount:0n},feeEstimate:y,grossFundingAmount:u};u=(w*110n+99n)/100n+2n,f=y}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=hn(s,e.tokenDescriptor);if(!o)return{preview:Ss(n,e.tokenDescriptor,t),feeEstimate:s,grossFundingAmount:t};const r=Hd(o,t),i=d=>o.grossAmount>0n?si(d*r,o.grossAmount):d,l=i(o.spicenetFee),c=i(o.bridgeFee??0n);return{preview:{...o,grossAmount:r,netAmount:t,spicenetFee:l,bridgeFee:c,totalFee:o.gasFee+l+c},feeEstimate:s,grossFundingAmount:r}}async function ai(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 Xn(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 Vd(e){if(e.isPayMode||e.needsSwap||e.isQuoting||e.pivot||!e.embeddedWalletAddress)return null;const t=e.asset,n=v.getTokenByAddress(e.executionTokenAddress,t.chainId);return!n||t.balance<=0n?null:ai({balance:t.balance,decimals:t.decimals,planForAmount:s=>Pn({selectedAsset:{asset:t,amount:Xn(s,t.decimals)},isPayMode:!1,isNon7702:!1,isFeeInclusiveInput:!1,parsedAmount:Number(Xn(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 Pn(e){const{signal:t,selectedAsset:n,isPayMode:s,isFeeInclusiveInput:o=!1,parsedAmount:r,needsSwap:i,exactOutputSwap:l,isNon7702:c,currentPaymentAmount:d,destinationToken:u,feeExecutionMode:f,resolvedTokenIn:m,embeddedWalletAddress:g,providerEmbeddedAddress:y,resolvedChainId:x,isConnected:w,address:C,ready:b,authenticated:I,isDirect:S,resolvedSwap:k,sourceSwap:E,pivot:F,isQuoting:T,executionTokenAddress:D,buildPayChainBatches:j,buildSupplyChainBatches:U,estimate:P}=e;if(e.feeOnlyAction&&!n&&e.feeFunding?.length!==0)return zd(e,Pn);if(e.feeOnlyAction&&e.actionProceeds&&e.actionProceeds.token.toLowerCase()!==u.address.toLowerCase()||e.feeOnlyAction&&n&&(n.asset._source==="spice"||n.asset._source==="wallet"&&n.asset.chainId===x)&&(m?m.toLowerCase()!==u.address.toLowerCase():n.asset.receiptTokenId||n.asset.chainTokens))return os(e);if(e.actionProceeds&&e.feeOnlyAction){const te=g||y;if(!te||!b||!I)return null;if(m&&m.toLowerCase()!==u.address.toLowerCase())throw new Error("Action proceeds require a matching fee-token source");return Ga({proceeds:e.actionProceeds,owner:te,token:u.address,signal:t,buildBatches:(B,$)=>j({...$,fundingAmountOverride:B}),baseline:()=>Pn({...e,actionProceeds:void 0,selectedAsset:n??{amount:"0",asset:{...u,name:u.symbol,balance:0n,balanceFormatted:0,balanceUsd:0,isNative:!1,_source:"spice"}}})})}if(!n?.asset)return null;if(s){if(!g&&!y||r<=0&&!e.feeOnlyAction||i&&!l&&!e.feeOnlyAction)return null;const te=Pt(d,u.decimals),B=m||zt(n.asset,x)||n.asset.address||u.address,$={chainId:x,tokenAddress:B,symbol:v.getTokenByAddress(B,x)?.symbol??n.asset.symbol,decimals:await fn(n.asset,B,x,u)};if(!w||!C||!b||!I)return null;const ie=g||y||C,L=i?l?.amountInMax??0n:te;if(L===0n&&!e.feeOnlyAction)return null;const H=F?await Uo({user:ie,pivot:F,buildSupplyChainBatches:J=>j({...J,sourceGasSkimOverride:1n}),signal:t}):0n,fe=Date.now();let Z=await ri({requiredNetFunding:L,feeOnlyAction:e.feeOnlyAction,buildBatches:J=>j({fundingAmountOverride:J,sourceGasSkimOverride:H}).then(M=>Va(Dd(M),ie,void 0,{requestTimestampMs:fe})),fundingToken:B,estimate:P,executionOptions:{userOverride:ie,useCustomTransfers:!0,feeExecutionMode:f,signal:t},tokenDescriptor:$});if(!Z.preview)return null;let he=0n,ge,ce=[],Ae=!1;for(let J=0;J<8;J++){if(t?.aborted)throw new Error("Fee estimation cancelled");if(ce=kn(await j({fundingAmountOverride:Z.grossFundingAmount,sourceGasSkimOverride:H,onSourceSpend:we=>{he=we},onActionCalls:we=>{ge=we}}),ie,Z.feeEstimate,{payoutAlreadyGross:!0,requestTimestampMs:fe}),e.feeOnlyAction){Ae=!0;break}const M=await P(ce,B,Z.grossFundingAmount,{userOverride:ie,useCustomTransfers:!0,feeExecutionMode:f,signal:t}),Y=f==="user-transfer"?oi(M,Z.feeEstimate):M,ue=hn(Y,$)??Ss(ce,$,L);if(!ue)return null;const We=L+ue.gasFee+ue.spicenetFee+(ue.bridgeFee??0n),Ce=hn(Z.feeEstimate,$),oe=(Ce?.gasFee??0n)===ue.gasFee&&(Ce?.spicenetFee??0n)===ue.spicenetFee&&(Ce?.bridgeFee??0n)===(ue.bridgeFee??0n),Ee=Z.grossFundingAmount===We&&oe;if(Z={feeEstimate:Y,grossFundingAmount:We,preview:{...ue,grossAmount:We,netAmount:L}},Ee){Ae=!0;break}}if(!Ae)throw new Error("Payment fees did not converge. Refresh the quote before submitting.");if(!Z.preview)return null;const N=F?Mt(H,F.source.decimals,F.destination.decimals,"ceil"):0n;return{...Z,batches:ce,sourceSpendCap:he,actionDefinition:ge,destinationAmount:te,preview:{...Z.preview,grossAmount:Z.preview.grossAmount+N,gasFee:Z.preview.gasFee+N,totalFee:(Z.preview.totalFee??0n)+N},...F?{sourceGasSkim:H}:{}}}if(r<=0||!g)return null;const O=g||y;if(F&&!E)return null;const q=Mo({isPayMode:s,selectedAsset:n,resolvedChainId:x,sourceSwap:E,pivot:F});if(!(!s&&!c&&n.asset?._source==="wallet"&&n.asset.chainId!==x)&&!S&&!k&&!T||T)return null;let R=await U();if(R.length===0)return null;const W={chainId:x,tokenAddress:D,symbol:v.getTokenByAddress(D,x)?.symbol??(n.asset.chainId===x&&h.addressesEqual(n.asset.address,D)?n.asset.symbol:u.symbol),decimals:await fn(n.asset,D,x,u)},K=q?await Uo({user:O,pivot:F,buildSupplyChainBatches:U,signal:t}):0n;q&&K>0n&&(R=await U({sourceGasSkimOverride:K}));const G=q?Mt(o?Ya(E,K):E.amountOutMinimum,F.source.decimals,F.destination.decimals,"floor"):Mt(Pt(n.amount,n.asset.decimals),n.asset.decimals,W.decimals,"floor"),_={userOverride:O,useCustomTransfers:!0,feeExecutionMode:f,signal:t,...q?{skipUserFundingPreflight:!0}:{}};let X=G,Q=await P(R,D,X,_);for(let te=0;te<8;te++){if(t?.aborted)throw new Error("Fee estimation cancelled");const B=hn(Q,W)??Ss(R,W,X);if(!B)return null;const $=Wo(B,G,o,f);X=$.grossAmount;let ie,L,H,fe,Z;const he=await U({fundingAmountOverride:X,sourceGasSkimOverride:K,actionContextOverride:$,onDestinationAmount:J=>{ie=J},onSourceSpend:J=>{L=J},onSwap:(J,M)=>{H=J,fe=M},onActionCalls:J=>{Z=J}}),ge=await P(he,D,X,_),ce=f==="user-transfer"?oi(ge,Q):ge,Ae=hn(ce,W)??Ss(he,W,X);if(!Ae)return null;const N=Wo(Ae,G,o,f);if(JSON.stringify($,(J,M)=>typeof M=="bigint"?M.toString():M)===JSON.stringify(N,(J,M)=>typeof M=="bigint"?M.toString():M)){const J=q?Mt(K,F.source.decimals,F.destination.decimals,"ceil"):0n;return{batches:he,fundingAmount:X,actionContext:$,sourceSpendCap:L,destinationAmount:ie,destinationSwap:H,swapInputAmount:fe,actionDefinition:Z,feeEstimate:ce,sourceGasSkim:K,preview:{...Ae,grossAmount:X+J,netAmount:$.netAmount,gasFee:Ae.gasFee+J,spicenetFee:$.feeBreakdown.spicenetFee,totalFee:$.combinedFeeAmount+J}}}Q=ce,R=he}throw new Error("Fees did not converge. Refresh the quote before submitting.")}function Wo(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 r=n?Oc(t,o,10n):null;if(r&&!r.coversFees)throw new Error("Amount is too small to cover fees. Increase the amount and retry.");const i=r?.spicenetFee??(s==="user-transfer"?ks(t,10n):e.spicenetFee);return{grossAmount:r?.grossAmount??t+i+o,netAmount:r?.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=zt(n,e.resolvedChainId);if(!s||!h.addressesEqual(s,e.executionTokenAddress))return;const o=v.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),r=Mn(t,o?.decimals??e.destinationToken.decimals,n.decimals);if(r<=n.balance)return;const i=A.formatUnits(r,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 Gd(e){const t=v.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 Kd(e){const t=e.selectedAsset.asset,n=Pt(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 Zd(e,t){return e.feeQuote?.sourceGasSkim!==void 0?e.feeQuote.sourceGasSkim:Uo({user:t,pivot:e.pivot,buildSupplyChainBatches:e.execution.buildSupplyChainBatches})}function Yd(e,t,n){const s=hn(e,Gd(t));if(s)return Wo(s,n,!!t.isFeeInclusiveInput,t.feeExecutionMode)}function ii(e,t,n){let s=0n,o=0n;const r=n.toLowerCase();for(const i of e)if(i.chainId===t){for(const l of i.calls??[])if(l.to.toLowerCase()===r)try{const c=A.decodeFunctionData({abi:A.erc20Abi,data:l.data});if(c.functionName!=="transfer")continue;const d=c.args[0].toLowerCase(),u=c.args[1];d===v.SPICE_PLATFORM_FEE_RECIPIENT.toLowerCase()?s+=u:d===v.SPICE_GAS_FEE_RECIPIENT.toLowerCase()&&(o+=u)}catch{continue}}return{spicenetFee:s,gasFee:o}}function Xd(e,t,n){if(!e.isFeeInclusiveInput||!e.needsSwap)return;const s=t.swapInputAmount??t.preview.netAmount,o=ii(n,e.resolvedChainId,e.resolvedTokenIn??e.executionTokenAddress);if(s+o.gasFee+o.spicenetFee>t.preview.grossAmount)throw new Error("Swap input plus fees exceeds the entered amount. Refresh the quote before retrying.")}function Jd(e,t,n){const s=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,o=ii(e,t.resolvedChainId,s);return o.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||o.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:Cn(o.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&Cn(o.gasFee,n.feeBreakdown.gasFee,100n)}function $d(e,t){return e?Cn(e.grossAmount,t.grossAmount,100n)&&Cn(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&Cn(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&Cn(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}function _d(e,t){const n=v.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 eu(e,t){const n=e.feeQuote;return n?.feeEstimate&&n.grossFundingAmount!==void 0?{grossFundingAmount:n.grossFundingAmount,feeEstimate:n.feeEstimate}:ri({...t,feeOnlyAction:e.feeOnlyAction,estimate:e.execution.estimate,tokenDescriptor:_d(e,t.fundingToken)})}function li(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 ci(e,t){const n=h.sanitizeError(t,"Payment failed. Please try again.");e.ui.setError(n),e.ui.setPaymentResult({status:"failed",error:n})}async function di(e){e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setStep("executing"),e.ui.setStatusMsg("Confirm the transaction in your external wallet..."),e.ui.setTxHash(null),e.isPayMode&&(e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"}));try{if(e.validateFeeQuote?.(),!e.feeQuote?.batches||!e.feeQuote.actionDefinition)throw new Error("Review the direct action plan before submitting.");const t=await e.execution.execute(e.feeQuote.batches,e.destinationToken.address,0n,e.execution.onProgress);e.ui.setTxHash(t),e.ui.setStep("success"),e.ui.setStatusMsg("Transaction confirmed"),e.isPayMode&&e.ui.setPaymentResult({status:"success",txHash:t})}catch(t){e.isPayMode?ci(e,t):li(e,t,!1)}finally{e.ui.setIsExecuting(!1)}}async function ui(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.directExternalAction)return di(e);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=Mo(e),o=s?await Zd(e,n):0n,r=x=>e.execution.buildSupplyChainBatches(s?{...x,sourceGasSkimOverride:o}:x);s&&Kd(e);const i=e.feeQuote?.batches?e.feeQuote:await Pn({...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 c=i.batches;const d=c.some(x=>x.tokenTransfers?.length),u={userOverride:n,useCustomTransfers:d,feeExecutionMode:e.feeExecutionMode,...s?{skipUserFundingPreflight:!0}:{}},f=i.fundingAmount,m=i.actionContext;Qd(e,f);let g=m;const y=await e.execution.execute(c,e.executionTokenAddress,d?f:0n,e.execution.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...u,skipUserFundingPreflight:!0,validateBeforeSubmit:x=>Xd(e,i,x),adjustBatchesForEstimate:({feeEstimate:x,chainBatches:w})=>{const C=Yd(x,e,l);if(!C)return null;const b=$d(g,C),I=Jd(w,e,C);return b||I?null:(g=C,r({fundingAmountOverride:C.grossAmount,actionContextOverride:C}))}}:{...u,skipPreSubmitFeeEstimate:!0});e.ui.setTxHash(y),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){li(e,n,t.signal.aborted)}finally{e.ui.setIsExecuting(!1)}}async function pi(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}const t=e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t){e.ui.setError("Select a payment source");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.parsedAmount>0&&e.needsSwap&&!e.exactOutputSwap){e.ui.setError("Swap quote not available. Try a different asset.");return}if(e.directExternalAction)return di(e);const n=_a(e)&&!t,s=n?e.feeQuote?.sourceGasSkim??0n:0n,o=r=>e.execution.buildPayChainBatches(n?{...r,sourceGasSkimOverride:s}:r);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 r=Pt(e.currentPaymentAmount,e.destinationToken.decimals),i={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,...n?{skipUserFundingPreflight:!0}:{}};if(t&&!e.feeOnlyAction){const I=await o(),S=await e.execution.execute(I,e.executionTokenAddress,0n,k=>{k.txHash&&(e.ui.setPaymentResult(E=>({...E??{status:"processing"},txHash:k.txHash})),e.ui.setTxHash(k.txHash))},void 0,i);e.ui.setPaymentResult(k=>({status:"success",txHash:k?.txHash||S}));return}const l=e.selectedAsset?.asset,c=e.feeQuote?.fundingSource;if(!l&&!e.actionProceeds&&!c)throw new Error("Select a payment source");const d=e.feeQuote?.fundingConversion?.tokenIn||c?.token||e.resolvedTokenIn||l?.address||e.destinationToken.address,u=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:r,f=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,m=!!e.feeQuote?.fundingConversion||!!c&&(c.kind!=="balance"||c.asset?._source==="wallet"),{grossFundingAmount:g,feeEstimate:y}=m?{grossFundingAmount:e.feeQuote.grossFundingAmount??0n,feeEstimate:void 0}:await eu(e,{requiredNetFunding:u,buildBatches:I=>e.execution.buildPayChainBatches({fundingAmountOverride:I}).then(S=>kn(S,f)),fundingToken:d,executionOptions:i}),x=e.feeQuote?.fundingBatches??e.feeQuote?.batches??kn(await o({fundingAmountOverride:g}),f,e.actionProceeds?void 0:y,{payoutAlreadyGross:!0}),w=jd(e,e.feeQuote?.fundingConversion?.tokenOut??d,g),C=e.feeOnlyAction||x.some(I=>I.tokenTransfers?.length),b=await e.execution.execute(x,d,C?g:0n,I=>{I.txHash&&(e.ui.setPaymentResult(S=>({...S,txHash:I.txHash})),e.ui.setTxHash(I.txHash))},void 0,{...i,...w,skipPreSubmitFeeEstimate:!0});e.ui.setPaymentResult(I=>({status:"success",txHash:I?.txHash||b}))}catch(r){ci(e,r)}finally{e.ui.setIsExecuting(!1)}}async function fi(e){const{definition:t,account:n,chainId:s}=e,{calls:o}=t;if(!h.addressesEqual(t.context.executorAddress,n)||t.context.chainId!==s||!o.length)throw new Error("The direct action no longer matches its wallet or chain.");const r=h.getClientForChain(s);let i;for(const l of o){await e.assertCurrent();const[c,d]=await Promise.all([va({client:r,account:n,calls:[l]}),r.getBalance({address:n})]);if(d<l.value+c)throw new Error("The external wallet has insufficient native balance for this transaction and network gas.");const{extWc:u,viemChain:f}=await Eo({wallet:e.wallet,account:n,chainId:s});i=await $c({extWc:u,viemChain:f,client:r,calls:[l],errorMessage:"The external transaction reverted. Retry the unfinished action when ready."})}if(!i)throw new Error("The direct action has no confirmed receipt.");return i}function tu(e,t,n){const s=[],o=(r,i,l)=>{l>0n&&s.push(v.isNativeToken(r)?{to:i,value:l,data:"0x"}:{to:r,value:0n,data:A.encodeFunctionData({abi:A.erc20Abi,functionName:"transfer",args:[i,l]})})};return t.feeExecutionMode==="user-transfer"&&t.feeBreakdown&&(o(t.feeToken??t.destinationToken,v.SPICE_PLATFORM_FEE_RECIPIENT,t.feeBreakdown.spicenetFee),o(t.feeToken??t.destinationToken,v.SPICE_GAS_FEE_RECIPIENT,t.feeBreakdown.gasFee+t.feeBreakdown.bridgeFee)),o(t.destinationToken,n,e),s}function nu(e,t,n,s){let o=0n;for(const r of e)if(r.chainId===n){for(const i of r.calls)if(h.addressesEqual(i.to,t))try{const l=A.decodeFunctionData({abi:A.erc20Abi,data:i.data});l.functionName==="transfer"&&h.addressesEqual(l.args[0],s)&&(o+=l.args[1])}catch{}}return o}async function mi(e){const{asset:t,embedded:n,external:s,amount:o}=e;if(!s||!e.externalWallet)throw new Error("Connect the source wallet before funding.");if(o<=0n)return;const r=h.getClientForChain(t.chainId),i=t.isNative||v.isNativeToken(t.address),[l,c]=await Promise.all([Sa({client:r,account:s,recipient:n,token:t.address,isNative:i,amount:o}),r.getBalance({address:s})]);if(c<l+(i?o:0n))throw new Error("The source wallet has insufficient native balance for funding and gas.");const{extWc:d,viemChain:u}=await Eo({wallet:e.externalWallet,account:s,chainId:t.chainId});await _c({extWc:d,sourceClient:r,recipient:n,tokenAddr:t.address,isNative:i,amount:o,viemChain:u,observer:{onSending:()=>e.assertCurrent()}})}function hi(e,t,n){return h.addressesEqual(e.address,t)&&e.chainId===n?e._source==="wallet"?0:1:2}function su(e,t,n,s){const o=hi(e,n,s)-hi(t,n,s);return o!==0?o:(t.balanceUsd||0)-(e.balanceUsd||0)}const ou=Pr;function gi(e){const t=p.useContext(h.SpiceFlowProviderContext),n=h.useProviderWallets(),s=t?.embeddedWalletAddress||n.embeddedAddress,o=t?.externalWalletAddress||n.externalAddress,r=(t?.mode||"7702")!=="7702",i=Dn({...e,owner:s,enabled:e.enabled&&!!s&&(!r||!!e.includeCrossChainEmbeddedAssets),role:"spend-source",destination:e.destinationToken}),l=Dn({...e,owner:o,enabled:e.enabled&&!!o&&(r||!!e.includeExternalWalletAssets),role:"spend-source",destination:e.destinationToken});return{displayAssets:p.useMemo(()=>[...i.assets,...l.assets].sort((c,d)=>su(c,d,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:r,refreshSpiceAssets:i.refresh,refreshWalletAssets:i.refresh,loading:i.loading||l.loading,refreshing:i.refreshing||l.refreshing,error:i.error||l.error}}function ru(e,t){return!e||e._source!=="wallet"?null:ro(e,t)}function Lo(e,t){return gr({aerodrome:!1,oneInch:e?.includeDefaults===!1?{chainIds:[]}:void 0,customVenues:t})}const zo=jn(),au=Lo(void 0,zo.input);function xi(e){return{venue:"mapped-transfer",amountOut:e,amountOutMinimum:e,calls:[]}}function yi(e){return{venue:"mapped-transfer",amountIn:e,amountInMax:e,amountOut:e,calls:[]}}async function qo(e){if(h.addressesEqual(e.tokenIn,e.tokenOut))return xi(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?Lo(e.liquidityVenues,jn(e.liquidityVenues).input):au).resolveSwap({type:"swap",tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:e.amountIn,maxSlippage:e.maxSlippage},e.chainId,e.recipient,e.selectedSwap);if(!t)throw new Error("No liquidity for this pair.");return t}async function iu(e){return h.addressesEqual(e.tokenIn,e.tokenOut)?yi(e.amountOut):Ns({customVenues:e.liquidityVenues?jn(e.liquidityVenues).output:zo.output}).getQuote({tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountOut:e.amountOut,maxSlippage:e.maxSlippage},e.chainId,e.recipient)}function wi(e){const{enabled:t=!0,direction:n,selectedAsset:s,destinationToken:o,chainId:r,recipient:i,paymentAmount:l,maxSlippage:c,refreshIntervalMs:d,resolveInputSwap:u,resolveExactOutputSwap:f}=e,m=p.useContext(h.SpiceFlowProviderContext),g=m?.liquidityVenues,y=JSON.stringify([m?.network,m?.apiUrl,m?.rpcOverrides]),[x,w]=p.useState(!1),[C,b]=p.useState(null),[I,S]=p.useState(null),[k,E]=p.useState(null),[F,T]=p.useState(null),[D,j]=p.useState(null),[U,P]=p.useState(null),[O,q]=p.useState(null),[R,W]=p.useState(null),[K,G]=p.useState(null),[_,X]=p.useState(null),[Q,te]=p.useState(null),[B,$]=p.useState(null),[ie,L]=p.useState(null),[H,fe]=p.useState(0),[Z,he]=p.useState(null),[ge,ce]=p.useState(null),Ae=p.useRef(null),N=p.useRef(null),J=p.useRef(0),M=p.useRef(new Map),Y=p.useCallback(()=>{J.current++,M.current.clear(),ce(null),fe(De=>De+1)},[]),ue=d&&d>0?d:null,We=g?JSON.stringify(g):"",Ce=p.useMemo(()=>g?jn(g):zo,[We]),oe=p.useMemo(()=>Lo(g,Ce.input),[Ce]),Ee=p.useMemo(()=>Ns({customVenues:[...f?[{name:"consumer-exact-output",chainIds:[r],preferred:!0,resolve:f}]:[],...Ce.output]}),[f,r,Ce]);p.useEffect(()=>{M.current.clear()},[Ee]);const we=p.useMemo(()=>t?ru(s?.asset,r):null,[t,s?.asset,r]),Pe=p.useMemo(()=>{if(!t||!s?.asset)return null;if(we)return we.destination.address;const De=zt(s.asset,r);if(De)return De;const Ge=an(s.asset.address,r,s.asset.chainId);return Ge?Ge.address:null},[t,s?.asset,r,we]),Qe=p.useMemo(()=>t&&s?.asset?Bn(s.asset,r):[],[t,s?.asset,r]),it=p.useMemo(()=>Qe.map(De=>De.toLowerCase()).join(","),[Qe]),ze=JSON.stringify([t,y,s?.asset.owner,s?.asset.location,s?.asset.receiptTokenId,s?.asset.address,s?.asset.chainId,s?.asset.decimals,s?.amount,r,it,n,l]);p.useEffect(()=>{let De=!1;if(N.current&&(clearTimeout(N.current),N.current=null),!t||!s?.asset||we||Qe.length<=1){$(null),L(null);return}return N.current=setTimeout(async()=>{const Ge=n==="input"?s.amount:l||"0";let qe=0n;try{qe=n==="input"?Pt(Ge,s.asset.decimals):0n}catch{qe=0n}try{const $e=await Dr(s.asset,r,{requiredAmount:qe});De||($($e),L(ze))}catch{De||$(null)}},400),()=>{De=!0,N.current&&(clearTimeout(N.current),N.current=null)}},[ze]);const Je=p.useMemo(()=>(ie===ze?B:null)??Pe,[B,ie,ze,Pe]),Re=p.useMemo(()=>!s?.asset||!Je?[]:[Je,...Qe.filter(De=>De.toLowerCase()!==Je.toLowerCase())],[s?.asset,Je,Qe]),ot=p.useMemo(()=>!s?.asset||!Hn(s.asset.address,s.asset.chainId,o.address,o.chainId)||!Je?!1:h.addressesEqual(Je,o.address),[s,o.address,o.chainId,Je]),_e=Je?h.addressesEqual(Je,o.address):!1,Ue=n==="output"&&parseFloat(l||"0")===0,Le=t&&!!s?.asset&&!ot&&!_e&&!Ue,ct=JSON.stringify([t,We,n,Le,y,s?.asset.owner,s?.asset.location,s?.asset.receiptTokenId,s?.asset.address,s?.asset.chainId,s?.asset.decimals,n==="input"?s?.amount:l,Re.map(De=>De.toLowerCase()),r,o.address.toLowerCase(),o.chainId,o.decimals,i?.toLowerCase(),c,ue,we?.source.address.toLowerCase()??""]),Me=p.useMemo(()=>({}),[ct,oe,Ee,u,H]),Ze=ge?.request===Me&&(!ue||ge.expiresAt>Date.now());return p.useEffect(()=>{if(!ue||ge?.request!==Me)return;const De=setTimeout(Y,Math.max(0,ge.expiresAt-Date.now()));return()=>clearTimeout(De)},[ue,ge,Me,Y]),p.useEffect(()=>{Ae.current&&clearTimeout(Ae.current),he(Me),ce(null),b(null);const De=n==="input"?s?.amount:l,Ge=parseFloat(De||"0");if(!t||!Number.isFinite(Ge)||Ge<=0||!s?.asset||!i||Re.length===0){J.current++,S(null),E(null),T(null),j(null),P(null),q(null),W(null),te(null),b(null),w(!1);return}const qe=s.asset.decimals;let $e;try{$e=n==="input"?Pt(s.amount,qe):Pt(l||"0",o.decimals)}catch(xe){J.current++,b(xe instanceof Error?xe.message:"Invalid amount or token precision"),w(!1);return}const Se=++J.current,Ne=()=>Se!==J.current;w(!0);const ft=n==="output"?150:400,ne=async(xe,me,ee,ye={chainId:r,tokenOut:o.address,amountIn:$e},Fe=Re)=>{for(const Ye of Fe){const je=`${y}:${We}:${n}:${ye.chainId}:${Ye.toLowerCase()}:${ye.tokenOut.toLowerCase()}:${ye.amountIn.toString()}:${i.toLowerCase()}:${c??"default"}:${ue??"default"}`,z=M.current.get(je),ke=z&&z.expiresAt>Date.now()?xe(z):void 0;if(ke)return{quote:ke,tokenIn:Ye,expiresAt:z.expiresAt};const be=await ee(Ye);if(Ne())return"stale";if(!be)continue;const He=Date.now()+Math.min(ue??3e4,3e4);return M.current.set(je,{expiresAt:He,direction:n,...me(be)}),{quote:be,tokenIn:Ye,expiresAt:He}}return null},Te=xe=>ne(me=>me.resolvedSwap,me=>({resolvedSwap:me}),async me=>{const ee=!we&&xe.chainId===r&&s.asset._source!=="wallet",ye=ee?await fn(s.asset,me,xe.chainId,o):qe;if(Ne())return null;const Fe=ee?Bs(xe.amountIn,qe,ye):xe.amountIn;if(h.addressesEqual(me,xe.tokenOut))return xi(Fe);const Ye={type:"swap",tokenIn:me,tokenOut:xe.tokenOut,amountIn:Fe,maxSlippage:c};if(u){const je=await u(Ye,xe.chainId,i);if(je)return je}return oe.resolveSwap(Ye,xe.chainId,i)},xe,xe.candidates);return Ae.current=setTimeout(async()=>{try{if(n==="input"){let xe=null,me=$e;if(we){if(xe=await Te({chainId:we.source.chainId,tokenOut:we.source.address,amountIn:$e,candidates:[s.asset.address]}),xe==="stale"||Ne())return;if(!xe)throw new Error("No liquidity for this pair");me=Mt(xe.quote.amountOutMinimum,we.source.decimals,we.destination.decimals,"floor")}const ee=Le||!we?await Te({chainId:r,tokenOut:o.address,amountIn:me,candidates:Re}):null;if(ee==="stale"||Ne())return;if(Le&&!ee)throw new Error("No liquidity for this pair");const ye=ee?ee.quote.amountOut:me,Fe=Math.min(ee?.expiresAt??1/0,xe?.expiresAt??1/0),Ye=we?.destination.decimals??await fn(s.asset,ee.tokenIn,r,o),je=!we&&s.asset._source!=="wallet"?Bs(me,qe,Ye):me;if(Ne())return;te(ee?.tokenIn??we?.destination.address??null),ce({request:Me,key:`${A.keccak256(A.toHex(ct))}:${Se}`,expiresAt:Fe}),W(ye),G(je),X(Ye),T(Le?ee?.quote??null:null),j(xe?.quote??null),P(null),q(null);const z=parseFloat(A.formatUnits(ye,o.decimals));S(z<.01?z.toPrecision(4):z.toLocaleString(void 0,{maximumFractionDigits:6})),E(null),b(null)}else{const xe=je=>ne(z=>z.exactOutputSwap,z=>({exactOutputSwap:z}),async z=>{try{return h.addressesEqual(z,je.tokenOut)?yi(je.amountOut):await Ee.getQuote({tokenIn:z,tokenOut:je.tokenOut,amountOut:je.amountOut,maxSlippage:c},je.chainId,i)}catch{return null}},{chainId:je.chainId,tokenOut:je.tokenOut,amountIn:je.amountOut},je.candidates),me=!we||Le,ee=me?await xe({chainId:r,tokenOut:o.address,amountOut:$e,candidates:Re}):null;if(ee==="stale"||Ne())return;if(me&&!ee)throw new Error("No liquidity for this pair");let ye=null;if(we){const je=ee?ee.quote.amountInMax:$e;if(ye=await xe({chainId:we.source.chainId,tokenOut:we.source.address,amountOut:Mt(je,we.destination.decimals,we.source.decimals,"ceil"),candidates:[s.asset.address]}),ye==="stale"||Ne())return;if(!ye)throw new Error("No liquidity for this pair")}const Fe=ye?qe:await fn(s.asset,ee.tokenIn,r,o);if(Ne())return;te(ee?.tokenIn??we?.destination.address??null),ce({request:Me,key:`${A.keccak256(A.toHex(ct))}:${Se}`,expiresAt:Math.min(ee?.expiresAt??1/0,ye?.expiresAt??1/0)}),q(ee?.quote??null),P(ye?.quote??null),T(null),j(null),W(null);const Ye=ye?.quote.amountIn??ee.quote.amountIn;E(A.formatUnits(Ye,Fe)),S(null),b(null)}}catch(xe){if(Ne())return;const me=xe instanceof Error?xe.message:"Failed to get quote";b(me),S(null),E(null),T(null),j(null),P(null),q(null),W(null),te(null)}finally{Ne()||w(!1)}},Le||we?ft:0),()=>{J.current++,Ae.current&&clearTimeout(Ae.current)}},[Me]),{inputAmount:Ze&&n==="input"?K:null,inputDecimals:Ze&&n==="input"?_:null,quoteKey:Ze?ge.key:null,quoteExpiresAt:Ze?ge.expiresAt:null,refreshQuote:Y,isQuoting:Z===Me?x:Le||!!we,quoteError:Z===Me?C:null,estimatedOutput:Ze?I:null,estimatedInput:Ze?k:null,resolvedSwap:Ze?F:null,exactOutputSwap:Ze?O:null,quoteAmountOut:Ze?R:null,resolvedTokenIn:Le&&Ze?Q??Je:Je,isDirect:_e,needsSwap:Le,selectedIsEquivalent:ot,sourceSwap:Ze?D:null,sourceExactOutputSwap:Ze?U:null,pivot:we}}function rs(e){const{enabled:t,destinationToken:n,selectedAsset:s,paymentAmount:o="0",sourceChains:r,supportedSourceAssets:i,buildActionCalls:l,feeExecutionMode:c="user-transfer",buildSpicenetBatch:d,onPayExecute:u,resolveExactOutputSwap:f,amountDirection:m="input",onSuccess:g,onError:y}=e,x=m==="output",w=m==="input-inclusive",C=x?"output":"input",b=n.chainId,I=p.useContext(h.SpiceFlowProviderContext),S=I?.mode||"7702",k=!1,E=!!I?.isWhitelistGateActive,F=!!I?.isWhitelistConfigured&&I?.isUserWhitelisted!==!0,T=p.useMemo(()=>r??I?.supportedChainIds??[],[r,I?.supportedChainIds]),D=i,{address:j,isConnected:U,isReady:P,isAuthenticated:O,provider:q}=h.useWallet(),{execute:R,estimate:W}=Es(),{externalWallet:K,embeddedAddress:G,activeWallet:_,activeAddress:X}=h.useProviderWallets(),Q=I?.externalWalletAddress,te=I?.embeddedWalletAddress||G,B=s,$=Mr(B?.asset,S!=="7702"),ie=!!B&&B.asset.chainId===n.chainId&&h.addressesEqual(v.normalizeNativeTokenAddress(B.asset.address),v.normalizeNativeTokenAddress(n.address)),L=S!=="7702"&&$&&ie&&(!x||Number(o)>0)&&!e.feeOnlyAction&&!e.actionProceeds,H=$&&!L,fe=e.actionExecution?.wallet==="external"&&!L,Z=u?"Move onPayExecute protocol calls to buildActionCalls and application updates to onSuccess before continuing.":fe&&(x||e.prependSourceEscrow||v.isNativeToken(n.address))?"External wallet execution requires an ERC20 input supply with SDK-managed funding.":null,he=p.useMemo(()=>fe&&Q?(le,ut)=>tu(le,ut,Q):l,[fe,Q,l]),{displayAssets:ge,filteredSpiceAssets:ce,walletAssets:Ae,embeddedWalletAddress:N,refreshSpiceAssets:J,refreshWalletAssets:M,loading:Y,refreshing:ue,error:We}=gi({address:j,destinationToken:n,supportedSourceAssets:D,sourceChains:T,additionalSourceTokens:[...e.additionalSourceTokens??[],...B?.asset._source==="wallet"?[{address:B.asset.address,chainId:B.asset.chainId,decimals:B.asset.decimals,symbol:B.asset.symbol,name:B.asset.name,logoURI:B.asset.logoURI}]:[]],includeExternalWalletAssets:e.includeExternalWalletAssets,includeCrossChainEmbeddedAssets:e.includeCrossChainEmbeddedAssets,enabled:t&&(S!=="7702"?!!Q:!!te)}),Ce=ge,oe=p.useMemo(()=>e.feeOnlyAction?Ce.filter(le=>le.balance>0n&&le.location!=="external"&&(le._source==="spice"||le._source==="wallet"&&le.chainId===b)):[],[Ce,e.feeOnlyAction,b]),Ee=B?[...Ae,...ce].find(le=>pt(le)===pt(B.asset)):void 0,we=p.useMemo(()=>B&&Ee?{...B,asset:Ee}:B,[B,Ee]),Pe=B?bn(Ee??B.asset,"spend-source",{allowedTokens:I?.allowedTokens,rpcOverrides:I?.rpcOverrides,liquidityVenues:I?.liquidityVenues,isWhitelistGateActive:E},n,D):null,Qe=Ee?Ee.balance<(B?.asset.balance??0n)?Ee.balance:B.asset.balance:0n,[it,ze]=p.useState(!1),[Je,Re]=p.useState(null),ot=p.useRef(y);ot.current=y;const _e=p.useCallback(le=>{Re(le),typeof le=="string"&&le&&ot.current?.(new Error(le),h.getRelayerErrorDetail(le))},[]),[Ue,Le]=p.useState("idle"),[ct,Me]=p.useState(""),[Ze,De]=p.useState(null),[Ge,qe]=p.useState(!1),[$e,Se]=p.useState(null),[Ne,ft]=p.useState(null),[ne,Te]=p.useState(!1),[xe,me]=p.useState(!1),[ee,ye]=p.useState(null),Fe=p.useRef(B),Ye=p.useRef(!1),je=p.useRef(null),z=p.useRef(null),ke=p.useRef(null),be=p.useRef(null),He=p.useRef(g),At=p.useRef(null),[Et,ve]=p.useState(null),[mt,ht]=p.useState(null),[wt,Gt]=p.useState(!1),[yn,ln]=p.useState(0);p.useEffect(()=>{Fe.current=B},[B]);const dt=L?Q:N||G||j,Rt=wi({enabled:t&&!F&&!L,direction:C,selectedAsset:B,destinationToken:n,chainId:b,recipient:dt,paymentAmount:o,resolveExactOutputSwap:f,resolveInputSwap:e.resolveInputSwap,maxSlippage:e.maxSlippage}),rt=L?{...Rt,quoteKey:"direct-external",quoteExpiresAt:null,quoteAmountOut:null,inputAmount:null,inputDecimals:B?.asset.decimals??null,isQuoting:!1,quoteError:null,isDirect:!0,needsSwap:!1,selectedIsEquivalent:!0,resolvedTokenIn:n.address,resolvedSwap:null,exactOutputSwap:null,sourceSwap:null,sourceExactOutputSwap:null,pivot:null,estimatedInput:x?o:B?.amount??null,estimatedOutput:x?o:B?.amount??null}:Rt,Be=rt,{isQuoting:jt,resolvedSwap:Ut,exactOutputSwap:Tt,quoteAmountOut:qt,resolvedTokenIn:Ke,isDirect:et,needsSwap:gt,selectedIsEquivalent:Wt,sourceSwap:nt,sourceExactOutputSwap:tt,pivot:de}=rt,xt=x?parseFloat(o||"0"):parseFloat(B?.amount||"")||0,_t=B?.asset?._source==="wallet",In=!!B?.asset&&_t&&B.asset.chainId!==b,An=B?Number(A.formatUnits(Qe,B.asset.decimals)):0,cn=p.useMemo(()=>{if(!B||x)return!1;try{return Pt(B.amount||"0",B.asset.decimals)>Qe}catch{return!0}},[B,x,Qe]);p.useEffect(()=>{t||(_e(null),ze(!1),Le("idle"),Me(""),De(null),qe(!1),Se(null),ft(null),Te(!1),me(!1),ye(null),Ye.current=!1,je.current&&(je.current.abort(),je.current=null))},[t]);const Wn=p.useCallback(le=>{Le({building:"building","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[le.step]||"executing"),Me(le.message),le.txHash&&De(le.txHash)},[]),Lt=p.useMemo(()=>({currentPaymentAmount:o,isFeeInclusiveInput:w,feeOnlyAction:e.feeOnlyAction,swapInputAmount:rt.inputAmount,destinationToken:n,embeddedWalletAddress:N,providerEmbeddedAddress:G,externalWalletAddress:Q,address:j,recipient:e.recipient??(S!=="7702"?Q:void 0),isNon7702:k,isPayMode:x,resolvedChainId:b,buildActionCalls:he,feeExecutionMode:c,buildSpicenetBatch:d,selectedAsset:B,needsSwap:gt,resolvedSwap:Ut,exactOutputSwap:Tt,quoteAmountOut:qt,resolvedTokenIn:Ke,sourceSwap:nt,sourceExactOutputSwap:tt,pivot:de,resolveSourceExactOutputSwap:async le=>{if(!de||!dt)throw new Error("Swap route is not ready.");const ut=await iu({chainId:de.source.chainId,recipient:dt,tokenIn:B.asset.address,tokenOut:de.source.address,amountOut:le,liquidityVenues:I?.liquidityVenues,maxSlippage:e.maxSlippage}).catch(()=>null);if(!ut)throw new Error("No liquidity for this pair.");return ut},resolveInputSwap:async(le,ut)=>{if(!Ke||!dt)throw new Error("Swap route is not ready.");return qo({chainId:b,recipient:dt,tokenIn:Ke,tokenOut:n.address,amountIn:le,selectedSwap:ut,liquidityVenues:I?.liquidityVenues,maxSlippage:e.maxSlippage,resolveInputSwap:e.resolveInputSwap})}}),[o,n,N,G,Q,j,e.recipient,e.feeOnlyAction,e.maxSlippage,e.resolveInputSwap,rt.inputAmount,w,S,k,x,b,he,c,d,B,gt,Ut,Tt,qt,Ke,nt,tt,de,dt,I?.liquidityVenues]),se=p.useMemo(()=>B?.asset?de?de.destination.address:gt&&Ke?Ke:B.asset.chainId===b?B.asset.address:Ke??zt(B.asset,b)??n.address:n.address,[B,n.address,gt,b,Ke,de]),ae=A.keccak256(A.stringToHex(JSON.stringify([B&&pt(B.asset),B?.amount,o,m,n.address,n.chainId,n.decimals,e.recipient,S,Q,L?Q:N,I?.apiUrl,I?.rpcOverrides,e.maxSlippage,c,e.feeOnlyAction,I?.liquidityVenues,I?.allowedTokens,E,D,T]))),Ie=p.useRef({key:ae,enabled:t,sourceBalance:Qe,sourceEligible:Pe?.eligible});Ie.current={key:ae,enabled:t,sourceBalance:Qe,sourceEligible:Pe?.eligible};const Ve=p.useRef(null),st=p.useRef(!1),yt=p.useCallback(()=>st.current?(st.current=!1,He.current=be.current.onSuccess,Ve.current={key:Ie.current.key,quote:be.current.feeQuote},ui(be.current)):Promise.resolve(),[]),Ct=L,Dt=F,It=(w||!!de)&&!!Ne&&Ne.netAmount===0n,vt=p.useMemo(()=>!!e.feeOnlyAction||(!!B?.asset||!!e.actionProceeds)&&xt>0,[B,xt,e.actionProceeds,e.feeOnlyAction]),kt=p.useMemo(()=>!t||!vt||!B?.asset&&!e.actionProceeds&&!e.feeOnlyAction?null:[ae,x?"pay":"supply",m,B?pt(B.asset):"sdk-funded",e.actionInput?.map(le=>`${le.token.toLowerCase()}:${le.amount}`).join(",")??"",e.feeFunding?.join(",")??"",JSON.stringify(I?.rpcOverrides),I?.apiUrl,e.recipient,B?.asset.address.toLowerCase(),B?.asset.chainId,B?.amount,o,n.address.toLowerCase(),n.chainId,b,Be.resolvedTokenIn?.toLowerCase()??"",Be.quoteKey,Be.needsSwap?"swap":"direct",Be.isDirect?"direct-token":"routed-token","7702",ie?"source-dest":"cross-chain",Be.isQuoting?"quoting":"quoted",Be.exactOutputSwap?.amountIn?.toString()??"",Be.exactOutputSwap?.amountInMax?.toString()??"",Be.exactOutputSwap?.venue??"",Be.resolvedSwap?.amountOut?.toString()??"",Be.quoteAmountOut?.toString()??"",Be.sourceSwap?.amountOutMinimum?.toString()??"",Be.sourceExactOutputSwap?.amountInMax?.toString()??"",Be.pivot?.source.address.toLowerCase()??"",N??"",G??"",j??""].join("|"),[t,ae,e.actionProceeds,e.feeOnlyAction,e.actionInput,e.feeFunding,it,Ue,vt,Ct,B,x,m,o,n,b,Be,k,ie,N,G,j]),Bt=p.useCallback(async(le,ut)=>{if(L){if(!Q||!B)throw new Error("Connect the external wallet before continuing.");return qd({selectedAsset:ut?.selectedAsset??B,destinationToken:n,paymentAmount:x?o:void 0,account:Q,beneficiary:e.recipient,buildActionCalls:he,feeExecutionMode:c})}const St={...Lt,requestTimestampMs:Date.now()};return await Pn({signal:le,feeOnlyAction:e.feeOnlyAction,actionInput:e.actionInput,actionProceeds:e.actionProceeds,feeFunding:e.feeFunding,feeFundingBalances:oe,liquidityVenues:I?.liquidityVenues,maxSlippage:e.maxSlippage,resolveExactOutputSwap:f,selectedAsset:B,isPayMode:x,isFeeInclusiveInput:w,parsedAmount:xt,needsSwap:Be.needsSwap,exactOutputSwap:Be.exactOutputSwap,isNon7702:k,isSourceDestToken:ie,currentPaymentAmount:o,destinationToken:n,feeExecutionMode:c,resolvedTokenIn:Be.resolvedTokenIn,embeddedWalletAddress:N,providerEmbeddedAddress:G,resolvedChainId:b,isConnected:U,address:j,ready:P,authenticated:O,isDirect:Be.isDirect,resolvedSwap:Be.resolvedSwap,sourceSwap:Be.sourceSwap,sourceExactOutputSwap:Be.sourceExactOutputSwap,pivot:Be.pivot,isQuoting:Be.isQuoting,executionTokenAddress:se,buildPayChainBatches:lt=>Po(St,lt),buildSupplyChainBatches:lt=>Os(St,lt),estimate:W,...ut})},[B,L,Q,e.recipient,he,e.feeOnlyAction,e.actionInput,e.actionProceeds,e.feeFunding,oe,e.maxSlippage,f,I?.liquidityVenues,x,w,xt,Be,k,ie,o,n,c,N,G,Lt,W,b,U,j,P,O,se]);p.useEffect(()=>{z.current=Bt},[Bt]);const Ln=p.useCallback(async le=>{if(x)return null;if(!B||pt(le)!==pt(B.asset)||!dt||!Ke)throw new Error("Select a source before calculating Max.");let ut=le.balance;if(L){if(!le.isNative&&!v.isNativeToken(le.address))return A.formatUnits(ut,le.decimals);const St=h.getClientForChain(le.chainId),lt=Q;let bt=ut;for(let Nt=0;Nt<8;Nt++){const un=await Bt(void 0,{selectedAsset:{asset:le,amount:A.formatUnits(Nt===0?1n:bt,le.decimals)}});if(!un?.actionDefinition)throw new Error("The direct action could not be sized.");const tn=await va({client:St,account:lt,calls:un.actionDefinition.calls}),En=ut>tn?ut-tn:0n;if(En===0n)return"0";if(Nt>0&&bt<=En)return A.formatUnits(bt,le.decimals);bt=En}throw new Error("Network gas could not be reserved for Max. Enter a smaller amount.")}if(H&&(le.isNative||v.isNativeToken(le.address))){if(!Q)throw new Error("Connect the source wallet before calculating Max.");const St=await Sa({client:h.getClientForChain(le.chainId),account:Q,recipient:dt,token:le.address,isNative:!0,amount:1n});ut-=St}return ai({balance:ut,decimals:le.decimals,planForAmount:async St=>{const lt={...Lt,requestTimestampMs:Date.now(),selectedAsset:{asset:le,amount:A.formatUnits(St,le.decimals)}};let bt=St;return de?(lt.sourceSwap=await qo({chainId:le.chainId,recipient:dt,tokenIn:le.address,tokenOut:de.source.address,amountIn:St,maxSlippage:e.maxSlippage,liquidityVenues:I?.liquidityVenues,resolveInputSwap:e.resolveInputSwap}),bt=Mt(lt.sourceSwap.amountOutMinimum,de.source.decimals,de.destination.decimals,"floor")):bt=Bs(St,le.decimals,await fn(le,Ke,b,n)),lt.resolvedSwap=gt?await lt.resolveInputSwap(bt):null,lt.swapInputAmount=bt,lt.quoteAmountOut=lt.resolvedSwap?.amountOut??bt,Bt(void 0,{selectedAsset:lt.selectedAsset,parsedAmount:Number(lt.selectedAsset.amount),sourceSwap:lt.sourceSwap,resolvedSwap:lt.resolvedSwap,isQuoting:!1,buildSupplyChainBatches:Nt=>Os(lt,Nt)})}})},[B,Lt,x,L,dt,Ke,b,n,H,Q,de,gt,Bt,e.maxSlippage,e.resolveInputSwap,I?.liquidityVenues]);yo({shouldRun:t&&!it&&Ue==="idle"&&vt&&!Be.isQuoting&&!!kt,deps:[t,it,Ue,vt,Ct,Be.isQuoting,kt],onSkip:()=>{if(!t){Te(!1),me(!1),ye(null),ft(null);return}if(it||Ue!=="idle"){Te(!1);return}if(!vt){ft(null),Te(!1),me(!1),ye(null);return}Be.isQuoting&&(Te(!1),me(!1))},onCleanup:()=>Te(!1),delayMs:500,backgroundIntervalMs:5e3,run:async({isBackground:le,isCurrent:ut,signal:St})=>{const lt=kt;le||(ye(null),Te(!0));try{const bt=await z.current?.(St);if(!ut())return;bt&<?(ke.current={key:lt,quote:bt},ft(bt.preview),me(!0)):(ke.current=null,ft(null),me(!1)),ye(null)}catch(bt){if(!ut())return;if(le&&ke.current?.key===lt){console.warn("[SpiceSupply] fee refresh failed:",bt);return}const Nt=h.sanitizeError(bt,"Unable to calculate fees for this action.");ke.current=null,ft(null),me(!1),ye(Nt)}finally{ut()&&Te(!1)}}});const dn=p.useCallback(()=>st.current?(st.current=!1,He.current=be.current.onSuccess,Ve.current={key:Ie.current.key,quote:be.current.feeQuote},pi(be.current)):Promise.resolve(),[]),Ot=x&&$e?.status==="success"?$e.txHash:Ue==="success"?Ze:null;p.useEffect(()=>{!Ot||At.current===Ot||(At.current=Ot,Gt(!0),ht(null),Promise.resolve().then(()=>He.current?.(Ot)).then(()=>{ve(Ot),J(),M()}).catch(le=>{ht(`Transaction confirmed; application update needs retry: ${h.sanitizeError(le,"Unable to finalize the action")}`)}).finally(()=>Gt(!1)))},[Ot,yn]);const Ht=!!Ot&&Et!==Ot,wn=Ht&&!mt,zn=p.useCallback(()=>{At.current=null,ln(le=>le+1)},[]),V=p.useCallback(()=>{qe(!1),Se(null),Ye.current=!1,J(),M()},[J,M]),re=kt&&ke.current?.key===kt?ke.current.quote:null,Oe=()=>{if(Z)throw new Error(Z);if(!Ie.current.enabled||Ie.current.key!==ae)throw new Error("The source, amount, beneficiary or configuration changed. Review the form before continuing.");if((B||e.feeOnlyAction)&&!re)throw new Error("A current action plan is required. Refresh the quote before submitting.");if(L&&B?.asset.owner&&!h.addressesEqual(B.asset.owner,Q))throw new Error("Reconnect the external wallet that owns the selected asset.");if(B&&(re?.sourceSpendCap??0n)>Ie.current.sourceBalance)throw new Error("The source balance changed. Review the available amount before continuing.");if(B&&!Ie.current.sourceEligible)throw new Error(Pe?.reason??"This source is unavailable.")},pe=async()=>Oe(),Xe=le=>({...le,sourceSpendCap:re?.sourceSpendCap,minimumDestinationAmount:re?.destinationAmount}),at=B&&re?.sourceSpendCap!==void 0?re.sourceSpendCap>Qe:cn,Kt={...Lt,resolvedSwap:re?.destinationSwap??Lt.resolvedSwap,swapInputAmount:re?.swapInputAmount??Lt.swapInputAmount};be.current={selectedAsset:B,parsedAmount:xt,currentPaymentAmount:o,isInsufficientBalance:at,isPayMode:x,isFeeInclusiveInput:w,feeOnlyAction:e.feeOnlyAction,actionProceeds:e.actionProceeds,validateFeeQuote:Oe,isNon7702:k,directExternalAction:L,isSourceDestToken:ie,needsSwap:gt,exactOutputSwap:Tt,selectedIsEquivalent:Wt,resolvedTokenIn:Ke,sourceSwap:nt,sourceExactOutputSwap:tt,pivot:de,embeddedWalletAddress:N,providerEmbeddedAddress:G,externalWallet:K,externalWalletAddress:Q,activeSignerWallet:_,activeSignerAddress:X,address:j,isConnected:U,ready:P,authenticated:O,provider:q,resolvedChainId:b,executionTokenAddress:se,destinationToken:n,buildActionCalls:he,feeExecutionMode:c,buildSpicenetBatch:d,onPayExecute:u,onSuccess:g,feeQuote:re,execution:{estimate:(le,ut,St,lt)=>W(le,ut,St,{...lt,userOverride:dt}),execute:async(le,ut,St,lt,bt,Nt)=>{if(await pe(),L){if(!re?.actionDefinition)throw new Error("The direct action plan is unavailable.");return fi({definition:re.actionDefinition,account:Q,chainId:n.chainId,wallet:K,assertCurrent:pe})}if(H&&B&&(Me("Transfer the selected source to your embedded wallet"),await mi({asset:B.asset,embedded:dt,external:Q,externalWallet:K,amount:re?.sourceSpendCap??0n,assertCurrent:pe}),await pe()),!fe)return R(le,ut,St,lt,bt,{...Nt,userOverride:dt,requireDestinationReceipt:!0,validateBeforeSubmit:async pn=>{await pe(),await Nt?.validateBeforeSubmit?.(pn)}});const un=Q;let tn=0n;await R(le,ut,St,pn=>lt?.(pn.step==="success"?{...pn,step:"executing",message:"Funds delivered. Confirm the action in your external wallet.",txHash:void 0}:pn),bt,{...Nt,userOverride:dt,requireDestinationReceipt:!0,validateBeforeSubmit:async pn=>{if(await pe(),await Nt?.validateBeforeSubmit?.(pn),tn=nu(pn,n.address,n.chainId,un),tn<=0n)throw new Error("The route does not deliver the action amount to the external wallet.")}}),await pe();const En={userAddress:un,executorAddress:un,beneficiary:e.recipient??un,chainId:n.chainId,destinationToken:n.address,feeToken:n.address,grossAmount:tn,netAmount:tn,combinedFeeAmount:0n,feeExecutionMode:c,feeBreakdown:{spicenetFee:0n,gasFee:0n,bridgeFee:0n}},Go=await l?.(tn,En)??[];if(!Go.length)throw new Error("No action calls configured.");return fi({definition:{amount:tn,context:En,calls:Go},account:un,chainId:n.chainId,wallet:K,assertCurrent:pe})},buildPayChainBatches:le=>Po(Kt,Xe(le)),buildSupplyChainBatches:le=>Os(Kt,Xe(le)),onProgress:Wn},ui:{setError:_e,setStep:Le,setStatusMsg:Me,setTxHash:De,setIsExecuting:ze,setShowStatusPanel:qe,setPaymentResult:Se},refs:{spiceDepositSubmittedRef:Ye,abortControllerRef:je}};const en=!!e.isZeroAmountPay&&!e.feeOnlyAction&&x&&xt===0,ls=x?(en||!!B?.asset||!!e.actionProceeds||!!e.feeOnlyAction)&&xt>=0&&!at&&!it&&(en||Ct||xe)&&!ee&&(en||e.feeOnlyAction||!gt||!!Tt)&&(en||e.feeOnlyAction||!de||!!tt)&&!Dt:!!B?.asset&&xt>0&&!at&&!it&&(L||xe)&&!ee&&!It&&(de?!!nt&&!jt&&(et||!!Ut):In||et||!!Ut&&!jt)&&!Dt,cs=!Z&&!!dt&&(!L||!!K&&(!B?.asset.owner||h.addressesEqual(B.asset.owner,Q)))&&(!fe||!!K&&!!Q)&&(S==="7702"||!!Q)&&!wt&&!mt&&t&&ls&&(en||!B&&(!!e.actionProceeds||!!e.feeOnlyAction)||!!Pe?.eligible)&&Ue!=="success"&&$e?.status!=="success"&&!rt.quoteError&&(en||!!kt&&ke.current?.key===kt);st.current=cs;const Us=p.useCallback(()=>{st.current=!1,ke.current=null,me(!1),Rt.refreshQuote(),Le("idle"),_e(null)},[Rt.refreshQuote,_e]),Ni=p.useCallback(()=>{qe(!1)},[]),Mi=p.useCallback(()=>{Le("idle"),De(null),J()},[J]),Ft=re??(ke.current?.key.startsWith(`${ae}|`)?ke.current.quote:null)??(Ve.current?.key===ae?Ve.current.quote:null),Pi=async le=>{if(L)throw new Error("This source executes directly from the external wallet; submit the action without embedded funding.");if(!(!H||!B)){if(!re||le!==re.sourceSpendCap)throw new Error("Use the displayed source funding maximum before preparing this action.");await pe(),await mi({asset:B.asset,embedded:dt,external:Q,externalWallet:K,amount:le,assertCurrent:pe})}};return{selectedAsset:we,capability:Pe,assets:{selectable:Ce,displayAssets:Ce,filteredSpiceAssets:ce,embeddedWalletAddress:N,externalAddress:Q,isNon7702:S!=="7702",refreshSpiceAssets:J,refreshWalletAssets:M,loading:Y,refreshing:ue,error:We},quote:{...rt,hasSourceConversion:!!de,executionInput:de&&Ft?{address:de.destination.address,chainId:de.destination.chainId,decimals:de.destination.decimals,amount:Ft.preview.netAmount}:null,...Ft?.destinationSwap?{resolvedSwap:Ft.destinationSwap,inputAmount:Ft.swapInputAmount,estimatedOutput:A.formatUnits(Ft.destinationSwap.amountOut,n.decimals)}:{}},fees:{fundingConversion:Ft?.fundingConversion,fundingSource:Ft?.fundingSource,proceedsUsed:Ft?.proceedsUsed,fundingShortfall:Ft?.grossFundingAmount,source:de&&Ft?{address:de.source.address,chainId:de.source.chainId,symbol:de.source.symbol,decimals:de.source.decimals,gasFee:Ft.sourceGasSkim??0n,spicenetFee:0n}:null,destinationAmount:Ft?.destinationAmount,sourceSpendCap:Ft?.sourceSpendCap,preview:Ft?.preview??Ne,isLoading:ne,ready:!!re,error:ee},amount:{sourceRequiredAmount:Ft?.sourceSpendCap??null,parsed:xt,isInsufficientBalance:at,sourceBalance:An,feesExceedAmount:It},status:{finalizing:wt||wn,finalizationError:mt,step:Ht&&Ue==="success"?"executing":Ue,statusMsg:Ht?mt??"Transaction confirmed. Updating application...":ct,txHash:Ze,isExecuting:it||wn,error:Z||mt||Je||Pe?.reason||null,showStatusPanel:Ge,paymentResult:Ht&&$e?.status==="success"?{...$e,status:"processing"}:$e},flags:{directExecutionFeeNote:Ct},retryFinalization:zn,fundEmbeddedSource:Pi,canExecute:cs,submitSupply:yt,submitPay:dn,retrySupply:Us,dismissPaymentStatus:Ni,resolveMaxAmount:Ln,resetAfterSuccess:Mi,resetPaymentState:V}}function lu(e){return`0x77${e.slice(4)}`}function bi({userAddress:e,destinationChainId:t,deliveryToken:n,deliveryAmount:s,withdrawalAmount:o,deliveryRecipient:r,deliveryTransfers:i,requestTimestampMs:l}){const c=i?.length?i:[{token:n,recipient:r,amount:o??s}],d=c.reduce((g,y)=>g+y.amount,0n);if(d<=0n)return null;const u=l??Date.now(),f=BigInt(Math.floor(u/1e3)),m=lu(A.keccak256(A.encodeAbiParameters([{type:"address"},{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[e??r,n,r,d,BigInt(t),BigInt(u)])));return{chainId:v.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:[{to:v.ZERO_ADDRESS,value:0n,data:A.encodeFunctionData({abi:v.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${t}`,idempotenceKey:m,nbf:0n,exp:f+3600n,metadata:"{}",transfers:c.map(g=>({token:A.getAddress(g.token).toLowerCase(),to:A.getAddress(g.recipient).toLowerCase(),amount:g.amount}))}]})}]}}const as=pt;function cu(e){const{asset:t,amount:n,recipient:s,owner:o,onSuccess:r}=e,i=t?.chainId??e.sourceChains?.[0]??0,l=p.useMemo(()=>v.getTokensForChain(i).find(w=>w.equivalenceGroup==="USDC"),[i]),[c,d]=p.useState(null),u=p.useCallback((w,C)=>{if(!t||n<=0n||n>t.balance||!s||!o||h.addressesEqual(o,s))throw new Error("Enter a valid withdrawal amount and recipient.");if(C.chainId!==t.chainId||!h.addressesEqual(C.executorAddress??C.userAddress,o))throw new Error("The withdrawal wallet or network changed. Review the withdrawal again.");return Ha(t.chainId,t.address,[{recipient:s,amount:n}]).calls},[t?.address,t?.chainId,t?.balance,n,s,o]),f=p.useMemo(()=>c?{asset:c,amount:"0"}:null,[c]),m=rs({enabled:e.enabled&&!!l&&!!t&&n>0n&&!!s&&!!o&&!h.addressesEqual(o,s),feeOnlyAction:!0,isZeroAmountPay:!0,amountDirection:"output",paymentAmount:"0",destinationToken:{address:l?.address??v.ZERO_ADDRESS,symbol:l?.symbol??"USDC",decimals:l?.decimals??6,chainId:i},recipient:o,selectedAsset:f,feeFunding:[],sourceChains:e.sourceChains,includeCrossChainEmbeddedAssets:!0,includeExternalWalletAssets:!1,feeExecutionMode:"backend-transfer",buildActionCalls:u,buildSpicenetBatch:bi,onError:(w,C)=>e.onError?.(w.message,C),onSuccess:async()=>{t&&(window.dispatchEvent(new CustomEvent("withdraw-completed")),await r?.({token:t.symbol,amount:A.formatUnits(n,t.decimals),chainId:i}))}}),g=`${e.enabled}:${t?.chainId}:${t?.address}:${n}:${s}`,y=p.useRef(g);p.useEffect(()=>{y.current===g||m.status.isExecuting||(y.current=g,(m.status.step==="success"||m.status.paymentResult?.status==="success")&&m.resetAfterSuccess())},[g,m.status.isExecuting,m.status.step,m.status.paymentResult?.status,m.resetAfterSuccess]);const x=p.useMemo(()=>l?m.assets.displayAssets.flatMap(w=>{if(w.location==="external")return[];const C=t&&w._source==="wallet"&&w.chainId===t.chainId&&h.addressesEqual(w.address,t.address)?n:0n,b=w.balance-C;return b>0n?[{...w,balance:b,balanceFormatted:Number(A.formatUnits(b,w.decimals))}]:[]}).sort((w,C)=>{const b=I=>I._source==="wallet"&&I.chainId===i?0:I._source==="spice"?1:2;return b(w)-b(C)||C.balanceFormatted-w.balanceFormatted}):[],[m.assets.displayAssets,l,i,t?.address,t?.chainId,n]);return p.useEffect(()=>{if(!e.enabled||m.status.isExecuting)return;const w=(c&&x.find(C=>as(C)===as(c)))??x[0]??null;(!c||!w||as(c)!==as(w)||c.balance!==w.balance)&&d(w)},[e.enabled,m.status.isExecuting,x,c]),{supply:m,candidates:x,source:c,setSource:d,feeToken:l,sourceKey:as}}const Ci=h.font.ui,du=({label:e,loading:t,balance:n,dark:s,dk:o})=>{const r=s?o.textSecondary:"#7D7C7B",i=s?o.textSecondary:"#71757A";return a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[a.jsx("span",{style:{fontFamily:Ci,fontSize:"17px",fontWeight:500,color:r,lineHeight:"24px"},children:e}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",fontFamily:Ci,fontSize:"13px",fontWeight:500,color:i,lineHeight:"16px"},children:["Balance:"," ",t?"...":n===null?"\u2014":h.formatBalance(n)]})]})},vi=({isOpen:e,position:t,title:n,items:s,selectedId:o,onSelect:r,portalAttribute:i})=>{const{dark:l,dk:c,primaryColor:d}=h.useSpiceBrand(),[u,f]=p.useState(null),[m,g]=p.useState(!1);return p.useEffect(()=>{if(!e){g(!1);return}const y=requestAnimationFrame(()=>{requestAnimationFrame(()=>g(!0))});return()=>cancelAnimationFrame(y)},[e]),!e||!t||s.length===0?null:Fn.createPortal(a.jsxs("div",{[`data-${i}-popover`]:"true",style:{position:"fixed",top:`${t.top}px`,left:`${t.left}px`,opacity:m?1:0,transform:m?"scale(1) translateY(0)":"scale(0.96) translateY(-6px)",transition:`opacity 200ms ${h.easing.out}, transform 200ms ${h.easing.out}`,backgroundColor:l?c.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 ${c.cardBorder}`,minWidth:"220px",zIndex:h.z.dropdown,fontFamily:h.font.mono},children:[a.jsx("div",{style:{marginBottom:"6px"},children:a.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:l?c.textPrimary:"#0e0d0b",textTransform:"uppercase",letterSpacing:"1px"},children:n})}),a.jsx("div",{style:{borderBottom:`1px solid ${c.cardBorder}`,marginBottom:"6px"}}),a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"2px"},children:s.map(y=>{const x=o===y.id,w=u===y.id;return a.jsxs("button",{onClick:C=>{C.stopPropagation(),r(y.id)},onMouseEnter:()=>f(y.id),onMouseLeave:()=>f(null),style:{display:"flex",alignItems:"center",gap:"8px",padding:"6px 4px",borderRadius:"8px",border:"none",cursor:"pointer",backgroundColor:x?l?c.hoverBg:"#f3f4f6":w?l?c.cardBg:"#f9fafb":"transparent",transition:"background-color 0.15s",width:"100%",fontFamily:h.font.mono},children:[y.icon&&a.jsx("img",{src:y.icon,alt:y.label,style:{width:"22px",height:"22px",borderRadius:"50%"}}),a.jsx("span",{style:{fontSize:"13px",fontWeight:x?700:500,textTransform:"uppercase",color:l?c.textPrimary:"#0e0d0b",letterSpacing:"0.5px",flex:1,textAlign:"left"},children:y.label}),y.detail&&a.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:c.textSecondary},children:y.detail}),x&&a.jsx(ga,{color:d,style:{flexShrink:0}})]},y.id)})})]}),document.body)},Ms=h.font.ui,uu=h.font.mono,pu=170,fu=({header:e,amount:t,receiveAmountDisplay:n,receiveUsdEstimate:s,selectedDestToken:o,destTokenSymbol:r,destChainName:i,destChainLogo:l,compatibleDestinationChains:c,networkSwitchRef:d,onOpenNetworkPopover:u,showNetworkPopover:f,setShowNetworkPopover:m,networkPopoverPos:g,selectedChainId:y,setSelectedChainId:x,dark:w,dk:C})=>{const b=w?C.cardBg:"#E9E9E9",I=w?C.cardBorder:"#C6C6C6",S=w?C.textSecondary:"#71757A",k=w?C.textPrimary:"#0E0D0B",E=w?C.cardBorder:"#C5C5C4",F=w?"rgba(255,255,255,0.08)":"#D4D3D3",T=r.length>8?"14px":r.length>6?"16px":"18px";return a.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,a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[a.jsxs("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[a.jsx(vn,{element:"div",value:n,title:n,fontFamily:Ms,color:t?k:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,overflow:"wrap"}),a.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:S,fontFamily:Ms,marginTop:"10px"},children:s})]}),a.jsxs("div",{style:{width:`${pu}px`,flexShrink:0,display:"flex",flexDirection:"column",alignItems:"stretch",gap:"8px"},children:[a.jsxs("div",{style:{backgroundColor:"transparent",border:`1px solid ${E}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px"},children:[a.jsx("img",{src:o?.logoURI||Wl,alt:r,style:{width:"24px",height:"24px",borderRadius:"50%"}}),a.jsx("span",{style:{fontSize:T,fontWeight:500,color:k,lineHeight:"1.3",fontFamily:Ms,flex:1,minWidth:0,letterSpacing:0},children:r})]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:F,borderTop:`1px solid ${E}`},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[l&&a.jsx("img",{src:l,alt:i,style:{width:"13px",height:"13px",borderRadius:"50%",flexShrink:0}}),a.jsx("span",{style:{fontSize:"11px",fontWeight:400,color:k,fontFamily:Ms,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:i})]}),a.jsx("button",{ref:d,onClick:D=>{D.stopPropagation(),u(d.current)},style:{background:"none",border:"none",cursor:c.length>1?"pointer":"not-allowed",padding:"0 0 0 8px",fontSize:"9.5px",fontFamily:uu,color:S,textDecoration:"underline",fontWeight:600,opacity:c.length>1?1:.45},children:"Switch"}),a.jsx(vi,{isOpen:f,position:g,title:"SELECT NETWORK",portalAttribute:"network",items:c.map(D=>{const j=h.getChainConfig(D);return{id:String(D),label:j?.displayName||String(D),icon:mn[D]||Vn}}),selectedId:y!==null?String(y):null,onSelect:D=>{x(Number(D)),m(!1)}})]})]}),a.jsx("div",{style:{minHeight:"14px"}})]})]})]})},mu=h.font.ui,xn=h.font.mono,hu=({show:e,onToggle:t,showCustomAddress:n,setShowCustomAddress:s,customRecipient:o,setCustomRecipient:r,externalAddress:i,recipientAddress:l,destChainName:c,destChainLogo:d,compatibleDestinationChains:u,txDetailsChainSwitchRef:f,onOpenNetworkPopover:m,sourceChainLabel:g,sourceDetailsLogo:y,sourceTokenLabel:x,amount:w,totalSourceDebitDisplay:C,receiveAmountDisplay:b,destTokenSymbol:I,shouldQuoteWithdrawGas:S,estimatingFee:k,feeError:E,displayedGasFee:F,selectedDestToken:T,theme:D,styles:j,dark:U,dk:P})=>{const O=U?P.textSecondary:"#71757A",q=U?P.textPrimary:"#0E0D0B",R=u.length>1,W=n&&o?A.isAddress(o)?h.truncateAddress(o):o:l?h.truncateAddress(l):"\u2014";return a.jsxs(a.Fragment,{children:[a.jsxs("div",{onClick:t,style:{display:"flex",alignItems:"center",gap:"6px",marginBottom:e?"10px":"0",cursor:"pointer",userSelect:"none"},children:[a.jsx("span",{style:{fontSize:"13px",color:O,fontFamily:mu,fontWeight:600},children:"Transaction Details"}),a.jsx(Zc,{size:12,color:O,style:{transform:e?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s"}})]}),e&&a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"7px"},children:[a.jsxs("div",{children:[a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[a.jsx("span",{style:{fontSize:"12px",color:O,fontFamily:xn,fontWeight:500,letterSpacing:"0.03em"},children:"TO"}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[a.jsx("span",{style:{fontSize:"13px",color:q,fontFamily:xn,fontWeight:500},children:W}),a.jsx("button",{onClick:()=>{s(K=>!K),!n&&i&&r(i)},style:{background:"none",border:"none",cursor:"pointer",padding:"0",fontSize:"9.5px",fontFamily:xn,color:O,textDecoration:"underline",fontWeight:600},children:n?"Reset":"Switch"})]})]}),n&&a.jsxs("div",{style:{marginTop:"6px"},children:[a.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:xn,fontWeight:700,letterSpacing:0,textTransform:"uppercase"},children:"CAUTION: ENTERING AN INCORRECT ADDRESS WILL RESULT IN LOSS OF FUNDS"}),a.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:K=>r(K.target.value),placeholder:"0x...",style:{width:"100%",padding:"8px 10px",borderRadius:"6px",border:`1px solid ${o&&!A.isAddress(o)?U?P.errorBorder:"#fca5a5":U?P.inputBorder:"#d1d5db"}`,backgroundColor:U?P.inputBg:"#f9fafb",color:U?P.inputText:"#111827",fontSize:"12px",fontFamily:xn,outline:"none",boxSizing:"border-box"}}),o&&!A.isAddress(o)&&a.jsx("span",{style:{fontSize:"11px",color:P.errorText,marginTop:"3px",display:"block"},children:"Invalid address"})]})]}),a.jsx(gn,{palette:P,labelColor:O,valueColor:q,label:"RECEIVING CHAIN",value:a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"7px"},children:[d&&a.jsx("img",{src:d,alt:c,style:{width:"14px",height:"14px",borderRadius:"50%"}}),a.jsx("span",{style:{fontSize:"13px",color:q,fontWeight:500,fontFamily:xn,textTransform:"uppercase"},children:c}),a.jsx("button",{ref:f,onClick:K=>{K.stopPropagation(),m(f.current)},style:{background:"none",border:"none",cursor:R?"pointer":"not-allowed",padding:"0",fontSize:"9.5px",fontFamily:xn,color:O,textDecoration:"underline",fontWeight:600,opacity:R?1:.45},children:"Switch"})]})}),a.jsx(gn,{palette:P,labelColor:O,valueColor:q,label:"REQUESTED WITHDRAWAL",value:a.jsxs(Ho,{logo:y||null,alt:g,primaryText:q,children:[w||"0"," ",x]})}),S&&a.jsx(gn,{palette:P,labelColor:O,valueColor:q,label:"TOTAL SOURCE DEBIT",value:a.jsxs(Ho,{logo:y||null,alt:g,primaryText:q,children:[C," ",x]})}),a.jsx(gn,{palette:P,labelColor:O,valueColor:q,label:"YOU RECEIVE",value:a.jsxs(Ho,{logo:d,alt:c,primaryText:q,gap:"4px",children:[b," ",I]})}),S&&a.jsxs(a.Fragment,{children:[a.jsx(gn,{palette:P,labelColor:O,label:"EST. NETWORK FEE",valueColor:E?"#f87171":q,value:k?"Estimating...":E?"Unavailable":F!==null&&T?`${Oo(F,T.decimals)} ${T.symbol}`:"Estimating..."}),E&&a.jsx($t,{variant:"error",size:"compact",palette:P,fontFamily:j?.fontFamily||D.typography.fontFamily,children:E})]})]})]})},gu=p.memo(hu),Ho=({logo:e,alt:t,primaryText:n,gap:s="6px",children:o})=>a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:s},children:[e&&a.jsx("img",{src:e,alt:t,style:{width:"13px",height:"13px",borderRadius:"50%"}}),a.jsx("span",{style:{fontSize:"13px",color:n,fontWeight:500,fontFamily:xn},children:o})]}),is=h.font.ui,xu=170,yu=({header:e,amount:t,setAmount:n,isInsufficient:s,sourceAmountDecimals:o,selectedSourceAsset:r,resolvedSelectedSourceAsset:i,spiceAssets:l,setSelectedSourceAsset:c,sourceUsdEstimate:d,sourceTokenLabel:u,sourceChainLabel:f,totalSelectedBalance:m,showSourceTokenPopover:g,setShowSourceTokenPopover:y,tokenPopoverPos:x,setTokenPopoverPos:w,tokenTriggerRef:C,primaryColor:b,dark:I,dk:S})=>{const k=I?S.cardBg:"#E9E9E9",E=I?S.cardBorder:"#C6C6C6",F=I?S.textSecondary:"#71757A",T=I?S.textPrimary:"#0E0D0B",D=I?S.cardBorder:"#C5C5C4",j=I?"rgba(255,255,255,0.08)":"#D4D3D3",U=u.length>8?"14px":u.length>6?"16px":"18px";return a.jsxs("div",{style:{backgroundColor:k,border:`1px solid ${E}`,borderRadius:"7px",padding:"14px 16px 12px 16px",minHeight:"138px",display:"flex",flexDirection:"column",gap:"6px",position:"relative"},children:[e,a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[a.jsxs("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[a.jsx(vn,{element:"input",ariaLabel:"Withdraw amount",ariaInvalid:s,dataSpiceflowFocus:!0,value:t,onChange:P=>{const O=P.target.value;if(O===""){n("");return}/^\d*\.?\d*$/.test(O)&&n(h.parseNumericInput(O.startsWith(".")?`0${O}`:O,o??r?.decimals))},placeholder:"0.0",fontFamily:is,color:s?"#ef4444":t?T:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,style:{width:"100%"}}),a.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:F,fontFamily:is,marginTop:"10px"},children:d})]}),a.jsx("div",{style:{width:`${xu}px`,flexShrink:0},children:a.jsxs("div",{style:{backgroundColor:"transparent",border:`1px solid ${D}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[a.jsxs("div",{ref:C,onClick:P=>{if(P.stopPropagation(),!g&&C.current){const O=C.current.getBoundingClientRect(),q=220,R=16;w({top:O.bottom+8,left:Math.min(Math.max(R,O.right-q),window.innerWidth-q-R)})}y(O=>!O)},style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px",cursor:"pointer"},children:[a.jsx("img",{src:io,alt:u,style:{width:"24px",height:"24px",borderRadius:"50%"}}),a.jsx("span",{style:{fontSize:U,fontWeight:500,color:T,lineHeight:"1.3",fontFamily:is,flex:1,minWidth:0,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",letterSpacing:0},children:u}),a.jsx(On,{size:15,color:T,strokeWidth:2.25})]}),a.jsx(vi,{isOpen:g,position:x,title:"SELECT TOKEN",portalAttribute:"token",items:(l||[]).map(P=>({id:P.receiptTokenId||P.address,label:P.displaySymbol||P.receiptTokenName||P.symbol,icon:io,detail:h.formatBalance(P.balanceFormatted)})),selectedId:i?.receiptTokenId||i?.address||null,onSelect:P=>{const O=(l||[]).find(q=>(q.receiptTokenId||q.address)===P);O&&(c(O),n("")),y(!1)}}),a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:j,borderTop:`1px solid ${D}`},children:a.jsx("span",{style:{fontSize:"11px",fontWeight:400,color:T,fontFamily:is,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:f})})]})})]}),a.jsxs("div",{style:{minHeight:"18px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[s?a.jsx("span",{style:{fontSize:"12px",color:S.errorText,fontFamily:is,fontWeight:500},children:"Insufficient Balance"}):a.jsx("span",{}),a.jsx("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0px",minHeight:"32px",marginRight:"-9px"},children:[0,25,50,75,100].map((P,O)=>{const q=O===4,R=parseFloat(t)||0,W=m>0&&Math.abs(R/m*100-P)<1;return a.jsx("button",{type:"button","aria-label":`Set amount to ${P}%`,"aria-pressed":W,onClick:()=>{const K=i?.balance??0n;n(P===0?"":A.formatUnits(K*BigInt(P)/100n,o??6))},title:`${P}%`,disabled:m===0,"data-spiceflow-focus":!0,style:{width:"32px",height:"32px",padding:"9px",border:"none",backgroundColor:"transparent",cursor:m===0?"not-allowed":"pointer",opacity:W?1:.5,transition:"opacity 0.15s ease",display:"flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box"},children:a.jsx(Fo,{pct:P,isMax:q,primaryColor:b,dark:I,fillColor:I?S.textSecondary:"#3C3E42"})},P)})})]})]})},wu=({dark:e,dk:t})=>a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[a.jsx("img",{src:xo,alt:"","aria-hidden":"true",style:{width:"13px",height:"13px",flexShrink:0,...e?{filter:"invert(0.6)"}:{}}}),a.jsx("p",{style:{fontSize:"13px",color:e?t.textSecondary:"#979AA0",margin:"0",lineHeight:"1.4",fontFamily:h.font.ui},children:"Withdraw collateral from your account to 10+ EVM blockchains."})]}),bu=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,styles:s,onWithdrawExecute:o,onWithdrawSuccess:r,onWithdrawError:i,availableTokens:l,initialSourceAssetId:c,walletAssets:d,buildSpicenetBatch:u})=>{const f=p.useContext(h.SpiceFlowProviderContext);if(!f)return a.jsx("div",{children:"Error: SpiceWithdraw must be used within SpiceFlowProvider"});const m=f.mode||"7702",g=m==="presign"||m==="ondemand",y=f.supportedChainIds,x=f.allowedTokens,w=!!d,C=d?.initialAsset,b=p.useMemo(()=>[...d?.extraAssets??[],...C?[C]:[]].map(se=>({address:se.address,chainId:se.chainId,symbol:se.symbol,decimals:se.decimals})),[d?.extraAssets,C]),I=f.isWhitelistGateActive,{theme:S,dark:k,dk:E}=h.useSpiceBrand(s),F=f.network,T=()=>g?"select":"provider-login",[D,j]=p.useState(T()),[U,P]=p.useState(!1),[O,q]=p.useState(null),[R,W]=p.useState(null),[K,G]=p.useState(""),[_,X]=p.useState(!1),[Q,te]=p.useState(!1),[B,$]=p.useState(!1),[ie,L]=p.useState(""),[H,fe]=p.useState(!0),Z=p.useRef(null),he=p.useRef(null),ge=p.useRef(null),[ce,Ae]=p.useState(null),[N,J]=p.useState(null),M=h.useWallet(),{isReady:Y,isAuthenticated:ue,address:We}=M,Ce=f?.embeddedWalletAddress,{address:oe,chainId:Ee}=Zt.useAccount(),we=f.externalWalletAddress||oe,[Pe,Qe]=p.useState(!1),[it,ze]=p.useState(null),Je=p.useRef(i);Je.current=i;const Re=p.useCallback(se=>{ze(se),typeof se=="string"&&se&&Je.current?.(se,h.getRelayerErrorDetail(se))},[]),[ot,_e]=p.useState(null),Ue=p.useRef(null),Le=p.useRef(!0),ct=p.useRef(null);p.useEffect(()=>(Le.current=!0,()=>{Le.current=!1}),[]);const{execute:Me,estimate:Ze}=Es(),[De,Ge]=p.useState(null),[qe,$e]=p.useState(null),[Se,Ne]=p.useState(!1),[ft,ne]=p.useState(null),{assets:Te,loading:xe,error:me,refresh:ee}=Dn({owner:Ce,role:"holding",includeWalletAssets:w,additionalSourceTokens:b,enabled:e&&!!Ce}),ye=p.useMemo(()=>{if(I)return[];const se=(ae,Ie)=>(Ie.balanceUsd||0)-(ae.balanceUsd||0);return(Te??[]).filter(ae=>ae.balance>0n&&bn(ae,"holding",{allowedTokens:x,isWhitelistGateActive:I}).eligible).sort(se)},[Te,x,I]),Fe=p.useMemo(()=>[...new Set([...y??[],...Object.keys(l??{}).map(Number),...(ye||[]).map(se=>se.chainId),...(ye||[]).flatMap(se=>Object.keys(se.chainTokens??{}).map(ae=>{const[,Ie]=ae.split(":"),Ve=Number(Ie);return Number.isFinite(Ve)?Ve:null}).filter(ae=>ae!==null))])].filter(se=>h.getChainConfig(se)?.network===F),[y,l,ye,F]),Ye=p.useMemo(()=>{if(l)return l;const se={};for(const ae of ye||[]){const Ie=Object.entries(ae.chainTokens??{});if(Ie.length>0){for(const[Ve,st]of Ie){const[yt,Ct,Dt]=Ve.split(":");if(yt!=="evm"||!Ct||!Dt)continue;const It=Number(Ct);if(!Number.isFinite(It))continue;const vt=Dt.startsWith("0x")?Dt.toLowerCase():`0x${Dt.toLowerCase()}`,kt=h.getChainConfig(It)?.supportedTokens?.find(Bt=>h.addressesEqual(Bt.address,vt));kt&&so(ae,vt,It)&&(se[It]||(se[It]=[]),se[It].find(Bt=>h.addressesEqual(Bt.address,vt))||se[It].push({address:vt,symbol:kt?.symbol||st?.name||ae.symbol,name:kt?.name||st?.name||ae.displayName||ae.name||ae.symbol,decimals:kt?.decimals??st?.decimals??ae.decimals,logoURI:kt?.logo||ae.logoURI}))}continue}se[ae.chainId]||(se[ae.chainId]=[]),se[ae.chainId].find(Ve=>h.addressesEqual(Ve.address,ae.address))||se[ae.chainId].push({address:ae.address,symbol:ae.symbol,name:ae.displayName||ae.name||ae.symbol,decimals:ae.decimals,logoURI:ae.logoURI})}return se},[l,ye]),je=p.useCallback((se,ae)=>{const Ie=yd(se,ae,ae?Ye[ae]??[]:[]);return!se||!Ie||!ae||se._source==="wallet"&&ae!==se.chainId?null:bn(se,"withdraw-destination",f,{...Ie,chainId:ae}).eligible?Ie:null},[Ye,f.allowedTokens,f.rpcOverrides,f.isWhitelistGateActive]),z=p.useMemo(()=>O?ye.find(se=>pt(se)===pt(O))??null:null,[O,ye]),ke=z?z.balanceError:me,be=z?._source==="wallet",He=p.useMemo(()=>{if(!z)return[];const se=Object.keys(z.chainTokens??{}).map(ae=>sn(ae)?.chainId??null).filter(ae=>ae!==null);return Array.from(new Set([...se,z.chainId,...Fe].filter(Number.isFinite))).filter(ae=>h.getChainConfig(ae)?.network===F&&je(z,ae)!==null)},[z,Fe,je,F]),At=p.useMemo(()=>{if(!z||typeof window>"u")return null;const se=`spiceflow:withdraw-chain:${z.receiptTokenId||z.address.toLowerCase()}`,ae=window.localStorage.getItem(se),Ie=ae?Number(ae):null;return Ie!==null&&Number.isFinite(Ie)&&He.includes(Ie)?Ie:null},[z,He]),Et=p.useMemo(()=>z?At!==null?At:Ee&&He.includes(Ee)?Ee:z.chainId&&He.includes(z.chainId)?z.chainId:He[0]??null:Fe[0]??null,[z,At,Ee,He,Fe]),ve=p.useMemo(()=>je(z,R),[je,z,R]);p.useEffect(()=>{e&&(q(null),G(""))},[e,c,C?.address,C?.chainId]),p.useEffect(()=>{if(!e||!ye.length||O)return;const se=C?ye.find(ae=>ae.chainId===C.chainId&&h.addressesEqual(ae.address,C.address)&&ae._source==="wallet"):c?ye.find(ae=>ae.receiptTokenId===c):ye[0];q(se??null),G("")},[e,ye,O,c,C]),p.useEffect(()=>{z&&(R===null||!He.includes(R))&&W(Et)},[z,R,Et,He]),p.useEffect(()=>{if(!_&&!Q)return;const se=ae=>{const Ie=ae.target;_&&!Z.current?.contains(Ie)&&!he.current?.contains(Ie)&&!Ie?.closest?.("[data-network-popover]")&&X(!1),Q&&!ge.current?.contains(Ie)&&!Ie?.closest?.("[data-token-popover]")&&te(!1)};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[_,Q]);const mt=p.useCallback(se=>{if(!se||He.length<=1)return;const ae=se.getBoundingClientRect(),Ie=220,Ve=16;Ae({top:ae.bottom+8,left:Math.min(Math.max(Ve,ae.right-Ie),window.innerWidth-Ie-Ve)}),X(st=>!st)},[He.length]),ht=p.useCallback(()=>fe(se=>!se),[]);p.useEffect(()=>{if(!z||R===null||typeof window>"u")return;const se=`spiceflow:withdraw-chain:${z.receiptTokenId||z.address.toLowerCase()}`;window.localStorage.setItem(se,String(R))},[z,R]);const wt=B?A.isAddress(ie)?ie:void 0:we||(be?void 0:Ce),Gt=Dn({owner:wt,role:"holding",includeRollupAssets:!1,sourceChains:R?[R]:[],additionalSourceTokens:ve&&R?[{...ve,chainId:R}]:[],enabled:e&&!!wt&&!!ve&&!!R}),yn=Gt.walletAssets.find(se=>h.addressesEqual(se.owner,wt)&&se.chainId===R&&h.addressesEqual(se.address,ve?.address)),ln=z?.balanceFormatted??0,dt=z?.displaySymbol||z?.receiptTokenName||z?.symbol||"Select token",Rt=z?.displayChainName||(be?h.getChainConfig(z.chainId)?.displayName:"Spicenet")||"Network",rt=z?.receiptTokenDecimals??z?.decimals,Be=p.useMemo(()=>{if(!ve||rt===void 0)return 0n;try{return Pt(K||"0",rt)}catch{return 0n}},[K,ve,rt]),jt=p.useMemo(()=>!ve||rt===void 0?0n:za(Be,rt,ve.decimals),[ve,rt,Be]),Ut=p.useMemo(()=>{if(be)return 0n;const se=qe??De;return!se||se<=0n||!ve||rt===void 0?0n:za(se,ve.decimals,rt)},[be,qe,De,ve,rt]),Tt=p.useMemo(()=>Be+Ut,[Be,Ut]),qt=qe??De,Ke=cu({enabled:e&&be,asset:be?z:null,amount:Be,recipient:wt,owner:Ce,sourceChains:y,onSuccess:r,onError:i}),et=Ke.supply,gt=Pe||be&&(et.status.isExecuting||et.status.finalizing),Wt=et.status.step==="success"||et.status.paymentResult?.status==="success",nt=p.useCallback(se=>{if(be||!R||!ve)return[];if(Be===0n||jt===0n||!wt)return[];const ae=Array.isArray(se)?se.filter(yt=>yt.amount>0n):[{token:ve.address,recipient:wt,amount:se??jt}],Ie=ae.reduce((yt,Ct)=>yt+Ct.amount,0n);if(Ie<=0n)return[];const Ve={chainId:R,calls:[],tokenTransfers:ae.map(yt=>({from:"escrow",to:yt.recipient,token:yt.token,amount:yt.amount}))};if(!u)return[Ve];const st=u({destinationChainId:R,deliveryToken:ve.address,deliveryAmount:Ie,deliveryRecipient:wt,deliveryTransfers:ae,requestTimestampMs:ct.current??Date.now()});return st?[st,Ve]:[Ve]},[be,R,ve,Be,jt,wt,u]),tt=p.useMemo(()=>nt(),[nt]),de=p.useMemo(()=>Ad(tt,ve?.address),[tt,ve?.address]),xt=p.useRef(null),_t=!be&&e&&!g&&!Pe&&!!ve&&!!R&&Be!==0n;yo({shouldRun:_t&&tt.length>0&&!!de,deps:[_t,tt.length>0,de],delayMs:500,onSkip:()=>{xt.current=null,Ge(null),ne(null),Ne(_t&&tt.length===0)},onCleanup:()=>Ne(!1),run:async({isCurrent:se,signal:ae})=>{const Ie=de;Ne(!0),ne(null);try{const Ve=await Id({batches:tt,tokenAddress:ve.address,chainId:R,estimate:Ze,signal:ae});if(!se())return;xt.current={key:Ie,quote:Ve},Ge(Ve.gasFee)}catch(Ve){if(!se())return;xt.current=null,Ge(null),ne(Ve instanceof Error?Ve.message:"Failed to estimate gas fee")}finally{se()&&Ne(!1)}}}),p.useEffect(()=>{Pe||$e(null)},[Pe,K,R,ve?.address]);const In=p.useCallback(()=>{P(!0),j("select")},[]),An=p.useCallback(()=>{gt||t()},[t,gt]),cn=p.useRef(null);cn.current={batches:tt,walletAddress:We,recipient:wt,token:ve,chainId:R,amount:K,receiveAmountRaw:jt,gasFee:De,feeEstimate:de&&xt.current?.key===de?xt.current.quote.feeEstimate:null,isNon7702:g,buildWithdrawBatches:nt,execution:{estimate:Ze,execute:Me},ui:{setIsExecuting:Qe,setExecutionError:Re,setExecutionProgress:_e,setLockedGasFee:$e},executionContextRef:Ue,isMountedRef:Le,onWithdrawExecute:o,onWithdrawSuccess:r,buildSpicenetBatch:u};const Wn=p.useCallback(()=>(ct.current=Date.now(),Wa(cn.current)),[]),Lt=p.useCallback(()=>(ct.current=Date.now(),Sd(cn.current)),[]);if(p.useEffect(()=>{if(!e){const se=setTimeout(()=>{j(T()),P(!1),q(null),W(null),G(""),X(!1),te(!1),$(!1),L(""),Qe(!1),Re(null),_e(null),Ue.current=null},300);return()=>clearTimeout(se)}},[e,g]),p.useEffect(()=>{if(!g&&e&&D==="provider-login"&&Y&&ue&&Ce&&!U){const se=setTimeout(()=>{P(!0),j("select")},100);return()=>clearTimeout(se)}},[g,e,D,Y,ue,Ce,U]),!e)return null;if(D==="provider-login"&&!g)return a.jsx(Ro,{onAuthSuccess:In,autoTrigger:!0});if(D==="select"){const se=parseFloat(K)||0,ae=rt?Oo(Tt,rt):K||"0",Ie=!!z&&Tt>z.balance,Ve=(R?h.getChainConfig(R):null)?.displayName||"Network",st=R?mn[R]||Vn:null,yt=ve?.symbol||"\u2014",Ct=dt,Dt=ve?Oo(jt,ve.decimals):"0",It=z&&z.balanceFormatted>0?z.balanceUsd/z.balanceFormatted:void 0,vt=z?.priceStatus==="stale",kt=qa(se,It,vt),Bt=qa(parseFloat(Dt)||0,It,vt),Ln=(!B||A.isAddress(ie))&&(!be||!h.addressesEqual(wt,Ce)),dn=!g&&!be&&se>0&&ve!==null,Ot=!dn||De!==null&&!Se&&!ft,Ht=se>0&&!Ie&&!xe&&!ke&&z!==null&&R!==null&&ve!==null&&wt&&Ln&&Ot&&jt>0n&&(!be||et.canExecute&&!Wt),wn=!Ht,zn=xe?"LOADING BALANCES":ke?"BALANCES UNAVAILABLE":z===null?"NO BALANCE":se===0?"ENTER AMOUNT":Ie?"INSUFFICIENT BALANCE":dn&&!Ot?ft?"GAS UNAVAILABLE":"ESTIMATING GAS":dn&&jt===0n?"AMOUNT TOO SMALL":be&&!et.canExecute?"REVIEW FEES":"WITHDRAW",V=!!ot&&(ot.step==="success"||ot.step==="error"),re=s?.primaryColor||S.colors.primary,Oe=402,pe=(Xe,at,Kt)=>a.jsx(du,{label:Xe,loading:Kt,balance:at,dark:k,dk:E});return a.jsx(Qt,{isOpen:!0,onClose:An,title:"Withdraw",subtitle:a.jsx(wu,{dark:k,dk:E}),styles:s,theme:S,dark:k,maxWidth:"486px",footerLinkText:"Spicenet accounts \u2192",overlayDimmed:!1,closeOnBackdropClick:n,overlayContent:V?a.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:a.jsx("div",{style:{pointerEvents:"auto"},children:a.jsx(Do,{type:"withdraw",isOpen:!0,isProcessing:Pe,onRetryTx:()=>{Lt()},onNewTx:()=>{_e(null),G(""),Re(null),Ue.current=null},onClose:()=>{_e(null),Re(null),Qe(!1),Ue.current=null},onComplete:()=>{_e(null),Re(null),Qe(!1),Ue.current=null},results:[{asset:{symbol:ve?.symbol||"Token",address:ve?.address||""},txHash:ot?.txHash||"",success:ot?.step==="success",error:ot?.error,amount:K}],chainId:R??void 0,theme:S})})}):null,children:a.jsxs("fieldset",{disabled:gt,style:{border:0,minWidth:0,width:"calc(100% - 32px)",maxWidth:`${Oe}px`,margin:"0 auto",padding:"0 0 4px 0",position:"relative"},children:[a.jsxs("div",{style:{marginTop:"16px",marginBottom:"16px",display:"flex",flexDirection:"column",gap:"16px"},children:[a.jsx(yu,{header:pe("Source",ln,xe),amount:K,setAmount:G,isInsufficient:Ie,sourceAmountDecimals:rt,selectedSourceAsset:z,resolvedSelectedSourceAsset:z,spiceAssets:ye,setSelectedSourceAsset:q,sourceUsdEstimate:kt,sourceTokenLabel:Ct,sourceChainLabel:Rt,totalSelectedBalance:ln,showSourceTokenPopover:Q,setShowSourceTokenPopover:te,tokenPopoverPos:N,setTokenPopoverPos:J,tokenTriggerRef:ge,primaryColor:re,dark:k,dk:E}),a.jsx(fu,{header:pe("Destination",yn?.balanceFormatted??null,Gt.loading),amount:K,receiveAmountDisplay:Dt,receiveUsdEstimate:Bt,selectedDestToken:ve,destTokenSymbol:yt,destChainName:Ve,destChainLogo:st,compatibleDestinationChains:He,networkSwitchRef:Z,onOpenNetworkPopover:mt,showNetworkPopover:_,setShowNetworkPopover:X,networkPopoverPos:ce,selectedChainId:R,setSelectedChainId:W,dark:k,dk:E})]}),a.jsxs("div",{style:{marginBottom:S.spacing.sm},children:[a.jsx(gu,{show:H,onToggle:ht,showCustomAddress:B,setShowCustomAddress:$,customRecipient:ie,setCustomRecipient:L,externalAddress:we,recipientAddress:wt,destChainName:Ve,destChainLogo:st,compatibleDestinationChains:He,txDetailsChainSwitchRef:he,onOpenNetworkPopover:mt,sourceChainLabel:Rt,sourceDetailsLogo:io,sourceTokenLabel:Ct,amount:K,totalSourceDebitDisplay:ae,receiveAmountDisplay:Dt,destTokenSymbol:yt,shouldQuoteWithdrawGas:dn,estimatingFee:Se,feeError:ft,displayedGasFee:qt,selectedDestToken:ve,theme:S,styles:s,dark:k,dk:E}),be&&a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[a.jsx(gn,{palette:E,label:"FEE ASSET",value:a.jsxs("select",{"aria-label":"Withdrawal fee asset",disabled:gt,value:Ke.source?Ke.sourceKey(Ke.source):"",onChange:Xe=>Ke.setSource(Ke.candidates.find(at=>Ke.sourceKey(at)===Xe.target.value)??null),children:[!Ke.candidates.length&&a.jsx("option",{value:"",children:"No eligible fee balance"}),Ke.candidates.map(Xe=>a.jsxs("option",{value:Ke.sourceKey(Xe),children:[Xe.displaySymbol||Xe.symbol," \xB7"," ",Xe._source==="spice"?"Spicenet":h.getChainConfig(Xe.chainId)?.displayName]},Ke.sourceKey(Xe)))]})}),a.jsx(gn,{palette:E,label:"MAXIMUM FEE FUNDING",value:et.fees.isLoading?"Estimating...":et.fees.ready&&Ke.source&&et.amount.sourceRequiredAmount!==null?`${A.formatUnits(et.amount.sourceRequiredAmount,Ke.source.decimals)} ${Ke.source.displaySymbol||Ke.source.symbol}`:"Unavailable"}),(et.status.error||et.fees.error)&&a.jsx($t,{variant:"error",size:"compact",palette:E,children:et.status.error||et.fees.error}),et.status.finalizationError&&a.jsx(h.Button,{variant:"outline",dark:k,disabled:et.status.finalizing,onClick:()=>void et.retryFinalization(),children:"Retry application update"}),et.status.statusMsg&&a.jsx("span",{role:"status",children:et.status.statusMsg})]}),z&&!xe&&He.length===0&&a.jsx($t,{variant:"warning",size:"compact",palette:E,children:"No withdrawal networks are available for this asset."}),it&&a.jsx($t,{variant:"error",size:"compact",palette:E,fontFamily:s?.fontFamily||S.typography.fontFamily,style:{marginBottom:"12px"},children:it}),me&&a.jsxs($t,{variant:ke?"error":"warning",size:"compact",palette:E,children:[ke?"Unable to load this balance. Please try again.":"Some other balances could not be refreshed."," ",a.jsx("button",{type:"button",onClick:()=>void ee(),children:"Retry"})]}),a.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:()=>{Ht&&(be?et.submitPay():Wn())},disabled:wn||gt,theme:S,dark:k,styles:s,style:{marginTop:"8px"},children:gt?"EXECUTING...":be&&Wt?"WITHDRAWN":zn})]})]})})}return null},ki=bu,Cu=({onDepositClick:e,onWithdrawClick:t,depositDisabled:n=!1,withdrawDisabled:s=!1,primaryColor:o="#EA4B4B",dark:r=!1})=>!e&&!t?null:a.jsxs("div",{style:{display:"flex",gap:"8px"},children:[e&&a.jsx(h.Button,{variant:"outline",onClick:e,disabled:n,dark:r,styles:{button:{backgroundColor:o}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&a.jsx(h.Button,{variant:"outline",onClick:()=>t(),disabled:s,dark:r,styles:{button:{backgroundColor:o}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),vu=p.memo(Cu),ku=({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 a.jsxs("div",{children:[a.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:t.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:e.title}),a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.items.map((o,r)=>a.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:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[o.tokenLogoURI?a.jsx("img",{src:o.tokenLogoURI,alt:o.tokenSymbol,style:{width:"20px",height:"20px",borderRadius:"50%"}}):a.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)}),a.jsxs("div",{children:[a.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:t.textPrimary},children:o.tokenSymbol}),a.jsx("div",{style:{fontSize:"11px",color:t.textSecondary},children:o.label})]})]}),a.jsx("div",{style:{fontSize:"13px",fontWeight:600,color:s(o.valueColor)},children:o.displayValue})]},r))})]})},Su=p.memo(ku);var Iu="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 Au=({appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,showUsdSummary:r=!0,address:i,dk:l,dark:c=!1,showModeToggle:d,isEmbeddedMode:u=!0,onModeToggle:f})=>{const[m,g]=p.useState(!1),y=async()=>{i&&await h.copyToClipboard(i)&&(g(!0),setTimeout(()=>g(!1),2e3))},x=t==="active",w=n||(x?"Active":"Inactive"),C=x?"#10b981":"#9ca3af",b=a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[a.jsxs("div",{children:[a.jsx("strong",{children:"Embedded:"})," Deposit assets into ",e," account and use them here."]}),a.jsxs("div",{children:[a.jsx("strong",{children:"External:"})," Use assets from your connected wallet here."]})]});return a.jsxs("div",{children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[a.jsxs("div",{style:{fontSize:"13px",fontWeight:600,color:l.textPrimary},children:[e," Account"]}),d?a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[a.jsxs("button",{onClick:f,style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:c?l.hoverBg:"#f3f4f6",border:c?`1px solid ${l.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"11px",fontWeight:600,fontFamily:h.font.mono,color:l.textSecondary,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease",letterSpacing:"0.02em"},children:[a.jsx("span",{children:u?"Embedded":"External"}),a.jsx("img",{src:Iu,alt:"","aria-hidden":"true",style:{width:"11px",height:"11px",display:"block",...c?{filter:"invert(0.65)"}:{}}})]}),a.jsx(ha,{content:b,label:"Account mode info",textColor:c?l.textPrimary:"#f9fafb",backgroundColor:c?l.cardBg:"#111827",borderColor:c?l.cardBorder:"rgba(255,255,255,0.08)",accentColor:c?l.textSecondary:"#6b7280",children:a.jsx("img",{src:xo,alt:"","aria-hidden":"true",style:{width:"12px",height:"12px",display:"block",...c?{filter:"invert(0.65)"}:{}}})})]}):a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:c?l.hoverBg:x?"#ecfdf5":"#f3f4f6",border:c?`1px solid ${l.cardBorder}`:x?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[a.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:C}}),a.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:c?l.textSecondary:x?"#065f46":"#6b7280"},children:w})]})]}),r&&a.jsx("div",{style:{fontSize:"28px",fontWeight:700,color:l.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:h.formatUsd(s)}),r&&o&&a.jsx("div",{style:{fontSize:"12px",color:l.textSecondary,marginBottom:"8px"},children:o}),i&&a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[a.jsx("span",{style:{fontSize:"12px",fontFamily:h.font.mono,color:c?l.textSecondary:"#9ca3af"},children:h.truncateAddress(i)}),a.jsx("button",{onClick:y,style:{padding:"2px 6px",fontSize:"10px",fontWeight:500,backgroundColor:"transparent",color:c?l.textSecondary:"#9ca3af",border:"none",cursor:"pointer",borderRadius:"4px",transition:"background-color 150ms ease, color 150ms ease"},title:"Copy address",children:m?"Copied":"Copy"})]})]})},Eu=p.memo(Au),Fu=e=>`${e.tokenAddress}-${e.chainId}`,Tu=({spiceAssets:e,loading:t,dk:n,dark:s=!1,canDirectWithdraw:o=!1,onDirectWithdraw:r,directWithdrawState:i,onWithdrawClick:l})=>{const c={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},d={backgroundColor:n.cardBg,border:s?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return t?a.jsxs("div",{children:[a.jsx("div",{style:c,children:"Idle Balances"}),[1,2].map(u=>a.jsx("div",{style:{...d,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},u))]}):e.length===0?a.jsxs("div",{children:[a.jsx("div",{style:c,children:"Idle Balances"}),a.jsx("div",{style:{...d,padding:"16px",textAlign:"center",fontSize:"13px",color:s?n.textSecondary:"#9ca3af"},children:"No assets yet. Deposit to get started."})]}):a.jsxs("div",{children:[a.jsx("div",{style:c,children:"Idle Balances"}),a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map(u=>{const f=h.getChainConfig(u.chainId),m=u.chainDisplayName||f?.displayName||`Chain ${u.chainId}`,g=u.tokenDisplaySymbol||u.tokenDisplayName||u.tokenSymbol,y=Fu(u),x=u.receiptTokenId&&l,w=x||o&&u.directWithdraw&&!!r,C=!x&&i?.key===y?i:null,b=C?.step==="pending";return a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...d},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[u.logoURI?a.jsx("img",{src:u.logoURI,alt:u.tokenSymbol,style:{width:"24px",height:"24px",borderRadius:"50%"}}):a.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)}),a.jsxs("div",{children:[a.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:g}),a.jsx("div",{style:{fontSize:"11px",color:s?n.textSecondary:"#9ca3af"},children:m})]})]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[a.jsxs("div",{style:{textAlign:"right"},children:[a.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:Hs({balance:BigInt(u.balance),decimals:u.tokenDecimals})}),a.jsx("div",{style:{fontSize:"11px",color:C?.step==="error"?n.errorText:s?n.textSecondary:"#9ca3af"},children:C?.step==="error"?C.message||"Withdraw failed":!Number.isFinite(u.usdValue)||u.usdValue<=0?"\u2014":`${h.formatUsd(u.usdValue)}${u.priceStatus==="stale"?" (stale)":""}`})]}),w&&a.jsx("button",{onClick:()=>{b||(x?x(u.receiptTokenId):r(u))},disabled:b,title:x?"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"})]})]},u.positionId??`${u.owner??""}:${u.location??""}:${u.receiptTokenId??`${u.tokenAddress}-${u.chainId}`}`)})})]})},ju=p.memo(Tu),Bu=({pendingDeposits:e,onCompleteDeposit:t,dk:n,dark:s=!1})=>e.length===0?null:a.jsxs("div",{children:[a.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:"Pending Deposits"}),a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((o,r)=>{const i=h.getChainConfig(o.chainId)?.displayName||`Chain ${o.chainId}`;return a.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:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[a.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)}),a.jsxs("div",{children:[a.jsxs("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:[o.amount," ",o.tokenSymbol]}),a.jsxs("div",{style:{fontSize:"11px",color:n.warningText},children:["on ",i]})]})]}),a.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}-${r}`)})})]}),Ru=p.memo(Bu),Du=({appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,showUsdSummary:r,address:i,spiceAssets:l,spiceAssetsLoading:c,pendingDeposits:d,customSections:u,notice:f,onDepositClick:m,onWithdrawClick:g,depositDisabled:y,onCompleteDeposit:x,primaryColor:w,dk:C,dark:b=!1,showModeToggle:I,isEmbeddedMode:S,onModeToggle:k,showConnectExternalCta:E,onConnectExternalWallet:F,connectExternalError:T,showHowItWorks:D=!0,canDirectWithdraw:j,onDirectWithdraw:U,directWithdrawState:P})=>{const[O,q]=p.useState(!1);return a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[a.jsx(Eu,{appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,showUsdSummary:r,address:i,dk:C,dark:b,showModeToggle:I,isEmbeddedMode:S,onModeToggle:k}),f&&a.jsx("div",{style:{padding:"10px 12px",borderRadius:"8px",backgroundColor:f.tone==="warning"?b?"rgba(245, 158, 11, 0.12)":"#fffbeb":f.tone==="success"?b?"rgba(16, 185, 129, 0.12)":"#ecfdf5":C.cardBg,border:f.tone==="warning"?b?"1px solid rgba(245, 158, 11, 0.35)":"1px solid #fde68a":f.tone==="success"?b?"1px solid rgba(16, 185, 129, 0.35)":"1px solid #a7f3d0":b?`1px solid ${C.cardBorder}`:"1px solid #e5e7eb",color:f.tone==="warning"?b?"#fbbf24":"#92400e":f.tone==="success"?b?"#34d399":"#047857":C.textSecondary,fontSize:"12px",lineHeight:1.45,fontWeight:500},children:f.message}),E&&a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[a.jsx("button",{onClick:F,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:w||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:h.font.ui,transition:"opacity 150ms ease"},children:"Connect External Wallet"}),T&&a.jsx("span",{style:{fontSize:"11px",color:b?C.errorText:"#b91c1c",lineHeight:1.4},children:T})]}),a.jsx("div",{style:{height:"1px",backgroundColor:b?"#2d2d2d":"#e5e7eb"}}),a.jsx(vu,{onDepositClick:m,onWithdrawClick:g,depositDisabled:y,primaryColor:w,dark:b}),D&&a.jsxs("div",{children:[a.jsxs("button",{onClick:()=>q(!O),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:C.cardBg,border:b?`1px solid ${C.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:C.textSecondary,fontSize:"12px",fontWeight:500},children:[a.jsx("span",{children:"How It Works"}),a.jsx("span",{style:{transform:O?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),O&&a.jsxs("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:b?C.cardBg:"#f0fdf4",border:b?`1px solid ${C.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:b?C.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),a.jsx(Ru,{pendingDeposits:d,onCompleteDeposit:x,dk:C,dark:b}),a.jsx(ju,{spiceAssets:l,loading:c,dk:C,dark:b,canDirectWithdraw:j,onDirectWithdraw:U,directWithdrawState:P,onWithdrawClick:g}),u.map((R,W)=>a.jsx(Su,{section:R,dk:C,dark:b},W))]})},Ou=p.memo(Du);function Nu({dark:e,onSuccess:t,onError:n}){const{disconnect:s}=Zt.useDisconnect(),{logout:o}=Ws.usePrivy(),[r,i]=p.useState(!1);return a.jsx(h.Button,{variant:"ghost",fullWidth:!0,dark:e,loading:r,onClick:async()=>{i(!0);try{s(),await o(),t()}catch(l){n(h.sanitizeError(l,"Unable to disconnect. Please try again."))}finally{i(!1)}},children:"Disconnect"})}const Vo=380,Sn=8,Mu=[],Pu={};function Si(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function Uu(e,t){const n=new Map;Object.entries(t).forEach(([o,r])=>{if(!Number.isFinite(r)||r<=0)return;n.set(o,r),n.set(o.toUpperCase(),r);const i=Si(o);i&&n.set(i,r)});const s=[e.symbol,e.displaySymbol,e.receiptTokenName,e.name,e.displayName];for(const o of s){if(!o)continue;const r=n.get(o)??n.get(o.toUpperCase());if(r!==void 0)return r;const i=Si(o);if(!i)continue;const l=n.get(i);if(l!==void 0)return l}return 0}const Wu=({appName:e="Spice",status:t="active",statusLabel:n,customSections:s=Mu,extraAssets:o=[],tokenPrices:r={},tokenLogos:i=Pu,breakdownLabels:l=[],notice:c,styles:d,dark:u=!1,onDepositSuccess:f,onDepositClick:m,onWithdrawClick:g,onCompleteDeposit:y,showModeToggle:x=!1,defaultMode:w,showUsdSummary:C=!0,alwaysShowEmbeddedIdle:b=!1,showDisconnect:I=!1})=>{const S=p.useContext(h.SpiceFlowProviderContext),k=S?.mode!=="7702",E=!!S?.isWhitelistGateActive,F=!!S?.isWhitelistConfigured&&S?.isUserWhitelisted!==!0,T=p.useRef(!1);p.useEffect(()=>{if(!T.current){if(h.hasStoredSpiceFlowMode()){T.current=!0;return}w&&S?.setMode&&(S.setMode(w==="non7702"?"ondemand":"7702"),T.current=!0)}},[S,w]);const[D,j]=p.useState(!1),[U,P]=p.useState(null),[O,q]=p.useState({top:0,bottom:0,left:0,placement:"below"}),R=p.useRef(null),W=p.useRef(null),{address:K,isConnected:G}=h.useWallet(),_=S?.embeddedWalletAddress,X=S?.externalWalletAddress,{embeddedAddress:Q}=h.useProviderWallets(),{dark:te,primaryColor:B,dk:$}=h.useSpiceBrand(d,u),ie=k&&!X,L=!k||b,H=L?_||Q:K,fe=p.useMemo(()=>S?.supportedChainIds??v.getChainIdsByNetwork("mainnet"),[S?.supportedChainIds]),Z=Dn({owner:L?H:X,role:"holding",sourceChains:fe,additionalSourceTokens:o.filter(ne=>!ne.receiptTokenId&&(!ne.owner||h.addressesEqual(ne.owner,L?H:X))).map(ne=>({address:ne.tokenAddress,chainId:ne.chainId,decimals:ne.tokenDecimals,symbol:ne.tokenSymbol,logoURI:ne.logoURI})),includeRollupAssets:L,enabled:L?!!H:!!X}),he=Z.assets.filter(ne=>ne._source==="spice"),ge=Z.walletAssets,ce=Z.loading,Ae=Z.refresh,N=L?H:X,J=p.useMemo(()=>o.filter(ne=>!ne.owner||ne.owner.toLowerCase()===N?.toLowerCase()).map(ne=>({...ne,owner:ne.owner??N,location:ne.location??(ne.receiptTokenId?"rollup":L?"embedded":"external")})),[o,N,L]),M=p.useMemo(()=>ge.map(ne=>({owner:ne.owner,location:ne.location,positionId:pt(ne),tokenAddress:ne.address,tokenSymbol:ne.symbol,tokenDecimals:ne.decimals,chainId:ne.chainId,chainDisplayName:h.getChainName(ne.chainId),balance:ne.balance.toString(),balanceFormatted:ne.balanceFormatted,usdValue:ne.balanceUsd||0,logoURI:ne.logoURI||i[ne.symbol],directWithdraw:L})),[ge,J,i,L]),Y=p.useMemo(()=>{const ne=L?he.map(ee=>{const ye=ee.balanceUsd||0,Fe=Number.isFinite(ee.balanceFormatted)?ee.balanceFormatted:0,Ye=Uu(ee,r),je=ee.priceStatus&&Ye>0?Ye*Fe:ye>0?ye:Ye*Fe;return{owner:ee.owner,location:ee.location,positionId:pt(ee),tokenAddress:ee.address,tokenSymbol:ee.symbol,tokenDisplaySymbol:zs(ee),tokenDisplayName:Xi(ee),tokenDecimals:ee.decimals,chainId:ee.chainId,chainDisplayName:qs(ee),balance:ee.balance.toString(),balanceFormatted:ee.balanceFormatted,usdValue:je,priceStatus:Ye>0?void 0:ee.priceStatus,logoURI:ee.logoURI,receiptTokenId:ee.receiptTokenId}}):[],Te=ee=>`${ee.owner?.toLowerCase()}:${ee.location}:${ee.chainId}:${ee.receiptTokenId??v.normalizeNativeTokenAddress(ee.tokenAddress).toLowerCase()}`,xe=new Map([...Z.rollupAssets,...ge].map(ee=>[Te({...ee,tokenAddress:ee.address}),ee])),me=new Map([...ne,...M].map(ee=>[Te(ee),ee]));for(const ee of ie?[]:J){const ye=Te(ee),Fe=me.get(ye);me.set(ye,Fe?{...ee,...Fe,logoURI:ee.logoURI??Fe.logoURI,tokenDisplayName:ee.tokenDisplayName??Fe.tokenDisplayName,tokenDisplaySymbol:ee.tokenDisplaySymbol??Fe.tokenDisplaySymbol}:ee)}return[...me.values()].filter(ee=>BigInt(ee.balance)>0n&&Nr({isDiscovered:xe.get(Te(ee))?.isDiscovered,balanceUsd:ee.usdValue},!0)&&Zo(xe.get(Te(ee))??{address:ee.tokenAddress,symbol:ee.tokenSymbol,displaySymbol:ee.tokenDisplaySymbol},S?.allowedTokens)).sort((ee,ye)=>ye.usdValue-ee.usdValue)},[L,ie,he,Z.rollupAssets,r,M,J,S?.allowedTokens]),ue=p.useMemo(()=>Y.reduce((ne,Te)=>ne+Te.usdValue,0),[Y]),{pendingDeposits:We,refresh:Ce}=sa({chainIds:fe,enabled:!!K,discoverWalletBalances:!0}),oe=p.useMemo(()=>s.reduce((ne,Te)=>ne+(Te.totalValue??0),0),[s]),Ee=ue+oe,we=p.useMemo(()=>{const ne=[];ue>0&&ne.push(`${h.formatUsd(ue)} idle`);for(const Te of s){const xe=l.find(me=>me.sectionTitle===Te.title)?.label||Te.title.toLowerCase();ne.push(`${h.formatUsd(Te.totalValue??0)} ${xe}`)}return ne.join(" \xB7 ")},[ue,s,l]),Pe=p.useCallback(ne=>{y?y(ne):P(ne)},[y]),Qe=p.useCallback(()=>{P(null)},[]),it=p.useCallback(()=>{P(null),f?.()},[f]),ze=p.useCallback(()=>{if(!R.current)return;const ne=R.current.getBoundingClientRect(),Te=window.innerHeight-ne.bottom-Sn,xe=ne.top-Sn,me=Te>=400||Te>=xe?"below":"above",ee=Math.max(Sn,Math.min(ne.right-Vo,window.innerWidth-Vo-Sn)),ye=me==="below"?ne.bottom+Sn:ne.top-Sn,Fe=me==="above"?window.innerHeight-ye:0;q({top:ye,bottom:Fe,left:ee,placement:me})},[]);p.useLayoutEffect(()=>{D&&ze()},[D,ze]),p.useEffect(()=>{if(!D)return;const ne=me=>{R.current&&!R.current.contains(me.target)&&W.current&&!W.current.contains(me.target)&&j(!1)},Te=me=>{me.key==="Escape"&&j(!1)},xe=()=>ze();return document.addEventListener("mousedown",ne),document.addEventListener("keydown",Te),window.addEventListener("scroll",xe,{passive:!0}),window.addEventListener("resize",ze),()=>{document.removeEventListener("mousedown",ne),document.removeEventListener("keydown",Te),window.removeEventListener("scroll",xe),window.removeEventListener("resize",ze)}},[D,ze]);const Je=L?_||Q||K:X||K,Re=p.useCallback(()=>{S?.setMode&&S.setMode(k?"7702":"ondemand")},[S,k]),[ot,_e]=p.useState(null);let Ue=null;try{Ue=Ws.useConnectWallet({onSuccess:()=>_e(null),onError:ne=>_e(h.sanitizeError(ne,"Failed to connect wallet."))}).connectWallet}catch{Ue=null}const Le=p.useCallback(()=>{Ue&&(j(!1),_e(null),Ue({walletChainType:"ethereum-only"}))},[Ue]),ct=!X&&!!Ue,Me=p.useCallback(()=>{j(!1),m?.()},[m]),Ze=p.useCallback(ne=>{j(!1),g?.(ne)},[g]),De=p.useCallback(ne=>{j(!1),Pe(ne)},[Pe]),[Ge,qe]=p.useState(null),$e=L&&!!X&&!h.addressesEqual(N,X),Se=p.useCallback(ne=>{const Te=ge.find(xe=>xe.chainId===ne.chainId&&h.addressesEqual(xe.address,ne.tokenAddress));Te&&(j(!1),qe(Te))},[ge]);if(typeof window>"u")return null;const Ne=a.jsxs("button",{ref:R,onClick:()=>j(!D),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:te?$.hoverBg:"#ffffff",border:te?`1px solid ${$.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:h.font.ui,color:te?$.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:te?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[a.jsxs("span",{children:[e," Account"]}),G&&C&&a.jsxs("span",{style:{color:te?$.textSecondary:"#6b7280"},children:["\xB7 ",h.formatUsd(Ee)]}),a.jsx("span",{style:{fontSize:"10px",color:te?$.textSecondary:"#9ca3af",transform:D?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),ft=D?Fn.createPortal(a.jsxs(a.Fragment,{children:[a.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:h.z.popover},onClick:()=>j(!1)}),a.jsxs("div",{ref:W,style:{position:"fixed",top:O.placement==="below"?`${O.top}px`:"auto",bottom:O.placement==="above"?`${O.bottom}px`:"auto",left:`${O.left}px`,width:`${Vo}px`,maxWidth:`calc(100vw - ${Sn*2}px)`,maxHeight:"80vh",backgroundColor:te?$.shell:"#ffffff",border:te?`1px solid ${$.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:te?"0 10px 40px rgba(0, 0, 0, 0.5)":"0 10px 40px rgba(0, 0, 0, 0.12)",zIndex:h.z.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${h.easing.out}`},children:[a.jsx(Ou,{appName:e,status:t,statusLabel:n,totalUsdValue:Ee,breakdownSubtitle:we,showUsdSummary:C,address:L?Je:K,spiceAssets:Y,spiceAssetsLoading:ce,pendingDeposits:We,customSections:s,notice:c,onDepositClick:m?Me:void 0,onWithdrawClick:g?Ze:void 0,depositDisabled:F,onCompleteDeposit:De,primaryColor:B,dk:$,dark:te,showModeToggle:x,isEmbeddedMode:!k,onModeToggle:Re,showConnectExternalCta:ct,onConnectExternalWallet:Le,connectExternalError:ot,showHowItWorks:!E,canDirectWithdraw:$e,onDirectWithdraw:Se}),I&&G&&a.jsx("div",{style:{padding:"0 16px 16px"},children:a.jsx(Nu,{dark:te,onSuccess:()=>j(!1),onError:_e})})]}),a.jsx("style",{children:`
|
|
43
|
+
`,Da=({title:e,showChevron:t,expanded:n,onToggleDetails:s,showClose:o,onClose:r,fontFamily:i,labelColor:l,textPrimary:c,closeHoverBg:d,closePressedBg:u})=>{const[f,m]=p.useState(!1),[g,y]=p.useState(!1);return a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"16px"},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:s?"pointer":"default"},onClick:s,children:[a.jsxs("span",{style:{fontSize:"13px",fontWeight:500,color:l,fontFamily:i},children:[e," "]}),t&&a.jsx(On,{color:l,direction:n?"up":"down"})]}),o&&a.jsx("button",{onClick:r,onMouseEnter:()=>m(!0),onMouseLeave:()=>{m(!1),y(!1)},onMouseDown:()=>y(!0),onMouseUp:()=>y(!1),style:{background:g?u:f?d:"none",border:"none",borderRadius:"4px",cursor:"pointer",padding:"4px",display:"flex",alignItems:"center",justifyContent:"center",color:f||g?c:l,transform:g?"scale(0.9)":f?"scale(1.1)":"scale(1)",transition:h.transition.interactive},children:a.jsx($n,{size:16})})]})},Oa=({chainName:e,bg:t,border:n,textPrimary:s,labelColor:o,primaryColor:r})=>a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"20px 16px",borderRadius:"8px",backgroundColor:t,border:`1px solid ${n}`,gap:"12px"},children:[a.jsx(h.Spinner,{size:24,borderWidth:3,color:r}),a.jsxs("div",{children:[a.jsx("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:h.font.mono,letterSpacing:"0.5px",color:s},children:"PROCESSING TRANSACTION"}),a.jsxs("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:o},children:["on ",e]})]})]}),Na=({bg:e,border:t,left:n,right:s})=>a.jsxs("div",{style:{padding:"10px 12px",borderRadius:"6px",backgroundColor:e,border:`1px solid ${t}`,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[n,s]}),Do=({isOpen:e,onClose:t,onComplete:n,closeOnComplete:s=!1,type:o,results:r,chainId:i,chainName:l,explorerUrl:c,theme:d,styles:u,dark:f,intentStatus:m,onRetry:g,onNewTx:y,onRetryTx:x,asOverlay:w=!0,isProcessing:C=!1,showStepBreakdown:b=!0})=>{const{theme:I,primaryColor:S,dark:k,dk:E}=h.useSpiceBrand(u,f),F=d||I,[T,D]=p.useState(!1),j=l??(i?h.getChainName(i):"Network"),U=c??(i&&h.getExplorerUrl(i,"").replace(/\/tx\/.*$/,"")||void 0),P=k?E.cardBg:"#ffffff",O=k?"0 4px 20px rgba(0, 0, 0, 0.4)":"0 4px 20px rgba(0, 0, 0, 0.1)",q=k?"0 -4px 8px -2px rgba(0, 0, 0, 0.4)":"0 -4px 8px -2px rgba(0, 0, 0, 0.15)",R=E.textSecondary,W=k?E.textPrimary:"#374151",K=k?E.inputBg:"#f9fafb",G=k?E.inputBorder:"#e5e7eb",_=k?E.inputBg:"#f3f4f6",X=k?E.inputBorder:"#e5e7eb",[Q,te]=p.useState(!0),B=k?E.inputBg:"#f9fafb",$=k?E.hoverBg:"#f3f4f6",ie=k?{successBg:E.successBg,successBorder:E.successBorder,successText:E.successText,errorBg:E.errorBg,errorBorder:E.errorBorder,errorText:E.errorText}:{},L=m?.steps.find(ce=>ce.status==="failed")?.error;p.useEffect(()=>{!e&&!m&&D(!1)},[e,m]);const H=()=>{D(!0),setTimeout(()=>{window.dispatchEvent(new CustomEvent("tx-complete",{detail:{type:o,results:r}})),window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:{type:o,status:"success",results:r}})),n?.(),s&&t()},300)},fe=()=>{te(!Q)};if(m){const{steps:ce,overallStatus:Ae}=m,N=Ae==="processing",J=Ae==="success",M=Ae==="failed",Y=ce.filter(oe=>oe.transactionHash)[0],ue=ce.length>1?ce.map(oe=>oe.chainName).filter(Boolean).join(" and "):j!=="Network"?j:ce[0]?.chainName||j,We=U||(Y?h.getExplorerUrl(Y.chainId,Y.transactionHash||"").replace(/\/tx\/.*$/,""):void 0),Ce=a.jsxs(a.Fragment,{children:[a.jsx(Da,{title:N?`Processing ${o.charAt(0).toUpperCase()+o.slice(1)}`:`${o.charAt(0).toUpperCase()+o.slice(1)} results`,showChevron:b,expanded:Q,onToggleDetails:fe,showClose:!N,onClose:t,fontFamily:u?.fontFamily||F.typography.fontFamily,labelColor:R,textPrimary:W,closeHoverBg:B,closePressedBg:$}),a.jsx("div",{style:{marginBottom:"16px"},children:N?a.jsx(Oa,{chainName:ue,bg:_,border:X,textPrimary:W,labelColor:R,primaryColor:S}):a.jsx(Ba,{isSuccess:J,type:o,chainName:ue,explorerUrl:We,txHash:Y?.transactionHash,dark:k,...ie,textSecondary:R})}),b&&a.jsx("div",{style:{overflow:"hidden",maxHeight:Q?"300px":"0px",opacity:Q?1:0,transition:"max-height 0.3s ease, opacity 0.3s ease",marginBottom:Q?"16px":"0"},children:a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:ce.map((oe,Ee)=>{const we=oe.transactionHash?h.getExplorerUrl(oe.chainId,oe.transactionHash):null;return a.jsx(Na,{bg:K,border:G,left:a.jsx("span",{style:{fontSize:"13px",color:W},children:oe.chainName?`On ${oe.chainName}`:oe.description||`Step ${Ee+1}`}),right:a.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:oe.status==="success"?"#10b981":oe.status==="failed"?"#ef4444":R,fontWeight:500},children:[we&&a.jsx("a",{href:we,target:"_blank",rel:"noopener noreferrer",style:{color:k?E.infoText:"#2563eb",textDecoration:"none"},onClick:Pe=>Pe.stopPropagation(),children:"View"}),oe.status==="success"?"\u2713":oe.status==="failed"?"\u2717":"\u25CB"]})},Ee)})})}),!N&&a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[M&&g&&a.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:g,theme:F,styles:u,dark:k,children:"TRY AGAIN"}),y&&a.jsxs(h.Button,{variant:"outline",fullWidth:!0,onClick:y,theme:F,styles:u,dark:k,children:["NEW ",o.toUpperCase()," \u2192"]})]})]});return w?a.jsxs("div",{style:{position:"absolute",bottom:0,left:0,right:0,zIndex:10,animation:T?"slideDown 0.3s ease-in forwards":"slideUp 0.3s ease-out forwards",pointerEvents:"auto"},children:[a.jsx("div",{style:{backgroundColor:P,borderRadius:"12px 12px 0 0",width:"100%",padding:"18px 24px 24px",boxShadow:q},children:Ce}),a.jsx("style",{children:Ra})]}):a.jsx("div",{style:{backgroundColor:P,borderRadius:"12px",padding:"24px",width:"100%",boxShadow:O},children:Ce})}if(!e&&!C||!C&&(!r||r.length===0))return null;const Z=r?r.every(ce=>ce.success):!1,he=r?.[0],ge=[...r??[]].reverse().find(ce=>ce.txHash)?.txHash||he?.txHash;return a.jsxs("div",{style:{position:w?"absolute":"relative",bottom:w?0:void 0,left:w?0:void 0,right:w?0:void 0,zIndex:w?10:void 0,animation:w?T?"slideDown 0.3s ease-in forwards":"slideUp 0.3s ease-out forwards":void 0,pointerEvents:"auto",width:"100%"},children:[a.jsx("div",{style:{backgroundColor:P,borderRadius:w?"12px 12px 0 0":"12px",width:"100%",padding:"18px 0 24px",boxShadow:w?q:O},children:a.jsxs("div",{style:{width:"100%",boxSizing:"border-box",padding:"0 24px"},children:[a.jsx(Da,{title:C?`Processing ${o.charAt(0).toUpperCase()+o.slice(1)}`:`${o.charAt(0).toUpperCase()+o.slice(1)} results`,showChevron:!C&&b,expanded:Q,onToggleDetails:C?void 0:fe,showClose:!C,onClose:t,fontFamily:u?.fontFamily||F.typography.fontFamily,labelColor:R,textPrimary:W,closeHoverBg:B,closePressedBg:$}),a.jsx("div",{style:{marginBottom:"16px",animation:"statusFadeIn 220ms cubic-bezier(0.22, 1, 0.36, 1) both"},children:C?a.jsx(Oa,{chainName:j,bg:_,border:X,textPrimary:W,labelColor:R,primaryColor:S}):a.jsx(Ba,{isSuccess:Z,type:o,chainName:j,explorerUrl:U,txHash:ge,dark:k,...ie,textSecondary:R})},C?"processing":Z?"success":"error"),!C&&b&&r&&r.length>1&&a.jsx("div",{style:{overflow:"hidden",maxHeight:Q?"200px":"0px",opacity:Q?1:0,transition:"max-height 0.3s ease, opacity 0.3s ease",marginBottom:Q?"16px":"0"},children:a.jsx("div",{style:{maxHeight:"180px",overflowY:"auto",display:"flex",flexDirection:"column",gap:"8px"},children:r.map((ce,Ae)=>a.jsx(Na,{bg:K,border:G,left:a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[a.jsx("span",{style:{fontWeight:600,fontSize:"13px",color:E.textPrimary,fontFamily:h.font.mono},children:ce.asset.symbol}),ce.amount&&a.jsx("span",{style:{fontSize:"12px",color:R},children:ce.amount})]}),right:a.jsx("span",{style:{fontSize:"12px",color:ce.success?"#10b981":"#ef4444",fontWeight:500},children:ce.success?"\u2713":"\u2717"})},Ae))})}),!C&&!Z&&r&&a.jsx("div",{style:{padding:"12px",backgroundColor:E.errorBg,border:`1px solid ${E.errorBorder}`,borderRadius:"8px",marginBottom:"16px"},children:a.jsx("p",{style:{fontSize:"13px",color:E.errorText,margin:0,lineHeight:1.5},children:L||r.find(ce=>!ce.success)?.error||`${o.charAt(0).toUpperCase()+o.slice(1)} failed. Please try again.`})}),!C&&a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[!Z&&x&&a.jsxs(h.Button,{variant:"outline",fullWidth:!0,onClick:x,theme:F,styles:u,dark:k,children:["TRY AGAIN ",o.toUpperCase()]}),Z&&a.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:H,theme:F,styles:u,dark:k,children:"DONE"})]})]})}),a.jsx("style",{children:Ra})]})};function Ma(e){const t=new Set(v.getEquivalentAddresses(e).map(n=>n.toLowerCase()));return t.add(e.toLowerCase()),t}const hd=["USDC","USDT","WETH","WBTC"];function Pa(e,t){const n=h.getChainConfig(t);if(!n)return;if(n.nativeCurrency.symbol.toUpperCase()===e.toUpperCase())return{address:v.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 an(e,t,n){const s=h.getChainConfig(t);if(!s)return;if(n!==void 0){if(v.isNativeToken(e)&&!v.getTokenByAddress(e,n))return;const i=oo(e,n,t);return i?{address:i.address.toLowerCase(),symbol:i.symbol,decimals:i.decimals,chainId:t}:void 0}if(v.isNativeToken(e))return;const o=Ma(e),r=s.supportedTokens?.find(i=>o.has(i.address.toLowerCase()));if(r)return{address:r.address.toLowerCase(),symbol:r.symbol,decimals:r.decimals,chainId:t}}function gd(e){const{sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:o,intermediaryCandidates:r=hd}=e;if(xs(t,n))return{strategy:"direct",sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:o,summary:`${t.symbol} fronted directly`};if(s===o&&(v.isNativeToken(t.address)||!v.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(an(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(an(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 r){const l=Pa(i,s);if(!l||xs(t,l)||xs(n,l))continue;const c=Pa(i,o);if(c&&xs(l,c))return{strategy:"intermediary",sourceAsset:t,outputAsset:n,intermediaryAsset:c,sourceChainId:s,destinationChainId:o,summary:`${t.symbol} \u2192 ${i} on source, fronted, then ${i} \u2192 ${n.symbol} on destination`}}throw new h.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:r})}async function xd(e){const{route:t,sourceAmount:n,userAddress:s,registry:o,actionCalls:r,slippage:i}=e;async function l(c,d,u,f){const m=await o.resolveSwap({type:"swap",tokenIn:d,tokenOut:u,amountIn:f,maxSlippage:i},c,s);if(!m)throw new h.SpiceflowError("NO_LIQUIDITY",`No venue returned a quote for ${d} \u2192 ${u} on chain ${c}. No liquidity available for this pair.`,{chainId:c,tokenIn:d,tokenOut:u,amountIn:f.toString()});return m}switch(t.strategy){case"direct-swap":{const c=await l(t.destinationChainId,t.sourceAsset.address,t.outputAsset.address,n);return{chainBatches:[{chainId:t.destinationChainId,calls:[...c.calls,...r]}],solverFrontToken:t.outputAsset,solverFrontAmount:0n,resolvedSwaps:{sourceSwap:c}}}case"direct":{const c=an(t.sourceAsset.address,t.destinationChainId,t.sourceChainId)||t.sourceAsset;if(Ma(c.address).has(t.outputAsset.address.toLowerCase()))return{chainBatches:[{chainId:t.destinationChainId,calls:r}],solverFrontToken:c,solverFrontAmount:n,resolvedSwaps:{}};const d=await l(t.destinationChainId,c.address,t.outputAsset.address,n);return{chainBatches:[{chainId:t.destinationChainId,calls:[...d.calls,...r]}],solverFrontToken:c,solverFrontAmount:n,resolvedSwaps:{destinationSwap:d}}}case"source-swap":{const c=an(t.outputAsset.address,t.sourceChainId,t.destinationChainId);if(!c)throw new h.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 d=an(t.outputAsset.address,t.destinationChainId,t.destinationChainId);if(!d)throw new h.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 u=await l(t.sourceChainId,t.sourceAsset.address,c.address,n);return{chainBatches:[{chainId:t.sourceChainId,calls:u.calls},{chainId:t.destinationChainId,calls:r}],solverFrontToken:d,solverFrontAmount:u.amountOutMinimum,resolvedSwaps:{sourceSwap:u}}}case"intermediary":{if(!t.intermediaryAsset)throw new h.SpiceflowError("ROUTE_STRATEGY_ERROR","Intermediary strategy requires an intermediary asset but none was provided in the route plan.",{strategy:t.strategy});const c=an(t.intermediaryAsset.address,t.sourceChainId,t.destinationChainId);if(!c)throw new h.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 d=await l(t.sourceChainId,t.sourceAsset.address,c.address,n),u=await l(t.destinationChainId,t.intermediaryAsset.address,t.outputAsset.address,d.amountOutMinimum);return{chainBatches:[{chainId:t.sourceChainId,calls:d.calls},{chainId:t.destinationChainId,calls:[...u.calls,...r]}],solverFrontToken:t.intermediaryAsset,solverFrontAmount:d.amountOutMinimum,resolvedSwaps:{sourceSwap:d,destinationSwap:u}}}default:throw new h.SpiceflowError("ROUTE_STRATEGY_ERROR",`Unknown route strategy: ${t.strategy}`,{strategy:t.strategy})}}function yd(e,t,n){if(!e||!t)return null;if(e._source==="wallet")return e._fundingWallet!=="embedded"||t!==e.chainId?null:{address:e.address,symbol:e.symbol,name:e.name,decimals:e.decimals,logoURI:e.logoURI};const s=Bn(e,t),o=Object.entries(e.chainTokens??{}).flatMap(([f,m])=>{const g=sn(f);return g?.chainId===t?[{parsed:g,detail:m}]:[]}),r=f=>n.find(m=>h.addressesEqual(m.address,f))??null,i=f=>{const m=o.find(({parsed:x})=>h.addressesEqual(x.address,f));if(!m)return null;const g=h.getChainConfig(t);if(v.isNativeToken(f))return g?{address:v.ZERO_ADDRESS,symbol:g.nativeCurrency.symbol,name:g.nativeCurrency.name,decimals:g.nativeCurrency.decimals,logoURI:e.logoURI}:null;const y=g?.supportedTokens?.find(x=>h.addressesEqual(x.address,f));return!y||!so(e,f,t)?null:{address:m.parsed.address,symbol:y.symbol,name:y.name||m.detail?.name||e.displayName||e.name||e.symbol,decimals:y.decimals,logoURI:y.logo||e.logoURI}},l=o.map(({parsed:f})=>f.address).filter(v.isNativeToken);for(const f of[...s,...l]){if(v.isNativeToken(f)){const y=i(f);if(y)return y}const m=r(f);if(m)return m;const g=i(f);if(g)return g}if(e.chainTokens||e.receiptTokenId)return null;const c=zt(e,t);if(c){const f=r(c);if(f)return f}const d=an(e.address,t,e.chainId);return d?r(d.address)||(n.length>0?null:{address:d.address,symbol:d.symbol||e.symbol,name:e.displayName||e.name||e.symbol,decimals:d.decimals??e.decimals,logoURI:e.logoURI}):null}function wd(e){const t=e.find(n=>v.isSpicenetChainId(n.chainId))?.calls?.[0]?.data;if(!t)return null;try{const n=A.decodeFunctionData({abi:v.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 bd(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()===v.SPICE_GAS_FEE_RECIPIENT.toLowerCase()?Cn(n.amount,o.amount,100n):n.amount===o.amount})}function Cd(e,t){const n=e.intents.flatMap(r=>r.batches).filter(r=>{const i=Jt(r);return BigInt(r.quotedAmount)>0n||BigInt(r.totalDebit)>0n||i.totalFee>0n}),s=n.filter(r=>r.chainId===t),o=s.length>0?s:n;return o.length===1?o[0]:null}function vd(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const s=n.token.toLowerCase(),o=n.recipient.toLowerCase(),r=`${s}:${o}`,i=t.get(r);i?i.amount+=n.amount:t.set(r,{...n})}return[...t.values()]}function Ua(e,t){if(!e.token||!e.recipient||e.chainId===null)return null;const n=Cd(t,e.chainId);if(!n)return null;const{gasFee:s,bridgeFee:o,spicenetFee:r}=Jt(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:v.SPICE_GAS_FEE_RECIPIENT,amount:i}),r>0n&&l.push({token:e.token.address,recipient:v.SPICE_PLATFORM_FEE_RECIPIENT,amount:r}),vd(l)}function kd(e,t,n){const s=Ua(e,t);return!s||bd(wd(n),s)?null:e.buildWithdrawBatches(s)}async function Wa(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=>v.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),r=Ua(e,o);r&&(t=e.buildWithdrawBatches(r));const i=o.intents[0]?.batches.find(l=>l.chainId===e.chainId)??o.intents[0]?.batches[0]??null;i&&e.ui.setLockedGasFee(Jt(i).totalFee)}else{const o=(e.feeEstimate??await e.execution.estimate(t,n,0n,s)).intents[0]?.batches[0]??null;o&&e.ui.setLockedGasFee(Jt(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:r})=>kd(e,o,r)}:{...s,skipPreSubmitFeeEstimate:!0})}La(e)}catch(t){const n=t instanceof Error?t.message:"Withdraw failed";e.ui.setExecutionError(n)}finally{e.ui.setIsExecuting(!1)}}}function La(e){window.dispatchEvent(new CustomEvent("withdraw-completed")),e.onWithdrawSuccess?.({token:e.token?.symbol||"",amount:e.amount,chainId:e.chainId})}async function Sd(e){const t=e.executionContextRef.current;if(!t){e.ui.setExecutionProgress(null),await Wa(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 h.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 ca({actionId:t.actionId,intentIndex:t.intentIndex,intentId:t.intentId,stepIndex:s,chainId:e.chainId??void 0,onStatusMessage:(r,i)=>{e.isMountedRef.current&&e.ui.setExecutionProgress({step:"executing",message:r,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})}La(e)}catch(n){const s=n instanceof Error?n.message:"Withdraw failed";e.ui.setExecutionError(s)}finally{e.ui.setIsExecuting(!1)}}async function Id(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=>Jt(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:Jt(s).totalFee,feeEstimate:t}}function Oo(e,t){return A.formatUnits(e,t).replace(/(\.\d*?[1-9])0+$|\.0+$/,"$1")}function za(e,t,n){return Mt(e,t,n,"floor")}function qa(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 Ad(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 Ha(e,t,n){const s=n.filter(o=>o.amount>0n);return{chainId:e,domain:"evm",tokenTransfers:[],calls:v.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([v.SPICE_GAS_FEE_RECIPIENT,v.SPICE_PLATFORM_FEE_RECIPIENT].map(e=>e.toLowerCase()));function Ed(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),r=`${s.toLowerCase()}:${o.toLowerCase()}`,i=t.get(r);i?i.amount+=n.amount:t.set(r,{token:s,to:o,amount:n.amount})}return[...t.values()]}function Fd(e,t){return`0x${t}${e.slice(4)}`}function Va(e,t,n,s){if(e.some(u=>u.domain==="spicenet"))return e;const o=n?.intents.flatMap(u=>u.batches),r=u=>u.from==="escrow",i=e.map(u=>{const f=o?.find(F=>F.chainId===u.chainId);if(!f)return u;const m=Jt(f),g=m.totalFee;if(g<=0n)return u;const y=(u.tokenTransfers??[]).filter(F=>r(F)&&A.getAddress(F.to).toLowerCase()===t.toLowerCase()),x=y.find(F=>!v.isNativeToken(A.getAddress(F.token)))??y[0];if(!x)return u;const w=A.getAddress(x.token),C=v.isNativeToken(w);let b=!1;const I=(u.tokenTransfers??[]).map(F=>b||!r(F)||A.getAddress(F.to).toLowerCase()!==t.toLowerCase()||A.getAddress(F.token).toLowerCase()!==w.toLowerCase()?F:(b=!0,{...F,amount:s?.payoutAlreadyGross?BigInt(F.amount):BigInt(F.amount)+g}));if(!b)return u;const S=(F,T)=>C?{to:F,value:T,data:"0x"}:{to:w,value:0n,data:A.encodeFunctionData({abi:A.erc20Abi,functionName:"transfer",args:[F,T]})},k=[];m.spicenetFee>0n&&k.push(S(v.SPICE_PLATFORM_FEE_RECIPIENT,m.spicenetFee));const E=m.gasFee+m.bridgeFee;return E>0n&&k.push(S(v.SPICE_GAS_FEE_RECIPIENT,E)),{...u,tokenTransfers:I,calls:[...k,...u.calls]}}),l=i.flatMap(u=>(u.tokenTransfers??[]).filter(r).map(f=>{const m=A.getAddress(f.token),g=A.getAddress(f.to),y=[{token:m,to:g,amount:BigInt(f.amount)}];return{chainId:u.chainId,transfers:Ed(y)}}));if(l.length===0)return e;const c=s?.requestTimestampMs??Date.now(),d=BigInt(Math.floor(c/1e3))+3600n;return[{chainId:v.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:l.map((u,f)=>{const m=A.keccak256(A.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,u.transfers[0].token,u.transfers.reduce((y,x)=>y+x.amount,0n),BigInt(u.chainId),BigInt(c+f)])),g=Fd(m,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:A.encodeFunctionData({abi:v.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${u.chainId}`,idempotenceKey:g,nbf:0n,exp:d,metadata:"{}",transfers:u.transfers.map(y=>({token:y.token.toLowerCase(),to:y.to,amount:y.amount}))}]})}})},...i]}function kn(e,t,n,s){const o=e.filter(i=>i.domain!=="spicenet"),r=i=>(i.tokenTransfers??[]).some(l=>l.from==="escrow");return[...o.filter(i=>!r(i)),...Va(o.filter(r),t,n,s)]}class es extends Error{constructor(t,n){super("The selected balance cannot cover the fee funding amount"),this.requiredAmount=t,this.balance=n,this.name="InsufficientFeeFundingBalanceError"}}function No(e,t,n,s,o){const r=e[e.length-1];if(!r?.calls.length||r.domain==="spicenet")throw new Error("Proceeds fees require a final destination action");const i=[{to:v.SPICE_PLATFORM_FEE_RECIPIENT,amount:o},{to:v.SPICE_GAS_FEE_RECIPIENT,amount:s}].filter(l=>l.amount>0n);return e.map(l=>l===r?{...l,calls:[...l.calls,...i.map(c=>({to:n,value:0n,data:A.encodeFunctionData({abi:A.erc20Abi,functionName:"transfer",args:[c.to,c.amount]})}))],tokenTransfers:[...l.tokenTransfers??[],...i.map(c=>({from:t,to:c.to,token:n,amount:c.amount}))]}:l)}async function Qa(e,t,n,s,o){const r=v.hashChainBatches(e),i=await h.relayerService.estimateBatchGas({user:t,outputToken:n,signal:s,requireSimulation:!0,includePlatformFee:o!==void 0,chainBatches:e.map((l,c)=>({...l,hash:r[c].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 Ga(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?.preview)throw new Error("Action fee quote is unavailable");let s=n.preview.gasFee;const o=n.preview.spicenetFee,r=n.preview.bridgeFee??0n;for(let i=0;i<5;i++){const l=s+o+r,c=t<l?t:l,d=l-c;if(d>0n&&e.fundShortfall===!1)throw new es(l,t);const u=d>0n?(d*110n+99n)/100n+2n:0n;let f=u,m;const g=kn(await e.buildBatches(u,{actionAmountOverride:e.actionAmountFor?.(l),onSourceSpend:w=>{f=w},onActionCalls:w=>{m=w}}),e.owner),y=No(g,e.owner,e.token,s+r,o),x=await Qa(y,e.owner,e.token,e.signal);if(x===s)return{preview:{...n.preview,grossAmount:u,netAmount:0n,gasFee:s,totalFee:l,gasQuoteSource:"estimated"},feeEstimate:n.feeEstimate,grossFundingAmount:u,proceedsAvailable:t,proceedsUsed:c,fundingBatches:y,sourceSpendCap:f,destinationAmount:0n,actionDefinition:m};s=x}throw new Error("Action proceeds fee estimate did not converge")}function Ka(e,t){let n,s;if(v.isNativeToken(t)){if(e.data!=="0x")return null;n=e.to,s=e.value}else{if(!h.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 h.addressesEqual(n,v.SPICE_GAS_FEE_RECIPIENT)?{gas:s,platform:0n}:h.addressesEqual(n,v.SPICE_PLATFORM_FEE_RECIPIENT)?{gas:0n,platform:s}:null}async function Td(e,t,n){const s=h.getClientForChain(e);return v.isNativeToken(n)?s.getBalance({address:t}):s.readContract({address:n,abi:A.erc20Abi,functionName:"balanceOf",args:[t]})}function Rs(e,t,n){return e.map(s=>s.chainId===t?{...s,calls:s.calls.filter(o=>!Ka(o,n))}:s)}function jd(e,t,n){if(!e.feeOnlyAction)return{};const s=e.embeddedWalletAddress??e.providerEmbeddedAddress,o=e.feeQuote?.fundingSource,r=o&&o.kind!=="proceeds"?void 0:e.actionProceeds,i=o&&(o.kind==="input"||o.kind==="balance"&&o.asset?._source==="wallet")?o:void 0;if(r||e.feeQuote?.fundingConversion||i){const u=e.feeQuote?.fundingConversion,f=r??{token:t,resolve:async()=>0n},m=e.feeQuote?.preview,g=e.feeQuote?.proceedsUsed,y=u?.fromProceeds?u.tokenIn:t;if(!m||g===void 0||!i&&f.token.toLowerCase()!==y.toLowerCase())throw new Error("Refresh the action proceeds quote");const x=m.gasFee+(m.bridgeFee??0n),w=m.spicenetFee,C=i?async()=>{e.validateFeeQuote?.();const I=await Td(e.resolvedChainId,s,i.token);e.validateFeeQuote?.();const S=i.kind==="input"?i.amount:u?.amountInMax??g;if(e.signal?.aborted||I<S||u&&u.amountOut<x+w)throw new Error("The fee funding balance changed; refresh before retrying");return u?[{chainId:e.resolvedChainId,token:t,amount:u.amountOut}]:[]}:async()=>{e.validateFeeQuote?.();const I=await f.resolve(e.signal);if(e.validateFeeQuote?.(),e.signal?.aborted||(u?.fromProceeds?I<u.amountInMax||u.amountOut<x+w:I<g||I+(u?.amountOut??n)<x+w))throw new Error("Action proceeds changed; refresh before retrying");return u?.fromProceeds?[{chainId:e.resolvedChainId,token:u.tokenIn,amount:u.amountInMax},{chainId:e.resolvedChainId,token:t,amount:u.amountOut}]:[{chainId:e.resolvedChainId,token:t,amount:g+(u?.amountOut??0n)}]},b=async I=>{await C();const S=await Qa(I,s,t,e.signal,u?w:void 0);if(await C(),(S>m.gasFee?S-m.gasFee:m.gasFee-S)*100n>S*15n)throw new Error("Action gas quote changed; refresh before retrying")};return{resolveActionOutputCredits:C,prepareForSigning:async I=>{const S=Rs(I,e.resolvedChainId,t).map(E=>({...E,tokenTransfers:E.tokenTransfers?.filter(F=>!(typeof F.from=="string"&&h.addressesEqual(F.from,s)&&(h.addressesEqual(F.to,v.SPICE_GAS_FEE_RECIPIENT)||h.addressesEqual(F.to,v.SPICE_PLATFORM_FEE_RECIPIENT))))})),k=No(S,s,t,x,w);return await b(k),k},validateBeforeSubmit:b}}const l=v.getTokenByAddress(t,e.resolvedChainId),c={chainId:e.resolvedChainId,tokenAddress:t,symbol:l?.symbol??e.destinationToken.symbol,decimals:e.executionTokenDecimals??l?.decimals??e.destinationToken.decimals},d=async u=>{e.validateFeeQuote?.();const f=Rs(u,e.resolvedChainId,t),m=await e.execution.estimate(f,t,n,{userOverride:s,useCustomTransfers:!0,feeExecutionMode:"backend-transfer"});e.validateFeeQuote?.();const g=hn(m,c);if(!g||g.chainId!==e.resolvedChainId)throw new Error("The fee service did not return the destination action's fee quote");if(g.gasFee+g.spicenetFee+(g.bridgeFee??0n)+2n>n)throw new Error("Fees exceed the displayed maximum funding; refresh the quote before retrying");return{raw:f,feeEstimate:m,fees:g}};return{prepareForSigning:async u=>{const{raw:f,feeEstimate:m}=await d(u);return kn(f,s,m,{payoutAlreadyGross:!0})},validateBeforeSubmit:async u=>{const{fees:f}=await d(u);let m=0n,g=0n;for(const x of u)if(x.chainId===e.resolvedChainId)for(const w of x.calls){const C=Ka(w,t);C&&(m+=C.gas,g+=C.platform)}if(m+g+2n>n)throw new Error("Signed fees exceed the displayed maximum funding");const y=f.gasFee+(f.bridgeFee??0n);if((m>y?m-y:y-m)*100n>y*15n||g!==f.spicenetFee)throw new Error("The signed gas quote changed materially; refresh before retrying")}}}const Bd="0xa9059cbb";function ts(e,t,n){return v.isNativeToken(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:A.encodeFunctionData({abi:A.erc20Abi,functionName:"transfer",args:[n,t]})}}function Za(e,t,n){return{chainId:n,calls:[ts(e,t,v.getEscrowContractAddress(n))]}}function Rd(e,t,n,s){const o=t.source.chainId;return{chainId:o,calls:[...e.calls,ts(t.source.address,n,v.getEscrowContractAddress(o)),...s>0n?[ts(t.source.address,s,v.SPICE_GAS_FEE_RECIPIENT)]:[]]}}function Ya(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 Xa(e,t,n){return e?.asset?._source==="wallet"&&e?.asset.chainId===n}function Ja(e){return e.isNative||v.isNativeToken(e.address)?!0:!v.getTokenByAddress(e.address,e.chainId)}function $a(e,t,n,s){return t!=="user-transfer"||!n||e.length===0||e[0]?.to.toLowerCase()!==s.toLowerCase()||!e[0]?.data.startsWith(Bd)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function ns(e,t,n,s){if(!t)return[e];const o=await t({...n,requestTimestampMs:s});return o?[o,e]:[e]}function Dd(e){return e.filter(t=>t.domain!=="spicenet")}function ss(e,t){const n=(e.tokenTransfers??[]).filter(s=>s.from==="escrow").map(s=>({token:v.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 Mn(e,t,n){return Mt(e,t,n,"ceil")}function _a(e){const t=e.selectedAsset?.asset;return e.isPayMode&&!!t&&t._source==="wallet"&&t.chainId!==e.resolvedChainId&&!!e.pivot}function Mo(e){const t=e.selectedAsset?.asset;return!e.isPayMode&&!!t&&t._source==="wallet"&&t.chainId!==e.resolvedChainId&&!!e.sourceSwap&&!!e.pivot}function Ds(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 ei(e,t,n){let s;const o=await e({...t,buildActionCalls:async(r,i)=>{s=r;const l=await t.buildActionCalls(r,i);return n?.onActionCalls?.({amount:r,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 Po=(e,t)=>ei(Od,e,t),Os=async(e,t)=>{const n=await ei(Nd,e,t),s=t?.actionContextOverride?.feeBreakdown,o=n[n.length-1];if(e.feeExecutionMode!=="user-transfer"||!s||!o)return n;const r=e.needsSwap&&e.resolvedTokenIn?e.resolvedTokenIn:e.destinationToken.address,[i]=Rs([o],e.resolvedChainId,r),l=Ha(e.resolvedChainId,r,[{recipient:v.SPICE_PLATFORM_FEE_RECIPIENT,amount:s.spicenetFee},{recipient:v.SPICE_GAS_FEE_RECIPIENT,amount:s.gasFee+(s.bridgeFee??0n)}]).calls,c=o.calls.filter(d=>!i.calls.includes(d));return c.length===l.length&&l.every(d=>c.some(u=>u.to.toLowerCase()===d.to.toLowerCase()&&u.value===d.value&&u.data===d.data))?n:[...n.slice(0,-1),{...i,calls:[...l,...i.calls]}]};async function Od(e,t){const{currentPaymentAmount:n,destinationToken:s,embeddedWalletAddress:o,providerEmbeddedAddress:r,address:i,isNon7702:l,resolvedChainId:c,buildActionCalls:d,feeExecutionMode:u,buildSpicenetBatch:f,needsSwap:m,exactOutputSwap:g,resolvedTokenIn:y,requestTimestampMs:x}=e,w=t?.sourceAssetOverride?{asset:t.sourceAssetOverride}:e.selectedAsset,C=t?.fundingTokenOverride??y,b=Pt(n,s.decimals),I=t?.actionAmountOverride??(e.feeOnlyAction?0n:b),S=!!e.feeOnlyAction&&(t?.fundingAmountOverride??0n)>0n,k=o||r||i;if(!k)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const E={userAddress:e.recipient??k,executorAddress:k,beneficiary:e.recipient??k,outputRecipient:m?k:void 0,chainId:c,destinationToken:s.address,grossAmount:t?.fundingAmountOverride??b,netAmount:I,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:u,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},F=await d(I,E),T={chainId:c,calls:F},D=!!w&&w.asset._source!=="wallet",j=Xa(w??null,l,c),U=D||j&&!!w&&!Ja(w.asset),P=(q,R)=>({token:v.normalizeNativeTokenAddress(q),from:"escrow",to:k,amount:R}),O=(q,R,W)=>j?[Za(q,R,c),...W]:W;if(b===0n&&!S)return[T];if(w?.asset._source==="wallet"&&w.asset.chainId!==c&&!e.pivot)throw new Error("A current source-to-destination funding route is required");if(e.feeOnlyAction&&t?.fundingTokenOverride&&j)return Ds(t.fundingAmountOverride??0n,t),[T];if(_a(e)){if(m&&!g)throw new Error("Swap quote not available yet");const q=t?.fundingAmountOverride??(g?g.amountInMax:b),R=t?.sourceGasSkimOverride??0n,W=Mt(q,e.pivot.destination.decimals,e.pivot.source.decimals,"ceil"),K=W+R,G=e.sourceExactOutputSwap,_=G&&(t?.reuseQuotedSourceSwap||G.amountOut>=K)?G:e.resolveSourceExactOutputSwap?await e.resolveSourceExactOutputSwap(K):null;if(!_)throw new Error("Swap quote not available yet");Ds(_.amountInMax,t);const X=w.asset;if(_.amountInMax>X.balance)throw new Error(`Insufficient ${X.symbol} for this payment. Required ${A.formatUnits(_.amountInMax,X.decimals)} ${X.symbol}; available ${A.formatUnits(X.balance,X.decimals)} ${X.symbol}.`);const Q=_.amountOut>=K?W:_.amountOut-R;if(Q<=0n)throw new Error("Amount is too small to cover fees. Increase the amount and retry.");const te={chainId:e.pivot.source.chainId,calls:[..._.calls,ts(e.pivot.source.address,Q,v.getEscrowContractAddress(e.pivot.source.chainId)),...R>0n?[ts(e.pivot.source.address,R,v.SPICE_GAS_FEE_RECIPIENT)]:[]]},B={chainId:c,calls:[...g?.calls??[],...F],tokenTransfers:[P(e.pivot.destination.address,q),...T.tokenTransfers??[]]},$=await ns(B,f,{userAddress:k,destinationChainId:c,deliveryToken:e.pivot.destination.address,deliveryAmount:q,deliveryRecipient:k,deliveryTransfers:ss(B),sourceAsset:w.asset},x);return[te,...$]}if(w){const q=t?.fundingAmountOverride??g?.amountInMax??b;Ds(Mn(q,await fn(w.asset,C??w.asset.address,c,s),w.asset.decimals),t)}if(m&&g){const q=C??zt(w.asset,c)??w.asset.address,R=t?.fundingAmountOverride??g.amountInMax,W=U?[P(q,R)]:[],K={chainId:c,calls:[...g.calls,...F],tokenTransfers:[...W,...T.tokenTransfers??[]]};if(!U)return[K];const G=await ns(K,f,{userAddress:k,destinationChainId:c,deliveryToken:q,deliveryAmount:R,deliveryRecipient:k,deliveryTransfers:ss(K),sourceAsset:w.asset},x);return O(q,R,G)}if(U){const q=C??zt(w.asset,c)??s.address;if(j&&!e.feeOnlyAction&&q.toLowerCase()===s.address.toLowerCase())return[T];const R=t?.fundingAmountOverride??b,W={...T,tokenTransfers:[P(q,R),...T.tokenTransfers??[]]},K=await ns(W,f,{userAddress:k,destinationChainId:c,deliveryToken:q,deliveryAmount:R,deliveryRecipient:k,deliveryTransfers:ss(W),sourceAsset:w.asset},x);return O(q,R,K)}return[T]}async function Nd(e,t){const{selectedAsset:n,embeddedWalletAddress:s,recipient:o,resolvedChainId:r,destinationToken:i,buildActionCalls:l,feeExecutionMode:c,buildSpicenetBatch:d,isPayMode:u,isNon7702:f,needsSwap:m,resolvedSwap:g,quoteAmountOut:y,resolvedTokenIn:x,requestTimestampMs:w}=e;if(!n?.asset||!s)return[];const C=o??s;if(!C)return[];const b=Mo(e);let I=e.sourceSwap,S=Pt(n.amount,n.asset.decimals),k=b?e.sourceSwap.amountOutMinimum:null;if(b&&e.isFeeInclusiveInput&&(k=Ya(e.sourceSwap,t?.sourceGasSkimOverride??0n)),b&&!e.isFeeInclusiveInput&&(t?.fundingAmountOverride!==void 0||(t?.sourceGasSkimOverride??0n)>0n)){k=t?.fundingAmountOverride!==void 0?Mn(t.fundingAmountOverride,e.pivot.destination.decimals,e.pivot.source.decimals):e.sourceSwap.amountOutMinimum;const L=k+(t?.sourceGasSkimOverride??0n);if(!e.resolveSourceExactOutputSwap)throw new Error("The source quote cannot include fees yet.");const H=await e.resolveSourceExactOutputSwap(L);if(H.amountOut<L)throw new Error("The source quote does not cover the accepted funding amount.");S=H.amountInMax,I={...H,amountOutMinimum:H.amountOut}}const E=b?e.pivot.destination.address:x??zt(n.asset,r)??i.address,F=b?e.pivot.destination.decimals:await fn(n.asset,E,r,i),T=t?.fundingAmountOverride??t?.actionAmountOverride??(b?Mt(k,e.pivot.source.decimals,F,"floor"):Bs(Pt(n.amount,n.asset.decimals),n.asset.decimals,F)),D=t?.fundingAmountOverride??T,j=t?.sourceFundingAmountOverride??Mn(T,F,n.asset.decimals);Ds(b?S:j,t);const U=t?.deliveryAmountOverride??(c==="user-transfer"?D:t?.actionContextOverride?.netAmount??D),P=t?.withdrawalAmountOverride??D,O=t?.actionAmountOverride??t?.actionContextOverride?.netAmount??T;let q=g;if(m&&!u&&(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 L=t?.actionContextOverride?.netAmount??O;(!q||e.swapInputAmount!==L)&&(q=await e.resolveInputSwap(L,g??void 0))}q&&t?.onSwap?.(q,t?.actionContextOverride?.netAmount??e.swapInputAmount??O);const R=q?.amountOutMinimum??y,W={userAddress:C,executorAddress:s,beneficiary:C,outputRecipient:m?s:void 0,chainId:r,destinationToken:i.address,feeToken:c==="user-transfer"&&m&&x?x:i.address,grossAmount:D,netAmount:O,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:c,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},K=await l(O,W),G=n.asset?._source==="wallet";if(!u&&G&&n.asset.chainId===r&&Ja(n.asset)){if(m){if(!x)throw new Error("Swap input token could not be resolved");if(!q||R===null)throw new Error("Swap quote not available yet")}if(m&&q&&R){const L=await l(t?.actionAmountOverride??R,{...W,netAmount:t?.actionAmountOverride??R}),{feeCall:H,remainingCalls:fe}=$a(L,c,m,W.feeToken);return[{chainId:r,calls:[...H?[H]:[],...q.calls,...fe]}]}return[{chainId:r,calls:K}]}if(!u&&G&&n.asset.chainId!==r&&!b)throw new Error("A current source-to-destination funding route is required");const _=n.asset._source!=="wallet",X=Xa(n,f,r);if(!(_||X||b))return[{chainId:r,calls:K}];const Q=b?Rd(I,e.pivot,k,t?.sourceGasSkimOverride??0n):X?Za(x??v.normalizeNativeTokenAddress(n.asset.address),j,r):null,te=(L,H)=>({token:v.normalizeNativeTokenAddress(L),from:"escrow",to:s,amount:H});if(m){if(!x)throw new Error("Swap input token could not be resolved");if(!q||R===null)throw new Error("Swap quote not available yet")}if(m&&q&&R&&x){const L=await l(t?.actionAmountOverride??R,{...W,netAmount:t?.actionAmountOverride??R}),{feeCall:H,remainingCalls:fe}=$a(L,c,m,W.feeToken),Z={chainId:r,calls:[...H?[H]:[],...q.calls,...fe],tokenTransfers:[te(x,U)]},he=await ns(Z,d,{userAddress:s,destinationChainId:r,deliveryToken:x,deliveryAmount:U,withdrawalAmount:P,deliveryRecipient:s,deliveryTransfers:ss(Z,P),sourceAsset:n.asset},w);return Q?[Q,...he]:he}const B=x??zt(n.asset,r)??i.address,$={chainId:r,calls:K,tokenTransfers:[te(B,U)]},ie=await ns($,d,{userAddress:s,destinationChainId:r,deliveryToken:B,deliveryAmount:U,withdrawalAmount:P,deliveryRecipient:s,deliveryTransfers:ss($,P),sourceAsset:n.asset},w);return Q?[Q,...ie]:ie}async function Md(e,t,n,s,o){let r=e;for(let i=0;i<4;i++){const l=await t(r),c=await s(l,n,r,o),d=Pc(c);if(d===null||d>=e)return r;const u=r-d,f=e+u;if(f<=r)return r;r=f}return r}function Pd(e){return{...e,resolve:async(t,n,s)=>{const o=await e.resolve(t,n,s),r=o?.calls[0]?.to;return!o||!r||v.isNativeToken(t.tokenIn)?o:{...o,calls:[{to:t.tokenIn,value:0n,data:A.encodeFunctionData({abi:A.erc20Abi,functionName:"approve",args:[r,o.amountInMax]})},...o.calls]}}}}function Ns(e){const t=(e?.customVenues??[]).map(s=>_i(Pd(s),e?.executorAddress));async function n(s,o,r){const i=t.filter(d=>d.chainIds.includes(o));if(i.length===0)throw new h.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 d=>({venue:d,quote:await d.resolve(s,o,r)})))).filter(d=>d.status==="fulfilled").map(d=>d.value).filter(d=>d.quote!==null);if(l.length===0)throw new h.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 c=l.find(d=>d.venue.preferred);return c?c.quote:(l.sort((d,u)=>d.quote.amountIn<u.quote.amountIn?-1:d.quote.amountIn>u.quote.amountIn?1:0),l[0].quote)}return{getQuote:n,venues:t}}function ti(e,t,n){if(e._source==="wallet")return e.chainId===t?e.address:null;const s=Bn(e,t);return s.find(o=>o.toLowerCase()===n.toLowerCase())??s[0]??null}async function ni(e,t,n,s){const o=v.hashChainBatches(s),r=await h.relayerService.estimateBatchGas({user:t,outputToken:n,requireSimulation:!0,includePlatformFee:!0,signal:e.signal,chainBatches:s.map((i,l)=>({...i,hash:o[l].hash}))});if(!r.simulationVerified||r.gasQuoteSource!=="estimated"||r.platformFee===void 0||r.gasFee<=0n)throw new Error("Fee funding requires verified gas and platform pricing");return r}async function os(e,t){const n=e.selectedAsset?.asset,s=!t&&!!e.actionProceeds&&e.actionProceeds.token.toLowerCase()!==e.destinationToken.address.toLowerCase(),o=!!t||s,r=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!r||!o&&(!n||n._source!=="spice"&&!(n._source==="wallet"&&n.chainId===e.resolvedChainId)))throw new Error("A local embedded or Spice balance is required for fee conversion");const i=t?t.token:s?e.actionProceeds.token:ti(n,e.resolvedChainId,e.destinationToken.address);if(!i)throw new Error("This receipt has no registered destination withdrawal token");const l=v.getTokenByAddress(i,e.resolvedChainId)?.decimals??(v.isNativeToken(i)?18:o?await h.getClientForChain(e.resolvedChainId).readContract({address:i,abi:A.erc20Abi,functionName:"decimals"}):n?._source==="wallet"?n.decimals:void 0);if(l===void 0)throw new Error("Fee funding token metadata is unavailable");const c=e.destinationToken.address;if(e.actionProceeds&&!s&&e.actionProceeds.token.toLowerCase()!==c.toLowerCase())throw new Error("Action proceeds must use the destination fee token");const d=t?t.amount:e.actionProceeds?await e.actionProceeds.resolve(e.signal):0n;if(d<0n||e.signal?.aborted)throw new Error("Action proceeds quote was cancelled or invalid");const u=Ns({customVenues:[...e.resolveExactOutputSwap?[{name:"consumer-exact-output",chainIds:[e.resolvedChainId],preferred:!0,resolve:e.resolveExactOutputSwap}]:[],...jn(e.liquidityVenues).output]}),f=g=>ni(e,r,c,g);let m=await f(await e.buildPayChainBatches({fundingAmountOverride:0n}));for(let g=0;g<8;g++){const y=m.gasFee+m.platformFee,x=o?0n:d<y?d:y,w=y-x,C=w>0n?(w*110n+99n)/100n+2n:0n,b=C>0n?await u.getQuote({tokenIn:i,tokenOut:c,amountOut:C,maxSlippage:e.maxSlippage},e.resolvedChainId,r):null;if(e.signal?.aborted)throw new Error("Fee conversion quote was cancelled");if(b&&(b.amountOut!==C||b.amountInMax<=0n||b.amountInMax<b.amountIn||!b.calls.length))throw new Error("Invalid exact-output fee conversion quote");const I=b?.amountInMax??0n,S=o?0n:Mn(I,l,n.decimals);if(o&&I>d)throw new es(I,d);if(!o&&S>n.balance)throw new es(S,n.balance);let k,E=kn(await e.buildPayChainBatches({fundingAmountOverride:o?0n:I,...o?{}:{fundingTokenOverride:i},...t?{actionAmountOverride:t.amount-I}:{},onActionCalls:T=>{k=T}}),r);if(b){const T=E.length-1;E=E.map((D,j)=>j===T?{...D,calls:[...D.calls,...b.calls]}:D)}E=No(E,r,c,m.gasFee,m.platformFee);const F=await f(E);if(F.gasFee<=m.gasFee&&(m.gasFee-F.gasFee)*100n<=F.gasFee*15n&&F.platformFee===m.platformFee){const T={tokenIn:i,tokenOut:c,amountInMax:I,amountOut:C,sourceAmountMax:S,...s?{fromProceeds:!0}:{},...t?{fromInput:!0}:{}};return{feeEstimate:null,preview:{symbol:e.destinationToken.symbol,decimals:e.destinationToken.decimals,grossAmount:o?0n:C,netAmount:0n,gasFee:m.gasFee,spicenetFee:m.platformFee,totalFee:y,gasQuoteSource:"estimated"},grossFundingAmount:o?0n:I,proceedsAvailable:d,proceedsUsed:o?y:x,fundingConversion:T,fundingBatches:E,sourceSpendCap:S,destinationAmount:0n,actionDefinition:k}}m=F}throw new Error("Fee conversion pricing did not converge")}const Ud=["input","proceeds","balance"];function Wd(e){const t=c=>h.addressesEqual(c,e.feeToken),n=(c,d)=>Number(c.swap)-Number(d.swap),s={input:[],proceeds:[],balance:[]};for(const c of e.inputs??[])c.amount>0n&&s.input.push({kind:"input",...c,swap:!t(c.token)});s.input.sort(n),e.proceeds&&e.proceeds.amount>0n&&s.proceeds.push({kind:"proceeds",...e.proceeds,swap:!t(e.proceeds.token)});const o=(c,d)=>d.balanceUsd-c.balanceUsd,r=e.balances.filter(c=>c._source==="wallet"&&c.chainId===e.chainId&&c.location!=="external").sort(o),i=e.balances.filter(c=>c._source==="spice").sort(o),l=c=>{const d=[];for(const u of c){if(u.balance<=0n)continue;const f=ti(u,e.chainId,e.feeToken);f&&(e.inputs?.some(m=>h.addressesEqual(m.token,f))||d.push({kind:"balance",token:f,amount:u.balance,asset:u,swap:!t(f)}))}return d.sort(n)};return s.balance=[...l(r),...l(i)],(e.order??Ud).flatMap(c=>s[c])}function Ld(e){return e instanceof es||e instanceof h.SpiceflowError&&e.code==="NO_SWAP_ROUTE"}async function zd(e,t){const n=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!n||!e.ready||!e.authenticated)return null;const s=e.destinationToken.address,o=e.actionProceeds?{token:e.actionProceeds.token,amount:await e.actionProceeds.resolve(e.signal)}:void 0;if(e.signal?.aborted)throw new Error("Fee funding quote was cancelled");if(o&&o.amount<0n)throw new Error("Action proceeds cannot be negative");const r=Wd({feeToken:s,chainId:e.resolvedChainId,inputs:e.actionInput,proceeds:o,balances:e.feeFundingBalances??[],order:e.feeFunding});let i;const l=()=>i??(i=(async()=>{const f=await ni(e,n,s,await e.buildPayChainBatches({fundingAmountOverride:0n}));return{feeEstimate:null,preview:{symbol:e.destinationToken.symbol,decimals:e.destinationToken.decimals,gasFee:f.gasFee,spicenetFee:f.platformFee,bridgeFee:0n,totalFee:f.gasFee+f.platformFee,grossAmount:0n,netAmount:0n,gasQuoteSource:"estimated"}}})()),c=(f,m)=>e.buildPayChainBatches({...m,fundingAmountOverride:f}),d=(f,m)=>Ga({proceeds:{token:s,resolve:async()=>f},owner:n,token:s,signal:e.signal,baseline:l,buildBatches:c,fundShortfall:!1,actionAmountFor:m}),u=async f=>{if(f.kind==="input")return f.swap?os({...e,actionProceeds:void 0},f):d(f.amount,x=>f.amount-x);if(f.kind==="proceeds"){const x={...e.actionProceeds,resolve:async()=>o.amount};return f.swap?os({...e,actionProceeds:x}):d(f.amount)}const m=f.asset;if(m._source==="wallet"&&!f.swap)return d(m.balance);const g={...e,selectedAsset:{asset:m,amount:"0"},resolvedTokenIn:f.token,actionInput:void 0,actionProceeds:void 0,buildPayChainBatches:x=>e.buildPayChainBatches({...x,sourceAssetOverride:m,fundingTokenOverride:x?.fundingTokenOverride??f.token})};if(f.swap)return os(g);const y=await t(g);if(y&&(y.sourceSpendCap??0n)>m.balance)throw new es(y.sourceSpendCap,m.balance);return y};for(const f of r)try{const m=await u(f);if(!m)continue;const{swap:g,...y}=f;return{...m,fundingSource:y}}catch(m){if(e.signal?.aborted||!Ld(m))throw m}throw new Error(`No available balance can cover this action's ${e.destinationToken.symbol} execution cost`)}async function qd(e){const t=e.selectedAsset.asset;if(t.chainId!==e.destinationToken.chainId||!h.addressesEqual(v.normalizeNativeTokenAddress(t.address),v.normalizeNativeTokenAddress(e.destinationToken.address)))throw new Error("Direct execution requires the destination token on its own chain.");if(t.decimals!==e.destinationToken.decimals)throw new Error("Source and destination token decimals do not match.");const n=Pt(e.paymentAmount??e.selectedAsset.amount,t.decimals);if(n<=0n)throw new Error("Enter a positive action amount.");const s={userAddress:e.beneficiary??e.account,executorAddress:e.account,beneficiary:e.beneficiary??e.account,chainId:e.destinationToken.chainId,destinationToken:e.destinationToken.address,feeToken:t.address,grossAmount:n,netAmount:n,combinedFeeAmount:0n,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:0n,gasFee:0n,bridgeFee:0n}},o=await e.buildActionCalls(n,s);if(!o.length)throw new Error("No action calls configured.");if(v.isNativeToken(t.address)&&o.reduce((r,i)=>r+i.value,0n)>n)throw new Error("The native action exceeds the accepted source amount.");return{actionDefinition:{amount:n,context:s,calls:o},actionContext:s,batches:[{chainId:s.chainId,calls:o}],fundingAmount:n,sourceSpendCap:n,destinationAmount:n,feeEstimate:null,preview:{symbol:t.symbol,decimals:t.decimals,grossAmount:n,netAmount:n,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}}}async function Uo(e){const[t]=await e.buildSupplyChainBatches({sourceGasSkimOverride:1n,reuseQuotedSourceSwap:!0});if(!t)throw new Error("Swap quote not available yet");const{gasFee:n}=await h.relayerService.estimateBatchGas({user:e.user,outputToken:e.pivot.source.address,stepIndex:0,chainBatches:[t],signal:e.signal});return n}const si=(e,t)=>(e+t-1n)/t;function oi(e,t){return e.intents.length===0?t:{...e,intents:e.intents.map(n=>({...n,batches:n.batches.map(s=>{const o=t.intents.find(l=>l.intentIndex===n.intentIndex)?.batches.find(l=>l.chainId===s.chainId);if(!o)return s;const r={...s.feeBreakdown};let i=0n;for(const l of["gasFee","bridgeFee"]){const c=BigInt(r[l]??"0"),d=BigInt(o.feeBreakdown[l]??"0");d>c&&(r[l]=d.toString(),i+=d-c)}return{...s,feeBreakdown:r,totalDebit:(BigInt(s.totalDebit)+i).toString()}})}))}}function Hd(e,t){const n=e.spicenetFee+(e.bridgeFee??0n);return e.grossAmount<=n?t+e.gasFee+n:si((t+e.gasFee)*e.grossAmount,e.grossAmount-n)+2n}async function ri(e){const{requiredNetFunding:t}=e;if(e.feeOnlyAction){const d=e.executionOptions?.userOverride;if(!d||t!==0n)throw new Error("Fee-only estimates require a zero action amount and its embedded executor");let u=1n,f;for(let m=0;m<8;m++){const g=kn(await e.buildBatches(u),d,f,{payoutAlreadyGross:!0}),y=await e.estimate(Rs(g,e.tokenDescriptor.chainId,e.fundingToken),e.fundingToken,u,{...e.executionOptions,feeExecutionMode:"backend-transfer"}),x=hn(y,e.tokenDescriptor);if(!x)throw new Error("The fee service did not return a fee quote for this action");const w=x.gasFee+x.spicenetFee+(x.bridgeFee??0n);if(f&&w+2n<=u)return{preview:{...x,grossAmount:u,netAmount:0n},feeEstimate:y,grossFundingAmount:u};u=(w*110n+99n)/100n+2n,f=y}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=hn(s,e.tokenDescriptor);if(!o)return{preview:Ss(n,e.tokenDescriptor,t),feeEstimate:s,grossFundingAmount:t};const r=Hd(o,t),i=d=>o.grossAmount>0n?si(d*r,o.grossAmount):d,l=i(o.spicenetFee),c=i(o.bridgeFee??0n);return{preview:{...o,grossAmount:r,netAmount:t,spicenetFee:l,bridgeFee:c,totalFee:o.gasFee+l+c},feeEstimate:s,grossFundingAmount:r}}async function ai(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 Xn(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 Vd(e){if(e.isPayMode||e.needsSwap||e.isQuoting||e.pivot||!e.embeddedWalletAddress)return null;const t=e.asset,n=v.getTokenByAddress(e.executionTokenAddress,t.chainId);return!n||t.balance<=0n?null:ai({balance:t.balance,decimals:t.decimals,planForAmount:s=>Pn({selectedAsset:{asset:t,amount:Xn(s,t.decimals)},isPayMode:!1,isNon7702:!1,isFeeInclusiveInput:!1,parsedAmount:Number(Xn(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 Pn(e){const{signal:t,selectedAsset:n,isPayMode:s,isFeeInclusiveInput:o=!1,parsedAmount:r,needsSwap:i,exactOutputSwap:l,isNon7702:c,currentPaymentAmount:d,destinationToken:u,feeExecutionMode:f,resolvedTokenIn:m,embeddedWalletAddress:g,providerEmbeddedAddress:y,resolvedChainId:x,isConnected:w,address:C,ready:b,authenticated:I,isDirect:S,resolvedSwap:k,sourceSwap:E,pivot:F,isQuoting:T,executionTokenAddress:D,buildPayChainBatches:j,buildSupplyChainBatches:U,estimate:P}=e;if(e.feeOnlyAction&&!n&&e.feeFunding?.length!==0)return zd(e,Pn);if(e.feeOnlyAction&&e.actionProceeds&&e.actionProceeds.token.toLowerCase()!==u.address.toLowerCase()||e.feeOnlyAction&&n&&(n.asset._source==="spice"||n.asset._source==="wallet"&&n.asset.chainId===x)&&(m?m.toLowerCase()!==u.address.toLowerCase():n.asset.receiptTokenId||n.asset.chainTokens))return os(e);if(e.actionProceeds&&e.feeOnlyAction){const te=g||y;if(!te||!b||!I)return null;if(m&&m.toLowerCase()!==u.address.toLowerCase())throw new Error("Action proceeds require a matching fee-token source");return Ga({proceeds:e.actionProceeds,owner:te,token:u.address,signal:t,buildBatches:(B,$)=>j({...$,fundingAmountOverride:B}),baseline:()=>Pn({...e,actionProceeds:void 0,selectedAsset:n??{amount:"0",asset:{...u,name:u.symbol,balance:0n,balanceFormatted:0,balanceUsd:0,isNative:!1,_source:"spice"}}})})}if(!n?.asset)return null;if(s){if(!g&&!y||r<=0&&!e.feeOnlyAction||i&&!l&&!e.feeOnlyAction)return null;const te=Pt(d,u.decimals),B=m||zt(n.asset,x)||n.asset.address||u.address,$={chainId:x,tokenAddress:B,symbol:v.getTokenByAddress(B,x)?.symbol??n.asset.symbol,decimals:await fn(n.asset,B,x,u)};if(!w||!C||!b||!I)return null;const ie=g||y||C,L=i?l?.amountInMax??0n:te;if(L===0n&&!e.feeOnlyAction)return null;const H=F?await Uo({user:ie,pivot:F,buildSupplyChainBatches:J=>j({...J,sourceGasSkimOverride:1n}),signal:t}):0n,fe=Date.now();let Z=await ri({requiredNetFunding:L,feeOnlyAction:e.feeOnlyAction,buildBatches:J=>j({fundingAmountOverride:J,sourceGasSkimOverride:H}).then(M=>Va(Dd(M),ie,void 0,{requestTimestampMs:fe})),fundingToken:B,estimate:P,executionOptions:{userOverride:ie,useCustomTransfers:!0,feeExecutionMode:f,signal:t},tokenDescriptor:$});if(!Z.preview)return null;let he=0n,ge,ce=[],Ae=!1;for(let J=0;J<8;J++){if(t?.aborted)throw new Error("Fee estimation cancelled");if(ce=kn(await j({fundingAmountOverride:Z.grossFundingAmount,sourceGasSkimOverride:H,onSourceSpend:we=>{he=we},onActionCalls:we=>{ge=we}}),ie,Z.feeEstimate,{payoutAlreadyGross:!0,requestTimestampMs:fe}),e.feeOnlyAction){Ae=!0;break}const M=await P(ce,B,Z.grossFundingAmount,{userOverride:ie,useCustomTransfers:!0,feeExecutionMode:f,signal:t}),Y=f==="user-transfer"?oi(M,Z.feeEstimate):M,ue=hn(Y,$)??Ss(ce,$,L);if(!ue)return null;const We=L+ue.gasFee+ue.spicenetFee+(ue.bridgeFee??0n),Ce=hn(Z.feeEstimate,$),oe=(Ce?.gasFee??0n)===ue.gasFee&&(Ce?.spicenetFee??0n)===ue.spicenetFee&&(Ce?.bridgeFee??0n)===(ue.bridgeFee??0n),Ee=Z.grossFundingAmount===We&&oe;if(Z={feeEstimate:Y,grossFundingAmount:We,preview:{...ue,grossAmount:We,netAmount:L}},Ee){Ae=!0;break}}if(!Ae)throw new Error("Payment fees did not converge. Refresh the quote before submitting.");if(!Z.preview)return null;const N=F?Mt(H,F.source.decimals,F.destination.decimals,"ceil"):0n;return{...Z,batches:ce,sourceSpendCap:he,actionDefinition:ge,destinationAmount:te,preview:{...Z.preview,grossAmount:Z.preview.grossAmount+N,gasFee:Z.preview.gasFee+N,totalFee:(Z.preview.totalFee??0n)+N},...F?{sourceGasSkim:H}:{}}}if(r<=0||!g)return null;const O=g||y;if(F&&!E)return null;const q=Mo({isPayMode:s,selectedAsset:n,resolvedChainId:x,sourceSwap:E,pivot:F});if(!(!s&&!c&&n.asset?._source==="wallet"&&n.asset.chainId!==x)&&!S&&!k&&!T||T)return null;let R=await U();if(R.length===0)return null;const W={chainId:x,tokenAddress:D,symbol:v.getTokenByAddress(D,x)?.symbol??(n.asset.chainId===x&&h.addressesEqual(n.asset.address,D)?n.asset.symbol:u.symbol),decimals:await fn(n.asset,D,x,u)},K=q?await Uo({user:O,pivot:F,buildSupplyChainBatches:U,signal:t}):0n;q&&K>0n&&(R=await U({sourceGasSkimOverride:K}));const G=q?Mt(o?Ya(E,K):E.amountOutMinimum,F.source.decimals,F.destination.decimals,"floor"):Mt(Pt(n.amount,n.asset.decimals),n.asset.decimals,W.decimals,"floor"),_={userOverride:O,useCustomTransfers:!0,feeExecutionMode:f,signal:t,...q?{skipUserFundingPreflight:!0}:{}};let X=G,Q=await P(R,D,X,_);for(let te=0;te<8;te++){if(t?.aborted)throw new Error("Fee estimation cancelled");const B=hn(Q,W)??Ss(R,W,X);if(!B)return null;const $=Wo(B,G,o,f);X=$.grossAmount;let ie,L,H,fe,Z;const he=await U({fundingAmountOverride:X,sourceGasSkimOverride:K,actionContextOverride:$,onDestinationAmount:J=>{ie=J},onSourceSpend:J=>{L=J},onSwap:(J,M)=>{H=J,fe=M},onActionCalls:J=>{Z=J}}),ge=await P(he,D,X,_),ce=f==="user-transfer"?oi(ge,Q):ge,Ae=hn(ce,W)??Ss(he,W,X);if(!Ae)return null;const N=Wo(Ae,G,o,f);if(JSON.stringify($,(J,M)=>typeof M=="bigint"?M.toString():M)===JSON.stringify(N,(J,M)=>typeof M=="bigint"?M.toString():M)){const J=q?Mt(K,F.source.decimals,F.destination.decimals,"ceil"):0n;return{batches:he,fundingAmount:X,actionContext:$,sourceSpendCap:L,destinationAmount:ie,destinationSwap:H,swapInputAmount:fe,actionDefinition:Z,feeEstimate:ce,sourceGasSkim:K,preview:{...Ae,grossAmount:X+J,netAmount:$.netAmount,gasFee:Ae.gasFee+J,spicenetFee:$.feeBreakdown.spicenetFee,totalFee:$.combinedFeeAmount+J}}}Q=ce,R=he}throw new Error("Fees did not converge. Refresh the quote before submitting.")}function Wo(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 r=n?Oc(t,o,10n):null;if(r&&!r.coversFees)throw new Error("Amount is too small to cover fees. Increase the amount and retry.");const i=r?.spicenetFee??(s==="user-transfer"?ks(t,10n):e.spicenetFee);return{grossAmount:r?.grossAmount??t+i+o,netAmount:r?.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=zt(n,e.resolvedChainId);if(!s||!h.addressesEqual(s,e.executionTokenAddress))return;const o=v.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),r=Mn(t,o?.decimals??e.destinationToken.decimals,n.decimals);if(r<=n.balance)return;const i=A.formatUnits(r,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 Gd(e){const t=v.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 Kd(e){const t=e.selectedAsset.asset,n=Pt(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 Zd(e,t){return e.feeQuote?.sourceGasSkim!==void 0?e.feeQuote.sourceGasSkim:Uo({user:t,pivot:e.pivot,buildSupplyChainBatches:e.execution.buildSupplyChainBatches})}function Yd(e,t,n){const s=hn(e,Gd(t));if(s)return Wo(s,n,!!t.isFeeInclusiveInput,t.feeExecutionMode)}function ii(e,t,n){let s=0n,o=0n;const r=n.toLowerCase();for(const i of e)if(i.chainId===t){for(const l of i.calls??[])if(l.to.toLowerCase()===r)try{const c=A.decodeFunctionData({abi:A.erc20Abi,data:l.data});if(c.functionName!=="transfer")continue;const d=c.args[0].toLowerCase(),u=c.args[1];d===v.SPICE_PLATFORM_FEE_RECIPIENT.toLowerCase()?s+=u:d===v.SPICE_GAS_FEE_RECIPIENT.toLowerCase()&&(o+=u)}catch{continue}}return{spicenetFee:s,gasFee:o}}function Xd(e,t,n){if(!e.isFeeInclusiveInput||!e.needsSwap)return;const s=t.swapInputAmount??t.preview.netAmount,o=ii(n,e.resolvedChainId,e.resolvedTokenIn??e.executionTokenAddress);if(s+o.gasFee+o.spicenetFee>t.preview.grossAmount)throw new Error("Swap input plus fees exceeds the entered amount. Refresh the quote before retrying.")}function Jd(e,t,n){const s=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,o=ii(e,t.resolvedChainId,s);return o.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||o.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:Cn(o.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&Cn(o.gasFee,n.feeBreakdown.gasFee,100n)}function $d(e,t){return e?Cn(e.grossAmount,t.grossAmount,100n)&&Cn(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&Cn(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&Cn(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}function _d(e,t){const n=v.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 eu(e,t){const n=e.feeQuote;return n?.feeEstimate&&n.grossFundingAmount!==void 0?{grossFundingAmount:n.grossFundingAmount,feeEstimate:n.feeEstimate}:ri({...t,feeOnlyAction:e.feeOnlyAction,estimate:e.execution.estimate,tokenDescriptor:_d(e,t.fundingToken)})}function li(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 ci(e,t){const n=h.sanitizeError(t,"Payment failed. Please try again.");e.ui.setError(n),e.ui.setPaymentResult({status:"failed",error:n})}async function di(e){e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setStep("executing"),e.ui.setStatusMsg("Confirm the transaction in your external wallet..."),e.ui.setTxHash(null),e.isPayMode&&(e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"}));try{if(e.validateFeeQuote?.(),!e.feeQuote?.batches||!e.feeQuote.actionDefinition)throw new Error("Review the direct action plan before submitting.");const t=await e.execution.execute(e.feeQuote.batches,e.destinationToken.address,0n,e.execution.onProgress);e.ui.setTxHash(t),e.ui.setStep("success"),e.ui.setStatusMsg("Transaction confirmed"),e.isPayMode&&e.ui.setPaymentResult({status:"success",txHash:t})}catch(t){e.isPayMode?ci(e,t):li(e,t,!1)}finally{e.ui.setIsExecuting(!1)}}async function ui(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.directExternalAction)return di(e);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=Mo(e),o=s?await Zd(e,n):0n,r=x=>e.execution.buildSupplyChainBatches(s?{...x,sourceGasSkimOverride:o}:x);s&&Kd(e);const i=e.feeQuote?.batches?e.feeQuote:await Pn({...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 c=i.batches;const d=c.some(x=>x.tokenTransfers?.length),u={userOverride:n,useCustomTransfers:d,feeExecutionMode:e.feeExecutionMode,...s?{skipUserFundingPreflight:!0}:{}},f=i.fundingAmount,m=i.actionContext;Qd(e,f);let g=m;const y=await e.execution.execute(c,e.executionTokenAddress,d?f:0n,e.execution.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...u,skipUserFundingPreflight:!0,validateBeforeSubmit:x=>Xd(e,i,x),adjustBatchesForEstimate:({feeEstimate:x,chainBatches:w})=>{const C=Yd(x,e,l);if(!C)return null;const b=$d(g,C),I=Jd(w,e,C);return b||I?null:(g=C,r({fundingAmountOverride:C.grossAmount,actionContextOverride:C}))}}:{...u,skipPreSubmitFeeEstimate:!0});e.ui.setTxHash(y),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){li(e,n,t.signal.aborted)}finally{e.ui.setIsExecuting(!1)}}async function pi(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}const t=e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t){e.ui.setError("Select a payment source");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.parsedAmount>0&&e.needsSwap&&!e.exactOutputSwap){e.ui.setError("Swap quote not available. Try a different asset.");return}if(e.directExternalAction)return di(e);const n=_a(e)&&!t,s=n?e.feeQuote?.sourceGasSkim??0n:0n,o=r=>e.execution.buildPayChainBatches(n?{...r,sourceGasSkimOverride:s}:r);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 r=Pt(e.currentPaymentAmount,e.destinationToken.decimals),i={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,...n?{skipUserFundingPreflight:!0}:{}};if(t&&!e.feeOnlyAction){const I=await o(),S=await e.execution.execute(I,e.executionTokenAddress,0n,k=>{k.txHash&&(e.ui.setPaymentResult(E=>({...E??{status:"processing"},txHash:k.txHash})),e.ui.setTxHash(k.txHash))},void 0,i);e.ui.setPaymentResult(k=>({status:"success",txHash:k?.txHash||S}));return}const l=e.selectedAsset?.asset,c=e.feeQuote?.fundingSource;if(!l&&!e.actionProceeds&&!c)throw new Error("Select a payment source");const d=e.feeQuote?.fundingConversion?.tokenIn||c?.token||e.resolvedTokenIn||l?.address||e.destinationToken.address,u=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:r,f=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,m=!!e.feeQuote?.fundingConversion||!!c&&(c.kind!=="balance"||c.asset?._source==="wallet"),{grossFundingAmount:g,feeEstimate:y}=m?{grossFundingAmount:e.feeQuote.grossFundingAmount??0n,feeEstimate:void 0}:await eu(e,{requiredNetFunding:u,buildBatches:I=>e.execution.buildPayChainBatches({fundingAmountOverride:I}).then(S=>kn(S,f)),fundingToken:d,executionOptions:i}),x=e.feeQuote?.fundingBatches??e.feeQuote?.batches??kn(await o({fundingAmountOverride:g}),f,e.actionProceeds?void 0:y,{payoutAlreadyGross:!0}),w=jd(e,e.feeQuote?.fundingConversion?.tokenOut??d,g),C=e.feeOnlyAction||x.some(I=>I.tokenTransfers?.length),b=await e.execution.execute(x,d,C?g:0n,I=>{I.txHash&&(e.ui.setPaymentResult(S=>({...S,txHash:I.txHash})),e.ui.setTxHash(I.txHash))},void 0,{...i,...w,skipPreSubmitFeeEstimate:!0});e.ui.setPaymentResult(I=>({status:"success",txHash:I?.txHash||b}))}catch(r){ci(e,r)}finally{e.ui.setIsExecuting(!1)}}async function fi(e){const{definition:t,account:n,chainId:s}=e,{calls:o}=t;if(!h.addressesEqual(t.context.executorAddress,n)||t.context.chainId!==s||!o.length)throw new Error("The direct action no longer matches its wallet or chain.");const r=h.getClientForChain(s);let i;for(const l of o){await e.assertCurrent();const[c,d]=await Promise.all([va({client:r,account:n,calls:[l]}),r.getBalance({address:n})]);if(d<l.value+c)throw new Error("The external wallet has insufficient native balance for this transaction and network gas.");const{extWc:u,viemChain:f}=await Eo({wallet:e.wallet,account:n,chainId:s});i=await $c({extWc:u,viemChain:f,client:r,calls:[l],errorMessage:"The external transaction reverted. Retry the unfinished action when ready."})}if(!i)throw new Error("The direct action has no confirmed receipt.");return i}function tu(e,t,n){const s=[],o=(r,i,l)=>{l>0n&&s.push(v.isNativeToken(r)?{to:i,value:l,data:"0x"}:{to:r,value:0n,data:A.encodeFunctionData({abi:A.erc20Abi,functionName:"transfer",args:[i,l]})})};return t.feeExecutionMode==="user-transfer"&&t.feeBreakdown&&(o(t.feeToken??t.destinationToken,v.SPICE_PLATFORM_FEE_RECIPIENT,t.feeBreakdown.spicenetFee),o(t.feeToken??t.destinationToken,v.SPICE_GAS_FEE_RECIPIENT,t.feeBreakdown.gasFee+t.feeBreakdown.bridgeFee)),o(t.destinationToken,n,e),s}function nu(e,t,n,s){let o=0n;for(const r of e)if(r.chainId===n){for(const i of r.calls)if(h.addressesEqual(i.to,t))try{const l=A.decodeFunctionData({abi:A.erc20Abi,data:i.data});l.functionName==="transfer"&&h.addressesEqual(l.args[0],s)&&(o+=l.args[1])}catch{}}return o}async function mi(e){const{asset:t,embedded:n,external:s,amount:o}=e;if(!s||!e.externalWallet)throw new Error("Connect the source wallet before funding.");if(o<=0n)return;const r=h.getClientForChain(t.chainId),i=t.isNative||v.isNativeToken(t.address),[l,c]=await Promise.all([Sa({client:r,account:s,recipient:n,token:t.address,isNative:i,amount:o}),r.getBalance({address:s})]);if(c<l+(i?o:0n))throw new Error("The source wallet has insufficient native balance for funding and gas.");const{extWc:d,viemChain:u}=await Eo({wallet:e.externalWallet,account:s,chainId:t.chainId});await _c({extWc:d,sourceClient:r,recipient:n,tokenAddr:t.address,isNative:i,amount:o,viemChain:u,observer:{onSending:()=>e.assertCurrent()}})}function hi(e,t,n){return h.addressesEqual(e.address,t)&&e.chainId===n?e._source==="wallet"?0:1:2}function su(e,t,n,s){const o=hi(e,n,s)-hi(t,n,s);return o!==0?o:(t.balanceUsd||0)-(e.balanceUsd||0)}const ou=Pr;function gi(e){const t=p.useContext(h.SpiceFlowProviderContext),n=h.useProviderWallets(),s=t?.embeddedWalletAddress||n.embeddedAddress,o=t?.externalWalletAddress||n.externalAddress,r=(t?.mode||"7702")!=="7702",i=Dn({...e,owner:s,enabled:e.enabled&&!!s&&(!r||!!e.includeCrossChainEmbeddedAssets),role:"spend-source",destination:e.destinationToken}),l=Dn({...e,owner:o,enabled:e.enabled&&!!o&&(r||!!e.includeExternalWalletAssets),role:"spend-source",destination:e.destinationToken});return{displayAssets:p.useMemo(()=>[...i.assets,...l.assets].sort((c,d)=>su(c,d,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:r,refreshSpiceAssets:i.refresh,refreshWalletAssets:i.refresh,loading:i.loading||l.loading,refreshing:i.refreshing||l.refreshing,error:i.error||l.error}}function ru(e,t){return!e||e._source!=="wallet"?null:ro(e,t)}function Lo(e,t){return gr({aerodrome:!1,oneInch:e?.includeDefaults===!1?{chainIds:[]}:void 0,customVenues:t})}const zo=jn(),au=Lo(void 0,zo.input);function xi(e){return{venue:"mapped-transfer",amountOut:e,amountOutMinimum:e,calls:[]}}function yi(e){return{venue:"mapped-transfer",amountIn:e,amountInMax:e,amountOut:e,calls:[]}}async function qo(e){if(h.addressesEqual(e.tokenIn,e.tokenOut))return xi(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?Lo(e.liquidityVenues,jn(e.liquidityVenues).input):au).resolveSwap({type:"swap",tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:e.amountIn,maxSlippage:e.maxSlippage},e.chainId,e.recipient,e.selectedSwap);if(!t)throw new Error("No liquidity for this pair.");return t}async function iu(e){return h.addressesEqual(e.tokenIn,e.tokenOut)?yi(e.amountOut):Ns({customVenues:e.liquidityVenues?jn(e.liquidityVenues).output:zo.output}).getQuote({tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountOut:e.amountOut,maxSlippage:e.maxSlippage},e.chainId,e.recipient)}function wi(e){const{enabled:t=!0,direction:n,selectedAsset:s,destinationToken:o,chainId:r,recipient:i,paymentAmount:l,maxSlippage:c,refreshIntervalMs:d,resolveInputSwap:u,resolveExactOutputSwap:f}=e,m=p.useContext(h.SpiceFlowProviderContext),g=m?.liquidityVenues,y=JSON.stringify([m?.network,m?.apiUrl,m?.rpcOverrides]),[x,w]=p.useState(!1),[C,b]=p.useState(null),[I,S]=p.useState(null),[k,E]=p.useState(null),[F,T]=p.useState(null),[D,j]=p.useState(null),[U,P]=p.useState(null),[O,q]=p.useState(null),[R,W]=p.useState(null),[K,G]=p.useState(null),[_,X]=p.useState(null),[Q,te]=p.useState(null),[B,$]=p.useState(null),[ie,L]=p.useState(null),[H,fe]=p.useState(0),[Z,he]=p.useState(null),[ge,ce]=p.useState(null),Ae=p.useRef(null),N=p.useRef(null),J=p.useRef(0),M=p.useRef(new Map),Y=p.useCallback(()=>{J.current++,M.current.clear(),ce(null),fe(De=>De+1)},[]),ue=d&&d>0?d:null,We=g?JSON.stringify(g):"",Ce=p.useMemo(()=>g?jn(g):zo,[We]),oe=p.useMemo(()=>Lo(g,Ce.input),[Ce]),Ee=p.useMemo(()=>Ns({customVenues:[...f?[{name:"consumer-exact-output",chainIds:[r],preferred:!0,resolve:f}]:[],...Ce.output]}),[f,r,Ce]);p.useEffect(()=>{M.current.clear()},[Ee]);const we=p.useMemo(()=>t?ru(s?.asset,r):null,[t,s?.asset,r]),Pe=p.useMemo(()=>{if(!t||!s?.asset)return null;if(we)return we.destination.address;const De=zt(s.asset,r);if(De)return De;const Ge=an(s.asset.address,r,s.asset.chainId);return Ge?Ge.address:null},[t,s?.asset,r,we]),Qe=p.useMemo(()=>t&&s?.asset?Bn(s.asset,r):[],[t,s?.asset,r]),it=p.useMemo(()=>Qe.map(De=>De.toLowerCase()).join(","),[Qe]),ze=JSON.stringify([t,y,s?.asset.owner,s?.asset.location,s?.asset.receiptTokenId,s?.asset.address,s?.asset.chainId,s?.asset.decimals,s?.amount,r,it,n,l]);p.useEffect(()=>{let De=!1;if(N.current&&(clearTimeout(N.current),N.current=null),!t||!s?.asset||we||Qe.length<=1){$(null),L(null);return}return N.current=setTimeout(async()=>{const Ge=n==="input"?s.amount:l||"0";let qe=0n;try{qe=n==="input"?Pt(Ge,s.asset.decimals):0n}catch{qe=0n}try{const $e=await Dr(s.asset,r,{requiredAmount:qe});De||($($e),L(ze))}catch{De||$(null)}},400),()=>{De=!0,N.current&&(clearTimeout(N.current),N.current=null)}},[ze]);const Je=p.useMemo(()=>(ie===ze?B:null)??Pe,[B,ie,ze,Pe]),Re=p.useMemo(()=>!s?.asset||!Je?[]:[Je,...Qe.filter(De=>De.toLowerCase()!==Je.toLowerCase())],[s?.asset,Je,Qe]),ot=p.useMemo(()=>!s?.asset||!Hn(s.asset.address,s.asset.chainId,o.address,o.chainId)||!Je?!1:h.addressesEqual(Je,o.address),[s,o.address,o.chainId,Je]),_e=Je?h.addressesEqual(Je,o.address):!1,Ue=n==="output"&&parseFloat(l||"0")===0,Le=t&&!!s?.asset&&!ot&&!_e&&!Ue,ct=JSON.stringify([t,We,n,Le,y,s?.asset.owner,s?.asset.location,s?.asset.receiptTokenId,s?.asset.address,s?.asset.chainId,s?.asset.decimals,n==="input"?s?.amount:l,Re.map(De=>De.toLowerCase()),r,o.address.toLowerCase(),o.chainId,o.decimals,i?.toLowerCase(),c,ue,we?.source.address.toLowerCase()??""]),Me=p.useMemo(()=>({}),[ct,oe,Ee,u,H]),Ze=ge?.request===Me&&(!ue||ge.expiresAt>Date.now());return p.useEffect(()=>{if(!ue||ge?.request!==Me)return;const De=setTimeout(Y,Math.max(0,ge.expiresAt-Date.now()));return()=>clearTimeout(De)},[ue,ge,Me,Y]),p.useEffect(()=>{Ae.current&&clearTimeout(Ae.current),he(Me),ce(null),b(null);const De=n==="input"?s?.amount:l,Ge=parseFloat(De||"0");if(!t||!Number.isFinite(Ge)||Ge<=0||!s?.asset||!i||Re.length===0){J.current++,S(null),E(null),T(null),j(null),P(null),q(null),W(null),te(null),b(null),w(!1);return}const qe=s.asset.decimals;let $e;try{$e=n==="input"?Pt(s.amount,qe):Pt(l||"0",o.decimals)}catch(xe){J.current++,b(xe instanceof Error?xe.message:"Invalid amount or token precision"),w(!1);return}const Se=++J.current,Ne=()=>Se!==J.current;w(!0);const ft=n==="output"?150:400,ne=async(xe,me,ee,ye={chainId:r,tokenOut:o.address,amountIn:$e},Fe=Re)=>{for(const Ye of Fe){const je=`${y}:${We}:${n}:${ye.chainId}:${Ye.toLowerCase()}:${ye.tokenOut.toLowerCase()}:${ye.amountIn.toString()}:${i.toLowerCase()}:${c??"default"}:${ue??"default"}`,z=M.current.get(je),ke=z&&z.expiresAt>Date.now()?xe(z):void 0;if(ke)return{quote:ke,tokenIn:Ye,expiresAt:z.expiresAt};const be=await ee(Ye);if(Ne())return"stale";if(!be)continue;const He=Date.now()+Math.min(ue??3e4,3e4);return M.current.set(je,{expiresAt:He,direction:n,...me(be)}),{quote:be,tokenIn:Ye,expiresAt:He}}return null},Te=xe=>ne(me=>me.resolvedSwap,me=>({resolvedSwap:me}),async me=>{const ee=!we&&xe.chainId===r&&s.asset._source!=="wallet",ye=ee?await fn(s.asset,me,xe.chainId,o):qe;if(Ne())return null;const Fe=ee?Bs(xe.amountIn,qe,ye):xe.amountIn;if(h.addressesEqual(me,xe.tokenOut))return xi(Fe);const Ye={type:"swap",tokenIn:me,tokenOut:xe.tokenOut,amountIn:Fe,maxSlippage:c};if(u){const je=await u(Ye,xe.chainId,i);if(je)return je}return oe.resolveSwap(Ye,xe.chainId,i)},xe,xe.candidates);return Ae.current=setTimeout(async()=>{try{if(n==="input"){let xe=null,me=$e;if(we){if(xe=await Te({chainId:we.source.chainId,tokenOut:we.source.address,amountIn:$e,candidates:[s.asset.address]}),xe==="stale"||Ne())return;if(!xe)throw new Error("No liquidity for this pair");me=Mt(xe.quote.amountOutMinimum,we.source.decimals,we.destination.decimals,"floor")}const ee=Le||!we?await Te({chainId:r,tokenOut:o.address,amountIn:me,candidates:Re}):null;if(ee==="stale"||Ne())return;if(Le&&!ee)throw new Error("No liquidity for this pair");const ye=ee?ee.quote.amountOut:me,Fe=Math.min(ee?.expiresAt??1/0,xe?.expiresAt??1/0),Ye=we?.destination.decimals??await fn(s.asset,ee.tokenIn,r,o),je=!we&&s.asset._source!=="wallet"?Bs(me,qe,Ye):me;if(Ne())return;te(ee?.tokenIn??we?.destination.address??null),ce({request:Me,key:`${A.keccak256(A.toHex(ct))}:${Se}`,expiresAt:Fe}),W(ye),G(je),X(Ye),T(Le?ee?.quote??null:null),j(xe?.quote??null),P(null),q(null);const z=parseFloat(A.formatUnits(ye,o.decimals));S(z<.01?z.toPrecision(4):z.toLocaleString(void 0,{maximumFractionDigits:6})),E(null),b(null)}else{const xe=je=>ne(z=>z.exactOutputSwap,z=>({exactOutputSwap:z}),async z=>{try{return h.addressesEqual(z,je.tokenOut)?yi(je.amountOut):await Ee.getQuote({tokenIn:z,tokenOut:je.tokenOut,amountOut:je.amountOut,maxSlippage:c},je.chainId,i)}catch{return null}},{chainId:je.chainId,tokenOut:je.tokenOut,amountIn:je.amountOut},je.candidates),me=!we||Le,ee=me?await xe({chainId:r,tokenOut:o.address,amountOut:$e,candidates:Re}):null;if(ee==="stale"||Ne())return;if(me&&!ee)throw new Error("No liquidity for this pair");let ye=null;if(we){const je=ee?ee.quote.amountInMax:$e;if(ye=await xe({chainId:we.source.chainId,tokenOut:we.source.address,amountOut:Mt(je,we.destination.decimals,we.source.decimals,"ceil"),candidates:[s.asset.address]}),ye==="stale"||Ne())return;if(!ye)throw new Error("No liquidity for this pair")}const Fe=ye?qe:await fn(s.asset,ee.tokenIn,r,o);if(Ne())return;te(ee?.tokenIn??we?.destination.address??null),ce({request:Me,key:`${A.keccak256(A.toHex(ct))}:${Se}`,expiresAt:Math.min(ee?.expiresAt??1/0,ye?.expiresAt??1/0)}),q(ee?.quote??null),P(ye?.quote??null),T(null),j(null),W(null);const Ye=ye?.quote.amountIn??ee.quote.amountIn;E(A.formatUnits(Ye,Fe)),S(null),b(null)}}catch(xe){if(Ne())return;const me=xe instanceof Error?xe.message:"Failed to get quote";b(me),S(null),E(null),T(null),j(null),P(null),q(null),W(null),te(null)}finally{Ne()||w(!1)}},Le||we?ft:0),()=>{J.current++,Ae.current&&clearTimeout(Ae.current)}},[Me]),{inputAmount:Ze&&n==="input"?K:null,inputDecimals:Ze&&n==="input"?_:null,quoteKey:Ze?ge.key:null,quoteExpiresAt:Ze?ge.expiresAt:null,refreshQuote:Y,isQuoting:Z===Me?x:Le||!!we,quoteError:Z===Me?C:null,estimatedOutput:Ze?I:null,estimatedInput:Ze?k:null,resolvedSwap:Ze?F:null,exactOutputSwap:Ze?O:null,quoteAmountOut:Ze?R:null,resolvedTokenIn:Le&&Ze?Q??Je:Je,isDirect:_e,needsSwap:Le,selectedIsEquivalent:ot,sourceSwap:Ze?D:null,sourceExactOutputSwap:Ze?U:null,pivot:we}}function rs(e){const{enabled:t,destinationToken:n,selectedAsset:s,paymentAmount:o="0",sourceChains:r,supportedSourceAssets:i,buildActionCalls:l,feeExecutionMode:c="user-transfer",buildSpicenetBatch:d,onPayExecute:u,resolveExactOutputSwap:f,amountDirection:m="input",onSuccess:g,onError:y}=e,x=m==="output",w=m==="input-inclusive",C=x?"output":"input",b=n.chainId,I=p.useContext(h.SpiceFlowProviderContext),S=I?.mode||"7702",k=!1,E=!!I?.isWhitelistGateActive,F=!!I?.isWhitelistConfigured&&I?.isUserWhitelisted!==!0,T=p.useMemo(()=>r??I?.supportedChainIds??[],[r,I?.supportedChainIds]),D=i,{address:j,isConnected:U,isReady:P,isAuthenticated:O,provider:q}=h.useWallet(),{execute:R,estimate:W}=Es(),{externalWallet:K,embeddedAddress:G,activeWallet:_,activeAddress:X}=h.useProviderWallets(),Q=I?.externalWalletAddress,te=I?.embeddedWalletAddress||G,B=s,$=Mr(B?.asset,S!=="7702"),ie=!!B&&B.asset.chainId===n.chainId&&h.addressesEqual(v.normalizeNativeTokenAddress(B.asset.address),v.normalizeNativeTokenAddress(n.address)),L=S!=="7702"&&$&&ie&&(!x||Number(o)>0)&&!e.feeOnlyAction&&!e.actionProceeds,H=$&&!L,fe=e.actionExecution?.wallet==="external"&&!L,Z=u?"Move onPayExecute protocol calls to buildActionCalls and application updates to onSuccess before continuing.":fe&&(x||e.prependSourceEscrow||v.isNativeToken(n.address))?"External wallet execution requires an ERC20 input supply with SDK-managed funding.":null,he=p.useMemo(()=>fe&&Q?(le,ut)=>tu(le,ut,Q):l,[fe,Q,l]),{displayAssets:ge,filteredSpiceAssets:ce,walletAssets:Ae,embeddedWalletAddress:N,refreshSpiceAssets:J,refreshWalletAssets:M,loading:Y,refreshing:ue,error:We}=gi({address:j,destinationToken:n,supportedSourceAssets:D,sourceChains:T,additionalSourceTokens:[...e.additionalSourceTokens??[],...B?.asset._source==="wallet"?[{address:B.asset.address,chainId:B.asset.chainId,decimals:B.asset.decimals,symbol:B.asset.symbol,name:B.asset.name,logoURI:B.asset.logoURI}]:[]],includeExternalWalletAssets:e.includeExternalWalletAssets,includeCrossChainEmbeddedAssets:e.includeCrossChainEmbeddedAssets,enabled:t&&(S!=="7702"?!!Q:!!te)}),Ce=ge,oe=p.useMemo(()=>e.feeOnlyAction?Ce.filter(le=>le.balance>0n&&le.location!=="external"&&(le._source==="spice"||le._source==="wallet"&&le.chainId===b)):[],[Ce,e.feeOnlyAction,b]),Ee=B?[...Ae,...ce].find(le=>pt(le)===pt(B.asset)):void 0,we=p.useMemo(()=>B&&Ee?{...B,asset:Ee}:B,[B,Ee]),Pe=B?bn(Ee??B.asset,"spend-source",{allowedTokens:I?.allowedTokens,rpcOverrides:I?.rpcOverrides,liquidityVenues:I?.liquidityVenues,isWhitelistGateActive:E},n,D):null,Qe=Ee?Ee.balance<(B?.asset.balance??0n)?Ee.balance:B.asset.balance:0n,[it,ze]=p.useState(!1),[Je,Re]=p.useState(null),ot=p.useRef(y);ot.current=y;const _e=p.useCallback(le=>{Re(le),typeof le=="string"&&le&&ot.current?.(new Error(le),h.getRelayerErrorDetail(le))},[]),[Ue,Le]=p.useState("idle"),[ct,Me]=p.useState(""),[Ze,De]=p.useState(null),[Ge,qe]=p.useState(!1),[$e,Se]=p.useState(null),[Ne,ft]=p.useState(null),[ne,Te]=p.useState(!1),[xe,me]=p.useState(!1),[ee,ye]=p.useState(null),Fe=p.useRef(B),Ye=p.useRef(!1),je=p.useRef(null),z=p.useRef(null),ke=p.useRef(null),be=p.useRef(null),He=p.useRef(g),At=p.useRef(null),[Et,ve]=p.useState(null),[mt,ht]=p.useState(null),[wt,Gt]=p.useState(!1),[yn,ln]=p.useState(0);p.useEffect(()=>{Fe.current=B},[B]);const dt=L?Q:N||G||j,Rt=wi({enabled:t&&!F&&!L,direction:C,selectedAsset:B,destinationToken:n,chainId:b,recipient:dt,paymentAmount:o,resolveExactOutputSwap:f,resolveInputSwap:e.resolveInputSwap,maxSlippage:e.maxSlippage}),rt=L?{...Rt,quoteKey:"direct-external",quoteExpiresAt:null,quoteAmountOut:null,inputAmount:null,inputDecimals:B?.asset.decimals??null,isQuoting:!1,quoteError:null,isDirect:!0,needsSwap:!1,selectedIsEquivalent:!0,resolvedTokenIn:n.address,resolvedSwap:null,exactOutputSwap:null,sourceSwap:null,sourceExactOutputSwap:null,pivot:null,estimatedInput:x?o:B?.amount??null,estimatedOutput:x?o:B?.amount??null}:Rt,Be=rt,{isQuoting:jt,resolvedSwap:Ut,exactOutputSwap:Tt,quoteAmountOut:qt,resolvedTokenIn:Ke,isDirect:et,needsSwap:gt,selectedIsEquivalent:Wt,sourceSwap:nt,sourceExactOutputSwap:tt,pivot:de}=rt,xt=x?parseFloat(o||"0"):parseFloat(B?.amount||"")||0,_t=B?.asset?._source==="wallet",In=!!B?.asset&&_t&&B.asset.chainId!==b,An=B?Number(A.formatUnits(Qe,B.asset.decimals)):0,cn=p.useMemo(()=>{if(!B||x)return!1;try{return Pt(B.amount||"0",B.asset.decimals)>Qe}catch{return!0}},[B,x,Qe]);p.useEffect(()=>{t||(_e(null),ze(!1),Le("idle"),Me(""),De(null),qe(!1),Se(null),ft(null),Te(!1),me(!1),ye(null),Ye.current=!1,je.current&&(je.current.abort(),je.current=null))},[t]);const Wn=p.useCallback(le=>{Le({building:"building","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[le.step]||"executing"),Me(le.message),le.txHash&&De(le.txHash)},[]),Lt=p.useMemo(()=>({currentPaymentAmount:o,isFeeInclusiveInput:w,feeOnlyAction:e.feeOnlyAction,swapInputAmount:rt.inputAmount,destinationToken:n,embeddedWalletAddress:N,providerEmbeddedAddress:G,externalWalletAddress:Q,address:j,recipient:e.recipient??(S!=="7702"?Q:void 0),isNon7702:k,isPayMode:x,resolvedChainId:b,buildActionCalls:he,feeExecutionMode:c,buildSpicenetBatch:d,selectedAsset:B,needsSwap:gt,resolvedSwap:Ut,exactOutputSwap:Tt,quoteAmountOut:qt,resolvedTokenIn:Ke,sourceSwap:nt,sourceExactOutputSwap:tt,pivot:de,resolveSourceExactOutputSwap:async le=>{if(!de||!dt)throw new Error("Swap route is not ready.");const ut=await iu({chainId:de.source.chainId,recipient:dt,tokenIn:B.asset.address,tokenOut:de.source.address,amountOut:le,liquidityVenues:I?.liquidityVenues,maxSlippage:e.maxSlippage}).catch(()=>null);if(!ut)throw new Error("No liquidity for this pair.");return ut},resolveInputSwap:async(le,ut)=>{if(!Ke||!dt)throw new Error("Swap route is not ready.");return qo({chainId:b,recipient:dt,tokenIn:Ke,tokenOut:n.address,amountIn:le,selectedSwap:ut,liquidityVenues:I?.liquidityVenues,maxSlippage:e.maxSlippage,resolveInputSwap:e.resolveInputSwap})}}),[o,n,N,G,Q,j,e.recipient,e.feeOnlyAction,e.maxSlippage,e.resolveInputSwap,rt.inputAmount,w,S,k,x,b,he,c,d,B,gt,Ut,Tt,qt,Ke,nt,tt,de,dt,I?.liquidityVenues]),se=p.useMemo(()=>B?.asset?de?de.destination.address:gt&&Ke?Ke:B.asset.chainId===b?B.asset.address:Ke??zt(B.asset,b)??n.address:n.address,[B,n.address,gt,b,Ke,de]),ae=A.keccak256(A.stringToHex(JSON.stringify([B&&pt(B.asset),B?.amount,o,m,n.address,n.chainId,n.decimals,e.recipient,S,Q,L?Q:N,I?.apiUrl,I?.rpcOverrides,e.maxSlippage,c,e.feeOnlyAction,I?.liquidityVenues,I?.allowedTokens,E,D,T]))),Ie=p.useRef({key:ae,enabled:t,sourceBalance:Qe,sourceEligible:Pe?.eligible});Ie.current={key:ae,enabled:t,sourceBalance:Qe,sourceEligible:Pe?.eligible};const Ve=p.useRef(null),st=p.useRef(!1),yt=p.useCallback(()=>st.current?(st.current=!1,He.current=be.current.onSuccess,Ve.current={key:Ie.current.key,quote:be.current.feeQuote},ui(be.current)):Promise.resolve(),[]),Ct=L,Dt=F,It=(w||!!de)&&!!Ne&&Ne.netAmount===0n,vt=p.useMemo(()=>!!e.feeOnlyAction||(!!B?.asset||!!e.actionProceeds)&&xt>0,[B,xt,e.actionProceeds,e.feeOnlyAction]),kt=p.useMemo(()=>!t||!vt||!B?.asset&&!e.actionProceeds&&!e.feeOnlyAction?null:[ae,x?"pay":"supply",m,B?pt(B.asset):"sdk-funded",e.actionInput?.map(le=>`${le.token.toLowerCase()}:${le.amount}`).join(",")??"",e.feeFunding?.join(",")??"",JSON.stringify(I?.rpcOverrides),I?.apiUrl,e.recipient,B?.asset.address.toLowerCase(),B?.asset.chainId,B?.amount,o,n.address.toLowerCase(),n.chainId,b,Be.resolvedTokenIn?.toLowerCase()??"",Be.quoteKey,Be.needsSwap?"swap":"direct",Be.isDirect?"direct-token":"routed-token","7702",ie?"source-dest":"cross-chain",Be.isQuoting?"quoting":"quoted",Be.exactOutputSwap?.amountIn?.toString()??"",Be.exactOutputSwap?.amountInMax?.toString()??"",Be.exactOutputSwap?.venue??"",Be.resolvedSwap?.amountOut?.toString()??"",Be.quoteAmountOut?.toString()??"",Be.sourceSwap?.amountOutMinimum?.toString()??"",Be.sourceExactOutputSwap?.amountInMax?.toString()??"",Be.pivot?.source.address.toLowerCase()??"",N??"",G??"",j??""].join("|"),[t,ae,e.actionProceeds,e.feeOnlyAction,e.actionInput,e.feeFunding,it,Ue,vt,Ct,B,x,m,o,n,b,Be,k,ie,N,G,j]),Bt=p.useCallback(async(le,ut)=>{if(L){if(!Q||!B)throw new Error("Connect the external wallet before continuing.");return qd({selectedAsset:ut?.selectedAsset??B,destinationToken:n,paymentAmount:x?o:void 0,account:Q,beneficiary:e.recipient,buildActionCalls:he,feeExecutionMode:c})}const St={...Lt,requestTimestampMs:Date.now()};return await Pn({signal:le,feeOnlyAction:e.feeOnlyAction,actionInput:e.actionInput,actionProceeds:e.actionProceeds,feeFunding:e.feeFunding,feeFundingBalances:oe,liquidityVenues:I?.liquidityVenues,maxSlippage:e.maxSlippage,resolveExactOutputSwap:f,selectedAsset:B,isPayMode:x,isFeeInclusiveInput:w,parsedAmount:xt,needsSwap:Be.needsSwap,exactOutputSwap:Be.exactOutputSwap,isNon7702:k,isSourceDestToken:ie,currentPaymentAmount:o,destinationToken:n,feeExecutionMode:c,resolvedTokenIn:Be.resolvedTokenIn,embeddedWalletAddress:N,providerEmbeddedAddress:G,resolvedChainId:b,isConnected:U,address:j,ready:P,authenticated:O,isDirect:Be.isDirect,resolvedSwap:Be.resolvedSwap,sourceSwap:Be.sourceSwap,sourceExactOutputSwap:Be.sourceExactOutputSwap,pivot:Be.pivot,isQuoting:Be.isQuoting,executionTokenAddress:se,buildPayChainBatches:lt=>Po(St,lt),buildSupplyChainBatches:lt=>Os(St,lt),estimate:W,...ut})},[B,L,Q,e.recipient,he,e.feeOnlyAction,e.actionInput,e.actionProceeds,e.feeFunding,oe,e.maxSlippage,f,I?.liquidityVenues,x,w,xt,Be,k,ie,o,n,c,N,G,Lt,W,b,U,j,P,O,se]);p.useEffect(()=>{z.current=Bt},[Bt]);const Ln=p.useCallback(async le=>{if(x)return null;if(!B||pt(le)!==pt(B.asset)||!dt||!Ke)throw new Error("Select a source before calculating Max.");let ut=le.balance;if(L){if(!le.isNative&&!v.isNativeToken(le.address))return A.formatUnits(ut,le.decimals);const St=h.getClientForChain(le.chainId),lt=Q;let bt=ut;for(let Nt=0;Nt<8;Nt++){const un=await Bt(void 0,{selectedAsset:{asset:le,amount:A.formatUnits(Nt===0?1n:bt,le.decimals)}});if(!un?.actionDefinition)throw new Error("The direct action could not be sized.");const tn=await va({client:St,account:lt,calls:un.actionDefinition.calls}),En=ut>tn?ut-tn:0n;if(En===0n)return"0";if(Nt>0&&bt<=En)return A.formatUnits(bt,le.decimals);bt=En}throw new Error("Network gas could not be reserved for Max. Enter a smaller amount.")}if(H&&(le.isNative||v.isNativeToken(le.address))){if(!Q)throw new Error("Connect the source wallet before calculating Max.");const St=await Sa({client:h.getClientForChain(le.chainId),account:Q,recipient:dt,token:le.address,isNative:!0,amount:1n});ut-=St}return ai({balance:ut,decimals:le.decimals,planForAmount:async St=>{const lt={...Lt,requestTimestampMs:Date.now(),selectedAsset:{asset:le,amount:A.formatUnits(St,le.decimals)}};let bt=St;return de?(lt.sourceSwap=await qo({chainId:le.chainId,recipient:dt,tokenIn:le.address,tokenOut:de.source.address,amountIn:St,maxSlippage:e.maxSlippage,liquidityVenues:I?.liquidityVenues,resolveInputSwap:e.resolveInputSwap}),bt=Mt(lt.sourceSwap.amountOutMinimum,de.source.decimals,de.destination.decimals,"floor")):bt=Bs(St,le.decimals,await fn(le,Ke,b,n)),lt.resolvedSwap=gt?await lt.resolveInputSwap(bt):null,lt.swapInputAmount=bt,lt.quoteAmountOut=lt.resolvedSwap?.amountOut??bt,Bt(void 0,{selectedAsset:lt.selectedAsset,parsedAmount:Number(lt.selectedAsset.amount),sourceSwap:lt.sourceSwap,resolvedSwap:lt.resolvedSwap,isQuoting:!1,buildSupplyChainBatches:Nt=>Os(lt,Nt)})}})},[B,Lt,x,L,dt,Ke,b,n,H,Q,de,gt,Bt,e.maxSlippage,e.resolveInputSwap,I?.liquidityVenues]);yo({shouldRun:t&&!it&&Ue==="idle"&&vt&&!Be.isQuoting&&!!kt,deps:[t,it,Ue,vt,Ct,Be.isQuoting,kt],onSkip:()=>{if(!t){Te(!1),me(!1),ye(null),ft(null);return}if(it||Ue!=="idle"){Te(!1);return}if(!vt){ft(null),Te(!1),me(!1),ye(null);return}Be.isQuoting&&(Te(!1),me(!1))},onCleanup:()=>Te(!1),delayMs:500,backgroundIntervalMs:5e3,run:async({isBackground:le,isCurrent:ut,signal:St})=>{const lt=kt;le||(ye(null),Te(!0));try{const bt=await z.current?.(St);if(!ut())return;bt&<?(ke.current={key:lt,quote:bt},ft(bt.preview),me(!0)):(ke.current=null,ft(null),me(!1)),ye(null)}catch(bt){if(!ut())return;if(le&&ke.current?.key===lt){console.warn("[SpiceSupply] fee refresh failed:",bt);return}const Nt=h.sanitizeError(bt,"Unable to calculate fees for this action.");ke.current=null,ft(null),me(!1),ye(Nt)}finally{ut()&&Te(!1)}}});const dn=p.useCallback(()=>st.current?(st.current=!1,He.current=be.current.onSuccess,Ve.current={key:Ie.current.key,quote:be.current.feeQuote},pi(be.current)):Promise.resolve(),[]),Ot=x&&$e?.status==="success"?$e.txHash:Ue==="success"?Ze:null;p.useEffect(()=>{!Ot||At.current===Ot||(At.current=Ot,Gt(!0),ht(null),Promise.resolve().then(()=>He.current?.(Ot)).then(()=>{ve(Ot),J(),M()}).catch(le=>{ht(`Transaction confirmed; application update needs retry: ${h.sanitizeError(le,"Unable to finalize the action")}`)}).finally(()=>Gt(!1)))},[Ot,yn]);const Ht=!!Ot&&Et!==Ot,wn=Ht&&!mt,zn=p.useCallback(()=>{At.current=null,ln(le=>le+1)},[]),V=p.useCallback(()=>{qe(!1),Se(null),Ye.current=!1,J(),M()},[J,M]),re=kt&&ke.current?.key===kt?ke.current.quote:null,Oe=()=>{if(Z)throw new Error(Z);if(!Ie.current.enabled||Ie.current.key!==ae)throw new Error("The source, amount, beneficiary or configuration changed. Review the form before continuing.");if((B||e.feeOnlyAction)&&!re)throw new Error("A current action plan is required. Refresh the quote before submitting.");if(L&&B?.asset.owner&&!h.addressesEqual(B.asset.owner,Q))throw new Error("Reconnect the external wallet that owns the selected asset.");if(B&&(re?.sourceSpendCap??0n)>Ie.current.sourceBalance)throw new Error("The source balance changed. Review the available amount before continuing.");if(B&&!Ie.current.sourceEligible)throw new Error(Pe?.reason??"This source is unavailable.")},pe=async()=>Oe(),Xe=le=>({...le,sourceSpendCap:re?.sourceSpendCap,minimumDestinationAmount:re?.destinationAmount}),at=B&&re?.sourceSpendCap!==void 0?re.sourceSpendCap>Qe:cn,Kt={...Lt,resolvedSwap:re?.destinationSwap??Lt.resolvedSwap,swapInputAmount:re?.swapInputAmount??Lt.swapInputAmount};be.current={selectedAsset:B,parsedAmount:xt,currentPaymentAmount:o,isInsufficientBalance:at,isPayMode:x,isFeeInclusiveInput:w,feeOnlyAction:e.feeOnlyAction,actionProceeds:e.actionProceeds,validateFeeQuote:Oe,isNon7702:k,directExternalAction:L,isSourceDestToken:ie,needsSwap:gt,exactOutputSwap:Tt,selectedIsEquivalent:Wt,resolvedTokenIn:Ke,sourceSwap:nt,sourceExactOutputSwap:tt,pivot:de,embeddedWalletAddress:N,providerEmbeddedAddress:G,externalWallet:K,externalWalletAddress:Q,activeSignerWallet:_,activeSignerAddress:X,address:j,isConnected:U,ready:P,authenticated:O,provider:q,resolvedChainId:b,executionTokenAddress:se,destinationToken:n,buildActionCalls:he,feeExecutionMode:c,buildSpicenetBatch:d,onPayExecute:u,onSuccess:g,feeQuote:re,execution:{estimate:(le,ut,St,lt)=>W(le,ut,St,{...lt,userOverride:dt}),execute:async(le,ut,St,lt,bt,Nt)=>{if(await pe(),L){if(!re?.actionDefinition)throw new Error("The direct action plan is unavailable.");return fi({definition:re.actionDefinition,account:Q,chainId:n.chainId,wallet:K,assertCurrent:pe})}if(H&&B&&(Me("Transfer the selected source to your embedded wallet"),await mi({asset:B.asset,embedded:dt,external:Q,externalWallet:K,amount:re?.sourceSpendCap??0n,assertCurrent:pe}),await pe()),!fe)return R(le,ut,St,lt,bt,{...Nt,userOverride:dt,requireDestinationReceipt:!0,validateBeforeSubmit:async pn=>{await pe(),await Nt?.validateBeforeSubmit?.(pn)}});const un=Q;let tn=0n;await R(le,ut,St,pn=>lt?.(pn.step==="success"?{...pn,step:"executing",message:"Funds delivered. Confirm the action in your external wallet.",txHash:void 0}:pn),bt,{...Nt,userOverride:dt,requireDestinationReceipt:!0,validateBeforeSubmit:async pn=>{if(await pe(),await Nt?.validateBeforeSubmit?.(pn),tn=nu(pn,n.address,n.chainId,un),tn<=0n)throw new Error("The route does not deliver the action amount to the external wallet.")}}),await pe();const En={userAddress:un,executorAddress:un,beneficiary:e.recipient??un,chainId:n.chainId,destinationToken:n.address,feeToken:n.address,grossAmount:tn,netAmount:tn,combinedFeeAmount:0n,feeExecutionMode:c,feeBreakdown:{spicenetFee:0n,gasFee:0n,bridgeFee:0n}},Go=await l?.(tn,En)??[];if(!Go.length)throw new Error("No action calls configured.");return fi({definition:{amount:tn,context:En,calls:Go},account:un,chainId:n.chainId,wallet:K,assertCurrent:pe})},buildPayChainBatches:le=>Po(Kt,Xe(le)),buildSupplyChainBatches:le=>Os(Kt,Xe(le)),onProgress:Wn},ui:{setError:_e,setStep:Le,setStatusMsg:Me,setTxHash:De,setIsExecuting:ze,setShowStatusPanel:qe,setPaymentResult:Se},refs:{spiceDepositSubmittedRef:Ye,abortControllerRef:je}};const en=!!e.isZeroAmountPay&&!e.feeOnlyAction&&x&&xt===0,ls=x?(en||!!B?.asset||!!e.actionProceeds||!!e.feeOnlyAction)&&xt>=0&&!at&&!it&&(en||Ct||xe)&&!ee&&(en||e.feeOnlyAction||!gt||!!Tt)&&(en||e.feeOnlyAction||!de||!!tt)&&!Dt:!!B?.asset&&xt>0&&!at&&!it&&(L||xe)&&!ee&&!It&&(de?!!nt&&!jt&&(et||!!Ut):In||et||!!Ut&&!jt)&&!Dt,cs=!Z&&!!dt&&(!L||!!K&&(!B?.asset.owner||h.addressesEqual(B.asset.owner,Q)))&&(!fe||!!K&&!!Q)&&(S==="7702"||!!Q)&&!wt&&!mt&&t&&ls&&(en||!B&&(!!e.actionProceeds||!!e.feeOnlyAction)||!!Pe?.eligible)&&Ue!=="success"&&$e?.status!=="success"&&!rt.quoteError&&(en||!!kt&&ke.current?.key===kt);st.current=cs;const Us=p.useCallback(()=>{st.current=!1,ke.current=null,me(!1),Rt.refreshQuote(),Le("idle"),_e(null)},[Rt.refreshQuote,_e]),Ni=p.useCallback(()=>{qe(!1)},[]),Mi=p.useCallback(()=>{Le("idle"),De(null),J()},[J]),Ft=re??(ke.current?.key.startsWith(`${ae}|`)?ke.current.quote:null)??(Ve.current?.key===ae?Ve.current.quote:null),Pi=async le=>{if(L)throw new Error("This source executes directly from the external wallet; submit the action without embedded funding.");if(!(!H||!B)){if(!re||le!==re.sourceSpendCap)throw new Error("Use the displayed source funding maximum before preparing this action.");await pe(),await mi({asset:B.asset,embedded:dt,external:Q,externalWallet:K,amount:le,assertCurrent:pe})}};return{selectedAsset:we,capability:Pe,assets:{selectable:Ce,displayAssets:Ce,filteredSpiceAssets:ce,embeddedWalletAddress:N,externalAddress:Q,isNon7702:S!=="7702",refreshSpiceAssets:J,refreshWalletAssets:M,loading:Y,refreshing:ue,error:We},quote:{...rt,hasSourceConversion:!!de,executionInput:de&&Ft?{address:de.destination.address,chainId:de.destination.chainId,decimals:de.destination.decimals,amount:Ft.preview.netAmount}:null,...Ft?.destinationSwap?{resolvedSwap:Ft.destinationSwap,inputAmount:Ft.swapInputAmount,estimatedOutput:A.formatUnits(Ft.destinationSwap.amountOut,n.decimals)}:{}},fees:{fundingConversion:Ft?.fundingConversion,fundingSource:Ft?.fundingSource,proceedsUsed:Ft?.proceedsUsed,fundingShortfall:Ft?.grossFundingAmount,source:de&&Ft?{address:de.source.address,chainId:de.source.chainId,symbol:de.source.symbol,decimals:de.source.decimals,gasFee:Ft.sourceGasSkim??0n,spicenetFee:0n}:null,destinationAmount:Ft?.destinationAmount,sourceSpendCap:Ft?.sourceSpendCap,preview:Ft?.preview??Ne,isLoading:ne,ready:!!re,error:ee},amount:{sourceRequiredAmount:Ft?.sourceSpendCap??null,parsed:xt,isInsufficientBalance:at,sourceBalance:An,feesExceedAmount:It},status:{finalizing:wt||wn,finalizationError:mt,step:Ht&&Ue==="success"?"executing":Ue,statusMsg:Ht?mt??"Transaction confirmed. Updating application...":ct,txHash:Ze,isExecuting:it||wn,error:Z||mt||Je||Pe?.reason||null,showStatusPanel:Ge,paymentResult:Ht&&$e?.status==="success"?{...$e,status:"processing"}:$e},flags:{directExecutionFeeNote:Ct},retryFinalization:zn,fundEmbeddedSource:Pi,canExecute:cs,submitSupply:yt,submitPay:dn,retrySupply:Us,dismissPaymentStatus:Ni,resolveMaxAmount:Ln,resetAfterSuccess:Mi,resetPaymentState:V}}function lu(e){return`0x77${e.slice(4)}`}function bi({userAddress:e,destinationChainId:t,deliveryToken:n,deliveryAmount:s,withdrawalAmount:o,deliveryRecipient:r,deliveryTransfers:i,requestTimestampMs:l}){const c=i?.length?i:[{token:n,recipient:r,amount:o??s}],d=c.reduce((g,y)=>g+y.amount,0n);if(d<=0n)return null;const u=l??Date.now(),f=BigInt(Math.floor(u/1e3)),m=lu(A.keccak256(A.encodeAbiParameters([{type:"address"},{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[e??r,n,r,d,BigInt(t),BigInt(u)])));return{chainId:v.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:[{to:v.ZERO_ADDRESS,value:0n,data:A.encodeFunctionData({abi:v.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${t}`,idempotenceKey:m,nbf:0n,exp:f+3600n,metadata:"{}",transfers:c.map(g=>({token:A.getAddress(g.token).toLowerCase(),to:A.getAddress(g.recipient).toLowerCase(),amount:g.amount}))}]})}]}}const as=pt;function cu(e){const{asset:t,amount:n,recipient:s,owner:o,onSuccess:r}=e,i=t?.chainId??e.sourceChains?.[0]??0,l=p.useMemo(()=>v.getTokensForChain(i).find(w=>w.equivalenceGroup==="USDC"),[i]),[c,d]=p.useState(null),u=p.useCallback((w,C)=>{if(!t||n<=0n||n>t.balance||!s||!o||h.addressesEqual(o,s))throw new Error("Enter a valid withdrawal amount and recipient.");if(C.chainId!==t.chainId||!h.addressesEqual(C.executorAddress??C.userAddress,o))throw new Error("The withdrawal wallet or network changed. Review the withdrawal again.");return Ha(t.chainId,t.address,[{recipient:s,amount:n}]).calls},[t?.address,t?.chainId,t?.balance,n,s,o]),f=p.useMemo(()=>c?{asset:c,amount:"0"}:null,[c]),m=rs({enabled:e.enabled&&!!l&&!!t&&n>0n&&!!s&&!!o&&!h.addressesEqual(o,s),feeOnlyAction:!0,isZeroAmountPay:!0,amountDirection:"output",paymentAmount:"0",destinationToken:{address:l?.address??v.ZERO_ADDRESS,symbol:l?.symbol??"USDC",decimals:l?.decimals??6,chainId:i},recipient:o,selectedAsset:f,feeFunding:[],sourceChains:e.sourceChains,includeCrossChainEmbeddedAssets:!0,includeExternalWalletAssets:!1,feeExecutionMode:"backend-transfer",buildActionCalls:u,buildSpicenetBatch:bi,onError:(w,C)=>e.onError?.(w.message,C),onSuccess:async()=>{t&&(window.dispatchEvent(new CustomEvent("withdraw-completed")),await r?.({token:t.symbol,amount:A.formatUnits(n,t.decimals),chainId:i}))}}),g=`${e.enabled}:${t?.chainId}:${t?.address}:${n}:${s}`,y=p.useRef(g);p.useEffect(()=>{y.current===g||m.status.isExecuting||(y.current=g,(m.status.step==="success"||m.status.paymentResult?.status==="success")&&m.resetAfterSuccess())},[g,m.status.isExecuting,m.status.step,m.status.paymentResult?.status,m.resetAfterSuccess]);const x=p.useMemo(()=>l?m.assets.displayAssets.flatMap(w=>{if(w.location==="external")return[];const C=t&&w._source==="wallet"&&w.chainId===t.chainId&&h.addressesEqual(w.address,t.address)?n:0n,b=w.balance-C;return b>0n?[{...w,balance:b,balanceFormatted:Number(A.formatUnits(b,w.decimals))}]:[]}).sort((w,C)=>{const b=I=>I._source==="wallet"&&I.chainId===i?0:I._source==="spice"?1:2;return b(w)-b(C)||C.balanceFormatted-w.balanceFormatted}):[],[m.assets.displayAssets,l,i,t?.address,t?.chainId,n]);return p.useEffect(()=>{if(!e.enabled||m.status.isExecuting)return;const w=(c&&x.find(C=>as(C)===as(c)))??x[0]??null;(!c||!w||as(c)!==as(w)||c.balance!==w.balance)&&d(w)},[e.enabled,m.status.isExecuting,x,c]),{supply:m,candidates:x,source:c,setSource:d,feeToken:l,sourceKey:as}}const Ci=h.font.ui,du=({label:e,loading:t,balance:n,dark:s,dk:o})=>{const r=s?o.textSecondary:"#7D7C7B",i=s?o.textSecondary:"#71757A";return a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[a.jsx("span",{style:{fontFamily:Ci,fontSize:"17px",fontWeight:500,color:r,lineHeight:"24px"},children:e}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",fontFamily:Ci,fontSize:"13px",fontWeight:500,color:i,lineHeight:"16px"},children:["Balance:"," ",t?"...":n===null?"\u2014":h.formatBalance(n)]})]})},vi=({isOpen:e,position:t,title:n,items:s,selectedId:o,onSelect:r,portalAttribute:i})=>{const{dark:l,dk:c,primaryColor:d}=h.useSpiceBrand(),[u,f]=p.useState(null),[m,g]=p.useState(!1);return p.useEffect(()=>{if(!e){g(!1);return}const y=requestAnimationFrame(()=>{requestAnimationFrame(()=>g(!0))});return()=>cancelAnimationFrame(y)},[e]),!e||!t||s.length===0?null:Fn.createPortal(a.jsxs("div",{[`data-${i}-popover`]:"true",style:{position:"fixed",top:`${t.top}px`,left:`${t.left}px`,opacity:m?1:0,transform:m?"scale(1) translateY(0)":"scale(0.96) translateY(-6px)",transition:`opacity 200ms ${h.easing.out}, transform 200ms ${h.easing.out}`,backgroundColor:l?c.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 ${c.cardBorder}`,minWidth:"220px",zIndex:h.z.dropdown,fontFamily:h.font.mono},children:[a.jsx("div",{style:{marginBottom:"6px"},children:a.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:l?c.textPrimary:"#0e0d0b",textTransform:"uppercase",letterSpacing:"1px"},children:n})}),a.jsx("div",{style:{borderBottom:`1px solid ${c.cardBorder}`,marginBottom:"6px"}}),a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"2px"},children:s.map(y=>{const x=o===y.id,w=u===y.id;return a.jsxs("button",{onClick:C=>{C.stopPropagation(),r(y.id)},onMouseEnter:()=>f(y.id),onMouseLeave:()=>f(null),style:{display:"flex",alignItems:"center",gap:"8px",padding:"6px 4px",borderRadius:"8px",border:"none",cursor:"pointer",backgroundColor:x?l?c.hoverBg:"#f3f4f6":w?l?c.cardBg:"#f9fafb":"transparent",transition:"background-color 0.15s",width:"100%",fontFamily:h.font.mono},children:[y.icon&&a.jsx("img",{src:y.icon,alt:y.label,style:{width:"22px",height:"22px",borderRadius:"50%"}}),a.jsx("span",{style:{fontSize:"13px",fontWeight:x?700:500,textTransform:"uppercase",color:l?c.textPrimary:"#0e0d0b",letterSpacing:"0.5px",flex:1,textAlign:"left"},children:y.label}),y.detail&&a.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:c.textSecondary},children:y.detail}),x&&a.jsx(ga,{color:d,style:{flexShrink:0}})]},y.id)})})]}),document.body)},Ms=h.font.ui,uu=h.font.mono,pu=170,fu=({header:e,amount:t,receiveAmountDisplay:n,receiveUsdEstimate:s,selectedDestToken:o,destTokenSymbol:r,destChainName:i,destChainLogo:l,compatibleDestinationChains:c,networkSwitchRef:d,onOpenNetworkPopover:u,showNetworkPopover:f,setShowNetworkPopover:m,networkPopoverPos:g,selectedChainId:y,setSelectedChainId:x,dark:w,dk:C})=>{const b=w?C.cardBg:"#E9E9E9",I=w?C.cardBorder:"#C6C6C6",S=w?C.textSecondary:"#71757A",k=w?C.textPrimary:"#0E0D0B",E=w?C.cardBorder:"#C5C5C4",F=w?"rgba(255,255,255,0.08)":"#D4D3D3",T=r.length>8?"14px":r.length>6?"16px":"18px";return a.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,a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[a.jsxs("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[a.jsx(vn,{element:"div",value:n,title:n,fontFamily:Ms,color:t?k:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,overflow:"wrap"}),a.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:S,fontFamily:Ms,marginTop:"10px"},children:s})]}),a.jsxs("div",{style:{width:`${pu}px`,flexShrink:0,display:"flex",flexDirection:"column",alignItems:"stretch",gap:"8px"},children:[a.jsxs("div",{style:{backgroundColor:"transparent",border:`1px solid ${E}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px"},children:[a.jsx("img",{src:o?.logoURI||Wl,alt:r,style:{width:"24px",height:"24px",borderRadius:"50%"}}),a.jsx("span",{style:{fontSize:T,fontWeight:500,color:k,lineHeight:"1.3",fontFamily:Ms,flex:1,minWidth:0,letterSpacing:0},children:r})]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:F,borderTop:`1px solid ${E}`},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[l&&a.jsx("img",{src:l,alt:i,style:{width:"13px",height:"13px",borderRadius:"50%",flexShrink:0}}),a.jsx("span",{style:{fontSize:"11px",fontWeight:400,color:k,fontFamily:Ms,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:i})]}),a.jsx("button",{ref:d,onClick:D=>{D.stopPropagation(),u(d.current)},style:{background:"none",border:"none",cursor:c.length>1?"pointer":"not-allowed",padding:"0 0 0 8px",fontSize:"9.5px",fontFamily:uu,color:S,textDecoration:"underline",fontWeight:600,opacity:c.length>1?1:.45},children:"Switch"}),a.jsx(vi,{isOpen:f,position:g,title:"SELECT NETWORK",portalAttribute:"network",items:c.map(D=>{const j=h.getChainConfig(D);return{id:String(D),label:j?.displayName||String(D),icon:mn[D]||Vn}}),selectedId:y!==null?String(y):null,onSelect:D=>{x(Number(D)),m(!1)}})]})]}),a.jsx("div",{style:{minHeight:"14px"}})]})]})]})},mu=h.font.ui,xn=h.font.mono,hu=({show:e,onToggle:t,showCustomAddress:n,setShowCustomAddress:s,customRecipient:o,setCustomRecipient:r,externalAddress:i,recipientAddress:l,destChainName:c,destChainLogo:d,compatibleDestinationChains:u,txDetailsChainSwitchRef:f,onOpenNetworkPopover:m,sourceChainLabel:g,sourceDetailsLogo:y,sourceTokenLabel:x,amount:w,totalSourceDebitDisplay:C,receiveAmountDisplay:b,destTokenSymbol:I,shouldQuoteWithdrawGas:S,estimatingFee:k,feeError:E,displayedGasFee:F,selectedDestToken:T,theme:D,styles:j,dark:U,dk:P})=>{const O=U?P.textSecondary:"#71757A",q=U?P.textPrimary:"#0E0D0B",R=u.length>1,W=n&&o?A.isAddress(o)?h.truncateAddress(o):o:l?h.truncateAddress(l):"\u2014";return a.jsxs(a.Fragment,{children:[a.jsxs("div",{onClick:t,style:{display:"flex",alignItems:"center",gap:"6px",marginBottom:e?"10px":"0",cursor:"pointer",userSelect:"none"},children:[a.jsx("span",{style:{fontSize:"13px",color:O,fontFamily:mu,fontWeight:600},children:"Transaction Details"}),a.jsx(Zc,{size:12,color:O,style:{transform:e?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s"}})]}),e&&a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"7px"},children:[a.jsxs("div",{children:[a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[a.jsx("span",{style:{fontSize:"12px",color:O,fontFamily:xn,fontWeight:500,letterSpacing:"0.03em"},children:"TO"}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[a.jsx("span",{style:{fontSize:"13px",color:q,fontFamily:xn,fontWeight:500},children:W}),a.jsx("button",{onClick:()=>{s(K=>!K),!n&&i&&r(i)},style:{background:"none",border:"none",cursor:"pointer",padding:"0",fontSize:"9.5px",fontFamily:xn,color:O,textDecoration:"underline",fontWeight:600},children:n?"Reset":"Switch"})]})]}),n&&a.jsxs("div",{style:{marginTop:"6px"},children:[a.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:xn,fontWeight:700,letterSpacing:0,textTransform:"uppercase"},children:"CAUTION: ENTERING AN INCORRECT ADDRESS WILL RESULT IN LOSS OF FUNDS"}),a.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:K=>r(K.target.value),placeholder:"0x...",style:{width:"100%",padding:"8px 10px",borderRadius:"6px",border:`1px solid ${o&&!A.isAddress(o)?U?P.errorBorder:"#fca5a5":U?P.inputBorder:"#d1d5db"}`,backgroundColor:U?P.inputBg:"#f9fafb",color:U?P.inputText:"#111827",fontSize:"12px",fontFamily:xn,outline:"none",boxSizing:"border-box"}}),o&&!A.isAddress(o)&&a.jsx("span",{style:{fontSize:"11px",color:P.errorText,marginTop:"3px",display:"block"},children:"Invalid address"})]})]}),a.jsx(gn,{palette:P,labelColor:O,valueColor:q,label:"RECEIVING CHAIN",value:a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"7px"},children:[d&&a.jsx("img",{src:d,alt:c,style:{width:"14px",height:"14px",borderRadius:"50%"}}),a.jsx("span",{style:{fontSize:"13px",color:q,fontWeight:500,fontFamily:xn,textTransform:"uppercase"},children:c}),a.jsx("button",{ref:f,onClick:K=>{K.stopPropagation(),m(f.current)},style:{background:"none",border:"none",cursor:R?"pointer":"not-allowed",padding:"0",fontSize:"9.5px",fontFamily:xn,color:O,textDecoration:"underline",fontWeight:600,opacity:R?1:.45},children:"Switch"})]})}),a.jsx(gn,{palette:P,labelColor:O,valueColor:q,label:"REQUESTED WITHDRAWAL",value:a.jsxs(Ho,{logo:y||null,alt:g,primaryText:q,children:[w||"0"," ",x]})}),S&&a.jsx(gn,{palette:P,labelColor:O,valueColor:q,label:"TOTAL SOURCE DEBIT",value:a.jsxs(Ho,{logo:y||null,alt:g,primaryText:q,children:[C," ",x]})}),a.jsx(gn,{palette:P,labelColor:O,valueColor:q,label:"YOU RECEIVE",value:a.jsxs(Ho,{logo:d,alt:c,primaryText:q,gap:"4px",children:[b," ",I]})}),S&&a.jsxs(a.Fragment,{children:[a.jsx(gn,{palette:P,labelColor:O,label:"EST. NETWORK FEE",valueColor:E?"#f87171":q,value:k?"Estimating...":E?"Unavailable":F!==null&&T?`${Oo(F,T.decimals)} ${T.symbol}`:"Estimating..."}),E&&a.jsx($t,{variant:"error",size:"compact",palette:P,fontFamily:j?.fontFamily||D.typography.fontFamily,children:E})]})]})]})},gu=p.memo(hu),Ho=({logo:e,alt:t,primaryText:n,gap:s="6px",children:o})=>a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:s},children:[e&&a.jsx("img",{src:e,alt:t,style:{width:"13px",height:"13px",borderRadius:"50%"}}),a.jsx("span",{style:{fontSize:"13px",color:n,fontWeight:500,fontFamily:xn},children:o})]}),is=h.font.ui,xu=170,yu=({header:e,amount:t,setAmount:n,isInsufficient:s,sourceAmountDecimals:o,selectedSourceAsset:r,resolvedSelectedSourceAsset:i,spiceAssets:l,setSelectedSourceAsset:c,sourceUsdEstimate:d,sourceTokenLabel:u,sourceChainLabel:f,totalSelectedBalance:m,showSourceTokenPopover:g,setShowSourceTokenPopover:y,tokenPopoverPos:x,setTokenPopoverPos:w,tokenTriggerRef:C,primaryColor:b,dark:I,dk:S})=>{const k=I?S.cardBg:"#E9E9E9",E=I?S.cardBorder:"#C6C6C6",F=I?S.textSecondary:"#71757A",T=I?S.textPrimary:"#0E0D0B",D=I?S.cardBorder:"#C5C5C4",j=I?"rgba(255,255,255,0.08)":"#D4D3D3",U=u.length>8?"14px":u.length>6?"16px":"18px";return a.jsxs("div",{style:{backgroundColor:k,border:`1px solid ${E}`,borderRadius:"7px",padding:"14px 16px 12px 16px",minHeight:"138px",display:"flex",flexDirection:"column",gap:"6px",position:"relative"},children:[e,a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[a.jsxs("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[a.jsx(vn,{element:"input",ariaLabel:"Withdraw amount",ariaInvalid:s,dataSpiceflowFocus:!0,value:t,onChange:P=>{const O=P.target.value;if(O===""){n("");return}/^\d*\.?\d*$/.test(O)&&n(h.parseNumericInput(O.startsWith(".")?`0${O}`:O,o??r?.decimals))},placeholder:"0.0",fontFamily:is,color:s?"#ef4444":t?T:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,style:{width:"100%"}}),a.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:F,fontFamily:is,marginTop:"10px"},children:d})]}),a.jsx("div",{style:{width:`${xu}px`,flexShrink:0},children:a.jsxs("div",{style:{backgroundColor:"transparent",border:`1px solid ${D}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[a.jsxs("div",{ref:C,onClick:P=>{if(P.stopPropagation(),!g&&C.current){const O=C.current.getBoundingClientRect(),q=220,R=16;w({top:O.bottom+8,left:Math.min(Math.max(R,O.right-q),window.innerWidth-q-R)})}y(O=>!O)},style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px",cursor:"pointer"},children:[a.jsx("img",{src:io,alt:u,style:{width:"24px",height:"24px",borderRadius:"50%"}}),a.jsx("span",{style:{fontSize:U,fontWeight:500,color:T,lineHeight:"1.3",fontFamily:is,flex:1,minWidth:0,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",letterSpacing:0},children:u}),a.jsx(On,{size:15,color:T,strokeWidth:2.25})]}),a.jsx(vi,{isOpen:g,position:x,title:"SELECT TOKEN",portalAttribute:"token",items:(l||[]).map(P=>({id:P.receiptTokenId||P.address,label:P.displaySymbol||P.receiptTokenName||P.symbol,icon:io,detail:h.formatBalance(P.balanceFormatted)})),selectedId:i?.receiptTokenId||i?.address||null,onSelect:P=>{const O=(l||[]).find(q=>(q.receiptTokenId||q.address)===P);O&&(c(O),n("")),y(!1)}}),a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:j,borderTop:`1px solid ${D}`},children:a.jsx("span",{style:{fontSize:"11px",fontWeight:400,color:T,fontFamily:is,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:f})})]})})]}),a.jsxs("div",{style:{minHeight:"18px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[s?a.jsx("span",{style:{fontSize:"12px",color:S.errorText,fontFamily:is,fontWeight:500},children:"Insufficient Balance"}):a.jsx("span",{}),a.jsx("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0px",minHeight:"32px",marginRight:"-9px"},children:[0,25,50,75,100].map((P,O)=>{const q=O===4,R=parseFloat(t)||0,W=m>0&&Math.abs(R/m*100-P)<1;return a.jsx("button",{type:"button","aria-label":`Set amount to ${P}%`,"aria-pressed":W,onClick:()=>{const K=i?.balance??0n;n(P===0?"":A.formatUnits(K*BigInt(P)/100n,o??6))},title:`${P}%`,disabled:m===0,"data-spiceflow-focus":!0,style:{width:"32px",height:"32px",padding:"9px",border:"none",backgroundColor:"transparent",cursor:m===0?"not-allowed":"pointer",opacity:W?1:.5,transition:"opacity 0.15s ease",display:"flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box"},children:a.jsx(Fo,{pct:P,isMax:q,primaryColor:b,dark:I,fillColor:I?S.textSecondary:"#3C3E42"})},P)})})]})]})},wu=({dark:e,dk:t})=>a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[a.jsx("img",{src:xo,alt:"","aria-hidden":"true",style:{width:"13px",height:"13px",flexShrink:0,...e?{filter:"invert(0.6)"}:{}}}),a.jsx("p",{style:{fontSize:"13px",color:e?t.textSecondary:"#979AA0",margin:"0",lineHeight:"1.4",fontFamily:h.font.ui},children:"Withdraw collateral from your account to 10+ EVM blockchains."})]}),bu=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,styles:s,onWithdrawExecute:o,onWithdrawSuccess:r,onWithdrawError:i,availableTokens:l,initialSourceAssetId:c,walletAssets:d,buildSpicenetBatch:u})=>{const f=p.useContext(h.SpiceFlowProviderContext);if(!f)return a.jsx("div",{children:"Error: SpiceWithdraw must be used within SpiceFlowProvider"});const m=f.mode||"7702",g=m==="presign"||m==="ondemand",y=f.supportedChainIds,x=f.allowedTokens,w=!!d,C=d?.initialAsset,b=p.useMemo(()=>[...d?.extraAssets??[],...C?[C]:[]].map(se=>({address:se.address,chainId:se.chainId,symbol:se.symbol,decimals:se.decimals})),[d?.extraAssets,C]),I=f.isWhitelistGateActive,{theme:S,dark:k,dk:E}=h.useSpiceBrand(s),F=f.network,T=()=>g?"select":"provider-login",[D,j]=p.useState(T()),[U,P]=p.useState(!1),[O,q]=p.useState(null),[R,W]=p.useState(null),[K,G]=p.useState(""),[_,X]=p.useState(!1),[Q,te]=p.useState(!1),[B,$]=p.useState(!1),[ie,L]=p.useState(""),[H,fe]=p.useState(!0),Z=p.useRef(null),he=p.useRef(null),ge=p.useRef(null),[ce,Ae]=p.useState(null),[N,J]=p.useState(null),M=h.useWallet(),{isReady:Y,isAuthenticated:ue,address:We}=M,Ce=f?.embeddedWalletAddress,{address:oe,chainId:Ee}=Zt.useAccount(),we=f.externalWalletAddress||oe,[Pe,Qe]=p.useState(!1),[it,ze]=p.useState(null),Je=p.useRef(i);Je.current=i;const Re=p.useCallback(se=>{ze(se),typeof se=="string"&&se&&Je.current?.(se,h.getRelayerErrorDetail(se))},[]),[ot,_e]=p.useState(null),Ue=p.useRef(null),Le=p.useRef(!0),ct=p.useRef(null);p.useEffect(()=>(Le.current=!0,()=>{Le.current=!1}),[]);const{execute:Me,estimate:Ze}=Es(),[De,Ge]=p.useState(null),[qe,$e]=p.useState(null),[Se,Ne]=p.useState(!1),[ft,ne]=p.useState(null),{assets:Te,loading:xe,error:me,refresh:ee}=Dn({owner:Ce,role:"holding",includeWalletAssets:w,additionalSourceTokens:b,enabled:e&&!!Ce}),ye=p.useMemo(()=>{if(I)return[];const se=(ae,Ie)=>(Ie.balanceUsd||0)-(ae.balanceUsd||0);return(Te??[]).filter(ae=>ae.balance>0n&&bn(ae,"holding",{allowedTokens:x,isWhitelistGateActive:I}).eligible).sort(se)},[Te,x,I]),Fe=p.useMemo(()=>[...new Set([...y??[],...Object.keys(l??{}).map(Number),...(ye||[]).map(se=>se.chainId),...(ye||[]).flatMap(se=>Object.keys(se.chainTokens??{}).map(ae=>{const[,Ie]=ae.split(":"),Ve=Number(Ie);return Number.isFinite(Ve)?Ve:null}).filter(ae=>ae!==null))])].filter(se=>h.getChainConfig(se)?.network===F),[y,l,ye,F]),Ye=p.useMemo(()=>{if(l)return l;const se={};for(const ae of ye||[]){const Ie=Object.entries(ae.chainTokens??{});if(Ie.length>0){for(const[Ve,st]of Ie){const[yt,Ct,Dt]=Ve.split(":");if(yt!=="evm"||!Ct||!Dt)continue;const It=Number(Ct);if(!Number.isFinite(It))continue;const vt=Dt.startsWith("0x")?Dt.toLowerCase():`0x${Dt.toLowerCase()}`,kt=h.getChainConfig(It)?.supportedTokens?.find(Bt=>h.addressesEqual(Bt.address,vt));kt&&so(ae,vt,It)&&(se[It]||(se[It]=[]),se[It].find(Bt=>h.addressesEqual(Bt.address,vt))||se[It].push({address:vt,symbol:kt?.symbol||st?.name||ae.symbol,name:kt?.name||st?.name||ae.displayName||ae.name||ae.symbol,decimals:kt?.decimals??st?.decimals??ae.decimals,logoURI:kt?.logo||ae.logoURI}))}continue}se[ae.chainId]||(se[ae.chainId]=[]),se[ae.chainId].find(Ve=>h.addressesEqual(Ve.address,ae.address))||se[ae.chainId].push({address:ae.address,symbol:ae.symbol,name:ae.displayName||ae.name||ae.symbol,decimals:ae.decimals,logoURI:ae.logoURI})}return se},[l,ye]),je=p.useCallback((se,ae)=>{const Ie=yd(se,ae,ae?Ye[ae]??[]:[]);return!se||!Ie||!ae||se._source==="wallet"&&ae!==se.chainId?null:bn(se,"withdraw-destination",f,{...Ie,chainId:ae}).eligible?Ie:null},[Ye,f.allowedTokens,f.rpcOverrides,f.isWhitelistGateActive]),z=p.useMemo(()=>O?ye.find(se=>pt(se)===pt(O))??null:null,[O,ye]),ke=z?z.balanceError:me,be=z?._source==="wallet",He=p.useMemo(()=>{if(!z)return[];const se=Object.keys(z.chainTokens??{}).map(ae=>sn(ae)?.chainId??null).filter(ae=>ae!==null);return Array.from(new Set([...se,z.chainId,...Fe].filter(Number.isFinite))).filter(ae=>h.getChainConfig(ae)?.network===F&&je(z,ae)!==null)},[z,Fe,je,F]),At=p.useMemo(()=>{if(!z||typeof window>"u")return null;const se=`spiceflow:withdraw-chain:${z.receiptTokenId||z.address.toLowerCase()}`,ae=window.localStorage.getItem(se),Ie=ae?Number(ae):null;return Ie!==null&&Number.isFinite(Ie)&&He.includes(Ie)?Ie:null},[z,He]),Et=p.useMemo(()=>z?At!==null?At:Ee&&He.includes(Ee)?Ee:z.chainId&&He.includes(z.chainId)?z.chainId:He[0]??null:Fe[0]??null,[z,At,Ee,He,Fe]),ve=p.useMemo(()=>je(z,R),[je,z,R]);p.useEffect(()=>{e&&(q(null),G(""))},[e,c,C?.address,C?.chainId]),p.useEffect(()=>{if(!e||!ye.length||O)return;const se=C?ye.find(ae=>ae.chainId===C.chainId&&h.addressesEqual(ae.address,C.address)&&ae._source==="wallet"):c?ye.find(ae=>ae.receiptTokenId===c):ye[0];q(se??null),G("")},[e,ye,O,c,C]),p.useEffect(()=>{z&&(R===null||!He.includes(R))&&W(Et)},[z,R,Et,He]),p.useEffect(()=>{if(!_&&!Q)return;const se=ae=>{const Ie=ae.target;_&&!Z.current?.contains(Ie)&&!he.current?.contains(Ie)&&!Ie?.closest?.("[data-network-popover]")&&X(!1),Q&&!ge.current?.contains(Ie)&&!Ie?.closest?.("[data-token-popover]")&&te(!1)};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[_,Q]);const mt=p.useCallback(se=>{if(!se||He.length<=1)return;const ae=se.getBoundingClientRect(),Ie=220,Ve=16;Ae({top:ae.bottom+8,left:Math.min(Math.max(Ve,ae.right-Ie),window.innerWidth-Ie-Ve)}),X(st=>!st)},[He.length]),ht=p.useCallback(()=>fe(se=>!se),[]);p.useEffect(()=>{if(!z||R===null||typeof window>"u")return;const se=`spiceflow:withdraw-chain:${z.receiptTokenId||z.address.toLowerCase()}`;window.localStorage.setItem(se,String(R))},[z,R]);const wt=B?A.isAddress(ie)?ie:void 0:we||(be?void 0:Ce),Gt=Dn({owner:wt,role:"holding",includeRollupAssets:!1,sourceChains:R?[R]:[],additionalSourceTokens:ve&&R?[{...ve,chainId:R}]:[],enabled:e&&!!wt&&!!ve&&!!R}),yn=Gt.walletAssets.find(se=>h.addressesEqual(se.owner,wt)&&se.chainId===R&&h.addressesEqual(se.address,ve?.address)),ln=z?.balanceFormatted??0,dt=z?.displaySymbol||z?.receiptTokenName||z?.symbol||"Select token",Rt=z?.displayChainName||(be?h.getChainConfig(z.chainId)?.displayName:"Spicenet")||"Network",rt=z?.receiptTokenDecimals??z?.decimals,Be=p.useMemo(()=>{if(!ve||rt===void 0)return 0n;try{return Pt(K||"0",rt)}catch{return 0n}},[K,ve,rt]),jt=p.useMemo(()=>!ve||rt===void 0?0n:za(Be,rt,ve.decimals),[ve,rt,Be]),Ut=p.useMemo(()=>{if(be)return 0n;const se=qe??De;return!se||se<=0n||!ve||rt===void 0?0n:za(se,ve.decimals,rt)},[be,qe,De,ve,rt]),Tt=p.useMemo(()=>Be+Ut,[Be,Ut]),qt=qe??De,Ke=cu({enabled:e&&be,asset:be?z:null,amount:Be,recipient:wt,owner:Ce,sourceChains:y,onSuccess:r,onError:i}),et=Ke.supply,gt=Pe||be&&(et.status.isExecuting||et.status.finalizing),Wt=et.status.step==="success"||et.status.paymentResult?.status==="success",nt=p.useCallback(se=>{if(be||!R||!ve)return[];if(Be===0n||jt===0n||!wt)return[];const ae=Array.isArray(se)?se.filter(yt=>yt.amount>0n):[{token:ve.address,recipient:wt,amount:se??jt}],Ie=ae.reduce((yt,Ct)=>yt+Ct.amount,0n);if(Ie<=0n)return[];const Ve={chainId:R,calls:[],tokenTransfers:ae.map(yt=>({from:"escrow",to:yt.recipient,token:yt.token,amount:yt.amount}))};if(!u)return[Ve];const st=u({destinationChainId:R,deliveryToken:ve.address,deliveryAmount:Ie,deliveryRecipient:wt,deliveryTransfers:ae,requestTimestampMs:ct.current??Date.now()});return st?[st,Ve]:[Ve]},[be,R,ve,Be,jt,wt,u]),tt=p.useMemo(()=>nt(),[nt]),de=p.useMemo(()=>Ad(tt,ve?.address),[tt,ve?.address]),xt=p.useRef(null),_t=!be&&e&&!g&&!Pe&&!!ve&&!!R&&Be!==0n;yo({shouldRun:_t&&tt.length>0&&!!de,deps:[_t,tt.length>0,de],delayMs:500,onSkip:()=>{xt.current=null,Ge(null),ne(null),Ne(_t&&tt.length===0)},onCleanup:()=>Ne(!1),run:async({isCurrent:se,signal:ae})=>{const Ie=de;Ne(!0),ne(null);try{const Ve=await Id({batches:tt,tokenAddress:ve.address,chainId:R,estimate:Ze,signal:ae});if(!se())return;xt.current={key:Ie,quote:Ve},Ge(Ve.gasFee)}catch(Ve){if(!se())return;xt.current=null,Ge(null),ne(Ve instanceof Error?Ve.message:"Failed to estimate gas fee")}finally{se()&&Ne(!1)}}}),p.useEffect(()=>{Pe||$e(null)},[Pe,K,R,ve?.address]);const In=p.useCallback(()=>{P(!0),j("select")},[]),An=p.useCallback(()=>{gt||t()},[t,gt]),cn=p.useRef(null);cn.current={batches:tt,walletAddress:We,recipient:wt,token:ve,chainId:R,amount:K,receiveAmountRaw:jt,gasFee:De,feeEstimate:de&&xt.current?.key===de?xt.current.quote.feeEstimate:null,isNon7702:g,buildWithdrawBatches:nt,execution:{estimate:Ze,execute:Me},ui:{setIsExecuting:Qe,setExecutionError:Re,setExecutionProgress:_e,setLockedGasFee:$e},executionContextRef:Ue,isMountedRef:Le,onWithdrawExecute:o,onWithdrawSuccess:r,buildSpicenetBatch:u};const Wn=p.useCallback(()=>(ct.current=Date.now(),Wa(cn.current)),[]),Lt=p.useCallback(()=>(ct.current=Date.now(),Sd(cn.current)),[]);if(p.useEffect(()=>{if(!e){const se=setTimeout(()=>{j(T()),P(!1),q(null),W(null),G(""),X(!1),te(!1),$(!1),L(""),Qe(!1),Re(null),_e(null),Ue.current=null},300);return()=>clearTimeout(se)}},[e,g]),p.useEffect(()=>{if(!g&&e&&D==="provider-login"&&Y&&ue&&Ce&&!U){const se=setTimeout(()=>{P(!0),j("select")},100);return()=>clearTimeout(se)}},[g,e,D,Y,ue,Ce,U]),!e)return null;if(D==="provider-login"&&!g)return a.jsx(Ro,{onAuthSuccess:In,autoTrigger:!0});if(D==="select"){const se=parseFloat(K)||0,ae=rt?Oo(Tt,rt):K||"0",Ie=!!z&&Tt>z.balance,Ve=(R?h.getChainConfig(R):null)?.displayName||"Network",st=R?mn[R]||Vn:null,yt=ve?.symbol||"\u2014",Ct=dt,Dt=ve?Oo(jt,ve.decimals):"0",It=z&&z.balanceFormatted>0?z.balanceUsd/z.balanceFormatted:void 0,vt=z?.priceStatus==="stale",kt=qa(se,It,vt),Bt=qa(parseFloat(Dt)||0,It,vt),Ln=(!B||A.isAddress(ie))&&(!be||!h.addressesEqual(wt,Ce)),dn=!g&&!be&&se>0&&ve!==null,Ot=!dn||De!==null&&!Se&&!ft,Ht=se>0&&!Ie&&!xe&&!ke&&z!==null&&R!==null&&ve!==null&&wt&&Ln&&Ot&&jt>0n&&(!be||et.canExecute&&!Wt),wn=!Ht,zn=xe?"LOADING BALANCES":ke?"BALANCES UNAVAILABLE":z===null?"NO BALANCE":se===0?"ENTER AMOUNT":Ie?"INSUFFICIENT BALANCE":dn&&!Ot?ft?"GAS UNAVAILABLE":"ESTIMATING GAS":dn&&jt===0n?"AMOUNT TOO SMALL":be&&!et.canExecute?"REVIEW FEES":"WITHDRAW",V=!!ot&&(ot.step==="success"||ot.step==="error"),re=s?.primaryColor||S.colors.primary,Oe=402,pe=(Xe,at,Kt)=>a.jsx(du,{label:Xe,loading:Kt,balance:at,dark:k,dk:E});return a.jsx(Qt,{isOpen:!0,onClose:An,title:"Withdraw",subtitle:a.jsx(wu,{dark:k,dk:E}),styles:s,theme:S,dark:k,maxWidth:"486px",footerLinkText:"Spicenet accounts \u2192",overlayDimmed:!1,closeOnBackdropClick:n,overlayContent:V?a.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:a.jsx("div",{style:{pointerEvents:"auto"},children:a.jsx(Do,{type:"withdraw",isOpen:!0,isProcessing:Pe,onRetryTx:()=>{Lt()},onNewTx:()=>{_e(null),G(""),Re(null),Ue.current=null},onClose:()=>{_e(null),Re(null),Qe(!1),Ue.current=null},onComplete:()=>{_e(null),Re(null),Qe(!1),Ue.current=null},results:[{asset:{symbol:ve?.symbol||"Token",address:ve?.address||""},txHash:ot?.txHash||"",success:ot?.step==="success",error:ot?.error,amount:K}],chainId:R??void 0,theme:S})})}):null,children:a.jsxs("fieldset",{disabled:gt,style:{border:0,minWidth:0,width:"calc(100% - 32px)",maxWidth:`${Oe}px`,margin:"0 auto",padding:"0 0 4px 0",position:"relative"},children:[a.jsxs("div",{style:{marginTop:"16px",marginBottom:"16px",display:"flex",flexDirection:"column",gap:"16px"},children:[a.jsx(yu,{header:pe("Source",ln,xe),amount:K,setAmount:G,isInsufficient:Ie,sourceAmountDecimals:rt,selectedSourceAsset:z,resolvedSelectedSourceAsset:z,spiceAssets:ye,setSelectedSourceAsset:q,sourceUsdEstimate:kt,sourceTokenLabel:Ct,sourceChainLabel:Rt,totalSelectedBalance:ln,showSourceTokenPopover:Q,setShowSourceTokenPopover:te,tokenPopoverPos:N,setTokenPopoverPos:J,tokenTriggerRef:ge,primaryColor:re,dark:k,dk:E}),a.jsx(fu,{header:pe("Destination",yn?.balanceFormatted??null,Gt.loading),amount:K,receiveAmountDisplay:Dt,receiveUsdEstimate:Bt,selectedDestToken:ve,destTokenSymbol:yt,destChainName:Ve,destChainLogo:st,compatibleDestinationChains:He,networkSwitchRef:Z,onOpenNetworkPopover:mt,showNetworkPopover:_,setShowNetworkPopover:X,networkPopoverPos:ce,selectedChainId:R,setSelectedChainId:W,dark:k,dk:E})]}),a.jsxs("div",{style:{marginBottom:S.spacing.sm},children:[a.jsx(gu,{show:H,onToggle:ht,showCustomAddress:B,setShowCustomAddress:$,customRecipient:ie,setCustomRecipient:L,externalAddress:we,recipientAddress:wt,destChainName:Ve,destChainLogo:st,compatibleDestinationChains:He,txDetailsChainSwitchRef:he,onOpenNetworkPopover:mt,sourceChainLabel:Rt,sourceDetailsLogo:io,sourceTokenLabel:Ct,amount:K,totalSourceDebitDisplay:ae,receiveAmountDisplay:Dt,destTokenSymbol:yt,shouldQuoteWithdrawGas:dn,estimatingFee:Se,feeError:ft,displayedGasFee:qt,selectedDestToken:ve,theme:S,styles:s,dark:k,dk:E}),be&&a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[a.jsx(gn,{palette:E,label:"FEE ASSET",value:a.jsxs("select",{"aria-label":"Withdrawal fee asset",disabled:gt,value:Ke.source?Ke.sourceKey(Ke.source):"",onChange:Xe=>Ke.setSource(Ke.candidates.find(at=>Ke.sourceKey(at)===Xe.target.value)??null),children:[!Ke.candidates.length&&a.jsx("option",{value:"",children:"No eligible fee balance"}),Ke.candidates.map(Xe=>a.jsxs("option",{value:Ke.sourceKey(Xe),children:[Xe.displaySymbol||Xe.symbol," \xB7"," ",Xe._source==="spice"?"Spicenet":h.getChainConfig(Xe.chainId)?.displayName]},Ke.sourceKey(Xe)))]})}),a.jsx(gn,{palette:E,label:"MAXIMUM FEE FUNDING",value:et.fees.isLoading?"Estimating...":et.fees.ready&&Ke.source&&et.amount.sourceRequiredAmount!==null?`${A.formatUnits(et.amount.sourceRequiredAmount,Ke.source.decimals)} ${Ke.source.displaySymbol||Ke.source.symbol}`:"Unavailable"}),(et.status.error||et.fees.error)&&a.jsx($t,{variant:"error",size:"compact",palette:E,children:et.status.error||et.fees.error}),et.status.finalizationError&&a.jsx(h.Button,{variant:"outline",dark:k,disabled:et.status.finalizing,onClick:()=>void et.retryFinalization(),children:"Retry application update"}),et.status.statusMsg&&a.jsx("span",{role:"status",children:et.status.statusMsg})]}),z&&!xe&&He.length===0&&a.jsx($t,{variant:"warning",size:"compact",palette:E,children:"No withdrawal networks are available for this asset."}),it&&a.jsx($t,{variant:"error",size:"compact",palette:E,fontFamily:s?.fontFamily||S.typography.fontFamily,style:{marginBottom:"12px"},children:it}),me&&a.jsxs($t,{variant:ke?"error":"warning",size:"compact",palette:E,children:[ke?"Unable to load this balance. Please try again.":"Some other balances could not be refreshed."," ",a.jsx("button",{type:"button",onClick:()=>void ee(),children:"Retry"})]}),a.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:()=>{Ht&&(be?et.submitPay():Wn())},disabled:wn||gt,theme:S,dark:k,styles:s,style:{marginTop:"8px"},children:gt?"EXECUTING...":be&&Wt?"WITHDRAWN":zn})]})]})})}return null},ki=bu,Cu=({onDepositClick:e,onWithdrawClick:t,depositDisabled:n=!1,withdrawDisabled:s=!1,primaryColor:o="#EA4B4B",dark:r=!1})=>!e&&!t?null:a.jsxs("div",{style:{display:"flex",gap:"8px"},children:[e&&a.jsx(h.Button,{variant:"outline",onClick:e,disabled:n,dark:r,styles:{button:{backgroundColor:o}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&a.jsx(h.Button,{variant:"outline",onClick:()=>t(),disabled:s,dark:r,styles:{button:{backgroundColor:o}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),vu=p.memo(Cu),ku=({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 a.jsxs("div",{children:[a.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:t.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:e.title}),a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.items.map((o,r)=>a.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:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[o.tokenLogoURI?a.jsx("img",{src:o.tokenLogoURI,alt:o.tokenSymbol,style:{width:"20px",height:"20px",borderRadius:"50%"}}):a.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)}),a.jsxs("div",{children:[a.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:t.textPrimary},children:o.tokenSymbol}),a.jsx("div",{style:{fontSize:"11px",color:t.textSecondary},children:o.label})]})]}),a.jsx("div",{style:{fontSize:"13px",fontWeight:600,color:s(o.valueColor)},children:o.displayValue})]},r))})]})},Su=p.memo(ku);var Iu="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 Au=({appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,showUsdSummary:r=!0,address:i,dk:l,dark:c=!1,showModeToggle:d,isEmbeddedMode:u=!0,onModeToggle:f})=>{const[m,g]=p.useState(!1),y=async()=>{i&&await h.copyToClipboard(i)&&(g(!0),setTimeout(()=>g(!1),2e3))},x=t==="active",w=n||(x?"Active":"Inactive"),C=x?"#10b981":"#9ca3af",b=a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[a.jsxs("div",{children:[a.jsx("strong",{children:"Embedded:"})," Deposit assets into ",e," account and use them here."]}),a.jsxs("div",{children:[a.jsx("strong",{children:"External:"})," Use assets from your connected wallet here."]})]});return a.jsxs("div",{children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[a.jsxs("div",{style:{fontSize:"13px",fontWeight:600,color:l.textPrimary},children:[e," Account"]}),d?a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[a.jsxs("button",{onClick:f,style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:c?l.hoverBg:"#f3f4f6",border:c?`1px solid ${l.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"11px",fontWeight:600,fontFamily:h.font.mono,color:l.textSecondary,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease",letterSpacing:"0.02em"},children:[a.jsx("span",{children:u?"Embedded":"External"}),a.jsx("img",{src:Iu,alt:"","aria-hidden":"true",style:{width:"11px",height:"11px",display:"block",...c?{filter:"invert(0.65)"}:{}}})]}),a.jsx(ha,{content:b,label:"Account mode info",textColor:c?l.textPrimary:"#f9fafb",backgroundColor:c?l.cardBg:"#111827",borderColor:c?l.cardBorder:"rgba(255,255,255,0.08)",accentColor:c?l.textSecondary:"#6b7280",children:a.jsx("img",{src:xo,alt:"","aria-hidden":"true",style:{width:"12px",height:"12px",display:"block",...c?{filter:"invert(0.65)"}:{}}})})]}):a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:c?l.hoverBg:x?"#ecfdf5":"#f3f4f6",border:c?`1px solid ${l.cardBorder}`:x?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[a.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:C}}),a.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:c?l.textSecondary:x?"#065f46":"#6b7280"},children:w})]})]}),r&&a.jsx("div",{style:{fontSize:"28px",fontWeight:700,color:l.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:h.formatUsd(s)}),r&&o&&a.jsx("div",{style:{fontSize:"12px",color:l.textSecondary,marginBottom:"8px"},children:o}),i&&a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[a.jsx("span",{style:{fontSize:"12px",fontFamily:h.font.mono,color:c?l.textSecondary:"#9ca3af"},children:h.truncateAddress(i)}),a.jsx("button",{onClick:y,style:{padding:"2px 6px",fontSize:"10px",fontWeight:500,backgroundColor:"transparent",color:c?l.textSecondary:"#9ca3af",border:"none",cursor:"pointer",borderRadius:"4px",transition:"background-color 150ms ease, color 150ms ease"},title:"Copy address",children:m?"Copied":"Copy"})]})]})},Eu=p.memo(Au),Fu=e=>`${e.tokenAddress}-${e.chainId}`,Tu=({spiceAssets:e,loading:t,dk:n,dark:s=!1,canDirectWithdraw:o=!1,onDirectWithdraw:r,directWithdrawState:i,onWithdrawClick:l})=>{const c={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},d={backgroundColor:n.cardBg,border:s?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return t?a.jsxs("div",{children:[a.jsx("div",{style:c,children:"Idle Balances"}),[1,2].map(u=>a.jsx("div",{style:{...d,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},u))]}):e.length===0?a.jsxs("div",{children:[a.jsx("div",{style:c,children:"Idle Balances"}),a.jsx("div",{style:{...d,padding:"16px",textAlign:"center",fontSize:"13px",color:s?n.textSecondary:"#9ca3af"},children:"No assets yet. Deposit to get started."})]}):a.jsxs("div",{children:[a.jsx("div",{style:c,children:"Idle Balances"}),a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map(u=>{const f=h.getChainConfig(u.chainId),m=u.chainDisplayName||f?.displayName||`Chain ${u.chainId}`,g=u.tokenDisplaySymbol||u.tokenDisplayName||u.tokenSymbol,y=Fu(u),x=u.receiptTokenId&&l,w=x||o&&u.directWithdraw&&!!r,C=!x&&i?.key===y?i:null,b=C?.step==="pending";return a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...d},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[u.logoURI?a.jsx("img",{src:u.logoURI,alt:u.tokenSymbol,style:{width:"24px",height:"24px",borderRadius:"50%"}}):a.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)}),a.jsxs("div",{children:[a.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:g}),a.jsx("div",{style:{fontSize:"11px",color:s?n.textSecondary:"#9ca3af"},children:m})]})]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[a.jsxs("div",{style:{textAlign:"right"},children:[a.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:Hs({balance:BigInt(u.balance),decimals:u.tokenDecimals})}),a.jsx("div",{style:{fontSize:"11px",color:C?.step==="error"?n.errorText:s?n.textSecondary:"#9ca3af"},children:C?.step==="error"?C.message||"Withdraw failed":!Number.isFinite(u.usdValue)||u.usdValue<=0?"\u2014":`${h.formatUsd(u.usdValue)}${u.priceStatus==="stale"?" (stale)":""}`})]}),w&&a.jsx("button",{onClick:()=>{b||(x?x(u.receiptTokenId):r(u))},disabled:b,title:x?"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"})]})]},u.positionId??`${u.owner??""}:${u.location??""}:${u.receiptTokenId??`${u.tokenAddress}-${u.chainId}`}`)})})]})},ju=p.memo(Tu),Bu=({pendingDeposits:e,onCompleteDeposit:t,dk:n,dark:s=!1})=>e.length===0?null:a.jsxs("div",{children:[a.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:"Pending Deposits"}),a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((o,r)=>{const i=h.getChainConfig(o.chainId)?.displayName||`Chain ${o.chainId}`;return a.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:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[a.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)}),a.jsxs("div",{children:[a.jsxs("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:[o.amount," ",o.tokenSymbol]}),a.jsxs("div",{style:{fontSize:"11px",color:n.warningText},children:["on ",i]})]})]}),a.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}-${r}`)})})]}),Ru=p.memo(Bu),Du=({appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,showUsdSummary:r,address:i,spiceAssets:l,spiceAssetsLoading:c,pendingDeposits:d,customSections:u,notice:f,onDepositClick:m,onWithdrawClick:g,depositDisabled:y,onCompleteDeposit:x,primaryColor:w,dk:C,dark:b=!1,showModeToggle:I,isEmbeddedMode:S,onModeToggle:k,showConnectExternalCta:E,onConnectExternalWallet:F,connectExternalError:T,showHowItWorks:D=!0,canDirectWithdraw:j,onDirectWithdraw:U,directWithdrawState:P})=>{const[O,q]=p.useState(!1);return a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[a.jsx(Eu,{appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,showUsdSummary:r,address:i,dk:C,dark:b,showModeToggle:I,isEmbeddedMode:S,onModeToggle:k}),f&&a.jsx("div",{style:{padding:"10px 12px",borderRadius:"8px",backgroundColor:f.tone==="warning"?b?"rgba(245, 158, 11, 0.12)":"#fffbeb":f.tone==="success"?b?"rgba(16, 185, 129, 0.12)":"#ecfdf5":C.cardBg,border:f.tone==="warning"?b?"1px solid rgba(245, 158, 11, 0.35)":"1px solid #fde68a":f.tone==="success"?b?"1px solid rgba(16, 185, 129, 0.35)":"1px solid #a7f3d0":b?`1px solid ${C.cardBorder}`:"1px solid #e5e7eb",color:f.tone==="warning"?b?"#fbbf24":"#92400e":f.tone==="success"?b?"#34d399":"#047857":C.textSecondary,fontSize:"12px",lineHeight:1.45,fontWeight:500},children:f.message}),E&&a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[a.jsx("button",{onClick:F,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:w||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:h.font.ui,transition:"opacity 150ms ease"},children:"Connect External Wallet"}),T&&a.jsx("span",{style:{fontSize:"11px",color:b?C.errorText:"#b91c1c",lineHeight:1.4},children:T})]}),a.jsx("div",{style:{height:"1px",backgroundColor:b?"#2d2d2d":"#e5e7eb"}}),a.jsx(vu,{onDepositClick:m,onWithdrawClick:g,depositDisabled:y,primaryColor:w,dark:b}),D&&a.jsxs("div",{children:[a.jsxs("button",{onClick:()=>q(!O),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:C.cardBg,border:b?`1px solid ${C.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:C.textSecondary,fontSize:"12px",fontWeight:500},children:[a.jsx("span",{children:"How It Works"}),a.jsx("span",{style:{transform:O?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),O&&a.jsxs("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:b?C.cardBg:"#f0fdf4",border:b?`1px solid ${C.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:b?C.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),a.jsx(Ru,{pendingDeposits:d,onCompleteDeposit:x,dk:C,dark:b}),a.jsx(ju,{spiceAssets:l,loading:c,dk:C,dark:b,canDirectWithdraw:j,onDirectWithdraw:U,directWithdrawState:P,onWithdrawClick:g}),u.map((R,W)=>a.jsx(Su,{section:R,dk:C,dark:b},W))]})},Ou=p.memo(Du);function Nu({dark:e,onSuccess:t,onError:n}){const{disconnect:s}=Zt.useDisconnect(),{logout:o}=Ws.usePrivy(),[r,i]=p.useState(!1);return a.jsx(h.Button,{variant:"ghost",fullWidth:!0,dark:e,loading:r,onClick:async()=>{i(!0);try{s(),await o(),t()}catch(l){n(h.sanitizeError(l,"Unable to disconnect. Please try again."))}finally{i(!1)}},children:"Disconnect"})}const Vo=380,Sn=8,Mu=[],Pu={};function Si(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function Uu(e,t){const n=new Map;Object.entries(t).forEach(([o,r])=>{if(!Number.isFinite(r)||r<=0)return;n.set(o,r),n.set(o.toUpperCase(),r);const i=Si(o);i&&n.set(i,r)});const s=[e.symbol,e.displaySymbol,e.receiptTokenName,e.name,e.displayName];for(const o of s){if(!o)continue;const r=n.get(o)??n.get(o.toUpperCase());if(r!==void 0)return r;const i=Si(o);if(!i)continue;const l=n.get(i);if(l!==void 0)return l}return 0}const Wu=({appName:e="Spice",status:t="active",statusLabel:n,customSections:s=Mu,extraAssets:o=[],tokenPrices:r={},tokenLogos:i=Pu,breakdownLabels:l=[],notice:c,styles:d,dark:u=!1,onDepositSuccess:f,onDepositClick:m,onWithdrawClick:g,onCompleteDeposit:y,showModeToggle:x=!1,defaultMode:w,showUsdSummary:C=!0,alwaysShowEmbeddedIdle:b=!1,showDisconnect:I=!1})=>{const S=p.useContext(h.SpiceFlowProviderContext),k=S?.mode!=="7702",E=!!S?.isWhitelistGateActive,F=!!S?.isWhitelistConfigured&&S?.isUserWhitelisted!==!0,T=p.useRef(!1);p.useEffect(()=>{if(!T.current){if(h.hasStoredSpiceFlowMode()){T.current=!0;return}w&&S?.setMode&&(S.setMode(w==="non7702"?"ondemand":"7702"),T.current=!0)}},[S,w]);const[D,j]=p.useState(!1),[U,P]=p.useState(null),[O,q]=p.useState({top:0,bottom:0,left:0,placement:"below"}),R=p.useRef(null),W=p.useRef(null),{address:K,isConnected:G}=h.useWallet(),_=S?.embeddedWalletAddress,X=S?.externalWalletAddress,{embeddedAddress:Q}=h.useProviderWallets(),{dark:te,primaryColor:B,dk:$}=h.useSpiceBrand(d,u),ie=k&&!X,L=!k||b,H=L?_||Q:K,fe=p.useMemo(()=>S?.supportedChainIds??v.getChainIdsByNetwork("mainnet"),[S?.supportedChainIds]),Z=Dn({owner:L?H:X,role:"holding",sourceChains:fe,additionalSourceTokens:o.filter(ne=>!ne.receiptTokenId&&(!ne.owner||h.addressesEqual(ne.owner,L?H:X))).map(ne=>({address:ne.tokenAddress,chainId:ne.chainId,decimals:ne.tokenDecimals,symbol:ne.tokenSymbol,logoURI:ne.logoURI})),includeRollupAssets:L,enabled:L?!!H:!!X}),he=Z.assets.filter(ne=>ne._source==="spice"),ge=Z.walletAssets,ce=Z.loading,Ae=Z.refresh,N=L?H:X,J=p.useMemo(()=>o.filter(ne=>!ne.owner||ne.owner.toLowerCase()===N?.toLowerCase()).map(ne=>({...ne,owner:ne.owner??N,location:ne.location??(ne.receiptTokenId?"rollup":L?"embedded":"external")})),[o,N,L]),M=p.useMemo(()=>ge.map(ne=>({owner:ne.owner,location:ne.location,positionId:pt(ne),tokenAddress:ne.address,tokenSymbol:ne.symbol,tokenDecimals:ne.decimals,chainId:ne.chainId,chainDisplayName:h.getChainName(ne.chainId),balance:ne.balance.toString(),balanceFormatted:ne.balanceFormatted,usdValue:ne.balanceUsd||0,logoURI:ne.logoURI||i[ne.symbol],directWithdraw:L})),[ge,J,i,L]),Y=p.useMemo(()=>{const ne=L?he.map(ee=>{const ye=ee.balanceUsd||0,Fe=Number.isFinite(ee.balanceFormatted)?ee.balanceFormatted:0,Ye=Uu(ee,r),je=ee.priceStatus&&Ye>0?Ye*Fe:ye>0?ye:Ye*Fe;return{owner:ee.owner,location:ee.location,positionId:pt(ee),tokenAddress:ee.address,tokenSymbol:ee.symbol,tokenDisplaySymbol:zs(ee),tokenDisplayName:Xi(ee),tokenDecimals:ee.decimals,chainId:ee.chainId,chainDisplayName:qs(ee),balance:ee.balance.toString(),balanceFormatted:ee.balanceFormatted,usdValue:je,priceStatus:Ye>0?void 0:ee.priceStatus,logoURI:ee.logoURI,receiptTokenId:ee.receiptTokenId}}):[],Te=ee=>`${ee.owner?.toLowerCase()}:${ee.location}:${ee.chainId}:${ee.receiptTokenId??v.normalizeNativeTokenAddress(ee.tokenAddress).toLowerCase()}`,xe=new Map([...Z.rollupAssets,...ge].map(ee=>[Te({...ee,tokenAddress:ee.address}),ee])),me=new Map([...ne,...M].map(ee=>[Te(ee),ee]));for(const ee of ie?[]:J){const ye=Te(ee),Fe=me.get(ye);me.set(ye,Fe?{...ee,...Fe,logoURI:ee.logoURI??Fe.logoURI,tokenDisplayName:ee.tokenDisplayName??Fe.tokenDisplayName,tokenDisplaySymbol:ee.tokenDisplaySymbol??Fe.tokenDisplaySymbol}:ee)}return[...me.values()].filter(ee=>BigInt(ee.balance)>0n&&Nr({isDiscovered:xe.get(Te(ee))?.isDiscovered,balanceUsd:ee.usdValue},!0)&&Zo(xe.get(Te(ee))??{address:ee.tokenAddress,symbol:ee.tokenSymbol,displaySymbol:ee.tokenDisplaySymbol},S?.allowedTokens)).sort((ee,ye)=>ye.usdValue-ee.usdValue)},[L,ie,he,Z.rollupAssets,r,M,J,S?.allowedTokens]),ue=p.useMemo(()=>Y.reduce((ne,Te)=>ne+Te.usdValue,0),[Y]),{pendingDeposits:We,refresh:Ce}=sa({chainIds:fe,enabled:!!K,discoverWalletBalances:!0}),oe=p.useMemo(()=>s.reduce((ne,Te)=>ne+(Te.totalValue??0),0),[s]),Ee=ue+oe,we=p.useMemo(()=>{const ne=[];ue>0&&ne.push(`${h.formatUsd(ue)} idle`);for(const Te of s){const xe=l.find(me=>me.sectionTitle===Te.title)?.label||Te.title.toLowerCase();ne.push(`${h.formatUsd(Te.totalValue??0)} ${xe}`)}return ne.join(" \xB7 ")},[ue,s,l]),Pe=p.useCallback(ne=>{y?y(ne):P(ne)},[y]),Qe=p.useCallback(()=>{P(null)},[]),it=p.useCallback(()=>{P(null),f?.()},[f]),ze=p.useCallback(()=>{if(!R.current)return;const ne=R.current.getBoundingClientRect(),Te=window.innerHeight-ne.bottom-Sn,xe=ne.top-Sn,me=Te>=400||Te>=xe?"below":"above",ee=Math.max(Sn,Math.min(ne.right-Vo,window.innerWidth-Vo-Sn)),ye=me==="below"?ne.bottom+Sn:ne.top-Sn,Fe=me==="above"?window.innerHeight-ye:0;q({top:ye,bottom:Fe,left:ee,placement:me})},[]);p.useLayoutEffect(()=>{D&&ze()},[D,ze]),p.useEffect(()=>{if(!D)return;const ne=me=>{R.current&&!R.current.contains(me.target)&&W.current&&!W.current.contains(me.target)&&j(!1)},Te=me=>{me.key==="Escape"&&j(!1)},xe=()=>ze();return document.addEventListener("mousedown",ne),document.addEventListener("keydown",Te),window.addEventListener("scroll",xe,{passive:!0}),window.addEventListener("resize",ze),()=>{document.removeEventListener("mousedown",ne),document.removeEventListener("keydown",Te),window.removeEventListener("scroll",xe),window.removeEventListener("resize",ze)}},[D,ze]);const Je=L?_||Q||K:X||K,Re=p.useCallback(()=>{S?.setMode&&S.setMode(k?"7702":"ondemand")},[S,k]),[ot,_e]=p.useState(null);let Ue=null;try{Ue=Ws.useConnectWallet({onSuccess:()=>_e(null),onError:ne=>_e(h.sanitizeError(ne,"Failed to connect wallet."))}).connectWallet}catch{Ue=null}const Le=p.useCallback(()=>{Ue&&(j(!1),_e(null),Ue({walletChainType:"ethereum-only"}))},[Ue]),ct=!X&&!!Ue,Me=p.useCallback(()=>{j(!1),m?.()},[m]),Ze=p.useCallback(ne=>{j(!1),g?.(ne)},[g]),De=p.useCallback(ne=>{j(!1),Pe(ne)},[Pe]),[Ge,qe]=p.useState(null),$e=L&&!!X&&!h.addressesEqual(N,X),Se=p.useCallback(ne=>{const Te=ge.find(xe=>xe.chainId===ne.chainId&&h.addressesEqual(xe.address,ne.tokenAddress));Te&&(j(!1),qe(Te))},[ge]);if(typeof window>"u")return null;const Ne=a.jsxs("button",{ref:R,onClick:()=>j(!D),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:te?$.hoverBg:"#ffffff",border:te?`1px solid ${$.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:h.font.ui,color:te?$.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:te?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[a.jsxs("span",{children:[e," Account"]}),G&&C&&a.jsxs("span",{style:{color:te?$.textSecondary:"#6b7280"},children:["\xB7 ",h.formatUsd(Ee)]}),a.jsx("span",{style:{fontSize:"10px",color:te?$.textSecondary:"#9ca3af",transform:D?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),ft=D?Fn.createPortal(a.jsxs(a.Fragment,{children:[a.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:h.z.popover},onClick:()=>j(!1)}),a.jsxs("div",{ref:W,style:{position:"fixed",top:O.placement==="below"?`${O.top}px`:"auto",bottom:O.placement==="above"?`${O.bottom}px`:"auto",left:`${O.left}px`,width:`${Vo}px`,maxWidth:`calc(100vw - ${Sn*2}px)`,maxHeight:"80vh",backgroundColor:te?$.shell:"#ffffff",border:te?`1px solid ${$.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:te?"0 10px 40px rgba(0, 0, 0, 0.5)":"0 10px 40px rgba(0, 0, 0, 0.12)",zIndex:h.z.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${h.easing.out}`},children:[a.jsx(Ou,{appName:e,status:t,statusLabel:n,totalUsdValue:Ee,breakdownSubtitle:we,showUsdSummary:C,address:L?Je:K,spiceAssets:Y,spiceAssetsLoading:ce,pendingDeposits:We,customSections:s,notice:c,onDepositClick:m?Me:void 0,onWithdrawClick:g?Ze:void 0,depositDisabled:F,onCompleteDeposit:De,primaryColor:B,dk:$,dark:te,showModeToggle:x,isEmbeddedMode:!k,onModeToggle:Re,showConnectExternalCta:ct,onConnectExternalWallet:Le,connectExternalError:ot,showHowItWorks:!E,canDirectWithdraw:$e,onDirectWithdraw:Se}),I&&G&&a.jsx("div",{style:{padding:"0 16px 16px"},children:a.jsx(Nu,{dark:te,onSuccess:()=>j(!1),onError:_e})})]}),a.jsx("style",{children:`
|
|
44
44
|
@keyframes accountDisplayFadeIn {
|
|
45
45
|
from { opacity: 0; transform: translateY(-4px); }
|
|
46
46
|
to { opacity: 1; transform: translateY(0); }
|