@spicenet-io/spiceflow-ui 3.3.45 → 3.3.46

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
@@ -100,9 +100,9 @@
100
100
  from { transform: rotate(0deg); }
101
101
  to { transform: rotate(360deg); }
102
102
  }
103
- `})]})},Ti="0xa9059cbb";function Ri(e){const t=new Map;for(const s of e){if(s.amount<=0n)continue;const o=j.getAddress(s.token),a=j.getAddress(s.to),r=`${o.toLowerCase()}:${a.toLowerCase()}`,i=t.get(r);i?i.amount+=s.amount:t.set(r,{token:o,to:a,amount:s.amount})}return[...t.values()]}function Mi(e,t){return`0x${t}${e.slice(4)}`}function Di(e,t,s){if(!Array.isArray(e))return 0n;const o=`evm:${t}:${s.slice(2).toLowerCase()}`;let a=0n;for(const r of e){if(!r||typeof r!="object")continue;const i=r,d=i.chainTokens;if((Array.isArray(d)?d.filter(u=>typeof u=="string"):d&&typeof d=="object"?Object.keys(d):[]).some(u=>u.toLowerCase()===o))try{a+=BigInt(i.balanceAvailable??"0")}catch{}}return a}async function Vo(e,t,s,o){const a=await fetch(`${e}/wallets/${t}/balance`,{cache:"no-store"});if(!a.ok)throw new Error(`Failed to fetch spice balance: ${a.status}`);const r=await a.json();return Di(r?.balances,s,o)}async function Ni({apiBaseUrl:e,user:t,chainId:s,tokenAddress:o,prevBalance:a,timeoutMs:r=3e4,pollIntervalMs:i=1500}){const d=Date.now()+r;for(await new Promise(u=>setTimeout(u,800));Date.now()<d;){try{if(await Vo(e,t,s,o)>a)return}catch(u){console.warn("[SpiceLockModal] spice balance poll failed:",u?.message)}await new Promise(u=>setTimeout(u,i))}console.warn("[SpiceLockModal] Spicenet indexer did not reflect deposit within timeout; proceeding with intent")}function Us(e,t){return Ps(e,t)}function Ps(e,t,s){const o=Wi(t,e),a=Math.floor(Date.now()/1e3)+60*10,r=F.hashChainBatches(o);return{user:e,...s?{chainAuthorizations:s}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:"0x00",nbf:0,exp:a,chainBatches:r.map((i,d)=>({hash:i.hash,chainId:i.chainId,tokenTransfers:o[d].domain==="spicenet"?[]:o[d].tokenTransfers??[],calls:i.calls}))}]}}function Wi(e,t){return e.map(s=>{if(s.domain==="spicenet"||s.calls.length===0)return s;const o=new Set((s.tokenTransfers??[]).filter(r=>(r.from==="escrow"||r.from==="solver")&&j.getAddress(r.to).toLowerCase()===t.toLowerCase()).map(r=>j.getAddress(r.token).toLowerCase()));if(o.size===0)return s;let a=0;for(const r of s.calls){if(!r.data?.startsWith(Ti))break;try{const i=j.decodeFunctionData({abi:p.U,data:r.data});if(i.functionName!=="transfer")break;const[d]=i.args;if(d.toLowerCase()===t.toLowerCase()||!o.has(j.getAddress(r.to).toLowerCase()))break;a+=1}catch{break}}return a===0?s:{...s,calls:s.calls.slice(a)}})}function Ut(e,t,s,o){if(e.some(l=>l.domain==="spicenet"))return e;const a=s?.intents.flatMap(l=>l.batches),r=l=>l.from==="escrow",i=e.map(l=>{const h=a?.find(C=>C.chainId===l.chainId);if(!h)return l;const f=on(h),g=f.totalFee;if(g<=0n)return l;const x=(l.tokenTransfers??[]).find(C=>r(C)&&j.getAddress(C.to).toLowerCase()===t.toLowerCase()&&!F.isNativeToken(j.getAddress(C.token)));if(!x)return l;const m=j.getAddress(x.token);let y=!1;const b=(l.tokenTransfers??[]).map(C=>y||!r(C)||j.getAddress(C.to).toLowerCase()!==t.toLowerCase()||j.getAddress(C.token).toLowerCase()!==m.toLowerCase()?C:(y=!0,{...C,amount:o?.payoutAlreadyGross?BigInt(C.amount):BigInt(C.amount)+g}));if(!y)return l;const S=[];f.spicenetFee>0n&&S.push({to:m,value:0n,data:j.encodeFunctionData({abi:p.U,functionName:"transfer",args:[F.SPICE_PLATFORM_FEE_RECIPIENT,f.spicenetFee]})});const w=f.gasFee+f.bridgeFee;return w>0n&&S.push({to:m,value:0n,data:j.encodeFunctionData({abi:p.U,functionName:"transfer",args:[F.SPICE_SOLVER_ADDRESS,w]})}),{...l,tokenTransfers:b,calls:[...S,...l.calls]}}),d=i.flatMap(l=>(l.tokenTransfers??[]).filter(r).map(h=>{const f=j.getAddress(h.token),g=j.getAddress(h.to),x=[{token:f,to:g,amount:BigInt(h.amount)}];return{chainId:l.chainId,transfers:Ri(x)}}));if(d.length===0)return e;const u=BigInt(Math.floor(Date.now()/1e3))+3600n;return[{chainId:F.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:d.map((l,h)=>{const f=j.keccak256(j.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,l.transfers[0].token,l.transfers.reduce((x,m)=>x+m.amount,0n),BigInt(l.chainId),BigInt(Date.now()+h)])),g=Mi(f,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:j.encodeFunctionData({abi:F.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${l.chainId}`,idempotenceKey:g,nbf:0n,exp:u,metadata:"{}",transfers:l.transfers.map(x=>({token:x.token.toLowerCase(),to:x.to,amount:x.amount}))}]})}})},...i]}function dn(e,t){const s=e.selectedAsset?.asset;if(!s||!e.selectedAsset?.amount)throw new Error("Select an asset and enter an amount");const o=t?.netAmount??j.parseUnits(e.selectedAsset.amount,s.decimals),a=t?.grossAmount??o;return e.resolveLockBatches({amount:j.formatUnits(o,s.decimals),amountWei:o,grossAmount:j.formatUnits(a,s.decimals),grossAmountWei:a})}async function zs(e,t,s){const o=[...new Set(s.filter(r=>r.domain!=="spicenet").map(r=>r.chainId))],a=[];for(const r of o){const i=p.getClientForChain(r),d=p.getDelegateContractAddress(r),u=await F.getAccountNonce(t,i),l=await e.actions.signAuthorization({contractAddress:d,chainId:r,nonce:Number(u)});a.push(l)}return a}async function qo(e,t,s){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 a=s??await zs(e,o,t),r=F.hashChainBatches(t),i=Math.floor(Date.now()/1e3)+60*10,d=r.map(x=>x.hash),u=j.keccak256(j.encodeAbiParameters([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,BigInt(i),d])),l=await e.actions.signMessage({raw:u}),h=typeof l=="string"?l:l.signature;if(!h)throw new Error("Failed to sign intent authorization");const f={mode:"7702",signatureType:"ecdsa",signature:h,nbf:0,exp:i,chainBatches:r.map((x,m)=>{const y=t[m],b=y.domain==="spicenet";return{hash:x.hash,chainId:x.chainId,tokenTransfers:b?[]:y.tokenTransfers??[],calls:x.calls}})},g=await p.relayerService.createAction({user:o,chainAuthorizations:a.map(x=>({r:x.r,s:x.s,yParity:x.yParity,address:x.address,chainId:Number(x.chainId),nonce:Number(x.nonce)})),intents:[f]});if(g){const x=p.createInitialSteps(t,p.getChainName),[m,y]=g.intentIds[0].split("/"),b=parseInt(y||"0",10),S=g.intentIds[0];e.startStatusPolling(g.intentIds[0],x),await Eo({actionId:m,intentIndex:b,intentId:S,totalSteps:t.length,isSpicenetStep:w=>t[w]?.domain==="spicenet",maxExecuteAttemptsForStep:w=>t[w]?.domain==="spicenet"?6:3,maxPolls:180})}}async function Ko(e){let t=dn(e);if(t.length===0)throw new Error("No lock batches configured");const s=e.isSemi7702&&e.providerEmbeddedAddress||e.address;if(!e.isConnected||!s)throw new Error("Please connect your wallet to continue");const o=await zs(e,s,t);let a=Ut([...t],s),r;for(let i=0;i<4;i+=1){const d=await p.relayerService.estimateActionFees(Ps(s,a,o.map(f=>({r:f.r,s:f.s,yParity:f.yParity,address:f.address,chainId:Number(f.chainId),nonce:Number(f.nonce)})))),u=Un(d,{symbol:e.selectedAsset?.asset.symbol??"",decimals:e.selectedAsset?.asset.decimals??18});if(!u)break;const l={grossAmount:u.grossAmount,netAmount:u.netAmount,feeAmount:u.totalFee??0n},h=r?.grossAmount===l.grossAmount&&r?.netAmount===l.netAmount&&r?.feeAmount===l.feeAmount;if(r=l,t=dn(e,r),a=Ut([...t],s,d),h)break}await qo(e,a,o)}async function Ui(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");if(!e.address||!e.embeddedWalletAddress)throw new Error("Embedded wallet not connected");const t=e.selectedAsset.asset,s=j.parseUnits(e.selectedAsset.amount,t.decimals),o=e.escrowAddress||p.getDelegateContractAddress(e.lockChainId),a=p.relayerService.getBaseUrl(),r=F.normalizeNativeTokenAddress(t.address);let i=0n;try{i=await Vo(a,e.embeddedWalletAddress,e.lockChainId,r)}catch(f){console.warn("[SpiceLockModal] could not snapshot spice balance pre-deposit:",f?.message)}const d=await e.actions.getEthereumProvider();await p.ensureWalletOnChain(d,e.lockChainId);const u=p.getChainConfig(e.lockChainId),l=j.createWalletClient({account:e.embeddedWalletAddress,transport:j.custom(d),chain:u?.viemChain});let h;if(t.isNative||F.isNativeToken(t.address))h=await l.sendTransaction({to:o,value:s,chain:u?.viemChain});else{const f=j.encodeFunctionData({abi:p.U,functionName:"transfer",args:[o,s]});h=await l.sendTransaction({to:t.address,data:f,chain:u?.viemChain})}if((await p.getClientForChain(e.lockChainId).waitForTransactionReceipt({hash:h,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to escrow failed");await Ni({apiBaseUrl:a,user:e.embeddedWalletAddress,chainId:e.lockChainId,tokenAddress:r,prevBalance:i}),await e.refreshSpiceAssets(),e.refreshWalletAssets(),await Ko(e)}async function Pi(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 A=e.resolveLockBatches();if(A.length===0)throw new Error("No lock batches configured");const E=e.selectedAsset.asset,R=j.parseUnits(e.selectedAsset.amount,E.decimals),B=await e.onLockExecute({asset:E,amount:e.selectedAsset.amount,amountWei:R,lockDurationMonths:e.selectedDuration?.months??0,chainBatches:A});B&&e.onLockSuccess?.(B);return}const s=e.resolveLockBatches();if(s.length===0)throw new Error("No lock batches configured");const o=e.selectedAsset.asset,a=j.parseUnits(e.selectedAsset.amount,o.decimals),r=o.chainId,i=e.escrowAddress||F.getEscrowContractAddress(r),d=F.normalizeNativeTokenAddress(o.address),u=o.isNative||F.isNativeToken(d),l=s.some(A=>A.tokenTransfers?.some(E=>E.from==="escrow")),h=A=>({chainId:r,calls:u?[{to:i,value:A,data:"0x"}]:[{to:d,value:0n,data:j.encodeFunctionData({abi:p.U,functionName:"transfer",args:[i,A]})}]}),f=(A,E,R)=>{const B=h(A);if(!l)return[B,...E];const I=Ut([...E],t,R);return[B,...I]};let g=dn(e),x=f(a,g);const m=await zs(e,t,x);let y;if(l)for(let A=0;A<4;A+=1){const E=await p.relayerService.estimateActionFees(Ps(t,x,m.map(T=>({r:T.r,s:T.s,yParity:T.yParity,address:T.address,chainId:Number(T.chainId),nonce:Number(T.nonce)})))),R=Un(E,{symbol:o.symbol,decimals:o.decimals});if(!R)break;const B={grossAmount:R.grossAmount,netAmount:R.netAmount,feeAmount:R.totalFee??0n},I=y?.grossAmount===B.grossAmount&&y?.netAmount===B.netAmount&&y?.feeAmount===B.feeAmount;if(y=B,g=dn(e,y),x=f(B.grossAmount,g,E),I)break}const b=y?.grossAmount??a,S=await e.externalWallet.getEthereumProvider();let w=null;try{const A=await S.request({method:"eth_chainId"});w=parseInt(A,16)}catch{w=null}w!==r&&await p.ensureWalletOnChain(S,r);const C=p.getChainConfig(r),v=j.createWalletClient({account:e.externalWalletAddress,chain:C?.viemChain,transport:j.custom(S)}),k=u?await v.sendTransaction({to:t,value:b,chain:C?.viemChain}):await v.sendTransaction({to:d,data:j.encodeFunctionData({abi:p.U,functionName:"transfer",args:[t,b]}),chain:C?.viemChain});if((await p.getClientForChain(r).waitForTransactionReceipt({hash:k,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to embedded wallet failed");await qo(e,x,m)}async function zi(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount||!e.requiresRelayerFeeEstimate)return null;if(e.isSemi7702){const i=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!i)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");let d=dn(e);if(d.length===0)throw new Error("No lock batches configured");const u=e.selectedAsset.asset,l=j.parseUnits(e.selectedAsset.amount,u.decimals),h=u.chainId,f=e.escrowAddress||F.getEscrowContractAddress(h),g=F.normalizeNativeTokenAddress(u.address),x=u.isNative||F.isNativeToken(g),m=d.some(v=>v.tokenTransfers?.some(k=>k.from==="escrow")),y=v=>({chainId:h,calls:x?[{to:f,value:v,data:"0x"}]:[{to:g,value:0n,data:j.encodeFunctionData({abi:p.U,functionName:"transfer",args:[f,v]})}]}),b=(v,k,A)=>{const E=y(v);if(!m)return[E,...k];const R=Ut([...k],i,A);return[E,...R]};let S=b(l,d),w=null,C;for(let v=0;v<4;v+=1){const k=await p.relayerService.estimateActionFees(Us(i,S)),A=Un(k,{symbol:u.symbol,decimals:u.decimals});if(!A)return w;const E={grossAmount:A.grossAmount,netAmount:A.netAmount,feeAmount:A.totalFee??0n},R=C?.grossAmount===E.grossAmount&&C?.netAmount===E.netAmount&&C?.feeAmount===E.feeAmount;if(w=A,C=E,d=dn(e,E),S=b(E.grossAmount,d,k),R)break}return w}const t=e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");let s=dn(e);if(s.length===0)throw new Error("No lock batches configured");let o=Ut([...s],t),a=null;for(let i=0;i<4;i+=1){const d=await p.relayerService.estimateActionFees(Us(t,o)),u=Un(d,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals});if(!u)return null;const l={grossAmount:u.grossAmount,netAmount:u.netAmount},h=a?.grossAmount===u.grossAmount&&a?.netAmount===u.netAmount&&a?.totalFee===u.totalFee;if(a=u,s=dn(e,l),o=Ut([...s],t,d),h)break}if(a)return a;const r=await p.relayerService.estimateActionFees(Us(t,o));return Un(r,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals})}async function Li(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.resolveLockBatches();if(t.length===0)throw new Error("No lock batches configured");const s=t.find(l=>l.chainId===e.lockChainId)||t[0];if(!s)throw new Error("No lock batch for lock chain");const o=await e.externalWallet.getEthereumProvider();let a=null;try{const l=await o.request({method:"eth_chainId"});a=parseInt(l,16)}catch{a=null}a!==e.lockChainId&&await p.ensureWalletOnChain(o,e.lockChainId);const r=p.getChainConfig(e.lockChainId),i=j.createWalletClient({account:e.externalWalletAddress,chain:r?.viemChain,transport:j.custom(o)}),d=p.getClientForChain(e.lockChainId);let u;for(const l of s.calls){const h=await i.sendTransaction({to:l.to,data:l.data,value:l.value,chain:r?.viemChain});if((await d.waitForTransactionReceipt({hash:h,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Lock transaction failed");u=h}u&&e.onLockSuccess?.(u)}async function Oi(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=s=>{console.error("[SpiceLockModal] lock failed:",s);const o=p.sanitizeError(s,""),a=typeof s?.shortMessage=="string"?s.shortMessage:typeof s?.message=="string"?s.message:"";e.ui.setError(o||a||"Transaction failed. Please try again.")};if(e.isSemi7702){if(e.isSourceDestToken){try{await Li(e)}catch(s){t(s)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{await Pi(e)}catch(s){t(s)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{e.isDirectDeposit&&!e.isSourceDestToken?await Ui(e):await Ko(e)}catch(s){t(s)}finally{e.ui.setIsExecuting(!1)}}const Zo=({isOpen:e,onClose:t,closeOnBackdropClick:s=!1,lockBatches:o,lockTokenSymbol:a,lockTokenLogoURI:r,destinationInputHook:i,sourceAssetInputHook:d,lockDurationHook:u,lockChainId:l,durationOptions:h,votingPowerEstimate:f,escrowAddress:g,includeWalletAssets:x=!1,destinationTokenAddress:m,onLockSuccess:y,onLockExecute:b,sourceToDestinationConversionRate:S,estimatedOutputAmount:w,onAddFunds:C,buildSpicenetBatch:v,styles:k,dark:A=!1})=>{const{theme:E,dark:R,primaryColor:B,dk:I}=p.useSpiceBrand(k,A),T=E.typography.fontFamily,D=c.useContext(p.SpiceFlowProviderContext),M=D?.mode||"7702",U=!!D?.isWhitelistGateActive,z=M!=="7702",W=c.useMemo(()=>D?.supportedChainIds??[],[D?.supportedChainIds]),Q=c.useMemo(()=>{if(U)return[];const Z=D?.allowedTokens;if(!Z||Z.length===0)return[];const ye=new Set(Z.map(Ee=>Ee.toLowerCase())),Ae=[],je=new Set;for(const Ee of W){const lt=p.getChainConfig(Ee);for(const ht of lt?.supportedTokens??[]){if(!ye.has(ht.symbol.toLowerCase()))continue;const qt=`${Ee}:${ht.address.toLowerCase()}`;je.has(qt)||(je.add(qt),Ae.push(j.getAddress(ht.address)))}}return Ae},[D?.allowedTokens,W,U]),N=R?I.cardBg:k?.assetSelector?.backgroundColor||k?.secondaryBackground||"#e9e9e9",L=R?`1px solid ${I.cardBorder}`:"0.5px solid #A8A8A7",q=R?"12px":"6px",K=R?I.textPrimary:"#111827",O=R?I.textSecondary:"#6b7280",G=c.useMemo(()=>({...k,assetSelector:{...k?.assetSelector,backgroundColor:R?I.cardBg:k?.assetSelector?.backgroundColor,borderRadius:R?"12px":k?.assetSelector?.borderRadius},secondaryBackground:R?I.cardBg:k?.secondaryBackground}),[k,R]),ce=c.useMemo(()=>R?{...E,colors:{...E.colors,secondary:I.cardBg,surfaceHover:I.hoverBg,border:I.cardBorder,borderHover:I.inputBorder}}:E,[R,E]),[P,ne]=c.useState(null),[me,ke]=c.useState(0),pe=u?.selectedDurationIdx??me,ge=u?.setSelectedDurationIdx??ke,[fe,V]=c.useState(!1),[re,X]=c.useState(null),[le,xe]=c.useState(null),[Se,J]=c.useState(!1),[Y,ae]=c.useState(!1),[Ce,We]=c.useState(null),[rt,Ke]=c.useState(!1),Ze=c.useRef(0),[oe,ie]=c.useState(!1),[Ye,_]=c.useState(null);At.useWalletClient(),At.useSwitchChain();const{chain:Me,address:ct}=At.useAccount();At.useConfig();const kt=c.useRef(Me);c.useEffect(()=>{kt.current=Me},[Me]);const st=p.useWallet(),{isReady:Pt,isAuthenticated:Rt,isConnected:mt,address:Ie,provider:Mt,actions:Zt}=st,{externalWallet:Yt,embeddedAddress:gt,externalAddress:zt}=p.useProviderWallets(),{intentStatus:Ge,startStatusPolling:vt,clearStatus:Qe}=oo({checkStepStatus:(Z,ye)=>p.relayerService.checkStepStatus(Z,ye),retryStep:async(Z,ye)=>{const[Ae,je]=Z.split("/"),Ee=parseInt(je||"0",10);await p.relayerService.executeStep(Ae,Ee,ye,{action:"execute"})},maxRetries:3}),{assets:$e,refetch:_e}=Wn({address:Ie,supportedChains:W,enabled:e&&mt&&!z&&!U,refetchInterval:3e4}),dt=c.useMemo(()=>{if(U)return[];if(Q.length===0)return $e;const Z=new Set(Q.map(ye=>ye.toLowerCase()));return $e.filter(ye=>Z.has(ye.address.toLowerCase()))},[$e,Q,U]),Et=p.useEmbeddedWalletAddress(),he=zt||ct,at=z?he:Et,it=c.useMemo(()=>{if(!x)return[];if(U)return m?[j.getAddress(m)]:[];const Z=new Set,ye=[],Ae=je=>{if(!je)return;const Ee=je.toLowerCase();Z.has(Ee)||(Z.add(Ee),ye.push(j.getAddress(je)))};if(m&&Ae(m),z)for(const je of Q)Ae(je);return ye},[x,z,m,Q,U]),jt=c.useMemo(()=>it.map(Z=>Z.toLowerCase()).sort().join(","),[it]),be=c.useMemo(()=>JSON.stringify([...W||[]].sort()),[W]),[Dt,et]=c.useState([]),ut=c.useRef(0),xt=c.useCallback(async()=>{if(!x||!at||it.length===0){ut.current++,et([]);return}const Z=++ut.current,ye=j.getAddress(at),Ae=W&&W.length>0?W:[l],je=it.map(H=>{const $=H.toLowerCase();if(m&&p.addressesEqual(H,m)){const ue=p.getChainConfig(l)?.supportedTokens?.find(ee=>p.addressesEqual(ee.address,$));return{address:H,chainId:l,configToken:ue?{decimals:ue.decimals,symbol:ue.symbol,name:ue.name,logo:ue.logo}:void 0}}for(const ue of Ae){const ee=p.getChainConfig(ue)?.supportedTokens?.find(Re=>p.addressesEqual(Re.address,$));if(ee)return{address:H,chainId:ue,configToken:{decimals:ee.decimals,symbol:ee.symbol,name:ee.name,logo:ee.logo}}}return{address:H,chainId:l}}),Ee=new Map;for(const H of je){const $=Ee.get(H.chainId)||[];$.push(H),Ee.set(H.chainId,$)}const lt=async(H,$)=>{try{const ue=await Tt.readContract(H,{address:$.address,abi:p.U,functionName:"balanceOf",args:[ye]});let ee,Re,Fe,Pe;if($.configToken)ee=$.configToken.decimals,Re=$.configToken.symbol,Fe=$.configToken.name,Pe=$.configToken.logo;else{const[Ft,pt,It]=await Promise.all([Tt.readContract(H,{address:$.address,abi:p.U,functionName:"decimals",args:[]}).catch(()=>18),Tt.readContract(H,{address:$.address,abi:p.U,functionName:"symbol",args:[]}).catch(()=>"TOKEN"),Tt.readContract(H,{address:$.address,abi:p.U,functionName:"name",args:[]}).catch(()=>"TOKEN")]);ee=Number(Ft),Re=pt,Fe=It}const ot=!!m&&p.addressesEqual($.address,m)&&$.chainId===l;ot&&r&&(Pe=r),ot&&a&&!$.configToken&&(Re==="TOKEN"&&(Re=a),Fe==="TOKEN"&&(Fe=a));const Qt=parseFloat((Number(ue)/Math.pow(10,ee)).toFixed(6));return{address:$.address,name:Fe,symbol:Re,decimals:ee,balance:ue,balanceFormatted:Qt,balanceUsd:0,logoURI:Pe,isNative:!1,chainId:$.chainId}}catch{return null}},ht=await Promise.all(Array.from(Ee.entries()).map(async([H,$])=>{let ue;try{ue=p.getClientForChain(H)}catch{return[]}const ee=[],Re=[];for(const Pe of $){const ot=ee.length;ee.push({address:Pe.address,abi:p.U,functionName:"balanceOf",args:[ye]}),Pe.configToken||ee.push({address:Pe.address,abi:p.U,functionName:"decimals",args:[]},{address:Pe.address,abi:p.U,functionName:"symbol",args:[]},{address:Pe.address,abi:p.U,functionName:"name",args:[]}),Re.push({start:ot,item:Pe})}let Fe=null;try{Fe=await ue.multicall({contracts:ee})}catch{Fe=null}return Fe?Re.map(({start:Pe,item:ot})=>{const Qt=Fe[Pe],Ft=Qt?.status==="success"?Qt.result:0n;let pt,It,Xt,an;if(ot.configToken)pt=ot.configToken.decimals,It=ot.configToken.symbol,Xt=ot.configToken.name,an=ot.configToken.logo;else{const we=Fe[Pe+1],de=Fe[Pe+2],Be=Fe[Pe+3];pt=we?.status==="success"?Number(we.result):18,It=de?.status==="success"?de.result:"TOKEN",Xt=Be?.status==="success"?Be.result:It}const xn=!!m&&p.addressesEqual(ot.address,m)&&ot.chainId===l;xn&&r&&(an=r),xn&&a&&!ot.configToken&&(It==="TOKEN"&&(It=a),Xt==="TOKEN"&&(Xt=a));const yn=parseFloat((Number(Ft)/Math.pow(10,pt)).toFixed(6));return{address:ot.address,name:Xt,symbol:It,decimals:pt,balance:Ft,balanceFormatted:yn,balanceUsd:0,logoURI:an,isNative:!1,chainId:ot.chainId}}):(await Promise.all($.map(Pe=>lt(ue,Pe)))).filter(Pe=>Pe!==null)}));if(Z!==ut.current)return;const qt=ht.flat();et(qt)},[x,at,jt,be,l,m,r,a]);c.useEffect(()=>{if(!e||!x){et([]);return}xt();const Z=setInterval(()=>{xt()},15e3);return()=>clearInterval(Z)},[xt,x,e]);const Gt=c.useCallback(()=>{xt()},[xt]),Lt=c.useMemo(()=>Dt.filter(Z=>Z.balance>0n),[Dt]),Xe=c.useMemo(()=>{if(z)return Lt.map(ye=>({...ye,_source:"wallet"}));if(!x)return dt;const Z=[];for(const ye of Lt)Z.push({...ye,_source:"wallet"});for(const ye of dt)Z.push({...ye,_source:"spice"});return Z},[z,x,Lt,dt]),_t=c.useMemo(()=>U?m?Xe.filter(Z=>p.addressesEqual(Z.address,m)&&Z.chainId===l):[]:Xe,[Xe,U,m,l]),Te=c.useRef(null),ft=c.useRef(null);c.useEffect(()=>{ft.current=P},[P]),c.useEffect(()=>{!U||!P?.asset||m&&p.addressesEqual(P.asset.address,m)&&P.asset.chainId===l||ne(null)},[U,P?.asset,m,l]),c.useEffect(()=>{e||(ne(null),X(null),xe(null),J(!1),ae(!1),We(null),V(!1),ie(!1),_(null),Ke(!1),Qe())},[e,Qe]),c.useEffect(()=>{i&&i.assetAmount!==(P?.amount||"")&&ne(Z=>Z&&{...Z,amount:i.assetAmount})},[i?.assetAmount]),c.useEffect(()=>{d&&d.assetAmount!==(P?.amount||"")&&ne(Z=>Z&&{...Z,amount:d.assetAmount})},[d?.assetAmount]),c.useEffect(()=>{if(!z&&Ge?.overallStatus==="success"&&Ge.intentId&&Te.current!==Ge.intentId&&Ie&&Ge.steps.find(Z=>Z.transactionHash)?.transactionHash){Te.current=Ge.intentId;const Z=ft.current;if(!Z?.asset||!Z.amount||Z.asset._source==="wallet"||j.parseUnits(Z.amount,Z.asset.decimals)===0n)return;_e()}},[Ge,Ie,l,_e,z]);const Oe=parseFloat(P?.amount||"")||0,yt=c.useMemo(()=>P?.asset?P.asset._source==="wallet"?P.asset.balanceFormatted??0:dt.find(Z=>p.addressesEqual(Z.address,P.asset.address)&&Z.chainId===P.asset.chainId)?.balanceFormatted??0:0,[P?.asset,dt]),qe=Oe>0&&(Ce?parseFloat(j.formatUnits(Ce.grossAmount,Ce.decimals))>yt:Oe>yt),Ct=u?.selectedDuration??h[pe]??h[0],Ue=c.useMemo(()=>!P?.asset||!m?!1:p.addressesEqual(P.asset.address,m)&&P.asset.chainId===l,[P?.asset,m,l]),Je=c.useMemo(()=>Oe<=0?0:Ue?Oe:!S||S<=0?0:Oe/S,[Oe,S,Ue]),He=c.useMemo(()=>Je<=0?null:Je.toLocaleString(void 0,{maximumFractionDigits:2}),[Je]),bt=f&&Je>0&&Ct?f(Je,Ct.months):void 0,tt=c.useMemo(()=>Oe<=0?"$0.00":Ue&&S?(Oe*S).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!S||S<=0?"$0.00":Oe.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[Oe,S,Ue]),Ot=c.useMemo(()=>{if(!He)return null;const Z=parseFloat(He.replace(/,/g,""));return Ue&&S?(Z*S).toLocaleString(void 0,{maximumFractionDigits:2}):S?(Z*S).toLocaleString(void 0,{maximumFractionDigits:2}):null},[He,S,Ue]),De=c.useCallback(Z=>{ne(ye=>({asset:Z,amount:ye?.asset?.address===Z.address&&ye?.asset?.chainId===Z.chainId&&ye.amount||""})),X(null),xe(null),ae(!1),We(null),d?.setSelectedAsset&&d.setSelectedAsset({symbol:Z.symbol,address:Z.address,decimals:Z.decimals,chainId:Z.chainId})},[d?.setSelectedAsset]),Vt=c.useCallback(Z=>{ne(ye=>ye&&{...ye,amount:Z}),X(null),xe(null),ae(!1),We(null),i&&i.setAssetAmount(Z),d&&d.setAssetAmount(Z)},[i,d]),Ht=c.useCallback(Z=>{if(typeof o=="function"){if(!P?.asset||!P.amount)throw new Error("Select an asset and enter an amount");return o({asset:P.asset,amount:Z?.amount??P.amount,amountWei:Z?.amountWei??j.parseUnits(P.amount,P.asset.decimals),grossAmount:Z?.grossAmount,grossAmountWei:Z?.grossAmountWei,feeAdjusted:!!Z})}return o},[o,P]),St=c.useRef(null),te=c.useMemo(()=>!P?.asset||Oe<=0?!1:z?!Ue&&!b:!0,[P,Oe,z,Ue,b]),se=c.useCallback(()=>zi(St.current),[]);c.useEffect(()=>{if(!e||fe)return;if(!P?.asset||Oe<=0){xe(null),J(!1),ae(!1),We(null);return}if(!te){xe(null),J(!1),ae(!0),We(null);return}let Z=!1;const ye=async()=>{const Ee=++Ze.current;xe(null),ae(!1),J(!0);try{const lt=await se();if(Z||Ze.current!==Ee)return;xe(null),ae(!0),We(lt)}catch(lt){if(Z||Ze.current!==Ee)return;xe(p.sanitizeError(lt,"Unable to calculate fees for this lock.")),ae(!1)}finally{!Z&&Ze.current===Ee&&J(!1)}},Ae=window.setTimeout(()=>{ye()},250),je=window.setInterval(()=>{ye()},1e4);return()=>{Z=!0,clearTimeout(Ae),window.clearInterval(je),J(!1),ae(!1)}},[e,fe,P,Oe,te,se]),c.useEffect(()=>{if(Ge?.overallStatus==="success"){const Z=Ge.steps.find(ye=>ye.transactionHash);y?.(Z?.transactionHash)}},[Ge?.overallStatus,y]);const ve=x&&P?.asset?._source==="wallet"&&P?.asset?.chainId===l,ze=c.useCallback(()=>Oi(St.current),[]),nt=!!P?.asset&&Oe>0&&!qe&&!fe&&(!te||Y&&!Se&&!le),Le=re||le,Ve=n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[n.jsx(bs,{color:O}),n.jsxs("p",{style:{fontSize:"13px",color:O,margin:0,lineHeight:"1.5"},children:["Add ",a," by converting assets from your account"]})]});if(St.current={selectedAsset:P,parsedAmount:Oe,selectedDuration:Ct,isInsufficientBalance:qe,isSemi7702:z,isSourceDestToken:Ue,isDirectDeposit:ve,requiresRelayerFeeEstimate:te,address:Ie,embeddedWalletAddress:Et,providerEmbeddedAddress:gt,externalWallet:Yt,externalWalletAddress:he,isConnected:mt,ready:Pt,authenticated:Rt,provider:Mt,actions:Zt,lockChainId:l,escrowAddress:g,onLockExecute:b,onLockSuccess:y,buildSpicenetBatch:v,resolveLockBatches:Ht,startStatusPolling:vt,refreshSpiceAssets:_e,refreshWalletAssets:Gt,ui:{setError:X,setIsExecuting:V,setShowStatusPanel:Ke}},!e)return null;const Ne={backgroundColor:N,border:L,borderRadius:q,padding:"16px",marginBottom:"16px"};return n.jsx(tn,{isOpen:e,onClose:t,title:`Add ${a} to your account`,subtitle:Ve,styles:k,dark:R,footerLinkText:"Spicenet accounts \u2192",overlayContent:oe?n.jsx("div",{}):void 0,closeOnBackdropClick:s,children:n.jsxs("div",{style:{padding:"0 24px 8px 24px",position:"relative"},children:[n.jsxs("div",{style:{marginBottom:"12px"},children:[C&&n.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:n.jsx(ws,{onClick:C,color:B,fontFamily:T})}),n.jsx("div",{style:{marginTop:"10px",fontSize:"13px",color:O,fontFamily:T},children:n.jsx(Dn,{assets:_t,selectedAsset:P??void 0,onAssetSelect:De,onAmountChange:Vt,label:"Amount",showBalance:!0,showMaxButton:!0,theme:ce,styles:G})}),n.jsx("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:O,fontFamily:T},children:tt})]}),n.jsxs("div",{style:Ne,children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:R?`1px solid ${I.cardBorder}`:"1px solid #e5e7eb"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[r?n.jsx("img",{src:r,alt:a,style:{width:"32px",height:"32px",borderRadius:"50%",objectFit:"cover"}}):n.jsx("div",{style:{width:"32px",height:"32px",borderRadius:"50%",backgroundColor:R?I.inputBg:"#d1d5db",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:700,color:K},children:a.slice(0,2)}),n.jsx("span",{style:{fontSize:"16px",fontWeight:600,color:K,fontFamily:T},children:a})]}),n.jsxs("div",{style:{textAlign:"right"},children:[n.jsx("div",{style:{fontSize:"22px",fontWeight:700,color:K,fontFamily:T,lineHeight:1.1},children:He??"0.00"}),n.jsxs("div",{style:{fontSize:"12px",color:O,fontFamily:T,marginTop:"2px"},children:["~$",Ot??"0.00"]})]})]}),n.jsxs("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:R?`1px solid ${I.cardBorder}`:"1px solid #e5e7eb"},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[n.jsx("span",{style:{fontSize:"15px",fontWeight:500,color:O,fontFamily:T},children:"Lock Duration"}),n.jsx(nn,{color:O})]}),n.jsx(Ai,{options:h,selectedIndex:pe,onSelect:ge,primaryColor:B,dark:R,textPrimary:K,textSecondary:O})]}),n.jsxs("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[n.jsx(ji,{durationMonths:Ct?.months,fontFamily:T,dark:R,textPrimary:K,textSecondary:O}),f&&n.jsx(Fi,{votes:bt,fontFamily:T,dark:R,textPrimary:K,textSecondary:O})]})]}),te&&n.jsx(Vn,{fontFamily:T,textPrimary:K,textSecondary:O,cardBg:N,cardBorder:L,resolvedDark:R,darkCardBorder:I.cardBorder,primaryColor:B,feePreview:Ce,isLoading:Se,errorText:le}),Le&&n.jsx(Sn,{variant:"error",palette:I,fontFamily:T,style:{marginBottom:"12px"},children:Le}),n.jsx(p.Button,{variant:"outline",fullWidth:!0,onClick:ze,disabled:!nt,loading:fe,dark:R,styles:{...k,button:{...k?.button,backgroundColor:B}},children:fe?ve&&!Ue?"DEPOSITING...":Ue?"LOCKING...":"CONVERTING...":Se&&te?"CALCULATING FEES...":ve&&!Ue?`DEPOSIT ${a}`:Ue?`LOCK ${a}`:`CONVERT TO ${a}`}),n.jsx(Bi,{isOpen:oe,data:Ye,isLocking:fe,lockError:Le,onContinue:ze,onClose:()=>ie(!1),primaryColor:B,fontFamily:T,dark:R}),Ge&&rt&&n.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:R?I.shell:"white",borderRadius:q,padding:"16px 0"},children:n.jsx(As,{type:"deposit",isOpen:!!Ge&&Ge.overallStatus!=="processing",isProcessing:fe||Ge?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{Qe(),Ke(!1),ze()},onNewTx:()=>{Qe(),Ke(!1),ne(null),Te.current=null,_e(),Gt()},onClose:()=>{Qe(),Ke(!1)},onComplete:()=>{Qe(),Ke(!1),ne(null),Te.current=null,_e(),Gt()},results:Ge?.overallStatus==="success"||Ge?.overallStatus==="failed"?Ge.steps.map(Z=>({asset:{symbol:P?.asset?.symbol||a,address:P?.asset?.address||""},txHash:Z.transactionHash||"",success:Z.status==="success",amount:P?.amount})):void 0,chainName:p.getChainName(l),explorerUrl:p.getExplorerUrl(l,"").replace(/\/tx\/.*$/,"")||void 0,theme:E,styles:k,dark:R})})]})})},Hi="0xa9059cbb";function Qi(e,t,s){return F.isNativeToken(e)?{to:s,value:t,data:"0x"}:{to:e,value:0n,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"transfer",args:[s,t]})}}function Ls(e,t,s,o){return t!=="user-transfer"||!s||e.length===0||e[0]?.to.toLowerCase()!==o.toLowerCase()||!e[0]?.data.startsWith(Hi)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function ts(e,t,s){if(!t)return[e];const o=await t(s);return o?[o,e]:[e]}function En(e,t,s){if(t===s)return e;if(t<s)return e*10n**BigInt(s-t);const o=10n**BigInt(t-s);return(e+o-1n)/o}async function Vi(e,t){const{currentPaymentAmount:s,destinationToken:o,embeddedWalletAddress:a,providerEmbeddedAddress:r,address:i,isNon7702:d,isPayMode:u,resolvedChainId:l,buildActionCalls:h,feeExecutionMode:f,buildSpicenetBatch:g,selectedAsset:x,needsSwap:m,exactOutputSwap:y,resolvedTokenIn:b}=e,S=j.parseUnits(s,o.decimals),w=t?.actionAmountOverride??S,C=a||r||(d?void 0:i);if(!C)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const v={userAddress:C,chainId:l,destinationToken:o.address,grossAmount:t?.fundingAmountOverride??S,netAmount:w,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:f,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},k=h(w,v),A={chainId:l,calls:k},E=(!u&&!d?!0:x?.asset?._source==="spice")||d,R=(B,I)=>({token:B,from:d?"solver":"escrow",to:C,amount:I});if(S===0n)return[A];if(m&&y){const B=b??$t(x.asset,l)??x.asset.address,I=t?.fundingAmountOverride??y.amountInMax,T=E?[R(B,I)]:[],D={to:B,value:0n,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"approve",args:[y.calls[0]?.to,y.amountInMax]})},M={chainId:l,calls:[D,...y.calls,...k],tokenTransfers:[...T,...A.tokenTransfers??[]]};return E?ts(M,g,{userAddress:C,destinationChainId:l,deliveryToken:B,deliveryAmount:I,deliveryRecipient:C,sourceAsset:x.asset}):[M]}if(E){const B=b??$t(x.asset,l)??o.address,I=t?.fundingAmountOverride??S,T={...A,tokenTransfers:[R(B,I),...A.tokenTransfers??[]]};return ts(T,g,{userAddress:C,destinationChainId:l,deliveryToken:B,deliveryAmount:I,deliveryRecipient:C,sourceAsset:x.asset})}return[A]}async function qi(e,t){const{selectedAsset:s,embeddedWalletAddress:o,externalWalletAddress:a,resolvedChainId:r,destinationToken:i,buildActionCalls:d,feeExecutionMode:u,buildSpicenetBatch:l,isPayMode:h,isNon7702:f,needsSwap:g,resolvedSwap:x,quoteAmountOut:m,resolvedTokenIn:y}=e,b=x?.amountOutMinimum??m;if(!s?.asset||!o)return[];const S=f?a:o;if(!S)return[];const w=t?.fundingAmountOverride??t?.actionAmountOverride??j.parseUnits(s.amount,s.asset.decimals),C=t?.fundingAmountOverride??w,v=t?.sourceFundingAmountOverride??w,k=t?.deliveryAmountOverride??C,A=t?.withdrawalAmountOverride??k,E=t?.actionAmountOverride??w,R={userAddress:S,chainId:r,destinationToken:i.address,feeToken:u==="user-transfer"&&g&&y?y:i.address,grossAmount:C,netAmount:E,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:u,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},B=d(E,R),I=s.asset?._source==="wallet";if(!h&&f&&I&&s.asset.chainId===r){if(g){if(!y)throw new Error("Swap input token could not be resolved");if(!x||b===null)throw new Error("Swap quote not available yet")}if(g&&x&&b){const L=d(t?.actionAmountOverride??b,{...R,netAmount:t?.actionAmountOverride??b}),{feeCall:q,remainingCalls:K}=Ls(L,u,g,R.feeToken);return[{chainId:r,calls:[...q?[q]:[],...x.calls,...K]}]}return[{chainId:r,calls:B}]}if(!h&&!f&&I){if(s.asset.chainId===r){if(g){if(!y)throw new Error("Swap input token could not be resolved");if(!x||b===null)throw new Error("Swap quote not available yet")}if(g&&x&&b){const L=d(t?.actionAmountOverride??b,{...R,netAmount:t?.actionAmountOverride??b}),{feeCall:q,remainingCalls:K}=Ls(L,u,g,R.feeToken);return[{chainId:r,calls:[...q?[q]:[],...x.calls,...K]}]}return[{chainId:r,calls:B}]}throw new Error("Cross-chain wallet supplies require external wallet mode")}const T=!h&&!f?s.asset?._source!=="wallet":s.asset?._source==="spice",D=f&&I;if(!(T||D))return[{chainId:r,calls:B}];const M=D&&s.asset.chainId!==r?{chainId:s.asset.chainId,calls:[Qi(F.normalizeNativeTokenAddress(s.asset.address),v,F.getEscrowContractAddress(s.asset.chainId))]}:null,U=(L,q)=>({token:L,from:D?"solver":"escrow",to:o,amount:q}),z=(L,q)=>D?[{token:L,from:"escrow",to:F.SPICE_SOLVER_ADDRESS,amount:q}]:[];if(g){if(!y)throw new Error("Swap input token could not be resolved");if(!x||b===null)throw new Error("Swap quote not available yet")}if(g&&x&&b&&y){const L=d(t?.actionAmountOverride??b,{...R,netAmount:t?.actionAmountOverride??b}),{feeCall:q,remainingCalls:K}=Ls(L,u,g,R.feeToken),O={chainId:r,calls:[...q?[q]:[],...x.calls,...K],tokenTransfers:[...z(y,A),U(y,k)]},G=await ts(O,l,{userAddress:o,destinationChainId:r,deliveryToken:y,deliveryAmount:k,withdrawalAmount:A,deliveryRecipient:o,sourceAsset:s.asset});return M?[M,...G]:G}const W=y??$t(s.asset,r)??i.address,Q={chainId:r,calls:B,tokenTransfers:[...z(W,A),U(W,k)]},N=await ts(Q,l,{userAddress:o,destinationChainId:r,deliveryToken:W,deliveryAmount:k,withdrawalAmount:A,deliveryRecipient:o,sourceAsset:s.asset});return M?[M,...N]:N}async function Ki(e,t,s,o,a){let r=e;for(let i=0;i<4;i++){const d=await t(r),u=await o(d,s,r,a),l=ei(u);if(l===null||l>=e)return r;const h=r-l,f=e+h;if(f<=r)return r;r=f}return r}function Zi(e,t,s,o){if(e<=0n)return 0n;const a=e-t;if(a<=0n)return 0n;const r=o+s;return r<=0n?a:a*o/r}function Yi(e,t){const s=j.formatUnits(e,t);return s.includes(".")?s.replace(/\.?0+$/,"")||"0":s}async function Gi(e){const{asset:t,isPayMode:s,isNon7702:o,needsSwap:a,isQuoting:r,embeddedWalletAddress:i,buildSupplyChainBatches:d,estimateGasless:u,executionTokenAddress:l,feeExecutionMode:h}=e;if(s||o||a||r||!i||t.balance<=0n)return null;const f=i,g=await d({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(g.length===0)return null;const x=g.some(C=>C.tokenTransfers?.length),m=await u(g,l,t.balance,x?{userOverride:f,useCustomTransfers:!0,feeExecutionMode:h}:h?{userOverride:f,feeExecutionMode:h}:{userOverride:f}),y=hn(m,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),b=y?En(y.gasFee,y.decimals,t.decimals):0n,S=y?En(y.spicenetFee,y.decimals,t.decimals):0n,w=Zi(t.balance,b,S,t.balance);return w>0n?Yi(w,t.decimals):null}async function Xi(e){const{selectedAsset:t,isPayMode:s,parsedAmount:o,needsSwap:a,exactOutputSwap:r,isNon7702:i,isSourceDestToken:d,currentPaymentAmount:u,destinationToken:l,feeExecutionMode:h,resolvedTokenIn:f,embeddedWalletAddress:g,providerEmbeddedAddress:x,resolvedChainId:m,isConnected:y,address:b,ready:S,authenticated:w,isDirect:C,resolvedSwap:v,isQuoting:k,executionTokenAddress:A,buildPayChainBatches:E,buildSupplyChainBatches:R,estimateGasless:B,estimateRequiredGrossFunding:I}=e;if(!t?.asset)return null;if(s){if(o<=0||a&&!r||i&&d)return null;const N=j.parseUnits(u,l.decimals),L=f||$t(t.asset,m)||t.asset.address||l.address,q={chainId:m,tokenAddress:L,symbol:F.getTokenByAddress(L,m)?.symbol??t.asset.symbol,decimals:F.getTokenByAddress(L,m)?.decimals??t.asset.decimals};if(i){const ne=g||x;if(!ne)return null;const me=ne,ke=a?r?.amountInMax??0n:N;if(ke===0n)return null;const pe=await I(ke,V=>E({fundingAmountOverride:V}).then(re=>Ut(re,me)),L,{userOverride:ne,useCustomTransfers:!0}),ge=Ut(await E({fundingAmountOverride:pe}),me),fe=await B(ge,L,pe,{userOverride:ne,useCustomTransfers:!0,feeExecutionMode:h});return hn(fe,q)}if(!y||!b||!S||!w)return null;const K=g||x||b,O=a?r?.amountInMax??0n:N;if(O===0n)return null;const G=await I(O,ne=>E({fundingAmountOverride:ne}).then(me=>Ut(me,K)),L,{useCustomTransfers:!0});let ce=Ut(await E({fundingAmountOverride:G}),K);const P=await B(ce,L,G,{useCustomTransfers:!0,feeExecutionMode:h});return hn(P,q)}if(o<=0||!g)return null;const T=g||x;if(!(!s&&!i&&t.asset?._source==="wallet"&&t.asset.chainId!==m)&&!C&&!v&&!k||k)return null;const D=j.parseUnits(t.amount,t.asset.decimals),M=await R();if(M.length===0)return null;const U=i&&t.asset?._source==="wallet"&&t.asset.chainId===m,z={chainId:m,tokenAddress:A,symbol:F.getTokenByAddress(A,m)?.symbol??l.symbol,decimals:F.getTokenByAddress(A,m)?.decimals??l.decimals};if(U){const N=await p.relayerService.estimateBatchGas({user:T,outputToken:A,stepIndex:0,chainBatches:M}),L=Bs(D,10n),q=L+N.gasFee;return{...z,grossAmount:D+q,netAmount:D,totalFee:q,gasFee:N.gasFee,spicenetFee:L,bridgeFee:0n,gasQuoteSource:N.gasQuoteSource}}const W=M.some(N=>N.tokenTransfers?.length),Q=await B(M,A,D,W?{userOverride:T,useCustomTransfers:!0,feeExecutionMode:h}:h?{userOverride:T,feeExecutionMode:h}:{userOverride:T});return hn(Q,z)}function Yo(e,t){const s=e.selectedAsset?.asset;if(!s||s?._source!=="wallet")return;const o=$t(s,e.resolvedChainId);if(!o||!p.addressesEqual(o,e.executionTokenAddress))return;const a=F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),r=En(t,a?.decimals??e.destinationToken.decimals,s.decimals);if(r<=s.balance)return;const i=j.formatUnits(r,s.decimals),d=j.formatUnits(s.balance,s.decimals);throw new Error(`Insufficient ${s.symbol} for amount plus fees. Required ${i} ${s.symbol}; available ${d} ${s.symbol}.`)}async function Ji(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){if(!e.externalWalletAddress){e.ui.setError("Please connect your external 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 s=await Go(e);e.ui.setTxHash(s??null)}else{e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.refs.spiceDepositSubmittedRef.current=!1;const s=new AbortController;e.refs.abortControllerRef.current=s,await $i(e,s.signal)}e.ui.setStep("success"),e.ui.setStatusMsg(e.isSourceDestToken?"Transaction confirmed":"Deposit confirmed")}catch(s){const o=s instanceof Error?s:new Error(String(s));if(o.name==="AbortError"||e.refs.abortControllerRef.current?.signal.aborted){e.ui.setStep("idle");return}const a=o.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(a),e.ui.setError(a),e.onError?.(o)}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 s=j.parseUnits(e.selectedAsset.amount,e.selectedAsset.asset.decimals),o=s;let a=await e.gasless.buildSupplyChainBatches();const r=e.selectedAsset.asset?._source==="wallet",i=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!r&&!a.some(g=>F.isSpicenetChainId(g.chainId)))throw new Error("Spice-funded supplies must include a Spicenet funding batch before the destination chain batch.");const d=a.some(g=>g.tokenTransfers?.length)?{userOverride:i,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}:e.feeExecutionMode?{userOverride:i,feeExecutionMode:e.feeExecutionMode}:{userOverride:i};let u=s;const l=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,h=e.feeExecutionMode==="user-transfer"&&!l?o:void 0;let f;for(let g=0;g<4;g+=1){const x=await e.gasless.estimateGasless(a,e.executionTokenAddress,u,d),m=hn(x,{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId)?.symbol??e.destinationToken.symbol,decimals:F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId)?.decimals??e.destinationToken.decimals}),y=m?.grossAmount??u;if(f=e.feeExecutionMode==="user-transfer"&&m?{grossAmount:m.grossAmount,netAmount:o,combinedFeeAmount:m.totalFee,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:m.spicenetFee,gasFee:m.gasFee,bridgeFee:m.bridgeFee??0n}}:void 0,e.feeExecutionMode==="user-transfer"&&m){u=y;break}if(y===u){u=y;break}u=y,a=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:h,actionContextOverride:f})}e.feeExecutionMode==="user-transfer"&&(Yo(e,u),a=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:h,actionContextOverride:f})),await e.gasless.executeGasless(a,e.executionTokenAddress,u,e.gasless.onProgress,t.signal,d),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(s){const o=s instanceof Error?s:new Error(String(s));if(o.name==="AbortError"||t.signal.aborted){e.ui.setStep("idle");return}const a=o.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(a),e.ui.setError(a),e.onError?.(o)}finally{e.ui.setIsExecuting(!1)}}async function $i(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 s=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!s)throw new Error("Embedded wallet not available \u2014 sign in to create one before supplying");const o=e.selectedAsset.asset,a=j.parseUnits(e.selectedAsset.amount,o.decimals),r=a,i=o?._source==="wallet"&&o.chainId===e.resolvedChainId;let d=await e.gasless.buildSupplyChainBatches();const u={userOverride:s,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode};let l=a;const h=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,f=e.feeExecutionMode==="user-transfer"&&!h?r:void 0;let g;if(i){const R=await p.relayerService.estimateBatchGas({user:s,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:d}),B=Bs(a,10n),I=B+R.gasFee;l=a+I,e.feeExecutionMode==="user-transfer"&&(g={grossAmount:l,netAmount:r,combinedFeeAmount:I,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:B,gasFee:R.gasFee,bridgeFee:0n}})}else{const R=await e.gasless.estimateGasless(d,e.executionTokenAddress,0n,u),B=hn(R,{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId)?.symbol??e.destinationToken.symbol,decimals:F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId)?.decimals??e.destinationToken.decimals});B&&(l=B.grossAmount>a?B.grossAmount:a,e.feeExecutionMode==="user-transfer"&&(g={grossAmount:l,netAmount:r,combinedFeeAmount:B.totalFee,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:B.spicenetFee,gasFee:B.gasFee,bridgeFee:B.bridgeFee??0n}}))}const x=F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),m=i?l:En(l,x?.decimals??e.destinationToken.decimals,o.decimals);Yo(e,l),d=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:l,sourceFundingAmountOverride:m,withdrawalAmountOverride:l,actionAmountOverride:f,actionContextOverride:g});const y=o.chainId,b=s,S=await e.externalWallet.getEthereumProvider();let w=null;try{const R=await S.request({method:"eth_chainId"});w=parseInt(R,16)}catch{w=null}w!==y&&(e.ui.setStatusMsg("Switching source network..."),await p.ensureWalletOnChain(S,y));const C=p.getChainConfig(y),v=j.createWalletClient({account:e.externalWalletAddress,chain:C?.viemChain,transport:j.custom(S)}),k=F.normalizeNativeTokenAddress(o.address),A=o.isNative||F.isNativeToken(k);e.ui.setStatusMsg("Funding embedded wallet...");const E=A?await v.sendTransaction({to:b,value:m,chain:C?.viemChain}):await v.sendTransaction({to:k,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"transfer",args:[b,m]}),chain:C?.viemChain});if((await p.getClientForChain(y).waitForTransactionReceipt({hash:E,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Embedded wallet funding failed");e.ui.setStatusMsg("Signing supply intent..."),await e.gasless.executeGasless(d,e.executionTokenAddress,0n,e.gasless.onProgress,t,u)}async function Go(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=j.parseUnits(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),s={userAddress:e.externalWalletAddress,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},o=e.buildActionCalls(t,s);if(o.length===0)throw new Error("No action calls configured");const a=await e.externalWallet.getEthereumProvider();let r=null;try{const h=await a.request({method:"eth_chainId"});r=parseInt(h,16)}catch{r=null}r!==e.resolvedChainId&&await p.ensureWalletOnChain(a,e.resolvedChainId);const i=p.getChainConfig(e.resolvedChainId),d=j.createWalletClient({account:e.externalWalletAddress,chain:i?.viemChain,transport:j.custom(a)}),u=p.getClientForChain(e.resolvedChainId);let l;for(const h of o){const f=await d.sendTransaction({to:h.to,data:h.data,value:h.value,chain:i?.viemChain});if((await u.waitForTransactionReceipt({hash:f,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transaction failed");l=f}return l}async function _i(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 s=e.selectedAsset.asset,o=s.chainId,a=j.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),r=e.selectedIsEquivalent?a:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(r===0n)throw new Error("Quote not available yet");const i=e.resolvedTokenIn||e.selectedAsset.asset.address,d={userOverride:t,useCustomTransfers:!0},u=await e.gasless.estimateRequiredGrossFunding(r,w=>e.gasless.buildPayChainBatches({fundingAmountOverride:w}),i,d),l=F.getEscrowContractAddress(o),h=await e.externalWallet.getEthereumProvider();let f=null;try{const w=await h.request({method:"eth_chainId"});f=parseInt(w,16)}catch{f=null}f!==o&&await p.ensureWalletOnChain(h,o);const g=p.getChainConfig(o),x=j.createWalletClient({account:e.externalWalletAddress,chain:g?.viemChain,transport:j.custom(h)}),m=F.normalizeNativeTokenAddress(s.address),y=s.isNative||F.isNativeToken(m)?await x.sendTransaction({to:l,value:u,chain:g?.viemChain}):await x.sendTransaction({to:m,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"transfer",args:[l,u]}),chain:g?.viemChain});if((await p.getClientForChain(o).waitForTransactionReceipt({hash:y,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Escrow deposit failed");const b=await e.gasless.buildPayChainBatches({fundingAmountOverride:u}),S=b.some(w=>w.tokenTransfers?.length);return await e.gasless.executeGasless(b,i,u,w=>{w.txHash&&(e.ui.setPaymentResult(C=>({...C??{status:"processing"},txHash:w.txHash})),e.ui.setTxHash(w.txHash))},void 0,S?d:{userOverride:t})}async function el(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}if(!e.selectedAsset?.asset){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){if(!e.externalWalletAddress){e.ui.setError("Please connect your external wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{let t;if(e.isSourceDestToken||e.parsedAmount===0)t=await Go(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const s=e.selectedAsset.asset,o=j.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),a=e.selectedIsEquivalent?o:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(a===0n)throw new Error("Quote not available yet");const r=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!r)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const i=e.resolvedTokenIn||s.address,d=await e.gasless.estimateRequiredGrossFunding(a,h=>e.gasless.buildPayChainBatches({fundingAmountOverride:h}),i,{userOverride:r,useCustomTransfers:!0}),u=await e.gasless.buildPayChainBatches({fundingAmountOverride:d}),l=await e.onPayExecute({asset:s,amount:e.currentPaymentAmount,amountWei:o,destinationToken:e.destinationToken,chainBatches:u,requiredNetFunding:a,grossFundingAmount:d,selectedIsEquivalent:e.selectedIsEquivalent,resolvedTokenIn:i,exactOutputSwapAmountInMax:e.exactOutputSwap?.amountInMax});l&&(e.ui.setTxHash(l),e.ui.setPaymentResult(h=>({...h??{status:"processing"},txHash:l}))),t=l||void 0}else t=await _i(e);e.ui.setPaymentResult(s=>({status:"success",txHash:s?.txHash||t||""}))}catch(t){const s=p.sanitizeError(t,"Payment failed. Please try again.");e.ui.setError(s),e.ui.setPaymentResult({status:"failed",error:s}),e.onError?.(t instanceof Error?t:new Error(s))}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 t=j.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),s=e.resolvedTokenIn||e.selectedAsset?.asset?.address||e.destinationToken.address,o=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:t,a={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode},r=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,i=await e.gasless.estimateRequiredGrossFunding(o,x=>e.gasless.buildPayChainBatches({fundingAmountOverride:x}).then(m=>Ut(m,r)),s,a);let d=i,u=Ut(await e.gasless.buildPayChainBatches({fundingAmountOverride:i}),r);const l=await e.gasless.estimateGasless(u,s,i,a),h=hn(l,{chainId:e.resolvedChainId,tokenAddress:s,symbol:F.getTokenByAddress(s,e.resolvedChainId)?.symbol??e.selectedAsset.asset.symbol,decimals:F.getTokenByAddress(s,e.resolvedChainId)?.decimals??e.selectedAsset.asset.decimals})?.grossAmount??i;h!==i&&(d=h),u=Ut(await e.gasless.buildPayChainBatches({fundingAmountOverride:d}),r,l,{payoutAlreadyGross:!0});const f=u.some(x=>x.tokenTransfers?.length),g=await e.gasless.executeGasless(u,s,f?d:0n,x=>{x.txHash&&(e.ui.setPaymentResult(m=>({...m,txHash:x.txHash})),e.ui.setTxHash(x.txHash))},void 0,a);e.ui.setPaymentResult(x=>({status:"success",txHash:x?.txHash||g}))}catch(t){const s=p.sanitizeError(t,"Payment failed. Please try again.");e.ui.setError(s),e.ui.setPaymentResult({status:"failed",error:s}),e.onError?.(t instanceof Error?t:new Error(s))}finally{e.ui.setIsExecuting(!1)}}const Xo=({variant:e,destinationSymbol:t,destinationLogoURI:s,destinationDecimals:o,primaryColor:a,fontFamily:r,textPrimary:i,textSecondary:d,cardBg:u,cardBorder:l,dk:h,dark:f,isQuoting:g,quoteError:x,estimatedOutput:m,paymentAmount:y,needsSwap:b,exactOutputSwap:S,adjustable:w=!1,maxAmount:C,onAmountChange:v})=>e==="supply"?n.jsxs("div",{style:{backgroundColor:u,border:`1px solid ${l}`,borderRadius:f?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",minHeight:"112px",display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"12px"},children:[n.jsxs("div",{style:{minWidth:0},children:[n.jsx("span",{style:{fontFamily:r,fontSize:"17px",fontWeight:500,color:f?"#a7abb2":"#7D7C7B",lineHeight:"24px"},children:"Used in TX"}),n.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:d,fontFamily:r,marginTop:"10px"},children:"Net amount after swap and fees"})]}),n.jsxs("div",{style:{textAlign:"right",minWidth:0,display:"inline-flex",alignItems:"center",gap:"8px",border:`1px solid ${l}`,borderRadius:"8px",padding:"8px 10px",minHeight:"42px"},children:[n.jsx(Jo,{symbol:t,logoURI:s,primaryColor:a,size:24}),n.jsx("span",{style:{fontSize:"16px",fontWeight:500,color:f?"#f3f4f6":"#3C3E42",lineHeight:"1.3",fontFamily:r,letterSpacing:0},children:t})]})]}),n.jsx("div",{style:{textAlign:"right",minWidth:0},children:g?n.jsx("span",{style:{fontSize:"18px",color:d,fontFamily:r},children:"Quoting..."}):x?n.jsx("span",{style:{fontSize:"13px",color:f?"#f87171":"#dc2626",fontFamily:r},children:"Quote failed"}):m?n.jsx(fn,{value:m,title:m,fontFamily:r,color:i,lineHeight:"0.95",textAlign:"right",maxFontSize:32,minFontSize:18}):n.jsx("span",{style:{fontSize:"20px",color:d,fontFamily:r},children:"\u2014"})})]}):n.jsx(tl,{destinationSymbol:t,destinationLogoURI:s,destinationDecimals:o,primaryColor:a,fontFamily:r,textPrimary:i,textSecondary:d,cardBg:u,cardBorder:l,dk:h,dark:f,paymentAmount:y||"0",needsSwap:b,exactOutputSwap:S,isQuoting:g,adjustable:w,maxAmount:C,onAmountChange:v}),Jo=({symbol:e,logoURI:t,primaryColor:s,size:o})=>t?n.jsx("img",{src:t,alt:e,style:{width:o,height:o,borderRadius:"50%",objectFit:"cover"}}):n.jsx("div",{style:{width:o,height:o,borderRadius:"50%",backgroundColor:`${s}22`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:o<30?"11px":"12px",fontWeight:700,color:s},children:e.slice(0,2)}),tl=({destinationSymbol:e,destinationLogoURI:t,destinationDecimals:s,primaryColor:o,fontFamily:a,textPrimary:r,textSecondary:i,cardBg:d,cardBorder:u,dk:l,dark:h,paymentAmount:f,needsSwap:g,exactOutputSwap:x,isQuoting:m,adjustable:y,maxAmount:b,onAmountChange:S})=>{const w='"IBM Plex Mono", monospace',C=parseFloat(f||"0"),v=b?parseFloat(b):0,[k,A]=c.useState(f||""),E=c.useRef(null),[R,B]=c.useState(null),[I,T]=c.useState(null);c.useEffect(()=>{y||A(f||"")},[f,y]);const D=z=>{let W=z;W.startsWith(".")&&(W="0"+W);const Q=wn(W);let N=Q;b&&parseFloat(Q)>parseFloat(b)&&(N=b),A(N),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>S?.(N),300)},M=z=>{if(!v)return;if(z===100){A(b||v.toString()),E.current&&clearTimeout(E.current),S?.(b||v.toString());return}const W=10**s,Q=Math.floor(v*z/100*W)/W,N=kn(Q,s);A(N),E.current&&clearTimeout(E.current),S?.(N)},U=v>0?parseFloat(k||"0")/v*100:0;return c.useEffect(()=>()=>{E.current&&clearTimeout(E.current)},[]),n.jsxs("div",{style:{backgroundColor:d,border:`1px solid ${u}`,borderRadius:h?"12px":"6px",padding:"16px",marginBottom:"16px"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[n.jsx(Jo,{symbol:e,logoURI:t,primaryColor:o,size:32}),n.jsxs("div",{children:[n.jsx("span",{style:{fontSize:"14px",fontWeight:600,color:r,fontFamily:a},children:"Payment"}),n.jsx("div",{style:{fontSize:"12px",color:i,fontFamily:a,marginTop:"2px"},children:e})]})]}),n.jsxs("div",{style:{textAlign:"right"},children:[y?n.jsx(fn,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:k,onChange:z=>D(z.target.value),placeholder:"0.0",fontFamily:w,color:r,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):n.jsx(fn,{element:"div",value:C>0?f:"0.00",title:C>0?f:"0.00",fontFamily:w,color:r,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),n.jsx("div",{style:{fontSize:"12px",color:i,fontFamily:w,marginTop:"2px"},children:e}),y&&v>0&&n.jsx("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((z,W)=>{const Q=Math.abs(U-z)<1,N=W===4,L=z/100,q=R===z,K=I===z;return n.jsx("button",{onClick:()=>M(z),onMouseEnter:()=>B(z),onMouseLeave:()=>{B(null),T(null)},onMouseDown:()=>T(z),onMouseUp:()=>T(null),title:`${z}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:Q?1:q?.8:.5,transform:K?"scale(0.85)":q?"scale(1.15)":"scale(1)",transition:Wt.interactive},children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[n.jsx("circle",{cx:"7",cy:"7",r:"6.84375",fill:N?o:"none",stroke:N?o:h?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!N&&L>0&&n.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${L>.5?1:0} 1 ${7+6.84375*Math.sin(L*2*Math.PI)} ${7-6.84375*Math.cos(L*2*Math.PI)} Z`,fill:h?l?.textSecondary||"#9ca3af":"#3C3E42"})]})},z)})})]})]}),g&&x&&!m&&n.jsx("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:h?`1px solid ${l?.cardBorder||u}`:"1px solid #e5e7eb",display:"flex",justifyContent:"flex-end"},children:n.jsxs("span",{style:{fontSize:"11px",color:i,fontFamily:a,opacity:.7},children:["via ",x.venue]})})]})};function $o(e,t,s){const o=p.addressesEqual(e.address,t),a=e.chainId===s,r=e._source==="wallet";return r&&o&&a?0:r&&a?1:!r&&o?2:!r&&a?3:4}function nl(e,t){return!t||t.length===0||t.some(s=>p.addressesEqual(s,e.address))?!0:Object.keys(e.chainTokens??{}).some(s=>{const o=An(s);return o?t.some(a=>p.addressesEqual(a,o.address)):!1})}function sl(e){const{destinationToken:t,supportedSourceAssets:s,sourceChains:o,enabled:a}=e,r=(c.useContext(p.SpiceFlowProviderContext)?.mode||"7702")!=="7702",i=p.useEmbeddedWalletAddress(),{externalAddress:d,embeddedAddress:u}=p.useProviderWallets(),l=i||u,{assets:h,refetch:f}=Wn({address:l,supportedChains:o,enabled:a&&!r&&!!l,refetchInterval:3e4}),g=c.useMemo(()=>r?[]:h.filter(A=>nl(A,s)),[h,s,r]),x=r?d:i,m=c.useMemo(()=>{const A=new Set,E=[],R=B=>{if(!B)return;const I=B.toLowerCase();A.has(I)||(A.add(I),E.push(j.getAddress(B)))};if(R(t.address),r&&s)for(const B of s)R(B);return E},[r,t.address,s]),y=c.useMemo(()=>m.map(A=>A.toLowerCase()).sort().join(","),[m]),b=c.useMemo(()=>JSON.stringify([...o||[]].sort()),[o]),[S,w]=c.useState([]),C=c.useRef(0),v=c.useCallback(async()=>{if(!a||!x||m.length===0){C.current++,w([]);return}const A=++C.current,E=j.getAddress(x),R=r?o&&o.length>0?o:[t.chainId]:[t.chainId],B=[];for(const M of m){const U=M.toLowerCase();if(U===F.ZERO_ADDRESS)continue;if(U===t.address.toLowerCase()){const W=p.getChainConfig(t.chainId)?.supportedTokens?.find(Q=>p.addressesEqual(Q.address,U));B.push({address:M,chainId:t.chainId,configToken:W?{decimals:W.decimals,symbol:W.symbol,name:W.name,logo:W.logo}:void 0});continue}let z=!1;for(const W of R){const Q=p.getChainConfig(W)?.supportedTokens?.find(N=>p.addressesEqual(N.address,U));if(Q){B.push({address:M,chainId:W,configToken:{decimals:Q.decimals,symbol:Q.symbol,name:Q.name,logo:Q.logo}}),z=!0;break}}z||B.push({address:M,chainId:t.chainId})}const I=new Map;for(const M of B){const U=I.get(M.chainId)||[];U.push(M),I.set(M.chainId,U)}const T=async(M,U)=>{try{const z=await Tt.readContract(M,{address:U.address,abi:j.erc20Abi,functionName:"balanceOf",args:[E]});let W,Q,N,L;if(U.configToken)W=U.configToken.decimals,Q=U.configToken.symbol,N=U.configToken.name,L=U.configToken.logo;else{const[O,G,ce]=await Promise.all([Tt.readContract(M,{address:U.address,abi:j.erc20Abi,functionName:"decimals"}).catch(()=>18),Tt.readContract(M,{address:U.address,abi:j.erc20Abi,functionName:"symbol"}).catch(()=>"TOKEN"),Tt.readContract(M,{address:U.address,abi:j.erc20Abi,functionName:"name"}).catch(()=>"TOKEN")]);W=Number(O),Q=G,N=ce}const q=p.addressesEqual(U.address,t.address)&&U.chainId===t.chainId;q&&t.logoURI&&(L=t.logoURI),q&&!U.configToken&&Q==="TOKEN"&&(Q=t.symbol,N=t.symbol);const K=parseFloat((Number(z)/Math.pow(10,W)).toFixed(6));return{address:U.address,name:N,symbol:Q,decimals:W,balance:z,balanceFormatted:K,balanceUsd:0,logoURI:L,isNative:!1,chainId:U.chainId}}catch{return null}},D=await Promise.all(Array.from(I.entries()).map(async([M,U])=>{let z;try{z=p.getClientForChain(M)}catch{return[]}const W=[],Q=[];for(const L of U){const q=W.length;W.push({address:L.address,abi:j.erc20Abi,functionName:"balanceOf",args:[E]}),L.configToken||W.push({address:L.address,abi:j.erc20Abi,functionName:"decimals"},{address:L.address,abi:j.erc20Abi,functionName:"symbol"},{address:L.address,abi:j.erc20Abi,functionName:"name"}),Q.push({start:q,item:L})}let N=null;try{N=await z.multicall({contracts:W})}catch{N=null}return N?Q.map(({start:L,item:q})=>{const K=N[L],O=K?.status==="success"?K.result:0n;let G,ce,P,ne;if(q.configToken)G=q.configToken.decimals,ce=q.configToken.symbol,P=q.configToken.name,ne=q.configToken.logo;else{const pe=N[L+1],ge=N[L+2],fe=N[L+3];G=pe?.status==="success"?Number(pe.result):18,ce=ge?.status==="success"?ge.result:"TOKEN",P=fe?.status==="success"?fe.result:ce}const me=p.addressesEqual(q.address,t.address)&&q.chainId===t.chainId;me&&t.logoURI&&(ne=t.logoURI),me&&!q.configToken&&ce==="TOKEN"&&(ce=t.symbol,P=t.symbol);const ke=parseFloat((Number(O)/Math.pow(10,G)).toFixed(6));return{address:q.address,name:P,symbol:ce,decimals:G,balance:O,balanceFormatted:ke,balanceUsd:0,logoURI:ne,isNative:!1,chainId:q.chainId}}):(await Promise.all(U.map(L=>T(z,L)))).filter(L=>L!==null)}));A===C.current&&w(D.flat())},[a,r,x,y,b,t.address,t.chainId,t.symbol,t.logoURI]);c.useEffect(()=>{if(!a){w([]);return}v();const A=setInterval(()=>{v()},15e3);return()=>clearInterval(A)},[v,a]);const k=c.useCallback(()=>{v()},[v]);return{displayAssets:c.useMemo(()=>{const A=[],E=S.filter(B=>B.balance>0n);for(const B of E)A.push({...B,_source:"wallet"});for(const B of g)A.push({...B,_source:"spice"});const R=t.address.toLowerCase();return A.sort((B,I)=>$o(B,R,t.chainId)-$o(I,R,t.chainId)),A},[S,g,t.address,t.chainId]),filteredSpiceAssets:g,walletAssets:S,embeddedWalletAddress:l,externalAddress:d,isNon7702:r,refreshSpiceAssets:f,refreshWalletAssets:k}}async function _o(e){const{tokenIn:t,tokenOut:s,amountIn:o,fee:a,chainId:r,config:i}=e;if(o<=0n)throw new Error("amountIn must be greater than 0");const d=(await p.getClientForChain(r).simulateContract({address:i.quoterV2,abi:F.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:s,amountIn:o,fee:a,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 er(e){const t=e.feeTiers??[100,500,3e3,1e4],s=await Promise.allSettled(t.map(a=>_o({...e,fee:a})));let o=null;for(let a=0;a<s.length;a++){const r=s[a];r.status==="fulfilled"&&(!o||r.value.amountOut>o.amountOut)&&(o={...r.value,fee:t[a]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}const ol=[{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 rl(e){const{tokenIn:t,tokenOut:s,amountOut:o,fee:a,chainId:r,config:i}=e;if(o<=0n)throw new Error("amountOut must be greater than 0");const d=(await p.getClientForChain(r).simulateContract({address:i.quoterV2,abi:ol,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:s,amount:o,fee:a,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 al(e){const t=e.feeTiers??[100,500,3e3,1e4],s=await Promise.allSettled(t.map(a=>rl({...e,fee:a})));let o=null;for(let a=0;a<s.length;a++){const r=s[a];r.status==="fulfilled"&&(!o||r.value.amountIn<o.amountIn)&&(o={...r.value,fee:t[a]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}function tr(e){return e.type==="swap"}const Os=.02,il=[1,8453,42161,10,137,43114,56],ll="https://api.1inch.dev/swap/v6.0";function nr(e,t){return F.applySlippage(e,t)}function sr(e){const t=e?.baseUrl??ll;return{name:"1inch",chainIds:e?.chainIds??il,resolve:async(s,o,a)=>{const r=s.maxSlippage??Os,i=r*100,d=F.isNativeToken(s.tokenIn)?F.NATIVE_TOKEN_ADDRESS:s.tokenIn,u=F.isNativeToken(s.tokenOut)?F.NATIVE_TOKEN_ADDRESS:s.tokenOut,l=F.isNativeToken(s.tokenIn);try{const h=new URL(`${t}/${o}/swap`);h.searchParams.set("src",d),h.searchParams.set("dst",u),h.searchParams.set("amount",s.amountIn.toString()),h.searchParams.set("from",a),h.searchParams.set("slippage",i.toString()),h.searchParams.set("disableEstimate","true"),h.searchParams.set("allowPartialFill","false");const f={Accept:"application/json"};e?.apiKey&&(f.Authorization=`Bearer ${e.apiKey}`);const g=await fetch(h.toString(),{headers:f});if(!g.ok)throw new p.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${g.status} for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}`,{venue:"1inch",chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn.toString(),cause:`HTTP ${g.status}`});const x=await g.json();if(!x.dstAmount||!x.tx)return console.warn(`[1inchVenue] No route data for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}`),null;const m=BigInt(x.dstAmount);if(m<=0n)return console.warn(`[1inchVenue] Zero output for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}`),null;const y=nr(m,r),b=[];return x.tx.to&&!l&&b.push({to:s.tokenIn,value:0n,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"approve",args:[x.tx.to,s.amountIn]})}),b.push({to:x.tx.to,value:BigInt(x.tx.value||"0"),data:x.tx.data}),{venue:"1inch",amountOut:m,amountOutMinimum:y,calls:b}}catch(h){if(h instanceof p.SpiceflowError)throw h;const f=h instanceof Error?h.message:String(h);throw new p.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] Exception for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}: ${f}`,{venue:"1inch",chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn.toString(),cause:f})}}}}const or=[4114,5115],Hs={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425"},rr={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453]};function ar(e){return{name:"satsuma",chainIds:e.chainIds??or,resolve:async(t,s,o)=>{const a=t.maxSlippage??Os,r=F.isNativeToken(t.tokenIn);let i;try{i=await er({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountIn:t.amountIn,chainId:s,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 ${s}.`),null}const d=nr(i.amountOut,a),u=[];return r||u.push({to:t.tokenIn,value:0n,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),u.push({to:e.swapRouter,value:r?t.amountIn:0n,data:j.encodeFunctionData({abi:F.uniV3SwapRouterAbi,functionName:"exactInputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:i.fee,recipient:o,amountIn:t.amountIn,amountOutMinimum:d,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:i.amountOut,amountOutMinimum:d,calls:u}}}}function ir(e){return{name:"satsuma",chainIds:e.chainIds??or,resolve:async(t,s,o)=>{const a=t.maxSlippage??Os,r=F.isNativeToken(t.tokenIn);let i;try{i=await al({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountOut:t.amountOut,chainId:s,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return null}const d=BigInt(Math.round(a*1e4)),u=i.amountIn+i.amountIn*d/10000n,l=[];return l.push({to:e.swapRouter,value:r?u:0n,data:j.encodeFunctionData({abi:cl,functionName:"exactOutputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:i.fee,recipient:o,amountOut:t.amountOut,amountInMaximum:u,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:i.amountIn,amountInMax:u,amountOut:t.amountOut,calls:l}}}}const cl=[{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 lr(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(ar(e.satsuma)),t.push(sr(e?.oneInch));function s(a){return t.find(r=>r.chainIds.includes(a))}async function o(a,r,i){const d=[],u=[];for(const l of a){if(!tr(l)){d.push(l);continue}const h=s(r);if(!h)throw new p.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${r}. Cannot resolve swap ${l.tokenIn} \u2192 ${l.tokenOut}.`,{chainId:r,tokenIn:l.tokenIn,tokenOut:l.tokenOut,amountIn:l.amountIn.toString()});const f=await h.resolve(l,r,i);if(!f)throw new p.SpiceflowError("NO_LIQUIDITY",`${h.name} returned no quote for ${l.tokenIn} \u2192 ${l.tokenOut} on chain ${r}.`,{venue:h.name,chainId:r,tokenIn:l.tokenIn,tokenOut:l.tokenOut,amountIn:l.amountIn.toString()});d.push(...f.calls),u.push(f)}return{calls:d,resolvedSwaps:u}}return{resolveSwapIntents:o,getVenueForChain:s,venues:t}}function dl(e){const t=e?.customVenues??[];async function s(o,a,r){const i=t.filter(u=>u.chainIds.includes(a));if(i.length===0)throw new p.SpiceflowError("NO_SWAP_ROUTE",`No exact-output venue supports chain ${a}`,{chainId:a,tokenIn:o.tokenIn,tokenOut:o.tokenOut});const d=(await Promise.allSettled(i.map(u=>u.resolve(o,a,r)))).filter(u=>u.status==="fulfilled").map(u=>u.value).filter(u=>u!==null);if(d.length===0)throw new p.SpiceflowError("NO_SWAP_ROUTE",`All aggregators failed for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${a}`,{chainId:a,tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountOut:o.amountOut.toString()});return d.sort((u,l)=>u.amountIn<l.amountIn?-1:u.amountIn>l.amountIn?1:0),d[0]}return{getQuote:s,venues:t}}const ul=lr({satsuma:Hs});function pl(e){const{direction:t,selectedAsset:s,destinationToken:o,chainId:a,recipient:r,paymentAmount:i}=e,[d,u]=c.useState(!1),[l,h]=c.useState(null),[f,g]=c.useState(null),[x,m]=c.useState(null),[y,b]=c.useState(null),[S,w]=c.useState(null),[C,v]=c.useState(null),[k,A]=c.useState(null),[E,R]=c.useState(null),B=c.useRef(null),I=c.useRef(0),T=c.useRef(new Map),D=c.useMemo(()=>ul,[]),M=c.useMemo(()=>dl({customVenues:[ir(Hs),ir(rr)]}),[]),U=c.useMemo(()=>{if(!s?.asset)return null;const G=$t(s.asset,a);if(G)return G;const ce=rn(s.asset.address,a,s.asset.chainId);return ce?ce.address:null},[s?.asset,a]),z=c.useMemo(()=>s?.asset?Yn(s.asset,a):[],[s?.asset,a]);c.useEffect(()=>{let G=!1;if(!s?.asset||z.length<=1){R(null);return}return(async()=>{const ce=t==="input"?s.amount:i||"0";let P=0n;try{P=t==="input"?j.parseUnits(ce,s.asset.decimals):0n}catch{P=0n}try{const ne=await So(s.asset,a,{requiredAmount:P});G||R(ne)}catch{G||R(null)}})(),()=>{G=!0}},[s?.asset,s?.amount,a,z,t,i]);const W=c.useMemo(()=>E??U,[E,U]),Q=c.useMemo(()=>!s?.asset||!W?[]:[W,...z.filter(G=>G.toLowerCase()!==W.toLowerCase())],[s?.asset,W,z]),N=c.useMemo(()=>!s?.asset||!Nn(s.asset.address,s.asset.chainId,o.address,o.chainId)||!W?!1:p.addressesEqual(W,o.address),[s,o.address,o.chainId,W]),L=W?p.addressesEqual(W,o.address):!1,q=t==="output"&&parseFloat(i||"0")===0,K=!!s?.asset&&!N&&!L&&!q,O=K?k??W:W;return c.useEffect(()=>{B.current&&clearTimeout(B.current);const G=t==="input"?s?.amount:i,ce=parseFloat(G||"0");if(!K||!Number.isFinite(ce)||ce<=0||!s?.asset||!r||Q.length===0){I.current++,g(null),m(null),b(null),w(null),v(null),A(null),h(null),u(!1);return}const P=s.asset.decimals;let ne;try{ne=t==="input"?j.parseUnits(s.amount,P):j.parseUnits(i||"0",o.decimals)}catch{I.current++,h("Invalid amount"),u(!1);return}const me=++I.current,ke=()=>me!==I.current;u(!0);const pe=t==="output"?150:400;return B.current=setTimeout(async()=>{try{if(t==="input"){const ge=D.getVenueForChain(a);if(!ge)throw new Error("No swap venue for this chain");let fe=null,V=null;for(const X of Q){const le=`${t}:${a}:${X.toLowerCase()}:${o.address.toLowerCase()}:${ne.toString()}`,xe=T.current.get(le);if(xe&&xe.expiresAt>Date.now()&&xe.resolvedSwap){fe=xe.resolvedSwap,V=X;break}const Se=await ge.resolve({type:"swap",tokenIn:X,tokenOut:o.address,amountIn:ne},a,r);if(ke())return;if(Se){T.current.set(le,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:Se}),fe=Se,V=X;break}}if(!fe||!V)throw new Error("No liquidity for this pair");A(V),v(fe.amountOut),b(fe),w(null);const re=parseFloat(j.formatUnits(fe.amountOut,o.decimals));g(re<.01?re.toPrecision(4):re.toLocaleString(void 0,{maximumFractionDigits:6})),m(null),h(null)}else{let ge=null,fe=null;for(const V of Q){const re=`${t}:${a}:${V.toLowerCase()}:${o.address.toLowerCase()}:${ne.toString()}`,X=T.current.get(re);if(X&&X.expiresAt>Date.now()&&X.exactOutputSwap){ge=X.exactOutputSwap,fe=V;break}try{const le=await M.getQuote({tokenIn:V,tokenOut:o.address,amountOut:ne},a,r);if(ke())return;T.current.set(re,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:le}),ge=le,fe=V;break}catch{if(ke())return}}if(!ge||!fe)throw new Error("No liquidity for this pair");A(fe),w(ge),b(null),v(null),m(parseFloat(j.formatUnits(ge.amountIn,P)).toFixed(6)),g(null),h(null)}}catch(ge){if(ke())return;const fe=ge instanceof Error?ge.message:"Failed to get quote";h(fe),g(null),m(null),b(null),w(null),v(null),A(null)}finally{ke()||u(!1)}},pe),()=>{B.current&&clearTimeout(B.current)}},[t,K,s?.amount,s?.asset?.address,s?.asset?.decimals,i,Q,a,o.address,o.decimals,r,D,M]),{isQuoting:d,quoteError:l,estimatedOutput:f,estimatedInput:x,resolvedSwap:y,exactOutputSwap:S,quoteAmountOut:C,resolvedTokenIn:O,isDirect:L,needsSwap:K,selectedIsEquivalent:N}}const cr={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},dr=["signing-delegation","signing-intent","submitting","executing"],ur=({isOpen:e,onClose:t,closeOnBackdropClick:s=!1,destinationToken:o,sourceChains:a,supportedSourceAssets:r,buildActionCalls:i,feeExecutionMode:d="user-transfer",buildSpicenetBatch:u,onPayExecute:l,actionLabel:h,amountDirection:f="input",swapDescription:g,directDescription:x,paymentAmount:m,amountInputMode:y="fixed",minPaymentAmount:b,maxPaymentAmount:S,onAmountChange:w,styles:C,dark:v,title:k,subtitle:A,onAddFunds:E,onSuccess:R,onError:B})=>{const I=f==="output",{theme:T,dark:D,primaryColor:M,dk:U,palette:z,fontFamily:W,monoFont:Q,inputDark:N,cardBg:L,cardBorder:q,textPrimary:K,textSecondary:O,subtitleText:G}=p.useSpiceBrand(C,v),ce=N?{...T,colors:{...T.colors,secondary:U.cardBg,surfaceHover:U.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:T,P=o.chainId,ne=c.useContext(p.SpiceFlowProviderContext),me=(ne?.mode||"7702")!=="7702",ke=!!ne?.isWhitelistGateActive,pe=c.useMemo(()=>a??ne?.supportedChainIds??[],[a,ne?.supportedChainIds]),ge=c.useMemo(()=>{if(ke)return[];if(r)return r;const de=ne?.allowedTokens;if(!de||de.length===0)return;const Be=new Set(de.map(Kt=>Kt.toLowerCase())),Bt=[],Jt=new Set;for(const Kt of pe){const jn=p.getChainConfig(Kt);for(const un of jn?.supportedTokens??[]){if(!Be.has(un.symbol.toLowerCase()))continue;const Fn=un.address.toLowerCase();Jt.has(Fn)||(Jt.add(Fn),Bt.push(un.address))}}return Bt},[r,ne?.allowedTokens,pe,ke]),fe=p.useWallet(),{address:V,isConnected:re,isReady:X,isAuthenticated:le,provider:xe}=fe,{executeGasless:Se,estimateGasless:J}=es(),{externalWallet:Y,externalAddress:ae,embeddedAddress:Ce}=p.useProviderWallets(),We=p.useEmbeddedWalletAddress()||Ce,{displayAssets:rt,filteredSpiceAssets:Ke,embeddedWalletAddress:Ze,refreshSpiceAssets:oe,refreshWalletAssets:ie}=sl({destinationToken:o,supportedSourceAssets:ge,sourceChains:pe,enabled:e&&(me?!!ae:!!We)}),Ye=ke||I||me?rt:Ke,[_,Me]=c.useState(null),[ct,kt]=c.useState(m||""),[st,Pt]=c.useState(!1),[Rt,mt]=c.useState(null),[Ie,Mt]=c.useState("idle"),[Zt,Yt]=c.useState(""),[gt,zt]=c.useState(null),[Ge,vt]=c.useState(!1),[Qe,$e]=c.useState(null),[_e,dt]=c.useState(null),[Et,he]=c.useState(!1),[at,it]=c.useState(!1),[jt,be]=c.useState(null),Dt=c.useRef(_),et=c.useRef(!1),ut=c.useRef(null),xt=c.useRef(0),Gt=c.useRef(null),Lt=c.useRef(null);c.useEffect(()=>{Dt.current=_},[_]);const Xe=y==="adjustable"?ct:m||"0",_t=Ze||Ce||V,{isQuoting:Te,quoteError:ft,estimatedOutput:Oe,resolvedSwap:yt,exactOutputSwap:qe,quoteAmountOut:Ct,resolvedTokenIn:Ue,isDirect:Je,needsSwap:He,selectedIsEquivalent:bt}=pl({direction:f,selectedAsset:_,destinationToken:o,chainId:P,recipient:_t,paymentAmount:Xe}),tt=I?parseFloat(Xe||"0"):parseFloat(_?.amount||"")||0,Ot=_?.asset?._source==="wallet",De=!!_?.asset&&Ot&&_.asset.chainId!==P,Vt=c.useMemo(()=>_?.asset?Ke.find(de=>p.addressesEqual(de.address,_.asset.address))?.balanceFormatted??0:0,[_,Ke]),Ht=Ot?_?.asset.balanceFormatted??0:Vt,St=c.useMemo(()=>{if(!_?.asset)return!1;if(I)return _e?En(_e.grossAmount,_e.decimals,_.asset.decimals)>_.asset.balance:bt||Je?tt>_.asset.balanceFormatted:qe?parseFloat(j.formatUnits(qe.amountInMax,_.asset.decimals))>_.asset.balanceFormatted:!1;if(_e){const de=En(_e.grossAmount,_e.decimals,_.asset.decimals);return Ot?de>_.asset.balance:parseFloat(j.formatUnits(de,_.asset.decimals))>Ht}return tt>Ht},[_,I,_e,bt,tt,qe,Ht,Ot,Je]);c.useEffect(()=>{e||(Me(null),mt(null),Pt(!1),Mt("idle"),Yt(""),zt(null),vt(!1),$e(null),dt(null),he(!1),it(!1),be(null),et.current=!1,y==="adjustable"&&kt(m||""),ut.current&&(ut.current.abort(),ut.current=null))},[e]);const te=c.useCallback(de=>{Me(Be=>({asset:de,amount:Be?.asset?.address===de.address&&Be?.asset?.chainId===de.chainId&&Be.amount||""})),mt(null),be(null),it(!1)},[]),se=c.useCallback(de=>{Me(Be=>Be&&{...Be,amount:de}),mt(null),be(null),it(!1)},[]),ve=c.useCallback(de=>{let Be=de;S&&parseFloat(Be)>parseFloat(S)&&(Be=S),kt(Be),w?.(Be),mt(null),be(null),it(!1)},[S,w]);c.useCallback(de=>{if(et.current||!V)return;const Be=Dt.current;!Be?.asset||!Be.amount||Be.asset?._source==="wallet"||j.parseUnits(I?Xe:Be.amount,Be.asset.decimals)===0n||(et.current=!0,oe())},[V,P,oe,I,Xe]);const ze=c.useCallback(de=>{Mt({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[de.step]||"executing"),Yt(de.message),de.txHash&&zt(de.txHash)},[]),nt=c.useMemo(()=>({currentPaymentAmount:Xe,destinationToken:o,embeddedWalletAddress:Ze,providerEmbeddedAddress:Ce,externalWalletAddress:ae,address:V,isNon7702:me,isPayMode:I,resolvedChainId:P,buildActionCalls:i,feeExecutionMode:d,buildSpicenetBatch:u,selectedAsset:_,needsSwap:He,resolvedSwap:yt,exactOutputSwap:qe,quoteAmountOut:Ct,resolvedTokenIn:Ue}),[Xe,o,Ze,Ce,ae,V,me,I,P,i,d,u,_,He,yt,qe,Ct,Ue]),Le=c.useCallback(de=>Vi(nt,de),[nt]),Ve=c.useCallback(de=>qi(nt,de),[nt]),Ne=c.useCallback((de,Be,Bt,Jt)=>Ki(de,Be,Bt,J,Jt),[J]),Z=c.useMemo(()=>_?.asset?He&&Ue?Ue:_.asset.chainId===P?_.asset.address:Ue??$t(_.asset,P)??o.address:o.address,[_,o.address,He,P,Ue]),ye=c.useCallback(()=>Ji(Lt.current),[]),Ae=c.useMemo(()=>_?.asset?p.addressesEqual(_.asset.address,o.address)&&_.asset.chainId===o.chainId:!1,[_,o.address,o.chainId]),je=me&&Ae,Ee=je&&tt>0&&!!_?.asset,lt=Rt,ht=c.useMemo(()=>!(!_?.asset||tt<=0),[_,tt,Ee]),qt=c.useMemo(()=>!e||st||Ie!=="idle"||!ht||Ee||!_?.asset?null:[I?"pay":"supply",f,_.asset.address.toLowerCase(),_.asset.chainId,_.amount,Xe,o.address.toLowerCase(),o.chainId,P,Ue?.toLowerCase()??"",He?"swap":"direct",Je?"direct-token":"routed-token",me?"non7702":"7702",Ae?"source-dest":"cross-chain",Te?"quoting":"quoted",qe?.amountIn?.toString()??"",qe?.amountInMax?.toString()??"",qe?.venue??"",yt?.amountOut?.toString()??"",Ct?.toString()??"",Ze??"",Ce??"",V??""].join("|"),[e,st,Ie,ht,Ee,_,I,f,Xe,o,P,Ue,He,Je,me,Ae,Te,qe,yt,Ct,Ze,Ce,V]),H=c.useCallback(()=>Xi({selectedAsset:_,isPayMode:I,parsedAmount:tt,needsSwap:He,exactOutputSwap:qe,isNon7702:me,isSourceDestToken:Ae,currentPaymentAmount:Xe,destinationToken:o,feeExecutionMode:d,resolvedTokenIn:Ue,embeddedWalletAddress:Ze,providerEmbeddedAddress:Ce,resolvedChainId:P,isConnected:re,address:V,ready:X,authenticated:le,isDirect:Je,resolvedSwap:yt,isQuoting:Te,executionTokenAddress:Z,buildPayChainBatches:Le,buildSupplyChainBatches:Ve,estimateGasless:J,estimateRequiredGrossFunding:Ne}),[_,I,tt,He,qe,me,Ae,Xe,o,d,Ue,Ze,Ce,Ne,Le,J,P,re,V,X,le,Je,yt,Te,Ve,Z]);c.useEffect(()=>{Gt.current=H},[H]);const $=c.useCallback(de=>Gi({asset:de,isPayMode:I,isNon7702:me,needsSwap:He,isQuoting:Te,embeddedWalletAddress:Ze,buildSupplyChainBatches:Ve,estimateGasless:J,executionTokenAddress:Z,feeExecutionMode:d}),[I,me,He,Te,Ze,Ve,J,Z,d]);c.useEffect(()=>{if(!e){he(!1),it(!1),be(null),dt(null);return}if(st||Ie!=="idle"){xt.current+=1,he(!1);return}if(!ht){dt(null),he(!1),it(!1),be(null);return}if(Ee){dt(null),he(!1),it(!0),be(null);return}if(!qt)return;let de=!1;const Be=async()=>{const Jt=++xt.current;be(null),he(!0);try{const Kt=await Gt.current?.();if(de||xt.current!==Jt)return;Kt?(dt(Kt),it(!0)):(dt(null),it(!1)),be(null)}catch(Kt){if(de||xt.current!==Jt)return;const jn=p.sanitizeError(Kt,"Unable to calculate fees for this action.");dt(null),it(!1),be(jn)}finally{!de&&xt.current===Jt&&he(!1)}},Bt=window.setTimeout(()=>{Be()},250);return()=>{de=!0,clearTimeout(Bt),he(!1)}},[e,st,Ie,ht,Ee,qt]);const ue=c.useCallback(()=>el(Lt.current),[]);c.useEffect(()=>{!I&&Ie==="success"&&gt&&(oe(),R?.(gt))},[I,Ie,gt,oe,R]),c.useEffect(()=>{if(!I||Qe?.status!=="success"||et.current||!V)return;et.current=!0;const de=Dt.current;!de?.asset||de.asset?._source==="wallet"||oe()},[I,Qe?.status,V,oe]);const ee=c.useRef(R),Re=c.useRef(B);c.useEffect(()=>{ee.current=R},[R]),c.useEffect(()=>{Re.current=B},[B]),c.useEffect(()=>{e&&(oe(),ie())},[e,oe,ie]),c.useEffect(()=>{I&&(Qe?.status==="success"&&ee.current?.(Qe.txHash||""),Qe?.status==="failed"&&Re.current?.(new Error("Payment execution failed")))},[I,Qe?.status]);const Fe=c.useCallback(()=>{vt(!1),$e(null),Me(null),et.current=!1,oe(),ie()},[oe,ie]);Lt.current={selectedAsset:_,parsedAmount:tt,currentPaymentAmount:Xe,isInsufficientBalance:St,isPayMode:I,isNon7702:me,isSourceDestToken:Ae,needsSwap:He,exactOutputSwap:qe,selectedIsEquivalent:bt,resolvedTokenIn:Ue,embeddedWalletAddress:Ze,providerEmbeddedAddress:Ce,externalWallet:Y,externalWalletAddress:ae,address:V,isConnected:re,ready:X,authenticated:le,provider:xe,resolvedChainId:P,executionTokenAddress:Z,destinationToken:o,buildActionCalls:i,feeExecutionMode:d,buildSpicenetBatch:u,onPayExecute:l,onError:B,gasless:{estimateGasless:J,executeGasless:Se,buildPayChainBatches:Le,buildSupplyChainBatches:Ve,estimateRequiredGrossFunding:Ne,onProgress:ze},ui:{setError:mt,setStep:Mt,setStatusMsg:Yt,setTxHash:zt,setIsExecuting:Pt,setShowStatusPanel:vt,setPaymentResult:$e},refs:{spiceDepositSubmittedRef:et,abortControllerRef:ut}};const Pe=I&&tt===0,ot=I?!!_?.asset&&tt>=0&&!St&&!st&&(Pe||Ee||at)&&!jt&&(Pe||!He||!!qe):!!_?.asset&&tt>0&&!St&&!st&&(je||at)&&!jt&&(De||Je||!!yt&&!Te),Qt=Je?x||`Your ${o.symbol} will be used directly.`:g||"Your assets will be swapped and used in a single atomic transaction.",Ft=(P?p.getChainConfig(P):void 0)?.viemChain?.blockExplorers?.default?.url??"",pt=dr.indexOf(Ie),It=st?(cr[Ie]||"EXECUTING...").toUpperCase():Ie==="success"?"DONE":St?"INSUFFICIENT BALANCE":h.toUpperCase(),Xt=c.useMemo(()=>{if(st)return"PAYING...";if(St&&_?.asset)return`INSUFFICIENT ${_.asset.symbol}`;if(h)return h.toUpperCase();const de=tt>0?` ${Xe} ${o.symbol}`:"";return He?`SWAP & PAY${de}`:`PAY${de}`},[st,St,_,h,tt,Xe,o.symbol,He]),an=Ie==="success"?()=>{Mt("idle"),Me(null),zt(null),oe()}:ye,xn=Ie==="success"?!1:!ot;if(!e)return null;const yn=I?k||`Pay ${o.symbol}`:h,we=I?A:n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[n.jsx("span",{style:{marginTop:"3px",flexShrink:0},children:n.jsx(bs,{color:G})}),n.jsx("p",{style:{fontSize:"12px",color:G,margin:0,lineHeight:"1.4",fontFamily:W},children:Qt})]});if(I){const de=Qe&&(Qe.status==="success"||Qe.status==="failed")?[{asset:{symbol:_?.asset?.symbol||o.symbol,address:_?.asset?.address||""},amount:Xe,txHash:Qe.txHash||"",success:Qe.status==="success",error:Qe.status==="failed"?Qe.error:void 0}]:void 0;return n.jsx(tn,{isOpen:e,onClose:t,title:yn,subtitle:we,styles:C,dark:D,footerLinkText:"Spicenet accounts \u2192",closeOnBackdropClick:s,children:n.jsxs("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[E&&n.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:n.jsx(ws,{onClick:E,color:M,fontFamily:W})}),n.jsx("div",{style:{marginBottom:"12px"},children:n.jsx(Dn,{assets:Ye,selectedAsset:_??void 0,onAssetSelect:te,onAmountChange:()=>{},label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:_?.asset?He?Te?"...":qe?`~${parseFloat(j.formatUnits(qe.amountIn,_.asset.decimals)).toFixed(6)}`:void 0:Xe??void 0:void 0,dark:D,theme:ce,styles:C})}),n.jsx(Xo,{variant:"pay",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:M,fontFamily:W,textPrimary:K,textSecondary:O,cardBg:L,cardBorder:q,dk:U,dark:D,isQuoting:Te,quoteError:ft,estimatedOutput:Oe,paymentAmount:Xe,needsSwap:He,exactOutputSwap:qe,adjustable:y==="adjustable",maxAmount:S,onAmountChange:ve}),ht&&n.jsx(Vn,{fontFamily:W,textPrimary:K,textSecondary:O,cardBg:L,cardBorder:q,resolvedDark:D,darkCardBorder:U.cardBorder,primaryColor:M,feePreview:_e,isLoading:Et,errorText:jt,directExecutionFeeNote:Ee}),lt&&n.jsx(Sn,{variant:"error",palette:z,fontFamily:W,style:{marginBottom:"12px"},children:lt}),n.jsx(p.Button,{variant:"outline",fullWidth:!0,onClick:ue,disabled:!ot,loading:st,dark:D,styles:{...C,button:{...C?.button,backgroundColor:M}},children:Xt}),Qe&&Ge&&n.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:D?U.shell:"white",borderRadius:D?"12px":"6px",padding:"16px 0"},children:n.jsx(As,{type:"payment",isOpen:Qe.status!=="processing",isProcessing:st||Qe.status==="processing",closeOnComplete:!1,chainName:p.getChainName(P),explorerUrl:p.getExplorerUrl(P,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{vt(!1),$e(null),ue()},onNewTx:Fe,onClose:()=>{vt(!1),$e(null)},onComplete:Fe,results:de,styles:C,dark:D})})]})})}return n.jsx(tn,{isOpen:e,onClose:t,title:yn,subtitle:we,dark:D,styles:C,theme:T,closeOnBackdropClick:s,children:n.jsxs("div",{style:{padding:"24px 24px 5px 24px",position:"relative"},children:[n.jsx("div",{style:{marginBottom:"16px"},children:n.jsx(Dn,{assets:Ye,selectedAsset:_||void 0,onAssetSelect:te,onAmountChange:se,disabled:st||Ie==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:ce,styles:C,dark:N,resolveMaxAmount:$,maxAmount:Ht>0?kn(Ht,_?.asset.decimals??o.decimals):void 0})}),_?.asset&&!Je&&n.jsx(Xo,{variant:"supply",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:M,fontFamily:W,textPrimary:K,textSecondary:O,cardBg:L,cardBorder:q,dark:D,isQuoting:Te,quoteError:ft,estimatedOutput:Oe}),ht&&n.jsx(Vn,{fontFamily:W,textPrimary:K,textSecondary:O,cardBg:L,cardBorder:q,resolvedDark:D,darkCardBorder:U.cardBorder,primaryColor:M,feePreview:_e,isLoading:Et,errorText:jt,directExecutionFeeNote:Ee}),Ie!=="idle"&&n.jsxs("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:Ie==="success"?L:Ie==="error"?z.errorBg:L,border:`1px solid ${Ie==="success"?q:Ie==="error"?z.errorBorder:q}`},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[Ie==="success"?n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:n.jsx("path",{d:"M5 13l4 4L19 7",stroke:z.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):Ie==="error"?n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:n.jsx("path",{d:"M18 6L6 18M6 6l12 12",stroke:z.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):n.jsx(p.Spinner,{size:14,color:M}),n.jsx("span",{style:{fontSize:"13px",fontWeight:500,color:Ie==="success"?K:Ie==="error"?z.errorText:K,fontFamily:W,flex:1},children:Ie==="success"?"Deposit confirmed":Ie==="error"?Zt||"Transaction failed":cr[Ie]||Zt}),Ie==="success"&&gt&&n.jsx("a",{href:`${Ft}/tx/${gt}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:M,fontFamily:W,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),Ie==="error"&&n.jsx("button",{onClick:()=>{Mt("idle"),mt(null),setTimeout(ye,50)},style:{background:"none",border:"none",fontSize:"12px",color:M,fontFamily:W,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),pt>=0&&Ie!=="success"&&Ie!=="error"&&n.jsx("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${O}22`,overflow:"hidden"},children:n.jsx("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:M,transformOrigin:"left center",transform:`scaleX(${(pt+1)/dr.length})`,transition:"transform 400ms ease"}})})]}),Rt&&Ie==="idle"&&n.jsx(Sn,{variant:"error",palette:z,fontFamily:W,style:{marginBottom:"16px"},children:Rt}),n.jsx(p.Button,{variant:"outline",fullWidth:!0,disabled:xn,onClick:an,theme:T,dark:D,styles:{...C,button:{...C?.button,backgroundColor:M}},style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:Q},children:It})]})})},fl=e=>n.jsx(ur,{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}),hl=({label:e="Export Wallet",style:t,className:s,onExport:o,onError:a})=>{const[r,i]=c.useState(!1),[d,u]=c.useState(!1),{primaryColor:l}=p.useSpiceBrand(),h=c.useContext(p.SpiceFlowProviderContext),{isAuthenticated:f}=p.useWallet();let g=null;try{g=Ln.usePrivy()}catch{}let x=null,m=null;try{x=Zs.useEmbeddedReveal(),m=Zs.useDynamicContext()}catch{x=null,m=null}const y=p.getDynamicEmbeddedWallet(m),b=c.useCallback(async()=>{if(!f){a?.("User is not authenticated. Please log in first.");return}try{if(h?.provider==="dynamic"){if(!x||!y){a?.("Dynamic is not available. Ensure the app is wrapped in a DynamicContextProvider.");return}await x.initExportProcess(!1),o?.();return}if(!g){a?.("Privy is not available. Ensure the app is wrapped in a PrivyProvider.");return}await g.exportWallet(),o?.()}catch(C){const v=C instanceof Error?C.message:"Failed to export wallet";console.error("Export wallet error:",C),a?.(v)}},[y,x,f,a,o,g,h?.provider]),S=!f,w={padding:"10px 20px",borderRadius:"8px",fontFamily:'"IBM Plex Mono", monospace',fontSize:"14px",fontWeight:500,letterSpacing:"0.4px",textTransform:"uppercase",cursor:S?"not-allowed":"pointer",opacity:S?.5:1,border:"1px solid #0e0d0b",color:"#0e0d0b",backgroundColor:d?`${l}cc`:r?`${l}ee`:l,transition:"background-color 150ms ease, transform 150ms ease",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"8px",...t};return n.jsxs("button",{onClick:b,onMouseEnter:()=>i(!0),onMouseLeave:()=>{i(!1),u(!1)},onMouseDown:()=>u(!0),onMouseUp:()=>u(!1),disabled:S,className:s,style:w,children:[n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),n.jsx("polyline",{points:"17 8 12 3 7 8"}),n.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]}),e]})};function pr(e){const t=c.useContext(p.SpiceFlowProviderContext),s=p.useEmbeddedWalletAddress(),o=e?.enabled===!1?void 0:s,a=t?.network?{network:t.network,pollIntervalMs:e?.pollIntervalMs,chainIds:e?.chainIds??t.supportedChainIds,discoverWalletBalances:e?.discoverWalletBalances}:void 0;return{...ho(o,a),embeddedWalletAddress:s}}const ml=({appName:e,status:t,statusLabel:s,totalUsdValue:o,breakdownSubtitle:a,address:r,dk:i,dark:d=!1,showModeToggle:u,isEmbeddedMode:l=!0,onModeToggle:h})=>{const[f,g]=c.useState(!1),x=async()=>{r&&await Lr(r)&&(g(!0),setTimeout(()=>g(!1),2e3))},m=t==="active",y=s||(m?"Active":"Inactive"),b=m?"#10b981":"#9ca3af",S=n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[n.jsxs("div",{children:[n.jsx("strong",{children:"Embedded:"})," Deposit assets into ",e," account and use them here."]}),n.jsxs("div",{children:[n.jsx("strong",{children:"External:"})," Use assets from your connected wallet here."]})]});return n.jsxs("div",{children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[n.jsxs("div",{style:{fontSize:"13px",fontWeight:600,color:i.textPrimary},children:[e," Account"]}),u?n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[n.jsxs("button",{onClick:h,style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:d?i.hoverBg:"#f3f4f6",border:d?`1px solid ${i.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"11px",fontWeight:600,fontFamily:'"IBM Plex Mono", monospace',color:i.textSecondary,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease",letterSpacing:"0.02em"},children:[n.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:l?"#22c55e":"#f59e0b"}}),n.jsx("span",{children:l?"Embedded":"External"})]}),n.jsx(ro,{content:S,label:"Account mode info",textColor:d?i.textPrimary:"#f9fafb",backgroundColor:d?i.cardBg:"#111827",borderColor:d?i.cardBorder:"rgba(255,255,255,0.08)",accentColor:d?i.textSecondary:"#6b7280",children:n.jsx("img",{src:Ss,alt:"","aria-hidden":"true",style:{width:"12px",height:"12px",display:"block",...d?{filter:"invert(0.65)"}:{}}})})]}):n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:d?i.hoverBg:m?"#ecfdf5":"#f3f4f6",border:d?`1px solid ${i.cardBorder}`:m?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[n.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:b}}),n.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:d?i.textSecondary:m?"#065f46":"#6b7280"},children:y})]})]}),n.jsx("div",{style:{fontSize:"28px",fontWeight:700,color:i.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:bn(o)}),a&&n.jsx("div",{style:{fontSize:"12px",color:i.textSecondary,marginBottom:"8px"},children:a}),r&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[n.jsx("span",{style:{fontSize:"12px",fontFamily:'"IBM Plex Mono", monospace',color:d?i.textSecondary:"#9ca3af"},children:zr(r)}),n.jsx("button",{onClick:x,style:{padding:"2px 6px",fontSize:"10px",fontWeight:500,backgroundColor:"transparent",color:d?i.textSecondary:"#9ca3af",border:"none",cursor:"pointer",borderRadius:"4px",transition:"background-color 150ms ease, color 150ms ease"},title:"Copy address",children:f?"Copied":"Copy"})]})]})},gl=({pendingDeposits:e,onCompleteDeposit:t,dk:s,dark:o=!1})=>e.length===0?null:n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:s.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:"Pending Deposits"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((a,r)=>{const i=p.getChainConfig(a.chainId)?.displayName||`Chain ${a.chainId}`;return n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:o?s.warningBg:"#fffbeb",border:o?`1px solid ${s.warningBorder}`:"1px solid #fde68a",borderRadius:"8px"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[n.jsx("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:o?s.hoverBg:"#fde68a",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:s.warningText},children:a.tokenSymbol.charAt(0)}),n.jsxs("div",{children:[n.jsxs("div",{style:{fontSize:"13px",fontWeight:500,color:s.textPrimary},children:[a.amount," ",a.tokenSymbol]}),n.jsxs("div",{style:{fontSize:"11px",color:s.warningText},children:["on ",i]})]})]}),n.jsx("button",{onClick:()=>t?.(a),style:{padding:"4px 12px",fontSize:"11px",fontWeight:600,backgroundColor:o?s.hoverBg:"#fef3c7",color:o?s.textPrimary:"#92400e",border:o?`1px solid ${s.warningBorder}`:"1px solid #fde68a",borderRadius:"9999px",cursor:"pointer",transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease"},children:"Complete"})]},`${a.tokenAddress}-${a.chainId}-${r}`)})})]}),xl=({spiceAssets:e,loading:t,dk:s,dark:o=!1})=>{const a={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:s.textSecondary,marginBottom:"8px",textTransform:"uppercase"},r={backgroundColor:s.cardBg,border:o?`1px solid ${s.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return t?n.jsxs("div",{children:[n.jsx("div",{style:a,children:"Idle Balances"}),[1,2].map(i=>n.jsx("div",{style:{...r,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},i))]}):e.length===0?n.jsxs("div",{children:[n.jsx("div",{style:a,children:"Idle Balances"}),n.jsx("div",{style:{...r,padding:"16px",textAlign:"center",fontSize:"13px",color:o?s.textSecondary:"#9ca3af"},children:"No assets yet. Deposit to get started."})]}):n.jsxs("div",{children:[n.jsx("div",{style:a,children:"Idle Balances"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((i,d)=>{const u=p.getChainConfig(i.chainId),l=i.chainDisplayName||u?.displayName||`Chain ${i.chainId}`,h=i.tokenDisplaySymbol||i.tokenDisplayName||i.tokenSymbol;return n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...r},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[i.logoURI?n.jsx("img",{src:i.logoURI,alt:i.tokenSymbol,style:{width:"24px",height:"24px",borderRadius:"50%"}}):n.jsx("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:o?s.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:s.textSecondary},children:h.charAt(0)}),n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:s.textPrimary},children:h}),n.jsx("div",{style:{fontSize:"11px",color:o?s.textSecondary:"#9ca3af"},children:l})]})]}),n.jsxs("div",{style:{textAlign:"right"},children:[n.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:s.textPrimary},children:ln(i.balanceFormatted)}),n.jsx("div",{style:{fontSize:"11px",color:o?s.textSecondary:"#9ca3af"},children:bn(i.usdValue)})]})]},`${i.tokenAddress}-${i.chainId}-${d}`)})})]})},yl=({section:e,dk:t,dark:s=!1})=>{const o=a=>{switch(a){case"green":return"#10b981";case"red":return"#ef4444";default:return t.textPrimary}};return n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:t.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:e.title}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.items.map((a,r)=>n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:t.cardBg,border:s?`1px solid ${t.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[a.tokenLogoURI?n.jsx("img",{src:a.tokenLogoURI,alt:a.tokenSymbol,style:{width:"20px",height:"20px",borderRadius:"50%"}}):n.jsx("div",{style:{width:"20px",height:"20px",borderRadius:"50%",backgroundColor:s?t.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",fontWeight:600,color:t.textSecondary},children:a.tokenSymbol.charAt(0)}),n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:t.textPrimary},children:a.tokenSymbol}),n.jsx("div",{style:{fontSize:"11px",color:t.textSecondary},children:a.label})]})]}),n.jsx("div",{style:{fontSize:"13px",fontWeight:600,color:o(a.valueColor)},children:a.displayValue})]},r))})]})},Cl=({onDepositClick:e,onWithdrawClick:t,depositDisabled:s=!1,withdrawDisabled:o=!1,primaryColor:a="#EA4B4B",dark:r=!1})=>!e&&!t?null:n.jsxs("div",{style:{display:"flex",gap:"8px"},children:[e&&n.jsx(p.Button,{variant:"outline",onClick:e,disabled:s,dark:r,styles:{button:{backgroundColor:a}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&n.jsx(p.Button,{variant:"outline",onClick:t,disabled:o,dark:r,styles:{button:{backgroundColor:a}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),bl=({appName:e,status:t,statusLabel:s,totalUsdValue:o,breakdownSubtitle:a,address:r,spiceAssets:i,spiceAssetsLoading:d,pendingDeposits:u,customSections:l,onDepositClick:h,onWithdrawClick:f,onCompleteDeposit:g,primaryColor:x,dk:m,dark:y=!1,showModeToggle:b,isEmbeddedMode:S,onModeToggle:w,showConnectExternalCta:C,onConnectExternalWallet:v,connectExternalError:k,showHowItWorks:A=!0})=>{const[E,R]=c.useState(!1);return n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[n.jsx(ml,{appName:e,status:t,statusLabel:s,totalUsdValue:o,breakdownSubtitle:a,address:r,dk:m,dark:y,showModeToggle:b,isEmbeddedMode:S,onModeToggle:w}),C&&n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[n.jsx("button",{onClick:v,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:x||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:'"Helvetica Neue", sans-serif',transition:"opacity 150ms ease"},children:"Connect External Wallet"}),k&&n.jsx("span",{style:{fontSize:"11px",color:y?m.errorText:"#b91c1c",lineHeight:1.4},children:k})]}),n.jsx("div",{style:{height:"1px",backgroundColor:y?"#2d2d2d":"#e5e7eb"}}),n.jsx(Cl,{onDepositClick:h,onWithdrawClick:f,primaryColor:x,dark:y}),A&&n.jsxs("div",{children:[n.jsxs("button",{onClick:()=>R(!E),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:m.cardBg,border:y?`1px solid ${m.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:m.textSecondary,fontSize:"12px",fontWeight:500},children:[n.jsx("span",{children:"How It Works"}),n.jsx("span",{style:{transform:E?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),E&&n.jsxs("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:y?m.cardBg:"#f0fdf4",border:y?`1px solid ${m.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:y?m.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),n.jsx(gl,{pendingDeposits:u,onCompleteDeposit:g,dk:m,dark:y}),n.jsx(xl,{spiceAssets:i,loading:d,dk:m,dark:y}),l.map((B,I)=>n.jsx(yl,{section:B,dk:m,dark:y},I))]})},Qs=380,gn=8,wl=[];function fr(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function kl(e,t){const s=new Map;Object.entries(t).forEach(([a,r])=>{if(!Number.isFinite(r)||r<=0)return;s.set(a,r),s.set(a.toUpperCase(),r);const i=fr(a);i&&s.set(i,r)});const o=[e.symbol,e.displaySymbol,e.receiptTokenName,e.name,e.displayName];for(const a of o){if(!a)continue;const r=s.get(a)??s.get(a.toUpperCase());if(r!==void 0)return r;const i=fr(a);if(!i)continue;const d=s.get(i);if(d!==void 0)return d}return 0}const vl=({appName:e="Spice",status:t="active",statusLabel:s,customSections:o=[],extraAssets:a=[],tokenPrices:r={},breakdownLabels:i=[],styles:d,dark:u=!1,onDepositSuccess:l,onDepositClick:h,onWithdrawClick:f,onCompleteDeposit:g,showModeToggle:x=!1,defaultMode:m})=>{const y=c.useContext(p.SpiceFlowProviderContext),b=y?.mode!=="7702",S=!!y?.isWhitelistGateActive,w=S?wl:a,C=c.useRef(!1);c.useEffect(()=>{if(!C.current){if(p.hasStoredSpiceFlowMode()){C.current=!0;return}m&&y?.setMode&&(y.setMode(m==="non7702"?"ondemand":"7702"),C.current=!0)}},[y,m]);const[v,k]=c.useState(!1),[A,E]=c.useState(null),[R,B]=c.useState({top:0,bottom:0,left:0,placement:"below"}),I=c.useRef(null),T=c.useRef(null),{address:D,isConnected:M}=p.useWallet(),U=p.useEmbeddedWalletAddress(),{externalAddress:z}=p.useProviderWallets(),{dark:W,primaryColor:Q,dk:N}=p.useSpiceBrand(d,u),L=!b&&U?U:D,q=c.useMemo(()=>y?.supportedChainIds??F.getChainIdsByNetwork("mainnet"),[y?.supportedChainIds]),{assets:K,loading:O}=Wn({address:L,supportedChains:q,enabled:!!L&&!b,refetchInterval:3e4}),G=c.useMemo(()=>[...b?[]:K.map(oe=>{const ie=oe.balanceUsd||0,Ye=Number.isFinite(oe.balanceFormatted)?oe.balanceFormatted:0,_=ie>0?ie:kl(oe,r)*Ye;return{tokenAddress:oe.address,tokenSymbol:oe.symbol,tokenDisplaySymbol:ms(oe),tokenDisplayName:Kr(oe),tokenDecimals:oe.decimals,chainId:oe.chainId,chainDisplayName:gs(oe),balance:oe.balance.toString(),balanceFormatted:oe.balanceFormatted,usdValue:_,logoURI:oe.logoURI}}),...w].filter(oe=>oe.balanceFormatted>0),[b,K,r,w]),ce=c.useMemo(()=>G.reduce((oe,ie)=>oe+ie.usdValue,0),[G]),{pendingDeposits:P}=pr({chainIds:q,enabled:!!D,discoverWalletBalances:!1}),ne=c.useMemo(()=>o.reduce((oe,ie)=>oe+ie.totalValue,0),[o]),me=ce+ne,ke=c.useMemo(()=>{const oe=[];ce>0&&oe.push(`${bn(ce)} idle`);for(const ie of o){const Ye=i.find(_=>_.sectionTitle===ie.title)?.label||ie.title.toLowerCase();oe.push(`${bn(ie.totalValue)} ${Ye}`)}return oe.join(" \xB7 ")},[ce,o,i]),pe=c.useCallback(oe=>{g?g(oe):E(oe)},[g]),ge=c.useCallback(()=>{E(null)},[]),fe=c.useCallback(()=>{E(null),l?.()},[l]),V=c.useCallback(()=>{if(!I.current)return;const oe=I.current.getBoundingClientRect(),ie=window.innerHeight-oe.bottom-gn,Ye=oe.top-gn,_=ie>=400||ie>=Ye?"below":"above",Me=Math.max(gn,Math.min(oe.right-Qs,window.innerWidth-Qs-gn)),ct=_==="below"?oe.bottom+gn:oe.top-gn,kt=_==="above"?window.innerHeight-ct:0;B({top:ct,bottom:kt,left:Me,placement:_})},[]);c.useLayoutEffect(()=>{v&&V()},[v,V]),c.useEffect(()=>{if(!v)return;const oe=_=>{I.current&&!I.current.contains(_.target)&&T.current&&!T.current.contains(_.target)&&k(!1)},ie=_=>{_.key==="Escape"&&k(!1)},Ye=()=>V();return document.addEventListener("mousedown",oe),document.addEventListener("keydown",ie),window.addEventListener("scroll",Ye,{passive:!0}),window.addEventListener("resize",V),()=>{document.removeEventListener("mousedown",oe),document.removeEventListener("keydown",ie),window.removeEventListener("scroll",Ye),window.removeEventListener("resize",V)}},[v,V]);const re=y?.mode==="7702",X=re?U||D:z||D,le=c.useCallback(()=>{y?.setMode&&y.setMode(re?"ondemand":"7702")},[y,re]),[xe,Se]=c.useState(null);let J=null;try{J=Ln.useConnectWallet({onSuccess:()=>Se(null),onError:oe=>Se(p.sanitizeError(oe,"Failed to connect wallet."))}).connectWallet}catch{J=null}const Y=c.useCallback(()=>{J&&(k(!1),Se(null),J({walletChainType:"ethereum-only"}))},[J]),ae=!z&&!!J,Ce=c.useCallback(()=>{k(!1),h?.()},[h]),We=c.useCallback(()=>{k(!1),f?.()},[f]),rt=c.useCallback(oe=>{k(!1),pe(oe)},[pe]);if(typeof window>"u")return null;const Ke=n.jsxs("button",{ref:I,onClick:()=>k(!v),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:W?N.hoverBg:"#ffffff",border:W?`1px solid ${N.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:'"Helvetica Neue", sans-serif',color:W?N.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:[n.jsx("span",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:Q,flexShrink:0}}),n.jsxs("span",{children:[e," Account"]}),M&&n.jsxs("span",{style:{color:W?N.textSecondary:"#6b7280"},children:["\xB7 ",bn(me)]}),n.jsx("span",{style:{fontSize:"10px",color:W?N.textSecondary:"#9ca3af",transform:v?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),Ze=v?Bn.createPortal(n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:pn.popover},onClick:()=>k(!1)}),n.jsx("div",{ref:T,style:{position:"fixed",top:R.placement==="below"?`${R.top}px`:"auto",bottom:R.placement==="above"?`${R.bottom}px`:"auto",left:`${R.left}px`,width:`${Qs}px`,maxWidth:`calc(100vw - ${gn*2}px)`,maxHeight:"80vh",backgroundColor:W?N.shell:"#ffffff",border:W?`1px solid ${N.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:pn.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${wt.out}`},children:n.jsx(bl,{appName:e,status:t,statusLabel:s,totalUsdValue:me,breakdownSubtitle:ke,address:re?X:D,spiceAssets:G,spiceAssetsLoading:O,pendingDeposits:P,customSections:o,onDepositClick:h?Ce:void 0,onWithdrawClick:f?We:void 0,onCompleteDeposit:rt,primaryColor:Q,dk:N,dark:W,showModeToggle:x,isEmbeddedMode:re,onModeToggle:le,showConnectExternalCta:ae,onConnectExternalWallet:Y,connectExternalError:xe,showHowItWorks:!S})}),n.jsx("style",{children:`
103
+ `})]})},Ti="0xa9059cbb";function Ri(e){const t=new Map;for(const s of e){if(s.amount<=0n)continue;const o=j.getAddress(s.token),a=j.getAddress(s.to),r=`${o.toLowerCase()}:${a.toLowerCase()}`,i=t.get(r);i?i.amount+=s.amount:t.set(r,{token:o,to:a,amount:s.amount})}return[...t.values()]}function Mi(e,t){return`0x${t}${e.slice(4)}`}function Di(e,t,s){if(!Array.isArray(e))return 0n;const o=`evm:${t}:${s.slice(2).toLowerCase()}`;let a=0n;for(const r of e){if(!r||typeof r!="object")continue;const i=r,d=i.chainTokens;if((Array.isArray(d)?d.filter(u=>typeof u=="string"):d&&typeof d=="object"?Object.keys(d):[]).some(u=>u.toLowerCase()===o))try{a+=BigInt(i.balanceAvailable??"0")}catch{}}return a}async function Vo(e,t,s,o){const a=await fetch(`${e}/wallets/${t}/balance`,{cache:"no-store"});if(!a.ok)throw new Error(`Failed to fetch spice balance: ${a.status}`);const r=await a.json();return Di(r?.balances,s,o)}async function Ni({apiBaseUrl:e,user:t,chainId:s,tokenAddress:o,prevBalance:a,timeoutMs:r=3e4,pollIntervalMs:i=1500}){const d=Date.now()+r;for(await new Promise(u=>setTimeout(u,800));Date.now()<d;){try{if(await Vo(e,t,s,o)>a)return}catch(u){console.warn("[SpiceLockModal] spice balance poll failed:",u?.message)}await new Promise(u=>setTimeout(u,i))}console.warn("[SpiceLockModal] Spicenet indexer did not reflect deposit within timeout; proceeding with intent")}function Us(e,t){return Ps(e,t)}function Ps(e,t,s){const o=Wi(t,e),a=Math.floor(Date.now()/1e3)+60*10,r=F.hashChainBatches(o);return{user:e,...s?{chainAuthorizations:s}:{},intents:[{mode:"7702",signatureType:"ecdsa",signature:"0x00",nbf:0,exp:a,chainBatches:r.map((i,d)=>({hash:i.hash,chainId:i.chainId,tokenTransfers:o[d].domain==="spicenet"?[]:o[d].tokenTransfers??[],calls:i.calls}))}]}}function Wi(e,t){return e.map(s=>{if(s.domain==="spicenet"||s.calls.length===0)return s;const o=new Set((s.tokenTransfers??[]).filter(r=>(r.from==="escrow"||r.from==="solver")&&j.getAddress(r.to).toLowerCase()===t.toLowerCase()).map(r=>j.getAddress(r.token).toLowerCase()));if(o.size===0)return s;let a=0;for(const r of s.calls){if(!r.data?.startsWith(Ti))break;try{const i=j.decodeFunctionData({abi:p.U,data:r.data});if(i.functionName!=="transfer")break;const[d]=i.args;if(d.toLowerCase()===t.toLowerCase()||!o.has(j.getAddress(r.to).toLowerCase()))break;a+=1}catch{break}}return a===0?s:{...s,calls:s.calls.slice(a)}})}function Ut(e,t,s,o){if(e.some(l=>l.domain==="spicenet"))return e;const a=s?.intents.flatMap(l=>l.batches),r=l=>l.from==="escrow",i=e.map(l=>{const h=a?.find(C=>C.chainId===l.chainId);if(!h)return l;const f=on(h),g=f.totalFee;if(g<=0n)return l;const x=(l.tokenTransfers??[]).find(C=>r(C)&&j.getAddress(C.to).toLowerCase()===t.toLowerCase()&&!F.isNativeToken(j.getAddress(C.token)));if(!x)return l;const m=j.getAddress(x.token);let y=!1;const b=(l.tokenTransfers??[]).map(C=>y||!r(C)||j.getAddress(C.to).toLowerCase()!==t.toLowerCase()||j.getAddress(C.token).toLowerCase()!==m.toLowerCase()?C:(y=!0,{...C,amount:o?.payoutAlreadyGross?BigInt(C.amount):BigInt(C.amount)+g}));if(!y)return l;const S=[];f.spicenetFee>0n&&S.push({to:m,value:0n,data:j.encodeFunctionData({abi:p.U,functionName:"transfer",args:[F.SPICE_PLATFORM_FEE_RECIPIENT,f.spicenetFee]})});const w=f.gasFee+f.bridgeFee;return w>0n&&S.push({to:m,value:0n,data:j.encodeFunctionData({abi:p.U,functionName:"transfer",args:[F.SPICE_SOLVER_ADDRESS,w]})}),{...l,tokenTransfers:b,calls:[...S,...l.calls]}}),d=i.flatMap(l=>(l.tokenTransfers??[]).filter(r).map(h=>{const f=j.getAddress(h.token),g=j.getAddress(h.to),x=[{token:f,to:g,amount:BigInt(h.amount)}];return{chainId:l.chainId,transfers:Ri(x)}}));if(d.length===0)return e;const u=BigInt(Math.floor(Date.now()/1e3))+3600n;return[{chainId:F.SPICENET_NATIVE_CHAIN_ID,domain:"spicenet",tokenTransfers:[],calls:d.map((l,h)=>{const f=j.keccak256(j.encodeAbiParameters([{type:"address"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"uint256"}],[t,l.transfers[0].token,l.transfers.reduce((x,m)=>x+m.amount,0n),BigInt(l.chainId),BigInt(Date.now()+h)])),g=Mi(f,"77");return{to:"0x0000000000000000000000000000000000000000",value:0n,data:j.encodeFunctionData({abi:F.spicenetAbi,functionName:"createWithdrawalRequest",args:[{chainId:`evm:${l.chainId}`,idempotenceKey:g,nbf:0n,exp:u,metadata:"{}",transfers:l.transfers.map(x=>({token:x.token.toLowerCase(),to:x.to,amount:x.amount}))}]})}})},...i]}function dn(e,t){const s=e.selectedAsset?.asset;if(!s||!e.selectedAsset?.amount)throw new Error("Select an asset and enter an amount");const o=t?.netAmount??j.parseUnits(e.selectedAsset.amount,s.decimals),a=t?.grossAmount??o;return e.resolveLockBatches({amount:j.formatUnits(o,s.decimals),amountWei:o,grossAmount:j.formatUnits(a,s.decimals),grossAmountWei:a})}async function zs(e,t,s){const o=[...new Set(s.filter(r=>r.domain!=="spicenet").map(r=>r.chainId))],a=[];for(const r of o){const i=p.getClientForChain(r),d=p.getDelegateContractAddress(r),u=await F.getAccountNonce(t,i),l=await e.actions.signAuthorization({contractAddress:d,chainId:r,nonce:Number(u)});a.push(l)}return a}async function qo(e,t,s){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 a=s??await zs(e,o,t),r=F.hashChainBatches(t),i=Math.floor(Date.now()/1e3)+60*10,d=r.map(x=>x.hash),u=j.keccak256(j.encodeAbiParameters([{type:"string"},{type:"uint256"},{type:"uint256"},{type:"bytes32[]"}],["ecdsa",0n,BigInt(i),d])),l=await e.actions.signMessage({raw:u}),h=typeof l=="string"?l:l.signature;if(!h)throw new Error("Failed to sign intent authorization");const f={mode:"7702",signatureType:"ecdsa",signature:h,nbf:0,exp:i,chainBatches:r.map((x,m)=>{const y=t[m],b=y.domain==="spicenet";return{hash:x.hash,chainId:x.chainId,tokenTransfers:b?[]:y.tokenTransfers??[],calls:x.calls}})},g=await p.relayerService.createAction({user:o,chainAuthorizations:a.map(x=>({r:x.r,s:x.s,yParity:x.yParity,address:x.address,chainId:Number(x.chainId),nonce:Number(x.nonce)})),intents:[f]});if(g){const x=p.createInitialSteps(t,p.getChainName),[m,y]=g.intentIds[0].split("/"),b=parseInt(y||"0",10),S=g.intentIds[0];e.startStatusPolling(g.intentIds[0],x),await Eo({actionId:m,intentIndex:b,intentId:S,totalSteps:t.length,isSpicenetStep:w=>t[w]?.domain==="spicenet",maxExecuteAttemptsForStep:w=>t[w]?.domain==="spicenet"?6:3,maxPolls:180})}}async function Ko(e){let t=dn(e);if(t.length===0)throw new Error("No lock batches configured");const s=e.isSemi7702&&e.providerEmbeddedAddress||e.address;if(!e.isConnected||!s)throw new Error("Please connect your wallet to continue");const o=await zs(e,s,t);let a=Ut([...t],s),r;for(let i=0;i<4;i+=1){const d=await p.relayerService.estimateActionFees(Ps(s,a,o.map(f=>({r:f.r,s:f.s,yParity:f.yParity,address:f.address,chainId:Number(f.chainId),nonce:Number(f.nonce)})))),u=Un(d,{symbol:e.selectedAsset?.asset.symbol??"",decimals:e.selectedAsset?.asset.decimals??18});if(!u)break;const l={grossAmount:u.grossAmount,netAmount:u.netAmount,feeAmount:u.totalFee??0n},h=r?.grossAmount===l.grossAmount&&r?.netAmount===l.netAmount&&r?.feeAmount===l.feeAmount;if(r=l,t=dn(e,r),a=Ut([...t],s,d),h)break}await qo(e,a,o)}async function Ui(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount)throw new Error("Select an asset and enter an amount");if(!e.address||!e.embeddedWalletAddress)throw new Error("Embedded wallet not connected");const t=e.selectedAsset.asset,s=j.parseUnits(e.selectedAsset.amount,t.decimals),o=e.escrowAddress||p.getDelegateContractAddress(e.lockChainId),a=p.relayerService.getBaseUrl(),r=F.normalizeNativeTokenAddress(t.address);let i=0n;try{i=await Vo(a,e.embeddedWalletAddress,e.lockChainId,r)}catch(f){console.warn("[SpiceLockModal] could not snapshot spice balance pre-deposit:",f?.message)}const d=await e.actions.getEthereumProvider();await p.ensureWalletOnChain(d,e.lockChainId);const u=p.getChainConfig(e.lockChainId),l=j.createWalletClient({account:e.embeddedWalletAddress,transport:j.custom(d),chain:u?.viemChain});let h;if(t.isNative||F.isNativeToken(t.address))h=await l.sendTransaction({to:o,value:s,chain:u?.viemChain});else{const f=j.encodeFunctionData({abi:p.U,functionName:"transfer",args:[o,s]});h=await l.sendTransaction({to:t.address,data:f,chain:u?.viemChain})}if((await p.getClientForChain(e.lockChainId).waitForTransactionReceipt({hash:h,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to escrow failed");await Ni({apiBaseUrl:a,user:e.embeddedWalletAddress,chainId:e.lockChainId,tokenAddress:r,prevBalance:i}),await e.refreshSpiceAssets(),e.refreshWalletAssets(),await Ko(e)}async function Pi(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 A=e.resolveLockBatches();if(A.length===0)throw new Error("No lock batches configured");const E=e.selectedAsset.asset,R=j.parseUnits(e.selectedAsset.amount,E.decimals),B=await e.onLockExecute({asset:E,amount:e.selectedAsset.amount,amountWei:R,lockDurationMonths:e.selectedDuration?.months??0,chainBatches:A});B&&e.onLockSuccess?.(B);return}const s=e.resolveLockBatches();if(s.length===0)throw new Error("No lock batches configured");const o=e.selectedAsset.asset,a=j.parseUnits(e.selectedAsset.amount,o.decimals),r=o.chainId,i=e.escrowAddress||F.getEscrowContractAddress(r),d=F.normalizeNativeTokenAddress(o.address),u=o.isNative||F.isNativeToken(d),l=s.some(A=>A.tokenTransfers?.some(E=>E.from==="escrow")),h=A=>({chainId:r,calls:u?[{to:i,value:A,data:"0x"}]:[{to:d,value:0n,data:j.encodeFunctionData({abi:p.U,functionName:"transfer",args:[i,A]})}]}),f=(A,E,R)=>{const B=h(A);if(!l)return[B,...E];const I=Ut([...E],t,R);return[B,...I]};let g=dn(e),x=f(a,g);const m=await zs(e,t,x);let y;if(l)for(let A=0;A<4;A+=1){const E=await p.relayerService.estimateActionFees(Ps(t,x,m.map(T=>({r:T.r,s:T.s,yParity:T.yParity,address:T.address,chainId:Number(T.chainId),nonce:Number(T.nonce)})))),R=Un(E,{symbol:o.symbol,decimals:o.decimals});if(!R)break;const B={grossAmount:R.grossAmount,netAmount:R.netAmount,feeAmount:R.totalFee??0n},I=y?.grossAmount===B.grossAmount&&y?.netAmount===B.netAmount&&y?.feeAmount===B.feeAmount;if(y=B,g=dn(e,y),x=f(B.grossAmount,g,E),I)break}const b=y?.grossAmount??a,S=await e.externalWallet.getEthereumProvider();let w=null;try{const A=await S.request({method:"eth_chainId"});w=parseInt(A,16)}catch{w=null}w!==r&&await p.ensureWalletOnChain(S,r);const C=p.getChainConfig(r),v=j.createWalletClient({account:e.externalWalletAddress,chain:C?.viemChain,transport:j.custom(S)}),k=u?await v.sendTransaction({to:t,value:b,chain:C?.viemChain}):await v.sendTransaction({to:d,data:j.encodeFunctionData({abi:p.U,functionName:"transfer",args:[t,b]}),chain:C?.viemChain});if((await p.getClientForChain(r).waitForTransactionReceipt({hash:k,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transfer to embedded wallet failed");await qo(e,x,m)}async function zi(e){if(!e.selectedAsset?.asset||!e.selectedAsset.amount||!e.requiresRelayerFeeEstimate)return null;if(e.isSemi7702){const i=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!i)throw new Error("Embedded wallet not available \u2014 sign in to create one before locking");let d=dn(e);if(d.length===0)throw new Error("No lock batches configured");const u=e.selectedAsset.asset,l=j.parseUnits(e.selectedAsset.amount,u.decimals),h=u.chainId,f=e.escrowAddress||F.getEscrowContractAddress(h),g=F.normalizeNativeTokenAddress(u.address),x=u.isNative||F.isNativeToken(g),m=d.some(v=>v.tokenTransfers?.some(k=>k.from==="escrow")),y=v=>({chainId:h,calls:x?[{to:f,value:v,data:"0x"}]:[{to:g,value:0n,data:j.encodeFunctionData({abi:p.U,functionName:"transfer",args:[f,v]})}]}),b=(v,k,A)=>{const E=y(v);if(!m)return[E,...k];const R=Ut([...k],i,A);return[E,...R]};let S=b(l,d),w=null,C;for(let v=0;v<4;v+=1){const k=await p.relayerService.estimateActionFees(Us(i,S)),A=Un(k,{symbol:u.symbol,decimals:u.decimals});if(!A)return w;const E={grossAmount:A.grossAmount,netAmount:A.netAmount,feeAmount:A.totalFee??0n},R=C?.grossAmount===E.grossAmount&&C?.netAmount===E.netAmount&&C?.feeAmount===E.feeAmount;if(w=A,C=E,d=dn(e,E),S=b(E.grossAmount,d,k),R)break}return w}const t=e.address;if(!e.isConnected||!t)throw new Error("Please connect your wallet to continue");let s=dn(e);if(s.length===0)throw new Error("No lock batches configured");let o=Ut([...s],t),a=null;for(let i=0;i<4;i+=1){const d=await p.relayerService.estimateActionFees(Us(t,o)),u=Un(d,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals});if(!u)return null;const l={grossAmount:u.grossAmount,netAmount:u.netAmount},h=a?.grossAmount===u.grossAmount&&a?.netAmount===u.netAmount&&a?.totalFee===u.totalFee;if(a=u,s=dn(e,l),o=Ut([...s],t,d),h)break}if(a)return a;const r=await p.relayerService.estimateActionFees(Us(t,o));return Un(r,{symbol:e.selectedAsset.asset.symbol,decimals:e.selectedAsset.asset.decimals})}async function Li(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.resolveLockBatches();if(t.length===0)throw new Error("No lock batches configured");const s=t.find(l=>l.chainId===e.lockChainId)||t[0];if(!s)throw new Error("No lock batch for lock chain");const o=await e.externalWallet.getEthereumProvider();let a=null;try{const l=await o.request({method:"eth_chainId"});a=parseInt(l,16)}catch{a=null}a!==e.lockChainId&&await p.ensureWalletOnChain(o,e.lockChainId);const r=p.getChainConfig(e.lockChainId),i=j.createWalletClient({account:e.externalWalletAddress,chain:r?.viemChain,transport:j.custom(o)}),d=p.getClientForChain(e.lockChainId);let u;for(const l of s.calls){const h=await i.sendTransaction({to:l.to,data:l.data,value:l.value,chain:r?.viemChain});if((await d.waitForTransactionReceipt({hash:h,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Lock transaction failed");u=h}u&&e.onLockSuccess?.(u)}async function Oi(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=s=>{console.error("[SpiceLockModal] lock failed:",s);const o=p.sanitizeError(s,""),a=typeof s?.shortMessage=="string"?s.shortMessage:typeof s?.message=="string"?s.message:"";e.ui.setError(o||a||"Transaction failed. Please try again.")};if(e.isSemi7702){if(e.isSourceDestToken){try{await Li(e)}catch(s){t(s)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{await Pi(e)}catch(s){t(s)}finally{e.ui.setIsExecuting(!1)}return}e.ui.setShowStatusPanel(!0);try{e.isDirectDeposit&&!e.isSourceDestToken?await Ui(e):await Ko(e)}catch(s){t(s)}finally{e.ui.setIsExecuting(!1)}}const Zo=({isOpen:e,onClose:t,closeOnBackdropClick:s=!1,lockBatches:o,lockTokenSymbol:a,lockTokenLogoURI:r,destinationInputHook:i,sourceAssetInputHook:d,lockDurationHook:u,lockChainId:l,durationOptions:h,votingPowerEstimate:f,escrowAddress:g,includeWalletAssets:x=!1,destinationTokenAddress:m,onLockSuccess:y,onLockExecute:b,sourceToDestinationConversionRate:S,estimatedOutputAmount:w,onAddFunds:C,buildSpicenetBatch:v,styles:k,dark:A=!1})=>{const{theme:E,dark:R,primaryColor:B,dk:I}=p.useSpiceBrand(k,A),T=E.typography.fontFamily,D=c.useContext(p.SpiceFlowProviderContext),M=D?.mode||"7702",U=!!D?.isWhitelistGateActive,z=M!=="7702",W=c.useMemo(()=>D?.supportedChainIds??[],[D?.supportedChainIds]),Q=c.useMemo(()=>{if(U)return[];const Z=D?.allowedTokens;if(!Z||Z.length===0)return[];const ye=new Set(Z.map(Ee=>Ee.toLowerCase())),Ae=[],je=new Set;for(const Ee of W){const lt=p.getChainConfig(Ee);for(const ht of lt?.supportedTokens??[]){if(!ye.has(ht.symbol.toLowerCase()))continue;const qt=`${Ee}:${ht.address.toLowerCase()}`;je.has(qt)||(je.add(qt),Ae.push(j.getAddress(ht.address)))}}return Ae},[D?.allowedTokens,W,U]),N=R?I.cardBg:k?.assetSelector?.backgroundColor||k?.secondaryBackground||"#e9e9e9",L=R?`1px solid ${I.cardBorder}`:"0.5px solid #A8A8A7",q=R?"12px":"6px",K=R?I.textPrimary:"#111827",O=R?I.textSecondary:"#6b7280",G=c.useMemo(()=>({...k,assetSelector:{...k?.assetSelector,backgroundColor:R?I.cardBg:k?.assetSelector?.backgroundColor,borderRadius:R?"12px":k?.assetSelector?.borderRadius},secondaryBackground:R?I.cardBg:k?.secondaryBackground}),[k,R]),ce=c.useMemo(()=>R?{...E,colors:{...E.colors,secondary:I.cardBg,surfaceHover:I.hoverBg,border:I.cardBorder,borderHover:I.inputBorder}}:E,[R,E]),[P,ne]=c.useState(null),[me,ke]=c.useState(0),pe=u?.selectedDurationIdx??me,ge=u?.setSelectedDurationIdx??ke,[fe,V]=c.useState(!1),[re,X]=c.useState(null),[le,xe]=c.useState(null),[Se,J]=c.useState(!1),[Y,ae]=c.useState(!1),[Ce,We]=c.useState(null),[rt,Ke]=c.useState(!1),Ze=c.useRef(0),[oe,ie]=c.useState(!1),[Ye,_]=c.useState(null);At.useWalletClient(),At.useSwitchChain();const{chain:Me,address:ct}=At.useAccount();At.useConfig();const kt=c.useRef(Me);c.useEffect(()=>{kt.current=Me},[Me]);const st=p.useWallet(),{isReady:Pt,isAuthenticated:Rt,isConnected:mt,address:Ie,provider:Mt,actions:Zt}=st,{externalWallet:Yt,embeddedAddress:gt,externalAddress:zt}=p.useProviderWallets(),{intentStatus:Ge,startStatusPolling:vt,clearStatus:Qe}=oo({checkStepStatus:(Z,ye)=>p.relayerService.checkStepStatus(Z,ye),retryStep:async(Z,ye)=>{const[Ae,je]=Z.split("/"),Ee=parseInt(je||"0",10);await p.relayerService.executeStep(Ae,Ee,ye,{action:"execute"})},maxRetries:3}),{assets:$e,refetch:_e}=Wn({address:Ie,supportedChains:W,enabled:e&&mt&&!z&&!U,refetchInterval:3e4}),dt=c.useMemo(()=>{if(U)return[];if(Q.length===0)return $e;const Z=new Set(Q.map(ye=>ye.toLowerCase()));return $e.filter(ye=>Z.has(ye.address.toLowerCase()))},[$e,Q,U]),Et=p.useEmbeddedWalletAddress(),he=zt||ct,at=z?he:Et,it=c.useMemo(()=>{if(!x)return[];if(U)return m?[j.getAddress(m)]:[];const Z=new Set,ye=[],Ae=je=>{if(!je)return;const Ee=je.toLowerCase();Z.has(Ee)||(Z.add(Ee),ye.push(j.getAddress(je)))};if(m&&Ae(m),z)for(const je of Q)Ae(je);return ye},[x,z,m,Q,U]),jt=c.useMemo(()=>it.map(Z=>Z.toLowerCase()).sort().join(","),[it]),be=c.useMemo(()=>JSON.stringify([...W||[]].sort()),[W]),[Dt,et]=c.useState([]),ut=c.useRef(0),xt=c.useCallback(async()=>{if(!x||!at||it.length===0){ut.current++,et([]);return}const Z=++ut.current,ye=j.getAddress(at),Ae=W&&W.length>0?W:[l],je=it.map(H=>{const $=H.toLowerCase();if(m&&p.addressesEqual(H,m)){const ue=p.getChainConfig(l)?.supportedTokens?.find(ee=>p.addressesEqual(ee.address,$));return{address:H,chainId:l,configToken:ue?{decimals:ue.decimals,symbol:ue.symbol,name:ue.name,logo:ue.logo}:void 0}}for(const ue of Ae){const ee=p.getChainConfig(ue)?.supportedTokens?.find(Re=>p.addressesEqual(Re.address,$));if(ee)return{address:H,chainId:ue,configToken:{decimals:ee.decimals,symbol:ee.symbol,name:ee.name,logo:ee.logo}}}return{address:H,chainId:l}}),Ee=new Map;for(const H of je){const $=Ee.get(H.chainId)||[];$.push(H),Ee.set(H.chainId,$)}const lt=async(H,$)=>{try{const ue=await Tt.readContract(H,{address:$.address,abi:p.U,functionName:"balanceOf",args:[ye]});let ee,Re,Fe,Pe;if($.configToken)ee=$.configToken.decimals,Re=$.configToken.symbol,Fe=$.configToken.name,Pe=$.configToken.logo;else{const[Ft,pt,It]=await Promise.all([Tt.readContract(H,{address:$.address,abi:p.U,functionName:"decimals",args:[]}).catch(()=>18),Tt.readContract(H,{address:$.address,abi:p.U,functionName:"symbol",args:[]}).catch(()=>"TOKEN"),Tt.readContract(H,{address:$.address,abi:p.U,functionName:"name",args:[]}).catch(()=>"TOKEN")]);ee=Number(Ft),Re=pt,Fe=It}const ot=!!m&&p.addressesEqual($.address,m)&&$.chainId===l;ot&&r&&(Pe=r),ot&&a&&!$.configToken&&(Re==="TOKEN"&&(Re=a),Fe==="TOKEN"&&(Fe=a));const Qt=parseFloat((Number(ue)/Math.pow(10,ee)).toFixed(6));return{address:$.address,name:Fe,symbol:Re,decimals:ee,balance:ue,balanceFormatted:Qt,balanceUsd:0,logoURI:Pe,isNative:!1,chainId:$.chainId}}catch{return null}},ht=await Promise.all(Array.from(Ee.entries()).map(async([H,$])=>{let ue;try{ue=p.getClientForChain(H)}catch{return[]}const ee=[],Re=[];for(const Pe of $){const ot=ee.length;ee.push({address:Pe.address,abi:p.U,functionName:"balanceOf",args:[ye]}),Pe.configToken||ee.push({address:Pe.address,abi:p.U,functionName:"decimals",args:[]},{address:Pe.address,abi:p.U,functionName:"symbol",args:[]},{address:Pe.address,abi:p.U,functionName:"name",args:[]}),Re.push({start:ot,item:Pe})}let Fe=null;try{Fe=await ue.multicall({contracts:ee})}catch{Fe=null}return Fe?Re.map(({start:Pe,item:ot})=>{const Qt=Fe[Pe],Ft=Qt?.status==="success"?Qt.result:0n;let pt,It,Xt,an;if(ot.configToken)pt=ot.configToken.decimals,It=ot.configToken.symbol,Xt=ot.configToken.name,an=ot.configToken.logo;else{const we=Fe[Pe+1],de=Fe[Pe+2],Be=Fe[Pe+3];pt=we?.status==="success"?Number(we.result):18,It=de?.status==="success"?de.result:"TOKEN",Xt=Be?.status==="success"?Be.result:It}const xn=!!m&&p.addressesEqual(ot.address,m)&&ot.chainId===l;xn&&r&&(an=r),xn&&a&&!ot.configToken&&(It==="TOKEN"&&(It=a),Xt==="TOKEN"&&(Xt=a));const yn=parseFloat((Number(Ft)/Math.pow(10,pt)).toFixed(6));return{address:ot.address,name:Xt,symbol:It,decimals:pt,balance:Ft,balanceFormatted:yn,balanceUsd:0,logoURI:an,isNative:!1,chainId:ot.chainId}}):(await Promise.all($.map(Pe=>lt(ue,Pe)))).filter(Pe=>Pe!==null)}));if(Z!==ut.current)return;const qt=ht.flat();et(qt)},[x,at,jt,be,l,m,r,a]);c.useEffect(()=>{if(!e||!x){et([]);return}xt();const Z=setInterval(()=>{xt()},15e3);return()=>clearInterval(Z)},[xt,x,e]);const Gt=c.useCallback(()=>{xt()},[xt]),Lt=c.useMemo(()=>Dt.filter(Z=>Z.balance>0n),[Dt]),Xe=c.useMemo(()=>{if(z)return Lt.map(ye=>({...ye,_source:"wallet"}));if(!x)return dt;const Z=[];for(const ye of Lt)Z.push({...ye,_source:"wallet"});for(const ye of dt)Z.push({...ye,_source:"spice"});return Z},[z,x,Lt,dt]),_t=c.useMemo(()=>U?m?Xe.filter(Z=>p.addressesEqual(Z.address,m)&&Z.chainId===l):[]:Xe,[Xe,U,m,l]),Te=c.useRef(null),ft=c.useRef(null);c.useEffect(()=>{ft.current=P},[P]),c.useEffect(()=>{!U||!P?.asset||m&&p.addressesEqual(P.asset.address,m)&&P.asset.chainId===l||ne(null)},[U,P?.asset,m,l]),c.useEffect(()=>{e||(ne(null),X(null),xe(null),J(!1),ae(!1),We(null),V(!1),ie(!1),_(null),Ke(!1),Qe())},[e,Qe]),c.useEffect(()=>{i&&i.assetAmount!==(P?.amount||"")&&ne(Z=>Z&&{...Z,amount:i.assetAmount})},[i?.assetAmount]),c.useEffect(()=>{d&&d.assetAmount!==(P?.amount||"")&&ne(Z=>Z&&{...Z,amount:d.assetAmount})},[d?.assetAmount]),c.useEffect(()=>{if(!z&&Ge?.overallStatus==="success"&&Ge.intentId&&Te.current!==Ge.intentId&&Ie&&Ge.steps.find(Z=>Z.transactionHash)?.transactionHash){Te.current=Ge.intentId;const Z=ft.current;if(!Z?.asset||!Z.amount||Z.asset._source==="wallet"||j.parseUnits(Z.amount,Z.asset.decimals)===0n)return;_e()}},[Ge,Ie,l,_e,z]);const Oe=parseFloat(P?.amount||"")||0,yt=c.useMemo(()=>P?.asset?P.asset._source==="wallet"?P.asset.balanceFormatted??0:dt.find(Z=>p.addressesEqual(Z.address,P.asset.address)&&Z.chainId===P.asset.chainId)?.balanceFormatted??0:0,[P?.asset,dt]),qe=Oe>0&&(Ce?parseFloat(j.formatUnits(Ce.grossAmount,Ce.decimals))>yt:Oe>yt),Ct=u?.selectedDuration??h[pe]??h[0],Ue=c.useMemo(()=>!P?.asset||!m?!1:p.addressesEqual(P.asset.address,m)&&P.asset.chainId===l,[P?.asset,m,l]),Je=c.useMemo(()=>Oe<=0?0:Ue?Oe:!S||S<=0?0:Oe/S,[Oe,S,Ue]),He=c.useMemo(()=>Je<=0?null:Je.toLocaleString(void 0,{maximumFractionDigits:2}),[Je]),bt=f&&Je>0&&Ct?f(Je,Ct.months):void 0,tt=c.useMemo(()=>Oe<=0?"$0.00":Ue&&S?(Oe*S).toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}):!S||S<=0?"$0.00":Oe.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2}),[Oe,S,Ue]),Ot=c.useMemo(()=>{if(!He)return null;const Z=parseFloat(He.replace(/,/g,""));return Ue&&S?(Z*S).toLocaleString(void 0,{maximumFractionDigits:2}):S?(Z*S).toLocaleString(void 0,{maximumFractionDigits:2}):null},[He,S,Ue]),De=c.useCallback(Z=>{ne(ye=>({asset:Z,amount:ye?.asset?.address===Z.address&&ye?.asset?.chainId===Z.chainId&&ye.amount||""})),X(null),xe(null),ae(!1),We(null),d?.setSelectedAsset&&d.setSelectedAsset({symbol:Z.symbol,address:Z.address,decimals:Z.decimals,chainId:Z.chainId})},[d?.setSelectedAsset]),Vt=c.useCallback(Z=>{ne(ye=>ye&&{...ye,amount:Z}),X(null),xe(null),ae(!1),We(null),i&&i.setAssetAmount(Z),d&&d.setAssetAmount(Z)},[i,d]),Ht=c.useCallback(Z=>{if(typeof o=="function"){if(!P?.asset||!P.amount)throw new Error("Select an asset and enter an amount");return o({asset:P.asset,amount:Z?.amount??P.amount,amountWei:Z?.amountWei??j.parseUnits(P.amount,P.asset.decimals),grossAmount:Z?.grossAmount,grossAmountWei:Z?.grossAmountWei,feeAdjusted:!!Z})}return o},[o,P]),St=c.useRef(null),te=c.useMemo(()=>!P?.asset||Oe<=0?!1:z?!Ue&&!b:!0,[P,Oe,z,Ue,b]),se=c.useCallback(()=>zi(St.current),[]);c.useEffect(()=>{if(!e||fe)return;if(!P?.asset||Oe<=0){xe(null),J(!1),ae(!1),We(null);return}if(!te){xe(null),J(!1),ae(!0),We(null);return}let Z=!1;const ye=async()=>{const Ee=++Ze.current;xe(null),ae(!1),J(!0);try{const lt=await se();if(Z||Ze.current!==Ee)return;xe(null),ae(!0),We(lt)}catch(lt){if(Z||Ze.current!==Ee)return;xe(p.sanitizeError(lt,"Unable to calculate fees for this lock.")),ae(!1)}finally{!Z&&Ze.current===Ee&&J(!1)}},Ae=window.setTimeout(()=>{ye()},250),je=window.setInterval(()=>{ye()},1e4);return()=>{Z=!0,clearTimeout(Ae),window.clearInterval(je),J(!1),ae(!1)}},[e,fe,P,Oe,te,se]),c.useEffect(()=>{if(Ge?.overallStatus==="success"){const Z=Ge.steps.find(ye=>ye.transactionHash);y?.(Z?.transactionHash)}},[Ge?.overallStatus,y]);const ve=x&&P?.asset?._source==="wallet"&&P?.asset?.chainId===l,ze=c.useCallback(()=>Oi(St.current),[]),nt=!!P?.asset&&Oe>0&&!qe&&!fe&&(!te||Y&&!Se&&!le),Le=re||le,Ve=n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"6px"},children:[n.jsx(bs,{color:O}),n.jsxs("p",{style:{fontSize:"13px",color:O,margin:0,lineHeight:"1.5"},children:["Add ",a," by converting assets from your account"]})]});if(St.current={selectedAsset:P,parsedAmount:Oe,selectedDuration:Ct,isInsufficientBalance:qe,isSemi7702:z,isSourceDestToken:Ue,isDirectDeposit:ve,requiresRelayerFeeEstimate:te,address:Ie,embeddedWalletAddress:Et,providerEmbeddedAddress:gt,externalWallet:Yt,externalWalletAddress:he,isConnected:mt,ready:Pt,authenticated:Rt,provider:Mt,actions:Zt,lockChainId:l,escrowAddress:g,onLockExecute:b,onLockSuccess:y,buildSpicenetBatch:v,resolveLockBatches:Ht,startStatusPolling:vt,refreshSpiceAssets:_e,refreshWalletAssets:Gt,ui:{setError:X,setIsExecuting:V,setShowStatusPanel:Ke}},!e)return null;const Ne={backgroundColor:N,border:L,borderRadius:q,padding:"16px",marginBottom:"16px"};return n.jsx(tn,{isOpen:e,onClose:t,title:`Add ${a} to your account`,subtitle:Ve,styles:k,dark:R,footerLinkText:"Spicenet accounts \u2192",overlayContent:oe?n.jsx("div",{}):void 0,closeOnBackdropClick:s,children:n.jsxs("div",{style:{padding:"0 24px 8px 24px",position:"relative"},children:[n.jsxs("div",{style:{marginBottom:"12px"},children:[C&&n.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:n.jsx(ws,{onClick:C,color:B,fontFamily:T})}),n.jsx("div",{style:{marginTop:"10px",fontSize:"13px",color:O,fontFamily:T},children:n.jsx(Dn,{assets:_t,selectedAsset:P??void 0,onAssetSelect:De,onAmountChange:Vt,label:"Amount",showBalance:!0,showMaxButton:!0,theme:ce,styles:G})}),n.jsx("div",{style:{marginTop:"6px",paddingLeft:"4px",fontSize:"13px",color:O,fontFamily:T},children:tt})]}),n.jsxs("div",{style:Ne,children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"16px",borderBottom:R?`1px solid ${I.cardBorder}`:"1px solid #e5e7eb"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[r?n.jsx("img",{src:r,alt:a,style:{width:"32px",height:"32px",borderRadius:"50%",objectFit:"cover"}}):n.jsx("div",{style:{width:"32px",height:"32px",borderRadius:"50%",backgroundColor:R?I.inputBg:"#d1d5db",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:700,color:K},children:a.slice(0,2)}),n.jsx("span",{style:{fontSize:"16px",fontWeight:600,color:K,fontFamily:T},children:a})]}),n.jsxs("div",{style:{textAlign:"right"},children:[n.jsx("div",{style:{fontSize:"22px",fontWeight:700,color:K,fontFamily:T,lineHeight:1.1},children:He??"0.00"}),n.jsxs("div",{style:{fontSize:"12px",color:O,fontFamily:T,marginTop:"2px"},children:["~$",Ot??"0.00"]})]})]}),n.jsxs("div",{style:{paddingTop:"16px",paddingBottom:"16px",borderBottom:R?`1px solid ${I.cardBorder}`:"1px solid #e5e7eb"},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[n.jsx("span",{style:{fontSize:"15px",fontWeight:500,color:O,fontFamily:T},children:"Lock Duration"}),n.jsx(nn,{color:O})]}),n.jsx(Ai,{options:h,selectedIndex:pe,onSelect:ge,primaryColor:B,dark:R,textPrimary:K,textSecondary:O})]}),n.jsxs("div",{style:{paddingTop:"12px",display:"flex",flexDirection:"column",gap:"8px"},children:[n.jsx(ji,{durationMonths:Ct?.months,fontFamily:T,dark:R,textPrimary:K,textSecondary:O}),f&&n.jsx(Fi,{votes:bt,fontFamily:T,dark:R,textPrimary:K,textSecondary:O})]})]}),te&&n.jsx(Vn,{fontFamily:T,textPrimary:K,textSecondary:O,cardBg:N,cardBorder:L,resolvedDark:R,darkCardBorder:I.cardBorder,primaryColor:B,feePreview:Ce,isLoading:Se,errorText:le}),Le&&n.jsx(Sn,{variant:"error",palette:I,fontFamily:T,style:{marginBottom:"12px"},children:Le}),n.jsx(p.Button,{variant:"outline",fullWidth:!0,onClick:ze,disabled:!nt,loading:fe,dark:R,styles:{...k,button:{...k?.button,backgroundColor:B}},children:fe?ve&&!Ue?"DEPOSITING...":Ue?"LOCKING...":"CONVERTING...":Se&&te?"CALCULATING FEES...":ve&&!Ue?`DEPOSIT ${a}`:Ue?`LOCK ${a}`:`CONVERT TO ${a}`}),n.jsx(Bi,{isOpen:oe,data:Ye,isLocking:fe,lockError:Le,onContinue:ze,onClose:()=>ie(!1),primaryColor:B,fontFamily:T,dark:R}),Ge&&rt&&n.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:R?I.shell:"white",borderRadius:q,padding:"16px 0"},children:n.jsx(As,{type:"deposit",isOpen:!!Ge&&Ge.overallStatus!=="processing",isProcessing:fe||Ge?.overallStatus==="processing",closeOnComplete:!1,onRetryTx:()=>{Qe(),Ke(!1),ze()},onNewTx:()=>{Qe(),Ke(!1),ne(null),Te.current=null,_e(),Gt()},onClose:()=>{Qe(),Ke(!1)},onComplete:()=>{Qe(),Ke(!1),ne(null),Te.current=null,_e(),Gt()},results:Ge?.overallStatus==="success"||Ge?.overallStatus==="failed"?Ge.steps.map(Z=>({asset:{symbol:P?.asset?.symbol||a,address:P?.asset?.address||""},txHash:Z.transactionHash||"",success:Z.status==="success",amount:P?.amount})):void 0,chainName:p.getChainName(l),explorerUrl:p.getExplorerUrl(l,"").replace(/\/tx\/.*$/,"")||void 0,theme:E,styles:k,dark:R})})]})})},Hi="0xa9059cbb";function Qi(e,t,s){return F.isNativeToken(e)?{to:s,value:t,data:"0x"}:{to:e,value:0n,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"transfer",args:[s,t]})}}function Ls(e,t,s,o){return t!=="user-transfer"||!s||e.length===0||e[0]?.to.toLowerCase()!==o.toLowerCase()||!e[0]?.data.startsWith(Hi)?{feeCall:null,remainingCalls:e}:{feeCall:e[0],remainingCalls:e.slice(1)}}async function ts(e,t,s){if(!t)return[e];const o=await t(s);return o?[o,e]:[e]}function En(e,t,s){if(t===s)return e;if(t<s)return e*10n**BigInt(s-t);const o=10n**BigInt(t-s);return(e+o-1n)/o}async function Vi(e,t){const{currentPaymentAmount:s,destinationToken:o,embeddedWalletAddress:a,providerEmbeddedAddress:r,address:i,isNon7702:d,isPayMode:u,resolvedChainId:l,buildActionCalls:h,feeExecutionMode:f,buildSpicenetBatch:g,selectedAsset:x,needsSwap:m,exactOutputSwap:y,resolvedTokenIn:b}=e,S=j.parseUnits(s,o.decimals),w=t?.actionAmountOverride??S,C=a||r||(d?void 0:i);if(!C)throw new Error("Embedded wallet address is not available. Please sign in and try again.");const v={userAddress:C,chainId:l,destinationToken:o.address,grossAmount:t?.fundingAmountOverride??S,netAmount:w,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:f,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},k=h(w,v),A={chainId:l,calls:k},E=(!u&&!d?!0:x?.asset?._source==="spice")||d,R=(B,I)=>({token:B,from:d?"solver":"escrow",to:C,amount:I});if(S===0n)return[A];if(m&&y){const B=b??$t(x.asset,l)??x.asset.address,I=t?.fundingAmountOverride??y.amountInMax,T=E?[R(B,I)]:[],D={to:B,value:0n,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"approve",args:[y.calls[0]?.to,y.amountInMax]})},M={chainId:l,calls:[D,...y.calls,...k],tokenTransfers:[...T,...A.tokenTransfers??[]]};return E?ts(M,g,{userAddress:C,destinationChainId:l,deliveryToken:B,deliveryAmount:I,deliveryRecipient:C,sourceAsset:x.asset}):[M]}if(E){const B=b??$t(x.asset,l)??o.address,I=t?.fundingAmountOverride??S,T={...A,tokenTransfers:[R(B,I),...A.tokenTransfers??[]]};return ts(T,g,{userAddress:C,destinationChainId:l,deliveryToken:B,deliveryAmount:I,deliveryRecipient:C,sourceAsset:x.asset})}return[A]}async function qi(e,t){const{selectedAsset:s,embeddedWalletAddress:o,externalWalletAddress:a,resolvedChainId:r,destinationToken:i,buildActionCalls:d,feeExecutionMode:u,buildSpicenetBatch:l,isPayMode:h,isNon7702:f,needsSwap:g,resolvedSwap:x,quoteAmountOut:m,resolvedTokenIn:y}=e,b=x?.amountOutMinimum??m;if(!s?.asset||!o)return[];const S=f?a:o;if(!S)return[];const w=t?.fundingAmountOverride??t?.actionAmountOverride??j.parseUnits(s.amount,s.asset.decimals),C=t?.fundingAmountOverride??w,v=t?.sourceFundingAmountOverride??w,k=t?.deliveryAmountOverride??C,A=t?.withdrawalAmountOverride??k,E=t?.actionAmountOverride??w,R={userAddress:S,chainId:r,destinationToken:i.address,feeToken:u==="user-transfer"&&g&&y?y:i.address,grossAmount:C,netAmount:E,combinedFeeAmount:t?.actionContextOverride?.combinedFeeAmount,feeExecutionMode:u,feeBreakdown:t?.actionContextOverride?.feeBreakdown,...t?.actionContextOverride},B=d(E,R),I=s.asset?._source==="wallet";if(!h&&f&&I&&s.asset.chainId===r){if(g){if(!y)throw new Error("Swap input token could not be resolved");if(!x||b===null)throw new Error("Swap quote not available yet")}if(g&&x&&b){const L=d(t?.actionAmountOverride??b,{...R,netAmount:t?.actionAmountOverride??b}),{feeCall:q,remainingCalls:K}=Ls(L,u,g,R.feeToken);return[{chainId:r,calls:[...q?[q]:[],...x.calls,...K]}]}return[{chainId:r,calls:B}]}if(!h&&!f&&I){if(s.asset.chainId===r){if(g){if(!y)throw new Error("Swap input token could not be resolved");if(!x||b===null)throw new Error("Swap quote not available yet")}if(g&&x&&b){const L=d(t?.actionAmountOverride??b,{...R,netAmount:t?.actionAmountOverride??b}),{feeCall:q,remainingCalls:K}=Ls(L,u,g,R.feeToken);return[{chainId:r,calls:[...q?[q]:[],...x.calls,...K]}]}return[{chainId:r,calls:B}]}throw new Error("Cross-chain wallet supplies require external wallet mode")}const T=!h&&!f?s.asset?._source!=="wallet":s.asset?._source==="spice",D=f&&I;if(!(T||D))return[{chainId:r,calls:B}];const M=D&&s.asset.chainId!==r?{chainId:s.asset.chainId,calls:[Qi(F.normalizeNativeTokenAddress(s.asset.address),v,F.getEscrowContractAddress(s.asset.chainId))]}:null,U=(L,q)=>({token:L,from:D?"solver":"escrow",to:o,amount:q}),z=(L,q)=>D?[{token:L,from:"escrow",to:F.SPICE_SOLVER_ADDRESS,amount:q}]:[];if(g){if(!y)throw new Error("Swap input token could not be resolved");if(!x||b===null)throw new Error("Swap quote not available yet")}if(g&&x&&b&&y){const L=d(t?.actionAmountOverride??b,{...R,netAmount:t?.actionAmountOverride??b}),{feeCall:q,remainingCalls:K}=Ls(L,u,g,R.feeToken),O={chainId:r,calls:[...q?[q]:[],...x.calls,...K],tokenTransfers:[...z(y,A),U(y,k)]},G=await ts(O,l,{userAddress:o,destinationChainId:r,deliveryToken:y,deliveryAmount:k,withdrawalAmount:A,deliveryRecipient:o,sourceAsset:s.asset});return M?[M,...G]:G}const W=y??$t(s.asset,r)??i.address,Q={chainId:r,calls:B,tokenTransfers:[...z(W,A),U(W,k)]},N=await ts(Q,l,{userAddress:o,destinationChainId:r,deliveryToken:W,deliveryAmount:k,withdrawalAmount:A,deliveryRecipient:o,sourceAsset:s.asset});return M?[M,...N]:N}async function Ki(e,t,s,o,a){let r=e;for(let i=0;i<4;i++){const d=await t(r),u=await o(d,s,r,a),l=ei(u);if(l===null||l>=e)return r;const h=r-l,f=e+h;if(f<=r)return r;r=f}return r}function Zi(e,t,s,o){if(e<=0n)return 0n;const a=e-t;if(a<=0n)return 0n;const r=o+s;return r<=0n?a:a*o/r}function Yi(e,t){const s=j.formatUnits(e,t);return s.includes(".")?s.replace(/\.?0+$/,"")||"0":s}async function Gi(e){const{asset:t,isPayMode:s,isNon7702:o,needsSwap:a,isQuoting:r,embeddedWalletAddress:i,buildSupplyChainBatches:d,estimateGasless:u,executionTokenAddress:l,feeExecutionMode:h}=e;if(s||o||a||r||!i||t.balance<=0n)return null;const f=i,g=await d({fundingAmountOverride:t.balance,actionAmountOverride:t.balance});if(g.length===0)return null;const x=g.some(C=>C.tokenTransfers?.length),m=await u(g,l,t.balance,x?{userOverride:f,useCustomTransfers:!0,feeExecutionMode:h}:h?{userOverride:f,feeExecutionMode:h}:{userOverride:f}),y=hn(m,{chainId:t.chainId,tokenAddress:t.address,symbol:t.symbol,decimals:t.decimals}),b=y?En(y.gasFee,y.decimals,t.decimals):0n,S=y?En(y.spicenetFee,y.decimals,t.decimals):0n,w=Zi(t.balance,b,S,t.balance);return w>0n?Yi(w,t.decimals):null}async function Xi(e){const{selectedAsset:t,isPayMode:s,parsedAmount:o,needsSwap:a,exactOutputSwap:r,isNon7702:i,isSourceDestToken:d,currentPaymentAmount:u,destinationToken:l,feeExecutionMode:h,resolvedTokenIn:f,embeddedWalletAddress:g,providerEmbeddedAddress:x,resolvedChainId:m,isConnected:y,address:b,ready:S,authenticated:w,isDirect:C,resolvedSwap:v,isQuoting:k,executionTokenAddress:A,buildPayChainBatches:E,buildSupplyChainBatches:R,estimateGasless:B,estimateRequiredGrossFunding:I}=e;if(!t?.asset)return null;if(s){if(o<=0||a&&!r||i&&d)return null;const N=j.parseUnits(u,l.decimals),L=f||$t(t.asset,m)||t.asset.address||l.address,q={chainId:m,tokenAddress:L,symbol:F.getTokenByAddress(L,m)?.symbol??t.asset.symbol,decimals:F.getTokenByAddress(L,m)?.decimals??t.asset.decimals};if(i){const ne=g||x;if(!ne)return null;const me=ne,ke=a?r?.amountInMax??0n:N;if(ke===0n)return null;const pe=await I(ke,V=>E({fundingAmountOverride:V}).then(re=>Ut(re,me)),L,{userOverride:ne,useCustomTransfers:!0}),ge=Ut(await E({fundingAmountOverride:pe}),me),fe=await B(ge,L,pe,{userOverride:ne,useCustomTransfers:!0,feeExecutionMode:h});return hn(fe,q)}if(!y||!b||!S||!w)return null;const K=g||x||b,O=a?r?.amountInMax??0n:N;if(O===0n)return null;const G=await I(O,ne=>E({fundingAmountOverride:ne}).then(me=>Ut(me,K)),L,{useCustomTransfers:!0});let ce=Ut(await E({fundingAmountOverride:G}),K);const P=await B(ce,L,G,{useCustomTransfers:!0,feeExecutionMode:h});return hn(P,q)}if(o<=0||!g)return null;const T=g||x;if(!(!s&&!i&&t.asset?._source==="wallet"&&t.asset.chainId!==m)&&!C&&!v&&!k||k)return null;const D=j.parseUnits(t.amount,t.asset.decimals),M=await R();if(M.length===0)return null;const U=i&&t.asset?._source==="wallet"&&t.asset.chainId===m,z={chainId:m,tokenAddress:A,symbol:F.getTokenByAddress(A,m)?.symbol??l.symbol,decimals:F.getTokenByAddress(A,m)?.decimals??l.decimals};if(U){const N=await p.relayerService.estimateBatchGas({user:T,outputToken:A,stepIndex:0,chainBatches:M}),L=Bs(D,10n),q=L+N.gasFee;return{...z,grossAmount:D+q,netAmount:D,totalFee:q,gasFee:N.gasFee,spicenetFee:L,bridgeFee:0n,gasQuoteSource:N.gasQuoteSource}}const W=M.some(N=>N.tokenTransfers?.length),Q=await B(M,A,D,W?{userOverride:T,useCustomTransfers:!0,feeExecutionMode:h}:h?{userOverride:T,feeExecutionMode:h}:{userOverride:T});return hn(Q,z)}function Yo(e,t){const s=e.selectedAsset?.asset;if(!s||s?._source!=="wallet")return;const o=$t(s,e.resolvedChainId);if(!o||!p.addressesEqual(o,e.executionTokenAddress))return;const a=F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),r=En(t,a?.decimals??e.destinationToken.decimals,s.decimals);if(r<=s.balance)return;const i=j.formatUnits(r,s.decimals),d=j.formatUnits(s.balance,s.decimals);throw new Error(`Insufficient ${s.symbol} for amount plus fees. Required ${i} ${s.symbol}; available ${d} ${s.symbol}.`)}async function Ji(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){if(!e.externalWalletAddress){e.ui.setError("Please connect your external 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 s=await Go(e);e.ui.setTxHash(s??null)}else{e.ui.setStep("signing-delegation"),e.ui.setStatusMsg("Building transaction..."),e.refs.spiceDepositSubmittedRef.current=!1;const s=new AbortController;e.refs.abortControllerRef.current=s,await $i(e,s.signal)}e.ui.setStep("success"),e.ui.setStatusMsg(e.isSourceDestToken?"Transaction confirmed":"Deposit confirmed")}catch(s){const o=s instanceof Error?s:new Error(String(s));if(o.name==="AbortError"||e.refs.abortControllerRef.current?.signal.aborted){e.ui.setStep("idle");return}const a=o.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(a),e.ui.setError(a),e.onError?.(o)}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 s=j.parseUnits(e.selectedAsset.amount,e.selectedAsset.asset.decimals),o=s;let a=await e.gasless.buildSupplyChainBatches();const r=e.selectedAsset.asset?._source==="wallet",i=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(e.buildSpicenetBatch&&!e.isPayMode&&!e.isNon7702&&!r&&!a.some(g=>F.isSpicenetChainId(g.chainId)))throw new Error("Spice-funded supplies must include a Spicenet funding batch before the destination chain batch.");const d=a.some(g=>g.tokenTransfers?.length)?{userOverride:i,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode}:e.feeExecutionMode?{userOverride:i,feeExecutionMode:e.feeExecutionMode}:{userOverride:i};let u=s;const l=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,h=e.feeExecutionMode==="user-transfer"&&!l?o:void 0;let f;for(let g=0;g<4;g+=1){const x=await e.gasless.estimateGasless(a,e.executionTokenAddress,u,d),m=hn(x,{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId)?.symbol??e.destinationToken.symbol,decimals:F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId)?.decimals??e.destinationToken.decimals}),y=m?.grossAmount??u;if(f=e.feeExecutionMode==="user-transfer"&&m?{grossAmount:m.grossAmount,netAmount:o,combinedFeeAmount:m.totalFee,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:m.spicenetFee,gasFee:m.gasFee,bridgeFee:m.bridgeFee??0n}}:void 0,e.feeExecutionMode==="user-transfer"&&m){u=y;break}if(y===u){u=y;break}u=y,a=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:h,actionContextOverride:f})}e.feeExecutionMode==="user-transfer"&&(Yo(e,u),a=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:u,actionAmountOverride:h,actionContextOverride:f})),await e.gasless.executeGasless(a,e.executionTokenAddress,u,e.gasless.onProgress,t.signal,d),e.ui.setStep("success"),e.ui.setStatusMsg("Deposit confirmed")}catch(s){const o=s instanceof Error?s:new Error(String(s));if(o.name==="AbortError"||t.signal.aborted){e.ui.setStep("idle");return}const a=o.message||"Transaction failed";e.ui.setStep("error"),e.ui.setStatusMsg(a),e.ui.setError(a),e.onError?.(o)}finally{e.ui.setIsExecuting(!1)}}async function $i(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 s=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!s)throw new Error("Embedded wallet not available \u2014 sign in to create one before supplying");const o=e.selectedAsset.asset,a=j.parseUnits(e.selectedAsset.amount,o.decimals),r=a,i=o?._source==="wallet"&&o.chainId===e.resolvedChainId;let d=await e.gasless.buildSupplyChainBatches();const u={userOverride:s,useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode};let l=a;const h=e.feeExecutionMode==="user-transfer"&&e.needsSwap&&!e.exactOutputSwap,f=e.feeExecutionMode==="user-transfer"&&!h?r:void 0;let g;if(i){const R=await p.relayerService.estimateBatchGas({user:s,outputToken:e.executionTokenAddress,stepIndex:0,chainBatches:d}),B=Bs(a,10n),I=B+R.gasFee;l=a+I,e.feeExecutionMode==="user-transfer"&&(g={grossAmount:l,netAmount:r,combinedFeeAmount:I,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:B,gasFee:R.gasFee,bridgeFee:0n}})}else{const R=await e.gasless.estimateGasless(d,e.executionTokenAddress,0n,u),B=hn(R,{chainId:e.resolvedChainId,tokenAddress:e.executionTokenAddress,symbol:F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId)?.symbol??e.destinationToken.symbol,decimals:F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId)?.decimals??e.destinationToken.decimals});B&&(l=B.grossAmount>a?B.grossAmount:a,e.feeExecutionMode==="user-transfer"&&(g={grossAmount:l,netAmount:r,combinedFeeAmount:B.totalFee,feeExecutionMode:e.feeExecutionMode,feeBreakdown:{spicenetFee:B.spicenetFee,gasFee:B.gasFee,bridgeFee:B.bridgeFee??0n}}))}const x=F.getTokenByAddress(e.executionTokenAddress,e.resolvedChainId),m=i?l:En(l,x?.decimals??e.destinationToken.decimals,o.decimals);Yo(e,l),d=await e.gasless.buildSupplyChainBatches({fundingAmountOverride:l,sourceFundingAmountOverride:m,withdrawalAmountOverride:l,actionAmountOverride:f,actionContextOverride:g});const y=o.chainId,b=s,S=await e.externalWallet.getEthereumProvider();let w=null;try{const R=await S.request({method:"eth_chainId"});w=parseInt(R,16)}catch{w=null}w!==y&&(e.ui.setStatusMsg("Switching source network..."),await p.ensureWalletOnChain(S,y));const C=p.getChainConfig(y),v=j.createWalletClient({account:e.externalWalletAddress,chain:C?.viemChain,transport:j.custom(S)}),k=F.normalizeNativeTokenAddress(o.address),A=o.isNative||F.isNativeToken(k);e.ui.setStatusMsg("Funding embedded wallet...");const E=A?await v.sendTransaction({to:b,value:m,chain:C?.viemChain}):await v.sendTransaction({to:k,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"transfer",args:[b,m]}),chain:C?.viemChain});if((await p.getClientForChain(y).waitForTransactionReceipt({hash:E,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Embedded wallet funding failed");e.ui.setStatusMsg("Signing supply intent..."),await e.gasless.executeGasless(d,e.executionTokenAddress,0n,e.gasless.onProgress,t,u)}async function Go(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=j.parseUnits(e.isPayMode?e.currentPaymentAmount:e.selectedAsset.amount,e.destinationToken.decimals),s={userAddress:e.externalWalletAddress,chainId:e.resolvedChainId,destinationToken:e.destinationToken.address},o=e.buildActionCalls(t,s);if(o.length===0)throw new Error("No action calls configured");const a=await e.externalWallet.getEthereumProvider();let r=null;try{const h=await a.request({method:"eth_chainId"});r=parseInt(h,16)}catch{r=null}r!==e.resolvedChainId&&await p.ensureWalletOnChain(a,e.resolvedChainId);const i=p.getChainConfig(e.resolvedChainId),d=j.createWalletClient({account:e.externalWalletAddress,chain:i?.viemChain,transport:j.custom(a)}),u=p.getClientForChain(e.resolvedChainId);let l;for(const h of o){const f=await d.sendTransaction({to:h.to,data:h.data,value:h.value,chain:i?.viemChain});if((await u.waitForTransactionReceipt({hash:f,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Transaction failed");l=f}return l}async function _i(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 s=e.selectedAsset.asset,o=s.chainId,a=j.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),r=e.selectedIsEquivalent?a:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(r===0n)throw new Error("Quote not available yet");const i=e.resolvedTokenIn||e.selectedAsset.asset.address,d={userOverride:t,useCustomTransfers:!0},u=await e.gasless.estimateRequiredGrossFunding(r,w=>e.gasless.buildPayChainBatches({fundingAmountOverride:w}),i,d),l=F.getEscrowContractAddress(o),h=await e.externalWallet.getEthereumProvider();let f=null;try{const w=await h.request({method:"eth_chainId"});f=parseInt(w,16)}catch{f=null}f!==o&&await p.ensureWalletOnChain(h,o);const g=p.getChainConfig(o),x=j.createWalletClient({account:e.externalWalletAddress,chain:g?.viemChain,transport:j.custom(h)}),m=F.normalizeNativeTokenAddress(s.address),y=s.isNative||F.isNativeToken(m)?await x.sendTransaction({to:l,value:u,chain:g?.viemChain}):await x.sendTransaction({to:m,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"transfer",args:[l,u]}),chain:g?.viemChain});if((await p.getClientForChain(o).waitForTransactionReceipt({hash:y,timeout:12e4,pollingInterval:2e3,confirmations:1})).status!=="success")throw new Error("Escrow deposit failed");const b=await e.gasless.buildPayChainBatches({fundingAmountOverride:u}),S=b.some(w=>w.tokenTransfers?.length);return await e.gasless.executeGasless(b,i,u,w=>{w.txHash&&(e.ui.setPaymentResult(C=>({...C??{status:"processing"},txHash:w.txHash})),e.ui.setTxHash(w.txHash))},void 0,S?d:{userOverride:t})}async function el(e){if(e.parsedAmount<0){e.ui.setError("Enter a valid payment amount");return}if(!e.selectedAsset?.asset){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){if(!e.externalWalletAddress){e.ui.setError("Please connect your external wallet to continue");return}e.ui.setIsExecuting(!0),e.ui.setError(null),e.ui.setShowStatusPanel(!0),e.ui.setPaymentResult({status:"processing"});try{let t;if(e.isSourceDestToken||e.parsedAmount===0)t=await Go(e);else if(e.onPayExecute&&e.selectedAsset?.asset){const s=e.selectedAsset.asset,o=j.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),a=e.selectedIsEquivalent?o:e.exactOutputSwap?e.exactOutputSwap.amountInMax:0n;if(a===0n)throw new Error("Quote not available yet");const r=e.embeddedWalletAddress||e.providerEmbeddedAddress;if(!r)throw new Error("Embedded wallet not available \u2014 sign in to create one before paying");const i=e.resolvedTokenIn||s.address,d=await e.gasless.estimateRequiredGrossFunding(a,h=>e.gasless.buildPayChainBatches({fundingAmountOverride:h}),i,{userOverride:r,useCustomTransfers:!0}),u=await e.gasless.buildPayChainBatches({fundingAmountOverride:d}),l=await e.onPayExecute({asset:s,amount:e.currentPaymentAmount,amountWei:o,destinationToken:e.destinationToken,chainBatches:u,requiredNetFunding:a,grossFundingAmount:d,selectedIsEquivalent:e.selectedIsEquivalent,resolvedTokenIn:i,exactOutputSwapAmountInMax:e.exactOutputSwap?.amountInMax});l&&(e.ui.setTxHash(l),e.ui.setPaymentResult(h=>({...h??{status:"processing"},txHash:l}))),t=l||void 0}else t=await _i(e);e.ui.setPaymentResult(s=>({status:"success",txHash:s?.txHash||t||""}))}catch(t){const s=p.sanitizeError(t,"Payment failed. Please try again.");e.ui.setError(s),e.ui.setPaymentResult({status:"failed",error:s}),e.onError?.(t instanceof Error?t:new Error(s))}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 t=j.parseUnits(e.currentPaymentAmount,e.destinationToken.decimals),s=e.resolvedTokenIn||e.selectedAsset?.asset?.address||e.destinationToken.address,o=e.needsSwap?e.exactOutputSwap?.amountInMax??0n:t,a={useCustomTransfers:!0,feeExecutionMode:e.feeExecutionMode},r=e.embeddedWalletAddress||e.providerEmbeddedAddress||e.address,i=await e.gasless.estimateRequiredGrossFunding(o,x=>e.gasless.buildPayChainBatches({fundingAmountOverride:x}).then(m=>Ut(m,r)),s,a);let d=i,u=Ut(await e.gasless.buildPayChainBatches({fundingAmountOverride:i}),r);const l=await e.gasless.estimateGasless(u,s,i,a),h=hn(l,{chainId:e.resolvedChainId,tokenAddress:s,symbol:F.getTokenByAddress(s,e.resolvedChainId)?.symbol??e.selectedAsset.asset.symbol,decimals:F.getTokenByAddress(s,e.resolvedChainId)?.decimals??e.selectedAsset.asset.decimals})?.grossAmount??i;h!==i&&(d=h),u=Ut(await e.gasless.buildPayChainBatches({fundingAmountOverride:d}),r,l,{payoutAlreadyGross:!0});const f=u.some(x=>x.tokenTransfers?.length),g=await e.gasless.executeGasless(u,s,f?d:0n,x=>{x.txHash&&(e.ui.setPaymentResult(m=>({...m,txHash:x.txHash})),e.ui.setTxHash(x.txHash))},void 0,a);e.ui.setPaymentResult(x=>({status:"success",txHash:x?.txHash||g}))}catch(t){const s=p.sanitizeError(t,"Payment failed. Please try again.");e.ui.setError(s),e.ui.setPaymentResult({status:"failed",error:s}),e.onError?.(t instanceof Error?t:new Error(s))}finally{e.ui.setIsExecuting(!1)}}const Xo=({variant:e,destinationSymbol:t,destinationLogoURI:s,destinationDecimals:o,primaryColor:a,fontFamily:r,textPrimary:i,textSecondary:d,cardBg:u,cardBorder:l,dk:h,dark:f,isQuoting:g,quoteError:x,estimatedOutput:m,paymentAmount:y,needsSwap:b,exactOutputSwap:S,adjustable:w=!1,maxAmount:C,onAmountChange:v})=>e==="supply"?n.jsxs("div",{style:{backgroundColor:u,border:`1px solid ${l}`,borderRadius:f?"8px":"7px",padding:"14px 16px 12px 16px",marginBottom:"16px",minHeight:"112px",display:"flex",flexDirection:"column",justifyContent:"space-between"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"12px"},children:[n.jsxs("div",{style:{minWidth:0},children:[n.jsx("span",{style:{fontFamily:r,fontSize:"17px",fontWeight:500,color:f?"#a7abb2":"#7D7C7B",lineHeight:"24px"},children:"Used in TX"}),n.jsx("div",{style:{fontSize:"12px",fontWeight:500,color:d,fontFamily:r,marginTop:"10px"},children:"Net amount after swap and fees"})]}),n.jsxs("div",{style:{textAlign:"right",minWidth:0,display:"inline-flex",alignItems:"center",gap:"8px",border:`1px solid ${l}`,borderRadius:"8px",padding:"8px 10px",minHeight:"42px"},children:[n.jsx(Jo,{symbol:t,logoURI:s,primaryColor:a,size:24}),n.jsx("span",{style:{fontSize:"16px",fontWeight:500,color:f?"#f3f4f6":"#3C3E42",lineHeight:"1.3",fontFamily:r,letterSpacing:0},children:t})]})]}),n.jsx("div",{style:{textAlign:"right",minWidth:0},children:g?n.jsx("span",{style:{fontSize:"18px",color:d,fontFamily:r},children:"Quoting..."}):x?n.jsx("span",{style:{fontSize:"13px",color:f?"#f87171":"#dc2626",fontFamily:r},children:"Quote failed"}):m?n.jsx(fn,{value:m,title:m,fontFamily:r,color:i,lineHeight:"0.95",textAlign:"right",maxFontSize:32,minFontSize:18}):n.jsx("span",{style:{fontSize:"20px",color:d,fontFamily:r},children:"\u2014"})})]}):n.jsx(tl,{destinationSymbol:t,destinationLogoURI:s,destinationDecimals:o,primaryColor:a,fontFamily:r,textPrimary:i,textSecondary:d,cardBg:u,cardBorder:l,dk:h,dark:f,paymentAmount:y||"0",needsSwap:b,exactOutputSwap:S,isQuoting:g,adjustable:w,maxAmount:C,onAmountChange:v}),Jo=({symbol:e,logoURI:t,primaryColor:s,size:o})=>t?n.jsx("img",{src:t,alt:e,style:{width:o,height:o,borderRadius:"50%",objectFit:"cover"}}):n.jsx("div",{style:{width:o,height:o,borderRadius:"50%",backgroundColor:`${s}22`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:o<30?"11px":"12px",fontWeight:700,color:s},children:e.slice(0,2)}),tl=({destinationSymbol:e,destinationLogoURI:t,destinationDecimals:s,primaryColor:o,fontFamily:a,textPrimary:r,textSecondary:i,cardBg:d,cardBorder:u,dk:l,dark:h,paymentAmount:f,needsSwap:g,exactOutputSwap:x,isQuoting:m,adjustable:y,maxAmount:b,onAmountChange:S})=>{const w='"IBM Plex Mono", monospace',C=parseFloat(f||"0"),v=b?parseFloat(b):0,[k,A]=c.useState(f||""),E=c.useRef(null),[R,B]=c.useState(null),[I,T]=c.useState(null);c.useEffect(()=>{y||A(f||"")},[f,y]);const D=z=>{let W=z;W.startsWith(".")&&(W="0"+W);const Q=wn(W);let N=Q;b&&parseFloat(Q)>parseFloat(b)&&(N=b),A(N),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>S?.(N),300)},M=z=>{if(!v)return;if(z===100){A(b||v.toString()),E.current&&clearTimeout(E.current),S?.(b||v.toString());return}const W=10**s,Q=Math.floor(v*z/100*W)/W,N=kn(Q,s);A(N),E.current&&clearTimeout(E.current),S?.(N)},U=v>0?parseFloat(k||"0")/v*100:0;return c.useEffect(()=>()=>{E.current&&clearTimeout(E.current)},[]),n.jsxs("div",{style:{backgroundColor:d,border:`1px solid ${u}`,borderRadius:h?"12px":"6px",padding:"16px",marginBottom:"16px"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[n.jsx(Jo,{symbol:e,logoURI:t,primaryColor:o,size:32}),n.jsxs("div",{children:[n.jsx("span",{style:{fontSize:"14px",fontWeight:600,color:r,fontFamily:a},children:"Payment"}),n.jsx("div",{style:{fontSize:"12px",color:i,fontFamily:a,marginTop:"2px"},children:e})]})]}),n.jsxs("div",{style:{textAlign:"right"},children:[y?n.jsx(fn,{element:"input",ariaLabel:`${e} amount`,dataSpiceflowFocus:!0,value:k,onChange:z=>D(z.target.value),placeholder:"0.0",fontFamily:w,color:r,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12,style:{width:"120px"}}):n.jsx(fn,{element:"div",value:C>0?f:"0.00",title:C>0?f:"0.00",fontFamily:w,color:r,lineHeight:1.1,textAlign:"right",maxFontSize:20,minFontSize:12}),n.jsx("div",{style:{fontSize:"12px",color:i,fontFamily:w,marginTop:"2px"},children:e}),y&&v>0&&n.jsx("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:"10px",marginTop:"6px"},children:[0,25,50,75,100].map((z,W)=>{const Q=Math.abs(U-z)<1,N=W===4,L=z/100,q=R===z,K=I===z;return n.jsx("button",{onClick:()=>M(z),onMouseEnter:()=>B(z),onMouseLeave:()=>{B(null),T(null)},onMouseDown:()=>T(z),onMouseUp:()=>T(null),title:`${z}%`,style:{width:"14px",height:"14px",padding:0,border:"none",backgroundColor:"transparent",cursor:"pointer",opacity:Q?1:q?.8:.5,transform:K?"scale(0.85)":q?"scale(1.15)":"scale(1)",transition:Wt.interactive},children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",children:[n.jsx("circle",{cx:"7",cy:"7",r:"6.84375",fill:N?o:"none",stroke:N?o:h?"#4a5568":"#3C3E42",strokeWidth:"0.3125"}),!N&&L>0&&n.jsx("path",{d:`M 7 7 L 7 0.15625 A 6.84375 6.84375 0 ${L>.5?1:0} 1 ${7+6.84375*Math.sin(L*2*Math.PI)} ${7-6.84375*Math.cos(L*2*Math.PI)} Z`,fill:h?l?.textSecondary||"#9ca3af":"#3C3E42"})]})},z)})})]})]}),g&&x&&!m&&n.jsx("div",{style:{marginTop:"12px",paddingTop:"12px",borderTop:h?`1px solid ${l?.cardBorder||u}`:"1px solid #e5e7eb",display:"flex",justifyContent:"flex-end"},children:n.jsxs("span",{style:{fontSize:"11px",color:i,fontFamily:a,opacity:.7},children:["via ",x.venue]})})]})};function $o(e,t,s){const o=p.addressesEqual(e.address,t),a=e.chainId===s,r=e._source==="wallet";return r&&o&&a?0:r&&a?1:!r&&o?2:!r&&a?3:4}function nl(e,t){return!t||t.length===0||t.some(s=>p.addressesEqual(s,e.address))?!0:Object.keys(e.chainTokens??{}).some(s=>{const o=An(s);return o?t.some(a=>p.addressesEqual(a,o.address)):!1})}function sl(e){const{destinationToken:t,supportedSourceAssets:s,sourceChains:o,enabled:a}=e,r=(c.useContext(p.SpiceFlowProviderContext)?.mode||"7702")!=="7702",i=p.useEmbeddedWalletAddress(),{externalAddress:d,embeddedAddress:u}=p.useProviderWallets(),l=i||u,{assets:h,refetch:f}=Wn({address:l,supportedChains:o,enabled:a&&!r&&!!l,refetchInterval:3e4}),g=c.useMemo(()=>r?[]:h.filter(A=>nl(A,s)),[h,s,r]),x=r?d:i,m=c.useMemo(()=>{const A=new Set,E=[],R=B=>{if(!B)return;const I=B.toLowerCase();A.has(I)||(A.add(I),E.push(j.getAddress(B)))};if(R(t.address),r&&s)for(const B of s)R(B);return E},[r,t.address,s]),y=c.useMemo(()=>m.map(A=>A.toLowerCase()).sort().join(","),[m]),b=c.useMemo(()=>JSON.stringify([...o||[]].sort()),[o]),[S,w]=c.useState([]),C=c.useRef(0),v=c.useCallback(async()=>{if(!a||!x||m.length===0){C.current++,w([]);return}const A=++C.current,E=j.getAddress(x),R=r?o&&o.length>0?o:[t.chainId]:[t.chainId],B=[];for(const M of m){const U=M.toLowerCase();if(U===F.ZERO_ADDRESS)continue;if(U===t.address.toLowerCase()){const W=p.getChainConfig(t.chainId)?.supportedTokens?.find(Q=>p.addressesEqual(Q.address,U));B.push({address:M,chainId:t.chainId,configToken:W?{decimals:W.decimals,symbol:W.symbol,name:W.name,logo:W.logo}:void 0});continue}let z=!1;for(const W of R){const Q=p.getChainConfig(W)?.supportedTokens?.find(N=>p.addressesEqual(N.address,U));if(Q){B.push({address:M,chainId:W,configToken:{decimals:Q.decimals,symbol:Q.symbol,name:Q.name,logo:Q.logo}}),z=!0;break}}z||B.push({address:M,chainId:t.chainId})}const I=new Map;for(const M of B){const U=I.get(M.chainId)||[];U.push(M),I.set(M.chainId,U)}const T=async(M,U)=>{try{const z=await Tt.readContract(M,{address:U.address,abi:j.erc20Abi,functionName:"balanceOf",args:[E]});let W,Q,N,L;if(U.configToken)W=U.configToken.decimals,Q=U.configToken.symbol,N=U.configToken.name,L=U.configToken.logo;else{const[O,G,ce]=await Promise.all([Tt.readContract(M,{address:U.address,abi:j.erc20Abi,functionName:"decimals"}).catch(()=>18),Tt.readContract(M,{address:U.address,abi:j.erc20Abi,functionName:"symbol"}).catch(()=>"TOKEN"),Tt.readContract(M,{address:U.address,abi:j.erc20Abi,functionName:"name"}).catch(()=>"TOKEN")]);W=Number(O),Q=G,N=ce}const q=p.addressesEqual(U.address,t.address)&&U.chainId===t.chainId;q&&t.logoURI&&(L=t.logoURI),q&&!U.configToken&&Q==="TOKEN"&&(Q=t.symbol,N=t.symbol);const K=parseFloat((Number(z)/Math.pow(10,W)).toFixed(6));return{address:U.address,name:N,symbol:Q,decimals:W,balance:z,balanceFormatted:K,balanceUsd:0,logoURI:L,isNative:!1,chainId:U.chainId}}catch{return null}},D=await Promise.all(Array.from(I.entries()).map(async([M,U])=>{let z;try{z=p.getClientForChain(M)}catch{return[]}const W=[],Q=[];for(const L of U){const q=W.length;W.push({address:L.address,abi:j.erc20Abi,functionName:"balanceOf",args:[E]}),L.configToken||W.push({address:L.address,abi:j.erc20Abi,functionName:"decimals"},{address:L.address,abi:j.erc20Abi,functionName:"symbol"},{address:L.address,abi:j.erc20Abi,functionName:"name"}),Q.push({start:q,item:L})}let N=null;try{N=await z.multicall({contracts:W})}catch{N=null}return N?Q.map(({start:L,item:q})=>{const K=N[L],O=K?.status==="success"?K.result:0n;let G,ce,P,ne;if(q.configToken)G=q.configToken.decimals,ce=q.configToken.symbol,P=q.configToken.name,ne=q.configToken.logo;else{const pe=N[L+1],ge=N[L+2],fe=N[L+3];G=pe?.status==="success"?Number(pe.result):18,ce=ge?.status==="success"?ge.result:"TOKEN",P=fe?.status==="success"?fe.result:ce}const me=p.addressesEqual(q.address,t.address)&&q.chainId===t.chainId;me&&t.logoURI&&(ne=t.logoURI),me&&!q.configToken&&ce==="TOKEN"&&(ce=t.symbol,P=t.symbol);const ke=parseFloat((Number(O)/Math.pow(10,G)).toFixed(6));return{address:q.address,name:P,symbol:ce,decimals:G,balance:O,balanceFormatted:ke,balanceUsd:0,logoURI:ne,isNative:!1,chainId:q.chainId}}):(await Promise.all(U.map(L=>T(z,L)))).filter(L=>L!==null)}));A===C.current&&w(D.flat())},[a,r,x,y,b,t.address,t.chainId,t.symbol,t.logoURI]);c.useEffect(()=>{if(!a){w([]);return}v();const A=setInterval(()=>{v()},15e3);return()=>clearInterval(A)},[v,a]);const k=c.useCallback(()=>{v()},[v]);return{displayAssets:c.useMemo(()=>{const A=[],E=S.filter(B=>B.balance>0n);for(const B of E)A.push({...B,_source:"wallet"});for(const B of g)A.push({...B,_source:"spice"});const R=t.address.toLowerCase();return A.sort((B,I)=>$o(B,R,t.chainId)-$o(I,R,t.chainId)),A},[S,g,t.address,t.chainId]),filteredSpiceAssets:g,walletAssets:S,embeddedWalletAddress:l,externalAddress:d,isNon7702:r,refreshSpiceAssets:f,refreshWalletAssets:k}}async function _o(e){const{tokenIn:t,tokenOut:s,amountIn:o,fee:a,chainId:r,config:i}=e;if(o<=0n)throw new Error("amountIn must be greater than 0");const d=(await p.getClientForChain(r).simulateContract({address:i.quoterV2,abi:F.uniV3QuoterV2Abi,functionName:"quoteExactInputSingle",args:[{tokenIn:t,tokenOut:s,amountIn:o,fee:a,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 er(e){const t=e.feeTiers??[100,500,3e3,1e4],s=await Promise.allSettled(t.map(a=>_o({...e,fee:a})));let o=null;for(let a=0;a<s.length;a++){const r=s[a];r.status==="fulfilled"&&(!o||r.value.amountOut>o.amountOut)&&(o={...r.value,fee:t[a]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}const ol=[{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 rl(e){const{tokenIn:t,tokenOut:s,amountOut:o,fee:a,chainId:r,config:i}=e;if(o<=0n)throw new Error("amountOut must be greater than 0");const d=(await p.getClientForChain(r).simulateContract({address:i.quoterV2,abi:ol,functionName:"quoteExactOutputSingle",args:[{tokenIn:t,tokenOut:s,amount:o,fee:a,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 al(e){const t=e.feeTiers??[100,500,3e3,1e4],s=await Promise.allSettled(t.map(a=>rl({...e,fee:a})));let o=null;for(let a=0;a<s.length;a++){const r=s[a];r.status==="fulfilled"&&(!o||r.value.amountIn<o.amountIn)&&(o={...r.value,fee:t[a]})}if(!o)throw new Error("No liquidity found for this pair on any fee tier.");return o}function tr(e){return e.type==="swap"}const Os=.02,il=[1,8453,42161,10,137,43114,56],ll="https://api.1inch.dev/swap/v6.0";function nr(e,t){return F.applySlippage(e,t)}function sr(e){const t=e?.baseUrl??ll;return{name:"1inch",chainIds:e?.chainIds??il,resolve:async(s,o,a)=>{const r=s.maxSlippage??Os,i=r*100,d=F.isNativeToken(s.tokenIn)?F.NATIVE_TOKEN_ADDRESS:s.tokenIn,u=F.isNativeToken(s.tokenOut)?F.NATIVE_TOKEN_ADDRESS:s.tokenOut,l=F.isNativeToken(s.tokenIn);try{const h=new URL(`${t}/${o}/swap`);h.searchParams.set("src",d),h.searchParams.set("dst",u),h.searchParams.set("amount",s.amountIn.toString()),h.searchParams.set("from",a),h.searchParams.set("slippage",i.toString()),h.searchParams.set("disableEstimate","true"),h.searchParams.set("allowPartialFill","false");const f={Accept:"application/json"};e?.apiKey&&(f.Authorization=`Bearer ${e.apiKey}`);const g=await fetch(h.toString(),{headers:f});if(!g.ok)throw new p.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] API returned ${g.status} for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}`,{venue:"1inch",chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn.toString(),cause:`HTTP ${g.status}`});const x=await g.json();if(!x.dstAmount||!x.tx)return console.warn(`[1inchVenue] No route data for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}`),null;const m=BigInt(x.dstAmount);if(m<=0n)return console.warn(`[1inchVenue] Zero output for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}`),null;const y=nr(m,r),b=[];return x.tx.to&&!l&&b.push({to:s.tokenIn,value:0n,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"approve",args:[x.tx.to,s.amountIn]})}),b.push({to:x.tx.to,value:BigInt(x.tx.value||"0"),data:x.tx.data}),{venue:"1inch",amountOut:m,amountOutMinimum:y,calls:b}}catch(h){if(h instanceof p.SpiceflowError)throw h;const f=h instanceof Error?h.message:String(h);throw new p.SpiceflowError("VENUE_API_ERROR",`[1inchVenue] Exception for ${s.tokenIn} \u2192 ${s.tokenOut} on chain ${o}: ${f}`,{venue:"1inch",chainId:o,tokenIn:s.tokenIn,tokenOut:s.tokenOut,amountIn:s.amountIn.toString(),cause:f})}}}}const or=[4114,5115],Hs={swapRouter:"0x565eD3D57fe40f78A46f348C220121AE093c3cF8",quoterV2:"0x428f20dd8926Eabe19653815Ed0BE7D6c36f8425"},rr={swapRouter:"0x2626664c2603336E57B271c5C0b26F421741e481",quoterV2:"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",chainIds:[8453]};function ar(e){return{name:"satsuma",chainIds:e.chainIds??or,resolve:async(t,s,o)=>{const a=t.maxSlippage??Os,r=F.isNativeToken(t.tokenIn);let i;try{i=await er({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountIn:t.amountIn,chainId:s,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 ${s}.`),null}const d=nr(i.amountOut,a),u=[];return r||u.push({to:t.tokenIn,value:0n,data:j.encodeFunctionData({abi:j.erc20Abi,functionName:"approve",args:[e.swapRouter,t.amountIn]})}),u.push({to:e.swapRouter,value:r?t.amountIn:0n,data:j.encodeFunctionData({abi:F.uniV3SwapRouterAbi,functionName:"exactInputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:i.fee,recipient:o,amountIn:t.amountIn,amountOutMinimum:d,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountOut:i.amountOut,amountOutMinimum:d,calls:u}}}}function ir(e){return{name:"satsuma",chainIds:e.chainIds??or,resolve:async(t,s,o)=>{const a=t.maxSlippage??Os,r=F.isNativeToken(t.tokenIn);let i;try{i=await al({tokenIn:t.tokenIn,tokenOut:t.tokenOut,amountOut:t.amountOut,chainId:s,config:{swapRouter:e.swapRouter,quoterV2:e.quoterV2},feeTiers:e.feeTiers})}catch{return null}const d=BigInt(Math.round(a*1e4)),u=i.amountIn+i.amountIn*d/10000n,l=[];return l.push({to:e.swapRouter,value:r?u:0n,data:j.encodeFunctionData({abi:cl,functionName:"exactOutputSingle",args:[{tokenIn:t.tokenIn,tokenOut:t.tokenOut,fee:i.fee,recipient:o,amountOut:t.amountOut,amountInMaximum:u,sqrtPriceLimitX96:0n}]})}),{venue:"satsuma",amountIn:i.amountIn,amountInMax:u,amountOut:t.amountOut,calls:l}}}}const cl=[{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 lr(e){const t=[];e?.customVenues&&t.push(...e.customVenues),e?.satsuma&&t.push(ar(e.satsuma)),t.push(sr(e?.oneInch));function s(a){return t.find(r=>r.chainIds.includes(a))}async function o(a,r,i){const d=[],u=[];for(const l of a){if(!tr(l)){d.push(l);continue}const h=s(r);if(!h)throw new p.SpiceflowError("NO_VENUE_FOR_CHAIN",`No liquidity venue configured for chain ${r}. Cannot resolve swap ${l.tokenIn} \u2192 ${l.tokenOut}.`,{chainId:r,tokenIn:l.tokenIn,tokenOut:l.tokenOut,amountIn:l.amountIn.toString()});const f=await h.resolve(l,r,i);if(!f)throw new p.SpiceflowError("NO_LIQUIDITY",`${h.name} returned no quote for ${l.tokenIn} \u2192 ${l.tokenOut} on chain ${r}.`,{venue:h.name,chainId:r,tokenIn:l.tokenIn,tokenOut:l.tokenOut,amountIn:l.amountIn.toString()});d.push(...f.calls),u.push(f)}return{calls:d,resolvedSwaps:u}}return{resolveSwapIntents:o,getVenueForChain:s,venues:t}}function dl(e){const t=e?.customVenues??[];async function s(o,a,r){const i=t.filter(u=>u.chainIds.includes(a));if(i.length===0)throw new p.SpiceflowError("NO_SWAP_ROUTE",`No exact-output venue supports chain ${a}`,{chainId:a,tokenIn:o.tokenIn,tokenOut:o.tokenOut});const d=(await Promise.allSettled(i.map(u=>u.resolve(o,a,r)))).filter(u=>u.status==="fulfilled").map(u=>u.value).filter(u=>u!==null);if(d.length===0)throw new p.SpiceflowError("NO_SWAP_ROUTE",`All aggregators failed for ${o.tokenIn} \u2192 ${o.tokenOut} on chain ${a}`,{chainId:a,tokenIn:o.tokenIn,tokenOut:o.tokenOut,amountOut:o.amountOut.toString()});return d.sort((u,l)=>u.amountIn<l.amountIn?-1:u.amountIn>l.amountIn?1:0),d[0]}return{getQuote:s,venues:t}}const ul=lr({satsuma:Hs});function pl(e){const{direction:t,selectedAsset:s,destinationToken:o,chainId:a,recipient:r,paymentAmount:i}=e,[d,u]=c.useState(!1),[l,h]=c.useState(null),[f,g]=c.useState(null),[x,m]=c.useState(null),[y,b]=c.useState(null),[S,w]=c.useState(null),[C,v]=c.useState(null),[k,A]=c.useState(null),[E,R]=c.useState(null),B=c.useRef(null),I=c.useRef(0),T=c.useRef(new Map),D=c.useMemo(()=>ul,[]),M=c.useMemo(()=>dl({customVenues:[ir(Hs),ir(rr)]}),[]),U=c.useMemo(()=>{if(!s?.asset)return null;const G=$t(s.asset,a);if(G)return G;const ce=rn(s.asset.address,a,s.asset.chainId);return ce?ce.address:null},[s?.asset,a]),z=c.useMemo(()=>s?.asset?Yn(s.asset,a):[],[s?.asset,a]);c.useEffect(()=>{let G=!1;if(!s?.asset||z.length<=1){R(null);return}return(async()=>{const ce=t==="input"?s.amount:i||"0";let P=0n;try{P=t==="input"?j.parseUnits(ce,s.asset.decimals):0n}catch{P=0n}try{const ne=await So(s.asset,a,{requiredAmount:P});G||R(ne)}catch{G||R(null)}})(),()=>{G=!0}},[s?.asset,s?.amount,a,z,t,i]);const W=c.useMemo(()=>E??U,[E,U]),Q=c.useMemo(()=>!s?.asset||!W?[]:[W,...z.filter(G=>G.toLowerCase()!==W.toLowerCase())],[s?.asset,W,z]),N=c.useMemo(()=>!s?.asset||!Nn(s.asset.address,s.asset.chainId,o.address,o.chainId)||!W?!1:p.addressesEqual(W,o.address),[s,o.address,o.chainId,W]),L=W?p.addressesEqual(W,o.address):!1,q=t==="output"&&parseFloat(i||"0")===0,K=!!s?.asset&&!N&&!L&&!q,O=K?k??W:W;return c.useEffect(()=>{B.current&&clearTimeout(B.current);const G=t==="input"?s?.amount:i,ce=parseFloat(G||"0");if(!K||!Number.isFinite(ce)||ce<=0||!s?.asset||!r||Q.length===0){I.current++,g(null),m(null),b(null),w(null),v(null),A(null),h(null),u(!1);return}const P=s.asset.decimals;let ne;try{ne=t==="input"?j.parseUnits(s.amount,P):j.parseUnits(i||"0",o.decimals)}catch{I.current++,h("Invalid amount"),u(!1);return}const me=++I.current,ke=()=>me!==I.current;u(!0);const pe=t==="output"?150:400;return B.current=setTimeout(async()=>{try{if(t==="input"){const ge=D.getVenueForChain(a);if(!ge)throw new Error("No swap venue for this chain");let fe=null,V=null;for(const X of Q){const le=`${t}:${a}:${X.toLowerCase()}:${o.address.toLowerCase()}:${ne.toString()}`,xe=T.current.get(le);if(xe&&xe.expiresAt>Date.now()&&xe.resolvedSwap){fe=xe.resolvedSwap,V=X;break}const Se=await ge.resolve({type:"swap",tokenIn:X,tokenOut:o.address,amountIn:ne},a,r);if(ke())return;if(Se){T.current.set(le,{expiresAt:Date.now()+3e4,direction:t,resolvedSwap:Se}),fe=Se,V=X;break}}if(!fe||!V)throw new Error("No liquidity for this pair");A(V),v(fe.amountOut),b(fe),w(null);const re=parseFloat(j.formatUnits(fe.amountOut,o.decimals));g(re<.01?re.toPrecision(4):re.toLocaleString(void 0,{maximumFractionDigits:6})),m(null),h(null)}else{let ge=null,fe=null;for(const V of Q){const re=`${t}:${a}:${V.toLowerCase()}:${o.address.toLowerCase()}:${ne.toString()}`,X=T.current.get(re);if(X&&X.expiresAt>Date.now()&&X.exactOutputSwap){ge=X.exactOutputSwap,fe=V;break}try{const le=await M.getQuote({tokenIn:V,tokenOut:o.address,amountOut:ne},a,r);if(ke())return;T.current.set(re,{expiresAt:Date.now()+3e4,direction:t,exactOutputSwap:le}),ge=le,fe=V;break}catch{if(ke())return}}if(!ge||!fe)throw new Error("No liquidity for this pair");A(fe),w(ge),b(null),v(null),m(parseFloat(j.formatUnits(ge.amountIn,P)).toFixed(6)),g(null),h(null)}}catch(ge){if(ke())return;const fe=ge instanceof Error?ge.message:"Failed to get quote";h(fe),g(null),m(null),b(null),w(null),v(null),A(null)}finally{ke()||u(!1)}},pe),()=>{B.current&&clearTimeout(B.current)}},[t,K,s?.amount,s?.asset?.address,s?.asset?.decimals,i,Q,a,o.address,o.decimals,r,D,M]),{isQuoting:d,quoteError:l,estimatedOutput:f,estimatedInput:x,resolvedSwap:y,exactOutputSwap:S,quoteAmountOut:C,resolvedTokenIn:O,isDirect:L,needsSwap:K,selectedIsEquivalent:N}}const cr={idle:"","signing-delegation":"Signing delegation...","signing-intent":"Signing intent...",submitting:"Submitting transaction...",executing:"Executing on-chain...",success:"Deposit confirmed",error:"Transaction failed"},dr=["signing-delegation","signing-intent","submitting","executing"],ur=({isOpen:e,onClose:t,closeOnBackdropClick:s=!1,destinationToken:o,sourceChains:a,supportedSourceAssets:r,buildActionCalls:i,feeExecutionMode:d="user-transfer",buildSpicenetBatch:u,onPayExecute:l,actionLabel:h,amountDirection:f="input",swapDescription:g,directDescription:x,paymentAmount:m,amountInputMode:y="fixed",minPaymentAmount:b,maxPaymentAmount:S,onAmountChange:w,styles:C,dark:v,title:k,subtitle:A,onAddFunds:E,onSuccess:R,onError:B})=>{const I=f==="output",{theme:T,dark:D,primaryColor:M,dk:U,palette:z,fontFamily:W,monoFont:Q,inputDark:N,cardBg:L,cardBorder:q,textPrimary:K,textSecondary:O,subtitleText:G}=p.useSpiceBrand(C,v),ce=N?{...T,colors:{...T.colors,secondary:U.cardBg,surfaceHover:U.hoverBg,border:"#2d2d2d",borderHover:"#3a3a3a"}}:T,P=o.chainId,ne=c.useContext(p.SpiceFlowProviderContext),me=(ne?.mode||"7702")!=="7702",ke=!!ne?.isWhitelistGateActive,pe=c.useMemo(()=>a??ne?.supportedChainIds??[],[a,ne?.supportedChainIds]),ge=c.useMemo(()=>{if(ke)return[];if(r)return r;const de=ne?.allowedTokens;if(!de||de.length===0)return;const Be=new Set(de.map(Kt=>Kt.toLowerCase())),Bt=[],Jt=new Set;for(const Kt of pe){const jn=p.getChainConfig(Kt);for(const un of jn?.supportedTokens??[]){if(!Be.has(un.symbol.toLowerCase()))continue;const Fn=un.address.toLowerCase();Jt.has(Fn)||(Jt.add(Fn),Bt.push(un.address))}}return Bt},[r,ne?.allowedTokens,pe,ke]),fe=p.useWallet(),{address:V,isConnected:re,isReady:X,isAuthenticated:le,provider:xe}=fe,{executeGasless:Se,estimateGasless:J}=es(),{externalWallet:Y,externalAddress:ae,embeddedAddress:Ce}=p.useProviderWallets(),We=p.useEmbeddedWalletAddress()||Ce,{displayAssets:rt,filteredSpiceAssets:Ke,embeddedWalletAddress:Ze,refreshSpiceAssets:oe,refreshWalletAssets:ie}=sl({destinationToken:o,supportedSourceAssets:ge,sourceChains:pe,enabled:e&&(me?!!ae:!!We)}),Ye=ke||I||me?rt:Ke,[_,Me]=c.useState(null),[ct,kt]=c.useState(m||""),[st,Pt]=c.useState(!1),[Rt,mt]=c.useState(null),[Ie,Mt]=c.useState("idle"),[Zt,Yt]=c.useState(""),[gt,zt]=c.useState(null),[Ge,vt]=c.useState(!1),[Qe,$e]=c.useState(null),[_e,dt]=c.useState(null),[Et,he]=c.useState(!1),[at,it]=c.useState(!1),[jt,be]=c.useState(null),Dt=c.useRef(_),et=c.useRef(!1),ut=c.useRef(null),xt=c.useRef(0),Gt=c.useRef(null),Lt=c.useRef(null);c.useEffect(()=>{Dt.current=_},[_]);const Xe=y==="adjustable"?ct:m||"0",_t=Ze||Ce||V,{isQuoting:Te,quoteError:ft,estimatedOutput:Oe,resolvedSwap:yt,exactOutputSwap:qe,quoteAmountOut:Ct,resolvedTokenIn:Ue,isDirect:Je,needsSwap:He,selectedIsEquivalent:bt}=pl({direction:f,selectedAsset:_,destinationToken:o,chainId:P,recipient:_t,paymentAmount:Xe}),tt=I?parseFloat(Xe||"0"):parseFloat(_?.amount||"")||0,Ot=_?.asset?._source==="wallet",De=!!_?.asset&&Ot&&_.asset.chainId!==P,Vt=c.useMemo(()=>_?.asset?Ke.find(de=>p.addressesEqual(de.address,_.asset.address))?.balanceFormatted??0:0,[_,Ke]),Ht=Ot?_?.asset.balanceFormatted??0:Vt,St=c.useMemo(()=>{if(!_?.asset)return!1;if(I)return _e?En(_e.grossAmount,_e.decimals,_.asset.decimals)>_.asset.balance:bt||Je?tt>_.asset.balanceFormatted:qe?parseFloat(j.formatUnits(qe.amountInMax,_.asset.decimals))>_.asset.balanceFormatted:!1;if(_e){const de=En(_e.grossAmount,_e.decimals,_.asset.decimals);return Ot?de>_.asset.balance:parseFloat(j.formatUnits(de,_.asset.decimals))>Ht}return tt>Ht},[_,I,_e,bt,tt,qe,Ht,Ot,Je]);c.useEffect(()=>{e||(Me(null),mt(null),Pt(!1),Mt("idle"),Yt(""),zt(null),vt(!1),$e(null),dt(null),he(!1),it(!1),be(null),et.current=!1,y==="adjustable"&&kt(m||""),ut.current&&(ut.current.abort(),ut.current=null))},[e]);const te=c.useCallback(de=>{Me(Be=>({asset:de,amount:Be?.asset?.address===de.address&&Be?.asset?.chainId===de.chainId&&Be.amount||""})),mt(null),be(null),it(!1)},[]),se=c.useCallback(de=>{Me(Be=>Be&&{...Be,amount:de}),mt(null),be(null),it(!1)},[]),ve=c.useCallback(de=>{let Be=de;S&&parseFloat(Be)>parseFloat(S)&&(Be=S),kt(Be),w?.(Be),mt(null),be(null),it(!1)},[S,w]);c.useCallback(de=>{if(et.current||!V)return;const Be=Dt.current;!Be?.asset||!Be.amount||Be.asset?._source==="wallet"||j.parseUnits(I?Xe:Be.amount,Be.asset.decimals)===0n||(et.current=!0,oe())},[V,P,oe,I,Xe]);const ze=c.useCallback(de=>{Mt({building:"signing-delegation","signing-delegation":"signing-delegation","signing-intent":"signing-intent",submitting:"submitting",executing:"executing",success:"success",error:"error"}[de.step]||"executing"),Yt(de.message),de.txHash&&zt(de.txHash)},[]),nt=c.useMemo(()=>({currentPaymentAmount:Xe,destinationToken:o,embeddedWalletAddress:Ze,providerEmbeddedAddress:Ce,externalWalletAddress:ae,address:V,isNon7702:me,isPayMode:I,resolvedChainId:P,buildActionCalls:i,feeExecutionMode:d,buildSpicenetBatch:u,selectedAsset:_,needsSwap:He,resolvedSwap:yt,exactOutputSwap:qe,quoteAmountOut:Ct,resolvedTokenIn:Ue}),[Xe,o,Ze,Ce,ae,V,me,I,P,i,d,u,_,He,yt,qe,Ct,Ue]),Le=c.useCallback(de=>Vi(nt,de),[nt]),Ve=c.useCallback(de=>qi(nt,de),[nt]),Ne=c.useCallback((de,Be,Bt,Jt)=>Ki(de,Be,Bt,J,Jt),[J]),Z=c.useMemo(()=>_?.asset?He&&Ue?Ue:_.asset.chainId===P?_.asset.address:Ue??$t(_.asset,P)??o.address:o.address,[_,o.address,He,P,Ue]),ye=c.useCallback(()=>Ji(Lt.current),[]),Ae=c.useMemo(()=>_?.asset?p.addressesEqual(_.asset.address,o.address)&&_.asset.chainId===o.chainId:!1,[_,o.address,o.chainId]),je=me&&Ae,Ee=je&&tt>0&&!!_?.asset,lt=Rt,ht=c.useMemo(()=>!(!_?.asset||tt<=0),[_,tt,Ee]),qt=c.useMemo(()=>!e||st||Ie!=="idle"||!ht||Ee||!_?.asset?null:[I?"pay":"supply",f,_.asset.address.toLowerCase(),_.asset.chainId,_.amount,Xe,o.address.toLowerCase(),o.chainId,P,Ue?.toLowerCase()??"",He?"swap":"direct",Je?"direct-token":"routed-token",me?"non7702":"7702",Ae?"source-dest":"cross-chain",Te?"quoting":"quoted",qe?.amountIn?.toString()??"",qe?.amountInMax?.toString()??"",qe?.venue??"",yt?.amountOut?.toString()??"",Ct?.toString()??"",Ze??"",Ce??"",V??""].join("|"),[e,st,Ie,ht,Ee,_,I,f,Xe,o,P,Ue,He,Je,me,Ae,Te,qe,yt,Ct,Ze,Ce,V]),H=c.useCallback(()=>Xi({selectedAsset:_,isPayMode:I,parsedAmount:tt,needsSwap:He,exactOutputSwap:qe,isNon7702:me,isSourceDestToken:Ae,currentPaymentAmount:Xe,destinationToken:o,feeExecutionMode:d,resolvedTokenIn:Ue,embeddedWalletAddress:Ze,providerEmbeddedAddress:Ce,resolvedChainId:P,isConnected:re,address:V,ready:X,authenticated:le,isDirect:Je,resolvedSwap:yt,isQuoting:Te,executionTokenAddress:Z,buildPayChainBatches:Le,buildSupplyChainBatches:Ve,estimateGasless:J,estimateRequiredGrossFunding:Ne}),[_,I,tt,He,qe,me,Ae,Xe,o,d,Ue,Ze,Ce,Ne,Le,J,P,re,V,X,le,Je,yt,Te,Ve,Z]);c.useEffect(()=>{Gt.current=H},[H]);const $=c.useCallback(de=>Gi({asset:de,isPayMode:I,isNon7702:me,needsSwap:He,isQuoting:Te,embeddedWalletAddress:Ze,buildSupplyChainBatches:Ve,estimateGasless:J,executionTokenAddress:Z,feeExecutionMode:d}),[I,me,He,Te,Ze,Ve,J,Z,d]);c.useEffect(()=>{if(!e){he(!1),it(!1),be(null),dt(null);return}if(st||Ie!=="idle"){xt.current+=1,he(!1);return}if(!ht){dt(null),he(!1),it(!1),be(null);return}if(Ee){dt(null),he(!1),it(!0),be(null);return}if(!qt)return;let de=!1;const Be=async()=>{const Jt=++xt.current;be(null),he(!0);try{const Kt=await Gt.current?.();if(de||xt.current!==Jt)return;Kt?(dt(Kt),it(!0)):(dt(null),it(!1)),be(null)}catch(Kt){if(de||xt.current!==Jt)return;const jn=p.sanitizeError(Kt,"Unable to calculate fees for this action.");dt(null),it(!1),be(jn)}finally{!de&&xt.current===Jt&&he(!1)}},Bt=window.setTimeout(()=>{Be()},250);return()=>{de=!0,clearTimeout(Bt),he(!1)}},[e,st,Ie,ht,Ee,qt]);const ue=c.useCallback(()=>el(Lt.current),[]);c.useEffect(()=>{!I&&Ie==="success"&&gt&&(oe(),R?.(gt))},[I,Ie,gt,oe,R]),c.useEffect(()=>{if(!I||Qe?.status!=="success"||et.current||!V)return;et.current=!0;const de=Dt.current;!de?.asset||de.asset?._source==="wallet"||oe()},[I,Qe?.status,V,oe]);const ee=c.useRef(R),Re=c.useRef(B);c.useEffect(()=>{ee.current=R},[R]),c.useEffect(()=>{Re.current=B},[B]),c.useEffect(()=>{e&&(oe(),ie())},[e,oe,ie]),c.useEffect(()=>{I&&(Qe?.status==="success"&&ee.current?.(Qe.txHash||""),Qe?.status==="failed"&&Re.current?.(new Error("Payment execution failed")))},[I,Qe?.status]);const Fe=c.useCallback(()=>{vt(!1),$e(null),Me(null),et.current=!1,oe(),ie()},[oe,ie]);Lt.current={selectedAsset:_,parsedAmount:tt,currentPaymentAmount:Xe,isInsufficientBalance:St,isPayMode:I,isNon7702:me,isSourceDestToken:Ae,needsSwap:He,exactOutputSwap:qe,selectedIsEquivalent:bt,resolvedTokenIn:Ue,embeddedWalletAddress:Ze,providerEmbeddedAddress:Ce,externalWallet:Y,externalWalletAddress:ae,address:V,isConnected:re,ready:X,authenticated:le,provider:xe,resolvedChainId:P,executionTokenAddress:Z,destinationToken:o,buildActionCalls:i,feeExecutionMode:d,buildSpicenetBatch:u,onPayExecute:l,onError:B,gasless:{estimateGasless:J,executeGasless:Se,buildPayChainBatches:Le,buildSupplyChainBatches:Ve,estimateRequiredGrossFunding:Ne,onProgress:ze},ui:{setError:mt,setStep:Mt,setStatusMsg:Yt,setTxHash:zt,setIsExecuting:Pt,setShowStatusPanel:vt,setPaymentResult:$e},refs:{spiceDepositSubmittedRef:et,abortControllerRef:ut}};const Pe=I&&tt===0,ot=I?!!_?.asset&&tt>=0&&!St&&!st&&(Pe||Ee||at)&&!jt&&(Pe||!He||!!qe):!!_?.asset&&tt>0&&!St&&!st&&(je||at)&&!jt&&(De||Je||!!yt&&!Te),Qt=Je?x||`Your ${o.symbol} will be used directly.`:g||"Your assets will be swapped and used in a single atomic transaction.",Ft=(P?p.getChainConfig(P):void 0)?.viemChain?.blockExplorers?.default?.url??"",pt=dr.indexOf(Ie),It=st?(cr[Ie]||"EXECUTING...").toUpperCase():Ie==="success"?"DONE":St?"INSUFFICIENT BALANCE":h.toUpperCase(),Xt=c.useMemo(()=>{if(st)return"PAYING...";if(St&&_?.asset)return`INSUFFICIENT ${_.asset.symbol}`;if(h)return h.toUpperCase();const de=tt>0?` ${Xe} ${o.symbol}`:"";return He?`SWAP & PAY${de}`:`PAY${de}`},[st,St,_,h,tt,Xe,o.symbol,He]),an=Ie==="success"?()=>{Mt("idle"),Me(null),zt(null),oe()}:ye,xn=Ie==="success"?!1:!ot;if(!e)return null;const yn=I?k||`Pay ${o.symbol}`:h,we=I?A:n.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"3px"},children:[n.jsx("span",{style:{marginTop:"3px",flexShrink:0},children:n.jsx(bs,{color:G})}),n.jsx("p",{style:{fontSize:"12px",color:G,margin:0,lineHeight:"1.4",fontFamily:W},children:Qt})]});if(I){const de=Qe&&(Qe.status==="success"||Qe.status==="failed")?[{asset:{symbol:_?.asset?.symbol||o.symbol,address:_?.asset?.address||""},amount:Xe,txHash:Qe.txHash||"",success:Qe.status==="success",error:Qe.status==="failed"?Qe.error:void 0}]:void 0;return n.jsx(tn,{isOpen:e,onClose:t,title:yn,subtitle:we,styles:C,dark:D,footerLinkText:"Spicenet accounts \u2192",closeOnBackdropClick:s,children:n.jsxs("div",{style:{padding:"16px 24px 8px 24px",position:"relative"},children:[E&&n.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:"6px"},children:n.jsx(ws,{onClick:E,color:M,fontFamily:W})}),n.jsx("div",{style:{marginBottom:"12px"},children:n.jsx(Dn,{assets:Ye,selectedAsset:_??void 0,onAssetSelect:te,onAmountChange:()=>{},label:"Pay with",showBalance:!0,showMaxButton:!1,hideAmountInput:!0,displayAmount:_?.asset?He?Te?"...":qe?`~${parseFloat(j.formatUnits(qe.amountIn,_.asset.decimals)).toFixed(6)}`:void 0:Xe??void 0:void 0,dark:D,theme:ce,styles:C})}),n.jsx(Xo,{variant:"pay",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:M,fontFamily:W,textPrimary:K,textSecondary:O,cardBg:L,cardBorder:q,dk:U,dark:D,isQuoting:Te,quoteError:ft,estimatedOutput:Oe,paymentAmount:Xe,needsSwap:He,exactOutputSwap:qe,adjustable:y==="adjustable",maxAmount:S,onAmountChange:ve}),ht&&n.jsx(Vn,{fontFamily:W,textPrimary:K,textSecondary:O,cardBg:L,cardBorder:q,resolvedDark:D,darkCardBorder:U.cardBorder,primaryColor:M,feePreview:_e,isLoading:Et,errorText:jt,directExecutionFeeNote:Ee}),lt&&n.jsx(Sn,{variant:"error",palette:z,fontFamily:W,style:{marginBottom:"12px"},children:lt}),n.jsx(p.Button,{variant:"outline",fullWidth:!0,onClick:ue,disabled:!ot,loading:st,dark:D,styles:{...C,button:{...C?.button,backgroundColor:M}},children:Xt}),Qe&&Ge&&n.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:10,backgroundColor:D?U.shell:"white",borderRadius:D?"12px":"6px",padding:"16px 0"},children:n.jsx(As,{type:"payment",isOpen:Qe.status!=="processing",isProcessing:st||Qe.status==="processing",closeOnComplete:!1,chainName:p.getChainName(P),explorerUrl:p.getExplorerUrl(P,"").replace(/\/tx\/.*$/,"")||void 0,onRetryTx:()=>{vt(!1),$e(null),ue()},onNewTx:Fe,onClose:()=>{vt(!1),$e(null)},onComplete:Fe,results:de,styles:C,dark:D})})]})})}return n.jsx(tn,{isOpen:e,onClose:t,title:yn,subtitle:we,dark:D,styles:C,theme:T,closeOnBackdropClick:s,children:n.jsxs("div",{style:{padding:"24px 24px 5px 24px",position:"relative"},children:[n.jsx("div",{style:{marginBottom:"16px"},children:n.jsx(Dn,{assets:Ye,selectedAsset:_||void 0,onAssetSelect:te,onAmountChange:se,disabled:st||Ie==="success",showBalance:!0,showMaxButton:!0,label:"From Wallet",placeholder:"0.00",theme:ce,styles:C,dark:N,resolveMaxAmount:$,maxAmount:Ht>0?kn(Ht,_?.asset.decimals??o.decimals):void 0})}),_?.asset&&!Je&&n.jsx(Xo,{variant:"supply",destinationSymbol:o.symbol,destinationLogoURI:o.logoURI,destinationDecimals:o.decimals,primaryColor:M,fontFamily:W,textPrimary:K,textSecondary:O,cardBg:L,cardBorder:q,dark:D,isQuoting:Te,quoteError:ft,estimatedOutput:Oe}),ht&&n.jsx(Vn,{fontFamily:W,textPrimary:K,textSecondary:O,cardBg:L,cardBorder:q,resolvedDark:D,darkCardBorder:U.cardBorder,primaryColor:M,feePreview:_e,isLoading:Et,errorText:jt,directExecutionFeeNote:Ee}),Ie!=="idle"&&n.jsxs("div",{style:{padding:"10px 14px",borderRadius:"7px",marginBottom:"16px",backgroundColor:Ie==="success"?L:Ie==="error"?z.errorBg:L,border:`1px solid ${Ie==="success"?q:Ie==="error"?z.errorBorder:q}`},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[Ie==="success"?n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:n.jsx("path",{d:"M5 13l4 4L19 7",stroke:z.successText,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"})}):Ie==="error"?n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",style:{flexShrink:0},children:n.jsx("path",{d:"M18 6L6 18M6 6l12 12",stroke:z.errorText,strokeWidth:"2.5",strokeLinecap:"round"})}):n.jsx(p.Spinner,{size:14,color:M}),n.jsx("span",{style:{fontSize:"13px",fontWeight:500,color:Ie==="success"?K:Ie==="error"?z.errorText:K,fontFamily:W,flex:1},children:Ie==="success"?"Deposit confirmed":Ie==="error"?Zt||"Transaction failed":cr[Ie]||Zt}),Ie==="success"&&gt&&n.jsx("a",{href:`${Ft}/tx/${gt}`,target:"_blank",rel:"noopener noreferrer",style:{fontSize:"12px",color:M,fontFamily:W,textDecoration:"none",whiteSpace:"nowrap",flexShrink:0},children:"View tx \u2192"}),Ie==="error"&&n.jsx("button",{onClick:()=>{Mt("idle"),mt(null),setTimeout(ye,50)},style:{background:"none",border:"none",fontSize:"12px",color:M,fontFamily:W,cursor:"pointer",padding:0,whiteSpace:"nowrap",flexShrink:0},children:"Retry \u2192"})]}),pt>=0&&Ie!=="success"&&Ie!=="error"&&n.jsx("div",{style:{marginTop:"8px",height:"3px",borderRadius:"2px",backgroundColor:`${O}22`,overflow:"hidden"},children:n.jsx("div",{style:{height:"100%",width:"100%",borderRadius:"2px",backgroundColor:M,transformOrigin:"left center",transform:`scaleX(${(pt+1)/dr.length})`,transition:"transform 400ms ease"}})})]}),Rt&&Ie==="idle"&&n.jsx(Sn,{variant:"error",palette:z,fontFamily:W,style:{marginBottom:"16px"},children:Rt}),n.jsx(p.Button,{variant:"outline",fullWidth:!0,disabled:xn,onClick:an,theme:T,dark:D,styles:{...C,button:{...C?.button,backgroundColor:M}},style:{fontSize:"20px",fontWeight:600,letterSpacing:"1.5px",fontFamily:Q},children:It})]})})},fl=e=>n.jsx(ur,{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}),hl=({label:e="Export Wallet",style:t,className:s,onExport:o,onError:a})=>{const[r,i]=c.useState(!1),[d,u]=c.useState(!1),{primaryColor:l}=p.useSpiceBrand(),h=c.useContext(p.SpiceFlowProviderContext),{isAuthenticated:f}=p.useWallet();let g=null;try{g=Ln.usePrivy()}catch{}let x=null,m=null;try{x=Zs.useEmbeddedReveal(),m=Zs.useDynamicContext()}catch{x=null,m=null}const y=p.getDynamicEmbeddedWallet(m),b=c.useCallback(async()=>{if(!f){a?.("User is not authenticated. Please log in first.");return}try{if(h?.provider==="dynamic"){if(!x||!y){a?.("Dynamic is not available. Ensure the app is wrapped in a DynamicContextProvider.");return}await x.initExportProcess(!1),o?.();return}if(!g){a?.("Privy is not available. Ensure the app is wrapped in a PrivyProvider.");return}await g.exportWallet(),o?.()}catch(C){const v=C instanceof Error?C.message:"Failed to export wallet";console.error("Export wallet error:",C),a?.(v)}},[y,x,f,a,o,g,h?.provider]),S=!f,w={padding:"10px 20px",borderRadius:"8px",fontFamily:'"IBM Plex Mono", monospace',fontSize:"14px",fontWeight:500,letterSpacing:"0.4px",textTransform:"uppercase",cursor:S?"not-allowed":"pointer",opacity:S?.5:1,border:"1px solid #0e0d0b",color:"#0e0d0b",backgroundColor:d?`${l}cc`:r?`${l}ee`:l,transition:"background-color 150ms ease, transform 150ms ease",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"8px",...t};return n.jsxs("button",{onClick:b,onMouseEnter:()=>i(!0),onMouseLeave:()=>{i(!1),u(!1)},onMouseDown:()=>u(!0),onMouseUp:()=>u(!1),disabled:S,className:s,style:w,children:[n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),n.jsx("polyline",{points:"17 8 12 3 7 8"}),n.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]}),e]})};function pr(e){const t=c.useContext(p.SpiceFlowProviderContext),s=p.useEmbeddedWalletAddress(),o=e?.enabled===!1?void 0:s,a=t?.network?{network:t.network,pollIntervalMs:e?.pollIntervalMs,chainIds:e?.chainIds??t.supportedChainIds,discoverWalletBalances:e?.discoverWalletBalances}:void 0;return{...ho(o,a),embeddedWalletAddress:s}}var ml="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 gl=({appName:e,status:t,statusLabel:s,totalUsdValue:o,breakdownSubtitle:a,address:r,dk:i,dark:d=!1,showModeToggle:u,isEmbeddedMode:l=!0,onModeToggle:h})=>{const[f,g]=c.useState(!1),x=async()=>{r&&await Lr(r)&&(g(!0),setTimeout(()=>g(!1),2e3))},m=t==="active",y=s||(m?"Active":"Inactive"),b=m?"#10b981":"#9ca3af",S=n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[n.jsxs("div",{children:[n.jsx("strong",{children:"Embedded:"})," Deposit assets into ",e," account and use them here."]}),n.jsxs("div",{children:[n.jsx("strong",{children:"External:"})," Use assets from your connected wallet here."]})]});return n.jsxs("div",{children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"4px"},children:[n.jsxs("div",{style:{fontSize:"13px",fontWeight:600,color:i.textPrimary},children:[e," Account"]}),u?n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[n.jsxs("button",{onClick:h,style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:d?i.hoverBg:"#f3f4f6",border:d?`1px solid ${i.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"11px",fontWeight:600,fontFamily:'"IBM Plex Mono", monospace',color:i.textSecondary,transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease",letterSpacing:"0.02em"},children:[n.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:l?"#22c55e":"#f59e0b"}}),n.jsx("span",{children:l?"Embedded":"External"}),n.jsx("img",{src:ml,alt:"","aria-hidden":"true",style:{width:"11px",height:"11px",display:"block",...d?{filter:"invert(0.65)"}:{}}})]}),n.jsx(ro,{content:S,label:"Account mode info",textColor:d?i.textPrimary:"#f9fafb",backgroundColor:d?i.cardBg:"#111827",borderColor:d?i.cardBorder:"rgba(255,255,255,0.08)",accentColor:d?i.textSecondary:"#6b7280",children:n.jsx("img",{src:Ss,alt:"","aria-hidden":"true",style:{width:"12px",height:"12px",display:"block",...d?{filter:"invert(0.65)"}:{}}})})]}):n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"2px 8px",borderRadius:"9999px",backgroundColor:d?i.hoverBg:m?"#ecfdf5":"#f3f4f6",border:d?`1px solid ${i.cardBorder}`:m?"1px solid #a7f3d0":"1px solid #e5e7eb"},children:[n.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:b}}),n.jsx("span",{style:{fontSize:"11px",fontWeight:500,color:d?i.textSecondary:m?"#065f46":"#6b7280"},children:y})]})]}),n.jsx("div",{style:{fontSize:"28px",fontWeight:700,color:i.textPrimary,lineHeight:1.2,marginBottom:"2px"},children:bn(o)}),a&&n.jsx("div",{style:{fontSize:"12px",color:i.textSecondary,marginBottom:"8px"},children:a}),r&&n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[n.jsx("span",{style:{fontSize:"12px",fontFamily:'"IBM Plex Mono", monospace',color:d?i.textSecondary:"#9ca3af"},children:zr(r)}),n.jsx("button",{onClick:x,style:{padding:"2px 6px",fontSize:"10px",fontWeight:500,backgroundColor:"transparent",color:d?i.textSecondary:"#9ca3af",border:"none",cursor:"pointer",borderRadius:"4px",transition:"background-color 150ms ease, color 150ms ease"},title:"Copy address",children:f?"Copied":"Copy"})]})]})},xl=({pendingDeposits:e,onCompleteDeposit:t,dk:s,dark:o=!1})=>e.length===0?null:n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:s.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:"Pending Deposits"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((a,r)=>{const i=p.getChainConfig(a.chainId)?.displayName||`Chain ${a.chainId}`;return n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:o?s.warningBg:"#fffbeb",border:o?`1px solid ${s.warningBorder}`:"1px solid #fde68a",borderRadius:"8px"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[n.jsx("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:o?s.hoverBg:"#fde68a",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:s.warningText},children:a.tokenSymbol.charAt(0)}),n.jsxs("div",{children:[n.jsxs("div",{style:{fontSize:"13px",fontWeight:500,color:s.textPrimary},children:[a.amount," ",a.tokenSymbol]}),n.jsxs("div",{style:{fontSize:"11px",color:s.warningText},children:["on ",i]})]})]}),n.jsx("button",{onClick:()=>t?.(a),style:{padding:"4px 12px",fontSize:"11px",fontWeight:600,backgroundColor:o?s.hoverBg:"#fef3c7",color:o?s.textPrimary:"#92400e",border:o?`1px solid ${s.warningBorder}`:"1px solid #fde68a",borderRadius:"9999px",cursor:"pointer",transition:"background-color 150ms ease, border-color 150ms ease, color 150ms ease"},children:"Complete"})]},`${a.tokenAddress}-${a.chainId}-${r}`)})})]}),yl=({spiceAssets:e,loading:t,dk:s,dark:o=!1})=>{const a={fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:s.textSecondary,marginBottom:"8px",textTransform:"uppercase"},r={backgroundColor:s.cardBg,border:o?`1px solid ${s.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"};return t?n.jsxs("div",{children:[n.jsx("div",{style:a,children:"Idle Balances"}),[1,2].map(i=>n.jsx("div",{style:{...r,padding:"12px",marginBottom:"6px",height:"48px",animation:"pulse 1.5s ease-in-out infinite",opacity:.5}},i))]}):e.length===0?n.jsxs("div",{children:[n.jsx("div",{style:a,children:"Idle Balances"}),n.jsx("div",{style:{...r,padding:"16px",textAlign:"center",fontSize:"13px",color:o?s.textSecondary:"#9ca3af"},children:"No assets yet. Deposit to get started."})]}):n.jsxs("div",{children:[n.jsx("div",{style:a,children:"Idle Balances"}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.map((i,d)=>{const u=p.getChainConfig(i.chainId),l=i.chainDisplayName||u?.displayName||`Chain ${i.chainId}`,h=i.tokenDisplaySymbol||i.tokenDisplayName||i.tokenSymbol;return n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",...r},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[i.logoURI?n.jsx("img",{src:i.logoURI,alt:i.tokenSymbol,style:{width:"24px",height:"24px",borderRadius:"50%"}}):n.jsx("div",{style:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:o?s.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:600,color:s.textSecondary},children:h.charAt(0)}),n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:s.textPrimary},children:h}),n.jsx("div",{style:{fontSize:"11px",color:o?s.textSecondary:"#9ca3af"},children:l})]})]}),n.jsxs("div",{style:{textAlign:"right"},children:[n.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:s.textPrimary},children:ln(i.balanceFormatted)}),n.jsx("div",{style:{fontSize:"11px",color:o?s.textSecondary:"#9ca3af"},children:bn(i.usdValue)})]})]},`${i.tokenAddress}-${i.chainId}-${d}`)})})]})},Cl=({section:e,dk:t,dark:s=!1})=>{const o=a=>{switch(a){case"green":return"#10b981";case"red":return"#ef4444";default:return t.textPrimary}};return n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"1px",color:t.textSecondary,marginBottom:"8px",textTransform:"uppercase"},children:e.title}),n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:e.items.map((a,r)=>n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",backgroundColor:t.cardBg,border:s?`1px solid ${t.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[a.tokenLogoURI?n.jsx("img",{src:a.tokenLogoURI,alt:a.tokenSymbol,style:{width:"20px",height:"20px",borderRadius:"50%"}}):n.jsx("div",{style:{width:"20px",height:"20px",borderRadius:"50%",backgroundColor:s?t.hoverBg:"#e5e7eb",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",fontWeight:600,color:t.textSecondary},children:a.tokenSymbol.charAt(0)}),n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:"13px",fontWeight:500,color:t.textPrimary},children:a.tokenSymbol}),n.jsx("div",{style:{fontSize:"11px",color:t.textSecondary},children:a.label})]})]}),n.jsx("div",{style:{fontSize:"13px",fontWeight:600,color:o(a.valueColor)},children:a.displayValue})]},r))})]})},bl=({onDepositClick:e,onWithdrawClick:t,depositDisabled:s=!1,withdrawDisabled:o=!1,primaryColor:a="#EA4B4B",dark:r=!1})=>!e&&!t?null:n.jsxs("div",{style:{display:"flex",gap:"8px"},children:[e&&n.jsx(p.Button,{variant:"outline",onClick:e,disabled:s,dark:r,styles:{button:{backgroundColor:a}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Deposit"}),t&&n.jsx(p.Button,{variant:"outline",onClick:t,disabled:o,dark:r,styles:{button:{backgroundColor:a}},style:{flex:1,height:"44px",fontSize:"12px"},children:"Withdraw"})]}),wl=({appName:e,status:t,statusLabel:s,totalUsdValue:o,breakdownSubtitle:a,address:r,spiceAssets:i,spiceAssetsLoading:d,pendingDeposits:u,customSections:l,onDepositClick:h,onWithdrawClick:f,onCompleteDeposit:g,primaryColor:x,dk:m,dark:y=!1,showModeToggle:b,isEmbeddedMode:S,onModeToggle:w,showConnectExternalCta:C,onConnectExternalWallet:v,connectExternalError:k,showHowItWorks:A=!0})=>{const[E,R]=c.useState(!1);return n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"16px",padding:"16px",maxHeight:"calc(80vh - 32px)",overflowY:"auto"},children:[n.jsx(gl,{appName:e,status:t,statusLabel:s,totalUsdValue:o,breakdownSubtitle:a,address:r,dk:m,dark:y,showModeToggle:b,isEmbeddedMode:S,onModeToggle:w}),C&&n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:[n.jsx("button",{onClick:v,style:{width:"100%",padding:"10px 14px",borderRadius:"8px",backgroundColor:x||"#EA4B4B",color:"#ffffff",border:"none",cursor:"pointer",fontSize:"13px",fontWeight:600,fontFamily:'"Helvetica Neue", sans-serif',transition:"opacity 150ms ease"},children:"Connect External Wallet"}),k&&n.jsx("span",{style:{fontSize:"11px",color:y?m.errorText:"#b91c1c",lineHeight:1.4},children:k})]}),n.jsx("div",{style:{height:"1px",backgroundColor:y?"#2d2d2d":"#e5e7eb"}}),n.jsx(bl,{onDepositClick:h,onWithdrawClick:f,primaryColor:x,dark:y}),A&&n.jsxs("div",{children:[n.jsxs("button",{onClick:()=>R(!E),style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"8px 12px",backgroundColor:m.cardBg,border:y?`1px solid ${m.cardBorder}`:"1px solid #e5e7eb",borderRadius:"8px",cursor:"pointer",color:m.textSecondary,fontSize:"12px",fontWeight:500},children:[n.jsx("span",{children:"How It Works"}),n.jsx("span",{style:{transform:E?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease",fontSize:"10px"},children:"\u25BE"})]}),E&&n.jsxs("div",{style:{marginTop:"6px",padding:"10px 12px",backgroundColor:y?m.cardBg:"#f0fdf4",border:y?`1px solid ${m.cardBorder}`:"1px solid #bbf7d0",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,color:y?m.textSecondary:"#374151"},children:["Fund your ",e," Account from any supported chain. Once funded, transact gas-free and asset-abstracted on ",e,"."]})]}),n.jsx(xl,{pendingDeposits:u,onCompleteDeposit:g,dk:m,dark:y}),n.jsx(yl,{spiceAssets:i,loading:d,dk:m,dark:y}),l.map((B,I)=>n.jsx(Cl,{section:B,dk:m,dark:y},I))]})},Qs=380,gn=8,kl=[];function fr(e){return e?.trim().replace(/^spice/i,"").replace(/[^a-z0-9]/gi,"").toUpperCase()||void 0}function vl(e,t){const s=new Map;Object.entries(t).forEach(([a,r])=>{if(!Number.isFinite(r)||r<=0)return;s.set(a,r),s.set(a.toUpperCase(),r);const i=fr(a);i&&s.set(i,r)});const o=[e.symbol,e.displaySymbol,e.receiptTokenName,e.name,e.displayName];for(const a of o){if(!a)continue;const r=s.get(a)??s.get(a.toUpperCase());if(r!==void 0)return r;const i=fr(a);if(!i)continue;const d=s.get(i);if(d!==void 0)return d}return 0}const Sl=({appName:e="Spice",status:t="active",statusLabel:s,customSections:o=[],extraAssets:a=[],tokenPrices:r={},breakdownLabels:i=[],styles:d,dark:u=!1,onDepositSuccess:l,onDepositClick:h,onWithdrawClick:f,onCompleteDeposit:g,showModeToggle:x=!1,defaultMode:m})=>{const y=c.useContext(p.SpiceFlowProviderContext),b=y?.mode!=="7702",S=!!y?.isWhitelistGateActive,w=S?kl:a,C=c.useRef(!1);c.useEffect(()=>{if(!C.current){if(p.hasStoredSpiceFlowMode()){C.current=!0;return}m&&y?.setMode&&(y.setMode(m==="non7702"?"ondemand":"7702"),C.current=!0)}},[y,m]);const[v,k]=c.useState(!1),[A,E]=c.useState(null),[R,B]=c.useState({top:0,bottom:0,left:0,placement:"below"}),I=c.useRef(null),T=c.useRef(null),{address:D,isConnected:M}=p.useWallet(),U=p.useEmbeddedWalletAddress(),{externalAddress:z}=p.useProviderWallets(),{dark:W,primaryColor:Q,dk:N}=p.useSpiceBrand(d,u),L=!b&&U?U:D,q=c.useMemo(()=>y?.supportedChainIds??F.getChainIdsByNetwork("mainnet"),[y?.supportedChainIds]),{assets:K,loading:O}=Wn({address:L,supportedChains:q,enabled:!!L&&!b,refetchInterval:3e4}),G=c.useMemo(()=>[...b?[]:K.map(oe=>{const ie=oe.balanceUsd||0,Ye=Number.isFinite(oe.balanceFormatted)?oe.balanceFormatted:0,_=ie>0?ie:vl(oe,r)*Ye;return{tokenAddress:oe.address,tokenSymbol:oe.symbol,tokenDisplaySymbol:ms(oe),tokenDisplayName:Kr(oe),tokenDecimals:oe.decimals,chainId:oe.chainId,chainDisplayName:gs(oe),balance:oe.balance.toString(),balanceFormatted:oe.balanceFormatted,usdValue:_,logoURI:oe.logoURI}}),...w].filter(oe=>oe.balanceFormatted>0),[b,K,r,w]),ce=c.useMemo(()=>G.reduce((oe,ie)=>oe+ie.usdValue,0),[G]),{pendingDeposits:P}=pr({chainIds:q,enabled:!!D,discoverWalletBalances:!1}),ne=c.useMemo(()=>o.reduce((oe,ie)=>oe+ie.totalValue,0),[o]),me=ce+ne,ke=c.useMemo(()=>{const oe=[];ce>0&&oe.push(`${bn(ce)} idle`);for(const ie of o){const Ye=i.find(_=>_.sectionTitle===ie.title)?.label||ie.title.toLowerCase();oe.push(`${bn(ie.totalValue)} ${Ye}`)}return oe.join(" \xB7 ")},[ce,o,i]),pe=c.useCallback(oe=>{g?g(oe):E(oe)},[g]),ge=c.useCallback(()=>{E(null)},[]),fe=c.useCallback(()=>{E(null),l?.()},[l]),V=c.useCallback(()=>{if(!I.current)return;const oe=I.current.getBoundingClientRect(),ie=window.innerHeight-oe.bottom-gn,Ye=oe.top-gn,_=ie>=400||ie>=Ye?"below":"above",Me=Math.max(gn,Math.min(oe.right-Qs,window.innerWidth-Qs-gn)),ct=_==="below"?oe.bottom+gn:oe.top-gn,kt=_==="above"?window.innerHeight-ct:0;B({top:ct,bottom:kt,left:Me,placement:_})},[]);c.useLayoutEffect(()=>{v&&V()},[v,V]),c.useEffect(()=>{if(!v)return;const oe=_=>{I.current&&!I.current.contains(_.target)&&T.current&&!T.current.contains(_.target)&&k(!1)},ie=_=>{_.key==="Escape"&&k(!1)},Ye=()=>V();return document.addEventListener("mousedown",oe),document.addEventListener("keydown",ie),window.addEventListener("scroll",Ye,{passive:!0}),window.addEventListener("resize",V),()=>{document.removeEventListener("mousedown",oe),document.removeEventListener("keydown",ie),window.removeEventListener("scroll",Ye),window.removeEventListener("resize",V)}},[v,V]);const re=y?.mode==="7702",X=re?U||D:z||D,le=c.useCallback(()=>{y?.setMode&&y.setMode(re?"ondemand":"7702")},[y,re]),[xe,Se]=c.useState(null);let J=null;try{J=Ln.useConnectWallet({onSuccess:()=>Se(null),onError:oe=>Se(p.sanitizeError(oe,"Failed to connect wallet."))}).connectWallet}catch{J=null}const Y=c.useCallback(()=>{J&&(k(!1),Se(null),J({walletChainType:"ethereum-only"}))},[J]),ae=!z&&!!J,Ce=c.useCallback(()=>{k(!1),h?.()},[h]),We=c.useCallback(()=>{k(!1),f?.()},[f]),rt=c.useCallback(oe=>{k(!1),pe(oe)},[pe]);if(typeof window>"u")return null;const Ke=n.jsxs("button",{ref:I,onClick:()=>k(!v),style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"8px 14px",borderRadius:"9999px",backgroundColor:W?N.hoverBg:"#ffffff",border:W?`1px solid ${N.cardBorder}`:"1px solid #e5e7eb",cursor:"pointer",fontSize:"13px",fontWeight:500,fontFamily:'"Helvetica Neue", sans-serif',color:W?N.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:[n.jsx("span",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:Q,flexShrink:0}}),n.jsxs("span",{children:[e," Account"]}),M&&n.jsxs("span",{style:{color:W?N.textSecondary:"#6b7280"},children:["\xB7 ",bn(me)]}),n.jsx("span",{style:{fontSize:"10px",color:W?N.textSecondary:"#9ca3af",transform:v?"rotate(180deg)":"rotate(0deg)",transition:"transform 200ms ease"},children:"\u25BE"})]}),Ze=v?Bn.createPortal(n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{position:"fixed",inset:0,backgroundColor:"rgba(0, 0, 0, 0.08)",zIndex:pn.popover},onClick:()=>k(!1)}),n.jsx("div",{ref:T,style:{position:"fixed",top:R.placement==="below"?`${R.top}px`:"auto",bottom:R.placement==="above"?`${R.bottom}px`:"auto",left:`${R.left}px`,width:`${Qs}px`,maxWidth:`calc(100vw - ${gn*2}px)`,maxHeight:"80vh",backgroundColor:W?N.shell:"#ffffff",border:W?`1px solid ${N.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:pn.popover+1,overflow:"hidden",animation:`accountDisplayFadeIn 200ms ${wt.out}`},children:n.jsx(wl,{appName:e,status:t,statusLabel:s,totalUsdValue:me,breakdownSubtitle:ke,address:re?X:D,spiceAssets:G,spiceAssetsLoading:O,pendingDeposits:P,customSections:o,onDepositClick:h?Ce:void 0,onWithdrawClick:f?We:void 0,onCompleteDeposit:rt,primaryColor:Q,dk:N,dark:W,showModeToggle:x,isEmbeddedMode:re,onModeToggle:le,showConnectExternalCta:ae,onConnectExternalWallet:Y,connectExternalError:xe,showHowItWorks:!S})}),n.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 n.jsxs(n.Fragment,{children:[Ke,Ze,A&&Bn.createPortal(n.jsx(fo,{isOpen:!0,onClose:ge,supportedChains:[A.chainId],escrowOnly:!0,escrowTokenAddress:A.tokenAddress,escrowAmount:A.amount,escrowTokenDecimals:A.tokenDecimals,escrowTokenSymbol:A.tokenSymbol,styles:d,onDepositSuccess:fe}),document.body)]})},hr=class qs extends c.Component{constructor(t){super(t),this.handleRetry=()=>{this.state.retryCount>=qs.MAX_RETRIES||this.setState(s=>({hasError:!1,error:null,retryCount:s.retryCount+1}))},this.state={hasError:!1,error:null,retryCount:0}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,s){console.error(`[SdkErrorBoundary] ${this.props.componentName||"SDK component"} failed:`,{message:t.message,componentStack:s.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"},s={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},a={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"},r={fontSize:"12px",color:"#888",margin:0},i=qs.MAX_RETRIES-this.state.retryCount;return n.jsxs("div",{style:t,children:[n.jsxs("p",{style:s,children:[this.props.componentName||"Component"," failed to load"]}),this.state.error&&n.jsx("p",{style:o,children:this.state.error.message}),i>0?n.jsxs("button",{onClick:this.handleRetry,style:a,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 (",i," left)"]}):n.jsx("p",{style:r,children:"Please refresh the page to try again"})]})}return this.props.children}};hr.MAX_RETRIES=3;let Sl=hr;const Il=()=>{const[e,t]=c.useState("0"),[s,o]=c.useState(null);return{assetAmount:e,setAssetAmount:t,selectedAsset:s,setSelectedAsset:o}};function Al(e,t=0){const[s,o]=c.useState(t),a=e[s]??e[0],r=c.useMemo(()=>a?BigInt(Math.round(a.months*30*24*3600)):0n,[a?.months]);return{selectedDurationIdx:s,setSelectedDurationIdx:o,selectedDuration:a,durationSeconds:r}}function El(){const{actions:e,isReady:t,isAuthenticated:s}=p.useWallet(),o=p.useEmbeddedWalletAddress(),a=c.useRef(!1),r=c.useRef(0),i=c.useRef(null),d=c.useRef(e),[u,l]=c.useState(0);d.current=e,c.useEffect(()=>{a.current=!1,r.current=0,i.current&&(clearTimeout(i.current),i.current=null)},[o]),c.useEffect(()=>{if(!o||!t||!s||a.current)return;a.current=!0;let h=!1;return(async()=>{await new Promise(f=>setTimeout(f,2e3));try{await p.ensureSmartWallet(o,d.current.signMessage),r.current=0}catch(f){console.warn("[SmartWallet] Registration failed:",f),a.current=!1,!h&&r.current<3&&(r.current+=1,i.current=setTimeout(()=>{l(g=>g+1)},5e3))}})(),()=>{h=!0,i.current&&(clearTimeout(i.current),i.current=null)}},[o,t,s,u])}const mr="https://portal-api.spicenet.io/api/v1/portal/mainnet",jl=e=>({"Content-Type":"application/json",Authorization:`Bearer ${e}`,"x-privy-access-token":e});async function Fl(e,t,s=mr){const o=await fetch(`${s}/link-wallet`,{method:"POST",headers:jl(e),body:JSON.stringify(t)});if(!o.ok){const a=await o.text().catch(()=>"");throw new Error(`Portal link-wallet failed: ${o.status} ${a}`.trim())}return o.json().catch(()=>({}))}const Vs=new Map;async function Bl({partnerId:e,campaignId:t,campaignGroup:s,embeddedWalletAddress:o,externalWalletAddress:a,token:r,baseUrl:i=mr}){const d=`${o.toLowerCase()}:${a.toLowerCase()}`,u=Vs.get(d);if(u)return u;const l=(async()=>{await Fl(r,{partnerId:e,campaignId:t,campaignGroup:s,embeddedWalletAddress:o,externalWalletAddress:a},i)})();Vs.set(d,l);try{await l}finally{Vs.delete(d)}}function Tl(e={}){const{enabled:t=!0,baseUrl:s}=e,o=c.useContext(p.SpiceFlowProviderContext)?.whitelistCheck,{isReady:a,isAuthenticated:r}=p.useWallet(),{embeddedAddress:i,externalAddress:d}=p.useProviderWallets();let u=null;try{({identityToken:u}=Ln.useIdentityToken())}catch{u=null}const l=e.partnerId??o?.partnerId,h=e.campaignId??o?.campaignId,f=e.campaignGroup??o?.campaignGroup,g=!!o,x=!!o?.isLinkedWallet,m=c.useRef(!1),y=c.useRef(0),b=c.useRef(null),[S,w]=c.useState(0);c.useEffect(()=>{m.current=!1,y.current=0,b.current&&(clearTimeout(b.current),b.current=null)},[i,d]),c.useEffect(()=>{if(!t||!a||!r||!u||!i||!d||!l||!g||x||m.current)return;m.current=!0;let C=!1;return(async()=>{try{await Bl({partnerId:l,campaignId:h,campaignGroup:f,embeddedWalletAddress:i,externalWalletAddress:d,token:u,baseUrl:s}),y.current=0}catch(v){console.warn("[WalletLink] Linking failed:",v),m.current=!1,!C&&y.current<3&&(y.current+=1,b.current=setTimeout(()=>{w(k=>k+1)},5e3))}})(),()=>{C=!0,b.current&&(clearTimeout(b.current),b.current=null)}},[t,a,r,u,i,d,l,h,f,g,x,s,S])}const ns=1500,gr="spiceflow-75f053db-70ab-4f37-83cc-abf68cb5b70d",Rl={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 xr(e,t,s){return(e*t+s-1n)/s}function yr(e,t=ns){return xr(e,BigInt(1e4+t),10000n)}function Cr(e,t){return`evm:${e}:${j.getAddress(t).toLowerCase()}`}function br(e){return Rl[e]??null}function Ml(e){return e==="testnet"?"https://iris-api-sandbox.circle.com":"https://iris-api.circle.com"}function Dl(e){const t=typeof e=="number"?e.toString():typeof e=="string"?e:"0",[s,o=""]=t.trim().split("."),a=BigInt(s||"0"),r=BigInt((o+"00").slice(0,2)||"0");return a*100n+r}function Nl(e,t){const s=Dl(t);return xr(e,s,1000000n)}async function Wl(e){const t=e.transferMode??"fast",s=br(e.sourceChainId),o=br(e.destinationChainId);if(!s||!o||s.network!==o.network)throw new Error(`Unsupported CCTP route ${e.sourceChainId} -> ${e.destinationChainId}`);let a=0n;const r=t==="fast"?1e3:2e3;if(t==="fast"){const d=e.fetchImpl??fetch,u=`${Ml(s.network)}/v2/burn/USDC/fees/${s.domain}/${o.domain}`,l=await d(u);if(!l.ok)throw new Error(`CCTP fee quote failed: ${l.status} ${l.statusText}`);const h=await l.json(),f=Array.isArray(h)?h:Array.isArray(h?.data)?h.data:[],g=f.find(x=>String(x.finalityThreshold??x.finalityThresholdExecuted??"")==="1000")??f[0];a=Nl(e.amountIn,g?.minimumFee??0)}const i=yr(a,e.bufferBps);return{provider:"cctp",sourceChainId:e.sourceChainId,destinationChainId:e.destinationChainId,tokenIn:j.getAddress(e.tokenIn),tokenOut:j.getAddress(e.tokenOut),amountIn:e.amountIn,estimatedAmountOut:e.amountIn>a?e.amountIn-a:0n,quotedBridgeFee:a,bufferedBridgeFee:i,bufferBps:e.bufferBps??ns,minFinalityThreshold:r,metadata:{sourceDomain:s.domain,destinationDomain:o.domain,transferMode:t}}}function ss(e){return typeof e=="string"&&e.length>0?e:void 0}function os(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 Ul(e){const t=e.estimate;return os(t?.toAmountMin)??os(t?.toAmount)??os(e.toAmountMin)??os(e.toAmount)}async function Pl(e){const t=e.integratorId??gr,s=e.fetchImpl??fetch,o=e.baseUrl??"https://v2.api.squidrouter.com",a=await s(`${o}/v2/route`,{method:"POST",headers:{"Content-Type":"application/json","x-integrator-id":t},body:JSON.stringify({fromAddress:j.getAddress(e.fromAddress),fromChain:String(e.sourceChainId),fromToken:j.getAddress(e.tokenIn),fromAmount:e.amountIn.toString(),toAddress:j.getAddress(e.toAddress),toChain:String(e.destinationChainId),toToken:j.getAddress(e.tokenOut),slippage:e.slippage??1,quoteOnly:e.quoteOnly??!0})}),r=await a.json().catch(()=>null);if(!a.ok){const l=typeof r?.message=="string"?r.message:`${a.status} ${a.statusText}`;throw new Error(`Squid route quote failed: ${l}`)}const i=r?.route;if(!i)throw new Error("Squid route quote response did not include route");const d=Ul(i);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:j.getAddress(e.tokenIn),tokenOut:j.getAddress(e.tokenOut),amountIn:e.amountIn,estimatedAmountOut:d,quotedBridgeFee:u,bufferedBridgeFee:yr(u,e.bufferBps),bufferBps:e.bufferBps??ns,...ss(i.quoteId)?{quoteId:ss(i.quoteId)}:{},...ss(a.headers.get("x-request-id"))?{route:ss(a.headers.get("x-request-id"))}:{},metadata:{requestId:a.headers.get("x-request-id")??void 0,slippage:e.slippage??1,quoteOnly:e.quoteOnly??!0}}}function zl(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 Ll(e){return`0x72${j.keccak256(j.encodeAbiParameters([{type:"address"},{type:"uint256"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"address"},{type:"uint256"},{type:"uint256"}],[j.getAddress(e.recipient),BigInt(e.fromChainId),j.getAddress(e.fromToken),e.fromAmount,BigInt(e.toChainId),j.getAddress(e.toToken),e.toAmountMin,e.salt??BigInt(Date.now())])).slice(4)}`}function Ol(e){const t=BigInt(Math.floor(Date.now()/1e3)),s=e.exp??t+3600n,o=e.nbf??0n,a=e.idempotenceKey??Ll({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:j.encodeFunctionData({abi:F.spicenetAbi,functionName:"createRebalancingRequest",args:[{idempotenceKey:a,nbf:o,exp:s,metadata:JSON.stringify(e.metadata??{}),recipient:j.getAddress(e.recipient).toLowerCase(),fromChainToken:Cr(e.fromChainId,e.fromToken),fromChainTokenAmount:e.fromAmount,toChainToken:Cr(e.toChainId,e.toToken),toChainTokenAmountMin:e.toAmountMin}]})}]}}function zn(e){try{return F.resolveTokenRef(e)}catch{throw new p.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 Hl(e,t){if(e[0].toUpperCase()===t[0].toUpperCase()&&e[1]===t[1])return!0;let s,o;try{s=zn(e),o=zn(t)}catch{return!1}const a=new Set(F.getEquivalentAddresses(o.address).map(r=>r.toLowerCase()));return a.add(o.address.toLowerCase()),a.has(s.address.toLowerCase())}function Ql(){const e=[];for(const t of Object.keys(F.CHAINS).map(Number))for(const s of F.getTokensForChain(t))e.push([s.symbol,t]);return e}async function Vl(e){const{action:t,inputToken:s,inputAmount:o,registry:a,userAddress:r,slippage:i,intermediaryCandidates:d}=e;if(t.calls.length===0)throw new p.SpiceflowError("INVALID_PARAMS","buildIntent: action.calls must not be empty.",{action:t});if(o<=0n)throw new p.SpiceflowError("INVALID_PARAMS","buildIntent: inputAmount must be greater than zero.",{inputAmount:o.toString()});const u=t.supportedInputTokens??Ql();if(!u.some(b=>Hl(s,b))){const b=u.map(([S,w])=>`${S} (chain ${w})`).join(", ");throw new p.SpiceflowError("ROUTE_UNSUPPORTED_INPUT",`Input token "${s[0]}" on chain ${s[1]} is not in the action's supported input tokens. Supported: ${b}.`,{inputToken:{symbol:s[0],chainId:s[1]},supportedInputTokens:u})}const l=zn(s),h=zn(t.outputToken),f=Lo({sourceAsset:l,outputAsset:h,sourceChainId:l.chainId,destinationChainId:t.chainId,intermediaryCandidates:d}),{chainBatches:g,solverFrontToken:x,solverFrontAmount:m,resolvedSwaps:y}=await Oo({route:f,sourceAmount:o,userAddress:r,registry:a,actionCalls:t.calls,slippage:i});return{chainBatches:g,route:f,resolvedSwaps:y,resolvedInputToken:l,resolvedOutputToken:h,solverFrontToken:x,solverFrontAmount:m}}const ql=[0n,1n,30n],Kl=new Set(["ABORT","CONCURRENT_EXECUTION","WALLET_DISCONNECTED","WALLET_REJECTED","NO_VENUE_FOR_CHAIN"]);function wr(e,t){return t===0n?e:e*(1000n-t)/1000n}async function Zl(e,t){const{chainId:s,swapCalls:o,quoteAmountOut:a,buildActionCalls:r,tokenAddress:i,tokenTransferAmount:d,onProgress:u,signal:l,options:h,buffers:f=ql}=t;for(let g=0;g<f.length;g++){const x=f[g],m=wr(a,x),y=r(m),b=[{chainId:s,calls:[...o,...y]}];try{return await e(b,i,d,u,l,h)}catch(S){if(p.isSpiceflowError(S)&&Kl.has(S.code)||S.name==="AbortError"||l?.aborted||S.message?.includes("User rejected")||S.message?.includes("User denied")||S.code===4001||g>=f.length-1)throw S;const w=Number(f[g+1])/10;console.warn(`[SwapThenAction] Action attempt ${g+1} failed (buffer ${Number(x)/10}%), retrying with ${w}% buffer...`,S.message),u?.({step:"signing-delegation",message:`Adjusting action amount, retrying (${w}% buffer)...`})}}throw new p.SpiceflowError("ALL_ATTEMPTS_FAILED","All action attempts failed after exhausting buffer progression.",{attempts:f.length,chainId:s})}Dr(),exports.SpiceFlowProvider=p.SpiceFlowProvider,exports.SpiceFlowProviderContext=p.SpiceFlowProviderContext,exports.SpiceflowError=p.SpiceflowError,exports.Spinner=p.Spinner,exports.buildDarkPalette=p.buildDarkPalette,exports.buildLightPalette=p.buildLightPalette,exports.getChainConfig=p.getChainConfig,exports.getChainName=p.getChainName,exports.isSpiceflowError=p.isSpiceflowError,exports.relayerService=p.relayerService,exports.resolveTheme=p.resolveTheme,exports.useEmbeddedWalletAddress=p.useEmbeddedWalletAddress,exports.useIsUserWhitelisted=p.useIsUserWhitelisted,exports.useSpiceBrand=p.useSpiceBrand,exports.useWallet=p.useWallet,Object.defineProperty(exports,"NATIVE_TOKEN_ADDRESS",{enumerable:!0,get:function(){return F.ZERO_ADDRESS}}),Object.defineProperty(exports,"SPICENET_NATIVE_CHAIN_ID",{enumerable:!0,get:function(){return F.SPICENET_NATIVE_CHAIN_ID}}),Object.defineProperty(exports,"SPICE_COMBINED_FEE_RECIPIENT",{enumerable:!0,get:function(){return F.SPICE_COMBINED_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_GAS_FEE_RECIPIENT",{enumerable:!0,get:function(){return F.SPICE_GAS_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_PLATFORM_FEE_RECIPIENT",{enumerable:!0,get:function(){return F.SPICE_PLATFORM_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_SOLVER_ADDRESS",{enumerable:!0,get:function(){return F.SPICE_SOLVER_ADDRESS}}),Object.defineProperty(exports,"applySlippage",{enumerable:!0,get:function(){return F.applySlippage}}),Object.defineProperty(exports,"buildUniV3SwapCalls",{enumerable:!0,get:function(){return F.buildUniV3SwapCalls}}),Object.defineProperty(exports,"getChainIdsByNetwork",{enumerable:!0,get:function(){return F.getChainIdsByNetwork}}),Object.defineProperty(exports,"getEscrowContractAddress",{enumerable:!0,get:function(){return F.getEscrowContractAddress}}),Object.defineProperty(exports,"isNativeToken",{enumerable:!0,get:function(){return F.isNativeToken}}),Object.defineProperty(exports,"isSpicenetChainId",{enumerable:!0,get:function(){return F.isSpicenetChainId}}),Object.defineProperty(exports,"normalizeNativeTokenAddress",{enumerable:!0,get:function(){return F.normalizeNativeTokenAddress}}),Object.defineProperty(exports,"spicenetAbi",{enumerable:!0,get:function(){return F.spicenetAbi}}),Object.defineProperty(exports,"spicenetWithdrawalAbi",{enumerable:!0,get:function(){return F.spicenetAbi}}),exports.AccountDisplay=vl,exports.AddFundsLink=ws,exports.CheckIcon=io,exports.ChevronIcon=nn,exports.CloseIcon=vn,exports.DEFAULT_BRIDGE_FEE_BUFFER_BPS=ns,exports.DEFAULT_SQUID_INTEGRATOR_ID=gr,exports.DetailRow=In,exports.ExportWalletButton=hl,exports.ProviderLogin=Is,exports.SATSUMA_CITREA_CONFIG=Hs,exports.SdkErrorBoundary=Sl,exports.SearchInput=ls,exports.SelectChainModal=Ma,exports.SpiceBalance=Ii,exports.SpiceDeposit=mo,exports.SpiceLock=Zo,exports.SpiceLockModal=Zo,exports.SpicePay=fl,exports.SpiceSupply=ur,exports.SpiceWithdraw=Ho,exports.StatusBanner=Sn,exports.UNIV3_BASE_CONFIG=rr,exports.applyBuffer=wr,exports.areEquivalentOnChains=Nn,exports.buildIntent=Vl,exports.buildRebalancingBatch=Ol,exports.buildRebalancingMetadata=zl,exports.buildRoutedBatches=Oo,exports.create1inchVenue=sr,exports.createLiquidityRegistry=lr,exports.createSatsumaVenue=ar,exports.duration=Nt,exports.easing=wt,exports.executeSwapThenAction=Zl,exports.findEquivalentOnChain=rn,exports.findTokenOnChain=Ws,exports.font=Ys,exports.getAssetChainTokenCandidates=Yn,exports.getBestUniV3Quote=er,exports.getUniV3Quote=_o,exports.isSwapIntent=tr,exports.quoteCctpFee=Wl,exports.quoteSquidFee=Pl,exports.radius=is,exports.resolveAssetTokenAddressOnChain=$t,exports.resolveFundedToken=So,exports.resolveRoute=Lo,exports.resolveTokenRef=zn,exports.transition=Wt,exports.useAssetInput=Il,exports.useGaslessExecution=es,exports.useLockDuration=Al,exports.useSmartWallet=El,exports.useSpiceAssets=Wn,exports.useSpiceExecution=es,exports.useSpicePendingDeposits=pr,exports.useWalletLink=Tl,exports.z=pn;
108
+ `})]}),document.body):null;return n.jsxs(n.Fragment,{children:[Ke,Ze,A&&Bn.createPortal(n.jsx(fo,{isOpen:!0,onClose:ge,supportedChains:[A.chainId],escrowOnly:!0,escrowTokenAddress:A.tokenAddress,escrowAmount:A.amount,escrowTokenDecimals:A.tokenDecimals,escrowTokenSymbol:A.tokenSymbol,styles:d,onDepositSuccess:fe}),document.body)]})},hr=class qs extends c.Component{constructor(t){super(t),this.handleRetry=()=>{this.state.retryCount>=qs.MAX_RETRIES||this.setState(s=>({hasError:!1,error:null,retryCount:s.retryCount+1}))},this.state={hasError:!1,error:null,retryCount:0}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,s){console.error(`[SdkErrorBoundary] ${this.props.componentName||"SDK component"} failed:`,{message:t.message,componentStack:s.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"},s={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},a={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"},r={fontSize:"12px",color:"#888",margin:0},i=qs.MAX_RETRIES-this.state.retryCount;return n.jsxs("div",{style:t,children:[n.jsxs("p",{style:s,children:[this.props.componentName||"Component"," failed to load"]}),this.state.error&&n.jsx("p",{style:o,children:this.state.error.message}),i>0?n.jsxs("button",{onClick:this.handleRetry,style:a,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 (",i," left)"]}):n.jsx("p",{style:r,children:"Please refresh the page to try again"})]})}return this.props.children}};hr.MAX_RETRIES=3;let Il=hr;const Al=()=>{const[e,t]=c.useState("0"),[s,o]=c.useState(null);return{assetAmount:e,setAssetAmount:t,selectedAsset:s,setSelectedAsset:o}};function El(e,t=0){const[s,o]=c.useState(t),a=e[s]??e[0],r=c.useMemo(()=>a?BigInt(Math.round(a.months*30*24*3600)):0n,[a?.months]);return{selectedDurationIdx:s,setSelectedDurationIdx:o,selectedDuration:a,durationSeconds:r}}function jl(){const{actions:e,isReady:t,isAuthenticated:s}=p.useWallet(),o=p.useEmbeddedWalletAddress(),a=c.useRef(!1),r=c.useRef(0),i=c.useRef(null),d=c.useRef(e),[u,l]=c.useState(0);d.current=e,c.useEffect(()=>{a.current=!1,r.current=0,i.current&&(clearTimeout(i.current),i.current=null)},[o]),c.useEffect(()=>{if(!o||!t||!s||a.current)return;a.current=!0;let h=!1;return(async()=>{await new Promise(f=>setTimeout(f,2e3));try{await p.ensureSmartWallet(o,d.current.signMessage),r.current=0}catch(f){console.warn("[SmartWallet] Registration failed:",f),a.current=!1,!h&&r.current<3&&(r.current+=1,i.current=setTimeout(()=>{l(g=>g+1)},5e3))}})(),()=>{h=!0,i.current&&(clearTimeout(i.current),i.current=null)}},[o,t,s,u])}const mr="https://portal-api.spicenet.io/api/v1/portal/mainnet",Fl=e=>({"Content-Type":"application/json",Authorization:`Bearer ${e}`,"x-privy-access-token":e});async function Bl(e,t,s=mr){const o=await fetch(`${s}/link-wallet`,{method:"POST",headers:Fl(e),body:JSON.stringify(t)});if(!o.ok){const a=await o.text().catch(()=>"");throw new Error(`Portal link-wallet failed: ${o.status} ${a}`.trim())}return o.json().catch(()=>({}))}const Vs=new Map;async function Tl({partnerId:e,campaignId:t,campaignGroup:s,embeddedWalletAddress:o,externalWalletAddress:a,token:r,baseUrl:i=mr}){const d=`${o.toLowerCase()}:${a.toLowerCase()}`,u=Vs.get(d);if(u)return u;const l=(async()=>{await Bl(r,{partnerId:e,campaignId:t,campaignGroup:s,embeddedWalletAddress:o,externalWalletAddress:a},i)})();Vs.set(d,l);try{await l}finally{Vs.delete(d)}}function Rl(e={}){const{enabled:t=!0,baseUrl:s}=e,o=c.useContext(p.SpiceFlowProviderContext)?.whitelistCheck,{isReady:a,isAuthenticated:r}=p.useWallet(),{embeddedAddress:i,externalAddress:d}=p.useProviderWallets();let u=null;try{({identityToken:u}=Ln.useIdentityToken())}catch{u=null}const l=e.partnerId??o?.partnerId,h=e.campaignId??o?.campaignId,f=e.campaignGroup??o?.campaignGroup,g=!!o,x=!!o?.isLinkedWallet,m=c.useRef(!1),y=c.useRef(0),b=c.useRef(null),[S,w]=c.useState(0);c.useEffect(()=>{m.current=!1,y.current=0,b.current&&(clearTimeout(b.current),b.current=null)},[i,d]),c.useEffect(()=>{if(!t||!a||!r||!u||!i||!d||!l||!g||x||m.current)return;m.current=!0;let C=!1;return(async()=>{try{await Tl({partnerId:l,campaignId:h,campaignGroup:f,embeddedWalletAddress:i,externalWalletAddress:d,token:u,baseUrl:s}),y.current=0}catch(v){console.warn("[WalletLink] Linking failed:",v),m.current=!1,!C&&y.current<3&&(y.current+=1,b.current=setTimeout(()=>{w(k=>k+1)},5e3))}})(),()=>{C=!0,b.current&&(clearTimeout(b.current),b.current=null)}},[t,a,r,u,i,d,l,h,f,g,x,s,S])}const ns=1500,gr="spiceflow-75f053db-70ab-4f37-83cc-abf68cb5b70d",Ml={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 xr(e,t,s){return(e*t+s-1n)/s}function yr(e,t=ns){return xr(e,BigInt(1e4+t),10000n)}function Cr(e,t){return`evm:${e}:${j.getAddress(t).toLowerCase()}`}function br(e){return Ml[e]??null}function Dl(e){return e==="testnet"?"https://iris-api-sandbox.circle.com":"https://iris-api.circle.com"}function Nl(e){const t=typeof e=="number"?e.toString():typeof e=="string"?e:"0",[s,o=""]=t.trim().split("."),a=BigInt(s||"0"),r=BigInt((o+"00").slice(0,2)||"0");return a*100n+r}function Wl(e,t){const s=Nl(t);return xr(e,s,1000000n)}async function Ul(e){const t=e.transferMode??"fast",s=br(e.sourceChainId),o=br(e.destinationChainId);if(!s||!o||s.network!==o.network)throw new Error(`Unsupported CCTP route ${e.sourceChainId} -> ${e.destinationChainId}`);let a=0n;const r=t==="fast"?1e3:2e3;if(t==="fast"){const d=e.fetchImpl??fetch,u=`${Dl(s.network)}/v2/burn/USDC/fees/${s.domain}/${o.domain}`,l=await d(u);if(!l.ok)throw new Error(`CCTP fee quote failed: ${l.status} ${l.statusText}`);const h=await l.json(),f=Array.isArray(h)?h:Array.isArray(h?.data)?h.data:[],g=f.find(x=>String(x.finalityThreshold??x.finalityThresholdExecuted??"")==="1000")??f[0];a=Wl(e.amountIn,g?.minimumFee??0)}const i=yr(a,e.bufferBps);return{provider:"cctp",sourceChainId:e.sourceChainId,destinationChainId:e.destinationChainId,tokenIn:j.getAddress(e.tokenIn),tokenOut:j.getAddress(e.tokenOut),amountIn:e.amountIn,estimatedAmountOut:e.amountIn>a?e.amountIn-a:0n,quotedBridgeFee:a,bufferedBridgeFee:i,bufferBps:e.bufferBps??ns,minFinalityThreshold:r,metadata:{sourceDomain:s.domain,destinationDomain:o.domain,transferMode:t}}}function ss(e){return typeof e=="string"&&e.length>0?e:void 0}function os(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 Pl(e){const t=e.estimate;return os(t?.toAmountMin)??os(t?.toAmount)??os(e.toAmountMin)??os(e.toAmount)}async function zl(e){const t=e.integratorId??gr,s=e.fetchImpl??fetch,o=e.baseUrl??"https://v2.api.squidrouter.com",a=await s(`${o}/v2/route`,{method:"POST",headers:{"Content-Type":"application/json","x-integrator-id":t},body:JSON.stringify({fromAddress:j.getAddress(e.fromAddress),fromChain:String(e.sourceChainId),fromToken:j.getAddress(e.tokenIn),fromAmount:e.amountIn.toString(),toAddress:j.getAddress(e.toAddress),toChain:String(e.destinationChainId),toToken:j.getAddress(e.tokenOut),slippage:e.slippage??1,quoteOnly:e.quoteOnly??!0})}),r=await a.json().catch(()=>null);if(!a.ok){const l=typeof r?.message=="string"?r.message:`${a.status} ${a.statusText}`;throw new Error(`Squid route quote failed: ${l}`)}const i=r?.route;if(!i)throw new Error("Squid route quote response did not include route");const d=Pl(i);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:j.getAddress(e.tokenIn),tokenOut:j.getAddress(e.tokenOut),amountIn:e.amountIn,estimatedAmountOut:d,quotedBridgeFee:u,bufferedBridgeFee:yr(u,e.bufferBps),bufferBps:e.bufferBps??ns,...ss(i.quoteId)?{quoteId:ss(i.quoteId)}:{},...ss(a.headers.get("x-request-id"))?{route:ss(a.headers.get("x-request-id"))}:{},metadata:{requestId:a.headers.get("x-request-id")??void 0,slippage:e.slippage??1,quoteOnly:e.quoteOnly??!0}}}function Ll(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 Ol(e){return`0x72${j.keccak256(j.encodeAbiParameters([{type:"address"},{type:"uint256"},{type:"address"},{type:"uint256"},{type:"uint256"},{type:"address"},{type:"uint256"},{type:"uint256"}],[j.getAddress(e.recipient),BigInt(e.fromChainId),j.getAddress(e.fromToken),e.fromAmount,BigInt(e.toChainId),j.getAddress(e.toToken),e.toAmountMin,e.salt??BigInt(Date.now())])).slice(4)}`}function Hl(e){const t=BigInt(Math.floor(Date.now()/1e3)),s=e.exp??t+3600n,o=e.nbf??0n,a=e.idempotenceKey??Ol({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:j.encodeFunctionData({abi:F.spicenetAbi,functionName:"createRebalancingRequest",args:[{idempotenceKey:a,nbf:o,exp:s,metadata:JSON.stringify(e.metadata??{}),recipient:j.getAddress(e.recipient).toLowerCase(),fromChainToken:Cr(e.fromChainId,e.fromToken),fromChainTokenAmount:e.fromAmount,toChainToken:Cr(e.toChainId,e.toToken),toChainTokenAmountMin:e.toAmountMin}]})}]}}function zn(e){try{return F.resolveTokenRef(e)}catch{throw new p.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 Ql(e,t){if(e[0].toUpperCase()===t[0].toUpperCase()&&e[1]===t[1])return!0;let s,o;try{s=zn(e),o=zn(t)}catch{return!1}const a=new Set(F.getEquivalentAddresses(o.address).map(r=>r.toLowerCase()));return a.add(o.address.toLowerCase()),a.has(s.address.toLowerCase())}function Vl(){const e=[];for(const t of Object.keys(F.CHAINS).map(Number))for(const s of F.getTokensForChain(t))e.push([s.symbol,t]);return e}async function ql(e){const{action:t,inputToken:s,inputAmount:o,registry:a,userAddress:r,slippage:i,intermediaryCandidates:d}=e;if(t.calls.length===0)throw new p.SpiceflowError("INVALID_PARAMS","buildIntent: action.calls must not be empty.",{action:t});if(o<=0n)throw new p.SpiceflowError("INVALID_PARAMS","buildIntent: inputAmount must be greater than zero.",{inputAmount:o.toString()});const u=t.supportedInputTokens??Vl();if(!u.some(b=>Ql(s,b))){const b=u.map(([S,w])=>`${S} (chain ${w})`).join(", ");throw new p.SpiceflowError("ROUTE_UNSUPPORTED_INPUT",`Input token "${s[0]}" on chain ${s[1]} is not in the action's supported input tokens. Supported: ${b}.`,{inputToken:{symbol:s[0],chainId:s[1]},supportedInputTokens:u})}const l=zn(s),h=zn(t.outputToken),f=Lo({sourceAsset:l,outputAsset:h,sourceChainId:l.chainId,destinationChainId:t.chainId,intermediaryCandidates:d}),{chainBatches:g,solverFrontToken:x,solverFrontAmount:m,resolvedSwaps:y}=await Oo({route:f,sourceAmount:o,userAddress:r,registry:a,actionCalls:t.calls,slippage:i});return{chainBatches:g,route:f,resolvedSwaps:y,resolvedInputToken:l,resolvedOutputToken:h,solverFrontToken:x,solverFrontAmount:m}}const Kl=[0n,1n,30n],Zl=new Set(["ABORT","CONCURRENT_EXECUTION","WALLET_DISCONNECTED","WALLET_REJECTED","NO_VENUE_FOR_CHAIN"]);function wr(e,t){return t===0n?e:e*(1000n-t)/1000n}async function Yl(e,t){const{chainId:s,swapCalls:o,quoteAmountOut:a,buildActionCalls:r,tokenAddress:i,tokenTransferAmount:d,onProgress:u,signal:l,options:h,buffers:f=Kl}=t;for(let g=0;g<f.length;g++){const x=f[g],m=wr(a,x),y=r(m),b=[{chainId:s,calls:[...o,...y]}];try{return await e(b,i,d,u,l,h)}catch(S){if(p.isSpiceflowError(S)&&Zl.has(S.code)||S.name==="AbortError"||l?.aborted||S.message?.includes("User rejected")||S.message?.includes("User denied")||S.code===4001||g>=f.length-1)throw S;const w=Number(f[g+1])/10;console.warn(`[SwapThenAction] Action attempt ${g+1} failed (buffer ${Number(x)/10}%), retrying with ${w}% buffer...`,S.message),u?.({step:"signing-delegation",message:`Adjusting action amount, retrying (${w}% buffer)...`})}}throw new p.SpiceflowError("ALL_ATTEMPTS_FAILED","All action attempts failed after exhausting buffer progression.",{attempts:f.length,chainId:s})}Dr(),exports.SpiceFlowProvider=p.SpiceFlowProvider,exports.SpiceFlowProviderContext=p.SpiceFlowProviderContext,exports.SpiceflowError=p.SpiceflowError,exports.Spinner=p.Spinner,exports.buildDarkPalette=p.buildDarkPalette,exports.buildLightPalette=p.buildLightPalette,exports.getChainConfig=p.getChainConfig,exports.getChainName=p.getChainName,exports.isSpiceflowError=p.isSpiceflowError,exports.relayerService=p.relayerService,exports.resolveTheme=p.resolveTheme,exports.useEmbeddedWalletAddress=p.useEmbeddedWalletAddress,exports.useIsUserWhitelisted=p.useIsUserWhitelisted,exports.useSpiceBrand=p.useSpiceBrand,exports.useWallet=p.useWallet,Object.defineProperty(exports,"NATIVE_TOKEN_ADDRESS",{enumerable:!0,get:function(){return F.ZERO_ADDRESS}}),Object.defineProperty(exports,"SPICENET_NATIVE_CHAIN_ID",{enumerable:!0,get:function(){return F.SPICENET_NATIVE_CHAIN_ID}}),Object.defineProperty(exports,"SPICE_COMBINED_FEE_RECIPIENT",{enumerable:!0,get:function(){return F.SPICE_COMBINED_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_GAS_FEE_RECIPIENT",{enumerable:!0,get:function(){return F.SPICE_GAS_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_PLATFORM_FEE_RECIPIENT",{enumerable:!0,get:function(){return F.SPICE_PLATFORM_FEE_RECIPIENT}}),Object.defineProperty(exports,"SPICE_SOLVER_ADDRESS",{enumerable:!0,get:function(){return F.SPICE_SOLVER_ADDRESS}}),Object.defineProperty(exports,"applySlippage",{enumerable:!0,get:function(){return F.applySlippage}}),Object.defineProperty(exports,"buildUniV3SwapCalls",{enumerable:!0,get:function(){return F.buildUniV3SwapCalls}}),Object.defineProperty(exports,"getChainIdsByNetwork",{enumerable:!0,get:function(){return F.getChainIdsByNetwork}}),Object.defineProperty(exports,"getEscrowContractAddress",{enumerable:!0,get:function(){return F.getEscrowContractAddress}}),Object.defineProperty(exports,"isNativeToken",{enumerable:!0,get:function(){return F.isNativeToken}}),Object.defineProperty(exports,"isSpicenetChainId",{enumerable:!0,get:function(){return F.isSpicenetChainId}}),Object.defineProperty(exports,"normalizeNativeTokenAddress",{enumerable:!0,get:function(){return F.normalizeNativeTokenAddress}}),Object.defineProperty(exports,"spicenetAbi",{enumerable:!0,get:function(){return F.spicenetAbi}}),Object.defineProperty(exports,"spicenetWithdrawalAbi",{enumerable:!0,get:function(){return F.spicenetAbi}}),exports.AccountDisplay=Sl,exports.AddFundsLink=ws,exports.CheckIcon=io,exports.ChevronIcon=nn,exports.CloseIcon=vn,exports.DEFAULT_BRIDGE_FEE_BUFFER_BPS=ns,exports.DEFAULT_SQUID_INTEGRATOR_ID=gr,exports.DetailRow=In,exports.ExportWalletButton=hl,exports.ProviderLogin=Is,exports.SATSUMA_CITREA_CONFIG=Hs,exports.SdkErrorBoundary=Il,exports.SearchInput=ls,exports.SelectChainModal=Ma,exports.SpiceBalance=Ii,exports.SpiceDeposit=mo,exports.SpiceLock=Zo,exports.SpiceLockModal=Zo,exports.SpicePay=fl,exports.SpiceSupply=ur,exports.SpiceWithdraw=Ho,exports.StatusBanner=Sn,exports.UNIV3_BASE_CONFIG=rr,exports.applyBuffer=wr,exports.areEquivalentOnChains=Nn,exports.buildIntent=ql,exports.buildRebalancingBatch=Hl,exports.buildRebalancingMetadata=Ll,exports.buildRoutedBatches=Oo,exports.create1inchVenue=sr,exports.createLiquidityRegistry=lr,exports.createSatsumaVenue=ar,exports.duration=Nt,exports.easing=wt,exports.executeSwapThenAction=Yl,exports.findEquivalentOnChain=rn,exports.findTokenOnChain=Ws,exports.font=Ys,exports.getAssetChainTokenCandidates=Yn,exports.getBestUniV3Quote=er,exports.getUniV3Quote=_o,exports.isSwapIntent=tr,exports.quoteCctpFee=Ul,exports.quoteSquidFee=zl,exports.radius=is,exports.resolveAssetTokenAddressOnChain=$t,exports.resolveFundedToken=So,exports.resolveRoute=Lo,exports.resolveTokenRef=zn,exports.transition=Wt,exports.useAssetInput=Al,exports.useGaslessExecution=es,exports.useLockDuration=El,exports.useSmartWallet=jl,exports.useSpiceAssets=Wn,exports.useSpiceExecution=es,exports.useSpicePendingDeposits=pr,exports.useWalletLink=Rl,exports.z=pn;