@spicenet-io/spiceflow-ui 4.14.1 → 4.14.2
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/auth-privy.js +1 -1
- package/dist/index.cjs.js +3 -3
- package/dist/index.js +3 -3
- package/package.json +1 -1
- package/README.md +0 -486
- /package/dist/{privy-CTIfxFeM.js → privy-B7TjILWd.js} +0 -0
package/dist/index.cjs.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
(function(){if(typeof document==="undefined"||document.getElementById("spiceflow-styles"))return;var s=document.createElement("style");s.id="spiceflow-styles";s.textContent="@keyframes spiceflow-spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}@keyframes spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}@media (prefers-reduced-motion:reduce){*,:after,:before{animation-duration:.001ms!important;animation-iteration-count:1!important;scroll-behavior:auto!important;transition-duration:.001ms!important}}.spiceflow-focus-ring:focus-visible,[data-spiceflow-focus]:focus-visible{border-radius:4px;outline:2px solid currentColor;outline-offset:2px}@media (forced-colors:active){.spiceflow-focus-ring:focus-visible,[data-spiceflow-focus]:focus-visible{outline:2px solid Highlight}}.ibm-plex-mono-thin{font-weight:100}.ibm-plex-mono-extralight,.ibm-plex-mono-thin{font-family:IBM Plex Mono,monospace!important;font-style:normal}.ibm-plex-mono-extralight{font-weight:200}.ibm-plex-mono-light{font-weight:300}.ibm-plex-mono-light,.ibm-plex-mono-regular{font-family:IBM Plex Mono,monospace!important;font-style:normal}.ibm-plex-mono-regular{font-weight:400}.ibm-plex-mono-medium{font-weight:500}.ibm-plex-mono-medium,.ibm-plex-mono-semibold{font-family:IBM Plex Mono,monospace!important;font-style:normal}.ibm-plex-mono-semibold{font-weight:600}.ibm-plex-mono-bold{font-family:IBM Plex Mono,monospace!important;font-style:normal;font-weight:700}#privy-modal-content button{border-radius:6px;font-family:IBM Plex Mono,monospace!important;font-size:small;letter-spacing:-.5px;text-transform:uppercase}#privy-modal-content input{background:#fff;border-radius:6px;padding-top:5px!important}#privy-dialog-title{display:none!important;font-size:18px;padding-bottom:10px;padding-top:10px}.AppLogoContainer-sc-a206bd44-0{display:none}#privy-modal-content{background:var(--Neutral-0,#fafafa);border:6px solid var(--Neutral-1,#e9e9e9);box-shadow:inset 0 0 0 1px rgba(0,0,0,.15),0 330px 92px transparent,0 211px 84px rgba(0,0,0,.01),0 119px 71px rgba(0,0,0,.05),0 53px 53px rgba(0,0,0,.09),0 13px 29px rgba(0,0,0,.1);height:auto!important;padding-bottom:10px}.Subtitle-sc-ddbf22b4-4{font-size:12px;margin-top:-14px;opacity:.5}.StyledLink-sc-1c6127e5-0{background:none!important}.StyledLink-sc-c8577138-0,.login-method-button{font-family:IBM Plex Mono,monospace!important}.StyledLink-sc-c8577138-0{font-style:uppercase}#protected-by-privy{color:#000!important}";document.head.appendChild(s)})();
|
|
3
|
-
"use strict";var Ki=Object.create;var sr=Object.defineProperty;var Zi=Object.getOwnPropertyDescriptor;var Xi=Object.getOwnPropertyNames;var Ji=Object.getPrototypeOf,$i=Object.prototype.hasOwnProperty;var _i=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Xi(t))!$i.call(e,o)&&o!==n&&sr(e,o,{get:()=>t[o],enumerable:!(s=Zi(t,o))||s.enumerable});return e};var el=(e,t,n)=>(n=e!=null?Ki(Ji(e)):{},_i(t||!e||!e.__esModule?sr(n,"default",{value:e,enumerable:!0}):n,e));const a=require("react/jsx-runtime"),f=require("./privy-n6MHafwm.js"),u=require("react"),v=require("@spicenet-io/spiceflow-core"),sn=require("wagmi"),T=require("viem"),_t=require("viem/actions"),Zs=require("@privy-io/react-auth"),jn=require("react-dom");require("@tanstack/react-query");const tl="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@100;200;300;400;500;600;700&display=swap",nl="spiceflow-ibm-plex-mono",sl="spiceflow-preconnect-googleapis",ol="spiceflow-preconnect-gstatic";function Xs(e,t){if(document.getElementById(e))return;const n=t();n.id=e,document.head.appendChild(n)}function rl(){typeof document>"u"||(Xs(sl,()=>{const e=document.createElement("link");return e.rel="preconnect",e.href="https://fonts.googleapis.com",e}),Xs(ol,()=>{const e=document.createElement("link");return e.rel="preconnect",e.href="https://fonts.gstatic.com",e.crossOrigin="",e}),Xs(nl,()=>{const e=document.createElement("link");return e.rel="stylesheet",e.href=tl,e}))}const al={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",8453:"0x4200000000000000000000000000000000000006",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",84532:"0x4200000000000000000000000000000000000006"},or=T.parseAbi(["function deposit() payable","function withdraw(uint256 wad)"]);function Js(e){return f.getChainConfig(e)?.wrappedNativeTokenAddress??al[e]}const $s=(e,t)=>({to:e,value:t,data:T.encodeFunctionData({abi:or,functionName:"deposit"})}),_s=(e,t)=>({to:e,value:0n,data:T.encodeFunctionData({abi:or,functionName:"withdraw",args:[t]})});function eo(e,t,n){const s=v.isNativeToken(t),o=v.isNativeToken(n);if(!s&&!o)return null;const r=Js(e);return r?{weth:r,wrapIn:s,unwrapOut:o}:null}function rr(e,t,n,s){const o=eo(e,t,n);return!o||s<=0n?null:o.wrapIn&&!o.unwrapOut&&n.toLowerCase()===o.weth.toLowerCase()?[$s(o.weth,s)]:o.unwrapOut&&!o.wrapIn&&t.toLowerCase()===o.weth.toLowerCase()?[_s(o.weth,s)]:null}function il(e){return{...e,resolve:async(t,n,s,o)=>{const r=rr(n,t.tokenIn,t.tokenOut,t.amountIn);if(r)return{venue:"native-wrap",amountOut:t.amountIn,amountOutMinimum:t.amountIn,calls:r};const i=await e.resolve(t,n,s,o);if(i)return i;const l=eo(n,t.tokenIn,t.tokenOut);if(!l)return null;const c=await e.resolve({...t,tokenIn:l.wrapIn?l.weth:t.tokenIn,tokenOut:l.unwrapOut?l.weth:t.tokenOut},n,s,o);return c?{...c,calls:[...l.wrapIn?[$s(l.weth,t.amountIn)]:[],...c.calls,...l.unwrapOut?[_s(l.weth,c.amountOutMinimum)]:[]]}:null}}}function ll(e){return{...e,resolve:async(t,n,s)=>{const o=rr(n,t.tokenIn,t.tokenOut,t.amountOut);if(o)return{venue:"native-wrap",amountIn:t.amountOut,amountInMax:t.amountOut,amountOut:t.amountOut,calls:o};const r=await e.resolve(t,n,s);if(r)return r;const i=eo(n,t.tokenIn,t.tokenOut);if(!i)return null;const l=await e.resolve({...t,tokenIn:i.wrapIn?i.weth:t.tokenIn,tokenOut:i.unwrapOut?i.weth:t.tokenOut},n,s);return l?{...l,calls:[...i.wrapIn?[$s(i.weth,l.amountInMax)]:[],...l.calls,...i.unwrapOut?[_s(i.weth,l.amountOut)]:[]]}:null}}}const ar=[100,500,3e3,1e4];function ps(e,t,n,s,o){const r=[];for(const i of n){const l=typeof i=="object"&&!Array.isArray(i)?i:void 0,c=l?l.tokens:Array.isArray(i)?i:[i];if(!c.length||c.length>2)throw new Error("A v3 route must have one or two intermediate tokens");const d=[e,...c,t];if(l&&(l.feeTiers.length!==d.length-1||l.feeTiers.some(m=>!m.length)))throw new Error("A v3 route needs fee tiers for every pool");if(new Set(d.map(m=>m.toLowerCase())).size!==d.length)continue;const p=(m,h)=>{if(m===d.length){r.push(o==="in"?h:ir(h));return}for(const x of l?.feeTiers[m-1]??s)p(m+1,T.concatHex([h,T.encodePacked(["uint24","address"],[x,d[m]])]))};p(1,d[0])}return[...new Set(r)]}function ir(e){const t=e.slice(2),n=[];for(let s=0;s<t.length;){const o=n.length%2===0?40:6;n.push(t.slice(s,s+o)),s+=o}return`0x${n.reverse().join("")}`}const cl=T.parseAbi(["function exactOutputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 amountOut, uint256 amountInMaximum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountIn)","function exactOutput((bytes path, address recipient, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),dl=T.parseAbi(["function exactOutputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountIn)","function exactOutput((bytes path, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),ul=1800;function lr(e){const{config:t,route:n,tokenIn:s,tokenOut:o,recipient:r,amountOut:i}=e,l=e.amountInMaximum,c=e.routerHasDeadline?dl:cl,d=e.routerHasDeadline?{deadline:BigInt(Math.floor(Date.now()/1e3)+ul)}:{},p=n.path?T.encodeFunctionData({abi:c,functionName:"exactOutput",args:[{path:n.path,recipient:r,...d,amountOut:i,amountInMaximum:l}]}):T.encodeFunctionData({abi:c,functionName:"exactOutputSingle",args:[{tokenIn:s,tokenOut:o,fee:n.fee,recipient:r,...d,amountOut:i,amountInMaximum:l,sqrtPriceLimitX96:0n}]});return{to:t.swapRouter,value:0n,data:p}}const pl=T.parseAbi(["function quoteExactInput(bytes path, uint256 amountIn) returns (uint256 amountOut, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate)","function quoteExactOutput(bytes path, uint256 amountOut) returns (uint256 amountIn, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate)"]);async function Qn(e,t,n,s,o){const r=f.getClientForChain(e),{result:i}=await r.simulateContract({address:t.quoterV2,abi:pl,functionName:o==="in"?"quoteExactInput":"quoteExactOutput",args:[n,s]}),[l,,,c]=i;if(l<=0n)throw new Error("No liquidity along this path.");return{amount:l,gasEstimate:c}}async function fl(e){const{tokenIn:t,tokenOut:n,amountIn:s,fee:o,chainId:r,config:i}=e;if(s<=0n)throw new Error("amountIn must be greater than 0");const l=(await f.getClientForChain(r).simulateContract({address:i.quoterV2,abi:v.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:s,fee:o,sqrtPriceLimitX96:0n}]})).result;if(l[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:l[0],sqrtPriceX96After:l[1],gasEstimate:l[3]}}async function cr(e){const t=e.feeTiers??ar,n=ps(e.tokenIn,e.tokenOut,e.hubs??[],t,"in"),s=await Promise.allSettled([...t.map(async r=>({...await fl({...e,fee:r}),fee:r})),...n.map(async r=>{const i=await Qn(e.chainId,e.config,r,e.amountIn,"in");return{amountOut:i.amount,sqrtPriceX96After:0n,gasEstimate:i.gasEstimate,fee:0,path:r}})]);let o=null;for(const r of s)r.status==="fulfilled"&&(!o||r.value.amountOut>o.amountOut)&&(o=r.value);if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}const ml=[{inputs:[{components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"amount",type:"uint256"},{name:"fee",type:"uint24"},{name:"sqrtPriceLimitX96",type:"uint160"}],name:"params",type:"tuple"}],name:"quoteExactOutputSingle",outputs:[{name:"amountIn",type:"uint256"},{name:"sqrtPriceX96After",type:"uint160"},{name:"initializedTicksCrossed",type:"uint32"},{name:"gasEstimate",type:"uint256"}],stateMutability:"nonpayable",type:"function"}];async function hl(e){const{tokenIn:t,tokenOut:n,amountOut:s,fee:o,chainId:r,config:i}=e;if(s<=0n)throw new Error("amountOut must be greater than 0");const l=(await f.getClientForChain(r).simulateContract({address:i.quoterV2,abi:ml,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:s,fee:o,sqrtPriceLimitX96:0n}]})).result;if(l[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:l[0],sqrtPriceX96After:l[1],gasEstimate:l[3]}}async function dr(e){const t=e.feeTiers??ar,n=ps(e.tokenIn,e.tokenOut,e.hubs??[],t,"out"),s=await Promise.allSettled([...t.map(async r=>({...await hl({...e,fee:r}),fee:r})),...n.map(async r=>{const i=await Qn(e.chainId,e.config,r,e.amountOut,"out");return{amountIn:i.amount,sqrtPriceX96After:0n,gasEstimate:i.gasEstimate,fee:0,path:r}})]);let o=null;for(const r of s)r.status==="fulfilled"&&(!o||r.value.amountIn<o.amountIn)&&(o=r.value);if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}function gl(e){return e.type==="swap"}const Gn=.02,xl=[1,8453,42161,10,137,43114,56],yl="https://api.1inch.dev/swap/v6.0";function to(e,t){return v.applySlippage(e,t)}function wl(e){const t=e?.baseUrl??yl;return{name:"1inch",chainIds:e?.chainIds??xl,resolve:async(n,s,o)=>{const r=n.maxSlippage??Gn,i=r*100,l=v.isNativeToken(n.tokenIn)?v.NATIVE_TOKEN_ADDRESS:n.tokenIn,c=v.isNativeToken(n.tokenOut)?v.NATIVE_TOKEN_ADDRESS:n.tokenOut,d=v.isNativeToken(n.tokenIn);try{const p=new URL(`${t}/${s}/swap`);p.searchParams.set("src",l),p.searchParams.set("dst",c),p.searchParams.set("amount",n.amountIn.toString()),p.searchParams.set("from",o),p.searchParams.set("slippage",i.toString()),p.searchParams.set("disableEstimate","true"),p.searchParams.set("allowPartialFill","false");const m={Accept:"application/json"};e?.apiKey&&(m.Authorization=`Bearer ${e.apiKey}`);const h=await fetch(p.toString(),{headers:m});if(!h.ok)throw new f.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${h.status} for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:`HTTP ${h.status}`});const x=await h.json();if(!x.dstAmount||!x.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const g=BigInt(x.dstAmount);if(g<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const y=to(g,r),w=[];return x.tx.to&&!d&&w.push({to:n.tokenIn,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"approve",args:[x.tx.to,n.amountIn]})}),w.push({to:x.tx.to,value:BigInt(x.tx.value||"0"),data:x.tx.data}),{venue:"1inch",amountOut:g,amountOutMinimum:y,calls:w}}catch(p){if(p instanceof f.SpiceflowError)throw p;const m=p instanceof Error?p.message:String(p);throw new f.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}: ${m}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:m})}}}}const ur=[4114,5115],no={name:"Satsuma",swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},pr={name:"Uniswap v3",swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x4200000000000000000000000000000000000006","0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]},fr={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[1],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2","0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"]},mr={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[42161],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x82aF49447D8a07e3bd95BD0d56f35241523fBab1","0xaf88d065e77c8cC2239327C5EDb3A432268e5831"]},bl={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[137],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270","0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"]},Cl={name:"Uniswap v3",swapRouter:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",quoterV2:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",chainIds:[56],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c","0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d"]},vl={name:"Uniswap v3",swapRouter:"0xfe31f71c1b106eac32f1a19239c9a9a72ddfb900",quoterV2:"0x661e93cca42afacb172121ef892830ca3b70f08d",chainIds:[143],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A","0x754704Bc059F8C67012fEd69BC8A327a5aafb603"]},hr={name:"Uniswap v3",swapRouter:"0xcaf681a66d020601342297493863e78c959e5cb2",quoterV2:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",chainIds:[4663],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73","0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"]},gr={name:"SushiSwap",swapRouter:"0x1e406484F1F204b23cE84B9901C0171a738fd406",quoterV2:"0x3E290e5E01818002A0b672148BdC7514D861C7B3",chainIds:[4663],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73","0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"],routerHasDeadline:!0},xr=T.parseAbi(["function exactInput((bytes path, address recipient, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),yr=T.parseAbi(["function exactInputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)","function exactInput((bytes path, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),kl=T.parseAbi(["function exactInput((bytes path, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),Sl=T.parseAbi(["function exactOutput((bytes path, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),so=1800,wr=[1,50,100,200,2e3],oo={name:"Aerodrome",swapRouter:"0xcbBb8035cAc7D4B3Ca7aBb74cF7BdF900215Ce0D",quoterV2:"0x3d4C22254F86f64B7eC90ab8F7aeC1FBFD271c6C",chainIds:[8453],hubCurrencies:["0x4200000000000000000000000000000000000006","0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]};function ro(e){const t=e.name??"Aerodrome",n=e.chainIds??[8453],s=e.tickSpacings??wr;return{name:t,chainIds:n,resolve:async(o,r,i)=>{if(v.isNativeToken(o.tokenIn)||v.isNativeToken(o.tokenOut))return null;const l=o.maxSlippage??Gn,c=[...s.map(w=>T.encodePacked(["address","uint24","address"],[o.tokenIn,w,o.tokenOut])),...ps(o.tokenIn,o.tokenOut,e.hubCurrencies??[],s,"in")],d={quoterV2:e.quoterV2},p=await Promise.allSettled(c.map(async w=>({path:w,amountOut:(await Qn(r,d,w,o.amountIn,"in")).amount})));let m=null;for(const w of p)w.status==="fulfilled"&&(!m||w.value.amountOut>m.amountOut)&&(m=w.value);if(!m)return console.warn(`[AerodromeVenue] No viable route for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${r}.`),null;const h=to(m.amountOut,l),x=BigInt(Math.floor(Date.now()/1e3)+so),g=T.encodeFunctionData({abi:kl,functionName:"exactInput",args:[{path:m.path,recipient:i,deadline:x,amountIn:o.amountIn,amountOutMinimum:h}]}),y=[{to:o.tokenIn,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"approve",args:[e.swapRouter,o.amountIn]})},{to:e.swapRouter,value:0n,data:g}];return{venue:t,amountOut:m.amountOut,amountOutMinimum:h,calls:y}}}}function br(e){const t=e.name??"Aerodrome",n=e.chainIds??[8453],s=e.tickSpacings??wr;return{name:t,chainIds:n,resolve:async(o,r,i)=>{if(v.isNativeToken(o.tokenIn)||v.isNativeToken(o.tokenOut))return null;const l=o.maxSlippage??Gn,c=[...s.map(y=>T.encodePacked(["address","uint24","address"],[o.tokenOut,y,o.tokenIn])),...ps(o.tokenIn,o.tokenOut,e.hubCurrencies??[],s,"out")],d={quoterV2:e.quoterV2},p=await Promise.allSettled(c.map(async y=>({path:y,amountIn:(await Qn(r,d,y,o.amountOut,"out")).amount})));let m=null;for(const y of p)y.status==="fulfilled"&&(!m||y.value.amountIn<m.amountIn)&&(m=y.value);if(!m)return console.warn(`[AerodromeExactOutputVenue] No viable route for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${r}.`),null;const h=BigInt(Math.round(l*1e4)),x=m.amountIn+m.amountIn*h/10000n,g=BigInt(Math.floor(Date.now()/1e3)+so);return{venue:t,amountIn:m.amountIn,amountInMax:x,amountOut:o.amountOut,calls:[{to:e.swapRouter,value:0n,data:T.encodeFunctionData({abi:Sl,functionName:"exactOutput",args:[{path:m.path,recipient:i,deadline:g,amountOut:o.amountOut,amountInMaximum:x}]})}]}}}}function Yn(e){const t=e.name??"Uniswap v3",n=e.chainIds??ur;return{name:t,chainIds:n,resolve:async(s,o,r,i)=>{if(v.isNativeToken(s.tokenIn)||v.isNativeToken(s.tokenOut))return null;const l=s.maxSlippage??Gn;let c;try{let g;if(i){if(i.venue!==t)return null;const y=i.calls.find(C=>C.to.toLowerCase()===e.swapRouter.toLowerCase());if(!y)return null;const w=T.decodeFunctionData({abi:e.routerHasDeadline?yr:[...xr,...v.uniV3SwapRouterAbi],data:y.data});if(w.functionName==="exactInput"){const{path:C}=w.args[0];if(C.slice(0,42).toLowerCase()!==s.tokenIn.toLowerCase()||`0x${C.slice(-40)}`.toLowerCase()!==s.tokenOut.toLowerCase())return null;g={path:C,fee:0}}else if(w.functionName==="exactInputSingle"){const{tokenIn:C,tokenOut:b,fee:S}=w.args[0];if(C.toLowerCase()!==s.tokenIn.toLowerCase()||b.toLowerCase()!==s.tokenOut.toLowerCase())return null;g={fee:S}}else return null}c=g?.path?{...g,amountOut:(await Qn(o,e,g.path,s.amountIn,"in")).amount}:await cr({tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn,chainId:o,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:g?[g.fee]:e.feeTiers,hubs:g?[]:[...e.hubCurrencies??[],...e.hubPaths??[]]})}catch{return console.warn(`[UniV3Venue] No viable route for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}.`),null}const d=to(c.amountOut,l),p=e.routerHasDeadline?{deadline:BigInt(Math.floor(Date.now()/1e3)+so)}:{},m=e.routerHasDeadline?yr:c.path?xr:v.uniV3SwapRouterAbi,h=c.path?T.encodeFunctionData({abi:m,functionName:"exactInput",args:[{path:c.path,recipient:r,...p,amountIn:s.amountIn,amountOutMinimum:d}]}):T.encodeFunctionData({abi:m,functionName:"exactInputSingle",args:[{tokenIn:s.tokenIn,tokenOut:s.tokenOut,fee:c.fee,recipient:r,...p,amountIn:s.amountIn,amountOutMinimum:d,sqrtPriceLimitX96:0n}]}),x=[{to:s.tokenIn,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"approve",args:[e.swapRouter,s.amountIn]})},{to:e.swapRouter,value:0n,data:h}];return{venue:t,amountOut:c.amountOut,amountOutMinimum:d,calls:x}}}}function ao(e){const t=e.name??"Uniswap v3",n=e.chainIds??ur;return{name:t,chainIds:n,resolve:async(s,o,r)=>{if(v.isNativeToken(s.tokenIn)||v.isNativeToken(s.tokenOut))return null;const i=s.maxSlippage??Gn;let l;try{l=await dr({tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountOut:s.amountOut,chainId:o,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers,hubs:[...e.hubCurrencies??[],...e.hubPaths??[]]})}catch{return null}const c=BigInt(Math.round(i*1e4)),d=l.amountIn+l.amountIn*c/10000n;return{venue:t,amountIn:l.amountIn,amountInMax:d,amountOut:s.amountOut,calls:[lr({config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},routerHasDeadline:e.routerHasDeadline,route:l,tokenIn:s.tokenIn,tokenOut:s.tokenOut,recipient:r,amountOut:s.amountOut,amountInMaximum:d})]}}}}function Cr(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(Yn(e.satsuma)),e?.aerodrome!==!1&&t.push(ro(e?.aerodrome??oo)),t.push(wl(e?.oneInch));const n=t.map(il);function s(i){return n.find(l=>l.chainIds.includes(i))}async function o(i,l,c,d){const p=n.filter(g=>g.chainIds.includes(l));if(p.length===0)throw new f.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${l}. Cannot resolve swap ${i.tokenIn} \u2192 ${i.tokenOut}.`,{chainId:l,tokenIn:i.tokenIn,tokenOut:i.tokenOut,amountIn:i.amountIn.toString()});const m=await Promise.allSettled(p.map(g=>g.resolve(i,l,c,d)));let h=null;for(const g of m)d&&g.status==="fulfilled"&&g.value&&(g.value.venue!==d.venue||g.value.calls.length!==d.calls.length||g.value.calls.some((y,w)=>y.to.toLowerCase()!==d.calls[w].to.toLowerCase()||y.data.slice(0,10)!==d.calls[w].data.slice(0,10)))||g.status==="fulfilled"&&g.value&&(!h||g.value.amountOut>h.amountOut)&&(h=g.value);if(h)return h;const x=m.find(g=>g.status==="rejected");if(x)throw x.reason;return null}async function r(i,l,c){const d=[],p=[];for(const m of i){if(!gl(m)){d.push(m);continue}const h=await o(m,l,c);if(!h)throw new f.SpiceflowError("NO_LIQUIDITY",`No venue returned a quote for ${m.tokenIn} \u2192 ${m.tokenOut} on chain ${l}.`,{chainId:l,tokenIn:m.tokenIn,tokenOut:m.tokenOut,amountIn:m.amountIn.toString()});d.push(...h.calls),p.push(h)}return{calls:d,resolvedSwaps:p}}return{resolveSwapIntents:r,resolveSwap:o,getVenueForChain:s,venues:t}}const on="0x0000000000000000000000000000000000000000",io=[{fee:100,tickSpacing:1},{fee:500,tickSpacing:10},{fee:3e3,tickSpacing:60},{fee:1e4,tickSpacing:200}],vr=on,kr=.02,Il=1800,Sr={name:"Uniswap v4",quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",universalRouter:"0x6ff5693b99212da76ad316178a184ab56d299b43",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",chainIds:[8453],hubCurrencies:["0x4200000000000000000000000000000000000006",on,"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]},Ir={name:"Uniswap v4",quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",universalRouter:"0x8876789976decbfcbbbe364623c63652db8c0904",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",routerHasHopPrice:!0,chainIds:[4663],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73",on,"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"]},Ar=T.parseAbi(["struct PoolKey { address currency0; address currency1; uint24 fee; int24 tickSpacing; address hooks; }","struct PathKey { address intermediateCurrency; uint24 fee; int24 tickSpacing; address hooks; bytes hookData; }","struct QuoteExactSingleParams { PoolKey poolKey; bool zeroForOne; uint128 exactAmount; bytes hookData; }","struct QuoteExactParams { address exactCurrency; PathKey[] path; uint128 exactAmount; }","function quoteExactInputSingle(QuoteExactSingleParams params) returns (uint256 amountOut, uint256 gasEstimate)","function quoteExactInput(QuoteExactParams params) returns (uint256 amountOut, uint256 gasEstimate)","function quoteExactOutputSingle(QuoteExactSingleParams params) returns (uint256 amountIn, uint256 gasEstimate)","function quoteExactOutput(QuoteExactParams params) returns (uint256 amountIn, uint256 gasEstimate)"]),Al=T.parseAbi(["function approve(address token, address spender, uint160 amount, uint48 expiration)"]),El=T.parseAbi(["function execute(bytes commands, bytes[] inputs, uint256 deadline) payable"]),Er="0x10",Fl="04",Tl="06",jl="07",Bl="08",Rl="09",fs="0c",ms="0e",Dl=[{name:"currency0",type:"address"},{name:"currency1",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"}],Ol=[{name:"intermediateCurrency",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"},{name:"hookData",type:"bytes"}],cn=(e,t)=>e.toLowerCase()===t.toLowerCase();function hs(e){return v.isNativeToken(e)?on:e}function Nl(e,t){return e.toLowerCase()<t.toLowerCase()?[e,t]:[t,e]}function Fr(e,t,n,s,o){const r=[],[i,l]=Nl(e,t);for(const{fee:d,tickSpacing:p}of io)r.push({kind:"single",poolKey:{currency0:i,currency1:l,fee:d,tickSpacing:p,hooks:vr},zeroForOne:cn(e,i)});const c=(d,p)=>!!o&&(cn(d,on)&&cn(p,o)||cn(d,o)&&cn(p,on));for(const d of n)if(!(cn(d,e)||cn(d,t))&&!(c(d,e)||c(d,t)))for(const p of io)for(const m of io){const h=(x,g)=>({intermediateCurrency:x,fee:g.fee,tickSpacing:g.tickSpacing,hooks:vr,hookData:"0x"});r.push({kind:"multi",path:s==="in"?[h(d,p),h(t,m)]:[h(e,p),h(d,m)]})}return r}async function Tr(e,t,n,s,o,r){const i=f.getClientForChain(e),l=(await Promise.allSettled(n.map(async c=>{const{result:d}=c.kind==="single"?await i.simulateContract({address:t.quoter,abi:Ar,functionName:r==="in"?"quoteExactInputSingle":"quoteExactOutputSingle",args:[{poolKey:c.poolKey,zeroForOne:c.zeroForOne,exactAmount:o,hookData:"0x"}]}):await i.simulateContract({address:t.quoter,abi:Ar,functionName:r==="in"?"quoteExactInput":"quoteExactOutput",args:[{exactCurrency:s,path:c.path,exactAmount:o}]}),p=d[0];if(p<=0n)throw new Error("zero quote");return{candidate:c,amount:p}}))).filter(c=>c.status==="fulfilled").map(c=>c.value);return l.length===0?null:(l.sort((c,d)=>c.amount<d.amount?-1:c.amount>d.amount?1:0),r==="in"?l[l.length-1]:l[0])}function jr(e){const{candidate:t,direction:n,currencyIn:s,currencyOut:o,recipient:r,exactAmount:i,limitAmount:l,deadline:c,routerHasHopPrice:d,sweepNativeTo:p}=e;let m,h;t.kind==="single"?(m=n==="in"?`0x${Tl}${fs}${ms}`:`0x${Bl}${fs}${ms}`,h=T.encodeAbiParameters([{type:"tuple",components:[{name:"poolKey",type:"tuple",components:Dl},{name:"zeroForOne",type:"bool"},{name:n==="in"?"amountIn":"amountOut",type:"uint128"},{name:n==="in"?"amountOutMinimum":"amountInMaximum",type:"uint128"},...d?[{name:"minHopPriceX36",type:"uint256"}]:[],{name:"hookData",type:"bytes"}]}],[{poolKey:t.poolKey,zeroForOne:t.zeroForOne,[n==="in"?"amountIn":"amountOut"]:i,[n==="in"?"amountOutMinimum":"amountInMaximum"]:l,...d?{minHopPriceX36:0n}:{},hookData:"0x"}])):(m=n==="in"?`0x${jl}${fs}${ms}`:`0x${Rl}${fs}${ms}`,h=T.encodeAbiParameters([{type:"tuple",components:[{name:n==="in"?"currencyIn":"currencyOut",type:"address"},{name:"path",type:"tuple[]",components:Ol},...d?[{name:"minHopPriceX36",type:"uint256[]"}]:[],{name:n==="in"?"amountIn":"amountOut",type:"uint128"},{name:n==="in"?"amountOutMinimum":"amountInMaximum",type:"uint128"}]}],[{[n==="in"?"currencyIn":"currencyOut"]:n==="in"?s:o,path:t.path,...d?{minHopPriceX36:[]}:{},[n==="in"?"amountIn":"amountOut"]:i,[n==="in"?"amountOutMinimum":"amountInMaximum"]:l}]));const x=T.encodeAbiParameters([{type:"address"},{type:"uint256"}],[s,n==="in"?i:l]),g=T.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"}],[o,r,0n]),y=T.encodeAbiParameters([{type:"bytes"},{type:"bytes[]"}],[m,[h,x,g]]),w=p?`${Er}${Fl}`:Er,C=p?[y,T.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"}],[on,p,0n])]:[y];return T.encodeFunctionData({abi:El,functionName:"execute",args:[w,C,c]})}function Br(){return BigInt(Math.floor(Date.now()/1e3)+Il)}function Rr(e,t,n,s){return{to:e.permit2,value:0n,data:T.encodeFunctionData({abi:Al,functionName:"approve",args:[t,e.universalRouter,n,Number(s)]})}}function Dr(e){const t=e.name??"Uniswap v4",n=e.v3?Yn({...e.v3,chainIds:e.chainIds}):null;return{name:t,chainIds:e.chainIds,resolve:async(s,o,r)=>{const i=s.maxSlippage??kr,l=hs(s.tokenIn),c=hs(s.tokenOut),d=v.isNativeToken(s.tokenIn),p=e.hubCurrencies??[on];let m=null;if(!cn(l,c)&&s.amountIn>0n){const h=await Tr(o,e,Fr(l,c,p,"in",Js(o)),l,s.amountIn,"in").catch(()=>null);if(h){const x=v.applySlippage(h.amount,i),g=Br(),y=[];d||(y.push({to:s.tokenIn,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"approve",args:[e.permit2,s.amountIn]})}),y.push(Rr(e,s.tokenIn,s.amountIn,g))),y.push({to:e.universalRouter,value:d?s.amountIn:0n,data:jr({candidate:h.candidate,direction:"in",currencyIn:l,currencyOut:c,recipient:r,exactAmount:s.amountIn,limitAmount:x,deadline:g,routerHasHopPrice:e.routerHasHopPrice})}),m={venue:t,amountOut:h.amount,amountOutMinimum:x,calls:y}}}return!m&&n?n.resolve(s,o,r):m}}}function Or(e){const t=e.name??"Uniswap v4";return{name:t,chainIds:e.chainIds,resolve:async(n,s,o)=>{const r=v.isNativeToken(n.tokenIn),i=hs(n.tokenIn),l=hs(n.tokenOut);if(cn(i,l)||n.amountOut<=0n)return null;const c=n.maxSlippage??kr,d=e.hubCurrencies??[on],p=await Tr(s,e,Fr(i,l,d,"out",Js(s)),l,n.amountOut,"out").catch(()=>null);if(!p)return null;const m=BigInt(Math.round(c*1e4)),h=p.amount+p.amount*m/10000n,x=Br();return{venue:t,amountIn:p.amount,amountInMax:h,amountOut:n.amountOut,calls:[...r?[]:[Rr(e,n.tokenIn,h,x)],{to:e.universalRouter,value:r?h:0n,data:jr({candidate:p.candidate,direction:"out",currencyIn:i,currencyOut:l,recipient:o,exactAmount:n.amountOut,limitAmount:h,deadline:x,routerHasHopPrice:e.routerHasHopPrice,sweepNativeTo:r?o:void 0})}]}}}}const lo=[{...no,protocol:"uniswap-v3",chainId:4114},{...no,protocol:"uniswap-v3",chainId:5115},{...pr,protocol:"uniswap-v3",chainId:8453},{...fr,protocol:"uniswap-v3",chainId:1},{...mr,protocol:"uniswap-v3",chainId:42161},{...bl,protocol:"uniswap-v3",chainId:137},{...Cl,protocol:"uniswap-v3",chainId:56},{...vl,protocol:"uniswap-v3",chainId:143},{...hr,protocol:"uniswap-v3",chainId:4663},{...gr,protocol:"uniswap-v3",chainId:4663},{...Sr,protocol:"uniswap-v4",chainId:8453},{...Ir,protocol:"uniswap-v4",chainId:4663},{...oo,protocol:"aerodrome-slipstream",chainId:8453}];function Bn(e){const t=e?.includeDefaults===!1?e.venues??[]:[...lo,...e?.venues??[]],n=[],s=[];for(const o of t){const r=[o.chainId];switch(o.protocol){case"uniswap-v3":{const i={...o,chainIds:r};n.push(Yn(i)),s.push(ao(i));break}case"uniswap-v4":{const i={...o,chainIds:r};n.push(Dr(i)),s.push(Or(i));break}case"aerodrome-slipstream":{const i={...o,chainIds:r};n.push(ro(i)),s.push(br(i));break}default:{const i=o;throw new f.SpiceflowError("INVALID_PARAMS",`Unsupported liquidity venue protocol: ${i.protocol}`,{protocol:i.protocol})}}}return{input:n,output:s}}const co=new Set(["WBTC","CBTC"]),Nr=new Set(["btc","wbtc","wcbtc","cbtc"]);function Mr(e,t){return!e||!t?!1:e===t?!0:co.has(e)&&co.has(t)}function dn(e){const[t,n,s]=e.split(":");if(t!=="evm"||!n||!s)return null;const o=Number(n);if(!Number.isFinite(o))return null;const r=s.startsWith("0x")?s.toLowerCase():`0x${s.toLowerCase()}`;return{chainId:o,address:r}}function gs(e){return(e??"").trim().replace(/^test\s+/i,"").replace(/^spice/i,"").toLowerCase().replace(/[^a-z0-9]/g,"")}function Ml(e){return new Set([e.receiptTokenName,e.displaySymbol,e.symbol,e.displayName,e.name].map(gs).filter(Boolean))}function Pl(e,t){const n=Ml(e),s=[t.symbol,t.name,t.equivalenceGroup].map(gs);if(s.some(i=>i&&n.has(i)))return!0;const o=[...n].some(i=>Nr.has(i)),r=s.some(i=>Nr.has(i))||co.has(t.equivalenceGroup??"");return o&&r}function Pr(e,t,n){const s=new Set(t.map(gs).filter(Boolean)),o=r=>{if(n&&f.addressesEqual(r.address,n))return 0;const i=[r.symbol,r.name,r.equivalenceGroup].map(gs).findIndex(l=>l&&s.has(l));return i===-1?4:i+1};return[...e].sort((r,i)=>{const l=o(r)-o(i);return l!==0?l:r.address.toLowerCase().localeCompare(i.address.toLowerCase())})}function Rn(e,t){const n=e.chainTokens?Object.keys(e.chainTokens):[],s=[];for(const o of n){const r=dn(o);if(!r||r.chainId!==t)continue;const i=r.address,l=v.isNativeToken(i)?f.getChainConfig(t)?.nativeCurrency:void 0,c=v.getTokenByAddress(i,t)??(l?{...l}:void 0);c&&(!uo(e,i,t)&&!(e.isUniversal&&Pl(e,c))||s.some(d=>f.addressesEqual(d,i))||s.push(i))}return Pr(s.map(o=>{const r=v.getTokenByAddress(o,t);return{address:o,symbol:r?.symbol,name:r?.name,equivalenceGroup:r?.equivalenceGroup}}),[e.receiptTokenName,e.displaySymbol,e.symbol,e.displayName,e.name],e.chainId===t&&!e.isUniversal?e.address:void 0).map(o=>o.address)}function uo(e,t,n){return e.chainId===n&&f.addressesEqual(e.address,t)?!0:Kn(e.address,e.chainId,t,n)}async function Ul(e,t){const n=f.getClientForChain(e),s=v.getEscrowContractAddress(e);return v.isNativeToken(t)?n.getBalance({address:s}):await n.readContract({address:t,abi:T.erc20Abi,functionName:"balanceOf",args:[s]})}function po(e,t,n){const s=v.getTokensForChain(n),o=s.find(i=>f.addressesEqual(i.address,e));if(o&&(t===n||!v.isNativeToken(e)))return o;const r=v.getTokenByAddress(e,t);if(r)return Pr(s.filter(i=>Mr(i.equivalenceGroup,r.equivalenceGroup)),[r.symbol,r.name,r.equivalenceGroup])[0]}function xs(e){return e.equivalenceGroup==="USDC"&&e.symbol.toUpperCase()!=="USDT"}function Ur(e){const t=v.getEscrowContract(e);if(!t||t===v.ZERO_ADDRESS)return;const n=v.getTokensForChain(e).filter(xs);return n.find(s=>s.symbol.toUpperCase()==="USDC")??n[0]}function fo(e,t){if(e.chainId===t)return null;const n=v.getEscrowContract(e.chainId),s=v.getEscrowContract(t);if(!n||n===v.ZERO_ADDRESS||!s||s===v.ZERO_ADDRESS)return null;const o=!e.isNative&&!v.isNativeToken(e.address)?v.getTokenByAddress(e.address,e.chainId):void 0,r=o&&xs(o)?po(e.address,e.chainId,t):void 0,i=r?o:Ur(e.chainId),l=r??Ur(t);if(!i||!l)return null;const c=d=>({address:d.address,symbol:d.symbol,decimals:d.decimals,chainId:d.chainId});return{source:c(i),destination:c(l)}}function Wl(e,t){return!!fo(e,t)}function Jt(e,t){if(e.chainId===t)return e.address;const n=po(e.address,e.chainId,t);return n?n.address:null}async function xn(e,t,n,s){const o=v.getTokenByAddress(t,n);return o?o.decimals:e?.chainId===n&&f.addressesEqual(e.address,t)&&!e.isUniversal?e.decimals:s?.chainId===n&&f.addressesEqual(s.address,t)?s.decimals:f.getTokenDecimals(n,t)}async function Wr(e,t,n={}){const s=Jt(e,t),o=Rn(e,t);if(o.length===0)return s;if(o.length===1)return o[0];const r=n.requiredAmount??0n,i=l=>{const c=o.map(d=>({candidate:d,balance:l.get(v.isNativeToken(d)?"native":d.toLowerCase())??0n})).filter(d=>d.balance>0n).sort((d,p)=>d.balance===p.balance?0:d.balance>p.balance?-1:1);return c.length===0?null:((r>0n?c.find(d=>d.balance>=r):c[0])??c[0]).candidate};try{const l=await Promise.all(o.map(async p=>({key:v.isNativeToken(p)?"native":p.toLowerCase(),value:await Ul(t,p)}))),c=new Map(l.map(({key:p,value:m})=>[p,m])),d=i(c);if(d)return d}catch{}return s}function Kn(e,t,n,s){const o=v.getTokenByAddress(e,t),r=v.getTokenByAddress(n,s);return o&&r?Mr(o.equivalenceGroup,r.equivalenceGroup):v.areEquivalent(e,n)}function ys(e,t){return Kn(e.address,e.chainId,t.address,t.chainId)}const Lr=.01;function zr(e,t=!1){const n=Number.isFinite(e.balanceUsd)&&e.balanceUsd>0;return e.isDiscovered?n&&e.balanceUsd>=Lr:!t||!n||e.balanceUsd>=Lr}function ws(e,t=!1){return!!e&&e._source==="wallet"&&(e.location==="external"||e._fundingWallet==="external"||!e.location&&!e._fundingWallet&&t)}function Ge(e){return e.positionId??`${e.owner?.toLowerCase()??""}:${e.location??e._source??""}:${e.chainId}:${e.receiptTokenId??v.normalizeNativeTokenAddress(e.address).toLowerCase()}`}function qr(e,t){if(!t?.length||e.symbol!==void 0&&f.isAssetAllowed({...e,symbol:e.symbol},t))return!0;const n=s=>t.some(o=>f.addressesEqual(v.normalizeNativeTokenAddress(o),v.normalizeNativeTokenAddress(s)));return n(e.address)||Object.keys(e.chainTokens??{}).some(s=>{const o=dn(s);return o?n(o.address):!1})}function kn(e,t,n,s,o,r){const i=(y,w=!1)=>({eligible:!1,reason:y,policyExcluded:w}),l=e._source==="wallet"||e.location==="external"||e.location==="embedded",c=t==="spend-source"&&l&&!!s&&e.chainId===s.chainId&&f.addressesEqual(v.normalizeNativeTokenAddress(e.address),v.normalizeNativeTokenAddress(s.address));if(n.isWhitelistGateActive||!c&&!f.isAssetAllowed(e,n.allowedTokens))return i("Asset excluded by client policy",!0);if(t!=="withdraw-destination"&&!c&&!zr(e))return i("Asset is unpriced or below the minimum value",!0);if(t==="holding")return{eligible:!0,reason:null};if(e.balanceError)return i(e.balanceError);if(!c&&!qr(e,o))return i("Asset excluded by action policy",!0);const d=new Set(s?[s.chainId]:[]);e._source!=="spice"&&e.location!=="rollup"&&d.add(e.chainId);for(const y of d)if(!f.getRpcUrlForChain(y,n.rpcOverrides)?.trim())return i(`Configure SpiceFlowProvider rpcOverrides[${y}] before using this asset.`);if(r?.requiresEscrow){const y=v.getTokenByAddress(e.address,e.chainId);if(!y||!xs(y))return i("This asset has no supported escrow mapping")}if(!s)return{eligible:!0,reason:null};const p=n.liquidityVenues?.includeDefaults===!1?n.liquidityVenues.venues??[]:[...lo,...n.liquidityVenues?.venues??[]],m=y=>p.some(w=>w.chainId===y),h=l&&e.chainId!==s.chainId,x=h?fo(e,s.chainId):null;if(h&&!x)return i("No supported source route");if(x&&!f.addressesEqual(v.normalizeNativeTokenAddress(e.address),v.normalizeNativeTokenAddress(x.source.address))&&!m(e.chainId))return i("No conversion venue configured on the source chain");const g=x?.destination.address??Jt(e,s.chainId);return t==="withdraw-destination"?(e.chainTokens||e.receiptTokenId?Rn(e,s.chainId):g?[g]:[]).some(y=>f.addressesEqual(v.normalizeNativeTokenAddress(y),v.normalizeNativeTokenAddress(s.address)))?{eligible:!0,reason:null}:i("No supported withdrawal mapping"):g&&f.addressesEqual(v.normalizeNativeTokenAddress(g),v.normalizeNativeTokenAddress(s.address))?{eligible:!0,reason:null}:!g&&!Wl(e,s.chainId)?i("No supported destination route"):m(s.chainId)?{eligible:!0,reason:null}:i("No conversion venue configured on the destination chain")}function bs(){const e=u.useContext(f.SpiceFlowProviderContext),[t]=u.useState(f.createInventoryStore);return e?.inventory??t}function mo(e,t,n,s,o){const r=bs(),i=o??r,l=u.useMemo(()=>i.entry(e),[i,e]),[,c]=u.useState(0);u.useEffect(()=>{if(n)return l.subscribe(()=>c(p=>p+1),t,s)},[l,n,t,s]);const d=u.useCallback(()=>l.refresh(),[l]);return{...n?l.snapshot():f.EMPTY_INVENTORY,refresh:d}}var Hr="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAA6lBMVEXc3NzX/v/1hRvZ2dnd3dzb29va7fpMaXHa1tPc3N35/v/c3Nzc3NzCrp/c3Nza2tp1PRbLsJzlr33uhSj0kTHcnWnUva7jdhuNX0B6Qhrsk0LOxMCFVDJ+RyGhfGTkeiGYVSHjdx3lij7khDPEsaPfoW/jgjLQuKXmgzB2PRb2hRvldhvjdRv4hhvpeRtwORb/ihryghvabhnsehrUaRjLXxXtfRt7PxXwexricRbRYhURFBeSTBe0XBrEZxmDRxiiVRrlgCbfzMAvLCmrWBgbMEh9UjBbOBe2pJi9byekk4nkgDHkgDJLNB7jlKArAAAAKXRSTlMzJv0TNSYsADUxKBwK/QUZ/URTx650/vqJ5YpMosxj3ezwkqa6/q3KrihQ98kAAAAJcEhZcwAACxMAAAsTAQCanBgAAATxSURBVHjapVeJcuI4EJXBdiRuw4JzDAFyzeIT22BsNgTIJNnM7Pz/90xLsmV5ChJm6SqqZOR+7teXWujsgLSqdU0jBCFCNK1ebR16D+39t1HXiKqqGDHBsCRavXEsQKutIVWln0aZ0BX8o7VbRwC06gS+LHQLIWAJqbc+A6iC+h7t3BCVVD8EaGgqOqSemaFqjcMA8PkP1RnEb0bIAPXD1peNqO8H0NQj1LkR2j6Ao/XLCOh/6JcQkOD/B/oUoV4GqGb6+HNdnCFUZYBG9nmsE/whBsZE5y9g0pAAcgcQQ1V0fAgDNnRFNQiW3cAA2lwfI3wxvunqyl4z4OOK3r0ZX2CUIbRzgFZOoHY9nW7NXt9QdFTGgCddMfq9cDudXteyLdLKAPII4NqXZcffzIPJQx8zDCFgev9hksw3fmf5pYalSCDJAGAw7Uz9zkuU2CNKRQiYPrIT76Xjwws5B/BjiwG0hQHAgIr/GHpeYvb+EtIzI88LH32+fy1MaDMAKOGCAUdYPnmmE82ERI7pPS25fsEB0UCgs4ZwVO08AwB5sT0zrmQSm7b94mff7yzPa8LBDQAQSSwo5DRsKxO7MF+mwNyIBAPwjHEhIQCNgOsHwnwmF4aeWwAcUEMO97DgABAvkUv13WgrqXeWQ7moGqiqFtkivJjTCADBDWTzZR9SE6pIquOSF6msGYdgPS0BSD4EJ6CikUB+DKcd2QkRB4hkF3SmQyyqHioKaViicF4AQEp7DqfgRJDCSwFxLlPQ5GMAAHJ9n4bRyQEcGkZ/HwColwBYHH3fXz6uHc+xnZgCxLDwnPXj0mcgUhRpOZSblTEE9c32ybMi27ELAHiILO9puwGIoXG48YEJ43UYzGYumG/LADbQcGezIFyPjRr+7aCREfTezLUqFtMB4QB87cSw4c56uqyPSz4A/S6UDuikqzkTmwLYfL1K4aFiVbolBCKHEWHlclahyRvMF4vFarWgOm5KV4vFnIbEqswuFUmD5oF0olAGFZ7+88VqvV05FMBZbderxZwXRqXEgSaSfCTp3cDiAIETvr2+riP64K1fX99ClhMA4AIH+YAqFVPGgGnFu+9v44Quk/Hb913suXyjzAGKSS7nnAEtgBg6WeAxLIjrLM56A+NQKueioVAGruW67OdWrCCwYqoS01XgZmLJHGhDkVqa3oXeSyUESaktvBrBJ5WU/sd3IxFI3tKKpkrwCDIQcjCkUfPAnIAJ+NSjcQ1tuuuNMCk11TORCVh5SEyWdXP2dmzxpk4TEzDnbMtM/lakligfLADQj3gOOysASNPd5l+QzS5NAWCVbUV9RTBol442cIIxsVnlwPthurtv/sOkeb9LQ2oS25qIcs6PNtmNvch0HBOKN/15P3h+5wDvz4P7/1IocNhzop7swvLxTjMpMm0viSa9m6/Pg+cf35j8gOXXm94kSjzbjIo8Esd7cbxCIBNzdNs3dAXdDQbN9ybIe3MwuEOKbvRvR2YigigNGNKMh28vu0ihswGp9ZuDJpNBs0+HFjjuUffyFpcnvfKQhbgym06wcnXHAe6umNWYjSlKkcXlMa8YpIrEIldMCMHyrLNvzDs0aBImxwyap4+6pw/bp4/71A/opAvH6Vee0y9dn1z70OfXvuziudcMSKdjLp786quecPWVL99Zfqt/ePkuX/8Jv/43Dl3/fwH9bPJ09nq7MQAAAABJRU5ErkJggg==",Ll="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAQlBMVEVMaXGGl/+Elf+HmP+Hmf+Hl/+Gl/+Flv+Glv+Gl/+Gl/+Gl/////+On/+Akv/4+f/v8f/i5v+9x//S2P+tuP+erP+W3PvUAAAAC3RSTlMArBlx7Isy/vvOXbb4wDYAAAAJcEhZcwAACxMAAAsTAQCanBgAAALuSURBVHjarVfbtqsgDOxu0UBpkOv//+pJRC0i2HZ58uTeqzOEyYXkduvY/Tn8KSEBpFB/w3O8/WTjoCSS6dn4S6rha477QxFGS0nHM56ckJL/ox73b+CDQAQJujKiQxTDR4qH4LN109gP8Ti/uyI46K4BUagTLZ4Cz+CZAsWzhx/oeP3RyImhjf/7ePzmxF8Hr7+zNsP3eL7GkWH4Bc8MlQ7P3/DMsIvFKHRLPzBsTWVBizIfVNMBg9H7mLQxTRdUkb9tfJxebNZjywuJW1bf2xcw4WXtzDF5bVqXuJ9HwETHNnPYeHRii0THgcwQyBxTBDQ9Fx7dEBr0TOCDYyeS6aigsFsCQIFgBh9YiVgxQA7EqM9KiCiS95nh5WsGPZ4k8ZZFRqfoY4shy9i8AaExxRgTMgcApuSODPMdRtn02wc7Z9HkPMsPa1ZVOsiRygga4udfZ5vTKKx/7GIBVFJHCUy0r705DNu3LQ9kEQ6NxMTXwWzhUTD7xlJr2MLvrZCBVazy2OD0iaC4BGh1k4cSLOSbbIuujKW4wT76aYefrGswuBJSEoBeUnaFk7nQcKEIJZRXMPsfM95O3p3KKAoRa/cJTh0pHKMybSqyiO8wMsG0wzODi7UK9u0Ah7FIJAj1+UyQcl4Gqi2uax+L/siJVKQyi+j251sbMoHTZrUqlctiojDGRX27WpivYNtdi4upKme0c/gXBmdzY7ZoOi/cWDeU7MJy+oKn3hzbT9/cFKt6pmKe9udnCoTeG103VW7EjrGZJMOD863GNzfVQ0EDP6aJUH61wBRHGZa23npYDDpuh8EnpPBRS6UUQOg9r8enzaDdmhmsPkH/da3bokkr/i0dwMmYU7lg0pRrwiVzNrW+n/dKhVzVVIbGnE9Jj86IA8glk87h+xGnGrJyzXwYNvdD1uUx7/qgeX3UvT5sXx/3ry8c11ee60vX9bXvvXjWfsC3i+d79YV19+WPH1bf/7B8Lxy8/isBINTp+v8Ph4CTcAywkiYAAAAASUVORK5CYII=",zl="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAPFBMVEVMaXGZhueZh+eYhuWXheWYh+eYhuaXheCYhuaah+j//fmhjvOSf+Sdi+q8sOzNxO/m4fT08fapmuja0/Jb/wGxAAAACnRSTlMArEz/IYtsA87sGIEBYwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAmJJREFUeNqtV4uSgyAMRIECGhTk///1otTKG3s2Mzdz03aXbEJIQkhuYv9jIx+komhKDnxk4v1F1wT+SoxcUj3PWu8Ex39U8lH4bzt4QthL6tlDA8OP5Iv1vMADGFc5+uRQnDWdEES81EwbNquXqDuBx8va6ZcXktUYBOkc/3GixsBvwA8neFGGGO7hdyeGAsMXeM/wBJ8ziLv6LwYeisD4f4lHhiAXmH9FvzYV3AchOw6At9gFKW4KANDbsttGoSyCKd1Ab4uxkzezhBQaRfQygHB3oj2FhjwT9QgifErM6jiOrQgAXe2UmcuiIKSuHG+mki2XCH0kYqzgF1vETyYszLFaxLBMNdsgDGNFAazRoUcwrDMlDYz28RS0newGcCRlDa8TK4YgxuORGj9x8NYVEsxjKQSp/pNAw5YRcJI/JP5nYeqxjAxeIfCeRQQDyWOos/y5xR2V4NIgYhRJVkjgpralBPcvQH4PsBxIX0DjJqKRdgYLtsYPUyqh60CsACXEQew7ECvAICZp7DqwQEIQXaR+CkzaoeKr3FewQdqg4mIy36VgLyZWz4G96N5vs8sKj0UPSlJGy4fAbWX88SgGQYgJVjDXi7JaaxYo9Oj4UQ0lrHCGdN25ceiEfNoZSfIomjhcKN26DarT0q4gaiyfe2C9u9hWNUBvRghbG+yd1AZNFFrjmu+ucXMF2j60OObE7f0m+mrv/5qQkimpO+IU8fKXQ9bDMe/5oPl81P3BsP183EeGu3GoLBw/WHnuLF20sXQ9X/ueL57PV99w+Z7P5Vvj8j3fXr7j9X/f/5Vsrv9/K3NM7mGXOq0AAAAASUVORK5CYII=",Zn="data:image/svg+xml,%3csvg width='8' height='11' viewBox='57 6 8 11' fill='none' xmlns='http://www.w3.org/2000/svg'%3e %3cpath d='M62.7081 13.27C62.742 13.27 62.7642 13.3057 62.7491 13.3362V13.336L61.1229 16.6083C61.0892 16.6761 60.9926 16.6759 60.959 16.6083L59.3382 13.336C59.3232 13.3057 59.3453 13.27 59.3792 13.27H62.7081Z' fill='%23EA4B4B'/%3e %3cpath d='M61.0026 9.71913C61.0194 9.68524 61.0678 9.68524 61.0845 9.71913L62.747 13.0897C62.762 13.12 62.7399 13.1557 62.706 13.1557H59.3763C59.3424 13.1557 59.3203 13.12 59.3353 13.0897L61.0026 9.71913Z' fill='%23EA4B4B'/%3e %3cpath d='M60.8426 9.63827C60.8766 9.63827 60.8987 9.6741 60.8835 9.70444L59.2164 13.0594C59.1995 13.0932 59.1513 13.0932 59.1345 13.0594L57.5001 9.77047C57.47 9.70962 57.5142 9.63827 57.5821 9.63827H60.8426Z' fill='%23EA4B4B'/%3e %3cpath d='M64.5036 9.63617C64.5715 9.63618 64.6157 9.70753 64.5855 9.76838H64.5854L62.9512 13.0573C62.9344 13.0911 62.8862 13.0912 62.8692 13.0573L61.2021 9.70235C61.187 9.672 61.2091 9.63617 61.2431 9.63617H64.5036Z' fill='%23EA4B4B'/%3e %3cpath d='M62.8284 6.18281C62.862 6.11518 62.9586 6.11518 62.9922 6.18281L64.5855 9.38969C64.6157 9.45054 64.5715 9.52189 64.5036 9.52189H61.2431C61.2091 9.52189 61.187 9.48605 61.2021 9.45571L62.8283 6.18265L62.8284 6.18281Z' fill='%23EA4B4B'/%3e %3cpath d='M62.3131 6.13196C62.381 6.13196 62.4252 6.20331 62.3951 6.26416C62.154 6.74935 61.9128 7.23455 61.6718 7.71975H61.6716C61.4225 8.22125 61.1733 8.72259 60.9242 9.22409C60.9074 9.25799 60.859 9.25799 60.8422 9.22409L60.6305 8.79587C60.6275 8.78957 60.6259 8.78263 60.6259 8.77553V6.22349C60.6259 6.17297 60.6668 6.13196 60.7173 6.13196H62.3131Z' fill='%23EA4B4B'/%3e%3c/svg%3e";const Xn=v.getChainMeta(1)?.logo??"",ql=v.TOKENS.find(e=>e.symbol==="USDC")?.logo??"",yn=Object.fromEntries([...v.getMainnetChains(),...v.getTestnetChains()].map(e=>[e.id,e.logo])),Jn={metamask:Hr,metaMask:Hr,rabby:Ll,phantom:zl},ho=Object.fromEntries(v.TOKENS.map(e=>[e.symbol.toUpperCase(),e.logo])),Hl={usdc:[8453,1,42161,5115,4114],usdt:[1],btc:[4114,42161,1,5115],wbtc:[1],weth:[8453,1],eth:[8453,1,42161,4663,84532,46630],ctusd:[5115,4114],wcbtc:[5115,4114]},Vl={btc:["wcbtc","cbtc","wbtc"]};function Cs(e){return e.replace(/^test\s*/i,"").replace(/^spice/i,"").trim()}function un(e){return Cs(e).toLowerCase()}function Vr(e){return un(e??"").replace(/[^a-z0-9]/g,"")}function go(e){const t=un(e);return[t,...Vl[t]??[]].filter(Boolean)}function Ql(e){try{return BigInt(e.balanceAvailable||"0")}catch{return 0n}}function Qr(e){return Array.isArray(e.chainTokens)?e.chainTokens:Object.keys(e.chainTokens??{})}function Gr(e,t){const n=f.getChainConfig(e),s=t.toLowerCase();return s===v.ZERO_ADDRESS.toLowerCase()?n?.nativeCurrency.decimals??18:n?.supportedTokens?.find(o=>o.address.toLowerCase()===s)?.decimals??18}function Gl(e,t,n,s=[]){const o=Gr(t,n),r=e.filter(l=>Yr(l,t,n,s));if(r.length===0)return null;const i=r.reduce((l,c)=>Math.min(l,c.decimals??o),o);return{chainDecimals:o,receiptDecimals:i}}function Yr(e,t,n,s){if(Qr(e).some(r=>{const i=dn(r);return i&&Kn(i.address,i.chainId,n,t)}))return!0;const o=new Set(s.map(Vr).filter(Boolean));return o.size===0?!1:o.has(Vr(e.tokenName||e.receiptToken))}function Kr(e,t,n,s=[]){const o=Gr(t,n);return e.reduce((r,i)=>Yr(i,t,n,s)?r+v.convertAmountBetweenDecimals(Ql(i),i.decimals??o,o):r,0n)}function Zr(e,t){const n=new Set([...go(t),...go(Cs(t))]);return[...e].sort((s,o)=>{const r=un(s.symbol),i=un(o.symbol),l=un(s.name),c=un(o.name),d=n.has(r)?0:n.has(l)?1:2,p=n.has(i)?0:n.has(c)?1:2;return d!==p?d-p:s.address.toLowerCase().localeCompare(o.address.toLowerCase())})[0]}function Yl(e){const t=e&&e.length>0?e:Object.keys(f.CHAIN_CONFIGS).map(Number).filter(Number.isFinite),n=new Map;for(const s of t){const o=f.getChainConfig(s);if(!o)continue;const r=`${s}:${v.ZERO_ADDRESS.toLowerCase()}`;n.has(r)||n.set(r,{address:v.ZERO_ADDRESS,chainId:s,symbol:o.nativeCurrency.symbol,name:o.nativeCurrency.name,decimals:o.nativeCurrency.decimals,isNative:!0,logoURI:ho[o.nativeCurrency.symbol.toUpperCase()]??o.logo});for(const i of o.supportedTokens??[]){const l=i.address.toLowerCase(),c=`${s}:${l}`;n.has(c)||n.set(c,{address:l,chainId:s,symbol:i.symbol,name:i.name,decimals:i.decimals,isNative:v.isNativeToken(l),logoURI:i.logo})}}return n}function Kl(e,t){const n=Yl(t),s=Cs(e.tokenName),o=un(e.tokenName),r=go(e.tokenName),i=Array.isArray(e.chainTokens)?e.chainTokens.map(g=>[g,void 0]):Object.entries(e.chainTokens??{}),l=i.map(([g])=>dn(g)).filter(g=>g!==null),c=new Map;for(const[g,y]of i){const w=dn(g);if(!w||!Number.isSafeInteger(w.chainId)||w.chainId<0||!/^evm:[0-9]+:(?:0x)?[0-9a-fA-F]{40}$/.test(g)){if(!Array.isArray(e.chainTokens))throw new Error("Invalid chain token metadata identity");continue}if(y!==void 0&&(!y||typeof y!="object"||Array.isArray(y)||y.name!==void 0&&typeof y.name!="string"||y.decimals!==void 0&&(!Number.isInteger(y.decimals)||y.decimals<0||y.decimals>255)))throw new Error("Invalid chain token metadata");const C=`${w.chainId}:${w.address.toLowerCase()}`;if(c.has(C)){const b=c.get(C);if(b?.name!==y?.name||b?.decimals!==y?.decimals)throw new Error("Conflicting chain token metadata")}c.set(C,y)}const d=(g,y)=>{const w=c.get(`${y.chainId}:${y.address.toLowerCase()}`);return{...g,name:typeof w?.name=="string"&&w.name.length>0?w.name:g.name,decimals:typeof w?.decimals=="number"?w.decimals:g.decimals}},p=l.map(g=>{const y=n.get(`${g.chainId}:${g.address.toLowerCase()}`);return y?d(y,g):void 0}).filter(g=>g!==void 0),m=Hl[o]??[];if(m.length>0)for(const g of m){const y=p.filter(w=>w.chainId===g);if(y.length>0)return Zr(y,e.tokenName)}if(p.length>0)return Zr(p,e.tokenName);const h=Array.from(n.values()).filter(g=>r.includes(un(g.symbol))||r.includes(un(g.name)));if(m.length>0)for(const g of m){const y=h.find(w=>w.chainId===g);if(y)return y}if(h.length>0)return h[0];const x=l[0];if(x){const g=c.get(`${x.chainId}:${x.address.toLowerCase()}`);return{address:x.address,chainId:x.chainId,symbol:s||e.tokenName,name:typeof g?.name=="string"&&g.name.length>0?g.name:s||e.tokenName,decimals:typeof g?.decimals=="number"?g.decimals:e.decimals??18,isNative:v.isNativeToken(x.address),logoURI:void 0}}}function Zl(e,t){let n;try{n=BigInt(e.balanceAvailable||"0")}catch{return null}if(n<=0n)return null;if(t?.length){const g=Qr(e).map(dn).filter(y=>y!==null);if(g.length>0&&!g.some(y=>t.includes(y.chainId)))return null}let s;try{s=Kl(e,t)}catch{return null}const o=s?.decimals??e.decimals??18,r=e.decimals??o,i=v.convertAmountBetweenDecimals(n,r,o),l=s?.address??v.ZERO_ADDRESS,c=s?.chainId??0,d=Cs(e.tokenName),p=s?.symbol??d,m=s?.name??d,h=parseFloat(T.formatUnits(i,o)),x=typeof e.balanceUsd=="number"?e.balanceUsd:typeof e.balanceUsd=="string"&&Number(e.balanceUsd)||0;return{address:l,symbol:p,name:m,decimals:o,chainId:c,balance:i,balanceFormatted:h,balanceUsd:x,isNative:s?.isNative??v.isNativeToken(l),logoURI:s?.logoURI,displaySymbol:d||p,displayName:d||m,displayChainName:"Spicenet",receiptTokenId:e.receiptToken,receiptTokenName:e.tokenName||m,receiptTokenDecimals:r,chainTokens:e.chainTokens&&!Array.isArray(e.chainTokens)?e.chainTokens:void 0,isUniversal:!0}}const xo=6e4,Xl=3e5,Xr="https://api.g.alchemy.com/prices/v1",Dn=new Map;function yo(e,t){try{const n=t??f.getClientForChain(e).transport.url;if(typeof n!="string")return null;const{hostname:s,pathname:o}=new URL(n);if(!s.endsWith(".g.alchemy.com"))return null;const r=o.split("/").filter(Boolean).pop();return r?{network:s.slice(0,-14),key:r}:null}catch{return null}}const $n=(e,t)=>`${e.network}:${e.key}:${t.toLowerCase()}`;function _n(e,t){const n=Dn.get($n(e,t));if(!n?.price||n.updatedAt===void 0)return;const s=Date.now()-n.updatedAt;if(!(s>=Xl))return{price:n.price,stale:s>=xo}}function Jr(e){const t=Number(e.prices?.find(n=>n.currency==="usd")?.value);return Number.isFinite(t)&&t>0?t:0}async function $r(e,t,n){const s=[],o=new Set,r=Date.now();for(const i of new Set(t.map(l=>l.toLowerCase()))){const l=Dn.get($n(e,i));l?.pending?o.add(l.pending):(!l||r-l.attemptedAt>=xo&&(l.updatedAt===void 0||r-l.updatedAt>=xo))&&s.push(i)}for(let i=0;i<s.length;i+=25){const l=s.slice(i,i+25),c=Promise.resolve().then(async()=>{try{const d=await n(l);for(const p of l){const m=d.get(p);if(!m)continue;const h=Dn.get($n(e,p));h.price=m,h.updatedAt=Date.now()}}catch{}finally{for(const d of l)Dn.get($n(e,d)).pending=void 0}});for(const d of l){const p=$n(e,d);Dn.set(p,{...Dn.get(p),attemptedAt:r,pending:c})}o.add(c)}await Promise.all(o)}async function wo(e,t){return await $r(e,t,async n=>{const s=await fetch(`${Xr}/${e.key}/tokens/by-address`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({addresses:n.map(i=>({network:e.network,address:i}))}),signal:AbortSignal.timeout(1e4)});if(!s.ok)throw new Error("Provider price request failed");const o=await s.json(),r=new Map;for(const i of o?.data??[]){if(i.network&&i.network!==e.network)continue;const l=String(i.address).toLowerCase();n.includes(l)&&r.set(l,Jr(i))}return r}),new Map(t.map(n=>[n.toLowerCase(),_n(e,n)?.price??0]))}async function bo(e,t){const n=`native:${t}`;return await $r(e,[n],async()=>{const s=await fetch(`${Xr}/${e.key}/tokens/by-symbol?symbols=${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(1e4)});if(!s.ok)throw new Error("Provider native price request failed");const o=(await s.json())?.data?.find(r=>r.symbol?.toUpperCase()===t.toUpperCase());return new Map([[n.toLowerCase(),o?Jr(o):0]])}),_n(e,n)?.price??0}async function Jl(e,t){const n=t.supportedChains,s=e.map(o=>{if(Number.isFinite(o.balanceUsd)&&o.balanceUsd>0)return[];const r=Object.keys(o.chainTokens??{}).map(dn).filter(i=>!!i&&T.isAddress(i.address)&&!!n?.includes(i.chainId));return r.sort((i,l)=>{const c=d=>d===t.nativeChainId?-1:n.indexOf(d);return c(i.chainId)-c(l.chainId)||+!f.addressesEqual(i.address,o.address)-+!f.addressesEqual(l.address,o.address)}),r.flatMap(i=>{const l=t.rpcOverrides?.[i.chainId];if(!l)return[];const c=yo(i.chainId,l);if(!c)return[];const d=v.isNativeToken(i.address)?f.getChainConfig(i.chainId)?.nativeCurrency.symbol:void 0,p=d?`native:${d}`:i.address;return[{rpc:c,token:p,address:i.address,nativeSymbol:d}]})});return(typeof document>"u"||!document.hidden)&&await Promise.all(s.map(async o=>{for(const r of o)if(r.nativeSymbol?await bo(r.rpc,r.nativeSymbol).catch(()=>0):(await wo(r.rpc,[r.address]).catch(()=>new Map)).get(r.address.toLowerCase()))break})),e.map((o,r)=>{if(Number.isFinite(o.balanceUsd)&&o.balanceUsd>0)return o;const i=s[r].map(l=>_n(l.rpc,l.token)).find(Boolean);return{...o,balanceUsd:i?o.balanceFormatted*i.price:0,priceStatus:i?i.stale?"stale":"fresh":"unavailable"}})}function $l(e,t,n){const s=u.useContext(f.SpiceFlowProviderContext),[o,r]=u.useState(()=>typeof document>"u"||!document.hidden);u.useEffect(()=>{const p=()=>r(!document.hidden);return document.addEventListener("visibilitychange",p),()=>document.removeEventListener("visibilitychange",p)},[]);const i={supportedChains:n??s?.supportedChainIds,nativeChainId:s?.nativeChainId,rpcOverrides:s?.rpcOverrides},l=JSON.stringify([e,i],(p,m)=>typeof m=="bigint"?m.toString():m),c=u.useCallback(()=>Jl(e,i),[l]),d=mo(`prices:${l}`,c,t&&o&&e.length>0,6e4);return d.updatedAt?d.assets:e}function _l(e){const t=e.chainTokens??e.chainTokenConfig;if(Array.isArray(t))return t.filter(n=>typeof n=="string");if(t&&typeof t=="object")return t}const _r=({address:e,supportedChains:t,enabled:n=!0,refetchInterval:s,priceEnabled:o=!1})=>{const r=u.useContext(f.SpiceFlowProviderContext),i=r?.apiUrl||f.RELAYER_API_URL,l=bs(),c=r?.supportedChainIds??t,d=JSON.stringify([...c??[]].sort((k,E)=>k-E)),p=e?.toLowerCase(),m=u.useCallback(async()=>{const k=await f.relayerFetch(`${i}/wallets/${p}/balance`,{cache:"no-store"});if(!k.ok)throw new Error(`Failed to fetch balance: ${k.status}`);const E=await k.json();if(!Array.isArray(E.balances))throw new Error("Invalid balance response");return E.balances.map(R=>{const j=Zl({receiptToken:typeof R.receiptToken=="string"?R.receiptToken:void 0,tokenName:String(R.tokenName??""),balanceAvailable:String(R.balanceAvailable??"0"),chainTokens:_l(R),decimals:typeof R.decimals=="number"?R.decimals:void 0,balanceUsd:typeof R.balanceUsd=="number"||typeof R.balanceUsd=="string"?R.balanceUsd:null},c);return j?{...j,owner:p,location:"rollup",_source:"spice",positionId:`${p}:rollup:${j.receiptTokenId??j.address}`}:null}).filter(R=>R!==null)},[p,i,d,r?.nativeChainId,r?.rpcOverrides]),{assets:h,loading:x,refreshing:g,error:y,updatedAt:w}=mo(`rollup:${p}:${i}:${d}`,m,n&&!!p,s??0,l),C=JSON.stringify(t??[]),b=u.useMemo(()=>y?h.map(k=>({...k,balanceError:y,balanceStatus:"stale"})):h,[h,y]),S=$l(b,n&&o,c),I=u.useMemo(()=>S.filter(k=>!t?.length||t.includes(k.chainId)||Object.keys(k.chainTokens??{}).some(E=>t.some(R=>E.startsWith(`evm:${R}:`)))),[S,C]),F=u.useCallback(k=>I.filter(E=>E.chainId===k),[I]);return{assets:I,loading:x,error:y,hasBalance:I.some(k=>k.balance>0n),refreshing:g,updatedAt:w,refetch:l.invalidate,getAssetsByChain:F}};async function ec(e,t,n){if(n)return{decimals:n.decimals,symbol:n.symbol,name:n.name,logoURI:n.logo};const[s,o,r]=await Promise.all([_t.readContract(e,{address:t,abi:T.erc20Abi,functionName:"decimals"}),_t.readContract(e,{address:t,abi:T.erc20Abi,functionName:"symbol"}).catch(()=>"TOKEN"),_t.readContract(e,{address:t,abi:T.erc20Abi,functionName:"name"}).catch(()=>"TOKEN")]);if(!Number.isInteger(Number(s))||Number(s)<0||Number(s)>255)throw new Error("Invalid token decimals");return{decimals:Number(s),symbol:o,name:r,logoURI:void 0}}const ea=async(e,t,n)=>{const s=f.getClientForChain(t,n),o=f.getChainConfig(t),r=await _t.getBalance(s,{address:e}),i=o.nativeCurrency,l=o.supportedTokens?.find(c=>v.isNativeToken(c.address));return{address:v.ZERO_ADDRESS,name:i.name,symbol:i.symbol,decimals:i.decimals,balance:r,balanceFormatted:Number(T.formatUnits(r,i.decimals)),balanceUsd:0,logoURI:l?.logo||o.logo,isNative:!0,chainId:t}},tc=async(e,t,n,s,o,r,i)=>{try{if(!T.isAddress(n))return null;const l=T.getAddress(n),c=T.isAddress(e)?T.getAddress(e):e,d=f.getClientForChain(t,i),p=await _t.readContract(d,{address:l,abi:T.erc20Abi,functionName:"balanceOf",args:[c]}),m=Number(T.formatUnits(p,r));return p>0n?{address:l,name:s,symbol:o,decimals:r,balance:p,balanceFormatted:m,balanceUsd:0,logoURI:void 0,isNative:!1,chainId:t}:null}catch(l){throw l}},ta=(e,t)=>{const n=f.getChainConfig(t);if(!n)return e;const s=new Set(e.map(r=>r.address.toLowerCase())),o=e.some(r=>r.isNative);for(const r of n.supportedTokens||[])v.isNativeToken(r.address)&&o||s.has(r.address.toLowerCase())||e.push({address:r.address,name:r.name,symbol:r.symbol,decimals:r.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:r.logo,isNative:v.isNativeToken(r.address),chainId:t});if(!e.find(r=>r.isNative)){const r=n.supportedTokens?.find(i=>v.isNativeToken(i.address));e.push({address:v.ZERO_ADDRESS,name:n.nativeCurrency.name,symbol:n.nativeCurrency.symbol,decimals:n.nativeCurrency.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:r?.logo||n.logo,isNative:!0,chainId:t})}return e},nc=async(e,t,n)=>{const s=[],o=async l=>{for(const c of l){const d=await tc(e,t,c.address,c.name,c.symbol,c.decimals,n);d&&(d.logoURI=c.logo,s.push(d))}},r=await ea(e,t,n);r.balance>0n&&s.push(r);const i=(f.getChainConfig(t)?.supportedTokens||[]).filter(l=>!v.isNativeToken(l.address));if(i.length>0)try{const l=f.getClientForChain(t,n),c=T.getAddress(e),d=i.filter(x=>T.isAddress(x.address)).map(x=>({address:T.getAddress(x.address),abi:T.erc20Abi,functionName:"balanceOf",args:[c]})),p=await l.multicall({contracts:d}),m=i.filter(x=>T.isAddress(x.address)),h=[];p.forEach((x,g)=>{if(x.status==="success"){const y=x.result;if(y&&y>0n){const w=m[g],C=Number(T.formatUnits(y,w.decimals));y>0n&&s.push({address:T.getAddress(w.address),name:w.name,symbol:w.symbol,decimals:w.decimals,balance:y,balanceFormatted:C,balanceUsd:0,logoURI:w.logo,isNative:!1,chainId:t})}}else h.push(m[g])}),await o(h)}catch{await o(i)}return{tokens:ta(s,t),chainId:t}},sc=async(e,t,n)=>{const s=new Map,o=yo(e,n?n[e]??"":void 0);if(!o)return s;const r=t.filter(d=>v.isNativeToken(d)),i=t.filter(d=>!v.isNativeToken(d)),[l,c]=await Promise.all([i.length?wo(o,i).catch(()=>new Map):new Map,r.length?bo(o,f.getChainConfig(e)?.nativeCurrency?.symbol??"ETH").catch(()=>0):0]);for(const[d,p]of l)p>0&&s.set(d,p);if(c>0)for(const d of r)s.set(d.toLowerCase(),c);return s},oc=async(e,t,n,s=!0,o)=>{const r=f.getClientForChain(t,o),i=T.getAddress(e),l=[];let c;do{const C=await r.request({method:"alchemy_getTokenBalances",params:[i,"erc20",c?{pageKey:c}:{}]});l.push(...C.tokenBalances),c=C.pageKey||void 0}while(c);const d=l.filter(C=>T.isAddress(C.contractAddress)&&!!C.tokenBalance&&BigInt(C.tokenBalance)>0n),p=f.getChainConfig(t)?.supportedTokens||[],m=C=>p.find(b=>b.address.toLowerCase()===C.toLowerCase()),h=[],x=await ea(e,t,o),[g,y,w]=await Promise.all([Promise.all(d.map(async C=>{const b=m(C.contractAddress);return b?{name:b.name,symbol:b.symbol,decimals:b.decimals,logo:b.logo??null}:await r.request({method:"alchemy_getTokenMetadata",params:[C.contractAddress]})})),s?wo(n,d.map(C=>C.contractAddress)):new Map(d.map(C=>[C.contractAddress.toLowerCase(),_n(n,C.contractAddress)?.price??0])),s&&x.balanceFormatted>0?bo(n,x.symbol):_n(n,`native:${x.symbol}`)?.price??0]);return x.balance>0n&&h.push({...x,balanceUsd:w*x.balanceFormatted}),d.forEach((C,b)=>{const S=g[b];if(!Number.isInteger(S.decimals)||S.decimals===null||S.decimals<0||S.decimals>255)throw new Error(`Invalid token metadata on chain ${t}`);const I=BigInt(C.tokenBalance),F=Number(T.formatUnits(I,S.decimals));if(I<=0n)return;const k=y.get(C.contractAddress.toLowerCase()),E=k?k*F:0;h.push({address:T.getAddress(C.contractAddress),name:S.name||"Unknown",symbol:S.symbol||"UNKNOWN",decimals:S.decimals,balance:I,balanceFormatted:F,balanceUsd:E,isDiscovered:!m(C.contractAddress),logoURI:S.logo||void 0,isNative:!1,chainId:t})}),{tokens:ta(h,t),chainId:t}},na=new Set,rc=async(e,t,n=!0,s)=>{try{const o=yo(t,s?s[t]??"":void 0);if(o)try{return await oc(e,t,o,n&&(typeof document>"u"||!document.hidden),s)}catch(r){na.has(t)||(na.add(t),console.warn(`Token discovery unavailable on chain ${t}; listing configured tokens only.`,r))}return await nc(e,t,s)}catch(o){throw o}},On=async(e,t,n=[],s)=>{if(!e)throw new Error("Wallet address is required");const o=f.getChainsForAssets(s),r=t?.length?[...new Set(t)]:Object.keys(o).map(Number),i=await Promise.allSettled(r.map(c=>rc(e,c,!0,s))),l={};return i.forEach((c,d)=>{const p=r[d];l[p]=c.status==="fulfilled"?c.value:{chainId:p,tokens:[],error:`Unable to refresh balances on chain ${p}`}}),(await Promise.allSettled(n.map(async c=>{const d=l[c.chainId];if(!d||d.error||d.tokens.some(y=>v.normalizeNativeTokenAddress(y.address).toLowerCase()===v.normalizeNativeTokenAddress(c.address).toLowerCase()))return;const p=f.getClientForChain(c.chainId,s),m=await ec(p,c.address,c.decimals!==void 0&&c.symbol?{decimals:c.decimals,symbol:c.symbol,name:c.name||c.symbol,logo:c.logoURI}:void 0),h=await _t.readContract(p,{address:c.address,abi:T.erc20Abi,functionName:"balanceOf",args:[e]}),x=await sc(c.chainId,[c.address],s),g=Number(T.formatUnits(h,m.decimals));d.tokens.push({...m,...c,name:m.name,symbol:m.symbol,decimals:m.decimals,balance:h,balanceFormatted:g,balanceUsd:(x.get(c.address.toLowerCase())||0)*g,isNative:!1})}))).forEach((c,d)=>{if(c.status==="rejected"){const p=l[n[d].chainId];p&&(p.error=`Unable to refresh token balances on chain ${p.chainId}`)}}),l},es=({address:e,supportedChains:t,fetchBalances:n=On,additionalTokens:s=[],enabled:o=!0,refreshInterval:r=0,priceEnabled:i=!0})=>{const l=u.useContext(f.SpiceFlowProviderContext),c=bs(),d=e?.toLowerCase(),p=JSON.stringify([...l?.supportedChainIds??t??[]].sort((b,S)=>b-S)),m=JSON.stringify(s);u.useEffect(()=>c.registerTokens(s),[c,m]);const h=d&&d===l?.embeddedWalletAddress?.toLowerCase()?"embedded":"external",x=`wallet:${JSON.stringify([l?.network,l?.apiUrl,l?.rpcOverrides])}:${d}:${h}:${p}:${c.fetcherId(n)}`,g=u.useCallback(async()=>{let b;try{b=await n(d,JSON.parse(p),c.tokens(),l?.rpcOverrides)}catch(k){const E=k instanceof Error?k.message:"Unable to refresh balances";b=Object.fromEntries(JSON.parse(p).map(R=>[R,{chainId:R,tokens:[],error:E}]))}const S=c.entry(x).snapshot().assets,I=JSON.parse(p).map(k=>b[k]??{chainId:k,tokens:[],error:`Unable to refresh balances on chain ${k}`}),F=I.flatMap(k=>k.error?[k.error]:[]);return{assets:I.flatMap(k=>k.error?S.filter(E=>E.chainId===k.chainId).map(E=>({...E,balanceError:k.error,balanceStatus:"stale"})):k.tokens.map(E=>({...E,owner:d,location:h,_fundingWallet:h,_source:"wallet",positionId:`${d}:${h}:${k.chainId}:${v.normalizeNativeTokenAddress(E.address).toLowerCase()}`}))),error:F.length?F.join("; "):null}},[c,d,p,n,h,x]),y=mo(x,g,o&&!!d,r,c),w=JSON.stringify(t&&[...t].sort((b,S)=>b-S)),C=u.useMemo(()=>t?y.assets.filter(b=>t.includes(b.chainId)):y.assets,[y.assets,w]);return u.useEffect(()=>{i&&o&&d&&y.refresh()},[i]),{...y,assets:C,refreshAssets:c.invalidate,getAssetsByChain:u.useCallback(b=>C.filter(S=>S.chainId===b),[C]),getNativeAssets:u.useCallback(()=>C.filter(b=>b.isNative),[C])}};function Nn(e){const t=u.useContext(f.SpiceFlowProviderContext),n=bs(),s=e.owner??((t?.mode||"7702")!=="7702"?t?.externalWalletAddress:t?.embeddedWalletAddress),o=s?.toLowerCase()!==t?.embeddedWalletAddress?.toLowerCase(),r=e.sourceChains??t?.supportedChainIds??[],i=(e.enabled??!0)&&!t?.isWhitelistGateActive,l=u.useMemo(()=>{const h=[...t?.additionalSourceTokens??[],...e.additionalSourceTokens??[],...e.destination?[e.destination]:[]];for(const x of e.supportedSourceAssets??[])for(const g of r){const y=f.getChainConfig(g)?.supportedTokens?.find(w=>f.isAssetAllowed(w,[x]));y&&h.push({...y,address:y.address,chainId:g,logoURI:y.logo})}return h},[e.destination,JSON.stringify(t?.additionalSourceTokens),JSON.stringify(e.additionalSourceTokens),JSON.stringify(e.supportedSourceAssets),JSON.stringify(r)]),c=es({address:s,supportedChains:r,fetchBalances:On,additionalTokens:l,enabled:i&&e.includeWalletAssets!==!1,refreshInterval:3e4}),d=_r({address:s,supportedChains:r,enabled:i&&e.includeRollupAssets!==!1&&!!s&&s.toLowerCase()===t?.embeddedWalletAddress?.toLowerCase(),priceEnabled:i,refetchInterval:3e4}),p=u.useMemo(()=>i?[...(e.includeWalletAssets===!1?[]:c.assets).map(h=>({...h,owner:h.owner??s,location:h.location??(o?"external":"embedded"),_source:"wallet"})),...(e.includeRollupAssets===!1||s?.toLowerCase()!==t?.embeddedWalletAddress?.toLowerCase()?[]:d.assets).map(h=>({...h,owner:h.owner??s,location:"rollup",_source:"spice"}))]:[],[i,c.assets,d.assets,e.includeWalletAssets,e.includeRollupAssets,s,o,t?.embeddedWalletAddress]),m=u.useMemo(()=>p.map(h=>({asset:h,...kn(h,e.role??"holding",{allowedTokens:t?.allowedTokens,rpcOverrides:t?.rpcOverrides,liquidityVenues:t?.liquidityVenues,isWhitelistGateActive:!!t?.isWhitelistGateActive},e.destination,e.supportedSourceAssets,{requiresEscrow:e.requiresEscrow})})),[p,t?.allowedTokens,t?.rpcOverrides,t?.liquidityVenues,t?.isWhitelistGateActive,e.role,e.destination,e.supportedSourceAssets,e.requiresEscrow]);return{positions:m,assets:u.useMemo(()=>m.filter(h=>h.eligible&&h.asset.balance>0n).map(h=>h.asset),[m]),walletAssets:u.useMemo(()=>p.filter(h=>h._source==="wallet"),[p]),rollupAssets:u.useMemo(()=>p.filter(h=>h._source==="spice"),[p]),loading:c.loading||d.loading,refreshing:c.refreshing||d.refreshing,error:c.error||d.error,refresh:n.invalidate}}function wn(e){const t=v.normalizeNativeTokenAddress(e.address);if(e.isNative||v.isNativeToken(t))return!1;const n=f.getChainConfig(e.chainId)?.supportedTokens?.some(o=>f.addressesEqual(o.address,t)),s=v.getTokenByAddress(t,e.chainId);return!!n&&!!s&&xs(s)}const sa="spiceflow:pendingDeposit",vs="spiceflow:pendingDepositChanged";function oa(e,t,n){return`${sa}:${e.toLowerCase()}:${t}:${n.toLowerCase()}`}function Co(){try{const e="__spiceflow_storage_test__";return localStorage.setItem(e,"1"),localStorage.removeItem(e),!0}catch{return!1}}function ac(e){if(!Co())return;const t=oa(e.embeddedWalletAddress,e.chainId,e.tokenAddress);try{localStorage.setItem(t,JSON.stringify(e)),window.dispatchEvent(new Event(vs))}catch(n){console.error("[pendingDeposit] Failed to save:",n)}}function ic(e){if(!Co())return[];const t=`${sa}:${e.toLowerCase()}:`,n=[],s=Date.now();for(let o=0;o<localStorage.length;o++){const r=localStorage.key(o);if(!(!r||!r.startsWith(t)))try{const i=localStorage.getItem(r);if(!i)continue;const l=JSON.parse(i);if(s-l.timestamp>6048e5){localStorage.removeItem(r);continue}n.push(l)}catch{localStorage.removeItem(r)}}return n}function vo(e,t,n){if(!Co())return;const s=oa(e,t,n);localStorage.removeItem(s),window.dispatchEvent(new Event(vs))}const lc=new Set(["USDC","SUSD","USD","NUSD","USDT","DAI","ENUSD","USDG"]),ra={ETH:"ethereum",WETH:"ethereum",BTC:"bitcoin",WBTC:"bitcoin",WCBTC:"bitcoin",CBTC:"bitcoin",ECBTC:"bitcoin",ARB:"arbitrum",MATIC:"matic-network",POL:"matic-network"};let ks=null;const cc=6e4;async function aa(e){const t={},n=new Set,s={};for(const r of e){const i=r.toUpperCase();if(lc.has(i))t[i]=1;else if(ra[i]){const l=ra[i];n.add(l),s[i]=l}else t[i]=0}if(n.size===0)return t;const o=Date.now();if(ks&&o-ks.timestamp<cc){for(const[r,i]of Object.entries(s))t[r]=ks.prices[i]??0;return t}try{const r=Array.from(n).join(","),i=await fetch(`https://api.coingecko.com/api/v3/simple/price?ids=${r}&vs_currencies=usd`);if(!i.ok)throw new Error(`CoinGecko ${i.status}`);const l=await i.json(),c={};for(const d of n)c[d]=l[d]?.usd??0;ks={prices:c,timestamp:o};for(const[d,p]of Object.entries(s))t[d]=c[p]??0}catch(r){console.warn("[fetchTokenPrices] CoinGecko fetch failed:",r);for(const i of Object.keys(s))t[i]=t[i]??0}return t}const dc=new Set(["cbtc","btc","wbtc","wcbtc","tbtc"]),uc=new Set(["usdc","usdt","dai","usdc.e","usdbc","usdg"]);async function pc(){const e=(await aa(["BTC"])).BTC;if(!e||e<=0)throw new Error("Failed to fetch BTC/USD price");return e}function fc(e){return dc.has(e.toLowerCase())}function mc(e){return uc.has(e.toLowerCase())}function hc(e,t,n,s){const o=10n**12n,r=BigInt(Math.round(s*Number(o))),i=t-n,l=10n**BigInt(Math.abs(i));let c=e*r/o;return i>0?c=c/l:i<0&&(c=c*l),c}const gc=.01,xc=5*60*1e3;function yc(e){const t=Number(T.formatUnits(e.verifiedBalance,e.tokenDecimals));return Number.isFinite(t)?t:0}async function wc(e){const t=bc(e);let n;try{n=await aa(t.map(s=>s.tokenSymbol))}catch{return t}return t.filter(s=>{const o=yc(s);if(o<=0)return!0;const r=n[s.tokenSymbol.toUpperCase()]??0;return!Number.isFinite(r)||r<=0?!0:o*r>=gc})}function bc(e){const t=new Map;for(const n of e){const s=`${n.chainId}:${n.tokenAddress.toLowerCase()}`;t.get(s)||t.set(s,{...n,amount:n.timestamp===0?T.formatUnits(n.verifiedBalance,n.tokenDecimals):n.amount,rawAmount:n.timestamp===0?n.verifiedBalance.toString():n.rawAmount,hasFullBalance:n.timestamp===0?!0:n.hasFullBalance})}return Array.from(t.values())}function ia(e,t){const[n,s]=u.useState([]),[o,r]=u.useState(!1),i=u.useRef(t);i.current=t;const l=u.useRef(0),c=u.useRef(0),d=u.useCallback(async({forceDiscovery:p=!1}={})=>{if(!e){s([]),r(!1);return}const m=++c.current,h=()=>m!==c.current;r(!0);try{const x=[],g=ic(e);for(const b of g){if(h())return;if(wn({address:b.tokenAddress,chainId:b.chainId,isNative:b.isNative}))try{const S=f.getClientForChain(b.chainId);let I;if(b.isNative||v.isNativeToken(b.tokenAddress)?I=await _t.getBalance(S,{address:e}):I=await _t.readContract(S,{address:T.getAddress(b.tokenAddress),abi:T.erc20Abi,functionName:"balanceOf",args:[e]}),h())return;I>0n?x.push({...b,verifiedBalance:I,hasFullBalance:I>=BigInt(b.rawAmount)}):Date.now()-b.timestamp>15*60*1e3&&vo(e,b.chainId,b.tokenAddress)}catch(S){console.warn(`[usePendingDeposit] Failed to verify balance for ${b.tokenSymbol} on chain ${b.chainId}:`,S),x.push({...b,verifiedBalance:0n,hasFullBalance:!1})}}if(h())return;const y=i.current,w=Date.now(),C=(y?.discoverWalletBalances??!0)&&(p||w-l.current>=xc);if(y?.network&&C){l.current=w;const b=y.chainIds??v.getChainIdsByNetwork(y.network),S=new Set(x.map(F=>`${F.chainId}:${F.tokenAddress.toLowerCase()}`)),I=[];for(const F of b){const k=f.getChainConfig(F);if(k?.supportedTokens)for(const E of k.supportedTokens){if(!wn({address:E.address,chainId:F,isNative:!1}))continue;const R=`${F}:${E.address.toLowerCase()}`;S.has(R)||I.push((async()=>{try{const j=f.getClientForChain(F),A=await _t.readContract(j,{address:T.getAddress(E.address),abi:T.erc20Abi,functionName:"balanceOf",args:[e]});return A>0n?{chainId:F,tokenAddress:E.address,tokenSymbol:E.symbol,tokenDecimals:E.decimals,amount:T.formatUnits(A,E.decimals),rawAmount:A.toString(),embeddedWalletAddress:e,externalWalletAddress:"",timestamp:0,isNative:!1,verifiedBalance:A,hasFullBalance:!0}:null}catch{return null}})())}}if(I.length>0){const F=await Promise.allSettled(I);if(h())return;for(const k of F)k.status==="fulfilled"&&k.value&&x.push(k.value)}}if(!h()){const b=await wc(x);if(h())return;s(b)}}catch(x){console.error("[usePendingDeposit] Verification error:",x),h()||s([])}finally{h()||r(!1)}},[e]);return u.useEffect(()=>{if(!i.current?.enabled){c.current++,s([]),r(!1);return}d({forceDiscovery:!0});const p=i.current?.pollIntervalMs??3e4;if(p<=0||!e)return()=>{c.current++};const m=setInterval(()=>{d({forceDiscovery:!1})},p),h=()=>d({forceDiscovery:!0});return window.addEventListener(vs,h),()=>{c.current++,window.removeEventListener(vs,h),clearInterval(m)}},[d,e]),{pendingDeposits:n,loading:o,refresh:()=>d({forceDiscovery:!0})}}function la(e){const t=u.useContext(f.SpiceFlowProviderContext),n=t?.embeddedWalletAddress,s=e?.enabled===!1?void 0:n,o=t?.network?{network:t.network,pollIntervalMs:e?.pollIntervalMs,chainIds:e?.chainIds??t.supportedChainIds,discoverWalletBalances:e?.discoverWalletBalances}:void 0;return{...ia(s,o),embeddedWalletAddress:n}}var ko="data:image/svg+xml,%3csvg width='10' height='10' viewBox='0 0 10 10' fill='none' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M5 4.99995V6.99995M5 3.31245V3.31189M9.5 5C9.5 7.48528 7.48528 9.5 5 9.5C2.51472 9.5 0.5 7.48528 0.5 5C0.5 2.51472 2.51472 0.5 5 0.5C7.48528 0.5 9.5 2.51472 9.5 5Z' stroke='black' stroke-opacity='0.4' stroke-linecap='round' stroke-linejoin='round'/%3e%3c/svg%3e";function So(e){const t=u.useRef(0),n=u.useRef(null),s=u.useRef(e.run);s.current=e.run;const o=u.useRef(e.onSkip);o.current=e.onSkip;const r=u.useRef(e.onCleanup);r.current=e.onCleanup,u.useEffect(()=>{if(!e.shouldRun){t.current+=1,n.current?.abort(),o.current?.();return}let i=!1,l=!1;const c=async m=>{if(m&&l)return;n.current?.abort();const h=new AbortController;n.current=h;const x=++t.current;l=!0;try{await s.current({isBackground:m,isCurrent:()=>!i&&t.current===x,signal:h.signal})}finally{l=!1}},d=window.setTimeout(()=>void c(!1),e.delayMs??250),p=e.backgroundIntervalMs?window.setInterval(()=>void c(!0),e.backgroundIntervalMs):void 0;return()=>{i=!0,n.current?.abort(),clearTimeout(d),p!==void 0&&window.clearInterval(p),r.current?.()}},[e.shouldRun,e.delayMs,e.backgroundIntervalMs,...e.deps])}function ca(e,t){if(e.length!==t.length)return!1;const n=v.hashChainBatches(e),s=v.hashChainBatches(t);return n.every((o,r)=>o.hash===s[r]?.hash)}const en=e=>new Promise(t=>setTimeout(t,e)),Cc="0xa9059cbb";function da(e){const t=e.findIndex(o=>v.isSpicenetChainId(o.chainId));if(t<=0)return[];const n=new Map,s=(o,r,i)=>{if(i<=0n)return;const l=`${o}:${r.toLowerCase()}`,c=n.get(l);c?c.amount+=i:n.set(l,{chainId:o,token:r,amount:i})};for(const o of e.slice(0,t)){const r=v.getEscrowContract(o.chainId);if(!(!r||r===v.ZERO_ADDRESS)){for(const i of o.calls)if(i.value&&i.value>0n&&f.addressesEqual(i.to,r)&&s(o.chainId,v.ZERO_ADDRESS,i.value),!!i.data?.startsWith(Cc))try{const l=T.decodeFunctionData({abi:T.erc20Abi,data:i.data});if(l.functionName!=="transfer")continue;const[c,d]=l.args;f.addressesEqual(c,r)&&s(o.chainId,i.to,d)}catch{}}}return[...n.values()]}function ua(e){const t=v.getTokenByAddress(e.token,e.chainId);return[t?.equivalenceGroup,t?.symbol,t?.name]}function pa(e,t){return Kr(e,t.chainId,t.token,ua(t))}function vc(e,t){const n=Gl(e,t.chainId,t.token,ua(t));return!n||n.receiptDecimals>=n.chainDecimals?t.amount:v.convertAmountBetweenDecimals(v.convertAmountBetweenDecimals(t.amount,n.chainDecimals,n.receiptDecimals),n.receiptDecimals,n.chainDecimals)}async function kc(e){const{deposits:t,baseline:n,fetchEntries:s,timeoutMs:o=12e4,intervalMs:r,signal:i,wait:l=en}=e;if(t.length===0)return!0;const c=new Map(t.map(m=>[m,pa(n,m)])),d=Date.now(),p=d+o;for(;!i?.aborted;){try{const g=await s();if(t.every(y=>pa(g,y)-c.get(y)>=vc(g,y)))return!0}catch{}const m=Date.now();if(m>=p)return!1;const h=m-d,x=r??(h<5e3?250:h<15e3?1e3:3e3);await l(Math.min(x,p-m))}return!1}function Sc(e,t){const n=v.hashChainBatches(e).map(s=>s.hash);return T.keccak256(T.encodeAbiParameters([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,t,n]))}async function Ic(e,t,n,s,o){if(s?.aborted)throw new f.SpiceflowError("ABORT","Execution transaction aborted");const r={raw:Sc(t,n)},i=o?await e.signMessage(r,o):await e.signMessage(r);console.debug("[SpiceFlow:execution]",{phase:"signature-returned",at:Date.now()});const l=typeof i=="string"?i:i.signature;if(!l)throw new f.SpiceflowError("SIGNATURE_FAILED","Failed to sign intent authorization. The wallet returned an empty signature.");return l}function Ac(e){return e.domain==="spicenet"||v.isSpicenetChainId(e.chainId)}async function Ec(e){const{chainBatches:t,signingAddress:n,actions:s,cache:o,signal:r,onSignatureRequested:i,beforeSign:l}=e;if(r?.aborted)throw new f.SpiceflowError("ABORT","Execution transaction aborted");const c=[...new Set(t.filter(m=>!Ac(m)).map(m=>m.chainId))].map(m=>({chainId:m,client:f.getClientForChain(m),delegateContract:f.getDelegateContractAddress(m)})),[d]=await Promise.all([Promise.all(c.map(async({chainId:m,client:h,delegateContract:x})=>{const g=Number(await v.getAccountNonce(n,h)),y=[n.toLowerCase(),m,x.toLowerCase(),g].join(":");return{chainId:m,delegateContract:x,nonce:g,cacheKey:y,cached:o?.get(y)}})),c.length?s.prepareSigning?.():void 0,l?.()]),p=[];for(const{chainId:m,delegateContract:h,nonce:x,cacheKey:g,cached:y}of d){if(y){p.push(y);continue}if(r?.aborted)throw new f.SpiceflowError("ABORT","Execution transaction aborted");const w=await s.signAuthorization({contractAddress:h,chainId:m,nonce:x},i),C={r:w.r,s:w.s,yParity:w.yParity,address:w.address??h,chainId:Number(w.chainId??m),nonce:Number(w.nonce??x)};o?.set(g,C),p.push(C)}return p}const fa=15;function Fc(e){return e.now-e.lastProgressAt>=e.pollTimeoutMs}function ma(e,t){return{intentId:e,steps:t.map(n=>({...n,status:"pending"})),overallStatus:"processing"}}function Ss(e,t,n){const s=e.steps.map(l=>({...l})),o=s[t];if(!o)return e;n.status==="success"||n.status==="completed"?(s[t]={...o,status:"success",transactionHash:n.transactionHash},t+1<s.length&&s[t+1].status==="pending"&&(s[t+1]={...s[t+1],status:"processing"})):n.status==="reverted"||n.status==="error"?s[t]={...o,status:"failed",transactionHash:n.transactionHash,error:n.error}:s[t]={...o,status:"processing"};const r=s.some(l=>l.status==="failed"),i=s.every(l=>l.status==="success");return{...e,steps:s,overallStatus:r?"failed":i?"success":"processing"}}function Tc({checkStepStatus:e,retryStep:t,maxRetries:n=3,pollingInterval:s=2500,pollTimeoutMs:o=3e5}){const[r,i]=u.useState(null),l=u.useRef(null),c=u.useRef(null),d=u.useRef(!1),p=u.useRef(!1),m=u.useRef(0),h=u.useRef({}),x=u.useRef(0),g=u.useCallback(I=>{l.current=I,i(I)},[]),y=u.useCallback(()=>{c.current&&(clearInterval(c.current),c.current=null)},[]),w=u.useCallback(()=>{m.current=0,h.current={},x.current=0,d.current=!0,y(),g(null)},[y,g]),C=u.useCallback((I,F)=>{y(),d.current=!1,g(ma(I,F))},[y,g]),b=u.useCallback((I,F)=>{const k=l.current;k&&g(Ss(k,I,F))},[g]),S=u.useCallback((I,F)=>{y(),d.current=!1,p.current=!1,m.current=0,h.current={},x.current=Date.now(),g(ma(I,F));const k=async()=>{if(!(d.current||p.current||!e)){p.current=!0;try{if(Fc({now:Date.now(),lastProgressAt:x.current,pollTimeoutMs:o})){const j=l.current;j&&g({...j,steps:j.steps.map(A=>A.status==="success"?A:{...A,status:"failed",error:"Taking longer than expected. It may still complete - check the explorer, then refresh."}),overallStatus:"failed"}),d.current=!0,y();return}const E=l.current;if(!E)return;const R=E.steps.findIndex(j=>j.status!=="success");if(R===-1){d.current=!0,y();return}if(!(R===0||E.steps[R-1].status==="success"))return;try{const j=E.steps[R].stepId,{data:A}=await e(I,j);if(m.current=0,A.status==="success"&&(x.current=Date.now()),A.status==="reverted"){const P=h.current[j]||0;if(t&&P<n){h.current[j]=P+1;try{await t(I,j)}catch(N){console.error(`[intentStatus] retry failed for step ${j}:`,N)}g(Ss(l.current,R,{status:"executing"}));return}}const M=Ss(l.current,R,A);g(M),M.overallStatus!=="processing"&&(d.current=!0,y())}catch(j){m.current+=1,console.error(`[intentStatus] poll error (${m.current}/${fa}):`,j),m.current>=fa&&(g(Ss(l.current,R,{status:"error"})),d.current=!0,y())}}finally{p.current=!1}}};k(),c.current=setInterval(k,s)},[e,t,n,s,o,y,g]);return u.useEffect(()=>()=>y(),[y]),{intentStatus:r,startStatusPolling:S,beginStatusTracking:C,applyStepUpdate:b,stopStatusPolling:y,clearStatus:w}}function jc(e,t){return(t||"").trim()||`Transaction ${e}. The transaction was rejected on-chain. This may be due to insufficient balance, price changes, or health factor constraints. Please verify your positions and try again.`}const Bc=350,Rc=2500;async function ha(e){const{actionId:t,intentIndex:n,intentId:s,stepIndex:o,maxPolls:r=48,maxExecuteAttempts:i=3,pollsBeforeRetry:l=5,maxConsecutiveStatusErrors:c=15,onStatusMessage:d,onStepUpdate:p,signal:m,chainId:h}=e;if(m?.aborted)throw new f.SpiceflowError("ABORT","Execution transaction aborted");let x="pending",g,y,w=0,C=0,b,S;const I=new Promise((k,E)=>{b=k,S=()=>E(new f.SpiceflowError("ABORT","Execution transaction aborted"))}),F=()=>{w++,f.relayerService.executeStep(t,n,o,{action:"execute"}).then(k=>{k.transactionHash&&(g=k.transactionHash),k.status==="success"&&b({status:k.status,transactionHash:k.transactionHash})}).catch(k=>{const E=k instanceof Error?k.message:String(k);console.warn(`[execution] executeStep ${o} attempt ${w} error (will poll):`,E)})};m?.addEventListener("abort",S,{once:!0});try{F();for(let k=0;k<r;k++){const E=k===0?Bc:Rc;try{const j=await Promise.race([en(E).then(()=>{}),I]);if(m?.aborted)throw new f.SpiceflowError("ABORT","Execution transaction aborted");const A=j??await Promise.race([f.relayerService.checkStepStatus(s,o).then(P=>P.data),I]);if(m?.aborted)throw new f.SpiceflowError("ABORT","Execution transaction aborted");C=0,x=A.status,y=A.error;const M=A.transactionHash;M&&(g=M),p?.({status:x,transactionHash:g,error:y})}catch(j){if(j instanceof Error&&(j.name==="AbortError"||j instanceof f.SpiceflowError&&j.code==="ABORT")||(C++,C>=c))throw j;continue}if(x==="created"&&k>=w*l&&w<i&&F(),x==="reverted"||x==="error")throw new f.SpiceflowError("ON_CHAIN_REVERT",jc(x,y),{status:x,txHash:g,actionId:t,intentId:s,stepId:o,chainId:h});if(x==="success"||x==="completed")return g;let R="Waiting for solver...";x==="executing"?R="Transaction executing...":x==="submitted"?R="Transaction submitted...":x==="created"&&(R="Waiting for relayer..."),d?.(R,g)}throw new f.SpiceflowError("POLLING_EXHAUSTED",`Transaction is still processing (status: ${x}). This doesn't mean it failed \u2014 the solver may still complete it. Check your positions in a few minutes, or try refreshing the page.`,{actionId:t,intentId:s,stepId:o,lastStatus:x,pollAttempts:r,maxPolls:r,txHash:g})}finally{m?.removeEventListener("abort",S)}}async function Dc(e){const{actionId:t,intentIndex:n,intentId:s,totalSteps:o,delayBeforeSpicenetStepMs:r=5e3,isSpicenetStep:i,beforeStep:l,maxExecuteAttemptsForStep:c,maxPolls:d=48,onStatusMessage:p,onStepUpdate:m,signal:h}=e;let x;for(let g=0;g<o;g++){if(g>0&&i?.(g)&&r>0&&await en(r),await l?.(g),h?.aborted)throw new f.SpiceflowError("ABORT","Execution transaction aborted");const y=c?.(g)??3,w=await ha({actionId:t,intentIndex:n,intentId:s,stepIndex:g,maxPolls:d,maxExecuteAttempts:y,maxConsecutiveStatusErrors:y===6?5:15,onStatusMessage:p,onStepUpdate:m?C=>m(g,C):void 0,signal:h});w&&(x=w)}return x}const Oc="0xa9059cbb";function Io(e,t){return e.map(n=>{if(n.domain==="spicenet"||v.isSpicenetChainId(n.chainId)||n.calls.length===0)return n;const s=new Set((n.tokenTransfers??[]).filter(i=>(i.from==="escrow"||i.from==="solver")&&f.addressesEqual(i.to,t)).map(i=>i.token.toLowerCase()));if(s.size===0)return n;const o=[...s].some(v.isNativeToken);let r=0;for(const i of n.calls){if(o&&i.value>0n&&i.data==="0x"&&!f.addressesEqual(i.to,t)){r+=1;continue}if(!i.data?.startsWith(Oc))break;try{const l=T.decodeFunctionData({abi:T.erc20Abi,data:i.data});if(l.functionName!=="transfer")break;const[c]=l.args;if(f.addressesEqual(c,t)||!s.has(i.to.toLowerCase()))break;r+=1}catch{break}}return r===0?n:{...n,calls:n.calls.slice(r)}})}async function Nc(e,t){if(!t||!/^0x[0-9a-f]{64}$/i.test(t))throw new Error("The destination receipt is not available yet; reconcile the existing action before retrying.");const n=await e.waitForTransactionReceipt({hash:t,timeout:12e4,pollingInterval:2e3,confirmations:1});if(n.transactionHash?.toLowerCase()!==t.toLowerCase()||n.status!=="success")throw new Error("The destination transaction has not been confirmed successfully. Reconcile the existing action before retrying.");return t}async function Is(e){let t=e.hash,n=!1;const s=Date.now()+12e4,o=i=>i.transactionHash&&i.transactionHash.toLowerCase()!==t.toLowerCase();let r=await e.client.waitForTransactionReceipt({hash:t,timeout:12e4,pollingInterval:2e3,confirmations:1,onReplaced:i=>{const l=i.transaction,c=i.replacedTransaction;if(!(i.reason==="repriced"&&c?.from&&c.nonce!==void 0&&/^0x[0-9a-f]{64}$/i.test(l?.hash??"")&&l?.to?.toLowerCase()===e.call.to.toLowerCase()&&(l.input??"0x").toLowerCase()===e.call.data.toLowerCase()&&BigInt(l.value??0)===e.call.value&&l.from?.toLowerCase()===c?.from?.toLowerCase()&&l.nonce===c?.nonce)){n=!0,e.onCancelled?.();return}t=l.hash,e.onRepriced?.(t)}});if(n)throw new Error("Transaction was cancelled or replaced with a different action; retry the unfinished action");if((e.confirmations??1)>1&&!o(r)&&r.status==="success"&&(r=await e.client.waitForTransactionReceipt({hash:t,timeout:Math.max(s-Date.now(),1),pollingInterval:2e3,confirmations:e.confirmations})),o(r))throw new Error("Unexpected transaction receipt; recover the submitted transaction before retrying");return{receipt:r,hash:t}}const Mc=10n,Pc=10n,Uc=5;function Ao(e){return e.map(t=>({...t,calls:[...t.calls],tokenTransfers:t.tokenTransfers?[...t.tokenTransfers]:void 0}))}function As({token:e,recipient:t,amount:n}){return{to:e,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"transfer",args:[t,n]})}}function Wc({chainBatches:e,token:t,amount:n}){const s=Ao(e),o=s[s.length-1];if(!o)return s;const r=v.getEscrowContractAddress(o.chainId);return o.calls=[...o.calls,As({token:t,recipient:r,amount:n})],s}function ga({chainBatches:e,user:t,token:n,grossAmount:s,gasFee:o}){const r=Ao(e),i=r[r.length-1];if(!i)throw new f.SpiceflowError("INVALID_PARAMS","Action-output escrow funding requires at least one chain batch.");const l=f.calculateBpsFee(s,Pc),c=o+l;if(c>=s)throw new f.SpiceflowError("INVALID_PARAMS","Borrow amount is too small after gas and Spicenet fees.",{grossAmount:s.toString(),gasFee:o.toString(),spicenetFee:l.toString()});const d=s-c,p=v.getEscrowContractAddress(i.chainId),m=[];return o>0n&&m.push(As({token:n,recipient:v.SPICE_GAS_FEE_RECIPIENT,amount:o})),l>0n&&m.push(As({token:n,recipient:v.SPICE_PLATFORM_FEE_RECIPIENT,amount:l})),i.calls=[...i.calls,...m,As({token:n,recipient:p,amount:d})],i.tokenTransfers=[...i.tokenTransfers??[],...o>0n?[{from:t,to:v.SPICE_GAS_FEE_RECIPIENT,token:n,amount:o}]:[],...l>0n?[{from:t,to:v.SPICE_PLATFORM_FEE_RECIPIENT,token:n,amount:l}]:[],{from:t,to:p,token:n,amount:d}],{chainBatches:r,gasFee:o,spicenetFee:l,netEscrowAmount:d,outputCredit:{chainId:i.chainId,token:n,amount:s}}}async function xa({chainBatches:e,user:t,token:n,grossAmount:s,chainAuthorizations:o}){let r=0n,i=ga({chainBatches:e,user:t,token:n,grossAmount:s,gasFee:r});for(let l=0;l<Uc;l+=1){const c=v.hashChainBatches(i.chainBatches),d=(await f.relayerService.estimateBatchGas({user:t,outputToken:n,chainBatches:i.chainBatches.map((p,m)=>({...p,hash:c[m].hash})),chainAuthorizations:o})).gasFee;if(d===r)return i;r=d,i=ga({chainBatches:e,user:t,token:n,grossAmount:s,gasFee:r})}throw new f.SpiceflowError("INVALID_PARAMS","Action-output fee estimate did not converge. Please retry.")}function pn(e){return v.isSpicenetChainId(e.chainId)}const Lc="0xa9059cbb";function ts(e,t){return`${e}:${v.normalizeNativeTokenAddress(t).toLowerCase()}`}function ya(e,t){return t===v.ZERO_ADDRESS.toLowerCase()?{symbol:f.getChainName(e),decimals:18}:v.getTokenByAddress(t,e)??{symbol:"tokens",decimals:18}}function zc(e,t){const n=v.getTokenByAddress(t,e);return[n?.equivalenceGroup,n?.symbol,n?.name]}async function Eo(e){return f.getWalletBalanceEntries(e)}async function qc(e,t,n){const s=new Map,o=n?.walletFundingRequirement,r=o&&ts(o.chainId,o.token);r&&s.set(r,0n);const i=new Map,l=new Map,c=new Map,d=new Map;for(const m of n?.actionOutputCredits??[]){const h=ts(m.chainId,m.token);d.set(h,(d.get(h)??0n)+m.amount)}for(const m of e){if(pn(m))continue;for(const g of m.tokenTransfers??[]){if(g.from!=="escrow"&&g.from!=="solver"||!f.addressesEqual(g.to,t))continue;const y=BigInt(g.amount??0);if(y<=0n)continue;const w=ts(m.chainId,g.token);i.set(w,(i.get(w)??0n)+y),g.from==="escrow"&&l.set(w,(l.get(w)??0n)+y)}const h=v.getEscrowContract(m.chainId),x=g=>!!h&&h!==v.ZERO_ADDRESS&&f.addressesEqual(g,h);for(const g of m.calls){if(g.value&&g.value>0n){const y=ts(m.chainId,v.ZERO_ADDRESS);s.set(y,(s.get(y)??0n)+g.value),x(g.to)&&c.set(y,(c.get(y)??0n)+g.value)}if(g.data?.startsWith(Lc))try{const y=T.decodeFunctionData({abi:T.erc20Abi,data:g.data});if(y.functionName!=="transfer")continue;const[w,C]=y.args,b=g.to.toLowerCase(),S=ts(m.chainId,b);s.set(S,(s.get(S)??0n)+C),x(w)&&c.set(S,(c.get(S)??0n)+C)}catch{}}}let p=null;for(const[m,h]of l){const x=h-(c.get(m)??0n);if(x<=0n)continue;const[g,y]=m.split(":"),w=Number(g),C=ya(w,y);p??(p=await Eo(t));const b=Kr(p,w,y,zc(w,y));if(!(b>=x))throw new f.SpiceflowError("INVALID_PARAMS",`Insufficient Spice ${C.symbol}: needs ${T.formatUnits(x,C.decimals)}, has ${T.formatUnits(b,C.decimals)}.`,{chainId:w,token:y,userAddress:t,requiredAmount:x.toString(),balance:b.toString(),balanceSource:"spice"})}for(const[m,h]of s){const[x,g]=m.split(":"),y=Number(x);let w=h-(i.get(m)??0n)-(d.get(m)??0n);if(o&&m===r&&o.amount>w&&(w=o.amount),w<=0n)continue;const C=f.getClientForChain(y),b=g===v.ZERO_ADDRESS.toLowerCase()?await C.getBalance({address:t}):await C.readContract({address:g,abi:T.erc20Abi,functionName:"balanceOf",args:[t]});if(b>=w)continue;const S=ya(y,g);throw new f.SpiceflowError("INVALID_PARAMS",`Insufficient ${S.symbol} on ${f.getChainName(y)}: needs ${T.formatUnits(w,S.decimals)}, has ${T.formatUnits(b,S.decimals)}.`,{chainId:y,token:g,userAddress:t,requiredAmount:w.toString(),balance:b.toString(),balanceSource:"wallet"})}}function Hc({chainBatches:e,tokenAddress:t,tokenTransferAmount:n,useCustomTransfers:s}){if(!(e.some(pn)||!(s?e.some(o=>pn(o)?!1:(o.tokenTransfers??[]).some(r=>r.from==="escrow"&&BigInt(r.amount??0)>0n)):n>0n)))throw new f.SpiceflowError("INVALID_PARAMS","Payouts funded from Spice balance require a Spicenet funding batch before the destination chain batch. Deposits into Spice balance and gas-only actions do not need one.",{tokenAddress:t,tokenTransferAmount:n.toString(),useCustomTransfers:!!s})}function Vc(e,t,n,s){t.forEach((o,r)=>{if(!o.to||!o.from||!o.token||o.amount===void 0)throw new f.SpiceflowError("INVALID_TOKEN_TRANSFER",`tokenTransfers[${r}] on chain ${e} is missing required fields (to/from/token/amount). This usually means the embedded wallet wasn't ready when the intent was built \u2014 please retry.`,{chainId:e,transferIndex:r,transfer:{from:o.from,to:o.to,token:o.token,amount:o.amount?.toString()},signingAddress:n,useCustomTransfers:s})})}function Es({user:e,chainBatches:t,tokenAddress:n,tokenTransferAmount:s,exp:o,signature:r,chainAuthorizations:i,useCustomTransfers:l}){const c=t,d=v.hashChainBatches(c),p=c.filter(m=>!pn(m)).length;if(Hc({chainBatches:c,tokenAddress:n,tokenTransferAmount:s,useCustomTransfers:l}),!l&&s>0n&&p>1)throw new f.SpiceflowError("INVALID_PARAMS","Multiple non-Spicenet batches require explicit tokenTransfers. Pass useCustomTransfers with per-batch transfers instead of relying on the default escrow payout injection.",{nonSpicenetBatchCount:p,tokenAddress:n,tokenTransferAmount:s.toString()});return{user:e,...i?{chainAuthorizations:i}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:r,nbf:0,exp:o,chainBatches:d.map((m,h)=>{const x=c[h],g=pn(x)?[]:l?x.tokenTransfers??[]:s>0n?[{from:"escrow",to:e,token:n,amount:s}]:[];return Vc(Number(m.chainId),g,e,l),{hash:m.hash,chainId:Number(m.chainId),tokenTransfers:g,calls:m.calls}})}]}}function wa(e,t){const n=t?.depositToEscrow?.gasFundingSource==="action-output"?t.depositToEscrow:null,s=t?.depositToEscrow&&!n?Wc({chainBatches:e,token:t.depositToEscrow.token,amount:t.depositToEscrow.amount}):Ao(e);return{actionOutputDeposit:n,batches:s}}let Fo=!1;function Fs(){const{address:e,isConnected:t,isAuthenticated:n,actions:s}=f.useWallet(),o=u.useRef(null),{intentStatus:r,startStatusPolling:i,beginStatusTracking:l,applyStepUpdate:c,clearStatus:d}=Tc({checkStepStatus:(w,C)=>f.relayerService.checkStepStatus(w,C),retryStep:async(w,C)=>{const[b,S]=w.split("/"),I=parseInt(S||"0",10);await f.relayerService.executeStep(b,I,C,{action:"execute"})}}),p=u.useRef(s),m=u.useRef(new Map);p.current=s;const h=u.useCallback((w,C,b,S,I)=>Ec({chainBatches:w,signingAddress:C,actions:p.current,cache:m.current,signal:b,onSignatureRequested:S,beforeSign:I}),[]),x=u.useCallback((w,C,b,S)=>Ic(p.current,w,C,b,S),[]),g=u.useCallback(async(w,C,b,S,I,F)=>{const k=(E,R,j)=>{S?.({step:E,message:R,...j})};if(Fo)throw new f.SpiceflowError("CONCURRENT_EXECUTION","A execution transaction is already in progress. Please wait.");Fo=!0;try{if(!e)throw new f.SpiceflowError("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const E=F?.userOverride||e,{actionOutputDeposit:R,batches:j}=wa(w,F);let A=j,M=[],P=F?.useCustomTransfers,N=da(A),B=null;const U=async()=>{for(let D=0;N.length>0&&D<3;D++)try{B=await Eo(E);break}catch(L){if(I?.aborted)throw new f.SpiceflowError("ABORT","Execution transaction aborted");if(D===2)throw new f.SpiceflowError("RELAYER_ERROR","Unable to read your Spice balance. Please try again before submitting the transaction.",{cause:L});await en(1e3)}await F?.validateBeforeSubmit?.(A)};k("building","Preparing your wallet and transaction...");const O=await h(A,E,I,()=>k("signing-delegation","Confirm the authorization in your wallet..."),U);if(k("building","Checking transaction fees and balances..."),I?.aborted)throw new f.SpiceflowError("ABORT","Execution transaction aborted");const z=BigInt(Math.floor(Date.now()/1e3)+3600);if(R){const D=await xa({chainBatches:w,user:E,token:R.token,grossAmount:R.amount,chainAuthorizations:O});A=D.chainBatches,M=[D.outputCredit],P=!0}if(!F?.skipPreSubmitFeeEstimate){let D=!1;if(F?.feeExecutionMode==="user-transfer"&&F.adjustBatchesForEstimate&&f.relayerService.canValidateActionFees()){const L=await f.relayerService.validateActionFees(Es({user:E,chainBatches:A,tokenAddress:C,tokenTransferAmount:b,exp:Number(z),signature:"0x00",chainAuthorizations:O,useCustomTransfers:P}),{signal:I});o.current=L;const $=await F.adjustBatchesForEstimate({feeEstimate:L,chainBatches:A});D=!$||ca(A,$),$&&(A=$)}for(let L=0;!D&&L<10;L++){const $=F?.feeExecutionMode==="user-transfer"?Io(A,E):A,de=Es({user:E,chainBatches:$,tokenAddress:C,tokenTransferAmount:b,exp:Number(z),signature:"0x00",chainAuthorizations:O,useCustomTransfers:P}),ce=await f.relayerService.estimateActionFees(de,{signal:I});o.current=ce;const he=await F?.adjustBatchesForEstimate?.({feeEstimate:ce,chainBatches:A}),X=!!he&&ca(A,he);if(!he||X){D=!0;break}A=he}if(!D)throw new f.SpiceflowError("INVALID_PARAMS","Fee estimate did not converge. Please retry.")}if(F?.prepareForSigning){const D=await F.prepareForSigning(A);if(D.length!==A.length||D.some((L,$)=>L.chainId!==A[$].chainId||L.domain!==A[$].domain))throw new Error("The funded route changed before signing");A=D}F?.resolveActionOutputCredits&&(M=await F.resolveActionOutputCredits()),(!F?.skipUserFundingPreflight||F.walletFundingRequirement)&&await qc(F?.skipUserFundingPreflight?[]:A,E,{actionOutputCredits:M,walletFundingRequirement:F?.walletFundingRequirement}),N=da(A),N.length&&!B&&(B=await f.getWalletBalanceEntries(E)),await F?.validateBeforeSubmit?.(A),k("building","Preparing the signing request...");const q=await x(A,z,I,()=>k("signing-intent","Confirm the transaction in your wallet..."));if(I?.aborted)throw new f.SpiceflowError("ABORT","Execution transaction aborted");k("submitting","Submitting to relayer...");const ue=Es({user:E,chainBatches:A,tokenAddress:C,tokenTransferAmount:b,exp:Number(z),signature:q,chainAuthorizations:O,useCustomTransfers:P}),le=Date.now();await F?.validateBeforeSubmit?.(A),console.debug("[SpiceFlow:execution]",{phase:"submit-check-complete",at:Date.now(),durationMs:Date.now()-le});const G=await f.relayerService.createAction(ue),[ne,re]=G.intentIds[0].split("/"),Y=parseInt(re||"0",10),_=`${ne}/${Y}`;k("executing","Executing on chain..."),k("executing","Executing on chain...",{actionId:ne,intentId:_,intentIndex:Y,totalSteps:A.length});const Z=A.length,pe=await Dc({actionId:ne,intentIndex:Y,intentId:_,totalSteps:Z,signal:I,...B?{delayBeforeSpicenetStepMs:0}:{},isSpicenetStep:D=>pn(A[D]),beforeStep:async D=>{if(!B||!pn(A[D]))return;const L=await kc({deposits:N,baseline:B,fetchEntries:()=>Eo(E),signal:I});if(I?.aborted)throw new f.SpiceflowError("ABORT","Execution transaction aborted");if(!L)throw new f.SpiceflowError("POLLING_EXHAUSTED","Your deposit is still waiting for Spice credit. Check this transaction's status before trying again.",{actionId:ne,intentId:_,stepId:D})},maxExecuteAttemptsForStep:D=>pn(A[D])?6:3,maxPolls:180,onStatusMessage:(D,L)=>{k("executing",D,{txHash:L,actionId:ne,intentId:_,intentIndex:Y,totalSteps:Z})}});if(F?.requireDestinationReceipt){const D=[...A].reverse().find(L=>!pn(L));if(!D)throw new Error("The action has no destination transaction to verify.");await Nc(f.getClientForChain(D.chainId),pe)}return k("success","Transaction successful!",{txHash:pe,actionId:ne,intentId:_,intentIndex:Y,totalSteps:Z}),pe||ne}catch(E){throw console.error("[Execution] Error:",E),k("error",E.message||"Transaction failed",{error:E.message}),E}finally{Fo=!1}},[e,n,h,x]),y=u.useCallback(async(w,C,b,S)=>{if(!e)throw new f.SpiceflowError("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const I=S?.userOverride||e,F=S?.validateFeeCalls===!0&&S.feeExecutionMode==="user-transfer"&&f.relayerService.canValidateActionFees(),{actionOutputDeposit:k,batches:E}=wa(w,S);let R=E;const j=S?.feeExecutionMode==="user-transfer"&&!F?Io(R,I):R,A=S?.signAuthorizationsForEstimate?await h(j,I):void 0;let M=S?.useCustomTransfers;k&&(R=(await xa({chainBatches:w,user:I,token:k.token,grossAmount:k.amount,chainAuthorizations:A})).chainBatches,M=!0);const P=S?.feeExecutionMode==="user-transfer"&&!F?Io(R,I):R,N=Es({user:I,chainBatches:P,tokenAddress:C,tokenTransferAmount:b,exp:Math.floor(Date.now()/1e3)+3600,signature:"0x00",chainAuthorizations:A,useCustomTransfers:M}),B=await(F?f.relayerService.validateActionFees(N,{signal:S?.signal}):f.relayerService.estimateActionFees(N,{signal:S?.signal}));return o.current=B,B},[e,h]);return{execute:g,estimate:y,lastFeeEstimate:o.current,hasEmbeddedWallet:t&&n,intentStatus:r,startStatusPolling:i,beginStatusTracking:l,applyStepUpdate:c,clearStatus:d}}const To=({color:e})=>a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:[a.jsx("circle",{cx:"7",cy:"7",r:"6.5",stroke:e,strokeWidth:"1.2"}),a.jsx("path",{d:"M7 6v4",stroke:e,strokeWidth:"1.2",strokeLinecap:"round"}),a.jsx("circle",{cx:"7",cy:"4.5",r:"0.7",fill:e})]}),ba=({content:e,label:t="More info",textColor:n="#f9fafb",backgroundColor:s="#111827",borderColor:o="rgba(255,255,255,0.08)",accentColor:r="#9ca3af",children:i})=>{const l=u.useId(),[c,d]=u.useState(!1),p=u.useRef(null),[m,h]=u.useState(!1),[x,g]=u.useState(null);u.useEffect(()=>{h(!0)},[]),u.useLayoutEffect(()=>{if(!c||!p.current)return;const w=()=>{if(!p.current)return;const C=p.current.getBoundingClientRect(),b=Math.min(220,window.innerWidth-48),S=Math.min(Math.max(C.left+C.width/2,24+b/2),window.innerWidth-24-b/2),I=C.top>84;g({top:I?C.top-10:C.bottom+10,left:S,placement:I?"top":"bottom"})};return w(),window.addEventListener("scroll",w,!0),window.addEventListener("resize",w),()=>{window.removeEventListener("scroll",w,!0),window.removeEventListener("resize",w)}},[c]);const y=c&&m&&x?jn.createPortal(a.jsxs("span",{id:l,role:"tooltip",style:{position:"fixed",left:x.left,top:x.top,transform:x.placement==="top"?"translate(-50%, -100%)":"translate(-50%, 0)",width:"220px",maxWidth:"min(220px, calc(100vw - 48px))",padding:"10px 12px",borderRadius:"10px",backgroundColor:s,color:n,border:`1px solid ${o}`,boxShadow:"0 18px 45px rgba(0,0,0,0.28)",fontSize:"11px",lineHeight:"1.45",fontWeight:500,textAlign:"left",zIndex:f.z.tooltip,pointerEvents:"none"},children:[e,a.jsx("span",{"aria-hidden":"true",style:{position:"absolute",left:"50%",width:"10px",height:"10px",transform:"translateX(-50%) rotate(45deg)",backgroundColor:s,...x.placement==="top"?{bottom:"-6px",borderRight:`1px solid ${o}`,borderBottom:`1px solid ${o}`}:{top:"-6px",borderTop:`1px solid ${o}`,borderLeft:`1px solid ${o}`}}})]}),document.body):null;return a.jsxs(a.Fragment,{children:[a.jsx("span",{ref:p,style:{position:"relative",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),children:a.jsx("button",{type:"button","aria-label":t,"aria-describedby":c?l:void 0,onFocus:()=>d(!0),onBlur:()=>d(!1),style:{width:"18px",height:"18px",borderRadius:"999px",display:"inline-flex",alignItems:"center",justifyContent:"center",border:`1px solid ${o}`,backgroundColor:"transparent",color:r,cursor:"help",padding:0,outline:"none",boxShadow:c?`0 0 0 2px ${r}26`:"none",transition:"border-color 120ms ease, box-shadow 120ms ease, color 120ms ease"},children:i||a.jsx(To,{color:r})})}),y]})},ns=(e,t,n,s)=>({width:e,height:e,fill:"none",className:t,"aria-hidden":n??!0,style:s}),Mn=({size:e=16,color:t="currentColor",strokeWidth:n=2,direction:s="down",className:o,style:r,"aria-hidden":i})=>a.jsx("svg",{...ns(e,o,i,{transform:s==="up"?"rotate(180deg)":void 0,transition:"transform 0.3s ease",...r}),viewBox:"0 0 16 16",children:a.jsx("path",{d:"M4 6L8 10L12 6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),Qc=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:s,style:o,"aria-hidden":r})=>a.jsxs("svg",{...ns(e,s,r,o),viewBox:"0 0 24 24",children:[a.jsx("circle",{cx:"11",cy:"11",r:"8",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"}),a.jsx("path",{d:"m21 21-4.3-4.3",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})]}),Gc=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:s,style:o,"aria-hidden":r})=>a.jsx("svg",{...ns(e,s,r,o),viewBox:"0 0 24 24",children:a.jsx("path",{d:"m6 9 6 6 6-6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),Yc=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:s,style:o,"aria-hidden":r})=>a.jsx("svg",{...ns(e,s,r,o),viewBox:"0 0 24 24",children:a.jsx("path",{d:"m9 18 6-6-6-6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),Ca=({size:e=14,color:t="currentColor",strokeWidth:n=2,className:s,style:o,"aria-hidden":r})=>a.jsx("svg",{...ns(e,s,r,o),viewBox:"0 0 16 16",children:a.jsx("path",{d:"M3 8L6.5 11.5L13 5",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})});function Ts(e,t){if(e===0n)return"0";const n=10n**BigInt(t),s=e/n,o=(e%n).toString().padStart(t,"0").replace(/0+$/,"");return o?`${s.toString()}.${o}`:s.toString()}function jo(e,t,n){const s=`${Ts(e,t)} ${n}`;return e===0n?s:`-${s}`}const Kc=({fontFamily:e,textPrimary:t,textSecondary:n,cardBg:s,cardBorder:o,resolvedDark:r,darkCardBorder:i,primaryColor:l,feePreview:c,asset:d,isLoading:p,errorText:m,directExecutionFeeNote:h=!1})=>{const x=f.useAssetDisplay(),g=d&&c&&[d.symbol,d.displaySymbol,d.receiptTokenName].includes(c.symbol)?x(d).symbol:c?.symbol,y=r?i??o:"#e5e7eb",w=r?"#111214":"#111827",C=r?"rgba(255,255,255,0.08)":"rgba(17,24,39,0.12)",b="#f87171",S=r?"#d1d5db":"#4b5563",I=r?"#f3f4f6":t,[F,k]=u.useState(!1),E=!!m,R=E?null:c,j=R?[{label:"Total Required",help:"Total amount required to fund this action.",value:`${Ts(R.grossAmount,R.decimals)} ${g}`,tone:"default"},{label:"Spicenet Fee",help:"Fees paid to Spicenet for intent processing and execution.",value:jo(R.spicenetFee,R.decimals,g),tone:"fee"},{label:"Network Fee",help:"Network fee shown in the same token you are using for this action.",value:jo(R.gasFee,R.decimals,g),tone:"fee"},...R.bridgeFee&&R.bridgeFee>0n?[{label:"Bridge Fee",help:"Estimated cost to rebalance liquidity for this action.",value:jo(R.bridgeFee,R.decimals,g),tone:"fee"}]:[],{label:"Used in TX",help:"Resulting amount of funds used in the transaction.",value:`${Ts(R.netAmount,R.decimals)} ${g}`,tone:"default"}]:[],A=R?`${Ts(R.grossAmount,R.decimals)} ${g}`:null;return E?a.jsx("div",{style:{backgroundColor:s,border:`1px solid ${o}`,borderRadius:r?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",boxShadow:r?"inset 0 1px 0 rgba(255,255,255,0.03)":"none"},children:a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:[a.jsx("span",{style:{fontSize:"17px",fontWeight:500,color:S,fontFamily:e,lineHeight:"24px"},children:"Fee"}),a.jsx("div",{style:{color:b,fontSize:"12px",lineHeight:"1.55",fontFamily:e},children:m})]})}):a.jsxs("div",{style:{backgroundColor:s,border:`1px solid ${o}`,borderRadius:r?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",boxShadow:r?"inset 0 1px 0 rgba(255,255,255,0.03)":"none"},children:[a.jsxs("button",{type:"button",onClick:()=>k(M=>!M),style:{display:"flex",justifyContent:"space-between",alignItems:"center",width:"100%",gap:"12px",marginBottom:F?"14px":0,background:"none",border:"none",padding:0,cursor:"pointer",textAlign:"left"},children:[a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px"},children:[a.jsx("span",{style:{fontSize:"17px",fontWeight:500,color:S,fontFamily:e,lineHeight:"24px"},children:"Fee"}),F&&a.jsx("span",{style:{fontSize:"12px",color:n,fontFamily:e,lineHeight:"1.45"},children:"What is funded, spent, and taken as fees"})]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",flexShrink:0},children:[A&&a.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:"2px",minWidth:0},children:[a.jsx("span",{style:{fontSize:"10px",fontWeight:700,color:n,fontFamily:e,letterSpacing:"0.08em",textTransform:"uppercase"},children:"Total required"}),a.jsx("span",{style:{fontSize:"14px",fontWeight:700,color:I,fontFamily:e,whiteSpace:"nowrap"},children:A})]}),p&&!h&&a.jsx("span",{style:{fontSize:"11px",fontWeight:600,color:l,fontFamily:e,padding:"6px 9px",borderRadius:"999px",backgroundColor:r?"rgba(255,255,255,0.04)":"rgba(0,0,0,0.035)",border:`1px solid ${r?y:"rgba(0,0,0,0.06)"}`,whiteSpace:"nowrap"},children:"Recalculating"}),a.jsx(Mn,{color:n,direction:F?"up":"down",style:{flexShrink:0}})]})]}),a.jsx("div",{style:{overflow:"hidden",maxHeight:F?"480px":"0px",opacity:F?1:0,transition:"max-height 0.24s ease, opacity 0.18s ease"},children:h?a.jsx("p",{style:{margin:0,color:n,fontSize:"12px",lineHeight:"1.55",fontFamily:e},children:"This path executes directly from the external wallet. Network gas is shown and paid in your wallet. No Spicenet fee is charged."}):j.length>0?a.jsxs(a.Fragment,{children:[a.jsx("div",{style:{display:"grid",gap:"10px"},children:j.map((M,P)=>a.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) auto",alignItems:"center",gap:"12px",paddingTop:P===0?0:"10px",borderTop:P===0?"none":`1px solid ${y}`,opacity:p?.74:1,transition:"opacity 120ms ease"},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0},children:[a.jsx("span",{style:{fontSize:"12px",color:n,fontFamily:e,fontWeight:500},children:M.label}),a.jsx(ba,{content:M.help,label:`${M.label} info`,textColor:"#f9fafb",backgroundColor:w,borderColor:C,accentColor:r?"#8f96a3":"#6b7280"})]}),a.jsx("span",{style:{fontSize:"12px",color:M.tone==="fee"?b:I,fontFamily:f.font.mono,textAlign:"right",fontWeight:M.label==="Used in TX"?600:500,letterSpacing:"-0.01em"},children:M.value})]},M.label))}),a.jsx("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:`1px solid ${y}`,fontSize:"11px",color:n,fontFamily:e,lineHeight:"1.45"},children:R?.gasQuoteSource==="estimated"?"Gas quote uses a live estimate.":R?.gasQuoteSource==="configured_fallback"?"Gas quote uses a configured fallback.":"Gas quote is currently zero."})]}):a.jsx("div",{style:{fontSize:"12px",color:m?b:n,fontFamily:e,opacity:m?1:.8,lineHeight:"1.5"},children:m||"Waiting for fee estimate..."})})]})},Bo=u.memo(Kc),ss=({size:e=20,strokeWidth:t=2,color:n="currentColor",style:s})=>a.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:s,children:[a.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]});var va="data:image/svg+xml,%3csvg width='108' height='22' viewBox='0 0 108 22' fill='none' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M1.9916 11.9854V11.2041H3.98379C4.48835 11.2041 4.87897 11.0739 5.15566 10.8135C5.43236 10.5498 5.5707 10.1868 5.5707 9.72461V9.71484C5.5707 9.24935 5.43236 8.88639 5.15566 8.62598C4.87897 8.36556 4.48835 8.23535 3.98379 8.23535H1.9916V7.4541H4.2084C4.65111 7.4541 5.04173 7.5485 5.38027 7.7373C5.71882 7.92611 5.98411 8.18978 6.17617 8.52832C6.37148 8.86686 6.46914 9.25911 6.46914 9.70508V9.71484C6.46914 10.1608 6.37148 10.5547 6.17617 10.8965C5.98411 11.2383 5.71882 11.5052 5.38027 11.6973C5.04173 11.8893 4.65111 11.9854 4.2084 11.9854H1.9916ZM1.55215 14.5V7.4541H2.43106V14.5H1.55215ZM9.51875 14.5928C9.0207 14.5928 8.58939 14.4837 8.2248 14.2656C7.86348 14.0443 7.58353 13.7301 7.38496 13.3232C7.18965 12.9163 7.09199 12.4329 7.09199 11.873V11.8633C7.09199 11.3001 7.18965 10.8151 7.38496 10.4082C7.58353 10.0013 7.86348 9.6888 8.2248 9.4707C8.58939 9.2526 9.0207 9.14355 9.51875 9.14355C10.0201 9.14355 10.4514 9.2526 10.8127 9.4707C11.174 9.6888 11.4523 10.0013 11.6477 10.4082C11.8462 10.8151 11.9455 11.3001 11.9455 11.8633V11.873C11.9455 12.4329 11.8462 12.9163 11.6477 13.3232C11.4523 13.7301 11.174 14.0443 10.8127 14.2656C10.4514 14.4837 10.0201 14.5928 9.51875 14.5928ZM9.51875 13.8408C9.85078 13.8408 10.1324 13.7627 10.3635 13.6064C10.5946 13.4502 10.7704 13.2256 10.8908 12.9326C11.0145 12.6396 11.0764 12.2865 11.0764 11.873V11.8633C11.0764 11.4466 11.0145 11.0918 10.8908 10.7988C10.7704 10.5059 10.5946 10.2829 10.3635 10.1299C10.1324 9.97363 9.85078 9.89551 9.51875 9.89551C9.18672 9.89551 8.90514 9.97363 8.67402 10.1299C8.4429 10.2829 8.26549 10.5059 8.1418 10.7988C8.02135 11.0918 7.96113 11.4466 7.96113 11.8633V11.873C7.96113 12.2865 8.02135 12.6396 8.1418 12.9326C8.26549 13.2256 8.4429 13.4502 8.67402 13.6064C8.90514 13.7627 9.18672 13.8408 9.51875 13.8408ZM13.7842 14.5L12.3096 9.23633H13.1592L14.1943 13.4453H14.2725L15.4492 9.23633H16.2549L17.4316 13.4453H17.5098L18.5449 9.23633H19.3896L17.915 14.5H17.0605L15.8838 10.4277H15.8057L14.6338 14.5H13.7842ZM22.1658 14.5928C21.6645 14.5928 21.2332 14.4821 20.8719 14.2607C20.5138 14.0394 20.2371 13.7269 20.0418 13.3232C19.8497 12.9163 19.7537 12.4378 19.7537 11.8877V11.8828C19.7537 11.3392 19.8497 10.8623 20.0418 10.4521C20.2371 10.042 20.5122 9.72135 20.867 9.49023C21.2218 9.25911 21.6368 9.14355 22.1121 9.14355C22.5906 9.14355 23.0008 9.25423 23.3426 9.47559C23.6876 9.69694 23.9513 10.0062 24.1336 10.4033C24.3191 10.7972 24.4119 11.2562 24.4119 11.7803V12.1123H20.1932V11.4336H23.9773L23.5574 12.0537V11.7168C23.5574 11.3034 23.4956 10.9632 23.3719 10.6963C23.2482 10.4294 23.0773 10.2308 22.8592 10.1006C22.6411 9.96712 22.3904 9.90039 22.1072 9.90039C21.824 9.90039 21.5701 9.97038 21.3455 10.1104C21.1242 10.2471 20.9484 10.4505 20.8182 10.7207C20.688 10.9909 20.6229 11.3229 20.6229 11.7168V12.0537C20.6229 12.4281 20.6863 12.7487 20.8133 13.0156C20.9402 13.2793 21.1209 13.4827 21.3553 13.626C21.5896 13.766 21.8663 13.8359 22.1854 13.8359C22.423 13.8359 22.6297 13.8034 22.8055 13.7383C22.9813 13.6732 23.1261 13.5902 23.24 13.4893C23.354 13.3883 23.4337 13.2858 23.4793 13.1816L23.4988 13.1377H24.3484L24.3387 13.1768C24.2931 13.3558 24.2117 13.5299 24.0945 13.6992C23.9806 13.8652 23.8325 14.0166 23.6502 14.1533C23.4679 14.2868 23.2514 14.3942 23.0008 14.4756C22.7534 14.5537 22.4751 14.5928 22.1658 14.5928ZM25.4303 14.5V9.23633H26.2799V10.0176H26.358C26.4589 9.74089 26.6298 9.52604 26.8707 9.37305C27.1116 9.22005 27.4094 9.14355 27.7643 9.14355C27.8456 9.14355 27.9254 9.14844 28.0035 9.1582C28.0849 9.16471 28.1467 9.17122 28.1891 9.17773V10.0029C28.1012 9.98665 28.0149 9.97526 27.9303 9.96875C27.8489 9.95898 27.761 9.9541 27.6666 9.9541C27.3964 9.9541 27.1572 10.0078 26.9488 10.1152C26.7405 10.2227 26.5761 10.3724 26.4557 10.5645C26.3385 10.7565 26.2799 10.9811 26.2799 11.2383V14.5H25.4303ZM30.9408 14.5928C30.4395 14.5928 30.0082 14.4821 29.6469 14.2607C29.2888 14.0394 29.0121 13.7269 28.8168 13.3232C28.6247 12.9163 28.5287 12.4378 28.5287 11.8877V11.8828C28.5287 11.3392 28.6247 10.8623 28.8168 10.4521C29.0121 10.042 29.2872 9.72135 29.642 9.49023C29.9968 9.25911 30.4118 9.14355 30.8871 9.14355C31.3656 9.14355 31.7758 9.25423 32.1176 9.47559C32.4626 9.69694 32.7263 10.0062 32.9086 10.4033C33.0941 10.7972 33.1869 11.2562 33.1869 11.7803V12.1123H28.9682V11.4336H32.7523L32.3324 12.0537V11.7168C32.3324 11.3034 32.2706 10.9632 32.1469 10.6963C32.0232 10.4294 31.8523 10.2308 31.6342 10.1006C31.4161 9.96712 31.1654 9.90039 30.8822 9.90039C30.599 9.90039 30.3451 9.97038 30.1205 10.1104C29.8992 10.2471 29.7234 10.4505 29.5932 10.7207C29.463 10.9909 29.3979 11.3229 29.3979 11.7168V12.0537C29.3979 12.4281 29.4613 12.7487 29.5883 13.0156C29.7152 13.2793 29.8959 13.4827 30.1303 13.626C30.3646 13.766 30.6413 13.8359 30.9604 13.8359C31.198 13.8359 31.4047 13.8034 31.5805 13.7383C31.7563 13.6732 31.9011 13.5902 32.015 13.4893C32.129 13.3883 32.2087 13.2858 32.2543 13.1816L32.2738 13.1377H33.1234L33.1137 13.1768C33.0681 13.3558 32.9867 13.5299 32.8695 13.6992C32.7556 13.8652 32.6075 14.0166 32.4252 14.1533C32.2429 14.2868 32.0264 14.3942 31.7758 14.4756C31.5284 14.5537 31.2501 14.5928 30.9408 14.5928ZM36.1486 14.5928C35.7059 14.5928 35.3186 14.4805 34.9865 14.2559C34.6545 14.0312 34.3973 13.7155 34.215 13.3086C34.0328 12.8984 33.9416 12.4199 33.9416 11.873V11.8633C33.9416 11.3132 34.0328 10.8346 34.215 10.4277C34.3973 10.0208 34.6529 9.70508 34.9816 9.48047C35.3137 9.25586 35.7027 9.14355 36.1486 9.14355C36.3895 9.14355 36.6158 9.18262 36.8273 9.26074C37.0422 9.33561 37.2326 9.44141 37.3986 9.57812C37.5647 9.71484 37.6949 9.8776 37.7893 10.0664H37.8674V7.14648H38.717V14.5H37.8674V13.6602H37.7893C37.6818 13.8555 37.5467 14.0231 37.384 14.1631C37.2212 14.2998 37.0357 14.4056 36.8273 14.4805C36.619 14.5553 36.3928 14.5928 36.1486 14.5928ZM36.3439 13.8408C36.663 13.8408 36.938 13.7611 37.1691 13.6016C37.4003 13.4421 37.5777 13.2158 37.7014 12.9229C37.8251 12.6266 37.8869 12.2767 37.8869 11.873V11.8633C37.8869 11.4564 37.8251 11.1064 37.7014 10.8135C37.5777 10.5205 37.4003 10.2943 37.1691 10.1348C36.938 9.97526 36.663 9.89551 36.3439 9.89551C36.0249 9.89551 35.7499 9.97526 35.5188 10.1348C35.2909 10.291 35.1151 10.5156 34.9914 10.8086C34.871 11.1016 34.8107 11.4531 34.8107 11.8633V11.873C34.8107 12.2799 34.871 12.6315 34.9914 12.9277C35.1151 13.2207 35.2909 13.4469 35.5188 13.6064C35.7499 13.7627 36.0249 13.8408 36.3439 13.8408ZM45.1775 14.5928C44.9334 14.5928 44.7072 14.5553 44.4988 14.4805C44.2905 14.4056 44.1049 14.2998 43.9422 14.1631C43.7794 14.0231 43.6443 13.8555 43.5369 13.6602H43.4588V14.5H42.6092V7.14648H43.4588V10.0664H43.5369C43.6346 9.8776 43.7648 9.71484 43.9275 9.57812C44.0936 9.44141 44.2824 9.33561 44.4939 9.26074C44.7088 9.18262 44.9367 9.14355 45.1775 9.14355C45.6235 9.14355 46.0109 9.25586 46.3396 9.48047C46.6717 9.70508 46.9288 10.0208 47.1111 10.4277C47.2934 10.8346 47.3846 11.3132 47.3846 11.8633V11.873C47.3846 12.4199 47.2934 12.8984 47.1111 13.3086C46.9288 13.7155 46.6717 14.0312 46.3396 14.2559C46.0109 14.4805 45.6235 14.5928 45.1775 14.5928ZM44.9822 13.8408C45.3045 13.8408 45.5796 13.7627 45.8074 13.6064C46.0353 13.4469 46.2094 13.2207 46.3299 12.9277C46.4536 12.6315 46.5154 12.2799 46.5154 11.873V11.8633C46.5154 11.4531 46.4536 11.1016 46.3299 10.8086C46.2094 10.5156 46.0353 10.291 45.8074 10.1348C45.5796 9.97526 45.3045 9.89551 44.9822 9.89551C44.6632 9.89551 44.3881 9.97526 44.157 10.1348C43.9259 10.2943 43.7485 10.5205 43.6248 10.8135C43.5011 11.1064 43.4393 11.4564 43.4393 11.8633V11.873C43.4393 12.2767 43.5011 12.6266 43.6248 12.9229C43.7485 13.2158 43.9259 13.4421 44.157 13.6016C44.3881 13.7611 44.6632 13.8408 44.9822 13.8408ZM48.6568 16.3457C48.6015 16.3457 48.5396 16.3424 48.4713 16.3359C48.4029 16.3327 48.3395 16.3262 48.2809 16.3164V15.6182C48.3329 15.6279 48.3899 15.6344 48.4518 15.6377C48.5136 15.641 48.5738 15.6426 48.6324 15.6426C48.8733 15.6426 49.0702 15.5807 49.2232 15.457C49.3795 15.3333 49.5048 15.1201 49.5992 14.8174L49.6969 14.5049L47.7486 9.23633H48.6568L50.2779 14.0996L49.941 13.5674H50.3414L50.0045 14.0996L51.6207 9.23633H52.5143L50.4586 14.8223C50.3154 15.2161 50.164 15.5238 50.0045 15.7451C49.845 15.9665 49.6578 16.1211 49.443 16.209C49.2314 16.3001 48.9693 16.3457 48.6568 16.3457Z' fill='%230E0D0B'/%3e%3cpath d='M62.7081 13.27C62.742 13.27 62.7642 13.3057 62.7491 13.3362V13.336L61.1229 16.6083C61.0892 16.6761 60.9926 16.6759 60.959 16.6083L59.3382 13.336C59.3232 13.3057 59.3453 13.27 59.3792 13.27H62.7081Z' fill='%23EA4B4B'/%3e%3cpath d='M61.0026 9.71913C61.0194 9.68524 61.0678 9.68524 61.0845 9.71913L62.747 13.0897C62.762 13.12 62.7399 13.1557 62.706 13.1557H59.3763C59.3424 13.1557 59.3203 13.12 59.3353 13.0897L61.0026 9.71913Z' fill='%23EA4B4B'/%3e%3cpath d='M60.8426 9.63827C60.8766 9.63827 60.8987 9.6741 60.8835 9.70444L59.2164 13.0594C59.1995 13.0932 59.1513 13.0932 59.1345 13.0594L57.5001 9.77047C57.47 9.70962 57.5142 9.63827 57.5821 9.63827H60.8426Z' fill='%23EA4B4B'/%3e%3cpath d='M64.5036 9.63617C64.5715 9.63618 64.6157 9.70753 64.5855 9.76838H64.5854L62.9512 13.0573C62.9344 13.0911 62.8862 13.0912 62.8692 13.0573L61.2021 9.70235C61.187 9.672 61.2091 9.63617 61.2431 9.63617H64.5036Z' fill='%23EA4B4B'/%3e%3cpath d='M62.8284 6.18281C62.862 6.11518 62.9586 6.11518 62.9922 6.18281L64.5855 9.38969C64.6157 9.45054 64.5715 9.52189 64.5036 9.52189H61.2431C61.2091 9.52189 61.187 9.48605 61.2021 9.45571L62.8283 6.18265L62.8284 6.18281Z' fill='%23EA4B4B'/%3e%3cpath d='M62.3131 6.13196C62.381 6.13196 62.4252 6.20331 62.3951 6.26416C62.154 6.74935 61.9128 7.23455 61.6718 7.71975H61.6716C61.4225 8.22125 61.1733 8.72259 60.9242 9.22409C60.9074 9.25799 60.859 9.25799 60.8422 9.22409L60.6305 8.79587C60.6275 8.78957 60.6259 8.78263 60.6259 8.77553V6.22349C60.6259 6.17297 60.6668 6.13196 60.7173 6.13196H62.3131Z' fill='%23EA4B4B'/%3e%3cpath fill-rule='evenodd' clip-rule='evenodd' d='M74.8537 10.0096C75.2721 10.0096 75.654 10.1125 75.9993 10.3184C76.3513 10.5177 76.6303 10.8032 76.8361 11.1751C77.0487 11.547 77.1549 11.9953 77.1549 12.52V12.6495C77.1549 13.1675 77.052 13.6158 76.8461 13.9943C76.6402 14.3729 76.3613 14.6618 76.0093 14.861C75.664 15.0603 75.2788 15.1599 74.8537 15.1599C74.515 15.1599 74.2261 15.1134 73.9871 15.0204C73.7546 14.9341 73.5653 14.8212 73.4192 14.6817C73.2731 14.5423 73.1602 14.3995 73.0805 14.2534H72.941V16.9659L72.1541 16.0013V10.1491H72.9211V10.956H73.0352C73.2729 10.6733 73.3893 10.4911 73.6683 10.2985C73.9538 10.1059 74.349 10.0096 74.8537 10.0096ZM74.6445 10.7069C74.1464 10.7069 73.7347 10.8696 73.4092 11.195C73.0905 11.5138 72.9311 11.9621 72.9311 12.5399V12.6296C72.9311 13.2074 73.0905 13.659 73.4092 13.9844C73.7347 14.3032 74.1464 14.4626 74.6445 14.4626C75.1492 14.4626 75.5577 14.3032 75.8698 13.9844C76.1886 13.659 76.348 13.2074 76.348 12.6296V12.5399C76.348 11.9621 76.1886 11.5138 75.8698 11.195C75.5577 10.8696 75.1492 10.7069 74.6445 10.7069Z' fill='%230E0D0B'/%3e%3cpath d='M78.5848 11.9583L78.5555 15.4596L77.7681 14.4846V10.9583L78.5848 11.9583Z' fill='%230E0D0B'/%3e%3cpath d='M101.588 10.2986H102.444L103 10.986H101.588V10.9867H100.802L101.588 11.9623V14.1937C101.588 14.3929 101.685 14.4926 101.877 14.4926H102.379L102.928 15.17H101.668C101.389 15.17 101.173 15.0936 101.021 14.9409C100.874 14.7881 100.801 14.5789 100.801 14.3133V10.986H99.8799L99.3217 10.2986H100.801V9.13501H101.588V10.2986Z' fill='%230E0D0B'/%3e%3cpath d='M69.0133 7.90764C69.4848 7.90764 69.9065 7.99068 70.2784 8.15671C70.6569 8.3161 70.9525 8.55517 71.165 8.87395C71.3842 9.18609 71.4938 9.58126 71.4938 10.0594V10.4778H70.667V10.0594C70.667 9.72072 70.5939 9.44842 70.4477 9.24254C70.3083 9.03666 70.1124 8.88392 69.86 8.7843C69.6143 8.68469 69.332 8.63487 69.0133 8.63487C68.555 8.63487 68.1864 8.7378 67.9075 8.94367C67.6286 9.14291 67.4891 9.4285 67.4891 9.80041C67.4891 10.0461 67.5488 10.2453 67.6684 10.3981C67.7879 10.5508 67.9573 10.677 68.1764 10.7767C68.3956 10.8696 68.658 10.9527 68.9635 11.0257L69.4815 11.1552C69.8866 11.2416 70.2485 11.3611 70.5673 11.5138C70.8927 11.6599 71.1517 11.8625 71.3443 12.1215C71.5369 12.3739 71.6332 12.706 71.6332 13.1177C71.6332 13.5295 71.5303 13.8881 71.3244 14.1936C71.1185 14.4991 70.8263 14.7382 70.4477 14.9109C70.0758 15.0769 69.6375 15.1599 69.1328 15.1599C68.6281 15.1599 68.1765 15.0702 67.778 14.8909C67.3795 14.7116 67.0641 14.4426 66.8316 14.084C66.6058 13.7187 66.4929 13.2638 66.4929 12.7192V12.51H67.3197V12.7192C67.3197 13.297 67.4891 13.7287 67.8278 14.0143C68.1665 14.2932 68.6015 14.4327 69.1328 14.4327C69.6774 14.4327 70.0924 14.3098 70.378 14.0641C70.6636 13.8183 70.8064 13.5095 70.8064 13.1376C70.8064 12.8786 70.74 12.6727 70.6072 12.52C70.481 12.3673 70.3017 12.2444 70.0692 12.1514C69.8368 12.0518 69.5645 11.9655 69.2523 11.8924L68.7343 11.7629C68.3292 11.6566 67.9706 11.5271 67.6584 11.3744C67.3463 11.2216 67.1006 11.0224 66.9213 10.7767C66.7486 10.5243 66.6623 10.2022 66.6623 9.81035C66.6623 9.41852 66.7585 9.07981 66.9511 8.79424C67.1504 8.50866 67.426 8.28953 67.778 8.13678C68.1366 7.98404 68.5484 7.90764 69.0133 7.90764Z' fill='%230E0D0B'/%3e%3cpath d='M81.6544 10.0096C82.1193 10.0096 82.5145 10.0959 82.8399 10.2686C83.1719 10.4412 83.431 10.6704 83.6169 10.956C83.8095 11.2415 83.9324 11.5471 83.9855 11.8725L83.2185 12.0318C83.1853 11.7928 83.1056 11.5736 82.9794 11.3744C82.8598 11.1752 82.6905 11.0158 82.4713 10.8962C82.2521 10.7767 81.9832 10.7169 81.6644 10.7169C81.339 10.7169 81.0468 10.7899 80.7877 10.936C80.5354 11.0821 80.3328 11.2914 80.1801 11.5637C80.034 11.836 79.9609 12.1614 79.9609 12.5399V12.6296C79.9609 13.0081 80.034 13.3335 80.1801 13.6058C80.3328 13.8781 80.5354 14.0873 80.7877 14.2334C81.0468 14.3795 81.339 14.4526 81.6644 14.4526C82.1492 14.4526 82.5178 14.3264 82.7702 14.0741C83.0292 13.8217 83.1886 13.5095 83.2483 13.1376L84.0254 13.307C83.9523 13.6257 83.8195 13.9279 83.6269 14.2135C83.4343 14.4991 83.172 14.7282 82.8399 14.9009C82.5145 15.0735 82.1193 15.1599 81.6544 15.1599C81.1829 15.1599 80.7579 15.0603 80.3793 14.861C80.0074 14.6551 79.7119 14.363 79.4927 13.9844C79.2802 13.6059 79.1739 13.1575 79.1739 12.6395V12.5299C79.1739 12.0053 79.2802 11.557 79.4927 11.1851C79.7119 10.8066 80.0074 10.5177 80.3793 10.3184C80.7579 10.1126 81.1829 10.0096 81.6544 10.0096Z' fill='%230E0D0B'/%3e%3cpath fill-rule='evenodd' clip-rule='evenodd' d='M86.7515 10.0096C87.2097 10.0096 87.6149 10.1092 87.9668 10.3084C88.3188 10.501 88.5944 10.78 88.7937 11.1452C88.9929 11.5105 89.0925 11.9389 89.0925 12.4304V12.7889H85.1177C85.1377 13.3136 85.3071 13.7254 85.6258 14.0243C85.9446 14.3165 86.3431 14.4626 86.8212 14.4626C87.2396 14.4626 87.5617 14.3663 87.7875 14.1737C88.0133 13.9811 88.186 13.752 88.3056 13.4863L88.983 13.815C88.8833 14.0209 88.7439 14.2268 88.5646 14.4327C88.3919 14.6386 88.1628 14.8113 87.8772 14.9507C87.5983 15.0902 87.2396 15.1599 86.8013 15.1599C86.3099 15.1599 85.8782 15.057 85.5063 14.8511C85.1344 14.6386 84.8455 14.343 84.6396 13.9645C84.4337 13.5859 84.3307 13.1476 84.3307 12.6495V12.5299C84.3307 12.0252 84.4337 11.5836 84.6396 11.205C84.8455 10.8265 85.1311 10.5342 85.4963 10.3284C85.8616 10.1159 86.28 10.0096 86.7515 10.0096ZM86.7515 10.7069C86.3066 10.7069 85.9413 10.8331 85.6557 11.0855C85.3701 11.3378 85.1941 11.6898 85.1277 12.1414H88.2956C88.269 11.6898 88.113 11.3378 87.8274 11.0855C87.5485 10.8331 87.1898 10.7069 86.7515 10.7069Z' fill='%230E0D0B'/%3e%3cpath fill-rule='evenodd' clip-rule='evenodd' d='M97.1624 10.0096C97.6207 10.0096 98.0258 10.1092 98.3778 10.3084C98.7298 10.501 99.0054 10.78 99.2046 11.1452C99.4039 11.5105 99.5035 11.9389 99.5035 12.4304V12.7889H95.5287C95.5487 13.3136 95.718 13.7254 96.0368 14.0243C96.3555 14.3165 96.754 14.4626 97.2322 14.4626C97.6505 14.4626 97.9727 14.3663 98.1985 14.1737C98.4243 13.9811 98.5969 13.752 98.7165 13.4863L99.3939 13.815C99.2943 14.0209 99.1548 14.2268 98.9755 14.4327C98.8028 14.6386 98.5737 14.8113 98.2881 14.9507C98.0092 15.0902 97.6506 15.1599 97.2123 15.1599C96.7208 15.1599 96.2892 15.057 95.9172 14.8511C95.5453 14.6386 95.2564 14.343 95.0505 13.9645C94.8446 13.5859 94.7417 13.1476 94.7417 12.6495V12.5299C94.7417 12.0252 94.8446 11.5836 95.0505 11.205C95.2564 10.8265 95.542 10.5342 95.9073 10.3284C96.2725 10.1158 96.6909 10.0096 97.1624 10.0096ZM97.1624 10.7069C96.7175 10.7069 96.3522 10.8331 96.0666 11.0855C95.7811 11.3378 95.6051 11.6898 95.5387 12.1414H98.7066C98.68 11.6898 98.5239 11.3378 98.2383 11.0855C97.9594 10.8331 97.6008 10.7069 97.1624 10.7069Z' fill='%230E0D0B'/%3e%3cpath d='M92.2484 10.0594C92.6137 10.0594 92.9391 10.1358 93.2247 10.2885C93.5169 10.4413 93.7494 10.6671 93.9221 10.966C94.0947 11.2648 94.1811 11.6334 94.1811 12.0717V15.1458H93.394V12.1315C93.394 11.6467 93.2712 11.2947 93.0255 11.0755C92.7864 10.8564 92.461 10.7468 92.0492 10.7468C91.5777 10.7468 91.1925 10.8995 90.8936 11.205C90.6014 11.5105 90.4553 11.9655 90.4553 12.5698V15.1458H89.6683V10.1491H90.4354V10.9582H90.5361C90.7355 10.7018 90.8604 10.5342 91.1128 10.3483C91.3718 10.1557 91.7503 10.0594 92.2484 10.0594Z' fill='%230E0D0B'/%3e%3cpath d='M78.5932 10.9581H77.7681V10.1514H78.6L78.5932 10.9581Z' fill='%230E0D0B'/%3e%3c/svg%3e";const ka=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(","),tn=({isOpen:e,onClose:t,title:n,subtitle:s,children:o,overlayContent:r,overlayDimmed:i=!0,styles:l,theme:c,maxWidth:d="522px",dark:p,footerLinkText:m,bannerSrc:h,bannerAlt:x,closeOnBackdropClick:g=!1})=>{const{theme:y,dark:w,dk:C,palette:b}=f.useSpiceBrand(l,p),S=p??w,I=c||y,F=l?.fontFamily||I.typography.fontFamily||f.font.ui,k=l?.primaryColor||I.colors.primary,E=u.useRef(null),R=u.useRef(null),j=u.useRef(null),A=u.useId(),[M,P]=u.useState(!1),[N,B]=u.useState(!1),U=u.useRef(t);if(u.useEffect(()=>{U.current=t},[t]),u.useEffect(()=>{if(!e){B(!1);return}R.current=document.activeElement;const q=document.body.style.overflow;document.body.style.overflow="hidden";const ue=requestAnimationFrame(()=>{const re=requestAnimationFrame(()=>B(!0));j.current=re}),le=()=>{const re=E.current;re&&(re.querySelectorAll(ka)[0]??re).focus({preventScroll:!0})},G=re=>{if(re.key==="Escape"){re.stopPropagation(),U.current();return}if(re.key!=="Tab")return;const Y=E.current;if(!Y)return;const _=Array.from(Y.querySelectorAll(ka)).filter(L=>!L.hasAttribute("aria-hidden"));if(_.length===0){re.preventDefault(),Y.focus();return}const Z=_[0],pe=_[_.length-1],D=document.activeElement;re.shiftKey&&D===Z?(re.preventDefault(),pe.focus()):!re.shiftKey&&D===pe&&(re.preventDefault(),Z.focus())},ne=requestAnimationFrame(le);return document.addEventListener("keydown",G),()=>{cancelAnimationFrame(ne),cancelAnimationFrame(ue),j.current&&cancelAnimationFrame(j.current),document.removeEventListener("keydown",G),document.body.style.overflow=q;const re=R.current;re&&typeof re.focus=="function"&&re.focus({preventScroll:!0})}},[e]),!e)return null;const O=!!h&&!M,z=x??"";return a.jsx("div",{onMouseDown:q=>{g&&q.target===q.currentTarget&&U.current()},style:{position:"fixed",inset:0,backgroundColor:S?"rgba(0,0,0,0.72)":"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",padding:"clamp(16px, 4vw, 48px)",zIndex:f.z.modal,opacity:N?1:0,transition:`opacity ${f.duration.normal} ${f.easing.out}`},children:a.jsx("div",{ref:E,role:"dialog","aria-modal":"true","aria-labelledby":A,tabIndex:-1,style:{backgroundColor:b.shellBorder,borderRadius:"12px",padding:"5px",width:"100%",maxWidth:d,boxSizing:"border-box",boxShadow:"0 16px 48px rgba(0, 0, 0, 0.4)",outline:"none",transform:N?"scale(1)":"scale(0.96)",transition:`transform ${f.duration.slow} ${f.easing.out}`,display:"flex",flexDirection:"column",maxHeight:"100%"},children:a.jsxs("div",{style:{backgroundColor:b.shell,border:`1px solid ${b.shellInnerBorder}`,borderRadius:"9px",width:"100%",padding:"0",display:"flex",flexDirection:"column",position:"relative",flex:"0 1 auto",minHeight:0,overflowY:"auto",overflowX:"hidden"},children:[r&&i&&a.jsx("div",{style:{position:"absolute",inset:0,backgroundColor:"rgba(0, 0, 0, 0.4)",zIndex:5,pointerEvents:"none",borderRadius:"12px"},"aria-hidden":"true"}),O&&a.jsxs("div",{style:{position:"relative",width:"100%"},children:[a.jsx("img",{src:h,style:{width:"100%",height:"auto",display:"block",borderRadius:"6px 6px 0 0"},alt:z,"aria-hidden":z===""?"true":void 0,onError:()=>P(!0)}),a.jsx("button",{type:"button",onClick:t,"aria-label":"Close dialog",style:{position:"absolute",top:"8px",right:"8px",minWidth:"44px",minHeight:"44px",color:b.textPrimary,padding:"8px",backgroundColor:"transparent",borderRadius:"9999px",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1},children:a.jsx(ss,{size:28,strokeWidth:2.5})})]}),a.jsxs("div",{style:{padding:"28px 28px 0 28px",position:"relative"},children:[!O&&a.jsx("button",{type:"button",onClick:t,"aria-label":"Close dialog",style:{position:"absolute",top:"10px",right:"10px",minWidth:"44px",minHeight:"44px",color:b.textSecondary,padding:"10px",backgroundColor:"transparent",borderRadius:"50%",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.2s",fontSize:"18px",fontWeight:"600"},onMouseEnter:q=>{q.currentTarget.style.backgroundColor=S?`${k}1a`:"#f3f4f6"},onMouseLeave:q=>{q.currentTarget.style.backgroundColor="transparent"},children:a.jsx(ss,{size:24,strokeWidth:2.4})}),a.jsx("h2",{id:A,style:{fontSize:"22px",fontWeight:"700",color:b.textPrimary,margin:"0",fontFamily:F,lineHeight:"1.12"},children:n})]}),s&&a.jsx("div",{style:{padding:"11px 28px 13px 28px",fontSize:"12px",color:b.textSecondary,margin:"0",lineHeight:"1.35",fontFamily:F,borderBottom:S?`1px solid ${C.cardBorder}`:"1px solid #cdcfd1"},children:s}),o,a.jsxs("div",{style:{padding:"12px 28px",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[a.jsx("img",{src:va,alt:"","aria-hidden":"true",width:108,height:22,decoding:"async",style:{width:"108px",height:"22px",opacity:S?.85:1,filter:S?"brightness(0) invert(1)":"none",margin:0,display:"block"}}),a.jsx("a",{href:"https://spiceflow-docs.spicenet.io",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"10px",color:b.textSecondary,textDecoration:"none",display:"flex",alignItems:"center",gap:"4px",fontFamily:F,lineHeight:"1"},children:a.jsx("span",{style:{color:k,textDecoration:"underline",fontWeight:"500"},children:m??"Learn more \u2192"})})]}),r]})})})},Sa=({dk:e,dark:t,message:n,buttonLabel:s,onAction:o,disabled:r=!1})=>a.jsxs("div",{style:{padding:"12px",backgroundColor:e.warningBg,borderRadius:"8px",border:`1px solid ${e.warningBorder}`},children:[a.jsx("p",{style:{margin:"0 0 10px 0",color:e.warningText,fontSize:"14px"},children:n}),a.jsx("button",{onClick:o,disabled:r,style:{width:"100%",padding:"8px 12px",borderRadius:"6px",border:`1px solid ${t?e.warningBorder:"#fbbf24"}`,backgroundColor:t?e.cardBg:"white",cursor:r?"not-allowed":"pointer",fontWeight:600,fontSize:"13px",color:e.warningText,opacity:r?.6:1},children:s})]}),Ia=({dk:e,dark:t,borderRadius:n,children:s})=>a.jsx("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:t?e.warningBg:"#fffbeb",border:`1px solid ${e.warningBorder}`,borderRadius:n,fontSize:"12px",color:e.warningText,lineHeight:"1.4"},children:s});async function Zc(e,t,n){let s=null;try{const o=await e.request({method:"eth_chainId"});s=parseInt(o,16)}catch{s=null}s!==t&&(n?.(),await f.ensureWalletOnChain(e,t))}function Aa(e){let t=e;const n=new Set;for(;t&&typeof t=="object"&&!n.has(t);){if(n.add(t),t.code===4001)return!0;t=t.cause}return!1}async function Ro(e){const t=e.provider??await e.wallet?.getEthereumProvider();if(!t)throw new Error("External wallet provider not available");await Zc(t,e.chainId,e.onSwitch);const n=await t.request({method:"eth_accounts"});if(!Array.isArray(n)||!n.some(o=>typeof o=="string"&&o.toLowerCase()===e.account.toLowerCase()))throw new Error("The connected source wallet changed. Reconnect the selected account before funding.");const s=f.getChainConfig(e.chainId)?.viemChain;return{extWc:T.createWalletClient({account:e.account,chain:s,transport:T.custom(t)}),viemChain:s}}async function Ea(e,t,n){const s=Date.now()+1e4;for(;Date.now()<s;){let o;try{o=await Promise.all([t.getBlockNumber({cacheTime:0}),e.request({method:"eth_blockNumber"}).then(BigInt)])}catch{return}if(o.every(r=>r>=n))return;await new Promise(r=>setTimeout(r,250))}}async function Xc(e){let t;for(const[n,s]of e.calls.entries()){await e.observer?.onSending?.(n);let o;try{o=await e.extWc.sendTransaction({to:s.to,data:s.data,value:s.value,chain:e.viemChain})}catch(l){throw Aa(l)&&e.observer?.onRejected?.(n),l}e.observer?.onSubmitted?.(n,o);const r=await Is({client:e.client,hash:o,call:s,onRepriced:l=>e.observer?.onSubmitted?.(n,l),onCancelled:()=>e.observer?.onReverted?.(n,o)});o=r.hash;const i=r.receipt;if(i.status!=="success")throw e.observer?.onReverted?.(n,o),new Error(e.errorMessage);await Ea(e.extWc,e.client,i.blockNumber),e.observer?.onConfirmed?.(n,o),t=o}return t}async function Fa(e){const t=await e.client.estimateFeesPerGas(),n=t.maxFeePerGas??t.gasPrice;if(typeof n!="bigint"||n<=0n)throw new Error("Network gas could not be priced.");let s=0n;for(const o of e.calls){const r=await e.client.estimateGas({account:e.account,...o});s+=(r*n*120n+99n)/100n}return s}function js(e,t,n,s){return n?{to:e,value:s,data:"0x"}:{to:t,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"transfer",args:[e,s]})}}async function Ta(e){const t=js(e.recipient,e.token,e.isNative,e.amount),[n,s]=await Promise.all([e.client.estimateGas({account:e.account,...t}),e.client.estimateFeesPerGas()]),o=s.maxFeePerGas??s.gasPrice;if(typeof o!="bigint"||o<=0n)throw new Error("Source transaction gas could not be priced.");return(n*o*120n+99n)/100n}function Do(e,t){return t.isNative?e.sendTransaction({to:t.recipient,value:t.amount,chain:t.viemChain}):e.sendTransaction({to:t.tokenAddr,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"transfer",args:[t.recipient,t.amount]}),chain:t.viemChain})}async function Jc(e){const{extWc:t,sourceClient:n,recipient:s,tokenAddr:o,isNative:r,amount:i}=e;if(i<=0n)return;await e.observer?.onSending?.(0);let l;try{l=await Do(t,{recipient:s,tokenAddr:o,isNative:r,amount:i,viemChain:e.viemChain})}catch(p){throw Aa(p)&&e.observer?.onRejected?.(0),p}e.observer?.onSubmitted?.(0,l);const c=await Is({client:n,hash:l,call:js(s,o,r,i),onRepriced:p=>e.observer?.onSubmitted?.(0,p),onCancelled:()=>e.observer?.onReverted?.(0,l)});l=c.hash;const d=c.receipt;if(d.status!=="success")throw e.observer?.onReverted?.(0,l),new Error("Embedded wallet funding failed");await Ea(t,n,d.blockNumber),e.observer?.onConfirmed?.(0,l)}function $c({sourceChainId:e,selectedAsset:t,destinationChainId:n,destinationTokenAddress:s,isCrossDenomination:o,convertedUsdAmount:r}){const i=v.normalizeNativeTokenAddress(t.asset.address),l=s;let c,d;if(l&&n)if(c=f.CHAIN_CONFIGS[n]?.supportedTokens?.find(p=>f.addressesEqual(p.address,l))?.decimals??t.asset.decimals,o){if(!r)throw new Error("Destination amount is still being calculated. Please retry in a moment.");d=r}else{const p=T.parseUnits(t.amount,t.asset.decimals);d=v.convertAmountBetweenDecimals(p,t.asset.decimals,c)}return{sourceChainId:e,depositTokenAddress:i,depositAmount:t.amount,depositTokenDecimals:t.asset.decimals,destinationChainId:n,destinationTokenAddress:l,destinationAmount:d,destinationTokenDecimals:c}}async function _c(e,t){if(!e)return[];if(Array.isArray(e))return e;const n=e;return e.length>=2?n(t.depositAmount,t.depositTokenAddress):n(t)}function ja(e,t){return!!e&&e.quotedAmount===t.amount&&e.chainId===t.chainId&&f.addressesEqual(e.token,t.token)}async function Bs(e,t){const n=await Do(e,{recipient:t.recipient,tokenAddr:t.tokenAddr,isNative:t.isNative,amount:t.amount});t.afterSend?.(n);const s=f.getClientForChain(t.chainId),{receipt:o,hash:r}=await Is({client:s,hash:n,call:js(t.recipient,t.tokenAddr,t.isNative,t.amount),confirmations:2});if(o.status!=="success")throw new Error(t.failureMessage);return t.settle&&await s.getBlockNumber()-o.blockNumber<2n&&await en(3e3),r}async function ed(e){const t=e.selectedDepositAssets.filter(o=>o.asset&&o.amount&&parseFloat(o.amount)>0);if(t.length===0){console.error("[DepositModal] No valid assets for deposit"),e.setError("Please select an asset and enter an amount");return}const n=t[0];if(!e.escrowOnly&&!e.sourceAddress){e.setError("External wallet not connected. Please connect your wallet in the previous step.");return}if(!e.isNon7702){if(!e.address||!e.embeddedWalletAddress){e.setError("Couldn't find your account wallet. Try reconnecting.");return}if(!e.isReady||!e.isAuthenticated){e.setError("Sign in to continue.");return}}if(e.zeroCreditError){e.setError(e.zeroCreditError);return}if(e.depositBalanceError){e.setError(e.depositBalanceError);return}if(e.isNon7702&&e.sponsorGas&&e.nativeChainId&&n.asset.chainId!==e.nativeChainId&&e.destinationTokenAddress){e.setError("Gas sponsorship is not supported for this deposit route. Disable sponsorGas to continue.");return}e.setIsExecuting(!0),e.setError(null);let s=!1;try{const o=n.asset.chainId,r=v.getEscrowContractAddress(o),i=T.parseUnits(n.amount,n.asset.decimals),l=t.length===1&&ja(e.effectiveDepositFee,{amount:i,token:v.normalizeNativeTokenAddress(n.asset.address),chainId:o}),c=!e.isNon7702&&!e.escrowOnly&&!wn(n.asset);if(!e.isNon7702&&t.length===1&&!c&&!l)throw new Error("Fee quote is out of date. Please wait for it to refresh.");let d=e.externalWalletClient;if(!e.escrowOnly){if(!d)throw new Error("External wallet not connected");if(e.externalProvider){const p=await Ro({provider:e.externalProvider,account:e.sourceAddress,chainId:o});p.viemChain&&(d=p.extWc)}}if(e.isNon7702){if(!d)throw new Error("External wallet not connected");if(!e.sourceAddress)throw new Error("External wallet address not available");if(e.nativeChainId&&o===e.nativeChainId){const p=f.getChainConfig(o),m=t.map(x=>`${x.amount} ${x.asset.symbol}`).join(", ");e.setConfirmationData({network:p?.displayName||`Chain ${o}`,amount:m,symbol:"",chainId:o}),e.setShowConfirmation(!0);let h=null;e.setDirectDepositStatus("processing"),e.setDirectDepositChainId(o);for(const x of t){const g=T.parseUnits(x.amount,x.asset.decimals),y=v.normalizeNativeTokenAddress(x.asset.address),w=x.asset.isNative||v.isNativeToken(y),C=await Bs(d,{chainId:o,recipient:r,tokenAddr:y,isNative:w,amount:g,failureMessage:`Escrow deposit failed for ${x.asset.symbol}`});h=C,e.setDirectDepositTxHash(C)}if(t[0]?.amount){const x=t[0].amount;if(e.onDepositExecute){e.setPostDepositStatus("executing");try{await e.onDepositExecute(x),e.setPostDepositStatus("success")}catch(y){console.error("ctx.onDepositExecute failed:",y),e.setPostDepositStatus("error"),e.setPostDepositError(y?.message||"Post-deposit instruction failed")}}else e.setPostDepositStatus("success");e.setDirectDepositStatus("success"),e.setPostDepositAmount(x),e.setPostDepositSuccess(!0);const g={type:"deposit",status:"success",amount:x,asset:t[0].asset.symbol,sourceChain:p?.displayName||`Chain ${o}`,txHash:h??void 0};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:g})),e.onDepositSuccess?.(g)}e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset)}else{const p=e.destinationChainId||e.nativeChainId;if(!p)throw new Error("Destination chain ID is required for non-7702 mode. Either pass ctx.destinationChainId to <SpiceDeposit> or set ctx.nativeChainId on <SpiceFlowProvider>.");const m=f.getDelegateContractAddress(o),h=r,x=[];let g=null;for(const y of t){const w=T.parseUnits(y.amount,y.asset.decimals),C=v.normalizeNativeTokenAddress(y.asset.address),b=y.asset.isNative||v.isNativeToken(C),S=await Bs(d,{chainId:o,recipient:h,tokenAddr:C,isNative:b,amount:w,failureMessage:`Transfer failed for ${y.asset.symbol}`,settle:!0});g||(g=S),e.depositDataRef.current||(e.depositDataRef.current=[]),e.depositDataRef.current.push({txHash:S,sender:e.sourceAddress,tokenAddress:C,chainId:o,amount:w.toString(),user:e.spiceBalanceUser}),x.push({tokenAddress:C,tokenAmount:w.toString(),sender:e.sourceAddress,receiver:h})}if(!g)throw new Error("No transaction hash generated");if(!e.destinationTokenAddress){const y={type:"deposit",status:"success",amount:t[0]?.amount,asset:t[0]?.asset?.symbol,sourceChain:f.getChainName(o),txHash:g};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:y})),e.onDepositSuccess?.(y),e.depositDataRef.current=null,e.bridgedAmountRef.current=t[0]?.amount||null,e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset),e.setShowConfirmation(!1);return}if(e.mode==="ondemand"){const y={to:m,value:BigInt(0),data:"0x"},w=await f.getTokenDecimals(p,e.destinationTokenAddress);let C=BigInt(0);for(const A of x){const M=BigInt(A.tokenAmount),P=v.normalizeNativeTokenAddress(A.tokenAddress),N=t.find(U=>{const O=v.normalizeNativeTokenAddress(U.asset.address);return f.addressesEqual(O,P)}),B=N?N.asset.decimals:await f.getTokenDecimals(o,v.ZERO_ADDRESS);C+=v.convertAmountBetweenDecimals(M,B,w)}e.isCrossDenomination&&e.convertedUsdAmount&&(C=e.convertedUsdAmount);const b={chainId:o,tokenTransfers:x.map(A=>({from:A.sender,to:A.receiver,token:A.tokenAddress,amount:BigInt(A.tokenAmount)})),call:y},S=e.isCrossDenomination&&e.convertedUsdAmount?[{from:e.sourceAddress,to:r,token:v.normalizeNativeTokenAddress(t[0].asset.address),amount:T.parseUnits(t[0].amount,t[0].asset.decimals)}]:[],I={chainId:p,tokenTransfers:[...S,{from:"escrow",to:e.sourceAddress,token:e.destinationTokenAddress,amount:C}],call:{to:e.destinationTokenAddress,value:BigInt(0),data:"0x"}},F={mode:"non-7702:on-demand",chainBatches:[b,I]},k={user:e.sourceAddress,intents:[F]},E=await f.relayerService.createAction(k),R=E.actionId,j=E.intentIds[0];if(!g)throw new Error("No transaction hash available");e.startStatusPolling(j,f.createInitialSteps([{chainId:o,calls:[y]},{chainId:p,calls:[I.call]}],A=>f.getChainName(A))),await f.relayerService.executeStep(R,0,0,{action:"execute",hash:g}),t[0]?.amount&&(e.bridgedAmountRef.current=t[0].amount),e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset),e.setShowConfirmation(!1)}else throw new Error("Presign mode not yet fully supported for cross-chain deposits")}}else{const p=[];let m=0,h;const x=l&&e.effectiveDepositFee?T.formatUnits(e.effectiveDepositFee.net,n.asset.decimals):n?.amount;for(const A of t){const M=T.parseUnits(A.amount,A.asset.decimals),P=l&&A===n,N=P?e.effectiveDepositFee.fee:0n,B=P?e.effectiveDepositFee.net:M,U=e.escrowOnly?M:M+N,O=v.normalizeNativeTokenAddress(A.asset.address),z=A.asset.isNative||v.isNativeToken(O);if(!e.escrowOnly&&!wn(A.asset)){e.setDirectDepositStatus("processing"),e.setDirectDepositChainId(o);const q=await Bs(d,{chainId:o,recipient:e.address,tokenAddr:O,isNative:z,amount:M,failureMessage:`Transfer to embedded wallet failed for ${A.asset.symbol}`});m+=1,A===n&&(h=q);continue}e.escrowOnly||await Bs(d,{chainId:o,recipient:e.address,tokenAddr:O,isNative:z,amount:U,failureMessage:`Transfer to embedded wallet failed for ${A.asset.symbol}`,afterSend:()=>ac({chainId:o,tokenAddress:v.normalizeNativeTokenAddress(A.asset.address),tokenSymbol:A.asset.symbol,tokenDecimals:A.asset.decimals,amount:A.amount,rawAmount:M.toString(),embeddedWalletAddress:e.address,externalWalletAddress:e.sourceAddress,timestamp:Date.now(),isNative:z}),settle:!0}),p.push(z?{to:r,value:B,data:"0x"}:{to:O,value:BigInt(0),data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"transfer",args:[r,B]})}),N>0n&&p.push(z?{to:v.SPICE_GAS_FEE_RECIPIENT,value:N,data:"0x"}:{to:O,value:BigInt(0),data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"transfer",args:[v.SPICE_GAS_FEE_RECIPIENT,N]})})}if(p.length===0){e.setDirectDepositTxHash(h??null),e.setDirectDepositStatus("success");const A={type:"deposit",status:"success",amount:n.amount,asset:n.asset.symbol,sourceChain:f.getChainName(o),txHash:h};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:A})),e.onDepositSuccess?.(A),e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(n.asset);return}m>0&&e.setDirectDepositStatus("idle");const g=t.find(A=>e.escrowOnly||wn(A.asset))??n,y=await f.getClientForChain(o).getBlockNumber(),w=p.map(A=>({...A,to:T.getAddress(A.to)})),C={chainId:o,recentBlock:y,calls:w,tokenTransfers:[]},b=$c({sourceChainId:o,selectedAsset:g===n&&x?{...n,amount:x}:g,destinationChainId:e.destinationChainId,destinationTokenAddress:e.destinationTokenAddress,isCrossDenomination:e.isCrossDenomination,convertedUsdAmount:e.convertedUsdAmount}),S=await _c(e.depositBatches,b),I=[C,...S];if(!e.address)throw new Error("Address not available");const F=[];if(e.isCrossDenomination&&e.convertedUsdAmount&&e.destinationTokenAddress){const A=e.selectedDepositAssets[0]?.asset;if(A){const M=T.parseUnits(e.selectedDepositAssets[0].amount,A.decimals);F.push({from:e.address,to:r,token:v.normalizeNativeTokenAddress(A.address),amount:M}),F.push({from:"escrow",to:e.address,token:e.destinationTokenAddress,amount:e.convertedUsdAmount})}}F.length>0&&I[1]&&(I[1].tokenTransfers=F);const k=f.createInitialSteps(I,A=>f.getChainName(A));let E=!1;const R=await e.execution.execute(I,v.ZERO_ADDRESS,0n,A=>{if(A.intentId&&!E){E=!0;for(const M of t)vo(e.address,o,v.normalizeNativeTokenAddress(M.asset.address));e.startStatusPolling(A.intentId,k)}},void 0,{userOverride:e.address,useCustomTransfers:!0,skipPreSubmitFeeEstimate:!0,skipUserFundingPreflight:!0});if(e.refreshAssets(),e.onDepositExecute&&g.amount)try{e.setPostDepositStatus("executing"),await e.onDepositExecute(x||g.amount),e.setPostDepositStatus("success"),e.setPostDepositAmount(x||g.amount),e.setPostDepositSuccess(!0)}catch(A){console.error("ctx.onDepositExecute failed (7702):",A),e.setPostDepositStatus("error"),e.setPostDepositError(A?.message||"Post-deposit instruction failed");return}const j={type:"deposit",status:"success",amount:g===n&&x||g.amount,asset:g.asset.symbol,sourceChain:f.getChainName(o),txHash:/^0x[0-9a-f]{64}$/i.test(R??"")?R:void 0};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:j})),e.onDepositSuccess?.(j),e.onDepositSelect&&e.onDepositSelect(g.asset)}}catch(o){s=!0,console.error("[DepositModal] executeDeposit CAUGHT ERROR:",o),console.error("[DepositModal] Error details:",{message:o?.message,code:o?.code,name:o?.name,stack:o?.stack?.slice(0,500)}),e.setError(f.sanitizeError(o,"Deposit failed")),e.clearStatus()}finally{e.setIsExecuting(!1),s&&e.setDirectDepositStatus("idle"),s||!e.getCurrentIntentStatus()&&e.getCurrentPostDepositStatus()!=="idle"||e.setShowConfirmation(!1)}}async function td(e){const{asset:t,assetIndex:n,selectedAssetCount:s,address:o,escrowOnly:r,isNon7702:i}=e;if(n!==0||i||s>1||!o||t.balance<=0n)return null;if(!r&&!wn(t))return f.formatRawTokenInput(t.balance,t.decimals);const l=await Ba({address:o,depositQuote:{asset:t,amount:t.balance,token:v.normalizeNativeTokenAddress(t.address),chainId:t.chainId},escrowOnly:r}),c=r?t.balance:t.balance>l.fee?t.balance-l.fee:0n;return f.formatRawTokenInput(c,t.decimals)}async function Ba(e){const{address:t,depositQuote:n,escrowOnly:s}=e,{asset:o,amount:r,token:i,chainId:l}=n,c=v.getEscrowContractAddress(l),d=o.isNative||v.isNativeToken(i),p=r>1n?1n:0n,m=[d?{to:c,value:r,data:"0x"}:{to:i,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"transfer",args:[c,r]})}];p>0n&&m.push(d?{to:v.SPICE_GAS_FEE_RECIPIENT,value:p,data:"0x"}:{to:i,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"transfer",args:[v.SPICE_GAS_FEE_RECIPIENT,p]})});const h={chainId:l,tokenTransfers:[],calls:m},x=(await f.relayerService.estimateBatchGas({user:t,outputToken:i,chainBatches:[{...h,hash:v.hashChainBatches([h])[0].hash}],signal:e.signal})).gasFee,g=s&&x<r?r-x:r;return{fee:x,net:g,quotedAmount:r,token:i,chainId:l}}function nd(e,t=40,n=18){const s=e.length,o=[{maxLength:7,shrink:0},{maxLength:10,shrink:6},{maxLength:13,shrink:12},{maxLength:16,shrink:16},{maxLength:20,shrink:19}].find(r=>s<=r.maxLength);return Math.max(n,t-(o?.shrink??22))}const Sn=({value:e,element:t="span",placeholder:n,ariaLabel:s,ariaInvalid:o,disabled:r,onChange:i,inputMode:l="decimal",autoComplete:c="off",dataSpiceflowFocus:d,fontFamily:p,fontWeight:m=700,color:h,textAlign:x,lineHeight:g=1,maxFontSize:y=40,minFontSize:w=18,overflow:C="ellipsis",title:b,style:S})=>{const I=nd(e||n||"",y,w),F=C==="wrap"?{overflowWrap:"anywhere",wordBreak:"break-word",whiteSpace:"normal"}:C==="ellipsis"?{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}:{},k={fontFamily:p,fontSize:`${I}px`,fontWeight:m,color:h,lineHeight:g,letterSpacing:0,textAlign:x,minWidth:0,maxWidth:"100%",...F,...S};return t==="input"?a.jsx("input",{type:"text",inputMode:l,autoComplete:c,"aria-label":s,"aria-invalid":o||void 0,"data-spiceflow-focus":d||void 0,value:e,onChange:i,placeholder:n,disabled:r,title:b,style:{backgroundColor:"transparent",border:"none",outline:"none",padding:0,width:"100%",...k}}):a.jsx(t,{title:b,style:k,children:e})},Oo=({pct:e,isMax:t,primaryColor:n,dark:s,fillColor:o})=>{const r=e/100;return a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[a.jsx("circle",{cx:"7",cy:"7",r:"6.84375",fill:t?n:"none",stroke:t?n:s?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!t&&r>0&&a.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${r>.5?1:0} 1 ${7+6.84375*Math.sin(r*2*Math.PI)} ${7-6.84375*Math.cos(r*2*Math.PI)} Z`,fill:o})]})},Ra=({chainId:e,name:t,size:n=16})=>{const s=e&&(yn[e]||v.getChainMeta(e)?.logo)||"";return s?a.jsx("img",{src:s,alt:t||`Chain ${e}`,loading:"lazy",decoding:"async",width:n,height:n,style:{width:`${n}px`,height:`${n}px`,borderRadius:"50%",objectFit:"cover",flexShrink:0}}):null},sd={1:"ethereum",56:"binance-smart-chain",137:"polygon-pos",143:"monad",4114:"citrea",4663:"robinhood",8453:"base",42161:"arbitrum-one"},od=6e4,os=new Map;function Da(e,t){return os.get(e)?.logos?.get(t.toLowerCase())}function rd(e,t){const n=sd[e];if(!n||v.isNativeToken(t))return;const s=os.get(e);if(s?.logos||s?.pending)return s.pending;if(s?.failedAt!==void 0&&Date.now()-s.failedAt<od)return;const o=Promise.resolve().then(async()=>{try{const r=await fetch(`https://tokens.coingecko.com/${n}/all.json`,{signal:AbortSignal.timeout(1e4)});if(!r.ok)throw new Error("Token list request failed");const i=await r.json(),l=new Map;for(const c of i?.tokens??[])c?.address&&c?.logoURI&&l.set(String(c.address).toLowerCase(),c.logoURI);os.set(e,{logos:l})}catch(r){console.warn(`[tokenLogos] Token list unavailable for chain ${e}`,r),os.set(e,{failedAt:Date.now()})}});return os.set(e,{...s,pending:o}),o}function Oa(e,t,n){const[s,o]=u.useState(),r=e||e===null||t===void 0||!n?void 0:`${t}:${n.toLowerCase()}`,i=r?Da(t,n):void 0;return u.useEffect(()=>{if(!r||i||t===void 0||!n)return;let l=!0;const c=()=>{const p=Da(t,n);l&&p&&o({token:r,logo:p})},d=rd(t,n);return d?d.then(c):c(),()=>{l=!1}},[r,i,t,n]),e||i||(s&&s.token===r?s.logo:void 0)}const Rs=({symbol:e,label:t,logoURI:n,chainId:s,address:o,size:r=20,theme:i})=>{const{theme:l}=f.useSpiceBrand(),c=i||l,[d,p]=u.useState(),m={width:`${r}px`,height:`${r}px`,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:`${r*.4}px`,fontWeight:c.typography.fontWeight.bold,flexShrink:0,overflow:"hidden",backgroundColor:"#ffffff"},h=Oa(n===null?null:n||ho[e.toUpperCase()],s,o);if(n===null)return null;if(h&&h!==d)return a.jsx("img",{src:h,alt:t??e,loading:"lazy",decoding:"async",style:{...m,objectFit:"cover"},onError:()=>p(h)});const x=ad(e);return a.jsx("div",{style:{...m,...x.style},children:x.icon})},ad=e=>{const t=e.toUpperCase(),n={ETH:{bg:"#627EEA",text:"#FFFFFF",icon:"\u039E"},BTC:{bg:"#F7931A",text:"#FFFFFF",icon:"\u20BF"},USDC:{bg:"#2775CA",text:"#FFFFFF"},USDT:{bg:"#26A17B",text:"#FFFFFF"},DAI:{bg:"#F5AC37",text:"#FFFFFF"},WETH:{bg:"#627EEA",text:"#FFFFFF",icon:"\u039E"},WBTC:{bg:"#F09242",text:"#FFFFFF",icon:"\u20BF"},CBTC:{bg:"#F7931A",text:"#FFFFFF",icon:"\u20BF"},USD:{bg:"#26A17B",text:"#FFFFFF",icon:"$"},MATIC:{bg:"#8247E5",text:"#FFFFFF"},AVAX:{bg:"#E84142",text:"#FFFFFF"},SOL:{bg:"#9945FF",text:"#FFFFFF"},DOT:{bg:"#E6007A",text:"#FFFFFF"},ADA:{bg:"#0033AD",text:"#FFFFFF"},LINK:{bg:"#375BD2",text:"#FFFFFF"},UNI:{bg:"#FF007A",text:"#FFFFFF"},AAVE:{bg:"#B6509E",text:"#FFFFFF"},CRV:{bg:"#40E0D0",text:"#000000"}}[t];if(n)return{style:{backgroundColor:n.bg,color:n.text},icon:n.icon||t.charAt(0)};const s=t.split("").reduce((l,c)=>c.charCodeAt(0)+((l<<5)-l),0),o=Math.abs(s)%360,r=`hsl(${o}, 60%, 50%)`,i=o>180?"#FFFFFF":"#000000";return{style:{backgroundColor:r,color:i},icon:t.charAt(0)}},id=({selectedAsset:e,assets:t,onAssetSelect:n,showDropdown:s,onToggleDropdown:o,disabled:r=!1,theme:i,onViewAllAssets:l})=>{const c=f.useAssetDisplay(),{theme:d}=f.useSpiceBrand(),p=i||d,m=u.useRef(null),h=u.useRef(null),x=u.useRef(null),[g,y]=u.useState(null);u.useEffect(()=>{if(s&&h.current){const N=()=>{if(h.current){const B=h.current.getBoundingClientRect();y({top:B.bottom+6,right:window.innerWidth-B.right})}};return N(),window.addEventListener("scroll",N,!0),window.addEventListener("resize",N),()=>{window.removeEventListener("scroll",N,!0),window.removeEventListener("resize",N)}}else y(null)},[s]),u.useEffect(()=>{const N=B=>{m.current&&!m.current.contains(B.target)&&x.current&&!x.current.contains(B.target)&&s&&o()};return s&&document.addEventListener("mousedown",N),()=>{document.removeEventListener("mousedown",N)}},[s,o]);const[w,C]=u.useState(!1),b=p.mode==="light",S={backgroundColor:"transparent",border:`1px solid ${b?"#aaaaaa":p.colors.border}`,borderRadius:"6px",color:p.colors.text,cursor:r?"not-allowed":"pointer",padding:"8px 14px 8px 10px",width:"100%",display:"flex",flexDirection:"column",gap:"4px",opacity:r?.6:1,transition:f.transition.interactive,transform:w?"scale(0.98)":"scale(1)"},I={display:"flex",justifyContent:"space-between",alignItems:"center",gap:"10px",minWidth:0},F={display:"flex",alignItems:"center",gap:"4px",paddingTop:"4px",borderTop:`1px solid ${p.colors.border}`},k=()=>g?{position:"fixed",top:`${g.top}px`,right:`${g.right}px`,backgroundColor:p.colors.secondary,border:`1px solid ${p.colors.border}`,borderRadius:p.borderRadius.md,boxShadow:p.shadows.lg,zIndex:f.z.dropdown,width:"200px",maxHeight:"300px",overflow:"auto"}:{},E={backgroundColor:"transparent",border:"none",color:p.colors.text,cursor:"pointer",padding:p.spacing.sm,width:"100%",display:"flex",alignItems:"center",gap:p.spacing.sm,transition:`background-color ${p.animation.normal}`,":hover":{backgroundColor:p.colors.surfaceHover}},R={display:"flex",flexDirection:"column",alignItems:"flex-start",flex:1},j={fontSize:p.typography.fontSize.sm,fontWeight:p.typography.fontWeight.medium},A={fontSize:p.typography.fontSize.xs,color:p.colors.textMuted},M={backgroundColor:"transparent",border:"none",borderTop:`1px solid ${p.colors.border}`,color:p.colors.primary,cursor:"pointer",padding:"10px 12px",width:"100%",display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",fontFamily:p.typography.fontFamily,fontSize:p.typography.fontSize.xs,fontWeight:p.typography.fontWeight.medium,textDecoration:"underline",textUnderlineOffset:"2px"},P={transition:`transform ${p.animation.normal}`,transform:s?"rotate(180deg)":"rotate(0deg)",flexShrink:0};return a.jsxs(a.Fragment,{children:[a.jsx("div",{style:{position:"relative"},ref:m,children:a.jsxs("div",{ref:h,style:S,onClick:r?void 0:o,onMouseLeave:()=>{C(!1)},onMouseDown:()=>C(!0),onMouseUp:()=>C(!1),children:[a.jsxs("div",{style:I,children:[a.jsx("div",{style:{display:"flex",alignItems:"center",gap:"8px",flex:1,minWidth:0},children:e?.asset?a.jsxs(a.Fragment,{children:[a.jsx(Rs,{symbol:e.asset.symbol,label:c(e.asset).symbol,logoURI:c(e.asset).logoURI,chainId:e.asset.chainId,address:e.asset.address,theme:p,size:24}),a.jsx("span",{style:{fontSize:"15px",fontWeight:500,color:p.colors.text,lineHeight:"1.5",flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:c(e.asset).symbol})]}):a.jsx("span",{style:{fontSize:"14px",color:p.colors.textMuted},children:"Select"})}),a.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:b?p.colors.textMuted:"#c7ccd4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:P,children:a.jsx("path",{d:"M6 9l6 6 6-6"})})]}),e?.asset&&a.jsxs("div",{style:F,children:[!e.asset.displayChainName&&a.jsx(Ra,{chainId:e.asset.chainId,theme:p}),a.jsx("span",{style:{fontSize:"11px",color:p.colors.textMuted},children:f.getAssetDisplayChainName(e.asset)})]})]})}),s&&g&&jn.createPortal(a.jsxs("div",{ref:x,style:k(),children:[t.length===0&&a.jsx("div",{style:{padding:"10px 12px",color:p.colors.textMuted,fontSize:p.typography.fontSize.xs},children:"No assets available"}),t.map(N=>a.jsxs("button",{style:E,onClick:()=>{n(N),o()},children:[a.jsx(Rs,{symbol:N.symbol,label:c(N).symbol,logoURI:c(N).logoURI,chainId:N.chainId,address:N.address,theme:p},Ge(N)),a.jsxs("div",{style:R,children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:p.spacing.xs},children:[a.jsx("span",{style:j,children:c(N).symbol}),!N.displayChainName&&a.jsx(Ra,{chainId:N.chainId,theme:p})]}),a.jsxs("span",{style:A,children:[f.formatAssetBalance(N)," \u2022"," ",f.getAssetDisplayChainName(N)]})]})]},Ge(N))),l&&a.jsxs("button",{type:"button",style:M,onClick:()=>{o(),l()},children:[a.jsx("span",{children:"View all assets"}),a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M5 12h14"}),a.jsx("path",{d:"M13 5l7 7-7 7"})]})]})]}),document.body)]})},ld=({assets:e,selectedAsset:t,onAssetSelect:n,onAmountChange:s,disabled:o=!1,loading:r=!1,label:i="Select Asset",showBalance:l=!0,showMaxButton:c=!0,placeholder:d="0.0",theme:p,styles:m,maxAmount:h,resolveMaxAmount:x,hideAmountInput:g=!1,displayAmount:y,dark:w,onViewAllAssets:C})=>{const b=f.useAssetDisplay(),{theme:S,primaryColor:I,dark:F,dk:k}=f.useSpiceBrand(m,w),E=p||S,R=w??F,[j,A]=u.useState(!1),[M,P]=u.useState(null),[N,B]=u.useState(null),[U,O]=u.useState(!1),[z,q]=u.useState(null),[ue,le]=u.useState(t?.amount||""),G=u.useRef(x),ne=t?.asset?Ge(t.asset):"",re=u.useRef(ne);re.current=ne;const Y=!!x,_=z??h;u.useEffect(()=>{G.current=x},[x]),u.useEffect(()=>{le(t?.amount||"")},[ne,t?.amount]),u.useEffect(()=>{q(null),O(!1)},[ne,Y,t?.asset?.balance]);const Z=()=>{const K=t?.asset;if(!K)return 0n;if(!_)return K.balance;const W=T.parseUnits(_,K.decimals);return W<K.balance?W:K.balance},pe=K=>{le(K),s?.(K)},D=K=>{const W=t?.asset,Q=f.parseNumericInput(K.startsWith(".")?`0${K}`:K,W?.decimals);if(!W||!Q)return pe(Q);const ae=T.parseUnits(Q,W.decimals),we=Z();pe(ae>we?T.formatUnits(we,W.decimals):Q)},L=async()=>{const K=t?.asset;if(!K||o)return;const W=ne,Q=G.current;if(z)return pe(z);if(Q){O(!0);try{const ae=await Q(K);if(re.current!==W)return;if(ae!==null){const we=f.parseNumericInput(ae,K.decimals);q(we),pe(we);return}return}catch(ae){console.warn("[AssetSelector] Failed to resolve max amount:",ae);return}finally{re.current===W&&O(!1)}}re.current===W&&pe(T.formatUnits(Z(),K.decimals))},$=async K=>{if(!(!t||o)){if(K===100)return L();pe(T.formatUnits(Z()*BigInt(K)/100n,t.asset.decimals))}},de=t?.asset?.balanceFormatted??0,ce=parseFloat(ue)||0,he=de>0?ce/de*100:0,X={backgroundColor:m?.assetSelector?.backgroundColor||m?.secondaryBackground||(R?k.cardBg:"#e9e9e9"),border:R?`0.5px solid ${k.cardBorder}`:"0.5px solid #A8A8A7",borderRadius:m?.assetSelector?.borderRadius||"6px",padding:m?.assetSelector?.padding||"16px",height:"auto",minHeight:g?void 0:"144px",display:"flex",flexDirection:"column",gap:"8px",position:"relative",opacity:o?.6:1};return r?a.jsx("div",{style:X,children:a.jsxs("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"space-between"},children:[a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[a.jsx("div",{style:{backgroundColor:R?k.hoverBg:"#d1d5db",borderRadius:"4px",height:"16px",width:"60px"}}),a.jsx("div",{style:{backgroundColor:R?k.hoverBg:"#d1d5db",borderRadius:"4px",height:"40px",width:"150px"}})]}),a.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:"8px"},children:[a.jsx("div",{style:{backgroundColor:R?k.hoverBg:"#d1d5db",borderRadius:"4px",height:"12px",width:"80px"}}),a.jsx("div",{style:{backgroundColor:R?k.hoverBg:"#d1d5db",borderRadius:"6px",height:"46px",width:"128px"}})]})]})}):a.jsxs("div",{style:X,children:[a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[a.jsx("span",{style:{fontFamily:m?.fontFamily||E.typography.fontFamily,fontSize:"16px",fontWeight:500,color:R?k.textSecondary:"#7d7c7b",lineHeight:"24px"},children:i}),l&&t?.asset&&a.jsxs("span",{style:{fontFamily:m?.fontFamily||E.typography.fontFamily,fontSize:"12px",fontWeight:500,color:R?k.textSecondary:"#71757a",lineHeight:"16px"},children:["Balance: ",f.formatAssetBalance(t.asset)]})]}),a.jsxs("div",{style:{display:"flex",justifyContent:g&&!y?"flex-start":"space-between",alignItems:"center",flex:1},children:[!g&&a.jsx(Sn,{element:"input",ariaLabel:t?.asset?`${b(t.asset).symbol} amount`:"Amount",dataSpiceflowFocus:!0,value:ue,onChange:K=>D(K.target.value),placeholder:d,disabled:o||!t?.asset,fontFamily:m?.fontFamily||E.typography.fontFamily,color:o?R?"rgba(255, 255, 255, 0.16)":"rgba(14, 13, 11, 0.16)":ue?R?"#ffffff":"#0e0d0b":R?"#4a5568":"#d1d5db",lineHeight:"1.08",maxFontSize:40,minFontSize:22,style:{width:"100%",maxWidth:"200px"}}),a.jsx("div",{style:{width:"176px",position:"relative",flexShrink:0},children:a.jsx(id,{selectedAsset:t,assets:e,onAssetSelect:n,showDropdown:j,onToggleDropdown:()=>A(!j),disabled:o,theme:E,onViewAllAssets:C})}),g&&y&&a.jsx(Sn,{element:"span",value:y,title:y,fontFamily:m?.fontFamily||E.typography.fontFamily,color:R?"#ffffff":"#0e0d0b",lineHeight:"1.08",textAlign:"right",maxFontSize:40,minFontSize:22,style:{flex:1}})]}),!g&&a.jsx("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",height:"14px"},children:[0,25,50,75,100].filter(K=>c||K!==100).map((K,W)=>{const Q=Math.abs(he-K)<1,ae=W===4,we=M===K,ke=N===K;return a.jsx("button",{onClick:()=>$(K),onMouseEnter:()=>P(K),onMouseLeave:()=>{P(null),B(null)},onMouseDown:()=>B(K),onMouseUp:()=>B(null),disabled:o||!t?.asset||K===100&&U,title:`${K}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:o||!t?.asset||K===100&&U?"not-allowed":"pointer",opacity:Q?1:we?.8:.5,transform:ke?"scale(0.85)":we?"scale(1.15)":"scale(1)",transition:f.transition.interactive},children:a.jsx(Oo,{pct:K,isMax:ae,primaryColor:I,dark:R,fillColor:R?k.textSecondary:"#3C3E42"})},K)})})]})},Pn=u.memo(ld),cd=({selectedDepositAssets:e,depositAssets:t,secondAssetOptions:n,loadingAssets:s,allowSecondAsset:o,theme:r,styles:i,dark:l,dk:c,onSelect:d,onAmountChange:p,onAdd:m,onRemove:h,resolveMaxAmount:x,onViewAllAssets:g})=>a.jsxs(a.Fragment,{children:[e.map((y,w)=>{const C=e.length===1?"Deposit":`Asset ${w+1}`;return a.jsxs("div",{style:{marginBottom:r.spacing.md,position:"relative"},children:[a.jsx(Pn,{assets:w===0?t:n,selectedAsset:y||void 0,onAssetSelect:b=>d(b,w),onAmountChange:b=>p(b,w),loading:s,label:C,showBalance:!0,theme:r,styles:i,allowSecondAsset:o&&w===0,onAddAsset:m,canAddAsset:e.length===1&&!!e[0]?.asset,resolveMaxAmount:x?b=>x(b,w):void 0,onViewAllAssets:w===0?g:void 0}),w===1&&a.jsx("button",{onClick:()=>h(w),style:{position:"absolute",top:"-2px",right:"-2px",background:l?`${c.cardBg}ee`:"rgba(255, 255, 255, 0.9)",border:`1px solid ${c.cardBorder}`,borderRadius:"50%",cursor:"pointer",color:r.colors.textMuted,fontSize:"16px",padding:"2px",width:"22px",height:"22px",display:"flex",alignItems:"center",justifyContent:"center",transition:f.transition.interactive,boxShadow:"0 1px 3px rgba(0, 0, 0, 0.1)"},onMouseEnter:b=>{b.currentTarget.style.color=l?c.errorText:"#ef4444",b.currentTarget.style.background=l?c.cardBg:"#fff",b.currentTarget.style.borderColor=l?c.errorBorder:"#fecaca"},onMouseLeave:b=>{b.currentTarget.style.color=r.colors.textMuted,b.currentTarget.style.background=l?`${c.cardBg}ee`:"rgba(255, 255, 255, 0.9)",b.currentTarget.style.borderColor=l?c.cardBorder:"#e5e7eb"},title:"Remove asset",children:"\xD7"})]},`asset-${w}`)}),e.length===0&&a.jsx("div",{style:{marginBottom:r.spacing.md},children:a.jsx(Pn,{assets:t,selectedAsset:void 0,onAssetSelect:y=>d(y,0),onAmountChange:y=>p(y,0),loading:s,label:"Deposit",showBalance:!0,theme:r,styles:i,allowSecondAsset:o,onAddAsset:m,canAddAsset:!1,resolveMaxAmount:x?y=>x(y,0):void 0},"initial-selector")})]}),dd=u.memo(cd);function ud(e,t){switch(e){case"success":return{bg:t.successBg,border:t.successBorder,text:t.successText};case"warning":return{bg:t.warningBg,border:t.warningBorder,text:t.warningText};case"error":return{bg:t.errorBg,border:t.errorBorder,text:t.errorText};case"info":return{bg:t.infoBg,border:t.infoBorder,text:t.infoText}}}const rn=({variant:e,palette:t,children:n,icon:s,style:o,fontFamily:r,size:i="default"})=>{const l=ud(e,t),c=i==="compact";return a.jsxs("div",{role:e==="error"?"alert":"status",style:{backgroundColor:l.bg,border:`1px solid ${l.border}`,borderRadius:c?"7px":"8px",padding:c?"8px 10px":"12px 16px",color:l.text,fontSize:c?"12px":"13px",lineHeight:c?1.4:1.5,display:"flex",alignItems:"flex-start",gap:c?"6px":"8px",fontFamily:r,...o},children:[s&&a.jsx("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:s}),a.jsx("span",{style:{minWidth:0,overflowWrap:"anywhere"},children:n})]})},Na=f.font.mono,bn=({label:e,value:t,palette:n,valueColor:s,labelColor:o,style:r})=>a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",...r},children:[a.jsx("span",{style:{fontSize:"12px",color:o??n.textSecondary,fontFamily:Na,fontWeight:500,letterSpacing:"0.03em",flexShrink:0,whiteSpace:"nowrap"},children:e}),a.jsx("span",{style:{fontSize:"13px",color:s??n.textPrimary,fontWeight:500,fontFamily:Na,minWidth:0,textAlign:"right",overflowWrap:"anywhere"},children:t})]}),No=({onClick:e,label:t="Add Funds",color:n,fontFamily:s,style:o})=>{const[r,i]=u.useState(!1);return a.jsxs("button",{type:"button",onClick:e,"data-spiceflow-focus":!0,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),style:{background:"none",border:"none",cursor:"pointer",padding:0,display:"inline-flex",alignItems:"center",gap:"4px",color:n,fontSize:"12px",fontWeight:500,fontFamily:s,textDecoration:"underline",textUnderlineOffset:"2px",whiteSpace:"nowrap",opacity:r?.75:1,transition:"opacity 150ms ease",...o},children:[t,a.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.8","aria-hidden":"true",children:[a.jsx("circle",{cx:"6",cy:"6",r:"5"}),a.jsx("path",{d:"M6 4v4M4 6h4",strokeLinecap:"round"})]})]})},Mo=({value:e,onChange:t,ariaLabel:n,placeholder:s,endAdornment:o,size:r="lg",dark:i,styles:l,inputRef:c,autoFocus:d})=>{const{dark:p,dk:m}=f.useSpiceBrand(l,i),h=i??p,x=r==="lg",g=x?"15px":"14px",y=x?"7px":"10px",w=x?f.radius.input:f.radius.sm,C=l?.fontFamily||f.font.ui,b=h?m.inputBg:"#FAFAFA",S=h?m.inputBorder:"#e5e7eb",I=h?m.textPrimary:"#374151",F=h?m.textSecondary:"#9ca3af";return a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",backgroundColor:b,borderRadius:w,boxShadow:h?"0 2px 4px rgba(0, 0, 0, 0.3)":"0 2px 4px rgba(0, 0, 0, 0.1)",padding:`${y} 5px`,border:`1px solid ${S}`},children:[a.jsx(Qc,{style:{color:F},size:24}),a.jsx("input",{ref:c,type:"text",role:"searchbox","aria-label":n,autoComplete:"off",spellCheck:!1,autoFocus:d,"data-spiceflow-focus":!0,placeholder:s,value:e,onChange:k=>t(k.target.value),style:{flex:1,backgroundColor:b,outline:"none",border:"none",color:I,fontSize:g,fontWeight:400,fontFamily:C}}),o]})},pd="This deposit didn't confirm in time. It may still have gone through, so check the explorer and refresh your balance before retrying.";function fd(e){return e?.overallStatus!=="failed"?{isFailed:!1,failureMessage:null}:{isFailed:!0,failureMessage:e.steps?.find(t=>t.status==="failed"&&!!t.error)?.error||pd}}const Ds=a.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",style:{flexShrink:0},children:[a.jsx("circle",{cx:"10",cy:"10",r:"10",fill:"#10b981"}),a.jsx("path",{d:"M6 10l3 3 5-6",stroke:"#ffffff",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),md=({isOpen:e,onClose:t,onConfirm:n,data:s,isExecuting:o=!1,error:r=null,theme:i,styles:l,intentStatus:c,postDepositStatus:d="idle",hasPostDepositInstruction:p=!1})=>{const{dark:m,dk:h,theme:x}=f.useSpiceBrand(l),[g,y]=u.useState(!1),[w,C]=u.useState(!0);u.useEffect(()=>{e||y(!1)},[e]);const b=()=>{y(!0),setTimeout(()=>{t()},300)},S=()=>{C(!w)};if(!e||!s)return null;const I=c?.overallStatus==="processing",F=c?.overallStatus==="success",k=!!c,{isFailed:E,failureMessage:R}=fd(c),j=!k&&p,A=j&&d==="executing",M=j&&d==="success",P=F&&p&&(d==="idle"||d==="executing")||A,N=F&&(!p||d==="success"||d==="error")||M||j&&d==="error",B=m?h.cardBg:"#ffffff",U=m?"0 -4px 20px rgba(0, 0, 0, 0.4)":"0 -4px 20px rgba(0, 0, 0, 0.15)",O=h.textSecondary,z=m?h.textPrimary:"#1f2937",q=m?h.textPrimary:"#1f2937",ue=ne=>a.jsx("div",{style:{marginBottom:i.spacing.md,padding:i.spacing.md,backgroundColor:l?.errorMessage?.backgroundColor||(i.mode==="light"?"#fef2f2":`${i.colors.error}20`),border:`1px solid ${l?.errorMessage?.borderColor||(i.mode==="light"?"#fecaca":i.colors.error)}`,borderRadius:l?.errorMessage?.borderRadius||i.borderRadius.md},children:a.jsx("p",{style:{color:l?.errorMessage?.color||i.colors.error,fontSize:l?.errorMessage?.fontSize||i.typography.fontSize.sm,margin:0,fontFamily:l?.errorMessage?.fontFamily||l?.fontFamily||i.typography.fontFamily},children:ne})}),le={fontSize:i.typography.fontSize.sm,fontWeight:500,color:O,fontFamily:f.font.mono,letterSpacing:"0.5px"},G=(ne,re,Y=z)=>a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[a.jsx("span",{style:le,children:ne}),a.jsx("span",{style:{fontSize:i.typography.fontSize.sm,fontWeight:500,color:Y,fontFamily:f.font.mono},children:re})]});return a.jsxs("div",{style:{position:"absolute",bottom:0,left:0,right:0,zIndex:10,animation:g?"slideDown 0.3s ease-in":"slideUp 0.3s ease-out",pointerEvents:"auto"},children:[a.jsxs("div",{style:{backgroundColor:B,borderRadius:"0",width:"100%",maxWidth:"522px",margin:"0 auto",padding:"18px 24px",boxShadow:U},children:[!F&&!M&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:i.spacing.md},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:"pointer"},onClick:S,children:[a.jsx("span",{style:{fontSize:"13px",fontWeight:i.typography.fontWeight.medium,color:O,fontFamily:l?.fontFamily||i.typography.fontFamily},children:"Transaction Details"}),a.jsx(Mn,{color:O,direction:w?"up":"down"})]}),a.jsx("button",{onClick:ne=>{ne.stopPropagation(),t()},style:{background:"none",border:"none",cursor:"pointer",padding:"4px",display:"flex",alignItems:"center",justifyContent:"center",color:O,transition:"color 0.2s ease"},onMouseEnter:ne=>{ne.currentTarget.style.color=q},onMouseLeave:ne=>{ne.currentTarget.style.color=O},children:a.jsx(ss,{size:16})})]}),a.jsxs("div",{style:{marginBottom:i.spacing.lg,display:"flex",flexDirection:"column",gap:i.spacing.md,overflow:"hidden",maxHeight:w?"200px":"0px",opacity:w?1:0,transition:"max-height 0.3s ease, opacity 0.3s ease"},children:[G("NETWORK",s.network),G("DEPOSITED AMOUNT",s.amount,i.colors.success),s.creditedAmount&&G("CREDITED AMOUNT",s.creditedAmount),s.spicenetFee&&G("SPICENET FEE",s.spicenetFee),s.networkFee&&G("EST. NETWORK FEE",s.networkFee)]})]}),r&&!k&&ue(r),E&&R&&ue(R),a.jsx(f.Button,{onClick:N||E?b:n,variant:"outline",fullWidth:!0,disabled:o||I||P||A,styles:l,theme:x,children:o||I||A||P?"PROCESSING...":N?"CONTINUE \u2192":E?"CLOSE":"CONFIRM DEPOSIT"}),N&&a.jsx("p",{style:{marginTop:i.spacing.md,marginBottom:0,fontSize:"14px",color:O,textAlign:"center",fontFamily:l?.fontFamily||i.typography.fontFamily},children:"Your funds are now available in your Account"}),a.jsx("div",{style:{marginTop:i.spacing.md,display:"flex",justifyContent:"center",alignItems:"center"},children:a.jsx("img",{src:va,alt:"Powered by SpiceNet",style:{height:"auto",width:"130px",opacity:1,filter:m?"brightness(0) invert(1) opacity(0.7)":"none"}})})]}),a.jsx("style",{children:`
|
|
3
|
+
"use strict";var Ki=Object.create;var sr=Object.defineProperty;var Zi=Object.getOwnPropertyDescriptor;var Xi=Object.getOwnPropertyNames;var Ji=Object.getPrototypeOf,$i=Object.prototype.hasOwnProperty;var _i=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Xi(t))!$i.call(e,o)&&o!==n&&sr(e,o,{get:()=>t[o],enumerable:!(s=Zi(t,o))||s.enumerable});return e};var el=(e,t,n)=>(n=e!=null?Ki(Ji(e)):{},_i(t||!e||!e.__esModule?sr(n,"default",{value:e,enumerable:!0}):n,e));const a=require("react/jsx-runtime"),f=require("./privy-n6MHafwm.js"),u=require("react"),v=require("@spicenet-io/spiceflow-core"),sn=require("wagmi"),T=require("viem"),_t=require("viem/actions"),Zs=require("@privy-io/react-auth"),jn=require("react-dom");require("@tanstack/react-query");const tl="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@100;200;300;400;500;600;700&display=swap",nl="spiceflow-ibm-plex-mono",sl="spiceflow-preconnect-googleapis",ol="spiceflow-preconnect-gstatic";function Xs(e,t){if(document.getElementById(e))return;const n=t();n.id=e,document.head.appendChild(n)}function rl(){typeof document>"u"||(Xs(sl,()=>{const e=document.createElement("link");return e.rel="preconnect",e.href="https://fonts.googleapis.com",e}),Xs(ol,()=>{const e=document.createElement("link");return e.rel="preconnect",e.href="https://fonts.gstatic.com",e.crossOrigin="",e}),Xs(nl,()=>{const e=document.createElement("link");return e.rel="stylesheet",e.href=tl,e}))}const al={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",8453:"0x4200000000000000000000000000000000000006",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",84532:"0x4200000000000000000000000000000000000006"},or=T.parseAbi(["function deposit() payable","function withdraw(uint256 wad)"]);function Js(e){return f.getChainConfig(e)?.wrappedNativeTokenAddress??al[e]}const $s=(e,t)=>({to:e,value:t,data:T.encodeFunctionData({abi:or,functionName:"deposit"})}),_s=(e,t)=>({to:e,value:0n,data:T.encodeFunctionData({abi:or,functionName:"withdraw",args:[t]})});function eo(e,t,n){const s=v.isNativeToken(t),o=v.isNativeToken(n);if(!s&&!o)return null;const r=Js(e);return r?{weth:r,wrapIn:s,unwrapOut:o}:null}function rr(e,t,n,s){const o=eo(e,t,n);return!o||s<=0n?null:o.wrapIn&&!o.unwrapOut&&n.toLowerCase()===o.weth.toLowerCase()?[$s(o.weth,s)]:o.unwrapOut&&!o.wrapIn&&t.toLowerCase()===o.weth.toLowerCase()?[_s(o.weth,s)]:null}function il(e){return{...e,resolve:async(t,n,s,o)=>{const r=rr(n,t.tokenIn,t.tokenOut,t.amountIn);if(r)return{venue:"native-wrap",amountOut:t.amountIn,amountOutMinimum:t.amountIn,calls:r};const i=await e.resolve(t,n,s,o);if(i)return i;const l=eo(n,t.tokenIn,t.tokenOut);if(!l)return null;const c=await e.resolve({...t,tokenIn:l.wrapIn?l.weth:t.tokenIn,tokenOut:l.unwrapOut?l.weth:t.tokenOut},n,s,o);return c?{...c,calls:[...l.wrapIn?[$s(l.weth,t.amountIn)]:[],...c.calls,...l.unwrapOut?[_s(l.weth,c.amountOutMinimum)]:[]]}:null}}}function ll(e){return{...e,resolve:async(t,n,s)=>{const o=rr(n,t.tokenIn,t.tokenOut,t.amountOut);if(o)return{venue:"native-wrap",amountIn:t.amountOut,amountInMax:t.amountOut,amountOut:t.amountOut,calls:o};const r=await e.resolve(t,n,s);if(r)return r;const i=eo(n,t.tokenIn,t.tokenOut);if(!i)return null;const l=await e.resolve({...t,tokenIn:i.wrapIn?i.weth:t.tokenIn,tokenOut:i.unwrapOut?i.weth:t.tokenOut},n,s);return l?{...l,calls:[...i.wrapIn?[$s(i.weth,l.amountInMax)]:[],...l.calls,...i.unwrapOut?[_s(i.weth,l.amountOut)]:[]]}:null}}}const ar=[100,500,3e3,1e4];function ps(e,t,n,s,o){const r=[];for(const i of n){const l=typeof i=="object"&&!Array.isArray(i)?i:void 0,c=l?l.tokens:Array.isArray(i)?i:[i];if(!c.length||c.length>2)throw new Error("A v3 route must have one or two intermediate tokens");const d=[e,...c,t];if(l&&(l.feeTiers.length!==d.length-1||l.feeTiers.some(m=>!m.length)))throw new Error("A v3 route needs fee tiers for every pool");if(new Set(d.map(m=>m.toLowerCase())).size!==d.length)continue;const p=(m,h)=>{if(m===d.length){r.push(o==="in"?h:ir(h));return}for(const x of l?.feeTiers[m-1]??s)p(m+1,T.concatHex([h,T.encodePacked(["uint24","address"],[x,d[m]])]))};p(1,d[0])}return[...new Set(r)]}function ir(e){const t=e.slice(2),n=[];for(let s=0;s<t.length;){const o=n.length%2===0?40:6;n.push(t.slice(s,s+o)),s+=o}return`0x${n.reverse().join("")}`}const cl=T.parseAbi(["function exactOutputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 amountOut, uint256 amountInMaximum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountIn)","function exactOutput((bytes path, address recipient, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),dl=T.parseAbi(["function exactOutputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountIn)","function exactOutput((bytes path, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),ul=1800;function lr(e){const{config:t,route:n,tokenIn:s,tokenOut:o,recipient:r,amountOut:i}=e,l=e.amountInMaximum,c=e.routerHasDeadline?dl:cl,d=e.routerHasDeadline?{deadline:BigInt(Math.floor(Date.now()/1e3)+ul)}:{},p=n.path?T.encodeFunctionData({abi:c,functionName:"exactOutput",args:[{path:n.path,recipient:r,...d,amountOut:i,amountInMaximum:l}]}):T.encodeFunctionData({abi:c,functionName:"exactOutputSingle",args:[{tokenIn:s,tokenOut:o,fee:n.fee,recipient:r,...d,amountOut:i,amountInMaximum:l,sqrtPriceLimitX96:0n}]});return{to:t.swapRouter,value:0n,data:p}}const pl=T.parseAbi(["function quoteExactInput(bytes path, uint256 amountIn) returns (uint256 amountOut, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate)","function quoteExactOutput(bytes path, uint256 amountOut) returns (uint256 amountIn, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate)"]);async function Qn(e,t,n,s,o){const r=f.getClientForChain(e),{result:i}=await r.simulateContract({address:t.quoterV2,abi:pl,functionName:o==="in"?"quoteExactInput":"quoteExactOutput",args:[n,s]}),[l,,,c]=i;if(l<=0n)throw new Error("No liquidity along this path.");return{amount:l,gasEstimate:c}}async function fl(e){const{tokenIn:t,tokenOut:n,amountIn:s,fee:o,chainId:r,config:i}=e;if(s<=0n)throw new Error("amountIn must be greater than 0");const l=(await f.getClientForChain(r).simulateContract({address:i.quoterV2,abi:v.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:s,fee:o,sqrtPriceLimitX96:0n}]})).result;if(l[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:l[0],sqrtPriceX96After:l[1],gasEstimate:l[3]}}async function cr(e){const t=e.feeTiers??ar,n=ps(e.tokenIn,e.tokenOut,e.hubs??[],t,"in"),s=await Promise.allSettled([...t.map(async r=>({...await fl({...e,fee:r}),fee:r})),...n.map(async r=>{const i=await Qn(e.chainId,e.config,r,e.amountIn,"in");return{amountOut:i.amount,sqrtPriceX96After:0n,gasEstimate:i.gasEstimate,fee:0,path:r}})]);let o=null;for(const r of s)r.status==="fulfilled"&&(!o||r.value.amountOut>o.amountOut)&&(o=r.value);if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}const ml=[{inputs:[{components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"amount",type:"uint256"},{name:"fee",type:"uint24"},{name:"sqrtPriceLimitX96",type:"uint160"}],name:"params",type:"tuple"}],name:"quoteExactOutputSingle",outputs:[{name:"amountIn",type:"uint256"},{name:"sqrtPriceX96After",type:"uint160"},{name:"initializedTicksCrossed",type:"uint32"},{name:"gasEstimate",type:"uint256"}],stateMutability:"nonpayable",type:"function"}];async function hl(e){const{tokenIn:t,tokenOut:n,amountOut:s,fee:o,chainId:r,config:i}=e;if(s<=0n)throw new Error("amountOut must be greater than 0");const l=(await f.getClientForChain(r).simulateContract({address:i.quoterV2,abi:ml,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:s,fee:o,sqrtPriceLimitX96:0n}]})).result;if(l[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:l[0],sqrtPriceX96After:l[1],gasEstimate:l[3]}}async function dr(e){const t=e.feeTiers??ar,n=ps(e.tokenIn,e.tokenOut,e.hubs??[],t,"out"),s=await Promise.allSettled([...t.map(async r=>({...await hl({...e,fee:r}),fee:r})),...n.map(async r=>{const i=await Qn(e.chainId,e.config,r,e.amountOut,"out");return{amountIn:i.amount,sqrtPriceX96After:0n,gasEstimate:i.gasEstimate,fee:0,path:r}})]);let o=null;for(const r of s)r.status==="fulfilled"&&(!o||r.value.amountIn<o.amountIn)&&(o=r.value);if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}function gl(e){return e.type==="swap"}const Gn=.02,xl=[1,8453,42161,10,137,43114,56],yl="https://api.1inch.dev/swap/v6.0";function to(e,t){return v.applySlippage(e,t)}function wl(e){const t=e?.baseUrl??yl;return{name:"1inch",chainIds:e?.chainIds??xl,resolve:async(n,s,o)=>{const r=n.maxSlippage??Gn,i=r*100,l=v.isNativeToken(n.tokenIn)?v.NATIVE_TOKEN_ADDRESS:n.tokenIn,c=v.isNativeToken(n.tokenOut)?v.NATIVE_TOKEN_ADDRESS:n.tokenOut,d=v.isNativeToken(n.tokenIn);try{const p=new URL(`${t}/${s}/swap`);p.searchParams.set("src",l),p.searchParams.set("dst",c),p.searchParams.set("amount",n.amountIn.toString()),p.searchParams.set("from",o),p.searchParams.set("slippage",i.toString()),p.searchParams.set("disableEstimate","true"),p.searchParams.set("allowPartialFill","false");const m={Accept:"application/json"};e?.apiKey&&(m.Authorization=`Bearer ${e.apiKey}`);const h=await fetch(p.toString(),{headers:m});if(!h.ok)throw new f.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${h.status} for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:`HTTP ${h.status}`});const x=await h.json();if(!x.dstAmount||!x.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const g=BigInt(x.dstAmount);if(g<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}`),null;const y=to(g,r),w=[];return x.tx.to&&!d&&w.push({to:n.tokenIn,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"approve",args:[x.tx.to,n.amountIn]})}),w.push({to:x.tx.to,value:BigInt(x.tx.value||"0"),data:x.tx.data}),{venue:"1inch",amountOut:g,amountOutMinimum:y,calls:w}}catch(p){if(p instanceof f.SpiceflowError)throw p;const m=p instanceof Error?p.message:String(p);throw new f.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${s}: ${m}`,{venue:"1inch",chainId:s,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:m})}}}}const ur=[4114,5115],no={name:"Satsuma",swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},pr={name:"Uniswap v3",swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x4200000000000000000000000000000000000006","0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]},fr={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[1],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2","0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"]},mr={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[42161],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x82aF49447D8a07e3bd95BD0d56f35241523fBab1","0xaf88d065e77c8cC2239327C5EDb3A432268e5831"]},bl={name:"Uniswap v3",swapRouter:"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45",quoterV2:"0x61fFE014bA17989E743c5F6cB21bF9697530B21e",chainIds:[137],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270","0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"]},Cl={name:"Uniswap v3",swapRouter:"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2",quoterV2:"0x78D78E420Da98ad378D7799bE8f4AF69033EB077",chainIds:[56],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c","0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d"]},vl={name:"Uniswap v3",swapRouter:"0xfe31f71c1b106eac32f1a19239c9a9a72ddfb900",quoterV2:"0x661e93cca42afacb172121ef892830ca3b70f08d",chainIds:[143],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A","0x754704Bc059F8C67012fEd69BC8A327a5aafb603"]},hr={name:"Uniswap v3",swapRouter:"0xcaf681a66d020601342297493863e78c959e5cb2",quoterV2:"0x33e885ed0ec9bf04ecfb19341582aadcb4c8a9e7",chainIds:[4663],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73","0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"]},gr={name:"SushiSwap",swapRouter:"0x1e406484F1F204b23cE84B9901C0171a738fd406",quoterV2:"0x3E290e5E01818002A0b672148BdC7514D861C7B3",chainIds:[4663],feeTiers:[100,500,3e3,1e4],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73","0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"],routerHasDeadline:!0},xr=T.parseAbi(["function exactInput((bytes path, address recipient, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),yr=T.parseAbi(["function exactInputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)","function exactInput((bytes path, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),kl=T.parseAbi(["function exactInput((bytes path, address recipient, uint256 deadline, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)"]),Sl=T.parseAbi(["function exactOutput((bytes path, address recipient, uint256 deadline, uint256 amountOut, uint256 amountInMaximum) params) payable returns (uint256 amountIn)"]),so=1800,wr=[1,50,100,200,2e3],oo={name:"Aerodrome",swapRouter:"0xcbBb8035cAc7D4B3Ca7aBb74cF7BdF900215Ce0D",quoterV2:"0x3d4C22254F86f64B7eC90ab8F7aeC1FBFD271c6C",chainIds:[8453],hubCurrencies:["0x4200000000000000000000000000000000000006","0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]};function ro(e){const t=e.name??"Aerodrome",n=e.chainIds??[8453],s=e.tickSpacings??wr;return{name:t,chainIds:n,resolve:async(o,r,i)=>{if(v.isNativeToken(o.tokenIn)||v.isNativeToken(o.tokenOut))return null;const l=o.maxSlippage??Gn,c=[...s.map(w=>T.encodePacked(["address","uint24","address"],[o.tokenIn,w,o.tokenOut])),...ps(o.tokenIn,o.tokenOut,e.hubCurrencies??[],s,"in")],d={quoterV2:e.quoterV2},p=await Promise.allSettled(c.map(async w=>({path:w,amountOut:(await Qn(r,d,w,o.amountIn,"in")).amount})));let m=null;for(const w of p)w.status==="fulfilled"&&(!m||w.value.amountOut>m.amountOut)&&(m=w.value);if(!m)return console.warn(`[AerodromeVenue] No viable route for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${r}.`),null;const h=to(m.amountOut,l),x=BigInt(Math.floor(Date.now()/1e3)+so),g=T.encodeFunctionData({abi:kl,functionName:"exactInput",args:[{path:m.path,recipient:i,deadline:x,amountIn:o.amountIn,amountOutMinimum:h}]}),y=[{to:o.tokenIn,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"approve",args:[e.swapRouter,o.amountIn]})},{to:e.swapRouter,value:0n,data:g}];return{venue:t,amountOut:m.amountOut,amountOutMinimum:h,calls:y}}}}function br(e){const t=e.name??"Aerodrome",n=e.chainIds??[8453],s=e.tickSpacings??wr;return{name:t,chainIds:n,resolve:async(o,r,i)=>{if(v.isNativeToken(o.tokenIn)||v.isNativeToken(o.tokenOut))return null;const l=o.maxSlippage??Gn,c=[...s.map(y=>T.encodePacked(["address","uint24","address"],[o.tokenOut,y,o.tokenIn])),...ps(o.tokenIn,o.tokenOut,e.hubCurrencies??[],s,"out")],d={quoterV2:e.quoterV2},p=await Promise.allSettled(c.map(async y=>({path:y,amountIn:(await Qn(r,d,y,o.amountOut,"out")).amount})));let m=null;for(const y of p)y.status==="fulfilled"&&(!m||y.value.amountIn<m.amountIn)&&(m=y.value);if(!m)return console.warn(`[AerodromeExactOutputVenue] No viable route for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${r}.`),null;const h=BigInt(Math.round(l*1e4)),x=m.amountIn+m.amountIn*h/10000n,g=BigInt(Math.floor(Date.now()/1e3)+so);return{venue:t,amountIn:m.amountIn,amountInMax:x,amountOut:o.amountOut,calls:[{to:e.swapRouter,value:0n,data:T.encodeFunctionData({abi:Sl,functionName:"exactOutput",args:[{path:m.path,recipient:i,deadline:g,amountOut:o.amountOut,amountInMaximum:x}]})}]}}}}function Yn(e){const t=e.name??"Uniswap v3",n=e.chainIds??ur;return{name:t,chainIds:n,resolve:async(s,o,r,i)=>{if(v.isNativeToken(s.tokenIn)||v.isNativeToken(s.tokenOut))return null;const l=s.maxSlippage??Gn;let c;try{let g;if(i){if(i.venue!==t)return null;const y=i.calls.find(C=>C.to.toLowerCase()===e.swapRouter.toLowerCase());if(!y)return null;const w=T.decodeFunctionData({abi:e.routerHasDeadline?yr:[...xr,...v.uniV3SwapRouterAbi],data:y.data});if(w.functionName==="exactInput"){const{path:C}=w.args[0];if(C.slice(0,42).toLowerCase()!==s.tokenIn.toLowerCase()||`0x${C.slice(-40)}`.toLowerCase()!==s.tokenOut.toLowerCase())return null;g={path:C,fee:0}}else if(w.functionName==="exactInputSingle"){const{tokenIn:C,tokenOut:b,fee:S}=w.args[0];if(C.toLowerCase()!==s.tokenIn.toLowerCase()||b.toLowerCase()!==s.tokenOut.toLowerCase())return null;g={fee:S}}else return null}c=g?.path?{...g,amountOut:(await Qn(o,e,g.path,s.amountIn,"in")).amount}:await cr({tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn,chainId:o,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:g?[g.fee]:e.feeTiers,hubs:g?[]:[...e.hubCurrencies??[],...e.hubPaths??[]]})}catch{return console.warn(`[UniV3Venue] No viable route for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}.`),null}const d=to(c.amountOut,l),p=e.routerHasDeadline?{deadline:BigInt(Math.floor(Date.now()/1e3)+so)}:{},m=e.routerHasDeadline?yr:c.path?xr:v.uniV3SwapRouterAbi,h=c.path?T.encodeFunctionData({abi:m,functionName:"exactInput",args:[{path:c.path,recipient:r,...p,amountIn:s.amountIn,amountOutMinimum:d}]}):T.encodeFunctionData({abi:m,functionName:"exactInputSingle",args:[{tokenIn:s.tokenIn,tokenOut:s.tokenOut,fee:c.fee,recipient:r,...p,amountIn:s.amountIn,amountOutMinimum:d,sqrtPriceLimitX96:0n}]}),x=[{to:s.tokenIn,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"approve",args:[e.swapRouter,s.amountIn]})},{to:e.swapRouter,value:0n,data:h}];return{venue:t,amountOut:c.amountOut,amountOutMinimum:d,calls:x}}}}function ao(e){const t=e.name??"Uniswap v3",n=e.chainIds??ur;return{name:t,chainIds:n,resolve:async(s,o,r)=>{if(v.isNativeToken(s.tokenIn)||v.isNativeToken(s.tokenOut))return null;const i=s.maxSlippage??Gn;let l;try{l=await dr({tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountOut:s.amountOut,chainId:o,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers,hubs:[...e.hubCurrencies??[],...e.hubPaths??[]]})}catch{return null}const c=BigInt(Math.round(i*1e4)),d=l.amountIn+l.amountIn*c/10000n;return{venue:t,amountIn:l.amountIn,amountInMax:d,amountOut:s.amountOut,calls:[lr({config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},routerHasDeadline:e.routerHasDeadline,route:l,tokenIn:s.tokenIn,tokenOut:s.tokenOut,recipient:r,amountOut:s.amountOut,amountInMaximum:d})]}}}}function Cr(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(Yn(e.satsuma)),e?.aerodrome!==!1&&t.push(ro(e?.aerodrome??oo)),t.push(wl(e?.oneInch));const n=t.map(il);function s(i){return n.find(l=>l.chainIds.includes(i))}async function o(i,l,c,d){const p=n.filter(g=>g.chainIds.includes(l));if(p.length===0)throw new f.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${l}. Cannot resolve swap ${i.tokenIn} \u2192 ${i.tokenOut}.`,{chainId:l,tokenIn:i.tokenIn,tokenOut:i.tokenOut,amountIn:i.amountIn.toString()});const m=await Promise.allSettled(p.map(g=>g.resolve(i,l,c,d)));let h=null;for(const g of m)d&&g.status==="fulfilled"&&g.value&&(g.value.venue!==d.venue||g.value.calls.length!==d.calls.length||g.value.calls.some((y,w)=>y.to.toLowerCase()!==d.calls[w].to.toLowerCase()||y.data.slice(0,10)!==d.calls[w].data.slice(0,10)))||g.status==="fulfilled"&&g.value&&(!h||g.value.amountOut>h.amountOut)&&(h=g.value);if(h)return h;const x=m.find(g=>g.status==="rejected");if(x)throw x.reason;return null}async function r(i,l,c){const d=[],p=[];for(const m of i){if(!gl(m)){d.push(m);continue}const h=await o(m,l,c);if(!h)throw new f.SpiceflowError("NO_LIQUIDITY",`No venue returned a quote for ${m.tokenIn} \u2192 ${m.tokenOut} on chain ${l}.`,{chainId:l,tokenIn:m.tokenIn,tokenOut:m.tokenOut,amountIn:m.amountIn.toString()});d.push(...h.calls),p.push(h)}return{calls:d,resolvedSwaps:p}}return{resolveSwapIntents:r,resolveSwap:o,getVenueForChain:s,venues:t}}const on="0x0000000000000000000000000000000000000000",io=[{fee:100,tickSpacing:1},{fee:500,tickSpacing:10},{fee:3e3,tickSpacing:60},{fee:1e4,tickSpacing:200}],vr=on,kr=.02,Il=1800,Sr={name:"Uniswap v4",quoter:"0x0d5e0f971ed27fbff6c2837bf31316121532048d",universalRouter:"0x6ff5693b99212da76ad316178a184ab56d299b43",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",chainIds:[8453],hubCurrencies:["0x4200000000000000000000000000000000000006",on,"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"]},Ir={name:"Uniswap v4",quoter:"0x8dc178efb8111bb0973dd9d722ebeff267c98f94",universalRouter:"0x8876789976decbfcbbbe364623c63652db8c0904",permit2:"0x000000000022d473030f116ddee9f6b43ac78ba3",routerHasHopPrice:!0,chainIds:[4663],hubCurrencies:["0x0bd7d308f8e1639fab988df18a8011f41eacad73",on,"0x5fc5360D0400a0Fd4f2af552ADD042D716F1d168"]},Ar=T.parseAbi(["struct PoolKey { address currency0; address currency1; uint24 fee; int24 tickSpacing; address hooks; }","struct PathKey { address intermediateCurrency; uint24 fee; int24 tickSpacing; address hooks; bytes hookData; }","struct QuoteExactSingleParams { PoolKey poolKey; bool zeroForOne; uint128 exactAmount; bytes hookData; }","struct QuoteExactParams { address exactCurrency; PathKey[] path; uint128 exactAmount; }","function quoteExactInputSingle(QuoteExactSingleParams params) returns (uint256 amountOut, uint256 gasEstimate)","function quoteExactInput(QuoteExactParams params) returns (uint256 amountOut, uint256 gasEstimate)","function quoteExactOutputSingle(QuoteExactSingleParams params) returns (uint256 amountIn, uint256 gasEstimate)","function quoteExactOutput(QuoteExactParams params) returns (uint256 amountIn, uint256 gasEstimate)"]),Al=T.parseAbi(["function approve(address token, address spender, uint160 amount, uint48 expiration)"]),El=T.parseAbi(["function execute(bytes commands, bytes[] inputs, uint256 deadline) payable"]),Er="0x10",Fl="04",Tl="06",jl="07",Bl="08",Rl="09",fs="0c",ms="0e",Dl=[{name:"currency0",type:"address"},{name:"currency1",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"}],Ol=[{name:"intermediateCurrency",type:"address"},{name:"fee",type:"uint24"},{name:"tickSpacing",type:"int24"},{name:"hooks",type:"address"},{name:"hookData",type:"bytes"}],cn=(e,t)=>e.toLowerCase()===t.toLowerCase();function hs(e){return v.isNativeToken(e)?on:e}function Nl(e,t){return e.toLowerCase()<t.toLowerCase()?[e,t]:[t,e]}function Fr(e,t,n,s,o){const r=[],[i,l]=Nl(e,t);for(const{fee:d,tickSpacing:p}of io)r.push({kind:"single",poolKey:{currency0:i,currency1:l,fee:d,tickSpacing:p,hooks:vr},zeroForOne:cn(e,i)});const c=(d,p)=>!!o&&(cn(d,on)&&cn(p,o)||cn(d,o)&&cn(p,on));for(const d of n)if(!(cn(d,e)||cn(d,t))&&!(c(d,e)||c(d,t)))for(const p of io)for(const m of io){const h=(x,g)=>({intermediateCurrency:x,fee:g.fee,tickSpacing:g.tickSpacing,hooks:vr,hookData:"0x"});r.push({kind:"multi",path:s==="in"?[h(d,p),h(t,m)]:[h(e,p),h(d,m)]})}return r}async function Tr(e,t,n,s,o,r){const i=f.getClientForChain(e),l=(await Promise.allSettled(n.map(async c=>{const{result:d}=c.kind==="single"?await i.simulateContract({address:t.quoter,abi:Ar,functionName:r==="in"?"quoteExactInputSingle":"quoteExactOutputSingle",args:[{poolKey:c.poolKey,zeroForOne:c.zeroForOne,exactAmount:o,hookData:"0x"}]}):await i.simulateContract({address:t.quoter,abi:Ar,functionName:r==="in"?"quoteExactInput":"quoteExactOutput",args:[{exactCurrency:s,path:c.path,exactAmount:o}]}),p=d[0];if(p<=0n)throw new Error("zero quote");return{candidate:c,amount:p}}))).filter(c=>c.status==="fulfilled").map(c=>c.value);return l.length===0?null:(l.sort((c,d)=>c.amount<d.amount?-1:c.amount>d.amount?1:0),r==="in"?l[l.length-1]:l[0])}function jr(e){const{candidate:t,direction:n,currencyIn:s,currencyOut:o,recipient:r,exactAmount:i,limitAmount:l,deadline:c,routerHasHopPrice:d,sweepNativeTo:p}=e;let m,h;t.kind==="single"?(m=n==="in"?`0x${Tl}${fs}${ms}`:`0x${Bl}${fs}${ms}`,h=T.encodeAbiParameters([{type:"tuple",components:[{name:"poolKey",type:"tuple",components:Dl},{name:"zeroForOne",type:"bool"},{name:n==="in"?"amountIn":"amountOut",type:"uint128"},{name:n==="in"?"amountOutMinimum":"amountInMaximum",type:"uint128"},...d?[{name:"minHopPriceX36",type:"uint256"}]:[],{name:"hookData",type:"bytes"}]}],[{poolKey:t.poolKey,zeroForOne:t.zeroForOne,[n==="in"?"amountIn":"amountOut"]:i,[n==="in"?"amountOutMinimum":"amountInMaximum"]:l,...d?{minHopPriceX36:0n}:{},hookData:"0x"}])):(m=n==="in"?`0x${jl}${fs}${ms}`:`0x${Rl}${fs}${ms}`,h=T.encodeAbiParameters([{type:"tuple",components:[{name:n==="in"?"currencyIn":"currencyOut",type:"address"},{name:"path",type:"tuple[]",components:Ol},...d?[{name:"minHopPriceX36",type:"uint256[]"}]:[],{name:n==="in"?"amountIn":"amountOut",type:"uint128"},{name:n==="in"?"amountOutMinimum":"amountInMaximum",type:"uint128"}]}],[{[n==="in"?"currencyIn":"currencyOut"]:n==="in"?s:o,path:t.path,...d?{minHopPriceX36:[]}:{},[n==="in"?"amountIn":"amountOut"]:i,[n==="in"?"amountOutMinimum":"amountInMaximum"]:l}]));const x=T.encodeAbiParameters([{type:"address"},{type:"uint256"}],[s,n==="in"?i:l]),g=T.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"}],[o,r,0n]),y=T.encodeAbiParameters([{type:"bytes"},{type:"bytes[]"}],[m,[h,x,g]]),w=p?`${Er}${Fl}`:Er,C=p?[y,T.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"}],[on,p,0n])]:[y];return T.encodeFunctionData({abi:El,functionName:"execute",args:[w,C,c]})}function Br(){return BigInt(Math.floor(Date.now()/1e3)+Il)}function Rr(e,t,n,s){return{to:e.permit2,value:0n,data:T.encodeFunctionData({abi:Al,functionName:"approve",args:[t,e.universalRouter,n,Number(s)]})}}function Dr(e){const t=e.name??"Uniswap v4",n=e.v3?Yn({...e.v3,chainIds:e.chainIds}):null;return{name:t,chainIds:e.chainIds,resolve:async(s,o,r)=>{const i=s.maxSlippage??kr,l=hs(s.tokenIn),c=hs(s.tokenOut),d=v.isNativeToken(s.tokenIn),p=e.hubCurrencies??[on];let m=null;if(!cn(l,c)&&s.amountIn>0n){const h=await Tr(o,e,Fr(l,c,p,"in",Js(o)),l,s.amountIn,"in").catch(()=>null);if(h){const x=v.applySlippage(h.amount,i),g=Br(),y=[];d||(y.push({to:s.tokenIn,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"approve",args:[e.permit2,s.amountIn]})}),y.push(Rr(e,s.tokenIn,s.amountIn,g))),y.push({to:e.universalRouter,value:d?s.amountIn:0n,data:jr({candidate:h.candidate,direction:"in",currencyIn:l,currencyOut:c,recipient:r,exactAmount:s.amountIn,limitAmount:x,deadline:g,routerHasHopPrice:e.routerHasHopPrice})}),m={venue:t,amountOut:h.amount,amountOutMinimum:x,calls:y}}}return!m&&n?n.resolve(s,o,r):m}}}function Or(e){const t=e.name??"Uniswap v4";return{name:t,chainIds:e.chainIds,resolve:async(n,s,o)=>{const r=v.isNativeToken(n.tokenIn),i=hs(n.tokenIn),l=hs(n.tokenOut);if(cn(i,l)||n.amountOut<=0n)return null;const c=n.maxSlippage??kr,d=e.hubCurrencies??[on],p=await Tr(s,e,Fr(i,l,d,"out",Js(s)),l,n.amountOut,"out").catch(()=>null);if(!p)return null;const m=BigInt(Math.round(c*1e4)),h=p.amount+p.amount*m/10000n,x=Br();return{venue:t,amountIn:p.amount,amountInMax:h,amountOut:n.amountOut,calls:[...r?[]:[Rr(e,n.tokenIn,h,x)],{to:e.universalRouter,value:r?h:0n,data:jr({candidate:p.candidate,direction:"out",currencyIn:i,currencyOut:l,recipient:o,exactAmount:n.amountOut,limitAmount:h,deadline:x,routerHasHopPrice:e.routerHasHopPrice,sweepNativeTo:r?o:void 0})}]}}}}const lo=[{...no,protocol:"uniswap-v3",chainId:4114},{...no,protocol:"uniswap-v3",chainId:5115},{...pr,protocol:"uniswap-v3",chainId:8453},{...fr,protocol:"uniswap-v3",chainId:1},{...mr,protocol:"uniswap-v3",chainId:42161},{...bl,protocol:"uniswap-v3",chainId:137},{...Cl,protocol:"uniswap-v3",chainId:56},{...vl,protocol:"uniswap-v3",chainId:143},{...hr,protocol:"uniswap-v3",chainId:4663},{...gr,protocol:"uniswap-v3",chainId:4663},{...Sr,protocol:"uniswap-v4",chainId:8453},{...Ir,protocol:"uniswap-v4",chainId:4663},{...oo,protocol:"aerodrome-slipstream",chainId:8453}];function Bn(e){const t=e?.includeDefaults===!1?e.venues??[]:[...lo,...e?.venues??[]],n=[],s=[];for(const o of t){const r=[o.chainId];switch(o.protocol){case"uniswap-v3":{const i={...o,chainIds:r};n.push(Yn(i)),s.push(ao(i));break}case"uniswap-v4":{const i={...o,chainIds:r};n.push(Dr(i)),s.push(Or(i));break}case"aerodrome-slipstream":{const i={...o,chainIds:r};n.push(ro(i)),s.push(br(i));break}default:{const i=o;throw new f.SpiceflowError("INVALID_PARAMS",`Unsupported liquidity venue protocol: ${i.protocol}`,{protocol:i.protocol})}}}return{input:n,output:s}}const co=new Set(["WBTC","CBTC"]),Nr=new Set(["btc","wbtc","wcbtc","cbtc"]);function Mr(e,t){return!e||!t?!1:e===t?!0:co.has(e)&&co.has(t)}function dn(e){const[t,n,s]=e.split(":");if(t!=="evm"||!n||!s)return null;const o=Number(n);if(!Number.isFinite(o))return null;const r=s.startsWith("0x")?s.toLowerCase():`0x${s.toLowerCase()}`;return{chainId:o,address:r}}function gs(e){return(e??"").trim().replace(/^test\s+/i,"").replace(/^spice/i,"").toLowerCase().replace(/[^a-z0-9]/g,"")}function Ml(e){return new Set([e.receiptTokenName,e.displaySymbol,e.symbol,e.displayName,e.name].map(gs).filter(Boolean))}function Pl(e,t){const n=Ml(e),s=[t.symbol,t.name,t.equivalenceGroup].map(gs);if(s.some(i=>i&&n.has(i)))return!0;const o=[...n].some(i=>Nr.has(i)),r=s.some(i=>Nr.has(i))||co.has(t.equivalenceGroup??"");return o&&r}function Pr(e,t,n){const s=new Set(t.map(gs).filter(Boolean)),o=r=>{if(n&&f.addressesEqual(r.address,n))return 0;const i=[r.symbol,r.name,r.equivalenceGroup].map(gs).findIndex(l=>l&&s.has(l));return i===-1?4:i+1};return[...e].sort((r,i)=>{const l=o(r)-o(i);return l!==0?l:r.address.toLowerCase().localeCompare(i.address.toLowerCase())})}function Rn(e,t){const n=e.chainTokens?Object.keys(e.chainTokens):[],s=[];for(const o of n){const r=dn(o);if(!r||r.chainId!==t)continue;const i=r.address,l=v.isNativeToken(i)?f.getChainConfig(t)?.nativeCurrency:void 0,c=v.getTokenByAddress(i,t)??(l?{...l}:void 0);c&&(!uo(e,i,t)&&!(e.isUniversal&&Pl(e,c))||s.some(d=>f.addressesEqual(d,i))||s.push(i))}return Pr(s.map(o=>{const r=v.getTokenByAddress(o,t);return{address:o,symbol:r?.symbol,name:r?.name,equivalenceGroup:r?.equivalenceGroup}}),[e.receiptTokenName,e.displaySymbol,e.symbol,e.displayName,e.name],e.chainId===t&&!e.isUniversal?e.address:void 0).map(o=>o.address)}function uo(e,t,n){return e.chainId===n&&f.addressesEqual(e.address,t)?!0:Kn(e.address,e.chainId,t,n)}async function Ul(e,t){const n=f.getClientForChain(e),s=v.getEscrowContractAddress(e);return v.isNativeToken(t)?n.getBalance({address:s}):await n.readContract({address:t,abi:T.erc20Abi,functionName:"balanceOf",args:[s]})}function po(e,t,n){const s=v.getTokensForChain(n),o=s.find(i=>f.addressesEqual(i.address,e));if(o&&(t===n||!v.isNativeToken(e)))return o;const r=v.getTokenByAddress(e,t);if(r)return Pr(s.filter(i=>Mr(i.equivalenceGroup,r.equivalenceGroup)),[r.symbol,r.name,r.equivalenceGroup])[0]}function xs(e){return e.equivalenceGroup==="USDC"&&e.symbol.toUpperCase()!=="USDT"}function Ur(e){const t=v.getEscrowContract(e);if(!t||t===v.ZERO_ADDRESS)return;const n=v.getTokensForChain(e).filter(xs);return n.find(s=>s.symbol.toUpperCase()==="USDC")??n[0]}function fo(e,t){if(e.chainId===t)return null;const n=v.getEscrowContract(e.chainId),s=v.getEscrowContract(t);if(!n||n===v.ZERO_ADDRESS||!s||s===v.ZERO_ADDRESS)return null;const o=!e.isNative&&!v.isNativeToken(e.address)?v.getTokenByAddress(e.address,e.chainId):void 0,r=o&&xs(o)?po(e.address,e.chainId,t):void 0,i=r?o:Ur(e.chainId),l=r??Ur(t);if(!i||!l)return null;const c=d=>({address:d.address,symbol:d.symbol,decimals:d.decimals,chainId:d.chainId});return{source:c(i),destination:c(l)}}function Wl(e,t){return!!fo(e,t)}function Jt(e,t){if(e.chainId===t)return e.address;const n=po(e.address,e.chainId,t);return n?n.address:null}async function xn(e,t,n,s){const o=v.getTokenByAddress(t,n);return o?o.decimals:e?.chainId===n&&f.addressesEqual(e.address,t)&&!e.isUniversal?e.decimals:s?.chainId===n&&f.addressesEqual(s.address,t)?s.decimals:f.getTokenDecimals(n,t)}async function Wr(e,t,n={}){const s=Jt(e,t),o=Rn(e,t);if(o.length===0)return s;if(o.length===1)return o[0];const r=n.requiredAmount??0n,i=l=>{const c=o.map(d=>({candidate:d,balance:l.get(v.isNativeToken(d)?"native":d.toLowerCase())??0n})).filter(d=>d.balance>0n).sort((d,p)=>d.balance===p.balance?0:d.balance>p.balance?-1:1);return c.length===0?null:((r>0n?c.find(d=>d.balance>=r):c[0])??c[0]).candidate};try{const l=await Promise.all(o.map(async p=>({key:v.isNativeToken(p)?"native":p.toLowerCase(),value:await Ul(t,p)}))),c=new Map(l.map(({key:p,value:m})=>[p,m])),d=i(c);if(d)return d}catch{}return s}function Kn(e,t,n,s){const o=v.getTokenByAddress(e,t),r=v.getTokenByAddress(n,s);return o&&r?Mr(o.equivalenceGroup,r.equivalenceGroup):v.areEquivalent(e,n)}function ys(e,t){return Kn(e.address,e.chainId,t.address,t.chainId)}const Lr=.01;function zr(e,t=!1){const n=Number.isFinite(e.balanceUsd)&&e.balanceUsd>0;return e.isDiscovered?n&&e.balanceUsd>=Lr:!t||!n||e.balanceUsd>=Lr}function ws(e,t=!1){return!!e&&e._source==="wallet"&&(e.location==="external"||e._fundingWallet==="external"||!e.location&&!e._fundingWallet&&t)}function Ge(e){return e.positionId??`${e.owner?.toLowerCase()??""}:${e.location??e._source??""}:${e.chainId}:${e.receiptTokenId??v.normalizeNativeTokenAddress(e.address).toLowerCase()}`}function qr(e,t){if(!t?.length||e.symbol!==void 0&&f.isAssetAllowed({...e,symbol:e.symbol},t))return!0;const n=s=>t.some(o=>f.addressesEqual(v.normalizeNativeTokenAddress(o),v.normalizeNativeTokenAddress(s)));return n(e.address)||Object.keys(e.chainTokens??{}).some(s=>{const o=dn(s);return o?n(o.address):!1})}function kn(e,t,n,s,o,r){const i=(y,w=!1)=>({eligible:!1,reason:y,policyExcluded:w}),l=e._source==="wallet"||e.location==="external"||e.location==="embedded",c=t==="spend-source"&&l&&!!s&&e.chainId===s.chainId&&f.addressesEqual(v.normalizeNativeTokenAddress(e.address),v.normalizeNativeTokenAddress(s.address));if(n.isWhitelistGateActive||!c&&!f.isAssetAllowed(e,n.allowedTokens))return i("Asset excluded by client policy",!0);if(t!=="withdraw-destination"&&!c&&!zr(e))return i("Asset is unpriced or below the minimum value",!0);if(t==="holding")return{eligible:!0,reason:null};if(e.balanceError)return i(e.balanceError);if(!c&&!qr(e,o))return i("Asset excluded by action policy",!0);const d=new Set(s?[s.chainId]:[]);e._source!=="spice"&&e.location!=="rollup"&&d.add(e.chainId);for(const y of d)if(!f.getRpcUrlForChain(y,n.rpcOverrides)?.trim())return i(`Configure SpiceFlowProvider rpcOverrides[${y}] before using this asset.`);if(r?.requiresEscrow){const y=v.getTokenByAddress(e.address,e.chainId);if(!y||!xs(y))return i("This asset has no supported escrow mapping")}if(!s)return{eligible:!0,reason:null};const p=n.liquidityVenues?.includeDefaults===!1?n.liquidityVenues.venues??[]:[...lo,...n.liquidityVenues?.venues??[]],m=y=>p.some(w=>w.chainId===y),h=l&&e.chainId!==s.chainId,x=h?fo(e,s.chainId):null;if(h&&!x)return i("No supported source route");if(x&&!f.addressesEqual(v.normalizeNativeTokenAddress(e.address),v.normalizeNativeTokenAddress(x.source.address))&&!m(e.chainId))return i("No conversion venue configured on the source chain");const g=x?.destination.address??Jt(e,s.chainId);return t==="withdraw-destination"?(e.chainTokens||e.receiptTokenId?Rn(e,s.chainId):g?[g]:[]).some(y=>f.addressesEqual(v.normalizeNativeTokenAddress(y),v.normalizeNativeTokenAddress(s.address)))?{eligible:!0,reason:null}:i("No supported withdrawal mapping"):g&&f.addressesEqual(v.normalizeNativeTokenAddress(g),v.normalizeNativeTokenAddress(s.address))?{eligible:!0,reason:null}:!g&&!Wl(e,s.chainId)?i("No supported destination route"):m(s.chainId)?{eligible:!0,reason:null}:i("No conversion venue configured on the destination chain")}function bs(){const e=u.useContext(f.SpiceFlowProviderContext),[t]=u.useState(f.createInventoryStore);return e?.inventory??t}function mo(e,t,n,s,o){const r=bs(),i=o??r,l=u.useMemo(()=>i.entry(e),[i,e]),[,c]=u.useState(0);u.useEffect(()=>{if(n)return l.subscribe(()=>c(p=>p+1),t,s)},[l,n,t,s]);const d=u.useCallback(()=>l.refresh(),[l]);return{...n?l.snapshot():f.EMPTY_INVENTORY,refresh:d}}var Hr="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAA6lBMVEXc3NzX/v/1hRvZ2dnd3dzb29va7fpMaXHa1tPc3N35/v/c3Nzc3NzCrp/c3Nza2tp1PRbLsJzlr33uhSj0kTHcnWnUva7jdhuNX0B6Qhrsk0LOxMCFVDJ+RyGhfGTkeiGYVSHjdx3lij7khDPEsaPfoW/jgjLQuKXmgzB2PRb2hRvldhvjdRv4hhvpeRtwORb/ihryghvabhnsehrUaRjLXxXtfRt7PxXwexricRbRYhURFBeSTBe0XBrEZxmDRxiiVRrlgCbfzMAvLCmrWBgbMEh9UjBbOBe2pJi9byekk4nkgDHkgDJLNB7jlKArAAAAKXRSTlMzJv0TNSYsADUxKBwK/QUZ/URTx650/vqJ5YpMosxj3ezwkqa6/q3KrihQ98kAAAAJcEhZcwAACxMAAAsTAQCanBgAAATxSURBVHjapVeJcuI4EJXBdiRuw4JzDAFyzeIT22BsNgTIJNnM7Pz/90xLsmV5ChJm6SqqZOR+7teXWujsgLSqdU0jBCFCNK1ebR16D+39t1HXiKqqGDHBsCRavXEsQKutIVWln0aZ0BX8o7VbRwC06gS+LHQLIWAJqbc+A6iC+h7t3BCVVD8EaGgqOqSemaFqjcMA8PkP1RnEb0bIAPXD1peNqO8H0NQj1LkR2j6Ao/XLCOh/6JcQkOD/B/oUoV4GqGb6+HNdnCFUZYBG9nmsE/whBsZE5y9g0pAAcgcQQ1V0fAgDNnRFNQiW3cAA2lwfI3wxvunqyl4z4OOK3r0ZX2CUIbRzgFZOoHY9nW7NXt9QdFTGgCddMfq9cDudXteyLdLKAPII4NqXZcffzIPJQx8zDCFgev9hksw3fmf5pYalSCDJAGAw7Uz9zkuU2CNKRQiYPrIT76Xjwws5B/BjiwG0hQHAgIr/GHpeYvb+EtIzI88LH32+fy1MaDMAKOGCAUdYPnmmE82ERI7pPS25fsEB0UCgs4ZwVO08AwB5sT0zrmQSm7b94mff7yzPa8LBDQAQSSwo5DRsKxO7MF+mwNyIBAPwjHEhIQCNgOsHwnwmF4aeWwAcUEMO97DgABAvkUv13WgrqXeWQ7moGqiqFtkivJjTCADBDWTzZR9SE6pIquOSF6msGYdgPS0BSD4EJ6CikUB+DKcd2QkRB4hkF3SmQyyqHioKaViicF4AQEp7DqfgRJDCSwFxLlPQ5GMAAHJ9n4bRyQEcGkZ/HwColwBYHH3fXz6uHc+xnZgCxLDwnPXj0mcgUhRpOZSblTEE9c32ybMi27ELAHiILO9puwGIoXG48YEJ43UYzGYumG/LADbQcGezIFyPjRr+7aCREfTezLUqFtMB4QB87cSw4c56uqyPSz4A/S6UDuikqzkTmwLYfL1K4aFiVbolBCKHEWHlclahyRvMF4vFarWgOm5KV4vFnIbEqswuFUmD5oF0olAGFZ7+88VqvV05FMBZbderxZwXRqXEgSaSfCTp3cDiAIETvr2+riP64K1fX99ClhMA4AIH+YAqFVPGgGnFu+9v44Quk/Hb913suXyjzAGKSS7nnAEtgBg6WeAxLIjrLM56A+NQKueioVAGruW67OdWrCCwYqoS01XgZmLJHGhDkVqa3oXeSyUESaktvBrBJ5WU/sd3IxFI3tKKpkrwCDIQcjCkUfPAnIAJ+NSjcQ1tuuuNMCk11TORCVh5SEyWdXP2dmzxpk4TEzDnbMtM/lakligfLADQj3gOOysASNPd5l+QzS5NAWCVbUV9RTBol442cIIxsVnlwPthurtv/sOkeb9LQ2oS25qIcs6PNtmNvch0HBOKN/15P3h+5wDvz4P7/1IocNhzop7swvLxTjMpMm0viSa9m6/Pg+cf35j8gOXXm94kSjzbjIo8Esd7cbxCIBNzdNs3dAXdDQbN9ybIe3MwuEOKbvRvR2YigigNGNKMh28vu0ihswGp9ZuDJpNBs0+HFjjuUffyFpcnvfKQhbgym06wcnXHAe6umNWYjSlKkcXlMa8YpIrEIldMCMHyrLNvzDs0aBImxwyap4+6pw/bp4/71A/opAvH6Vee0y9dn1z70OfXvuziudcMSKdjLp786quecPWVL99Zfqt/ePkuX/8Jv/43Dl3/fwH9bPJ09nq7MQAAAABJRU5ErkJggg==",Ll="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAQlBMVEVMaXGGl/+Elf+HmP+Hmf+Hl/+Gl/+Flv+Glv+Gl/+Gl/+Gl/////+On/+Akv/4+f/v8f/i5v+9x//S2P+tuP+erP+W3PvUAAAAC3RSTlMArBlx7Isy/vvOXbb4wDYAAAAJcEhZcwAACxMAAAsTAQCanBgAAALuSURBVHjarVfbtqsgDOxu0UBpkOv//+pJRC0i2HZ58uTeqzOEyYXkduvY/Tn8KSEBpFB/w3O8/WTjoCSS6dn4S6rha477QxFGS0nHM56ckJL/ox73b+CDQAQJujKiQxTDR4qH4LN109gP8Ti/uyI46K4BUagTLZ4Cz+CZAsWzhx/oeP3RyImhjf/7ePzmxF8Hr7+zNsP3eL7GkWH4Bc8MlQ7P3/DMsIvFKHRLPzBsTWVBizIfVNMBg9H7mLQxTRdUkb9tfJxebNZjywuJW1bf2xcw4WXtzDF5bVqXuJ9HwETHNnPYeHRii0THgcwQyBxTBDQ9Fx7dEBr0TOCDYyeS6aigsFsCQIFgBh9YiVgxQA7EqM9KiCiS95nh5WsGPZ4k8ZZFRqfoY4shy9i8AaExxRgTMgcApuSODPMdRtn02wc7Z9HkPMsPa1ZVOsiRygga4udfZ5vTKKx/7GIBVFJHCUy0r705DNu3LQ9kEQ6NxMTXwWzhUTD7xlJr2MLvrZCBVazy2OD0iaC4BGh1k4cSLOSbbIuujKW4wT76aYefrGswuBJSEoBeUnaFk7nQcKEIJZRXMPsfM95O3p3KKAoRa/cJTh0pHKMybSqyiO8wMsG0wzODi7UK9u0Ah7FIJAj1+UyQcl4Gqi2uax+L/siJVKQyi+j251sbMoHTZrUqlctiojDGRX27WpivYNtdi4upKme0c/gXBmdzY7ZoOi/cWDeU7MJy+oKn3hzbT9/cFKt6pmKe9udnCoTeG103VW7EjrGZJMOD863GNzfVQ0EDP6aJUH61wBRHGZa23npYDDpuh8EnpPBRS6UUQOg9r8enzaDdmhmsPkH/da3bokkr/i0dwMmYU7lg0pRrwiVzNrW+n/dKhVzVVIbGnE9Jj86IA8glk87h+xGnGrJyzXwYNvdD1uUx7/qgeX3UvT5sXx/3ry8c11ee60vX9bXvvXjWfsC3i+d79YV19+WPH1bf/7B8Lxy8/isBINTp+v8Ph4CTcAywkiYAAAAASUVORK5CYII=",zl="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAPFBMVEVMaXGZhueZh+eYhuWXheWYh+eYhuaXheCYhuaah+j//fmhjvOSf+Sdi+q8sOzNxO/m4fT08fapmuja0/Jb/wGxAAAACnRSTlMArEz/IYtsA87sGIEBYwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAmJJREFUeNqtV4uSgyAMRIECGhTk///1otTKG3s2Mzdz03aXbEJIQkhuYv9jIx+komhKDnxk4v1F1wT+SoxcUj3PWu8Ex39U8lH4bzt4QthL6tlDA8OP5Iv1vMADGFc5+uRQnDWdEES81EwbNquXqDuBx8va6ZcXktUYBOkc/3GixsBvwA8neFGGGO7hdyeGAsMXeM/wBJ8ziLv6LwYeisD4f4lHhiAXmH9FvzYV3AchOw6At9gFKW4KANDbsttGoSyCKd1Ab4uxkzezhBQaRfQygHB3oj2FhjwT9QgifErM6jiOrQgAXe2UmcuiIKSuHG+mki2XCH0kYqzgF1vETyYszLFaxLBMNdsgDGNFAazRoUcwrDMlDYz28RS0newGcCRlDa8TK4YgxuORGj9x8NYVEsxjKQSp/pNAw5YRcJI/JP5nYeqxjAxeIfCeRQQDyWOos/y5xR2V4NIgYhRJVkjgpralBPcvQH4PsBxIX0DjJqKRdgYLtsYPUyqh60CsACXEQew7ECvAICZp7DqwQEIQXaR+CkzaoeKr3FewQdqg4mIy36VgLyZWz4G96N5vs8sKj0UPSlJGy4fAbWX88SgGQYgJVjDXi7JaaxYo9Oj4UQ0lrHCGdN25ceiEfNoZSfIomjhcKN26DarT0q4gaiyfe2C9u9hWNUBvRghbG+yd1AZNFFrjmu+ucXMF2j60OObE7f0m+mrv/5qQkimpO+IU8fKXQ9bDMe/5oPl81P3BsP183EeGu3GoLBw/WHnuLF20sXQ9X/ueL57PV99w+Z7P5Vvj8j3fXr7j9X/f/5Vsrv9/K3NM7mGXOq0AAAAASUVORK5CYII=",Zn="data:image/svg+xml,%3csvg width='8' height='11' viewBox='57 6 8 11' fill='none' xmlns='http://www.w3.org/2000/svg'%3e %3cpath d='M62.7081 13.27C62.742 13.27 62.7642 13.3057 62.7491 13.3362V13.336L61.1229 16.6083C61.0892 16.6761 60.9926 16.6759 60.959 16.6083L59.3382 13.336C59.3232 13.3057 59.3453 13.27 59.3792 13.27H62.7081Z' fill='%23EA4B4B'/%3e %3cpath d='M61.0026 9.71913C61.0194 9.68524 61.0678 9.68524 61.0845 9.71913L62.747 13.0897C62.762 13.12 62.7399 13.1557 62.706 13.1557H59.3763C59.3424 13.1557 59.3203 13.12 59.3353 13.0897L61.0026 9.71913Z' fill='%23EA4B4B'/%3e %3cpath d='M60.8426 9.63827C60.8766 9.63827 60.8987 9.6741 60.8835 9.70444L59.2164 13.0594C59.1995 13.0932 59.1513 13.0932 59.1345 13.0594L57.5001 9.77047C57.47 9.70962 57.5142 9.63827 57.5821 9.63827H60.8426Z' fill='%23EA4B4B'/%3e %3cpath d='M64.5036 9.63617C64.5715 9.63618 64.6157 9.70753 64.5855 9.76838H64.5854L62.9512 13.0573C62.9344 13.0911 62.8862 13.0912 62.8692 13.0573L61.2021 9.70235C61.187 9.672 61.2091 9.63617 61.2431 9.63617H64.5036Z' fill='%23EA4B4B'/%3e %3cpath d='M62.8284 6.18281C62.862 6.11518 62.9586 6.11518 62.9922 6.18281L64.5855 9.38969C64.6157 9.45054 64.5715 9.52189 64.5036 9.52189H61.2431C61.2091 9.52189 61.187 9.48605 61.2021 9.45571L62.8283 6.18265L62.8284 6.18281Z' fill='%23EA4B4B'/%3e %3cpath d='M62.3131 6.13196C62.381 6.13196 62.4252 6.20331 62.3951 6.26416C62.154 6.74935 61.9128 7.23455 61.6718 7.71975H61.6716C61.4225 8.22125 61.1733 8.72259 60.9242 9.22409C60.9074 9.25799 60.859 9.25799 60.8422 9.22409L60.6305 8.79587C60.6275 8.78957 60.6259 8.78263 60.6259 8.77553V6.22349C60.6259 6.17297 60.6668 6.13196 60.7173 6.13196H62.3131Z' fill='%23EA4B4B'/%3e%3c/svg%3e";const Xn=v.getChainMeta(1)?.logo??"",ql=v.TOKENS.find(e=>e.symbol==="USDC")?.logo??"",yn=Object.fromEntries([...v.getMainnetChains(),...v.getTestnetChains()].map(e=>[e.id,e.logo])),Jn={metamask:Hr,metaMask:Hr,rabby:Ll,phantom:zl},ho=Object.fromEntries(v.TOKENS.map(e=>[e.symbol.toUpperCase(),e.logo])),Hl={usdc:[8453,1,42161,5115,4114],usdt:[1],btc:[4114,42161,1,5115],wbtc:[1],weth:[8453,1],eth:[8453,1,42161,4663,84532,46630],ctusd:[5115,4114],wcbtc:[5115,4114]},Vl={btc:["wcbtc","cbtc","wbtc"]};function Cs(e){return e.replace(/^test\s*/i,"").replace(/^spice/i,"").trim()}function un(e){return Cs(e).toLowerCase()}function Vr(e){return un(e??"").replace(/[^a-z0-9]/g,"")}function go(e){const t=un(e);return[t,...Vl[t]??[]].filter(Boolean)}function Ql(e){try{return BigInt(e.balanceAvailable||"0")}catch{return 0n}}function Qr(e){return Array.isArray(e.chainTokens)?e.chainTokens:Object.keys(e.chainTokens??{})}function Gr(e,t){const n=f.getChainConfig(e),s=t.toLowerCase();return s===v.ZERO_ADDRESS.toLowerCase()?n?.nativeCurrency.decimals??18:n?.supportedTokens?.find(o=>o.address.toLowerCase()===s)?.decimals??18}function Gl(e,t,n,s=[]){const o=Gr(t,n),r=e.filter(l=>Yr(l,t,n,s));if(r.length===0)return null;const i=r.reduce((l,c)=>Math.min(l,c.decimals??o),o);return{chainDecimals:o,receiptDecimals:i}}function Yr(e,t,n,s){if(Qr(e).some(r=>{const i=dn(r);return i&&Kn(i.address,i.chainId,n,t)}))return!0;const o=new Set(s.map(Vr).filter(Boolean));return o.size===0?!1:o.has(Vr(e.tokenName||e.receiptToken))}function Kr(e,t,n,s=[]){const o=Gr(t,n);return e.reduce((r,i)=>Yr(i,t,n,s)?r+v.convertAmountBetweenDecimals(Ql(i),i.decimals??o,o):r,0n)}function Zr(e,t){const n=new Set([...go(t),...go(Cs(t))]);return[...e].sort((s,o)=>{const r=un(s.symbol),i=un(o.symbol),l=un(s.name),c=un(o.name),d=n.has(r)?0:n.has(l)?1:2,p=n.has(i)?0:n.has(c)?1:2;return d!==p?d-p:s.address.toLowerCase().localeCompare(o.address.toLowerCase())})[0]}function Yl(e){const t=e&&e.length>0?e:Object.keys(f.CHAIN_CONFIGS).map(Number).filter(Number.isFinite),n=new Map;for(const s of t){const o=f.getChainConfig(s);if(!o)continue;const r=`${s}:${v.ZERO_ADDRESS.toLowerCase()}`;n.has(r)||n.set(r,{address:v.ZERO_ADDRESS,chainId:s,symbol:o.nativeCurrency.symbol,name:o.nativeCurrency.name,decimals:o.nativeCurrency.decimals,isNative:!0,logoURI:ho[o.nativeCurrency.symbol.toUpperCase()]??o.logo});for(const i of o.supportedTokens??[]){const l=i.address.toLowerCase(),c=`${s}:${l}`;n.has(c)||n.set(c,{address:l,chainId:s,symbol:i.symbol,name:i.name,decimals:i.decimals,isNative:v.isNativeToken(l),logoURI:i.logo})}}return n}function Kl(e,t){const n=Yl(t),s=Cs(e.tokenName),o=un(e.tokenName),r=go(e.tokenName),i=Array.isArray(e.chainTokens)?e.chainTokens.map(g=>[g,void 0]):Object.entries(e.chainTokens??{}),l=i.map(([g])=>dn(g)).filter(g=>g!==null),c=new Map;for(const[g,y]of i){const w=dn(g);if(!w||!Number.isSafeInteger(w.chainId)||w.chainId<0||!/^evm:[0-9]+:(?:0x)?[0-9a-fA-F]{40}$/.test(g)){if(!Array.isArray(e.chainTokens))throw new Error("Invalid chain token metadata identity");continue}if(y!==void 0&&(!y||typeof y!="object"||Array.isArray(y)||y.name!==void 0&&typeof y.name!="string"||y.decimals!==void 0&&(!Number.isInteger(y.decimals)||y.decimals<0||y.decimals>255)))throw new Error("Invalid chain token metadata");const C=`${w.chainId}:${w.address.toLowerCase()}`;if(c.has(C)){const b=c.get(C);if(b?.name!==y?.name||b?.decimals!==y?.decimals)throw new Error("Conflicting chain token metadata")}c.set(C,y)}const d=(g,y)=>{const w=c.get(`${y.chainId}:${y.address.toLowerCase()}`);return{...g,name:typeof w?.name=="string"&&w.name.length>0?w.name:g.name,decimals:typeof w?.decimals=="number"?w.decimals:g.decimals}},p=l.map(g=>{const y=n.get(`${g.chainId}:${g.address.toLowerCase()}`);return y?d(y,g):void 0}).filter(g=>g!==void 0),m=Hl[o]??[];if(m.length>0)for(const g of m){const y=p.filter(w=>w.chainId===g);if(y.length>0)return Zr(y,e.tokenName)}if(p.length>0)return Zr(p,e.tokenName);const h=Array.from(n.values()).filter(g=>r.includes(un(g.symbol))||r.includes(un(g.name)));if(m.length>0)for(const g of m){const y=h.find(w=>w.chainId===g);if(y)return y}if(h.length>0)return h[0];const x=l[0];if(x){const g=c.get(`${x.chainId}:${x.address.toLowerCase()}`);return{address:x.address,chainId:x.chainId,symbol:s||e.tokenName,name:typeof g?.name=="string"&&g.name.length>0?g.name:s||e.tokenName,decimals:typeof g?.decimals=="number"?g.decimals:e.decimals??18,isNative:v.isNativeToken(x.address),logoURI:void 0}}}function Zl(e,t){let n;try{n=BigInt(e.balanceAvailable||"0")}catch{return null}if(n<=0n)return null;if(t?.length){const g=Qr(e).map(dn).filter(y=>y!==null);if(g.length>0&&!g.some(y=>t.includes(y.chainId)))return null}let s;try{s=Kl(e,t)}catch{return null}const o=s?.decimals??e.decimals??18,r=e.decimals??o,i=v.convertAmountBetweenDecimals(n,r,o),l=s?.address??v.ZERO_ADDRESS,c=s?.chainId??0,d=Cs(e.tokenName),p=s?.symbol??d,m=s?.name??d,h=parseFloat(T.formatUnits(i,o)),x=typeof e.balanceUsd=="number"?e.balanceUsd:typeof e.balanceUsd=="string"&&Number(e.balanceUsd)||0;return{address:l,symbol:p,name:m,decimals:o,chainId:c,balance:i,balanceFormatted:h,balanceUsd:x,isNative:s?.isNative??v.isNativeToken(l),logoURI:s?.logoURI,displaySymbol:d||p,displayName:d||m,displayChainName:"Spicenet",receiptTokenId:e.receiptToken,receiptTokenName:e.tokenName||m,receiptTokenDecimals:r,chainTokens:e.chainTokens&&!Array.isArray(e.chainTokens)?e.chainTokens:void 0,isUniversal:!0}}const xo=6e4,Xl=3e5,Xr="https://api.g.alchemy.com/prices/v1",Dn=new Map;function yo(e,t){try{const n=t??f.getClientForChain(e).transport.url;if(typeof n!="string")return null;const{hostname:s,pathname:o}=new URL(n);if(!s.endsWith(".g.alchemy.com"))return null;const r=o.split("/").filter(Boolean).pop();return r?{network:s.slice(0,-14),key:r}:null}catch{return null}}const $n=(e,t)=>`${e.network}:${e.key}:${t.toLowerCase()}`;function _n(e,t){const n=Dn.get($n(e,t));if(!n?.price||n.updatedAt===void 0)return;const s=Date.now()-n.updatedAt;if(!(s>=Xl))return{price:n.price,stale:s>=xo}}function Jr(e){const t=Number(e.prices?.find(n=>n.currency==="usd")?.value);return Number.isFinite(t)&&t>0?t:0}async function $r(e,t,n){const s=[],o=new Set,r=Date.now();for(const i of new Set(t.map(l=>l.toLowerCase()))){const l=Dn.get($n(e,i));l?.pending?o.add(l.pending):(!l||r-l.attemptedAt>=xo&&(l.updatedAt===void 0||r-l.updatedAt>=xo))&&s.push(i)}for(let i=0;i<s.length;i+=25){const l=s.slice(i,i+25),c=Promise.resolve().then(async()=>{try{const d=await n(l);for(const p of l){const m=d.get(p);if(!m)continue;const h=Dn.get($n(e,p));h.price=m,h.updatedAt=Date.now()}}catch{}finally{for(const d of l)Dn.get($n(e,d)).pending=void 0}});for(const d of l){const p=$n(e,d);Dn.set(p,{...Dn.get(p),attemptedAt:r,pending:c})}o.add(c)}await Promise.all(o)}async function wo(e,t){return await $r(e,t,async n=>{const s=await fetch(`${Xr}/${e.key}/tokens/by-address`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({addresses:n.map(i=>({network:e.network,address:i}))}),signal:AbortSignal.timeout(1e4)});if(!s.ok)throw new Error("Provider price request failed");const o=await s.json(),r=new Map;for(const i of o?.data??[]){if(i.network&&i.network!==e.network)continue;const l=String(i.address).toLowerCase();n.includes(l)&&r.set(l,Jr(i))}return r}),new Map(t.map(n=>[n.toLowerCase(),_n(e,n)?.price??0]))}async function bo(e,t){const n=`native:${t}`;return await $r(e,[n],async()=>{const s=await fetch(`${Xr}/${e.key}/tokens/by-symbol?symbols=${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(1e4)});if(!s.ok)throw new Error("Provider native price request failed");const o=(await s.json())?.data?.find(r=>r.symbol?.toUpperCase()===t.toUpperCase());return new Map([[n.toLowerCase(),o?Jr(o):0]])}),_n(e,n)?.price??0}async function Jl(e,t){const n=t.supportedChains,s=e.map(o=>{if(Number.isFinite(o.balanceUsd)&&o.balanceUsd>0)return[];const r=Object.keys(o.chainTokens??{}).map(dn).filter(i=>!!i&&T.isAddress(i.address)&&!!n?.includes(i.chainId));return r.sort((i,l)=>{const c=d=>d===t.nativeChainId?-1:n.indexOf(d);return c(i.chainId)-c(l.chainId)||+!f.addressesEqual(i.address,o.address)-+!f.addressesEqual(l.address,o.address)}),r.flatMap(i=>{const l=t.rpcOverrides?.[i.chainId];if(!l)return[];const c=yo(i.chainId,l);if(!c)return[];const d=v.isNativeToken(i.address)?f.getChainConfig(i.chainId)?.nativeCurrency.symbol:void 0,p=d?`native:${d}`:i.address;return[{rpc:c,token:p,address:i.address,nativeSymbol:d}]})});return(typeof document>"u"||!document.hidden)&&await Promise.all(s.map(async o=>{for(const r of o)if(r.nativeSymbol?await bo(r.rpc,r.nativeSymbol).catch(()=>0):(await wo(r.rpc,[r.address]).catch(()=>new Map)).get(r.address.toLowerCase()))break})),e.map((o,r)=>{if(Number.isFinite(o.balanceUsd)&&o.balanceUsd>0)return o;const i=s[r].map(l=>_n(l.rpc,l.token)).find(Boolean);return{...o,balanceUsd:i?o.balanceFormatted*i.price:0,priceStatus:i?i.stale?"stale":"fresh":"unavailable"}})}function $l(e,t,n){const s=u.useContext(f.SpiceFlowProviderContext),[o,r]=u.useState(()=>typeof document>"u"||!document.hidden);u.useEffect(()=>{const p=()=>r(!document.hidden);return document.addEventListener("visibilitychange",p),()=>document.removeEventListener("visibilitychange",p)},[]);const i={supportedChains:n??s?.supportedChainIds,nativeChainId:s?.nativeChainId,rpcOverrides:s?.rpcOverrides},l=JSON.stringify([e,i],(p,m)=>typeof m=="bigint"?m.toString():m),c=u.useCallback(()=>Jl(e,i),[l]),d=mo(`prices:${l}`,c,t&&o&&e.length>0,6e4);return d.updatedAt?d.assets:e}function _l(e){const t=e.chainTokens??e.chainTokenConfig;if(Array.isArray(t))return t.filter(n=>typeof n=="string");if(t&&typeof t=="object")return t}const _r=({address:e,supportedChains:t,enabled:n=!0,refetchInterval:s,priceEnabled:o=!1})=>{const r=u.useContext(f.SpiceFlowProviderContext),i=r?.apiUrl||f.RELAYER_API_URL,l=bs(),c=r?.supportedChainIds??t,d=JSON.stringify([...c??[]].sort((k,E)=>k-E)),p=e?.toLowerCase(),m=u.useCallback(async()=>{const k=await f.relayerFetch(`${i}/wallets/${p}/balance`,{cache:"no-store"});if(!k.ok)throw new Error(`Failed to fetch balance: ${k.status}`);const E=await k.json();if(!Array.isArray(E.balances))throw new Error("Invalid balance response");return E.balances.map(R=>{const j=Zl({receiptToken:typeof R.receiptToken=="string"?R.receiptToken:void 0,tokenName:String(R.tokenName??""),balanceAvailable:String(R.balanceAvailable??"0"),chainTokens:_l(R),decimals:typeof R.decimals=="number"?R.decimals:void 0,balanceUsd:typeof R.balanceUsd=="number"||typeof R.balanceUsd=="string"?R.balanceUsd:null},c);return j?{...j,owner:p,location:"rollup",_source:"spice",positionId:`${p}:rollup:${j.receiptTokenId??j.address}`}:null}).filter(R=>R!==null)},[p,i,d,r?.nativeChainId,r?.rpcOverrides]),{assets:h,loading:x,refreshing:g,error:y,updatedAt:w}=mo(`rollup:${p}:${i}:${d}`,m,n&&!!p,s??0,l),C=JSON.stringify(t??[]),b=u.useMemo(()=>y?h.map(k=>({...k,balanceError:y,balanceStatus:"stale"})):h,[h,y]),S=$l(b,n&&o,c),I=u.useMemo(()=>S.filter(k=>!t?.length||t.includes(k.chainId)||Object.keys(k.chainTokens??{}).some(E=>t.some(R=>E.startsWith(`evm:${R}:`)))),[S,C]),F=u.useCallback(k=>I.filter(E=>E.chainId===k),[I]);return{assets:I,loading:x,error:y,hasBalance:I.some(k=>k.balance>0n),refreshing:g,updatedAt:w,refetch:l.invalidate,getAssetsByChain:F}};async function ec(e,t,n){if(n)return{decimals:n.decimals,symbol:n.symbol,name:n.name,logoURI:n.logo};const[s,o,r]=await Promise.all([_t.readContract(e,{address:t,abi:T.erc20Abi,functionName:"decimals"}),_t.readContract(e,{address:t,abi:T.erc20Abi,functionName:"symbol"}).catch(()=>"TOKEN"),_t.readContract(e,{address:t,abi:T.erc20Abi,functionName:"name"}).catch(()=>"TOKEN")]);if(!Number.isInteger(Number(s))||Number(s)<0||Number(s)>255)throw new Error("Invalid token decimals");return{decimals:Number(s),symbol:o,name:r,logoURI:void 0}}const ea=async(e,t,n)=>{const s=f.getClientForChain(t,n),o=f.getChainConfig(t),r=await _t.getBalance(s,{address:e}),i=o.nativeCurrency,l=o.supportedTokens?.find(c=>v.isNativeToken(c.address));return{address:v.ZERO_ADDRESS,name:i.name,symbol:i.symbol,decimals:i.decimals,balance:r,balanceFormatted:Number(T.formatUnits(r,i.decimals)),balanceUsd:0,logoURI:l?.logo||o.logo,isNative:!0,chainId:t}},tc=async(e,t,n,s,o,r,i)=>{try{if(!T.isAddress(n))return null;const l=T.getAddress(n),c=T.isAddress(e)?T.getAddress(e):e,d=f.getClientForChain(t,i),p=await _t.readContract(d,{address:l,abi:T.erc20Abi,functionName:"balanceOf",args:[c]}),m=Number(T.formatUnits(p,r));return p>0n?{address:l,name:s,symbol:o,decimals:r,balance:p,balanceFormatted:m,balanceUsd:0,logoURI:void 0,isNative:!1,chainId:t}:null}catch(l){throw l}},ta=(e,t)=>{const n=f.getChainConfig(t);if(!n)return e;const s=new Set(e.map(r=>r.address.toLowerCase())),o=e.some(r=>r.isNative);for(const r of n.supportedTokens||[])v.isNativeToken(r.address)&&o||s.has(r.address.toLowerCase())||e.push({address:r.address,name:r.name,symbol:r.symbol,decimals:r.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:r.logo,isNative:v.isNativeToken(r.address),chainId:t});if(!e.find(r=>r.isNative)){const r=n.supportedTokens?.find(i=>v.isNativeToken(i.address));e.push({address:v.ZERO_ADDRESS,name:n.nativeCurrency.name,symbol:n.nativeCurrency.symbol,decimals:n.nativeCurrency.decimals,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,logoURI:r?.logo||n.logo,isNative:!0,chainId:t})}return e},nc=async(e,t,n)=>{const s=[],o=async l=>{for(const c of l){const d=await tc(e,t,c.address,c.name,c.symbol,c.decimals,n);d&&(d.logoURI=c.logo,s.push(d))}},r=await ea(e,t,n);r.balance>0n&&s.push(r);const i=(f.getChainConfig(t)?.supportedTokens||[]).filter(l=>!v.isNativeToken(l.address));if(i.length>0)try{const l=f.getClientForChain(t,n),c=T.getAddress(e),d=i.filter(x=>T.isAddress(x.address)).map(x=>({address:T.getAddress(x.address),abi:T.erc20Abi,functionName:"balanceOf",args:[c]})),p=await l.multicall({contracts:d}),m=i.filter(x=>T.isAddress(x.address)),h=[];p.forEach((x,g)=>{if(x.status==="success"){const y=x.result;if(y&&y>0n){const w=m[g],C=Number(T.formatUnits(y,w.decimals));y>0n&&s.push({address:T.getAddress(w.address),name:w.name,symbol:w.symbol,decimals:w.decimals,balance:y,balanceFormatted:C,balanceUsd:0,logoURI:w.logo,isNative:!1,chainId:t})}}else h.push(m[g])}),await o(h)}catch{await o(i)}return{tokens:ta(s,t),chainId:t}},sc=async(e,t,n)=>{const s=new Map,o=yo(e,n?n[e]??"":void 0);if(!o)return s;const r=t.filter(d=>v.isNativeToken(d)),i=t.filter(d=>!v.isNativeToken(d)),[l,c]=await Promise.all([i.length?wo(o,i).catch(()=>new Map):new Map,r.length?bo(o,f.getChainConfig(e)?.nativeCurrency?.symbol??"ETH").catch(()=>0):0]);for(const[d,p]of l)p>0&&s.set(d,p);if(c>0)for(const d of r)s.set(d.toLowerCase(),c);return s},oc=async(e,t,n,s=!0,o)=>{const r=f.getClientForChain(t,o),i=T.getAddress(e),l=[];let c;do{const C=await r.request({method:"alchemy_getTokenBalances",params:[i,"erc20",c?{pageKey:c}:{}]});l.push(...C.tokenBalances),c=C.pageKey||void 0}while(c);const d=l.filter(C=>T.isAddress(C.contractAddress)&&!!C.tokenBalance&&BigInt(C.tokenBalance)>0n),p=f.getChainConfig(t)?.supportedTokens||[],m=C=>p.find(b=>b.address.toLowerCase()===C.toLowerCase()),h=[],x=await ea(e,t,o),[g,y,w]=await Promise.all([Promise.all(d.map(async C=>{const b=m(C.contractAddress);return b?{name:b.name,symbol:b.symbol,decimals:b.decimals,logo:b.logo??null}:await r.request({method:"alchemy_getTokenMetadata",params:[C.contractAddress]})})),s?wo(n,d.map(C=>C.contractAddress)):new Map(d.map(C=>[C.contractAddress.toLowerCase(),_n(n,C.contractAddress)?.price??0])),s&&x.balanceFormatted>0?bo(n,x.symbol):_n(n,`native:${x.symbol}`)?.price??0]);return x.balance>0n&&h.push({...x,balanceUsd:w*x.balanceFormatted}),d.forEach((C,b)=>{const S=g[b];if(!Number.isInteger(S.decimals)||S.decimals===null||S.decimals<0||S.decimals>255)throw new Error(`Invalid token metadata on chain ${t}`);const I=BigInt(C.tokenBalance),F=Number(T.formatUnits(I,S.decimals));if(I<=0n)return;const k=y.get(C.contractAddress.toLowerCase()),E=k?k*F:0;h.push({address:T.getAddress(C.contractAddress),name:S.name||"Unknown",symbol:S.symbol||"UNKNOWN",decimals:S.decimals,balance:I,balanceFormatted:F,balanceUsd:E,isDiscovered:!m(C.contractAddress),logoURI:S.logo||void 0,isNative:!1,chainId:t})}),{tokens:ta(h,t),chainId:t}},na=new Set,rc=async(e,t,n=!0,s)=>{try{const o=yo(t,s?s[t]??"":void 0);if(o)try{return await oc(e,t,o,n&&(typeof document>"u"||!document.hidden),s)}catch(r){na.has(t)||(na.add(t),console.warn(`Token discovery unavailable on chain ${t}; listing configured tokens only.`,r))}return await nc(e,t,s)}catch(o){throw o}},On=async(e,t,n=[],s)=>{if(!e)throw new Error("Wallet address is required");const o=f.getChainsForAssets(s),r=t?.length?[...new Set(t)]:Object.keys(o).map(Number),i=await Promise.allSettled(r.map(c=>rc(e,c,!0,s))),l={};return i.forEach((c,d)=>{const p=r[d];l[p]=c.status==="fulfilled"?c.value:{chainId:p,tokens:[],error:`Unable to refresh balances on chain ${p}`}}),(await Promise.allSettled(n.map(async c=>{const d=l[c.chainId];if(!d||d.error||d.tokens.some(y=>v.normalizeNativeTokenAddress(y.address).toLowerCase()===v.normalizeNativeTokenAddress(c.address).toLowerCase()))return;const p=f.getClientForChain(c.chainId,s),m=await ec(p,c.address,c.decimals!==void 0&&c.symbol?{decimals:c.decimals,symbol:c.symbol,name:c.name||c.symbol,logo:c.logoURI}:void 0),h=await _t.readContract(p,{address:c.address,abi:T.erc20Abi,functionName:"balanceOf",args:[e]}),x=await sc(c.chainId,[c.address],s),g=Number(T.formatUnits(h,m.decimals));d.tokens.push({...m,...c,name:m.name,symbol:m.symbol,decimals:m.decimals,balance:h,balanceFormatted:g,balanceUsd:(x.get(c.address.toLowerCase())||0)*g,isNative:!1})}))).forEach((c,d)=>{if(c.status==="rejected"){const p=l[n[d].chainId];p&&(p.error=`Unable to refresh token balances on chain ${p.chainId}`)}}),l},es=({address:e,supportedChains:t,fetchBalances:n=On,additionalTokens:s=[],enabled:o=!0,refreshInterval:r=0,priceEnabled:i=!0})=>{const l=u.useContext(f.SpiceFlowProviderContext),c=bs(),d=e?.toLowerCase(),p=JSON.stringify([...l?.supportedChainIds??t??[]].sort((b,S)=>b-S)),m=JSON.stringify(s);u.useEffect(()=>c.registerTokens(s),[c,m]);const h=d&&d===l?.embeddedWalletAddress?.toLowerCase()?"embedded":"external",x=`wallet:${JSON.stringify([l?.network,l?.apiUrl,l?.rpcOverrides])}:${d}:${h}:${p}:${c.fetcherId(n)}`,g=u.useCallback(async()=>{let b;try{b=await n(d,JSON.parse(p),c.tokens(),l?.rpcOverrides)}catch(k){const E=k instanceof Error?k.message:"Unable to refresh balances";b=Object.fromEntries(JSON.parse(p).map(R=>[R,{chainId:R,tokens:[],error:E}]))}const S=c.entry(x).snapshot().assets,I=JSON.parse(p).map(k=>b[k]??{chainId:k,tokens:[],error:`Unable to refresh balances on chain ${k}`}),F=I.flatMap(k=>k.error?[k.error]:[]);return{assets:I.flatMap(k=>k.error?S.filter(E=>E.chainId===k.chainId).map(E=>({...E,balanceError:k.error,balanceStatus:"stale"})):k.tokens.map(E=>({...E,owner:d,location:h,_fundingWallet:h,_source:"wallet",positionId:`${d}:${h}:${k.chainId}:${v.normalizeNativeTokenAddress(E.address).toLowerCase()}`}))),error:F.length?F.join("; "):null}},[c,d,p,n,h,x]),y=mo(x,g,o&&!!d,r,c),w=JSON.stringify(t&&[...t].sort((b,S)=>b-S)),C=u.useMemo(()=>t?y.assets.filter(b=>t.includes(b.chainId)):y.assets,[y.assets,w]);return u.useEffect(()=>{i&&o&&d&&y.refresh()},[i]),{...y,assets:C,refreshAssets:c.invalidate,getAssetsByChain:u.useCallback(b=>C.filter(S=>S.chainId===b),[C]),getNativeAssets:u.useCallback(()=>C.filter(b=>b.isNative),[C])}};function Nn(e){const t=u.useContext(f.SpiceFlowProviderContext),n=bs(),s=e.owner??((t?.mode||"7702")!=="7702"?t?.externalWalletAddress:t?.embeddedWalletAddress),o=s?.toLowerCase()!==t?.embeddedWalletAddress?.toLowerCase(),r=e.sourceChains??t?.supportedChainIds??[],i=(e.enabled??!0)&&!t?.isWhitelistGateActive,l=u.useMemo(()=>{const h=[...t?.additionalSourceTokens??[],...e.additionalSourceTokens??[],...e.destination?[e.destination]:[]];for(const x of e.supportedSourceAssets??[])for(const g of r){const y=f.getChainConfig(g)?.supportedTokens?.find(w=>f.isAssetAllowed(w,[x]));y&&h.push({...y,address:y.address,chainId:g,logoURI:y.logo})}return h},[e.destination,JSON.stringify(t?.additionalSourceTokens),JSON.stringify(e.additionalSourceTokens),JSON.stringify(e.supportedSourceAssets),JSON.stringify(r)]),c=es({address:s,supportedChains:r,fetchBalances:On,additionalTokens:l,enabled:i&&e.includeWalletAssets!==!1,refreshInterval:3e4}),d=_r({address:s,supportedChains:r,enabled:i&&e.includeRollupAssets!==!1&&!!s&&s.toLowerCase()===t?.embeddedWalletAddress?.toLowerCase(),priceEnabled:i,refetchInterval:3e4}),p=u.useMemo(()=>i?[...(e.includeWalletAssets===!1?[]:c.assets).map(h=>({...h,owner:h.owner??s,location:h.location??(o?"external":"embedded"),_source:"wallet"})),...(e.includeRollupAssets===!1||s?.toLowerCase()!==t?.embeddedWalletAddress?.toLowerCase()?[]:d.assets).map(h=>({...h,owner:h.owner??s,location:"rollup",_source:"spice"}))]:[],[i,c.assets,d.assets,e.includeWalletAssets,e.includeRollupAssets,s,o,t?.embeddedWalletAddress]),m=u.useMemo(()=>p.map(h=>({asset:h,...kn(h,e.role??"holding",{allowedTokens:t?.allowedTokens,rpcOverrides:t?.rpcOverrides,liquidityVenues:t?.liquidityVenues,isWhitelistGateActive:!!t?.isWhitelistGateActive},e.destination,e.supportedSourceAssets,{requiresEscrow:e.requiresEscrow})})),[p,t?.allowedTokens,t?.rpcOverrides,t?.liquidityVenues,t?.isWhitelistGateActive,e.role,e.destination,e.supportedSourceAssets,e.requiresEscrow]);return{positions:m,assets:u.useMemo(()=>m.filter(h=>h.eligible&&h.asset.balance>0n).map(h=>h.asset),[m]),walletAssets:u.useMemo(()=>p.filter(h=>h._source==="wallet"),[p]),rollupAssets:u.useMemo(()=>p.filter(h=>h._source==="spice"),[p]),loading:c.loading||d.loading,refreshing:c.refreshing||d.refreshing,error:c.error||d.error,refresh:n.invalidate}}function wn(e){const t=v.normalizeNativeTokenAddress(e.address);if(e.isNative||v.isNativeToken(t))return!1;const n=f.getChainConfig(e.chainId)?.supportedTokens?.some(o=>f.addressesEqual(o.address,t)),s=v.getTokenByAddress(t,e.chainId);return!!n&&!!s&&xs(s)}const sa="spiceflow:pendingDeposit",vs="spiceflow:pendingDepositChanged";function oa(e,t,n){return`${sa}:${e.toLowerCase()}:${t}:${n.toLowerCase()}`}function Co(){try{const e="__spiceflow_storage_test__";return localStorage.setItem(e,"1"),localStorage.removeItem(e),!0}catch{return!1}}function ac(e){if(!Co())return;const t=oa(e.embeddedWalletAddress,e.chainId,e.tokenAddress);try{localStorage.setItem(t,JSON.stringify(e)),window.dispatchEvent(new Event(vs))}catch(n){console.error("[pendingDeposit] Failed to save:",n)}}function ic(e){if(!Co())return[];const t=`${sa}:${e.toLowerCase()}:`,n=[],s=Date.now();for(let o=0;o<localStorage.length;o++){const r=localStorage.key(o);if(!(!r||!r.startsWith(t)))try{const i=localStorage.getItem(r);if(!i)continue;const l=JSON.parse(i);if(s-l.timestamp>6048e5){localStorage.removeItem(r);continue}n.push(l)}catch{localStorage.removeItem(r)}}return n}function vo(e,t,n){if(!Co())return;const s=oa(e,t,n);localStorage.removeItem(s),window.dispatchEvent(new Event(vs))}const lc=new Set(["USDC","SUSD","USD","NUSD","USDT","DAI","ENUSD","USDG"]),ra={ETH:"ethereum",WETH:"ethereum",BTC:"bitcoin",WBTC:"bitcoin",WCBTC:"bitcoin",CBTC:"bitcoin",ECBTC:"bitcoin",ARB:"arbitrum",MATIC:"matic-network",POL:"matic-network"};let ks=null;const cc=6e4;async function aa(e){const t={},n=new Set,s={};for(const r of e){const i=r.toUpperCase();if(lc.has(i))t[i]=1;else if(ra[i]){const l=ra[i];n.add(l),s[i]=l}else t[i]=0}if(n.size===0)return t;const o=Date.now();if(ks&&o-ks.timestamp<cc){for(const[r,i]of Object.entries(s))t[r]=ks.prices[i]??0;return t}try{const r=Array.from(n).join(","),i=await fetch(`https://api.coingecko.com/api/v3/simple/price?ids=${r}&vs_currencies=usd`);if(!i.ok)throw new Error(`CoinGecko ${i.status}`);const l=await i.json(),c={};for(const d of n)c[d]=l[d]?.usd??0;ks={prices:c,timestamp:o};for(const[d,p]of Object.entries(s))t[d]=c[p]??0}catch(r){console.warn("[fetchTokenPrices] CoinGecko fetch failed:",r);for(const i of Object.keys(s))t[i]=t[i]??0}return t}const dc=new Set(["cbtc","btc","wbtc","wcbtc","tbtc"]),uc=new Set(["usdc","usdt","dai","usdc.e","usdbc","usdg"]);async function pc(){const e=(await aa(["BTC"])).BTC;if(!e||e<=0)throw new Error("Failed to fetch BTC/USD price");return e}function fc(e){return dc.has(e.toLowerCase())}function mc(e){return uc.has(e.toLowerCase())}function hc(e,t,n,s){const o=10n**12n,r=BigInt(Math.round(s*Number(o))),i=t-n,l=10n**BigInt(Math.abs(i));let c=e*r/o;return i>0?c=c/l:i<0&&(c=c*l),c}const gc=.01,xc=5*60*1e3;function yc(e){const t=Number(T.formatUnits(e.verifiedBalance,e.tokenDecimals));return Number.isFinite(t)?t:0}async function wc(e){const t=bc(e);let n;try{n=await aa(t.map(s=>s.tokenSymbol))}catch{return t}return t.filter(s=>{const o=yc(s);if(o<=0)return!0;const r=n[s.tokenSymbol.toUpperCase()]??0;return!Number.isFinite(r)||r<=0?!0:o*r>=gc})}function bc(e){const t=new Map;for(const n of e){const s=`${n.chainId}:${n.tokenAddress.toLowerCase()}`;t.get(s)||t.set(s,{...n,amount:n.timestamp===0?T.formatUnits(n.verifiedBalance,n.tokenDecimals):n.amount,rawAmount:n.timestamp===0?n.verifiedBalance.toString():n.rawAmount,hasFullBalance:n.timestamp===0?!0:n.hasFullBalance})}return Array.from(t.values())}function ia(e,t){const[n,s]=u.useState([]),[o,r]=u.useState(!1),i=u.useRef(t);i.current=t;const l=u.useRef(0),c=u.useRef(0),d=u.useCallback(async({forceDiscovery:p=!1}={})=>{if(!e){s([]),r(!1);return}const m=++c.current,h=()=>m!==c.current;r(!0);try{const x=[],g=ic(e);for(const b of g){if(h())return;if(wn({address:b.tokenAddress,chainId:b.chainId,isNative:b.isNative}))try{const S=f.getClientForChain(b.chainId);let I;if(b.isNative||v.isNativeToken(b.tokenAddress)?I=await _t.getBalance(S,{address:e}):I=await _t.readContract(S,{address:T.getAddress(b.tokenAddress),abi:T.erc20Abi,functionName:"balanceOf",args:[e]}),h())return;I>0n?x.push({...b,verifiedBalance:I,hasFullBalance:I>=BigInt(b.rawAmount)}):Date.now()-b.timestamp>15*60*1e3&&vo(e,b.chainId,b.tokenAddress)}catch(S){console.warn(`[usePendingDeposit] Failed to verify balance for ${b.tokenSymbol} on chain ${b.chainId}:`,S),x.push({...b,verifiedBalance:0n,hasFullBalance:!1})}}if(h())return;const y=i.current,w=Date.now(),C=(y?.discoverWalletBalances??!0)&&(p||w-l.current>=xc);if(y?.network&&C){l.current=w;const b=y.chainIds??v.getChainIdsByNetwork(y.network),S=new Set(x.map(F=>`${F.chainId}:${F.tokenAddress.toLowerCase()}`)),I=[];for(const F of b){const k=f.getChainConfig(F);if(k?.supportedTokens)for(const E of k.supportedTokens){if(!wn({address:E.address,chainId:F,isNative:!1}))continue;const R=`${F}:${E.address.toLowerCase()}`;S.has(R)||I.push((async()=>{try{const j=f.getClientForChain(F),A=await _t.readContract(j,{address:T.getAddress(E.address),abi:T.erc20Abi,functionName:"balanceOf",args:[e]});return A>0n?{chainId:F,tokenAddress:E.address,tokenSymbol:E.symbol,tokenDecimals:E.decimals,amount:T.formatUnits(A,E.decimals),rawAmount:A.toString(),embeddedWalletAddress:e,externalWalletAddress:"",timestamp:0,isNative:!1,verifiedBalance:A,hasFullBalance:!0}:null}catch{return null}})())}}if(I.length>0){const F=await Promise.allSettled(I);if(h())return;for(const k of F)k.status==="fulfilled"&&k.value&&x.push(k.value)}}if(!h()){const b=await wc(x);if(h())return;s(b)}}catch(x){console.error("[usePendingDeposit] Verification error:",x),h()||s([])}finally{h()||r(!1)}},[e]);return u.useEffect(()=>{if(!i.current?.enabled){c.current++,s([]),r(!1);return}d({forceDiscovery:!0});const p=i.current?.pollIntervalMs??3e4;if(p<=0||!e)return()=>{c.current++};const m=setInterval(()=>{d({forceDiscovery:!1})},p),h=()=>d({forceDiscovery:!0});return window.addEventListener(vs,h),()=>{c.current++,window.removeEventListener(vs,h),clearInterval(m)}},[d,e]),{pendingDeposits:n,loading:o,refresh:()=>d({forceDiscovery:!0})}}function la(e){const t=u.useContext(f.SpiceFlowProviderContext),n=t?.embeddedWalletAddress,s=e?.enabled===!1?void 0:n,o=t?.network?{network:t.network,pollIntervalMs:e?.pollIntervalMs,chainIds:e?.chainIds??t.supportedChainIds,discoverWalletBalances:e?.discoverWalletBalances}:void 0;return{...ia(s,o),embeddedWalletAddress:n}}var ko="data:image/svg+xml,%3csvg width='10' height='10' viewBox='0 0 10 10' fill='none' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M5 4.99995V6.99995M5 3.31245V3.31189M9.5 5C9.5 7.48528 7.48528 9.5 5 9.5C2.51472 9.5 0.5 7.48528 0.5 5C0.5 2.51472 2.51472 0.5 5 0.5C7.48528 0.5 9.5 2.51472 9.5 5Z' stroke='black' stroke-opacity='0.4' stroke-linecap='round' stroke-linejoin='round'/%3e%3c/svg%3e";function So(e){const t=u.useRef(0),n=u.useRef(null),s=u.useRef(e.run);s.current=e.run;const o=u.useRef(e.onSkip);o.current=e.onSkip;const r=u.useRef(e.onCleanup);r.current=e.onCleanup,u.useEffect(()=>{if(!e.shouldRun){t.current+=1,n.current?.abort(),o.current?.();return}let i=!1,l=!1;const c=async h=>{if(h&&l)return;n.current?.abort();const x=new AbortController;n.current=x;const g=++t.current;l=!0;try{await s.current({isBackground:h,isCurrent:()=>!i&&t.current===g,signal:x.signal})}finally{l=!1}},d=window.setTimeout(()=>void c(!1),e.delayMs??250),p=()=>{document.hidden||c(!0)},m=e.backgroundIntervalMs?window.setInterval(p,e.backgroundIntervalMs):void 0;return m!==void 0&&document.addEventListener("visibilitychange",p),()=>{i=!0,n.current?.abort(),clearTimeout(d),m!==void 0&&(window.clearInterval(m),document.removeEventListener("visibilitychange",p)),r.current?.()}},[e.shouldRun,e.delayMs,e.backgroundIntervalMs,...e.deps])}function ca(e,t){if(e.length!==t.length)return!1;const n=v.hashChainBatches(e),s=v.hashChainBatches(t);return n.every((o,r)=>o.hash===s[r]?.hash)}const en=e=>new Promise(t=>setTimeout(t,e)),Cc="0xa9059cbb";function da(e){const t=e.findIndex(o=>v.isSpicenetChainId(o.chainId));if(t<=0)return[];const n=new Map,s=(o,r,i)=>{if(i<=0n)return;const l=`${o}:${r.toLowerCase()}`,c=n.get(l);c?c.amount+=i:n.set(l,{chainId:o,token:r,amount:i})};for(const o of e.slice(0,t)){const r=v.getEscrowContract(o.chainId);if(!(!r||r===v.ZERO_ADDRESS)){for(const i of o.calls)if(i.value&&i.value>0n&&f.addressesEqual(i.to,r)&&s(o.chainId,v.ZERO_ADDRESS,i.value),!!i.data?.startsWith(Cc))try{const l=T.decodeFunctionData({abi:T.erc20Abi,data:i.data});if(l.functionName!=="transfer")continue;const[c,d]=l.args;f.addressesEqual(c,r)&&s(o.chainId,i.to,d)}catch{}}}return[...n.values()]}function ua(e){const t=v.getTokenByAddress(e.token,e.chainId);return[t?.equivalenceGroup,t?.symbol,t?.name]}function pa(e,t){return Kr(e,t.chainId,t.token,ua(t))}function vc(e,t){const n=Gl(e,t.chainId,t.token,ua(t));return!n||n.receiptDecimals>=n.chainDecimals?t.amount:v.convertAmountBetweenDecimals(v.convertAmountBetweenDecimals(t.amount,n.chainDecimals,n.receiptDecimals),n.receiptDecimals,n.chainDecimals)}async function kc(e){const{deposits:t,baseline:n,fetchEntries:s,timeoutMs:o=12e4,intervalMs:r,signal:i,wait:l=en}=e;if(t.length===0)return!0;const c=new Map(t.map(m=>[m,pa(n,m)])),d=Date.now(),p=d+o;for(;!i?.aborted;){try{const g=await s();if(t.every(y=>pa(g,y)-c.get(y)>=vc(g,y)))return!0}catch{}const m=Date.now();if(m>=p)return!1;const h=m-d,x=r??(h<5e3?250:h<15e3?1e3:3e3);await l(Math.min(x,p-m))}return!1}function Sc(e,t){const n=v.hashChainBatches(e).map(s=>s.hash);return T.keccak256(T.encodeAbiParameters([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,t,n]))}async function Ic(e,t,n,s,o){if(s?.aborted)throw new f.SpiceflowError("ABORT","Execution transaction aborted");const r={raw:Sc(t,n)},i=o?await e.signMessage(r,o):await e.signMessage(r);console.debug("[SpiceFlow:execution]",{phase:"signature-returned",at:Date.now()});const l=typeof i=="string"?i:i.signature;if(!l)throw new f.SpiceflowError("SIGNATURE_FAILED","Failed to sign intent authorization. The wallet returned an empty signature.");return l}function Ac(e){return e.domain==="spicenet"||v.isSpicenetChainId(e.chainId)}async function Ec(e){const{chainBatches:t,signingAddress:n,actions:s,cache:o,signal:r,onSignatureRequested:i,beforeSign:l}=e;if(r?.aborted)throw new f.SpiceflowError("ABORT","Execution transaction aborted");const c=[...new Set(t.filter(m=>!Ac(m)).map(m=>m.chainId))].map(m=>({chainId:m,client:f.getClientForChain(m),delegateContract:f.getDelegateContractAddress(m)})),[d]=await Promise.all([Promise.all(c.map(async({chainId:m,client:h,delegateContract:x})=>{const g=Number(await v.getAccountNonce(n,h)),y=[n.toLowerCase(),m,x.toLowerCase(),g].join(":");return{chainId:m,delegateContract:x,nonce:g,cacheKey:y,cached:o?.get(y)}})),c.length?s.prepareSigning?.():void 0,l?.()]),p=[];for(const{chainId:m,delegateContract:h,nonce:x,cacheKey:g,cached:y}of d){if(y){p.push(y);continue}if(r?.aborted)throw new f.SpiceflowError("ABORT","Execution transaction aborted");const w=await s.signAuthorization({contractAddress:h,chainId:m,nonce:x},i),C={r:w.r,s:w.s,yParity:w.yParity,address:w.address??h,chainId:Number(w.chainId??m),nonce:Number(w.nonce??x)};o?.set(g,C),p.push(C)}return p}const fa=15;function Fc(e){return e.now-e.lastProgressAt>=e.pollTimeoutMs}function ma(e,t){return{intentId:e,steps:t.map(n=>({...n,status:"pending"})),overallStatus:"processing"}}function Ss(e,t,n){const s=e.steps.map(l=>({...l})),o=s[t];if(!o)return e;n.status==="success"||n.status==="completed"?(s[t]={...o,status:"success",transactionHash:n.transactionHash},t+1<s.length&&s[t+1].status==="pending"&&(s[t+1]={...s[t+1],status:"processing"})):n.status==="reverted"||n.status==="error"?s[t]={...o,status:"failed",transactionHash:n.transactionHash,error:n.error}:s[t]={...o,status:"processing"};const r=s.some(l=>l.status==="failed"),i=s.every(l=>l.status==="success");return{...e,steps:s,overallStatus:r?"failed":i?"success":"processing"}}function Tc({checkStepStatus:e,retryStep:t,maxRetries:n=3,pollingInterval:s=2500,pollTimeoutMs:o=3e5}){const[r,i]=u.useState(null),l=u.useRef(null),c=u.useRef(null),d=u.useRef(!1),p=u.useRef(!1),m=u.useRef(0),h=u.useRef({}),x=u.useRef(0),g=u.useCallback(I=>{l.current=I,i(I)},[]),y=u.useCallback(()=>{c.current&&(clearInterval(c.current),c.current=null)},[]),w=u.useCallback(()=>{m.current=0,h.current={},x.current=0,d.current=!0,y(),g(null)},[y,g]),C=u.useCallback((I,F)=>{y(),d.current=!1,g(ma(I,F))},[y,g]),b=u.useCallback((I,F)=>{const k=l.current;k&&g(Ss(k,I,F))},[g]),S=u.useCallback((I,F)=>{y(),d.current=!1,p.current=!1,m.current=0,h.current={},x.current=Date.now(),g(ma(I,F));const k=async()=>{if(!(d.current||p.current||!e)){p.current=!0;try{if(Fc({now:Date.now(),lastProgressAt:x.current,pollTimeoutMs:o})){const j=l.current;j&&g({...j,steps:j.steps.map(A=>A.status==="success"?A:{...A,status:"failed",error:"Taking longer than expected. It may still complete - check the explorer, then refresh."}),overallStatus:"failed"}),d.current=!0,y();return}const E=l.current;if(!E)return;const R=E.steps.findIndex(j=>j.status!=="success");if(R===-1){d.current=!0,y();return}if(!(R===0||E.steps[R-1].status==="success"))return;try{const j=E.steps[R].stepId,{data:A}=await e(I,j);if(m.current=0,A.status==="success"&&(x.current=Date.now()),A.status==="reverted"){const P=h.current[j]||0;if(t&&P<n){h.current[j]=P+1;try{await t(I,j)}catch(N){console.error(`[intentStatus] retry failed for step ${j}:`,N)}g(Ss(l.current,R,{status:"executing"}));return}}const M=Ss(l.current,R,A);g(M),M.overallStatus!=="processing"&&(d.current=!0,y())}catch(j){m.current+=1,console.error(`[intentStatus] poll error (${m.current}/${fa}):`,j),m.current>=fa&&(g(Ss(l.current,R,{status:"error"})),d.current=!0,y())}}finally{p.current=!1}}};k(),c.current=setInterval(k,s)},[e,t,n,s,o,y,g]);return u.useEffect(()=>()=>y(),[y]),{intentStatus:r,startStatusPolling:S,beginStatusTracking:C,applyStepUpdate:b,stopStatusPolling:y,clearStatus:w}}function jc(e,t){return(t||"").trim()||`Transaction ${e}. The transaction was rejected on-chain. This may be due to insufficient balance, price changes, or health factor constraints. Please verify your positions and try again.`}const Bc=350,Rc=2500;async function ha(e){const{actionId:t,intentIndex:n,intentId:s,stepIndex:o,maxPolls:r=48,maxExecuteAttempts:i=3,pollsBeforeRetry:l=5,maxConsecutiveStatusErrors:c=15,onStatusMessage:d,onStepUpdate:p,signal:m,chainId:h}=e;if(m?.aborted)throw new f.SpiceflowError("ABORT","Execution transaction aborted");let x="pending",g,y,w=0,C=0,b,S;const I=new Promise((k,E)=>{b=k,S=()=>E(new f.SpiceflowError("ABORT","Execution transaction aborted"))}),F=()=>{w++,f.relayerService.executeStep(t,n,o,{action:"execute"}).then(k=>{k.transactionHash&&(g=k.transactionHash),k.status==="success"&&b({status:k.status,transactionHash:k.transactionHash})}).catch(k=>{const E=k instanceof Error?k.message:String(k);console.warn(`[execution] executeStep ${o} attempt ${w} error (will poll):`,E)})};m?.addEventListener("abort",S,{once:!0});try{F();for(let k=0;k<r;k++){const E=k===0?Bc:Rc;try{const j=await Promise.race([en(E).then(()=>{}),I]);if(m?.aborted)throw new f.SpiceflowError("ABORT","Execution transaction aborted");const A=j??await Promise.race([f.relayerService.checkStepStatus(s,o).then(P=>P.data),I]);if(m?.aborted)throw new f.SpiceflowError("ABORT","Execution transaction aborted");C=0,x=A.status,y=A.error;const M=A.transactionHash;M&&(g=M),p?.({status:x,transactionHash:g,error:y})}catch(j){if(j instanceof Error&&(j.name==="AbortError"||j instanceof f.SpiceflowError&&j.code==="ABORT")||(C++,C>=c))throw j;continue}if(x==="created"&&k>=w*l&&w<i&&F(),x==="reverted"||x==="error")throw new f.SpiceflowError("ON_CHAIN_REVERT",jc(x,y),{status:x,txHash:g,actionId:t,intentId:s,stepId:o,chainId:h});if(x==="success"||x==="completed")return g;let R="Waiting for solver...";x==="executing"?R="Transaction executing...":x==="submitted"?R="Transaction submitted...":x==="created"&&(R="Waiting for relayer..."),d?.(R,g)}throw new f.SpiceflowError("POLLING_EXHAUSTED",`Transaction is still processing (status: ${x}). This doesn't mean it failed \u2014 the solver may still complete it. Check your positions in a few minutes, or try refreshing the page.`,{actionId:t,intentId:s,stepId:o,lastStatus:x,pollAttempts:r,maxPolls:r,txHash:g})}finally{m?.removeEventListener("abort",S)}}async function Dc(e){const{actionId:t,intentIndex:n,intentId:s,totalSteps:o,delayBeforeSpicenetStepMs:r=5e3,isSpicenetStep:i,beforeStep:l,maxExecuteAttemptsForStep:c,maxPolls:d=48,onStatusMessage:p,onStepUpdate:m,signal:h}=e;let x;for(let g=0;g<o;g++){if(g>0&&i?.(g)&&r>0&&await en(r),await l?.(g),h?.aborted)throw new f.SpiceflowError("ABORT","Execution transaction aborted");const y=c?.(g)??3,w=await ha({actionId:t,intentIndex:n,intentId:s,stepIndex:g,maxPolls:d,maxExecuteAttempts:y,maxConsecutiveStatusErrors:y===6?5:15,onStatusMessage:p,onStepUpdate:m?C=>m(g,C):void 0,signal:h});w&&(x=w)}return x}const Oc="0xa9059cbb";function Io(e,t){return e.map(n=>{if(n.domain==="spicenet"||v.isSpicenetChainId(n.chainId)||n.calls.length===0)return n;const s=new Set((n.tokenTransfers??[]).filter(i=>(i.from==="escrow"||i.from==="solver")&&f.addressesEqual(i.to,t)).map(i=>i.token.toLowerCase()));if(s.size===0)return n;const o=[...s].some(v.isNativeToken);let r=0;for(const i of n.calls){if(o&&i.value>0n&&i.data==="0x"&&!f.addressesEqual(i.to,t)){r+=1;continue}if(!i.data?.startsWith(Oc))break;try{const l=T.decodeFunctionData({abi:T.erc20Abi,data:i.data});if(l.functionName!=="transfer")break;const[c]=l.args;if(f.addressesEqual(c,t)||!s.has(i.to.toLowerCase()))break;r+=1}catch{break}}return r===0?n:{...n,calls:n.calls.slice(r)}})}async function Nc(e,t){if(!t||!/^0x[0-9a-f]{64}$/i.test(t))throw new Error("The destination receipt is not available yet; reconcile the existing action before retrying.");const n=await e.waitForTransactionReceipt({hash:t,timeout:12e4,pollingInterval:2e3,confirmations:1});if(n.transactionHash?.toLowerCase()!==t.toLowerCase()||n.status!=="success")throw new Error("The destination transaction has not been confirmed successfully. Reconcile the existing action before retrying.");return t}async function Is(e){let t=e.hash,n=!1;const s=Date.now()+12e4,o=i=>i.transactionHash&&i.transactionHash.toLowerCase()!==t.toLowerCase();let r=await e.client.waitForTransactionReceipt({hash:t,timeout:12e4,pollingInterval:2e3,confirmations:1,onReplaced:i=>{const l=i.transaction,c=i.replacedTransaction;if(!(i.reason==="repriced"&&c?.from&&c.nonce!==void 0&&/^0x[0-9a-f]{64}$/i.test(l?.hash??"")&&l?.to?.toLowerCase()===e.call.to.toLowerCase()&&(l.input??"0x").toLowerCase()===e.call.data.toLowerCase()&&BigInt(l.value??0)===e.call.value&&l.from?.toLowerCase()===c?.from?.toLowerCase()&&l.nonce===c?.nonce)){n=!0,e.onCancelled?.();return}t=l.hash,e.onRepriced?.(t)}});if(n)throw new Error("Transaction was cancelled or replaced with a different action; retry the unfinished action");if((e.confirmations??1)>1&&!o(r)&&r.status==="success"&&(r=await e.client.waitForTransactionReceipt({hash:t,timeout:Math.max(s-Date.now(),1),pollingInterval:2e3,confirmations:e.confirmations})),o(r))throw new Error("Unexpected transaction receipt; recover the submitted transaction before retrying");return{receipt:r,hash:t}}const Mc=10n,Pc=10n,Uc=5;function Ao(e){return e.map(t=>({...t,calls:[...t.calls],tokenTransfers:t.tokenTransfers?[...t.tokenTransfers]:void 0}))}function As({token:e,recipient:t,amount:n}){return{to:e,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"transfer",args:[t,n]})}}function Wc({chainBatches:e,token:t,amount:n}){const s=Ao(e),o=s[s.length-1];if(!o)return s;const r=v.getEscrowContractAddress(o.chainId);return o.calls=[...o.calls,As({token:t,recipient:r,amount:n})],s}function ga({chainBatches:e,user:t,token:n,grossAmount:s,gasFee:o}){const r=Ao(e),i=r[r.length-1];if(!i)throw new f.SpiceflowError("INVALID_PARAMS","Action-output escrow funding requires at least one chain batch.");const l=f.calculateBpsFee(s,Pc),c=o+l;if(c>=s)throw new f.SpiceflowError("INVALID_PARAMS","Borrow amount is too small after gas and Spicenet fees.",{grossAmount:s.toString(),gasFee:o.toString(),spicenetFee:l.toString()});const d=s-c,p=v.getEscrowContractAddress(i.chainId),m=[];return o>0n&&m.push(As({token:n,recipient:v.SPICE_GAS_FEE_RECIPIENT,amount:o})),l>0n&&m.push(As({token:n,recipient:v.SPICE_PLATFORM_FEE_RECIPIENT,amount:l})),i.calls=[...i.calls,...m,As({token:n,recipient:p,amount:d})],i.tokenTransfers=[...i.tokenTransfers??[],...o>0n?[{from:t,to:v.SPICE_GAS_FEE_RECIPIENT,token:n,amount:o}]:[],...l>0n?[{from:t,to:v.SPICE_PLATFORM_FEE_RECIPIENT,token:n,amount:l}]:[],{from:t,to:p,token:n,amount:d}],{chainBatches:r,gasFee:o,spicenetFee:l,netEscrowAmount:d,outputCredit:{chainId:i.chainId,token:n,amount:s}}}async function xa({chainBatches:e,user:t,token:n,grossAmount:s,chainAuthorizations:o}){let r=0n,i=ga({chainBatches:e,user:t,token:n,grossAmount:s,gasFee:r});for(let l=0;l<Uc;l+=1){const c=v.hashChainBatches(i.chainBatches),d=(await f.relayerService.estimateBatchGas({user:t,outputToken:n,chainBatches:i.chainBatches.map((p,m)=>({...p,hash:c[m].hash})),chainAuthorizations:o})).gasFee;if(d===r)return i;r=d,i=ga({chainBatches:e,user:t,token:n,grossAmount:s,gasFee:r})}throw new f.SpiceflowError("INVALID_PARAMS","Action-output fee estimate did not converge. Please retry.")}function pn(e){return v.isSpicenetChainId(e.chainId)}const Lc="0xa9059cbb";function ts(e,t){return`${e}:${v.normalizeNativeTokenAddress(t).toLowerCase()}`}function ya(e,t){return t===v.ZERO_ADDRESS.toLowerCase()?{symbol:f.getChainName(e),decimals:18}:v.getTokenByAddress(t,e)??{symbol:"tokens",decimals:18}}function zc(e,t){const n=v.getTokenByAddress(t,e);return[n?.equivalenceGroup,n?.symbol,n?.name]}async function Eo(e){return f.getWalletBalanceEntries(e)}async function qc(e,t,n){const s=new Map,o=n?.walletFundingRequirement,r=o&&ts(o.chainId,o.token);r&&s.set(r,0n);const i=new Map,l=new Map,c=new Map,d=new Map;for(const m of n?.actionOutputCredits??[]){const h=ts(m.chainId,m.token);d.set(h,(d.get(h)??0n)+m.amount)}for(const m of e){if(pn(m))continue;for(const g of m.tokenTransfers??[]){if(g.from!=="escrow"&&g.from!=="solver"||!f.addressesEqual(g.to,t))continue;const y=BigInt(g.amount??0);if(y<=0n)continue;const w=ts(m.chainId,g.token);i.set(w,(i.get(w)??0n)+y),g.from==="escrow"&&l.set(w,(l.get(w)??0n)+y)}const h=v.getEscrowContract(m.chainId),x=g=>!!h&&h!==v.ZERO_ADDRESS&&f.addressesEqual(g,h);for(const g of m.calls){if(g.value&&g.value>0n){const y=ts(m.chainId,v.ZERO_ADDRESS);s.set(y,(s.get(y)??0n)+g.value),x(g.to)&&c.set(y,(c.get(y)??0n)+g.value)}if(g.data?.startsWith(Lc))try{const y=T.decodeFunctionData({abi:T.erc20Abi,data:g.data});if(y.functionName!=="transfer")continue;const[w,C]=y.args,b=g.to.toLowerCase(),S=ts(m.chainId,b);s.set(S,(s.get(S)??0n)+C),x(w)&&c.set(S,(c.get(S)??0n)+C)}catch{}}}let p=null;for(const[m,h]of l){const x=h-(c.get(m)??0n);if(x<=0n)continue;const[g,y]=m.split(":"),w=Number(g),C=ya(w,y);p??(p=await Eo(t));const b=Kr(p,w,y,zc(w,y));if(!(b>=x))throw new f.SpiceflowError("INVALID_PARAMS",`Insufficient Spice ${C.symbol}: needs ${T.formatUnits(x,C.decimals)}, has ${T.formatUnits(b,C.decimals)}.`,{chainId:w,token:y,userAddress:t,requiredAmount:x.toString(),balance:b.toString(),balanceSource:"spice"})}for(const[m,h]of s){const[x,g]=m.split(":"),y=Number(x);let w=h-(i.get(m)??0n)-(d.get(m)??0n);if(o&&m===r&&o.amount>w&&(w=o.amount),w<=0n)continue;const C=f.getClientForChain(y),b=g===v.ZERO_ADDRESS.toLowerCase()?await C.getBalance({address:t}):await C.readContract({address:g,abi:T.erc20Abi,functionName:"balanceOf",args:[t]});if(b>=w)continue;const S=ya(y,g);throw new f.SpiceflowError("INVALID_PARAMS",`Insufficient ${S.symbol} on ${f.getChainName(y)}: needs ${T.formatUnits(w,S.decimals)}, has ${T.formatUnits(b,S.decimals)}.`,{chainId:y,token:g,userAddress:t,requiredAmount:w.toString(),balance:b.toString(),balanceSource:"wallet"})}}function Hc({chainBatches:e,tokenAddress:t,tokenTransferAmount:n,useCustomTransfers:s}){if(!(e.some(pn)||!(s?e.some(o=>pn(o)?!1:(o.tokenTransfers??[]).some(r=>r.from==="escrow"&&BigInt(r.amount??0)>0n)):n>0n)))throw new f.SpiceflowError("INVALID_PARAMS","Payouts funded from Spice balance require a Spicenet funding batch before the destination chain batch. Deposits into Spice balance and gas-only actions do not need one.",{tokenAddress:t,tokenTransferAmount:n.toString(),useCustomTransfers:!!s})}function Vc(e,t,n,s){t.forEach((o,r)=>{if(!o.to||!o.from||!o.token||o.amount===void 0)throw new f.SpiceflowError("INVALID_TOKEN_TRANSFER",`tokenTransfers[${r}] on chain ${e} is missing required fields (to/from/token/amount). This usually means the embedded wallet wasn't ready when the intent was built \u2014 please retry.`,{chainId:e,transferIndex:r,transfer:{from:o.from,to:o.to,token:o.token,amount:o.amount?.toString()},signingAddress:n,useCustomTransfers:s})})}function Es({user:e,chainBatches:t,tokenAddress:n,tokenTransferAmount:s,exp:o,signature:r,chainAuthorizations:i,useCustomTransfers:l}){const c=t,d=v.hashChainBatches(c),p=c.filter(m=>!pn(m)).length;if(Hc({chainBatches:c,tokenAddress:n,tokenTransferAmount:s,useCustomTransfers:l}),!l&&s>0n&&p>1)throw new f.SpiceflowError("INVALID_PARAMS","Multiple non-Spicenet batches require explicit tokenTransfers. Pass useCustomTransfers with per-batch transfers instead of relying on the default escrow payout injection.",{nonSpicenetBatchCount:p,tokenAddress:n,tokenTransferAmount:s.toString()});return{user:e,...i?{chainAuthorizations:i}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:r,nbf:0,exp:o,chainBatches:d.map((m,h)=>{const x=c[h],g=pn(x)?[]:l?x.tokenTransfers??[]:s>0n?[{from:"escrow",to:e,token:n,amount:s}]:[];return Vc(Number(m.chainId),g,e,l),{hash:m.hash,chainId:Number(m.chainId),tokenTransfers:g,calls:m.calls}})}]}}function wa(e,t){const n=t?.depositToEscrow?.gasFundingSource==="action-output"?t.depositToEscrow:null,s=t?.depositToEscrow&&!n?Wc({chainBatches:e,token:t.depositToEscrow.token,amount:t.depositToEscrow.amount}):Ao(e);return{actionOutputDeposit:n,batches:s}}let Fo=!1;function Fs(){const{address:e,isConnected:t,isAuthenticated:n,actions:s}=f.useWallet(),o=u.useRef(null),{intentStatus:r,startStatusPolling:i,beginStatusTracking:l,applyStepUpdate:c,clearStatus:d}=Tc({checkStepStatus:(w,C)=>f.relayerService.checkStepStatus(w,C),retryStep:async(w,C)=>{const[b,S]=w.split("/"),I=parseInt(S||"0",10);await f.relayerService.executeStep(b,I,C,{action:"execute"})}}),p=u.useRef(s),m=u.useRef(new Map);p.current=s;const h=u.useCallback((w,C,b,S,I)=>Ec({chainBatches:w,signingAddress:C,actions:p.current,cache:m.current,signal:b,onSignatureRequested:S,beforeSign:I}),[]),x=u.useCallback((w,C,b,S)=>Ic(p.current,w,C,b,S),[]),g=u.useCallback(async(w,C,b,S,I,F)=>{const k=(E,R,j)=>{S?.({step:E,message:R,...j})};if(Fo)throw new f.SpiceflowError("CONCURRENT_EXECUTION","A execution transaction is already in progress. Please wait.");Fo=!0;try{if(!e)throw new f.SpiceflowError("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const E=F?.userOverride||e,{actionOutputDeposit:R,batches:j}=wa(w,F);let A=j,M=[],P=F?.useCustomTransfers,N=da(A),B=null;const U=async()=>{for(let D=0;N.length>0&&D<3;D++)try{B=await Eo(E);break}catch(L){if(I?.aborted)throw new f.SpiceflowError("ABORT","Execution transaction aborted");if(D===2)throw new f.SpiceflowError("RELAYER_ERROR","Unable to read your Spice balance. Please try again before submitting the transaction.",{cause:L});await en(1e3)}await F?.validateBeforeSubmit?.(A)};k("building","Preparing your wallet and transaction...");const O=await h(A,E,I,()=>k("signing-delegation","Confirm the authorization in your wallet..."),U);if(k("building","Checking transaction fees and balances..."),I?.aborted)throw new f.SpiceflowError("ABORT","Execution transaction aborted");const z=BigInt(Math.floor(Date.now()/1e3)+3600);if(R){const D=await xa({chainBatches:w,user:E,token:R.token,grossAmount:R.amount,chainAuthorizations:O});A=D.chainBatches,M=[D.outputCredit],P=!0}if(!F?.skipPreSubmitFeeEstimate){let D=!1;if(F?.feeExecutionMode==="user-transfer"&&F.adjustBatchesForEstimate&&f.relayerService.canValidateActionFees()){const L=await f.relayerService.validateActionFees(Es({user:E,chainBatches:A,tokenAddress:C,tokenTransferAmount:b,exp:Number(z),signature:"0x00",chainAuthorizations:O,useCustomTransfers:P}),{signal:I});o.current=L;const $=await F.adjustBatchesForEstimate({feeEstimate:L,chainBatches:A});D=!$||ca(A,$),$&&(A=$)}for(let L=0;!D&&L<10;L++){const $=F?.feeExecutionMode==="user-transfer"?Io(A,E):A,de=Es({user:E,chainBatches:$,tokenAddress:C,tokenTransferAmount:b,exp:Number(z),signature:"0x00",chainAuthorizations:O,useCustomTransfers:P}),ce=await f.relayerService.estimateActionFees(de,{signal:I});o.current=ce;const he=await F?.adjustBatchesForEstimate?.({feeEstimate:ce,chainBatches:A}),X=!!he&&ca(A,he);if(!he||X){D=!0;break}A=he}if(!D)throw new f.SpiceflowError("INVALID_PARAMS","Fee estimate did not converge. Please retry.")}if(F?.prepareForSigning){const D=await F.prepareForSigning(A);if(D.length!==A.length||D.some((L,$)=>L.chainId!==A[$].chainId||L.domain!==A[$].domain))throw new Error("The funded route changed before signing");A=D}F?.resolveActionOutputCredits&&(M=await F.resolveActionOutputCredits()),(!F?.skipUserFundingPreflight||F.walletFundingRequirement)&&await qc(F?.skipUserFundingPreflight?[]:A,E,{actionOutputCredits:M,walletFundingRequirement:F?.walletFundingRequirement}),N=da(A),N.length&&!B&&(B=await f.getWalletBalanceEntries(E)),await F?.validateBeforeSubmit?.(A),k("building","Preparing the signing request...");const q=await x(A,z,I,()=>k("signing-intent","Confirm the transaction in your wallet..."));if(I?.aborted)throw new f.SpiceflowError("ABORT","Execution transaction aborted");k("submitting","Submitting to relayer...");const ue=Es({user:E,chainBatches:A,tokenAddress:C,tokenTransferAmount:b,exp:Number(z),signature:q,chainAuthorizations:O,useCustomTransfers:P}),le=Date.now();await F?.validateBeforeSubmit?.(A),console.debug("[SpiceFlow:execution]",{phase:"submit-check-complete",at:Date.now(),durationMs:Date.now()-le});const G=await f.relayerService.createAction(ue),[ne,re]=G.intentIds[0].split("/"),Y=parseInt(re||"0",10),_=`${ne}/${Y}`;k("executing","Executing on chain..."),k("executing","Executing on chain...",{actionId:ne,intentId:_,intentIndex:Y,totalSteps:A.length});const Z=A.length,pe=await Dc({actionId:ne,intentIndex:Y,intentId:_,totalSteps:Z,signal:I,...B?{delayBeforeSpicenetStepMs:0}:{},isSpicenetStep:D=>pn(A[D]),beforeStep:async D=>{if(!B||!pn(A[D]))return;const L=await kc({deposits:N,baseline:B,fetchEntries:()=>Eo(E),signal:I});if(I?.aborted)throw new f.SpiceflowError("ABORT","Execution transaction aborted");if(!L)throw new f.SpiceflowError("POLLING_EXHAUSTED","Your deposit is still waiting for Spice credit. Check this transaction's status before trying again.",{actionId:ne,intentId:_,stepId:D})},maxExecuteAttemptsForStep:D=>pn(A[D])?6:3,maxPolls:180,onStatusMessage:(D,L)=>{k("executing",D,{txHash:L,actionId:ne,intentId:_,intentIndex:Y,totalSteps:Z})}});if(F?.requireDestinationReceipt){const D=[...A].reverse().find(L=>!pn(L));if(!D)throw new Error("The action has no destination transaction to verify.");await Nc(f.getClientForChain(D.chainId),pe)}return k("success","Transaction successful!",{txHash:pe,actionId:ne,intentId:_,intentIndex:Y,totalSteps:Z}),pe||ne}catch(E){throw console.error("[Execution] Error:",E),k("error",E.message||"Transaction failed",{error:E.message}),E}finally{Fo=!1}},[e,n,h,x]),y=u.useCallback(async(w,C,b,S)=>{if(!e)throw new f.SpiceflowError("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const I=S?.userOverride||e,F=S?.validateFeeCalls===!0&&S.feeExecutionMode==="user-transfer"&&f.relayerService.canValidateActionFees(),{actionOutputDeposit:k,batches:E}=wa(w,S);let R=E;const j=S?.feeExecutionMode==="user-transfer"&&!F?Io(R,I):R,A=S?.signAuthorizationsForEstimate?await h(j,I):void 0;let M=S?.useCustomTransfers;k&&(R=(await xa({chainBatches:w,user:I,token:k.token,grossAmount:k.amount,chainAuthorizations:A})).chainBatches,M=!0);const P=S?.feeExecutionMode==="user-transfer"&&!F?Io(R,I):R,N=Es({user:I,chainBatches:P,tokenAddress:C,tokenTransferAmount:b,exp:Math.floor(Date.now()/1e3)+3600,signature:"0x00",chainAuthorizations:A,useCustomTransfers:M}),B=await(F?f.relayerService.validateActionFees(N,{signal:S?.signal}):f.relayerService.estimateActionFees(N,{signal:S?.signal}));return o.current=B,B},[e,h]);return{execute:g,estimate:y,lastFeeEstimate:o.current,hasEmbeddedWallet:t&&n,intentStatus:r,startStatusPolling:i,beginStatusTracking:l,applyStepUpdate:c,clearStatus:d}}const To=({color:e})=>a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:[a.jsx("circle",{cx:"7",cy:"7",r:"6.5",stroke:e,strokeWidth:"1.2"}),a.jsx("path",{d:"M7 6v4",stroke:e,strokeWidth:"1.2",strokeLinecap:"round"}),a.jsx("circle",{cx:"7",cy:"4.5",r:"0.7",fill:e})]}),ba=({content:e,label:t="More info",textColor:n="#f9fafb",backgroundColor:s="#111827",borderColor:o="rgba(255,255,255,0.08)",accentColor:r="#9ca3af",children:i})=>{const l=u.useId(),[c,d]=u.useState(!1),p=u.useRef(null),[m,h]=u.useState(!1),[x,g]=u.useState(null);u.useEffect(()=>{h(!0)},[]),u.useLayoutEffect(()=>{if(!c||!p.current)return;const w=()=>{if(!p.current)return;const C=p.current.getBoundingClientRect(),b=Math.min(220,window.innerWidth-48),S=Math.min(Math.max(C.left+C.width/2,24+b/2),window.innerWidth-24-b/2),I=C.top>84;g({top:I?C.top-10:C.bottom+10,left:S,placement:I?"top":"bottom"})};return w(),window.addEventListener("scroll",w,!0),window.addEventListener("resize",w),()=>{window.removeEventListener("scroll",w,!0),window.removeEventListener("resize",w)}},[c]);const y=c&&m&&x?jn.createPortal(a.jsxs("span",{id:l,role:"tooltip",style:{position:"fixed",left:x.left,top:x.top,transform:x.placement==="top"?"translate(-50%, -100%)":"translate(-50%, 0)",width:"220px",maxWidth:"min(220px, calc(100vw - 48px))",padding:"10px 12px",borderRadius:"10px",backgroundColor:s,color:n,border:`1px solid ${o}`,boxShadow:"0 18px 45px rgba(0,0,0,0.28)",fontSize:"11px",lineHeight:"1.45",fontWeight:500,textAlign:"left",zIndex:f.z.tooltip,pointerEvents:"none"},children:[e,a.jsx("span",{"aria-hidden":"true",style:{position:"absolute",left:"50%",width:"10px",height:"10px",transform:"translateX(-50%) rotate(45deg)",backgroundColor:s,...x.placement==="top"?{bottom:"-6px",borderRight:`1px solid ${o}`,borderBottom:`1px solid ${o}`}:{top:"-6px",borderTop:`1px solid ${o}`,borderLeft:`1px solid ${o}`}}})]}),document.body):null;return a.jsxs(a.Fragment,{children:[a.jsx("span",{ref:p,style:{position:"relative",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),children:a.jsx("button",{type:"button","aria-label":t,"aria-describedby":c?l:void 0,onFocus:()=>d(!0),onBlur:()=>d(!1),style:{width:"18px",height:"18px",borderRadius:"999px",display:"inline-flex",alignItems:"center",justifyContent:"center",border:`1px solid ${o}`,backgroundColor:"transparent",color:r,cursor:"help",padding:0,outline:"none",boxShadow:c?`0 0 0 2px ${r}26`:"none",transition:"border-color 120ms ease, box-shadow 120ms ease, color 120ms ease"},children:i||a.jsx(To,{color:r})})}),y]})},ns=(e,t,n,s)=>({width:e,height:e,fill:"none",className:t,"aria-hidden":n??!0,style:s}),Mn=({size:e=16,color:t="currentColor",strokeWidth:n=2,direction:s="down",className:o,style:r,"aria-hidden":i})=>a.jsx("svg",{...ns(e,o,i,{transform:s==="up"?"rotate(180deg)":void 0,transition:"transform 0.3s ease",...r}),viewBox:"0 0 16 16",children:a.jsx("path",{d:"M4 6L8 10L12 6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),Qc=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:s,style:o,"aria-hidden":r})=>a.jsxs("svg",{...ns(e,s,r,o),viewBox:"0 0 24 24",children:[a.jsx("circle",{cx:"11",cy:"11",r:"8",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"}),a.jsx("path",{d:"m21 21-4.3-4.3",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})]}),Gc=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:s,style:o,"aria-hidden":r})=>a.jsx("svg",{...ns(e,s,r,o),viewBox:"0 0 24 24",children:a.jsx("path",{d:"m6 9 6 6 6-6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),Yc=({size:e=24,color:t="currentColor",strokeWidth:n=2,className:s,style:o,"aria-hidden":r})=>a.jsx("svg",{...ns(e,s,r,o),viewBox:"0 0 24 24",children:a.jsx("path",{d:"m9 18 6-6-6-6",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})}),Ca=({size:e=14,color:t="currentColor",strokeWidth:n=2,className:s,style:o,"aria-hidden":r})=>a.jsx("svg",{...ns(e,s,r,o),viewBox:"0 0 16 16",children:a.jsx("path",{d:"M3 8L6.5 11.5L13 5",stroke:t,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"})});function Ts(e,t){if(e===0n)return"0";const n=10n**BigInt(t),s=e/n,o=(e%n).toString().padStart(t,"0").replace(/0+$/,"");return o?`${s.toString()}.${o}`:s.toString()}function jo(e,t,n){const s=`${Ts(e,t)} ${n}`;return e===0n?s:`-${s}`}const Kc=({fontFamily:e,textPrimary:t,textSecondary:n,cardBg:s,cardBorder:o,resolvedDark:r,darkCardBorder:i,primaryColor:l,feePreview:c,asset:d,isLoading:p,errorText:m,directExecutionFeeNote:h=!1})=>{const x=f.useAssetDisplay(),g=d&&c&&[d.symbol,d.displaySymbol,d.receiptTokenName].includes(c.symbol)?x(d).symbol:c?.symbol,y=r?i??o:"#e5e7eb",w=r?"#111214":"#111827",C=r?"rgba(255,255,255,0.08)":"rgba(17,24,39,0.12)",b="#f87171",S=r?"#d1d5db":"#4b5563",I=r?"#f3f4f6":t,[F,k]=u.useState(!1),E=!!m,R=E?null:c,j=R?[{label:"Total Required",help:"Total amount required to fund this action.",value:`${Ts(R.grossAmount,R.decimals)} ${g}`,tone:"default"},{label:"Spicenet Fee",help:"Fees paid to Spicenet for intent processing and execution.",value:jo(R.spicenetFee,R.decimals,g),tone:"fee"},{label:"Network Fee",help:"Network fee shown in the same token you are using for this action.",value:jo(R.gasFee,R.decimals,g),tone:"fee"},...R.bridgeFee&&R.bridgeFee>0n?[{label:"Bridge Fee",help:"Estimated cost to rebalance liquidity for this action.",value:jo(R.bridgeFee,R.decimals,g),tone:"fee"}]:[],{label:"Used in TX",help:"Resulting amount of funds used in the transaction.",value:`${Ts(R.netAmount,R.decimals)} ${g}`,tone:"default"}]:[],A=R?`${Ts(R.grossAmount,R.decimals)} ${g}`:null;return E?a.jsx("div",{style:{backgroundColor:s,border:`1px solid ${o}`,borderRadius:r?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",boxShadow:r?"inset 0 1px 0 rgba(255,255,255,0.03)":"none"},children:a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"10px"},children:[a.jsx("span",{style:{fontSize:"17px",fontWeight:500,color:S,fontFamily:e,lineHeight:"24px"},children:"Fee"}),a.jsx("div",{style:{color:b,fontSize:"12px",lineHeight:"1.55",fontFamily:e},children:m})]})}):a.jsxs("div",{style:{backgroundColor:s,border:`1px solid ${o}`,borderRadius:r?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",boxShadow:r?"inset 0 1px 0 rgba(255,255,255,0.03)":"none"},children:[a.jsxs("button",{type:"button",onClick:()=>k(M=>!M),style:{display:"flex",justifyContent:"space-between",alignItems:"center",width:"100%",gap:"12px",marginBottom:F?"14px":0,background:"none",border:"none",padding:0,cursor:"pointer",textAlign:"left"},children:[a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px"},children:[a.jsx("span",{style:{fontSize:"17px",fontWeight:500,color:S,fontFamily:e,lineHeight:"24px"},children:"Fee"}),F&&a.jsx("span",{style:{fontSize:"12px",color:n,fontFamily:e,lineHeight:"1.45"},children:"What is funded, spent, and taken as fees"})]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",flexShrink:0},children:[A&&a.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:"2px",minWidth:0},children:[a.jsx("span",{style:{fontSize:"10px",fontWeight:700,color:n,fontFamily:e,letterSpacing:"0.08em",textTransform:"uppercase"},children:"Total required"}),a.jsx("span",{style:{fontSize:"14px",fontWeight:700,color:I,fontFamily:e,whiteSpace:"nowrap"},children:A})]}),p&&!h&&a.jsx("span",{style:{fontSize:"11px",fontWeight:600,color:l,fontFamily:e,padding:"6px 9px",borderRadius:"999px",backgroundColor:r?"rgba(255,255,255,0.04)":"rgba(0,0,0,0.035)",border:`1px solid ${r?y:"rgba(0,0,0,0.06)"}`,whiteSpace:"nowrap"},children:"Recalculating"}),a.jsx(Mn,{color:n,direction:F?"up":"down",style:{flexShrink:0}})]})]}),a.jsx("div",{style:{overflow:"hidden",maxHeight:F?"480px":"0px",opacity:F?1:0,transition:"max-height 0.24s ease, opacity 0.18s ease"},children:h?a.jsx("p",{style:{margin:0,color:n,fontSize:"12px",lineHeight:"1.55",fontFamily:e},children:"This path executes directly from the external wallet. Network gas is shown and paid in your wallet. No Spicenet fee is charged."}):j.length>0?a.jsxs(a.Fragment,{children:[a.jsx("div",{style:{display:"grid",gap:"10px"},children:j.map((M,P)=>a.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) auto",alignItems:"center",gap:"12px",paddingTop:P===0?0:"10px",borderTop:P===0?"none":`1px solid ${y}`,opacity:p?.74:1,transition:"opacity 120ms ease"},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0},children:[a.jsx("span",{style:{fontSize:"12px",color:n,fontFamily:e,fontWeight:500},children:M.label}),a.jsx(ba,{content:M.help,label:`${M.label} info`,textColor:"#f9fafb",backgroundColor:w,borderColor:C,accentColor:r?"#8f96a3":"#6b7280"})]}),a.jsx("span",{style:{fontSize:"12px",color:M.tone==="fee"?b:I,fontFamily:f.font.mono,textAlign:"right",fontWeight:M.label==="Used in TX"?600:500,letterSpacing:"-0.01em"},children:M.value})]},M.label))}),a.jsx("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:`1px solid ${y}`,fontSize:"11px",color:n,fontFamily:e,lineHeight:"1.45"},children:R?.gasQuoteSource==="estimated"?"Gas quote uses a live estimate.":R?.gasQuoteSource==="configured_fallback"?"Gas quote uses a configured fallback.":"Gas quote is currently zero."})]}):a.jsx("div",{style:{fontSize:"12px",color:m?b:n,fontFamily:e,opacity:m?1:.8,lineHeight:"1.5"},children:m||"Waiting for fee estimate..."})})]})},Bo=u.memo(Kc),ss=({size:e=20,strokeWidth:t=2,color:n="currentColor",style:s})=>a.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:s,children:[a.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]});var va="data:image/svg+xml,%3csvg width='108' height='22' viewBox='0 0 108 22' fill='none' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M1.9916 11.9854V11.2041H3.98379C4.48835 11.2041 4.87897 11.0739 5.15566 10.8135C5.43236 10.5498 5.5707 10.1868 5.5707 9.72461V9.71484C5.5707 9.24935 5.43236 8.88639 5.15566 8.62598C4.87897 8.36556 4.48835 8.23535 3.98379 8.23535H1.9916V7.4541H4.2084C4.65111 7.4541 5.04173 7.5485 5.38027 7.7373C5.71882 7.92611 5.98411 8.18978 6.17617 8.52832C6.37148 8.86686 6.46914 9.25911 6.46914 9.70508V9.71484C6.46914 10.1608 6.37148 10.5547 6.17617 10.8965C5.98411 11.2383 5.71882 11.5052 5.38027 11.6973C5.04173 11.8893 4.65111 11.9854 4.2084 11.9854H1.9916ZM1.55215 14.5V7.4541H2.43106V14.5H1.55215ZM9.51875 14.5928C9.0207 14.5928 8.58939 14.4837 8.2248 14.2656C7.86348 14.0443 7.58353 13.7301 7.38496 13.3232C7.18965 12.9163 7.09199 12.4329 7.09199 11.873V11.8633C7.09199 11.3001 7.18965 10.8151 7.38496 10.4082C7.58353 10.0013 7.86348 9.6888 8.2248 9.4707C8.58939 9.2526 9.0207 9.14355 9.51875 9.14355C10.0201 9.14355 10.4514 9.2526 10.8127 9.4707C11.174 9.6888 11.4523 10.0013 11.6477 10.4082C11.8462 10.8151 11.9455 11.3001 11.9455 11.8633V11.873C11.9455 12.4329 11.8462 12.9163 11.6477 13.3232C11.4523 13.7301 11.174 14.0443 10.8127 14.2656C10.4514 14.4837 10.0201 14.5928 9.51875 14.5928ZM9.51875 13.8408C9.85078 13.8408 10.1324 13.7627 10.3635 13.6064C10.5946 13.4502 10.7704 13.2256 10.8908 12.9326C11.0145 12.6396 11.0764 12.2865 11.0764 11.873V11.8633C11.0764 11.4466 11.0145 11.0918 10.8908 10.7988C10.7704 10.5059 10.5946 10.2829 10.3635 10.1299C10.1324 9.97363 9.85078 9.89551 9.51875 9.89551C9.18672 9.89551 8.90514 9.97363 8.67402 10.1299C8.4429 10.2829 8.26549 10.5059 8.1418 10.7988C8.02135 11.0918 7.96113 11.4466 7.96113 11.8633V11.873C7.96113 12.2865 8.02135 12.6396 8.1418 12.9326C8.26549 13.2256 8.4429 13.4502 8.67402 13.6064C8.90514 13.7627 9.18672 13.8408 9.51875 13.8408ZM13.7842 14.5L12.3096 9.23633H13.1592L14.1943 13.4453H14.2725L15.4492 9.23633H16.2549L17.4316 13.4453H17.5098L18.5449 9.23633H19.3896L17.915 14.5H17.0605L15.8838 10.4277H15.8057L14.6338 14.5H13.7842ZM22.1658 14.5928C21.6645 14.5928 21.2332 14.4821 20.8719 14.2607C20.5138 14.0394 20.2371 13.7269 20.0418 13.3232C19.8497 12.9163 19.7537 12.4378 19.7537 11.8877V11.8828C19.7537 11.3392 19.8497 10.8623 20.0418 10.4521C20.2371 10.042 20.5122 9.72135 20.867 9.49023C21.2218 9.25911 21.6368 9.14355 22.1121 9.14355C22.5906 9.14355 23.0008 9.25423 23.3426 9.47559C23.6876 9.69694 23.9513 10.0062 24.1336 10.4033C24.3191 10.7972 24.4119 11.2562 24.4119 11.7803V12.1123H20.1932V11.4336H23.9773L23.5574 12.0537V11.7168C23.5574 11.3034 23.4956 10.9632 23.3719 10.6963C23.2482 10.4294 23.0773 10.2308 22.8592 10.1006C22.6411 9.96712 22.3904 9.90039 22.1072 9.90039C21.824 9.90039 21.5701 9.97038 21.3455 10.1104C21.1242 10.2471 20.9484 10.4505 20.8182 10.7207C20.688 10.9909 20.6229 11.3229 20.6229 11.7168V12.0537C20.6229 12.4281 20.6863 12.7487 20.8133 13.0156C20.9402 13.2793 21.1209 13.4827 21.3553 13.626C21.5896 13.766 21.8663 13.8359 22.1854 13.8359C22.423 13.8359 22.6297 13.8034 22.8055 13.7383C22.9813 13.6732 23.1261 13.5902 23.24 13.4893C23.354 13.3883 23.4337 13.2858 23.4793 13.1816L23.4988 13.1377H24.3484L24.3387 13.1768C24.2931 13.3558 24.2117 13.5299 24.0945 13.6992C23.9806 13.8652 23.8325 14.0166 23.6502 14.1533C23.4679 14.2868 23.2514 14.3942 23.0008 14.4756C22.7534 14.5537 22.4751 14.5928 22.1658 14.5928ZM25.4303 14.5V9.23633H26.2799V10.0176H26.358C26.4589 9.74089 26.6298 9.52604 26.8707 9.37305C27.1116 9.22005 27.4094 9.14355 27.7643 9.14355C27.8456 9.14355 27.9254 9.14844 28.0035 9.1582C28.0849 9.16471 28.1467 9.17122 28.1891 9.17773V10.0029C28.1012 9.98665 28.0149 9.97526 27.9303 9.96875C27.8489 9.95898 27.761 9.9541 27.6666 9.9541C27.3964 9.9541 27.1572 10.0078 26.9488 10.1152C26.7405 10.2227 26.5761 10.3724 26.4557 10.5645C26.3385 10.7565 26.2799 10.9811 26.2799 11.2383V14.5H25.4303ZM30.9408 14.5928C30.4395 14.5928 30.0082 14.4821 29.6469 14.2607C29.2888 14.0394 29.0121 13.7269 28.8168 13.3232C28.6247 12.9163 28.5287 12.4378 28.5287 11.8877V11.8828C28.5287 11.3392 28.6247 10.8623 28.8168 10.4521C29.0121 10.042 29.2872 9.72135 29.642 9.49023C29.9968 9.25911 30.4118 9.14355 30.8871 9.14355C31.3656 9.14355 31.7758 9.25423 32.1176 9.47559C32.4626 9.69694 32.7263 10.0062 32.9086 10.4033C33.0941 10.7972 33.1869 11.2562 33.1869 11.7803V12.1123H28.9682V11.4336H32.7523L32.3324 12.0537V11.7168C32.3324 11.3034 32.2706 10.9632 32.1469 10.6963C32.0232 10.4294 31.8523 10.2308 31.6342 10.1006C31.4161 9.96712 31.1654 9.90039 30.8822 9.90039C30.599 9.90039 30.3451 9.97038 30.1205 10.1104C29.8992 10.2471 29.7234 10.4505 29.5932 10.7207C29.463 10.9909 29.3979 11.3229 29.3979 11.7168V12.0537C29.3979 12.4281 29.4613 12.7487 29.5883 13.0156C29.7152 13.2793 29.8959 13.4827 30.1303 13.626C30.3646 13.766 30.6413 13.8359 30.9604 13.8359C31.198 13.8359 31.4047 13.8034 31.5805 13.7383C31.7563 13.6732 31.9011 13.5902 32.015 13.4893C32.129 13.3883 32.2087 13.2858 32.2543 13.1816L32.2738 13.1377H33.1234L33.1137 13.1768C33.0681 13.3558 32.9867 13.5299 32.8695 13.6992C32.7556 13.8652 32.6075 14.0166 32.4252 14.1533C32.2429 14.2868 32.0264 14.3942 31.7758 14.4756C31.5284 14.5537 31.2501 14.5928 30.9408 14.5928ZM36.1486 14.5928C35.7059 14.5928 35.3186 14.4805 34.9865 14.2559C34.6545 14.0312 34.3973 13.7155 34.215 13.3086C34.0328 12.8984 33.9416 12.4199 33.9416 11.873V11.8633C33.9416 11.3132 34.0328 10.8346 34.215 10.4277C34.3973 10.0208 34.6529 9.70508 34.9816 9.48047C35.3137 9.25586 35.7027 9.14355 36.1486 9.14355C36.3895 9.14355 36.6158 9.18262 36.8273 9.26074C37.0422 9.33561 37.2326 9.44141 37.3986 9.57812C37.5647 9.71484 37.6949 9.8776 37.7893 10.0664H37.8674V7.14648H38.717V14.5H37.8674V13.6602H37.7893C37.6818 13.8555 37.5467 14.0231 37.384 14.1631C37.2212 14.2998 37.0357 14.4056 36.8273 14.4805C36.619 14.5553 36.3928 14.5928 36.1486 14.5928ZM36.3439 13.8408C36.663 13.8408 36.938 13.7611 37.1691 13.6016C37.4003 13.4421 37.5777 13.2158 37.7014 12.9229C37.8251 12.6266 37.8869 12.2767 37.8869 11.873V11.8633C37.8869 11.4564 37.8251 11.1064 37.7014 10.8135C37.5777 10.5205 37.4003 10.2943 37.1691 10.1348C36.938 9.97526 36.663 9.89551 36.3439 9.89551C36.0249 9.89551 35.7499 9.97526 35.5188 10.1348C35.2909 10.291 35.1151 10.5156 34.9914 10.8086C34.871 11.1016 34.8107 11.4531 34.8107 11.8633V11.873C34.8107 12.2799 34.871 12.6315 34.9914 12.9277C35.1151 13.2207 35.2909 13.4469 35.5188 13.6064C35.7499 13.7627 36.0249 13.8408 36.3439 13.8408ZM45.1775 14.5928C44.9334 14.5928 44.7072 14.5553 44.4988 14.4805C44.2905 14.4056 44.1049 14.2998 43.9422 14.1631C43.7794 14.0231 43.6443 13.8555 43.5369 13.6602H43.4588V14.5H42.6092V7.14648H43.4588V10.0664H43.5369C43.6346 9.8776 43.7648 9.71484 43.9275 9.57812C44.0936 9.44141 44.2824 9.33561 44.4939 9.26074C44.7088 9.18262 44.9367 9.14355 45.1775 9.14355C45.6235 9.14355 46.0109 9.25586 46.3396 9.48047C46.6717 9.70508 46.9288 10.0208 47.1111 10.4277C47.2934 10.8346 47.3846 11.3132 47.3846 11.8633V11.873C47.3846 12.4199 47.2934 12.8984 47.1111 13.3086C46.9288 13.7155 46.6717 14.0312 46.3396 14.2559C46.0109 14.4805 45.6235 14.5928 45.1775 14.5928ZM44.9822 13.8408C45.3045 13.8408 45.5796 13.7627 45.8074 13.6064C46.0353 13.4469 46.2094 13.2207 46.3299 12.9277C46.4536 12.6315 46.5154 12.2799 46.5154 11.873V11.8633C46.5154 11.4531 46.4536 11.1016 46.3299 10.8086C46.2094 10.5156 46.0353 10.291 45.8074 10.1348C45.5796 9.97526 45.3045 9.89551 44.9822 9.89551C44.6632 9.89551 44.3881 9.97526 44.157 10.1348C43.9259 10.2943 43.7485 10.5205 43.6248 10.8135C43.5011 11.1064 43.4393 11.4564 43.4393 11.8633V11.873C43.4393 12.2767 43.5011 12.6266 43.6248 12.9229C43.7485 13.2158 43.9259 13.4421 44.157 13.6016C44.3881 13.7611 44.6632 13.8408 44.9822 13.8408ZM48.6568 16.3457C48.6015 16.3457 48.5396 16.3424 48.4713 16.3359C48.4029 16.3327 48.3395 16.3262 48.2809 16.3164V15.6182C48.3329 15.6279 48.3899 15.6344 48.4518 15.6377C48.5136 15.641 48.5738 15.6426 48.6324 15.6426C48.8733 15.6426 49.0702 15.5807 49.2232 15.457C49.3795 15.3333 49.5048 15.1201 49.5992 14.8174L49.6969 14.5049L47.7486 9.23633H48.6568L50.2779 14.0996L49.941 13.5674H50.3414L50.0045 14.0996L51.6207 9.23633H52.5143L50.4586 14.8223C50.3154 15.2161 50.164 15.5238 50.0045 15.7451C49.845 15.9665 49.6578 16.1211 49.443 16.209C49.2314 16.3001 48.9693 16.3457 48.6568 16.3457Z' fill='%230E0D0B'/%3e%3cpath d='M62.7081 13.27C62.742 13.27 62.7642 13.3057 62.7491 13.3362V13.336L61.1229 16.6083C61.0892 16.6761 60.9926 16.6759 60.959 16.6083L59.3382 13.336C59.3232 13.3057 59.3453 13.27 59.3792 13.27H62.7081Z' fill='%23EA4B4B'/%3e%3cpath d='M61.0026 9.71913C61.0194 9.68524 61.0678 9.68524 61.0845 9.71913L62.747 13.0897C62.762 13.12 62.7399 13.1557 62.706 13.1557H59.3763C59.3424 13.1557 59.3203 13.12 59.3353 13.0897L61.0026 9.71913Z' fill='%23EA4B4B'/%3e%3cpath d='M60.8426 9.63827C60.8766 9.63827 60.8987 9.6741 60.8835 9.70444L59.2164 13.0594C59.1995 13.0932 59.1513 13.0932 59.1345 13.0594L57.5001 9.77047C57.47 9.70962 57.5142 9.63827 57.5821 9.63827H60.8426Z' fill='%23EA4B4B'/%3e%3cpath d='M64.5036 9.63617C64.5715 9.63618 64.6157 9.70753 64.5855 9.76838H64.5854L62.9512 13.0573C62.9344 13.0911 62.8862 13.0912 62.8692 13.0573L61.2021 9.70235C61.187 9.672 61.2091 9.63617 61.2431 9.63617H64.5036Z' fill='%23EA4B4B'/%3e%3cpath d='M62.8284 6.18281C62.862 6.11518 62.9586 6.11518 62.9922 6.18281L64.5855 9.38969C64.6157 9.45054 64.5715 9.52189 64.5036 9.52189H61.2431C61.2091 9.52189 61.187 9.48605 61.2021 9.45571L62.8283 6.18265L62.8284 6.18281Z' fill='%23EA4B4B'/%3e%3cpath d='M62.3131 6.13196C62.381 6.13196 62.4252 6.20331 62.3951 6.26416C62.154 6.74935 61.9128 7.23455 61.6718 7.71975H61.6716C61.4225 8.22125 61.1733 8.72259 60.9242 9.22409C60.9074 9.25799 60.859 9.25799 60.8422 9.22409L60.6305 8.79587C60.6275 8.78957 60.6259 8.78263 60.6259 8.77553V6.22349C60.6259 6.17297 60.6668 6.13196 60.7173 6.13196H62.3131Z' fill='%23EA4B4B'/%3e%3cpath fill-rule='evenodd' clip-rule='evenodd' d='M74.8537 10.0096C75.2721 10.0096 75.654 10.1125 75.9993 10.3184C76.3513 10.5177 76.6303 10.8032 76.8361 11.1751C77.0487 11.547 77.1549 11.9953 77.1549 12.52V12.6495C77.1549 13.1675 77.052 13.6158 76.8461 13.9943C76.6402 14.3729 76.3613 14.6618 76.0093 14.861C75.664 15.0603 75.2788 15.1599 74.8537 15.1599C74.515 15.1599 74.2261 15.1134 73.9871 15.0204C73.7546 14.9341 73.5653 14.8212 73.4192 14.6817C73.2731 14.5423 73.1602 14.3995 73.0805 14.2534H72.941V16.9659L72.1541 16.0013V10.1491H72.9211V10.956H73.0352C73.2729 10.6733 73.3893 10.4911 73.6683 10.2985C73.9538 10.1059 74.349 10.0096 74.8537 10.0096ZM74.6445 10.7069C74.1464 10.7069 73.7347 10.8696 73.4092 11.195C73.0905 11.5138 72.9311 11.9621 72.9311 12.5399V12.6296C72.9311 13.2074 73.0905 13.659 73.4092 13.9844C73.7347 14.3032 74.1464 14.4626 74.6445 14.4626C75.1492 14.4626 75.5577 14.3032 75.8698 13.9844C76.1886 13.659 76.348 13.2074 76.348 12.6296V12.5399C76.348 11.9621 76.1886 11.5138 75.8698 11.195C75.5577 10.8696 75.1492 10.7069 74.6445 10.7069Z' fill='%230E0D0B'/%3e%3cpath d='M78.5848 11.9583L78.5555 15.4596L77.7681 14.4846V10.9583L78.5848 11.9583Z' fill='%230E0D0B'/%3e%3cpath d='M101.588 10.2986H102.444L103 10.986H101.588V10.9867H100.802L101.588 11.9623V14.1937C101.588 14.3929 101.685 14.4926 101.877 14.4926H102.379L102.928 15.17H101.668C101.389 15.17 101.173 15.0936 101.021 14.9409C100.874 14.7881 100.801 14.5789 100.801 14.3133V10.986H99.8799L99.3217 10.2986H100.801V9.13501H101.588V10.2986Z' fill='%230E0D0B'/%3e%3cpath d='M69.0133 7.90764C69.4848 7.90764 69.9065 7.99068 70.2784 8.15671C70.6569 8.3161 70.9525 8.55517 71.165 8.87395C71.3842 9.18609 71.4938 9.58126 71.4938 10.0594V10.4778H70.667V10.0594C70.667 9.72072 70.5939 9.44842 70.4477 9.24254C70.3083 9.03666 70.1124 8.88392 69.86 8.7843C69.6143 8.68469 69.332 8.63487 69.0133 8.63487C68.555 8.63487 68.1864 8.7378 67.9075 8.94367C67.6286 9.14291 67.4891 9.4285 67.4891 9.80041C67.4891 10.0461 67.5488 10.2453 67.6684 10.3981C67.7879 10.5508 67.9573 10.677 68.1764 10.7767C68.3956 10.8696 68.658 10.9527 68.9635 11.0257L69.4815 11.1552C69.8866 11.2416 70.2485 11.3611 70.5673 11.5138C70.8927 11.6599 71.1517 11.8625 71.3443 12.1215C71.5369 12.3739 71.6332 12.706 71.6332 13.1177C71.6332 13.5295 71.5303 13.8881 71.3244 14.1936C71.1185 14.4991 70.8263 14.7382 70.4477 14.9109C70.0758 15.0769 69.6375 15.1599 69.1328 15.1599C68.6281 15.1599 68.1765 15.0702 67.778 14.8909C67.3795 14.7116 67.0641 14.4426 66.8316 14.084C66.6058 13.7187 66.4929 13.2638 66.4929 12.7192V12.51H67.3197V12.7192C67.3197 13.297 67.4891 13.7287 67.8278 14.0143C68.1665 14.2932 68.6015 14.4327 69.1328 14.4327C69.6774 14.4327 70.0924 14.3098 70.378 14.0641C70.6636 13.8183 70.8064 13.5095 70.8064 13.1376C70.8064 12.8786 70.74 12.6727 70.6072 12.52C70.481 12.3673 70.3017 12.2444 70.0692 12.1514C69.8368 12.0518 69.5645 11.9655 69.2523 11.8924L68.7343 11.7629C68.3292 11.6566 67.9706 11.5271 67.6584 11.3744C67.3463 11.2216 67.1006 11.0224 66.9213 10.7767C66.7486 10.5243 66.6623 10.2022 66.6623 9.81035C66.6623 9.41852 66.7585 9.07981 66.9511 8.79424C67.1504 8.50866 67.426 8.28953 67.778 8.13678C68.1366 7.98404 68.5484 7.90764 69.0133 7.90764Z' fill='%230E0D0B'/%3e%3cpath d='M81.6544 10.0096C82.1193 10.0096 82.5145 10.0959 82.8399 10.2686C83.1719 10.4412 83.431 10.6704 83.6169 10.956C83.8095 11.2415 83.9324 11.5471 83.9855 11.8725L83.2185 12.0318C83.1853 11.7928 83.1056 11.5736 82.9794 11.3744C82.8598 11.1752 82.6905 11.0158 82.4713 10.8962C82.2521 10.7767 81.9832 10.7169 81.6644 10.7169C81.339 10.7169 81.0468 10.7899 80.7877 10.936C80.5354 11.0821 80.3328 11.2914 80.1801 11.5637C80.034 11.836 79.9609 12.1614 79.9609 12.5399V12.6296C79.9609 13.0081 80.034 13.3335 80.1801 13.6058C80.3328 13.8781 80.5354 14.0873 80.7877 14.2334C81.0468 14.3795 81.339 14.4526 81.6644 14.4526C82.1492 14.4526 82.5178 14.3264 82.7702 14.0741C83.0292 13.8217 83.1886 13.5095 83.2483 13.1376L84.0254 13.307C83.9523 13.6257 83.8195 13.9279 83.6269 14.2135C83.4343 14.4991 83.172 14.7282 82.8399 14.9009C82.5145 15.0735 82.1193 15.1599 81.6544 15.1599C81.1829 15.1599 80.7579 15.0603 80.3793 14.861C80.0074 14.6551 79.7119 14.363 79.4927 13.9844C79.2802 13.6059 79.1739 13.1575 79.1739 12.6395V12.5299C79.1739 12.0053 79.2802 11.557 79.4927 11.1851C79.7119 10.8066 80.0074 10.5177 80.3793 10.3184C80.7579 10.1126 81.1829 10.0096 81.6544 10.0096Z' fill='%230E0D0B'/%3e%3cpath fill-rule='evenodd' clip-rule='evenodd' d='M86.7515 10.0096C87.2097 10.0096 87.6149 10.1092 87.9668 10.3084C88.3188 10.501 88.5944 10.78 88.7937 11.1452C88.9929 11.5105 89.0925 11.9389 89.0925 12.4304V12.7889H85.1177C85.1377 13.3136 85.3071 13.7254 85.6258 14.0243C85.9446 14.3165 86.3431 14.4626 86.8212 14.4626C87.2396 14.4626 87.5617 14.3663 87.7875 14.1737C88.0133 13.9811 88.186 13.752 88.3056 13.4863L88.983 13.815C88.8833 14.0209 88.7439 14.2268 88.5646 14.4327C88.3919 14.6386 88.1628 14.8113 87.8772 14.9507C87.5983 15.0902 87.2396 15.1599 86.8013 15.1599C86.3099 15.1599 85.8782 15.057 85.5063 14.8511C85.1344 14.6386 84.8455 14.343 84.6396 13.9645C84.4337 13.5859 84.3307 13.1476 84.3307 12.6495V12.5299C84.3307 12.0252 84.4337 11.5836 84.6396 11.205C84.8455 10.8265 85.1311 10.5342 85.4963 10.3284C85.8616 10.1159 86.28 10.0096 86.7515 10.0096ZM86.7515 10.7069C86.3066 10.7069 85.9413 10.8331 85.6557 11.0855C85.3701 11.3378 85.1941 11.6898 85.1277 12.1414H88.2956C88.269 11.6898 88.113 11.3378 87.8274 11.0855C87.5485 10.8331 87.1898 10.7069 86.7515 10.7069Z' fill='%230E0D0B'/%3e%3cpath fill-rule='evenodd' clip-rule='evenodd' d='M97.1624 10.0096C97.6207 10.0096 98.0258 10.1092 98.3778 10.3084C98.7298 10.501 99.0054 10.78 99.2046 11.1452C99.4039 11.5105 99.5035 11.9389 99.5035 12.4304V12.7889H95.5287C95.5487 13.3136 95.718 13.7254 96.0368 14.0243C96.3555 14.3165 96.754 14.4626 97.2322 14.4626C97.6505 14.4626 97.9727 14.3663 98.1985 14.1737C98.4243 13.9811 98.5969 13.752 98.7165 13.4863L99.3939 13.815C99.2943 14.0209 99.1548 14.2268 98.9755 14.4327C98.8028 14.6386 98.5737 14.8113 98.2881 14.9507C98.0092 15.0902 97.6506 15.1599 97.2123 15.1599C96.7208 15.1599 96.2892 15.057 95.9172 14.8511C95.5453 14.6386 95.2564 14.343 95.0505 13.9645C94.8446 13.5859 94.7417 13.1476 94.7417 12.6495V12.5299C94.7417 12.0252 94.8446 11.5836 95.0505 11.205C95.2564 10.8265 95.542 10.5342 95.9073 10.3284C96.2725 10.1158 96.6909 10.0096 97.1624 10.0096ZM97.1624 10.7069C96.7175 10.7069 96.3522 10.8331 96.0666 11.0855C95.7811 11.3378 95.6051 11.6898 95.5387 12.1414H98.7066C98.68 11.6898 98.5239 11.3378 98.2383 11.0855C97.9594 10.8331 97.6008 10.7069 97.1624 10.7069Z' fill='%230E0D0B'/%3e%3cpath d='M92.2484 10.0594C92.6137 10.0594 92.9391 10.1358 93.2247 10.2885C93.5169 10.4413 93.7494 10.6671 93.9221 10.966C94.0947 11.2648 94.1811 11.6334 94.1811 12.0717V15.1458H93.394V12.1315C93.394 11.6467 93.2712 11.2947 93.0255 11.0755C92.7864 10.8564 92.461 10.7468 92.0492 10.7468C91.5777 10.7468 91.1925 10.8995 90.8936 11.205C90.6014 11.5105 90.4553 11.9655 90.4553 12.5698V15.1458H89.6683V10.1491H90.4354V10.9582H90.5361C90.7355 10.7018 90.8604 10.5342 91.1128 10.3483C91.3718 10.1557 91.7503 10.0594 92.2484 10.0594Z' fill='%230E0D0B'/%3e%3cpath d='M78.5932 10.9581H77.7681V10.1514H78.6L78.5932 10.9581Z' fill='%230E0D0B'/%3e%3c/svg%3e";const ka=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(","),tn=({isOpen:e,onClose:t,title:n,subtitle:s,children:o,overlayContent:r,overlayDimmed:i=!0,styles:l,theme:c,maxWidth:d="522px",dark:p,footerLinkText:m,bannerSrc:h,bannerAlt:x,closeOnBackdropClick:g=!1})=>{const{theme:y,dark:w,dk:C,palette:b}=f.useSpiceBrand(l,p),S=p??w,I=c||y,F=l?.fontFamily||I.typography.fontFamily||f.font.ui,k=l?.primaryColor||I.colors.primary,E=u.useRef(null),R=u.useRef(null),j=u.useRef(null),A=u.useId(),[M,P]=u.useState(!1),[N,B]=u.useState(!1),U=u.useRef(t);if(u.useEffect(()=>{U.current=t},[t]),u.useEffect(()=>{if(!e){B(!1);return}R.current=document.activeElement;const q=document.body.style.overflow;document.body.style.overflow="hidden";const ue=requestAnimationFrame(()=>{const re=requestAnimationFrame(()=>B(!0));j.current=re}),le=()=>{const re=E.current;re&&(re.querySelectorAll(ka)[0]??re).focus({preventScroll:!0})},G=re=>{if(re.key==="Escape"){re.stopPropagation(),U.current();return}if(re.key!=="Tab")return;const Y=E.current;if(!Y)return;const _=Array.from(Y.querySelectorAll(ka)).filter(L=>!L.hasAttribute("aria-hidden"));if(_.length===0){re.preventDefault(),Y.focus();return}const Z=_[0],pe=_[_.length-1],D=document.activeElement;re.shiftKey&&D===Z?(re.preventDefault(),pe.focus()):!re.shiftKey&&D===pe&&(re.preventDefault(),Z.focus())},ne=requestAnimationFrame(le);return document.addEventListener("keydown",G),()=>{cancelAnimationFrame(ne),cancelAnimationFrame(ue),j.current&&cancelAnimationFrame(j.current),document.removeEventListener("keydown",G),document.body.style.overflow=q;const re=R.current;re&&typeof re.focus=="function"&&re.focus({preventScroll:!0})}},[e]),!e)return null;const O=!!h&&!M,z=x??"";return a.jsx("div",{onMouseDown:q=>{g&&q.target===q.currentTarget&&U.current()},style:{position:"fixed",inset:0,backgroundColor:S?"rgba(0,0,0,0.72)":"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",padding:"clamp(16px, 4vw, 48px)",zIndex:f.z.modal,opacity:N?1:0,transition:`opacity ${f.duration.normal} ${f.easing.out}`},children:a.jsx("div",{ref:E,role:"dialog","aria-modal":"true","aria-labelledby":A,tabIndex:-1,style:{backgroundColor:b.shellBorder,borderRadius:"12px",padding:"5px",width:"100%",maxWidth:d,boxSizing:"border-box",boxShadow:"0 16px 48px rgba(0, 0, 0, 0.4)",outline:"none",transform:N?"scale(1)":"scale(0.96)",transition:`transform ${f.duration.slow} ${f.easing.out}`,display:"flex",flexDirection:"column",maxHeight:"100%"},children:a.jsxs("div",{style:{backgroundColor:b.shell,border:`1px solid ${b.shellInnerBorder}`,borderRadius:"9px",width:"100%",padding:"0",display:"flex",flexDirection:"column",position:"relative",flex:"0 1 auto",minHeight:0,overflowY:"auto",overflowX:"hidden"},children:[r&&i&&a.jsx("div",{style:{position:"absolute",inset:0,backgroundColor:"rgba(0, 0, 0, 0.4)",zIndex:5,pointerEvents:"none",borderRadius:"12px"},"aria-hidden":"true"}),O&&a.jsxs("div",{style:{position:"relative",width:"100%"},children:[a.jsx("img",{src:h,style:{width:"100%",height:"auto",display:"block",borderRadius:"6px 6px 0 0"},alt:z,"aria-hidden":z===""?"true":void 0,onError:()=>P(!0)}),a.jsx("button",{type:"button",onClick:t,"aria-label":"Close dialog",style:{position:"absolute",top:"8px",right:"8px",minWidth:"44px",minHeight:"44px",color:b.textPrimary,padding:"8px",backgroundColor:"transparent",borderRadius:"9999px",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1},children:a.jsx(ss,{size:28,strokeWidth:2.5})})]}),a.jsxs("div",{style:{padding:"28px 28px 0 28px",position:"relative"},children:[!O&&a.jsx("button",{type:"button",onClick:t,"aria-label":"Close dialog",style:{position:"absolute",top:"10px",right:"10px",minWidth:"44px",minHeight:"44px",color:b.textSecondary,padding:"10px",backgroundColor:"transparent",borderRadius:"50%",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.2s",fontSize:"18px",fontWeight:"600"},onMouseEnter:q=>{q.currentTarget.style.backgroundColor=S?`${k}1a`:"#f3f4f6"},onMouseLeave:q=>{q.currentTarget.style.backgroundColor="transparent"},children:a.jsx(ss,{size:24,strokeWidth:2.4})}),a.jsx("h2",{id:A,style:{fontSize:"22px",fontWeight:"700",color:b.textPrimary,margin:"0",fontFamily:F,lineHeight:"1.12"},children:n})]}),s&&a.jsx("div",{style:{padding:"11px 28px 13px 28px",fontSize:"12px",color:b.textSecondary,margin:"0",lineHeight:"1.35",fontFamily:F,borderBottom:S?`1px solid ${C.cardBorder}`:"1px solid #cdcfd1"},children:s}),o,a.jsxs("div",{style:{padding:"12px 28px",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[a.jsx("img",{src:va,alt:"","aria-hidden":"true",width:108,height:22,decoding:"async",style:{width:"108px",height:"22px",opacity:S?.85:1,filter:S?"brightness(0) invert(1)":"none",margin:0,display:"block"}}),a.jsx("a",{href:"https://spiceflow-docs.spicenet.io",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"10px",color:b.textSecondary,textDecoration:"none",display:"flex",alignItems:"center",gap:"4px",fontFamily:F,lineHeight:"1"},children:a.jsx("span",{style:{color:k,textDecoration:"underline",fontWeight:"500"},children:m??"Learn more \u2192"})})]}),r]})})})},Sa=({dk:e,dark:t,message:n,buttonLabel:s,onAction:o,disabled:r=!1})=>a.jsxs("div",{style:{padding:"12px",backgroundColor:e.warningBg,borderRadius:"8px",border:`1px solid ${e.warningBorder}`},children:[a.jsx("p",{style:{margin:"0 0 10px 0",color:e.warningText,fontSize:"14px"},children:n}),a.jsx("button",{onClick:o,disabled:r,style:{width:"100%",padding:"8px 12px",borderRadius:"6px",border:`1px solid ${t?e.warningBorder:"#fbbf24"}`,backgroundColor:t?e.cardBg:"white",cursor:r?"not-allowed":"pointer",fontWeight:600,fontSize:"13px",color:e.warningText,opacity:r?.6:1},children:s})]}),Ia=({dk:e,dark:t,borderRadius:n,children:s})=>a.jsx("div",{style:{padding:"8px 12px",marginBottom:"8px",backgroundColor:t?e.warningBg:"#fffbeb",border:`1px solid ${e.warningBorder}`,borderRadius:n,fontSize:"12px",color:e.warningText,lineHeight:"1.4"},children:s});async function Zc(e,t,n){let s=null;try{const o=await e.request({method:"eth_chainId"});s=parseInt(o,16)}catch{s=null}s!==t&&(n?.(),await f.ensureWalletOnChain(e,t))}function Aa(e){let t=e;const n=new Set;for(;t&&typeof t=="object"&&!n.has(t);){if(n.add(t),t.code===4001)return!0;t=t.cause}return!1}async function Ro(e){const t=e.provider??await e.wallet?.getEthereumProvider();if(!t)throw new Error("External wallet provider not available");await Zc(t,e.chainId,e.onSwitch);const n=await t.request({method:"eth_accounts"});if(!Array.isArray(n)||!n.some(o=>typeof o=="string"&&o.toLowerCase()===e.account.toLowerCase()))throw new Error("The connected source wallet changed. Reconnect the selected account before funding.");const s=f.getChainConfig(e.chainId)?.viemChain;return{extWc:T.createWalletClient({account:e.account,chain:s,transport:T.custom(t)}),viemChain:s}}async function Ea(e,t,n){const s=Date.now()+1e4;for(;Date.now()<s;){let o;try{o=await Promise.all([t.getBlockNumber({cacheTime:0}),e.request({method:"eth_blockNumber"}).then(BigInt)])}catch{return}if(o.every(r=>r>=n))return;await new Promise(r=>setTimeout(r,250))}}async function Xc(e){let t;for(const[n,s]of e.calls.entries()){await e.observer?.onSending?.(n);let o;try{o=await e.extWc.sendTransaction({to:s.to,data:s.data,value:s.value,chain:e.viemChain})}catch(l){throw Aa(l)&&e.observer?.onRejected?.(n),l}e.observer?.onSubmitted?.(n,o);const r=await Is({client:e.client,hash:o,call:s,onRepriced:l=>e.observer?.onSubmitted?.(n,l),onCancelled:()=>e.observer?.onReverted?.(n,o)});o=r.hash;const i=r.receipt;if(i.status!=="success")throw e.observer?.onReverted?.(n,o),new Error(e.errorMessage);await Ea(e.extWc,e.client,i.blockNumber),e.observer?.onConfirmed?.(n,o),t=o}return t}async function Fa(e){const t=await e.client.estimateFeesPerGas(),n=t.maxFeePerGas??t.gasPrice;if(typeof n!="bigint"||n<=0n)throw new Error("Network gas could not be priced.");let s=0n;for(const o of e.calls){const r=await e.client.estimateGas({account:e.account,...o});s+=(r*n*120n+99n)/100n}return s}function js(e,t,n,s){return n?{to:e,value:s,data:"0x"}:{to:t,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"transfer",args:[e,s]})}}async function Ta(e){const t=js(e.recipient,e.token,e.isNative,e.amount),[n,s]=await Promise.all([e.client.estimateGas({account:e.account,...t}),e.client.estimateFeesPerGas()]),o=s.maxFeePerGas??s.gasPrice;if(typeof o!="bigint"||o<=0n)throw new Error("Source transaction gas could not be priced.");return(n*o*120n+99n)/100n}function Do(e,t){return t.isNative?e.sendTransaction({to:t.recipient,value:t.amount,chain:t.viemChain}):e.sendTransaction({to:t.tokenAddr,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"transfer",args:[t.recipient,t.amount]}),chain:t.viemChain})}async function Jc(e){const{extWc:t,sourceClient:n,recipient:s,tokenAddr:o,isNative:r,amount:i}=e;if(i<=0n)return;await e.observer?.onSending?.(0);let l;try{l=await Do(t,{recipient:s,tokenAddr:o,isNative:r,amount:i,viemChain:e.viemChain})}catch(p){throw Aa(p)&&e.observer?.onRejected?.(0),p}e.observer?.onSubmitted?.(0,l);const c=await Is({client:n,hash:l,call:js(s,o,r,i),onRepriced:p=>e.observer?.onSubmitted?.(0,p),onCancelled:()=>e.observer?.onReverted?.(0,l)});l=c.hash;const d=c.receipt;if(d.status!=="success")throw e.observer?.onReverted?.(0,l),new Error("Embedded wallet funding failed");await Ea(t,n,d.blockNumber),e.observer?.onConfirmed?.(0,l)}function $c({sourceChainId:e,selectedAsset:t,destinationChainId:n,destinationTokenAddress:s,isCrossDenomination:o,convertedUsdAmount:r}){const i=v.normalizeNativeTokenAddress(t.asset.address),l=s;let c,d;if(l&&n)if(c=f.CHAIN_CONFIGS[n]?.supportedTokens?.find(p=>f.addressesEqual(p.address,l))?.decimals??t.asset.decimals,o){if(!r)throw new Error("Destination amount is still being calculated. Please retry in a moment.");d=r}else{const p=T.parseUnits(t.amount,t.asset.decimals);d=v.convertAmountBetweenDecimals(p,t.asset.decimals,c)}return{sourceChainId:e,depositTokenAddress:i,depositAmount:t.amount,depositTokenDecimals:t.asset.decimals,destinationChainId:n,destinationTokenAddress:l,destinationAmount:d,destinationTokenDecimals:c}}async function _c(e,t){if(!e)return[];if(Array.isArray(e))return e;const n=e;return e.length>=2?n(t.depositAmount,t.depositTokenAddress):n(t)}function ja(e,t){return!!e&&e.quotedAmount===t.amount&&e.chainId===t.chainId&&f.addressesEqual(e.token,t.token)}async function Bs(e,t){const n=await Do(e,{recipient:t.recipient,tokenAddr:t.tokenAddr,isNative:t.isNative,amount:t.amount});t.afterSend?.(n);const s=f.getClientForChain(t.chainId),{receipt:o,hash:r}=await Is({client:s,hash:n,call:js(t.recipient,t.tokenAddr,t.isNative,t.amount),confirmations:2});if(o.status!=="success")throw new Error(t.failureMessage);return t.settle&&await s.getBlockNumber()-o.blockNumber<2n&&await en(3e3),r}async function ed(e){const t=e.selectedDepositAssets.filter(o=>o.asset&&o.amount&&parseFloat(o.amount)>0);if(t.length===0){console.error("[DepositModal] No valid assets for deposit"),e.setError("Please select an asset and enter an amount");return}const n=t[0];if(!e.escrowOnly&&!e.sourceAddress){e.setError("External wallet not connected. Please connect your wallet in the previous step.");return}if(!e.isNon7702){if(!e.address||!e.embeddedWalletAddress){e.setError("Couldn't find your account wallet. Try reconnecting.");return}if(!e.isReady||!e.isAuthenticated){e.setError("Sign in to continue.");return}}if(e.zeroCreditError){e.setError(e.zeroCreditError);return}if(e.depositBalanceError){e.setError(e.depositBalanceError);return}if(e.isNon7702&&e.sponsorGas&&e.nativeChainId&&n.asset.chainId!==e.nativeChainId&&e.destinationTokenAddress){e.setError("Gas sponsorship is not supported for this deposit route. Disable sponsorGas to continue.");return}e.setIsExecuting(!0),e.setError(null);let s=!1;try{const o=n.asset.chainId,r=v.getEscrowContractAddress(o),i=T.parseUnits(n.amount,n.asset.decimals),l=t.length===1&&ja(e.effectiveDepositFee,{amount:i,token:v.normalizeNativeTokenAddress(n.asset.address),chainId:o}),c=!e.isNon7702&&!e.escrowOnly&&!wn(n.asset);if(!e.isNon7702&&t.length===1&&!c&&!l)throw new Error("Fee quote is out of date. Please wait for it to refresh.");let d=e.externalWalletClient;if(!e.escrowOnly){if(!d)throw new Error("External wallet not connected");if(e.externalProvider){const p=await Ro({provider:e.externalProvider,account:e.sourceAddress,chainId:o});p.viemChain&&(d=p.extWc)}}if(e.isNon7702){if(!d)throw new Error("External wallet not connected");if(!e.sourceAddress)throw new Error("External wallet address not available");if(e.nativeChainId&&o===e.nativeChainId){const p=f.getChainConfig(o),m=t.map(x=>`${x.amount} ${x.asset.symbol}`).join(", ");e.setConfirmationData({network:p?.displayName||`Chain ${o}`,amount:m,symbol:"",chainId:o}),e.setShowConfirmation(!0);let h=null;e.setDirectDepositStatus("processing"),e.setDirectDepositChainId(o);for(const x of t){const g=T.parseUnits(x.amount,x.asset.decimals),y=v.normalizeNativeTokenAddress(x.asset.address),w=x.asset.isNative||v.isNativeToken(y),C=await Bs(d,{chainId:o,recipient:r,tokenAddr:y,isNative:w,amount:g,failureMessage:`Escrow deposit failed for ${x.asset.symbol}`});h=C,e.setDirectDepositTxHash(C)}if(t[0]?.amount){const x=t[0].amount;if(e.onDepositExecute){e.setPostDepositStatus("executing");try{await e.onDepositExecute(x),e.setPostDepositStatus("success")}catch(y){console.error("ctx.onDepositExecute failed:",y),e.setPostDepositStatus("error"),e.setPostDepositError(y?.message||"Post-deposit instruction failed")}}else e.setPostDepositStatus("success");e.setDirectDepositStatus("success"),e.setPostDepositAmount(x),e.setPostDepositSuccess(!0);const g={type:"deposit",status:"success",amount:x,asset:t[0].asset.symbol,sourceChain:p?.displayName||`Chain ${o}`,txHash:h??void 0};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:g})),e.onDepositSuccess?.(g)}e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset)}else{const p=e.destinationChainId||e.nativeChainId;if(!p)throw new Error("Destination chain ID is required for non-7702 mode. Either pass ctx.destinationChainId to <SpiceDeposit> or set ctx.nativeChainId on <SpiceFlowProvider>.");const m=f.getDelegateContractAddress(o),h=r,x=[];let g=null;for(const y of t){const w=T.parseUnits(y.amount,y.asset.decimals),C=v.normalizeNativeTokenAddress(y.asset.address),b=y.asset.isNative||v.isNativeToken(C),S=await Bs(d,{chainId:o,recipient:h,tokenAddr:C,isNative:b,amount:w,failureMessage:`Transfer failed for ${y.asset.symbol}`,settle:!0});g||(g=S),e.depositDataRef.current||(e.depositDataRef.current=[]),e.depositDataRef.current.push({txHash:S,sender:e.sourceAddress,tokenAddress:C,chainId:o,amount:w.toString(),user:e.spiceBalanceUser}),x.push({tokenAddress:C,tokenAmount:w.toString(),sender:e.sourceAddress,receiver:h})}if(!g)throw new Error("No transaction hash generated");if(!e.destinationTokenAddress){const y={type:"deposit",status:"success",amount:t[0]?.amount,asset:t[0]?.asset?.symbol,sourceChain:f.getChainName(o),txHash:g};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:y})),e.onDepositSuccess?.(y),e.depositDataRef.current=null,e.bridgedAmountRef.current=t[0]?.amount||null,e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset),e.setShowConfirmation(!1);return}if(e.mode==="ondemand"){const y={to:m,value:BigInt(0),data:"0x"},w=await f.getTokenDecimals(p,e.destinationTokenAddress);let C=BigInt(0);for(const A of x){const M=BigInt(A.tokenAmount),P=v.normalizeNativeTokenAddress(A.tokenAddress),N=t.find(U=>{const O=v.normalizeNativeTokenAddress(U.asset.address);return f.addressesEqual(O,P)}),B=N?N.asset.decimals:await f.getTokenDecimals(o,v.ZERO_ADDRESS);C+=v.convertAmountBetweenDecimals(M,B,w)}e.isCrossDenomination&&e.convertedUsdAmount&&(C=e.convertedUsdAmount);const b={chainId:o,tokenTransfers:x.map(A=>({from:A.sender,to:A.receiver,token:A.tokenAddress,amount:BigInt(A.tokenAmount)})),call:y},S=e.isCrossDenomination&&e.convertedUsdAmount?[{from:e.sourceAddress,to:r,token:v.normalizeNativeTokenAddress(t[0].asset.address),amount:T.parseUnits(t[0].amount,t[0].asset.decimals)}]:[],I={chainId:p,tokenTransfers:[...S,{from:"escrow",to:e.sourceAddress,token:e.destinationTokenAddress,amount:C}],call:{to:e.destinationTokenAddress,value:BigInt(0),data:"0x"}},F={mode:"non-7702:on-demand",chainBatches:[b,I]},k={user:e.sourceAddress,intents:[F]},E=await f.relayerService.createAction(k),R=E.actionId,j=E.intentIds[0];if(!g)throw new Error("No transaction hash available");e.startStatusPolling(j,f.createInitialSteps([{chainId:o,calls:[y]},{chainId:p,calls:[I.call]}],A=>f.getChainName(A))),await f.relayerService.executeStep(R,0,0,{action:"execute",hash:g}),t[0]?.amount&&(e.bridgedAmountRef.current=t[0].amount),e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(t[0].asset),e.setShowConfirmation(!1)}else throw new Error("Presign mode not yet fully supported for cross-chain deposits")}}else{const p=[];let m=0,h;const x=l&&e.effectiveDepositFee?T.formatUnits(e.effectiveDepositFee.net,n.asset.decimals):n?.amount;for(const A of t){const M=T.parseUnits(A.amount,A.asset.decimals),P=l&&A===n,N=P?e.effectiveDepositFee.fee:0n,B=P?e.effectiveDepositFee.net:M,U=e.escrowOnly?M:M+N,O=v.normalizeNativeTokenAddress(A.asset.address),z=A.asset.isNative||v.isNativeToken(O);if(!e.escrowOnly&&!wn(A.asset)){e.setDirectDepositStatus("processing"),e.setDirectDepositChainId(o);const q=await Bs(d,{chainId:o,recipient:e.address,tokenAddr:O,isNative:z,amount:M,failureMessage:`Transfer to embedded wallet failed for ${A.asset.symbol}`});m+=1,A===n&&(h=q);continue}e.escrowOnly||await Bs(d,{chainId:o,recipient:e.address,tokenAddr:O,isNative:z,amount:U,failureMessage:`Transfer to embedded wallet failed for ${A.asset.symbol}`,afterSend:()=>ac({chainId:o,tokenAddress:v.normalizeNativeTokenAddress(A.asset.address),tokenSymbol:A.asset.symbol,tokenDecimals:A.asset.decimals,amount:A.amount,rawAmount:M.toString(),embeddedWalletAddress:e.address,externalWalletAddress:e.sourceAddress,timestamp:Date.now(),isNative:z}),settle:!0}),p.push(z?{to:r,value:B,data:"0x"}:{to:O,value:BigInt(0),data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"transfer",args:[r,B]})}),N>0n&&p.push(z?{to:v.SPICE_GAS_FEE_RECIPIENT,value:N,data:"0x"}:{to:O,value:BigInt(0),data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"transfer",args:[v.SPICE_GAS_FEE_RECIPIENT,N]})})}if(p.length===0){e.setDirectDepositTxHash(h??null),e.setDirectDepositStatus("success");const A={type:"deposit",status:"success",amount:n.amount,asset:n.asset.symbol,sourceChain:f.getChainName(o),txHash:h};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:A})),e.onDepositSuccess?.(A),e.refreshAssets(),e.onDepositSelect&&e.onDepositSelect(n.asset);return}m>0&&e.setDirectDepositStatus("idle");const g=t.find(A=>e.escrowOnly||wn(A.asset))??n,y=await f.getClientForChain(o).getBlockNumber(),w=p.map(A=>({...A,to:T.getAddress(A.to)})),C={chainId:o,recentBlock:y,calls:w,tokenTransfers:[]},b=$c({sourceChainId:o,selectedAsset:g===n&&x?{...n,amount:x}:g,destinationChainId:e.destinationChainId,destinationTokenAddress:e.destinationTokenAddress,isCrossDenomination:e.isCrossDenomination,convertedUsdAmount:e.convertedUsdAmount}),S=await _c(e.depositBatches,b),I=[C,...S];if(!e.address)throw new Error("Address not available");const F=[];if(e.isCrossDenomination&&e.convertedUsdAmount&&e.destinationTokenAddress){const A=e.selectedDepositAssets[0]?.asset;if(A){const M=T.parseUnits(e.selectedDepositAssets[0].amount,A.decimals);F.push({from:e.address,to:r,token:v.normalizeNativeTokenAddress(A.address),amount:M}),F.push({from:"escrow",to:e.address,token:e.destinationTokenAddress,amount:e.convertedUsdAmount})}}F.length>0&&I[1]&&(I[1].tokenTransfers=F);const k=f.createInitialSteps(I,A=>f.getChainName(A));let E=!1;const R=await e.execution.execute(I,v.ZERO_ADDRESS,0n,A=>{if(A.intentId&&!E){E=!0;for(const M of t)vo(e.address,o,v.normalizeNativeTokenAddress(M.asset.address));e.startStatusPolling(A.intentId,k)}},void 0,{userOverride:e.address,useCustomTransfers:!0,skipPreSubmitFeeEstimate:!0,skipUserFundingPreflight:!0});if(e.refreshAssets(),e.onDepositExecute&&g.amount)try{e.setPostDepositStatus("executing"),await e.onDepositExecute(x||g.amount),e.setPostDepositStatus("success"),e.setPostDepositAmount(x||g.amount),e.setPostDepositSuccess(!0)}catch(A){console.error("ctx.onDepositExecute failed (7702):",A),e.setPostDepositStatus("error"),e.setPostDepositError(A?.message||"Post-deposit instruction failed");return}const j={type:"deposit",status:"success",amount:g===n&&x||g.amount,asset:g.asset.symbol,sourceChain:f.getChainName(o),txHash:/^0x[0-9a-f]{64}$/i.test(R??"")?R:void 0};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:j})),e.onDepositSuccess?.(j),e.onDepositSelect&&e.onDepositSelect(g.asset)}}catch(o){s=!0,console.error("[DepositModal] executeDeposit CAUGHT ERROR:",o),console.error("[DepositModal] Error details:",{message:o?.message,code:o?.code,name:o?.name,stack:o?.stack?.slice(0,500)}),e.setError(f.sanitizeError(o,"Deposit failed")),e.clearStatus()}finally{e.setIsExecuting(!1),s&&e.setDirectDepositStatus("idle"),s||!e.getCurrentIntentStatus()&&e.getCurrentPostDepositStatus()!=="idle"||e.setShowConfirmation(!1)}}async function td(e){const{asset:t,assetIndex:n,selectedAssetCount:s,address:o,escrowOnly:r,isNon7702:i}=e;if(n!==0||i||s>1||!o||t.balance<=0n)return null;if(!r&&!wn(t))return f.formatRawTokenInput(t.balance,t.decimals);const l=await Ba({address:o,depositQuote:{asset:t,amount:t.balance,token:v.normalizeNativeTokenAddress(t.address),chainId:t.chainId},escrowOnly:r}),c=r?t.balance:t.balance>l.fee?t.balance-l.fee:0n;return f.formatRawTokenInput(c,t.decimals)}async function Ba(e){const{address:t,depositQuote:n,escrowOnly:s}=e,{asset:o,amount:r,token:i,chainId:l}=n,c=v.getEscrowContractAddress(l),d=o.isNative||v.isNativeToken(i),p=r>1n?1n:0n,m=[d?{to:c,value:r,data:"0x"}:{to:i,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"transfer",args:[c,r]})}];p>0n&&m.push(d?{to:v.SPICE_GAS_FEE_RECIPIENT,value:p,data:"0x"}:{to:i,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"transfer",args:[v.SPICE_GAS_FEE_RECIPIENT,p]})});const h={chainId:l,tokenTransfers:[],calls:m},x=(await f.relayerService.estimateBatchGas({user:t,outputToken:i,chainBatches:[{...h,hash:v.hashChainBatches([h])[0].hash}],signal:e.signal})).gasFee,g=s&&x<r?r-x:r;return{fee:x,net:g,quotedAmount:r,token:i,chainId:l}}function nd(e,t=40,n=18){const s=e.length,o=[{maxLength:7,shrink:0},{maxLength:10,shrink:6},{maxLength:13,shrink:12},{maxLength:16,shrink:16},{maxLength:20,shrink:19}].find(r=>s<=r.maxLength);return Math.max(n,t-(o?.shrink??22))}const Sn=({value:e,element:t="span",placeholder:n,ariaLabel:s,ariaInvalid:o,disabled:r,onChange:i,inputMode:l="decimal",autoComplete:c="off",dataSpiceflowFocus:d,fontFamily:p,fontWeight:m=700,color:h,textAlign:x,lineHeight:g=1,maxFontSize:y=40,minFontSize:w=18,overflow:C="ellipsis",title:b,style:S})=>{const I=nd(e||n||"",y,w),F=C==="wrap"?{overflowWrap:"anywhere",wordBreak:"break-word",whiteSpace:"normal"}:C==="ellipsis"?{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}:{},k={fontFamily:p,fontSize:`${I}px`,fontWeight:m,color:h,lineHeight:g,letterSpacing:0,textAlign:x,minWidth:0,maxWidth:"100%",...F,...S};return t==="input"?a.jsx("input",{type:"text",inputMode:l,autoComplete:c,"aria-label":s,"aria-invalid":o||void 0,"data-spiceflow-focus":d||void 0,value:e,onChange:i,placeholder:n,disabled:r,title:b,style:{backgroundColor:"transparent",border:"none",outline:"none",padding:0,width:"100%",...k}}):a.jsx(t,{title:b,style:k,children:e})},Oo=({pct:e,isMax:t,primaryColor:n,dark:s,fillColor:o})=>{const r=e/100;return a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[a.jsx("circle",{cx:"7",cy:"7",r:"6.84375",fill:t?n:"none",stroke:t?n:s?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!t&&r>0&&a.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${r>.5?1:0} 1 ${7+6.84375*Math.sin(r*2*Math.PI)} ${7-6.84375*Math.cos(r*2*Math.PI)} Z`,fill:o})]})},Ra=({chainId:e,name:t,size:n=16})=>{const s=e&&(yn[e]||v.getChainMeta(e)?.logo)||"";return s?a.jsx("img",{src:s,alt:t||`Chain ${e}`,loading:"lazy",decoding:"async",width:n,height:n,style:{width:`${n}px`,height:`${n}px`,borderRadius:"50%",objectFit:"cover",flexShrink:0}}):null},sd={1:"ethereum",56:"binance-smart-chain",137:"polygon-pos",143:"monad",4114:"citrea",4663:"robinhood",8453:"base",42161:"arbitrum-one"},od=6e4,os=new Map;function Da(e,t){return os.get(e)?.logos?.get(t.toLowerCase())}function rd(e,t){const n=sd[e];if(!n||v.isNativeToken(t))return;const s=os.get(e);if(s?.logos||s?.pending)return s.pending;if(s?.failedAt!==void 0&&Date.now()-s.failedAt<od)return;const o=Promise.resolve().then(async()=>{try{const r=await fetch(`https://tokens.coingecko.com/${n}/all.json`,{signal:AbortSignal.timeout(1e4)});if(!r.ok)throw new Error("Token list request failed");const i=await r.json(),l=new Map;for(const c of i?.tokens??[])c?.address&&c?.logoURI&&l.set(String(c.address).toLowerCase(),c.logoURI);os.set(e,{logos:l})}catch(r){console.warn(`[tokenLogos] Token list unavailable for chain ${e}`,r),os.set(e,{failedAt:Date.now()})}});return os.set(e,{...s,pending:o}),o}function Oa(e,t,n){const[s,o]=u.useState(),r=e||e===null||t===void 0||!n?void 0:`${t}:${n.toLowerCase()}`,i=r?Da(t,n):void 0;return u.useEffect(()=>{if(!r||i||t===void 0||!n)return;let l=!0;const c=()=>{const p=Da(t,n);l&&p&&o({token:r,logo:p})},d=rd(t,n);return d?d.then(c):c(),()=>{l=!1}},[r,i,t,n]),e||i||(s&&s.token===r?s.logo:void 0)}const Rs=({symbol:e,label:t,logoURI:n,chainId:s,address:o,size:r=20,theme:i})=>{const{theme:l}=f.useSpiceBrand(),c=i||l,[d,p]=u.useState(),m={width:`${r}px`,height:`${r}px`,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:`${r*.4}px`,fontWeight:c.typography.fontWeight.bold,flexShrink:0,overflow:"hidden",backgroundColor:"#ffffff"},h=Oa(n===null?null:n||ho[e.toUpperCase()],s,o);if(n===null)return null;if(h&&h!==d)return a.jsx("img",{src:h,alt:t??e,loading:"lazy",decoding:"async",style:{...m,objectFit:"cover"},onError:()=>p(h)});const x=ad(e);return a.jsx("div",{style:{...m,...x.style},children:x.icon})},ad=e=>{const t=e.toUpperCase(),n={ETH:{bg:"#627EEA",text:"#FFFFFF",icon:"\u039E"},BTC:{bg:"#F7931A",text:"#FFFFFF",icon:"\u20BF"},USDC:{bg:"#2775CA",text:"#FFFFFF"},USDT:{bg:"#26A17B",text:"#FFFFFF"},DAI:{bg:"#F5AC37",text:"#FFFFFF"},WETH:{bg:"#627EEA",text:"#FFFFFF",icon:"\u039E"},WBTC:{bg:"#F09242",text:"#FFFFFF",icon:"\u20BF"},CBTC:{bg:"#F7931A",text:"#FFFFFF",icon:"\u20BF"},USD:{bg:"#26A17B",text:"#FFFFFF",icon:"$"},MATIC:{bg:"#8247E5",text:"#FFFFFF"},AVAX:{bg:"#E84142",text:"#FFFFFF"},SOL:{bg:"#9945FF",text:"#FFFFFF"},DOT:{bg:"#E6007A",text:"#FFFFFF"},ADA:{bg:"#0033AD",text:"#FFFFFF"},LINK:{bg:"#375BD2",text:"#FFFFFF"},UNI:{bg:"#FF007A",text:"#FFFFFF"},AAVE:{bg:"#B6509E",text:"#FFFFFF"},CRV:{bg:"#40E0D0",text:"#000000"}}[t];if(n)return{style:{backgroundColor:n.bg,color:n.text},icon:n.icon||t.charAt(0)};const s=t.split("").reduce((l,c)=>c.charCodeAt(0)+((l<<5)-l),0),o=Math.abs(s)%360,r=`hsl(${o}, 60%, 50%)`,i=o>180?"#FFFFFF":"#000000";return{style:{backgroundColor:r,color:i},icon:t.charAt(0)}},id=({selectedAsset:e,assets:t,onAssetSelect:n,showDropdown:s,onToggleDropdown:o,disabled:r=!1,theme:i,onViewAllAssets:l})=>{const c=f.useAssetDisplay(),{theme:d}=f.useSpiceBrand(),p=i||d,m=u.useRef(null),h=u.useRef(null),x=u.useRef(null),[g,y]=u.useState(null);u.useEffect(()=>{if(s&&h.current){const N=()=>{if(h.current){const B=h.current.getBoundingClientRect();y({top:B.bottom+6,right:window.innerWidth-B.right})}};return N(),window.addEventListener("scroll",N,!0),window.addEventListener("resize",N),()=>{window.removeEventListener("scroll",N,!0),window.removeEventListener("resize",N)}}else y(null)},[s]),u.useEffect(()=>{const N=B=>{m.current&&!m.current.contains(B.target)&&x.current&&!x.current.contains(B.target)&&s&&o()};return s&&document.addEventListener("mousedown",N),()=>{document.removeEventListener("mousedown",N)}},[s,o]);const[w,C]=u.useState(!1),b=p.mode==="light",S={backgroundColor:"transparent",border:`1px solid ${b?"#aaaaaa":p.colors.border}`,borderRadius:"6px",color:p.colors.text,cursor:r?"not-allowed":"pointer",padding:"8px 14px 8px 10px",width:"100%",display:"flex",flexDirection:"column",gap:"4px",opacity:r?.6:1,transition:f.transition.interactive,transform:w?"scale(0.98)":"scale(1)"},I={display:"flex",justifyContent:"space-between",alignItems:"center",gap:"10px",minWidth:0},F={display:"flex",alignItems:"center",gap:"4px",paddingTop:"4px",borderTop:`1px solid ${p.colors.border}`},k=()=>g?{position:"fixed",top:`${g.top}px`,right:`${g.right}px`,backgroundColor:p.colors.secondary,border:`1px solid ${p.colors.border}`,borderRadius:p.borderRadius.md,boxShadow:p.shadows.lg,zIndex:f.z.dropdown,width:"200px",maxHeight:"300px",overflow:"auto"}:{},E={backgroundColor:"transparent",border:"none",color:p.colors.text,cursor:"pointer",padding:p.spacing.sm,width:"100%",display:"flex",alignItems:"center",gap:p.spacing.sm,transition:`background-color ${p.animation.normal}`,":hover":{backgroundColor:p.colors.surfaceHover}},R={display:"flex",flexDirection:"column",alignItems:"flex-start",flex:1},j={fontSize:p.typography.fontSize.sm,fontWeight:p.typography.fontWeight.medium},A={fontSize:p.typography.fontSize.xs,color:p.colors.textMuted},M={backgroundColor:"transparent",border:"none",borderTop:`1px solid ${p.colors.border}`,color:p.colors.primary,cursor:"pointer",padding:"10px 12px",width:"100%",display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",fontFamily:p.typography.fontFamily,fontSize:p.typography.fontSize.xs,fontWeight:p.typography.fontWeight.medium,textDecoration:"underline",textUnderlineOffset:"2px"},P={transition:`transform ${p.animation.normal}`,transform:s?"rotate(180deg)":"rotate(0deg)",flexShrink:0};return a.jsxs(a.Fragment,{children:[a.jsx("div",{style:{position:"relative"},ref:m,children:a.jsxs("div",{ref:h,style:S,onClick:r?void 0:o,onMouseLeave:()=>{C(!1)},onMouseDown:()=>C(!0),onMouseUp:()=>C(!1),children:[a.jsxs("div",{style:I,children:[a.jsx("div",{style:{display:"flex",alignItems:"center",gap:"8px",flex:1,minWidth:0},children:e?.asset?a.jsxs(a.Fragment,{children:[a.jsx(Rs,{symbol:e.asset.symbol,label:c(e.asset).symbol,logoURI:c(e.asset).logoURI,chainId:e.asset.chainId,address:e.asset.address,theme:p,size:24}),a.jsx("span",{style:{fontSize:"15px",fontWeight:500,color:p.colors.text,lineHeight:"1.5",flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:c(e.asset).symbol})]}):a.jsx("span",{style:{fontSize:"14px",color:p.colors.textMuted},children:"Select"})}),a.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:b?p.colors.textMuted:"#c7ccd4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:P,children:a.jsx("path",{d:"M6 9l6 6 6-6"})})]}),e?.asset&&a.jsxs("div",{style:F,children:[!e.asset.displayChainName&&a.jsx(Ra,{chainId:e.asset.chainId,theme:p}),a.jsx("span",{style:{fontSize:"11px",color:p.colors.textMuted},children:f.getAssetDisplayChainName(e.asset)})]})]})}),s&&g&&jn.createPortal(a.jsxs("div",{ref:x,style:k(),children:[t.length===0&&a.jsx("div",{style:{padding:"10px 12px",color:p.colors.textMuted,fontSize:p.typography.fontSize.xs},children:"No assets available"}),t.map(N=>a.jsxs("button",{style:E,onClick:()=>{n(N),o()},children:[a.jsx(Rs,{symbol:N.symbol,label:c(N).symbol,logoURI:c(N).logoURI,chainId:N.chainId,address:N.address,theme:p},Ge(N)),a.jsxs("div",{style:R,children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:p.spacing.xs},children:[a.jsx("span",{style:j,children:c(N).symbol}),!N.displayChainName&&a.jsx(Ra,{chainId:N.chainId,theme:p})]}),a.jsxs("span",{style:A,children:[f.formatAssetBalance(N)," \u2022"," ",f.getAssetDisplayChainName(N)]})]})]},Ge(N))),l&&a.jsxs("button",{type:"button",style:M,onClick:()=>{o(),l()},children:[a.jsx("span",{children:"View all assets"}),a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M5 12h14"}),a.jsx("path",{d:"M13 5l7 7-7 7"})]})]})]}),document.body)]})},ld=({assets:e,selectedAsset:t,onAssetSelect:n,onAmountChange:s,disabled:o=!1,loading:r=!1,label:i="Select Asset",showBalance:l=!0,showMaxButton:c=!0,placeholder:d="0.0",theme:p,styles:m,maxAmount:h,resolveMaxAmount:x,hideAmountInput:g=!1,displayAmount:y,dark:w,onViewAllAssets:C})=>{const b=f.useAssetDisplay(),{theme:S,primaryColor:I,dark:F,dk:k}=f.useSpiceBrand(m,w),E=p||S,R=w??F,[j,A]=u.useState(!1),[M,P]=u.useState(null),[N,B]=u.useState(null),[U,O]=u.useState(!1),[z,q]=u.useState(null),[ue,le]=u.useState(t?.amount||""),G=u.useRef(x),ne=t?.asset?Ge(t.asset):"",re=u.useRef(ne);re.current=ne;const Y=!!x,_=z??h;u.useEffect(()=>{G.current=x},[x]),u.useEffect(()=>{le(t?.amount||"")},[ne,t?.amount]),u.useEffect(()=>{q(null),O(!1)},[ne,Y,t?.asset?.balance]);const Z=()=>{const K=t?.asset;if(!K)return 0n;if(!_)return K.balance;const W=T.parseUnits(_,K.decimals);return W<K.balance?W:K.balance},pe=K=>{le(K),s?.(K)},D=K=>{const W=t?.asset,Q=f.parseNumericInput(K.startsWith(".")?`0${K}`:K,W?.decimals);if(!W||!Q)return pe(Q);const ae=T.parseUnits(Q,W.decimals),we=Z();pe(ae>we?T.formatUnits(we,W.decimals):Q)},L=async()=>{const K=t?.asset;if(!K||o)return;const W=ne,Q=G.current;if(z)return pe(z);if(Q){O(!0);try{const ae=await Q(K);if(re.current!==W)return;if(ae!==null){const we=f.parseNumericInput(ae,K.decimals);q(we),pe(we);return}return}catch(ae){console.warn("[AssetSelector] Failed to resolve max amount:",ae);return}finally{re.current===W&&O(!1)}}re.current===W&&pe(T.formatUnits(Z(),K.decimals))},$=async K=>{if(!(!t||o)){if(K===100)return L();pe(T.formatUnits(Z()*BigInt(K)/100n,t.asset.decimals))}},de=t?.asset?.balanceFormatted??0,ce=parseFloat(ue)||0,he=de>0?ce/de*100:0,X={backgroundColor:m?.assetSelector?.backgroundColor||m?.secondaryBackground||(R?k.cardBg:"#e9e9e9"),border:R?`0.5px solid ${k.cardBorder}`:"0.5px solid #A8A8A7",borderRadius:m?.assetSelector?.borderRadius||"6px",padding:m?.assetSelector?.padding||"16px",height:"auto",minHeight:g?void 0:"144px",display:"flex",flexDirection:"column",gap:"8px",position:"relative",opacity:o?.6:1};return r?a.jsx("div",{style:X,children:a.jsxs("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"space-between"},children:[a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[a.jsx("div",{style:{backgroundColor:R?k.hoverBg:"#d1d5db",borderRadius:"4px",height:"16px",width:"60px"}}),a.jsx("div",{style:{backgroundColor:R?k.hoverBg:"#d1d5db",borderRadius:"4px",height:"40px",width:"150px"}})]}),a.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:"8px"},children:[a.jsx("div",{style:{backgroundColor:R?k.hoverBg:"#d1d5db",borderRadius:"4px",height:"12px",width:"80px"}}),a.jsx("div",{style:{backgroundColor:R?k.hoverBg:"#d1d5db",borderRadius:"6px",height:"46px",width:"128px"}})]})]})}):a.jsxs("div",{style:X,children:[a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[a.jsx("span",{style:{fontFamily:m?.fontFamily||E.typography.fontFamily,fontSize:"16px",fontWeight:500,color:R?k.textSecondary:"#7d7c7b",lineHeight:"24px"},children:i}),l&&t?.asset&&a.jsxs("span",{style:{fontFamily:m?.fontFamily||E.typography.fontFamily,fontSize:"12px",fontWeight:500,color:R?k.textSecondary:"#71757a",lineHeight:"16px"},children:["Balance: ",f.formatAssetBalance(t.asset)]})]}),a.jsxs("div",{style:{display:"flex",justifyContent:g&&!y?"flex-start":"space-between",alignItems:"center",flex:1},children:[!g&&a.jsx(Sn,{element:"input",ariaLabel:t?.asset?`${b(t.asset).symbol} amount`:"Amount",dataSpiceflowFocus:!0,value:ue,onChange:K=>D(K.target.value),placeholder:d,disabled:o||!t?.asset,fontFamily:m?.fontFamily||E.typography.fontFamily,color:o?R?"rgba(255, 255, 255, 0.16)":"rgba(14, 13, 11, 0.16)":ue?R?"#ffffff":"#0e0d0b":R?"#4a5568":"#d1d5db",lineHeight:"1.08",maxFontSize:40,minFontSize:22,style:{width:"100%",maxWidth:"200px"}}),a.jsx("div",{style:{width:"176px",position:"relative",flexShrink:0},children:a.jsx(id,{selectedAsset:t,assets:e,onAssetSelect:n,showDropdown:j,onToggleDropdown:()=>A(!j),disabled:o,theme:E,onViewAllAssets:C})}),g&&y&&a.jsx(Sn,{element:"span",value:y,title:y,fontFamily:m?.fontFamily||E.typography.fontFamily,color:R?"#ffffff":"#0e0d0b",lineHeight:"1.08",textAlign:"right",maxFontSize:40,minFontSize:22,style:{flex:1}})]}),!g&&a.jsx("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",height:"14px"},children:[0,25,50,75,100].filter(K=>c||K!==100).map((K,W)=>{const Q=Math.abs(he-K)<1,ae=W===4,we=M===K,ke=N===K;return a.jsx("button",{onClick:()=>$(K),onMouseEnter:()=>P(K),onMouseLeave:()=>{P(null),B(null)},onMouseDown:()=>B(K),onMouseUp:()=>B(null),disabled:o||!t?.asset||K===100&&U,title:`${K}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:o||!t?.asset||K===100&&U?"not-allowed":"pointer",opacity:Q?1:we?.8:.5,transform:ke?"scale(0.85)":we?"scale(1.15)":"scale(1)",transition:f.transition.interactive},children:a.jsx(Oo,{pct:K,isMax:ae,primaryColor:I,dark:R,fillColor:R?k.textSecondary:"#3C3E42"})},K)})})]})},Pn=u.memo(ld),cd=({selectedDepositAssets:e,depositAssets:t,secondAssetOptions:n,loadingAssets:s,allowSecondAsset:o,theme:r,styles:i,dark:l,dk:c,onSelect:d,onAmountChange:p,onAdd:m,onRemove:h,resolveMaxAmount:x,onViewAllAssets:g})=>a.jsxs(a.Fragment,{children:[e.map((y,w)=>{const C=e.length===1?"Deposit":`Asset ${w+1}`;return a.jsxs("div",{style:{marginBottom:r.spacing.md,position:"relative"},children:[a.jsx(Pn,{assets:w===0?t:n,selectedAsset:y||void 0,onAssetSelect:b=>d(b,w),onAmountChange:b=>p(b,w),loading:s,label:C,showBalance:!0,theme:r,styles:i,allowSecondAsset:o&&w===0,onAddAsset:m,canAddAsset:e.length===1&&!!e[0]?.asset,resolveMaxAmount:x?b=>x(b,w):void 0,onViewAllAssets:w===0?g:void 0}),w===1&&a.jsx("button",{onClick:()=>h(w),style:{position:"absolute",top:"-2px",right:"-2px",background:l?`${c.cardBg}ee`:"rgba(255, 255, 255, 0.9)",border:`1px solid ${c.cardBorder}`,borderRadius:"50%",cursor:"pointer",color:r.colors.textMuted,fontSize:"16px",padding:"2px",width:"22px",height:"22px",display:"flex",alignItems:"center",justifyContent:"center",transition:f.transition.interactive,boxShadow:"0 1px 3px rgba(0, 0, 0, 0.1)"},onMouseEnter:b=>{b.currentTarget.style.color=l?c.errorText:"#ef4444",b.currentTarget.style.background=l?c.cardBg:"#fff",b.currentTarget.style.borderColor=l?c.errorBorder:"#fecaca"},onMouseLeave:b=>{b.currentTarget.style.color=r.colors.textMuted,b.currentTarget.style.background=l?`${c.cardBg}ee`:"rgba(255, 255, 255, 0.9)",b.currentTarget.style.borderColor=l?c.cardBorder:"#e5e7eb"},title:"Remove asset",children:"\xD7"})]},`asset-${w}`)}),e.length===0&&a.jsx("div",{style:{marginBottom:r.spacing.md},children:a.jsx(Pn,{assets:t,selectedAsset:void 0,onAssetSelect:y=>d(y,0),onAmountChange:y=>p(y,0),loading:s,label:"Deposit",showBalance:!0,theme:r,styles:i,allowSecondAsset:o,onAddAsset:m,canAddAsset:!1,resolveMaxAmount:x?y=>x(y,0):void 0},"initial-selector")})]}),dd=u.memo(cd);function ud(e,t){switch(e){case"success":return{bg:t.successBg,border:t.successBorder,text:t.successText};case"warning":return{bg:t.warningBg,border:t.warningBorder,text:t.warningText};case"error":return{bg:t.errorBg,border:t.errorBorder,text:t.errorText};case"info":return{bg:t.infoBg,border:t.infoBorder,text:t.infoText}}}const rn=({variant:e,palette:t,children:n,icon:s,style:o,fontFamily:r,size:i="default"})=>{const l=ud(e,t),c=i==="compact";return a.jsxs("div",{role:e==="error"?"alert":"status",style:{backgroundColor:l.bg,border:`1px solid ${l.border}`,borderRadius:c?"7px":"8px",padding:c?"8px 10px":"12px 16px",color:l.text,fontSize:c?"12px":"13px",lineHeight:c?1.4:1.5,display:"flex",alignItems:"flex-start",gap:c?"6px":"8px",fontFamily:r,...o},children:[s&&a.jsx("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:s}),a.jsx("span",{style:{minWidth:0,overflowWrap:"anywhere"},children:n})]})},Na=f.font.mono,bn=({label:e,value:t,palette:n,valueColor:s,labelColor:o,style:r})=>a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",...r},children:[a.jsx("span",{style:{fontSize:"12px",color:o??n.textSecondary,fontFamily:Na,fontWeight:500,letterSpacing:"0.03em",flexShrink:0,whiteSpace:"nowrap"},children:e}),a.jsx("span",{style:{fontSize:"13px",color:s??n.textPrimary,fontWeight:500,fontFamily:Na,minWidth:0,textAlign:"right",overflowWrap:"anywhere"},children:t})]}),No=({onClick:e,label:t="Add Funds",color:n,fontFamily:s,style:o})=>{const[r,i]=u.useState(!1);return a.jsxs("button",{type:"button",onClick:e,"data-spiceflow-focus":!0,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),style:{background:"none",border:"none",cursor:"pointer",padding:0,display:"inline-flex",alignItems:"center",gap:"4px",color:n,fontSize:"12px",fontWeight:500,fontFamily:s,textDecoration:"underline",textUnderlineOffset:"2px",whiteSpace:"nowrap",opacity:r?.75:1,transition:"opacity 150ms ease",...o},children:[t,a.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.8","aria-hidden":"true",children:[a.jsx("circle",{cx:"6",cy:"6",r:"5"}),a.jsx("path",{d:"M6 4v4M4 6h4",strokeLinecap:"round"})]})]})},Mo=({value:e,onChange:t,ariaLabel:n,placeholder:s,endAdornment:o,size:r="lg",dark:i,styles:l,inputRef:c,autoFocus:d})=>{const{dark:p,dk:m}=f.useSpiceBrand(l,i),h=i??p,x=r==="lg",g=x?"15px":"14px",y=x?"7px":"10px",w=x?f.radius.input:f.radius.sm,C=l?.fontFamily||f.font.ui,b=h?m.inputBg:"#FAFAFA",S=h?m.inputBorder:"#e5e7eb",I=h?m.textPrimary:"#374151",F=h?m.textSecondary:"#9ca3af";return a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",backgroundColor:b,borderRadius:w,boxShadow:h?"0 2px 4px rgba(0, 0, 0, 0.3)":"0 2px 4px rgba(0, 0, 0, 0.1)",padding:`${y} 5px`,border:`1px solid ${S}`},children:[a.jsx(Qc,{style:{color:F},size:24}),a.jsx("input",{ref:c,type:"text",role:"searchbox","aria-label":n,autoComplete:"off",spellCheck:!1,autoFocus:d,"data-spiceflow-focus":!0,placeholder:s,value:e,onChange:k=>t(k.target.value),style:{flex:1,backgroundColor:b,outline:"none",border:"none",color:I,fontSize:g,fontWeight:400,fontFamily:C}}),o]})},pd="This deposit didn't confirm in time. It may still have gone through, so check the explorer and refresh your balance before retrying.";function fd(e){return e?.overallStatus!=="failed"?{isFailed:!1,failureMessage:null}:{isFailed:!0,failureMessage:e.steps?.find(t=>t.status==="failed"&&!!t.error)?.error||pd}}const Ds=a.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",style:{flexShrink:0},children:[a.jsx("circle",{cx:"10",cy:"10",r:"10",fill:"#10b981"}),a.jsx("path",{d:"M6 10l3 3 5-6",stroke:"#ffffff",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),md=({isOpen:e,onClose:t,onConfirm:n,data:s,isExecuting:o=!1,error:r=null,theme:i,styles:l,intentStatus:c,postDepositStatus:d="idle",hasPostDepositInstruction:p=!1})=>{const{dark:m,dk:h,theme:x}=f.useSpiceBrand(l),[g,y]=u.useState(!1),[w,C]=u.useState(!0);u.useEffect(()=>{e||y(!1)},[e]);const b=()=>{y(!0),setTimeout(()=>{t()},300)},S=()=>{C(!w)};if(!e||!s)return null;const I=c?.overallStatus==="processing",F=c?.overallStatus==="success",k=!!c,{isFailed:E,failureMessage:R}=fd(c),j=!k&&p,A=j&&d==="executing",M=j&&d==="success",P=F&&p&&(d==="idle"||d==="executing")||A,N=F&&(!p||d==="success"||d==="error")||M||j&&d==="error",B=m?h.cardBg:"#ffffff",U=m?"0 -4px 20px rgba(0, 0, 0, 0.4)":"0 -4px 20px rgba(0, 0, 0, 0.15)",O=h.textSecondary,z=m?h.textPrimary:"#1f2937",q=m?h.textPrimary:"#1f2937",ue=ne=>a.jsx("div",{style:{marginBottom:i.spacing.md,padding:i.spacing.md,backgroundColor:l?.errorMessage?.backgroundColor||(i.mode==="light"?"#fef2f2":`${i.colors.error}20`),border:`1px solid ${l?.errorMessage?.borderColor||(i.mode==="light"?"#fecaca":i.colors.error)}`,borderRadius:l?.errorMessage?.borderRadius||i.borderRadius.md},children:a.jsx("p",{style:{color:l?.errorMessage?.color||i.colors.error,fontSize:l?.errorMessage?.fontSize||i.typography.fontSize.sm,margin:0,fontFamily:l?.errorMessage?.fontFamily||l?.fontFamily||i.typography.fontFamily},children:ne})}),le={fontSize:i.typography.fontSize.sm,fontWeight:500,color:O,fontFamily:f.font.mono,letterSpacing:"0.5px"},G=(ne,re,Y=z)=>a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[a.jsx("span",{style:le,children:ne}),a.jsx("span",{style:{fontSize:i.typography.fontSize.sm,fontWeight:500,color:Y,fontFamily:f.font.mono},children:re})]});return a.jsxs("div",{style:{position:"absolute",bottom:0,left:0,right:0,zIndex:10,animation:g?"slideDown 0.3s ease-in":"slideUp 0.3s ease-out",pointerEvents:"auto"},children:[a.jsxs("div",{style:{backgroundColor:B,borderRadius:"0",width:"100%",maxWidth:"522px",margin:"0 auto",padding:"18px 24px",boxShadow:U},children:[!F&&!M&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:i.spacing.md},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:"pointer"},onClick:S,children:[a.jsx("span",{style:{fontSize:"13px",fontWeight:i.typography.fontWeight.medium,color:O,fontFamily:l?.fontFamily||i.typography.fontFamily},children:"Transaction Details"}),a.jsx(Mn,{color:O,direction:w?"up":"down"})]}),a.jsx("button",{onClick:ne=>{ne.stopPropagation(),t()},style:{background:"none",border:"none",cursor:"pointer",padding:"4px",display:"flex",alignItems:"center",justifyContent:"center",color:O,transition:"color 0.2s ease"},onMouseEnter:ne=>{ne.currentTarget.style.color=q},onMouseLeave:ne=>{ne.currentTarget.style.color=O},children:a.jsx(ss,{size:16})})]}),a.jsxs("div",{style:{marginBottom:i.spacing.lg,display:"flex",flexDirection:"column",gap:i.spacing.md,overflow:"hidden",maxHeight:w?"200px":"0px",opacity:w?1:0,transition:"max-height 0.3s ease, opacity 0.3s ease"},children:[G("NETWORK",s.network),G("DEPOSITED AMOUNT",s.amount,i.colors.success),s.creditedAmount&&G("CREDITED AMOUNT",s.creditedAmount),s.spicenetFee&&G("SPICENET FEE",s.spicenetFee),s.networkFee&&G("EST. NETWORK FEE",s.networkFee)]})]}),r&&!k&&ue(r),E&&R&&ue(R),a.jsx(f.Button,{onClick:N||E?b:n,variant:"outline",fullWidth:!0,disabled:o||I||P||A,styles:l,theme:x,children:o||I||A||P?"PROCESSING...":N?"CONTINUE \u2192":E?"CLOSE":"CONFIRM DEPOSIT"}),N&&a.jsx("p",{style:{marginTop:i.spacing.md,marginBottom:0,fontSize:"14px",color:O,textAlign:"center",fontFamily:l?.fontFamily||i.typography.fontFamily},children:"Your funds are now available in your Account"}),a.jsx("div",{style:{marginTop:i.spacing.md,display:"flex",justifyContent:"center",alignItems:"center"},children:a.jsx("img",{src:va,alt:"Powered by SpiceNet",style:{height:"auto",width:"130px",opacity:1,filter:m?"brightness(0) invert(1) opacity(0.7)":"none"}})})]}),a.jsx("style",{children:`
|
|
4
4
|
@keyframes slideUp {
|
|
5
5
|
from {
|
|
6
6
|
transform: translateY(100%);
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
transform: translateY(0);
|
|
29
29
|
}
|
|
30
30
|
}
|
|
31
|
-
`})]})},Ma=u.memo(({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,onDepositSelect:s,depositBatches:o,supportedChains:r,title:i,styles:l,onDepositAssetChange:c,assetInputHook:d,externalWalletAddress:p,onDepositAmountChange:m,allowSecondAsset:h=!1,destinationChainId:x,destinationTokenAddress:g,onDepositExecute:y,depositActionLabel:w,nativeChainId:C,sponsorGas:b=!1,preSelectedAsset:S,escrowOnly:I=!1,escrowTokenAddress:F,escrowAmount:k,escrowTokenDecimals:E,escrowTokenSymbol:R,onSubmit:j,onDepositSuccess:A,onDepositError:M,embeddedWalletAddress:P,onViewAllAssets:N})=>{const B=u.useContext(f.SpiceFlowProviderContext),U=B?.mode||"7702",O=B?.allowedTokens,z=!!B?.isWhitelistGateActive,q=!I&&!!B?.isWhitelistConfigured&&B?.isUserWhitelisted!==!0,ue=d?.assetAmount||"",{theme:le,dark:G,appName:ne,primaryColor:re,dk:Y}=f.useSpiceBrand(l),_=f.useWallet(),{isReady:Z,isAuthenticated:pe}=_,{externalWallet:D}=f.useProviderWallets(),L=B?.embeddedWalletAddress||P,$=U!="7702",de=$?!!p:Z&&pe&&!!L,ce=L,he=p,X=ce??he,K=f.useAssetDisplay(),{data:W}=sn.useWalletClient(),[Q,ae]=u.useState(W),we=u.useRef(null),ke=u.useRef(D);ke.current=D;const Ie=D?.address;u.useEffect(()=>{const H=ke.current;if(!H||!he){we.current=null,ae(W);return}if(H.address?.toLowerCase()!==he?.toLowerCase()){we.current=null,ae(W);return}H.getEthereumProvider().then(async ge=>{we.current=ge;const Oe=await ge.request({method:"eth_chainId"}),Ce=parseInt(Oe,16),ot=f.getChainConfig(Ce),Ze=await H.getWalletClient(Ce);ae(ot?T.createWalletClient({account:he,chain:ot.viemChain,transport:T.custom(ge)}):Ze)}).catch(()=>{we.current=null,ae(W)})},[Ie,he,W]);const be=u.useRef(null),[J,Ye]=u.useState([]),{assets:Ne,loading:dt,error:rt,refreshAssets:Me}=es({address:I?ce:he||ce,supportedChains:r,fetchBalances:On,enabled:e,refreshInterval:e?5e3:0}),Pe=u.useMemo(()=>Ne.filter(H=>H.balance>0n&&kn(H,"deposit-source",{allowedTokens:O,rpcOverrides:B?.rpcOverrides,liquidityVenues:B?.liquidityVenues,isWhitelistGateActive:z},void 0,void 0,{requiresEscrow:$||I}).eligible).sort((H,ge)=>ge.balanceUsd-H.balanceUsd),[Ne,O,B?.rpcOverrides,z,$,I]),Xe=u.useMemo(()=>{if(!J[0]?.asset)return[];const H=J[0].asset.chainId;return Pe.filter(ge=>ge.chainId===H)},[Pe,J]),[Ue,ht]=u.useState(!1),[We,at]=u.useState(null),Ae=u.useRef(M);Ae.current=M;const Qe=u.useCallback(H=>{at(H),typeof H=="string"&&H&&Ae.current?.(H,f.getRelayerErrorDetail(H))},[]),[Re,_e]=u.useState("idle"),He=u.useCallback(H=>{typeof H=="string"&&H&&Ae.current?.(H,f.getRelayerErrorDetail(H))},[]),[et,ut]=u.useState(!1),[tt,Ee]=u.useState(null),[st,gt]=u.useState("idle"),[Fe,ee]=u.useState(null),[te,De]=u.useState(null),[ye,ie]=u.useState(null),[je,ve]=u.useState(null),[V,Le]=u.useState(null),{intentStatus:me,startStatusPolling:ze,clearStatus:vt,execute:kt}=Fs(),Se=u.useCallback((H,ge)=>{const Oe=f.CHAIN_CONFIGS[ge];return Oe?Oe.supportedTokens?.find(Ce=>f.addressesEqual(Ce.address,H))?.symbol??null:null},[]),yt=u.useMemo(()=>{const H=J[0]?.asset;if(!H||!g||!x)return!1;const ge=Se(g,x);return fc(H.symbol)&&!!ge&&mc(ge)},[J,g,x,Se]);u.useEffect(()=>{J.length>0&&ue!==J[0]?.amount&&Ye(H=>{if(H.length===0)return H;const ge=[...H];return ge[0]={...ge[0],amount:ue||""},ge})},[ue]),u.useEffect(()=>{J.length!==0&&Ye(H=>{let ge=!1;const Oe=H.map(Ce=>{if(!Ce.asset)return Ce;const ot=Pe.find(Ze=>Ze.chainId===Ce.asset.chainId&&f.addressesEqual(Ze.address,Ce.asset.address));return ot?ot===Ce.asset||ot.balance===Ce.asset.balance?Ce:(ge=!0,{...Ce,asset:ot,amount:Ce.amount}):Ce});return ge?Oe:H})},[Pe,J.length]),u.useEffect(()=>{if(!S||J.length>0||Pe.length===0)return;const H=Pe.find(ge=>ge.chainId===S.chainId&&f.addressesEqual(ge.address,S.address));H&&(Ye([{asset:H,amount:""}]),c?.(H))},[S,Pe,J.length]);const wt=u.useRef(null);u.useEffect(()=>{if($&&me?.overallStatus==="success"&&y&&Re==="idle"){const H=wt.current,ge=be.current;H&&(async()=>{try{_e("executing"),await y(H),_e("success"),Ee(H),ut(!0);const Oe=Array.isArray(ge)?ge[0]:void 0,Ce={type:"deposit",status:"success",amount:H,asset:Oe?.tokenAddress,sourceChain:Oe?String(Oe.chainId):void 0,txHash:Oe?.txHash};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:Ce})),A?.(Ce)}catch(Oe){console.error("onDepositExecute failed:",Oe),_e("error"),He(f.sanitizeError(Oe,"Post-deposit instruction failed"))}finally{wt.current=null,be.current=null}})()}},[me?.overallStatus,$,Re]);const it=u.useCallback(()=>{Qe(null)},[]);u.useEffect(()=>{e||(ut(!1),Ee(null),gt("idle"),ee(null),De(null))},[e]);const nn=u.useCallback((H,ge)=>{Ye(Oe=>{const Ce=[...Oe];return Ce[ge]={asset:H,amount:Ce[ge]?.amount||""},Ce}),ge===0&&c?.(H),it()},[c,it]),mn=u.useCallback(async(H,ge)=>{if(Ye(Oe=>{const Ce=[...Oe];return Ce[ge]&&(Ce[ge]={...Ce[ge],amount:H}),Ce}),it(),ge===0)if(d?.setAssetAmount(H),yt&&H&&parseFloat(H)>0)try{const Oe=ye??await pc();ye||ie(Oe);const Ce=J[0]?.asset;if(!Ce)return;const ot=T.parseUnits(H,Ce.decimals),Ze=g?Se(g,x):null,gn=f.CHAIN_CONFIGS[x]?.supportedTokens?.find(Vs=>f.addressesEqual(Vs.address,g))?.decimals??6,qn=hc(ot,Ce.decimals,gn,Oe);ve(qn);const Hn=T.formatUnits(qn,gn),Hs=Oe.toLocaleString("en-US",{maximumFractionDigits:0});Le(`${H} ${Ce.symbol} \u2248 $${parseFloat(Hn).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})} ${Ze??"USD"} (rate: $${Hs}/BTC)`),m?.(Hn)}catch(Oe){console.error("Failed to fetch BTC/USD price:",Oe),Le(null),ve(null),m?.(H)}else Le(null),ve(null),m?.(H)},[it,d,m,yt,ye,J,g,x,Se]),Gt=u.useCallback(()=>{J.length<2&&Ye(H=>[...H,{asset:null,amount:""}])},[J.length]),an=u.useCallback(H=>{Ye(ge=>ge.filter((Oe,Ce)=>Ce!==H)),it()},[it]),Yt=u.useRef(!1),It=u.useRef(!1);u.useEffect(()=>{e||(Yt.current=!1,It.current=!1,Ke(null),Rt(null))},[e]);const[Ft,Wt]=u.useState(!1),[Bt,Tt]=u.useState(null),[Mt,Ke]=u.useState(null),[qe,Rt]=u.useState(null),[Kt,Dt]=u.useState(!1),[Be,Lt]=u.useState(null),Te=u.useMemo(()=>{const H=J[0];if(J.length!==1||!H?.asset||!H.amount||parseFloat(H.amount)<=0)return null;try{return{asset:H.asset,amount:T.parseUnits(H.amount,H.asset.decimals),token:v.normalizeNativeTokenAddress(H.asset.address),chainId:H.asset.chainId}}catch{return null}},[J]),Ot=!$&&!I&&!!Te&&!wn(Te.asset),pt=u.useMemo(()=>Te?[Te.chainId,Te.token.toLowerCase(),Te.amount.toString(),I?"escrow":"normal"].join("|"):null,[Te,I]),nt=u.useCallback(async(H,ge)=>ce?Ba({address:ce,depositQuote:H,escrowOnly:I,signal:ge}):null,[ce,I]),ln=u.useCallback(async H=>Te?nt(Te,H):null,[Te,nt]),Vt=u.useRef(ln);Vt.current=ln,So({shouldRun:e&&!$&&!Ot&&!!pt&&!Ft&&!Ue,deps:[e,$,Ot,pt,Ft,Ue],delayMs:500,backgroundIntervalMs:1e4,onSkip:()=>{Ke(null),Lt(null),Dt(!1)},onCleanup:()=>Dt(!1),run:async({isBackground:H,isCurrent:ge,signal:Oe})=>{H||(Lt(null),Dt(!0));try{const Ce=await Vt.current(Oe);ge()&&Ke(Ce)}catch(Ce){if(!ge())return;Ke(null),Lt(Ce instanceof Error?Ce.message:"Failed to estimate gas fee")}finally{ge()&&Dt(!1)}}}),u.useEffect(()=>{Ft||Ue||Rt(null)},[Ft,Ue,pt]);const zn=async()=>{if(J.length===0||!J[0]?.asset)return;const H=J.filter(Ze=>Ze.asset&&Ze.amount&&parseFloat(Ze.amount)>0);if(H.length===0)return;const ge=H[0],Oe=f.getChainConfig(ge.asset.chainId),Ce=H.map(Ze=>{const gn=parseFloat(Ze.amount);return`${isNaN(gn)?Ze.amount:gn.toPrecision(6).replace(/\.?0+$/,"")} ${Ze.asset.symbol}`}).join(", "),ot={network:Oe?.displayName||`Chain ${ge.asset.chainId}`,amount:Ce,symbol:"",chainId:ge.asset.chainId};if(!$&&H.length===1&&Mt){Rt(Mt);const Ze=H[0];ot.creditedAmount=`${T.formatUnits(Mt.net,Ze.asset.decimals)} ${wn(Ze.asset)?K({...Ze.asset,location:"rollup",_source:"spice",receiptTokenName:"spiceUSDC"}).symbol:Ze.asset.symbol}`,ot.networkFee=`${T.formatUnits(Mt.fee,Ze.asset.decimals)} ${Ze.asset.symbol}`}Tt(ot),Wt(!0)},oe=u.useRef(me);oe.current=me;const fe=u.useRef(Re);fe.current=Re;const xe=async()=>{await ed({selectedDepositAssets:J,escrowOnly:I,sourceAddress:he,isNon7702:$,address:ce,embeddedWalletAddress:L,isReady:Z,isAuthenticated:pe,zeroCreditError:Ve,depositBalanceError:Ut,externalWalletClient:Q,externalProvider:we.current,effectiveDepositFee:ft,depositBatches:o,destinationChainId:x,destinationTokenAddress:g,isCrossDenomination:yt,convertedUsdAmount:je,mode:U,sponsorGas:b,nativeChainId:C,spiceBalanceUser:X,depositDataRef:be,bridgedAmountRef:wt,setIsExecuting:ht,setError:Qe,setConfirmationData:Tt,setShowConfirmation:Wt,setDirectDepositStatus:gt,setDirectDepositChainId:De,setDirectDepositTxHash:ee,setPostDepositStatus:_e,setPostDepositError:He,setPostDepositAmount:Ee,setPostDepositSuccess:ut,startStatusPolling:ze,clearStatus:vt,refreshAssets:Me,onDepositExecute:y,onDepositSelect:s,onDepositSuccess:A,execution:{execute:kt},getCurrentIntentStatus:()=>oe.current,getCurrentPostDepositStatus:()=>fe.current})},Ve=u.useMemo(()=>{for(const H of J)if(!(!H?.asset||!H.amount||parseFloat(H.amount)<=0))try{const ge=H.asset.decimals,Oe=T.parseUnits(H.amount,ge);if(Oe<=0n)continue;const Ce=v.normalizeNativeTokenAddress(H.asset.address),ot=v.isNativeToken(Ce)?v.getTokenByAddress(Ce,H.asset.chainId)?.equivalenceGroup:v.getEquivalenceGroup(Ce),Ze=H.asset.receiptTokenDecimals??(ot==="ETH"||ot==="ARB"?18:ot==="USDC"||ot==="SUSD"||ot==="WBTC"||ot==="CBTC"?6:void 0);if(Ze===void 0||ge<=Ze||v.convertAmountBetweenDecimals(Oe,ge,Ze)>0n)continue;return`Amount too small. Minimum deposit for this asset is ${T.formatUnits(10n**BigInt(ge-Ze),ge)} ${H.asset.symbol}.`}catch{continue}return null},[J]),St=!$&&!!Te&&!Ot,ft=qe??Mt,Pt=!!Te&&ja(ft,Te),Ut=u.useMemo(()=>{if(!Te)return null;if(Ot)return Te.asset.balance>=Te.amount?null:`Insufficient ${Te.asset.symbol}. Need ${T.formatUnits(Te.amount,Te.asset.decimals)} ${Te.asset.symbol}.`;if(!St||!Pt)return null;const H=I?Te.amount:Te.amount+ft.fee;return Te.asset.balance>=H?null:`Insufficient ${Te.asset.symbol}. Need ${T.formatUnits(H,Te.asset.decimals)} ${Te.asset.symbol} including gas.`},[St,Ot,Te,Pt,ft,I]),[qt,At]=u.useState(!1),Nt=J[0]?.asset?.chainId,bt=Ne.find(H=>H.isNative&&H.chainId===Nt)?.balance??0n;u.useEffect(()=>{if(!e||!Nt){At(!1);return}let H=!1;return(async()=>{try{const ge=await f.getClientForChain(Nt).getGasPrice()*150000n;H||At(bt<ge)}catch{H||At(!1)}})(),()=>{H=!0}},[e,Nt,bt]);const vn=!St||Pt&&!Kt&&!Be&&!Ut,Et=u.useCallback((H,ge)=>td({asset:H,assetIndex:ge,selectedAssetCount:J.length,address:ce,escrowOnly:I,isNon7702:$}),[$,J.length,ce,I]),Zt=u.useMemo(()=>{if(!Te||!ft||!Pt)return null;const H=I?Te.amount:Te.amount+ft.fee;return{symbol:Te.asset.symbol,decimals:Te.asset.decimals,grossAmount:H,netAmount:ft.net,totalFee:ft.fee,gasFee:ft.fee,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"estimated"}},[Te,ft,Pt,I]),$t=parseFloat(J[0]?.amount||"")||0,Xt=J.length>0&&J[0]?.asset&&J[0]?.amount&&$t>0&&de&&!Ue&&!Ve&&!Ut&&vn&&!q;u.useEffect(()=>{if(!I||!F||!k||Yt.current||!de)return;const H=r[0];if(!H)return;const ge=f.getAllAssetsForChain(H,[]).find(Ce=>f.addressesEqual(Ce.address,F));let Oe;if(ge)Oe=ge;else if(E!==void 0&&R)Oe={address:F,symbol:R,name:R,decimals:E,chainId:H,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,isNative:v.isNativeToken(F)};else{console.warn("[DepositModal] escrowOnly: no matching asset and missing escrowTokenDecimals/escrowTokenSymbol for",F);return}Yt.current=!0,Ye([{asset:Oe,amount:k}])},[I,F,k,E,R,de,r]),u.useEffect(()=>{!I||!Xt||It.current||Ue||(It.current=!0,xe())},[I,Xt,Ue]);const hn=rt||We||Ve||Ut,Fn=()=>{if(Ue)return"Executing Deposit...";if(!de)return"Wallet Not Connected";if(U==="7702"){if(!Z)return"Loading...";if(!pe)return"Authentication Required"}return J[0]?.asset?J[0]?.amount?Ve?"AMOUNT TOO SMALL":Ut?"INSUFFICIENT BALANCE":St&&!vn?Be?"GAS UNAVAILABLE":"ESTIMATING GAS":"DEPOSIT":"ENTER AMOUNT":"SELECT TOKEN"};return e?a.jsx(tn,{isOpen:e,onClose:t,closeOnBackdropClick:n,title:i||`Deposit to your ${ne} account`,subtitle:a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[a.jsx("img",{src:ko,alt:"","aria-hidden":"true",style:{width:"13px",height:"13px",flexShrink:0,...G?{filter:"invert(0.6)"}:{}}}),a.jsx("p",{style:{fontSize:"12px",color:Y.textSecondary,margin:"0",lineHeight:"1.4",fontFamily:f.font.ui},children:`Deposit collateral to your ${ne} Account from any supported network.`})]}),dark:G,overlayContent:Ft||me||Re!=="idle"&&y?a.jsx("div",{}):void 0,styles:l,theme:le,children:a.jsxs("div",{style:{padding:"24px 24px 5px 24px"},children:[a.jsx(dd,{selectedDepositAssets:J,depositAssets:Pe,secondAssetOptions:Xe,loadingAssets:dt,allowSecondAsset:h,theme:le,styles:l,dark:G,dk:Y,onSelect:nn,onAmountChange:mn,onAdd:Gt,onRemove:an,resolveMaxAmount:Et,onViewAllAssets:N}),St&&Te&&a.jsx(Bo,{fontFamily:l?.fontFamily||le.typography.fontFamily,textPrimary:Y.textPrimary,textSecondary:Y.textSecondary,cardBg:G?Y.inputBg:"#ffffff",cardBorder:Y.cardBorder,resolvedDark:G,darkCardBorder:Y.cardBorder,primaryColor:re,feePreview:Zt,isLoading:Kt||St&&!Pt,errorText:Be}),a.jsx(hd,{intentStatus:me,postDepositSuccess:et,postDepositAmount:tt,postDepositStatus:Re,depositActionLabel:w,sourceChainName:J[0]?.asset?.chainId?f.getChainName(J[0].asset.chainId):"Destination Chain",directDepositStatus:st,directDepositTxHash:Fe,directDepositChainId:te,styles:l}),a.jsx(md,{isOpen:Ft||!!me||Re!=="idle"&&!!y,onClose:()=>{Wt(!1),me&&vt();const H=Re==="success"&&!me,ge=me?.overallStatus==="success"&&(y?Re==="success":!0);(H||ge)&&t()},onConfirm:()=>{if(!Ue)return j?.(),xe()},data:Bt,isExecuting:Ue,error:We,theme:le,styles:l,intentStatus:me,postDepositStatus:Re,hasPostDepositInstruction:!!y}),V&&a.jsxs(Ia,{dk:Y,dark:G,borderRadius:le.borderRadius.md,children:["\u26A1 ",V]}),qt&&a.jsx(Ia,{dk:Y,dark:G,borderRadius:le.borderRadius.md,children:"Low native balance in the external wallet. The deposit to spicenet account might fail."}),a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:0,marginBottom:0,margin:0,padding:0},children:[hn?a.jsx("div",{style:{marginBottom:"10px",fontSize:"12px",lineHeight:"1.45",color:Y.errorText,fontFamily:l?.fontFamily||le.typography.fontFamily},children:hn}):null,a.jsx(f.Button,{variant:"outline",fullWidth:!0,onClick:zn,disabled:!Xt||!de||Ue,theme:le,dark:G,styles:l,children:Fn()})]})]})}):null});function Qt(e,t,n,s){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const o=10n**BigInt(t-n);return s==="ceil"?(e+o-1n)/o:e/o}function zt(e,t){if(!Number.isInteger(t)||t<0||t>255)throw new Error("Invalid token decimals");if(!/^\d+(?:\.\d*)?$/.test(e))throw new Error("Enter a valid amount.");if((e.split(".")[1]?.replace(/0+$/,"")??"").length>t)throw new Error(`Use at most ${t} decimal places for this source.`);return T.parseUnits(e,t)}function Os(e,t,n){const s=Qt(e,t,n,"floor");if(Qt(s,n,t,"floor")!==e)throw new Error(`Use at most ${n} decimal places for this delivered token.`);return s}function gd(e){return`0x77${e.slice(4)}`}function Ns({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((x,g)=>x+g.amount,0n);if(d<=0n)return null;const p=l??Date.now(),m=BigInt(Math.floor(p/1e3)),h=gd(T.keccak256(T.encodeAbiParameters([{type:"address"},{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[e??r,n,r,d,BigInt(t),BigInt(p)])));return{chainId:v.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:[{to:v.ZERO_ADDRESS,value:0n,data:T.encodeFunctionData({abi:v.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${t}`,idempotenceKey:h,nbf:0n,exp:m+3600n,metadata:"{}",transfers:c.map(x=>({token:T.getAddress(x.token).toLowerCase(),to:T.getAddress(x.recipient).toLowerCase(),amount:x.amount}))}]})}]}}const Po=e=>{const[t,n]=u.useState(!1),s=u.useContext(f.SpiceFlowProviderContext),{dark:o,dk:r}=f.useSpiceBrand();if(u.useEffect(()=>{n(!0)},[]),!t)return a.jsx("div",{className:e.className,children:a.jsx("button",{disabled:!0,style:{padding:"12px 24px",fontSize:"16px",backgroundColor:o?r.hoverBg:"#ccc",color:o?r.textSecondary:"white",border:o?`1px solid ${r.buttonBorder}`:"none",borderRadius:"4px",cursor:"not-allowed"},children:"Loading..."})});if(!s){const i='ProviderLogin must be used within SpiceFlowProvider. Please wrap your app with <SpiceFlowProvider provider="privy">.';return a.jsx("div",{className:e.className,children:a.jsx("button",{onClick:()=>{e.onAuthError&&e.onAuthError(i)},style:{padding:"12px 24px",fontSize:"16px",backgroundColor:o?r.errorBg:"#dc2626",color:o?r.errorText:"white",border:o?`1px solid ${r.errorBorder}`:"none",borderRadius:"4px",cursor:"pointer"},children:"Provider Not Found"})})}return a.jsx(f.PrivyLogin,{...e})},Pa=({isSuccess:e,type:t,chainName:n,explorerUrl:s,txHash:o,dark:r=!1,successBg:i="#d1fae5",successBorder:l="#6ee7b7",successText:c="#065f46",errorBg:d="#fee2e2",errorBorder:p="#fca5a5",errorText:m="#dc2626",textSecondary:h="#6b7280"})=>a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px",borderRadius:"8px",backgroundColor:e?i:d,border:e?`1px solid ${l}`:`1px solid ${p}`},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[a.jsx("div",{style:{width:"28px",height:"28px",borderRadius:"50%",backgroundColor:e?"#10b981":"#ef4444",display:"flex",alignItems:"center",justifyContent:"center"},children:e?a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:a.jsx("path",{d:"M11.6667 3.5L5.25 9.91667L2.33333 7",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}):a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:a.jsx("path",{d:"M10.5 3.5L3.5 10.5M3.5 3.5L10.5 10.5",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),a.jsxs("div",{children:[a.jsx("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:f.font.mono,letterSpacing:"0.5px",color:e?c:m},children:e?`${t.toUpperCase()} CONFIRMED`:`${t.toUpperCase()} FAILED`}),a.jsxs("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:h},children:["on ",n]})]})]}),s&&o&&a.jsxs("a",{href:`${s}/tx/${o}`,target:"_blank",rel:"noopener noreferrer",style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"13px",color:h,textDecoration:"none",whiteSpace:"nowrap"},children:["View on explorer",a.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:[a.jsx("path",{d:"M9 6.5V9.5C9 9.76522 8.89464 10.0196 8.70711 10.2071C8.51957 10.3946 8.26522 10.5 8 10.5H2.5C2.23478 10.5 1.98043 10.3946 1.79289 10.2071C1.60536 10.0196 1.5 9.76522 1.5 9.5V4C1.5 3.73478 1.60536 3.48043 1.79289 3.29289C1.98043 3.10536 2.23478 3 2.5 3H5.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),a.jsx("path",{d:"M7.5 1.5H10.5V4.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),a.jsx("path",{d:"M5 7L10.5 1.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})]})]})]}),Ua=`
|
|
31
|
+
`})]})},Ma=u.memo(({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,onDepositSelect:s,depositBatches:o,supportedChains:r,title:i,styles:l,onDepositAssetChange:c,assetInputHook:d,externalWalletAddress:p,onDepositAmountChange:m,allowSecondAsset:h=!1,destinationChainId:x,destinationTokenAddress:g,onDepositExecute:y,depositActionLabel:w,nativeChainId:C,sponsorGas:b=!1,preSelectedAsset:S,escrowOnly:I=!1,escrowTokenAddress:F,escrowAmount:k,escrowTokenDecimals:E,escrowTokenSymbol:R,onSubmit:j,onDepositSuccess:A,onDepositError:M,embeddedWalletAddress:P,onViewAllAssets:N})=>{const B=u.useContext(f.SpiceFlowProviderContext),U=B?.mode||"7702",O=B?.allowedTokens,z=!!B?.isWhitelistGateActive,q=!I&&!!B?.isWhitelistConfigured&&B?.isUserWhitelisted!==!0,ue=d?.assetAmount||"",{theme:le,dark:G,appName:ne,primaryColor:re,dk:Y}=f.useSpiceBrand(l),_=f.useWallet(),{isReady:Z,isAuthenticated:pe}=_,{externalWallet:D}=f.useProviderWallets(),L=B?.embeddedWalletAddress||P,$=U!="7702",de=$?!!p:Z&&pe&&!!L,ce=L,he=p,X=ce??he,K=f.useAssetDisplay(),{data:W}=sn.useWalletClient(),[Q,ae]=u.useState(W),we=u.useRef(null),ke=u.useRef(D);ke.current=D;const Ie=D?.address;u.useEffect(()=>{const H=ke.current;if(!H||!he){we.current=null,ae(W);return}if(H.address?.toLowerCase()!==he?.toLowerCase()){we.current=null,ae(W);return}H.getEthereumProvider().then(async ge=>{we.current=ge;const Oe=await ge.request({method:"eth_chainId"}),Ce=parseInt(Oe,16),ot=f.getChainConfig(Ce),Ze=await H.getWalletClient(Ce);ae(ot?T.createWalletClient({account:he,chain:ot.viemChain,transport:T.custom(ge)}):Ze)}).catch(()=>{we.current=null,ae(W)})},[Ie,he,W]);const be=u.useRef(null),[J,Ye]=u.useState([]),{assets:Ne,loading:dt,error:rt,refreshAssets:Me}=es({address:I?ce:he||ce,supportedChains:r,fetchBalances:On,enabled:e,refreshInterval:e?5e3:0}),Pe=u.useMemo(()=>Ne.filter(H=>H.balance>0n&&kn(H,"deposit-source",{allowedTokens:O,rpcOverrides:B?.rpcOverrides,liquidityVenues:B?.liquidityVenues,isWhitelistGateActive:z},void 0,void 0,{requiresEscrow:$||I}).eligible).sort((H,ge)=>ge.balanceUsd-H.balanceUsd),[Ne,O,B?.rpcOverrides,z,$,I]),Xe=u.useMemo(()=>{if(!J[0]?.asset)return[];const H=J[0].asset.chainId;return Pe.filter(ge=>ge.chainId===H)},[Pe,J]),[Ue,ht]=u.useState(!1),[We,at]=u.useState(null),Ae=u.useRef(M);Ae.current=M;const Qe=u.useCallback(H=>{at(H),typeof H=="string"&&H&&Ae.current?.(H,f.getRelayerErrorDetail(H))},[]),[Re,_e]=u.useState("idle"),He=u.useCallback(H=>{typeof H=="string"&&H&&Ae.current?.(H,f.getRelayerErrorDetail(H))},[]),[et,ut]=u.useState(!1),[tt,Ee]=u.useState(null),[st,gt]=u.useState("idle"),[Fe,ee]=u.useState(null),[te,De]=u.useState(null),[ye,ie]=u.useState(null),[je,ve]=u.useState(null),[V,Le]=u.useState(null),{intentStatus:me,startStatusPolling:ze,clearStatus:vt,execute:kt}=Fs(),Se=u.useCallback((H,ge)=>{const Oe=f.CHAIN_CONFIGS[ge];return Oe?Oe.supportedTokens?.find(Ce=>f.addressesEqual(Ce.address,H))?.symbol??null:null},[]),yt=u.useMemo(()=>{const H=J[0]?.asset;if(!H||!g||!x)return!1;const ge=Se(g,x);return fc(H.symbol)&&!!ge&&mc(ge)},[J,g,x,Se]);u.useEffect(()=>{J.length>0&&ue!==J[0]?.amount&&Ye(H=>{if(H.length===0)return H;const ge=[...H];return ge[0]={...ge[0],amount:ue||""},ge})},[ue]),u.useEffect(()=>{J.length!==0&&Ye(H=>{let ge=!1;const Oe=H.map(Ce=>{if(!Ce.asset)return Ce;const ot=Pe.find(Ze=>Ze.chainId===Ce.asset.chainId&&f.addressesEqual(Ze.address,Ce.asset.address));return ot?ot===Ce.asset||ot.balance===Ce.asset.balance?Ce:(ge=!0,{...Ce,asset:ot,amount:Ce.amount}):Ce});return ge?Oe:H})},[Pe,J.length]),u.useEffect(()=>{if(!S||J.length>0||Pe.length===0)return;const H=Pe.find(ge=>ge.chainId===S.chainId&&f.addressesEqual(ge.address,S.address));H&&(Ye([{asset:H,amount:""}]),c?.(H))},[S,Pe,J.length]);const wt=u.useRef(null);u.useEffect(()=>{if($&&me?.overallStatus==="success"&&y&&Re==="idle"){const H=wt.current,ge=be.current;H&&(async()=>{try{_e("executing"),await y(H),_e("success"),Ee(H),ut(!0);const Oe=Array.isArray(ge)?ge[0]:void 0,Ce={type:"deposit",status:"success",amount:H,asset:Oe?.tokenAddress,sourceChain:Oe?String(Oe.chainId):void 0,txHash:Oe?.txHash};window.dispatchEvent(new CustomEvent("spiceflow:action",{detail:Ce})),A?.(Ce)}catch(Oe){console.error("onDepositExecute failed:",Oe),_e("error"),He(f.sanitizeError(Oe,"Post-deposit instruction failed"))}finally{wt.current=null,be.current=null}})()}},[me?.overallStatus,$,Re]);const it=u.useCallback(()=>{Qe(null)},[]);u.useEffect(()=>{e||(ut(!1),Ee(null),gt("idle"),ee(null),De(null))},[e]);const nn=u.useCallback((H,ge)=>{Ye(Oe=>{const Ce=[...Oe];return Ce[ge]={asset:H,amount:Ce[ge]?.amount||""},Ce}),ge===0&&c?.(H),it()},[c,it]),mn=u.useCallback(async(H,ge)=>{if(Ye(Oe=>{const Ce=[...Oe];return Ce[ge]&&(Ce[ge]={...Ce[ge],amount:H}),Ce}),it(),ge===0)if(d?.setAssetAmount(H),yt&&H&&parseFloat(H)>0)try{const Oe=ye??await pc();ye||ie(Oe);const Ce=J[0]?.asset;if(!Ce)return;const ot=T.parseUnits(H,Ce.decimals),Ze=g?Se(g,x):null,gn=f.CHAIN_CONFIGS[x]?.supportedTokens?.find(Vs=>f.addressesEqual(Vs.address,g))?.decimals??6,qn=hc(ot,Ce.decimals,gn,Oe);ve(qn);const Hn=T.formatUnits(qn,gn),Hs=Oe.toLocaleString("en-US",{maximumFractionDigits:0});Le(`${H} ${Ce.symbol} \u2248 $${parseFloat(Hn).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})} ${Ze??"USD"} (rate: $${Hs}/BTC)`),m?.(Hn)}catch(Oe){console.error("Failed to fetch BTC/USD price:",Oe),Le(null),ve(null),m?.(H)}else Le(null),ve(null),m?.(H)},[it,d,m,yt,ye,J,g,x,Se]),Gt=u.useCallback(()=>{J.length<2&&Ye(H=>[...H,{asset:null,amount:""}])},[J.length]),an=u.useCallback(H=>{Ye(ge=>ge.filter((Oe,Ce)=>Ce!==H)),it()},[it]),Yt=u.useRef(!1),It=u.useRef(!1);u.useEffect(()=>{e||(Yt.current=!1,It.current=!1,Ke(null),Rt(null))},[e]);const[Ft,Wt]=u.useState(!1),[Bt,Tt]=u.useState(null),[Mt,Ke]=u.useState(null),[qe,Rt]=u.useState(null),[Kt,Dt]=u.useState(!1),[Be,Lt]=u.useState(null),Te=u.useMemo(()=>{const H=J[0];if(J.length!==1||!H?.asset||!H.amount||parseFloat(H.amount)<=0)return null;try{return{asset:H.asset,amount:T.parseUnits(H.amount,H.asset.decimals),token:v.normalizeNativeTokenAddress(H.asset.address),chainId:H.asset.chainId}}catch{return null}},[J]),Ot=!$&&!I&&!!Te&&!wn(Te.asset),pt=u.useMemo(()=>Te?[Te.chainId,Te.token.toLowerCase(),Te.amount.toString(),I?"escrow":"normal"].join("|"):null,[Te,I]),nt=u.useCallback(async(H,ge)=>ce?Ba({address:ce,depositQuote:H,escrowOnly:I,signal:ge}):null,[ce,I]),ln=u.useCallback(async H=>Te?nt(Te,H):null,[Te,nt]),Vt=u.useRef(ln);Vt.current=ln,So({shouldRun:e&&!$&&!Ot&&!!pt&&!Ft&&!Ue,deps:[e,$,Ot,pt,Ft,Ue],delayMs:500,backgroundIntervalMs:3e4,onSkip:()=>{Ke(null),Lt(null),Dt(!1)},onCleanup:()=>Dt(!1),run:async({isBackground:H,isCurrent:ge,signal:Oe})=>{H||(Lt(null),Dt(!0));try{const Ce=await Vt.current(Oe);ge()&&Ke(Ce)}catch(Ce){if(!ge())return;Ke(null),Lt(Ce instanceof Error?Ce.message:"Failed to estimate gas fee")}finally{ge()&&Dt(!1)}}}),u.useEffect(()=>{Ft||Ue||Rt(null)},[Ft,Ue,pt]);const zn=async()=>{if(J.length===0||!J[0]?.asset)return;const H=J.filter(Ze=>Ze.asset&&Ze.amount&&parseFloat(Ze.amount)>0);if(H.length===0)return;const ge=H[0],Oe=f.getChainConfig(ge.asset.chainId),Ce=H.map(Ze=>{const gn=parseFloat(Ze.amount);return`${isNaN(gn)?Ze.amount:gn.toPrecision(6).replace(/\.?0+$/,"")} ${Ze.asset.symbol}`}).join(", "),ot={network:Oe?.displayName||`Chain ${ge.asset.chainId}`,amount:Ce,symbol:"",chainId:ge.asset.chainId};if(!$&&H.length===1&&Mt){Rt(Mt);const Ze=H[0];ot.creditedAmount=`${T.formatUnits(Mt.net,Ze.asset.decimals)} ${wn(Ze.asset)?K({...Ze.asset,location:"rollup",_source:"spice",receiptTokenName:"spiceUSDC"}).symbol:Ze.asset.symbol}`,ot.networkFee=`${T.formatUnits(Mt.fee,Ze.asset.decimals)} ${Ze.asset.symbol}`}Tt(ot),Wt(!0)},oe=u.useRef(me);oe.current=me;const fe=u.useRef(Re);fe.current=Re;const xe=async()=>{await ed({selectedDepositAssets:J,escrowOnly:I,sourceAddress:he,isNon7702:$,address:ce,embeddedWalletAddress:L,isReady:Z,isAuthenticated:pe,zeroCreditError:Ve,depositBalanceError:Ut,externalWalletClient:Q,externalProvider:we.current,effectiveDepositFee:ft,depositBatches:o,destinationChainId:x,destinationTokenAddress:g,isCrossDenomination:yt,convertedUsdAmount:je,mode:U,sponsorGas:b,nativeChainId:C,spiceBalanceUser:X,depositDataRef:be,bridgedAmountRef:wt,setIsExecuting:ht,setError:Qe,setConfirmationData:Tt,setShowConfirmation:Wt,setDirectDepositStatus:gt,setDirectDepositChainId:De,setDirectDepositTxHash:ee,setPostDepositStatus:_e,setPostDepositError:He,setPostDepositAmount:Ee,setPostDepositSuccess:ut,startStatusPolling:ze,clearStatus:vt,refreshAssets:Me,onDepositExecute:y,onDepositSelect:s,onDepositSuccess:A,execution:{execute:kt},getCurrentIntentStatus:()=>oe.current,getCurrentPostDepositStatus:()=>fe.current})},Ve=u.useMemo(()=>{for(const H of J)if(!(!H?.asset||!H.amount||parseFloat(H.amount)<=0))try{const ge=H.asset.decimals,Oe=T.parseUnits(H.amount,ge);if(Oe<=0n)continue;const Ce=v.normalizeNativeTokenAddress(H.asset.address),ot=v.isNativeToken(Ce)?v.getTokenByAddress(Ce,H.asset.chainId)?.equivalenceGroup:v.getEquivalenceGroup(Ce),Ze=H.asset.receiptTokenDecimals??(ot==="ETH"||ot==="ARB"?18:ot==="USDC"||ot==="SUSD"||ot==="WBTC"||ot==="CBTC"?6:void 0);if(Ze===void 0||ge<=Ze||v.convertAmountBetweenDecimals(Oe,ge,Ze)>0n)continue;return`Amount too small. Minimum deposit for this asset is ${T.formatUnits(10n**BigInt(ge-Ze),ge)} ${H.asset.symbol}.`}catch{continue}return null},[J]),St=!$&&!!Te&&!Ot,ft=qe??Mt,Pt=!!Te&&ja(ft,Te),Ut=u.useMemo(()=>{if(!Te)return null;if(Ot)return Te.asset.balance>=Te.amount?null:`Insufficient ${Te.asset.symbol}. Need ${T.formatUnits(Te.amount,Te.asset.decimals)} ${Te.asset.symbol}.`;if(!St||!Pt)return null;const H=I?Te.amount:Te.amount+ft.fee;return Te.asset.balance>=H?null:`Insufficient ${Te.asset.symbol}. Need ${T.formatUnits(H,Te.asset.decimals)} ${Te.asset.symbol} including gas.`},[St,Ot,Te,Pt,ft,I]),[qt,At]=u.useState(!1),Nt=J[0]?.asset?.chainId,bt=Ne.find(H=>H.isNative&&H.chainId===Nt)?.balance??0n;u.useEffect(()=>{if(!e||!Nt){At(!1);return}let H=!1;return(async()=>{try{const ge=await f.getClientForChain(Nt).getGasPrice()*150000n;H||At(bt<ge)}catch{H||At(!1)}})(),()=>{H=!0}},[e,Nt,bt]);const vn=!St||Pt&&!Kt&&!Be&&!Ut,Et=u.useCallback((H,ge)=>td({asset:H,assetIndex:ge,selectedAssetCount:J.length,address:ce,escrowOnly:I,isNon7702:$}),[$,J.length,ce,I]),Zt=u.useMemo(()=>{if(!Te||!ft||!Pt)return null;const H=I?Te.amount:Te.amount+ft.fee;return{symbol:Te.asset.symbol,decimals:Te.asset.decimals,grossAmount:H,netAmount:ft.net,totalFee:ft.fee,gasFee:ft.fee,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"estimated"}},[Te,ft,Pt,I]),$t=parseFloat(J[0]?.amount||"")||0,Xt=J.length>0&&J[0]?.asset&&J[0]?.amount&&$t>0&&de&&!Ue&&!Ve&&!Ut&&vn&&!q;u.useEffect(()=>{if(!I||!F||!k||Yt.current||!de)return;const H=r[0];if(!H)return;const ge=f.getAllAssetsForChain(H,[]).find(Ce=>f.addressesEqual(Ce.address,F));let Oe;if(ge)Oe=ge;else if(E!==void 0&&R)Oe={address:F,symbol:R,name:R,decimals:E,chainId:H,balance:BigInt(0),balanceFormatted:0,balanceUsd:0,isNative:v.isNativeToken(F)};else{console.warn("[DepositModal] escrowOnly: no matching asset and missing escrowTokenDecimals/escrowTokenSymbol for",F);return}Yt.current=!0,Ye([{asset:Oe,amount:k}])},[I,F,k,E,R,de,r]),u.useEffect(()=>{!I||!Xt||It.current||Ue||(It.current=!0,xe())},[I,Xt,Ue]);const hn=rt||We||Ve||Ut,Fn=()=>{if(Ue)return"Executing Deposit...";if(!de)return"Wallet Not Connected";if(U==="7702"){if(!Z)return"Loading...";if(!pe)return"Authentication Required"}return J[0]?.asset?J[0]?.amount?Ve?"AMOUNT TOO SMALL":Ut?"INSUFFICIENT BALANCE":St&&!vn?Be?"GAS UNAVAILABLE":"ESTIMATING GAS":"DEPOSIT":"ENTER AMOUNT":"SELECT TOKEN"};return e?a.jsx(tn,{isOpen:e,onClose:t,closeOnBackdropClick:n,title:i||`Deposit to your ${ne} account`,subtitle:a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[a.jsx("img",{src:ko,alt:"","aria-hidden":"true",style:{width:"13px",height:"13px",flexShrink:0,...G?{filter:"invert(0.6)"}:{}}}),a.jsx("p",{style:{fontSize:"12px",color:Y.textSecondary,margin:"0",lineHeight:"1.4",fontFamily:f.font.ui},children:`Deposit collateral to your ${ne} Account from any supported network.`})]}),dark:G,overlayContent:Ft||me||Re!=="idle"&&y?a.jsx("div",{}):void 0,styles:l,theme:le,children:a.jsxs("div",{style:{padding:"24px 24px 5px 24px"},children:[a.jsx(dd,{selectedDepositAssets:J,depositAssets:Pe,secondAssetOptions:Xe,loadingAssets:dt,allowSecondAsset:h,theme:le,styles:l,dark:G,dk:Y,onSelect:nn,onAmountChange:mn,onAdd:Gt,onRemove:an,resolveMaxAmount:Et,onViewAllAssets:N}),St&&Te&&a.jsx(Bo,{fontFamily:l?.fontFamily||le.typography.fontFamily,textPrimary:Y.textPrimary,textSecondary:Y.textSecondary,cardBg:G?Y.inputBg:"#ffffff",cardBorder:Y.cardBorder,resolvedDark:G,darkCardBorder:Y.cardBorder,primaryColor:re,feePreview:Zt,isLoading:Kt||St&&!Pt,errorText:Be}),a.jsx(hd,{intentStatus:me,postDepositSuccess:et,postDepositAmount:tt,postDepositStatus:Re,depositActionLabel:w,sourceChainName:J[0]?.asset?.chainId?f.getChainName(J[0].asset.chainId):"Destination Chain",directDepositStatus:st,directDepositTxHash:Fe,directDepositChainId:te,styles:l}),a.jsx(md,{isOpen:Ft||!!me||Re!=="idle"&&!!y,onClose:()=>{Wt(!1),me&&vt();const H=Re==="success"&&!me,ge=me?.overallStatus==="success"&&(y?Re==="success":!0);(H||ge)&&t()},onConfirm:()=>{if(!Ue)return j?.(),xe()},data:Bt,isExecuting:Ue,error:We,theme:le,styles:l,intentStatus:me,postDepositStatus:Re,hasPostDepositInstruction:!!y}),V&&a.jsxs(Ia,{dk:Y,dark:G,borderRadius:le.borderRadius.md,children:["\u26A1 ",V]}),qt&&a.jsx(Ia,{dk:Y,dark:G,borderRadius:le.borderRadius.md,children:"Low native balance in the external wallet. The deposit to spicenet account might fail."}),a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:0,marginBottom:0,margin:0,padding:0},children:[hn?a.jsx("div",{style:{marginBottom:"10px",fontSize:"12px",lineHeight:"1.45",color:Y.errorText,fontFamily:l?.fontFamily||le.typography.fontFamily},children:hn}):null,a.jsx(f.Button,{variant:"outline",fullWidth:!0,onClick:zn,disabled:!Xt||!de||Ue,theme:le,dark:G,styles:l,children:Fn()})]})]})}):null});function Qt(e,t,n,s){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const o=10n**BigInt(t-n);return s==="ceil"?(e+o-1n)/o:e/o}function zt(e,t){if(!Number.isInteger(t)||t<0||t>255)throw new Error("Invalid token decimals");if(!/^\d+(?:\.\d*)?$/.test(e))throw new Error("Enter a valid amount.");if((e.split(".")[1]?.replace(/0+$/,"")??"").length>t)throw new Error(`Use at most ${t} decimal places for this source.`);return T.parseUnits(e,t)}function Os(e,t,n){const s=Qt(e,t,n,"floor");if(Qt(s,n,t,"floor")!==e)throw new Error(`Use at most ${n} decimal places for this delivered token.`);return s}function gd(e){return`0x77${e.slice(4)}`}function Ns({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((x,g)=>x+g.amount,0n);if(d<=0n)return null;const p=l??Date.now(),m=BigInt(Math.floor(p/1e3)),h=gd(T.keccak256(T.encodeAbiParameters([{type:"address"},{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[e??r,n,r,d,BigInt(t),BigInt(p)])));return{chainId:v.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:[{to:v.ZERO_ADDRESS,value:0n,data:T.encodeFunctionData({abi:v.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${t}`,idempotenceKey:h,nbf:0n,exp:m+3600n,metadata:"{}",transfers:c.map(x=>({token:T.getAddress(x.token).toLowerCase(),to:T.getAddress(x.recipient).toLowerCase(),amount:x.amount}))}]})}]}}const Po=e=>{const[t,n]=u.useState(!1),s=u.useContext(f.SpiceFlowProviderContext),{dark:o,dk:r}=f.useSpiceBrand();if(u.useEffect(()=>{n(!0)},[]),!t)return a.jsx("div",{className:e.className,children:a.jsx("button",{disabled:!0,style:{padding:"12px 24px",fontSize:"16px",backgroundColor:o?r.hoverBg:"#ccc",color:o?r.textSecondary:"white",border:o?`1px solid ${r.buttonBorder}`:"none",borderRadius:"4px",cursor:"not-allowed"},children:"Loading..."})});if(!s){const i='ProviderLogin must be used within SpiceFlowProvider. Please wrap your app with <SpiceFlowProvider provider="privy">.';return a.jsx("div",{className:e.className,children:a.jsx("button",{onClick:()=>{e.onAuthError&&e.onAuthError(i)},style:{padding:"12px 24px",fontSize:"16px",backgroundColor:o?r.errorBg:"#dc2626",color:o?r.errorText:"white",border:o?`1px solid ${r.errorBorder}`:"none",borderRadius:"4px",cursor:"pointer"},children:"Provider Not Found"})})}return a.jsx(f.PrivyLogin,{...e})},Pa=({isSuccess:e,type:t,chainName:n,explorerUrl:s,txHash:o,dark:r=!1,successBg:i="#d1fae5",successBorder:l="#6ee7b7",successText:c="#065f46",errorBg:d="#fee2e2",errorBorder:p="#fca5a5",errorText:m="#dc2626",textSecondary:h="#6b7280"})=>a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px",borderRadius:"8px",backgroundColor:e?i:d,border:e?`1px solid ${l}`:`1px solid ${p}`},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[a.jsx("div",{style:{width:"28px",height:"28px",borderRadius:"50%",backgroundColor:e?"#10b981":"#ef4444",display:"flex",alignItems:"center",justifyContent:"center"},children:e?a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:a.jsx("path",{d:"M11.6667 3.5L5.25 9.91667L2.33333 7",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}):a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:a.jsx("path",{d:"M10.5 3.5L3.5 10.5M3.5 3.5L10.5 10.5",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),a.jsxs("div",{children:[a.jsx("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:f.font.mono,letterSpacing:"0.5px",color:e?c:m},children:e?`${t.toUpperCase()} CONFIRMED`:`${t.toUpperCase()} FAILED`}),a.jsxs("p",{style:{margin:"2px 0 0 0",fontSize:"12px",color:h},children:["on ",n]})]})]}),s&&o&&a.jsxs("a",{href:`${s}/tx/${o}`,target:"_blank",rel:"noopener noreferrer",style:{display:"flex",alignItems:"center",gap:"4px",fontSize:"13px",color:h,textDecoration:"none",whiteSpace:"nowrap"},children:["View on explorer",a.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:[a.jsx("path",{d:"M9 6.5V9.5C9 9.76522 8.89464 10.0196 8.70711 10.2071C8.51957 10.3946 8.26522 10.5 8 10.5H2.5C2.23478 10.5 1.98043 10.3946 1.79289 10.2071C1.60536 10.0196 1.5 9.76522 1.5 9.5V4C1.5 3.73478 1.60536 3.48043 1.79289 3.29289C1.98043 3.10536 2.23478 3 2.5 3H5.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),a.jsx("path",{d:"M7.5 1.5H10.5V4.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),a.jsx("path",{d:"M5 7L10.5 1.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"})]})]})]}),Ua=`
|
|
32
32
|
@keyframes slideUp {
|
|
33
33
|
from { transform: translateY(100%); }
|
|
34
34
|
to { transform: translateY(0); }
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
from { opacity: 0; transform: translateY(4px); }
|
|
42
42
|
to { opacity: 1; transform: translateY(0); }
|
|
43
43
|
}
|
|
44
|
-
`,Wa=({title:e,showChevron:t,expanded:n,onToggleDetails:s,showClose:o,onClose:r,fontFamily:i,labelColor:l,textPrimary:c,closeHoverBg:d,closePressedBg:p})=>{const[m,h]=u.useState(!1),[x,g]=u.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(Mn,{color:l,direction:n?"up":"down"})]}),o&&a.jsx("button",{onClick:r,onMouseEnter:()=>h(!0),onMouseLeave:()=>{h(!1),g(!1)},onMouseDown:()=>g(!0),onMouseUp:()=>g(!1),style:{background:x?p:m?d:"none",border:"none",borderRadius:"4px",cursor:"pointer",padding:"4px",display:"flex",alignItems:"center",justifyContent:"center",color:m||x?c:l,transform:x?"scale(0.9)":m?"scale(1.1)":"scale(1)",transition:f.transition.interactive},children:a.jsx(ss,{size:16})})]})},La=({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(f.Spinner,{size:24,borderWidth:3,color:r}),a.jsxs("div",{children:[a.jsx("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:f.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]})]})]}),za=({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]}),Uo=({isOpen:e,onClose:t,onComplete:n,closeOnComplete:s=!1,type:o,results:r,chainId:i,chainName:l,explorerUrl:c,theme:d,styles:p,dark:m,intentStatus:h,onRetry:x,onNewTx:g,onRetryTx:y,asOverlay:w=!0,isProcessing:C=!1,showStepBreakdown:b=!0})=>{const{theme:S,primaryColor:I,dark:F,dk:k}=f.useSpiceBrand(p,m),E=d||S,[R,j]=u.useState(!1),A=l??(i?f.getChainName(i):"Network"),M=c??(i&&f.getExplorerUrl(i,"").replace(/\/tx\/.*$/,"")||void 0),P=F?k.cardBg:"#ffffff",N=F?"0 4px 20px rgba(0, 0, 0, 0.4)":"0 4px 20px rgba(0, 0, 0, 0.1)",B=F?"0 -4px 8px -2px rgba(0, 0, 0, 0.4)":"0 -4px 8px -2px rgba(0, 0, 0, 0.15)",U=k.textSecondary,O=F?k.textPrimary:"#374151",z=F?k.inputBg:"#f9fafb",q=F?k.inputBorder:"#e5e7eb",ue=F?k.inputBg:"#f3f4f6",le=F?k.inputBorder:"#e5e7eb",[G,ne]=u.useState(!0),re=F?k.inputBg:"#f9fafb",Y=F?k.hoverBg:"#f3f4f6",_=F?{successBg:k.successBg,successBorder:k.successBorder,successText:k.successText,errorBg:k.errorBg,errorBorder:k.errorBorder,errorText:k.errorText}:{},Z=h?.steps.find(ce=>ce.status==="failed")?.error;u.useEffect(()=>{!e&&!h&&j(!1)},[e,h]);const pe=()=>{j(!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)},D=()=>{ne(!G)};if(h){const{steps:ce,overallStatus:he}=h,X=he==="processing",K=he==="success",W=he==="failed",Q=ce.filter(Ie=>Ie.transactionHash)[0],ae=ce.length>1?ce.map(Ie=>Ie.chainName).filter(Boolean).join(" and "):A!=="Network"?A:ce[0]?.chainName||A,we=M||(Q?f.getExplorerUrl(Q.chainId,Q.transactionHash||"").replace(/\/tx\/.*$/,""):void 0),ke=a.jsxs(a.Fragment,{children:[a.jsx(Wa,{title:X?`Processing ${o.charAt(0).toUpperCase()+o.slice(1)}`:`${o.charAt(0).toUpperCase()+o.slice(1)} results`,showChevron:b,expanded:G,onToggleDetails:D,showClose:!X,onClose:t,fontFamily:p?.fontFamily||E.typography.fontFamily,labelColor:U,textPrimary:O,closeHoverBg:re,closePressedBg:Y}),a.jsx("div",{style:{marginBottom:"16px"},children:X?a.jsx(La,{chainName:ae,bg:ue,border:le,textPrimary:O,labelColor:U,primaryColor:I}):a.jsx(Pa,{isSuccess:K,type:o,chainName:ae,explorerUrl:we,txHash:Q?.transactionHash,dark:F,..._,textSecondary:U})}),b&&a.jsx("div",{style:{overflow:"hidden",maxHeight:G?"300px":"0px",opacity:G?1:0,transition:"max-height 0.3s ease, opacity 0.3s ease",marginBottom:G?"16px":"0"},children:a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:ce.map((Ie,be)=>{const J=Ie.transactionHash?f.getExplorerUrl(Ie.chainId,Ie.transactionHash):null;return a.jsx(za,{bg:z,border:q,left:a.jsx("span",{style:{fontSize:"13px",color:O},children:Ie.chainName?`On ${Ie.chainName}`:Ie.description||`Step ${be+1}`}),right:a.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:Ie.status==="success"?"#10b981":Ie.status==="failed"?"#ef4444":U,fontWeight:500},children:[J&&a.jsx("a",{href:J,target:"_blank",rel:"noopener noreferrer",style:{color:F?k.infoText:"#2563eb",textDecoration:"none"},onClick:Ye=>Ye.stopPropagation(),children:"View"}),Ie.status==="success"?"\u2713":Ie.status==="failed"?"\u2717":"\u25CB"]})},be)})})}),!X&&a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[W&&x&&a.jsx(f.Button,{variant:"outline",fullWidth:!0,onClick:x,theme:E,styles:p,dark:F,children:"TRY AGAIN"}),g&&a.jsxs(f.Button,{variant:"outline",fullWidth:!0,onClick:g,theme:E,styles:p,dark:F,children:["NEW ",o.toUpperCase()," \u2192"]})]})]});return w?a.jsxs("div",{style:{position:"absolute",bottom:0,left:0,right:0,zIndex:10,animation:R?"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:B},children:ke}),a.jsx("style",{children:Ua})]}):a.jsx("div",{style:{backgroundColor:P,borderRadius:"12px",padding:"24px",width:"100%",boxShadow:N},children:ke})}if(!e&&!C||!C&&(!r||r.length===0))return null;const L=r?r.every(ce=>ce.success):!1,$=r?.[0],de=[...r??[]].reverse().find(ce=>ce.txHash)?.txHash||$?.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?R?"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?B:N},children:a.jsxs("div",{style:{width:"100%",boxSizing:"border-box",padding:"0 24px"},children:[a.jsx(Wa,{title:C?`Processing ${o.charAt(0).toUpperCase()+o.slice(1)}`:`${o.charAt(0).toUpperCase()+o.slice(1)} results`,showChevron:!C&&b,expanded:G,onToggleDetails:C?void 0:D,showClose:!C,onClose:t,fontFamily:p?.fontFamily||E.typography.fontFamily,labelColor:U,textPrimary:O,closeHoverBg:re,closePressedBg:Y}),a.jsx("div",{style:{marginBottom:"16px",animation:"statusFadeIn 220ms cubic-bezier(0.22, 1, 0.36, 1) both"},children:C?a.jsx(La,{chainName:A,bg:ue,border:le,textPrimary:O,labelColor:U,primaryColor:I}):a.jsx(Pa,{isSuccess:L,type:o,chainName:A,explorerUrl:M,txHash:de,dark:F,..._,textSecondary:U})},C?"processing":L?"success":"error"),!C&&b&&r&&r.length>1&&a.jsx("div",{style:{overflow:"hidden",maxHeight:G?"200px":"0px",opacity:G?1:0,transition:"max-height 0.3s ease, opacity 0.3s ease",marginBottom:G?"16px":"0"},children:a.jsx("div",{style:{maxHeight:"180px",overflowY:"auto",display:"flex",flexDirection:"column",gap:"8px"},children:r.map((ce,he)=>a.jsx(za,{bg:z,border:q,left:a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[a.jsx("span",{style:{fontWeight:600,fontSize:"13px",color:k.textPrimary,fontFamily:f.font.mono},children:ce.asset.symbol}),ce.amount&&a.jsx("span",{style:{fontSize:"12px",color:U},children:ce.amount})]}),right:a.jsx("span",{style:{fontSize:"12px",color:ce.success?"#10b981":"#ef4444",fontWeight:500},children:ce.success?"\u2713":"\u2717"})},he))})}),!C&&!L&&r&&a.jsx("div",{style:{padding:"12px",backgroundColor:k.errorBg,border:`1px solid ${k.errorBorder}`,borderRadius:"8px",marginBottom:"16px"},children:a.jsx("p",{style:{fontSize:"13px",color:k.errorText,margin:0,lineHeight:1.5},children:Z||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:[!L&&y&&a.jsxs(f.Button,{variant:"outline",fullWidth:!0,onClick:y,theme:E,styles:p,dark:F,children:["TRY AGAIN ",o.toUpperCase()]}),L&&a.jsx(f.Button,{variant:"outline",fullWidth:!0,onClick:pe,theme:E,styles:p,dark:F,children:"DONE"})]})]})}),a.jsx("style",{children:Ua})]})};function qa(e){const t=new Set(v.getEquivalentAddresses(e).map(n=>n.toLowerCase()));return t.add(e.toLowerCase()),t}const xd=["USDC","USDT","WETH","WBTC"];function Ha(e,t){const n=f.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 fn(e,t,n){const s=f.getChainConfig(t);if(!s)return;if(n!==void 0){if(v.isNativeToken(e)&&!v.getTokenByAddress(e,n))return;const i=po(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=qa(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 yd(e){const{sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:o,intermediaryCandidates:r=xd}=e;if(ys(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(fn(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(fn(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=Ha(i,s);if(!l||ys(t,l)||ys(n,l))continue;const c=Ha(i,o);if(c&&ys(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 f.SpiceflowError("ROUTE_STRATEGY_ERROR",`No viable cross-chain route found from ${t.symbol} (chain ${s}) to ${n.symbol} (chain ${o}). No intermediary asset is available on both chains.`,{sourceAsset:t.symbol,outputAsset:n.symbol,sourceChainId:s,destinationChainId:o,candidatesChecked:r})}async function wd(e){const{route:t,sourceAmount:n,userAddress:s,registry:o,actionCalls:r,slippage:i}=e;async function l(c,d,p,m){const h=await o.resolveSwap({type:"swap",tokenIn:d,tokenOut:p,amountIn:m,maxSlippage:i},c,s);if(!h)throw new f.SpiceflowError("NO_LIQUIDITY",`No venue returned a quote for ${d} \u2192 ${p} on chain ${c}. No liquidity available for this pair.`,{chainId:c,tokenIn:d,tokenOut:p,amountIn:m.toString()});return h}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=fn(t.sourceAsset.address,t.destinationChainId,t.sourceChainId)||t.sourceAsset;if(qa(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=fn(t.outputAsset.address,t.sourceChainId,t.destinationChainId);if(!c)throw new f.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Output asset ${t.outputAsset.symbol} (${t.outputAsset.address}) not found on source chain ${t.sourceChainId}`,{token:t.outputAsset.symbol,address:t.outputAsset.address,chainId:t.sourceChainId,side:"source"});const d=fn(t.outputAsset.address,t.destinationChainId,t.destinationChainId);if(!d)throw new f.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Output asset ${t.outputAsset.symbol} (${t.outputAsset.address}) not found on destination chain ${t.destinationChainId}`,{token:t.outputAsset.symbol,address:t.outputAsset.address,chainId:t.destinationChainId,side:"destination"});const p=await l(t.sourceChainId,t.sourceAsset.address,c.address,n);return{chainBatches:[{chainId:t.sourceChainId,calls:p.calls},{chainId:t.destinationChainId,calls:r}],solverFrontToken:d,solverFrontAmount:p.amountOutMinimum,resolvedSwaps:{sourceSwap:p}}}case"intermediary":{if(!t.intermediaryAsset)throw new f.SpiceflowError("ROUTE_STRATEGY_ERROR","Intermediary strategy requires an intermediary asset but none was provided in the route plan.",{strategy:t.strategy});const c=fn(t.intermediaryAsset.address,t.sourceChainId,t.destinationChainId);if(!c)throw new f.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Intermediary ${t.intermediaryAsset.symbol} (${t.intermediaryAsset.address}) not found on source chain ${t.sourceChainId}`,{token:t.intermediaryAsset.symbol,address:t.intermediaryAsset.address,chainId:t.sourceChainId,side:"source"});const d=await l(t.sourceChainId,t.sourceAsset.address,c.address,n),p=await l(t.destinationChainId,t.intermediaryAsset.address,t.outputAsset.address,d.amountOutMinimum);return{chainBatches:[{chainId:t.sourceChainId,calls:d.calls},{chainId:t.destinationChainId,calls:[...p.calls,...r]}],solverFrontToken:t.intermediaryAsset,solverFrontAmount:d.amountOutMinimum,resolvedSwaps:{sourceSwap:d,destinationSwap:p}}}default:throw new f.SpiceflowError("ROUTE_STRATEGY_ERROR",`Unknown route strategy: ${t.strategy}`,{strategy:t.strategy})}}function bd(e,t,n){if(!e||!t)return null;const s=Rn(e,t),o=Object.entries(e.chainTokens??{}).flatMap(([m,h])=>{const x=dn(m);return x?.chainId===t?[{parsed:x,detail:h}]:[]}),r=m=>n.find(h=>f.addressesEqual(h.address,m))??null,i=m=>{const h=o.find(({parsed:y})=>f.addressesEqual(y.address,m));if(!h)return null;const x=f.getChainConfig(t);if(v.isNativeToken(m))return x?{address:v.ZERO_ADDRESS,symbol:x.nativeCurrency.symbol,name:x.nativeCurrency.name,decimals:x.nativeCurrency.decimals,logoURI:e.logoURI}:null;const g=x?.supportedTokens?.find(y=>f.addressesEqual(y.address,m));return!g||!uo(e,m,t)?null:{address:h.parsed.address,symbol:g.symbol,name:g.name||h.detail?.name||e.displayName||e.name||e.symbol,decimals:g.decimals,logoURI:g.logo||e.logoURI}},l=o.map(({parsed:m})=>m.address).filter(v.isNativeToken);for(const m of[...s,...l]){if(v.isNativeToken(m)){const g=i(m);if(g)return g}const h=r(m);if(h)return h;const x=i(m);if(x)return x}if(e.chainTokens||e.receiptTokenId)return null;const c=Jt(e,t);if(c){const m=r(c);if(m)return m}const d=fn(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 Cd(e){const t=e.find(n=>v.isSpicenetChainId(n.chainId))?.calls?.[0]?.data;if(!t)return null;try{const n=T.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 vd(e,t){if(!e||e.length!==t.length)return!1;const n=s=>s.reduce((o,r)=>o+r.amount,0n);return n(e)!==n(t)?!1:e.every((s,o)=>{const r=t[o];return s.token.toLowerCase()!==r.token.toLowerCase()||s.recipient.toLowerCase()!==r.recipient.toLowerCase()?!1:s.recipient.toLowerCase()===v.SPICE_GAS_FEE_RECIPIENT.toLowerCase()?f.amountsWithinBps(s.amount,r.amount,100n):s.recipient.toLowerCase()!==v.SPICE_PLATFORM_FEE_RECIPIENT.toLowerCase()||s.amount===r.amount})}function kd(e,t){const n=e.intents.flatMap(r=>r.batches).filter(r=>{const i=f.getBatchFees(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 Sd(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 Va(e,t){if(!e.token||!e.recipient||e.chainId===null)return null;const n=kd(t,e.chainId);if(!n)return null;const{gasFee:s,bridgeFee:o,spicenetFee:r}=f.getBatchFees(n),i=s+o,l=e.grossAmountRaw-i-r;if(l<=0n)throw new Error("Withdrawal amount does not cover the network fee.");const c=[{token:e.token.address,recipient:e.recipient,amount:l}];return i>0n&&c.push({token:e.token.address,recipient:v.SPICE_GAS_FEE_RECIPIENT,amount:i}),r>0n&&c.push({token:e.token.address,recipient:v.SPICE_PLATFORM_FEE_RECIPIENT,amount:r}),Sd(c)}function Id(e,t,n){const s=Va(e,t);return!s||vd(Cd(n),s)?null:e.buildWithdrawBatches(s)}async function Qa(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=Va(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(f.getBatchFees(i).totalFee)}else{const o=(e.feeEstimate??await e.execution.estimate(t,n,0n,s)).intents[0]?.batches[0]??null;o&&e.ui.setLockedGasFee(f.getBatchFees(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})=>Id(e,o,r)}:{...s,skipPreSubmitFeeEstimate:!0})}Ga(e)}catch(t){const n=t instanceof Error?t.message:"Withdraw failed";e.ui.setExecutionError(n)}finally{e.ui.setIsExecuting(!1)}}}function Ga(e){window.dispatchEvent(new CustomEvent("withdraw-completed")),e.onWithdrawSuccess?.({token:e.token?.symbol||"",amount:e.amount,chainId:e.chainId})}async function Ad(e){const t=e.executionContextRef.current;if(!t){e.ui.setExecutionProgress(null),await Qa(e);return}e.ui.setIsExecuting(!0),e.ui.setExecutionError(null),e.ui.setExecutionProgress({step:"executing",message:"Resuming existing action...",actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps});try{let n=t.totalSteps;for(let s=0;s<t.totalSteps;s++)if((await f.relayerService.checkStepStatus(t.intentId,s)).data.status!=="success"){n=s;break}if(n>=t.totalSteps)e.ui.setExecutionProgress(s=>({...s||{step:"success",message:"Transaction successful!",actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps},step:"success",message:"Transaction successful!"}));else for(let s=n;s<t.totalSteps;s++){const o=await ha({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})}Ga(e)}catch(n){const s=n instanceof Error?n.message:"Withdraw failed";e.ui.setExecutionError(s)}finally{e.ui.setIsExecuting(!1)}}async function Ed(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=>f.getBatchFees(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:f.getBatchFees(s).totalFee,feeEstimate:t}}function Wo(e,t){return T.formatUnits(e,t).replace(/(\.\d*?[1-9])0+$|\.0+$/,"$1")}function Fd(e,t,n){return Qt(e,t,n,"floor")}function Ya(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 Td(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 Ka(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:T.encodeFunctionData({abi:T.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 jd(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const s=T.getAddress(n.token),o=T.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 Bd(e,t){return`0x${t}${e.slice(4)}`}function Za(e,t,n,s){if(e.some(p=>p.domain==="spicenet"))return e;const o=n?.intents.flatMap(p=>p.batches),r=p=>p.from==="escrow",i=e.map(p=>{const m=o?.find(E=>E.chainId===p.chainId);if(!m)return p;const h=f.getBatchFees(m),x=h.totalFee;if(x<=0n)return p;const g=(p.tokenTransfers??[]).filter(E=>r(E)&&T.getAddress(E.to).toLowerCase()===t.toLowerCase()),y=g.find(E=>!v.isNativeToken(T.getAddress(E.token)))??g[0];if(!y)return p;const w=T.getAddress(y.token),C=v.isNativeToken(w);let b=!1;const S=(p.tokenTransfers??[]).map(E=>b||!r(E)||T.getAddress(E.to).toLowerCase()!==t.toLowerCase()||T.getAddress(E.token).toLowerCase()!==w.toLowerCase()?E:(b=!0,{...E,amount:s?.payoutAlreadyGross?BigInt(E.amount):BigInt(E.amount)+x}));if(!b)return p;const I=(E,R)=>C?{to:E,value:R,data:"0x"}:{to:w,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"transfer",args:[E,R]})},F=[];h.spicenetFee>0n&&F.push(I(v.SPICE_PLATFORM_FEE_RECIPIENT,h.spicenetFee));const k=h.gasFee+h.bridgeFee;return k>0n&&F.push(I(v.SPICE_GAS_FEE_RECIPIENT,k)),{...p,tokenTransfers:S,calls:[...F,...p.calls]}}),l=i.flatMap(p=>(p.tokenTransfers??[]).filter(r).map(m=>{const h=T.getAddress(m.token),x=T.getAddress(m.to),g=[{token:h,to:x,amount:BigInt(m.amount)}];return{chainId:p.chainId,transfers:jd(g)}}));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((p,m)=>{const h=T.keccak256(T.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,p.transfers[0].token,p.transfers.reduce((g,y)=>g+y.amount,0n),BigInt(p.chainId),BigInt(c+m)])),x=Bd(h,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:T.encodeFunctionData({abi:v.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${p.chainId}`,idempotenceKey:x,nbf:0n,exp:d,metadata:"{}",transfers:p.transfers.map(g=>({token:g.token.toLowerCase(),to:g.to,amount:g.amount}))}]})}})},...i]}function In(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)),...Za(o.filter(r),t,n,s)]}class Un 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 Lo(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:T.encodeFunctionData({abi:T.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 Xa(e,t,n,s,o){const r=v.hashChainBatches(e),i=await f.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 Ja(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 Un(l,t);const p=d>0n?(d*110n+99n)/100n+2n:0n;let m=p,h;const x=In(await e.buildBatches(p,{actionAmountOverride:e.actionAmountFor?.(l),onSourceSpend:w=>{m=w},onActionCalls:w=>{h=w}}),e.owner),g=Lo(x,e.owner,e.token,s+r,o),y=await Xa(g,e.owner,e.token,e.signal);if(y<=s&&(s-y)*100n<=y*15n)return{preview:{...n.preview,grossAmount:p,netAmount:0n,gasFee:s,totalFee:l,gasQuoteSource:"estimated"},feeEstimate:n.feeEstimate,grossFundingAmount:p,proceedsAvailable:t,proceedsUsed:c,fundingBatches:g,sourceSpendCap:m,destinationAmount:0n,actionDefinition:h};s=y}throw new Error("Action proceeds fee estimate did not converge")}function $a(e,t){let n,s;if(v.isNativeToken(t)){if(e.data!=="0x")return null;n=e.to,s=e.value}else{if(!f.addressesEqual(e.to,t))return null;try{const o=T.decodeFunctionData({abi:T.erc20Abi,data:e.data});if(o.functionName!=="transfer")return null;[n,s]=o.args}catch{return null}}return f.addressesEqual(n,v.SPICE_GAS_FEE_RECIPIENT)?{gas:s,platform:0n}:f.addressesEqual(n,v.SPICE_PLATFORM_FEE_RECIPIENT)?{gas:0n,platform:s}:null}async function Rd(e,t,n){const s=f.getClientForChain(e);return v.isNativeToken(n)?s.getBalance({address:t}):s.readContract({address:n,abi:T.erc20Abi,functionName:"balanceOf",args:[t]})}function Ms(e,t,n){return e.map(s=>s.chainId===t?{...s,calls:s.calls.filter(o=>!$a(o,n))}:s)}function _a(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 p=e.feeQuote?.fundingConversion,m=r??{token:t,resolve:async()=>0n},h=e.feeQuote?.preview,x=e.feeQuote?.proceedsUsed,g=p?.fromProceeds?p.tokenIn:t;if(!h||x===void 0||!i&&m.token.toLowerCase()!==g.toLowerCase())throw new Error("Refresh the action proceeds quote");const y=h.gasFee+(h.bridgeFee??0n),w=h.spicenetFee,C=i?async()=>{e.validateFeeQuote?.();const S=await Rd(e.resolvedChainId,s,i.token);e.validateFeeQuote?.();const I=i.kind==="input"?i.amount:(p?.amountInMax??x)+(i.reservedAmount??0n);if(e.signal?.aborted||S<I||p&&p.amountOut<y+w)throw new Error("The fee funding balance changed; refresh before retrying");return p?[{chainId:e.resolvedChainId,token:t,amount:p.amountOut}]:[]}:async()=>{e.validateFeeQuote?.();const S=await m.resolve(e.signal);if(e.validateFeeQuote?.(),e.signal?.aborted||(p?.fromProceeds?S<p.amountInMax||p.amountOut<y+w:S<x||S+(p?.amountOut??n)<y+w))throw new Error("Action proceeds changed; refresh before retrying");return p?.fromProceeds?[{chainId:e.resolvedChainId,token:p.tokenIn,amount:p.amountInMax},{chainId:e.resolvedChainId,token:t,amount:p.amountOut}]:[{chainId:e.resolvedChainId,token:t,amount:x+(p?.amountOut??0n)}]},b=async S=>{await C();const I=await Xa(S,s,t,e.signal,p?w:void 0);if(await C(),(I>h.gasFee?I-h.gasFee:h.gasFee-I)*100n>I*15n)throw new Error("Action gas quote changed; refresh before retrying")};return{resolveActionOutputCredits:C,prepareForSigning:async S=>{const I=Ms(S,e.resolvedChainId,t).map(k=>({...k,tokenTransfers:k.tokenTransfers?.filter(E=>!(typeof E.from=="string"&&f.addressesEqual(E.from,s)&&(f.addressesEqual(E.to,v.SPICE_GAS_FEE_RECIPIENT)||f.addressesEqual(E.to,v.SPICE_PLATFORM_FEE_RECIPIENT))))})),F=Lo(I,s,t,y,w);return await b(F),F},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 p=>{e.validateFeeQuote?.();const m=Ms(p,e.resolvedChainId,t),h=await e.execution.estimate(m,t,n,{userOverride:s,useCustomTransfers:!0,feeExecutionMode:"backend-transfer"});e.validateFeeQuote?.();const x=f.getSupplyFeePreview(h,c);if(!x||x.chainId!==e.resolvedChainId)throw new Error("The fee service did not return the destination action's fee quote");if(x.gasFee+x.spicenetFee+(x.bridgeFee??0n)+2n>n)throw new Error("Fees exceed the displayed maximum funding; refresh the quote before retrying");return{raw:m,feeEstimate:h,fees:x}};return{prepareForSigning:async p=>{const{raw:m,feeEstimate:h}=await d(p);return In(m,s,h,{payoutAlreadyGross:!0})},validateBeforeSubmit:async p=>{const{fees:m}=await d(p);let h=0n,x=0n;for(const y of p)if(y.chainId===e.resolvedChainId)for(const w of y.calls){const C=$a(w,t);C&&(h+=C.gas,x+=C.platform)}if(h+x+2n>n)throw new Error("Signed fees exceed the displayed maximum funding");const g=m.gasFee+(m.bridgeFee??0n);if((h>g?h-g:g-h)*100n>g*15n||x!==m.spicenetFee)throw new Error("The signed gas quote changed materially; refresh before retrying")}}}const Dd="0xa9059cbb";function rs(e,t,n){return v.isNativeToken(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"transfer",args:[n,t]})}}function ei(e,t,n){return{chainId:n,calls:[rs(e,t,v.getEscrowContractAddress(n))]}}function Od(e,t,n,s){const o=t.source.chainId;return{chainId:o,calls:[...e.calls,rs(t.source.address,n,v.getEscrowContractAddress(o)),...s>0n?[rs(t.source.address,s,v.SPICE_GAS_FEE_RECIPIENT)]:[]]}}function ti(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 ni(e,t,n){return e?.asset?._source==="wallet"&&e?.asset.chainId===n}function si(e){return e.isNative||v.isNativeToken(e.address)?!0:!v.getTokenByAddress(e.address,e.chainId)}function oi(e,t,n,s){return t!=="user-transfer"||!n||e.length===0||e[0]?.to.toLowerCase()!==s.toLowerCase()||!e[0]?.data.startsWith(Dd)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function as(e,t,n,s){const o=await(t??Ns)({...n,requestTimestampMs:s});return o?[o,e]:[e]}function Nd(e){return e.filter(t=>t.domain!=="spicenet")}function is(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 Wn(e,t,n){return Qt(e,t,n,"ceil")}function ri(e){const t=e.selectedAsset?.asset;return e.isPayMode&&!!t&&t._source==="wallet"&&t.chainId!==e.resolvedChainId&&!!e.pivot}function zo(e){const t=e.selectedAsset?.asset;return!e.isPayMode&&!!t&&t._source==="wallet"&&t.chainId!==e.resolvedChainId&&!!e.sourceSwap&&!!e.pivot}function Ps(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 ai(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 Us=(e,t)=>ai(Md,e,t),Ws=async(e,t)=>{const n=await ai(Pd,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]=Ms([o],e.resolvedChainId,r),l=Ka(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(p=>p.to.toLowerCase()===d.to.toLowerCase()&&p.value===d.value&&p.data===d.data))?n:[...n.slice(0,-1),{...i,calls:[...l,...i.calls]}]};async function Md(e,t){const{currentPaymentAmount:n,destinationToken:s,embeddedWalletAddress:o,providerEmbeddedAddress:r,address:i,isNon7702:l,resolvedChainId:c,buildActionCalls:d,feeExecutionMode:p,buildSpicenetBatch:m,needsSwap:h,exactOutputSwap:x,resolvedTokenIn:g,requestTimestampMs:y}=e,w=t?.sourceAssetOverride?{asset:t.sourceAssetOverride}:e.selectedAsset,C=t?.fundingTokenOverride??g,b=zt(n,s.decimals),S=t?.actionAmountOverride??(e.feeOnlyAction?0n:b),I=!!e.feeOnlyAction&&(t?.fundingAmountOverride??0n)>0n,F=o||r||i;if(!F)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const k={userAddress:e.recipient??F,executorAddress:F,beneficiary:e.recipient??F,outputRecipient:h?F:void 0,chainId:c,destinationToken:s.address,grossAmount:t?.fundingAmountOverride??b,netAmount:S,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:p,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},E=await d(S,k),R={chainId:c,calls:E},j=!!w&&w.asset._source!=="wallet",A=ni(w??null,l,c),M=j||A&&!!w&&!si(w.asset),P=(B,U)=>({token:v.normalizeNativeTokenAddress(B),from:"escrow",to:F,amount:U}),N=(B,U,O)=>A?[ei(B,U,c),...O]:O;if(b===0n&&!I)return[R];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&&A)return Ps(t.fundingAmountOverride??0n,t),[R];if(ri(e)){if(h&&!x)throw new Error("Swap quote not available yet");const B=t?.fundingAmountOverride??(x?x.amountInMax:b),U=t?.sourceGasSkimOverride??0n,O=Qt(B,e.pivot.destination.decimals,e.pivot.source.decimals,"ceil"),z=O+U,q=e.sourceExactOutputSwap,ue=q&&(t?.reuseQuotedSourceSwap||q.amountOut>=z)?q:e.resolveSourceExactOutputSwap?await e.resolveSourceExactOutputSwap(z):null;if(!ue)throw new Error("Swap quote not available yet");Ps(ue.amountInMax,t);const le=w.asset;if(ue.amountInMax>le.balance)throw new Error(`Insufficient ${le.symbol} for this payment. Required ${T.formatUnits(ue.amountInMax,le.decimals)} ${le.symbol}; available ${T.formatUnits(le.balance,le.decimals)} ${le.symbol}.`);const G=ue.amountOut>=z?O:ue.amountOut-U;if(G<=0n)throw new Error("Amount is too small to cover fees. Increase the amount and retry.");const ne={chainId:e.pivot.source.chainId,calls:[...ue.calls,rs(e.pivot.source.address,G,v.getEscrowContractAddress(e.pivot.source.chainId)),...U>0n?[rs(e.pivot.source.address,U,v.SPICE_GAS_FEE_RECIPIENT)]:[]]},re={chainId:c,calls:[...x?.calls??[],...E],tokenTransfers:[P(e.pivot.destination.address,B),...R.tokenTransfers??[]]},Y=await as(re,m,{userAddress:F,destinationChainId:c,deliveryToken:e.pivot.destination.address,deliveryAmount:B,deliveryRecipient:F,deliveryTransfers:is(re),sourceAsset:w.asset},y);return[ne,...Y]}if(w){const B=t?.fundingAmountOverride??x?.amountInMax??b;Ps(Wn(B,await xn(w.asset,C??w.asset.address,c,s),w.asset.decimals),t)}if(h&&x){const B=C??Jt(w.asset,c)??w.asset.address,U=t?.fundingAmountOverride??x.amountInMax,O=M?[P(B,U)]:[],z={chainId:c,calls:[...x.calls,...E],tokenTransfers:[...O,...R.tokenTransfers??[]]};if(!M)return[z];const q=await as(z,m,{userAddress:F,destinationChainId:c,deliveryToken:B,deliveryAmount:U,deliveryRecipient:F,deliveryTransfers:is(z),sourceAsset:w.asset},y);return N(B,U,q)}if(M){const B=C??Jt(w.asset,c)??s.address;if(A&&!e.feeOnlyAction&&B.toLowerCase()===s.address.toLowerCase())return[R];const U=t?.fundingAmountOverride??b,O={...R,tokenTransfers:[P(B,U),...R.tokenTransfers??[]]},z=await as(O,m,{userAddress:F,destinationChainId:c,deliveryToken:B,deliveryAmount:U,deliveryRecipient:F,deliveryTransfers:is(O),sourceAsset:w.asset},y);return N(B,U,z)}return[R]}async function Pd(e,t){const{selectedAsset:n,embeddedWalletAddress:s,recipient:o,resolvedChainId:r,destinationToken:i,buildActionCalls:l,feeExecutionMode:c,buildSpicenetBatch:d,isPayMode:p,isNon7702:m,needsSwap:h,resolvedSwap:x,quoteAmountOut:g,resolvedTokenIn:y,requestTimestampMs:w}=e;if(!n?.asset||!s)return[];const C=o??s;if(!C)return[];const b=zo(e);let S=e.sourceSwap,I=zt(n.amount,n.asset.decimals),F=b?e.sourceSwap.amountOutMinimum:null;if(b&&e.isFeeInclusiveInput&&(F=ti(e.sourceSwap,t?.sourceGasSkimOverride??0n)),b&&!e.isFeeInclusiveInput&&(t?.fundingAmountOverride!==void 0||(t?.sourceGasSkimOverride??0n)>0n)){F=t?.fundingAmountOverride!==void 0?Wn(t.fundingAmountOverride,e.pivot.destination.decimals,e.pivot.source.decimals):e.sourceSwap.amountOutMinimum;const Z=F+(t?.sourceGasSkimOverride??0n);if(!e.resolveSourceExactOutputSwap)throw new Error("The source quote cannot include fees yet.");const pe=await e.resolveSourceExactOutputSwap(Z);if(pe.amountOut<Z)throw new Error("The source quote does not cover the accepted funding amount.");I=pe.amountInMax,S={...pe,amountOutMinimum:pe.amountOut}}const k=b?e.pivot.destination.address:y??Jt(n.asset,r)??i.address,E=b?e.pivot.destination.decimals:await xn(n.asset,k,r,i),R=t?.fundingAmountOverride??t?.actionAmountOverride??(b?Qt(F,e.pivot.source.decimals,E,"floor"):Os(zt(n.amount,n.asset.decimals),n.asset.decimals,E)),j=t?.fundingAmountOverride??R,A=t?.sourceFundingAmountOverride??Wn(R,E,n.asset.decimals);Ps(b?I:A,t);const M=t?.deliveryAmountOverride??(c==="user-transfer"?j:t?.actionContextOverride?.netAmount??j),P=t?.withdrawalAmountOverride??M,N=t?.actionAmountOverride??t?.actionContextOverride?.netAmount??R;let B=x;if(h&&!p&&(t?.actionContextOverride?.netAmount!==void 0||b&&(t?.sourceGasSkimOverride??0n)>0n&&!t?.reuseQuotedSourceSwap)){if(!e.resolveInputSwap)throw new Error("Swap quote cannot be refreshed for the amount after fees.");const Z=t?.actionContextOverride?.netAmount??N;(!B||e.swapInputAmount!==Z)&&(B=await e.resolveInputSwap(Z,x??void 0))}B&&t?.onSwap?.(B,t?.actionContextOverride?.netAmount??e.swapInputAmount??N);const U=B?.amountOutMinimum??g,O={userAddress:C,executorAddress:s,beneficiary:C,outputRecipient:h?s:void 0,chainId:r,destinationToken:i.address,feeToken:c==="user-transfer"&&h&&y?y:i.address,grossAmount:j,netAmount:N,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:c,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},z=()=>l(N,O),q=n.asset?._source==="wallet";if(!p&&q&&n.asset.chainId===r&&si(n.asset)){if(h){if(!y)throw new Error("Swap input token could not be resolved");if(!B||U===null)throw new Error("Swap quote not available yet")}if(h&&B&&U){const Z=await l(t?.actionAmountOverride??U,{...O,netAmount:t?.actionAmountOverride??U}),{feeCall:pe,remainingCalls:D}=oi(Z,c,h,O.feeToken);return[{chainId:r,calls:[...pe?[pe]:[],...B.calls,...D]}]}return[{chainId:r,calls:await z()}]}if(!p&&q&&n.asset.chainId!==r&&!b)throw new Error("A current source-to-destination funding route is required");const ue=n.asset._source!=="wallet",le=ni(n,m,r);if(!(ue||le||b))return[{chainId:r,calls:await z()}];const G=b?Od(S,e.pivot,F,t?.sourceGasSkimOverride??0n):le?ei(y??v.normalizeNativeTokenAddress(n.asset.address),A,r):null,ne=(Z,pe)=>({token:v.normalizeNativeTokenAddress(Z),from:"escrow",to:s,amount:pe});if(h){if(!y)throw new Error("Swap input token could not be resolved");if(!B||U===null)throw new Error("Swap quote not available yet")}if(h&&B&&U&&y){const Z=await l(t?.actionAmountOverride??U,{...O,netAmount:t?.actionAmountOverride??U}),{feeCall:pe,remainingCalls:D}=oi(Z,c,h,O.feeToken),L={chainId:r,calls:[...pe?[pe]:[],...B.calls,...D],tokenTransfers:[ne(y,M)]},$=await as(L,d,{userAddress:s,destinationChainId:r,deliveryToken:y,deliveryAmount:M,withdrawalAmount:P,deliveryRecipient:s,deliveryTransfers:is(L,P),sourceAsset:n.asset},w);return G?[G,...$]:$}const re=y??Jt(n.asset,r)??i.address,Y={chainId:r,calls:await z(),tokenTransfers:[ne(re,M)]},_=await as(Y,d,{userAddress:s,destinationChainId:r,deliveryToken:re,deliveryAmount:M,withdrawalAmount:P,deliveryRecipient:s,deliveryTransfers:is(Y,P),sourceAsset:n.asset},w);return G?[G,..._]:_}async function Ud(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=f.getSingleNetOutput(c);if(d===null||d>=e)return r;const p=r-d,m=e+p;if(m<=r)return r;r=m}return r}function Wd(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:T.encodeFunctionData({abi:T.erc20Abi,functionName:"approve",args:[r,o.amountInMax]})},...o.calls]}}}}function Ls(e){const t=(e?.customVenues??[]).map(s=>ll(Wd(s)));async function n(s,o,r){const i=t.filter(d=>d.chainIds.includes(o));if(i.length===0)throw new f.SpiceflowError("NO_SWAP_ROUTE",`No exact-output venue supports chain ${o}`,{chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut});const l=(await Promise.allSettled(i.map(async 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 f.SpiceflowError("NO_SWAP_ROUTE",`All aggregators failed for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}`,{chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountOut:s.amountOut.toString()});const c=l.find(d=>d.venue.preferred);return c?c.quote:(l.sort((d,p)=>d.quote.amountIn<p.quote.amountIn?-1:d.quote.amountIn>p.quote.amountIn?1:0),l[0].quote)}return{getQuote:n,venues:t}}function ii(e,t,n){if(e._source==="wallet")return e.chainId===t?e.address:null;const s=Rn(e,t);return s.find(o=>o.toLowerCase()===n.toLowerCase())??s[0]??null}async function li(e,t,n,s){const o=v.hashChainBatches(s),r=await f.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 ls(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:ii(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 f.getClientForChain(e.resolvedChainId).readContract({address:i,abi:T.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 p=Ls({customVenues:[...e.resolveExactOutputSwap?[{name:"consumer-exact-output",chainIds:[e.resolvedChainId],preferred:!0,resolve:e.resolveExactOutputSwap}]:[],...Bn(e.liquidityVenues).output]}),m=x=>li(e,r,c,x);let h=await m(await e.buildPayChainBatches({fundingAmountOverride:0n}));for(let x=0;x<8;x++){const g=h.gasFee+h.platformFee,y=o?0n:d<g?d:g,w=g-y,C=w>0n?(w*110n+99n)/100n+2n:0n,b=C>0n?await p.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 S=b?.amountInMax??0n,I=o?0n:Wn(S,l,n.decimals);if(o&&S>d)throw new Un(S,d);if(!o&&I>n.balance)throw new Un(I,n.balance);let F,k=In(await e.buildPayChainBatches({fundingAmountOverride:o?0n:S,...o?{}:{fundingTokenOverride:i},...t?{actionAmountOverride:t.amount-S}:{},onActionCalls:R=>{F=R}}),r);if(b){const R=k.length-1;k=k.map((j,A)=>A===R?{...j,calls:[...j.calls,...b.calls]}:j)}k=Lo(k,r,c,h.gasFee,h.platformFee);const E=await m(k);if(E.gasFee<=h.gasFee&&(h.gasFee-E.gasFee)*100n<=E.gasFee*15n&&E.platformFee===h.platformFee){const R={tokenIn:i,tokenOut:c,amountInMax:S,amountOut:C,sourceAmountMax:I,...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:h.gasFee,spicenetFee:h.platformFee,totalFee:g,gasQuoteSource:"estimated"},grossFundingAmount:o?0n:S,proceedsAvailable:d,proceedsUsed:o?g:y,fundingConversion:R,fundingBatches:k,sourceSpendCap:I,destinationAmount:0n,actionDefinition:F}}h=E}throw new Error("Fee conversion pricing did not converge")}const qo=["input","proceeds","balance"];function Ld(e){if(e.reserve&&e.reserve.amount<0n)throw new Error("Fee funding reserve cannot be negative");const t=l=>f.addressesEqual(l,e.feeToken),n=(l,c)=>Number(l.swap)-Number(c.swap),s={input:[],proceeds:[],balance:[]};for(const l of e.inputs??[])l.amount>0n&&s.input.push({kind:"input",...l,swap:!t(l.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=e.balances.filter(l=>l._source==="wallet"&&l.chainId===e.chainId&&l.location!=="external"),r=e.balances.filter(l=>l._source==="spice"),i=l=>{const c=[];for(const d of l){const p=e.reserve&&Ge(d)===Ge(e.reserve.asset)?e.reserve.amount:0n,m=d.balance-p;if(m<=0n)continue;const h=p>0n?{...d,balance:m,balanceFormatted:Number(T.formatUnits(m,d.decimals)),balanceUsd:d.balanceUsd*Number(m)/Number(d.balance)}:d,x=ii(h,e.chainId,e.feeToken);x&&(e.inputs?.some(g=>f.addressesEqual(g.token,x)&&!(e.reserve&&f.addressesEqual(e.reserve.asset.address,g.token)))||c.push({kind:"balance",token:x,amount:h.balance,asset:h,...p>0n?{reservedAmount:p}:{},swap:!t(x)}))}return c.sort((d,p)=>n(d,p)||p.asset.balanceUsd-d.asset.balanceUsd)};return s.balance=[...i(o),...i(r)],(e.order??qo).flatMap(l=>s[l])}function zd(e){return e instanceof Un||e instanceof f.SpiceflowError&&e.code==="NO_SWAP_ROUTE"}async function ci(e,t){const n=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!n||!e.ready||!e.authenticated)return null;const s=e.destinationToken.address;let o;const r=()=>o??(o=(async()=>{const d=await li(e,n,s,await e.buildPayChainBatches({fundingAmountOverride:0n}));return{feeEstimate:null,preview:{symbol:e.destinationToken.symbol,decimals:e.destinationToken.decimals,gasFee:d.gasFee,spicenetFee:d.platformFee,bridgeFee:0n,totalFee:d.gasFee+d.platformFee,grossAmount:0n,netAmount:0n,gasQuoteSource:"estimated"}}})()),i=(d,p)=>e.buildPayChainBatches({...p,fundingAmountOverride:d}),l=(d,p)=>Ja({proceeds:{token:s,resolve:async()=>d},owner:n,token:s,signal:e.signal,baseline:r,buildBatches:i,fundShortfall:!1,actionAmountFor:p}),c=async d=>{if(d.kind==="input")return d.swap?ls({...e,actionProceeds:void 0},d):l(d.amount,x=>d.amount-x);if(d.kind==="proceeds"){const x={...e.actionProceeds,resolve:async()=>d.amount};return d.swap?ls({...e,actionProceeds:x}):l(d.amount)}const p=d.asset;if(p._source==="wallet"&&!d.swap)return l(p.balance);const m={...e,selectedAsset:{asset:p,amount:"0"},resolvedTokenIn:d.token,actionInput:void 0,actionProceeds:void 0,buildPayChainBatches:x=>e.buildPayChainBatches({...x,sourceAssetOverride:p,fundingTokenOverride:x?.fundingTokenOverride??d.token})};if(d.swap)return ls(m);const h=await t(m);if(h&&(h.sourceSpendCap??0n)>p.balance)throw new Un(h.sourceSpendCap,p.balance);return h};for(const d of e.feeFunding??qo){const p=d==="proceeds"&&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(p&&p.amount<0n)throw new Error("Action proceeds cannot be negative");const m=Ld({feeToken:s,chainId:e.resolvedChainId,inputs:e.actionInput,proceeds:p,balances:e.feeFundingBalances??[],order:[d],reserve:e.feeFundingReserve});for(const h of m)try{const x=await c(h);if(!x)continue;const{swap:g,...y}=h;return{...x,fundingSource:y}}catch(x){if(e.signal?.aborted||!zd(x))throw x}}throw new Error(`No available balance can cover this action's ${e.destinationToken.symbol} execution cost`)}async function qd(e,t,n,s=!1){const o=e.selectedAsset,r=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!o||!r||!e.ready||!e.authenticated||e.isQuoting)return null;if(o.asset._source!=="wallet"||o.asset.chainId!==e.resolvedChainId||!ws(o.asset)&&o.asset.owner&&!f.addressesEqual(o.asset.owner,r))throw new Error("Funded fee hierarchy requires principal on the action chain in the executing wallet.");if(s&&(e.isPayMode||!e.isFeeInclusiveInput||t.recipient&&!f.addressesEqual(t.recipient,r)))throw new Error("Output-funded actions require an input-inclusive amount left in the executing wallet.");if(e.isPayMode&&e.needsSwap&&!e.exactOutputSwap)return null;const i=e.isPayMode?zt(e.currentPaymentAmount,e.destinationToken.decimals):void 0;if(e.isPayMode&&e.needsSwap&&e.exactOutputSwap.amountOut!==i)throw new Error("Wait for the payment quote for the current amount.");const l=v.getTokensForChain(e.resolvedChainId).find(w=>w.equivalenceGroup==="USDC");if(!l)throw new Error("Configure the execution fee token for this chain.");const c={...l,address:l.address,chainId:e.resolvedChainId},d=i!==void 0?e.needsSwap?e.exactOutputSwap.amountInMax:i:zt(o.amount,o.asset.decimals);if(d<=0n||d>o.asset.balance)throw new Error("Enter an amount within the available balance.");if(!e.isPayMode&&e.needsSwap&&t.swapInputAmount!=null&&t.swapInputAmount!==d)throw new Error("Wait for the action quote for the current amount.");const p=i??(e.needsSwap?t.resolvedSwap?.amountOutMinimum??0n:d);let m=t.resolvedSwap??void 0,h=d,x=p;const g={...e,feeOnlyAction:!0,selectedAsset:null,isPayMode:!0,isFeeInclusiveInput:!1,parsedAmount:0,currentPaymentAmount:"0",destinationToken:c,resolvedTokenIn:c.address,executionTokenAddress:c.address,needsSwap:!1,resolvedSwap:null,isDirect:!0,actionInput:!e.isPayMode&&e.isFeeInclusiveInput?[{token:o.asset.address,amount:d}]:void 0,actionProceeds:s?{token:e.destinationToken.address,resolve:async()=>p>0n?p-1n:0n}:e.actionProceeds,feeFundingBalances:e.feeFundingBalances?.filter(w=>!w.balanceError&&!(e.feeFundingReserve&&Ge(e.feeFundingReserve.asset)!==Ge(o.asset)&&Ge(w)===Ge(e.feeFundingReserve.asset))&&!ws(w)&&(!w.owner||f.addressesEqual(w.owner,r))),feeFundingReserve:{asset:o.asset,amount:e.feeFundingReserve&&Ge(e.feeFundingReserve.asset)===Ge(o.asset)&&e.feeFundingReserve.amount>d?e.feeFundingReserve.amount:d},buildPayChainBatches:async w=>{const C=w?.actionAmountOverride??d;if(C<=0n)throw new Un(d+1n,d);const b=!e.isPayMode&&e.needsSwap?C===d?t.resolvedSwap:await t.resolveInputSwap?.(C,t.resolvedSwap??void 0):null,S=e.needsSwap?e.isPayMode?e.exactOutputSwap:b:null;if(e.needsSwap&&!S)throw new Error("The action quote is unavailable.");m=b??void 0,h=C,x=i??m?.amountOutMinimum??C;const I={userAddress:t.recipient??r,executorAddress:r,beneficiary:t.recipient??r,outputRecipient:r,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address,grossAmount:p,netAmount:x,feeToken:c.address,feeExecutionMode:"backend-transfer"},F=await t.buildActionCalls(x,I),k={amount:x,context:I,calls:F},E=[...S?.calls??[],...F];return Us({...t,selectedAsset:null,feeOnlyAction:!0,isPayMode:!0,isFeeInclusiveInput:!1,currentPaymentAmount:"0",destinationToken:c,resolvedTokenIn:c.address,needsSwap:!1,resolvedSwap:null,exactOutputSwap:null,quoteAmountOut:null,feeExecutionMode:"backend-transfer",buildActionCalls:()=>E},{...w,onActionCalls:()=>w?.onActionCalls?.(k)})}},y=await ci(g,n);if(!y)return null;if(s&&y.fundingSource?.kind==="proceeds"&&(x-=y.fundingConversion?.amountInMax??y.proceedsUsed??0n),x<=0n)throw new Error("Not enough action output remains after execution costs.");return{...y,fundedFeeToken:c,batches:y.fundingBatches??y.batches,destinationSwap:m,swapInputAmount:h,destinationAmount:x,sourceSpendCap:d+(y.fundingSource?.kind==="balance"&&y.fundingSource.asset&&Ge(y.fundingSource.asset)===Ge(o.asset)?y.fundingConversion?.amountInMax??y.proceedsUsed??0n:0n)}}async function Hd(e){const t=e.selectedAsset.asset;if(t.chainId!==e.destinationToken.chainId||!f.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=zt(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 di(e){const[t]=await e.buildSupplyChainBatches({sourceGasSkimOverride:1n,reuseQuotedSourceSwap:!0});if(!t)throw new Error("Swap quote not available yet");const{gasFee:n}=await f.relayerService.estimateBatchGas({user:e.user,outputToken:e.pivot.source.address,stepIndex:0,chainBatches:[t],signal:e.signal});return n}const ui=(e,t)=>(e+t-1n)/t;function Ho(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 Vd(e,t){const n=e.spicenetFee+(e.bridgeFee??0n);return e.grossAmount<=n?t+e.gasFee+n:ui((t+e.gasFee)*e.grossAmount,e.grossAmount-n)+2n}async function pi(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 p=1n,m;for(let h=0;h<8;h++){const x=In(await e.buildBatches(p),d,m,{payoutAlreadyGross:!0}),g=await e.estimate(Ms(x,e.tokenDescriptor.chainId,e.fundingToken),e.fundingToken,p,{...e.executionOptions,feeExecutionMode:"backend-transfer"}),y=f.getSupplyFeePreview(g,e.tokenDescriptor);if(!y)throw new Error("The fee service did not return a fee quote for this action");const w=y.gasFee+y.spicenetFee+(y.bridgeFee??0n);if(m&&w+2n<=p)return{preview:{...y,grossAmount:p,netAmount:0n},feeEstimate:g,grossFundingAmount:p};p=(w*110n+99n)/100n+2n,m=g}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=f.getSupplyFeePreview(s,e.tokenDescriptor);if(!o)return{preview:f.getEscrowFreeFeePreview(n,e.tokenDescriptor,t),feeEstimate:s,grossFundingAmount:t};const r=Vd(o,t),i=d=>o.grossAmount>0n?ui(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 fi(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 f.formatRawTokenInput(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 Qd(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:fi({balance:t.balance,decimals:t.decimals,planForAmount:s=>An({selectedAsset:{asset:t,amount:f.formatRawTokenInput(s,t.decimals)},isPayMode:!1,isNon7702:!1,isFeeInclusiveInput:!1,parsedAmount:Number(f.formatRawTokenInput(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 An(e){const{signal:t,selectedAsset:n,isPayMode:s,isFeeInclusiveInput:o=!1,parsedAmount:r,needsSwap:i,exactOutputSwap:l,isNon7702:c,currentPaymentAmount:d,destinationToken:p,feeExecutionMode:m,resolvedTokenIn:h,embeddedWalletAddress:x,providerEmbeddedAddress:g,resolvedChainId:y,isConnected:w,address:C,ready:b,authenticated:S,isDirect:I,resolvedSwap:F,sourceSwap:k,pivot:E,isQuoting:R,executionTokenAddress:j,buildPayChainBatches:A,buildSupplyChainBatches:M,estimate:P}=e;if(e.feeOnlyAction&&!n&&e.feeFunding?.length!==0)return ci(e,An);if(e.feeOnlyAction&&e.actionProceeds&&e.actionProceeds.token.toLowerCase()!==p.address.toLowerCase()||e.feeOnlyAction&&n&&(n.asset._source==="spice"||n.asset._source==="wallet"&&n.asset.chainId===y)&&(h?h.toLowerCase()!==p.address.toLowerCase():n.asset.receiptTokenId||n.asset.chainTokens))return ls(e);if(e.actionProceeds&&e.feeOnlyAction){const re=x||g;if(!re||!b||!S)return null;if(h&&h.toLowerCase()!==p.address.toLowerCase())throw new Error("Action proceeds require a matching fee-token source");return Ja({proceeds:e.actionProceeds,owner:re,token:p.address,signal:t,buildBatches:(Y,_)=>A({..._,fundingAmountOverride:Y}),baseline:()=>An({...e,actionProceeds:void 0,selectedAsset:n??{amount:"0",asset:{...p,name:p.symbol,balance:0n,balanceFormatted:0,balanceUsd:0,isNative:!1,_source:"spice"}}})})}if(!n?.asset)return null;if(s){if(!x&&!g||r<=0&&!e.feeOnlyAction||i&&!l&&!e.feeOnlyAction)return null;const re=zt(d,p.decimals),Y=h||Jt(n.asset,y)||n.asset.address||p.address,_={chainId:y,tokenAddress:Y,symbol:v.getTokenByAddress(Y,y)?.symbol??n.asset.symbol,decimals:await xn(n.asset,Y,y,p)};if(!w||!C||!b||!S)return null;const Z=x||g||C,pe=i?l?.amountInMax??0n:re;if(pe===0n&&!e.feeOnlyAction)return null;const D=E?await di({user:Z,pivot:E,buildSupplyChainBatches:W=>A({...W,sourceGasSkimOverride:1n}),signal:t}):0n,L=Date.now();let $=await pi({requiredNetFunding:pe,feeOnlyAction:e.feeOnlyAction,buildBatches:W=>A({fundingAmountOverride:W,sourceGasSkimOverride:D}).then(Q=>Za(Nd(Q),Z,void 0,{requestTimestampMs:L})),fundingToken:Y,estimate:P,executionOptions:{userOverride:Z,useCustomTransfers:!0,feeExecutionMode:m,signal:t},tokenDescriptor:_});if(!$.preview)return null;let de=0n,ce,he=[],X=!1;for(let W=0;W<8;W++){if(t?.aborted)throw new Error("Fee estimation cancelled");if(he=In(await A({fundingAmountOverride:$.grossFundingAmount,sourceGasSkimOverride:D,onSourceSpend:Ye=>{de=Ye},onActionCalls:Ye=>{ce=Ye}}),Z,$.feeEstimate,{payoutAlreadyGross:!0,requestTimestampMs:L}),e.feeOnlyAction){X=!0;break}const Q=await P(he,Y,$.grossFundingAmount,{userOverride:Z,useCustomTransfers:!0,feeExecutionMode:m,signal:t}),ae=m==="user-transfer"?Ho(Q,$.feeEstimate):Q,we=f.getSupplyFeePreview(ae,_)??f.getEscrowFreeFeePreview(he,_,pe);if(!we)return null;const ke=pe+we.gasFee+we.spicenetFee+(we.bridgeFee??0n),Ie=f.getSupplyFeePreview($.feeEstimate,_),be=(Ie?.gasFee??0n)===we.gasFee&&(Ie?.spicenetFee??0n)===we.spicenetFee&&(Ie?.bridgeFee??0n)===(we.bridgeFee??0n),J=$.grossFundingAmount===ke&&be;if($={feeEstimate:ae,grossFundingAmount:ke,preview:{...we,grossAmount:ke,netAmount:pe}},J){X=!0;break}}if(!X)throw new Error("Payment fees did not converge. Refresh the quote before submitting.");if(!$.preview)return null;const K=E?Qt(D,E.source.decimals,E.destination.decimals,"ceil"):0n;return{...$,batches:he,sourceSpendCap:de,actionDefinition:ce,destinationAmount:re,preview:{...$.preview,grossAmount:$.preview.grossAmount+K,gasFee:$.preview.gasFee+K,totalFee:($.preview.totalFee??0n)+K},...E?{sourceGasSkim:D}:{}}}if(r<=0||!x)return null;const N=x||g;if(E&&!k)return null;const B=zo({isPayMode:s,selectedAsset:n,resolvedChainId:y,sourceSwap:k,pivot:E});if(!(!s&&!c&&n.asset?._source==="wallet"&&n.asset.chainId!==y)&&!I&&!F&&!R||R)return null;let U=await M();if(U.length===0)return null;const O={chainId:y,tokenAddress:j,symbol:v.getTokenByAddress(j,y)?.symbol??(n.asset.chainId===y&&f.addressesEqual(n.asset.address,j)?n.asset.symbol:p.symbol),decimals:await xn(n.asset,j,y,p)},z=B&&e.initialFeeEstimate!==void 0&&e.initialSourceGasSkim!==void 0,q=B?z?e.initialSourceGasSkim:await di({user:N,pivot:E,buildSupplyChainBatches:M,signal:t}):0n;B&&q>0n&&(U=await M({sourceGasSkimOverride:q}));const ue=B?Qt(o?ti(k,q):k.amountOutMinimum,E.source.decimals,E.destination.decimals,"floor"):Qt(zt(n.amount,n.asset.decimals),n.asset.decimals,O.decimals,"floor"),le={userOverride:N,useCustomTransfers:!0,feeExecutionMode:m,signal:t,...B?{skipUserFundingPreflight:!0}:{}};let G=ue,ne=e.initialFeeEstimate??await P(U,j,G,le);for(let re=0;re<8;re++){if(t?.aborted)throw new Error("Fee estimation cancelled");const Y=f.getSupplyFeePreview(ne,O)??f.getEscrowFreeFeePreview(U,O,G);if(!Y)return null;const _=Vo(Y,ue,o,m);G=_.grossAmount;let Z,pe,D,L,$;const de=await M({fundingAmountOverride:G,sourceGasSkimOverride:q,actionContextOverride:_,onDestinationAmount:Q=>{Z=Q},onSourceSpend:Q=>{pe=Q},onSwap:(Q,ae)=>{D=Q,L=ae},onActionCalls:Q=>{$=Q}}),[ce,he]=await Promise.all([P(de,j,G,{...le,validateFeeCalls:e.initialFeeEstimate!==void 0}),z?f.relayerService.estimateBatchGas({user:N,outputToken:E.source.address,stepIndex:0,chainBatches:[de[0]],signal:t}):void 0]);if(he&&!(m==="user-transfer"?f.feeAmountsWithinTolerance(q,he.gasFee,e.feeToleranceBps):he.gasFee===q))throw new Error("Source gas changed. Prepare a fresh fee quote.");const X=m==="user-transfer"?Ho(ce,ne):ce,K=f.getSupplyFeePreview(X,O)??f.getEscrowFreeFeePreview(de,O,G);if(!K)return null;const W=Vo(K,ue,o,m);if(JSON.stringify(_,(Q,ae)=>typeof ae=="bigint"?ae.toString():ae)===JSON.stringify(W,(Q,ae)=>typeof ae=="bigint"?ae.toString():ae)||m==="user-transfer"&&f.feeBreakdownsWithinTolerance(_.feeBreakdown,W.feeBreakdown,e.feeToleranceBps)){const Q=m==="user-transfer"?Y:K,ae=B?Qt(q,E.source.decimals,E.destination.decimals,"ceil"):0n;return{batches:de,fundingAmount:G,actionContext:_,sourceSpendCap:pe,destinationAmount:Z,destinationSwap:D,swapInputAmount:L,actionDefinition:$,feeEstimate:m==="user-transfer"?ne:X,sourceGasSkim:q,preview:{...Q,grossAmount:G+ae,netAmount:_.netAmount,gasFee:Q.gasFee+ae,spicenetFee:_.feeBreakdown.spicenetFee,totalFee:_.combinedFeeAmount+ae}}}ne=X,U=de}throw new Error("Fees did not converge. Refresh the quote before submitting.")}class mi extends Error{constructor(t){super("Amount is too small to cover fees. Increase the amount and retry."),this.preview=t,this.name="FeeShortfallError"}}function Vo(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?f.splitFeeInclusiveAmount(t,o,10n):null;if(r&&!r.coversFees)throw new mi({...e,grossAmount:t,netAmount:0n,spicenetFee:0n,totalFee:o});const i=r?.spicenetFee??(s==="user-transfer"?f.calculateBpsFee(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 Gd(e,t){const n=e.selectedAsset?.asset;if(!n||n?._source!=="wallet")return;const s=Jt(n,e.resolvedChainId);if(!s||!f.addressesEqual(s,e.executionTokenAddress))return;const o=v.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),r=Wn(t,o?.decimals??e.destinationToken.decimals,n.decimals);if(r<=n.balance)return;const i=T.formatUnits(r,n.decimals),l=T.formatUnits(n.balance,n.decimals);throw new Error(`Insufficient ${n.symbol} for this total amount. Required ${i} ${n.symbol}; available ${l} ${n.symbol}.`)}function Yd(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=zt(e.selectedAsset.amount,t.decimals);if(n<=t.balance)return n;throw new Error(`Insufficient ${t.symbol} for this total amount. Required ${T.formatUnits(n,t.decimals)} ${t.symbol}; available ${T.formatUnits(t.balance,t.decimals)} ${t.symbol}.`)}function Zd(e,t,n){const s=f.getSupplyFeePreview(e,Yd(t));if(s)return Vo(s,n,!!t.isFeeInclusiveInput,t.feeExecutionMode)}function Xd(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=T.decodeFunctionData({abi:T.erc20Abi,data:l.data});if(c.functionName!=="transfer")continue;const d=c.args[0].toLowerCase(),p=c.args[1];d===v.SPICE_PLATFORM_FEE_RECIPIENT.toLowerCase()?s+=p:d===v.SPICE_GAS_FEE_RECIPIENT.toLowerCase()&&(o+=p)}catch{continue}}return{spicenetFee:s,gasFee:o}}function Jd(e,t,n,s){const o=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,r=Xd(e,t.resolvedChainId,o);return r.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||r.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:f.feeAmountsWithinTolerance(r.spicenetFee,n.feeBreakdown.spicenetFee,t.feeToleranceBps)&&f.feeAmountsWithinTolerance(r.gasFee,n.feeBreakdown.gasFee,t.feeToleranceBps)&&f.feeAmountsWithinTolerance(s.feeBreakdown.bridgeFee,n.feeBreakdown.bridgeFee,t.feeToleranceBps)}function $d(e,t,n){return e?f.amountsWithinBps(e.grossAmount,t.grossAmount,100n)&&f.feeBreakdownsWithinTolerance(e.feeBreakdown,t.feeBreakdown,n):!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}:pi({...t,feeOnlyAction:e.feeOnlyAction,estimate:e.execution.estimate,tokenDescriptor:_d(e,t.fundingToken)})}function hi(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 gi(e,t){const n=f.sanitizeError(t,"Payment failed. Please try again.");e.ui.setError(n),e.ui.setPaymentResult({status:"failed",error:n})}async function xi(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?gi(e,t):hi(e,t,!1)}finally{e.ui.setIsExecuting(!1)}}async function yi(e,t,n){e.validateFeeQuote?.();const s=e.feeQuote;if(!s.batches||s.sourceSpendCap===void 0||!s.fundingSource)throw new Error("Refresh the action before submitting.");const o=s.fundedFeeToken,r=s.grossFundingAmount??0n,i=_a({...e,signal:n,feeOnlyAction:!0,destinationToken:o,actionProceeds:e.actionProceeds??{token:s.fundingSource.token,resolve:async()=>s.proceedsAvailable??0n}},o.address,r);return e.execution.execute(s.batches,s.fundingConversion?.tokenIn??s.fundingSource.token,r,t,n,{...i,userOverride:e.embeddedWalletAddress||e.providerEmbeddedAddress,useCustomTransfers:!0,feeExecutionMode:"backend-transfer",skipPreSubmitFeeEstimate:!0})}async function wi(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 xi(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;if(e.feeQuote?.fundedFeeToken){const x=await yi(e,e.execution.onProgress,t.signal);e.ui.setTxHash(x),e.ui.setStep("success"),e.ui.setStatusMsg("Transaction confirmed");return}const s=zo(e);s&&Kd(e);const o=e.feeQuote?.batches?e.feeQuote:await An({...e,feeExecutionMode:e.feeExecutionMode,isDirect:!e.needsSwap,isQuoting:!1,resolvedSwap:null,buildPayChainBatches:e.execution.buildPayChainBatches,buildSupplyChainBatches:e.execution.buildSupplyChainBatches,estimate:e.execution.estimate});if(!o?.batches||o.fundingAmount===void 0||!o.actionContext)throw new Error("A current action plan is required. Refresh the quote before submitting.");const r=e.isFeeInclusiveInput?o.actionContext.grossAmount:o.actionContext.netAmount;let i=o.batches;const l=i.some(x=>x.tokenTransfers?.length),c={userOverride:n,useCustomTransfers:l,feeExecutionMode:e.feeExecutionMode,...s?{skipUserFundingPreflight:!0}:{}},d=o.fundingAmount,p=o.actionContext;Gd(e,d);const m=p,h=await e.execution.execute(i,e.executionTokenAddress,l?d:0n,e.execution.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...c,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:x,chainBatches:g})=>{const y=Zd(o.feeEstimate?Ho(x,o.feeEstimate):x,e,r);if(!y)throw new Error("Unable to validate the accepted fees. Refresh the quote before submitting.");const w=$d(m,y,e.feeToleranceBps),C=Jd(g,e,y,m);if(w||C)return null;throw new Error("Transaction fees changed. Refresh the quote before submitting.")}}:{...c,skipPreSubmitFeeEstimate:!0});e.ui.setTxHash(h),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){hi(e,n,t.signal.aborted)}finally{e.ui.setIsExecuting(!1)}}async function bi(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 xi(e);const n=ri(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{if(e.feeQuote?.fundedFeeToken){const S=await yi(e,I=>{I.txHash&&(e.ui.setTxHash(I.txHash),e.ui.setPaymentResult({status:"processing",txHash:I.txHash}))});e.ui.setPaymentResult(I=>({status:"success",txHash:I?.txHash||S}));return}const r=zt(e.currentPaymentAmount,e.destinationToken.decimals),i={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,...n?{skipUserFundingPreflight:!0}:{}};if(t&&!e.feeOnlyAction){const S=await o(),I=await e.execution.execute(S,e.executionTokenAddress,0n,F=>{F.txHash&&(e.ui.setPaymentResult(k=>({...k??{status:"processing"},txHash:F.txHash})),e.ui.setTxHash(F.txHash))},void 0,i);e.ui.setPaymentResult(F=>({status:"success",txHash:F?.txHash||I}));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,p=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:r,m=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,h=!!e.feeQuote?.fundingConversion||!!c&&(c.kind!=="balance"||c.asset?._source==="wallet"),{grossFundingAmount:x,feeEstimate:g}=h?{grossFundingAmount:e.feeQuote.grossFundingAmount??0n,feeEstimate:void 0}:await eu(e,{requiredNetFunding:p,buildBatches:S=>e.execution.buildPayChainBatches({fundingAmountOverride:S}).then(I=>In(I,m)),fundingToken:d,executionOptions:i});let y=e.feeQuote?.fundingBatches??e.feeQuote?.batches??In(await o({fundingAmountOverride:x}),m,e.actionProceeds?void 0:g,{payoutAlreadyGross:!0});const w=_a(e,e.feeQuote?.fundingConversion?.tokenOut??d,x);w.prepareForSigning&&(y=await w.prepareForSigning(y));const C=y.some(S=>S.tokenTransfers?.length),b=await e.execution.execute(y,d,C?x:0n,S=>{S.txHash&&(e.ui.setPaymentResult(I=>({...I,txHash:S.txHash})),e.ui.setTxHash(S.txHash))},void 0,{...i,...w,skipPreSubmitFeeEstimate:!0});e.ui.setPaymentResult(S=>({status:"success",txHash:S?.txHash||b}))}catch(r){gi(e,r)}finally{e.ui.setIsExecuting(!1)}}async function tu(e){const{definition:t,account:n,chainId:s}=e,{calls:o}=t;if(!f.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=f.getClientForChain(s);let i;for(const l of o){await e.assertCurrent();const[c,d]=await Promise.all([Fa({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:p,viemChain:m}=await Ro({wallet:e.wallet,account:n,chainId:s});i=await Xc({extWc:p,viemChain:m,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}async function Ci(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=f.getClientForChain(t.chainId),i=t.isNative||v.isNativeToken(t.address),[l,c]=await Promise.all([Ta({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:p}=await Ro({wallet:e.externalWallet,account:s,chainId:t.chainId});await Jc({extWc:d,sourceClient:r,recipient:n,tokenAddr:t.address,isNative:i,amount:o,viemChain:p,observer:{onSending:()=>e.assertCurrent()}})}function vi(e){const t=u.useContext(f.SpiceFlowProviderContext),n=f.getChainConfig(e.chainId),s=e.address??n?.supportedTokens?.find(g=>g.symbol.toLowerCase()===e.symbol?.toLowerCase())?.address,o=e.symbol??(s&&v.isNativeToken(s)?n?.nativeCurrency?.symbol:n?.supportedTokens?.find(g=>!!s&&f.addressesEqual(g.address,s))?.symbol),r=f.getRpcUrlForChain(e.chainId,t?.rpcOverrides),[i,l]=u.useState(0),c=`${e.chainId}:${s?.toLowerCase()}:${r}:${e.decimals??""}:${o??""}:${i}`,[d,p]=u.useState(null);u.useEffect(()=>{let g=!1;if(!(!e.enabled||!s||!r?.trim()))return Promise.all([e.decimals??f.getTokenDecimals(e.chainId,s,t?.rpcOverrides),o??_t.readContract(f.getClientForChain(e.chainId,t?.rpcOverrides),{address:s,abi:T.erc20Abi,functionName:"symbol"}).catch(()=>{})]).then(([y,w])=>{if(!Number.isInteger(y)||y<0||y>255)throw new Error("Invalid destination token decimals");g||p({key:c,decimals:y,symbol:w})}).catch(y=>{g||p({key:c,error:y.message})}),()=>{g=!0}},[e.enabled,c]);const m=d?.key===c?d:null,h=u.useMemo(()=>({address:s??v.ZERO_ADDRESS,chainId:e.chainId,decimals:m?.decimals??0,symbol:o??m?.symbol??(s?f.truncateAddress(s):""),logoURI:e.logoURI}),[s,e.chainId,m?.decimals,m?.symbol,o,e.logoURI]),x=e.enabled?s?r?.trim()?m?.error??null:`Configure SpiceFlowProvider rpcOverrides[${e.chainId}] before continuing.`:"Configure the destination token address before continuing.":null;return{token:h,error:x,ready:e.enabled&&!!s&&!!r?.trim()&&m?.decimals!==void 0,refresh:u.useCallback(()=>l(g=>g+1),[])}}function ki(e,t){const n=!!e&&e.symbol!==void 0&&e.decimals!==void 0,s=vi({enabled:t&&!!e&&!n,chainId:e?.chainId??0,address:e?.address,decimals:e?.decimals,symbol:e?.symbol,logoURI:e?.logoURI});return{token:e?n?e:s.ready?s.token:void 0:void 0,error:s.error}}const Qo={address:v.ZERO_ADDRESS,symbol:"",decimals:18,chainId:0};function Si(e,t,n){return f.addressesEqual(e.address,t)&&e.chainId===n?e._source==="wallet"?0:1:2}function nu(e,t,n,s){const o=Si(e,n,s)-Si(t,n,s);return o!==0?o:(t.balanceUsd||0)-(e.balanceUsd||0)}const su=qr;function Ii(e){const t=u.useContext(f.SpiceFlowProviderContext),n=f.useProviderWallets(),s=t?.embeddedWalletAddress||n.embeddedAddress,o=t?.externalWalletAddress||n.externalAddress,r=(t?.mode||"7702")!=="7702",i=e.destinationToken??Qo,l=e.enabled&&!!e.destinationToken,c=Nn({...e,owner:s,enabled:l&&!!s&&(!r||e.includeCrossChainEmbeddedAssets!==!1),role:"spend-source",destination:e.destinationToken}),d=Nn({...e,owner:o,enabled:l&&!!o&&(r||e.includeExternalWalletAssets!==!1),role:"spend-source",destination:e.destinationToken});return{displayAssets:u.useMemo(()=>[...c.assets,...d.assets].sort((p,m)=>nu(p,m,i.address,i.chainId)),[c.assets,d.assets,i.address,i.chainId]),filteredSpiceAssets:c.rollupAssets,walletAssets:[...c.walletAssets,...d.walletAssets],embeddedWalletAddress:s,externalAddress:o,isNon7702:r,refreshSpiceAssets:c.refresh,refreshWalletAssets:c.refresh,loading:c.loading||d.loading,refreshing:c.refreshing||d.refreshing,error:c.error||d.error}}function ou(e,t){return!e||e._source!=="wallet"?null:fo(e,t)}function Go(e){return Cr({aerodrome:!1,oneInch:{chainIds:[]},customVenues:e})}const Yo=Bn(),ru=Go(Yo.input);function Ai(e){return{venue:"mapped-transfer",amountOut:e,amountOutMinimum:e,calls:[]}}function Ei(e){return{venue:"mapped-transfer",amountIn:e,amountInMax:e,amountOut:e,calls:[]}}async function Ko(e){if(f.addressesEqual(e.tokenIn,e.tokenOut))return Ai(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?Go(Bn(e.liquidityVenues).input):ru).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 au(e){return f.addressesEqual(e.tokenIn,e.tokenOut)?Ei(e.amountOut):Ls({customVenues:e.liquidityVenues?Bn(e.liquidityVenues).output:Yo.output}).getQuote({tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountOut:e.amountOut,maxSlippage:e.maxSlippage},e.chainId,e.recipient)}function Fi(e){const{enabled:t=!0,direction:n,selectedAsset:s,destinationToken:o,chainId:r=o.chainId,recipient:i,paymentAmount:l,maxSlippage:c,refreshIntervalMs:d,resolveInputSwap:p,resolveExactOutputSwap:m}=e,h=u.useContext(f.SpiceFlowProviderContext),x=h?.liquidityVenues,g=JSON.stringify([h?.network,h?.apiUrl,h?.rpcOverrides]),[y,w]=u.useState(!1),[C,b]=u.useState(null),[S,I]=u.useState(null),[F,k]=u.useState(null),[E,R]=u.useState(null),[j,A]=u.useState(null),[M,P]=u.useState(null),[N,B]=u.useState(null),[U,O]=u.useState(null),[z,q]=u.useState(null),[ue,le]=u.useState(null),[G,ne]=u.useState(null),[re,Y]=u.useState(null),[_,Z]=u.useState(null),[pe,D]=u.useState(0),[L,$]=u.useState(null),[de,ce]=u.useState(null),he=u.useRef(null),X=u.useRef(null),K=u.useRef(0),W=u.useRef(new Map),Q=u.useCallback(()=>{K.current++,W.current.clear(),ce(null),D(Re=>Re+1)},[]),ae=d&&d>0?d:null,we=x?JSON.stringify(x):"",ke=u.useMemo(()=>x?Bn(x):Yo,[we]),Ie=u.useMemo(()=>Go(ke.input),[ke]),be=u.useMemo(()=>Ls({customVenues:[...m?[{name:"consumer-exact-output",chainIds:[r],preferred:!0,resolve:m}]:[],...ke.output]}),[m,r,ke]);u.useEffect(()=>{W.current.clear()},[be]);const J=u.useMemo(()=>t?ou(s?.asset,r):null,[t,s?.asset,r]),Ye=u.useMemo(()=>{if(!t||!s?.asset)return null;if(J)return J.destination.address;const Re=Jt(s.asset,r);if(Re)return Re;const _e=fn(s.asset.address,r,s.asset.chainId);return _e?_e.address:null},[t,s?.asset,r,J]),Ne=u.useMemo(()=>t&&s?.asset?Rn(s.asset,r):[],[t,s?.asset,r]),dt=u.useMemo(()=>Ne.map(Re=>Re.toLowerCase()).join(","),[Ne]),rt=JSON.stringify([t,g,s?.asset.owner,s?.asset.location,s?.asset.receiptTokenId,s?.asset.address,s?.asset.chainId,s?.asset.decimals,s?.amount,r,dt,n,l]);u.useEffect(()=>{let Re=!1;if(X.current&&(clearTimeout(X.current),X.current=null),!t||!s?.asset||J||Ne.length<=1){Y(null),Z(null);return}return X.current=setTimeout(async()=>{const _e=n==="input"?s.amount:l||"0";let He=0n;try{He=n==="input"?zt(_e,s.asset.decimals):0n}catch{He=0n}try{const et=await Wr(s.asset,r,{requiredAmount:He});Re||(Y(et),Z(rt))}catch{Re||Y(null)}},400),()=>{Re=!0,X.current&&(clearTimeout(X.current),X.current=null)}},[rt]);const Me=u.useMemo(()=>(_===rt?re:null)??Ye,[re,_,rt,Ye]),Pe=u.useMemo(()=>!s?.asset||!Me?[]:[Me,...Ne.filter(Re=>Re.toLowerCase()!==Me.toLowerCase())],[s?.asset,Me,Ne]),Xe=u.useMemo(()=>!s?.asset||!Kn(s.asset.address,s.asset.chainId,o.address,o.chainId)||!Me?!1:f.addressesEqual(Me,o.address),[s,o.address,o.chainId,Me]),Ue=Me?f.addressesEqual(Me,o.address):!1,ht=n==="output"&&parseFloat(l||"0")===0,We=t&&!!s?.asset&&!Xe&&!Ue&&!ht,at=JSON.stringify([t,we,n,We,g,s?.asset.owner,s?.asset.location,s?.asset.receiptTokenId,s?.asset.address,s?.asset.chainId,s?.asset.decimals,n==="input"?s?.amount:l,Pe.map(Re=>Re.toLowerCase()),r,o.address.toLowerCase(),o.chainId,o.decimals,i?.toLowerCase(),c,ae,J?.source.address.toLowerCase()??""]),Ae=u.useMemo(()=>({}),[at,Ie,be,p,pe]),Qe=de?.request===Ae&&(!ae||de.expiresAt>Date.now());return u.useEffect(()=>{if(!ae||de?.request!==Ae)return;const Re=setTimeout(Q,Math.max(0,de.expiresAt-Date.now()));return()=>clearTimeout(Re)},[ae,de,Ae,Q]),u.useEffect(()=>{he.current&&clearTimeout(he.current),$(Ae),ce(null),b(null);const Re=n==="input"?s?.amount:l,_e=parseFloat(Re||"0");if(!t||!Number.isFinite(_e)||_e<=0||!s?.asset||!i||Pe.length===0){K.current++,I(null),k(null),R(null),A(null),P(null),B(null),O(null),ne(null),b(null),w(!1);return}const He=s.asset.decimals;let et;try{et=n==="input"?zt(s.amount,He):zt(l||"0",o.decimals)}catch(Fe){K.current++,b(Fe instanceof Error?Fe.message:"Invalid amount or token precision"),w(!1);return}const ut=++K.current,tt=()=>ut!==K.current;w(!0);const Ee=n==="output"?150:100,st=async(Fe,ee,te,De={chainId:r,tokenOut:o.address,amountIn:et},ye=Pe)=>{for(const ie of ye){const je=`${g}:${we}:${n}:${De.chainId}:${ie.toLowerCase()}:${De.tokenOut.toLowerCase()}:${De.amountIn.toString()}:${i.toLowerCase()}:${c??"default"}:${ae??"default"}`,ve=W.current.get(je),V=ve&&ve.expiresAt>Date.now()?Fe(ve):void 0;if(V)return{quote:V,tokenIn:ie,expiresAt:ve.expiresAt};const Le=await te(ie);if(tt())return"stale";if(!Le)continue;const me=Date.now()+Math.min(ae??3e4,3e4);return W.current.set(je,{expiresAt:me,direction:n,...ee(Le)}),{quote:Le,tokenIn:ie,expiresAt:me}}return null},gt=Fe=>st(ee=>ee.resolvedSwap,ee=>({resolvedSwap:ee}),async ee=>{const te=!J&&Fe.chainId===r&&s.asset._source!=="wallet",De=te?await xn(s.asset,ee,Fe.chainId,o):He;if(tt())return null;const ye=te?Os(Fe.amountIn,He,De):Fe.amountIn;if(f.addressesEqual(ee,Fe.tokenOut))return Ai(ye);const ie={type:"swap",tokenIn:ee,tokenOut:Fe.tokenOut,amountIn:ye,maxSlippage:c};if(p){const je=await p(ie,Fe.chainId,i);if(je)return je}return Ie.resolveSwap(ie,Fe.chainId,i)},Fe,Fe.candidates);return he.current=setTimeout(async()=>{try{if(n==="input"){let Fe=null,ee=et;if(J){if(Fe=await gt({chainId:J.source.chainId,tokenOut:J.source.address,amountIn:et,candidates:[s.asset.address]}),Fe==="stale"||tt())return;if(!Fe)throw new Error("No liquidity for this pair");ee=Qt(Fe.quote.amountOutMinimum,J.source.decimals,J.destination.decimals,"floor")}const te=We||!J?await gt({chainId:r,tokenOut:o.address,amountIn:ee,candidates:Pe}):null;if(te==="stale"||tt())return;if(We&&!te)throw new Error("No liquidity for this pair");const De=te?te.quote.amountOut:ee,ye=Math.min(te?.expiresAt??1/0,Fe?.expiresAt??1/0),ie=J?.destination.decimals??await xn(s.asset,te.tokenIn,r,o),je=!J&&s.asset._source!=="wallet"?Os(ee,He,ie):ee;if(tt())return;ne(te?.tokenIn??J?.destination.address??null),ce({request:Ae,key:`${T.keccak256(T.toHex(at))}:${ut}`,expiresAt:ye}),O(De),q(je),le(ie),R(We?te?.quote??null:null),A(Fe?.quote??null),P(null),B(null);const ve=parseFloat(T.formatUnits(De,o.decimals));I(ve<.01?ve.toPrecision(4):ve.toLocaleString(void 0,{maximumFractionDigits:6})),k(null),b(null)}else{const Fe=je=>st(ve=>ve.exactOutputSwap,ve=>({exactOutputSwap:ve}),async ve=>{try{return f.addressesEqual(ve,je.tokenOut)?Ei(je.amountOut):await be.getQuote({tokenIn:ve,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),ee=!J||We,te=ee?await Fe({chainId:r,tokenOut:o.address,amountOut:et,candidates:Pe}):null;if(te==="stale"||tt())return;if(ee&&!te)throw new Error("No liquidity for this pair");let De=null;if(J){const je=te?te.quote.amountInMax:et;if(De=await Fe({chainId:J.source.chainId,tokenOut:J.source.address,amountOut:Qt(je,J.destination.decimals,J.source.decimals,"ceil"),candidates:[s.asset.address]}),De==="stale"||tt())return;if(!De)throw new Error("No liquidity for this pair")}const ye=De?He:await xn(s.asset,te.tokenIn,r,o);if(tt())return;ne(te?.tokenIn??J?.destination.address??null),ce({request:Ae,key:`${T.keccak256(T.toHex(at))}:${ut}`,expiresAt:Math.min(te?.expiresAt??1/0,De?.expiresAt??1/0)}),B(te?.quote??null),P(De?.quote??null),R(null),A(null),O(null);const ie=De?.quote.amountIn??te.quote.amountIn;k(T.formatUnits(ie,ye)),I(null),b(null)}}catch(Fe){if(tt())return;const ee=Fe instanceof Error?Fe.message:"Failed to get quote";b(ee),I(null),k(null),R(null),A(null),P(null),B(null),O(null),ne(null)}finally{tt()||w(!1)}},We||J?Ee:0),()=>{K.current++,he.current&&clearTimeout(he.current)}},[Ae]),{inputAmount:Qe&&n==="input"?z:null,inputDecimals:Qe&&n==="input"?ue:null,quoteKey:Qe?de.key:null,quoteExpiresAt:Qe?de.expiresAt:null,refreshQuote:Q,isQuoting:L===Ae?y:We||!!J,quoteError:L===Ae?C:null,estimatedOutput:Qe?S:null,estimatedInput:Qe?F:null,resolvedSwap:Qe?E:null,exactOutputSwap:Qe?N:null,quoteAmountOut:Qe?U:null,resolvedTokenIn:We&&Qe?G??Me:Me,isDirect:Ue,needsSwap:We,selectedIsEquivalent:Xe,sourceSwap:Qe?j:null,sourceExactOutputSwap:Qe?M:null,pivot:J}}function cs(e){const{enabled:t=!0,destinationToken:n,selectedAsset:s,paymentAmount:o="0",sourceChains:r,supportedSourceAssets:i,buildActionCalls:l,feeExecutionMode:c="user-transfer",buildSpicenetBatch:d,onPayExecute:p,resolveExactOutputSwap:m,amountDirection:h=e.feeOnlyAction?"output":"input",onSuccess:x,onError:g}=e,y=ki(n,t),w=y.token??Qo,C=t&&!!y.token,b=h==="output",S=h==="input-inclusive",I=e.feeFunding?.length!==0&&(e.actionProceeds==="output"||!!e.feeFunding?.length),F=b?"output":"input",k=w.chainId,E=u.useContext(f.SpiceFlowProviderContext),R=f.resolveFeeToleranceBps(E?.feeToleranceBps),j=E?.mode||"7702",A=!1,M=!!E?.isWhitelistGateActive,P=!!E?.isWhitelistConfigured&&E?.isUserWhitelisted!==!0,N=u.useMemo(()=>r??E?.supportedChainIds??[],[r,E?.supportedChainIds]),B=i,{address:U,isConnected:O,isReady:z,isAuthenticated:q,provider:ue}=f.useWallet(),{execute:le,estimate:G}=Fs(),{externalWallet:ne,embeddedAddress:re,activeWallet:Y,activeAddress:_}=f.useProviderWallets(),Z=E?.externalWalletAddress,pe=E?.embeddedWalletAddress||re,D=s,L=ws(D?.asset,j!=="7702"),$=!!D&&D.asset.chainId===w.chainId&&f.addressesEqual(v.normalizeNativeTokenAddress(D.asset.address),v.normalizeNativeTokenAddress(w.address)),de=j!=="7702"&&L&&$&&(!b||Number(o)>0)&&!e.feeOnlyAction&&!e.actionProceeds,ce=L&&!de,he=y.error?y.error:p?"Move onPayExecute protocol calls to buildActionCalls and application updates to onSuccess before continuing.":e.actionExecution?.wallet==="external"&&!de?"This action requires the external wallet as its caller. Select its destination token on the destination chain for direct execution, or configure a beneficiary-capable embedded action for routing.":null,{displayAssets:X,filteredSpiceAssets:K,walletAssets:W,embeddedWalletAddress:Q,refreshSpiceAssets:ae,refreshWalletAssets:we,loading:ke,refreshing:Ie,error:be}=Ii({address:U,destinationToken:w,supportedSourceAssets:B,sourceChains:N,additionalSourceTokens:[...e.additionalSourceTokens??[],...D?.asset._source==="wallet"?[{address:D.asset.address,chainId:D.asset.chainId,decimals:D.asset.decimals,symbol:D.asset.symbol,name:D.asset.name,logoURI:D.asset.logoURI}]:[]],includeExternalWalletAssets:e.includeExternalWalletAssets,includeCrossChainEmbeddedAssets:e.includeCrossChainEmbeddedAssets,enabled:C&&(j!=="7702"?!!Z:!!pe)}),J=X,Ye=u.useMemo(()=>e.feeOnlyAction||I?J.filter(se=>se.balance>0n&&se.location!=="external"&&(se._source==="spice"||se._source==="wallet"&&se.chainId===k)):[],[J,e.feeOnlyAction,I,k]),Ne=D?[...W,...K].find(se=>Ge(se)===Ge(D.asset)):void 0,dt=u.useMemo(()=>D&&Ne?{...D,asset:Ne}:D,[D,Ne]),rt=D?kn(Ne??D.asset,"spend-source",{allowedTokens:E?.allowedTokens,rpcOverrides:E?.rpcOverrides,liquidityVenues:E?.liquidityVenues,isWhitelistGateActive:M},w,B):null,Me=Ne?Ne.balance<(D?.asset.balance??0n)?Ne.balance:D.asset.balance:0n,[Pe,Xe]=u.useState(!1),[Ue,ht]=u.useState(null),We=u.useRef(g);We.current=g;const at=u.useCallback(se=>{ht(se),typeof se=="string"&&se&&We.current?.(new Error(se),f.getRelayerErrorDetail(se))},[]),[Ae,Qe]=u.useState("idle"),[Re,_e]=u.useState(""),[He,et]=u.useState(null),[ut,tt]=u.useState(!1),[Ee,st]=u.useState(null),[gt,Fe]=u.useState(null),[ee,te]=u.useState(!1),[De,ye]=u.useState(!1),[ie,je]=u.useState(null),ve=u.useRef(D),V=u.useRef(!1),Le=u.useRef(null),me=u.useRef(null),ze=u.useRef(null),vt=u.useRef(null),kt=u.useRef(null),Se=u.useRef(null),yt=u.useRef(x),wt=u.useRef(null),it=u.useRef(!1),[nn,mn]=u.useState(null),[Gt,an]=u.useState(null),[Yt,It]=u.useState(!1),[Ft,Wt]=u.useState(0),Bt=Ee?.status==="success"?Ee.txHash:Ae==="success"?He:null,Tt=!!Bt&&nn!==Bt,Mt=u.useRef(Tt);Mt.current=Tt,u.useEffect(()=>{ve.current=D},[D]);const Ke=de?Z:Q||re||U,qe=C&&!Pe&&Ae==="idle"&&!he&&!P&&!!Ke&&!de&&!b&&S&&c==="user-transfer"&&!e.feeOnlyAction&&!e.actionInput&&!e.actionProceeds&&!!D&&Number(D.amount||"0")===0&&!!rt?.eligible&&Me>0n,Rt=u.useMemo(()=>{if(!qe||!D)return D;const se=10n**BigInt(D.asset.decimals);return{...D,amount:T.formatUnits(Me<se?Me:se,D.asset.decimals)}},[qe,D,Me]),Kt=Fi({enabled:C&&!P&&!de,direction:F,selectedAsset:Rt,destinationToken:w,chainId:k,recipient:Ke,paymentAmount:o,resolveExactOutputSwap:m,resolveInputSwap:e.resolveInputSwap,maxSlippage:e.maxSlippage}),Dt=de?{...Kt,quoteKey:"direct-external",quoteExpiresAt:null,quoteAmountOut:null,inputAmount:null,inputDecimals:D?.asset.decimals??null,isQuoting:!1,quoteError:null,isDirect:!0,needsSwap:!1,selectedIsEquivalent:!0,resolvedTokenIn:w.address,resolvedSwap:null,exactOutputSwap:null,sourceSwap:null,sourceExactOutputSwap:null,pivot:null,estimatedInput:b?o:D?.amount??null,estimatedOutput:b?o:D?.amount??null}:Kt,Be=Dt,{isQuoting:Lt,resolvedSwap:Te,exactOutputSwap:Ot,quoteAmountOut:pt,resolvedTokenIn:nt,isDirect:ln,needsSwap:Vt,selectedIsEquivalent:zn,sourceSwap:oe,sourceExactOutputSwap:fe,pivot:xe}=Dt,Ve=b?parseFloat(o||"0"):parseFloat(D?.amount||"")||0,St=D?.asset?._source==="wallet",ft=!!D?.asset&&St&&D.asset.chainId!==k,Pt=D?Number(T.formatUnits(Me,D.asset.decimals)):0,Ut=u.useMemo(()=>{if(!D||b)return!1;try{return zt(D.amount||"0",D.asset.decimals)>Me}catch{return!0}},[D,b,Me]);u.useEffect(()=>{C||(at(null),Xe(!1),Tt||(Qe("idle"),_e(""),et(null),tt(!1),st(null)),Fe(null),te(!1),ye(!1),je(null),V.current=!1,Le.current&&(Le.current.abort(),Le.current=null))},[C,Tt]);const qt=u.useCallback(se=>{Qe({building:"building","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[se.step]||"executing"),_e(se.message),se.txHash&&et(se.txHash)},[]),At=u.useMemo(()=>({currentPaymentAmount:o,isFeeInclusiveInput:S,feeOnlyAction:e.feeOnlyAction,swapInputAmount:Dt.inputAmount,destinationToken:w,embeddedWalletAddress:Q,providerEmbeddedAddress:re,externalWalletAddress:Z,address:U,recipient:e.recipient??(j!=="7702"?Z:void 0),isNon7702:A,isPayMode:b,resolvedChainId:k,buildActionCalls:l,feeExecutionMode:c,buildSpicenetBatch:d,selectedAsset:D,needsSwap:Vt,resolvedSwap:Te,exactOutputSwap:Ot,quoteAmountOut:pt,resolvedTokenIn:nt,sourceSwap:oe,sourceExactOutputSwap:fe,pivot:xe,resolveSourceExactOutputSwap:async se=>{if(!xe||!Ke)throw new Error("Swap route is not ready.");const $e=await au({chainId:xe.source.chainId,recipient:Ke,tokenIn:D.asset.address,tokenOut:xe.source.address,amountOut:se,liquidityVenues:E?.liquidityVenues,maxSlippage:e.maxSlippage}).catch(()=>null);if(!$e)throw new Error("No liquidity for this pair.");return $e},resolveInputSwap:async(se,$e)=>{if(!nt||!Ke)throw new Error("Swap route is not ready.");return Ko({chainId:k,recipient:Ke,tokenIn:nt,tokenOut:w.address,amountIn:se,selectedSwap:$e,liquidityVenues:E?.liquidityVenues,maxSlippage:e.maxSlippage,resolveInputSwap:e.resolveInputSwap})}}),[o,w,Q,re,Z,U,e.recipient,e.feeOnlyAction,e.maxSlippage,e.resolveInputSwap,Dt.inputAmount,S,j,A,b,k,l,c,d,D,Vt,Te,Ot,pt,nt,oe,fe,xe,Ke,E?.liquidityVenues]),Nt=u.useMemo(()=>D?.asset?xe?xe.destination.address:Vt&&nt?nt:D.asset.chainId===k?D.asset.address:nt??Jt(D.asset,k)??w.address:w.address,[D,w.address,Vt,k,nt,xe]),bt=JSON.stringify([D&&Ge(D.asset),h,w.address,w.chainId,w.decimals,e.recipient,j,Z,de?Z:Q,E?.apiUrl,E?.rpcOverrides,e.maxSlippage,c,R,e.feeOnlyAction,e.actionProceeds==="output"?"output":e.actionProceeds?.token,e.feeFunding,e.actionInput?.map(se=>[se.token,se.amount.toString()]),e.feeFundingReserve&&Ge(e.feeFundingReserve.asset),e.feeFundingReserve?.amount.toString(),E?.liquidityVenues,E?.allowedTokens,M,B,N,e.actionInput,e.actionProceeds,e.feeFunding,k,Nt,Be.pivot?.source.address,Be.pivot?.destination.address],(se,$e)=>typeof $e=="bigint"?$e.toString():$e),vn=u.useRef(null);vn.current=C&&!Pe&&!he&&!P?bt:null,u.useEffect(()=>()=>{kt.current?.controller.abort(),kt.current=null},[bt,C,Pe,he,P]);const Et=T.keccak256(T.stringToHex(JSON.stringify([bt,D?.amount,o]))),Zt=u.useRef({key:Et,enabled:C,sourceBalance:Me,sourceEligible:rt?.eligible});Zt.current={key:Et,enabled:C,sourceBalance:Me,sourceEligible:rt?.eligible};const $t=u.useRef(null),Xt=u.useRef(!1),hn=u.useRef(e.onSubmit);hn.current=e.onSubmit;const Fn=u.useCallback(()=>Xt.current?(Xt.current=!1,hn.current?.(),yt.current=Se.current.onSuccess,$t.current={key:Zt.current.key,quote:Se.current.feeQuote},wi(Se.current)):Promise.resolve(),[]),H=de,ge=P,Oe=!ze.current?.quote.fundedFeeToken&&(S||!!xe)&&!!gt&>.netAmount===0n,Ce=u.useMemo(()=>!!e.feeOnlyAction||(!!D?.asset||!!e.actionProceeds)&&Ve>0,[D,Ve,e.actionProceeds,e.feeOnlyAction]),ot=u.useMemo(()=>!C||!Ce||!D?.asset&&!e.actionProceeds&&!e.feeOnlyAction?null:[Et,b?"pay":"supply",h,D?Ge(D.asset):"sdk-funded",e.actionInput?.map(se=>`${se.token.toLowerCase()}:${se.amount}`).join(",")??"",e.feeFunding?.join(",")??"",JSON.stringify(E?.rpcOverrides),E?.apiUrl,e.recipient,D?.asset.address.toLowerCase(),D?.asset.chainId,D?.amount,o,w.address.toLowerCase(),w.chainId,k,Be.resolvedTokenIn?.toLowerCase()??"",Be.quoteKey,Be.needsSwap?"swap":"direct",Be.isDirect?"direct-token":"routed-token","7702",$?"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()??"",Q??"",re??"",U??""].join("|"),[C,Et,e.actionProceeds,e.feeOnlyAction,e.actionInput,e.feeFunding,Pe,Ae,Ce,H,D,b,h,o,w,k,Be,A,$,Q,re,U]),Ze=u.useCallback(async(se,$e,Ct)=>{if(de){if(!Z||!D)throw new Error("Connect the external wallet before continuing.");return Hd({selectedAsset:$e?.selectedAsset??D,destinationToken:w,paymentAmount:b?o:void 0,account:Z,beneficiary:e.recipient,buildActionCalls:l,feeExecutionMode:c})}const lt={...Ct??{...At,selectedAsset:Rt},requestTimestampMs:Date.now()},Je={signal:se,feeToleranceBps:R,feeOnlyAction:e.feeOnlyAction,actionInput:e.actionInput,actionProceeds:e.actionProceeds==="output"?void 0:e.actionProceeds,feeFunding:e.feeFunding,feeFundingBalances:Ye,feeFundingReserve:e.feeFundingReserve,liquidityVenues:E?.liquidityVenues,maxSlippage:e.maxSlippage,resolveExactOutputSwap:m,selectedAsset:Rt,isPayMode:b,isFeeInclusiveInput:S,parsedAmount:qe?Number(Rt.amount):Ve,needsSwap:Be.needsSwap,exactOutputSwap:Be.exactOutputSwap,isNon7702:A,isSourceDestToken:$,currentPaymentAmount:o,destinationToken:w,feeExecutionMode:c,resolvedTokenIn:Be.resolvedTokenIn,embeddedWalletAddress:Q,providerEmbeddedAddress:re,resolvedChainId:k,isConnected:O,address:U,ready:z,authenticated:q,isDirect:Be.isDirect,resolvedSwap:Be.resolvedSwap,sourceSwap:Be.sourceSwap,sourceExactOutputSwap:Be.sourceExactOutputSwap,pivot:Be.pivot,isQuoting:Be.isQuoting,executionTokenAddress:Nt,buildPayChainBatches:ct=>Us(lt,ct),buildSupplyChainBatches:ct=>Ws(lt,ct),estimate:G,...$e},mt=!Je.feeOnlyAction&&Je.selectedAsset&&I&&Je.selectedAsset.asset._source==="wallet"&&Je.selectedAsset.asset.chainId===k;if(I&&!Je.feeOnlyAction&&Je.selectedAsset&&!mt&&e.feeFunding&&e.feeFunding.join(",")!==qo.join(","))throw new Error("Fee-source overrides require a wallet source on the action chain.");return mt||I&&e.actionProceeds==="output"?qd(Je,lt,An,e.actionProceeds==="output"):An(Je)},[D,I,Rt,qe,de,Z,e.recipient,l,e.feeOnlyAction,e.actionInput,e.actionProceeds,e.feeFunding,Ye,e.feeFundingReserve,e.maxSlippage,m,R,E?.liquidityVenues,b,S,Ve,Be,A,$,o,w,c,Q,re,At,G,k,O,U,z,q,Nt]);u.useEffect(()=>{me.current=Ze},[Ze]);const gn=u.useCallback(async se=>{if(b)return null;if(!D||Ge(se)!==Ge(D.asset)||!Ke||!nt)throw new Error("Select a source before calculating Max.");let $e=se.balance;if(de){if(!se.isNative&&!v.isNativeToken(se.address))return T.formatUnits($e,se.decimals);const Ct=f.getClientForChain(se.chainId),lt=Z;let Je=$e;for(let mt=0;mt<8;mt++){const ct=await Ze(void 0,{selectedAsset:{asset:se,amount:T.formatUnits(mt===0?1n:Je,se.decimals)}});if(!ct?.actionDefinition)throw new Error("The direct action could not be sized.");const Ht=await Fa({client:Ct,account:lt,calls:ct.actionDefinition.calls}),Ks=$e>Ht?$e-Ht:0n;if(Ks===0n)return"0";if(mt>0&&Je<=Ks)return T.formatUnits(Je,se.decimals);Je=Ks}throw new Error("Network gas could not be reserved for Max. Enter a smaller amount.")}if(ce&&(se.isNative||v.isNativeToken(se.address))){if(!Z)throw new Error("Connect the source wallet before calculating Max.");const Ct=await Ta({client:f.getClientForChain(se.chainId),account:Z,recipient:Ke,token:se.address,isNative:!0,amount:1n});$e-=Ct}return I&&S&&se._source==="wallet"&&se.chainId===k?T.formatUnits($e>0n?$e:0n,se.decimals):fi({balance:$e,decimals:se.decimals,planForAmount:async Ct=>{const lt={...At,requestTimestampMs:Date.now(),selectedAsset:{asset:se,amount:T.formatUnits(Ct,se.decimals)}};let Je=Ct;xe?(lt.sourceSwap=await Ko({chainId:se.chainId,recipient:Ke,tokenIn:se.address,tokenOut:xe.source.address,amountIn:Ct,maxSlippage:e.maxSlippage,liquidityVenues:E?.liquidityVenues,resolveInputSwap:e.resolveInputSwap}),Je=Qt(lt.sourceSwap.amountOutMinimum,xe.source.decimals,xe.destination.decimals,"floor")):Je=Os(Ct,se.decimals,await xn(se,nt,k,w)),lt.resolvedSwap=Vt?await lt.resolveInputSwap(Je):null,lt.swapInputAmount=Je,lt.quoteAmountOut=lt.resolvedSwap?.amountOut??Je;const mt=I&&se._source==="wallet"&&se.chainId===k,ct=await Ze(void 0,{selectedAsset:lt.selectedAsset,...mt?{isFeeInclusiveInput:!0}:{},parsedAmount:Number(lt.selectedAsset.amount),sourceSwap:lt.sourceSwap,resolvedSwap:lt.resolvedSwap,isQuoting:!1,buildSupplyChainBatches:Ht=>Ws(lt,Ht)},lt);return mt&&ct?.fundingSource?.kind==="input"&&!S?{...ct,sourceSpendCap:Ct+(Ct-ct.swapInputAmount)}:ct}})},[D,I,At,b,de,Ke,nt,k,w,ce,Z,xe,Vt,Ze,e.maxSlippage,e.resolveInputSwap,e.actionProceeds,e.feeFunding,S,E?.liquidityVenues]);So({shouldRun:C&&!Pe&&Ae==="idle"&&(Ce||qe)&&!Be.isQuoting&&(!!ot||qe),deps:[C,Pe,Ae,Ce,H,Be.isQuoting,ot,qe,bt],onSkip:()=>{if(!C){vt.current=null,te(!1),ye(!1),je(null),Fe(null);return}if(Pe||Ae!=="idle"){te(!1);return}if(!Ce){Fe(null),te(!1),ye(!1),je(null);return}Be.isQuoting&&(te(!1),ye(!1))},onCleanup:()=>te(!1),delayMs:Be.needsSwap||Be.pivot?0:100,backgroundIntervalMs:5e3,run:async({isBackground:se,isCurrent:$e,signal:Ct})=>{if(qe){const Je=vt.current;if(Je?.scope===bt&&Date.now()-Je.at<3e4||kt.current?.scope===bt&&Date.now()-kt.current.at<3e4)return;kt.current?.controller.abort();const mt=new AbortController,ct=me.current?.(mt.signal).then(Ht=>{mt.signal.aborted||vn.current!==bt||!Ht?.feeEstimate||(vt.current={scope:bt,at:Date.now(),feeEstimate:Ht.feeEstimate,sourceGasSkim:Ht.sourceGasSkim})}).catch(Ht=>{mt.signal.aborted||console.debug("[SpiceSupply] fee prewarm unavailable:",Ht)})??Promise.resolve();kt.current={scope:bt,at:Date.now(),controller:mt,promise:ct},await ct;return}const lt=ot;se||(je(null),te(!0));try{if(kt.current?.scope===bt&&await kt.current.promise,Ct.aborted||!$e())return;const Je=vt.current,mt=!b&&Je?.scope===bt&&Date.now()-Je.at<3e4?Je:void 0;let ct;try{ct=await me.current?.(Ct,mt?{initialFeeEstimate:mt.feeEstimate,initialSourceGasSkim:mt.sourceGasSkim}:void 0)}catch(Ht){if(!mt||Ct.aborted||!$e())throw Ht;ct=await me.current?.(Ct)}if(!$e())return;ct&<?(ze.current={key:lt,quote:ct},ct.feeEstimate&&(vt.current={scope:bt,at:Date.now(),feeEstimate:ct.feeEstimate,sourceGasSkim:ct.sourceGasSkim}),Fe(ct.preview),ye(!0)):(ze.current=null,Fe(null),ye(!1)),je(null)}catch(Je){if(!$e())return;if(se&&ze.current?.key===lt){console.warn("[SpiceSupply] fee refresh failed:",Je);return}const mt=f.sanitizeError(Je,"Unable to calculate fees for this action.");ze.current=null,Fe(Je instanceof mi?Je.preview:null),ye(!1),je(mt)}finally{$e()&&te(!1)}}});const qn=u.useCallback(()=>Xt.current?(Xt.current=!1,hn.current?.(),yt.current=Se.current.onSuccess,$t.current={key:Zt.current.key,quote:Se.current.feeQuote},bi(Se.current)):Promise.resolve(),[]);u.useEffect(()=>{if(!Bt||wt.current===Bt)return;wt.current=Bt;const se=yt.current;it.current=!0,It(!0),an(null),Promise.resolve().then(()=>se?.(Bt)).then(()=>{mn(Bt),ae(),we()}).catch($e=>{an(`Transaction confirmed; application update needs retry: ${f.sanitizeError($e,"Unable to finalize the action")}`)}).finally(()=>{it.current=!1,It(!1)})},[Bt,Ft]);const Hn=Tt&&!Gt,Hs=u.useCallback(()=>{!Mt.current||it.current||(wt.current=null,Wt(se=>se+1))},[]),Vs=u.useCallback(()=>{Mt.current||(tt(!1),st(null),V.current=!1,ae(),we())},[ae,we]),jt=ot&&ze.current?.key===ot?ze.current.quote:null,Qs=(se=!0)=>{if(he)throw new Error(he);if(!Zt.current.enabled||Zt.current.key!==Et)throw new Error("The source, amount, beneficiary or configuration changed. Review the form before continuing.");if((D||e.feeOnlyAction)&&!jt)throw new Error("A current action plan is required. Refresh the quote before submitting.");if(de&&D?.asset.owner&&!f.addressesEqual(D.asset.owner,Z))throw new Error("Reconnect the external wallet that owns the selected asset.");if(se&&D&&(jt?.sourceSpendCap??0n)>Zt.current.sourceBalance)throw new Error("The source balance changed. Review the available amount before continuing.");if(se&&D&&!Zt.current.sourceEligible)throw new Error(rt?.reason??"This source is unavailable.")},Vn=async()=>Qs(),_o=se=>({...se,sourceSpendCap:jt?.sourceSpendCap,minimumDestinationAmount:jt?.destinationAmount}),us=D&&jt?.sourceSpendCap!==void 0?jt.sourceSpendCap>Me:Ut,er={...At,resolvedSwap:jt?.destinationSwap??At.resolvedSwap,swapInputAmount:jt?.swapInputAmount??At.swapInputAmount};let Gs=!1;Se.current={selectedAsset:D,parsedAmount:Ve,currentPaymentAmount:o,isInsufficientBalance:us,isPayMode:b,isFeeInclusiveInput:S,feeOnlyAction:e.feeOnlyAction,actionProceeds:e.actionProceeds==="output"?void 0:e.actionProceeds,validateFeeQuote:()=>Qs(!Gs),isNon7702:A,directExternalAction:de,isSourceDestToken:$,needsSwap:Vt,exactOutputSwap:Ot,selectedIsEquivalent:zn,resolvedTokenIn:nt,sourceSwap:oe,sourceExactOutputSwap:fe,pivot:xe,embeddedWalletAddress:Q,providerEmbeddedAddress:re,externalWallet:ne,externalWalletAddress:Z,activeSignerWallet:Y,activeSignerAddress:_,address:U,isConnected:O,ready:z,authenticated:q,provider:ue,resolvedChainId:k,executionTokenAddress:Nt,destinationToken:w,buildActionCalls:l,feeExecutionMode:c,feeToleranceBps:R,buildSpicenetBatch:d,onPayExecute:p,onSuccess:x,feeQuote:jt,execution:{estimate:(se,$e,Ct,lt)=>G(se,$e,Ct,{...lt,userOverride:Ke}),execute:async(se,$e,Ct,lt,Je,mt)=>{const ct=async()=>Qs(!Gs);if(await Vn(),de){if(!jt?.actionDefinition)throw new Error("The direct action plan is unavailable.");return tu({definition:jt.actionDefinition,account:Z,chainId:w.chainId,wallet:ne,assertCurrent:Vn})}return ce&&D&&(_e("Transfer the selected source to your embedded wallet"),await Ci({asset:D.asset,embedded:Ke,external:Z,externalWallet:ne,amount:jt?.sourceSpendCap??0n,assertCurrent:Vn}),Gs=!0,await ct()),le(se,$e,Ct,lt,Je,{...mt,userOverride:Ke,requireDestinationReceipt:!0,walletFundingRequirement:D?.asset._source==="wallet"&&jt?.sourceSpendCap!==void 0?{chainId:D.asset.chainId,token:D.asset.address,amount:jt.sourceSpendCap}:void 0,validateBeforeSubmit:async Ht=>{await ct(),await mt?.validateBeforeSubmit?.(Ht)}})},buildPayChainBatches:se=>Us(er,_o(se)),buildSupplyChainBatches:se=>Ws(er,_o(se)),onProgress:qt},ui:{setError:at,setStep:Qe,setStatusMsg:_e,setTxHash:et,setIsExecuting:Xe,setShowStatusPanel:tt,setPaymentResult:st},refs:{spiceDepositSubmittedRef:V,abortControllerRef:Le}};const Tn=!!e.isZeroAmountPay&&!e.feeOnlyAction&&b&&Ve===0,Vi=b?(Tn||!!D?.asset||!!e.actionProceeds||!!e.feeOnlyAction)&&Ve>=0&&!us&&!Pe&&(Tn||H||De)&&!ie&&(Tn||e.feeOnlyAction||!Vt||!!Ot)&&(Tn||e.feeOnlyAction||!xe||!!fe)&&!ge:!!D?.asset&&Ve>0&&!us&&!Pe&&(de||De)&&!ie&&!Oe&&(xe?!!oe&&!Lt&&(ln||!!Te):ft||ln||!!Te&&!Lt)&&!ge,tr=!he&&!!Ke&&(!de||!!ne&&(!D?.asset.owner||f.addressesEqual(D.asset.owner,Z)))&&(j==="7702"||!!Z)&&!Tt&&!Yt&&!Gt&&C&&Vi&&(Tn||!D&&(!!e.actionProceeds||!!e.feeOnlyAction)||!!rt?.eligible)&&Ae!=="success"&&Ee?.status!=="success"&&!Dt.quoteError&&(Tn||!!ot&&ze.current?.key===ot);Xt.current=tr;const Ys=u.useCallback(()=>{Mt.current||(Xt.current=!1,ze.current=null,ye(!1),Kt.refreshQuote(),Qe("idle"),at(null),_e(""),st(null),tt(!1))},[Kt.refreshQuote,at]),nr=u.useRef(Et);u.useEffect(()=>{const se=nr.current!==Et;nr.current=Et,(se||f.isUserRejection(Ue))&&Ae==="error"&&!Pe&&$t.current&&$t.current.key!==Et&&Ys()},[Et,Ae,Pe,Ue,Ys]);const Qi=u.useCallback(()=>{tt(!1)},[]),Gi=u.useCallback(()=>{Mt.current||(Qe("idle"),et(null),ae())},[ae]),xt=jt??(ze.current?.key.startsWith(`${Et}|`)?ze.current.quote:null)??($t.current?.key===Et?$t.current.quote:null),Yi=async se=>{if(de)throw new Error("This source executes directly from the external wallet; submit the action without embedded funding.");if(!(!ce||!D)){if(!jt||se!==jt.sourceSpendCap)throw new Error("Use the displayed source funding maximum before preparing this action.");await Vn(),await Ci({asset:D.asset,embedded:Ke,external:Z,externalWallet:ne,amount:se,assertCurrent:Vn})}};return{selectedAsset:dt,capability:rt,assets:{selectable:J,displayAssets:J,filteredSpiceAssets:K,embeddedWalletAddress:Q,externalAddress:Z,isNon7702:j!=="7702",refreshSpiceAssets:ae,refreshWalletAssets:we,loading:ke,refreshing:Ie,error:be},quote:{...Dt,...qe?{quoteKey:null,quoteExpiresAt:null,quoteError:null,isQuoting:!1,estimatedInput:null,estimatedOutput:null,quoteAmountOut:null,inputAmount:null,resolvedSwap:null,sourceSwap:null,exactOutputSwap:null,sourceExactOutputSwap:null}:{},hasSourceConversion:!!xe,executionInput:xe&&xt?{address:xe.destination.address,chainId:xe.destination.chainId,decimals:xe.destination.decimals,amount:xt.preview.netAmount}:null,...xt?.destinationSwap?{resolvedSwap:xt.destinationSwap,inputAmount:xt.swapInputAmount,estimatedOutput:T.formatUnits(xt.destinationSwap.amountOut,w.decimals)}:{},...xt?.fundedFeeToken&&xt.destinationAmount!==void 0?{estimatedOutput:T.formatUnits(xt.destinationAmount+(xt.destinationSwap?xt.destinationSwap.amountOut-xt.destinationSwap.amountOutMinimum:0n),w.decimals)}:{}},fees:{fundingConversion:xt?.fundingConversion,fundingSource:xt?.fundingSource,proceedsUsed:xt?.proceedsUsed,fundingShortfall:xt?.grossFundingAmount,source:xe&&xt?{address:xe.source.address,chainId:xe.source.chainId,symbol:xe.source.symbol,decimals:xe.source.decimals,gasFee:xt.sourceGasSkim??0n,spicenetFee:0n}:null,destinationAmount:xt?.destinationAmount,sourceSpendCap:xt?.sourceSpendCap,preview:qe?null:xt?.preview??gt,isLoading:!qe&&ee,ready:!qe&&!!jt,error:qe?null:ie},amount:{sourceRequiredAmount:xt?.sourceSpendCap??null,parsed:Ve,isInsufficientBalance:us,sourceBalance:Pt,feesExceedAmount:Oe},status:{finalizing:Yt||Hn,finalizationError:Gt,step:Tt&&Ae==="success"?"executing":Ae,statusMsg:Tt?Gt??"Transaction confirmed. Updating application...":Re,txHash:He,isExecuting:Pe||Hn,error:he||Gt||Ue||rt?.reason||null,showStatusPanel:ut,paymentResult:Tt&&Ee?.status==="success"?{...Ee,status:"processing"}:Ee},flags:{directExecutionFeeNote:H},retryFinalization:Hs,fundEmbeddedSource:Yi,canExecute:tr,submit:b?qn:Fn,submitSupply:Fn,submitPay:qn,retrySupply:Ys,dismissPaymentStatus:Qi,resolveMaxAmount:gn,max:()=>D?gn(D.asset):Promise.resolve(null),resetAfterSuccess:Gi,resetPaymentState:Vs}}function iu(e){const{asset:t,amount:n,recipient:s,owner:o,onSuccess:r}=e,i=t?.chainId??e.sourceChains?.[0]??0,l=u.useMemo(()=>v.getTokensForChain(i).find(w=>w.equivalenceGroup==="USDC"),[i]),c=u.useCallback((w,C)=>{if(!t||n<=0n||n>t.balance||!s||!o||f.addressesEqual(o,s))throw new Error("Enter a valid withdrawal amount and recipient.");if(C.chainId!==t.chainId||!f.addressesEqual(C.executorAddress??C.userAddress,o))throw new Error("The withdrawal wallet or network changed. Review the withdrawal again.");return Ka(t.chainId,t.address,[{recipient:s,amount:n}]).calls},[t?.address,t?.chainId,t?.balance,n,s,o]),d=u.useMemo(()=>t?{asset:t,amount:n}:void 0,[t,n]),p=u.useMemo(()=>t?[{address:t.address,chainId:t.chainId,symbol:t.symbol,decimals:t.decimals,logoURI:t.logoURI}]:void 0,[t?.address,t?.chainId,t?.symbol,t?.decimals,t?.logoURI]),m=cs({enabled:e.enabled&&!!l&&!!t&&n>0n&&!!s&&!!o&&!f.addressesEqual(o,s),feeOnlyAction:!0,isZeroAmountPay:!0,amountDirection:"output",paymentAmount:"0",destinationToken:{address:l?.address??v.ZERO_ADDRESS,symbol:l?.symbol??"USDC",decimals:l?.decimals??6,chainId:i},recipient:s,selectedAsset:null,feeFundingReserve:d,additionalSourceTokens:p,sourceChains:e.sourceChains,includeCrossChainEmbeddedAssets:!0,includeExternalWalletAssets:!1,feeExecutionMode:"backend-transfer",buildActionCalls:c,buildSpicenetBatch:Ns,onError:(w,C)=>e.onError?.(w.message,C),onSuccess:async()=>{t&&(window.dispatchEvent(new CustomEvent("withdraw-completed")),await r?.({token:t.symbol,amount:T.formatUnits(n,t.decimals),chainId:i}))}}),h=`${e.enabled}:${t?.chainId}:${t?.address}:${n}:${s}`,x=u.useRef(h);u.useEffect(()=>{x.current===h||m.status.isExecuting||(x.current=h,(m.status.step==="success"||m.status.paymentResult?.status==="success")&&m.resetAfterSuccess())},[h,m.status.isExecuting,m.status.step,m.status.paymentResult?.status,m.resetAfterSuccess]);const g=m.fees.fundingSource?.asset,y=g?g._source==="wallet"?m.fees.fundingConversion?.amountInMax??m.fees.proceedsUsed:m.amount.sourceRequiredAmount:null;return{supply:m,source:g,maximumFeeFunding:y}}const Ti=f.font.ui,lu=({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:Ti,fontSize:"17px",fontWeight:500,color:r,lineHeight:"24px"},children:e}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",fontFamily:Ti,fontSize:"13px",fontWeight:500,color:i,lineHeight:"16px"},children:["Balance:"," ",t?"...":n===null?"\u2014":f.formatBalance(n)]})]})},ji=({isOpen:e,position:t,title:n,items:s,selectedId:o,onSelect:r,portalAttribute:i})=>{const{dark:l,dk:c,primaryColor:d}=f.useSpiceBrand(),[p,m]=u.useState(null),[h,x]=u.useState(!1);return u.useEffect(()=>{if(!e){x(!1);return}const g=requestAnimationFrame(()=>{requestAnimationFrame(()=>x(!0))});return()=>cancelAnimationFrame(g)},[e]),!e||!t||s.length===0?null:jn.createPortal(a.jsxs("div",{[`data-${i}-popover`]:"true",style:{position:"fixed",top:`${t.top}px`,left:`${t.left}px`,opacity:h?1:0,transform:h?"scale(1) translateY(0)":"scale(0.96) translateY(-6px)",transition:`opacity 200ms ${f.easing.out}, transform 200ms ${f.easing.out}`,backgroundColor:l?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:f.z.dropdown,fontFamily:f.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(g=>{const y=o===g.id,w=p===g.id;return a.jsxs("button",{onClick:C=>{C.stopPropagation(),r(g.id)},onMouseEnter:()=>m(g.id),onMouseLeave:()=>m(null),style:{display:"flex",alignItems:"center",gap:"8px",padding:"6px 4px",borderRadius:"8px",border:"none",cursor:"pointer",backgroundColor:y?l?c.hoverBg:"#f3f4f6":w?l?c.cardBg:"#f9fafb":"transparent",transition:"background-color 0.15s",width:"100%",fontFamily:f.font.mono},children:[g.icon&&a.jsx("img",{src:g.icon,alt:g.label,style:{width:"22px",height:"22px",borderRadius:"50%"}}),a.jsx("span",{style:{fontSize:"13px",fontWeight:y?700:500,textTransform:"uppercase",color:l?c.textPrimary:"#0e0d0b",letterSpacing:"0.5px",flex:1,textAlign:"left"},children:g.label}),g.detail&&a.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:c.textSecondary},children:g.detail}),y&&a.jsx(Ca,{color:d,style:{flexShrink:0}})]},g.id)})})]}),document.body)},zs=f.font.ui,cu=f.font.mono,du=170,uu=({header:e,amount:t,receiveAmountDisplay:n,receiveUsdEstimate:s,selectedDestToken:o,destTokenSymbol:r,destChainName:i,destChainLogo:l,compatibleDestinationChains:c,networkSwitchRef:d,onOpenNetworkPopover:p,showNetworkPopover:m,setShowNetworkPopover:h,networkPopoverPos:x,selectedChainId:g,setSelectedChainId:y,dark:w,dk:C})=>{const b=w?C.cardBg:"#E9E9E9",S=w?C.cardBorder:"#C6C6C6",I=w?C.textSecondary:"#71757A",F=w?C.textPrimary:"#0E0D0B",k=w?C.cardBorder:"#C5C5C4",E=w?"rgba(255,255,255,0.08)":"#D4D3D3",R=r.length>8?"14px":r.length>6?"16px":"18px";return a.jsxs("div",{style:{backgroundColor:b,border:`1px solid ${S}`,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(Sn,{element:"div",value:n,title:n,fontFamily:zs,color:t?F:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,overflow:"wrap"}),a.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:I,fontFamily:zs,marginTop:"10px"},children:s})]}),a.jsxs("div",{style:{width:`${du}px`,flexShrink:0,display:"flex",flexDirection:"column",alignItems:"stretch",gap:"8px"},children:[a.jsxs("div",{style:{backgroundColor:"transparent",border:`1px solid ${k}`,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||ql,alt:r,style:{width:"24px",height:"24px",borderRadius:"50%"}}),a.jsx("span",{style:{fontSize:R,fontWeight:500,color:F,lineHeight:"1.3",fontFamily:zs,flex:1,minWidth:0,letterSpacing:0},children:r})]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:E,borderTop:`1px solid ${k}`},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:F,fontFamily:zs,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:i})]}),a.jsx("button",{ref:d,onClick:j=>{j.stopPropagation(),p(d.current)},style:{background:"none",border:"none",cursor:c.length>1?"pointer":"not-allowed",padding:"0 0 0 8px",fontSize:"9.5px",fontFamily:cu,color:I,textDecoration:"underline",fontWeight:600,opacity:c.length>1?1:.45},children:"Switch"}),a.jsx(ji,{isOpen:m,position:x,title:"SELECT NETWORK",portalAttribute:"network",items:c.map(j=>{const A=f.getChainConfig(j);return{id:String(j),label:A?.displayName||String(j),icon:yn[j]||Xn}}),selectedId:g!==null?String(g):null,onSelect:j=>{y(Number(j)),h(!1)}})]})]}),a.jsx("div",{style:{minHeight:"14px"}})]})]})]})},pu=f.font.ui,Cn=f.font.mono,fu=({show:e,onToggle:t,showCustomAddress:n,setShowCustomAddress:s,customRecipient:o,setCustomRecipient:r,externalAddress:i,recipientAddress:l,destChainName:c,destChainLogo:d,compatibleDestinationChains:p,txDetailsChainSwitchRef:m,onOpenNetworkPopover:h,sourceChainLabel:x,sourceDetailsLogo:g,sourceTokenLabel:y,amount:w,totalSourceDebitDisplay:C,receiveAmountDisplay:b,destTokenSymbol:S,shouldQuoteWithdrawGas:I,estimatingFee:F,feeError:k,displayedGasFee:E,selectedDestToken:R,theme:j,styles:A,dark:M,dk:P})=>{const N=M?P.textSecondary:"#71757A",B=M?P.textPrimary:"#0E0D0B",U=p.length>1,O=n&&o?T.isAddress(o)?f.truncateAddress(o):o:l?f.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:N,fontFamily:pu,fontWeight:600},children:"Transaction Details"}),a.jsx(Gc,{size:12,color:N,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:N,fontFamily:Cn,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:B,fontFamily:Cn,fontWeight:500},children:O}),a.jsx("button",{onClick:()=>{s(z=>!z),!n&&i&&r(i)},style:{background:"none",border:"none",cursor:"pointer",padding:"0",fontSize:"9.5px",fontFamily:Cn,color:N,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:Cn,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&&!T.isAddress(o)?!0:void 0,"data-spiceflow-focus":!0,value:o,onChange:z=>r(z.target.value),placeholder:"0x...",style:{width:"100%",padding:"8px 10px",borderRadius:"6px",border:`1px solid ${o&&!T.isAddress(o)?M?P.errorBorder:"#fca5a5":M?P.inputBorder:"#d1d5db"}`,backgroundColor:M?P.inputBg:"#f9fafb",color:M?P.inputText:"#111827",fontSize:"12px",fontFamily:Cn,outline:"none",boxSizing:"border-box"}}),o&&!T.isAddress(o)&&a.jsx("span",{style:{fontSize:"11px",color:P.errorText,marginTop:"3px",display:"block"},children:"Invalid address"})]})]}),a.jsx(bn,{palette:P,labelColor:N,valueColor:B,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:B,fontWeight:500,fontFamily:Cn,textTransform:"uppercase"},children:c}),a.jsx("button",{ref:m,onClick:z=>{z.stopPropagation(),h(m.current)},style:{background:"none",border:"none",cursor:U?"pointer":"not-allowed",padding:"0",fontSize:"9.5px",fontFamily:Cn,color:N,textDecoration:"underline",fontWeight:600,opacity:U?1:.45},children:"Switch"})]})}),a.jsx(bn,{palette:P,labelColor:N,valueColor:B,label:"REQUESTED WITHDRAWAL",value:a.jsxs(Zo,{logo:g||null,alt:x,primaryText:B,children:[w||"0"," ",y]})}),I&&a.jsx(bn,{palette:P,labelColor:N,valueColor:B,label:"TOTAL SOURCE DEBIT",value:a.jsxs(Zo,{logo:g||null,alt:x,primaryText:B,children:[C," ",y]})}),a.jsx(bn,{palette:P,labelColor:N,valueColor:B,label:"YOU RECEIVE",value:a.jsxs(Zo,{logo:d,alt:c,primaryText:B,gap:"4px",children:[b," ",S]})}),I&&a.jsxs(a.Fragment,{children:[a.jsx(bn,{palette:P,labelColor:N,label:"EST. NETWORK FEE",valueColor:k?"#f87171":B,value:F?"Estimating...":k?"Unavailable":E!==null&&R?`${Wo(E,R.decimals)} ${R.symbol}`:"Estimating..."}),k&&a.jsx(rn,{variant:"error",size:"compact",palette:P,fontFamily:A?.fontFamily||j.typography.fontFamily,children:k})]})]})]})},mu=u.memo(fu),Zo=({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:Cn},children:o})]}),ds=f.font.ui,hu=170,gu=({header:e,amount:t,setAmount:n,isInsufficient:s,sourceAmountDecimals:o,selectedSourceAsset:r,resolvedSelectedSourceAsset:i,spiceAssets:l,setSelectedSourceAsset:c,sourceUsdEstimate:d,sourceTokenLabel:p,sourceChainLabel:m,totalSelectedBalance:h,showSourceTokenPopover:x,setShowSourceTokenPopover:g,tokenPopoverPos:y,setTokenPopoverPos:w,tokenTriggerRef:C,primaryColor:b,dark:S,dk:I})=>{const F=f.useAssetDisplay(),k=i?F({...i,logoURI:Zn}).logoURI:Zn,E=S?I.cardBg:"#E9E9E9",R=S?I.cardBorder:"#C6C6C6",j=S?I.textSecondary:"#71757A",A=S?I.textPrimary:"#0E0D0B",M=S?I.cardBorder:"#C5C5C4",P=S?"rgba(255,255,255,0.08)":"#D4D3D3",N=p.length>8?"14px":p.length>6?"16px":"18px";return a.jsxs("div",{style:{backgroundColor:E,border:`1px solid ${R}`,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(Sn,{element:"input",ariaLabel:"Withdraw amount",ariaInvalid:s,dataSpiceflowFocus:!0,value:t,onChange:B=>{const U=B.target.value;if(U===""){n("");return}/^\d*\.?\d*$/.test(U)&&n(f.parseNumericInput(U.startsWith(".")?`0${U}`:U,o??r?.decimals))},placeholder:"0.0",fontFamily:ds,color:s?"#ef4444":t?A:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,style:{width:"100%"}}),a.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:j,fontFamily:ds,marginTop:"10px"},children:d})]}),a.jsx("div",{style:{width:`${hu}px`,flexShrink:0},children:a.jsxs("div",{style:{backgroundColor:"transparent",border:`1px solid ${M}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[a.jsxs("div",{ref:C,onClick:B=>{if(B.stopPropagation(),!x&&C.current){const U=C.current.getBoundingClientRect(),O=220,z=16;w({top:U.bottom+8,left:Math.min(Math.max(z,U.right-O),window.innerWidth-O-z)})}g(U=>!U)},style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px",cursor:"pointer"},children:[k&&a.jsx("img",{src:k,alt:p,style:{width:"24px",height:"24px",borderRadius:"50%"}}),a.jsx("span",{style:{fontSize:N,fontWeight:500,color:A,lineHeight:"1.3",fontFamily:ds,flex:1,minWidth:0,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",letterSpacing:0},children:p}),a.jsx(Mn,{size:15,color:A,strokeWidth:2.25})]}),a.jsx(ji,{isOpen:x,position:y,title:"SELECT TOKEN",portalAttribute:"token",items:(l||[]).map(B=>({id:B.receiptTokenId||B.address,label:F({...B,displaySymbol:B.displaySymbol||B.receiptTokenName}).symbol,icon:F({...B,logoURI:Zn}).logoURI||void 0,detail:f.formatBalance(B.balanceFormatted)})),selectedId:i?.receiptTokenId||i?.address||null,onSelect:B=>{const U=(l||[]).find(O=>(O.receiptTokenId||O.address)===B);U&&(c(U),n("")),g(!1)}}),a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:P,borderTop:`1px solid ${M}`},children:a.jsx("span",{style:{fontSize:"11px",fontWeight:400,color:A,fontFamily:ds,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:m})})]})})]}),a.jsxs("div",{style:{minHeight:"18px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[s?a.jsx("span",{style:{fontSize:"12px",color:I.errorText,fontFamily:ds,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((B,U)=>{const O=U===4,z=parseFloat(t)||0,q=h>0&&Math.abs(z/h*100-B)<1;return a.jsx("button",{type:"button","aria-label":`Set amount to ${B}%`,"aria-pressed":q,onClick:()=>{const ue=h*B/100,le=r?.decimals??6,G=Math.floor(ue*10**le)/10**le;n(B===0?"":G>0?f.formatDecimalInput(G,le):"")},title:`${B}%`,disabled:h===0,"data-spiceflow-focus":!0,style:{width:"32px",height:"32px",padding:"9px",border:"none",backgroundColor:"transparent",cursor:h===0?"not-allowed":"pointer",opacity:q?1:.5,transition:"opacity 0.15s ease",display:"flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box"},children:a.jsx(Oo,{pct:B,isMax:O,primaryColor:b,dark:S,fillColor:S?I.textSecondary:"#3C3E42"})},B)})})]})]})},xu=({dark:e,dk:t})=>a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[a.jsx("img",{src:ko,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:f.font.ui},children:"Withdraw collateral from your account to 10+ EVM blockchains."})]}),yu=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,styles:s,onWithdrawExecute:o,onWithdrawSuccess:r,onWithdrawError:i,availableTokens:l,initialSourceAssetId:c,walletAssets:d,buildSpicenetBatch:p=Ns})=>{const m=u.useContext(f.SpiceFlowProviderContext);if(!m)return a.jsx("div",{children:"Error: SpiceWithdraw must be used within SpiceFlowProvider"});const h=m.mode||"7702",x=h==="presign"||h==="ondemand",g=m.supportedChainIds,y=m.allowedTokens,w=!!d,C=d?.initialAsset,b=u.useMemo(()=>[...d?.extraAssets??[],...C?[C]:[]].map(oe=>({address:oe.address,chainId:oe.chainId,symbol:oe.symbol,decimals:oe.decimals})),[d?.extraAssets,C]),S=m.isWhitelistGateActive,{theme:I,dark:F,dk:k}=f.useSpiceBrand(s),E=f.useAssetDisplay(),R=m.network,j=()=>x?"select":"provider-login",[A,M]=u.useState(j()),[P,N]=u.useState(!1),[B,U]=u.useState(null),[O,z]=u.useState(null),[q,ue]=u.useState(""),[le,G]=u.useState(!1),[ne,re]=u.useState(!1),[Y,_]=u.useState(!1),[Z,pe]=u.useState(""),[D,L]=u.useState(!0),$=u.useRef(null),de=u.useRef(null),ce=u.useRef(null),[he,X]=u.useState(null),[K,W]=u.useState(null),Q=f.useWallet(),{isReady:ae,isAuthenticated:we,address:ke}=Q,Ie=m?.embeddedWalletAddress,{address:be,chainId:J}=sn.useAccount(),Ye=m.externalWalletAddress||be,[Ne,dt]=u.useState(!1),[rt,Me]=u.useState(null),Pe=u.useRef(i);Pe.current=i;const Xe=u.useCallback(oe=>{Me(oe),typeof oe=="string"&&oe&&Pe.current?.(oe,f.getRelayerErrorDetail(oe))},[]),[Ue,ht]=u.useState(null),We=u.useRef(null),at=u.useRef(!0),Ae=u.useRef(null);u.useEffect(()=>(at.current=!0,()=>{at.current=!1}),[]);const{execute:Qe,estimate:Re}=Fs(),[_e,He]=u.useState(null),[et,ut]=u.useState(null),[tt,Ee]=u.useState(!1),[st,gt]=u.useState(null),{assets:Fe,loading:ee,error:te,refresh:De}=Nn({owner:Ie,role:"holding",includeWalletAssets:w,additionalSourceTokens:b,enabled:e&&!!Ie}),ye=u.useMemo(()=>{if(S)return[];const oe=(fe,xe)=>(xe.balanceUsd||0)-(fe.balanceUsd||0);return(Fe??[]).filter(fe=>fe.balance>0n&&kn(fe,"holding",{allowedTokens:y,isWhitelistGateActive:S}).eligible).sort(oe)},[Fe,y,S]),ie=u.useMemo(()=>[...new Set([...g??[],...Object.keys(l??{}).map(Number),...(ye||[]).map(oe=>oe.chainId),...(ye||[]).flatMap(oe=>Object.keys(oe.chainTokens??{}).map(fe=>{const[,xe]=fe.split(":"),Ve=Number(xe);return Number.isFinite(Ve)?Ve:null}).filter(fe=>fe!==null))])].filter(oe=>f.getChainConfig(oe)?.network===R),[g,l,ye,R]),je=u.useMemo(()=>{if(l)return l;const oe={};for(const fe of ye||[]){const xe=Object.entries(fe.chainTokens??{});if(xe.length>0){for(const[Ve,St]of xe){const[ft,Pt,Ut]=Ve.split(":");if(ft!=="evm"||!Pt||!Ut)continue;const qt=Number(Pt);if(!Number.isFinite(qt))continue;const At=Ut.startsWith("0x")?Ut.toLowerCase():`0x${Ut.toLowerCase()}`,Nt=f.getChainConfig(qt)?.supportedTokens?.find(bt=>f.addressesEqual(bt.address,At));Nt&&uo(fe,At,qt)&&(oe[qt]||(oe[qt]=[]),oe[qt].find(bt=>f.addressesEqual(bt.address,At))||oe[qt].push({address:At,symbol:Nt?.symbol||St?.name||fe.symbol,name:Nt?.name||St?.name||fe.displayName||fe.name||fe.symbol,decimals:Nt?.decimals??St?.decimals??fe.decimals,logoURI:Nt?.logo||fe.logoURI}))}continue}oe[fe.chainId]||(oe[fe.chainId]=[]),oe[fe.chainId].find(Ve=>f.addressesEqual(Ve.address,fe.address))||oe[fe.chainId].push({address:fe.address,symbol:fe.symbol,name:fe.displayName||fe.name||fe.symbol,decimals:fe.decimals,logoURI:fe.logoURI})}return oe},[l,ye]),ve=u.useCallback((oe,fe)=>{const xe=bd(oe,fe,fe?je[fe]??[]:[]);return!oe||!xe||!fe||oe._source==="wallet"&&fe!==oe.chainId?null:kn(oe,"withdraw-destination",m,{...xe,chainId:fe}).eligible?xe:null},[je,m.allowedTokens,m.rpcOverrides,m.isWhitelistGateActive]),V=u.useMemo(()=>B?ye.find(oe=>Ge(oe)===Ge(B))??null:null,[B,ye]),Le=V?V.balanceError:te,me=V?._source==="wallet",ze=u.useMemo(()=>{if(!V)return[];const oe=Object.keys(V.chainTokens??{}).map(fe=>dn(fe)?.chainId??null).filter(fe=>fe!==null);return Array.from(new Set([...oe,V.chainId,...ie].filter(Number.isFinite))).filter(fe=>f.getChainConfig(fe)?.network===R&&ve(V,fe)!==null)},[V,ie,ve,R]),vt=u.useMemo(()=>{if(!V||typeof window>"u")return null;const oe=`spiceflow:withdraw-chain:${V.receiptTokenId||V.address.toLowerCase()}`,fe=window.localStorage.getItem(oe),xe=fe?Number(fe):null;return xe!==null&&Number.isFinite(xe)&&ze.includes(xe)?xe:null},[V,ze]),kt=u.useMemo(()=>V?vt!==null?vt:J&&ze.includes(J)?J:V.chainId&&ze.includes(V.chainId)?V.chainId:ze[0]??null:ie[0]??null,[V,vt,J,ze,ie]),Se=u.useMemo(()=>ve(V,O),[ve,V,O]);u.useEffect(()=>{e&&(U(null),ue(""))},[e,c,C?.address,C?.chainId]),u.useEffect(()=>{if(!e||!ye.length||B)return;const oe=C?ye.find(fe=>fe.chainId===C.chainId&&f.addressesEqual(fe.address,C.address)&&fe._source==="wallet"):c?ye.find(fe=>fe.receiptTokenId===c):ye[0];U(oe??null),ue("")},[e,ye,B,c,C]),u.useEffect(()=>{V&&(O===null||!ze.includes(O))&&z(kt)},[V,O,kt,ze]),u.useEffect(()=>{if(!le&&!ne)return;const oe=fe=>{const xe=fe.target;le&&!$.current?.contains(xe)&&!de.current?.contains(xe)&&!xe?.closest?.("[data-network-popover]")&&G(!1),ne&&!ce.current?.contains(xe)&&!xe?.closest?.("[data-token-popover]")&&re(!1)};return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[le,ne]);const yt=u.useCallback(oe=>{if(!oe||ze.length<=1)return;const fe=oe.getBoundingClientRect(),xe=220,Ve=16;X({top:fe.bottom+8,left:Math.min(Math.max(Ve,fe.right-xe),window.innerWidth-xe-Ve)}),G(St=>!St)},[ze.length]),wt=u.useCallback(()=>L(oe=>!oe),[]);u.useEffect(()=>{if(!V||O===null||typeof window>"u")return;const oe=`spiceflow:withdraw-chain:${V.receiptTokenId||V.address.toLowerCase()}`;window.localStorage.setItem(oe,String(O))},[V,O]);const it=Y?T.isAddress(Z)?Z:void 0:Ye||(me?void 0:Ie),nn=Nn({owner:it,role:"holding",includeRollupAssets:!1,sourceChains:O?[O]:[],additionalSourceTokens:Se&&O?[{...Se,chainId:O}]:[],enabled:e&&!!it&&!!Se&&!!O}),mn=nn.walletAssets.find(oe=>f.addressesEqual(oe.owner,it)&&oe.chainId===O&&f.addressesEqual(oe.address,Se?.address)),Gt=V?.balanceFormatted??0,an=V?E({...V,displaySymbol:V.displaySymbol||V.receiptTokenName}).symbol:"Select token",Yt=V?.displayChainName||(me?f.getChainConfig(V.chainId)?.displayName:"Spicenet")||"Network",It=V?.receiptTokenDecimals??V?.decimals,Ft=u.useMemo(()=>{if(!Se||It===void 0)return 0n;try{return zt(q||"0",It)}catch{return 0n}},[q,Se,It]),Wt=u.useMemo(()=>!Se||It===void 0?0n:Fd(Ft,It,Se.decimals),[Se,It,Ft]),Bt=et??_e,Tt=u.useMemo(()=>{const oe=me?0n:Bt??0n;return Wt>oe?Wt-oe:0n},[me,Bt,Wt]),Mt=Ft,Ke=iu({enabled:e&&me,asset:me?V:null,amount:Ft,recipient:it,owner:Ie,sourceChains:g,onSuccess:r,onError:i}),qe=Ke.supply,Rt=Ne||me&&(qe.status.isExecuting||qe.status.finalizing),Kt=qe.status.step==="success"||qe.status.paymentResult?.status==="success",Dt=u.useCallback(oe=>{if(me||!O||!Se)return[];if(Ft===0n||Wt===0n||!it)return[];const fe=Array.isArray(oe)?oe.filter(ft=>ft.amount>0n):[{token:Se.address,recipient:it,amount:oe??Wt}],xe=fe.reduce((ft,Pt)=>ft+Pt.amount,0n);if(xe<=0n)return[];const Ve={chainId:O,calls:[],tokenTransfers:fe.map(ft=>({from:"escrow",to:ft.recipient,token:ft.token,amount:ft.amount}))},St=p({destinationChainId:O,deliveryToken:Se.address,deliveryAmount:xe,deliveryRecipient:it,deliveryTransfers:fe,requestTimestampMs:Ae.current??Date.now()});return St?[St,Ve]:[Ve]},[me,O,Se,Ft,Wt,it,p]),Be=u.useMemo(()=>Dt(),[Dt]),Lt=u.useMemo(()=>Td(Be,Se?.address),[Be,Se?.address]),Te=u.useRef(null),Ot=!me&&e&&!x&&!Ne&&!!Se&&!!O&&Ft!==0n;So({shouldRun:Ot&&Be.length>0&&!!Lt,deps:[Ot,Be.length>0,Lt],delayMs:500,onSkip:()=>{Te.current=null,He(null),gt(null),Ee(Ot&&Be.length===0)},onCleanup:()=>Ee(!1),run:async({isCurrent:oe,signal:fe})=>{const xe=Lt;Ee(!0),gt(null);try{const Ve=await Ed({batches:Be,tokenAddress:Se.address,chainId:O,estimate:Re,signal:fe});if(!oe())return;Te.current={key:xe,quote:Ve},He(Ve.gasFee)}catch(Ve){if(!oe())return;Te.current=null,He(null),gt(Ve instanceof Error?Ve.message:"Failed to estimate gas fee")}finally{oe()&&Ee(!1)}}}),u.useEffect(()=>{Ne||ut(null)},[Ne,q,O,Se?.address]);const pt=u.useCallback(()=>{N(!0),M("select")},[]),nt=u.useCallback(()=>{Rt||t()},[t,Rt]),ln=u.useRef(null);ln.current={batches:Be,walletAddress:ke,recipient:it,token:Se,chainId:O,amount:q,grossAmountRaw:Wt,gasFee:_e,feeEstimate:Lt&&Te.current?.key===Lt?Te.current.quote.feeEstimate:null,isNon7702:x,buildWithdrawBatches:Dt,execution:{estimate:Re,execute:Qe},ui:{setIsExecuting:dt,setExecutionError:Xe,setExecutionProgress:ht,setLockedGasFee:ut},executionContextRef:We,isMountedRef:at,onWithdrawExecute:o,onWithdrawSuccess:r,buildSpicenetBatch:p};const Vt=u.useCallback(()=>(Ae.current=Date.now(),Qa(ln.current)),[]),zn=u.useCallback(()=>(Ae.current=Date.now(),Ad(ln.current)),[]);if(u.useEffect(()=>{if(!e){const oe=setTimeout(()=>{M(j()),N(!1),U(null),z(null),ue(""),G(!1),re(!1),_(!1),pe(""),dt(!1),Xe(null),ht(null),We.current=null},300);return()=>clearTimeout(oe)}},[e,x]),u.useEffect(()=>{if(!x&&e&&A==="provider-login"&&ae&&we&&Ie&&!P){const oe=setTimeout(()=>{N(!0),M("select")},100);return()=>clearTimeout(oe)}},[x,e,A,ae,we,Ie,P]),!e)return null;if(A==="provider-login"&&!x)return a.jsx(Po,{onAuthSuccess:pt,autoTrigger:!0});if(A==="select"){const oe=parseFloat(q)||0,fe=It?Wo(Mt,It):q||"0",xe=!!V&&Mt>V.balance,Ve=(O?f.getChainConfig(O):null)?.displayName||"Network",St=O?yn[O]||Xn:null,ft=Se?.symbol||"\u2014",Pt=an,Ut=Se?Wo(Tt,Se.decimals):"0",qt=V&&V.balanceFormatted>0?V.balanceUsd/V.balanceFormatted:void 0,At=V?.priceStatus==="stale",Nt=Ya(oe,qt,At),bt=Ya(parseFloat(Ut)||0,qt,At),vn=(!Y||T.isAddress(Z))&&(!me||!f.addressesEqual(it,Ie)),Et=!x&&!me&&oe>0&&Se!==null,Zt=!Et||_e!==null&&!tt&&!st,$t=oe>0&&!xe&&!ee&&!Le&&V!==null&&O!==null&&Se!==null&&it&&vn&&Zt&&Tt>0n&&(!me||qe.canExecute&&!Kt),Xt=!$t,hn=ee?"LOADING BALANCES":Le?"BALANCES UNAVAILABLE":V===null?"NO BALANCE":oe===0?"ENTER AMOUNT":xe?"INSUFFICIENT BALANCE":Et&&!Zt?st?"GAS UNAVAILABLE":"ESTIMATING GAS":Et&&Tt===0n?"AMOUNT TOO SMALL":me&&!qe.canExecute?"REVIEW FEES":"WITHDRAW",Fn=!!Ue&&(Ue.step==="success"||Ue.step==="error"),H=s?.primaryColor||I.colors.primary,ge=402,Oe=(Ce,ot,Ze)=>a.jsx(lu,{label:Ce,loading:Ze,balance:ot,dark:F,dk:k});return a.jsx(tn,{isOpen:!0,onClose:nt,title:"Withdraw",subtitle:a.jsx(xu,{dark:F,dk:k}),styles:s,theme:I,dark:F,maxWidth:"486px",footerLinkText:"Spicenet accounts \u2192",overlayDimmed:!1,closeOnBackdropClick:n,overlayContent:Fn?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(Uo,{type:"withdraw",isOpen:!0,isProcessing:Ne,onRetryTx:()=>{zn()},onNewTx:()=>{ht(null),ue(""),Xe(null),We.current=null},onClose:()=>{ht(null),Xe(null),dt(!1),We.current=null},onComplete:()=>{ht(null),Xe(null),dt(!1),We.current=null},results:[{asset:{symbol:Se?.symbol||"Token",address:Se?.address||""},txHash:Ue?.txHash||"",success:Ue?.step==="success",error:Ue?.error,amount:q}],chainId:O??void 0,theme:I})})}):null,children:a.jsxs("fieldset",{disabled:Rt,style:{border:0,minWidth:0,width:"calc(100% - 32px)",maxWidth:`${ge}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(gu,{header:Oe("Source",Gt,ee),amount:q,setAmount:ue,isInsufficient:xe,sourceAmountDecimals:It,selectedSourceAsset:V,resolvedSelectedSourceAsset:V,spiceAssets:ye,setSelectedSourceAsset:U,sourceUsdEstimate:Nt,sourceTokenLabel:Pt,sourceChainLabel:Yt,totalSelectedBalance:Gt,showSourceTokenPopover:ne,setShowSourceTokenPopover:re,tokenPopoverPos:K,setTokenPopoverPos:W,tokenTriggerRef:ce,primaryColor:H,dark:F,dk:k}),a.jsx(uu,{header:Oe("Destination",mn?.balanceFormatted??null,nn.loading),amount:q,receiveAmountDisplay:Ut,receiveUsdEstimate:bt,selectedDestToken:Se,destTokenSymbol:ft,destChainName:Ve,destChainLogo:St,compatibleDestinationChains:ze,networkSwitchRef:$,onOpenNetworkPopover:yt,showNetworkPopover:le,setShowNetworkPopover:G,networkPopoverPos:he,selectedChainId:O,setSelectedChainId:z,dark:F,dk:k})]}),a.jsxs("div",{style:{marginBottom:I.spacing.sm},children:[a.jsx(mu,{show:D,onToggle:wt,showCustomAddress:Y,setShowCustomAddress:_,customRecipient:Z,setCustomRecipient:pe,externalAddress:Ye,recipientAddress:it,destChainName:Ve,destChainLogo:St,compatibleDestinationChains:ze,txDetailsChainSwitchRef:de,onOpenNetworkPopover:yt,sourceChainLabel:Yt,sourceDetailsLogo:V?E({...V,logoURI:Zn}).logoURI:Zn,sourceTokenLabel:Pt,amount:q,totalSourceDebitDisplay:fe,receiveAmountDisplay:Ut,destTokenSymbol:ft,shouldQuoteWithdrawGas:Et,estimatingFee:tt,feeError:st,displayedGasFee:Bt,selectedDestToken:Se,theme:I,styles:s,dark:F,dk:k}),me&&a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[a.jsx(bn,{palette:k,label:"FEE ASSET",value:qe.fees.isLoading?"Estimating...":Ke.source?`${E(Ke.source).symbol} \xB7 ${Ke.source._source==="spice"?"Spicenet":f.getChainConfig(Ke.source.chainId)?.displayName}`:"Unavailable"}),a.jsx(bn,{palette:k,label:"MAXIMUM FEE FUNDING",value:qe.fees.isLoading?"Estimating...":qe.fees.ready&&Ke.source&&Ke.maximumFeeFunding!=null?`${T.formatUnits(Ke.maximumFeeFunding,Ke.source.decimals)} ${E(Ke.source).symbol}`:"Unavailable"}),(qe.status.error||qe.fees.error)&&a.jsx(rn,{variant:"error",size:"compact",palette:k,children:qe.status.error||qe.fees.error}),qe.status.finalizationError&&a.jsx(f.Button,{variant:"outline",dark:F,disabled:qe.status.finalizing,onClick:()=>void qe.retryFinalization(),children:"Retry application update"}),qe.status.statusMsg&&a.jsx("span",{role:"status",children:qe.status.statusMsg})]}),V&&!ee&&ze.length===0&&a.jsx(rn,{variant:"warning",size:"compact",palette:k,children:"No withdrawal networks are available for this asset."}),rt&&a.jsx(rn,{variant:"error",size:"compact",palette:k,fontFamily:s?.fontFamily||I.typography.fontFamily,style:{marginBottom:"12px"},children:rt}),te&&a.jsxs(rn,{variant:Le?"error":"warning",size:"compact",palette:k,children:[Le?"Unable to load this balance. Please try again.":"Some other balances could not be refreshed."," ",a.jsx("button",{type:"button",onClick:()=>void De(),children:"Retry"})]}),a.jsx(f.Button,{variant:"outline",fullWidth:!0,onClick:()=>{$t&&(me?qe.submitPay():Vt())},disabled:Xt||Rt,theme:I,dark:F,styles:s,style:{marginTop:"8px"},children:Rt?"EXECUTING...":me&&Kt?"WITHDRAWN":hn})]})]})})}return null},Xo=yu,wu=({onDepositClick:e,onWithdrawClick:t,depositDisabled:n=!1,withdrawDisabled:s=!1,primaryColor:o="#EA4B4B",buttonStyles:r,dark:i=!1})=>{if(!e&&!t)return null;const l={button:{backgroundColor:o,...r}};return a.jsxs("div",{style:{display:"flex",gap:"8px"},children:[e&&a.jsx(f.Button,{variant:"outline",onClick:e,disabled:n,dark:i,styles:l,style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&a.jsx(f.Button,{variant:"outline",onClick:()=>t(),disabled:s,dark:i,styles:l,style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]})},bu=u.memo(wu),Cu=({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))})]})},vu=u.memo(Cu);var ku="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 Su=({appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,showUsdSummary:r=!0,address:i,dk:l,dark:c=!1,showModeToggle:d,isEmbeddedMode:p=!0,onModeToggle:m})=>{const[h,x]=u.useState(!1),g=async()=>{i&&await f.copyToClipboard(i)&&(x(!0),setTimeout(()=>x(!1),2e3))},y=t==="active",w=n||(y?"Active":"Inactive"),C=y?"#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:m,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:f.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:p?"Embedded":"External"}),a.jsx("img",{src:ku,alt:"","aria-hidden":"true",style:{width:"11px",height:"11px",display:"block",...c?{filter:"invert(0.65)"}:{}}})]}),a.jsx(ba,{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:ko,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:y?"#ecfdf5":"#f3f4f6",border:c?`1px solid ${l.cardBorder}`:y?"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:y?"#065f46":"#6b7280"},children:w})]})]}),r&&a.jsx("div",{style:{fontSize:"28px",fontWeight:700,color:l.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:f.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:f.font.mono,color:c?l.textSecondary:"#9ca3af"},children:f.truncateAddress(i)}),a.jsx("button",{onClick:g,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:h?"Copied":"Copy"})]})]})},Iu=u.memo(Su),Au=({asset:e,label:t,logo:n,dk:s,dark:o})=>{const r=Oa(n,e.chainId,e.tokenAddress),[i,l]=u.useState();return n===null?null:r&&r!==i?a.jsx("img",{src:r,alt:t,onError:()=>l(r),style:{width:"24px",height:"24px",borderRadius:"50%"}}):a.jsx("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:o?s.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:s.textSecondary},children:t.charAt(0)})},Eu=e=>`${e.tokenAddress}-${e.chainId}`,Fu=({spiceAssets:e,loading:t,dk:n,dark:s=!1,canDirectWithdraw:o=!1,onDirectWithdraw:r,directWithdrawState:i,onWithdrawClick:l,limit:c})=>{const d=f.useAssetDisplay(),[p,m]=u.useState(!1),h=c!==void 0&&!p?Math.max(e.length-c,0):0,x=h>0?e.slice(0,c):e,g={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},y={backgroundColor:n.cardBg,border:s?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return t?a.jsxs("div",{children:[a.jsx("div",{style:g,children:"Idle Balances"}),[1,2].map(w=>a.jsx("div",{style:{...y,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},w))]}):e.length===0?a.jsxs("div",{children:[a.jsx("div",{style:g,children:"Idle Balances"}),a.jsx("div",{style:{...y,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:g,children:"Idle Balances"}),a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[x.map(w=>{const C=f.getChainConfig(w.chainId),b=w.chainDisplayName||C?.displayName||`Chain ${w.chainId}`,S=d({symbol:w.tokenSymbol,displaySymbol:w.tokenDisplaySymbol||w.tokenDisplayName,displayName:w.tokenDisplayName,receiptTokenId:w.receiptTokenId,receiptTokenName:w.receiptTokenName,location:w.location,logoURI:w.logoURI}),I=S.symbol,F=Eu(w),k=w.receiptTokenId&&l,E=k||o&&w.directWithdraw&&!!r,R=!k&&i?.key===F?i:null,j=R?.step==="pending";return a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...y},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[a.jsx(Au,{asset:w,label:I,logo:S.logoURI,dk:n,dark:s}),a.jsxs("div",{children:[a.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:I}),a.jsx("div",{style:{fontSize:"11px",color:s?n.textSecondary:"#9ca3af"},children:b})]})]}),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:f.formatAssetBalance({balance:BigInt(w.balance),decimals:w.tokenDecimals})}),a.jsx("div",{style:{fontSize:"11px",color:R?.step==="error"?n.errorText:s?n.textSecondary:"#9ca3af"},children:R?.step==="error"?R.message||"Withdraw failed":!Number.isFinite(w.usdValue)||w.usdValue<=0?"\u2014":`${f.formatUsd(w.usdValue)}${w.priceStatus==="stale"?" (stale)":""}`})]}),E&&a.jsx("button",{onClick:()=>{j||(k?k(w.receiptTokenId):r(w))},disabled:j,title:k?"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:j?"default":"pointer",opacity:j?.6:1,whiteSpace:"nowrap"},children:j?"Withdrawing\u2026":"Withdraw"})]})]},w.positionId??`${w.owner??""}:${w.location??""}:${w.receiptTokenId??`${w.tokenAddress}-${w.chainId}`}`)}),c!==void 0&&e.length>c&&a.jsxs("button",{onClick:()=>m(!p),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:"6px",width:"100%",padding:"8px 12px",...y,cursor:"pointer",color:n.textSecondary,fontSize:"12px",fontWeight:500},children:[a.jsx("span",{children:p?"Show less":`Show ${h} more`}),a.jsx("span",{style:{transform:p?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]})]})]})},Tu=u.memo(Fu),ju=({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=f.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}`)})})]}),Bu=u.memo(ju),Ru=({appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,showUsdSummary:r,address:i,spiceAssets:l,spiceAssetsLoading:c,pendingDeposits:d,customSections:p,notice:m,onDepositClick:h,onWithdrawClick:x,depositDisabled:g,onCompleteDeposit:y,primaryColor:w,buttonStyles:C,dk:b,dark:S=!1,showModeToggle:I,isEmbeddedMode:F,onModeToggle:k,showConnectExternalCta:E,onConnectExternalWallet:R,connectExternalError:j,showHowItWorks:A=!0,canDirectWithdraw:M,onDirectWithdraw:P,directWithdrawState:N,idleBalancesLimit:B})=>{const[U,O]=u.useState(!1);return a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[a.jsx(Iu,{appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,showUsdSummary:r,address:i,dk:b,dark:S,showModeToggle:I,isEmbeddedMode:F,onModeToggle:k}),m&&a.jsx("div",{style:{padding:"10px 12px",borderRadius:"8px",backgroundColor:m.tone==="warning"?S?"rgba(245, 158, 11, 0.12)":"#fffbeb":m.tone==="success"?S?"rgba(16, 185, 129, 0.12)":"#ecfdf5":b.cardBg,border:m.tone==="warning"?S?"1px solid rgba(245, 158, 11, 0.35)":"1px solid #fde68a":m.tone==="success"?S?"1px solid rgba(16, 185, 129, 0.35)":"1px solid #a7f3d0":S?`1px solid ${b.cardBorder}`:"1px solid #e5e7eb",color:m.tone==="warning"?S?"#fbbf24":"#92400e":m.tone==="success"?S?"#34d399":"#047857":b.textSecondary,fontSize:"12px",lineHeight:1.45,fontWeight:500},children:m.message}),E&&a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[a.jsx("button",{onClick:R,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:w||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:f.font.ui,transition:"opacity 150ms ease"},children:"Connect External Wallet"}),j&&a.jsx("span",{style:{fontSize:"11px",color:S?b.errorText:"#b91c1c",lineHeight:1.4},children:j})]}),a.jsx("div",{style:{height:"1px",backgroundColor:S?"#2d2d2d":"#e5e7eb"}}),a.jsx(bu,{onDepositClick:h,onWithdrawClick:x,depositDisabled:g,primaryColor:w,buttonStyles:C,dark:S}),A&&a.jsxs("div",{children:[a.jsxs("button",{onClick:()=>O(!U),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:b.cardBg,border:S?`1px solid ${b.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:b.textSecondary,fontSize:"12px",fontWeight:500},children:[a.jsx("span",{children:"How It Works"}),a.jsx("span",{style:{transform:U?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),U&&a.jsxs("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:S?b.cardBg:"#f0fdf4",border:S?`1px solid ${b.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:S?b.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),a.jsx(Bu,{pendingDeposits:d,onCompleteDeposit:y,dk:b,dark:S}),a.jsx(Tu,{spiceAssets:l,loading:c,dk:b,dark:S,canDirectWithdraw:M,onDirectWithdraw:P,directWithdrawState:N,onWithdrawClick:x,limit:B}),p.map((z,q)=>a.jsx(vu,{section:z,dk:b,dark:S},q))]})},Du=u.memo(Ru);function Ou({dark:e,onSuccess:t,onError:n}){const{disconnect:s}=sn.useDisconnect(),{logout:o}=Zs.usePrivy(),[r,i]=u.useState(!1);return a.jsx(f.Button,{variant:"ghost",fullWidth:!0,dark:e,loading:r,onClick:async()=>{i(!0);try{s(),await o(),t()}catch(l){n(f.sanitizeError(l,"Unable to disconnect. Please try again."))}finally{i(!1)}},children:"Disconnect"})}const Jo=380,En=8,Nu=[],Mu={};function Bi(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function Pu(e,t){const n=new Map;Object.entries(t).forEach(([o,r])=>{if(!Number.isFinite(r)||r<=0)return;n.set(o,r),n.set(o.toUpperCase(),r);const i=Bi(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=Bi(o);if(!i)continue;const l=n.get(i);if(l!==void 0)return l}return 0}const Ri=({appName:e,status:t="active",statusLabel:n,customSections:s=Nu,extraAssets:o=[],tokenPrices:r={},tokenLogos:i=Mu,breakdownLabels:l=[],notice:c,styles:d,dark:p,onDepositSuccess:m,onDepositClick:h,onWithdrawClick:x,onCompleteDeposit:g,showModeToggle:y=!1,defaultMode:w,showUsdSummary:C=!0,alwaysShowEmbeddedIdle:b=!1,idleBalancesLimit:S,showDisconnect:I=!1})=>{const F=u.useContext(f.SpiceFlowProviderContext),k=F?.mode!=="7702",E=!!F?.isWhitelistGateActive,R=!!F?.isWhitelistConfigured&&F?.isUserWhitelisted!==!0,j=u.useRef(!1);u.useEffect(()=>{if(!j.current){if(f.hasStoredSpiceFlowMode()){j.current=!0;return}w&&F?.setMode&&(F.setMode(w==="non7702"?"ondemand":"7702"),j.current=!0)}},[F,w]);const[A,M]=u.useState(!1),[P,N]=u.useState(null),[B,U]=u.useState({top:0,bottom:0,left:0,placement:"below"}),O=u.useRef(null),z=u.useRef(null),{address:q,isConnected:ue}=f.useWallet(),le=F?.embeddedWalletAddress,G=F?.externalWalletAddress,{embeddedAddress:ne}=f.useProviderWallets(),{brand:re,dark:Y,primaryColor:_,dk:Z}=f.useSpiceBrand(d,p),pe=e??re?.appName??"Spice",D=k&&!G,L=!k||b,$=L?le||ne:q,de=u.useMemo(()=>F?.supportedChainIds??v.getChainIdsByNetwork("mainnet"),[F?.supportedChainIds]),ce=Nn({owner:L?$:G,role:"holding",sourceChains:de,additionalSourceTokens:o.filter(ee=>!ee.receiptTokenId&&(!ee.owner||f.addressesEqual(ee.owner,L?$:G))).map(ee=>({address:ee.tokenAddress,chainId:ee.chainId,decimals:ee.tokenDecimals,symbol:ee.tokenSymbol,logoURI:ee.logoURI})),includeRollupAssets:L,enabled:L?!!$:!!G}),he=ce.assets.filter(ee=>ee._source==="spice"),X=ce.walletAssets,K=ce.loading,W=ce.refresh,Q=L?$:G,ae=u.useMemo(()=>o.filter(ee=>!ee.owner||ee.owner.toLowerCase()===Q?.toLowerCase()).map(ee=>({...ee,owner:ee.owner??Q,location:ee.location??(ee.receiptTokenId?"rollup":L?"embedded":"external")})),[o,Q,L]),we=u.useMemo(()=>{const ee=new Map(Object.entries(r).filter(([,te])=>Number.isFinite(te)&&te>0).map(([te,De])=>[te.toLowerCase(),De]));return X.map(te=>({owner:te.owner,location:te.location,positionId:Ge(te),tokenAddress:te.address,tokenSymbol:te.symbol,tokenDecimals:te.decimals,chainId:te.chainId,chainDisplayName:f.getChainName(te.chainId),balance:te.balance.toString(),balanceFormatted:te.balanceFormatted,usdValue:te.balanceUsd||(ee.get(`${te.chainId}:${te.address.toLowerCase()}`)??0)*te.balanceFormatted,logoURI:te.logoURI||i[te.symbol],directWithdraw:L}))},[X,ae,i,r,L]),ke=u.useMemo(()=>{const ee=L?he.map(ie=>{const je=ie.balanceUsd||0,ve=Number.isFinite(ie.balanceFormatted)?ie.balanceFormatted:0,V=Pu(ie,r),Le=ie.priceStatus&&V>0?V*ve:je>0?je:V*ve;return{owner:ie.owner,location:ie.location,positionId:Ge(ie),tokenAddress:ie.address,tokenSymbol:ie.symbol,tokenDisplaySymbol:f.getAssetDisplaySymbol(ie),tokenDisplayName:f.getAssetDisplayName(ie),tokenDecimals:ie.decimals,chainId:ie.chainId,chainDisplayName:f.getAssetDisplayChainName(ie),balance:ie.balance.toString(),balanceFormatted:ie.balanceFormatted,usdValue:Le,priceStatus:V>0?void 0:ie.priceStatus,logoURI:ie.logoURI,receiptTokenId:ie.receiptTokenId,receiptTokenName:ie.receiptTokenName}}):[],te=ie=>`${ie.owner?.toLowerCase()}:${ie.location}:${ie.chainId}:${ie.receiptTokenId??v.normalizeNativeTokenAddress(ie.tokenAddress).toLowerCase()}`,De=new Map([...ce.rollupAssets,...X].map(ie=>[te({...ie,tokenAddress:ie.address}),ie])),ye=new Map([...ee,...we].map(ie=>[te(ie),ie]));for(const ie of D?[]:ae){const je=te(ie),ve=ye.get(je);ye.set(je,ve?{...ie,...ve,logoURI:ie.logoURI??ve.logoURI,tokenDisplayName:ie.tokenDisplayName??ve.tokenDisplayName,tokenDisplaySymbol:ie.tokenDisplaySymbol??ve.tokenDisplaySymbol}:ie)}return[...ye.values()].filter(ie=>BigInt(ie.balance)>0n&&zr({isDiscovered:De.get(te(ie))?.isDiscovered,balanceUsd:ie.usdValue},!0)&&f.isAssetAllowed(De.get(te(ie))??{address:ie.tokenAddress,symbol:ie.tokenSymbol,displaySymbol:ie.tokenDisplaySymbol},F?.allowedTokens)).sort((ie,je)=>je.usdValue-ie.usdValue)},[L,D,he,ce.rollupAssets,r,we,ae,F?.allowedTokens]),Ie=u.useMemo(()=>ke.reduce((ee,te)=>ee+te.usdValue,0),[ke]),{pendingDeposits:be,refresh:J}=la({chainIds:de,enabled:!!q,discoverWalletBalances:!0}),Ye=u.useMemo(()=>s.reduce((ee,te)=>ee+(te.totalValue??0),0),[s]),Ne=Ie+Ye,dt=u.useMemo(()=>{const ee=[];Ie>0&&ee.push(`${f.formatUsd(Ie)} idle`);for(const te of s){const De=l.find(ye=>ye.sectionTitle===te.title)?.label||te.title.toLowerCase();ee.push(`${f.formatUsd(te.totalValue??0)} ${De}`)}return ee.join(" \xB7 ")},[Ie,s,l]),rt=u.useCallback(ee=>{g?g(ee):N(ee)},[g]),Me=u.useCallback(()=>{N(null)},[]),Pe=u.useCallback(()=>{N(null),m?.()},[m]),Xe=u.useCallback(()=>{if(!O.current)return;const ee=O.current.getBoundingClientRect(),te=window.innerHeight-ee.bottom-En,De=ee.top-En,ye=te>=400||te>=De?"below":"above",ie=Math.max(En,Math.min(ee.right-Jo,window.innerWidth-Jo-En)),je=ye==="below"?ee.bottom+En:ee.top-En,ve=ye==="above"?window.innerHeight-je:0;U({top:je,bottom:ve,left:ie,placement:ye})},[]);u.useLayoutEffect(()=>{A&&Xe()},[A,Xe]),u.useEffect(()=>{if(!A)return;const ee=ye=>{O.current&&!O.current.contains(ye.target)&&z.current&&!z.current.contains(ye.target)&&M(!1)},te=ye=>{ye.key==="Escape"&&M(!1)},De=()=>Xe();return document.addEventListener("mousedown",ee),document.addEventListener("keydown",te),window.addEventListener("scroll",De,{passive:!0}),window.addEventListener("resize",Xe),()=>{document.removeEventListener("mousedown",ee),document.removeEventListener("keydown",te),window.removeEventListener("scroll",De),window.removeEventListener("resize",Xe)}},[A,Xe]);const Ue=L?le||ne||q:G||q,ht=u.useCallback(()=>{F?.setMode&&F.setMode(k?"7702":"ondemand")},[F,k]),[We,at]=u.useState(null);let Ae=null;try{Ae=Zs.useConnectWallet({onSuccess:()=>at(null),onError:ee=>at(f.sanitizeError(ee,"Failed to connect wallet."))}).connectWallet}catch{Ae=null}const Qe=u.useCallback(()=>{Ae&&(M(!1),at(null),Ae({walletChainType:"ethereum-only"}))},[Ae]),Re=!G&&!!Ae,_e=u.useCallback(()=>{M(!1),h?.()},[h]),He=u.useCallback(ee=>{M(!1),x?.(ee)},[x]),et=u.useCallback(ee=>{M(!1),rt(ee)},[rt]),[ut,tt]=u.useState(null),Ee=L&&!!G&&!f.addressesEqual(Q,G),st=u.useCallback(ee=>{const te=X.find(De=>De.chainId===ee.chainId&&f.addressesEqual(De.address,ee.tokenAddress));te&&(M(!1),tt(te))},[X]);if(typeof window>"u")return null;const gt=a.jsxs("button",{ref:O,onClick:()=>M(!A),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:Y?Z.hoverBg:"#ffffff",border:Y?`1px solid ${Z.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:f.font.ui,color:Y?Z.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:Y?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[a.jsxs("span",{children:[pe," Account"]}),ue&&C&&a.jsxs("span",{style:{color:Y?Z.textSecondary:"#6b7280"},children:["\xB7 ",f.formatUsd(Ne)]}),a.jsx("span",{style:{fontSize:"10px",color:Y?Z.textSecondary:"#9ca3af",transform:A?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),Fe=A?jn.createPortal(a.jsxs(a.Fragment,{children:[a.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:f.z.popover},onClick:()=>M(!1)}),a.jsxs("div",{ref:z,style:{position:"fixed",top:B.placement==="below"?`${B.top}px`:"auto",bottom:B.placement==="above"?`${B.bottom}px`:"auto",left:`${B.left}px`,width:`${Jo}px`,maxWidth:`calc(100vw - ${En*2}px)`,maxHeight:"80vh",backgroundColor:Y?Z.shell:"#ffffff",border:Y?`1px solid ${Z.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:Y?"0 10px 40px rgba(0, 0, 0, 0.5)":"0 10px 40px rgba(0, 0, 0, 0.12)",zIndex:f.z.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${f.easing.out}`},children:[a.jsx(Du,{appName:pe,status:t,statusLabel:n,totalUsdValue:Ne,breakdownSubtitle:dt,showUsdSummary:C,address:L?Ue:q,spiceAssets:ke,spiceAssetsLoading:K,pendingDeposits:be,customSections:s,notice:c,onDepositClick:h?_e:void 0,onWithdrawClick:x?He:void 0,depositDisabled:R,onCompleteDeposit:et,primaryColor:_,buttonStyles:d?.button,dk:Z,dark:Y,showModeToggle:y,isEmbeddedMode:!k,onModeToggle:ht,showConnectExternalCta:Re,onConnectExternalWallet:Qe,connectExternalError:We,showHowItWorks:!E,canDirectWithdraw:Ee,onDirectWithdraw:st,idleBalancesLimit:S}),I&&ue&&a.jsx("div",{style:{padding:"0 16px 16px"},children:a.jsx(Ou,{dark:Y,onSuccess:()=>M(!1),onError:at})})]}),a.jsx("style",{children:`
|
|
44
|
+
`,Wa=({title:e,showChevron:t,expanded:n,onToggleDetails:s,showClose:o,onClose:r,fontFamily:i,labelColor:l,textPrimary:c,closeHoverBg:d,closePressedBg:p})=>{const[m,h]=u.useState(!1),[x,g]=u.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(Mn,{color:l,direction:n?"up":"down"})]}),o&&a.jsx("button",{onClick:r,onMouseEnter:()=>h(!0),onMouseLeave:()=>{h(!1),g(!1)},onMouseDown:()=>g(!0),onMouseUp:()=>g(!1),style:{background:x?p:m?d:"none",border:"none",borderRadius:"4px",cursor:"pointer",padding:"4px",display:"flex",alignItems:"center",justifyContent:"center",color:m||x?c:l,transform:x?"scale(0.9)":m?"scale(1.1)":"scale(1)",transition:f.transition.interactive},children:a.jsx(ss,{size:16})})]})},La=({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(f.Spinner,{size:24,borderWidth:3,color:r}),a.jsxs("div",{children:[a.jsx("p",{style:{margin:0,fontSize:"14px",fontWeight:600,fontFamily:f.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]})]})]}),za=({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]}),Uo=({isOpen:e,onClose:t,onComplete:n,closeOnComplete:s=!1,type:o,results:r,chainId:i,chainName:l,explorerUrl:c,theme:d,styles:p,dark:m,intentStatus:h,onRetry:x,onNewTx:g,onRetryTx:y,asOverlay:w=!0,isProcessing:C=!1,showStepBreakdown:b=!0})=>{const{theme:S,primaryColor:I,dark:F,dk:k}=f.useSpiceBrand(p,m),E=d||S,[R,j]=u.useState(!1),A=l??(i?f.getChainName(i):"Network"),M=c??(i&&f.getExplorerUrl(i,"").replace(/\/tx\/.*$/,"")||void 0),P=F?k.cardBg:"#ffffff",N=F?"0 4px 20px rgba(0, 0, 0, 0.4)":"0 4px 20px rgba(0, 0, 0, 0.1)",B=F?"0 -4px 8px -2px rgba(0, 0, 0, 0.4)":"0 -4px 8px -2px rgba(0, 0, 0, 0.15)",U=k.textSecondary,O=F?k.textPrimary:"#374151",z=F?k.inputBg:"#f9fafb",q=F?k.inputBorder:"#e5e7eb",ue=F?k.inputBg:"#f3f4f6",le=F?k.inputBorder:"#e5e7eb",[G,ne]=u.useState(!0),re=F?k.inputBg:"#f9fafb",Y=F?k.hoverBg:"#f3f4f6",_=F?{successBg:k.successBg,successBorder:k.successBorder,successText:k.successText,errorBg:k.errorBg,errorBorder:k.errorBorder,errorText:k.errorText}:{},Z=h?.steps.find(ce=>ce.status==="failed")?.error;u.useEffect(()=>{!e&&!h&&j(!1)},[e,h]);const pe=()=>{j(!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)},D=()=>{ne(!G)};if(h){const{steps:ce,overallStatus:he}=h,X=he==="processing",K=he==="success",W=he==="failed",Q=ce.filter(Ie=>Ie.transactionHash)[0],ae=ce.length>1?ce.map(Ie=>Ie.chainName).filter(Boolean).join(" and "):A!=="Network"?A:ce[0]?.chainName||A,we=M||(Q?f.getExplorerUrl(Q.chainId,Q.transactionHash||"").replace(/\/tx\/.*$/,""):void 0),ke=a.jsxs(a.Fragment,{children:[a.jsx(Wa,{title:X?`Processing ${o.charAt(0).toUpperCase()+o.slice(1)}`:`${o.charAt(0).toUpperCase()+o.slice(1)} results`,showChevron:b,expanded:G,onToggleDetails:D,showClose:!X,onClose:t,fontFamily:p?.fontFamily||E.typography.fontFamily,labelColor:U,textPrimary:O,closeHoverBg:re,closePressedBg:Y}),a.jsx("div",{style:{marginBottom:"16px"},children:X?a.jsx(La,{chainName:ae,bg:ue,border:le,textPrimary:O,labelColor:U,primaryColor:I}):a.jsx(Pa,{isSuccess:K,type:o,chainName:ae,explorerUrl:we,txHash:Q?.transactionHash,dark:F,..._,textSecondary:U})}),b&&a.jsx("div",{style:{overflow:"hidden",maxHeight:G?"300px":"0px",opacity:G?1:0,transition:"max-height 0.3s ease, opacity 0.3s ease",marginBottom:G?"16px":"0"},children:a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:ce.map((Ie,be)=>{const J=Ie.transactionHash?f.getExplorerUrl(Ie.chainId,Ie.transactionHash):null;return a.jsx(za,{bg:z,border:q,left:a.jsx("span",{style:{fontSize:"13px",color:O},children:Ie.chainName?`On ${Ie.chainName}`:Ie.description||`Step ${be+1}`}),right:a.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"8px",fontSize:"12px",color:Ie.status==="success"?"#10b981":Ie.status==="failed"?"#ef4444":U,fontWeight:500},children:[J&&a.jsx("a",{href:J,target:"_blank",rel:"noopener noreferrer",style:{color:F?k.infoText:"#2563eb",textDecoration:"none"},onClick:Ye=>Ye.stopPropagation(),children:"View"}),Ie.status==="success"?"\u2713":Ie.status==="failed"?"\u2717":"\u25CB"]})},be)})})}),!X&&a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[W&&x&&a.jsx(f.Button,{variant:"outline",fullWidth:!0,onClick:x,theme:E,styles:p,dark:F,children:"TRY AGAIN"}),g&&a.jsxs(f.Button,{variant:"outline",fullWidth:!0,onClick:g,theme:E,styles:p,dark:F,children:["NEW ",o.toUpperCase()," \u2192"]})]})]});return w?a.jsxs("div",{style:{position:"absolute",bottom:0,left:0,right:0,zIndex:10,animation:R?"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:B},children:ke}),a.jsx("style",{children:Ua})]}):a.jsx("div",{style:{backgroundColor:P,borderRadius:"12px",padding:"24px",width:"100%",boxShadow:N},children:ke})}if(!e&&!C||!C&&(!r||r.length===0))return null;const L=r?r.every(ce=>ce.success):!1,$=r?.[0],de=[...r??[]].reverse().find(ce=>ce.txHash)?.txHash||$?.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?R?"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?B:N},children:a.jsxs("div",{style:{width:"100%",boxSizing:"border-box",padding:"0 24px"},children:[a.jsx(Wa,{title:C?`Processing ${o.charAt(0).toUpperCase()+o.slice(1)}`:`${o.charAt(0).toUpperCase()+o.slice(1)} results`,showChevron:!C&&b,expanded:G,onToggleDetails:C?void 0:D,showClose:!C,onClose:t,fontFamily:p?.fontFamily||E.typography.fontFamily,labelColor:U,textPrimary:O,closeHoverBg:re,closePressedBg:Y}),a.jsx("div",{style:{marginBottom:"16px",animation:"statusFadeIn 220ms cubic-bezier(0.22, 1, 0.36, 1) both"},children:C?a.jsx(La,{chainName:A,bg:ue,border:le,textPrimary:O,labelColor:U,primaryColor:I}):a.jsx(Pa,{isSuccess:L,type:o,chainName:A,explorerUrl:M,txHash:de,dark:F,..._,textSecondary:U})},C?"processing":L?"success":"error"),!C&&b&&r&&r.length>1&&a.jsx("div",{style:{overflow:"hidden",maxHeight:G?"200px":"0px",opacity:G?1:0,transition:"max-height 0.3s ease, opacity 0.3s ease",marginBottom:G?"16px":"0"},children:a.jsx("div",{style:{maxHeight:"180px",overflowY:"auto",display:"flex",flexDirection:"column",gap:"8px"},children:r.map((ce,he)=>a.jsx(za,{bg:z,border:q,left:a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[a.jsx("span",{style:{fontWeight:600,fontSize:"13px",color:k.textPrimary,fontFamily:f.font.mono},children:ce.asset.symbol}),ce.amount&&a.jsx("span",{style:{fontSize:"12px",color:U},children:ce.amount})]}),right:a.jsx("span",{style:{fontSize:"12px",color:ce.success?"#10b981":"#ef4444",fontWeight:500},children:ce.success?"\u2713":"\u2717"})},he))})}),!C&&!L&&r&&a.jsx("div",{style:{padding:"12px",backgroundColor:k.errorBg,border:`1px solid ${k.errorBorder}`,borderRadius:"8px",marginBottom:"16px"},children:a.jsx("p",{style:{fontSize:"13px",color:k.errorText,margin:0,lineHeight:1.5},children:Z||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:[!L&&y&&a.jsxs(f.Button,{variant:"outline",fullWidth:!0,onClick:y,theme:E,styles:p,dark:F,children:["TRY AGAIN ",o.toUpperCase()]}),L&&a.jsx(f.Button,{variant:"outline",fullWidth:!0,onClick:pe,theme:E,styles:p,dark:F,children:"DONE"})]})]})}),a.jsx("style",{children:Ua})]})};function qa(e){const t=new Set(v.getEquivalentAddresses(e).map(n=>n.toLowerCase()));return t.add(e.toLowerCase()),t}const xd=["USDC","USDT","WETH","WBTC"];function Ha(e,t){const n=f.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 fn(e,t,n){const s=f.getChainConfig(t);if(!s)return;if(n!==void 0){if(v.isNativeToken(e)&&!v.getTokenByAddress(e,n))return;const i=po(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=qa(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 yd(e){const{sourceAsset:t,outputAsset:n,sourceChainId:s,destinationChainId:o,intermediaryCandidates:r=xd}=e;if(ys(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(fn(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(fn(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=Ha(i,s);if(!l||ys(t,l)||ys(n,l))continue;const c=Ha(i,o);if(c&&ys(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 f.SpiceflowError("ROUTE_STRATEGY_ERROR",`No viable cross-chain route found from ${t.symbol} (chain ${s}) to ${n.symbol} (chain ${o}). No intermediary asset is available on both chains.`,{sourceAsset:t.symbol,outputAsset:n.symbol,sourceChainId:s,destinationChainId:o,candidatesChecked:r})}async function wd(e){const{route:t,sourceAmount:n,userAddress:s,registry:o,actionCalls:r,slippage:i}=e;async function l(c,d,p,m){const h=await o.resolveSwap({type:"swap",tokenIn:d,tokenOut:p,amountIn:m,maxSlippage:i},c,s);if(!h)throw new f.SpiceflowError("NO_LIQUIDITY",`No venue returned a quote for ${d} \u2192 ${p} on chain ${c}. No liquidity available for this pair.`,{chainId:c,tokenIn:d,tokenOut:p,amountIn:m.toString()});return h}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=fn(t.sourceAsset.address,t.destinationChainId,t.sourceChainId)||t.sourceAsset;if(qa(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=fn(t.outputAsset.address,t.sourceChainId,t.destinationChainId);if(!c)throw new f.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Output asset ${t.outputAsset.symbol} (${t.outputAsset.address}) not found on source chain ${t.sourceChainId}`,{token:t.outputAsset.symbol,address:t.outputAsset.address,chainId:t.sourceChainId,side:"source"});const d=fn(t.outputAsset.address,t.destinationChainId,t.destinationChainId);if(!d)throw new f.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Output asset ${t.outputAsset.symbol} (${t.outputAsset.address}) not found on destination chain ${t.destinationChainId}`,{token:t.outputAsset.symbol,address:t.outputAsset.address,chainId:t.destinationChainId,side:"destination"});const p=await l(t.sourceChainId,t.sourceAsset.address,c.address,n);return{chainBatches:[{chainId:t.sourceChainId,calls:p.calls},{chainId:t.destinationChainId,calls:r}],solverFrontToken:d,solverFrontAmount:p.amountOutMinimum,resolvedSwaps:{sourceSwap:p}}}case"intermediary":{if(!t.intermediaryAsset)throw new f.SpiceflowError("ROUTE_STRATEGY_ERROR","Intermediary strategy requires an intermediary asset but none was provided in the route plan.",{strategy:t.strategy});const c=fn(t.intermediaryAsset.address,t.sourceChainId,t.destinationChainId);if(!c)throw new f.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Intermediary ${t.intermediaryAsset.symbol} (${t.intermediaryAsset.address}) not found on source chain ${t.sourceChainId}`,{token:t.intermediaryAsset.symbol,address:t.intermediaryAsset.address,chainId:t.sourceChainId,side:"source"});const d=await l(t.sourceChainId,t.sourceAsset.address,c.address,n),p=await l(t.destinationChainId,t.intermediaryAsset.address,t.outputAsset.address,d.amountOutMinimum);return{chainBatches:[{chainId:t.sourceChainId,calls:d.calls},{chainId:t.destinationChainId,calls:[...p.calls,...r]}],solverFrontToken:t.intermediaryAsset,solverFrontAmount:d.amountOutMinimum,resolvedSwaps:{sourceSwap:d,destinationSwap:p}}}default:throw new f.SpiceflowError("ROUTE_STRATEGY_ERROR",`Unknown route strategy: ${t.strategy}`,{strategy:t.strategy})}}function bd(e,t,n){if(!e||!t)return null;const s=Rn(e,t),o=Object.entries(e.chainTokens??{}).flatMap(([m,h])=>{const x=dn(m);return x?.chainId===t?[{parsed:x,detail:h}]:[]}),r=m=>n.find(h=>f.addressesEqual(h.address,m))??null,i=m=>{const h=o.find(({parsed:y})=>f.addressesEqual(y.address,m));if(!h)return null;const x=f.getChainConfig(t);if(v.isNativeToken(m))return x?{address:v.ZERO_ADDRESS,symbol:x.nativeCurrency.symbol,name:x.nativeCurrency.name,decimals:x.nativeCurrency.decimals,logoURI:e.logoURI}:null;const g=x?.supportedTokens?.find(y=>f.addressesEqual(y.address,m));return!g||!uo(e,m,t)?null:{address:h.parsed.address,symbol:g.symbol,name:g.name||h.detail?.name||e.displayName||e.name||e.symbol,decimals:g.decimals,logoURI:g.logo||e.logoURI}},l=o.map(({parsed:m})=>m.address).filter(v.isNativeToken);for(const m of[...s,...l]){if(v.isNativeToken(m)){const g=i(m);if(g)return g}const h=r(m);if(h)return h;const x=i(m);if(x)return x}if(e.chainTokens||e.receiptTokenId)return null;const c=Jt(e,t);if(c){const m=r(c);if(m)return m}const d=fn(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 Cd(e){const t=e.find(n=>v.isSpicenetChainId(n.chainId))?.calls?.[0]?.data;if(!t)return null;try{const n=T.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 vd(e,t){if(!e||e.length!==t.length)return!1;const n=s=>s.reduce((o,r)=>o+r.amount,0n);return n(e)!==n(t)?!1:e.every((s,o)=>{const r=t[o];return s.token.toLowerCase()!==r.token.toLowerCase()||s.recipient.toLowerCase()!==r.recipient.toLowerCase()?!1:s.recipient.toLowerCase()===v.SPICE_GAS_FEE_RECIPIENT.toLowerCase()?f.amountsWithinBps(s.amount,r.amount,100n):s.recipient.toLowerCase()!==v.SPICE_PLATFORM_FEE_RECIPIENT.toLowerCase()||s.amount===r.amount})}function kd(e,t){const n=e.intents.flatMap(r=>r.batches).filter(r=>{const i=f.getBatchFees(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 Sd(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 Va(e,t){if(!e.token||!e.recipient||e.chainId===null)return null;const n=kd(t,e.chainId);if(!n)return null;const{gasFee:s,bridgeFee:o,spicenetFee:r}=f.getBatchFees(n),i=s+o,l=e.grossAmountRaw-i-r;if(l<=0n)throw new Error("Withdrawal amount does not cover the network fee.");const c=[{token:e.token.address,recipient:e.recipient,amount:l}];return i>0n&&c.push({token:e.token.address,recipient:v.SPICE_GAS_FEE_RECIPIENT,amount:i}),r>0n&&c.push({token:e.token.address,recipient:v.SPICE_PLATFORM_FEE_RECIPIENT,amount:r}),Sd(c)}function Id(e,t,n){const s=Va(e,t);return!s||vd(Cd(n),s)?null:e.buildWithdrawBatches(s)}async function Qa(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=Va(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(f.getBatchFees(i).totalFee)}else{const o=(e.feeEstimate??await e.execution.estimate(t,n,0n,s)).intents[0]?.batches[0]??null;o&&e.ui.setLockedGasFee(f.getBatchFees(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})=>Id(e,o,r)}:{...s,skipPreSubmitFeeEstimate:!0})}Ga(e)}catch(t){const n=t instanceof Error?t.message:"Withdraw failed";e.ui.setExecutionError(n)}finally{e.ui.setIsExecuting(!1)}}}function Ga(e){window.dispatchEvent(new CustomEvent("withdraw-completed")),e.onWithdrawSuccess?.({token:e.token?.symbol||"",amount:e.amount,chainId:e.chainId})}async function Ad(e){const t=e.executionContextRef.current;if(!t){e.ui.setExecutionProgress(null),await Qa(e);return}e.ui.setIsExecuting(!0),e.ui.setExecutionError(null),e.ui.setExecutionProgress({step:"executing",message:"Resuming existing action...",actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps});try{let n=t.totalSteps;for(let s=0;s<t.totalSteps;s++)if((await f.relayerService.checkStepStatus(t.intentId,s)).data.status!=="success"){n=s;break}if(n>=t.totalSteps)e.ui.setExecutionProgress(s=>({...s||{step:"success",message:"Transaction successful!",actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps},step:"success",message:"Transaction successful!"}));else for(let s=n;s<t.totalSteps;s++){const o=await ha({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})}Ga(e)}catch(n){const s=n instanceof Error?n.message:"Withdraw failed";e.ui.setExecutionError(s)}finally{e.ui.setIsExecuting(!1)}}async function Ed(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=>f.getBatchFees(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:f.getBatchFees(s).totalFee,feeEstimate:t}}function Wo(e,t){return T.formatUnits(e,t).replace(/(\.\d*?[1-9])0+$|\.0+$/,"$1")}function Fd(e,t,n){return Qt(e,t,n,"floor")}function Ya(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 Td(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 Ka(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:T.encodeFunctionData({abi:T.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 jd(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const s=T.getAddress(n.token),o=T.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 Bd(e,t){return`0x${t}${e.slice(4)}`}function Za(e,t,n,s){if(e.some(p=>p.domain==="spicenet"))return e;const o=n?.intents.flatMap(p=>p.batches),r=p=>p.from==="escrow",i=e.map(p=>{const m=o?.find(E=>E.chainId===p.chainId);if(!m)return p;const h=f.getBatchFees(m),x=h.totalFee;if(x<=0n)return p;const g=(p.tokenTransfers??[]).filter(E=>r(E)&&T.getAddress(E.to).toLowerCase()===t.toLowerCase()),y=g.find(E=>!v.isNativeToken(T.getAddress(E.token)))??g[0];if(!y)return p;const w=T.getAddress(y.token),C=v.isNativeToken(w);let b=!1;const S=(p.tokenTransfers??[]).map(E=>b||!r(E)||T.getAddress(E.to).toLowerCase()!==t.toLowerCase()||T.getAddress(E.token).toLowerCase()!==w.toLowerCase()?E:(b=!0,{...E,amount:s?.payoutAlreadyGross?BigInt(E.amount):BigInt(E.amount)+x}));if(!b)return p;const I=(E,R)=>C?{to:E,value:R,data:"0x"}:{to:w,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"transfer",args:[E,R]})},F=[];h.spicenetFee>0n&&F.push(I(v.SPICE_PLATFORM_FEE_RECIPIENT,h.spicenetFee));const k=h.gasFee+h.bridgeFee;return k>0n&&F.push(I(v.SPICE_GAS_FEE_RECIPIENT,k)),{...p,tokenTransfers:S,calls:[...F,...p.calls]}}),l=i.flatMap(p=>(p.tokenTransfers??[]).filter(r).map(m=>{const h=T.getAddress(m.token),x=T.getAddress(m.to),g=[{token:h,to:x,amount:BigInt(m.amount)}];return{chainId:p.chainId,transfers:jd(g)}}));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((p,m)=>{const h=T.keccak256(T.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,p.transfers[0].token,p.transfers.reduce((g,y)=>g+y.amount,0n),BigInt(p.chainId),BigInt(c+m)])),x=Bd(h,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:T.encodeFunctionData({abi:v.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${p.chainId}`,idempotenceKey:x,nbf:0n,exp:d,metadata:"{}",transfers:p.transfers.map(g=>({token:g.token.toLowerCase(),to:g.to,amount:g.amount}))}]})}})},...i]}function In(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)),...Za(o.filter(r),t,n,s)]}class Un 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 Lo(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:T.encodeFunctionData({abi:T.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 Xa(e,t,n,s,o){const r=v.hashChainBatches(e),i=await f.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 Ja(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 Un(l,t);const p=d>0n?(d*110n+99n)/100n+2n:0n;let m=p,h;const x=In(await e.buildBatches(p,{actionAmountOverride:e.actionAmountFor?.(l),onSourceSpend:w=>{m=w},onActionCalls:w=>{h=w}}),e.owner),g=Lo(x,e.owner,e.token,s+r,o),y=await Xa(g,e.owner,e.token,e.signal);if(y<=s&&(s-y)*100n<=y*15n)return{preview:{...n.preview,grossAmount:p,netAmount:0n,gasFee:s,totalFee:l,gasQuoteSource:"estimated"},feeEstimate:n.feeEstimate,grossFundingAmount:p,proceedsAvailable:t,proceedsUsed:c,fundingBatches:g,sourceSpendCap:m,destinationAmount:0n,actionDefinition:h};s=y}throw new Error("Action proceeds fee estimate did not converge")}function $a(e,t){let n,s;if(v.isNativeToken(t)){if(e.data!=="0x")return null;n=e.to,s=e.value}else{if(!f.addressesEqual(e.to,t))return null;try{const o=T.decodeFunctionData({abi:T.erc20Abi,data:e.data});if(o.functionName!=="transfer")return null;[n,s]=o.args}catch{return null}}return f.addressesEqual(n,v.SPICE_GAS_FEE_RECIPIENT)?{gas:s,platform:0n}:f.addressesEqual(n,v.SPICE_PLATFORM_FEE_RECIPIENT)?{gas:0n,platform:s}:null}async function Rd(e,t,n){const s=f.getClientForChain(e);return v.isNativeToken(n)?s.getBalance({address:t}):s.readContract({address:n,abi:T.erc20Abi,functionName:"balanceOf",args:[t]})}function Ms(e,t,n){return e.map(s=>s.chainId===t?{...s,calls:s.calls.filter(o=>!$a(o,n))}:s)}function _a(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 p=e.feeQuote?.fundingConversion,m=r??{token:t,resolve:async()=>0n},h=e.feeQuote?.preview,x=e.feeQuote?.proceedsUsed,g=p?.fromProceeds?p.tokenIn:t;if(!h||x===void 0||!i&&m.token.toLowerCase()!==g.toLowerCase())throw new Error("Refresh the action proceeds quote");const y=h.gasFee+(h.bridgeFee??0n),w=h.spicenetFee,C=i?async()=>{e.validateFeeQuote?.();const S=await Rd(e.resolvedChainId,s,i.token);e.validateFeeQuote?.();const I=i.kind==="input"?i.amount:(p?.amountInMax??x)+(i.reservedAmount??0n);if(e.signal?.aborted||S<I||p&&p.amountOut<y+w)throw new Error("The fee funding balance changed; refresh before retrying");return p?[{chainId:e.resolvedChainId,token:t,amount:p.amountOut}]:[]}:async()=>{e.validateFeeQuote?.();const S=await m.resolve(e.signal);if(e.validateFeeQuote?.(),e.signal?.aborted||(p?.fromProceeds?S<p.amountInMax||p.amountOut<y+w:S<x||S+(p?.amountOut??n)<y+w))throw new Error("Action proceeds changed; refresh before retrying");return p?.fromProceeds?[{chainId:e.resolvedChainId,token:p.tokenIn,amount:p.amountInMax},{chainId:e.resolvedChainId,token:t,amount:p.amountOut}]:[{chainId:e.resolvedChainId,token:t,amount:x+(p?.amountOut??0n)}]},b=async S=>{await C();const I=await Xa(S,s,t,e.signal,p?w:void 0);if(await C(),(I>h.gasFee?I-h.gasFee:h.gasFee-I)*100n>I*15n)throw new Error("Action gas quote changed; refresh before retrying")};return{resolveActionOutputCredits:C,prepareForSigning:async S=>{const I=Ms(S,e.resolvedChainId,t).map(k=>({...k,tokenTransfers:k.tokenTransfers?.filter(E=>!(typeof E.from=="string"&&f.addressesEqual(E.from,s)&&(f.addressesEqual(E.to,v.SPICE_GAS_FEE_RECIPIENT)||f.addressesEqual(E.to,v.SPICE_PLATFORM_FEE_RECIPIENT))))})),F=Lo(I,s,t,y,w);return await b(F),F},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 p=>{e.validateFeeQuote?.();const m=Ms(p,e.resolvedChainId,t),h=await e.execution.estimate(m,t,n,{userOverride:s,useCustomTransfers:!0,feeExecutionMode:"backend-transfer"});e.validateFeeQuote?.();const x=f.getSupplyFeePreview(h,c);if(!x||x.chainId!==e.resolvedChainId)throw new Error("The fee service did not return the destination action's fee quote");if(x.gasFee+x.spicenetFee+(x.bridgeFee??0n)+2n>n)throw new Error("Fees exceed the displayed maximum funding; refresh the quote before retrying");return{raw:m,feeEstimate:h,fees:x}};return{prepareForSigning:async p=>{const{raw:m,feeEstimate:h}=await d(p);return In(m,s,h,{payoutAlreadyGross:!0})},validateBeforeSubmit:async p=>{const{fees:m}=await d(p);let h=0n,x=0n;for(const y of p)if(y.chainId===e.resolvedChainId)for(const w of y.calls){const C=$a(w,t);C&&(h+=C.gas,x+=C.platform)}if(h+x+2n>n)throw new Error("Signed fees exceed the displayed maximum funding");const g=m.gasFee+(m.bridgeFee??0n);if((h>g?h-g:g-h)*100n>g*15n||x!==m.spicenetFee)throw new Error("The signed gas quote changed materially; refresh before retrying")}}}const Dd="0xa9059cbb";function rs(e,t,n){return v.isNativeToken(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:T.encodeFunctionData({abi:T.erc20Abi,functionName:"transfer",args:[n,t]})}}function ei(e,t,n){return{chainId:n,calls:[rs(e,t,v.getEscrowContractAddress(n))]}}function Od(e,t,n,s){const o=t.source.chainId;return{chainId:o,calls:[...e.calls,rs(t.source.address,n,v.getEscrowContractAddress(o)),...s>0n?[rs(t.source.address,s,v.SPICE_GAS_FEE_RECIPIENT)]:[]]}}function ti(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 ni(e,t,n){return e?.asset?._source==="wallet"&&e?.asset.chainId===n}function si(e){return e.isNative||v.isNativeToken(e.address)?!0:!v.getTokenByAddress(e.address,e.chainId)}function oi(e,t,n,s){return t!=="user-transfer"||!n||e.length===0||e[0]?.to.toLowerCase()!==s.toLowerCase()||!e[0]?.data.startsWith(Dd)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function as(e,t,n,s){const o=await(t??Ns)({...n,requestTimestampMs:s});return o?[o,e]:[e]}function Nd(e){return e.filter(t=>t.domain!=="spicenet")}function is(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 Wn(e,t,n){return Qt(e,t,n,"ceil")}function ri(e){const t=e.selectedAsset?.asset;return e.isPayMode&&!!t&&t._source==="wallet"&&t.chainId!==e.resolvedChainId&&!!e.pivot}function zo(e){const t=e.selectedAsset?.asset;return!e.isPayMode&&!!t&&t._source==="wallet"&&t.chainId!==e.resolvedChainId&&!!e.sourceSwap&&!!e.pivot}function Ps(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 ai(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 Us=(e,t)=>ai(Md,e,t),Ws=async(e,t)=>{const n=await ai(Pd,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]=Ms([o],e.resolvedChainId,r),l=Ka(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(p=>p.to.toLowerCase()===d.to.toLowerCase()&&p.value===d.value&&p.data===d.data))?n:[...n.slice(0,-1),{...i,calls:[...l,...i.calls]}]};async function Md(e,t){const{currentPaymentAmount:n,destinationToken:s,embeddedWalletAddress:o,providerEmbeddedAddress:r,address:i,isNon7702:l,resolvedChainId:c,buildActionCalls:d,feeExecutionMode:p,buildSpicenetBatch:m,needsSwap:h,exactOutputSwap:x,resolvedTokenIn:g,requestTimestampMs:y}=e,w=t?.sourceAssetOverride?{asset:t.sourceAssetOverride}:e.selectedAsset,C=t?.fundingTokenOverride??g,b=zt(n,s.decimals),S=t?.actionAmountOverride??(e.feeOnlyAction?0n:b),I=!!e.feeOnlyAction&&(t?.fundingAmountOverride??0n)>0n,F=o||r||i;if(!F)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const k={userAddress:e.recipient??F,executorAddress:F,beneficiary:e.recipient??F,outputRecipient:h?F:void 0,chainId:c,destinationToken:s.address,grossAmount:t?.fundingAmountOverride??b,netAmount:S,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:p,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},E=await d(S,k),R={chainId:c,calls:E},j=!!w&&w.asset._source!=="wallet",A=ni(w??null,l,c),M=j||A&&!!w&&!si(w.asset),P=(B,U)=>({token:v.normalizeNativeTokenAddress(B),from:"escrow",to:F,amount:U}),N=(B,U,O)=>A?[ei(B,U,c),...O]:O;if(b===0n&&!I)return[R];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&&A)return Ps(t.fundingAmountOverride??0n,t),[R];if(ri(e)){if(h&&!x)throw new Error("Swap quote not available yet");const B=t?.fundingAmountOverride??(x?x.amountInMax:b),U=t?.sourceGasSkimOverride??0n,O=Qt(B,e.pivot.destination.decimals,e.pivot.source.decimals,"ceil"),z=O+U,q=e.sourceExactOutputSwap,ue=q&&(t?.reuseQuotedSourceSwap||q.amountOut>=z)?q:e.resolveSourceExactOutputSwap?await e.resolveSourceExactOutputSwap(z):null;if(!ue)throw new Error("Swap quote not available yet");Ps(ue.amountInMax,t);const le=w.asset;if(ue.amountInMax>le.balance)throw new Error(`Insufficient ${le.symbol} for this payment. Required ${T.formatUnits(ue.amountInMax,le.decimals)} ${le.symbol}; available ${T.formatUnits(le.balance,le.decimals)} ${le.symbol}.`);const G=ue.amountOut>=z?O:ue.amountOut-U;if(G<=0n)throw new Error("Amount is too small to cover fees. Increase the amount and retry.");const ne={chainId:e.pivot.source.chainId,calls:[...ue.calls,rs(e.pivot.source.address,G,v.getEscrowContractAddress(e.pivot.source.chainId)),...U>0n?[rs(e.pivot.source.address,U,v.SPICE_GAS_FEE_RECIPIENT)]:[]]},re={chainId:c,calls:[...x?.calls??[],...E],tokenTransfers:[P(e.pivot.destination.address,B),...R.tokenTransfers??[]]},Y=await as(re,m,{userAddress:F,destinationChainId:c,deliveryToken:e.pivot.destination.address,deliveryAmount:B,deliveryRecipient:F,deliveryTransfers:is(re),sourceAsset:w.asset},y);return[ne,...Y]}if(w){const B=t?.fundingAmountOverride??x?.amountInMax??b;Ps(Wn(B,await xn(w.asset,C??w.asset.address,c,s),w.asset.decimals),t)}if(h&&x){const B=C??Jt(w.asset,c)??w.asset.address,U=t?.fundingAmountOverride??x.amountInMax,O=M?[P(B,U)]:[],z={chainId:c,calls:[...x.calls,...E],tokenTransfers:[...O,...R.tokenTransfers??[]]};if(!M)return[z];const q=await as(z,m,{userAddress:F,destinationChainId:c,deliveryToken:B,deliveryAmount:U,deliveryRecipient:F,deliveryTransfers:is(z),sourceAsset:w.asset},y);return N(B,U,q)}if(M){const B=C??Jt(w.asset,c)??s.address;if(A&&!e.feeOnlyAction&&B.toLowerCase()===s.address.toLowerCase())return[R];const U=t?.fundingAmountOverride??b,O={...R,tokenTransfers:[P(B,U),...R.tokenTransfers??[]]},z=await as(O,m,{userAddress:F,destinationChainId:c,deliveryToken:B,deliveryAmount:U,deliveryRecipient:F,deliveryTransfers:is(O),sourceAsset:w.asset},y);return N(B,U,z)}return[R]}async function Pd(e,t){const{selectedAsset:n,embeddedWalletAddress:s,recipient:o,resolvedChainId:r,destinationToken:i,buildActionCalls:l,feeExecutionMode:c,buildSpicenetBatch:d,isPayMode:p,isNon7702:m,needsSwap:h,resolvedSwap:x,quoteAmountOut:g,resolvedTokenIn:y,requestTimestampMs:w}=e;if(!n?.asset||!s)return[];const C=o??s;if(!C)return[];const b=zo(e);let S=e.sourceSwap,I=zt(n.amount,n.asset.decimals),F=b?e.sourceSwap.amountOutMinimum:null;if(b&&e.isFeeInclusiveInput&&(F=ti(e.sourceSwap,t?.sourceGasSkimOverride??0n)),b&&!e.isFeeInclusiveInput&&(t?.fundingAmountOverride!==void 0||(t?.sourceGasSkimOverride??0n)>0n)){F=t?.fundingAmountOverride!==void 0?Wn(t.fundingAmountOverride,e.pivot.destination.decimals,e.pivot.source.decimals):e.sourceSwap.amountOutMinimum;const Z=F+(t?.sourceGasSkimOverride??0n);if(!e.resolveSourceExactOutputSwap)throw new Error("The source quote cannot include fees yet.");const pe=await e.resolveSourceExactOutputSwap(Z);if(pe.amountOut<Z)throw new Error("The source quote does not cover the accepted funding amount.");I=pe.amountInMax,S={...pe,amountOutMinimum:pe.amountOut}}const k=b?e.pivot.destination.address:y??Jt(n.asset,r)??i.address,E=b?e.pivot.destination.decimals:await xn(n.asset,k,r,i),R=t?.fundingAmountOverride??t?.actionAmountOverride??(b?Qt(F,e.pivot.source.decimals,E,"floor"):Os(zt(n.amount,n.asset.decimals),n.asset.decimals,E)),j=t?.fundingAmountOverride??R,A=t?.sourceFundingAmountOverride??Wn(R,E,n.asset.decimals);Ps(b?I:A,t);const M=t?.deliveryAmountOverride??(c==="user-transfer"?j:t?.actionContextOverride?.netAmount??j),P=t?.withdrawalAmountOverride??M,N=t?.actionAmountOverride??t?.actionContextOverride?.netAmount??R;let B=x;if(h&&!p&&(t?.actionContextOverride?.netAmount!==void 0||b&&(t?.sourceGasSkimOverride??0n)>0n&&!t?.reuseQuotedSourceSwap)){if(!e.resolveInputSwap)throw new Error("Swap quote cannot be refreshed for the amount after fees.");const Z=t?.actionContextOverride?.netAmount??N;(!B||e.swapInputAmount!==Z)&&(B=await e.resolveInputSwap(Z,x??void 0))}B&&t?.onSwap?.(B,t?.actionContextOverride?.netAmount??e.swapInputAmount??N);const U=B?.amountOutMinimum??g,O={userAddress:C,executorAddress:s,beneficiary:C,outputRecipient:h?s:void 0,chainId:r,destinationToken:i.address,feeToken:c==="user-transfer"&&h&&y?y:i.address,grossAmount:j,netAmount:N,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:c,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},z=()=>l(N,O),q=n.asset?._source==="wallet";if(!p&&q&&n.asset.chainId===r&&si(n.asset)){if(h){if(!y)throw new Error("Swap input token could not be resolved");if(!B||U===null)throw new Error("Swap quote not available yet")}if(h&&B&&U){const Z=await l(t?.actionAmountOverride??U,{...O,netAmount:t?.actionAmountOverride??U}),{feeCall:pe,remainingCalls:D}=oi(Z,c,h,O.feeToken);return[{chainId:r,calls:[...pe?[pe]:[],...B.calls,...D]}]}return[{chainId:r,calls:await z()}]}if(!p&&q&&n.asset.chainId!==r&&!b)throw new Error("A current source-to-destination funding route is required");const ue=n.asset._source!=="wallet",le=ni(n,m,r);if(!(ue||le||b))return[{chainId:r,calls:await z()}];const G=b?Od(S,e.pivot,F,t?.sourceGasSkimOverride??0n):le?ei(y??v.normalizeNativeTokenAddress(n.asset.address),A,r):null,ne=(Z,pe)=>({token:v.normalizeNativeTokenAddress(Z),from:"escrow",to:s,amount:pe});if(h){if(!y)throw new Error("Swap input token could not be resolved");if(!B||U===null)throw new Error("Swap quote not available yet")}if(h&&B&&U&&y){const Z=await l(t?.actionAmountOverride??U,{...O,netAmount:t?.actionAmountOverride??U}),{feeCall:pe,remainingCalls:D}=oi(Z,c,h,O.feeToken),L={chainId:r,calls:[...pe?[pe]:[],...B.calls,...D],tokenTransfers:[ne(y,M)]},$=await as(L,d,{userAddress:s,destinationChainId:r,deliveryToken:y,deliveryAmount:M,withdrawalAmount:P,deliveryRecipient:s,deliveryTransfers:is(L,P),sourceAsset:n.asset},w);return G?[G,...$]:$}const re=y??Jt(n.asset,r)??i.address,Y={chainId:r,calls:await z(),tokenTransfers:[ne(re,M)]},_=await as(Y,d,{userAddress:s,destinationChainId:r,deliveryToken:re,deliveryAmount:M,withdrawalAmount:P,deliveryRecipient:s,deliveryTransfers:is(Y,P),sourceAsset:n.asset},w);return G?[G,..._]:_}async function Ud(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=f.getSingleNetOutput(c);if(d===null||d>=e)return r;const p=r-d,m=e+p;if(m<=r)return r;r=m}return r}function Wd(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:T.encodeFunctionData({abi:T.erc20Abi,functionName:"approve",args:[r,o.amountInMax]})},...o.calls]}}}}function Ls(e){const t=(e?.customVenues??[]).map(s=>ll(Wd(s)));async function n(s,o,r){const i=t.filter(d=>d.chainIds.includes(o));if(i.length===0)throw new f.SpiceflowError("NO_SWAP_ROUTE",`No exact-output venue supports chain ${o}`,{chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut});const l=(await Promise.allSettled(i.map(async 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 f.SpiceflowError("NO_SWAP_ROUTE",`All aggregators failed for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}`,{chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountOut:s.amountOut.toString()});const c=l.find(d=>d.venue.preferred);return c?c.quote:(l.sort((d,p)=>d.quote.amountIn<p.quote.amountIn?-1:d.quote.amountIn>p.quote.amountIn?1:0),l[0].quote)}return{getQuote:n,venues:t}}function ii(e,t,n){if(e._source==="wallet")return e.chainId===t?e.address:null;const s=Rn(e,t);return s.find(o=>o.toLowerCase()===n.toLowerCase())??s[0]??null}async function li(e,t,n,s){const o=v.hashChainBatches(s),r=await f.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 ls(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:ii(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 f.getClientForChain(e.resolvedChainId).readContract({address:i,abi:T.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 p=Ls({customVenues:[...e.resolveExactOutputSwap?[{name:"consumer-exact-output",chainIds:[e.resolvedChainId],preferred:!0,resolve:e.resolveExactOutputSwap}]:[],...Bn(e.liquidityVenues).output]}),m=x=>li(e,r,c,x);let h=await m(await e.buildPayChainBatches({fundingAmountOverride:0n}));for(let x=0;x<8;x++){const g=h.gasFee+h.platformFee,y=o?0n:d<g?d:g,w=g-y,C=w>0n?(w*110n+99n)/100n+2n:0n,b=C>0n?await p.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 S=b?.amountInMax??0n,I=o?0n:Wn(S,l,n.decimals);if(o&&S>d)throw new Un(S,d);if(!o&&I>n.balance)throw new Un(I,n.balance);let F,k=In(await e.buildPayChainBatches({fundingAmountOverride:o?0n:S,...o?{}:{fundingTokenOverride:i},...t?{actionAmountOverride:t.amount-S}:{},onActionCalls:R=>{F=R}}),r);if(b){const R=k.length-1;k=k.map((j,A)=>A===R?{...j,calls:[...j.calls,...b.calls]}:j)}k=Lo(k,r,c,h.gasFee,h.platformFee);const E=await m(k);if(E.gasFee<=h.gasFee&&(h.gasFee-E.gasFee)*100n<=E.gasFee*15n&&E.platformFee===h.platformFee){const R={tokenIn:i,tokenOut:c,amountInMax:S,amountOut:C,sourceAmountMax:I,...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:h.gasFee,spicenetFee:h.platformFee,totalFee:g,gasQuoteSource:"estimated"},grossFundingAmount:o?0n:S,proceedsAvailable:d,proceedsUsed:o?g:y,fundingConversion:R,fundingBatches:k,sourceSpendCap:I,destinationAmount:0n,actionDefinition:F}}h=E}throw new Error("Fee conversion pricing did not converge")}const qo=["input","proceeds","balance"];function Ld(e){if(e.reserve&&e.reserve.amount<0n)throw new Error("Fee funding reserve cannot be negative");const t=l=>f.addressesEqual(l,e.feeToken),n=(l,c)=>Number(l.swap)-Number(c.swap),s={input:[],proceeds:[],balance:[]};for(const l of e.inputs??[])l.amount>0n&&s.input.push({kind:"input",...l,swap:!t(l.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=e.balances.filter(l=>l._source==="wallet"&&l.chainId===e.chainId&&l.location!=="external"),r=e.balances.filter(l=>l._source==="spice"),i=l=>{const c=[];for(const d of l){const p=e.reserve&&Ge(d)===Ge(e.reserve.asset)?e.reserve.amount:0n,m=d.balance-p;if(m<=0n)continue;const h=p>0n?{...d,balance:m,balanceFormatted:Number(T.formatUnits(m,d.decimals)),balanceUsd:d.balanceUsd*Number(m)/Number(d.balance)}:d,x=ii(h,e.chainId,e.feeToken);x&&(e.inputs?.some(g=>f.addressesEqual(g.token,x)&&!(e.reserve&&f.addressesEqual(e.reserve.asset.address,g.token)))||c.push({kind:"balance",token:x,amount:h.balance,asset:h,...p>0n?{reservedAmount:p}:{},swap:!t(x)}))}return c.sort((d,p)=>n(d,p)||p.asset.balanceUsd-d.asset.balanceUsd)};return s.balance=[...i(o),...i(r)],(e.order??qo).flatMap(l=>s[l])}function zd(e){return e instanceof Un||e instanceof f.SpiceflowError&&e.code==="NO_SWAP_ROUTE"}async function ci(e,t){const n=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!n||!e.ready||!e.authenticated)return null;const s=e.destinationToken.address;let o;const r=()=>o??(o=(async()=>{const d=await li(e,n,s,await e.buildPayChainBatches({fundingAmountOverride:0n}));return{feeEstimate:null,preview:{symbol:e.destinationToken.symbol,decimals:e.destinationToken.decimals,gasFee:d.gasFee,spicenetFee:d.platformFee,bridgeFee:0n,totalFee:d.gasFee+d.platformFee,grossAmount:0n,netAmount:0n,gasQuoteSource:"estimated"}}})()),i=(d,p)=>e.buildPayChainBatches({...p,fundingAmountOverride:d}),l=(d,p)=>Ja({proceeds:{token:s,resolve:async()=>d},owner:n,token:s,signal:e.signal,baseline:r,buildBatches:i,fundShortfall:!1,actionAmountFor:p}),c=async d=>{if(d.kind==="input")return d.swap?ls({...e,actionProceeds:void 0},d):l(d.amount,x=>d.amount-x);if(d.kind==="proceeds"){const x={...e.actionProceeds,resolve:async()=>d.amount};return d.swap?ls({...e,actionProceeds:x}):l(d.amount)}const p=d.asset;if(p._source==="wallet"&&!d.swap)return l(p.balance);const m={...e,selectedAsset:{asset:p,amount:"0"},resolvedTokenIn:d.token,actionInput:void 0,actionProceeds:void 0,buildPayChainBatches:x=>e.buildPayChainBatches({...x,sourceAssetOverride:p,fundingTokenOverride:x?.fundingTokenOverride??d.token})};if(d.swap)return ls(m);const h=await t(m);if(h&&(h.sourceSpendCap??0n)>p.balance)throw new Un(h.sourceSpendCap,p.balance);return h};for(const d of e.feeFunding??qo){const p=d==="proceeds"&&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(p&&p.amount<0n)throw new Error("Action proceeds cannot be negative");const m=Ld({feeToken:s,chainId:e.resolvedChainId,inputs:e.actionInput,proceeds:p,balances:e.feeFundingBalances??[],order:[d],reserve:e.feeFundingReserve});for(const h of m)try{const x=await c(h);if(!x)continue;const{swap:g,...y}=h;return{...x,fundingSource:y}}catch(x){if(e.signal?.aborted||!zd(x))throw x}}throw new Error(`No available balance can cover this action's ${e.destinationToken.symbol} execution cost`)}async function qd(e,t,n,s=!1){const o=e.selectedAsset,r=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!o||!r||!e.ready||!e.authenticated||e.isQuoting)return null;if(o.asset._source!=="wallet"||o.asset.chainId!==e.resolvedChainId||!ws(o.asset)&&o.asset.owner&&!f.addressesEqual(o.asset.owner,r))throw new Error("Funded fee hierarchy requires principal on the action chain in the executing wallet.");if(s&&(e.isPayMode||!e.isFeeInclusiveInput||t.recipient&&!f.addressesEqual(t.recipient,r)))throw new Error("Output-funded actions require an input-inclusive amount left in the executing wallet.");if(e.isPayMode&&e.needsSwap&&!e.exactOutputSwap)return null;const i=e.isPayMode?zt(e.currentPaymentAmount,e.destinationToken.decimals):void 0;if(e.isPayMode&&e.needsSwap&&e.exactOutputSwap.amountOut!==i)throw new Error("Wait for the payment quote for the current amount.");const l=v.getTokensForChain(e.resolvedChainId).find(w=>w.equivalenceGroup==="USDC");if(!l)throw new Error("Configure the execution fee token for this chain.");const c={...l,address:l.address,chainId:e.resolvedChainId},d=i!==void 0?e.needsSwap?e.exactOutputSwap.amountInMax:i:zt(o.amount,o.asset.decimals);if(d<=0n||d>o.asset.balance)throw new Error("Enter an amount within the available balance.");if(!e.isPayMode&&e.needsSwap&&t.swapInputAmount!=null&&t.swapInputAmount!==d)throw new Error("Wait for the action quote for the current amount.");const p=i??(e.needsSwap?t.resolvedSwap?.amountOutMinimum??0n:d);let m=t.resolvedSwap??void 0,h=d,x=p;const g={...e,feeOnlyAction:!0,selectedAsset:null,isPayMode:!0,isFeeInclusiveInput:!1,parsedAmount:0,currentPaymentAmount:"0",destinationToken:c,resolvedTokenIn:c.address,executionTokenAddress:c.address,needsSwap:!1,resolvedSwap:null,isDirect:!0,actionInput:!e.isPayMode&&e.isFeeInclusiveInput?[{token:o.asset.address,amount:d}]:void 0,actionProceeds:s?{token:e.destinationToken.address,resolve:async()=>p>0n?p-1n:0n}:e.actionProceeds,feeFundingBalances:e.feeFundingBalances?.filter(w=>!w.balanceError&&!(e.feeFundingReserve&&Ge(e.feeFundingReserve.asset)!==Ge(o.asset)&&Ge(w)===Ge(e.feeFundingReserve.asset))&&!ws(w)&&(!w.owner||f.addressesEqual(w.owner,r))),feeFundingReserve:{asset:o.asset,amount:e.feeFundingReserve&&Ge(e.feeFundingReserve.asset)===Ge(o.asset)&&e.feeFundingReserve.amount>d?e.feeFundingReserve.amount:d},buildPayChainBatches:async w=>{const C=w?.actionAmountOverride??d;if(C<=0n)throw new Un(d+1n,d);const b=!e.isPayMode&&e.needsSwap?C===d?t.resolvedSwap:await t.resolveInputSwap?.(C,t.resolvedSwap??void 0):null,S=e.needsSwap?e.isPayMode?e.exactOutputSwap:b:null;if(e.needsSwap&&!S)throw new Error("The action quote is unavailable.");m=b??void 0,h=C,x=i??m?.amountOutMinimum??C;const I={userAddress:t.recipient??r,executorAddress:r,beneficiary:t.recipient??r,outputRecipient:r,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address,grossAmount:p,netAmount:x,feeToken:c.address,feeExecutionMode:"backend-transfer"},F=await t.buildActionCalls(x,I),k={amount:x,context:I,calls:F},E=[...S?.calls??[],...F];return Us({...t,selectedAsset:null,feeOnlyAction:!0,isPayMode:!0,isFeeInclusiveInput:!1,currentPaymentAmount:"0",destinationToken:c,resolvedTokenIn:c.address,needsSwap:!1,resolvedSwap:null,exactOutputSwap:null,quoteAmountOut:null,feeExecutionMode:"backend-transfer",buildActionCalls:()=>E},{...w,onActionCalls:()=>w?.onActionCalls?.(k)})}},y=await ci(g,n);if(!y)return null;if(s&&y.fundingSource?.kind==="proceeds"&&(x-=y.fundingConversion?.amountInMax??y.proceedsUsed??0n),x<=0n)throw new Error("Not enough action output remains after execution costs.");return{...y,fundedFeeToken:c,batches:y.fundingBatches??y.batches,destinationSwap:m,swapInputAmount:h,destinationAmount:x,sourceSpendCap:d+(y.fundingSource?.kind==="balance"&&y.fundingSource.asset&&Ge(y.fundingSource.asset)===Ge(o.asset)?y.fundingConversion?.amountInMax??y.proceedsUsed??0n:0n)}}async function Hd(e){const t=e.selectedAsset.asset;if(t.chainId!==e.destinationToken.chainId||!f.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=zt(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 di(e){const[t]=await e.buildSupplyChainBatches({sourceGasSkimOverride:1n,reuseQuotedSourceSwap:!0});if(!t)throw new Error("Swap quote not available yet");const{gasFee:n}=await f.relayerService.estimateBatchGas({user:e.user,outputToken:e.pivot.source.address,stepIndex:0,chainBatches:[t],signal:e.signal});return n}const ui=(e,t)=>(e+t-1n)/t;function Ho(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 Vd(e,t){const n=e.spicenetFee+(e.bridgeFee??0n);return e.grossAmount<=n?t+e.gasFee+n:ui((t+e.gasFee)*e.grossAmount,e.grossAmount-n)+2n}async function pi(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 p=1n,m;for(let h=0;h<8;h++){const x=In(await e.buildBatches(p),d,m,{payoutAlreadyGross:!0}),g=await e.estimate(Ms(x,e.tokenDescriptor.chainId,e.fundingToken),e.fundingToken,p,{...e.executionOptions,feeExecutionMode:"backend-transfer"}),y=f.getSupplyFeePreview(g,e.tokenDescriptor);if(!y)throw new Error("The fee service did not return a fee quote for this action");const w=y.gasFee+y.spicenetFee+(y.bridgeFee??0n);if(m&&w+2n<=p)return{preview:{...y,grossAmount:p,netAmount:0n},feeEstimate:g,grossFundingAmount:p};p=(w*110n+99n)/100n+2n,m=g}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=f.getSupplyFeePreview(s,e.tokenDescriptor);if(!o)return{preview:f.getEscrowFreeFeePreview(n,e.tokenDescriptor,t),feeEstimate:s,grossFundingAmount:t};const r=Vd(o,t),i=d=>o.grossAmount>0n?ui(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 fi(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 f.formatRawTokenInput(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 Qd(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:fi({balance:t.balance,decimals:t.decimals,planForAmount:s=>An({selectedAsset:{asset:t,amount:f.formatRawTokenInput(s,t.decimals)},isPayMode:!1,isNon7702:!1,isFeeInclusiveInput:!1,parsedAmount:Number(f.formatRawTokenInput(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 An(e){const{signal:t,selectedAsset:n,isPayMode:s,isFeeInclusiveInput:o=!1,parsedAmount:r,needsSwap:i,exactOutputSwap:l,isNon7702:c,currentPaymentAmount:d,destinationToken:p,feeExecutionMode:m,resolvedTokenIn:h,embeddedWalletAddress:x,providerEmbeddedAddress:g,resolvedChainId:y,isConnected:w,address:C,ready:b,authenticated:S,isDirect:I,resolvedSwap:F,sourceSwap:k,pivot:E,isQuoting:R,executionTokenAddress:j,buildPayChainBatches:A,buildSupplyChainBatches:M,estimate:P}=e;if(e.feeOnlyAction&&!n&&e.feeFunding?.length!==0)return ci(e,An);if(e.feeOnlyAction&&e.actionProceeds&&e.actionProceeds.token.toLowerCase()!==p.address.toLowerCase()||e.feeOnlyAction&&n&&(n.asset._source==="spice"||n.asset._source==="wallet"&&n.asset.chainId===y)&&(h?h.toLowerCase()!==p.address.toLowerCase():n.asset.receiptTokenId||n.asset.chainTokens))return ls(e);if(e.actionProceeds&&e.feeOnlyAction){const re=x||g;if(!re||!b||!S)return null;if(h&&h.toLowerCase()!==p.address.toLowerCase())throw new Error("Action proceeds require a matching fee-token source");return Ja({proceeds:e.actionProceeds,owner:re,token:p.address,signal:t,buildBatches:(Y,_)=>A({..._,fundingAmountOverride:Y}),baseline:()=>An({...e,actionProceeds:void 0,selectedAsset:n??{amount:"0",asset:{...p,name:p.symbol,balance:0n,balanceFormatted:0,balanceUsd:0,isNative:!1,_source:"spice"}}})})}if(!n?.asset)return null;if(s){if(!x&&!g||r<=0&&!e.feeOnlyAction||i&&!l&&!e.feeOnlyAction)return null;const re=zt(d,p.decimals),Y=h||Jt(n.asset,y)||n.asset.address||p.address,_={chainId:y,tokenAddress:Y,symbol:v.getTokenByAddress(Y,y)?.symbol??n.asset.symbol,decimals:await xn(n.asset,Y,y,p)};if(!w||!C||!b||!S)return null;const Z=x||g||C,pe=i?l?.amountInMax??0n:re;if(pe===0n&&!e.feeOnlyAction)return null;const D=E?await di({user:Z,pivot:E,buildSupplyChainBatches:W=>A({...W,sourceGasSkimOverride:1n}),signal:t}):0n,L=Date.now();let $=await pi({requiredNetFunding:pe,feeOnlyAction:e.feeOnlyAction,buildBatches:W=>A({fundingAmountOverride:W,sourceGasSkimOverride:D}).then(Q=>Za(Nd(Q),Z,void 0,{requestTimestampMs:L})),fundingToken:Y,estimate:P,executionOptions:{userOverride:Z,useCustomTransfers:!0,feeExecutionMode:m,signal:t},tokenDescriptor:_});if(!$.preview)return null;let de=0n,ce,he=[],X=!1;for(let W=0;W<8;W++){if(t?.aborted)throw new Error("Fee estimation cancelled");if(he=In(await A({fundingAmountOverride:$.grossFundingAmount,sourceGasSkimOverride:D,onSourceSpend:Ye=>{de=Ye},onActionCalls:Ye=>{ce=Ye}}),Z,$.feeEstimate,{payoutAlreadyGross:!0,requestTimestampMs:L}),e.feeOnlyAction){X=!0;break}const Q=await P(he,Y,$.grossFundingAmount,{userOverride:Z,useCustomTransfers:!0,feeExecutionMode:m,signal:t}),ae=m==="user-transfer"?Ho(Q,$.feeEstimate):Q,we=f.getSupplyFeePreview(ae,_)??f.getEscrowFreeFeePreview(he,_,pe);if(!we)return null;const ke=pe+we.gasFee+we.spicenetFee+(we.bridgeFee??0n),Ie=f.getSupplyFeePreview($.feeEstimate,_),be=(Ie?.gasFee??0n)===we.gasFee&&(Ie?.spicenetFee??0n)===we.spicenetFee&&(Ie?.bridgeFee??0n)===(we.bridgeFee??0n),J=$.grossFundingAmount===ke&&be;if($={feeEstimate:ae,grossFundingAmount:ke,preview:{...we,grossAmount:ke,netAmount:pe}},J){X=!0;break}}if(!X)throw new Error("Payment fees did not converge. Refresh the quote before submitting.");if(!$.preview)return null;const K=E?Qt(D,E.source.decimals,E.destination.decimals,"ceil"):0n;return{...$,batches:he,sourceSpendCap:de,actionDefinition:ce,destinationAmount:re,preview:{...$.preview,grossAmount:$.preview.grossAmount+K,gasFee:$.preview.gasFee+K,totalFee:($.preview.totalFee??0n)+K},...E?{sourceGasSkim:D}:{}}}if(r<=0||!x)return null;const N=x||g;if(E&&!k)return null;const B=zo({isPayMode:s,selectedAsset:n,resolvedChainId:y,sourceSwap:k,pivot:E});if(!(!s&&!c&&n.asset?._source==="wallet"&&n.asset.chainId!==y)&&!I&&!F&&!R||R)return null;let U=await M();if(U.length===0)return null;const O={chainId:y,tokenAddress:j,symbol:v.getTokenByAddress(j,y)?.symbol??(n.asset.chainId===y&&f.addressesEqual(n.asset.address,j)?n.asset.symbol:p.symbol),decimals:await xn(n.asset,j,y,p)},z=B&&e.initialFeeEstimate!==void 0&&e.initialSourceGasSkim!==void 0,q=B?z?e.initialSourceGasSkim:await di({user:N,pivot:E,buildSupplyChainBatches:M,signal:t}):0n;B&&q>0n&&(U=await M({sourceGasSkimOverride:q}));const ue=B?Qt(o?ti(k,q):k.amountOutMinimum,E.source.decimals,E.destination.decimals,"floor"):Qt(zt(n.amount,n.asset.decimals),n.asset.decimals,O.decimals,"floor"),le={userOverride:N,useCustomTransfers:!0,feeExecutionMode:m,signal:t,...B?{skipUserFundingPreflight:!0}:{}};let G=ue,ne=e.initialFeeEstimate??await P(U,j,G,le);for(let re=0;re<8;re++){if(t?.aborted)throw new Error("Fee estimation cancelled");const Y=f.getSupplyFeePreview(ne,O)??f.getEscrowFreeFeePreview(U,O,G);if(!Y)return null;const _=Vo(Y,ue,o,m);G=_.grossAmount;let Z,pe,D,L,$;const de=await M({fundingAmountOverride:G,sourceGasSkimOverride:q,actionContextOverride:_,onDestinationAmount:Q=>{Z=Q},onSourceSpend:Q=>{pe=Q},onSwap:(Q,ae)=>{D=Q,L=ae},onActionCalls:Q=>{$=Q}}),[ce,he]=await Promise.all([P(de,j,G,{...le,validateFeeCalls:e.initialFeeEstimate!==void 0}),z?f.relayerService.estimateBatchGas({user:N,outputToken:E.source.address,stepIndex:0,chainBatches:[de[0]],signal:t}):void 0]);if(he&&!(m==="user-transfer"?f.feeAmountsWithinTolerance(q,he.gasFee,e.feeToleranceBps):he.gasFee===q))throw new Error("Source gas changed. Prepare a fresh fee quote.");const X=m==="user-transfer"?Ho(ce,ne):ce,K=f.getSupplyFeePreview(X,O)??f.getEscrowFreeFeePreview(de,O,G);if(!K)return null;const W=Vo(K,ue,o,m);if(JSON.stringify(_,(Q,ae)=>typeof ae=="bigint"?ae.toString():ae)===JSON.stringify(W,(Q,ae)=>typeof ae=="bigint"?ae.toString():ae)||m==="user-transfer"&&f.feeBreakdownsWithinTolerance(_.feeBreakdown,W.feeBreakdown,e.feeToleranceBps)){const Q=m==="user-transfer"?Y:K,ae=B?Qt(q,E.source.decimals,E.destination.decimals,"ceil"):0n;return{batches:de,fundingAmount:G,actionContext:_,sourceSpendCap:pe,destinationAmount:Z,destinationSwap:D,swapInputAmount:L,actionDefinition:$,feeEstimate:m==="user-transfer"?ne:X,sourceGasSkim:q,preview:{...Q,grossAmount:G+ae,netAmount:_.netAmount,gasFee:Q.gasFee+ae,spicenetFee:_.feeBreakdown.spicenetFee,totalFee:_.combinedFeeAmount+ae}}}ne=X,U=de}throw new Error("Fees did not converge. Refresh the quote before submitting.")}class mi extends Error{constructor(t){super("Amount is too small to cover fees. Increase the amount and retry."),this.preview=t,this.name="FeeShortfallError"}}function Vo(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?f.splitFeeInclusiveAmount(t,o,10n):null;if(r&&!r.coversFees)throw new mi({...e,grossAmount:t,netAmount:0n,spicenetFee:0n,totalFee:o});const i=r?.spicenetFee??(s==="user-transfer"?f.calculateBpsFee(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 Gd(e,t){const n=e.selectedAsset?.asset;if(!n||n?._source!=="wallet")return;const s=Jt(n,e.resolvedChainId);if(!s||!f.addressesEqual(s,e.executionTokenAddress))return;const o=v.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),r=Wn(t,o?.decimals??e.destinationToken.decimals,n.decimals);if(r<=n.balance)return;const i=T.formatUnits(r,n.decimals),l=T.formatUnits(n.balance,n.decimals);throw new Error(`Insufficient ${n.symbol} for this total amount. Required ${i} ${n.symbol}; available ${l} ${n.symbol}.`)}function Yd(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=zt(e.selectedAsset.amount,t.decimals);if(n<=t.balance)return n;throw new Error(`Insufficient ${t.symbol} for this total amount. Required ${T.formatUnits(n,t.decimals)} ${t.symbol}; available ${T.formatUnits(t.balance,t.decimals)} ${t.symbol}.`)}function Zd(e,t,n){const s=f.getSupplyFeePreview(e,Yd(t));if(s)return Vo(s,n,!!t.isFeeInclusiveInput,t.feeExecutionMode)}function Xd(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=T.decodeFunctionData({abi:T.erc20Abi,data:l.data});if(c.functionName!=="transfer")continue;const d=c.args[0].toLowerCase(),p=c.args[1];d===v.SPICE_PLATFORM_FEE_RECIPIENT.toLowerCase()?s+=p:d===v.SPICE_GAS_FEE_RECIPIENT.toLowerCase()&&(o+=p)}catch{continue}}return{spicenetFee:s,gasFee:o}}function Jd(e,t,n,s){const o=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,r=Xd(e,t.resolvedChainId,o);return r.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||r.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:f.feeAmountsWithinTolerance(r.spicenetFee,n.feeBreakdown.spicenetFee,t.feeToleranceBps)&&f.feeAmountsWithinTolerance(r.gasFee,n.feeBreakdown.gasFee,t.feeToleranceBps)&&f.feeAmountsWithinTolerance(s.feeBreakdown.bridgeFee,n.feeBreakdown.bridgeFee,t.feeToleranceBps)}function $d(e,t,n){return e?f.amountsWithinBps(e.grossAmount,t.grossAmount,100n)&&f.feeBreakdownsWithinTolerance(e.feeBreakdown,t.feeBreakdown,n):!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}:pi({...t,feeOnlyAction:e.feeOnlyAction,estimate:e.execution.estimate,tokenDescriptor:_d(e,t.fundingToken)})}function hi(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 gi(e,t){const n=f.sanitizeError(t,"Payment failed. Please try again.");e.ui.setError(n),e.ui.setPaymentResult({status:"failed",error:n})}async function xi(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?gi(e,t):hi(e,t,!1)}finally{e.ui.setIsExecuting(!1)}}async function yi(e,t,n){e.validateFeeQuote?.();const s=e.feeQuote;if(!s.batches||s.sourceSpendCap===void 0||!s.fundingSource)throw new Error("Refresh the action before submitting.");const o=s.fundedFeeToken,r=s.grossFundingAmount??0n,i=_a({...e,signal:n,feeOnlyAction:!0,destinationToken:o,actionProceeds:e.actionProceeds??{token:s.fundingSource.token,resolve:async()=>s.proceedsAvailable??0n}},o.address,r);return e.execution.execute(s.batches,s.fundingConversion?.tokenIn??s.fundingSource.token,r,t,n,{...i,userOverride:e.embeddedWalletAddress||e.providerEmbeddedAddress,useCustomTransfers:!0,feeExecutionMode:"backend-transfer",skipPreSubmitFeeEstimate:!0})}async function wi(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 xi(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;if(e.feeQuote?.fundedFeeToken){const x=await yi(e,e.execution.onProgress,t.signal);e.ui.setTxHash(x),e.ui.setStep("success"),e.ui.setStatusMsg("Transaction confirmed");return}const s=zo(e);s&&Kd(e);const o=e.feeQuote?.batches?e.feeQuote:await An({...e,feeExecutionMode:e.feeExecutionMode,isDirect:!e.needsSwap,isQuoting:!1,resolvedSwap:null,buildPayChainBatches:e.execution.buildPayChainBatches,buildSupplyChainBatches:e.execution.buildSupplyChainBatches,estimate:e.execution.estimate});if(!o?.batches||o.fundingAmount===void 0||!o.actionContext)throw new Error("A current action plan is required. Refresh the quote before submitting.");const r=e.isFeeInclusiveInput?o.actionContext.grossAmount:o.actionContext.netAmount;let i=o.batches;const l=i.some(x=>x.tokenTransfers?.length),c={userOverride:n,useCustomTransfers:l,feeExecutionMode:e.feeExecutionMode,...s?{skipUserFundingPreflight:!0}:{}},d=o.fundingAmount,p=o.actionContext;Gd(e,d);const m=p,h=await e.execution.execute(i,e.executionTokenAddress,l?d:0n,e.execution.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...c,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:x,chainBatches:g})=>{const y=Zd(o.feeEstimate?Ho(x,o.feeEstimate):x,e,r);if(!y)throw new Error("Unable to validate the accepted fees. Refresh the quote before submitting.");const w=$d(m,y,e.feeToleranceBps),C=Jd(g,e,y,m);if(w||C)return null;throw new Error("Transaction fees changed. Refresh the quote before submitting.")}}:{...c,skipPreSubmitFeeEstimate:!0});e.ui.setTxHash(h),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){hi(e,n,t.signal.aborted)}finally{e.ui.setIsExecuting(!1)}}async function bi(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 xi(e);const n=ri(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{if(e.feeQuote?.fundedFeeToken){const S=await yi(e,I=>{I.txHash&&(e.ui.setTxHash(I.txHash),e.ui.setPaymentResult({status:"processing",txHash:I.txHash}))});e.ui.setPaymentResult(I=>({status:"success",txHash:I?.txHash||S}));return}const r=zt(e.currentPaymentAmount,e.destinationToken.decimals),i={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,...n?{skipUserFundingPreflight:!0}:{}};if(t&&!e.feeOnlyAction){const S=await o(),I=await e.execution.execute(S,e.executionTokenAddress,0n,F=>{F.txHash&&(e.ui.setPaymentResult(k=>({...k??{status:"processing"},txHash:F.txHash})),e.ui.setTxHash(F.txHash))},void 0,i);e.ui.setPaymentResult(F=>({status:"success",txHash:F?.txHash||I}));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,p=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:r,m=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,h=!!e.feeQuote?.fundingConversion||!!c&&(c.kind!=="balance"||c.asset?._source==="wallet"),{grossFundingAmount:x,feeEstimate:g}=h?{grossFundingAmount:e.feeQuote.grossFundingAmount??0n,feeEstimate:void 0}:await eu(e,{requiredNetFunding:p,buildBatches:S=>e.execution.buildPayChainBatches({fundingAmountOverride:S}).then(I=>In(I,m)),fundingToken:d,executionOptions:i});let y=e.feeQuote?.fundingBatches??e.feeQuote?.batches??In(await o({fundingAmountOverride:x}),m,e.actionProceeds?void 0:g,{payoutAlreadyGross:!0});const w=_a(e,e.feeQuote?.fundingConversion?.tokenOut??d,x);w.prepareForSigning&&(y=await w.prepareForSigning(y));const C=y.some(S=>S.tokenTransfers?.length),b=await e.execution.execute(y,d,C?x:0n,S=>{S.txHash&&(e.ui.setPaymentResult(I=>({...I,txHash:S.txHash})),e.ui.setTxHash(S.txHash))},void 0,{...i,...w,skipPreSubmitFeeEstimate:!0});e.ui.setPaymentResult(S=>({status:"success",txHash:S?.txHash||b}))}catch(r){gi(e,r)}finally{e.ui.setIsExecuting(!1)}}async function tu(e){const{definition:t,account:n,chainId:s}=e,{calls:o}=t;if(!f.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=f.getClientForChain(s);let i;for(const l of o){await e.assertCurrent();const[c,d]=await Promise.all([Fa({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:p,viemChain:m}=await Ro({wallet:e.wallet,account:n,chainId:s});i=await Xc({extWc:p,viemChain:m,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}async function Ci(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=f.getClientForChain(t.chainId),i=t.isNative||v.isNativeToken(t.address),[l,c]=await Promise.all([Ta({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:p}=await Ro({wallet:e.externalWallet,account:s,chainId:t.chainId});await Jc({extWc:d,sourceClient:r,recipient:n,tokenAddr:t.address,isNative:i,amount:o,viemChain:p,observer:{onSending:()=>e.assertCurrent()}})}function vi(e){const t=u.useContext(f.SpiceFlowProviderContext),n=f.getChainConfig(e.chainId),s=e.address??n?.supportedTokens?.find(g=>g.symbol.toLowerCase()===e.symbol?.toLowerCase())?.address,o=e.symbol??(s&&v.isNativeToken(s)?n?.nativeCurrency?.symbol:n?.supportedTokens?.find(g=>!!s&&f.addressesEqual(g.address,s))?.symbol),r=f.getRpcUrlForChain(e.chainId,t?.rpcOverrides),[i,l]=u.useState(0),c=`${e.chainId}:${s?.toLowerCase()}:${r}:${e.decimals??""}:${o??""}:${i}`,[d,p]=u.useState(null);u.useEffect(()=>{let g=!1;if(!(!e.enabled||!s||!r?.trim()))return Promise.all([e.decimals??f.getTokenDecimals(e.chainId,s,t?.rpcOverrides),o??_t.readContract(f.getClientForChain(e.chainId,t?.rpcOverrides),{address:s,abi:T.erc20Abi,functionName:"symbol"}).catch(()=>{})]).then(([y,w])=>{if(!Number.isInteger(y)||y<0||y>255)throw new Error("Invalid destination token decimals");g||p({key:c,decimals:y,symbol:w})}).catch(y=>{g||p({key:c,error:y.message})}),()=>{g=!0}},[e.enabled,c]);const m=d?.key===c?d:null,h=u.useMemo(()=>({address:s??v.ZERO_ADDRESS,chainId:e.chainId,decimals:m?.decimals??0,symbol:o??m?.symbol??(s?f.truncateAddress(s):""),logoURI:e.logoURI}),[s,e.chainId,m?.decimals,m?.symbol,o,e.logoURI]),x=e.enabled?s?r?.trim()?m?.error??null:`Configure SpiceFlowProvider rpcOverrides[${e.chainId}] before continuing.`:"Configure the destination token address before continuing.":null;return{token:h,error:x,ready:e.enabled&&!!s&&!!r?.trim()&&m?.decimals!==void 0,refresh:u.useCallback(()=>l(g=>g+1),[])}}function ki(e,t){const n=!!e&&e.symbol!==void 0&&e.decimals!==void 0,s=vi({enabled:t&&!!e&&!n,chainId:e?.chainId??0,address:e?.address,decimals:e?.decimals,symbol:e?.symbol,logoURI:e?.logoURI});return{token:e?n?e:s.ready?s.token:void 0:void 0,error:s.error}}const Qo={address:v.ZERO_ADDRESS,symbol:"",decimals:18,chainId:0};function Si(e,t,n){return f.addressesEqual(e.address,t)&&e.chainId===n?e._source==="wallet"?0:1:2}function nu(e,t,n,s){const o=Si(e,n,s)-Si(t,n,s);return o!==0?o:(t.balanceUsd||0)-(e.balanceUsd||0)}const su=qr;function Ii(e){const t=u.useContext(f.SpiceFlowProviderContext),n=f.useProviderWallets(),s=t?.embeddedWalletAddress||n.embeddedAddress,o=t?.externalWalletAddress||n.externalAddress,r=(t?.mode||"7702")!=="7702",i=e.destinationToken??Qo,l=e.enabled&&!!e.destinationToken,c=Nn({...e,owner:s,enabled:l&&!!s&&(!r||e.includeCrossChainEmbeddedAssets!==!1),role:"spend-source",destination:e.destinationToken}),d=Nn({...e,owner:o,enabled:l&&!!o&&(r||e.includeExternalWalletAssets!==!1),role:"spend-source",destination:e.destinationToken});return{displayAssets:u.useMemo(()=>[...c.assets,...d.assets].sort((p,m)=>nu(p,m,i.address,i.chainId)),[c.assets,d.assets,i.address,i.chainId]),filteredSpiceAssets:c.rollupAssets,walletAssets:[...c.walletAssets,...d.walletAssets],embeddedWalletAddress:s,externalAddress:o,isNon7702:r,refreshSpiceAssets:c.refresh,refreshWalletAssets:c.refresh,loading:c.loading||d.loading,refreshing:c.refreshing||d.refreshing,error:c.error||d.error}}function ou(e,t){return!e||e._source!=="wallet"?null:fo(e,t)}function Go(e){return Cr({aerodrome:!1,oneInch:{chainIds:[]},customVenues:e})}const Yo=Bn(),ru=Go(Yo.input);function Ai(e){return{venue:"mapped-transfer",amountOut:e,amountOutMinimum:e,calls:[]}}function Ei(e){return{venue:"mapped-transfer",amountIn:e,amountInMax:e,amountOut:e,calls:[]}}async function Ko(e){if(f.addressesEqual(e.tokenIn,e.tokenOut))return Ai(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?Go(Bn(e.liquidityVenues).input):ru).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 au(e){return f.addressesEqual(e.tokenIn,e.tokenOut)?Ei(e.amountOut):Ls({customVenues:e.liquidityVenues?Bn(e.liquidityVenues).output:Yo.output}).getQuote({tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountOut:e.amountOut,maxSlippage:e.maxSlippage},e.chainId,e.recipient)}function Fi(e){const{enabled:t=!0,direction:n,selectedAsset:s,destinationToken:o,chainId:r=o.chainId,recipient:i,paymentAmount:l,maxSlippage:c,refreshIntervalMs:d,resolveInputSwap:p,resolveExactOutputSwap:m}=e,h=u.useContext(f.SpiceFlowProviderContext),x=h?.liquidityVenues,g=JSON.stringify([h?.network,h?.apiUrl,h?.rpcOverrides]),[y,w]=u.useState(!1),[C,b]=u.useState(null),[S,I]=u.useState(null),[F,k]=u.useState(null),[E,R]=u.useState(null),[j,A]=u.useState(null),[M,P]=u.useState(null),[N,B]=u.useState(null),[U,O]=u.useState(null),[z,q]=u.useState(null),[ue,le]=u.useState(null),[G,ne]=u.useState(null),[re,Y]=u.useState(null),[_,Z]=u.useState(null),[pe,D]=u.useState(0),[L,$]=u.useState(null),[de,ce]=u.useState(null),he=u.useRef(null),X=u.useRef(null),K=u.useRef(0),W=u.useRef(new Map),Q=u.useCallback(()=>{K.current++,W.current.clear(),ce(null),D(Re=>Re+1)},[]),ae=d&&d>0?d:null,we=x?JSON.stringify(x):"",ke=u.useMemo(()=>x?Bn(x):Yo,[we]),Ie=u.useMemo(()=>Go(ke.input),[ke]),be=u.useMemo(()=>Ls({customVenues:[...m?[{name:"consumer-exact-output",chainIds:[r],preferred:!0,resolve:m}]:[],...ke.output]}),[m,r,ke]);u.useEffect(()=>{W.current.clear()},[be]);const J=u.useMemo(()=>t?ou(s?.asset,r):null,[t,s?.asset,r]),Ye=u.useMemo(()=>{if(!t||!s?.asset)return null;if(J)return J.destination.address;const Re=Jt(s.asset,r);if(Re)return Re;const _e=fn(s.asset.address,r,s.asset.chainId);return _e?_e.address:null},[t,s?.asset,r,J]),Ne=u.useMemo(()=>t&&s?.asset?Rn(s.asset,r):[],[t,s?.asset,r]),dt=u.useMemo(()=>Ne.map(Re=>Re.toLowerCase()).join(","),[Ne]),rt=JSON.stringify([t,g,s?.asset.owner,s?.asset.location,s?.asset.receiptTokenId,s?.asset.address,s?.asset.chainId,s?.asset.decimals,s?.amount,r,dt,n,l]);u.useEffect(()=>{let Re=!1;if(X.current&&(clearTimeout(X.current),X.current=null),!t||!s?.asset||J||Ne.length<=1){Y(null),Z(null);return}return X.current=setTimeout(async()=>{const _e=n==="input"?s.amount:l||"0";let He=0n;try{He=n==="input"?zt(_e,s.asset.decimals):0n}catch{He=0n}try{const et=await Wr(s.asset,r,{requiredAmount:He});Re||(Y(et),Z(rt))}catch{Re||Y(null)}},400),()=>{Re=!0,X.current&&(clearTimeout(X.current),X.current=null)}},[rt]);const Me=u.useMemo(()=>(_===rt?re:null)??Ye,[re,_,rt,Ye]),Pe=u.useMemo(()=>!s?.asset||!Me?[]:[Me,...Ne.filter(Re=>Re.toLowerCase()!==Me.toLowerCase())],[s?.asset,Me,Ne]),Xe=u.useMemo(()=>!s?.asset||!Kn(s.asset.address,s.asset.chainId,o.address,o.chainId)||!Me?!1:f.addressesEqual(Me,o.address),[s,o.address,o.chainId,Me]),Ue=Me?f.addressesEqual(Me,o.address):!1,ht=n==="output"&&parseFloat(l||"0")===0,We=t&&!!s?.asset&&!Xe&&!Ue&&!ht,at=JSON.stringify([t,we,n,We,g,s?.asset.owner,s?.asset.location,s?.asset.receiptTokenId,s?.asset.address,s?.asset.chainId,s?.asset.decimals,n==="input"?s?.amount:l,Pe.map(Re=>Re.toLowerCase()),r,o.address.toLowerCase(),o.chainId,o.decimals,i?.toLowerCase(),c,ae,J?.source.address.toLowerCase()??""]),Ae=u.useMemo(()=>({}),[at,Ie,be,p,pe]),Qe=de?.request===Ae&&(!ae||de.expiresAt>Date.now());return u.useEffect(()=>{if(!ae||de?.request!==Ae)return;const Re=setTimeout(Q,Math.max(0,de.expiresAt-Date.now()));return()=>clearTimeout(Re)},[ae,de,Ae,Q]),u.useEffect(()=>{he.current&&clearTimeout(he.current),$(Ae),ce(null),b(null);const Re=n==="input"?s?.amount:l,_e=parseFloat(Re||"0");if(!t||!Number.isFinite(_e)||_e<=0||!s?.asset||!i||Pe.length===0){K.current++,I(null),k(null),R(null),A(null),P(null),B(null),O(null),ne(null),b(null),w(!1);return}const He=s.asset.decimals;let et;try{et=n==="input"?zt(s.amount,He):zt(l||"0",o.decimals)}catch(Fe){K.current++,b(Fe instanceof Error?Fe.message:"Invalid amount or token precision"),w(!1);return}const ut=++K.current,tt=()=>ut!==K.current;w(!0);const Ee=n==="output"?150:100,st=async(Fe,ee,te,De={chainId:r,tokenOut:o.address,amountIn:et},ye=Pe)=>{for(const ie of ye){const je=`${g}:${we}:${n}:${De.chainId}:${ie.toLowerCase()}:${De.tokenOut.toLowerCase()}:${De.amountIn.toString()}:${i.toLowerCase()}:${c??"default"}:${ae??"default"}`,ve=W.current.get(je),V=ve&&ve.expiresAt>Date.now()?Fe(ve):void 0;if(V)return{quote:V,tokenIn:ie,expiresAt:ve.expiresAt};const Le=await te(ie);if(tt())return"stale";if(!Le)continue;const me=Date.now()+Math.min(ae??3e4,3e4);return W.current.set(je,{expiresAt:me,direction:n,...ee(Le)}),{quote:Le,tokenIn:ie,expiresAt:me}}return null},gt=Fe=>st(ee=>ee.resolvedSwap,ee=>({resolvedSwap:ee}),async ee=>{const te=!J&&Fe.chainId===r&&s.asset._source!=="wallet",De=te?await xn(s.asset,ee,Fe.chainId,o):He;if(tt())return null;const ye=te?Os(Fe.amountIn,He,De):Fe.amountIn;if(f.addressesEqual(ee,Fe.tokenOut))return Ai(ye);const ie={type:"swap",tokenIn:ee,tokenOut:Fe.tokenOut,amountIn:ye,maxSlippage:c};if(p){const je=await p(ie,Fe.chainId,i);if(je)return je}return Ie.resolveSwap(ie,Fe.chainId,i)},Fe,Fe.candidates);return he.current=setTimeout(async()=>{try{if(n==="input"){let Fe=null,ee=et;if(J){if(Fe=await gt({chainId:J.source.chainId,tokenOut:J.source.address,amountIn:et,candidates:[s.asset.address]}),Fe==="stale"||tt())return;if(!Fe)throw new Error("No liquidity for this pair");ee=Qt(Fe.quote.amountOutMinimum,J.source.decimals,J.destination.decimals,"floor")}const te=We||!J?await gt({chainId:r,tokenOut:o.address,amountIn:ee,candidates:Pe}):null;if(te==="stale"||tt())return;if(We&&!te)throw new Error("No liquidity for this pair");const De=te?te.quote.amountOut:ee,ye=Math.min(te?.expiresAt??1/0,Fe?.expiresAt??1/0),ie=J?.destination.decimals??await xn(s.asset,te.tokenIn,r,o),je=!J&&s.asset._source!=="wallet"?Os(ee,He,ie):ee;if(tt())return;ne(te?.tokenIn??J?.destination.address??null),ce({request:Ae,key:`${T.keccak256(T.toHex(at))}:${ut}`,expiresAt:ye}),O(De),q(je),le(ie),R(We?te?.quote??null:null),A(Fe?.quote??null),P(null),B(null);const ve=parseFloat(T.formatUnits(De,o.decimals));I(ve<.01?ve.toPrecision(4):ve.toLocaleString(void 0,{maximumFractionDigits:6})),k(null),b(null)}else{const Fe=je=>st(ve=>ve.exactOutputSwap,ve=>({exactOutputSwap:ve}),async ve=>{try{return f.addressesEqual(ve,je.tokenOut)?Ei(je.amountOut):await be.getQuote({tokenIn:ve,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),ee=!J||We,te=ee?await Fe({chainId:r,tokenOut:o.address,amountOut:et,candidates:Pe}):null;if(te==="stale"||tt())return;if(ee&&!te)throw new Error("No liquidity for this pair");let De=null;if(J){const je=te?te.quote.amountInMax:et;if(De=await Fe({chainId:J.source.chainId,tokenOut:J.source.address,amountOut:Qt(je,J.destination.decimals,J.source.decimals,"ceil"),candidates:[s.asset.address]}),De==="stale"||tt())return;if(!De)throw new Error("No liquidity for this pair")}const ye=De?He:await xn(s.asset,te.tokenIn,r,o);if(tt())return;ne(te?.tokenIn??J?.destination.address??null),ce({request:Ae,key:`${T.keccak256(T.toHex(at))}:${ut}`,expiresAt:Math.min(te?.expiresAt??1/0,De?.expiresAt??1/0)}),B(te?.quote??null),P(De?.quote??null),R(null),A(null),O(null);const ie=De?.quote.amountIn??te.quote.amountIn;k(T.formatUnits(ie,ye)),I(null),b(null)}}catch(Fe){if(tt())return;const ee=Fe instanceof Error?Fe.message:"Failed to get quote";b(ee),I(null),k(null),R(null),A(null),P(null),B(null),O(null),ne(null)}finally{tt()||w(!1)}},We||J?Ee:0),()=>{K.current++,he.current&&clearTimeout(he.current)}},[Ae]),{inputAmount:Qe&&n==="input"?z:null,inputDecimals:Qe&&n==="input"?ue:null,quoteKey:Qe?de.key:null,quoteExpiresAt:Qe?de.expiresAt:null,refreshQuote:Q,isQuoting:L===Ae?y:We||!!J,quoteError:L===Ae?C:null,estimatedOutput:Qe?S:null,estimatedInput:Qe?F:null,resolvedSwap:Qe?E:null,exactOutputSwap:Qe?N:null,quoteAmountOut:Qe?U:null,resolvedTokenIn:We&&Qe?G??Me:Me,isDirect:Ue,needsSwap:We,selectedIsEquivalent:Xe,sourceSwap:Qe?j:null,sourceExactOutputSwap:Qe?M:null,pivot:J}}function cs(e){const{enabled:t=!0,destinationToken:n,selectedAsset:s,paymentAmount:o="0",sourceChains:r,supportedSourceAssets:i,buildActionCalls:l,feeExecutionMode:c="user-transfer",buildSpicenetBatch:d,onPayExecute:p,resolveExactOutputSwap:m,amountDirection:h=e.feeOnlyAction?"output":"input",onSuccess:x,onError:g}=e,y=ki(n,t),w=y.token??Qo,C=t&&!!y.token,b=h==="output",S=h==="input-inclusive",I=e.feeFunding?.length!==0&&(e.actionProceeds==="output"||!!e.feeFunding?.length),F=b?"output":"input",k=w.chainId,E=u.useContext(f.SpiceFlowProviderContext),R=f.resolveFeeToleranceBps(E?.feeToleranceBps),j=E?.mode||"7702",A=!1,M=!!E?.isWhitelistGateActive,P=!!E?.isWhitelistConfigured&&E?.isUserWhitelisted!==!0,N=u.useMemo(()=>r??E?.supportedChainIds??[],[r,E?.supportedChainIds]),B=i,{address:U,isConnected:O,isReady:z,isAuthenticated:q,provider:ue}=f.useWallet(),{execute:le,estimate:G}=Fs(),{externalWallet:ne,embeddedAddress:re,activeWallet:Y,activeAddress:_}=f.useProviderWallets(),Z=E?.externalWalletAddress,pe=E?.embeddedWalletAddress||re,D=s,L=ws(D?.asset,j!=="7702"),$=!!D&&D.asset.chainId===w.chainId&&f.addressesEqual(v.normalizeNativeTokenAddress(D.asset.address),v.normalizeNativeTokenAddress(w.address)),de=j!=="7702"&&L&&$&&(!b||Number(o)>0)&&!e.feeOnlyAction&&!e.actionProceeds,ce=L&&!de,he=y.error?y.error:p?"Move onPayExecute protocol calls to buildActionCalls and application updates to onSuccess before continuing.":e.actionExecution?.wallet==="external"&&!de?"This action requires the external wallet as its caller. Select its destination token on the destination chain for direct execution, or configure a beneficiary-capable embedded action for routing.":null,{displayAssets:X,filteredSpiceAssets:K,walletAssets:W,embeddedWalletAddress:Q,refreshSpiceAssets:ae,refreshWalletAssets:we,loading:ke,refreshing:Ie,error:be}=Ii({address:U,destinationToken:w,supportedSourceAssets:B,sourceChains:N,additionalSourceTokens:[...e.additionalSourceTokens??[],...D?.asset._source==="wallet"?[{address:D.asset.address,chainId:D.asset.chainId,decimals:D.asset.decimals,symbol:D.asset.symbol,name:D.asset.name,logoURI:D.asset.logoURI}]:[]],includeExternalWalletAssets:e.includeExternalWalletAssets,includeCrossChainEmbeddedAssets:e.includeCrossChainEmbeddedAssets,enabled:C&&(j!=="7702"?!!Z:!!pe)}),J=X,Ye=u.useMemo(()=>e.feeOnlyAction||I?J.filter(se=>se.balance>0n&&se.location!=="external"&&(se._source==="spice"||se._source==="wallet"&&se.chainId===k)):[],[J,e.feeOnlyAction,I,k]),Ne=D?[...W,...K].find(se=>Ge(se)===Ge(D.asset)):void 0,dt=u.useMemo(()=>D&&Ne?{...D,asset:Ne}:D,[D,Ne]),rt=D?kn(Ne??D.asset,"spend-source",{allowedTokens:E?.allowedTokens,rpcOverrides:E?.rpcOverrides,liquidityVenues:E?.liquidityVenues,isWhitelistGateActive:M},w,B):null,Me=Ne?Ne.balance<(D?.asset.balance??0n)?Ne.balance:D.asset.balance:0n,[Pe,Xe]=u.useState(!1),[Ue,ht]=u.useState(null),We=u.useRef(g);We.current=g;const at=u.useCallback(se=>{ht(se),typeof se=="string"&&se&&We.current?.(new Error(se),f.getRelayerErrorDetail(se))},[]),[Ae,Qe]=u.useState("idle"),[Re,_e]=u.useState(""),[He,et]=u.useState(null),[ut,tt]=u.useState(!1),[Ee,st]=u.useState(null),[gt,Fe]=u.useState(null),[ee,te]=u.useState(!1),[De,ye]=u.useState(!1),[ie,je]=u.useState(null),ve=u.useRef(D),V=u.useRef(!1),Le=u.useRef(null),me=u.useRef(null),ze=u.useRef(null),vt=u.useRef(null),kt=u.useRef(null),Se=u.useRef(null),yt=u.useRef(x),wt=u.useRef(null),it=u.useRef(!1),[nn,mn]=u.useState(null),[Gt,an]=u.useState(null),[Yt,It]=u.useState(!1),[Ft,Wt]=u.useState(0),Bt=Ee?.status==="success"?Ee.txHash:Ae==="success"?He:null,Tt=!!Bt&&nn!==Bt,Mt=u.useRef(Tt);Mt.current=Tt,u.useEffect(()=>{ve.current=D},[D]);const Ke=de?Z:Q||re||U,qe=C&&!Pe&&Ae==="idle"&&!he&&!P&&!!Ke&&!de&&!b&&S&&c==="user-transfer"&&!e.feeOnlyAction&&!e.actionInput&&!e.actionProceeds&&!!D&&Number(D.amount||"0")===0&&!!rt?.eligible&&Me>0n,Rt=u.useMemo(()=>{if(!qe||!D)return D;const se=10n**BigInt(D.asset.decimals);return{...D,amount:T.formatUnits(Me<se?Me:se,D.asset.decimals)}},[qe,D,Me]),Kt=Fi({enabled:C&&!P&&!de,direction:F,selectedAsset:Rt,destinationToken:w,chainId:k,recipient:Ke,paymentAmount:o,resolveExactOutputSwap:m,resolveInputSwap:e.resolveInputSwap,maxSlippage:e.maxSlippage}),Dt=de?{...Kt,quoteKey:"direct-external",quoteExpiresAt:null,quoteAmountOut:null,inputAmount:null,inputDecimals:D?.asset.decimals??null,isQuoting:!1,quoteError:null,isDirect:!0,needsSwap:!1,selectedIsEquivalent:!0,resolvedTokenIn:w.address,resolvedSwap:null,exactOutputSwap:null,sourceSwap:null,sourceExactOutputSwap:null,pivot:null,estimatedInput:b?o:D?.amount??null,estimatedOutput:b?o:D?.amount??null}:Kt,Be=Dt,{isQuoting:Lt,resolvedSwap:Te,exactOutputSwap:Ot,quoteAmountOut:pt,resolvedTokenIn:nt,isDirect:ln,needsSwap:Vt,selectedIsEquivalent:zn,sourceSwap:oe,sourceExactOutputSwap:fe,pivot:xe}=Dt,Ve=b?parseFloat(o||"0"):parseFloat(D?.amount||"")||0,St=D?.asset?._source==="wallet",ft=!!D?.asset&&St&&D.asset.chainId!==k,Pt=D?Number(T.formatUnits(Me,D.asset.decimals)):0,Ut=u.useMemo(()=>{if(!D||b)return!1;try{return zt(D.amount||"0",D.asset.decimals)>Me}catch{return!0}},[D,b,Me]);u.useEffect(()=>{C||(at(null),Xe(!1),Tt||(Qe("idle"),_e(""),et(null),tt(!1),st(null)),Fe(null),te(!1),ye(!1),je(null),V.current=!1,Le.current&&(Le.current.abort(),Le.current=null))},[C,Tt]);const qt=u.useCallback(se=>{Qe({building:"building","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[se.step]||"executing"),_e(se.message),se.txHash&&et(se.txHash)},[]),At=u.useMemo(()=>({currentPaymentAmount:o,isFeeInclusiveInput:S,feeOnlyAction:e.feeOnlyAction,swapInputAmount:Dt.inputAmount,destinationToken:w,embeddedWalletAddress:Q,providerEmbeddedAddress:re,externalWalletAddress:Z,address:U,recipient:e.recipient??(j!=="7702"?Z:void 0),isNon7702:A,isPayMode:b,resolvedChainId:k,buildActionCalls:l,feeExecutionMode:c,buildSpicenetBatch:d,selectedAsset:D,needsSwap:Vt,resolvedSwap:Te,exactOutputSwap:Ot,quoteAmountOut:pt,resolvedTokenIn:nt,sourceSwap:oe,sourceExactOutputSwap:fe,pivot:xe,resolveSourceExactOutputSwap:async se=>{if(!xe||!Ke)throw new Error("Swap route is not ready.");const $e=await au({chainId:xe.source.chainId,recipient:Ke,tokenIn:D.asset.address,tokenOut:xe.source.address,amountOut:se,liquidityVenues:E?.liquidityVenues,maxSlippage:e.maxSlippage}).catch(()=>null);if(!$e)throw new Error("No liquidity for this pair.");return $e},resolveInputSwap:async(se,$e)=>{if(!nt||!Ke)throw new Error("Swap route is not ready.");return Ko({chainId:k,recipient:Ke,tokenIn:nt,tokenOut:w.address,amountIn:se,selectedSwap:$e,liquidityVenues:E?.liquidityVenues,maxSlippage:e.maxSlippage,resolveInputSwap:e.resolveInputSwap})}}),[o,w,Q,re,Z,U,e.recipient,e.feeOnlyAction,e.maxSlippage,e.resolveInputSwap,Dt.inputAmount,S,j,A,b,k,l,c,d,D,Vt,Te,Ot,pt,nt,oe,fe,xe,Ke,E?.liquidityVenues]),Nt=u.useMemo(()=>D?.asset?xe?xe.destination.address:Vt&&nt?nt:D.asset.chainId===k?D.asset.address:nt??Jt(D.asset,k)??w.address:w.address,[D,w.address,Vt,k,nt,xe]),bt=JSON.stringify([D&&Ge(D.asset),h,w.address,w.chainId,w.decimals,e.recipient,j,Z,de?Z:Q,E?.apiUrl,E?.rpcOverrides,e.maxSlippage,c,R,e.feeOnlyAction,e.actionProceeds==="output"?"output":e.actionProceeds?.token,e.feeFunding,e.actionInput?.map(se=>[se.token,se.amount.toString()]),e.feeFundingReserve&&Ge(e.feeFundingReserve.asset),e.feeFundingReserve?.amount.toString(),E?.liquidityVenues,E?.allowedTokens,M,B,N,e.actionInput,e.actionProceeds,e.feeFunding,k,Nt,Be.pivot?.source.address,Be.pivot?.destination.address],(se,$e)=>typeof $e=="bigint"?$e.toString():$e),vn=u.useRef(null);vn.current=C&&!Pe&&!he&&!P?bt:null,u.useEffect(()=>()=>{kt.current?.controller.abort(),kt.current=null},[bt,C,Pe,he,P]);const Et=T.keccak256(T.stringToHex(JSON.stringify([bt,D?.amount,o]))),Zt=u.useRef({key:Et,enabled:C,sourceBalance:Me,sourceEligible:rt?.eligible});Zt.current={key:Et,enabled:C,sourceBalance:Me,sourceEligible:rt?.eligible};const $t=u.useRef(null),Xt=u.useRef(!1),hn=u.useRef(e.onSubmit);hn.current=e.onSubmit;const Fn=u.useCallback(()=>Xt.current?(Xt.current=!1,hn.current?.(),yt.current=Se.current.onSuccess,$t.current={key:Zt.current.key,quote:Se.current.feeQuote},wi(Se.current)):Promise.resolve(),[]),H=de,ge=P,Oe=!ze.current?.quote.fundedFeeToken&&(S||!!xe)&&!!gt&>.netAmount===0n,Ce=u.useMemo(()=>!!e.feeOnlyAction||(!!D?.asset||!!e.actionProceeds)&&Ve>0,[D,Ve,e.actionProceeds,e.feeOnlyAction]),ot=u.useMemo(()=>!C||!Ce||!D?.asset&&!e.actionProceeds&&!e.feeOnlyAction?null:[Et,b?"pay":"supply",h,D?Ge(D.asset):"sdk-funded",e.actionInput?.map(se=>`${se.token.toLowerCase()}:${se.amount}`).join(",")??"",e.feeFunding?.join(",")??"",JSON.stringify(E?.rpcOverrides),E?.apiUrl,e.recipient,D?.asset.address.toLowerCase(),D?.asset.chainId,D?.amount,o,w.address.toLowerCase(),w.chainId,k,Be.resolvedTokenIn?.toLowerCase()??"",Be.quoteKey,Be.needsSwap?"swap":"direct",Be.isDirect?"direct-token":"routed-token","7702",$?"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()??"",Q??"",re??"",U??""].join("|"),[C,Et,e.actionProceeds,e.feeOnlyAction,e.actionInput,e.feeFunding,Pe,Ae,Ce,H,D,b,h,o,w,k,Be,A,$,Q,re,U]),Ze=u.useCallback(async(se,$e,Ct)=>{if(de){if(!Z||!D)throw new Error("Connect the external wallet before continuing.");return Hd({selectedAsset:$e?.selectedAsset??D,destinationToken:w,paymentAmount:b?o:void 0,account:Z,beneficiary:e.recipient,buildActionCalls:l,feeExecutionMode:c})}const lt={...Ct??{...At,selectedAsset:Rt},requestTimestampMs:Date.now()},Je={signal:se,feeToleranceBps:R,feeOnlyAction:e.feeOnlyAction,actionInput:e.actionInput,actionProceeds:e.actionProceeds==="output"?void 0:e.actionProceeds,feeFunding:e.feeFunding,feeFundingBalances:Ye,feeFundingReserve:e.feeFundingReserve,liquidityVenues:E?.liquidityVenues,maxSlippage:e.maxSlippage,resolveExactOutputSwap:m,selectedAsset:Rt,isPayMode:b,isFeeInclusiveInput:S,parsedAmount:qe?Number(Rt.amount):Ve,needsSwap:Be.needsSwap,exactOutputSwap:Be.exactOutputSwap,isNon7702:A,isSourceDestToken:$,currentPaymentAmount:o,destinationToken:w,feeExecutionMode:c,resolvedTokenIn:Be.resolvedTokenIn,embeddedWalletAddress:Q,providerEmbeddedAddress:re,resolvedChainId:k,isConnected:O,address:U,ready:z,authenticated:q,isDirect:Be.isDirect,resolvedSwap:Be.resolvedSwap,sourceSwap:Be.sourceSwap,sourceExactOutputSwap:Be.sourceExactOutputSwap,pivot:Be.pivot,isQuoting:Be.isQuoting,executionTokenAddress:Nt,buildPayChainBatches:ct=>Us(lt,ct),buildSupplyChainBatches:ct=>Ws(lt,ct),estimate:G,...$e},mt=!Je.feeOnlyAction&&Je.selectedAsset&&I&&Je.selectedAsset.asset._source==="wallet"&&Je.selectedAsset.asset.chainId===k;if(I&&!Je.feeOnlyAction&&Je.selectedAsset&&!mt&&e.feeFunding&&e.feeFunding.join(",")!==qo.join(","))throw new Error("Fee-source overrides require a wallet source on the action chain.");return mt||I&&e.actionProceeds==="output"?qd(Je,lt,An,e.actionProceeds==="output"):An(Je)},[D,I,Rt,qe,de,Z,e.recipient,l,e.feeOnlyAction,e.actionInput,e.actionProceeds,e.feeFunding,Ye,e.feeFundingReserve,e.maxSlippage,m,R,E?.liquidityVenues,b,S,Ve,Be,A,$,o,w,c,Q,re,At,G,k,O,U,z,q,Nt]);u.useEffect(()=>{me.current=Ze},[Ze]);const gn=u.useCallback(async se=>{if(b)return null;if(!D||Ge(se)!==Ge(D.asset)||!Ke||!nt)throw new Error("Select a source before calculating Max.");let $e=se.balance;if(de){if(!se.isNative&&!v.isNativeToken(se.address))return T.formatUnits($e,se.decimals);const Ct=f.getClientForChain(se.chainId),lt=Z;let Je=$e;for(let mt=0;mt<8;mt++){const ct=await Ze(void 0,{selectedAsset:{asset:se,amount:T.formatUnits(mt===0?1n:Je,se.decimals)}});if(!ct?.actionDefinition)throw new Error("The direct action could not be sized.");const Ht=await Fa({client:Ct,account:lt,calls:ct.actionDefinition.calls}),Ks=$e>Ht?$e-Ht:0n;if(Ks===0n)return"0";if(mt>0&&Je<=Ks)return T.formatUnits(Je,se.decimals);Je=Ks}throw new Error("Network gas could not be reserved for Max. Enter a smaller amount.")}if(ce&&(se.isNative||v.isNativeToken(se.address))){if(!Z)throw new Error("Connect the source wallet before calculating Max.");const Ct=await Ta({client:f.getClientForChain(se.chainId),account:Z,recipient:Ke,token:se.address,isNative:!0,amount:1n});$e-=Ct}return I&&S&&se._source==="wallet"&&se.chainId===k?T.formatUnits($e>0n?$e:0n,se.decimals):fi({balance:$e,decimals:se.decimals,planForAmount:async Ct=>{const lt={...At,requestTimestampMs:Date.now(),selectedAsset:{asset:se,amount:T.formatUnits(Ct,se.decimals)}};let Je=Ct;xe?(lt.sourceSwap=await Ko({chainId:se.chainId,recipient:Ke,tokenIn:se.address,tokenOut:xe.source.address,amountIn:Ct,maxSlippage:e.maxSlippage,liquidityVenues:E?.liquidityVenues,resolveInputSwap:e.resolveInputSwap}),Je=Qt(lt.sourceSwap.amountOutMinimum,xe.source.decimals,xe.destination.decimals,"floor")):Je=Os(Ct,se.decimals,await xn(se,nt,k,w)),lt.resolvedSwap=Vt?await lt.resolveInputSwap(Je):null,lt.swapInputAmount=Je,lt.quoteAmountOut=lt.resolvedSwap?.amountOut??Je;const mt=I&&se._source==="wallet"&&se.chainId===k,ct=await Ze(void 0,{selectedAsset:lt.selectedAsset,...mt?{isFeeInclusiveInput:!0}:{},parsedAmount:Number(lt.selectedAsset.amount),sourceSwap:lt.sourceSwap,resolvedSwap:lt.resolvedSwap,isQuoting:!1,buildSupplyChainBatches:Ht=>Ws(lt,Ht)},lt);return mt&&ct?.fundingSource?.kind==="input"&&!S?{...ct,sourceSpendCap:Ct+(Ct-ct.swapInputAmount)}:ct}})},[D,I,At,b,de,Ke,nt,k,w,ce,Z,xe,Vt,Ze,e.maxSlippage,e.resolveInputSwap,e.actionProceeds,e.feeFunding,S,E?.liquidityVenues]);So({shouldRun:C&&!Pe&&Ae==="idle"&&(Ce||qe)&&!Be.isQuoting&&(!!ot||qe),deps:[C,Pe,Ae,Ce,H,Be.isQuoting,ot,qe,bt],onSkip:()=>{if(!C){vt.current=null,te(!1),ye(!1),je(null),Fe(null);return}if(Pe||Ae!=="idle"){te(!1);return}if(!Ce){Fe(null),te(!1),ye(!1),je(null);return}Be.isQuoting&&(te(!1),ye(!1))},onCleanup:()=>te(!1),delayMs:Be.needsSwap||Be.pivot?0:100,backgroundIntervalMs:3e4,run:async({isBackground:se,isCurrent:$e,signal:Ct})=>{if(qe){const Je=vt.current;if(Je?.scope===bt&&Date.now()-Je.at<3e4||kt.current?.scope===bt&&Date.now()-kt.current.at<3e4)return;kt.current?.controller.abort();const mt=new AbortController,ct=me.current?.(mt.signal).then(Ht=>{mt.signal.aborted||vn.current!==bt||!Ht?.feeEstimate||(vt.current={scope:bt,at:Date.now(),feeEstimate:Ht.feeEstimate,sourceGasSkim:Ht.sourceGasSkim})}).catch(Ht=>{mt.signal.aborted||console.debug("[SpiceSupply] fee prewarm unavailable:",Ht)})??Promise.resolve();kt.current={scope:bt,at:Date.now(),controller:mt,promise:ct},await ct;return}const lt=ot;se||(je(null),te(!0));try{if(kt.current?.scope===bt&&await kt.current.promise,Ct.aborted||!$e())return;const Je=vt.current,mt=!b&&Je?.scope===bt&&Date.now()-Je.at<3e4?Je:void 0;let ct;try{ct=await me.current?.(Ct,mt?{initialFeeEstimate:mt.feeEstimate,initialSourceGasSkim:mt.sourceGasSkim}:void 0)}catch(Ht){if(!mt||Ct.aborted||!$e())throw Ht;ct=await me.current?.(Ct)}if(!$e())return;ct&<?(ze.current={key:lt,quote:ct},ct.feeEstimate&&(vt.current={scope:bt,at:Date.now(),feeEstimate:ct.feeEstimate,sourceGasSkim:ct.sourceGasSkim}),Fe(ct.preview),ye(!0)):(ze.current=null,Fe(null),ye(!1)),je(null)}catch(Je){if(!$e())return;if(se&&ze.current?.key===lt){console.warn("[SpiceSupply] fee refresh failed:",Je);return}const mt=f.sanitizeError(Je,"Unable to calculate fees for this action.");ze.current=null,Fe(Je instanceof mi?Je.preview:null),ye(!1),je(mt)}finally{$e()&&te(!1)}}});const qn=u.useCallback(()=>Xt.current?(Xt.current=!1,hn.current?.(),yt.current=Se.current.onSuccess,$t.current={key:Zt.current.key,quote:Se.current.feeQuote},bi(Se.current)):Promise.resolve(),[]);u.useEffect(()=>{if(!Bt||wt.current===Bt)return;wt.current=Bt;const se=yt.current;it.current=!0,It(!0),an(null),Promise.resolve().then(()=>se?.(Bt)).then(()=>{mn(Bt),ae(),we()}).catch($e=>{an(`Transaction confirmed; application update needs retry: ${f.sanitizeError($e,"Unable to finalize the action")}`)}).finally(()=>{it.current=!1,It(!1)})},[Bt,Ft]);const Hn=Tt&&!Gt,Hs=u.useCallback(()=>{!Mt.current||it.current||(wt.current=null,Wt(se=>se+1))},[]),Vs=u.useCallback(()=>{Mt.current||(tt(!1),st(null),V.current=!1,ae(),we())},[ae,we]),jt=ot&&ze.current?.key===ot?ze.current.quote:null,Qs=(se=!0)=>{if(he)throw new Error(he);if(!Zt.current.enabled||Zt.current.key!==Et)throw new Error("The source, amount, beneficiary or configuration changed. Review the form before continuing.");if((D||e.feeOnlyAction)&&!jt)throw new Error("A current action plan is required. Refresh the quote before submitting.");if(de&&D?.asset.owner&&!f.addressesEqual(D.asset.owner,Z))throw new Error("Reconnect the external wallet that owns the selected asset.");if(se&&D&&(jt?.sourceSpendCap??0n)>Zt.current.sourceBalance)throw new Error("The source balance changed. Review the available amount before continuing.");if(se&&D&&!Zt.current.sourceEligible)throw new Error(rt?.reason??"This source is unavailable.")},Vn=async()=>Qs(),_o=se=>({...se,sourceSpendCap:jt?.sourceSpendCap,minimumDestinationAmount:jt?.destinationAmount}),us=D&&jt?.sourceSpendCap!==void 0?jt.sourceSpendCap>Me:Ut,er={...At,resolvedSwap:jt?.destinationSwap??At.resolvedSwap,swapInputAmount:jt?.swapInputAmount??At.swapInputAmount};let Gs=!1;Se.current={selectedAsset:D,parsedAmount:Ve,currentPaymentAmount:o,isInsufficientBalance:us,isPayMode:b,isFeeInclusiveInput:S,feeOnlyAction:e.feeOnlyAction,actionProceeds:e.actionProceeds==="output"?void 0:e.actionProceeds,validateFeeQuote:()=>Qs(!Gs),isNon7702:A,directExternalAction:de,isSourceDestToken:$,needsSwap:Vt,exactOutputSwap:Ot,selectedIsEquivalent:zn,resolvedTokenIn:nt,sourceSwap:oe,sourceExactOutputSwap:fe,pivot:xe,embeddedWalletAddress:Q,providerEmbeddedAddress:re,externalWallet:ne,externalWalletAddress:Z,activeSignerWallet:Y,activeSignerAddress:_,address:U,isConnected:O,ready:z,authenticated:q,provider:ue,resolvedChainId:k,executionTokenAddress:Nt,destinationToken:w,buildActionCalls:l,feeExecutionMode:c,feeToleranceBps:R,buildSpicenetBatch:d,onPayExecute:p,onSuccess:x,feeQuote:jt,execution:{estimate:(se,$e,Ct,lt)=>G(se,$e,Ct,{...lt,userOverride:Ke}),execute:async(se,$e,Ct,lt,Je,mt)=>{const ct=async()=>Qs(!Gs);if(await Vn(),de){if(!jt?.actionDefinition)throw new Error("The direct action plan is unavailable.");return tu({definition:jt.actionDefinition,account:Z,chainId:w.chainId,wallet:ne,assertCurrent:Vn})}return ce&&D&&(_e("Transfer the selected source to your embedded wallet"),await Ci({asset:D.asset,embedded:Ke,external:Z,externalWallet:ne,amount:jt?.sourceSpendCap??0n,assertCurrent:Vn}),Gs=!0,await ct()),le(se,$e,Ct,lt,Je,{...mt,userOverride:Ke,requireDestinationReceipt:!0,walletFundingRequirement:D?.asset._source==="wallet"&&jt?.sourceSpendCap!==void 0?{chainId:D.asset.chainId,token:D.asset.address,amount:jt.sourceSpendCap}:void 0,validateBeforeSubmit:async Ht=>{await ct(),await mt?.validateBeforeSubmit?.(Ht)}})},buildPayChainBatches:se=>Us(er,_o(se)),buildSupplyChainBatches:se=>Ws(er,_o(se)),onProgress:qt},ui:{setError:at,setStep:Qe,setStatusMsg:_e,setTxHash:et,setIsExecuting:Xe,setShowStatusPanel:tt,setPaymentResult:st},refs:{spiceDepositSubmittedRef:V,abortControllerRef:Le}};const Tn=!!e.isZeroAmountPay&&!e.feeOnlyAction&&b&&Ve===0,Vi=b?(Tn||!!D?.asset||!!e.actionProceeds||!!e.feeOnlyAction)&&Ve>=0&&!us&&!Pe&&(Tn||H||De)&&!ie&&(Tn||e.feeOnlyAction||!Vt||!!Ot)&&(Tn||e.feeOnlyAction||!xe||!!fe)&&!ge:!!D?.asset&&Ve>0&&!us&&!Pe&&(de||De)&&!ie&&!Oe&&(xe?!!oe&&!Lt&&(ln||!!Te):ft||ln||!!Te&&!Lt)&&!ge,tr=!he&&!!Ke&&(!de||!!ne&&(!D?.asset.owner||f.addressesEqual(D.asset.owner,Z)))&&(j==="7702"||!!Z)&&!Tt&&!Yt&&!Gt&&C&&Vi&&(Tn||!D&&(!!e.actionProceeds||!!e.feeOnlyAction)||!!rt?.eligible)&&Ae!=="success"&&Ee?.status!=="success"&&!Dt.quoteError&&(Tn||!!ot&&ze.current?.key===ot);Xt.current=tr;const Ys=u.useCallback(()=>{Mt.current||(Xt.current=!1,ze.current=null,ye(!1),Kt.refreshQuote(),Qe("idle"),at(null),_e(""),st(null),tt(!1))},[Kt.refreshQuote,at]),nr=u.useRef(Et);u.useEffect(()=>{const se=nr.current!==Et;nr.current=Et,(se||f.isUserRejection(Ue))&&Ae==="error"&&!Pe&&$t.current&&$t.current.key!==Et&&Ys()},[Et,Ae,Pe,Ue,Ys]);const Qi=u.useCallback(()=>{tt(!1)},[]),Gi=u.useCallback(()=>{Mt.current||(Qe("idle"),et(null),ae())},[ae]),xt=jt??(ze.current?.key.startsWith(`${Et}|`)?ze.current.quote:null)??($t.current?.key===Et?$t.current.quote:null),Yi=async se=>{if(de)throw new Error("This source executes directly from the external wallet; submit the action without embedded funding.");if(!(!ce||!D)){if(!jt||se!==jt.sourceSpendCap)throw new Error("Use the displayed source funding maximum before preparing this action.");await Vn(),await Ci({asset:D.asset,embedded:Ke,external:Z,externalWallet:ne,amount:se,assertCurrent:Vn})}};return{selectedAsset:dt,capability:rt,assets:{selectable:J,displayAssets:J,filteredSpiceAssets:K,embeddedWalletAddress:Q,externalAddress:Z,isNon7702:j!=="7702",refreshSpiceAssets:ae,refreshWalletAssets:we,loading:ke,refreshing:Ie,error:be},quote:{...Dt,...qe?{quoteKey:null,quoteExpiresAt:null,quoteError:null,isQuoting:!1,estimatedInput:null,estimatedOutput:null,quoteAmountOut:null,inputAmount:null,resolvedSwap:null,sourceSwap:null,exactOutputSwap:null,sourceExactOutputSwap:null}:{},hasSourceConversion:!!xe,executionInput:xe&&xt?{address:xe.destination.address,chainId:xe.destination.chainId,decimals:xe.destination.decimals,amount:xt.preview.netAmount}:null,...xt?.destinationSwap?{resolvedSwap:xt.destinationSwap,inputAmount:xt.swapInputAmount,estimatedOutput:T.formatUnits(xt.destinationSwap.amountOut,w.decimals)}:{},...xt?.fundedFeeToken&&xt.destinationAmount!==void 0?{estimatedOutput:T.formatUnits(xt.destinationAmount+(xt.destinationSwap?xt.destinationSwap.amountOut-xt.destinationSwap.amountOutMinimum:0n),w.decimals)}:{}},fees:{fundingConversion:xt?.fundingConversion,fundingSource:xt?.fundingSource,proceedsUsed:xt?.proceedsUsed,fundingShortfall:xt?.grossFundingAmount,source:xe&&xt?{address:xe.source.address,chainId:xe.source.chainId,symbol:xe.source.symbol,decimals:xe.source.decimals,gasFee:xt.sourceGasSkim??0n,spicenetFee:0n}:null,destinationAmount:xt?.destinationAmount,sourceSpendCap:xt?.sourceSpendCap,preview:qe?null:xt?.preview??gt,isLoading:!qe&&ee,ready:!qe&&!!jt,error:qe?null:ie},amount:{sourceRequiredAmount:xt?.sourceSpendCap??null,parsed:Ve,isInsufficientBalance:us,sourceBalance:Pt,feesExceedAmount:Oe},status:{finalizing:Yt||Hn,finalizationError:Gt,step:Tt&&Ae==="success"?"executing":Ae,statusMsg:Tt?Gt??"Transaction confirmed. Updating application...":Re,txHash:He,isExecuting:Pe||Hn,error:he||Gt||Ue||rt?.reason||null,showStatusPanel:ut,paymentResult:Tt&&Ee?.status==="success"?{...Ee,status:"processing"}:Ee},flags:{directExecutionFeeNote:H},retryFinalization:Hs,fundEmbeddedSource:Yi,canExecute:tr,submit:b?qn:Fn,submitSupply:Fn,submitPay:qn,retrySupply:Ys,dismissPaymentStatus:Qi,resolveMaxAmount:gn,max:()=>D?gn(D.asset):Promise.resolve(null),resetAfterSuccess:Gi,resetPaymentState:Vs}}function iu(e){const{asset:t,amount:n,recipient:s,owner:o,onSuccess:r}=e,i=t?.chainId??e.sourceChains?.[0]??0,l=u.useMemo(()=>v.getTokensForChain(i).find(w=>w.equivalenceGroup==="USDC"),[i]),c=u.useCallback((w,C)=>{if(!t||n<=0n||n>t.balance||!s||!o||f.addressesEqual(o,s))throw new Error("Enter a valid withdrawal amount and recipient.");if(C.chainId!==t.chainId||!f.addressesEqual(C.executorAddress??C.userAddress,o))throw new Error("The withdrawal wallet or network changed. Review the withdrawal again.");return Ka(t.chainId,t.address,[{recipient:s,amount:n}]).calls},[t?.address,t?.chainId,t?.balance,n,s,o]),d=u.useMemo(()=>t?{asset:t,amount:n}:void 0,[t,n]),p=u.useMemo(()=>t?[{address:t.address,chainId:t.chainId,symbol:t.symbol,decimals:t.decimals,logoURI:t.logoURI}]:void 0,[t?.address,t?.chainId,t?.symbol,t?.decimals,t?.logoURI]),m=cs({enabled:e.enabled&&!!l&&!!t&&n>0n&&!!s&&!!o&&!f.addressesEqual(o,s),feeOnlyAction:!0,isZeroAmountPay:!0,amountDirection:"output",paymentAmount:"0",destinationToken:{address:l?.address??v.ZERO_ADDRESS,symbol:l?.symbol??"USDC",decimals:l?.decimals??6,chainId:i},recipient:s,selectedAsset:null,feeFundingReserve:d,additionalSourceTokens:p,sourceChains:e.sourceChains,includeCrossChainEmbeddedAssets:!0,includeExternalWalletAssets:!1,feeExecutionMode:"backend-transfer",buildActionCalls:c,buildSpicenetBatch:Ns,onError:(w,C)=>e.onError?.(w.message,C),onSuccess:async()=>{t&&(window.dispatchEvent(new CustomEvent("withdraw-completed")),await r?.({token:t.symbol,amount:T.formatUnits(n,t.decimals),chainId:i}))}}),h=`${e.enabled}:${t?.chainId}:${t?.address}:${n}:${s}`,x=u.useRef(h);u.useEffect(()=>{x.current===h||m.status.isExecuting||(x.current=h,(m.status.step==="success"||m.status.paymentResult?.status==="success")&&m.resetAfterSuccess())},[h,m.status.isExecuting,m.status.step,m.status.paymentResult?.status,m.resetAfterSuccess]);const g=m.fees.fundingSource?.asset,y=g?g._source==="wallet"?m.fees.fundingConversion?.amountInMax??m.fees.proceedsUsed:m.amount.sourceRequiredAmount:null;return{supply:m,source:g,maximumFeeFunding:y}}const Ti=f.font.ui,lu=({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:Ti,fontSize:"17px",fontWeight:500,color:r,lineHeight:"24px"},children:e}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",fontFamily:Ti,fontSize:"13px",fontWeight:500,color:i,lineHeight:"16px"},children:["Balance:"," ",t?"...":n===null?"\u2014":f.formatBalance(n)]})]})},ji=({isOpen:e,position:t,title:n,items:s,selectedId:o,onSelect:r,portalAttribute:i})=>{const{dark:l,dk:c,primaryColor:d}=f.useSpiceBrand(),[p,m]=u.useState(null),[h,x]=u.useState(!1);return u.useEffect(()=>{if(!e){x(!1);return}const g=requestAnimationFrame(()=>{requestAnimationFrame(()=>x(!0))});return()=>cancelAnimationFrame(g)},[e]),!e||!t||s.length===0?null:jn.createPortal(a.jsxs("div",{[`data-${i}-popover`]:"true",style:{position:"fixed",top:`${t.top}px`,left:`${t.left}px`,opacity:h?1:0,transform:h?"scale(1) translateY(0)":"scale(0.96) translateY(-6px)",transition:`opacity 200ms ${f.easing.out}, transform 200ms ${f.easing.out}`,backgroundColor:l?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:f.z.dropdown,fontFamily:f.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(g=>{const y=o===g.id,w=p===g.id;return a.jsxs("button",{onClick:C=>{C.stopPropagation(),r(g.id)},onMouseEnter:()=>m(g.id),onMouseLeave:()=>m(null),style:{display:"flex",alignItems:"center",gap:"8px",padding:"6px 4px",borderRadius:"8px",border:"none",cursor:"pointer",backgroundColor:y?l?c.hoverBg:"#f3f4f6":w?l?c.cardBg:"#f9fafb":"transparent",transition:"background-color 0.15s",width:"100%",fontFamily:f.font.mono},children:[g.icon&&a.jsx("img",{src:g.icon,alt:g.label,style:{width:"22px",height:"22px",borderRadius:"50%"}}),a.jsx("span",{style:{fontSize:"13px",fontWeight:y?700:500,textTransform:"uppercase",color:l?c.textPrimary:"#0e0d0b",letterSpacing:"0.5px",flex:1,textAlign:"left"},children:g.label}),g.detail&&a.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:c.textSecondary},children:g.detail}),y&&a.jsx(Ca,{color:d,style:{flexShrink:0}})]},g.id)})})]}),document.body)},zs=f.font.ui,cu=f.font.mono,du=170,uu=({header:e,amount:t,receiveAmountDisplay:n,receiveUsdEstimate:s,selectedDestToken:o,destTokenSymbol:r,destChainName:i,destChainLogo:l,compatibleDestinationChains:c,networkSwitchRef:d,onOpenNetworkPopover:p,showNetworkPopover:m,setShowNetworkPopover:h,networkPopoverPos:x,selectedChainId:g,setSelectedChainId:y,dark:w,dk:C})=>{const b=w?C.cardBg:"#E9E9E9",S=w?C.cardBorder:"#C6C6C6",I=w?C.textSecondary:"#71757A",F=w?C.textPrimary:"#0E0D0B",k=w?C.cardBorder:"#C5C5C4",E=w?"rgba(255,255,255,0.08)":"#D4D3D3",R=r.length>8?"14px":r.length>6?"16px":"18px";return a.jsxs("div",{style:{backgroundColor:b,border:`1px solid ${S}`,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(Sn,{element:"div",value:n,title:n,fontFamily:zs,color:t?F:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,overflow:"wrap"}),a.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:I,fontFamily:zs,marginTop:"10px"},children:s})]}),a.jsxs("div",{style:{width:`${du}px`,flexShrink:0,display:"flex",flexDirection:"column",alignItems:"stretch",gap:"8px"},children:[a.jsxs("div",{style:{backgroundColor:"transparent",border:`1px solid ${k}`,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||ql,alt:r,style:{width:"24px",height:"24px",borderRadius:"50%"}}),a.jsx("span",{style:{fontSize:R,fontWeight:500,color:F,lineHeight:"1.3",fontFamily:zs,flex:1,minWidth:0,letterSpacing:0},children:r})]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:E,borderTop:`1px solid ${k}`},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:F,fontFamily:zs,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:i})]}),a.jsx("button",{ref:d,onClick:j=>{j.stopPropagation(),p(d.current)},style:{background:"none",border:"none",cursor:c.length>1?"pointer":"not-allowed",padding:"0 0 0 8px",fontSize:"9.5px",fontFamily:cu,color:I,textDecoration:"underline",fontWeight:600,opacity:c.length>1?1:.45},children:"Switch"}),a.jsx(ji,{isOpen:m,position:x,title:"SELECT NETWORK",portalAttribute:"network",items:c.map(j=>{const A=f.getChainConfig(j);return{id:String(j),label:A?.displayName||String(j),icon:yn[j]||Xn}}),selectedId:g!==null?String(g):null,onSelect:j=>{y(Number(j)),h(!1)}})]})]}),a.jsx("div",{style:{minHeight:"14px"}})]})]})]})},pu=f.font.ui,Cn=f.font.mono,fu=({show:e,onToggle:t,showCustomAddress:n,setShowCustomAddress:s,customRecipient:o,setCustomRecipient:r,externalAddress:i,recipientAddress:l,destChainName:c,destChainLogo:d,compatibleDestinationChains:p,txDetailsChainSwitchRef:m,onOpenNetworkPopover:h,sourceChainLabel:x,sourceDetailsLogo:g,sourceTokenLabel:y,amount:w,totalSourceDebitDisplay:C,receiveAmountDisplay:b,destTokenSymbol:S,shouldQuoteWithdrawGas:I,estimatingFee:F,feeError:k,displayedGasFee:E,selectedDestToken:R,theme:j,styles:A,dark:M,dk:P})=>{const N=M?P.textSecondary:"#71757A",B=M?P.textPrimary:"#0E0D0B",U=p.length>1,O=n&&o?T.isAddress(o)?f.truncateAddress(o):o:l?f.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:N,fontFamily:pu,fontWeight:600},children:"Transaction Details"}),a.jsx(Gc,{size:12,color:N,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:N,fontFamily:Cn,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:B,fontFamily:Cn,fontWeight:500},children:O}),a.jsx("button",{onClick:()=>{s(z=>!z),!n&&i&&r(i)},style:{background:"none",border:"none",cursor:"pointer",padding:"0",fontSize:"9.5px",fontFamily:Cn,color:N,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:Cn,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&&!T.isAddress(o)?!0:void 0,"data-spiceflow-focus":!0,value:o,onChange:z=>r(z.target.value),placeholder:"0x...",style:{width:"100%",padding:"8px 10px",borderRadius:"6px",border:`1px solid ${o&&!T.isAddress(o)?M?P.errorBorder:"#fca5a5":M?P.inputBorder:"#d1d5db"}`,backgroundColor:M?P.inputBg:"#f9fafb",color:M?P.inputText:"#111827",fontSize:"12px",fontFamily:Cn,outline:"none",boxSizing:"border-box"}}),o&&!T.isAddress(o)&&a.jsx("span",{style:{fontSize:"11px",color:P.errorText,marginTop:"3px",display:"block"},children:"Invalid address"})]})]}),a.jsx(bn,{palette:P,labelColor:N,valueColor:B,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:B,fontWeight:500,fontFamily:Cn,textTransform:"uppercase"},children:c}),a.jsx("button",{ref:m,onClick:z=>{z.stopPropagation(),h(m.current)},style:{background:"none",border:"none",cursor:U?"pointer":"not-allowed",padding:"0",fontSize:"9.5px",fontFamily:Cn,color:N,textDecoration:"underline",fontWeight:600,opacity:U?1:.45},children:"Switch"})]})}),a.jsx(bn,{palette:P,labelColor:N,valueColor:B,label:"REQUESTED WITHDRAWAL",value:a.jsxs(Zo,{logo:g||null,alt:x,primaryText:B,children:[w||"0"," ",y]})}),I&&a.jsx(bn,{palette:P,labelColor:N,valueColor:B,label:"TOTAL SOURCE DEBIT",value:a.jsxs(Zo,{logo:g||null,alt:x,primaryText:B,children:[C," ",y]})}),a.jsx(bn,{palette:P,labelColor:N,valueColor:B,label:"YOU RECEIVE",value:a.jsxs(Zo,{logo:d,alt:c,primaryText:B,gap:"4px",children:[b," ",S]})}),I&&a.jsxs(a.Fragment,{children:[a.jsx(bn,{palette:P,labelColor:N,label:"EST. NETWORK FEE",valueColor:k?"#f87171":B,value:F?"Estimating...":k?"Unavailable":E!==null&&R?`${Wo(E,R.decimals)} ${R.symbol}`:"Estimating..."}),k&&a.jsx(rn,{variant:"error",size:"compact",palette:P,fontFamily:A?.fontFamily||j.typography.fontFamily,children:k})]})]})]})},mu=u.memo(fu),Zo=({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:Cn},children:o})]}),ds=f.font.ui,hu=170,gu=({header:e,amount:t,setAmount:n,isInsufficient:s,sourceAmountDecimals:o,selectedSourceAsset:r,resolvedSelectedSourceAsset:i,spiceAssets:l,setSelectedSourceAsset:c,sourceUsdEstimate:d,sourceTokenLabel:p,sourceChainLabel:m,totalSelectedBalance:h,showSourceTokenPopover:x,setShowSourceTokenPopover:g,tokenPopoverPos:y,setTokenPopoverPos:w,tokenTriggerRef:C,primaryColor:b,dark:S,dk:I})=>{const F=f.useAssetDisplay(),k=i?F({...i,logoURI:Zn}).logoURI:Zn,E=S?I.cardBg:"#E9E9E9",R=S?I.cardBorder:"#C6C6C6",j=S?I.textSecondary:"#71757A",A=S?I.textPrimary:"#0E0D0B",M=S?I.cardBorder:"#C5C5C4",P=S?"rgba(255,255,255,0.08)":"#D4D3D3",N=p.length>8?"14px":p.length>6?"16px":"18px";return a.jsxs("div",{style:{backgroundColor:E,border:`1px solid ${R}`,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(Sn,{element:"input",ariaLabel:"Withdraw amount",ariaInvalid:s,dataSpiceflowFocus:!0,value:t,onChange:B=>{const U=B.target.value;if(U===""){n("");return}/^\d*\.?\d*$/.test(U)&&n(f.parseNumericInput(U.startsWith(".")?`0${U}`:U,o??r?.decimals))},placeholder:"0.0",fontFamily:ds,color:s?"#ef4444":t?A:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,style:{width:"100%"}}),a.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:j,fontFamily:ds,marginTop:"10px"},children:d})]}),a.jsx("div",{style:{width:`${hu}px`,flexShrink:0},children:a.jsxs("div",{style:{backgroundColor:"transparent",border:`1px solid ${M}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[a.jsxs("div",{ref:C,onClick:B=>{if(B.stopPropagation(),!x&&C.current){const U=C.current.getBoundingClientRect(),O=220,z=16;w({top:U.bottom+8,left:Math.min(Math.max(z,U.right-O),window.innerWidth-O-z)})}g(U=>!U)},style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px",cursor:"pointer"},children:[k&&a.jsx("img",{src:k,alt:p,style:{width:"24px",height:"24px",borderRadius:"50%"}}),a.jsx("span",{style:{fontSize:N,fontWeight:500,color:A,lineHeight:"1.3",fontFamily:ds,flex:1,minWidth:0,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",letterSpacing:0},children:p}),a.jsx(Mn,{size:15,color:A,strokeWidth:2.25})]}),a.jsx(ji,{isOpen:x,position:y,title:"SELECT TOKEN",portalAttribute:"token",items:(l||[]).map(B=>({id:B.receiptTokenId||B.address,label:F({...B,displaySymbol:B.displaySymbol||B.receiptTokenName}).symbol,icon:F({...B,logoURI:Zn}).logoURI||void 0,detail:f.formatBalance(B.balanceFormatted)})),selectedId:i?.receiptTokenId||i?.address||null,onSelect:B=>{const U=(l||[]).find(O=>(O.receiptTokenId||O.address)===B);U&&(c(U),n("")),g(!1)}}),a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:P,borderTop:`1px solid ${M}`},children:a.jsx("span",{style:{fontSize:"11px",fontWeight:400,color:A,fontFamily:ds,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:m})})]})})]}),a.jsxs("div",{style:{minHeight:"18px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[s?a.jsx("span",{style:{fontSize:"12px",color:I.errorText,fontFamily:ds,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((B,U)=>{const O=U===4,z=parseFloat(t)||0,q=h>0&&Math.abs(z/h*100-B)<1;return a.jsx("button",{type:"button","aria-label":`Set amount to ${B}%`,"aria-pressed":q,onClick:()=>{const ue=h*B/100,le=r?.decimals??6,G=Math.floor(ue*10**le)/10**le;n(B===0?"":G>0?f.formatDecimalInput(G,le):"")},title:`${B}%`,disabled:h===0,"data-spiceflow-focus":!0,style:{width:"32px",height:"32px",padding:"9px",border:"none",backgroundColor:"transparent",cursor:h===0?"not-allowed":"pointer",opacity:q?1:.5,transition:"opacity 0.15s ease",display:"flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box"},children:a.jsx(Oo,{pct:B,isMax:O,primaryColor:b,dark:S,fillColor:S?I.textSecondary:"#3C3E42"})},B)})})]})]})},xu=({dark:e,dk:t})=>a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[a.jsx("img",{src:ko,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:f.font.ui},children:"Withdraw collateral from your account to 10+ EVM blockchains."})]}),yu=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,styles:s,onWithdrawExecute:o,onWithdrawSuccess:r,onWithdrawError:i,availableTokens:l,initialSourceAssetId:c,walletAssets:d,buildSpicenetBatch:p=Ns})=>{const m=u.useContext(f.SpiceFlowProviderContext);if(!m)return a.jsx("div",{children:"Error: SpiceWithdraw must be used within SpiceFlowProvider"});const h=m.mode||"7702",x=h==="presign"||h==="ondemand",g=m.supportedChainIds,y=m.allowedTokens,w=!!d,C=d?.initialAsset,b=u.useMemo(()=>[...d?.extraAssets??[],...C?[C]:[]].map(oe=>({address:oe.address,chainId:oe.chainId,symbol:oe.symbol,decimals:oe.decimals})),[d?.extraAssets,C]),S=m.isWhitelistGateActive,{theme:I,dark:F,dk:k}=f.useSpiceBrand(s),E=f.useAssetDisplay(),R=m.network,j=()=>x?"select":"provider-login",[A,M]=u.useState(j()),[P,N]=u.useState(!1),[B,U]=u.useState(null),[O,z]=u.useState(null),[q,ue]=u.useState(""),[le,G]=u.useState(!1),[ne,re]=u.useState(!1),[Y,_]=u.useState(!1),[Z,pe]=u.useState(""),[D,L]=u.useState(!0),$=u.useRef(null),de=u.useRef(null),ce=u.useRef(null),[he,X]=u.useState(null),[K,W]=u.useState(null),Q=f.useWallet(),{isReady:ae,isAuthenticated:we,address:ke}=Q,Ie=m?.embeddedWalletAddress,{address:be,chainId:J}=sn.useAccount(),Ye=m.externalWalletAddress||be,[Ne,dt]=u.useState(!1),[rt,Me]=u.useState(null),Pe=u.useRef(i);Pe.current=i;const Xe=u.useCallback(oe=>{Me(oe),typeof oe=="string"&&oe&&Pe.current?.(oe,f.getRelayerErrorDetail(oe))},[]),[Ue,ht]=u.useState(null),We=u.useRef(null),at=u.useRef(!0),Ae=u.useRef(null);u.useEffect(()=>(at.current=!0,()=>{at.current=!1}),[]);const{execute:Qe,estimate:Re}=Fs(),[_e,He]=u.useState(null),[et,ut]=u.useState(null),[tt,Ee]=u.useState(!1),[st,gt]=u.useState(null),{assets:Fe,loading:ee,error:te,refresh:De}=Nn({owner:Ie,role:"holding",includeWalletAssets:w,additionalSourceTokens:b,enabled:e&&!!Ie}),ye=u.useMemo(()=>{if(S)return[];const oe=(fe,xe)=>(xe.balanceUsd||0)-(fe.balanceUsd||0);return(Fe??[]).filter(fe=>fe.balance>0n&&kn(fe,"holding",{allowedTokens:y,isWhitelistGateActive:S}).eligible).sort(oe)},[Fe,y,S]),ie=u.useMemo(()=>[...new Set([...g??[],...Object.keys(l??{}).map(Number),...(ye||[]).map(oe=>oe.chainId),...(ye||[]).flatMap(oe=>Object.keys(oe.chainTokens??{}).map(fe=>{const[,xe]=fe.split(":"),Ve=Number(xe);return Number.isFinite(Ve)?Ve:null}).filter(fe=>fe!==null))])].filter(oe=>f.getChainConfig(oe)?.network===R),[g,l,ye,R]),je=u.useMemo(()=>{if(l)return l;const oe={};for(const fe of ye||[]){const xe=Object.entries(fe.chainTokens??{});if(xe.length>0){for(const[Ve,St]of xe){const[ft,Pt,Ut]=Ve.split(":");if(ft!=="evm"||!Pt||!Ut)continue;const qt=Number(Pt);if(!Number.isFinite(qt))continue;const At=Ut.startsWith("0x")?Ut.toLowerCase():`0x${Ut.toLowerCase()}`,Nt=f.getChainConfig(qt)?.supportedTokens?.find(bt=>f.addressesEqual(bt.address,At));Nt&&uo(fe,At,qt)&&(oe[qt]||(oe[qt]=[]),oe[qt].find(bt=>f.addressesEqual(bt.address,At))||oe[qt].push({address:At,symbol:Nt?.symbol||St?.name||fe.symbol,name:Nt?.name||St?.name||fe.displayName||fe.name||fe.symbol,decimals:Nt?.decimals??St?.decimals??fe.decimals,logoURI:Nt?.logo||fe.logoURI}))}continue}oe[fe.chainId]||(oe[fe.chainId]=[]),oe[fe.chainId].find(Ve=>f.addressesEqual(Ve.address,fe.address))||oe[fe.chainId].push({address:fe.address,symbol:fe.symbol,name:fe.displayName||fe.name||fe.symbol,decimals:fe.decimals,logoURI:fe.logoURI})}return oe},[l,ye]),ve=u.useCallback((oe,fe)=>{const xe=bd(oe,fe,fe?je[fe]??[]:[]);return!oe||!xe||!fe||oe._source==="wallet"&&fe!==oe.chainId?null:kn(oe,"withdraw-destination",m,{...xe,chainId:fe}).eligible?xe:null},[je,m.allowedTokens,m.rpcOverrides,m.isWhitelistGateActive]),V=u.useMemo(()=>B?ye.find(oe=>Ge(oe)===Ge(B))??null:null,[B,ye]),Le=V?V.balanceError:te,me=V?._source==="wallet",ze=u.useMemo(()=>{if(!V)return[];const oe=Object.keys(V.chainTokens??{}).map(fe=>dn(fe)?.chainId??null).filter(fe=>fe!==null);return Array.from(new Set([...oe,V.chainId,...ie].filter(Number.isFinite))).filter(fe=>f.getChainConfig(fe)?.network===R&&ve(V,fe)!==null)},[V,ie,ve,R]),vt=u.useMemo(()=>{if(!V||typeof window>"u")return null;const oe=`spiceflow:withdraw-chain:${V.receiptTokenId||V.address.toLowerCase()}`,fe=window.localStorage.getItem(oe),xe=fe?Number(fe):null;return xe!==null&&Number.isFinite(xe)&&ze.includes(xe)?xe:null},[V,ze]),kt=u.useMemo(()=>V?vt!==null?vt:J&&ze.includes(J)?J:V.chainId&&ze.includes(V.chainId)?V.chainId:ze[0]??null:ie[0]??null,[V,vt,J,ze,ie]),Se=u.useMemo(()=>ve(V,O),[ve,V,O]);u.useEffect(()=>{e&&(U(null),ue(""))},[e,c,C?.address,C?.chainId]),u.useEffect(()=>{if(!e||!ye.length||B)return;const oe=C?ye.find(fe=>fe.chainId===C.chainId&&f.addressesEqual(fe.address,C.address)&&fe._source==="wallet"):c?ye.find(fe=>fe.receiptTokenId===c):ye[0];U(oe??null),ue("")},[e,ye,B,c,C]),u.useEffect(()=>{V&&(O===null||!ze.includes(O))&&z(kt)},[V,O,kt,ze]),u.useEffect(()=>{if(!le&&!ne)return;const oe=fe=>{const xe=fe.target;le&&!$.current?.contains(xe)&&!de.current?.contains(xe)&&!xe?.closest?.("[data-network-popover]")&&G(!1),ne&&!ce.current?.contains(xe)&&!xe?.closest?.("[data-token-popover]")&&re(!1)};return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[le,ne]);const yt=u.useCallback(oe=>{if(!oe||ze.length<=1)return;const fe=oe.getBoundingClientRect(),xe=220,Ve=16;X({top:fe.bottom+8,left:Math.min(Math.max(Ve,fe.right-xe),window.innerWidth-xe-Ve)}),G(St=>!St)},[ze.length]),wt=u.useCallback(()=>L(oe=>!oe),[]);u.useEffect(()=>{if(!V||O===null||typeof window>"u")return;const oe=`spiceflow:withdraw-chain:${V.receiptTokenId||V.address.toLowerCase()}`;window.localStorage.setItem(oe,String(O))},[V,O]);const it=Y?T.isAddress(Z)?Z:void 0:Ye||(me?void 0:Ie),nn=Nn({owner:it,role:"holding",includeRollupAssets:!1,sourceChains:O?[O]:[],additionalSourceTokens:Se&&O?[{...Se,chainId:O}]:[],enabled:e&&!!it&&!!Se&&!!O}),mn=nn.walletAssets.find(oe=>f.addressesEqual(oe.owner,it)&&oe.chainId===O&&f.addressesEqual(oe.address,Se?.address)),Gt=V?.balanceFormatted??0,an=V?E({...V,displaySymbol:V.displaySymbol||V.receiptTokenName}).symbol:"Select token",Yt=V?.displayChainName||(me?f.getChainConfig(V.chainId)?.displayName:"Spicenet")||"Network",It=V?.receiptTokenDecimals??V?.decimals,Ft=u.useMemo(()=>{if(!Se||It===void 0)return 0n;try{return zt(q||"0",It)}catch{return 0n}},[q,Se,It]),Wt=u.useMemo(()=>!Se||It===void 0?0n:Fd(Ft,It,Se.decimals),[Se,It,Ft]),Bt=et??_e,Tt=u.useMemo(()=>{const oe=me?0n:Bt??0n;return Wt>oe?Wt-oe:0n},[me,Bt,Wt]),Mt=Ft,Ke=iu({enabled:e&&me,asset:me?V:null,amount:Ft,recipient:it,owner:Ie,sourceChains:g,onSuccess:r,onError:i}),qe=Ke.supply,Rt=Ne||me&&(qe.status.isExecuting||qe.status.finalizing),Kt=qe.status.step==="success"||qe.status.paymentResult?.status==="success",Dt=u.useCallback(oe=>{if(me||!O||!Se)return[];if(Ft===0n||Wt===0n||!it)return[];const fe=Array.isArray(oe)?oe.filter(ft=>ft.amount>0n):[{token:Se.address,recipient:it,amount:oe??Wt}],xe=fe.reduce((ft,Pt)=>ft+Pt.amount,0n);if(xe<=0n)return[];const Ve={chainId:O,calls:[],tokenTransfers:fe.map(ft=>({from:"escrow",to:ft.recipient,token:ft.token,amount:ft.amount}))},St=p({destinationChainId:O,deliveryToken:Se.address,deliveryAmount:xe,deliveryRecipient:it,deliveryTransfers:fe,requestTimestampMs:Ae.current??Date.now()});return St?[St,Ve]:[Ve]},[me,O,Se,Ft,Wt,it,p]),Be=u.useMemo(()=>Dt(),[Dt]),Lt=u.useMemo(()=>Td(Be,Se?.address),[Be,Se?.address]),Te=u.useRef(null),Ot=!me&&e&&!x&&!Ne&&!!Se&&!!O&&Ft!==0n;So({shouldRun:Ot&&Be.length>0&&!!Lt,deps:[Ot,Be.length>0,Lt],delayMs:500,onSkip:()=>{Te.current=null,He(null),gt(null),Ee(Ot&&Be.length===0)},onCleanup:()=>Ee(!1),run:async({isCurrent:oe,signal:fe})=>{const xe=Lt;Ee(!0),gt(null);try{const Ve=await Ed({batches:Be,tokenAddress:Se.address,chainId:O,estimate:Re,signal:fe});if(!oe())return;Te.current={key:xe,quote:Ve},He(Ve.gasFee)}catch(Ve){if(!oe())return;Te.current=null,He(null),gt(Ve instanceof Error?Ve.message:"Failed to estimate gas fee")}finally{oe()&&Ee(!1)}}}),u.useEffect(()=>{Ne||ut(null)},[Ne,q,O,Se?.address]);const pt=u.useCallback(()=>{N(!0),M("select")},[]),nt=u.useCallback(()=>{Rt||t()},[t,Rt]),ln=u.useRef(null);ln.current={batches:Be,walletAddress:ke,recipient:it,token:Se,chainId:O,amount:q,grossAmountRaw:Wt,gasFee:_e,feeEstimate:Lt&&Te.current?.key===Lt?Te.current.quote.feeEstimate:null,isNon7702:x,buildWithdrawBatches:Dt,execution:{estimate:Re,execute:Qe},ui:{setIsExecuting:dt,setExecutionError:Xe,setExecutionProgress:ht,setLockedGasFee:ut},executionContextRef:We,isMountedRef:at,onWithdrawExecute:o,onWithdrawSuccess:r,buildSpicenetBatch:p};const Vt=u.useCallback(()=>(Ae.current=Date.now(),Qa(ln.current)),[]),zn=u.useCallback(()=>(Ae.current=Date.now(),Ad(ln.current)),[]);if(u.useEffect(()=>{if(!e){const oe=setTimeout(()=>{M(j()),N(!1),U(null),z(null),ue(""),G(!1),re(!1),_(!1),pe(""),dt(!1),Xe(null),ht(null),We.current=null},300);return()=>clearTimeout(oe)}},[e,x]),u.useEffect(()=>{if(!x&&e&&A==="provider-login"&&ae&&we&&Ie&&!P){const oe=setTimeout(()=>{N(!0),M("select")},100);return()=>clearTimeout(oe)}},[x,e,A,ae,we,Ie,P]),!e)return null;if(A==="provider-login"&&!x)return a.jsx(Po,{onAuthSuccess:pt,autoTrigger:!0});if(A==="select"){const oe=parseFloat(q)||0,fe=It?Wo(Mt,It):q||"0",xe=!!V&&Mt>V.balance,Ve=(O?f.getChainConfig(O):null)?.displayName||"Network",St=O?yn[O]||Xn:null,ft=Se?.symbol||"\u2014",Pt=an,Ut=Se?Wo(Tt,Se.decimals):"0",qt=V&&V.balanceFormatted>0?V.balanceUsd/V.balanceFormatted:void 0,At=V?.priceStatus==="stale",Nt=Ya(oe,qt,At),bt=Ya(parseFloat(Ut)||0,qt,At),vn=(!Y||T.isAddress(Z))&&(!me||!f.addressesEqual(it,Ie)),Et=!x&&!me&&oe>0&&Se!==null,Zt=!Et||_e!==null&&!tt&&!st,$t=oe>0&&!xe&&!ee&&!Le&&V!==null&&O!==null&&Se!==null&&it&&vn&&Zt&&Tt>0n&&(!me||qe.canExecute&&!Kt),Xt=!$t,hn=ee?"LOADING BALANCES":Le?"BALANCES UNAVAILABLE":V===null?"NO BALANCE":oe===0?"ENTER AMOUNT":xe?"INSUFFICIENT BALANCE":Et&&!Zt?st?"GAS UNAVAILABLE":"ESTIMATING GAS":Et&&Tt===0n?"AMOUNT TOO SMALL":me&&!qe.canExecute?"REVIEW FEES":"WITHDRAW",Fn=!!Ue&&(Ue.step==="success"||Ue.step==="error"),H=s?.primaryColor||I.colors.primary,ge=402,Oe=(Ce,ot,Ze)=>a.jsx(lu,{label:Ce,loading:Ze,balance:ot,dark:F,dk:k});return a.jsx(tn,{isOpen:!0,onClose:nt,title:"Withdraw",subtitle:a.jsx(xu,{dark:F,dk:k}),styles:s,theme:I,dark:F,maxWidth:"486px",footerLinkText:"Spicenet accounts \u2192",overlayDimmed:!1,closeOnBackdropClick:n,overlayContent:Fn?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(Uo,{type:"withdraw",isOpen:!0,isProcessing:Ne,onRetryTx:()=>{zn()},onNewTx:()=>{ht(null),ue(""),Xe(null),We.current=null},onClose:()=>{ht(null),Xe(null),dt(!1),We.current=null},onComplete:()=>{ht(null),Xe(null),dt(!1),We.current=null},results:[{asset:{symbol:Se?.symbol||"Token",address:Se?.address||""},txHash:Ue?.txHash||"",success:Ue?.step==="success",error:Ue?.error,amount:q}],chainId:O??void 0,theme:I})})}):null,children:a.jsxs("fieldset",{disabled:Rt,style:{border:0,minWidth:0,width:"calc(100% - 32px)",maxWidth:`${ge}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(gu,{header:Oe("Source",Gt,ee),amount:q,setAmount:ue,isInsufficient:xe,sourceAmountDecimals:It,selectedSourceAsset:V,resolvedSelectedSourceAsset:V,spiceAssets:ye,setSelectedSourceAsset:U,sourceUsdEstimate:Nt,sourceTokenLabel:Pt,sourceChainLabel:Yt,totalSelectedBalance:Gt,showSourceTokenPopover:ne,setShowSourceTokenPopover:re,tokenPopoverPos:K,setTokenPopoverPos:W,tokenTriggerRef:ce,primaryColor:H,dark:F,dk:k}),a.jsx(uu,{header:Oe("Destination",mn?.balanceFormatted??null,nn.loading),amount:q,receiveAmountDisplay:Ut,receiveUsdEstimate:bt,selectedDestToken:Se,destTokenSymbol:ft,destChainName:Ve,destChainLogo:St,compatibleDestinationChains:ze,networkSwitchRef:$,onOpenNetworkPopover:yt,showNetworkPopover:le,setShowNetworkPopover:G,networkPopoverPos:he,selectedChainId:O,setSelectedChainId:z,dark:F,dk:k})]}),a.jsxs("div",{style:{marginBottom:I.spacing.sm},children:[a.jsx(mu,{show:D,onToggle:wt,showCustomAddress:Y,setShowCustomAddress:_,customRecipient:Z,setCustomRecipient:pe,externalAddress:Ye,recipientAddress:it,destChainName:Ve,destChainLogo:St,compatibleDestinationChains:ze,txDetailsChainSwitchRef:de,onOpenNetworkPopover:yt,sourceChainLabel:Yt,sourceDetailsLogo:V?E({...V,logoURI:Zn}).logoURI:Zn,sourceTokenLabel:Pt,amount:q,totalSourceDebitDisplay:fe,receiveAmountDisplay:Ut,destTokenSymbol:ft,shouldQuoteWithdrawGas:Et,estimatingFee:tt,feeError:st,displayedGasFee:Bt,selectedDestToken:Se,theme:I,styles:s,dark:F,dk:k}),me&&a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[a.jsx(bn,{palette:k,label:"FEE ASSET",value:qe.fees.isLoading?"Estimating...":Ke.source?`${E(Ke.source).symbol} \xB7 ${Ke.source._source==="spice"?"Spicenet":f.getChainConfig(Ke.source.chainId)?.displayName}`:"Unavailable"}),a.jsx(bn,{palette:k,label:"MAXIMUM FEE FUNDING",value:qe.fees.isLoading?"Estimating...":qe.fees.ready&&Ke.source&&Ke.maximumFeeFunding!=null?`${T.formatUnits(Ke.maximumFeeFunding,Ke.source.decimals)} ${E(Ke.source).symbol}`:"Unavailable"}),(qe.status.error||qe.fees.error)&&a.jsx(rn,{variant:"error",size:"compact",palette:k,children:qe.status.error||qe.fees.error}),qe.status.finalizationError&&a.jsx(f.Button,{variant:"outline",dark:F,disabled:qe.status.finalizing,onClick:()=>void qe.retryFinalization(),children:"Retry application update"}),qe.status.statusMsg&&a.jsx("span",{role:"status",children:qe.status.statusMsg})]}),V&&!ee&&ze.length===0&&a.jsx(rn,{variant:"warning",size:"compact",palette:k,children:"No withdrawal networks are available for this asset."}),rt&&a.jsx(rn,{variant:"error",size:"compact",palette:k,fontFamily:s?.fontFamily||I.typography.fontFamily,style:{marginBottom:"12px"},children:rt}),te&&a.jsxs(rn,{variant:Le?"error":"warning",size:"compact",palette:k,children:[Le?"Unable to load this balance. Please try again.":"Some other balances could not be refreshed."," ",a.jsx("button",{type:"button",onClick:()=>void De(),children:"Retry"})]}),a.jsx(f.Button,{variant:"outline",fullWidth:!0,onClick:()=>{$t&&(me?qe.submitPay():Vt())},disabled:Xt||Rt,theme:I,dark:F,styles:s,style:{marginTop:"8px"},children:Rt?"EXECUTING...":me&&Kt?"WITHDRAWN":hn})]})]})})}return null},Xo=yu,wu=({onDepositClick:e,onWithdrawClick:t,depositDisabled:n=!1,withdrawDisabled:s=!1,primaryColor:o="#EA4B4B",buttonStyles:r,dark:i=!1})=>{if(!e&&!t)return null;const l={button:{backgroundColor:o,...r}};return a.jsxs("div",{style:{display:"flex",gap:"8px"},children:[e&&a.jsx(f.Button,{variant:"outline",onClick:e,disabled:n,dark:i,styles:l,style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&a.jsx(f.Button,{variant:"outline",onClick:()=>t(),disabled:s,dark:i,styles:l,style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]})},bu=u.memo(wu),Cu=({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))})]})},vu=u.memo(Cu);var ku="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 Su=({appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,showUsdSummary:r=!0,address:i,dk:l,dark:c=!1,showModeToggle:d,isEmbeddedMode:p=!0,onModeToggle:m})=>{const[h,x]=u.useState(!1),g=async()=>{i&&await f.copyToClipboard(i)&&(x(!0),setTimeout(()=>x(!1),2e3))},y=t==="active",w=n||(y?"Active":"Inactive"),C=y?"#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:m,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:f.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:p?"Embedded":"External"}),a.jsx("img",{src:ku,alt:"","aria-hidden":"true",style:{width:"11px",height:"11px",display:"block",...c?{filter:"invert(0.65)"}:{}}})]}),a.jsx(ba,{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:ko,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:y?"#ecfdf5":"#f3f4f6",border:c?`1px solid ${l.cardBorder}`:y?"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:y?"#065f46":"#6b7280"},children:w})]})]}),r&&a.jsx("div",{style:{fontSize:"28px",fontWeight:700,color:l.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:f.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:f.font.mono,color:c?l.textSecondary:"#9ca3af"},children:f.truncateAddress(i)}),a.jsx("button",{onClick:g,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:h?"Copied":"Copy"})]})]})},Iu=u.memo(Su),Au=({asset:e,label:t,logo:n,dk:s,dark:o})=>{const r=Oa(n,e.chainId,e.tokenAddress),[i,l]=u.useState();return n===null?null:r&&r!==i?a.jsx("img",{src:r,alt:t,onError:()=>l(r),style:{width:"24px",height:"24px",borderRadius:"50%"}}):a.jsx("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:o?s.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:s.textSecondary},children:t.charAt(0)})},Eu=e=>`${e.tokenAddress}-${e.chainId}`,Fu=({spiceAssets:e,loading:t,dk:n,dark:s=!1,canDirectWithdraw:o=!1,onDirectWithdraw:r,directWithdrawState:i,onWithdrawClick:l,limit:c})=>{const d=f.useAssetDisplay(),[p,m]=u.useState(!1),h=c!==void 0&&!p?Math.max(e.length-c,0):0,x=h>0?e.slice(0,c):e,g={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},y={backgroundColor:n.cardBg,border:s?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return t?a.jsxs("div",{children:[a.jsx("div",{style:g,children:"Idle Balances"}),[1,2].map(w=>a.jsx("div",{style:{...y,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},w))]}):e.length===0?a.jsxs("div",{children:[a.jsx("div",{style:g,children:"Idle Balances"}),a.jsx("div",{style:{...y,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:g,children:"Idle Balances"}),a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[x.map(w=>{const C=f.getChainConfig(w.chainId),b=w.chainDisplayName||C?.displayName||`Chain ${w.chainId}`,S=d({symbol:w.tokenSymbol,displaySymbol:w.tokenDisplaySymbol||w.tokenDisplayName,displayName:w.tokenDisplayName,receiptTokenId:w.receiptTokenId,receiptTokenName:w.receiptTokenName,location:w.location,logoURI:w.logoURI}),I=S.symbol,F=Eu(w),k=w.receiptTokenId&&l,E=k||o&&w.directWithdraw&&!!r,R=!k&&i?.key===F?i:null,j=R?.step==="pending";return a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...y},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[a.jsx(Au,{asset:w,label:I,logo:S.logoURI,dk:n,dark:s}),a.jsxs("div",{children:[a.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:I}),a.jsx("div",{style:{fontSize:"11px",color:s?n.textSecondary:"#9ca3af"},children:b})]})]}),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:f.formatAssetBalance({balance:BigInt(w.balance),decimals:w.tokenDecimals})}),a.jsx("div",{style:{fontSize:"11px",color:R?.step==="error"?n.errorText:s?n.textSecondary:"#9ca3af"},children:R?.step==="error"?R.message||"Withdraw failed":!Number.isFinite(w.usdValue)||w.usdValue<=0?"\u2014":`${f.formatUsd(w.usdValue)}${w.priceStatus==="stale"?" (stale)":""}`})]}),E&&a.jsx("button",{onClick:()=>{j||(k?k(w.receiptTokenId):r(w))},disabled:j,title:k?"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:j?"default":"pointer",opacity:j?.6:1,whiteSpace:"nowrap"},children:j?"Withdrawing\u2026":"Withdraw"})]})]},w.positionId??`${w.owner??""}:${w.location??""}:${w.receiptTokenId??`${w.tokenAddress}-${w.chainId}`}`)}),c!==void 0&&e.length>c&&a.jsxs("button",{onClick:()=>m(!p),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:"6px",width:"100%",padding:"8px 12px",...y,cursor:"pointer",color:n.textSecondary,fontSize:"12px",fontWeight:500},children:[a.jsx("span",{children:p?"Show less":`Show ${h} more`}),a.jsx("span",{style:{transform:p?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]})]})]})},Tu=u.memo(Fu),ju=({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=f.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}`)})})]}),Bu=u.memo(ju),Ru=({appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,showUsdSummary:r,address:i,spiceAssets:l,spiceAssetsLoading:c,pendingDeposits:d,customSections:p,notice:m,onDepositClick:h,onWithdrawClick:x,depositDisabled:g,onCompleteDeposit:y,primaryColor:w,buttonStyles:C,dk:b,dark:S=!1,showModeToggle:I,isEmbeddedMode:F,onModeToggle:k,showConnectExternalCta:E,onConnectExternalWallet:R,connectExternalError:j,showHowItWorks:A=!0,canDirectWithdraw:M,onDirectWithdraw:P,directWithdrawState:N,idleBalancesLimit:B})=>{const[U,O]=u.useState(!1);return a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[a.jsx(Iu,{appName:e,status:t,statusLabel:n,totalUsdValue:s,breakdownSubtitle:o,showUsdSummary:r,address:i,dk:b,dark:S,showModeToggle:I,isEmbeddedMode:F,onModeToggle:k}),m&&a.jsx("div",{style:{padding:"10px 12px",borderRadius:"8px",backgroundColor:m.tone==="warning"?S?"rgba(245, 158, 11, 0.12)":"#fffbeb":m.tone==="success"?S?"rgba(16, 185, 129, 0.12)":"#ecfdf5":b.cardBg,border:m.tone==="warning"?S?"1px solid rgba(245, 158, 11, 0.35)":"1px solid #fde68a":m.tone==="success"?S?"1px solid rgba(16, 185, 129, 0.35)":"1px solid #a7f3d0":S?`1px solid ${b.cardBorder}`:"1px solid #e5e7eb",color:m.tone==="warning"?S?"#fbbf24":"#92400e":m.tone==="success"?S?"#34d399":"#047857":b.textSecondary,fontSize:"12px",lineHeight:1.45,fontWeight:500},children:m.message}),E&&a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[a.jsx("button",{onClick:R,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:w||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:f.font.ui,transition:"opacity 150ms ease"},children:"Connect External Wallet"}),j&&a.jsx("span",{style:{fontSize:"11px",color:S?b.errorText:"#b91c1c",lineHeight:1.4},children:j})]}),a.jsx("div",{style:{height:"1px",backgroundColor:S?"#2d2d2d":"#e5e7eb"}}),a.jsx(bu,{onDepositClick:h,onWithdrawClick:x,depositDisabled:g,primaryColor:w,buttonStyles:C,dark:S}),A&&a.jsxs("div",{children:[a.jsxs("button",{onClick:()=>O(!U),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:b.cardBg,border:S?`1px solid ${b.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:b.textSecondary,fontSize:"12px",fontWeight:500},children:[a.jsx("span",{children:"How It Works"}),a.jsx("span",{style:{transform:U?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),U&&a.jsxs("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:S?b.cardBg:"#f0fdf4",border:S?`1px solid ${b.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:S?b.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),a.jsx(Bu,{pendingDeposits:d,onCompleteDeposit:y,dk:b,dark:S}),a.jsx(Tu,{spiceAssets:l,loading:c,dk:b,dark:S,canDirectWithdraw:M,onDirectWithdraw:P,directWithdrawState:N,onWithdrawClick:x,limit:B}),p.map((z,q)=>a.jsx(vu,{section:z,dk:b,dark:S},q))]})},Du=u.memo(Ru);function Ou({dark:e,onSuccess:t,onError:n}){const{disconnect:s}=sn.useDisconnect(),{logout:o}=Zs.usePrivy(),[r,i]=u.useState(!1);return a.jsx(f.Button,{variant:"ghost",fullWidth:!0,dark:e,loading:r,onClick:async()=>{i(!0);try{s(),await o(),t()}catch(l){n(f.sanitizeError(l,"Unable to disconnect. Please try again."))}finally{i(!1)}},children:"Disconnect"})}const Jo=380,En=8,Nu=[],Mu={};function Bi(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function Pu(e,t){const n=new Map;Object.entries(t).forEach(([o,r])=>{if(!Number.isFinite(r)||r<=0)return;n.set(o,r),n.set(o.toUpperCase(),r);const i=Bi(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=Bi(o);if(!i)continue;const l=n.get(i);if(l!==void 0)return l}return 0}const Ri=({appName:e,status:t="active",statusLabel:n,customSections:s=Nu,extraAssets:o=[],tokenPrices:r={},tokenLogos:i=Mu,breakdownLabels:l=[],notice:c,styles:d,dark:p,onDepositSuccess:m,onDepositClick:h,onWithdrawClick:x,onCompleteDeposit:g,showModeToggle:y=!1,defaultMode:w,showUsdSummary:C=!0,alwaysShowEmbeddedIdle:b=!1,idleBalancesLimit:S,showDisconnect:I=!1})=>{const F=u.useContext(f.SpiceFlowProviderContext),k=F?.mode!=="7702",E=!!F?.isWhitelistGateActive,R=!!F?.isWhitelistConfigured&&F?.isUserWhitelisted!==!0,j=u.useRef(!1);u.useEffect(()=>{if(!j.current){if(f.hasStoredSpiceFlowMode()){j.current=!0;return}w&&F?.setMode&&(F.setMode(w==="non7702"?"ondemand":"7702"),j.current=!0)}},[F,w]);const[A,M]=u.useState(!1),[P,N]=u.useState(null),[B,U]=u.useState({top:0,bottom:0,left:0,placement:"below"}),O=u.useRef(null),z=u.useRef(null),{address:q,isConnected:ue}=f.useWallet(),le=F?.embeddedWalletAddress,G=F?.externalWalletAddress,{embeddedAddress:ne}=f.useProviderWallets(),{brand:re,dark:Y,primaryColor:_,dk:Z}=f.useSpiceBrand(d,p),pe=e??re?.appName??"Spice",D=k&&!G,L=!k||b,$=L?le||ne:q,de=u.useMemo(()=>F?.supportedChainIds??v.getChainIdsByNetwork("mainnet"),[F?.supportedChainIds]),ce=Nn({owner:L?$:G,role:"holding",sourceChains:de,additionalSourceTokens:o.filter(ee=>!ee.receiptTokenId&&(!ee.owner||f.addressesEqual(ee.owner,L?$:G))).map(ee=>({address:ee.tokenAddress,chainId:ee.chainId,decimals:ee.tokenDecimals,symbol:ee.tokenSymbol,logoURI:ee.logoURI})),includeRollupAssets:L,enabled:L?!!$:!!G}),he=ce.assets.filter(ee=>ee._source==="spice"),X=ce.walletAssets,K=ce.loading,W=ce.refresh,Q=L?$:G,ae=u.useMemo(()=>o.filter(ee=>!ee.owner||ee.owner.toLowerCase()===Q?.toLowerCase()).map(ee=>({...ee,owner:ee.owner??Q,location:ee.location??(ee.receiptTokenId?"rollup":L?"embedded":"external")})),[o,Q,L]),we=u.useMemo(()=>{const ee=new Map(Object.entries(r).filter(([,te])=>Number.isFinite(te)&&te>0).map(([te,De])=>[te.toLowerCase(),De]));return X.map(te=>({owner:te.owner,location:te.location,positionId:Ge(te),tokenAddress:te.address,tokenSymbol:te.symbol,tokenDecimals:te.decimals,chainId:te.chainId,chainDisplayName:f.getChainName(te.chainId),balance:te.balance.toString(),balanceFormatted:te.balanceFormatted,usdValue:te.balanceUsd||(ee.get(`${te.chainId}:${te.address.toLowerCase()}`)??0)*te.balanceFormatted,logoURI:te.logoURI||i[te.symbol],directWithdraw:L}))},[X,ae,i,r,L]),ke=u.useMemo(()=>{const ee=L?he.map(ie=>{const je=ie.balanceUsd||0,ve=Number.isFinite(ie.balanceFormatted)?ie.balanceFormatted:0,V=Pu(ie,r),Le=ie.priceStatus&&V>0?V*ve:je>0?je:V*ve;return{owner:ie.owner,location:ie.location,positionId:Ge(ie),tokenAddress:ie.address,tokenSymbol:ie.symbol,tokenDisplaySymbol:f.getAssetDisplaySymbol(ie),tokenDisplayName:f.getAssetDisplayName(ie),tokenDecimals:ie.decimals,chainId:ie.chainId,chainDisplayName:f.getAssetDisplayChainName(ie),balance:ie.balance.toString(),balanceFormatted:ie.balanceFormatted,usdValue:Le,priceStatus:V>0?void 0:ie.priceStatus,logoURI:ie.logoURI,receiptTokenId:ie.receiptTokenId,receiptTokenName:ie.receiptTokenName}}):[],te=ie=>`${ie.owner?.toLowerCase()}:${ie.location}:${ie.chainId}:${ie.receiptTokenId??v.normalizeNativeTokenAddress(ie.tokenAddress).toLowerCase()}`,De=new Map([...ce.rollupAssets,...X].map(ie=>[te({...ie,tokenAddress:ie.address}),ie])),ye=new Map([...ee,...we].map(ie=>[te(ie),ie]));for(const ie of D?[]:ae){const je=te(ie),ve=ye.get(je);ye.set(je,ve?{...ie,...ve,logoURI:ie.logoURI??ve.logoURI,tokenDisplayName:ie.tokenDisplayName??ve.tokenDisplayName,tokenDisplaySymbol:ie.tokenDisplaySymbol??ve.tokenDisplaySymbol}:ie)}return[...ye.values()].filter(ie=>BigInt(ie.balance)>0n&&zr({isDiscovered:De.get(te(ie))?.isDiscovered,balanceUsd:ie.usdValue},!0)&&f.isAssetAllowed(De.get(te(ie))??{address:ie.tokenAddress,symbol:ie.tokenSymbol,displaySymbol:ie.tokenDisplaySymbol},F?.allowedTokens)).sort((ie,je)=>je.usdValue-ie.usdValue)},[L,D,he,ce.rollupAssets,r,we,ae,F?.allowedTokens]),Ie=u.useMemo(()=>ke.reduce((ee,te)=>ee+te.usdValue,0),[ke]),{pendingDeposits:be,refresh:J}=la({chainIds:de,enabled:!!q,discoverWalletBalances:!0}),Ye=u.useMemo(()=>s.reduce((ee,te)=>ee+(te.totalValue??0),0),[s]),Ne=Ie+Ye,dt=u.useMemo(()=>{const ee=[];Ie>0&&ee.push(`${f.formatUsd(Ie)} idle`);for(const te of s){const De=l.find(ye=>ye.sectionTitle===te.title)?.label||te.title.toLowerCase();ee.push(`${f.formatUsd(te.totalValue??0)} ${De}`)}return ee.join(" \xB7 ")},[Ie,s,l]),rt=u.useCallback(ee=>{g?g(ee):N(ee)},[g]),Me=u.useCallback(()=>{N(null)},[]),Pe=u.useCallback(()=>{N(null),m?.()},[m]),Xe=u.useCallback(()=>{if(!O.current)return;const ee=O.current.getBoundingClientRect(),te=window.innerHeight-ee.bottom-En,De=ee.top-En,ye=te>=400||te>=De?"below":"above",ie=Math.max(En,Math.min(ee.right-Jo,window.innerWidth-Jo-En)),je=ye==="below"?ee.bottom+En:ee.top-En,ve=ye==="above"?window.innerHeight-je:0;U({top:je,bottom:ve,left:ie,placement:ye})},[]);u.useLayoutEffect(()=>{A&&Xe()},[A,Xe]),u.useEffect(()=>{if(!A)return;const ee=ye=>{O.current&&!O.current.contains(ye.target)&&z.current&&!z.current.contains(ye.target)&&M(!1)},te=ye=>{ye.key==="Escape"&&M(!1)},De=()=>Xe();return document.addEventListener("mousedown",ee),document.addEventListener("keydown",te),window.addEventListener("scroll",De,{passive:!0}),window.addEventListener("resize",Xe),()=>{document.removeEventListener("mousedown",ee),document.removeEventListener("keydown",te),window.removeEventListener("scroll",De),window.removeEventListener("resize",Xe)}},[A,Xe]);const Ue=L?le||ne||q:G||q,ht=u.useCallback(()=>{F?.setMode&&F.setMode(k?"7702":"ondemand")},[F,k]),[We,at]=u.useState(null);let Ae=null;try{Ae=Zs.useConnectWallet({onSuccess:()=>at(null),onError:ee=>at(f.sanitizeError(ee,"Failed to connect wallet."))}).connectWallet}catch{Ae=null}const Qe=u.useCallback(()=>{Ae&&(M(!1),at(null),Ae({walletChainType:"ethereum-only"}))},[Ae]),Re=!G&&!!Ae,_e=u.useCallback(()=>{M(!1),h?.()},[h]),He=u.useCallback(ee=>{M(!1),x?.(ee)},[x]),et=u.useCallback(ee=>{M(!1),rt(ee)},[rt]),[ut,tt]=u.useState(null),Ee=L&&!!G&&!f.addressesEqual(Q,G),st=u.useCallback(ee=>{const te=X.find(De=>De.chainId===ee.chainId&&f.addressesEqual(De.address,ee.tokenAddress));te&&(M(!1),tt(te))},[X]);if(typeof window>"u")return null;const gt=a.jsxs("button",{ref:O,onClick:()=>M(!A),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:Y?Z.hoverBg:"#ffffff",border:Y?`1px solid ${Z.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:f.font.ui,color:Y?Z.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:Y?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[a.jsxs("span",{children:[pe," Account"]}),ue&&C&&a.jsxs("span",{style:{color:Y?Z.textSecondary:"#6b7280"},children:["\xB7 ",f.formatUsd(Ne)]}),a.jsx("span",{style:{fontSize:"10px",color:Y?Z.textSecondary:"#9ca3af",transform:A?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),Fe=A?jn.createPortal(a.jsxs(a.Fragment,{children:[a.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:f.z.popover},onClick:()=>M(!1)}),a.jsxs("div",{ref:z,style:{position:"fixed",top:B.placement==="below"?`${B.top}px`:"auto",bottom:B.placement==="above"?`${B.bottom}px`:"auto",left:`${B.left}px`,width:`${Jo}px`,maxWidth:`calc(100vw - ${En*2}px)`,maxHeight:"80vh",backgroundColor:Y?Z.shell:"#ffffff",border:Y?`1px solid ${Z.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:Y?"0 10px 40px rgba(0, 0, 0, 0.5)":"0 10px 40px rgba(0, 0, 0, 0.12)",zIndex:f.z.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${f.easing.out}`},children:[a.jsx(Du,{appName:pe,status:t,statusLabel:n,totalUsdValue:Ne,breakdownSubtitle:dt,showUsdSummary:C,address:L?Ue:q,spiceAssets:ke,spiceAssetsLoading:K,pendingDeposits:be,customSections:s,notice:c,onDepositClick:h?_e:void 0,onWithdrawClick:x?He:void 0,depositDisabled:R,onCompleteDeposit:et,primaryColor:_,buttonStyles:d?.button,dk:Z,dark:Y,showModeToggle:y,isEmbeddedMode:!k,onModeToggle:ht,showConnectExternalCta:Re,onConnectExternalWallet:Qe,connectExternalError:We,showHowItWorks:!E,canDirectWithdraw:Ee,onDirectWithdraw:st,idleBalancesLimit:S}),I&&ue&&a.jsx("div",{style:{padding:"0 16px 16px"},children:a.jsx(Ou,{dark:Y,onSuccess:()=>M(!1),onError:at})})]}),a.jsx("style",{children:`
|
|
45
45
|
@keyframes accountDisplayFadeIn {
|
|
46
46
|
from { opacity: 0; transform: translateY(-4px); }
|
|
47
47
|
to { opacity: 1; transform: translateY(0); }
|