@spicenet-io/spiceflow-ui 3.3.40 → 3.3.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -63,7 +63,7 @@
63
63
  transform: translateY(0);
64
64
  }
65
65
  }
66
- `})]})},Es=new Set(["WBTC","CBTC"]),Co=new Set(["btc","wbtc","wcbtc","cbtc"]);function bo(e,t){return!e||!t?!1:e===t?!0:Es.has(e)&&Es.has(t)}function In(e){const[t,s,o]=e.split(":");if(t!=="evm"||!s||!o)return null;const a=Number(s);if(!Number.isFinite(a))return null;const r=o.startsWith("0x")?o.toLowerCase():`0x${o.toLowerCase()}`;return{chainId:a,address:r}}function Kn(e){return(e??"").trim().replace(/^test\s+/i,"").replace(/^spice/i,"").toLowerCase().replace(/[^a-z0-9]/g,"")}function Da(e){return new Set([e.receiptTokenName,e.displaySymbol,e.symbol,e.displayName,e.name].map(Kn).filter(Boolean))}function Na(e,t){const s=Da(e),o=[t.symbol,t.name,t.equivalenceGroup].map(Kn);if(o.some(i=>i&&s.has(i)))return!0;const a=[...s].some(i=>Co.has(i)),r=o.some(i=>Co.has(i))||Es.has(t.equivalenceGroup??"");return a&&r}function wo(e,t,s){const o=new Set(t.map(Kn).filter(Boolean)),a=r=>{if(s&&p.addressesEqual(r.address,s))return 0;const i=[r.symbol,r.name,r.equivalenceGroup].map(Kn).findIndex(d=>d&&o.has(d));return i===-1?4:i+1};return[...e].sort((r,i)=>{const d=a(r)-a(i);return d!==0?d:r.address.toLowerCase().localeCompare(i.address.toLowerCase())})}const ko=typeof process<"u"&&process.env?.NEXT_PUBLIC_MORALIS_API_KEY||typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:yn&&yn.tagName.toUpperCase()==="SCRIPT"&&yn.src||new URL("index.cjs.js",document.baseURI).href}<"u"&&void 0||"",Wa="https://deep-index.moralis.io/api/v2.2";function Zn(e,t){const s=e.chainTokens?Object.keys(e.chainTokens):[],o=[];for(const a of s){const r=In(a);if(!r||r.chainId!==t)continue;const i=r.address,d=F.getTokenByAddress(i,t);d&&(!js(e,i,t)&&!(e.isUniversal&&Na(e,d))||o.some(u=>p.addressesEqual(u,i))||o.push(i))}return wo(o.map(a=>{const r=F.getTokenByAddress(a,t);return{address:a,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(a=>a.address)}function js(e,t,s){return e.chainId===s&&p.addressesEqual(e.address,t)?!0:Nn(e.address,e.chainId,t,s)}async function Ua(e,t){const s=p.getClientForChain(e),o=F.getEscrowContractAddress(e);return F.isNativeToken(t)?s.getBalance({address:o}):await s.readContract({address:t,abi:j.erc20Abi,functionName:"balanceOf",args:[o]})}function vo(e,t,s){const o=F.getTokensForChain(s),a=o.find(i=>p.addressesEqual(i.address,e));if(a)return a;const r=F.getTokenByAddress(e,t);if(r)return wo(o.filter(i=>bo(i.equivalenceGroup,r.equivalenceGroup)),[r.symbol,r.name,r.equivalenceGroup])[0]}function $t(e,t){if(e.chainId===t)return e.address;const s=vo(e.address,e.chainId,t);return s?s.address:null}async function So(e,t,s={}){const o=$t(e,t),a=Zn(e,t);if(a.length===0)return o;if(a.length===1)return a[0];const r=s.requiredAmount??0n,i=u=>{const l=a.map(h=>({candidate:h,balance:u.get(F.isNativeToken(h)?"native":h.toLowerCase())??0n})).filter(h=>h.balance>0n).sort((h,f)=>h.balance===f.balance?0:h.balance>f.balance?-1:1);return l.length===0?null:((r>0n?l.find(h=>h.balance>=r):l[0])??l[0]).candidate},d=p.getChainsForAssets()[t];if(d?.moralisName&&ko){const u=new Map,l=a.some(h=>F.isNativeToken(h));try{if(l)try{const f=p.getClientForChain(t),m=F.getEscrowContractAddress(t);u.set("native",await f.getBalance({address:m}))}catch{}const h=await fetch(`${Wa}/wallets/${F.getEscrowContractAddress(t)}/tokens?chain=${d.moralisName}`,{headers:{"X-API-Key":ko}});if(h.ok){const f=await h.json();for(const x of f?.result||[]){const g=String(x.token_address||"").toLowerCase();if(g)try{u.set(g,BigInt(String(x.balance||"0")))}catch{}}const m=i(u);if(m)return m}}catch{}}try{const u=await Promise.all(a.map(async f=>({key:F.isNativeToken(f)?"native":f.toLowerCase(),value:await Ua(t,f)}))),l=new Map(u.map(({key:f,value:m})=>[f,m])),h=i(l);if(h)return h}catch{}return o}function Nn(e,t,s,o){const a=F.getTokenByAddress(e,t),r=F.getTokenByAddress(s,o);return a&&r?bo(a.equivalenceGroup,r.equivalenceGroup):F.areEquivalent(e,s)}function Yn(e,t){return Nn(e.address,e.chainId,t.address,t.chainId)}const Pa={usdc:[8453,1,42161,5115,4114],usdt:[1],btc:[4114,42161,1,5115],wbtc:[1],weth:[8453,1],ctusd:[5115,4114],wcbtc:[5115,4114]},za={btc:["wcbtc","cbtc","wbtc"]};function Gn(e){return e.replace(/^test\s+/i,"").replace(/^spice/i,"").trim()}function nn(e){return Gn(e).toLowerCase()}function Io(e){return nn(e??"").replace(/[^a-z0-9]/g,"")}function Fs(e){const t=nn(e);return[t,...za[t]??[]].filter(Boolean)}function La(e){try{return BigInt(e.balanceAvailable||"0")}catch{return 0n}}function Oa(e){return Array.isArray(e.chainTokens)?e.chainTokens:Object.keys(e.chainTokens??{})}function Ha(e,t,s,o=[]){const a=p.getChainConfig(t),r=s.toLowerCase(),i=r===F.ZERO_ADDRESS.toLowerCase()?a?.nativeCurrency.decimals??18:a?.supportedTokens?.find(u=>u.address.toLowerCase()===r)?.decimals??18,d=new Set(o.map(Io).filter(Boolean));return e.reduce((u,l)=>{const h=La(l),f=l.decimals??i,m=F.convertAmountBetweenDecimals(h,f,i);if(Oa(l).some(g=>{const y=In(g);return y&&Nn(y.address,y.chainId,s,t)}))return u+m;if(d.size===0)return u;const x=Io(l.tokenName||l.receiptToken);return d.has(x)?u+m:u},0n)}function Qa(e,t){const s=new Set([...Fs(t),...Fs(Gn(t))]);return[...e].sort((o,a)=>{const r=nn(o.symbol),i=nn(a.symbol),d=nn(o.name),u=nn(a.name),l=s.has(r)?0:s.has(d)?1:2,h=s.has(i)?0:s.has(u)?1:2;return l!==h?l-h:o.address.toLowerCase().localeCompare(a.address.toLowerCase())})[0]}function Va(e){const t=e&&e.length>0?e:Object.keys(p.CHAIN_CONFIGS).map(Number).filter(Number.isFinite),s=new Map;for(const o of t){const a=p.getChainConfig(o);if(!a)continue;const r=`${o}:${F.ZERO_ADDRESS.toLowerCase()}`;s.has(r)||s.set(r,{address:F.ZERO_ADDRESS,chainId:o,symbol:a.nativeCurrency.symbol,name:a.nativeCurrency.name,decimals:a.nativeCurrency.decimals,isNative:!0,logoURI:a.logo});for(const i of a.supportedTokens??[]){const d=i.address.toLowerCase(),u=`${o}:${d}`;s.has(u)||s.set(u,{address:d,chainId:o,symbol:i.symbol,name:i.name,decimals:i.decimals,isNative:F.isNativeToken(d),logoURI:i.logo})}}return s}function qa(e,t){const s=Va(t),o=Gn(e.tokenName),a=nn(e.tokenName),r=Fs(e.tokenName),i=Array.isArray(e.chainTokens)?e.chainTokens.map(g=>[g,void 0]):Object.entries(e.chainTokens??{}),d=i.map(([g])=>In(g)).filter(g=>g!==null),u=new Map(i.map(([g,y])=>[g,y])),l=(g,y)=>{const k=u.get(`evm:${y.chainId}:${y.address.slice(2).toLowerCase()}`);return{...g,name:typeof k?.name=="string"&&k.name.length>0?k.name:g.name,decimals:typeof k?.decimals=="number"?k.decimals:g.decimals}},h=d.map(g=>{const y=s.get(`${g.chainId}:${g.address.toLowerCase()}`);return y?l(y,g):void 0}).filter(g=>g!==void 0),f=Pa[a]??[];if(f.length>0)for(const g of f){const y=h.find(k=>k.chainId===g);if(y)return y}if(h.length>0)return Qa(h,e.tokenName);const m=Array.from(s.values()).filter(g=>r.includes(nn(g.symbol))||r.includes(nn(g.name)));if(f.length>0)for(const g of f){const y=m.find(k=>k.chainId===g);if(y)return y}if(m.length>0)return m[0];const x=d[0];if(x){const g=u.get(`evm:${x.chainId}:${x.address.slice(2).toLowerCase()}`);return{address:x.address,chainId:x.chainId,symbol:o||e.tokenName,name:typeof g?.name=="string"&&g.name.length>0?g.name:o||e.tokenName,decimals:typeof g?.decimals=="number"?g.decimals:e.decimals??18,isNative:F.isNativeToken(x.address),logoURI:void 0}}}function Ka(e,t){let s;try{s=BigInt(e.balanceAvailable||"0")}catch{return null}if(s<=0n)return null;const o=qa(e,t),a=o?.decimals??e.decimals??18,r=e.decimals??a,i=F.convertAmountBetweenDecimals(s,r,a),d=o?.address??F.ZERO_ADDRESS,u=o?.chainId??0,l=Gn(e.tokenName),h=o?.symbol??l,f=o?.name??l,m=parseFloat(j.formatUnits(i,a)),x=typeof e.balanceUsd=="number"?e.balanceUsd:typeof e.balanceUsd=="string"&&Number(e.balanceUsd)||0;return{address:d,symbol:h,name:f,decimals:a,chainId:u,balance:i,balanceFormatted:m,balanceUsd:x,isNative:o?.isNative??F.isNativeToken(d),logoURI:o?.logoURI,displaySymbol:e.tokenName||h,displayName:e.tokenName||f,displayChainName:"Spicenet",receiptTokenId:e.receiptToken,receiptTokenName:e.tokenName||f,receiptTokenDecimals:r,chainTokens:e.chainTokens&&!Array.isArray(e.chainTokens)?e.chainTokens:void 0,isUniversal:!0}}function Za(e){const t=e.chainTokens??e.chainTokenConfig;if(Array.isArray(t))return t.filter(s=>typeof s=="string");if(t&&typeof t=="object")return t}const Wn=({address:e,supportedChains:t,enabled:s=!0,refetchInterval:o})=>{const a=c.useContext(p.SpiceFlowProviderContext)?.apiUrl||p.RELAYER_API_URL,[r,i]=c.useState([]),[d,u]=c.useState(!1),[l,h]=c.useState(null),[f,m]=c.useState(!1),x=c.useRef(!1),g=c.useRef(!1),y=t?JSON.stringify([...t].sort()):"",k=c.useCallback(async(C=!1)=>{if(!e||!s){i([]),m(!1),x.current=!1;return}if(!g.current){g.current=!0,!x.current&&!C&&u(!0),h(null);try{const v=await fetch(`${a}/wallets/${e}/balance`,{cache:"no-store"});if(!v.ok)throw new Error(`Failed to fetch balance: ${v.status}`);const w=await v.json();if(w.balances&&Array.isArray(w.balances)){const A=w.balances.map(E=>Ka({receiptToken:typeof E.receiptToken=="string"?E.receiptToken:void 0,tokenName:String(E.tokenName??""),balanceAvailable:String(E.balanceAvailable??"0"),chainTokens:Za(E),decimals:typeof E.decimals=="number"?E.decimals:void 0,balanceUsd:typeof E.balanceUsd=="number"||typeof E.balanceUsd=="string"?E.balanceUsd:null},t)).filter(E=>E!==null);i(A),m(A.length>0),x.current=!0}else i([]),m(!1)}catch(v){const w=v instanceof Error?v.message:"Failed to fetch balance";h(w),console.error("Error fetching Spice assets:",v),x.current||(i([]),m(!1))}finally{u(!1),g.current=!1}}},[e,s,y,a]);c.useEffect(()=>{s&&e&&(x.current=!1,k(!1))},[e,s,y]),c.useEffect(()=>{if(!s||!e||!o)return;const C=setInterval(()=>{k(!0)},o);return()=>clearInterval(C)},[e,s,o,y]);const S=c.useCallback(C=>r.filter(v=>v.chainId===C),[r]),b=c.useCallback(async()=>{await k(!0)},[k]);return{assets:r,loading:d,error:l,hasBalance:f,refetch:b,getAssetsByChain:S}},Ao=e=>new Promise(t=>setTimeout(t,e));function Ya(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 Ga=350,Xa=1e3;async function Ja(e){const{actionId:t,intentIndex:s,intentId:o,stepIndex:a,maxPolls:r=120,maxExecuteAttempts:i=3,pollsBeforeRetry:d=5,maxConsecutiveStatusErrors:u=15,onStatusMessage:l,signal:h,chainId:f}=e;let m="pending",x,g,y=0,k=0;const S=()=>{y++,p.relayerService.executeStep(t,s,a,{action:"execute"}).then(b=>{b.transactionHash&&(x=b.transactionHash)}).catch(b=>{const C=b instanceof Error?b.message:String(b);console.warn(`[execution] executeStep ${a} attempt ${y} error (will poll):`,C)})};S();for(let b=0;b<r;b++){if(await Ao(b===0?Ga:Xa),h?.aborted)throw new p.SpiceflowError("ABORT","Gasless transaction aborted");try{const v=await p.relayerService.checkStepStatus(o,a);k=0,m=v.data.status,g=v.data.error;const w=v.data.transactionHash;w&&(x=w)}catch(v){if(v instanceof Error&&(v.name==="AbortError"||v instanceof p.SpiceflowError&&v.code==="ABORT")||(k++,k>=u))throw v;continue}if(m==="created"&&b>=y*d&&y<i&&S(),m==="reverted"||m==="error")throw new p.SpiceflowError("ON_CHAIN_REVERT",Ya(m,g),{status:m,txHash:x,actionId:t,intentId:o,stepId:a,chainId:f});if(m==="success"||m==="completed")return x;let C="Waiting for solver...";m==="executing"?C="Transaction executing...":m==="submitted"?C="Transaction submitted...":m==="created"&&(C="Waiting for relayer..."),l?.(C,x)}throw new p.SpiceflowError("POLLING_EXHAUSTED",`Transaction is still processing (status: ${m}). 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:o,stepId:a,lastStatus:m,pollAttempts:r,maxPolls:r,txHash:x})}async function Eo(e){const{actionId:t,intentIndex:s,intentId:o,totalSteps:a,delayBeforeSpicenetStepMs:r=5e3,isSpicenetStep:i,maxExecuteAttemptsForStep:d,maxPolls:u=120,onStatusMessage:l,signal:h}=e;let f;for(let m=0;m<a;m++){m>0&&i?.(m)&&r>0&&await Ao(r);const x=d?.(m)??3,g=await Ja({actionId:t,intentIndex:s,intentId:o,stepIndex:m,maxPolls:u,maxExecuteAttempts:x,maxConsecutiveStatusErrors:x===6?5:15,onStatusMessage:l,signal:h});g&&(f=g)}return f}function Bs(e,t){return e<=0n||t<=0n?0n:(e*t+10000n-1n)/10000n}function sn(e){const t=BigInt(e.feeBreakdown.spicenetFee),s=BigInt(e.feeBreakdown.gasFee),o=BigInt(e.feeBreakdown.bridgeFee??"0"),a=t+s+o;return{spicenetFee:t,gasFee:s,bridgeFee:o,totalFee:a}}function jo(e){const t=BigInt(e.quotedAmount),s=BigInt(e.totalDebit),{totalFee:o}=sn(e);return t>0n||s>0n||o>0n}function $a(e){const t=BigInt(e.quotedAmount),s=BigInt(e.totalDebit),{totalFee:o}=sn(e),a=t+o;return s>a?s:a}function _a(e){const t=[];for(const s of e.intents)for(const o of s.batches)t.push(BigInt(o.quotedAmount));return t.length!==1?null:t[0]}function Un(e,t){const s=e.intents.flatMap(u=>u.batches).filter(jo);if(s.length===0||s.length>1)return null;const o=s[0],{gasFee:a,spicenetFee:r,bridgeFee:i,totalFee:d}=sn(o);return{symbol:t.symbol,decimals:t.decimals,grossAmount:BigInt(o.totalDebit),netAmount:t.actionAmount??BigInt(o.quotedAmount),totalFee:d,spicenetFee:r,gasFee:a,bridgeFee:i,gasQuoteSource:o.gasQuoteSource}}function mn(e,t){const s=e.intents.flatMap(h=>h.batches).filter(jo);if(s.length===0)return null;const o=s.filter(h=>h.chainId===t.chainId),a=o.length>0?o:s;if(a.length>1)return null;const r=a[0],{gasFee:i,spicenetFee:d,bridgeFee:u,totalFee:l}=sn(r);return{chainId:r.chainId,tokenAddress:t.tokenAddress,symbol:t.symbol,decimals:t.decimals,grossAmount:$a(r),netAmount:BigInt(r.quotedAmount),totalFee:l,gasFee:i,spicenetFee:d,bridgeFee:u,gasQuoteSource:r.gasQuoteSource}}const ei=10n,ti=5;function Xn(e){return e.map(t=>({...t,calls:[...t.calls],tokenTransfers:t.tokenTransfers?[...t.tokenTransfers]:void 0}))}function Jn({token:e,recipient:t,amount:s}){return{to:e,value:0n,data:j.encodeFunctionData({abi:p.U,functionName:"transfer",args:[t,s]})}}function Fo({chainBatches:e,token:t,amount:s}){const o=Xn(e),a=o[o.length-1];if(!a)return o;const r=F.getEscrowContractAddress(a.chainId);return a.calls=[...a.calls,Jn({token:t,recipient:r,amount:s})],o}function Bo({chainBatches:e,user:t,token:s,grossAmount:o,gasFee:a}){const r=Xn(e),i=r[r.length-1];if(!i)throw new p.SpiceflowError("INVALID_PARAMS","Action-output escrow funding requires at least one chain batch.");const d=Bs(o,ei),u=a+d;if(u>=o)throw new p.SpiceflowError("INVALID_PARAMS","Borrow amount is too small after gas and Spicenet fees.",{grossAmount:o.toString(),gasFee:a.toString(),spicenetFee:d.toString()});const l=o-u,h=F.getEscrowContractAddress(i.chainId),f=[];return a>0n&&f.push(Jn({token:s,recipient:F.SPICE_GAS_FEE_RECIPIENT,amount:a})),d>0n&&f.push(Jn({token:s,recipient:F.SPICE_PLATFORM_FEE_RECIPIENT,amount:d})),i.calls=[...i.calls,...f,Jn({token:s,recipient:h,amount:l})],i.tokenTransfers=[...i.tokenTransfers??[],...a>0n?[{from:t,to:F.SPICE_GAS_FEE_RECIPIENT,token:s,amount:a}]:[],...d>0n?[{from:t,to:F.SPICE_PLATFORM_FEE_RECIPIENT,token:s,amount:d}]:[],{from:t,to:h,token:s,amount:l}],{chainBatches:r,gasFee:a,spicenetFee:d,netEscrowAmount:l,outputCredit:{chainId:i.chainId,token:s,amount:o}}}async function To({chainBatches:e,user:t,token:s,grossAmount:o,chainAuthorizations:a}){let r=0n,i=Bo({chainBatches:e,user:t,token:s,grossAmount:o,gasFee:r});for(let d=0;d<ti;d+=1){const u=F.hashChainBatches(i.chainBatches),l=(await p.relayerService.estimateBatchGas({user:t,outputToken:s,chainBatches:i.chainBatches.map((h,f)=>({...h,hash:u[f].hash})),chainAuthorizations:a})).gasFee;if(l===r)return i;r=l,i=Bo({chainBatches:e,user:t,token:s,grossAmount:o,gasFee:r})}throw new p.SpiceflowError("INVALID_PARAMS","Action-output fee estimate did not converge. Please retry.")}function gn(e){return F.isSpicenetChainId(e.chainId)}function ni(e,t){if(e.length!==t.length)return!1;const s=F.hashChainBatches(e),o=F.hashChainBatches(t);return s.every((a,r)=>a.hash===o[r]?.hash)}const Mo="0xa9059cbb";function $n(e,t){return`${e}:${t.toLowerCase()}`}function Ro(e,t){return t===F.ZERO_ADDRESS.toLowerCase()?{symbol:p.getChainName(e),decimals:18}:F.getTokenByAddress(t,e)??{symbol:"tokens",decimals:18}}function si(e,t){const s=F.getTokenByAddress(t,e);return[s?.equivalenceGroup,s?.symbol,s?.name]}async function oi(e){return p.getWalletBalanceEntries(e)}function Ts(e,t){return e.map(s=>{if(gn(s)||s.calls.length===0)return s;const o=new Set((s.tokenTransfers??[]).filter(r=>(r.from==="escrow"||r.from==="solver")&&p.addressesEqual(r.to,t)).map(r=>r.token.toLowerCase()));if(o.size===0)return s;let a=0;for(const r of s.calls){if(!r.data?.startsWith(Mo))break;try{const i=j.decodeFunctionData({abi:p.U,data:r.data});if(i.functionName!=="transfer")break;const[d]=i.args;if(p.addressesEqual(d,t)||!o.has(r.to.toLowerCase()))break;a+=1}catch{break}}return a===0?s:{...s,calls:s.calls.slice(a)}})}async function ri(e,t,s){const o=new Map,a=new Map,r=new Map,i=new Map;for(const u of s?.actionOutputCredits??[]){const l=$n(u.chainId,u.token);i.set(l,(i.get(l)??0n)+u.amount)}for(const u of e)if(!gn(u)){for(const l of u.tokenTransfers??[]){if(l.from!=="escrow"&&l.from!=="solver"||!p.addressesEqual(l.to,t))continue;const h=BigInt(l.amount??0);if(h<=0n)continue;const f=$n(u.chainId,l.token);a.set(f,(a.get(f)??0n)+h),l.from==="escrow"&&r.set(f,(r.get(f)??0n)+h)}for(const l of u.calls){if(l.value&&l.value>0n){const h=$n(u.chainId,F.ZERO_ADDRESS);o.set(h,(o.get(h)??0n)+l.value)}if(l.data?.startsWith(Mo))try{const h=j.decodeFunctionData({abi:p.U,data:l.data});if(h.functionName!=="transfer")continue;const[,f]=h.args,m=l.to.toLowerCase(),x=$n(u.chainId,m);o.set(x,(o.get(x)??0n)+f)}catch{}}}let d=null;for(const[u,l]of r){if(l<=0n)continue;const[h,f]=u.split(":"),m=Number(h),x=Ro(m,f);d??(d=await oi(t));const g=Ha(d,m,f,si(m,f));if(!(g>=l))throw new p.SpiceflowError("INVALID_PARAMS",`Insufficient Spice ${x.symbol}: needs ${j.formatUnits(l,x.decimals)}, has ${j.formatUnits(g,x.decimals)}.`,{chainId:m,token:f,userAddress:t,requiredAmount:l.toString(),balance:g.toString(),balanceSource:"spice"})}for(const[u,l]of o){if(l<=0n)continue;const[h,f]=u.split(":"),m=Number(h),x=l-(a.get(u)??0n)-(i.get(u)??0n);if(x<=0n)continue;const g=p.getClientForChain(m),y=f===F.ZERO_ADDRESS.toLowerCase()?await g.getBalance({address:t}):await g.readContract({address:f,abi:p.U,functionName:"balanceOf",args:[t]});if(y>=x)continue;const k=Ro(m,f);throw new p.SpiceflowError("INVALID_PARAMS",`Insufficient ${k.symbol} on ${p.getChainName(m)}: needs ${j.formatUnits(x,k.decimals)}, has ${j.formatUnits(y,k.decimals)}.`,{chainId:m,token:f,userAddress:t,requiredAmount:x.toString(),balance:y.toString(),balanceSource:"wallet"})}}function ai({chainBatches:e,tokenAddress:t,tokenTransferAmount:s,useCustomTransfers:o}){if(!(e.some(gn)||!(o?e.some(a=>gn(a)?!1:(a.tokenTransfers??[]).some(r=>r.from==="escrow"&&BigInt(r.amount??0)>0n)):s>0n)))throw new p.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:s.toString(),useCustomTransfers:!!o})}function ii(e,t,s,o){t.forEach((a,r)=>{if(!a.to||!a.from||!a.token||a.amount===void 0)throw new p.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:a.from,to:a.to,token:a.token,amount:a.amount?.toString()},signingAddress:s,useCustomTransfers:o})})}function Ms({user:e,chainBatches:t,tokenAddress:s,tokenTransferAmount:o,exp:a,signature:r,chainAuthorizations:i,useCustomTransfers:d}){const u=t,l=F.hashChainBatches(u),h=u.filter(f=>!gn(f)).length;if(ai({chainBatches:u,tokenAddress:s,tokenTransferAmount:o,useCustomTransfers:d}),!d&&o>0n&&h>1)throw new p.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:h,tokenAddress:s,tokenTransferAmount:o.toString()});return{user:e,...i?{chainAuthorizations:i}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:r,nbf:0,exp:a,chainBatches:l.map((f,m)=>{const x=u[m],g=gn(x)?[]:d?x.tokenTransfers??[]:o>0n?[{from:"escrow",to:e,token:s,amount:o}]:[];return ii(Number(f.chainId),g,e,d),{hash:f.hash,chainId:Number(f.chainId),tokenTransfers:g,calls:f.calls}})}]}}function li(e,t){const s=F.hashChainBatches(e).map(o=>o.hash);return j.keccak256(j.encodeAbiParameters([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,t,s]))}let Rs=!1;function _n(){const{address:e,isConnected:t,isAuthenticated:s,actions:o}=p.useWallet(),[a,r]=c.useState(null),i=c.useRef(o),d=c.useRef(new Map);i.current=o;const u=c.useCallback(async(m,x,g)=>{const y=[...new Set(m.filter(b=>!gn(b)).map(b=>b.chainId))],k=await Promise.all(y.map(async b=>{const C=p.getClientForChain(b),v=p.getDelegateContractAddress(b),w=Number(await F.getAccountNonce(x,C)),A=[x.toLowerCase(),b,v.toLowerCase(),w].join(":");return{chainId:b,delegateContract:v,nonce:w,cacheKey:A,cached:d.current.get(A)}})),S=[];for(const{chainId:b,delegateContract:C,nonce:v,cacheKey:w,cached:A}of k){if(A){S.push(A);continue}if(g?.aborted)throw new p.SpiceflowError("ABORT","Gasless transaction aborted");const E=await i.current.signAuthorization({contractAddress:C,chainId:b,nonce:v}),M={r:E.r,s:E.s,yParity:E.yParity,address:E.address??C,chainId:Number(E.chainId??b),nonce:Number(E.nonce??v)};d.current.set(w,M),S.push(M)}return S},[]),l=c.useCallback(async(m,x,g)=>{if(g?.aborted)throw new p.SpiceflowError("ABORT","Gasless transaction aborted");const y=await i.current.signMessage({raw:li(m,x)}),k=typeof y=="string"?y:y.signature;if(!k)throw new p.SpiceflowError("SIGNATURE_FAILED","Failed to sign intent authorization. The wallet returned an empty signature.");return k},[]),h=c.useCallback(async(m,x,g,y,k,S)=>{const b=(C,v,w)=>{y?.({step:C,message:v,...w})};if(Rs)throw new p.SpiceflowError("CONCURRENT_EXECUTION","A gasless transaction is already in progress. Please wait.");Rs=!0;try{if(!e)throw new p.SpiceflowError("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const C=S?.userOverride||e,v=S?.depositToEscrow?.gasFundingSource==="action-output"?S.depositToEscrow:null;let w=S?.depositToEscrow&&!v?Fo({chainBatches:m,token:S.depositToEscrow.token,amount:S.depositToEscrow.amount}):Xn(m),A=[],E=S?.useCustomTransfers;b("signing-delegation","Sign delegation in your wallet...");const M=await u(w,C,k);if(k?.aborted)throw new p.SpiceflowError("ABORT","Gasless transaction aborted");const B=BigInt(Math.floor(Date.now()/1e3)+3600);if(v){const O=await To({chainBatches:m,user:C,token:v.token,grossAmount:v.amount,chainAuthorizations:M});w=O.chainBatches,A=[O.outputCredit],E=!0}if(!S?.skipPreSubmitFeeEstimate){let O=!1;for(let q=0;q<5;q++){const K=S?.feeExecutionMode==="user-transfer"?Ts(w,C):w,H=Ms({user:C,chainBatches:K,tokenAddress:x,tokenTransferAmount:g,exp:Number(B),signature:"0x00",chainAuthorizations:M,useCustomTransfers:E}),G=await p.relayerService.estimateActionFees(H);r(G);const ce=S?.adjustBatchesForEstimate?.({feeEstimate:G,chainBatches:w});if(!ce||ni(w,ce)){O=!0;break}w=ce}if(!O)throw new p.SpiceflowError("INVALID_PARAMS","Withdraw fee estimate did not converge. Please retry.")}S?.skipUserFundingPreflight||await ri(w,C,{actionOutputCredits:A}),b("signing-intent","Sign the intent in your wallet...");const I=await l(w,B,k);if(k?.aborted)throw new p.SpiceflowError("ABORT","Gasless transaction aborted");b("submitting","Submitting to relayer...");const T=Ms({user:C,chainBatches:w,tokenAddress:x,tokenTransferAmount:g,exp:Number(B),signature:I,chainAuthorizations:M,useCustomTransfers:E}),D=await p.relayerService.createAction(T),[R,U]=D.intentIds[0].split("/"),L=parseInt(U||"0",10),W=`${R}/${L}`;b("executing","Executing on chain..."),b("executing","Executing on chain...",{actionId:R,intentId:W,intentIndex:L,totalSteps:w.length});const Q=w.length,N=await Eo({actionId:R,intentIndex:L,intentId:W,totalSteps:Q,signal:k,isSpicenetStep:O=>w[O]?.domain==="spicenet",maxExecuteAttemptsForStep:O=>w[O]?.domain==="spicenet"?6:3,maxPolls:180,onStatusMessage:(O,q)=>{b("executing",O,{txHash:q,actionId:R,intentId:W,intentIndex:L,totalSteps:Q})}});return b("success","Transaction successful!",{txHash:N,actionId:R,intentId:W,intentIndex:L,totalSteps:Q}),N||R}catch(C){throw console.error("[GaslessExecution] Error:",C),b("error",C.message||"Transaction failed",{error:C.message}),C}finally{Rs=!1}},[e,s,u,l]),f=c.useCallback(async(m,x,g,y)=>{if(!e)throw new p.SpiceflowError("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const k=y?.userOverride||e,S=y?.depositToEscrow?.gasFundingSource==="action-output"?y.depositToEscrow:null;let b=y?.depositToEscrow&&!S?Fo({chainBatches:m,token:y.depositToEscrow.token,amount:y.depositToEscrow.amount}):Xn(m);const C=y?.feeExecutionMode==="user-transfer"?Ts(b,k):b,v=y?.signAuthorizationsForEstimate?await u(C,k):void 0;let w=y?.useCustomTransfers;S&&(b=(await To({chainBatches:m,user:k,token:S.token,grossAmount:S.amount,chainAuthorizations:v})).chainBatches,w=!0);const A=y?.feeExecutionMode==="user-transfer"?Ts(b,k):b,E=Ms({user:k,chainBatches:A,tokenAddress:x,tokenTransferAmount:g,exp:Math.floor(Date.now()/1e3)+3600,signature:"0x00",chainAuthorizations:v,useCustomTransfers:w}),M=await p.relayerService.estimateActionFees(E);return r(M),M},[e,u]);return{executeGasless:h,estimateGasless:f,lastFeeEstimate:a,hasEmbeddedWallet:t&&s}}const ci={usdc:1,"usdc.e":1,usdt:1,dai:1,ctusd:1,wbtc:1e5,wcbtc:1e5,cbtc:1e5};function Ds(e,t){return j.formatUnits(e,t).replace(/(\.\d*?[1-9])0+$|\.0+$/,"$1")}function Do(e,t,s){return t===s?e:t<s?e*10n**BigInt(s-t):e/10n**BigInt(t-s)}function No(e,t){const s=t?ci[t.trim().toLowerCase()]??0:0,o=e*s;return o<=0?"$0":o>=1?`$${o.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}`:`$${o.toFixed(4).replace(/0+$/,"").replace(/\.$/,"")}`}function di(e,t){return t?JSON.stringify({tokenAddress:t.toLowerCase(),batches:e.map(s=>({chainId:s.chainId,calls:s.calls.map(o=>({to:o.to.toLowerCase(),value:o.value.toString(),data:o.data})),tokenTransfers:(s.tokenTransfers??[]).map(o=>({from:o.from,to:o.to.toLowerCase(),token:o.token.toLowerCase(),amount:o.amount.toString()}))}))}):null}function ui(e){const t=e.find(s=>F.isSpicenetChainId(s.chainId))?.calls?.[0]?.data;if(!t)return null;try{const s=j.decodeFunctionData({abi:F.spicenetAbi,data:t});return s.functionName!=="createWithdrawalRequest"?null:s.args[0].transfers.map(o=>({token:o.token,recipient:o.to,amount:o.amount}))}catch{return null}}function pi(e,t){return!e||e.length!==t.length?!1:e.every((s,o)=>{const a=t[o];return s.token.toLowerCase()===a.token.toLowerCase()&&s.recipient.toLowerCase()===a.recipient.toLowerCase()&&s.amount===a.amount})}function fi(e,t){const s=e.intents.flatMap(r=>r.batches).filter(r=>{const i=sn(r);return BigInt(r.quotedAmount)>0n||BigInt(r.totalDebit)>0n||i.totalFee>0n}),o=s.filter(r=>r.chainId===t),a=o.length>0?o:s;return a.length===1?a[0]:null}function hi(e){const t=new Map;for(const s of e){if(s.amount<=0n)continue;const o=s.token.toLowerCase(),a=s.recipient.toLowerCase(),r=`${o}:${a}`,i=t.get(r);i?i.amount+=s.amount:t.set(r,{...s})}return[...t.values()]}function mi(e,t){if(!e.token||!e.recipient||e.chainId===null)return null;const s=fi(t,e.chainId);if(!s)return null;const{gasFee:o,bridgeFee:a,spicenetFee:r}=sn(s),i=o+a,d=[{token:e.token.address,recipient:e.recipient,amount:e.receiveAmountRaw}];return i>0n&&d.push({token:e.token.address,recipient:F.SPICE_GAS_FEE_RECIPIENT,amount:i}),r>0n&&d.push({token:e.token.address,recipient:F.SPICE_PLATFORM_FEE_RECIPIENT,amount:r}),hi(d)}async function Wo(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(u=>F.isSpicenetChainId(u.chainId)))throw new Error("Spice withdrawals must include a Spicenet funding batch before the destination chain batch.");const s=e.token?.address||"",o={useCustomTransfers:!0},a=await e.gasless.estimateGasless(t,s,0n,o);let r=a;const i=mi(e,a);e.buildSpicenetBatch&&i!==null&&!pi(ui(t),i)&&(t=e.buildWithdrawBatches(i));const d=r.intents[0]?.batches[0]??null;d&&e.ui.setLockedGasFee(sn(d).totalFee),await e.gasless.executeGasless(t,s,0n,u=>{u.actionId&&u.intentId&&typeof u.intentIndex=="number"&&typeof u.totalSteps=="number"&&(e.executionContextRef.current={actionId:u.actionId,intentId:u.intentId,intentIndex:u.intentIndex,totalSteps:u.totalSteps}),e.ui.setExecutionProgress(u)},void 0,{...o,skipPreSubmitFeeEstimate:!0,submittedFeeEstimate:r})}window.dispatchEvent(new CustomEvent("withdraw-completed")),e.onWithdrawSuccess?.({token:e.token?.symbol||"",amount:e.amount,chainId:e.chainId})}catch(t){const s=t instanceof Error?t.message:"Withdraw failed";e.ui.setExecutionError(s),e.onWithdrawError?.(s)}finally{e.ui.setIsExecuting(!1)}}}async function gi(e){const t=e.executionContextRef.current;if(!t){e.ui.setExecutionProgress(null),await Wo(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 s=t.totalSteps;for(let o=0;o<t.totalSteps;o++)if((await p.relayerService.checkStepStatus(t.intentId,o)).data.status!=="success"){s=o;break}if(s>=t.totalSteps)e.ui.setExecutionProgress(o=>({...o||{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 o=s;o<t.totalSteps;o++){let a="pending",r;try{const i=await p.relayerService.executeStep(t.actionId,t.intentIndex,o,{action:"execute"});i.transactionHash&&(r=i.transactionHash)}catch{}for(let i=0;i<120;i++){if(await new Promise(u=>setTimeout(u,Math.min(1e3+i*1e3,5e3))),!e.isMountedRef.current)return;const d=await p.relayerService.checkStepStatus(t.intentId,o);if(!e.isMountedRef.current)return;if(a=d.data.status,d.data.transactionHash&&(r=d.data.transactionHash),a==="success"){e.ui.setExecutionProgress({step:o===t.totalSteps-1?"success":"executing",message:o===t.totalSteps-1?"Transaction successful!":"Executing remaining steps...",txHash:r,actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps});break}if(a==="reverted"||a==="error")throw new Error("Withdraw failed");e.ui.setExecutionProgress({step:"executing",message:"Executing remaining steps...",txHash:r,actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps})}if(!e.isMountedRef.current)return;if(a!=="success")throw new Error("Withdraw is still processing")}window.dispatchEvent(new CustomEvent("withdraw-completed")),e.onWithdrawSuccess?.({token:e.token?.symbol||"",amount:e.amount,chainId:e.chainId})}catch(s){const o=s instanceof Error?s.message:"Withdraw failed";e.ui.setExecutionError(o),e.onWithdrawError?.(o)}finally{e.ui.setIsExecuting(!1)}}async function xi(e){const t=(await e.estimateGasless(e.batches,e.tokenAddress,0n,{useCustomTransfers:!0})).intents[0]?.batches[0];if(!t)throw new Error("No gas fee estimate was returned for this withdraw.");return sn(t).totalFee}const Uo='"IBM Plex Mono", monospace',Po='"Helvetica Neue", sans-serif',yi=({show:e,position:t,popoverRef:s,spiceAssets:o,dark:a,dk:r})=>{if(!e||!t)return null;const i=a?r.textSecondary:"#71757A",d=a?r.textPrimary:"#0E0D0B",u=o||[];return n.jsxs("div",{ref:s,"data-balance-popover":!0,style:{position:"fixed",top:`${t.top}px`,left:`${t.left}px`,width:"220px",background:a?r.cardBg:"#FFFFFF",border:`1px solid ${a?r.cardBorder:"#D6D6D6"}`,borderRadius:"10px",boxShadow:a?"0 12px 32px rgba(0,0,0,0.32)":"0 12px 28px rgba(15, 23, 42, 0.14)",padding:"10px",zIndex:40},children:[n.jsx("div",{style:{fontFamily:Uo,fontSize:"11px",letterSpacing:"0.05em",color:i,marginBottom:"8px"},children:"ALL BALANCES"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:u.length>0?u.map(l=>{const h=l.displaySymbol||l.receiptTokenName||l.symbol;return n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"10px",padding:"6px 0"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0},children:[l.logoURI?n.jsx("img",{src:l.logoURI,alt:h,style:{width:"18px",height:"18px",borderRadius:"50%",flexShrink:0}}):n.jsx("div",{style:{width:"18px",height:"18px",borderRadius:"50%",border:`1px solid ${a?r.cardBorder:"#C8C8C8"}`,flexShrink:0}}),n.jsx("span",{style:{fontFamily:Po,fontSize:"13px",color:d,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:h})]}),n.jsx("span",{style:{fontFamily:Uo,fontSize:"12px",color:d,flexShrink:0},children:an(l.balanceFormatted)})]},l.receiptTokenId||l.address)}):n.jsx("span",{style:{fontFamily:Po,fontSize:"13px",color:i},children:"No balances"})})]})},Ci='"Helvetica Neue", sans-serif',ln='"IBM Plex Mono", monospace',bi=({show:e,onToggle:t,showCustomAddress:s,setShowCustomAddress:o,customRecipient:a,setCustomRecipient:r,externalAddress:i,recipientAddress:d,destChainName:u,destChainLogo:l,compatibleDestinationChains:h,txDetailsChainSwitchRef:f,onOpenNetworkPopover:m,sourceChainLabel:x,sourceDetailsLogo:g,sourceTokenLabel:y,amount:k,totalSourceDebitDisplay:S,receiveAmountDisplay:b,destTokenSymbol:C,shouldQuoteWithdrawGas:v,estimatingFee:w,feeError:A,displayedGasFee:E,selectedDestToken:M,theme:B,styles:I,dark:T,dk:D})=>{const R=T?D.textSecondary:"#71757A",U=T?D.textPrimary:"#0E0D0B",L=h.length>1,W=s&&a?j.isAddress(a)?`${a.slice(0,6)}...${a.slice(-4)}`:a:d?`${d.slice(0,6)}...${d.slice(-4)}`:"\u2014";return n.jsxs(n.Fragment,{children:[n.jsxs("div",{onClick:t,style:{display:"flex",alignItems:"center",gap:"6px",marginBottom:e?"10px":"0",cursor:"pointer",userSelect:"none"},children:[n.jsx("span",{style:{fontSize:"13px",color:R,fontFamily:Ci,fontWeight:600},children:"Transaction Details"}),n.jsx(os.ChevronDown,{size:12,color:R,style:{transform:e?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s"}})]}),e&&n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"7px"},children:[n.jsxs("div",{children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[n.jsx("span",{style:{fontSize:"12px",color:R,fontFamily:ln,fontWeight:500,letterSpacing:"0.03em"},children:"TO"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[n.jsx("span",{style:{fontSize:"13px",color:U,fontFamily:ln,fontWeight:500},children:W}),n.jsx("button",{onClick:()=>{o(Q=>!Q),!s&&i&&r(i)},style:{background:"none",border:"none",cursor:"pointer",padding:"0",fontSize:"9.5px",fontFamily:ln,color:R,textDecoration:"underline",fontWeight:600},children:s?"Reset":"Switch"})]})]}),s&&n.jsxs("div",{style:{marginTop:"6px"},children:[n.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:ln,fontWeight:700,letterSpacing:0,textTransform:"uppercase"},children:"CAUTION: ENTERING AN INCORRECT ADDRESS WILL RESULT IN LOSS OF FUNDS"}),n.jsx("input",{type:"text",autoComplete:"off",spellCheck:!1,"aria-label":"Recipient address","aria-invalid":a&&!j.isAddress(a)?!0:void 0,"data-spiceflow-focus":!0,value:a,onChange:Q=>r(Q.target.value),placeholder:"0x...",style:{width:"100%",padding:"8px 10px",borderRadius:"6px",border:`1px solid ${a&&!j.isAddress(a)?T?D.errorBorder:"#fca5a5":T?D.inputBorder:"#d1d5db"}`,backgroundColor:T?D.inputBg:"#f9fafb",color:T?D.inputText:"#111827",fontSize:"12px",fontFamily:ln,outline:"none",boxSizing:"border-box"}}),a&&!j.isAddress(a)&&n.jsx("span",{style:{fontSize:"11px",color:D.errorText,marginTop:"3px",display:"block"},children:"Invalid address"})]})]}),n.jsx(Sn,{palette:D,labelColor:R,valueColor:U,label:"RECEIVING CHAIN",value:n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"7px"},children:[l&&n.jsx("img",{src:l,alt:u,style:{width:"14px",height:"14px",borderRadius:"50%"}}),n.jsx("span",{style:{fontSize:"13px",color:U,fontWeight:500,fontFamily:ln,textTransform:"uppercase"},children:u}),n.jsx("button",{ref:f,onClick:Q=>{Q.stopPropagation(),m(f.current)},style:{background:"none",border:"none",cursor:L?"pointer":"not-allowed",padding:"0",fontSize:"9.5px",fontFamily:ln,color:R,textDecoration:"underline",fontWeight:600,opacity:L?1:.45},children:"Switch"})]})}),n.jsx(Sn,{palette:D,labelColor:R,valueColor:U,label:"REQUESTED WITHDRAWAL",value:n.jsxs(Ns,{logo:g||null,alt:x,primaryText:U,children:[k||"0"," ",y]})}),v&&n.jsx(Sn,{palette:D,labelColor:R,valueColor:U,label:"TOTAL SOURCE DEBIT",value:n.jsxs(Ns,{logo:g||null,alt:x,primaryText:U,children:[S," ",y]})}),n.jsx(Sn,{palette:D,labelColor:R,valueColor:U,label:"YOU RECEIVE",value:n.jsxs(Ns,{logo:l,alt:u,primaryText:U,gap:"4px",children:[b," ",C]})}),v&&n.jsxs(n.Fragment,{children:[n.jsx(Sn,{palette:D,labelColor:R,label:"EST. GAS FEE",valueColor:A?"#f87171":U,value:w?"Estimating...":A?"Unavailable":E!==null&&M?`${Ds(E,M.decimals)} ${M.symbol}`:"Estimating..."}),A&&n.jsx(vn,{variant:"error",size:"compact",palette:D,fontFamily:I?.fontFamily||B.typography.fontFamily,children:A})]})]})]})},Ns=({logo:e,alt:t,primaryText:s,gap:o="6px",children:a})=>n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:o},children:[e&&n.jsx("img",{src:e,alt:t,style:{width:"13px",height:"13px",borderRadius:"50%"}}),n.jsx("span",{style:{fontSize:"13px",color:s,fontWeight:500,fontFamily:ln},children:a})]});function zo(e){const t=new Set(F.getEquivalentAddresses(e).map(s=>s.toLowerCase()));return t.add(e.toLowerCase()),t}const wi=["USDC","USDT","WETH","WBTC"];function Ws(e,t){const s=p.getChainConfig(t);if(!s)return;if(s.nativeCurrency.symbol.toUpperCase()===e.toUpperCase())return{address:F.ZERO_ADDRESS,symbol:s.nativeCurrency.symbol,decimals:s.nativeCurrency.decimals,chainId:t};const o=s.supportedTokens?.find(a=>a.symbol.toUpperCase()===e.toUpperCase());if(o)return{address:o.address.toLowerCase(),symbol:o.symbol,decimals:o.decimals,chainId:t}}function on(e,t,s){const o=p.getChainConfig(t);if(!o)return;if(s!==void 0){const i=vo(e,s,t);if(i)return{address:i.address.toLowerCase(),symbol:i.symbol,decimals:i.decimals,chainId:t}}const a=zo(e);if([...a].some(i=>F.isNativeToken(i)))return{address:F.ZERO_ADDRESS,symbol:o.nativeCurrency.symbol,decimals:o.nativeCurrency.decimals,chainId:t};const r=o.supportedTokens?.find(i=>a.has(i.address.toLowerCase()));if(r)return{address:r.address.toLowerCase(),symbol:r.symbol,decimals:r.decimals,chainId:t}}function Lo(e){const{sourceAsset:t,outputAsset:s,sourceChainId:o,destinationChainId:a,intermediaryCandidates:r=wi}=e;if(Yn(t,s))return{strategy:"direct",sourceAsset:t,outputAsset:s,sourceChainId:o,destinationChainId:a,summary:`${t.symbol} fronted directly`};if(on(t.address,a,o))return{strategy:"direct",sourceAsset:t,outputAsset:s,sourceChainId:o,destinationChainId:a,summary:`${t.symbol} fronted on destination, swapped to ${s.symbol}`};if(on(s.address,o,a))return{strategy:"source-swap",sourceAsset:t,outputAsset:s,sourceChainId:o,destinationChainId:a,summary:`${t.symbol} \u2192 ${s.symbol} on source chain, then fronted`};for(const i of r){const d=Ws(i,o);if(!d||Yn(t,d)||Yn(s,d))continue;const u=Ws(i,a);if(u&&Yn(d,u))return{strategy:"intermediary",sourceAsset:t,outputAsset:s,intermediaryAsset:u,sourceChainId:o,destinationChainId:a,summary:`${t.symbol} \u2192 ${i} on source, fronted, then ${i} \u2192 ${s.symbol} on destination`}}throw new p.SpiceflowError("ROUTE_STRATEGY_ERROR",`No viable cross-chain route found from ${t.symbol} (chain ${o}) to ${s.symbol} (chain ${a}). No intermediary asset is available on both chains.`,{sourceAsset:t.symbol,outputAsset:s.symbol,sourceChainId:o,destinationChainId:a,candidatesChecked:r})}async function Oo(e){const{route:t,sourceAmount:s,userAddress:o,registry:a,actionCalls:r,slippage:i}=e;async function d(u,l,h,f){const m=a.getVenueForChain(u);if(!m)throw new p.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${u}. Cannot resolve swap ${l} \u2192 ${h}.`,{chainId:u,tokenIn:l,tokenOut:h,amountIn:f.toString()});const x=await m.resolve({type:"swap",tokenIn:l,tokenOut:h,amountIn:f,maxSlippage:i},u,o);if(!x)throw new p.SpiceflowError("NO_LIQUIDITY",`${m.name} returned no quote for ${l} \u2192 ${h} on chain ${u}. No liquidity available for this pair.`,{venue:m.name,chainId:u,tokenIn:l,tokenOut:h,amountIn:f.toString()});return x}switch(t.strategy){case"direct":{const u=on(t.sourceAsset.address,t.destinationChainId,t.sourceChainId)||t.sourceAsset;if(zo(u.address).has(t.outputAsset.address.toLowerCase()))return{chainBatches:[{chainId:t.destinationChainId,calls:r}],solverFrontToken:u,solverFrontAmount:s,resolvedSwaps:{}};const l=await d(t.destinationChainId,u.address,t.outputAsset.address,s);return{chainBatches:[{chainId:t.destinationChainId,calls:[...l.calls,...r]}],solverFrontToken:u,solverFrontAmount:s,resolvedSwaps:{destinationSwap:l}}}case"source-swap":{const u=on(t.outputAsset.address,t.sourceChainId,t.destinationChainId);if(!u)throw new p.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 l=on(t.outputAsset.address,t.destinationChainId,t.destinationChainId);if(!l)throw new p.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 h=await d(t.sourceChainId,t.sourceAsset.address,u.address,s);return{chainBatches:[{chainId:t.sourceChainId,calls:h.calls},{chainId:t.destinationChainId,calls:r}],solverFrontToken:l,solverFrontAmount:h.amountOutMinimum,resolvedSwaps:{sourceSwap:h}}}case"intermediary":{if(!t.intermediaryAsset)throw new p.SpiceflowError("ROUTE_STRATEGY_ERROR","Intermediary strategy requires an intermediary asset but none was provided in the route plan.",{strategy:t.strategy});const u=on(t.intermediaryAsset.address,t.sourceChainId,t.destinationChainId);if(!u)throw new p.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 l=await d(t.sourceChainId,t.sourceAsset.address,u.address,s),h=await d(t.destinationChainId,t.intermediaryAsset.address,t.outputAsset.address,l.amountOutMinimum);return{chainBatches:[{chainId:t.sourceChainId,calls:l.calls},{chainId:t.destinationChainId,calls:[...h.calls,...r]}],solverFrontToken:t.intermediaryAsset,solverFrontAmount:l.amountOutMinimum,resolvedSwaps:{sourceSwap:l,destinationSwap:h}}}default:throw new p.SpiceflowError("ROUTE_STRATEGY_ERROR",`Unknown route strategy: ${t.strategy}`,{strategy:t.strategy})}}const ki=({isOpen:e,onClose:t,closeOnBackdropClick:s=!1,styles:o,onWithdrawExecute:a,withdrawActionLabel:r,onWithdrawSuccess:i,onWithdrawError:d,autoCloseDelay:u,availableTokens:l,buildSpicenetBatch:h})=>{const f=c.useContext(p.SpiceFlowProviderContext);if(!f)return n.jsx("div",{children:"Error: SpiceWithdraw must be used within SpiceFlowProvider"});const m=f.mode||"7702",x=m==="presign"||m==="ondemand",g=f.supportedChainIds,y=f.allowedTokens,k=f.isWhitelistGateActive,S=!0,{theme:b,dark:C,dk:v}=p.useSpiceBrand(o),w=f.network,A=()=>x?"select":"provider-login",[E,M]=c.useState(A()),[B,I]=c.useState(!1),[T,D]=c.useState(null),[R,U]=c.useState(null),[L,W]=c.useState(""),[Q,N]=c.useState(!1),[O,q]=c.useState(!1),[K,H]=c.useState(!1),[G,ce]=c.useState(!1),[z,ee]=c.useState(""),[ge,ve]=c.useState(!0),fe=c.useRef(null),xe=c.useRef(null),he=c.useRef(null),V=c.useRef(null),[re,X]=c.useState(null),[le,ye]=c.useState(null),[Ie,J]=c.useState(null),Y=p.useWallet(),{isReady:ae,isAuthenticated:be,address:Ne}=Y,rt=p.useEmbeddedWalletAddress(),{address:qe,chainId:Ke}=It.useAccount(),[oe,ie]=c.useState(!1),[Ze,$]=c.useState(null),[Be,dt]=c.useState(null),kt=c.useRef(null),nt=c.useRef(!0);c.useEffect(()=>(nt.current=!0,()=>{nt.current=!1}),[]);const{executeGasless:zt,estimateGasless:Rt}=_n(),[mt,Ae]=c.useState(null),[Dt,Yt]=c.useState(null),[Gt,xt]=c.useState(!1),[Lt,Ye]=c.useState(null),{assets:vt,loading:Pe}=Wn({address:rt,enabled:e&&!!rt,refetchInterval:3e4}),Xe=c.useMemo(()=>{if(k)return[];if(!y||y.length===0)return vt;const te=new Set(y.map(se=>se.toLowerCase()));return(vt||[]).filter(se=>[se.symbol,se.displaySymbol,se.receiptTokenName].some(Se=>typeof Se=="string"&&te.has(Se.toLowerCase())))},[vt,y,k]),Je=c.useMemo(()=>[...new Set([...g??[],...Object.keys(l??{}).map(Number),...(Xe||[]).map(te=>te.chainId),...(Xe||[]).flatMap(te=>Object.keys(te.chainTokens??{}).map(se=>{const[,Se]=se.split(":"),ze=Number(Se);return Number.isFinite(ze)?ze:null}).filter(se=>se!==null))])].filter(te=>p.getChainConfig(te)?.network===w),[g,l,Xe,w]),ut=c.useMemo(()=>{if(l)return l;const te={};for(const se of Xe||[]){const Se=Object.entries(se.chainTokens??{});if(Se.length>0){for(const[ze,Qe]of Se){const[Le,Oe,Z]=ze.split(":");if(Le!=="evm"||!Oe||!Z)continue;const de=Number(Oe);if(!Number.isFinite(de))continue;const He=Z.startsWith("0x")?Z.toLowerCase():`0x${Z.toLowerCase()}`,ke=p.getChainConfig(de)?.supportedTokens?.find(Ee=>p.addressesEqual(Ee.address,He));ke&&js(se,He,de)&&(te[de]||(te[de]=[]),te[de].find(Ee=>p.addressesEqual(Ee.address,He))||te[de].push({address:He,symbol:ke?.symbol||Qe?.name||se.symbol,name:ke?.name||Qe?.name||se.displayName||se.name||se.symbol,decimals:ke?.decimals??Qe?.decimals??se.decimals,logoURI:ke?.logo||se.logoURI}))}continue}te[se.chainId]||(te[se.chainId]=[]),te[se.chainId].find(ze=>p.addressesEqual(ze.address,se.address))||te[se.chainId].push({address:se.address,symbol:se.symbol,name:se.displayName||se.name||se.symbol,decimals:se.decimals,logoURI:se.logoURI})}return te},[l,Xe]),At=c.useCallback((te,se)=>{if(!te||!se)return null;const Se=Zn(te,se),ze=Object.entries(te.chainTokens??{}).flatMap(([ke,Ee])=>{const Re=In(ke);return Re?.chainId===se?[{parsed:Re,detail:Ee}]:[]}),Qe=ut?.[se]||[],Le=ke=>Qe.find(Ee=>p.addressesEqual(Ee.address,ke))??null,Oe=ke=>{const Ee=p.getChainConfig(se)?.supportedTokens?.find(ft=>p.addressesEqual(ft.address,ke));if(!Ee||!js(te,ke,se))return null;const Re=ze.find(({parsed:ft})=>p.addressesEqual(ft.address,ke));return Re?{address:Re.parsed.address,symbol:Ee.symbol,name:Ee.name||Re.detail?.name||te.displayName||te.name||te.symbol,decimals:Ee.decimals,logoURI:Ee.logo||te.logoURI}:null};for(const ke of Se){const Ee=Le(ke);if(Ee)return Ee;const Re=Oe(ke);if(Re)return Re}const Z=$t(te,se);if(Z){const ke=Le(Z);if(ke)return ke;const Ee=Oe(Z);if(Ee)return Ee}const de=on(te.address,se,te.chainId);return de?Le(de.address)||(Qe.length>0?null:{address:de.address,symbol:de.symbol||te.symbol,name:te.displayName||te.name||te.symbol,decimals:de.decimals??te.decimals,logoURI:te.logoURI}):null},[ut]),me=c.useMemo(()=>{if(!T)return null;const te=T.receiptTokenId||`${T.chainId}:${T.address.toLowerCase()}`;return Xe.find(se=>(se.receiptTokenId||`${se.chainId}:${se.address.toLowerCase()}`)===te)||T},[T,Xe]),st=c.useMemo(()=>{if(!me)return[];const te=Object.keys(me.chainTokens??{}).map(se=>In(se)?.chainId??null).filter(se=>se!==null);return Array.from(new Set([...te,me.chainId,...Je].filter(Number.isFinite))).filter(se=>se!==1&&p.getChainConfig(se)?.network===w&&At(me,se)!==null)},[me,Je,At,w]),pt=c.useMemo(()=>{if(!me||typeof window>"u")return null;const te=`spiceflow:withdraw-chain:${me.receiptTokenId||me.address.toLowerCase()}`,se=window.localStorage.getItem(te),Se=se?Number(se):null;return Se!==null&&Number.isFinite(Se)&&st.includes(Se)?Se:null},[me,st]),Et=c.useMemo(()=>me?pt!==null?pt:Ke&&st.includes(Ke)?Ke:me.chainId&&st.includes(me.chainId)?me.chainId:st[0]??Je[0]??null:Je[0]??null,[me,pt,Ke,st,Je]),Ce=c.useMemo(()=>At(me,R),[At,me,R]);c.useEffect(()=>{!Xe?.length||me||D(Xe[0])},[S,Xe,me]),c.useEffect(()=>{!me||(R===null||!st.includes(R))&&U(Et)},[S,me,R,Et,st]),c.useEffect(()=>{if(!Q&&!O&&!K)return;const te=se=>{const Se=se.target;Q&&!fe.current?.contains(Se)&&!xe.current?.contains(Se)&&!Se?.closest?.("[data-network-popover]")&&N(!1),O&&!he.current?.contains(Se)&&!Se?.closest?.("[data-token-popover]")&&q(!1),K&&!V.current?.contains(Se)&&!Se?.closest?.("[data-balance-trigger]")&&H(!1)};return document.addEventListener("mousedown",te),()=>document.removeEventListener("mousedown",te)},[Q,O,K]);const jt=c.useCallback(te=>{if(!te||st.length<=1)return;const se=te.getBoundingClientRect(),Se=220,ze=16;X({top:se.bottom+8,left:Math.min(Math.max(ze,se.right-Se),window.innerWidth-Se-ze)}),N(Qe=>!Qe)},[st.length]);c.useEffect(()=>{if(!me||R===null||typeof window>"u")return;const te=`spiceflow:withdraw-chain:${me.receiptTokenId||me.address.toLowerCase()}`;window.localStorage.setItem(te,String(R))},[me,R]);const $e=G&&z&&j.isAddress(z)?z:qe||rt,lt=me?.balanceFormatted??0,Ft=c.useCallback(te=>{if(!te)return;const se=te.getBoundingClientRect();J({top:se.bottom+8,left:se.right-220}),H(!0)},[]),Xt=me?.displaySymbol||me?.receiptTokenName||me?.symbol||"spiceUSDC",Ot=me?.displayChainName||"Spicenet",ot=ps,Ht=ps,Te=me?.receiptTokenDecimals??me?.decimals,We=c.useMemo(()=>{if(!Ce||!Te)return 0n;try{return j.parseUnits(L||"0",Te)}catch{return 0n}},[L,Ce,Te]),St=c.useMemo(()=>!Ce||!Te?0n:Do(We,Te,Ce.decimals),[Ce,Te,We]),yt=c.useMemo(()=>{const te=Dt??mt;return!te||te<=0n||!Ce||!Te?0n:Do(te,Ce.decimals,Te)},[Dt,mt,Ce,Te]),Ue=c.useMemo(()=>We+yt,[We,yt]),_e=Dt??mt,at=c.useCallback(te=>{if(!R||!Ce)return[];if(We===0n||St===0n||!$e)return[];const se=Array.isArray(te)?te.filter(Le=>Le.amount>0n):[{token:Ce.address,recipient:$e,amount:te??St}],Se=se.reduce((Le,Oe)=>Le+Oe.amount,0n);if(Se<=0n)return[];const ze={chainId:R,calls:[],tokenTransfers:se.map(Le=>({from:"escrow",to:Le.recipient,token:Le.token,amount:Le.amount}))};if(!h)return[ze];const Qe=h({destinationChainId:R,deliveryToken:Ce.address,deliveryAmount:Se,deliveryRecipient:$e,deliveryTransfers:se});return Qe?[Qe,ze]:[ze]},[S,R,Ce,We,St,$e,h]),et=c.useMemo(()=>at(),[at]),Ge=c.useMemo(()=>di(et,Ce?.address),[et,Ce?.address]),Ct=c.useRef(null),tt=c.useRef(0);c.useEffect(()=>{let te=!1;if(!e||x||oe||!Ce||We===0n){Ct.current=null,Ae(null),Ye(null),xt(!1);return}if(et.length===0){Ct.current=null,Ae(null),xt(!0);return}if(!Ge){Ct.current=null,Ae(null),Ye(null),xt(!1);return}if(Ct.current===Ge)return;Ct.current=Ge;const se=++tt.current;return(async()=>{xt(!0),Ye(null);try{const Se=await xi({batches:et,tokenAddress:Ce.address,estimateGasless:Rt});if(te||se!==tt.current)return;Ae(Se)}catch(Se){if(te||se!==tt.current)return;Ct.current=null,Ae(null),Ye(Se instanceof Error?Se.message:"Failed to estimate gas fee")}finally{!te&&se===tt.current&&xt(!1)}})(),()=>{te=!0}},[e,x,oe,Ce,Rt,We,et,Ge]),c.useEffect(()=>{oe||Yt(null)},[oe,L,R,Ce?.address]);const Qt=c.useCallback(()=>{I(!0),M("select")},[S]),Me=c.useCallback(()=>{t()},[t]),Kt=c.useRef(null);Kt.current={batches:et,walletAddress:Ne,recipient:$e,token:Ce,chainId:R,amount:L,receiveAmountRaw:St,gasFee:mt,isNon7702:x,buildWithdrawBatches:at,gasless:{estimateGasless:Rt,executeGasless:zt},ui:{setIsExecuting:ie,setExecutionError:$,setExecutionProgress:dt,setLockedGasFee:Yt},executionContextRef:kt,isMountedRef:nt,onWithdrawExecute:a,onWithdrawSuccess:i,onWithdrawError:d,buildSpicenetBatch:h};const Bt=c.useCallback(()=>Wo(Kt.current),[]),ht=c.useCallback(()=>gi(Kt.current),[]);if(c.useEffect(()=>{if(!e){const te=setTimeout(()=>{M(A()),I(!1),D(null),U(null),W(""),N(!1),q(!1),ce(!1),ee(""),ie(!1),$(null),dt(null),kt.current=null},300);return()=>clearTimeout(te)}},[e,x]),c.useEffect(()=>{if(!x&&e&&E==="provider-login"&&ae&&be&&rt&&!B){const te=setTimeout(()=>{I(!0),M("select")},100);return()=>clearTimeout(te)}},[x,e,E,ae,be,rt,B,S]),!e)return null;if(E==="provider-login"&&!x)return n.jsx(Is,{onAuthSuccess:Qt,autoTrigger:!0});if(E==="select"&&S){const te=parseFloat(L)||0,se=Te?Ds(Ue,Te):L||"0",Se=parseFloat(se)||0,ze=Se>0&&Se>lt,Qe=(R?p.getChainConfig(R):null)?.displayName||"Network",Le=R?_t[R]||Tn:null,Oe=Ce?.symbol||"\u2014",Z=Xt,de=Ce?Ds(St,Ce.decimals):"0",He=No(te,Ce?.symbol||me?.symbol),ke=No(parseFloat(de)||0,Ce?.symbol||me?.symbol),Ee=!G||!z||j.isAddress(z),Re=!x&&te>0&&Ce!==null,ft=!Re||mt!==null&&!Gt&&!Lt,gt=te>0&&!ze&&T!==null&&R!==null&&Ce!==null&&$e&&Ee&&ft&&St>0n,it=!gt,P=T===null?"NO BALANCE":te===0?"ENTER AMOUNT":ze?"INSUFFICIENT BALANCE":Re&&!ft?Lt?"GAS UNAVAILABLE":"ESTIMATING GAS":Re&&St===0n?"AMOUNT TOO SMALL":"WITHDRAW",_=!!Be&&(Be.step==="success"||Be.step==="error"),ue=n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[n.jsx("img",{src:Ss,alt:"","aria-hidden":"true",style:{width:"13px",height:"13px",flexShrink:0,...C?{filter:"invert(0.6)"}:{}}}),n.jsx("p",{style:{fontSize:"13px",color:C?v.textSecondary:"#979AA0",margin:"0",lineHeight:"1.4",fontFamily:'"Helvetica Neue", sans-serif'},children:"Withdraw collateral from your account to 10+ EVM blockchains."})]}),ne='"Helvetica Neue", sans-serif',Fe='"IBM Plex Mono", monospace',je=o?.primaryColor||b.colors.primary,Ve=C?v.cardBg:"#E9E9E9",Nt=C?v.cardBorder:"#C6C6C6",Vt=C?v.textSecondary:"#7D7C7B",bt=C?v.textSecondary:"#71757A",ct=C?v.textPrimary:"#0E0D0B",qt=C?v.cardBorder:"#C5C5C4",rn=C?"rgba(255,255,255,0.08)":"#D4D3D3",dn=170,En=Z.length>8?"14px":Z.length>6?"16px":"18px",un=Oe.length>8?"14px":Oe.length>6?"16px":"18px";return n.jsx(en,{isOpen:!0,onClose:Me,title:"Withdraw",subtitle:ue,styles:o,theme:b,dark:C,maxWidth:"486px",footerLinkText:"Spicenet accounts \u2192",overlayDimmed:!1,closeOnBackdropClick:s,overlayContent:_?n.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:n.jsx("div",{style:{pointerEvents:"auto"},children:n.jsx(As,{type:"withdraw",isOpen:!0,isProcessing:oe,onRetryTx:()=>{ht()},onNewTx:()=>{dt(null),W(""),$(null),kt.current=null},onClose:()=>{dt(null),$(null),ie(!1),kt.current=null},onComplete:()=>{dt(null),$(null),ie(!1),kt.current=null},results:[{asset:{symbol:Ce?.symbol||"Token",address:Ce?.address||""},txHash:Be?.txHash||"",success:Be?.step==="success",error:Be?.error,amount:L}],chainName:R?p.getChainName(R):"Network",explorerUrl:R?p.getExplorerUrl(R,"").replace(/\/tx\/.*$/,""):void 0,theme:b})})}):null,children:n.jsxs("div",{style:{width:"402px",margin:"0 auto",padding:"0 0 4px 0",position:"relative"},children:[n.jsx(yi,{show:K,position:Ie,popoverRef:V,spiceAssets:Xe,dark:C,dk:v}),n.jsxs("div",{style:{marginTop:"16px",marginBottom:"16px",display:"flex",flexDirection:"column",gap:"16px"},children:[n.jsxs("div",{style:{backgroundColor:Ve,border:`1px solid ${Nt}`,borderRadius:"7px",padding:"14px 16px 12px 16px",minHeight:"138px",display:"flex",flexDirection:"column",gap:"6px",position:"relative"},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[n.jsx("span",{style:{fontFamily:ne,fontSize:"17px",fontWeight:500,color:Vt,lineHeight:"24px"},children:"Source"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",fontFamily:ne,fontSize:"13px",fontWeight:500,color:bt,lineHeight:"16px"},children:["Balance:"," ",Pe?"...":an(lt),n.jsx("button",{type:"button","data-balance-trigger":!0,onClick:we=>{we.stopPropagation(),Ft(we.currentTarget)},style:{width:"15px",height:"15px",borderRadius:"999px",border:"1px solid #EA4B4B",color:"#EA4B4B",display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:"9px",fontWeight:500,lineHeight:1,boxSizing:"border-box",background:"transparent",padding:0,cursor:"pointer"},children:n.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"1.5px"},children:[0,1,2].map(we=>n.jsx("span",{style:{width:"1.75px",height:"1.75px",borderRadius:"999px",backgroundColor:"#EA4B4B",display:"block"}},we))})})]})]}),n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[n.jsxs("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[n.jsx(hn,{element:"input",ariaLabel:"Withdraw amount",ariaInvalid:ze,dataSpiceflowFocus:!0,value:L,onChange:we=>{const pe=we.target.value;if(pe===""){W("");return}/^\d*\.?\d*$/.test(pe)&&W(bn(pe.startsWith(".")?`0${pe}`:pe,Te??T?.decimals))},placeholder:"0.0",fontFamily:ne,color:ze?"#ef4444":L?ct:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,style:{width:"100%"}}),n.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:bt,fontFamily:ne,marginTop:"10px"},children:He})]}),n.jsx("div",{style:{width:`${dn}px`,flexShrink:0},children:n.jsxs("div",{style:{backgroundColor:"transparent",border:`1px solid ${qt}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[n.jsxs("div",{ref:he,onClick:we=>{if(we.stopPropagation(),!O&&he.current){const pe=he.current.getBoundingClientRect(),De=220,Tt=16;ye({top:pe.bottom+8,left:Math.min(Math.max(Tt,pe.right-De),window.innerWidth-De-Tt)})}q(pe=>!pe)},style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px",cursor:"pointer"},children:[n.jsx("img",{src:ot,alt:Z,style:{width:"24px",height:"24px",borderRadius:"50%"}}),n.jsx("span",{style:{fontSize:En,fontWeight:500,color:ct,lineHeight:"1.3",fontFamily:ne,flex:1,minWidth:0,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",letterSpacing:0},children:Z}),n.jsx(tn,{size:15,color:ct,strokeWidth:2.25})]}),n.jsx(xo,{isOpen:O,position:le,title:"SELECT TOKEN",portalAttribute:"token",items:(Xe||[]).map(we=>({id:we.receiptTokenId||we.address,label:we.displaySymbol||we.receiptTokenName||we.symbol,icon:ps,detail:an(we.balanceFormatted)})),selectedId:me?.receiptTokenId||me?.address||null,onSelect:we=>{const pe=(Xe||[]).find(De=>(De.receiptTokenId||De.address)===we);pe&&(D(pe),W("")),q(!1)}}),n.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:rn,borderTop:`1px solid ${qt}`},children:n.jsx("span",{style:{fontSize:"11px",fontWeight:400,color:ct,fontFamily:ne,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:Ot})})]})})]}),n.jsxs("div",{style:{minHeight:"18px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[ze?n.jsx("span",{style:{fontSize:"12px",color:v.errorText,fontFamily:ne,fontWeight:500},children:"Insufficient Balance"}):n.jsx("span",{}),n.jsx("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0px",minHeight:"32px",marginRight:"-9px"},children:[0,25,50,75,100].map((we,pe)=>{const De=pe===4,Tt=we/100,Jt=parseFloat(L)||0,Zt=lt>0&&Math.abs(Jt/lt*100-we)<1;return n.jsx("button",{type:"button","aria-label":`Set amount to ${we}%`,"aria-pressed":Zt,onClick:()=>{const jn=lt*we/100,pn=T?.decimals??6,Fn=Math.floor(jn*10**pn)/10**pn;W(we===0?"":Fn>0?wn(Fn,pn):"")},title:`${we}%`,disabled:lt===0,"data-spiceflow-focus":!0,style:{width:"32px",height:"32px",padding:"9px",border:"none",backgroundColor:"transparent",cursor:lt===0?"not-allowed":"pointer",opacity:Zt?1:.5,transition:"opacity 0.15s ease",display:"flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box"},children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[n.jsx("circle",{cx:"7",cy:"7",r:"6.84375",fill:De?je:"none",stroke:De?je:C?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!De&&Tt>0&&n.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${Tt>.5?1:0} 1 ${7+6.84375*Math.sin(Tt*2*Math.PI)} ${7-6.84375*Math.cos(Tt*2*Math.PI)} Z`,fill:C?v.textSecondary:"#3C3E42"})]})},we)})})]})]}),n.jsxs("div",{style:{backgroundColor:Ve,border:`1px solid ${Nt}`,borderRadius:"7px",padding:"14px 16px 12px 16px",minHeight:"138px",display:"flex",flexDirection:"column",gap:"6px"},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[n.jsx("span",{style:{fontFamily:ne,fontSize:"17px",fontWeight:500,color:Vt,lineHeight:"24px"},children:"Destination"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",fontFamily:ne,fontSize:"13px",fontWeight:500,color:bt,lineHeight:"16px"},children:["Balance:"," ",Pe?"...":an(lt),n.jsx("button",{type:"button","data-balance-trigger":!0,onClick:we=>{we.stopPropagation(),Ft(we.currentTarget)},style:{width:"15px",height:"15px",borderRadius:"999px",border:"1px solid #EA4B4B",color:"#EA4B4B",display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:"9px",fontWeight:500,lineHeight:1,boxSizing:"border-box",background:"transparent",padding:0,cursor:"pointer"},children:n.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"1.5px"},children:[0,1,2].map(we=>n.jsx("span",{style:{width:"1.75px",height:"1.75px",borderRadius:"999px",backgroundColor:"#EA4B4B",display:"block"}},we))})})]})]}),n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[n.jsxs("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[n.jsx(hn,{element:"div",value:de,title:de,fontFamily:ne,color:L?ct:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,overflow:"wrap"}),n.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:bt,fontFamily:ne,marginTop:"10px"},children:ke})]}),n.jsxs("div",{style:{width:`${dn}px`,flexShrink:0,display:"flex",flexDirection:"column",alignItems:"stretch",gap:"8px"},children:[n.jsxs("div",{style:{backgroundColor:"transparent",border:`1px solid ${qt}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px"},children:[n.jsx("img",{src:Ce?.logoURI||Mn,alt:Oe,style:{width:"24px",height:"24px",borderRadius:"50%"}}),n.jsx("span",{style:{fontSize:un,fontWeight:500,color:ct,lineHeight:"1.3",fontFamily:ne,flex:1,minWidth:0,letterSpacing:0},children:Oe})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:rn,borderTop:`1px solid ${qt}`},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[Le&&n.jsx("img",{src:Le,alt:Qe,style:{width:"13px",height:"13px",borderRadius:"50%",flexShrink:0}}),n.jsx("span",{style:{fontSize:"11px",fontWeight:400,color:ct,fontFamily:ne,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:Qe})]}),n.jsx("button",{ref:fe,onClick:we=>{we.stopPropagation(),jt(fe.current)},style:{background:"none",border:"none",cursor:st.length>1?"pointer":"not-allowed",padding:"0 0 0 8px",fontSize:"9.5px",fontFamily:Fe,color:bt,textDecoration:"underline",fontWeight:600,opacity:st.length>1?1:.45},children:"Switch"}),n.jsx(xo,{isOpen:Q,position:re,title:"SELECT NETWORK",portalAttribute:"network",items:st.map(we=>{const pe=p.getChainConfig(we);return{id:String(we),label:pe?.displayName||String(we),icon:_t[we]||Tn}}),selectedId:R!==null?String(R):null,onSelect:we=>{U(Number(we)),N(!1)}})]})]}),n.jsx("div",{style:{minHeight:"14px"}})]})]})]})]}),n.jsxs("div",{style:{marginBottom:b.spacing.sm},children:[n.jsx(bi,{show:ge,onToggle:()=>ve(we=>!we),showCustomAddress:G,setShowCustomAddress:ce,customRecipient:z,setCustomRecipient:ee,externalAddress:qe,recipientAddress:$e,destChainName:Qe,destChainLogo:Le,compatibleDestinationChains:st,txDetailsChainSwitchRef:xe,onOpenNetworkPopover:jt,sourceChainLabel:Ot,sourceDetailsLogo:Ht,sourceTokenLabel:Z,amount:L,totalSourceDebitDisplay:se,receiveAmountDisplay:de,destTokenSymbol:Oe,shouldQuoteWithdrawGas:Re,estimatingFee:Gt,feeError:Lt,displayedGasFee:_e,selectedDestToken:Ce,theme:b,styles:o,dark:C,dk:v}),Ze&&n.jsx(vn,{variant:"error",size:"compact",palette:v,fontFamily:o?.fontFamily||b.typography.fontFamily,style:{marginBottom:"12px"},children:Ze}),n.jsx(p.Button,{variant:"outline",fullWidth:!0,onClick:()=>{gt&&Bt()},disabled:it||oe,theme:b,dark:C,styles:o,style:{marginTop:"8px"},children:oe?"EXECUTING...":P})]})]})})}return null},Ho=ki;var vi="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAKlBMVEVMaXHpSkrmS0vrSkrmR0fpSkrrSkroSUnqSkrpSkrpSkrpSkrsS0vzTk68N2lZAAAADHRSTlMA/SoEHOX1RcdliKnuQ9TkAAAACXBIWXMAAAsTAAALEwEAmpwYAAAB4UlEQVR42u1XyRbDIAhUcQ/8/+9WUROzNIvtMbxefMo4yACpEOcG4geD30G0C07B8P0qWkzm3QgJEBAsIUqURJMe8NcToZTlR8YJgGev5wwVd2QEG+FZGIl+9iUyloGQvL5NIt2V6RfqoCPRHMZN/0ofy+NBKEsO41b4wVaHADWdvgGqGyR0o5/Tvw/pmr7v6C/XhRbVaTYqfU5bgPVGDUNmYDgXT6UP28xEvAyjpw/H2pD5wGE2ivZZPGv6fXF5JlhEdfr68AUB4vdsqHP6DWPWyDYbITsz/asecXDR+vXPtZbOdmG0o7324dJYVFypLRu6+ptws9aV53glhUIqMCDaqNxdKwjkoQDkzpkAjL1vWwCJA1YBUgpRjlkDULl9jxjFudjHbBkXWg3ZT4N3q9AkMOXUrMM0VZ3oVJk3QXSbvNi0CzNXUimZ2LeatBl7Ie57CiQ9k9EVYEripKVYwJMlq+qKN3eyVzaLu/pArtl0pgFok6XS1j6fjI8BUDZGvPkCvAAvwJdiuipnuZRzJL5q93li0M53pp6Bq4bicZnb2kuMh/8Num9ycOsP9NUalBJ/trG2rmH5/Boabji1FxsbbFhzmaezHAPANlxxcDwvwzWNZ3ps2P0X02MG4rX/2Ad4/i9F5OK4gwAAAABJRU5ErkJggg==";const Pn=e=>{const t=Math.round(e*1e5)/1e5;return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:5}).format(t)},Qo=e=>{const t=Math.round(e*1e5)/1e5;return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:5}).format(t)},Si=({balanceData:e,isLoading:t=!1,styles:s,className:o="",showHeader:a=!0,onAccountClick:r,onDepositClick:i,onWithdrawClick:d,vaultBalance:u,fetchVaultBalance:l,onWithdrawExecute:h,withdrawActionLabel:f,destinationChainId:m,destinationTokenAddress:x,customSections:g,showDefaultSections:y=!0})=>{const k=c.useContext(p.SpiceFlowProviderContext),S=(k?.mode||"7702")!=="7702",b=k?.appName||"Spicenet",{dark:C,primaryColor:v,dk:w,theme:A}=p.useSpiceBrand(s),[E,M]=c.useState(!0),[B,I]=c.useState(!1),[T,D]=c.useState(!1),[R,U]=c.useState(null),{isConnected:L}=It.useAccount(),{disconnect:W}=It.useDisconnect();c.useEffect(()=>{S&&l&&l().then(H=>{const G=Math.round(H*1e5)/1e5;U(G)}).catch(H=>{console.error("Error fetching vault balance:",H),U(null)})},[S,l]);const Q=()=>{M(!E)},N=c.useMemo(()=>{if(!e.freeCollateralItems)return null;const H=e.freeCollateralItems.filter(z=>z.name==="USDC");if(H.length===0)return null;const G=H.reduce((z,ee)=>z+ee.balance,0),ce=[];return H.forEach(z=>{z.networks&&z.networks.forEach(ee=>{(ee===1||ee===11155111||ee===8453||ee===84532)&&(ce.includes(ee)||ce.push(ee))})}),ce.length===0&&ce.push(1,8453),{name:"USDC",totalBalance:G,networks:ce,subtitle:H[0]?.subtitle||"USD COIN"}},[e.freeCollateralItems]),O=c.useMemo(()=>{if(S){if(R!==null)return R;if(u!=null)return u}return e.freeCollateralItems?e.freeCollateralItems.reduce((H,G)=>H+G.balance,0):e.freeCollateral},[S,R,u,e.freeCollateralItems,e.freeCollateral]),q=H=>E?H:"******",K=()=>{W(),I(!1),D(!1)};return n.jsxs("div",{className:o,style:{borderRadius:"16px",backgroundColor:C?w.shell:"#D5D5D5",width:"522px",padding:"8px",fontFamily:s?.fontFamily||'"Helvetica Neue", sans-serif',...s?.container},children:[n.jsxs("div",{style:{background:C?w.cardBg:" white",display:"flex",flexDirection:"column"},children:[n.jsxs("div",{style:{backgroundColor:C?w.inputBg:"#E9E9E9",borderRadius:"0 0 16px 16px",padding:"20px",display:"flex",flexFlow:"column"},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"4px"},children:[n.jsxs("p",{style:{fontSize:"14px",fontWeight:500,fontFamily:'"IBM Plex Mono", monospace',color:C?w.textPrimary:"#0E0D0B",margin:0},children:[b.toUpperCase()," BALANCE"]}),L&&n.jsx("button",{onClick:K,"aria-label":"Disconnect wallet",style:{width:"36px",height:"36px",borderRadius:"8px",border:C?`1px solid ${v}33`:"1px solid #E5E7EB",background:C?w.inputBg:"white",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",transition:Ut.interactive,padding:"8px"},onMouseEnter:H=>{H.currentTarget.style.backgroundColor=C?w.cardBg:"#F3F4F6"},onMouseLeave:H=>{H.currentTarget.style.backgroundColor=C?w.inputBg:"white"},children:n.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),n.jsx("polyline",{points:"16 17 21 12 16 7"}),n.jsx("line",{x1:"21",y1:"12",x2:"9",y2:"12"})]})})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.percentageChange!==void 0&&e.percentageChange!==null&&n.jsxs("div",{style:{fontSize:"13px",fontWeight:700,color:e.percentageChange>=0?C?w.successText:"#009C51":C?w.errorText:"#EF4444"},children:[e.percentageChange>=0?"+":"",e.percentageChange.toFixed(2),"%"]}),n.jsx("button",{onClick:Q,style:{background:"none",border:"none",cursor:"pointer",padding:"8px",display:"flex",alignItems:"center",justifyContent:"center",transition:"opacity 0.2s ease"},onMouseEnter:H=>{H.currentTarget.style.opacity="0.7"},onMouseLeave:H=>{H.currentTarget.style.opacity="1"},children:E?n.jsxs("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",children:[n.jsx("path",{d:"M12 5C7 5 2.73 8.11 1 12.5C2.73 16.89 7 20 12 20C17 20 21.27 16.89 23 12.5C21.27 8.11 17 5 12 5Z",stroke:C?w.textSecondary:"#1A1A1A",strokeWidth:"2",fill:"none"}),n.jsx("circle",{cx:"12",cy:"12.5",r:"3",stroke:C?w.textSecondary:"#1A1A1A",strokeWidth:"2",fill:"none"})]}):n.jsxs("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",children:[n.jsx("path",{d:"M12 5C7 5 2.73 8.11 1 12.5C2.73 16.89 7 20 12 20C17 20 21.27 16.89 23 12.5C21.27 8.11 17 5 12 5Z",stroke:C?w.textSecondary:"#1A1A1A",strokeWidth:"2",fill:"none"}),n.jsx("path",{d:"M3 3L21 21",stroke:C?w.textSecondary:"#1A1A1A",strokeWidth:"2",strokeLinecap:"round"})]})})]}),n.jsx("p",{style:{fontSize:"40px",fontWeight:700,color:C?w.textPrimary:"black"},children:q(Pn(S&&R!==null?R:S&&u!==void 0&&u!==null?u:e.totalBalance))}),n.jsxs("div",{style:{display:"flex",gap:"12px",marginTop:"16px"},children:[n.jsx(p.Button,{variant:"outline",fullWidth:!0,onClick:()=>{i?i():I(!0)},theme:A,dark:C,styles:s,children:"DEPOSIT"}),n.jsx(p.Button,{variant:"outline",fullWidth:!0,onClick:()=>{d?d():D(!0)},theme:A,dark:C,styles:s,children:"WITHDRAW"})]})]}),n.jsxs("div",{style:{background:C?w.cardBg:"white",padding:"12px 20px",borderRadius:"12px"},children:[y&&n.jsx(go,{title:"FREE COLLATERAL",icon:vi,amount:q(Qo(O)),defaultExpanded:!1,children:S&&(R!==null||u!=null)?n.jsx(qn,{name:"USDC",balance:q(Pn(R!==null?R:u)),subtitle:"USD COIN",icon:Mn,onClick:r?()=>r("usdc-vault"):void 0}):N?n.jsx(qn,{name:N.name,balance:q(Pn(N.totalBalance)),subtitle:N.subtitle,networks:N.networks,icon:Mn,onClick:r?()=>r(N.name):void 0}):e.freeCollateralItems&&e.freeCollateralItems.length>0?e.freeCollateralItems.map((H,G)=>n.jsxs(c.Fragment,{children:[n.jsx(qn,{name:H.name,balance:q(Pn(H.balance)),subtitle:H.subtitle,networks:H.networks,icon:H.name==="USDC"?Mn:void 0,onClick:r?()=>r(H.id):void 0}),G<e.freeCollateralItems.length-1&&n.jsx("div",{style:{height:"1px",backgroundColor:C?w.cardBorder:"#D0D2D8",margin:"4px 0"}})]},H.id)):n.jsx("div",{style:{padding:"12px 0",color:C?w.textSecondary:"#6B7280",fontSize:"13px",fontFamily:'"IBM Plex Mono", monospace'},children:"No collateral items available"})}),g&&g.length>0&&g.filter(H=>H&&H.id&&H.title&&typeof H.title=="string"&&H.title.trim().length>0).map(H=>n.jsx(go,{title:H.title,icon:H.icon||void 0,amount:q(Qo(H.totalBalance||0)),defaultExpanded:H.defaultExpanded!==void 0?H.defaultExpanded:!1,children:H.items&&H.items.length>0?H.items.map((G,ce)=>n.jsxs(c.Fragment,{children:[n.jsx(qn,{name:G.name,balance:q(Pn(G.balance)),subtitle:G.subtitle,networks:G.networks,icon:G.name==="USDC"?Mn:void 0,onClick:r?()=>r(G.id):void 0}),ce<H.items.length-1&&n.jsx("div",{style:{height:"1px",backgroundColor:C?w.cardBorder:"#D0D2D8",margin:"4px 0"}})]},G.id||`item-${ce}`)):n.jsx("div",{style:{padding:"12px 0",color:C?w.textSecondary:"#6B7280",fontSize:"13px",fontFamily:'"IBM Plex Mono", monospace'},children:H.emptyMessage||"No items available"})},H.id))]})]}),B&&n.jsx(mo,{isOpen:B,onClose:()=>I(!1),styles:s}),T&&n.jsx(Ho,{isOpen:T,onClose:()=>D(!1),styles:s,onWithdrawExecute:h,withdrawActionLabel:f})]})},Ii=({options:e,selectedIndex:t,onSelect:s,primaryColor:o,dark:a=!1,textPrimary:r="#111827",textSecondary:i="#6b7280",trackColor:d})=>{const u=e.length-1,l=d||(a?"#3a3a3a":"#d1d5db"),h=a?"4px":"50%",f=a?"none":"2px solid white",m=a?"none":`0 0 0 1px ${o}`;return n.jsxs("div",{style:{width:"100%",userSelect:"none"},children:[n.jsxs("div",{style:{position:"relative",paddingBottom:"4px"},children:[n.jsx("div",{style:{position:"absolute",top:"50%",left:0,right:0,height:"4px",background:l,borderRadius:"2px",transform:"translateY(-50%)",pointerEvents:"none"}}),n.jsx("div",{style:{position:"absolute",top:"50%",left:0,width:`${t/u*100}%`,height:"4px",background:o,borderRadius:"2px",transform:"translateY(-50%)",pointerEvents:"none",transition:"width 0.15s ease"}}),n.jsx("input",{type:"range","aria-label":"Lock duration","aria-valuetext":e[t]?.label,"data-spiceflow-focus":!0,min:0,max:u,step:1,value:t,onChange:x=>s(Number(x.target.value)),style:{WebkitAppearance:"none",appearance:"none",width:"100%",height:"20px",background:"transparent",cursor:"pointer",outline:"none",border:"none",position:"relative",zIndex:1,margin:0,padding:0}})]}),n.jsx("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"6px"},children:e.map((x,g)=>n.jsxs("div",{onClick:()=>s(g),style:{display:"flex",flexDirection:"column",alignItems:g===0?"flex-start":g===u?"flex-end":"center",cursor:"pointer",flex:1},children:[n.jsx("span",{style:{fontSize:"12px",fontWeight:g===t?700:400,color:g===t?r:i,whiteSpace:"nowrap",transition:"color 0.15s, font-weight 0.15s"},children:x.label}),x.highlight&&n.jsx("span",{style:{fontSize:"10px",color:i,whiteSpace:"nowrap"},children:"(most common)"})]},g))}),n.jsx("style",{children:`
66
+ `})]})},Es=new Set(["WBTC","CBTC"]),Co=new Set(["btc","wbtc","wcbtc","cbtc"]);function bo(e,t){return!e||!t?!1:e===t?!0:Es.has(e)&&Es.has(t)}function In(e){const[t,s,o]=e.split(":");if(t!=="evm"||!s||!o)return null;const a=Number(s);if(!Number.isFinite(a))return null;const r=o.startsWith("0x")?o.toLowerCase():`0x${o.toLowerCase()}`;return{chainId:a,address:r}}function Kn(e){return(e??"").trim().replace(/^test\s+/i,"").replace(/^spice/i,"").toLowerCase().replace(/[^a-z0-9]/g,"")}function Da(e){return new Set([e.receiptTokenName,e.displaySymbol,e.symbol,e.displayName,e.name].map(Kn).filter(Boolean))}function Na(e,t){const s=Da(e),o=[t.symbol,t.name,t.equivalenceGroup].map(Kn);if(o.some(i=>i&&s.has(i)))return!0;const a=[...s].some(i=>Co.has(i)),r=o.some(i=>Co.has(i))||Es.has(t.equivalenceGroup??"");return a&&r}function wo(e,t,s){const o=new Set(t.map(Kn).filter(Boolean)),a=r=>{if(s&&p.addressesEqual(r.address,s))return 0;const i=[r.symbol,r.name,r.equivalenceGroup].map(Kn).findIndex(d=>d&&o.has(d));return i===-1?4:i+1};return[...e].sort((r,i)=>{const d=a(r)-a(i);return d!==0?d:r.address.toLowerCase().localeCompare(i.address.toLowerCase())})}const ko=typeof process<"u"&&process.env?.NEXT_PUBLIC_MORALIS_API_KEY||typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:yn&&yn.tagName.toUpperCase()==="SCRIPT"&&yn.src||new URL("index.cjs.js",document.baseURI).href}<"u"&&void 0||"",Wa="https://deep-index.moralis.io/api/v2.2";function Zn(e,t){const s=e.chainTokens?Object.keys(e.chainTokens):[],o=[];for(const a of s){const r=In(a);if(!r||r.chainId!==t)continue;const i=r.address,d=F.getTokenByAddress(i,t);d&&(!js(e,i,t)&&!(e.isUniversal&&Na(e,d))||o.some(u=>p.addressesEqual(u,i))||o.push(i))}return wo(o.map(a=>{const r=F.getTokenByAddress(a,t);return{address:a,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(a=>a.address)}function js(e,t,s){return e.chainId===s&&p.addressesEqual(e.address,t)?!0:Nn(e.address,e.chainId,t,s)}async function Ua(e,t){const s=p.getClientForChain(e),o=F.getEscrowContractAddress(e);return F.isNativeToken(t)?s.getBalance({address:o}):await s.readContract({address:t,abi:j.erc20Abi,functionName:"balanceOf",args:[o]})}function vo(e,t,s){const o=F.getTokensForChain(s),a=o.find(i=>p.addressesEqual(i.address,e));if(a)return a;const r=F.getTokenByAddress(e,t);if(r)return wo(o.filter(i=>bo(i.equivalenceGroup,r.equivalenceGroup)),[r.symbol,r.name,r.equivalenceGroup])[0]}function $t(e,t){if(e.chainId===t)return e.address;const s=vo(e.address,e.chainId,t);return s?s.address:null}async function So(e,t,s={}){const o=$t(e,t),a=Zn(e,t);if(a.length===0)return o;if(a.length===1)return a[0];const r=s.requiredAmount??0n,i=u=>{const l=a.map(h=>({candidate:h,balance:u.get(F.isNativeToken(h)?"native":h.toLowerCase())??0n})).filter(h=>h.balance>0n).sort((h,f)=>h.balance===f.balance?0:h.balance>f.balance?-1:1);return l.length===0?null:((r>0n?l.find(h=>h.balance>=r):l[0])??l[0]).candidate},d=p.getChainsForAssets()[t];if(d?.moralisName&&ko){const u=new Map,l=a.some(h=>F.isNativeToken(h));try{if(l)try{const f=p.getClientForChain(t),m=F.getEscrowContractAddress(t);u.set("native",await f.getBalance({address:m}))}catch{}const h=await fetch(`${Wa}/wallets/${F.getEscrowContractAddress(t)}/tokens?chain=${d.moralisName}`,{headers:{"X-API-Key":ko}});if(h.ok){const f=await h.json();for(const x of f?.result||[]){const g=String(x.token_address||"").toLowerCase();if(g)try{u.set(g,BigInt(String(x.balance||"0")))}catch{}}const m=i(u);if(m)return m}}catch{}}try{const u=await Promise.all(a.map(async f=>({key:F.isNativeToken(f)?"native":f.toLowerCase(),value:await Ua(t,f)}))),l=new Map(u.map(({key:f,value:m})=>[f,m])),h=i(l);if(h)return h}catch{}return o}function Nn(e,t,s,o){const a=F.getTokenByAddress(e,t),r=F.getTokenByAddress(s,o);return a&&r?bo(a.equivalenceGroup,r.equivalenceGroup):F.areEquivalent(e,s)}function Yn(e,t){return Nn(e.address,e.chainId,t.address,t.chainId)}const Pa={usdc:[8453,1,42161,5115,4114],usdt:[1],btc:[4114,42161,1,5115],wbtc:[1],weth:[8453,1],ctusd:[5115,4114],wcbtc:[5115,4114]},za={btc:["wcbtc","cbtc","wbtc"]};function Gn(e){return e.replace(/^test\s+/i,"").replace(/^spice/i,"").trim()}function nn(e){return Gn(e).toLowerCase()}function Io(e){return nn(e??"").replace(/[^a-z0-9]/g,"")}function Fs(e){const t=nn(e);return[t,...za[t]??[]].filter(Boolean)}function La(e){try{return BigInt(e.balanceAvailable||"0")}catch{return 0n}}function Oa(e){return Array.isArray(e.chainTokens)?e.chainTokens:Object.keys(e.chainTokens??{})}function Ha(e,t,s,o=[]){const a=p.getChainConfig(t),r=s.toLowerCase(),i=r===F.ZERO_ADDRESS.toLowerCase()?a?.nativeCurrency.decimals??18:a?.supportedTokens?.find(u=>u.address.toLowerCase()===r)?.decimals??18,d=new Set(o.map(Io).filter(Boolean));return e.reduce((u,l)=>{const h=La(l),f=l.decimals??i,m=F.convertAmountBetweenDecimals(h,f,i);if(Oa(l).some(g=>{const y=In(g);return y&&Nn(y.address,y.chainId,s,t)}))return u+m;if(d.size===0)return u;const x=Io(l.tokenName||l.receiptToken);return d.has(x)?u+m:u},0n)}function Qa(e,t){const s=new Set([...Fs(t),...Fs(Gn(t))]);return[...e].sort((o,a)=>{const r=nn(o.symbol),i=nn(a.symbol),d=nn(o.name),u=nn(a.name),l=s.has(r)?0:s.has(d)?1:2,h=s.has(i)?0:s.has(u)?1:2;return l!==h?l-h:o.address.toLowerCase().localeCompare(a.address.toLowerCase())})[0]}function Va(e){const t=e&&e.length>0?e:Object.keys(p.CHAIN_CONFIGS).map(Number).filter(Number.isFinite),s=new Map;for(const o of t){const a=p.getChainConfig(o);if(!a)continue;const r=`${o}:${F.ZERO_ADDRESS.toLowerCase()}`;s.has(r)||s.set(r,{address:F.ZERO_ADDRESS,chainId:o,symbol:a.nativeCurrency.symbol,name:a.nativeCurrency.name,decimals:a.nativeCurrency.decimals,isNative:!0,logoURI:a.logo});for(const i of a.supportedTokens??[]){const d=i.address.toLowerCase(),u=`${o}:${d}`;s.has(u)||s.set(u,{address:d,chainId:o,symbol:i.symbol,name:i.name,decimals:i.decimals,isNative:F.isNativeToken(d),logoURI:i.logo})}}return s}function qa(e,t){const s=Va(t),o=Gn(e.tokenName),a=nn(e.tokenName),r=Fs(e.tokenName),i=Array.isArray(e.chainTokens)?e.chainTokens.map(g=>[g,void 0]):Object.entries(e.chainTokens??{}),d=i.map(([g])=>In(g)).filter(g=>g!==null),u=new Map(i.map(([g,y])=>[g,y])),l=(g,y)=>{const k=u.get(`evm:${y.chainId}:${y.address.slice(2).toLowerCase()}`);return{...g,name:typeof k?.name=="string"&&k.name.length>0?k.name:g.name,decimals:typeof k?.decimals=="number"?k.decimals:g.decimals}},h=d.map(g=>{const y=s.get(`${g.chainId}:${g.address.toLowerCase()}`);return y?l(y,g):void 0}).filter(g=>g!==void 0),f=Pa[a]??[];if(f.length>0)for(const g of f){const y=h.find(k=>k.chainId===g);if(y)return y}if(h.length>0)return Qa(h,e.tokenName);const m=Array.from(s.values()).filter(g=>r.includes(nn(g.symbol))||r.includes(nn(g.name)));if(f.length>0)for(const g of f){const y=m.find(k=>k.chainId===g);if(y)return y}if(m.length>0)return m[0];const x=d[0];if(x){const g=u.get(`evm:${x.chainId}:${x.address.slice(2).toLowerCase()}`);return{address:x.address,chainId:x.chainId,symbol:o||e.tokenName,name:typeof g?.name=="string"&&g.name.length>0?g.name:o||e.tokenName,decimals:typeof g?.decimals=="number"?g.decimals:e.decimals??18,isNative:F.isNativeToken(x.address),logoURI:void 0}}}function Ka(e,t){let s;try{s=BigInt(e.balanceAvailable||"0")}catch{return null}if(s<=0n)return null;const o=qa(e,t),a=o?.decimals??e.decimals??18,r=e.decimals??a,i=F.convertAmountBetweenDecimals(s,r,a),d=o?.address??F.ZERO_ADDRESS,u=o?.chainId??0,l=Gn(e.tokenName),h=o?.symbol??l,f=o?.name??l,m=parseFloat(j.formatUnits(i,a)),x=typeof e.balanceUsd=="number"?e.balanceUsd:typeof e.balanceUsd=="string"&&Number(e.balanceUsd)||0;return{address:d,symbol:h,name:f,decimals:a,chainId:u,balance:i,balanceFormatted:m,balanceUsd:x,isNative:o?.isNative??F.isNativeToken(d),logoURI:o?.logoURI,displaySymbol:e.tokenName||h,displayName:e.tokenName||f,displayChainName:"Spicenet",receiptTokenId:e.receiptToken,receiptTokenName:e.tokenName||f,receiptTokenDecimals:r,chainTokens:e.chainTokens&&!Array.isArray(e.chainTokens)?e.chainTokens:void 0,isUniversal:!0}}function Za(e){const t=e.chainTokens??e.chainTokenConfig;if(Array.isArray(t))return t.filter(s=>typeof s=="string");if(t&&typeof t=="object")return t}const Wn=({address:e,supportedChains:t,enabled:s=!0,refetchInterval:o})=>{const a=c.useContext(p.SpiceFlowProviderContext)?.apiUrl||p.RELAYER_API_URL,[r,i]=c.useState([]),[d,u]=c.useState(!1),[l,h]=c.useState(null),[f,m]=c.useState(!1),x=c.useRef(!1),g=c.useRef(!1),y=t?JSON.stringify([...t].sort()):"",k=c.useCallback(async(C=!1)=>{if(!e||!s){i([]),m(!1),x.current=!1;return}if(!g.current){g.current=!0,!x.current&&!C&&u(!0),h(null);try{const v=await fetch(`${a}/wallets/${e}/balance`,{cache:"no-store"});if(!v.ok)throw new Error(`Failed to fetch balance: ${v.status}`);const w=await v.json();if(w.balances&&Array.isArray(w.balances)){const A=w.balances.map(E=>Ka({receiptToken:typeof E.receiptToken=="string"?E.receiptToken:void 0,tokenName:String(E.tokenName??""),balanceAvailable:String(E.balanceAvailable??"0"),chainTokens:Za(E),decimals:typeof E.decimals=="number"?E.decimals:void 0,balanceUsd:typeof E.balanceUsd=="number"||typeof E.balanceUsd=="string"?E.balanceUsd:null},t)).filter(E=>E!==null);i(A),m(A.length>0),x.current=!0}else i([]),m(!1)}catch(v){const w=v instanceof Error?v.message:"Failed to fetch balance";h(w),console.error("Error fetching Spice assets:",v),x.current||(i([]),m(!1))}finally{u(!1),g.current=!1}}},[e,s,y,a]);c.useEffect(()=>{s&&e&&(x.current=!1,k(!1))},[e,s,y]),c.useEffect(()=>{if(!s||!e||!o)return;const C=setInterval(()=>{k(!0)},o);return()=>clearInterval(C)},[e,s,o,y]);const S=c.useCallback(C=>r.filter(v=>v.chainId===C),[r]),b=c.useCallback(async()=>{await k(!0)},[k]);return{assets:r,loading:d,error:l,hasBalance:f,refetch:b,getAssetsByChain:S}},Ao=e=>new Promise(t=>setTimeout(t,e));function Ya(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 Ga=350,Xa=1e3;async function Ja(e){const{actionId:t,intentIndex:s,intentId:o,stepIndex:a,maxPolls:r=120,maxExecuteAttempts:i=3,pollsBeforeRetry:d=5,maxConsecutiveStatusErrors:u=15,onStatusMessage:l,signal:h,chainId:f}=e;let m="pending",x,g,y=0,k=0;const S=()=>{y++,p.relayerService.executeStep(t,s,a,{action:"execute"}).then(b=>{b.transactionHash&&(x=b.transactionHash)}).catch(b=>{const C=b instanceof Error?b.message:String(b);console.warn(`[execution] executeStep ${a} attempt ${y} error (will poll):`,C)})};S();for(let b=0;b<r;b++){if(await Ao(b===0?Ga:Xa),h?.aborted)throw new p.SpiceflowError("ABORT","Gasless transaction aborted");try{const v=await p.relayerService.checkStepStatus(o,a);k=0,m=v.data.status,g=v.data.error;const w=v.data.transactionHash;w&&(x=w)}catch(v){if(v instanceof Error&&(v.name==="AbortError"||v instanceof p.SpiceflowError&&v.code==="ABORT")||(k++,k>=u))throw v;continue}if(m==="created"&&b>=y*d&&y<i&&S(),m==="reverted"||m==="error")throw new p.SpiceflowError("ON_CHAIN_REVERT",Ya(m,g),{status:m,txHash:x,actionId:t,intentId:o,stepId:a,chainId:f});if(m==="success"||m==="completed")return x;let C="Waiting for solver...";m==="executing"?C="Transaction executing...":m==="submitted"?C="Transaction submitted...":m==="created"&&(C="Waiting for relayer..."),l?.(C,x)}throw new p.SpiceflowError("POLLING_EXHAUSTED",`Transaction is still processing (status: ${m}). 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:o,stepId:a,lastStatus:m,pollAttempts:r,maxPolls:r,txHash:x})}async function Eo(e){const{actionId:t,intentIndex:s,intentId:o,totalSteps:a,delayBeforeSpicenetStepMs:r=5e3,isSpicenetStep:i,maxExecuteAttemptsForStep:d,maxPolls:u=120,onStatusMessage:l,signal:h}=e;let f;for(let m=0;m<a;m++){m>0&&i?.(m)&&r>0&&await Ao(r);const x=d?.(m)??3,g=await Ja({actionId:t,intentIndex:s,intentId:o,stepIndex:m,maxPolls:u,maxExecuteAttempts:x,maxConsecutiveStatusErrors:x===6?5:15,onStatusMessage:l,signal:h});g&&(f=g)}return f}function Bs(e,t){return e<=0n||t<=0n?0n:(e*t+10000n-1n)/10000n}function sn(e){const t=BigInt(e.feeBreakdown.spicenetFee),s=BigInt(e.feeBreakdown.gasFee),o=BigInt(e.feeBreakdown.bridgeFee??"0"),a=t+s+o;return{spicenetFee:t,gasFee:s,bridgeFee:o,totalFee:a}}function jo(e){const t=BigInt(e.quotedAmount),s=BigInt(e.totalDebit),{totalFee:o}=sn(e);return t>0n||s>0n||o>0n}function $a(e){const t=BigInt(e.quotedAmount),s=BigInt(e.totalDebit),{totalFee:o}=sn(e),a=t+o;return s>a?s:a}function _a(e){const t=[];for(const s of e.intents)for(const o of s.batches)t.push(BigInt(o.quotedAmount));return t.length!==1?null:t[0]}function Un(e,t){const s=e.intents.flatMap(l=>l.batches).filter(jo);if(s.length===0||s.length>1)return null;const o=s[0],{gasFee:a,spicenetFee:r,bridgeFee:i,totalFee:d}=sn(o),u=t.actionAmount??BigInt(o.quotedAmount);return{symbol:t.symbol,decimals:t.decimals,grossAmount:u+d,netAmount:u,totalFee:d,spicenetFee:r,gasFee:a,bridgeFee:i,gasQuoteSource:o.gasQuoteSource}}function mn(e,t){const s=e.intents.flatMap(h=>h.batches).filter(jo);if(s.length===0)return null;const o=s.filter(h=>h.chainId===t.chainId),a=o.length>0?o:s;if(a.length>1)return null;const r=a[0],{gasFee:i,spicenetFee:d,bridgeFee:u,totalFee:l}=sn(r);return{chainId:r.chainId,tokenAddress:t.tokenAddress,symbol:t.symbol,decimals:t.decimals,grossAmount:$a(r),netAmount:BigInt(r.quotedAmount),totalFee:l,gasFee:i,spicenetFee:d,bridgeFee:u,gasQuoteSource:r.gasQuoteSource}}const ei=10n,ti=5;function Xn(e){return e.map(t=>({...t,calls:[...t.calls],tokenTransfers:t.tokenTransfers?[...t.tokenTransfers]:void 0}))}function Jn({token:e,recipient:t,amount:s}){return{to:e,value:0n,data:j.encodeFunctionData({abi:p.U,functionName:"transfer",args:[t,s]})}}function Fo({chainBatches:e,token:t,amount:s}){const o=Xn(e),a=o[o.length-1];if(!a)return o;const r=F.getEscrowContractAddress(a.chainId);return a.calls=[...a.calls,Jn({token:t,recipient:r,amount:s})],o}function Bo({chainBatches:e,user:t,token:s,grossAmount:o,gasFee:a}){const r=Xn(e),i=r[r.length-1];if(!i)throw new p.SpiceflowError("INVALID_PARAMS","Action-output escrow funding requires at least one chain batch.");const d=Bs(o,ei),u=a+d;if(u>=o)throw new p.SpiceflowError("INVALID_PARAMS","Borrow amount is too small after gas and Spicenet fees.",{grossAmount:o.toString(),gasFee:a.toString(),spicenetFee:d.toString()});const l=o-u,h=F.getEscrowContractAddress(i.chainId),f=[];return a>0n&&f.push(Jn({token:s,recipient:F.SPICE_GAS_FEE_RECIPIENT,amount:a})),d>0n&&f.push(Jn({token:s,recipient:F.SPICE_PLATFORM_FEE_RECIPIENT,amount:d})),i.calls=[...i.calls,...f,Jn({token:s,recipient:h,amount:l})],i.tokenTransfers=[...i.tokenTransfers??[],...a>0n?[{from:t,to:F.SPICE_GAS_FEE_RECIPIENT,token:s,amount:a}]:[],...d>0n?[{from:t,to:F.SPICE_PLATFORM_FEE_RECIPIENT,token:s,amount:d}]:[],{from:t,to:h,token:s,amount:l}],{chainBatches:r,gasFee:a,spicenetFee:d,netEscrowAmount:l,outputCredit:{chainId:i.chainId,token:s,amount:o}}}async function To({chainBatches:e,user:t,token:s,grossAmount:o,chainAuthorizations:a}){let r=0n,i=Bo({chainBatches:e,user:t,token:s,grossAmount:o,gasFee:r});for(let d=0;d<ti;d+=1){const u=F.hashChainBatches(i.chainBatches),l=(await p.relayerService.estimateBatchGas({user:t,outputToken:s,chainBatches:i.chainBatches.map((h,f)=>({...h,hash:u[f].hash})),chainAuthorizations:a})).gasFee;if(l===r)return i;r=l,i=Bo({chainBatches:e,user:t,token:s,grossAmount:o,gasFee:r})}throw new p.SpiceflowError("INVALID_PARAMS","Action-output fee estimate did not converge. Please retry.")}function gn(e){return F.isSpicenetChainId(e.chainId)}function ni(e,t){if(e.length!==t.length)return!1;const s=F.hashChainBatches(e),o=F.hashChainBatches(t);return s.every((a,r)=>a.hash===o[r]?.hash)}const Mo="0xa9059cbb";function $n(e,t){return`${e}:${t.toLowerCase()}`}function Ro(e,t){return t===F.ZERO_ADDRESS.toLowerCase()?{symbol:p.getChainName(e),decimals:18}:F.getTokenByAddress(t,e)??{symbol:"tokens",decimals:18}}function si(e,t){const s=F.getTokenByAddress(t,e);return[s?.equivalenceGroup,s?.symbol,s?.name]}async function oi(e){return p.getWalletBalanceEntries(e)}function Ts(e,t){return e.map(s=>{if(gn(s)||s.calls.length===0)return s;const o=new Set((s.tokenTransfers??[]).filter(r=>(r.from==="escrow"||r.from==="solver")&&p.addressesEqual(r.to,t)).map(r=>r.token.toLowerCase()));if(o.size===0)return s;let a=0;for(const r of s.calls){if(!r.data?.startsWith(Mo))break;try{const i=j.decodeFunctionData({abi:p.U,data:r.data});if(i.functionName!=="transfer")break;const[d]=i.args;if(p.addressesEqual(d,t)||!o.has(r.to.toLowerCase()))break;a+=1}catch{break}}return a===0?s:{...s,calls:s.calls.slice(a)}})}async function ri(e,t,s){const o=new Map,a=new Map,r=new Map,i=new Map;for(const u of s?.actionOutputCredits??[]){const l=$n(u.chainId,u.token);i.set(l,(i.get(l)??0n)+u.amount)}for(const u of e)if(!gn(u)){for(const l of u.tokenTransfers??[]){if(l.from!=="escrow"&&l.from!=="solver"||!p.addressesEqual(l.to,t))continue;const h=BigInt(l.amount??0);if(h<=0n)continue;const f=$n(u.chainId,l.token);a.set(f,(a.get(f)??0n)+h),l.from==="escrow"&&r.set(f,(r.get(f)??0n)+h)}for(const l of u.calls){if(l.value&&l.value>0n){const h=$n(u.chainId,F.ZERO_ADDRESS);o.set(h,(o.get(h)??0n)+l.value)}if(l.data?.startsWith(Mo))try{const h=j.decodeFunctionData({abi:p.U,data:l.data});if(h.functionName!=="transfer")continue;const[,f]=h.args,m=l.to.toLowerCase(),x=$n(u.chainId,m);o.set(x,(o.get(x)??0n)+f)}catch{}}}let d=null;for(const[u,l]of r){if(l<=0n)continue;const[h,f]=u.split(":"),m=Number(h),x=Ro(m,f);d??(d=await oi(t));const g=Ha(d,m,f,si(m,f));if(!(g>=l))throw new p.SpiceflowError("INVALID_PARAMS",`Insufficient Spice ${x.symbol}: needs ${j.formatUnits(l,x.decimals)}, has ${j.formatUnits(g,x.decimals)}.`,{chainId:m,token:f,userAddress:t,requiredAmount:l.toString(),balance:g.toString(),balanceSource:"spice"})}for(const[u,l]of o){if(l<=0n)continue;const[h,f]=u.split(":"),m=Number(h),x=l-(a.get(u)??0n)-(i.get(u)??0n);if(x<=0n)continue;const g=p.getClientForChain(m),y=f===F.ZERO_ADDRESS.toLowerCase()?await g.getBalance({address:t}):await g.readContract({address:f,abi:p.U,functionName:"balanceOf",args:[t]});if(y>=x)continue;const k=Ro(m,f);throw new p.SpiceflowError("INVALID_PARAMS",`Insufficient ${k.symbol} on ${p.getChainName(m)}: needs ${j.formatUnits(x,k.decimals)}, has ${j.formatUnits(y,k.decimals)}.`,{chainId:m,token:f,userAddress:t,requiredAmount:x.toString(),balance:y.toString(),balanceSource:"wallet"})}}function ai({chainBatches:e,tokenAddress:t,tokenTransferAmount:s,useCustomTransfers:o}){if(!(e.some(gn)||!(o?e.some(a=>gn(a)?!1:(a.tokenTransfers??[]).some(r=>r.from==="escrow"&&BigInt(r.amount??0)>0n)):s>0n)))throw new p.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:s.toString(),useCustomTransfers:!!o})}function ii(e,t,s,o){t.forEach((a,r)=>{if(!a.to||!a.from||!a.token||a.amount===void 0)throw new p.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:a.from,to:a.to,token:a.token,amount:a.amount?.toString()},signingAddress:s,useCustomTransfers:o})})}function Ms({user:e,chainBatches:t,tokenAddress:s,tokenTransferAmount:o,exp:a,signature:r,chainAuthorizations:i,useCustomTransfers:d}){const u=t,l=F.hashChainBatches(u),h=u.filter(f=>!gn(f)).length;if(ai({chainBatches:u,tokenAddress:s,tokenTransferAmount:o,useCustomTransfers:d}),!d&&o>0n&&h>1)throw new p.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:h,tokenAddress:s,tokenTransferAmount:o.toString()});return{user:e,...i?{chainAuthorizations:i}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:r,nbf:0,exp:a,chainBatches:l.map((f,m)=>{const x=u[m],g=gn(x)?[]:d?x.tokenTransfers??[]:o>0n?[{from:"escrow",to:e,token:s,amount:o}]:[];return ii(Number(f.chainId),g,e,d),{hash:f.hash,chainId:Number(f.chainId),tokenTransfers:g,calls:f.calls}})}]}}function li(e,t){const s=F.hashChainBatches(e).map(o=>o.hash);return j.keccak256(j.encodeAbiParameters([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,t,s]))}let Rs=!1;function _n(){const{address:e,isConnected:t,isAuthenticated:s,actions:o}=p.useWallet(),[a,r]=c.useState(null),i=c.useRef(o),d=c.useRef(new Map);i.current=o;const u=c.useCallback(async(m,x,g)=>{const y=[...new Set(m.filter(b=>!gn(b)).map(b=>b.chainId))],k=await Promise.all(y.map(async b=>{const C=p.getClientForChain(b),v=p.getDelegateContractAddress(b),w=Number(await F.getAccountNonce(x,C)),A=[x.toLowerCase(),b,v.toLowerCase(),w].join(":");return{chainId:b,delegateContract:v,nonce:w,cacheKey:A,cached:d.current.get(A)}})),S=[];for(const{chainId:b,delegateContract:C,nonce:v,cacheKey:w,cached:A}of k){if(A){S.push(A);continue}if(g?.aborted)throw new p.SpiceflowError("ABORT","Gasless transaction aborted");const E=await i.current.signAuthorization({contractAddress:C,chainId:b,nonce:v}),M={r:E.r,s:E.s,yParity:E.yParity,address:E.address??C,chainId:Number(E.chainId??b),nonce:Number(E.nonce??v)};d.current.set(w,M),S.push(M)}return S},[]),l=c.useCallback(async(m,x,g)=>{if(g?.aborted)throw new p.SpiceflowError("ABORT","Gasless transaction aborted");const y=await i.current.signMessage({raw:li(m,x)}),k=typeof y=="string"?y:y.signature;if(!k)throw new p.SpiceflowError("SIGNATURE_FAILED","Failed to sign intent authorization. The wallet returned an empty signature.");return k},[]),h=c.useCallback(async(m,x,g,y,k,S)=>{const b=(C,v,w)=>{y?.({step:C,message:v,...w})};if(Rs)throw new p.SpiceflowError("CONCURRENT_EXECUTION","A gasless transaction is already in progress. Please wait.");Rs=!0;try{if(!e)throw new p.SpiceflowError("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const C=S?.userOverride||e,v=S?.depositToEscrow?.gasFundingSource==="action-output"?S.depositToEscrow:null;let w=S?.depositToEscrow&&!v?Fo({chainBatches:m,token:S.depositToEscrow.token,amount:S.depositToEscrow.amount}):Xn(m),A=[],E=S?.useCustomTransfers;b("signing-delegation","Sign delegation in your wallet...");const M=await u(w,C,k);if(k?.aborted)throw new p.SpiceflowError("ABORT","Gasless transaction aborted");const B=BigInt(Math.floor(Date.now()/1e3)+3600);if(v){const O=await To({chainBatches:m,user:C,token:v.token,grossAmount:v.amount,chainAuthorizations:M});w=O.chainBatches,A=[O.outputCredit],E=!0}if(!S?.skipPreSubmitFeeEstimate){let O=!1;for(let q=0;q<5;q++){const K=S?.feeExecutionMode==="user-transfer"?Ts(w,C):w,H=Ms({user:C,chainBatches:K,tokenAddress:x,tokenTransferAmount:g,exp:Number(B),signature:"0x00",chainAuthorizations:M,useCustomTransfers:E}),G=await p.relayerService.estimateActionFees(H);r(G);const ce=S?.adjustBatchesForEstimate?.({feeEstimate:G,chainBatches:w});if(!ce||ni(w,ce)){O=!0;break}w=ce}if(!O)throw new p.SpiceflowError("INVALID_PARAMS","Withdraw fee estimate did not converge. Please retry.")}S?.skipUserFundingPreflight||await ri(w,C,{actionOutputCredits:A}),b("signing-intent","Sign the intent in your wallet...");const I=await l(w,B,k);if(k?.aborted)throw new p.SpiceflowError("ABORT","Gasless transaction aborted");b("submitting","Submitting to relayer...");const T=Ms({user:C,chainBatches:w,tokenAddress:x,tokenTransferAmount:g,exp:Number(B),signature:I,chainAuthorizations:M,useCustomTransfers:E}),D=await p.relayerService.createAction(T),[R,U]=D.intentIds[0].split("/"),L=parseInt(U||"0",10),W=`${R}/${L}`;b("executing","Executing on chain..."),b("executing","Executing on chain...",{actionId:R,intentId:W,intentIndex:L,totalSteps:w.length});const Q=w.length,N=await Eo({actionId:R,intentIndex:L,intentId:W,totalSteps:Q,signal:k,isSpicenetStep:O=>w[O]?.domain==="spicenet",maxExecuteAttemptsForStep:O=>w[O]?.domain==="spicenet"?6:3,maxPolls:180,onStatusMessage:(O,q)=>{b("executing",O,{txHash:q,actionId:R,intentId:W,intentIndex:L,totalSteps:Q})}});return b("success","Transaction successful!",{txHash:N,actionId:R,intentId:W,intentIndex:L,totalSteps:Q}),N||R}catch(C){throw console.error("[GaslessExecution] Error:",C),b("error",C.message||"Transaction failed",{error:C.message}),C}finally{Rs=!1}},[e,s,u,l]),f=c.useCallback(async(m,x,g,y)=>{if(!e)throw new p.SpiceflowError("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const k=y?.userOverride||e,S=y?.depositToEscrow?.gasFundingSource==="action-output"?y.depositToEscrow:null;let b=y?.depositToEscrow&&!S?Fo({chainBatches:m,token:y.depositToEscrow.token,amount:y.depositToEscrow.amount}):Xn(m);const C=y?.feeExecutionMode==="user-transfer"?Ts(b,k):b,v=y?.signAuthorizationsForEstimate?await u(C,k):void 0;let w=y?.useCustomTransfers;S&&(b=(await To({chainBatches:m,user:k,token:S.token,grossAmount:S.amount,chainAuthorizations:v})).chainBatches,w=!0);const A=y?.feeExecutionMode==="user-transfer"?Ts(b,k):b,E=Ms({user:k,chainBatches:A,tokenAddress:x,tokenTransferAmount:g,exp:Math.floor(Date.now()/1e3)+3600,signature:"0x00",chainAuthorizations:v,useCustomTransfers:w}),M=await p.relayerService.estimateActionFees(E);return r(M),M},[e,u]);return{executeGasless:h,estimateGasless:f,lastFeeEstimate:a,hasEmbeddedWallet:t&&s}}const ci={usdc:1,"usdc.e":1,usdt:1,dai:1,ctusd:1,wbtc:1e5,wcbtc:1e5,cbtc:1e5};function Ds(e,t){return j.formatUnits(e,t).replace(/(\.\d*?[1-9])0+$|\.0+$/,"$1")}function Do(e,t,s){return t===s?e:t<s?e*10n**BigInt(s-t):e/10n**BigInt(t-s)}function No(e,t){const s=t?ci[t.trim().toLowerCase()]??0:0,o=e*s;return o<=0?"$0":o>=1?`$${o.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}`:`$${o.toFixed(4).replace(/0+$/,"").replace(/\.$/,"")}`}function di(e,t){return t?JSON.stringify({tokenAddress:t.toLowerCase(),batches:e.map(s=>({chainId:s.chainId,calls:s.calls.map(o=>({to:o.to.toLowerCase(),value:o.value.toString(),data:o.data})),tokenTransfers:(s.tokenTransfers??[]).map(o=>({from:o.from,to:o.to.toLowerCase(),token:o.token.toLowerCase(),amount:o.amount.toString()}))}))}):null}function ui(e){const t=e.find(s=>F.isSpicenetChainId(s.chainId))?.calls?.[0]?.data;if(!t)return null;try{const s=j.decodeFunctionData({abi:F.spicenetAbi,data:t});return s.functionName!=="createWithdrawalRequest"?null:s.args[0].transfers.map(o=>({token:o.token,recipient:o.to,amount:o.amount}))}catch{return null}}function pi(e,t){return!e||e.length!==t.length?!1:e.every((s,o)=>{const a=t[o];return s.token.toLowerCase()===a.token.toLowerCase()&&s.recipient.toLowerCase()===a.recipient.toLowerCase()&&s.amount===a.amount})}function fi(e,t){const s=e.intents.flatMap(r=>r.batches).filter(r=>{const i=sn(r);return BigInt(r.quotedAmount)>0n||BigInt(r.totalDebit)>0n||i.totalFee>0n}),o=s.filter(r=>r.chainId===t),a=o.length>0?o:s;return a.length===1?a[0]:null}function hi(e){const t=new Map;for(const s of e){if(s.amount<=0n)continue;const o=s.token.toLowerCase(),a=s.recipient.toLowerCase(),r=`${o}:${a}`,i=t.get(r);i?i.amount+=s.amount:t.set(r,{...s})}return[...t.values()]}function mi(e,t){if(!e.token||!e.recipient||e.chainId===null)return null;const s=fi(t,e.chainId);if(!s)return null;const{gasFee:o,bridgeFee:a,spicenetFee:r}=sn(s),i=o+a,d=[{token:e.token.address,recipient:e.recipient,amount:e.receiveAmountRaw}];return i>0n&&d.push({token:e.token.address,recipient:F.SPICE_GAS_FEE_RECIPIENT,amount:i}),r>0n&&d.push({token:e.token.address,recipient:F.SPICE_PLATFORM_FEE_RECIPIENT,amount:r}),hi(d)}async function Wo(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(u=>F.isSpicenetChainId(u.chainId)))throw new Error("Spice withdrawals must include a Spicenet funding batch before the destination chain batch.");const s=e.token?.address||"",o={useCustomTransfers:!0},a=await e.gasless.estimateGasless(t,s,0n,o);let r=a;const i=mi(e,a);e.buildSpicenetBatch&&i!==null&&!pi(ui(t),i)&&(t=e.buildWithdrawBatches(i));const d=r.intents[0]?.batches[0]??null;d&&e.ui.setLockedGasFee(sn(d).totalFee),await e.gasless.executeGasless(t,s,0n,u=>{u.actionId&&u.intentId&&typeof u.intentIndex=="number"&&typeof u.totalSteps=="number"&&(e.executionContextRef.current={actionId:u.actionId,intentId:u.intentId,intentIndex:u.intentIndex,totalSteps:u.totalSteps}),e.ui.setExecutionProgress(u)},void 0,{...o,skipPreSubmitFeeEstimate:!0,submittedFeeEstimate:r})}window.dispatchEvent(new CustomEvent("withdraw-completed")),e.onWithdrawSuccess?.({token:e.token?.symbol||"",amount:e.amount,chainId:e.chainId})}catch(t){const s=t instanceof Error?t.message:"Withdraw failed";e.ui.setExecutionError(s),e.onWithdrawError?.(s)}finally{e.ui.setIsExecuting(!1)}}}async function gi(e){const t=e.executionContextRef.current;if(!t){e.ui.setExecutionProgress(null),await Wo(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 s=t.totalSteps;for(let o=0;o<t.totalSteps;o++)if((await p.relayerService.checkStepStatus(t.intentId,o)).data.status!=="success"){s=o;break}if(s>=t.totalSteps)e.ui.setExecutionProgress(o=>({...o||{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 o=s;o<t.totalSteps;o++){let a="pending",r;try{const i=await p.relayerService.executeStep(t.actionId,t.intentIndex,o,{action:"execute"});i.transactionHash&&(r=i.transactionHash)}catch{}for(let i=0;i<120;i++){if(await new Promise(u=>setTimeout(u,Math.min(1e3+i*1e3,5e3))),!e.isMountedRef.current)return;const d=await p.relayerService.checkStepStatus(t.intentId,o);if(!e.isMountedRef.current)return;if(a=d.data.status,d.data.transactionHash&&(r=d.data.transactionHash),a==="success"){e.ui.setExecutionProgress({step:o===t.totalSteps-1?"success":"executing",message:o===t.totalSteps-1?"Transaction successful!":"Executing remaining steps...",txHash:r,actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps});break}if(a==="reverted"||a==="error")throw new Error("Withdraw failed");e.ui.setExecutionProgress({step:"executing",message:"Executing remaining steps...",txHash:r,actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps})}if(!e.isMountedRef.current)return;if(a!=="success")throw new Error("Withdraw is still processing")}window.dispatchEvent(new CustomEvent("withdraw-completed")),e.onWithdrawSuccess?.({token:e.token?.symbol||"",amount:e.amount,chainId:e.chainId})}catch(s){const o=s instanceof Error?s.message:"Withdraw failed";e.ui.setExecutionError(o),e.onWithdrawError?.(o)}finally{e.ui.setIsExecuting(!1)}}async function xi(e){const t=(await e.estimateGasless(e.batches,e.tokenAddress,0n,{useCustomTransfers:!0})).intents[0]?.batches[0];if(!t)throw new Error("No gas fee estimate was returned for this withdraw.");return sn(t).totalFee}const Uo='"IBM Plex Mono", monospace',Po='"Helvetica Neue", sans-serif',yi=({show:e,position:t,popoverRef:s,spiceAssets:o,dark:a,dk:r})=>{if(!e||!t)return null;const i=a?r.textSecondary:"#71757A",d=a?r.textPrimary:"#0E0D0B",u=o||[];return n.jsxs("div",{ref:s,"data-balance-popover":!0,style:{position:"fixed",top:`${t.top}px`,left:`${t.left}px`,width:"220px",background:a?r.cardBg:"#FFFFFF",border:`1px solid ${a?r.cardBorder:"#D6D6D6"}`,borderRadius:"10px",boxShadow:a?"0 12px 32px rgba(0,0,0,0.32)":"0 12px 28px rgba(15, 23, 42, 0.14)",padding:"10px",zIndex:40},children:[n.jsx("div",{style:{fontFamily:Uo,fontSize:"11px",letterSpacing:"0.05em",color:i,marginBottom:"8px"},children:"ALL BALANCES"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:u.length>0?u.map(l=>{const h=l.displaySymbol||l.receiptTokenName||l.symbol;return n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"10px",padding:"6px 0"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0},children:[l.logoURI?n.jsx("img",{src:l.logoURI,alt:h,style:{width:"18px",height:"18px",borderRadius:"50%",flexShrink:0}}):n.jsx("div",{style:{width:"18px",height:"18px",borderRadius:"50%",border:`1px solid ${a?r.cardBorder:"#C8C8C8"}`,flexShrink:0}}),n.jsx("span",{style:{fontFamily:Po,fontSize:"13px",color:d,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:h})]}),n.jsx("span",{style:{fontFamily:Uo,fontSize:"12px",color:d,flexShrink:0},children:an(l.balanceFormatted)})]},l.receiptTokenId||l.address)}):n.jsx("span",{style:{fontFamily:Po,fontSize:"13px",color:i},children:"No balances"})})]})},Ci='"Helvetica Neue", sans-serif',ln='"IBM Plex Mono", monospace',bi=({show:e,onToggle:t,showCustomAddress:s,setShowCustomAddress:o,customRecipient:a,setCustomRecipient:r,externalAddress:i,recipientAddress:d,destChainName:u,destChainLogo:l,compatibleDestinationChains:h,txDetailsChainSwitchRef:f,onOpenNetworkPopover:m,sourceChainLabel:x,sourceDetailsLogo:g,sourceTokenLabel:y,amount:k,totalSourceDebitDisplay:S,receiveAmountDisplay:b,destTokenSymbol:C,shouldQuoteWithdrawGas:v,estimatingFee:w,feeError:A,displayedGasFee:E,selectedDestToken:M,theme:B,styles:I,dark:T,dk:D})=>{const R=T?D.textSecondary:"#71757A",U=T?D.textPrimary:"#0E0D0B",L=h.length>1,W=s&&a?j.isAddress(a)?`${a.slice(0,6)}...${a.slice(-4)}`:a:d?`${d.slice(0,6)}...${d.slice(-4)}`:"\u2014";return n.jsxs(n.Fragment,{children:[n.jsxs("div",{onClick:t,style:{display:"flex",alignItems:"center",gap:"6px",marginBottom:e?"10px":"0",cursor:"pointer",userSelect:"none"},children:[n.jsx("span",{style:{fontSize:"13px",color:R,fontFamily:Ci,fontWeight:600},children:"Transaction Details"}),n.jsx(os.ChevronDown,{size:12,color:R,style:{transform:e?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s"}})]}),e&&n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"7px"},children:[n.jsxs("div",{children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[n.jsx("span",{style:{fontSize:"12px",color:R,fontFamily:ln,fontWeight:500,letterSpacing:"0.03em"},children:"TO"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[n.jsx("span",{style:{fontSize:"13px",color:U,fontFamily:ln,fontWeight:500},children:W}),n.jsx("button",{onClick:()=>{o(Q=>!Q),!s&&i&&r(i)},style:{background:"none",border:"none",cursor:"pointer",padding:"0",fontSize:"9.5px",fontFamily:ln,color:R,textDecoration:"underline",fontWeight:600},children:s?"Reset":"Switch"})]})]}),s&&n.jsxs("div",{style:{marginTop:"6px"},children:[n.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:ln,fontWeight:700,letterSpacing:0,textTransform:"uppercase"},children:"CAUTION: ENTERING AN INCORRECT ADDRESS WILL RESULT IN LOSS OF FUNDS"}),n.jsx("input",{type:"text",autoComplete:"off",spellCheck:!1,"aria-label":"Recipient address","aria-invalid":a&&!j.isAddress(a)?!0:void 0,"data-spiceflow-focus":!0,value:a,onChange:Q=>r(Q.target.value),placeholder:"0x...",style:{width:"100%",padding:"8px 10px",borderRadius:"6px",border:`1px solid ${a&&!j.isAddress(a)?T?D.errorBorder:"#fca5a5":T?D.inputBorder:"#d1d5db"}`,backgroundColor:T?D.inputBg:"#f9fafb",color:T?D.inputText:"#111827",fontSize:"12px",fontFamily:ln,outline:"none",boxSizing:"border-box"}}),a&&!j.isAddress(a)&&n.jsx("span",{style:{fontSize:"11px",color:D.errorText,marginTop:"3px",display:"block"},children:"Invalid address"})]})]}),n.jsx(Sn,{palette:D,labelColor:R,valueColor:U,label:"RECEIVING CHAIN",value:n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"7px"},children:[l&&n.jsx("img",{src:l,alt:u,style:{width:"14px",height:"14px",borderRadius:"50%"}}),n.jsx("span",{style:{fontSize:"13px",color:U,fontWeight:500,fontFamily:ln,textTransform:"uppercase"},children:u}),n.jsx("button",{ref:f,onClick:Q=>{Q.stopPropagation(),m(f.current)},style:{background:"none",border:"none",cursor:L?"pointer":"not-allowed",padding:"0",fontSize:"9.5px",fontFamily:ln,color:R,textDecoration:"underline",fontWeight:600,opacity:L?1:.45},children:"Switch"})]})}),n.jsx(Sn,{palette:D,labelColor:R,valueColor:U,label:"REQUESTED WITHDRAWAL",value:n.jsxs(Ns,{logo:g||null,alt:x,primaryText:U,children:[k||"0"," ",y]})}),v&&n.jsx(Sn,{palette:D,labelColor:R,valueColor:U,label:"TOTAL SOURCE DEBIT",value:n.jsxs(Ns,{logo:g||null,alt:x,primaryText:U,children:[S," ",y]})}),n.jsx(Sn,{palette:D,labelColor:R,valueColor:U,label:"YOU RECEIVE",value:n.jsxs(Ns,{logo:l,alt:u,primaryText:U,gap:"4px",children:[b," ",C]})}),v&&n.jsxs(n.Fragment,{children:[n.jsx(Sn,{palette:D,labelColor:R,label:"EST. GAS FEE",valueColor:A?"#f87171":U,value:w?"Estimating...":A?"Unavailable":E!==null&&M?`${Ds(E,M.decimals)} ${M.symbol}`:"Estimating..."}),A&&n.jsx(vn,{variant:"error",size:"compact",palette:D,fontFamily:I?.fontFamily||B.typography.fontFamily,children:A})]})]})]})},Ns=({logo:e,alt:t,primaryText:s,gap:o="6px",children:a})=>n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:o},children:[e&&n.jsx("img",{src:e,alt:t,style:{width:"13px",height:"13px",borderRadius:"50%"}}),n.jsx("span",{style:{fontSize:"13px",color:s,fontWeight:500,fontFamily:ln},children:a})]});function zo(e){const t=new Set(F.getEquivalentAddresses(e).map(s=>s.toLowerCase()));return t.add(e.toLowerCase()),t}const wi=["USDC","USDT","WETH","WBTC"];function Ws(e,t){const s=p.getChainConfig(t);if(!s)return;if(s.nativeCurrency.symbol.toUpperCase()===e.toUpperCase())return{address:F.ZERO_ADDRESS,symbol:s.nativeCurrency.symbol,decimals:s.nativeCurrency.decimals,chainId:t};const o=s.supportedTokens?.find(a=>a.symbol.toUpperCase()===e.toUpperCase());if(o)return{address:o.address.toLowerCase(),symbol:o.symbol,decimals:o.decimals,chainId:t}}function on(e,t,s){const o=p.getChainConfig(t);if(!o)return;if(s!==void 0){const i=vo(e,s,t);if(i)return{address:i.address.toLowerCase(),symbol:i.symbol,decimals:i.decimals,chainId:t}}const a=zo(e);if([...a].some(i=>F.isNativeToken(i)))return{address:F.ZERO_ADDRESS,symbol:o.nativeCurrency.symbol,decimals:o.nativeCurrency.decimals,chainId:t};const r=o.supportedTokens?.find(i=>a.has(i.address.toLowerCase()));if(r)return{address:r.address.toLowerCase(),symbol:r.symbol,decimals:r.decimals,chainId:t}}function Lo(e){const{sourceAsset:t,outputAsset:s,sourceChainId:o,destinationChainId:a,intermediaryCandidates:r=wi}=e;if(Yn(t,s))return{strategy:"direct",sourceAsset:t,outputAsset:s,sourceChainId:o,destinationChainId:a,summary:`${t.symbol} fronted directly`};if(on(t.address,a,o))return{strategy:"direct",sourceAsset:t,outputAsset:s,sourceChainId:o,destinationChainId:a,summary:`${t.symbol} fronted on destination, swapped to ${s.symbol}`};if(on(s.address,o,a))return{strategy:"source-swap",sourceAsset:t,outputAsset:s,sourceChainId:o,destinationChainId:a,summary:`${t.symbol} \u2192 ${s.symbol} on source chain, then fronted`};for(const i of r){const d=Ws(i,o);if(!d||Yn(t,d)||Yn(s,d))continue;const u=Ws(i,a);if(u&&Yn(d,u))return{strategy:"intermediary",sourceAsset:t,outputAsset:s,intermediaryAsset:u,sourceChainId:o,destinationChainId:a,summary:`${t.symbol} \u2192 ${i} on source, fronted, then ${i} \u2192 ${s.symbol} on destination`}}throw new p.SpiceflowError("ROUTE_STRATEGY_ERROR",`No viable cross-chain route found from ${t.symbol} (chain ${o}) to ${s.symbol} (chain ${a}). No intermediary asset is available on both chains.`,{sourceAsset:t.symbol,outputAsset:s.symbol,sourceChainId:o,destinationChainId:a,candidatesChecked:r})}async function Oo(e){const{route:t,sourceAmount:s,userAddress:o,registry:a,actionCalls:r,slippage:i}=e;async function d(u,l,h,f){const m=a.getVenueForChain(u);if(!m)throw new p.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${u}. Cannot resolve swap ${l} \u2192 ${h}.`,{chainId:u,tokenIn:l,tokenOut:h,amountIn:f.toString()});const x=await m.resolve({type:"swap",tokenIn:l,tokenOut:h,amountIn:f,maxSlippage:i},u,o);if(!x)throw new p.SpiceflowError("NO_LIQUIDITY",`${m.name} returned no quote for ${l} \u2192 ${h} on chain ${u}. No liquidity available for this pair.`,{venue:m.name,chainId:u,tokenIn:l,tokenOut:h,amountIn:f.toString()});return x}switch(t.strategy){case"direct":{const u=on(t.sourceAsset.address,t.destinationChainId,t.sourceChainId)||t.sourceAsset;if(zo(u.address).has(t.outputAsset.address.toLowerCase()))return{chainBatches:[{chainId:t.destinationChainId,calls:r}],solverFrontToken:u,solverFrontAmount:s,resolvedSwaps:{}};const l=await d(t.destinationChainId,u.address,t.outputAsset.address,s);return{chainBatches:[{chainId:t.destinationChainId,calls:[...l.calls,...r]}],solverFrontToken:u,solverFrontAmount:s,resolvedSwaps:{destinationSwap:l}}}case"source-swap":{const u=on(t.outputAsset.address,t.sourceChainId,t.destinationChainId);if(!u)throw new p.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 l=on(t.outputAsset.address,t.destinationChainId,t.destinationChainId);if(!l)throw new p.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 h=await d(t.sourceChainId,t.sourceAsset.address,u.address,s);return{chainBatches:[{chainId:t.sourceChainId,calls:h.calls},{chainId:t.destinationChainId,calls:r}],solverFrontToken:l,solverFrontAmount:h.amountOutMinimum,resolvedSwaps:{sourceSwap:h}}}case"intermediary":{if(!t.intermediaryAsset)throw new p.SpiceflowError("ROUTE_STRATEGY_ERROR","Intermediary strategy requires an intermediary asset but none was provided in the route plan.",{strategy:t.strategy});const u=on(t.intermediaryAsset.address,t.sourceChainId,t.destinationChainId);if(!u)throw new p.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 l=await d(t.sourceChainId,t.sourceAsset.address,u.address,s),h=await d(t.destinationChainId,t.intermediaryAsset.address,t.outputAsset.address,l.amountOutMinimum);return{chainBatches:[{chainId:t.sourceChainId,calls:l.calls},{chainId:t.destinationChainId,calls:[...h.calls,...r]}],solverFrontToken:t.intermediaryAsset,solverFrontAmount:l.amountOutMinimum,resolvedSwaps:{sourceSwap:l,destinationSwap:h}}}default:throw new p.SpiceflowError("ROUTE_STRATEGY_ERROR",`Unknown route strategy: ${t.strategy}`,{strategy:t.strategy})}}const ki=({isOpen:e,onClose:t,closeOnBackdropClick:s=!1,styles:o,onWithdrawExecute:a,withdrawActionLabel:r,onWithdrawSuccess:i,onWithdrawError:d,autoCloseDelay:u,availableTokens:l,buildSpicenetBatch:h})=>{const f=c.useContext(p.SpiceFlowProviderContext);if(!f)return n.jsx("div",{children:"Error: SpiceWithdraw must be used within SpiceFlowProvider"});const m=f.mode||"7702",x=m==="presign"||m==="ondemand",g=f.supportedChainIds,y=f.allowedTokens,k=f.isWhitelistGateActive,S=!0,{theme:b,dark:C,dk:v}=p.useSpiceBrand(o),w=f.network,A=()=>x?"select":"provider-login",[E,M]=c.useState(A()),[B,I]=c.useState(!1),[T,D]=c.useState(null),[R,U]=c.useState(null),[L,W]=c.useState(""),[Q,N]=c.useState(!1),[O,q]=c.useState(!1),[K,H]=c.useState(!1),[G,ce]=c.useState(!1),[z,ee]=c.useState(""),[ge,ve]=c.useState(!0),fe=c.useRef(null),xe=c.useRef(null),he=c.useRef(null),V=c.useRef(null),[re,X]=c.useState(null),[le,ye]=c.useState(null),[Ie,J]=c.useState(null),Y=p.useWallet(),{isReady:ae,isAuthenticated:be,address:Ne}=Y,rt=p.useEmbeddedWalletAddress(),{address:qe,chainId:Ke}=It.useAccount(),[oe,ie]=c.useState(!1),[Ze,$]=c.useState(null),[Be,dt]=c.useState(null),kt=c.useRef(null),nt=c.useRef(!0);c.useEffect(()=>(nt.current=!0,()=>{nt.current=!1}),[]);const{executeGasless:zt,estimateGasless:Rt}=_n(),[mt,Ae]=c.useState(null),[Dt,Yt]=c.useState(null),[Gt,xt]=c.useState(!1),[Lt,Ye]=c.useState(null),{assets:vt,loading:Pe}=Wn({address:rt,enabled:e&&!!rt,refetchInterval:3e4}),Xe=c.useMemo(()=>{if(k)return[];if(!y||y.length===0)return vt;const te=new Set(y.map(se=>se.toLowerCase()));return(vt||[]).filter(se=>[se.symbol,se.displaySymbol,se.receiptTokenName].some(Se=>typeof Se=="string"&&te.has(Se.toLowerCase())))},[vt,y,k]),Je=c.useMemo(()=>[...new Set([...g??[],...Object.keys(l??{}).map(Number),...(Xe||[]).map(te=>te.chainId),...(Xe||[]).flatMap(te=>Object.keys(te.chainTokens??{}).map(se=>{const[,Se]=se.split(":"),ze=Number(Se);return Number.isFinite(ze)?ze:null}).filter(se=>se!==null))])].filter(te=>p.getChainConfig(te)?.network===w),[g,l,Xe,w]),ut=c.useMemo(()=>{if(l)return l;const te={};for(const se of Xe||[]){const Se=Object.entries(se.chainTokens??{});if(Se.length>0){for(const[ze,Qe]of Se){const[Le,Oe,Z]=ze.split(":");if(Le!=="evm"||!Oe||!Z)continue;const de=Number(Oe);if(!Number.isFinite(de))continue;const He=Z.startsWith("0x")?Z.toLowerCase():`0x${Z.toLowerCase()}`,ke=p.getChainConfig(de)?.supportedTokens?.find(Ee=>p.addressesEqual(Ee.address,He));ke&&js(se,He,de)&&(te[de]||(te[de]=[]),te[de].find(Ee=>p.addressesEqual(Ee.address,He))||te[de].push({address:He,symbol:ke?.symbol||Qe?.name||se.symbol,name:ke?.name||Qe?.name||se.displayName||se.name||se.symbol,decimals:ke?.decimals??Qe?.decimals??se.decimals,logoURI:ke?.logo||se.logoURI}))}continue}te[se.chainId]||(te[se.chainId]=[]),te[se.chainId].find(ze=>p.addressesEqual(ze.address,se.address))||te[se.chainId].push({address:se.address,symbol:se.symbol,name:se.displayName||se.name||se.symbol,decimals:se.decimals,logoURI:se.logoURI})}return te},[l,Xe]),At=c.useCallback((te,se)=>{if(!te||!se)return null;const Se=Zn(te,se),ze=Object.entries(te.chainTokens??{}).flatMap(([ke,Ee])=>{const Re=In(ke);return Re?.chainId===se?[{parsed:Re,detail:Ee}]:[]}),Qe=ut?.[se]||[],Le=ke=>Qe.find(Ee=>p.addressesEqual(Ee.address,ke))??null,Oe=ke=>{const Ee=p.getChainConfig(se)?.supportedTokens?.find(ft=>p.addressesEqual(ft.address,ke));if(!Ee||!js(te,ke,se))return null;const Re=ze.find(({parsed:ft})=>p.addressesEqual(ft.address,ke));return Re?{address:Re.parsed.address,symbol:Ee.symbol,name:Ee.name||Re.detail?.name||te.displayName||te.name||te.symbol,decimals:Ee.decimals,logoURI:Ee.logo||te.logoURI}:null};for(const ke of Se){const Ee=Le(ke);if(Ee)return Ee;const Re=Oe(ke);if(Re)return Re}const Z=$t(te,se);if(Z){const ke=Le(Z);if(ke)return ke;const Ee=Oe(Z);if(Ee)return Ee}const de=on(te.address,se,te.chainId);return de?Le(de.address)||(Qe.length>0?null:{address:de.address,symbol:de.symbol||te.symbol,name:te.displayName||te.name||te.symbol,decimals:de.decimals??te.decimals,logoURI:te.logoURI}):null},[ut]),me=c.useMemo(()=>{if(!T)return null;const te=T.receiptTokenId||`${T.chainId}:${T.address.toLowerCase()}`;return Xe.find(se=>(se.receiptTokenId||`${se.chainId}:${se.address.toLowerCase()}`)===te)||T},[T,Xe]),st=c.useMemo(()=>{if(!me)return[];const te=Object.keys(me.chainTokens??{}).map(se=>In(se)?.chainId??null).filter(se=>se!==null);return Array.from(new Set([...te,me.chainId,...Je].filter(Number.isFinite))).filter(se=>se!==1&&p.getChainConfig(se)?.network===w&&At(me,se)!==null)},[me,Je,At,w]),pt=c.useMemo(()=>{if(!me||typeof window>"u")return null;const te=`spiceflow:withdraw-chain:${me.receiptTokenId||me.address.toLowerCase()}`,se=window.localStorage.getItem(te),Se=se?Number(se):null;return Se!==null&&Number.isFinite(Se)&&st.includes(Se)?Se:null},[me,st]),Et=c.useMemo(()=>me?pt!==null?pt:Ke&&st.includes(Ke)?Ke:me.chainId&&st.includes(me.chainId)?me.chainId:st[0]??Je[0]??null:Je[0]??null,[me,pt,Ke,st,Je]),Ce=c.useMemo(()=>At(me,R),[At,me,R]);c.useEffect(()=>{!Xe?.length||me||D(Xe[0])},[S,Xe,me]),c.useEffect(()=>{!me||(R===null||!st.includes(R))&&U(Et)},[S,me,R,Et,st]),c.useEffect(()=>{if(!Q&&!O&&!K)return;const te=se=>{const Se=se.target;Q&&!fe.current?.contains(Se)&&!xe.current?.contains(Se)&&!Se?.closest?.("[data-network-popover]")&&N(!1),O&&!he.current?.contains(Se)&&!Se?.closest?.("[data-token-popover]")&&q(!1),K&&!V.current?.contains(Se)&&!Se?.closest?.("[data-balance-trigger]")&&H(!1)};return document.addEventListener("mousedown",te),()=>document.removeEventListener("mousedown",te)},[Q,O,K]);const jt=c.useCallback(te=>{if(!te||st.length<=1)return;const se=te.getBoundingClientRect(),Se=220,ze=16;X({top:se.bottom+8,left:Math.min(Math.max(ze,se.right-Se),window.innerWidth-Se-ze)}),N(Qe=>!Qe)},[st.length]);c.useEffect(()=>{if(!me||R===null||typeof window>"u")return;const te=`spiceflow:withdraw-chain:${me.receiptTokenId||me.address.toLowerCase()}`;window.localStorage.setItem(te,String(R))},[me,R]);const $e=G&&z&&j.isAddress(z)?z:qe||rt,lt=me?.balanceFormatted??0,Ft=c.useCallback(te=>{if(!te)return;const se=te.getBoundingClientRect();J({top:se.bottom+8,left:se.right-220}),H(!0)},[]),Xt=me?.displaySymbol||me?.receiptTokenName||me?.symbol||"spiceUSDC",Ot=me?.displayChainName||"Spicenet",ot=ps,Ht=ps,Te=me?.receiptTokenDecimals??me?.decimals,We=c.useMemo(()=>{if(!Ce||!Te)return 0n;try{return j.parseUnits(L||"0",Te)}catch{return 0n}},[L,Ce,Te]),St=c.useMemo(()=>!Ce||!Te?0n:Do(We,Te,Ce.decimals),[Ce,Te,We]),yt=c.useMemo(()=>{const te=Dt??mt;return!te||te<=0n||!Ce||!Te?0n:Do(te,Ce.decimals,Te)},[Dt,mt,Ce,Te]),Ue=c.useMemo(()=>We+yt,[We,yt]),_e=Dt??mt,at=c.useCallback(te=>{if(!R||!Ce)return[];if(We===0n||St===0n||!$e)return[];const se=Array.isArray(te)?te.filter(Le=>Le.amount>0n):[{token:Ce.address,recipient:$e,amount:te??St}],Se=se.reduce((Le,Oe)=>Le+Oe.amount,0n);if(Se<=0n)return[];const ze={chainId:R,calls:[],tokenTransfers:se.map(Le=>({from:"escrow",to:Le.recipient,token:Le.token,amount:Le.amount}))};if(!h)return[ze];const Qe=h({destinationChainId:R,deliveryToken:Ce.address,deliveryAmount:Se,deliveryRecipient:$e,deliveryTransfers:se});return Qe?[Qe,ze]:[ze]},[S,R,Ce,We,St,$e,h]),et=c.useMemo(()=>at(),[at]),Ge=c.useMemo(()=>di(et,Ce?.address),[et,Ce?.address]),Ct=c.useRef(null),tt=c.useRef(0);c.useEffect(()=>{let te=!1;if(!e||x||oe||!Ce||We===0n){Ct.current=null,Ae(null),Ye(null),xt(!1);return}if(et.length===0){Ct.current=null,Ae(null),xt(!0);return}if(!Ge){Ct.current=null,Ae(null),Ye(null),xt(!1);return}if(Ct.current===Ge)return;Ct.current=Ge;const se=++tt.current;return(async()=>{xt(!0),Ye(null);try{const Se=await xi({batches:et,tokenAddress:Ce.address,estimateGasless:Rt});if(te||se!==tt.current)return;Ae(Se)}catch(Se){if(te||se!==tt.current)return;Ct.current=null,Ae(null),Ye(Se instanceof Error?Se.message:"Failed to estimate gas fee")}finally{!te&&se===tt.current&&xt(!1)}})(),()=>{te=!0}},[e,x,oe,Ce,Rt,We,et,Ge]),c.useEffect(()=>{oe||Yt(null)},[oe,L,R,Ce?.address]);const Qt=c.useCallback(()=>{I(!0),M("select")},[S]),Me=c.useCallback(()=>{t()},[t]),Kt=c.useRef(null);Kt.current={batches:et,walletAddress:Ne,recipient:$e,token:Ce,chainId:R,amount:L,receiveAmountRaw:St,gasFee:mt,isNon7702:x,buildWithdrawBatches:at,gasless:{estimateGasless:Rt,executeGasless:zt},ui:{setIsExecuting:ie,setExecutionError:$,setExecutionProgress:dt,setLockedGasFee:Yt},executionContextRef:kt,isMountedRef:nt,onWithdrawExecute:a,onWithdrawSuccess:i,onWithdrawError:d,buildSpicenetBatch:h};const Bt=c.useCallback(()=>Wo(Kt.current),[]),ht=c.useCallback(()=>gi(Kt.current),[]);if(c.useEffect(()=>{if(!e){const te=setTimeout(()=>{M(A()),I(!1),D(null),U(null),W(""),N(!1),q(!1),ce(!1),ee(""),ie(!1),$(null),dt(null),kt.current=null},300);return()=>clearTimeout(te)}},[e,x]),c.useEffect(()=>{if(!x&&e&&E==="provider-login"&&ae&&be&&rt&&!B){const te=setTimeout(()=>{I(!0),M("select")},100);return()=>clearTimeout(te)}},[x,e,E,ae,be,rt,B,S]),!e)return null;if(E==="provider-login"&&!x)return n.jsx(Is,{onAuthSuccess:Qt,autoTrigger:!0});if(E==="select"&&S){const te=parseFloat(L)||0,se=Te?Ds(Ue,Te):L||"0",Se=parseFloat(se)||0,ze=Se>0&&Se>lt,Qe=(R?p.getChainConfig(R):null)?.displayName||"Network",Le=R?_t[R]||Tn:null,Oe=Ce?.symbol||"\u2014",Z=Xt,de=Ce?Ds(St,Ce.decimals):"0",He=No(te,Ce?.symbol||me?.symbol),ke=No(parseFloat(de)||0,Ce?.symbol||me?.symbol),Ee=!G||!z||j.isAddress(z),Re=!x&&te>0&&Ce!==null,ft=!Re||mt!==null&&!Gt&&!Lt,gt=te>0&&!ze&&T!==null&&R!==null&&Ce!==null&&$e&&Ee&&ft&&St>0n,it=!gt,P=T===null?"NO BALANCE":te===0?"ENTER AMOUNT":ze?"INSUFFICIENT BALANCE":Re&&!ft?Lt?"GAS UNAVAILABLE":"ESTIMATING GAS":Re&&St===0n?"AMOUNT TOO SMALL":"WITHDRAW",_=!!Be&&(Be.step==="success"||Be.step==="error"),ue=n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[n.jsx("img",{src:Ss,alt:"","aria-hidden":"true",style:{width:"13px",height:"13px",flexShrink:0,...C?{filter:"invert(0.6)"}:{}}}),n.jsx("p",{style:{fontSize:"13px",color:C?v.textSecondary:"#979AA0",margin:"0",lineHeight:"1.4",fontFamily:'"Helvetica Neue", sans-serif'},children:"Withdraw collateral from your account to 10+ EVM blockchains."})]}),ne='"Helvetica Neue", sans-serif',Fe='"IBM Plex Mono", monospace',je=o?.primaryColor||b.colors.primary,Ve=C?v.cardBg:"#E9E9E9",Nt=C?v.cardBorder:"#C6C6C6",Vt=C?v.textSecondary:"#7D7C7B",bt=C?v.textSecondary:"#71757A",ct=C?v.textPrimary:"#0E0D0B",qt=C?v.cardBorder:"#C5C5C4",rn=C?"rgba(255,255,255,0.08)":"#D4D3D3",dn=170,En=Z.length>8?"14px":Z.length>6?"16px":"18px",un=Oe.length>8?"14px":Oe.length>6?"16px":"18px";return n.jsx(en,{isOpen:!0,onClose:Me,title:"Withdraw",subtitle:ue,styles:o,theme:b,dark:C,maxWidth:"486px",footerLinkText:"Spicenet accounts \u2192",overlayDimmed:!1,closeOnBackdropClick:s,overlayContent:_?n.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:n.jsx("div",{style:{pointerEvents:"auto"},children:n.jsx(As,{type:"withdraw",isOpen:!0,isProcessing:oe,onRetryTx:()=>{ht()},onNewTx:()=>{dt(null),W(""),$(null),kt.current=null},onClose:()=>{dt(null),$(null),ie(!1),kt.current=null},onComplete:()=>{dt(null),$(null),ie(!1),kt.current=null},results:[{asset:{symbol:Ce?.symbol||"Token",address:Ce?.address||""},txHash:Be?.txHash||"",success:Be?.step==="success",error:Be?.error,amount:L}],chainName:R?p.getChainName(R):"Network",explorerUrl:R?p.getExplorerUrl(R,"").replace(/\/tx\/.*$/,""):void 0,theme:b})})}):null,children:n.jsxs("div",{style:{width:"402px",margin:"0 auto",padding:"0 0 4px 0",position:"relative"},children:[n.jsx(yi,{show:K,position:Ie,popoverRef:V,spiceAssets:Xe,dark:C,dk:v}),n.jsxs("div",{style:{marginTop:"16px",marginBottom:"16px",display:"flex",flexDirection:"column",gap:"16px"},children:[n.jsxs("div",{style:{backgroundColor:Ve,border:`1px solid ${Nt}`,borderRadius:"7px",padding:"14px 16px 12px 16px",minHeight:"138px",display:"flex",flexDirection:"column",gap:"6px",position:"relative"},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[n.jsx("span",{style:{fontFamily:ne,fontSize:"17px",fontWeight:500,color:Vt,lineHeight:"24px"},children:"Source"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",fontFamily:ne,fontSize:"13px",fontWeight:500,color:bt,lineHeight:"16px"},children:["Balance:"," ",Pe?"...":an(lt),n.jsx("button",{type:"button","data-balance-trigger":!0,onClick:we=>{we.stopPropagation(),Ft(we.currentTarget)},style:{width:"15px",height:"15px",borderRadius:"999px",border:"1px solid #EA4B4B",color:"#EA4B4B",display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:"9px",fontWeight:500,lineHeight:1,boxSizing:"border-box",background:"transparent",padding:0,cursor:"pointer"},children:n.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"1.5px"},children:[0,1,2].map(we=>n.jsx("span",{style:{width:"1.75px",height:"1.75px",borderRadius:"999px",backgroundColor:"#EA4B4B",display:"block"}},we))})})]})]}),n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[n.jsxs("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[n.jsx(hn,{element:"input",ariaLabel:"Withdraw amount",ariaInvalid:ze,dataSpiceflowFocus:!0,value:L,onChange:we=>{const pe=we.target.value;if(pe===""){W("");return}/^\d*\.?\d*$/.test(pe)&&W(bn(pe.startsWith(".")?`0${pe}`:pe,Te??T?.decimals))},placeholder:"0.0",fontFamily:ne,color:ze?"#ef4444":L?ct:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,style:{width:"100%"}}),n.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:bt,fontFamily:ne,marginTop:"10px"},children:He})]}),n.jsx("div",{style:{width:`${dn}px`,flexShrink:0},children:n.jsxs("div",{style:{backgroundColor:"transparent",border:`1px solid ${qt}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[n.jsxs("div",{ref:he,onClick:we=>{if(we.stopPropagation(),!O&&he.current){const pe=he.current.getBoundingClientRect(),De=220,Tt=16;ye({top:pe.bottom+8,left:Math.min(Math.max(Tt,pe.right-De),window.innerWidth-De-Tt)})}q(pe=>!pe)},style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px",cursor:"pointer"},children:[n.jsx("img",{src:ot,alt:Z,style:{width:"24px",height:"24px",borderRadius:"50%"}}),n.jsx("span",{style:{fontSize:En,fontWeight:500,color:ct,lineHeight:"1.3",fontFamily:ne,flex:1,minWidth:0,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",letterSpacing:0},children:Z}),n.jsx(tn,{size:15,color:ct,strokeWidth:2.25})]}),n.jsx(xo,{isOpen:O,position:le,title:"SELECT TOKEN",portalAttribute:"token",items:(Xe||[]).map(we=>({id:we.receiptTokenId||we.address,label:we.displaySymbol||we.receiptTokenName||we.symbol,icon:ps,detail:an(we.balanceFormatted)})),selectedId:me?.receiptTokenId||me?.address||null,onSelect:we=>{const pe=(Xe||[]).find(De=>(De.receiptTokenId||De.address)===we);pe&&(D(pe),W("")),q(!1)}}),n.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:rn,borderTop:`1px solid ${qt}`},children:n.jsx("span",{style:{fontSize:"11px",fontWeight:400,color:ct,fontFamily:ne,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:Ot})})]})})]}),n.jsxs("div",{style:{minHeight:"18px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[ze?n.jsx("span",{style:{fontSize:"12px",color:v.errorText,fontFamily:ne,fontWeight:500},children:"Insufficient Balance"}):n.jsx("span",{}),n.jsx("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0px",minHeight:"32px",marginRight:"-9px"},children:[0,25,50,75,100].map((we,pe)=>{const De=pe===4,Tt=we/100,Jt=parseFloat(L)||0,Zt=lt>0&&Math.abs(Jt/lt*100-we)<1;return n.jsx("button",{type:"button","aria-label":`Set amount to ${we}%`,"aria-pressed":Zt,onClick:()=>{const jn=lt*we/100,pn=T?.decimals??6,Fn=Math.floor(jn*10**pn)/10**pn;W(we===0?"":Fn>0?wn(Fn,pn):"")},title:`${we}%`,disabled:lt===0,"data-spiceflow-focus":!0,style:{width:"32px",height:"32px",padding:"9px",border:"none",backgroundColor:"transparent",cursor:lt===0?"not-allowed":"pointer",opacity:Zt?1:.5,transition:"opacity 0.15s ease",display:"flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box"},children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[n.jsx("circle",{cx:"7",cy:"7",r:"6.84375",fill:De?je:"none",stroke:De?je:C?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!De&&Tt>0&&n.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${Tt>.5?1:0} 1 ${7+6.84375*Math.sin(Tt*2*Math.PI)} ${7-6.84375*Math.cos(Tt*2*Math.PI)} Z`,fill:C?v.textSecondary:"#3C3E42"})]})},we)})})]})]}),n.jsxs("div",{style:{backgroundColor:Ve,border:`1px solid ${Nt}`,borderRadius:"7px",padding:"14px 16px 12px 16px",minHeight:"138px",display:"flex",flexDirection:"column",gap:"6px"},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[n.jsx("span",{style:{fontFamily:ne,fontSize:"17px",fontWeight:500,color:Vt,lineHeight:"24px"},children:"Destination"}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",fontFamily:ne,fontSize:"13px",fontWeight:500,color:bt,lineHeight:"16px"},children:["Balance:"," ",Pe?"...":an(lt),n.jsx("button",{type:"button","data-balance-trigger":!0,onClick:we=>{we.stopPropagation(),Ft(we.currentTarget)},style:{width:"15px",height:"15px",borderRadius:"999px",border:"1px solid #EA4B4B",color:"#EA4B4B",display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:"9px",fontWeight:500,lineHeight:1,boxSizing:"border-box",background:"transparent",padding:0,cursor:"pointer"},children:n.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"1.5px"},children:[0,1,2].map(we=>n.jsx("span",{style:{width:"1.75px",height:"1.75px",borderRadius:"999px",backgroundColor:"#EA4B4B",display:"block"}},we))})})]})]}),n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[n.jsxs("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[n.jsx(hn,{element:"div",value:de,title:de,fontFamily:ne,color:L?ct:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,overflow:"wrap"}),n.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:bt,fontFamily:ne,marginTop:"10px"},children:ke})]}),n.jsxs("div",{style:{width:`${dn}px`,flexShrink:0,display:"flex",flexDirection:"column",alignItems:"stretch",gap:"8px"},children:[n.jsxs("div",{style:{backgroundColor:"transparent",border:`1px solid ${qt}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px"},children:[n.jsx("img",{src:Ce?.logoURI||Mn,alt:Oe,style:{width:"24px",height:"24px",borderRadius:"50%"}}),n.jsx("span",{style:{fontSize:un,fontWeight:500,color:ct,lineHeight:"1.3",fontFamily:ne,flex:1,minWidth:0,letterSpacing:0},children:Oe})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:rn,borderTop:`1px solid ${qt}`},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[Le&&n.jsx("img",{src:Le,alt:Qe,style:{width:"13px",height:"13px",borderRadius:"50%",flexShrink:0}}),n.jsx("span",{style:{fontSize:"11px",fontWeight:400,color:ct,fontFamily:ne,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:Qe})]}),n.jsx("button",{ref:fe,onClick:we=>{we.stopPropagation(),jt(fe.current)},style:{background:"none",border:"none",cursor:st.length>1?"pointer":"not-allowed",padding:"0 0 0 8px",fontSize:"9.5px",fontFamily:Fe,color:bt,textDecoration:"underline",fontWeight:600,opacity:st.length>1?1:.45},children:"Switch"}),n.jsx(xo,{isOpen:Q,position:re,title:"SELECT NETWORK",portalAttribute:"network",items:st.map(we=>{const pe=p.getChainConfig(we);return{id:String(we),label:pe?.displayName||String(we),icon:_t[we]||Tn}}),selectedId:R!==null?String(R):null,onSelect:we=>{U(Number(we)),N(!1)}})]})]}),n.jsx("div",{style:{minHeight:"14px"}})]})]})]})]}),n.jsxs("div",{style:{marginBottom:b.spacing.sm},children:[n.jsx(bi,{show:ge,onToggle:()=>ve(we=>!we),showCustomAddress:G,setShowCustomAddress:ce,customRecipient:z,setCustomRecipient:ee,externalAddress:qe,recipientAddress:$e,destChainName:Qe,destChainLogo:Le,compatibleDestinationChains:st,txDetailsChainSwitchRef:xe,onOpenNetworkPopover:jt,sourceChainLabel:Ot,sourceDetailsLogo:Ht,sourceTokenLabel:Z,amount:L,totalSourceDebitDisplay:se,receiveAmountDisplay:de,destTokenSymbol:Oe,shouldQuoteWithdrawGas:Re,estimatingFee:Gt,feeError:Lt,displayedGasFee:_e,selectedDestToken:Ce,theme:b,styles:o,dark:C,dk:v}),Ze&&n.jsx(vn,{variant:"error",size:"compact",palette:v,fontFamily:o?.fontFamily||b.typography.fontFamily,style:{marginBottom:"12px"},children:Ze}),n.jsx(p.Button,{variant:"outline",fullWidth:!0,onClick:()=>{gt&&Bt()},disabled:it||oe,theme:b,dark:C,styles:o,style:{marginTop:"8px"},children:oe?"EXECUTING...":P})]})]})})}return null},Ho=ki;var vi="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAKlBMVEVMaXHpSkrmS0vrSkrmR0fpSkrrSkroSUnqSkrpSkrpSkrpSkrsS0vzTk68N2lZAAAADHRSTlMA/SoEHOX1RcdliKnuQ9TkAAAACXBIWXMAAAsTAAALEwEAmpwYAAAB4UlEQVR42u1XyRbDIAhUcQ/8/+9WUROzNIvtMbxefMo4yACpEOcG4geD30G0C07B8P0qWkzm3QgJEBAsIUqURJMe8NcToZTlR8YJgGev5wwVd2QEG+FZGIl+9iUyloGQvL5NIt2V6RfqoCPRHMZN/0ofy+NBKEsO41b4wVaHADWdvgGqGyR0o5/Tvw/pmr7v6C/XhRbVaTYqfU5bgPVGDUNmYDgXT6UP28xEvAyjpw/H2pD5wGE2ivZZPGv6fXF5JlhEdfr68AUB4vdsqHP6DWPWyDYbITsz/asecXDR+vXPtZbOdmG0o7324dJYVFypLRu6+ptws9aV53glhUIqMCDaqNxdKwjkoQDkzpkAjL1vWwCJA1YBUgpRjlkDULl9jxjFudjHbBkXWg3ZT4N3q9AkMOXUrMM0VZ3oVJk3QXSbvNi0CzNXUimZ2LeatBl7Ie57CiQ9k9EVYEripKVYwJMlq+qKN3eyVzaLu/pArtl0pgFok6XS1j6fjI8BUDZGvPkCvAAvwJdiuipnuZRzJL5q93li0M53pp6Bq4bicZnb2kuMh/8Num9ycOsP9NUalBJ/trG2rmH5/Boabji1FxsbbFhzmaezHAPANlxxcDwvwzWNZ3ps2P0X02MG4rX/2Ad4/i9F5OK4gwAAAABJRU5ErkJggg==";const Pn=e=>{const t=Math.round(e*1e5)/1e5;return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:5}).format(t)},Qo=e=>{const t=Math.round(e*1e5)/1e5;return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:5}).format(t)},Si=({balanceData:e,isLoading:t=!1,styles:s,className:o="",showHeader:a=!0,onAccountClick:r,onDepositClick:i,onWithdrawClick:d,vaultBalance:u,fetchVaultBalance:l,onWithdrawExecute:h,withdrawActionLabel:f,destinationChainId:m,destinationTokenAddress:x,customSections:g,showDefaultSections:y=!0})=>{const k=c.useContext(p.SpiceFlowProviderContext),S=(k?.mode||"7702")!=="7702",b=k?.appName||"Spicenet",{dark:C,primaryColor:v,dk:w,theme:A}=p.useSpiceBrand(s),[E,M]=c.useState(!0),[B,I]=c.useState(!1),[T,D]=c.useState(!1),[R,U]=c.useState(null),{isConnected:L}=It.useAccount(),{disconnect:W}=It.useDisconnect();c.useEffect(()=>{S&&l&&l().then(H=>{const G=Math.round(H*1e5)/1e5;U(G)}).catch(H=>{console.error("Error fetching vault balance:",H),U(null)})},[S,l]);const Q=()=>{M(!E)},N=c.useMemo(()=>{if(!e.freeCollateralItems)return null;const H=e.freeCollateralItems.filter(z=>z.name==="USDC");if(H.length===0)return null;const G=H.reduce((z,ee)=>z+ee.balance,0),ce=[];return H.forEach(z=>{z.networks&&z.networks.forEach(ee=>{(ee===1||ee===11155111||ee===8453||ee===84532)&&(ce.includes(ee)||ce.push(ee))})}),ce.length===0&&ce.push(1,8453),{name:"USDC",totalBalance:G,networks:ce,subtitle:H[0]?.subtitle||"USD COIN"}},[e.freeCollateralItems]),O=c.useMemo(()=>{if(S){if(R!==null)return R;if(u!=null)return u}return e.freeCollateralItems?e.freeCollateralItems.reduce((H,G)=>H+G.balance,0):e.freeCollateral},[S,R,u,e.freeCollateralItems,e.freeCollateral]),q=H=>E?H:"******",K=()=>{W(),I(!1),D(!1)};return n.jsxs("div",{className:o,style:{borderRadius:"16px",backgroundColor:C?w.shell:"#D5D5D5",width:"522px",padding:"8px",fontFamily:s?.fontFamily||'"Helvetica Neue", sans-serif',...s?.container},children:[n.jsxs("div",{style:{background:C?w.cardBg:" white",display:"flex",flexDirection:"column"},children:[n.jsxs("div",{style:{backgroundColor:C?w.inputBg:"#E9E9E9",borderRadius:"0 0 16px 16px",padding:"20px",display:"flex",flexFlow:"column"},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"4px"},children:[n.jsxs("p",{style:{fontSize:"14px",fontWeight:500,fontFamily:'"IBM Plex Mono", monospace',color:C?w.textPrimary:"#0E0D0B",margin:0},children:[b.toUpperCase()," BALANCE"]}),L&&n.jsx("button",{onClick:K,"aria-label":"Disconnect wallet",style:{width:"36px",height:"36px",borderRadius:"8px",border:C?`1px solid ${v}33`:"1px solid #E5E7EB",background:C?w.inputBg:"white",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",transition:Ut.interactive,padding:"8px"},onMouseEnter:H=>{H.currentTarget.style.backgroundColor=C?w.cardBg:"#F3F4F6"},onMouseLeave:H=>{H.currentTarget.style.backgroundColor=C?w.inputBg:"white"},children:n.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),n.jsx("polyline",{points:"16 17 21 12 16 7"}),n.jsx("line",{x1:"21",y1:"12",x2:"9",y2:"12"})]})})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.percentageChange!==void 0&&e.percentageChange!==null&&n.jsxs("div",{style:{fontSize:"13px",fontWeight:700,color:e.percentageChange>=0?C?w.successText:"#009C51":C?w.errorText:"#EF4444"},children:[e.percentageChange>=0?"+":"",e.percentageChange.toFixed(2),"%"]}),n.jsx("button",{onClick:Q,style:{background:"none",border:"none",cursor:"pointer",padding:"8px",display:"flex",alignItems:"center",justifyContent:"center",transition:"opacity 0.2s ease"},onMouseEnter:H=>{H.currentTarget.style.opacity="0.7"},onMouseLeave:H=>{H.currentTarget.style.opacity="1"},children:E?n.jsxs("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",children:[n.jsx("path",{d:"M12 5C7 5 2.73 8.11 1 12.5C2.73 16.89 7 20 12 20C17 20 21.27 16.89 23 12.5C21.27 8.11 17 5 12 5Z",stroke:C?w.textSecondary:"#1A1A1A",strokeWidth:"2",fill:"none"}),n.jsx("circle",{cx:"12",cy:"12.5",r:"3",stroke:C?w.textSecondary:"#1A1A1A",strokeWidth:"2",fill:"none"})]}):n.jsxs("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",children:[n.jsx("path",{d:"M12 5C7 5 2.73 8.11 1 12.5C2.73 16.89 7 20 12 20C17 20 21.27 16.89 23 12.5C21.27 8.11 17 5 12 5Z",stroke:C?w.textSecondary:"#1A1A1A",strokeWidth:"2",fill:"none"}),n.jsx("path",{d:"M3 3L21 21",stroke:C?w.textSecondary:"#1A1A1A",strokeWidth:"2",strokeLinecap:"round"})]})})]}),n.jsx("p",{style:{fontSize:"40px",fontWeight:700,color:C?w.textPrimary:"black"},children:q(Pn(S&&R!==null?R:S&&u!==void 0&&u!==null?u:e.totalBalance))}),n.jsxs("div",{style:{display:"flex",gap:"12px",marginTop:"16px"},children:[n.jsx(p.Button,{variant:"outline",fullWidth:!0,onClick:()=>{i?i():I(!0)},theme:A,dark:C,styles:s,children:"DEPOSIT"}),n.jsx(p.Button,{variant:"outline",fullWidth:!0,onClick:()=>{d?d():D(!0)},theme:A,dark:C,styles:s,children:"WITHDRAW"})]})]}),n.jsxs("div",{style:{background:C?w.cardBg:"white",padding:"12px 20px",borderRadius:"12px"},children:[y&&n.jsx(go,{title:"FREE COLLATERAL",icon:vi,amount:q(Qo(O)),defaultExpanded:!1,children:S&&(R!==null||u!=null)?n.jsx(qn,{name:"USDC",balance:q(Pn(R!==null?R:u)),subtitle:"USD COIN",icon:Mn,onClick:r?()=>r("usdc-vault"):void 0}):N?n.jsx(qn,{name:N.name,balance:q(Pn(N.totalBalance)),subtitle:N.subtitle,networks:N.networks,icon:Mn,onClick:r?()=>r(N.name):void 0}):e.freeCollateralItems&&e.freeCollateralItems.length>0?e.freeCollateralItems.map((H,G)=>n.jsxs(c.Fragment,{children:[n.jsx(qn,{name:H.name,balance:q(Pn(H.balance)),subtitle:H.subtitle,networks:H.networks,icon:H.name==="USDC"?Mn:void 0,onClick:r?()=>r(H.id):void 0}),G<e.freeCollateralItems.length-1&&n.jsx("div",{style:{height:"1px",backgroundColor:C?w.cardBorder:"#D0D2D8",margin:"4px 0"}})]},H.id)):n.jsx("div",{style:{padding:"12px 0",color:C?w.textSecondary:"#6B7280",fontSize:"13px",fontFamily:'"IBM Plex Mono", monospace'},children:"No collateral items available"})}),g&&g.length>0&&g.filter(H=>H&&H.id&&H.title&&typeof H.title=="string"&&H.title.trim().length>0).map(H=>n.jsx(go,{title:H.title,icon:H.icon||void 0,amount:q(Qo(H.totalBalance||0)),defaultExpanded:H.defaultExpanded!==void 0?H.defaultExpanded:!1,children:H.items&&H.items.length>0?H.items.map((G,ce)=>n.jsxs(c.Fragment,{children:[n.jsx(qn,{name:G.name,balance:q(Pn(G.balance)),subtitle:G.subtitle,networks:G.networks,icon:G.name==="USDC"?Mn:void 0,onClick:r?()=>r(G.id):void 0}),ce<H.items.length-1&&n.jsx("div",{style:{height:"1px",backgroundColor:C?w.cardBorder:"#D0D2D8",margin:"4px 0"}})]},G.id||`item-${ce}`)):n.jsx("div",{style:{padding:"12px 0",color:C?w.textSecondary:"#6B7280",fontSize:"13px",fontFamily:'"IBM Plex Mono", monospace'},children:H.emptyMessage||"No items available"})},H.id))]})]}),B&&n.jsx(mo,{isOpen:B,onClose:()=>I(!1),styles:s}),T&&n.jsx(Ho,{isOpen:T,onClose:()=>D(!1),styles:s,onWithdrawExecute:h,withdrawActionLabel:f})]})},Ii=({options:e,selectedIndex:t,onSelect:s,primaryColor:o,dark:a=!1,textPrimary:r="#111827",textSecondary:i="#6b7280",trackColor:d})=>{const u=e.length-1,l=d||(a?"#3a3a3a":"#d1d5db"),h=a?"4px":"50%",f=a?"none":"2px solid white",m=a?"none":`0 0 0 1px ${o}`;return n.jsxs("div",{style:{width:"100%",userSelect:"none"},children:[n.jsxs("div",{style:{position:"relative",paddingBottom:"4px"},children:[n.jsx("div",{style:{position:"absolute",top:"50%",left:0,right:0,height:"4px",background:l,borderRadius:"2px",transform:"translateY(-50%)",pointerEvents:"none"}}),n.jsx("div",{style:{position:"absolute",top:"50%",left:0,width:`${t/u*100}%`,height:"4px",background:o,borderRadius:"2px",transform:"translateY(-50%)",pointerEvents:"none",transition:"width 0.15s ease"}}),n.jsx("input",{type:"range","aria-label":"Lock duration","aria-valuetext":e[t]?.label,"data-spiceflow-focus":!0,min:0,max:u,step:1,value:t,onChange:x=>s(Number(x.target.value)),style:{WebkitAppearance:"none",appearance:"none",width:"100%",height:"20px",background:"transparent",cursor:"pointer",outline:"none",border:"none",position:"relative",zIndex:1,margin:0,padding:0}})]}),n.jsx("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"6px"},children:e.map((x,g)=>n.jsxs("div",{onClick:()=>s(g),style:{display:"flex",flexDirection:"column",alignItems:g===0?"flex-start":g===u?"flex-end":"center",cursor:"pointer",flex:1},children:[n.jsx("span",{style:{fontSize:"12px",fontWeight:g===t?700:400,color:g===t?r:i,whiteSpace:"nowrap",transition:"color 0.15s, font-weight 0.15s"},children:x.label}),x.highlight&&n.jsx("span",{style:{fontSize:"10px",color:i,whiteSpace:"nowrap"},children:"(most common)"})]},g))}),n.jsx("style",{children:`
67
67
  input[type='range']::-webkit-slider-thumb {
68
68
  -webkit-appearance: none;
69
69
  width: 20px;
package/dist/index.js CHANGED
@@ -63,7 +63,7 @@ import{jsxs as g,jsx as a,Fragment as fn}from"react/jsx-runtime";import hn,{useS
63
63
  transform: translateY(0);
64
64
  }
65
65
  }
66
- `})]})},As=new Set(["WBTC","CBTC"]),Er=new Set(["btc","wbtc","wcbtc","cbtc"]);function Fr(e,t){return!e||!t?!1:e===t?!0:As.has(e)&&As.has(t)}function io(e){const[t,n,o]=e.split(":");if(t!=="evm"||!n||!o)return null;const r=Number(n);if(!Number.isFinite(r))return null;const s=o.startsWith("0x")?o.toLowerCase():`0x${o.toLowerCase()}`;return{chainId:r,address:s}}function zo(e){return(e??"").trim().replace(/^test\s+/i,"").replace(/^spice/i,"").toLowerCase().replace(/[^a-z0-9]/g,"")}function al(e){return new Set([e.receiptTokenName,e.displaySymbol,e.symbol,e.displayName,e.name].map(zo).filter(Boolean))}function il(e,t){const n=al(e),o=[t.symbol,t.name,t.equivalenceGroup].map(zo);if(o.some(i=>i&&n.has(i)))return!0;const r=[...n].some(i=>Er.has(i)),s=o.some(i=>Er.has(i))||As.has(t.equivalenceGroup??"");return r&&s}function Br(e,t,n){const o=new Set(t.map(zo).filter(Boolean)),r=s=>{if(n&&Te(s.address,n))return 0;const i=[s.symbol,s.name,s.equivalenceGroup].map(zo).findIndex(c=>c&&o.has(c));return i===-1?4:i+1};return[...e].sort((s,i)=>{const c=r(s)-r(i);return c!==0?c:s.address.toLowerCase().localeCompare(i.address.toLowerCase())})}const Tr=typeof process<"u"&&process.env?.NEXT_PUBLIC_MORALIS_API_KEY||typeof import.meta<"u"&&import.meta.env?.VITE_MORALIS_API_KEY||"",ll="https://deep-index.moralis.io/api/v2.2";function Lo(e,t){const n=e.chainTokens?Object.keys(e.chainTokens):[],o=[];for(const r of n){const s=io(r);if(!s||s.chainId!==t)continue;const i=s.address,c=Tt(i,t);c&&(!Ss(e,i,t)&&!(e.isUniversal&&il(e,c))||o.some(d=>Te(d,i))||o.push(i))}return Br(o.map(r=>{const s=Tt(r,t);return{address:r,symbol:s?.symbol,name:s?.name,equivalenceGroup:s?.equivalenceGroup}}),[e.receiptTokenName,e.displaySymbol,e.symbol,e.displayName,e.name],e.chainId===t&&!e.isUniversal?e.address:void 0).map(r=>r.address)}function Ss(e,t,n){return e.chainId===n&&Te(e.address,t)?!0:ko(e.address,e.chainId,t,n)}async function cl(e,t){const n=lt(e),o=xn(e);return Pe(t)?n.getBalance({address:o}):await n.readContract({address:t,abi:Vt,functionName:"balanceOf",args:[o]})}function Mr(e,t,n){const o=Js(n),r=o.find(i=>Te(i.address,e));if(r)return r;const s=Tt(e,t);if(s)return Br(o.filter(i=>Fr(i.equivalenceGroup,s.equivalenceGroup)),[s.symbol,s.name,s.equivalenceGroup])[0]}function En(e,t){if(e.chainId===t)return e.address;const n=Mr(e.address,e.chainId,t);return n?n.address:null}async function Rr(e,t,n={}){const o=En(e,t),r=Lo(e,t);if(r.length===0)return o;if(r.length===1)return r[0];const s=n.requiredAmount??0n,i=d=>{const l=r.map(p=>({candidate:p,balance:d.get(Pe(p)?"native":p.toLowerCase())??0n})).filter(p=>p.balance>0n).sort((p,u)=>p.balance===u.balance?0:p.balance>u.balance?-1:1);return l.length===0?null:((s>0n?l.find(p=>p.balance>=s):l[0])??l[0]).candidate},c=Yn()[t];if(c?.moralisName&&Tr){const d=new Map,l=r.some(p=>Pe(p));try{if(l)try{const u=lt(t),f=xn(t);d.set("native",await u.getBalance({address:f}))}catch{}const p=await fetch(`${ll}/wallets/${xn(t)}/tokens?chain=${c.moralisName}`,{headers:{"X-API-Key":Tr}});if(p.ok){const u=await p.json();for(const m of u?.result||[]){const h=String(m.token_address||"").toLowerCase();if(h)try{d.set(h,BigInt(String(m.balance||"0")))}catch{}}const f=i(d);if(f)return f}}catch{}}try{const d=await Promise.all(r.map(async u=>({key:Pe(u)?"native":u.toLowerCase(),value:await cl(t,u)}))),l=new Map(d.map(({key:u,value:f})=>[u,f])),p=i(l);if(p)return p}catch{}return o}function ko(e,t,n,o){const r=Tt(e,t),s=Tt(n,o);return r&&s?Fr(r.equivalenceGroup,s.equivalenceGroup):Va(e,n)}function Oo(e,t){return ko(e.address,e.chainId,t.address,t.chainId)}const dl={usdc:[8453,1,42161,5115,4114],usdt:[1],btc:[4114,42161,1,5115],wbtc:[1],weth:[8453,1],ctusd:[5115,4114],wcbtc:[5115,4114]},ul={btc:["wcbtc","cbtc","wbtc"]};function Ho(e){return e.replace(/^test\s+/i,"").replace(/^spice/i,"").trim()}function Wn(e){return Ho(e).toLowerCase()}function Dr(e){return Wn(e??"").replace(/[^a-z0-9]/g,"")}function Es(e){const t=Wn(e);return[t,...ul[t]??[]].filter(Boolean)}function pl(e){try{return BigInt(e.balanceAvailable||"0")}catch{return 0n}}function fl(e){return Array.isArray(e.chainTokens)?e.chainTokens:Object.keys(e.chainTokens??{})}function hl(e,t,n,o=[]){const r=Re(t),s=n.toLowerCase(),i=s===Lt.toLowerCase()?r?.nativeCurrency.decimals??18:r?.supportedTokens?.find(d=>d.address.toLowerCase()===s)?.decimals??18,c=new Set(o.map(Dr).filter(Boolean));return e.reduce((d,l)=>{const p=pl(l),u=l.decimals??i,f=mo(p,u,i);if(fl(l).some(h=>{const y=io(h);return y&&ko(y.address,y.chainId,n,t)}))return d+f;if(c.size===0)return d;const m=Dr(l.tokenName||l.receiptToken);return c.has(m)?d+f:d},0n)}function ml(e,t){const n=new Set([...Es(t),...Es(Ho(t))]);return[...e].sort((o,r)=>{const s=Wn(o.symbol),i=Wn(r.symbol),c=Wn(o.name),d=Wn(r.name),l=n.has(s)?0:n.has(c)?1:2,p=n.has(i)?0:n.has(d)?1:2;return l!==p?l-p:o.address.toLowerCase().localeCompare(r.address.toLowerCase())})[0]}function gl(e){const t=e&&e.length>0?e:Object.keys(Eo).map(Number).filter(Number.isFinite),n=new Map;for(const o of t){const r=Re(o);if(!r)continue;const s=`${o}:${Lt.toLowerCase()}`;n.has(s)||n.set(s,{address:Lt,chainId:o,symbol:r.nativeCurrency.symbol,name:r.nativeCurrency.name,decimals:r.nativeCurrency.decimals,isNative:!0,logoURI:r.logo});for(const i of r.supportedTokens??[]){const c=i.address.toLowerCase(),d=`${o}:${c}`;n.has(d)||n.set(d,{address:c,chainId:o,symbol:i.symbol,name:i.name,decimals:i.decimals,isNative:Pe(c),logoURI:i.logo})}}return n}function yl(e,t){const n=gl(t),o=Ho(e.tokenName),r=Wn(e.tokenName),s=Es(e.tokenName),i=Array.isArray(e.chainTokens)?e.chainTokens.map(h=>[h,void 0]):Object.entries(e.chainTokens??{}),c=i.map(([h])=>io(h)).filter(h=>h!==null),d=new Map(i.map(([h,y])=>[h,y])),l=(h,y)=>{const C=d.get(`evm:${y.chainId}:${y.address.slice(2).toLowerCase()}`);return{...h,name:typeof C?.name=="string"&&C.name.length>0?C.name:h.name,decimals:typeof C?.decimals=="number"?C.decimals:h.decimals}},p=c.map(h=>{const y=n.get(`${h.chainId}:${h.address.toLowerCase()}`);return y?l(y,h):void 0}).filter(h=>h!==void 0),u=dl[r]??[];if(u.length>0)for(const h of u){const y=p.find(C=>C.chainId===h);if(y)return y}if(p.length>0)return ml(p,e.tokenName);const f=Array.from(n.values()).filter(h=>s.includes(Wn(h.symbol))||s.includes(Wn(h.name)));if(u.length>0)for(const h of u){const y=f.find(C=>C.chainId===h);if(y)return y}if(f.length>0)return f[0];const m=c[0];if(m){const h=d.get(`evm:${m.chainId}:${m.address.slice(2).toLowerCase()}`);return{address:m.address,chainId:m.chainId,symbol:o||e.tokenName,name:typeof h?.name=="string"&&h.name.length>0?h.name:o||e.tokenName,decimals:typeof h?.decimals=="number"?h.decimals:e.decimals??18,isNative:Pe(m.address),logoURI:void 0}}}function xl(e,t){let n;try{n=BigInt(e.balanceAvailable||"0")}catch{return null}if(n<=0n)return null;const o=yl(e,t),r=o?.decimals??e.decimals??18,s=e.decimals??r,i=mo(n,s,r),c=o?.address??Lt,d=o?.chainId??0,l=Ho(e.tokenName),p=o?.symbol??l,u=o?.name??l,f=parseFloat(tt(i,r)),m=typeof e.balanceUsd=="number"?e.balanceUsd:typeof e.balanceUsd=="string"&&Number(e.balanceUsd)||0;return{address:c,symbol:p,name:u,decimals:r,chainId:d,balance:i,balanceFormatted:f,balanceUsd:m,isNative:o?.isNative??Pe(c),logoURI:o?.logoURI,displaySymbol:e.tokenName||p,displayName:e.tokenName||u,displayChainName:"Spicenet",receiptTokenId:e.receiptToken,receiptTokenName:e.tokenName||u,receiptTokenDecimals:s,chainTokens:e.chainTokens&&!Array.isArray(e.chainTokens)?e.chainTokens:void 0,isUniversal:!0}}function bl(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 vo=({address:e,supportedChains:t,enabled:n=!0,refetchInterval:o})=>{const r=Jt(zt)?.apiUrl||Da,[s,i]=M([]),[c,d]=M(!1),[l,p]=M(null),[u,f]=M(!1),m=ie(!1),h=ie(!1),y=t?JSON.stringify([...t].sort()):"",C=ce(async(x=!1)=>{if(!e||!n){i([]),f(!1),m.current=!1;return}if(!h.current){h.current=!0,!m.current&&!x&&d(!0),p(null);try{const k=await fetch(`${r}/wallets/${e}/balance`,{cache:"no-store"});if(!k.ok)throw new Error(`Failed to fetch balance: ${k.status}`);const w=await k.json();if(w.balances&&Array.isArray(w.balances)){const A=w.balances.map(S=>xl({receiptToken:typeof S.receiptToken=="string"?S.receiptToken:void 0,tokenName:String(S.tokenName??""),balanceAvailable:String(S.balanceAvailable??"0"),chainTokens:bl(S),decimals:typeof S.decimals=="number"?S.decimals:void 0,balanceUsd:typeof S.balanceUsd=="number"||typeof S.balanceUsd=="string"?S.balanceUsd:null},t)).filter(S=>S!==null);i(A),f(A.length>0),m.current=!0}else i([]),f(!1)}catch(k){const w=k instanceof Error?k.message:"Failed to fetch balance";p(w),console.error("Error fetching Spice assets:",k),m.current||(i([]),f(!1))}finally{d(!1),h.current=!1}}},[e,n,y,r]);J(()=>{n&&e&&(m.current=!1,C(!1))},[e,n,y]),J(()=>{if(!n||!e||!o)return;const x=setInterval(()=>{C(!0)},o);return()=>clearInterval(x)},[e,n,o,y]);const v=ce(x=>s.filter(k=>k.chainId===x),[s]),b=ce(async()=>{await C(!0)},[C]);return{assets:s,loading:c,error:l,hasBalance:u,refetch:b,getAssetsByChain:v}},Wr=e=>new Promise(t=>setTimeout(t,e));function wl(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 Cl=350,kl=1e3;async function vl(e){const{actionId:t,intentIndex:n,intentId:o,stepIndex:r,maxPolls:s=120,maxExecuteAttempts:i=3,pollsBeforeRetry:c=5,maxConsecutiveStatusErrors:d=15,onStatusMessage:l,signal:p,chainId:u}=e;let f="pending",m,h,y=0,C=0;const v=()=>{y++,$e.executeStep(t,n,r,{action:"execute"}).then(b=>{b.transactionHash&&(m=b.transactionHash)}).catch(b=>{const x=b instanceof Error?b.message:String(b);console.warn(`[execution] executeStep ${r} attempt ${y} error (will poll):`,x)})};v();for(let b=0;b<s;b++){if(await Wr(b===0?Cl:kl),p?.aborted)throw new De("ABORT","Gasless transaction aborted");try{const k=await $e.checkStepStatus(o,r);C=0,f=k.data.status,h=k.data.error;const w=k.data.transactionHash;w&&(m=w)}catch(k){if(k instanceof Error&&(k.name==="AbortError"||k instanceof De&&k.code==="ABORT")||(C++,C>=d))throw k;continue}if(f==="created"&&b>=y*c&&y<i&&v(),f==="reverted"||f==="error")throw new De("ON_CHAIN_REVERT",wl(f,h),{status:f,txHash:m,actionId:t,intentId:o,stepId:r,chainId:u});if(f==="success"||f==="completed")return m;let x="Waiting for solver...";f==="executing"?x="Transaction executing...":f==="submitted"?x="Transaction submitted...":f==="created"&&(x="Waiting for relayer..."),l?.(x,m)}throw new De("POLLING_EXHAUSTED",`Transaction is still processing (status: ${f}). 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:o,stepId:r,lastStatus:f,pollAttempts:s,maxPolls:s,txHash:m})}async function Nr(e){const{actionId:t,intentIndex:n,intentId:o,totalSteps:r,delayBeforeSpicenetStepMs:s=5e3,isSpicenetStep:i,maxExecuteAttemptsForStep:c,maxPolls:d=120,onStatusMessage:l,signal:p}=e;let u;for(let f=0;f<r;f++){f>0&&i?.(f)&&s>0&&await Wr(s);const m=c?.(f)??3,h=await vl({actionId:t,intentIndex:n,intentId:o,stepIndex:f,maxPolls:d,maxExecuteAttempts:m,maxConsecutiveStatusErrors:m===6?5:15,onStatusMessage:l,signal:p});h&&(u=h)}return u}function Fs(e,t){return e<=0n||t<=0n?0n:(e*t+10000n-1n)/10000n}function Nn(e){const t=BigInt(e.feeBreakdown.spicenetFee),n=BigInt(e.feeBreakdown.gasFee),o=BigInt(e.feeBreakdown.bridgeFee??"0"),r=t+n+o;return{spicenetFee:t,gasFee:n,bridgeFee:o,totalFee:r}}function Pr(e){const t=BigInt(e.quotedAmount),n=BigInt(e.totalDebit),{totalFee:o}=Nn(e);return t>0n||n>0n||o>0n}function Il(e){const t=BigInt(e.quotedAmount),n=BigInt(e.totalDebit),{totalFee:o}=Nn(e),r=t+o;return n>r?n:r}function Al(e){const t=[];for(const n of e.intents)for(const o of n.batches)t.push(BigInt(o.quotedAmount));return t.length!==1?null:t[0]}function Io(e,t){const n=e.intents.flatMap(d=>d.batches).filter(Pr);if(n.length===0||n.length>1)return null;const o=n[0],{gasFee:r,spicenetFee:s,bridgeFee:i,totalFee:c}=Nn(o);return{symbol:t.symbol,decimals:t.decimals,grossAmount:BigInt(o.totalDebit),netAmount:t.actionAmount??BigInt(o.quotedAmount),totalFee:c,spicenetFee:s,gasFee:r,bridgeFee:i,gasQuoteSource:o.gasQuoteSource}}function Xn(e,t){const n=e.intents.flatMap(p=>p.batches).filter(Pr);if(n.length===0)return null;const o=n.filter(p=>p.chainId===t.chainId),r=o.length>0?o:n;if(r.length>1)return null;const s=r[0],{gasFee:i,spicenetFee:c,bridgeFee:d,totalFee:l}=Nn(s);return{chainId:s.chainId,tokenAddress:t.tokenAddress,symbol:t.symbol,decimals:t.decimals,grossAmount:Il(s),netAmount:BigInt(s.quotedAmount),totalFee:l,gasFee:i,spicenetFee:c,bridgeFee:d,gasQuoteSource:s.gasQuoteSource}}const Sl=10n,El=5;function jo(e){return e.map(t=>({...t,calls:[...t.calls],tokenTransfers:t.tokenTransfers?[...t.tokenTransfers]:void 0}))}function Qo({token:e,recipient:t,amount:n}){return{to:e,value:0n,data:mt({abi:qe,functionName:"transfer",args:[t,n]})}}function Ur({chainBatches:e,token:t,amount:n}){const o=jo(e),r=o[o.length-1];if(!r)return o;const s=xn(r.chainId);return r.calls=[...r.calls,Qo({token:t,recipient:s,amount:n})],o}function zr({chainBatches:e,user:t,token:n,grossAmount:o,gasFee:r}){const s=jo(e),i=s[s.length-1];if(!i)throw new De("INVALID_PARAMS","Action-output escrow funding requires at least one chain batch.");const c=Fs(o,Sl),d=r+c;if(d>=o)throw new De("INVALID_PARAMS","Borrow amount is too small after gas and Spicenet fees.",{grossAmount:o.toString(),gasFee:r.toString(),spicenetFee:c.toString()});const l=o-d,p=xn(i.chainId),u=[];return r>0n&&u.push(Qo({token:n,recipient:Kn,amount:r})),c>0n&&u.push(Qo({token:n,recipient:Bo,amount:c})),i.calls=[...i.calls,...u,Qo({token:n,recipient:p,amount:l})],i.tokenTransfers=[...i.tokenTransfers??[],...r>0n?[{from:t,to:Kn,token:n,amount:r}]:[],...c>0n?[{from:t,to:Bo,token:n,amount:c}]:[],{from:t,to:p,token:n,amount:l}],{chainBatches:s,gasFee:r,spicenetFee:c,netEscrowAmount:l,outputCredit:{chainId:i.chainId,token:n,amount:o}}}async function Lr({chainBatches:e,user:t,token:n,grossAmount:o,chainAuthorizations:r}){let s=0n,i=zr({chainBatches:e,user:t,token:n,grossAmount:o,gasFee:s});for(let c=0;c<El;c+=1){const d=Fn(i.chainBatches),l=(await $e.estimateBatchGas({user:t,outputToken:n,chainBatches:i.chainBatches.map((p,u)=>({...p,hash:d[u].hash})),chainAuthorizations:r})).gasFee;if(l===s)return i;s=l,i=zr({chainBatches:e,user:t,token:n,grossAmount:o,gasFee:s})}throw new De("INVALID_PARAMS","Action-output fee estimate did not converge. Please retry.")}function Jn(e){return To(e.chainId)}function Fl(e,t){if(e.length!==t.length)return!1;const n=Fn(e),o=Fn(t);return n.every((r,s)=>r.hash===o[s]?.hash)}const Or="0xa9059cbb";function Vo(e,t){return`${e}:${t.toLowerCase()}`}function Hr(e,t){return t===Lt.toLowerCase()?{symbol:tn(e),decimals:18}:Tt(t,e)??{symbol:"tokens",decimals:18}}function Bl(e,t){const n=Tt(t,e);return[n?.equivalenceGroup,n?.symbol,n?.name]}async function Tl(e){return Wa(e)}function Bs(e,t){return e.map(n=>{if(Jn(n)||n.calls.length===0)return n;const o=new Set((n.tokenTransfers??[]).filter(s=>(s.from==="escrow"||s.from==="solver")&&Te(s.to,t)).map(s=>s.token.toLowerCase()));if(o.size===0)return n;let r=0;for(const s of n.calls){if(!s.data?.startsWith(Or))break;try{const i=Mo({abi:qe,data:s.data});if(i.functionName!=="transfer")break;const[c]=i.args;if(Te(c,t)||!o.has(s.to.toLowerCase()))break;r+=1}catch{break}}return r===0?n:{...n,calls:n.calls.slice(r)}})}async function Ml(e,t,n){const o=new Map,r=new Map,s=new Map,i=new Map;for(const d of n?.actionOutputCredits??[]){const l=Vo(d.chainId,d.token);i.set(l,(i.get(l)??0n)+d.amount)}for(const d of e)if(!Jn(d)){for(const l of d.tokenTransfers??[]){if(l.from!=="escrow"&&l.from!=="solver"||!Te(l.to,t))continue;const p=BigInt(l.amount??0);if(p<=0n)continue;const u=Vo(d.chainId,l.token);r.set(u,(r.get(u)??0n)+p),l.from==="escrow"&&s.set(u,(s.get(u)??0n)+p)}for(const l of d.calls){if(l.value&&l.value>0n){const p=Vo(d.chainId,Lt);o.set(p,(o.get(p)??0n)+l.value)}if(l.data?.startsWith(Or))try{const p=Mo({abi:qe,data:l.data});if(p.functionName!=="transfer")continue;const[,u]=p.args,f=l.to.toLowerCase(),m=Vo(d.chainId,f);o.set(m,(o.get(m)??0n)+u)}catch{}}}let c=null;for(const[d,l]of s){if(l<=0n)continue;const[p,u]=d.split(":"),f=Number(p),m=Hr(f,u);c??(c=await Tl(t));const h=hl(c,f,u,Bl(f,u));if(!(h>=l))throw new De("INVALID_PARAMS",`Insufficient Spice ${m.symbol}: needs ${tt(l,m.decimals)}, has ${tt(h,m.decimals)}.`,{chainId:f,token:u,userAddress:t,requiredAmount:l.toString(),balance:h.toString(),balanceSource:"spice"})}for(const[d,l]of o){if(l<=0n)continue;const[p,u]=d.split(":"),f=Number(p),m=l-(r.get(d)??0n)-(i.get(d)??0n);if(m<=0n)continue;const h=lt(f),y=u===Lt.toLowerCase()?await h.getBalance({address:t}):await h.readContract({address:u,abi:qe,functionName:"balanceOf",args:[t]});if(y>=m)continue;const C=Hr(f,u);throw new De("INVALID_PARAMS",`Insufficient ${C.symbol} on ${tn(f)}: needs ${tt(m,C.decimals)}, has ${tt(y,C.decimals)}.`,{chainId:f,token:u,userAddress:t,requiredAmount:m.toString(),balance:y.toString(),balanceSource:"wallet"})}}function Rl({chainBatches:e,tokenAddress:t,tokenTransferAmount:n,useCustomTransfers:o}){if(!(e.some(Jn)||!(o?e.some(r=>Jn(r)?!1:(r.tokenTransfers??[]).some(s=>s.from==="escrow"&&BigInt(s.amount??0)>0n)):n>0n)))throw new De("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:!!o})}function Dl(e,t,n,o){t.forEach((r,s)=>{if(!r.to||!r.from||!r.token||r.amount===void 0)throw new De("INVALID_TOKEN_TRANSFER",`tokenTransfers[${s}] 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:s,transfer:{from:r.from,to:r.to,token:r.token,amount:r.amount?.toString()},signingAddress:n,useCustomTransfers:o})})}function Ts({user:e,chainBatches:t,tokenAddress:n,tokenTransferAmount:o,exp:r,signature:s,chainAuthorizations:i,useCustomTransfers:c}){const d=t,l=Fn(d),p=d.filter(u=>!Jn(u)).length;if(Rl({chainBatches:d,tokenAddress:n,tokenTransferAmount:o,useCustomTransfers:c}),!c&&o>0n&&p>1)throw new De("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:o.toString()});return{user:e,...i?{chainAuthorizations:i}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:s,nbf:0,exp:r,chainBatches:l.map((u,f)=>{const m=d[f],h=Jn(m)?[]:c?m.tokenTransfers??[]:o>0n?[{from:"escrow",to:e,token:n,amount:o}]:[];return Dl(Number(u.chainId),h,e,c),{hash:u.hash,chainId:Number(u.chainId),tokenTransfers:h,calls:u.calls}})}]}}function Wl(e,t){const n=Fn(e).map(o=>o.hash);return go(yo([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,t,n]))}let Ms=!1;function qo(){const{address:e,isConnected:t,isAuthenticated:n,actions:o}=An(),[r,s]=M(null),i=ie(o),c=ie(new Map);i.current=o;const d=ce(async(f,m,h)=>{const y=[...new Set(f.filter(b=>!Jn(b)).map(b=>b.chainId))],C=await Promise.all(y.map(async b=>{const x=lt(b),k=fo(b),w=Number(await es(m,x)),A=[m.toLowerCase(),b,k.toLowerCase(),w].join(":");return{chainId:b,delegateContract:k,nonce:w,cacheKey:A,cached:c.current.get(A)}})),v=[];for(const{chainId:b,delegateContract:x,nonce:k,cacheKey:w,cached:A}of C){if(A){v.push(A);continue}if(h?.aborted)throw new De("ABORT","Gasless transaction aborted");const S=await i.current.signAuthorization({contractAddress:x,chainId:b,nonce:k}),B={r:S.r,s:S.s,yParity:S.yParity,address:S.address??x,chainId:Number(S.chainId??b),nonce:Number(S.nonce??k)};c.current.set(w,B),v.push(B)}return v},[]),l=ce(async(f,m,h)=>{if(h?.aborted)throw new De("ABORT","Gasless transaction aborted");const y=await i.current.signMessage({raw:Wl(f,m)}),C=typeof y=="string"?y:y.signature;if(!C)throw new De("SIGNATURE_FAILED","Failed to sign intent authorization. The wallet returned an empty signature.");return C},[]),p=ce(async(f,m,h,y,C,v)=>{const b=(x,k,w)=>{y?.({step:x,message:k,...w})};if(Ms)throw new De("CONCURRENT_EXECUTION","A gasless transaction is already in progress. Please wait.");Ms=!0;try{if(!e)throw new De("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const x=v?.userOverride||e,k=v?.depositToEscrow?.gasFundingSource==="action-output"?v.depositToEscrow:null;let w=v?.depositToEscrow&&!k?Ur({chainBatches:f,token:v.depositToEscrow.token,amount:v.depositToEscrow.amount}):jo(f),A=[],S=v?.useCustomTransfers;b("signing-delegation","Sign delegation in your wallet...");const B=await d(w,x,C);if(C?.aborted)throw new De("ABORT","Gasless transaction aborted");const E=BigInt(Math.floor(Date.now()/1e3)+3600);if(k){const L=await Lr({chainBatches:f,user:x,token:k.token,grossAmount:k.amount,chainAuthorizations:B});w=L.chainBatches,A=[L.outputCredit],S=!0}if(!v?.skipPreSubmitFeeEstimate){let L=!1;for(let Q=0;Q<5;Q++){const V=v?.feeExecutionMode==="user-transfer"?Bs(w,x):w,O=Ts({user:x,chainBatches:V,tokenAddress:m,tokenTransferAmount:h,exp:Number(E),signature:"0x00",chainAuthorizations:B,useCustomTransfers:S}),K=await $e.estimateActionFees(O);s(K);const ue=v?.adjustBatchesForEstimate?.({feeEstimate:K,chainBatches:w});if(!ue||Fl(w,ue)){L=!0;break}w=ue}if(!L)throw new De("INVALID_PARAMS","Withdraw fee estimate did not converge. Please retry.")}v?.skipUserFundingPreflight||await Ml(w,x,{actionOutputCredits:A}),b("signing-intent","Sign the intent in your wallet...");const I=await l(w,E,C);if(C?.aborted)throw new De("ABORT","Gasless transaction aborted");b("submitting","Submitting to relayer...");const F=Ts({user:x,chainBatches:w,tokenAddress:m,tokenTransferAmount:h,exp:Number(E),signature:I,chainAuthorizations:B,useCustomTransfers:S}),R=await $e.createAction(F),[T,N]=R.intentIds[0].split("/"),z=parseInt(N||"0",10),W=`${T}/${z}`;b("executing","Executing on chain..."),b("executing","Executing on chain...",{actionId:T,intentId:W,intentIndex:z,totalSteps:w.length});const H=w.length,D=await Nr({actionId:T,intentIndex:z,intentId:W,totalSteps:H,signal:C,isSpicenetStep:L=>w[L]?.domain==="spicenet",maxExecuteAttemptsForStep:L=>w[L]?.domain==="spicenet"?6:3,maxPolls:180,onStatusMessage:(L,Q)=>{b("executing",L,{txHash:Q,actionId:T,intentId:W,intentIndex:z,totalSteps:H})}});return b("success","Transaction successful!",{txHash:D,actionId:T,intentId:W,intentIndex:z,totalSteps:H}),D||T}catch(x){throw console.error("[GaslessExecution] Error:",x),b("error",x.message||"Transaction failed",{error:x.message}),x}finally{Ms=!1}},[e,n,d,l]),u=ce(async(f,m,h,y)=>{if(!e)throw new De("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const C=y?.userOverride||e,v=y?.depositToEscrow?.gasFundingSource==="action-output"?y.depositToEscrow:null;let b=y?.depositToEscrow&&!v?Ur({chainBatches:f,token:y.depositToEscrow.token,amount:y.depositToEscrow.amount}):jo(f);const x=y?.feeExecutionMode==="user-transfer"?Bs(b,C):b,k=y?.signAuthorizationsForEstimate?await d(x,C):void 0;let w=y?.useCustomTransfers;v&&(b=(await Lr({chainBatches:f,user:C,token:v.token,grossAmount:v.amount,chainAuthorizations:k})).chainBatches,w=!0);const A=y?.feeExecutionMode==="user-transfer"?Bs(b,C):b,S=Ts({user:C,chainBatches:A,tokenAddress:m,tokenTransferAmount:h,exp:Math.floor(Date.now()/1e3)+3600,signature:"0x00",chainAuthorizations:k,useCustomTransfers:w}),B=await $e.estimateActionFees(S);return s(B),B},[e,d]);return{executeGasless:p,estimateGasless:u,lastFeeEstimate:r,hasEmbeddedWallet:t&&n}}const Nl={usdc:1,"usdc.e":1,usdt:1,dai:1,ctusd:1,wbtc:1e5,wcbtc:1e5,cbtc:1e5};function Rs(e,t){return tt(e,t).replace(/(\.\d*?[1-9])0+$|\.0+$/,"$1")}function jr(e,t,n){return t===n?e:t<n?e*10n**BigInt(n-t):e/10n**BigInt(t-n)}function Qr(e,t){const n=t?Nl[t.trim().toLowerCase()]??0:0,o=e*n;return o<=0?"$0":o>=1?`$${o.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}`:`$${o.toFixed(4).replace(/0+$/,"").replace(/\.$/,"")}`}function Pl(e,t){return t?JSON.stringify({tokenAddress:t.toLowerCase(),batches:e.map(n=>({chainId:n.chainId,calls:n.calls.map(o=>({to:o.to.toLowerCase(),value:o.value.toString(),data:o.data})),tokenTransfers:(n.tokenTransfers??[]).map(o=>({from:o.from,to:o.to.toLowerCase(),token:o.token.toLowerCase(),amount:o.amount.toString()}))}))}):null}function Ul(e){const t=e.find(n=>To(n.chainId))?.calls?.[0]?.data;if(!t)return null;try{const n=Mo({abi:ts,data:t});return n.functionName!=="createWithdrawalRequest"?null:n.args[0].transfers.map(o=>({token:o.token,recipient:o.to,amount:o.amount}))}catch{return null}}function zl(e,t){return!e||e.length!==t.length?!1:e.every((n,o)=>{const r=t[o];return n.token.toLowerCase()===r.token.toLowerCase()&&n.recipient.toLowerCase()===r.recipient.toLowerCase()&&n.amount===r.amount})}function Ll(e,t){const n=e.intents.flatMap(s=>s.batches).filter(s=>{const i=Nn(s);return BigInt(s.quotedAmount)>0n||BigInt(s.totalDebit)>0n||i.totalFee>0n}),o=n.filter(s=>s.chainId===t),r=o.length>0?o:n;return r.length===1?r[0]:null}function Ol(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const o=n.token.toLowerCase(),r=n.recipient.toLowerCase(),s=`${o}:${r}`,i=t.get(s);i?i.amount+=n.amount:t.set(s,{...n})}return[...t.values()]}function Hl(e,t){if(!e.token||!e.recipient||e.chainId===null)return null;const n=Ll(t,e.chainId);if(!n)return null;const{gasFee:o,bridgeFee:r,spicenetFee:s}=Nn(n),i=o+r,c=[{token:e.token.address,recipient:e.recipient,amount:e.receiveAmountRaw}];return i>0n&&c.push({token:e.token.address,recipient:Kn,amount:i}),s>0n&&c.push({token:e.token.address,recipient:Bo,amount:s}),Ol(c)}async function Vr(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(d=>To(d.chainId)))throw new Error("Spice withdrawals must include a Spicenet funding batch before the destination chain batch.");const n=e.token?.address||"",o={useCustomTransfers:!0},r=await e.gasless.estimateGasless(t,n,0n,o);let s=r;const i=Hl(e,r);e.buildSpicenetBatch&&i!==null&&!zl(Ul(t),i)&&(t=e.buildWithdrawBatches(i));const c=s.intents[0]?.batches[0]??null;c&&e.ui.setLockedGasFee(Nn(c).totalFee),await e.gasless.executeGasless(t,n,0n,d=>{d.actionId&&d.intentId&&typeof d.intentIndex=="number"&&typeof d.totalSteps=="number"&&(e.executionContextRef.current={actionId:d.actionId,intentId:d.intentId,intentIndex:d.intentIndex,totalSteps:d.totalSteps}),e.ui.setExecutionProgress(d)},void 0,{...o,skipPreSubmitFeeEstimate:!0,submittedFeeEstimate:s})}window.dispatchEvent(new CustomEvent("withdraw-completed")),e.onWithdrawSuccess?.({token:e.token?.symbol||"",amount:e.amount,chainId:e.chainId})}catch(t){const n=t instanceof Error?t.message:"Withdraw failed";e.ui.setExecutionError(n),e.onWithdrawError?.(n)}finally{e.ui.setIsExecuting(!1)}}}async function jl(e){const t=e.executionContextRef.current;if(!t){e.ui.setExecutionProgress(null),await Vr(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 o=0;o<t.totalSteps;o++)if((await $e.checkStepStatus(t.intentId,o)).data.status!=="success"){n=o;break}if(n>=t.totalSteps)e.ui.setExecutionProgress(o=>({...o||{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 o=n;o<t.totalSteps;o++){let r="pending",s;try{const i=await $e.executeStep(t.actionId,t.intentIndex,o,{action:"execute"});i.transactionHash&&(s=i.transactionHash)}catch{}for(let i=0;i<120;i++){if(await new Promise(d=>setTimeout(d,Math.min(1e3+i*1e3,5e3))),!e.isMountedRef.current)return;const c=await $e.checkStepStatus(t.intentId,o);if(!e.isMountedRef.current)return;if(r=c.data.status,c.data.transactionHash&&(s=c.data.transactionHash),r==="success"){e.ui.setExecutionProgress({step:o===t.totalSteps-1?"success":"executing",message:o===t.totalSteps-1?"Transaction successful!":"Executing remaining steps...",txHash:s,actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps});break}if(r==="reverted"||r==="error")throw new Error("Withdraw failed");e.ui.setExecutionProgress({step:"executing",message:"Executing remaining steps...",txHash:s,actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps})}if(!e.isMountedRef.current)return;if(r!=="success")throw new Error("Withdraw is still processing")}window.dispatchEvent(new CustomEvent("withdraw-completed")),e.onWithdrawSuccess?.({token:e.token?.symbol||"",amount:e.amount,chainId:e.chainId})}catch(n){const o=n instanceof Error?n.message:"Withdraw failed";e.ui.setExecutionError(o),e.onWithdrawError?.(o)}finally{e.ui.setIsExecuting(!1)}}async function Ql(e){const t=(await e.estimateGasless(e.batches,e.tokenAddress,0n,{useCustomTransfers:!0})).intents[0]?.batches[0];if(!t)throw new Error("No gas fee estimate was returned for this withdraw.");return Nn(t).totalFee}const qr='"IBM Plex Mono", monospace',Yr='"Helvetica Neue", sans-serif',Vl=({show:e,position:t,popoverRef:n,spiceAssets:o,dark:r,dk:s})=>{if(!e||!t)return null;const i=r?s.textSecondary:"#71757A",c=r?s.textPrimary:"#0E0D0B",d=o||[];return g("div",{ref:n,"data-balance-popover":!0,style:{position:"fixed",top:`${t.top}px`,left:`${t.left}px`,width:"220px",background:r?s.cardBg:"#FFFFFF",border:`1px solid ${r?s.cardBorder:"#D6D6D6"}`,borderRadius:"10px",boxShadow:r?"0 12px 32px rgba(0,0,0,0.32)":"0 12px 28px rgba(15, 23, 42, 0.14)",padding:"10px",zIndex:40},children:[a("div",{style:{fontFamily:qr,fontSize:"11px",letterSpacing:"0.05em",color:i,marginBottom:"8px"},children:"ALL BALANCES"}),a("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:d.length>0?d.map(l=>{const p=l.displaySymbol||l.receiptTokenName||l.symbol;return g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"10px",padding:"6px 0"},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0},children:[l.logoURI?a("img",{src:l.logoURI,alt:p,style:{width:"18px",height:"18px",borderRadius:"50%",flexShrink:0}}):a("div",{style:{width:"18px",height:"18px",borderRadius:"50%",border:`1px solid ${r?s.cardBorder:"#C8C8C8"}`,flexShrink:0}}),a("span",{style:{fontFamily:Yr,fontSize:"13px",color:c,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:p})]}),a("span",{style:{fontFamily:qr,fontSize:"12px",color:c,flexShrink:0},children:On(l.balanceFormatted)})]},l.receiptTokenId||l.address)}):a("span",{style:{fontFamily:Yr,fontSize:"13px",color:i},children:"No balances"})})]})},ql='"Helvetica Neue", sans-serif',Hn='"IBM Plex Mono", monospace',Yl=({show:e,onToggle:t,showCustomAddress:n,setShowCustomAddress:o,customRecipient:r,setCustomRecipient:s,externalAddress:i,recipientAddress:c,destChainName:d,destChainLogo:l,compatibleDestinationChains:p,txDetailsChainSwitchRef:u,onOpenNetworkPopover:f,sourceChainLabel:m,sourceDetailsLogo:h,sourceTokenLabel:y,amount:C,totalSourceDebitDisplay:v,receiveAmountDisplay:b,destTokenSymbol:x,shouldQuoteWithdrawGas:k,estimatingFee:w,feeError:A,displayedGasFee:S,selectedDestToken:B,theme:E,styles:I,dark:F,dk:R})=>{const T=F?R.textSecondary:"#71757A",N=F?R.textPrimary:"#0E0D0B",z=p.length>1,W=n&&r?bn(r)?`${r.slice(0,6)}...${r.slice(-4)}`:r:c?`${c.slice(0,6)}...${c.slice(-4)}`:"\u2014";return g(fn,{children:[g("div",{onClick:t,style:{display:"flex",alignItems:"center",gap:"6px",marginBottom:e?"10px":"0",cursor:"pointer",userSelect:"none"},children:[a("span",{style:{fontSize:"13px",color:T,fontFamily:ql,fontWeight:600},children:"Transaction Details"}),a(Ma,{size:12,color:T,style:{transform:e?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s"}})]}),e&&g("div",{style:{display:"flex",flexDirection:"column",gap:"7px"},children:[g("div",{children:[g("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[a("span",{style:{fontSize:"12px",color:T,fontFamily:Hn,fontWeight:500,letterSpacing:"0.03em"},children:"TO"}),g("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[a("span",{style:{fontSize:"13px",color:N,fontFamily:Hn,fontWeight:500},children:W}),a("button",{onClick:()=>{o(H=>!H),!n&&i&&s(i)},style:{background:"none",border:"none",cursor:"pointer",padding:"0",fontSize:"9.5px",fontFamily:Hn,color:T,textDecoration:"underline",fontWeight:600},children:n?"Reset":"Switch"})]})]}),n&&g("div",{style:{marginTop:"6px"},children:[a("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:Hn,fontWeight:700,letterSpacing:0,textTransform:"uppercase"},children:"CAUTION: ENTERING AN INCORRECT ADDRESS WILL RESULT IN LOSS OF FUNDS"}),a("input",{type:"text",autoComplete:"off",spellCheck:!1,"aria-label":"Recipient address","aria-invalid":r&&!bn(r)?!0:void 0,"data-spiceflow-focus":!0,value:r,onChange:H=>s(H.target.value),placeholder:"0x...",style:{width:"100%",padding:"8px 10px",borderRadius:"6px",border:`1px solid ${r&&!bn(r)?F?R.errorBorder:"#fca5a5":F?R.inputBorder:"#d1d5db"}`,backgroundColor:F?R.inputBg:"#f9fafb",color:F?R.inputText:"#111827",fontSize:"12px",fontFamily:Hn,outline:"none",boxSizing:"border-box"}}),r&&!bn(r)&&a("span",{style:{fontSize:"11px",color:R.errorText,marginTop:"3px",display:"block"},children:"Invalid address"})]})]}),a(ao,{palette:R,labelColor:T,valueColor:N,label:"RECEIVING CHAIN",value:g("div",{style:{display:"flex",alignItems:"center",gap:"7px"},children:[l&&a("img",{src:l,alt:d,style:{width:"14px",height:"14px",borderRadius:"50%"}}),a("span",{style:{fontSize:"13px",color:N,fontWeight:500,fontFamily:Hn,textTransform:"uppercase"},children:d}),a("button",{ref:u,onClick:H=>{H.stopPropagation(),f(u.current)},style:{background:"none",border:"none",cursor:z?"pointer":"not-allowed",padding:"0",fontSize:"9.5px",fontFamily:Hn,color:T,textDecoration:"underline",fontWeight:600,opacity:z?1:.45},children:"Switch"})]})}),a(ao,{palette:R,labelColor:T,valueColor:N,label:"REQUESTED WITHDRAWAL",value:g(Ds,{logo:h||null,alt:m,primaryText:N,children:[C||"0"," ",y]})}),k&&a(ao,{palette:R,labelColor:T,valueColor:N,label:"TOTAL SOURCE DEBIT",value:g(Ds,{logo:h||null,alt:m,primaryText:N,children:[v," ",y]})}),a(ao,{palette:R,labelColor:T,valueColor:N,label:"YOU RECEIVE",value:g(Ds,{logo:l,alt:d,primaryText:N,gap:"4px",children:[b," ",x]})}),k&&g(fn,{children:[a(ao,{palette:R,labelColor:T,label:"EST. GAS FEE",valueColor:A?"#f87171":N,value:w?"Estimating...":A?"Unavailable":S!==null&&B?`${Rs(S,B.decimals)} ${B.symbol}`:"Estimating..."}),A&&a(ro,{variant:"error",size:"compact",palette:R,fontFamily:I?.fontFamily||E.typography.fontFamily,children:A})]})]})]})},Ds=({logo:e,alt:t,primaryText:n,gap:o="6px",children:r})=>g("div",{style:{display:"flex",alignItems:"center",gap:o},children:[e&&a("img",{src:e,alt:t,style:{width:"13px",height:"13px",borderRadius:"50%"}}),a("span",{style:{fontSize:"13px",color:n,fontWeight:500,fontFamily:Hn},children:r})]});function Kr(e){const t=new Set($s(e).map(n=>n.toLowerCase()));return t.add(e.toLowerCase()),t}const Kl=["USDC","USDT","WETH","WBTC"];function Ws(e,t){const n=Re(t);if(!n)return;if(n.nativeCurrency.symbol.toUpperCase()===e.toUpperCase())return{address:Lt,symbol:n.nativeCurrency.symbol,decimals:n.nativeCurrency.decimals,chainId:t};const o=n.supportedTokens?.find(r=>r.symbol.toUpperCase()===e.toUpperCase());if(o)return{address:o.address.toLowerCase(),symbol:o.symbol,decimals:o.decimals,chainId:t}}function Pn(e,t,n){const o=Re(t);if(!o)return;if(n!==void 0){const i=Mr(e,n,t);if(i)return{address:i.address.toLowerCase(),symbol:i.symbol,decimals:i.decimals,chainId:t}}const r=Kr(e);if([...r].some(i=>Pe(i)))return{address:Lt,symbol:o.nativeCurrency.symbol,decimals:o.nativeCurrency.decimals,chainId:t};const s=o.supportedTokens?.find(i=>r.has(i.address.toLowerCase()));if(s)return{address:s.address.toLowerCase(),symbol:s.symbol,decimals:s.decimals,chainId:t}}function Zr(e){const{sourceAsset:t,outputAsset:n,sourceChainId:o,destinationChainId:r,intermediaryCandidates:s=Kl}=e;if(Oo(t,n))return{strategy:"direct",sourceAsset:t,outputAsset:n,sourceChainId:o,destinationChainId:r,summary:`${t.symbol} fronted directly`};if(Pn(t.address,r,o))return{strategy:"direct",sourceAsset:t,outputAsset:n,sourceChainId:o,destinationChainId:r,summary:`${t.symbol} fronted on destination, swapped to ${n.symbol}`};if(Pn(n.address,o,r))return{strategy:"source-swap",sourceAsset:t,outputAsset:n,sourceChainId:o,destinationChainId:r,summary:`${t.symbol} \u2192 ${n.symbol} on source chain, then fronted`};for(const i of s){const c=Ws(i,o);if(!c||Oo(t,c)||Oo(n,c))continue;const d=Ws(i,r);if(d&&Oo(c,d))return{strategy:"intermediary",sourceAsset:t,outputAsset:n,intermediaryAsset:d,sourceChainId:o,destinationChainId:r,summary:`${t.symbol} \u2192 ${i} on source, fronted, then ${i} \u2192 ${n.symbol} on destination`}}throw new De("ROUTE_STRATEGY_ERROR",`No viable cross-chain route found from ${t.symbol} (chain ${o}) to ${n.symbol} (chain ${r}). No intermediary asset is available on both chains.`,{sourceAsset:t.symbol,outputAsset:n.symbol,sourceChainId:o,destinationChainId:r,candidatesChecked:s})}async function Gr(e){const{route:t,sourceAmount:n,userAddress:o,registry:r,actionCalls:s,slippage:i}=e;async function c(d,l,p,u){const f=r.getVenueForChain(d);if(!f)throw new De("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${d}. Cannot resolve swap ${l} \u2192 ${p}.`,{chainId:d,tokenIn:l,tokenOut:p,amountIn:u.toString()});const m=await f.resolve({type:"swap",tokenIn:l,tokenOut:p,amountIn:u,maxSlippage:i},d,o);if(!m)throw new De("NO_LIQUIDITY",`${f.name} returned no quote for ${l} \u2192 ${p} on chain ${d}. No liquidity available for this pair.`,{venue:f.name,chainId:d,tokenIn:l,tokenOut:p,amountIn:u.toString()});return m}switch(t.strategy){case"direct":{const d=Pn(t.sourceAsset.address,t.destinationChainId,t.sourceChainId)||t.sourceAsset;if(Kr(d.address).has(t.outputAsset.address.toLowerCase()))return{chainBatches:[{chainId:t.destinationChainId,calls:s}],solverFrontToken:d,solverFrontAmount:n,resolvedSwaps:{}};const l=await c(t.destinationChainId,d.address,t.outputAsset.address,n);return{chainBatches:[{chainId:t.destinationChainId,calls:[...l.calls,...s]}],solverFrontToken:d,solverFrontAmount:n,resolvedSwaps:{destinationSwap:l}}}case"source-swap":{const d=Pn(t.outputAsset.address,t.sourceChainId,t.destinationChainId);if(!d)throw new De("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 l=Pn(t.outputAsset.address,t.destinationChainId,t.destinationChainId);if(!l)throw new De("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 c(t.sourceChainId,t.sourceAsset.address,d.address,n);return{chainBatches:[{chainId:t.sourceChainId,calls:p.calls},{chainId:t.destinationChainId,calls:s}],solverFrontToken:l,solverFrontAmount:p.amountOutMinimum,resolvedSwaps:{sourceSwap:p}}}case"intermediary":{if(!t.intermediaryAsset)throw new De("ROUTE_STRATEGY_ERROR","Intermediary strategy requires an intermediary asset but none was provided in the route plan.",{strategy:t.strategy});const d=Pn(t.intermediaryAsset.address,t.sourceChainId,t.destinationChainId);if(!d)throw new De("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 l=await c(t.sourceChainId,t.sourceAsset.address,d.address,n),p=await c(t.destinationChainId,t.intermediaryAsset.address,t.outputAsset.address,l.amountOutMinimum);return{chainBatches:[{chainId:t.sourceChainId,calls:l.calls},{chainId:t.destinationChainId,calls:[...p.calls,...s]}],solverFrontToken:t.intermediaryAsset,solverFrontAmount:l.amountOutMinimum,resolvedSwaps:{sourceSwap:l,destinationSwap:p}}}default:throw new De("ROUTE_STRATEGY_ERROR",`Unknown route strategy: ${t.strategy}`,{strategy:t.strategy})}}const Zl=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,styles:o,onWithdrawExecute:r,withdrawActionLabel:s,onWithdrawSuccess:i,onWithdrawError:c,autoCloseDelay:d,availableTokens:l,buildSpicenetBatch:p})=>{const u=Jt(zt);if(!u)return a("div",{children:"Error: SpiceWithdraw must be used within SpiceFlowProvider"});const f=u.mode||"7702",m=f==="presign"||f==="ondemand",h=u.supportedChainIds,y=u.allowedTokens,C=u.isWhitelistGateActive,v=!0,{theme:b,dark:x,dk:k}=it(o),w=u.network,A=()=>m?"select":"provider-login",[S,B]=M(A()),[E,I]=M(!1),[F,R]=M(null),[T,N]=M(null),[z,W]=M(""),[H,D]=M(!1),[L,Q]=M(!1),[V,O]=M(!1),[K,ue]=M(!1),[U,_]=M(""),[xe,Ae]=M(!0),me=ie(null),be=ie(null),ge=ie(null),j=ie(null),[re,Z]=M(null),[de,we]=M(null),[Ee,G]=M(null),Y=An(),{isReady:ae,isAuthenticated:ke,address:Qe}=Y,bt=Sn(),{address:nt,chainId:ot}=ho(),[oe,le]=M(!1),[st,X]=M(null),[Ue,St]=M(null),Ht=ie(null),gt=ie(!0);J(()=>(gt.current=!0,()=>{gt.current=!1}),[]);const{executeGasless:rn,estimateGasless:$t}=qo(),[Rt,Fe]=M(null),[_t,Cn]=M(null),[kn,Wt]=M(!1),[an,rt]=M(null),{assets:jt,loading:Ke}=vo({address:bt,enabled:e&&!!bt,refetchInterval:3e4}),ct=se(()=>{if(C)return[];if(!y||y.length===0)return jt;const ee=new Set(y.map(ne=>ne.toLowerCase()));return(jt||[]).filter(ne=>[ne.symbol,ne.displaySymbol,ne.receiptTokenName].some(Se=>typeof Se=="string"&&ee.has(Se.toLowerCase())))},[jt,y,C]),dt=se(()=>[...new Set([...h??[],...Object.keys(l??{}).map(Number),...(ct||[]).map(ee=>ee.chainId),...(ct||[]).flatMap(ee=>Object.keys(ee.chainTokens??{}).map(ne=>{const[,Se]=ne.split(":"),Ze=Number(Se);return Number.isFinite(Ze)?Ze:null}).filter(ne=>ne!==null))])].filter(ee=>Re(ee)?.network===w),[h,l,ct,w]),Et=se(()=>{if(l)return l;const ee={};for(const ne of ct||[]){const Se=Object.entries(ne.chainTokens??{});if(Se.length>0){for(const[Ze,_e]of Se){const[Ge,Xe,q]=Ze.split(":");if(Ge!=="evm"||!Xe||!q)continue;const pe=Number(Xe);if(!Number.isFinite(pe))continue;const Je=q.startsWith("0x")?q.toLowerCase():`0x${q.toLowerCase()}`,Ie=Re(pe)?.supportedTokens?.find(Be=>Te(Be.address,Je));Ie&&Ss(ne,Je,pe)&&(ee[pe]||(ee[pe]=[]),ee[pe].find(Be=>Te(Be.address,Je))||ee[pe].push({address:Je,symbol:Ie?.symbol||_e?.name||ne.symbol,name:Ie?.name||_e?.name||ne.displayName||ne.name||ne.symbol,decimals:Ie?.decimals??_e?.decimals??ne.decimals,logoURI:Ie?.logo||ne.logoURI}))}continue}ee[ne.chainId]||(ee[ne.chainId]=[]),ee[ne.chainId].find(Ze=>Te(Ze.address,ne.address))||ee[ne.chainId].push({address:ne.address,symbol:ne.symbol,name:ne.displayName||ne.name||ne.symbol,decimals:ne.decimals,logoURI:ne.logoURI})}return ee},[l,ct]),qt=ce((ee,ne)=>{if(!ee||!ne)return null;const Se=Lo(ee,ne),Ze=Object.entries(ee.chainTokens??{}).flatMap(([Ie,Be])=>{const Oe=io(Ie);return Oe?.chainId===ne?[{parsed:Oe,detail:Be}]:[]}),_e=Et?.[ne]||[],Ge=Ie=>_e.find(Be=>Te(Be.address,Ie))??null,Xe=Ie=>{const Be=Re(ne)?.supportedTokens?.find(Bt=>Te(Bt.address,Ie));if(!Be||!Ss(ee,Ie,ne))return null;const Oe=Ze.find(({parsed:Bt})=>Te(Bt.address,Ie));return Oe?{address:Oe.parsed.address,symbol:Be.symbol,name:Be.name||Oe.detail?.name||ee.displayName||ee.name||ee.symbol,decimals:Be.decimals,logoURI:Be.logo||ee.logoURI}:null};for(const Ie of Se){const Be=Ge(Ie);if(Be)return Be;const Oe=Xe(Ie);if(Oe)return Oe}const q=En(ee,ne);if(q){const Ie=Ge(q);if(Ie)return Ie;const Be=Xe(q);if(Be)return Be}const pe=Pn(ee.address,ne,ee.chainId);return pe?Ge(pe.address)||(_e.length>0?null:{address:pe.address,symbol:pe.symbol||ee.symbol,name:ee.displayName||ee.name||ee.symbol,decimals:pe.decimals??ee.decimals,logoURI:ee.logoURI}):null},[Et]),ye=se(()=>{if(!F)return null;const ee=F.receiptTokenId||`${F.chainId}:${F.address.toLowerCase()}`;return ct.find(ne=>(ne.receiptTokenId||`${ne.chainId}:${ne.address.toLowerCase()}`)===ee)||F},[F,ct]),yt=se(()=>{if(!ye)return[];const ee=Object.keys(ye.chainTokens??{}).map(ne=>io(ne)?.chainId??null).filter(ne=>ne!==null);return Array.from(new Set([...ee,ye.chainId,...dt].filter(Number.isFinite))).filter(ne=>ne!==1&&Re(ne)?.network===w&&qt(ye,ne)!==null)},[ye,dt,qt,w]),Ft=se(()=>{if(!ye||typeof window>"u")return null;const ee=`spiceflow:withdraw-chain:${ye.receiptTokenId||ye.address.toLowerCase()}`,ne=window.localStorage.getItem(ee),Se=ne?Number(ne):null;return Se!==null&&Number.isFinite(Se)&&yt.includes(Se)?Se:null},[ye,yt]),Yt=se(()=>ye?Ft!==null?Ft:ot&&yt.includes(ot)?ot:ye.chainId&&yt.includes(ye.chainId)?ye.chainId:yt[0]??dt[0]??null:dt[0]??null,[ye,Ft,ot,yt,dt]),Ce=se(()=>qt(ye,T),[qt,ye,T]);J(()=>{!ct?.length||ye||R(ct[0])},[v,ct,ye]),J(()=>{!ye||(T===null||!yt.includes(T))&&N(Yt)},[v,ye,T,Yt,yt]),J(()=>{if(!H&&!L&&!V)return;const ee=ne=>{const Se=ne.target;H&&!me.current?.contains(Se)&&!be.current?.contains(Se)&&!Se?.closest?.("[data-network-popover]")&&D(!1),L&&!ge.current?.contains(Se)&&!Se?.closest?.("[data-token-popover]")&&Q(!1),V&&!j.current?.contains(Se)&&!Se?.closest?.("[data-balance-trigger]")&&O(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[H,L,V]);const Kt=ce(ee=>{if(!ee||yt.length<=1)return;const ne=ee.getBoundingClientRect(),Se=220,Ze=16;Z({top:ne.bottom+8,left:Math.min(Math.max(Ze,ne.right-Se),window.innerWidth-Se-Ze)}),D(_e=>!_e)},[yt.length]);J(()=>{if(!ye||T===null||typeof window>"u")return;const ee=`spiceflow:withdraw-chain:${ye.receiptTokenId||ye.address.toLowerCase()}`;window.localStorage.setItem(ee,String(T))},[ye,T]);const ut=K&&U&&bn(U)?U:nt||bt,kt=ye?.balanceFormatted??0,Zt=ce(ee=>{if(!ee)return;const ne=ee.getBoundingClientRect();G({top:ne.bottom+8,left:ne.right-220}),O(!0)},[]),vn=ye?.displaySymbol||ye?.receiptTokenName||ye?.symbol||"spiceUSDC",ln=ye?.displayChainName||"Spicenet",xt=ds,cn=ds,ze=ye?.receiptTokenDecimals??ye?.decimals,Ve=se(()=>{if(!Ce||!ze)return 0n;try{return je(z||"0",ze)}catch{return 0n}},[z,Ce,ze]),Qt=se(()=>!Ce||!ze?0n:jr(Ve,ze,Ce.decimals),[Ce,ze,Ve]),Nt=se(()=>{const ee=_t??Rt;return!ee||ee<=0n||!Ce||!ze?0n:jr(ee,Ce.decimals,ze)},[_t,Rt,Ce,ze]),Ye=se(()=>Ve+Nt,[Ve,Nt]),pt=_t??Rt,wt=ce(ee=>{if(!T||!Ce)return[];if(Ve===0n||Qt===0n||!ut)return[];const ne=Array.isArray(ee)?ee.filter(Ge=>Ge.amount>0n):[{token:Ce.address,recipient:ut,amount:ee??Qt}],Se=ne.reduce((Ge,Xe)=>Ge+Xe.amount,0n);if(Se<=0n)return[];const Ze={chainId:T,calls:[],tokenTransfers:ne.map(Ge=>({from:"escrow",to:Ge.recipient,token:Ge.token,amount:Ge.amount}))};if(!p)return[Ze];const _e=p({destinationChainId:T,deliveryToken:Ce.address,deliveryAmount:Se,deliveryRecipient:ut,deliveryTransfers:ne});return _e?[_e,Ze]:[Ze]},[v,T,Ce,Ve,Qt,ut,p]),ft=se(()=>wt(),[wt]),at=se(()=>Pl(ft,Ce?.address),[ft,Ce?.address]),Pt=ie(null),ht=ie(0);J(()=>{let ee=!1;if(!e||m||oe||!Ce||Ve===0n){Pt.current=null,Fe(null),rt(null),Wt(!1);return}if(ft.length===0){Pt.current=null,Fe(null),Wt(!0);return}if(!at){Pt.current=null,Fe(null),rt(null),Wt(!1);return}if(Pt.current===at)return;Pt.current=at;const ne=++ht.current;return(async()=>{Wt(!0),rt(null);try{const Se=await Ql({batches:ft,tokenAddress:Ce.address,estimateGasless:$t});if(ee||ne!==ht.current)return;Fe(Se)}catch(Se){if(ee||ne!==ht.current)return;Pt.current=null,Fe(null),rt(Se instanceof Error?Se.message:"Failed to estimate gas fee")}finally{!ee&&ne===ht.current&&Wt(!1)}})(),()=>{ee=!0}},[e,m,oe,Ce,$t,Ve,ft,at]),J(()=>{oe||Cn(null)},[oe,z,T,Ce?.address]);const dn=ce(()=>{I(!0),B("select")},[v]),Le=ce(()=>{t()},[t]),mn=ie(null);mn.current={batches:ft,walletAddress:Qe,recipient:ut,token:Ce,chainId:T,amount:z,receiveAmountRaw:Qt,gasFee:Rt,isNon7702:m,buildWithdrawBatches:wt,gasless:{estimateGasless:$t,executeGasless:rn},ui:{setIsExecuting:le,setExecutionError:X,setExecutionProgress:St,setLockedGasFee:Cn},executionContextRef:Ht,isMountedRef:gt,onWithdrawExecute:r,onWithdrawSuccess:i,onWithdrawError:c,buildSpicenetBatch:p};const Gt=ce(()=>Vr(mn.current),[]),Mt=ce(()=>jl(mn.current),[]);if(J(()=>{if(!e){const ee=setTimeout(()=>{B(A()),I(!1),R(null),N(null),W(""),D(!1),Q(!1),ue(!1),_(""),le(!1),X(null),St(null),Ht.current=null},300);return()=>clearTimeout(ee)}},[e,m]),J(()=>{if(!m&&e&&S==="provider-login"&&ae&&ke&&bt&&!E){const ee=setTimeout(()=>{I(!0),B("select")},100);return()=>clearTimeout(ee)}},[m,e,S,ae,ke,bt,E,v]),!e)return null;if(S==="provider-login"&&!m)return a(vs,{onAuthSuccess:dn,autoTrigger:!0});if(S==="select"&&v){const ee=parseFloat(z)||0,ne=ze?Rs(Ye,ze):z||"0",Se=parseFloat(ne)||0,Ze=Se>0&&Se>kt,_e=(T?Re(T):null)?.displayName||"Network",Ge=T?Mn[T]||xo:null,Xe=Ce?.symbol||"\u2014",q=vn,pe=Ce?Rs(Qt,Ce.decimals):"0",Je=Qr(ee,Ce?.symbol||ye?.symbol),Ie=Qr(parseFloat(pe)||0,Ce?.symbol||ye?.symbol),Be=!K||!U||bn(U),Oe=!m&&ee>0&&Ce!==null,Bt=!Oe||Rt!==null&&!kn&&!an,Dt=ee>0&&!Ze&&F!==null&&T!==null&&Ce!==null&&ut&&Be&&Bt&&Qt>0n,Ct=!Dt,P=F===null?"NO BALANCE":ee===0?"ENTER AMOUNT":Ze?"INSUFFICIENT BALANCE":Oe&&!Bt?an?"GAS UNAVAILABLE":"ESTIMATING GAS":Oe&&Qt===0n?"AMOUNT TOO SMALL":"WITHDRAW",$=!!Ue&&(Ue.step==="success"||Ue.step==="error"),fe=g("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[a("img",{src:ks,alt:"","aria-hidden":"true",style:{width:"13px",height:"13px",flexShrink:0,...x?{filter:"invert(0.6)"}:{}}}),a("p",{style:{fontSize:"13px",color:x?k.textSecondary:"#979AA0",margin:"0",lineHeight:"1.4",fontFamily:'"Helvetica Neue", sans-serif'},children:"Withdraw collateral from your account to 10+ EVM blockchains."})]}),te='"Helvetica Neue", sans-serif',Ne='"IBM Plex Mono", monospace',Me=o?.primaryColor||b.colors.primary,et=x?k.cardBg:"#E9E9E9",en=x?k.cardBorder:"#C6C6C6",un=x?k.textSecondary:"#7D7C7B",Ut=x?k.textSecondary:"#71757A",vt=x?k.textPrimary:"#0E0D0B",pn=x?k.cardBorder:"#C5C5C4",Un=x?"rgba(255,255,255,0.08)":"#D4D3D3",Qn=170,co=q.length>8?"14px":q.length>6?"16px":"18px",Vn=Xe.length>8?"14px":Xe.length>6?"16px":"18px";return a(Rn,{isOpen:!0,onClose:Le,title:"Withdraw",subtitle:fe,styles:o,theme:b,dark:x,maxWidth:"486px",footerLinkText:"Spicenet accounts \u2192",overlayDimmed:!1,closeOnBackdropClick:n,overlayContent:$?a("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("div",{style:{pointerEvents:"auto"},children:a(Is,{type:"withdraw",isOpen:!0,isProcessing:oe,onRetryTx:()=>{Mt()},onNewTx:()=>{St(null),W(""),X(null),Ht.current=null},onClose:()=>{St(null),X(null),le(!1),Ht.current=null},onComplete:()=>{St(null),X(null),le(!1),Ht.current=null},results:[{asset:{symbol:Ce?.symbol||"Token",address:Ce?.address||""},txHash:Ue?.txHash||"",success:Ue?.step==="success",error:Ue?.error,amount:z}],chainName:T?tn(T):"Network",explorerUrl:T?_n(T,"").replace(/\/tx\/.*$/,""):void 0,theme:b})})}):null,children:g("div",{style:{width:"402px",margin:"0 auto",padding:"0 0 4px 0",position:"relative"},children:[a(Vl,{show:V,position:Ee,popoverRef:j,spiceAssets:ct,dark:x,dk:k}),g("div",{style:{marginTop:"16px",marginBottom:"16px",display:"flex",flexDirection:"column",gap:"16px"},children:[g("div",{style:{backgroundColor:et,border:`1px solid ${en}`,borderRadius:"7px",padding:"14px 16px 12px 16px",minHeight:"138px",display:"flex",flexDirection:"column",gap:"6px",position:"relative"},children:[g("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[a("span",{style:{fontFamily:te,fontSize:"17px",fontWeight:500,color:un,lineHeight:"24px"},children:"Source"}),g("div",{style:{display:"flex",alignItems:"center",gap:"6px",fontFamily:te,fontSize:"13px",fontWeight:500,color:Ut,lineHeight:"16px"},children:["Balance:"," ",Ke?"...":On(kt),a("button",{type:"button","data-balance-trigger":!0,onClick:ve=>{ve.stopPropagation(),Zt(ve.currentTarget)},style:{width:"15px",height:"15px",borderRadius:"999px",border:"1px solid #EA4B4B",color:"#EA4B4B",display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:"9px",fontWeight:500,lineHeight:1,boxSizing:"border-box",background:"transparent",padding:0,cursor:"pointer"},children:a("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"1.5px"},children:[0,1,2].map(ve=>a("span",{style:{width:"1.75px",height:"1.75px",borderRadius:"999px",backgroundColor:"#EA4B4B",display:"block"}},ve))})})]})]}),g("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[g("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[a(Gn,{element:"input",ariaLabel:"Withdraw amount",ariaInvalid:Ze,dataSpiceflowFocus:!0,value:z,onChange:ve=>{const he=ve.target.value;if(he===""){W("");return}/^\d*\.?\d*$/.test(he)&&W(no(he.startsWith(".")?`0${he}`:he,ze??F?.decimals))},placeholder:"0.0",fontFamily:te,color:Ze?"#ef4444":z?vt:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,style:{width:"100%"}}),a("div",{style:{fontSize:"12px",fontWeight:500,color:Ut,fontFamily:te,marginTop:"10px"},children:Je})]}),a("div",{style:{width:`${Qn}px`,flexShrink:0},children:g("div",{style:{backgroundColor:"transparent",border:`1px solid ${pn}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[g("div",{ref:ge,onClick:ve=>{if(ve.stopPropagation(),!L&&ge.current){const he=ge.current.getBoundingClientRect(),He=220,Xt=16;we({top:he.bottom+8,left:Math.min(Math.max(Xt,he.right-He),window.innerWidth-He-Xt)})}Q(he=>!he)},style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px",cursor:"pointer"},children:[a("img",{src:xt,alt:q,style:{width:"24px",height:"24px",borderRadius:"50%"}}),a("span",{style:{fontSize:co,fontWeight:500,color:vt,lineHeight:"1.3",fontFamily:te,flex:1,minWidth:0,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",letterSpacing:0},children:q}),a(Dn,{size:15,color:vt,strokeWidth:2.25})]}),a(Ar,{isOpen:L,position:de,title:"SELECT TOKEN",portalAttribute:"token",items:(ct||[]).map(ve=>({id:ve.receiptTokenId||ve.address,label:ve.displaySymbol||ve.receiptTokenName||ve.symbol,icon:ds,detail:On(ve.balanceFormatted)})),selectedId:ye?.receiptTokenId||ye?.address||null,onSelect:ve=>{const he=(ct||[]).find(He=>(He.receiptTokenId||He.address)===ve);he&&(R(he),W("")),Q(!1)}}),a("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:Un,borderTop:`1px solid ${pn}`},children:a("span",{style:{fontSize:"11px",fontWeight:400,color:vt,fontFamily:te,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:ln})})]})})]}),g("div",{style:{minHeight:"18px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[Ze?a("span",{style:{fontSize:"12px",color:k.errorText,fontFamily:te,fontWeight:500},children:"Insufficient Balance"}):a("span",{}),a("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0px",minHeight:"32px",marginRight:"-9px"},children:[0,25,50,75,100].map((ve,he)=>{const He=he===4,Xt=ve/100,In=parseFloat(z)||0,gn=kt>0&&Math.abs(In/kt*100-ve)<1;return a("button",{type:"button","aria-label":`Set amount to ${ve}%`,"aria-pressed":gn,onClick:()=>{const uo=kt*ve/100,qn=F?.decimals??6,po=Math.floor(uo*10**qn)/10**qn;W(ve===0?"":po>0?oo(po,qn):"")},title:`${ve}%`,disabled:kt===0,"data-spiceflow-focus":!0,style:{width:"32px",height:"32px",padding:"9px",border:"none",backgroundColor:"transparent",cursor:kt===0?"not-allowed":"pointer",opacity:gn?1:.5,transition:"opacity 0.15s ease",display:"flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box"},children:g("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[a("circle",{cx:"7",cy:"7",r:"6.84375",fill:He?Me:"none",stroke:He?Me:x?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!He&&Xt>0&&a("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${Xt>.5?1:0} 1 ${7+6.84375*Math.sin(Xt*2*Math.PI)} ${7-6.84375*Math.cos(Xt*2*Math.PI)} Z`,fill:x?k.textSecondary:"#3C3E42"})]})},ve)})})]})]}),g("div",{style:{backgroundColor:et,border:`1px solid ${en}`,borderRadius:"7px",padding:"14px 16px 12px 16px",minHeight:"138px",display:"flex",flexDirection:"column",gap:"6px"},children:[g("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[a("span",{style:{fontFamily:te,fontSize:"17px",fontWeight:500,color:un,lineHeight:"24px"},children:"Destination"}),g("div",{style:{display:"flex",alignItems:"center",gap:"6px",fontFamily:te,fontSize:"13px",fontWeight:500,color:Ut,lineHeight:"16px"},children:["Balance:"," ",Ke?"...":On(kt),a("button",{type:"button","data-balance-trigger":!0,onClick:ve=>{ve.stopPropagation(),Zt(ve.currentTarget)},style:{width:"15px",height:"15px",borderRadius:"999px",border:"1px solid #EA4B4B",color:"#EA4B4B",display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:"9px",fontWeight:500,lineHeight:1,boxSizing:"border-box",background:"transparent",padding:0,cursor:"pointer"},children:a("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"1.5px"},children:[0,1,2].map(ve=>a("span",{style:{width:"1.75px",height:"1.75px",borderRadius:"999px",backgroundColor:"#EA4B4B",display:"block"}},ve))})})]})]}),g("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[g("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[a(Gn,{element:"div",value:pe,title:pe,fontFamily:te,color:z?vt:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,overflow:"wrap"}),a("div",{style:{fontSize:"12px",fontWeight:500,color:Ut,fontFamily:te,marginTop:"10px"},children:Ie})]}),g("div",{style:{width:`${Qn}px`,flexShrink:0,display:"flex",flexDirection:"column",alignItems:"stretch",gap:"8px"},children:[g("div",{style:{backgroundColor:"transparent",border:`1px solid ${pn}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px"},children:[a("img",{src:Ce?.logoURI||bo,alt:Xe,style:{width:"24px",height:"24px",borderRadius:"50%"}}),a("span",{style:{fontSize:Vn,fontWeight:500,color:vt,lineHeight:"1.3",fontFamily:te,flex:1,minWidth:0,letterSpacing:0},children:Xe})]}),g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:Un,borderTop:`1px solid ${pn}`},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[Ge&&a("img",{src:Ge,alt:_e,style:{width:"13px",height:"13px",borderRadius:"50%",flexShrink:0}}),a("span",{style:{fontSize:"11px",fontWeight:400,color:vt,fontFamily:te,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:_e})]}),a("button",{ref:me,onClick:ve=>{ve.stopPropagation(),Kt(me.current)},style:{background:"none",border:"none",cursor:yt.length>1?"pointer":"not-allowed",padding:"0 0 0 8px",fontSize:"9.5px",fontFamily:Ne,color:Ut,textDecoration:"underline",fontWeight:600,opacity:yt.length>1?1:.45},children:"Switch"}),a(Ar,{isOpen:H,position:re,title:"SELECT NETWORK",portalAttribute:"network",items:yt.map(ve=>{const he=Re(ve);return{id:String(ve),label:he?.displayName||String(ve),icon:Mn[ve]||xo}}),selectedId:T!==null?String(T):null,onSelect:ve=>{N(Number(ve)),D(!1)}})]})]}),a("div",{style:{minHeight:"14px"}})]})]})]})]}),g("div",{style:{marginBottom:b.spacing.sm},children:[a(Yl,{show:xe,onToggle:()=>Ae(ve=>!ve),showCustomAddress:K,setShowCustomAddress:ue,customRecipient:U,setCustomRecipient:_,externalAddress:nt,recipientAddress:ut,destChainName:_e,destChainLogo:Ge,compatibleDestinationChains:yt,txDetailsChainSwitchRef:be,onOpenNetworkPopover:Kt,sourceChainLabel:ln,sourceDetailsLogo:cn,sourceTokenLabel:q,amount:z,totalSourceDebitDisplay:ne,receiveAmountDisplay:pe,destTokenSymbol:Xe,shouldQuoteWithdrawGas:Oe,estimatingFee:kn,feeError:an,displayedGasFee:pt,selectedDestToken:Ce,theme:b,styles:o,dark:x,dk:k}),st&&a(ro,{variant:"error",size:"compact",palette:k,fontFamily:o?.fontFamily||b.typography.fontFamily,style:{marginBottom:"12px"},children:st}),a(It,{variant:"outline",fullWidth:!0,onClick:()=>{Dt&&Gt()},disabled:Ct||oe,theme:b,dark:x,styles:o,style:{marginTop:"8px"},children:oe?"EXECUTING...":P})]})]})})}return null},Xr=Zl;var Gl="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAKlBMVEVMaXHpSkrmS0vrSkrmR0fpSkrrSkroSUnqSkrpSkrpSkrpSkrsS0vzTk68N2lZAAAADHRSTlMA/SoEHOX1RcdliKnuQ9TkAAAACXBIWXMAAAsTAAALEwEAmpwYAAAB4UlEQVR42u1XyRbDIAhUcQ/8/+9WUROzNIvtMbxefMo4yACpEOcG4geD30G0C07B8P0qWkzm3QgJEBAsIUqURJMe8NcToZTlR8YJgGev5wwVd2QEG+FZGIl+9iUyloGQvL5NIt2V6RfqoCPRHMZN/0ofy+NBKEsO41b4wVaHADWdvgGqGyR0o5/Tvw/pmr7v6C/XhRbVaTYqfU5bgPVGDUNmYDgXT6UP28xEvAyjpw/H2pD5wGE2ivZZPGv6fXF5JlhEdfr68AUB4vdsqHP6DWPWyDYbITsz/asecXDR+vXPtZbOdmG0o7324dJYVFypLRu6+ptws9aV53glhUIqMCDaqNxdKwjkoQDkzpkAjL1vWwCJA1YBUgpRjlkDULl9jxjFudjHbBkXWg3ZT4N3q9AkMOXUrMM0VZ3oVJk3QXSbvNi0CzNXUimZ2LeatBl7Ie57CiQ9k9EVYEripKVYwJMlq+qKN3eyVzaLu/pArtl0pgFok6XS1j6fjI8BUDZGvPkCvAAvwJdiuipnuZRzJL5q93li0M53pp6Bq4bicZnb2kuMh/8Num9ycOsP9NUalBJ/trG2rmH5/Boabji1FxsbbFhzmaezHAPANlxxcDwvwzWNZ3ps2P0X02MG4rX/2Ad4/i9F5OK4gwAAAABJRU5ErkJggg==";const Ao=e=>{const t=Math.round(e*1e5)/1e5;return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:5}).format(t)},Jr=e=>{const t=Math.round(e*1e5)/1e5;return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:5}).format(t)},Xl=({balanceData:e,isLoading:t=!1,styles:n,className:o="",showHeader:r=!0,onAccountClick:s,onDepositClick:i,onWithdrawClick:c,vaultBalance:d,fetchVaultBalance:l,onWithdrawExecute:p,withdrawActionLabel:u,destinationChainId:f,destinationTokenAddress:m,customSections:h,showDefaultSections:y=!0})=>{const C=Jt(zt),v=(C?.mode||"7702")!=="7702",b=C?.appName||"Spicenet",{dark:x,primaryColor:k,dk:w,theme:A}=it(n),[S,B]=M(!0),[E,I]=M(!1),[F,R]=M(!1),[T,N]=M(null),{isConnected:z}=ho(),{disconnect:W}=Gs();J(()=>{v&&l&&l().then(O=>{const K=Math.round(O*1e5)/1e5;N(K)}).catch(O=>{console.error("Error fetching vault balance:",O),N(null)})},[v,l]);const H=()=>{B(!S)},D=se(()=>{if(!e.freeCollateralItems)return null;const O=e.freeCollateralItems.filter(U=>U.name==="USDC");if(O.length===0)return null;const K=O.reduce((U,_)=>U+_.balance,0),ue=[];return O.forEach(U=>{U.networks&&U.networks.forEach(_=>{(_===1||_===11155111||_===8453||_===84532)&&(ue.includes(_)||ue.push(_))})}),ue.length===0&&ue.push(1,8453),{name:"USDC",totalBalance:K,networks:ue,subtitle:O[0]?.subtitle||"USD COIN"}},[e.freeCollateralItems]),L=se(()=>{if(v){if(T!==null)return T;if(d!=null)return d}return e.freeCollateralItems?e.freeCollateralItems.reduce((O,K)=>O+K.balance,0):e.freeCollateral},[v,T,d,e.freeCollateralItems,e.freeCollateral]),Q=O=>S?O:"******",V=()=>{W(),I(!1),R(!1)};return g("div",{className:o,style:{borderRadius:"16px",backgroundColor:x?w.shell:"#D5D5D5",width:"522px",padding:"8px",fontFamily:n?.fontFamily||'"Helvetica Neue", sans-serif',...n?.container},children:[g("div",{style:{background:x?w.cardBg:" white",display:"flex",flexDirection:"column"},children:[g("div",{style:{backgroundColor:x?w.inputBg:"#E9E9E9",borderRadius:"0 0 16px 16px",padding:"20px",display:"flex",flexFlow:"column"},children:[g("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"4px"},children:[g("p",{style:{fontSize:"14px",fontWeight:500,fontFamily:'"IBM Plex Mono", monospace',color:x?w.textPrimary:"#0E0D0B",margin:0},children:[b.toUpperCase()," BALANCE"]}),z&&a("button",{onClick:V,"aria-label":"Disconnect wallet",style:{width:"36px",height:"36px",borderRadius:"8px",border:x?`1px solid ${k}33`:"1px solid #E5E7EB",background:x?w.inputBg:"white",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",transition:on.interactive,padding:"8px"},onMouseEnter:O=>{O.currentTarget.style.backgroundColor=x?w.cardBg:"#F3F4F6"},onMouseLeave:O=>{O.currentTarget.style.backgroundColor=x?w.inputBg:"white"},children:g("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),a("polyline",{points:"16 17 21 12 16 7"}),a("line",{x1:"21",y1:"12",x2:"9",y2:"12"})]})})]}),g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.percentageChange!==void 0&&e.percentageChange!==null&&g("div",{style:{fontSize:"13px",fontWeight:700,color:e.percentageChange>=0?x?w.successText:"#009C51":x?w.errorText:"#EF4444"},children:[e.percentageChange>=0?"+":"",e.percentageChange.toFixed(2),"%"]}),a("button",{onClick:H,style:{background:"none",border:"none",cursor:"pointer",padding:"8px",display:"flex",alignItems:"center",justifyContent:"center",transition:"opacity 0.2s ease"},onMouseEnter:O=>{O.currentTarget.style.opacity="0.7"},onMouseLeave:O=>{O.currentTarget.style.opacity="1"},children:S?g("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",children:[a("path",{d:"M12 5C7 5 2.73 8.11 1 12.5C2.73 16.89 7 20 12 20C17 20 21.27 16.89 23 12.5C21.27 8.11 17 5 12 5Z",stroke:x?w.textSecondary:"#1A1A1A",strokeWidth:"2",fill:"none"}),a("circle",{cx:"12",cy:"12.5",r:"3",stroke:x?w.textSecondary:"#1A1A1A",strokeWidth:"2",fill:"none"})]}):g("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",children:[a("path",{d:"M12 5C7 5 2.73 8.11 1 12.5C2.73 16.89 7 20 12 20C17 20 21.27 16.89 23 12.5C21.27 8.11 17 5 12 5Z",stroke:x?w.textSecondary:"#1A1A1A",strokeWidth:"2",fill:"none"}),a("path",{d:"M3 3L21 21",stroke:x?w.textSecondary:"#1A1A1A",strokeWidth:"2",strokeLinecap:"round"})]})})]}),a("p",{style:{fontSize:"40px",fontWeight:700,color:x?w.textPrimary:"black"},children:Q(Ao(v&&T!==null?T:v&&d!==void 0&&d!==null?d:e.totalBalance))}),g("div",{style:{display:"flex",gap:"12px",marginTop:"16px"},children:[a(It,{variant:"outline",fullWidth:!0,onClick:()=>{i?i():I(!0)},theme:A,dark:x,styles:n,children:"DEPOSIT"}),a(It,{variant:"outline",fullWidth:!0,onClick:()=>{c?c():R(!0)},theme:A,dark:x,styles:n,children:"WITHDRAW"})]})]}),g("div",{style:{background:x?w.cardBg:"white",padding:"12px 20px",borderRadius:"12px"},children:[y&&a(Ir,{title:"FREE COLLATERAL",icon:Gl,amount:Q(Jr(L)),defaultExpanded:!1,children:v&&(T!==null||d!=null)?a(Uo,{name:"USDC",balance:Q(Ao(T!==null?T:d)),subtitle:"USD COIN",icon:bo,onClick:s?()=>s("usdc-vault"):void 0}):D?a(Uo,{name:D.name,balance:Q(Ao(D.totalBalance)),subtitle:D.subtitle,networks:D.networks,icon:bo,onClick:s?()=>s(D.name):void 0}):e.freeCollateralItems&&e.freeCollateralItems.length>0?e.freeCollateralItems.map((O,K)=>g(hn.Fragment,{children:[a(Uo,{name:O.name,balance:Q(Ao(O.balance)),subtitle:O.subtitle,networks:O.networks,icon:O.name==="USDC"?bo:void 0,onClick:s?()=>s(O.id):void 0}),K<e.freeCollateralItems.length-1&&a("div",{style:{height:"1px",backgroundColor:x?w.cardBorder:"#D0D2D8",margin:"4px 0"}})]},O.id)):a("div",{style:{padding:"12px 0",color:x?w.textSecondary:"#6B7280",fontSize:"13px",fontFamily:'"IBM Plex Mono", monospace'},children:"No collateral items available"})}),h&&h.length>0&&h.filter(O=>O&&O.id&&O.title&&typeof O.title=="string"&&O.title.trim().length>0).map(O=>a(Ir,{title:O.title,icon:O.icon||void 0,amount:Q(Jr(O.totalBalance||0)),defaultExpanded:O.defaultExpanded!==void 0?O.defaultExpanded:!1,children:O.items&&O.items.length>0?O.items.map((K,ue)=>g(hn.Fragment,{children:[a(Uo,{name:K.name,balance:Q(Ao(K.balance)),subtitle:K.subtitle,networks:K.networks,icon:K.name==="USDC"?bo:void 0,onClick:s?()=>s(K.id):void 0}),ue<O.items.length-1&&a("div",{style:{height:"1px",backgroundColor:x?w.cardBorder:"#D0D2D8",margin:"4px 0"}})]},K.id||`item-${ue}`)):a("div",{style:{padding:"12px 0",color:x?w.textSecondary:"#6B7280",fontSize:"13px",fontFamily:'"IBM Plex Mono", monospace'},children:O.emptyMessage||"No items available"})},O.id))]})]}),E&&a(vr,{isOpen:E,onClose:()=>I(!1),styles:n}),F&&a(Xr,{isOpen:F,onClose:()=>R(!1),styles:n,onWithdrawExecute:p,withdrawActionLabel:u})]})},Jl=({options:e,selectedIndex:t,onSelect:n,primaryColor:o,dark:r=!1,textPrimary:s="#111827",textSecondary:i="#6b7280",trackColor:c})=>{const d=e.length-1,l=c||(r?"#3a3a3a":"#d1d5db"),p=r?"4px":"50%",u=r?"none":"2px solid white",f=r?"none":`0 0 0 1px ${o}`;return g("div",{style:{width:"100%",userSelect:"none"},children:[g("div",{style:{position:"relative",paddingBottom:"4px"},children:[a("div",{style:{position:"absolute",top:"50%",left:0,right:0,height:"4px",background:l,borderRadius:"2px",transform:"translateY(-50%)",pointerEvents:"none"}}),a("div",{style:{position:"absolute",top:"50%",left:0,width:`${t/d*100}%`,height:"4px",background:o,borderRadius:"2px",transform:"translateY(-50%)",pointerEvents:"none",transition:"width 0.15s ease"}}),a("input",{type:"range","aria-label":"Lock duration","aria-valuetext":e[t]?.label,"data-spiceflow-focus":!0,min:0,max:d,step:1,value:t,onChange:m=>n(Number(m.target.value)),style:{WebkitAppearance:"none",appearance:"none",width:"100%",height:"20px",background:"transparent",cursor:"pointer",outline:"none",border:"none",position:"relative",zIndex:1,margin:0,padding:0}})]}),a("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"6px"},children:e.map((m,h)=>g("div",{onClick:()=>n(h),style:{display:"flex",flexDirection:"column",alignItems:h===0?"flex-start":h===d?"flex-end":"center",cursor:"pointer",flex:1},children:[a("span",{style:{fontSize:"12px",fontWeight:h===t?700:400,color:h===t?s:i,whiteSpace:"nowrap",transition:"color 0.15s, font-weight 0.15s"},children:m.label}),m.highlight&&a("span",{style:{fontSize:"10px",color:i,whiteSpace:"nowrap"},children:"(most common)"})]},h))}),a("style",{children:`
66
+ `})]})},As=new Set(["WBTC","CBTC"]),Er=new Set(["btc","wbtc","wcbtc","cbtc"]);function Fr(e,t){return!e||!t?!1:e===t?!0:As.has(e)&&As.has(t)}function io(e){const[t,n,o]=e.split(":");if(t!=="evm"||!n||!o)return null;const r=Number(n);if(!Number.isFinite(r))return null;const s=o.startsWith("0x")?o.toLowerCase():`0x${o.toLowerCase()}`;return{chainId:r,address:s}}function zo(e){return(e??"").trim().replace(/^test\s+/i,"").replace(/^spice/i,"").toLowerCase().replace(/[^a-z0-9]/g,"")}function al(e){return new Set([e.receiptTokenName,e.displaySymbol,e.symbol,e.displayName,e.name].map(zo).filter(Boolean))}function il(e,t){const n=al(e),o=[t.symbol,t.name,t.equivalenceGroup].map(zo);if(o.some(i=>i&&n.has(i)))return!0;const r=[...n].some(i=>Er.has(i)),s=o.some(i=>Er.has(i))||As.has(t.equivalenceGroup??"");return r&&s}function Br(e,t,n){const o=new Set(t.map(zo).filter(Boolean)),r=s=>{if(n&&Te(s.address,n))return 0;const i=[s.symbol,s.name,s.equivalenceGroup].map(zo).findIndex(c=>c&&o.has(c));return i===-1?4:i+1};return[...e].sort((s,i)=>{const c=r(s)-r(i);return c!==0?c:s.address.toLowerCase().localeCompare(i.address.toLowerCase())})}const Tr=typeof process<"u"&&process.env?.NEXT_PUBLIC_MORALIS_API_KEY||typeof import.meta<"u"&&import.meta.env?.VITE_MORALIS_API_KEY||"",ll="https://deep-index.moralis.io/api/v2.2";function Lo(e,t){const n=e.chainTokens?Object.keys(e.chainTokens):[],o=[];for(const r of n){const s=io(r);if(!s||s.chainId!==t)continue;const i=s.address,c=Tt(i,t);c&&(!Ss(e,i,t)&&!(e.isUniversal&&il(e,c))||o.some(d=>Te(d,i))||o.push(i))}return Br(o.map(r=>{const s=Tt(r,t);return{address:r,symbol:s?.symbol,name:s?.name,equivalenceGroup:s?.equivalenceGroup}}),[e.receiptTokenName,e.displaySymbol,e.symbol,e.displayName,e.name],e.chainId===t&&!e.isUniversal?e.address:void 0).map(r=>r.address)}function Ss(e,t,n){return e.chainId===n&&Te(e.address,t)?!0:ko(e.address,e.chainId,t,n)}async function cl(e,t){const n=lt(e),o=xn(e);return Pe(t)?n.getBalance({address:o}):await n.readContract({address:t,abi:Vt,functionName:"balanceOf",args:[o]})}function Mr(e,t,n){const o=Js(n),r=o.find(i=>Te(i.address,e));if(r)return r;const s=Tt(e,t);if(s)return Br(o.filter(i=>Fr(i.equivalenceGroup,s.equivalenceGroup)),[s.symbol,s.name,s.equivalenceGroup])[0]}function En(e,t){if(e.chainId===t)return e.address;const n=Mr(e.address,e.chainId,t);return n?n.address:null}async function Rr(e,t,n={}){const o=En(e,t),r=Lo(e,t);if(r.length===0)return o;if(r.length===1)return r[0];const s=n.requiredAmount??0n,i=d=>{const l=r.map(p=>({candidate:p,balance:d.get(Pe(p)?"native":p.toLowerCase())??0n})).filter(p=>p.balance>0n).sort((p,u)=>p.balance===u.balance?0:p.balance>u.balance?-1:1);return l.length===0?null:((s>0n?l.find(p=>p.balance>=s):l[0])??l[0]).candidate},c=Yn()[t];if(c?.moralisName&&Tr){const d=new Map,l=r.some(p=>Pe(p));try{if(l)try{const u=lt(t),f=xn(t);d.set("native",await u.getBalance({address:f}))}catch{}const p=await fetch(`${ll}/wallets/${xn(t)}/tokens?chain=${c.moralisName}`,{headers:{"X-API-Key":Tr}});if(p.ok){const u=await p.json();for(const m of u?.result||[]){const h=String(m.token_address||"").toLowerCase();if(h)try{d.set(h,BigInt(String(m.balance||"0")))}catch{}}const f=i(d);if(f)return f}}catch{}}try{const d=await Promise.all(r.map(async u=>({key:Pe(u)?"native":u.toLowerCase(),value:await cl(t,u)}))),l=new Map(d.map(({key:u,value:f})=>[u,f])),p=i(l);if(p)return p}catch{}return o}function ko(e,t,n,o){const r=Tt(e,t),s=Tt(n,o);return r&&s?Fr(r.equivalenceGroup,s.equivalenceGroup):Va(e,n)}function Oo(e,t){return ko(e.address,e.chainId,t.address,t.chainId)}const dl={usdc:[8453,1,42161,5115,4114],usdt:[1],btc:[4114,42161,1,5115],wbtc:[1],weth:[8453,1],ctusd:[5115,4114],wcbtc:[5115,4114]},ul={btc:["wcbtc","cbtc","wbtc"]};function Ho(e){return e.replace(/^test\s+/i,"").replace(/^spice/i,"").trim()}function Wn(e){return Ho(e).toLowerCase()}function Dr(e){return Wn(e??"").replace(/[^a-z0-9]/g,"")}function Es(e){const t=Wn(e);return[t,...ul[t]??[]].filter(Boolean)}function pl(e){try{return BigInt(e.balanceAvailable||"0")}catch{return 0n}}function fl(e){return Array.isArray(e.chainTokens)?e.chainTokens:Object.keys(e.chainTokens??{})}function hl(e,t,n,o=[]){const r=Re(t),s=n.toLowerCase(),i=s===Lt.toLowerCase()?r?.nativeCurrency.decimals??18:r?.supportedTokens?.find(d=>d.address.toLowerCase()===s)?.decimals??18,c=new Set(o.map(Dr).filter(Boolean));return e.reduce((d,l)=>{const p=pl(l),u=l.decimals??i,f=mo(p,u,i);if(fl(l).some(h=>{const y=io(h);return y&&ko(y.address,y.chainId,n,t)}))return d+f;if(c.size===0)return d;const m=Dr(l.tokenName||l.receiptToken);return c.has(m)?d+f:d},0n)}function ml(e,t){const n=new Set([...Es(t),...Es(Ho(t))]);return[...e].sort((o,r)=>{const s=Wn(o.symbol),i=Wn(r.symbol),c=Wn(o.name),d=Wn(r.name),l=n.has(s)?0:n.has(c)?1:2,p=n.has(i)?0:n.has(d)?1:2;return l!==p?l-p:o.address.toLowerCase().localeCompare(r.address.toLowerCase())})[0]}function gl(e){const t=e&&e.length>0?e:Object.keys(Eo).map(Number).filter(Number.isFinite),n=new Map;for(const o of t){const r=Re(o);if(!r)continue;const s=`${o}:${Lt.toLowerCase()}`;n.has(s)||n.set(s,{address:Lt,chainId:o,symbol:r.nativeCurrency.symbol,name:r.nativeCurrency.name,decimals:r.nativeCurrency.decimals,isNative:!0,logoURI:r.logo});for(const i of r.supportedTokens??[]){const c=i.address.toLowerCase(),d=`${o}:${c}`;n.has(d)||n.set(d,{address:c,chainId:o,symbol:i.symbol,name:i.name,decimals:i.decimals,isNative:Pe(c),logoURI:i.logo})}}return n}function yl(e,t){const n=gl(t),o=Ho(e.tokenName),r=Wn(e.tokenName),s=Es(e.tokenName),i=Array.isArray(e.chainTokens)?e.chainTokens.map(h=>[h,void 0]):Object.entries(e.chainTokens??{}),c=i.map(([h])=>io(h)).filter(h=>h!==null),d=new Map(i.map(([h,y])=>[h,y])),l=(h,y)=>{const C=d.get(`evm:${y.chainId}:${y.address.slice(2).toLowerCase()}`);return{...h,name:typeof C?.name=="string"&&C.name.length>0?C.name:h.name,decimals:typeof C?.decimals=="number"?C.decimals:h.decimals}},p=c.map(h=>{const y=n.get(`${h.chainId}:${h.address.toLowerCase()}`);return y?l(y,h):void 0}).filter(h=>h!==void 0),u=dl[r]??[];if(u.length>0)for(const h of u){const y=p.find(C=>C.chainId===h);if(y)return y}if(p.length>0)return ml(p,e.tokenName);const f=Array.from(n.values()).filter(h=>s.includes(Wn(h.symbol))||s.includes(Wn(h.name)));if(u.length>0)for(const h of u){const y=f.find(C=>C.chainId===h);if(y)return y}if(f.length>0)return f[0];const m=c[0];if(m){const h=d.get(`evm:${m.chainId}:${m.address.slice(2).toLowerCase()}`);return{address:m.address,chainId:m.chainId,symbol:o||e.tokenName,name:typeof h?.name=="string"&&h.name.length>0?h.name:o||e.tokenName,decimals:typeof h?.decimals=="number"?h.decimals:e.decimals??18,isNative:Pe(m.address),logoURI:void 0}}}function xl(e,t){let n;try{n=BigInt(e.balanceAvailable||"0")}catch{return null}if(n<=0n)return null;const o=yl(e,t),r=o?.decimals??e.decimals??18,s=e.decimals??r,i=mo(n,s,r),c=o?.address??Lt,d=o?.chainId??0,l=Ho(e.tokenName),p=o?.symbol??l,u=o?.name??l,f=parseFloat(tt(i,r)),m=typeof e.balanceUsd=="number"?e.balanceUsd:typeof e.balanceUsd=="string"&&Number(e.balanceUsd)||0;return{address:c,symbol:p,name:u,decimals:r,chainId:d,balance:i,balanceFormatted:f,balanceUsd:m,isNative:o?.isNative??Pe(c),logoURI:o?.logoURI,displaySymbol:e.tokenName||p,displayName:e.tokenName||u,displayChainName:"Spicenet",receiptTokenId:e.receiptToken,receiptTokenName:e.tokenName||u,receiptTokenDecimals:s,chainTokens:e.chainTokens&&!Array.isArray(e.chainTokens)?e.chainTokens:void 0,isUniversal:!0}}function bl(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 vo=({address:e,supportedChains:t,enabled:n=!0,refetchInterval:o})=>{const r=Jt(zt)?.apiUrl||Da,[s,i]=M([]),[c,d]=M(!1),[l,p]=M(null),[u,f]=M(!1),m=ie(!1),h=ie(!1),y=t?JSON.stringify([...t].sort()):"",C=ce(async(x=!1)=>{if(!e||!n){i([]),f(!1),m.current=!1;return}if(!h.current){h.current=!0,!m.current&&!x&&d(!0),p(null);try{const k=await fetch(`${r}/wallets/${e}/balance`,{cache:"no-store"});if(!k.ok)throw new Error(`Failed to fetch balance: ${k.status}`);const w=await k.json();if(w.balances&&Array.isArray(w.balances)){const A=w.balances.map(S=>xl({receiptToken:typeof S.receiptToken=="string"?S.receiptToken:void 0,tokenName:String(S.tokenName??""),balanceAvailable:String(S.balanceAvailable??"0"),chainTokens:bl(S),decimals:typeof S.decimals=="number"?S.decimals:void 0,balanceUsd:typeof S.balanceUsd=="number"||typeof S.balanceUsd=="string"?S.balanceUsd:null},t)).filter(S=>S!==null);i(A),f(A.length>0),m.current=!0}else i([]),f(!1)}catch(k){const w=k instanceof Error?k.message:"Failed to fetch balance";p(w),console.error("Error fetching Spice assets:",k),m.current||(i([]),f(!1))}finally{d(!1),h.current=!1}}},[e,n,y,r]);J(()=>{n&&e&&(m.current=!1,C(!1))},[e,n,y]),J(()=>{if(!n||!e||!o)return;const x=setInterval(()=>{C(!0)},o);return()=>clearInterval(x)},[e,n,o,y]);const v=ce(x=>s.filter(k=>k.chainId===x),[s]),b=ce(async()=>{await C(!0)},[C]);return{assets:s,loading:c,error:l,hasBalance:u,refetch:b,getAssetsByChain:v}},Wr=e=>new Promise(t=>setTimeout(t,e));function wl(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 Cl=350,kl=1e3;async function vl(e){const{actionId:t,intentIndex:n,intentId:o,stepIndex:r,maxPolls:s=120,maxExecuteAttempts:i=3,pollsBeforeRetry:c=5,maxConsecutiveStatusErrors:d=15,onStatusMessage:l,signal:p,chainId:u}=e;let f="pending",m,h,y=0,C=0;const v=()=>{y++,$e.executeStep(t,n,r,{action:"execute"}).then(b=>{b.transactionHash&&(m=b.transactionHash)}).catch(b=>{const x=b instanceof Error?b.message:String(b);console.warn(`[execution] executeStep ${r} attempt ${y} error (will poll):`,x)})};v();for(let b=0;b<s;b++){if(await Wr(b===0?Cl:kl),p?.aborted)throw new De("ABORT","Gasless transaction aborted");try{const k=await $e.checkStepStatus(o,r);C=0,f=k.data.status,h=k.data.error;const w=k.data.transactionHash;w&&(m=w)}catch(k){if(k instanceof Error&&(k.name==="AbortError"||k instanceof De&&k.code==="ABORT")||(C++,C>=d))throw k;continue}if(f==="created"&&b>=y*c&&y<i&&v(),f==="reverted"||f==="error")throw new De("ON_CHAIN_REVERT",wl(f,h),{status:f,txHash:m,actionId:t,intentId:o,stepId:r,chainId:u});if(f==="success"||f==="completed")return m;let x="Waiting for solver...";f==="executing"?x="Transaction executing...":f==="submitted"?x="Transaction submitted...":f==="created"&&(x="Waiting for relayer..."),l?.(x,m)}throw new De("POLLING_EXHAUSTED",`Transaction is still processing (status: ${f}). 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:o,stepId:r,lastStatus:f,pollAttempts:s,maxPolls:s,txHash:m})}async function Nr(e){const{actionId:t,intentIndex:n,intentId:o,totalSteps:r,delayBeforeSpicenetStepMs:s=5e3,isSpicenetStep:i,maxExecuteAttemptsForStep:c,maxPolls:d=120,onStatusMessage:l,signal:p}=e;let u;for(let f=0;f<r;f++){f>0&&i?.(f)&&s>0&&await Wr(s);const m=c?.(f)??3,h=await vl({actionId:t,intentIndex:n,intentId:o,stepIndex:f,maxPolls:d,maxExecuteAttempts:m,maxConsecutiveStatusErrors:m===6?5:15,onStatusMessage:l,signal:p});h&&(u=h)}return u}function Fs(e,t){return e<=0n||t<=0n?0n:(e*t+10000n-1n)/10000n}function Nn(e){const t=BigInt(e.feeBreakdown.spicenetFee),n=BigInt(e.feeBreakdown.gasFee),o=BigInt(e.feeBreakdown.bridgeFee??"0"),r=t+n+o;return{spicenetFee:t,gasFee:n,bridgeFee:o,totalFee:r}}function Pr(e){const t=BigInt(e.quotedAmount),n=BigInt(e.totalDebit),{totalFee:o}=Nn(e);return t>0n||n>0n||o>0n}function Il(e){const t=BigInt(e.quotedAmount),n=BigInt(e.totalDebit),{totalFee:o}=Nn(e),r=t+o;return n>r?n:r}function Al(e){const t=[];for(const n of e.intents)for(const o of n.batches)t.push(BigInt(o.quotedAmount));return t.length!==1?null:t[0]}function Io(e,t){const n=e.intents.flatMap(l=>l.batches).filter(Pr);if(n.length===0||n.length>1)return null;const o=n[0],{gasFee:r,spicenetFee:s,bridgeFee:i,totalFee:c}=Nn(o),d=t.actionAmount??BigInt(o.quotedAmount);return{symbol:t.symbol,decimals:t.decimals,grossAmount:d+c,netAmount:d,totalFee:c,spicenetFee:s,gasFee:r,bridgeFee:i,gasQuoteSource:o.gasQuoteSource}}function Xn(e,t){const n=e.intents.flatMap(p=>p.batches).filter(Pr);if(n.length===0)return null;const o=n.filter(p=>p.chainId===t.chainId),r=o.length>0?o:n;if(r.length>1)return null;const s=r[0],{gasFee:i,spicenetFee:c,bridgeFee:d,totalFee:l}=Nn(s);return{chainId:s.chainId,tokenAddress:t.tokenAddress,symbol:t.symbol,decimals:t.decimals,grossAmount:Il(s),netAmount:BigInt(s.quotedAmount),totalFee:l,gasFee:i,spicenetFee:c,bridgeFee:d,gasQuoteSource:s.gasQuoteSource}}const Sl=10n,El=5;function jo(e){return e.map(t=>({...t,calls:[...t.calls],tokenTransfers:t.tokenTransfers?[...t.tokenTransfers]:void 0}))}function Qo({token:e,recipient:t,amount:n}){return{to:e,value:0n,data:mt({abi:qe,functionName:"transfer",args:[t,n]})}}function Ur({chainBatches:e,token:t,amount:n}){const o=jo(e),r=o[o.length-1];if(!r)return o;const s=xn(r.chainId);return r.calls=[...r.calls,Qo({token:t,recipient:s,amount:n})],o}function zr({chainBatches:e,user:t,token:n,grossAmount:o,gasFee:r}){const s=jo(e),i=s[s.length-1];if(!i)throw new De("INVALID_PARAMS","Action-output escrow funding requires at least one chain batch.");const c=Fs(o,Sl),d=r+c;if(d>=o)throw new De("INVALID_PARAMS","Borrow amount is too small after gas and Spicenet fees.",{grossAmount:o.toString(),gasFee:r.toString(),spicenetFee:c.toString()});const l=o-d,p=xn(i.chainId),u=[];return r>0n&&u.push(Qo({token:n,recipient:Kn,amount:r})),c>0n&&u.push(Qo({token:n,recipient:Bo,amount:c})),i.calls=[...i.calls,...u,Qo({token:n,recipient:p,amount:l})],i.tokenTransfers=[...i.tokenTransfers??[],...r>0n?[{from:t,to:Kn,token:n,amount:r}]:[],...c>0n?[{from:t,to:Bo,token:n,amount:c}]:[],{from:t,to:p,token:n,amount:l}],{chainBatches:s,gasFee:r,spicenetFee:c,netEscrowAmount:l,outputCredit:{chainId:i.chainId,token:n,amount:o}}}async function Lr({chainBatches:e,user:t,token:n,grossAmount:o,chainAuthorizations:r}){let s=0n,i=zr({chainBatches:e,user:t,token:n,grossAmount:o,gasFee:s});for(let c=0;c<El;c+=1){const d=Fn(i.chainBatches),l=(await $e.estimateBatchGas({user:t,outputToken:n,chainBatches:i.chainBatches.map((p,u)=>({...p,hash:d[u].hash})),chainAuthorizations:r})).gasFee;if(l===s)return i;s=l,i=zr({chainBatches:e,user:t,token:n,grossAmount:o,gasFee:s})}throw new De("INVALID_PARAMS","Action-output fee estimate did not converge. Please retry.")}function Jn(e){return To(e.chainId)}function Fl(e,t){if(e.length!==t.length)return!1;const n=Fn(e),o=Fn(t);return n.every((r,s)=>r.hash===o[s]?.hash)}const Or="0xa9059cbb";function Vo(e,t){return`${e}:${t.toLowerCase()}`}function Hr(e,t){return t===Lt.toLowerCase()?{symbol:tn(e),decimals:18}:Tt(t,e)??{symbol:"tokens",decimals:18}}function Bl(e,t){const n=Tt(t,e);return[n?.equivalenceGroup,n?.symbol,n?.name]}async function Tl(e){return Wa(e)}function Bs(e,t){return e.map(n=>{if(Jn(n)||n.calls.length===0)return n;const o=new Set((n.tokenTransfers??[]).filter(s=>(s.from==="escrow"||s.from==="solver")&&Te(s.to,t)).map(s=>s.token.toLowerCase()));if(o.size===0)return n;let r=0;for(const s of n.calls){if(!s.data?.startsWith(Or))break;try{const i=Mo({abi:qe,data:s.data});if(i.functionName!=="transfer")break;const[c]=i.args;if(Te(c,t)||!o.has(s.to.toLowerCase()))break;r+=1}catch{break}}return r===0?n:{...n,calls:n.calls.slice(r)}})}async function Ml(e,t,n){const o=new Map,r=new Map,s=new Map,i=new Map;for(const d of n?.actionOutputCredits??[]){const l=Vo(d.chainId,d.token);i.set(l,(i.get(l)??0n)+d.amount)}for(const d of e)if(!Jn(d)){for(const l of d.tokenTransfers??[]){if(l.from!=="escrow"&&l.from!=="solver"||!Te(l.to,t))continue;const p=BigInt(l.amount??0);if(p<=0n)continue;const u=Vo(d.chainId,l.token);r.set(u,(r.get(u)??0n)+p),l.from==="escrow"&&s.set(u,(s.get(u)??0n)+p)}for(const l of d.calls){if(l.value&&l.value>0n){const p=Vo(d.chainId,Lt);o.set(p,(o.get(p)??0n)+l.value)}if(l.data?.startsWith(Or))try{const p=Mo({abi:qe,data:l.data});if(p.functionName!=="transfer")continue;const[,u]=p.args,f=l.to.toLowerCase(),m=Vo(d.chainId,f);o.set(m,(o.get(m)??0n)+u)}catch{}}}let c=null;for(const[d,l]of s){if(l<=0n)continue;const[p,u]=d.split(":"),f=Number(p),m=Hr(f,u);c??(c=await Tl(t));const h=hl(c,f,u,Bl(f,u));if(!(h>=l))throw new De("INVALID_PARAMS",`Insufficient Spice ${m.symbol}: needs ${tt(l,m.decimals)}, has ${tt(h,m.decimals)}.`,{chainId:f,token:u,userAddress:t,requiredAmount:l.toString(),balance:h.toString(),balanceSource:"spice"})}for(const[d,l]of o){if(l<=0n)continue;const[p,u]=d.split(":"),f=Number(p),m=l-(r.get(d)??0n)-(i.get(d)??0n);if(m<=0n)continue;const h=lt(f),y=u===Lt.toLowerCase()?await h.getBalance({address:t}):await h.readContract({address:u,abi:qe,functionName:"balanceOf",args:[t]});if(y>=m)continue;const C=Hr(f,u);throw new De("INVALID_PARAMS",`Insufficient ${C.symbol} on ${tn(f)}: needs ${tt(m,C.decimals)}, has ${tt(y,C.decimals)}.`,{chainId:f,token:u,userAddress:t,requiredAmount:m.toString(),balance:y.toString(),balanceSource:"wallet"})}}function Rl({chainBatches:e,tokenAddress:t,tokenTransferAmount:n,useCustomTransfers:o}){if(!(e.some(Jn)||!(o?e.some(r=>Jn(r)?!1:(r.tokenTransfers??[]).some(s=>s.from==="escrow"&&BigInt(s.amount??0)>0n)):n>0n)))throw new De("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:!!o})}function Dl(e,t,n,o){t.forEach((r,s)=>{if(!r.to||!r.from||!r.token||r.amount===void 0)throw new De("INVALID_TOKEN_TRANSFER",`tokenTransfers[${s}] 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:s,transfer:{from:r.from,to:r.to,token:r.token,amount:r.amount?.toString()},signingAddress:n,useCustomTransfers:o})})}function Ts({user:e,chainBatches:t,tokenAddress:n,tokenTransferAmount:o,exp:r,signature:s,chainAuthorizations:i,useCustomTransfers:c}){const d=t,l=Fn(d),p=d.filter(u=>!Jn(u)).length;if(Rl({chainBatches:d,tokenAddress:n,tokenTransferAmount:o,useCustomTransfers:c}),!c&&o>0n&&p>1)throw new De("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:o.toString()});return{user:e,...i?{chainAuthorizations:i}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:s,nbf:0,exp:r,chainBatches:l.map((u,f)=>{const m=d[f],h=Jn(m)?[]:c?m.tokenTransfers??[]:o>0n?[{from:"escrow",to:e,token:n,amount:o}]:[];return Dl(Number(u.chainId),h,e,c),{hash:u.hash,chainId:Number(u.chainId),tokenTransfers:h,calls:u.calls}})}]}}function Wl(e,t){const n=Fn(e).map(o=>o.hash);return go(yo([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,t,n]))}let Ms=!1;function qo(){const{address:e,isConnected:t,isAuthenticated:n,actions:o}=An(),[r,s]=M(null),i=ie(o),c=ie(new Map);i.current=o;const d=ce(async(f,m,h)=>{const y=[...new Set(f.filter(b=>!Jn(b)).map(b=>b.chainId))],C=await Promise.all(y.map(async b=>{const x=lt(b),k=fo(b),w=Number(await es(m,x)),A=[m.toLowerCase(),b,k.toLowerCase(),w].join(":");return{chainId:b,delegateContract:k,nonce:w,cacheKey:A,cached:c.current.get(A)}})),v=[];for(const{chainId:b,delegateContract:x,nonce:k,cacheKey:w,cached:A}of C){if(A){v.push(A);continue}if(h?.aborted)throw new De("ABORT","Gasless transaction aborted");const S=await i.current.signAuthorization({contractAddress:x,chainId:b,nonce:k}),B={r:S.r,s:S.s,yParity:S.yParity,address:S.address??x,chainId:Number(S.chainId??b),nonce:Number(S.nonce??k)};c.current.set(w,B),v.push(B)}return v},[]),l=ce(async(f,m,h)=>{if(h?.aborted)throw new De("ABORT","Gasless transaction aborted");const y=await i.current.signMessage({raw:Wl(f,m)}),C=typeof y=="string"?y:y.signature;if(!C)throw new De("SIGNATURE_FAILED","Failed to sign intent authorization. The wallet returned an empty signature.");return C},[]),p=ce(async(f,m,h,y,C,v)=>{const b=(x,k,w)=>{y?.({step:x,message:k,...w})};if(Ms)throw new De("CONCURRENT_EXECUTION","A gasless transaction is already in progress. Please wait.");Ms=!0;try{if(!e)throw new De("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const x=v?.userOverride||e,k=v?.depositToEscrow?.gasFundingSource==="action-output"?v.depositToEscrow:null;let w=v?.depositToEscrow&&!k?Ur({chainBatches:f,token:v.depositToEscrow.token,amount:v.depositToEscrow.amount}):jo(f),A=[],S=v?.useCustomTransfers;b("signing-delegation","Sign delegation in your wallet...");const B=await d(w,x,C);if(C?.aborted)throw new De("ABORT","Gasless transaction aborted");const E=BigInt(Math.floor(Date.now()/1e3)+3600);if(k){const L=await Lr({chainBatches:f,user:x,token:k.token,grossAmount:k.amount,chainAuthorizations:B});w=L.chainBatches,A=[L.outputCredit],S=!0}if(!v?.skipPreSubmitFeeEstimate){let L=!1;for(let Q=0;Q<5;Q++){const V=v?.feeExecutionMode==="user-transfer"?Bs(w,x):w,O=Ts({user:x,chainBatches:V,tokenAddress:m,tokenTransferAmount:h,exp:Number(E),signature:"0x00",chainAuthorizations:B,useCustomTransfers:S}),K=await $e.estimateActionFees(O);s(K);const ue=v?.adjustBatchesForEstimate?.({feeEstimate:K,chainBatches:w});if(!ue||Fl(w,ue)){L=!0;break}w=ue}if(!L)throw new De("INVALID_PARAMS","Withdraw fee estimate did not converge. Please retry.")}v?.skipUserFundingPreflight||await Ml(w,x,{actionOutputCredits:A}),b("signing-intent","Sign the intent in your wallet...");const I=await l(w,E,C);if(C?.aborted)throw new De("ABORT","Gasless transaction aborted");b("submitting","Submitting to relayer...");const F=Ts({user:x,chainBatches:w,tokenAddress:m,tokenTransferAmount:h,exp:Number(E),signature:I,chainAuthorizations:B,useCustomTransfers:S}),R=await $e.createAction(F),[T,N]=R.intentIds[0].split("/"),z=parseInt(N||"0",10),W=`${T}/${z}`;b("executing","Executing on chain..."),b("executing","Executing on chain...",{actionId:T,intentId:W,intentIndex:z,totalSteps:w.length});const H=w.length,D=await Nr({actionId:T,intentIndex:z,intentId:W,totalSteps:H,signal:C,isSpicenetStep:L=>w[L]?.domain==="spicenet",maxExecuteAttemptsForStep:L=>w[L]?.domain==="spicenet"?6:3,maxPolls:180,onStatusMessage:(L,Q)=>{b("executing",L,{txHash:Q,actionId:T,intentId:W,intentIndex:z,totalSteps:H})}});return b("success","Transaction successful!",{txHash:D,actionId:T,intentId:W,intentIndex:z,totalSteps:H}),D||T}catch(x){throw console.error("[GaslessExecution] Error:",x),b("error",x.message||"Transaction failed",{error:x.message}),x}finally{Ms=!1}},[e,n,d,l]),u=ce(async(f,m,h,y)=>{if(!e)throw new De("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const C=y?.userOverride||e,v=y?.depositToEscrow?.gasFundingSource==="action-output"?y.depositToEscrow:null;let b=y?.depositToEscrow&&!v?Ur({chainBatches:f,token:y.depositToEscrow.token,amount:y.depositToEscrow.amount}):jo(f);const x=y?.feeExecutionMode==="user-transfer"?Bs(b,C):b,k=y?.signAuthorizationsForEstimate?await d(x,C):void 0;let w=y?.useCustomTransfers;v&&(b=(await Lr({chainBatches:f,user:C,token:v.token,grossAmount:v.amount,chainAuthorizations:k})).chainBatches,w=!0);const A=y?.feeExecutionMode==="user-transfer"?Bs(b,C):b,S=Ts({user:C,chainBatches:A,tokenAddress:m,tokenTransferAmount:h,exp:Math.floor(Date.now()/1e3)+3600,signature:"0x00",chainAuthorizations:k,useCustomTransfers:w}),B=await $e.estimateActionFees(S);return s(B),B},[e,d]);return{executeGasless:p,estimateGasless:u,lastFeeEstimate:r,hasEmbeddedWallet:t&&n}}const Nl={usdc:1,"usdc.e":1,usdt:1,dai:1,ctusd:1,wbtc:1e5,wcbtc:1e5,cbtc:1e5};function Rs(e,t){return tt(e,t).replace(/(\.\d*?[1-9])0+$|\.0+$/,"$1")}function jr(e,t,n){return t===n?e:t<n?e*10n**BigInt(n-t):e/10n**BigInt(t-n)}function Qr(e,t){const n=t?Nl[t.trim().toLowerCase()]??0:0,o=e*n;return o<=0?"$0":o>=1?`$${o.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}`:`$${o.toFixed(4).replace(/0+$/,"").replace(/\.$/,"")}`}function Pl(e,t){return t?JSON.stringify({tokenAddress:t.toLowerCase(),batches:e.map(n=>({chainId:n.chainId,calls:n.calls.map(o=>({to:o.to.toLowerCase(),value:o.value.toString(),data:o.data})),tokenTransfers:(n.tokenTransfers??[]).map(o=>({from:o.from,to:o.to.toLowerCase(),token:o.token.toLowerCase(),amount:o.amount.toString()}))}))}):null}function Ul(e){const t=e.find(n=>To(n.chainId))?.calls?.[0]?.data;if(!t)return null;try{const n=Mo({abi:ts,data:t});return n.functionName!=="createWithdrawalRequest"?null:n.args[0].transfers.map(o=>({token:o.token,recipient:o.to,amount:o.amount}))}catch{return null}}function zl(e,t){return!e||e.length!==t.length?!1:e.every((n,o)=>{const r=t[o];return n.token.toLowerCase()===r.token.toLowerCase()&&n.recipient.toLowerCase()===r.recipient.toLowerCase()&&n.amount===r.amount})}function Ll(e,t){const n=e.intents.flatMap(s=>s.batches).filter(s=>{const i=Nn(s);return BigInt(s.quotedAmount)>0n||BigInt(s.totalDebit)>0n||i.totalFee>0n}),o=n.filter(s=>s.chainId===t),r=o.length>0?o:n;return r.length===1?r[0]:null}function Ol(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const o=n.token.toLowerCase(),r=n.recipient.toLowerCase(),s=`${o}:${r}`,i=t.get(s);i?i.amount+=n.amount:t.set(s,{...n})}return[...t.values()]}function Hl(e,t){if(!e.token||!e.recipient||e.chainId===null)return null;const n=Ll(t,e.chainId);if(!n)return null;const{gasFee:o,bridgeFee:r,spicenetFee:s}=Nn(n),i=o+r,c=[{token:e.token.address,recipient:e.recipient,amount:e.receiveAmountRaw}];return i>0n&&c.push({token:e.token.address,recipient:Kn,amount:i}),s>0n&&c.push({token:e.token.address,recipient:Bo,amount:s}),Ol(c)}async function Vr(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(d=>To(d.chainId)))throw new Error("Spice withdrawals must include a Spicenet funding batch before the destination chain batch.");const n=e.token?.address||"",o={useCustomTransfers:!0},r=await e.gasless.estimateGasless(t,n,0n,o);let s=r;const i=Hl(e,r);e.buildSpicenetBatch&&i!==null&&!zl(Ul(t),i)&&(t=e.buildWithdrawBatches(i));const c=s.intents[0]?.batches[0]??null;c&&e.ui.setLockedGasFee(Nn(c).totalFee),await e.gasless.executeGasless(t,n,0n,d=>{d.actionId&&d.intentId&&typeof d.intentIndex=="number"&&typeof d.totalSteps=="number"&&(e.executionContextRef.current={actionId:d.actionId,intentId:d.intentId,intentIndex:d.intentIndex,totalSteps:d.totalSteps}),e.ui.setExecutionProgress(d)},void 0,{...o,skipPreSubmitFeeEstimate:!0,submittedFeeEstimate:s})}window.dispatchEvent(new CustomEvent("withdraw-completed")),e.onWithdrawSuccess?.({token:e.token?.symbol||"",amount:e.amount,chainId:e.chainId})}catch(t){const n=t instanceof Error?t.message:"Withdraw failed";e.ui.setExecutionError(n),e.onWithdrawError?.(n)}finally{e.ui.setIsExecuting(!1)}}}async function jl(e){const t=e.executionContextRef.current;if(!t){e.ui.setExecutionProgress(null),await Vr(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 o=0;o<t.totalSteps;o++)if((await $e.checkStepStatus(t.intentId,o)).data.status!=="success"){n=o;break}if(n>=t.totalSteps)e.ui.setExecutionProgress(o=>({...o||{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 o=n;o<t.totalSteps;o++){let r="pending",s;try{const i=await $e.executeStep(t.actionId,t.intentIndex,o,{action:"execute"});i.transactionHash&&(s=i.transactionHash)}catch{}for(let i=0;i<120;i++){if(await new Promise(d=>setTimeout(d,Math.min(1e3+i*1e3,5e3))),!e.isMountedRef.current)return;const c=await $e.checkStepStatus(t.intentId,o);if(!e.isMountedRef.current)return;if(r=c.data.status,c.data.transactionHash&&(s=c.data.transactionHash),r==="success"){e.ui.setExecutionProgress({step:o===t.totalSteps-1?"success":"executing",message:o===t.totalSteps-1?"Transaction successful!":"Executing remaining steps...",txHash:s,actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps});break}if(r==="reverted"||r==="error")throw new Error("Withdraw failed");e.ui.setExecutionProgress({step:"executing",message:"Executing remaining steps...",txHash:s,actionId:t.actionId,intentId:t.intentId,intentIndex:t.intentIndex,totalSteps:t.totalSteps})}if(!e.isMountedRef.current)return;if(r!=="success")throw new Error("Withdraw is still processing")}window.dispatchEvent(new CustomEvent("withdraw-completed")),e.onWithdrawSuccess?.({token:e.token?.symbol||"",amount:e.amount,chainId:e.chainId})}catch(n){const o=n instanceof Error?n.message:"Withdraw failed";e.ui.setExecutionError(o),e.onWithdrawError?.(o)}finally{e.ui.setIsExecuting(!1)}}async function Ql(e){const t=(await e.estimateGasless(e.batches,e.tokenAddress,0n,{useCustomTransfers:!0})).intents[0]?.batches[0];if(!t)throw new Error("No gas fee estimate was returned for this withdraw.");return Nn(t).totalFee}const qr='"IBM Plex Mono", monospace',Yr='"Helvetica Neue", sans-serif',Vl=({show:e,position:t,popoverRef:n,spiceAssets:o,dark:r,dk:s})=>{if(!e||!t)return null;const i=r?s.textSecondary:"#71757A",c=r?s.textPrimary:"#0E0D0B",d=o||[];return g("div",{ref:n,"data-balance-popover":!0,style:{position:"fixed",top:`${t.top}px`,left:`${t.left}px`,width:"220px",background:r?s.cardBg:"#FFFFFF",border:`1px solid ${r?s.cardBorder:"#D6D6D6"}`,borderRadius:"10px",boxShadow:r?"0 12px 32px rgba(0,0,0,0.32)":"0 12px 28px rgba(15, 23, 42, 0.14)",padding:"10px",zIndex:40},children:[a("div",{style:{fontFamily:qr,fontSize:"11px",letterSpacing:"0.05em",color:i,marginBottom:"8px"},children:"ALL BALANCES"}),a("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:d.length>0?d.map(l=>{const p=l.displaySymbol||l.receiptTokenName||l.symbol;return g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"10px",padding:"6px 0"},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0},children:[l.logoURI?a("img",{src:l.logoURI,alt:p,style:{width:"18px",height:"18px",borderRadius:"50%",flexShrink:0}}):a("div",{style:{width:"18px",height:"18px",borderRadius:"50%",border:`1px solid ${r?s.cardBorder:"#C8C8C8"}`,flexShrink:0}}),a("span",{style:{fontFamily:Yr,fontSize:"13px",color:c,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:p})]}),a("span",{style:{fontFamily:qr,fontSize:"12px",color:c,flexShrink:0},children:On(l.balanceFormatted)})]},l.receiptTokenId||l.address)}):a("span",{style:{fontFamily:Yr,fontSize:"13px",color:i},children:"No balances"})})]})},ql='"Helvetica Neue", sans-serif',Hn='"IBM Plex Mono", monospace',Yl=({show:e,onToggle:t,showCustomAddress:n,setShowCustomAddress:o,customRecipient:r,setCustomRecipient:s,externalAddress:i,recipientAddress:c,destChainName:d,destChainLogo:l,compatibleDestinationChains:p,txDetailsChainSwitchRef:u,onOpenNetworkPopover:f,sourceChainLabel:m,sourceDetailsLogo:h,sourceTokenLabel:y,amount:C,totalSourceDebitDisplay:v,receiveAmountDisplay:b,destTokenSymbol:x,shouldQuoteWithdrawGas:k,estimatingFee:w,feeError:A,displayedGasFee:S,selectedDestToken:B,theme:E,styles:I,dark:F,dk:R})=>{const T=F?R.textSecondary:"#71757A",N=F?R.textPrimary:"#0E0D0B",z=p.length>1,W=n&&r?bn(r)?`${r.slice(0,6)}...${r.slice(-4)}`:r:c?`${c.slice(0,6)}...${c.slice(-4)}`:"\u2014";return g(fn,{children:[g("div",{onClick:t,style:{display:"flex",alignItems:"center",gap:"6px",marginBottom:e?"10px":"0",cursor:"pointer",userSelect:"none"},children:[a("span",{style:{fontSize:"13px",color:T,fontFamily:ql,fontWeight:600},children:"Transaction Details"}),a(Ma,{size:12,color:T,style:{transform:e?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s"}})]}),e&&g("div",{style:{display:"flex",flexDirection:"column",gap:"7px"},children:[g("div",{children:[g("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[a("span",{style:{fontSize:"12px",color:T,fontFamily:Hn,fontWeight:500,letterSpacing:"0.03em"},children:"TO"}),g("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[a("span",{style:{fontSize:"13px",color:N,fontFamily:Hn,fontWeight:500},children:W}),a("button",{onClick:()=>{o(H=>!H),!n&&i&&s(i)},style:{background:"none",border:"none",cursor:"pointer",padding:"0",fontSize:"9.5px",fontFamily:Hn,color:T,textDecoration:"underline",fontWeight:600},children:n?"Reset":"Switch"})]})]}),n&&g("div",{style:{marginTop:"6px"},children:[a("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:Hn,fontWeight:700,letterSpacing:0,textTransform:"uppercase"},children:"CAUTION: ENTERING AN INCORRECT ADDRESS WILL RESULT IN LOSS OF FUNDS"}),a("input",{type:"text",autoComplete:"off",spellCheck:!1,"aria-label":"Recipient address","aria-invalid":r&&!bn(r)?!0:void 0,"data-spiceflow-focus":!0,value:r,onChange:H=>s(H.target.value),placeholder:"0x...",style:{width:"100%",padding:"8px 10px",borderRadius:"6px",border:`1px solid ${r&&!bn(r)?F?R.errorBorder:"#fca5a5":F?R.inputBorder:"#d1d5db"}`,backgroundColor:F?R.inputBg:"#f9fafb",color:F?R.inputText:"#111827",fontSize:"12px",fontFamily:Hn,outline:"none",boxSizing:"border-box"}}),r&&!bn(r)&&a("span",{style:{fontSize:"11px",color:R.errorText,marginTop:"3px",display:"block"},children:"Invalid address"})]})]}),a(ao,{palette:R,labelColor:T,valueColor:N,label:"RECEIVING CHAIN",value:g("div",{style:{display:"flex",alignItems:"center",gap:"7px"},children:[l&&a("img",{src:l,alt:d,style:{width:"14px",height:"14px",borderRadius:"50%"}}),a("span",{style:{fontSize:"13px",color:N,fontWeight:500,fontFamily:Hn,textTransform:"uppercase"},children:d}),a("button",{ref:u,onClick:H=>{H.stopPropagation(),f(u.current)},style:{background:"none",border:"none",cursor:z?"pointer":"not-allowed",padding:"0",fontSize:"9.5px",fontFamily:Hn,color:T,textDecoration:"underline",fontWeight:600,opacity:z?1:.45},children:"Switch"})]})}),a(ao,{palette:R,labelColor:T,valueColor:N,label:"REQUESTED WITHDRAWAL",value:g(Ds,{logo:h||null,alt:m,primaryText:N,children:[C||"0"," ",y]})}),k&&a(ao,{palette:R,labelColor:T,valueColor:N,label:"TOTAL SOURCE DEBIT",value:g(Ds,{logo:h||null,alt:m,primaryText:N,children:[v," ",y]})}),a(ao,{palette:R,labelColor:T,valueColor:N,label:"YOU RECEIVE",value:g(Ds,{logo:l,alt:d,primaryText:N,gap:"4px",children:[b," ",x]})}),k&&g(fn,{children:[a(ao,{palette:R,labelColor:T,label:"EST. GAS FEE",valueColor:A?"#f87171":N,value:w?"Estimating...":A?"Unavailable":S!==null&&B?`${Rs(S,B.decimals)} ${B.symbol}`:"Estimating..."}),A&&a(ro,{variant:"error",size:"compact",palette:R,fontFamily:I?.fontFamily||E.typography.fontFamily,children:A})]})]})]})},Ds=({logo:e,alt:t,primaryText:n,gap:o="6px",children:r})=>g("div",{style:{display:"flex",alignItems:"center",gap:o},children:[e&&a("img",{src:e,alt:t,style:{width:"13px",height:"13px",borderRadius:"50%"}}),a("span",{style:{fontSize:"13px",color:n,fontWeight:500,fontFamily:Hn},children:r})]});function Kr(e){const t=new Set($s(e).map(n=>n.toLowerCase()));return t.add(e.toLowerCase()),t}const Kl=["USDC","USDT","WETH","WBTC"];function Ws(e,t){const n=Re(t);if(!n)return;if(n.nativeCurrency.symbol.toUpperCase()===e.toUpperCase())return{address:Lt,symbol:n.nativeCurrency.symbol,decimals:n.nativeCurrency.decimals,chainId:t};const o=n.supportedTokens?.find(r=>r.symbol.toUpperCase()===e.toUpperCase());if(o)return{address:o.address.toLowerCase(),symbol:o.symbol,decimals:o.decimals,chainId:t}}function Pn(e,t,n){const o=Re(t);if(!o)return;if(n!==void 0){const i=Mr(e,n,t);if(i)return{address:i.address.toLowerCase(),symbol:i.symbol,decimals:i.decimals,chainId:t}}const r=Kr(e);if([...r].some(i=>Pe(i)))return{address:Lt,symbol:o.nativeCurrency.symbol,decimals:o.nativeCurrency.decimals,chainId:t};const s=o.supportedTokens?.find(i=>r.has(i.address.toLowerCase()));if(s)return{address:s.address.toLowerCase(),symbol:s.symbol,decimals:s.decimals,chainId:t}}function Zr(e){const{sourceAsset:t,outputAsset:n,sourceChainId:o,destinationChainId:r,intermediaryCandidates:s=Kl}=e;if(Oo(t,n))return{strategy:"direct",sourceAsset:t,outputAsset:n,sourceChainId:o,destinationChainId:r,summary:`${t.symbol} fronted directly`};if(Pn(t.address,r,o))return{strategy:"direct",sourceAsset:t,outputAsset:n,sourceChainId:o,destinationChainId:r,summary:`${t.symbol} fronted on destination, swapped to ${n.symbol}`};if(Pn(n.address,o,r))return{strategy:"source-swap",sourceAsset:t,outputAsset:n,sourceChainId:o,destinationChainId:r,summary:`${t.symbol} \u2192 ${n.symbol} on source chain, then fronted`};for(const i of s){const c=Ws(i,o);if(!c||Oo(t,c)||Oo(n,c))continue;const d=Ws(i,r);if(d&&Oo(c,d))return{strategy:"intermediary",sourceAsset:t,outputAsset:n,intermediaryAsset:d,sourceChainId:o,destinationChainId:r,summary:`${t.symbol} \u2192 ${i} on source, fronted, then ${i} \u2192 ${n.symbol} on destination`}}throw new De("ROUTE_STRATEGY_ERROR",`No viable cross-chain route found from ${t.symbol} (chain ${o}) to ${n.symbol} (chain ${r}). No intermediary asset is available on both chains.`,{sourceAsset:t.symbol,outputAsset:n.symbol,sourceChainId:o,destinationChainId:r,candidatesChecked:s})}async function Gr(e){const{route:t,sourceAmount:n,userAddress:o,registry:r,actionCalls:s,slippage:i}=e;async function c(d,l,p,u){const f=r.getVenueForChain(d);if(!f)throw new De("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${d}. Cannot resolve swap ${l} \u2192 ${p}.`,{chainId:d,tokenIn:l,tokenOut:p,amountIn:u.toString()});const m=await f.resolve({type:"swap",tokenIn:l,tokenOut:p,amountIn:u,maxSlippage:i},d,o);if(!m)throw new De("NO_LIQUIDITY",`${f.name} returned no quote for ${l} \u2192 ${p} on chain ${d}. No liquidity available for this pair.`,{venue:f.name,chainId:d,tokenIn:l,tokenOut:p,amountIn:u.toString()});return m}switch(t.strategy){case"direct":{const d=Pn(t.sourceAsset.address,t.destinationChainId,t.sourceChainId)||t.sourceAsset;if(Kr(d.address).has(t.outputAsset.address.toLowerCase()))return{chainBatches:[{chainId:t.destinationChainId,calls:s}],solverFrontToken:d,solverFrontAmount:n,resolvedSwaps:{}};const l=await c(t.destinationChainId,d.address,t.outputAsset.address,n);return{chainBatches:[{chainId:t.destinationChainId,calls:[...l.calls,...s]}],solverFrontToken:d,solverFrontAmount:n,resolvedSwaps:{destinationSwap:l}}}case"source-swap":{const d=Pn(t.outputAsset.address,t.sourceChainId,t.destinationChainId);if(!d)throw new De("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 l=Pn(t.outputAsset.address,t.destinationChainId,t.destinationChainId);if(!l)throw new De("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 c(t.sourceChainId,t.sourceAsset.address,d.address,n);return{chainBatches:[{chainId:t.sourceChainId,calls:p.calls},{chainId:t.destinationChainId,calls:s}],solverFrontToken:l,solverFrontAmount:p.amountOutMinimum,resolvedSwaps:{sourceSwap:p}}}case"intermediary":{if(!t.intermediaryAsset)throw new De("ROUTE_STRATEGY_ERROR","Intermediary strategy requires an intermediary asset but none was provided in the route plan.",{strategy:t.strategy});const d=Pn(t.intermediaryAsset.address,t.sourceChainId,t.destinationChainId);if(!d)throw new De("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 l=await c(t.sourceChainId,t.sourceAsset.address,d.address,n),p=await c(t.destinationChainId,t.intermediaryAsset.address,t.outputAsset.address,l.amountOutMinimum);return{chainBatches:[{chainId:t.sourceChainId,calls:l.calls},{chainId:t.destinationChainId,calls:[...p.calls,...s]}],solverFrontToken:t.intermediaryAsset,solverFrontAmount:l.amountOutMinimum,resolvedSwaps:{sourceSwap:l,destinationSwap:p}}}default:throw new De("ROUTE_STRATEGY_ERROR",`Unknown route strategy: ${t.strategy}`,{strategy:t.strategy})}}const Zl=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,styles:o,onWithdrawExecute:r,withdrawActionLabel:s,onWithdrawSuccess:i,onWithdrawError:c,autoCloseDelay:d,availableTokens:l,buildSpicenetBatch:p})=>{const u=Jt(zt);if(!u)return a("div",{children:"Error: SpiceWithdraw must be used within SpiceFlowProvider"});const f=u.mode||"7702",m=f==="presign"||f==="ondemand",h=u.supportedChainIds,y=u.allowedTokens,C=u.isWhitelistGateActive,v=!0,{theme:b,dark:x,dk:k}=it(o),w=u.network,A=()=>m?"select":"provider-login",[S,B]=M(A()),[E,I]=M(!1),[F,R]=M(null),[T,N]=M(null),[z,W]=M(""),[H,D]=M(!1),[L,Q]=M(!1),[V,O]=M(!1),[K,ue]=M(!1),[U,_]=M(""),[xe,Ae]=M(!0),me=ie(null),be=ie(null),ge=ie(null),j=ie(null),[re,Z]=M(null),[de,we]=M(null),[Ee,G]=M(null),Y=An(),{isReady:ae,isAuthenticated:ke,address:Qe}=Y,bt=Sn(),{address:nt,chainId:ot}=ho(),[oe,le]=M(!1),[st,X]=M(null),[Ue,St]=M(null),Ht=ie(null),gt=ie(!0);J(()=>(gt.current=!0,()=>{gt.current=!1}),[]);const{executeGasless:rn,estimateGasless:$t}=qo(),[Rt,Fe]=M(null),[_t,Cn]=M(null),[kn,Wt]=M(!1),[an,rt]=M(null),{assets:jt,loading:Ke}=vo({address:bt,enabled:e&&!!bt,refetchInterval:3e4}),ct=se(()=>{if(C)return[];if(!y||y.length===0)return jt;const ee=new Set(y.map(ne=>ne.toLowerCase()));return(jt||[]).filter(ne=>[ne.symbol,ne.displaySymbol,ne.receiptTokenName].some(Se=>typeof Se=="string"&&ee.has(Se.toLowerCase())))},[jt,y,C]),dt=se(()=>[...new Set([...h??[],...Object.keys(l??{}).map(Number),...(ct||[]).map(ee=>ee.chainId),...(ct||[]).flatMap(ee=>Object.keys(ee.chainTokens??{}).map(ne=>{const[,Se]=ne.split(":"),Ze=Number(Se);return Number.isFinite(Ze)?Ze:null}).filter(ne=>ne!==null))])].filter(ee=>Re(ee)?.network===w),[h,l,ct,w]),Et=se(()=>{if(l)return l;const ee={};for(const ne of ct||[]){const Se=Object.entries(ne.chainTokens??{});if(Se.length>0){for(const[Ze,_e]of Se){const[Ge,Xe,q]=Ze.split(":");if(Ge!=="evm"||!Xe||!q)continue;const pe=Number(Xe);if(!Number.isFinite(pe))continue;const Je=q.startsWith("0x")?q.toLowerCase():`0x${q.toLowerCase()}`,Ie=Re(pe)?.supportedTokens?.find(Be=>Te(Be.address,Je));Ie&&Ss(ne,Je,pe)&&(ee[pe]||(ee[pe]=[]),ee[pe].find(Be=>Te(Be.address,Je))||ee[pe].push({address:Je,symbol:Ie?.symbol||_e?.name||ne.symbol,name:Ie?.name||_e?.name||ne.displayName||ne.name||ne.symbol,decimals:Ie?.decimals??_e?.decimals??ne.decimals,logoURI:Ie?.logo||ne.logoURI}))}continue}ee[ne.chainId]||(ee[ne.chainId]=[]),ee[ne.chainId].find(Ze=>Te(Ze.address,ne.address))||ee[ne.chainId].push({address:ne.address,symbol:ne.symbol,name:ne.displayName||ne.name||ne.symbol,decimals:ne.decimals,logoURI:ne.logoURI})}return ee},[l,ct]),qt=ce((ee,ne)=>{if(!ee||!ne)return null;const Se=Lo(ee,ne),Ze=Object.entries(ee.chainTokens??{}).flatMap(([Ie,Be])=>{const Oe=io(Ie);return Oe?.chainId===ne?[{parsed:Oe,detail:Be}]:[]}),_e=Et?.[ne]||[],Ge=Ie=>_e.find(Be=>Te(Be.address,Ie))??null,Xe=Ie=>{const Be=Re(ne)?.supportedTokens?.find(Bt=>Te(Bt.address,Ie));if(!Be||!Ss(ee,Ie,ne))return null;const Oe=Ze.find(({parsed:Bt})=>Te(Bt.address,Ie));return Oe?{address:Oe.parsed.address,symbol:Be.symbol,name:Be.name||Oe.detail?.name||ee.displayName||ee.name||ee.symbol,decimals:Be.decimals,logoURI:Be.logo||ee.logoURI}:null};for(const Ie of Se){const Be=Ge(Ie);if(Be)return Be;const Oe=Xe(Ie);if(Oe)return Oe}const q=En(ee,ne);if(q){const Ie=Ge(q);if(Ie)return Ie;const Be=Xe(q);if(Be)return Be}const pe=Pn(ee.address,ne,ee.chainId);return pe?Ge(pe.address)||(_e.length>0?null:{address:pe.address,symbol:pe.symbol||ee.symbol,name:ee.displayName||ee.name||ee.symbol,decimals:pe.decimals??ee.decimals,logoURI:ee.logoURI}):null},[Et]),ye=se(()=>{if(!F)return null;const ee=F.receiptTokenId||`${F.chainId}:${F.address.toLowerCase()}`;return ct.find(ne=>(ne.receiptTokenId||`${ne.chainId}:${ne.address.toLowerCase()}`)===ee)||F},[F,ct]),yt=se(()=>{if(!ye)return[];const ee=Object.keys(ye.chainTokens??{}).map(ne=>io(ne)?.chainId??null).filter(ne=>ne!==null);return Array.from(new Set([...ee,ye.chainId,...dt].filter(Number.isFinite))).filter(ne=>ne!==1&&Re(ne)?.network===w&&qt(ye,ne)!==null)},[ye,dt,qt,w]),Ft=se(()=>{if(!ye||typeof window>"u")return null;const ee=`spiceflow:withdraw-chain:${ye.receiptTokenId||ye.address.toLowerCase()}`,ne=window.localStorage.getItem(ee),Se=ne?Number(ne):null;return Se!==null&&Number.isFinite(Se)&&yt.includes(Se)?Se:null},[ye,yt]),Yt=se(()=>ye?Ft!==null?Ft:ot&&yt.includes(ot)?ot:ye.chainId&&yt.includes(ye.chainId)?ye.chainId:yt[0]??dt[0]??null:dt[0]??null,[ye,Ft,ot,yt,dt]),Ce=se(()=>qt(ye,T),[qt,ye,T]);J(()=>{!ct?.length||ye||R(ct[0])},[v,ct,ye]),J(()=>{!ye||(T===null||!yt.includes(T))&&N(Yt)},[v,ye,T,Yt,yt]),J(()=>{if(!H&&!L&&!V)return;const ee=ne=>{const Se=ne.target;H&&!me.current?.contains(Se)&&!be.current?.contains(Se)&&!Se?.closest?.("[data-network-popover]")&&D(!1),L&&!ge.current?.contains(Se)&&!Se?.closest?.("[data-token-popover]")&&Q(!1),V&&!j.current?.contains(Se)&&!Se?.closest?.("[data-balance-trigger]")&&O(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[H,L,V]);const Kt=ce(ee=>{if(!ee||yt.length<=1)return;const ne=ee.getBoundingClientRect(),Se=220,Ze=16;Z({top:ne.bottom+8,left:Math.min(Math.max(Ze,ne.right-Se),window.innerWidth-Se-Ze)}),D(_e=>!_e)},[yt.length]);J(()=>{if(!ye||T===null||typeof window>"u")return;const ee=`spiceflow:withdraw-chain:${ye.receiptTokenId||ye.address.toLowerCase()}`;window.localStorage.setItem(ee,String(T))},[ye,T]);const ut=K&&U&&bn(U)?U:nt||bt,kt=ye?.balanceFormatted??0,Zt=ce(ee=>{if(!ee)return;const ne=ee.getBoundingClientRect();G({top:ne.bottom+8,left:ne.right-220}),O(!0)},[]),vn=ye?.displaySymbol||ye?.receiptTokenName||ye?.symbol||"spiceUSDC",ln=ye?.displayChainName||"Spicenet",xt=ds,cn=ds,ze=ye?.receiptTokenDecimals??ye?.decimals,Ve=se(()=>{if(!Ce||!ze)return 0n;try{return je(z||"0",ze)}catch{return 0n}},[z,Ce,ze]),Qt=se(()=>!Ce||!ze?0n:jr(Ve,ze,Ce.decimals),[Ce,ze,Ve]),Nt=se(()=>{const ee=_t??Rt;return!ee||ee<=0n||!Ce||!ze?0n:jr(ee,Ce.decimals,ze)},[_t,Rt,Ce,ze]),Ye=se(()=>Ve+Nt,[Ve,Nt]),pt=_t??Rt,wt=ce(ee=>{if(!T||!Ce)return[];if(Ve===0n||Qt===0n||!ut)return[];const ne=Array.isArray(ee)?ee.filter(Ge=>Ge.amount>0n):[{token:Ce.address,recipient:ut,amount:ee??Qt}],Se=ne.reduce((Ge,Xe)=>Ge+Xe.amount,0n);if(Se<=0n)return[];const Ze={chainId:T,calls:[],tokenTransfers:ne.map(Ge=>({from:"escrow",to:Ge.recipient,token:Ge.token,amount:Ge.amount}))};if(!p)return[Ze];const _e=p({destinationChainId:T,deliveryToken:Ce.address,deliveryAmount:Se,deliveryRecipient:ut,deliveryTransfers:ne});return _e?[_e,Ze]:[Ze]},[v,T,Ce,Ve,Qt,ut,p]),ft=se(()=>wt(),[wt]),at=se(()=>Pl(ft,Ce?.address),[ft,Ce?.address]),Pt=ie(null),ht=ie(0);J(()=>{let ee=!1;if(!e||m||oe||!Ce||Ve===0n){Pt.current=null,Fe(null),rt(null),Wt(!1);return}if(ft.length===0){Pt.current=null,Fe(null),Wt(!0);return}if(!at){Pt.current=null,Fe(null),rt(null),Wt(!1);return}if(Pt.current===at)return;Pt.current=at;const ne=++ht.current;return(async()=>{Wt(!0),rt(null);try{const Se=await Ql({batches:ft,tokenAddress:Ce.address,estimateGasless:$t});if(ee||ne!==ht.current)return;Fe(Se)}catch(Se){if(ee||ne!==ht.current)return;Pt.current=null,Fe(null),rt(Se instanceof Error?Se.message:"Failed to estimate gas fee")}finally{!ee&&ne===ht.current&&Wt(!1)}})(),()=>{ee=!0}},[e,m,oe,Ce,$t,Ve,ft,at]),J(()=>{oe||Cn(null)},[oe,z,T,Ce?.address]);const dn=ce(()=>{I(!0),B("select")},[v]),Le=ce(()=>{t()},[t]),mn=ie(null);mn.current={batches:ft,walletAddress:Qe,recipient:ut,token:Ce,chainId:T,amount:z,receiveAmountRaw:Qt,gasFee:Rt,isNon7702:m,buildWithdrawBatches:wt,gasless:{estimateGasless:$t,executeGasless:rn},ui:{setIsExecuting:le,setExecutionError:X,setExecutionProgress:St,setLockedGasFee:Cn},executionContextRef:Ht,isMountedRef:gt,onWithdrawExecute:r,onWithdrawSuccess:i,onWithdrawError:c,buildSpicenetBatch:p};const Gt=ce(()=>Vr(mn.current),[]),Mt=ce(()=>jl(mn.current),[]);if(J(()=>{if(!e){const ee=setTimeout(()=>{B(A()),I(!1),R(null),N(null),W(""),D(!1),Q(!1),ue(!1),_(""),le(!1),X(null),St(null),Ht.current=null},300);return()=>clearTimeout(ee)}},[e,m]),J(()=>{if(!m&&e&&S==="provider-login"&&ae&&ke&&bt&&!E){const ee=setTimeout(()=>{I(!0),B("select")},100);return()=>clearTimeout(ee)}},[m,e,S,ae,ke,bt,E,v]),!e)return null;if(S==="provider-login"&&!m)return a(vs,{onAuthSuccess:dn,autoTrigger:!0});if(S==="select"&&v){const ee=parseFloat(z)||0,ne=ze?Rs(Ye,ze):z||"0",Se=parseFloat(ne)||0,Ze=Se>0&&Se>kt,_e=(T?Re(T):null)?.displayName||"Network",Ge=T?Mn[T]||xo:null,Xe=Ce?.symbol||"\u2014",q=vn,pe=Ce?Rs(Qt,Ce.decimals):"0",Je=Qr(ee,Ce?.symbol||ye?.symbol),Ie=Qr(parseFloat(pe)||0,Ce?.symbol||ye?.symbol),Be=!K||!U||bn(U),Oe=!m&&ee>0&&Ce!==null,Bt=!Oe||Rt!==null&&!kn&&!an,Dt=ee>0&&!Ze&&F!==null&&T!==null&&Ce!==null&&ut&&Be&&Bt&&Qt>0n,Ct=!Dt,P=F===null?"NO BALANCE":ee===0?"ENTER AMOUNT":Ze?"INSUFFICIENT BALANCE":Oe&&!Bt?an?"GAS UNAVAILABLE":"ESTIMATING GAS":Oe&&Qt===0n?"AMOUNT TOO SMALL":"WITHDRAW",$=!!Ue&&(Ue.step==="success"||Ue.step==="error"),fe=g("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[a("img",{src:ks,alt:"","aria-hidden":"true",style:{width:"13px",height:"13px",flexShrink:0,...x?{filter:"invert(0.6)"}:{}}}),a("p",{style:{fontSize:"13px",color:x?k.textSecondary:"#979AA0",margin:"0",lineHeight:"1.4",fontFamily:'"Helvetica Neue", sans-serif'},children:"Withdraw collateral from your account to 10+ EVM blockchains."})]}),te='"Helvetica Neue", sans-serif',Ne='"IBM Plex Mono", monospace',Me=o?.primaryColor||b.colors.primary,et=x?k.cardBg:"#E9E9E9",en=x?k.cardBorder:"#C6C6C6",un=x?k.textSecondary:"#7D7C7B",Ut=x?k.textSecondary:"#71757A",vt=x?k.textPrimary:"#0E0D0B",pn=x?k.cardBorder:"#C5C5C4",Un=x?"rgba(255,255,255,0.08)":"#D4D3D3",Qn=170,co=q.length>8?"14px":q.length>6?"16px":"18px",Vn=Xe.length>8?"14px":Xe.length>6?"16px":"18px";return a(Rn,{isOpen:!0,onClose:Le,title:"Withdraw",subtitle:fe,styles:o,theme:b,dark:x,maxWidth:"486px",footerLinkText:"Spicenet accounts \u2192",overlayDimmed:!1,closeOnBackdropClick:n,overlayContent:$?a("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("div",{style:{pointerEvents:"auto"},children:a(Is,{type:"withdraw",isOpen:!0,isProcessing:oe,onRetryTx:()=>{Mt()},onNewTx:()=>{St(null),W(""),X(null),Ht.current=null},onClose:()=>{St(null),X(null),le(!1),Ht.current=null},onComplete:()=>{St(null),X(null),le(!1),Ht.current=null},results:[{asset:{symbol:Ce?.symbol||"Token",address:Ce?.address||""},txHash:Ue?.txHash||"",success:Ue?.step==="success",error:Ue?.error,amount:z}],chainName:T?tn(T):"Network",explorerUrl:T?_n(T,"").replace(/\/tx\/.*$/,""):void 0,theme:b})})}):null,children:g("div",{style:{width:"402px",margin:"0 auto",padding:"0 0 4px 0",position:"relative"},children:[a(Vl,{show:V,position:Ee,popoverRef:j,spiceAssets:ct,dark:x,dk:k}),g("div",{style:{marginTop:"16px",marginBottom:"16px",display:"flex",flexDirection:"column",gap:"16px"},children:[g("div",{style:{backgroundColor:et,border:`1px solid ${en}`,borderRadius:"7px",padding:"14px 16px 12px 16px",minHeight:"138px",display:"flex",flexDirection:"column",gap:"6px",position:"relative"},children:[g("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[a("span",{style:{fontFamily:te,fontSize:"17px",fontWeight:500,color:un,lineHeight:"24px"},children:"Source"}),g("div",{style:{display:"flex",alignItems:"center",gap:"6px",fontFamily:te,fontSize:"13px",fontWeight:500,color:Ut,lineHeight:"16px"},children:["Balance:"," ",Ke?"...":On(kt),a("button",{type:"button","data-balance-trigger":!0,onClick:ve=>{ve.stopPropagation(),Zt(ve.currentTarget)},style:{width:"15px",height:"15px",borderRadius:"999px",border:"1px solid #EA4B4B",color:"#EA4B4B",display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:"9px",fontWeight:500,lineHeight:1,boxSizing:"border-box",background:"transparent",padding:0,cursor:"pointer"},children:a("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"1.5px"},children:[0,1,2].map(ve=>a("span",{style:{width:"1.75px",height:"1.75px",borderRadius:"999px",backgroundColor:"#EA4B4B",display:"block"}},ve))})})]})]}),g("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[g("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[a(Gn,{element:"input",ariaLabel:"Withdraw amount",ariaInvalid:Ze,dataSpiceflowFocus:!0,value:z,onChange:ve=>{const he=ve.target.value;if(he===""){W("");return}/^\d*\.?\d*$/.test(he)&&W(no(he.startsWith(".")?`0${he}`:he,ze??F?.decimals))},placeholder:"0.0",fontFamily:te,color:Ze?"#ef4444":z?vt:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,style:{width:"100%"}}),a("div",{style:{fontSize:"12px",fontWeight:500,color:Ut,fontFamily:te,marginTop:"10px"},children:Je})]}),a("div",{style:{width:`${Qn}px`,flexShrink:0},children:g("div",{style:{backgroundColor:"transparent",border:`1px solid ${pn}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[g("div",{ref:ge,onClick:ve=>{if(ve.stopPropagation(),!L&&ge.current){const he=ge.current.getBoundingClientRect(),He=220,Xt=16;we({top:he.bottom+8,left:Math.min(Math.max(Xt,he.right-He),window.innerWidth-He-Xt)})}Q(he=>!he)},style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px",cursor:"pointer"},children:[a("img",{src:xt,alt:q,style:{width:"24px",height:"24px",borderRadius:"50%"}}),a("span",{style:{fontSize:co,fontWeight:500,color:vt,lineHeight:"1.3",fontFamily:te,flex:1,minWidth:0,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",letterSpacing:0},children:q}),a(Dn,{size:15,color:vt,strokeWidth:2.25})]}),a(Ar,{isOpen:L,position:de,title:"SELECT TOKEN",portalAttribute:"token",items:(ct||[]).map(ve=>({id:ve.receiptTokenId||ve.address,label:ve.displaySymbol||ve.receiptTokenName||ve.symbol,icon:ds,detail:On(ve.balanceFormatted)})),selectedId:ye?.receiptTokenId||ye?.address||null,onSelect:ve=>{const he=(ct||[]).find(He=>(He.receiptTokenId||He.address)===ve);he&&(R(he),W("")),Q(!1)}}),a("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:Un,borderTop:`1px solid ${pn}`},children:a("span",{style:{fontSize:"11px",fontWeight:400,color:vt,fontFamily:te,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:ln})})]})})]}),g("div",{style:{minHeight:"18px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[Ze?a("span",{style:{fontSize:"12px",color:k.errorText,fontFamily:te,fontWeight:500},children:"Insufficient Balance"}):a("span",{}),a("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0px",minHeight:"32px",marginRight:"-9px"},children:[0,25,50,75,100].map((ve,he)=>{const He=he===4,Xt=ve/100,In=parseFloat(z)||0,gn=kt>0&&Math.abs(In/kt*100-ve)<1;return a("button",{type:"button","aria-label":`Set amount to ${ve}%`,"aria-pressed":gn,onClick:()=>{const uo=kt*ve/100,qn=F?.decimals??6,po=Math.floor(uo*10**qn)/10**qn;W(ve===0?"":po>0?oo(po,qn):"")},title:`${ve}%`,disabled:kt===0,"data-spiceflow-focus":!0,style:{width:"32px",height:"32px",padding:"9px",border:"none",backgroundColor:"transparent",cursor:kt===0?"not-allowed":"pointer",opacity:gn?1:.5,transition:"opacity 0.15s ease",display:"flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box"},children:g("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[a("circle",{cx:"7",cy:"7",r:"6.84375",fill:He?Me:"none",stroke:He?Me:x?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!He&&Xt>0&&a("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${Xt>.5?1:0} 1 ${7+6.84375*Math.sin(Xt*2*Math.PI)} ${7-6.84375*Math.cos(Xt*2*Math.PI)} Z`,fill:x?k.textSecondary:"#3C3E42"})]})},ve)})})]})]}),g("div",{style:{backgroundColor:et,border:`1px solid ${en}`,borderRadius:"7px",padding:"14px 16px 12px 16px",minHeight:"138px",display:"flex",flexDirection:"column",gap:"6px"},children:[g("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[a("span",{style:{fontFamily:te,fontSize:"17px",fontWeight:500,color:un,lineHeight:"24px"},children:"Destination"}),g("div",{style:{display:"flex",alignItems:"center",gap:"6px",fontFamily:te,fontSize:"13px",fontWeight:500,color:Ut,lineHeight:"16px"},children:["Balance:"," ",Ke?"...":On(kt),a("button",{type:"button","data-balance-trigger":!0,onClick:ve=>{ve.stopPropagation(),Zt(ve.currentTarget)},style:{width:"15px",height:"15px",borderRadius:"999px",border:"1px solid #EA4B4B",color:"#EA4B4B",display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:"9px",fontWeight:500,lineHeight:1,boxSizing:"border-box",background:"transparent",padding:0,cursor:"pointer"},children:a("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"1.5px"},children:[0,1,2].map(ve=>a("span",{style:{width:"1.75px",height:"1.75px",borderRadius:"999px",backgroundColor:"#EA4B4B",display:"block"}},ve))})})]})]}),g("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[g("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[a(Gn,{element:"div",value:pe,title:pe,fontFamily:te,color:z?vt:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,overflow:"wrap"}),a("div",{style:{fontSize:"12px",fontWeight:500,color:Ut,fontFamily:te,marginTop:"10px"},children:Ie})]}),g("div",{style:{width:`${Qn}px`,flexShrink:0,display:"flex",flexDirection:"column",alignItems:"stretch",gap:"8px"},children:[g("div",{style:{backgroundColor:"transparent",border:`1px solid ${pn}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px"},children:[a("img",{src:Ce?.logoURI||bo,alt:Xe,style:{width:"24px",height:"24px",borderRadius:"50%"}}),a("span",{style:{fontSize:Vn,fontWeight:500,color:vt,lineHeight:"1.3",fontFamily:te,flex:1,minWidth:0,letterSpacing:0},children:Xe})]}),g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:Un,borderTop:`1px solid ${pn}`},children:[g("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[Ge&&a("img",{src:Ge,alt:_e,style:{width:"13px",height:"13px",borderRadius:"50%",flexShrink:0}}),a("span",{style:{fontSize:"11px",fontWeight:400,color:vt,fontFamily:te,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:_e})]}),a("button",{ref:me,onClick:ve=>{ve.stopPropagation(),Kt(me.current)},style:{background:"none",border:"none",cursor:yt.length>1?"pointer":"not-allowed",padding:"0 0 0 8px",fontSize:"9.5px",fontFamily:Ne,color:Ut,textDecoration:"underline",fontWeight:600,opacity:yt.length>1?1:.45},children:"Switch"}),a(Ar,{isOpen:H,position:re,title:"SELECT NETWORK",portalAttribute:"network",items:yt.map(ve=>{const he=Re(ve);return{id:String(ve),label:he?.displayName||String(ve),icon:Mn[ve]||xo}}),selectedId:T!==null?String(T):null,onSelect:ve=>{N(Number(ve)),D(!1)}})]})]}),a("div",{style:{minHeight:"14px"}})]})]})]})]}),g("div",{style:{marginBottom:b.spacing.sm},children:[a(Yl,{show:xe,onToggle:()=>Ae(ve=>!ve),showCustomAddress:K,setShowCustomAddress:ue,customRecipient:U,setCustomRecipient:_,externalAddress:nt,recipientAddress:ut,destChainName:_e,destChainLogo:Ge,compatibleDestinationChains:yt,txDetailsChainSwitchRef:be,onOpenNetworkPopover:Kt,sourceChainLabel:ln,sourceDetailsLogo:cn,sourceTokenLabel:q,amount:z,totalSourceDebitDisplay:ne,receiveAmountDisplay:pe,destTokenSymbol:Xe,shouldQuoteWithdrawGas:Oe,estimatingFee:kn,feeError:an,displayedGasFee:pt,selectedDestToken:Ce,theme:b,styles:o,dark:x,dk:k}),st&&a(ro,{variant:"error",size:"compact",palette:k,fontFamily:o?.fontFamily||b.typography.fontFamily,style:{marginBottom:"12px"},children:st}),a(It,{variant:"outline",fullWidth:!0,onClick:()=>{Dt&&Gt()},disabled:Ct||oe,theme:b,dark:x,styles:o,style:{marginTop:"8px"},children:oe?"EXECUTING...":P})]})]})})}return null},Xr=Zl;var Gl="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAKlBMVEVMaXHpSkrmS0vrSkrmR0fpSkrrSkroSUnqSkrpSkrpSkrpSkrsS0vzTk68N2lZAAAADHRSTlMA/SoEHOX1RcdliKnuQ9TkAAAACXBIWXMAAAsTAAALEwEAmpwYAAAB4UlEQVR42u1XyRbDIAhUcQ/8/+9WUROzNIvtMbxefMo4yACpEOcG4geD30G0C07B8P0qWkzm3QgJEBAsIUqURJMe8NcToZTlR8YJgGev5wwVd2QEG+FZGIl+9iUyloGQvL5NIt2V6RfqoCPRHMZN/0ofy+NBKEsO41b4wVaHADWdvgGqGyR0o5/Tvw/pmr7v6C/XhRbVaTYqfU5bgPVGDUNmYDgXT6UP28xEvAyjpw/H2pD5wGE2ivZZPGv6fXF5JlhEdfr68AUB4vdsqHP6DWPWyDYbITsz/asecXDR+vXPtZbOdmG0o7324dJYVFypLRu6+ptws9aV53glhUIqMCDaqNxdKwjkoQDkzpkAjL1vWwCJA1YBUgpRjlkDULl9jxjFudjHbBkXWg3ZT4N3q9AkMOXUrMM0VZ3oVJk3QXSbvNi0CzNXUimZ2LeatBl7Ie57CiQ9k9EVYEripKVYwJMlq+qKN3eyVzaLu/pArtl0pgFok6XS1j6fjI8BUDZGvPkCvAAvwJdiuipnuZRzJL5q93li0M53pp6Bq4bicZnb2kuMh/8Num9ycOsP9NUalBJ/trG2rmH5/Boabji1FxsbbFhzmaezHAPANlxxcDwvwzWNZ3ps2P0X02MG4rX/2Ad4/i9F5OK4gwAAAABJRU5ErkJggg==";const Ao=e=>{const t=Math.round(e*1e5)/1e5;return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:5}).format(t)},Jr=e=>{const t=Math.round(e*1e5)/1e5;return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:5}).format(t)},Xl=({balanceData:e,isLoading:t=!1,styles:n,className:o="",showHeader:r=!0,onAccountClick:s,onDepositClick:i,onWithdrawClick:c,vaultBalance:d,fetchVaultBalance:l,onWithdrawExecute:p,withdrawActionLabel:u,destinationChainId:f,destinationTokenAddress:m,customSections:h,showDefaultSections:y=!0})=>{const C=Jt(zt),v=(C?.mode||"7702")!=="7702",b=C?.appName||"Spicenet",{dark:x,primaryColor:k,dk:w,theme:A}=it(n),[S,B]=M(!0),[E,I]=M(!1),[F,R]=M(!1),[T,N]=M(null),{isConnected:z}=ho(),{disconnect:W}=Gs();J(()=>{v&&l&&l().then(O=>{const K=Math.round(O*1e5)/1e5;N(K)}).catch(O=>{console.error("Error fetching vault balance:",O),N(null)})},[v,l]);const H=()=>{B(!S)},D=se(()=>{if(!e.freeCollateralItems)return null;const O=e.freeCollateralItems.filter(U=>U.name==="USDC");if(O.length===0)return null;const K=O.reduce((U,_)=>U+_.balance,0),ue=[];return O.forEach(U=>{U.networks&&U.networks.forEach(_=>{(_===1||_===11155111||_===8453||_===84532)&&(ue.includes(_)||ue.push(_))})}),ue.length===0&&ue.push(1,8453),{name:"USDC",totalBalance:K,networks:ue,subtitle:O[0]?.subtitle||"USD COIN"}},[e.freeCollateralItems]),L=se(()=>{if(v){if(T!==null)return T;if(d!=null)return d}return e.freeCollateralItems?e.freeCollateralItems.reduce((O,K)=>O+K.balance,0):e.freeCollateral},[v,T,d,e.freeCollateralItems,e.freeCollateral]),Q=O=>S?O:"******",V=()=>{W(),I(!1),R(!1)};return g("div",{className:o,style:{borderRadius:"16px",backgroundColor:x?w.shell:"#D5D5D5",width:"522px",padding:"8px",fontFamily:n?.fontFamily||'"Helvetica Neue", sans-serif',...n?.container},children:[g("div",{style:{background:x?w.cardBg:" white",display:"flex",flexDirection:"column"},children:[g("div",{style:{backgroundColor:x?w.inputBg:"#E9E9E9",borderRadius:"0 0 16px 16px",padding:"20px",display:"flex",flexFlow:"column"},children:[g("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"4px"},children:[g("p",{style:{fontSize:"14px",fontWeight:500,fontFamily:'"IBM Plex Mono", monospace',color:x?w.textPrimary:"#0E0D0B",margin:0},children:[b.toUpperCase()," BALANCE"]}),z&&a("button",{onClick:V,"aria-label":"Disconnect wallet",style:{width:"36px",height:"36px",borderRadius:"8px",border:x?`1px solid ${k}33`:"1px solid #E5E7EB",background:x?w.inputBg:"white",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",transition:on.interactive,padding:"8px"},onMouseEnter:O=>{O.currentTarget.style.backgroundColor=x?w.cardBg:"#F3F4F6"},onMouseLeave:O=>{O.currentTarget.style.backgroundColor=x?w.inputBg:"white"},children:g("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),a("polyline",{points:"16 17 21 12 16 7"}),a("line",{x1:"21",y1:"12",x2:"9",y2:"12"})]})})]}),g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.percentageChange!==void 0&&e.percentageChange!==null&&g("div",{style:{fontSize:"13px",fontWeight:700,color:e.percentageChange>=0?x?w.successText:"#009C51":x?w.errorText:"#EF4444"},children:[e.percentageChange>=0?"+":"",e.percentageChange.toFixed(2),"%"]}),a("button",{onClick:H,style:{background:"none",border:"none",cursor:"pointer",padding:"8px",display:"flex",alignItems:"center",justifyContent:"center",transition:"opacity 0.2s ease"},onMouseEnter:O=>{O.currentTarget.style.opacity="0.7"},onMouseLeave:O=>{O.currentTarget.style.opacity="1"},children:S?g("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",children:[a("path",{d:"M12 5C7 5 2.73 8.11 1 12.5C2.73 16.89 7 20 12 20C17 20 21.27 16.89 23 12.5C21.27 8.11 17 5 12 5Z",stroke:x?w.textSecondary:"#1A1A1A",strokeWidth:"2",fill:"none"}),a("circle",{cx:"12",cy:"12.5",r:"3",stroke:x?w.textSecondary:"#1A1A1A",strokeWidth:"2",fill:"none"})]}):g("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",children:[a("path",{d:"M12 5C7 5 2.73 8.11 1 12.5C2.73 16.89 7 20 12 20C17 20 21.27 16.89 23 12.5C21.27 8.11 17 5 12 5Z",stroke:x?w.textSecondary:"#1A1A1A",strokeWidth:"2",fill:"none"}),a("path",{d:"M3 3L21 21",stroke:x?w.textSecondary:"#1A1A1A",strokeWidth:"2",strokeLinecap:"round"})]})})]}),a("p",{style:{fontSize:"40px",fontWeight:700,color:x?w.textPrimary:"black"},children:Q(Ao(v&&T!==null?T:v&&d!==void 0&&d!==null?d:e.totalBalance))}),g("div",{style:{display:"flex",gap:"12px",marginTop:"16px"},children:[a(It,{variant:"outline",fullWidth:!0,onClick:()=>{i?i():I(!0)},theme:A,dark:x,styles:n,children:"DEPOSIT"}),a(It,{variant:"outline",fullWidth:!0,onClick:()=>{c?c():R(!0)},theme:A,dark:x,styles:n,children:"WITHDRAW"})]})]}),g("div",{style:{background:x?w.cardBg:"white",padding:"12px 20px",borderRadius:"12px"},children:[y&&a(Ir,{title:"FREE COLLATERAL",icon:Gl,amount:Q(Jr(L)),defaultExpanded:!1,children:v&&(T!==null||d!=null)?a(Uo,{name:"USDC",balance:Q(Ao(T!==null?T:d)),subtitle:"USD COIN",icon:bo,onClick:s?()=>s("usdc-vault"):void 0}):D?a(Uo,{name:D.name,balance:Q(Ao(D.totalBalance)),subtitle:D.subtitle,networks:D.networks,icon:bo,onClick:s?()=>s(D.name):void 0}):e.freeCollateralItems&&e.freeCollateralItems.length>0?e.freeCollateralItems.map((O,K)=>g(hn.Fragment,{children:[a(Uo,{name:O.name,balance:Q(Ao(O.balance)),subtitle:O.subtitle,networks:O.networks,icon:O.name==="USDC"?bo:void 0,onClick:s?()=>s(O.id):void 0}),K<e.freeCollateralItems.length-1&&a("div",{style:{height:"1px",backgroundColor:x?w.cardBorder:"#D0D2D8",margin:"4px 0"}})]},O.id)):a("div",{style:{padding:"12px 0",color:x?w.textSecondary:"#6B7280",fontSize:"13px",fontFamily:'"IBM Plex Mono", monospace'},children:"No collateral items available"})}),h&&h.length>0&&h.filter(O=>O&&O.id&&O.title&&typeof O.title=="string"&&O.title.trim().length>0).map(O=>a(Ir,{title:O.title,icon:O.icon||void 0,amount:Q(Jr(O.totalBalance||0)),defaultExpanded:O.defaultExpanded!==void 0?O.defaultExpanded:!1,children:O.items&&O.items.length>0?O.items.map((K,ue)=>g(hn.Fragment,{children:[a(Uo,{name:K.name,balance:Q(Ao(K.balance)),subtitle:K.subtitle,networks:K.networks,icon:K.name==="USDC"?bo:void 0,onClick:s?()=>s(K.id):void 0}),ue<O.items.length-1&&a("div",{style:{height:"1px",backgroundColor:x?w.cardBorder:"#D0D2D8",margin:"4px 0"}})]},K.id||`item-${ue}`)):a("div",{style:{padding:"12px 0",color:x?w.textSecondary:"#6B7280",fontSize:"13px",fontFamily:'"IBM Plex Mono", monospace'},children:O.emptyMessage||"No items available"})},O.id))]})]}),E&&a(vr,{isOpen:E,onClose:()=>I(!1),styles:n}),F&&a(Xr,{isOpen:F,onClose:()=>R(!1),styles:n,onWithdrawExecute:p,withdrawActionLabel:u})]})},Jl=({options:e,selectedIndex:t,onSelect:n,primaryColor:o,dark:r=!1,textPrimary:s="#111827",textSecondary:i="#6b7280",trackColor:c})=>{const d=e.length-1,l=c||(r?"#3a3a3a":"#d1d5db"),p=r?"4px":"50%",u=r?"none":"2px solid white",f=r?"none":`0 0 0 1px ${o}`;return g("div",{style:{width:"100%",userSelect:"none"},children:[g("div",{style:{position:"relative",paddingBottom:"4px"},children:[a("div",{style:{position:"absolute",top:"50%",left:0,right:0,height:"4px",background:l,borderRadius:"2px",transform:"translateY(-50%)",pointerEvents:"none"}}),a("div",{style:{position:"absolute",top:"50%",left:0,width:`${t/d*100}%`,height:"4px",background:o,borderRadius:"2px",transform:"translateY(-50%)",pointerEvents:"none",transition:"width 0.15s ease"}}),a("input",{type:"range","aria-label":"Lock duration","aria-valuetext":e[t]?.label,"data-spiceflow-focus":!0,min:0,max:d,step:1,value:t,onChange:m=>n(Number(m.target.value)),style:{WebkitAppearance:"none",appearance:"none",width:"100%",height:"20px",background:"transparent",cursor:"pointer",outline:"none",border:"none",position:"relative",zIndex:1,margin:0,padding:0}})]}),a("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"6px"},children:e.map((m,h)=>g("div",{onClick:()=>n(h),style:{display:"flex",flexDirection:"column",alignItems:h===0?"flex-start":h===d?"flex-end":"center",cursor:"pointer",flex:1},children:[a("span",{style:{fontSize:"12px",fontWeight:h===t?700:400,color:h===t?s:i,whiteSpace:"nowrap",transition:"color 0.15s, font-weight 0.15s"},children:m.label}),m.highlight&&a("span",{style:{fontSize:"10px",color:i,whiteSpace:"nowrap"},children:"(most common)"})]},h))}),a("style",{children:`
67
67
  input[type='range']::-webkit-slider-thumb {
68
68
  -webkit-appearance: none;
69
69
  width: 20px;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spicenet-io/spiceflow-ui",
3
- "version": "3.3.40",
3
+ "version": "3.3.41",
4
4
  "description": "Spiceflow UI SDK",
5
5
  "type": "module",
6
6
  "packageManager": "bun@1.3.13",