@spicenet-io/spiceflow-ui 3.3.83 → 3.3.84-escrow.0
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
|
-
`})]})},Vs=new Set(["WBTC","CBTC"]),Ko=new Set(["btc","wbtc","wcbtc","cbtc"]);function Zo(e,t){return!e||!t?!1:e===t?!0:Vs.has(e)&&Vs.has(t)}function Nn(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 a=o.startsWith("0x")?o.toLowerCase():`0x${o.toLowerCase()}`;return{chainId:r,address:a}}function ss(e){return(e??"").trim().replace(/^test\s+/i,"").replace(/^spice/i,"").toLowerCase().replace(/[^a-z0-9]/g,"")}function Ai(e){return new Set([e.receiptTokenName,e.displaySymbol,e.symbol,e.displayName,e.name].map(ss).filter(Boolean))}function Ei(e,t){const n=Ai(e),o=[t.symbol,t.name,t.equivalenceGroup].map(ss);if(o.some(l=>l&&n.has(l)))return!0;const r=[...n].some(l=>Ko.has(l)),a=o.some(l=>Ko.has(l))||Vs.has(t.equivalenceGroup??"");return r&&a}function Yo(e,t,n){const o=new Set(t.map(ss).filter(Boolean)),r=a=>{if(n&&h.addressesEqual(a.address,n))return 0;const l=[a.symbol,a.name,a.equivalenceGroup].map(ss).findIndex(d=>d&&o.has(d));return l===-1?4:l+1};return[...e].sort((a,l)=>{const d=r(a)-r(l);return d!==0?d:a.address.toLowerCase().localeCompare(l.address.toLowerCase())})}const Xo=typeof process<"u"&&process.env?.NEXT_PUBLIC_MORALIS_API_KEY||typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:Fn&&Fn.tagName.toUpperCase()==="SCRIPT"&&Fn.src||new URL("index.cjs.js",document.baseURI).href}<"u"&&void 0||"",ji="https://deep-index.moralis.io/api/v2.2";function os(e,t){const n=e.chainTokens?Object.keys(e.chainTokens):[],o=[];for(const r of n){const a=Nn(r);if(!a||a.chainId!==t)continue;const l=a.address,d=B.getTokenByAddress(l,t);d&&(!Gs(e,l,t)&&!(e.isUniversal&&Ei(e,d))||o.some(u=>h.addressesEqual(u,l))||o.push(l))}return Yo(o.map(r=>{const a=B.getTokenByAddress(r,t);return{address:r,symbol:a?.symbol,name:a?.name,equivalenceGroup:a?.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 Gs(e,t,n){return e.chainId===n&&h.addressesEqual(e.address,t)?!0:Qn(e.address,e.chainId,t,n)}async function Fi(e,t){const n=h.getClientForChain(e),o=B.getEscrowContractAddress(e);return B.isNativeToken(t)?n.getBalance({address:o}):await n.readContract({address:t,abi:M.erc20Abi,functionName:"balanceOf",args:[o]})}function Jo(e,t,n){const o=B.getTokensForChain(n),r=o.find(l=>h.addressesEqual(l.address,e));if(r)return r;const a=B.getTokenByAddress(e,t);if(a)return Yo(o.filter(l=>Zo(l.equivalenceGroup,a.equivalenceGroup)),[a.symbol,a.name,a.equivalenceGroup])[0]}function rn(e,t){if(e.chainId===t)return e.address;const n=Jo(e.address,e.chainId,t);return n?n.address:null}async function $o(e,t,n={}){const o=rn(e,t),r=os(e,t);if(r.length===0)return o;if(r.length===1)return r[0];const a=n.requiredAmount??0n,l=u=>{const c=r.map(f=>({candidate:f,balance:u.get(B.isNativeToken(f)?"native":f.toLowerCase())??0n})).filter(f=>f.balance>0n).sort((f,p)=>f.balance===p.balance?0:f.balance>p.balance?-1:1);return c.length===0?null:((a>0n?c.find(f=>f.balance>=a):c[0])??c[0]).candidate},d=h.getChainsForAssets()[t];if(d?.moralisName&&Xo){const u=new Map,c=r.some(f=>B.isNativeToken(f));try{if(c)try{const p=h.getClientForChain(t),g=B.getEscrowContractAddress(t);u.set("native",await p.getBalance({address:g}))}catch{}const f=await fetch(`${ji}/wallets/${B.getEscrowContractAddress(t)}/tokens?chain=${d.moralisName}`,{headers:{"X-API-Key":Xo}});if(f.ok){const p=await f.json();for(const x of p?.result||[]){const m=String(x.token_address||"").toLowerCase();if(m)try{u.set(m,BigInt(String(x.balance||"0")))}catch{}}const g=l(u);if(g)return g}}catch{}}try{const u=await Promise.all(r.map(async p=>({key:B.isNativeToken(p)?"native":p.toLowerCase(),value:await Fi(t,p)}))),c=new Map(u.map(({key:p,value:g})=>[p,g])),f=l(c);if(f)return f}catch{}return o}function Qn(e,t,n,o){const r=B.getTokenByAddress(e,t),a=B.getTokenByAddress(n,o);return r&&a?Zo(r.equivalenceGroup,a.equivalenceGroup):B.areEquivalent(e,n)}function rs(e,t){return Qn(e.address,e.chainId,t.address,t.chainId)}const Bi={usdc:[8453,1,42161,5115,4114],usdt:[1],btc:[4114,42161,1,5115],wbtc:[1],weth:[8453,1],ctusd:[5115,4114],wcbtc:[5115,4114]},Ti={btc:["wcbtc","cbtc","wbtc"]};function as(e){return e.replace(/^test\s+/i,"").replace(/^spice/i,"").trim()}function hn(e){return as(e).toLowerCase()}function _o(e){return hn(e??"").replace(/[^a-z0-9]/g,"")}function Ks(e){const t=hn(e);return[t,...Ti[t]??[]].filter(Boolean)}function Mi(e){try{return BigInt(e.balanceAvailable||"0")}catch{return 0n}}function Ri(e){return Array.isArray(e.chainTokens)?e.chainTokens:Object.keys(e.chainTokens??{})}function Di(e,t,n,o=[]){const r=h.getChainConfig(t),a=n.toLowerCase(),l=a===B.ZERO_ADDRESS.toLowerCase()?r?.nativeCurrency.decimals??18:r?.supportedTokens?.find(u=>u.address.toLowerCase()===a)?.decimals??18,d=new Set(o.map(_o).filter(Boolean));return e.reduce((u,c)=>{const f=Mi(c),p=c.decimals??l,g=B.convertAmountBetweenDecimals(f,p,l);if(Ri(c).some(m=>{const y=Nn(m);return y&&Qn(y.address,y.chainId,n,t)}))return u+g;if(d.size===0)return u;const x=_o(c.tokenName||c.receiptToken);return d.has(x)?u+g:u},0n)}function Ni(e,t){const n=new Set([...Ks(t),...Ks(as(t))]);return[...e].sort((o,r)=>{const a=hn(o.symbol),l=hn(r.symbol),d=hn(o.name),u=hn(r.name),c=n.has(a)?0:n.has(d)?1:2,f=n.has(l)?0:n.has(u)?1:2;return c!==f?c-f:o.address.toLowerCase().localeCompare(r.address.toLowerCase())})[0]}function Pi(e){const t=e&&e.length>0?e:Object.keys(h.CHAIN_CONFIGS).map(Number).filter(Number.isFinite),n=new Map;for(const o of t){const r=h.getChainConfig(o);if(!r)continue;const a=`${o}:${B.ZERO_ADDRESS.toLowerCase()}`;n.has(a)||n.set(a,{address:B.ZERO_ADDRESS,chainId:o,symbol:r.nativeCurrency.symbol,name:r.nativeCurrency.name,decimals:r.nativeCurrency.decimals,isNative:!0,logoURI:r.logo});for(const l of r.supportedTokens??[]){const d=l.address.toLowerCase(),u=`${o}:${d}`;n.has(u)||n.set(u,{address:d,chainId:o,symbol:l.symbol,name:l.name,decimals:l.decimals,isNative:B.isNativeToken(d),logoURI:l.logo})}}return n}function Wi(e,t){const n=Pi(t),o=as(e.tokenName),r=hn(e.tokenName),a=Ks(e.tokenName),l=Array.isArray(e.chainTokens)?e.chainTokens.map(m=>[m,void 0]):Object.entries(e.chainTokens??{}),d=l.map(([m])=>Nn(m)).filter(m=>m!==null),u=new Map(l.map(([m,y])=>[m,y])),c=(m,y)=>{const C=u.get(`evm:${y.chainId}:${y.address.slice(2).toLowerCase()}`);return{...m,name:typeof C?.name=="string"&&C.name.length>0?C.name:m.name,decimals:typeof C?.decimals=="number"?C.decimals:m.decimals}},f=d.map(m=>{const y=n.get(`${m.chainId}:${m.address.toLowerCase()}`);return y?c(y,m):void 0}).filter(m=>m!==void 0),p=Bi[r]??[];if(p.length>0)for(const m of p){const y=f.find(C=>C.chainId===m);if(y)return y}if(f.length>0)return Ni(f,e.tokenName);const g=Array.from(n.values()).filter(m=>a.includes(hn(m.symbol))||a.includes(hn(m.name)));if(p.length>0)for(const m of p){const y=g.find(C=>C.chainId===m);if(y)return y}if(g.length>0)return g[0];const x=d[0];if(x){const m=u.get(`evm:${x.chainId}:${x.address.slice(2).toLowerCase()}`);return{address:x.address,chainId:x.chainId,symbol:o||e.tokenName,name:typeof m?.name=="string"&&m.name.length>0?m.name:o||e.tokenName,decimals:typeof m?.decimals=="number"?m.decimals:e.decimals??18,isNative:B.isNativeToken(x.address),logoURI:void 0}}}function Ui(e,t){let n;try{n=BigInt(e.balanceAvailable||"0")}catch{return null}if(n<=0n)return null;const o=Wi(e,t),r=o?.decimals??e.decimals??18,a=e.decimals??r,l=B.convertAmountBetweenDecimals(n,a,r),d=o?.address??B.ZERO_ADDRESS,u=o?.chainId??0,c=as(e.tokenName),f=o?.symbol??c,p=o?.name??c,g=parseFloat(M.formatUnits(l,r)),x=typeof e.balanceUsd=="number"?e.balanceUsd:typeof e.balanceUsd=="string"&&Number(e.balanceUsd)||0;return{address:d,symbol:f,name:p,decimals:r,chainId:u,balance:l,balanceFormatted:g,balanceUsd:x,isNative:o?.isNative??B.isNativeToken(d),logoURI:o?.logoURI,displaySymbol:e.tokenName||f,displayName:e.tokenName||p,displayChainName:"Spicenet",receiptTokenId:e.receiptToken,receiptTokenName:e.tokenName||p,receiptTokenDecimals:a,chainTokens:e.chainTokens&&!Array.isArray(e.chainTokens)?e.chainTokens:void 0,isUniversal:!0}}function zi(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 Vn=({address:e,supportedChains:t,enabled:n=!0,refetchInterval:o})=>{const r=i.useContext(h.SpiceFlowProviderContext)?.apiUrl||h.RELAYER_API_URL,[a,l]=i.useState([]),[d,u]=i.useState(!1),[c,f]=i.useState(null),[p,g]=i.useState(!1),x=i.useRef(!1),m=i.useRef(!1),y=t?JSON.stringify([...t].sort()):"",C=i.useCallback(async(A=!1)=>{if(!e||!n){l([]),g(!1),x.current=!1;return}if(!m.current){m.current=!0,!x.current&&!A&&u(!0),f(null);try{const v=await fetch(`${r}/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 R=w.balances.map(E=>Ui({receiptToken:typeof E.receiptToken=="string"?E.receiptToken:void 0,tokenName:String(E.tokenName??""),balanceAvailable:String(E.balanceAvailable??"0"),chainTokens:zi(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);l(R),g(R.length>0),x.current=!0}else l([]),g(!1)}catch(v){const w=v instanceof Error?v.message:"Failed to fetch balance";f(w),console.error("Error fetching Spice assets:",v),x.current||(l([]),g(!1))}finally{u(!1),m.current=!1}}},[e,n,y,r]);i.useEffect(()=>{n&&e&&(x.current=!1,C(!1))},[e,n,y]),i.useEffect(()=>{if(!n||!e||!o)return;const A=setInterval(()=>{C(!0)},o);return()=>clearInterval(A)},[e,n,o,y]);const k=i.useCallback(A=>a.filter(v=>v.chainId===A),[a]),b=i.useCallback(async()=>{await C(!0)},[C]);return{assets:a,loading:d,error:c,hasBalance:p,refetch:b,getAssetsByChain:k}},er=e=>new Promise(t=>setTimeout(t,e));function Oi(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 Li=350,Hi=2500;async function qi(e){const{actionId:t,intentIndex:n,intentId:o,stepIndex:r,maxPolls:a=48,maxExecuteAttempts:l=3,pollsBeforeRetry:d=5,maxConsecutiveStatusErrors:u=15,onStatusMessage:c,signal:f,chainId:p}=e;let g="pending",x,m,y=0,C=0;const k=()=>{y++,h.relayerService.executeStep(t,n,r,{action:"execute"}).then(b=>{b.transactionHash&&(x=b.transactionHash)}).catch(b=>{const A=b instanceof Error?b.message:String(b);console.warn(`[execution] executeStep ${r} attempt ${y} error (will poll):`,A)})};k();for(let b=0;b<a;b++){if(await er(b===0?Li:Hi),f?.aborted)throw new h.SpiceflowError("ABORT","Gasless transaction aborted");try{const v=await h.relayerService.checkStepStatus(o,r);C=0,g=v.data.status,m=v.data.error;const w=v.data.transactionHash;w&&(x=w)}catch(v){if(v instanceof Error&&(v.name==="AbortError"||v instanceof h.SpiceflowError&&v.code==="ABORT")||(C++,C>=u))throw v;continue}if(g==="created"&&b>=y*d&&y<l&&k(),g==="reverted"||g==="error")throw new h.SpiceflowError("ON_CHAIN_REVERT",Oi(g,m),{status:g,txHash:x,actionId:t,intentId:o,stepId:r,chainId:p});if(g==="success"||g==="completed")return x;let A="Waiting for solver...";g==="executing"?A="Transaction executing...":g==="submitted"?A="Transaction submitted...":g==="created"&&(A="Waiting for relayer..."),c?.(A,x)}throw new h.SpiceflowError("POLLING_EXHAUSTED",`Transaction is still processing (status: ${g}). 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:g,pollAttempts:a,maxPolls:a,txHash:x})}async function tr(e){const{actionId:t,intentIndex:n,intentId:o,totalSteps:r,delayBeforeSpicenetStepMs:a=5e3,isSpicenetStep:l,maxExecuteAttemptsForStep:d,maxPolls:u=48,onStatusMessage:c,signal:f}=e;let p;for(let g=0;g<r;g++){g>0&&l?.(g)&&a>0&&await er(a);const x=d?.(g)??3,m=await qi({actionId:t,intentIndex:n,intentId:o,stepIndex:g,maxPolls:u,maxExecuteAttempts:x,maxConsecutiveStatusErrors:x===6?5:15,onStatusMessage:c,signal:f});m&&(p=m)}return p}function is(e,t){return e<=0n||t<=0n?0n:(e*t+10000n-1n)/10000n}function $t(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 nr(e){const t=BigInt(e.quotedAmount),n=BigInt(e.totalDebit),{totalFee:o}=$t(e);return t>0n||n>0n||o>0n}function Qi(e){const t=BigInt(e.quotedAmount),n=BigInt(e.totalDebit),{totalFee:o}=$t(e),r=t+o;return n>r?n:r}function Vi(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 An(e,t){const n=e.intents.flatMap(c=>c.batches).filter(nr);if(n.length===0||n.length>1&&t.actionAmount===void 0)return null;let o=0n,r=0n,a=0n,l=0n;for(const c of n){const f=$t(c);o+=f.gasFee,r+=f.spicenetFee,a+=f.bridgeFee,l+=f.totalFee}const d=n.some(c=>c.gasQuoteSource==="estimated")?"estimated":n.some(c=>c.gasQuoteSource==="configured_fallback")?"configured_fallback":n[0].gasQuoteSource,u=t.actionAmount??BigInt(n[0].quotedAmount);return{symbol:t.symbol,decimals:t.decimals,grossAmount:u+l,netAmount:u,totalFee:l,spicenetFee:r,gasFee:o,bridgeFee:a,gasQuoteSource:d}}function wn(e,t){const n=e.intents.flatMap(f=>f.batches).filter(nr);if(n.length===0)return null;const o=n.filter(f=>f.chainId===t.chainId),r=o.length>0?o:n;if(r.length>1)return null;const a=r[0],{gasFee:l,spicenetFee:d,bridgeFee:u,totalFee:c}=$t(a);return{chainId:a.chainId,tokenAddress:t.tokenAddress,symbol:t.symbol,decimals:t.decimals,grossAmount:Qi(a),netAmount:BigInt(a.quotedAmount),totalFee:c,gasFee:l,spicenetFee:d,bridgeFee:u,gasQuoteSource:a.gasQuoteSource}}const Gi=10n,Ki=5;function ls(e){return e.map(t=>({...t,calls:[...t.calls],tokenTransfers:t.tokenTransfers?[...t.tokenTransfers]:void 0}))}function cs({token:e,recipient:t,amount:n}){return{to:e,value:0n,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[t,n]})}}function sr({chainBatches:e,token:t,amount:n}){const o=ls(e),r=o[o.length-1];if(!r)return o;const a=B.getEscrowContractAddress(r.chainId);return r.calls=[...r.calls,cs({token:t,recipient:a,amount:n})],o}function or({chainBatches:e,user:t,token:n,grossAmount:o,gasFee:r}){const a=ls(e),l=a[a.length-1];if(!l)throw new h.SpiceflowError("INVALID_PARAMS","Action-output escrow funding requires at least one chain batch.");const d=is(o,Gi),u=r+d;if(u>=o)throw new h.SpiceflowError("INVALID_PARAMS","Borrow amount is too small after gas and Spicenet fees.",{grossAmount:o.toString(),gasFee:r.toString(),spicenetFee:d.toString()});const c=o-u,f=B.getEscrowContractAddress(l.chainId),p=[];return r>0n&&p.push(cs({token:n,recipient:B.SPICE_GAS_FEE_RECIPIENT,amount:r})),d>0n&&p.push(cs({token:n,recipient:B.SPICE_PLATFORM_FEE_RECIPIENT,amount:d})),l.calls=[...l.calls,...p,cs({token:n,recipient:f,amount:c})],l.tokenTransfers=[...l.tokenTransfers??[],...r>0n?[{from:t,to:B.SPICE_GAS_FEE_RECIPIENT,token:n,amount:r}]:[],...d>0n?[{from:t,to:B.SPICE_PLATFORM_FEE_RECIPIENT,token:n,amount:d}]:[],{from:t,to:f,token:n,amount:c}],{chainBatches:a,gasFee:r,spicenetFee:d,netEscrowAmount:c,outputCredit:{chainId:l.chainId,token:n,amount:o}}}async function rr({chainBatches:e,user:t,token:n,grossAmount:o,chainAuthorizations:r}){let a=0n,l=or({chainBatches:e,user:t,token:n,grossAmount:o,gasFee:a});for(let d=0;d<Ki;d+=1){const u=B.hashChainBatches(l.chainBatches),c=(await h.relayerService.estimateBatchGas({user:t,outputToken:n,chainBatches:l.chainBatches.map((f,p)=>({...f,hash:u[p].hash})),chainAuthorizations:r})).gasFee;if(c===a)return l;a=c,l=or({chainBatches:e,user:t,token:n,grossAmount:o,gasFee:a})}throw new h.SpiceflowError("INVALID_PARAMS","Action-output fee estimate did not converge. Please retry.")}function En(e){return B.isSpicenetChainId(e.chainId)}function Zi(e,t){if(e.length!==t.length)return!1;const n=B.hashChainBatches(e),o=B.hashChainBatches(t);return n.every((r,a)=>r.hash===o[a]?.hash)}const ar="0xa9059cbb";function ds(e,t){return`${e}:${t.toLowerCase()}`}function ir(e,t){return t===B.ZERO_ADDRESS.toLowerCase()?{symbol:h.getChainName(e),decimals:18}:B.getTokenByAddress(t,e)??{symbol:"tokens",decimals:18}}function Yi(e,t){const n=B.getTokenByAddress(t,e);return[n?.equivalenceGroup,n?.symbol,n?.name]}async function Xi(e){return h.getWalletBalanceEntries(e)}function Zs(e,t){return e.map(n=>{if(En(n)||n.calls.length===0)return n;const o=new Set((n.tokenTransfers??[]).filter(a=>(a.from==="escrow"||a.from==="solver")&&h.addressesEqual(a.to,t)).map(a=>a.token.toLowerCase()));if(o.size===0)return n;let r=0;for(const a of n.calls){if(!a.data?.startsWith(ar))break;try{const l=M.decodeFunctionData({abi:h.P,data:a.data});if(l.functionName!=="transfer")break;const[d]=l.args;if(h.addressesEqual(d,t)||!o.has(a.to.toLowerCase()))break;r+=1}catch{break}}return r===0?n:{...n,calls:n.calls.slice(r)}})}async function Ji(e,t,n){const o=new Map,r=new Map,a=new Map,l=new Map;for(const u of n?.actionOutputCredits??[]){const c=ds(u.chainId,u.token);l.set(c,(l.get(c)??0n)+u.amount)}for(const u of e)if(!En(u)){for(const c of u.tokenTransfers??[]){if(c.from!=="escrow"&&c.from!=="solver"||!h.addressesEqual(c.to,t))continue;const f=BigInt(c.amount??0);if(f<=0n)continue;const p=ds(u.chainId,c.token);r.set(p,(r.get(p)??0n)+f),c.from==="escrow"&&a.set(p,(a.get(p)??0n)+f)}for(const c of u.calls){if(c.value&&c.value>0n){const f=ds(u.chainId,B.ZERO_ADDRESS);o.set(f,(o.get(f)??0n)+c.value)}if(c.data?.startsWith(ar))try{const f=M.decodeFunctionData({abi:h.P,data:c.data});if(f.functionName!=="transfer")continue;const[,p]=f.args,g=c.to.toLowerCase(),x=ds(u.chainId,g);o.set(x,(o.get(x)??0n)+p)}catch{}}}let d=null;for(const[u,c]of a){if(c<=0n)continue;const[f,p]=u.split(":"),g=Number(f),x=ir(g,p);d??(d=await Xi(t));const m=Di(d,g,p,Yi(g,p));if(!(m>=c))throw new h.SpiceflowError("INVALID_PARAMS",`Insufficient Spice ${x.symbol}: needs ${M.formatUnits(c,x.decimals)}, has ${M.formatUnits(m,x.decimals)}.`,{chainId:g,token:p,userAddress:t,requiredAmount:c.toString(),balance:m.toString(),balanceSource:"spice"})}for(const[u,c]of o){if(c<=0n)continue;const[f,p]=u.split(":"),g=Number(f),x=c-(r.get(u)??0n)-(l.get(u)??0n);if(x<=0n)continue;const m=h.getClientForChain(g),y=p===B.ZERO_ADDRESS.toLowerCase()?await m.getBalance({address:t}):await m.readContract({address:p,abi:h.P,functionName:"balanceOf",args:[t]});if(y>=x)continue;const C=ir(g,p);throw new h.SpiceflowError("INVALID_PARAMS",`Insufficient ${C.symbol} on ${h.getChainName(g)}: needs ${M.formatUnits(x,C.decimals)}, has ${M.formatUnits(y,C.decimals)}.`,{chainId:g,token:p,userAddress:t,requiredAmount:x.toString(),balance:y.toString(),balanceSource:"wallet"})}}function $i({chainBatches:e,tokenAddress:t,tokenTransferAmount:n,useCustomTransfers:o}){if(!(e.some(En)||!(o?e.some(r=>En(r)?!1:(r.tokenTransfers??[]).some(a=>a.from==="escrow"&&BigInt(a.amount??0)>0n)):n>0n)))throw new h.SpiceflowError("INVALID_PARAMS","Payouts funded from Spice balance require a Spicenet funding batch before the destination chain batch. Deposits into Spice balance and gas-only actions do not need one.",{tokenAddress:t,tokenTransferAmount:n.toString(),useCustomTransfers:!!o})}function _i(e,t,n,o){t.forEach((r,a)=>{if(!r.to||!r.from||!r.token||r.amount===void 0)throw new h.SpiceflowError("INVALID_TOKEN_TRANSFER",`tokenTransfers[${a}] 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:a,transfer:{from:r.from,to:r.to,token:r.token,amount:r.amount?.toString()},signingAddress:n,useCustomTransfers:o})})}function Ys({user:e,chainBatches:t,tokenAddress:n,tokenTransferAmount:o,exp:r,signature:a,chainAuthorizations:l,useCustomTransfers:d}){const u=t,c=B.hashChainBatches(u),f=u.filter(p=>!En(p)).length;if($i({chainBatches:u,tokenAddress:n,tokenTransferAmount:o,useCustomTransfers:d}),!d&&o>0n&&f>1)throw new h.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:f,tokenAddress:n,tokenTransferAmount:o.toString()});return{user:e,...l?{chainAuthorizations:l}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:a,nbf:0,exp:r,chainBatches:c.map((p,g)=>{const x=u[g],m=En(x)?[]:d?x.tokenTransfers??[]:o>0n?[{from:"escrow",to:e,token:n,amount:o}]:[];return _i(Number(p.chainId),m,e,d),{hash:p.hash,chainId:Number(p.chainId),tokenTransfers:m,calls:p.calls}})}]}}function el(e,t){const n=B.hashChainBatches(e).map(o=>o.hash);return M.keccak256(M.encodeAbiParameters([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,t,n]))}let Xs=!1;function Pn(){const{address:e,isConnected:t,isAuthenticated:n,actions:o}=h.useWallet(),[r,a]=i.useState(null),l=i.useRef(o),d=i.useRef(new Map);l.current=o;const u=i.useCallback(async(g,x,m)=>{const y=[...new Set(g.filter(b=>!En(b)).map(b=>b.chainId))],C=await Promise.all(y.map(async b=>{const A=h.getClientForChain(b),v=h.getDelegateContractAddress(b),w=Number(await B.getAccountNonce(x,A)),R=[x.toLowerCase(),b,v.toLowerCase(),w].join(":");return{chainId:b,delegateContract:v,nonce:w,cacheKey:R,cached:d.current.get(R)}})),k=[];for(const{chainId:b,delegateContract:A,nonce:v,cacheKey:w,cached:R}of C){if(R){k.push(R);continue}if(m?.aborted)throw new h.SpiceflowError("ABORT","Gasless transaction aborted");const E=await l.current.signAuthorization({contractAddress:A,chainId:b,nonce:v}),P={r:E.r,s:E.s,yParity:E.yParity,address:E.address??A,chainId:Number(E.chainId??b),nonce:Number(E.nonce??v)};d.current.set(w,P),k.push(P)}return k},[]),c=i.useCallback(async(g,x,m)=>{if(m?.aborted)throw new h.SpiceflowError("ABORT","Gasless transaction aborted");const y=await l.current.signMessage({raw:el(g,x)}),C=typeof y=="string"?y:y.signature;if(!C)throw new h.SpiceflowError("SIGNATURE_FAILED","Failed to sign intent authorization. The wallet returned an empty signature.");return C},[]),f=i.useCallback(async(g,x,m,y,C,k)=>{const b=(A,v,w)=>{y?.({step:A,message:v,...w})};if(Xs)throw new h.SpiceflowError("CONCURRENT_EXECUTION","A gasless transaction is already in progress. Please wait.");Xs=!0;try{if(!e)throw new h.SpiceflowError("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const A=k?.userOverride||e,v=k?.depositToEscrow?.gasFundingSource==="action-output"?k.depositToEscrow:null;let w=k?.depositToEscrow&&!v?sr({chainBatches:g,token:k.depositToEscrow.token,amount:k.depositToEscrow.amount}):ls(g),R=[],E=k?.useCustomTransfers;b("signing-delegation","Sign delegation in your wallet...");const P=await u(w,A,C);if(C?.aborted)throw new h.SpiceflowError("ABORT","Gasless transaction aborted");const T=BigInt(Math.floor(Date.now()/1e3)+3600);if(v){const O=await rr({chainBatches:g,user:A,token:v.token,grossAmount:v.amount,chainAuthorizations:P});w=O.chainBatches,R=[O.outputCredit],E=!0}if(!k?.skipPreSubmitFeeEstimate){let O=!1;for(let H=0;H<10;H++){const J=k?.feeExecutionMode==="user-transfer"?Zs(w,A):w,U=Ys({user:A,chainBatches:J,tokenAddress:x,tokenTransferAmount:m,exp:Number(T),signature:"0x00",chainAuthorizations:P,useCustomTransfers:E}),z=await h.relayerService.estimateActionFees(U);a(z);const ie=await k?.adjustBatchesForEstimate?.({feeEstimate:z,chainBatches:w}),q=!!ie&&Zi(w,ie);if(!ie||q){O=!0;break}w=ie}if(!O)throw new h.SpiceflowError("INVALID_PARAMS","Fee estimate did not converge. Please retry.")}k?.skipUserFundingPreflight||await Ji(w,A,{actionOutputCredits:R}),b("signing-intent","Sign the intent in your wallet...");const F=await c(w,T,C);if(C?.aborted)throw new h.SpiceflowError("ABORT","Gasless transaction aborted");b("submitting","Submitting to relayer...");const S=Ys({user:A,chainBatches:w,tokenAddress:x,tokenTransferAmount:m,exp:Number(T),signature:F,chainAuthorizations:P,useCustomTransfers:E}),j=await h.relayerService.createAction(S),[I,N]=j.intentIds[0].split("/"),D=parseInt(N||"0",10),L=`${I}/${D}`;b("executing","Executing on chain..."),b("executing","Executing on chain...",{actionId:I,intentId:L,intentIndex:D,totalSteps:w.length});const Q=w.length,W=await tr({actionId:I,intentIndex:D,intentId:L,totalSteps:Q,signal:C,isSpicenetStep:O=>w[O]?.domain==="spicenet",maxExecuteAttemptsForStep:O=>w[O]?.domain==="spicenet"?6:3,maxPolls:180,onStatusMessage:(O,H)=>{b("executing",O,{txHash:H,actionId:I,intentId:L,intentIndex:D,totalSteps:Q})}});return b("success","Transaction successful!",{txHash:W,actionId:I,intentId:L,intentIndex:D,totalSteps:Q}),W||I}catch(A){throw console.error("[GaslessExecution] Error:",A),b("error",A.message||"Transaction failed",{error:A.message}),A}finally{Xs=!1}},[e,n,u,c]),p=i.useCallback(async(g,x,m,y)=>{if(!e)throw new h.SpiceflowError("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const C=y?.userOverride||e,k=y?.depositToEscrow?.gasFundingSource==="action-output"?y.depositToEscrow:null;let b=y?.depositToEscrow&&!k?sr({chainBatches:g,token:y.depositToEscrow.token,amount:y.depositToEscrow.amount}):ls(g);const A=y?.feeExecutionMode==="user-transfer"?Zs(b,C):b,v=y?.signAuthorizationsForEstimate?await u(A,C):void 0;let w=y?.useCustomTransfers;k&&(b=(await rr({chainBatches:g,user:C,token:k.token,grossAmount:k.amount,chainAuthorizations:v})).chainBatches,w=!0);const R=y?.feeExecutionMode==="user-transfer"?Zs(b,C):b,E=Ys({user:C,chainBatches:R,tokenAddress:x,tokenTransferAmount:m,exp:Math.floor(Date.now()/1e3)+3600,signature:"0x00",chainAuthorizations:v,useCustomTransfers:w}),P=await h.relayerService.estimateActionFees(E);return a(P),P},[e,u]);return{executeGasless:f,estimateGasless:p,lastFeeEstimate:r,hasEmbeddedWallet:t&&n}}const tl={usdc:1,"usdc.e":1,usdt:1,dai:1,ctusd:1,wbtc:1e5,wcbtc:1e5,cbtc:1e5};function Js(e,t){return M.formatUnits(e,t).replace(/(\.\d*?[1-9])0+$|\.0+$/,"$1")}function lr(e,t,n){return t===n?e:t<n?e*10n**BigInt(n-t):e/10n**BigInt(t-n)}function cr(e,t){const n=t?tl[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 nl(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 sl(e){const t=e.find(n=>B.isSpicenetChainId(n.chainId))?.calls?.[0]?.data;if(!t)return null;try{const n=M.decodeFunctionData({abi:B.spicenetAbi,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 ol(e,t,n){if(e===t)return!0;const o=e>t?e:t;return o===0n?!1:(e>t?e-t:t-e)*10000n<=o*n}function rl(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()?!1:n.recipient.toLowerCase()===B.SPICE_GAS_FEE_RECIPIENT.toLowerCase()?ol(n.amount,r.amount,100n):n.amount===r.amount})}function al(e,t){const n=e.intents.flatMap(a=>a.batches).filter(a=>{const l=$t(a);return BigInt(a.quotedAmount)>0n||BigInt(a.totalDebit)>0n||l.totalFee>0n}),o=n.filter(a=>a.chainId===t),r=o.length>0?o:n;return r.length===1?r[0]:null}function il(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const o=n.token.toLowerCase(),r=n.recipient.toLowerCase(),a=`${o}:${r}`,l=t.get(a);l?l.amount+=n.amount:t.set(a,{...n})}return[...t.values()]}function dr(e,t){if(!e.token||!e.recipient||e.chainId===null)return null;const n=al(t,e.chainId);if(!n)return null;const{gasFee:o,bridgeFee:r,spicenetFee:a}=$t(n),l=o+r,d=[{token:e.token.address,recipient:e.recipient,amount:e.receiveAmountRaw}];return l>0n&&d.push({token:e.token.address,recipient:B.SPICE_GAS_FEE_RECIPIENT,amount:l}),a>0n&&d.push({token:e.token.address,recipient:B.SPICE_PLATFORM_FEE_RECIPIENT,amount:a}),il(d)}function ur(e,t,n){const o=dr(e,t);return!o||rl(sl(n),o)?null:e.buildWithdrawBatches(o)}async function pr(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(r=>B.isSpicenetChainId(r.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};if(e.buildSpicenetBatch){const r=await e.gasless.estimateGasless(t,n,0n,{...o,adjustBatchesForEstimate:({feeEstimate:d,chainBatches:u})=>ur(e,d,u)}),a=dr(e,r);a&&(t=e.buildWithdrawBatches(a));const l=r.intents[0]?.batches.find(d=>d.chainId===e.chainId)??r.intents[0]?.batches[0]??null;l&&e.ui.setLockedGasFee($t(l).totalFee)}else{const r=(await e.gasless.estimateGasless(t,n,0n,o)).intents[0]?.batches[0]??null;r&&e.ui.setLockedGasFee($t(r).totalFee)}await e.gasless.executeGasless(t,n,0n,r=>{r.actionId&&r.intentId&&typeof r.intentIndex=="number"&&typeof r.totalSteps=="number"&&(e.executionContextRef.current={actionId:r.actionId,intentId:r.intentId,intentIndex:r.intentIndex,totalSteps:r.totalSteps}),e.ui.setExecutionProgress(r)},void 0,e.buildSpicenetBatch?{...o,adjustBatchesForEstimate:({feeEstimate:r,chainBatches:a})=>ur(e,r,a)}:o)}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 ll(e){const t=e.executionContextRef.current;if(!t){e.ui.setExecutionProgress(null),await pr(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 h.relayerService.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",a;try{const l=await h.relayerService.executeStep(t.actionId,t.intentIndex,o,{action:"execute"});l.transactionHash&&(a=l.transactionHash)}catch{}for(let l=0;l<120;l++){if(await new Promise(u=>setTimeout(u,Math.min(1e3+l*1e3,5e3))),!e.isMountedRef.current)return;const d=await h.relayerService.checkStepStatus(t.intentId,o);if(!e.isMountedRef.current)return;if(r=d.data.status,d.data.transactionHash&&(a=d.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:a,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:a,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 cl(e){const t=await e.estimateGasless(e.batches,e.tokenAddress,0n,{useCustomTransfers:!0}),n=t.intents.flatMap(r=>r.batches).filter(r=>$t(r).totalFee>0n),o=n.filter(r=>r.chainId===e.chainId)[0]??n[0]??t.intents[0]?.batches[0];if(!o)throw new Error("No gas fee estimate was returned for this withdraw.");return $t(o).totalFee}const fr='"IBM Plex Mono", monospace',hr='"Helvetica Neue", sans-serif',dl=({show:e,position:t,popoverRef:n,spiceAssets:o,dark:r,dk:a})=>{if(!e||!t)return null;const l=r?a.textSecondary:"#71757A",d=r?a.textPrimary:"#0E0D0B",u=o||[];return s.jsxs("div",{ref:n,"data-balance-popover":!0,style:{position:"fixed",top:`${t.top}px`,left:`${t.left}px`,width:"220px",background:r?a.cardBg:"#FFFFFF",border:`1px solid ${r?a.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:[s.jsx("div",{style:{fontFamily:fr,fontSize:"11px",letterSpacing:"0.05em",color:l,marginBottom:"8px"},children:"ALL BALANCES"}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:u.length>0?u.map(c=>{const f=c.displaySymbol||c.receiptTokenName||c.symbol;return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"10px",padding:"6px 0"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0},children:[c.logoURI?s.jsx("img",{src:c.logoURI,alt:f,style:{width:"18px",height:"18px",borderRadius:"50%",flexShrink:0}}):s.jsx("div",{style:{width:"18px",height:"18px",borderRadius:"50%",border:`1px solid ${r?a.cardBorder:"#C8C8C8"}`,flexShrink:0}}),s.jsx("span",{style:{fontFamily:hr,fontSize:"13px",color:d,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:f})]}),s.jsx("span",{style:{fontFamily:fr,fontSize:"12px",color:d,flexShrink:0},children:bn(c.balanceFormatted)})]},c.receiptTokenId||c.address)}):s.jsx("span",{style:{fontFamily:hr,fontSize:"13px",color:l},children:"No balances"})})]})},ul='"Helvetica Neue", sans-serif',kn='"IBM Plex Mono", monospace',pl=({show:e,onToggle:t,showCustomAddress:n,setShowCustomAddress:o,customRecipient:r,setCustomRecipient:a,externalAddress:l,recipientAddress:d,destChainName:u,destChainLogo:c,compatibleDestinationChains:f,txDetailsChainSwitchRef:p,onOpenNetworkPopover:g,sourceChainLabel:x,sourceDetailsLogo:m,sourceTokenLabel:y,amount:C,totalSourceDebitDisplay:k,receiveAmountDisplay:b,destTokenSymbol:A,shouldQuoteWithdrawGas:v,estimatingFee:w,feeError:R,displayedGasFee:E,selectedDestToken:P,theme:T,styles:F,dark:S,dk:j})=>{const I=S?j.textSecondary:"#71757A",N=S?j.textPrimary:"#0E0D0B",D=f.length>1,L=n&&r?M.isAddress(r)?`${r.slice(0,6)}...${r.slice(-4)}`:r:d?`${d.slice(0,6)}...${d.slice(-4)}`:"\u2014";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onClick:t,style:{display:"flex",alignItems:"center",gap:"6px",marginBottom:e?"10px":"0",cursor:"pointer",userSelect:"none"},children:[s.jsx("span",{style:{fontSize:"13px",color:I,fontFamily:ul,fontWeight:600},children:"Transaction Details"}),s.jsx(vs.ChevronDown,{size:12,color:I,style:{transform:e?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s"}})]}),e&&s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"7px"},children:[s.jsxs("div",{children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsx("span",{style:{fontSize:"12px",color:I,fontFamily:kn,fontWeight:500,letterSpacing:"0.03em"},children:"TO"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.jsx("span",{style:{fontSize:"13px",color:N,fontFamily:kn,fontWeight:500},children:L}),s.jsx("button",{onClick:()=>{o(Q=>!Q),!n&&l&&a(l)},style:{background:"none",border:"none",cursor:"pointer",padding:"0",fontSize:"9.5px",fontFamily:kn,color:I,textDecoration:"underline",fontWeight:600},children:n?"Reset":"Switch"})]})]}),n&&s.jsxs("div",{style:{marginTop:"6px"},children:[s.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:kn,fontWeight:700,letterSpacing:0,textTransform:"uppercase"},children:"CAUTION: ENTERING AN INCORRECT ADDRESS WILL RESULT IN LOSS OF FUNDS"}),s.jsx("input",{type:"text",autoComplete:"off",spellCheck:!1,"aria-label":"Recipient address","aria-invalid":r&&!M.isAddress(r)?!0:void 0,"data-spiceflow-focus":!0,value:r,onChange:Q=>a(Q.target.value),placeholder:"0x...",style:{width:"100%",padding:"8px 10px",borderRadius:"6px",border:`1px solid ${r&&!M.isAddress(r)?S?j.errorBorder:"#fca5a5":S?j.inputBorder:"#d1d5db"}`,backgroundColor:S?j.inputBg:"#f9fafb",color:S?j.inputText:"#111827",fontSize:"12px",fontFamily:kn,outline:"none",boxSizing:"border-box"}}),r&&!M.isAddress(r)&&s.jsx("span",{style:{fontSize:"11px",color:j.errorText,marginTop:"3px",display:"block"},children:"Invalid address"})]})]}),s.jsx(Dn,{palette:j,labelColor:I,valueColor:N,label:"RECEIVING CHAIN",value:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"7px"},children:[c&&s.jsx("img",{src:c,alt:u,style:{width:"14px",height:"14px",borderRadius:"50%"}}),s.jsx("span",{style:{fontSize:"13px",color:N,fontWeight:500,fontFamily:kn,textTransform:"uppercase"},children:u}),s.jsx("button",{ref:p,onClick:Q=>{Q.stopPropagation(),g(p.current)},style:{background:"none",border:"none",cursor:D?"pointer":"not-allowed",padding:"0",fontSize:"9.5px",fontFamily:kn,color:I,textDecoration:"underline",fontWeight:600,opacity:D?1:.45},children:"Switch"})]})}),s.jsx(Dn,{palette:j,labelColor:I,valueColor:N,label:"REQUESTED WITHDRAWAL",value:s.jsxs($s,{logo:m||null,alt:x,primaryText:N,children:[C||"0"," ",y]})}),v&&s.jsx(Dn,{palette:j,labelColor:I,valueColor:N,label:"TOTAL SOURCE DEBIT",value:s.jsxs($s,{logo:m||null,alt:x,primaryText:N,children:[k," ",y]})}),s.jsx(Dn,{palette:j,labelColor:I,valueColor:N,label:"YOU RECEIVE",value:s.jsxs($s,{logo:c,alt:u,primaryText:N,gap:"4px",children:[b," ",A]})}),v&&s.jsxs(s.Fragment,{children:[s.jsx(Dn,{palette:j,labelColor:I,label:"EST. GAS FEE",valueColor:R?"#f87171":N,value:w?"Estimating...":R?"Unavailable":E!==null&&P?`${Js(E,P.decimals)} ${P.symbol}`:"Estimating..."}),R&&s.jsx(Rn,{variant:"error",size:"compact",palette:j,fontFamily:F?.fontFamily||T.typography.fontFamily,children:R})]})]})]})},fl=i.memo(pl),$s=({logo:e,alt:t,primaryText:n,gap:o="6px",children:r})=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:o},children:[e&&s.jsx("img",{src:e,alt:t,style:{width:"13px",height:"13px",borderRadius:"50%"}}),s.jsx("span",{style:{fontSize:"13px",color:n,fontWeight:500,fontFamily:kn},children:r})]});function mr(e){const t=new Set(B.getEquivalentAddresses(e).map(n=>n.toLowerCase()));return t.add(e.toLowerCase()),t}const hl=["USDC","USDT","WETH","WBTC"];function _s(e,t){const n=h.getChainConfig(t);if(!n)return;if(n.nativeCurrency.symbol.toUpperCase()===e.toUpperCase())return{address:B.ZERO_ADDRESS,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 mn(e,t,n){const o=h.getChainConfig(t);if(!o)return;if(n!==void 0){const l=Jo(e,n,t);if(l)return{address:l.address.toLowerCase(),symbol:l.symbol,decimals:l.decimals,chainId:t}}const r=mr(e);if([...r].some(l=>B.isNativeToken(l)))return{address:B.ZERO_ADDRESS,symbol:o.nativeCurrency.symbol,decimals:o.nativeCurrency.decimals,chainId:t};const a=o.supportedTokens?.find(l=>r.has(l.address.toLowerCase()));if(a)return{address:a.address.toLowerCase(),symbol:a.symbol,decimals:a.decimals,chainId:t}}function gr(e){const{sourceAsset:t,outputAsset:n,sourceChainId:o,destinationChainId:r,intermediaryCandidates:a=hl}=e;if(rs(t,n))return{strategy:"direct",sourceAsset:t,outputAsset:n,sourceChainId:o,destinationChainId:r,summary:`${t.symbol} fronted directly`};if(mn(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(mn(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 l of a){const d=_s(l,o);if(!d||rs(t,d)||rs(n,d))continue;const u=_s(l,r);if(u&&rs(d,u))return{strategy:"intermediary",sourceAsset:t,outputAsset:n,intermediaryAsset:u,sourceChainId:o,destinationChainId:r,summary:`${t.symbol} \u2192 ${l} on source, fronted, then ${l} \u2192 ${n.symbol} on destination`}}throw new h.SpiceflowError("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:a})}async function xr(e){const{route:t,sourceAmount:n,userAddress:o,registry:r,actionCalls:a,slippage:l}=e;async function d(u,c,f,p){const g=r.getVenueForChain(u);if(!g)throw new h.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${u}. Cannot resolve swap ${c} \u2192 ${f}.`,{chainId:u,tokenIn:c,tokenOut:f,amountIn:p.toString()});const x=await g.resolve({type:"swap",tokenIn:c,tokenOut:f,amountIn:p,maxSlippage:l},u,o);if(!x)throw new h.SpiceflowError("NO_LIQUIDITY",`${g.name} returned no quote for ${c} \u2192 ${f} on chain ${u}. No liquidity available for this pair.`,{venue:g.name,chainId:u,tokenIn:c,tokenOut:f,amountIn:p.toString()});return x}switch(t.strategy){case"direct":{const u=mn(t.sourceAsset.address,t.destinationChainId,t.sourceChainId)||t.sourceAsset;if(mr(u.address).has(t.outputAsset.address.toLowerCase()))return{chainBatches:[{chainId:t.destinationChainId,calls:a}],solverFrontToken:u,solverFrontAmount:n,resolvedSwaps:{}};const c=await d(t.destinationChainId,u.address,t.outputAsset.address,n);return{chainBatches:[{chainId:t.destinationChainId,calls:[...c.calls,...a]}],solverFrontToken:u,solverFrontAmount:n,resolvedSwaps:{destinationSwap:c}}}case"source-swap":{const u=mn(t.outputAsset.address,t.sourceChainId,t.destinationChainId);if(!u)throw new h.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Output asset ${t.outputAsset.symbol} (${t.outputAsset.address}) not found on source chain ${t.sourceChainId}`,{token:t.outputAsset.symbol,address:t.outputAsset.address,chainId:t.sourceChainId,side:"source"});const c=mn(t.outputAsset.address,t.destinationChainId,t.destinationChainId);if(!c)throw new h.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Output asset ${t.outputAsset.symbol} (${t.outputAsset.address}) not found on destination chain ${t.destinationChainId}`,{token:t.outputAsset.symbol,address:t.outputAsset.address,chainId:t.destinationChainId,side:"destination"});const f=await d(t.sourceChainId,t.sourceAsset.address,u.address,n);return{chainBatches:[{chainId:t.sourceChainId,calls:f.calls},{chainId:t.destinationChainId,calls:a}],solverFrontToken:c,solverFrontAmount:f.amountOutMinimum,resolvedSwaps:{sourceSwap:f}}}case"intermediary":{if(!t.intermediaryAsset)throw new h.SpiceflowError("ROUTE_STRATEGY_ERROR","Intermediary strategy requires an intermediary asset but none was provided in the route plan.",{strategy:t.strategy});const u=mn(t.intermediaryAsset.address,t.sourceChainId,t.destinationChainId);if(!u)throw new h.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Intermediary ${t.intermediaryAsset.symbol} (${t.intermediaryAsset.address}) not found on source chain ${t.sourceChainId}`,{token:t.intermediaryAsset.symbol,address:t.intermediaryAsset.address,chainId:t.sourceChainId,side:"source"});const c=await d(t.sourceChainId,t.sourceAsset.address,u.address,n),f=await d(t.destinationChainId,t.intermediaryAsset.address,t.outputAsset.address,c.amountOutMinimum);return{chainBatches:[{chainId:t.sourceChainId,calls:c.calls},{chainId:t.destinationChainId,calls:[...f.calls,...a]}],solverFrontToken:t.intermediaryAsset,solverFrontAmount:c.amountOutMinimum,resolvedSwaps:{sourceSwap:c,destinationSwap:f}}}default:throw new h.SpiceflowError("ROUTE_STRATEGY_ERROR",`Unknown route strategy: ${t.strategy}`,{strategy:t.strategy})}}const ml=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,styles:o,onWithdrawExecute:r,withdrawActionLabel:a,onWithdrawSuccess:l,onWithdrawError:d,autoCloseDelay:u,availableTokens:c,buildSpicenetBatch:f})=>{const p=i.useContext(h.SpiceFlowProviderContext);if(!p)return s.jsx("div",{children:"Error: SpiceWithdraw must be used within SpiceFlowProvider"});const g=p.mode||"7702",x=g==="presign"||g==="ondemand",m=p.supportedChainIds,y=p.allowedTokens,C=p.isWhitelistGateActive,k=!0,{theme:b,dark:A,dk:v}=h.useSpiceBrand(o),w=p.network,R=()=>x?"select":"provider-login",[E,P]=i.useState(R()),[T,F]=i.useState(!1),[S,j]=i.useState(null),[I,N]=i.useState(null),[D,L]=i.useState(""),[Q,W]=i.useState(!1),[O,H]=i.useState(!1),[J,U]=i.useState(!1),[z,ie]=i.useState(!1),[q,$]=i.useState(""),[le,he]=i.useState(!0),me=i.useRef(null),ue=i.useRef(null),ge=i.useRef(null),Y=i.useRef(null),[oe,K]=i.useState(null),[ne,ce]=i.useState(null),[Ce,be]=i.useState(null),G=h.useWallet(),{isReady:ee,isAuthenticated:_,address:Ae}=G,Be=h.useEmbeddedWalletAddress(),{address:kt,chainId:_e}=Qt.useAccount(),[vt,Ve]=i.useState(!1),[xe,Ee]=i.useState(null),[ze,lt]=i.useState(null),et=i.useRef(null),re=i.useRef(!0),we=i.useRef(null);i.useEffect(()=>(re.current=!0,()=>{re.current=!1}),[]);const{executeGasless:Ge,estimateGasless:je}=Pn(),[Me,Et]=i.useState(null),[Rt,ct]=i.useState(null),[Se,St]=i.useState(!1),[bt,mt]=i.useState(null),{assets:De,loading:zt}=Vn({address:Be,enabled:e&&!!Be,refetchInterval:3e4}),We=i.useMemo(()=>{if(C)return[];if(!y||y.length===0)return De;const te=new Set(y.map(se=>se.toLowerCase()));return(De||[]).filter(se=>[se.symbol,se.displaySymbol,se.receiptTokenName].some(ve=>typeof ve=="string"&&te.has(ve.toLowerCase())))},[De,y,C]),gt=i.useMemo(()=>[...new Set([...m??[],...Object.keys(c??{}).map(Number),...(We||[]).map(te=>te.chainId),...(We||[]).flatMap(te=>Object.keys(te.chainTokens??{}).map(se=>{const[,ve]=se.split(":"),qe=Number(ve);return Number.isFinite(qe)?qe:null}).filter(se=>se!==null))])].filter(te=>h.getChainConfig(te)?.network===w),[m,c,We,w]),Je=i.useMemo(()=>{if(c)return c;const te={};for(const se of We||[]){const ve=Object.entries(se.chainTokens??{});if(ve.length>0){for(const[qe,yt]of ve){const[pt,ft,ut]=qe.split(":");if(pt!=="evm"||!ft||!ut)continue;const Pe=Number(ft);if(!Number.isFinite(Pe))continue;const Tt=ut.startsWith("0x")?ut.toLowerCase():`0x${ut.toLowerCase()}`,He=h.getChainConfig(Pe)?.supportedTokens?.find(X=>h.addressesEqual(X.address,Tt));He&&Gs(se,Tt,Pe)&&(te[Pe]||(te[Pe]=[]),te[Pe].find(X=>h.addressesEqual(X.address,Tt))||te[Pe].push({address:Tt,symbol:He?.symbol||yt?.name||se.symbol,name:He?.name||yt?.name||se.displayName||se.name||se.symbol,decimals:He?.decimals??yt?.decimals??se.decimals,logoURI:He?.logo||se.logoURI}))}continue}te[se.chainId]||(te[se.chainId]=[]),te[se.chainId].find(qe=>h.addressesEqual(qe.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},[c,We]),wt=i.useCallback((te,se)=>{if(!te||!se)return null;const ve=os(te,se),qe=Object.entries(te.chainTokens??{}).flatMap(([He,X])=>{const ye=Nn(He);return ye?.chainId===se?[{parsed:ye,detail:X}]:[]}),yt=Je?.[se]||[],pt=He=>yt.find(X=>h.addressesEqual(X.address,He))??null,ft=He=>{const X=h.getChainConfig(se)?.supportedTokens?.find(Ct=>h.addressesEqual(Ct.address,He));if(!X||!Gs(te,He,se))return null;const ye=qe.find(({parsed:Ct})=>h.addressesEqual(Ct.address,He));return ye?{address:ye.parsed.address,symbol:X.symbol,name:X.name||ye.detail?.name||te.displayName||te.name||te.symbol,decimals:X.decimals,logoURI:X.logo||te.logoURI}:null};for(const He of ve){const X=pt(He);if(X)return X;const ye=ft(He);if(ye)return ye}const ut=rn(te,se);if(ut){const He=pt(ut);if(He)return He;const X=ft(ut);if(X)return X}const Pe=mn(te.address,se,te.chainId);return Pe?pt(Pe.address)||(yt.length>0?null:{address:Pe.address,symbol:Pe.symbol||te.symbol,name:te.displayName||te.name||te.symbol,decimals:Pe.decimals??te.decimals,logoURI:te.logoURI}):null},[Je]),fe=i.useMemo(()=>{if(!S)return null;const te=S.receiptTokenId||`${S.chainId}:${S.address.toLowerCase()}`;return We.find(se=>(se.receiptTokenId||`${se.chainId}:${se.address.toLowerCase()}`)===te)||S},[S,We]),Ke=i.useMemo(()=>{if(!fe)return[];const te=Object.keys(fe.chainTokens??{}).map(se=>Nn(se)?.chainId??null).filter(se=>se!==null);return Array.from(new Set([...te,fe.chainId,...gt].filter(Number.isFinite))).filter(se=>se!==1&&h.getChainConfig(se)?.network===w&&wt(fe,se)!==null)},[fe,gt,wt,w]),tt=i.useMemo(()=>{if(!fe||typeof window>"u")return null;const te=`spiceflow:withdraw-chain:${fe.receiptTokenId||fe.address.toLowerCase()}`,se=window.localStorage.getItem(te),ve=se?Number(se):null;return ve!==null&&Number.isFinite(ve)&&Ke.includes(ve)?ve:null},[fe,Ke]),xt=i.useMemo(()=>fe?tt!==null?tt:_e&&Ke.includes(_e)?_e:fe.chainId&&Ke.includes(fe.chainId)?fe.chainId:Ke[0]??gt[0]??null:gt[0]??null,[fe,tt,_e,Ke,gt]),Re=i.useMemo(()=>wt(fe,I),[wt,fe,I]);i.useEffect(()=>{!We?.length||fe||j(We[0])},[k,We,fe]),i.useEffect(()=>{!fe||(I===null||!Ke.includes(I))&&N(xt)},[k,fe,I,xt,Ke]),i.useEffect(()=>{if(!Q&&!O&&!J)return;const te=se=>{const ve=se.target;Q&&!me.current?.contains(ve)&&!ue.current?.contains(ve)&&!ve?.closest?.("[data-network-popover]")&&W(!1),O&&!ge.current?.contains(ve)&&!ve?.closest?.("[data-token-popover]")&&H(!1),J&&!Y.current?.contains(ve)&&!ve?.closest?.("[data-balance-trigger]")&&U(!1)};return document.addEventListener("mousedown",te),()=>document.removeEventListener("mousedown",te)},[Q,O,J]);const nt=i.useCallback(te=>{if(!te||Ke.length<=1)return;const se=te.getBoundingClientRect(),ve=220,qe=16;K({top:se.bottom+8,left:Math.min(Math.max(qe,se.right-ve),window.innerWidth-ve-qe)}),W(yt=>!yt)},[Ke.length]),Pt=i.useCallback(()=>he(te=>!te),[]);i.useEffect(()=>{if(!fe||I===null||typeof window>"u")return;const te=`spiceflow:withdraw-chain:${fe.receiptTokenId||fe.address.toLowerCase()}`;window.localStorage.setItem(te,String(I))},[fe,I]);const Ye=z&&q&&M.isAddress(q)?q:kt||Be,st=fe?.balanceFormatted??0,jt=i.useCallback(te=>{if(!te)return;const se=te.getBoundingClientRect();be({top:se.bottom+8,left:se.right-220}),U(!0)},[]),Ft=fe?.displaySymbol||fe?.receiptTokenName||fe?.symbol||"spiceUSDC",Ot=fe?.displayChainName||"Spicenet",Bt=Ts,Wt=Ts,dt=fe?.receiptTokenDecimals??fe?.decimals,Te=i.useMemo(()=>{if(!Re||!dt)return 0n;try{return M.parseUnits(D||"0",dt)}catch{return 0n}},[D,Re,dt]),Mt=i.useMemo(()=>!Re||!dt?0n:lr(Te,dt,Re.decimals),[Re,dt,Te]),Ne=i.useMemo(()=>{const te=Rt??Me;return!te||te<=0n||!Re||!dt?0n:lr(te,Re.decimals,dt)},[Rt,Me,Re,dt]),_t=i.useMemo(()=>Te+Ne,[Te,Ne]),Lt=Rt??Me,It=i.useCallback(te=>{if(!I||!Re)return[];if(Te===0n||Mt===0n||!Ye)return[];const se=Array.isArray(te)?te.filter(pt=>pt.amount>0n):[{token:Re.address,recipient:Ye,amount:te??Mt}],ve=se.reduce((pt,ft)=>pt+ft.amount,0n);if(ve<=0n)return[];const qe={chainId:I,calls:[],tokenTransfers:se.map(pt=>({from:"escrow",to:pt.recipient,token:pt.token,amount:pt.amount}))};if(!f)return[qe];const yt=f({destinationChainId:I,deliveryToken:Re.address,deliveryAmount:ve,deliveryRecipient:Ye,deliveryTransfers:se,requestTimestampMs:we.current??Date.now()});return yt?[yt,qe]:[qe]},[k,I,Re,Te,Mt,Ye,f]),Qe=i.useMemo(()=>It(),[It]),de=i.useMemo(()=>nl(Qe,Re?.address),[Qe,Re?.address]),Le=i.useRef(null),ot=i.useRef(0);i.useEffect(()=>{let te=!1;if(!e||x||vt||!Re||!I||Te===0n){Le.current=null,Et(null),mt(null),St(!1);return}if(Qe.length===0){Le.current=null,Et(null),St(!0);return}if(!de){Le.current=null,Et(null),mt(null),St(!1);return}if(Le.current===de)return;Le.current=de;const se=++ot.current;return(async()=>{St(!0),mt(null);try{const ve=await cl({batches:Qe,tokenAddress:Re.address,chainId:I,estimateGasless:je});if(te||se!==ot.current)return;Et(ve)}catch(ve){if(te||se!==ot.current)return;Le.current=null,Et(null),mt(ve instanceof Error?ve.message:"Failed to estimate gas fee")}finally{!te&&se===ot.current&&St(!1)}})(),()=>{te=!0}},[e,x,vt,Re,je,Te,Qe,de]),i.useEffect(()=>{vt||ct(null)},[vt,D,I,Re?.address]);const Xe=i.useCallback(()=>{F(!0),P("select")},[k]),Ht=i.useCallback(()=>{t()},[t]),ke=i.useRef(null);ke.current={batches:Qe,walletAddress:Ae,recipient:Ye,token:Re,chainId:I,amount:D,receiveAmountRaw:Mt,gasFee:Me,isNon7702:x,buildWithdrawBatches:It,gasless:{estimateGasless:je,executeGasless:Ge},ui:{setIsExecuting:Ve,setExecutionError:Ee,setExecutionProgress:lt,setLockedGasFee:ct},executionContextRef:et,isMountedRef:re,onWithdrawExecute:r,onWithdrawSuccess:l,onWithdrawError:d,buildSpicenetBatch:f};const Yt=i.useCallback(()=>(we.current=Date.now(),pr(ke.current)),[]),sn=i.useCallback(()=>(we.current=Date.now(),ll(ke.current)),[]);if(i.useEffect(()=>{if(!e){const te=setTimeout(()=>{P(R()),F(!1),j(null),N(null),L(""),W(!1),H(!1),ie(!1),$(""),Ve(!1),Ee(null),lt(null),et.current=null},300);return()=>clearTimeout(te)}},[e,x]),i.useEffect(()=>{if(!x&&e&&E==="provider-login"&&ee&&_&&Be&&!T){const te=setTimeout(()=>{F(!0),P("select")},100);return()=>clearTimeout(te)}},[x,e,E,ee,_,Be,T,k]),!e)return null;if(E==="provider-login"&&!x)return s.jsx(qs,{onAuthSuccess:Xe,autoTrigger:!0});if(E==="select"&&k){const te=parseFloat(D)||0,se=dt?Js(_t,dt):D||"0",ve=parseFloat(se)||0,qe=ve>0&&ve>st,yt=(I?h.getChainConfig(I):null)?.displayName||"Network",pt=I?dn[I]||On:null,ft=Re?.symbol||"\u2014",ut=Ft,Pe=Re?Js(Mt,Re.decimals):"0",Tt=cr(te,Re?.symbol||fe?.symbol),He=cr(parseFloat(Pe)||0,Re?.symbol||fe?.symbol),X=!z||!q||M.isAddress(q),ye=!x&&te>0&&Re!==null,Ct=!ye||Me!==null&&!Se&&!bt,$e=te>0&&te<fn,it=te>0&&!$e&&!qe&&S!==null&&I!==null&&Re!==null&&Ye&&X&&Ct&&Mt>0n,ht=!it,Ut=S===null?"NO BALANCE":te===0?"ENTER AMOUNT":$e?`MINIMUM ${fn}`:qe?"INSUFFICIENT BALANCE":ye&&!Ct?bt?"GAS UNAVAILABLE":"ESTIMATING GAS":ye&&Mt===0n?"AMOUNT TOO SMALL":"WITHDRAW",on=!!ze&&(ze.step==="success"||ze.step==="error"),V=s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[s.jsx("img",{src:Hs,alt:"","aria-hidden":"true",style:{width:"13px",height:"13px",flexShrink:0,...A?{filter:"invert(0.6)"}:{}}}),s.jsx("p",{style:{fontSize:"13px",color:A?v.textSecondary:"#979AA0",margin:"0",lineHeight:"1.4",fontFamily:'"Helvetica Neue", sans-serif'},children:"Withdraw collateral from your account to 10+ EVM blockchains."})]}),Z='"Helvetica Neue", sans-serif',pe='"IBM Plex Mono", monospace',ae=o?.primaryColor||b.colors.primary,Oe=A?v.cardBg:"#E9E9E9",Ue=A?v.cardBorder:"#C6C6C6",Ze=A?v.textSecondary:"#7D7C7B",rt=A?v.textSecondary:"#71757A",Dt=A?v.textPrimary:"#0E0D0B",qt=A?v.cardBorder:"#C5C5C4",Gt=A?"rgba(255,255,255,0.08)":"#D4D3D3",Xt=170,ln=ut.length>8?"14px":ut.length>6?"16px":"18px",gn=ft.length>8?"14px":ft.length>6?"16px":"18px";return s.jsx(un,{isOpen:!0,onClose:Ht,title:"Withdraw",subtitle:V,styles:o,theme:b,dark:A,maxWidth:"486px",footerLinkText:"Spicenet accounts \u2192",overlayDimmed:!1,closeOnBackdropClick:n,overlayContent:on?s.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:s.jsx("div",{style:{pointerEvents:"auto"},children:s.jsx(Qs,{type:"withdraw",isOpen:!0,isProcessing:vt,onRetryTx:()=>{sn()},onNewTx:()=>{lt(null),L(""),Ee(null),et.current=null},onClose:()=>{lt(null),Ee(null),Ve(!1),et.current=null},onComplete:()=>{lt(null),Ee(null),Ve(!1),et.current=null},results:[{asset:{symbol:Re?.symbol||"Token",address:Re?.address||""},txHash:ze?.txHash||"",success:ze?.step==="success",error:ze?.error,amount:D}],chainName:I?h.getChainName(I):"Network",explorerUrl:I?h.getExplorerUrl(I,"").replace(/\/tx\/.*$/,""):void 0,theme:b})})}):null,children:s.jsxs("div",{style:{width:"402px",margin:"0 auto",padding:"0 0 4px 0",position:"relative"},children:[s.jsx(dl,{show:J,position:Ce,popoverRef:Y,spiceAssets:We,dark:A,dk:v}),s.jsxs("div",{style:{marginTop:"16px",marginBottom:"16px",display:"flex",flexDirection:"column",gap:"16px"},children:[s.jsxs("div",{style:{backgroundColor:Oe,border:`1px solid ${Ue}`,borderRadius:"7px",padding:"14px 16px 12px 16px",minHeight:"138px",display:"flex",flexDirection:"column",gap:"6px",position:"relative"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsx("span",{style:{fontFamily:Z,fontSize:"17px",fontWeight:500,color:Ze,lineHeight:"24px"},children:"Source"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",fontFamily:Z,fontSize:"13px",fontWeight:500,color:rt,lineHeight:"16px"},children:["Balance:"," ",zt?"...":bn(st),s.jsx("button",{type:"button","data-balance-trigger":!0,onClick:Fe=>{Fe.stopPropagation(),jt(Fe.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:s.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"1.5px"},children:[0,1,2].map(Fe=>s.jsx("span",{style:{width:"1.75px",height:"1.75px",borderRadius:"999px",backgroundColor:"#EA4B4B",display:"block"}},Fe))})})]})]}),s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[s.jsxs("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[s.jsx(Sn,{element:"input",ariaLabel:"Withdraw amount",ariaInvalid:qe,dataSpiceflowFocus:!0,value:D,onChange:Fe=>{const At=Fe.target.value;if(At===""){L("");return}/^\d*\.?\d*$/.test(At)&&L(Tn(At.startsWith(".")?`0${At}`:At,dt??S?.decimals))},placeholder:"0.0",fontFamily:Z,color:qe?"#ef4444":D?Dt:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,style:{width:"100%"}}),s.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:rt,fontFamily:Z,marginTop:"10px"},children:Tt})]}),s.jsx("div",{style:{width:`${Xt}px`,flexShrink:0},children:s.jsxs("div",{style:{backgroundColor:"transparent",border:`1px solid ${qt}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[s.jsxs("div",{ref:ge,onClick:Fe=>{if(Fe.stopPropagation(),!O&&ge.current){const At=ge.current.getBoundingClientRect(),Kt=220,en=16;ce({top:At.bottom+8,left:Math.min(Math.max(en,At.right-Kt),window.innerWidth-Kt-en)})}H(At=>!At)},style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px",cursor:"pointer"},children:[s.jsx("img",{src:Bt,alt:ut,style:{width:"24px",height:"24px",borderRadius:"50%"}}),s.jsx("span",{style:{fontSize:ln,fontWeight:500,color:Dt,lineHeight:"1.3",fontFamily:Z,flex:1,minWidth:0,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",letterSpacing:0},children:ut}),s.jsx(pn,{size:15,color:Dt,strokeWidth:2.25})]}),s.jsx(Vo,{isOpen:O,position:ne,title:"SELECT TOKEN",portalAttribute:"token",items:(We||[]).map(Fe=>({id:Fe.receiptTokenId||Fe.address,label:Fe.displaySymbol||Fe.receiptTokenName||Fe.symbol,icon:Ts,detail:bn(Fe.balanceFormatted)})),selectedId:fe?.receiptTokenId||fe?.address||null,onSelect:Fe=>{const At=(We||[]).find(Kt=>(Kt.receiptTokenId||Kt.address)===Fe);At&&(j(At),L("")),H(!1)}}),s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:Gt,borderTop:`1px solid ${qt}`},children:s.jsx("span",{style:{fontSize:"11px",fontWeight:400,color:Dt,fontFamily:Z,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:Ot})})]})})]}),s.jsxs("div",{style:{minHeight:"18px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[qe?s.jsx("span",{style:{fontSize:"12px",color:v.errorText,fontFamily:Z,fontWeight:500},children:"Insufficient Balance"}):s.jsx("span",{}),s.jsx("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0px",minHeight:"32px",marginRight:"-9px"},children:[0,25,50,75,100].map((Fe,At)=>{const Kt=At===4,en=Fe/100,vn=parseFloat(D)||0,Un=st>0&&Math.abs(vn/st*100-Fe)<1;return s.jsx("button",{type:"button","aria-label":`Set amount to ${Fe}%`,"aria-pressed":Un,onClick:()=>{const Ie=st*Fe/100,at=S?.decimals??6,cn=Math.floor(Ie*10**at)/10**at;L(Fe===0?"":cn>0?Mn(cn,at):"")},title:`${Fe}%`,disabled:st===0,"data-spiceflow-focus":!0,style:{width:"32px",height:"32px",padding:"9px",border:"none",backgroundColor:"transparent",cursor:st===0?"not-allowed":"pointer",opacity:Un?1:.5,transition:"opacity 0.15s ease",display:"flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box"},children:s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[s.jsx("circle",{cx:"7",cy:"7",r:"6.84375",fill:Kt?ae:"none",stroke:Kt?ae:A?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!Kt&&en>0&&s.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${en>.5?1:0} 1 ${7+6.84375*Math.sin(en*2*Math.PI)} ${7-6.84375*Math.cos(en*2*Math.PI)} Z`,fill:A?v.textSecondary:"#3C3E42"})]})},Fe)})})]})]}),s.jsxs("div",{style:{backgroundColor:Oe,border:`1px solid ${Ue}`,borderRadius:"7px",padding:"14px 16px 12px 16px",minHeight:"138px",display:"flex",flexDirection:"column",gap:"6px"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsx("span",{style:{fontFamily:Z,fontSize:"17px",fontWeight:500,color:Ze,lineHeight:"24px"},children:"Destination"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",fontFamily:Z,fontSize:"13px",fontWeight:500,color:rt,lineHeight:"16px"},children:["Balance:"," ",zt?"...":bn(st),s.jsx("button",{type:"button","data-balance-trigger":!0,onClick:Fe=>{Fe.stopPropagation(),jt(Fe.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:s.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"1.5px"},children:[0,1,2].map(Fe=>s.jsx("span",{style:{width:"1.75px",height:"1.75px",borderRadius:"999px",backgroundColor:"#EA4B4B",display:"block"}},Fe))})})]})]}),s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[s.jsxs("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[s.jsx(Sn,{element:"div",value:Pe,title:Pe,fontFamily:Z,color:D?Dt:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,overflow:"wrap"}),s.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:rt,fontFamily:Z,marginTop:"10px"},children:He})]}),s.jsxs("div",{style:{width:`${Xt}px`,flexShrink:0,display:"flex",flexDirection:"column",alignItems:"stretch",gap:"8px"},children:[s.jsxs("div",{style:{backgroundColor:"transparent",border:`1px solid ${qt}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px"},children:[s.jsx("img",{src:Re?.logoURI||Ln,alt:ft,style:{width:"24px",height:"24px",borderRadius:"50%"}}),s.jsx("span",{style:{fontSize:gn,fontWeight:500,color:Dt,lineHeight:"1.3",fontFamily:Z,flex:1,minWidth:0,letterSpacing:0},children:ft})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:Gt,borderTop:`1px solid ${qt}`},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[pt&&s.jsx("img",{src:pt,alt:yt,style:{width:"13px",height:"13px",borderRadius:"50%",flexShrink:0}}),s.jsx("span",{style:{fontSize:"11px",fontWeight:400,color:Dt,fontFamily:Z,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:yt})]}),s.jsx("button",{ref:me,onClick:Fe=>{Fe.stopPropagation(),nt(me.current)},style:{background:"none",border:"none",cursor:Ke.length>1?"pointer":"not-allowed",padding:"0 0 0 8px",fontSize:"9.5px",fontFamily:pe,color:rt,textDecoration:"underline",fontWeight:600,opacity:Ke.length>1?1:.45},children:"Switch"}),s.jsx(Vo,{isOpen:Q,position:oe,title:"SELECT NETWORK",portalAttribute:"network",items:Ke.map(Fe=>{const At=h.getChainConfig(Fe);return{id:String(Fe),label:At?.displayName||String(Fe),icon:dn[Fe]||On}}),selectedId:I!==null?String(I):null,onSelect:Fe=>{N(Number(Fe)),W(!1)}})]})]}),s.jsx("div",{style:{minHeight:"14px"}})]})]})]})]}),s.jsxs("div",{style:{marginBottom:b.spacing.sm},children:[s.jsx(fl,{show:le,onToggle:Pt,showCustomAddress:z,setShowCustomAddress:ie,customRecipient:q,setCustomRecipient:$,externalAddress:kt,recipientAddress:Ye,destChainName:yt,destChainLogo:pt,compatibleDestinationChains:Ke,txDetailsChainSwitchRef:ue,onOpenNetworkPopover:nt,sourceChainLabel:Ot,sourceDetailsLogo:Wt,sourceTokenLabel:ut,amount:D,totalSourceDebitDisplay:se,receiveAmountDisplay:Pe,destTokenSymbol:ft,shouldQuoteWithdrawGas:ye,estimatingFee:Se,feeError:bt,displayedGasFee:Lt,selectedDestToken:Re,theme:b,styles:o,dark:A,dk:v}),xe&&s.jsx(Rn,{variant:"error",size:"compact",palette:v,fontFamily:o?.fontFamily||b.typography.fontFamily,style:{marginBottom:"12px"},children:xe}),s.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:()=>{it&&Yt()},disabled:ht||vt,theme:b,dark:A,styles:o,style:{marginTop:"8px"},children:vt?"EXECUTING...":Ut})]})]})})}return null},yr=ml;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 Gn=e=>{const t=Math.round(e*1e5)/1e5;return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:5}).format(t)},Cr=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:a,onDepositClick:l,onWithdrawClick:d,vaultBalance:u,fetchVaultBalance:c,onWithdrawExecute:f,withdrawActionLabel:p,destinationChainId:g,destinationTokenAddress:x,customSections:m,showDefaultSections:y=!0})=>{const C=i.useContext(h.SpiceFlowProviderContext),k=(C?.mode||"7702")!=="7702",b=C?.appName||"Spicenet",{dark:A,primaryColor:v,dk:w,theme:R}=h.useSpiceBrand(n),[E,P]=i.useState(!0),[T,F]=i.useState(!1),[S,j]=i.useState(!1),[I,N]=i.useState(null),{isConnected:D}=Qt.useAccount(),{disconnect:L}=Qt.useDisconnect();i.useEffect(()=>{k&&c&&c().then(U=>{const z=Math.round(U*1e5)/1e5;N(z)}).catch(U=>{console.error("Error fetching vault balance:",U),N(null)})},[k,c]);const Q=()=>{P(!E)},W=i.useMemo(()=>{if(!e.freeCollateralItems)return null;const U=e.freeCollateralItems.filter(q=>q.name==="USDC");if(U.length===0)return null;const z=U.reduce((q,$)=>q+$.balance,0),ie=[];return U.forEach(q=>{q.networks&&q.networks.forEach($=>{($===1||$===11155111||$===8453||$===84532)&&(ie.includes($)||ie.push($))})}),ie.length===0&&ie.push(1,8453),{name:"USDC",totalBalance:z,networks:ie,subtitle:U[0]?.subtitle||"USD COIN"}},[e.freeCollateralItems]),O=i.useMemo(()=>{if(k){if(I!==null)return I;if(u!=null)return u}return e.freeCollateralItems?e.freeCollateralItems.reduce((U,z)=>U+z.balance,0):e.freeCollateral},[k,I,u,e.freeCollateralItems,e.freeCollateral]),H=U=>E?U:"******",J=()=>{L(),F(!1),j(!1)};return s.jsxs("div",{className:o,style:{borderRadius:"16px",backgroundColor:A?w.shell:"#D5D5D5",width:"522px",padding:"8px",fontFamily:n?.fontFamily||'"Helvetica Neue", sans-serif',...n?.container},children:[s.jsxs("div",{style:{background:A?w.cardBg:" white",display:"flex",flexDirection:"column"},children:[s.jsxs("div",{style:{backgroundColor:A?w.inputBg:"#E9E9E9",borderRadius:"0 0 16px 16px",padding:"20px",display:"flex",flexFlow:"column"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"4px"},children:[s.jsxs("p",{style:{fontSize:"14px",fontWeight:500,fontFamily:'"IBM Plex Mono", monospace',color:A?w.textPrimary:"#0E0D0B",margin:0},children:[b.toUpperCase()," BALANCE"]}),D&&s.jsx("button",{onClick:J,"aria-label":"Disconnect wallet",style:{width:"36px",height:"36px",borderRadius:"8px",border:A?`1px solid ${v}33`:"1px solid #E5E7EB",background:A?w.inputBg:"white",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",transition:Jt.interactive,padding:"8px"},onMouseEnter:U=>{U.currentTarget.style.backgroundColor=A?w.cardBg:"#F3F4F6"},onMouseLeave:U=>{U.currentTarget.style.backgroundColor=A?w.inputBg:"white"},children:s.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),s.jsx("polyline",{points:"16 17 21 12 16 7"}),s.jsx("line",{x1:"21",y1:"12",x2:"9",y2:"12"})]})})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.percentageChange!==void 0&&e.percentageChange!==null&&s.jsxs("div",{style:{fontSize:"13px",fontWeight:700,color:e.percentageChange>=0?A?w.successText:"#009C51":A?w.errorText:"#EF4444"},children:[e.percentageChange>=0?"+":"",e.percentageChange.toFixed(2),"%"]}),s.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:U=>{U.currentTarget.style.opacity="0.7"},onMouseLeave:U=>{U.currentTarget.style.opacity="1"},children:E?s.jsxs("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",children:[s.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:A?w.textSecondary:"#1A1A1A",strokeWidth:"2",fill:"none"}),s.jsx("circle",{cx:"12",cy:"12.5",r:"3",stroke:A?w.textSecondary:"#1A1A1A",strokeWidth:"2",fill:"none"})]}):s.jsxs("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",children:[s.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:A?w.textSecondary:"#1A1A1A",strokeWidth:"2",fill:"none"}),s.jsx("path",{d:"M3 3L21 21",stroke:A?w.textSecondary:"#1A1A1A",strokeWidth:"2",strokeLinecap:"round"})]})})]}),s.jsx("p",{style:{fontSize:"40px",fontWeight:700,color:A?w.textPrimary:"black"},children:H(Gn(k&&I!==null?I:k&&u!==void 0&&u!==null?u:e.totalBalance))}),s.jsxs("div",{style:{display:"flex",gap:"12px",marginTop:"16px"},children:[s.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:()=>{l?l():F(!0)},theme:R,dark:A,styles:n,children:"DEPOSIT"}),s.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:()=>{d?d():j(!0)},theme:R,dark:A,styles:n,children:"WITHDRAW"})]})]}),s.jsxs("div",{style:{background:A?w.cardBg:"white",padding:"12px 20px",borderRadius:"12px"},children:[y&&s.jsx(Qo,{title:"FREE COLLATERAL",icon:gl,amount:H(Cr(O)),defaultExpanded:!1,children:k&&(I!==null||u!=null)?s.jsx(ns,{name:"USDC",balance:H(Gn(I!==null?I:u)),subtitle:"USD COIN",icon:Ln,onClick:a?()=>a("usdc-vault"):void 0}):W?s.jsx(ns,{name:W.name,balance:H(Gn(W.totalBalance)),subtitle:W.subtitle,networks:W.networks,icon:Ln,onClick:a?()=>a(W.name):void 0}):e.freeCollateralItems&&e.freeCollateralItems.length>0?e.freeCollateralItems.map((U,z)=>s.jsxs(i.Fragment,{children:[s.jsx(ns,{name:U.name,balance:H(Gn(U.balance)),subtitle:U.subtitle,networks:U.networks,icon:U.name==="USDC"?Ln:void 0,onClick:a?()=>a(U.id):void 0}),z<e.freeCollateralItems.length-1&&s.jsx("div",{style:{height:"1px",backgroundColor:A?w.cardBorder:"#D0D2D8",margin:"4px 0"}})]},U.id)):s.jsx("div",{style:{padding:"12px 0",color:A?w.textSecondary:"#6B7280",fontSize:"13px",fontFamily:'"IBM Plex Mono", monospace'},children:"No collateral items available"})}),m&&m.length>0&&m.filter(U=>U&&U.id&&U.title&&typeof U.title=="string"&&U.title.trim().length>0).map(U=>s.jsx(Qo,{title:U.title,icon:U.icon||void 0,amount:H(Cr(U.totalBalance||0)),defaultExpanded:U.defaultExpanded!==void 0?U.defaultExpanded:!1,children:U.items&&U.items.length>0?U.items.map((z,ie)=>s.jsxs(i.Fragment,{children:[s.jsx(ns,{name:z.name,balance:H(Gn(z.balance)),subtitle:z.subtitle,networks:z.networks,icon:z.name==="USDC"?Ln:void 0,onClick:a?()=>a(z.id):void 0}),ie<U.items.length-1&&s.jsx("div",{style:{height:"1px",backgroundColor:A?w.cardBorder:"#D0D2D8",margin:"4px 0"}})]},z.id||`item-${ie}`)):s.jsx("div",{style:{padding:"12px 0",color:A?w.textSecondary:"#6B7280",fontSize:"13px",fontFamily:'"IBM Plex Mono", monospace'},children:U.emptyMessage||"No items available"})},U.id))]})]}),T&&s.jsx(qo,{isOpen:T,onClose:()=>F(!1),styles:n}),S&&s.jsx(yr,{isOpen:S,onClose:()=>j(!1),styles:n,onWithdrawExecute:f,withdrawActionLabel:p})]})},yl=({options:e,selectedIndex:t,onSelect:n,primaryColor:o,dark:r=!1,textPrimary:a="#111827",textSecondary:l="#6b7280",trackColor:d})=>{const u=e.length-1,c=d||(r?"#3a3a3a":"#d1d5db"),f=r?"4px":"50%",p=r?"none":"2px solid white",g=r?"none":`0 0 0 1px ${o}`;return s.jsxs("div",{style:{width:"100%",userSelect:"none"},children:[s.jsxs("div",{style:{position:"relative",paddingBottom:"4px"},children:[s.jsx("div",{style:{position:"absolute",top:"50%",left:0,right:0,height:"4px",background:c,borderRadius:"2px",transform:"translateY(-50%)",pointerEvents:"none"}}),s.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"}}),s.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=>n(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}})]}),s.jsx("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"6px"},children:e.map((x,m)=>s.jsxs("div",{onClick:()=>n(m),style:{display:"flex",flexDirection:"column",alignItems:m===0?"flex-start":m===u?"flex-end":"center",cursor:"pointer",flex:1},children:[s.jsx("span",{style:{fontSize:"12px",fontWeight:m===t?700:400,color:m===t?a:l,whiteSpace:"nowrap",transition:"color 0.15s, font-weight 0.15s"},children:x.label}),x.highlight&&s.jsx("span",{style:{fontSize:"10px",color:l,whiteSpace:"nowrap"},children:"(most common)"})]},m))}),s.jsx("style",{children:`
|
|
66
|
+
`})]})},Vs=new Set(["WBTC","CBTC"]),Ko=new Set(["btc","wbtc","wcbtc","cbtc"]);function Zo(e,t){return!e||!t?!1:e===t?!0:Vs.has(e)&&Vs.has(t)}function Nn(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 a=o.startsWith("0x")?o.toLowerCase():`0x${o.toLowerCase()}`;return{chainId:r,address:a}}function ss(e){return(e??"").trim().replace(/^test\s+/i,"").replace(/^spice/i,"").toLowerCase().replace(/[^a-z0-9]/g,"")}function Ai(e){return new Set([e.receiptTokenName,e.displaySymbol,e.symbol,e.displayName,e.name].map(ss).filter(Boolean))}function Ei(e,t){const n=Ai(e),o=[t.symbol,t.name,t.equivalenceGroup].map(ss);if(o.some(l=>l&&n.has(l)))return!0;const r=[...n].some(l=>Ko.has(l)),a=o.some(l=>Ko.has(l))||Vs.has(t.equivalenceGroup??"");return r&&a}function Yo(e,t,n){const o=new Set(t.map(ss).filter(Boolean)),r=a=>{if(n&&h.addressesEqual(a.address,n))return 0;const l=[a.symbol,a.name,a.equivalenceGroup].map(ss).findIndex(d=>d&&o.has(d));return l===-1?4:l+1};return[...e].sort((a,l)=>{const d=r(a)-r(l);return d!==0?d:a.address.toLowerCase().localeCompare(l.address.toLowerCase())})}const Xo=typeof process<"u"&&process.env?.NEXT_PUBLIC_MORALIS_API_KEY||typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:Fn&&Fn.tagName.toUpperCase()==="SCRIPT"&&Fn.src||new URL("index.cjs.js",document.baseURI).href}<"u"&&void 0||"",ji="https://deep-index.moralis.io/api/v2.2";function os(e,t){const n=e.chainTokens?Object.keys(e.chainTokens):[],o=[];for(const r of n){const a=Nn(r);if(!a||a.chainId!==t)continue;const l=a.address,d=B.getTokenByAddress(l,t);d&&(!Gs(e,l,t)&&!(e.isUniversal&&Ei(e,d))||o.some(u=>h.addressesEqual(u,l))||o.push(l))}return Yo(o.map(r=>{const a=B.getTokenByAddress(r,t);return{address:r,symbol:a?.symbol,name:a?.name,equivalenceGroup:a?.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 Gs(e,t,n){return e.chainId===n&&h.addressesEqual(e.address,t)?!0:Qn(e.address,e.chainId,t,n)}async function Fi(e,t){const n=h.getClientForChain(e),o=B.getEscrowContractAddress(e);return B.isNativeToken(t)?n.getBalance({address:o}):await n.readContract({address:t,abi:M.erc20Abi,functionName:"balanceOf",args:[o]})}function Jo(e,t,n){const o=B.getTokensForChain(n),r=o.find(l=>h.addressesEqual(l.address,e));if(r)return r;const a=B.getTokenByAddress(e,t);if(a)return Yo(o.filter(l=>Zo(l.equivalenceGroup,a.equivalenceGroup)),[a.symbol,a.name,a.equivalenceGroup])[0]}function rn(e,t){if(e.chainId===t)return e.address;const n=Jo(e.address,e.chainId,t);return n?n.address:null}async function $o(e,t,n={}){const o=rn(e,t),r=os(e,t);if(r.length===0)return o;if(r.length===1)return r[0];const a=n.requiredAmount??0n,l=u=>{const c=r.map(f=>({candidate:f,balance:u.get(B.isNativeToken(f)?"native":f.toLowerCase())??0n})).filter(f=>f.balance>0n).sort((f,p)=>f.balance===p.balance?0:f.balance>p.balance?-1:1);return c.length===0?null:((a>0n?c.find(f=>f.balance>=a):c[0])??c[0]).candidate},d=h.getChainsForAssets()[t];if(d?.moralisName&&Xo){const u=new Map,c=r.some(f=>B.isNativeToken(f));try{if(c)try{const p=h.getClientForChain(t),g=B.getEscrowContractAddress(t);u.set("native",await p.getBalance({address:g}))}catch{}const f=await fetch(`${ji}/wallets/${B.getEscrowContractAddress(t)}/tokens?chain=${d.moralisName}`,{headers:{"X-API-Key":Xo}});if(f.ok){const p=await f.json();for(const x of p?.result||[]){const m=String(x.token_address||"").toLowerCase();if(m)try{u.set(m,BigInt(String(x.balance||"0")))}catch{}}const g=l(u);if(g)return g}}catch{}}try{const u=await Promise.all(r.map(async p=>({key:B.isNativeToken(p)?"native":p.toLowerCase(),value:await Fi(t,p)}))),c=new Map(u.map(({key:p,value:g})=>[p,g])),f=l(c);if(f)return f}catch{}return o}function Qn(e,t,n,o){const r=B.getTokenByAddress(e,t),a=B.getTokenByAddress(n,o);return r&&a?Zo(r.equivalenceGroup,a.equivalenceGroup):B.areEquivalent(e,n)}function rs(e,t){return Qn(e.address,e.chainId,t.address,t.chainId)}const Bi={usdc:[8453,1,42161,5115,4114],usdt:[1],btc:[4114,42161,1,5115],wbtc:[1],weth:[8453,1],ctusd:[5115,4114],wcbtc:[5115,4114]},Ti={btc:["wcbtc","cbtc","wbtc"]};function as(e){return e.replace(/^test\s+/i,"").replace(/^spice/i,"").trim()}function hn(e){return as(e).toLowerCase()}function _o(e){return hn(e??"").replace(/[^a-z0-9]/g,"")}function Ks(e){const t=hn(e);return[t,...Ti[t]??[]].filter(Boolean)}function Mi(e){try{return BigInt(e.balanceAvailable||"0")}catch{return 0n}}function Ri(e){return Array.isArray(e.chainTokens)?e.chainTokens:Object.keys(e.chainTokens??{})}function Di(e,t,n,o=[]){const r=h.getChainConfig(t),a=n.toLowerCase(),l=a===B.ZERO_ADDRESS.toLowerCase()?r?.nativeCurrency.decimals??18:r?.supportedTokens?.find(u=>u.address.toLowerCase()===a)?.decimals??18,d=new Set(o.map(_o).filter(Boolean));return e.reduce((u,c)=>{const f=Mi(c),p=c.decimals??l,g=B.convertAmountBetweenDecimals(f,p,l);if(Ri(c).some(m=>{const y=Nn(m);return y&&Qn(y.address,y.chainId,n,t)}))return u+g;if(d.size===0)return u;const x=_o(c.tokenName||c.receiptToken);return d.has(x)?u+g:u},0n)}function Ni(e,t){const n=new Set([...Ks(t),...Ks(as(t))]);return[...e].sort((o,r)=>{const a=hn(o.symbol),l=hn(r.symbol),d=hn(o.name),u=hn(r.name),c=n.has(a)?0:n.has(d)?1:2,f=n.has(l)?0:n.has(u)?1:2;return c!==f?c-f:o.address.toLowerCase().localeCompare(r.address.toLowerCase())})[0]}function Pi(e){const t=e&&e.length>0?e:Object.keys(h.CHAIN_CONFIGS).map(Number).filter(Number.isFinite),n=new Map;for(const o of t){const r=h.getChainConfig(o);if(!r)continue;const a=`${o}:${B.ZERO_ADDRESS.toLowerCase()}`;n.has(a)||n.set(a,{address:B.ZERO_ADDRESS,chainId:o,symbol:r.nativeCurrency.symbol,name:r.nativeCurrency.name,decimals:r.nativeCurrency.decimals,isNative:!0,logoURI:r.logo});for(const l of r.supportedTokens??[]){const d=l.address.toLowerCase(),u=`${o}:${d}`;n.has(u)||n.set(u,{address:d,chainId:o,symbol:l.symbol,name:l.name,decimals:l.decimals,isNative:B.isNativeToken(d),logoURI:l.logo})}}return n}function Wi(e,t){const n=Pi(t),o=as(e.tokenName),r=hn(e.tokenName),a=Ks(e.tokenName),l=Array.isArray(e.chainTokens)?e.chainTokens.map(m=>[m,void 0]):Object.entries(e.chainTokens??{}),d=l.map(([m])=>Nn(m)).filter(m=>m!==null),u=new Map(l.map(([m,y])=>[m,y])),c=(m,y)=>{const C=u.get(`evm:${y.chainId}:${y.address.slice(2).toLowerCase()}`);return{...m,name:typeof C?.name=="string"&&C.name.length>0?C.name:m.name,decimals:typeof C?.decimals=="number"?C.decimals:m.decimals}},f=d.map(m=>{const y=n.get(`${m.chainId}:${m.address.toLowerCase()}`);return y?c(y,m):void 0}).filter(m=>m!==void 0),p=Bi[r]??[];if(p.length>0)for(const m of p){const y=f.find(C=>C.chainId===m);if(y)return y}if(f.length>0)return Ni(f,e.tokenName);const g=Array.from(n.values()).filter(m=>a.includes(hn(m.symbol))||a.includes(hn(m.name)));if(p.length>0)for(const m of p){const y=g.find(C=>C.chainId===m);if(y)return y}if(g.length>0)return g[0];const x=d[0];if(x){const m=u.get(`evm:${x.chainId}:${x.address.slice(2).toLowerCase()}`);return{address:x.address,chainId:x.chainId,symbol:o||e.tokenName,name:typeof m?.name=="string"&&m.name.length>0?m.name:o||e.tokenName,decimals:typeof m?.decimals=="number"?m.decimals:e.decimals??18,isNative:B.isNativeToken(x.address),logoURI:void 0}}}function Ui(e,t){let n;try{n=BigInt(e.balanceAvailable||"0")}catch{return null}if(n<=0n)return null;const o=Wi(e,t),r=o?.decimals??e.decimals??18,a=e.decimals??r,l=B.convertAmountBetweenDecimals(n,a,r),d=o?.address??B.ZERO_ADDRESS,u=o?.chainId??0,c=as(e.tokenName),f=o?.symbol??c,p=o?.name??c,g=parseFloat(M.formatUnits(l,r)),x=typeof e.balanceUsd=="number"?e.balanceUsd:typeof e.balanceUsd=="string"&&Number(e.balanceUsd)||0;return{address:d,symbol:f,name:p,decimals:r,chainId:u,balance:l,balanceFormatted:g,balanceUsd:x,isNative:o?.isNative??B.isNativeToken(d),logoURI:o?.logoURI,displaySymbol:e.tokenName||f,displayName:e.tokenName||p,displayChainName:"Spicenet",receiptTokenId:e.receiptToken,receiptTokenName:e.tokenName||p,receiptTokenDecimals:a,chainTokens:e.chainTokens&&!Array.isArray(e.chainTokens)?e.chainTokens:void 0,isUniversal:!0}}function zi(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 Vn=({address:e,supportedChains:t,enabled:n=!0,refetchInterval:o})=>{const r=i.useContext(h.SpiceFlowProviderContext)?.apiUrl||h.RELAYER_API_URL,[a,l]=i.useState([]),[d,u]=i.useState(!1),[c,f]=i.useState(null),[p,g]=i.useState(!1),x=i.useRef(!1),m=i.useRef(!1),y=t?JSON.stringify([...t].sort()):"",C=i.useCallback(async(A=!1)=>{if(!e||!n){l([]),g(!1),x.current=!1;return}if(!m.current){m.current=!0,!x.current&&!A&&u(!0),f(null);try{const v=await fetch(`${r}/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 R=w.balances.map(E=>Ui({receiptToken:typeof E.receiptToken=="string"?E.receiptToken:void 0,tokenName:String(E.tokenName??""),balanceAvailable:String(E.balanceAvailable??"0"),chainTokens:zi(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);l(R),g(R.length>0),x.current=!0}else l([]),g(!1)}catch(v){const w=v instanceof Error?v.message:"Failed to fetch balance";f(w),console.error("Error fetching Spice assets:",v),x.current||(l([]),g(!1))}finally{u(!1),m.current=!1}}},[e,n,y,r]);i.useEffect(()=>{n&&e&&(x.current=!1,C(!1))},[e,n,y]),i.useEffect(()=>{if(!n||!e||!o)return;const A=setInterval(()=>{C(!0)},o);return()=>clearInterval(A)},[e,n,o,y]);const k=i.useCallback(A=>a.filter(v=>v.chainId===A),[a]),b=i.useCallback(async()=>{await C(!0)},[C]);return{assets:a,loading:d,error:c,hasBalance:p,refetch:b,getAssetsByChain:k}};function Oi(e){let t=!1;const n=e.map(o=>o.from!=="solver"?o:(t=!0,{...o,from:"escrow"}));return t&&console.warn("[Spiceflow] Normalized from:'solver' delivery transfer to from:'escrow' (7702 mode)."),t?n:e}const er=e=>new Promise(t=>setTimeout(t,e));function Li(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 Hi=350,qi=2500;async function Qi(e){const{actionId:t,intentIndex:n,intentId:o,stepIndex:r,maxPolls:a=48,maxExecuteAttempts:l=3,pollsBeforeRetry:d=5,maxConsecutiveStatusErrors:u=15,onStatusMessage:c,signal:f,chainId:p}=e;let g="pending",x,m,y=0,C=0;const k=()=>{y++,h.relayerService.executeStep(t,n,r,{action:"execute"}).then(b=>{b.transactionHash&&(x=b.transactionHash)}).catch(b=>{const A=b instanceof Error?b.message:String(b);console.warn(`[execution] executeStep ${r} attempt ${y} error (will poll):`,A)})};k();for(let b=0;b<a;b++){if(await er(b===0?Hi:qi),f?.aborted)throw new h.SpiceflowError("ABORT","Gasless transaction aborted");try{const v=await h.relayerService.checkStepStatus(o,r);C=0,g=v.data.status,m=v.data.error;const w=v.data.transactionHash;w&&(x=w)}catch(v){if(v instanceof Error&&(v.name==="AbortError"||v instanceof h.SpiceflowError&&v.code==="ABORT")||(C++,C>=u))throw v;continue}if(g==="created"&&b>=y*d&&y<l&&k(),g==="reverted"||g==="error")throw new h.SpiceflowError("ON_CHAIN_REVERT",Li(g,m),{status:g,txHash:x,actionId:t,intentId:o,stepId:r,chainId:p});if(g==="success"||g==="completed")return x;let A="Waiting for solver...";g==="executing"?A="Transaction executing...":g==="submitted"?A="Transaction submitted...":g==="created"&&(A="Waiting for relayer..."),c?.(A,x)}throw new h.SpiceflowError("POLLING_EXHAUSTED",`Transaction is still processing (status: ${g}). 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:g,pollAttempts:a,maxPolls:a,txHash:x})}async function tr(e){const{actionId:t,intentIndex:n,intentId:o,totalSteps:r,delayBeforeSpicenetStepMs:a=5e3,isSpicenetStep:l,maxExecuteAttemptsForStep:d,maxPolls:u=48,onStatusMessage:c,signal:f}=e;let p;for(let g=0;g<r;g++){g>0&&l?.(g)&&a>0&&await er(a);const x=d?.(g)??3,m=await Qi({actionId:t,intentIndex:n,intentId:o,stepIndex:g,maxPolls:u,maxExecuteAttempts:x,maxConsecutiveStatusErrors:x===6?5:15,onStatusMessage:c,signal:f});m&&(p=m)}return p}function is(e,t){return e<=0n||t<=0n?0n:(e*t+10000n-1n)/10000n}function $t(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 nr(e){const t=BigInt(e.quotedAmount),n=BigInt(e.totalDebit),{totalFee:o}=$t(e);return t>0n||n>0n||o>0n}function Vi(e){const t=BigInt(e.quotedAmount),n=BigInt(e.totalDebit),{totalFee:o}=$t(e),r=t+o;return n>r?n:r}function Gi(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 An(e,t){const n=e.intents.flatMap(c=>c.batches).filter(nr);if(n.length===0||n.length>1&&t.actionAmount===void 0)return null;let o=0n,r=0n,a=0n,l=0n;for(const c of n){const f=$t(c);o+=f.gasFee,r+=f.spicenetFee,a+=f.bridgeFee,l+=f.totalFee}const d=n.some(c=>c.gasQuoteSource==="estimated")?"estimated":n.some(c=>c.gasQuoteSource==="configured_fallback")?"configured_fallback":n[0].gasQuoteSource,u=t.actionAmount??BigInt(n[0].quotedAmount);return{symbol:t.symbol,decimals:t.decimals,grossAmount:u+l,netAmount:u,totalFee:l,spicenetFee:r,gasFee:o,bridgeFee:a,gasQuoteSource:d}}function wn(e,t){const n=e.intents.flatMap(f=>f.batches).filter(nr);if(n.length===0)return null;const o=n.filter(f=>f.chainId===t.chainId),r=o.length>0?o:n;if(r.length>1)return null;const a=r[0],{gasFee:l,spicenetFee:d,bridgeFee:u,totalFee:c}=$t(a);return{chainId:a.chainId,tokenAddress:t.tokenAddress,symbol:t.symbol,decimals:t.decimals,grossAmount:Vi(a),netAmount:BigInt(a.quotedAmount),totalFee:c,gasFee:l,spicenetFee:d,bridgeFee:u,gasQuoteSource:a.gasQuoteSource}}const Ki=10n,Zi=5;function ls(e){return e.map(t=>({...t,calls:[...t.calls],tokenTransfers:t.tokenTransfers?[...t.tokenTransfers]:void 0}))}function cs({token:e,recipient:t,amount:n}){return{to:e,value:0n,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[t,n]})}}function sr({chainBatches:e,token:t,amount:n}){const o=ls(e),r=o[o.length-1];if(!r)return o;const a=B.getEscrowContractAddress(r.chainId);return r.calls=[...r.calls,cs({token:t,recipient:a,amount:n})],o}function or({chainBatches:e,user:t,token:n,grossAmount:o,gasFee:r}){const a=ls(e),l=a[a.length-1];if(!l)throw new h.SpiceflowError("INVALID_PARAMS","Action-output escrow funding requires at least one chain batch.");const d=is(o,Ki),u=r+d;if(u>=o)throw new h.SpiceflowError("INVALID_PARAMS","Borrow amount is too small after gas and Spicenet fees.",{grossAmount:o.toString(),gasFee:r.toString(),spicenetFee:d.toString()});const c=o-u,f=B.getEscrowContractAddress(l.chainId),p=[];return r>0n&&p.push(cs({token:n,recipient:B.SPICE_GAS_FEE_RECIPIENT,amount:r})),d>0n&&p.push(cs({token:n,recipient:B.SPICE_PLATFORM_FEE_RECIPIENT,amount:d})),l.calls=[...l.calls,...p,cs({token:n,recipient:f,amount:c})],l.tokenTransfers=[...l.tokenTransfers??[],...r>0n?[{from:t,to:B.SPICE_GAS_FEE_RECIPIENT,token:n,amount:r}]:[],...d>0n?[{from:t,to:B.SPICE_PLATFORM_FEE_RECIPIENT,token:n,amount:d}]:[],{from:t,to:f,token:n,amount:c}],{chainBatches:a,gasFee:r,spicenetFee:d,netEscrowAmount:c,outputCredit:{chainId:l.chainId,token:n,amount:o}}}async function rr({chainBatches:e,user:t,token:n,grossAmount:o,chainAuthorizations:r}){let a=0n,l=or({chainBatches:e,user:t,token:n,grossAmount:o,gasFee:a});for(let d=0;d<Zi;d+=1){const u=B.hashChainBatches(l.chainBatches),c=(await h.relayerService.estimateBatchGas({user:t,outputToken:n,chainBatches:l.chainBatches.map((f,p)=>({...f,hash:u[p].hash})),chainAuthorizations:r})).gasFee;if(c===a)return l;a=c,l=or({chainBatches:e,user:t,token:n,grossAmount:o,gasFee:a})}throw new h.SpiceflowError("INVALID_PARAMS","Action-output fee estimate did not converge. Please retry.")}function En(e){return B.isSpicenetChainId(e.chainId)}function Yi(e,t){if(e.length!==t.length)return!1;const n=B.hashChainBatches(e),o=B.hashChainBatches(t);return n.every((r,a)=>r.hash===o[a]?.hash)}const ar="0xa9059cbb";function ds(e,t){return`${e}:${t.toLowerCase()}`}function ir(e,t){return t===B.ZERO_ADDRESS.toLowerCase()?{symbol:h.getChainName(e),decimals:18}:B.getTokenByAddress(t,e)??{symbol:"tokens",decimals:18}}function Xi(e,t){const n=B.getTokenByAddress(t,e);return[n?.equivalenceGroup,n?.symbol,n?.name]}async function Ji(e){return h.getWalletBalanceEntries(e)}function Zs(e,t){return e.map(n=>{if(En(n)||n.calls.length===0)return n;const o=new Set((n.tokenTransfers??[]).filter(a=>(a.from==="escrow"||a.from==="solver")&&h.addressesEqual(a.to,t)).map(a=>a.token.toLowerCase()));if(o.size===0)return n;let r=0;for(const a of n.calls){if(!a.data?.startsWith(ar))break;try{const l=M.decodeFunctionData({abi:h.P,data:a.data});if(l.functionName!=="transfer")break;const[d]=l.args;if(h.addressesEqual(d,t)||!o.has(a.to.toLowerCase()))break;r+=1}catch{break}}return r===0?n:{...n,calls:n.calls.slice(r)}})}async function $i(e,t,n){const o=new Map,r=new Map,a=new Map,l=new Map;for(const u of n?.actionOutputCredits??[]){const c=ds(u.chainId,u.token);l.set(c,(l.get(c)??0n)+u.amount)}for(const u of e)if(!En(u)){for(const c of u.tokenTransfers??[]){if(c.from!=="escrow"&&c.from!=="solver"||!h.addressesEqual(c.to,t))continue;const f=BigInt(c.amount??0);if(f<=0n)continue;const p=ds(u.chainId,c.token);r.set(p,(r.get(p)??0n)+f),c.from==="escrow"&&a.set(p,(a.get(p)??0n)+f)}for(const c of u.calls){if(c.value&&c.value>0n){const f=ds(u.chainId,B.ZERO_ADDRESS);o.set(f,(o.get(f)??0n)+c.value)}if(c.data?.startsWith(ar))try{const f=M.decodeFunctionData({abi:h.P,data:c.data});if(f.functionName!=="transfer")continue;const[,p]=f.args,g=c.to.toLowerCase(),x=ds(u.chainId,g);o.set(x,(o.get(x)??0n)+p)}catch{}}}let d=null;for(const[u,c]of a){if(c<=0n)continue;const[f,p]=u.split(":"),g=Number(f),x=ir(g,p);d??(d=await Ji(t));const m=Di(d,g,p,Xi(g,p));if(!(m>=c))throw new h.SpiceflowError("INVALID_PARAMS",`Insufficient Spice ${x.symbol}: needs ${M.formatUnits(c,x.decimals)}, has ${M.formatUnits(m,x.decimals)}.`,{chainId:g,token:p,userAddress:t,requiredAmount:c.toString(),balance:m.toString(),balanceSource:"spice"})}for(const[u,c]of o){if(c<=0n)continue;const[f,p]=u.split(":"),g=Number(f),x=c-(r.get(u)??0n)-(l.get(u)??0n);if(x<=0n)continue;const m=h.getClientForChain(g),y=p===B.ZERO_ADDRESS.toLowerCase()?await m.getBalance({address:t}):await m.readContract({address:p,abi:h.P,functionName:"balanceOf",args:[t]});if(y>=x)continue;const C=ir(g,p);throw new h.SpiceflowError("INVALID_PARAMS",`Insufficient ${C.symbol} on ${h.getChainName(g)}: needs ${M.formatUnits(x,C.decimals)}, has ${M.formatUnits(y,C.decimals)}.`,{chainId:g,token:p,userAddress:t,requiredAmount:x.toString(),balance:y.toString(),balanceSource:"wallet"})}}function _i({chainBatches:e,tokenAddress:t,tokenTransferAmount:n,useCustomTransfers:o}){if(!(e.some(En)||!(o?e.some(r=>En(r)?!1:(r.tokenTransfers??[]).some(a=>a.from==="escrow"&&BigInt(a.amount??0)>0n)):n>0n)))throw new h.SpiceflowError("INVALID_PARAMS","Payouts funded from Spice balance require a Spicenet funding batch before the destination chain batch. Deposits into Spice balance and gas-only actions do not need one.",{tokenAddress:t,tokenTransferAmount:n.toString(),useCustomTransfers:!!o})}function el(e,t,n,o){t.forEach((r,a)=>{if(!r.to||!r.from||!r.token||r.amount===void 0)throw new h.SpiceflowError("INVALID_TOKEN_TRANSFER",`tokenTransfers[${a}] 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:a,transfer:{from:r.from,to:r.to,token:r.token,amount:r.amount?.toString()},signingAddress:n,useCustomTransfers:o})})}function Ys({user:e,chainBatches:t,tokenAddress:n,tokenTransferAmount:o,exp:r,signature:a,chainAuthorizations:l,useCustomTransfers:d}){const u=t,c=B.hashChainBatches(u),f=u.filter(p=>!En(p)).length;if(_i({chainBatches:u,tokenAddress:n,tokenTransferAmount:o,useCustomTransfers:d}),!d&&o>0n&&f>1)throw new h.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:f,tokenAddress:n,tokenTransferAmount:o.toString()});return{user:e,...l?{chainAuthorizations:l}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:a,nbf:0,exp:r,chainBatches:c.map((p,g)=>{const x=u[g],m=En(x)?[]:d?Oi(x.tokenTransfers??[]):o>0n?[{from:"escrow",to:e,token:n,amount:o}]:[];return el(Number(p.chainId),m,e,d),{hash:p.hash,chainId:Number(p.chainId),tokenTransfers:m,calls:p.calls}})}]}}function tl(e,t){const n=B.hashChainBatches(e).map(o=>o.hash);return M.keccak256(M.encodeAbiParameters([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,t,n]))}let Xs=!1;function Pn(){const{address:e,isConnected:t,isAuthenticated:n,actions:o}=h.useWallet(),[r,a]=i.useState(null),l=i.useRef(o),d=i.useRef(new Map);l.current=o;const u=i.useCallback(async(g,x,m)=>{const y=[...new Set(g.filter(b=>!En(b)).map(b=>b.chainId))],C=await Promise.all(y.map(async b=>{const A=h.getClientForChain(b),v=h.getDelegateContractAddress(b),w=Number(await B.getAccountNonce(x,A)),R=[x.toLowerCase(),b,v.toLowerCase(),w].join(":");return{chainId:b,delegateContract:v,nonce:w,cacheKey:R,cached:d.current.get(R)}})),k=[];for(const{chainId:b,delegateContract:A,nonce:v,cacheKey:w,cached:R}of C){if(R){k.push(R);continue}if(m?.aborted)throw new h.SpiceflowError("ABORT","Gasless transaction aborted");const E=await l.current.signAuthorization({contractAddress:A,chainId:b,nonce:v}),P={r:E.r,s:E.s,yParity:E.yParity,address:E.address??A,chainId:Number(E.chainId??b),nonce:Number(E.nonce??v)};d.current.set(w,P),k.push(P)}return k},[]),c=i.useCallback(async(g,x,m)=>{if(m?.aborted)throw new h.SpiceflowError("ABORT","Gasless transaction aborted");const y=await l.current.signMessage({raw:tl(g,x)}),C=typeof y=="string"?y:y.signature;if(!C)throw new h.SpiceflowError("SIGNATURE_FAILED","Failed to sign intent authorization. The wallet returned an empty signature.");return C},[]),f=i.useCallback(async(g,x,m,y,C,k)=>{const b=(A,v,w)=>{y?.({step:A,message:v,...w})};if(Xs)throw new h.SpiceflowError("CONCURRENT_EXECUTION","A gasless transaction is already in progress. Please wait.");Xs=!0;try{if(!e)throw new h.SpiceflowError("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const A=k?.userOverride||e,v=k?.depositToEscrow?.gasFundingSource==="action-output"?k.depositToEscrow:null;let w=k?.depositToEscrow&&!v?sr({chainBatches:g,token:k.depositToEscrow.token,amount:k.depositToEscrow.amount}):ls(g),R=[],E=k?.useCustomTransfers;b("signing-delegation","Sign delegation in your wallet...");const P=await u(w,A,C);if(C?.aborted)throw new h.SpiceflowError("ABORT","Gasless transaction aborted");const T=BigInt(Math.floor(Date.now()/1e3)+3600);if(v){const O=await rr({chainBatches:g,user:A,token:v.token,grossAmount:v.amount,chainAuthorizations:P});w=O.chainBatches,R=[O.outputCredit],E=!0}if(!k?.skipPreSubmitFeeEstimate){let O=!1;for(let H=0;H<10;H++){const J=k?.feeExecutionMode==="user-transfer"?Zs(w,A):w,U=Ys({user:A,chainBatches:J,tokenAddress:x,tokenTransferAmount:m,exp:Number(T),signature:"0x00",chainAuthorizations:P,useCustomTransfers:E}),z=await h.relayerService.estimateActionFees(U);a(z);const ie=await k?.adjustBatchesForEstimate?.({feeEstimate:z,chainBatches:w}),q=!!ie&&Yi(w,ie);if(!ie||q){O=!0;break}w=ie}if(!O)throw new h.SpiceflowError("INVALID_PARAMS","Fee estimate did not converge. Please retry.")}k?.skipUserFundingPreflight||await $i(w,A,{actionOutputCredits:R}),b("signing-intent","Sign the intent in your wallet...");const F=await c(w,T,C);if(C?.aborted)throw new h.SpiceflowError("ABORT","Gasless transaction aborted");b("submitting","Submitting to relayer...");const S=Ys({user:A,chainBatches:w,tokenAddress:x,tokenTransferAmount:m,exp:Number(T),signature:F,chainAuthorizations:P,useCustomTransfers:E}),j=await h.relayerService.createAction(S),[I,N]=j.intentIds[0].split("/"),D=parseInt(N||"0",10),L=`${I}/${D}`;b("executing","Executing on chain..."),b("executing","Executing on chain...",{actionId:I,intentId:L,intentIndex:D,totalSteps:w.length});const Q=w.length,W=await tr({actionId:I,intentIndex:D,intentId:L,totalSteps:Q,signal:C,isSpicenetStep:O=>w[O]?.domain==="spicenet",maxExecuteAttemptsForStep:O=>w[O]?.domain==="spicenet"?6:3,maxPolls:180,onStatusMessage:(O,H)=>{b("executing",O,{txHash:H,actionId:I,intentId:L,intentIndex:D,totalSteps:Q})}});return b("success","Transaction successful!",{txHash:W,actionId:I,intentId:L,intentIndex:D,totalSteps:Q}),W||I}catch(A){throw console.error("[GaslessExecution] Error:",A),b("error",A.message||"Transaction failed",{error:A.message}),A}finally{Xs=!1}},[e,n,u,c]),p=i.useCallback(async(g,x,m,y)=>{if(!e)throw new h.SpiceflowError("WALLET_DISCONNECTED","No wallet connected. Please log in first.");const C=y?.userOverride||e,k=y?.depositToEscrow?.gasFundingSource==="action-output"?y.depositToEscrow:null;let b=y?.depositToEscrow&&!k?sr({chainBatches:g,token:y.depositToEscrow.token,amount:y.depositToEscrow.amount}):ls(g);const A=y?.feeExecutionMode==="user-transfer"?Zs(b,C):b,v=y?.signAuthorizationsForEstimate?await u(A,C):void 0;let w=y?.useCustomTransfers;k&&(b=(await rr({chainBatches:g,user:C,token:k.token,grossAmount:k.amount,chainAuthorizations:v})).chainBatches,w=!0);const R=y?.feeExecutionMode==="user-transfer"?Zs(b,C):b,E=Ys({user:C,chainBatches:R,tokenAddress:x,tokenTransferAmount:m,exp:Math.floor(Date.now()/1e3)+3600,signature:"0x00",chainAuthorizations:v,useCustomTransfers:w}),P=await h.relayerService.estimateActionFees(E);return a(P),P},[e,u]);return{executeGasless:f,estimateGasless:p,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 Js(e,t){return M.formatUnits(e,t).replace(/(\.\d*?[1-9])0+$|\.0+$/,"$1")}function lr(e,t,n){return t===n?e:t<n?e*10n**BigInt(n-t):e/10n**BigInt(t-n)}function cr(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 sl(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 ol(e){const t=e.find(n=>B.isSpicenetChainId(n.chainId))?.calls?.[0]?.data;if(!t)return null;try{const n=M.decodeFunctionData({abi:B.spicenetAbi,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 rl(e,t,n){if(e===t)return!0;const o=e>t?e:t;return o===0n?!1:(e>t?e-t:t-e)*10000n<=o*n}function al(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()?!1:n.recipient.toLowerCase()===B.SPICE_GAS_FEE_RECIPIENT.toLowerCase()?rl(n.amount,r.amount,100n):n.amount===r.amount})}function il(e,t){const n=e.intents.flatMap(a=>a.batches).filter(a=>{const l=$t(a);return BigInt(a.quotedAmount)>0n||BigInt(a.totalDebit)>0n||l.totalFee>0n}),o=n.filter(a=>a.chainId===t),r=o.length>0?o:n;return r.length===1?r[0]:null}function ll(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const o=n.token.toLowerCase(),r=n.recipient.toLowerCase(),a=`${o}:${r}`,l=t.get(a);l?l.amount+=n.amount:t.set(a,{...n})}return[...t.values()]}function dr(e,t){if(!e.token||!e.recipient||e.chainId===null)return null;const n=il(t,e.chainId);if(!n)return null;const{gasFee:o,bridgeFee:r,spicenetFee:a}=$t(n),l=o+r,d=[{token:e.token.address,recipient:e.recipient,amount:e.receiveAmountRaw}];return l>0n&&d.push({token:e.token.address,recipient:B.SPICE_GAS_FEE_RECIPIENT,amount:l}),a>0n&&d.push({token:e.token.address,recipient:B.SPICE_PLATFORM_FEE_RECIPIENT,amount:a}),ll(d)}function ur(e,t,n){const o=dr(e,t);return!o||al(ol(n),o)?null:e.buildWithdrawBatches(o)}async function pr(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(r=>B.isSpicenetChainId(r.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};if(e.buildSpicenetBatch){const r=await e.gasless.estimateGasless(t,n,0n,{...o,adjustBatchesForEstimate:({feeEstimate:d,chainBatches:u})=>ur(e,d,u)}),a=dr(e,r);a&&(t=e.buildWithdrawBatches(a));const l=r.intents[0]?.batches.find(d=>d.chainId===e.chainId)??r.intents[0]?.batches[0]??null;l&&e.ui.setLockedGasFee($t(l).totalFee)}else{const r=(await e.gasless.estimateGasless(t,n,0n,o)).intents[0]?.batches[0]??null;r&&e.ui.setLockedGasFee($t(r).totalFee)}await e.gasless.executeGasless(t,n,0n,r=>{r.actionId&&r.intentId&&typeof r.intentIndex=="number"&&typeof r.totalSteps=="number"&&(e.executionContextRef.current={actionId:r.actionId,intentId:r.intentId,intentIndex:r.intentIndex,totalSteps:r.totalSteps}),e.ui.setExecutionProgress(r)},void 0,e.buildSpicenetBatch?{...o,adjustBatchesForEstimate:({feeEstimate:r,chainBatches:a})=>ur(e,r,a)}:o)}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 cl(e){const t=e.executionContextRef.current;if(!t){e.ui.setExecutionProgress(null),await pr(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 h.relayerService.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",a;try{const l=await h.relayerService.executeStep(t.actionId,t.intentIndex,o,{action:"execute"});l.transactionHash&&(a=l.transactionHash)}catch{}for(let l=0;l<120;l++){if(await new Promise(u=>setTimeout(u,Math.min(1e3+l*1e3,5e3))),!e.isMountedRef.current)return;const d=await h.relayerService.checkStepStatus(t.intentId,o);if(!e.isMountedRef.current)return;if(r=d.data.status,d.data.transactionHash&&(a=d.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:a,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:a,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 dl(e){const t=await e.estimateGasless(e.batches,e.tokenAddress,0n,{useCustomTransfers:!0}),n=t.intents.flatMap(r=>r.batches).filter(r=>$t(r).totalFee>0n),o=n.filter(r=>r.chainId===e.chainId)[0]??n[0]??t.intents[0]?.batches[0];if(!o)throw new Error("No gas fee estimate was returned for this withdraw.");return $t(o).totalFee}const fr='"IBM Plex Mono", monospace',hr='"Helvetica Neue", sans-serif',ul=({show:e,position:t,popoverRef:n,spiceAssets:o,dark:r,dk:a})=>{if(!e||!t)return null;const l=r?a.textSecondary:"#71757A",d=r?a.textPrimary:"#0E0D0B",u=o||[];return s.jsxs("div",{ref:n,"data-balance-popover":!0,style:{position:"fixed",top:`${t.top}px`,left:`${t.left}px`,width:"220px",background:r?a.cardBg:"#FFFFFF",border:`1px solid ${r?a.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:[s.jsx("div",{style:{fontFamily:fr,fontSize:"11px",letterSpacing:"0.05em",color:l,marginBottom:"8px"},children:"ALL BALANCES"}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:u.length>0?u.map(c=>{const f=c.displaySymbol||c.receiptTokenName||c.symbol;return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"10px",padding:"6px 0"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0},children:[c.logoURI?s.jsx("img",{src:c.logoURI,alt:f,style:{width:"18px",height:"18px",borderRadius:"50%",flexShrink:0}}):s.jsx("div",{style:{width:"18px",height:"18px",borderRadius:"50%",border:`1px solid ${r?a.cardBorder:"#C8C8C8"}`,flexShrink:0}}),s.jsx("span",{style:{fontFamily:hr,fontSize:"13px",color:d,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:f})]}),s.jsx("span",{style:{fontFamily:fr,fontSize:"12px",color:d,flexShrink:0},children:bn(c.balanceFormatted)})]},c.receiptTokenId||c.address)}):s.jsx("span",{style:{fontFamily:hr,fontSize:"13px",color:l},children:"No balances"})})]})},pl='"Helvetica Neue", sans-serif',kn='"IBM Plex Mono", monospace',fl=({show:e,onToggle:t,showCustomAddress:n,setShowCustomAddress:o,customRecipient:r,setCustomRecipient:a,externalAddress:l,recipientAddress:d,destChainName:u,destChainLogo:c,compatibleDestinationChains:f,txDetailsChainSwitchRef:p,onOpenNetworkPopover:g,sourceChainLabel:x,sourceDetailsLogo:m,sourceTokenLabel:y,amount:C,totalSourceDebitDisplay:k,receiveAmountDisplay:b,destTokenSymbol:A,shouldQuoteWithdrawGas:v,estimatingFee:w,feeError:R,displayedGasFee:E,selectedDestToken:P,theme:T,styles:F,dark:S,dk:j})=>{const I=S?j.textSecondary:"#71757A",N=S?j.textPrimary:"#0E0D0B",D=f.length>1,L=n&&r?M.isAddress(r)?`${r.slice(0,6)}...${r.slice(-4)}`:r:d?`${d.slice(0,6)}...${d.slice(-4)}`:"\u2014";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onClick:t,style:{display:"flex",alignItems:"center",gap:"6px",marginBottom:e?"10px":"0",cursor:"pointer",userSelect:"none"},children:[s.jsx("span",{style:{fontSize:"13px",color:I,fontFamily:pl,fontWeight:600},children:"Transaction Details"}),s.jsx(vs.ChevronDown,{size:12,color:I,style:{transform:e?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s"}})]}),e&&s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"7px"},children:[s.jsxs("div",{children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsx("span",{style:{fontSize:"12px",color:I,fontFamily:kn,fontWeight:500,letterSpacing:"0.03em"},children:"TO"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.jsx("span",{style:{fontSize:"13px",color:N,fontFamily:kn,fontWeight:500},children:L}),s.jsx("button",{onClick:()=>{o(Q=>!Q),!n&&l&&a(l)},style:{background:"none",border:"none",cursor:"pointer",padding:"0",fontSize:"9.5px",fontFamily:kn,color:I,textDecoration:"underline",fontWeight:600},children:n?"Reset":"Switch"})]})]}),n&&s.jsxs("div",{style:{marginTop:"6px"},children:[s.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:kn,fontWeight:700,letterSpacing:0,textTransform:"uppercase"},children:"CAUTION: ENTERING AN INCORRECT ADDRESS WILL RESULT IN LOSS OF FUNDS"}),s.jsx("input",{type:"text",autoComplete:"off",spellCheck:!1,"aria-label":"Recipient address","aria-invalid":r&&!M.isAddress(r)?!0:void 0,"data-spiceflow-focus":!0,value:r,onChange:Q=>a(Q.target.value),placeholder:"0x...",style:{width:"100%",padding:"8px 10px",borderRadius:"6px",border:`1px solid ${r&&!M.isAddress(r)?S?j.errorBorder:"#fca5a5":S?j.inputBorder:"#d1d5db"}`,backgroundColor:S?j.inputBg:"#f9fafb",color:S?j.inputText:"#111827",fontSize:"12px",fontFamily:kn,outline:"none",boxSizing:"border-box"}}),r&&!M.isAddress(r)&&s.jsx("span",{style:{fontSize:"11px",color:j.errorText,marginTop:"3px",display:"block"},children:"Invalid address"})]})]}),s.jsx(Dn,{palette:j,labelColor:I,valueColor:N,label:"RECEIVING CHAIN",value:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"7px"},children:[c&&s.jsx("img",{src:c,alt:u,style:{width:"14px",height:"14px",borderRadius:"50%"}}),s.jsx("span",{style:{fontSize:"13px",color:N,fontWeight:500,fontFamily:kn,textTransform:"uppercase"},children:u}),s.jsx("button",{ref:p,onClick:Q=>{Q.stopPropagation(),g(p.current)},style:{background:"none",border:"none",cursor:D?"pointer":"not-allowed",padding:"0",fontSize:"9.5px",fontFamily:kn,color:I,textDecoration:"underline",fontWeight:600,opacity:D?1:.45},children:"Switch"})]})}),s.jsx(Dn,{palette:j,labelColor:I,valueColor:N,label:"REQUESTED WITHDRAWAL",value:s.jsxs($s,{logo:m||null,alt:x,primaryText:N,children:[C||"0"," ",y]})}),v&&s.jsx(Dn,{palette:j,labelColor:I,valueColor:N,label:"TOTAL SOURCE DEBIT",value:s.jsxs($s,{logo:m||null,alt:x,primaryText:N,children:[k," ",y]})}),s.jsx(Dn,{palette:j,labelColor:I,valueColor:N,label:"YOU RECEIVE",value:s.jsxs($s,{logo:c,alt:u,primaryText:N,gap:"4px",children:[b," ",A]})}),v&&s.jsxs(s.Fragment,{children:[s.jsx(Dn,{palette:j,labelColor:I,label:"EST. GAS FEE",valueColor:R?"#f87171":N,value:w?"Estimating...":R?"Unavailable":E!==null&&P?`${Js(E,P.decimals)} ${P.symbol}`:"Estimating..."}),R&&s.jsx(Rn,{variant:"error",size:"compact",palette:j,fontFamily:F?.fontFamily||T.typography.fontFamily,children:R})]})]})]})},hl=i.memo(fl),$s=({logo:e,alt:t,primaryText:n,gap:o="6px",children:r})=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:o},children:[e&&s.jsx("img",{src:e,alt:t,style:{width:"13px",height:"13px",borderRadius:"50%"}}),s.jsx("span",{style:{fontSize:"13px",color:n,fontWeight:500,fontFamily:kn},children:r})]});function mr(e){const t=new Set(B.getEquivalentAddresses(e).map(n=>n.toLowerCase()));return t.add(e.toLowerCase()),t}const ml=["USDC","USDT","WETH","WBTC"];function _s(e,t){const n=h.getChainConfig(t);if(!n)return;if(n.nativeCurrency.symbol.toUpperCase()===e.toUpperCase())return{address:B.ZERO_ADDRESS,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 mn(e,t,n){const o=h.getChainConfig(t);if(!o)return;if(n!==void 0){const l=Jo(e,n,t);if(l)return{address:l.address.toLowerCase(),symbol:l.symbol,decimals:l.decimals,chainId:t}}const r=mr(e);if([...r].some(l=>B.isNativeToken(l)))return{address:B.ZERO_ADDRESS,symbol:o.nativeCurrency.symbol,decimals:o.nativeCurrency.decimals,chainId:t};const a=o.supportedTokens?.find(l=>r.has(l.address.toLowerCase()));if(a)return{address:a.address.toLowerCase(),symbol:a.symbol,decimals:a.decimals,chainId:t}}function gr(e){const{sourceAsset:t,outputAsset:n,sourceChainId:o,destinationChainId:r,intermediaryCandidates:a=ml}=e;if(rs(t,n))return{strategy:"direct",sourceAsset:t,outputAsset:n,sourceChainId:o,destinationChainId:r,summary:`${t.symbol} fronted directly`};if(mn(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(mn(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 l of a){const d=_s(l,o);if(!d||rs(t,d)||rs(n,d))continue;const u=_s(l,r);if(u&&rs(d,u))return{strategy:"intermediary",sourceAsset:t,outputAsset:n,intermediaryAsset:u,sourceChainId:o,destinationChainId:r,summary:`${t.symbol} \u2192 ${l} on source, fronted, then ${l} \u2192 ${n.symbol} on destination`}}throw new h.SpiceflowError("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:a})}async function xr(e){const{route:t,sourceAmount:n,userAddress:o,registry:r,actionCalls:a,slippage:l}=e;async function d(u,c,f,p){const g=r.getVenueForChain(u);if(!g)throw new h.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${u}. Cannot resolve swap ${c} \u2192 ${f}.`,{chainId:u,tokenIn:c,tokenOut:f,amountIn:p.toString()});const x=await g.resolve({type:"swap",tokenIn:c,tokenOut:f,amountIn:p,maxSlippage:l},u,o);if(!x)throw new h.SpiceflowError("NO_LIQUIDITY",`${g.name} returned no quote for ${c} \u2192 ${f} on chain ${u}. No liquidity available for this pair.`,{venue:g.name,chainId:u,tokenIn:c,tokenOut:f,amountIn:p.toString()});return x}switch(t.strategy){case"direct":{const u=mn(t.sourceAsset.address,t.destinationChainId,t.sourceChainId)||t.sourceAsset;if(mr(u.address).has(t.outputAsset.address.toLowerCase()))return{chainBatches:[{chainId:t.destinationChainId,calls:a}],solverFrontToken:u,solverFrontAmount:n,resolvedSwaps:{}};const c=await d(t.destinationChainId,u.address,t.outputAsset.address,n);return{chainBatches:[{chainId:t.destinationChainId,calls:[...c.calls,...a]}],solverFrontToken:u,solverFrontAmount:n,resolvedSwaps:{destinationSwap:c}}}case"source-swap":{const u=mn(t.outputAsset.address,t.sourceChainId,t.destinationChainId);if(!u)throw new h.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Output asset ${t.outputAsset.symbol} (${t.outputAsset.address}) not found on source chain ${t.sourceChainId}`,{token:t.outputAsset.symbol,address:t.outputAsset.address,chainId:t.sourceChainId,side:"source"});const c=mn(t.outputAsset.address,t.destinationChainId,t.destinationChainId);if(!c)throw new h.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Output asset ${t.outputAsset.symbol} (${t.outputAsset.address}) not found on destination chain ${t.destinationChainId}`,{token:t.outputAsset.symbol,address:t.outputAsset.address,chainId:t.destinationChainId,side:"destination"});const f=await d(t.sourceChainId,t.sourceAsset.address,u.address,n);return{chainBatches:[{chainId:t.sourceChainId,calls:f.calls},{chainId:t.destinationChainId,calls:a}],solverFrontToken:c,solverFrontAmount:f.amountOutMinimum,resolvedSwaps:{sourceSwap:f}}}case"intermediary":{if(!t.intermediaryAsset)throw new h.SpiceflowError("ROUTE_STRATEGY_ERROR","Intermediary strategy requires an intermediary asset but none was provided in the route plan.",{strategy:t.strategy});const u=mn(t.intermediaryAsset.address,t.sourceChainId,t.destinationChainId);if(!u)throw new h.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Intermediary ${t.intermediaryAsset.symbol} (${t.intermediaryAsset.address}) not found on source chain ${t.sourceChainId}`,{token:t.intermediaryAsset.symbol,address:t.intermediaryAsset.address,chainId:t.sourceChainId,side:"source"});const c=await d(t.sourceChainId,t.sourceAsset.address,u.address,n),f=await d(t.destinationChainId,t.intermediaryAsset.address,t.outputAsset.address,c.amountOutMinimum);return{chainBatches:[{chainId:t.sourceChainId,calls:c.calls},{chainId:t.destinationChainId,calls:[...f.calls,...a]}],solverFrontToken:t.intermediaryAsset,solverFrontAmount:c.amountOutMinimum,resolvedSwaps:{sourceSwap:c,destinationSwap:f}}}default:throw new h.SpiceflowError("ROUTE_STRATEGY_ERROR",`Unknown route strategy: ${t.strategy}`,{strategy:t.strategy})}}const gl=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,styles:o,onWithdrawExecute:r,withdrawActionLabel:a,onWithdrawSuccess:l,onWithdrawError:d,autoCloseDelay:u,availableTokens:c,buildSpicenetBatch:f})=>{const p=i.useContext(h.SpiceFlowProviderContext);if(!p)return s.jsx("div",{children:"Error: SpiceWithdraw must be used within SpiceFlowProvider"});const g=p.mode||"7702",x=g==="presign"||g==="ondemand",m=p.supportedChainIds,y=p.allowedTokens,C=p.isWhitelistGateActive,k=!0,{theme:b,dark:A,dk:v}=h.useSpiceBrand(o),w=p.network,R=()=>x?"select":"provider-login",[E,P]=i.useState(R()),[T,F]=i.useState(!1),[S,j]=i.useState(null),[I,N]=i.useState(null),[D,L]=i.useState(""),[Q,W]=i.useState(!1),[O,H]=i.useState(!1),[J,U]=i.useState(!1),[z,ie]=i.useState(!1),[q,$]=i.useState(""),[le,he]=i.useState(!0),me=i.useRef(null),ue=i.useRef(null),ge=i.useRef(null),Y=i.useRef(null),[oe,K]=i.useState(null),[ne,ce]=i.useState(null),[Ce,be]=i.useState(null),G=h.useWallet(),{isReady:ee,isAuthenticated:_,address:Ae}=G,Be=h.useEmbeddedWalletAddress(),{address:kt,chainId:_e}=Qt.useAccount(),[vt,Ve]=i.useState(!1),[xe,Ee]=i.useState(null),[ze,lt]=i.useState(null),et=i.useRef(null),re=i.useRef(!0),we=i.useRef(null);i.useEffect(()=>(re.current=!0,()=>{re.current=!1}),[]);const{executeGasless:Ge,estimateGasless:je}=Pn(),[Me,Et]=i.useState(null),[Rt,ct]=i.useState(null),[Se,St]=i.useState(!1),[bt,mt]=i.useState(null),{assets:De,loading:zt}=Vn({address:Be,enabled:e&&!!Be,refetchInterval:3e4}),We=i.useMemo(()=>{if(C)return[];if(!y||y.length===0)return De;const te=new Set(y.map(se=>se.toLowerCase()));return(De||[]).filter(se=>[se.symbol,se.displaySymbol,se.receiptTokenName].some(ve=>typeof ve=="string"&&te.has(ve.toLowerCase())))},[De,y,C]),gt=i.useMemo(()=>[...new Set([...m??[],...Object.keys(c??{}).map(Number),...(We||[]).map(te=>te.chainId),...(We||[]).flatMap(te=>Object.keys(te.chainTokens??{}).map(se=>{const[,ve]=se.split(":"),qe=Number(ve);return Number.isFinite(qe)?qe:null}).filter(se=>se!==null))])].filter(te=>h.getChainConfig(te)?.network===w),[m,c,We,w]),Je=i.useMemo(()=>{if(c)return c;const te={};for(const se of We||[]){const ve=Object.entries(se.chainTokens??{});if(ve.length>0){for(const[qe,yt]of ve){const[pt,ft,ut]=qe.split(":");if(pt!=="evm"||!ft||!ut)continue;const Pe=Number(ft);if(!Number.isFinite(Pe))continue;const Tt=ut.startsWith("0x")?ut.toLowerCase():`0x${ut.toLowerCase()}`,He=h.getChainConfig(Pe)?.supportedTokens?.find(X=>h.addressesEqual(X.address,Tt));He&&Gs(se,Tt,Pe)&&(te[Pe]||(te[Pe]=[]),te[Pe].find(X=>h.addressesEqual(X.address,Tt))||te[Pe].push({address:Tt,symbol:He?.symbol||yt?.name||se.symbol,name:He?.name||yt?.name||se.displayName||se.name||se.symbol,decimals:He?.decimals??yt?.decimals??se.decimals,logoURI:He?.logo||se.logoURI}))}continue}te[se.chainId]||(te[se.chainId]=[]),te[se.chainId].find(qe=>h.addressesEqual(qe.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},[c,We]),wt=i.useCallback((te,se)=>{if(!te||!se)return null;const ve=os(te,se),qe=Object.entries(te.chainTokens??{}).flatMap(([He,X])=>{const ye=Nn(He);return ye?.chainId===se?[{parsed:ye,detail:X}]:[]}),yt=Je?.[se]||[],pt=He=>yt.find(X=>h.addressesEqual(X.address,He))??null,ft=He=>{const X=h.getChainConfig(se)?.supportedTokens?.find(Ct=>h.addressesEqual(Ct.address,He));if(!X||!Gs(te,He,se))return null;const ye=qe.find(({parsed:Ct})=>h.addressesEqual(Ct.address,He));return ye?{address:ye.parsed.address,symbol:X.symbol,name:X.name||ye.detail?.name||te.displayName||te.name||te.symbol,decimals:X.decimals,logoURI:X.logo||te.logoURI}:null};for(const He of ve){const X=pt(He);if(X)return X;const ye=ft(He);if(ye)return ye}const ut=rn(te,se);if(ut){const He=pt(ut);if(He)return He;const X=ft(ut);if(X)return X}const Pe=mn(te.address,se,te.chainId);return Pe?pt(Pe.address)||(yt.length>0?null:{address:Pe.address,symbol:Pe.symbol||te.symbol,name:te.displayName||te.name||te.symbol,decimals:Pe.decimals??te.decimals,logoURI:te.logoURI}):null},[Je]),fe=i.useMemo(()=>{if(!S)return null;const te=S.receiptTokenId||`${S.chainId}:${S.address.toLowerCase()}`;return We.find(se=>(se.receiptTokenId||`${se.chainId}:${se.address.toLowerCase()}`)===te)||S},[S,We]),Ke=i.useMemo(()=>{if(!fe)return[];const te=Object.keys(fe.chainTokens??{}).map(se=>Nn(se)?.chainId??null).filter(se=>se!==null);return Array.from(new Set([...te,fe.chainId,...gt].filter(Number.isFinite))).filter(se=>se!==1&&h.getChainConfig(se)?.network===w&&wt(fe,se)!==null)},[fe,gt,wt,w]),tt=i.useMemo(()=>{if(!fe||typeof window>"u")return null;const te=`spiceflow:withdraw-chain:${fe.receiptTokenId||fe.address.toLowerCase()}`,se=window.localStorage.getItem(te),ve=se?Number(se):null;return ve!==null&&Number.isFinite(ve)&&Ke.includes(ve)?ve:null},[fe,Ke]),xt=i.useMemo(()=>fe?tt!==null?tt:_e&&Ke.includes(_e)?_e:fe.chainId&&Ke.includes(fe.chainId)?fe.chainId:Ke[0]??gt[0]??null:gt[0]??null,[fe,tt,_e,Ke,gt]),Re=i.useMemo(()=>wt(fe,I),[wt,fe,I]);i.useEffect(()=>{!We?.length||fe||j(We[0])},[k,We,fe]),i.useEffect(()=>{!fe||(I===null||!Ke.includes(I))&&N(xt)},[k,fe,I,xt,Ke]),i.useEffect(()=>{if(!Q&&!O&&!J)return;const te=se=>{const ve=se.target;Q&&!me.current?.contains(ve)&&!ue.current?.contains(ve)&&!ve?.closest?.("[data-network-popover]")&&W(!1),O&&!ge.current?.contains(ve)&&!ve?.closest?.("[data-token-popover]")&&H(!1),J&&!Y.current?.contains(ve)&&!ve?.closest?.("[data-balance-trigger]")&&U(!1)};return document.addEventListener("mousedown",te),()=>document.removeEventListener("mousedown",te)},[Q,O,J]);const nt=i.useCallback(te=>{if(!te||Ke.length<=1)return;const se=te.getBoundingClientRect(),ve=220,qe=16;K({top:se.bottom+8,left:Math.min(Math.max(qe,se.right-ve),window.innerWidth-ve-qe)}),W(yt=>!yt)},[Ke.length]),Pt=i.useCallback(()=>he(te=>!te),[]);i.useEffect(()=>{if(!fe||I===null||typeof window>"u")return;const te=`spiceflow:withdraw-chain:${fe.receiptTokenId||fe.address.toLowerCase()}`;window.localStorage.setItem(te,String(I))},[fe,I]);const Ye=z&&q&&M.isAddress(q)?q:kt||Be,st=fe?.balanceFormatted??0,jt=i.useCallback(te=>{if(!te)return;const se=te.getBoundingClientRect();be({top:se.bottom+8,left:se.right-220}),U(!0)},[]),Ft=fe?.displaySymbol||fe?.receiptTokenName||fe?.symbol||"spiceUSDC",Ot=fe?.displayChainName||"Spicenet",Bt=Ts,Wt=Ts,dt=fe?.receiptTokenDecimals??fe?.decimals,Te=i.useMemo(()=>{if(!Re||!dt)return 0n;try{return M.parseUnits(D||"0",dt)}catch{return 0n}},[D,Re,dt]),Mt=i.useMemo(()=>!Re||!dt?0n:lr(Te,dt,Re.decimals),[Re,dt,Te]),Ne=i.useMemo(()=>{const te=Rt??Me;return!te||te<=0n||!Re||!dt?0n:lr(te,Re.decimals,dt)},[Rt,Me,Re,dt]),_t=i.useMemo(()=>Te+Ne,[Te,Ne]),Lt=Rt??Me,It=i.useCallback(te=>{if(!I||!Re)return[];if(Te===0n||Mt===0n||!Ye)return[];const se=Array.isArray(te)?te.filter(pt=>pt.amount>0n):[{token:Re.address,recipient:Ye,amount:te??Mt}],ve=se.reduce((pt,ft)=>pt+ft.amount,0n);if(ve<=0n)return[];const qe={chainId:I,calls:[],tokenTransfers:se.map(pt=>({from:"escrow",to:pt.recipient,token:pt.token,amount:pt.amount}))};if(!f)return[qe];const yt=f({destinationChainId:I,deliveryToken:Re.address,deliveryAmount:ve,deliveryRecipient:Ye,deliveryTransfers:se,requestTimestampMs:we.current??Date.now()});return yt?[yt,qe]:[qe]},[k,I,Re,Te,Mt,Ye,f]),Qe=i.useMemo(()=>It(),[It]),de=i.useMemo(()=>sl(Qe,Re?.address),[Qe,Re?.address]),Le=i.useRef(null),ot=i.useRef(0);i.useEffect(()=>{let te=!1;if(!e||x||vt||!Re||!I||Te===0n){Le.current=null,Et(null),mt(null),St(!1);return}if(Qe.length===0){Le.current=null,Et(null),St(!0);return}if(!de){Le.current=null,Et(null),mt(null),St(!1);return}if(Le.current===de)return;Le.current=de;const se=++ot.current;return(async()=>{St(!0),mt(null);try{const ve=await dl({batches:Qe,tokenAddress:Re.address,chainId:I,estimateGasless:je});if(te||se!==ot.current)return;Et(ve)}catch(ve){if(te||se!==ot.current)return;Le.current=null,Et(null),mt(ve instanceof Error?ve.message:"Failed to estimate gas fee")}finally{!te&&se===ot.current&&St(!1)}})(),()=>{te=!0}},[e,x,vt,Re,je,Te,Qe,de]),i.useEffect(()=>{vt||ct(null)},[vt,D,I,Re?.address]);const Xe=i.useCallback(()=>{F(!0),P("select")},[k]),Ht=i.useCallback(()=>{t()},[t]),ke=i.useRef(null);ke.current={batches:Qe,walletAddress:Ae,recipient:Ye,token:Re,chainId:I,amount:D,receiveAmountRaw:Mt,gasFee:Me,isNon7702:x,buildWithdrawBatches:It,gasless:{estimateGasless:je,executeGasless:Ge},ui:{setIsExecuting:Ve,setExecutionError:Ee,setExecutionProgress:lt,setLockedGasFee:ct},executionContextRef:et,isMountedRef:re,onWithdrawExecute:r,onWithdrawSuccess:l,onWithdrawError:d,buildSpicenetBatch:f};const Yt=i.useCallback(()=>(we.current=Date.now(),pr(ke.current)),[]),sn=i.useCallback(()=>(we.current=Date.now(),cl(ke.current)),[]);if(i.useEffect(()=>{if(!e){const te=setTimeout(()=>{P(R()),F(!1),j(null),N(null),L(""),W(!1),H(!1),ie(!1),$(""),Ve(!1),Ee(null),lt(null),et.current=null},300);return()=>clearTimeout(te)}},[e,x]),i.useEffect(()=>{if(!x&&e&&E==="provider-login"&&ee&&_&&Be&&!T){const te=setTimeout(()=>{F(!0),P("select")},100);return()=>clearTimeout(te)}},[x,e,E,ee,_,Be,T,k]),!e)return null;if(E==="provider-login"&&!x)return s.jsx(qs,{onAuthSuccess:Xe,autoTrigger:!0});if(E==="select"&&k){const te=parseFloat(D)||0,se=dt?Js(_t,dt):D||"0",ve=parseFloat(se)||0,qe=ve>0&&ve>st,yt=(I?h.getChainConfig(I):null)?.displayName||"Network",pt=I?dn[I]||On:null,ft=Re?.symbol||"\u2014",ut=Ft,Pe=Re?Js(Mt,Re.decimals):"0",Tt=cr(te,Re?.symbol||fe?.symbol),He=cr(parseFloat(Pe)||0,Re?.symbol||fe?.symbol),X=!z||!q||M.isAddress(q),ye=!x&&te>0&&Re!==null,Ct=!ye||Me!==null&&!Se&&!bt,$e=te>0&&te<fn,it=te>0&&!$e&&!qe&&S!==null&&I!==null&&Re!==null&&Ye&&X&&Ct&&Mt>0n,ht=!it,Ut=S===null?"NO BALANCE":te===0?"ENTER AMOUNT":$e?`MINIMUM ${fn}`:qe?"INSUFFICIENT BALANCE":ye&&!Ct?bt?"GAS UNAVAILABLE":"ESTIMATING GAS":ye&&Mt===0n?"AMOUNT TOO SMALL":"WITHDRAW",on=!!ze&&(ze.step==="success"||ze.step==="error"),V=s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"5px"},children:[s.jsx("img",{src:Hs,alt:"","aria-hidden":"true",style:{width:"13px",height:"13px",flexShrink:0,...A?{filter:"invert(0.6)"}:{}}}),s.jsx("p",{style:{fontSize:"13px",color:A?v.textSecondary:"#979AA0",margin:"0",lineHeight:"1.4",fontFamily:'"Helvetica Neue", sans-serif'},children:"Withdraw collateral from your account to 10+ EVM blockchains."})]}),Z='"Helvetica Neue", sans-serif',pe='"IBM Plex Mono", monospace',ae=o?.primaryColor||b.colors.primary,Oe=A?v.cardBg:"#E9E9E9",Ue=A?v.cardBorder:"#C6C6C6",Ze=A?v.textSecondary:"#7D7C7B",rt=A?v.textSecondary:"#71757A",Dt=A?v.textPrimary:"#0E0D0B",qt=A?v.cardBorder:"#C5C5C4",Gt=A?"rgba(255,255,255,0.08)":"#D4D3D3",Xt=170,ln=ut.length>8?"14px":ut.length>6?"16px":"18px",gn=ft.length>8?"14px":ft.length>6?"16px":"18px";return s.jsx(un,{isOpen:!0,onClose:Ht,title:"Withdraw",subtitle:V,styles:o,theme:b,dark:A,maxWidth:"486px",footerLinkText:"Spicenet accounts \u2192",overlayDimmed:!1,closeOnBackdropClick:n,overlayContent:on?s.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:s.jsx("div",{style:{pointerEvents:"auto"},children:s.jsx(Qs,{type:"withdraw",isOpen:!0,isProcessing:vt,onRetryTx:()=>{sn()},onNewTx:()=>{lt(null),L(""),Ee(null),et.current=null},onClose:()=>{lt(null),Ee(null),Ve(!1),et.current=null},onComplete:()=>{lt(null),Ee(null),Ve(!1),et.current=null},results:[{asset:{symbol:Re?.symbol||"Token",address:Re?.address||""},txHash:ze?.txHash||"",success:ze?.step==="success",error:ze?.error,amount:D}],chainName:I?h.getChainName(I):"Network",explorerUrl:I?h.getExplorerUrl(I,"").replace(/\/tx\/.*$/,""):void 0,theme:b})})}):null,children:s.jsxs("div",{style:{width:"402px",margin:"0 auto",padding:"0 0 4px 0",position:"relative"},children:[s.jsx(ul,{show:J,position:Ce,popoverRef:Y,spiceAssets:We,dark:A,dk:v}),s.jsxs("div",{style:{marginTop:"16px",marginBottom:"16px",display:"flex",flexDirection:"column",gap:"16px"},children:[s.jsxs("div",{style:{backgroundColor:Oe,border:`1px solid ${Ue}`,borderRadius:"7px",padding:"14px 16px 12px 16px",minHeight:"138px",display:"flex",flexDirection:"column",gap:"6px",position:"relative"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsx("span",{style:{fontFamily:Z,fontSize:"17px",fontWeight:500,color:Ze,lineHeight:"24px"},children:"Source"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",fontFamily:Z,fontSize:"13px",fontWeight:500,color:rt,lineHeight:"16px"},children:["Balance:"," ",zt?"...":bn(st),s.jsx("button",{type:"button","data-balance-trigger":!0,onClick:Fe=>{Fe.stopPropagation(),jt(Fe.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:s.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"1.5px"},children:[0,1,2].map(Fe=>s.jsx("span",{style:{width:"1.75px",height:"1.75px",borderRadius:"999px",backgroundColor:"#EA4B4B",display:"block"}},Fe))})})]})]}),s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[s.jsxs("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[s.jsx(Sn,{element:"input",ariaLabel:"Withdraw amount",ariaInvalid:qe,dataSpiceflowFocus:!0,value:D,onChange:Fe=>{const At=Fe.target.value;if(At===""){L("");return}/^\d*\.?\d*$/.test(At)&&L(Tn(At.startsWith(".")?`0${At}`:At,dt??S?.decimals))},placeholder:"0.0",fontFamily:Z,color:qe?"#ef4444":D?Dt:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,style:{width:"100%"}}),s.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:rt,fontFamily:Z,marginTop:"10px"},children:Tt})]}),s.jsx("div",{style:{width:`${Xt}px`,flexShrink:0},children:s.jsxs("div",{style:{backgroundColor:"transparent",border:`1px solid ${qt}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[s.jsxs("div",{ref:ge,onClick:Fe=>{if(Fe.stopPropagation(),!O&&ge.current){const At=ge.current.getBoundingClientRect(),Kt=220,en=16;ce({top:At.bottom+8,left:Math.min(Math.max(en,At.right-Kt),window.innerWidth-Kt-en)})}H(At=>!At)},style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px",cursor:"pointer"},children:[s.jsx("img",{src:Bt,alt:ut,style:{width:"24px",height:"24px",borderRadius:"50%"}}),s.jsx("span",{style:{fontSize:ln,fontWeight:500,color:Dt,lineHeight:"1.3",fontFamily:Z,flex:1,minWidth:0,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",letterSpacing:0},children:ut}),s.jsx(pn,{size:15,color:Dt,strokeWidth:2.25})]}),s.jsx(Vo,{isOpen:O,position:ne,title:"SELECT TOKEN",portalAttribute:"token",items:(We||[]).map(Fe=>({id:Fe.receiptTokenId||Fe.address,label:Fe.displaySymbol||Fe.receiptTokenName||Fe.symbol,icon:Ts,detail:bn(Fe.balanceFormatted)})),selectedId:fe?.receiptTokenId||fe?.address||null,onSelect:Fe=>{const At=(We||[]).find(Kt=>(Kt.receiptTokenId||Kt.address)===Fe);At&&(j(At),L("")),H(!1)}}),s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:Gt,borderTop:`1px solid ${qt}`},children:s.jsx("span",{style:{fontSize:"11px",fontWeight:400,color:Dt,fontFamily:Z,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:Ot})})]})})]}),s.jsxs("div",{style:{minHeight:"18px",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[qe?s.jsx("span",{style:{fontSize:"12px",color:v.errorText,fontFamily:Z,fontWeight:500},children:"Insufficient Balance"}):s.jsx("span",{}),s.jsx("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0px",minHeight:"32px",marginRight:"-9px"},children:[0,25,50,75,100].map((Fe,At)=>{const Kt=At===4,en=Fe/100,vn=parseFloat(D)||0,Un=st>0&&Math.abs(vn/st*100-Fe)<1;return s.jsx("button",{type:"button","aria-label":`Set amount to ${Fe}%`,"aria-pressed":Un,onClick:()=>{const Ie=st*Fe/100,at=S?.decimals??6,cn=Math.floor(Ie*10**at)/10**at;L(Fe===0?"":cn>0?Mn(cn,at):"")},title:`${Fe}%`,disabled:st===0,"data-spiceflow-focus":!0,style:{width:"32px",height:"32px",padding:"9px",border:"none",backgroundColor:"transparent",cursor:st===0?"not-allowed":"pointer",opacity:Un?1:.5,transition:"opacity 0.15s ease",display:"flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box"},children:s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[s.jsx("circle",{cx:"7",cy:"7",r:"6.84375",fill:Kt?ae:"none",stroke:Kt?ae:A?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!Kt&&en>0&&s.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${en>.5?1:0} 1 ${7+6.84375*Math.sin(en*2*Math.PI)} ${7-6.84375*Math.cos(en*2*Math.PI)} Z`,fill:A?v.textSecondary:"#3C3E42"})]})},Fe)})})]})]}),s.jsxs("div",{style:{backgroundColor:Oe,border:`1px solid ${Ue}`,borderRadius:"7px",padding:"14px 16px 12px 16px",minHeight:"138px",display:"flex",flexDirection:"column",gap:"6px"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsx("span",{style:{fontFamily:Z,fontSize:"17px",fontWeight:500,color:Ze,lineHeight:"24px"},children:"Destination"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",fontFamily:Z,fontSize:"13px",fontWeight:500,color:rt,lineHeight:"16px"},children:["Balance:"," ",zt?"...":bn(st),s.jsx("button",{type:"button","data-balance-trigger":!0,onClick:Fe=>{Fe.stopPropagation(),jt(Fe.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:s.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"1.5px"},children:[0,1,2].map(Fe=>s.jsx("span",{style:{width:"1.75px",height:"1.75px",borderRadius:"999px",backgroundColor:"#EA4B4B",display:"block"}},Fe))})})]})]}),s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"12px",flex:1},children:[s.jsxs("div",{style:{flex:1,minWidth:0,alignSelf:"flex-start",paddingTop:"4px"},children:[s.jsx(Sn,{element:"div",value:Pe,title:Pe,fontFamily:Z,color:D?Dt:"#A8A8A7",lineHeight:"0.95",maxFontSize:54,minFontSize:32,overflow:"wrap"}),s.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:rt,fontFamily:Z,marginTop:"10px"},children:He})]}),s.jsxs("div",{style:{width:`${Xt}px`,flexShrink:0,display:"flex",flexDirection:"column",alignItems:"stretch",gap:"8px"},children:[s.jsxs("div",{style:{backgroundColor:"transparent",border:`1px solid ${qt}`,borderRadius:"8px",overflow:"hidden",width:"100%",display:"flex",flexDirection:"column",boxSizing:"border-box"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",padding:"9px 10px 8px 10px"},children:[s.jsx("img",{src:Re?.logoURI||Ln,alt:ft,style:{width:"24px",height:"24px",borderRadius:"50%"}}),s.jsx("span",{style:{fontSize:gn,fontWeight:500,color:Dt,lineHeight:"1.3",fontFamily:Z,flex:1,minWidth:0,letterSpacing:0},children:ft})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"5px 10px",backgroundColor:Gt,borderTop:`1px solid ${qt}`},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[pt&&s.jsx("img",{src:pt,alt:yt,style:{width:"13px",height:"13px",borderRadius:"50%",flexShrink:0}}),s.jsx("span",{style:{fontSize:"11px",fontWeight:400,color:Dt,fontFamily:Z,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",textTransform:"uppercase"},children:yt})]}),s.jsx("button",{ref:me,onClick:Fe=>{Fe.stopPropagation(),nt(me.current)},style:{background:"none",border:"none",cursor:Ke.length>1?"pointer":"not-allowed",padding:"0 0 0 8px",fontSize:"9.5px",fontFamily:pe,color:rt,textDecoration:"underline",fontWeight:600,opacity:Ke.length>1?1:.45},children:"Switch"}),s.jsx(Vo,{isOpen:Q,position:oe,title:"SELECT NETWORK",portalAttribute:"network",items:Ke.map(Fe=>{const At=h.getChainConfig(Fe);return{id:String(Fe),label:At?.displayName||String(Fe),icon:dn[Fe]||On}}),selectedId:I!==null?String(I):null,onSelect:Fe=>{N(Number(Fe)),W(!1)}})]})]}),s.jsx("div",{style:{minHeight:"14px"}})]})]})]})]}),s.jsxs("div",{style:{marginBottom:b.spacing.sm},children:[s.jsx(hl,{show:le,onToggle:Pt,showCustomAddress:z,setShowCustomAddress:ie,customRecipient:q,setCustomRecipient:$,externalAddress:kt,recipientAddress:Ye,destChainName:yt,destChainLogo:pt,compatibleDestinationChains:Ke,txDetailsChainSwitchRef:ue,onOpenNetworkPopover:nt,sourceChainLabel:Ot,sourceDetailsLogo:Wt,sourceTokenLabel:ut,amount:D,totalSourceDebitDisplay:se,receiveAmountDisplay:Pe,destTokenSymbol:ft,shouldQuoteWithdrawGas:ye,estimatingFee:Se,feeError:bt,displayedGasFee:Lt,selectedDestToken:Re,theme:b,styles:o,dark:A,dk:v}),xe&&s.jsx(Rn,{variant:"error",size:"compact",palette:v,fontFamily:o?.fontFamily||b.typography.fontFamily,style:{marginBottom:"12px"},children:xe}),s.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:()=>{it&&Yt()},disabled:ht||vt,theme:b,dark:A,styles:o,style:{marginTop:"8px"},children:vt?"EXECUTING...":Ut})]})]})})}return null},yr=gl;var xl="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 Gn=e=>{const t=Math.round(e*1e5)/1e5;return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:5}).format(t)},Cr=e=>{const t=Math.round(e*1e5)/1e5;return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:5}).format(t)},yl=({balanceData:e,isLoading:t=!1,styles:n,className:o="",showHeader:r=!0,onAccountClick:a,onDepositClick:l,onWithdrawClick:d,vaultBalance:u,fetchVaultBalance:c,onWithdrawExecute:f,withdrawActionLabel:p,destinationChainId:g,destinationTokenAddress:x,customSections:m,showDefaultSections:y=!0})=>{const C=i.useContext(h.SpiceFlowProviderContext),k=(C?.mode||"7702")!=="7702",b=C?.appName||"Spicenet",{dark:A,primaryColor:v,dk:w,theme:R}=h.useSpiceBrand(n),[E,P]=i.useState(!0),[T,F]=i.useState(!1),[S,j]=i.useState(!1),[I,N]=i.useState(null),{isConnected:D}=Qt.useAccount(),{disconnect:L}=Qt.useDisconnect();i.useEffect(()=>{k&&c&&c().then(U=>{const z=Math.round(U*1e5)/1e5;N(z)}).catch(U=>{console.error("Error fetching vault balance:",U),N(null)})},[k,c]);const Q=()=>{P(!E)},W=i.useMemo(()=>{if(!e.freeCollateralItems)return null;const U=e.freeCollateralItems.filter(q=>q.name==="USDC");if(U.length===0)return null;const z=U.reduce((q,$)=>q+$.balance,0),ie=[];return U.forEach(q=>{q.networks&&q.networks.forEach($=>{($===1||$===11155111||$===8453||$===84532)&&(ie.includes($)||ie.push($))})}),ie.length===0&&ie.push(1,8453),{name:"USDC",totalBalance:z,networks:ie,subtitle:U[0]?.subtitle||"USD COIN"}},[e.freeCollateralItems]),O=i.useMemo(()=>{if(k){if(I!==null)return I;if(u!=null)return u}return e.freeCollateralItems?e.freeCollateralItems.reduce((U,z)=>U+z.balance,0):e.freeCollateral},[k,I,u,e.freeCollateralItems,e.freeCollateral]),H=U=>E?U:"******",J=()=>{L(),F(!1),j(!1)};return s.jsxs("div",{className:o,style:{borderRadius:"16px",backgroundColor:A?w.shell:"#D5D5D5",width:"522px",padding:"8px",fontFamily:n?.fontFamily||'"Helvetica Neue", sans-serif',...n?.container},children:[s.jsxs("div",{style:{background:A?w.cardBg:" white",display:"flex",flexDirection:"column"},children:[s.jsxs("div",{style:{backgroundColor:A?w.inputBg:"#E9E9E9",borderRadius:"0 0 16px 16px",padding:"20px",display:"flex",flexFlow:"column"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"4px"},children:[s.jsxs("p",{style:{fontSize:"14px",fontWeight:500,fontFamily:'"IBM Plex Mono", monospace',color:A?w.textPrimary:"#0E0D0B",margin:0},children:[b.toUpperCase()," BALANCE"]}),D&&s.jsx("button",{onClick:J,"aria-label":"Disconnect wallet",style:{width:"36px",height:"36px",borderRadius:"8px",border:A?`1px solid ${v}33`:"1px solid #E5E7EB",background:A?w.inputBg:"white",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",transition:Jt.interactive,padding:"8px"},onMouseEnter:U=>{U.currentTarget.style.backgroundColor=A?w.cardBg:"#F3F4F6"},onMouseLeave:U=>{U.currentTarget.style.backgroundColor=A?w.inputBg:"white"},children:s.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),s.jsx("polyline",{points:"16 17 21 12 16 7"}),s.jsx("line",{x1:"21",y1:"12",x2:"9",y2:"12"})]})})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.percentageChange!==void 0&&e.percentageChange!==null&&s.jsxs("div",{style:{fontSize:"13px",fontWeight:700,color:e.percentageChange>=0?A?w.successText:"#009C51":A?w.errorText:"#EF4444"},children:[e.percentageChange>=0?"+":"",e.percentageChange.toFixed(2),"%"]}),s.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:U=>{U.currentTarget.style.opacity="0.7"},onMouseLeave:U=>{U.currentTarget.style.opacity="1"},children:E?s.jsxs("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",children:[s.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:A?w.textSecondary:"#1A1A1A",strokeWidth:"2",fill:"none"}),s.jsx("circle",{cx:"12",cy:"12.5",r:"3",stroke:A?w.textSecondary:"#1A1A1A",strokeWidth:"2",fill:"none"})]}):s.jsxs("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",children:[s.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:A?w.textSecondary:"#1A1A1A",strokeWidth:"2",fill:"none"}),s.jsx("path",{d:"M3 3L21 21",stroke:A?w.textSecondary:"#1A1A1A",strokeWidth:"2",strokeLinecap:"round"})]})})]}),s.jsx("p",{style:{fontSize:"40px",fontWeight:700,color:A?w.textPrimary:"black"},children:H(Gn(k&&I!==null?I:k&&u!==void 0&&u!==null?u:e.totalBalance))}),s.jsxs("div",{style:{display:"flex",gap:"12px",marginTop:"16px"},children:[s.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:()=>{l?l():F(!0)},theme:R,dark:A,styles:n,children:"DEPOSIT"}),s.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:()=>{d?d():j(!0)},theme:R,dark:A,styles:n,children:"WITHDRAW"})]})]}),s.jsxs("div",{style:{background:A?w.cardBg:"white",padding:"12px 20px",borderRadius:"12px"},children:[y&&s.jsx(Qo,{title:"FREE COLLATERAL",icon:xl,amount:H(Cr(O)),defaultExpanded:!1,children:k&&(I!==null||u!=null)?s.jsx(ns,{name:"USDC",balance:H(Gn(I!==null?I:u)),subtitle:"USD COIN",icon:Ln,onClick:a?()=>a("usdc-vault"):void 0}):W?s.jsx(ns,{name:W.name,balance:H(Gn(W.totalBalance)),subtitle:W.subtitle,networks:W.networks,icon:Ln,onClick:a?()=>a(W.name):void 0}):e.freeCollateralItems&&e.freeCollateralItems.length>0?e.freeCollateralItems.map((U,z)=>s.jsxs(i.Fragment,{children:[s.jsx(ns,{name:U.name,balance:H(Gn(U.balance)),subtitle:U.subtitle,networks:U.networks,icon:U.name==="USDC"?Ln:void 0,onClick:a?()=>a(U.id):void 0}),z<e.freeCollateralItems.length-1&&s.jsx("div",{style:{height:"1px",backgroundColor:A?w.cardBorder:"#D0D2D8",margin:"4px 0"}})]},U.id)):s.jsx("div",{style:{padding:"12px 0",color:A?w.textSecondary:"#6B7280",fontSize:"13px",fontFamily:'"IBM Plex Mono", monospace'},children:"No collateral items available"})}),m&&m.length>0&&m.filter(U=>U&&U.id&&U.title&&typeof U.title=="string"&&U.title.trim().length>0).map(U=>s.jsx(Qo,{title:U.title,icon:U.icon||void 0,amount:H(Cr(U.totalBalance||0)),defaultExpanded:U.defaultExpanded!==void 0?U.defaultExpanded:!1,children:U.items&&U.items.length>0?U.items.map((z,ie)=>s.jsxs(i.Fragment,{children:[s.jsx(ns,{name:z.name,balance:H(Gn(z.balance)),subtitle:z.subtitle,networks:z.networks,icon:z.name==="USDC"?Ln:void 0,onClick:a?()=>a(z.id):void 0}),ie<U.items.length-1&&s.jsx("div",{style:{height:"1px",backgroundColor:A?w.cardBorder:"#D0D2D8",margin:"4px 0"}})]},z.id||`item-${ie}`)):s.jsx("div",{style:{padding:"12px 0",color:A?w.textSecondary:"#6B7280",fontSize:"13px",fontFamily:'"IBM Plex Mono", monospace'},children:U.emptyMessage||"No items available"})},U.id))]})]}),T&&s.jsx(qo,{isOpen:T,onClose:()=>F(!1),styles:n}),S&&s.jsx(yr,{isOpen:S,onClose:()=>j(!1),styles:n,onWithdrawExecute:f,withdrawActionLabel:p})]})},Cl=({options:e,selectedIndex:t,onSelect:n,primaryColor:o,dark:r=!1,textPrimary:a="#111827",textSecondary:l="#6b7280",trackColor:d})=>{const u=e.length-1,c=d||(r?"#3a3a3a":"#d1d5db"),f=r?"4px":"50%",p=r?"none":"2px solid white",g=r?"none":`0 0 0 1px ${o}`;return s.jsxs("div",{style:{width:"100%",userSelect:"none"},children:[s.jsxs("div",{style:{position:"relative",paddingBottom:"4px"},children:[s.jsx("div",{style:{position:"absolute",top:"50%",left:0,right:0,height:"4px",background:c,borderRadius:"2px",transform:"translateY(-50%)",pointerEvents:"none"}}),s.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"}}),s.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=>n(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}})]}),s.jsx("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"6px"},children:e.map((x,m)=>s.jsxs("div",{onClick:()=>n(m),style:{display:"flex",flexDirection:"column",alignItems:m===0?"flex-start":m===u?"flex-end":"center",cursor:"pointer",flex:1},children:[s.jsx("span",{style:{fontSize:"12px",fontWeight:m===t?700:400,color:m===t?a:l,whiteSpace:"nowrap",transition:"color 0.15s, font-weight 0.15s"},children:x.label}),x.highlight&&s.jsx("span",{style:{fontSize:"10px",color:l,whiteSpace:"nowrap"},children:"(most common)"})]},m))}),s.jsx("style",{children:`
|
|
67
67
|
input[type='range']::-webkit-slider-thumb {
|
|
68
68
|
-webkit-appearance: none;
|
|
69
69
|
width: 20px;
|
|
@@ -87,7 +87,7 @@
|
|
|
87
87
|
input[type='range']::-webkit-slider-thumb:hover {
|
|
88
88
|
transform: scale(1.12);
|
|
89
89
|
}
|
|
90
|
-
`})]})},
|
|
90
|
+
`})]})},bl=i.memo(Cl);function wl(e){const t=new Date;t.setDate(t.getDate()+Math.floor(e*30));const n=["January","February","March","April","May","June","July","August","September","October","November","December"],o=t.getDate(),r=o===1||o===21||o===31?"st":o===2||o===22?"nd":o===3||o===23?"rd":"th";return`${n[t.getMonth()]} ${o}${r} ${t.getFullYear()}`}const kl=({durationMonths:e,fontFamily:t,dark:n=!1,textPrimary:o="#111827",textSecondary:r="#6b7280"})=>s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[s.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 14 14",fill:"none",style:{flexShrink:0},children:[s.jsx("circle",{cx:"7",cy:"7",r:"6.5",stroke:r,strokeWidth:"1.2"}),s.jsx("path",{d:"M7 6v4",stroke:r,strokeWidth:"1.2",strokeLinecap:"round"}),s.jsx("circle",{cx:"7",cy:"4.5",r:"0.7",fill:r})]}),s.jsx("span",{style:{fontSize:"13px",color:r,fontFamily:t},children:"Estimated Lock Expiry"})]}),s.jsx("span",{style:{fontSize:n?"17px":"13px",fontWeight:700,color:o,fontFamily:'"IBM Plex Mono", monospace',letterSpacing:"0.3px"},children:e!==void 0?wl(e):"\u2014"})]}),vl=i.memo(kl),Sl=({votes:e,fontFamily:t,dark:n=!1,textPrimary:o="#111827",textSecondary:r="#6b7280"})=>s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[s.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 14 14",fill:"none",style:{flexShrink:0},children:[s.jsx("circle",{cx:"7",cy:"7",r:"6.5",stroke:r,strokeWidth:"1.2"}),s.jsx("path",{d:"M7 6v4",stroke:r,strokeWidth:"1.2",strokeLinecap:"round"}),s.jsx("circle",{cx:"7",cy:"4.5",r:"0.7",fill:r})]}),s.jsx("span",{style:{fontSize:"13px",color:r,fontFamily:t},children:"Estimated voting power"})]}),s.jsx("span",{style:{fontSize:n?"17px":"13px",fontWeight:700,color:o,fontFamily:'"IBM Plex Mono", monospace',letterSpacing:"0.3px"},children:e!==void 0?`${e} votes/epoch`:"\u2014"})]}),Il=i.memo(Sl),Al=({isOpen:e,data:t,isLocking:n,lockError:o,onContinue:r,onClose:a,primaryColor:l,fontFamily:d,dark:u=!1})=>{const{dk:c}=h.useSpiceBrand(),[f,p]=i.useState(!1),[g,x]=i.useState(!0),m=u?c.cardBg:"#ffffff",y=c.textPrimary,C=c.textSecondary,k=u?c.inputPlaceholder:"#9ca3af",b=u?c.successBg:"#d1fae5",A=u?c.successBorder:"#6ee7b7",v=u?c.successText:"#065f46",w=c.errorBg,R=c.errorBorder;i.useEffect(()=>{e||p(!1)},[e]);const E=()=>{p(!0),setTimeout(a,300)};if(!e||!t)return null;const P=[{label:"NETWORK",value:t.sourceNetwork.toUpperCase()},{label:"DEPOSITED AMOUNT",value:`${t.depositedAmount} ${t.depositedSymbol}`,positive:!0}];return s.jsxs("div",{style:{position:"absolute",bottom:0,left:0,right:0,zIndex:10,animation:f?"lockSlideDown 0.3s ease-in":"lockSlideUp 0.3s ease-out",pointerEvents:"auto"},children:[s.jsxs("div",{style:{backgroundColor:m,width:"100%",padding:"18px 24px",boxShadow:u?"0 -4px 20px rgba(0,0,0,0.4)":"0 -4px 20px rgba(0,0,0,0.15)"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",backgroundColor:b,border:`1px solid ${A}`,borderRadius:"8px",padding:"10px 14px",marginBottom:"16px"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:[s.jsx("circle",{cx:"10",cy:"10",r:"10",fill:"#10b981"}),s.jsx("path",{d:"M6 10l3 3 5-6",stroke:"#fff",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),s.jsx("span",{style:{fontSize:"13px",fontWeight:700,color:v,fontFamily:'"IBM Plex Mono", monospace',letterSpacing:"0.3px"},children:"CONFIRMED TRANSACTION"})]}),t.explorerUrl&&s.jsxs("a",{href:t.explorerUrl,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:v,textDecoration:"none",display:"flex",alignItems:"center",gap:"4px",fontFamily:d},children:["View on explorer",s.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:s.jsx("path",{d:"M2.5 9.5L9.5 2.5M9.5 2.5H5M9.5 2.5V7"})})]})]}),s.jsxs("div",{onClick:()=>x(T=>!T),style:{display:"flex",alignItems:"center",justifyContent:"space-between",cursor:"pointer",marginBottom:"8px"},children:[s.jsx("span",{style:{fontSize:"13px",fontWeight:500,color:C,fontFamily:d},children:"Transaction Details"}),s.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:[s.jsx(pn,{color:C,direction:g?"up":"down"}),s.jsx("button",{onClick:T=>{T.stopPropagation(),E()},style:{background:"none",border:"none",cursor:"pointer",padding:"2px",color:C,display:"flex",alignItems:"center"},children:s.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:s.jsx("path",{d:"M11 3L3 11M3 3l8 8",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round"})})})]})]}),s.jsx("div",{style:{overflow:"hidden",maxHeight:g?"200px":"0",opacity:g?1:0,transition:"max-height 0.3s ease, opacity 0.3s ease",marginBottom:g?"16px":"8px",display:"flex",flexDirection:"column",gap:"10px"},children:P.map(T=>s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[s.jsx("span",{style:{fontSize:"12px",fontWeight:500,color:k,fontFamily:'"IBM Plex Mono", monospace',letterSpacing:"0.5px"},children:T.label}),s.jsx("span",{style:{fontSize:"12px",fontWeight:600,color:T.positive?"#10b981":y,fontFamily:'"IBM Plex Mono", monospace'},children:T.value})]},T.label))}),o&&s.jsx("div",{style:{marginBottom:"12px",padding:"10px 14px",backgroundColor:w,border:`1px solid ${R}`,borderRadius:"6px"},children:s.jsx("p",{style:{color:"#ef4444",fontSize:"13px",margin:0,fontFamily:d},children:o})}),s.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:r,disabled:n,loading:n,dark:u,styles:{button:{backgroundColor:l}},style:{height:"48px"},children:n?"LOCKING...":"CONTINUE \u2192"}),s.jsx("div",{style:{marginTop:"12px",display:"flex",justifyContent:"center"},children:s.jsx("img",{src:Jn,alt:"Powered by SpiceNet",style:{height:"auto",width:"130px"}})})]}),s.jsx("style",{children:`
|
|
91
91
|
@keyframes lockSlideUp {
|
|
92
92
|
from { transform: translateY(100%); }
|
|
93
93
|
to { transform: translateY(0); }
|
|
@@ -100,9 +100,9 @@
|
|
|
100
100
|
from { transform: rotate(0deg); }
|
|
101
101
|
to { transform: rotate(360deg); }
|
|
102
102
|
}
|
|
103
|
-
`})]})},Al="0xa9059cbb";function El(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const o=M.getAddress(n.token),r=M.getAddress(n.to),a=`${o.toLowerCase()}:${r.toLowerCase()}`,l=t.get(a);l?l.amount+=n.amount:t.set(a,{token:o,to:r,amount:n.amount})}return[...t.values()]}function jl(e,t){return`0x${t}${e.slice(4)}`}function eo(e,t){return br(e,t)}function br(e,t,n){const o=Fl(t,e),r=Math.floor(Date.now()/1e3)+60*10,a=B.hashChainBatches(o);return{user:e,...n?{chainAuthorizations:n}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:"0x00",nbf:0,exp:r,chainBatches:a.map((l,d)=>({hash:l.hash,chainId:l.chainId,tokenTransfers:o[d].domain==="spicenet"?[]:o[d].tokenTransfers??[],calls:l.calls}))}]}}function Fl(e,t){return e.map(n=>{if(n.domain==="spicenet"||n.calls.length===0)return n;const o=new Set((n.tokenTransfers??[]).filter(a=>(a.from==="escrow"||a.from==="solver")&&M.getAddress(a.to).toLowerCase()===t.toLowerCase()).map(a=>M.getAddress(a.token).toLowerCase()));if(o.size===0)return n;let r=0;for(const a of n.calls){if(!a.data?.startsWith(Al))break;try{const l=M.decodeFunctionData({abi:h.P,data:a.data});if(l.functionName!=="transfer")break;const[d]=l.args;if(d.toLowerCase()===t.toLowerCase()||!o.has(M.getAddress(a.to).toLowerCase()))break;r+=1}catch{break}}return r===0?n:{...n,calls:n.calls.slice(r)}})}function tn(e,t,n,o){if(e.some(f=>f.domain==="spicenet"))return e;const r=n?.intents.flatMap(f=>f.batches),a=f=>f.from==="escrow",l=e.map(f=>{const p=r?.find(v=>v.chainId===f.chainId);if(!p)return f;const g=$t(p),x=g.totalFee;if(x<=0n)return f;const m=(f.tokenTransfers??[]).find(v=>a(v)&&M.getAddress(v.to).toLowerCase()===t.toLowerCase()&&!B.isNativeToken(M.getAddress(v.token)));if(!m)return f;const y=M.getAddress(m.token);let C=!1;const k=(f.tokenTransfers??[]).map(v=>C||!a(v)||M.getAddress(v.to).toLowerCase()!==t.toLowerCase()||M.getAddress(v.token).toLowerCase()!==y.toLowerCase()?v:(C=!0,{...v,amount:o?.payoutAlreadyGross?BigInt(v.amount):BigInt(v.amount)+x}));if(!C)return f;const b=[];g.spicenetFee>0n&&b.push({to:y,value:0n,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[B.SPICE_PLATFORM_FEE_RECIPIENT,g.spicenetFee]})});const A=g.gasFee+g.bridgeFee;return A>0n&&b.push({to:y,value:0n,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[B.SPICE_GAS_FEE_RECIPIENT,A]})}),{...f,tokenTransfers:k,calls:[...b,...f.calls]}}),d=l.flatMap(f=>(f.tokenTransfers??[]).filter(a).map(p=>{const g=M.getAddress(p.token),x=M.getAddress(p.to),m=[{token:g,to:x,amount:BigInt(p.amount)}];return{chainId:f.chainId,transfers:El(m)}}));if(d.length===0)return e;const u=o?.requestTimestampMs??Date.now(),c=BigInt(Math.floor(u/1e3))+3600n;return[{chainId:B.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:d.map((f,p)=>{const g=M.keccak256(M.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,f.transfers[0].token,f.transfers.reduce((m,y)=>m+y.amount,0n),BigInt(f.chainId),BigInt(u+p)])),x=jl(g,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:M.encodeFunctionData({abi:B.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${f.chainId}`,idempotenceKey:x,nbf:0n,exp:c,metadata:"{}",transfers:f.transfers.map(m=>({token:m.token.toLowerCase(),to:m.to,amount:m.amount}))}]})}})},...l]}function us(e,t){return t?e.some(n=>(n.tokenTransfers??[]).some(o=>o.from==="escrow"&&BigInt(o.amount)>=t.grossAmount)):!1}function wr(e){return!e.isSemi7702&&e.isDirectDeposit&&!e.isSourceDestToken}function to(e){const t=e.selectedAsset?.asset,n=e.selectedAsset?.amount;if(!(!t||!n))return M.parseUnits(n,t.decimals)}function kr(e){return e.map(t=>({r:t.r,s:t.s,yParity:t.yParity,address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce)}))}function Bl(e,t){if(e.length!==t.length)return!1;const n=B.hashChainBatches(e),o=B.hashChainBatches(t);return n.every((r,a)=>r.hash===o[a]?.hash)}async function ps({user:e,batches:t,authorizations:n,adjustBatchesForEstimate:o}){let r=t;const a=kr(n);for(let l=0;l<10;l+=1){const d=await h.relayerService.estimateActionFees(br(e,r,a)),u=await o({feeEstimate:d,batches:r});if(!u||Bl(r,u))return r;r=u}throw new Error("Fee estimate did not converge. Please retry.")}function an(e,t){const n=e.selectedAsset?.asset;if(!n||!e.selectedAsset?.amount)throw new Error("Select an asset and enter an amount");const o=M.parseUnits(e.selectedAsset.amount,n.decimals),r=t?.grossAmount??o;return e.resolveLockBatches({amount:e.selectedAsset.amount,amountWei:o,grossAmount:M.formatUnits(r,n.decimals),grossAmountWei:r})}async function fs(e,t,n){const o=[...new Set(n.filter(a=>a.domain!=="spicenet").map(a=>a.chainId))],r=[];for(const a of o){const l=h.getClientForChain(a),d=h.getDelegateContractAddress(a),u=await B.getAccountNonce(t,l),c=await e.actions.signAuthorization({contractAddress:d,chainId:a,nonce:Number(u)});r.push(c)}return r}async function no(e,t,n){const o=e.isSemi7702&&e.providerEmbeddedAddress||e.address;if(!e.isConnected||!o)throw new Error("Please connect your wallet to continue");if(t.length===0)throw new Error("No lock batches configured");if(!e.ready||!e.authenticated)throw new Error(`Please authenticate with ${e.provider||"wallet provider"} to continue`);const r=n??await fs(e,o,t),a=B.hashChainBatches(t),l=Math.floor(Date.now()/1e3)+60*10,d=a.map(x=>x.hash),u=M.keccak256(M.encodeAbiParameters([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,BigInt(l),d])),c=await e.actions.signMessage({raw:u}),f=typeof c=="string"?c:c.signature;if(!f)throw new Error("Failed to sign intent authorization");const p={mode:"7702",signatureType:"ecdsa",signature:f,nbf:0,exp:l,chainBatches:a.map((x,m)=>{const y=t[m],C=y.domain==="spicenet";return{hash:x.hash,chainId:x.chainId,tokenTransfers:C?[]:y.tokenTransfers??[],calls:x.calls}})},g=await h.relayerService.createAction({user:o,chainAuthorizations:kr(r),intents:[p]});if(g){const x=h.createInitialSteps(t,h.getChainName),[m,y]=g.intentIds[0].split("/"),C=parseInt(y||"0",10),k=g.intentIds[0];e.startStatusPolling(g.intentIds[0],x),await tr({actionId:m,intentIndex:C,intentId:k,totalSteps:t.length,isSpicenetStep:b=>t[b]?.domain==="spicenet",maxExecuteAttemptsForStep:b=>t[b]?.domain==="spicenet"?6:3,maxPolls:72})}}async function Tl(e){let t=an(e);if(t.length===0)throw new Error("No lock batches configured");const n=e.isSemi7702&&e.providerEmbeddedAddress||e.address;if(!e.isConnected||!n)throw new Error("Please connect your wallet to continue");const o=await fs(e,n,t),r=Date.now();let a=tn([...t],n,void 0,{requestTimestampMs:r}),l;a=await ps({user:n,batches:a,authorizations:o,adjustBatchesForEstimate:({feeEstimate:d})=>{const u=An(d,{symbol:e.selectedAsset?.asset.symbol??"",decimals:e.selectedAsset?.asset.decimals??18,actionAmount:to(e)});return u?(l={grossAmount:u.grossAmount,netAmount:u.netAmount,feeAmount:u.totalFee??0n},t=an(e,l),tn([...t],n,d,{payoutAlreadyGross:us(t,l),requestTimestampMs:r})):null}}),await no(e,a,o)}async function Ml(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");const n=e.resolveLockBatches();if(n.length===0)throw new Error("No lock batches configured");const o=e.selectedAsset.asset,r=M.parseUnits(e.selectedAsset.amount,o.decimals),a=o.chainId,l=e.escrowAddress||B.getEscrowContractAddress(a),d=B.normalizeNativeTokenAddress(o.address),u=o.isNative||B.isNativeToken(d),c=Date.now();let f;const p=n.some(k=>k.tokenTransfers?.some(b=>b.from==="escrow")),g=k=>({chainId:a,calls:u?[{to:l,value:k,data:"0x"}]:[{to:d,value:0n,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[l,k]})}]}),x=(k,b,A,v)=>{const w=g(k);if(!p)return[w,...b];const R=tn([...b],t,A,{payoutAlreadyGross:us(b,v),requestTimestampMs:c});return[w,...R]};let m=an(e),y=x(r,m);const C=await fs(e,t,y);p&&(y=await ps({user:t,batches:y,authorizations:C,adjustBatchesForEstimate:({feeEstimate:k})=>{const b=An(k,{symbol:o.symbol,decimals:o.decimals,actionAmount:r});return b?(f={grossAmount:b.grossAmount,netAmount:b.netAmount,feeAmount:b.totalFee??0n},m=an(e,f),x(f.grossAmount,m,k,f)):null}})),await no(e,y,C)}async function Rl(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");if(e.onLockExecute){const T=e.resolveLockBatches();if(T.length===0)throw new Error("No lock batches configured");const F=e.selectedAsset.asset,S=M.parseUnits(e.selectedAsset.amount,F.decimals),j=await e.onLockExecute({asset:F,amount:e.selectedAsset.amount,amountWei:S,lockDurationMonths:e.selectedDuration?.months??0,chainBatches:T});j&&e.onLockSuccess?.(j);return}const n=e.resolveLockBatches();if(n.length===0)throw new Error("No lock batches configured");const o=e.selectedAsset.asset,r=M.parseUnits(e.selectedAsset.amount,o.decimals),a=o.chainId,l=e.escrowAddress||B.getEscrowContractAddress(a),d=B.normalizeNativeTokenAddress(o.address),u=o.isNative||B.isNativeToken(d),c=n.some(T=>T.tokenTransfers?.some(F=>F.from==="escrow")),f=Date.now();let p;const g=T=>({chainId:a,calls:u?[{to:l,value:T,data:"0x"}]:[{to:d,value:0n,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[l,T]})}]}),x=(T,F,S,j)=>{const I=g(T);if(!c)return[I,...F];const N=tn([...F],t,S,{payoutAlreadyGross:us(F,j),requestTimestampMs:f});return[I,...N]};let m=an(e),y=x(r,m);const C=await fs(e,t,y);c&&(y=await ps({user:t,batches:y,authorizations:C,adjustBatchesForEstimate:({feeEstimate:T})=>{const F=An(T,{symbol:o.symbol,decimals:o.decimals,actionAmount:r});return F?(p={grossAmount:F.grossAmount,netAmount:F.netAmount,feeAmount:F.totalFee??0n},m=an(e,p),x(p.grossAmount,m,T,p)):null}}));const k=p?.grossAmount??r,b=await e.externalWallet.getEthereumProvider();let A=null;try{const T=await b.request({method:"eth_chainId"});A=parseInt(T,16)}catch{A=null}A!==a&&await h.ensureWalletOnChain(b,a);const v=h.getChainConfig(a),w=M.createWalletClient({account:e.externalWalletAddress,chain:v?.viemChain,transport:M.custom(b)}),R=h.getClientForChain(a),E=async T=>{if(T<=0n)return;const F=u?await w.sendTransaction({to:t,value:T,chain:v?.viemChain}):await w.sendTransaction({to:d,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[t,T]}),chain:v?.viemChain});if((await R.waitForTransactionReceipt({hash:F,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to embedded wallet failed")};await E(k);let P=k;if(c)for(let T=0;T<4;T+=1){y=await ps({user:t,batches:y,authorizations:C,adjustBatchesForEstimate:({feeEstimate:S})=>{const j=An(S,{symbol:o.symbol,decimals:o.decimals,actionAmount:r});return j?(p={grossAmount:j.grossAmount,netAmount:j.netAmount,feeAmount:j.totalFee??0n},m=an(e,p),x(p.grossAmount,m,S,p)):null}});const F=p?.grossAmount??r;if(F<=P)break;await E(F-P),P=F}await no(e,y,C)}async function Dl(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount||!e.requiresRelayerFeeEstimate)return null;if(e.isSemi7702||wr(e)){const l=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address;if(!l)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");let d=an(e);if(d.length===0)throw new Error("No lock batches configured");const u=e.selectedAsset.asset,c=M.parseUnits(e.selectedAsset.amount,u.decimals),f=u.chainId,p=e.escrowAddress||B.getEscrowContractAddress(f),g=B.normalizeNativeTokenAddress(u.address),x=u.isNative||B.isNativeToken(g),m=d.some(v=>v.tokenTransfers?.some(w=>w.from==="escrow")),y=v=>({chainId:f,calls:x?[{to:p,value:v,data:"0x"}]:[{to:g,value:0n,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[p,v]})}]}),C=(v,w,R)=>{const E=y(v);if(!m)return[E,...w];const P=tn([...w],l,R,{payoutAlreadyGross:w.some(T=>(T.tokenTransfers??[]).some(F=>F.from==="escrow"&&BigInt(F.amount)>=v))});return[E,...P]};let k=C(c,d),b=null,A;for(let v=0;v<4;v+=1){const w=await h.relayerService.estimateActionFees(eo(l,k)),R=An(w,{symbol:u.symbol,decimals:u.decimals,actionAmount:c});if(!R)return b;const E={grossAmount:R.grossAmount,netAmount:R.netAmount,feeAmount:R.totalFee??0n},P=A?.grossAmount===E.grossAmount&&A?.netAmount===E.netAmount&&A?.feeAmount===E.feeAmount;if(b=R,A=E,d=an(e,E),k=C(E.grossAmount,d,w),P)break}return b}const t=e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");let n=an(e);if(n.length===0)throw new Error("No lock batches configured");let o=tn([...n],t),r=null;for(let l=0;l<4;l+=1){const d=await h.relayerService.estimateActionFees(eo(t,o)),u=An(d,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:to(e)});if(!u)return null;const c={grossAmount:u.grossAmount},f=r?.grossAmount===u.grossAmount&&r?.netAmount===u.netAmount&&r?.totalFee===u.totalFee;if(r=u,n=an(e,c),o=tn([...n],t,d,{payoutAlreadyGross:us(n,c)}),f)break}if(r)return r;const a=await h.relayerService.estimateActionFees(eo(t,o));return An(a,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:to(e)})}async function Nl(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");const t=e.activeSignerWallet??e.externalWallet,n=e.activeSignerAddress??e.externalWalletAddress;if(!n||!t)throw new Error("Please connect your wallet to continue");const o=e.resolveLockBatches();if(o.length===0)throw new Error("No lock batches configured");const r=o.find(p=>p.chainId===e.lockChainId)||o[0];if(!r)throw new Error("No lock batch for lock chain");const a=await t.getEthereumProvider();let l=null;try{const p=await a.request({method:"eth_chainId"});l=parseInt(p,16)}catch{l=null}l!==e.lockChainId&&await h.ensureWalletOnChain(a,e.lockChainId);const d=h.getChainConfig(e.lockChainId),u=M.createWalletClient({account:n,chain:d?.viemChain,transport:M.custom(a)}),c=h.getClientForChain(e.lockChainId);let f;for(const p of r.calls){const g=await u.sendTransaction({to:p.to,data:p.data,value:p.value,chain:d?.viemChain});if((await c.waitForTransactionReceipt({hash:g,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Lock transaction failed");f=g}f&&e.onLockSuccess?.(f)}async function Pl(e){if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance. Add more assets.");return}e.ui.setIsExecuting(!0),e.ui.setError(null);const t=n=>{console.error("[SpiceLockModal] lock failed:",n);const o=h.sanitizeError(n,""),r=typeof n?.shortMessage=="string"?n.shortMessage:typeof n?.message=="string"?n.message:"";e.ui.setError(o||r||"Transaction failed. Please try again.")};if(e.isSemi7702){if(e.isSourceDestToken){try{await Nl(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{await Rl(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{wr(e)?await Ml(e):await Tl(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}}const vr=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,lockBatches:o,lockTokenSymbol:r,lockTokenLogoURI:a,destinationInputHook:l,sourceAssetInputHook:d,lockDurationHook:u,lockChainId:c,durationOptions:f,votingPowerEstimate:p,escrowAddress:g,includeWalletAssets:x=!1,destinationTokenAddress:m,onLockSuccess:y,onLockExecute:C,sourceToDestinationConversionRate:k,estimatedOutputAmount:b,onAddFunds:A,buildSpicenetBatch:v,styles:w,dark:R=!1})=>{const{theme:E,dark:P,primaryColor:T,dk:F}=h.useSpiceBrand(w,R),S=E.typography.fontFamily,j=i.useContext(h.SpiceFlowProviderContext),I=j?.mode||"7702",N=!!j?.isWhitelistGateActive,D=I!=="7702",L=i.useMemo(()=>j?.supportedChainIds??[],[j?.supportedChainIds]),Q=i.useMemo(()=>{if(N)return[];const X=j?.allowedTokens;if(!X||X.length===0)return[];const ye=new Set(X.map(it=>it.toLowerCase())),Ct=[],$e=new Set;for(const it of L){const ht=h.getChainConfig(it);for(const Ut of ht?.supportedTokens??[]){if(!ye.has(Ut.symbol.toLowerCase()))continue;const on=`${it}:${Ut.address.toLowerCase()}`;$e.has(on)||($e.add(on),Ct.push(M.getAddress(Ut.address)))}}return Ct},[j?.allowedTokens,L,N]),W=P?F.cardBg:w?.assetSelector?.backgroundColor||w?.secondaryBackground||"#e9e9e9",O=P?`1px solid ${F.cardBorder}`:"0.5px solid #A8A8A7",H=P?"12px":"6px",J=P?F.textPrimary:"#111827",U=P?F.textSecondary:"#6b7280",z=i.useMemo(()=>({...w,assetSelector:{...w?.assetSelector,backgroundColor:P?F.cardBg:w?.assetSelector?.backgroundColor,borderRadius:P?"12px":w?.assetSelector?.borderRadius},secondaryBackground:P?F.cardBg:w?.secondaryBackground}),[w,P]),ie=i.useMemo(()=>P?{...E,colors:{...E.colors,secondary:F.cardBg,surfaceHover:F.hoverBg,border:F.cardBorder,borderHover:F.inputBorder}}:E,[P,E]),[q,$]=i.useState(null),[le,he]=i.useState(0),me=u?.selectedDurationIdx??le,ue=u?.setSelectedDurationIdx??he,[ge,Y]=i.useState(!1),[oe,K]=i.useState(null),[ne,ce]=i.useState(null),[Ce,be]=i.useState(!1),[G,ee]=i.useState(!1),[_,Ae]=i.useState(null),[Be,kt]=i.useState(!1),_e=i.useRef(0),[vt,Ve]=i.useState(!1),[xe,Ee]=i.useState(null);Qt.useWalletClient(),Qt.useSwitchChain();const{chain:ze,address:lt}=Qt.useAccount();Qt.useConfig();const et=i.useRef(ze);i.useEffect(()=>{et.current=ze},[ze]);const re=h.useWallet(),{isReady:we,isAuthenticated:Ge,isConnected:je,address:Me,provider:Et,actions:Rt}=re,{externalWallet:ct,embeddedAddress:Se,externalAddress:St,activeWallet:bt,activeAddress:mt}=h.useProviderWallets(),{intentStatus:De,startStatusPolling:zt,clearStatus:We}=Ro({checkStepStatus:(X,ye)=>h.relayerService.checkStepStatus(X,ye),retryStep:async(X,ye)=>{const[Ct,$e]=X.split("/"),it=parseInt($e||"0",10);await h.relayerService.executeStep(Ct,it,ye,{action:"execute"})},maxRetries:3}),{assets:gt,refetch:Je}=Vn({address:Me,supportedChains:L,enabled:e&&je&&!D&&!N,refetchInterval:3e4}),wt=i.useMemo(()=>{if(N)return[];if(Q.length===0)return gt;const X=new Set(Q.map(ye=>ye.toLowerCase()));return gt.filter(ye=>X.has(ye.address.toLowerCase()))},[gt,Q,N]),fe=h.useEmbeddedWalletAddress(),Ke=St||lt,tt=D?mt??Ke:fe,xt=i.useMemo(()=>{if(!x)return[];if(N)return m?[M.getAddress(m)]:[];const X=new Set,ye=[],Ct=$e=>{if(!$e)return;const it=$e.toLowerCase();X.has(it)||(X.add(it),ye.push(M.getAddress($e)))};m&&Ct(m);for(const $e of Q)Ct($e);return ye},[x,D,m,Q,N]),Re=i.useMemo(()=>xt.map(X=>X.toLowerCase()).sort().join(","),[xt]),nt=i.useMemo(()=>JSON.stringify([...L||[]].sort()),[L]),[Pt,Ye]=i.useState([]),st=i.useRef(0),jt=i.useRef(async()=>{}),Ft=i.useCallback(async()=>{if(!x||!tt||xt.length===0){st.current++,Ye([]);return}const X=++st.current,ye=M.getAddress(tt),Ct=D?L&&L.length>0?L:[c]:[c],$e=xt.map(V=>{const Z=V.toLowerCase();if(m&&h.addressesEqual(V,m)){const pe=h.getChainConfig(c)?.supportedTokens?.find(ae=>h.addressesEqual(ae.address,Z));return{address:V,chainId:c,configToken:pe?{decimals:pe.decimals,symbol:pe.symbol,name:pe.name,logo:pe.logo}:void 0}}for(const pe of Ct){const ae=h.getChainConfig(pe)?.supportedTokens?.find(Oe=>h.addressesEqual(Oe.address,Z));if(ae)return{address:V,chainId:pe,configToken:{decimals:ae.decimals,symbol:ae.symbol,name:ae.name,logo:ae.logo}}}return{address:V,chainId:c}}),it=new Map;for(const V of $e){const Z=it.get(V.chainId)||[];Z.push(V),it.set(V.chainId,Z)}const ht=async(V,Z)=>{try{const pe=await Zt.readContract(V,{address:Z.address,abi:h.P,functionName:"balanceOf",args:[ye]});let ae,Oe,Ue,Ze;if(Z.configToken)ae=Z.configToken.decimals,Oe=Z.configToken.symbol,Ue=Z.configToken.name,Ze=Z.configToken.logo;else{const[qt,Gt,Xt]=await Promise.all([Zt.readContract(V,{address:Z.address,abi:h.P,functionName:"decimals",args:[]}).catch(()=>18),Zt.readContract(V,{address:Z.address,abi:h.P,functionName:"symbol",args:[]}).catch(()=>"TOKEN"),Zt.readContract(V,{address:Z.address,abi:h.P,functionName:"name",args:[]}).catch(()=>"TOKEN")]);ae=Number(qt),Oe=Gt,Ue=Xt}const rt=!!m&&h.addressesEqual(Z.address,m)&&Z.chainId===c;rt&&a&&(Ze=a),rt&&r&&!Z.configToken&&(Oe==="TOKEN"&&(Oe=r),Ue==="TOKEN"&&(Ue=r));const Dt=parseFloat((Number(pe)/Math.pow(10,ae)).toFixed(6));return{address:Z.address,name:Ue,symbol:Oe,decimals:ae,balance:pe,balanceFormatted:Dt,balanceUsd:0,logoURI:Ze,isNative:!1,chainId:Z.chainId}}catch{return null}},Ut=await Promise.all(Array.from(it.entries()).map(async([V,Z])=>{let pe;try{pe=h.getClientForChain(V)}catch{return[]}const ae=[],Oe=[];for(const Ze of Z){const rt=ae.length;ae.push({address:Ze.address,abi:h.P,functionName:"balanceOf",args:[ye]}),Ze.configToken||ae.push({address:Ze.address,abi:h.P,functionName:"decimals",args:[]},{address:Ze.address,abi:h.P,functionName:"symbol",args:[]},{address:Ze.address,abi:h.P,functionName:"name",args:[]}),Oe.push({start:rt,item:Ze})}let Ue=null;try{Ue=await pe.multicall({contracts:ae})}catch{Ue=null}return Ue?Oe.map(({start:Ze,item:rt})=>{const Dt=Ue[Ze],qt=Dt?.status==="success"?Dt.result:0n;let Gt,Xt,ln,gn;if(rt.configToken)Gt=rt.configToken.decimals,Xt=rt.configToken.symbol,ln=rt.configToken.name,gn=rt.configToken.logo;else{const Kt=Ue[Ze+1],en=Ue[Ze+2],vn=Ue[Ze+3];Gt=Kt?.status==="success"?Number(Kt.result):18,Xt=en?.status==="success"?en.result:"TOKEN",ln=vn?.status==="success"?vn.result:Xt}const Fe=!!m&&h.addressesEqual(rt.address,m)&&rt.chainId===c;Fe&&a&&(gn=a),Fe&&r&&!rt.configToken&&(Xt==="TOKEN"&&(Xt=r),ln==="TOKEN"&&(ln=r));const At=parseFloat((Number(qt)/Math.pow(10,Gt)).toFixed(6));return{address:rt.address,name:ln,symbol:Xt,decimals:Gt,balance:qt,balanceFormatted:At,balanceUsd:0,logoURI:gn,isNative:!1,chainId:rt.chainId}}):(await Promise.all(Z.map(Ze=>ht(pe,Ze)))).filter(Ze=>Ze!==null)}));if(X!==st.current)return;const on=Ut.flat();Ye(on)},[x,D,tt,Re,nt,c,m,a,r]);i.useEffect(()=>{jt.current=Ft},[Ft]),i.useEffect(()=>{if(!e||!x){Ye([]);return}jt.current();const X=setInterval(()=>{jt.current()},15e3);return()=>clearInterval(X)},[x,e,tt,Re,nt,c,m]);const Ot=i.useCallback(()=>{Ft()},[Ft]),Bt=i.useMemo(()=>Pt.filter(X=>X.balance>0n),[Pt]),Wt=i.useMemo(()=>{if(D)return Bt.map(ye=>({...ye,_source:"wallet"}));if(!x)return wt;const X=[];for(const ye of Bt)X.push({...ye,_source:"wallet"});for(const ye of wt)X.push({...ye,_source:"spice"});return X},[D,x,Bt,wt]),dt=i.useMemo(()=>N?m?Wt.filter(X=>h.addressesEqual(X.address,m)&&X.chainId===c):[]:Wt,[Wt,N,m,c]),Te=i.useRef(null),Mt=i.useRef(null);i.useEffect(()=>{Mt.current=q},[q]),i.useEffect(()=>{!N||!q?.asset||m&&h.addressesEqual(q.asset.address,m)&&q.asset.chainId===c||$(null)},[N,q?.asset,m,c]),i.useEffect(()=>{e||($(null),K(null),ce(null),be(!1),ee(!1),Ae(null),Y(!1),Ve(!1),Ee(null),kt(!1),We())},[e,We]),i.useEffect(()=>{l&&l.assetAmount!==(q?.amount||"")&&$(X=>X&&{...X,amount:l.assetAmount})},[l?.assetAmount]),i.useEffect(()=>{d&&d.assetAmount!==(q?.amount||"")&&$(X=>X&&{...X,amount:d.assetAmount})},[d?.assetAmount]),i.useEffect(()=>{if(!D&&De?.overallStatus==="success"&&De.intentId&&Te.current!==De.intentId&&Me&&De.steps.find(X=>X.transactionHash)?.transactionHash){Te.current=De.intentId;const X=Mt.current;if(!X?.asset||!X.amount||X.asset._source==="wallet"||M.parseUnits(X.amount,X.asset.decimals)===0n)return;Je()}},[De,Me,c,Je,D]);const Ne=parseFloat(q?.amount||"")||0,_t=Ne>0&&Ne<fn,Lt=i.useMemo(()=>q?.asset?q.asset._source==="wallet"?q.asset.balanceFormatted??0:wt.find(X=>h.addressesEqual(X.address,q.asset.address)&&X.chainId===q.asset.chainId)?.balanceFormatted??0:0,[q?.asset,wt]),It=Ne>0&&(_?parseFloat(M.formatUnits(_.grossAmount,_.decimals))>Lt:Ne>Lt),Qe=u?.selectedDuration??f[me]??f[0],de=i.useMemo(()=>!q?.asset||!m?!1:h.addressesEqual(q.asset.address,m)&&q.asset.chainId===c,[q?.asset,m,c]),Le=i.useMemo(()=>Ne<=0?0:de?Ne:!k||k<=0?0:Ne/k,[Ne,k,de]),ot=i.useMemo(()=>Le<=0?null:Le.toLocaleString(void 0,{maximumFractionDigits:2}),[Le]),Xe=p&&Le>0&&Qe?p(Le,Qe.months):void 0,Ht=i.useMemo(()=>Ne<=0?"$0.00":de&&k?(Ne*k).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!k||k<=0?"$0.00":Ne.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[Ne,k,de]),ke=i.useMemo(()=>{if(!ot)return null;const X=parseFloat(ot.replace(/,/g,""));return de&&k?(X*k).toLocaleString(void 0,{maximumFractionDigits:2}):k?(X*k).toLocaleString(void 0,{maximumFractionDigits:2}):null},[ot,k,de]),Yt=i.useCallback(X=>{$(ye=>({asset:X,amount:ye?.asset?.address===X.address&&ye?.asset?.chainId===X.chainId&&ye.amount||""})),K(null),ce(null),ee(!1),Ae(null),d?.setSelectedAsset&&d.setSelectedAsset({symbol:X.symbol,address:X.address,decimals:X.decimals,chainId:X.chainId})},[d?.setSelectedAsset]),sn=i.useCallback(X=>{$(ye=>ye&&{...ye,amount:X}),K(null),ce(null),ee(!1),Ae(null),l&&l.setAssetAmount(X),d&&d.setAssetAmount(X)},[l,d]),te=i.useCallback(X=>{if(typeof o=="function"){if(!q?.asset||!q.amount)throw new Error("Select an asset and enter an amount");return o({asset:q.asset,amount:X?.amount??q.amount,amountWei:X?.amountWei??M.parseUnits(q.amount,q.asset.decimals),grossAmount:X?.grossAmount,grossAmountWei:X?.grossAmountWei,feeAdjusted:!!X})}return o},[o,q]),se=i.useRef(null),ve=i.useMemo(()=>!q?.asset||Ne<=0?!1:D?!de&&!C:!0,[q,Ne,D,de,C]),qe=i.useCallback(()=>Dl(se.current),[]),yt=i.useMemo(()=>!q?.asset||Ne<=0?null:`${q.asset.address.toLowerCase()}:${q.asset.chainId}:${q.amount??""}`,[q?.asset?.address,q?.asset?.chainId,q?.amount,Ne]);i.useEffect(()=>{if(!e||ge)return;if(!q?.asset||Ne<=0){ce(null),be(!1),ee(!1),Ae(null);return}if(!ve){ce(null),be(!1),ee(!0),Ae(null);return}let X=!1;const ye=async it=>{const ht=++_e.current;it||(ce(null),ee(!1),be(!0));try{const Ut=await qe();if(X||_e.current!==ht)return;ce(null),ee(!0),Ae(Ut)}catch(Ut){if(X||_e.current!==ht)return;it||(ce(h.sanitizeError(Ut,"Unable to calculate fees for this lock.")),ee(!1))}finally{!X&&_e.current===ht&&!it&&be(!1)}},Ct=window.setTimeout(()=>{ye(!1)},250),$e=window.setInterval(()=>{ye(!0)},3e4);return()=>{X=!0,clearTimeout(Ct),window.clearInterval($e)}},[e,ge,yt,ve,qe]),i.useEffect(()=>{if(De?.overallStatus==="success"){const X=De.steps.find(ye=>ye.transactionHash);y?.(X?.transactionHash)}},[De?.overallStatus,y]);const pt=x&&q?.asset?._source==="wallet"&&q?.asset?.chainId===c,ft=i.useCallback(()=>Pl(se.current),[]),ut=!!q?.asset&&Ne>0&&!_t&&!It&&!ge&&(!ve||G&&!Ce&&!ne),Pe=oe||ne,Tt=s.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[s.jsx(Us,{color:U}),s.jsxs("p",{style:{fontSize:"13px",color:U,margin:0,lineHeight:"1.5"},children:["Add ",r," by converting assets from your account"]})]});if(se.current={selectedAsset:q,parsedAmount:Ne,selectedDuration:Qe,isInsufficientBalance:It,isSemi7702:D,isSourceDestToken:de,isDirectDeposit:pt,requiresRelayerFeeEstimate:ve,address:Me,embeddedWalletAddress:fe,providerEmbeddedAddress:Se,externalWallet:ct,externalWalletAddress:Ke,activeSignerWallet:bt,activeSignerAddress:mt,isConnected:je,ready:we,authenticated:Ge,provider:Et,actions:Rt,lockChainId:c,escrowAddress:g,onLockExecute:C,onLockSuccess:y,buildSpicenetBatch:v,resolveLockBatches:te,startStatusPolling:zt,refreshSpiceAssets:Je,refreshWalletAssets:Ot,ui:{setError:K,setIsExecuting:Y,setShowStatusPanel:kt}},!e)return null;const He={backgroundColor:W,border:O,borderRadius:H,padding:"16px",marginBottom:"16px"};return s.jsx(un,{isOpen:e,onClose:t,title:`Add ${r} to your account`,subtitle:Tt,styles:w,dark:P,footerLinkText:"Spicenet accounts \u2192",overlayContent:vt?s.jsx("div",{}):void 0,closeOnBackdropClick:n,children:s.jsxs("div",{style:{padding:"0 24px 8px 24px",position:"relative"},children:[s.jsxs("div",{style:{marginBottom:"12px"},children:[A&&s.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:s.jsx(zs,{onClick:A,color:T,fontFamily:S})}),s.jsx("div",{style:{marginTop:"10px",fontSize:"13px",color:U,fontFamily:S},children:s.jsx(qn,{assets:dt,selectedAsset:q??void 0,onAssetSelect:Yt,onAmountChange:sn,label:"Amount",showBalance:!0,showMaxButton:!0,theme:ie,styles:z})}),s.jsx("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:U,fontFamily:S},children:Ht})]}),s.jsxs("div",{style:He,children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:P?`1px solid ${F.cardBorder}`:"1px solid #e5e7eb"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[a?s.jsx("img",{src:a,alt:r,style:{width:"32px",height:"32px",borderRadius:"50%",objectFit:"cover"}}):s.jsx("div",{style:{width:"32px",height:"32px",borderRadius:"50%",backgroundColor:P?F.inputBg:"#d1d5db",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:700,color:J},children:r.slice(0,2)}),s.jsx("span",{style:{fontSize:"16px",fontWeight:600,color:J,fontFamily:S},children:r})]}),s.jsxs("div",{style:{textAlign:"right"},children:[s.jsx("div",{style:{fontSize:"22px",fontWeight:700,color:J,fontFamily:S,lineHeight:1.1},children:ot??"0.00"}),s.jsxs("div",{style:{fontSize:"12px",color:U,fontFamily:S,marginTop:"2px"},children:["~$",ke??"0.00"]})]})]}),s.jsxs("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:P?`1px solid ${F.cardBorder}`:"1px solid #e5e7eb"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[s.jsx("span",{style:{fontSize:"15px",fontWeight:500,color:U,fontFamily:S},children:"Lock Duration"}),s.jsx(pn,{color:U})]}),s.jsx(Cl,{options:f,selectedIndex:me,onSelect:ue,primaryColor:T,dark:P,textPrimary:J,textSecondary:U})]}),s.jsxs("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[s.jsx(kl,{durationMonths:Qe?.months,fontFamily:S,dark:P,textPrimary:J,textSecondary:U}),p&&s.jsx(Sl,{votes:Xe,fontFamily:S,dark:P,textPrimary:J,textSecondary:U})]})]}),ve&&s.jsx(es,{fontFamily:S,textPrimary:J,textSecondary:U,cardBg:W,cardBorder:O,resolvedDark:P,darkCardBorder:F.cardBorder,primaryColor:T,feePreview:_,isLoading:Ce,errorText:ne}),Pe&&s.jsx(Rn,{variant:"error",palette:F,fontFamily:S,style:{marginBottom:"12px"},children:Pe}),s.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:ft,disabled:!ut,loading:ge,dark:P,styles:{...w,button:{...w?.button,backgroundColor:T}},children:ge?de?"LOCKING...":"CONVERTING...":_t?`MINIMUM ${fn}`:Ce&&ve?"CALCULATING FEES...":de?`LOCK ${r}`:`CONVERT TO ${r}`}),s.jsx(Il,{isOpen:vt,data:xe,isLocking:ge,lockError:Pe,onContinue:ft,onClose:()=>Ve(!1),primaryColor:T,fontFamily:S,dark:P}),De&&Be&&s.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:P?"rgba(0, 0, 0, 0.45)":"rgba(255, 255, 255, 0.55)",backdropFilter:"blur(2px)",WebkitBackdropFilter:"blur(2px)",borderRadius:H},children:s.jsx(Qs,{type:"lock",showStepBreakdown:!1,isOpen:!!De&&De.overallStatus!=="processing",isProcessing:ge||De?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{We(),kt(!1),ft()},onNewTx:()=>{We(),kt(!1),$(null),Te.current=null,Je(),Ot()},onClose:()=>{We(),kt(!1)},onComplete:()=>{We(),kt(!1),$(null),Te.current=null,Je(),Ot()},results:De?.overallStatus==="success"||De?.overallStatus==="failed"?De.steps.map(X=>({asset:{symbol:q?.asset?.symbol||r,address:q?.asset?.address||""},txHash:X.transactionHash||"",success:X.status==="success",amount:q?.amount})):void 0,chainName:h.getChainName(c),explorerUrl:h.getExplorerUrl(c,"").replace(/\/tx\/.*$/,"")||void 0,theme:E,styles:w,dark:P})})]})})},Wl="0xa9059cbb";function Sr(e,t,n){return B.isNativeToken(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"transfer",args:[n,t]})}}function Ir(e,t,n){return{chainId:n,calls:[Sr(e,t,B.getEscrowContractAddress(n))]}}function Ar(e,t,n){return!t&&e?.asset?._source==="wallet"&&e?.asset.chainId===n}function Er(e,t,n,o){return t!=="user-transfer"||!n||e.length===0||e[0]?.to.toLowerCase()!==o.toLowerCase()||!e[0]?.data.startsWith(Wl)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function hs(e,t,n,o){if(!t)return[e];const r=await t({...n,requestTimestampMs:o});return r?[r,e]:[e]}function Kn(e){return e.filter(t=>t.domain!=="spicenet")}function ms(e){const t=(e.tokenTransfers??[]).filter(n=>n.from==="escrow").map(n=>({token:B.normalizeNativeTokenAddress(n.token),recipient:n.to,amount:BigInt(n.amount)})).filter(n=>n.amount>0n);return t.length>0?t:void 0}function nn(e,t,n){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const o=10n**BigInt(t-n);return(e+o-1n)/o}async function so(e,t){const{currentPaymentAmount:n,destinationToken:o,embeddedWalletAddress:r,providerEmbeddedAddress:a,address:l,isNon7702:d,isPayMode:u,resolvedChainId:c,buildActionCalls:f,feeExecutionMode:p,buildSpicenetBatch:g,selectedAsset:x,needsSwap:m,exactOutputSwap:y,resolvedTokenIn:C,requestTimestampMs:k}=e,b=M.parseUnits(n,o.decimals),A=t?.actionAmountOverride??b,v=r||a||(d?void 0:l);if(!v)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const w={userAddress:v,chainId:c,destinationToken:o.address,grossAmount:t?.fundingAmountOverride??b,netAmount:A,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:p,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},R=f(A,w),E={chainId:c,calls:R},P=!u&&!d?!0:x?.asset?._source==="spice",T=Ar(x??null,d,c),F=P||d||T,S=(I,N)=>({token:I,from:d?"solver":"escrow",to:v,amount:N}),j=(I,N,D)=>T?[Ir(I,N,c),...D]:D;if(b===0n)return[E];if(m&&y){const I=C??rn(x.asset,c)??x.asset.address,N=t?.fundingAmountOverride??y.amountInMax,D=F?[S(I,N)]:[],L={to:I,value:0n,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"approve",args:[y.calls[0]?.to,y.amountInMax]})},Q={chainId:c,calls:[L,...y.calls,...R],tokenTransfers:[...D,...E.tokenTransfers??[]]};if(!F)return[Q];const W=await hs(Q,g,{userAddress:v,destinationChainId:c,deliveryToken:I,deliveryAmount:N,deliveryRecipient:v,deliveryTransfers:ms(Q),sourceAsset:x.asset},k);return j(I,N,W)}if(F){const I=C??rn(x.asset,c)??o.address,N=t?.fundingAmountOverride??b,D={...E,tokenTransfers:[S(I,N),...E.tokenTransfers??[]]},L=await hs(D,g,{userAddress:v,destinationChainId:c,deliveryToken:I,deliveryAmount:N,deliveryRecipient:v,deliveryTransfers:ms(D),sourceAsset:x.asset},k);return j(I,N,L)}return[E]}async function oo(e,t){const{selectedAsset:n,embeddedWalletAddress:o,externalWalletAddress:r,recipient:a,resolvedChainId:l,destinationToken:d,buildActionCalls:u,feeExecutionMode:c,buildSpicenetBatch:f,isPayMode:p,isNon7702:g,needsSwap:x,resolvedSwap:m,quoteAmountOut:y,resolvedTokenIn:C,requestTimestampMs:k}=e,b=m?.amountOutMinimum??y;if(!n?.asset||!o)return[];const A=a??(g?r:o);if(!A)return[];const v=t?.fundingAmountOverride??t?.actionAmountOverride??M.parseUnits(n.amount,n.asset.decimals),w=t?.fundingAmountOverride??v,R=t?.sourceFundingAmountOverride??v,E=t?.deliveryAmountOverride??w,P=t?.withdrawalAmountOverride??E,T=t?.actionAmountOverride??v,F={userAddress:A,chainId:l,destinationToken:d.address,feeToken:c==="user-transfer"&&x&&C?C:d.address,grossAmount:w,netAmount:T,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:c,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},S=u(T,F),j=n.asset?._source==="wallet";if(!p&&g&&j&&n.asset.chainId===l){if(x){if(!C)throw new Error("Swap input token could not be resolved");if(!m||b===null)throw new Error("Swap quote not available yet")}if(x&&m&&b){const U=u(t?.actionAmountOverride??b,{...F,netAmount:t?.actionAmountOverride??b}),{feeCall:z,remainingCalls:ie}=Er(U,c,x,F.feeToken);return[{chainId:l,calls:[...z?[z]:[],...m.calls,...ie]}]}return[{chainId:l,calls:S}]}if(!p&&!g&&j&&n.asset.chainId!==l)throw new Error("Cross-chain wallet supplies require external wallet mode");const I=!p&&!g?n.asset?._source!=="wallet":n.asset?._source==="spice",N=g&&j,D=Ar(n,g,l);if(!(I||N||D))return[{chainId:l,calls:S}];const L=D?Ir(C??B.normalizeNativeTokenAddress(n.asset.address),R,l):N&&n.asset.chainId!==l?{chainId:n.asset.chainId,calls:[Sr(B.normalizeNativeTokenAddress(n.asset.address),R,B.getEscrowContractAddress(n.asset.chainId))]}:null,Q=(U,z)=>({token:U,from:N?"solver":"escrow",to:o,amount:z}),W=(U,z)=>N?[{token:U,from:"escrow",to:B.SPICE_SOLVER_ADDRESS,amount:z}]:[];if(x){if(!C)throw new Error("Swap input token could not be resolved");if(!m||b===null)throw new Error("Swap quote not available yet")}if(x&&m&&b&&C){const U=u(t?.actionAmountOverride??b,{...F,netAmount:t?.actionAmountOverride??b}),{feeCall:z,remainingCalls:ie}=Er(U,c,x,F.feeToken),q={chainId:l,calls:[...z?[z]:[],...m.calls,...ie],tokenTransfers:[...W(C,P),Q(C,E)]},$=await hs(q,f,{userAddress:o,destinationChainId:l,deliveryToken:C,deliveryAmount:E,withdrawalAmount:P,deliveryRecipient:o,deliveryTransfers:ms(q),sourceAsset:n.asset},k);return L?[L,...$]:$}const O=C??rn(n.asset,l)??d.address,H={chainId:l,calls:S,tokenTransfers:[...W(O,P),Q(O,E)]},J=await hs(H,f,{userAddress:o,destinationChainId:l,deliveryToken:O,deliveryAmount:E,withdrawalAmount:P,deliveryRecipient:o,deliveryTransfers:ms(H),sourceAsset:n.asset},k);return L?[L,...J]:J}async function ro(e,t,n,o,r){let a=e;for(let l=0;l<4;l++){const d=await t(a),u=await o(d,n,a,r),c=Vi(u);if(c===null||c>=e)return a;const f=a-c,p=e+f;if(p<=a)return a;a=p}return a}function Ul(e,t,n,o){if(e<=0n)return 0n;const r=e-t;if(r<=0n)return 0n;const a=o+n;return a<=0n?r:r*o/a}function zl(e,t){const n=M.formatUnits(e,t);return n.includes(".")?n.replace(/\.?0+$/,"")||"0":n}async function jr(e){const{asset:t,isPayMode:n,isNon7702:o,needsSwap:r,isQuoting:a,embeddedWalletAddress:l,buildSupplyChainBatches:d,estimateGasless:u,executionTokenAddress:c,feeExecutionMode:f}=e;if(n||o||r||a||!l||t.balance<=0n)return null;const p=l,g=await d({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(g.length===0)return null;const x=g.some(A=>A.tokenTransfers?.length),m=await u(g,c,t.balance,x?{userOverride:p,useCustomTransfers:!0,feeExecutionMode:f}:f?{userOverride:p,feeExecutionMode:f}:{userOverride:p}),y=wn(m,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),C=y?nn(y.gasFee,y.decimals,t.decimals):0n,k=y?nn(y.spicenetFee,y.decimals,t.decimals):0n,b=Ul(t.balance,C,k,t.balance);return b>0n?zl(b,t.decimals):null}async function ao(e){const{selectedAsset:t,isPayMode:n,parsedAmount:o,needsSwap:r,exactOutputSwap:a,isNon7702:l,isSourceDestToken:d,currentPaymentAmount:u,destinationToken:c,feeExecutionMode:f,resolvedTokenIn:p,embeddedWalletAddress:g,providerEmbeddedAddress:x,resolvedChainId:m,isConnected:y,address:C,ready:k,authenticated:b,isDirect:A,resolvedSwap:v,isQuoting:w,executionTokenAddress:R,buildPayChainBatches:E,buildSupplyChainBatches:P,estimateGasless:T,estimateRequiredGrossFunding:F}=e;if(!t?.asset)return null;if(n){if(o<=0||r&&!a||d)return null;const W=M.parseUnits(u,c.decimals),O=p||rn(t.asset,m)||t.asset.address||c.address,H={chainId:m,tokenAddress:O,symbol:B.getTokenByAddress(O,m)?.symbol??t.asset.symbol,decimals:B.getTokenByAddress(O,m)?.decimals??t.asset.decimals};if(l){const $=g||x;if(!$)return null;const le=$,he=r?a?.amountInMax??0n:W;if(he===0n)return null;const me=await F(he,Y=>E({fundingAmountOverride:Y}).then(oe=>tn(Kn(oe),le)),O,{userOverride:$,useCustomTransfers:!0}),ue=tn(Kn(await E({fundingAmountOverride:me})),le),ge=await T(ue,O,me,{userOverride:$,useCustomTransfers:!0,feeExecutionMode:f});return wn(ge,H)}if(!y||!C||!k||!b)return null;const J=g||x||C,U=r?a?.amountInMax??0n:W;if(U===0n)return null;const z=await F(U,$=>E({fundingAmountOverride:$}).then(le=>tn(Kn(le),J)),O,{useCustomTransfers:!0});let ie=tn(Kn(await E({fundingAmountOverride:z})),J);const q=await T(ie,O,z,{useCustomTransfers:!0,feeExecutionMode:f});return wn(q,H)}if(o<=0||!g)return null;const S=g||x;if(!(!n&&!l&&t.asset?._source==="wallet"&&t.asset.chainId!==m)&&!A&&!v&&!w||w)return null;const j=M.parseUnits(t.amount,t.asset.decimals),I=await P();if(I.length===0)return null;const N=l&&t.asset?._source==="wallet"&&t.asset.chainId===m,D={chainId:m,tokenAddress:R,symbol:B.getTokenByAddress(R,m)?.symbol??c.symbol,decimals:B.getTokenByAddress(R,m)?.decimals??c.decimals};if(N){const W=await h.relayerService.estimateBatchGas({user:S,outputToken:R,stepIndex:0,chainBatches:I}),O=is(j,10n),H=O+W.gasFee;return{...D,grossAmount:j+H,netAmount:j,totalFee:H,gasFee:W.gasFee,spicenetFee:O,bridgeFee:0n,gasQuoteSource:W.gasQuoteSource}}const L=I.some(W=>W.tokenTransfers?.length),Q=await T(I,R,j,L?{userOverride:S,useCustomTransfers:!0,feeExecutionMode:f}:f?{userOverride:S,feeExecutionMode:f}:{userOverride:S});return wn(Q,D)}const Ol=10n;function Fr(e,t){const n=e.selectedAsset?.asset;if(!n||n?._source!=="wallet")return;const o=rn(n,e.resolvedChainId);if(!o||!h.addressesEqual(o,e.executionTokenAddress))return;const r=B.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),a=nn(t,r?.decimals??e.destinationToken.decimals,n.decimals);if(a<=n.balance)return;const l=M.formatUnits(a,n.decimals),d=M.formatUnits(n.balance,n.decimals);throw new Error(`Insufficient ${n.symbol} for amount plus fees. Required ${l} ${n.symbol}; available ${d} ${n.symbol}.`)}function io(e){const t=B.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:t?.symbol??e.destinationToken.symbol,decimals:t?.decimals??e.destinationToken.decimals}}function Zn(e,t,n){const o=wn(e,io(t));if(!o)return;const r=is(n,Ol),a=o.bridgeFee??0n,l=r+o.gasFee+a;return{grossAmount:n+l,netAmount:n,combinedFeeAmount:l,feeExecutionMode:"user-transfer",feeBreakdown:{spicenetFee:r,gasFee:o.gasFee,bridgeFee:a}}}function Wn(e,t,n){if(e===t)return!0;const o=e>t?e:t;return o===0n?!1:(e>t?e-t:t-e)*10000n<=o*n}function Br(e,t,n){let o=0n,r=0n;const a=n.toLowerCase();for(const l of e)if(l.chainId===t){for(const d of l.calls??[])if(d.to.toLowerCase()===a)try{const u=M.decodeFunctionData({abi:M.erc20Abi,data:d.data});if(u.functionName!=="transfer")continue;const c=u.args[0].toLowerCase(),f=u.args[1];c===B.SPICE_PLATFORM_FEE_RECIPIENT.toLowerCase()?o+=f:c===B.SPICE_GAS_FEE_RECIPIENT.toLowerCase()&&(r+=f)}catch{continue}}return{spicenetFee:o,gasFee:r}}function lo(e,t,n){const o=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,r=Br(e,t.resolvedChainId,o);return r.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||r.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:Wn(r.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&Wn(r.gasFee,n.feeBreakdown.gasFee,100n)}function Tr(e,t){return e?Wn(e.grossAmount,t.grossAmount,100n)&&Wn(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&Wn(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&Wn(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}async function co(e){if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.isNon7702){const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setTxHash(null);try{if(e.isSourceDestToken){e.ui.setStep("executing"),e.ui.setStatusMsg("Submitting transaction...");const o=await gs(e);e.ui.setTxHash(o??null)}else{e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.refs.spiceDepositSubmittedRef.current=!1;const o=new AbortController;e.refs.abortControllerRef.current=o,await Mr(e,o.signal)}e.ui.setStep("success"),e.ui.setStatusMsg(e.isSourceDestToken?"Transaction confirmed":"Deposit confirmed")}catch(o){const r=o instanceof Error?o:new Error(String(o));if(r.name==="AbortError"||e.refs.abortControllerRef.current?.signal.aborted){e.ui.setStep("idle");return}const a=r.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(a),e.ui.setError(a),e.onError?.(r)}finally{e.ui.setIsExecuting(!1)}return}if(!e.embeddedWalletAddress){e.ui.setError("Wallet not ready");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.ui.setTxHash(null),e.refs.spiceDepositSubmittedRef.current=!1;const t=new AbortController;e.refs.abortControllerRef.current=t;try{const n=M.parseUnits(e.selectedAsset.amount,e.selectedAsset.asset.decimals),o=n;let r=await e.gasless.buildSupplyChainBatches();const a=e.selectedAsset.asset?._source==="wallet",l=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!a&&!r.some(x=>B.isSpicenetChainId(x.chainId)))throw new Error("Spice-funded supplies must include a Spicenet funding batch before the destination chain batch.");const d=r.some(x=>x.tokenTransfers?.length)?{userOverride:l,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}:e.feeExecutionMode?{userOverride:l,feeExecutionMode:e.feeExecutionMode}:{userOverride:l};let u=n;const c=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,f=e.feeExecutionMode==="user-transfer"&&!c?o:void 0;let p;for(let x=0;x<4;x+=1){const m=await e.gasless.estimateGasless(r,e.executionTokenAddress,u,d),y=wn(m,io(e));p=e.feeExecutionMode==="user-transfer"&&y?Zn(m,e,o):void 0;const C=p?.grossAmount??y?.grossAmount??u;if(C===u){u=C;break}u=C,r=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:f,actionContextOverride:p})}e.feeExecutionMode==="user-transfer"&&(Fr(e,u),r=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:f,actionContextOverride:p}));let g=p;await e.gasless.executeGasless(r,e.executionTokenAddress,u,e.gasless.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...d,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:x,chainBatches:m})=>{const y=Zn(x,e,o);if(!y)return null;const C=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&e.resolvedTokenIn?e.resolvedTokenIn:e.executionTokenAddress;Br(m,e.resolvedChainId,C);const k=Tr(g,y),b=lo(m,e,y);return k||b?null:(g=y,e.gasless.buildSupplyChainBatches({fundingAmountOverride:y.grossAmount,actionAmountOverride:f,actionContextOverride:y}))}}:d),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){const o=n instanceof Error?n:new Error(String(n));if(o.name==="AbortError"||t.signal.aborted){e.ui.setStep("idle");return}const r=o.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(r),e.ui.setError(r),e.onError?.(o)}finally{e.ui.setIsExecuting(!1)}}async function Mr(e,t){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const n=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!n)throw new Error("Embedded wallet not available \u2014 sign in to create one before supplying");const o=e.selectedAsset.asset,r=M.parseUnits(e.selectedAsset.amount,o.decimals),a=r,l=o?._source==="wallet"&&o.chainId===e.resolvedChainId;let d=await e.gasless.buildSupplyChainBatches();const u={userOverride:n,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,signAuthorizationsForEstimate:!0};let c=r;const f=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,p=e.feeExecutionMode==="user-transfer"&&!f?a:void 0;let g;if(l){const S=await h.relayerService.estimateBatchGas({user:n,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:d}),j=is(r,10n),I=j+S.gasFee;c=r+I,e.feeExecutionMode==="user-transfer"&&(g={grossAmount:c,netAmount:a,combinedFeeAmount:I,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:j,gasFee:S.gasFee,bridgeFee:0n}})}else for(let S=0;S<4;S+=1){const j=await e.gasless.estimateGasless(d,e.executionTokenAddress,0n,u),I=e.feeExecutionMode==="user-transfer"?Zn(j,e,a):void 0,N=wn(j,io(e)),D=I?.grossAmount??(N?N.grossAmount>r?N.grossAmount:r:c);if(g=I,D===c){c=D;break}c=D;const L=B.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),Q=nn(c,L?.decimals??e.destinationToken.decimals,o.decimals);d=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:Q,withdrawalAmountOverride:c,actionAmountOverride:p,actionContextOverride:I})}const x=B.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);let m=l?c:nn(c,x?.decimals??e.destinationToken.decimals,o.decimals);Fr(e,c),d=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:m,withdrawalAmountOverride:c,actionAmountOverride:p,actionContextOverride:g});const y=o.chainId,C=n,k=await e.externalWallet.getEthereumProvider();let b=null;try{const S=await k.request({method:"eth_chainId"});b=parseInt(S,16)}catch{b=null}b!==y&&(e.ui.setStatusMsg("Switching source network..."),await h.ensureWalletOnChain(k,y));const A=h.getChainConfig(y),v=M.createWalletClient({account:e.externalWalletAddress,chain:A?.viemChain,transport:M.custom(k)}),w=B.normalizeNativeTokenAddress(o.address),R=o.isNative||B.isNativeToken(w),E=h.getClientForChain(y),P=async S=>{if(S<=0n)return;const j=R?await v.sendTransaction({to:C,value:S,chain:A?.viemChain}):await v.sendTransaction({to:w,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"transfer",args:[C,S]}),chain:A?.viemChain});if((await E.waitForTransactionReceipt({hash:j,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Embedded wallet funding failed")};e.ui.setStatusMsg("Funding embedded wallet..."),await P(m);let T=m;if(e.feeExecutionMode==="user-transfer")for(let S=0;S<4;S+=1){const j=await e.gasless.estimateGasless(d,e.executionTokenAddress,0n,u),I=Zn(j,e,a);if(!I)break;const N=l?I.grossAmount:nn(I.grossAmount,x?.decimals??e.destinationToken.decimals,o.decimals);if(N>T&&(e.ui.setStatusMsg("Topping up embedded wallet..."),await P(N-T),T=N),g=I,c=I.grossAmount,m=N,d=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:m,withdrawalAmountOverride:c,actionAmountOverride:p,actionContextOverride:I}),lo(d,e,I))break}e.ui.setStatusMsg("Signing supply intent...");let F=g;await e.gasless.executeGasless(d,e.executionTokenAddress,0n,e.gasless.onProgress,t,e.feeExecutionMode==="user-transfer"?{...u,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:S,chainBatches:j})=>{const I=Zn(S,e,a);if(!I)return null;const N=Tr(F,I),D=lo(j,e,I);if(N||D)return null;if(I.grossAmount>c)throw new Error("Fee estimate increased after wallet funding. Please retry so the signed fee can match the latest relayer estimate.");F=I;const L=l?I.grossAmount:nn(I.grossAmount,x?.decimals??e.destinationToken.decimals,o.decimals);return e.gasless.buildSupplyChainBatches({fundingAmountOverride:I.grossAmount,sourceFundingAmountOverride:L,withdrawalAmountOverride:I.grossAmount,actionAmountOverride:p,actionContextOverride:I})}}:u)}async function gs(e){const t=e.isPayMode&&e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t)throw new Error("Select a payment source");const n=e.activeSignerWallet??e.externalWallet,o=e.activeSignerAddress??e.externalWalletAddress;if(!o||!n)throw new Error("Please connect your wallet to continue");const r=M.parseUnits(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),a={userAddress:o,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},l=e.buildActionCalls(r,a);if(l.length===0)throw new Error("No action calls configured");const d=await n.getEthereumProvider();let u=null;try{const x=await d.request({method:"eth_chainId"});u=parseInt(x,16)}catch{u=null}u!==e.resolvedChainId&&await h.ensureWalletOnChain(d,e.resolvedChainId);const c=h.getChainConfig(e.resolvedChainId),f=M.createWalletClient({account:o,chain:c?.viemChain,transport:M.custom(d)}),p=h.getClientForChain(e.resolvedChainId);let g;for(const x of l){const m=await f.sendTransaction({to:x.to,data:x.data,value:x.value,chain:c?.viemChain});if((await p.waitForTransactionReceipt({hash:m,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transaction failed");g=m}return g}async function Rr(e){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const n=e.selectedAsset.asset,o=n.chainId,r=M.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),a=e.selectedIsEquivalent?r:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(a===0n)throw new Error("Quote not available yet");const l=e.resolvedTokenIn||e.selectedAsset.asset.address,d={userOverride:t,useCustomTransfers:!0},u=await e.gasless.estimateRequiredGrossFunding(a,b=>e.gasless.buildPayChainBatches({fundingAmountOverride:b}),l,d),c=B.getEscrowContractAddress(o),f=await e.externalWallet.getEthereumProvider();let p=null;try{const b=await f.request({method:"eth_chainId"});p=parseInt(b,16)}catch{p=null}p!==o&&await h.ensureWalletOnChain(f,o);const g=h.getChainConfig(o),x=M.createWalletClient({account:e.externalWalletAddress,chain:g?.viemChain,transport:M.custom(f)}),m=B.normalizeNativeTokenAddress(n.address),y=n.isNative||B.isNativeToken(m)?await x.sendTransaction({to:c,value:u,chain:g?.viemChain}):await x.sendTransaction({to:m,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"transfer",args:[c,u]}),chain:g?.viemChain});if((await h.getClientForChain(o).waitForTransactionReceipt({hash:y,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Escrow deposit failed");const C=await e.gasless.buildPayChainBatches({fundingAmountOverride:u}),k=C.some(b=>b.tokenTransfers?.length);return await e.gasless.executeGasless(C,l,u,b=>{b.txHash&&(e.ui.setPaymentResult(A=>({...A??{status:"processing"},txHash:b.txHash})),e.ui.setTxHash(b.txHash))},void 0,k?d:{userOverride:t})}async function uo(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}const t=e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t){e.ui.setError("Select a payment source");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.parsedAmount>0&&e.needsSwap&&!e.exactOutputSwap){e.ui.setError("Swap quote not available. Try a different asset.");return}if(e.isNon7702){const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken||t?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{let o;if(e.isSourceDestToken||e.parsedAmount===0)o=await gs(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const r=e.selectedAsset.asset,a=M.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),l=e.selectedIsEquivalent?a:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(l===0n)throw new Error("Quote not available yet");const d=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!d)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const u=e.resolvedTokenIn||r.address,c=await e.gasless.estimateRequiredGrossFunding(l,g=>e.gasless.buildPayChainBatches({fundingAmountOverride:g}),u,{userOverride:d,useCustomTransfers:!0}),f=await e.gasless.buildPayChainBatches({fundingAmountOverride:c}),p=await e.onPayExecute({asset:r,amount:e.currentPaymentAmount,amountWei:a,destinationToken:e.destinationToken,chainBatches:f,requiredNetFunding:l,grossFundingAmount:c,selectedIsEquivalent:e.selectedIsEquivalent,resolvedTokenIn:u,exactOutputSwapAmountInMax:e.exactOutputSwap?.amountInMax});p&&(e.ui.setTxHash(p),e.ui.setPaymentResult(g=>({...g??{status:"processing"},txHash:p}))),o=p||void 0}else o=await Rr(e);e.ui.setPaymentResult(r=>({status:"success",txHash:r?.txHash||o||""}))}catch(o){const r=h.sanitizeError(o,"Payment failed. Please try again.");e.ui.setError(r),e.ui.setPaymentResult({status:"failed",error:r}),e.onError?.(o instanceof Error?o:new Error(r))}finally{e.ui.setIsExecuting(!1)}return}if(e.isSourceDestToken){if(!(e.activeSignerAddress??e.externalWalletAddress??e.address)){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{const n=await gs(e);e.ui.setPaymentResult(o=>({status:"success",txHash:o?.txHash||n||""}))}catch(n){const o=h.sanitizeError(n,"Payment failed. Please try again.");e.ui.setError(o),e.ui.setPaymentResult({status:"failed",error:o}),e.onError?.(n instanceof Error?n:new Error(o))}finally{e.ui.setIsExecuting(!1)}return}if(!e.isConnected||!e.address){e.ui.setError("Please connect your wallet to continue");return}if(!e.ready||!e.authenticated){e.ui.setError(`Please authenticate with ${e.provider||"wallet provider"} to continue`);return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{const n=M.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),o={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode};if(t){const C=await e.gasless.buildPayChainBatches({actionAmountOverride:0n,fundingAmountOverride:0n}),k=await e.gasless.executeGasless(C,e.destinationToken.address,0n,b=>{b.txHash&&(e.ui.setPaymentResult(A=>({...A,txHash:b.txHash})),e.ui.setTxHash(b.txHash))},void 0,o);e.ui.setPaymentResult(b=>({status:"success",txHash:b?.txHash||k}));return}const r=e.selectedAsset?.asset;if(!r)throw new Error("Select a payment source");const a=e.resolvedTokenIn||r.address||e.destinationToken.address,l=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:n,d=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,u=(C,k,b)=>{const A=Kn(C),v=E=>(E.tokenTransfers??[]).some(P=>P.from==="escrow"),w=A.filter(E=>!v(E)),R=A.filter(v);return[...w,...tn(R,d,k,b)]},c=await e.gasless.estimateRequiredGrossFunding(l,C=>e.gasless.buildPayChainBatches({fundingAmountOverride:C}).then(k=>u(k)),a,o);let f=c,p=u(await e.gasless.buildPayChainBatches({fundingAmountOverride:c}));const g=await e.gasless.estimateGasless(p,a,c,o),x=wn(g,{chainId:e.resolvedChainId,tokenAddress:a,symbol:B.getTokenByAddress(a,e.resolvedChainId)?.symbol??r.symbol,decimals:B.getTokenByAddress(a,e.resolvedChainId)?.decimals??r.decimals})?.grossAmount??c;x!==c&&(f=x),p=u(await e.gasless.buildPayChainBatches({fundingAmountOverride:f}),g,{payoutAlreadyGross:!0});const m=p.some(C=>C.tokenTransfers?.length),y=await e.gasless.executeGasless(p,a,m?f:0n,C=>{C.txHash&&(e.ui.setPaymentResult(k=>({...k,txHash:C.txHash})),e.ui.setTxHash(C.txHash))},void 0,o);e.ui.setPaymentResult(C=>({status:"success",txHash:C?.txHash||y}))}catch(n){const o=h.sanitizeError(n,"Payment failed. Please try again.");e.ui.setError(o),e.ui.setPaymentResult({status:"failed",error:o}),e.onError?.(n instanceof Error?n:new Error(o))}finally{e.ui.setIsExecuting(!1)}}const Ll=({variant:e,destinationSymbol:t,destinationLogoURI:n,destinationDecimals:o,primaryColor:r,fontFamily:a,textPrimary:l,textSecondary:d,cardBg:u,cardBorder:c,dk:f,dark:p,isQuoting:g,quoteError:x,estimatedOutput:m,paymentAmount:y,needsSwap:C,exactOutputSwap:k,adjustable:b=!1,maxAmount:A,onAmountChange:v})=>e==="supply"?s.jsxs("div",{style:{backgroundColor:u,border:`1px solid ${c}`,borderRadius:p?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",minHeight:"112px",display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"12px"},children:[s.jsxs("div",{style:{minWidth:0},children:[s.jsx("span",{style:{fontFamily:a,fontSize:"17px",fontWeight:500,color:p?"#a7abb2":"#7D7C7B",lineHeight:"24px"},children:"Used in TX"}),s.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:d,fontFamily:a,marginTop:"10px"},children:"Net amount after swap and fees"})]}),s.jsxs("div",{style:{textAlign:"right",minWidth:0,display:"inline-flex",alignItems:"center",gap:"8px",border:`1px solid ${c}`,borderRadius:"8px",padding:"8px 10px",minHeight:"42px"},children:[s.jsx(Nr,{symbol:t,logoURI:n,primaryColor:r,size:24}),s.jsx("span",{style:{fontSize:"16px",fontWeight:500,color:p?"#f3f4f6":"#3C3E42",lineHeight:"1.3",fontFamily:a,letterSpacing:0},children:t})]})]}),s.jsx("div",{style:{textAlign:"right",minWidth:0},children:g?s.jsx("span",{style:{fontSize:"18px",color:d,fontFamily:a},children:"Quoting..."}):x?s.jsx("span",{style:{fontSize:"13px",color:p?"#f87171":"#dc2626",fontFamily:a},children:"Quote failed"}):m?s.jsx(Sn,{value:m,title:m,fontFamily:a,color:l,lineHeight:"0.95",textAlign:"right",maxFontSize:32,minFontSize:18}):s.jsx("span",{style:{fontSize:"20px",color:d,fontFamily:a},children:"\u2014"})})]}):s.jsx(Hl,{destinationSymbol:t,destinationLogoURI:n,destinationDecimals:o,primaryColor:r,fontFamily:a,textPrimary:l,textSecondary:d,cardBg:u,cardBorder:c,dk:f,dark:p,paymentAmount:y||"0",needsSwap:C,exactOutputSwap:k,isQuoting:g,adjustable:b,maxAmount:A,onAmountChange:v}),Dr=i.memo(Ll),Nr=({symbol:e,logoURI:t,primaryColor:n,size:o})=>t?s.jsx("img",{src:t,alt:e,style:{width:o,height:o,borderRadius:"50%",objectFit:"cover"}}):s.jsx("div",{style:{width:o,height:o,borderRadius:"50%",backgroundColor:`${n}22`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:o<30?"11px":"12px",fontWeight:700,color:n},children:e.slice(0,2)}),Hl=({destinationSymbol:e,destinationLogoURI:t,destinationDecimals:n,primaryColor:o,fontFamily:r,textPrimary:a,textSecondary:l,cardBg:d,cardBorder:u,dk:c,dark:f,paymentAmount:p,needsSwap:g,exactOutputSwap:x,isQuoting:m,adjustable:y,maxAmount:C,onAmountChange:k})=>{const b='"IBM Plex Mono", monospace',A=parseFloat(p||"0"),v=C?parseFloat(C):0,[w,R]=i.useState(p||""),E=i.useRef(null),[P,T]=i.useState(null),[F,S]=i.useState(null);i.useEffect(()=>{y||R(p||"")},[p,y]);const j=D=>{let L=D;L.startsWith(".")&&(L="0"+L);const Q=Tn(L);let W=Q;C&&parseFloat(Q)>parseFloat(C)&&(W=C),R(W),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>k?.(W),300)},I=D=>{if(!v)return;if(D===100){R(C||v.toString()),E.current&&clearTimeout(E.current),k?.(C||v.toString());return}const L=10**n,Q=Math.floor(v*D/100*L)/L,W=Mn(Q,n);R(W),E.current&&clearTimeout(E.current),k?.(W)},N=v>0?parseFloat(w||"0")/v*100:0;return i.useEffect(()=>()=>{E.current&&clearTimeout(E.current)},[]),s.jsxs("div",{style:{backgroundColor:d,border:`1px solid ${u}`,borderRadius:f?"12px":"6px",padding:"16px",marginBottom:"16px"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[s.jsx(Nr,{symbol:e,logoURI:t,primaryColor:o,size:32}),s.jsxs("div",{children:[s.jsx("span",{style:{fontSize:"14px",fontWeight:600,color:a,fontFamily:r},children:"Payment"}),s.jsx("div",{style:{fontSize:"12px",color:l,fontFamily:r,marginTop:"2px"},children:e})]})]}),s.jsxs("div",{style:{textAlign:"right"},children:[y?s.jsx(Sn,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:w,onChange:D=>j(D.target.value),placeholder:"0.0",fontFamily:b,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):s.jsx(Sn,{element:"div",value:A>0?p:"0.00",title:A>0?p:"0.00",fontFamily:b,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),s.jsx("div",{style:{fontSize:"12px",color:l,fontFamily:b,marginTop:"2px"},children:e}),y&&v>0&&s.jsx("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((D,L)=>{const Q=Math.abs(N-D)<1,W=L===4,O=D/100,H=P===D,J=F===D;return s.jsx("button",{onClick:()=>I(D),onMouseEnter:()=>T(D),onMouseLeave:()=>{T(null),S(null)},onMouseDown:()=>S(D),onMouseUp:()=>S(null),title:`${D}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:Q?1:H?.8:.5,transform:J?"scale(0.85)":H?"scale(1.15)":"scale(1)",transition:Jt.interactive},children:s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[s.jsx("circle",{cx:"7",cy:"7",r:"6.84375",fill:W?o:"none",stroke:W?o:f?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!W&&O>0&&s.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${O>.5?1:0} 1 ${7+6.84375*Math.sin(O*2*Math.PI)} ${7-6.84375*Math.cos(O*2*Math.PI)} Z`,fill:f?c?.textSecondary||"#9ca3af":"#3C3E42"})]})},D)})})]})]}),g&&x&&!m&&s.jsx("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:f?`1px solid ${c?.cardBorder||u}`:"1px solid #e5e7eb",display:"flex",justifyContent:"flex-end"},children:s.jsxs("span",{style:{fontSize:"11px",color:l,fontFamily:r,opacity:.7},children:["via ",x.venue]})})]})};function Pr(e,t,n){const o=h.addressesEqual(e.address,t),r=e.chainId===n,a=e._source==="wallet";return a&&o&&r?0:a&&r?1:!a&&o?2:!a&&r?3:4}function Wr(e,t){return!t||t.length===0||t.some(n=>h.addressesEqual(n,e.address))?!0:Object.keys(e.chainTokens??{}).some(n=>{const o=Nn(n);return o?t.some(r=>h.addressesEqual(r,o.address)):!1})}function po(e){const{destinationToken:t,supportedSourceAssets:n,sourceChains:o,enabled:r}=e,a=(i.useContext(h.SpiceFlowProviderContext)?.mode||"7702")!=="7702",l=h.useEmbeddedWalletAddress(),{externalAddress:d,embeddedAddress:u,activeAddress:c}=h.useProviderWallets(),f=l||u,{assets:p,refetch:g}=Vn({address:f,supportedChains:o,enabled:r&&!a&&!!f,refetchInterval:3e4}),x=i.useMemo(()=>a?[]:p.filter(P=>Wr(P,n)),[p,n,a]),m=a?c??d:l,y=i.useMemo(()=>{const P=new Set,T=[],F=S=>{if(!S)return;const j=S.toLowerCase();P.has(j)||(P.add(j),T.push(M.getAddress(S)))};if(F(t.address),n)for(const S of n)F(S);return T},[a,t.address,n]),C=i.useMemo(()=>y.map(P=>P.toLowerCase()).sort().join(","),[y]),k=i.useMemo(()=>JSON.stringify([...o||[]].sort()),[o]),[b,A]=i.useState([]),v=i.useRef(0),w=i.useRef(async()=>{}),R=i.useCallback(async()=>{if(!r||!m||y.length===0){v.current++,A([]);return}const P=++v.current,T=M.getAddress(m),F=a?o&&o.length>0?o:[t.chainId]:[t.chainId],S=[];for(const D of y){const L=D.toLowerCase();if(L===B.ZERO_ADDRESS)continue;if(L===t.address.toLowerCase()){const W=h.getChainConfig(t.chainId)?.supportedTokens?.find(O=>h.addressesEqual(O.address,L));S.push({address:D,chainId:t.chainId,configToken:W?{decimals:W.decimals,symbol:W.symbol,name:W.name,logo:W.logo}:void 0});continue}let Q=!1;for(const W of F){const O=h.getChainConfig(W)?.supportedTokens?.find(H=>h.addressesEqual(H.address,L));if(O){S.push({address:D,chainId:W,configToken:{decimals:O.decimals,symbol:O.symbol,name:O.name,logo:O.logo}}),Q=!0;break}}Q||S.push({address:D,chainId:t.chainId})}const j=new Map;for(const D of S){const L=j.get(D.chainId)||[];L.push(D),j.set(D.chainId,L)}const I=async(D,L)=>{try{const Q=await Zt.readContract(D,{address:L.address,abi:M.erc20Abi,functionName:"balanceOf",args:[T]});let W,O,H,J;if(L.configToken)W=L.configToken.decimals,O=L.configToken.symbol,H=L.configToken.name,J=L.configToken.logo;else{const[ie,q,$]=await Promise.all([Zt.readContract(D,{address:L.address,abi:M.erc20Abi,functionName:"decimals"}).catch(()=>18),Zt.readContract(D,{address:L.address,abi:M.erc20Abi,functionName:"symbol"}).catch(()=>"TOKEN"),Zt.readContract(D,{address:L.address,abi:M.erc20Abi,functionName:"name"}).catch(()=>"TOKEN")]);W=Number(ie),O=q,H=$}const U=h.addressesEqual(L.address,t.address)&&L.chainId===t.chainId;U&&t.logoURI&&(J=t.logoURI),U&&!L.configToken&&O==="TOKEN"&&(O=t.symbol,H=t.symbol);const z=parseFloat((Number(Q)/Math.pow(10,W)).toFixed(6));return{address:L.address,name:H,symbol:O,decimals:W,balance:Q,balanceFormatted:z,balanceUsd:0,logoURI:J,isNative:!1,chainId:L.chainId}}catch{return null}},N=await Promise.all(Array.from(j.entries()).map(async([D,L])=>{let Q;try{Q=h.getClientForChain(D)}catch{return[]}const W=[],O=[];for(const J of L){const U=W.length;W.push({address:J.address,abi:M.erc20Abi,functionName:"balanceOf",args:[T]}),J.configToken||W.push({address:J.address,abi:M.erc20Abi,functionName:"decimals"},{address:J.address,abi:M.erc20Abi,functionName:"symbol"},{address:J.address,abi:M.erc20Abi,functionName:"name"}),O.push({start:U,item:J})}let H=null;try{H=await Q.multicall({contracts:W})}catch{H=null}return H?O.map(({start:J,item:U})=>{const z=H[J],ie=z?.status==="success"?z.result:0n;let q,$,le,he;if(U.configToken)q=U.configToken.decimals,$=U.configToken.symbol,le=U.configToken.name,he=U.configToken.logo;else{const ge=H[J+1],Y=H[J+2],oe=H[J+3];q=ge?.status==="success"?Number(ge.result):18,$=Y?.status==="success"?Y.result:"TOKEN",le=oe?.status==="success"?oe.result:$}const me=h.addressesEqual(U.address,t.address)&&U.chainId===t.chainId;me&&t.logoURI&&(he=t.logoURI),me&&!U.configToken&&$==="TOKEN"&&($=t.symbol,le=t.symbol);const ue=parseFloat((Number(ie)/Math.pow(10,q)).toFixed(6));return{address:U.address,name:le,symbol:$,decimals:q,balance:ie,balanceFormatted:ue,balanceUsd:0,logoURI:he,isNative:!1,chainId:U.chainId}}):(await Promise.all(L.map(J=>I(Q,J)))).filter(J=>J!==null)}));P===v.current&&A(N.flat())},[r,a,m,C,k,t.address,t.chainId,t.symbol,t.logoURI]);i.useEffect(()=>{w.current=R},[R]),i.useEffect(()=>{if(!r){A([]);return}w.current();const P=setInterval(()=>{w.current()},15e3);return()=>clearInterval(P)},[r,a,m,C,k,t.address,t.chainId]);const E=i.useCallback(()=>{R()},[R]);return{displayAssets:i.useMemo(()=>{const P=[],T=b.filter(S=>S.balance>0n);for(const S of T)P.push({...S,_source:"wallet"});for(const S of x)P.push({...S,_source:"spice"});const F=t.address.toLowerCase();return P.sort((S,j)=>Pr(S,F,t.chainId)-Pr(j,F,t.chainId)),P},[b,x,t.address,t.chainId]),filteredSpiceAssets:x,walletAssets:b,embeddedWalletAddress:f,externalAddress:d,isNon7702:a,refreshSpiceAssets:g,refreshWalletAssets:E}}async function Ur(e){const{tokenIn:t,tokenOut:n,amountIn:o,fee:r,chainId:a,config:l}=e;if(o<=0n)throw new Error("amountIn must be greater than 0");const d=(await h.getClientForChain(a).simulateContract({address:l.quoterV2,abi:B.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:o,fee:r,sqrtPriceLimitX96:0n}]})).result;if(d[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:d[0],sqrtPriceX96After:d[1],gasEstimate:d[3]}}async function zr(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(r=>Ur({...e,fee:r})));let o=null;for(let r=0;r<n.length;r++){const a=n[r];a.status==="fulfilled"&&(!o||a.value.amountOut>o.amountOut)&&(o={...a.value,fee:t[r]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}const ql=[{inputs:[{components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"amount",type:"uint256"},{name:"fee",type:"uint24"},{name:"sqrtPriceLimitX96",type:"uint160"}],name:"params",type:"tuple"}],name:"quoteExactOutputSingle",outputs:[{name:"amountIn",type:"uint256"},{name:"sqrtPriceX96After",type:"uint160"},{name:"initializedTicksCrossed",type:"uint32"},{name:"gasEstimate",type:"uint256"}],stateMutability:"nonpayable",type:"function"}];async function Ql(e){const{tokenIn:t,tokenOut:n,amountOut:o,fee:r,chainId:a,config:l}=e;if(o<=0n)throw new Error("amountOut must be greater than 0");const d=(await h.getClientForChain(a).simulateContract({address:l.quoterV2,abi:ql,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:o,fee:r,sqrtPriceLimitX96:0n}]})).result;if(d[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:d[0],sqrtPriceX96After:d[1],gasEstimate:d[3]}}async function Vl(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(r=>Ql({...e,fee:r})));let o=null;for(let r=0;r<n.length;r++){const a=n[r];a.status==="fulfilled"&&(!o||a.value.amountIn<o.amountIn)&&(o={...a.value,fee:t[r]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}function Or(e){return e.type==="swap"}const fo=.02,Gl=[1,8453,42161,10,137,43114,56],Kl="https://api.1inch.dev/swap/v6.0";function Lr(e,t){return B.applySlippage(e,t)}function Hr(e){const t=e?.baseUrl??Kl;return{name:"1inch",chainIds:e?.chainIds??Gl,resolve:async(n,o,r)=>{const a=n.maxSlippage??fo,l=a*100,d=B.isNativeToken(n.tokenIn)?B.NATIVE_TOKEN_ADDRESS:n.tokenIn,u=B.isNativeToken(n.tokenOut)?B.NATIVE_TOKEN_ADDRESS:n.tokenOut,c=B.isNativeToken(n.tokenIn);try{const f=new URL(`${t}/${o}/swap`);f.searchParams.set("src",d),f.searchParams.set("dst",u),f.searchParams.set("amount",n.amountIn.toString()),f.searchParams.set("from",r),f.searchParams.set("slippage",l.toString()),f.searchParams.set("disableEstimate","true"),f.searchParams.set("allowPartialFill","false");const p={Accept:"application/json"};e?.apiKey&&(p.Authorization=`Bearer ${e.apiKey}`);const g=await fetch(f.toString(),{headers:p});if(!g.ok)throw new h.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${g.status} for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`,{venue:"1inch",chainId:o,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:`HTTP ${g.status}`});const x=await g.json();if(!x.dstAmount||!x.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const m=BigInt(x.dstAmount);if(m<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const y=Lr(m,a),C=[];return x.tx.to&&!c&&C.push({to:n.tokenIn,value:0n,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"approve",args:[x.tx.to,n.amountIn]})}),C.push({to:x.tx.to,value:BigInt(x.tx.value||"0"),data:x.tx.data}),{venue:"1inch",amountOut:m,amountOutMinimum:y,calls:C}}catch(f){if(f instanceof h.SpiceflowError)throw f;const p=f instanceof Error?f.message:String(f);throw new h.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}: ${p}`,{venue:"1inch",chainId:o,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:p})}}}}const qr=[4114,5115],ho={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},Qr={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[3e3]};function Vr(e){return{name:"satsuma",chainIds:e.chainIds??qr,resolve:async(t,n,o)=>{const r=t.maxSlippage??fo,a=B.isNativeToken(t.tokenIn);let l;try{l=await zr({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountIn:t.amountIn,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return console.warn(`[SatsumaVenue] No viable fee tier for ${t.tokenIn} \u2192 ${t.tokenOut} on chain ${n}.`),null}const d=Lr(l.amountOut,r),u=[];return a||u.push({to:t.tokenIn,value:0n,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),u.push({to:e.swapRouter,value:a?t.amountIn:0n,data:M.encodeFunctionData({abi:B.uniV3SwapRouterAbi,functionName:"exactInputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:l.fee,recipient:o,amountIn:t.amountIn,amountOutMinimum:d,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:l.amountOut,amountOutMinimum:d,calls:u}}}}function Gr(e){return{name:"satsuma",chainIds:e.chainIds??qr,resolve:async(t,n,o)=>{const r=t.maxSlippage??fo,a=B.isNativeToken(t.tokenIn);let l;try{l=await Vl({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountOut:t.amountOut,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return null}const d=BigInt(Math.round(r*1e4)),u=l.amountIn+l.amountIn*d/10000n,c=[];return c.push({to:e.swapRouter,value:a?u:0n,data:M.encodeFunctionData({abi:Zl,functionName:"exactOutputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:l.fee,recipient:o,amountOut:t.amountOut,amountInMaximum:u,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:l.amountIn,amountInMax:u,amountOut:t.amountOut,calls:c}}}}const Zl=[{inputs:[{components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"fee",type:"uint24"},{name:"recipient",type:"address"},{name:"amountOut",type:"uint256"},{name:"amountInMaximum",type:"uint256"},{name:"sqrtPriceLimitX96",type:"uint160"}],name:"params",type:"tuple"}],name:"exactOutputSingle",outputs:[{name:"amountIn",type:"uint256"}],stateMutability:"payable",type:"function"}];function Kr(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(Vr(e.satsuma)),t.push(Hr(e?.oneInch));function n(r){return t.find(a=>a.chainIds.includes(r))}async function o(r,a,l){const d=[],u=[];for(const c of r){if(!Or(c)){d.push(c);continue}const f=n(a);if(!f)throw new h.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${a}. Cannot resolve swap ${c.tokenIn} \u2192 ${c.tokenOut}.`,{chainId:a,tokenIn:c.tokenIn,tokenOut:c.tokenOut,amountIn:c.amountIn.toString()});const p=await f.resolve(c,a,l);if(!p)throw new h.SpiceflowError("NO_LIQUIDITY",`${f.name} returned no quote for ${c.tokenIn} \u2192 ${c.tokenOut} on chain ${a}.`,{venue:f.name,chainId:a,tokenIn:c.tokenIn,tokenOut:c.tokenOut,amountIn:c.amountIn.toString()});d.push(...p.calls),u.push(p)}return{calls:d,resolvedSwaps:u}}return{resolveSwapIntents:o,getVenueForChain:n,venues:t}}function Zr(e){const t=e?.customVenues??[];async function n(o,r,a){const l=t.filter(u=>u.chainIds.includes(r));if(l.length===0)throw new h.SpiceflowError("NO_SWAP_ROUTE",`No exact-output venue supports chain ${r}`,{chainId:r,tokenIn:o.tokenIn,tokenOut:o.tokenOut});const d=(await Promise.allSettled(l.map(u=>u.resolve(o,r,a)))).filter(u=>u.status==="fulfilled").map(u=>u.value).filter(u=>u!==null);if(d.length===0)throw new h.SpiceflowError("NO_SWAP_ROUTE",`All aggregators failed for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${r}`,{chainId:r,tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountOut:o.amountOut.toString()});return d.sort((u,c)=>u.amountIn<c.amountIn?-1:u.amountIn>c.amountIn?1:0),d[0]}return{getQuote:n,venues:t}}const Yr=Kr({satsuma:ho});async function Yl(e){const t=Yr.getVenueForChain(e.chainId);if(!t)throw new Error(`No swap venue configured for chain ${e.chainId}.`);const n=await t.resolve({type:"swap",tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:e.amountIn},e.chainId,e.recipient);if(!n)throw new Error("No liquidity for this pair.");return n}function mo(e){const{direction:t,selectedAsset:n,destinationToken:o,chainId:r,recipient:a,paymentAmount:l,resolveExactOutputSwap:d}=e,[u,c]=i.useState(!1),[f,p]=i.useState(null),[g,x]=i.useState(null),[m,y]=i.useState(null),[C,k]=i.useState(null),[b,A]=i.useState(null),[v,w]=i.useState(null),[R,E]=i.useState(null),[P,T]=i.useState(null),F=i.useRef(null),S=i.useRef(null),j=i.useRef(0),I=i.useRef(new Map),N=i.useMemo(()=>Yr,[]),D=i.useMemo(()=>Zr({customVenues:[...d?[{name:"consumer-exact-output",chainIds:[r],resolve:d}]:[],Gr(ho),Gr(Qr)]}),[d,r]),L=i.useMemo(()=>{if(!n?.asset)return null;const $=rn(n.asset,r);if($)return $;const le=mn(n.asset.address,r,n.asset.chainId);return le?le.address:null},[n?.asset,r]),Q=i.useMemo(()=>n?.asset?os(n.asset,r):[],[n?.asset,r]),W=i.useMemo(()=>Q.map($=>$.toLowerCase()).join(","),[Q]);i.useEffect(()=>{let $=!1;if(S.current&&(clearTimeout(S.current),S.current=null),!n?.asset||Q.length<=1){T(null);return}return S.current=setTimeout(async()=>{const le=t==="input"?n.amount:l||"0";let he=0n;try{he=t==="input"?M.parseUnits(le,n.asset.decimals):0n}catch{he=0n}try{const me=await $o(n.asset,r,{requiredAmount:he});$||T(me)}catch{$||T(null)}},400),()=>{$=!0,S.current&&(clearTimeout(S.current),S.current=null)}},[n?.asset,n?.amount,r,Q.length,W,t,l]);const O=i.useMemo(()=>P??L,[P,L]),H=i.useMemo(()=>!n?.asset||!O?[]:[O,...Q.filter($=>$.toLowerCase()!==O.toLowerCase())],[n?.asset,O,Q]),J=i.useMemo(()=>!n?.asset||!Qn(n.asset.address,n.asset.chainId,o.address,o.chainId)||!O?!1:h.addressesEqual(O,o.address),[n,o.address,o.chainId,O]),U=O?h.addressesEqual(O,o.address):!1,z=t==="output"&&parseFloat(l||"0")===0,ie=!!n?.asset&&!J&&!U&&!z,q=ie?R??O:O;return i.useEffect(()=>{F.current&&clearTimeout(F.current);const $=t==="input"?n?.amount:l,le=parseFloat($||"0");if(!ie||!Number.isFinite(le)||le<=0||!n?.asset||!a||H.length===0){j.current++,x(null),y(null),k(null),A(null),w(null),E(null),p(null),c(!1);return}const he=n.asset.decimals;let me;try{me=t==="input"?M.parseUnits(n.amount,he):M.parseUnits(l||"0",o.decimals)}catch{j.current++,p("Invalid amount"),c(!1);return}const ue=++j.current,ge=()=>ue!==j.current;c(!0);const Y=t==="output"?150:400;return F.current=setTimeout(async()=>{try{if(t==="input"){const oe=N.getVenueForChain(r);if(!oe)throw new Error("No swap venue for this chain");let K=null,ne=null;for(const Ce of H){const be=`${t}:${r}:${Ce.toLowerCase()}:${o.address.toLowerCase()}:${me.toString()}`,G=I.current.get(be);if(G&&G.expiresAt>Date.now()&&G.resolvedSwap){K=G.resolvedSwap,ne=Ce;break}const ee=await oe.resolve({type:"swap",tokenIn:Ce,tokenOut:o.address,amountIn:me},r,a);if(ge())return;if(ee){I.current.set(be,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:ee}),K=ee,ne=Ce;break}}if(!K||!ne)throw new Error("No liquidity for this pair");E(ne),w(K.amountOut),k(K),A(null);const ce=parseFloat(M.formatUnits(K.amountOut,o.decimals));x(ce<.01?ce.toPrecision(4):ce.toLocaleString(void 0,{maximumFractionDigits:6})),y(null),p(null)}else{let oe=null,K=null;for(const ne of H){const ce=`${t}:${r}:${ne.toLowerCase()}:${o.address.toLowerCase()}:${me.toString()}`,Ce=I.current.get(ce);if(Ce&&Ce.expiresAt>Date.now()&&Ce.exactOutputSwap){oe=Ce.exactOutputSwap,K=ne;break}try{const be=await D.getQuote({tokenIn:ne,tokenOut:o.address,amountOut:me},r,a);if(ge())return;I.current.set(ce,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:be}),oe=be,K=ne;break}catch{if(ge())return}}if(!oe||!K)throw new Error("No liquidity for this pair");E(K),A(oe),k(null),w(null),y(parseFloat(M.formatUnits(oe.amountIn,he)).toFixed(6)),x(null),p(null)}}catch(oe){if(ge())return;const K=oe instanceof Error?oe.message:"Failed to get quote";p(K),x(null),y(null),k(null),A(null),w(null),E(null)}finally{ge()||c(!1)}},Y),()=>{F.current&&clearTimeout(F.current)}},[t,ie,n?.amount,n?.asset?.address,n?.asset?.decimals,l,H,r,o.address,o.decimals,a,N,D]),{isQuoting:u,quoteError:f,estimatedOutput:g,estimatedInput:m,resolvedSwap:C,exactOutputSwap:b,quoteAmountOut:v,resolvedTokenIn:q,isDirect:U,needsSwap:ie,selectedIsEquivalent:J}}const Xr={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},Jr=["signing-delegation","signing-intent","submitting","executing"],Xl=()=>{},$r=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,destinationToken:o,sourceChains:r,supportedSourceAssets:a,buildActionCalls:l,feeExecutionMode:d="user-transfer",buildSpicenetBatch:u,onPayExecute:c,resolveExactOutputSwap:f,actionLabel:p,amountDirection:g="input",swapDescription:x,directDescription:m,paymentAmount:y,amountInputMode:C="fixed",minPaymentAmount:k,maxPaymentAmount:b,onAmountChange:A,styles:v,dark:w,title:R,subtitle:E,onAddFunds:P,onSuccess:T,onError:F})=>{const S=g==="output",{theme:j,dark:I,primaryColor:N,dk:D,palette:L,fontFamily:Q,monoFont:W,inputDark:O,cardBg:H,cardBorder:J,textPrimary:U,textSecondary:z,subtitleText:ie}=h.useSpiceBrand(v,w),q=i.useMemo(()=>O?{...j,colors:{...j.colors,secondary:D.cardBg,surfaceHover:D.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:j,[O,j,D.cardBg,D.hoverBg]),$=o.chainId,le=i.useContext(h.SpiceFlowProviderContext),he=(le?.mode||"7702")!=="7702",me=!!le?.isWhitelistGateActive,ue=!!le?.isWhitelistConfigured&&le?.isUserWhitelisted!==!0,ge=i.useMemo(()=>r??le?.supportedChainIds??[],[r,le?.supportedChainIds]),Y=i.useMemo(()=>{if(me)return[];if(a)return a;const Ie=le?.allowedTokens;if(!Ie||Ie.length===0)return;const at=new Set(Ie.map(yn=>yn.toLowerCase())),cn=[],xn=new Set;for(const yn of ge){const ws=h.getChainConfig(yn);for(const ks of ws?.supportedTokens??[]){if(!at.has(ks.symbol.toLowerCase()))continue;const Co=ks.address.toLowerCase();xn.has(Co)||(xn.add(Co),cn.push(ks.address))}}return cn},[a,le?.allowedTokens,ge,me]),oe=h.useWallet(),{address:K,isConnected:ne,isReady:ce,isAuthenticated:Ce,provider:be}=oe,{executeGasless:G,estimateGasless:ee}=Pn(),{externalWallet:_,externalAddress:Ae,embeddedAddress:Be,activeWallet:kt,activeAddress:_e}=h.useProviderWallets(),vt=h.useEmbeddedWalletAddress()||Be,{displayAssets:Ve,filteredSpiceAssets:xe,embeddedWalletAddress:Ee,refreshSpiceAssets:ze,refreshWalletAssets:lt}=po({destinationToken:o,supportedSourceAssets:Y,sourceChains:ge,enabled:e&&(he?!!Ae:!!vt)}),et=me||S||he?Ve:xe,[re,we]=i.useState(null),[Ge,je]=i.useState(y||""),[Me,Et]=i.useState(!1),[Rt,ct]=i.useState(null),[Se,St]=i.useState("idle"),[bt,mt]=i.useState(""),[De,zt]=i.useState(null),[We,gt]=i.useState(!1),[Je,wt]=i.useState(null),[fe,Ke]=i.useState(null),[tt,xt]=i.useState(!1),[Re,nt]=i.useState(!1),[Pt,Ye]=i.useState(null),st=i.useRef(re),jt=i.useRef(!1),Ft=i.useRef(null),Ot=i.useRef(null),Bt=i.useRef(0),Wt=i.useRef(null),dt=i.useRef(null);i.useEffect(()=>{st.current=re},[re]);const Te=C==="adjustable"?Ge:y||"0",Mt=Ee||Be||K,{isQuoting:Ne,quoteError:_t,estimatedOutput:Lt,resolvedSwap:It,exactOutputSwap:Qe,quoteAmountOut:de,resolvedTokenIn:Le,isDirect:ot,needsSwap:Xe,selectedIsEquivalent:Ht}=mo({direction:g,selectedAsset:re,destinationToken:o,chainId:$,recipient:Mt,paymentAmount:Te,resolveExactOutputSwap:f}),ke=S?parseFloat(Te||"0"):parseFloat(re?.amount||"")||0,Yt=ke>0&&ke<fn,sn=re?.asset?._source==="wallet",te=!!re?.asset&&sn&&re.asset.chainId!==$,se=i.useMemo(()=>re?.asset?xe.find(Ie=>h.addressesEqual(Ie.address,re.asset.address))?.balanceFormatted??0:0,[re,xe]),ve=sn?re?.asset.balanceFormatted??0:se,qe=i.useMemo(()=>{if(!re?.asset)return!1;if(S)return fe?nn(fe.grossAmount,fe.decimals,re.asset.decimals)>re.asset.balance:Ht||ot?ke>re.asset.balanceFormatted:Qe?parseFloat(M.formatUnits(Qe.amountInMax,re.asset.decimals))>re.asset.balanceFormatted:!1;if(fe){const Ie=nn(fe.grossAmount,fe.decimals,re.asset.decimals);return sn?Ie>re.asset.balance:parseFloat(M.formatUnits(Ie,re.asset.decimals))>ve}return ke>ve},[re,S,fe,Ht,ke,Qe,ve,sn,ot]);i.useEffect(()=>{e||(we(null),ct(null),Et(!1),St("idle"),mt(""),zt(null),gt(!1),wt(null),Ke(null),xt(!1),nt(!1),Ye(null),jt.current=!1,C==="adjustable"&&je(y||""),Ft.current&&(Ft.current.abort(),Ft.current=null))},[e]);const yt=i.useCallback(Ie=>{we(at=>({asset:Ie,amount:at?.asset?.address===Ie.address&&at?.asset?.chainId===Ie.chainId&&at.amount||""})),ct(null),Ye(null),nt(!1)},[]),pt=i.useCallback(Ie=>{we(at=>at&&{...at,amount:Ie}),ct(null),Ye(null),nt(!1)},[]),ft=i.useCallback(Ie=>{let at=Ie;b&&parseFloat(at)>parseFloat(b)&&(at=b),je(at),A?.(at),ct(null),Ye(null),nt(!1)},[b,A]);i.useCallback(Ie=>{if(jt.current||!K)return;const at=st.current;!at?.asset||!at.amount||at.asset?._source==="wallet"||M.parseUnits(S?Te:at.amount,at.asset.decimals)===0n||(jt.current=!0,ze())},[K,$,ze,S,Te]);const ut=i.useCallback(Ie=>{St({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[Ie.step]||"executing"),mt(Ie.message),Ie.txHash&&zt(Ie.txHash)},[]),Pe=i.useMemo(()=>({currentPaymentAmount:Te,destinationToken:o,embeddedWalletAddress:Ee,providerEmbeddedAddress:Be,externalWalletAddress:Ae,address:K,isNon7702:he,isPayMode:S,resolvedChainId:$,buildActionCalls:l,feeExecutionMode:d,buildSpicenetBatch:u,selectedAsset:re,needsSwap:Xe,resolvedSwap:It,exactOutputSwap:Qe,quoteAmountOut:de,resolvedTokenIn:Le}),[Te,o,Ee,Be,Ae,K,he,S,$,l,d,u,re,Xe,It,Qe,de,Le]),Tt=i.useCallback(Ie=>so({...Pe,requestTimestampMs:Ot.current??Date.now()},Ie),[Pe]),He=i.useCallback(Ie=>oo({...Pe,requestTimestampMs:Ot.current??Date.now()},Ie),[Pe]),X=i.useCallback((Ie,at,cn,xn)=>ro(Ie,at,cn,ee,xn),[ee]),ye=i.useMemo(()=>re?.asset?Xe&&Le?Le:re.asset.chainId===$?re.asset.address:Le??rn(re.asset,$)??o.address:o.address,[re,o.address,Xe,$,Le]),Ct=i.useCallback(()=>(Ot.current=Date.now(),co(dt.current)),[]),$e=i.useMemo(()=>re?.asset?h.addressesEqual(re.asset.address,o.address)&&re.asset.chainId===o.chainId:!1,[re,o.address,o.chainId]),it=$e&&(he||S),ht=it&&ke>0&&!!re?.asset,Ut=i.useMemo(()=>{if(!ht)return null;let Ie;try{Ie=M.parseUnits(Te||"0",o.decimals)}catch{return null}return{symbol:o.symbol,decimals:o.decimals,grossAmount:Ie,netAmount:Ie,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}},[ht,Te,o.symbol,o.decimals]),on=Rt,V=i.useMemo(()=>!(!re?.asset||ke<=0),[re,ke,ht]),Z=i.useMemo(()=>!e||Me||Se!=="idle"||!V||ht||!re?.asset?null:[S?"pay":"supply",g,re.asset.address.toLowerCase(),re.asset.chainId,re.amount,Te,o.address.toLowerCase(),o.chainId,$,Le?.toLowerCase()??"",Xe?"swap":"direct",ot?"direct-token":"routed-token",he?"non7702":"7702",$e?"source-dest":"cross-chain",Ne?"quoting":"quoted",Qe?.amountIn?.toString()??"",Qe?.amountInMax?.toString()??"",Qe?.venue??"",It?.amountOut?.toString()??"",de?.toString()??"",Ee??"",Be??"",K??""].join("|"),[e,Me,Se,V,ht,re,S,g,Te,o,$,Le,Xe,ot,he,$e,Ne,Qe,It,de,Ee,Be,K]),pe=i.useCallback(()=>ao({selectedAsset:re,isPayMode:S,parsedAmount:ke,needsSwap:Xe,exactOutputSwap:Qe,isNon7702:he,isSourceDestToken:$e,currentPaymentAmount:Te,destinationToken:o,feeExecutionMode:d,resolvedTokenIn:Le,embeddedWalletAddress:Ee,providerEmbeddedAddress:Be,resolvedChainId:$,isConnected:ne,address:K,ready:ce,authenticated:Ce,isDirect:ot,resolvedSwap:It,isQuoting:Ne,executionTokenAddress:ye,buildPayChainBatches:Tt,buildSupplyChainBatches:He,estimateGasless:ee,estimateRequiredGrossFunding:X}),[re,S,ke,Xe,Qe,he,$e,Te,o,d,Le,Ee,Be,X,Tt,ee,$,ne,K,ce,Ce,ot,It,Ne,He,ye]);i.useEffect(()=>{Wt.current=pe},[pe]);const ae=i.useCallback(Ie=>jr({asset:Ie,isPayMode:S,isNon7702:he,needsSwap:Xe,isQuoting:Ne,embeddedWalletAddress:Ee,buildSupplyChainBatches:He,estimateGasless:ee,executionTokenAddress:ye,feeExecutionMode:d}),[S,he,Xe,Ne,Ee,He,ee,ye,d]);i.useEffect(()=>{if(!e){xt(!1),nt(!1),Ye(null),Ke(null);return}if(Me||Se!=="idle"){Bt.current+=1,xt(!1);return}if(!V){Ke(null),xt(!1),nt(!1),Ye(null);return}if(ht){Ke(Ut),xt(!1),nt(!0),Ye(null);return}if(Ne){Bt.current+=1,xt(!1),nt(!1);return}if(!Z)return;let Ie=!1;const at=async()=>{const xn=++Bt.current;Ye(null),xt(!0);try{const yn=await Wt.current?.();if(Ie||Bt.current!==xn)return;yn?(Ke(yn),nt(!0)):(Ke(null),nt(!1)),Ye(null)}catch(yn){if(Ie||Bt.current!==xn)return;const ws=h.sanitizeError(yn,"Unable to calculate fees for this action.");Ke(null),nt(!1),Ye(ws)}finally{!Ie&&Bt.current===xn&&xt(!1)}},cn=window.setTimeout(()=>{at()},250);return()=>{Ie=!0,clearTimeout(cn),xt(!1)}},[e,Me,Se,V,ht,Ut,Ne,Z]);const Oe=i.useCallback(()=>(Ot.current=Date.now(),uo(dt.current)),[]);i.useEffect(()=>{!S&&Se==="success"&&De&&(ze(),T?.(De))},[S,Se,De,ze,T]),i.useEffect(()=>{if(!S||Je?.status!=="success"||jt.current||!K)return;jt.current=!0;const Ie=st.current;!Ie?.asset||Ie.asset?._source==="wallet"||ze()},[S,Je?.status,K,ze]);const Ue=i.useRef(T),Ze=i.useRef(F);i.useEffect(()=>{Ue.current=T},[T]),i.useEffect(()=>{Ze.current=F},[F]),i.useEffect(()=>{e&&(ze(),lt())},[e,ze,lt]),i.useEffect(()=>{S&&(Je?.status==="success"&&Ue.current?.(Je.txHash||""),Je?.status==="failed"&&Ze.current?.(new Error("Payment execution failed")))},[S,Je?.status]);const rt=i.useCallback(()=>{gt(!1),wt(null),we(null),jt.current=!1,ze(),lt()},[ze,lt]);dt.current={selectedAsset:re,parsedAmount:ke,currentPaymentAmount:Te,isInsufficientBalance:qe,isPayMode:S,isNon7702:he,isSourceDestToken:$e,needsSwap:Xe,exactOutputSwap:Qe,selectedIsEquivalent:Ht,resolvedTokenIn:Le,embeddedWalletAddress:Ee,providerEmbeddedAddress:Be,externalWallet:_,externalWalletAddress:Ae,activeSignerWallet:kt,activeSignerAddress:_e,address:K,isConnected:ne,ready:ce,authenticated:Ce,provider:be,resolvedChainId:$,executionTokenAddress:ye,destinationToken:o,buildActionCalls:l,feeExecutionMode:d,buildSpicenetBatch:u,onPayExecute:c,onSuccess:T,onError:F,gasless:{estimateGasless:ee,executeGasless:G,buildPayChainBatches:Tt,buildSupplyChainBatches:He,estimateRequiredGrossFunding:X,onProgress:ut},ui:{setError:ct,setStep:St,setStatusMsg:mt,setTxHash:zt,setIsExecuting:Et,setShowStatusPanel:gt,setPaymentResult:wt},refs:{spiceDepositSubmittedRef:jt,abortControllerRef:Ft}};const Dt=y?.trim(),qt=S&&C==="fixed"&&Dt!==void 0&&Dt!==""&&ke===0,Gt=S?(qt||!!re?.asset)&&ke>=0&&!Yt&&!qe&&!Me&&(qt||ht||Re)&&!Pt&&(qt||!Xe||!!Qe)&&!ue:!!re?.asset&&ke>0&&!Yt&&!qe&&!Me&&(it||Re)&&!Pt&&(te||ot||!!It&&!Ne)&&!ue,Xt=ot?m||`Your ${o.symbol} will be used directly.`:x||"Your assets will be swapped and used in a single atomic transaction.",ln=($?h.getChainConfig($):void 0)?.viemChain?.blockExplorers?.default?.url??"",gn=Jr.indexOf(Se),Fe=Me?(Xr[Se]||"EXECUTING...").toUpperCase():Se==="success"?"DONE":Yt?`MINIMUM ${fn}`:qe?"INSUFFICIENT BALANCE":p.toUpperCase(),At=i.useMemo(()=>{if(Me)return"PAYING...";if(Yt)return`MINIMUM ${fn}`;if(qe&&re?.asset)return`INSUFFICIENT ${re.asset.symbol}`;if(p)return p.toUpperCase();const Ie=ke>0?` ${Te} ${o.symbol}`:"";return Xe?`SWAP & PAY${Ie}`:`PAY${Ie}`},[Me,Yt,qe,re,p,ke,Te,o.symbol,Xe]),Kt=Se==="success"?()=>{St("idle"),we(null),zt(null),ze()}:Ct,en=Se==="success"?!1:!Gt;if(!e)return null;const vn=S?R||`Pay ${o.symbol}`:p,Un=S?E:s.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[s.jsx("span",{style:{marginTop:"3px",flexShrink:0},children:s.jsx(Us,{color:ie})}),s.jsx("p",{style:{fontSize:"12px",color:ie,margin:0,lineHeight:"1.4",fontFamily:Q},children:Xt})]});if(S){const Ie=Je&&(Je.status==="success"||Je.status==="failed")?[{asset:{symbol:re?.asset?.symbol||o.symbol,address:re?.asset?.address||""},amount:Te,txHash:Je.txHash||"",success:Je.status==="success",error:Je.status==="failed"?Je.error:void 0}]:void 0;return s.jsx(un,{isOpen:e,onClose:t,title:vn,subtitle:Un,styles:v,dark:I,footerLinkText:"Spicenet accounts \u2192",closeOnBackdropClick:n,children:s.jsxs("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[P&&s.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:s.jsx(zs,{onClick:P,color:N,fontFamily:Q})}),!qt&&s.jsx("div",{style:{marginBottom:"12px"},children:s.jsx(qn,{assets:et,selectedAsset:re??void 0,onAssetSelect:yt,onAmountChange:Xl,label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:re?.asset?Xe?Ne?"...":Qe?`~${parseFloat(M.formatUnits(Qe.amountIn,re.asset.decimals)).toFixed(6)}`:void 0:Te??void 0:void 0,dark:I,theme:q,styles:v})}),s.jsx(Dr,{variant:"pay",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:N,fontFamily:Q,textPrimary:U,textSecondary:z,cardBg:H,cardBorder:J,dk:D,dark:I,isQuoting:Ne,quoteError:_t,estimatedOutput:Lt,paymentAmount:Te,needsSwap:Xe,exactOutputSwap:Qe,adjustable:C==="adjustable",maxAmount:b,onAmountChange:ft}),V&&s.jsx(es,{fontFamily:Q,textPrimary:U,textSecondary:z,cardBg:H,cardBorder:J,resolvedDark:I,darkCardBorder:D.cardBorder,primaryColor:N,feePreview:fe,isLoading:tt,errorText:Pt,directExecutionFeeNote:ht}),on&&s.jsx(Rn,{variant:"error",palette:L,fontFamily:Q,style:{marginBottom:"12px"},children:on}),s.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:Oe,disabled:!Gt,loading:Me,dark:I,styles:{...v,button:{...v?.button,backgroundColor:N}},children:At}),Je&&We&&s.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:I?D.shell:"white",borderRadius:I?"12px":"6px",padding:"16px 0"},children:s.jsx(Qs,{type:"payment",isOpen:Je.status!=="processing",isProcessing:Me||Je.status==="processing",closeOnComplete:!1,chainName:h.getChainName($),explorerUrl:h.getExplorerUrl($,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{gt(!1),wt(null),Oe()},onNewTx:rt,onClose:()=>{gt(!1),wt(null)},onComplete:rt,results:Ie,styles:v,dark:I})})]})})}return s.jsx(un,{isOpen:e,onClose:t,title:vn,subtitle:Un,dark:I,styles:v,theme:j,closeOnBackdropClick:n,children:s.jsxs("div",{style:{padding:"24px 24px 5px 24px",position:"relative"},children:[s.jsx("div",{style:{marginBottom:"16px"},children:s.jsx(qn,{assets:et,selectedAsset:re||void 0,onAssetSelect:yt,onAmountChange:pt,disabled:Me||Se==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:q,styles:v,dark:O,resolveMaxAmount:ae,maxAmount:ve>0?Mn(ve,re?.asset.decimals??o.decimals):void 0})}),re?.asset&&!ot&&s.jsx(Dr,{variant:"supply",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:N,fontFamily:Q,textPrimary:U,textSecondary:z,cardBg:H,cardBorder:J,dark:I,isQuoting:Ne,quoteError:_t,estimatedOutput:Lt}),V&&s.jsx(es,{fontFamily:Q,textPrimary:U,textSecondary:z,cardBg:H,cardBorder:J,resolvedDark:I,darkCardBorder:D.cardBorder,primaryColor:N,feePreview:fe,isLoading:tt,errorText:Pt,directExecutionFeeNote:ht}),Se!=="idle"&&s.jsxs("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:Se==="success"?H:Se==="error"?L.errorBg:H,border:`1px solid ${Se==="success"?J:Se==="error"?L.errorBorder:J}`},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[Se==="success"?s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:s.jsx("path",{d:"M5 13l4 4L19 7",stroke:L.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):Se==="error"?s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:s.jsx("path",{d:"M18 6L6 18M6 6l12 12",stroke:L.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):s.jsx(h.Spinner,{size:14,color:N}),s.jsx("span",{style:{fontSize:"13px",fontWeight:500,color:Se==="success"?U:Se==="error"?L.errorText:U,fontFamily:Q,flex:1},children:Se==="success"?"Deposit confirmed":Se==="error"?bt||"Transaction failed":Xr[Se]||bt}),Se==="success"&&De&&s.jsx("a",{href:`${ln}/tx/${De}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:N,fontFamily:Q,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),Se==="error"&&s.jsx("button",{onClick:()=>{St("idle"),ct(null),setTimeout(Ct,50)},style:{background:"none",border:"none",fontSize:"12px",color:N,fontFamily:Q,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),gn>=0&&Se!=="success"&&Se!=="error"&&s.jsx("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${z}22`,overflow:"hidden"},children:s.jsx("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:N,transformOrigin:"left center",transform:`scaleX(${(gn+1)/Jr.length})`,transition:"transform 400ms ease"}})})]}),Rt&&Se==="idle"&&s.jsx(Rn,{variant:"error",palette:L,fontFamily:Q,style:{marginBottom:"16px"},children:Rt}),s.jsx(h.Button,{variant:"outline",fullWidth:!0,disabled:en,onClick:Kt,theme:j,dark:I,styles:{...v,button:{...v?.button,backgroundColor:N}},style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:W},children:Fe})]})})},Jl=e=>s.jsx($r,{isOpen:e.isOpen,onClose:e.onClose,closeOnBackdropClick:e.closeOnBackdropClick,amountDirection:"output",destinationToken:{address:e.paymentTokenAddress,symbol:e.paymentTokenSymbol,decimals:e.paymentTokenDecimals,chainId:e.paymentChainId,logoURI:e.paymentTokenLogoURI},buildActionCalls:e.buildActionCalls,buildSpicenetBatch:e.buildSpicenetBatch,actionLabel:e.ctaLabel||"PAY",paymentAmount:e.paymentAmount,amountInputMode:e.amountInputMode,minPaymentAmount:e.minPaymentAmount,maxPaymentAmount:e.maxPaymentAmount,onAmountChange:e.onAmountChange,title:e.title,subtitle:e.subtitle,onAddFunds:e.onAddFunds,styles:e.styles,dark:e.dark,onSuccess:e.onPaymentSuccess,onError:e.onPaymentError}),$l=({label:e="Export Wallet",style:t,className:n,onExport:o,onError:r})=>{const[a,l]=i.useState(!1),[d,u]=i.useState(!1),{primaryColor:c}=h.useSpiceBrand(),f=i.useContext(h.SpiceFlowProviderContext),{isAuthenticated:p}=h.useWallet();let g=null;try{g=Ss.usePrivy()}catch{}let x=null,m=null;try{x=wo.useEmbeddedReveal(),m=wo.useDynamicContext()}catch{x=null,m=null}const y=h.getDynamicEmbeddedWallet(m),C=i.useCallback(async()=>{if(!p){r?.("User is not authenticated. Please log in first.");return}try{if(f?.provider==="dynamic"){if(!x||!y){r?.("Dynamic is not available. Ensure the app is wrapped in a DynamicContextProvider.");return}await x.initExportProcess(!1),o?.();return}if(!g){r?.("Privy is not available. Ensure the app is wrapped in a PrivyProvider.");return}await g.exportWallet(),o?.()}catch(A){const v=A instanceof Error?A.message:"Failed to export wallet";console.error("Export wallet error:",A),r?.(v)}},[y,x,p,r,o,g,f?.provider]),k=!p,b={padding:"10px 20px",borderRadius:"8px",fontFamily:'"IBM Plex Mono", monospace',fontSize:"14px",fontWeight:500,letterSpacing:"0.4px",textTransform:"uppercase",cursor:k?"not-allowed":"pointer",opacity:k?.5:1,border:"1px solid #0e0d0b",color:"#0e0d0b",backgroundColor:d?`${c}cc`:a?`${c}ee`:c,transition:"background-color 150ms ease, transform 150ms ease",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"8px",...t};return s.jsxs("button",{onClick:C,onMouseEnter:()=>l(!0),onMouseLeave:()=>{l(!1),u(!1)},onMouseDown:()=>u(!0),onMouseUp:()=>u(!1),disabled:k,className:n,style:b,children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),s.jsx("polyline",{points:"17 8 12 3 7 8"}),s.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]}),e]})};function _r(e){const t=i.useContext(h.SpiceFlowProviderContext),n=h.useEmbeddedWalletAddress(),o=e?.enabled===!1?void 0:n,r=t?.network?{network:t.network,pollIntervalMs:e?.pollIntervalMs,chainIds:e?.chainIds??t.supportedChainIds,discoverWalletBalances:e?.discoverWalletBalances}:void 0;return{...Ho(o,r),embeddedWalletAddress:n}}var _l="data:image/svg+xml,%3csvg width='11' height='11' viewBox='0 0 24 24' fill='none' stroke='black' stroke-opacity='0.5' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' xmlns='http://www.w3.org/2000/svg'%3e%3cpolyline points='17 1 21 5 17 9' /%3e%3cpath d='M3 11V9a4 4 0 0 1 4-4h14' /%3e%3cpolyline points='7 23 3 19 7 15' /%3e%3cpath d='M21 13v2a4 4 0 0 1-4 4H3' /%3e%3c/svg%3e";const ec=({appName:e,status:t,statusLabel:n,totalUsdValue:o,breakdownSubtitle:r,address:a,dk:l,dark:d=!1,showModeToggle:u,isEmbeddedMode:c=!0,onModeToggle:f})=>{const[p,g]=i.useState(!1),x=async()=>{a&&await Aa(a)&&(g(!0),setTimeout(()=>g(!1),2e3))},m=t==="active",y=n||(m?"Active":"Inactive"),C=m?"#10b981":"#9ca3af",k=s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Embedded:"})," Deposit assets into ",e," account and use them here."]}),s.jsxs("div",{children:[s.jsx("strong",{children:"External:"})," Use assets from your connected wallet here."]})]});return s.jsxs("div",{children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[s.jsxs("div",{style:{fontSize:"13px",fontWeight:600,color:l.textPrimary},children:[e," Account"]}),u?s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[s.jsxs("button",{onClick:f,style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:d?l.hoverBg:"#f3f4f6",border:d?`1px solid ${l.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"11px",fontWeight:600,fontFamily:'"IBM Plex Mono", monospace',color:l.textSecondary,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease",letterSpacing:"0.02em"},children:[s.jsx("span",{children:c?"Embedded":"External"}),s.jsx("img",{src:_l,alt:"","aria-hidden":"true",style:{width:"11px",height:"11px",display:"block",...d?{filter:"invert(0.65)"}:{}}})]}),s.jsx(Do,{content:k,label:"Account mode info",textColor:d?l.textPrimary:"#f9fafb",backgroundColor:d?l.cardBg:"#111827",borderColor:d?l.cardBorder:"rgba(255,255,255,0.08)",accentColor:d?l.textSecondary:"#6b7280",children:s.jsx("img",{src:Hs,alt:"","aria-hidden":"true",style:{width:"12px",height:"12px",display:"block",...d?{filter:"invert(0.65)"}:{}}})})]}):s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:d?l.hoverBg:m?"#ecfdf5":"#f3f4f6",border:d?`1px solid ${l.cardBorder}`:m?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[s.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:C}}),s.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:d?l.textSecondary:m?"#065f46":"#6b7280"},children:y})]})]}),s.jsx("div",{style:{fontSize:"28px",fontWeight:700,color:l.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:Bn(o)}),r&&s.jsx("div",{style:{fontSize:"12px",color:l.textSecondary,marginBottom:"8px"},children:r}),a&&s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[s.jsx("span",{style:{fontSize:"12px",fontFamily:'"IBM Plex Mono", monospace',color:d?l.textSecondary:"#9ca3af"},children:Ao(a)}),s.jsx("button",{onClick:x,style:{padding:"2px 6px",fontSize:"10px",fontWeight:500,backgroundColor:"transparent",color:d?l.textSecondary:"#9ca3af",border:"none",cursor:"pointer",borderRadius:"4px",transition:"background-color 150ms ease, color 150ms ease"},title:"Copy address",children:p?"Copied":"Copy"})]})]})},tc=i.memo(ec),nc=({pendingDeposits:e,onCompleteDeposit:t,dk:n,dark:o=!1})=>e.length===0?null:s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:"Pending Deposits"}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((r,a)=>{const l=h.getChainConfig(r.chainId)?.displayName||`Chain ${r.chainId}`;return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:o?n.warningBg:"#fffbeb",border:o?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"8px"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.jsx("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:o?n.hoverBg:"#fde68a",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:n.warningText},children:r.tokenSymbol.charAt(0)}),s.jsxs("div",{children:[s.jsxs("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:[r.amount," ",r.tokenSymbol]}),s.jsxs("div",{style:{fontSize:"11px",color:n.warningText},children:["on ",l]})]})]}),s.jsx("button",{onClick:()=>t?.(r),style:{padding:"4px 12px",fontSize:"11px",fontWeight:600,backgroundColor:o?n.hoverBg:"#fef3c7",color:o?n.textPrimary:"#92400e",border:o?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"9999px",cursor:"pointer",transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease"},children:"Complete"})]},`${r.tokenAddress}-${r.chainId}-${a}`)})})]}),sc=i.memo(nc),oc=e=>`${e.tokenAddress}-${e.chainId}`,rc=({spiceAssets:e,loading:t,dk:n,dark:o=!1,canDirectWithdraw:r=!1,onDirectWithdraw:a,directWithdrawState:l})=>{const d={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},u={backgroundColor:n.cardBg,border:o?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return t?s.jsxs("div",{children:[s.jsx("div",{style:d,children:"Idle Balances"}),[1,2].map(c=>s.jsx("div",{style:{...u,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},c))]}):e.length===0?s.jsxs("div",{children:[s.jsx("div",{style:d,children:"Idle Balances"}),s.jsx("div",{style:{...u,padding:"16px",textAlign:"center",fontSize:"13px",color:o?n.textSecondary:"#9ca3af"},children:"No assets yet. Deposit to get started."})]}):s.jsxs("div",{children:[s.jsx("div",{style:d,children:"Idle Balances"}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((c,f)=>{const p=h.getChainConfig(c.chainId),g=c.chainDisplayName||p?.displayName||`Chain ${c.chainId}`,x=c.tokenDisplaySymbol||c.tokenDisplayName||c.tokenSymbol,m=oc(c),y=r&&c.directWithdraw&&!!a,C=l?.key===m?l:null,k=C?.step==="pending";return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...u},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[c.logoURI?s.jsx("img",{src:c.logoURI,alt:c.tokenSymbol,style:{width:"24px",height:"24px",borderRadius:"50%"}}):s.jsx("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:o?n.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:n.textSecondary},children:x.charAt(0)}),s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:x}),s.jsx("div",{style:{fontSize:"11px",color:o?n.textSecondary:"#9ca3af"},children:g})]})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[s.jsxs("div",{style:{textAlign:"right"},children:[s.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:bn(c.balanceFormatted)}),s.jsx("div",{style:{fontSize:"11px",color:C?.step==="error"?n.errorText:o?n.textSecondary:"#9ca3af"},children:C?.step==="error"?C.message||"Withdraw failed":Bn(c.usdValue)})]}),y&&s.jsx("button",{onClick:()=>!k&&a(c),disabled:k,title:"Withdraw to external wallet",style:{padding:"6px 10px",borderRadius:"6px",border:o?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",backgroundColor:o?n.hoverBg:"#ffffff",color:n.textPrimary,fontSize:"11px",fontWeight:600,cursor:k?"default":"pointer",opacity:k?.6:1,whiteSpace:"nowrap"},children:k?"Withdrawing\u2026":"Withdraw"})]})]},`${c.tokenAddress}-${c.chainId}-${f}`)})})]})},ac=i.memo(rc),ic=({section:e,dk:t,dark:n=!1})=>{const o=r=>{switch(r){case"green":return"#10b981";case"red":return"#ef4444";default:return t.textPrimary}};return s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:t.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:e.title}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.items.map((r,a)=>s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:t.cardBg,border:n?`1px solid ${t.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[r.tokenLogoURI?s.jsx("img",{src:r.tokenLogoURI,alt:r.tokenSymbol,style:{width:"20px",height:"20px",borderRadius:"50%"}}):s.jsx("div",{style:{width:"20px",height:"20px",borderRadius:"50%",backgroundColor:n?t.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",fontWeight:600,color:t.textSecondary},children:r.tokenSymbol.charAt(0)}),s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:t.textPrimary},children:r.tokenSymbol}),s.jsx("div",{style:{fontSize:"11px",color:t.textSecondary},children:r.label})]})]}),s.jsx("div",{style:{fontSize:"13px",fontWeight:600,color:o(r.valueColor)},children:r.displayValue})]},a))})]})},lc=i.memo(ic),cc=({onDepositClick:e,onWithdrawClick:t,depositDisabled:n=!1,withdrawDisabled:o=!1,primaryColor:r="#EA4B4B",dark:a=!1})=>!e&&!t?null:s.jsxs("div",{style:{display:"flex",gap:"8px"},children:[e&&s.jsx(h.Button,{variant:"outline",onClick:e,disabled:n,dark:a,styles:{button:{backgroundColor:r}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&s.jsx(h.Button,{variant:"outline",onClick:t,disabled:o,dark:a,styles:{button:{backgroundColor:r}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),dc=i.memo(cc),uc=({appName:e,status:t,statusLabel:n,totalUsdValue:o,breakdownSubtitle:r,address:a,spiceAssets:l,spiceAssetsLoading:d,pendingDeposits:u,customSections:c,notice:f,onDepositClick:p,onWithdrawClick:g,depositDisabled:x,onCompleteDeposit:m,primaryColor:y,dk:C,dark:k=!1,showModeToggle:b,isEmbeddedMode:A,onModeToggle:v,showConnectExternalCta:w,onConnectExternalWallet:R,connectExternalError:E,showHowItWorks:P=!0,canDirectWithdraw:T,onDirectWithdraw:F,directWithdrawState:S})=>{const[j,I]=i.useState(!1);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[s.jsx(tc,{appName:e,status:t,statusLabel:n,totalUsdValue:o,breakdownSubtitle:r,address:a,dk:C,dark:k,showModeToggle:b,isEmbeddedMode:A,onModeToggle:v}),f&&s.jsx("div",{style:{padding:"10px 12px",borderRadius:"8px",backgroundColor:f.tone==="warning"?k?"rgba(245, 158, 11, 0.12)":"#fffbeb":f.tone==="success"?k?"rgba(16, 185, 129, 0.12)":"#ecfdf5":C.cardBg,border:f.tone==="warning"?k?"1px solid rgba(245, 158, 11, 0.35)":"1px solid #fde68a":f.tone==="success"?k?"1px solid rgba(16, 185, 129, 0.35)":"1px solid #a7f3d0":k?`1px solid ${C.cardBorder}`:"1px solid #e5e7eb",color:f.tone==="warning"?k?"#fbbf24":"#92400e":f.tone==="success"?k?"#34d399":"#047857":C.textSecondary,fontSize:"12px",lineHeight:1.45,fontWeight:500},children:f.message}),w&&s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[s.jsx("button",{onClick:R,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:y||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:'"Helvetica Neue", sans-serif',transition:"opacity 150ms ease"},children:"Connect External Wallet"}),E&&s.jsx("span",{style:{fontSize:"11px",color:k?C.errorText:"#b91c1c",lineHeight:1.4},children:E})]}),s.jsx("div",{style:{height:"1px",backgroundColor:k?"#2d2d2d":"#e5e7eb"}}),s.jsx(dc,{onDepositClick:p,onWithdrawClick:g,depositDisabled:x,primaryColor:y,dark:k}),P&&s.jsxs("div",{children:[s.jsxs("button",{onClick:()=>I(!j),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:C.cardBg,border:k?`1px solid ${C.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:C.textSecondary,fontSize:"12px",fontWeight:500},children:[s.jsx("span",{children:"How It Works"}),s.jsx("span",{style:{transform:j?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),j&&s.jsxs("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:k?C.cardBg:"#f0fdf4",border:k?`1px solid ${C.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:k?C.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),s.jsx(sc,{pendingDeposits:u,onCompleteDeposit:m,dk:C,dark:k}),s.jsx(ac,{spiceAssets:l,loading:d,dk:C,dark:k,canDirectWithdraw:T,onDirectWithdraw:F,directWithdrawState:S}),c.map((N,D)=>s.jsx(lc,{section:N,dk:C,dark:k},D))]})},pc=i.memo(uc);function fc(e,t,n){const o=t-n.gasBridge-n.spicenetFee;if(o<=0n)throw new Error("Balance is too small to cover the network fee.");const r=[{recipient:e,amount:o}];return n.gasBridge>0n&&r.push({recipient:B.SPICE_GAS_FEE_RECIPIENT,amount:n.gasBridge}),n.spicenetFee>0n&&r.push({recipient:B.SPICE_PLATFORM_FEE_RECIPIENT,amount:n.spicenetFee}),r}function hc(e,t,n){if(e===t)return!0;const o=e>t?e:t;return o===0n?!1:(e>t?e-t:t-e)*10000n<=o*n}const mc=new Set([B.SPICE_GAS_FEE_RECIPIENT,B.SPICE_PLATFORM_FEE_RECIPIENT].map(e=>e.toLowerCase()));function gc(e,t){return!e||e.length!==t.length?!1:e.every((n,o)=>{const r=t[o];return n.recipient.toLowerCase()!==r.recipient.toLowerCase()?!1:mc.has(n.recipient.toLowerCase())?hc(n.amount,r.amount,100n):!0})}function ea(e,t,n){return{chainId:e,domain:"evm",tokenTransfers:[],calls:n.filter(o=>o.amount>0n).map(o=>({to:t,value:0n,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[o.recipient,o.amount]})}))}}function xc(e,t){const n=e.intents.flatMap(r=>r.batches).filter(r=>$t(r).totalFee>0n),o=n.filter(r=>r.chainId===t);return(o.length>0?o:n)[0]??null}function yc(e,t,n,o){const r=xc(o,e),{gasFee:a,bridgeFee:l,spicenetFee:d}=r?$t(r):{gasFee:0n,bridgeFee:0n,spicenetFee:0n};return fc(t,n,{gasBridge:a+l,spicenetFee:d})}function Cc(){const{executeGasless:e}=Pn(),t=h.useEmbeddedWalletAddress(),{embeddedAddress:n}=h.useProviderWallets(),o=t||n;return{withdraw:i.useCallback(async({tokenAddress:r,chainId:a,balance:l,recipient:d,onProgress:u})=>{const c=r,f=d;if(l<=0n)throw new Error("Nothing to withdraw.");const p=[ea(a,c,[{recipient:f,amount:l}])];let g=null;return e(p,c,0n,u,void 0,{useCustomTransfers:!0,userOverride:o,adjustBatchesForEstimate:({feeEstimate:x})=>{const m=yc(a,f,l,x);return gc(g,m)?null:(g=m,[ea(a,c,m)])}})},[e,o])}}function bc(e){return!!e.embeddedAddress&&!!e.externalAddress}const go=380,jn=8,wc=[];function ta(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function kc(e,t){const n=new Map;Object.entries(t).forEach(([r,a])=>{if(!Number.isFinite(a)||a<=0)return;n.set(r,a),n.set(r.toUpperCase(),a);const l=ta(r);l&&n.set(l,a)});const o=[e.symbol,e.displaySymbol,e.receiptTokenName,e.name,e.displayName];for(const r of o){if(!r)continue;const a=n.get(r)??n.get(r.toUpperCase());if(a!==void 0)return a;const l=ta(r);if(!l)continue;const d=n.get(l);if(d!==void 0)return d}return 0}const vc=({appName:e="Spice",status:t="active",statusLabel:n,customSections:o=wc,extraAssets:r=[],tokenPrices:a={},breakdownLabels:l=[],notice:d,styles:u,dark:c=!1,onDepositSuccess:f,onDepositClick:p,onWithdrawClick:g,onCompleteDeposit:x,showModeToggle:m=!1,defaultMode:y})=>{const C=i.useContext(h.SpiceFlowProviderContext),k=C?.mode!=="7702",b=!!C?.isWhitelistGateActive,A=!!C?.isWhitelistConfigured&&C?.isUserWhitelisted!==!0,v=i.useRef(!1);i.useEffect(()=>{if(!v.current){if(h.hasStoredSpiceFlowMode()){v.current=!0;return}y&&C?.setMode&&(C.setMode(y==="non7702"?"ondemand":"7702"),v.current=!0)}},[C,y]);const[w,R]=i.useState(!1),[E,P]=i.useState(null),[T,F]=i.useState({top:0,bottom:0,left:0,placement:"below"}),S=i.useRef(null),j=i.useRef(null),{address:I,isConnected:N}=h.useWallet(),D=h.useEmbeddedWalletAddress(),{externalAddress:L,embeddedAddress:Q}=h.useProviderWallets(),{dark:W,primaryColor:O,dk:H}=h.useSpiceBrand(u,c),J=k&&!L,U=!k||J,z=U?D||Q:I,ie=i.useMemo(()=>C?.supportedChainIds??B.getChainIdsByNetwork("mainnet"),[C?.supportedChainIds]),{assets:q,loading:$}=Vn({address:z,supportedChains:ie,enabled:!!z&&U,refetchInterval:3e4}),le=i.useMemo(()=>{const we=U?q.map(je=>{const Me=je.balanceUsd||0,Et=Number.isFinite(je.balanceFormatted)?je.balanceFormatted:0,Rt=Me>0?Me:kc(je,a)*Et;return{tokenAddress:je.address,tokenSymbol:je.symbol,tokenDisplaySymbol:Ds(je),tokenDisplayName:Ma(je),tokenDecimals:je.decimals,chainId:je.chainId,chainDisplayName:Ns(je),balance:je.balance.toString(),balanceFormatted:je.balanceFormatted,usdValue:Rt,logoURI:je.logoURI}}):[],Ge=J?[]:r;return[...we,...Ge].filter(je=>je.balanceFormatted>0)},[U,J,q,a,r]),he=i.useMemo(()=>le.reduce((we,Ge)=>we+Ge.usdValue,0),[le]),{pendingDeposits:me}=_r({chainIds:ie,enabled:!!I,discoverWalletBalances:!0}),ue=i.useMemo(()=>o.reduce((we,Ge)=>we+Ge.totalValue,0),[o]),ge=he+ue,Y=i.useMemo(()=>{const we=[];he>0&&we.push(`${Bn(he)} idle`);for(const Ge of o){const je=l.find(Me=>Me.sectionTitle===Ge.title)?.label||Ge.title.toLowerCase();we.push(`${Bn(Ge.totalValue)} ${je}`)}return we.join(" \xB7 ")},[he,o,l]),oe=i.useCallback(we=>{x?x(we):P(we)},[x]),K=i.useCallback(()=>{P(null)},[]),ne=i.useCallback(()=>{P(null),f?.()},[f]),ce=i.useCallback(()=>{if(!S.current)return;const we=S.current.getBoundingClientRect(),Ge=window.innerHeight-we.bottom-jn,je=we.top-jn,Me=Ge>=400||Ge>=je?"below":"above",Et=Math.max(jn,Math.min(we.right-go,window.innerWidth-go-jn)),Rt=Me==="below"?we.bottom+jn:we.top-jn,ct=Me==="above"?window.innerHeight-Rt:0;F({top:Rt,bottom:ct,left:Et,placement:Me})},[]);i.useLayoutEffect(()=>{w&&ce()},[w,ce]),i.useEffect(()=>{if(!w)return;const we=Me=>{S.current&&!S.current.contains(Me.target)&&j.current&&!j.current.contains(Me.target)&&R(!1)},Ge=Me=>{Me.key==="Escape"&&R(!1)},je=()=>ce();return document.addEventListener("mousedown",we),document.addEventListener("keydown",Ge),window.addEventListener("scroll",je,{passive:!0}),window.addEventListener("resize",ce),()=>{document.removeEventListener("mousedown",we),document.removeEventListener("keydown",Ge),window.removeEventListener("scroll",je),window.removeEventListener("resize",ce)}},[w,ce]);const Ce=U?D||Q||I:L||I,be=i.useCallback(()=>{C?.setMode&&C.setMode(U?"ondemand":"7702")},[C,U]),[G,ee]=i.useState(null);let _=null;try{_=Ss.useConnectWallet({onSuccess:()=>ee(null),onError:we=>ee(h.sanitizeError(we,"Failed to connect wallet."))}).connectWallet}catch{_=null}const Ae=i.useCallback(()=>{_&&(R(!1),ee(null),_({walletChainType:"ethereum-only"}))},[_]),Be=!L&&!!_,kt=i.useCallback(()=>{R(!1),p?.()},[p]),_e=i.useCallback(()=>{R(!1),g?.()},[g]),vt=i.useCallback(we=>{R(!1),oe(we)},[oe]),{withdraw:Ve}=Cc(),[xe,Ee]=i.useState(null),ze=bc({embeddedAddress:D||Q,externalAddress:L}),lt=i.useCallback(async we=>{if(!L)return;const Ge=`${we.tokenAddress}-${we.chainId}`;Ee({key:Ge,step:"pending"});try{await Ve({tokenAddress:we.tokenAddress,chainId:we.chainId,balance:BigInt(we.balance),recipient:L}),Ee(null)}catch(je){Ee({key:Ge,step:"error",message:h.sanitizeError(je,"Withdraw failed")})}},[Ve,L]);if(typeof window>"u")return null;const et=s.jsxs("button",{ref:S,onClick:()=>R(!w),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:W?H.hoverBg:"#ffffff",border:W?`1px solid ${H.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:'"Helvetica Neue", sans-serif',color:W?H.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:W?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[s.jsxs("span",{children:[e," Account"]}),N&&s.jsxs("span",{style:{color:W?H.textSecondary:"#6b7280"},children:["\xB7 ",Bn(ge)]}),s.jsx("span",{style:{fontSize:"10px",color:W?H.textSecondary:"#9ca3af",transform:w?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),re=w?zn.createPortal(s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:Cn.popover},onClick:()=>R(!1)}),s.jsx("div",{ref:j,style:{position:"fixed",top:T.placement==="below"?`${T.top}px`:"auto",bottom:T.placement==="above"?`${T.bottom}px`:"auto",left:`${T.left}px`,width:`${go}px`,maxWidth:`calc(100vw - ${jn*2}px)`,maxHeight:"80vh",backgroundColor:W?H.shell:"#ffffff",border:W?`1px solid ${H.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:W?"0 10px 40px rgba(0, 0, 0, 0.5)":"0 10px 40px rgba(0, 0, 0, 0.12)",zIndex:Cn.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${Nt.out}`},children:s.jsx(pc,{appName:e,status:t,statusLabel:n,totalUsdValue:ge,breakdownSubtitle:Y,address:U?Ce:I,spiceAssets:le,spiceAssetsLoading:$,pendingDeposits:me,customSections:o,notice:d,onDepositClick:p?kt:void 0,onWithdrawClick:g?_e:void 0,depositDisabled:A,onCompleteDeposit:vt,primaryColor:O,dk:H,dark:W,showModeToggle:m,isEmbeddedMode:U,onModeToggle:be,showConnectExternalCta:Be,onConnectExternalWallet:Ae,connectExternalError:G,showHowItWorks:!b,canDirectWithdraw:ze,onDirectWithdraw:lt,directWithdrawState:xe})}),s.jsx("style",{children:`
|
|
103
|
+
`})]})},El="0xa9059cbb";function jl(e){const t=new Map;for(const n of e){if(n.amount<=0n)continue;const o=M.getAddress(n.token),r=M.getAddress(n.to),a=`${o.toLowerCase()}:${r.toLowerCase()}`,l=t.get(a);l?l.amount+=n.amount:t.set(a,{token:o,to:r,amount:n.amount})}return[...t.values()]}function Fl(e,t){return`0x${t}${e.slice(4)}`}function eo(e,t){return br(e,t)}function br(e,t,n){const o=Bl(t,e),r=Math.floor(Date.now()/1e3)+60*10,a=B.hashChainBatches(o);return{user:e,...n?{chainAuthorizations:n}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:"0x00",nbf:0,exp:r,chainBatches:a.map((l,d)=>({hash:l.hash,chainId:l.chainId,tokenTransfers:o[d].domain==="spicenet"?[]:o[d].tokenTransfers??[],calls:l.calls}))}]}}function Bl(e,t){return e.map(n=>{if(n.domain==="spicenet"||n.calls.length===0)return n;const o=new Set((n.tokenTransfers??[]).filter(a=>(a.from==="escrow"||a.from==="solver")&&M.getAddress(a.to).toLowerCase()===t.toLowerCase()).map(a=>M.getAddress(a.token).toLowerCase()));if(o.size===0)return n;let r=0;for(const a of n.calls){if(!a.data?.startsWith(El))break;try{const l=M.decodeFunctionData({abi:h.P,data:a.data});if(l.functionName!=="transfer")break;const[d]=l.args;if(d.toLowerCase()===t.toLowerCase()||!o.has(M.getAddress(a.to).toLowerCase()))break;r+=1}catch{break}}return r===0?n:{...n,calls:n.calls.slice(r)}})}function tn(e,t,n,o){if(e.some(f=>f.domain==="spicenet"))return e;const r=n?.intents.flatMap(f=>f.batches),a=f=>f.from==="escrow",l=e.map(f=>{const p=r?.find(v=>v.chainId===f.chainId);if(!p)return f;const g=$t(p),x=g.totalFee;if(x<=0n)return f;const m=(f.tokenTransfers??[]).find(v=>a(v)&&M.getAddress(v.to).toLowerCase()===t.toLowerCase()&&!B.isNativeToken(M.getAddress(v.token)));if(!m)return f;const y=M.getAddress(m.token);let C=!1;const k=(f.tokenTransfers??[]).map(v=>C||!a(v)||M.getAddress(v.to).toLowerCase()!==t.toLowerCase()||M.getAddress(v.token).toLowerCase()!==y.toLowerCase()?v:(C=!0,{...v,amount:o?.payoutAlreadyGross?BigInt(v.amount):BigInt(v.amount)+x}));if(!C)return f;const b=[];g.spicenetFee>0n&&b.push({to:y,value:0n,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[B.SPICE_PLATFORM_FEE_RECIPIENT,g.spicenetFee]})});const A=g.gasFee+g.bridgeFee;return A>0n&&b.push({to:y,value:0n,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[B.SPICE_GAS_FEE_RECIPIENT,A]})}),{...f,tokenTransfers:k,calls:[...b,...f.calls]}}),d=l.flatMap(f=>(f.tokenTransfers??[]).filter(a).map(p=>{const g=M.getAddress(p.token),x=M.getAddress(p.to),m=[{token:g,to:x,amount:BigInt(p.amount)}];return{chainId:f.chainId,transfers:jl(m)}}));if(d.length===0)return e;const u=o?.requestTimestampMs??Date.now(),c=BigInt(Math.floor(u/1e3))+3600n;return[{chainId:B.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:d.map((f,p)=>{const g=M.keccak256(M.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,f.transfers[0].token,f.transfers.reduce((m,y)=>m+y.amount,0n),BigInt(f.chainId),BigInt(u+p)])),x=Fl(g,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:M.encodeFunctionData({abi:B.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${f.chainId}`,idempotenceKey:x,nbf:0n,exp:c,metadata:"{}",transfers:f.transfers.map(m=>({token:m.token.toLowerCase(),to:m.to,amount:m.amount}))}]})}})},...l]}function us(e,t){return t?e.some(n=>(n.tokenTransfers??[]).some(o=>o.from==="escrow"&&BigInt(o.amount)>=t.grossAmount)):!1}function wr(e){return!e.isSemi7702&&e.isDirectDeposit&&!e.isSourceDestToken}function to(e){const t=e.selectedAsset?.asset,n=e.selectedAsset?.amount;if(!(!t||!n))return M.parseUnits(n,t.decimals)}function kr(e){return e.map(t=>({r:t.r,s:t.s,yParity:t.yParity,address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce)}))}function Tl(e,t){if(e.length!==t.length)return!1;const n=B.hashChainBatches(e),o=B.hashChainBatches(t);return n.every((r,a)=>r.hash===o[a]?.hash)}async function ps({user:e,batches:t,authorizations:n,adjustBatchesForEstimate:o}){let r=t;const a=kr(n);for(let l=0;l<10;l+=1){const d=await h.relayerService.estimateActionFees(br(e,r,a)),u=await o({feeEstimate:d,batches:r});if(!u||Tl(r,u))return r;r=u}throw new Error("Fee estimate did not converge. Please retry.")}function an(e,t){const n=e.selectedAsset?.asset;if(!n||!e.selectedAsset?.amount)throw new Error("Select an asset and enter an amount");const o=M.parseUnits(e.selectedAsset.amount,n.decimals),r=t?.grossAmount??o;return e.resolveLockBatches({amount:e.selectedAsset.amount,amountWei:o,grossAmount:M.formatUnits(r,n.decimals),grossAmountWei:r})}async function fs(e,t,n){const o=[...new Set(n.filter(a=>a.domain!=="spicenet").map(a=>a.chainId))],r=[];for(const a of o){const l=h.getClientForChain(a),d=h.getDelegateContractAddress(a),u=await B.getAccountNonce(t,l),c=await e.actions.signAuthorization({contractAddress:d,chainId:a,nonce:Number(u)});r.push(c)}return r}async function no(e,t,n){const o=e.isSemi7702&&e.providerEmbeddedAddress||e.address;if(!e.isConnected||!o)throw new Error("Please connect your wallet to continue");if(t.length===0)throw new Error("No lock batches configured");if(!e.ready||!e.authenticated)throw new Error(`Please authenticate with ${e.provider||"wallet provider"} to continue`);const r=n??await fs(e,o,t),a=B.hashChainBatches(t),l=Math.floor(Date.now()/1e3)+60*10,d=a.map(x=>x.hash),u=M.keccak256(M.encodeAbiParameters([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,BigInt(l),d])),c=await e.actions.signMessage({raw:u}),f=typeof c=="string"?c:c.signature;if(!f)throw new Error("Failed to sign intent authorization");const p={mode:"7702",signatureType:"ecdsa",signature:f,nbf:0,exp:l,chainBatches:a.map((x,m)=>{const y=t[m],C=y.domain==="spicenet";return{hash:x.hash,chainId:x.chainId,tokenTransfers:C?[]:y.tokenTransfers??[],calls:x.calls}})},g=await h.relayerService.createAction({user:o,chainAuthorizations:kr(r),intents:[p]});if(g){const x=h.createInitialSteps(t,h.getChainName),[m,y]=g.intentIds[0].split("/"),C=parseInt(y||"0",10),k=g.intentIds[0];e.startStatusPolling(g.intentIds[0],x),await tr({actionId:m,intentIndex:C,intentId:k,totalSteps:t.length,isSpicenetStep:b=>t[b]?.domain==="spicenet",maxExecuteAttemptsForStep:b=>t[b]?.domain==="spicenet"?6:3,maxPolls:72})}}async function Ml(e){let t=an(e);if(t.length===0)throw new Error("No lock batches configured");const n=e.isSemi7702&&e.providerEmbeddedAddress||e.address;if(!e.isConnected||!n)throw new Error("Please connect your wallet to continue");const o=await fs(e,n,t),r=Date.now();let a=tn([...t],n,void 0,{requestTimestampMs:r}),l;a=await ps({user:n,batches:a,authorizations:o,adjustBatchesForEstimate:({feeEstimate:d})=>{const u=An(d,{symbol:e.selectedAsset?.asset.symbol??"",decimals:e.selectedAsset?.asset.decimals??18,actionAmount:to(e)});return u?(l={grossAmount:u.grossAmount,netAmount:u.netAmount,feeAmount:u.totalFee??0n},t=an(e,l),tn([...t],n,d,{payoutAlreadyGross:us(t,l),requestTimestampMs:r})):null}}),await no(e,a,o)}async function Rl(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");const n=e.resolveLockBatches();if(n.length===0)throw new Error("No lock batches configured");const o=e.selectedAsset.asset,r=M.parseUnits(e.selectedAsset.amount,o.decimals),a=o.chainId,l=e.escrowAddress||B.getEscrowContractAddress(a),d=B.normalizeNativeTokenAddress(o.address),u=o.isNative||B.isNativeToken(d),c=Date.now();let f;const p=n.some(k=>k.tokenTransfers?.some(b=>b.from==="escrow")),g=k=>({chainId:a,calls:u?[{to:l,value:k,data:"0x"}]:[{to:d,value:0n,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[l,k]})}]}),x=(k,b,A,v)=>{const w=g(k);if(!p)return[w,...b];const R=tn([...b],t,A,{payoutAlreadyGross:us(b,v),requestTimestampMs:c});return[w,...R]};let m=an(e),y=x(r,m);const C=await fs(e,t,y);p&&(y=await ps({user:t,batches:y,authorizations:C,adjustBatchesForEstimate:({feeEstimate:k})=>{const b=An(k,{symbol:o.symbol,decimals:o.decimals,actionAmount:r});return b?(f={grossAmount:b.grossAmount,netAmount:b.netAmount,feeAmount:b.totalFee??0n},m=an(e,f),x(f.grossAmount,m,k,f)):null}})),await no(e,y,C)}async function Dl(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");if(e.onLockExecute){const T=e.resolveLockBatches();if(T.length===0)throw new Error("No lock batches configured");const F=e.selectedAsset.asset,S=M.parseUnits(e.selectedAsset.amount,F.decimals),j=await e.onLockExecute({asset:F,amount:e.selectedAsset.amount,amountWei:S,lockDurationMonths:e.selectedDuration?.months??0,chainBatches:T});j&&e.onLockSuccess?.(j);return}const n=e.resolveLockBatches();if(n.length===0)throw new Error("No lock batches configured");const o=e.selectedAsset.asset,r=M.parseUnits(e.selectedAsset.amount,o.decimals),a=o.chainId,l=e.escrowAddress||B.getEscrowContractAddress(a),d=B.normalizeNativeTokenAddress(o.address),u=o.isNative||B.isNativeToken(d),c=n.some(T=>T.tokenTransfers?.some(F=>F.from==="escrow")),f=Date.now();let p;const g=T=>({chainId:a,calls:u?[{to:l,value:T,data:"0x"}]:[{to:d,value:0n,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[l,T]})}]}),x=(T,F,S,j)=>{const I=g(T);if(!c)return[I,...F];const N=tn([...F],t,S,{payoutAlreadyGross:us(F,j),requestTimestampMs:f});return[I,...N]};let m=an(e),y=x(r,m);const C=await fs(e,t,y);c&&(y=await ps({user:t,batches:y,authorizations:C,adjustBatchesForEstimate:({feeEstimate:T})=>{const F=An(T,{symbol:o.symbol,decimals:o.decimals,actionAmount:r});return F?(p={grossAmount:F.grossAmount,netAmount:F.netAmount,feeAmount:F.totalFee??0n},m=an(e,p),x(p.grossAmount,m,T,p)):null}}));const k=p?.grossAmount??r,b=await e.externalWallet.getEthereumProvider();let A=null;try{const T=await b.request({method:"eth_chainId"});A=parseInt(T,16)}catch{A=null}A!==a&&await h.ensureWalletOnChain(b,a);const v=h.getChainConfig(a),w=M.createWalletClient({account:e.externalWalletAddress,chain:v?.viemChain,transport:M.custom(b)}),R=h.getClientForChain(a),E=async T=>{if(T<=0n)return;const F=u?await w.sendTransaction({to:t,value:T,chain:v?.viemChain}):await w.sendTransaction({to:d,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[t,T]}),chain:v?.viemChain});if((await R.waitForTransactionReceipt({hash:F,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to embedded wallet failed")};await E(k);let P=k;if(c)for(let T=0;T<4;T+=1){y=await ps({user:t,batches:y,authorizations:C,adjustBatchesForEstimate:({feeEstimate:S})=>{const j=An(S,{symbol:o.symbol,decimals:o.decimals,actionAmount:r});return j?(p={grossAmount:j.grossAmount,netAmount:j.netAmount,feeAmount:j.totalFee??0n},m=an(e,p),x(p.grossAmount,m,S,p)):null}});const F=p?.grossAmount??r;if(F<=P)break;await E(F-P),P=F}await no(e,y,C)}async function Nl(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount||!e.requiresRelayerFeeEstimate)return null;if(e.isSemi7702||wr(e)){const l=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address;if(!l)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");let d=an(e);if(d.length===0)throw new Error("No lock batches configured");const u=e.selectedAsset.asset,c=M.parseUnits(e.selectedAsset.amount,u.decimals),f=u.chainId,p=e.escrowAddress||B.getEscrowContractAddress(f),g=B.normalizeNativeTokenAddress(u.address),x=u.isNative||B.isNativeToken(g),m=d.some(v=>v.tokenTransfers?.some(w=>w.from==="escrow")),y=v=>({chainId:f,calls:x?[{to:p,value:v,data:"0x"}]:[{to:g,value:0n,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[p,v]})}]}),C=(v,w,R)=>{const E=y(v);if(!m)return[E,...w];const P=tn([...w],l,R,{payoutAlreadyGross:w.some(T=>(T.tokenTransfers??[]).some(F=>F.from==="escrow"&&BigInt(F.amount)>=v))});return[E,...P]};let k=C(c,d),b=null,A;for(let v=0;v<4;v+=1){const w=await h.relayerService.estimateActionFees(eo(l,k)),R=An(w,{symbol:u.symbol,decimals:u.decimals,actionAmount:c});if(!R)return b;const E={grossAmount:R.grossAmount,netAmount:R.netAmount,feeAmount:R.totalFee??0n},P=A?.grossAmount===E.grossAmount&&A?.netAmount===E.netAmount&&A?.feeAmount===E.feeAmount;if(b=R,A=E,d=an(e,E),k=C(E.grossAmount,d,w),P)break}return b}const t=e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");let n=an(e);if(n.length===0)throw new Error("No lock batches configured");let o=tn([...n],t),r=null;for(let l=0;l<4;l+=1){const d=await h.relayerService.estimateActionFees(eo(t,o)),u=An(d,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:to(e)});if(!u)return null;const c={grossAmount:u.grossAmount},f=r?.grossAmount===u.grossAmount&&r?.netAmount===u.netAmount&&r?.totalFee===u.totalFee;if(r=u,n=an(e,c),o=tn([...n],t,d,{payoutAlreadyGross:us(n,c)}),f)break}if(r)return r;const a=await h.relayerService.estimateActionFees(eo(t,o));return An(a,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals,actionAmount:to(e)})}async function Pl(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");const t=e.activeSignerWallet??e.externalWallet,n=e.activeSignerAddress??e.externalWalletAddress;if(!n||!t)throw new Error("Please connect your wallet to continue");const o=e.resolveLockBatches();if(o.length===0)throw new Error("No lock batches configured");const r=o.find(p=>p.chainId===e.lockChainId)||o[0];if(!r)throw new Error("No lock batch for lock chain");const a=await t.getEthereumProvider();let l=null;try{const p=await a.request({method:"eth_chainId"});l=parseInt(p,16)}catch{l=null}l!==e.lockChainId&&await h.ensureWalletOnChain(a,e.lockChainId);const d=h.getChainConfig(e.lockChainId),u=M.createWalletClient({account:n,chain:d?.viemChain,transport:M.custom(a)}),c=h.getClientForChain(e.lockChainId);let f;for(const p of r.calls){const g=await u.sendTransaction({to:p.to,data:p.data,value:p.value,chain:d?.viemChain});if((await c.waitForTransactionReceipt({hash:g,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Lock transaction failed");f=g}f&&e.onLockSuccess?.(f)}async function Wl(e){if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance. Add more assets.");return}e.ui.setIsExecuting(!0),e.ui.setError(null);const t=n=>{console.error("[SpiceLockModal] lock failed:",n);const o=h.sanitizeError(n,""),r=typeof n?.shortMessage=="string"?n.shortMessage:typeof n?.message=="string"?n.message:"";e.ui.setError(o||r||"Transaction failed. Please try again.")};if(e.isSemi7702){if(e.isSourceDestToken){try{await Pl(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{await Dl(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{wr(e)?await Rl(e):await Ml(e)}catch(n){t(n)}finally{e.ui.setIsExecuting(!1)}}const vr=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,lockBatches:o,lockTokenSymbol:r,lockTokenLogoURI:a,destinationInputHook:l,sourceAssetInputHook:d,lockDurationHook:u,lockChainId:c,durationOptions:f,votingPowerEstimate:p,escrowAddress:g,includeWalletAssets:x=!1,destinationTokenAddress:m,onLockSuccess:y,onLockExecute:C,sourceToDestinationConversionRate:k,estimatedOutputAmount:b,onAddFunds:A,buildSpicenetBatch:v,styles:w,dark:R=!1})=>{const{theme:E,dark:P,primaryColor:T,dk:F}=h.useSpiceBrand(w,R),S=E.typography.fontFamily,j=i.useContext(h.SpiceFlowProviderContext),I=j?.mode||"7702",N=!!j?.isWhitelistGateActive,D=I!=="7702",L=i.useMemo(()=>j?.supportedChainIds??[],[j?.supportedChainIds]),Q=i.useMemo(()=>{if(N)return[];const X=j?.allowedTokens;if(!X||X.length===0)return[];const ye=new Set(X.map(it=>it.toLowerCase())),Ct=[],$e=new Set;for(const it of L){const ht=h.getChainConfig(it);for(const Ut of ht?.supportedTokens??[]){if(!ye.has(Ut.symbol.toLowerCase()))continue;const on=`${it}:${Ut.address.toLowerCase()}`;$e.has(on)||($e.add(on),Ct.push(M.getAddress(Ut.address)))}}return Ct},[j?.allowedTokens,L,N]),W=P?F.cardBg:w?.assetSelector?.backgroundColor||w?.secondaryBackground||"#e9e9e9",O=P?`1px solid ${F.cardBorder}`:"0.5px solid #A8A8A7",H=P?"12px":"6px",J=P?F.textPrimary:"#111827",U=P?F.textSecondary:"#6b7280",z=i.useMemo(()=>({...w,assetSelector:{...w?.assetSelector,backgroundColor:P?F.cardBg:w?.assetSelector?.backgroundColor,borderRadius:P?"12px":w?.assetSelector?.borderRadius},secondaryBackground:P?F.cardBg:w?.secondaryBackground}),[w,P]),ie=i.useMemo(()=>P?{...E,colors:{...E.colors,secondary:F.cardBg,surfaceHover:F.hoverBg,border:F.cardBorder,borderHover:F.inputBorder}}:E,[P,E]),[q,$]=i.useState(null),[le,he]=i.useState(0),me=u?.selectedDurationIdx??le,ue=u?.setSelectedDurationIdx??he,[ge,Y]=i.useState(!1),[oe,K]=i.useState(null),[ne,ce]=i.useState(null),[Ce,be]=i.useState(!1),[G,ee]=i.useState(!1),[_,Ae]=i.useState(null),[Be,kt]=i.useState(!1),_e=i.useRef(0),[vt,Ve]=i.useState(!1),[xe,Ee]=i.useState(null);Qt.useWalletClient(),Qt.useSwitchChain();const{chain:ze,address:lt}=Qt.useAccount();Qt.useConfig();const et=i.useRef(ze);i.useEffect(()=>{et.current=ze},[ze]);const re=h.useWallet(),{isReady:we,isAuthenticated:Ge,isConnected:je,address:Me,provider:Et,actions:Rt}=re,{externalWallet:ct,embeddedAddress:Se,externalAddress:St,activeWallet:bt,activeAddress:mt}=h.useProviderWallets(),{intentStatus:De,startStatusPolling:zt,clearStatus:We}=Ro({checkStepStatus:(X,ye)=>h.relayerService.checkStepStatus(X,ye),retryStep:async(X,ye)=>{const[Ct,$e]=X.split("/"),it=parseInt($e||"0",10);await h.relayerService.executeStep(Ct,it,ye,{action:"execute"})},maxRetries:3}),{assets:gt,refetch:Je}=Vn({address:Me,supportedChains:L,enabled:e&&je&&!D&&!N,refetchInterval:3e4}),wt=i.useMemo(()=>{if(N)return[];if(Q.length===0)return gt;const X=new Set(Q.map(ye=>ye.toLowerCase()));return gt.filter(ye=>X.has(ye.address.toLowerCase()))},[gt,Q,N]),fe=h.useEmbeddedWalletAddress(),Ke=St||lt,tt=D?mt??Ke:fe,xt=i.useMemo(()=>{if(!x)return[];if(N)return m?[M.getAddress(m)]:[];const X=new Set,ye=[],Ct=$e=>{if(!$e)return;const it=$e.toLowerCase();X.has(it)||(X.add(it),ye.push(M.getAddress($e)))};m&&Ct(m);for(const $e of Q)Ct($e);return ye},[x,D,m,Q,N]),Re=i.useMemo(()=>xt.map(X=>X.toLowerCase()).sort().join(","),[xt]),nt=i.useMemo(()=>JSON.stringify([...L||[]].sort()),[L]),[Pt,Ye]=i.useState([]),st=i.useRef(0),jt=i.useRef(async()=>{}),Ft=i.useCallback(async()=>{if(!x||!tt||xt.length===0){st.current++,Ye([]);return}const X=++st.current,ye=M.getAddress(tt),Ct=D?L&&L.length>0?L:[c]:[c],$e=xt.map(V=>{const Z=V.toLowerCase();if(m&&h.addressesEqual(V,m)){const pe=h.getChainConfig(c)?.supportedTokens?.find(ae=>h.addressesEqual(ae.address,Z));return{address:V,chainId:c,configToken:pe?{decimals:pe.decimals,symbol:pe.symbol,name:pe.name,logo:pe.logo}:void 0}}for(const pe of Ct){const ae=h.getChainConfig(pe)?.supportedTokens?.find(Oe=>h.addressesEqual(Oe.address,Z));if(ae)return{address:V,chainId:pe,configToken:{decimals:ae.decimals,symbol:ae.symbol,name:ae.name,logo:ae.logo}}}return{address:V,chainId:c}}),it=new Map;for(const V of $e){const Z=it.get(V.chainId)||[];Z.push(V),it.set(V.chainId,Z)}const ht=async(V,Z)=>{try{const pe=await Zt.readContract(V,{address:Z.address,abi:h.P,functionName:"balanceOf",args:[ye]});let ae,Oe,Ue,Ze;if(Z.configToken)ae=Z.configToken.decimals,Oe=Z.configToken.symbol,Ue=Z.configToken.name,Ze=Z.configToken.logo;else{const[qt,Gt,Xt]=await Promise.all([Zt.readContract(V,{address:Z.address,abi:h.P,functionName:"decimals",args:[]}).catch(()=>18),Zt.readContract(V,{address:Z.address,abi:h.P,functionName:"symbol",args:[]}).catch(()=>"TOKEN"),Zt.readContract(V,{address:Z.address,abi:h.P,functionName:"name",args:[]}).catch(()=>"TOKEN")]);ae=Number(qt),Oe=Gt,Ue=Xt}const rt=!!m&&h.addressesEqual(Z.address,m)&&Z.chainId===c;rt&&a&&(Ze=a),rt&&r&&!Z.configToken&&(Oe==="TOKEN"&&(Oe=r),Ue==="TOKEN"&&(Ue=r));const Dt=parseFloat((Number(pe)/Math.pow(10,ae)).toFixed(6));return{address:Z.address,name:Ue,symbol:Oe,decimals:ae,balance:pe,balanceFormatted:Dt,balanceUsd:0,logoURI:Ze,isNative:!1,chainId:Z.chainId}}catch{return null}},Ut=await Promise.all(Array.from(it.entries()).map(async([V,Z])=>{let pe;try{pe=h.getClientForChain(V)}catch{return[]}const ae=[],Oe=[];for(const Ze of Z){const rt=ae.length;ae.push({address:Ze.address,abi:h.P,functionName:"balanceOf",args:[ye]}),Ze.configToken||ae.push({address:Ze.address,abi:h.P,functionName:"decimals",args:[]},{address:Ze.address,abi:h.P,functionName:"symbol",args:[]},{address:Ze.address,abi:h.P,functionName:"name",args:[]}),Oe.push({start:rt,item:Ze})}let Ue=null;try{Ue=await pe.multicall({contracts:ae})}catch{Ue=null}return Ue?Oe.map(({start:Ze,item:rt})=>{const Dt=Ue[Ze],qt=Dt?.status==="success"?Dt.result:0n;let Gt,Xt,ln,gn;if(rt.configToken)Gt=rt.configToken.decimals,Xt=rt.configToken.symbol,ln=rt.configToken.name,gn=rt.configToken.logo;else{const Kt=Ue[Ze+1],en=Ue[Ze+2],vn=Ue[Ze+3];Gt=Kt?.status==="success"?Number(Kt.result):18,Xt=en?.status==="success"?en.result:"TOKEN",ln=vn?.status==="success"?vn.result:Xt}const Fe=!!m&&h.addressesEqual(rt.address,m)&&rt.chainId===c;Fe&&a&&(gn=a),Fe&&r&&!rt.configToken&&(Xt==="TOKEN"&&(Xt=r),ln==="TOKEN"&&(ln=r));const At=parseFloat((Number(qt)/Math.pow(10,Gt)).toFixed(6));return{address:rt.address,name:ln,symbol:Xt,decimals:Gt,balance:qt,balanceFormatted:At,balanceUsd:0,logoURI:gn,isNative:!1,chainId:rt.chainId}}):(await Promise.all(Z.map(Ze=>ht(pe,Ze)))).filter(Ze=>Ze!==null)}));if(X!==st.current)return;const on=Ut.flat();Ye(on)},[x,D,tt,Re,nt,c,m,a,r]);i.useEffect(()=>{jt.current=Ft},[Ft]),i.useEffect(()=>{if(!e||!x){Ye([]);return}jt.current();const X=setInterval(()=>{jt.current()},15e3);return()=>clearInterval(X)},[x,e,tt,Re,nt,c,m]);const Ot=i.useCallback(()=>{Ft()},[Ft]),Bt=i.useMemo(()=>Pt.filter(X=>X.balance>0n),[Pt]),Wt=i.useMemo(()=>{if(D)return Bt.map(ye=>({...ye,_source:"wallet"}));if(!x)return wt;const X=[];for(const ye of Bt)X.push({...ye,_source:"wallet"});for(const ye of wt)X.push({...ye,_source:"spice"});return X},[D,x,Bt,wt]),dt=i.useMemo(()=>N?m?Wt.filter(X=>h.addressesEqual(X.address,m)&&X.chainId===c):[]:Wt,[Wt,N,m,c]),Te=i.useRef(null),Mt=i.useRef(null);i.useEffect(()=>{Mt.current=q},[q]),i.useEffect(()=>{!N||!q?.asset||m&&h.addressesEqual(q.asset.address,m)&&q.asset.chainId===c||$(null)},[N,q?.asset,m,c]),i.useEffect(()=>{e||($(null),K(null),ce(null),be(!1),ee(!1),Ae(null),Y(!1),Ve(!1),Ee(null),kt(!1),We())},[e,We]),i.useEffect(()=>{l&&l.assetAmount!==(q?.amount||"")&&$(X=>X&&{...X,amount:l.assetAmount})},[l?.assetAmount]),i.useEffect(()=>{d&&d.assetAmount!==(q?.amount||"")&&$(X=>X&&{...X,amount:d.assetAmount})},[d?.assetAmount]),i.useEffect(()=>{if(!D&&De?.overallStatus==="success"&&De.intentId&&Te.current!==De.intentId&&Me&&De.steps.find(X=>X.transactionHash)?.transactionHash){Te.current=De.intentId;const X=Mt.current;if(!X?.asset||!X.amount||X.asset._source==="wallet"||M.parseUnits(X.amount,X.asset.decimals)===0n)return;Je()}},[De,Me,c,Je,D]);const Ne=parseFloat(q?.amount||"")||0,_t=Ne>0&&Ne<fn,Lt=i.useMemo(()=>q?.asset?q.asset._source==="wallet"?q.asset.balanceFormatted??0:wt.find(X=>h.addressesEqual(X.address,q.asset.address)&&X.chainId===q.asset.chainId)?.balanceFormatted??0:0,[q?.asset,wt]),It=Ne>0&&(_?parseFloat(M.formatUnits(_.grossAmount,_.decimals))>Lt:Ne>Lt),Qe=u?.selectedDuration??f[me]??f[0],de=i.useMemo(()=>!q?.asset||!m?!1:h.addressesEqual(q.asset.address,m)&&q.asset.chainId===c,[q?.asset,m,c]),Le=i.useMemo(()=>Ne<=0?0:de?Ne:!k||k<=0?0:Ne/k,[Ne,k,de]),ot=i.useMemo(()=>Le<=0?null:Le.toLocaleString(void 0,{maximumFractionDigits:2}),[Le]),Xe=p&&Le>0&&Qe?p(Le,Qe.months):void 0,Ht=i.useMemo(()=>Ne<=0?"$0.00":de&&k?(Ne*k).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!k||k<=0?"$0.00":Ne.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[Ne,k,de]),ke=i.useMemo(()=>{if(!ot)return null;const X=parseFloat(ot.replace(/,/g,""));return de&&k?(X*k).toLocaleString(void 0,{maximumFractionDigits:2}):k?(X*k).toLocaleString(void 0,{maximumFractionDigits:2}):null},[ot,k,de]),Yt=i.useCallback(X=>{$(ye=>({asset:X,amount:ye?.asset?.address===X.address&&ye?.asset?.chainId===X.chainId&&ye.amount||""})),K(null),ce(null),ee(!1),Ae(null),d?.setSelectedAsset&&d.setSelectedAsset({symbol:X.symbol,address:X.address,decimals:X.decimals,chainId:X.chainId})},[d?.setSelectedAsset]),sn=i.useCallback(X=>{$(ye=>ye&&{...ye,amount:X}),K(null),ce(null),ee(!1),Ae(null),l&&l.setAssetAmount(X),d&&d.setAssetAmount(X)},[l,d]),te=i.useCallback(X=>{if(typeof o=="function"){if(!q?.asset||!q.amount)throw new Error("Select an asset and enter an amount");return o({asset:q.asset,amount:X?.amount??q.amount,amountWei:X?.amountWei??M.parseUnits(q.amount,q.asset.decimals),grossAmount:X?.grossAmount,grossAmountWei:X?.grossAmountWei,feeAdjusted:!!X})}return o},[o,q]),se=i.useRef(null),ve=i.useMemo(()=>!q?.asset||Ne<=0?!1:D?!de&&!C:!0,[q,Ne,D,de,C]),qe=i.useCallback(()=>Nl(se.current),[]),yt=i.useMemo(()=>!q?.asset||Ne<=0?null:`${q.asset.address.toLowerCase()}:${q.asset.chainId}:${q.amount??""}`,[q?.asset?.address,q?.asset?.chainId,q?.amount,Ne]);i.useEffect(()=>{if(!e||ge)return;if(!q?.asset||Ne<=0){ce(null),be(!1),ee(!1),Ae(null);return}if(!ve){ce(null),be(!1),ee(!0),Ae(null);return}let X=!1;const ye=async it=>{const ht=++_e.current;it||(ce(null),ee(!1),be(!0));try{const Ut=await qe();if(X||_e.current!==ht)return;ce(null),ee(!0),Ae(Ut)}catch(Ut){if(X||_e.current!==ht)return;it||(ce(h.sanitizeError(Ut,"Unable to calculate fees for this lock.")),ee(!1))}finally{!X&&_e.current===ht&&!it&&be(!1)}},Ct=window.setTimeout(()=>{ye(!1)},250),$e=window.setInterval(()=>{ye(!0)},3e4);return()=>{X=!0,clearTimeout(Ct),window.clearInterval($e)}},[e,ge,yt,ve,qe]),i.useEffect(()=>{if(De?.overallStatus==="success"){const X=De.steps.find(ye=>ye.transactionHash);y?.(X?.transactionHash)}},[De?.overallStatus,y]);const pt=x&&q?.asset?._source==="wallet"&&q?.asset?.chainId===c,ft=i.useCallback(()=>Wl(se.current),[]),ut=!!q?.asset&&Ne>0&&!_t&&!It&&!ge&&(!ve||G&&!Ce&&!ne),Pe=oe||ne,Tt=s.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[s.jsx(Us,{color:U}),s.jsxs("p",{style:{fontSize:"13px",color:U,margin:0,lineHeight:"1.5"},children:["Add ",r," by converting assets from your account"]})]});if(se.current={selectedAsset:q,parsedAmount:Ne,selectedDuration:Qe,isInsufficientBalance:It,isSemi7702:D,isSourceDestToken:de,isDirectDeposit:pt,requiresRelayerFeeEstimate:ve,address:Me,embeddedWalletAddress:fe,providerEmbeddedAddress:Se,externalWallet:ct,externalWalletAddress:Ke,activeSignerWallet:bt,activeSignerAddress:mt,isConnected:je,ready:we,authenticated:Ge,provider:Et,actions:Rt,lockChainId:c,escrowAddress:g,onLockExecute:C,onLockSuccess:y,buildSpicenetBatch:v,resolveLockBatches:te,startStatusPolling:zt,refreshSpiceAssets:Je,refreshWalletAssets:Ot,ui:{setError:K,setIsExecuting:Y,setShowStatusPanel:kt}},!e)return null;const He={backgroundColor:W,border:O,borderRadius:H,padding:"16px",marginBottom:"16px"};return s.jsx(un,{isOpen:e,onClose:t,title:`Add ${r} to your account`,subtitle:Tt,styles:w,dark:P,footerLinkText:"Spicenet accounts \u2192",overlayContent:vt?s.jsx("div",{}):void 0,closeOnBackdropClick:n,children:s.jsxs("div",{style:{padding:"0 24px 8px 24px",position:"relative"},children:[s.jsxs("div",{style:{marginBottom:"12px"},children:[A&&s.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:s.jsx(zs,{onClick:A,color:T,fontFamily:S})}),s.jsx("div",{style:{marginTop:"10px",fontSize:"13px",color:U,fontFamily:S},children:s.jsx(qn,{assets:dt,selectedAsset:q??void 0,onAssetSelect:Yt,onAmountChange:sn,label:"Amount",showBalance:!0,showMaxButton:!0,theme:ie,styles:z})}),s.jsx("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:U,fontFamily:S},children:Ht})]}),s.jsxs("div",{style:He,children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:P?`1px solid ${F.cardBorder}`:"1px solid #e5e7eb"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[a?s.jsx("img",{src:a,alt:r,style:{width:"32px",height:"32px",borderRadius:"50%",objectFit:"cover"}}):s.jsx("div",{style:{width:"32px",height:"32px",borderRadius:"50%",backgroundColor:P?F.inputBg:"#d1d5db",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:700,color:J},children:r.slice(0,2)}),s.jsx("span",{style:{fontSize:"16px",fontWeight:600,color:J,fontFamily:S},children:r})]}),s.jsxs("div",{style:{textAlign:"right"},children:[s.jsx("div",{style:{fontSize:"22px",fontWeight:700,color:J,fontFamily:S,lineHeight:1.1},children:ot??"0.00"}),s.jsxs("div",{style:{fontSize:"12px",color:U,fontFamily:S,marginTop:"2px"},children:["~$",ke??"0.00"]})]})]}),s.jsxs("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:P?`1px solid ${F.cardBorder}`:"1px solid #e5e7eb"},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[s.jsx("span",{style:{fontSize:"15px",fontWeight:500,color:U,fontFamily:S},children:"Lock Duration"}),s.jsx(pn,{color:U})]}),s.jsx(bl,{options:f,selectedIndex:me,onSelect:ue,primaryColor:T,dark:P,textPrimary:J,textSecondary:U})]}),s.jsxs("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[s.jsx(vl,{durationMonths:Qe?.months,fontFamily:S,dark:P,textPrimary:J,textSecondary:U}),p&&s.jsx(Il,{votes:Xe,fontFamily:S,dark:P,textPrimary:J,textSecondary:U})]})]}),ve&&s.jsx(es,{fontFamily:S,textPrimary:J,textSecondary:U,cardBg:W,cardBorder:O,resolvedDark:P,darkCardBorder:F.cardBorder,primaryColor:T,feePreview:_,isLoading:Ce,errorText:ne}),Pe&&s.jsx(Rn,{variant:"error",palette:F,fontFamily:S,style:{marginBottom:"12px"},children:Pe}),s.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:ft,disabled:!ut,loading:ge,dark:P,styles:{...w,button:{...w?.button,backgroundColor:T}},children:ge?de?"LOCKING...":"CONVERTING...":_t?`MINIMUM ${fn}`:Ce&&ve?"CALCULATING FEES...":de?`LOCK ${r}`:`CONVERT TO ${r}`}),s.jsx(Al,{isOpen:vt,data:xe,isLocking:ge,lockError:Pe,onContinue:ft,onClose:()=>Ve(!1),primaryColor:T,fontFamily:S,dark:P}),De&&Be&&s.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:P?"rgba(0, 0, 0, 0.45)":"rgba(255, 255, 255, 0.55)",backdropFilter:"blur(2px)",WebkitBackdropFilter:"blur(2px)",borderRadius:H},children:s.jsx(Qs,{type:"lock",showStepBreakdown:!1,isOpen:!!De&&De.overallStatus!=="processing",isProcessing:ge||De?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{We(),kt(!1),ft()},onNewTx:()=>{We(),kt(!1),$(null),Te.current=null,Je(),Ot()},onClose:()=>{We(),kt(!1)},onComplete:()=>{We(),kt(!1),$(null),Te.current=null,Je(),Ot()},results:De?.overallStatus==="success"||De?.overallStatus==="failed"?De.steps.map(X=>({asset:{symbol:q?.asset?.symbol||r,address:q?.asset?.address||""},txHash:X.transactionHash||"",success:X.status==="success",amount:q?.amount})):void 0,chainName:h.getChainName(c),explorerUrl:h.getExplorerUrl(c,"").replace(/\/tx\/.*$/,"")||void 0,theme:E,styles:w,dark:P})})]})})},Ul="0xa9059cbb";function Sr(e,t,n){return B.isNativeToken(e)?{to:n,value:t,data:"0x"}:{to:e,value:0n,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"transfer",args:[n,t]})}}function Ir(e,t,n){return{chainId:n,calls:[Sr(e,t,B.getEscrowContractAddress(n))]}}function Ar(e,t,n){return!t&&e?.asset?._source==="wallet"&&e?.asset.chainId===n}function Er(e,t,n,o){return t!=="user-transfer"||!n||e.length===0||e[0]?.to.toLowerCase()!==o.toLowerCase()||!e[0]?.data.startsWith(Ul)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function hs(e,t,n,o){if(!t)return[e];const r=await t({...n,requestTimestampMs:o});return r?[r,e]:[e]}function Kn(e){return e.filter(t=>t.domain!=="spicenet")}function ms(e){const t=(e.tokenTransfers??[]).filter(n=>n.from==="escrow").map(n=>({token:B.normalizeNativeTokenAddress(n.token),recipient:n.to,amount:BigInt(n.amount)})).filter(n=>n.amount>0n);return t.length>0?t:void 0}function nn(e,t,n){if(t===n)return e;if(t<n)return e*10n**BigInt(n-t);const o=10n**BigInt(t-n);return(e+o-1n)/o}async function so(e,t){const{currentPaymentAmount:n,destinationToken:o,embeddedWalletAddress:r,providerEmbeddedAddress:a,address:l,isNon7702:d,isPayMode:u,resolvedChainId:c,buildActionCalls:f,feeExecutionMode:p,buildSpicenetBatch:g,selectedAsset:x,needsSwap:m,exactOutputSwap:y,resolvedTokenIn:C,requestTimestampMs:k}=e,b=M.parseUnits(n,o.decimals),A=t?.actionAmountOverride??b,v=r||a||(d?void 0:l);if(!v)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const w={userAddress:v,chainId:c,destinationToken:o.address,grossAmount:t?.fundingAmountOverride??b,netAmount:A,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:p,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},R=f(A,w),E={chainId:c,calls:R},P=!u&&!d?!0:x?.asset?._source==="spice",T=Ar(x??null,d,c),F=P||d||T,S=(I,N)=>({token:I,from:d?"solver":"escrow",to:v,amount:N}),j=(I,N,D)=>T?[Ir(I,N,c),...D]:D;if(b===0n)return[E];if(m&&y){const I=C??rn(x.asset,c)??x.asset.address,N=t?.fundingAmountOverride??y.amountInMax,D=F?[S(I,N)]:[],L={to:I,value:0n,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"approve",args:[y.calls[0]?.to,y.amountInMax]})},Q={chainId:c,calls:[L,...y.calls,...R],tokenTransfers:[...D,...E.tokenTransfers??[]]};if(!F)return[Q];const W=await hs(Q,g,{userAddress:v,destinationChainId:c,deliveryToken:I,deliveryAmount:N,deliveryRecipient:v,deliveryTransfers:ms(Q),sourceAsset:x.asset},k);return j(I,N,W)}if(F){const I=C??rn(x.asset,c)??o.address,N=t?.fundingAmountOverride??b,D={...E,tokenTransfers:[S(I,N),...E.tokenTransfers??[]]},L=await hs(D,g,{userAddress:v,destinationChainId:c,deliveryToken:I,deliveryAmount:N,deliveryRecipient:v,deliveryTransfers:ms(D),sourceAsset:x.asset},k);return j(I,N,L)}return[E]}async function oo(e,t){const{selectedAsset:n,embeddedWalletAddress:o,externalWalletAddress:r,recipient:a,resolvedChainId:l,destinationToken:d,buildActionCalls:u,feeExecutionMode:c,buildSpicenetBatch:f,isPayMode:p,isNon7702:g,needsSwap:x,resolvedSwap:m,quoteAmountOut:y,resolvedTokenIn:C,requestTimestampMs:k}=e,b=m?.amountOutMinimum??y;if(!n?.asset||!o)return[];const A=a??(g?r:o);if(!A)return[];const v=t?.fundingAmountOverride??t?.actionAmountOverride??M.parseUnits(n.amount,n.asset.decimals),w=t?.fundingAmountOverride??v,R=t?.sourceFundingAmountOverride??v,E=t?.deliveryAmountOverride??w,P=t?.withdrawalAmountOverride??E,T=t?.actionAmountOverride??v,F={userAddress:A,chainId:l,destinationToken:d.address,feeToken:c==="user-transfer"&&x&&C?C:d.address,grossAmount:w,netAmount:T,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:c,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},S=u(T,F),j=n.asset?._source==="wallet";if(!p&&g&&j&&n.asset.chainId===l){if(x){if(!C)throw new Error("Swap input token could not be resolved");if(!m||b===null)throw new Error("Swap quote not available yet")}if(x&&m&&b){const U=u(t?.actionAmountOverride??b,{...F,netAmount:t?.actionAmountOverride??b}),{feeCall:z,remainingCalls:ie}=Er(U,c,x,F.feeToken);return[{chainId:l,calls:[...z?[z]:[],...m.calls,...ie]}]}return[{chainId:l,calls:S}]}if(!p&&!g&&j&&n.asset.chainId!==l)throw new Error("Cross-chain wallet supplies require external wallet mode");const I=!p&&!g?n.asset?._source!=="wallet":n.asset?._source==="spice",N=g&&j,D=Ar(n,g,l);if(!(I||N||D))return[{chainId:l,calls:S}];const L=D?Ir(C??B.normalizeNativeTokenAddress(n.asset.address),R,l):N&&n.asset.chainId!==l?{chainId:n.asset.chainId,calls:[Sr(B.normalizeNativeTokenAddress(n.asset.address),R,B.getEscrowContractAddress(n.asset.chainId))]}:null,Q=(U,z)=>({token:U,from:N?"solver":"escrow",to:o,amount:z}),W=(U,z)=>N?[{token:U,from:"escrow",to:B.SPICE_SOLVER_ADDRESS,amount:z}]:[];if(x){if(!C)throw new Error("Swap input token could not be resolved");if(!m||b===null)throw new Error("Swap quote not available yet")}if(x&&m&&b&&C){const U=u(t?.actionAmountOverride??b,{...F,netAmount:t?.actionAmountOverride??b}),{feeCall:z,remainingCalls:ie}=Er(U,c,x,F.feeToken),q={chainId:l,calls:[...z?[z]:[],...m.calls,...ie],tokenTransfers:[...W(C,P),Q(C,E)]},$=await hs(q,f,{userAddress:o,destinationChainId:l,deliveryToken:C,deliveryAmount:E,withdrawalAmount:P,deliveryRecipient:o,deliveryTransfers:ms(q),sourceAsset:n.asset},k);return L?[L,...$]:$}const O=C??rn(n.asset,l)??d.address,H={chainId:l,calls:S,tokenTransfers:[...W(O,P),Q(O,E)]},J=await hs(H,f,{userAddress:o,destinationChainId:l,deliveryToken:O,deliveryAmount:E,withdrawalAmount:P,deliveryRecipient:o,deliveryTransfers:ms(H),sourceAsset:n.asset},k);return L?[L,...J]:J}async function ro(e,t,n,o,r){let a=e;for(let l=0;l<4;l++){const d=await t(a),u=await o(d,n,a,r),c=Gi(u);if(c===null||c>=e)return a;const f=a-c,p=e+f;if(p<=a)return a;a=p}return a}function zl(e,t,n,o){if(e<=0n)return 0n;const r=e-t;if(r<=0n)return 0n;const a=o+n;return a<=0n?r:r*o/a}function Ol(e,t){const n=M.formatUnits(e,t);return n.includes(".")?n.replace(/\.?0+$/,"")||"0":n}async function jr(e){const{asset:t,isPayMode:n,isNon7702:o,needsSwap:r,isQuoting:a,embeddedWalletAddress:l,buildSupplyChainBatches:d,estimateGasless:u,executionTokenAddress:c,feeExecutionMode:f}=e;if(n||o||r||a||!l||t.balance<=0n)return null;const p=l,g=await d({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(g.length===0)return null;const x=g.some(A=>A.tokenTransfers?.length),m=await u(g,c,t.balance,x?{userOverride:p,useCustomTransfers:!0,feeExecutionMode:f}:f?{userOverride:p,feeExecutionMode:f}:{userOverride:p}),y=wn(m,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),C=y?nn(y.gasFee,y.decimals,t.decimals):0n,k=y?nn(y.spicenetFee,y.decimals,t.decimals):0n,b=zl(t.balance,C,k,t.balance);return b>0n?Ol(b,t.decimals):null}async function ao(e){const{selectedAsset:t,isPayMode:n,parsedAmount:o,needsSwap:r,exactOutputSwap:a,isNon7702:l,isSourceDestToken:d,currentPaymentAmount:u,destinationToken:c,feeExecutionMode:f,resolvedTokenIn:p,embeddedWalletAddress:g,providerEmbeddedAddress:x,resolvedChainId:m,isConnected:y,address:C,ready:k,authenticated:b,isDirect:A,resolvedSwap:v,isQuoting:w,executionTokenAddress:R,buildPayChainBatches:E,buildSupplyChainBatches:P,estimateGasless:T,estimateRequiredGrossFunding:F}=e;if(!t?.asset)return null;if(n){if(o<=0||r&&!a||d)return null;const W=M.parseUnits(u,c.decimals),O=p||rn(t.asset,m)||t.asset.address||c.address,H={chainId:m,tokenAddress:O,symbol:B.getTokenByAddress(O,m)?.symbol??t.asset.symbol,decimals:B.getTokenByAddress(O,m)?.decimals??t.asset.decimals};if(l){const $=g||x;if(!$)return null;const le=$,he=r?a?.amountInMax??0n:W;if(he===0n)return null;const me=await F(he,Y=>E({fundingAmountOverride:Y}).then(oe=>tn(Kn(oe),le)),O,{userOverride:$,useCustomTransfers:!0}),ue=tn(Kn(await E({fundingAmountOverride:me})),le),ge=await T(ue,O,me,{userOverride:$,useCustomTransfers:!0,feeExecutionMode:f});return wn(ge,H)}if(!y||!C||!k||!b)return null;const J=g||x||C,U=r?a?.amountInMax??0n:W;if(U===0n)return null;const z=await F(U,$=>E({fundingAmountOverride:$}).then(le=>tn(Kn(le),J)),O,{useCustomTransfers:!0});let ie=tn(Kn(await E({fundingAmountOverride:z})),J);const q=await T(ie,O,z,{useCustomTransfers:!0,feeExecutionMode:f});return wn(q,H)}if(o<=0||!g)return null;const S=g||x;if(!(!n&&!l&&t.asset?._source==="wallet"&&t.asset.chainId!==m)&&!A&&!v&&!w||w)return null;const j=M.parseUnits(t.amount,t.asset.decimals),I=await P();if(I.length===0)return null;const N=l&&t.asset?._source==="wallet"&&t.asset.chainId===m,D={chainId:m,tokenAddress:R,symbol:B.getTokenByAddress(R,m)?.symbol??c.symbol,decimals:B.getTokenByAddress(R,m)?.decimals??c.decimals};if(N){const W=await h.relayerService.estimateBatchGas({user:S,outputToken:R,stepIndex:0,chainBatches:I}),O=is(j,10n),H=O+W.gasFee;return{...D,grossAmount:j+H,netAmount:j,totalFee:H,gasFee:W.gasFee,spicenetFee:O,bridgeFee:0n,gasQuoteSource:W.gasQuoteSource}}const L=I.some(W=>W.tokenTransfers?.length),Q=await T(I,R,j,L?{userOverride:S,useCustomTransfers:!0,feeExecutionMode:f}:f?{userOverride:S,feeExecutionMode:f}:{userOverride:S});return wn(Q,D)}const Ll=10n;function Fr(e,t){const n=e.selectedAsset?.asset;if(!n||n?._source!=="wallet")return;const o=rn(n,e.resolvedChainId);if(!o||!h.addressesEqual(o,e.executionTokenAddress))return;const r=B.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),a=nn(t,r?.decimals??e.destinationToken.decimals,n.decimals);if(a<=n.balance)return;const l=M.formatUnits(a,n.decimals),d=M.formatUnits(n.balance,n.decimals);throw new Error(`Insufficient ${n.symbol} for amount plus fees. Required ${l} ${n.symbol}; available ${d} ${n.symbol}.`)}function io(e){const t=B.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);return{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:t?.symbol??e.destinationToken.symbol,decimals:t?.decimals??e.destinationToken.decimals}}function Zn(e,t,n){const o=wn(e,io(t));if(!o)return;const r=is(n,Ll),a=o.bridgeFee??0n,l=r+o.gasFee+a;return{grossAmount:n+l,netAmount:n,combinedFeeAmount:l,feeExecutionMode:"user-transfer",feeBreakdown:{spicenetFee:r,gasFee:o.gasFee,bridgeFee:a}}}function Wn(e,t,n){if(e===t)return!0;const o=e>t?e:t;return o===0n?!1:(e>t?e-t:t-e)*10000n<=o*n}function Br(e,t,n){let o=0n,r=0n;const a=n.toLowerCase();for(const l of e)if(l.chainId===t){for(const d of l.calls??[])if(d.to.toLowerCase()===a)try{const u=M.decodeFunctionData({abi:M.erc20Abi,data:d.data});if(u.functionName!=="transfer")continue;const c=u.args[0].toLowerCase(),f=u.args[1];c===B.SPICE_PLATFORM_FEE_RECIPIENT.toLowerCase()?o+=f:c===B.SPICE_GAS_FEE_RECIPIENT.toLowerCase()&&(r+=f)}catch{continue}}return{spicenetFee:o,gasFee:r}}function lo(e,t,n){const o=t.feeExecutionMode==="user-transfer"&&t.needsSwap&&t.resolvedTokenIn?t.resolvedTokenIn:t.executionTokenAddress,r=Br(e,t.resolvedChainId,o);return r.spicenetFee===0n&&n.feeBreakdown.spicenetFee>0n||r.gasFee===0n&&n.feeBreakdown.gasFee>0n?!1:Wn(r.spicenetFee,n.feeBreakdown.spicenetFee,100n)&&Wn(r.gasFee,n.feeBreakdown.gasFee,100n)}function Tr(e,t){return e?Wn(e.grossAmount,t.grossAmount,100n)&&Wn(e.feeBreakdown.spicenetFee,t.feeBreakdown.spicenetFee,100n)&&Wn(e.feeBreakdown.gasFee,t.feeBreakdown.gasFee,100n)&&Wn(e.feeBreakdown.bridgeFee,t.feeBreakdown.bridgeFee,100n):!1}async function co(e){if(!e.selectedAsset?.asset||e.parsedAmount<=0){e.ui.setError("Select an asset and enter an amount");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.isNon7702){const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setTxHash(null);try{if(e.isSourceDestToken){e.ui.setStep("executing"),e.ui.setStatusMsg("Submitting transaction...");const o=await gs(e);e.ui.setTxHash(o??null)}else{e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.refs.spiceDepositSubmittedRef.current=!1;const o=new AbortController;e.refs.abortControllerRef.current=o,await Mr(e,o.signal)}e.ui.setStep("success"),e.ui.setStatusMsg(e.isSourceDestToken?"Transaction confirmed":"Deposit confirmed")}catch(o){const r=o instanceof Error?o:new Error(String(o));if(r.name==="AbortError"||e.refs.abortControllerRef.current?.signal.aborted){e.ui.setStep("idle");return}const a=r.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(a),e.ui.setError(a),e.onError?.(r)}finally{e.ui.setIsExecuting(!1)}return}if(!e.embeddedWalletAddress){e.ui.setError("Wallet not ready");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.ui.setTxHash(null),e.refs.spiceDepositSubmittedRef.current=!1;const t=new AbortController;e.refs.abortControllerRef.current=t;try{const n=M.parseUnits(e.selectedAsset.amount,e.selectedAsset.asset.decimals),o=n;let r=await e.gasless.buildSupplyChainBatches();const a=e.selectedAsset.asset?._source==="wallet",l=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!a&&!r.some(x=>B.isSpicenetChainId(x.chainId)))throw new Error("Spice-funded supplies must include a Spicenet funding batch before the destination chain batch.");const d=r.some(x=>x.tokenTransfers?.length)?{userOverride:l,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}:e.feeExecutionMode?{userOverride:l,feeExecutionMode:e.feeExecutionMode}:{userOverride:l};let u=n;const c=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,f=e.feeExecutionMode==="user-transfer"&&!c?o:void 0;let p;for(let x=0;x<4;x+=1){const m=await e.gasless.estimateGasless(r,e.executionTokenAddress,u,d),y=wn(m,io(e));p=e.feeExecutionMode==="user-transfer"&&y?Zn(m,e,o):void 0;const C=p?.grossAmount??y?.grossAmount??u;if(C===u){u=C;break}u=C,r=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:f,actionContextOverride:p})}e.feeExecutionMode==="user-transfer"&&(Fr(e,u),r=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:f,actionContextOverride:p}));let g=p;await e.gasless.executeGasless(r,e.executionTokenAddress,u,e.gasless.onProgress,t.signal,e.feeExecutionMode==="user-transfer"?{...d,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:x,chainBatches:m})=>{const y=Zn(x,e,o);if(!y)return null;const C=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&e.resolvedTokenIn?e.resolvedTokenIn:e.executionTokenAddress;Br(m,e.resolvedChainId,C);const k=Tr(g,y),b=lo(m,e,y);return k||b?null:(g=y,e.gasless.buildSupplyChainBatches({fundingAmountOverride:y.grossAmount,actionAmountOverride:f,actionContextOverride:y}))}}:d),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(n){const o=n instanceof Error?n:new Error(String(n));if(o.name==="AbortError"||t.signal.aborted){e.ui.setStep("idle");return}const r=o.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(r),e.ui.setError(r),e.onError?.(o)}finally{e.ui.setIsExecuting(!1)}}async function Mr(e,t){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const n=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!n)throw new Error("Embedded wallet not available \u2014 sign in to create one before supplying");const o=e.selectedAsset.asset,r=M.parseUnits(e.selectedAsset.amount,o.decimals),a=r,l=o?._source==="wallet"&&o.chainId===e.resolvedChainId;let d=await e.gasless.buildSupplyChainBatches();const u={userOverride:n,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode,signAuthorizationsForEstimate:!0};let c=r;const f=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,p=e.feeExecutionMode==="user-transfer"&&!f?a:void 0;let g;if(l){const S=await h.relayerService.estimateBatchGas({user:n,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:d}),j=is(r,10n),I=j+S.gasFee;c=r+I,e.feeExecutionMode==="user-transfer"&&(g={grossAmount:c,netAmount:a,combinedFeeAmount:I,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:j,gasFee:S.gasFee,bridgeFee:0n}})}else for(let S=0;S<4;S+=1){const j=await e.gasless.estimateGasless(d,e.executionTokenAddress,0n,u),I=e.feeExecutionMode==="user-transfer"?Zn(j,e,a):void 0,N=wn(j,io(e)),D=I?.grossAmount??(N?N.grossAmount>r?N.grossAmount:r:c);if(g=I,D===c){c=D;break}c=D;const L=B.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),Q=nn(c,L?.decimals??e.destinationToken.decimals,o.decimals);d=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:Q,withdrawalAmountOverride:c,actionAmountOverride:p,actionContextOverride:I})}const x=B.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId);let m=l?c:nn(c,x?.decimals??e.destinationToken.decimals,o.decimals);Fr(e,c),d=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:m,withdrawalAmountOverride:c,actionAmountOverride:p,actionContextOverride:g});const y=o.chainId,C=n,k=await e.externalWallet.getEthereumProvider();let b=null;try{const S=await k.request({method:"eth_chainId"});b=parseInt(S,16)}catch{b=null}b!==y&&(e.ui.setStatusMsg("Switching source network..."),await h.ensureWalletOnChain(k,y));const A=h.getChainConfig(y),v=M.createWalletClient({account:e.externalWalletAddress,chain:A?.viemChain,transport:M.custom(k)}),w=B.normalizeNativeTokenAddress(o.address),R=o.isNative||B.isNativeToken(w),E=h.getClientForChain(y),P=async S=>{if(S<=0n)return;const j=R?await v.sendTransaction({to:C,value:S,chain:A?.viemChain}):await v.sendTransaction({to:w,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"transfer",args:[C,S]}),chain:A?.viemChain});if((await E.waitForTransactionReceipt({hash:j,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Embedded wallet funding failed")};e.ui.setStatusMsg("Funding embedded wallet..."),await P(m);let T=m;if(e.feeExecutionMode==="user-transfer")for(let S=0;S<4;S+=1){const j=await e.gasless.estimateGasless(d,e.executionTokenAddress,0n,u),I=Zn(j,e,a);if(!I)break;const N=l?I.grossAmount:nn(I.grossAmount,x?.decimals??e.destinationToken.decimals,o.decimals);if(N>T&&(e.ui.setStatusMsg("Topping up embedded wallet..."),await P(N-T),T=N),g=I,c=I.grossAmount,m=N,d=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:c,sourceFundingAmountOverride:m,withdrawalAmountOverride:c,actionAmountOverride:p,actionContextOverride:I}),lo(d,e,I))break}e.ui.setStatusMsg("Signing supply intent...");let F=g;await e.gasless.executeGasless(d,e.executionTokenAddress,0n,e.gasless.onProgress,t,e.feeExecutionMode==="user-transfer"?{...u,skipUserFundingPreflight:!0,adjustBatchesForEstimate:({feeEstimate:S,chainBatches:j})=>{const I=Zn(S,e,a);if(!I)return null;const N=Tr(F,I),D=lo(j,e,I);if(N||D)return null;if(I.grossAmount>c)throw new Error("Fee estimate increased after wallet funding. Please retry so the signed fee can match the latest relayer estimate.");F=I;const L=l?I.grossAmount:nn(I.grossAmount,x?.decimals??e.destinationToken.decimals,o.decimals);return e.gasless.buildSupplyChainBatches({fundingAmountOverride:I.grossAmount,sourceFundingAmountOverride:L,withdrawalAmountOverride:I.grossAmount,actionAmountOverride:p,actionContextOverride:I})}}:u)}async function gs(e){const t=e.isPayMode&&e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t)throw new Error("Select a payment source");const n=e.activeSignerWallet??e.externalWallet,o=e.activeSignerAddress??e.externalWalletAddress;if(!o||!n)throw new Error("Please connect your wallet to continue");const r=M.parseUnits(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),a={userAddress:o,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},l=e.buildActionCalls(r,a);if(l.length===0)throw new Error("No action calls configured");const d=await n.getEthereumProvider();let u=null;try{const x=await d.request({method:"eth_chainId"});u=parseInt(x,16)}catch{u=null}u!==e.resolvedChainId&&await h.ensureWalletOnChain(d,e.resolvedChainId);const c=h.getChainConfig(e.resolvedChainId),f=M.createWalletClient({account:o,chain:c?.viemChain,transport:M.custom(d)}),p=h.getClientForChain(e.resolvedChainId);let g;for(const x of l){const m=await f.sendTransaction({to:x.to,data:x.data,value:x.value,chain:c?.viemChain});if((await p.waitForTransactionReceipt({hash:m,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transaction failed");g=m}return g}async function Rr(e){if(!e.selectedAsset?.asset)throw new Error("Select a payment source");if(!e.externalWalletAddress||!e.externalWallet)throw new Error("Please connect your external wallet to continue");const t=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!t)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const n=e.selectedAsset.asset,o=n.chainId,r=M.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),a=e.selectedIsEquivalent?r:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(a===0n)throw new Error("Quote not available yet");const l=e.resolvedTokenIn||e.selectedAsset.asset.address,d={userOverride:t,useCustomTransfers:!0},u=await e.gasless.estimateRequiredGrossFunding(a,b=>e.gasless.buildPayChainBatches({fundingAmountOverride:b}),l,d),c=B.getEscrowContractAddress(o),f=await e.externalWallet.getEthereumProvider();let p=null;try{const b=await f.request({method:"eth_chainId"});p=parseInt(b,16)}catch{p=null}p!==o&&await h.ensureWalletOnChain(f,o);const g=h.getChainConfig(o),x=M.createWalletClient({account:e.externalWalletAddress,chain:g?.viemChain,transport:M.custom(f)}),m=B.normalizeNativeTokenAddress(n.address),y=n.isNative||B.isNativeToken(m)?await x.sendTransaction({to:c,value:u,chain:g?.viemChain}):await x.sendTransaction({to:m,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"transfer",args:[c,u]}),chain:g?.viemChain});if((await h.getClientForChain(o).waitForTransactionReceipt({hash:y,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Escrow deposit failed");const C=await e.gasless.buildPayChainBatches({fundingAmountOverride:u}),k=C.some(b=>b.tokenTransfers?.length);return await e.gasless.executeGasless(C,l,u,b=>{b.txHash&&(e.ui.setPaymentResult(A=>({...A??{status:"processing"},txHash:b.txHash})),e.ui.setTxHash(b.txHash))},void 0,k?d:{userOverride:t})}async function uo(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}const t=e.parsedAmount===0;if(!e.selectedAsset?.asset&&!t){e.ui.setError("Select a payment source");return}if(e.isInsufficientBalance){e.ui.setError("Insufficient balance");return}if(e.parsedAmount>0&&e.needsSwap&&!e.exactOutputSwap){e.ui.setError("Swap quote not available. Try a different asset.");return}if(e.isNon7702){const n=e.activeSignerAddress??e.externalWalletAddress;if(e.isSourceDestToken||t?!n:!e.externalWalletAddress){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{let o;if(e.isSourceDestToken||e.parsedAmount===0)o=await gs(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const r=e.selectedAsset.asset,a=M.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),l=e.selectedIsEquivalent?a:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(l===0n)throw new Error("Quote not available yet");const d=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!d)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const u=e.resolvedTokenIn||r.address,c=await e.gasless.estimateRequiredGrossFunding(l,g=>e.gasless.buildPayChainBatches({fundingAmountOverride:g}),u,{userOverride:d,useCustomTransfers:!0}),f=await e.gasless.buildPayChainBatches({fundingAmountOverride:c}),p=await e.onPayExecute({asset:r,amount:e.currentPaymentAmount,amountWei:a,destinationToken:e.destinationToken,chainBatches:f,requiredNetFunding:l,grossFundingAmount:c,selectedIsEquivalent:e.selectedIsEquivalent,resolvedTokenIn:u,exactOutputSwapAmountInMax:e.exactOutputSwap?.amountInMax});p&&(e.ui.setTxHash(p),e.ui.setPaymentResult(g=>({...g??{status:"processing"},txHash:p}))),o=p||void 0}else o=await Rr(e);e.ui.setPaymentResult(r=>({status:"success",txHash:r?.txHash||o||""}))}catch(o){const r=h.sanitizeError(o,"Payment failed. Please try again.");e.ui.setError(r),e.ui.setPaymentResult({status:"failed",error:r}),e.onError?.(o instanceof Error?o:new Error(r))}finally{e.ui.setIsExecuting(!1)}return}if(e.isSourceDestToken){if(!(e.activeSignerAddress??e.externalWalletAddress??e.address)){e.ui.setError("Please connect your wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{const n=await gs(e);e.ui.setPaymentResult(o=>({status:"success",txHash:o?.txHash||n||""}))}catch(n){const o=h.sanitizeError(n,"Payment failed. Please try again.");e.ui.setError(o),e.ui.setPaymentResult({status:"failed",error:o}),e.onError?.(n instanceof Error?n:new Error(o))}finally{e.ui.setIsExecuting(!1)}return}if(!e.isConnected||!e.address){e.ui.setError("Please connect your wallet to continue");return}if(!e.ready||!e.authenticated){e.ui.setError(`Please authenticate with ${e.provider||"wallet provider"} to continue`);return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{const n=M.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),o={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode};if(t){const C=await e.gasless.buildPayChainBatches({actionAmountOverride:0n,fundingAmountOverride:0n}),k=await e.gasless.executeGasless(C,e.destinationToken.address,0n,b=>{b.txHash&&(e.ui.setPaymentResult(A=>({...A,txHash:b.txHash})),e.ui.setTxHash(b.txHash))},void 0,o);e.ui.setPaymentResult(b=>({status:"success",txHash:b?.txHash||k}));return}const r=e.selectedAsset?.asset;if(!r)throw new Error("Select a payment source");const a=e.resolvedTokenIn||r.address||e.destinationToken.address,l=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:n,d=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,u=(C,k,b)=>{const A=Kn(C),v=E=>(E.tokenTransfers??[]).some(P=>P.from==="escrow"),w=A.filter(E=>!v(E)),R=A.filter(v);return[...w,...tn(R,d,k,b)]},c=await e.gasless.estimateRequiredGrossFunding(l,C=>e.gasless.buildPayChainBatches({fundingAmountOverride:C}).then(k=>u(k)),a,o);let f=c,p=u(await e.gasless.buildPayChainBatches({fundingAmountOverride:c}));const g=await e.gasless.estimateGasless(p,a,c,o),x=wn(g,{chainId:e.resolvedChainId,tokenAddress:a,symbol:B.getTokenByAddress(a,e.resolvedChainId)?.symbol??r.symbol,decimals:B.getTokenByAddress(a,e.resolvedChainId)?.decimals??r.decimals})?.grossAmount??c;x!==c&&(f=x),p=u(await e.gasless.buildPayChainBatches({fundingAmountOverride:f}),g,{payoutAlreadyGross:!0});const m=p.some(C=>C.tokenTransfers?.length),y=await e.gasless.executeGasless(p,a,m?f:0n,C=>{C.txHash&&(e.ui.setPaymentResult(k=>({...k,txHash:C.txHash})),e.ui.setTxHash(C.txHash))},void 0,o);e.ui.setPaymentResult(C=>({status:"success",txHash:C?.txHash||y}))}catch(n){const o=h.sanitizeError(n,"Payment failed. Please try again.");e.ui.setError(o),e.ui.setPaymentResult({status:"failed",error:o}),e.onError?.(n instanceof Error?n:new Error(o))}finally{e.ui.setIsExecuting(!1)}}const Hl=({variant:e,destinationSymbol:t,destinationLogoURI:n,destinationDecimals:o,primaryColor:r,fontFamily:a,textPrimary:l,textSecondary:d,cardBg:u,cardBorder:c,dk:f,dark:p,isQuoting:g,quoteError:x,estimatedOutput:m,paymentAmount:y,needsSwap:C,exactOutputSwap:k,adjustable:b=!1,maxAmount:A,onAmountChange:v})=>e==="supply"?s.jsxs("div",{style:{backgroundColor:u,border:`1px solid ${c}`,borderRadius:p?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",minHeight:"112px",display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"12px"},children:[s.jsxs("div",{style:{minWidth:0},children:[s.jsx("span",{style:{fontFamily:a,fontSize:"17px",fontWeight:500,color:p?"#a7abb2":"#7D7C7B",lineHeight:"24px"},children:"Used in TX"}),s.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:d,fontFamily:a,marginTop:"10px"},children:"Net amount after swap and fees"})]}),s.jsxs("div",{style:{textAlign:"right",minWidth:0,display:"inline-flex",alignItems:"center",gap:"8px",border:`1px solid ${c}`,borderRadius:"8px",padding:"8px 10px",minHeight:"42px"},children:[s.jsx(Nr,{symbol:t,logoURI:n,primaryColor:r,size:24}),s.jsx("span",{style:{fontSize:"16px",fontWeight:500,color:p?"#f3f4f6":"#3C3E42",lineHeight:"1.3",fontFamily:a,letterSpacing:0},children:t})]})]}),s.jsx("div",{style:{textAlign:"right",minWidth:0},children:g?s.jsx("span",{style:{fontSize:"18px",color:d,fontFamily:a},children:"Quoting..."}):x?s.jsx("span",{style:{fontSize:"13px",color:p?"#f87171":"#dc2626",fontFamily:a},children:"Quote failed"}):m?s.jsx(Sn,{value:m,title:m,fontFamily:a,color:l,lineHeight:"0.95",textAlign:"right",maxFontSize:32,minFontSize:18}):s.jsx("span",{style:{fontSize:"20px",color:d,fontFamily:a},children:"\u2014"})})]}):s.jsx(ql,{destinationSymbol:t,destinationLogoURI:n,destinationDecimals:o,primaryColor:r,fontFamily:a,textPrimary:l,textSecondary:d,cardBg:u,cardBorder:c,dk:f,dark:p,paymentAmount:y||"0",needsSwap:C,exactOutputSwap:k,isQuoting:g,adjustable:b,maxAmount:A,onAmountChange:v}),Dr=i.memo(Hl),Nr=({symbol:e,logoURI:t,primaryColor:n,size:o})=>t?s.jsx("img",{src:t,alt:e,style:{width:o,height:o,borderRadius:"50%",objectFit:"cover"}}):s.jsx("div",{style:{width:o,height:o,borderRadius:"50%",backgroundColor:`${n}22`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:o<30?"11px":"12px",fontWeight:700,color:n},children:e.slice(0,2)}),ql=({destinationSymbol:e,destinationLogoURI:t,destinationDecimals:n,primaryColor:o,fontFamily:r,textPrimary:a,textSecondary:l,cardBg:d,cardBorder:u,dk:c,dark:f,paymentAmount:p,needsSwap:g,exactOutputSwap:x,isQuoting:m,adjustable:y,maxAmount:C,onAmountChange:k})=>{const b='"IBM Plex Mono", monospace',A=parseFloat(p||"0"),v=C?parseFloat(C):0,[w,R]=i.useState(p||""),E=i.useRef(null),[P,T]=i.useState(null),[F,S]=i.useState(null);i.useEffect(()=>{y||R(p||"")},[p,y]);const j=D=>{let L=D;L.startsWith(".")&&(L="0"+L);const Q=Tn(L);let W=Q;C&&parseFloat(Q)>parseFloat(C)&&(W=C),R(W),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>k?.(W),300)},I=D=>{if(!v)return;if(D===100){R(C||v.toString()),E.current&&clearTimeout(E.current),k?.(C||v.toString());return}const L=10**n,Q=Math.floor(v*D/100*L)/L,W=Mn(Q,n);R(W),E.current&&clearTimeout(E.current),k?.(W)},N=v>0?parseFloat(w||"0")/v*100:0;return i.useEffect(()=>()=>{E.current&&clearTimeout(E.current)},[]),s.jsxs("div",{style:{backgroundColor:d,border:`1px solid ${u}`,borderRadius:f?"12px":"6px",padding:"16px",marginBottom:"16px"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[s.jsx(Nr,{symbol:e,logoURI:t,primaryColor:o,size:32}),s.jsxs("div",{children:[s.jsx("span",{style:{fontSize:"14px",fontWeight:600,color:a,fontFamily:r},children:"Payment"}),s.jsx("div",{style:{fontSize:"12px",color:l,fontFamily:r,marginTop:"2px"},children:e})]})]}),s.jsxs("div",{style:{textAlign:"right"},children:[y?s.jsx(Sn,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:w,onChange:D=>j(D.target.value),placeholder:"0.0",fontFamily:b,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):s.jsx(Sn,{element:"div",value:A>0?p:"0.00",title:A>0?p:"0.00",fontFamily:b,color:a,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),s.jsx("div",{style:{fontSize:"12px",color:l,fontFamily:b,marginTop:"2px"},children:e}),y&&v>0&&s.jsx("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((D,L)=>{const Q=Math.abs(N-D)<1,W=L===4,O=D/100,H=P===D,J=F===D;return s.jsx("button",{onClick:()=>I(D),onMouseEnter:()=>T(D),onMouseLeave:()=>{T(null),S(null)},onMouseDown:()=>S(D),onMouseUp:()=>S(null),title:`${D}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:Q?1:H?.8:.5,transform:J?"scale(0.85)":H?"scale(1.15)":"scale(1)",transition:Jt.interactive},children:s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[s.jsx("circle",{cx:"7",cy:"7",r:"6.84375",fill:W?o:"none",stroke:W?o:f?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!W&&O>0&&s.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${O>.5?1:0} 1 ${7+6.84375*Math.sin(O*2*Math.PI)} ${7-6.84375*Math.cos(O*2*Math.PI)} Z`,fill:f?c?.textSecondary||"#9ca3af":"#3C3E42"})]})},D)})})]})]}),g&&x&&!m&&s.jsx("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:f?`1px solid ${c?.cardBorder||u}`:"1px solid #e5e7eb",display:"flex",justifyContent:"flex-end"},children:s.jsxs("span",{style:{fontSize:"11px",color:l,fontFamily:r,opacity:.7},children:["via ",x.venue]})})]})};function Pr(e,t,n){const o=h.addressesEqual(e.address,t),r=e.chainId===n,a=e._source==="wallet";return a&&o&&r?0:a&&r?1:!a&&o?2:!a&&r?3:4}function Wr(e,t){return!t||t.length===0||t.some(n=>h.addressesEqual(n,e.address))?!0:Object.keys(e.chainTokens??{}).some(n=>{const o=Nn(n);return o?t.some(r=>h.addressesEqual(r,o.address)):!1})}function po(e){const{destinationToken:t,supportedSourceAssets:n,sourceChains:o,enabled:r}=e,a=(i.useContext(h.SpiceFlowProviderContext)?.mode||"7702")!=="7702",l=h.useEmbeddedWalletAddress(),{externalAddress:d,embeddedAddress:u,activeAddress:c}=h.useProviderWallets(),f=l||u,{assets:p,refetch:g}=Vn({address:f,supportedChains:o,enabled:r&&!a&&!!f,refetchInterval:3e4}),x=i.useMemo(()=>a?[]:p.filter(P=>Wr(P,n)),[p,n,a]),m=a?c??d:l,y=i.useMemo(()=>{const P=new Set,T=[],F=S=>{if(!S)return;const j=S.toLowerCase();P.has(j)||(P.add(j),T.push(M.getAddress(S)))};if(F(t.address),n)for(const S of n)F(S);return T},[a,t.address,n]),C=i.useMemo(()=>y.map(P=>P.toLowerCase()).sort().join(","),[y]),k=i.useMemo(()=>JSON.stringify([...o||[]].sort()),[o]),[b,A]=i.useState([]),v=i.useRef(0),w=i.useRef(async()=>{}),R=i.useCallback(async()=>{if(!r||!m||y.length===0){v.current++,A([]);return}const P=++v.current,T=M.getAddress(m),F=a?o&&o.length>0?o:[t.chainId]:[t.chainId],S=[];for(const D of y){const L=D.toLowerCase();if(L===B.ZERO_ADDRESS)continue;if(L===t.address.toLowerCase()){const W=h.getChainConfig(t.chainId)?.supportedTokens?.find(O=>h.addressesEqual(O.address,L));S.push({address:D,chainId:t.chainId,configToken:W?{decimals:W.decimals,symbol:W.symbol,name:W.name,logo:W.logo}:void 0});continue}let Q=!1;for(const W of F){const O=h.getChainConfig(W)?.supportedTokens?.find(H=>h.addressesEqual(H.address,L));if(O){S.push({address:D,chainId:W,configToken:{decimals:O.decimals,symbol:O.symbol,name:O.name,logo:O.logo}}),Q=!0;break}}Q||S.push({address:D,chainId:t.chainId})}const j=new Map;for(const D of S){const L=j.get(D.chainId)||[];L.push(D),j.set(D.chainId,L)}const I=async(D,L)=>{try{const Q=await Zt.readContract(D,{address:L.address,abi:M.erc20Abi,functionName:"balanceOf",args:[T]});let W,O,H,J;if(L.configToken)W=L.configToken.decimals,O=L.configToken.symbol,H=L.configToken.name,J=L.configToken.logo;else{const[ie,q,$]=await Promise.all([Zt.readContract(D,{address:L.address,abi:M.erc20Abi,functionName:"decimals"}).catch(()=>18),Zt.readContract(D,{address:L.address,abi:M.erc20Abi,functionName:"symbol"}).catch(()=>"TOKEN"),Zt.readContract(D,{address:L.address,abi:M.erc20Abi,functionName:"name"}).catch(()=>"TOKEN")]);W=Number(ie),O=q,H=$}const U=h.addressesEqual(L.address,t.address)&&L.chainId===t.chainId;U&&t.logoURI&&(J=t.logoURI),U&&!L.configToken&&O==="TOKEN"&&(O=t.symbol,H=t.symbol);const z=parseFloat((Number(Q)/Math.pow(10,W)).toFixed(6));return{address:L.address,name:H,symbol:O,decimals:W,balance:Q,balanceFormatted:z,balanceUsd:0,logoURI:J,isNative:!1,chainId:L.chainId}}catch{return null}},N=await Promise.all(Array.from(j.entries()).map(async([D,L])=>{let Q;try{Q=h.getClientForChain(D)}catch{return[]}const W=[],O=[];for(const J of L){const U=W.length;W.push({address:J.address,abi:M.erc20Abi,functionName:"balanceOf",args:[T]}),J.configToken||W.push({address:J.address,abi:M.erc20Abi,functionName:"decimals"},{address:J.address,abi:M.erc20Abi,functionName:"symbol"},{address:J.address,abi:M.erc20Abi,functionName:"name"}),O.push({start:U,item:J})}let H=null;try{H=await Q.multicall({contracts:W})}catch{H=null}return H?O.map(({start:J,item:U})=>{const z=H[J],ie=z?.status==="success"?z.result:0n;let q,$,le,he;if(U.configToken)q=U.configToken.decimals,$=U.configToken.symbol,le=U.configToken.name,he=U.configToken.logo;else{const ge=H[J+1],Y=H[J+2],oe=H[J+3];q=ge?.status==="success"?Number(ge.result):18,$=Y?.status==="success"?Y.result:"TOKEN",le=oe?.status==="success"?oe.result:$}const me=h.addressesEqual(U.address,t.address)&&U.chainId===t.chainId;me&&t.logoURI&&(he=t.logoURI),me&&!U.configToken&&$==="TOKEN"&&($=t.symbol,le=t.symbol);const ue=parseFloat((Number(ie)/Math.pow(10,q)).toFixed(6));return{address:U.address,name:le,symbol:$,decimals:q,balance:ie,balanceFormatted:ue,balanceUsd:0,logoURI:he,isNative:!1,chainId:U.chainId}}):(await Promise.all(L.map(J=>I(Q,J)))).filter(J=>J!==null)}));P===v.current&&A(N.flat())},[r,a,m,C,k,t.address,t.chainId,t.symbol,t.logoURI]);i.useEffect(()=>{w.current=R},[R]),i.useEffect(()=>{if(!r){A([]);return}w.current();const P=setInterval(()=>{w.current()},15e3);return()=>clearInterval(P)},[r,a,m,C,k,t.address,t.chainId]);const E=i.useCallback(()=>{R()},[R]);return{displayAssets:i.useMemo(()=>{const P=[],T=b.filter(S=>S.balance>0n);for(const S of T)P.push({...S,_source:"wallet"});for(const S of x)P.push({...S,_source:"spice"});const F=t.address.toLowerCase();return P.sort((S,j)=>Pr(S,F,t.chainId)-Pr(j,F,t.chainId)),P},[b,x,t.address,t.chainId]),filteredSpiceAssets:x,walletAssets:b,embeddedWalletAddress:f,externalAddress:d,isNon7702:a,refreshSpiceAssets:g,refreshWalletAssets:E}}async function Ur(e){const{tokenIn:t,tokenOut:n,amountIn:o,fee:r,chainId:a,config:l}=e;if(o<=0n)throw new Error("amountIn must be greater than 0");const d=(await h.getClientForChain(a).simulateContract({address:l.quoterV2,abi:B.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:n,amountIn:o,fee:r,sqrtPriceLimitX96:0n}]})).result;if(d[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 output.");return{amountOut:d[0],sqrtPriceX96After:d[1],gasEstimate:d[3]}}async function zr(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(r=>Ur({...e,fee:r})));let o=null;for(let r=0;r<n.length;r++){const a=n[r];a.status==="fulfilled"&&(!o||a.value.amountOut>o.amountOut)&&(o={...a.value,fee:t[r]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}const Ql=[{inputs:[{components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"amount",type:"uint256"},{name:"fee",type:"uint24"},{name:"sqrtPriceLimitX96",type:"uint160"}],name:"params",type:"tuple"}],name:"quoteExactOutputSingle",outputs:[{name:"amountIn",type:"uint256"},{name:"sqrtPriceX96After",type:"uint160"},{name:"initializedTicksCrossed",type:"uint32"},{name:"gasEstimate",type:"uint256"}],stateMutability:"nonpayable",type:"function"}];async function Vl(e){const{tokenIn:t,tokenOut:n,amountOut:o,fee:r,chainId:a,config:l}=e;if(o<=0n)throw new Error("amountOut must be greater than 0");const d=(await h.getClientForChain(a).simulateContract({address:l.quoterV2,abi:Ql,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:n,amount:o,fee:r,sqrtPriceLimitX96:0n}]})).result;if(d[0]<=0n)throw new Error("No liquidity found for this pair. The pool returned 0 input.");return{amountIn:d[0],sqrtPriceX96After:d[1],gasEstimate:d[3]}}async function Gl(e){const t=e.feeTiers??[100,500,3e3,1e4],n=await Promise.allSettled(t.map(r=>Vl({...e,fee:r})));let o=null;for(let r=0;r<n.length;r++){const a=n[r];a.status==="fulfilled"&&(!o||a.value.amountIn<o.amountIn)&&(o={...a.value,fee:t[r]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}function Or(e){return e.type==="swap"}const fo=.02,Kl=[1,8453,42161,10,137,43114,56],Zl="https://api.1inch.dev/swap/v6.0";function Lr(e,t){return B.applySlippage(e,t)}function Hr(e){const t=e?.baseUrl??Zl;return{name:"1inch",chainIds:e?.chainIds??Kl,resolve:async(n,o,r)=>{const a=n.maxSlippage??fo,l=a*100,d=B.isNativeToken(n.tokenIn)?B.NATIVE_TOKEN_ADDRESS:n.tokenIn,u=B.isNativeToken(n.tokenOut)?B.NATIVE_TOKEN_ADDRESS:n.tokenOut,c=B.isNativeToken(n.tokenIn);try{const f=new URL(`${t}/${o}/swap`);f.searchParams.set("src",d),f.searchParams.set("dst",u),f.searchParams.set("amount",n.amountIn.toString()),f.searchParams.set("from",r),f.searchParams.set("slippage",l.toString()),f.searchParams.set("disableEstimate","true"),f.searchParams.set("allowPartialFill","false");const p={Accept:"application/json"};e?.apiKey&&(p.Authorization=`Bearer ${e.apiKey}`);const g=await fetch(f.toString(),{headers:p});if(!g.ok)throw new h.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${g.status} for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`,{venue:"1inch",chainId:o,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:`HTTP ${g.status}`});const x=await g.json();if(!x.dstAmount||!x.tx)return console.warn(`[1inchVenue] No route data for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const m=BigInt(x.dstAmount);if(m<=0n)return console.warn(`[1inchVenue] Zero output for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}`),null;const y=Lr(m,a),C=[];return x.tx.to&&!c&&C.push({to:n.tokenIn,value:0n,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"approve",args:[x.tx.to,n.amountIn]})}),C.push({to:x.tx.to,value:BigInt(x.tx.value||"0"),data:x.tx.data}),{venue:"1inch",amountOut:m,amountOutMinimum:y,calls:C}}catch(f){if(f instanceof h.SpiceflowError)throw f;const p=f instanceof Error?f.message:String(f);throw new h.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] Exception for ${n.tokenIn} \u2192 ${n.tokenOut} on chain ${o}: ${p}`,{venue:"1inch",chainId:o,tokenIn:n.tokenIn,tokenOut:n.tokenOut,amountIn:n.amountIn.toString(),cause:p})}}}}const qr=[4114,5115],ho={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425",feeTiers:[3e3]},Qr={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453],feeTiers:[3e3]};function Vr(e){return{name:"satsuma",chainIds:e.chainIds??qr,resolve:async(t,n,o)=>{const r=t.maxSlippage??fo,a=B.isNativeToken(t.tokenIn);let l;try{l=await zr({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountIn:t.amountIn,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return console.warn(`[SatsumaVenue] No viable fee tier for ${t.tokenIn} \u2192 ${t.tokenOut} on chain ${n}.`),null}const d=Lr(l.amountOut,r),u=[];return a||u.push({to:t.tokenIn,value:0n,data:M.encodeFunctionData({abi:M.erc20Abi,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),u.push({to:e.swapRouter,value:a?t.amountIn:0n,data:M.encodeFunctionData({abi:B.uniV3SwapRouterAbi,functionName:"exactInputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:l.fee,recipient:o,amountIn:t.amountIn,amountOutMinimum:d,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:l.amountOut,amountOutMinimum:d,calls:u}}}}function Gr(e){return{name:"satsuma",chainIds:e.chainIds??qr,resolve:async(t,n,o)=>{const r=t.maxSlippage??fo,a=B.isNativeToken(t.tokenIn);let l;try{l=await Gl({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountOut:t.amountOut,chainId:n,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return null}const d=BigInt(Math.round(r*1e4)),u=l.amountIn+l.amountIn*d/10000n,c=[];return c.push({to:e.swapRouter,value:a?u:0n,data:M.encodeFunctionData({abi:Yl,functionName:"exactOutputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:l.fee,recipient:o,amountOut:t.amountOut,amountInMaximum:u,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:l.amountIn,amountInMax:u,amountOut:t.amountOut,calls:c}}}}const Yl=[{inputs:[{components:[{name:"tokenIn",type:"address"},{name:"tokenOut",type:"address"},{name:"fee",type:"uint24"},{name:"recipient",type:"address"},{name:"amountOut",type:"uint256"},{name:"amountInMaximum",type:"uint256"},{name:"sqrtPriceLimitX96",type:"uint160"}],name:"params",type:"tuple"}],name:"exactOutputSingle",outputs:[{name:"amountIn",type:"uint256"}],stateMutability:"payable",type:"function"}];function Kr(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(Vr(e.satsuma)),t.push(Hr(e?.oneInch));function n(r){return t.find(a=>a.chainIds.includes(r))}async function o(r,a,l){const d=[],u=[];for(const c of r){if(!Or(c)){d.push(c);continue}const f=n(a);if(!f)throw new h.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${a}. Cannot resolve swap ${c.tokenIn} \u2192 ${c.tokenOut}.`,{chainId:a,tokenIn:c.tokenIn,tokenOut:c.tokenOut,amountIn:c.amountIn.toString()});const p=await f.resolve(c,a,l);if(!p)throw new h.SpiceflowError("NO_LIQUIDITY",`${f.name} returned no quote for ${c.tokenIn} \u2192 ${c.tokenOut} on chain ${a}.`,{venue:f.name,chainId:a,tokenIn:c.tokenIn,tokenOut:c.tokenOut,amountIn:c.amountIn.toString()});d.push(...p.calls),u.push(p)}return{calls:d,resolvedSwaps:u}}return{resolveSwapIntents:o,getVenueForChain:n,venues:t}}function Zr(e){const t=e?.customVenues??[];async function n(o,r,a){const l=t.filter(u=>u.chainIds.includes(r));if(l.length===0)throw new h.SpiceflowError("NO_SWAP_ROUTE",`No exact-output venue supports chain ${r}`,{chainId:r,tokenIn:o.tokenIn,tokenOut:o.tokenOut});const d=(await Promise.allSettled(l.map(u=>u.resolve(o,r,a)))).filter(u=>u.status==="fulfilled").map(u=>u.value).filter(u=>u!==null);if(d.length===0)throw new h.SpiceflowError("NO_SWAP_ROUTE",`All aggregators failed for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${r}`,{chainId:r,tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountOut:o.amountOut.toString()});return d.sort((u,c)=>u.amountIn<c.amountIn?-1:u.amountIn>c.amountIn?1:0),d[0]}return{getQuote:n,venues:t}}const Yr=Kr({satsuma:ho});async function Xl(e){const t=Yr.getVenueForChain(e.chainId);if(!t)throw new Error(`No swap venue configured for chain ${e.chainId}.`);const n=await t.resolve({type:"swap",tokenIn:e.tokenIn,tokenOut:e.tokenOut,amountIn:e.amountIn},e.chainId,e.recipient);if(!n)throw new Error("No liquidity for this pair.");return n}function mo(e){const{direction:t,selectedAsset:n,destinationToken:o,chainId:r,recipient:a,paymentAmount:l,resolveExactOutputSwap:d}=e,[u,c]=i.useState(!1),[f,p]=i.useState(null),[g,x]=i.useState(null),[m,y]=i.useState(null),[C,k]=i.useState(null),[b,A]=i.useState(null),[v,w]=i.useState(null),[R,E]=i.useState(null),[P,T]=i.useState(null),F=i.useRef(null),S=i.useRef(null),j=i.useRef(0),I=i.useRef(new Map),N=i.useMemo(()=>Yr,[]),D=i.useMemo(()=>Zr({customVenues:[...d?[{name:"consumer-exact-output",chainIds:[r],resolve:d}]:[],Gr(ho),Gr(Qr)]}),[d,r]),L=i.useMemo(()=>{if(!n?.asset)return null;const $=rn(n.asset,r);if($)return $;const le=mn(n.asset.address,r,n.asset.chainId);return le?le.address:null},[n?.asset,r]),Q=i.useMemo(()=>n?.asset?os(n.asset,r):[],[n?.asset,r]),W=i.useMemo(()=>Q.map($=>$.toLowerCase()).join(","),[Q]);i.useEffect(()=>{let $=!1;if(S.current&&(clearTimeout(S.current),S.current=null),!n?.asset||Q.length<=1){T(null);return}return S.current=setTimeout(async()=>{const le=t==="input"?n.amount:l||"0";let he=0n;try{he=t==="input"?M.parseUnits(le,n.asset.decimals):0n}catch{he=0n}try{const me=await $o(n.asset,r,{requiredAmount:he});$||T(me)}catch{$||T(null)}},400),()=>{$=!0,S.current&&(clearTimeout(S.current),S.current=null)}},[n?.asset,n?.amount,r,Q.length,W,t,l]);const O=i.useMemo(()=>P??L,[P,L]),H=i.useMemo(()=>!n?.asset||!O?[]:[O,...Q.filter($=>$.toLowerCase()!==O.toLowerCase())],[n?.asset,O,Q]),J=i.useMemo(()=>!n?.asset||!Qn(n.asset.address,n.asset.chainId,o.address,o.chainId)||!O?!1:h.addressesEqual(O,o.address),[n,o.address,o.chainId,O]),U=O?h.addressesEqual(O,o.address):!1,z=t==="output"&&parseFloat(l||"0")===0,ie=!!n?.asset&&!J&&!U&&!z,q=ie?R??O:O;return i.useEffect(()=>{F.current&&clearTimeout(F.current);const $=t==="input"?n?.amount:l,le=parseFloat($||"0");if(!ie||!Number.isFinite(le)||le<=0||!n?.asset||!a||H.length===0){j.current++,x(null),y(null),k(null),A(null),w(null),E(null),p(null),c(!1);return}const he=n.asset.decimals;let me;try{me=t==="input"?M.parseUnits(n.amount,he):M.parseUnits(l||"0",o.decimals)}catch{j.current++,p("Invalid amount"),c(!1);return}const ue=++j.current,ge=()=>ue!==j.current;c(!0);const Y=t==="output"?150:400;return F.current=setTimeout(async()=>{try{if(t==="input"){const oe=N.getVenueForChain(r);if(!oe)throw new Error("No swap venue for this chain");let K=null,ne=null;for(const Ce of H){const be=`${t}:${r}:${Ce.toLowerCase()}:${o.address.toLowerCase()}:${me.toString()}`,G=I.current.get(be);if(G&&G.expiresAt>Date.now()&&G.resolvedSwap){K=G.resolvedSwap,ne=Ce;break}const ee=await oe.resolve({type:"swap",tokenIn:Ce,tokenOut:o.address,amountIn:me},r,a);if(ge())return;if(ee){I.current.set(be,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:ee}),K=ee,ne=Ce;break}}if(!K||!ne)throw new Error("No liquidity for this pair");E(ne),w(K.amountOut),k(K),A(null);const ce=parseFloat(M.formatUnits(K.amountOut,o.decimals));x(ce<.01?ce.toPrecision(4):ce.toLocaleString(void 0,{maximumFractionDigits:6})),y(null),p(null)}else{let oe=null,K=null;for(const ne of H){const ce=`${t}:${r}:${ne.toLowerCase()}:${o.address.toLowerCase()}:${me.toString()}`,Ce=I.current.get(ce);if(Ce&&Ce.expiresAt>Date.now()&&Ce.exactOutputSwap){oe=Ce.exactOutputSwap,K=ne;break}try{const be=await D.getQuote({tokenIn:ne,tokenOut:o.address,amountOut:me},r,a);if(ge())return;I.current.set(ce,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:be}),oe=be,K=ne;break}catch{if(ge())return}}if(!oe||!K)throw new Error("No liquidity for this pair");E(K),A(oe),k(null),w(null),y(parseFloat(M.formatUnits(oe.amountIn,he)).toFixed(6)),x(null),p(null)}}catch(oe){if(ge())return;const K=oe instanceof Error?oe.message:"Failed to get quote";p(K),x(null),y(null),k(null),A(null),w(null),E(null)}finally{ge()||c(!1)}},Y),()=>{F.current&&clearTimeout(F.current)}},[t,ie,n?.amount,n?.asset?.address,n?.asset?.decimals,l,H,r,o.address,o.decimals,a,N,D]),{isQuoting:u,quoteError:f,estimatedOutput:g,estimatedInput:m,resolvedSwap:C,exactOutputSwap:b,quoteAmountOut:v,resolvedTokenIn:q,isDirect:U,needsSwap:ie,selectedIsEquivalent:J}}const Xr={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},Jr=["signing-delegation","signing-intent","submitting","executing"],Jl=()=>{},$r=({isOpen:e,onClose:t,closeOnBackdropClick:n=!1,destinationToken:o,sourceChains:r,supportedSourceAssets:a,buildActionCalls:l,feeExecutionMode:d="user-transfer",buildSpicenetBatch:u,onPayExecute:c,resolveExactOutputSwap:f,actionLabel:p,amountDirection:g="input",swapDescription:x,directDescription:m,paymentAmount:y,amountInputMode:C="fixed",minPaymentAmount:k,maxPaymentAmount:b,onAmountChange:A,styles:v,dark:w,title:R,subtitle:E,onAddFunds:P,onSuccess:T,onError:F})=>{const S=g==="output",{theme:j,dark:I,primaryColor:N,dk:D,palette:L,fontFamily:Q,monoFont:W,inputDark:O,cardBg:H,cardBorder:J,textPrimary:U,textSecondary:z,subtitleText:ie}=h.useSpiceBrand(v,w),q=i.useMemo(()=>O?{...j,colors:{...j.colors,secondary:D.cardBg,surfaceHover:D.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:j,[O,j,D.cardBg,D.hoverBg]),$=o.chainId,le=i.useContext(h.SpiceFlowProviderContext),he=(le?.mode||"7702")!=="7702",me=!!le?.isWhitelistGateActive,ue=!!le?.isWhitelistConfigured&&le?.isUserWhitelisted!==!0,ge=i.useMemo(()=>r??le?.supportedChainIds??[],[r,le?.supportedChainIds]),Y=i.useMemo(()=>{if(me)return[];if(a)return a;const Ie=le?.allowedTokens;if(!Ie||Ie.length===0)return;const at=new Set(Ie.map(yn=>yn.toLowerCase())),cn=[],xn=new Set;for(const yn of ge){const ws=h.getChainConfig(yn);for(const ks of ws?.supportedTokens??[]){if(!at.has(ks.symbol.toLowerCase()))continue;const Co=ks.address.toLowerCase();xn.has(Co)||(xn.add(Co),cn.push(ks.address))}}return cn},[a,le?.allowedTokens,ge,me]),oe=h.useWallet(),{address:K,isConnected:ne,isReady:ce,isAuthenticated:Ce,provider:be}=oe,{executeGasless:G,estimateGasless:ee}=Pn(),{externalWallet:_,externalAddress:Ae,embeddedAddress:Be,activeWallet:kt,activeAddress:_e}=h.useProviderWallets(),vt=h.useEmbeddedWalletAddress()||Be,{displayAssets:Ve,filteredSpiceAssets:xe,embeddedWalletAddress:Ee,refreshSpiceAssets:ze,refreshWalletAssets:lt}=po({destinationToken:o,supportedSourceAssets:Y,sourceChains:ge,enabled:e&&(he?!!Ae:!!vt)}),et=me||S||he?Ve:xe,[re,we]=i.useState(null),[Ge,je]=i.useState(y||""),[Me,Et]=i.useState(!1),[Rt,ct]=i.useState(null),[Se,St]=i.useState("idle"),[bt,mt]=i.useState(""),[De,zt]=i.useState(null),[We,gt]=i.useState(!1),[Je,wt]=i.useState(null),[fe,Ke]=i.useState(null),[tt,xt]=i.useState(!1),[Re,nt]=i.useState(!1),[Pt,Ye]=i.useState(null),st=i.useRef(re),jt=i.useRef(!1),Ft=i.useRef(null),Ot=i.useRef(null),Bt=i.useRef(0),Wt=i.useRef(null),dt=i.useRef(null);i.useEffect(()=>{st.current=re},[re]);const Te=C==="adjustable"?Ge:y||"0",Mt=Ee||Be||K,{isQuoting:Ne,quoteError:_t,estimatedOutput:Lt,resolvedSwap:It,exactOutputSwap:Qe,quoteAmountOut:de,resolvedTokenIn:Le,isDirect:ot,needsSwap:Xe,selectedIsEquivalent:Ht}=mo({direction:g,selectedAsset:re,destinationToken:o,chainId:$,recipient:Mt,paymentAmount:Te,resolveExactOutputSwap:f}),ke=S?parseFloat(Te||"0"):parseFloat(re?.amount||"")||0,Yt=ke>0&&ke<fn,sn=re?.asset?._source==="wallet",te=!!re?.asset&&sn&&re.asset.chainId!==$,se=i.useMemo(()=>re?.asset?xe.find(Ie=>h.addressesEqual(Ie.address,re.asset.address))?.balanceFormatted??0:0,[re,xe]),ve=sn?re?.asset.balanceFormatted??0:se,qe=i.useMemo(()=>{if(!re?.asset)return!1;if(S)return fe?nn(fe.grossAmount,fe.decimals,re.asset.decimals)>re.asset.balance:Ht||ot?ke>re.asset.balanceFormatted:Qe?parseFloat(M.formatUnits(Qe.amountInMax,re.asset.decimals))>re.asset.balanceFormatted:!1;if(fe){const Ie=nn(fe.grossAmount,fe.decimals,re.asset.decimals);return sn?Ie>re.asset.balance:parseFloat(M.formatUnits(Ie,re.asset.decimals))>ve}return ke>ve},[re,S,fe,Ht,ke,Qe,ve,sn,ot]);i.useEffect(()=>{e||(we(null),ct(null),Et(!1),St("idle"),mt(""),zt(null),gt(!1),wt(null),Ke(null),xt(!1),nt(!1),Ye(null),jt.current=!1,C==="adjustable"&&je(y||""),Ft.current&&(Ft.current.abort(),Ft.current=null))},[e]);const yt=i.useCallback(Ie=>{we(at=>({asset:Ie,amount:at?.asset?.address===Ie.address&&at?.asset?.chainId===Ie.chainId&&at.amount||""})),ct(null),Ye(null),nt(!1)},[]),pt=i.useCallback(Ie=>{we(at=>at&&{...at,amount:Ie}),ct(null),Ye(null),nt(!1)},[]),ft=i.useCallback(Ie=>{let at=Ie;b&&parseFloat(at)>parseFloat(b)&&(at=b),je(at),A?.(at),ct(null),Ye(null),nt(!1)},[b,A]);i.useCallback(Ie=>{if(jt.current||!K)return;const at=st.current;!at?.asset||!at.amount||at.asset?._source==="wallet"||M.parseUnits(S?Te:at.amount,at.asset.decimals)===0n||(jt.current=!0,ze())},[K,$,ze,S,Te]);const ut=i.useCallback(Ie=>{St({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[Ie.step]||"executing"),mt(Ie.message),Ie.txHash&&zt(Ie.txHash)},[]),Pe=i.useMemo(()=>({currentPaymentAmount:Te,destinationToken:o,embeddedWalletAddress:Ee,providerEmbeddedAddress:Be,externalWalletAddress:Ae,address:K,isNon7702:he,isPayMode:S,resolvedChainId:$,buildActionCalls:l,feeExecutionMode:d,buildSpicenetBatch:u,selectedAsset:re,needsSwap:Xe,resolvedSwap:It,exactOutputSwap:Qe,quoteAmountOut:de,resolvedTokenIn:Le}),[Te,o,Ee,Be,Ae,K,he,S,$,l,d,u,re,Xe,It,Qe,de,Le]),Tt=i.useCallback(Ie=>so({...Pe,requestTimestampMs:Ot.current??Date.now()},Ie),[Pe]),He=i.useCallback(Ie=>oo({...Pe,requestTimestampMs:Ot.current??Date.now()},Ie),[Pe]),X=i.useCallback((Ie,at,cn,xn)=>ro(Ie,at,cn,ee,xn),[ee]),ye=i.useMemo(()=>re?.asset?Xe&&Le?Le:re.asset.chainId===$?re.asset.address:Le??rn(re.asset,$)??o.address:o.address,[re,o.address,Xe,$,Le]),Ct=i.useCallback(()=>(Ot.current=Date.now(),co(dt.current)),[]),$e=i.useMemo(()=>re?.asset?h.addressesEqual(re.asset.address,o.address)&&re.asset.chainId===o.chainId:!1,[re,o.address,o.chainId]),it=$e&&(he||S),ht=it&&ke>0&&!!re?.asset,Ut=i.useMemo(()=>{if(!ht)return null;let Ie;try{Ie=M.parseUnits(Te||"0",o.decimals)}catch{return null}return{symbol:o.symbol,decimals:o.decimals,grossAmount:Ie,netAmount:Ie,totalFee:0n,gasFee:0n,spicenetFee:0n,bridgeFee:0n,gasQuoteSource:"static_zero"}},[ht,Te,o.symbol,o.decimals]),on=Rt,V=i.useMemo(()=>!(!re?.asset||ke<=0),[re,ke,ht]),Z=i.useMemo(()=>!e||Me||Se!=="idle"||!V||ht||!re?.asset?null:[S?"pay":"supply",g,re.asset.address.toLowerCase(),re.asset.chainId,re.amount,Te,o.address.toLowerCase(),o.chainId,$,Le?.toLowerCase()??"",Xe?"swap":"direct",ot?"direct-token":"routed-token",he?"non7702":"7702",$e?"source-dest":"cross-chain",Ne?"quoting":"quoted",Qe?.amountIn?.toString()??"",Qe?.amountInMax?.toString()??"",Qe?.venue??"",It?.amountOut?.toString()??"",de?.toString()??"",Ee??"",Be??"",K??""].join("|"),[e,Me,Se,V,ht,re,S,g,Te,o,$,Le,Xe,ot,he,$e,Ne,Qe,It,de,Ee,Be,K]),pe=i.useCallback(()=>ao({selectedAsset:re,isPayMode:S,parsedAmount:ke,needsSwap:Xe,exactOutputSwap:Qe,isNon7702:he,isSourceDestToken:$e,currentPaymentAmount:Te,destinationToken:o,feeExecutionMode:d,resolvedTokenIn:Le,embeddedWalletAddress:Ee,providerEmbeddedAddress:Be,resolvedChainId:$,isConnected:ne,address:K,ready:ce,authenticated:Ce,isDirect:ot,resolvedSwap:It,isQuoting:Ne,executionTokenAddress:ye,buildPayChainBatches:Tt,buildSupplyChainBatches:He,estimateGasless:ee,estimateRequiredGrossFunding:X}),[re,S,ke,Xe,Qe,he,$e,Te,o,d,Le,Ee,Be,X,Tt,ee,$,ne,K,ce,Ce,ot,It,Ne,He,ye]);i.useEffect(()=>{Wt.current=pe},[pe]);const ae=i.useCallback(Ie=>jr({asset:Ie,isPayMode:S,isNon7702:he,needsSwap:Xe,isQuoting:Ne,embeddedWalletAddress:Ee,buildSupplyChainBatches:He,estimateGasless:ee,executionTokenAddress:ye,feeExecutionMode:d}),[S,he,Xe,Ne,Ee,He,ee,ye,d]);i.useEffect(()=>{if(!e){xt(!1),nt(!1),Ye(null),Ke(null);return}if(Me||Se!=="idle"){Bt.current+=1,xt(!1);return}if(!V){Ke(null),xt(!1),nt(!1),Ye(null);return}if(ht){Ke(Ut),xt(!1),nt(!0),Ye(null);return}if(Ne){Bt.current+=1,xt(!1),nt(!1);return}if(!Z)return;let Ie=!1;const at=async()=>{const xn=++Bt.current;Ye(null),xt(!0);try{const yn=await Wt.current?.();if(Ie||Bt.current!==xn)return;yn?(Ke(yn),nt(!0)):(Ke(null),nt(!1)),Ye(null)}catch(yn){if(Ie||Bt.current!==xn)return;const ws=h.sanitizeError(yn,"Unable to calculate fees for this action.");Ke(null),nt(!1),Ye(ws)}finally{!Ie&&Bt.current===xn&&xt(!1)}},cn=window.setTimeout(()=>{at()},250);return()=>{Ie=!0,clearTimeout(cn),xt(!1)}},[e,Me,Se,V,ht,Ut,Ne,Z]);const Oe=i.useCallback(()=>(Ot.current=Date.now(),uo(dt.current)),[]);i.useEffect(()=>{!S&&Se==="success"&&De&&(ze(),T?.(De))},[S,Se,De,ze,T]),i.useEffect(()=>{if(!S||Je?.status!=="success"||jt.current||!K)return;jt.current=!0;const Ie=st.current;!Ie?.asset||Ie.asset?._source==="wallet"||ze()},[S,Je?.status,K,ze]);const Ue=i.useRef(T),Ze=i.useRef(F);i.useEffect(()=>{Ue.current=T},[T]),i.useEffect(()=>{Ze.current=F},[F]),i.useEffect(()=>{e&&(ze(),lt())},[e,ze,lt]),i.useEffect(()=>{S&&(Je?.status==="success"&&Ue.current?.(Je.txHash||""),Je?.status==="failed"&&Ze.current?.(new Error("Payment execution failed")))},[S,Je?.status]);const rt=i.useCallback(()=>{gt(!1),wt(null),we(null),jt.current=!1,ze(),lt()},[ze,lt]);dt.current={selectedAsset:re,parsedAmount:ke,currentPaymentAmount:Te,isInsufficientBalance:qe,isPayMode:S,isNon7702:he,isSourceDestToken:$e,needsSwap:Xe,exactOutputSwap:Qe,selectedIsEquivalent:Ht,resolvedTokenIn:Le,embeddedWalletAddress:Ee,providerEmbeddedAddress:Be,externalWallet:_,externalWalletAddress:Ae,activeSignerWallet:kt,activeSignerAddress:_e,address:K,isConnected:ne,ready:ce,authenticated:Ce,provider:be,resolvedChainId:$,executionTokenAddress:ye,destinationToken:o,buildActionCalls:l,feeExecutionMode:d,buildSpicenetBatch:u,onPayExecute:c,onSuccess:T,onError:F,gasless:{estimateGasless:ee,executeGasless:G,buildPayChainBatches:Tt,buildSupplyChainBatches:He,estimateRequiredGrossFunding:X,onProgress:ut},ui:{setError:ct,setStep:St,setStatusMsg:mt,setTxHash:zt,setIsExecuting:Et,setShowStatusPanel:gt,setPaymentResult:wt},refs:{spiceDepositSubmittedRef:jt,abortControllerRef:Ft}};const Dt=y?.trim(),qt=S&&C==="fixed"&&Dt!==void 0&&Dt!==""&&ke===0,Gt=S?(qt||!!re?.asset)&&ke>=0&&!Yt&&!qe&&!Me&&(qt||ht||Re)&&!Pt&&(qt||!Xe||!!Qe)&&!ue:!!re?.asset&&ke>0&&!Yt&&!qe&&!Me&&(it||Re)&&!Pt&&(te||ot||!!It&&!Ne)&&!ue,Xt=ot?m||`Your ${o.symbol} will be used directly.`:x||"Your assets will be swapped and used in a single atomic transaction.",ln=($?h.getChainConfig($):void 0)?.viemChain?.blockExplorers?.default?.url??"",gn=Jr.indexOf(Se),Fe=Me?(Xr[Se]||"EXECUTING...").toUpperCase():Se==="success"?"DONE":Yt?`MINIMUM ${fn}`:qe?"INSUFFICIENT BALANCE":p.toUpperCase(),At=i.useMemo(()=>{if(Me)return"PAYING...";if(Yt)return`MINIMUM ${fn}`;if(qe&&re?.asset)return`INSUFFICIENT ${re.asset.symbol}`;if(p)return p.toUpperCase();const Ie=ke>0?` ${Te} ${o.symbol}`:"";return Xe?`SWAP & PAY${Ie}`:`PAY${Ie}`},[Me,Yt,qe,re,p,ke,Te,o.symbol,Xe]),Kt=Se==="success"?()=>{St("idle"),we(null),zt(null),ze()}:Ct,en=Se==="success"?!1:!Gt;if(!e)return null;const vn=S?R||`Pay ${o.symbol}`:p,Un=S?E:s.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[s.jsx("span",{style:{marginTop:"3px",flexShrink:0},children:s.jsx(Us,{color:ie})}),s.jsx("p",{style:{fontSize:"12px",color:ie,margin:0,lineHeight:"1.4",fontFamily:Q},children:Xt})]});if(S){const Ie=Je&&(Je.status==="success"||Je.status==="failed")?[{asset:{symbol:re?.asset?.symbol||o.symbol,address:re?.asset?.address||""},amount:Te,txHash:Je.txHash||"",success:Je.status==="success",error:Je.status==="failed"?Je.error:void 0}]:void 0;return s.jsx(un,{isOpen:e,onClose:t,title:vn,subtitle:Un,styles:v,dark:I,footerLinkText:"Spicenet accounts \u2192",closeOnBackdropClick:n,children:s.jsxs("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[P&&s.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:s.jsx(zs,{onClick:P,color:N,fontFamily:Q})}),!qt&&s.jsx("div",{style:{marginBottom:"12px"},children:s.jsx(qn,{assets:et,selectedAsset:re??void 0,onAssetSelect:yt,onAmountChange:Jl,label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:re?.asset?Xe?Ne?"...":Qe?`~${parseFloat(M.formatUnits(Qe.amountIn,re.asset.decimals)).toFixed(6)}`:void 0:Te??void 0:void 0,dark:I,theme:q,styles:v})}),s.jsx(Dr,{variant:"pay",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:N,fontFamily:Q,textPrimary:U,textSecondary:z,cardBg:H,cardBorder:J,dk:D,dark:I,isQuoting:Ne,quoteError:_t,estimatedOutput:Lt,paymentAmount:Te,needsSwap:Xe,exactOutputSwap:Qe,adjustable:C==="adjustable",maxAmount:b,onAmountChange:ft}),V&&s.jsx(es,{fontFamily:Q,textPrimary:U,textSecondary:z,cardBg:H,cardBorder:J,resolvedDark:I,darkCardBorder:D.cardBorder,primaryColor:N,feePreview:fe,isLoading:tt,errorText:Pt,directExecutionFeeNote:ht}),on&&s.jsx(Rn,{variant:"error",palette:L,fontFamily:Q,style:{marginBottom:"12px"},children:on}),s.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:Oe,disabled:!Gt,loading:Me,dark:I,styles:{...v,button:{...v?.button,backgroundColor:N}},children:At}),Je&&We&&s.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:I?D.shell:"white",borderRadius:I?"12px":"6px",padding:"16px 0"},children:s.jsx(Qs,{type:"payment",isOpen:Je.status!=="processing",isProcessing:Me||Je.status==="processing",closeOnComplete:!1,chainName:h.getChainName($),explorerUrl:h.getExplorerUrl($,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{gt(!1),wt(null),Oe()},onNewTx:rt,onClose:()=>{gt(!1),wt(null)},onComplete:rt,results:Ie,styles:v,dark:I})})]})})}return s.jsx(un,{isOpen:e,onClose:t,title:vn,subtitle:Un,dark:I,styles:v,theme:j,closeOnBackdropClick:n,children:s.jsxs("div",{style:{padding:"24px 24px 5px 24px",position:"relative"},children:[s.jsx("div",{style:{marginBottom:"16px"},children:s.jsx(qn,{assets:et,selectedAsset:re||void 0,onAssetSelect:yt,onAmountChange:pt,disabled:Me||Se==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:q,styles:v,dark:O,resolveMaxAmount:ae,maxAmount:ve>0?Mn(ve,re?.asset.decimals??o.decimals):void 0})}),re?.asset&&!ot&&s.jsx(Dr,{variant:"supply",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:N,fontFamily:Q,textPrimary:U,textSecondary:z,cardBg:H,cardBorder:J,dark:I,isQuoting:Ne,quoteError:_t,estimatedOutput:Lt}),V&&s.jsx(es,{fontFamily:Q,textPrimary:U,textSecondary:z,cardBg:H,cardBorder:J,resolvedDark:I,darkCardBorder:D.cardBorder,primaryColor:N,feePreview:fe,isLoading:tt,errorText:Pt,directExecutionFeeNote:ht}),Se!=="idle"&&s.jsxs("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:Se==="success"?H:Se==="error"?L.errorBg:H,border:`1px solid ${Se==="success"?J:Se==="error"?L.errorBorder:J}`},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[Se==="success"?s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:s.jsx("path",{d:"M5 13l4 4L19 7",stroke:L.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):Se==="error"?s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:s.jsx("path",{d:"M18 6L6 18M6 6l12 12",stroke:L.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):s.jsx(h.Spinner,{size:14,color:N}),s.jsx("span",{style:{fontSize:"13px",fontWeight:500,color:Se==="success"?U:Se==="error"?L.errorText:U,fontFamily:Q,flex:1},children:Se==="success"?"Deposit confirmed":Se==="error"?bt||"Transaction failed":Xr[Se]||bt}),Se==="success"&&De&&s.jsx("a",{href:`${ln}/tx/${De}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:N,fontFamily:Q,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),Se==="error"&&s.jsx("button",{onClick:()=>{St("idle"),ct(null),setTimeout(Ct,50)},style:{background:"none",border:"none",fontSize:"12px",color:N,fontFamily:Q,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),gn>=0&&Se!=="success"&&Se!=="error"&&s.jsx("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${z}22`,overflow:"hidden"},children:s.jsx("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:N,transformOrigin:"left center",transform:`scaleX(${(gn+1)/Jr.length})`,transition:"transform 400ms ease"}})})]}),Rt&&Se==="idle"&&s.jsx(Rn,{variant:"error",palette:L,fontFamily:Q,style:{marginBottom:"16px"},children:Rt}),s.jsx(h.Button,{variant:"outline",fullWidth:!0,disabled:en,onClick:Kt,theme:j,dark:I,styles:{...v,button:{...v?.button,backgroundColor:N}},style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:W},children:Fe})]})})},$l=e=>s.jsx($r,{isOpen:e.isOpen,onClose:e.onClose,closeOnBackdropClick:e.closeOnBackdropClick,amountDirection:"output",destinationToken:{address:e.paymentTokenAddress,symbol:e.paymentTokenSymbol,decimals:e.paymentTokenDecimals,chainId:e.paymentChainId,logoURI:e.paymentTokenLogoURI},buildActionCalls:e.buildActionCalls,buildSpicenetBatch:e.buildSpicenetBatch,actionLabel:e.ctaLabel||"PAY",paymentAmount:e.paymentAmount,amountInputMode:e.amountInputMode,minPaymentAmount:e.minPaymentAmount,maxPaymentAmount:e.maxPaymentAmount,onAmountChange:e.onAmountChange,title:e.title,subtitle:e.subtitle,onAddFunds:e.onAddFunds,styles:e.styles,dark:e.dark,onSuccess:e.onPaymentSuccess,onError:e.onPaymentError}),_l=({label:e="Export Wallet",style:t,className:n,onExport:o,onError:r})=>{const[a,l]=i.useState(!1),[d,u]=i.useState(!1),{primaryColor:c}=h.useSpiceBrand(),f=i.useContext(h.SpiceFlowProviderContext),{isAuthenticated:p}=h.useWallet();let g=null;try{g=Ss.usePrivy()}catch{}let x=null,m=null;try{x=wo.useEmbeddedReveal(),m=wo.useDynamicContext()}catch{x=null,m=null}const y=h.getDynamicEmbeddedWallet(m),C=i.useCallback(async()=>{if(!p){r?.("User is not authenticated. Please log in first.");return}try{if(f?.provider==="dynamic"){if(!x||!y){r?.("Dynamic is not available. Ensure the app is wrapped in a DynamicContextProvider.");return}await x.initExportProcess(!1),o?.();return}if(!g){r?.("Privy is not available. Ensure the app is wrapped in a PrivyProvider.");return}await g.exportWallet(),o?.()}catch(A){const v=A instanceof Error?A.message:"Failed to export wallet";console.error("Export wallet error:",A),r?.(v)}},[y,x,p,r,o,g,f?.provider]),k=!p,b={padding:"10px 20px",borderRadius:"8px",fontFamily:'"IBM Plex Mono", monospace',fontSize:"14px",fontWeight:500,letterSpacing:"0.4px",textTransform:"uppercase",cursor:k?"not-allowed":"pointer",opacity:k?.5:1,border:"1px solid #0e0d0b",color:"#0e0d0b",backgroundColor:d?`${c}cc`:a?`${c}ee`:c,transition:"background-color 150ms ease, transform 150ms ease",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"8px",...t};return s.jsxs("button",{onClick:C,onMouseEnter:()=>l(!0),onMouseLeave:()=>{l(!1),u(!1)},onMouseDown:()=>u(!0),onMouseUp:()=>u(!1),disabled:k,className:n,style:b,children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),s.jsx("polyline",{points:"17 8 12 3 7 8"}),s.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]}),e]})};function _r(e){const t=i.useContext(h.SpiceFlowProviderContext),n=h.useEmbeddedWalletAddress(),o=e?.enabled===!1?void 0:n,r=t?.network?{network:t.network,pollIntervalMs:e?.pollIntervalMs,chainIds:e?.chainIds??t.supportedChainIds,discoverWalletBalances:e?.discoverWalletBalances}:void 0;return{...Ho(o,r),embeddedWalletAddress:n}}var ec="data:image/svg+xml,%3csvg width='11' height='11' viewBox='0 0 24 24' fill='none' stroke='black' stroke-opacity='0.5' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' xmlns='http://www.w3.org/2000/svg'%3e%3cpolyline points='17 1 21 5 17 9' /%3e%3cpath d='M3 11V9a4 4 0 0 1 4-4h14' /%3e%3cpolyline points='7 23 3 19 7 15' /%3e%3cpath d='M21 13v2a4 4 0 0 1-4 4H3' /%3e%3c/svg%3e";const tc=({appName:e,status:t,statusLabel:n,totalUsdValue:o,breakdownSubtitle:r,address:a,dk:l,dark:d=!1,showModeToggle:u,isEmbeddedMode:c=!0,onModeToggle:f})=>{const[p,g]=i.useState(!1),x=async()=>{a&&await Aa(a)&&(g(!0),setTimeout(()=>g(!1),2e3))},m=t==="active",y=n||(m?"Active":"Inactive"),C=m?"#10b981":"#9ca3af",k=s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[s.jsxs("div",{children:[s.jsx("strong",{children:"Embedded:"})," Deposit assets into ",e," account and use them here."]}),s.jsxs("div",{children:[s.jsx("strong",{children:"External:"})," Use assets from your connected wallet here."]})]});return s.jsxs("div",{children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[s.jsxs("div",{style:{fontSize:"13px",fontWeight:600,color:l.textPrimary},children:[e," Account"]}),u?s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[s.jsxs("button",{onClick:f,style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:d?l.hoverBg:"#f3f4f6",border:d?`1px solid ${l.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"11px",fontWeight:600,fontFamily:'"IBM Plex Mono", monospace',color:l.textSecondary,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease",letterSpacing:"0.02em"},children:[s.jsx("span",{children:c?"Embedded":"External"}),s.jsx("img",{src:ec,alt:"","aria-hidden":"true",style:{width:"11px",height:"11px",display:"block",...d?{filter:"invert(0.65)"}:{}}})]}),s.jsx(Do,{content:k,label:"Account mode info",textColor:d?l.textPrimary:"#f9fafb",backgroundColor:d?l.cardBg:"#111827",borderColor:d?l.cardBorder:"rgba(255,255,255,0.08)",accentColor:d?l.textSecondary:"#6b7280",children:s.jsx("img",{src:Hs,alt:"","aria-hidden":"true",style:{width:"12px",height:"12px",display:"block",...d?{filter:"invert(0.65)"}:{}}})})]}):s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:d?l.hoverBg:m?"#ecfdf5":"#f3f4f6",border:d?`1px solid ${l.cardBorder}`:m?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[s.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:C}}),s.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:d?l.textSecondary:m?"#065f46":"#6b7280"},children:y})]})]}),s.jsx("div",{style:{fontSize:"28px",fontWeight:700,color:l.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:Bn(o)}),r&&s.jsx("div",{style:{fontSize:"12px",color:l.textSecondary,marginBottom:"8px"},children:r}),a&&s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[s.jsx("span",{style:{fontSize:"12px",fontFamily:'"IBM Plex Mono", monospace',color:d?l.textSecondary:"#9ca3af"},children:Ao(a)}),s.jsx("button",{onClick:x,style:{padding:"2px 6px",fontSize:"10px",fontWeight:500,backgroundColor:"transparent",color:d?l.textSecondary:"#9ca3af",border:"none",cursor:"pointer",borderRadius:"4px",transition:"background-color 150ms ease, color 150ms ease"},title:"Copy address",children:p?"Copied":"Copy"})]})]})},nc=i.memo(tc),sc=({pendingDeposits:e,onCompleteDeposit:t,dk:n,dark:o=!1})=>e.length===0?null:s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:"Pending Deposits"}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((r,a)=>{const l=h.getChainConfig(r.chainId)?.displayName||`Chain ${r.chainId}`;return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:o?n.warningBg:"#fffbeb",border:o?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"8px"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[s.jsx("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:o?n.hoverBg:"#fde68a",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:n.warningText},children:r.tokenSymbol.charAt(0)}),s.jsxs("div",{children:[s.jsxs("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:[r.amount," ",r.tokenSymbol]}),s.jsxs("div",{style:{fontSize:"11px",color:n.warningText},children:["on ",l]})]})]}),s.jsx("button",{onClick:()=>t?.(r),style:{padding:"4px 12px",fontSize:"11px",fontWeight:600,backgroundColor:o?n.hoverBg:"#fef3c7",color:o?n.textPrimary:"#92400e",border:o?`1px solid ${n.warningBorder}`:"1px solid #fde68a",borderRadius:"9999px",cursor:"pointer",transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease"},children:"Complete"})]},`${r.tokenAddress}-${r.chainId}-${a}`)})})]}),oc=i.memo(sc),rc=e=>`${e.tokenAddress}-${e.chainId}`,ac=({spiceAssets:e,loading:t,dk:n,dark:o=!1,canDirectWithdraw:r=!1,onDirectWithdraw:a,directWithdrawState:l})=>{const d={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:n.textSecondary,marginBottom:"8px",textTransform:"uppercase"},u={backgroundColor:n.cardBg,border:o?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return t?s.jsxs("div",{children:[s.jsx("div",{style:d,children:"Idle Balances"}),[1,2].map(c=>s.jsx("div",{style:{...u,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},c))]}):e.length===0?s.jsxs("div",{children:[s.jsx("div",{style:d,children:"Idle Balances"}),s.jsx("div",{style:{...u,padding:"16px",textAlign:"center",fontSize:"13px",color:o?n.textSecondary:"#9ca3af"},children:"No assets yet. Deposit to get started."})]}):s.jsxs("div",{children:[s.jsx("div",{style:d,children:"Idle Balances"}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((c,f)=>{const p=h.getChainConfig(c.chainId),g=c.chainDisplayName||p?.displayName||`Chain ${c.chainId}`,x=c.tokenDisplaySymbol||c.tokenDisplayName||c.tokenSymbol,m=rc(c),y=r&&c.directWithdraw&&!!a,C=l?.key===m?l:null,k=C?.step==="pending";return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...u},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[c.logoURI?s.jsx("img",{src:c.logoURI,alt:c.tokenSymbol,style:{width:"24px",height:"24px",borderRadius:"50%"}}):s.jsx("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:o?n.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:n.textSecondary},children:x.charAt(0)}),s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:x}),s.jsx("div",{style:{fontSize:"11px",color:o?n.textSecondary:"#9ca3af"},children:g})]})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[s.jsxs("div",{style:{textAlign:"right"},children:[s.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:n.textPrimary},children:bn(c.balanceFormatted)}),s.jsx("div",{style:{fontSize:"11px",color:C?.step==="error"?n.errorText:o?n.textSecondary:"#9ca3af"},children:C?.step==="error"?C.message||"Withdraw failed":Bn(c.usdValue)})]}),y&&s.jsx("button",{onClick:()=>!k&&a(c),disabled:k,title:"Withdraw to external wallet",style:{padding:"6px 10px",borderRadius:"6px",border:o?`1px solid ${n.cardBorder}`:"1px solid #e5e7eb",backgroundColor:o?n.hoverBg:"#ffffff",color:n.textPrimary,fontSize:"11px",fontWeight:600,cursor:k?"default":"pointer",opacity:k?.6:1,whiteSpace:"nowrap"},children:k?"Withdrawing\u2026":"Withdraw"})]})]},`${c.tokenAddress}-${c.chainId}-${f}`)})})]})},ic=i.memo(ac),lc=({section:e,dk:t,dark:n=!1})=>{const o=r=>{switch(r){case"green":return"#10b981";case"red":return"#ef4444";default:return t.textPrimary}};return s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:t.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:e.title}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.items.map((r,a)=>s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:t.cardBg,border:n?`1px solid ${t.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[r.tokenLogoURI?s.jsx("img",{src:r.tokenLogoURI,alt:r.tokenSymbol,style:{width:"20px",height:"20px",borderRadius:"50%"}}):s.jsx("div",{style:{width:"20px",height:"20px",borderRadius:"50%",backgroundColor:n?t.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",fontWeight:600,color:t.textSecondary},children:r.tokenSymbol.charAt(0)}),s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:t.textPrimary},children:r.tokenSymbol}),s.jsx("div",{style:{fontSize:"11px",color:t.textSecondary},children:r.label})]})]}),s.jsx("div",{style:{fontSize:"13px",fontWeight:600,color:o(r.valueColor)},children:r.displayValue})]},a))})]})},cc=i.memo(lc),dc=({onDepositClick:e,onWithdrawClick:t,depositDisabled:n=!1,withdrawDisabled:o=!1,primaryColor:r="#EA4B4B",dark:a=!1})=>!e&&!t?null:s.jsxs("div",{style:{display:"flex",gap:"8px"},children:[e&&s.jsx(h.Button,{variant:"outline",onClick:e,disabled:n,dark:a,styles:{button:{backgroundColor:r}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&s.jsx(h.Button,{variant:"outline",onClick:t,disabled:o,dark:a,styles:{button:{backgroundColor:r}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),uc=i.memo(dc),pc=({appName:e,status:t,statusLabel:n,totalUsdValue:o,breakdownSubtitle:r,address:a,spiceAssets:l,spiceAssetsLoading:d,pendingDeposits:u,customSections:c,notice:f,onDepositClick:p,onWithdrawClick:g,depositDisabled:x,onCompleteDeposit:m,primaryColor:y,dk:C,dark:k=!1,showModeToggle:b,isEmbeddedMode:A,onModeToggle:v,showConnectExternalCta:w,onConnectExternalWallet:R,connectExternalError:E,showHowItWorks:P=!0,canDirectWithdraw:T,onDirectWithdraw:F,directWithdrawState:S})=>{const[j,I]=i.useState(!1);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[s.jsx(nc,{appName:e,status:t,statusLabel:n,totalUsdValue:o,breakdownSubtitle:r,address:a,dk:C,dark:k,showModeToggle:b,isEmbeddedMode:A,onModeToggle:v}),f&&s.jsx("div",{style:{padding:"10px 12px",borderRadius:"8px",backgroundColor:f.tone==="warning"?k?"rgba(245, 158, 11, 0.12)":"#fffbeb":f.tone==="success"?k?"rgba(16, 185, 129, 0.12)":"#ecfdf5":C.cardBg,border:f.tone==="warning"?k?"1px solid rgba(245, 158, 11, 0.35)":"1px solid #fde68a":f.tone==="success"?k?"1px solid rgba(16, 185, 129, 0.35)":"1px solid #a7f3d0":k?`1px solid ${C.cardBorder}`:"1px solid #e5e7eb",color:f.tone==="warning"?k?"#fbbf24":"#92400e":f.tone==="success"?k?"#34d399":"#047857":C.textSecondary,fontSize:"12px",lineHeight:1.45,fontWeight:500},children:f.message}),w&&s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[s.jsx("button",{onClick:R,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:y||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:'"Helvetica Neue", sans-serif',transition:"opacity 150ms ease"},children:"Connect External Wallet"}),E&&s.jsx("span",{style:{fontSize:"11px",color:k?C.errorText:"#b91c1c",lineHeight:1.4},children:E})]}),s.jsx("div",{style:{height:"1px",backgroundColor:k?"#2d2d2d":"#e5e7eb"}}),s.jsx(uc,{onDepositClick:p,onWithdrawClick:g,depositDisabled:x,primaryColor:y,dark:k}),P&&s.jsxs("div",{children:[s.jsxs("button",{onClick:()=>I(!j),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:C.cardBg,border:k?`1px solid ${C.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:C.textSecondary,fontSize:"12px",fontWeight:500},children:[s.jsx("span",{children:"How It Works"}),s.jsx("span",{style:{transform:j?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),j&&s.jsxs("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:k?C.cardBg:"#f0fdf4",border:k?`1px solid ${C.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:k?C.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),s.jsx(oc,{pendingDeposits:u,onCompleteDeposit:m,dk:C,dark:k}),s.jsx(ic,{spiceAssets:l,loading:d,dk:C,dark:k,canDirectWithdraw:T,onDirectWithdraw:F,directWithdrawState:S}),c.map((N,D)=>s.jsx(cc,{section:N,dk:C,dark:k},D))]})},fc=i.memo(pc);function hc(e,t,n){const o=t-n.gasBridge-n.spicenetFee;if(o<=0n)throw new Error("Balance is too small to cover the network fee.");const r=[{recipient:e,amount:o}];return n.gasBridge>0n&&r.push({recipient:B.SPICE_GAS_FEE_RECIPIENT,amount:n.gasBridge}),n.spicenetFee>0n&&r.push({recipient:B.SPICE_PLATFORM_FEE_RECIPIENT,amount:n.spicenetFee}),r}function mc(e,t,n){if(e===t)return!0;const o=e>t?e:t;return o===0n?!1:(e>t?e-t:t-e)*10000n<=o*n}const gc=new Set([B.SPICE_GAS_FEE_RECIPIENT,B.SPICE_PLATFORM_FEE_RECIPIENT].map(e=>e.toLowerCase()));function xc(e,t){return!e||e.length!==t.length?!1:e.every((n,o)=>{const r=t[o];return n.recipient.toLowerCase()!==r.recipient.toLowerCase()?!1:gc.has(n.recipient.toLowerCase())?mc(n.amount,r.amount,100n):!0})}function ea(e,t,n){return{chainId:e,domain:"evm",tokenTransfers:[],calls:n.filter(o=>o.amount>0n).map(o=>({to:t,value:0n,data:M.encodeFunctionData({abi:h.P,functionName:"transfer",args:[o.recipient,o.amount]})}))}}function yc(e,t){const n=e.intents.flatMap(r=>r.batches).filter(r=>$t(r).totalFee>0n),o=n.filter(r=>r.chainId===t);return(o.length>0?o:n)[0]??null}function Cc(e,t,n,o){const r=yc(o,e),{gasFee:a,bridgeFee:l,spicenetFee:d}=r?$t(r):{gasFee:0n,bridgeFee:0n,spicenetFee:0n};return hc(t,n,{gasBridge:a+l,spicenetFee:d})}function bc(){const{executeGasless:e}=Pn(),t=h.useEmbeddedWalletAddress(),{embeddedAddress:n}=h.useProviderWallets(),o=t||n;return{withdraw:i.useCallback(async({tokenAddress:r,chainId:a,balance:l,recipient:d,onProgress:u})=>{const c=r,f=d;if(l<=0n)throw new Error("Nothing to withdraw.");const p=[ea(a,c,[{recipient:f,amount:l}])];let g=null;return e(p,c,0n,u,void 0,{useCustomTransfers:!0,userOverride:o,adjustBatchesForEstimate:({feeEstimate:x})=>{const m=Cc(a,f,l,x);return xc(g,m)?null:(g=m,[ea(a,c,m)])}})},[e,o])}}function wc(e){return!!e.embeddedAddress&&!!e.externalAddress}const go=380,jn=8,kc=[];function ta(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function vc(e,t){const n=new Map;Object.entries(t).forEach(([r,a])=>{if(!Number.isFinite(a)||a<=0)return;n.set(r,a),n.set(r.toUpperCase(),a);const l=ta(r);l&&n.set(l,a)});const o=[e.symbol,e.displaySymbol,e.receiptTokenName,e.name,e.displayName];for(const r of o){if(!r)continue;const a=n.get(r)??n.get(r.toUpperCase());if(a!==void 0)return a;const l=ta(r);if(!l)continue;const d=n.get(l);if(d!==void 0)return d}return 0}const Sc=({appName:e="Spice",status:t="active",statusLabel:n,customSections:o=kc,extraAssets:r=[],tokenPrices:a={},breakdownLabels:l=[],notice:d,styles:u,dark:c=!1,onDepositSuccess:f,onDepositClick:p,onWithdrawClick:g,onCompleteDeposit:x,showModeToggle:m=!1,defaultMode:y})=>{const C=i.useContext(h.SpiceFlowProviderContext),k=C?.mode!=="7702",b=!!C?.isWhitelistGateActive,A=!!C?.isWhitelistConfigured&&C?.isUserWhitelisted!==!0,v=i.useRef(!1);i.useEffect(()=>{if(!v.current){if(h.hasStoredSpiceFlowMode()){v.current=!0;return}y&&C?.setMode&&(C.setMode(y==="non7702"?"ondemand":"7702"),v.current=!0)}},[C,y]);const[w,R]=i.useState(!1),[E,P]=i.useState(null),[T,F]=i.useState({top:0,bottom:0,left:0,placement:"below"}),S=i.useRef(null),j=i.useRef(null),{address:I,isConnected:N}=h.useWallet(),D=h.useEmbeddedWalletAddress(),{externalAddress:L,embeddedAddress:Q}=h.useProviderWallets(),{dark:W,primaryColor:O,dk:H}=h.useSpiceBrand(u,c),J=k&&!L,U=!k||J,z=U?D||Q:I,ie=i.useMemo(()=>C?.supportedChainIds??B.getChainIdsByNetwork("mainnet"),[C?.supportedChainIds]),{assets:q,loading:$}=Vn({address:z,supportedChains:ie,enabled:!!z&&U,refetchInterval:3e4}),le=i.useMemo(()=>{const we=U?q.map(je=>{const Me=je.balanceUsd||0,Et=Number.isFinite(je.balanceFormatted)?je.balanceFormatted:0,Rt=Me>0?Me:vc(je,a)*Et;return{tokenAddress:je.address,tokenSymbol:je.symbol,tokenDisplaySymbol:Ds(je),tokenDisplayName:Ma(je),tokenDecimals:je.decimals,chainId:je.chainId,chainDisplayName:Ns(je),balance:je.balance.toString(),balanceFormatted:je.balanceFormatted,usdValue:Rt,logoURI:je.logoURI}}):[],Ge=J?[]:r;return[...we,...Ge].filter(je=>je.balanceFormatted>0)},[U,J,q,a,r]),he=i.useMemo(()=>le.reduce((we,Ge)=>we+Ge.usdValue,0),[le]),{pendingDeposits:me}=_r({chainIds:ie,enabled:!!I,discoverWalletBalances:!0}),ue=i.useMemo(()=>o.reduce((we,Ge)=>we+Ge.totalValue,0),[o]),ge=he+ue,Y=i.useMemo(()=>{const we=[];he>0&&we.push(`${Bn(he)} idle`);for(const Ge of o){const je=l.find(Me=>Me.sectionTitle===Ge.title)?.label||Ge.title.toLowerCase();we.push(`${Bn(Ge.totalValue)} ${je}`)}return we.join(" \xB7 ")},[he,o,l]),oe=i.useCallback(we=>{x?x(we):P(we)},[x]),K=i.useCallback(()=>{P(null)},[]),ne=i.useCallback(()=>{P(null),f?.()},[f]),ce=i.useCallback(()=>{if(!S.current)return;const we=S.current.getBoundingClientRect(),Ge=window.innerHeight-we.bottom-jn,je=we.top-jn,Me=Ge>=400||Ge>=je?"below":"above",Et=Math.max(jn,Math.min(we.right-go,window.innerWidth-go-jn)),Rt=Me==="below"?we.bottom+jn:we.top-jn,ct=Me==="above"?window.innerHeight-Rt:0;F({top:Rt,bottom:ct,left:Et,placement:Me})},[]);i.useLayoutEffect(()=>{w&&ce()},[w,ce]),i.useEffect(()=>{if(!w)return;const we=Me=>{S.current&&!S.current.contains(Me.target)&&j.current&&!j.current.contains(Me.target)&&R(!1)},Ge=Me=>{Me.key==="Escape"&&R(!1)},je=()=>ce();return document.addEventListener("mousedown",we),document.addEventListener("keydown",Ge),window.addEventListener("scroll",je,{passive:!0}),window.addEventListener("resize",ce),()=>{document.removeEventListener("mousedown",we),document.removeEventListener("keydown",Ge),window.removeEventListener("scroll",je),window.removeEventListener("resize",ce)}},[w,ce]);const Ce=U?D||Q||I:L||I,be=i.useCallback(()=>{C?.setMode&&C.setMode(U?"ondemand":"7702")},[C,U]),[G,ee]=i.useState(null);let _=null;try{_=Ss.useConnectWallet({onSuccess:()=>ee(null),onError:we=>ee(h.sanitizeError(we,"Failed to connect wallet."))}).connectWallet}catch{_=null}const Ae=i.useCallback(()=>{_&&(R(!1),ee(null),_({walletChainType:"ethereum-only"}))},[_]),Be=!L&&!!_,kt=i.useCallback(()=>{R(!1),p?.()},[p]),_e=i.useCallback(()=>{R(!1),g?.()},[g]),vt=i.useCallback(we=>{R(!1),oe(we)},[oe]),{withdraw:Ve}=bc(),[xe,Ee]=i.useState(null),ze=wc({embeddedAddress:D||Q,externalAddress:L}),lt=i.useCallback(async we=>{if(!L)return;const Ge=`${we.tokenAddress}-${we.chainId}`;Ee({key:Ge,step:"pending"});try{await Ve({tokenAddress:we.tokenAddress,chainId:we.chainId,balance:BigInt(we.balance),recipient:L}),Ee(null)}catch(je){Ee({key:Ge,step:"error",message:h.sanitizeError(je,"Withdraw failed")})}},[Ve,L]);if(typeof window>"u")return null;const et=s.jsxs("button",{ref:S,onClick:()=>R(!w),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:W?H.hoverBg:"#ffffff",border:W?`1px solid ${H.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:'"Helvetica Neue", sans-serif',color:W?H.textPrimary:"#111827",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",boxShadow:W?"none":"0 1px 2px rgba(0,0,0,0.05)"},children:[s.jsxs("span",{children:[e," Account"]}),N&&s.jsxs("span",{style:{color:W?H.textSecondary:"#6b7280"},children:["\xB7 ",Bn(ge)]}),s.jsx("span",{style:{fontSize:"10px",color:W?H.textSecondary:"#9ca3af",transform:w?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),re=w?zn.createPortal(s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:Cn.popover},onClick:()=>R(!1)}),s.jsx("div",{ref:j,style:{position:"fixed",top:T.placement==="below"?`${T.top}px`:"auto",bottom:T.placement==="above"?`${T.bottom}px`:"auto",left:`${T.left}px`,width:`${go}px`,maxWidth:`calc(100vw - ${jn*2}px)`,maxHeight:"80vh",backgroundColor:W?H.shell:"#ffffff",border:W?`1px solid ${H.cardBorder}`:"1px solid #e5e7eb",borderRadius:"12px",boxShadow:W?"0 10px 40px rgba(0, 0, 0, 0.5)":"0 10px 40px rgba(0, 0, 0, 0.12)",zIndex:Cn.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${Nt.out}`},children:s.jsx(fc,{appName:e,status:t,statusLabel:n,totalUsdValue:ge,breakdownSubtitle:Y,address:U?Ce:I,spiceAssets:le,spiceAssetsLoading:$,pendingDeposits:me,customSections:o,notice:d,onDepositClick:p?kt:void 0,onWithdrawClick:g?_e:void 0,depositDisabled:A,onCompleteDeposit:vt,primaryColor:O,dk:H,dark:W,showModeToggle:m,isEmbeddedMode:U,onModeToggle:be,showConnectExternalCta:Be,onConnectExternalWallet:Ae,connectExternalError:G,showHowItWorks:!b,canDirectWithdraw:ze,onDirectWithdraw:lt,directWithdrawState:xe})}),s.jsx("style",{children:`
|
|
104
104
|
@keyframes accountDisplayFadeIn {
|
|
105
105
|
from { opacity: 0; transform: translateY(-4px); }
|
|
106
106
|
to { opacity: 1; transform: translateY(0); }
|
|
107
107
|
}
|
|
108
|
-
`})]}),document.body):null;return s.jsxs(s.Fragment,{children:[et,re,E&&zn.createPortal(s.jsx(Lo,{isOpen:!0,onClose:K,supportedChains:[E.chainId],escrowOnly:!0,escrowTokenAddress:E.tokenAddress,escrowAmount:E.amount,escrowTokenDecimals:E.tokenDecimals,escrowTokenSymbol:E.tokenSymbol,styles:u,onDepositSuccess:ne}),document.body)]})},na=class yo extends i.Component{constructor(t){super(t),this.handleRetry=()=>{this.state.retryCount>=yo.MAX_RETRIES||this.setState(n=>({hasError:!1,error:null,retryCount:n.retryCount+1}))},this.state={hasError:!1,error:null,retryCount:0}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error(`[SdkErrorBoundary] ${this.props.componentName||"SDK component"} failed:`,{message:t.message,componentStack:n.componentStack})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const t={display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"24px",borderRadius:"8px",border:"1px solid rgba(239, 68, 68, 0.2)",backgroundColor:this.props.dark?"rgba(239, 68, 68, 0.08)":"rgba(239, 68, 68, 0.05)",gap:"12px"},n={fontSize:"14px",color:"#f87171",margin:0},o={fontSize:"12px",color:"#888",maxWidth:"280px",textAlign:"center",overflow:"hidden",display:"-webkit-box",WebkitLineClamp:3,WebkitBoxOrient:"vertical",margin:0},r={padding:"8px 16px",fontSize:"12px",borderRadius:"6px",backgroundColor:this.props.dark?"#2a2a2a":"#f3f4f6",color:this.props.dark?"#888":"#374151",border:this.props.dark?"1px solid #3a3a3a":"1px solid #d1d5db",cursor:"pointer",transition:"background-color 150ms ease"},a={fontSize:"12px",color:"#888",margin:0},l=yo.MAX_RETRIES-this.state.retryCount;return s.jsxs("div",{style:t,children:[s.jsxs("p",{style:n,children:[this.props.componentName||"Component"," failed to load"]}),this.state.error&&s.jsx("p",{style:o,children:this.state.error.message}),l>0?s.jsxs("button",{onClick:this.handleRetry,style:r,onMouseEnter:d=>{d.target.style.backgroundColor=this.props.dark?"#333":"#e5e7eb"},onMouseLeave:d=>{d.target.style.backgroundColor=this.props.dark?"#2a2a2a":"#f3f4f6"},children:["Try again (",l," left)"]}):s.jsx("p",{style:a,children:"Please refresh the page to try again"})]})}return this.props.children}};na.MAX_RETRIES=3;let Sc=na;const xo="spiceflow:wallet-notice:seen",Ic=()=>{if(typeof window>"u")return null;try{return window.localStorage.getItem(xo)}catch{return null}},Ac=e=>{if(!(typeof window>"u"))try{window.localStorage.setItem(xo,e)}catch{}},Ec=()=>{if(!(typeof window>"u"))try{window.localStorage.removeItem(xo)}catch{}},jc=()=>{const e=i.useContext(h.SpiceFlowProviderContext),{externalAddress:t}=h.useProviderWallets(),[n,o]=i.useState(!1),r=i.useRef(null),a=t?t.toLowerCase():null,l=e?.isWhitelistConfigured??!1,d=e?.isWhitelistChecking??!1,u=e?.isUserWhitelisted??null;i.useEffect(()=>{if(!a){r.current&&(Ec(),o(!1)),r.current=null;return}r.current=a,!(!l||d||u===null)&&Ic()!==a&&(Ac(a),o(!0))},[a,l,d,u]);const c=i.useCallback(()=>o(!1),[]);return{isOpen:n,close:c,externalAddress:t,whitelisted:u===!0}},Fc=(e,t)=>({title:e.whitelisted?"You're whitelisted":"Wallet connected",body:e.whitelisted?s.jsxs(s.Fragment,{children:["The"," ",s.jsx("span",{style:{fontWeight:600,color:t.accentText},children:e.shortAddress})," ","or the linked Spicenet portal wallet is whitelisted. Feel free to try to use ",e.appName," with ",t.tokens,", cross-chain, supported chains"," ",t.chains.join(", "),"."]}):s.jsxs(s.Fragment,{children:["The"," ",s.jsx("span",{style:{fontWeight:600,color:t.accentText},children:e.shortAddress})," ","or the linked Spicenet portal is not whitelisted. You can use"," ",e.appName," normally as you always have."]})}),Bc=({isOpen:e,whitelisted:t,address:n,onClose:o,appName:r,tokens:a="stablecoins",chains:l=["Base","Arbitrum","Citrea"],renderContent:d,styles:u,dark:c})=>{const{appName:f,dark:p,palette:g,fontFamily:x}=h.useSpiceBrand(u,c),m=c??p,y=r??f,C=i.useId(),k=i.useRef(null),b=i.useRef(o);i.useEffect(()=>{b.current=o},[o]);const[A,v]=i.useState(!1),[w,R]=i.useState(!1);if(i.useEffect(()=>{if(e){v(!0);return}if(!A)return;R(!1);const N=setTimeout(()=>v(!1),300);return()=>clearTimeout(N)},[e,A]),i.useEffect(()=>{if(!A)return;const N=document.body.style.overflow;document.body.style.overflow="hidden";const D=requestAnimationFrame(()=>{requestAnimationFrame(()=>R(!0))}),L=Q=>{Q.key==="Escape"&&(Q.stopPropagation(),b.current())};return document.addEventListener("keydown",L),()=>{cancelAnimationFrame(D),document.removeEventListener("keydown",L),document.body.style.overflow=N}},[A]),!A)return null;const E=()=>b.current(),P=t?g.successBg:g.warningBg,T=t?g.successBorder:g.warningBorder,F=t?g.successText:g.warningText,S=n?Ao(n):"your wallet",j={whitelisted:t,address:n,shortAddress:S,appName:y},I=d?d(j):Fc(j,{tokens:a,chains:l,accentText:F});return s.jsx("div",{onMouseDown:N=>{N.target===N.currentTarget&&E()},style:{position:"fixed",inset:0,backgroundColor:m?"rgba(0,0,0,0.72)":"rgba(0,0,0,0.5)",display:"flex",alignItems:"flex-end",justifyContent:"center",zIndex:Cn.modal,opacity:w?1:0,transition:`opacity ${Vt.normal} ${Nt.out}`},children:s.jsxs("div",{ref:k,role:"dialog","aria-modal":"true","aria-labelledby":C,style:{backgroundColor:g.shell,borderTop:`1px solid ${g.shellInnerBorder}`,borderRadius:"16px 16px 0 0",width:"100%",maxWidth:"522px",boxSizing:"border-box",boxShadow:"0 -16px 48px rgba(0, 0, 0, 0.4)",padding:"24px 24px 16px 24px",transform:w?"translateY(0)":"translateY(100%)",transition:`transform ${Vt.slow} ${Nt.out}`,fontFamily:x},children:[s.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"12px"},children:[s.jsx("h2",{id:C,style:{fontSize:"20px",fontWeight:700,color:g.textPrimary,margin:0,lineHeight:1.15},children:I.title}),s.jsx("button",{type:"button",onClick:E,"aria-label":"Close notice",style:{color:g.textSecondary,backgroundColor:"transparent",border:"none",cursor:"pointer",padding:"4px",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:s.jsx(In,{size:22,strokeWidth:2.4})})]}),s.jsx("div",{style:{marginTop:"16px",backgroundColor:P,border:`1px solid ${T}`,borderRadius:"10px",padding:"14px 16px",color:g.textPrimary,fontSize:"14px",lineHeight:1.5},children:I.body}),s.jsx("div",{style:{marginTop:"16px"},children:s.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:E,styles:u,dark:m,children:"Got it"})}),s.jsx("div",{style:{marginTop:"14px",display:"flex",justifyContent:"center"},children:s.jsx("img",{src:Jn,alt:"","aria-hidden":"true",width:108,height:22,decoding:"async",style:{width:"108px",height:"22px",opacity:m?.85:1,filter:m?"brightness(0) invert(1)":"none",display:"block"}})})]})})},Tc=({styles:e,dark:t,appName:n,tokens:o,chains:r,renderContent:a,onClose:l})=>{const{isOpen:d,close:u,externalAddress:c,whitelisted:f}=jc(),p=i.useCallback(()=>{u(),l?.()},[u,l]);return s.jsx(Bc,{isOpen:d,whitelisted:f,address:c,onClose:p,appName:n,tokens:o,chains:r,renderContent:a,styles:e,dark:t})},Mc=()=>{const[e,t]=i.useState("0"),[n,o]=i.useState(null);return{assetAmount:e,setAssetAmount:t,selectedAsset:n,setSelectedAsset:o}};function Rc(e,t=0){const[n,o]=i.useState(t),r=e[n]??e[0],a=i.useMemo(()=>r?BigInt(Math.round(r.months*30*24*3600)):0n,[r?.months]);return{selectedDurationIdx:n,setSelectedDurationIdx:o,selectedDuration:r,durationSeconds:a}}function Dc(){const{actions:e,isReady:t,isAuthenticated:n}=h.useWallet(),o=h.useEmbeddedWalletAddress(),r=i.useRef(!1),a=i.useRef(0),l=i.useRef(null),d=i.useRef(e),[u,c]=i.useState(0);d.current=e,i.useEffect(()=>{r.current=!1,a.current=0,l.current&&(clearTimeout(l.current),l.current=null)},[o]),i.useEffect(()=>{if(!o||!t||!n||r.current)return;r.current=!0;let f=!1;return(async()=>{await new Promise(p=>setTimeout(p,2e3));try{await h.ensureSmartWallet(o,d.current.signMessage),a.current=0}catch(p){console.warn("[SmartWallet] Registration failed:",p),r.current=!1,!f&&a.current<3&&(a.current+=1,l.current=setTimeout(()=>{c(g=>g+1)},5e3))}})(),()=>{f=!0,l.current&&(clearTimeout(l.current),l.current=null)}},[o,t,n,u])}function xs(e){const{destinationToken:t,recipient:n,buildActionCalls:o,buildSpicenetBatch:r,amountMode:a,amount:l,sourceChains:d,supportedSourceAssets:u,feeExecutionMode:c="user-transfer",enabled:f=!0,onSuccess:p,onError:g}=e,x=a==="exact-output"?"output":"input",m=x==="output",y=t.chainId,C=i.useContext(h.SpiceFlowProviderContext),k=(C?.mode||"7702")!=="7702",b=!!C?.isWhitelistGateActive,A=i.useMemo(()=>d??C?.supportedChainIds??[],[d,C?.supportedChainIds]),v=i.useMemo(()=>b?[]:u,[b,u]),w=h.useWallet(),{address:R,isConnected:E,isReady:P,isAuthenticated:T,provider:F}=w,{executeGasless:S,estimateGasless:j}=Pn(),{externalWallet:I,externalAddress:N,embeddedAddress:D}=h.useProviderWallets(),L=h.useEmbeddedWalletAddress()||D,{displayAssets:Q,filteredSpiceAssets:W,embeddedWalletAddress:O,refreshSpiceAssets:H,refreshWalletAssets:J}=po({destinationToken:t,supportedSourceAssets:v,sourceChains:A,enabled:f&&(k?!!N:!!L)}),U=Q,[z,ie]=i.useState(null),[q,$]=i.useState(!1),[le,he]=i.useState(null),[me,ue]=i.useState("idle"),[ge,Y]=i.useState(""),[oe,K]=i.useState(null),[ne,ce]=i.useState(null),[,Ce]=i.useState(!1),[be,G]=i.useState(null),[ee,_]=i.useState(!1),[Ae,Be]=i.useState(!1),[kt,_e]=i.useState(null),vt=i.useRef(z),Ve=i.useRef(!1),xe=i.useRef(null),Ee=i.useRef(0),ze=i.useRef(null),lt=i.useRef(null);i.useEffect(()=>{vt.current=z},[z]);const et=m?l||"0":z?.amount||"0";i.useEffect(()=>{f||(ie(null),he(null),$(!1),ue("idle"),Y(""),K(null),ce(null),Ce(!1),G(null),_(!1),Be(!1),_e(null),Ve.current=!1,xe.current&&(xe.current.abort(),xe.current=null))},[f]),i.useEffect(()=>{m||ie(de=>de&&de.amount!==l?{...de,amount:l}:de)},[l,m]);const re=i.useCallback(de=>{ie(de),he(null),_e(null),Be(!1)},[]),we=i.useCallback(de=>{ie(Le=>({asset:de,amount:Le?.asset?.address===de.address&&Le?.asset?.chainId===de.chainId&&Le.amount||(m?"":l)})),he(null),_e(null),Be(!1)},[l,m]),Ge=O||D||R,{isQuoting:je,quoteError:Me,estimatedOutput:Et,estimatedInput:Rt,resolvedSwap:ct,exactOutputSwap:Se,quoteAmountOut:St,resolvedTokenIn:bt,isDirect:mt,needsSwap:De,selectedIsEquivalent:zt}=mo({direction:x,selectedAsset:z,destinationToken:t,chainId:y,recipient:Ge,paymentAmount:et}),We=m?parseFloat(et):parseFloat(z?.amount||"")||0,gt=z?.asset?._source==="wallet",Je=!!z?.asset&>&&z.asset.chainId!==y,wt=gt&&z?.asset?._fundingWallet==="external",fe=z?.asset?._source!=="spice"&&(k||wt),Ke=i.useMemo(()=>z?.asset?W.find(de=>h.addressesEqual(de.address,z.asset.address))?.balanceFormatted??0:0,[z,W]),tt=gt?z?.asset.balanceFormatted??0:Ke||(z?.asset.balanceFormatted??0),xt=i.useMemo(()=>{if(!z?.asset)return!1;if(m)return be?nn(be.grossAmount,be.decimals,z.asset.decimals)>z.asset.balance:zt||mt?We>z.asset.balanceFormatted:Se?parseFloat(M.formatUnits(Se.amountInMax,z.asset.decimals))>z.asset.balanceFormatted:!1;if(be){const de=nn(be.grossAmount,be.decimals,z.asset.decimals);return gt?de>z.asset.balance:parseFloat(M.formatUnits(de,z.asset.decimals))>tt}return We>tt},[z,m,be,zt,We,Se,tt,gt,mt]),Re=i.useCallback(de=>{ue({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[de.step]||"executing"),Y(de.message),de.txHash&&K(de.txHash)},[]),nt=i.useMemo(()=>({currentPaymentAmount:et,destinationToken:t,embeddedWalletAddress:O,providerEmbeddedAddress:D,externalWalletAddress:N,address:R,recipient:n,isNon7702:fe,isPayMode:m,resolvedChainId:y,buildActionCalls:o,feeExecutionMode:c,buildSpicenetBatch:r,selectedAsset:z,needsSwap:De,resolvedSwap:ct,exactOutputSwap:Se,quoteAmountOut:St,resolvedTokenIn:bt}),[et,t,O,D,N,R,n,fe,m,y,o,c,r,z,De,ct,Se,St,bt]),Pt=i.useCallback(de=>so(nt,de),[nt]),Ye=i.useCallback(de=>oo(nt,de),[nt]),st=i.useCallback((de,Le,ot,Xe)=>ro(de,Le,ot,j,Xe),[j]),jt=i.useMemo(()=>z?.asset?De&&bt?bt:z.asset.chainId===y?z.asset.address:bt??rn(z.asset,y)??t.address:t.address,[z,t.address,De,y,bt]),Ft=i.useMemo(()=>z?.asset?h.addressesEqual(z.asset.address,t.address)&&z.asset.chainId===t.chainId:!1,[z,t.address,t.chainId]),Ot=fe&&Ft,Bt=Ot&&We>0&&!!z?.asset,Wt=i.useMemo(()=>!(!z?.asset||We<=0),[z,We]),dt=i.useMemo(()=>!f||q||me!=="idle"||!Wt||Bt||!z?.asset?null:[m?"pay":"supply",x,z.asset.address.toLowerCase(),z.asset.chainId,z.amount,et,t.address.toLowerCase(),t.chainId,y,bt?.toLowerCase()??"",De?"swap":"direct",mt?"direct-token":"routed-token",fe?"non7702":"7702",Ft?"source-dest":"cross-chain",je?"quoting":"quoted",n?.toLowerCase()??"",Se?.amountIn?.toString()??"",Se?.amountInMax?.toString()??"",Se?.venue??"",ct?.amountOut?.toString()??"",St?.toString()??"",O??"",D??"",R??""].join("|"),[f,q,me,Wt,Bt,z,m,x,et,t,y,bt,De,mt,fe,Ft,je,n,Se,ct,St,O,D,R]),Te=i.useCallback(()=>ao({selectedAsset:z,isPayMode:m,parsedAmount:We,needsSwap:De,exactOutputSwap:Se,isNon7702:fe,isSourceDestToken:Ft,currentPaymentAmount:et,destinationToken:t,feeExecutionMode:c,resolvedTokenIn:bt,embeddedWalletAddress:O,providerEmbeddedAddress:D,resolvedChainId:y,isConnected:E,address:R,ready:P,authenticated:T,isDirect:mt,resolvedSwap:ct,isQuoting:je,executionTokenAddress:jt,buildPayChainBatches:Pt,buildSupplyChainBatches:Ye,estimateGasless:j,estimateRequiredGrossFunding:st}),[z,m,We,De,Se,fe,Ft,et,t,c,bt,O,D,st,Pt,j,y,E,R,P,T,mt,ct,je,Ye,jt,n]);i.useEffect(()=>{ze.current=Te},[Te]),i.useEffect(()=>{if(!f){_(!1),Be(!1),_e(null),G(null);return}if(q||me!=="idle"){Ee.current+=1,_(!1);return}if(!Wt){G(null),_(!1),Be(!1),_e(null);return}if(Bt){G(null),_(!1),Be(!0),_e(null);return}if(je){Ee.current+=1,_(!1),Be(!1);return}if(!dt)return;let de=!1;const Le=async()=>{const Xe=++Ee.current;_e(null),_(!0);try{const Ht=await ze.current?.();if(de||Ee.current!==Xe)return;Ht?(G(Ht),Be(!0)):(G(null),Be(!1)),_e(null)}catch(Ht){if(de||Ee.current!==Xe)return;const ke=h.sanitizeError(Ht,"Unable to calculate fees for this action.");G(null),Be(!1),_e(ke)}finally{!de&&Ee.current===Xe&&_(!1)}},ot=window.setTimeout(()=>{Le()},250);return()=>{de=!0,clearTimeout(ot),_(!1)}},[f,q,me,Wt,Bt,je,dt]),i.useEffect(()=>{!m&&me==="success"&&oe&&(H(),p?.(oe))},[m,me,oe,H,p]),i.useEffect(()=>{if(!m||ne?.status!=="success"||Ve.current||!R)return;Ve.current=!0;const de=vt.current;!de?.asset||de.asset?._source==="wallet"||H()},[m,ne?.status,R,H]);const Mt=i.useRef(p),Ne=i.useRef(g);i.useEffect(()=>{Mt.current=p},[p]),i.useEffect(()=>{Ne.current=g},[g]),i.useEffect(()=>{m&&(ne?.status==="success"&&Mt.current?.(ne.txHash||""),ne?.status==="failed"&&Ne.current?.(new Error("Payment execution failed")))},[m,ne?.status]),i.useEffect(()=>{f&&(H(),J())},[f,H,J]),lt.current={selectedAsset:z,parsedAmount:We,currentPaymentAmount:et,isInsufficientBalance:xt,isPayMode:m,isNon7702:fe,isSourceDestToken:Ft,needsSwap:De,exactOutputSwap:Se,selectedIsEquivalent:zt,resolvedTokenIn:bt,embeddedWalletAddress:O,providerEmbeddedAddress:D,externalWallet:I,externalWalletAddress:N,address:R,isConnected:E,ready:P,authenticated:T,provider:F,resolvedChainId:y,executionTokenAddress:jt,destinationToken:t,recipient:n,buildActionCalls:o,feeExecutionMode:c,buildSpicenetBatch:r,onError:g,gasless:{estimateGasless:j,executeGasless:S,buildPayChainBatches:Pt,buildSupplyChainBatches:Ye,estimateRequiredGrossFunding:st,onProgress:Re},ui:{setError:he,setStep:ue,setStatusMsg:Y,setTxHash:K,setIsExecuting:$,setShowStatusPanel:Ce,setPaymentResult:ce},refs:{spiceDepositSubmittedRef:Ve,abortControllerRef:xe}};const _t=i.useCallback(async()=>{const de=lt.current;de&&(de.isPayMode?await uo(de):await co(de))},[]),Lt=m&&We===0,It=m?!!z?.asset&&We>=0&&!xt&&!q&&(Lt||Bt||Ae)&&!kt&&(Lt||!De||!!Se):!!z?.asset&&We>0&&!xt&&!q&&(Ot||Ae)&&!kt&&(Je||mt||!!ct&&!je),Qe=i.useCallback(()=>{H(),J()},[H,J]);return{sources:U,selectedAsset:z,setSelectedAsset:re,selectAsset:we,quote:{isQuoting:je,error:Me,estimatedInput:Rt,estimatedOutput:Et,isDirect:mt,needsSwap:De},feePreview:be,isFeePreviewLoading:ee,feePreviewError:kt,canSubmit:It,execute:_t,isExecuting:q,step:me,statusMsg:ge,txHash:oe,paymentResult:ne,refreshAssets:Qe}}function Nc(e){return xs({...e,amountMode:"exact-input"})}function Pc(e){return xs({...e,amountMode:"exact-output"})}function Wc(e){return xs({...e,amountMode:"exact-input"})}const ys=1500,sa="spiceflow-75f053db-70ab-4f37-83cc-abf68cb5b70d",Uc={1:{chainId:1,domain:0,network:"mainnet"},42161:{chainId:42161,domain:3,network:"mainnet"},8453:{chainId:8453,domain:6,network:"mainnet"},11155111:{chainId:11155111,domain:0,network:"testnet"},421614:{chainId:421614,domain:3,network:"testnet"},84532:{chainId:84532,domain:6,network:"testnet"}};function oa(e,t,n){return(e*t+n-1n)/n}function ra(e,t=ys){return oa(e,BigInt(1e4+t),10000n)}function aa(e,t){return`evm:${e}:${M.getAddress(t).toLowerCase()}`}function ia(e){return Uc[e]??null}function zc(e){return e==="testnet"?"https://iris-api-sandbox.circle.com":"https://iris-api.circle.com"}function Oc(e){const t=typeof e=="number"?e.toString():typeof e=="string"?e:"0",[n,o=""]=t.trim().split("."),r=BigInt(n||"0"),a=BigInt((o+"00").slice(0,2)||"0");return r*100n+a}function Lc(e,t){const n=Oc(t);return oa(e,n,1000000n)}async function Hc(e){const t=e.transferMode??"fast",n=ia(e.sourceChainId),o=ia(e.destinationChainId);if(!n||!o||n.network!==o.network)throw new Error(`Unsupported CCTP route ${e.sourceChainId} -> ${e.destinationChainId}`);let r=0n;const a=t==="fast"?1e3:2e3;if(t==="fast"){const d=e.fetchImpl??fetch,u=`${zc(n.network)}/v2/burn/USDC/fees/${n.domain}/${o.domain}`,c=await d(u);if(!c.ok)throw new Error(`CCTP fee quote failed: ${c.status} ${c.statusText}`);const f=await c.json(),p=Array.isArray(f)?f:Array.isArray(f?.data)?f.data:[],g=p.find(x=>String(x.finalityThreshold??x.finalityThresholdExecuted??"")==="1000")??p[0];r=Lc(e.amountIn,g?.minimumFee??0)}const l=ra(r,e.bufferBps);return{provider:"cctp",sourceChainId:e.sourceChainId,destinationChainId:e.destinationChainId,tokenIn:M.getAddress(e.tokenIn),tokenOut:M.getAddress(e.tokenOut),amountIn:e.amountIn,estimatedAmountOut:e.amountIn>r?e.amountIn-r:0n,quotedBridgeFee:r,bufferedBridgeFee:l,bufferBps:e.bufferBps??ys,minFinalityThreshold:a,metadata:{sourceDomain:n.domain,destinationDomain:o.domain,transferMode:t}}}function Cs(e){return typeof e=="string"&&e.length>0?e:void 0}function bs(e){return typeof e=="bigint"?e:typeof e=="number"&&Number.isFinite(e)?BigInt(Math.trunc(e)):typeof e=="string"&&/^\d+$/.test(e)?BigInt(e):null}function qc(e){const t=e.estimate;return bs(t?.toAmountMin)??bs(t?.toAmount)??bs(e.toAmountMin)??bs(e.toAmount)}async function Qc(e){const t=e.integratorId??sa,n=e.fetchImpl??fetch,o=e.baseUrl??"https://v2.api.squidrouter.com",r=await n(`${o}/v2/route`,{method:"POST",headers:{"Content-Type":"application/json","x-integrator-id":t},body:JSON.stringify({fromAddress:M.getAddress(e.fromAddress),fromChain:String(e.sourceChainId),fromToken:M.getAddress(e.tokenIn),fromAmount:e.amountIn.toString(),toAddress:M.getAddress(e.toAddress),toChain:String(e.destinationChainId),toToken:M.getAddress(e.tokenOut),slippage:e.slippage??1,quoteOnly:e.quoteOnly??!0})}),a=await r.json().catch(()=>null);if(!r.ok){const c=typeof a?.message=="string"?a.message:`${r.status} ${r.statusText}`;throw new Error(`Squid route quote failed: ${c}`)}const l=a?.route;if(!l)throw new Error("Squid route quote response did not include route");const d=qc(l);if(d===null)throw new Error("Squid route quote response did not include output amount");const u=e.amountIn>d?e.amountIn-d:0n;return{provider:"squid",sourceChainId:e.sourceChainId,destinationChainId:e.destinationChainId,tokenIn:M.getAddress(e.tokenIn),tokenOut:M.getAddress(e.tokenOut),amountIn:e.amountIn,estimatedAmountOut:d,quotedBridgeFee:u,bufferedBridgeFee:ra(u,e.bufferBps),bufferBps:e.bufferBps??ys,...Cs(l.quoteId)?{quoteId:Cs(l.quoteId)}:{},...Cs(r.headers.get("x-request-id"))?{route:Cs(r.headers.get("x-request-id"))}:{},metadata:{requestId:r.headers.get("x-request-id")??void 0,slippage:e.slippage??1,quoteOnly:e.quoteOnly??!0}}}function Vc(e){return{type:"rebalancing",version:1,reason:e.reason??"spiceflow-intent",bridge:{provider:e.bridgeQuote.provider,quoteId:e.bridgeQuote.quoteId,route:e.bridgeQuote.route,sourceChainId:e.bridgeQuote.sourceChainId,destinationChainId:e.bridgeQuote.destinationChainId,tokenIn:e.bridgeQuote.tokenIn,tokenOut:e.bridgeQuote.tokenOut,amountIn:e.bridgeQuote.amountIn.toString(),estimatedAmountOut:e.bridgeQuote.estimatedAmountOut.toString(),quotedBridgeFee:e.bridgeQuote.quotedBridgeFee.toString(),bufferedBridgeFee:e.bridgeQuote.bufferedBridgeFee.toString(),bufferBps:e.bridgeQuote.bufferBps,minFinalityThreshold:e.bridgeQuote.minFinalityThreshold,...e.bridgeQuote.metadata},sourceAsset:e.sourceAsset?{chainId:e.sourceAsset.chainId,token:e.sourceAsset.address,symbol:e.sourceAsset.symbol,decimals:e.sourceAsset.decimals}:void 0,...e.extra}}function Gc(e){return`0x72${M.keccak256(M.encodeAbiParameters([{type:"address"},{type:"uint256"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"address"},{type:"uint256"},{type:"uint256"}],[M.getAddress(e.recipient),BigInt(e.fromChainId),M.getAddress(e.fromToken),e.fromAmount,BigInt(e.toChainId),M.getAddress(e.toToken),e.toAmountMin,e.salt??BigInt(Date.now())])).slice(4)}`}function Kc(e){const t=BigInt(Math.floor(Date.now()/1e3)),n=e.exp??t+3600n,o=e.nbf??0n,r=e.idempotenceKey??Gc({recipient:e.recipient,fromChainId:e.fromChainId,fromToken:e.fromToken,fromAmount:e.fromAmount,toChainId:e.toChainId,toToken:e.toToken,toAmountMin:e.toAmountMin});return{chainId:e.spicenetChainId,tokenTransfers:[],calls:[{to:"0x0000000000000000000000000000000000000000",value:0n,data:M.encodeFunctionData({abi:B.spicenetAbi,functionName:"createRebalancingRequest",args:[{idempotenceKey:r,nbf:o,exp:n,metadata:JSON.stringify(e.metadata??{}),recipient:M.getAddress(e.recipient).toLowerCase(),fromChainToken:aa(e.fromChainId,e.fromToken),fromChainTokenAmount:e.fromAmount,toChainToken:aa(e.toChainId,e.toToken),toChainTokenAmountMin:e.toAmountMin}]})}]}}function Yn(e){try{return B.resolveTokenRef(e)}catch{throw new h.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Token "${e[0]}" not found on chain ${e[1]} in the token registry.`,{symbol:e[0],chainId:e[1]})}}function Zc(e,t){if(e[0].toUpperCase()===t[0].toUpperCase()&&e[1]===t[1])return!0;let n,o;try{n=Yn(e),o=Yn(t)}catch{return!1}const r=new Set(B.getEquivalentAddresses(o.address).map(a=>a.toLowerCase()));return r.add(o.address.toLowerCase()),r.has(n.address.toLowerCase())}function Yc(){const e=[];for(const t of Object.keys(B.CHAINS).map(Number))for(const n of B.getTokensForChain(t))e.push([n.symbol,t]);return e}async function Xc(e){const{action:t,inputToken:n,inputAmount:o,registry:r,userAddress:a,slippage:l,intermediaryCandidates:d}=e;if(t.calls.length===0)throw new h.SpiceflowError("INVALID_PARAMS","buildIntent: action.calls must not be empty.",{action:t});if(o<=0n)throw new h.SpiceflowError("INVALID_PARAMS","buildIntent: inputAmount must be greater than zero.",{inputAmount:o.toString()});const u=t.supportedInputTokens??Yc();if(!u.some(C=>Zc(n,C))){const C=u.map(([k,b])=>`${k} (chain ${b})`).join(", ");throw new h.SpiceflowError("ROUTE_UNSUPPORTED_INPUT",`Input token "${n[0]}" on chain ${n[1]} is not in the action's supported input tokens. Supported: ${C}.`,{inputToken:{symbol:n[0],chainId:n[1]},supportedInputTokens:u})}const c=Yn(n),f=Yn(t.outputToken),p=gr({sourceAsset:c,outputAsset:f,sourceChainId:c.chainId,destinationChainId:t.chainId,intermediaryCandidates:d}),{chainBatches:g,solverFrontToken:x,solverFrontAmount:m,resolvedSwaps:y}=await xr({route:p,sourceAmount:o,userAddress:a,registry:r,actionCalls:t.calls,slippage:l});return{chainBatches:g,route:p,resolvedSwaps:y,resolvedInputToken:c,resolvedOutputToken:f,solverFrontToken:x,solverFrontAmount:m}}const Jc=[0n,1n,30n],$c=new Set(["ABORT","CONCURRENT_EXECUTION","WALLET_DISCONNECTED","WALLET_REJECTED","NO_VENUE_FOR_CHAIN"]);function la(e,t){return t===0n?e:e*(1000n-t)/1000n}async function _c(e,t){const{chainId:n,swapCalls:o,quoteAmountOut:r,buildActionCalls:a,tokenAddress:l,tokenTransferAmount:d,onProgress:u,signal:c,options:f,buffers:p=Jc}=t;for(let g=0;g<p.length;g++){const x=p[g],m=la(r,x),y=a(m),C=[{chainId:n,calls:[...o,...y]}];try{return await e(C,l,d,u,c,f)}catch(k){const b=typeof k?.message=="string"?k.message:String(k?.message??"");if(h.isSpiceflowError(k)&&$c.has(k.code)||k.name==="AbortError"||c?.aborted||b.includes("User rejected")||b.includes("User denied")||k.code===4001||g>=p.length-1)throw k;const A=Number(p[g+1])/10;console.warn(`[SwapThenAction] Action attempt ${g+1} failed (buffer ${Number(x)/10}%), retrying with ${A}% buffer...`,k.message),u?.({step:"signing-delegation",message:`Adjusting action amount, retrying (${A}% buffer)...`})}}throw new h.SpiceflowError("ALL_ATTEMPTS_FAILED","All action attempts failed after exhausting buffer progression.",{attempts:p.length,chainId:n})}wa(),exports.SpiceFlowProvider=h.SpiceFlowProvider,exports.SpiceFlowProviderContext=h.SpiceFlowProviderContext,exports.SpiceflowError=h.SpiceflowError,exports.Spinner=h.Spinner,exports.buildDarkPalette=h.buildDarkPalette,exports.buildLightPalette=h.buildLightPalette,exports.getChainConfig=h.getChainConfig,exports.getChainName=h.getChainName,exports.isSpiceflowError=h.isSpiceflowError,exports.relayerService=h.relayerService,exports.resolveTheme=h.resolveTheme,exports.useEmbeddedWalletAddress=h.useEmbeddedWalletAddress,exports.useIsUserWhitelisted=h.useIsUserWhitelisted,exports.useSpiceBrand=h.useSpiceBrand,exports.useWallet=h.useWallet,Object.defineProperty(exports,"NATIVE_TOKEN_ADDRESS",{enumerable:!0,get:function(){return B.ZERO_ADDRESS}}),Object.defineProperty(exports,"SPICENET_NATIVE_CHAIN_ID",{enumerable:!0,get:function(){return B.SPICENET_NATIVE_CHAIN_ID}}),Object.defineProperty(exports,"SPICE_COMBINED_FEE_RECIPIENT",{enumerable:!0,get:function(){return B.SPICE_COMBINED_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_GAS_FEE_RECIPIENT",{enumerable:!0,get:function(){return B.SPICE_GAS_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_PLATFORM_FEE_RECIPIENT",{enumerable:!0,get:function(){return B.SPICE_PLATFORM_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_SOLVER_ADDRESS",{enumerable:!0,get:function(){return B.SPICE_SOLVER_ADDRESS}}),Object.defineProperty(exports,"applySlippage",{enumerable:!0,get:function(){return B.applySlippage}}),Object.defineProperty(exports,"buildUniV3SwapCalls",{enumerable:!0,get:function(){return B.buildUniV3SwapCalls}}),Object.defineProperty(exports,"getChainIdsByNetwork",{enumerable:!0,get:function(){return B.getChainIdsByNetwork}}),Object.defineProperty(exports,"getEscrowContractAddress",{enumerable:!0,get:function(){return B.getEscrowContractAddress}}),Object.defineProperty(exports,"isNativeToken",{enumerable:!0,get:function(){return B.isNativeToken}}),Object.defineProperty(exports,"isSpicenetChainId",{enumerable:!0,get:function(){return B.isSpicenetChainId}}),Object.defineProperty(exports,"normalizeNativeTokenAddress",{enumerable:!0,get:function(){return B.normalizeNativeTokenAddress}}),Object.defineProperty(exports,"spicenetAbi",{enumerable:!0,get:function(){return B.spicenetAbi}}),Object.defineProperty(exports,"spicenetWithdrawalAbi",{enumerable:!0,get:function(){return B.spicenetAbi}}),exports.AccountDisplay=vc,exports.AddFundsLink=zs,exports.CheckIcon=Po,exports.ChevronIcon=pn,exports.CloseIcon=In,exports.DEFAULT_BRIDGE_FEE_BUFFER_BPS=ys,exports.DEFAULT_SQUID_INTEGRATOR_ID=sa,exports.DetailRow=Dn,exports.ExportWalletButton=$l,exports.ProviderLogin=qs,exports.SATSUMA_CITREA_CONFIG=ho,exports.SdkErrorBoundary=Sc,exports.SearchInput=Es,exports.SelectChainModal=Si,exports.SpiceBalance=xl,exports.SpiceDeposit=qo,exports.SpiceLock=vr,exports.SpiceLockModal=vr,exports.SpicePay=Jl,exports.SpiceSupply=$r,exports.SpiceWalletNotice=Tc,exports.SpiceWithdraw=yr,exports.StatusBanner=Rn,exports.UNIV3_BASE_CONFIG=Qr,exports.applyBuffer=la,exports.areEquivalentOnChains=Qn,exports.buildIntent=Xc,exports.buildPayChainBatches=so,exports.buildRebalancingBatch=Kc,exports.buildRebalancingMetadata=Vc,exports.buildRoutedBatches=xr,exports.buildSupplyChainBatches=oo,exports.create1inchVenue=Hr,exports.createExactOutputRegistry=Zr,exports.createLiquidityRegistry=Kr,exports.createSatsumaVenue=Vr,exports.duration=Vt,exports.easing=Nt,exports.estimateFeePreview=ao,exports.estimateRequiredGrossFunding=ro,exports.estimateSupplyMaxAmount=jr,exports.executeDirectExternalAction=gs,exports.executeNon7702Pay=Rr,exports.executeNon7702Supply=Mr,exports.executePay=uo,exports.executeSupply=co,exports.executeSwapThenAction=_c,exports.findEquivalentOnChain=mn,exports.findTokenOnChain=_s,exports.font=ko,exports.getAssetChainTokenCandidates=os,exports.getBestUniV3Quote=zr,exports.getUniV3Quote=Ur,exports.isSupportedSupplyAsset=Wr,exports.isSwapIntent=Or,exports.quoteCctpFee=Hc,exports.quoteSquidFee=Qc,exports.radius=As,exports.resolveAssetTokenAddressOnChain=rn,exports.resolveFundedToken=$o,exports.resolveInputSupplySwapQuote=Yl,exports.resolveRoute=gr,exports.resolveTokenRef=Yn,exports.scaleTokenAmount=nn,exports.transition=Jt,exports.useAssetInput=Mc,exports.useGaslessExecution=Pn,exports.useLockDuration=Rc,exports.usePay=Pc,exports.useRepay=Wc,exports.useSmartWallet=Dc,exports.useSpiceAction=xs,exports.useSpiceAssets=Vn,exports.useSpiceExecution=Pn,exports.useSpicePendingDeposits=_r,exports.useSupply=Nc,exports.useSupplyAssets=po,exports.useSupplyQuote=mo,exports.z=Cn;
|
|
108
|
+
`})]}),document.body):null;return s.jsxs(s.Fragment,{children:[et,re,E&&zn.createPortal(s.jsx(Lo,{isOpen:!0,onClose:K,supportedChains:[E.chainId],escrowOnly:!0,escrowTokenAddress:E.tokenAddress,escrowAmount:E.amount,escrowTokenDecimals:E.tokenDecimals,escrowTokenSymbol:E.tokenSymbol,styles:u,onDepositSuccess:ne}),document.body)]})},na=class yo extends i.Component{constructor(t){super(t),this.handleRetry=()=>{this.state.retryCount>=yo.MAX_RETRIES||this.setState(n=>({hasError:!1,error:null,retryCount:n.retryCount+1}))},this.state={hasError:!1,error:null,retryCount:0}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error(`[SdkErrorBoundary] ${this.props.componentName||"SDK component"} failed:`,{message:t.message,componentStack:n.componentStack})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const t={display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"24px",borderRadius:"8px",border:"1px solid rgba(239, 68, 68, 0.2)",backgroundColor:this.props.dark?"rgba(239, 68, 68, 0.08)":"rgba(239, 68, 68, 0.05)",gap:"12px"},n={fontSize:"14px",color:"#f87171",margin:0},o={fontSize:"12px",color:"#888",maxWidth:"280px",textAlign:"center",overflow:"hidden",display:"-webkit-box",WebkitLineClamp:3,WebkitBoxOrient:"vertical",margin:0},r={padding:"8px 16px",fontSize:"12px",borderRadius:"6px",backgroundColor:this.props.dark?"#2a2a2a":"#f3f4f6",color:this.props.dark?"#888":"#374151",border:this.props.dark?"1px solid #3a3a3a":"1px solid #d1d5db",cursor:"pointer",transition:"background-color 150ms ease"},a={fontSize:"12px",color:"#888",margin:0},l=yo.MAX_RETRIES-this.state.retryCount;return s.jsxs("div",{style:t,children:[s.jsxs("p",{style:n,children:[this.props.componentName||"Component"," failed to load"]}),this.state.error&&s.jsx("p",{style:o,children:this.state.error.message}),l>0?s.jsxs("button",{onClick:this.handleRetry,style:r,onMouseEnter:d=>{d.target.style.backgroundColor=this.props.dark?"#333":"#e5e7eb"},onMouseLeave:d=>{d.target.style.backgroundColor=this.props.dark?"#2a2a2a":"#f3f4f6"},children:["Try again (",l," left)"]}):s.jsx("p",{style:a,children:"Please refresh the page to try again"})]})}return this.props.children}};na.MAX_RETRIES=3;let Ic=na;const xo="spiceflow:wallet-notice:seen",Ac=()=>{if(typeof window>"u")return null;try{return window.localStorage.getItem(xo)}catch{return null}},Ec=e=>{if(!(typeof window>"u"))try{window.localStorage.setItem(xo,e)}catch{}},jc=()=>{if(!(typeof window>"u"))try{window.localStorage.removeItem(xo)}catch{}},Fc=()=>{const e=i.useContext(h.SpiceFlowProviderContext),{externalAddress:t}=h.useProviderWallets(),[n,o]=i.useState(!1),r=i.useRef(null),a=t?t.toLowerCase():null,l=e?.isWhitelistConfigured??!1,d=e?.isWhitelistChecking??!1,u=e?.isUserWhitelisted??null;i.useEffect(()=>{if(!a){r.current&&(jc(),o(!1)),r.current=null;return}r.current=a,!(!l||d||u===null)&&Ac()!==a&&(Ec(a),o(!0))},[a,l,d,u]);const c=i.useCallback(()=>o(!1),[]);return{isOpen:n,close:c,externalAddress:t,whitelisted:u===!0}},Bc=(e,t)=>({title:e.whitelisted?"You're whitelisted":"Wallet connected",body:e.whitelisted?s.jsxs(s.Fragment,{children:["The"," ",s.jsx("span",{style:{fontWeight:600,color:t.accentText},children:e.shortAddress})," ","or the linked Spicenet portal wallet is whitelisted. Feel free to try to use ",e.appName," with ",t.tokens,", cross-chain, supported chains"," ",t.chains.join(", "),"."]}):s.jsxs(s.Fragment,{children:["The"," ",s.jsx("span",{style:{fontWeight:600,color:t.accentText},children:e.shortAddress})," ","or the linked Spicenet portal is not whitelisted. You can use"," ",e.appName," normally as you always have."]})}),Tc=({isOpen:e,whitelisted:t,address:n,onClose:o,appName:r,tokens:a="stablecoins",chains:l=["Base","Arbitrum","Citrea"],renderContent:d,styles:u,dark:c})=>{const{appName:f,dark:p,palette:g,fontFamily:x}=h.useSpiceBrand(u,c),m=c??p,y=r??f,C=i.useId(),k=i.useRef(null),b=i.useRef(o);i.useEffect(()=>{b.current=o},[o]);const[A,v]=i.useState(!1),[w,R]=i.useState(!1);if(i.useEffect(()=>{if(e){v(!0);return}if(!A)return;R(!1);const N=setTimeout(()=>v(!1),300);return()=>clearTimeout(N)},[e,A]),i.useEffect(()=>{if(!A)return;const N=document.body.style.overflow;document.body.style.overflow="hidden";const D=requestAnimationFrame(()=>{requestAnimationFrame(()=>R(!0))}),L=Q=>{Q.key==="Escape"&&(Q.stopPropagation(),b.current())};return document.addEventListener("keydown",L),()=>{cancelAnimationFrame(D),document.removeEventListener("keydown",L),document.body.style.overflow=N}},[A]),!A)return null;const E=()=>b.current(),P=t?g.successBg:g.warningBg,T=t?g.successBorder:g.warningBorder,F=t?g.successText:g.warningText,S=n?Ao(n):"your wallet",j={whitelisted:t,address:n,shortAddress:S,appName:y},I=d?d(j):Bc(j,{tokens:a,chains:l,accentText:F});return s.jsx("div",{onMouseDown:N=>{N.target===N.currentTarget&&E()},style:{position:"fixed",inset:0,backgroundColor:m?"rgba(0,0,0,0.72)":"rgba(0,0,0,0.5)",display:"flex",alignItems:"flex-end",justifyContent:"center",zIndex:Cn.modal,opacity:w?1:0,transition:`opacity ${Vt.normal} ${Nt.out}`},children:s.jsxs("div",{ref:k,role:"dialog","aria-modal":"true","aria-labelledby":C,style:{backgroundColor:g.shell,borderTop:`1px solid ${g.shellInnerBorder}`,borderRadius:"16px 16px 0 0",width:"100%",maxWidth:"522px",boxSizing:"border-box",boxShadow:"0 -16px 48px rgba(0, 0, 0, 0.4)",padding:"24px 24px 16px 24px",transform:w?"translateY(0)":"translateY(100%)",transition:`transform ${Vt.slow} ${Nt.out}`,fontFamily:x},children:[s.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"12px"},children:[s.jsx("h2",{id:C,style:{fontSize:"20px",fontWeight:700,color:g.textPrimary,margin:0,lineHeight:1.15},children:I.title}),s.jsx("button",{type:"button",onClick:E,"aria-label":"Close notice",style:{color:g.textSecondary,backgroundColor:"transparent",border:"none",cursor:"pointer",padding:"4px",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:s.jsx(In,{size:22,strokeWidth:2.4})})]}),s.jsx("div",{style:{marginTop:"16px",backgroundColor:P,border:`1px solid ${T}`,borderRadius:"10px",padding:"14px 16px",color:g.textPrimary,fontSize:"14px",lineHeight:1.5},children:I.body}),s.jsx("div",{style:{marginTop:"16px"},children:s.jsx(h.Button,{variant:"outline",fullWidth:!0,onClick:E,styles:u,dark:m,children:"Got it"})}),s.jsx("div",{style:{marginTop:"14px",display:"flex",justifyContent:"center"},children:s.jsx("img",{src:Jn,alt:"","aria-hidden":"true",width:108,height:22,decoding:"async",style:{width:"108px",height:"22px",opacity:m?.85:1,filter:m?"brightness(0) invert(1)":"none",display:"block"}})})]})})},Mc=({styles:e,dark:t,appName:n,tokens:o,chains:r,renderContent:a,onClose:l})=>{const{isOpen:d,close:u,externalAddress:c,whitelisted:f}=Fc(),p=i.useCallback(()=>{u(),l?.()},[u,l]);return s.jsx(Tc,{isOpen:d,whitelisted:f,address:c,onClose:p,appName:n,tokens:o,chains:r,renderContent:a,styles:e,dark:t})},Rc=()=>{const[e,t]=i.useState("0"),[n,o]=i.useState(null);return{assetAmount:e,setAssetAmount:t,selectedAsset:n,setSelectedAsset:o}};function Dc(e,t=0){const[n,o]=i.useState(t),r=e[n]??e[0],a=i.useMemo(()=>r?BigInt(Math.round(r.months*30*24*3600)):0n,[r?.months]);return{selectedDurationIdx:n,setSelectedDurationIdx:o,selectedDuration:r,durationSeconds:a}}function Nc(){const{actions:e,isReady:t,isAuthenticated:n}=h.useWallet(),o=h.useEmbeddedWalletAddress(),r=i.useRef(!1),a=i.useRef(0),l=i.useRef(null),d=i.useRef(e),[u,c]=i.useState(0);d.current=e,i.useEffect(()=>{r.current=!1,a.current=0,l.current&&(clearTimeout(l.current),l.current=null)},[o]),i.useEffect(()=>{if(!o||!t||!n||r.current)return;r.current=!0;let f=!1;return(async()=>{await new Promise(p=>setTimeout(p,2e3));try{await h.ensureSmartWallet(o,d.current.signMessage),a.current=0}catch(p){console.warn("[SmartWallet] Registration failed:",p),r.current=!1,!f&&a.current<3&&(a.current+=1,l.current=setTimeout(()=>{c(g=>g+1)},5e3))}})(),()=>{f=!0,l.current&&(clearTimeout(l.current),l.current=null)}},[o,t,n,u])}function xs(e){const{destinationToken:t,recipient:n,buildActionCalls:o,buildSpicenetBatch:r,amountMode:a,amount:l,sourceChains:d,supportedSourceAssets:u,feeExecutionMode:c="user-transfer",enabled:f=!0,onSuccess:p,onError:g}=e,x=a==="exact-output"?"output":"input",m=x==="output",y=t.chainId,C=i.useContext(h.SpiceFlowProviderContext),k=(C?.mode||"7702")!=="7702",b=!!C?.isWhitelistGateActive,A=i.useMemo(()=>d??C?.supportedChainIds??[],[d,C?.supportedChainIds]),v=i.useMemo(()=>b?[]:u,[b,u]),w=h.useWallet(),{address:R,isConnected:E,isReady:P,isAuthenticated:T,provider:F}=w,{executeGasless:S,estimateGasless:j}=Pn(),{externalWallet:I,externalAddress:N,embeddedAddress:D}=h.useProviderWallets(),L=h.useEmbeddedWalletAddress()||D,{displayAssets:Q,filteredSpiceAssets:W,embeddedWalletAddress:O,refreshSpiceAssets:H,refreshWalletAssets:J}=po({destinationToken:t,supportedSourceAssets:v,sourceChains:A,enabled:f&&(k?!!N:!!L)}),U=Q,[z,ie]=i.useState(null),[q,$]=i.useState(!1),[le,he]=i.useState(null),[me,ue]=i.useState("idle"),[ge,Y]=i.useState(""),[oe,K]=i.useState(null),[ne,ce]=i.useState(null),[,Ce]=i.useState(!1),[be,G]=i.useState(null),[ee,_]=i.useState(!1),[Ae,Be]=i.useState(!1),[kt,_e]=i.useState(null),vt=i.useRef(z),Ve=i.useRef(!1),xe=i.useRef(null),Ee=i.useRef(0),ze=i.useRef(null),lt=i.useRef(null);i.useEffect(()=>{vt.current=z},[z]);const et=m?l||"0":z?.amount||"0";i.useEffect(()=>{f||(ie(null),he(null),$(!1),ue("idle"),Y(""),K(null),ce(null),Ce(!1),G(null),_(!1),Be(!1),_e(null),Ve.current=!1,xe.current&&(xe.current.abort(),xe.current=null))},[f]),i.useEffect(()=>{m||ie(de=>de&&de.amount!==l?{...de,amount:l}:de)},[l,m]);const re=i.useCallback(de=>{ie(de),he(null),_e(null),Be(!1)},[]),we=i.useCallback(de=>{ie(Le=>({asset:de,amount:Le?.asset?.address===de.address&&Le?.asset?.chainId===de.chainId&&Le.amount||(m?"":l)})),he(null),_e(null),Be(!1)},[l,m]),Ge=O||D||R,{isQuoting:je,quoteError:Me,estimatedOutput:Et,estimatedInput:Rt,resolvedSwap:ct,exactOutputSwap:Se,quoteAmountOut:St,resolvedTokenIn:bt,isDirect:mt,needsSwap:De,selectedIsEquivalent:zt}=mo({direction:x,selectedAsset:z,destinationToken:t,chainId:y,recipient:Ge,paymentAmount:et}),We=m?parseFloat(et):parseFloat(z?.amount||"")||0,gt=z?.asset?._source==="wallet",Je=!!z?.asset&>&&z.asset.chainId!==y,wt=gt&&z?.asset?._fundingWallet==="external",fe=z?.asset?._source!=="spice"&&(k||wt),Ke=i.useMemo(()=>z?.asset?W.find(de=>h.addressesEqual(de.address,z.asset.address))?.balanceFormatted??0:0,[z,W]),tt=gt?z?.asset.balanceFormatted??0:Ke||(z?.asset.balanceFormatted??0),xt=i.useMemo(()=>{if(!z?.asset)return!1;if(m)return be?nn(be.grossAmount,be.decimals,z.asset.decimals)>z.asset.balance:zt||mt?We>z.asset.balanceFormatted:Se?parseFloat(M.formatUnits(Se.amountInMax,z.asset.decimals))>z.asset.balanceFormatted:!1;if(be){const de=nn(be.grossAmount,be.decimals,z.asset.decimals);return gt?de>z.asset.balance:parseFloat(M.formatUnits(de,z.asset.decimals))>tt}return We>tt},[z,m,be,zt,We,Se,tt,gt,mt]),Re=i.useCallback(de=>{ue({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[de.step]||"executing"),Y(de.message),de.txHash&&K(de.txHash)},[]),nt=i.useMemo(()=>({currentPaymentAmount:et,destinationToken:t,embeddedWalletAddress:O,providerEmbeddedAddress:D,externalWalletAddress:N,address:R,recipient:n,isNon7702:fe,isPayMode:m,resolvedChainId:y,buildActionCalls:o,feeExecutionMode:c,buildSpicenetBatch:r,selectedAsset:z,needsSwap:De,resolvedSwap:ct,exactOutputSwap:Se,quoteAmountOut:St,resolvedTokenIn:bt}),[et,t,O,D,N,R,n,fe,m,y,o,c,r,z,De,ct,Se,St,bt]),Pt=i.useCallback(de=>so(nt,de),[nt]),Ye=i.useCallback(de=>oo(nt,de),[nt]),st=i.useCallback((de,Le,ot,Xe)=>ro(de,Le,ot,j,Xe),[j]),jt=i.useMemo(()=>z?.asset?De&&bt?bt:z.asset.chainId===y?z.asset.address:bt??rn(z.asset,y)??t.address:t.address,[z,t.address,De,y,bt]),Ft=i.useMemo(()=>z?.asset?h.addressesEqual(z.asset.address,t.address)&&z.asset.chainId===t.chainId:!1,[z,t.address,t.chainId]),Ot=fe&&Ft,Bt=Ot&&We>0&&!!z?.asset,Wt=i.useMemo(()=>!(!z?.asset||We<=0),[z,We]),dt=i.useMemo(()=>!f||q||me!=="idle"||!Wt||Bt||!z?.asset?null:[m?"pay":"supply",x,z.asset.address.toLowerCase(),z.asset.chainId,z.amount,et,t.address.toLowerCase(),t.chainId,y,bt?.toLowerCase()??"",De?"swap":"direct",mt?"direct-token":"routed-token",fe?"non7702":"7702",Ft?"source-dest":"cross-chain",je?"quoting":"quoted",n?.toLowerCase()??"",Se?.amountIn?.toString()??"",Se?.amountInMax?.toString()??"",Se?.venue??"",ct?.amountOut?.toString()??"",St?.toString()??"",O??"",D??"",R??""].join("|"),[f,q,me,Wt,Bt,z,m,x,et,t,y,bt,De,mt,fe,Ft,je,n,Se,ct,St,O,D,R]),Te=i.useCallback(()=>ao({selectedAsset:z,isPayMode:m,parsedAmount:We,needsSwap:De,exactOutputSwap:Se,isNon7702:fe,isSourceDestToken:Ft,currentPaymentAmount:et,destinationToken:t,feeExecutionMode:c,resolvedTokenIn:bt,embeddedWalletAddress:O,providerEmbeddedAddress:D,resolvedChainId:y,isConnected:E,address:R,ready:P,authenticated:T,isDirect:mt,resolvedSwap:ct,isQuoting:je,executionTokenAddress:jt,buildPayChainBatches:Pt,buildSupplyChainBatches:Ye,estimateGasless:j,estimateRequiredGrossFunding:st}),[z,m,We,De,Se,fe,Ft,et,t,c,bt,O,D,st,Pt,j,y,E,R,P,T,mt,ct,je,Ye,jt,n]);i.useEffect(()=>{ze.current=Te},[Te]),i.useEffect(()=>{if(!f){_(!1),Be(!1),_e(null),G(null);return}if(q||me!=="idle"){Ee.current+=1,_(!1);return}if(!Wt){G(null),_(!1),Be(!1),_e(null);return}if(Bt){G(null),_(!1),Be(!0),_e(null);return}if(je){Ee.current+=1,_(!1),Be(!1);return}if(!dt)return;let de=!1;const Le=async()=>{const Xe=++Ee.current;_e(null),_(!0);try{const Ht=await ze.current?.();if(de||Ee.current!==Xe)return;Ht?(G(Ht),Be(!0)):(G(null),Be(!1)),_e(null)}catch(Ht){if(de||Ee.current!==Xe)return;const ke=h.sanitizeError(Ht,"Unable to calculate fees for this action.");G(null),Be(!1),_e(ke)}finally{!de&&Ee.current===Xe&&_(!1)}},ot=window.setTimeout(()=>{Le()},250);return()=>{de=!0,clearTimeout(ot),_(!1)}},[f,q,me,Wt,Bt,je,dt]),i.useEffect(()=>{!m&&me==="success"&&oe&&(H(),p?.(oe))},[m,me,oe,H,p]),i.useEffect(()=>{if(!m||ne?.status!=="success"||Ve.current||!R)return;Ve.current=!0;const de=vt.current;!de?.asset||de.asset?._source==="wallet"||H()},[m,ne?.status,R,H]);const Mt=i.useRef(p),Ne=i.useRef(g);i.useEffect(()=>{Mt.current=p},[p]),i.useEffect(()=>{Ne.current=g},[g]),i.useEffect(()=>{m&&(ne?.status==="success"&&Mt.current?.(ne.txHash||""),ne?.status==="failed"&&Ne.current?.(new Error("Payment execution failed")))},[m,ne?.status]),i.useEffect(()=>{f&&(H(),J())},[f,H,J]),lt.current={selectedAsset:z,parsedAmount:We,currentPaymentAmount:et,isInsufficientBalance:xt,isPayMode:m,isNon7702:fe,isSourceDestToken:Ft,needsSwap:De,exactOutputSwap:Se,selectedIsEquivalent:zt,resolvedTokenIn:bt,embeddedWalletAddress:O,providerEmbeddedAddress:D,externalWallet:I,externalWalletAddress:N,address:R,isConnected:E,ready:P,authenticated:T,provider:F,resolvedChainId:y,executionTokenAddress:jt,destinationToken:t,recipient:n,buildActionCalls:o,feeExecutionMode:c,buildSpicenetBatch:r,onError:g,gasless:{estimateGasless:j,executeGasless:S,buildPayChainBatches:Pt,buildSupplyChainBatches:Ye,estimateRequiredGrossFunding:st,onProgress:Re},ui:{setError:he,setStep:ue,setStatusMsg:Y,setTxHash:K,setIsExecuting:$,setShowStatusPanel:Ce,setPaymentResult:ce},refs:{spiceDepositSubmittedRef:Ve,abortControllerRef:xe}};const _t=i.useCallback(async()=>{const de=lt.current;de&&(de.isPayMode?await uo(de):await co(de))},[]),Lt=m&&We===0,It=m?!!z?.asset&&We>=0&&!xt&&!q&&(Lt||Bt||Ae)&&!kt&&(Lt||!De||!!Se):!!z?.asset&&We>0&&!xt&&!q&&(Ot||Ae)&&!kt&&(Je||mt||!!ct&&!je),Qe=i.useCallback(()=>{H(),J()},[H,J]);return{sources:U,selectedAsset:z,setSelectedAsset:re,selectAsset:we,quote:{isQuoting:je,error:Me,estimatedInput:Rt,estimatedOutput:Et,isDirect:mt,needsSwap:De},feePreview:be,isFeePreviewLoading:ee,feePreviewError:kt,canSubmit:It,execute:_t,isExecuting:q,step:me,statusMsg:ge,txHash:oe,paymentResult:ne,refreshAssets:Qe}}function Pc(e){return xs({...e,amountMode:"exact-input"})}function Wc(e){return xs({...e,amountMode:"exact-output"})}function Uc(e){return xs({...e,amountMode:"exact-input"})}const ys=1500,sa="spiceflow-75f053db-70ab-4f37-83cc-abf68cb5b70d",zc={1:{chainId:1,domain:0,network:"mainnet"},42161:{chainId:42161,domain:3,network:"mainnet"},8453:{chainId:8453,domain:6,network:"mainnet"},11155111:{chainId:11155111,domain:0,network:"testnet"},421614:{chainId:421614,domain:3,network:"testnet"},84532:{chainId:84532,domain:6,network:"testnet"}};function oa(e,t,n){return(e*t+n-1n)/n}function ra(e,t=ys){return oa(e,BigInt(1e4+t),10000n)}function aa(e,t){return`evm:${e}:${M.getAddress(t).toLowerCase()}`}function ia(e){return zc[e]??null}function Oc(e){return e==="testnet"?"https://iris-api-sandbox.circle.com":"https://iris-api.circle.com"}function Lc(e){const t=typeof e=="number"?e.toString():typeof e=="string"?e:"0",[n,o=""]=t.trim().split("."),r=BigInt(n||"0"),a=BigInt((o+"00").slice(0,2)||"0");return r*100n+a}function Hc(e,t){const n=Lc(t);return oa(e,n,1000000n)}async function qc(e){const t=e.transferMode??"fast",n=ia(e.sourceChainId),o=ia(e.destinationChainId);if(!n||!o||n.network!==o.network)throw new Error(`Unsupported CCTP route ${e.sourceChainId} -> ${e.destinationChainId}`);let r=0n;const a=t==="fast"?1e3:2e3;if(t==="fast"){const d=e.fetchImpl??fetch,u=`${Oc(n.network)}/v2/burn/USDC/fees/${n.domain}/${o.domain}`,c=await d(u);if(!c.ok)throw new Error(`CCTP fee quote failed: ${c.status} ${c.statusText}`);const f=await c.json(),p=Array.isArray(f)?f:Array.isArray(f?.data)?f.data:[],g=p.find(x=>String(x.finalityThreshold??x.finalityThresholdExecuted??"")==="1000")??p[0];r=Hc(e.amountIn,g?.minimumFee??0)}const l=ra(r,e.bufferBps);return{provider:"cctp",sourceChainId:e.sourceChainId,destinationChainId:e.destinationChainId,tokenIn:M.getAddress(e.tokenIn),tokenOut:M.getAddress(e.tokenOut),amountIn:e.amountIn,estimatedAmountOut:e.amountIn>r?e.amountIn-r:0n,quotedBridgeFee:r,bufferedBridgeFee:l,bufferBps:e.bufferBps??ys,minFinalityThreshold:a,metadata:{sourceDomain:n.domain,destinationDomain:o.domain,transferMode:t}}}function Cs(e){return typeof e=="string"&&e.length>0?e:void 0}function bs(e){return typeof e=="bigint"?e:typeof e=="number"&&Number.isFinite(e)?BigInt(Math.trunc(e)):typeof e=="string"&&/^\d+$/.test(e)?BigInt(e):null}function Qc(e){const t=e.estimate;return bs(t?.toAmountMin)??bs(t?.toAmount)??bs(e.toAmountMin)??bs(e.toAmount)}async function Vc(e){const t=e.integratorId??sa,n=e.fetchImpl??fetch,o=e.baseUrl??"https://v2.api.squidrouter.com",r=await n(`${o}/v2/route`,{method:"POST",headers:{"Content-Type":"application/json","x-integrator-id":t},body:JSON.stringify({fromAddress:M.getAddress(e.fromAddress),fromChain:String(e.sourceChainId),fromToken:M.getAddress(e.tokenIn),fromAmount:e.amountIn.toString(),toAddress:M.getAddress(e.toAddress),toChain:String(e.destinationChainId),toToken:M.getAddress(e.tokenOut),slippage:e.slippage??1,quoteOnly:e.quoteOnly??!0})}),a=await r.json().catch(()=>null);if(!r.ok){const c=typeof a?.message=="string"?a.message:`${r.status} ${r.statusText}`;throw new Error(`Squid route quote failed: ${c}`)}const l=a?.route;if(!l)throw new Error("Squid route quote response did not include route");const d=Qc(l);if(d===null)throw new Error("Squid route quote response did not include output amount");const u=e.amountIn>d?e.amountIn-d:0n;return{provider:"squid",sourceChainId:e.sourceChainId,destinationChainId:e.destinationChainId,tokenIn:M.getAddress(e.tokenIn),tokenOut:M.getAddress(e.tokenOut),amountIn:e.amountIn,estimatedAmountOut:d,quotedBridgeFee:u,bufferedBridgeFee:ra(u,e.bufferBps),bufferBps:e.bufferBps??ys,...Cs(l.quoteId)?{quoteId:Cs(l.quoteId)}:{},...Cs(r.headers.get("x-request-id"))?{route:Cs(r.headers.get("x-request-id"))}:{},metadata:{requestId:r.headers.get("x-request-id")??void 0,slippage:e.slippage??1,quoteOnly:e.quoteOnly??!0}}}function Gc(e){return{type:"rebalancing",version:1,reason:e.reason??"spiceflow-intent",bridge:{provider:e.bridgeQuote.provider,quoteId:e.bridgeQuote.quoteId,route:e.bridgeQuote.route,sourceChainId:e.bridgeQuote.sourceChainId,destinationChainId:e.bridgeQuote.destinationChainId,tokenIn:e.bridgeQuote.tokenIn,tokenOut:e.bridgeQuote.tokenOut,amountIn:e.bridgeQuote.amountIn.toString(),estimatedAmountOut:e.bridgeQuote.estimatedAmountOut.toString(),quotedBridgeFee:e.bridgeQuote.quotedBridgeFee.toString(),bufferedBridgeFee:e.bridgeQuote.bufferedBridgeFee.toString(),bufferBps:e.bridgeQuote.bufferBps,minFinalityThreshold:e.bridgeQuote.minFinalityThreshold,...e.bridgeQuote.metadata},sourceAsset:e.sourceAsset?{chainId:e.sourceAsset.chainId,token:e.sourceAsset.address,symbol:e.sourceAsset.symbol,decimals:e.sourceAsset.decimals}:void 0,...e.extra}}function Kc(e){return`0x72${M.keccak256(M.encodeAbiParameters([{type:"address"},{type:"uint256"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"address"},{type:"uint256"},{type:"uint256"}],[M.getAddress(e.recipient),BigInt(e.fromChainId),M.getAddress(e.fromToken),e.fromAmount,BigInt(e.toChainId),M.getAddress(e.toToken),e.toAmountMin,e.salt??BigInt(Date.now())])).slice(4)}`}function Zc(e){const t=BigInt(Math.floor(Date.now()/1e3)),n=e.exp??t+3600n,o=e.nbf??0n,r=e.idempotenceKey??Kc({recipient:e.recipient,fromChainId:e.fromChainId,fromToken:e.fromToken,fromAmount:e.fromAmount,toChainId:e.toChainId,toToken:e.toToken,toAmountMin:e.toAmountMin});return{chainId:e.spicenetChainId,tokenTransfers:[],calls:[{to:"0x0000000000000000000000000000000000000000",value:0n,data:M.encodeFunctionData({abi:B.spicenetAbi,functionName:"createRebalancingRequest",args:[{idempotenceKey:r,nbf:o,exp:n,metadata:JSON.stringify(e.metadata??{}),recipient:M.getAddress(e.recipient).toLowerCase(),fromChainToken:aa(e.fromChainId,e.fromToken),fromChainTokenAmount:e.fromAmount,toChainToken:aa(e.toChainId,e.toToken),toChainTokenAmountMin:e.toAmountMin}]})}]}}function Yn(e){try{return B.resolveTokenRef(e)}catch{throw new h.SpiceflowError("ROUTE_TOKEN_NOT_FOUND",`Token "${e[0]}" not found on chain ${e[1]} in the token registry.`,{symbol:e[0],chainId:e[1]})}}function Yc(e,t){if(e[0].toUpperCase()===t[0].toUpperCase()&&e[1]===t[1])return!0;let n,o;try{n=Yn(e),o=Yn(t)}catch{return!1}const r=new Set(B.getEquivalentAddresses(o.address).map(a=>a.toLowerCase()));return r.add(o.address.toLowerCase()),r.has(n.address.toLowerCase())}function Xc(){const e=[];for(const t of Object.keys(B.CHAINS).map(Number))for(const n of B.getTokensForChain(t))e.push([n.symbol,t]);return e}async function Jc(e){const{action:t,inputToken:n,inputAmount:o,registry:r,userAddress:a,slippage:l,intermediaryCandidates:d}=e;if(t.calls.length===0)throw new h.SpiceflowError("INVALID_PARAMS","buildIntent: action.calls must not be empty.",{action:t});if(o<=0n)throw new h.SpiceflowError("INVALID_PARAMS","buildIntent: inputAmount must be greater than zero.",{inputAmount:o.toString()});const u=t.supportedInputTokens??Xc();if(!u.some(C=>Yc(n,C))){const C=u.map(([k,b])=>`${k} (chain ${b})`).join(", ");throw new h.SpiceflowError("ROUTE_UNSUPPORTED_INPUT",`Input token "${n[0]}" on chain ${n[1]} is not in the action's supported input tokens. Supported: ${C}.`,{inputToken:{symbol:n[0],chainId:n[1]},supportedInputTokens:u})}const c=Yn(n),f=Yn(t.outputToken),p=gr({sourceAsset:c,outputAsset:f,sourceChainId:c.chainId,destinationChainId:t.chainId,intermediaryCandidates:d}),{chainBatches:g,solverFrontToken:x,solverFrontAmount:m,resolvedSwaps:y}=await xr({route:p,sourceAmount:o,userAddress:a,registry:r,actionCalls:t.calls,slippage:l});return{chainBatches:g,route:p,resolvedSwaps:y,resolvedInputToken:c,resolvedOutputToken:f,solverFrontToken:x,solverFrontAmount:m}}const $c=[0n,1n,30n],_c=new Set(["ABORT","CONCURRENT_EXECUTION","WALLET_DISCONNECTED","WALLET_REJECTED","NO_VENUE_FOR_CHAIN"]);function la(e,t){return t===0n?e:e*(1000n-t)/1000n}async function ed(e,t){const{chainId:n,swapCalls:o,quoteAmountOut:r,buildActionCalls:a,tokenAddress:l,tokenTransferAmount:d,onProgress:u,signal:c,options:f,buffers:p=$c}=t;for(let g=0;g<p.length;g++){const x=p[g],m=la(r,x),y=a(m),C=[{chainId:n,calls:[...o,...y]}];try{return await e(C,l,d,u,c,f)}catch(k){const b=typeof k?.message=="string"?k.message:String(k?.message??"");if(h.isSpiceflowError(k)&&_c.has(k.code)||k.name==="AbortError"||c?.aborted||b.includes("User rejected")||b.includes("User denied")||k.code===4001||g>=p.length-1)throw k;const A=Number(p[g+1])/10;console.warn(`[SwapThenAction] Action attempt ${g+1} failed (buffer ${Number(x)/10}%), retrying with ${A}% buffer...`,k.message),u?.({step:"signing-delegation",message:`Adjusting action amount, retrying (${A}% buffer)...`})}}throw new h.SpiceflowError("ALL_ATTEMPTS_FAILED","All action attempts failed after exhausting buffer progression.",{attempts:p.length,chainId:n})}wa(),exports.SpiceFlowProvider=h.SpiceFlowProvider,exports.SpiceFlowProviderContext=h.SpiceFlowProviderContext,exports.SpiceflowError=h.SpiceflowError,exports.Spinner=h.Spinner,exports.buildDarkPalette=h.buildDarkPalette,exports.buildLightPalette=h.buildLightPalette,exports.getChainConfig=h.getChainConfig,exports.getChainName=h.getChainName,exports.isSpiceflowError=h.isSpiceflowError,exports.relayerService=h.relayerService,exports.resolveTheme=h.resolveTheme,exports.useEmbeddedWalletAddress=h.useEmbeddedWalletAddress,exports.useIsUserWhitelisted=h.useIsUserWhitelisted,exports.useSpiceBrand=h.useSpiceBrand,exports.useWallet=h.useWallet,Object.defineProperty(exports,"NATIVE_TOKEN_ADDRESS",{enumerable:!0,get:function(){return B.ZERO_ADDRESS}}),Object.defineProperty(exports,"SPICENET_NATIVE_CHAIN_ID",{enumerable:!0,get:function(){return B.SPICENET_NATIVE_CHAIN_ID}}),Object.defineProperty(exports,"SPICE_COMBINED_FEE_RECIPIENT",{enumerable:!0,get:function(){return B.SPICE_COMBINED_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_GAS_FEE_RECIPIENT",{enumerable:!0,get:function(){return B.SPICE_GAS_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_PLATFORM_FEE_RECIPIENT",{enumerable:!0,get:function(){return B.SPICE_PLATFORM_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_SOLVER_ADDRESS",{enumerable:!0,get:function(){return B.SPICE_SOLVER_ADDRESS}}),Object.defineProperty(exports,"applySlippage",{enumerable:!0,get:function(){return B.applySlippage}}),Object.defineProperty(exports,"buildUniV3SwapCalls",{enumerable:!0,get:function(){return B.buildUniV3SwapCalls}}),Object.defineProperty(exports,"getChainIdsByNetwork",{enumerable:!0,get:function(){return B.getChainIdsByNetwork}}),Object.defineProperty(exports,"getEscrowContractAddress",{enumerable:!0,get:function(){return B.getEscrowContractAddress}}),Object.defineProperty(exports,"isNativeToken",{enumerable:!0,get:function(){return B.isNativeToken}}),Object.defineProperty(exports,"isSpicenetChainId",{enumerable:!0,get:function(){return B.isSpicenetChainId}}),Object.defineProperty(exports,"normalizeNativeTokenAddress",{enumerable:!0,get:function(){return B.normalizeNativeTokenAddress}}),Object.defineProperty(exports,"spicenetAbi",{enumerable:!0,get:function(){return B.spicenetAbi}}),Object.defineProperty(exports,"spicenetWithdrawalAbi",{enumerable:!0,get:function(){return B.spicenetAbi}}),exports.AccountDisplay=Sc,exports.AddFundsLink=zs,exports.CheckIcon=Po,exports.ChevronIcon=pn,exports.CloseIcon=In,exports.DEFAULT_BRIDGE_FEE_BUFFER_BPS=ys,exports.DEFAULT_SQUID_INTEGRATOR_ID=sa,exports.DetailRow=Dn,exports.ExportWalletButton=_l,exports.ProviderLogin=qs,exports.SATSUMA_CITREA_CONFIG=ho,exports.SdkErrorBoundary=Ic,exports.SearchInput=Es,exports.SelectChainModal=Si,exports.SpiceBalance=yl,exports.SpiceDeposit=qo,exports.SpiceLock=vr,exports.SpiceLockModal=vr,exports.SpicePay=$l,exports.SpiceSupply=$r,exports.SpiceWalletNotice=Mc,exports.SpiceWithdraw=yr,exports.StatusBanner=Rn,exports.UNIV3_BASE_CONFIG=Qr,exports.applyBuffer=la,exports.areEquivalentOnChains=Qn,exports.buildIntent=Jc,exports.buildPayChainBatches=so,exports.buildRebalancingBatch=Zc,exports.buildRebalancingMetadata=Gc,exports.buildRoutedBatches=xr,exports.buildSupplyChainBatches=oo,exports.create1inchVenue=Hr,exports.createExactOutputRegistry=Zr,exports.createLiquidityRegistry=Kr,exports.createSatsumaVenue=Vr,exports.duration=Vt,exports.easing=Nt,exports.estimateFeePreview=ao,exports.estimateRequiredGrossFunding=ro,exports.estimateSupplyMaxAmount=jr,exports.executeDirectExternalAction=gs,exports.executeNon7702Pay=Rr,exports.executeNon7702Supply=Mr,exports.executePay=uo,exports.executeSupply=co,exports.executeSwapThenAction=ed,exports.findEquivalentOnChain=mn,exports.findTokenOnChain=_s,exports.font=ko,exports.getAssetChainTokenCandidates=os,exports.getBestUniV3Quote=zr,exports.getUniV3Quote=Ur,exports.isSupportedSupplyAsset=Wr,exports.isSwapIntent=Or,exports.quoteCctpFee=qc,exports.quoteSquidFee=Vc,exports.radius=As,exports.resolveAssetTokenAddressOnChain=rn,exports.resolveFundedToken=$o,exports.resolveInputSupplySwapQuote=Xl,exports.resolveRoute=gr,exports.resolveTokenRef=Yn,exports.scaleTokenAmount=nn,exports.transition=Jt,exports.useAssetInput=Rc,exports.useGaslessExecution=Pn,exports.useLockDuration=Dc,exports.usePay=Wc,exports.useRepay=Uc,exports.useSmartWallet=Nc,exports.useSpiceAction=xs,exports.useSpiceAssets=Vn,exports.useSpiceExecution=Pn,exports.useSpicePendingDeposits=_r,exports.useSupply=Pc,exports.useSupplyAssets=po,exports.useSupplyQuote=mo,exports.z=Cn;
|